spotify.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  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. console.log("ERROR", err);
  510. this.publishProgress({
  511. status: "working",
  512. message: `Failed to get alternative media for ${mediaSource}`,
  513. data: {
  514. mediaSource,
  515. status: "error"
  516. }
  517. });
  518. }
  519. });
  520. console.log("Done!");
  521. this.publishProgress({
  522. status: "finished",
  523. message: `Finished getting alternative media`
  524. });
  525. }
  526. /**
  527. *
  528. * @param {*} payload
  529. * @returns
  530. */
  531. async GET_ALTERNATIVE_MEDIA_SOURCES_FOR_TRACK(payload) {
  532. const { mediaSource, collectAlternativeMediaSourcesOrigins } = payload;
  533. if (!mediaSource || !mediaSource.startsWith("spotify:"))
  534. throw new Error("Media source provided is not a valid Spotify media source.");
  535. const spotifyTrackId = mediaSource.split(":")[1];
  536. const { track: spotifyTrack } = await SpotifyModule.runJob(
  537. "GET_TRACK",
  538. {
  539. identifier: spotifyTrackId,
  540. createMissing: true
  541. },
  542. this
  543. );
  544. const ISRC = spotifyTrack.externalIds.isrc;
  545. if (!ISRC) throw new Error(`ISRC not found for Spotify track ${mediaSource}.`);
  546. const mediaSources = new Set();
  547. const mediaSourcesOrigins = {};
  548. const jobsToRun = [];
  549. try {
  550. const ISRCApiResponse = await MusicBrainzModule.runJob(
  551. "API_CALL",
  552. {
  553. url: `https://musicbrainz.org/ws/2/isrc/${ISRC}`,
  554. params: {
  555. fmt: "json",
  556. inc: "url-rels+work-rels"
  557. }
  558. },
  559. this
  560. );
  561. // console.log("ISRCApiResponse");
  562. // console.dir(ISRCApiResponse, { depth: 5 });
  563. ISRCApiResponse.recordings.forEach(recording => {
  564. recording.relations.forEach(relation => {
  565. if (relation["target-type"] === "url" && relation.url) {
  566. // relation["type-id"] === "7e41ef12-a124-4324-afdb-fdbae687a89c"
  567. const { resource } = relation.url;
  568. if (resource.indexOf("soundcloud.com") !== -1) {
  569. // throw new Error(`Unable to parse SoundCloud resource ${resource}.`);
  570. const promise = new Promise(resolve => {
  571. SoundcloudModule.runJob(
  572. "GET_TRACK_FROM_URL",
  573. { identifier: resource, createMissing: true },
  574. this
  575. )
  576. .then(response => {
  577. const { trackId } = response.track;
  578. const mediaSource = `soundcloud:${trackId}`;
  579. mediaSources.add(mediaSource);
  580. if (collectAlternativeMediaSourcesOrigins) {
  581. const mediaSourceOrigins = [
  582. `Spotify track ${spotifyTrackId}`,
  583. `ISRC ${ISRC}`,
  584. `MusicBrainz recordings`,
  585. `MusicBrainz recording ${recording.id}`,
  586. `MusicBrainz relations`,
  587. `MusicBrainz relation target-type url`,
  588. `MusicBrainz relation resource ${resource}`,
  589. `SoundCloud ID ${trackId}`
  590. ];
  591. if (!mediaSourcesOrigins[mediaSource])
  592. mediaSourcesOrigins[mediaSource] = [];
  593. mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  594. }
  595. resolve();
  596. })
  597. .catch(() => {
  598. resolve();
  599. });
  600. });
  601. jobsToRun.push(promise);
  602. return;
  603. }
  604. if (resource.indexOf("youtube.com") !== -1 || resource.indexOf("youtu.be") !== -1) {
  605. const match = youtubeVideoUrlRegex.exec(resource);
  606. if (!match) throw new Error(`Unable to parse YouTube resource ${resource}.`);
  607. const { youtubeId } = match.groups;
  608. if (!youtubeId) throw new Error(`Unable to parse YouTube resource ${resource}.`);
  609. const mediaSource = `youtube:${youtubeId}`;
  610. mediaSources.add(mediaSource);
  611. if (collectAlternativeMediaSourcesOrigins) {
  612. const mediaSourceOrigins = [
  613. `Spotify track ${spotifyTrackId}`,
  614. `ISRC ${ISRC}`,
  615. `MusicBrainz recordings`,
  616. `MusicBrainz recording ${recording.id}`,
  617. `MusicBrainz relations`,
  618. `MusicBrainz relation target-type url`,
  619. `MusicBrainz relation resource ${resource}`,
  620. `YouTube ID ${youtubeId}`
  621. ];
  622. if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  623. mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  624. }
  625. return;
  626. }
  627. return;
  628. }
  629. if (relation["target-type"] === "work") {
  630. const promise = new Promise(resolve => {
  631. WikiDataModule.runJob(
  632. "API_GET_DATA_FROM_MUSICBRAINZ_WORK",
  633. { workId: relation.work.id },
  634. this
  635. )
  636. .then(resultBody => {
  637. const youtubeIds = Array.from(
  638. new Set(
  639. resultBody.results.bindings
  640. .filter(binding => !!binding.YouTube_video_ID)
  641. .map(binding => binding.YouTube_video_ID.value)
  642. )
  643. );
  644. // const soundcloudIds = Array.from(
  645. // new Set(
  646. // resultBody.results.bindings
  647. // .filter(binding => !!binding["SoundCloud_track_ID"])
  648. // .map(binding => binding["SoundCloud_track_ID"].value)
  649. // )
  650. // );
  651. const musicVideoEntityUrls = Array.from(
  652. new Set(
  653. resultBody.results.bindings
  654. .filter(binding => !!binding.Music_video_entity_URL)
  655. .map(binding => binding.Music_video_entity_URL.value)
  656. )
  657. );
  658. youtubeIds.forEach(youtubeId => {
  659. const mediaSource = `youtube:${youtubeId}`;
  660. mediaSources.add(mediaSource);
  661. if (collectAlternativeMediaSourcesOrigins) {
  662. const mediaSourceOrigins = [
  663. `Spotify track ${spotifyTrackId}`,
  664. `ISRC ${ISRC}`,
  665. `MusicBrainz recordings`,
  666. `MusicBrainz recording ${recording.id}`,
  667. `MusicBrainz relations`,
  668. `MusicBrainz relation target-type work`,
  669. `MusicBrainz relation work id ${relation.work.id}`,
  670. `WikiData select from MusicBrainz work id ${relation.work.id}`,
  671. `YouTube ID ${youtubeId}`
  672. ];
  673. if (!mediaSourcesOrigins[mediaSource])
  674. mediaSourcesOrigins[mediaSource] = [];
  675. mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  676. }
  677. });
  678. // soundcloudIds.forEach(soundcloudId => {
  679. // const mediaSource = `soundcloud:${soundcloudId}`;
  680. // mediaSources.add(mediaSource);
  681. // if (collectAlternativeMediaSourcesOrigins) {
  682. // const mediaSourceOrigins = [
  683. // `Spotify track ${spotifyTrackId}`,
  684. // `ISRC ${ISRC}`,
  685. // `MusicBrainz recordings`,
  686. // `MusicBrainz recording ${recording.id}`,
  687. // `MusicBrainz relations`,
  688. // `MusicBrainz relation target-type work`,
  689. // `MusicBrainz relation work id ${relation.work.id}`,
  690. // `WikiData select from MusicBrainz work id ${relation.work.id}`,
  691. // `SoundCloud ID ${soundcloudId}`
  692. // ];
  693. // if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  694. // mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  695. // }
  696. // });
  697. const promisesToRun2 = [];
  698. musicVideoEntityUrls.forEach(musicVideoEntityUrl => {
  699. promisesToRun2.push(
  700. new Promise(resolve => {
  701. WikiDataModule.runJob(
  702. "API_GET_DATA_FROM_ENTITY_URL",
  703. { entityUrl: musicVideoEntityUrl },
  704. this
  705. ).then(resultBody => {
  706. const youtubeIds = Array.from(
  707. new Set(
  708. resultBody.results.bindings
  709. .filter(binding => !!binding.YouTube_video_ID)
  710. .map(binding => binding.YouTube_video_ID.value)
  711. )
  712. );
  713. // const soundcloudIds = Array.from(
  714. // new Set(
  715. // resultBody.results.bindings
  716. // .filter(binding => !!binding["SoundCloud_track_ID"])
  717. // .map(binding => binding["SoundCloud_track_ID"].value)
  718. // )
  719. // );
  720. youtubeIds.forEach(youtubeId => {
  721. const mediaSource = `youtube:${youtubeId}`;
  722. mediaSources.add(mediaSource);
  723. // if (collectAlternativeMediaSourcesOrigins) {
  724. // const mediaSourceOrigins = [
  725. // `Spotify track ${spotifyTrackId}`,
  726. // `ISRC ${ISRC}`,
  727. // `MusicBrainz recordings`,
  728. // `MusicBrainz recording ${recording.id}`,
  729. // `MusicBrainz relations`,
  730. // `MusicBrainz relation target-type work`,
  731. // `MusicBrainz relation work id ${relation.work.id}`,
  732. // `WikiData select from MusicBrainz work id ${relation.work.id}`,
  733. // `YouTube ID ${youtubeId}`
  734. // ];
  735. // if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  736. // mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  737. // }
  738. });
  739. // soundcloudIds.forEach(soundcloudId => {
  740. // const mediaSource = `soundcloud:${soundcloudId}`;
  741. // mediaSources.add(mediaSource);
  742. // // if (collectAlternativeMediaSourcesOrigins) {
  743. // // const mediaSourceOrigins = [
  744. // // `Spotify track ${spotifyTrackId}`,
  745. // // `ISRC ${ISRC}`,
  746. // // `MusicBrainz recordings`,
  747. // // `MusicBrainz recording ${recording.id}`,
  748. // // `MusicBrainz relations`,
  749. // // `MusicBrainz relation target-type work`,
  750. // // `MusicBrainz relation work id ${relation.work.id}`,
  751. // // `WikiData select from MusicBrainz work id ${relation.work.id}`,
  752. // // `SoundCloud ID ${soundcloudId}`
  753. // // ];
  754. // // if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  755. // // mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  756. // // }
  757. // });
  758. resolve();
  759. });
  760. })
  761. );
  762. });
  763. Promise.allSettled(promisesToRun2).then(resolve);
  764. })
  765. .catch(err => {
  766. console.log("KRISWORKERR", err);
  767. resolve();
  768. });
  769. });
  770. jobsToRun.push(promise);
  771. //WikiDataModule.runJob("API_GET_DATA_FROM_MUSICBRAINZ_WORK", { workId: relation.work.id }, this));
  772. return;
  773. }
  774. });
  775. });
  776. } catch (err) {
  777. console.log("Error during initial ISRC getting/parsing", err);
  778. }
  779. try {
  780. const RecordingApiResponse = await MusicBrainzModule.runJob(
  781. "API_CALL",
  782. {
  783. url: `https://musicbrainz.org/ws/2/recording/`,
  784. params: {
  785. fmt: "json",
  786. query: `isrc:${ISRC}`
  787. }
  788. },
  789. this
  790. );
  791. const releaseIds = new Set();
  792. const releaseGroupIds = new Set();
  793. RecordingApiResponse.recordings.forEach(recording => {
  794. const recordingId = recording.id;
  795. // console.log("Recording:", recording.id);
  796. recording.releases.forEach(release => {
  797. const releaseId = release.id;
  798. // console.log("Release:", releaseId);
  799. const releaseGroupId = release["release-group"].id;
  800. // console.log("Release group:", release["release-group"]);
  801. // console.log("Release group id:", release["release-group"].id);
  802. // console.log("Release group type id:", release["release-group"]["type-id"]);
  803. // console.log("Release group primary type id:", release["release-group"]["primary-type-id"]);
  804. // console.log("Release group primary type:", release["release-group"]["primary-type"]);
  805. // d6038452-8ee0-3f68-affc-2de9a1ede0b9 = single
  806. // 6d0c5bf6-7a33-3420-a519-44fc63eedebf = EP
  807. if (
  808. release["release-group"]["type-id"] === "d6038452-8ee0-3f68-affc-2de9a1ede0b9" ||
  809. release["release-group"]["type-id"] === "6d0c5bf6-7a33-3420-a519-44fc63eedebf"
  810. ) {
  811. releaseIds.add(releaseId);
  812. releaseGroupIds.add(releaseGroupId);
  813. }
  814. });
  815. });
  816. Array.from(releaseGroupIds).forEach(releaseGroupId => {
  817. const promise = new Promise(resolve => {
  818. WikiDataModule.runJob("API_GET_DATA_FROM_MUSICBRAINZ_RELEASE_GROUP", { releaseGroupId }, this)
  819. .then(resultBody => {
  820. const youtubeIds = Array.from(
  821. new Set(
  822. resultBody.results.bindings
  823. .filter(binding => !!binding.YouTube_video_ID)
  824. .map(binding => binding.YouTube_video_ID.value)
  825. )
  826. );
  827. // const soundcloudIds = Array.from(
  828. // new Set(
  829. // resultBody.results.bindings
  830. // .filter(binding => !!binding["SoundCloud_track_ID"])
  831. // .map(binding => binding["SoundCloud_track_ID"].value)
  832. // )
  833. // );
  834. const musicVideoEntityUrls = Array.from(
  835. new Set(
  836. resultBody.results.bindings
  837. .filter(binding => !!binding.Music_video_entity_URL)
  838. .map(binding => binding.Music_video_entity_URL.value)
  839. )
  840. );
  841. youtubeIds.forEach(youtubeId => {
  842. const mediaSource = `youtube:${youtubeId}`;
  843. mediaSources.add(mediaSource);
  844. // if (collectAlternativeMediaSourcesOrigins) {
  845. // const mediaSourceOrigins = [
  846. // `Spotify track ${spotifyTrackId}`,
  847. // `ISRC ${ISRC}`,
  848. // `MusicBrainz recordings`,
  849. // `MusicBrainz recording ${recording.id}`,
  850. // `MusicBrainz relations`,
  851. // `MusicBrainz relation target-type work`,
  852. // `MusicBrainz relation work id ${relation.work.id}`,
  853. // `WikiData select from MusicBrainz work id ${relation.work.id}`,
  854. // `YouTube ID ${youtubeId}`
  855. // ];
  856. // if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  857. // mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  858. // }
  859. });
  860. // soundcloudIds.forEach(soundcloudId => {
  861. // const mediaSource = `soundcloud:${soundcloudId}`;
  862. // mediaSources.add(mediaSource);
  863. // // if (collectAlternativeMediaSourcesOrigins) {
  864. // // const mediaSourceOrigins = [
  865. // // `Spotify track ${spotifyTrackId}`,
  866. // // `ISRC ${ISRC}`,
  867. // // `MusicBrainz recordings`,
  868. // // `MusicBrainz recording ${recording.id}`,
  869. // // `MusicBrainz relations`,
  870. // // `MusicBrainz relation target-type work`,
  871. // // `MusicBrainz relation work id ${relation.work.id}`,
  872. // // `WikiData select from MusicBrainz work id ${relation.work.id}`,
  873. // // `SoundCloud ID ${soundcloudId}`
  874. // // ];
  875. // // if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  876. // // mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  877. // // }
  878. // });
  879. const promisesToRun2 = [];
  880. musicVideoEntityUrls.forEach(musicVideoEntityUrl => {
  881. promisesToRun2.push(
  882. new Promise(resolve => {
  883. WikiDataModule.runJob(
  884. "API_GET_DATA_FROM_ENTITY_URL",
  885. { entityUrl: musicVideoEntityUrl },
  886. this
  887. ).then(resultBody => {
  888. const youtubeIds = Array.from(
  889. new Set(
  890. resultBody.results.bindings
  891. .filter(binding => !!binding.YouTube_video_ID)
  892. .map(binding => binding.YouTube_video_ID.value)
  893. )
  894. );
  895. // const soundcloudIds = Array.from(
  896. // new Set(
  897. // resultBody.results.bindings
  898. // .filter(binding => !!binding["SoundCloud_track_ID"])
  899. // .map(binding => binding["SoundCloud_track_ID"].value)
  900. // )
  901. // );
  902. youtubeIds.forEach(youtubeId => {
  903. const mediaSource = `youtube:${youtubeId}`;
  904. mediaSources.add(mediaSource);
  905. // if (collectAlternativeMediaSourcesOrigins) {
  906. // const mediaSourceOrigins = [
  907. // `Spotify track ${spotifyTrackId}`,
  908. // `ISRC ${ISRC}`,
  909. // `MusicBrainz recordings`,
  910. // `MusicBrainz recording ${recording.id}`,
  911. // `MusicBrainz relations`,
  912. // `MusicBrainz relation target-type work`,
  913. // `MusicBrainz relation work id ${relation.work.id}`,
  914. // `WikiData select from MusicBrainz work id ${relation.work.id}`,
  915. // `YouTube ID ${youtubeId}`
  916. // ];
  917. // if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  918. // mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  919. // }
  920. });
  921. // soundcloudIds.forEach(soundcloudId => {
  922. // const mediaSource = `soundcloud:${soundcloudId}`;
  923. // mediaSources.add(mediaSource);
  924. // // if (collectAlternativeMediaSourcesOrigins) {
  925. // // const mediaSourceOrigins = [
  926. // // `Spotify track ${spotifyTrackId}`,
  927. // // `ISRC ${ISRC}`,
  928. // // `MusicBrainz recordings`,
  929. // // `MusicBrainz recording ${recording.id}`,
  930. // // `MusicBrainz relations`,
  931. // // `MusicBrainz relation target-type work`,
  932. // // `MusicBrainz relation work id ${relation.work.id}`,
  933. // // `WikiData select from MusicBrainz work id ${relation.work.id}`,
  934. // // `SoundCloud ID ${soundcloudId}`
  935. // // ];
  936. // // if (!mediaSourcesOrigins[mediaSource]) mediaSourcesOrigins[mediaSource] = [];
  937. // // mediaSourcesOrigins[mediaSource].push(mediaSourceOrigins);
  938. // // }
  939. // });
  940. resolve();
  941. });
  942. })
  943. );
  944. });
  945. Promise.allSettled(promisesToRun2).then(resolve);
  946. })
  947. .catch(err => {
  948. console.log("KRISWORKERR", err);
  949. resolve();
  950. });
  951. });
  952. jobsToRun.push(promise);
  953. });
  954. } catch (err) {
  955. console.log("Error during getting releases from ISRC", err);
  956. }
  957. // console.log("RecordingApiResponse");
  958. // console.dir(RecordingApiResponse, { depth: 10 });
  959. // console.dir(RecordingApiResponse.recordings[0].releases[0], { depth: 10 });
  960. await Promise.allSettled(jobsToRun);
  961. return {
  962. mediaSources: Array.from(mediaSources),
  963. mediaSourcesOrigins
  964. };
  965. }
  966. }
  967. export default new _SpotifyModule();