force build/unit amounts to be > 0
[browser-rts.git] / src / api.ts
1 import { HttpServer } from './lib/server';
2 import * as config from './config';
3 import { AccountRepository } from './repository/accounts';
4 import { CityRepository } from './repository/city';
5 import { MailRepository } from './repository/mail';
6 import {BadInputError, ERROR_CODE, NotFoundError} from './errors';
7 import { renderKingomOverview } from './render/kingdom-overview';
8 import { renderLandDevelopment } from './render/land-development';
9 import { tick } from './tasks/tick';
10 import { construction } from './tasks/construction';
11 import { unitTraining } from './tasks/unit-training';
12 import { fight } from './tasks/fight';
13 import { renderUnitTraining } from './render/unit-training';
14 import { launchOffensive, listOperations, renderOverworldMap } from './render/map';
15 import { createBullBoard } from '@bull-board/api';
16 import { BullAdapter } from '@bull-board/api/bullAdapter';
17 import _ from 'lodash';
18 import { renderCost } from './render/costs';
19 import {renderMailroom, renderMessage} from './render/mail';
20 import {topbar} from './render/topbar';
21 import {renderPublicChatMessage} from './render/chat-message';
22
23
24 const server = new HttpServer(config.API_PORT);
25 const accountRepo = new AccountRepository();
26 const cityRepo = new CityRepository();
27 const mailRepo = new MailRepository();
28
29 const msgBuffer: string[] = [];
30
31 createBullBoard({
32         queues: [
33                 new BullAdapter(tick.queue),
34                 new BullAdapter(construction.queue),
35                 new BullAdapter(unitTraining.queue),
36                 new BullAdapter(fight.queue)
37         ],
38         serverAdapter: server.bullAdapter,
39 });
40
41 server.post<{
42         body: {username: string, password: string}}, 
43         string
44         >
45         ('/accounts', async (req) => {
46         const { username, password} = req.body;
47         if(!username || !password || username.length < 3 || password.length < 3) {
48                 throw new BadInputError('Invalid username or password', ERROR_CODE.INVALID_USERNAME);
49         }
50         const acct = await accountRepo.create(username, password);
51
52         // lets create the city!
53         await cityRepo.create(acct.id);
54
55         return `<div class="alert success">You are all signed up! You can go ahead and log in</div>`;
56 });
57
58 server.post<{body: {username: string, password: string}}, void>('/login', async (req, raw, res) => {
59         const { username, password} = req.body;
60         if(!username || !password || username.length < 3 || password.length < 3) {
61                 throw new BadInputError('Invalid username or password', ERROR_CODE.INVALID_USERNAME);
62         }
63         const {account, session} = await accountRepo.login(username, password);
64         if(!account) {
65                 throw new NotFoundError('Invalid username or password', ERROR_CODE.USER_NOT_FOUND);
66         }
67
68         res.setHeader('hx-redirect', `/game.html?token=${session.id}&id=${session.account_id}`);
69
70 });
71
72 server.post<{body: {
73         soldiers: number,
74         attackers: number,
75         defenders: number,
76         sp_attackers: number,
77         sp_defenders: number
78   }}, string>('/attack-power', async req => {
79         const power = await cityRepo.power(req.body);
80
81         return power.toLocaleString();
82
83 });
84
85 server.get<{params: { cityId: string }}, string>('/city/:cityId', async req => {
86         const account = await accountRepo.validate(req.authInfo.accountId, req.authInfo.token);
87         const yourCity = await cityRepo.getUsersCity(account.id);
88         const city = await cityRepo.findById(req.params.cityId);
89         const acct = await accountRepo.FindOne({id: city.owner});
90
91
92         return await launchOffensive(city, acct || {
93                 id: '-',
94                 username: 'Rebels',
95                 password: ''
96         }, yourCity, account);
97 });
98
99 server.get<{}, string>('/poll/overview', async req => {
100         const account = await accountRepo.validate(req.authInfo.accountId, req.authInfo.token);
101         const city = await cityRepo.getUsersCity(account.id);
102
103   const usage = {
104     foodUsagePerTick: await cityRepo.foodUsagePerTick(city),
105     foodProductionPerTick: await cityRepo.foodProductionPerTick(city),
106     energyUsagePerTick: await cityRepo.energyUsagePerTick(city),
107     energyProductionPerTick: await cityRepo.energyProductionPerTick(city)
108   }
109
110         return renderKingomOverview({
111     ...city,
112     ...usage
113   }, account) + topbar({...city, ...usage});
114 });
115
116 server.get<{}, string>('/poll/construction', async req => {
117         const account = await accountRepo.validate(req.authInfo.accountId, req.authInfo.token);
118         const city = await cityRepo.getUsersCity(account.id);
119         const buildings = await cityRepo.buildingRepository.list();
120
121         const buildQueues = await cityRepo.getBuildQueues(account.id);
122   const usage = {
123     foodUsagePerTick: await cityRepo.foodUsagePerTick(city),
124     foodProductionPerTick: await cityRepo.foodProductionPerTick(city),
125     energyUsagePerTick: await cityRepo.energyUsagePerTick(city),
126     energyProductionPerTick: await cityRepo.energyProductionPerTick(city)
127   }
128         return renderLandDevelopment(city, buildings, buildQueues) + topbar({...city, ...usage});
129 });
130
131 server.get<{}, string>('/poll/unit-training', async req => {
132         const account = await accountRepo.validate(req.authInfo.accountId, req.authInfo.token);
133         const city = await cityRepo.getUsersCity(account.id);
134
135         const unitTrainingQueues = await cityRepo.getUnitTrainingQueues(account.id);
136         const units = await cityRepo.unitRepository.list();
137   const usage = {
138     foodUsagePerTick: await cityRepo.foodUsagePerTick(city),
139     foodProductionPerTick: await cityRepo.foodProductionPerTick(city),
140     energyUsagePerTick: await cityRepo.energyUsagePerTick(city),
141     energyProductionPerTick: await cityRepo.energyProductionPerTick(city)
142   }
143
144         return renderUnitTraining(city, units, unitTrainingQueues) + topbar({
145     ...city,
146     ...usage
147   });
148 });
149
150 server.post<{body: {sector: string}}, string>('/poll/map', async req => {
151         const account = await accountRepo.validate(req.authInfo.accountId, req.authInfo.token);
152         const city = await cityRepo.getUsersCity(account.id);
153
154   let sector = city.sector_id;
155   if(req.body.sector) {
156     try {
157       sector = parseInt(req.body.sector);
158     }
159     catch(e) {
160       sector = city.sector_id;
161     }
162   }
163
164   const usage = {
165     foodUsagePerTick: await cityRepo.foodUsagePerTick(city),
166     foodProductionPerTick: await cityRepo.foodProductionPerTick(city),
167     energyUsagePerTick: await cityRepo.energyUsagePerTick(city),
168     energyProductionPerTick: await cityRepo.energyProductionPerTick(city)
169   }
170
171         return renderOverworldMap(await cityRepo.findAllInSector(sector), city, sector) + topbar({
172     ...city,
173     ...usage
174   });
175 });
176
177 server.get<{}, string>('/poll/mailroom', async req => {
178         const account = await accountRepo.validate(req.authInfo.accountId, req.authInfo.token);
179         const city = await cityRepo.getUsersCity(account.id);
180
181   const usage = {
182     foodUsagePerTick: await cityRepo.foodUsagePerTick(city),
183     foodProductionPerTick: await cityRepo.foodProductionPerTick(city),
184     energyUsagePerTick: await cityRepo.energyUsagePerTick(city),
185     energyProductionPerTick: await cityRepo.energyProductionPerTick(city)
186   }
187
188         return renderMailroom(await mailRepo.listReceivedMessages(account.id)) + topbar({
189     ...city,
190     ...usage
191   });
192 });
193
194
195 server.post<{
196         body: {
197                 amount: string,
198                 building_type: string
199         }
200 }, string>('/cost/construction', async req => {
201         const amount = parseInt(req.body.amount.trim(), 10);
202
203         if(isNaN(amount) || amount < 1) {
204                 return '';
205         }
206         const building = await cityRepo.buildingRepository.findBySlug(req.body.building_type);
207
208         if(!building) {
209                 throw new NotFoundError(`Invalid building type ${req.body.building_type}`, ERROR_CODE.INVALID_BUILDING);
210         }
211
212   const cost = {
213                 credits: building.credits * amount,
214                 alloys: building.alloys * amount,
215                 energy: building.energy * amount,
216                 land: building.land * amount,
217                 time: building.time
218   };
219
220   return renderCost(cost);
221 });
222
223 server.post<{
224         body: {
225                 amount: string;
226                 type: string;
227         }
228 }, string>('/cost/training', async req => {
229         const amount = parseInt(req.body.amount, 10);
230
231         if(isNaN(amount) || amount < 1) {
232                 return '';
233         }
234
235         const unit = await cityRepo.unitRepository.findBySlug(req.body.type);
236         if(!unit) {
237                 throw new NotFoundError(`Invalid unit type ${req.body.type}`, ERROR_CODE.INVALID_UNIT);
238         }
239
240         return renderCost({
241                 population: unit.population * amount,
242                 soldiers: unit.soldiers * amount,
243                 attackers: unit.attackers * amount,
244                 defenders: unit.defenders * amount,
245                 credits: unit.credits * amount,
246                 food: unit.food * amount,
247     time: unit.time * amount
248         });
249 });
250
251 server.post<{
252         body: {
253                 amount: string,
254                 building_type: string,
255         }
256 }, void>('/build', async req => {
257   const account = await accountRepo.validate(req.authInfo.accountId, req.authInfo.token);
258   const city = await cityRepo.getUsersCity(account.id);
259
260   const amount = parseInt(req.body.amount, 10);
261   if(amount < 1) {
262     throw new BadInputError('Please specify an amount > 0', ERROR_CODE.INVALID_AMOUNT);
263   }
264   const building = await cityRepo.buildingRepository.findBySlug(req.body.building_type);
265
266   if(!building) {
267     throw new NotFoundError(`Invalid building type ${req.body.building_type}`, ERROR_CODE.INVALID_BUILDING);
268   }
269
270   const queueData = await cityRepo.buildBuilding(building, amount, city);
271
272         construction.trigger(queueData, { delay: queueData.due });
273 }, 'reload-construction-queue');
274
275 server.post<{
276                 body: {
277                         amount: string,
278                         type: string
279                 }
280         },
281         void
282         >('/units', async req => {
283         const acct = await accountRepo.validate(req.authInfo.accountId, req.authInfo.token);
284         const city = await cityRepo.getUsersCity(acct.id);
285
286         const amount  = parseInt(req.body.amount, 10);
287   if(amount < 1) {
288     throw new BadInputError('Please specify an amount > 0', ERROR_CODE.INVALID_AMOUNT);
289   }
290         const unit = await cityRepo.unitRepository.findBySlug(req.body.type);
291
292         if(!unit) {
293                 throw new NotFoundError(`Invalid unit type ${req.body.type}`, ERROR_CODE.INVALID_UNIT);
294         }
295
296         const queueData = await cityRepo.train(unit, amount, city);
297         unitTraining.trigger(queueData, { delay: queueData.due });
298
299 }, 'reload-unit-training');
300
301 server.post<{
302         body: {
303                 city: string,
304                 soldiers: string,
305                 attackers: string,
306                 defenders: string,
307                 sp_attackers: string,
308                 sp_defenders: string
309         }
310         }, 
311         void
312         >('/attack', async req => {
313                 const acct = await accountRepo.validate(req.authInfo.accountId, req.authInfo.token);
314                 const city = await cityRepo.getUsersCity(acct.id);
315                 const attackedCity = await cityRepo.findById(req.body.city);
316
317                 const army = {
318                         soldiers: parseInt(req.body.soldiers),
319                         attackers: parseInt(req.body.attackers),
320                         defenders: parseInt(req.body.defenders),
321                         sp_attackers: parseInt(req.body.sp_attackers),
322                         sp_defenders: parseInt(req.body.sp_defenders)
323                 };
324
325                 const armyQueue = await cityRepo.attack(city, attackedCity, army);
326
327                 fight.trigger(armyQueue, {
328                         delay: armyQueue.due - Date.now()
329                 });
330         }, 'reload-outgoing-attacks');
331
332 server.get<void, string>('/messages', async req => {
333         const acct = await accountRepo.validate(req.authInfo.accountId, req.authInfo.token);
334         const msgs = await mailRepo.listReceivedMessages(acct.id);
335
336         return JSON.stringify(msgs);
337 });
338
339 server.get<{params: {id: string}}, string>('/messages/:id', async req => {
340         const acct = await accountRepo.validate(req.authInfo.accountId, req.authInfo.token);
341         const msg = await mailRepo.getMessage(req.params.id, acct.id);
342
343         if(!msg) {
344                 throw new NotFoundError('No such message', ERROR_CODE.DUPLICATE_CACHE_KEY);
345         }
346
347         await mailRepo.markAsRead(msg.id, msg.to_account);
348
349         return renderMessage(msg);
350 });
351
352 server.get<void, string>('/attacks/outgoing', async req => {
353         const acct = await accountRepo.validate(req.authInfo.accountId, req.authInfo.token);
354         const city = await cityRepo.getUsersCity(acct.id);
355         const attacks = await cityRepo.armyRepository.listOutgoing(city.id);
356
357         return listOperations(attacks);
358 });
359
360 server.post<{body: {message: string}}, void>('/chat', async req => {
361   const acct = await accountRepo.validate(req.authInfo.accountId, req.authInfo.token);
362   const now = Date.now();
363
364   console.log(acct.username, req.body.message, now);
365
366   const msg = renderPublicChatMessage(acct.username, req.body.message);
367   server.ws.emit('/chat-message', msg);
368   msgBuffer.unshift(msg);
369   while(msgBuffer.length > 30) {
370     msgBuffer.pop();
371   }
372 });
373
374 server.ws.on('connection', async socket => {
375   const auth = server.authFromUrl(socket.request.headers['referer']);
376   const acct = await accountRepo.validate(auth.authInfo.accountId, auth.authInfo.token);
377
378   server.ws.emit('/chat-message', msgBuffer.join("\n"));
379
380   server.ws.emit('/chat-message', renderPublicChatMessage('Server', `${acct.username} logged in`));
381
382 });
383
384 server.start();
385
386 tick.trigger({
387   lastTickAt: 0,
388   lastTick: 0
389 });