-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
195 lines (175 loc) · 5.33 KB
/
utils.js
File metadata and controls
195 lines (175 loc) · 5.33 KB
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
const { DEFAULT_HOST, DEFAULT_PORT, DEFAULT_TOKEN } = require("./config");
const dbHost = utools.dbStorage.getItem("host");
const dbPort = utools.dbStorage.getItem("port");
const dbToken = utools.dbStorage.getItem("token");
const api = `http://${dbHost || DEFAULT_HOST}:${dbPort || DEFAULT_PORT}/api`;
const token = dbToken || DEFAULT_TOKEN;
/**
* request 方法
* @param {string} url - 请求的 URL
* @param {Object} options - 请求选项
* @param {string} [options.method='GET'] - 请求方法 (GET, POST, PUT, DELETE, etc.)
* @param {Object} [options.headers={}] - 请求头
* @param {Object|string} [options.body=null] - 请求体 (对于 POST 和 PUT 请求)
* @returns {Promise<Object>} - 返回一个 Promise,解析为响应的 JSON 对象
*/
const request = async (url, options = {}) => {
// 设置默认的请求方法为 GET
const method = options.method || "GET";
// 设置默认的请求头
const headers = options.headers || {};
// 处理请求体
let body = options.body || null;
// 如果请求体是一个对象,将其转换为 JSON 字符串,并设置 Content-Type 为 application/json
if (typeof body === "object" && !(body instanceof FormData)) {
body = JSON.stringify(body);
headers["Content-Type"] = "application/json";
}
// 发送请求
try {
const response = await fetch(url, {
method,
headers,
body,
}).catch((error) => {
utools.showNotification(`❌ 出错:${JSON.stringify(error)}`);
});
if (!response) return;
// 检查响应状态码
if (!response.ok) {
utools.showNotification(
`❌ 出错:HTTP error! status: ${response.status}`
);
throw new Error(`HTTP error! status: ${response.status}`);
}
// 解析响应为 JSON
return response.json();
} catch (error) {
if (error?.name === "AbortError") {
console.log("Aborted");
} else {
throw error;
}
}
};
/**
*
* @param {*} param0
* @param {*} args
* @returns
*/
const logseqRequest = ({ logseqApi, signal }, args) => {
return request(api, {
signal,
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: {
method: logseqApi,
args,
},
});
};
const dateFormatters = {
do: (date) => getOrdinalDate(date.getDate()),
MMM: (date) =>
new Intl.DateTimeFormat("en-US", { month: "short" }).format(date),
MMMM: (date) =>
new Intl.DateTimeFormat("en-US", { month: "long" }).format(date),
E: (date) =>
new Intl.DateTimeFormat("en-US", { weekday: "short" }).format(date),
EEE: (date) =>
new Intl.DateTimeFormat("en-US", { weekday: "short" }).format(date),
EEEE: (date) =>
new Intl.DateTimeFormat("en-US", { weekday: "long" }).format(date),
dd: (date) => pad(date.getDate()),
MM: (date) => pad(date.getMonth() + 1),
yyyy: (date) => date.getFullYear(),
};
const formatDate = (date, format) => {
return format.replace(/do|MMM|MMMM|E{1,4}|dd|MM|yyyy/g, (match) => {
return dateFormatters[match] ? dateFormatters[match](date) : match;
});
};
const getOrdinalDate = (date) => {
const suffixes = ["th", "st", "nd", "rd"];
const v = date % 100;
return date + (suffixes[(v - 20) % 10] || suffixes[v] || suffixes[0]);
};
const pad = (number) => (number < 10 ? "0" + number : number);
const base64ToBuffer = (base64String) => {
const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, "+")
.replace(/_/g, "/");
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
};
const dataUrlToBuffer = (urlData) => {
const [head, base64] = urlData.split(",");
const type = head.match(/:(.*?);/)[1];
return [base64ToBuffer(base64), type];
};
/**
* 根据文件名匹配文件类型和格式
* @param {string} fileName - 文件名
* @returns {Object} - 包含类型和格式的对象
*/
function getFileTypeAndFormat(fileName) {
// 文件类型和对应的格式
const fileTypes = {
image: ["jpg", "jpeg", "png", "gif", "bmp", "tiff", "svg", "webp"],
video: ["mp4", "avi", "mov", "mkv", "flv", "wmv", "webm"],
audio: ["mp3", "wav", "flac", "aac", "ogg", "wma"],
markdown: ["md"],
pdf: ["pdf"],
document: ["txt", "doc", "docx", "xls", "xlsx", "ppt", "pptx"],
archive: ["zip", "rar", "7z", "tar", "gz"],
code: [
"html",
"css",
"js",
"jsx",
"ts",
"tsx",
"java",
"py",
"cpp",
"c",
"cs",
"php",
],
};
// 获取文件扩展名
const extension = fileName.split(".").pop().toLowerCase();
const name = fileName.replace(`.${extension}`, "");
// 匹配文件类型
for (const [type, formats] of Object.entries(fileTypes)) {
if (formats.includes(extension)) {
return { type, format: extension, name };
}
}
// 如果没有匹配的类型和格式,返回未知类型
return { type: "unknown", format: extension, name };
}
const debounce = (func, wait = 300) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => func(...args), wait);
};
};
module.exports = {
request,
logseqRequest,
formatDate,
dataUrlToBuffer,
getFileTypeAndFormat,
debounce,
};