@dohaidang/locket_mod.js 0.0.0-stage → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +131 -0
- package/README.md +287 -2
- package/caption_presets.json +2021 -0
- package/index.d.ts +82 -0
- package/index.js +24 -0
- package/lib/client.js +86 -0
- package/lib/device.js +160 -0
- package/lib/exceptions.js +31 -0
- package/lib/http.js +21 -0
- package/lib/modules/chat.js +396 -0
- package/lib/modules/friends.js +147 -0
- package/lib/modules/moments.js +1114 -0
- package/lib/modules/user.js +162 -0
- package/lib/session.js +131 -0
- package/package.json +49 -6
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
const fs = require("fs");
|
|
2
|
+
const path = require("path");
|
|
3
|
+
const { randomUUID } = require("crypto");
|
|
4
|
+
const { fetchWithTimeout } = require("../http");
|
|
5
|
+
|
|
6
|
+
class ReactionEmoji {
|
|
7
|
+
static YELLOW_HEART = "💛";
|
|
8
|
+
static FIRE = "🔥";
|
|
9
|
+
static HEART_EYES = "😍";
|
|
10
|
+
static TWO_HEARTS = "💕";
|
|
11
|
+
static SPARKLE_HEART = "💖";
|
|
12
|
+
static SMILING_HEARTS = "🥰";
|
|
13
|
+
static LAUGHING = "😂";
|
|
14
|
+
static KISS = "💋";
|
|
15
|
+
static HEART_HANDS = "🫶";
|
|
16
|
+
static RED_HEART = "❤️";
|
|
17
|
+
static DEFAULT_QUICK_REACTIONS = ["💛", "🔥", "😍", "💕"];
|
|
18
|
+
static OFFICIAL_PALETTE = ["💛", "💖", "🥰", "😂", "🔥", "💋", "🫶", "❤️", "😍", "💕"];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
class ChatModule {
|
|
22
|
+
constructor(client) {
|
|
23
|
+
this.client = client;
|
|
24
|
+
this.ReactionEmoji = ReactionEmoji;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
static getSupportedReactions() {
|
|
28
|
+
return [...ReactionEmoji.OFFICIAL_PALETTE];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
_getHistoryFile() {
|
|
32
|
+
const baseDir = path.dirname(path.resolve(this.client.session.sessionPath || "locket.js_session.json"));
|
|
33
|
+
return path.join(baseDir, "chat_history.json");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
_loadHistory() {
|
|
37
|
+
const hfile = this._getHistoryFile();
|
|
38
|
+
if (fs.existsSync(hfile)) {
|
|
39
|
+
try { return JSON.parse(fs.readFileSync(hfile, "utf-8")); } catch (e) { return {}; }
|
|
40
|
+
}
|
|
41
|
+
return {};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
_saveHistory(history) {
|
|
45
|
+
const hfile = this._getHistoryFile();
|
|
46
|
+
try { fs.writeFileSync(hfile, JSON.stringify(history, null, 2), "utf-8"); } catch (e) {}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
recordMessage(options) {
|
|
50
|
+
const { conversationId, senderUid, receiverUid, text, messageId = null, clientToken = null, timestamp = null, reaction = null } = options;
|
|
51
|
+
const history = this._loadHistory();
|
|
52
|
+
const conv = history[conversationId] || (history[conversationId] = []);
|
|
53
|
+
const ts = timestamp || new Date().toISOString();
|
|
54
|
+
const entry = {
|
|
55
|
+
conversation_id: conversationId,
|
|
56
|
+
message_id: messageId,
|
|
57
|
+
client_token: clientToken,
|
|
58
|
+
sender_uid: senderUid,
|
|
59
|
+
receiver_uid: receiverUid,
|
|
60
|
+
is_me: senderUid === this.client.session.uid,
|
|
61
|
+
text,
|
|
62
|
+
has_reaction: Boolean(reaction),
|
|
63
|
+
reaction,
|
|
64
|
+
timestamp: ts
|
|
65
|
+
};
|
|
66
|
+
for (let i = 0; i < conv.length; i++) {
|
|
67
|
+
const existing = conv[i];
|
|
68
|
+
if ((clientToken && existing.client_token === clientToken) || (messageId && existing.message_id === messageId)) {
|
|
69
|
+
conv[i] = { ...existing, ...entry };
|
|
70
|
+
this._saveHistory(history);
|
|
71
|
+
return conv[i];
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
conv.push(entry);
|
|
75
|
+
conv.sort((a, b) => String(a.timestamp).localeCompare(String(b.timestamp)));
|
|
76
|
+
this._saveHistory(history);
|
|
77
|
+
return entry;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async fetchMessagesFromServer(options = {}) {
|
|
81
|
+
const { conversationId = null, otherUserId = null } = options;
|
|
82
|
+
let token;
|
|
83
|
+
try { token = await this.client.session.getValidToken(); } catch (e) { return []; }
|
|
84
|
+
const myUid = this.client.session.uid;
|
|
85
|
+
if (!token) return [];
|
|
86
|
+
|
|
87
|
+
let cid = conversationId;
|
|
88
|
+
if (!cid && otherUserId) {
|
|
89
|
+
try {
|
|
90
|
+
const uUrl = `https://firestore.googleapis.com/v1/projects/locket-4252a/databases/(default)/documents/users/${myUid}/conversations`;
|
|
91
|
+
const uRes = await fetchWithTimeout(uUrl, { headers: { Authorization: `Bearer ${token}` } }, 30000);
|
|
92
|
+
const uData = await uRes.json();
|
|
93
|
+
for (const doc of (uData.documents || [])) {
|
|
94
|
+
const cCandidate = doc.name.split("/").pop();
|
|
95
|
+
const cUrl = `https://firestore.googleapis.com/v1/projects/locket-4252a/databases/(default)/documents/conversations/${cCandidate}`;
|
|
96
|
+
const cRes = await fetchWithTimeout(cUrl, { headers: { Authorization: `Bearer ${token}` } }, 30000);
|
|
97
|
+
const cData = await cRes.json();
|
|
98
|
+
const members = ((cData.fields && cData.fields.members && cData.fields.members.arrayValue && cData.fields.members.arrayValue.values) || []).map(v => v.stringValue);
|
|
99
|
+
if (members.includes(otherUserId)) { cid = cCandidate; break; }
|
|
100
|
+
}
|
|
101
|
+
} catch (e) {}
|
|
102
|
+
}
|
|
103
|
+
if (!cid) return [];
|
|
104
|
+
|
|
105
|
+
const url = `https://firestore.googleapis.com/v1/projects/locket-4252a/databases/(default)/documents/conversations/${cid}/messages`;
|
|
106
|
+
let data;
|
|
107
|
+
try {
|
|
108
|
+
const res = await fetchWithTimeout(url, { headers: { Authorization: `Bearer ${token}` } }, 30000);
|
|
109
|
+
data = await res.json();
|
|
110
|
+
} catch (e) { return []; }
|
|
111
|
+
|
|
112
|
+
const serverMessages = [];
|
|
113
|
+
for (const doc of (data.documents || [])) {
|
|
114
|
+
const fields = doc.fields || {};
|
|
115
|
+
const docId = doc.name.split("/").pop();
|
|
116
|
+
const sender = (fields.sender && fields.sender.stringValue) || "";
|
|
117
|
+
const body = (fields.body && fields.body.stringValue) || "";
|
|
118
|
+
const createdAt = (fields.created_at && fields.created_at.timestampValue) || "";
|
|
119
|
+
const clientToken = (fields.client_token && fields.client_token.stringValue) || null;
|
|
120
|
+
|
|
121
|
+
const reactionsList = [];
|
|
122
|
+
if (fields.reactions) {
|
|
123
|
+
for (const r of (fields.reactions.arrayValue && fields.reactions.arrayValue.values) || []) {
|
|
124
|
+
const rf = (r.mapValue && r.mapValue.fields) || {};
|
|
125
|
+
reactionsList.push({
|
|
126
|
+
sender: (rf.sender && rf.sender.stringValue) || null,
|
|
127
|
+
emoji: (rf.emoji && rf.emoji.stringValue) || null,
|
|
128
|
+
created_at: (rf.created_at && rf.created_at.timestampValue) || null
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const isMe = sender === myUid;
|
|
134
|
+
const msgObj = {
|
|
135
|
+
conversation_id: cid,
|
|
136
|
+
message_id: docId,
|
|
137
|
+
client_token: clientToken,
|
|
138
|
+
sender_uid: sender,
|
|
139
|
+
receiver_uid: otherUserId ? otherUserId : (isMe ? null : myUid),
|
|
140
|
+
is_me: isMe,
|
|
141
|
+
text: body,
|
|
142
|
+
has_reaction: reactionsList.length > 0,
|
|
143
|
+
reaction: reactionsList.length ? reactionsList[0].emoji : null,
|
|
144
|
+
reactions: reactionsList,
|
|
145
|
+
timestamp: createdAt
|
|
146
|
+
};
|
|
147
|
+
serverMessages.push(msgObj);
|
|
148
|
+
this.recordMessage({
|
|
149
|
+
conversationId: cid,
|
|
150
|
+
senderUid: sender,
|
|
151
|
+
receiverUid: msgObj.receiver_uid,
|
|
152
|
+
text: body,
|
|
153
|
+
messageId: docId,
|
|
154
|
+
clientToken,
|
|
155
|
+
reaction: msgObj.reaction
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
serverMessages.sort((a, b) => String(a.timestamp).localeCompare(String(b.timestamp)));
|
|
159
|
+
return serverMessages;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async getMessages(options = {}) {
|
|
163
|
+
const { otherUserId = null, conversationId = null, fetchServer = true } = options;
|
|
164
|
+
if (fetchServer) {
|
|
165
|
+
const serverMsgs = await this.fetchMessagesFromServer({ conversationId, otherUserId });
|
|
166
|
+
if (serverMsgs && serverMsgs.length) return serverMsgs;
|
|
167
|
+
}
|
|
168
|
+
const history = this._loadHistory();
|
|
169
|
+
const myUid = this.client.session.uid;
|
|
170
|
+
const matched = [];
|
|
171
|
+
for (const [cid, msgs] of Object.entries(history)) {
|
|
172
|
+
if (conversationId && cid !== conversationId) continue;
|
|
173
|
+
for (const m of msgs) {
|
|
174
|
+
if (otherUserId) {
|
|
175
|
+
if (m.sender_uid === otherUserId || m.receiver_uid === otherUserId) matched.push(m);
|
|
176
|
+
} else {
|
|
177
|
+
matched.push(m);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
matched.sort((a, b) => String(a.timestamp).localeCompare(String(b.timestamp)));
|
|
182
|
+
return matched;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async sendMessage(options) {
|
|
186
|
+
const { receiverUid, text = null, momentUid = null } = options;
|
|
187
|
+
const token = randomUUID().toUpperCase();
|
|
188
|
+
const msgText = (text !== null && text !== "") ? text : (momentUid ? "\u200b" : "");
|
|
189
|
+
const payload = {
|
|
190
|
+
receiver_uid: receiverUid,
|
|
191
|
+
msg: msgText,
|
|
192
|
+
moment_uid: momentUid,
|
|
193
|
+
from_memory: false,
|
|
194
|
+
intensity: { value: "0", "@type": "type.googleapis.com/google.protobuf.Int64Value" },
|
|
195
|
+
client_token: token
|
|
196
|
+
};
|
|
197
|
+
const res = await this.client.postApi("sendChatMessageV2", payload);
|
|
198
|
+
const convUid = res && res.data && res.data.conversation_uid;
|
|
199
|
+
if (convUid) {
|
|
200
|
+
this.recordMessage({
|
|
201
|
+
conversationId: convUid,
|
|
202
|
+
senderUid: this.client.session.uid,
|
|
203
|
+
receiverUid,
|
|
204
|
+
text: text || "",
|
|
205
|
+
clientToken: token
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
const dataRes = (res && res.data) ? res.data : res;
|
|
209
|
+
if (dataRes && typeof dataRes === "object" && !dataRes.msg_id) {
|
|
210
|
+
dataRes.msg_id = token;
|
|
211
|
+
dataRes.client_token = token;
|
|
212
|
+
}
|
|
213
|
+
return dataRes;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async sendMoment(receiverUid, momentUid, text = null) {
|
|
217
|
+
return this.sendMessage({ receiverUid, text, momentUid });
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async deleteMessage(conversationUid, messageUid, validateOwnership = true) {
|
|
221
|
+
if (validateOwnership) {
|
|
222
|
+
const history = this._loadHistory();
|
|
223
|
+
const conv = history[conversationUid] || [];
|
|
224
|
+
for (const m of conv) {
|
|
225
|
+
if ((m.message_id === messageUid || m.client_token === messageUid) && !m.is_me) {
|
|
226
|
+
throw new Error(`Cannot recall/delete message (${messageUid}) because it was sent by someone else. You can only recall your own messages.`);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
const payload = { conversation_uid: conversationUid, message_uid: messageUid };
|
|
231
|
+
const res = await this.client.postApi("deleteChatMessage", payload);
|
|
232
|
+
if (res && res.status === 200) {
|
|
233
|
+
const history = this._loadHistory();
|
|
234
|
+
if (history[conversationUid]) {
|
|
235
|
+
history[conversationUid] = history[conversationUid].filter(m => m.message_id !== messageUid && m.client_token !== messageUid);
|
|
236
|
+
this._saveHistory(history);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return res;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async sendReaction(conversationId, messageId, emoji, validateReceiver = true) {
|
|
243
|
+
if (validateReceiver) {
|
|
244
|
+
const history = this._loadHistory();
|
|
245
|
+
const conv = history[conversationId] || [];
|
|
246
|
+
for (const m of conv) {
|
|
247
|
+
if (m.message_id === messageId && m.is_me) {
|
|
248
|
+
throw new Error(`Cannot react to your own message (${messageId}). Locket only allows reactions on friend's messages.`);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
const payload = { conversation_id: conversationId, message_id: messageId, emoji };
|
|
253
|
+
const res = await this.client.postApi("sendChatMessageReaction", payload);
|
|
254
|
+
if (res && res.status === 200) {
|
|
255
|
+
const history = this._loadHistory();
|
|
256
|
+
if (history[conversationId]) {
|
|
257
|
+
for (const m of history[conversationId]) {
|
|
258
|
+
if (m.message_id === messageId) { m.reaction = emoji; m.has_reaction = true; }
|
|
259
|
+
}
|
|
260
|
+
this._saveHistory(history);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
return res;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async removeReaction(conversationId, messageId) {
|
|
267
|
+
const payload = { conversation_id: conversationId, message_id: messageId };
|
|
268
|
+
const res = await this.client.postApi("removeChatMessageReaction", payload);
|
|
269
|
+
if (res && res.status === 200) {
|
|
270
|
+
const history = this._loadHistory();
|
|
271
|
+
if (history[conversationId]) {
|
|
272
|
+
for (const m of history[conversationId]) {
|
|
273
|
+
if (m.message_id === messageId) { m.reaction = null; m.has_reaction = false; }
|
|
274
|
+
}
|
|
275
|
+
this._saveHistory(history);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return res;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
async markAsRead(options = {}) {
|
|
282
|
+
const { conversationUid = null, otherUserId = null, sendReadReceipt = true } = options;
|
|
283
|
+
const payload = { send_read_receipt: Boolean(sendReadReceipt) };
|
|
284
|
+
if (conversationUid) payload.conversation_uid = conversationUid;
|
|
285
|
+
if (otherUserId) payload.other_user_id = otherUserId;
|
|
286
|
+
return this.client.postApi("markAsRead", payload);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
async getConversations() {
|
|
290
|
+
let token;
|
|
291
|
+
try { token = await this.client.session.getValidToken(); } catch (e) { return []; }
|
|
292
|
+
const myUid = this.client.session.uid;
|
|
293
|
+
if (!token) return [];
|
|
294
|
+
const url = `https://firestore.googleapis.com/v1/projects/locket-4252a/databases/(default)/documents/users/${myUid}/conversations`;
|
|
295
|
+
let data;
|
|
296
|
+
try {
|
|
297
|
+
const res = await fetchWithTimeout(url, { headers: { Authorization: `Bearer ${token}` } }, 30000);
|
|
298
|
+
data = await res.json();
|
|
299
|
+
} catch (e) { return []; }
|
|
300
|
+
|
|
301
|
+
const conversations = [];
|
|
302
|
+
for (const doc of (data.documents || [])) {
|
|
303
|
+
const fields = doc.fields || {};
|
|
304
|
+
const cid = doc.name.split("/").pop();
|
|
305
|
+
const members = ((fields.members && fields.members.arrayValue && fields.members.arrayValue.values) || []).map(v => v.stringValue);
|
|
306
|
+
const otherUid = members.filter(m => m !== myUid)[0] || null;
|
|
307
|
+
const latestMsgField = (fields.latest_message && fields.latest_message.mapValue && fields.latest_message.mapValue.fields) || {};
|
|
308
|
+
const latestBody = (latestMsgField.body && latestMsgField.body.stringValue) || null;
|
|
309
|
+
const latestSender = (latestMsgField.sender && latestMsgField.sender.stringValue) || null;
|
|
310
|
+
const latestTime = (latestMsgField.created_at && latestMsgField.created_at.timestampValue) || null;
|
|
311
|
+
const unreadCount = parseInt((fields.unread_count && fields.unread_count.integerValue) || 0);
|
|
312
|
+
const isRead = (fields.is_read && fields.is_read.booleanValue) !== false;
|
|
313
|
+
const otherReadTime = (fields.other_last_read_at && fields.other_last_read_at.timestampValue) || null;
|
|
314
|
+
conversations.push({
|
|
315
|
+
conversation_id: cid,
|
|
316
|
+
peer_uid: otherUid,
|
|
317
|
+
members,
|
|
318
|
+
unread_count: unreadCount,
|
|
319
|
+
is_read: isRead,
|
|
320
|
+
other_last_read_at: otherReadTime,
|
|
321
|
+
latest_message: { text: latestBody, sender_uid: latestSender, timestamp: latestTime }
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
return conversations;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
async listenRealtime(otherUserId, onMessage, options = {}) {
|
|
328
|
+
let WebSocket;
|
|
329
|
+
try { WebSocket = require("ws"); } catch (e) {
|
|
330
|
+
throw new Error("The 'ws' package is required for real-time streaming. Install it using: npm install ws");
|
|
331
|
+
}
|
|
332
|
+
const { autoReconnect = true, maxReconnects = 10, reconnectDelayMs = 2000 } = options || {};
|
|
333
|
+
|
|
334
|
+
let targetUid = otherUserId;
|
|
335
|
+
if (otherUserId && !/[A-Z]/.test(otherUserId) && otherUserId.length < 28) {
|
|
336
|
+
try {
|
|
337
|
+
const prof = await this.client.user.getProfileByUsername(otherUserId);
|
|
338
|
+
if (prof && prof.uid) targetUid = prof.uid;
|
|
339
|
+
} catch (e) {}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const myUid = this.client.session.uid;
|
|
343
|
+
|
|
344
|
+
const controller = {
|
|
345
|
+
_ws: null,
|
|
346
|
+
_closed: false,
|
|
347
|
+
_attempts: 0,
|
|
348
|
+
get ws() { return this._ws; },
|
|
349
|
+
close() {
|
|
350
|
+
this._closed = true;
|
|
351
|
+
if (this._ws) try { this._ws.close(); } catch (e) {}
|
|
352
|
+
},
|
|
353
|
+
on(event, cb) {
|
|
354
|
+
if (this._ws) this._ws.on(event, cb);
|
|
355
|
+
return this;
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
const connect = async () => {
|
|
360
|
+
if (controller._closed) return;
|
|
361
|
+
const token = await this.client.session.getValidToken();
|
|
362
|
+
const wsUrl = `wss://api.locketcamera.com/wss_v2/chat?otherUserId=${targetUid}&userId=${myUid}`;
|
|
363
|
+
const headers = {
|
|
364
|
+
Authorization: `Bearer ${token}`,
|
|
365
|
+
"User-Agent": this.client.device.userAgent,
|
|
366
|
+
"x-ios-bundle-identifier": this.client.device.bundleId
|
|
367
|
+
};
|
|
368
|
+
const ws = new WebSocket(wsUrl, { headers });
|
|
369
|
+
controller._ws = ws;
|
|
370
|
+
|
|
371
|
+
ws.on("message", (raw) => {
|
|
372
|
+
let data;
|
|
373
|
+
try { data = JSON.parse(raw.toString()); } catch (e) { data = raw.toString(); }
|
|
374
|
+
if (typeof onMessage === "function") {
|
|
375
|
+
const r = onMessage(data);
|
|
376
|
+
if (r && typeof r.then === "function") r.catch(() => {});
|
|
377
|
+
}
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
ws.on("close", () => {
|
|
381
|
+
if (controller._closed || !autoReconnect) return;
|
|
382
|
+
if (controller._attempts >= maxReconnects) return;
|
|
383
|
+
controller._attempts += 1;
|
|
384
|
+
const delay = Math.min(reconnectDelayMs * controller._attempts, 30000);
|
|
385
|
+
setTimeout(() => { connect().catch(() => {}); }, delay);
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
ws.on("error", () => {});
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
await connect();
|
|
392
|
+
return controller;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
module.exports = { ChatModule, ReactionEmoji };
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
const { LocketError } = require("../exceptions");
|
|
2
|
+
const { fetchWithTimeout } = require("../http");
|
|
3
|
+
|
|
4
|
+
class FriendsModule {
|
|
5
|
+
constructor(client) {
|
|
6
|
+
this.client = client;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
async getGroupsAndFriends() {
|
|
10
|
+
const res = await this.client.postApi("getGroupsState", {});
|
|
11
|
+
return (res && res.data) ? res.data : res;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
async getAllFriends() {
|
|
15
|
+
const token = await this.client.session.getValidToken();
|
|
16
|
+
const myUid = this.client.session.uid;
|
|
17
|
+
const url = `https://firestore.googleapis.com/v1/projects/locket-4252a/databases/(default)/documents/users/${myUid}/friends`;
|
|
18
|
+
const req = { headers: { Authorization: `Bearer ${token}` } };
|
|
19
|
+
let friends = [];
|
|
20
|
+
try {
|
|
21
|
+
const res = await fetchWithTimeout(url, { headers: { Authorization: `Bearer ${token}` } }, 30000);
|
|
22
|
+
const data = await res.json();
|
|
23
|
+
const uids = (data.documents || []).map((doc) => doc.name.split("/").pop());
|
|
24
|
+
const profiles = await Promise.all(uids.map(async (fuid) => {
|
|
25
|
+
try { return await this.client.user.getProfile(fuid); }
|
|
26
|
+
catch (e) { return { uid: fuid }; }
|
|
27
|
+
}));
|
|
28
|
+
friends = profiles;
|
|
29
|
+
} catch (e) {}
|
|
30
|
+
return friends;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async getFriendRequests() {
|
|
34
|
+
const token = await this.client.session.getValidToken();
|
|
35
|
+
const myUid = this.client.session.uid;
|
|
36
|
+
const base = `https://firestore.googleapis.com/v1/projects/locket-4252a/databases/(default)/documents/users/${myUid}`;
|
|
37
|
+
const headers = { Authorization: `Bearer ${token}` };
|
|
38
|
+
const res = { incoming: [], outgoing: [] };
|
|
39
|
+
await Promise.all(["incoming_friend_requests", "outgoing_friend_requests"].map(async (reqType) => {
|
|
40
|
+
const key = reqType.includes("incoming") ? "incoming" : "outgoing";
|
|
41
|
+
try {
|
|
42
|
+
const url = `${base}/${reqType}`;
|
|
43
|
+
const r = await fetchWithTimeout(url, { headers }, 30000);
|
|
44
|
+
const data = await r.json();
|
|
45
|
+
const uids = (data.documents || []).map((doc) => doc.name.split("/").pop());
|
|
46
|
+
const profiles = await Promise.all(uids.map(async (fuid) => {
|
|
47
|
+
try { return await this.client.user.getProfile(fuid); }
|
|
48
|
+
catch (e) { return { uid: fuid }; }
|
|
49
|
+
}));
|
|
50
|
+
res[key] = profiles;
|
|
51
|
+
} catch (e) {}
|
|
52
|
+
}));
|
|
53
|
+
return res;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async resolveInviteTokenFromUsername(username) {
|
|
57
|
+
const url = `https://locket.cam/${username}`;
|
|
58
|
+
try {
|
|
59
|
+
const r = await fetchWithTimeout(url, { headers: { "User-Agent": "com.locket.Locket/2.68.0 iPhone/27.0" } }, 30000);
|
|
60
|
+
const html = await r.text();
|
|
61
|
+
let m = html.match(/locket\.camera%2Finvites%2F([a-zA-Z0-9]+)/);
|
|
62
|
+
if (!m) m = html.match(/locket\.camera\/invites\/([a-zA-Z0-9]+)/);
|
|
63
|
+
if (m) return m[1];
|
|
64
|
+
} catch (e) {}
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async fetchUserByInviteToken(inviteToken) {
|
|
69
|
+
const res = await this.client.postApi("fetchUserForInviteToken", { invite_token: inviteToken });
|
|
70
|
+
return (res && res.data) ? res.data : res;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async sendRequest(userUid, source = "inviteCardPopup") {
|
|
74
|
+
const payload = {
|
|
75
|
+
user_uid: userUid,
|
|
76
|
+
source,
|
|
77
|
+
platform: "iOS",
|
|
78
|
+
create_ofr_for_temp_users: false,
|
|
79
|
+
share_history_eligible: true,
|
|
80
|
+
get_reengagement_status: false,
|
|
81
|
+
prompted_reengagement: false,
|
|
82
|
+
rollcall: false,
|
|
83
|
+
invite_variant: { value: "1002", "@type": "type.googleapis.com/google.protobuf.Int64Value" }
|
|
84
|
+
};
|
|
85
|
+
return this.client.postApi("sendFriendRequest", payload);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async sendRequestByUsername(username) {
|
|
89
|
+
const token = await this.resolveInviteTokenFromUsername(username);
|
|
90
|
+
if (token) {
|
|
91
|
+
const userData = await this.fetchUserByInviteToken(token);
|
|
92
|
+
const uid = (userData && userData.user && userData.user.uid) ? userData.user.uid : null;
|
|
93
|
+
if (uid) return this.sendRequest(uid);
|
|
94
|
+
}
|
|
95
|
+
const profile = await this.client.user.getProfileByUsername(username);
|
|
96
|
+
if (profile && profile.uid) return this.sendRequest(profile.uid);
|
|
97
|
+
throw new Error(`User not found for username: ${username}`);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async acceptRequest(userUid) {
|
|
101
|
+
const payload = {
|
|
102
|
+
user_uid: userUid,
|
|
103
|
+
during_signup: false,
|
|
104
|
+
ios_version: `${this.client.device.appVersion}.${this.client.device.buildNumber}`
|
|
105
|
+
};
|
|
106
|
+
const res = await this.client.postApi("acceptFriendRequest", payload);
|
|
107
|
+
return (res && res.data) ? res.data : res;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async _resolveTargetUid(userOrUid) {
|
|
111
|
+
const clean = String(userOrUid).trim().replace(/^@/, "");
|
|
112
|
+
if (clean.length === 28 && /^[a-zA-Z0-9]+$/.test(clean) && !/^[a-zA-Z]+$/.test(clean) && !/^[0-9]+$/.test(clean)) {
|
|
113
|
+
return clean;
|
|
114
|
+
}
|
|
115
|
+
try {
|
|
116
|
+
const profile = await this.client.user.getProfileByUsername(clean);
|
|
117
|
+
if (profile && profile.uid) return profile.uid;
|
|
118
|
+
} catch (e) {}
|
|
119
|
+
return clean;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async remove(userUid) {
|
|
123
|
+
const targetUid = await this._resolveTargetUid(userUid);
|
|
124
|
+
return this.client.postApi("removeFriend", { user_uid: targetUid });
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async block(userUid) {
|
|
128
|
+
const targetUid = await this._resolveTargetUid(userUid);
|
|
129
|
+
return this.client.postApi("blockFriend", { user_uid: targetUid });
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async unblock(userUid) {
|
|
133
|
+
const targetUid = await this._resolveTargetUid(userUid);
|
|
134
|
+
return this.client.postApi("unblockUser", { user_uid: targetUid });
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async suggestFriends(phoneContacts = null) {
|
|
138
|
+
const payload = {
|
|
139
|
+
contacts: phoneContacts || [],
|
|
140
|
+
smart_friend_suggestions: { "@type": "type.googleapis.com/google.protobuf.Int64Value", value: "0" }
|
|
141
|
+
};
|
|
142
|
+
const res = await this.client.postApi("suggestFriends", payload);
|
|
143
|
+
return (res && res.data) ? res.data : res;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
module.exports = { FriendsModule };
|