-
Notifications
You must be signed in to change notification settings - Fork 6
/
app.js
executable file
·1287 lines (1083 loc) · 45.9 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/nodejs
/**
* Part of the evias/pacNEM package.
*
* NOTICE OF LICENSE
*
* Licensed under MIT License.
*
* This source file is subject to the MIT License that is
* bundled with this package in the LICENSE file.
*
* @package evias/pacNEM
* @author Grégory Saive <[email protected]>
* @license MIT License
* @copyright (c) 2017, Grégory Saive <[email protected]>
* @link http://github.com/evias/pacNEM
*/
var app = require('express')(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
path = require('path'),
handlebars = require("handlebars"),
expressHbs = require("express-handlebars"),
auth = require("http-auth"),
mongoose = require("mongoose"),
bodyParser = require("body-parser"),
config = require("config"),
nem = require("nem-sdk").default,
i18n = require("i18next"),
i18nFileSystemBackend = require('i18next-node-fs-backend'),
i18nMiddleware = require('i18next-express-middleware'),
fs = require("fs"),
flash = require("connect-flash"),
session = require("express-session"),
validator = require("express-validator");
// internal core dependencies
var logger = require('./core/logger.js');
var __smartfilename = path.basename(__filename);
var serverLog = function(req, msg, type) {
var logMsg = "[" + type + "] " + msg + " (" + (req.headers ? req.headers['x-forwarded-for'] : "?") + " - " +
(req.connection ? req.connection.remoteAddress : "?") + " - " +
(req.socket ? req.socket.remoteAddress : "?") + " - " +
(req.connection && req.connection.socket ? req.connection.socket.remoteAddress : "?") + ")";
logger.info(__smartfilename, __line, logMsg);
};
// configure view engine (handlebars)
app.engine(".hbs", expressHbs({
extname: ".hbs",
defaultLayout: "default.hbs",
layoutPath: "views/layouts"
}));
app.set("view engine", "hbs");
// configure translations with i18next
i18n.use(i18nFileSystemBackend)
.init({
lng: "en",
fallbackLng: "en",
defaultNS: "translation",
whitelist: ["en", "de", "fr"],
nonExplicitWhitelist: true,
preload: ["en", "de", "fr"],
backend: {
loadPath: "locales/{{lng}}/{{ns}}.json"
}
});
// configure body-parser usage for POST API calls.
app.use(bodyParser.urlencoded({ extended: true }));
/**
* Basic HTTP Authentication
*
* COMMENT BLOCK if you wish to open the website
* to the public.
*/
if (!config.get("pacnem.isPublic", false)) {
var basicAuth = auth.basic({
realm: "This is a Highly Secured Area - Monkey at Work.",
file: __dirname + "/pacnem.htpasswd"
});
app.use(auth.connect(basicAuth));
}
/**
* End Basic HTTP Authentication BLOCK
*/
/**
* Configure Express Application Middlewares:
* - flash (connect-flash) notifications helper
* - session (express-session)
* - validator (express-validator)
*
* Used for Notifications across the game, input validation
* and cross-request messages.
*/
app.configure(function() {
app.use(session({
cookie: { maxAge: 60000 },
secret: config.get("pacnem.secretKey"),
resave: false,
saveUninitialized: false
}));
app.use(flash());
app.use(validator());
// LOCALES MANAGEMENT in frontend
app.use(function(req, res, next) {
req.i18n = i18n;
if (req.session.locale) // check if user has changed i18n settings
req.i18n.changeLanguage(req.session.locale);
next();
});
// Cache for Frontend Static Assets (2 Days)
app.use(function(req, res, next) {
var oneDay = 86400000;
if (req.url.match(/\.(css|js|png|jpg|gif|svg|ttf|woff)$/)) {
res.setHeader('Cache-Control', 'public, max-age=' + (oneDay * 2));
}
next();
});
});
/**
* End Application Middlewares
*/
// redirect non-www to www
// app.get('/*', function(req, res, next) {
// var protocol = 'http' + (req.connection.encrypted ? 's' : '') + '://',
// host = req.headers.host,
// href;
// if (!req.headers.host.match(/^(www|m)\./)) {
// var newHost = protocol + 'www.pacnem.com';
// res.statusCode = 301;
// res.setHeader("Location", newHost);
// res.write("Redirecting to " + newHost);
// return res.end();
// } else {
// return next();
// }
// });
/**
* Configure the PacNEM Backend Modules. This includes following:
*
* - PacNEMBlockchain : defines general blockchain config (hosts, wallets)
* - PacNEMDB : MongoDB (mongoose) wrapper for the PacNEM backend
* - PaymentsProtocol : PacNEM's Payment Protocol defines how to handle Invoices
* - HallOfFame : Blockchain Hall of Fame business layer
* - SponsorEngine : Blockchain Advertizing Pay per View
* - Authenticator : Authentication on the Blockchain
* - GameCredits : Game Credits as Mosaics on the Blockchain
* - PacNEMSockets : Websockets for the PacNEM Game.
* - PacNEM_Crons : Define workers for the PacNEM Backend
*
* I know that some of those business layer classes would have probably
* been easier to work with if they worked only with a Database, but the
* fun of the project was to link as many Blockchain Features to it as
* possible.
*
* Enjoy :)
*/
// configure blockchain layer
var blockchain = require('./core/blockchain/service.js');
var PacNEMBlockchain = new blockchain.service(io, nem, logger);
// configure database layer
var models = require('./core/db/models.js');
var PacNEMDB = new models.pacnem(io, PacNEMBlockchain);
var CreditsCore = require("./core/blockchain/game-credits.js");
var GameCredits = new CreditsCore.GameCredits(io, logger, PacNEMBlockchain, PacNEMDB);
var GameCreditsErrors = new CreditsCore.GameCreditErrors();
var AuthenticatorCore = require("./core/blockchain/authenticator.js");
var Authenticator = new AuthenticatorCore.Authenticator(io, logger, PacNEMBlockchain, PacNEMDB);
var AuthErrors = new AuthenticatorCore.AuthenticatorErrors();
Authenticator.fetchPersonalTokens();
// configure our PaymentsCore implementation, handling payment
// processor NEMBot communication
var PaymentsCore = require("./core/blockchain/payments-core.js").PaymentsCore;
var PaymentsProtocol = new PaymentsCore(io, logger, PacNEMBlockchain, PacNEMDB, GameCredits, Authenticator);
var HallOfFameCore = require("./core/blockchain/hall-of-fame.js").HallOfFame;
var HallOfFame = new HallOfFameCore(io, logger, PacNEMBlockchain, PacNEMDB);
HallOfFame.fetchBlockchainHallOfFame();
var SponsorEngineCore = require("./core/blockchain/sponsor-engine.js").SponsorEngine;
var SponsorEngine = new SponsorEngineCore(io, logger, PacNEMBlockchain, PacNEMDB);
var PacNEMProtocol = require("./core/pacman/socket.js").PacNEMProtocol;
var PacNEMSockets = new PacNEMProtocol(io, logger, PacNEMBlockchain, PacNEMDB, HallOfFame, SponsorEngine, Authenticator, GameCredits);
var JobsScheduler = require("./core/scheduler.js").JobsScheduler;
var PacNEM_Crons = new JobsScheduler(logger, PacNEMBlockchain, PacNEMDB, GameCredits);
PacNEM_Crons.hourly();
PacNEM_Crons.fetchHourlySeenMosaics();
var PacNEM_i18n = function() {
this.getLocales = function() {
var paths = {
"en": __dirname + '/locales/en/translation.json',
"de": __dirname + '/locales/de/translation.json',
"fr": __dirname + '/locales/fr/translation.json'
};
var locales = { "en": {}, "de": {}, "fr": {} };
for (var lang in paths) {
var json = fs.readFileSync(paths[lang]);
locales[lang] = JSON.parse(json);
}
return locales;
};
};
var PacNEM_Frontend_Config = {
"business": PacNEMBlockchain.getVendorWallet(),
"application": PacNEMBlockchain.getPublicWallet(),
"namespace": PacNEMBlockchain.getNamespace(),
"dataSalt": config.get("pacnem.secretKey"),
"facebookAppId": config.get("pacnem.facebookAppId"),
"localesJSON": JSON.stringify((new PacNEM_i18n()).getLocales()).replace(/'/g, "\\'")
};
/**
* Serving static Assets (images, CSS, JS files)
* @param {*} req
* @param {*} res
*/
var serveStaticFile = function(req, res, path) {
var file = req.params ? req.params[0] : "";
if (!file.length)
return res.send(404);
// make sure file exists
var path = __dirname + path + file;
if (!fs.existsSync(path)) {
return res.send(404);
}
return res.sendfile(path);
};
/**
* View Engine Customization
*
* - handlebars t() helper for template translations handling with i18next
**/
handlebars.registerHelper('t', function(key, sub) {
if (typeof sub != "undefined" && sub !== undefined && typeof sub === "string" && sub.length)
// dynamic subnamespace
var key = key + "." + sub;
return new handlebars.SafeString(i18n.t(key));
});
/**
* Handlebars counter() helper implementation for frontend
* templates
*/
handlebars.registerHelper("time", function() {
return new handlebars.SafeString("" + new Date().valueOf());
});
/**
* Third Party static asset serving
* - Bootstrap
* - Handlebars
* - i18next
* - jQuery
*/
app.get('/3rdparty/*', function(req, res) {
return serveStaticFile(req, res, "/www/3rdparty/");
});
app.get('/img/*', function(req, res) {
return serveStaticFile(req, res, "/img/");
});
app.get('/css/*', function(req, res) {
return serveStaticFile(req, res, "/www/css/");
});
app.get('/js/*', function(req, res) {
return serveStaticFile(req, res, "/www/js/");
});
// SSL Certificate Verification
app.get('/.well-known/acme-challenge/*', function(req, res) {
return serveStaticFile(req, res, "/www/ssl-verification/");
});
/**
* Static Files (assets) Serving
*
* Also includes asynchronously loaded templates,
* those are stored in views/partials/*.hbs files.
*/
app.get('/favicon.ico', function(req, res) {
res.sendfile(__dirname + '/www/favicon.ico');
});
app.get('/robots.txt', function(req, res) {
res.sendfile(__dirname + '/www/robots.txt');
});
/**
* - Asynchronous `player-authenticate` login screen
* * This screen will also check for available sessions
* to keep the Player logged in.
* - Asynchronous Template Serving
* - XHR Translations loading
*
* The templates present in views/partials can be rendered
* using the jQFileTemplate frontend implementation.
*/
app.get('/resources/templates/:address/player-authenticate', function(req, res) {
var ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
var bundle = {
ip: ip,
client: req.headers['user-agent'],
address: req.params.address.replace(/-/g, '')
};
Authenticator.getActiveSession(bundle, function(session) {
// Player has an active Session, no need to authenticate
var tpl = fs.readFileSync(__dirname + '/views/partials/player-back.hbs');
tpl = tpl.toString().replace(/%TOKEN%/g, session.checksum);
return res.send(tpl);
}, function(response) {
// Player must now enter a Token to authenticate.
return res.sendfile(__dirname + '/views/partials/player-authenticate.hbs');
});
});
app.get('/resources/templates/:name', function(req, res) {
res.sendfile(__dirname + '/views/partials/' + req.params.name + '.hbs');
});
/**
* Frontend Web Application Serving
*
* This part of the game is where the end-user is active. Served
* frontend URLs include:
*
* - GET /sponsor : Page with Form for Sponsor Registration
* - POST /sponsor : Sponsor Registration Process
* - GET /:lang? : Frontend home page
*/
app.get("/sponsor", function(req, res) {
var currentLanguage = i18n.language;
var currentNetwork = PacNEMBlockchain.getNetwork();
var viewData = {
currentNetwork: currentNetwork,
currentLanguage: currentLanguage,
PacNEM_Frontend_Config: PacNEM_Frontend_Config,
errors: {},
values: {}
};
res.render("sponsor", viewData);
});
app.post("/sponsor", function(req, res) {
var currentLanguage = i18n.language;
var currentNetwork = PacNEMBlockchain.getNetwork();
var viewData = {
currentNetwork: currentNetwork,
currentLanguage: currentLanguage,
PacNEM_Frontend_Config: PacNEM_Frontend_Config,
errors: {},
values: {}
};
var mandatoryFieldError = i18n.t("sponsor_engine.error_missing_mandatory_field");
//XXX SANITIZE
//req.check("realname", mandatoryFieldError).notEmpty();
//req.check("email", mandatoryFieldError).notEmpty();
//req.check("email", mandatoryFieldError).isEmail();
//req.check("sponsorname", mandatoryFieldError).notEmpty();
//req.check("type_advertizing", mandatoryFieldError).notEmpty();
//req.check("description", mandatoryFieldError).notEmpty();
var input = {
"realname": req.body.realname,
"xem": req.body.xem,
"email": req.body.email,
"sponsorname": req.body.sponsorname,
"url": req.body.url,
"type_advertizing": req.body.type_advertizing,
"description": req.body.description
};
//var errors = req.validationErrors();
//if (errors) {
//XXX errors will be indexed by field name
var errors = {};
var isFormValid = true;
var mandatories = ["realname", "xem", "email", "sponsorname", "type_advertizing", "description"];
for (var i in mandatories) {
var field = mandatories[i];
if (!input[field] || !input[field].length) {
errors[field] = i18n.t("sponsor_engine.error_missing_mandatory_field");
isFormValid = false;
}
}
if (!isFormValid) {
viewData["errors"] = errors;
viewData["values"] = input;
return res.render("sponsor", viewData);
}
//}
//serverLog(req, JSON.stringify(input), "[DEBUG]");
//serverLog(req, JSON.stringify(errors), "[DEBUG]");
//serverLog(req, JSON.stringify(isFormValid), "[DEBUG]");
// Form input is valid!
PacNEMDB.NEMSponsor.findOne({ email: input.email }, function(err, sponsor) {
if (err) {
// error reading sponsor
viewData.errors = { general: err };
return res.render("sponsor", viewData);
}
if (sponsor) {
// sponsor by email already exists!
viewData.errors = { general: i18n.t("sponsor_engine.error_email_unique") };
return res.render("sponsor", viewData);
}
var sponsorSlug = input.sponsorname.toLowerCase().replace(/[^\w ]+/g, '').replace(/ +/g, '-');
sponsor = new PacNEMDB.NEMSponsor({
slug: sponsorSlug,
realName: input.realname,
xem: input.xem.replace(/-/g, ""),
sponsorName: input.sponsorname,
email: input.email,
description: input.description,
websiteUrl: input.url,
advertType: input.type_advertizing,
createdAt: new Date().valueOf()
});
sponsor.save(function(err) {
if (err) {
// error saving sponsor
viewData.errors = { general: err };
return res.render("sponsor", viewData);
}
req.flash("info", i18n.t("sponsor_engine.registered_success"));
return res.redirect("/");
})
});
});
app.get("/", function(req, res) {
var currentLanguage = req.i18n.language;
var currentNetwork = PacNEMBlockchain.getNetwork();
var notificationMessage = typeof flash("info") == "undefined" ? "" : req.flash("info");
var viewData = {
currentNetwork: currentNetwork,
currentLanguage: currentLanguage,
PacNEM_Frontend_Config: PacNEM_Frontend_Config,
notificationMessage: notificationMessage,
isFacebookCanvas: false
};
res.render("play", viewData);
});
// Facebook Canvas Game
app.post("/facebook/game", function(req, res) {
var currentLanguage = req.i18n.language;
var currentNetwork = PacNEMBlockchain.getNetwork();
var notificationMessage = typeof flash("info") == "undefined" ? "" : req.flash("info");
var isFacebook = req.query.fb && parseInt(req.query.fb) === 1;
console.log("[DEBUG] Handling Facebook Canvas request with: body: '" + JSON.stringify(req.body) + "', headers: '" + JSON.stringify(req.headers) + "', query: '" + JSON.stringify(req.query) + "'");
var viewData = {
currentNetwork: currentNetwork,
currentLanguage: currentLanguage,
PacNEM_Frontend_Config: PacNEM_Frontend_Config,
notificationMessage: notificationMessage,
isFacebookCanvas: isFacebook
};
res.render("play", viewData);
});
// change language fake middleware
app.get("/:lang", function(req, res) {
var currentLanguage = req.params.lang;
var validLang = { "en": true, "de": true, "fr": true };
if (!validLang.hasOwnProperty(currentLanguage))
currentLanguage = "en";
var currentNetwork = PacNEMBlockchain.getNetwork();
req.session.locale = currentLanguage;
if (req.headers.referer)
return res.redirect(req.headers.referer);
return res.redirect("/");
});
/**
* API Routes
*
* Following routes are used for handling the business/data
* layer.
*
* All API routes are prefixed by `/api/v1` currently. Following
* API routes are defined by PacNEM:
*
* - GET /sessions/get : Read Player Data from Database and issue pacnem_heart_sync
* - GET /scores : Read PacNEM Hall Of Fame
* - GET /sponsors/random : Fetch random sponsor from the Sponsor Database
* - GET /credits/buy : Create Invoice for Frontend for buying Game Credits
* - GET /credits/history : View Invoice History (or Single Invoice)
* - GET /credits/remaining : Read latest synchronized Game Credits for a Player
* - GET /lounge/get : Read Lounge Informations
*
* - POST /sessions/store : Store Player Data to the Database and issue pacnem_heart_sync
* - POST /sessions/verify : Player authentication (Personal Token - Pay-per-play only)
* - POST /sponsors/watch : Save an *ad view* for the given Sponsor
*/
app.get("/api/v1/sessions/get", function(req, res) {
res.setHeader('Content-Type', 'application/json');
if (!req.query.address || !req.query.address.length)
return res.send(JSON.stringify({ "status": "error", "message": "Mandatory field `address` is missing." }));
var input = {
"xem": req.query.address.replace(/-/g, ""),
"username": req.query.username,
"sid": req.query.sid ? req.query.sid : ""
};
var keyUsername = input.username.replace(/[\.]/g, "-");
var keySocketId = input.sid.replace(/[\.]/g, "-");
// fetch an existing NEMGamer entry by XEM address, this
PacNEMDB.NEMGamer.findOne({ "xem": input.xem }, function(err, player) {
if (err) {
// error mode
var errorMessage = "Error occured on NEMGamer READ: " + err;
serverLog(req, errorMessage, "ERROR");
return res.send(JSON.stringify({ "status": "error", "message": errorMessage }));
}
if (!player) {
// NEMGamer entry not created yet, JiT creation.
var uname = {}
uname[keyUsername] = {};
uname[keyUsername][keySocketId] = true;
var player = new PacNEMDB.NEMGamer({
usernames: uname,
xem: input.xem,
lastScore: input.score,
highScore: input.score,
socketIds: [input.sid],
countGames: 0,
createdAt: new Date().valueOf()
});
}
// read blockchain for evias.pacnem:heart mosaic on the given NEMGamer model.
GameCredits.fetchHeartsByGamer(player);
// session retrieved.
return res.send(JSON.stringify({ item: player }));
});
});
app.post("/api/v1/sessions/store", function(req, res) {
res.setHeader('Content-Type', 'application/json');
var input = {
"xem": req.body.xem.replace(/-/g, ""),
"username": req.body.username.replace(/[^A-Za-z0-9\-_\.]/g, ""),
"score": parseInt(req.body.score),
"type": req.body.type.replace(/[^a-z0-9\-]/g, ""),
"sid": req.body.sid.replace(/[^A-Za-z0-9\-_\.#~]/g, ""),
"validateHearts": parseInt(req.body.validateHearts) === 1
};
var keyUsername = input.username.replace(/[\.]/g, "-");
var keySocketId = input.sid.replace(/[\.]/g, "-");
// mongoDB model NEMGamer unique on xem address + username pair.
PacNEMDB.NEMGamer.findOne({ "xem": input.xem }, function(err, player) {
if (!err && player) {
// update mode
var highScore = input.score > player.highScore ? input.score : player.highScore;
player.xem = input.xem;
player.lastScore = input.score;
player.highScore = highScore;
player.updatedAt = new Date().valueOf();
if (!player.usernames)
player.usernames = {};
if (!player.usernames.hasOwnProperty(keyUsername)) {
// register new username
player.usernames[keyUsername] = {};
player.usernames[keyUsername][keySocketId] = true;
} else if (!player.usernames[keyUsername].hasOwnProperty(keySocketId)) {
// save new socket id for existing username
player.usernames[keyUsername][keySocketId] = true;
}
if (!player.socketIds || !player.socketIds.length)
player.socketIds = [input.sid];
else {
var sockets = player.socketIds;
sockets.push(input.sid);
player.socketIds = sockets;
}
player.save(function(err) {
if (err) {
serverLog(req, "Error ocurred when saving NEMGamer: " + err, "ERROR");
}
});
if (input.validateHearts === true) {
// read blockchain for evias.pacnem:heart mosaic on the given NEMGamer model.
GameCredits.fetchHeartsByGamer(player);
}
return res.send(JSON.stringify({ item: player }));
} else if (!player) {
// creation mode
var uname = {}
uname[keyUsername] = {};
uname[keyUsername][keySocketId] = true;
var player = new PacNEMDB.NEMGamer({
usernames: uname,
xem: input.xem,
lastScore: input.score,
highScore: input.score,
socketIds: [input.sid],
countGames: 0,
createdAt: new Date().valueOf()
});
player.save(function(err) {
if (err) {
serverLog(req, "Error ocurred when saving NEMGamer: " + err, "ERROR");
}
});
if (input.validateHearts === true) {
// read blockchain for evias.pacnem:heart mosaic on the given NEMGamer model.
GameCredits.fetchHeartsByGamer(player);
}
return res.send(JSON.stringify({ item: player }));
} else {
// error mode
var errorMessage = "Error occured on NEMGamer update: " + err;
serverLog(req, errorMessage, "ERROR");
return res.send(JSON.stringify({ "status": "error", "message": errorMessage }));
}
});
});
app.post("/api/v1/sessions/verify", function(req, res) {
res.setHeader('Content-Type', 'application/json');
var ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
var bundle = {
"from": ip,
"address": req.body.address,
"creds": req.body.creds,
"headers": req.headers
};
var CryptoJS = PacNEMBlockchain.getSDK().crypto.js;
var payload = JSON.stringify({
ip: bundle.from,
client: bundle.headers["user-agent"],
address: bundle.address
});
var uaSession = CryptoJS.lib.WordArray.create(payload);
var checksum = CryptoJS.MD5(uaSession).toString();
Authenticator.authenticateAddress(bundle, function(token) {
// Authentication was successful, Player can now play PacNEM
res.send(JSON.stringify({ "status": "ok", "code": 1, "item": session.checksum }));
}, function(response) {
// Authentication ERROR !
if (response.code == AuthErrors.E_SERVER_ERROR || response.code == AuthErrors.E_CLIENT_BLOCKED) {
// server error or client blocked already
res.send(JSON.stringify({ "status": "error", "code": response.code, "error": response.error }));
} else {
// save a failed logins entry in case its not a server error..
var failed = new PacNEMDB.NEMFailedLogins({
ipAddress: bundle.from,
address: bundle.address,
browserData: JSON.stringify(req.headers),
checksum: checksum,
createdAt: new Date().valueOf()
});
failed.save(function(err) {
res.send(JSON.stringify({ "status": "error", "code": response.code, "error": response.error }));
});
}
});
});
app.post("/api/v1/sessions/forget", function(req, res) {
res.setHeader('Content-Type', 'application/json');
var ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
var bundle = {
ip: ip,
client: req.headers['user-agent'],
address: req.body.address.replace(/-/g, ''),
};
Authenticator.expireActiveSession(bundle, function(session) {
if (!session) {
return res.send(JSON.stringify({ "status": "error", "code": AuthErrors.E_SERVER_ERROR, "error": "E_SERVER_ERROR" }));
}
return res.send(JSON.stringify({
"status": "ok",
"code": AuthErrors.E_SESSION_EXPIRED
}));
});
});
app.get("/api/v1/scores", function(req, res) {
res.setHeader('Content-Type', 'application/json');
HallOfFame.fetchBlockchainHallOfFame(null, function(hallOfFame) {
var ranking = hallOfFame.ranking;
var scores = [];
for (var i = 0; i < ranking.length; i++) {
var rScore = ranking[i];
var fmtTime = rScore.timestamp.toISOString().replace(/T/, ' ')
.replace(/\..+/, '');
scores.push({
position: i + 1,
score: rScore.score,
username: rScore.username,
address: rScore.address,
truncAddress: rScore.address.substr(0, 8),
transactionHash: rScore.transactionHash,
truncHash: rScore.transactionHash.substr(0, 8),
scoreDate: fmtTime
});
}
res.send(JSON.stringify({ data: scores }));
});
});
app.get("/api/v1/sponsors/random", function(req, res) {
res.setHeader('Content-Type', 'application/json');
var query = { "isApproved": true };
var address = req.query.address ? req.query.address : null;
if (address && address.length)
//XXX also validate NEM address format
query["xem"] = address;
PacNEMDB.NEMSponsor.find(query, function(err, sponsors) {
if (err) {
serverLog(req, "Error ocurred when reading NEMSponsor: " + err, "ERROR");
return res.send(500);
}
if (!sponsors || !sponsors.length) {
sponsor = new PacNEMDB.NEMSponsor({
slug: "evias-services",
realName: "eVias Services",
xem: "TDWZ55R5VIHSH5WWK6CEGAIP7D35XVFZ3RU2S5UQ",
sponsorName: "evias-services",
email: "[email protected]",
description: "eVias Services was founded in 2015 and is characterized by expertise in the field of Software development services, for the Web and Embedded devices. Specialized in the domain of Blockchain and Distributed Ledger Technology since 2010, eVias Services is part of the pioneering development community around the Bitcoin protocol and the technology that comes along with it.",
websiteUrl: "https://evias.be",
contentUrl: "https://evias.be/wp-content/themes/chilly/images/slider.jpg",
advertType: "image",
createdAt: new Date().valueOf()
});
sponsor.save();
sponsors.push(sponsor);
}
var cntSponsors = sponsors.length;
var randSponsor = sponsors[0];
// XXX content per sponsor..
var content = {
"type": "image",
"url": randSponsor.contentUrl || "https://placeholdit.imgix.net/~text?txtsize=47&txt=500%C3%97300&w=500&h=300",
"isImage": true,
"isVideo": false
};
var response = {
data: {
sponsor: randSponsor,
content: content
}
};
res.send(JSON.stringify(response));
});
});
app.post("/api/v1/sponsors/watch", function(req, res) {
res.setHeader('Content-Type', 'application/json');
var input = {
"slug": req.body.sponsor,
"username": req.body.player
};
//XXX NO-BREAK HERE
return res.send(JSON.stringify({ "status": "ok", "item": { "total": 0 } }));
// find sponsor then check if reward should be paid
var query = { "slug": input.slug };
PacNEMDB.NEMSponsor.findOne(query, function(err, sponsor) {
if (err) {
serverLog(req, "Error ocurred when reading NEMSponsor: " + err, "ERROR");
return res.send(500);
}
// maximum +1 every minute
var limitAge = new Date().valueOf() - (1 * 60 * 1000);
var adViewCounts = !sponsor.updatedAt || sponsor.updatedAt <= limitAge;
if (!sponsor.countAdViews)
sponsor.countAdViews = 0;
if (adViewCounts) {
sponsor.countAdViews = sponsor.countAdViews + 1;
sponsor.updatedAt = new Date().valueOf();
} else {
// Ad View came too early, not counted. (2 minutes interval)
serverLog(req, "Sponsor Ad View Skipped! With last save adView at: " + JSON.stringify(sponsor.updatedAt), "DEBUG");
return res.send(JSON.stringify({ "status": "ok" }));
}
sponsor.save(function(err) {
// now that the Ad View has been counted, we can save data and
// check whether it is needed to initiate a Payout or not.
PacNEMDB.NEMSponsorAdView.findOne({ "player": input.username }, null, { sort: { createdAt: -1 } }, function(err, adView) {
if (err) {
serverLog(req, "Error ocurred when reading NEMSponsorAdView: " + err, "ERROR");
return res.send(500);
}
serverLog(req, "Ad View counted in Sponsor Engine for Sponsor: " + JSON.stringify(sponsor), "DEBUG");
var nAdView = new PacNEMDB.NEMSponsorAdView({
player: input.username,
sponsorRef: sponsor.reference,
createdAt: new Date().valueOf()
});
nAdView.save(function(err) {
if (sponsor.countAdViews % 3 === 0) {
// every 3 ad views we will send mosaics pacnem:daily-ad-view
SponsorEngine.sendRewardForViews(sponsor);
}
return res.send(JSON.stringify({ "status": "ok", "item": { "total": sponsor.countAdViews } }));
});
});
});
});
});
app.get("/api/v1/credits/buy", function(req, res) {
res.setHeader('Content-Type', 'application/json');
var amount = parseFloat(config.get("prices.entry"));
var clientSocketId = req.query.usid ? req.query.usid : null;
if (!clientSocketId || !clientSocketId.length)
return res.send(JSON.stringify({ "status": "error", "message": "Mandatory field `Client Socket ID` is invalid." }));
var invoiceNumber = req.query.num ? req.query.num : null;
var payer = req.query.payer ? req.query.payer : undefined;
if (!payer.length || PacNEMBlockchain.isApplicationWallet(payer))
// cannot be one of the application wallets
return res.send(JSON.stringify({ "status": "error", "message": "Invalid value for field `payer`." }));
var recipient = req.query.recipient ? req.query.recipient : config.get("pacnem.business"); // the App's MultiSig wallet
if (!recipient.length || !PacNEMBlockchain.isApplicationWallet(recipient))
// must be one of the application wallets
return res.send(JSON.stringify({ "status": "error", "message": "Invalid value for field `recipient`." }));
var heartPrice = parseFloat(config.get("prices.heart")); // in XEM
var receivingHearts = Math.ceil(amount * heartPrice); // XEM price * (1 Heart / x XEM)
var invoiceAmount = amount * 1000000; // convert amount to micro XEM
var currentNetwork = PacNEMBlockchain.getNetwork();
var disableChannel = req.query.chan ? req.query.chan == "0" : false;
var dbConditions = {
payerXEM: payer,
recipientXEM: recipient
};
// when no invoiceNumber is given, create or retrieve in following statuses
dbConditions["status"] = { $in: ["not_paid", "identified", "unconfirmed", "paid_partly", "paid"] };
if (invoiceNumber && invoiceNumber.length) {
// load invoice by number
dbConditions["number"] = decodeURIComponent(invoiceNumber);
delete dbConditions["status"];
}
//serverLog("DEBUG", JSON.stringify(dbConditions), "DEBUG");
// mongoDB model NEMPaymentChannel unique on xem address + message pair.
PacNEMDB.NEMPaymentChannel.findOne(dbConditions, function(err, invoice) {
if (!err && !invoice) {
// creation mode
var invoice = new PacNEMDB.NEMPaymentChannel({
recipientXEM: recipient,
payerXEM: payer,
amount: invoiceAmount,
amountPaid: 0,
amountUnconfirmed: 0,
status: "not_paid",
countHearts: receivingHearts,
createdAt: new Date().valueOf()
});
invoice.save(function(err) {
return PaymentsProtocol.startPaymentChannel(invoice, clientSocketId, function(invoice) {
// payment channel created, end create-invoice response.
var statusLabelClass = "label-default";
var statusLabelIcon = "glyphicon glyphicon-time";
if (invoice.isPaid) {
statusLabelClass = "label-success";
statusLabelIcon = "glyphicon glyphicon-ok";
} else if (invoice.status == "paid_partly") {
statusLabelClass = "label-info";
statusLabelIcon = "glyphicon glyphicon-download-alt";
}
res.send(JSON.stringify({
status: "ok",