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
| <script>
(function () {
const shell = document.querySelector('.attachments-shell[data-openlist-endpoint]');
if (!shell) return;
const endpoint = shell.dataset.openlistEndpoint.replace(/\/+$/, '');
const rootPath = normalizePath(shell.dataset.openlistRoot || '/');
const list = document.getElementById('attachmentsList');
const breadcrumb = document.getElementById('attachmentsBreadcrumb');
const alertBox = document.getElementById('attachmentsAlert');
let currentPath = coerceToRoot(getInitialPath());
let entries = [];
let isLoading = false;
function normalizePath(value) {
let path = String(value || '/').replace(/\\/g, '/').trim();
if (!path.startsWith('/')) path = '/' + path;
path = path.replace(/\/+/g, '/');
if (path.length > 1) path = path.replace(/\/$/, '');
return path || '/';
}
function coerceToRoot(path) {
const normalized = normalizePath(path);
if (rootPath === '/') return normalized;
return normalized === rootPath || normalized.startsWith(rootPath + '/') ? normalized : rootPath;
}
function getInitialPath() {
const params = new URLSearchParams(window.location.search);
return params.get('path') || rootPath;
}
function joinPath(base, name) {
return normalizePath((base === '/' ? '' : base) + '/' + name);
}
function formatSize(size) {
if (!Number.isFinite(size) || size < 0) return '大小未知';
if (size === 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let value = size;
let index = 0;
while (value >= 1024 && index < units.length - 1) {
value /= 1024;
index++;
}
return (value >= 10 || index === 0 ? value.toFixed(0) : value.toFixed(1)) + ' ' + units[index];
}
function formatDate(value) {
if (!value) return '时间未知';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return '时间未知';
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
}
function fileExtension(name) {
const index = name.lastIndexOf('.');
if (index <= 0 || index === name.length - 1) return 'FILE';
return name.slice(index + 1, index + 5).toUpperCase();
}
function fileKind(name) {
const extension = fileExtension(name).toLowerCase();
if (['epub', 'mobi', 'azw', 'azw3', 'fb2', 'cbz', 'cbr'].includes(extension)) return 'book';
if (extension === 'pdf') return 'pdf';
if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp', 'heic', 'avif'].includes(extension)) return 'image';
if (['mp4', 'mkv', 'mov', 'avi', 'webm', 'flv', 'wmv'].includes(extension)) return 'video';
if (['mp3', 'flac', 'wav', 'aac', 'ogg', 'm4a'].includes(extension)) return 'audio';
if (['zip', 'rar', '7z', 'tar', 'gz', 'bz2', 'xz'].includes(extension)) return 'archive';
if (['js', 'ts', 'jsx', 'tsx', 'go', 'py', 'java', 'rs', 'c', 'cpp', 'cs', 'html', 'css', 'scss', 'json', 'yaml', 'yml', 'xml', 'md'].includes(extension)) return 'code';
if (['db', 'sql', 'csv', 'xlsx', 'xls'].includes(extension)) return 'data';
if (['doc', 'docx', 'ppt', 'pptx', 'txt', 'rtf'].includes(extension)) return 'document';
return 'file';
}
function sortEntries(items) {
return [...items].sort((left, right) => {
if (left.is_dir !== right.is_dir) return left.is_dir ? -1 : 1;
return left.name.localeCompare(right.name, 'zh-CN', { numeric: true, sensitivity: 'base' });
});
}
async function postOpenList(route, body) {
const response = await fetch(endpoint + route, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
});
if (!response.ok) {
throw new Error('Files 请求失败:HTTP ' + response.status);
}
const payload = await response.json();
if (payload.code !== 200) {
throw new Error(payload.message || 'Files 返回了异常状态');
}
return payload.data || {};
}
function setBusy(nextBusy) {
isLoading = nextBusy;
shell.classList.toggle('is-loading', nextBusy);
}
function showAlert(message) {
if (!message) {
alertBox.hidden = true;
alertBox.textContent = '';
return;
}
alertBox.hidden = false;
alertBox.textContent = message;
}
function renderBreadcrumb() {
breadcrumb.replaceChildren();
const rootParts = rootPath.split('/').filter(Boolean);
const currentParts = currentPath.split('/').filter(Boolean);
const visibleParts = currentParts.slice(rootParts.length);
const rootButton = document.createElement('button');
rootButton.type = 'button';
rootButton.textContent = 'Files';
rootButton.disabled = currentPath === rootPath;
rootButton.addEventListener('click', () => navigateTo(rootPath));
breadcrumb.appendChild(rootButton);
let cumulative = rootPath;
visibleParts.forEach((part, index) => {
const separator = document.createElement('span');
separator.textContent = '/';
separator.setAttribute('aria-hidden', 'true');
breadcrumb.appendChild(separator);
const crumbPath = joinPath(cumulative, part);
cumulative = crumbPath;
const crumb = document.createElement('button');
crumb.type = 'button';
crumb.textContent = part;
crumb.disabled = index === visibleParts.length - 1;
crumb.addEventListener('click', () => navigateTo(crumbPath));
breadcrumb.appendChild(crumb);
});
}
function renderEntries() {
const sortedEntries = sortEntries(entries);
const fragment = document.createDocumentFragment();
if (sortedEntries.length === 0) {
const empty = document.createElement('div');
empty.className = 'attachments-empty';
const title = document.createElement('h3');
title.textContent = '这个目录暂时为空';
const description = document.createElement('p');
description.textContent = '可以通过上方路径返回其它目录。';
empty.append(title, description);
list.replaceChildren(empty);
return;
}
sortedEntries.forEach((item) => {
const itemRow = document.createElement('article');
const itemPath = joinPath(currentPath, item.name);
const kind = item.is_dir ? 'folder' : fileKind(item.name);
itemRow.className = 'attachments-list-item attachments-list-item--' + kind + (item.is_dir ? ' is-directory' : '');
itemRow.tabIndex = 0;
itemRow.setAttribute('role', 'button');
itemRow.setAttribute('aria-label', (item.is_dir ? '打开目录 ' : '下载文件 ') + item.name);
const icon = document.createElement('div');
icon.className = 'attachments-file-icon attachments-file-icon--' + kind;
if (item.is_dir) {
icon.setAttribute('aria-hidden', 'true');
} else {
icon.textContent = fileExtension(item.name);
}
const body = document.createElement('div');
body.className = 'attachments-list-body';
const title = document.createElement('h3');
title.textContent = item.name;
const meta = document.createElement('p');
meta.textContent = item.is_dir ? '目录 · ' + formatDate(item.modified) : formatSize(Number(item.size)) + ' · ' + formatDate(item.modified);
body.append(title, meta);
itemRow.append(icon, body);
const open = () => {
if (isLoading) return;
if (item.is_dir) {
navigateTo(itemPath);
} else {
openFile(itemPath, item.name);
}
};
itemRow.addEventListener('click', open);
itemRow.addEventListener('keydown', (event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
open();
}
});
fragment.appendChild(itemRow);
});
list.replaceChildren(fragment);
}
function updateUrl(path, replace) {
const url = new URL(window.location.href);
if (path === rootPath) {
url.searchParams.delete('path');
} else {
url.searchParams.set('path', path);
}
const state = { path: path };
if (replace) {
window.history.replaceState(state, '', url);
} else {
window.history.pushState(state, '', url);
}
}
async function loadDirectory(path, options) {
const nextPath = coerceToRoot(path);
currentPath = nextPath;
renderBreadcrumb();
setBusy(true);
showAlert('');
try {
const data = await postOpenList('/api/fs/list', {
path: currentPath,
password: '',
page: 1,
per_page: 1000,
refresh: Boolean(options && options.refresh)
});
entries = Array.isArray(data.content) ? data.content : [];
renderEntries();
if (!options || !options.skipHistory) {
updateUrl(currentPath, Boolean(options && options.replaceHistory));
}
} catch (error) {
entries = [];
list.replaceChildren();
showAlert(error.message || 'Files 暂时无法访问');
} finally {
setBusy(false);
}
}
function navigateTo(path) {
loadDirectory(path, { skipHistory: false });
}
async function openFile(path, name) {
setBusy(true);
showAlert('');
try {
const data = await postOpenList('/api/fs/get', {
path: path,
password: ''
});
if (!data.raw_url) {
throw new Error('这个文件暂时没有可用的直链');
}
const link = document.createElement('a');
link.href = data.raw_url;
link.download = name;
link.rel = 'noopener noreferrer';
document.body.appendChild(link);
link.click();
link.remove();
} catch (error) {
showAlert(error.message || '下载链接获取失败');
} finally {
setBusy(false);
}
}
window.addEventListener('popstate', () => loadDirectory(getInitialPath(), { skipHistory: true }));
loadDirectory(currentPath, { replaceHistory: true });
})();
</script>
{{ end }}
|