-
Notifications
You must be signed in to change notification settings - Fork 0
/
better-release-radar.ts
358 lines (312 loc) · 10.7 KB
/
better-release-radar.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import * as fs from "fs";
import * as path from "path";
import * as fuzz from "fuzzball";
import * as http from "http";
import { fileURLToPath } from "url";
import { Command } from "commander";
import SpotifyWebApi from "spotify-web-api-node";
import winston from "winston";
import chalk from "chalk";
import Table from "cli-table3";
// TypeScript Interfaces for data structures
interface Artist {
id: string;
name: string;
}
interface Album {
name: string;
release_date: string;
url: string;
artist: string;
type: "album" | "single" | "compilation";
}
interface RawAlbum {
name: string;
release_date: string;
uri: string;
id: string;
album_type: "album" | "single" | "compilation";
available_markets?: string[];
}
// CLI Argument Parsing
const program = new Command();
program
.option(
"--max-age-days <number>",
"Maximum age of albums to display in days",
"60"
)
.option("--hide-eps", "Hide EPs, only show full-length releases", false)
.option("--show-urls", "Show full URLs instead of Spotify URIs", false)
.option("--log-file <path>", "Path to log file", "log.log")
.option("--log-level <level>", "Logging level", "info")
.option("--region <region>", "Region for album releases", "CA")
.parse(process.argv);
const options = program.opts();
// Logging Setup with Winston
const logger = winston.createLogger({
level: options.logLevel,
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf(({ timestamp, level, message }) => {
return `[${timestamp}] [${level.toUpperCase()}]: ${message}`;
})
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: options.logFile }),
],
});
// Constants for the script
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const cacheDir = path.join(__dirname, ".cache");
const tokenCacheFile = path.join(cacheDir, "spotify_tokens.json");
const today = new Date();
const todayCacheFile = path.join(
cacheDir,
`followed_artists_${today.toISOString().split("T")[0]}.json`
);
const SPOTIFY_ALBUM_URL_BASE = "https://open.spotify.com/album/";
// Set up Spotify API
const spotifyApi = new SpotifyWebApi({
clientId: process.env.SPOTIPY_CLIENT_ID || "",
clientSecret: process.env.SPOTIPY_CLIENT_SECRET || "",
redirectUri: "http://localhost:8888/callback",
});
// Step 1: Generate an Authorization URL
function getAuthorizationURL() {
const authorizeURL = spotifyApi.createAuthorizeURL(
["user-follow-read"],
"random-state"
);
console.log(`Authorize your app by visiting this URL: ${authorizeURL}`);
}
// Step 2: Save Tokens to Cache
function saveTokensToCache(accessToken: string, refreshToken: string) {
const tokens = {
accessToken,
refreshToken,
expiresAt: Date.now() + 3600 * 1000, // Set expiry for 1 hour (you can always refresh)
};
fs.writeFileSync(tokenCacheFile, JSON.stringify(tokens));
}
// Step 3: Load Tokens from Cache
function loadTokensFromCache(): {
accessToken: string;
refreshToken: string;
expiresAt: number;
} | null {
if (fs.existsSync(tokenCacheFile)) {
const tokens = JSON.parse(fs.readFileSync(tokenCacheFile, "utf8"));
return tokens;
}
return null;
}
// Step 4: Exchange Authorization Code for Access Token and Refresh Token
async function exchangeAuthorizationCode(code: string) {
try {
const data = await spotifyApi.authorizationCodeGrant(code);
const { access_token, refresh_token } = data.body;
spotifyApi.setAccessToken(access_token);
spotifyApi.setRefreshToken(refresh_token);
saveTokensToCache(access_token, refresh_token);
console.log("Access token and refresh token set.");
} catch (err) {
console.error("Error exchanging authorization code:", err);
}
}
// Step 5: Use refresh token to get a new access token (if needed)
async function refreshAccessToken() {
console.log("Refreshing access token...");
try {
const tokens = loadTokensFromCache(); // Load tokens before trying to refresh
if (!tokens || !tokens.refreshToken) {
throw new Error("Refresh token is missing from cache"); // Handle missing refresh token case
}
// Set the refresh token in the spotifyApi instance
spotifyApi.setRefreshToken(tokens.refreshToken);
// Attempt to refresh the access token using the refresh token
const data = await spotifyApi.refreshAccessToken();
const accessToken = data.body["access_token"];
// Update the spotifyApi instance with the new access token
spotifyApi.setAccessToken(accessToken);
// Save the new access token, but keep the same refresh token in the cache
saveTokensToCache(accessToken, tokens.refreshToken);
console.log("Access token has been refreshed.");
} catch (err) {
console.error("Error refreshing access token", err);
}
}
// Step 6: Authenticate Spotify (Use cached tokens or refresh if needed)
async function authenticateSpotify() {
const tokens = loadTokensFromCache();
if (tokens && tokens.expiresAt > Date.now()) {
spotifyApi.setAccessToken(tokens.accessToken);
spotifyApi.setRefreshToken(tokens.refreshToken);
console.log("Using cached Spotify tokens.");
} else if (tokens && tokens.refreshToken) {
await refreshAccessToken(); // Use refresh token if access token expired
} else {
getAuthorizationURL(); // No tokens, need to authorize
startLocalServer();
}
}
// Step 7: Set up a local server to capture the authorization code from Spotify
function startLocalServer() {
const server = http.createServer(async (req, res) => {
if (req.url && req.url.startsWith("/callback")) {
const url = new URL(req.url, `http://localhost:8888`);
const code = url.searchParams.get("code");
if (code) {
console.log("Authorization code received:", code);
await exchangeAuthorizationCode(code);
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Authorization successful! You can close this window.");
} else {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end("No authorization code found.");
}
server.close(); // Close the server after handling the callback
await main(); // Proceed with fetching data once authenticated
}
});
server.listen(8888, () => {
console.log(
"Listening for Spotify authorization code on http://localhost:8888/callback"
);
});
}
// Ensure that the cache directory exists
if (!fs.existsSync(cacheDir)) {
fs.mkdirSync(cacheDir);
}
// Utility Functions
const daysBetween = (date1: Date, date2: Date) =>
Math.abs((+date1 - +date2) / (1000 * 60 * 60 * 24));
function deleteOldCacheFiles(directory: string, maxAgeDays: number = 30) {
const now = Date.now();
fs.readdirSync(directory).forEach((file) => {
const filePath = path.join(directory, file);
const stats = fs.statSync(filePath);
const fileAgeDays = (now - stats.mtimeMs) / (1000 * 60 * 60 * 24);
if (fileAgeDays > maxAgeDays) {
fs.unlinkSync(filePath);
logger.info(`Deleted old cache file: ${file}`);
}
});
}
async function fetchFollowedArtists(): Promise<Artist[]> {
try {
const response = await spotifyApi.getFollowedArtists({ limit: 50 });
return response.body.artists.items.map((artist) => ({
id: artist.id,
name: artist.name,
}));
} catch (err) {
logger.error("Error fetching followed artists:", err);
throw err;
}
}
async function fetchArtistAlbums(artistId: string): Promise<RawAlbum[]> {
try {
const response = await spotifyApi.getArtistAlbums(artistId, { limit: 50 });
return response.body.items;
} catch (err) {
logger.error(`Error fetching albums for artist ${artistId}`, err);
throw err;
}
}
/// Function to calculate fuzzy similarity between two album names
function isSimilarAlbum(
albumName: string,
seenNames: string[],
threshold = 80
): boolean {
for (const name of seenNames) {
const similarity = fuzz.ratio(albumName, name);
if (similarity >= threshold) {
return true;
}
}
return false;
}
// Function to display albums in a nice formatted table with colors
function displayAlbums(albums) {
// Creating a new table with headers
const table = new Table({
head: [
chalk.bold("Type"),
chalk.bold("Date"),
chalk.bold("URL"),
chalk.bold("Artist"),
chalk.bold("Name"),
],
colWidths: [10, 12, 50, 30, 50],
});
// Adding each album to the table
albums.forEach((album) => {
table.push([
chalk.green(album.type), // Make album type green
chalk.yellow(album.release_date), // Date in yellow
chalk.cyan(album.url), // URL in cyan
chalk.magenta(album.artist), // Artist name in magenta
chalk.whiteBright(album.name), // Album name in white
]);
});
// Print the table to the console
console.log(table.toString());
}
// Main function to fetch and display albums
async function main() {
logger.info("Starting Better Release Radar...");
await authenticateSpotify(); // Ensure authentication is handled
deleteOldCacheFiles(cacheDir, 60);
let artists: Artist[];
if (fs.existsSync(todayCacheFile)) {
artists = JSON.parse(fs.readFileSync(todayCacheFile, "utf8"));
logger.info(`Loaded artists from cache: ${todayCacheFile}`);
} else {
artists = await fetchFollowedArtists();
fs.writeFileSync(todayCacheFile, JSON.stringify(artists));
logger.info("Fetched and cached followed artists");
}
const albums: Album[] = [];
const seenAlbumNames: string[] = [];
const todayDate = new Date();
for (const artist of artists) {
const artistAlbums = await fetchArtistAlbums(artist.id);
for (const album of artistAlbums) {
const albumDate = new Date(album.release_date);
if (
daysBetween(todayDate, albumDate) <= parseInt(options.maxAgeDays, 10) &&
(!options.region ||
(album.available_markets &&
album.available_markets.includes(options.region))) &&
(!options.hideEps || album.album_type === "album") &&
!isSimilarAlbum(album.name, seenAlbumNames)
) {
seenAlbumNames.push(album.name); // Add album name to seen list
albums.push({
name: album.name,
release_date: album.release_date,
url: options.showUrls
? `${SPOTIFY_ALBUM_URL_BASE}${album.id}`
: album.uri,
artist: artist.name,
type: album.album_type as "album" | "single" | "compilation", // Cast to known types
});
}
}
}
// Sort albums by release date
albums.sort(
(a, b) =>
new Date(b.release_date).getTime() - new Date(a.release_date).getTime()
);
// Output the albums in a nice table format
displayAlbums(albums);
}
main().catch((err) => {
logger.error("Error running the script:", err);
});