songs.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. import async from "async";
  2. import config from "config";
  3. import mongoose from "mongoose";
  4. import CoreClass from "../core";
  5. let SongsModule;
  6. let CacheModule;
  7. let DBModule;
  8. let UtilsModule;
  9. let YouTubeModule;
  10. let StationsModule;
  11. let PlaylistsModule;
  12. class _SongsModule extends CoreClass {
  13. // eslint-disable-next-line require-jsdoc
  14. constructor() {
  15. super("songs");
  16. SongsModule = this;
  17. }
  18. /**
  19. * Initialises the songs module
  20. *
  21. * @returns {Promise} - returns promise (reject, resolve)
  22. */
  23. async initialize() {
  24. this.setStage(1);
  25. CacheModule = this.moduleManager.modules.cache;
  26. DBModule = this.moduleManager.modules.db;
  27. UtilsModule = this.moduleManager.modules.utils;
  28. YouTubeModule = this.moduleManager.modules.youtube;
  29. StationsModule = this.moduleManager.modules.stations;
  30. PlaylistsModule = this.moduleManager.modules.playlists;
  31. this.SongModel = await DBModule.runJob("GET_MODEL", { modelName: "song" });
  32. this.SongSchemaCache = await CacheModule.runJob("GET_SCHEMA", { schemaName: "song" });
  33. this.setStage(2);
  34. return new Promise((resolve, reject) =>
  35. async.waterfall(
  36. [
  37. next => {
  38. this.setStage(2);
  39. CacheModule.runJob("HGETALL", { table: "songs" })
  40. .then(songs => {
  41. next(null, songs);
  42. })
  43. .catch(next);
  44. },
  45. (songs, next) => {
  46. this.setStage(3);
  47. if (!songs) return next();
  48. const songIds = Object.keys(songs);
  49. return async.each(
  50. songIds,
  51. (songId, next) => {
  52. SongsModule.SongModel.findOne({ songId }, (err, song) => {
  53. if (err) next(err);
  54. else if (!song)
  55. CacheModule.runJob("HDEL", {
  56. table: "songs",
  57. key: songId
  58. })
  59. .then(() => next())
  60. .catch(next);
  61. else next();
  62. });
  63. },
  64. next
  65. );
  66. },
  67. next => {
  68. this.setStage(4);
  69. SongsModule.SongModel.find({}, next);
  70. },
  71. (songs, next) => {
  72. this.setStage(5);
  73. async.each(
  74. songs,
  75. (song, next) => {
  76. CacheModule.runJob("HSET", {
  77. table: "songs",
  78. key: song.songId,
  79. value: SongsModule.SongSchemaCache(song)
  80. })
  81. .then(() => next())
  82. .catch(next);
  83. },
  84. next
  85. );
  86. }
  87. ],
  88. async err => {
  89. if (err) {
  90. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  91. reject(new Error(err));
  92. } else resolve();
  93. }
  94. )
  95. );
  96. }
  97. /**
  98. * Gets a song by id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  99. *
  100. * @param {object} payload - object containing the payload
  101. * @param {string} payload.id - the id of the song we are trying to get
  102. * @returns {Promise} - returns a promise (resolve, reject)
  103. */
  104. GET_SONG(payload) {
  105. return new Promise((resolve, reject) =>
  106. async.waterfall(
  107. [
  108. next => {
  109. if (!mongoose.Types.ObjectId.isValid(payload.id)) return next("Id is not a valid ObjectId.");
  110. return CacheModule.runJob("HGET", { table: "songs", key: payload.id }, this)
  111. .then(song => next(null, song))
  112. .catch(next);
  113. },
  114. (song, next) => {
  115. if (song) return next(true, song);
  116. return SongsModule.SongModel.findOne({ _id: payload.id }, next);
  117. },
  118. (song, next) => {
  119. if (song) {
  120. CacheModule.runJob(
  121. "HSET",
  122. {
  123. table: "songs",
  124. key: payload.id,
  125. value: song
  126. },
  127. this
  128. ).then(song => next(null, song));
  129. } else next("Song not found.");
  130. }
  131. ],
  132. (err, song) => {
  133. if (err && err !== true) return reject(new Error(err));
  134. return resolve({ song });
  135. }
  136. )
  137. );
  138. }
  139. /**
  140. * Makes sure that if a song is not currently in the songs db, to add it
  141. *
  142. * @param {object} payload - an object containing the payload
  143. * @param {string} payload.songId - the youtube song id of the song we are trying to ensure is in the songs db
  144. * @param {string} payload.userId - the youtube song id of the song we are trying to ensure is in the songs db
  145. * @param {string} payload.automaticallyRequested - whether the song was automatically requested or not
  146. * @returns {Promise} - returns a promise (resolve, reject)
  147. */
  148. ENSURE_SONG_EXISTS_BY_SONG_ID(payload) {
  149. return new Promise((resolve, reject) =>
  150. async.waterfall(
  151. [
  152. next => {
  153. SongsModule.SongModel.findOne({ songId: payload.songId }, next);
  154. },
  155. (song, next) => {
  156. if (song && song.duration > 0) next(true, song);
  157. else {
  158. YouTubeModule.runJob("GET_SONG", { songId: payload.songId }, this)
  159. .then(response => {
  160. next(null, song, response.song);
  161. })
  162. .catch(next);
  163. }
  164. // else if (song && song.duration <= 0) {
  165. // YouTubeModule.runJob("GET_SONG", { songId: payload.songId }, this)
  166. // .then(response => next(null, { ...response.song }, false))
  167. // .catch(next);
  168. // } else {
  169. // YouTubeModule.runJob("GET_SONG", { songId: payload.songId }, this)
  170. // .then(response => next(null, { ...response.song }, false))
  171. // .catch(next);
  172. // }
  173. },
  174. (song, youtubeSong, next) => {
  175. if (song && song.duration <= 0) {
  176. song.duration = youtubeSong.duration;
  177. song.save({ validateBeforeSave: true }, err => {
  178. if (err) return next(err, song);
  179. return next(null, song);
  180. });
  181. } else {
  182. const status =
  183. (!payload.userId && config.get("hideAnonymousSongs")) ||
  184. (payload.automaticallyRequested && config.get("hideAutomaticallyRequestedSongs"))
  185. ? "hidden"
  186. : "unverified";
  187. const song = new SongsModule.SongModel({
  188. ...youtubeSong,
  189. status,
  190. requestedBy: payload.userId,
  191. requestedAt: Date.now()
  192. });
  193. song.save({ validateBeforeSave: true }, err => {
  194. if (err) return next(err, song);
  195. return next(null, song);
  196. });
  197. }
  198. }
  199. ],
  200. (err, song) => {
  201. if (err && err !== true) return reject(new Error(err));
  202. return resolve({ song });
  203. }
  204. )
  205. );
  206. }
  207. /**
  208. * Gets a song by song id from the cache or Mongo, and if it isn't in the cache yet, adds it the cache
  209. *
  210. * @param {object} payload - an object containing the payload
  211. * @param {string} payload.songId - the mongo id of the song we are trying to get
  212. * @returns {Promise} - returns a promise (resolve, reject)
  213. */
  214. GET_SONG_FROM_ID(payload) {
  215. return new Promise((resolve, reject) =>
  216. async.waterfall(
  217. [
  218. next => {
  219. SongsModule.SongModel.findOne({ songId: payload.songId }, next);
  220. }
  221. ],
  222. (err, song) => {
  223. if (err && err !== true) return reject(new Error(err));
  224. return resolve({ song });
  225. }
  226. )
  227. );
  228. }
  229. /**
  230. * Gets a song from id from Mongo and updates the cache with it
  231. *
  232. * @param {object} payload - an object containing the payload
  233. * @param {string} payload.songId - the id of the song we are trying to update
  234. * @returns {Promise} - returns a promise (resolve, reject)
  235. */
  236. UPDATE_SONG(payload) {
  237. return new Promise((resolve, reject) =>
  238. async.waterfall(
  239. [
  240. next => {
  241. SongsModule.SongModel.findOne({ _id: payload.songId }, next);
  242. },
  243. (song, next) => {
  244. if (!song) {
  245. CacheModule.runJob("HDEL", {
  246. table: "songs",
  247. key: payload.songId
  248. });
  249. return next("Song not found.");
  250. }
  251. return CacheModule.runJob(
  252. "HSET",
  253. {
  254. table: "songs",
  255. key: payload.songId,
  256. value: song
  257. },
  258. this
  259. )
  260. .then(song => {
  261. next(null, song);
  262. })
  263. .catch(next);
  264. },
  265. (song, next) => {
  266. next(null, song);
  267. const { _id, songId, title, artists, thumbnail, duration, status } = song;
  268. const trimmedSong = {
  269. _id,
  270. songId,
  271. title,
  272. artists,
  273. thumbnail,
  274. duration,
  275. status
  276. };
  277. this.log("INFO", `Going to update playlists and stations now for song ${_id}`);
  278. DBModule.runJob("GET_MODEL", { modelName: "playlist" }).then(playlistModel => {
  279. playlistModel.updateMany(
  280. { "songs._id": song._id },
  281. { $set: { "songs.$": trimmedSong } },
  282. err => {
  283. if (err) this.log("ERROR", err);
  284. else
  285. playlistModel.find({ "songs._id": song._id }, (err, playlists) => {
  286. playlists.forEach(playlist => {
  287. PlaylistsModule.runJob("UPDATE_PLAYLIST", {
  288. playlistId: playlist._id
  289. });
  290. });
  291. });
  292. }
  293. );
  294. });
  295. DBModule.runJob("GET_MODEL", { modelName: "station" }).then(stationModel => {
  296. stationModel.updateMany(
  297. { "queue._id": song._id },
  298. {
  299. $set: {
  300. "queue.$.songId": songId,
  301. "queue.$.title": title,
  302. "queue.$.artists": artists,
  303. "queue.$.thumbnail": thumbnail,
  304. "queue.$.duration": duration,
  305. "queue.$.status": status
  306. }
  307. },
  308. err => {
  309. if (err) this.log("ERROR", err);
  310. else
  311. stationModel.find({ "queue._id": song._id }, (err, stations) => {
  312. stations.forEach(station => {
  313. StationsModule.runJob("UPDATE_STATION", { stationId: station._id });
  314. });
  315. });
  316. }
  317. );
  318. });
  319. },
  320. (song, next) => {
  321. async.eachLimit(
  322. song.genres,
  323. 1,
  324. (genre, next) => {
  325. PlaylistsModule.runJob("AUTOFILL_GENRE_PLAYLIST", { genre }, this)
  326. .then(() => {
  327. next();
  328. })
  329. .catch(err => next(err));
  330. },
  331. err => {
  332. next(err, song);
  333. }
  334. );
  335. }
  336. ],
  337. (err, song) => {
  338. if (err && err !== true) return reject(new Error(err));
  339. return resolve(song);
  340. }
  341. )
  342. );
  343. }
  344. /**
  345. * Deletes song from id from Mongo and cache
  346. *
  347. * @param {object} payload - returns an object containing the payload
  348. * @param {string} payload.songId - the id of the song we are trying to delete
  349. * @returns {Promise} - returns a promise (resolve, reject)
  350. */
  351. DELETE_SONG(payload) {
  352. return new Promise((resolve, reject) =>
  353. async.waterfall(
  354. [
  355. next => {
  356. SongsModule.SongModel.deleteOne({ songId: payload.songId }, next);
  357. },
  358. next => {
  359. CacheModule.runJob(
  360. "HDEL",
  361. {
  362. table: "songs",
  363. key: payload.songId
  364. },
  365. this
  366. )
  367. .then(() => next())
  368. .catch(next);
  369. }
  370. ],
  371. err => {
  372. if (err && err !== true) return reject(new Error(err));
  373. return resolve();
  374. }
  375. )
  376. );
  377. }
  378. /**
  379. * Recalculates dislikes and likes for a song
  380. *
  381. * @param {object} payload - returns an object containing the payload
  382. * @param {string} payload.musareSongId - the (musare) id of the song
  383. * @param {string} payload.songId - the (mongodb) id of the song
  384. * @returns {Promise} - returns a promise (resolve, reject)
  385. */
  386. async RECALCULATE_SONG_RATINGS(payload) {
  387. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  388. return new Promise((resolve, reject) => {
  389. async.waterfall(
  390. [
  391. next => {
  392. playlistModel.countDocuments(
  393. { songs: { $elemMatch: { songId: payload.musareSongId } }, displayName: "Liked Songs" },
  394. (err, likes) => {
  395. if (err) return next(err);
  396. return next(null, likes);
  397. }
  398. );
  399. },
  400. (likes, next) => {
  401. playlistModel.countDocuments(
  402. { songs: { $elemMatch: { songId: payload.musareSongId } }, displayName: "Disliked Songs" },
  403. (err, dislikes) => {
  404. if (err) return next(err);
  405. return next(err, { likes, dislikes });
  406. }
  407. );
  408. },
  409. ({ likes, dislikes }, next) => {
  410. SongsModule.SongModel.updateOne(
  411. { _id: payload.songId },
  412. {
  413. $set: {
  414. likes,
  415. dislikes
  416. }
  417. },
  418. err => next(err, { likes, dislikes })
  419. );
  420. }
  421. ],
  422. (err, { likes, dislikes }) => {
  423. if (err) return reject(new Error(err));
  424. return resolve({ likes, dislikes });
  425. }
  426. );
  427. });
  428. }
  429. /**
  430. * Gets an array of all genres
  431. *
  432. * @returns {Promise} - returns a promise (resolve, reject)
  433. */
  434. GET_ALL_GENRES() {
  435. return new Promise((resolve, reject) =>
  436. async.waterfall(
  437. [
  438. next => {
  439. SongsModule.SongModel.find({ status: "verified" }, { genres: 1, _id: false }, next);
  440. },
  441. (songs, next) => {
  442. let allGenres = [];
  443. songs.forEach(song => {
  444. allGenres = allGenres.concat(song.genres);
  445. });
  446. const lowerCaseGenres = allGenres.map(genre => genre.toLowerCase());
  447. const uniqueGenres = lowerCaseGenres.filter(
  448. (value, index, self) => self.indexOf(value) === index
  449. );
  450. next(null, uniqueGenres);
  451. }
  452. ],
  453. (err, genres) => {
  454. if (err && err !== true) return reject(new Error(err));
  455. return resolve({ genres });
  456. }
  457. )
  458. );
  459. }
  460. /**
  461. * Gets an array of all songs with a specific genre
  462. *
  463. * @param {object} payload - returns an object containing the payload
  464. * @param {string} payload.genre - the genre
  465. * @returns {Promise} - returns a promise (resolve, reject)
  466. */
  467. GET_ALL_SONGS_WITH_GENRE(payload) {
  468. return new Promise((resolve, reject) =>
  469. async.waterfall(
  470. [
  471. next => {
  472. SongsModule.SongModel.find(
  473. {
  474. status: "verified",
  475. genres: { $regex: new RegExp(`^${payload.genre.toLowerCase()}$`, "i") }
  476. },
  477. next
  478. );
  479. }
  480. ],
  481. (err, songs) => {
  482. if (err && err !== true) return reject(new Error(err));
  483. return resolve({ songs });
  484. }
  485. )
  486. );
  487. }
  488. // runjob songs GET_ORPHANED_PLAYLIST_SONGS {}
  489. /**
  490. * Gets a orphaned playlist songs
  491. *
  492. * @returns {Promise} - returns promise (reject, resolve)
  493. */
  494. GET_ORPHANED_PLAYLIST_SONGS() {
  495. return new Promise((resolve, reject) => {
  496. DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this).then(playlistModel => {
  497. playlistModel.find({}, (err, playlists) => {
  498. if (err) reject(new Error(err));
  499. else {
  500. SongsModule.SongModel.find({}, { _id: true, songId: true }, (err, songs) => {
  501. if (err) reject(new Error(err));
  502. else {
  503. const musareSongIds = songs.map(song => song._id.toString());
  504. const orphanedSongIds = new Set();
  505. async.eachLimit(
  506. playlists,
  507. 1,
  508. (playlist, next) => {
  509. playlist.songs.forEach(song => {
  510. if (
  511. (!song._id || musareSongIds.indexOf(song._id.toString() === -1)) &&
  512. !orphanedSongIds.has(song.songId)
  513. ) {
  514. orphanedSongIds.add(song.songId);
  515. }
  516. });
  517. next();
  518. },
  519. () => {
  520. resolve({ songIds: Array.from(orphanedSongIds) });
  521. }
  522. );
  523. }
  524. });
  525. }
  526. });
  527. });
  528. });
  529. }
  530. /**
  531. * Requests a song, adding it to the DB
  532. *
  533. * @param {object} payload - The payload
  534. * @param {string} payload.songId - The YouTube song id of the song
  535. * @param {string} payload.userId - The user id of the person requesting the song
  536. * @returns {Promise} - returns promise (reject, resolve)
  537. */
  538. REQUEST_SONG(payload) {
  539. return new Promise((resolve, reject) => {
  540. const { songId, userId } = payload;
  541. const requestedAt = Date.now();
  542. async.waterfall(
  543. [
  544. next => {
  545. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  546. .then(UserModel => {
  547. UserModel.findOne({ _id: userId }, { "preferences.anonymousSongRequests": 1 }, next);
  548. })
  549. .catch(next);
  550. },
  551. (user, next) => {
  552. SongsModule.SongModel.findOne({ songId }, (err, song) => next(err, user, song));
  553. },
  554. // Get YouTube data from id
  555. (user, song, next) => {
  556. if (song) return next("This song is already in the database.");
  557. // TODO Add err object as first param of callback
  558. const requestedBy = user.preferences.anonymousSongRequests ? null : userId;
  559. const status = !requestedBy && config.get("hideAnonymousSongs") ? "hidden" : "unverified";
  560. return YouTubeModule.runJob("GET_SONG", { songId }, this)
  561. .then(response => {
  562. const { song } = response;
  563. song.artists = [];
  564. song.genres = [];
  565. song.skipDuration = 0;
  566. song.explicit = false;
  567. song.requestedBy = user.preferences.anonymousSongRequests ? null : userId;
  568. song.requestedAt = requestedAt;
  569. song.status = status;
  570. next(null, song);
  571. })
  572. .catch(next);
  573. },
  574. (newSong, next) => {
  575. const song = new SongsModule.SongModel(newSong);
  576. song.save({ validateBeforeSave: false }, err => {
  577. if (err) return next(err, song);
  578. return next(null, song);
  579. });
  580. },
  581. (song, next) => {
  582. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  583. .then(UserModel => {
  584. UserModel.findOne({ _id: userId }, (err, user) => {
  585. if (err) return next(err);
  586. if (!user) return next(null, song);
  587. user.statistics.songsRequested += 1;
  588. return user.save(err => {
  589. if (err) return next(err);
  590. return next(null, song);
  591. });
  592. });
  593. })
  594. .catch(next);
  595. }
  596. ],
  597. async (err, song) => {
  598. if (err) reject(err);
  599. SongsModule.runJob("UPDATE_SONG", { songId: song._id });
  600. CacheModule.runJob("PUB", {
  601. channel: "song.newUnverifiedSong",
  602. value: song._id
  603. });
  604. resolve();
  605. }
  606. );
  607. });
  608. }
  609. /**
  610. * Hides a song
  611. *
  612. * @param {object} payload - The payload
  613. * @param {string} payload.songId - The Musare song id of the song
  614. * @returns {Promise} - returns promise (reject, resolve)
  615. */
  616. HIDE_SONG(payload) {
  617. return new Promise((resolve, reject) => {
  618. const { songId } = payload;
  619. async.waterfall(
  620. [
  621. next => {
  622. SongsModule.SongModel.findOne({ _id: songId }, next);
  623. },
  624. // Get YouTube data from id
  625. (song, next) => {
  626. if (!song) return next("This song does not exist.");
  627. if (song.status === "hidden") return next("This song is already hidden.");
  628. if (song.status === "verified") return next("Verified songs cannot be hidden.");
  629. // TODO Add err object as first param of callback
  630. return next();
  631. },
  632. next => {
  633. SongsModule.SongModel.updateOne({ _id: songId }, { status: "hidden" }, next);
  634. },
  635. (res, next) => {
  636. SongsModule.runJob("UPDATE_SONG", { songId });
  637. next();
  638. }
  639. ],
  640. async err => {
  641. if (err) reject(err);
  642. CacheModule.runJob("PUB", {
  643. channel: "song.newHiddenSong",
  644. value: songId
  645. });
  646. CacheModule.runJob("PUB", {
  647. channel: "song.removedUnverifiedSong",
  648. value: songId
  649. });
  650. resolve();
  651. }
  652. );
  653. });
  654. }
  655. /**
  656. * Unhides a song
  657. *
  658. * @param {object} payload - The payload
  659. * @param {string} payload.songId - The Musare song id of the song
  660. * @returns {Promise} - returns promise (reject, resolve)
  661. */
  662. UNHIDE_SONG(payload) {
  663. return new Promise((resolve, reject) => {
  664. const { songId } = payload;
  665. async.waterfall(
  666. [
  667. next => {
  668. SongsModule.SongModel.findOne({ _id: songId }, next);
  669. },
  670. // Get YouTube data from id
  671. (song, next) => {
  672. if (!song) return next("This song does not exist.");
  673. if (song.status !== "hidden") return next("This song is not hidden.");
  674. // TODO Add err object as first param of callback
  675. return next();
  676. },
  677. next => {
  678. SongsModule.SongModel.updateOne({ _id: songId }, { status: "unverified" }, next);
  679. },
  680. (res, next) => {
  681. SongsModule.runJob("UPDATE_SONG", { songId });
  682. next();
  683. }
  684. ],
  685. async err => {
  686. if (err) reject(err);
  687. CacheModule.runJob("PUB", {
  688. channel: "song.newUnverifiedSong",
  689. value: songId
  690. });
  691. CacheModule.runJob("PUB", {
  692. channel: "song.removedHiddenSong",
  693. value: songId
  694. });
  695. resolve();
  696. }
  697. );
  698. });
  699. }
  700. // runjob songs REQUEST_ORPHANED_PLAYLIST_SONGS {}
  701. /**
  702. * Requests all orphaned playlist songs, adding them to the database
  703. *
  704. * @returns {Promise} - returns promise (reject, resolve)
  705. */
  706. REQUEST_ORPHANED_PLAYLIST_SONGS() {
  707. return new Promise((resolve, reject) => {
  708. DBModule.runJob("GET_MODEL", { modelName: "playlist" })
  709. .then(playlistModel => {
  710. SongsModule.runJob("GET_ORPHANED_PLAYLIST_SONGS", {}, this).then(response => {
  711. const { songIds } = response;
  712. const playlistsToUpdate = new Set();
  713. async.eachLimit(
  714. songIds,
  715. 1,
  716. (songId, next) => {
  717. async.waterfall(
  718. [
  719. next => {
  720. console.log(
  721. songId,
  722. `this is song ${songIds.indexOf(songId) + 1}/${songIds.length}`
  723. );
  724. setTimeout(next, 150);
  725. },
  726. next => {
  727. SongsModule.runJob(
  728. "ENSURE_SONG_EXISTS_BY_SONG_ID",
  729. { songId, automaticallyRequested: true },
  730. this
  731. )
  732. .then(() => next())
  733. .catch(next);
  734. // SongsModule.runJob("REQUEST_SONG", { songId, userId: null }, this)
  735. // .then(() => {
  736. // next();
  737. // })
  738. // .catch(next);
  739. },
  740. next => {
  741. console.log(444, songId);
  742. SongsModule.SongModel.findOne({ songId }, next);
  743. },
  744. (song, next) => {
  745. const { _id, title, artists, thumbnail, duration, status } = song;
  746. const trimmedSong = {
  747. _id,
  748. songId,
  749. title,
  750. artists,
  751. thumbnail,
  752. duration,
  753. status
  754. };
  755. playlistModel.updateMany(
  756. { "songs.songId": song.songId },
  757. { $set: { "songs.$": trimmedSong } },
  758. err => {
  759. next(err, song);
  760. }
  761. );
  762. },
  763. (song, next) => {
  764. playlistModel.find({ "songs._id": song._id }, next);
  765. },
  766. (playlists, next) => {
  767. playlists.forEach(playlist => {
  768. playlistsToUpdate.add(playlist._id.toString());
  769. });
  770. next();
  771. }
  772. ],
  773. next
  774. );
  775. },
  776. err => {
  777. if (err) reject(err);
  778. else {
  779. async.eachLimit(
  780. Array.from(playlistsToUpdate),
  781. 1,
  782. (playlistId, next) => {
  783. PlaylistsModule.runJob(
  784. "UPDATE_PLAYLIST",
  785. {
  786. playlistId
  787. },
  788. this
  789. )
  790. .then(() => {
  791. next();
  792. })
  793. .catch(next);
  794. },
  795. err => {
  796. if (err) reject(err);
  797. else resolve();
  798. }
  799. );
  800. }
  801. }
  802. );
  803. });
  804. })
  805. .catch(reject);
  806. });
  807. }
  808. }
  809. export default new _SongsModule();