-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·309 lines (285 loc) · 10.7 KB
/
index.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
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
#! /usr/bin/env node
import path from 'node:path';
import os from 'node:os';
import url from 'node:url';
import _ from 'lodash';
import fs from 'fs-extra';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import LastFM from './lib/LastFM.js';
import AcoustID from './lib/AcoustID.js';
import CoverArtArchive from './lib/CoverArtArchive.js';
import Youtube from './lib/Youtube.js';
import MusicBrainz from './lib/MusicBrainz.js';
import Media from './lib/Media.js';
import Logger from './lib/Logger.js';
const argv = yargs(hideBin(process.argv))
.usage('Usage: $0 [options]')
.example(
'$0 -u Maxattax97 -l 10 -k 1 -o ~/Music -c 4',
"Downloads the 10 most recently loved songs, one at a time for Maxattax97 to home's Music folder with 4 threads of concurrency",
)
.alias('u', 'username')
.nargs('u', 1)
.describe('u', 'The user we are interested in collecting loved songs from')
.string('u') // We parse this path ourselves (might have wildcards).
.demandOption('u')
.alias('o', 'output')
.nargs('o', 1)
.describe(
'o',
'Output path representing your library to synchronize music to',
)
.normalize('o') // Normalizes to a path.
.default('o', './music/')
.alias('c', 'concurrency')
.nargs('c', 1)
.number('c')
.describe(
'c',
'How many threads youtube-dl is allowed to take up for converting codecs',
)
.default('c', os.cpus().length - 1) // This is threads, not cores. Drop one so we don't bog down the whole system.
.alias('l', 'limit')
.nargs('l', 1)
.number('l')
.describe('l', 'How deep to dive into the LastFM loved list')
.default('l', Infinity)
.alias('k', 'chunk')
.nargs('k', 1)
.number('k')
.describe(
'k',
'How many songs should be fetched at a time from LastFM (uses pagination)',
)
.default('k', 10)
.help('h')
.alias('h', 'help')
.parse();
const init = async () => {
const configuration = JSON.parse(
(await fs.readFile('./api-keys.json')).toString(),
);
const pkg = JSON.parse((await fs.readFile('./package.json')).toString());
const USER_AGENT = `lastfm-love-aggregator/${pkg.version} ( https://github.com/Maxattax97/lastfm-love-aggregator )`;
const lfm = new LastFM({
apiKey: configuration.apiKey,
sharedSecret: configuration.sharedSecret,
});
const aid = new AcoustID({
apiKey: configuration.acoustidApiKey,
});
const caa = new CoverArtArchive();
const yt = new Youtube({
threads: argv.threads,
});
const mb = new MusicBrainz({
userAgent: USER_AGENT,
retryOn: true,
});
const user = _.defaultTo(argv.username, 'Maxattax97');
const storagePath = _.defaultTo(
argv.output,
path.join(url.fileURLToPath(import.meta.url), 'music'),
);
Logger.info(`Creating directory: ${storagePath} ...`);
await fs.ensureDir(storagePath);
// TODO: Check the local files before you download them.
Logger.info('Scanning directory metadata ...');
const scanResult = await Media.scanDirectory({
directory: storagePath,
});
Logger.debug('Scan complete: %o', scanResult);
Logger.info(`Retrieving LastFM loved tracks for ${user} ...`);
try {
const lovedResponse = await lfm.userGetLovedTracks({
user,
limit: argv.chunk,
});
const loved = LastFM.parseTracks(lovedResponse.lovedtracks.track);
Logger.debug('Loved songs: %o', loved);
const queue = [];
_.each(loved, (lovedTrack) => {
const asyncId = `[${_.defaultTo(
lovedTrack.title,
'Untitled',
)} by ${_.defaultTo(lovedTrack.artist, 'Unknown')}]`;
queue.push(
(async () => {
try {
const match = _.find(
scanResult,
(track) => track.Comment === lovedTrack.mbid
|| track.Comment === lovedTrack.url
|| (track.title === lovedTrack.title
&& track.artist === lovedTrack.artist),
);
if (match) {
Logger.info(
`${asyncId} already exists in the library, skipping ...`,
);
Logger.debug(
`${asyncId} already exists in the library, skipping: %o`,
match,
);
// TODO: Stop paging after a match.
return;
}
const ytScrape = await lfm.scrapeSong(lovedTrack);
Logger.debug(`${asyncId} Youtube URL: %o`, ytScrape);
if (ytScrape.youtubeUrl) {
try {
Logger.info(`Downloading audio for ${asyncId} ...`);
const audioDownload = await yt.download({
url: ytScrape.youtubeUrl,
filename: `${ytScrape.artist} - ${ytScrape.title}`
.replace(/[<>:"|?*/\\]/g, ' ')
.trim(),
});
Logger.debug(`${asyncId} Audio download: %o`, audioDownload);
let track = null;
let response = null;
try {
response = await aid.lookup({
file: audioDownload.path,
});
} catch (errAcoustic) {
Logger.warn(
`${asyncId} Failed to find an AcousticID match: %o`,
errAcoustic,
);
}
if (response && response.results.length > 0) {
Logger.info(`An AcousticID entry was found for ${asyncId}`);
Logger.debug(`${asyncId} Entry found: %o`, response);
track = AcoustID.parseTrack(response);
} else {
let mbRelease = null;
try {
mbRelease = await mb.track({
mbid: lovedTrack.mbid,
});
Logger.info(`${asyncId} Found a MusicBrainz entry`);
track = MusicBrainz.parseTrack({
trackId: lovedTrack.mbid,
apiResponse: mbRelease,
});
} catch (errMusicBrainz) {
Logger.warn(
`${asyncId} Failed to find a MusicBrainz entry`,
);
}
}
if (track) {
try {
const coverArt = await caa.getFront({
releaseId: track.releaseId,
});
track.cover = coverArt.path;
Logger.info(`A cover art was found for ${asyncId}`);
} catch (errCoverArt) {
if (errCoverArt.message.indexOf('NOT FOUND') >= 0) {
// noop.
} else {
Logger.warn(
`${asyncId} Could not find cover art for ${track.releaseId}:`,
errCoverArt.message,
);
}
}
}
if (track) {
track.comment = track.mbid;
} else {
track = {};
}
// Fill in whatever is missing with the youtube metadata.
track = _.defaultsDeep(track, {
title: ytScrape.title,
artist: ytScrape.artist,
cover: audioDownload.thumbnailPath,
// Tag the mbid and LastFM URL so we can check it later for syncing purposes.
comment: lovedTrack.mbid ? lovedTrack.mbid : lovedTrack.url,
});
Logger.debug(`${asyncId} Finalized track: %o`, track);
if (track.cover && track.cover.indexOf('.jpg') >= 0) {
Logger.debug(`${asyncId} Embedding cover with metadata ...`);
await Media.setMetadata(
_.defaults(track, {
file: audioDownload.path,
attachments: track.cover,
}),
);
} else {
Logger.warn(
`${asyncId} Embedding only metadata ... this is due to a bug in the Youtube API and pending workaround in youtube-dl, see: https://github.com/ytdl-org/youtube-dl/issues/25687`,
);
await Media.setMetadata(
_.defaults(track, {
file: audioDownload.path,
}),
);
}
// TODO: Organize into folders with an CLI option.
const artistTitleFilename = `${track.artist} - ${track.title}`
.replace(/[<>:"|?*/\\]/g, ' ')
.trim();
const restingPlace = path.join(
storagePath,
`${artistTitleFilename}.mp3`,
);
await fs.move(audioDownload.path, restingPlace, {
overwrite: true,
});
Logger.info(
`Updated metadata for ${asyncId} and relocated to ${restingPlace}`,
);
} catch (errYtDl) {
if (
errYtDl.message
&& errYtDl.message.indexOf(
'No mimetype is known for stream 1',
) >= 0
) {
Logger.warn(
`${asyncId} can't be downloaded at this time due to a bug in the Youtube API and pending workaround in youtube-dl, see: https://github.com/ytdl-org/youtube-dl/issues/25687`,
);
} else if (
errYtDl.message
&& errYtDl.message.indexOf('Bad Request') >= 0
) {
Logger.warn(
`Youtube is prohibitting download of ${asyncId} (reasons could include: age-locked, spam protection, DNS errors, or other issues) -- skipping...`,
);
Logger.debug(errYtDl);
} else {
Logger.error(
`${asyncId} Failed to download audio from ${ytScrape.youtubeUrl}: `,
errYtDl,
);
}
}
} else {
Logger.warn(
`${asyncId} has no linked YouTube video -- skipping ...`,
);
}
} catch (errYtScrape) {
Logger.error(
`${asyncId} Failed to scrape Youtube URL's from LastFM: `,
errYtScrape.message,
);
}
})(),
);
});
await Promise.all(queue);
Logger.info('Cleaning up ...');
await caa.cleanup();
await yt.cleanup();
Logger.info('All jobs done, your library has been synchronized');
} catch (errLastFM) {
Logger.error('Failed to read loved songs from LastFM: %o', errLastFM);
}
};
init();