forked from Reamd7/notion-zh_CN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.js
88 lines (81 loc) · 2.2 KB
/
worker.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
const BaseUrl = "自定义cloudflare worker 域名"
const NotionUrl = "www.notion.so";
const BasePath = `https://${BaseUrl}`;
const NotionPath = `https://${NotionUrl}`;
addEventListener('fetch', function(event) {
event.respondWith(handleRequest(event.request))
})
class ElementHandler {
async element(element) {
const res = await fetch("https://cdn.jsdelivr.net/gh/Reamd7/notion-zh_CN@main/json/zh.json").then(res => {
return res.text();
})
element.prepend(`
<script id="messages" type="application/json" data-locale="zh-CN">
${res}
</script>
`, {
html: true
})
}
}
class ScriptHandler {
element(element) {
element.append(`
<script>
window.CONFIG.domainBaseUrl = "${BasePath}"
</script>
`, {
html: true
})
}
}
async function handleRequest(request) {
const method = request.method;
const headers = new Headers(request.headers);
headers.set("origin", NotionPath)
headers.set("referer", NotionPath);
headers.set("host", NotionPath);
const destinationURL = request.url.replace(BaseUrl, NotionUrl);
if (method === "GET") {
const headers = request.headers;
return fetch(destinationURL, {
method: request.method,
headers: headers,
}).then(rep => {
const contentType = rep.headers.get("Content-Type")
if (contentType.startsWith("text/html")) {
return new HTMLRewriter().on("head", new ElementHandler()).on("body", new ScriptHandler()).transform(rep)
}
return rep;
})
} else {
let selfheader = {};
headers.forEach((v, k) => {
selfheader[k] = v;
})
selfheader = {
...selfheader,
origin: NotionPath,
referer: NotionPath,
host: NotionPath,
}
const newR = new Request(destinationURL, {
...request,
method: request.method,
headers: selfheader,
body: request.body,
});
return fetch(newR).then(rep => {
let selfheader = {};
rep.headers.forEach((v, k) => {
selfheader[k] = v.replaceAll(NotionUrl, BaseUrl);
})
return new Response(rep.body, {
status: rep.status,
statusText: rep.statusText,
headers: selfheader
})
})
}
}