Skip to content

Commit 7212843

Browse files
committed
fix token-fetcher
update msg-passing with Hooker unlimited storage enabled
1 parent 2888492 commit 7212843

11 files changed

+226
-68
lines changed

ChangeLog.md

+5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
# 知乎疯牛病 --- 更新日志
22

3+
## 1.0.8
4+
* 部分移除本地数据库的容量限制
5+
* 紧急修复token获取问题
6+
* 优化了与Hooker的信息传递机制
7+
38
## 1.0.7
49
* 知乎改前端啦,紧急修复
510
* 几个辅助页面的小修复

DBExportor/POD.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,8 @@ unsafe public override int GetHashCode(byte[] obj)
5757
}
5858
}
5959
}
60-
private static readonly Dictionary<byte[], uint> Mapper = new Dictionary<byte[], uint>(3000000, new ByteStringComparer());
61-
private static readonly List<byte[]> Cache = new List<byte[]>(3000000);
60+
private static readonly Dictionary<byte[], uint> Mapper = new Dictionary<byte[], uint>(5000000, new ByteStringComparer());
61+
private static readonly List<byte[]> Cache = new List<byte[]>(5000000);
6262
static UIDPool()
6363
{
6464
Cache.Add(null);

ZhiHuExt/ContentBase.js

+75-3
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
let _CUR_USER;
44
let _CUR_ANSWER;
55
let _CUR_QUESTION;
6-
/**@type {UserToken}*/
6+
/**@type {UserToken|UserToken2}*/
77
let _CUR_TOKEN;
8+
/**@type {HTMLScriptElement}*/
9+
let _CUR_HOOKER;
810
let _Base_Lim_Date = new Date(2017, 1, 1).toUTCSeconds();
911
class ContentBase
1012
{
@@ -16,6 +18,7 @@ class ContentBase
1618
static set CUR_QUESTION(qst) { _CUR_QUESTION = qst; }
1719
static get CUR_TOKEN() { return _CUR_TOKEN; }
1820
static set CUR_TOKEN(token) { _CUR_TOKEN = token; }
21+
static get CUR_HOOKER() { return _CUR_HOOKER; }
1922
static get BASE_LIM_DATE() { return _Base_Lim_Date; }
2023
static set BASE_LIM_DATE(time) { time = _Base_Lim_Date; }
2124

@@ -164,6 +167,30 @@ class ContentBase
164167
return;
165168
chrome.runtime.sendMessage({ action: "update", target: target, data: { key: key, obj: objs, updator: updator } });
166169
}
170+
static reportSpam(id, type)
171+
{
172+
const payload = { "resource_id": id, "type": type, "reason_type": "spam", "source": "web" };
173+
const pms = $.Deferred();
174+
ContentBase._post("https://www.zhihu.com/api/v4/reports", payload)
175+
.done((data, status, xhr) =>
176+
{
177+
if (xhr.status === 204 || xhr.status === 200)
178+
{
179+
pms.resolve();
180+
ContentBase._report("spams", { id: id, type: type });
181+
}
182+
})
183+
.fail((data, status, xhr) =>
184+
{
185+
if (data.responseJSON)
186+
pms.reject({ code: data.responseJSON.error.code, error: data.responseJSON.error.message });
187+
else
188+
pms.reject({ code: xhr.status, error: "unknown error" });
189+
})
190+
return pms;
191+
}
192+
193+
167194
/**@param {string} rawhtml*/
168195
static keepOnlyDataDiv(rawhtml)
169196
{
@@ -233,7 +260,7 @@ class ContentBase
233260
let errcnt = 0;
234261
let time = begintime || new Date().toUTCSeconds();
235262
limittime = limittime || ContentBase.BASE_LIM_DATE;
236-
const tokenhead = ContentBase.CUR_TOKEN.toHeader();
263+
const tokenhead = ContentBase.CUR_TOKEN ? ContentBase.CUR_TOKEN.toHeader() : {};
237264
const ret = new StandardDB();
238265
let isEnd = false;
239266
for (let i = 0; i < maxloop && time > limittime && !isEnd; ++i)
@@ -398,7 +425,8 @@ class ContentBase
398425
return;
399426
}
400427
const state = JSON.parse(dataElement.dataset.state);
401-
ContentBase.CUR_TOKEN = new UserToken(state.token);
428+
if(state.token)
429+
ContentBase.CUR_TOKEN = new UserToken(state.token);
402430
const theuser = state.entities.users[uid];
403431
if (!theuser)
404432
{
@@ -434,4 +462,48 @@ class ContentBase
434462
}
435463
}
436464

