94 lines
2.3 KiB
TypeScript
94 lines
2.3 KiB
TypeScript
import axios from "axios";
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
|
|
export async function download_image_from_caa(mbid: string) {
|
|
console.log("[DEBUG]: download_image_from_caa:", mbid);
|
|
try {
|
|
const response = await axios.get(
|
|
`http://coverartarchive.org/release/${mbid}`,
|
|
);
|
|
const img_response = await axios.get(
|
|
response.data.images[0].thumbnails["250"],
|
|
{
|
|
responseType: "arraybuffer",
|
|
},
|
|
);
|
|
|
|
const mb_dist = path.join(
|
|
process.cwd(),
|
|
"public",
|
|
"covers",
|
|
"mb",
|
|
`${mbid}.png`,
|
|
);
|
|
fs.writeFileSync(mb_dist, img_response.data);
|
|
} catch (error) {
|
|
console.error("Error fetching data:", error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function itunes_cover_url(artist: string, album: string) {
|
|
artist = (
|
|
artist.toLowerCase().split(/\s+feat\.?|\s+w\s*|\s+&\s+/)[0] || artist
|
|
).trim();
|
|
|
|
let query = `${artist} ${album}`
|
|
.replace(/\([^)]*\)/g, "")
|
|
.replace(/\[[^\]]*\]/g, "")
|
|
.replace(/[-_,"':;|]/g, " ")
|
|
.toLowerCase();
|
|
|
|
const apple_music_results = await fetch("https://itunes.apple.com/search", {
|
|
body: new URLSearchParams({
|
|
term: query,
|
|
entity: "song",
|
|
limit: "10",
|
|
}),
|
|
method: "POST",
|
|
}).then((res) => res.json());
|
|
|
|
for (let result of apple_music_results.results) {
|
|
if (artist == result.artistName.toLowerCase()) {
|
|
return result.artworkUrl100.replace("100x100bb.jpg", "200x200bb.png");
|
|
}
|
|
}
|
|
}
|
|
|
|
export async function download_image_from_itunes(
|
|
rawArtist: string,
|
|
rawAlbum: string,
|
|
safeArtist: string,
|
|
safeAlbum: string,
|
|
) {
|
|
console.log("[DEBUG]: download_image_from_itunes:", rawArtist, rawAlbum);
|
|
try {
|
|
const itunes_url = await itunes_cover_url(rawArtist, rawAlbum);
|
|
|
|
if (!itunes_url) {
|
|
throw new Error(`iTunes URL not found for ${rawArtist} - ${rawAlbum}`);
|
|
}
|
|
|
|
const artist_dist = path.join(
|
|
process.cwd(),
|
|
"public",
|
|
"covers",
|
|
"itunes",
|
|
safeArtist,
|
|
);
|
|
if (!fs.existsSync(artist_dist)) {
|
|
fs.mkdirSync(artist_dist, { recursive: true });
|
|
}
|
|
|
|
const img_response = await axios.get(itunes_url, {
|
|
responseType: "arraybuffer",
|
|
});
|
|
|
|
fs.writeFileSync(`${artist_dist}/${safeAlbum}.png`, img_response.data);
|
|
} catch (error) {
|
|
console.error("Error fetching data:", error);
|
|
throw error;
|
|
}
|
|
}
|