-
Notifications
You must be signed in to change notification settings - Fork 0
/
updateCover.ts
99 lines (83 loc) · 2.45 KB
/
updateCover.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import chalk from "npm:chalk";
function arrayBufferToBase64(buffer: ArrayBuffer): string {
const uint8Array = new Uint8Array(buffer);
let binary = "";
uint8Array.forEach((byte) => {
binary += String.fromCharCode(byte);
});
return btoa(binary);
}
async function getCoverUrl(token: string, albumId: string): Promise<null> {
const headers = new Headers({
"Authorization": `Bearer ${token}`,
"Accept": "application/json",
"Content-Type": "application/json",
});
try {
const res = await fetch(`https://api.spotify.com/v1/albums/${albumId}`, {
method: "GET",
headers,
});
if (!res.ok) {
console.error(`Error: ${res.status} - ${res.statusText}`);
return null;
}
const data = await res.json();
return data.images[1].url;
} catch (error) {
console.error("Error while getting album cover", error);
throw error;
}
}
async function downloadCover(url: string): Promise<string> {
try {
// Fetch the image from the URL
console.log(chalk.cyan("Downloading cover..."));
const res = await fetch(url);
if (!res.ok) {
throw new Error(`Failed to fetch cover: ${res.statusText}`);
}
// Convert the response body into an ArrayBuffer
const arrayBuffer = await res.arrayBuffer();
// Convert the ArrayBuffer to a Base64 string
const base64String = arrayBufferToBase64(arrayBuffer);
return base64String;
} catch (error) {
console.error("Error while downloading cover:", error);
throw error;
}
}
export default async function updateCover(
id: string,
token: string,
albumId: string
): Promise<null> {
const imgUrl = await getCoverUrl(token, albumId);
if (!imgUrl) return null;
const img = await downloadCover(imgUrl);
if (!imgUrl) return null;
const headers = new Headers({
"Authorization": `Bearer ${token}`,
"Accept": "application/json",
"Content-Type": "application/json",
});
try {
const res = await fetch(
`https://api.spotify.com/v1/playlists/${id}/images`,
{
method: "PUT",
headers,
body: img,
}
);
if (!res.ok) {
console.error(`Error: ${res.status} - ${res.statusText}`);
return null;
}
console.log(chalk.green("Updated cover"));
return null;
} catch (error) {
console.error("Error while updating album cover", error);
throw error;
}
}