465+
/**@param e {CustomEvent}*/
466+
function hookerHandler(e)
467+
{
468+
switch (e.detail.type)
469+
{
470+
case "udid":
471+
{
472+
const oldId = ContentBase.CUR_TOKEN && ContentBase.CUR_TOKEN.xUDID;
473+
if (e.detail.udid != oldId)
474+
{
475+
ContentBase.CUR_TOKEN = new UserToken2(e.detail.udid);
476+
console.log("UDID changed:", oldId, e.detail.udid, e);
477+
}
478+
} break;
479+
}
480+
}
481+
482+
{
483+
const obs = new MutationObserver(records =>
484+
{
485+
for (let i = 0; i < records.length; ++i)
486+
{
487+
const record = records[i];
488+
if (record.type != "childList")
489+
continue;
490+
const nodes = record.addedNodes;
491+
for (let j = 0; j < nodes.length; ++j)
492+
{
493+
const node = nodes[j];
494+
if (!(node instanceof HTMLScriptElement))
495+
continue;
496+
if (node.id === "ZHIHU_HOOKER")
497+
{
498+
obs.disconnect();
499+
_CUR_HOOKER = node;
500+
node.addEventListener("ZHHookerNotify", hookerHandler);
501+
console.log("[ZHIHU_Hook] inked!");
502+
return;
503+
}
504+
}
505+
}
506+
});
507+
obs.observe(document, { "childList": true, "subtree": true });
508+
}
437509

ZhiHuExt/PageEnhance.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@
7272
console.log(state);
7373
const entities = APIParser.parseEntities(state.entities);
7474
ContentBase._report("batch", entities);
75-
ContentBase.CUR_TOKEN = new UserToken(state.token);
75+
if (state.token)
76+
ContentBase.CUR_TOKEN = new UserToken(state.token);
7677
console.log(entities);
7778
if (pageType === "people")
7879
{

ZhiHuExt/StatVoter.html

+6-6
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,18 @@
2525
<div>
2626
<h3 style="text-align:center">
2727
<span id="zansum"></span>个赞中, 有<span id="banzansum"></span>个来自封禁用户的赞
28-
<button id="chkAllStatus">检测全部</button>
28+
<button id="chkAllStatus">检测全部</button><button id="Btn-Similarity">相似度</button>
2929
</h3>
3030
<table id="maintable" class="cell-border hover order-column stripe" width="100%">
3131
<thead>
3232
<tr>
33-
<th width="35%">名字</th>
34-
<th width="13%">状态</th>
35-
<th width="10%">文章数</th>
36-
<th width="10%">回答数</th>
33+
<th width="30%">名字</th>
34+
<th width="10%">状态</th>
35+
<th width="7%">文章数</th>
36+
<th width="8%">回答数</th>
3737
<th width="10%">关注者</th>
3838
<th width="10%">赞数</th>
39-
<th width="12%">点赞计数</th>
39+
<th width="10%">点赞计数</th>
4040
</tr>
4141
</thead>
4242
</table>

ZhiHuExt/StatVoter.js

+69-3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,31 @@
44
let finalUserMap;
55
/**@type {SimpleBag}*/
66
let finalBag;
7+
let CUR_ANSWER, CUR_
8+
9+
function reportSpam(id, type)
10+
{
11+
const payload = { "resource_id": id, "type": type, "reason_type": "spam", "source": "web" };
12+
//req.setRequestHeader("Referer", "https://www.zhihu.com/people/" + id + "/activities");
13+
const pms = $.Deferred();
14+
ContentBase._post("https://www.zhihu.com/api/v4/reports", payload)
15+
.done((data, status, xhr) =>
16+
{
17+
if (xhr.status === 204 || xhr.status === 200)
18+
{
19+
pms.resolve();
20+
ContentBase._report("spams", { id: id, type: type });
21+
}
22+
})
23+
.fail((data, status, xhr) =>
24+
{
25+
if (data.responseJSON)
26+
pms.reject({ code: data.responseJSON.error.code, error: data.responseJSON.error.message });
27+
else
28+
pms.reject({ code: xhr.status, error: "unknown error" });
29+
})
30+
return pms;
31+
}
732

833
/**
934
* @param {...BagArray} voters
@@ -37,14 +62,15 @@ async function StatVoters(...voters)
3762
{
3863
paging: true,
3964
deferRender: true,
40-
lengthMenu: [[20, 50, 100, -1], [20, 50, 100, "All"]],
65+
lengthMenu: [[20, 100, 200, -1], [20, 100, 200, "All"]],
4166
data: data,
4267
order: [[6, "desc"], [5, "desc"], [1, "asc"]],
4368
columns:
4469
[
4570
{
4671
data: "usr",
47-
render: displayRender(dat => `<a class="bgopen usr" data-id="${dat.id}" href="https://www.zhihu.com/people/${dat.id}">${dat.name}</a>`)
72+
render: displayRender(dat => `<a class="bgopen usr" data-id="${dat.id}" href="https://www.zhihu.com/people/${dat.id}">${dat.name}</a>
73+
<button class="Btn-ReportSpam" data-id="${dat.id}" data-type="member">广告</button>`)
4874
},
4975
{
5076
data: "status",
@@ -118,7 +144,47 @@ $(document).on("click", "#copyusr", e =>
118144
const request = { action: "copy", data: JSON.stringify(finalBag.elements()) };
119145
SendMsgAsync(request);
120146
});
121-
147+
$("body").on("click", "button.Btn-ReportSpam", e =>
148+
{
149+
const btn = e.target;
150+
reportSpam(btn.dataset.id, btn.dataset.type)
151+
.done(() => btn.style.backgroundColor = "rgb(0,224,32)")
152+
.fail((e) =>
153+
{
154+
console.warn("report fail:" + e.code, e.error);
155+
if (e.code === 103001)//repeat
156+
btn.style.backgroundColor = "rgb(224,224,32)";
157+
else if (e.code === 4039)//need verify
158+
btn.style.backgroundColor = "rgb(32,64,192)";
159+
else
160+
btn.style.backgroundColor = "rgb(224,0,32)";
161+
});
162+
});
163+
$("body").on("click", "button.Btn-Similarity", e =>
164+
{
165+
const thisbtn = e.target;
166+
const msg = { action: "chksim", target: "user", data: null };
167+
/**@type {HTMLButtonElement[]}*/
168+
const btns = $("#maintable").find("button.Btn-ReportSpam").toArray();
169+
console.log("detect " + btns.length + " user");
170+
chrome.runtime.sendMessage(msg, /**@param {[string, [number, number, number]][]} result*/(result) =>
171+
{
172+
console.log(result);
173+
const simmap = new Map(result.data);
174+
let maxcnt = 0;
175+
btns.forEach(btn =>
176+
{
177+
const counts = simmap.get(btn.dataset.id);
178+
btn.textContent = `${counts[0]}(${counts[1]})/${counts[2]}`;
179+
btn.style.fontSize = "smaller";
180+
btn.style.fontWeight = "bold";
181+
maxcnt = Math.max(maxcnt, counts[0]);
182+
});
183+
thisbtn.textContent = `${maxcnt}(${result.limit})`;
184+
thisbtn.style.fontSize = "smaller";
185+
thisbtn.style.fontWeight = "bold";
186+
});
187+
});
122188

