-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathindex.html
945 lines (879 loc) · 31.7 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<link rel="icon" href="/favicon.ico"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/3.2.40/vue.global.js"></script>
<title>Vite App</title>
<style>
</style>
</head>
<body>
<div id="app"></div>
<script>
const isDev = true
//发布脚本,从这里开始复制
//发布脚本,从这里开始复制
//发布脚本,从这里开始复制
if (!isDev) {
window.onerror = function (message, source, lineno, colno, error) {
console.log('捕获到异常:', {message, source, lineno, colno, error});
}
window.addEventListener('error', (error) => {
console.log('捕获到异常:', error);
}, true)
window.addEventListener("unhandledrejection", function (e) {
e.preventDefault()
console.log('捕获到异常:', e);
return true;
});
} else {
window.GM_registerMenuCommand = function () {
}
window.GM_openInTab = function () {
}
}
if (window.top !== window.self) {
window.win = () => window.top
window.baseUrl = 'https://v2ex.com'
window.win().isFrame = true
//直接使用v2的jquery,因为v2对jquery作了修改,加了一些header,缺少这些header发送请求会报403
window.$ = window.win().$
} else {
window.win = () => window
//这里必须一致。不然会报跨域
window.baseUrl = location.origin
window.win().isFrame = false
}
window.initPost = {
replies: [],
nestedReplies: [],
username: '',
member: {},
node: {},
headerTemplate: '',
title: '',
id: '',
type: 'post',
once: '',
replyCount: 0,
clickCount: 0,
thankCount: 0,
collectCount: 0,
isFavorite: false,
isIgnore: false,
isThanked: false,
isReport: false,
}
window.win().doc = window.win().document
window.win().query = (v) => window.win().document.querySelector(v)
window.clone = (val) => JSON.parse(JSON.stringify(val))
window.user = {
tagPrefix: '--用户标签--',
tags: {},
username: '',
avatar: '',
tagsId: ''
}
window.pageType = ''
window.pageData = {pageNo: 1}
window.config = {
showToolbar: true,
showPreviewBtn: true,
autoOpenDetail: true,
openTag: true,
clickPostItemOpenDetail: true,
// newTabOpen: true,
closePostDetailBySpace: true,//点击空白处关闭详情
contentAutoCollapse: true,//点击空白处关闭详情
viewType: 'card',
commentDisplayType: 0
}
window.isNight = $('.Night').length === 1
window.cb = null
window.postList = []
window.parse = {
//解析帖子内容
async parsePostContent(post = {}, body, htmlText) {
let once = htmlText.match(/var once = "([\d]+)";/)
// console.log(once)
if (once && once[1]) {
post.once = once[1]
}
post.isReport = htmlText.includes('你已对本主题进行了报告')
let topic_buttons = body.find('.topic_buttons')
if (topic_buttons.length) {
let favoriteNode = topic_buttons.find('.tb:first')
if (favoriteNode.length) {
post.isFavorite = favoriteNode[0].innerText === '取消收藏'
}
let ignoreNode = topic_buttons.find('.tb:nth-child(3)')
if (ignoreNode.length) {
post.isIgnore = ignoreNode[0].innerText === '取消忽略'
}
//
let thankNode = topic_buttons.find('#topic_thank .tb')
if (!thankNode.length) {
post.isThanked = true
}
let topic_stats = topic_buttons.find('.topic_stats')
//topic_stats = $(`<div class="fr topic_stats" style="padding-top: 4px;">9569 次点击 ∙ 28 人收藏 ∙ 1 人感谢 </div>`)
//收藏数、感谢数
if (topic_stats.length) {
let text = topic_stats[0].innerText
let reg1 = text.matchAll(/([\d]+)[\s]*人收藏/g)
let collectCountReg = [...reg1]
if (collectCountReg.length) {
post.collectCount = Number(collectCountReg[0][1])
}
// console.log([...collectCountReg])
let reg2 = text.matchAll(/([\d]+)[\s]*人感谢/g)
let thankCountReg = [...reg2]
if (thankCountReg.length) {
post.thankCount = Number(thankCountReg[0][1])
}
let reg3 = text.matchAll(/([\d]+)[\s]*次点击/g)
let clickCountReg = [...reg3]
if (clickCountReg.length) {
post.clickCount = Number(clickCountReg[0][1])
}
// console.log([...thankCountReg])
}
}
// console.log('基本信息', post)
body.find('.topic_buttons').remove()
let header = body.find('#Main .box').first()
post.headerTemplate = `${header.html()} `
return post
},
//获取帖子所有回复
async getPostAllReplies(post = {}, body, htmlText, pageNo = 1) {
if (body.find('#no-comments-yet').length) {
return post
}
let box = body.find('#Main > .box')[1]
let cells = box.querySelectorAll('.cell')
post.fr = cells[0].querySelector('.cell .fr').innerHTML
cells = Array.from(cells)
//获取创建时间
let snow = cells[0].querySelector('.snow')
post.createDate = snow?.nextSibling.nodeValue.trim() || ''
let repliesMap = []
if (cells[1].id) {
repliesMap.push({i: pageNo, replyList: this.parsePageReplies(cells.slice(1))})
let replies = this.getAllReply(repliesMap)
post.replies = replies
post.replyCount = replies.length
post.allReplyUsers = Array.from(new Set(replies.map(v => v.username)))
let nestedList = this.createNestedList(replies, post.allReplyUsers)
if (nestedList) post.nestedReplies = nestedList
return post
} else {
let promiseList = []
// console.log(this.current.repliesMap)
return new Promise((resolve, reject) => {
repliesMap.push({i: pageNo, replyList: this.parsePageReplies(cells.slice(2, cells.length - 1))})
let pages = cells[1].querySelectorAll('a')
pages = Array.from(pages)
// console.log(pages)
let url = window.baseUrl + '/t/' + post.id
for (let i = 0; i < pages.length; i++) {
let currentPageNo = Number(pages[i].innerText)
if (currentPageNo == pageNo) continue
promiseList.push(this.fetchPostOtherPageReplies(url + '?p=' + currentPageNo, currentPageNo))
}
Promise.allSettled(promiseList).then(
(results) => {
results.filter((result) => result.status === "fulfilled").map(v => repliesMap.push(v.value))
let replies = this.getAllReply(repliesMap)
post.replies = replies
post.replyCount = replies.length
post.allReplyUsers = Array.from(new Set(replies.map(v => v.username)))
let nestedList = this.createNestedList(replies, post.allReplyUsers)
if (nestedList) post.nestedReplies = nestedList
resolve(post)
}
);
})
}
},
//请求帖子其他页的回复
fetchPostOtherPageReplies(url, pageNo) {
return new Promise(resolve => {
$.get(url).then(res => {
let s = res.match(/<body[^>]*>([\s\S]+?)<\/body>/g)
let box = $(s[0]).find('#Main .box')[1]
let cells = box.querySelectorAll('.cell')
cells = Array.from(cells)
resolve({i: pageNo, replyList: this.parsePageReplies(cells.slice(2, cells.length - 1))})
})
})
},
//解析页面的回复
parsePageReplies(nodes) {
let replyList = []
nodes.forEach((node, index) => {
if (!node.id) return
let item = {
thankCount: 0,
isThanked: false,
isOp: false,
id: node.id.replace('r_', '')
}
let reply_content = node.querySelector('.reply_content')
// console.log('reply_content',reply_content)
item.reply_content = reply_content.innerHTML
item.reply_text = reply_content.innerText
let {users, floor} = this.parseReplyContent(item.reply_content)
item.replyUsers = users
item.replyFloor = floor
if (index === 5) {
// console.log(item)
// console.log(reply_content.innerText)
// console.log(reply_content.innerHTML)
}
let ago = node.querySelector('.ago')
item.date = ago.innerText
let userNode = node.querySelector('strong a')
item.username = userNode.innerText
let avatar = node.querySelector('td img')
item.avatar = avatar.src
let no = node.querySelector('.no')
item.floor = Number(no.innerText)
let thank_area = node.querySelector('.thank_area')
if (thank_area) {
item.isThanked = thank_area.classList.contains('thanked')
}
let small = node.querySelector('.small')
if (small) {
item.thankCount = Number(small.innerText)
}
let op = node.querySelector('.op')
if (op) {
item.isOp = true
}
let mod = node.querySelector('.mod')
if (mod) {
item.isMod = true
}
// console.log('item', item)
replyList.push(item)
})
return replyList
},
//解析回复内容,解析出@用户,回复楼层。用于后续生成嵌套楼层
parseReplyContent(str) {
if (!str) return
let users = []
let getUsername = (userStr) => {
let endIndex = userStr.indexOf('">')
if (endIndex > -1) {
let user = userStr.substring(0, endIndex)
if (!users.find(i => i === user)) {
users.push(user)
}
}
}
// str = `@<a hr a> #4 @<a1 href="/member/Eiden1">Eiden1</a1> @<a href="/member/Eiden111">Eiden21</a> #11 这也是执行阶段,所谓的安装也是程序业务的 setup 。<br>windows 、Android 并没有系统级的 CD-KEY 。`
let floorReg = /@<a href="\/member\/[\s\S]+?<\/a>[\s]+#([\d]+)/g
let userReg = /@<a href="\/member\/([\s\S]+?)<\/a>/g
let hasFloor = str.matchAll(floorReg)
let res = [...hasFloor]
// console.log('总匹配', res)
let floor = -1
if (res.length) {
floor = Number(res[0][1])
}
let has = str.matchAll(userReg)
let res2 = [...has]
// console.log('总匹配', res2)
if (res2.length > 1) {
res2.map(item => {
getUsername(item[1])
})
}
if (res2.length === 1) {
getUsername(res2[0][1])
}
// console.log('用户', users)
// console.log('楼层', floor)
return {users, floor}
},
//获取帖子详情
async getPostDetail(post = {}, body, htmlText, pageNo = 1) {
post = await this.parsePostContent(post, body, htmlText)
return await this.getPostAllReplies(post, body, htmlText, pageNo)
},
getAllReply(repliesMap = []) {
return repliesMap.sort((a, b) => a.i - b.i).reduce((pre, i) => {
pre = pre.concat(i.replyList)
return pre
}, [])
},
//生成嵌套回复
createNestedList(allList = []) {
if (!allList.length) return []
if ((Date.now() - window.win().lastCallDate) < 1000) {
// console.log('短时间内,重复调用,因为监听了replies,所以打开时会触发两次。第二次不管他')
return false
}
// console.log('cal-createNestedList', Date.now())
let list = JSON.parse(JSON.stringify(allList))
let nestedList = []
list.map((item, index) => {
let startList = list.slice(0, index)
//用于918489这种情况,@不存在的人
let startReplyUsers = Array.from(new Set(startList.map(v => v.username)))
let endList = list.slice(index + 1)
item.level = 0
if (index === 0) {
nestedList.push(this.findChildren(item, endList, list))
} else {
if (!item.isUse) {
//是否是一级回复
let isOneLevelReply = false
if (item.replyUsers.length) {
if (item.replyUsers.length > 1) {
isOneLevelReply = true
} else {
isOneLevelReply = !startReplyUsers.find(v => v === item.replyUsers[0]);
}
} else {
isOneLevelReply = true
}
if (isOneLevelReply) {
item.level === 0
nestedList.push(this.findChildren(item, endList, list))
}
}
}
})
// console.log('replies长度', allList)
// console.log('nestedList长度', nestedList)
window.win().lastCallDate = Date.now()
return nestedList
},
//查找子回复
findChildren(item, endList, all) {
const fn = (child, endList2, parent,) => {
child.level = parent.level + 1
let rIndex = all.findIndex(v => v.floor === child.floor)
if (rIndex > -1) {
all[rIndex].isUse = true
}
parent.children.push(this.findChildren(child, endList2, all,))
}
// console.log('endList', endList)
item.children = []
// if (item.floor === 46) debugger
let floorReplyList = []
//先找到指定楼层的回复,再去循环查找子回复
//原因:问题930155
for (let i = 0; i < endList.length; i++) {
let currentItem = endList[i]
//如果已被使用,直接跳过
if (currentItem.isUse) continue
if (currentItem.replyFloor === item.floor) {
//必须楼层对应的名字和@人的名字相同。因为经常出现不相同的情况
if (currentItem.replyUsers.length === 1 && currentItem.replyUsers[0] === item.username) {
if (item.floor === 3) {
console.log('i', i)
}
//先标记为使用,不然遇到“问题930155”,会出现重复回复
currentItem.isUse = true
floorReplyList.push({endList: endList.slice(i + 1), currentItem})
//问题930155:这里不能直接找子级,如果item为A,currentItem为B,但随后A又回复了B,然后C回复A。这样直接找子级就会把C归类到B的子回复,而不是直接A的子回复
//截图:930155.png
// fn(currentItem, endList.slice(i + 1), item)
} else {
currentItem.isWrong = true
}
}
}
floorReplyList.map(({currentItem, endList}) => {
fn(currentItem, endList, item)
})
//下一个我的下标,如果有下一个我,那么当前item的子回复应在当前和下个我的区间内查找
let nextMeIndex = endList.findIndex(v => v.username === item.username)
let findList = nextMeIndex > -1 ? endList.slice(0, nextMeIndex) : endList
for (let i = 0; i < findList.length; i++) {
let currentItem = findList[i]
//如果已被使用,直接跳过
if (currentItem.isUse) continue
let endList2 = endList.slice(i + 1)
if (currentItem.replyUsers.length === 1) {
//如果是下一条是同一人的回复,那么跳出循环
if (currentItem.username === item.username) {
//自己回复自己的特殊情况
if (currentItem.replyUsers[0] === item.username) {
fn(currentItem, endList2, item)
}
return item
} else {
if (currentItem.replyUsers[0] === item.username) {
fn(currentItem, endList2, item)
}
}
} else {
//下一条是同一人的回复,并且均未@人。直接跳过
if (currentItem.username === item.username) return item
}
}
item.children = item.children.sort((a, b) => a.floor - b.floor)
return item
},
findChildren2(item, endList, all) {
const fn = (child, endList2, parent) => {
child.level = parent.level + 1
let rIndex = all.findIndex(v => v.floor === child.floor)
if (rIndex > -1) {
all[rIndex].isUse = true
}
parent.children.push(this.findChildren(child, endList2, all))
}
// console.log('endList', endList)
item.children = []
// if (item.floor ==8)debugger
for (let i = 0; i < endList.length; i++) {
let currentItem = endList[i]
//如果已被使用,直接跳过
if (currentItem.isUse) continue
let endList2 = endList.slice(i + 1)
//注: 2022-10-26,回复被忽略、用户被ban,会占据原来的楼层,以楼层号来判断会出问题
// if (currentItem.replyFloor !== -1) {
// if (currentItem.replyFloor === item.floor) {
// fn(currentItem, endList2, item)
// }
// }
if (currentItem.replyUsers.length) {
// //找出自己最近一条正常回复,以那条为搜索终点
// let rIndex = endList.findIndex(v => v.username === item.username && (currentItem.replyUsers.length === 0 && currentItem.replyFloor === -1))
// if (rIndex > -1) {
// endList2 = endList.slice(i + 1, rIndex)
// }
//如果是下一条是同一人的回复,那么跳出循环。children从下一条开始找
if (currentItem.username === item.username) {
//自己回复自己的特殊情况
if (currentItem.replyUsers[0] === item.username) {
fn(currentItem, endList2, item)
continue
}
//有种特殊情况,就是自己连着评论了两条。然后后面的人以#号的方式 回复了自己第一条。
//如果检测到下条是自己的回复,直接略过的话就会丢失第一条的所有楼中楼回复
//具体如下
// 自己:1楼,在for的时候,如果碰到 2楼不能直接跳过,直接略过的话就会丢失第一条的所有楼中楼回复,即3楼。所以应该以3楼为起点
//进行楼中楼查找,查找完了再跳过
// 自己:2楼
// 别人:指定回复1楼
// endList2.map((v, vi) => {
// if (v.replyFloor === item.floor) {
// fn(v, endList.slice(vi + 1), item)
// }
// })
break
} else {
if (currentItem.replyUsers[0] === item.username) {
fn(currentItem, endList2, item)
}
}
} else {
//下一条是同一人的回复,并且均未@人。直接跳过
if (currentItem.username === item.username) return item
}
}
return item
},
//解析其他页面
parseOtherPage(html, pageType) {
let bodyText = html.match(/<body[^>]*>([\s\S]+?)<\/body>/g)
let body = $(bodyText[0])
if (pageType === 'recent') {
let list = body.find('.item')
let res = this.parsePagePostList(Array.from(list))
let page = body.find('.cell:last').html()
return {...res, page}
}
if (pageType === 'nodePage') {
let topics = body.find('#TopicsNode')
let list = topics.children()
let res = this.parsePagePostList(Array.from(list))
let page = topics.next().html()
return {...res, page}
}
},
//解析页面帖子列表
parsePagePostList(list, box) {
list.forEach(itemDom => {
let item = window.clone(window.initPost)
let item_title = itemDom.querySelector('.item_title a')
let {href, id} = window.parse.parseA(item_title)
item.id = id
item.href = href
item.url = window.win().location.origin + '/api/topics/show.json?id=' + item.id
itemDom.classList.add('post-item')
itemDom.classList.add(`id_${id}`)
window.postList.push(item)
})
Promise.allSettled(window.postList.map(item => $.get(item.url))).then(res => {
let ok = res.filter((r) => r.status === "fulfilled").map(v => v.value[0])
// let fail = res.filter((r) => r.status === "rejected")
box.style.boxShadow = 'unset'
box.style.background = 'unset'
if (window.config.viewType === 'card') {
list.forEach(itemDom => {
itemDom.classList.add('preview')
})
}
ok.map(postItem => {
if (postItem?.id) {
let itemDom = box.querySelector(`.id_${postItem.id}`)
if (window.config.showPreviewBtn) {
//添加切换按钮
let td = itemDom.querySelector('td:nth-child(4)')
td.style.position = 'relative'
let toggle = document.createElement('div')
toggle.dataset['id'] = postItem.id
toggle.classList.add('toggle')
toggle.innerText = '点击展开/收起'
td.append(toggle)
}
let index = window.postList.findIndex(v => v.id == postItem.id)
if (index > -1) {
let obj = window.postList[index]
window.postList[index] = Object.assign({}, obj, postItem)
if (postItem.content_rendered) {
let a = document.createElement('a')
a.href = obj.href
a.classList.add('post-content')
let div = document.createElement('div')
div.innerHTML = postItem.content_rendered
a.append(div)
// console.log(div.clientHeight)
itemDom.append(a)
}
}
}
})
cbChecker({type: 'syncData'})
})
},
parseA(a) {
let href = a.href
let id
if (href.includes('/t/')) {
if (href.includes('#')) {
id = href.substring(href.indexOf('/t/') + 3, href.indexOf('#'))
} else {
id = href.substring(href.indexOf('/t/') + 3,)
}
}
return {href, id}
},
//创建记事本里面的tag标签
async createTagNote() {
let data = new FormData()
data.append('content', '--用户标签--')
data.append('parent_id', 0)
data.append('syntax', 0)
let apiRes = await window.win().fetch(`${window.baseUrl}/notes/new`, {method: 'post', body: data})
console.log(apiRes)
if (apiRes.redirected && apiRes.status === 200) {
//成功
return apiRes.url.substr(-5)
}
return null
},
//标签操作
async saveTags(val) {
let data = new FormData()
data.append('content', window.user.tagPrefix + JSON.stringify(val))
data.append('syntax', 0)
let apiRes = await window.win().fetch(`${window.baseUrl}/notes/edit/${window.user.tagsId}`, {
method: 'post', body: data
})
return apiRes.redirected && apiRes.status === 200;
}
}
async function sleep(time) {
return new Promise(resolve => {
// console.log('等待vue加载完成,第' + count + '次', Date.now())
setTimeout(resolve, time)
})
}
async function cbChecker(val, count = 0) {
if (window.cb) {
window.cb(val)
} else {
while ((!window.cb) && count < 20) {
await sleep(500)
count++
}
window.cb && window.cb(val)
}
}
//初始化脚本菜单
function initMonkeyMenu() {
GM_registerMenuCommand("脚本设置", function (event) {
cbChecker({type: 'openSetting'})
});
GM_registerMenuCommand('💬 反馈 & 建议', function () {
GM_openInTab('https://github.com/zyronon/v2ex-script/issues', {
active: true,
insert: true,
setParent: true
});
});
}
//初始化样式表
function initStyle() {
//给Wrapper和content取消宽高,是因为好像是v2的屏蔽机制,时不时会v2会修复这两个div的宽高,让网页变形
let style2 = `
html, body {
font-size: 62.5%;
}
#Wrapper {
height: unset !important;
width: unset !important;
}
#Wrapper > .content {
height: unset !important;
width: unset !important;
}
.post-item {
background: white;
}
.post-item > .post-content {
height: 0;
margin-top: 0;
}
.post-item:hover .toggle {
display: flex;
}
.toggle {
position: absolute;
right: 0;
top: 0.5rem;
width: 8rem;
height: 100%;
display: flex;
justify-content: flex-end;
align-items: flex-end;
cursor: pointer;
font-size: 1.2rem;
color: #ccc;
display: none;
}
.preview {
margin: 1rem 0;
border: 1px solid #e2e2e2;
border-radius: 0.4rem;
cursor: pointer;
}
.preview:hover {
border: 1px solid #968b8b;
}
.preview > .post-content {
height: unset !important;
margin-top: 0.5rem !important;
}
.post-content {
margin-top: 0.5rem;
display: block;
max-height: 20rem;
overflow: hidden;
text-decoration: unset !important;
line-break: anywhere;
}
.post-content:link {
color: black;
}
.post-content:visited {
color: #afb9c1 !important;
}
.Night .post-item {
background: #18222d !important;
}
.Night .preview {
border: 1px solid #3b536e;
}
.Night .preview > .post-content:link {
color: #d1d5d9;
}
.Night .preview > .post-content:visited {
color: #393f4e !important;
}
`
let addStyle2 = document.createElement("style");
addStyle2.rel = "stylesheet";
addStyle2.type = "text/css";
addStyle2.innerHTML = style2
$(window.win().doc.head).append(addStyle2)
}
initMonkeyMenu()
initStyle()
window.win().canParseV2exPage = true
if (window.win().canParseV2exPage) {
let location2 = window.win().location
if (location2.pathname === '/') {
window.pageType = 'home'
} else if (location2.href.match(/.com\/?tab=/)) {
window.pageType = 'home'
} else if (location2.href.match(/.com\/go\//)) {
if (!location2.href.includes('/links')) {
window.pageType = 'nodePage'
}
} else if (location2.href.match(/.com\/recent/)) {
window.pageType = 'recent'
} else {
let r = location2.href.match(/.com\/t\/([\d]+)/)
if (r) {
window.pageType = 'post'
window.pageData.id = r[1]
if (location2.search) {
let pr = location2.href.match(/\?p=([\d]+)/)
if (pr) window.pageData.pageNo = Number(pr[1])
}
}
}
let top2 = window.win().query('.tools .top:nth-child(2)').text
if (top2 !== '注册') {
window.user.username = top2
window.user.avatar = $('#Rightbar .box .avatar', window.win().doc).attr('src')
cbChecker({type: 'syncData'})
//获取或创建记事本的标签
$.get(window.baseUrl + '/notes').then(r => {
let bodyText = r.match(/<body[^>]*>([\s\S]+?)<\/body>/g)
let body = $(bodyText[0])
let items = body.find('#Main .box .note_item_title a')
let needCreateNoteTags = true
if (items.length) {
let tags = Array.from(items).find(v => v.innerText.includes(window.user.tagPrefix))
if (tags) {
needCreateNoteTags = false
window.user.tagsId = tags.href.substr(-5)
cbChecker({type: 'syncData'})
$.get(window.baseUrl + '/notes/edit/' + window.user.tagsId).then(r2 => {
bodyText = r2.match(/<body[^>]*>([\s\S]+?)<\/body>/g)
body = $(bodyText[0])
let text = body.find('.note_editor').text()
if (text === window.user.tagPrefix) {
window.user.tags = {}
} else {
let tagJson = text.substring(window.user.tagPrefix.length)
try {
window.user.tags = JSON.parse(tagJson)
} catch (e) {
console.log('tage', tagJson)
window.user.tags = {}
}
}
cbChecker({type: 'syncData'})
})
}
}
if (needCreateNoteTags) {
window.parse.createTagNote().then(r => {
if (r) {
window.user.tagsId = r
window.user.tags = {}
cbChecker({type: 'syncData'})
}
})
}
})
}
//获取默认配置
let configStr = window.win().localStorage.getItem('v2ex-config')
if (configStr) {
let configObj = JSON.parse(configStr)
configObj = configObj[window.user.username ?? 'default']
if (configObj) {
window.config = Object.assign(window.config, configObj)
}
}
let $section = document.createElement('section')
$section.id = 'app'
let box
let list
switch (window.pageType) {
case 'nodePage':
box = window.win().doc.querySelectorAll('#Wrapper #Main .box')
let topics = box[1].querySelector('#TopicsNode')
list = topics.querySelectorAll('.cell')
list[0].before($section)
window.parse.parsePagePostList(list, box[1])
break
case 'recent':
case 'home':
box = window.win().query('#Wrapper #Main .box')
list = box.querySelectorAll('.item')
list[0].before($section)
window.parse.parsePagePostList(list, box)
break
case 'post':
box = window.win().query('#Wrapper #Main .box')
box.after($section)
window.parse.parsePostContent(
{id: window.pageData.id},
$(window.win().doc.body),
window.win().doc.documentElement.outerHTML
).then(async res => {
// console.log('详情页-基本信息解析完成', new Date())
window.pageData.post = res
await cbChecker({type: 'postContent', value: res}, 0)
})
window.parse.getPostAllReplies(
{id: window.pageData.id},
$(window.win().doc.body),
window.win().doc.documentElement.outerHTML,
window.pageData.pageNo
).then(async res => {
// console.log('详情页-回复解析完成', new Date())
window.pageData.post = Object.assign(window.pageData.post, res)
await cbChecker({type: 'postReplies', value: res}, 0)
})
break
default:
console.error('未知页面')
break
}
}
//发布脚本,从这里结束复制
//发布脚本,从这里结束复制
//发布脚本,从这里结束复制
//开发时自动更新window.top head里面添加的vue style
if (window.win().isFrame && isDev) {
function getStyle(html) {
let reg = html.match(/(<title>Vite App<\/title>[\s\S]+)/g)
if (reg) {
return reg[0]
}
return `<style></style>`
}
function removeVueStyle() {
let title = $('title:nth-child(2)', window.win().doc.head)
while (title.next().length) {
title.next().remove()
}
title.remove()
}
window.onbeforeunload = removeVueStyle
let observe = new MutationObserver(() => {
removeVueStyle()
let headHtml = window.document.head.innerHTML
let reg = getStyle(headHtml)
$(window.win().doc.head).append($(`<head>${reg}</head>`))
});
observe.observe(window.document.head, {
attributes: true, //目标节点的属性变化
childList: true, //目标节点的子节点的新增和删除
characterData: true, //如果目标节点为characterData节点(一种抽象接口,具体可以为文本节点,注释节点,以及处理指令节点)时,也要观察该节点的文本内容是否发生变化
subtree: true, //目标节点所有后代节点的attributes、childList、characterData变化
});
}
</script>
<script type="module" src="/src/main.js"></script>
</body>
</html>