web/src/utils/utils.ts

80 lines
2.4 KiB
TypeScript
Raw Normal View History

2021-05-24 14:19:37 +00:00
import {DecryptResult} from "@/decrypt/entity";
2021-05-24 19:06:28 +00:00
import {FileSystemDirectoryHandle} from "@/shims-fs";
2021-05-24 14:19:37 +00:00
2021-05-24 15:48:52 +00:00
export enum FilenamePolicy {
ArtistAndTitle,
TitleOnly,
TitleAndArtist,
SameAsOriginal,
}
export const FilenamePolicies: { key: FilenamePolicy, text: string }[] = [
{key: FilenamePolicy.ArtistAndTitle, text: "歌手-歌曲名"},
{key: FilenamePolicy.TitleOnly, text: "歌曲名"},
{key: FilenamePolicy.TitleAndArtist, text: "歌曲名-歌手"},
{key: FilenamePolicy.SameAsOriginal, text: "同源文件名"},
]
2021-05-24 19:06:28 +00:00
export function GetDownloadFilename(data: DecryptResult, policy: FilenamePolicy): string {
2021-05-24 15:48:52 +00:00
switch (policy) {
case FilenamePolicy.TitleOnly:
2021-05-24 19:06:28 +00:00
return `${data.title}.${data.ext}`;
2021-05-24 15:48:52 +00:00
case FilenamePolicy.TitleAndArtist:
2021-05-24 19:06:28 +00:00
return `${data.title} - ${data.artist}.${data.ext}`;
2021-05-24 15:48:52 +00:00
case FilenamePolicy.SameAsOriginal:
2021-05-24 19:06:28 +00:00
return `${data.rawFilename}.${data.ext}`;
default:
case FilenamePolicy.ArtistAndTitle:
return `${data.artist} - ${data.title}.${data.ext}`;
2020-02-06 08:01:35 +00:00
}
2021-05-24 19:06:28 +00:00
}
export async function DirectlyWriteFile(data: DecryptResult, policy: FilenamePolicy, dir: FileSystemDirectoryHandle) {
let filename = GetDownloadFilename(data, policy)
// prevent filename exist
try {
await dir.getFileHandle(filename)
filename = `${new Date().getTime()} - ${filename}`
} catch (e) {
}
const file = await dir.getFileHandle(filename, {create: true})
const w = await file.createWritable()
await w.write(data.blob)
await w.close()
}
export function DownloadBlobMusic(data: DecryptResult, policy: FilenamePolicy) {
const a = document.createElement('a');
a.href = data.file;
a.download = GetDownloadFilename(data, policy)
2020-02-06 08:01:35 +00:00
document.body.append(a);
a.click();
a.remove();
}
2021-05-24 14:19:37 +00:00
export function RemoveBlobMusic(data: DecryptResult) {
2020-02-06 08:01:35 +00:00
URL.revokeObjectURL(data.file);
2021-05-24 14:19:37 +00:00
if (data.picture?.startsWith("blob:")) {
URL.revokeObjectURL(data.picture);
}
2021-05-24 14:19:37 +00:00
}
export class DecryptQueue {
private readonly pending: (() => Promise<void>)[];
constructor() {
this.pending = []
}
queue(fn: () => Promise<void>) {
this.pending.push(fn)
this.consume()
}
2021-05-24 14:19:37 +00:00
private consume() {
const fn = this.pending.shift()
if (fn) fn().then(() => this.consume).catch(console.error)
}
2020-02-06 08:01:35 +00:00
}