-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDownload Weibo Images & videos.user.js
1865 lines (1842 loc) · 102 KB
/
Download Weibo Images & videos.user.js
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
// ==UserScript==
// @name Download Weibo Images & Videos (Only support new version weibo UI)
// @name:zh-CN 下载微博图片和视频(仅支持新版界面)
// @version 1.3.5
// @description Download images and videos from new version weibo UI webpage.
// @description:zh-CN 从新版微博界面下载图片和视频。
// @author OWENDSWANG
// @match https://weibo.com/*
// @match https://www.weibo.com/*
// @match https://s.weibo.com/weibo*
// @match https://s.weibo.com/realtime*
// @match https://s.weibo.com/video*
// @exclude https://weibo.com/tv/*
// @exclude https://www.weibo.com/tv/*
// @exclude https://weibo.com/p/*
// @exclude https://www.weibo.com/p/*
// @icon https://weibo.com/favicon.ico
// @license MIT
// @homepage https://greasyfork.org/scripts/430877
// @supportURL https://github.com/owendswang/Download-Weibo-Images-Videos
// @grant GM_xmlhttpRequest
// @grant GM_notification
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @grant GM_cookie
// @connect weibo.com
// @connect www.weibo.com
// @connect sinaimg.cn
// @connect weibocdn.com
// @connect localhost
// @namespace http://tampermonkey.net/
// @run-at document-end
// @require https://cdnjs.cloudflare.com/ajax/libs/jszip/3.9.1/jszip.min.js
// @downloadURL https://update.greasyfork.org/scripts/430877/Download%20Weibo%20Images%20%20Videos%20%28Only%20support%20new%20version%20weibo%20UI%29.user.js
// @updateURL https://update.greasyfork.org/scripts/430877/Download%20Weibo%20Images%20%20Videos%20%28Only%20support%20new%20version%20weibo%20UI%29.meta.js
// ==/UserScript==
(function() {
'use strict';
const settingVersion = 1;
let text = [];
let text_zh = [
/*0*/ '添加下载按钮',
/*1*/ '欢迎使用“下载微博图片”脚本',
/*2*/ '请选择添加下载按钮的方式:',
/*3*/ '点击“添加下载按钮”来添加下载按钮。',
/*4*/ '当鼠标位于浏览器页面时添加下载按钮,但这种方式会占用很多CPU资源。',
/*5*/ '确定',
/*6*/ '下载设置',
/*7*/ '下载文件名称',
/*8*/ '{original} - 原文件名\n{username} - 原博主名称\n{userid} - 原博主ID\n{mblogid} - 原博mblogid\n{uid} - 原博uid\n{ext} - 文件后缀\n{index} - 图片序号\n{YYYY} {MM} {DD} {HH} {mm} {ss} - 原博发布时\n间的年份、月份、日期、小时、分钟、秒,可\n分开独立使用\n{content} - 博文内容(最多前25个字符)',
/*9*/ '下载队列',
/*10*/ '重试',
/*11*/ '关闭',
/*12*/ '取消',
/*13*/ '打包下载',
/*14*/ '打包文件名',
/*15*/ '与“下载文件名称”规则相同,但{original}、{ext}、{index}除外',
/*16*/ '单独设置转发微博下载文件名称',
/*17*/ '转发微博下载文件名称',
/*18*/ '除“下载文件名”规则外,额外标签如下:\n{re.mblogid} - 转博mblogid\n{re.username} - 转发博主名称\n{re.userid} - 转发博主ID\n{re.uid} - 转博uid\n{re.content} - 转发博文内容(最多前25个字符)\n{re.YYYY} {re.MM} {re.DD} {re.HH} {re.mm} {re.ss}\n - 原博发布时间的年份、月份、日期、小时、\n分钟、秒,可分开独立使用',
/*19*/ '转发微博打包文件名',
/*20*/ '与“转发微博下载文件名称”规则相同,但{original}、{ext}、{index}除外',
/*21*/ '使用Aria2c远程下载',
/*22*/ 'RPC接口地址',
/*23*/ '使用此方式下载,无法使用打包功能,无法在页面右下角显示下载进度和结果。',
/*24*/ '如果接口地址不是localhost,需手动将地址添加到XHR白名单。',
/*25*/ '设置',
/*26*/ '<b>注意</b>:',
/*27*/ '启用“打包下载”时,需区分多文件名称,\n避免重复而导致打包后只有一个文件,文件命\n名时,必须包含{original}、{index}中至少一个\n标签。',
/*28*/ '下载视频封面',
/*29*/ '下载无水印图片',
/*30*/ '图片质量会下降',
/*31*/ '隐藏页面上的设置按钮',
/*32*/ '可在浏览器扩展Tampermonkey下拉菜单中打开\n设置窗口。',
];
let text_en = [
/*0*/ 'Add Download Buttons',
/*1*/ 'Welcome Using \'Download Weibo Images\' Script',
/*2*/ 'Which way do you like to add download buttons to each weibo post?',
/*3*/ 'Click \'Add Download Buttons\' button to add download buttons.',
/*4*/ 'When mouse over browser page, add download buttons automatically. But it takes a lot of CPU usage.',
/*5*/ 'OK',
/*6*/ 'Download Setting',
/*7*/ 'Download File Name',
/*8*/ '{original} - Original file name\n{username} - Original user name\n{userid} - Original user ID\n{mblogid} - Original mblogid\n{uid} - Original uid\n{ext} - File extention\n{index} - Image index\n{YYYY} {MM} {DD} {HH} {mm} {ss} - "Year", \n"Month", "Date", "Hour", "Minute", "Second" \nof the created time of the original post\n{content} - Original post content (limited to \nfirst 25 characters)',
/*9*/ 'Download Queue',
/*10*/ 'Retry',
/*11*/ 'Close',
/*12*/ 'Cancel',
/*13*/ 'Pack download files as a ZIP file',
/*14*/ 'ZIP File Name',
/*15*/ 'The same rules as "Download File Name" except {original}, {ext} and {index}',
/*16*/ 'Different File Name for Retweets',
/*17*/ 'Retweet Download File Name',
/*18*/ 'Except the rules for "Download File Name", there are additional tags as below.\n{re.mblogid} - Retweet mblogid\n{re.username} - Retweet user name\n{re.userid} - Retweet user ID\n{re.uid} - Retweet uid\n{re.content} - Retweet post content (limited to first 25 characters)\n{re.YYYY} {re.MM} {re.DD} {re.HH} {re.mm} {re.ss} - "Year", "Month", "Date", "Hour", "Minute", "Second" of the created time of the retweet post',
/*19*/ 'Retweet Zip File Name',
/*20*/ 'The same rules as "Retweet Download File Name" except {original}, {ext} and {index}',
/*21*/ 'Use Aria2c remote download API',
/*22*/ 'RPC Url',
/*23*/ 'In this mode, You would not be able to download in ZIP mode and to observe download progress and result.',
/*24*/ 'If it\'s not \'localhost\', you would have to add it to \'XHR white list\'.',
/*25*/ 'Settings',
/*26*/ '<b>Attention</b>: ',
/*27*/ 'When \'ZIP mode\' enabled, you have \nto include one of the tags {original} or {index} \nto avoid duplicated ones being overwritten.',
/*28*/ 'Download video cover image',
/*29*/ 'Download Images without watermarks',
/*30*/ 'Image quality is lower than those \nwith watermarks',
/*31*/ 'Hide \'Settings\' button on the web page',
/*32*/ '\'Settings\' modal could be called \nout by click on the dropdown menu of \nTampermoneky extension.',
];
if(navigator.language.substr(0, 2) == 'zh') {
text = text_zh;
} else {
text = text_en;
}
let downloadQueueCard = document.createElement('div');
downloadQueueCard.style.position = 'fixed';
downloadQueueCard.style.bottom = '0.5rem';
downloadQueueCard.style.left = '0.5rem';
downloadQueueCard.style.maxHeight = '50vh';
downloadQueueCard.style.overflowY = 'auto';
downloadQueueCard.style.overflowX = 'hidden';
let downloadQueueTitle = document.createElement('div');
downloadQueueTitle.textContent = text[9];
downloadQueueTitle.style.fontSize = '0.8rem';
downloadQueueTitle.style.color = 'gray';
downloadQueueTitle.style.display = 'none';
downloadQueueCard.appendChild(downloadQueueTitle);
document.body.appendChild(downloadQueueCard);
let progressBar = document.createElement('div');
progressBar.style.height = '1.4rem';
progressBar.style.width = '23rem';
// progressBar.style.background = 'linear-gradient(to right, red 100%, transparent 100%)';
progressBar.style.borderStyle = 'solid';
progressBar.style.borderWidth = '0.1rem';
progressBar.style.borderColor = 'grey';
progressBar.style.borderRadius = '0.5rem';
progressBar.style.boxSizing = 'content-box';
progressBar.style.marginTop = '0.5rem';
progressBar.style.marginRight = '1rem';
progressBar.style.position = 'relative';
let progressText = document.createElement('div');
// progressText.textContent = 'test.test';
progressText.style.mixBlendMode = 'screen';
progressText.style.width = '100%';
progressText.style.textAlign = 'center';
progressText.style.color = 'orange';
progressText.style.fontSize = '0.7rem';
progressText.style.lineHeight = '1.4rem';
progressText.style.overflow = 'hidden';
progressBar.appendChild(progressText);
let progressCloseBtn = document.createElement('button');
progressCloseBtn.style.border = 'unset';
progressCloseBtn.style.background = 'unset';
progressCloseBtn.style.color = 'orange';
progressCloseBtn.style.position = 'absolute';
progressCloseBtn.style.right = '0';
progressCloseBtn.style.top = '0.1rem';
progressCloseBtn.style.fontSize = '1rem';
progressCloseBtn.style.lineHeight = '1rem';
progressCloseBtn.style.cursor = 'pointer';
progressCloseBtn.textContent = '×';
progressCloseBtn.title = text[12];
progressCloseBtn.onmouseover = function(e){
this.style.color = 'red';
}
progressCloseBtn.onmouseout = function(e){
this.style.color = 'orange';
}
progressBar.appendChild(progressCloseBtn);
// downloadQueueCard.appendChild(progressBar);
function saveAs(blob, name) {
const link = document.createElement("a");
link.style.display = "none";
link.href = URL.createObjectURL(blob);
link.download = name;
link.target = '_blank';
document.body.appendChild(link);
link.click();
const timeout = setTimeout(() => {
URL.revokeObjectURL(link.href);
link.parentNode.removeChild(link);
}, 1000);
}
function send2Aria2c(url, fileName, headerFlag) {
// console.log(downloadUrl);
return new Promise(function(resolve, reject) {
GM_cookie.list({ url: '.weibo.com' }, function(cookies, error) {
if (error) {
console.error(error);
} else {
// console.log(cookies);
let header = [ 'User-Agent: ' + window.navigator.userAgent ];
if (headerFlag) {
header.push('Referer: https://' + location.host);
header.push('Origin: https://' + location.host);
}
if (cookies && cookies.length > 0) {
header.push('Cookie: ' + cookies.map((cookie) => (cookie.name + '=' + cookie.value)).join('; '));
}
downloadQueueTitle.style.display = 'block';
let progress = downloadQueueCard.appendChild(progressBar.cloneNode(true));
progress.firstChild.textContent = fileName;
GM_xmlhttpRequest({
method: 'POST',
url: GM_getValue('ariaRpcUrl','http://localhost:6800/jsonrpc'),
data: JSON.stringify({
jsonrpc: '2.0',
id: 'weibo',
method: 'aria2.addUri',
params: [ [ url ], { header, out: fileName } ],
}),
headers: {"Content-Type": "application/json"},
onload: function(response) {
// console.log(response.responseText);
progress.style.background = 'green';
const timeout = setTimeout(() => {
progress.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
}, 1000);
progress.lastChild.onclick = function(e) {
clearTimeout(timeout);
this.parentNode.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
}
resolve(response);
},
onabort: function(e) { resolve(null); },
onerror: function(e) { downloadError(e, url, fileName, headerFlag, progress); resolve(null); },
ontimeout: function(e) { downloadError(e, url, fileName, headerFlag, progress); resolve(null); },
});
}
})
// 下面这种原生的方法,因为安全原因,不被浏览器允许,属于跨域,且在https页面上请求http。
/*let oReq = new XMLHttpRequest();
oReq.open("POST", GM_getValue('ariaRpcUrl','http://localhost:6800/jsonrpc'));
oReq.setRequestHeader('Content-Type', 'application/json')
oReq.onload = (e) => {
// console.log(response.responseText);
progress.style.background = 'green';
const timeout = setTimeout(() => {
progress.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
}, 1000);
progress.lastChild.onclick = function(e) {
clearTimeout(timeout);
this.parentNode.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
}
resolve(oReq.response);
};
oReq.onerror = (e) => { downloadError(e, url, fileName, headerFlag, progress); resolve(null); };
oReq.onabort = (e) => { resolve(null); };
oReq.ontimeout = (e) => { downloadError(e, url, fileName, headerFlag, progress); resolve(null); };
oReq.send(JSON.stringify({
jsonrpc: '2.0',
id: 'weibo',
method: 'aria2.addUri',
params: [ [ url ], { header, out: fileName } ],
}));
progress.lastChild.onclick = function(e) {
oReq.abort();
this.parentNode.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
};*/
});
}
function httpRequest(url, method = 'GET', data = null) {
return new Promise(function(resolve, reject) {
let oReq = new XMLHttpRequest();
oReq.open(method, url);
oReq.responseType = 'json';
oReq.onload = (e) => { resolve(oReq.response); };
oReq.onerror = (e) => { resolve(null); };
oReq.onabort = (e) => { resolve(null); };
oReq.ontimeout = (e) => { resolve(null); };
oReq.setRequestHeader('X-XSRF-TOKEN', getCookie('XSRF-TOKEN'));
if(typeof(data) === 'string') {
oReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
oReq.send(data);
} else if(typeof(data) === 'object') {
oReq.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
oReq.send(JSON.stringify(data));
} else {
oReq.send();
}
});
}
function gmHttpRequest(url, method = 'GET', data = null, ua = null) {
return new Promise(function(resolve, reject) {
// console.log(url);
let headers = {
'Referer': 'https://' + location.host,
'Origin': 'https://' + location.host,
'X-XSRF-TOKEN': getCookie('XSRF-TOKEN'),
};
if(typeof(data) === 'string') {
headers['Content-Type'] = 'application/x-www-form-urlencoded';
} else if(typeof(data) === 'object') {
headers['Content-Type'] = 'application/json;charset=UTF-8';
}
if(ua) {
headers['User-Agent'] = ua;
}
// console.log(headers)
GM_xmlhttpRequest({
method,
url,
data,
responseType: 'json',
headers,
onload: ({ status, response }) => {
// console.log(response);
resolve(response)
},
onabort: function(e) { resolve(null); },
onerror: function(e) { resolve(null); },
ontimeout: function(e) { resolve(null); },
});
});
}
function downloadError(e, url, name, headerFlag, progress, zipMode = false, ariaMode = false) {
// console.log(e, url);
/*GM_notification({
title: 'Download error',
text: 'Error: ' + e.error + '\nUrl: ' + url,
silent: true,
timeout: 3,
});*/
progress.style.background = 'red';
progress.firstChild.textContent = name + ' [' + (e.error || 'Unknown') + ']';
progress.firstChild.style.color = 'yellow';
progress.firstChild.style.mixBlendMode = 'unset';
if (!zipMode) {
let progressRetryBtn = document.createElement('button');
progressRetryBtn.style.border = 'unset';
progressRetryBtn.style.background = 'unset';
progressRetryBtn.style.color = 'yellow';
progressRetryBtn.style.position = 'absolute';
progressRetryBtn.style.right = '1.2rem';
progressRetryBtn.style.top = '0.05rem';
progressRetryBtn.style.fontSize = '1rem';
progressRetryBtn.style.lineHeight = '1rem';
progressRetryBtn.style.cursor = 'pointer';
progressRetryBtn.style.letterSpacing = '-0.2rem';
progressRetryBtn.textContent = '⤤⤦';
progressRetryBtn.title = text[10];
progressRetryBtn.onmouseover = function(e){
this.style.color = 'white';
}
progressRetryBtn.onmouseout = function(e){
this.style.color = 'yellow';
}
progressRetryBtn.onclick = function(e) {
this.parentNode.remove();
if (ariaMode) {
send2Aria2c(url, name, headerFlag);
} else {
downloadWrapper(url, name, headerFlag);
}
}
progress.insertBefore(progressRetryBtn, progress.lastChild);
}
progress.lastChild.title = text[11];
progress.lastChild.style.color = 'yellow';
progress.lastChild.onmouseover = function(e){
this.style.color = 'white';
};
progress.lastChild.onmouseout = function(e){
this.style.color = 'yellow';
};
progress.lastChild.onclick = function(e) {
this.parentNode.remove();
if(progress.parent.childElementCount == 1) progress.parent.firstChild.style.display = 'none';
};
// setTimeout(() => { progress.remove(); if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none'; }, 1000);
}
function getCookie(key = null) {
let cookiesArr = document.cookie.split('; ');
let cookiesObj = {};
for (const cookie of cookiesArr) {
let [ name, value ] = cookie.split('=');
cookiesObj[name] = value;
}
if (key) {
return cookiesObj[key];
} else {
return cookiesObj;
}
}
function downloadWrapper(url, name, headerFlag = false, zipMode = false) {
// console.log(url);
downloadQueueTitle.style.display = 'block';
let progress = downloadQueueCard.appendChild(progressBar.cloneNode(true));
progress.firstChild.textContent = name + ' [0%]';
if (zipMode) {
return new Promise(function(resolve, reject) {
const download = GM_xmlhttpRequest({
method: 'GET',
url,
responseType: 'blob',
headers: headerFlag ? {
'Referer': 'https://' + location.host,
'Origin': 'https://' + location.host
} : null,
onprogress: (e) => {
// e = { int done, finalUrl, bool lengthComputable, int loaded, int position, int readyState, response, str responseHeaders, responseText, responseXML, int status, statusText, int total, int totalSize }
const percent = e.done / e.total * 100;
progress.style.background = 'linear-gradient(to right, green ' + percent + '%, transparent ' + percent + '%)';
progress.firstChild.textContent = name + ' [' + percent.toFixed(0) + '%]';
},
onload: ({ status, response }) => {
const timeout = setTimeout(() => {
progress.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
}, 1000);
progress.lastChild.onclick = function(e) {
clearTimeout(timeout);
this.parentNode.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
};
resolve(response);
},
onabort: function(e) { resolve(null); },
onerror: function(e) { downloadError(e, url, name, headerFlag, progress); resolve(null); },
ontimeout: function(e) { downloadError(e, url, name, headerFlag, progress); resolve(null); },
});
progress.lastChild.onclick = function(e) {
download.abort();
this.parentNode.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
};
// 下面这种原生的方法,可以正常下载非V+的资源,遇到V+的资源会报错。
/*let oReq = new XMLHttpRequest();
oReq.open("GET", url);
oReq.responseType = 'blob';
oReq.onprogress = (e) => {
// console.log(e);
const percent = e.loaded / e.total * 100;
progress.style.background = 'linear-gradient(to right, green ' + percent + '%, transparent ' + percent + '%)';
progress.firstChild.textContent = name + ' [' + percent.toFixed(0) + '%]';
};
oReq.onload = (e) => {
const timeout = setTimeout(() => {
progress.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
}, 1000);
progress.lastChild.onclick = function(e) {
clearTimeout(timeout);
this.parentNode.remove();
oReq.abort();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
};
resolve(oReq.response);
};
oReq.onerror = (e) => { downloadError(e, url, name, headerFlag, progress); resolve(null); };
oReq.onabort = (e) => { resolve(null); };
oReq.ontimeout = (e) => { downloadError(e, url, name, headerFlag, progress); resolve(null); };
oReq.send();
progress.lastChild.onclick = function(e) {
this.parentNode.remove();
oReq.abort();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
};*/
});
} else {
/*const download = GM_download({
url,
name,
headers: headerFlag ? {
'Referer': 'https://' + location.host,
'Origin': 'https://' + location.host
} : null,
onprogress: (e) => {
// e = { int done, finalUrl, bool lengthComputable, int loaded, int position, int readyState, response, str responseHeaders, responseText, responseXML, int status, statusText, int total, int totalSize }
const percent = e.done / e.total * 100;
progress.style.background = 'linear-gradient(to right, green ' + percent + '%, transparent ' + percent + '%)';
progress.firstChild.textContent = name + ' [' + percent.toFixed(0) + '%]';
},
onload: ({ status, response }) => {
const timeout = setTimeout(() => {
progress.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
}, 1000);
progress.lastChild.onclick = function(e) {
clearTimeout(timeout);
this.parentNode.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
}
},
onerror: (e) => { downloadError(e, url, name, headerFlag, progress); },
ontimeout: (e) => { downloadError(e, url, name, headerFlag, progress); },
});
progress.lastChild.onclick = function(e) {
download.abort();
this.parentNode.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
};*/
// 这个方法也可以,而且不是走GM_download,不会被油猴设置里的下载选项影响。
const download = GM_xmlhttpRequest({
method: 'GET',
url,
responseType: 'blob',
headers: headerFlag ? {
'Referer': 'https://' + location.host,
'Origin': 'https://' + location.host
} : null,
onprogress: (e) => {
// e = { int done, finalUrl, bool lengthComputable, int loaded, int position, int readyState, response, str responseHeaders, responseText, responseXML, int status, statusText, int total, int totalSize }
const percent = e.done / e.total * 100;
progress.style.background = 'linear-gradient(to right, green ' + percent + '%, transparent ' + percent + '%)';
progress.firstChild.textContent = name + ' [' + percent.toFixed(0) + '%]';
},
onload: ({ status, response }) => {
const timeout = setTimeout(() => {
progress.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
}, 1000);
progress.lastChild.onclick = function(e) {
clearTimeout(timeout);
this.parentNode.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
};
saveAs(response, name);
},
});
progress.lastChild.onclick = function(e) {
download.abort();
this.parentNode.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
};
// 下面这种原生的方法,可以正常下载非V+的资源,遇到V+的资源会报错。
/*let oReq = new XMLHttpRequest();
oReq.open("GET", url);
oReq.responseType = 'blob';
oReq.onprogress = (e) => {
// console.log(e);
const percent = e.loaded / e.total * 100;
progress.style.background = 'linear-gradient(to right, green ' + percent + '%, transparent ' + percent + '%)';
progress.firstChild.textContent = name + ' [' + percent.toFixed(0) + '%]';
};
oReq.onload = (e) => {
const timeout = setTimeout(() => {
progress.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
}, 1000);
progress.lastChild.onclick = function(e) {
clearTimeout(timeout);
this.parentNode.remove();
oReq.abort();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
};
saveAs(oReq.response, name);
};
oReq.onerror = (e) => { downloadError(e, url, name, headerFlag, progress); };
oReq.ontimeout = (e) => { downloadError(e, url, name, headerFlag, progress); };
oReq.send();
progress.lastChild.onclick = function(e) {
this.parentNode.remove();
oReq.abort();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
};*/
// 下面fetch的方法,感觉不是很好写,所以就不用下面的方法。
/*(async function () {
let controller = new AbortController();
const response = await fetch(url, { signal: controller.signal });
progress.lastChild.onclick = function(e) {
controller.abort();
this.parentNode.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
}
const contentLength = response.headers.get('content-length');
const total = parseInt(contentLength, 10);
let loaded = 0;
const reader = response.body.getReader();
const res = new Response(new ReadableStream({
async start(controller) {
while(true) {
const { done, value } = await reader.read();
if (value) loaded += value.length;
const percent = loaded / total * 100;
progress.style.background = 'linear-gradient(to right, green ' + percent + '%, transparent ' + percent + '%)';
progress.firstChild.textContent = name + ' [' + percent.toFixed(0) + '%]';
if (done) {
break;
controller.close();
}
}
}
}));
const blob = await res.blob();
const link = document.createElement("a");
link.style.display = "none";
link.href = URL.createObjectURL(blob);
link.download = name;
link.target = '_blank';
document.body.appendChild(link);
link.click();
progress.style.background = 'green';
const timeout = setTimeout(() => {
progress.remove();
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
URL.revokeObjectURL(link.href);
link.parentNode.removeChild(link);
}, 1000);
progress.lastChild.onclick = function(e) {
clearTimeout(timeout);
this.parentNode.remove();
URL.revokeObjectURL(link.href);
link.parentNode.removeChild(link);
if(downloadQueueCard.childElementCount == 1) downloadQueueTitle.style.display = 'none';
}
})();*/
}
}
function getName(nameSetting, originalName, ext, userName, userId, postId, postUid, index, postTime, content, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetContent) {
let setName = nameSetting;
setName = setName.replace('{ext}', ext);
setName = setName.replace('{original}', originalName);
setName = setName.replace('{username}', userName);
setName = setName.replace('{userid}', userId);
setName = setName.replace('{mblogid}', postId);
setName = setName.replace('{uid}', postUid);
setName = setName.replace('{index}', index);
setName = setName.replace('{content}', content.substring(0, 25));
let YYYY, MM, DD, HH, mm, ss;
const postAt = new Date(postTime);
if (postTime) {
YYYY = postAt.getFullYear().toString();
MM = (postAt.getMonth() + 1).toString().padStart(2, '0');
DD = postAt.getDate().toString().padStart(2, '0');
HH = postAt.getHours().toString().padStart(2, '0');
mm = postAt.getMinutes().toString().padStart(2, '0');
ss = postAt.getSeconds().toString().padStart(2, '0');
}
setName = setName.replace('{YYYY}', YYYY);
setName = setName.replace('{MM}', MM);
setName = setName.replace('{DD}', DD);
setName = setName.replace('{HH}', HH);
setName = setName.replace('{mm}', mm);
setName = setName.replace('{ss}', ss);
if (retweetPostId && GM_getValue('retweetMode', false)) {
setName = setName.replace('{re.mblogid}', retweetPostId);
setName = setName.replace('{re.username}', retweetUserName);
setName = setName.replace('{re.userid}', retweetUserId);
setName = setName.replace('{re.uid}', retweetPostUid);
setName = setName.replace('{re.content}', retweetContent.substring(0, 25));
let reYYYY, reMM, reDD, reHH, remm, ress;
const retweetPostAt = new Date(retweetPostTime);
if (retweetPostTime) {
reYYYY = retweetPostAt.getFullYear().toString();
reMM = (retweetPostAt.getMonth() + 1).toString().padStart(2, '0');
reDD = retweetPostAt.getDate().toString().padStart(2, '0');
reHH = retweetPostAt.getHours().toString().padStart(2, '0');
remm = retweetPostAt.getMinutes().toString().padStart(2, '0');
ress = retweetPostAt.getSeconds().toString().padStart(2, '0');
}
setName = setName.replace('{re.YYYY}', reYYYY);
setName = setName.replace('{re.MM}', reMM);
setName = setName.replace('{re.DD}', reDD);
setName = setName.replace('{re.HH}', reHH);
setName = setName.replace('{re.mm}', remm);
setName = setName.replace('{re.ss}', ress);
}
return setName.replace(/[<|>|*|"|\/|\|:|?|\n]/g, '_');
}
function handleDownloadList(downloadList, packName) {
if (GM_getValue('ariaMode', false)) {
for (const item of downloadList) {
send2Aria2c(item.url, item.name, item.headerFlag);
}
} else if (GM_getValue('zipMode', false)) {
let zip = new JSZip();
// console.log('zip', zip);
let promises = downloadList.map(async function(ele, idx) {
return await downloadWrapper(ele.url, ele.name, ele.headerFlag, true).then(function(data) {
// console.log(ele, idx, 'data', data);
const currDate = new Date();
const dateWithOffset = new Date(currDate.getTime() - currDate.getTimezoneOffset() * 60000);
if (data) zip.file(downloadList[idx].name, data, { date: dateWithOffset });
});
});
// console.log('promises', promises);
Promise.all(promises).then(async function(responseList) {
// console.log('responseList', responseList);
// console.log('zip', zip);
// console.log('generateAsync', zip.generateAsync());
const content = await zip.generateAsync({ type: 'blob', streamFiles: true }/*, function({ percent, currentFile }) { console.log(percent); }*/);
// console.log('content', content);
if (zip.files && Object.keys(zip.files).length > 0) saveAs(content, packName);
});
} else {
for (const item of downloadList) {
downloadWrapper(item.url, item.name, item.headerFlag);
}
}
}
async function handleVideo(mediaInfo, padLength, userName, userId, postId, postUid, index, postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText) {
const newList = [];
let largeVidUrl = mediaInfo.playback_list ? mediaInfo.playback_list[0].play_info.url : ( mediaInfo.mp4_hd_url || mediaInfo.stream_url_hd || mediaInfo.stream_url );
if(mediaInfo.hasOwnProperty('h5_url') && mediaInfo.h5_url) {
const urlObj = new URL(mediaInfo.h5_url); // e.g. 'https://video.weibo.com/show?fid=1034:4924511439749139'
const fid = urlObj.searchParams.get('fid');
let url = 'https://' + location.host + '/tv/api/component?page=/tv/show/' + fid; // e.g. 'https://weibo.com/tv/api/component?page=/tv/show/1034:4924511439749139'
// let url = 'https://h5.video.weibo.com/api/component?page=/show/' + fid; // e.g. 'https://h5.video.weibo.com/api/component?page=/show/1034:5070572795658319'
let data = 'data={"Component_Play_Playinfo":{"oid":"' + fid + '"}}'; // e.g. 'data={"Component_Play_Playinfo":{"oid":"1034:4924511439749139"}}'
// console.log(url, data);
let tvRes = await gmHttpRequest(url, 'POST', data);
// console.log(tvRes);
if(tvRes && tvRes.data && tvRes.data.Component_Play_Playinfo && tvRes.data.Component_Play_Playinfo.urls && Object.keys(tvRes.data.Component_Play_Playinfo.urls).length > 0) {
largeVidUrl = tvRes.data.Component_Play_Playinfo.urls[Object.keys(tvRes.data.Component_Play_Playinfo.urls)[0]];
if(largeVidUrl.startsWith('//')) {
largeVidUrl = 'http:' + largeVidUrl;
}
}
}
// console.log(largeVidUrl);
let vidName = largeVidUrl.split('?')[0];
vidName = vidName.split('/')[vidName.split('/').length - 1].split('?')[0];
let originalName = vidName.split('.')[0];
let ext = vidName.split('.')[1];
const setName = getName((GM_getValue('retweetMode', false) && retweetPostId) ? GM_getValue('retweetFileName', '{original}.{ext}') : GM_getValue('dlFileName', '{original}.{ext}'), originalName, ext, userName, userId, postId, postUid, index.toString().padStart(padLength, '0'), postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText);
newList.push({ url: largeVidUrl, name: setName, headerFlag: true });
if(GM_getValue('dlVidCov', true) && mediaInfo.hasOwnProperty('big_pic_info')) {
let picUrl = mediaInfo.big_pic_info.pic_big.url;
let largePicUrl = picUrl.replace('/orj480/', GM_getValue('rmWtrMrk', false) ? '/oslarge/' : '/large/');
let picName = largePicUrl.split('/')[largePicUrl.split('/').length - 1].split('?')[0];
let originalName = picName.split('.')[0];
let ext = picName.split('.')[1];
const setName = getName((GM_getValue('retweetMode', false) && retweetPostId) ? GM_getValue('retweetFileName', '{original}.{ext}') : GM_getValue('dlFileName', '{original}.{ext}'), originalName, ext, userName, userId, postId, postUid, index.toString().padStart(padLength, '0'), postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText);
newList.push({url: largePicUrl, name: setName, headerFlag: true });
}
return newList;
}
function handlePic(pic, padLength, userName, userId, postId, postUid, index, postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText) {
let newList = [];
let picId = pic.pic_id;
let picUrl = pic.largest?.url || pic.pic_big?.url;
let picSize = picUrl.split('/')[3];
let largePicUrl = picUrl.replace('/' + picSize + '/', GM_getValue('rmWtrMrk', false) ? '/oslarge/' : '/large/');
let downloadUrl = GM_getValue('rmWtrMrk', false) ? largePicUrl : ('https://weibo.com/ajax/common/download?pid=' + picId);
let picName = largePicUrl.split('/')[largePicUrl.split('/').length - 1].split('?')[0];
let originalName = picName.split('.')[0];
let ext = picName.split('.')[1];
const setName = getName((GM_getValue('retweetMode', false) && retweetPostId) ? GM_getValue('retweetFileName', '{original}.{ext}') : GM_getValue('dlFileName', '{original}.{ext}'), originalName, ext, userName, userId, postId, postUid, index.toString().padStart(padLength, '0'), postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText);
newList.push({ url: GM_getValue('ariaMode', false) ? largePicUrl : downloadUrl, name: setName, headerFlag: true });
if(pic.hasOwnProperty('video')) {
let videoUrl = pic.video;
let videoName = videoUrl.split('%2F')[videoUrl.split('%2F').length - 1].split('?')[0];
videoName = videoName.split('/')[videoName.split('/').length - 1].split('?')[0];
if (!videoName.includes('.')) videoName = videoUrl.split('/')[videoUrl.split('/').length - 1].split('?')[0];
// console.log(videoUrl, videoName);
let originalName = videoName.split('.')[0];
let ext = videoName.split('.')[1];
const setName = getName((GM_getValue('retweetMode', false) && retweetPostId) ? GM_getValue('retweetFileName', '{original}.{ext}') : GM_getValue('dlFileName', '{original}.{ext}'), originalName, ext, userName, userId, postId, postUid, index.toString().padStart(padLength, '0'), postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText);
newList.push({ url: videoUrl, name: setName, headerFlag: true });
}
return newList;
}
function addDlBtn(footer) {
// console.log('add download button');
let dlBtnDiv = document.createElement('div');
dlBtnDiv.className = 'woo-box-item-flex toolbar_item_1ky_D toolbar_cursor_34j5V';
let divInDiv = document.createElement('div');
divInDiv.className = 'woo-box-flex woo-box-alignCenter woo-box-justifyCenter toolbar_like_20yPI toolbar_likebox_1rLfZ toolbar_wrap_np6Ug';
let dlBtn = document.createElement('button');
dlBtn.className = 'woo-like-main toolbar_btn_Cg9tz download-button';
dlBtn.setAttribute('tabindex', '0');
dlBtn.setAttribute('title', '下载');
// dlBtn.innerHTML = '<span class="woo-like-iconWrap"><svg class="woo-like-icon"><use xlink:href="#woo_svg_download"></use></svg></span><span class="woo-like-count">下载</span>';
dlBtn.innerHTML = '<span class="woo-like-iconWrap"><i class="woo-font woo-font--imgSave woo-like-icon"></i></span><span class="woo-like-count">下载</span>';
dlBtn.addEventListener('click', async function(event) {
event.preventDefault();
const article = this.closest('article.woo-panel-main');
if(article) {
// let contentRow = article.getElementsByClassName('content_row_-r5Tk')[0];
const header = article.getElementsByTagName('header')[0];
const postLink = header.getElementsByClassName('head-info_time_6sFQg')[0];
let postId = postLink.href.split('/')[postLink.href.split('/').length - 1];
const resJson = await httpRequest('https://' + location.host + '/ajax/statuses/show?id=' + postId);
// console.log(resJson);
let status = resJson;
let retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText;
if(resJson.hasOwnProperty('retweeted_status')) {
status = resJson.retweeted_status;
retweetPostId = resJson.mblogid;
retweetUserName = resJson.user.screen_name;
retweetUserId = resJson.user.idstr;
retweetPostUid = resJson.idstr;
retweetPostTime = resJson.created_at;
retweetText = resJson.text_raw;
}
postId = status.mblogid;
const picInfos = status.pic_infos;
const picIds = status.pic_ids;
const mixMediaInfo = status.mix_media_info;
const userName = status.user.screen_name;
const userId = status.user.idstr;
const postUid = status.idstr;
const postTime = status.created_at;
const text = status.text_raw;
let downloadList = [];
if(footer.parentElement.getElementsByTagName('video').length > 0) {
// console.log('download video');
if(resJson.page_info?.media_info) {
downloadList = downloadList.concat(await handleVideo(resJson.page_info.media_info, 1, userName, userId, postId, postUid, 1, postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText));
}
/*if(resJson.page_info?.pic_info && GM_getValue('dlVidCov', true)) {
downloadList = downloadList.concat(handlePic(resJson.page_info.pic_info, 1, userName, userId, postId, postUid, 1, postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText));
}*/
}
if (picInfos) {
// console.log('download images');
let index = 0;
let padLength = Object.entries(picInfos).length.toString().length;
for (const [id, pic] of Object.entries(picInfos)) {
index += 1;
downloadList = downloadList.concat(handlePic(pic, padLength, userName, userId, postId, postUid, index, postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText));
}
}
/*if (picIds) {
// console.log('download images');
let index = 0;
let padLength = picIds.length.toString().length;
for (const picId of Object.entries(picIds)) {
index += 1;
downloadList = downloadList.concat(handlePic(picId, padLength, userName, userId, postId, postUid, index, postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText));
}
}*/
if (mixMediaInfo && mixMediaInfo.items) {
// console.log('mix media');
let index = 0;
let padLength = Object.entries(mixMediaInfo.items).length.toString().length;
for (const [id, media] of Object.entries(mixMediaInfo.items)) {
index += 1;
if(media.type === 'video') {
downloadList = downloadList.concat(await handleVideo(media.data.media_info, padLength, userName, userId, postId, postUid, index, postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText));
if (GM_getValue('dlVidCov', true)) {
downloadList = downloadList.concat(handlePic(media.data.pic_info, padLength, userName, userId, postId, postUid, index, postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText));
}
} else if (media.type === 'pic') {
downloadList = downloadList.concat(handlePic(media.data, padLength, userName, userId, postId, postUid, index, postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText));
}
}
}
const packName = getName((GM_getValue('retweetMode', false) && retweetPostId) ? GM_getValue('retweetPackFileName', '{mblogid}.zip') : GM_getValue('packFileName', '{mblogid}.zip'), '{original}', '{ext}', userName, userId, postId, postUid, '{index}', postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText);
handleDownloadList(downloadList, packName);
}
});
divInDiv.appendChild(dlBtn);
dlBtnDiv.appendChild(divInDiv);
footer.firstChild.firstChild.firstChild.appendChild(dlBtnDiv);
// console.log('added download button');
}
function addSingleDlBtn(img, idx = 0) {
// console.log(img);
const imgCtn = img.parentElement;
const dlBtn = document.createElement('div');
dlBtn.style.color = 'dimgray';
dlBtn.style.position = 'absolute';
dlBtn.style.bottom = '0';
dlBtn.style.left = '0';
dlBtn.style.backgroundColor = 'rgba(255, 255, 255, 0.4)';
dlBtn.style.padding = '0.3rem';
dlBtn.style.borderRadius = '0 8px';
dlBtn.style.width = '1rem';
dlBtn.style.height = '1rem';
dlBtn.style.cursor = 'pointer';
dlBtn.style.zIndex = '11';
dlBtn.innerHTML = '<i class="woo-font woo-font--imgSave"></i>';
dlBtn.addEventListener('mouseenter', (event) => { dlBtn.style.backgroundColor = 'rgba(255, 255, 255, 0.8)'; dlBtn.style.color = 'black'; });
dlBtn.addEventListener('mouseleave', (event) => { dlBtn.style.backgroundColor = 'rgba(255, 255, 255, 0.4)'; dlBtn.style.color = 'dimgray'; });
dlBtn.addEventListener('click', async function(event) {
event.stopPropagation();
const article = this.closest('article.woo-panel-main');
if(article) {
// let contentRow = article.getElementsByClassName('content_row_-r5Tk')[0];
const header = article.getElementsByTagName('header')[0];
const postLink = header.getElementsByClassName('head-info_time_6sFQg')[0];
let postId = postLink.href.split('/')[postLink.href.split('/').length - 1];
const resJson = await httpRequest('https://' + location.host + '/ajax/statuses/show?id=' + postId);
// console.log(resJson);
let status = resJson;
let retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText;
if(resJson.hasOwnProperty('retweeted_status')) {
status = resJson.retweeted_status;
retweetPostId = resJson.mblogid;
retweetUserName = resJson.user.screen_name;
retweetUserId = resJson.user.idstr;
retweetPostUid = resJson.idstr;
retweetPostTime = resJson.created_at;
retweetText = resJson.text_raw;
}
postId = status.mblogid;
const picInfos = status.pic_infos;
const picIds = status.pic_ids;
const mixMediaInfo = status.mix_media_info;
const userName = status.user.screen_name;
const userId = status.user.idstr;
const postUid = status.idstr;
const postTime = status.created_at;
const text = status.text_raw;
let downloadList = [];
if (picInfos) {
// console.log('download images');
let padLength = Object.entries(picInfos).length.toString().length;
// console.log(idx, picInfos);
const pic = Object.entries(picInfos)[idx][1];
downloadList = downloadList.concat(handlePic(pic, padLength, userName, userId, postId, postUid, idx + 1, postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText));
}
/*if (picIds) {
// console.log('download images');
let padLength = picIds.length.toString().length;
// console.log(idx, picInfos);
const picId = picIds[idx];
downloadList = downloadList.concat(handlePic(picId, padLength, userName, userId, postId, postUid, idx + 1, postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText));
}*/
if (mixMediaInfo && mixMediaInfo.items) {
// console.log('mix media');
// console.log(mixMediaInfo.items);
let padLength = Object.entries(mixMediaInfo.items).length.toString().length;
const media = Object.entries(mixMediaInfo.items)[idx][1];
if(media.type === 'video') {
downloadList = downloadList.concat(await handleVideo(media.data.media_info, padLength, userName, userId, postId, postUid, idx + 1, postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText));
if(GM_getValue('dlVidCov', true)) {
downloadList = downloadList.concat(handlePic(media.data.pic_info, padLength, userName, userId, postId, postUid, idx + 1, postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText));
}
} else if (media.type === 'pic') {
downloadList = downloadList.concat(handlePic(media.data, padLength, userName, userId, postId, postUid, idx + 1, postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText));
}
}
const packName = getName((GM_getValue('retweetMode', false) && retweetPostId) ? GM_getValue('retweetPackFileName', '{mblogid}.zip') : GM_getValue('packFileName', '{mblogid}.zip'), '{original}', '{ext}', userName, userId, postId, postUid, '{index}', postTime, text, retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText);
handleDownloadList(downloadList, packName);
}
});
imgCtn.appendChild(dlBtn);
}
function sAddDlBtn(footer) {
// console.log('add download button on search');
const lis = footer.getElementsByTagName('li');
for (const li of lis) {
li.style.width = '25%';
}
let dlBtnLi = document.createElement('li');
dlBtnLi.style.width = '25%';
let aInLi = document.createElement('a');
aInLi.className = 'woo-box-flex woo-box-alignCenter woo-box-justifyCenter';
aInLi.setAttribute('title', '下载');
aInLi.setAttribute('href', 'javascript:void(0);');
let dlBtn = document.createElement('button');
dlBtn.className = 'woo-like-main toolbar_btn download-button';
dlBtn.innerHTML = '<span class="woo-like-iconWrap"><svg class="woo-like-icon"><use xlink:href="#woo_svg_download"></use></svg></span><span class="woo-like-count">下载</span>';
aInLi.addEventListener('click', function(event) { event.preventDefault(); });
dlBtn.addEventListener('click', async function(event) {
// console.log('download');
event.preventDefault();
const cardWrap = this.closest('div.card-wrap');
// console.log(cardWrap);
const mid = cardWrap.getAttribute('mid');
// console.log(mid);
if(mid) {
// console.log('https://' + location.host + '/ajax/statuses/show?id=' + mid);
const resJson = await gmHttpRequest('https://weibo.com/ajax/statuses/show?id=' + mid);
// console.log(resJson);
let status = resJson;
let retweetPostId, retweetUserName, retweetUserId, retweetPostUid, retweetPostTime, retweetText;
if(resJson.hasOwnProperty('retweeted_status')) {
status = resJson.retweeted_status;
retweetPostId = resJson.mblogid;
retweetUserName = resJson.user.screen_name;
retweetUserId = resJson.user.idstr;
retweetPostUid = resJson.idstr;
retweetPostTime = resJson.created_at;
retweetText = resJson.text_raw;
}
const postId = status.mblogid;
const picInfos = status.pic_infos;
const picIds = status.pic_ids;
const mixMediaInfo = status.mix_media_info;
const userName = status.user.screen_name;
const userId = status.user.idstr;