/** * @typedef {object} PathItem * @property {"Dir"|"SymlinkDir"|"File"|"SymlinkFile"} path_type * @property {string} name * @property {number} mtime * @property {number} size */ // https://stackoverflow.com/a/901144/3642588 const params = new Proxy(new URLSearchParams(window.location.search), { get: (searchParams, prop) => searchParams.get(prop), }); const dirEmptyNote = params.q ? 'No results' : DATA.dir_exists ? 'Empty folder' : 'Folder will be created when a file is uploaded'; /** * @type Element */ let $pathsTable; /** * @type Element */ let $pathsTableBody; /** * @type Element */ let $uploadersTable; /** * @type Element */ let $emptyFolder; class Uploader { /** * @type number */ idx; /** * @type File */ file; /** * @type string */ name; /** * @type Element */ $uploadStatus; /** * @type number */ uploaded = 0; /** * @type number */ lastUptime = 0; static globalIdx = 0; constructor(file, dirs) { this.name = [...dirs, file.name].join("/"); this.idx = Uploader.globalIdx++; this.file = file; } upload() { const { file, idx, name } = this; let url = getUrl(name); $uploadersTable.insertAdjacentHTML("beforeend", ` ${getSvg(file.path_type)} ${name} `); $uploadersTable.classList.remove("hidden"); $emptyFolder.classList.add("hidden"); this.$uploadStatus = document.getElementById(`uploadStatus${idx}`); this.lastUptime = Date.now(); const ajax = new XMLHttpRequest(); ajax.upload.addEventListener("progress", e => this.progress(e), false); ajax.addEventListener("readystatechange", () => { if(ajax.readyState === 4) { if (ajax.status >= 200 && ajax.status < 300) { this.complete(); } else { this.fail(); } } }) ajax.addEventListener("error", () => this.fail(), false); ajax.addEventListener("abort", () => this.fail(), false); ajax.open("PUT", url); ajax.send(file); } progress(event) { let now = Date.now(); let speed = (event.loaded - this.uploaded) / (now - this.lastUptime) * 1000; let [speedValue, speedUnit] = formatSize(speed); const speedText = `${speedValue}${speedUnit.toLowerCase()}/s`; const progress = formatPercent((event.loaded / event.total) * 100); const duration = formatDuration((event.total - event.loaded) / speed) this.$uploadStatus.innerHTML = `${speedText}${progress}${duration}`; this.uploaded = event.loaded; this.lastUptime = now; } complete() { this.$uploadStatus.innerHTML = `✓`; } fail() { this.$uploadStatus.innerHTML = `✗`; } } /** * Add breadcrumb * @param {string} href * @param {string} uri_prefix */ function addBreadcrumb(href, uri_prefix) { const $breadcrumb = document.querySelector(".breadcrumb"); let parts = []; if (href === "/") { parts = [""]; } else { parts = href.split("/"); } const len = parts.length; let path = uri_prefix; for (let i = 0; i < len; i++) { const name = parts[i]; if (i > 0) { if (!path.endsWith("/")) { path += "/"; } path += encodeURI(name); } if (i === 0) { $breadcrumb.insertAdjacentHTML("beforeend", ``); } else if (i === len - 1) { $breadcrumb.insertAdjacentHTML("beforeend", `${name}`); } else { $breadcrumb.insertAdjacentHTML("beforeend", `${name}`); } if (i !== len - 1) { $breadcrumb.insertAdjacentHTML("beforeend", `/`); } } } /** * Add pathitem * @param {PathItem} file * @param {number} index */ function addPath(file, index) { let url = getUrl(file.name) let actionDelete = ""; let actionDownload = ""; if (file.path_type.endsWith("Dir")) { url += "/"; actionDownload = `
`; } else { actionDownload = `
`; } if (DATA.allow_delete) { actionDelete = `
`; } let actionCell = ` ${actionDownload} ${actionDelete} ` $pathsTableBody.insertAdjacentHTML("beforeend", ` ${getSvg(file.path_type)} ${file.name} ${formatMtime(file.mtime)} ${formatSize(file.size).join(" ")} ${actionCell} `) } /** * Delete pathitem * @param {number} index * @returns */ async function deletePath(index) { const file = DATA.paths[index]; if (!file) return; if (!confirm(`Delete \`${file.name}\`?`)) return; try { const res = await fetch(getUrl(file.name), { method: "DELETE", }); if (res.status >= 200 && res.status < 300) { document.getElementById(`addPath${index}`).remove(); DATA.paths[index] = null; if (!DATA.paths.find(v => !!v)) { $pathsTable.classList.add("hidden"); $emptyFolder.textContent = dirEmptyNote; $emptyFolder.classList.remove("hidden"); } } else { throw new Error(await res.text()) } } catch (err) { alert(`Cannot delete \`${file.name}\`, ${err.message}`); } } function dropzone() { ["drag", "dragstart", "dragend", "dragover", "dragenter", "dragleave", "drop"].forEach(name => { document.addEventListener(name, e => { e.preventDefault(); e.stopPropagation(); }); }); document.addEventListener("drop", e => { if (!e.dataTransfer.items[0].webkitGetAsEntry) { const files = e.dataTransfer.files.filter(v => v.size > 0); for (const file of files) { new Uploader(file, []).upload(); } } else { const entries = []; const len = e.dataTransfer.items.length; for (let i = 0; i < len; i++) { entries.push(e.dataTransfer.items[i].webkitGetAsEntry()); } addFileEntries(entries, []) } }); } async function addFileEntries(entries, dirs) { for (const entry of entries) { if (entry.isFile) { entry.file(file => { new Uploader(file, dirs).upload(); }); } else if (entry.isDirectory) { const dirReader = entry.createReader() dirReader.readEntries(entries => addFileEntries(entries, [...dirs, entry.name])); } } } function getUrl(name) { let url = location.href.split('?')[0]; if (!url.endsWith("/")) url += "/"; url += encodeURI(name); return url; } function getSvg(path_type) { switch (path_type) { case "Dir": return ``; case "File": return ``; case "SymlinkDir": return ``; default: return ``; } } function formatMtime(mtime) { if (!mtime) return "" const date = new Date(mtime); const year = date.getFullYear(); const month = padZero(date.getMonth() + 1, 2); const day = padZero(date.getDate(), 2); const hours = padZero(date.getHours(), 2); const minutes = padZero(date.getMinutes(), 2); return `${year}-${month}-${day} ${hours}:${minutes}`; } function padZero(value, size) { return ("0".repeat(size) + value).slice(-1 * size) } function formatSize(size) { if (!size) return [] const sizes = ['B', 'KB', 'MB', 'GB', 'TB']; if (size == 0) return [0, "Byte"]; const i = parseInt(Math.floor(Math.log(size) / Math.log(1024))); return [Math.round(size / Math.pow(1024, i), 2), sizes[i]]; } function formatDuration(seconds) { seconds = Math.ceil(seconds); let h = Math.floor(seconds / 3600); let m = Math.floor((seconds - h * 3600) / 60); let s = seconds - h * 3600 - m * 60 return `${padZero(h, 2)}:${padZero(m, 2)}:${padZero(s, 2)}`; } function formatPercent(precent) { if (precent > 10) { return precent.toFixed(1) + "%"; } else { return precent.toFixed(2) + "%"; } } function ready() { $pathsTable = document.querySelector(".paths-table") $pathsTableBody = document.querySelector(".paths-table tbody"); $uploadersTable = document.querySelector(".uploaders-table"); $emptyFolder = document.querySelector(".empty-folder"); if (DATA.allow_search) { document.querySelector(".searchbar").classList.remove("hidden"); if (params.q) { document.getElementById('search').value = params.q; } } addBreadcrumb(DATA.href, DATA.uri_prefix); if (Array.isArray(DATA.paths)) { const len = DATA.paths.length; if (len > 0) { $pathsTable.classList.remove("hidden"); } for (let i = 0; i < len; i++) { addPath(DATA.paths[i], i); } if (len == 0) { $emptyFolder.textContent = dirEmptyNote; $emptyFolder.classList.remove("hidden"); } } if (DATA.allow_upload) { dropzone(); document.querySelector(".upload-control").classList.remove("hidden"); document.getElementById("file").addEventListener("change", e => { const files = e.target.files; for (let file of files) { new Uploader(file, []).upload(); } }); } }