|
1 | | -import { normalizeFiletype } from "../helpers/normalizeFiletype"; |
| 1 | +import db from "../db/db"; |
| 2 | +import { MAX_CONVERT_PROCESS } from "../helpers/env"; |
| 3 | +import { normalizeFiletype, normalizeOutputFiletype } from "../helpers/normalizeFiletype"; |
2 | 4 | import { convert as convertassimp, properties as propertiesassimp } from "./assimp"; |
3 | 5 | import { convert as convertCalibre, properties as propertiesCalibre } from "./calibre"; |
4 | 6 | import { convert as convertDvisvgm, properties as propertiesDvisvgm } from "./dvisvgm"; |
@@ -111,6 +113,63 @@ const properties: Record< |
111 | 113 | }, |
112 | 114 | }; |
113 | 115 |
|
| 116 | +function chunks<T>(arr: T[], size: number): T[][] { |
| 117 | + if(size <= 0){ |
| 118 | + return [arr] |
| 119 | + } |
| 120 | + return Array.from({ length: Math.ceil(arr.length / size) }, (_: T, i: number) => |
| 121 | + arr.slice(i * size, i * size + size) |
| 122 | + ); |
| 123 | +} |
| 124 | + |
| 125 | +export async function handleConvert( |
| 126 | + fileNames: string[], |
| 127 | + userUploadsDir: string, |
| 128 | + userOutputDir: string, |
| 129 | + convertTo: string, |
| 130 | + converterName: string, |
| 131 | + jobId: any |
| 132 | +) { |
| 133 | + |
| 134 | + const query = db.query( |
| 135 | + "INSERT INTO file_names (job_id, file_name, output_file_name, status) VALUES (?1, ?2, ?3, ?4)", |
| 136 | + ); |
| 137 | + |
| 138 | + |
| 139 | + for (const chunk of chunks(fileNames, MAX_CONVERT_PROCESS)) { |
| 140 | + const toProcess: Promise<string>[] = []; |
| 141 | + for(const fileName of chunk) { |
| 142 | + const filePath = `${userUploadsDir}${fileName}`; |
| 143 | + const fileTypeOrig = fileName.split(".").pop() ?? ""; |
| 144 | + const fileType = normalizeFiletype(fileTypeOrig); |
| 145 | + const newFileExt = normalizeOutputFiletype(convertTo); |
| 146 | + const newFileName = fileName.replace( |
| 147 | + new RegExp(`${fileTypeOrig}(?!.*${fileTypeOrig})`), |
| 148 | + newFileExt, |
| 149 | + ); |
| 150 | + const targetPath = `${userOutputDir}${newFileName}`; |
| 151 | + toProcess.push( |
| 152 | + new Promise((resolve, reject) => { |
| 153 | + mainConverter( |
| 154 | + filePath, |
| 155 | + fileType, |
| 156 | + convertTo, |
| 157 | + targetPath, |
| 158 | + {}, |
| 159 | + converterName, |
| 160 | + ).then(r => { |
| 161 | + if (jobId.value) { |
| 162 | + query.run(jobId.value, fileName, newFileName, r); |
| 163 | + } |
| 164 | + resolve(r); |
| 165 | + }).catch(c => reject(c)); |
| 166 | + }) |
| 167 | + ); |
| 168 | + } |
| 169 | + await Promise.all(toProcess); |
| 170 | + } |
| 171 | +} |
| 172 | + |
114 | 173 | export async function mainConverter( |
115 | 174 | inputFilePath: string, |
116 | 175 | fileTypeOriginal: string, |
|
0 commit comments