-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
1471 lines (1093 loc) · 51.5 KB
/
server.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/env node
const validUrl=/^(http|https):\/\/.{1,}\..{1,}/gi;
// Core modules:
const fs = require('fs');
const path = require('path');
const querystring = require('querystring');
const url = require('url');
const https = require('https');
// Other modules:
const express = require('express');
const bodyParser = require('body-parser');
// Mailchimp Marketing API
const mailchimp = require("@mailchimp/mailchimp_marketing");
mailchimp.setConfig({
apiKey: process.env.mcapikey,
server: process.env.mcapikey.split("-")[1],
});
// ATProtocol (for Bluesky)
const blue = require('@atproto/api');
// The Express web server itself:
const app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json({limit: '50mb'}))
app.disable('etag');
app.disable('x-powered-by');
app.enable('trust proxy');
// Error handler for Express and its middlewares, like BodyParser, etc.
// Source: https://stackoverflow.com/a/53048858/5471286
app.use((err, req, res, callback) => {
console.error(err);
res.sendStatus(500);
callback();
});
// Tedious: used to connect to SQL Server:
const Connection = require('tedious').Connection;
const Request = require('tedious').Request;
const Types = require('tedious').TYPES;
// Connection string to the SQL Database:
var connectionString = {
server: process.env.dbserver,
authentication: {
type: 'default',
options: {
userName: process.env.dblogin,
password: process.env.dbpassword
}
},
options: { encrypt : true,
database : process.env.dbname,
connectTimeout : 20000, // 20 seconds before connection attempt times out.
requestTimeout : 30000, // 20 seconds before request times out.
rowCollectionOnRequestCompletion : true,
dateFormat : 'ymd',
keepAlive : true, /*
isolationLevel: 'SERIALIZABLE',
connectionIsolationLevel : 'SERIALIZABLE', */
appName : 'callfordataspeakers.com', // host name of the web server
validateBulkLoadParameters: true // whatever it takes to stop the nagging.
}
};
/*-----------------------------------------------------------------------------
Start the web server
-----------------------------------------------------------------------------*/
var serverPort=process.argv[2] || process.env.PORT || 3000;
console.log(' **** CALLFORDATASPEAKERS.COM ****');
console.log('HTTP port: '+serverPort);
console.log('Database server: '+process.env.dbserver);
console.log('Express env: '+app.settings.env);
console.log('');
app.listen(serverPort, () => console.log('READY.'));
/*-----------------------------------------------------------------------------
Start page: Speaker registration
-----------------------------------------------------------------------------*/
app.get('/', function (req, res, next) {
httpHeaders(res);
// Serve up assets/speaker.html:
res.status(200).send(createHTML('speaker.html', {}));
});
/*-----------------------------------------------------------------------------
Event request
-----------------------------------------------------------------------------*/
app.all('/event', function (req, res, next) {
var map={};
if (req.body.url) { map.url=encodeHtml(req.body.url); }
if (req.body.email) { map.url=encodeHtml(req.body.email); }
if (req.body.fname) { map.url=encodeHtml(req.body.fname); }
if (req.body.lname) { map.url=encodeHtml(req.body.lname); }
if (req.body.eventname) { map.url=encodeHtml(req.body.eventname); }
if (req.body.venue) { map.url=encodeHtml(req.body.venue); }
if (req.body.date) {
var dt=new Date(req.body.date);
if (!isNaN(dt)) {
map.year=dt.getUTCFullYear();
map.month=dt.getUTCMonth()+1;
map.day=dt.getUTCDate();
}
}
if (req.body.year) { map.year=encodeHtml(req.body.year); }
if (req.body.month) { map.month=encodeHtml(req.body.month); }
if (req.body.day) { map.day=encodeHtml(req.body.day); }
if (req.body.virtual) { map.virtual_check='checked'; }
if (req.body.conference) { map.conference_check='checked'; }
if (req.body.precon) { map.precon_check='checked'; }
if (req.body.usergroup) { map.usergroup_check='checked'; }
if (req.body.paid) { map.paid_check='checked'; }
httpHeaders(res);
// Serve up assets/event.html:
res.status(200).send(createHTML('event.html', map));
});
/*-----------------------------------------------------------------------------
Event request moderation
-----------------------------------------------------------------------------*/
app.get('/moderate/:token', function (req, res, next) {
httpHeaders(res);
// Serve up assets/event.html:
res.status(200).send(createHTML('moderate.html', {}));
});
/*-----------------------------------------------------------------------------
Register a new event request, send a request email to moderator:
-----------------------------------------------------------------------------*/
app.all('/request', function (req, res, next) {
httpHeaders(res);
// Parse query string parameters:
queryParams = querystring.parse(url.parse(req.url).query);
// The "c" variable is passed from the Mailchimp validation form, and I
// suppose it fills some kind of purpose that we pass it back in our response:
jQueryIdentifier=queryParams.c;
// Honey trap triggered: this is a bot
if (queryParams.free_hunny) {
res.status(404).send("Nice try, bot.");
return;
}
// Could be GET or POST, so we'll check both:
var formName=(queryParams.FNAME || req.body.FNAME)+' '+(queryParams.LNAME || req.body.LNAME);
var formEmail=req.body.EMAIL || queryParams.EMAIL;
var formEventName=req.body.EVENT || queryParams.EVENT;
var formEventVenue=req.body.VENUE || queryParams.VENUE;
var formEventDate;
try {
formEventDate=new Date(
(queryParams["EVENTDATE[year]"] || req.body["EVENTDATE[year]"])+'-'+
(queryParams["EVENTDATE[month]"] || req.body["EVENTDATE[month]"])+'-'+
(queryParams["EVENTDATE[day]"] || req.body["EVENTDATE[day]"])+' 00:00:00+00:00').toISOString().split("T")[0];
} catch(err) {
res.status(400).send("Input validation failed on EVENTDATE parameters.");
return;
}
var formEventEndDate;
try {
formEventEndDate=new Date(
(queryParams["EVENTENDDATE[year]"] || req.body["EVENTENDDATE[year]"])+'-'+
(queryParams["EVENTENDDATE[month]"] || req.body["EVENTENDDATE[month]"])+'-'+
(queryParams["EVENTENDDATE[day]"] || req.body["EVENTENDDATE[day]"])+' 00:00:00+00:00').toISOString().split("T")[0];
} catch(err) {
}
var formEventURL=queryParams.URL || req.body.URL;
var formEventInfo=queryParams.INFO || req.body.INFO;
// If you select a single region, it's a string, but with multiple regions, the
// variable turns into an array. So if it's an array, we need to turn it back
// into a comma-delimited string again.
var formEventRegions=(queryParams.REGION || req.body.REGION);
if (typeof formEventRegions!='string') {
formEventRegions=formEventRegions.join(",");
}
// Same type of logic for event type as for event region above.
var formEventType=(queryParams.TYPE || req.body.TYPE || "");
if (typeof formEventType!='string') {
formEventType=formEventType.join(", ");
}
// Very basic form validation:
if(!formName || !formEmail || !formEventName ||
!formEventVenue || !formEventDate ||
formEventRegions.split(",").length>3 ||
!formEventURL.match(validUrl)) {
console.log("Pretty clever, huh.");
res.status(400).send('Not like this.');
return;
} else {
// Save the everything to the SQL Server table:
sqlQuery(connectionString,
'EXECUTE CallForDataSpeakers.Insert_Campaign @Name=@Name, @Email=@Email, @EventName=@EventName, @EventType=@EventType, @Regions=@Regions, @Venue=@Venue, @Date=@Date, @EndDate=@EndDate, @URL=@URL, @Information=@Information;',
[ { "name": 'Name', "type": Types.NVarChar, "value": formName },
{ "name": 'Email', "type": Types.NVarChar, "value": formEmail },
{ "name": 'EventName', "type": Types.NVarChar, "value": formEventName },
{ "name": 'EventType', "type": Types.NVarChar, "value": formEventType },
{ "name": 'Regions', "type": Types.NVarChar, "value": formEventRegions },
{ "name": 'Venue', "type": Types.NVarChar, "value": formEventVenue },
{ "name": 'Date', "type": Types.Date, "value": formEventDate },
{ "name": 'EndDate', "type": Types.Date, "value": formEventEndDate },
{ "name": 'URL', "type": Types.NVarChar, "value": formEventURL },
{ "name": 'Information', "type": Types.NVarChar, "value": formEventInfo }],
// The stored procedure will return a uniqueidentifier (Token), used to identify
// each event request:
function(recordset) {
if (recordset) {
// Create an email to all moderators, requesting event approval:
var approveButton='<a class="mcnButton" title="Review" href="https://'+req.hostname+'/moderate/'+recordset[0].Token+'" '+
'target="_blank" style="font-weight:normal;letter-spacing:normal;line-height:100%;text-align:center;'+
'text-decoration:none;color:#000000;">Review</a>';
// These are the "mc:edit" values that we want to fill into our template:
var templateSections={
"name": formName,
"event_email": formEmail,
"event_regions": formEventRegions,
"event_name": formEventName,
"event_type": formEventType,
"event_venue": formEventVenue,
"event_date": formEventDate + (formEventEndDate ? ' -> ' + formEventEndDate : ''),
"event_url": formEventURL,
"event_info": formEventInfo,
"event_approve": approveButton
};
// Here's where we send the campaign:
sendCampaign(process.env.organizer_audience, // Audience
'Moderators', // Segment name
'',
process.env.request_template, // Template name
false, // Tracking
false, // Tweet
templateSections, // Values template fields
'New campaign request', // Subject line
'There\'s a new request for a call for speakers email to review.', // Preview
'[email protected]') // Reply-to
// Send successful:
.then(() => {
res.status(200).send(
jQueryIdentifier+'('+
JSON.stringify({
"result": "success",
"msg": "Thank you. A moderator will review your request."
})+')'
);
return;
})
// Send failed:
.catch(err => {
console.log(err);
res.status(500).send(
jQueryIdentifier+'('+
JSON.stringify({
"result": "error",
"msg": "Sorry. Something didn\'t work out."
})+')'
);
return;
});
} else {
console.log('ERROR: Couldn\'t create the campain record in the database.');
res.status(500).send('There was a problem with the database connection.');
return;
}
});
}
});
/*-----------------------------------------------------------------------------
Modify an event request from the moderation interface:
-----------------------------------------------------------------------------*/
// Save any changes to the request before sending it out
app.post('/api/update/:token', function(req, res, next) {
console.log('1');
var formEventDate;
try {
formEventDate=new Date(
req.body["EVENTDATE[year]"]+'-'+
req.body["EVENTDATE[month]"]+'-'+
req.body["EVENTDATE[day]"]+' 00:00:00+00:00').toISOString().split("T")[0];
console.log('1a');
} catch(err) {
console.log('1b');
console.log(err);
res.status(400).send('That\'s odd.');
return;
}
console.log('2');
var formEventEndDate;
try {
formEventEndDate=new Date(
req.body["EVENTENDDATE[year]"]+'-'+
req.body["EVENTENDDATE[month]"]+'-'+
req.body["EVENTENDDATE[day]"]+' 00:00:00+00:00').toISOString().split("T")[0];
} catch(err) {
}
console.log('3');
console.log('eventDate:', formEventDate);
console.log('eventEndDate:', formEventEndDate);
// Save the everything to the SQL Server table:
try {
sqlQuery(connectionString,
'EXECUTE CallForDataSpeakers.Update_Campaign @Token=@Token, @Name=@Name, @Email=@Email, @EventName=@EventName, @EventType=@EventType, @Regions=@Regions, @Venue=@Venue, @Date=@Date, @EndDate=@EndDate, @URL=@URL, @Information=@Information;',
[ { "name": 'Token', "type": Types.NVarChar, "value": req.params.token},
{ "name": 'Name', "type": Types.NVarChar, "value": req.body.NAME },
{ "name": 'Email', "type": Types.NVarChar, "value": req.body.EMAIL },
{ "name": 'EventName', "type": Types.NVarChar, "value": req.body.EVENT },
{ "name": 'EventType', "type": Types.NVarChar, "value": req.body.TYPE },
{ "name": 'Regions', "type": Types.NVarChar, "value": req.body.REGION },
{ "name": 'Venue', "type": Types.NVarChar, "value": req.body.VENUE },
{ "name": 'Date', "type": Types.Date, "value": formEventDate },
{ "name": 'EndDate', "type": Types.Date, "value": formEventEndDate },
{ "name": 'URL', "type": Types.NVarChar, "value": req.body.URL },
{ "name": 'Information', "type": Types.NVarChar, "value": req.body.INFO }],
// The stored procedure will return a uniqueidentifier (Token), used to identify
// each event request:
function(recordset) {
if (recordset) {
res.status(200).send('ok');
} else {
console.log('ERROR: Couldn\'t create the campain record in the database.');
res.status(404).send('There was a problem with the database connection.');
return;
}
});
} catch(e) {
res.status(500).send('There was a problem with the database connection.');
}
});
/*-----------------------------------------------------------------------------
Approve an event request, send campaign to speakers:
-----------------------------------------------------------------------------*/
app.get('/approve/:token', function (req, res, next) {
res.status(200).send(createHTML('message.html', {
"subject": "Approving...",
"message": "Hang on..",
"script": '<script src="/assets/approve.js"></script>'
}));
});
app.get('/approve/:token/do', function (req, res, next) {
httpHeaders(res);
// The part of the URL that reflects the token:
var token=req.params.token;
// Approve the campaign in the database and retrieve the event information:
sqlQuery(connectionString,
'EXECUTE CallForDataSpeakers.Approve_Campaign @Token=@Token;',
[ { "name": 'Token', "type": Types.NVarChar, "value": token }],
async function(recordset) {
if (recordset) {
var fromDate = recordset[0].Date;
var toDate = recordset[0].EndDate;
// formatting the event date; example: Tuesday, December 22, 2020"
var eventDateString=fromDate.toLocaleDateString("en-US", { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
// for a range of dates, construct a human-readable date interval text:
if (recordset[0].EndDate) {
if (recordset[0].Date != recordset[0].EndDate) {
// "Friday, May 17 until Saturday, May 18, 2024"
if (toDate.getFullYear() != fromDate.getFullYear()) {
eventDateString=fromDate.toLocaleDateString("en-US", { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }) +
' until '+toDate.toLocaleDateString("en-US", { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
}
// "Friday, May 17, 2024 until Saturday, May 18, 2024"
else {
eventDateString=fromDate.toLocaleDateString("en-US", { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }) +
' until '+toDate.toLocaleDateString("en-US", { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
}
}
}
var eventInfoString=recordset[0].Information;
if (eventInfoString===null) { eventInfoString=''; }
// If the only region is "Virtual", this is a virtual event.
// If there are other regions, but they include "Virtual", this is a hybrid event.
// If there's no "Virtual" region, this is an in-person event.
var eventVirtualString;
if (recordset[0].Regions.toUpperCase().replace(' ', '').split(',')=='VIRTUAL') {
eventVirtualString='This is a virtual event';
}
else if (recordset[0].Regions.toUpperCase().replace(' ', '').split(',').includes('VIRTUAL')) {
eventVirtualString='This is an in-person event, but may also accept virtual session abtracts.';
}
else {
eventVirtualString='This is an in-person event.';
}
var cfsURL = recordset[0].URL;
// This is the button at the bottom of the email:
var eventButton='<a class="mcnButton" href="'+
// Add UTM parameters
cfsURL+(cfsURL.toLowerCase().indexOf('utm_source')==-1 ? (cfsURL.indexOf('?')==-1 ? '?' : '&')+'utm_source=callfordataspeakers&utm_campaign=speaker-email' : '')+'" '+
'target="_blank" '+
'style="font-weight:normal;letter-spacing:normal;line-height:100%;text-align:center;'+
'text-decoration:none;color:#000000;">View the Call for Speakers</a>';
var calendarLink='';
if (cfsURL.toLowerCase().indexOf('sessionize.com/')>0) {
calendarLink='<a href="'+cfsURL.replace('sessionize.com/', 'sessionize.com/add-to-calendar/cfs/')+'" style="text-decoration: underline; color: #000000;">Add to my calendar</a>';
}
// These are the "mc:edit" values that we want to fill into our template:
var templateSections={
"event_name": recordset[0].EventName,
"event_date": eventDateString,
"event_virtual": eventVirtualString,
"event_venue": recordset[0].Venue,
"event_type": recordset[0].EventType,
"name": recordset[0].Name,
"event_email": recordset[0].Email,
"event_info": eventInfoString,
"event_button": eventButton,
"calendar_link": calendarLink
};
// Send the Mailchimp campaign to all our subscribers:
sendCampaign(process.env.speaker_audience, // Audience
'',
recordset[0].Regions, // Region group members
process.env.campaign_template, // Template name
true, // Tracking
true, // Tweet
templateSections, // Values to template fields
'Call for speakers: '+recordset[0].EventName, // Subject line
recordset[0].EventName+' is coming to you on '+eventDateString+'. The call for speakers is open!', // Preview
'[email protected]') // Reply-to
// Success:
.then((cfsCampaignId) => {
// Post to Mastodon (if one is configured in the
// environment variables)
if (process.env.mastodon_access_token) {
postToMastodon('Call for speakers: '+recordset[0].EventName+
' - https://'+process.env.mcapikey.split('-')[1]+'.campaign-archive.com/?u='+
process.env.mailchimp_social_identifer+'&id='+cfsCampaignId);
}
// Post to Bluesky (if one is configured in the
// environment variables)
if (process.env.bluesky_password) {
postToBluesky('Call for speakers: '+recordset[0].EventName+
' - https://'+process.env.mcapikey.split('-')[1]+'.campaign-archive.com/?u='+
process.env.mailchimp_social_identifer+'&id='+cfsCampaignId);
}
res.status(200).send(createHTML('message.html', {
"subject": "Campaign sent",
"message": "Your campaign has been scheduled and will be sent out."
}));
return;
})
// Or not:
.catch(err => {
res.status(500).json(err);
return;
});
} else {
console.log('Invalid token: '+token+'.');
res.status(404).send(createHTML('message.html', {
"subject": "Nope",
"message": "That token is invalid or already used."
}));
return;
}
});
});
/*-----------------------------------------------------------------------------
REST API-ish to list events:
-----------------------------------------------------------------------------*/
app.get('/api/events', function (req, res, next) {
httpHeaders(res);
// Approve the campaign in the database and retrieve the event information:
sqlQuery(connectionString,
'SELECT EventName, EventType, Regions, Email, Venue, [Date], EndDate, [URL], Information, Cfs_Closes, Created, Lat, Long FROM CallForDataSpeakers.Feed ORDER BY [Date], Created;', [],
async function(recordset) {
res.status(200).json(recordset);
return;
});
});
app.get('/api/event/:token', function (req, res, next) {
httpHeaders(res);
// Approve the campaign in the database and retrieve the event information:
sqlQuery(connectionString,
'SELECT Name, EventName, EventType, Regions, Email, Venue, [Date], EndDate, [URL], Information, Cfs_Closes, Created FROM CallForDataSpeakers.Campaigns WHERE Token=@Token AND Sent IS NULL;',
[ { "name": 'Token', "type": Types.NVarChar, "value": req.params.token }],
async function(recordset) {
if (recordset) {
if (recordset[0].URL.toLowerCase().indexOf('sessionize.com/')>-1 && process.env.sessionize_apikey) {
blob=await fetchSessionizeEvent(recordset[0].URL);
if (blob) {
recordset[0].Sessionize=blob;
}
}
res.status(200).json(recordset);
return;
} else {
res.status(500).send('');
}
});
});
/*-----------------------------------------------------------------------------
List events:
-----------------------------------------------------------------------------*/
app.get('/list', function (req, res, next) {
httpHeaders(res);
res.status(200).send(createHTML('list.html', {}));
return;
});
/*-----------------------------------------------------------------------------
List precon speakers:
-----------------------------------------------------------------------------*/
app.get('/precon', function (req, res, next) {
httpHeaders(res);
res.status(200).send(createHTML('precon.html', {}));
return;
});
/*-----------------------------------------------------------------------------
RSS feed:
-----------------------------------------------------------------------------*/
app.get('/feed', async function (req, res, next) {
var items='';
sqlQuery(connectionString,
'SELECT EventName, EventType, Regions, Email, Venue, [Date], [URL], Information, Created, DATEDIFF_BIG(second, {d \'1970-01-01\'}, Created) AS uid FROM CallForDataSpeakers.Feed ORDER BY Created DESC;', [],
async function(recordset) {
var lastBuildDate=new Date(Date.now())
recordset.forEach(item => {
var eventDate=item.Date.toLocaleDateString("en-US", { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
items+='<item>\n'+
'<title>'+encodeHtml(item.EventName)+'</title>\n'+
'<link>'+item.URL+(item.URL.toLowerCase().indexOf('utm_source')==-1 ? (item.URL.indexOf('?')==-1 ? '?' : '&')+'utm_source=callfordataspeakers&utm_campaign=rss-feed' : '')+'</link>\n'+
'<dc:creator>Call for Data Speakers</dc:creator>\n'+
'<pubDate>' + item.Created.toUTCString() + '</pubDate>\n'+
'<category>Call for Speakers</category>\n'+
'<guid isPermaLink="false">'+item.uid+'</guid>\n'+
'<description><![CDATA['+encodeHtml(item.EventName)+']]></description>\n'+
'<content:encoded><![CDATA['+
encodeHtml(item.EventName)+' is coming to you on '+eventDate+'<br/>\n'+
'The <a href="'+item.URL+(item.URL.toLowerCase().indexOf('utm_source')==-1 ? (item.URL.indexOf('?')==-1 ? '?' : '&')+'utm_source=callfordataspeakers&utm_campaign=rss-feed' : '')+'">call for speakers</a> is open.\n'+
']]></content:encoded>\n'+
'<media:content url="https://'+req.hostname+'/assets/callfordataspeakers-logo.png" medium="image">\n'+
'<media:title type="html">dhmacher</media:title>\n'+
'</media:content>\n'+
'</item>\n\n'
});
res.type('application/rss+xml; charset=UTF-8');
res.status(200).send(createHTML('rss.xml', {
"lastBuildDate": lastBuildDate.toUTCString(),
"items": items
}));
return;
});
});
// https://stackoverflow.com/a/57448862/5471286
const encodeHtml = str => str.replace(/[&<>'"]/g,
tag => ({
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"'
}[tag]));
/*-----------------------------------------------------------------------------
List events:
-----------------------------------------------------------------------------*/
app.get('/api/sync-mailchimp/:apikey', async function (req, res, next) {
if (req.params.apikey==process.env.apikey) {
try {
// Update subscriber count:
var subscriberCount = await getSubscriberCount(process.env.speaker_audience);
// Update campaign/email count:
getCampaignCount(process.env.speaker_audience);
res.status(200).json(subscriberCount);
} catch(err) {
res.status(500);
}
console.log('Done');
} else {
console.log('Invalid API key for /api/sync-mailchimp');
res.status(401).send('Invalid API key');
}
});
async function getSubscriberCount(listName) {
var listId;
var groupId;
var subscriberCount;
var regions=[];
// Find the "Speakers" list (the audience):
var allLists = await mailchimp.lists.getAllLists();
Array.prototype.forEach.call(allLists.lists, list => {
if (list.name==listName) {
listId=list.id;
subscriberCount=list.stats.member_count;
}
});
// Find the "Regions" group:
var allGroups = await mailchimp.lists.getListInterestCategories(listId);
Array.prototype.forEach.call(allGroups.categories, group => {
if (group.title=='Region') {
groupId=group.id;
}
});
// Fetch all regions:
var allGroupMembers=await mailchimp.lists.listInterestCategoryInterests(listId, groupId, {"count": 100});
Array.prototype.forEach.call(allGroupMembers.interests, member => {
regions.push({
"name": member.name,
"subscriber_count": member.subscriber_count
});
});
// Write to file
fs.writeFileSync(__dirname + '/assets/subscriber-count.json', JSON.stringify(regions));
// Return the results:
return(regions);
}
async function getCampaignCount(listName) {
var offset=0;
var pageSize=1000;
var done=false;
var campaignCount=0;
var emailCount=0;
while (!done) {
// Fetch a page of campaigns:
var allCampaigns = await mailchimp.campaigns.list({ "count": pageSize, "offset": offset });
if (allCampaigns.campaigns.length>0) {
Array.prototype.forEach.call(allCampaigns.campaigns, campaign => {
if (campaign.recipients.list_name==listName) {
campaignCount++;
emailCount+=campaign.emails_sent;
}
});
// Set the next page to fetch:
offset+=pageSize;
if (allCampaigns.campaigns.length<pageSize) { done=true; }
} else {
done=true;
}
}
fs.writeFileSync(__dirname + '/assets/campaign-count.json', JSON.stringify({ "campaigns": campaignCount, "emails": emailCount }));
}
app.get('/api/get-sessionize', async function (req, res, next) {
var details={};
try {
details=await fetchSessionizeEvent(req.query.url);
res.status(200).send(JSON.stringify({
"URL": details.cfpLink,
"EventName": details.name,
"Date": details.eventDates.start,
"EndDate": details.eventDates.end,
"Venue": (details.location ? details.location.full : '')
}));
} catch(e) {
res.status(404).send('');
}
});
app.get('/api/sync-sessionize/:apikey', async function (req, res, next) {
if (req.params.apikey==process.env.apikey) {
await updateCfsCloseDates(res);
} else {
console.log('Invalid API key for /api/sync-sessionize');
res.status(401).send('Invalid API key');
}
});
async function updateCfsCloseDates(res) {
// Check the closing dates for Sessionize CfS where
// 1) there isn't one yet (new event), or
// 2) it's Sunday (check all of them once a week, in case they change)
sqlQuery(connectionString,
'SELECT Token, [URL], Cfs_Closes '+
'FROM CallForDataSpeakers.Campaigns '+
'WHERE [Date]>SYSUTCDATETIME() '+
' AND [URL] LIKE \'https://sessionize.com/_%\' '+
' AND ISNULL(Cfs_Closes, {d \'2099-12-31\'})>DATEADD(day, -14, SYSDATETIME());', [],
function(recordset) {
recordset.forEach(async function(record) {
var cfs=await fetchSessionizeEvent(record.URL)
var formattedUtcTime=cfs.cfpDates.endUtc.replace('T', ' ');
console.log(record.URL, formattedUtcTime);
sqlQuery(connectionString,
'EXECUTE CallForDataSpeakers.Update_CfsClose @Token=@Token, @Cfs_Closes=@Cfs_Closes;',
[ { "name": 'Token', "type": Types.NVarChar, "value": record.Token },
{ "name": 'Cfs_Closes', "type": Types.NVarChar, "value": formattedUtcTime }],
function(recordset) {});
});
});
res.status(200).send('OK');
}
async function getCalendar(url) {
const options = {
method: 'GET'
};
return new Promise((resolve, reject) => {
const req = https.request(url, options, (res) => {
if (res.statusCode>204) {
return reject(new Error('status='+res.statusCode));
}
const body = [];
res.on('data', (chunk) => body.push(chunk));
res.on('end', () => {
//console.log(Buffer.concat(body).toString());
var resBlob;
resBlob = Buffer.concat(body).toString();
resolve(resBlob);
});
})
req.on('error', (err) => {
reject(err);
})
req.on('timeout', () => {
req.destroy();
reject(new Error('Request time out'));
})
req.end();
});
}
/*-----------------------------------------------------------------------------
Other related assets, like client-side JS, CSS, images, whatever:
-----------------------------------------------------------------------------*/
app.get('/assets/:asset', function (req, res, next) {
httpHeaders(res);
var options = {
root: __dirname + '/assets/',
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
res.sendFile(req.params.asset, options, function(err) {
if (err) {
res.send(err);
return;
}
});
});
app.get('/:asset', function (req, res, next) {
httpHeaders(res);
var options = {
root: __dirname + '/assets/',
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
res.sendFile(req.params.asset, options, function(err) {
if (err) {
res.send(err);
return;
}
});
});
/*-----------------------------------------------------------------------------
Format the HTML template:
-----------------------------------------------------------------------------*/
function createHTML(templateFile, values) {
var rn=Math.random();
// Read the template file:
var htmlTemplate = fs.readFileSync(path.resolve(__dirname, './assets/'+templateFile), 'utf8').toString();
// Loop through the JSON blob given as the argument to this function,
// replace all occurrences of <%=param%> in the template with their
// respective values.
for (var param in values) {
if (values.hasOwnProperty(param)) {
htmlTemplate = htmlTemplate.split('\<\%\='+param+'\%\>').join(values[param]);