feat: add zip downloading

This commit is contained in:
PiratePeep 2025-03-23 16:45:11 -06:00
parent cdae798fcf
commit ab275b5de7
5 changed files with 124 additions and 12 deletions

View file

@ -53,7 +53,8 @@ RUN apk --no-cache add \
poppler-utils \
gcompat \
libva-utils \
py3-numpy
py3-numpy \
zip
RUN apk --no-cache add calibre --repository=http://dl-cdn.alpinelinux.org/alpine/edge/testing/

View file

@ -13,6 +13,33 @@ window.downloadAll = function () {
}, index * 100);
});
};
window.downloadZip = function () {
const jobId = window.location.pathname.split("/").pop();
const userId = document.querySelector("meta[name='user-id']").content;
fetch(`${webroot}/zip/${userId}/${jobId}`, {
method: "GET",
})
.then((res) => {
if (res.ok) {
return res.blob();
}
return Promise.reject(new Error("Failed to download zip"));
})
.then((blob) => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `convertx-${userId}-${jobId}.zip`;
document.body.appendChild(a);
a.click();
a.remove();
})
.catch((err) => console.log(err));
};
const jobId = window.location.pathname.split("/").pop();
const main = document.querySelector("main");
let progressElem = document.querySelector("progress");

View file

@ -4,16 +4,19 @@ export const BaseHtml = ({
children,
title = "ConvertX",
webroot = "",
userId = "",
}: {
children: JSX.Element;
title?: string;
webroot?: string;
userId?: string;
}) => (
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="webroot" content={webroot} />
<meta name="user-id" content={userId} />
<title safe>{title}</title>
<link rel="stylesheet" href={`${webroot}/generated.css`} />
<link

63
src/helpers/zip.ts Normal file
View file

@ -0,0 +1,63 @@
import { execFile } from "node:child_process";
import * as fs from "node:fs";
import * as path from "path";
import { getAllTargets } from "../converters/main";
export const zip = (inputPath: string, outputPath: string) => {
return new Promise((resolve, reject) => {
const absoluteInputPath = path.resolve(inputPath);
const absoluteOutputPath = path.resolve(outputPath);
const allTargets = getAllTargets();
const supportedExtensions = new Set<string>();
Object.values(allTargets).forEach((extensions) => {
extensions.forEach((ext) => supportedExtensions.add(ext));
});
fs.readdir(absoluteInputPath, { withFileTypes: true }, (err, entries) => {
if (err) {
return reject(err);
}
const files = entries
.filter((entry) => entry.isFile())
.filter((entry) => entry.name !== path.basename(outputPath))
.map((entry) => entry.name)
.filter((filename) => {
// We don't want to zip files with unsafe characters
if (!/^[a-zA-Z0-9._-]+\.[a-zA-Z0-9]+$/.test(filename)) {
return false;
}
const extension = path.extname(filename).substring(1).toLowerCase();
return supportedExtensions.has(extension);
});
if (files.length === 0) {
return reject(new Error("No files to zip"));
}
execFile(
"zip",
["-j", absoluteOutputPath, ...files],
{ cwd: absoluteInputPath },
(error, stdout, stderr) => {
if (error) {
reject(error);
}
if (stdout) {
console.log(`stdout: ${stdout}`);
}
if (stderr) {
console.error(`stderr: ${stderr}`);
}
resolve("Done");
},
);
});
});
};

View file

@ -20,6 +20,7 @@ import {
normalizeOutputFiletype,
} from "./helpers/normalizeFiletype";
import "./helpers/printVersions";
import { zip } from "./helpers/zip";
mkdir("./data", { recursive: true }).catch(console.error);
const db = new Database("./data/mydb.sqlite", { create: true });
@ -563,7 +564,7 @@ const app = new Elysia({
console.log("jobId set to:", id);
return (
<BaseHtml webroot={WEBROOT}>
<BaseHtml webroot={WEBROOT} userId={user.id}>
<>
<Header
webroot={WEBROOT}
@ -981,7 +982,7 @@ const app = new Elysia({
userJobs = userJobs.filter((job) => job.num_files > 0);
return (
<BaseHtml webroot={WEBROOT} title="ConvertX | Results">
<BaseHtml webroot={WEBROOT} title="ConvertX | Results" userId={user.id}>
<>
<Header
webroot={WEBROOT}
@ -1116,7 +1117,7 @@ const app = new Elysia({
.all(params.jobId);
return (
<BaseHtml webroot={WEBROOT} title="ConvertX | Result">
<BaseHtml webroot={WEBROOT} title="ConvertX | Result" userId={user.id}>
<>
<Header
webroot={WEBROOT}
@ -1132,7 +1133,7 @@ const app = new Elysia({
<article class="article">
<div class="mb-4 flex items-center justify-between">
<h1 class="text-xl">Results</h1>
<div>
<div class="flex items-center gap-2">
<button
type="button"
class="btn-primary float-right w-40"
@ -1145,6 +1146,16 @@ const app = new Elysia({
? "Download All"
: "Converting..."}
</button>
<button
type="button"
class="btn-primary float-right w-40"
onclick="downloadZip()"
{...(files.length !== job.num_files
? { disabled: true, "aria-busy": "true" }
: "")}
>
Download Zip
</button>
</div>
</div>
<progress
@ -1431,7 +1442,7 @@ const app = new Elysia({
}
return (
<BaseHtml webroot={WEBROOT} title="ConvertX | Converters">
<BaseHtml webroot={WEBROOT} title="ConvertX | Converters" userId={user.id}>
<>
<Header
webroot={WEBROOT}
@ -1499,7 +1510,6 @@ const app = new Elysia({
.get(
"/zip/:userId/:jobId",
async ({ params, jwt, redirect, cookie: { auth } }) => {
// TODO: Implement zip download
if (!auth?.value) {
return redirect(`${WEBROOT}/login`, 302);
}
@ -1517,16 +1527,24 @@ const app = new Elysia({
return redirect(`${WEBROOT}/results`, 302);
}
// const userId = decodeURIComponent(params.userId);
// const jobId = decodeURIComponent(params.jobId);
// const outputPath = `${outputDir}${userId}/`{jobId}/);
const userId = decodeURIComponent(params.userId);
const jobId = decodeURIComponent(params.jobId);
const outputPath = `${outputDir}${userId}/${jobId}/`;
const zipPath = `${outputPath}/convertx-${userId}-${jobId}.zip`;
// return Bun.zip(outputPath);
await zip(outputPath, zipPath);
return Bun.file(zipPath);
},
)
.onError(({ error }) => {
.onError(({ error, set }) => {
// log.error(` ${request.method} ${request.url}`, code, error);
console.error(error);
set.status = 500;
return {
message: "Internal Server Error",
};
});
if (process.env.NODE_ENV !== "production") {