-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlibrary.js
More file actions
650 lines (574 loc) ยท 29.1 KB
/
Copy pathlibrary.js
File metadata and controls
650 lines (574 loc) ยท 29.1 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
'use strict';
const db = require.main.require('./src/database');
const meta = require.main.require('./src/meta');
const posts = require.main.require('./src/posts');
const topics = require.main.require('./src/topics');
const users = require.main.require('./src/user');
const websockets = require.main.require('./src/socket.io');
const messaging = require.main.require('./src/messaging');
const AliExpressService = require('./aliexpress');
const plugin = {};
const ADMIN_UIDS = [1, 2];
const WHITELIST_DB_KEY = 'plugin:cline-links:whitelist';
// ืืคืชืืืช DB ืขืืืจ state ืฉื ืขืืืื ืคืืกื.
// state: 'pending' (ืขืืืื ืืจื ืืกืชืืื) | 'clean' (ืืื ืฉืื ืื) | 'modified' (ืืฉ ืืืืคืืช).
// ืืฉืืืฆื 'modified', ืืืคืชื replacements ืืืื JSON ืฉื ืืคืช originalโfinal.
const stateKey = (pid) => `plugin:cline-links:post:${pid}:state`;
const replacementsKey = (pid) => `plugin:cline-links:post:${pid}:replacements`;
const PENDING_INDEX_KEY = 'plugin:cline-links:pending'; // set ืฉื pids ืขื state=pending (ืื ืืงืื ืืขืืืื)
// ืขืืืจ ืืืืขืืช ืฆ'ืื: ืืื ื-NodeBB ืืืื ืืืืขื (mid) ืืชืื ืืืืืืงื ืืืชืจืื ืฉื ืฉืื
// ืืืืื - ืืฉ ืจืง roomId. ืืื ืฉืืืจืื ืืช ืืืืืคืืช ืคืจ-ืืืจ (ืืฆืืืจ, ืืขืืื ืื ื ืืืง),
// ืืืขืงื ื-pending ืืื ืกื ืฉื mid-ืื ืฉืขืืืื ืืขืืืื ืืืืชื ืืืจ - ืื state ืืืื,
// ืื ืืื ืืืืขืืช ืืืืืืช ืืืืืช ืืขืืืื ืืืืชื ืืืจ ืื-ืืื ืืช.
const roomPendingKey = (roomId) => `plugin:cline-links:room:${roomId}:pending`;
const roomReplacementsKey = (roomId) => `plugin:cline-links:room:${roomId}:replacements`;
const ROOM_PENDING_INDEX_KEY = 'plugin:cline-links:room-pending'; // set ืฉื "roomId:mid" (ืื ืืงืื ืืขืืืื)
const POLL_INTERVAL_MS = 200;
const POLL_TIMEOUT_MS = 10000;
const BLACKLISTED_PARAMS = [
'spm', 'aff_id', 'aff_platform', 'aff_trace_key', 'tag', 'ref',
'_x_cid', '_x_ads_channel', '_x_campaign', '_x_vst_scene',
'refer_share_id', 'refer_share_uid', 'invite_code',
'linkCode', 'ref_', 'creative', 'camp', 'collection_id',
'pdp_npi', 'gps-id', 'scm', 'ws_ab_test', 'sourceType'
];
// sku_id/skuId/pdp_ext_f ืืืืื ืืช ืืืจืืืฆืื (ืืืฉื ืฆืืข) ืฉื ืืืจื ืืืืชื item id -
// ืจ' AliExpress Color Link Copier. ืื ืื ื-API ืฉื ืืฉืืชืคืื ืืืืืจ ืงืืฉืืจ ืืื
// ืืคืจืืืจ ืืื ืืื ืืงืจื, ืืชืืกืฃ ืขืฆืื ืื ืืืืจ ืืืกืืจ ืืืชื.
const WHITELISTED_PARAMS = [
'productIds', 'bundle_id', 'g_site', 'g_region', 'g_lg', 'g_ccy', 'subj',
'sku_id', 'skuId', 'pdp_ext_f'
];
const CLEANING_RULES = [
{
name: 'Short Links',
regex: /(?:https?:\/\/)?(?:s\.click\.aliexpress\.com|a\.aliexpress\.com|temu\.to|share\.temu\.com|amzn\.to|ebay\.to)\/[^\s)]+/g,
resolve: true,
isAliExpress: true
},
{
name: 'AliExpress Direct',
regex: /(?:https?:\/\/)?(?:\w+\.)?aliexpress\.com\/(?:item\/|ssr\/|store\/|p\/)[^\s)]+/g,
resolve: false,
isAliExpress: true
},
{
name: 'Temu Direct',
regex: /(?:https?:\/\/)?(?:\w+\.)?temu\.com\/[^\s)]+/g,
resolve: false,
isAliExpress: false
},
{
name: 'Amazon Direct',
regex: /(?:https?:\/\/)?(?:\w+\.)?amazon\.(?:com|co\.uk|de|it|fr|es|ca)\/(?:dp|gp\/product)\/[\w\d]+[^\s)]*/g,
resolve: false,
isAliExpress: false
}
];
plugin.init = async function (params) {
// console.log('[cline-links] โ
Plugin init() called - hooks should be registered');
const { router, middleware } = params;
router.get('/admin/plugins/cline-links', middleware.admin.buildHeader, plugin.renderAdmin);
router.get('/api/admin/plugins/cline-links', plugin.renderAdmin);
// ื ืืงืื pending ืชืงืืข ื-crash ืงืืื: ืื ืคืจืื ืฉื ืฉืืจ ื-pending ืื ืืกืืื ืืขืืื
// ืืืืกืื ืืช ืืืืื ืขื timeout. ื ืกืืจ ืืช ืืกืืืื ืืื ืฉืืืืืืื ืืืฆืื (ืขื ืชืืื ื-DB,
// ืฉืืืชืื ืฉืื ืขืืื, ืืื ืื ืืืจืืจื ืืืืื ืืืชืจ ืืืืื ืชืงืืข).
try {
const stuckPids = await db.getSetMembers(PENDING_INDEX_KEY);
if (stuckPids && stuckPids.length) {
await Promise.all(stuckPids.map(async (pid) => {
await db.delete(stateKey(pid));
await db.setRemove(PENDING_INDEX_KEY, pid);
}));
}
const stuckRoomMids = await db.getSetMembers(ROOM_PENDING_INDEX_KEY);
if (stuckRoomMids && stuckRoomMids.length) {
await Promise.all(stuckRoomMids.map(async (entry) => {
const sep = entry.indexOf(':');
const roomId = entry.slice(0, sep);
const mid = entry.slice(sep + 1);
await db.setRemove(roomPendingKey(roomId), mid);
await db.setRemove(ROOM_PENDING_INDEX_KEY, entry);
}));
}
} catch (err) {
console.error('[cline-links] init cleanup error:', err);
}
};
plugin.renderAdmin = function (req, res) {
res.render('admin/plugins/cline-links', { title: 'Cline Links & Affiliate' });
};
plugin.addAdminNavigation = async function (header) {
header.plugins.push({ route: '/plugins/cline-links', icon: 'fa-shopping-cart', name: 'Cline Links' });
return header;
};
// ืงืืฆืืจ-ืืจื ืืชืืืื ืื ืืืื: ืื ืืขืืืื ืจืฅ ืืืืชื ืชืืืื, ื-email hook ืืืื
// ืืืืืช ืืฉืืจืืช ื-Promise ืืืงืื polling ื-DB. ืืงืื ืคืืืืจืฆืืืช multi-process,
// ืชืืืื ืืืจ ืืืืงืง ื-polling โ ืืื ืืกืืจ.
const inFlight = new Map(); // pid -> Promise (ืขืืืื ืคืืกื ืืืื)
const roomInFlight = new Map(); // roomId -> Set<Promise> (ืืื ืืืืขืืช ืืืืืืช ืืืืืช ืืขืืืื ืืืืชื ืืืจ ืื-ืืื ืืช)
async function markPending(pid) {
await Promise.all([
db.set(stateKey(pid), 'pending'),
db.setAdd(PENDING_INDEX_KEY, String(pid)),
db.delete(replacementsKey(pid)),
]);
}
async function markFinished(pid, replacements) {
const hasChanges = replacements && replacements.size > 0;
if (hasChanges) {
const obj = {};
for (const [orig, final] of replacements) obj[orig] = final;
await db.setObject(replacementsKey(pid), obj);
await db.set(stateKey(pid), 'modified');
} else {
await db.delete(replacementsKey(pid));
await db.set(stateKey(pid), 'clean');
}
await db.setRemove(PENDING_INDEX_KEY, String(pid));
}
async function getState(pid) {
return await db.get(stateKey(pid));
}
async function getReplacements(pid) {
const obj = await db.getObject(replacementsKey(pid));
if (!obj) return null;
return new Map(Object.entries(obj));
}
function startProcessing(pid) {
if (!pid) return null;
const key = String(pid);
if (inFlight.has(key)) return inFlight.get(key);
const p = (async () => {
let result = { replacements: new Map() };
try {
// Safety net: ื-filter:post.create ืืืชืื ืฉื-pid ืขืื ืื ืืื ืืืื
// ืืืื markPending ืื ืจืฅ. ื ืกืื ืืื ืืืชืจ ืืืืืื, ืืคื ื ืืขืืืื ืขืฆืื.
try { await markPending(pid); }
catch (err) { console.error('[cline-links] markPending in startProcessing error:', err); }
result = await processPostContent(pid);
} finally {
try { await markFinished(pid, result.replacements); }
catch (err) { console.error('[cline-links] markFinished error:', err); }
}
return result;
})().finally(() => { if (inFlight.get(key) === p) inFlight.delete(key); });
inFlight.set(key, p);
return p;
}
// Hooks: filter:post.create / filter:post.edit ืจืฆืื *ืืคื ื* ืฉืืืจืช ืืคืืกื.
// ืื ืื ื ืืกืื ืื pending ืืื ืืื ืฉืื ื-email hook ื ืืจื ืืคื ื ืฉ-post.save ืืกืชืืื,
// ืืื ืืืฆื ืืช ืืกืืืื ืืืืื.
plugin.handlePostFilter = async (data) => {
const pid = data?.post?.pid;
if (pid) {
try { await markPending(pid); }
catch (err) { console.error('[cline-links] markPending error:', err); }
}
return data;
};
plugin.handlePostSave = (data) => {
// console.log('[cline-links] ๐ handlePostSave fired, pid=', data?.post?.pid, 'hasContent=', !!data?.post?.content);
if (data?.post?.pid) setImmediate(() => startProcessing(data.post.pid));
};
plugin.handlePostEdit = (data) => {
// console.log('[cline-links] ๐ handlePostEdit fired, pid=', data?.post?.pid, 'hasContent=', !!data?.post?.content);
if (data?.post?.pid) setImmediate(() => startProcessing(data.post.pid));
};
// --- ืืืืขืืช ืฆ'ืื ---
// ืื ืืืื ืืคืืกืืื, ืืื ื-NodeBB "pid" ืืงืืื ืืชืื ืืืืืืงื ืืืชืจืื ืฉื ืฆ'ืื - ืืื
// roomId ืื ืงืืื ืชืืื. ืืื ืืืืืคืืช ื ืฉืืจืืช ืคืจ-ืืืจ (ืืฆืืืจ), ืื-pending ืืื ืกื
// ืฉื mid-ืื ืืขืืืื ืืืืชื ืืืจ, ืืื ืฉืืื ืืืืขืืช ืืืืชื ืืืจ ืื ืืืจืกื ืื ืืช ืื.
async function markMessagePending(roomId, mid) {
await Promise.all([
db.setAdd(roomPendingKey(roomId), String(mid)),
db.setAdd(ROOM_PENDING_INDEX_KEY, `${roomId}:${mid}`),
]);
}
async function markMessageFinished(roomId, mid, replacements) {
if (replacements && replacements.size > 0) {
const obj = {};
for (const [orig, final] of replacements) obj[orig] = final;
await db.setObject(roomReplacementsKey(roomId), obj); // ืืฆืืจืฃ ืืืคื ืืงืืืืช ืฉื ืืืืจ, ืื ืืืจืก
}
await db.setRemove(roomPendingKey(roomId), String(mid));
await db.setRemove(ROOM_PENDING_INDEX_KEY, `${roomId}:${mid}`);
}
function startProcessingMessage(message) {
const { roomId, mid } = message;
const p = (async () => {
let result = { replacements: new Map() };
try {
try { await markMessagePending(roomId, mid); }
catch (err) { console.error('[cline-links] markMessagePending error:', err); }
result = await processMessageContent(message);
} finally {
try { await markMessageFinished(roomId, mid, result.replacements); }
catch (err) { console.error('[cline-links] markMessageFinished error:', err); }
}
return result;
})();
let set = roomInFlight.get(roomId);
if (!set) { set = new Set(); roomInFlight.set(roomId, set); }
set.add(p);
p.finally(() => { set.delete(p); if (set.size === 0) roomInFlight.delete(roomId); });
return p;
}
// filter:messaging.save ืจืฅ *ืืคื ื* ืฉืืืืืขื ื ืฉืืจืช, ื-NodeBB ืืืชืื ืื (await).
// ืืกืื ืื pending ืืื - ืืืืืง ืืื handlePostFilter ืืฆื ืคืืกืืื - ืืื ืฉืืฉื-email
// hook (ืฉื ืฉืืฃ ื-notifyUsersInRoom, ืฉืจืฅ ืืื ืืืจื ืฉืืืืืขื ื ืฉืืจืช) ืืืืืง, ืืกืืืื
// ืืืื ืืืจ ื-DB. ืืื ืื ืืฉ ืืืื-ืืื ืฉืื ืืืืืขื ื ืฉืืจื ืืื ืื ืื ื ืขืืืื ืื ืกืืื ื
// pending (ืื action:messaging.save+setImmediate ืจืฆืื ืืืจื), ืื-email "ืืคืกืคืก"
// ืืช ืืืืชื ื ืืืงืื ืืช ืืงืืฉืืจ ืืืืืื.
plugin.handleMessageFilter = async (message) => {
if (message?.mid && message?.roomId) {
try { await markMessagePending(message.roomId, message.mid); }
catch (err) { console.error('[cline-links] markMessagePending (filter) error:', err); }
}
return message;
};
// action:messaging.save ื ืืจื ืืืจื ืฉืืืืืขื ืืืจ ื ืฉืืจื - ืืื ืืจืืฆืื ืืช ืืขืืืื
// ืืืื (resolve/API) ืืจืงืข, ืืื ืืืกืื ืืช ืฉืืืืช ืืืืืขื.
plugin.handleMessageSave = (data) => {
const message = data?.message;
if (message?.mid && message?.roomId) {
setImmediate(() => startProcessingMessage(message));
}
};
async function processMessageContent(message) {
const replacements = new Map();
try {
if (!message || !message.content || !message.mid) return { replacements };
const settings = await meta.settings.get('cline-links');
const ownerUid = parseInt(message.fromuid, 10);
const aliService = new AliExpressService(settings);
const result = await findAndReplaceLinks(message.content, ownerUid, settings, aliService);
if (!result.modified) return { replacements };
for (const [orig, final] of result.replacements) replacements.set(orig, final);
// ืื ืืฉืชืืฉืื ื-messaging.editMessage: ืืคืื ืงืฆืื ืืื ืชืืื ืืกืื ืช ืืช
// ืืืืืขื ื"ื ืขืจืื" (ืฉืื edited), ืื ืืื ื ืืขืื ืืขืจืืื ืืืืื ืข"ื ืืืฉืชืืฉ.
// ืืื ืฉืืืืืขื ืชืืฉืืจ ืืื ืชื "ื ืขืจื" ืืืจื ื ืืงืื ืืงืืฉืืจืื - ืืืืืง ืืื
// ืฉืคืืกืืื ืื ืืกืืื ืื ืืขืจืืืื ืืืจื ืืืชื ืชืืืื - ืืืชืืื ืืช ืืฉืื ืืฉืืจืืช
// ืืืฉืืจืื ืืช ืืืจืืข ื-Socket ืืขืฆืื ื, ืืืืชื ืคืืจืื ืฉื messaging.editMessage.
await messaging.setMessageField(message.mid, 'content', result.content);
const messages = await messaging.getMessagesData([message.mid], message.fromuid, message.roomId, true);
if (messages[0]) {
const roomName = messages[0].deleted ? `uid_${message.fromuid}` : `chat_room_${message.roomId}`;
websockets.in(roomName).emit('event:chats.edit', { messages });
}
} catch (err) {
console.error('[cline-links] processMessageContent error:', err);
}
return { replacements };
}
async function waitForState(pid) {
// ืงืืฆืืจ-ืืจื ืืชืืืื ืื ืืืื
const local = inFlight.get(String(pid));
if (local) {
try { await local; } catch (_) { /* state ื-DB ืืกืคืจ ืืช ืืกืืคืืจ */ }
}
const deadline = Date.now() + POLL_TIMEOUT_MS;
while (Date.now() < deadline) {
const state = await getState(pid);
if (state !== 'pending') return state; // 'clean' | 'modified' | null
await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
}
console.warn(`[cline-links] โฑ๏ธ waitForState timeout for pid=${pid}`);
return await getState(pid); // ื ืืืืจ ืืช ืื ืฉืืฉ, ืื ืื ืขืืืื pending
}
// ืืืชืื ืืื ืืขืืืืืื ืฉืจืฆืื ืืจืืข ืขื ืืืืจ (ืงืืฆืืจ-ืืจื ืืชืืืื ืื ืืืื), ืืื ืืืืง
// ืืช ืกื ื-pending ื-DB ืขื timeout - ืืื ืืืกืืช ืื multi-process ืืื ืขืืืืืื
// ืฉืืชืืืื ืืืจื ืืงืจืืื ืืจืืฉืื ื. ืชืืื ืืืืืจ ืืช ืืคืช ืืืืืคืืช ืืืฆืืืจืช ืฉื ืืืืจ,
// ืื ืื ืขืืืื ื ืฉืืจื mid-ืื pending (ืขืืืฃ ืืืง ืืืืืืคืืช ืืืฉืจ ืืืืืช ืื ืฆื).
async function waitForRoom(roomId) {
const local = roomInFlight.get(roomId);
if (local && local.size) {
try { await Promise.allSettled([...local]); } catch (_) { /* ืื ืืืืจ ืืงืจืืช, allSettled ืื ื ืืฉื */ }
}
const deadline = Date.now() + POLL_TIMEOUT_MS;
while (Date.now() < deadline) {
const pending = await db.getSetMembers(roomPendingKey(roomId));
if (!pending || pending.length === 0) break;
await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
}
return await getRoomReplacements(roomId);
}
async function getRoomReplacements(roomId) {
const obj = await db.getObject(roomReplacementsKey(roomId));
if (!obj) return null;
return new Map(Object.entries(obj));
}
plugin.handleEmailParams = async (data) => {
try {
// ื-hook ืืงืื ืืขืืคืช: { template, email, language, params, caller }.
// ืืคืจืืืจืื ืืืืืชืืื ืฉื ืืชืื ืืช ื ืืฆืืื ื-data.params.
const inner = data?.params || {};
const pid = parseInt(inner.pid ?? inner.notification?.pid, 10);
const roomId = inner.notification?.roomId;
let replacements;
if (pid) {
const state = await waitForState(pid);
// 'clean' ืื null/ืื-ืืกืืื โ ืืื ืื ืืืืืืฃ, ืืืฆืืื ืืื (ืงืจืืืช DB ืืืช).
if (state !== 'modified') return data;
replacements = await getReplacements(pid);
} else if (roomId) {
replacements = await waitForRoom(roomId);
} else {
return data;
}
if (!replacements || replacements.size === 0) return data;
// ืชืืื ืืฆ'ืื (ืืื bodyLong ืฉื ืคืืกืืื) ืืืืข ืืืืื ืืืจื ืจืื ืืืจ markdown
// (linkify), ืฉืืืจื & ื-& ืืชืื ืืงืืฉืืจ ืืืืฆื/href. ืืื ืื ืกืื ืื
// ืืช ืืืจืกื ืืืืืจืืช ืฉื ืืืคืชื/ืืขืจื, ืื ืืกืฃ ืืืจืกื ืืืืืืืช.
const escapeAmp = (str) => str.replace(/&/g, '&');
// ื-linkify autolink ืืฉ ืื "ืจืืืื" ืงืืืื ืืืงื ืฉื ืืืงืกื ืืืืฆื ืืื ืชืื
// <a> (ืืืฉื %21 ืืืคื ื-! ืืชืฆืืื ืืื ื ืฉืืจ %21 ื-href) - ืื ืฉืืืงืกื
// ืืืืฆื ืื ืืืืจื ืชืืื ืืืื-ืืืืื ืืืจืกื ืืืืืืืช/ืืืืืจืืช. decodeURIComponent
// ืืื + ืืืืื HTML-entities ืื ืจืื ืืช ืฉื ืืื ืืืืชื ืืืจืืืช ืืืฉืืืื, ืืื
// ืื ืกืืช ืืฉืืืจ ืืช ืืืืืืจืืชื ืืืืืืง ืฉื ืืกืคืจืืื.
function normalizeForCompare(str) {
let s = String(str)
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
.replace(/"/g, '"').replace(/'/g, '\'');
try { s = decodeURIComponent(s); } catch (_) { /* ืงืืืื ืืืงื/ืื ืชืงืื - ืืฉืืืื ืืื ืฉืืื */ }
return s;
}
const apply = (text) => {
if (typeof text !== 'string' || !text) return text;
let out = text;
// 1. ืชืืืืช <a href="...">ืืงืกื</a>: ืืจืื ืืืจ ืขืืื ืืฉื ืืช ืขืื ืชืืืื
// ืืงืืืื ืืขืืจ ื-& -> & (ืืืฉื "?" ืืจืื ืฉืืืคื ื-%3F) - ืืชืืื
// ืืืืืงืช ืฉื ืืืืจืืืช ืื ืชืืื ืชืกืคืืง. ืืฉืืืื ืืช ื-href ืืืช ืืืงืกื
// ืืืืฆื ืืคื ืืฉืืขืืช (decodeURIComponent ืืื + ืืืืื HTML-entities
// ืืฉื ื ืืฆืืืื), ืืจืง ืืืงืจื ืฉื ืืชืืื ืืืจืกืื ืืช ืฉื ืืื ืืงืืฉืืจ ืืกืืคื -
// ืืื ืื ืืืขืช ืืืงืกื ืืืชืื-ืืืฉืืช ืฉืืชื ืืืฉืชืืฉ (ืกืื ืืงืก [ืืงืกื](url)).
out = out.replace(/<a\b([^>]*)href="([^"]*)"([^>]*)>([\s\S]*?)<\/a>/g, (match, before, href, after, innerText) => {
const normHref = normalizeForCompare(href);
for (const [orig, final] of replacements) {
if (orig === final || normHref !== normalizeForCompare(orig)) continue;
const escFinal = escapeAmp(final);
const newInner = normalizeForCompare(innerText) === normalizeForCompare(orig) ? escFinal : innerText;
return `<a${before}href="${escFinal}"${after}>${newInner}</a>`;
}
return match;
});
// 2. ืืงืกื ืจืืื (ืืืืฅ ืืชืืืืช <a>) - ืืืฉื subject/intro, ืื ืงืืฉืืจ
// ืฉืื ืขืืจ autolink: ืืืืคื ืืฉืืจื, ืืืื ื ืืกืืื ืขื & ืืืืจื ื-&.
for (const [orig, final] of replacements) {
if (orig === final) continue;
const escOrig = escapeAmp(orig);
const pairs = [[orig, final]];
if (escOrig !== orig) pairs.push([escOrig, escapeAmp(final)]);
for (const [from, to] of pairs) {
const escapedRegex = from.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
out = out.replace(new RegExp(escapedRegex, 'g'), to);
}
}
return out;
};
if (inner.body) inner.body = apply(inner.body);
if (inner.intro) inner.intro = apply(inner.intro);
if (inner.subject) inner.subject = apply(inner.subject);
if (inner.notification) {
if (inner.notification.bodyShort) inner.notification.bodyShort = apply(inner.notification.bodyShort);
if (inner.notification.bodyLong) inner.notification.bodyLong = apply(inner.notification.bodyLong);
if (inner.notification.bodyEmail) inner.notification.bodyEmail = apply(inner.notification.bodyEmail);
if (inner.notification.subject) inner.notification.subject = apply(inner.notification.subject);
}
} catch (err) {
console.error('[cline-links] handleEmailParams error:', err);
}
return data;
};
// Tracking ID ืืฉืืืืฉ ื-API ืฉื ืืฉืืชืคืื: ืื ืืืฉืชืืฉ ืืืืืจ Tracking ID ืืืชืื
// ืืืฉืืช ื-ACP (userOverrides), ื ืฉืชืืฉ ืื ืืืงืื ื-Tracking ID ืืืืื ืฉื ืืชืืกืฃ.
function getTrackingIdForUser(ownerUid, settings) {
if (ownerUid > 0 && settings && settings.userOverrides) {
try {
const overrides = JSON.parse(settings.userOverrides);
if (Array.isArray(overrides)) {
const match = overrides.find(entry => parseInt(entry.uid, 10) === ownerUid);
if (match && match.trackingId) return match.trackingId;
}
} catch (err) {
console.error('[cline-links] getTrackingIdForUser parse error:', err);
}
}
return null;
}
// ืืืืืงืช ืืืืืื/ื ืืงืื/ืืืจื ืืืฉืืชืคืช ืืคืืกืืื ืืืืืืขืืช ืฆ'ืื.
async function findAndReplaceLinks(content, ownerUid, settings, aliService) {
const replacements = new Map();
const enabled = settings && settings.enabled === 'on';
let currentContent = content;
let modified = false;
let matches = [];
for (const rule of CLEANING_RULES) {
const found = currentContent.match(rule.regex);
if (found) found.forEach(url => matches.push({ url, rule }));
}
if (matches.length === 0) {
return { content: currentContent, modified, replacements };
}
const uniqueLinks = [...new Set(matches.map(m => m.url))];
for (const originalUrl of uniqueLinks) {
const normalizedOriginal = normalizeUrl(originalUrl);
// ืืืืงื: ืืื ืืงืืฉืืจ ืืื ืืื ืืืจ ืงืืฉืืจ "ืืืกืื" (ืืืืจ ืืขืืจ ืข"ื ืืคืืจืื)
if (await db.isSetMember(WHITELIST_DB_KEY, normalizedOriginal)) {
continue;
}
const match = matches.find(m => m.url === originalUrl);
let workUrl = normalizedOriginal;
let wasConverted = false;
// 1. Resolve (ืจืง ืื ืื ืืืืื)
if (match.rule.resolve) {
workUrl = await resolveShortLink(workUrl);
}
// 2. Strip Parameters
let finalUrl = stripAffiliateParameters(workUrl);
// 3. AliExpress API Conversion
if (enabled && (match.rule.isAliExpress || finalUrl.includes('aliexpress.com'))) {
const subId = ownerUid > 0 ? `u${ownerUid}` : 'guest';
const trackingId = getTrackingIdForUser(ownerUid, settings);
const affiliateUrl = await aliService.convertToAffiliate(finalUrl, subId, trackingId);
if (affiliateUrl) {
finalUrl = affiliateUrl;
wasConverted = true;
}
}
// 4. ืืืื ื: ืื ืื ื ืฉืืืจืื ืืช ืืชืืฆืื ืืกืืคืืช ืืจืฉืืื ืืืื ื
// ืื ืื ืงืืฉืืจ ืืงืืฆืจ (s.click) ืฉื ืืฆืจ ืขืืฉืื, ืืื ืื ืืขืืื ืฉืื ืืขืืื.
if (wasConverted || match.rule.resolve) {
await db.setAdd(WHITELIST_DB_KEY, normalizeUrl(finalUrl));
}
// 5. ืืืืคื
if (finalUrl !== originalUrl) {
const escaped = originalUrl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
currentContent = currentContent.replace(new RegExp(escaped, 'g'), finalUrl);
modified = true;
replacements.set(originalUrl, finalUrl);
}
}
return { content: currentContent, modified, replacements };
}
async function processPostContent(pid) {
// console.log(`[cline-links] โถ๏ธ processPostContent START pid=${pid}`);
const replacements = new Map();
try {
const postData = await posts.getPostData(pid);
if (!postData || !postData.content) {
// console.log(`[cline-links] โ pid=${pid} no postData/content, postData=${!!postData}`);
return { replacements };
}
// console.log(`[cline-links] ๐ pid=${pid} content length=${postData.content.length}, uid=${postData.uid}`);
const settings = await meta.settings.get('cline-links');
const postOwnerUid = parseInt(postData.uid, 10);
const aliService = new AliExpressService(settings);
const result = await findAndReplaceLinks(postData.content, postOwnerUid, settings, aliService);
if (!result.modified) {
// console.log(`[cline-links] โ pid=${pid} no matching URLs found, returning`);
return { replacements };
}
for (const [orig, final] of result.replacements) replacements.set(orig, final);
const currentContent = result.content;
{
// console.log(`[cline-links] ๐พ saving pid=${pid}, new content preview:`, currentContent.substring(0, 300));
await posts.setPostField(pid, 'content', currentContent);
await posts.clearCachedPost(pid);
const verifyData = await posts.getPostData(pid);
// console.log(`[cline-links] โ
verify after save pid=${pid}, stored content preview:`, verifyData?.content?.substring(0, 300));
// ืื ืืื ืืืืืงืช ืฉื ืืืืืืงื ื-Socket ืืคื ืืืืืื ืืชืงืื ื
const [topicData, userData, parsedPost] = await Promise.all([
topics.getTopicData(postData.tid),
users.getUserFields(postOwnerUid, ['username', 'userslug', 'displayname']),
posts.parsePost({ ...postData, content: currentContent })
]);
const isMainPost = parseInt(pid, 10) === parseInt(topicData.mainPid, 10);
// ืืืืืืงื ื-Topic ืืืฆืืืฆื ืฉืืืคืืข ืคืขืืืื
const simpleTopic = {
tid: parseInt(topicData.tid, 10),
cid: parseInt(topicData.cid, 10),
title: topicData.title,
isMainPost: isMainPost,
renamed: false,
tagsupdated: false
};
const editResult = {
topic: simpleTopic,
editor: {
username: userData.username,
userslug: userData.userslug,
uid: postOwnerUid,
displayname: userData.displayname,
isLocal: true
},
post: {
content: parsedPost.content, // ื-HTML ืืืขืืื
pid: parseInt(pid, 10),
tid: parseInt(postData.tid, 10),
uid: postOwnerUid,
timestamp: postData.timestamp,
timestampISO: new Date(postData.timestamp).toISOString(),
deleted: false,
upvotes: 0,
downvotes: 0,
deleterUid: 0,
replies: 0,
bookmarks: 0,
votes: 0,
cid: parseInt(topicData.cid, 10),
editor: postOwnerUid,
topic: simpleTopic, // ืืืื ืืืืคืืข ืื ืคื
changed: true // ืืืื ืืืืคืืข ืืชืื ืืคืืกื
}
};
websockets.in(`topic_${postData.tid}`).emit('event:post_edited', editResult);
// console.log(`[cline-links] Broadcasted exact structure for PID ${pid}`);
}
} catch (err) {
console.error('[cline-links] Error:', err);
}
return { replacements };
}
function normalizeUrl(url) {
if (!url) return '';
let cleaned = url.replace(/[).,;!]+$/, '').trim();
if (!/^https?:\/\//i.test(cleaned)) {
cleaned = 'https://' + cleaned;
}
return cleaned;
}
function stripAffiliateParameters(url) {
try {
const urlObj = new URL(normalizeUrl(url));
const params = urlObj.searchParams;
const keys = Array.from(params.keys());
keys.forEach(key => {
if (BLACKLISTED_PARAMS.includes(key) || key.startsWith('_x_')) {
params.delete(key);
} else if (
(urlObj.pathname.includes('/item/') || urlObj.pathname.includes('/ssr/') || urlObj.pathname.includes('/dp/')) &&
!WHITELISTED_PARAMS.includes(key)
) {
params.delete(key);
}
});
return urlObj.toString();
} catch (e) {
return url;
}
}
async function resolveShortLink(url) {
try {
const response = await fetch(url, {
method: 'GET',
redirect: 'follow',
headers: { 'User-Agent': 'Mozilla/5.0' },
signal: AbortSignal.timeout(5000)
});
return response.url;
} catch (err) {
return url;
}
}
module.exports = plugin;