forked from xifangczy/cat-catch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunction.js
254 lines (244 loc) · 8.45 KB
/
function.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
// 追加0
function appendZero(date) {
return parseInt(date) < 10 ? `0${date}` : date;
}
// 秒转换成时间
function secToTime(sec) {
let hour = (sec / 3600) | 0;
let min = ((sec % 3600) / 60) | 0;
sec = (sec % 60) | 0;
let time = hour > 0 ? hour + ":" : "";
time += min.toString().padStart(2, '0') + ":";
time += sec.toString().padStart(2, '0');
return time;
}
// 字节转换成大小
function byteToSize(byte) {
if (!byte || byte < 1024) { return 0; }
if (byte < 1024 * 1024) {
return (byte / 1024).toFixed(1) + "KB";
} else if (byte < 1024 * 1024 * 1024) {
return (byte / 1024 / 1024).toFixed(1) + "MB";
} else {
return (byte / 1024 / 1024 / 1024).toFixed(1) + "GB";
}
}
// Firefox download API 无法下载 data URL
function downloadDataURL(url, fileName) {
const link = document.createElement("a");
link.href = url;
link.download = fileName;
link.click();
delete link;
}
// 判断是否为空
function isEmpty(obj) {
return (typeof obj == "undefined" ||
obj == null ||
obj == "" ||
obj == " ")
}
// 修改请求头
function setRequestHeaders(data = {}, callback = undefined) {
chrome.tabs.getCurrent(function (tabs) {
const rules = { removeRuleIds: [tabs ? tabs.id : 1] };
if (Object.keys(data).length) {
const requestHeaders = Object.keys(data).map(key => ({ header: key, operation: "set", value: data[key] }));
rules.addRules = [{
"id": tabs ? tabs.id : 1,
"action": {
"type": "modifyHeaders",
"requestHeaders": requestHeaders
},
"condition": {
"resourceTypes": ["xmlhttprequest", "media", "image"]
}
}];
if (tabs) {
rules.addRules[0].condition.tabIds = [tabs.id];
}
}
// console.log(rules);
chrome.declarativeNetRequest.updateSessionRules(rules, function () {
callback && callback();
});
});
}
function awaitG(callback, sec = 0) {
const timer = setInterval(() => {
if (G.initSyncComplete && G.initLocalComplete) {
clearInterval(timer);
callback();
}
}, sec);
}
// 分割字符串
function splitString(text, separator) {
text = text.trim();
if (text.length == 0) { return []; }
const parts = [];
let inQuotes = false;
let inSingleQuotes = false;
let start = 0;
for (let i = 0; i < text.length; i++) {
if (text[i] === separator && !inQuotes && !inSingleQuotes) {
parts.push(text.slice(start, i));
start = i + 1;
} else if (text[i] === '"' && !inSingleQuotes) {
inQuotes = !inQuotes;
} else if (text[i] === "'" && !inQuotes) {
inSingleQuotes = !inSingleQuotes;
}
}
parts.push(text.slice(start));
return parts;
}
// 模板 函数 实现
function templatesFunction(text, action, data) {
text = isEmpty(text) ? "" : text.toString();
action = splitString(action, "|");
for (let item of action) {
let action = item.trim(); // 函数
let arg = []; //参数
// 查找 ":" 区分函数与参数
const colon = item.indexOf(":");
if (colon != -1) {
action = item.slice(0, colon).trim();
arg = splitString(item.slice(colon + 1).trim(), ",").map(item => {
return item.trim().replace(/^['"]|['"]$/g, "");
});
}
// 字符串不允许为空 除非 exists find 函数
if (isEmpty(text) && action != "exists" && action != "find") { return "" };
// 参数不能为空 除非 filter 函数
if (arg.length == 0 && action != "filter") { return text }
if (action == "slice") {
text = text.slice(...arg);
} else if (action == "replace") {
text = text.replace(...arg);
} else if (action == "replaceAll") {
text = text.replaceAll(...arg);
} else if (action == "regexp") {
const result = text.match(new RegExp(...arg));
text = "";
if (result && result.length >= 2) {
for (let i = 1; i < result.length; i++) {
text += result[i].trim();
}
}
} else if (action == "exists") {
if (text) {
text = arg[0].replaceAll("*", text);
continue;
}
if (arg[1]) {
text = arg[1].replaceAll("*", text);
continue;
}
text = "";
} else if (action == "to") {
if (arg[0] == "base64") {
text = window.Base64 ? Base64.encode(text) : btoa(unescape(encodeURIComponent(text)));
} else if (arg[0] == "urlEncode") {
text = encodeURIComponent(text);
} else if (arg[0] == "urlDecode") {
text = decodeURIComponent(text);
} else if (arg[0] == "lowerCase") {
text = text.toLowerCase();
} else if (arg[0] == "upperCase") {
text = text.toUpperCase();
} else if (arg[0] == "trim") {
text = text.trim();
} else if (arg[0] == "filter") {
text = stringModify(text.trim());
}
} else if (action == "find") {
text = "";
if (data.pageDOM) {
try {
text = data.pageDOM.querySelector(arg[0]).innerHTML;
} catch (e) { text = ""; }
}
} else if (action == "filter") {
text = stringModify(text, arg[0]);
}
}
return text;
}
function templates(text, data) {
if (isEmpty(text)) { return ""; }
// fullFileName
try {
data.fullFileName = new URL(data.url).pathname.split("/").pop();
} catch (e) {
data.fullFileName = 'NULL';
}
// fileName
data.fileName = data.fullFileName.split(".");
data.fileName.length > 1 && data.fileName.pop();
data.fileName = data.fileName.join(".");
// ext
if (isEmpty(data.ext)) {
data.ext = data.fullFileName.split(".");
data.ext = data.ext.length == 1 ? "" : data.ext[data.ext.length - 1];
}
const date = new Date();
let _data = {
// 资源信息
url: data.url ?? "",
referer: data.requestHeaders?.referer ?? "",
origin: data.requestHeaders?.origin ?? "",
initiator: data.requestHeaders?.referer ? data.requestHeaders.referer : data.initiator,
webUrl: data.webUrl ?? "",
title: data._title ?? data.title,
pageDOM: data.pageDOM,
cookie: data.cookie ?? "",
// 时间相关
year: date.getFullYear(),
month: appendZero(date.getMonth() + 1),
date: appendZero(date.getDate()),
day: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][date.getDay()],
fullDate: `${date.getFullYear()}-${appendZero(date.getMonth() + 1)}-${appendZero(date.getDate())}`,
time: `${appendZero(date.getHours())}'${appendZero(date.getMinutes())}'${appendZero(date.getSeconds())}`,
hours: appendZero(date.getHours()),
minutes: appendZero(date.getMinutes()),
seconds: appendZero(date.getSeconds()),
now: Date.now(),
// 文件名
fullFileName: data.fullFileName ? data.fullFileName : "",
fileName: data.fileName ? data.fileName : "",
ext: data.ext ?? "",
// 全局变量
mobileUserAgent: G.MobileUserAgent,
userAgent: G.userAgent ? G.userAgent : navigator.userAgent,
}
_data = { ...data, ..._data };
text = text.replace(reTemplates, function (original, tag, action) {
tag = tag.trim();
if (action) {
return templatesFunction(_data[tag], action.trim(), _data);
}
return _data[tag] ?? original;
});
return text;
}
// 从url中获取文件名
function getUrlFileName(url) {
let pathname = new URL(url).pathname;
let filename = pathname.split("/").pop();
return filename ? filename : "NULL";
}
/**
* 解析json字符串 解析错误返回默认值
* @param {string} str json字符串
* @param {object} error 解析错误返回的默认值
* @returns {object} 返回解析后的对象
*/
function JSONparse(str, error = {}) {
if (!str) { return error; }
try {
return JSON.parse(str);
} catch (e) {
return error;
}
}