-
Notifications
You must be signed in to change notification settings - Fork 4
/
ckylin-bilibili-unfollow.user.js
4320 lines (4290 loc) · 243 KB
/
ckylin-bilibili-unfollow.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 [Bilibili] 关注管理器
// @namespace ckylin-bilibili-foman
// @version 0.2.22
// @description 快速排序和筛选你的关注列表,一键取关不再关注的UP等
// @author CKylinMC
// @updateURL https://cdn.jsdelivr.net/gh/CKylinMC/UserJS/scripts/ckylin-bilibili-unfollow.user.js
// @supportURL https://github.com/CKylinMC/UserJS
// @require https://greasyfork.org/scripts/429720-cktools/code/CKTools.js?version=1034581
// @require https://update.greasyfork.org/scripts/470305/1216506/md5-func.js
// @include http://space.bilibili.com/*
// @include https://space.bilibili.com/*
// @connect api.bilibili.com
// @grant GM_registerMenuCommand
// @grant GM_getResourceText
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_removeValue
// @grant unsafeWindow
// @license GPL-3.0-only
// @compatible chrome 80+
// @compatible firefox 74+
// ==/UserScript==
;(function () {
'use strict';
const s = {
get(key, def) {
const val = GM_getValue(key);
if (typeof (val) == 'undefined' || val === null) return def;
return val;
},
set(key, val) {
GM_setValue(key, val);
},
del(key) {
if (typeof (GM_removeValue) == 'function') GM_removeValue(key);
else GM_setValue(key, undefined);
}
};
const datas = {
status: 0,
total: 0,
fetched: 0,
pages: 0,
followings: [],
mappings: {},
dommappings: {},
checked: [],
tags: {},
self: 0,
isSelf: false,
currUid: 0,
fetchstat: "OK",
currInfo: {
black: -1,
follower: -1,
following: -1,
mid: -1,
whisper: -1,
},
preventUserCard: false,
settings: {
get autoExtendInfo() {
return s.get('autoExtendInfo', true);
},
set autoExtendInfo(val) {
s.set('autoExtendInfo', val);
},
get lazyRenderForList() {
return s.get('lazyRenderForList', true);
},
set lazyRenderForList(val) {
s.set('lazyRenderForList', val);
},
get batchOperationDelay() {
return s.get('batchOperationDelay', .5);
},
set batchOperationDelay(val) {
s.set('batchOperationDelay', val);
},
get enableExpermentals() {
return s.get('enableExpermentals', false);
},
set enableExpermentals(val) {
return s.set('enableExpermentals', val);
},
}
};
const cfg = {
debug: !false,
retrial: 3,
enableNewModules: false,
VERSION: "0.2.22",
infobarTemplate: () => `共读取 ${datas.fetched} 条关注`,
titleTemplate: () => `<h1>关注管理器 FoMan <small>v${cfg.VERSION} ${cfg.debug ? "debug" : ""}</small> ${datas.settings.enableExpermentals ? "!" : ""}</h1>`,
// Turn this on will abort all alerts.
I_KNOW_WHAT_IM_DOING: false
}
const get = q => document.querySelector(q);
const getAll = q => document.querySelectorAll(q);
const wait = t => new Promise(r => setTimeout(r, t));
const batchDelay = async () => await wait(datas.settings.batchOperationDelay * 1000);
const log = (...m) => cfg.debug && console.warn('[FoMan]', ...m);
const mdi = (name, asHTML = true, px = '10', extras = []) => {
const i = CKTools.domHelper('i', {
classnames: ['mdi', `mdi-${name}`, `mdi-${px}px`, ...extras],
text: ' '
});
return asHTML ? i.outerHTML : i;
};
const getSelfId = async () => {
let stat = unsafeWindow.UserStatus;
let retrial = 20;
while (stat === null || stat === undefined) {
if (--retrial < 0) return 0;
log("Waiting for userstatus...")
await wait(200);
}
if (!stat.userInfo.isLogin) {
log("NOT LOGIN");
return -1
}
log("User:", stat.userInfo.mid, stat.userInfo);
return stat.userInfo.mid;
};
async function copy(txt = '') {
try {
await navigator.clipboard.writeText(txt);
return true;
} catch (e) {
return false;
}
}
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
const makeDom = async (domname, func = () => {
}) => {
if (CKTools.domHelper) return CKTools.domHelper(domname, func);
const d = document.createElement(domname);
if (typeof (func) == 'function') func.constructor.name == 'AsyncFunction' ? await func(d) : func(d);
return d;
};
const isHardCoreMember = d => d.is_senior_member === 1;
const isFans = d => d.attribute === 6;
const isWhisper = d => d.attribute === 1;
const isNearly = d => {
const nearly = (new Date).getTime() - (60 * 60 * 24 * 7 * 4 * 3 * 1000);
return parseInt(d + "000") > nearly;
}
const isLongAgo = (d) => {
const loneAgo = (new Date).getTime() - (60 * 60 * 24 * 7 * 4 * 12 * 2 * 1000);
return parseInt(d + "000") < loneAgo;
}
/* StackOverflow 10730362 */
const getCookie = (name) => {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
const getCSRFToken = () => getCookie("bili_jct");
const getBgColor = () => {/*兼容blbl进化的夜间模式*/
try {
let color = getComputedStyle(document.body).backgroundColor;
if (color === "rgba(0, 0, 0, 0)") return "white";
else return color;
} catch (e) {
return "white"
}
}
const getCurrentUid = async () => {
setInfoBar("正在查询当前用户UID");
let paths = location.pathname.split('/');
if (paths.length > 1) {
return paths[1];
} else throw "Failed to get current ID";
};
const getHeaders = () => {
return {
"user-agent": unsafeWindow.navigator.userAgent,
"cookie": unsafeWindow.document.cookie.split('; ').map(it => it.split("=")).map(it => it.map(i => i.match(/[^\x00-\x7F]/gm) ? encodeURIComponent(i) : i)).map(it => it.join("=")).join(", "),
"origin": "space.bilibili.com",
"referer": "https://www.bilibili.com/"
}
};
const getUInfoURL = () => `https://api.bilibili.com/x/space/wbi/acc/info`;//wbi,mid
const getUserCardInfo = uid => `https://api.bilibili.com/x/web-interface/card?mid=${uid}`;
const getGroupURL = () => `https://api.bilibili.com/x/relation/tags`;
const getWhispersURL = (pn, ps = 50) => `https://api.bilibili.com/x/relation/whispers?pn=${pn}&ps=${ps}&order=desc&order_type=attention`;// removed
const getFetchURL = (uid, pn) => `https://api.bilibili.com/x/relation/followings?vmid=${uid}&pn=${pn}&ps=50&order=desc&order_type=attention`;
const getUnfolURL = () => `https://api.bilibili.com/x/relation/modify`;
const getFollowURL = () => `https://api.bilibili.com/x/relation/batch/modify`;
const getLatestVidURL = () => `https://api.bilibili.com/x/space/wbi/arc/search`;//wbi,?mid=${uid}&ps=1&pn=1`;
const getSubInfoURL = uid => `https://api.bilibili.com/x/relation/stat?vmid=${uid}`;
const getCreateGroupURL = () => `https://api.bilibili.com/x/relation/tag/create`;
const getRenameGroupURL = () => `https://api.bilibili.com/x/relation/tag/update`;
const getRemoveGroupURL = () => `https://api.bilibili.com/x/relation/tag/del`;
const getMoveToGroupURL = () => `https://api.bilibili.com/x/relation/tags/addUsers`;
const getCopyToGroupURL = () => `https://api.bilibili.com/x/relation/tags/copyUsers`;
const getDynamicURL = (selfid, hostid) => `https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history?visitor_uid=${selfid}&host_uid=${hostid}&offset_dynamic_id=0&need_top=1&platform=web`;
const getRequest = path => new Request(path, {
method: 'GET',
headers: getHeaders(),
credentials: "include"
});
const getPostRequest = (path, body = null) => new Request(path, {
method: 'POST',
headers: getHeaders(),
credentials: "include",
body
});
const cacheGroupList = async () => {
setInfoBar("正在获取分组信息...");
try {
const jsonData = await (await fetch(getRequest(getGroupURL()))).json();
if (jsonData && jsonData.code === 0) {
datas.tags = [];
for (let tag of jsonData.data) {
datas.tags[tag.tagid] = tag;
}
return true;
} else {
log(jsonData);
return false;
}
} catch (err) {
log(err);
return false;
}
};
const createGroup = async (tagname) => {
setInfoBar(`正在创建新的分组"${tagname}"...`);
try {
const jsonData = await (await fetch(
getPostRequest(getCreateGroupURL(),
new URLSearchParams({
tag: tagname,
csrf: getCSRFToken()
}))));
if (jsonData.code === 0) return true;
else throw new Error(jsonData.message);
} catch (err) {
log(err);
return false;
} finally {
await cacheGroupList();
CacheManager.save();
}
}
const renameGroup = async (tagid, tagname) => {
setInfoBar(`正在修改分组为"${tagname}"...`);
try {
const jsonData = await (await fetch(
getPostRequest(getRenameGroupURL(),
new URLSearchParams({
tagid,
name: tagname,
csrf: getCSRFToken()
}))));
if (jsonData.code === 0) return true;
else throw new Error(jsonData.message);
} catch (err) {
log(err);
return false;
} finally {
await cacheGroupList();
CacheManager.save();
await renderListTo(get("#CKFOMAN-MAINLIST"), datas.followings, true);
resetInfoBar();
}
}
const removeGroup = async (tagid) => {
setInfoBar(`正在移除分组"${tagid}"...`);
try {
const jsonData = await (await fetch(
getPostRequest(getRemoveGroupURL(),
new URLSearchParams({
tagid,
csrf: getCSRFToken()
}))));
if (jsonData.code === 0) return true;
else throw new Error(jsonData.message);
} catch (err) {
log(err);
return false;
} finally {
await cacheGroupList();
CacheManager.save();
await renderListTo(get("#CKFOMAN-MAINLIST"), datas.followings, true);
resetInfoBar();
}
}
const moveUserToDefaultGroup = uids => moveUserToGroup(uids, [0]);//unused
const moveUserToGroup = async (uids, tagids) => {
setInfoBar(`正在移动用户分组...`);
try {
const jsonData = await (await fetch(
getPostRequest(getMoveToGroupURL(),
new URLSearchParams({
fids: uids.join(','),
tagids: tagids.join(','),
csrf: getCSRFToken()
}))).json());
if (jsonData.code === 0) {
for (let uid of uids) {
const u = parseInt(uid);
let targetUser;
if (datas.mappings.includes(u)) {
targetUser = datas.mappings[u];
} else if (datas.mappings.includes(uid)) {
targetUser = datas.mappings[uid];
} else {
//TODO: need reload
}
targetUser.tag = tagids.map(i => parseInt(i))
}
return true;
}
else throw new Error(jsonData.message);
} catch (err) {
log(err);
return false;
}
}
const copyUserToGroup = async (uids, tagids) => {
setInfoBar(`正在添加用户分组...`);
try {
const jsonData = await (await fetch(
getPostRequest(getCopyToGroupURL(),
new URLSearchParams({
fids: uids.join(','),
tagids: tagids.join(','),
csrf: getCSRFToken()
}))).json());
log(jsonData, jsonData.code, jsonData.code === 0);//TODO:BUG
if (jsonData.code == 0) {
for (let uid of uids) {
const u = parseInt(uid);
let targetUser;
if (datas.mappings.includes(u)) {
targetUser = datas.mappings[u];
} else if (datas.mappings.includes(uid)) {
targetUser = datas.mappings[uid];
} else {
//TODO: need reload
}
targetUser.tag = (function () {
const tag = [];
for (const tid of [...targetUser.tag, ...tagids]) {
const ntid = parseInt(tid);
if (!tag.includes(ntid)) tag.push(ntid)
}
return tag;
})()
}
return true;
}
else throw new Error(jsonData.message);
} catch (err) {
log(err);
return false;
}
}
const getCurrSubStat = async uid => {
try {
const jsonData = await (await fetch(getRequest(getSubInfoURL(uid)))).json();
if (jsonData && jsonData.code === 0) {
return jsonData.data;
} else {
log("Failed fetch self info: unexpected response", jsonData);
return null;
}
} catch (e) {
log("Failed fetch self info: error found", e);
return null;
}
}
const getLatestVideoPublishDate = async uid => {
try {
const jsonData = await (await fetch(getRequest(getLatestVidURL() + "?" + await getWbiSignedParams({
mid: uid, ps: 1, pn: 1
})))).json();
if (jsonData && jsonData.code === 0) {
if (
jsonData.data
&& jsonData.data.list
) {
let mostCates = "";
if (jsonData.data.list.tlist.length !== 0) {
let max = 0, name = "";
for (let itemname of Object.keys(jsonData.data.list.tlist)) {
const item = jsonData.data.list.tlist[itemname];
if (item.count > max) {
max = item.count;
name = item.name;
} else if (item.count === max) {
name += "、" + item.name;
}
}
mostCates = name;
}
if (jsonData.data.list.vlist.length === 0) {
return { ok: false, mostCates: mostCates }
}
const vid = jsonData.data.list.vlist[0];
return { ok: true, value: vid.created, vinfo: { aid: vid.aid, title: vid.title, pic: vid.pic, play: vid.play }, mostCates: mostCates }
} else {
return { ok: false }
}
} else {
return { ok: false }
}
} catch (e) {
log(uid, e)
return { ok: false }
}
};
const getTypeNameFromDynamicTypeID = (id, fallback = '?') => {
switch (+id) {
case 1:
return mdi('share') + "转发动态";
case 2:
return mdi('image-multiple') + "相册图片";
case 4:
return mdi('text');//文字动态
case 8:
return mdi('youtube') + "视频投稿";
case 16:
return mdi('video-box') + "小视频";
case 64:
return mdi('newspaper-variant-outline') + "专栏文章";
case 128:
return fallback;
case 256:
return mdi('playlist-music') + "音频投稿";
case 512:
return mdi('filmstrip-box-multiple') + "番剧更新";
case 1024:
return fallback;
case 2048:
return mdi('playlist-play') + "歌单分享";
case 4300:
return mdi('playlist-star') + "收藏夹";
default: return fallback;
}
}
const getContentFromDynamic = (card) => {
if (!card) return '无法解析内容(空内容)';
if (card.item?.content) return card.item.content;
if (card.aid) return 'av' + card.aid + ' | <b>' + card.title + "</b><br>简介: " + card.desc;
if (card.item?.pictures) return card.item.pictures_count + '张图片';
if (card.origin) return `转发自${card?.user?.uname}: ${card.item?.content}`;
if (card.item?.description) return card.item.description;
if (card.summary) return `cv${card.id} | <b>${card.title}</b><br>简介: ${card.summary}`
return '无法解析内容(未知特征)';
}
const parseDynamic = (d) => {
const dynamic = {
id: d.desc.dynamic_id_str,
sender: d.desc.user_profile,
like: d.desc.like,
comment: d.desc.comment,
repost: d.desc.repost,
status: d.desc.status,
timestamp: d.desc.timestamp,
type: d.desc.type,
content: getContentFromDynamic(d.card),
origin: (d.desc.orig_dy_id && d.desc.orig_dy_id !== 0) ? (
d.card.origin = JSON.parse(d.card.origin),
getContentFromDynamic(d.card.origin)
) : null,
istop: d.extra.is_space_top === 1,
isrepost: d.desc.orig_dy_id && d.desc.orig_dy_id !== 0,
publisher: d.desc.orig_dy_id ? (d.desc.orig_dy_id === 0 ? d.card.user : d.card.origin_user.info) : d.card.user,
prefix: getTypeNameFromDynamicTypeID(d.desc.type),
origprefix: getTypeNameFromDynamicTypeID(d.desc.orig_type)
};
return dynamic;
}
const getDynamic = async uid => {
try {
const jsonData = await (await fetch(getRequest(getDynamicURL(datas.self, uid)))).json();
if (jsonData && jsonData.code === 0) {
const data = jsonData.data.cards;
const dynamics = {
top: null,
next: null,
}
if (!data || data.length === 0) {
return dynamics;
}
let d = data.shift();
d.card = JSON.parse(d.card);
let obj = parseDynamic(d);
if (obj.istop) {
dynamics.top = obj;
let nd = data.shift();
nd.card = JSON.parse(nd.card);
let nobj = parseDynamic(nd);
dynamics.next = nobj;
} else {
dynamics.next = obj;
}
return dynamics;
} else {
log("Failed fetch self info: unexpected response", jsonData);
return null;
}
} catch (e) {
log("Failed fetch self info: error found", e);
return null;
}
}
const getUserStats = async (uid, withraw = false, fast = false) => {
try {
const jsonData = fast? (await (await fetch(getRequest(getUserCardInfo(uid)))).json()) : (await (await fetch(getRequest(getUInfoURL()+"?"+await getWbiSignedParams({mid:uid})))).json());
if (jsonData && jsonData.code === 0) {
// const udata = jsonData.data;
const udata = fast? jsonData.data.card : jsonData.data;
const parsedData = {
ok: true,
level: udata.level ?? udata.level_info.current_level,
banned: udata.silence === 1,
RIP: udata.sys_notice === 20,
disputed: udata.sys_notice === 8,
notice: udata.sys_notice,
sign: udata.sign,
cates: udata.tags,
lives: udata.live_room,
official_verify: udata.official_verify ?? udata.official,
follower: udata.stats?.follower ?? udata.fans ?? jsonData.data?.follower
};
if (withraw) {
return Object.assign({}, udata, parsedData);
}
return parsedData
}
} catch (e) {
log("UINFO failed:",e.message)
}
return { ok: false }
}
const fillUserStatus = async (uid, refresh = false, fast = false) => {
setInfoBar(`正在为${uid}填充用户信息`)
uid = parseInt(uid);
if (datas.mappings[uid] && datas.mappings[uid].filled) {
log(uid, "already filled")
resetInfoBar();
return datas.mappings[uid];
}
let userinfo = await getUserStats(uid, refresh, fast);
if (userinfo.ok) {
if (refresh) datas.mappings[uid] = userinfo;
datas.mappings[uid].level = userinfo.level;
datas.mappings[uid].banned = userinfo.banned;
datas.mappings[uid].RIP = userinfo.RIP;
datas.mappings[uid].disputed = userinfo.disputed;
datas.mappings[uid].notice = userinfo.notice;
datas.mappings[uid].sign = userinfo.sign;
datas.mappings[uid].cates = userinfo.cates;
datas.mappings[uid].lives = userinfo.lives;
datas.mappings[uid].follower = userinfo.follower;
datas.mappings[uid].filled = !fast;
if (!userinfo.banned && !userinfo.RIP) {
const lastUpdate = await getLatestVideoPublishDate(uid);
log(uid, lastUpdate)
if (lastUpdate.ok) {
datas.mappings[uid].lastUpdate = lastUpdate.value;
datas.mappings[uid].lastUpdateInfo = lastUpdate.vinfo;
}
if (lastUpdate.mostCates) datas.mappings[uid].mostCates = lastUpdate.mostCates;
}
log(uid, datas.mappings[uid]);
} else {
log(uid, "fetch space info failed");
}
resetInfoBar();
return datas.mappings[uid];
}
const RELE_ACTION = {
FOLLOW: 1,
UNFOLLOW: 2,
WHISPER: 3,
UNWHISPER: 4,
BLOCK: 5,
UNBLOCK: 6,
KICKFANS: 7
}
const batchOperateUser = async (uids = [], actCode) => {
if (uids.length === 0) return { ok: false, res: "UIDS is empty" };
if (!Object.values(RELE_ACTION).includes(actCode)) {
if (Object.keys(RELE_ACTION).includes(actCode)) {
actCode = RELE_ACTION[actCode];
} else {
return { ok: false, res: "Unknown action code" };
}
}
const act = actCode;
log("Batch Operating with Action Code", act);
const operate = async (_uids, _act) => {
try {
const jsonData = await (await fetch(getPostRequest(getFollowURL(), new URLSearchParams(`fids=${_uids.join(',')}&act=${_act}&re_src=11&jsonp=jsonp&csrf=${getCSRFToken()}`)))).json()
if (jsonData && jsonData.code === 0) return { ok: true, uids, res: "" };
return { ok: false, uids, res: jsonData.message, data: jsonData.data };
} catch (e) {
return { ok: false, uids, res: e.message };
}
}
const list = [...uids];
const results = { ok: true, uids, res: "", data: { failed_fids: [], failed_results: [] } };//failed_fids
if (list.length > 50) log("WARNING: Operating with more than 50 items, it may cause some issues.");
while (list.length) {
const currents = list.splice(0, 50);
const result = await operate(currents, act);
if (!result.ok) {
results.ok = false;
results.res = "部分请求出现错误";
results.data.failed_fids.concat(result.data.failed_fids);
results.data.failed_results.push(result);
}
}
log("Results:", results);
return results;
}
const convertToWhisper = async (uids) => {
log("Unfollowing", uids);
let unfo = uids.length === 1 ? await operateUser(uids[0], RELE_ACTION.UNFOLLOW) : await batchOperateUser(uids, RELE_ACTION.UNFOLLOW);
log("Unfollowed:", unfo);
if (!unfo.ok) return unfo;
log("Whispering", uids);
let whis = uids.length === 1 ? await operateUser(uids[0], RELE_ACTION.WHISPER) : await batchOperateUser(uids, RELE_ACTION.WHISPER);
log("Whispered:", whis);
return whis;
}
const convertToFollow = async (uids) => {
log("Unwhispering", uids);
let unwh = uids.length === 1 ? await operateUser(uids[0], RELE_ACTION.UNWHISPER) : await batchOperateUser(uids, RELE_ACTION.UNWHISPER);
log("Unwhispered:", unwh);
if (!unwh.ok) return unwh;
log("Following", uids);
let foll = uids.length === 1 ? await operateUser(uids[0], RELE_ACTION.FOLLOW) : await batchOperateUser(uids, RELE_ACTION.FOLLOW);
log("Followed:", foll);
return foll;
}
// CSDN https://blog.csdn.net/namechenfl/article/details/91968396
function numberFormat(value) {
let param = {};
let k = 10000,
sizes = ['', '万', '亿', '万亿'],
i;
if (value < k) {
param.value = value
param.unit = ''
} else {
i = Math.floor(Math.log(value) / Math.log(k));
param.value = ((value / Math.pow(k, i))).toFixed(2);
param.unit = sizes[i];
}
return param;
}
const operateUser = async (uid, actCode) => {
if (!Object.values(RELE_ACTION).includes(actCode)) {
if (Object.keys(RELE_ACTION).includes(actCode)) {
actCode = RELE_ACTION[actCode];
} else {
return { ok: false, res: "Unknown action code" };
}
}
const act = actCode;
log("Operating with Action Code", act);
try {
const jsonData = await (await fetch(getPostRequest(getUnfolURL(), new URLSearchParams(`fid=${uid}&act=${act}&re_src=11&jsonp=jsonp&csrf=${getCSRFToken()}`)))).json()
if (jsonData && jsonData.code === 0) return { ok: true, uid, res: "" };
return { ok: false, uid, res: jsonData.message };
} catch (e) {
return { ok: false, uid, res: e.message };
}
}
const unfollowUser = async (uid, iswhisper = false) => {
try {
if (datas.isSelf) {
iswhisper = datas.mappings[uid].attribute === 1 || datas.mappings[uid].isWhisper;
}
return operateUser(uid, iswhisper ? RELE_ACTION.UNWHISPER : RELE_ACTION.UNFOLLOW);
} catch (e) {
return { ok: false, uid, res: e.message };
}
}
const unfollowUsers = async uids => {
let okgroup = [];
let errgroup = [];
for (let uid of uids) {
setInfoBar(`正在取关 ${uid} ...`)
let result = await unfollowUser(uid);
log(result);
if (result.ok) {
okgroup.push(uid);
} else {
errgroup.push(uid);
}
await batchDelay();
}
setInfoBar(`取关完成`)
return {
ok: errgroup.length === 0,
okgroup, errgroup
}
}
const fetchFollowings = async (uid, page = 1) => {
let retry = cfg.retrial;
while (retry-- > 0) {
try {
const jsonData = await (await fetch(getRequest(getFetchURL(uid, page)))).json();
if (jsonData) {
if (jsonData.code === 0) return jsonData;
if (jsonData.code === 22007) {
retry = -1;
datas.fetchstat = "GUEST-LIMIT";
throw "Not the owner of uid " + uid;
}
if (jsonData.code === 22115) {
retry = -1;
datas.fetchstat = "PERMS-DENIED";
throw "Permission denied.";
}
}
log("Unexcept fetch result", "retry:", retry, "uid:", uid, "p:", page, "data", jsonData)
} catch (e) {
if (datas.fetchstat === "OK") datas.fetchstat = "ERRORED";
log("Errored while fetching followings", "retry:", retry, "uid:", uid, "p:", page, "e:", e);
}
}
return null;
}
const fetchWhisperFollowings = async (uid, page = 1) => {
if (!datas.isSelf) return null;
let retry = cfg.retrial;
while (retry-- > 0) {
try {
const jsonData = await (await fetch(getRequest(getWhispersURL(page)))).json();
if (jsonData) {
if (jsonData.code === 0) {
for (let item of jsonData.data.list) {
item.isWhisper = true;
}
return jsonData;
}
if (jsonData.code === 22007) {
retry = -1;
datas.fetchstat = "GUEST-LIMIT";
throw "Not the owner of uid " + uid;
}
if (jsonData.code === 22115) {
retry = -1;
datas.fetchstat = "PERMS-DENIED";
throw "Permission denied.";
}
}
log("Unexcept fetch result", "retry:", retry, "uid:", uid, "p:", page, "data", jsonData)
} catch (e) {
if (datas.fetchstat === "OK") datas.fetchstat = "ERRORED";
log("Errored while fetching followings", "retry:", retry, "uid:", uid, "p:", page, "e:", e);
}
}
return null;
}
const getFollowings = async (force = false) => {
if (datas.status === 1) {
log("Task canceled due to busy");
return;
}
log("Fetching followings with param force =", force ? "true" : "false");
cfg.infobarTemplate = () => `共读取 ${datas.fetched} 条关注`;
datas.status = 1;
datas.checked = [];
let currentPageNum = 1;
const uid = await getCurrentUid();
const self = await getSelfId();
datas.currUid = uid;
datas.self = self;
if (self === -1) {
if (!cfg.I_KNOW_WHAT_IM_DOING) alertModal("没有登录", "你没有登录,部分功能可能无法正常工作。", "确定");
log("Not login");
} else if (self === 0) {
if (!cfg.I_KNOW_WHAT_IM_DOING) alertModal("获取当前用户信息失败", "无法得知当前页面是否为你的个人空间,因此部分功能可能无法正常工作。", "确定");
log("Failed fetch current user");
} else if (self + "" !== uid) {
if (!cfg.I_KNOW_WHAT_IM_DOING) alertModal("他人的关注列表", "这不是你的个人空间,因此获取的关注列表也不是你的列表。<br>非本人关注列表最多显示前250个关注。<br>你仍然可以对其进行筛选,但是不能进行操作。", "确定");
log("Other's space.");
} else if (self + "" === uid) {
datas.isSelf = true;
}
unsafeWindow.FoMan_CurrentUser = () => createUserInfoCardFromOthers(datas.currUid);
cfg.titleTemplate = () => `<h1>关注管理器 <small>v${cfg.VERSION} ${cfg.debug ? "debug" : ""} ${datas.settings.enableExpermentals ? "!" : ""} <span style="color:grey;font-size:x-small;margin-right:12px;float:right">当前展示: UID:${datas.currUid} ${datas.isSelf ? "(你)" : `(${document.title.replace("的个人空间_哔哩哔哩_bilibili", "").replace("的个人空间_哔哩哔哩_Bilibili", "")})`} <a href='javascript:void(0)' onclick='FoMan_CurrentUser()'>👁️🗨️</a></span></small></h1>`
setTitle();
let needreload = force || !CacheManager.load();
const currInfo = await getCurrSubStat(uid);
if (datas.currInfo.following !== -1 && currInfo !== null) {
if (force === false && datas.currInfo.following === currInfo.following && datas.currInfo.whisper === currInfo.whisper) {
if (datas.fetched > 0)
needreload = false;
} else if (!needreload && (datas.currInfo.following !== currInfo.following || datas.currInfo.whisper !== currInfo.whisper)) {
alertModal("自动重新加载", "检测到数据变化,已经自动重新加载。", "确定");
needreload = true;
}
}
datas.currInfo = currInfo;
if (needreload) {
datas.followings = [];
datas.mappings = {};
datas.fetched = 0;
const firstPageData = await fetchFollowings(uid, currentPageNum);
if (!firstPageData) throw "Failed to fetch followings";
datas.total = firstPageData.data.total;
datas.pages = Math.floor(datas.total / 50) + (datas.total % 50 ? 1 : 0);
datas.followings = datas.followings.concat(firstPageData.data.list);
datas.fetched += firstPageData.data.list.length;
firstPageData.data.list.forEach(it => {
datas.mappings[parseInt(it.mid)] = it;
})
currentPageNum += 1;
for (; currentPageNum <= datas.pages; currentPageNum++) {
const currentData = await fetchFollowings(uid, currentPageNum);
if (!currentData) break;
datas.followings = datas.followings.concat(currentData.data.list);
datas.fetched += currentData.data.list.length;
currentData.data.list.forEach(it => {
datas.mappings[parseInt(it.mid)] = it;
});
setInfoBar(`正在查询关注数据:已获取 ${datas.fetched} 条数据`);
}
log("isSelf? ", datas.isSelf);
if (datas.isSelf) {
setInfoBar(`正在查询悄悄关注数据`);
let whisperPageNum = 1;
let fetched = 0;
const whisperPages = Math.floor(datas.currInfo.whisper / 50) + (datas.currInfo.whisper % 50 ? 1 : 0);
for (; whisperPageNum <= whisperPages; whisperPageNum++) {
const currentData = await fetchWhisperFollowings(whisperPageNum);
log(currentData);
if (!currentData) break;
datas.followings = datas.followings.concat(currentData.data.list);
fetched += currentData.data.list.length;
currentData.data.list.forEach(it => {
datas.mappings[parseInt(it.mid)] = it;
});
setInfoBar(`正在查询悄悄关注数据:已获取 ${fetched} 条数据`);
}
}
console.error("expermentals:",datas.settings.enableExpermentals);
if(datas.settings.enableExpermentals){
setInfoBar("正在填充更多信息");
// let testcount = 5;
for(let fo of datas.followings){
// if(testcount--<0) break;
let id = fo.mid ?? fo.uid;
await fillUserStatus(id, false, true);
}
}
CacheManager.save();
} else {
log("Using last result.");
cfg.infobarTemplate = () => `共读取 ${datas.fetched} 条关注(缓存,<a href="javascript:void(0)" onclick="openFollowManager(true)">点此重新加载</a>)`
setInfoBar("使用上次数据");
}
datas.status = 2;
log("fetch completed.");
autoCacheCleaner();
}
const autoCacheCleaner = (force = false) => {
let size = CacheManager.getSize();
if (force || size >= 2) {
setInfoBar("正在整理缓存空间...");
alertModal('请稍等', '由于缓存空间到达警戒值,正在自动整理缓存,请稍等...');
CacheManager.prune();
let aftersize = CacheManager.getSize();
if (aftersize >= 2) {
alertModal('请稍等', '缓存空间仍然处于警戒值以上,整理缓存无效,正在自动清理缓存,请稍等...');
CacheManager.clean();
}
aftersize = CacheManager.getSize();
alertModal('清理完成', '本次自动清理释放了' + (size - aftersize) + ' MB缓存空间。', "确定");
resetInfoBar();
}
}
unsafeWindow.FoManCleaner = (force = false) => autoCacheCleaner(force);
const CacheProvider = {
storage: window.localStorage,
prefix: "Unfollow_",
expire: 1000 * 60 * 60 * 2,
getKey: (key) => CacheProvider.prefix + key,
valueWrapper: (value = '', no = false) => {
log(JSON.stringify({
et: no ? (new Date('2999/1/1')).getTime() : (new Date()).getTime() + CacheProvider.expire,
vl: value
}));
return JSON.stringify({
et: no ? (new Date('2999/1/1')).getTime() : (new Date()).getTime() + CacheProvider.expire,
vl: value
});
},
getValue: (value = "{}", key = null, noprefix = false) => {
try {
const itemArc = JSON.parse(value);
if (itemArc.hasOwnProperty('et') && itemArc.et >= (new Date()).getTime()) {
return itemArc.vl;
}
if (key) CacheProvider.del(key, noprefix);
return null;
} catch (e) {
if (key) CacheProvider.del(key, noprefix);
return null;
}
},
list: () => Object.keys(CacheProvider.storage).filter(el => el.startsWith(CacheProvider.prefix)),
has: (key, noprefix = false) => {
if (!noprefix) {
key = CacheProvider.getKey(key);
}
return CacheProvider.storage.getItem(key) === null;
},
valid: (key, noprefix = false) => {
if (!noprefix) {
key = CacheProvider.getKey(key);
}
if (CacheProvider.has(key, true)) {
const value = CacheProvider.storage.getItem(key);
return CacheProvider.getValue(value, key, true) !== null;
} else return false;
},
set: (key, val, noexpire = false, noprefix = false) => {
if (!noprefix) {
key = CacheProvider.getKey(key);
}
CacheProvider.storage.setItem(key, CacheProvider.valueWrapper(val, noexpire));
},
get: (key, fallback = null, noprefix = false) => {
if (!noprefix) {
key = CacheProvider.getKey(key);
}
const result = CacheProvider.storage.getItem(key);
log('Cache-get-with-key', key, result);
if (result === null) return fallback;
log('Cache-get-parsed-value', key, CacheProvider.getValue(result, key, true));
return CacheProvider.getValue(result, key, true);
},
del: (key, noprefix = false) => {
if (!noprefix) {
key = CacheProvider.getKey(key);
}
delete CacheProvider.storage[key];
},
prune: () => {
const count = {
valid: 0, expired: 0
};
CacheProvider.list().forEach(it => {
if (!it) return;
if (CacheProvider.valid(it, true)) {
count.valid++;
} else {
count.expired++;
}
})
return;
},
getSize: (filter = (key) => key.startsWith(CacheProvider.prefix)) => {
const sum = (...args) => args.reduce((a, b) => a + b, 0);
return sum(...Object.keys(CacheProvider.storage).filter(filter).map(it => CacheProvider.storage.getItem(it).length));
}
}
const CacheManager = {
version: 1,
save: (uid = datas.currUid) => {
const { total, fetched, pages, followings, tags, currInfo } = datas;
const tagclone = {};
for (let tn of Object.keys(tags)) {
tagclone[tn + ''] = tags[tn];
}
/*log({
total,fetched,pages,followings,mappings,tagclone,currInfo
});*/
CacheProvider.set(`cache_${uid}`, {
total, fetched, pages, followings, tagclone, currInfo, cacheVersion: CacheManager.version
});
},
load: (uid = datas.currUid) => {
if (!datas.isSelf) return false;
const cached = CacheProvider.get(`cache_${uid}`);