@dohaidang/locket_mod.js 0.0.0-stage → 0.0.4
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,1114 @@
|
|
|
1
|
+
const fs = require("fs");
|
|
2
|
+
const path = require("path");
|
|
3
|
+
const os = require("os");
|
|
4
|
+
const { randomUUID } = require("crypto");
|
|
5
|
+
const { spawn, spawnSync } = require("child_process");
|
|
6
|
+
const { StorageUploadError, LocketAPIError, AuthenticationError } = require("../exceptions");
|
|
7
|
+
const { fetchWithTimeout } = require("../http");
|
|
8
|
+
|
|
9
|
+
let sharp = null;
|
|
10
|
+
try { sharp = require("sharp"); } catch (e) { sharp = null; }
|
|
11
|
+
|
|
12
|
+
class NoteType {
|
|
13
|
+
static STANDARD = "standard";
|
|
14
|
+
static REVIEW = "review";
|
|
15
|
+
static MUSIC = "music";
|
|
16
|
+
static LOCATION = "location";
|
|
17
|
+
static WEATHER = "weather";
|
|
18
|
+
static TIME = "time";
|
|
19
|
+
static STREAK = "streak";
|
|
20
|
+
static STAR_SIGN = "star_sign";
|
|
21
|
+
static POLL = "poll";
|
|
22
|
+
static LOCKET_COUNT = "locket_count";
|
|
23
|
+
static COLORS = "colors";
|
|
24
|
+
static HALLOWEEN_2026 = "halloween_2026";
|
|
25
|
+
static CHRISTMAS_EVE_2026 = "christmas_eve_2026";
|
|
26
|
+
static CHRISTMAS_DAY_2026 = "christmas_day_2026";
|
|
27
|
+
static NEW_YEARS_EVE_2026 = "new_years_eve_2026";
|
|
28
|
+
static NEW_YEARS_DAY_2027 = "new_years_day_2027";
|
|
29
|
+
static NEW_YEARS_DAY_2027_ALTERNATE = "new_years_day_2027_alternate";
|
|
30
|
+
static AUTUMN_2026 = "autumn_2026";
|
|
31
|
+
static COLOR_PALETTE = "color_palette";
|
|
32
|
+
static PARTY_TIME = "party_time";
|
|
33
|
+
static GOOD_MORNING = "good_morning";
|
|
34
|
+
static GOODNIGHT = "goodnight";
|
|
35
|
+
static OOTD = "ootd";
|
|
36
|
+
static MISS_YOU = "miss_you";
|
|
37
|
+
static TOI_NHO_EM = "toi_nho_em";
|
|
38
|
+
static DOI_ROI = "custom_4281443912454362723";
|
|
39
|
+
static DANG_BAN_TUONG_TU = "custom_4278420056830692855";
|
|
40
|
+
static REP_TIN_NHAN_DI = "custom_-5230082930652109611";
|
|
41
|
+
static MO_HON_NHUNG_TAM_HIEN = "custom_-3194172128167113174";
|
|
42
|
+
static MUON_DUOC_OM = "custom_951140262642706115";
|
|
43
|
+
static HOI_BI_NHO = "custom_-2517074947356721928";
|
|
44
|
+
static DANG_GHEN = "custom_8704346769822013791";
|
|
45
|
+
static NGU_NGON_GIAC_MO_CO_EM = "custom_-6322769402934766020";
|
|
46
|
+
static HAO_HAN = "custom_-7748601173102319221";
|
|
47
|
+
static CAM_LANH = "custom_5086729225261087312";
|
|
48
|
+
static BAT_LUC = "custom_-8827799067762644667";
|
|
49
|
+
static XIN_LUI_DUOC_CHUA = "custom_1207712346050008572";
|
|
50
|
+
static ROT_NUOC_MAT = "custom_7843091339669964287";
|
|
51
|
+
static GUC_NGA = "custom_-6209580156274658388";
|
|
52
|
+
static TIEN_DINH = "custom_2624241615109400076";
|
|
53
|
+
static CHE_MANH = "custom_6333530155972530884";
|
|
54
|
+
static XINH_GAI_AN_PHIM_1 = "custom_5236262895016786086";
|
|
55
|
+
static DI_LAM_VI_DAM_ME = "custom_4629360466318251663";
|
|
56
|
+
static YEUU_EMM = "custom_2356683405459396780";
|
|
57
|
+
static YEUU_ANHH = "custom_-156517413958162274";
|
|
58
|
+
static HOI_CHIEU_TROI_MUA = "custom_-1002616293585878253";
|
|
59
|
+
static CON_VIEN_LA_LAN = "custom_2988924028358029735";
|
|
60
|
+
static AIIII_HOIIII = "custom_-776650182805465343";
|
|
61
|
+
static TAI_ONG_DE_NGOAI_DAU_A = "custom_8807240841082552583";
|
|
62
|
+
static CHAN_BO_MAY_DI = "custom_9142722434980417998";
|
|
63
|
+
static OACH_XA_LACH = "custom_-2275483743616875628";
|
|
64
|
+
static E_HE = "custom_-1964354746873974650";
|
|
65
|
+
static UA_ALO = "custom_-8051687911840908357";
|
|
66
|
+
static MAY_CHU_LA_DU_DU = "custom_5306143805773536410";
|
|
67
|
+
static LANH_THAY_ME = "custom_8500361098265117961";
|
|
68
|
+
static DAY_LA_CAI_VIEC = "custom_9196689374819632769";
|
|
69
|
+
static DEP_TRAI_AN_PHIM_2 = "custom_-1593423561129370554";
|
|
70
|
+
static NHO_ANH_CH = "custom_1826983258186006295";
|
|
71
|
+
static BIEN_OI_HUUUUUUU = "custom_-7090905829866915796";
|
|
72
|
+
static YEU_ME = "custom_5774090202020534389";
|
|
73
|
+
static NHO_NGY = "custom_158060084751342837";
|
|
74
|
+
static OAN_TA_LA_VAN = "custom_-8740976725662466401";
|
|
75
|
+
static KHA_NANG_CAO = "custom_2881592073605293252";
|
|
76
|
+
static O_QUA_KIEU = "custom_530435604131815207";
|
|
77
|
+
static LANH_NHO_AI = "custom_3095077949020722512";
|
|
78
|
+
static DUNG_NHANG_NHIT = "custom_-1835481008846003750";
|
|
79
|
+
static HOM_NAY_TOI_BUON = "custom_2800157096924376465";
|
|
80
|
+
static GAP_NHAU_CAI_NHI = "custom_-1606761404320333220";
|
|
81
|
+
static ANK_IU_EIM = "custom_-985711000650511532";
|
|
82
|
+
static MONG_TON_HOA_SEN_THAY_CANH_NAY = "custom_8417033934333284867";
|
|
83
|
+
static DAM_NHAU_KHONG = "custom_-8088027983880581018";
|
|
84
|
+
static SIEU_CAP_BA_KHI = "custom_2329667605952175965";
|
|
85
|
+
static DU_AN_MA = "custom_-3231089972810420922";
|
|
86
|
+
static DOC_SO_TAI_KHOAN = "custom_5553591653597204903";
|
|
87
|
+
static AI_SO_THI_DI_VE = "custom_-666096677004943582";
|
|
88
|
+
static CON_CAI_NIT = "custom_-3548848387881782452";
|
|
89
|
+
static CANH_BAO_CO_HAT = "custom_1285814533953315227";
|
|
90
|
+
static THAN_CHUA_MA_DON = "custom_-7627856025199367222";
|
|
91
|
+
static AI_MUON = "custom_1443622437168042269";
|
|
92
|
+
static HAY_RA_DE_QUA_A = "custom_2923223443268332123";
|
|
93
|
+
static GIAM_SUC_MANH_CON_TUONG_NAY = "custom_5807806141447560156";
|
|
94
|
+
static MAC_CO_QUA_HAI_OI = "custom_7816289860114210553";
|
|
95
|
+
static MINH_LA_LOP = "custom_-5360614187519837840";
|
|
96
|
+
static DEP_TRAI_CO_GI_SAI = "custom_-6998405490882227027";
|
|
97
|
+
static FEELING_CUTE = "feeling_cute";
|
|
98
|
+
static CU = "cu";
|
|
99
|
+
static WEDDING_TIME = "wedding_time";
|
|
100
|
+
static CAM_THAY_HANH_PHUC = "cam_thay_hanh_phuc";
|
|
101
|
+
static COFFEE_TIME = "coffee_time";
|
|
102
|
+
static SNAKE_VIBES = "snake_vibes";
|
|
103
|
+
static MIXUE_TIME = "mixue_time";
|
|
104
|
+
static LOCKET_TIME = "locket_time";
|
|
105
|
+
static CINEMA_TIME = "cinema_time";
|
|
106
|
+
static DATING_TIME = "dating_time";
|
|
107
|
+
static GRADUATION_DAY = "graduation_day";
|
|
108
|
+
static SHOPPING_TIME = "shopping_time";
|
|
109
|
+
static DINNER_TIME = "dinner_time";
|
|
110
|
+
static CHILLING_TIME = "chilling_time";
|
|
111
|
+
static XIN_VINH_BIET_CU = "xin_vinh_biet_cu";
|
|
112
|
+
static CHAY_NGAY_DI = "chay_ngay_di";
|
|
113
|
+
static CU_TU_TU_KHOAI_SE_NHU = "cu_tu_tu_khoai_se_nhu";
|
|
114
|
+
static KIEM_TRA_NHAN_PHAM = "kiem_tra_nhan_pham";
|
|
115
|
+
static DOC_SO_TAI_KHOAN_2 = "doc_so_tai_khoan";
|
|
116
|
+
static AI_SO_THI_DI_VE_2 = "ai_so_thi_di_ve";
|
|
117
|
+
static CON_CAI_NIT_2 = "con_cai_nit";
|
|
118
|
+
static CANH_BAO_CO_HAT_2 = "canh_bao_co_hat";
|
|
119
|
+
static THAN_CHUA_MA_DON_2 = "than_chua_ma_don";
|
|
120
|
+
static AI_MUON_2 = "ai_muon";
|
|
121
|
+
static HAY_RA_DE_QUA_A_2 = "hay_ra_de_qua_a";
|
|
122
|
+
static GIAM_SUC_MANH_CON_TUONG = "giam_suc_manh_con_tuong";
|
|
123
|
+
static MAC_CO_QUA_HAI_OI_2 = "mac_co_qua_hai_oi";
|
|
124
|
+
static MINH_LA_LOP_2 = "minh_la_lop";
|
|
125
|
+
static DEP_TRAI_CO_GI_SAI_2 = "dep_trai_co_gi_sai";
|
|
126
|
+
static MONG_TON_HOA_SEN = "mong_ton_hoa_sen";
|
|
127
|
+
static DAM_NHAU_KHONG_2 = "dam_nhau_khong";
|
|
128
|
+
static SIEU_CAP_BA_KHI_2 = "sieu_cap_ba_khi";
|
|
129
|
+
static DU_AN_MA_2 = "du_an_ma";
|
|
130
|
+
static HOI_CHIEU_TROI_MUA_2 = "hoi_chieu_troi_mua";
|
|
131
|
+
static TUYET_DOI_KHONG_NGHE = "tuyet_doi_khong_nghe";
|
|
132
|
+
static FLEX_DEN_HOI_THO_CUOI = "flex_den_hoi_tho_cuoi";
|
|
133
|
+
static OVERTHINKING_VAI_CHUONG = "overthinking_vai_chuong";
|
|
134
|
+
static KE_CHUYEN_NGHE_CHOI = "ke_chuyen_nghe_choi";
|
|
135
|
+
static XINH_DEP_TUYET_VOI = "xinh_dep_tuyet_voi";
|
|
136
|
+
static TRAM_CAM_NHE = "tram_cam_nhe";
|
|
137
|
+
static CHUA_DU_WOW = "chua_du_wow";
|
|
138
|
+
static BOC_TRUNG_SIT_RIT = "boc_trung_sit_rit";
|
|
139
|
+
static HEN_LAM_MOI_XUI_DUOC_VAY_A = "hen_lam_moi_xui_duoc_vay_a";
|
|
140
|
+
static RA_DUONG_NE_MOI_ANH = "ra_duong_ne_moi_anh";
|
|
141
|
+
static CUNG_CUNG_DI = "cung_cung_di";
|
|
142
|
+
static TUYET_DOI_DIEN_ANH = "tuyet_doi_dien_anh";
|
|
143
|
+
static DU_BA_KHI_CHUA = "du_ba_khi_chua";
|
|
144
|
+
static UA_ALO_2 = "ua_alo";
|
|
145
|
+
static CAI_GI_VAY_TROI = "cai_gi_vay_troi";
|
|
146
|
+
static NAY_LA_HET_CUU = "nay_la_het_cuu";
|
|
147
|
+
static QUA_LA_DIEN_ANH = "qua_la_dien_anh";
|
|
148
|
+
static CUOI_XIU = "cuoi_xiu";
|
|
149
|
+
static TOANG_THAT_ROI = "toang_that_roi";
|
|
150
|
+
static TOI_ROI_TOI_ROI = "toi_roi_toi_roi";
|
|
151
|
+
static KHONG_THE_TIN_NOI = "khong_the_tin_noi";
|
|
152
|
+
static NGAY_MOI_VUI_VE = "ngay_moi_vui_ve";
|
|
153
|
+
static NGU_NGON = "ngu_ngon";
|
|
154
|
+
static AN_COM_CHUA = "an_com_chua";
|
|
155
|
+
static DI_CHOI_KHONG = "di_choi_khong";
|
|
156
|
+
static TINH_HOA_HOI_TU = "tinh_hoa_hoi_tu";
|
|
157
|
+
static PHU_TINH_KHONG_PHU_BAN = "phu_tinh_khong_phu_ban";
|
|
158
|
+
static NGOAN_XINH_YEU = "ngoan_xinh_yeu";
|
|
159
|
+
static NHIN_LA_BIET_UY_TIN = "nhin_la_biet_uy_tin";
|
|
160
|
+
static LUON_VUI_TUOI = "luon_vui_tuoi";
|
|
161
|
+
static BAT_ON_THAT_SU = "bat_on_that_su";
|
|
162
|
+
static KHONG_CAM_XUC = "khong_cam_xuc";
|
|
163
|
+
static PHU_HUYNH_DUNG_XEM = "phu_huynh_dung_xem";
|
|
164
|
+
static CHECK_VAR = "check_var";
|
|
165
|
+
static QUA_NHIEU_SU_DE_THUONG = "qua_nhieu_su_de_thuong";
|
|
166
|
+
static MAC_BAY_TINH_YEU = "mac_bay_tinh_yeu";
|
|
167
|
+
static SONG_GIO_PHU_DOI_TRAI = "song_gio_phu_doi_trai";
|
|
168
|
+
static DEADLINE_RUOT = "deadline_ruot";
|
|
169
|
+
static TIEN_DAU_MA_TIEU = "tien_dau_ma_tieu";
|
|
170
|
+
static NGHIEN_CUU_KHOA_HOC = "nghien_cuu_khoa_hoc";
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
class MomentsModule {
|
|
174
|
+
static STORAGE_IMG_URL = "https://firebasestorage.googleapis.com/v0/b/locket-img/o";
|
|
175
|
+
static STORAGE_VIDEO_URL = "https://firebasestorage.googleapis.com/v0/b/locket-video/o";
|
|
176
|
+
|
|
177
|
+
constructor(client) {
|
|
178
|
+
this.client = client;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
_getHistoryFile() {
|
|
182
|
+
const uid = (this.client.session && this.client.session.uid) || "default";
|
|
183
|
+
const filename = `my_moments_${uid}.json`;
|
|
184
|
+
const sessionPath = (this.client.session && this.client.session.sessionPath) || "";
|
|
185
|
+
if (sessionPath && path.dirname(sessionPath)) {
|
|
186
|
+
return path.join(path.dirname(sessionPath), filename);
|
|
187
|
+
}
|
|
188
|
+
return filename;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
_loadHistory() {
|
|
192
|
+
const filepath = this._getHistoryFile();
|
|
193
|
+
const uid = (this.client.session && this.client.session.uid) || "default";
|
|
194
|
+
const candidates = [filepath, `my_moments_${uid}.json`, path.join("..", `my_moments_${uid}.json`)];
|
|
195
|
+
for (const p of candidates) {
|
|
196
|
+
if (p && fs.existsSync(p)) {
|
|
197
|
+
try {
|
|
198
|
+
const data = JSON.parse(fs.readFileSync(p, "utf-8"));
|
|
199
|
+
if (Array.isArray(data)) return data;
|
|
200
|
+
} catch (e) {}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return [];
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
_saveHistory(history) {
|
|
207
|
+
const filepath = this._getHistoryFile();
|
|
208
|
+
try { fs.writeFileSync(filepath, JSON.stringify(history, null, 2), "utf-8"); } catch (e) {}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
recordPostedMoment(momentData) {
|
|
212
|
+
if (!momentData || typeof momentData !== "object") return;
|
|
213
|
+
const mid = momentData.canonical_uid || momentData.id;
|
|
214
|
+
if (!mid) return;
|
|
215
|
+
let history = this._loadHistory();
|
|
216
|
+
history = history.filter(m => (m.canonical_uid || m.id) !== mid);
|
|
217
|
+
history.unshift(momentData);
|
|
218
|
+
this._saveHistory(history);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
static _randomId(length = 20) {
|
|
222
|
+
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
|
223
|
+
let out = "";
|
|
224
|
+
for (let i = 0; i < length; i++) out += chars[Math.floor(Math.random() * chars.length)];
|
|
225
|
+
return out;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async _convertToWebp(imageData, quality = 85) {
|
|
229
|
+
if (sharp) {
|
|
230
|
+
try {
|
|
231
|
+
const img = sharp(imageData);
|
|
232
|
+
const meta = await img.metadata();
|
|
233
|
+
const conv = (meta.hasAlpha) ? img.toFormat("webp", { quality }) : img.toFormat("webp", { quality });
|
|
234
|
+
return await conv.toBuffer();
|
|
235
|
+
} catch (e) {}
|
|
236
|
+
}
|
|
237
|
+
return Buffer.from(imageData);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async extractThumbnail(videoInput, timestampSec = 1.0) {
|
|
241
|
+
let ffmpegBin = null;
|
|
242
|
+
try { ffmpegBin = require("imageio-ffmpeg").getFfmpegExe(); } catch (e) {}
|
|
243
|
+
if (!ffmpegBin) ffmpegBin = "ffmpeg";
|
|
244
|
+
|
|
245
|
+
let tempIn = null;
|
|
246
|
+
let tempOut = null;
|
|
247
|
+
try {
|
|
248
|
+
let inPath = videoInput;
|
|
249
|
+
if (typeof videoInput === "string" && (videoInput.startsWith("http://") || videoInput.startsWith("https://"))) {
|
|
250
|
+
const parsed = new URL(videoInput);
|
|
251
|
+
const origin = `${parsed.protocol}//${parsed.host}/`;
|
|
252
|
+
let resp = await fetch(videoInput, { headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36", Accept: "*/*", Referer: origin } });
|
|
253
|
+
if (resp.status !== 200) resp = await fetch(videoInput);
|
|
254
|
+
if (resp.status === 200) {
|
|
255
|
+
const ab = await resp.arrayBuffer();
|
|
256
|
+
const fd = fs.openSync(tempIn = path.join(os.tmpdir(), `vin_${Date.now()}.mp4`), "w");
|
|
257
|
+
fs.writeSync(fd, Buffer.from(ab));
|
|
258
|
+
fs.closeSync(fd);
|
|
259
|
+
inPath = tempIn;
|
|
260
|
+
} else {
|
|
261
|
+
inPath = videoInput;
|
|
262
|
+
}
|
|
263
|
+
} else if (Buffer.isBuffer(videoInput) || videoInput instanceof Uint8Array) {
|
|
264
|
+
tempIn = path.join(os.tmpdir(), `vin_${Date.now()}.mp4`);
|
|
265
|
+
fs.writeFileSync(tempIn, Buffer.from(videoInput));
|
|
266
|
+
inPath = tempIn;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
tempOut = path.join(os.tmpdir(), `vout_${Date.now()}.jpg`);
|
|
270
|
+
const args = [ffmpegBin, "-y", "-ss", String(timestampSec), "-i", inPath, "-vframes", "1", "-q:v", "2", tempOut];
|
|
271
|
+
spawnSync(args[0], args.slice(1), { stdio: "ignore" });
|
|
272
|
+
|
|
273
|
+
if (fs.existsSync(tempOut) && fs.statSync(tempOut).size > 0) {
|
|
274
|
+
const jpgBytes = fs.readFileSync(tempOut);
|
|
275
|
+
return await this._convertToWebp(jpgBytes);
|
|
276
|
+
}
|
|
277
|
+
return Buffer.alloc(0);
|
|
278
|
+
} finally {
|
|
279
|
+
if (tempIn && fs.existsSync(tempIn)) try { fs.unlinkSync(tempIn); } catch (e) {}
|
|
280
|
+
if (tempOut && fs.existsSync(tempOut)) try { fs.unlinkSync(tempOut); } catch (e) {}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async uploadImage(filePathOrBytes, contentType = "image/webp") {
|
|
285
|
+
let rawBytes;
|
|
286
|
+
if (typeof filePathOrBytes === "string") {
|
|
287
|
+
if (filePathOrBytes.startsWith("http://") || filePathOrBytes.startsWith("https://")) {
|
|
288
|
+
const parsedUrl = new URL(filePathOrBytes);
|
|
289
|
+
const domainOrigin = `${parsedUrl.protocol}//${parsedUrl.host}/`;
|
|
290
|
+
let resp = await fetch(filePathOrBytes, { headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36", Accept: "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.9", Referer: domainOrigin } });
|
|
291
|
+
if (resp.status !== 200) resp = await fetch(filePathOrBytes);
|
|
292
|
+
if (resp.status !== 200) throw new StorageUploadError(`Failed to download image from URL (${resp.status}): ${filePathOrBytes}`);
|
|
293
|
+
rawBytes = Buffer.from(await resp.arrayBuffer());
|
|
294
|
+
} else {
|
|
295
|
+
rawBytes = fs.readFileSync(filePathOrBytes);
|
|
296
|
+
}
|
|
297
|
+
} else {
|
|
298
|
+
rawBytes = Buffer.from(filePathOrBytes);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const webpBytes = await this._convertToWebp(rawBytes);
|
|
302
|
+
const token = randomUUID();
|
|
303
|
+
const filename = `${MomentsModule._randomId(20)}.webp`;
|
|
304
|
+
const userUid = this.client.session.uid;
|
|
305
|
+
const idToken = await this.client.session.getValidToken();
|
|
306
|
+
const objectPath = `users/${userUid}/moments/thumbnails/${filename}`;
|
|
307
|
+
const encodedName = encodeURIComponent(objectPath);
|
|
308
|
+
const initUrl = `${MomentsModule.STORAGE_IMG_URL}/${encodedName}?uploadType=resumable&name=${encodedName}`;
|
|
309
|
+
const metadata = {
|
|
310
|
+
bucket: "",
|
|
311
|
+
contentType,
|
|
312
|
+
name: objectPath,
|
|
313
|
+
metadata: { visibility: "private", creator: userUid },
|
|
314
|
+
cacheControl: "public, max-age=604800"
|
|
315
|
+
};
|
|
316
|
+
const headers = {
|
|
317
|
+
"Content-Type": "application/json; charset=UTF-8",
|
|
318
|
+
Authorization: `Firebase ${idToken}`,
|
|
319
|
+
"x-goog-upload-protocol": "resumable",
|
|
320
|
+
"x-goog-upload-command": "start",
|
|
321
|
+
"x-goog-upload-content-type": contentType,
|
|
322
|
+
"x-goog-upload-content-length": String(webpBytes.length),
|
|
323
|
+
"x-firebase-storage-version": "ios/12.12.1",
|
|
324
|
+
"x-firebase-gmpid": this.client.session.constructor.FIREBASE_APP_ID,
|
|
325
|
+
"User-Agent": `${this.client.device.userAgent} (GTMSUF/1)`
|
|
326
|
+
};
|
|
327
|
+
const initRes = await fetch(initUrl, { method: "POST", headers, body: JSON.stringify(metadata) });
|
|
328
|
+
if (initRes.status !== 200) throw new StorageUploadError(`Image upload initialization failed (${initRes.status}): ${await initRes.text()}`);
|
|
329
|
+
const uploadUrl = initRes.headers.get("x-goog-upload-url");
|
|
330
|
+
if (!uploadUrl) throw new StorageUploadError("Missing upload URL from Firebase Storage");
|
|
331
|
+
|
|
332
|
+
const uploadHeaders = {
|
|
333
|
+
"Content-Type": "application/octet-stream",
|
|
334
|
+
"x-goog-upload-protocol": "resumable",
|
|
335
|
+
"x-goog-upload-command": "upload, finalize",
|
|
336
|
+
"x-goog-upload-offset": "0",
|
|
337
|
+
"x-goog-upload-content-length": String(webpBytes.length)
|
|
338
|
+
};
|
|
339
|
+
const uploadRes = await fetch(uploadUrl, { method: "PUT", headers: uploadHeaders, body: webpBytes });
|
|
340
|
+
if (uploadRes.status !== 200) throw new StorageUploadError(`Image upload transfer failed (${uploadRes.status}): ${await uploadRes.text()}`);
|
|
341
|
+
|
|
342
|
+
let downloadToken = token;
|
|
343
|
+
try {
|
|
344
|
+
const rj = await uploadRes.json();
|
|
345
|
+
if (rj.downloadTokens) downloadToken = rj.downloadTokens.split(",")[0];
|
|
346
|
+
} catch (e) {}
|
|
347
|
+
return `${MomentsModule.STORAGE_IMG_URL}/${encodedName}?alt=media&token=${downloadToken}`;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
async optimizeVideo(videoInput, options = {}) {
|
|
351
|
+
const { targetSizeBytes = 5650000, maxDimension = 1080, preserveResolution = true, priority = "balanced", progressCallback = null } = options;
|
|
352
|
+
|
|
353
|
+
let ffmpegBin = null;
|
|
354
|
+
try { ffmpegBin = require("imageio-ffmpeg").getFfmpegExe(); } catch (e) {}
|
|
355
|
+
if (!ffmpegBin) ffmpegBin = "ffmpeg";
|
|
356
|
+
|
|
357
|
+
let tempIn = null;
|
|
358
|
+
let inPath = videoInput;
|
|
359
|
+
if (Buffer.isBuffer(videoInput) || videoInput instanceof Uint8Array) {
|
|
360
|
+
tempIn = path.join(os.tmpdir(), `vin_${Date.now()}.mp4`);
|
|
361
|
+
fs.writeFileSync(tempIn, Buffer.from(videoInput));
|
|
362
|
+
inPath = tempIn;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
try {
|
|
366
|
+
const probe = spawnSync(ffmpegBin, ["-i", inPath], { encoding: "utf-8" });
|
|
367
|
+
const errStr = (probe.stderr || "") + (probe.stdout || "");
|
|
368
|
+
const m = errStr.match(/Duration:\s*(\d+):(\d+):(\d+\.\d+)/);
|
|
369
|
+
let duration = 10.0;
|
|
370
|
+
if (m) {
|
|
371
|
+
const h = parseFloat(m[1]); const mins = parseFloat(m[2]); const s = parseFloat(m[3]);
|
|
372
|
+
duration = h * 3600 + mins * 60 + s;
|
|
373
|
+
duration = Math.max(1.0, duration);
|
|
374
|
+
}
|
|
375
|
+
const hasAudio = errStr.includes("Audio:");
|
|
376
|
+
|
|
377
|
+
const totalTargetBits = targetSizeBytes * 8;
|
|
378
|
+
const totalBitrateKbps = (totalTargetBits / duration) / 1000;
|
|
379
|
+
|
|
380
|
+
const normP = (priority || "balanced").toLowerCase();
|
|
381
|
+
let audioKbps = 0;
|
|
382
|
+
if (hasAudio) {
|
|
383
|
+
if (["audio", "music", "tieng", "sound"].includes(normP)) {
|
|
384
|
+
if (duration > 300) audioKbps = 64;
|
|
385
|
+
else if (duration > 120) audioKbps = 96;
|
|
386
|
+
else if (duration > 45) audioKbps = 128;
|
|
387
|
+
else audioKbps = 160;
|
|
388
|
+
} else if (["video", "resolution", "hinh_anh"].includes(normP)) {
|
|
389
|
+
if (duration > 300) audioKbps = 24;
|
|
390
|
+
else if (duration > 120) audioKbps = 32;
|
|
391
|
+
else if (duration > 45) audioKbps = 48;
|
|
392
|
+
else audioKbps = 64;
|
|
393
|
+
} else {
|
|
394
|
+
if (duration > 300) audioKbps = 32;
|
|
395
|
+
else if (duration > 120) audioKbps = 64;
|
|
396
|
+
else if (duration > 45) audioKbps = 96;
|
|
397
|
+
else audioKbps = 128;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
let fpsTarget = null;
|
|
402
|
+
let muxOverhead = 0.94;
|
|
403
|
+
if (duration > 300) { fpsTarget = 24; muxOverhead = 0.88; }
|
|
404
|
+
else if (duration > 120) { fpsTarget = 30; muxOverhead = 0.91; }
|
|
405
|
+
const gopSize = (fpsTarget || 30) * 2;
|
|
406
|
+
|
|
407
|
+
const netBitrateKbps = totalBitrateKbps * muxOverhead;
|
|
408
|
+
let videoKbps = Math.round(netBitrateKbps - audioKbps);
|
|
409
|
+
videoKbps = Math.max(35, Math.min(videoKbps, 4000));
|
|
410
|
+
|
|
411
|
+
const tempOut = path.join(os.tmpdir(), `vout_${Date.now()}.mp4`);
|
|
412
|
+
fs.closeSync(fs.openSync(tempOut, "w"));
|
|
413
|
+
|
|
414
|
+
let useHevc = false;
|
|
415
|
+
if (preserveResolution) {
|
|
416
|
+
const chk = spawnSync(ffmpegBin, ["-encoders"], { encoding: "utf-8" });
|
|
417
|
+
if ((chk.stdout || "").includes("libx265")) useHevc = true;
|
|
418
|
+
}
|
|
419
|
+
const encPreset = duration > 180 ? "veryfast" : "fast";
|
|
420
|
+
|
|
421
|
+
let cmd = [ffmpegBin, "-y", "-i", inPath];
|
|
422
|
+
if (useHevc) {
|
|
423
|
+
const scaleFilter = "scale=trunc(iw/2)*2:trunc(ih/2)*2";
|
|
424
|
+
cmd = cmd.concat(["-c:v", "libx265", "-tag:v", "hvc1", "-pix_fmt", "yuv420p", "-preset", encPreset, "-b:v", `${videoKbps}k`, "-maxrate", `${videoKbps}k`, "-bufsize", `${Math.round(videoKbps * 1.2)}k`, "-g", String(gopSize), "-keyint_min", String(Math.floor(gopSize / 2)), "-x265-params", "no-open-gop=1:repeat-headers=1", "-vf", scaleFilter, "-movflags", "+faststart"]);
|
|
425
|
+
if (fpsTarget) cmd = cmd.concat(["-r", String(fpsTarget)]);
|
|
426
|
+
} else {
|
|
427
|
+
let scaleFilter;
|
|
428
|
+
if (preserveResolution) scaleFilter = "scale=trunc(iw/2)*2:trunc(ih/2)*2";
|
|
429
|
+
else {
|
|
430
|
+
const scaleLimit = duration > 45 ? 720 : maxDimension;
|
|
431
|
+
scaleFilter = `scale=w='min(${scaleLimit},iw)':h='min(${scaleLimit},ih)':force_original_aspect_ratio=decrease,scale=trunc(iw/2)*2:trunc(ih/2)*2`;
|
|
432
|
+
}
|
|
433
|
+
cmd = cmd.concat(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "fast", "-b:v", `${videoKbps}k`, "-maxrate", `${Math.round(videoKbps * 1.15)}k`, "-bufsize", `${Math.round(videoKbps * 1.8)}k`, "-g", String(gopSize), "-keyint_min", String(Math.floor(gopSize / 2)), "-vf", scaleFilter, "-movflags", "+faststart"]);
|
|
434
|
+
if (fpsTarget) cmd = cmd.concat(["-r", String(fpsTarget)]);
|
|
435
|
+
}
|
|
436
|
+
if (hasAudio) cmd = cmd.concat(["-c:a", "aac", "-b:a", `${audioKbps}k`]);
|
|
437
|
+
else cmd = cmd.concat(["-an"]);
|
|
438
|
+
cmd = cmd.concat([tempOut]);
|
|
439
|
+
|
|
440
|
+
const proc = spawn(cmd[0], cmd.slice(1), { stdio: ["ignore", "ignore", "pipe"] });
|
|
441
|
+
let stderrBuf = "";
|
|
442
|
+
const timePattern = /time=(\d+):(\d+):(\d+\.\d+)/;
|
|
443
|
+
let lastPct = -1;
|
|
444
|
+
proc.stderr.on("data", (chunk) => {
|
|
445
|
+
stderrBuf += chunk.toString();
|
|
446
|
+
const lines = stderrBuf.split(/\r?\n/);
|
|
447
|
+
stderrBuf = lines.pop();
|
|
448
|
+
for (const line of lines) {
|
|
449
|
+
const match = timePattern.exec(line);
|
|
450
|
+
if (match) {
|
|
451
|
+
const curSec = parseFloat(match[1]) * 3600 + parseFloat(match[2]) * 60 + parseFloat(match[3]);
|
|
452
|
+
const pct = Math.min(99, Math.floor((curSec / duration) * 100));
|
|
453
|
+
if (pct !== lastPct) {
|
|
454
|
+
lastPct = pct;
|
|
455
|
+
if (progressCallback) try { progressCallback(pct, `Nén video HEVC (${pct}%)...`); } catch (e) {}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
});
|
|
460
|
+
await new Promise((resolve, reject) => {
|
|
461
|
+
proc.on("close", (code) => {
|
|
462
|
+
if (code !== 0) reject(new StorageUploadError("Video compression failed during encoding."));
|
|
463
|
+
else resolve();
|
|
464
|
+
});
|
|
465
|
+
proc.on("error", reject);
|
|
466
|
+
});
|
|
467
|
+
if (progressCallback) try { progressCallback(100, "Nén video hoàn tất 100%!"); } catch (e) {}
|
|
468
|
+
|
|
469
|
+
const outBytes = fs.readFileSync(tempOut);
|
|
470
|
+
try { fs.unlinkSync(tempOut); } catch (e) {}
|
|
471
|
+
return outBytes;
|
|
472
|
+
} finally {
|
|
473
|
+
if (tempIn && fs.existsSync(tempIn)) try { fs.unlinkSync(tempIn); } catch (e) {}
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
async uploadVideo(videoPathOrBytes, options = {}) {
|
|
478
|
+
const { contentType = "video/mp4", autoCompress = true, priority = "balanced", progressCallback = null } = options;
|
|
479
|
+
let videoBytes;
|
|
480
|
+
let videoInput;
|
|
481
|
+
if (typeof videoPathOrBytes === "string") {
|
|
482
|
+
if (videoPathOrBytes.startsWith("http://") || videoPathOrBytes.startsWith("https://")) {
|
|
483
|
+
const parsedVurl = new URL(videoPathOrBytes);
|
|
484
|
+
const vOrigin = `${parsedVurl.protocol}//${parsedVurl.host}/`;
|
|
485
|
+
let resp = await fetch(videoPathOrBytes, { headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36", Accept: "*/*", Referer: vOrigin } });
|
|
486
|
+
if (resp.status !== 200) resp = await fetch(videoPathOrBytes);
|
|
487
|
+
if (resp.status !== 200) throw new StorageUploadError(`Failed to download video from URL (${resp.status}): ${videoPathOrBytes}`);
|
|
488
|
+
videoBytes = Buffer.from(await resp.arrayBuffer());
|
|
489
|
+
videoInput = videoBytes;
|
|
490
|
+
} else {
|
|
491
|
+
videoBytes = fs.readFileSync(videoPathOrBytes);
|
|
492
|
+
videoInput = videoPathOrBytes;
|
|
493
|
+
}
|
|
494
|
+
} else {
|
|
495
|
+
videoBytes = Buffer.from(videoPathOrBytes);
|
|
496
|
+
videoInput = videoBytes;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
if (videoBytes.length >= 6291456) {
|
|
500
|
+
if (autoCompress) {
|
|
501
|
+
videoBytes = await this.optimizeVideo(videoInput, { priority, progressCallback });
|
|
502
|
+
} else {
|
|
503
|
+
throw new StorageUploadError(`Video size (${videoBytes.length} bytes / ${(videoBytes.length / 1024 / 1024).toFixed(2)} MB) exceeds Locket's strict limit of 6 MB (6,291,455 bytes). Please compress before uploading.`);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
const token = randomUUID();
|
|
508
|
+
const filename = `${MomentsModule._randomId(20)}.mp4`;
|
|
509
|
+
const userUid = this.client.session.uid;
|
|
510
|
+
const idToken = await this.client.session.getValidToken();
|
|
511
|
+
const objectPath = `users/${userUid}/moments/videos/${filename}`;
|
|
512
|
+
const encodedName = encodeURIComponent(objectPath);
|
|
513
|
+
const initUrl = `${MomentsModule.STORAGE_VIDEO_URL}/${encodedName}?uploadType=resumable&name=${encodedName}`;
|
|
514
|
+
const metadata = {
|
|
515
|
+
bucket: "",
|
|
516
|
+
contentType,
|
|
517
|
+
name: objectPath,
|
|
518
|
+
metadata: { visibility: "private", creator: userUid },
|
|
519
|
+
cacheControl: "public, max-age=604800"
|
|
520
|
+
};
|
|
521
|
+
const headers = {
|
|
522
|
+
"Content-Type": "application/json; charset=UTF-8",
|
|
523
|
+
Authorization: `Firebase ${idToken}`,
|
|
524
|
+
"x-goog-upload-protocol": "resumable",
|
|
525
|
+
"x-goog-upload-command": "start",
|
|
526
|
+
"x-goog-upload-content-type": contentType,
|
|
527
|
+
"x-goog-upload-content-length": String(videoBytes.length),
|
|
528
|
+
"x-firebase-storage-version": "ios/12.12.1",
|
|
529
|
+
"x-firebase-gmpid": this.client.session.constructor.FIREBASE_APP_ID,
|
|
530
|
+
"User-Agent": `${this.client.device.userAgent} (GTMSUF/1)`
|
|
531
|
+
};
|
|
532
|
+
const initRes = await fetch(initUrl, { method: "POST", headers, body: JSON.stringify(metadata) });
|
|
533
|
+
if (initRes.status !== 200) throw new StorageUploadError(`Video upload initialization failed (${initRes.status}): ${await initRes.text()}`);
|
|
534
|
+
const uploadUrl = initRes.headers.get("x-goog-upload-url");
|
|
535
|
+
if (!uploadUrl) throw new StorageUploadError("Missing upload URL from Firebase Storage");
|
|
536
|
+
|
|
537
|
+
const uploadHeaders = {
|
|
538
|
+
"Content-Type": "application/octet-stream",
|
|
539
|
+
"x-goog-upload-protocol": "resumable",
|
|
540
|
+
"x-goog-upload-command": "upload, finalize",
|
|
541
|
+
"x-goog-upload-offset": "0",
|
|
542
|
+
"x-goog-upload-content-length": String(videoBytes.length)
|
|
543
|
+
};
|
|
544
|
+
const uploadRes = await fetch(uploadUrl, { method: "PUT", headers: uploadHeaders, body: videoBytes });
|
|
545
|
+
if (uploadRes.status !== 200) throw new StorageUploadError(`Video data upload failed (${uploadRes.status}): ${await uploadRes.text()}`);
|
|
546
|
+
|
|
547
|
+
let downloadToken = token;
|
|
548
|
+
try {
|
|
549
|
+
const rj = await uploadRes.json();
|
|
550
|
+
if (rj.downloadTokens) downloadToken = rj.downloadTokens.split(",")[0];
|
|
551
|
+
} catch (e) {}
|
|
552
|
+
return `${MomentsModule.STORAGE_VIDEO_URL}/${encodedName}?alt=media&token=${downloadToken}`;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
buildOverlay(options = {}) {
|
|
556
|
+
const { text = "", noteType = NoteType.STANDARD, icon = null, colors = null, textColor = null } = options;
|
|
557
|
+
let presetInfo = null;
|
|
558
|
+
const presetFile = path.join(__dirname, "..", "..", "caption_presets.json");
|
|
559
|
+
const cleanKey = noteType.replace("caption:", "");
|
|
560
|
+
if (fs.existsSync(presetFile)) {
|
|
561
|
+
try {
|
|
562
|
+
const presets = JSON.parse(fs.readFileSync(presetFile, "utf-8"));
|
|
563
|
+
presetInfo = presets[cleanKey] || null;
|
|
564
|
+
} catch (e) {}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
let finalText = text;
|
|
568
|
+
let finalType = noteType;
|
|
569
|
+
let finalColors = colors !== null ? colors : [];
|
|
570
|
+
let finalTextColor = textColor || "#FFFFFFE6";
|
|
571
|
+
let finalIcon = icon;
|
|
572
|
+
|
|
573
|
+
if (presetInfo) {
|
|
574
|
+
if (!finalText) finalText = presetInfo.text || "";
|
|
575
|
+
finalType = presetInfo.type || "static_content";
|
|
576
|
+
if (colors === null) finalColors = presetInfo.colors || [];
|
|
577
|
+
if (!textColor && presetInfo.text_color) finalTextColor = presetInfo.text_color;
|
|
578
|
+
if (!finalIcon && presetInfo.icon) finalIcon = presetInfo.icon;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
let targetOverlayId;
|
|
582
|
+
let dataType;
|
|
583
|
+
if (noteType === NoteType.STANDARD) {
|
|
584
|
+
targetOverlayId = "caption:standard";
|
|
585
|
+
dataType = "standard";
|
|
586
|
+
} else if (presetInfo && presetInfo.overlay_id) {
|
|
587
|
+
targetOverlayId = presetInfo.overlay_id;
|
|
588
|
+
dataType = presetInfo.type || "static_content";
|
|
589
|
+
} else if (noteType.startsWith("caption:")) {
|
|
590
|
+
targetOverlayId = noteType;
|
|
591
|
+
dataType = finalType.includes("static_content") ? "static_content" : noteType.split(":").pop();
|
|
592
|
+
} else {
|
|
593
|
+
targetOverlayId = `caption:${noteType}`;
|
|
594
|
+
dataType = noteType;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
const maxLinesVal = (presetInfo || ["static_content", "streak", "time", "review"].includes(dataType)) ? "1" : "4";
|
|
598
|
+
const overlayData = {
|
|
599
|
+
text: finalText,
|
|
600
|
+
type: dataType,
|
|
601
|
+
text_color: finalTextColor,
|
|
602
|
+
max_lines: { value: maxLinesVal, "@type": "type.googleapis.com/google.protobuf.Int64Value" },
|
|
603
|
+
background: { material_blur: finalColors.length ? "regular" : "ultra_thin", colors: finalColors }
|
|
604
|
+
};
|
|
605
|
+
if (finalIcon) overlayData.icon = { data: finalIcon, type: "emoji" };
|
|
606
|
+
|
|
607
|
+
return {
|
|
608
|
+
overlay_type: "caption",
|
|
609
|
+
overlay_id: targetOverlayId,
|
|
610
|
+
alt_text: finalIcon ? `${finalIcon} ${finalText}` : finalText,
|
|
611
|
+
data: overlayData
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
async post(options = {}) {
|
|
616
|
+
const {
|
|
617
|
+
image = null,
|
|
618
|
+
caption = "",
|
|
619
|
+
video = null,
|
|
620
|
+
noteType = NoteType.STANDARD,
|
|
621
|
+
icon = null,
|
|
622
|
+
colors = null,
|
|
623
|
+
textColor = null,
|
|
624
|
+
isPrivate = false,
|
|
625
|
+
recipients = null,
|
|
626
|
+
autoCompress = true,
|
|
627
|
+
priority = "balanced",
|
|
628
|
+
progressCallback = null
|
|
629
|
+
} = options;
|
|
630
|
+
|
|
631
|
+
let img = image;
|
|
632
|
+
if (video && !image) {
|
|
633
|
+
img = await this.extractThumbnail(video);
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
let thumbUrl = "";
|
|
637
|
+
if (typeof img === "string" && (img.startsWith("http://") || img.startsWith("https://"))) {
|
|
638
|
+
if (img.includes("firebasestorage.googleapis.com") && img.includes("alt=media")) {
|
|
639
|
+
thumbUrl = img;
|
|
640
|
+
} else {
|
|
641
|
+
thumbUrl = await this.uploadImage(img);
|
|
642
|
+
}
|
|
643
|
+
} else if (img) {
|
|
644
|
+
thumbUrl = await this.uploadImage(img);
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
let videoUrl = null;
|
|
648
|
+
if (video) {
|
|
649
|
+
if (typeof video === "string" && (video.startsWith("http://") || video.startsWith("https://"))) {
|
|
650
|
+
if (video.includes("firebasestorage.googleapis.com") && video.includes("alt=media")) {
|
|
651
|
+
videoUrl = video;
|
|
652
|
+
} else {
|
|
653
|
+
videoUrl = await this.uploadVideo(video, { autoCompress, priority, progressCallback });
|
|
654
|
+
}
|
|
655
|
+
} else {
|
|
656
|
+
videoUrl = await this.uploadVideo(video, { autoCompress, priority, progressCallback });
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
const overlays = [];
|
|
661
|
+
let cap = caption;
|
|
662
|
+
if (caption || noteType !== NoteType.STANDARD || colors || icon) {
|
|
663
|
+
const ov = this.buildOverlay({ text: caption, noteType, icon, colors, textColor });
|
|
664
|
+
overlays.push(ov);
|
|
665
|
+
if (!caption) cap = ov.alt_text || "";
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
const payload = {
|
|
669
|
+
thumbnail_url: thumbUrl,
|
|
670
|
+
overlays,
|
|
671
|
+
sent_to_self_only: isPrivate,
|
|
672
|
+
sent_to_all: !isPrivate && !recipients,
|
|
673
|
+
recipients: recipients || [],
|
|
674
|
+
md5: `${randomUUID().replace(/-/g, "")}_${Math.floor(Date.now() / 1000)}`
|
|
675
|
+
};
|
|
676
|
+
if (cap && !overlays.length) payload.caption = cap;
|
|
677
|
+
if (videoUrl) payload.video_url = videoUrl;
|
|
678
|
+
|
|
679
|
+
const res = await this.client.postApi("postMomentV2", payload);
|
|
680
|
+
if (res && (res.status !== undefined && res.status !== 200 && res.status !== null) || (res && res.errors)) {
|
|
681
|
+
const errMsg = (res && (res.errors || res.error)) || `Locket API error ${res && res.status}`;
|
|
682
|
+
throw new LocketAPIError(`Post moment failed: ${errMsg}`);
|
|
683
|
+
}
|
|
684
|
+
const dataRes = (res && res.data) ? res.data : res;
|
|
685
|
+
if (dataRes && typeof dataRes === "object") {
|
|
686
|
+
if (!dataRes.id && dataRes.canonical_uid) dataRes.id = dataRes.canonical_uid;
|
|
687
|
+
const momentEntry = {
|
|
688
|
+
moment_uid: dataRes.canonical_uid || dataRes.id,
|
|
689
|
+
canonical_uid: dataRes.canonical_uid || dataRes.id,
|
|
690
|
+
thumbnail_url: thumbUrl,
|
|
691
|
+
video_url: videoUrl,
|
|
692
|
+
caption: cap || "",
|
|
693
|
+
created_at: new Date().toISOString()
|
|
694
|
+
};
|
|
695
|
+
this.recordPostedMoment(momentEntry);
|
|
696
|
+
}
|
|
697
|
+
return dataRes;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
async getLatest() {
|
|
701
|
+
const res = await this.client.postApi("getLatestMomentV2", { should_count_missed_moments: true });
|
|
702
|
+
return (res && res.data) ? res.data : [];
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
async getSharedMomentsByUsername(username, limit = null) {
|
|
706
|
+
const profile = await this.client.user.getProfileByUsername(username);
|
|
707
|
+
const targetUid = profile ? profile.uid : null;
|
|
708
|
+
if (!targetUid) return [];
|
|
709
|
+
return this.getSharedMomentsByUser(targetUid, limit);
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
async getSharedMomentsByUser(userUid, limit = null) {
|
|
713
|
+
const moments = [];
|
|
714
|
+
const seenUids = new Set();
|
|
715
|
+
let currentSync = null;
|
|
716
|
+
try {
|
|
717
|
+
const allFriends = await this.client.friends.getAllFriends();
|
|
718
|
+
const friendUids = allFriends.map(f => f.uid).filter(Boolean);
|
|
719
|
+
const otherFriends = friendUids.filter(fuid => fuid !== userUid);
|
|
720
|
+
|
|
721
|
+
while (true) {
|
|
722
|
+
const payload = {
|
|
723
|
+
should_count_missed_moments: true,
|
|
724
|
+
include_group_moments: true,
|
|
725
|
+
excluded_users: otherFriends
|
|
726
|
+
};
|
|
727
|
+
if (currentSync) payload.sync_token = currentSync;
|
|
728
|
+
const feedRes = await this.client.postApi("getLatestMomentV2", payload);
|
|
729
|
+
const data = (feedRes && feedRes.data) ? feedRes.data : [];
|
|
730
|
+
if (!data || !data.length) break;
|
|
731
|
+
|
|
732
|
+
let newCount = 0;
|
|
733
|
+
for (const m of data) {
|
|
734
|
+
const mid = m.canonical_uid;
|
|
735
|
+
if (mid && !seenUids.has(mid)) {
|
|
736
|
+
seenUids.add(mid);
|
|
737
|
+
newCount++;
|
|
738
|
+
currentSync = mid;
|
|
739
|
+
if (m.user === userUid) {
|
|
740
|
+
let createdTs = "";
|
|
741
|
+
const dateField = m.date;
|
|
742
|
+
if (dateField && typeof dateField === "object" && dateField._seconds) createdTs = String(dateField._seconds);
|
|
743
|
+
moments.push({
|
|
744
|
+
moment_uid: mid,
|
|
745
|
+
user_uid: userUid,
|
|
746
|
+
thumbnail_url: m.thumbnail_url,
|
|
747
|
+
image_url: m.image_url || m.thumbnail_url,
|
|
748
|
+
video_url: m.video_url,
|
|
749
|
+
caption: m.caption || "",
|
|
750
|
+
overlays: m.overlays || [],
|
|
751
|
+
created_at: createdTs,
|
|
752
|
+
date: dateField,
|
|
753
|
+
md5: m.md5,
|
|
754
|
+
source: "feed"
|
|
755
|
+
});
|
|
756
|
+
if (limit && moments.length >= limit) return moments.slice(0, limit);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
if (newCount === 0 || (feedRes && feedRes.status === 304)) break;
|
|
761
|
+
}
|
|
762
|
+
} catch (e) {}
|
|
763
|
+
return moments;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
async getFilters() {
|
|
767
|
+
const res = await this.client.postApi("getFilters", {});
|
|
768
|
+
return (res && res.data) ? res.data : res;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
async markAsViewed(momentUid) {
|
|
772
|
+
return this.client.postApi("markMomentAsViewed", { moment_uid: momentUid });
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
async react(momentUid, reaction = "❤️", fromMemory = false) {
|
|
776
|
+
const payload = {
|
|
777
|
+
moment_uid: momentUid,
|
|
778
|
+
reaction,
|
|
779
|
+
from_memory: fromMemory,
|
|
780
|
+
intensity: { "@type": "type.googleapis.com/google.protobuf.Int64Value", value: "0" }
|
|
781
|
+
};
|
|
782
|
+
return this.client.postApi("reactToMoment", payload);
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
async getRollcallPosts(weekOfYear = null, year = null, source = "banner") {
|
|
786
|
+
const now = new Date();
|
|
787
|
+
const iso = this._isoWeek(now);
|
|
788
|
+
if (weekOfYear === null) weekOfYear = iso.week;
|
|
789
|
+
if (year === null) year = iso.year;
|
|
790
|
+
const payload = {
|
|
791
|
+
week_of_year: { "@type": "type.googleapis.com/google.protobuf.Int64Value", value: String(weekOfYear) },
|
|
792
|
+
year: { "@type": "type.googleapis.com/google.protobuf.Int64Value", value: String(year) },
|
|
793
|
+
source
|
|
794
|
+
};
|
|
795
|
+
const res = await this.client.postApi("getRollcallPosts", payload);
|
|
796
|
+
return (res && res.data) ? res.data : res;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
_isoWeek(d) {
|
|
800
|
+
const date = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
|
|
801
|
+
const dayNum = date.getUTCDay() || 7;
|
|
802
|
+
date.setUTCDate(date.getUTCDate() + 4 - dayNum);
|
|
803
|
+
const yearStart = new Date(Date.UTC(date.getUTCFullYear(), 0, 1));
|
|
804
|
+
const week = Math.ceil((((date - yearStart) / 86400000) + 1) / 7);
|
|
805
|
+
return { year: date.getUTCFullYear(), week };
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
async getAllMyMoments(options = {}) {
|
|
809
|
+
const { limit = null, startDate = null, endDate = null } = options;
|
|
810
|
+
const parseTs = (tsStr) => {
|
|
811
|
+
if (!tsStr) return null;
|
|
812
|
+
try {
|
|
813
|
+
let s = String(tsStr).replace("Z", "+00:00");
|
|
814
|
+
if (s.length === 10) s += "T00:00:00+00:00";
|
|
815
|
+
return new Date(s);
|
|
816
|
+
} catch (e) { return null; }
|
|
817
|
+
};
|
|
818
|
+
let dtStart = parseTs(startDate);
|
|
819
|
+
let dtEnd = parseTs(endDate);
|
|
820
|
+
if (dtEnd && String(endDate).trim().length === 10) {
|
|
821
|
+
dtEnd = new Date(dtEnd); dtEnd.setHours(23, 59, 59, 999);
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
const token = await this.client.session.getValidToken();
|
|
825
|
+
const myUid = this.client.session.uid;
|
|
826
|
+
const moments = [];
|
|
827
|
+
const seenMids = new Set();
|
|
828
|
+
|
|
829
|
+
const postedHistory = this._loadHistory();
|
|
830
|
+
const postedCandidates = [];
|
|
831
|
+
for (const p of postedHistory) {
|
|
832
|
+
const mid = p.moment_uid || p.canonical_uid || p.id;
|
|
833
|
+
if (!mid || seenMids.has(mid)) continue;
|
|
834
|
+
const createdRaw = p.created_at || "";
|
|
835
|
+
if (dtStart || dtEnd) {
|
|
836
|
+
const docDt = parseTs(createdRaw);
|
|
837
|
+
if (docDt) {
|
|
838
|
+
if (dtStart && docDt < dtStart) continue;
|
|
839
|
+
if (dtEnd && docDt > dtEnd) continue;
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
postedCandidates.push({ p, mid, createdRaw });
|
|
843
|
+
}
|
|
844
|
+
const postedViews = await Promise.all(postedCandidates.map((c) => this.getViews(c.mid)));
|
|
845
|
+
for (let i = 0; i < postedCandidates.length; i++) {
|
|
846
|
+
const { p, mid, createdRaw } = postedCandidates[i];
|
|
847
|
+
if (seenMids.has(mid)) continue;
|
|
848
|
+
seenMids.add(mid);
|
|
849
|
+
const viewsData = postedViews[i];
|
|
850
|
+
moments.push({
|
|
851
|
+
moment_uid: mid,
|
|
852
|
+
thumbnail_url: p.thumbnail_url,
|
|
853
|
+
video_url: p.video_url,
|
|
854
|
+
caption: p.caption || "",
|
|
855
|
+
views_count: (viewsData && viewsData.count) || 0,
|
|
856
|
+
viewers: (viewsData && viewsData.moment_views) || [],
|
|
857
|
+
reactions: (viewsData && viewsData.reactions) || [],
|
|
858
|
+
created_at: createdRaw,
|
|
859
|
+
source: "posted_moment"
|
|
860
|
+
});
|
|
861
|
+
if (limit && moments.length >= limit) return moments.slice(0, limit);
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
try {
|
|
865
|
+
const uUrl = `https://firestore.googleapis.com/v1/projects/locket-4252a/databases/(default)/documents/users/${myUid}/conversations`;
|
|
866
|
+
const uRes = await fetchWithTimeout(uUrl, { headers: { Authorization: `Bearer ${token}` } }, 30000);
|
|
867
|
+
const uData = await uRes.json();
|
|
868
|
+
const userStoragePath = `users%2F${myUid}%2Fmoments`;
|
|
869
|
+
for (const doc of (uData.documents || [])) {
|
|
870
|
+
const cid = doc.name.split("/").pop();
|
|
871
|
+
const mUrl = `https://firestore.googleapis.com/v1/projects/locket-4252a/databases/(default)/documents/conversations/${cid}/messages?pageSize=200`;
|
|
872
|
+
const mRes = await fetchWithTimeout(mUrl, { headers: { Authorization: `Bearer ${token}` } }, 30000);
|
|
873
|
+
const mData = await mRes.json();
|
|
874
|
+
for (const mdoc of (mData.documents || [])) {
|
|
875
|
+
const f = mdoc.fields || {};
|
|
876
|
+
const thumb = (f.thumbnail_url && f.thumbnail_url.stringValue) || "";
|
|
877
|
+
const rm = (f.reply_moment && f.reply_moment.stringValue) || null;
|
|
878
|
+
const createdRaw = (f.created_at && f.created_at.timestampValue) || "";
|
|
879
|
+
if (thumb && thumb.includes(userStoragePath.replace(/%2F/g, "/"))) {
|
|
880
|
+
const mid = rm || mdoc.name.split("/").pop();
|
|
881
|
+
if (!mid || seenMids.has(mid)) continue;
|
|
882
|
+
if (dtStart || dtEnd) {
|
|
883
|
+
const docDt = parseTs(createdRaw);
|
|
884
|
+
if (docDt) {
|
|
885
|
+
if (dtStart && docDt < dtStart) continue;
|
|
886
|
+
if (dtEnd && docDt > dtEnd) continue;
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
const viewsData = await this.getViews(mid);
|
|
890
|
+
if (viewsData && (viewsData.status === 200 || viewsData.status === null || viewsData.count !== undefined)) {
|
|
891
|
+
seenMids.add(mid);
|
|
892
|
+
moments.push({
|
|
893
|
+
moment_uid: mid,
|
|
894
|
+
thumbnail_url: thumb,
|
|
895
|
+
video_url: null,
|
|
896
|
+
caption: "",
|
|
897
|
+
views_count: (viewsData && viewsData.count) || 0,
|
|
898
|
+
viewers: (viewsData && viewsData.moment_views) || [],
|
|
899
|
+
reactions: (viewsData && viewsData.reactions) || [],
|
|
900
|
+
created_at: createdRaw,
|
|
901
|
+
source: "posted_moment"
|
|
902
|
+
});
|
|
903
|
+
if (limit && moments.length >= limit) return moments.slice(0, limit);
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
} catch (e) {}
|
|
909
|
+
return moments;
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
encodeQueryCursor({ date, docName }) {
|
|
913
|
+
return date && docName
|
|
914
|
+
? Buffer.from(JSON.stringify({ date, docName })).toString("base64url")
|
|
915
|
+
: null;
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
decodeQueryCursor(token) {
|
|
919
|
+
if (!token) return null;
|
|
920
|
+
try {
|
|
921
|
+
const cursor = JSON.parse(Buffer.from(token, "base64url").toString());
|
|
922
|
+
return cursor?.date && cursor?.docName ? cursor : null;
|
|
923
|
+
} catch {
|
|
924
|
+
return null;
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
getDocDateValue(doc) {
|
|
929
|
+
const raw = doc?.fields?.date?.timestampValue || doc?.createTime || new Date(0).toISOString();
|
|
930
|
+
return typeof raw === "string" ? raw : new Date(0).toISOString();
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
parseFirestoreValue(value) {
|
|
934
|
+
if (!value) return null;
|
|
935
|
+
|
|
936
|
+
const types = {
|
|
937
|
+
stringValue: (v) => v,
|
|
938
|
+
integerValue: (v) => Number.parseInt(v, 10),
|
|
939
|
+
doubleValue: (v) => Number.parseFloat(v),
|
|
940
|
+
booleanValue: (v) => v,
|
|
941
|
+
timestampValue: (v) => v,
|
|
942
|
+
nullValue: () => null,
|
|
943
|
+
referenceValue: (v) => v,
|
|
944
|
+
};
|
|
945
|
+
|
|
946
|
+
for (const [key, parser] of Object.entries(types)) {
|
|
947
|
+
if (value[key] !== undefined) return parser(value[key]);
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
if (value.mapValue) {
|
|
951
|
+
return Object.fromEntries(
|
|
952
|
+
Object.entries(value.mapValue.fields || {}).map(([key, item]) => [key, this.parseFirestoreValue(item)])
|
|
953
|
+
);
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
if (value.arrayValue) {
|
|
957
|
+
return (value.arrayValue.values || []).map((item) => this.parseFirestoreValue(item));
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
if (value.geoPointValue) {
|
|
961
|
+
return {
|
|
962
|
+
latitude: value.geoPointValue.latitude,
|
|
963
|
+
longitude: value.geoPointValue.longitude,
|
|
964
|
+
};
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
return null;
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
async getMoments({ filteredByUserId = null, limit = 20, pageToken = null } = {}) {
|
|
971
|
+
const { uid } = this.client.session;
|
|
972
|
+
if (!uid) throw new AuthenticationError("Not authenticated");
|
|
973
|
+
|
|
974
|
+
const idToken = await this.client.session.getValidToken();
|
|
975
|
+
const pageSize = Math.max(1, Math.min(Number.isFinite(Number(limit)) ? Number(limit) : 20, 100));
|
|
976
|
+
|
|
977
|
+
const cursor = this.decodeQueryCursor(pageToken);
|
|
978
|
+
const url = `https://firestore.googleapis.com/v1/projects/locket-4252a/databases/locket/documents/history/${uid}`;
|
|
979
|
+
|
|
980
|
+
const structuredQuery = {
|
|
981
|
+
from: [{ collectionId: "entries" }],
|
|
982
|
+
orderBy: [
|
|
983
|
+
{ field: { fieldPath: "date" }, direction: "DESCENDING" },
|
|
984
|
+
{ field: { fieldPath: "__name__" }, direction: "DESCENDING" },
|
|
985
|
+
],
|
|
986
|
+
limit: pageSize,
|
|
987
|
+
...(filteredByUserId && {
|
|
988
|
+
where: {
|
|
989
|
+
fieldFilter: {
|
|
990
|
+
field: { fieldPath: "user" },
|
|
991
|
+
op: "EQUAL",
|
|
992
|
+
value: { stringValue: filteredByUserId },
|
|
993
|
+
},
|
|
994
|
+
},
|
|
995
|
+
}),
|
|
996
|
+
...(cursor && {
|
|
997
|
+
startAt: {
|
|
998
|
+
values: [
|
|
999
|
+
{ timestampValue: cursor.date },
|
|
1000
|
+
{ referenceValue: cursor.docName },
|
|
1001
|
+
],
|
|
1002
|
+
before: false,
|
|
1003
|
+
},
|
|
1004
|
+
}),
|
|
1005
|
+
};
|
|
1006
|
+
|
|
1007
|
+
let response;
|
|
1008
|
+
try {
|
|
1009
|
+
response = await fetchWithTimeout(
|
|
1010
|
+
`${url}:runQuery`,
|
|
1011
|
+
{
|
|
1012
|
+
method: "POST",
|
|
1013
|
+
headers: {
|
|
1014
|
+
...this.client.device.defaultHeaders,
|
|
1015
|
+
Authorization: `Bearer ${idToken}`,
|
|
1016
|
+
"Content-Type": "application/json",
|
|
1017
|
+
Accept: "application/json",
|
|
1018
|
+
},
|
|
1019
|
+
body: JSON.stringify({ structuredQuery }),
|
|
1020
|
+
},
|
|
1021
|
+
30000
|
|
1022
|
+
);
|
|
1023
|
+
} catch (e) {
|
|
1024
|
+
throw new LocketAPIError("Firestore request failed", null, { message: e && e.message ? e.message : String(e) });
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
if (!response.ok) {
|
|
1028
|
+
let errData = null;
|
|
1029
|
+
try {
|
|
1030
|
+
errData = await response.json();
|
|
1031
|
+
} catch (e) {}
|
|
1032
|
+
throw new LocketAPIError("Firestore request failed", response.status, errData);
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
const rows = await response.json();
|
|
1036
|
+
const documents = (rows || []).flatMap((row) => (row.document ? [row.document] : []));
|
|
1037
|
+
|
|
1038
|
+
const moments = documents
|
|
1039
|
+
.map((doc) => {
|
|
1040
|
+
const fields = doc.fields || {};
|
|
1041
|
+
const get = (key) => this.parseFirestoreValue(fields[key]);
|
|
1042
|
+
|
|
1043
|
+
const date = get("date") || this.getDocDateValue(doc);
|
|
1044
|
+
const momentUid = fields.canonical_uid?.stringValue || fields.moment_uid?.stringValue || doc.name?.split("/").pop();
|
|
1045
|
+
|
|
1046
|
+
const ts = date ? new Date(date).getTime() : NaN;
|
|
1047
|
+
return {
|
|
1048
|
+
moment_uid: momentUid,
|
|
1049
|
+
user_uid: filteredByUserId || uid,
|
|
1050
|
+
thumbnail_url: get("thumbnail_url") || "",
|
|
1051
|
+
image_url: get("image_url") || get("thumbnail_url") || "",
|
|
1052
|
+
video_url: get("video_url") || "",
|
|
1053
|
+
caption: get("caption") || "",
|
|
1054
|
+
overlays: get("overlays") || [],
|
|
1055
|
+
created_at: Number.isFinite(ts) ? String(Math.floor(ts / 1000)) : "",
|
|
1056
|
+
date,
|
|
1057
|
+
md5: fields.md5?.stringValue || "",
|
|
1058
|
+
};
|
|
1059
|
+
})
|
|
1060
|
+
.filter((moment) => moment.moment_uid);
|
|
1061
|
+
|
|
1062
|
+
const lastDoc = documents.at(-1);
|
|
1063
|
+
const nextPageToken =
|
|
1064
|
+
documents.length === pageSize && lastDoc
|
|
1065
|
+
? this.encodeQueryCursor({
|
|
1066
|
+
date: this.getDocDateValue(lastDoc),
|
|
1067
|
+
docName: lastDoc.name,
|
|
1068
|
+
})
|
|
1069
|
+
: null;
|
|
1070
|
+
|
|
1071
|
+
return { moments, nextPageToken };
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
async getViews(momentUid) {
|
|
1075
|
+
const payload = { moment_uid: momentUid };
|
|
1076
|
+
const res = await this.client.postApi("getMomentViews", payload);
|
|
1077
|
+
const viewsDict = (res && typeof res === "object") ? (res.data || res) : {};
|
|
1078
|
+
const reactions = [];
|
|
1079
|
+
try {
|
|
1080
|
+
const token = await this.client.session.getValidToken();
|
|
1081
|
+
const url = `https://firestore.googleapis.com/v1/projects/locket-4252a/databases/(default)/documents/moments/${momentUid}/reactions`;
|
|
1082
|
+
const r = await fetchWithTimeout(url, { headers: { Authorization: `Bearer ${token}` } }, 30000);
|
|
1083
|
+
const data = await r.json();
|
|
1084
|
+
for (const doc of (data.documents || [])) {
|
|
1085
|
+
const f = doc.fields || {};
|
|
1086
|
+
reactions.push({
|
|
1087
|
+
emoji: (f.string && f.string.stringValue) || "",
|
|
1088
|
+
sender: (f.user && f.user.stringValue) || "",
|
|
1089
|
+
created_at: (f.created_at && f.created_at.timestampValue) || ""
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
} catch (e) {}
|
|
1093
|
+
if (viewsDict && typeof viewsDict === "object") viewsDict.reactions = reactions;
|
|
1094
|
+
return viewsDict;
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
async comment(momentUid, receiverUid, text, fromMemory = false) {
|
|
1098
|
+
const payload = {
|
|
1099
|
+
moment_uid: momentUid,
|
|
1100
|
+
receiver_uid: receiverUid,
|
|
1101
|
+
msg: text,
|
|
1102
|
+
from_memory: fromMemory,
|
|
1103
|
+
client_token: null
|
|
1104
|
+
};
|
|
1105
|
+
const res = await this.client.postApi("sendChatMessageV2", payload);
|
|
1106
|
+
return (res && res.data) ? res.data : res;
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
async delete(momentUid) {
|
|
1110
|
+
return this.client.postApi("deleteMomentV2", { moment_uid: momentUid, canonical_uid: momentUid });
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
module.exports = { MomentsModule, NoteType };
|