-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
269 lines (238 loc) · 7.69 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
const url = require("url");
const appUrl = "https://oliversgame.deals";
const appIcon = "https://oliversgame.deals/icons/icon-192x192.png";
// Setup Firebase SDK
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const axios = require("axios");
const cors = require('cors')({ origin: true });
let emulated = process.env.FIREBASE_EMULATED === "true";
if (process.env.GOOGLE_APPLICATION_CREDENTIALS !== undefined) {
var serviceAccount = require(process.env.GOOGLE_APPLICATION_CREDENTIALS);
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
} else {
admin.initializeApp();
}
const topic = emulated === true ? "deals-dev" : "deals";
const CHANNEL_MAIN = "main";
/**
* Ensures the user who invoked the function is an admin.
*/
function ensureAdmin(context) {
const uid = context.auth.uid;
if (uid === null) {
throw new functions.https.HttpsError("unauthenticated", "Not logged in");
}
return admin
.firestore()
.collection("admins")
.doc(uid)
.get()
.catch(err => {
console.error("Failed to get admins collection document", err);
throw new functions.https.HttpsError(
"internal",
"Failed to determine admin status"
);
})
.then(docRef => {
if (docRef.exists === false) {
throw new functions.https.HttpsError(
"permission-denied",
"Not an admin"
);
}
return Promise.resolve();
});
}
/**
* Subscribe a client to the deals FCM topic.
* Uses the request context to know the user's FCM token.
* Data optionally { channel: string }, which can be used to augment which deals
* topic to subscribe to. Only allowed to be used by admins.
*/
exports.subscribe = functions.https.onCall((data, context) => {
const fcmToken = context.instanceIdToken;
let channel = data && data.channel ? data.channel : CHANNEL_MAIN;
const subTopic = `${topic}-${channel}`;
var baseProm = Promise.resolve();
if (channel !== CHANNEL_MAIN) {
baseProm = ensureAdmin(context);
}
return baseProm
.then(() => admin.messaging().subscribeToTopic(fcmToken, subTopic))
.then(resp => {
return Promise.resolve({});
});
});
/**
* Unsubscribe a client from the deals FCM topic.
* Uses the request context to know the user's FCM token.
* Data optionally { channel: string }, which can be used to augment which deals
* topic to unsubscribe from. Only allowed to be used by admins.
*/
exports.unsubscribe = functions.https.onCall((data, context) => {
const fcmToken = context.instanceIdToken;
const channel = data && data.channel ? data.channel : CHANNEL_MAIN;
const unsubTopic = `${topic}-${channel}`;
var baseProm = Promise.resolve();
if (channel !== CHANNEL_MAIN) {
baseProm = ensureAdmin(context);
}
return baseProm
.then(() => admin.messaging().unsubscribeFromTopic(fcmToken, unsubTopic))
.then(resp => {
return Promise.resolve({});
});
});
/**
* Send a notification about a new game deal to clients subscribed to the
* deals topic.
* Data must be { dealId: string, confirmResend: bool, channel: string }, where
* dealId is the ID of the deals document and confirmResend is set to true if you
* want to send a notification for a deal which has already had a notification
* sent, this key is optional. The channel key can be used to augment which topic
* to send the notification to.
*/
exports.notify = functions.https.onCall((data, context) => {
const channel = data && data.channel ? data.channel : CHANNEL_MAIN;
const notifyTopic = `${topic}-${channel}`;
const dealId = data.dealId;
const confirmResend = data.confirmResend || false;
// Determine if admin
return ensureAdmin(context)
.then(() => {
// Get deal from database
return admin.firestore().collection("deals").doc(dealId).get();
})
.catch(error => {
console.error("Failed to get deal to send notification for", error);
throw new functions.https.HttpsError(
"internal",
"Failed to retrieve deal"
);
})
.then(async docRef => {
if (docRef.exists === false) {
throw new functions.https.HttpsError(
"not-found",
"Deal does not exist"
);
}
const deal = docRef.data();
// Check if we are okay to resend the notification
const notificationSent =
channel in deal.notificationSent
? deal.notificationSent[channel]
: false;
if (notificationSent === true && confirmResend === false) {
throw new functions.https.HttpsError(
"already-exists",
"Notification already sent for " + "this deal"
);
}
// Send a Discord message
const dealLink = url.parse(deal.link);
const dealPrice = deal.isFree === true ? "free" : deal.price;
const webhookData = {
"content": "Hi there, it's me, totally not anti-Semitic Oliver, bringing you a brand new game deal!",
"embeds": [
{
"title": deal.name,
"type": "rich",
"description": `${dealPrice === "free" ? "FREE" : "$" + dealPrice}! (click the title above to get the game)\nExpires ${deal.expires.toDate().toDateString()}`,
"url": deal.link,
}
]
}
if (deal.image) {
webhookData.embeds[0].image = {
"url": deal.image,
"height": 100,
"width": 100
}
}
// eslint-disable-next-line promise/no-nesting
await axios.post(functions.config().discord.webhook, webhookData)
.catch(error => console.error(error));
// Send notification to clients who subscribe
return admin.messaging().send({
topic: notifyTopic,
webpush: {
notification: {
title: `Deal on ${deal.name} (${dealPrice})`,
body:
`${deal.name} is now available at ` +
`${dealLink.hostname} for ${dealPrice}`,
icon: appIcon,
image: deal.image,
requireInteraction: true,
},
fcmOptions: {
link: appUrl,
},
},
fcmOptions: {
analyticsLabel: `${dealId}-${channel}`,
},
});
})
.then(() => {
// Record that notification was sent on channel
var sentUpdate = {};
sentUpdate[`notificationSent.${channel}`] = true;
return admin
.firestore()
.collection("deals")
.doc(dealId)
.update(sentUpdate);
});
});
// !!!FOR LOCAL DEVELOPMENT USE ONLY!!!
// If firebase is being emulated expose some development utility functions
if (emulated === true) {
/**
* Makes the current user an admin. Useful for setting up the local database with
* the correct admin users.
* Data must be the user's ID (uid).
*/
exports.devMakeUserAdmin = functions.https.onCall((data, context) => {
return admin
.firestore()
.collection("admins")
.doc(data)
.set({
admin: true,
})
.catch(error => {
throw new functions.https.HttpsError(
"internal",
"Failed to make user " + data + " an admin: " + error
);
});
});
/**
* Removes admin status from the current user. Useful for testing how pages will
* behave for non-admin users.
* Data must be the user's ID (uid).
*/
exports.devRemoveUserAdmin = functions.https.onCall((data, context) => {
return admin
.firestore()
.collection("admins")
.doc(data)
.delete()
.catch(error => {
throw new functions.https.HttpsError(
"internal",
"Failed to remove admin" +
"priviledges from user " +
data +
": " +
error
);
});
});
}