123189
!async function()
124190
{

ZhiHuExt/ZhiHuHooker.js

+21-10
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,12 @@
88
{
99
"use strict"
1010
window.BLOCKING_VOTER = false;
11-
/**@description parse query string to key-value object
11+
/**@type {HTMLScriptElement}*/
12+
const selfDom = document.querySelector("#ZHIHU_HOOKER");
13+
/**@type {string}*/
14+
let udid;
15+
/**
16+
* @description parse query string to key-value object
1217
* @param {string} qurl URL's query string
1318
* @returns {{[x:string]: string}} key-value object
1419
*/
@@ -49,16 +54,16 @@
4954
return resp;
5055
}
5156
/**
52-
* @param {HTMLElement} blockdom
5357
* @param {string} api
5458
* @param {string} id
5559
* @returns {Promise<Response>}
5660
*/
57-
function blockVoter(blockdom, api, id)
61+
function blockVoter(api, id)
5862
{
5963
id = typeof (window.BLOCKING_VOTER) === "number" ? window.BLOCKING_VOTER : id;
60-
if (blockdom)
61-
document.body.removeChild(blockdom);
64+
if (selfDom)
65+
selfDom.dataset.blockingVoters = false;
66+
//document.body.removeChild(blockdom);
6267
return new Promise(resolve =>
6368
{
6469
chrome.runtime.sendMessage(extid, { api: api, target: "BLOCKING", id: Number(id), data: null }, ret =>
@@ -79,6 +84,10 @@
7984
*/
8085
async function newfetch(req, init)
8186
{
87+
if (init && init.headers && init.headers.hasOwnProperty("X-UDID") && selfDom)
88+
{
89+
selfDom.dispatchEvent(new CustomEvent("ZHHookerNotify", {detail: {udid: init.headers["X-UDID"], type: "udid"}}));
90+
}
8291
if (!req.includes("www.zhihu.com/api/v"))
8392
return oldfetch(req, init);
8493
const apiparts = req.substring(req.indexOf("/api/v") + 8, req.indexOf("?")).split("/");
@@ -103,8 +112,9 @@
103112
}
104113
}
105114
const pms = oldfetch(newreq, init);
106-
const BLOCKING_FLAG = document.querySelector("#ZHE_BLOCKING_VOTER");
107-
const shouldBlock = window.BLOCKING_VOTER ? window.BLOCKING_VOTER : (BLOCKING_FLAG ? true : false);
115+
// const BLOCKING_FLAG = document.querySelector("#ZHE_BLOCKING_VOTER");
116+
// const shouldBlock = window.BLOCKING_VOTER ? window.BLOCKING_VOTER : (BLOCKING_FLAG ? true : false);
117+
const shouldBlock = window.BLOCKING_VOTER ? window.BLOCKING_VOTER : (selfDom && selfDom.dataset.blockingVoters ? true : false);
108118
if (apiparts[0] === "members")//capture [members, {id}, ...]
109119
{
110120
if (!apiparts[2])//empty, dirty hook for locked user
@@ -142,11 +152,11 @@
142152
}
143153
else if (apiparts[0] === "answers" && apiparts[2] === "voters")
144154
{
145-
return shouldBlock ? blockVoter(BLOCKING_FLAG, "answer", apiparts[1]) : sendData(req, pms, "answers", "voters", { id: apiparts[1] });
155+
return shouldBlock ? blockVoter("answer", apiparts[1]) : sendData(req, pms, "answers", "voters", { id: apiparts[1] });
146156
}
147157
else if (apiparts[0] === "articles" && apiparts[2] === "likers")
148158
{
149-
return shouldBlock ? blockVoter(BLOCKING_FLAG, "article", apiparts[1]) : sendData(req, pms, "articles", "voters", { id: apiparts[1] });
159+
return shouldBlock ? blockVoter("article", apiparts[1]) : sendData(req, pms, "articles", "voters", { id: apiparts[1] });
150160
}
151161
else if (apiparts[0] === "articles" && apiparts[2] === "recommendation")
152162
{
@@ -158,7 +168,7 @@
158168
}
159169
else if (apiparts[0] === "questions" && apiparts[2] === "followers")
160170
{
161-
return shouldBlock ? blockVoter(BLOCKING_FLAG, "questions", apiparts[1]) : sendData(req, pms, "questions", "qstfollows", { qid: apiparts[1] });
171+
return shouldBlock ? blockVoter("questions", apiparts[1]) : sendData(req, pms, "questions", "qstfollows", { qid: apiparts[1] });
162172
}
163173
else if (apiparts[0] === "explore" && apiparts[1] === "recommendations")
164174
{
@@ -208,6 +218,7 @@
208218

209219

210220
const inj = document.createElement("script");
221+
inj.id = "ZHIHU_HOOKER";
211222
inj.innerHTML = `(${Hooker})("${chrome.runtime.id}");`;
212223
document.documentElement.appendChild(inj);
213224
}()

ZhiHuExt/background.js

+8-5
Original file line numberDiff line numberDiff line change
@@ -173,13 +173,16 @@ function checkSpamUser(waitUsers, keepNormal)
173173
}
174174

175175
/**
176-
* @param {"answer" | "article"} target
177-
* @param {number | string} id
176+
* @param {"answer" | "article" | "user"} target
177+
* @param {number | string | string[]} id
178178
*/
179179
async function checkUserSimilarity(target, id)
180180
{
181-
const theid = Number(id);
182-
const voters = db.getVoters(theid, target);
181+
let voters;
182+
if (target === "user")
183+
voters = id;
184+
else
185+
voters = db.getVoters(Number(id), target);
183186
const result = await Analyse.findUserSimilarityInVote(voters);
184187
return result;
185188
}
@@ -534,7 +537,7 @@ chrome.runtime.onMessageExternal.addListener(
534537
}
535538
})();
536539

537-
chrome.notifications.onButtonClicked.addListener(notificationId =>
540+
chrome.notifications.onClicked.addListener(notificationId =>
538541
{
539542
if (notificationId === "UpdInfo")
540543
chrome.tabs.create({ active: true, url: "https://www.github.com/XZiar/ZhiHuExt/releases" });

0 commit comments

Comments
 (0)