-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmessaging.ts
More file actions
executable file
·226 lines (201 loc) · 7.25 KB
/
messaging.ts
File metadata and controls
executable file
·226 lines (201 loc) · 7.25 KB
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
import * as admin from "firebase-admin";
import { Const, Messaging, RoomUser, Tweet, User, constToJSON, mediaTypeToJSON } from "./Gen/data";
import { onSchedule } from "firebase-functions/v2/scheduler";
import { logger } from "firebase-functions";
import { HttpsError, onCall } from "firebase-functions/v2/https";
import { checkUserExists, getUserById } from "./users";
import { getRoomById } from "./room";
// export const sendMessage = onCall({
// enforceAppCheck: true,
// }, (request): void => {
// admin.messaging().send({
// token: "device token",
// data: {
// hello: "world",
// },
// "notification": {
// "title": "Match update",
// "body": "Arsenal goal in added time, score is now 3-0"
// },
// // Set Android priority to "high"
// android: {
// priority: "high",
// },
// // Add APNS (Apple) config
// apns: {
// payload: {
// aps: {
// contentAvailable: true,
// },
// },
// headers: {
// "apns-push-type": "background",
// "apns-priority": "5", // Must be `5` when `contentAvailable` is set to true.
// "apns-topic": "io.flutter.plugins.firebase.messaging", // bundle identifier
// },
// },
// });
// });
export const callUnsubscribeFromTopic = onCall({
enforceAppCheck: true,
region: 'asia-south1',
}, async (request): Promise<void> => {
let uid = request.auth!.uid;
const roomuser = RoomUser.fromJSON(request.data);
toggleTopicSubsription(false, uid, roomuser.room!, null)
return;
})
export const callSubscribeFromTopic = onCall({
enforceAppCheck: true,
region: 'asia-south1',
}, async (request): Promise<void> => {
let uid = request.auth!.uid;
const roomuser = RoomUser.fromJSON(request.data);
toggleTopicSubsription(true, uid, roomuser.room!, null)
return;
})
export async function toggleTopicSubsription(subscribe: boolean, userId: string, roomId: string, token: string | null) {
let fcmToken = token ?? Messaging.fromJSON((await admin.firestore()
.doc(`fcmTokens/${userId}`).get().catch((e) => {
throw new HttpsError('aborted', e);
})).data()).fcmToken;
if (fcmToken) {
(subscribe ?
admin.messaging().subscribeToTopic(fcmToken, roomId)
: admin.messaging().unsubscribeFromTopic(fcmToken, roomId))
.then(async (v) => {
await admin.firestore().collection(constToJSON(Const.roomusers))
.doc(`${userId}_${roomId}`)
.update(
RoomUser.toJSON(RoomUser.create({
subscribed: subscribe,
updated: new Date(),
}))!)
.then(
async () => {
// await admin.firestore().collection(constToJSON(Const.users))
// .doc(userId)
// .update(
// User.toJSON(User.create({
// updated: new Date()
// }))!
// )
// .catch((err) => {
// throw new HttpsError('aborted', 'updateUserTime error');
// });
}
)
.catch((err) => {
throw new HttpsError('aborted', 'updateRoomUser failed');
});
}).catch((e) => {
console.log(e)
});
}
return;
}
export async function tweetToTopic(tweet: Tweet) {
let imgMeta = tweet.gallery?.find((imageMeta) => {
// if (imageMeta.path == null) {
// return false;
// }
return imageMeta.unsplashurl !== null;// || imageMeta.type === null;
})
let user = await getUserById(tweet.user!)
let room = await getRoomById(tweet.room!)
let text = tweet.text?.substring(0, 120);
text = text?.includes('TextEditor') ? 'Post' : text
admin.messaging().send(
{
topic: tweet.room!,
// token: '',
android: {
priority: "high",
},
data: {
'uid': tweet.uid!,
'room': tweet.room!,
'user': tweet.user!,
'mediaType': mediaTypeToJSON(tweet.mediaType!),
},
notification: {
"title": `${room?.displayName} (${user?.displayName})`,
"body": text,
imageUrl: imgMeta?.unsplashurl,
}
}
).then((v) => {
console.log(`send ${v}`)
}).catch((e) => {
console.log(e)
});
return;
}
// fetch(
// "https://fcm.googleapis.com/v1/projects/spacemoonfire/messages:send",
// {
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// },
// body: JSON.stringify({
// "message": {
// "name": "string",
// "token": "cpx_7x41SXmPSV3G8mbql3:APA91bE0n3euIfNykVtgLc_6nhCj2CgiCm0-DhKmGRaQUXGBUjpM2f5kyjOe8UYkL3RxQ1l6P89Bvfp6-LZH9QXxhnRIVAALJAwyDRYXboZPB-HFnGS7z13XlyZgY-p7za5P6GPfbxFV",
// "data": Tweet.toJSON(tweet),
// "android": {
// "priority": "high",
// },
// "notification": {
// "title": user?.uid,
// "body": tweet.text,
// }
// }
// })
// },
// ).then((v) => {
// console.log(v.status)
// return;
// })
export async function deleteFCMToken(userId: string) {
await admin.firestore().doc(`fcmTokens/${userId}`).delete().catch((e) => {
console.log('Failed deleteFCMToken')
})
}
export const callFCMtokenUpdate = onCall({
enforceAppCheck: true,
region: 'asia-south1',
}, async (request): Promise<void> => {
let uid = request.auth?.uid;
const { fcmToken } = request.data;
let userExists = await checkUserExists(uid!)
if (userExists) {
admin.firestore().doc(`fcmTokens/${uid}`).set(
Messaging.toJSON(
Messaging.create({
fcmToken: fcmToken,
timestamp: new Date(),
})
)!, { merge: true })
.catch((error) => {
throw new HttpsError('aborted', 'Error adding new field to custom claims');
});
} else {
throw new HttpsError('aborted', 'No user error');
}
return;
});
const EXPIRATION_TIME = 1000 * 60 * 60 * 24 * 60;
export const pruneTokens = onSchedule({
schedule: 'every 24 hours',
enforceAppCheck: true,
region: 'asia-south1',
}, async (event) => {
const staleTokensResult = await admin.firestore().collection('fcmTokens')
.where("timestamp", "<", new Date(Date.now() - EXPIRATION_TIME))
.get();
// Delete devices with stale tokens
staleTokensResult.forEach(function (doc) { doc.ref.delete(); });
logger.log("Token cleanup finished");
return;
});