taglib-wasm
Version:
TagLib-Wasm is the universal tagging library for TypeScript/JavaScript platforms: Browsers, Node.js, Deno, Bun, Cloudflare Workers, and Electron apps
90 lines (89 loc) • 2.51 kB
JavaScript
import { MetadataError } from "../errors/classes.js";
import {
applyCoverArt,
applyPictures,
readCoverArt,
readPictures
} from "../simple/index.js";
import { readFileData } from "../utils/file.js";
import { writeFileData } from "../utils/write.js";
async function copyCoverArt(sourcePath, targetPath, options = {}) {
if (options.copyAll) {
const pictures = await readPictures(sourcePath);
if (pictures.length === 0) {
throw new MetadataError("read", `No pictures found. Path: ${sourcePath}`);
}
const modifiedBuffer = await applyPictures(targetPath, pictures);
await writeFileData(targetPath, modifiedBuffer);
} else {
const coverData = await readCoverArt(sourcePath);
if (!coverData) {
throw new MetadataError(
"read",
`No cover art found. Path: ${sourcePath}`
);
}
const pictures = await readPictures(sourcePath);
const coverPicture = pictures.find(
(p) => p.type === "FrontCover"
) ?? pictures[0];
const modifiedBuffer = await applyCoverArt(
targetPath,
coverData,
coverPicture.mimeType
);
await writeFileData(targetPath, modifiedBuffer);
}
}
async function fileExists(path) {
try {
const data = await readFileData(path);
return data.length > 0;
} catch {
return false;
}
}
async function findCoverFile(dir, names, extensions) {
for (const name of names) {
for (const ext of extensions) {
const path = `${dir}${name}.${ext}`;
if (await fileExists(path)) {
return path;
}
}
}
return void 0;
}
async function findCoverArtFiles(audioPath) {
const dir = audioPath.substring(0, audioPath.lastIndexOf("/") + 1);
const extensions = ["jpg", "jpeg", "png", "gif", "webp"];
const found = {};
const frontPath = await findCoverFile(
dir,
["cover", "front", "Cover", "Front"],
extensions
);
if (frontPath) found.front = frontPath;
const folderPath = await findCoverFile(
dir,
["folder", "Folder"],
extensions
);
if (folderPath) found.folder = folderPath;
const otherNames = ["album", "artwork", "Album", "Artwork"];
for (const name of otherNames) {
const path = await findCoverFile(dir, [name], extensions);
if (path) found[name.toLowerCase()] = path;
}
const backPath = await findCoverFile(
dir,
["back", "Back", "back-cover", "Back-Cover"],
extensions
);
if (backPath) found.back = backPath;
return found;
}
export {
copyCoverArt,
findCoverArtFiles
};