-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
728 lines (646 loc) · 22.5 KB
/
index.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
const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
const { initializeApp } = require('firebase-admin/app');
const { getFirestore, FieldValue } = require('firebase-admin/firestore');
const { parseISO, isAfter } = require('date-fns');
initializeApp();
const db = getFirestore();
const API_KEY = functions.config().tmdb.key;
const GMAIL_EMAIL = functions.config().gmail.email;
const GMAIL_PASSWORD = functions.config().gmail.password;
// fetch new specials for all comedians & update top favorite calculations
const maintenanceSchedule = 'every 12 hours';
//
// db retrieval functions
//
const getFirebaseDoc = async (collection, doc) => {
return db
.collection(collection)
.doc(doc)
.get()
.then((document) => {
if (!(document && document.exists)) throw Error(`--> /${collection}/${doc} doesn't exist`);
return document.data();
})
.then((data) => {
return { ...data };
});
};
// retrieve "specials/latest" doc
const getLatestSpecialsData = async () => {
return getFirebaseDoc('specials', 'latest');
};
// retrieve "/specials/latest" doc
const getUpcomingSpecialsData = async () => {
return getFirebaseDoc('specials', 'upcoming');
};
// retrieve "/comedians/latest" doc
const getLatestComediansData = async () => {
return getFirebaseDoc('comedians', 'latest');
};
//
// user favorite toggling
// - updates personal favorites: /users/{userId}/favorites: [] array
// - updates content favorite count: /comedians/all/{comedianId}: favorites: +/-1; (or /specials/all)
//
exports.toggleUserFavorite = functions
.runWith({
enforceAppCheck: true,
})
.https.onCall(async (data, context) => {
// for testing purposes:
// db.collection('specials')
// .doc('all')
// .update({
// 1043110: FieldValue.delete(),
// 150879: FieldValue.delete(),
// 654123: FieldValue.delete(),
// })
// .then(async () => {
// await getNewSpecialsForAllComedians();
// console.log('test complete');
// });
// return;
// app check w/ recaptcha v3
if (context.app == undefined) {
throw new functions.https.HttpsError(
'failed-precondition',
'This function must be called from an App Check verified app.',
);
}
const userId = context.auth.uid;
const userEmail = context.auth.token.email;
// favoriteId: "category-tmdbId" (ie: "comedians-123456789", "specials-123456789")
const favoriteId = data.favoriteId;
const [category, tmdbId] = favoriteId.split('-');
const userDocRef = db.collection('users').doc(userId);
const userDocResponse = await userDocRef.get();
const userDocData = userDocResponse.data();
const userDocFavoritesArr = userDocData.favorites;
// /comedians/all or /specials/all
const contentAllDocRef = db.collection(category).doc('all');
if (userDocFavoritesArr.includes(favoriteId)) {
// remove favorite from /users/.../favorites: []
userDocRef.set({ favorites: FieldValue.arrayRemove(favoriteId) }, { merge: true });
// update content's favorite count: /{comedians/specials}/all/id: {favorites: # }
contentAllDocRef.set(
{
[tmdbId]: {
favorites: FieldValue.increment(-1),
},
},
{ merge: true },
);
if (category === 'comedians') unsubscribeUserToComedian(userId, userEmail, tmdbId);
} else {
// add favorite from /users/.../favorites: []
userDocRef.set({ favorites: FieldValue.arrayUnion(favoriteId) }, { merge: true });
// update content's favorite count: /{comedians/specials}/all/id: {favorites: # }
contentAllDocRef.set(
{
[tmdbId]: {
favorites: FieldValue.increment(1),
},
},
{ merge: true },
);
if (category === 'comedians') subscribeUserToComedian(userId, userEmail, tmdbId);
}
});
const subscribeUserToComedian = async (userId, userEmail, comedianId) => {
console.log(`Subscribing: ${userEmail} (${userId}) to ${comedianId}`);
const comedianSubscribersDocRef = db.collection('comedianSubscribers').doc(comedianId);
comedianSubscribersDocRef.set(
{
[userId]: {
id: userId,
email: userEmail,
},
},
{ merge: true },
);
};
const unsubscribeUserToComedian = async (userId, userEmail, comedianId) => {
console.log(`Unsubscribing: ${userEmail} (${userId}) to ${comedianId}`);
const comedianSubscribersDocRef = db.collection('comedianSubscribers').doc(comedianId);
comedianSubscribersDocRef.update({
[userId]: FieldValue.delete(),
});
};
//
// update top favorite comedians & specials on a schedule
//
exports.updateTopFavorites = functions.pubsub.schedule(maintenanceSchedule).onRun(async () => {
const topComediansLimit = 10;
const topSpecialsLimit = 10;
const getNewTopFavorites = (allComediansOrAllSpecialsDocData, favoriteCountLimit) => {
return Object.keys(allComediansOrAllSpecialsDocData)
.map((id) => {
const data = allComediansOrAllSpecialsDocData[id];
return { ...data };
})
.sort((a, b) => (a.favorites < b.favorites ? 1 : -1))
.splice(0, favoriteCountLimit)
.reduce((prev, curr) => {
return {
...prev,
[curr.id]: {
...curr,
},
};
}, {});
};
const comediansAllDocData = await getFirebaseDoc('comedians', 'all');
const specialsAllDocData = await getFirebaseDoc('specials', 'all');
const updatedTopComediansData = getNewTopFavorites(comediansAllDocData, topComediansLimit);
const updatedTopSpecialsData = getNewTopFavorites(specialsAllDocData, topSpecialsLimit);
db.collection('comedians')
.doc('topFavorites')
.set(updatedTopComediansData)
.then(() =>
db
.collection('specials')
.doc('topFavorites')
.set(updatedTopSpecialsData)
.then(() => {
console.log('Successfully updated top favorites');
})
.catch((e) => {
console.log('Failed to update top favorites.');
console.log(e);
}),
);
return null;
});
//
// scheduled function: get new specials for all comedians
//
exports.getNewSpecialsForAllComedians = functions.pubsub
.schedule(maintenanceSchedule)
.onRun(async () => {
return await getNewSpecialsForAllComedians();
});
const getNewSpecialsForAllComedians = async () => {
const allComediansDocData = await getFirebaseDoc('comedians', 'all');
const allSpecialsDocData = await getFirebaseDoc('specials', 'all');
const allComedianIds = Object.keys(allComediansDocData);
const allExistingSpecialIds = Object.keys(allSpecialsDocData);
for (const comedianId of allComedianIds) {
const specialsRawData = await fetchTmdbSpecialsData(comedianId);
// determine if the comedian has any new specials
const newSpecials = specialsRawData.filter((newSpecial) => {
return allExistingSpecialIds.some(
(existingSpecialId) => Number(newSpecial.id) === Number(existingSpecialId),
)
? false
: true;
});
// if no new specials are available, stop here.
if (newSpecials.length === 0) return;
// comedian has new specials
try {
// get fresh data for the comedian's page
const comedianRawData = await fetchTmdbComedianData(comedianId);
console.log(`${comedianRawData.name} has ${newSpecials.length} new specials!`);
// add only new specials to /specials/all
// this prevents overwriting existing favorite counts (set to 0 on being added)
await addSpecialsToAllSpecialsDoc(newSpecials);
// add only new specials to .../upcoming and .../latest if applicable
// existing specials in the db have already been checked
await addSpecialsToLatestAndUpcomingSpecialsDocs(newSpecials);
// update /comedianPages/{comedianId}/
await addComedianPageDoc(comedianRawData, specialsRawData);
// update all /specialPages/ related to comedian
await addSpecialsPageDocs(comedianRawData, specialsRawData);
// create notifications for all users who like this comedian
await createAllUserNotifications(comedianRawData, newSpecials);
console.log(`Successfully updated with ${comedianRawData.name}'s new specials!`);
} catch (e) {
console.log(`Failed to add ${comedianRawData.name}'s new specials`);
console.error(e);
}
}
return null;
};
//
// notifications are created after fetching new specials data for all comedians
// - stored in: /users/{uid}/notifications: []
//
const createAllUserNotifications = async (comedianRawData, newSpecials) => {
await newSpecials.forEach(async (specialRawData) => {
const comedianId = comedianRawData.id;
// get all users subscribed to this comedian
const comedianSubscribersDocRef = db
.collection('comedianSubscribers')
.doc(comedianId.toString());
const comedianSubscribersDocResponse = await comedianSubscribersDocRef.get();
// if no users are subscribed to this comedian, stop here.
if (!comedianSubscribersDocResponse.exists) return;
const comedianSubscribersData = await comedianSubscribersDocResponse.data();
const userIds = Object.keys(comedianSubscribersData);
const userEmails = Object.keys(comedianSubscribersData).reduce((prev, id) => {
return `${prev}${comedianSubscribersData[id].email},`;
}, '');
try {
await sendEmailNotification(userEmails, specialRawData, comedianRawData);
} catch (e) {
console.log(`Email notification fail: ${e}`);
}
for (const uid of userIds) {
try {
await createFrontendUserNotification(uid, comedianRawData, specialRawData);
} catch (e) {
console.error(`Unable to create front end notification for ${uid}\n${e}`);
}
}
});
console.log('Successfully created frontend user notifications');
};
const createFrontendUserNotification = async (userId, comedianRawData, specialRawData) => {
const notification = {
comedian: {
name: comedianRawData.name,
id: comedianRawData.id,
profile_path: comedianRawData.profile_path,
},
data: {
id: specialRawData.id,
title: specialRawData.title,
poster_path: specialRawData.poster_path,
backdrop_path: specialRawData.backdrop_path,
release_date: specialRawData.release_date,
},
};
return await db
.collection('users')
.doc(userId)
.update({
notifications: FieldValue.arrayUnion(notification),
});
};
// TODO: Create an aesthetic HTML/CSS e-mail notification
const sendEmailNotification = async (emailList, specialRawData, comedianRawData) => {
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: { user: GMAIL_EMAIL, pass: GMAIL_PASSWORD },
});
const message = {
from: GMAIL_EMAIL,
to: emailList,
subject: `${comedianRawData.name} released a new comedy special!`,
html: `<a href="https://comedy.bmilcs.com/specials/${specialRawData.id}"><h1>${
specialRawData.title
}</h1></a><img alt=${specialRawData.title} src=${getTMDBImageURL(
specialRawData.poster_path,
)} />`,
};
return await transporter.sendMail(message);
};
//
// add comedian & their specials to the db: triggered by client
//
exports.addComedianAndSpecials = functions
.runWith({
enforceAppCheck: true,
})
.https.onCall(async (data, context) => {
// app check w/ recaptcha v3
if (context.app == undefined) {
throw new functions.https.HttpsError(
'failed-precondition',
'This function must be called from an App Check verified app.',
);
}
const { id } = data;
if (!id) return;
const specialsRawData = await fetchTmdbSpecialsData(id);
const comedianRawData = await fetchTmdbComedianData(id);
if (
!comedianRawData.id ||
comedianRawData.success === false ||
specialsRawData.success === false
) {
throw new functions.https.HttpsError(
'Fail',
`Unable to add the comedian at this time. Something went wrong when fetching TMDB data for Person ID #${id}`,
);
}
return addComedianPageDoc(comedianRawData, specialsRawData)
.then(() => addSpecialsPageDocs(comedianRawData, specialsRawData))
.then(() => addComedianToAllComediansDoc(comedianRawData))
.then(() => addComedianToLatestComediansDoc(comedianRawData))
.then(() => addSpecialsToAllSpecialsDoc(specialsRawData))
.then(() => addSpecialsToLatestAndUpcomingSpecialsDocs(specialsRawData))
.catch((error) => {
console.log(error);
throw new functions.https.HttpsError(
'Something went wrong while setting up the new comedian database entries.',
{
...error,
},
);
});
});
//
// firestore: /comedianPages/{comedianId}/
//
const addComedianPageDoc = (comedianRawData, specialsRawData) => {
const comedian = {
name: comedianRawData.name,
id: comedianRawData.id,
profile_path: comedianRawData.profile_path,
biography: comedianRawData.biography,
birthday: comedianRawData.birthday,
imdb_id: comedianRawData.imdb_id,
};
const categorizedContent = specialsRawData.reduce(
(prev, special) => {
if (isSpecial(comedianRawData.name, special.title)) {
return {
...prev,
specials: {
...prev.specials,
[special.id]: {
id: special.id,
title: special.title,
poster_path: special.poster_path,
backdrop_path: special.backdrop_path,
release_date: special.release_date,
},
},
};
} else if (isAppearance(comedianRawData.name, special.title)) {
return {
...prev,
appearances: {
...prev.appearances,
[special.id]: {
id: special.id,
title: special.title,
poster_path: special.poster_path,
backdrop_path: special.backdrop_path,
release_date: special.release_date,
},
},
};
} else {
return prev;
}
},
{ specials: {}, appearances: {} },
);
const pageData = {
personalData: { ...comedian },
...categorizedContent,
};
const comedianId = comedianRawData.id;
return db.collection('comedianPages').doc(comedianId.toString()).set(pageData);
};
//
// firestore: /specialPages/{id}
//
const addSpecialsPageDocs = async (comedianRawData, specialsRawData) => {
const comedian = {
comedian: comedianRawData.name,
comedianId: comedianRawData.id,
profile_path: comedianRawData.profile_path,
};
const specials = specialsRawData.reduce((prev, special, index) => {
// each special page features the details of the special
// and provides links to other specials by the same comedian
const otherSpecialsByComedian = specialsRawData
.filter((x, i) => i !== index)
.map((other) => {
return {
id: other.id,
title: other.title,
release_date: other.release_date,
poster_path: other.poster_path,
backdrop_path: other.backdrop_path,
};
});
return {
...prev,
[special.id]: {
comedian: {
name: comedianRawData.name,
id: comedianRawData.id,
profile_path: comedianRawData.profile_path,
},
data: {
id: special.id,
title: special.title,
...(special.poster_path && { poster_path: special.poster_path }),
...(special.backdrop_path && { backdrop_path: special.backdrop_path }),
...(special.runtime && { runtime: special.runtime }),
...(special.status && { status: special.status }),
...(special.overview && { overview: special.overview }),
...(special.homepage && { homepage: special.homepage }),
...(special.release_date && { release_date: special.release_date }),
...(isSpecial(comedianRawData.name, special.title) && { type: 'special' }),
...(isAppearance(comedianRawData.name, special.title) && { type: 'appearance' }),
},
otherContent: otherSpecialsByComedian,
},
};
}, {});
const batch = db.batch();
for (const special in specials) {
const pageData = {
...comedian,
...specials[special],
};
const docRef = db.collection('specialPages').doc(special);
batch.set(docRef, pageData);
}
return await batch.commit();
};
//
// firestore: /comedians/all
//
const addComedianToAllComediansDoc = (comedianRawData) => {
const comedian = {
[comedianRawData.id]: {
name: comedianRawData.name,
id: comedianRawData.id,
profile_path: comedianRawData.profile_path,
favorites: 0,
},
};
return db.collection('comedians').doc('all').set(comedian, { merge: true });
};
//
// firestore: /specials/all
//
const addSpecialsToAllSpecialsDoc = (specialsRawData) => {
const specials = specialsRawData.reduce((prev, special) => {
return {
...prev,
[special.id]: {
id: special.id,
title: special.title,
poster_path: special.poster_path,
backdrop_path: special.backdrop_path,
release_date: special.release_date,
favorites: 0,
},
};
}, {});
return db.collection('specials').doc('all').set(specials, { merge: true });
};
//
// firestore: /comedians/latest
//
// add comedian to /comedians/latest & restrict latest count to a finite #
const addComedianToLatestComediansDoc = async (comedianRawData) => {
const comedian = {
[comedianRawData.id]: {
name: comedianRawData.name,
id: comedianRawData.id,
profile_path: comedianRawData.profile_path,
dateAdded: FieldValue.serverTimestamp(),
},
};
let latestComedians = await getLatestComediansData().catch(() => {
return {};
});
latestComedians = { ...latestComedians, ...comedian };
const latestTenComedians = reduceLatestCountToNum(latestComedians, 10, 'dateAdded');
return db.collection('comedians').doc('latest').set(latestTenComedians);
};
//
// firestore: /specials/latest & /specials/upcoming
//
// add recently released specials to /specials/latest & upcoming specials to /specials/upcoming
const addSpecialsToLatestAndUpcomingSpecialsDocs = async (specialsRawData) => {
const specials = specialsRawData.reduce((prev, special) => {
return {
...prev,
[special.id]: {
id: special.id,
title: special.title,
poster_path: special.poster_path,
backdrop_path: special.backdrop_path,
release_date: special.release_date,
},
};
}, {});
let latest = await getLatestSpecialsData().catch(() => {
return {};
});
let upcoming = await getUpcomingSpecialsData().catch(() => {
return {};
});
// for each special, check the dateField
// - if not released yet, add to /specials/upcoming
// - if newer than one of the latest 10, add to /specials/latest
for (const specialId in specials) {
const specialData = specials[specialId];
const isNotReleasedYet = isSpecialNotOutYet(specialData);
if (isNotReleasedYet) {
upcoming = {
...upcoming,
[specialId]: specialData,
};
} else {
const isALatestRelease = isSpecialALatestRelease(specialData, latest);
if (isALatestRelease) {
latest = {
...latest,
[specialId]: specialData,
};
}
}
}
const latestTenSpecials = reduceLatestCountToNum(latest, 10, 'release_date');
return db
.collection('specials')
.doc('latest')
.set(latestTenSpecials)
.then(() => db.collection('specials').doc('upcoming').set(upcoming));
};
const isSpecial = (comedianName, title) => {
const [firstName, lastName] = comedianName.split(' ');
const titlePrefix = title.split(':')[0];
const isSpecial = title.includes(firstName) && title.includes(lastName);
const isAppearance = titlePrefix.includes('Presents');
return isSpecial && !isAppearance ? true : false;
};
const isAppearance = (comedianName, title) => {
const [firstName, lastName] = comedianName.split(' ');
const titlePrefix = title.split(':')[0];
const isAppearance =
titlePrefix.includes('Presents') ||
!(titlePrefix.includes(firstName) && titlePrefix.includes(lastName));
return isAppearance ? true : false;
};
// returns true if special's release date is after today's date
const isSpecialNotOutYet = (special) => {
const specialDate = parseISO(special.release_date);
const today = new Date();
return isAfter(specialDate, today) ? true : false;
};
// returns true if a special's date is after one of the latest specials dates
const isSpecialALatestRelease = (special, latestSpecialsObj) => {
const specialDate = parseISO(special.release_date);
// when /specials/latest is empty, accept any special as a latest release
if (!latestSpecialsObj || Object.keys(latestSpecialsObj).length === 0) return true;
for (const existingSpecial in latestSpecialsObj) {
const existingDate = parseISO(latestSpecialsObj[existingSpecial].release_date);
const isMoreRecent = isAfter(specialDate, existingDate);
if (isMoreRecent) {
isALatestSpecial = true;
return true;
}
}
return false;
};
// given a object of comedians or specials, sort by "dateField" &
// limit the results to "num"
const reduceLatestCountToNum = (dataObj, num, dateField) => {
const array = [];
for (const data in dataObj) {
array.push(dataObj[data]);
}
return array
.sort((a, b) => {
const aDate = parseISO(a[dateField]);
const bDate = parseISO(b[dateField]);
return isAfter(aDate, bDate) ? -1 : 1;
})
.splice(0, num)
.reduce((prev, curr) => {
return { ...prev, [curr.id]: { ...curr } };
}, {});
};
//
// tmdb-related functions
//
const fetchTmdbComedianData = async (comedianId) => {
const comedianUrl = getPersonDetailsURL(comedianId);
const comedianData = await fetchData(comedianUrl);
return comedianData;
};
const fetchTmdbSpecialsData = async (comedianId) => {
const specialsUrl = getAllSpecialsForPersonURL(comedianId);
const { results: specialsData } = await fetchData(specialsUrl);
return specialsData;
};
const getTMDBImageURL = (path) => {
return `https://image.tmdb.org/t/p/original/${path}`;
};
const getAllSpecialsForPersonURL = function (personId) {
return `https://api.themoviedb.org/3/discover/movie?api_key=${API_KEY}&with_keywords=9716&with_cast=${personId}`;
};
const getPersonDetailsURL = function (personId) {
return `https://api.themoviedb.org/3/person/${personId}?api_key=${API_KEY}`;
};
const fetchData = async function (url) {
try {
const response = await fetch(url);
const json = await response.json();
return json;
} catch (err) {
return err;
}
};