spotify.js 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  1. import mongoose from "mongoose";
  2. import async from "async";
  3. import config from "config";
  4. import * as rax from "retry-axios";
  5. import axios from "axios";
  6. import url from "url";
  7. import CoreClass from "../core";
  8. let SpotifyModule;
  9. let SoundcloudModule;
  10. let DBModule;
  11. let CacheModule;
  12. let MediaModule;
  13. let MusicBrainzModule;
  14. let WikiDataModule;
  15. const youtubeVideoUrlRegex =
  16. /^(https?:\/\/)?(www\.)?(m\.)?(music\.)?(youtube\.com|youtu\.be)\/(watch\?v=)?(?<youtubeId>[\w-]{11})((&([A-Za-z0-9]+)?)*)?$/;
  17. const youtubeVideoIdRegex = /^([\w-]{11})$/;
  18. const spotifyTrackObjectToMusareTrackObject = spotifyTrackObject => {
  19. return {
  20. trackId: spotifyTrackObject.id,
  21. name: spotifyTrackObject.name,
  22. albumId: spotifyTrackObject.album.id,
  23. albumTitle: spotifyTrackObject.album.title,
  24. albumImageUrl: spotifyTrackObject.album.images[0].url,
  25. artists: spotifyTrackObject.artists.map(artist => artist.name),
  26. artistIds: spotifyTrackObject.artists.map(artist => artist.id),
  27. duration: spotifyTrackObject.duration_ms / 1000,
  28. explicit: spotifyTrackObject.explicit,
  29. externalIds: spotifyTrackObject.external_ids,
  30. popularity: spotifyTrackObject.popularity,
  31. isLocal: spotifyTrackObject.is_local
  32. };
  33. };
  34. class RateLimitter {
  35. /**
  36. * Constructor
  37. *
  38. * @param {number} timeBetween - The time between each allowed YouTube request
  39. */
  40. constructor(timeBetween) {
  41. this.dateStarted = Date.now();
  42. this.timeBetween = timeBetween;
  43. }
  44. /**
  45. * Returns a promise that resolves whenever the ratelimit of a YouTube request is done
  46. *
  47. * @returns {Promise} - promise that gets resolved when the rate limit allows it
  48. */
  49. continue() {
  50. return new Promise(resolve => {
  51. if (Date.now() - this.dateStarted >= this.timeBetween) resolve();
  52. else setTimeout(resolve, this.dateStarted + this.timeBetween - Date.now());
  53. });
  54. }
  55. /**
  56. * Restart the rate limit timer
  57. */
  58. restart() {
  59. this.dateStarted = Date.now();
  60. }
  61. }
  62. class _SpotifyModule extends CoreClass {
  63. // eslint-disable-next-line require-jsdoc
  64. constructor() {
  65. super("spotify");
  66. SpotifyModule = this;
  67. }
  68. /**
  69. * Initialises the spotify module
  70. *
  71. * @returns {Promise} - returns promise (reject, resolve)
  72. */
  73. async initialize() {
  74. DBModule = this.moduleManager.modules.db;
  75. CacheModule = this.moduleManager.modules.cache;
  76. MediaModule = this.moduleManager.modules.media;
  77. MusicBrainzModule = this.moduleManager.modules.musicbrainz;
  78. SoundcloudModule = this.moduleManager.modules.soundcloud;
  79. WikiDataModule = this.moduleManager.modules.wikidata;
  80. // this.youtubeApiRequestModel = this.YoutubeApiRequestModel = await DBModule.runJob("GET_MODEL", {
  81. // modelName: "youtubeApiRequest"
  82. // });
  83. this.spotifyTrackModel = this.SpotifyTrackModel = await DBModule.runJob("GET_MODEL", {
  84. modelName: "spotifyTrack"
  85. });
  86. return new Promise((resolve, reject) => {
  87. if (!config.has("apis.spotify") || !config.get("apis.spotify.enabled")) {
  88. reject(new Error("Spotify is not enabled."));
  89. return;
  90. }
  91. this.rateLimiter = new RateLimitter(config.get("apis.spotify.rateLimit"));
  92. this.requestTimeout = config.get("apis.spotify.requestTimeout");
  93. this.axios = axios.create();
  94. this.axios.defaults.raxConfig = {
  95. instance: this.axios,
  96. retry: config.get("apis.spotify.retryAmount"),
  97. noResponseRetries: config.get("apis.spotify.retryAmount")
  98. };
  99. rax.attach(this.axios);
  100. resolve();
  101. });
  102. }
  103. /**
  104. *
  105. * @returns
  106. */
  107. GET_API_TOKEN() {
  108. return new Promise((resolve, reject) => {
  109. CacheModule.runJob("GET", { key: "spotifyApiKey" }, this).then(spotifyApiKey => {
  110. if (spotifyApiKey) {
  111. resolve(spotifyApiKey);
  112. return;
  113. }
  114. this.log("INFO", `No Spotify API token stored in cache, requesting new token.`);
  115. const clientId = config.get("apis.spotify.clientId");
  116. const clientSecret = config.get("apis.spotify.clientSecret");
  117. const unencoded = `${clientId}:${clientSecret}`;
  118. const encoded = Buffer.from(unencoded).toString("base64");
  119. const params = new url.URLSearchParams({ grant_type: "client_credentials" });
  120. SpotifyModule.axios
  121. .post("https://accounts.spotify.com/api/token", params.toString(), {
  122. headers: {
  123. Authorization: `Basic ${encoded}`,
  124. "Content-Type": "application/x-www-form-urlencoded"
  125. }
  126. })
  127. .then(res => {
  128. const { access_token: accessToken, expires_in: expiresIn } = res.data;
  129. // TODO TTL can be later if stuck in queue
  130. CacheModule.runJob(
  131. "SET",
  132. { key: "spotifyApiKey", value: accessToken, ttl: expiresIn - 30 },
  133. this
  134. )
  135. .then(spotifyApiKey => {
  136. this.log(
  137. "SUCCESS",
  138. `Stored new Spotify API token in cache. Expires in ${expiresIn - 30}`
  139. );
  140. resolve(spotifyApiKey);
  141. })
  142. .catch(err => {
  143. this.log(
  144. "ERROR",
  145. `Failed to store new Spotify API token in cache.`,
  146. typeof err === "string" ? err : err.message
  147. );
  148. reject(err);
  149. });
  150. })
  151. .catch(err => {
  152. this.log(
  153. "ERROR",
  154. `Failed to get new Spotify API token.`,
  155. typeof err === "string" ? err : err.message
  156. );
  157. reject(err);
  158. });
  159. });
  160. });
  161. }
  162. /**
  163. * Perform Spotify API get track request
  164. *
  165. * @param {object} payload - object that contains the payload
  166. * @param {object} payload.params - request parameters
  167. * @returns {Promise} - returns promise (reject, resolve)
  168. */
  169. API_GET_TRACK(payload) {
  170. return new Promise((resolve, reject) => {
  171. const { trackId } = payload;
  172. SpotifyModule.runJob(
  173. "API_CALL",
  174. {
  175. url: `https://api.spotify.com/v1/tracks/${trackId}`
  176. },
  177. this
  178. )
  179. .then(response => {
  180. resolve(response);
  181. })
  182. .catch(err => {
  183. reject(err);
  184. });
  185. });
  186. }
  187. /**
  188. * Perform Spotify API get playlist request
  189. *
  190. * @param {object} payload - object that contains the payload
  191. * @param {object} payload.params - request parameters
  192. * @returns {Promise} - returns promise (reject, resolve)
  193. */
  194. API_GET_PLAYLIST(payload) {
  195. return new Promise((resolve, reject) => {
  196. const { playlistId, nextUrl } = payload;
  197. SpotifyModule.runJob(
  198. "API_CALL",
  199. {
  200. url: nextUrl || `https://api.spotify.com/v1/playlists/${playlistId}/tracks`
  201. },
  202. this
  203. )
  204. .then(response => {
  205. resolve(response);
  206. })
  207. .catch(err => {
  208. reject(err);
  209. });
  210. });
  211. }
  212. /**
  213. * Perform Spotify API call
  214. *
  215. * @param {object} payload - object that contains the payload
  216. * @param {object} payload.url - request url
  217. * @param {object} payload.params - request parameters
  218. * @param {object} payload.quotaCost - request quotaCost
  219. * @returns {Promise} - returns promise (reject, resolve)
  220. */
  221. API_CALL(payload) {
  222. return new Promise((resolve, reject) => {
  223. // const { url, params, quotaCost } = payload;
  224. const { url } = payload;
  225. SpotifyModule.runJob("GET_API_TOKEN", {}, this)
  226. .then(spotifyApiToken => {
  227. SpotifyModule.axios
  228. .get(url, {
  229. headers: {
  230. Authorization: `Bearer ${spotifyApiToken}`
  231. },
  232. timeout: SpotifyModule.requestTimeout
  233. })
  234. .then(response => {
  235. if (response.data.error) {
  236. reject(new Error(response.data.error));
  237. } else {
  238. resolve({ response });
  239. }
  240. })
  241. .catch(err => {
  242. reject(err);
  243. });
  244. })
  245. .catch(err => {
  246. this.log(
  247. "ERROR",
  248. `Spotify API call failed as an error occured whilst getting the API token`,
  249. typeof err === "string" ? err : err.message
  250. );
  251. resolve(err);
  252. });
  253. });
  254. }
  255. /**
  256. * Create Spotify track
  257. *
  258. * @param {object} payload - an object containing the payload
  259. * @param {string} payload.spotifyTracks - the spotifyTracks
  260. * @returns {Promise} - returns a promise (resolve, reject)
  261. */
  262. CREATE_TRACKS(payload) {
  263. return new Promise((resolve, reject) => {
  264. async.waterfall(
  265. [
  266. next => {
  267. const { spotifyTracks } = payload;
  268. if (!Array.isArray(spotifyTracks)) next("Invalid spotifyTracks type");
  269. else {
  270. const trackIds = spotifyTracks.map(spotifyTrack => spotifyTrack.trackId);
  271. SpotifyModule.spotifyTrackModel.find({ trackId: trackIds }, (err, existingTracks) => {
  272. if (err) return next(err);
  273. const existingTrackIds = existingTracks.map(existingTrack => existingTrack.trackId);
  274. const newSpotifyTracks = spotifyTracks.filter(
  275. spotifyTrack => existingTrackIds.indexOf(spotifyTrack.trackId) === -1
  276. );
  277. SpotifyModule.spotifyTrackModel.insertMany(newSpotifyTracks, next);
  278. });
  279. }
  280. },
  281. (spotifyTracks, next) => {
  282. const mediaSources = spotifyTracks.map(spotifyTrack => `spotify:${spotifyTrack.trackId}`);
  283. async.eachLimit(
  284. mediaSources,
  285. 2,
  286. (mediaSource, next) => {
  287. MediaModule.runJob("RECALCULATE_RATINGS", { mediaSource }, this)
  288. .then(() => next())
  289. .catch(next);
  290. },
  291. err => {
  292. if (err) next(err);
  293. else next(null, spotifyTracks);
  294. }
  295. );
  296. }
  297. ],
  298. (err, spotifyTracks) => {
  299. if (err) reject(new Error(err));
  300. else resolve({ spotifyTracks });
  301. }
  302. );
  303. });
  304. }
  305. /**
  306. * Gets tracks from media sources
  307. *
  308. * @param {object} payload
  309. * @returns {Promise}
  310. */
  311. async GET_TRACKS_FROM_MEDIA_SOURCES(payload) {
  312. return new Promise((resolve, reject) => {
  313. const { mediaSources } = payload;
  314. const responses = {};
  315. const promises = [];
  316. mediaSources.forEach(mediaSource => {
  317. promises.push(
  318. new Promise(resolve => {
  319. const trackId = mediaSource.split(":")[1];
  320. SpotifyModule.runJob("GET_TRACK", { identifier: trackId, createMissing: true }, this)
  321. .then(({ track }) => {
  322. responses[mediaSource] = track;
  323. })
  324. .catch(err => {
  325. SpotifyModule.log(
  326. "ERROR",
  327. `Getting tracked with media source ${mediaSource} failed.`,
  328. typeof err === "string" ? err : err.message
  329. );
  330. responses[mediaSource] = typeof err === "string" ? err : err.message;
  331. })
  332. .finally(() => {
  333. resolve();
  334. });
  335. })
  336. );
  337. });
  338. Promise.all(promises)
  339. .then(() => {
  340. SpotifyModule.log("SUCCESS", `Got all tracks.`);
  341. resolve({ tracks: responses });
  342. })
  343. .catch(reject);
  344. });
  345. }
  346. /**
  347. * Get Spotify track
  348. *
  349. * @param {object} payload - an object containing the payload
  350. * @param {string} payload.identifier - the spotify track ObjectId or track id
  351. * @param {string} payload.createMissing - attempt to fetch and create track if not in db
  352. * @returns {Promise} - returns a promise (resolve, reject)
  353. */
  354. GET_TRACK(payload) {
  355. return new Promise((resolve, reject) => {
  356. async.waterfall(
  357. [
  358. next => {
  359. const query = mongoose.isObjectIdOrHexString(payload.identifier)
  360. ? { _id: payload.identifier }
  361. : { trackId: payload.identifier };
  362. return SpotifyModule.spotifyTrackModel.findOne(query, next);
  363. },
  364. (track, next) => {
  365. if (track) return next(null, track, false);
  366. if (mongoose.isObjectIdOrHexString(payload.identifier) || !payload.createMissing)
  367. return next("Spotify track not found.");
  368. return SpotifyModule.runJob("API_GET_TRACK", { trackId: payload.identifier }, this)
  369. .then(({ response }) => {
  370. const { data } = response;
  371. if (!data || !data.id)
  372. return next("The specified track does not exist or cannot be publicly accessed.");
  373. const spotifyTrack = spotifyTrackObjectToMusareTrackObject(data);
  374. return next(null, false, spotifyTrack);
  375. })
  376. .catch(next);
  377. },
  378. (track, spotifyTrack, next) => {
  379. if (track) return next(null, track, true);
  380. return SpotifyModule.runJob("CREATE_TRACKS", { spotifyTracks: [spotifyTrack] }, this)
  381. .then(res => {
  382. if (res.spotifyTracks.length === 1) next(null, res.spotifyTracks[0], false);
  383. else next("Spotify track not found.");
  384. })
  385. .catch(next);
  386. }
  387. ],
  388. (err, track, existing) => {
  389. if (err) reject(new Error(err));
  390. else if (track.isLocal) reject(new Error("Track is local."));
  391. else resolve({ track, existing });
  392. }
  393. );
  394. });
  395. }
  396. /**
  397. * Returns an array of songs taken from a Spotify playlist
  398. *
  399. * @param {object} payload - object that contains the payload
  400. * @param {string} payload.url - the id of the Spotify playlist
  401. * @returns {Promise} - returns promise (reject, resolve)
  402. */
  403. GET_PLAYLIST(payload) {
  404. return new Promise((resolve, reject) => {
  405. const spotifyPlaylistUrlRegex = /.+open\.spotify\.com\/playlist\/(?<playlistId>[A-Za-z0-9]+)/;
  406. const match = spotifyPlaylistUrlRegex.exec(payload.url);
  407. if (!match || !match.groups) {
  408. SpotifyModule.log("ERROR", "GET_PLAYLIST", "Invalid Spotify playlist URL query.");
  409. reject(new Error("Invalid playlist URL."));
  410. return;
  411. }
  412. const { playlistId } = match.groups;
  413. async.waterfall(
  414. [
  415. next => {
  416. let spotifyTracks = [];
  417. let total = -1;
  418. let nextUrl = "";
  419. async.whilst(
  420. next => {
  421. SpotifyModule.log(
  422. "INFO",
  423. `Getting playlist progress for job (${this.toString()}): ${
  424. spotifyTracks.length
  425. } tracks gotten so far. Total tracks: ${total}.`
  426. );
  427. next(null, nextUrl !== null);
  428. },
  429. next => {
  430. // Add 250ms delay between each job request
  431. setTimeout(() => {
  432. SpotifyModule.runJob("API_GET_PLAYLIST", { playlistId, nextUrl }, this)
  433. .then(({ response }) => {
  434. const { data } = response;
  435. if (!data)
  436. return next("The provided URL does not exist or cannot be accessed.");
  437. total = data.total;
  438. nextUrl = data.next;
  439. const { items } = data;
  440. const trackObjects = items.map(item => item.track);
  441. const newSpotifyTracks = trackObjects.map(trackObject =>
  442. spotifyTrackObjectToMusareTrackObject(trackObject)
  443. );
  444. spotifyTracks = spotifyTracks.concat(newSpotifyTracks);
  445. next();
  446. })
  447. .catch(err => next(err));
  448. }, 1000);
  449. },
  450. err => {
  451. if (err) next(err);
  452. else {
  453. return SpotifyModule.runJob("CREATE_TRACKS", { spotifyTracks }, this)
  454. .then(() => {
  455. next(
  456. null,
  457. spotifyTracks.map(spotifyTrack => spotifyTrack.trackId)
  458. );
  459. })
  460. .catch(next);
  461. }
  462. }
  463. );
  464. }
  465. ],
  466. (err, soundcloudTrackIds) => {
  467. if (err && err !== true) {
  468. SpotifyModule.log(
  469. "ERROR",
  470. "GET_PLAYLIST",
  471. "Some error has occurred.",
  472. typeof err === "string" ? err : err.message
  473. );
  474. reject(new Error(typeof err === "string" ? err : err.message));
  475. } else {
  476. resolve({ songs: soundcloudTrackIds });
  477. }
  478. }
  479. );
  480. // kind;
  481. });
  482. }
  483. /**
  484. *
  485. * @param {*} payload
  486. * @returns
  487. */
  488. async GET_ALTERNATIVE_MEDIA_SOURCES_FOR_TRACKS(payload) {
  489. const { mediaSources, collectAlternativeMediaSourcesOrigins } = payload;
  490. // console.log("KR*S94955", mediaSources);
  491. // this.pub
  492. await async.eachLimit(mediaSources, 1, async mediaSource => {
  493. try {
  494. const result = await SpotifyModule.runJob(
  495. "GET_ALTERNATIVE_MEDIA_SOURCES_FOR_TRACK",
  496. { mediaSource, collectAlternativeMediaSourcesOrigins },
  497. this
  498. );
  499. this.publishProgress({
  500. status: "working",
  501. message: `Got alternative media for ${mediaSource}`,
  502. data: {
  503. mediaSource,
  504. status: "success",
  505. result
  506. }
  507. });
  508. } catch (err) {
  509. this.publishProgress({
  510. status: "working",
  511. message: `Failed to get alternative media for ${mediaSource}`,
  512. data: {
  513. mediaSource,
  514. status: "error"
  515. }
  516. });
  517. }
  518. });
  519. console.log("Done!");
  520. this.publishProgress({
  521. status: "finished",
  522. message: `Finished getting alternative media`
  523. });
  524. }
  525. /**
  526. *
  527. * @param {*} payload
  528. * @returns
  529. */
  530. async GET_ALTERNATIVE_MEDIA_SOURCES_FOR_TRACK(payload) {
  531. const { mediaSource, collectAlternativeMediaSourcesOrigins } = payload;
  532. if (!mediaSource || !mediaSource.startsWith("spotify:"))
  533. throw new Error("Media source provided is not a valid Spotify media source.");
  534. const spotifyTrackId = mediaSource.split(":")[1];
  535. const { track: spotifyTrack } = await SpotifyModule.runJob(
  536. "GET_TRACK",
  537. {
  538. identifier: spotifyTrackId,
  539. createMissing: true
  540. },
  541. this
  542. );
  543. const ISRC = spotifyTrack.externalIds.isrc;
  544. if (!ISRC) throw new Error(`ISRC not found for Spotify track ${mediaSource}.`);
  545. const mediaSources = new Set();
  546. const mediaSourcesOrigins = {};
  547. const jobsToRun = [];
  548. const ISRCApiResponse = await MusicBrainzModule.runJob(
  549. "API_CALL",
  550. {
  551. url: `https://musicbrainz.org/ws/2/isrc/${ISRC}`,
  552. params: {
  553. fmt: "json",
  554. inc: "url-rels+work-rels"
  555. }
  556. },
  557. this
  558. );
  559. // console.log("ISRCApiResponse");
  560. // console.dir(ISRCApiResponse, { depth: 5 });
  561. ISRCApiResponse.recordings.forEach(recording => {
  562. recording.relations.forEach(relation => {
  563. if (relation["target-type"] === "url" && relation.url) {
  564. // relation["type-id"] === "7e41ef12-a124-4324-afdb-fdbae687a89c"
  565. const { resource } = relation.url;
  566. if (resource.indexOf("soundcloud.com") !== -1) {
  567. // throw new Error(`Unable to parse SoundCloud resource ${resource}.`);
  568. const promise = new Promise(resolve => {
  569. SoundcloudModule.runJob(
  570. "GET_TRACK_FROM_URL",
  571. { identifier: resource, createMissing: true },
  572. this
  573. )
  574. .then(response => {
  575. const { trackId } = response.track;
  576. const mediaSource = `soundcloud:${trackId}`;
  577. mediaSources.add(mediaSource);
  578. if (collectAlternativeMediaSourcesOrigins) {
  579. const mediaSourceOrigins = [
  580. `Spotify track ${spotifyTrackId}`,
  581. `ISRC ${ISRC}`,
  582. `MusicBrainz recordings`,
  583. `MusicBrainz recording ${recording.id}`,
  584. `MusicBrainz relations`,
  585. `MusicBrainz relation target-type url`,
  586. `MusicBrainz relation resource ${resource}`,
  587. `SoundCloud ID ${trackId}`
  588. ];
  589. if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  590. mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  591. }
  592. resolve();
  593. })
  594. .catch(() => {
  595. resolve();
  596. });
  597. });
  598. jobsToRun.push(promise);
  599. return;
  600. }
  601. if (resource.indexOf("youtube.com") !== -1 || resource.indexOf("youtu.be") !== -1) {
  602. const match = youtubeVideoUrlRegex.exec(resource);
  603. if (!match) throw new Error(`Unable to parse YouTube resource ${resource}.`);
  604. const { youtubeId } = match.groups;
  605. if (!youtubeId) throw new Error(`Unable to parse YouTube resource ${resource}.`);
  606. const mediaSource = `youtube:${youtubeId}`;
  607. mediaSources.add(mediaSource);
  608. if (collectAlternativeMediaSourcesOrigins) {
  609. const mediaSourceOrigins = [
  610. `Spotify track ${spotifyTrackId}`,
  611. `ISRC ${ISRC}`,
  612. `MusicBrainz recordings`,
  613. `MusicBrainz recording ${recording.id}`,
  614. `MusicBrainz relations`,
  615. `MusicBrainz relation target-type url`,
  616. `MusicBrainz relation resource ${resource}`,
  617. `YouTube ID ${youtubeId}`
  618. ];
  619. if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  620. mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  621. }
  622. return;
  623. }
  624. return;
  625. }
  626. if (relation["target-type"] === "work") {
  627. const promise = new Promise(resolve => {
  628. WikiDataModule.runJob("API_GET_DATA_FROM_MUSICBRAINZ_WORK", { workId: relation.work.id }, this)
  629. .then(resultBody => {
  630. const youtubeIds = Array.from(
  631. new Set(
  632. resultBody.results.bindings
  633. .filter(binding => !!binding.YouTube_video_ID)
  634. .map(binding => binding.YouTube_video_ID.value)
  635. )
  636. );
  637. // const soundcloudIds = Array.from(
  638. // new Set(
  639. // resultBody.results.bindings
  640. // .filter(binding => !!binding["SoundCloud_track_ID"])
  641. // .map(binding => binding["SoundCloud_track_ID"].value)
  642. // )
  643. // );
  644. const musicVideoEntityUrls = Array.from(
  645. new Set(
  646. resultBody.results.bindings
  647. .filter(binding => !!binding.Music_video_entity_URL)
  648. .map(binding => binding.Music_video_entity_URL.value)
  649. )
  650. );
  651. youtubeIds.forEach(youtubeId => {
  652. const mediaSource = `youtube:${youtubeId}`;
  653. mediaSources.add(mediaSource);
  654. if (collectAlternativeMediaSourcesOrigins) {
  655. const mediaSourceOrigins = [
  656. `Spotify track ${spotifyTrackId}`,
  657. `ISRC ${ISRC}`,
  658. `MusicBrainz recordings`,
  659. `MusicBrainz recording ${recording.id}`,
  660. `MusicBrainz relations`,
  661. `MusicBrainz relation target-type work`,
  662. `MusicBrainz relation work id ${relation.work.id}`,
  663. `WikiData select from MusicBrainz work id ${relation.work.id}`,
  664. `YouTube ID ${youtubeId}`
  665. ];
  666. if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  667. mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  668. }
  669. });
  670. // soundcloudIds.forEach(soundcloudId => {
  671. // const mediaSource = `soundcloud:${soundcloudId}`;
  672. // mediaSources.add(mediaSource);
  673. // if (collectAlternativeMediaSourcesOrigins) {
  674. // const mediaSourceOrigins = [
  675. // `Spotify track ${spotifyTrackId}`,
  676. // `ISRC ${ISRC}`,
  677. // `MusicBrainz recordings`,
  678. // `MusicBrainz recording ${recording.id}`,
  679. // `MusicBrainz relations`,
  680. // `MusicBrainz relation target-type work`,
  681. // `MusicBrainz relation work id ${relation.work.id}`,
  682. // `WikiData select from MusicBrainz work id ${relation.work.id}`,
  683. // `SoundCloud ID ${soundcloudId}`
  684. // ];
  685. // if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  686. // mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  687. // }
  688. // });
  689. const promisesToRun2 = [];
  690. musicVideoEntityUrls.forEach(musicVideoEntityUrl => {
  691. promisesToRun2.push(
  692. new Promise(resolve => {
  693. WikiDataModule.runJob(
  694. "API_GET_DATA_FROM_ENTITY_URL",
  695. { entityUrl: musicVideoEntityUrl },
  696. this
  697. ).then(resultBody => {
  698. const youtubeIds = Array.from(
  699. new Set(
  700. resultBody.results.bindings
  701. .filter(binding => !!binding.YouTube_video_ID)
  702. .map(binding => binding.YouTube_video_ID.value)
  703. )
  704. );
  705. // const soundcloudIds = Array.from(
  706. // new Set(
  707. // resultBody.results.bindings
  708. // .filter(binding => !!binding["SoundCloud_track_ID"])
  709. // .map(binding => binding["SoundCloud_track_ID"].value)
  710. // )
  711. // );
  712. youtubeIds.forEach(youtubeId => {
  713. const mediaSource = `youtube:${youtubeId}`;
  714. mediaSources.add(mediaSource);
  715. // if (collectAlternativeMediaSourcesOrigins) {
  716. // const mediaSourceOrigins = [
  717. // `Spotify track ${spotifyTrackId}`,
  718. // `ISRC ${ISRC}`,
  719. // `MusicBrainz recordings`,
  720. // `MusicBrainz recording ${recording.id}`,
  721. // `MusicBrainz relations`,
  722. // `MusicBrainz relation target-type work`,
  723. // `MusicBrainz relation work id ${relation.work.id}`,
  724. // `WikiData select from MusicBrainz work id ${relation.work.id}`,
  725. // `YouTube ID ${youtubeId}`
  726. // ];
  727. // if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  728. // mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  729. // }
  730. });
  731. // soundcloudIds.forEach(soundcloudId => {
  732. // const mediaSource = `soundcloud:${soundcloudId}`;
  733. // mediaSources.add(mediaSource);
  734. // // if (collectAlternativeMediaSourcesOrigins) {
  735. // // const mediaSourceOrigins = [
  736. // // `Spotify track ${spotifyTrackId}`,
  737. // // `ISRC ${ISRC}`,
  738. // // `MusicBrainz recordings`,
  739. // // `MusicBrainz recording ${recording.id}`,
  740. // // `MusicBrainz relations`,
  741. // // `MusicBrainz relation target-type work`,
  742. // // `MusicBrainz relation work id ${relation.work.id}`,
  743. // // `WikiData select from MusicBrainz work id ${relation.work.id}`,
  744. // // `SoundCloud ID ${soundcloudId}`
  745. // // ];
  746. // // if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  747. // // mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  748. // // }
  749. // });
  750. resolve();
  751. });
  752. })
  753. );
  754. });
  755. Promise.allSettled(promisesToRun2).then(resolve);
  756. })
  757. .catch(err => {
  758. console.log("KRISWORKERR", err);
  759. resolve();
  760. });
  761. });
  762. jobsToRun.push(promise);
  763. //WikiDataModule.runJob("API_GET_DATA_FROM_MUSICBRAINZ_WORK", { workId: relation.work.id }, this));
  764. return;
  765. }
  766. });
  767. });
  768. const RecordingApiResponse = await MusicBrainzModule.runJob(
  769. "API_CALL",
  770. {
  771. url: `https://musicbrainz.org/ws/2/recording/`,
  772. params: {
  773. fmt: "json",
  774. query: `isrc:${ISRC}`
  775. }
  776. },
  777. this
  778. );
  779. const releaseIds = new Set();
  780. const releaseGroupIds = new Set();
  781. RecordingApiResponse.recordings.forEach(recording => {
  782. const recordingId = recording.id;
  783. // console.log("Recording:", recording.id);
  784. recording.releases.forEach(release => {
  785. const releaseId = release.id;
  786. // console.log("Release:", releaseId);
  787. const releaseGroupId = release["release-group"].id;
  788. // console.log("Release group:", release["release-group"]);
  789. // console.log("Release group id:", release["release-group"].id);
  790. // console.log("Release group type id:", release["release-group"]["type-id"]);
  791. // console.log("Release group primary type id:", release["release-group"]["primary-type-id"]);
  792. // console.log("Release group primary type:", release["release-group"]["primary-type"]);
  793. // d6038452-8ee0-3f68-affc-2de9a1ede0b9 = single
  794. // 6d0c5bf6-7a33-3420-a519-44fc63eedebf = EP
  795. if (
  796. release["release-group"]["type-id"] === "d6038452-8ee0-3f68-affc-2de9a1ede0b9" ||
  797. release["release-group"]["type-id"] === "6d0c5bf6-7a33-3420-a519-44fc63eedebf"
  798. ) {
  799. releaseIds.add(releaseId);
  800. releaseGroupIds.add(releaseGroupId);
  801. }
  802. });
  803. });
  804. Array.from(releaseGroupIds).forEach(releaseGroupId => {
  805. const promise = new Promise(resolve => {
  806. WikiDataModule.runJob("API_GET_DATA_FROM_MUSICBRAINZ_RELEASE_GROUP", { releaseGroupId }, this)
  807. .then(resultBody => {
  808. const youtubeIds = Array.from(
  809. new Set(
  810. resultBody.results.bindings
  811. .filter(binding => !!binding.YouTube_video_ID)
  812. .map(binding => binding.YouTube_video_ID.value)
  813. )
  814. );
  815. // const soundcloudIds = Array.from(
  816. // new Set(
  817. // resultBody.results.bindings
  818. // .filter(binding => !!binding["SoundCloud_track_ID"])
  819. // .map(binding => binding["SoundCloud_track_ID"].value)
  820. // )
  821. // );
  822. const musicVideoEntityUrls = Array.from(
  823. new Set(
  824. resultBody.results.bindings
  825. .filter(binding => !!binding.Music_video_entity_URL)
  826. .map(binding => binding.Music_video_entity_URL.value)
  827. )
  828. );
  829. youtubeIds.forEach(youtubeId => {
  830. const mediaSource = `youtube:${youtubeId}`;
  831. mediaSources.add(mediaSource);
  832. // if (collectAlternativeMediaSourcesOrigins) {
  833. // const mediaSourceOrigins = [
  834. // `Spotify track ${spotifyTrackId}`,
  835. // `ISRC ${ISRC}`,
  836. // `MusicBrainz recordings`,
  837. // `MusicBrainz recording ${recording.id}`,
  838. // `MusicBrainz relations`,
  839. // `MusicBrainz relation target-type work`,
  840. // `MusicBrainz relation work id ${relation.work.id}`,
  841. // `WikiData select from MusicBrainz work id ${relation.work.id}`,
  842. // `YouTube ID ${youtubeId}`
  843. // ];
  844. // if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  845. // mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  846. // }
  847. });
  848. // soundcloudIds.forEach(soundcloudId => {
  849. // const mediaSource = `soundcloud:${soundcloudId}`;
  850. // mediaSources.add(mediaSource);
  851. // // if (collectAlternativeMediaSourcesOrigins) {
  852. // // const mediaSourceOrigins = [
  853. // // `Spotify track ${spotifyTrackId}`,
  854. // // `ISRC ${ISRC}`,
  855. // // `MusicBrainz recordings`,
  856. // // `MusicBrainz recording ${recording.id}`,
  857. // // `MusicBrainz relations`,
  858. // // `MusicBrainz relation target-type work`,
  859. // // `MusicBrainz relation work id ${relation.work.id}`,
  860. // // `WikiData select from MusicBrainz work id ${relation.work.id}`,
  861. // // `SoundCloud ID ${soundcloudId}`
  862. // // ];
  863. // // if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  864. // // mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  865. // // }
  866. // });
  867. const promisesToRun2 = [];
  868. musicVideoEntityUrls.forEach(musicVideoEntityUrl => {
  869. promisesToRun2.push(
  870. new Promise(resolve => {
  871. WikiDataModule.runJob(
  872. "API_GET_DATA_FROM_ENTITY_URL",
  873. { entityUrl: musicVideoEntityUrl },
  874. this
  875. ).then(resultBody => {
  876. const youtubeIds = Array.from(
  877. new Set(
  878. resultBody.results.bindings
  879. .filter(binding => !!binding.YouTube_video_ID)
  880. .map(binding => binding.YouTube_video_ID.value)
  881. )
  882. );
  883. // const soundcloudIds = Array.from(
  884. // new Set(
  885. // resultBody.results.bindings
  886. // .filter(binding => !!binding["SoundCloud_track_ID"])
  887. // .map(binding => binding["SoundCloud_track_ID"].value)
  888. // )
  889. // );
  890. youtubeIds.forEach(youtubeId => {
  891. const mediaSource = `youtube:${youtubeId}`;
  892. mediaSources.add(mediaSource);
  893. // if (collectAlternativeMediaSourcesOrigins) {
  894. // const mediaSourceOrigins = [
  895. // `Spotify track ${spotifyTrackId}`,
  896. // `ISRC ${ISRC}`,
  897. // `MusicBrainz recordings`,
  898. // `MusicBrainz recording ${recording.id}`,
  899. // `MusicBrainz relations`,
  900. // `MusicBrainz relation target-type work`,
  901. // `MusicBrainz relation work id ${relation.work.id}`,
  902. // `WikiData select from MusicBrainz work id ${relation.work.id}`,
  903. // `YouTube ID ${youtubeId}`
  904. // ];
  905. // if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  906. // mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  907. // }
  908. });
  909. // soundcloudIds.forEach(soundcloudId => {
  910. // const mediaSource = `soundcloud:${soundcloudId}`;
  911. // mediaSources.add(mediaSource);
  912. // // if (collectAlternativeMediaSourcesOrigins) {
  913. // // const mediaSourceOrigins = [
  914. // // `Spotify track ${spotifyTrackId}`,
  915. // // `ISRC ${ISRC}`,
  916. // // `MusicBrainz recordings`,
  917. // // `MusicBrainz recording ${recording.id}`,
  918. // // `MusicBrainz relations`,
  919. // // `MusicBrainz relation target-type work`,
  920. // // `MusicBrainz relation work id ${relation.work.id}`,
  921. // // `WikiData select from MusicBrainz work id ${relation.work.id}`,
  922. // // `SoundCloud ID ${soundcloudId}`
  923. // // ];
  924. // // if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  925. // // mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  926. // // }
  927. // });
  928. resolve();
  929. });
  930. })
  931. );
  932. });
  933. Promise.allSettled(promisesToRun2).then(resolve);
  934. })
  935. .catch(err => {
  936. console.log("KRISWORKERR", err);
  937. resolve();
  938. });
  939. });
  940. jobsToRun.push(promise);
  941. });
  942. // console.log("RecordingApiResponse");
  943. // console.dir(RecordingApiResponse, { depth: 10 });
  944. // console.dir(RecordingApiResponse.recordings[0].releases[0], { depth: 10 });
  945. await Promise.allSettled(jobsToRun);
  946. return {
  947. mediaSources: Array.from(mediaSources),
  948. mediaSourcesOrigins
  949. };
  950. }
  951. }
  952. export default new _SpotifyModule();