Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
10019 lines (8990 loc) · 371 KB
/
Copy pathcontent.js
File metadata and controls
10019 lines (8990 loc) · 371 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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* global DLSQ */
/* =========================================================================
【GSS 聊天面板】content.js
- 這是注入到直播網頁的內容腳本(顯示浮動貼圖發送面板)
- 功能:發送貼圖、頁面元素控制、劇院模式
- 對應:popup.html 是「管理面板」(擴充彈出視窗)
========================================================================= */
// 【調試工具】確保 testYouTubeLive 可用(如果 gsstracker.js 還沒載入,提供臨時版本)
if (typeof window.testYouTubeLive === 'undefined') {
window.testYouTubeLive = function () {
if (window._gssTracker && window._gssTracker.debugYouTubeLive) {
return window._gssTracker.debugYouTubeLive();
}
console.log('[GSS Tracker] 尚未初始化,請等待頁面載入完成');
return null;
};
}
const TAG = typeof DLSQ !== 'undefined' ? DLSQ : null;
// 當前版本(用於更新通知)
// 直接讀取 manifest.json 的版本號(只需改 manifest.json 即可)
const CURRENT_VERSION = chrome.runtime.getManifest().version;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// ========= 平台適配器架構開關 =========
// true = 使用新的 platforms/ 架構
// false = 使用舊的內建函數 (向後相容後備)
const USE_NEW_PLATFORM_ADAPTER = true;
// 輔助函數:取得平台適配器
function getPlatformAdapter() {
if (typeof window !== 'undefined' && window.GSS && window.GSS.Platform) {
return window.GSS.Platform.getPlatformAdapter();
}
return null;
}
// 輔助函數:檢查新架構是否可用
function isNewPlatformAvailable() {
return USE_NEW_PLATFORM_ADAPTER && getPlatformAdapter() !== null;
}
// ==================== 通用配置常量 ====================
/**
* 多平台聊天容器選擇器(按優先級排序)
* 注意:WTV 使用獨立的 [data-chat-scroll-container],不包含在此列表中
*/
const CHAT_CONTAINER_SELECTORS = [
'#chatroom-messages', // Kick 虛擬滾動容器
'.overflow-y-auto.height-100', // DLive
'.scrollable-area', // Twitch 真正可滾動的容器
'[data-a-target="chat-list"]', // Twitch 備援
'.chat-scroll-area', // Twitch 備援
'.chat-room__content', // Twitch 舊版
'.chat-list', // 通用
'[data-chat="true"] [class*="overflow-y"]', // Kick 新版
'[class*="ChatContainer"] [class*="overflow"]', // Kick 容器
'#chat-input-wrapper ~ div [class*="overflow-y"]', // Kick 舊版
'.chat-container [class*="overflow"]', // Kick 備援
'[class*="chat-scroll"]', // Kick 滾動容器
'[class*="ChatMessageList"]', // Kick 消息列表
'[class*="chat-messages"]', // Kick 聊天消息
'.vs_chatv9_messages', // Vaughn
'[class*="message-list"]' // 通用
];
/**
* 查找聊天容器元素
* @param {boolean} requireScrollable - 是否要求容器可滾動
* @returns {HTMLElement|null}
*/
function findChatContainer(requireScrollable = false) {
for (const selector of CHAT_CONTAINER_SELECTORS) {
const el = document.querySelector(selector);
if (el) {
if (!requireScrollable || el.scrollHeight > el.clientHeight) {
return el;
}
}
}
return null;
}
/**
* 執行聊天室滾動到底部(通用版本,不適用於 WTV)
* @param {HTMLElement} wrapper - 貼圖包裝元素
* @param {string} platform - 平台名稱(可選,自動檢測)
*/
function scrollToBottom(wrapper, platform = null) {
const currentPlatform = platform || getCurrentPlatform();
// 如果是小圖模式,跳過自動捲動
const isInline = (window.gssStickerSizeMode === 'small');
if (isInline) {
console.log('[GSS] Skip scroll: inline mode');
return;
}
// WTV 使用獨立邏輯,不走這裡
if (currentPlatform === 'wtv') {
console.warn('[GSS] WTV should use its own scroll logic');
return;
}
// 【測試】gosh 平台暫時禁用自動滾軸,測試官方是否會幫忙滾動
if (currentPlatform === 'gosh') {
console.log('[GSS] Skip scroll: gosh platform (testing official scroll)');
return;
}
const chatContainer = findChatContainer(true);
if (!chatContainer) {
// fallback: 使用 scrollIntoView
wrapper?.parentElement?.scrollIntoView(false);
return;
}
// 檢查用戶是否在底部附近
const distanceToBottom = chatContainer.scrollHeight - chatContainer.scrollTop - chatContainer.clientHeight;
if (distanceToBottom > 500) {
console.log('[GSS] Skip scroll: user not near bottom');
return;
}
// 根據不同平台執行滾動
if (currentPlatform === 'kick') {
chatContainer.scrollTop = chatContainer.scrollHeight;
} else if (currentPlatform === 'twitch') {
const targetScroll = chatContainer.scrollHeight;
chatContainer.scrollTo({ top: targetScroll, behavior: 'auto' });
chatContainer.dispatchEvent(new Event('scroll', { bubbles: true }));
window.dispatchEvent(new Event('scroll', { bubbles: true }));
// 點擊"暫停"按鈕恢復自動滾動
const resumeBtn = document.querySelector('button[class*="scroll"], button[dir="ltr"]');
if (resumeBtn && resumeBtn.textContent.includes('暂停')) {
resumeBtn.click();
}
setTimeout(() => {
chatContainer.scrollTo({ top: chatContainer.scrollHeight, behavior: 'auto' });
}, 100);
} else {
// 其他平台使用 scrollIntoView
wrapper?.parentElement?.scrollIntoView(false);
}
}
/**
* 為媒體元素綁定滾動事件(通用版本,不適用於 WTV)
* @param {HTMLElement} mediaEl - 圖片或視頻元素
* @param {HTMLElement} wrapper - 包裝元素
*/
function bindMediaScroll(mediaEl, wrapper) {
if (!mediaEl || mediaEl.dataset.dlsqScrollBound) return;
mediaEl.dataset.dlsqScrollBound = 'true';
// 【同步】記錄到貼圖牆
if (window.GSS_ImageLogger) {
const url = mediaEl.src || mediaEl.dataset.gssUrl;
const id = mediaEl.alt || mediaEl.dataset.ytId || '';
if (url) {
window.GSS_ImageLogger.log(url, id);
}
}
const doScroll = () => scrollToBottom(wrapper);
mediaEl.addEventListener('load', doScroll);
mediaEl.addEventListener('error', doScroll);
// 如果已經加載完成,延遲執行
if (mediaEl.complete) {
setTimeout(doScroll, 200);
}
}
// ========= 語言設定 =========
let currentLang = 'zh';
// 支援的語言列表
const SUPPORTED_LANGS = ['zh', 'zh-CN', 'en', 'ja', 'ko'];
// 語言對應表:將 i18n.js 的語言代碼映射到 content.js 的語言代碼
const LANG_MAP = {
'zh-TW': 'zh',
'zh-CN': 'zh-CN',
'en': 'en',
'ja': 'ja',
'ko': 'ko'
};
function getContentLang(uiLang) {
return LANG_MAP[uiLang] || 'zh';
}
const UI_I18N = {
zh: {
addToQuick: '新增到 GSS',
fav: '標記常用(★)',
stickerLoggerTitle: '貼圖記錄牆',
stickerLoggerPanelTitle: '🖼️ 貼圖記錄牆',
stickerLoggerClearBtn: '清空記錄',
unfav: '取消常用(★)',
hide: '隱藏',
unhide: '取消隱藏',
tags: '標籤',
zoomImage: '放大圖片',
sendSameSticker: '↵ 發送相同圖片',
added: (n) => `✅ 已新增(共 ${n} 個)`,
exists: (n) => `ℹ️ 已存在(共 ${n} 個)`,
favMarked: '✅ 已標記常用(★)',
favUnmarked: '✅ 已取消常用',
hidden: `✅ 已隱藏(到「隱藏」分頁可永久刪除)`,
unhidden: '✅ 已取消隱藏',
removeTag: (tag) => `✅ 已移除 #${tag}`,
addTag: (tag) => `✅ 已加上 #${tag}`,
deleted: (n) => `✅ 已從清單刪除(剩 ${n} 個)`,
notInList: 'ℹ️ 清單內沒有此 ID',
loading: '載入中…',
all: '全部 / ALL',
dl: 'DL',
im: 'IM',
me: 'ME',
yt: 'YT',
wtv: 'WTV',
hiddenTab: (n) => `隱藏 (${n})`,
notInListMsg: '不在清單內',
emptyVocabMsg: '詞庫為空時仍可用上方「常用/隱藏」;要套用其他 #標籤請到 popup 建立詞庫',
permDelete: '從清單永久刪除…',
uncategorizedTab: (n) => `未分類 (${n})`,
prevPage: '< 上一頁',
nextPage: '下一頁 >',
extensionUpdated: '❌ 擴充已更新,請重新整理頁面',
sendFailed: '貼圖送出失敗',
sendFailedPrefix: '發送失敗:',
unknownError: '未知錯誤',
updateChangelog: '查看更新日誌',
updateNewVersion: '📢 有新更新!點擊查看',
helpPage: '查看使用說明',
sharedChatKickTwitchWarning: '⚠️ Twitch 聊天室無法在 KICK 頁面嵌入\n\n這是 Twitch 的安全策略限制,\n請在支援的直播平台頁面使用 Twitch 共用聊天。',
autoSend: '自動發送',
autoSendOn: '自動發送:開',
autoSendOff: '自動發送:關'
},
'zh-CN': {
addToQuick: '添加到 GSS',
fav: '标记常用(★)',
stickerLoggerTitle: '贴图记录墙',
stickerLoggerPanelTitle: '🖼️ 贴图记录墙',
stickerLoggerClearBtn: '清空记录',
unfav: '取消常用(★)',
hide: '隐藏',
unhide: '取消隐藏',
tags: '标签',
zoomImage: '放大图片',
sendSameSticker: '↵ 发送相同图片',
added: (n) => `✅ 已添加(共 ${n} 个)`,
exists: (n) => `ℹ️ 已存在(共 ${n} 个)`,
favMarked: '✅ 已标记常用(★)',
favUnmarked: '✅ 已取消常用',
hidden: `✅ 已隐藏(到「隐藏」分页可永久删除)`,
unhidden: '✅ 已取消隐藏',
removeTag: (tag) => `✅ 已移除 #${tag}`,
addTag: (tag) => `✅ 已添加 #${tag}`,
deleted: (n) => `✅ 已从清单删除(剩 ${n} 个)`,
notInList: 'ℹ️ 清单内没有此 ID',
loading: '加载中…',
all: '全部 / ALL',
dl: 'DL',
im: 'IM',
me: 'ME',
yt: 'YT',
wtv: 'WTV',
hiddenTab: (n) => `隐藏 (${n})`,
notInListMsg: '不在清单内',
emptyVocabMsg: '词库为空时仍可用上方「常用/隐藏」;要套用其他 #标签请到 popup 建立词库',
permDelete: '从清单永久删除…',
uncategorizedTab: (n) => `未分类 (${n})`,
prevPage: '< 上一页',
nextPage: '下一页 >',
extensionUpdated: '❌ 扩展已更新,请刷新页面',
sendFailed: '贴图发送失败',
sendFailedPrefix: '发送失败:',
unknownError: '未知错误',
updateChangelog: '查看更新日志',
updateNewVersion: '📢 有新更新!点击查看',
helpPage: '查看使用说明',
sharedChatKickTwitchWarning: '⚠️ Twitch 聊天室無法在 KICK 頁面嵌入\n\n這是 Twitch 的安全策略限制,\n請在支援的直播平台頁面使用 Twitch 共用聊天。',
autoSend: '自动发送',
autoSendOn: '自动发送:开',
autoSendOff: '自动发送:关'
},
en: {
addToQuick: 'Add to GSS',
fav: 'Mark as Favorite (★)',
stickerLoggerTitle: 'Sticker Log Wall',
stickerLoggerPanelTitle: '🖼️ Sticker Log Wall',
stickerLoggerClearBtn: 'Clear Records',
unfav: 'Unmark Favorite (★)',
hide: 'Hide',
unhide: 'Unhide',
tags: 'Tags',
zoomImage: 'Zoom Image',
sendSameSticker: '↵ Send Same Image',
added: (n) => `✅ Added (${n} total)`,
exists: (n) => `ℹ️ Already exists (${n} total)`,
favMarked: '✅ Marked as favorite (★)',
favUnmarked: '✅ Unmarked as favorite',
hidden: `✅ Hidden (find in "Hidden" tab to permanently delete)`,
unhidden: '✅ Unhidden',
removeTag: (tag) => `✅ Removed #${tag}`,
addTag: (tag) => `✅ Added #${tag}`,
deleted: (n) => `✅ Deleted from list (${n} remaining)`,
notInList: 'ℹ️ ID not in list',
loading: 'Loading…',
all: 'All',
dl: 'DL',
im: 'IM',
me: 'ME',
yt: 'YT',
wtv: 'WTV',
hiddenTab: (n) => `Hidden (${n})`,
notInListMsg: 'Not in list',
emptyVocabMsg: 'When vocabulary is empty, you can still use "Favorite/Hide" above; to apply other #tags, add them in popup',
permDelete: 'Permanently delete from list…',
uncategorizedTab: (n) => `Uncategorized (${n})`,
prevPage: '< Prev',
nextPage: 'Next >',
extensionUpdated: '❌ Extension updated, please refresh page',
sendFailed: 'Failed to send sticker',
sendFailedPrefix: 'Send failed:',
unknownError: 'Unknown error',
updateChangelog: 'View Changelog',
updateNewVersion: '📢 New update available! Click to view',
helpPage: 'View Help',
sharedChatKickTwitchWarning: '⚠️ Twitch chat cannot be embedded on KICK pages\n\nThis is a Twitch security policy restriction.\nPlease use Twitch shared chat on supported streaming platform pages.',
autoSend: 'Auto Send',
autoSendOn: 'Auto Send: On',
autoSendOff: 'Auto Send: Off'
},
ja: {
addToQuick: 'GSSに追加',
fav: 'お気に入り登録(★)',
stickerLoggerTitle: 'ステッカーログ壁',
stickerLoggerPanelTitle: '🖼️ ステッカーログ壁',
stickerLoggerClearBtn: '記録をクリア',
unfav: 'お気に入り解除(★)',
hide: '非表示',
unhide: '非表示解除',
tags: 'タグ',
zoomImage: '画像を拡大',
sendSameSticker: '↵ 同じ画像を送信',
added: (n) => `✅ 追加しました(計 ${n} 個)`,
exists: (n) => `ℹ️ 既に存在します(計 ${n} 個)`,
favMarked: '✅ お気に入りに追加しました(★)',
favUnmarked: '✅ お気に入りから削除しました',
hidden: `✅ 非表示にしました(「非表示」タブで完全削除可能)`,
unhidden: '✅ 非表示を解除しました',
removeTag: (tag) => `✅ #${tag} を削除しました`,
addTag: (tag) => `✅ #${tag} を追加しました`,
deleted: (n) => `✅ リストから削除しました(残り ${n} 個)`,
notInList: 'ℹ️ リストにこの ID がありません',
loading: '読み込み中…',
all: '全て / ALL',
dl: 'DL',
im: 'IM',
me: 'ME',
yt: 'YT',
wtv: 'WTV',
hiddenTab: (n) => `非表示 (${n})`,
notInListMsg: 'リストにありません',
emptyVocabMsg: '辞書が空でも「お気に入り/非表示」は使用可能;その他の #タグ を追加するには popup で辞書を作成してください',
permDelete: 'リストから完全に削除…',
uncategorizedTab: (n) => `未分類 (${n})`,
prevPage: '< 前へ',
nextPage: '次へ >',
extensionUpdated: '❌ 拡張機能が更新されました。ページを更新してください',
sendFailed: 'スタンプの送信に失敗しました',
sendFailedPrefix: '送信失敗:',
unknownError: '不明なエラー',
updateChangelog: '更新履歴を見る',
updateNewVersion: '📢 新しい更新があります!クリックして見る',
helpPage: '使い方を見る',
sharedChatKickTwitchWarning: '⚠️ TwitchチャットはKICKページに埋め込めません\n\nこれはTwitchのセキュリティポリシーによる制限です。\nサポートされている配信プラットフォームページでTwitch共用チャットをご利用ください。',
autoSend: '自動送信',
autoSendOn: '自動送信:オン',
autoSendOff: '自動送信:オフ'
},
ko: {
addToQuick: 'GSS에 추가',
fav: '즐겨찾기 등록(★)',
stickerLoggerTitle: '스티커 로그 벽',
stickerLoggerPanelTitle: '🖼️ 스티커 로그 벽',
stickerLoggerClearBtn: '기록 지우기',
unfav: '즐겨찾기 해제(★)',
hide: '숨기기',
unhide: '숨기기 해제',
tags: '태그',
zoomImage: '이미지 확대',
sendSameSticker: '↵ 같은 이미지 보내기',
added: (n) => `✅ 추가되었습니다(총 ${n} 개)`,
exists: (n) => `ℹ️ 이미 존재합니다(총 ${n} 개)`,
favMarked: '✅ 즐겨찾기에 추가되었습니다(★)',
favUnmarked: '✅ 즐겨찾기에서 제거되었습니다',
hidden: `✅ 숨김 처리되었습니다("숨김" 탭에서 완전 삭제 가능)`,
unhidden: '✅ 숨김 해제되었습니다',
removeTag: (tag) => `✅ #${tag} 삭제됨`,
addTag: (tag) => `✅ #${tag} 추가됨`,
deleted: (n) => `✅ 목록에서 삭제되었습니다(남은 ${n} 개)`,
notInList: 'ℹ️ 목록에 이 ID가 없습니다',
loading: '로딩 중…',
all: '전체 / ALL',
dl: 'DL',
im: 'IM',
me: 'ME',
yt: 'YT',
wtv: 'WTV',
hiddenTab: (n) => `숨김 (${n})`,
notInListMsg: '목록에 없음',
emptyVocabMsg: '사전이 비어있어도 "즐겨찾기/숨김"은 사용 가능;다른 #태그 를 추가하려면 popup에서 사전을 만드세요',
permDelete: '목록에서 영구 삭제…',
uncategorizedTab: (n) => `미분류 (${n})`,
prevPage: '< 이전',
nextPage: '다음 >',
extensionUpdated: '❌ 확장 프로그램이 업데이트되었습니다. 페이지를 새로고침해 주세요',
sendFailed: '스티커 전송 실패',
sendFailedPrefix: '전송 실패:',
unknownError: '알 수 없는 오류',
updateChangelog: '업데이트 내역 보기',
updateNewVersion: '📢 새로운 업데이트가 있습니다! 클릭해서 보기',
helpPage: '사용 방법 보기',
sharedChatKickTwitchWarning: '⚠️ 트위치 채팅은 KICK 페이지에 임베드할 수 없습니다\n\n이것은 트위치 보안 정책의 제한입니다.\n지원되는 스트리밍 플랫폼 페이지에서 트위치 공용 채팅을 사용해 주세요.',
autoSend: '자동 전송',
autoSendOn: '자동 전송: 켜기',
autoSendOff: '자동 전송: 끄기'
}
};
function t(key, ...args) {
const dict = UI_I18N[currentLang] || UI_I18N.zh;
const val = dict[key];
if (typeof val === 'function') return val(...args);
return val || key;
}
function initLanguage() {
try {
chrome.storage.sync.get(['uiLang'], (result) => {
currentLang = getContentLang(result.uiLang);
// 初始化後立即更新面板按鈕文字
updatePanelButtonTexts();
});
} catch (e) {
// Extension context invalidated
}
}
// 監聽語言變化
try {
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName === 'sync' && changes.uiLang) {
currentLang = getContentLang(changes.uiLang.newValue);
// 刷新面板以更新語言
const panel = document.getElementById(UI.panelId);
if (panel?.classList.contains('open')) {
refreshPanelStickers().catch(() => { });
}
// 更新選單文字
updateContextMenuTexts();
// 更新面板按鈕文字
updatePanelButtonTexts();
}
});
} catch (e) {
// Extension context invalidated
}
// ========= GSS-分類安全檢查 =========
// 安全檢查:確保圖片連結是安全的
function isSafeImageUrl(url) {
try {
// 檢查 URL 格式
const urlObj = new URL(url);
// 只允許 HTTP/HTTPS 協議
if (!['http:', 'https:'].includes(urlObj.protocol)) {
return false;
}
// 檢查文件擴展名
const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg', '.mp4'];
const hasAllowedExtension = allowedExtensions.some(ext =>
urlObj.pathname.toLowerCase().endsWith(ext)
);
if (!hasAllowedExtension) {
return false;
}
// 檢查域名白名單(可選)
const trustedDomains = [
'i.imgur.com', 'imgur.com',
'cdn.discordapp.com', 'media.discordapp.net',
'i.redd.it', 'preview.redd.it',
'pbs.twimg.com',
'cdn.pixil.art',
'i.nhentai.net', // 如果需要的話
'storage.googleapis.com',
'github.com', 'raw.githubusercontent.com'
];
// 如果是受信任的域名,直接允許
if (trustedDomains.some(domain => urlObj.hostname.includes(domain))) {
return true;
}
// 對於其他域名,進行額外檢查
// 不允許的域名模式
const blockedPatterns = [
/localhost/i,
/127\.0\.0\.1/,
/192\.168\./,
/10\./,
/\.onion/i,
/\.bit/i
];
if (blockedPatterns.some(pattern => pattern.test(urlObj.hostname))) {
return false;
}
// 檢查 URL 長度限制
if (url.length > 2048) {
return false;
}
// 檢查是否包含可疑字符(包含對 URL 編碼後的代碼進行解碼檢查)
const suspiciousPatterns = [
/javascript:/i,
/data:/i,
/vbscript:/i,
/<script/i,
/onload=/i,
/onerror=/i
];
if (suspiciousPatterns.some(pattern => pattern.test(url))) {
return false;
}
// 進階檢查:解碼後的 URL 是否包含惡意代碼
try {
const decodedUrl = decodeURIComponent(url);
if (suspiciousPatterns.some(pattern => pattern.test(decodedUrl))) {
console.warn('[GSS] 偵測到編碼後的惡意代碼:', decodedUrl);
return false;
}
} catch (e) {
// 如果解碼失敗,可能是 URL 本身格式有問題,為安全起見繼續檢查
}
return true;
} catch (error) {
console.warn('[GSS] URL 安全檢查失敗:', error);
return false;
}
}
// ========= 零寬字符隱藏訊息功能 =========
// 方案C: 只使用2種零寬字符表示1bit (Twitch會過濾U+FEFF和U+200D)
const ZW_CHARS = {
'0': '\u200B', // 零寬空格 = 0
'1': '\u200C' // 零寬非連接符 = 1
};
const ZW_REVERSE = Object.fromEntries(Object.entries(ZW_CHARS).map(([k, v]) => [v, k]));
// 將字串編碼為零寬字符
function encodeToZeroWidth(str) {
const bytes = new TextEncoder().encode(str);
let encoded = '';
for (const byte of bytes) {
// 每個byte轉成8個bit,每個bit用一個零寬字符表示
const b = byte.toString(2).padStart(8, '0');
for (const bit of b) {
encoded += ZW_CHARS[bit];
}
}
return encoded;
}
// 從零寬字符解碼
function decodeFromZeroWidth(zwStr) {
let bits = '';
for (const char of zwStr) {
const bit = ZW_REVERSE[char];
if (bit) bits += bit;
}
// 每8bit一組轉成byte
const bytes = [];
for (let i = 0; i < bits.length; i += 8) {
const byte = bits.slice(i, i + 8);
if (byte.length === 8) {
bytes.push(parseInt(byte, 2));
}
}
return new TextDecoder().decode(new Uint8Array(bytes));
}
// 發送隱藏訊息(使用 GraphQL 像 IM 功能一樣)
async function sendHiddenMessage(message, visibleMarker = ' ') {
const encoded = encodeToZeroWidth(message);
const fullText = visibleMarker + encoded;
try {
await sendChatMessage(fullText);
return true;
} catch (err) {
showSendFailureToast(`${t('sendFailedPrefix')} ${err.message}`);
return false;
}
}
// ========= UI: Chat-side button + floating panel =========
const UI = {
rootId: 'dlsq_root',
btnId: 'dlsq_btn',
panelId: 'dlsq_panel',
styleId: 'dlsq_style_v2',
ctxMenuId: 'dlsq_ctx_menu',
panelTagMenuId: 'dlsq_panel_tag_menu',
failToastId: 'dlsq_fail_overlay',
tabDLId: 'dlsq_tab_dl',
tabCBId: 'dlsq_tab_cb',
tabMEId: 'dlsq_tab_me',
tabIMId: 'dlsq_tab_im',
tabYTId: 'dlsq_tab_yt',
zoomOverlayId: 'dlsq_zoom_overlay'
};
let panelFilterType = 'all'; // 'all', 'DL', 'IM', 'ME'
let panelFilterTag = '__all__';
let panelCurrentPage = 1; // 當前頁碼(分頁功能)
const PANEL_PAGE_SIZE = 12; // 每頁顯示 12 張貼圖(3行×4欄)
/** 保留標籤:帶此標籤的貼圖只在「隱藏」分頁顯示;一般分頁的「刪除」改為加此標籤 */
const PANEL_HIDDEN_TAG = '隱藏';
const PANEL_FILTER_HIDDEN = '__hidden__';
const PANEL_FILTER_UNCATEGORIZED = '__uncategorized__';
let suppressTileClickUntil = 0;
let suppressPanelAutoCloseUntil = 0;
let panelRefreshSeq = 0;
const PANEL_GRID_COLS = 4;
const PANEL_GRID_ROW_HEIGHT = 72;
const PANEL_GRID_MIN_HEIGHT = 72;
const PANEL_GRID_MAX_HEIGHT = 220;
let failToastHideTimer = null;
function suppressTileClickFor(ms = 450) {
suppressTileClickUntil = Date.now() + Math.max(0, Number(ms) || 0);
}
function isTileClickSuppressed() {
return Date.now() < suppressTileClickUntil;
}
function suppressPanelAutoCloseFor(ms = 700) {
suppressPanelAutoCloseUntil = Date.now() + Math.max(0, Number(ms) || 0);
}
function isPanelAutoCloseSuppressed() {
return Date.now() < suppressPanelAutoCloseUntil;
}
function ensureStyles() {
let style = document.getElementById(UI.styleId);
if (!style) {
style = document.createElement('style');
style.id = UI.styleId;
document.documentElement.appendChild(style);
}
style.textContent = `
#${UI.rootId} { position: relative; z-index: 999999; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
#${UI.btnId} {
width: 26px; height: 26px; border-radius: 6px;
border: 1px solid rgba(255,255,255,0.14);
background: rgba(20,22,26,0.92);
color: rgba(255,255,255,0.92);
cursor: pointer;
display: inline-flex; align-items: center; justify-content: center;
margin-left: 6px;
margin-right: 10px;
user-select: none;
}
#${UI.btnId}:hover { background: rgba(28,30,36,0.96); border-color: rgba(120,190,255,0.45); }
/* ===== Update button pulse animation ===== */
@keyframes dlsq-pulse {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.7; transform: scale(1.15); }
}
/* ===== 统一图片样式 - 全部在下一行 (display: block) ===== */
.dlsq-im-replaced {
display: var(--gss-sticker-display, block) !important;
margin: var(--gss-sticker-margin, 4px 0) !important;
clear: var(--gss-sticker-clear, both) !important;
}
/* Gosh 平台專用樣式 - 強制換行 */
.pc-chat-panel-main .gss-im-replaced,
.pc-chat-panel-main .dlsq-chat-img,
.pc-chat-panel-main .dlsq-chat-video {
display: block !important;
margin: 4px 0 !important;
clear: both !important;
}
/* 強制打破 Gosh 平台的內聯鏈 */
.pc-chat-panel-main .chat-message-body,
.pc-chat-panel-main .chat-message-body span,
.pc-chat-panel-main .chat-message-body .inline,
.pc-chat-panel-main .chat-message-body .inline-block {
display: inline !important;
}
/* Gosh 平台貼圖容器強制換行 */
.pc-chat-panel-main .dlsq-hidden-decoded,
.pc-chat-panel-main .dlsq-hidden-decoded a {
display: block !important;
width: 100% !important;
}
.pc-chat-panel-main .dlsq-hidden-decoded img,
.pc-chat-panel-main .dlsq-hidden-decoded video {
display: block !important;
margin: 4px 0 !important;
clear: both !important;
}
.dlsq-chat-img {
max-width: var(--gss-sticker-max-width, 100px);
max-height: var(--gss-sticker-max-height, 100px);
width: auto;
height: auto;
border-radius: 8px;
cursor: default;
display: var(--gss-sticker-img-display, inline-block);
margin: 0;
border: 2px solid transparent;
object-fit: contain;
clear: none;
}
/* WTV 平台贴图样式 */
.dlsq-wtv-sticker {
max-width: var(--gss-sticker-max-width, 100px);
max-height: var(--gss-sticker-max-height, 100px);
width: auto;
height: auto;
border-radius: 4px;
display: inline-block;
margin: 0;
clear: none;
}
/* 视频样式 - 也在下一行 */
.dlsq-chat-video {
max-width: var(--gss-sticker-max-width, 100px);
max-height: var(--gss-sticker-max-height, 100px);
width: auto;
height: auto;
border-radius: 8px;
cursor: default;
display: inline-block;
margin: 0;
border: 2px solid transparent;
clear: none;
}
/* YouTube 缩略图 - 更大尺寸 */
.dlsq-chat-yt {
max-width: 160px;
max-height: 90px;
border-radius: 8px;
display: block;
cursor: pointer;
object-fit: cover;
}
/* YouTube 缩略图容器 - 确保播放按钮居中定位 */
.dlsq-yt-thumbnail, .gss-yt-thumbnail {
position: relative !important;
display: var(--gss-sticker-display, block) !important;
width: fit-content !important;
height: fit-content !important;
line-height: 0 !important;
margin: var(--gss-sticker-margin, 4px 0) !important;
clear: var(--gss-sticker-clear, both) !important;
}
.dlsq-yt-thumbnail img, .gss-yt-thumbnail img {
max-width: var(--gss-sticker-max-width, 100px) !important;
max-height: var(--gss-sticker-max-height, 100px) !important;
display: block !important;
}
.dlsq-yt-shorts {
display: var(--gss-sticker-display, block) !important;
max-width: var(--gss-sticker-max-width, 100px) !important;
width: var(--gss-sticker-max-width, 100px) !important;
aspect-ratio: 9 / 16 !important;
margin: var(--gss-sticker-margin, 4px 0) !important;
clear: var(--gss-sticker-clear, both) !important;
}
/* 零宽解码标记 */
.dlsq-hidden-decoded {
opacity: 0.85;
}
#${UI.panelId} {
position: fixed;
right: 16px;
bottom: 100px;
width: 384px;
max-width: calc(100vw - 32px);
max-height: 480px;
overflow: hidden;
display: none;
background: rgba(16,18,22,0.98);
border: 1px solid rgba(255,255,255,0.12);
border-radius: 10px;
box-shadow: 0 16px 44px rgba(0,0,0,0.55);
z-index: 2147483647;
}
/* iframe 模式:更窄的面板 */
#${UI.panelId}.iframe-mode {
width: 320px;
right: 10px;
bottom: 90px;
max-height: 480px;
}
#${UI.panelId}.iframe-mode .body {
max-height: 520px !important;
}
#${UI.panelId}.iframe-mode .grid {
grid-template-columns: repeat(3, 1fr);
height: 320px !important;
max-height: none !important;
}
#${UI.panelId}.iframe-mode .tabs {
height: 70px;
}
#${UI.panelId}.open { display: block; }
#${UI.panelId} .hdr {
display: flex; align-items: center; justify-content: space-between;
padding: 10px 10px;
background: linear-gradient(180deg, rgba(28,30,36,0.98), rgba(18,20,24,0.98));
color: rgba(255,255,255,0.92);
font-size: 12px;
font-weight: 600;
border-bottom: 1px solid rgba(255,255,255,0.10);
}
#${UI.panelId} .hdr .close {
cursor: pointer;
padding: 2px 6px;
border-radius: 6px;
background: rgba(255,255,255,0.10);
}
#${UI.panelId} .hdr .close:hover { background: rgba(255,255,255,0.18); }
#${UI.panelId} .body { padding: 10px; overflow: auto; max-height: 420px; }
#${UI.panelId} .tabs {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 10px;
height: 72px;
overflow-y: auto;
padding: 6px 2px 6px 0;
flex-shrink: 0;
align-content: flex-start;
}
#${UI.panelId} .tabs .tab {
border: 1px solid rgba(255,255,255,0.14);
background: rgba(10,12,16,0.88);
color: rgba(255,255,255,0.88);
font-size: 11px;
padding: 5px 8px;
border-radius: 999px;
cursor: pointer;
max-width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
#${UI.panelId} .tabs .tab:hover { background: rgba(120,190,255,0.14); border-color: rgba(120,190,255,0.45); }
#${UI.panelId} .tabs .tab.on {
background: rgba(120,190,255,0.22);
border-color: rgba(120,190,255,0.55);
color: rgba(255,255,255,0.96);
}
#${UI.panelId} .grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 8px;
height: 216px;
padding-right: 2px;
}
#${UI.panelId} .tile {
border: 0 !important;
outline: none !important;
box-shadow: none !important;
border-radius: 10px;
background: transparent !important;
padding: 0 !important;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
height: 64px;
position: relative;
}
#${UI.panelId} .tile:hover { background: rgba(120,190,255,0.10); }
#${UI.panelId} .tile:active { background: rgba(120,190,255,0.16); }
#${UI.panelId} .tile img { max-width: 48px; max-height: 48px; }
#${UI.panelId} .tile .fallback {
font-size: 10px;
color: rgba(255,255,255,0.82);
text-align: center;
line-height: 1.2;
padding: 0 2px;
word-break: break-word;
}
#${UI.panelId} .tile .fav {
position: absolute;
top: 4px;
left: 6px;
font-size: 12px;
color: #ffd43b;
text-shadow: 0 2px 10px rgba(0,0,0,0.65);
display: none;
pointer-events: none;
}
#${UI.panelId} .tile.favored .fav { display: block; }
#${UI.panelId} .status {
margin-top: 8px;
font-size: 11px;
color: rgba(255,255,255,0.72);
min-height: 14px;
}
/* ===== Chat Button (聊天室輸入框按鈕) ===== */
#${UI.btnId} {
background: transparent;
border: none;
cursor: pointer;
padding: 4px;
margin: 0 4px;
border-radius: 4px;
display: inline-flex;
align-items: center;
justify-content: center;
z-index: 1000;
transition: background 0.15s ease;
}
#${UI.btnId}:hover {
background: rgba(120,190,255,0.2);
}
#${UI.btnId} img {
display: block;
width: 20px;
height: 20px;
}
/* ===== Right-click context menu (add sticker ID) ===== */
#${UI.ctxMenuId} {
position: fixed;
z-index: 2147483647 !important;
min-width: 180px;
display: none;
background: rgba(16,18,22,0.98);
border: 1px solid rgba(255,255,255,0.12);
border-radius: 10px;
box-shadow: 0 16px 44px rgba(0,0,0,0.55);
padding: 6px;
color: rgba(255,255,255,0.92);
font-size: 12px;
}
#${UI.ctxMenuId}.open { display: block; }
#${UI.ctxMenuId} .item {
padding: 8px 10px;
border-radius: 8px;
cursor: pointer;
user-select: none;
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
#${UI.ctxMenuId} .item:hover { background: rgba(120,190,255,0.14); }