1import type { App } from "./elm/types"
2import { fileExtension } from "../common"
3import { transformUrl } from "../urls"
4
5
6// 🏔️
7
8
9let app: App
10
11
12
13// 🚀
14
15
16export function init(a: App) {
17 app = a
18}
19
20
21
22// 🛠️
23
24
25export async function download(group) {
26 const { saveAs } = await import("file-saver").then(a => a.default)
27 const JSZip = await import("jszip").then(a => a.default)
28
29 const zip = new JSZip()
30 const folder = zip.folder("Diffuse - " + group.name)
31 if (!folder) throw new Error("Failed to create ZIP file")
32
33 return group.tracks
34 .reduce((acc, track) => {
35 return acc
36 .then(() => transformUrl(track.url, app))
37 .then(fetch)
38 .then((r: Response) => {
39 const mimeType = r.headers.get("content-type")
40 const fileExt = (mimeType ? fileExtension(mimeType) : null) || track.path.match(/\.(\w+)$/)[1] || "unknown-ext"
41
42 return r.blob().then((b: Blob) => folder.file(track.filename + "." + fileExt, b))
43 })
44 }, Promise.resolve())
45 .then(() => zip.generateAsync({ type: "blob" }))
46 .then((zipFile: Blob) => {
47 saveAs(zipFile, "Diffuse - " + group.name + ".zip")
48 app.ports.downloadTracksFinished.send(null)
49 })
50}