init: backend
This commit is contained in:
77
src/download_cover.ts
Normal file
77
src/download_cover.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import axios from "axios";
|
||||
import fs from "node:fs";
|
||||
|
||||
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",
|
||||
},
|
||||
);
|
||||
|
||||
fs.writeFileSync(`public/covers/mb/${mbid}.png`, 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(
|
||||
artist: string,
|
||||
album: string,
|
||||
) {
|
||||
console.log("[DEBUG]: download_image_from_itunes:", artist, album);
|
||||
try {
|
||||
const itunes_url = await itunes_cover_url(artist, album);
|
||||
|
||||
if (!itunes_url) {
|
||||
throw new Error(`iTunes URL not found for ${artist} - ${album}`);
|
||||
}
|
||||
|
||||
const artist_dir = `public/covers/itunes/${artist}`;
|
||||
if (!fs.existsSync(artist_dir)) {
|
||||
fs.mkdirSync(artist_dir, { recursive: true });
|
||||
}
|
||||
|
||||
const img_response = await axios.get(itunes_url, {
|
||||
responseType: "arraybuffer",
|
||||
});
|
||||
|
||||
fs.writeFileSync(`${artist_dir}/${album}.png`, img_response.data);
|
||||
} catch (error) {
|
||||
console.error("Error fetching data:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user