This repository has been archived by the owner on Feb 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.js
57 lines (49 loc) · 1.76 KB
/
api.js
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
const { getAccounts } = require("powercord/webpack").getModule(["getAccounts"], false);
const BASE_URL = "https://api.spotify.com/v1/me/player";
class SpotifyError extends Error {}
function getToken() {
return getAccounts().find((a) => a.type === "spotify")?.accessToken;
}
function request(endpoint, method, data) {
const token = getToken();
if (!token)
return Promise.reject(
new SpotifyError(
"Spotify Token could not be retrieved. Please link your Spotify to Discord in Settings > Connections"
)
);
return fetch(BASE_URL + endpoint, {
method,
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
}
}).then(async (r) => {
if (r.ok) return r;
switch (r.status) {
case 401:
case 403:
throw new SpotifyError("Unauthorized. Try relinking your Spotify");
case 404:
throw new SpotifyError("No player found. Do you have Spotify running?");
case 429:
throw new SpotifyError("Chill!!!! You're clicking the button too damn much D:");
default:
if (r.status >= 500) throw new SpotifyError("Wow, Spotify is having server issues O_o Try again later");
console.error(`[PlayOnSpotify] ${r.status}: ${r.statusText} - ${await r.text()}`);
throw new SpotifyError("Unknown Error. Check the console");
}
});
}
function play(data) {
return request("/play", "PUT", data);
}
function queue(uri) {
return request(`/queue?uri=${encodeURIComponent(uri)}`, "POST", void 0);
}
module.exports = {
play,
queue,
SpotifyError
};