-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
1927 lines (1712 loc) · 81.7 KB
/
content.js
File metadata and controls
1927 lines (1712 loc) · 81.7 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
(function() {
'use strict';
const XHS_PUBLISH_URL = 'https://creator.xiaohongshu.com/publish/publish?source=&published=true&from=tab_switch&target=image';
const INSTAGRAM_CREATE_URL = 'https://www.instagram.com/';
const XHS_STORAGE_KEY = 'tweetsnap_pending_post';
const INSTAGRAM_STORAGE_KEY = 'tweetsnap_pending_post_instagram';
const INS_TO_X_STORAGE_KEY = 'tweetsnap_pending_ins_to_x';
const INS_TO_X_DONE_KEY = 'tweetsnap_last_applied_ins_to_x';
const TIKTOK_TO_X_STORAGE_KEY = 'tweetsnap_pending_tiktok_to_x';
const TIKTOK_TO_X_DONE_KEY = 'tweetsnap_last_applied_tiktok_to_x';
const MOBILE_TWEET_WIDTH = 375;
const XHS_SPLIT_HEIGHT_RATIO = 2.0;
const XHS_SPLIT_OVERLAP_PX = 48;
const REACT_TWEET_API_BASE_URL = 'https://react-tweet.vercel.app/api/tweet/';
function isZhLanguage() {
const lang = (document.documentElement.getAttribute('lang') || navigator.language || '').toLowerCase();
return lang.startsWith('zh');
}
function t(zh, en) {
return isZhLanguage() ? zh : en;
}
function addStyle(cssText) {
const style = document.createElement('style');
style.textContent = cssText;
document.head.appendChild(style);
}
// Add only necessary button styles
addStyle(`
.screenshot-button {
display: flex;
align-items: center;
flex-direction: row;
width: 100%;
padding: 12px 16px;
cursor: pointer;
font-size: 15px;
transition-property: background-color, box-shadow;
transition-duration: 0.2s;
outline-style: none;
box-sizing: border-box;
min-height: 0px;
min-width: 0px;
border: 0 solid black;
background-color: rgba(0, 0, 0, 0);
margin: 0px;
}
.screenshot-button:hover {
background-color: rgba(15, 20, 25, 0.1);
}
.screenshot-icon {
margin-right: 0px; /* Keep margin 0, alignment handled by flex */
width: 18.75px;
height: 18.75px;
/* font-weight: bold; Removed as it doesn't apply well to SVG stroke */
vertical-align: text-bottom; /* Align icon better with text */
}
.screenshot-notification {
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
background-color: #1DA1F2;
color: white;
padding: 10px 20px;
border-radius: 20px;
z-index: 9999;
box-shadow: 0 2px 10px rgba(0,0,0,0.2);
opacity: 1;
transition: opacity 0.5s ease-out;
}
.screenshot-notification.fade-out {
opacity: 0;
}
`);
function findTweetMainContent(menuButton) {
const article = menuButton.closest('article[role="article"]');
if (!article) return null;
return article;
}
function collectTweetData(tweetContainer) {
const textNode = tweetContainer.querySelector('[data-testid="tweetText"]');
const text = textNode ? textNode.innerText.trim() : '';
const userNameNode = tweetContainer.querySelector('[data-testid="User-Name"]');
const author = userNameNode ? userNameNode.innerText.split('\n')[0].trim() : '';
const statusLink = tweetContainer.querySelector('a[href*="/status/"][role="link"]');
const tweetUrl = statusLink ? new URL(statusLink.getAttribute('href'), location.origin).toString() : location.href;
return { text, author, tweetUrl };
}
function showNotification(message, background = '#1DA1F2', durationMs = 2200) {
const notification = document.createElement('div');
notification.className = 'screenshot-notification';
notification.textContent = message;
notification.style.backgroundColor = background;
document.body.appendChild(notification);
setTimeout(() => {
notification.classList.add('fade-out');
setTimeout(() => notification.remove(), 500);
}, durationMs);
return notification;
}
function getVideoProgressToast() {
const id = 'tweetsnap-video-progress';
let el = document.getElementById(id);
if (!el) {
el = document.createElement('div');
el.id = id;
el.className = 'screenshot-notification';
el.style.minWidth = '240px';
el.style.textAlign = 'center';
document.body.appendChild(el);
}
return el;
}
function updateVideoProgressToast(text, background = '#1DA1F2', autoHideMs = 0) {
const el = getVideoProgressToast();
el.classList.remove('fade-out');
el.textContent = text;
el.style.backgroundColor = background;
if (autoHideMs > 0) {
setTimeout(() => {
const current = document.getElementById('tweetsnap-video-progress');
if (!current) return;
current.classList.add('fade-out');
setTimeout(() => current.remove(), 500);
}, autoHideMs);
}
}
function sanitizeFilename(text) {
return (text || 'tweet')
.replace(/[\\/:*?"<>|]/g, '_')
.replace(/\s+/g, ' ')
.trim()
.slice(0, 40) || 'tweet';
}
function setNativeInputValue(input, value) {
const proto = Object.getPrototypeOf(input);
const descriptor = Object.getOwnPropertyDescriptor(proto, 'value');
if (descriptor && descriptor.set) {
descriptor.set.call(input, value);
} else {
input.value = value;
}
}
function setComposerText(node, text) {
if (!node) return false;
const value = String(text || '');
node.focus();
if ('value' in node) {
setNativeInputValue(node, value);
node.dispatchEvent(new Event('input', { bubbles: true }));
node.dispatchEvent(new Event('change', { bubbles: true }));
const readback = String(node.value || '');
return value ? readback.includes(value.slice(0, Math.min(16, value.length))) : true;
}
const isEditable = node.getAttribute('contenteditable') === 'true' || node.isContentEditable;
if (isEditable) {
try {
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(node);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand('insertText', false, value);
} catch (error) {
// Fallback to direct assignment when execCommand is blocked.
node.textContent = value;
}
try {
node.dispatchEvent(new InputEvent('input', {
bubbles: true,
inputType: 'insertText',
data: value
}));
} catch (error) {
node.dispatchEvent(new Event('input', { bubbles: true }));
}
node.dispatchEvent(new Event('change', { bubbles: true }));
const readback = (node.innerText || node.textContent || '').trim();
return value ? readback.includes(value.slice(0, Math.min(16, value.length))) : true;
}
node.textContent = value;
node.dispatchEvent(new Event('input', { bubbles: true }));
node.dispatchEvent(new Event('change', { bubbles: true }));
return true;
}
function fetchRemoteBlobViaBackground(url) {
return new Promise((resolve) => {
if (!chrome.runtime || !chrome.runtime.sendMessage) {
resolve(null);
return;
}
chrome.runtime.sendMessage({ type: 'FETCH_REMOTE_BLOB', url }, (response) => {
if (chrome.runtime.lastError || !response || !response.ok || !response.dataUrl) {
resolve(null);
return;
}
try {
const [header, base64] = String(response.dataUrl).split(',');
const mimeMatch = header.match(/data:(.*?);base64/);
const mime = mimeMatch ? mimeMatch[1] : (response.mime || 'application/octet-stream');
const binary = atob(base64 || '');
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i += 1) {
bytes[i] = binary.charCodeAt(i);
}
const blob = new Blob([bytes], { type: mime });
resolve(blob);
} catch (error) {
resolve(null);
}
});
});
}
function dataUrlToBlob(dataUrl) {
try {
const [header, base64] = String(dataUrl || '').split(',');
if (!header || !base64) return null;
const mimeMatch = header.match(/data:(.*?);base64/);
const mime = mimeMatch ? mimeMatch[1] : 'application/octet-stream';
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i += 1) {
bytes[i] = binary.charCodeAt(i);
}
return new Blob([bytes], { type: mime });
} catch (error) {
return null;
}
}
function getPreferredXComposerRoot() {
const dialogCandidates = Array.from(document.querySelectorAll('[role="dialog"]'))
.filter((dialog) => dialog && dialog.offsetParent !== null)
.filter((dialog) => dialog.querySelector('[data-testid="tweetTextarea_0"], div[role="textbox"][contenteditable="true"], textarea'));
if (dialogCandidates.length > 0) {
return dialogCandidates[dialogCandidates.length - 1];
}
const pageComposer = document.querySelector('main [data-testid="tweetTextarea_0"], main div[role="textbox"][contenteditable="true"], main textarea[data-testid="tweetTextarea_0"]');
if (pageComposer) {
return pageComposer.closest('main') || document;
}
return document;
}
function getXComposerTextNode(root = document) {
const selectors = [
'div[data-testid="tweetTextarea_0"][contenteditable="true"]',
'div[role="textbox"][data-testid="tweetTextarea_0"]',
'textarea[data-testid="tweetTextarea_0"]',
'[data-testid="tweetTextarea_0"] div[role="textbox"][contenteditable="true"]'
];
for (const selector of selectors) {
const node = root.querySelector(selector);
if (!node || node.offsetParent === null) continue;
const inComposer = node.closest('[data-testid="tweetTextarea_0"], [data-testid="toolBar"], [aria-label*="Post" i], [aria-label*="贴文"]');
if (!inComposer && !node.matches('[data-testid="tweetTextarea_0"]')) continue;
return node;
}
return null;
}
function isVideoAcceptInput(node) {
if (!node) return false;
const accept = String(node.getAttribute('accept') || '').toLowerCase();
return accept.includes('video') || accept.includes('.mp4') || accept.includes('quicktime') || accept.includes('.mov');
}
function getXComposerFileInput(root = document, options = {}) {
const { preferVideo = false } = options || {};
const nodes = Array.from(root.querySelectorAll('input[type="file"]'))
.filter((node) => node && !node.disabled);
if (nodes.length === 0) return null;
if (preferVideo) {
const videoNode = nodes.find((node) => isVideoAcceptInput(node));
if (videoNode) return videoNode;
}
const byTestId = nodes.find((node) => node.getAttribute('data-testid') === 'fileInput');
if (byTestId) return byTestId;
const imageNode = nodes.find((node) => {
const accept = String(node.getAttribute('accept') || '').toLowerCase();
return accept.includes('image');
});
if (imageNode) return imageNode;
return nodes[0] || null;
}
function extensionFromMime(mime) {
if (!mime) return 'bin';
if (mime.includes('jpeg')) return 'jpg';
if (mime.includes('png')) return 'png';
if (mime.includes('gif')) return 'gif';
if (mime.includes('webp')) return 'webp';
if (mime.includes('mp4')) return 'mp4';
if (mime.includes('webm')) return 'webm';
if (mime.includes('quicktime')) return 'mov';
return 'bin';
}
async function readBlobHeadText(blob, length = 160) {
try {
const chunk = blob.slice(0, length);
const text = await chunk.text();
return String(text || '').trim().toLowerCase();
} catch (error) {
return '';
}
}
async function isLikelyHtmlBlob(blob) {
const type = String(blob && blob.type ? blob.type : '').toLowerCase();
if (type.includes('text/html') || type.includes('application/xhtml+xml')) {
return true;
}
const head = await readBlobHeadText(blob, 200);
if (!head) return false;
return head.startsWith('<!doctype html') || head.startsWith('<html') || head.includes('<head');
}
async function isLikelyMp4Blob(blob) {
try {
const header = await blob.slice(0, 256).arrayBuffer();
const bytes = new Uint8Array(header);
if (bytes.length < 8) return false;
const ascii = Array.from(bytes)
.map((b) => (b >= 32 && b <= 126 ? String.fromCharCode(b) : ' '))
.join('');
return ascii.includes('ftyp');
} catch (error) {
return false;
}
}
async function uploadInsMediaToX(fileInput, mediaUrls, options = {}) {
if (!fileInput || !Array.isArray(mediaUrls) || mediaUrls.length === 0) {
return { uploaded: 0, total: 0 };
}
const {
maxItems = 4,
filenamePrefix = 'instagram_media',
forcedMime = '',
forcedExt = '',
maxBytesPerFile = 0,
requireVideoMp4 = false,
strictMp4Signature = false,
fallbackMime = 'application/octet-stream'
} = options || {};
const limitedMediaUrls = mediaUrls.slice(0, maxItems);
const dt = new DataTransfer();
let uploaded = 0;
let rejected = 0;
let invalidFormat = 0;
for (let i = 0; i < limitedMediaUrls.length; i += 1) {
const mediaUrl = limitedMediaUrls[i];
let blob = await fetchRemoteBlobViaBackground(mediaUrl);
if (!blob) {
await new Promise((resolve) => setTimeout(resolve, 450));
blob = await fetchRemoteBlobViaBackground(mediaUrl);
}
if (!blob) continue;
if (maxBytesPerFile > 0 && blob.size > maxBytesPerFile) {
rejected += 1;
continue;
}
if (requireVideoMp4) {
const htmlBlob = await isLikelyHtmlBlob(blob);
if (htmlBlob) {
invalidFormat += 1;
continue;
}
if (strictMp4Signature) {
const mp4Blob = await isLikelyMp4Blob(blob);
if (!mp4Blob) {
invalidFormat += 1;
continue;
}
}
}
const resolvedMime = forcedMime || blob.type || fallbackMime;
const ext = forcedExt || extensionFromMime(resolvedMime);
const file = new File([blob], `${filenamePrefix}_${i + 1}.${ext}`, {
type: resolvedMime
});
dt.items.add(file);
uploaded += 1;
}
if (uploaded === 0) {
return { uploaded: 0, total: limitedMediaUrls.length, rejected, invalidFormat };
}
fileInput.files = dt.files;
fileInput.dispatchEvent(new Event('input', { bubbles: true }));
fileInput.dispatchEvent(new Event('change', { bubbles: true }));
return { uploaded, total: limitedMediaUrls.length, rejected, invalidFormat };
}
async function uploadDataUrlsToX(fileInput, dataUrls, options = {}) {
if (!fileInput || !Array.isArray(dataUrls) || dataUrls.length === 0) {
return { uploaded: 0, total: 0, rejected: 0, invalidFormat: 0 };
}
const {
maxItems = 1,
filenamePrefix = 'media',
forcedMime = '',
forcedExt = '',
maxBytesPerFile = 0,
requireVideoMp4 = false,
strictMp4Signature = false,
fallbackMime = 'application/octet-stream'
} = options || {};
const dt = new DataTransfer();
let uploaded = 0;
let rejected = 0;
let invalidFormat = 0;
const limited = dataUrls.slice(0, maxItems);
for (let i = 0; i < limited.length; i += 1) {
const blobRaw = dataUrlToBlob(limited[i]);
if (!blobRaw) {
invalidFormat += 1;
continue;
}
const blob = forcedMime && blobRaw.type !== forcedMime
? new Blob([blobRaw], { type: forcedMime })
: blobRaw;
if (maxBytesPerFile > 0 && blob.size > maxBytesPerFile) {
rejected += 1;
continue;
}
if (requireVideoMp4) {
const htmlBlob = await isLikelyHtmlBlob(blob);
if (htmlBlob) {
invalidFormat += 1;
continue;
}
if (strictMp4Signature) {
const mp4Blob = await isLikelyMp4Blob(blob);
if (!mp4Blob) {
invalidFormat += 1;
continue;
}
}
}
const resolvedMime = forcedMime || blob.type || fallbackMime;
const ext = forcedExt || extensionFromMime(resolvedMime);
const file = new File([blob], `${filenamePrefix}_${i + 1}.${ext}`, { type: resolvedMime });
dt.items.add(file);
uploaded += 1;
}
if (uploaded === 0) {
return { uploaded: 0, total: limited.length, rejected, invalidFormat };
}
fileInput.files = dt.files;
fileInput.dispatchEvent(new Event('input', { bubbles: true }));
fileInput.dispatchEvent(new Event('change', { bubbles: true }));
const assigned = fileInput.files && fileInput.files.length > 0 ? fileInput.files[0] : null;
if (requireVideoMp4 && assigned && assigned.type && !String(assigned.type).toLowerCase().startsWith('video/')) {
return { uploaded: 0, total: limited.length, rejected, invalidFormat: invalidFormat + 1 };
}
return { uploaded, total: limited.length, rejected, invalidFormat };
}
function markInsToXDone(id) {
if (!chrome.storage || !chrome.storage.local) return;
chrome.storage.local.set({ [INS_TO_X_DONE_KEY]: id }, () => {
chrome.storage.local.remove(INS_TO_X_STORAGE_KEY);
});
}
function markTikTokToXDone(id) {
if (!chrome.storage || !chrome.storage.local) return;
chrome.storage.local.set({ [TIKTOK_TO_X_DONE_KEY]: id }, () => {
chrome.storage.local.remove(TIKTOK_TO_X_STORAGE_KEY);
});
}
function startInsToXAutofill() {
if (!chrome.storage || !chrome.storage.local) return;
chrome.storage.local.get([INS_TO_X_STORAGE_KEY, INS_TO_X_DONE_KEY], (data) => {
const payload = data[INS_TO_X_STORAGE_KEY];
const doneId = data[INS_TO_X_DONE_KEY];
if (!payload || !payload.id) return;
if (doneId && doneId === payload.id) return;
const age = Date.now() - (payload.createdAt || 0);
if (age > 30 * 60 * 1000) {
chrome.storage.local.remove(INS_TO_X_STORAGE_KEY);
return;
}
let attempts = 0;
const maxAttempts = 80;
let textDone = false;
let mediaDone = false;
let finalUploadResult = null;
const timer = setInterval(async () => {
attempts += 1;
const composerRoot = getPreferredXComposerRoot();
const textNode = getXComposerTextNode(composerRoot);
const fileInput = getXComposerFileInput(composerRoot);
if (!textDone && textNode) {
textDone = setComposerText(textNode, payload.description || '');
}
if (!mediaDone && fileInput) {
mediaDone = true;
finalUploadResult = await uploadInsMediaToX(fileInput, payload.mediaUrls || []);
}
if (textDone && mediaDone) {
clearInterval(timer);
markInsToXDone(payload.id);
const uploaded = finalUploadResult && typeof finalUploadResult.uploaded === 'number'
? finalUploadResult.uploaded
: 0;
const total = finalUploadResult && typeof finalUploadResult.total === 'number'
? finalUploadResult.total
: 0;
if (uploaded === total && total > 0) {
showNotification(t('已自动填充并上传 Instagram 媒体到 X', 'Instagram content filled and media uploaded to X'), '#17BF63', 2600);
} else if (total > 0) {
showNotification(t(`已上传 ${uploaded}/${total} 个媒体,请检查后发送`, `${uploaded}/${total} media uploaded, please review`), '#F59E0B', 3000);
} else {
showNotification(t('未找到可上传媒体,请检查后发送', 'No media uploaded, please review'), '#F59E0B', 3000);
}
return;
}
if (attempts >= maxAttempts) {
clearInterval(timer);
showNotification(t('自动导入 Instagram 内容超时,请手动检查', 'Instagram import timed out, please check manually'), '#E0245E', 3000);
}
}, 500);
});
}
function startTikTokToXAutofill() {
if (!chrome.storage || !chrome.storage.local) return;
chrome.storage.local.get([TIKTOK_TO_X_STORAGE_KEY, TIKTOK_TO_X_DONE_KEY], (data) => {
const payload = data[TIKTOK_TO_X_STORAGE_KEY];
const doneId = data[TIKTOK_TO_X_DONE_KEY];
if (!payload || !payload.id) return;
if (doneId && doneId === payload.id) return;
const age = Date.now() - (payload.createdAt || 0);
if (age > 30 * 60 * 1000) {
chrome.storage.local.remove(TIKTOK_TO_X_STORAGE_KEY);
return;
}
let attempts = 0;
const maxAttempts = 90;
let textDone = false;
let mediaDone = false;
let finalUploadResult = null;
const timer = setInterval(async () => {
attempts += 1;
const composerRoot = getPreferredXComposerRoot();
const textNode = getXComposerTextNode(composerRoot);
const fileInput = getXComposerFileInput(composerRoot, { preferVideo: true });
if (!textDone && textNode) {
textDone = setComposerText(textNode, payload.description || '');
}
if (!mediaDone && fileInput) {
mediaDone = true;
const uploadOptions = {
maxItems: 1,
filenamePrefix: 'tiktok_video',
forcedMime: 'video/mp4',
forcedExt: 'mp4',
maxBytesPerFile: 512 * 1024 * 1024,
requireVideoMp4: true,
strictMp4Signature: false,
fallbackMime: 'video/mp4'
};
if (payload.mediaDataUrl) {
finalUploadResult = await uploadDataUrlsToX(fileInput, [payload.mediaDataUrl], uploadOptions);
if (!finalUploadResult || finalUploadResult.uploaded === 0) {
finalUploadResult = await uploadInsMediaToX(fileInput, (payload.mediaUrls || []).slice(0, 1), uploadOptions);
}
} else {
// TikTok often returns octet-stream/blob source in browser context.
// Force mp4 metadata so X web composer recognizes it as video.
finalUploadResult = await uploadInsMediaToX(fileInput, (payload.mediaUrls || []).slice(0, 1), uploadOptions);
}
}
if (textDone && mediaDone) {
clearInterval(timer);
markTikTokToXDone(payload.id);
const uploaded = finalUploadResult && typeof finalUploadResult.uploaded === 'number'
? finalUploadResult.uploaded
: 0;
const total = finalUploadResult && typeof finalUploadResult.total === 'number'
? finalUploadResult.total
: 0;
const rejected = finalUploadResult && typeof finalUploadResult.rejected === 'number'
? finalUploadResult.rejected
: 0;
const invalidFormat = finalUploadResult && typeof finalUploadResult.invalidFormat === 'number'
? finalUploadResult.invalidFormat
: 0;
if (uploaded === total && total > 0) {
showNotification(t('已自动填充并上传 TikTok 视频到 X', 'TikTok content filled and video uploaded to X'), '#17BF63', 2800);
} else if (invalidFormat > 0) {
showNotification(t('获取到的 TikTok 资源不是可上传 MP4,请手动下载后上传', 'TikTok resource is not a valid MP4. Please download and upload manually'), '#F59E0B', 3800);
} else if (rejected > 0) {
showNotification(t('视频体积超过 X 限制,请压缩后手动上传', 'Video exceeds X size limit, please compress and upload manually'), '#F59E0B', 3600);
} else if (total > 0) {
showNotification(t('视频未自动上传成功,请手动上传后发送', 'Video upload did not complete, please upload manually'), '#F59E0B', 3200);
} else {
showNotification(t('未找到可上传视频,请手动上传后发送', 'No uploadable video found, please upload manually'), '#F59E0B', 3200);
}
return;
}
if (attempts >= maxAttempts) {
clearInterval(timer);
showNotification(t('自动导入 TikTok 内容超时,请手动检查', 'TikTok import timed out, please check manually'), '#E0245E', 3200);
}
}, 500);
});
}
function extractTweetId(tweetUrl) {
if (!tweetUrl) return null;
try {
const parsed = new URL(tweetUrl, location.origin);
const match = parsed.pathname.match(/\/status\/(\d+)/);
return match ? match[1] : null;
} catch (error) {
const match = String(tweetUrl).match(/\/status\/(\d+)/);
return match ? match[1] : null;
}
}
function pickBestMp4FromVariants(variants) {
if (!Array.isArray(variants) || variants.length === 0) {
return null;
}
const mp4s = variants
.filter((item) => item && (item.content_type === 'video/mp4' || item.type === 'video/mp4'))
.map((item) => ({
url: item.url || item.src,
bitrate: typeof item.bitrate === 'number' ? item.bitrate : 0
}))
.filter((item) => !!item.url);
if (mp4s.length === 0) return null;
mp4s.sort((a, b) => b.bitrate - a.bitrate);
return mp4s[0].url;
}
async function fetchVideoUrlFromReactTweetApi(tweetId) {
if (!tweetId) return null;
const apiUrl = `${REACT_TWEET_API_BASE_URL}${tweetId}`;
try {
const response = await fetch(apiUrl);
if (!response.ok) return null;
const json = await response.json();
const data = json && json.data;
if (!data) return null;
// Priority: mediaDetails.video_info.variants -> video.variants
if (Array.isArray(data.mediaDetails)) {
for (const media of data.mediaDetails) {
const best = pickBestMp4FromVariants(media && media.video_info && media.video_info.variants);
if (best) return best;
}
}
const bestFromVideo = pickBestMp4FromVariants(data.video && data.video.variants);
if (bestFromVideo) return bestFromVideo;
return null;
} catch (error) {
return null;
}
}
function findVideoSourceInTweet(tweetContainer) {
const videoEl = tweetContainer.querySelector('video');
if (!videoEl) {
return null;
}
const candidates = [];
if (videoEl.currentSrc) candidates.push(videoEl.currentSrc);
if (videoEl.src) candidates.push(videoEl.src);
videoEl.querySelectorAll('source').forEach((source) => {
if (source.src) candidates.push(source.src);
});
const unique = Array.from(new Set(candidates.filter(Boolean)));
if (unique.length === 0) {
return null;
}
const direct = unique.find((url) => /\.(mp4|webm)(\?|$)/i.test(url) || url.startsWith('blob:'));
return direct || unique[0];
}
function downloadBlob(blob, filename) {
const link = document.createElement('a');
const objectUrl = URL.createObjectURL(blob);
link.href = objectUrl;
link.download = filename;
document.body.appendChild(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(objectUrl), 3000);
}
function triggerBrowserDownload(url, filename) {
return new Promise((resolve) => {
if (!chrome.runtime || !chrome.runtime.sendMessage) {
resolve({ ok: false, error: 'runtime unavailable' });
return;
}
chrome.runtime.sendMessage(
{
type: 'DOWNLOAD_VIDEO_URL',
url,
filename
},
(response) => {
if (chrome.runtime.lastError) {
resolve({ ok: false, error: chrome.runtime.lastError.message });
return;
}
resolve(response || { ok: false, error: 'empty response' });
}
);
});
}
async function downloadVideoFromTweet(menuButton) {
const tweetContainer = findTweetMainContent(menuButton);
if (!tweetContainer) {
showNotification(t('未找到推文容器', 'Tweet container not found'), '#E0245E');
return;
}
const tweetData = collectTweetData(tweetContainer);
const tweetId = extractTweetId(tweetData && tweetData.tweetUrl ? tweetData.tweetUrl : location.href);
const apiVideoUrl = await fetchVideoUrlFromReactTweetApi(tweetId);
const { author } = tweetData || {};
const filename = `${sanitizeFilename(author)}_${Date.now()}.mp4`;
const sourceUrl = apiVideoUrl || findVideoSourceInTweet(tweetContainer);
if (!sourceUrl) {
showNotification(t('未找到可下载的视频直链', 'No downloadable video URL found'), '#E0245E', 2600);
return;
}
showNotification(t('正在下载视频...', 'Starting video download...'));
try {
if (/\.m3u8(\?|$)/i.test(sourceUrl)) {
showNotification(t('检测到流媒体地址,暂不支持直接下载该格式', 'Detected m3u8 stream, direct download is not supported'), '#F59E0B', 2800);
return;
}
const dlResult = await triggerBrowserDownload(sourceUrl, filename);
if (dlResult && dlResult.ok) {
showNotification(t('视频下载已开始', 'Video download started'), '#17BF63');
return;
}
const response = await fetch(sourceUrl);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const blob = await response.blob();
downloadBlob(blob, filename);
showNotification(t('视频下载已开始', 'Video download started'), '#17BF63');
} catch (error) {
console.error('Video download failed:', error);
showNotification(t('视频下载失败,可能受跨域或源格式限制', 'Video download failed (CORS or source format limitation)'), '#E0245E', 2800);
}
}
function setupVideoDownloadProgressListener() {
if (!chrome.runtime || !chrome.runtime.onMessage) {
return;
}
chrome.runtime.onMessage.addListener((message) => {
if (!message || message.type !== 'VIDEO_DOWNLOAD_PROGRESS') {
return;
}
if (message.state === 'complete') {
updateVideoProgressToast(t('视频下载完成', 'Video download complete'), '#17BF63', 1800);
return;
}
if (message.state === 'interrupted') {
const reason = message.error ? (isZhLanguage() ? `(${message.error})` : ` (${message.error})`) : '';
updateVideoProgressToast(`${t('视频下载失败', 'Video download failed')}${reason}`, '#E0245E', 2600);
return;
}
const received = typeof message.bytesReceived === 'number' ? message.bytesReceived : 0;
const total = typeof message.totalBytes === 'number' ? message.totalBytes : 0;
if (total > 0) {
const percent = Math.max(0, Math.min(100, Math.floor((received / total) * 100)));
updateVideoProgressToast(`${t('视频下载中', 'Downloading video')} ${percent}%`, '#1DA1F2');
return;
}
if (received > 0) {
const mb = (received / (1024 * 1024)).toFixed(1);
updateVideoProgressToast(`${t('视频下载中', 'Downloading video')} ${mb}MB`, '#1DA1F2');
return;
}
updateVideoProgressToast(`${t('视频下载中', 'Downloading video')}...`, '#1DA1F2');
});
}
function blobToDataURL(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
}
function loadImageFromDataUrl(dataUrl) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = dataUrl;
});
}
async function normalizeInstagramImageTopAnchored(dataUrl) {
// Instagram feed max portrait is 4:5. If image is taller than that,
// crop from the top instead of center to keep the "start" of content.
const MIN_RATIO = 4 / 5;
try {
const img = await loadImageFromDataUrl(dataUrl);
const width = img.naturalWidth || img.width;
const height = img.naturalHeight || img.height;
if (!width || !height) return { dataUrl, wasTopCropped: false };
const ratio = width / height;
if (ratio >= MIN_RATIO) {
return { dataUrl, wasTopCropped: false };
}
const targetHeight = Math.floor(width / MIN_RATIO);
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = targetHeight;
const ctx = canvas.getContext('2d');
if (!ctx) return { dataUrl, wasTopCropped: false };
// Top-aligned draw: keep top area, cut from the bottom.
ctx.drawImage(img, 0, 0, width, targetHeight, 0, 0, width, targetHeight);
return {
dataUrl: canvas.toDataURL('image/png'),
wasTopCropped: true
};
} catch (error) {
return { dataUrl, wasTopCropped: false };
}
}
async function splitTallImageForXhs(dataUrl) {
try {
const img = await loadImageFromDataUrl(dataUrl);
const width = img.naturalWidth || img.width;
const height = img.naturalHeight || img.height;
if (!width || !height) return [dataUrl];
if (height <= width * XHS_SPLIT_HEIGHT_RATIO) {
return [dataUrl];
}
const midpoint = Math.floor(height / 2);
const overlap = Math.min(XHS_SPLIT_OVERLAP_PX, Math.floor(height * 0.08));
const slices = [
{ startY: 0, endY: Math.min(height, midpoint + overlap) },
{ startY: Math.max(0, midpoint - overlap), endY: height }
];
return slices.map(({ startY, endY }) => {
const sliceHeight = Math.max(1, endY - startY);
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = sliceHeight;
const ctx = canvas.getContext('2d');
if (!ctx) {
return dataUrl;
}
ctx.drawImage(img, 0, startY, width, sliceHeight, 0, 0, width, sliceHeight);
return canvas.toDataURL('image/png');
});
} catch (error) {
return [dataUrl];
}
}
async function fetchImageAsDataUrl(url) {
try {
const response = await fetch(url);
if (!response.ok) {
return null;
}
const blob = await response.blob();
return await blobToDataURL(blob);
} catch (error) {
return null;
}
}
function normalizeTweetImageUrl(url) {
if (!url) return null;
try {
const parsed = new URL(url, location.origin);
if (parsed.searchParams.has('name')) {
parsed.searchParams.set('name', 'large');
}
return parsed.toString();
} catch (error) {
return url;
}
}
async function collectTweetImageDataUrls(tweetContainer) {
const imageNodes = Array.from(tweetContainer.querySelectorAll('div[data-testid="tweetPhoto"] img'));
const rawUrls = imageNodes
.map((img) => img.currentSrc || img.src)
.filter(Boolean)
.map(normalizeTweetImageUrl);
const uniqueUrls = Array.from(new Set(rawUrls)).slice(0, 8);
const results = [];
for (const imageUrl of uniqueUrls) {
const dataUrl = await fetchImageAsDataUrl(imageUrl);
if (dataUrl) {
results.push(dataUrl);
}
}
return results;
}
function openXhsPublishPage() {
return new Promise((resolve) => {