-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.js
More file actions
727 lines (667 loc) · 29.9 KB
/
main.js
File metadata and controls
727 lines (667 loc) · 29.9 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
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
function onWindowLoad(callback) {
if (window.addEventListener) {
window.addEventListener('load', callback, false);
} else {
window.attachEvent('onload', callback);
}
}
function dom(select) {
return document.querySelectorAll(select);
}
// if file is a service worker
if (this.document && g_this_script !== 'inside_test') {
var g_this_script = g_this_script || document.currentScript;
var g_icon_base = null;
onWindowLoad(setup_menu);
onWindowLoad(setup_auth_html);
onWindowLoad(setup_files);
onWindowLoad(setup_page);
onWindowLoad(setup_upload);
if (g_this_script.attributes['env'].value == 'test') {
onWindowLoad(setup_test);
}
}
function el(tag, props, ch, attrs) {
var n = Object.assign(document.createElement(tag), (props === undefined) ? {} : props);
var child = (ch === undefined) ? [] : ch;
n = child.reduce((e, c) => { e.appendChild(c); return e; }, n);
var attributes = (attrs === undefined) ? {} : attrs;
n = Object.entries(attributes).reduce((e, [k, v]) => { e.setAttribute(k, v); return e; }, n);
return n;
}
Number.prototype.padLeft = function(base, chr) {
var len = (String(base || 10).length - String(this).length) + 1;
return len > 0 ? new Array(len).join(chr || '0') + this : this;
};
String.prototype.format = function() {
var args = arguments;
return this.replace(/{([0-9]+)}/g, function(match, index) {
return typeof args[index] == 'undefined' ? match : args[index];
});
};
IconMap = {
'7z': 'application-x-7z-compressed', 'aac': 'audio-x-generic', 'apk': 'android-package-archive', 'apng': 'image-png', 'atom': 'application-atom+xml', 'avi': 'audio-x-generic', 'bash': 'application-x-executable-script', 'bmp': 'image-bmp', 'c': 'text-x-csrc', 'cfg': 'text-x-generic', 'coffee': 'application-x-javascript', 'conf': 'text-x-generic', 'cpp': 'text-x-c++src', 'csh': 'application-x-executable-script', 'css': 'text-css', 'csv': 'text-csv', 'db': 'application-vnd.oasis.opendocument.database', 'deb': 'application-x-deb', 'desktop': 'application-x-desktop', 'doc': 'x-office-document', 'docx': 'x-office-document', 'eml': 'message-rfc822', 'epub': 'application-epub+zip', 'erb': 'application-x-ruby', 'ex': 'text-x-generic', 'exe': 'application-x-executable', 'fla': 'video-x-generic', 'flac': 'audio-x-flac', 'flv': 'video-x-generic', 'gif': 'image-gif', 'gml': 'text-xml', 'go': 'text-x-generic', 'gpx': 'text-xml', 'gz': 'application-x-gzip', 'h': 'text-x-chdr', 'hxx': 'text-x-c++hdr', 'hs': 'text-x-haskell', 'htm': 'text-html', 'html': 'text-html', 'ico': 'image-x-ico', 'ini': 'text-x-generic', 'iso': 'application-x-cd-image', 'jar': 'application-x-java-archive', 'java': 'application-x-java', 'jpeg': 'image-jpeg', 'jpg': 'image-jpeg', 'js': 'application-x-javascript', 'log': 'text-x-generic', 'lua': 'text-x-generic', 'm3u': 'audio-x-generic', 'markdown': 'text-x-generic', 'md': 'text-x-generic', 'mkv': 'video-x-matroska', 'mp3': 'audio-x-mpeg', 'mp4': 'video-mp4', 'odp': 'x-office-presentation', 'ods': 'x-office-spreadsheet', 'odt': 'x-office-document', 'ogg': 'audio-x-generic', 'otf': 'application-x-font-otf', 'pdf': 'application-pdf', 'pgp': 'application-pgp', 'php': 'application-x-php', 'pkg': 'package-x-generic', 'pl': 'application-x-perl', 'png': 'image-png', 'ppt': 'x-office-presentation', 'pptx': 'x-office-presentation', 'psd': 'image-x-psd', 'py': 'text-x-generic', 'pyc': 'application-x-python-bytecode', 'rar': 'application-x-rar', 'rb': 'application-x-ruby', 'rpm': 'application-x-rpm', 'rtf': 'text-rtf', 'sh': 'application-x-executable-script', 'svg': 'image-svg+xml-compressed', 'svgz': 'image-svg+xml-compressed', 'swf': 'application-x-shockwave-flash', 'tar': 'application-x-tar', 'text': 'text-x-generic', 'tiff': 'image-tiff', 'ttf': 'application-x-font-ttf', 'txt': 'text-x-generic', 'wav': 'audio-x-wav', 'webm': 'video-webm', 'wmv': 'video-x-wmv', 'xcf': 'image-x-xcf', 'xhtml': 'text-html', 'xls': 'x-office-spreadsheet', 'xlsx': 'x-office-spreadsheet', 'xml': 'text-xml', 'xpi': 'package-x-generic', 'xz': 'application-x-lzma-compressed-tar', 'zip': 'application-zip', 'zsh': 'application-x-executable-script', 'opml': 'text-xml', '.': 'folder',
};
function icontag(icon) {
return el('img', {
height: 24,
src: '{0}{1}.svg'.format(g_icon_base, icon.replace('/', '-')),
alt: '',
}, [], {
'class': 'fileicon',
'type': 'image/svg+xml',
'onerror': "this.src=\'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\'",
});
}
function iconFor(ext) {
var icon = 'application-octet-stream';
if (IconMap[ext] !== undefined) {
icon = IconMap[ext];
}
if (g_icon_base === null) {
return el('div');
}
return icontag(icon);
}
function file_ext(path) {
if (path.endsWith('/')) {
return '.';
}
return path.slice(path.lastIndexOf('.') + 1).toLowerCase();
}
function format_name(name, link) {
var fileext = file_ext(link);
var isdir = link.endsWith('/');
var html = el('a', {
href: link,
rel: 'noopener', // tabnabbing
...(isdir ? {} : { download: name })
}, [
iconFor(fileext),
el('span', { innerText: name }),
], { 'data-link': link });
return el('td', {}, [html], { 'data-sort': link });
}
function format_size(size) {
var bytes = size;
for (var u = 0; Math.abs(bytes) >= 1024; bytes /= 1024) u++;
var hsz = bytes.toFixed(!!u) + " " + "BKMGTPEZY"[u] + (u ? "iB" : "");
return el('td', {
title: size,
innerText: (size == 0) ? '-' : hsz
}, [], { 'data-sort': size });
}
function format_date(date, now, with_seconds) {
var d = new Date(date);
if (!d.getTime()) {
d = new Date(Number.MAX_SAFE_INTEGER / 10);
}
var iso = d.toISOString();
var formatted_24h = [d.getHours().padLeft(),
d.getMinutes().padLeft()].concat(with_seconds ? [d.getSeconds().padLeft()] : []).join(':');
return el('td', {
title: iso,
innerText: (() => {
var diff = Math.round(((now - d.getTime()) / 1000) + (d.getTimezoneOffset() * 60));
if (diff > (60 * 60 * 24 * 2)) { // more than 2days in the past
return formatted_24h +
' ' +
[d.getDate().padLeft(),
(d.getMonth() + 1).padLeft(),
d.getFullYear()].join('/');
} else if (diff > -(60 * 60 * 12)) {
var dim_s = [60, 60, 24];
var di = 0;
for (di = 0; diff >= dim_s[di] && di < 3; diff /= dim_s[di]) di++;
diff = Math.round(diff);
if (di > 2) { // More than one day
return "Yesterday" + ' ' + formatted_24h;
}
return diff + " " + ["second", "minute", "hour"][di] + (diff ? "s" : "") + " ago";
} else { // We are too far in the future don't display
return '-';
}
})()
}, [], { 'data-sort': date });
}
function sort_table(theads, tbodies, column, descending) {
// ui
theads.forEach(thead => [...thead.children].forEach((el, i) => {
delete el.dataset.sortway;
if (i == column) {
el.dataset.sortway = (descending ? 'descending' : 'ascending');
}
}));
tbodies.forEach(tbody => {
if (!tbody.rows.length) return;
tbody.style.cursor = 'progress';
var sorted = [...tbody.rows].map((tr, idx) => [tr, tr.cells[column].dataset.sort, idx])
.sort((a, b) => a[1].localeCompare(b[1], undefined, { 'numeric': true }) || (descending ? b[2] - a[2] : a[2] - b[2]))
.map((e) => e[0]);
tbody.append(...(descending ? sorted.reverse() : sorted));
tbody.style.cursor = 'default';
})
}
function table(headers, entries) {
return el('table', { border: 1, cellpadding: 1, cellspacing: 1 }, [
el('thead', { id: 'fthead' }, headers.map((f, idx) => el('th', {
role: 'colheader',
innerText: f
}, [], {
'onclick': "sort_table(dom('#fthead'), dom('#ftbody'), {0}, this.dataset.sortway == 'ascending')".format(idx),
}))),
el('tbody', { id: 'ftbody' }, entries, { 'item_count': entries.length }),
]);
}
function parse_entries(inp, now, date_format) {
var fpre_length = 4;
var fpre_cnt = {};
var fext_cnt = {};
var e = inp.split('\n').filter((l) => l.length > 0 && l != '<a href="../">../</a>').map((entry) => {
entry = entry.split('</a>');
var link = entry[0].split('">');
var link = decodeURIComponent(link[0].substr(9)); // <a href="
var name = link;
entry = entry[1].trim().split(/\s+/);
var date = new Date(entry[0] + ' ' + entry[1]).getTime();
var size = (entry[2] == '-' || entry.length < 3) ? 0 : parseInt(entry[2]);
var fpre = name.substr(0, fpre_length);
var fext = file_ext(link);
fpre_cnt[fpre] = (fpre_cnt[fpre] ? fpre_cnt[fpre] : 0) + 1;
fext_cnt[fext] = (fext_cnt[fext] ? fext_cnt[fext] : 0) + 1;
return [name, link, size, date];
}).map((data) => el('tr', {}, [
format_name(data[0], data[1]),
format_size(data[2]),
format_date(data[3], now, date_format == 'seconds'),
]));
return [e, fpre_cnt, fext_cnt];
}
function insert_accesses(accesses, loc) {
var accesses = accesses.filter((a) => !a.startsWith('/___ngxp/') && a != "");
if (accesses.length == 0) {
return false;
}
if (accesses.some((a) => loc.startsWith(a))) {
return true; // just an empty directory we have access
}
return el('pre', {},
accesses.map((a) => [el('a', {
href: a[a.length - 1] == '/' ? a : a + '/',
innerText: a,
}, [], {}), document.createTextNode("\n")]
).flat()
);
}
function files_stats_auto_sort(fpre_cnt, fext_cnt, fcount) {
var uitype = 'default';
var getcnt = (list) => list.reduce((acc, key) => acc + ((fext_cnt[key] !== undefined) ? fext_cnt[key] : 0), 0);
var fwithprefix = Math.max.apply(null, Object.values(fpre_cnt));
var vids = getcnt(['mkv', 'avi', 'webm', 'mov', 'mp4', 'ogg']);
var imgs = getcnt(['gif', 'png', 'jpeg', 'jpg', 'tiff', 'bpm']);
var audios = getcnt(['mp3', 'wav', 'ogg', 'aac']);
if ((imgs / fcount) > 0.8) {
uitype = 'photo_gallery';
} else if ([vids, audios, fwithprefix].some((c) => (c / fcount) > 0.82)) {
uitype = 'media_season';
} else if (vids == 1 && ((fcount < 6) || (getcnt(['nfo']) > 0))) {
uitype = 'tvshow_episode';
}
var has_media = (vids + imgs + audios) > 0;
return [uitype, has_media];
}
function setup_files() {
var now = new Date().getTime();
var date_format = g_this_script.attributes['date-format'].value;
var user = g_this_script.attributes['user'].value;
var accesses = Array.from(g_this_script.attributes['accesses'].value.split('|'));
g_icon_base = g_this_script.attributes['icons'].value;
console.log("user: {0}".format(user));
var body = dom('body')[0];
var pre = dom('pre');
if (pre.length == 0) { // nothing, probably unauthorized, insert or tell menu
var pre_opt = insert_accesses(accesses, document.location.pathname);
if (pre_opt === false) {
menu_need_auth();
return;
} else if (pre_opt === true) {
return;
} else {
body.appendChild(pre_opt);
pre = dom('pre');
}
}
menu_has_auth(!['wan_anon', 'local_anon', ''].includes(user));
var [entries, fpre_cnt, fext_cnt] = parse_entries(pre[0].innerHTML, now, date_format);
var fcount = entries.length;
var t = table(['Filename', 'Size', 'Date'], entries);
// remove everything except menu and auth_form
[...body.children].forEach((c) => {
if (!['menu', 'auth_form'].includes(c.id)) {
body.removeChild(c);
}
})
body.appendChild(t);
var uitype_func = {
'photo_gallery': () => sort_table(dom('#fthead'), dom('#ftbody'), 0, false), // TODO gallery mode for images (https://darekkay.com/blog/photography-website/ or https://www.files.gallery/)
'tvshow_episode': () => sort_table(dom('#fthead'), dom('#ftbody'), 1, true), // sort by size
'media_season': () => sort_table(dom('#fthead'), dom('#ftbody'), 0, false), // sort by name
'default': () => sort_table(dom('#fthead'), dom('#ftbody'), 2, true), // default sort by date
};
var [uitype, has_media] = files_stats_auto_sort(fpre_cnt, fext_cnt, fcount);
console.log("ui type: {0}".format(uitype));
uitype_func[uitype]();
if (fcount > 0) {
menu_has_files();
}
if (has_media) {
menu_has_media();
}
var wgetcode = el('div', { id: 'wget_code' }, [
el('code', { innerText: "wget -r -c -nH --no-parent --reject 'index.html*' '{0}'".format(document.location) }) // TODO wget add cookie if logged in
], { 'class': 'form hide' });
body.insertBefore(wgetcode, body.firstChild);
}
/* Media */
var media_action_called = false;
function media_actions() {
if (media_action_called) { return; }
media_action_called = true;
var tbodies = dom('#ftbody');
for (j = 0; j < tbodies.length; j++) {
var tbody = tbodies[j];
if (tbody.rows.length == 0) {
continue;
}
Array.from(tbody.rows).forEach((tr) => {
var link = tr.cells[0].dataset.sort;
var media = format_media_el(link);
if (media !== null) {
tr.cells[0].appendChild(media);
}
});
}
}
function format_media_el(link) {
var fext = file_ext(link);
var media_html = (button, media_el, onclick) => {
return el('span', {}, [
el('input', { type: 'button', value: button }, [], { 'onclick': onclick + ' ; el_hide_toggle(event.target.nextSibling);' }),
media_el,
]);
};
var err_disable = { 'onerror': 'event.target.parentNode.previousSibling.disabled = "disabled"' };
var m = {
'gif,png,jpeg,jpg,tiff,bpm': () => media_html(
"🖼️", el('img', { width: '320', }, [], { 'class': 'hide', 'data-src': link }),
'event.target.nextSibling.src = event.target.nextSibling.dataset.src',
),
'mkv,avi,webm,mov,mp4,ogg': () => media_html(
"📽️", el('video', { width: '320', height: '240', controls: 'controls', preload: 'none' }, [
el('source', { src: link, type: 'video/{0}'.format(fext.replace('mkv', 'x-matroska').replace('avi', 'divx')) }, [], err_disable)
], { 'class': 'hide' }), ''
),
'mp3,wav,ogg,aac,flac': () => media_html(
"📻", el('audio', { width: '320', controls: 'controls', preload: 'none' }, [
el('source', { src: link, }, [], err_disable)
], { 'class': 'hide' }), ''
),
};
for (var k in m) {
if (k.split(',').includes(fext)) {
return m[k]();
}
}
return null;
}
/* Menu */
function setup_page() {
var name = g_this_script.attributes['name'].value;
document.title = '{0} {1}'.format(name, document.location.pathname);
var favicon = g_this_script.attributes['favicon'].value;
var svgmagic = '<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>{0}</text></svg>'.format(favicon);
document.head.appendChild(el('link', { rel: 'shortcut icon', href: 'data:image/svg+xml,' + svgmagic, size: '24x24', type: 'image/ico' }));
document.head.appendChild(el('meta', { name: 'viewport', content: 'width=device-width, initial-scale=1' }));
}
function setup_menu() {
var status = g_this_script.attributes['status'].value;
var user = g_this_script.attributes['user'].value;
var body = dom('body')[0];
var m = el('div', { id: 'menu' }, [
el('input', { type: 'button', value: "💾", title: 'bulk download/upload' }, [], { 'class': 'hide', 'onclick': 'menu_toggle(event, "wget_code");' }),
el('input', { type: 'button', value: "🔐", title: 'login' }, [], { 'class': 'hide', 'onclick': 'menu_toggle(event, "auth_form");' }),
el('input', { type: 'button', value: "📤", title: 'upload' }, [], { 'class': 'hide', 'onclick': 'menu_toggle(event, "upload_form");' }),
el('input', { type: 'button', value: "🛋️", title: 'media mode' }, [], { 'class': 'hide', 'onclick': 'media_actions(); event.target.disabled = "disabled"' }),
el('input', { type: 'button', value: "🧪", title: 'unit test page' }, [], { 'class': 'hide' }),
el('span', { id: 'username', innerText: user }),
el('span', { id: 'status', innerText: status }),
]);
body.appendChild(m);
}
function menu_has_files() {
var menu = dom('#menu')[0];
menu.children[0].classList.remove('hide');
}
function menu_has_auth(loggedin) {
var menu = dom('#menu')[0];
if (loggedin) {
menu.children[1].onclick = auth_logout;
menu.children[1].value = '🚪';
menu.children[1].title = 'logout';
}
menu.children[1].classList.remove('hide');
}
function menu_has_upload(disable) {
var menu = dom('#menu')[0];
menu.children[2].classList.remove('hide');
menu.children[2].disabled = disable;
}
function menu_has_media() {
var menu = dom('#menu')[0];
menu.children[3].classList.remove('hide');
}
function menu_has_test(location) {
var menu = dom('#menu')[0];
menu.children[4].onclick = () => { window.location.href="{0}".format(location) };
menu.children[4].classList.remove('hide');
}
function menu_need_auth() {
var menu = dom('#menu')[0];
menu_toggle(null, "auth_form");
menu.children[1].disabled = true;
}
function el_hide_toggle(el) {
if (el.classList.contains('hide')) {
el.classList.remove('hide');
} else {
el.classList.add('hide');
}
}
function menu_toggle(_ev, id) {
el_hide_toggle(dom('#' + id)[0]);
}
/* Test */
function setup_test() {
var s = g_this_script.attributes['src'].value;
var qunit = s.substring(0, s.lastIndexOf('/') + 1) + 'qunit.html';
fetch(qunit).then((response) => {
if (response.ok) {
menu_has_test(qunit);
}
});
}
/* AUTH */
function setup_auth_html() { // called if auth is needed
var body = dom('body')[0];
var logform = el('form', { id: 'auth_form' }, [
el('input', { name: 'username', type: 'text', placeholder: 'Username' }),
el('input', { name: 'password', type: 'password', placeholder: 'Password' }),
el('input', { type: 'submit', value: 'Sign In' }),
], { 'class': 'form hide', 'onsubmit': 'auth_login(event);' });
body.appendChild(logform);
}
function auth_login(ev) {
ev.preventDefault();
var password_el = ev.target.children[1];
var user_el = ev.target.children[0];
var user = user_el.value;
var password = password_el.value;
var headers = new Headers();
headers.append('Authorization', 'Basic ' + btoa(user + ":" + password));
fetch(g_this_script.attributes['login'].value, {
method: "POST",
headers: headers,
}).then((r) => {
document.location.reload();
})
}
function auth_logout(ev) {
ev.preventDefault();
console.log('logout');
fetch(g_this_script.attributes['logout'].value, { method: "POST" }).then((r) => {
document.location.reload();
})
}
/* UPLOAD */
// TODO show a curl command for terminal users
var upload_func = null;
var upload_endpoint = null;
var upload_max_size = null;
function setup_upload() {
// Feature detection for required features
if (!(!!((typeof (File) !== 'undefined') && (typeof (Blob) !== 'undefined') && (typeof (FileList) !== 'undefined') && (Blob.prototype.webkitSlice || Blob.prototype.mozSlice || Blob.prototype.slice)))) {
console.error('Browser does not support chunked uploading');
return;
}
upload_max_size = g_this_script.attributes['upload-max-size'].value;
upload_endpoint = g_this_script.attributes['upload'].value;
if (upload_endpoint === null || upload_endpoint === undefined) {
return;
}
// check server is able to receive uploads
return fetch(upload_endpoint).then(function(response) {
if (!response.ok) {
if (response.status == 411) {
console.warn("Chunked upload not supported client side, defaulting to raw upload");
return upload_raw;
} else if (response.status == 404) {
console.info("Server doesn't support upload");
} else if (response.status == 403 || response.status == 401) {
console.warn("Upload need auth");
menu_has_auth(false);
menu_has_upload(true);
return null;
} else {
console.error(response);
}
return null;
}
return response.text().then((body) => (body.length < 20) ? upload_raw : null); // 200 <= status < 400 If it returns contents, probably server doesn't support upload
}).then((func) => {
// create ui
upload_func = func;
if (upload_func === null) {
return;
}
menu_has_upload(false);
var body = dom('body')[0];
var updiv = el('div', { id: 'upload_form' }, [
el('form', {}, [
el('input', { name: 'File', type: 'file' }, [], { "multiple": "multiple" }),
el('input', { type: 'button', value: 'Upload' }, [], { 'onclick': 'upload_form_start(event);' }),
], { 'class': 'form' }),
el('table', { border: 1, cellpadding: 1, cellspacing: 1 }, [
el('thead', { id: 'fthead' }, ['Filename', 'Progress'].map((f) => el('th', { innerText: f }))),
el('tbody', { id: 'ftbody' }),
], { 'class': 'hide' }),
], { 'class': 'hide' });
body.insertBefore(updiv, body.firstChild);
});
}
function uploade_etc_and_speed(now, transfer_size, transferred_size, last_transferred_date, last_transferred_size) {
var estimate_to_completion = -1.0;
var speed = 0.0;
var duration = now - last_transferred_date;
if (duration != 0.0) {
speed = (transferred_size - last_transferred_size) / (duration / 1000);
if (speed != 0) {
estimate_to_completion = (transfer_size - transferred_size) / speed;
}
}
return [estimate_to_completion, speed];
}
function up_progress([e, [ui_span, _]]) {
var ftotal = e.total == 0 ? 1 : e.total;
var floaded = e.loaded == 0 ? 1 : e.loaded;
var perc = Math.floor((floaded / ftotal) * 100);
var bar = ui_span.children[0];
var last_transferred_date = bar.dataset.lasttransferreddate;
if (last_transferred_date === undefined) {
last_transferred_date = e.timeStamp;
}
var last_transferred_size = bar.dataset.lasttransferredsize;
if (last_transferred_size === undefined) {
last_transferred_size = 0;
}
var duration = e.timeStamp - last_transferred_date;
var [etc, speed] = uploade_etc_and_speed(e.timeStamp, ftotal, floaded, last_transferred_date, last_transferred_size);
console.log("{0}%, transferred {1}MiB/{2}MiB, {3}MiB/S in the last {4}s should finish in {5} seconds".format(perc, (floaded / (1024 * 1024)).toFixed(1), (ftotal / (1024 * 1024)).toFixed(1), (speed / (1024 * 1024)).toFixed(2), (duration / 1000).toFixed(0), (etc).toFixed(0)));
bar.value = perc;
bar.dataset.lasttransferreddate = e.timeStamp;
bar.dataset.lasttransferredsize = floaded;
};
function up_success([xhr, [ui_span, _]]) {
console.log('Success - server responded with:', xhr.responseText);
ui_span.children[1].innerText = '\u2713';
return xhr.responseText;
};
function up_error([xhr, [ui_span, _]]) {
console.error('A server error occurred:', xhr.responseText); // Could retry at this stage depending on xhr.status
ui_span.children[1].innerText = '\u274C';
return xhr.responseText;
};
function up_meta_info(f, chunk_cnt, chunk_size, chunk_last_size, chunk_fileno) {
// /!\ /!\ /!\ A copy of conversion script should be
// kept on server to avoid RCE from users
var fixupcmd = 'find ./ -type f | while read -r h; do' // find all files in current folder
fixupcmd += ' if [ ! -f "$h" ]; then continue; fi' // put in $h file that still exists
fixupcmd += ' && read -r -n 16 head < "$h" && if [ "$head" != "#ngxpupload_meta" ]; then continue; fi';
fixupcmd += ' && IFS=\'/\' read -r name chk_cnt chk_sz chk_lsz < <(jq -Rr \'fromjson? | [(.name | sub("/";"_";"g")), (.chunk_cnt|tonumber), (.chunk_size|tonumber), (.chunk_last_size|tonumber)] | join("/")\' "$h")';
fixupcmd += ' && eval "chk_fileno=( $( jq -Rr --arg d "$1" \'fromjson? | .chunk_fileno[] | select(test("^[0-9]*$")) | "\\($d)\\(.)" | @sh\' "$h" ) )"';
fixupcmd += ' && stats=$(stat -c "%n %s" "$h" "${chk_fileno[@]}" | sort | uniq -f1 -c)';
fixupcmd += ' && stats=${stats% [0-9]*} && stats=${stats// } && stats=${stats//$\'\\n\'}';
fixupcmd += ' && expected="$(( chk_cnt - ( chk_lsz > 0 ) ))${chk_fileno[0]}${chk_sz}"';
fixupcmd += ' && if (( chk_lsz > 0 )); then; expected+="1${chk_fileno[-1]}${chk_lsz}"; fi';
fixupcmd += ' && { [ "$stats" = "${expected}1${h}" ] || { echo "$h meta invalid" >&2; break; }; }';
fixupcmd += ' && cat "${chk_fileno[@]}" > "$name" && rm -f "$h" "${chk_fileno[@]}"; done';
var meta = "#ngxpupload_meta\n" + JSON.stringify({
'name': f.name,
'size': f.size,
'type': f.type,
'chunk_cnt': chunk_cnt,
'chunk_size': chunk_size,
'chunk_last_size': chunk_last_size,
'chunk_fileno': chunk_fileno,
'uploader': g_this_script.attributes['user'].value,
}) + '\n';
meta += '# Fixup command\n# ' + fixupcmd + '\n';
return meta;
}
function upload_form_start(ev) {
if (upload_func === null) {
console.error("Handle upload func is null");
return;
}
var form = ev.target.parentNode;
var table = form.parentNode.children[1];
table.classList.remove("hide");
var file = form.children[0];
Array.from(file.files).forEach((f) => {
var up_progress_el = el('span', {}, [
el('progress', { max: 100, value: 0 }),
el('span', { innerText: '◌' }),
]);
var upentry = el('tr', {}, [
el('td', {}, [
icontag(f.type),
el('span', { innerText: f.name }),
]),
el('td', {}, [up_progress_el]),
]);
table.appendChild(upentry);
upload_ngxp_file(f, up_progress_el, upload_func, upload_endpoint, upload_max_size);
});
form.reset();
}
function upload_ngxp_file(f, ui_span, upload_func, upload_endpoint, upload_max_size) {
var chunk_cnt = 1;
var chunk_size = f.size;
var chunk_last_size = 0;
if (upload_max_size > 0 && f.size > upload_max_size) {
// upload in chunks
chunk_cnt = f.size / upload_max_size | 0;
chunk_size = upload_max_size;
chunk_last_size = f.size % upload_max_size | 0;
if (chunk_last_size > 0) {
chunk_cnt += 1;
}
console.log('Chunked upload -> Filesize: {0} ChunkCnt: {1} ChunkSz: {2} ChunkLastSz: {3} upload_max_size: {4}'.format(f.size, chunk_cnt, chunk_size, chunk_last_size, upload_max_size));
}
//start real upload
var seeker = 0;
ui_span.children[1].innerText = '◌';
var promise_chain = Promise.resolve(([null, [ui_span, []]]));
for (var i = 0; i < chunk_cnt; i++) {
let chunk_txt = '◌';
if (chunk_cnt > 1) {
chunk_txt = '{0}/{1}'.format(i + 1, chunk_cnt);
}
var chsz = chunk_size;
if ((seeker + chsz) > f.size) {
chsz = chunk_last_size;
}
let chunk = f.slice(seeker, seeker + chsz);
seeker += chsz;
promise_chain = promise_chain.then(([xhr, [ui_span, chunk_fileno]]) => {
if (xhr !== null) {
chunk_fileno.push(xhr.responseText);
}
ui_span.children[1].innerText = chunk_txt;
return upload_func(
upload_endpoint, chunk, up_progress, [ui_span, chunk_fileno]
);
});
}
// finally upload meta file
return promise_chain.then(([xhr, [ui_span, chunk_fileno]]) => {
if (xhr !== null) {
chunk_fileno.push(xhr.responseText);
}
ui_span.children[1].innerText = '⏺';
var meta = up_meta_info(f, chunk_cnt, chunk_size, chunk_last_size, chunk_fileno);
return upload_func(
upload_endpoint, meta, up_progress, [ui_span, chunk_fileno]
);
}).then(up_success, up_error);
}
function upload_raw(url, file, progress, cb_data) {
return new Promise((resolve, reject) => {
aborting = false;
xhr = new XMLHttpRequest(); // use xhr, fetch doesn't have a progress event
xhr.open('POST', url, true);
var headers = {
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'attachment; filename="{0}"'.format(encodeURIComponent(file.name)),
'X-Content-Range': 'bytes 0-{0}/{1}'.format(file.size - 1, file.size),
};
xhr = Object.entries(headers).reduce((xhr, [k, v]) => { xhr.setRequestHeader(k, v); return xhr; }, xhr);
xhr.upload.addEventListener('progress', (e) => {
if (aborting) { return; }
progress([e, cb_data]);
});
xhr.addEventListener('load', (ev) => {
var xhr = ev.target;
if (aborting) { return; }
if (xhr.readyState >= 4) {
if (xhr.status >= 200 && xhr.status <= 299) {
progress([ev, cb_data]);
resolve([xhr, cb_data]);
} else {
try {
xhr.abort();
} catch (err) { }
reject([xhr, cb_data]);
}
}
});
xhr.addEventListener('error', (ev) => {
var xhr = ev.target;
if (aborting) { return; }
try {
xhr.abort();
} catch (err) { }
reject([xhr, cb_data])
});
xhr.send(file);
});
}