-
Notifications
You must be signed in to change notification settings - Fork 1
/
spotify.ts
217 lines (197 loc) · 7.44 KB
/
spotify.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import { config, cosmicSync } from "@anandchowdhary/cosmic";
import dayjs from "dayjs";
import week from "dayjs/plugin/weekOfYear";
import { join } from "path";
import SpotifyAPI from "spotify-web-api-node";
import { integrationConfig, write } from "../common";
import type { Integration } from "../integration";
dayjs.extend(week);
cosmicSync("stethoscope");
/**
* From `T` make a set of properties by key `K` become optional
* @source https://github.com/piotrwitek/utility-types/blob/master/src/mapped-types.ts#L540
*/
type Optional<T extends object, K extends keyof T = keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
const api = new SpotifyAPI({
clientId: config("spotifyClientId") || "example",
clientSecret: config("spotifyClientSecret") || "example",
redirectUri: config("spotifyCallbackUrl") || "http://localhost:3000/callback",
accessToken: config("spotifyAccessToken") || "example",
refreshToken: config("spotifyRefreshToken") || "example",
});
const callbackUrl = async () => {
const authorizeURL = api.createAuthorizeURL(["user-top-read", "user-library-read"], "state");
console.log(authorizeURL);
};
const authTokens = async (code: string) => {
const { body } = await api.authorizationCodeGrant(code);
console.log("Access token", body.access_token);
console.log("Refresh token", body.refresh_token);
};
const cleanSpotifyArtistResponse = (
artist: Optional<SpotifyApi.ArtistObjectFull, "followers" | "external_urls" | "popularity">
) => {
delete artist.followers;
delete artist.external_urls;
delete artist.popularity;
return artist;
};
const cleanSpotifyTrackResponse = (
track:
| Optional<
SpotifyApi.TrackObjectFull,
| "available_markets"
| "disc_number"
| "duration_ms"
| "external_urls"
| "id"
| "is_playable"
| "linked_from"
| "type"
| "track_number"
| "uri"
| "external_ids"
| "popularity"
>
| Optional<
SpotifyApi.TrackObjectSimplified,
| "available_markets"
| "disc_number"
| "duration_ms"
| "external_urls"
| "id"
| "type"
| "is_playable"
| "linked_from"
| "track_number"
| "uri"
>
) => {
delete track.available_markets;
delete track.disc_number;
delete track.duration_ms;
delete track.external_urls;
delete track.id;
delete track.is_playable;
delete track.linked_from;
delete track.track_number;
delete track.uri;
delete track.type;
if ("external_ids" in track) delete track.external_ids;
if ("popularity" in track) delete track.popularity;
if ("album" in track) {
delete (track.album as any).album_type;
delete (track.album as any).available_markets;
delete (track.album as any).external_urls;
delete (track.album as any).id;
}
return track;
};
const cleanSpotifyArtistsResponse = (artists: SpotifyApi.ArtistObjectFull[]) => {
return artists.map((artist) => cleanSpotifyArtistResponse(artist));
};
const cleanSpotifyTracksResponse = (tracks: SpotifyApi.TrackObjectFull[]) => {
return tracks.map((track) => cleanSpotifyTrackResponse(track));
};
export default class Spotify implements Integration {
name = "spotify";
cli = { callbackUrl, authTokens };
async update() {
console.log("Spotify: Starting...");
const data = await api.refreshAccessToken();
api.setAccessToken(data.body.access_token);
console.log("Spotify: Refreshed access token");
if (integrationConfig("spotify", "history")) {
const history = await api.getMyRecentlyPlayedTracks();
const itemsByDate: { [index: string]: Array<any> } = {};
for await (const item of history.body.items) {
const date = dayjs(item.played_at);
const year = date.format("YYYY");
const month = date.format("MM");
const day = date.format("DD");
itemsByDate[`${year}/${month}/${day}`] = itemsByDate[`${year}/${month}/${day}`] || [];
itemsByDate[`${year}/${month}/${day}`].push(cleanSpotifyTrackResponse(item.track));
}
for await (const key of Object.keys(itemsByDate)) {
await write(
join(".", "data", "spotify-music", "daily", key, "listening-history.json"),
JSON.stringify(itemsByDate[key], null, 2)
);
}
console.log("Spotify: Added listening history");
}
const date = dayjs();
const year = date.format("YYYY");
const month = date.format("MM");
const day = date.format("DD");
if (integrationConfig("spotify", "library")) {
const library = await api.getMySavedTracks();
const libraryItems = cleanSpotifyTracksResponse(library.body.items.map((item) => item.track)).map(
(item, index) => ({
...item,
date: library.body.items[index].added_at,
})
);
await write(
join(".", "data", "spotify-music", "daily", year, month, day, "library.json"),
JSON.stringify(libraryItems, null, 2)
);
console.log("Spotify: Added library");
}
if (integrationConfig("spotify", "top-tracks")) {
const shortTermTopTracks = cleanSpotifyTracksResponse(
(await api.getMyTopTracks({ time_range: "short_term" })).body.items
);
await write(
join(".", "data", "spotify-music", "daily", year, month, day, "top-tracks", "short-term.json"),
JSON.stringify(shortTermTopTracks, null, 2)
);
console.log("Spotify: Added short-term top tracks");
const mediumTermTopTracks = cleanSpotifyTracksResponse(
(await api.getMyTopTracks({ time_range: "medium_term" })).body.items
);
await write(
join(".", "data", "spotify-music", "daily", year, month, day, "top-tracks", "medium-term.json"),
JSON.stringify(mediumTermTopTracks, null, 2)
);
console.log("Spotify: Added medium-term top tracks");
const longTermTopTracks = cleanSpotifyTracksResponse(
(await api.getMyTopTracks({ time_range: "long_term" })).body.items
);
await write(
join(".", "data", "spotify-music", "daily", year, month, day, "top-tracks", "long-term.json"),
JSON.stringify(longTermTopTracks, null, 2)
);
console.log("Spotify: Added long-term top tracks");
}
if (integrationConfig("spotify", "top-artists")) {
const shortTermTopArtists = cleanSpotifyArtistsResponse(
(await api.getMyTopArtists({ time_range: "short_term" })).body.items
);
await write(
join(".", "data", "spotify-music", "daily", year, month, day, "top-artists", "short-term.json"),
JSON.stringify(shortTermTopArtists, null, 2)
);
console.log("Spotify: Added short-term top artists");
const mediumTermTopArtists = cleanSpotifyArtistsResponse(
(await api.getMyTopArtists({ time_range: "medium_term" })).body.items
);
await write(
join(".", "data", "spotify-music", "daily", year, month, day, "top-artists", "medium-term.json"),
JSON.stringify(mediumTermTopArtists, null, 2)
);
console.log("Spotify: Added medium-term top artists");
const longTermTopArtists = cleanSpotifyArtistsResponse(
(await api.getMyTopArtists({ time_range: "long_term" })).body.items
);
await write(
join(".", "data", "spotify-music", "daily", year, month, day, "top-artists", "long-term.json"),
JSON.stringify(longTermTopArtists, null, 2)
);
console.log("Spotify: Added long-term top artists");
}
console.log("Spotify: Completed");
}
async legacy() {}
async summary() {}
}