78 lines
2.3 KiB
JavaScript
78 lines
2.3 KiB
JavaScript
import { api, describeError } from "./api.js";
|
|
|
|
const fields = {
|
|
form: document.getElementById("download-form"),
|
|
urls: document.getElementById("download-urls"),
|
|
name: document.getElementById("download-name"),
|
|
autoExtract: document.getElementById("auto-extract"),
|
|
destination: document.getElementById("download-destination"),
|
|
subfolder: document.getElementById("download-subfolder"),
|
|
error: document.getElementById("download-error"),
|
|
};
|
|
|
|
export function setupDownloadForm(onCreated) {
|
|
fields.form.addEventListener("submit", (event) => submitDownloads(event, onCreated));
|
|
fields.urls.addEventListener("keydown", (event) => {
|
|
if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) {
|
|
event.preventDefault();
|
|
fields.form.requestSubmit();
|
|
}
|
|
});
|
|
fields.destination.addEventListener("change", updateSubfolderState);
|
|
}
|
|
|
|
export function setAutoExtractDefault(enabled) {
|
|
fields.autoExtract.checked = enabled;
|
|
}
|
|
|
|
export function destinationSelect() {
|
|
return fields.destination;
|
|
}
|
|
|
|
export function updateSubfolderState() {
|
|
fields.subfolder.disabled = fields.destination.value === "";
|
|
}
|
|
|
|
async function submitDownloads(event, onCreated) {
|
|
event.preventDefault();
|
|
fields.error.textContent = "";
|
|
|
|
const urls = fields.urls.value.split("\n").map((line) => line.trim()).filter(Boolean);
|
|
const fileName = fields.name.value.trim();
|
|
if (urls.length === 0) {
|
|
fields.error.textContent = "Paste at least one link.";
|
|
return;
|
|
}
|
|
if (fileName && urls.length > 1) {
|
|
fields.error.textContent = "A file name can only be set when downloading a single link.";
|
|
return;
|
|
}
|
|
|
|
const failedUrls = [];
|
|
let firstError = "";
|
|
for (const url of urls) {
|
|
try {
|
|
await api.createJob({
|
|
url,
|
|
fileName,
|
|
autoExtract: fields.autoExtract.checked,
|
|
destination: fields.destination.value,
|
|
subfolder: fields.subfolder.value.trim(),
|
|
});
|
|
} catch (error) {
|
|
failedUrls.push(url);
|
|
if (!firstError) firstError = describeError(error);
|
|
}
|
|
}
|
|
|
|
fields.urls.value = failedUrls.join("\n");
|
|
if (failedUrls.length === 0) {
|
|
fields.name.value = "";
|
|
fields.subfolder.value = "";
|
|
} else {
|
|
const prefix = urls.length > 1 ? `${failedUrls.length} of ${urls.length} links failed: ` : "";
|
|
fields.error.textContent = prefix + firstError;
|
|
}
|
|
await onCreated();
|
|
}
|