playlists.js 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409
  1. import async from "async";
  2. import { isLoginRequired } from "./hooks";
  3. import moduleManager from "../../index";
  4. const DBModule = moduleManager.modules.db;
  5. const UtilsModule = moduleManager.modules.utils;
  6. const IOModule = moduleManager.modules.io;
  7. const SongsModule = moduleManager.modules.songs;
  8. const CacheModule = moduleManager.modules.cache;
  9. const PlaylistsModule = moduleManager.modules.playlists;
  10. const YouTubeModule = moduleManager.modules.youtube;
  11. const ActivitiesModule = moduleManager.modules.activities;
  12. CacheModule.runJob("SUB", {
  13. channel: "playlist.create",
  14. cb: playlist => {
  15. IOModule.runJob("SOCKETS_FROM_USER", { userId: playlist.createdBy }, this).then(response => {
  16. response.sockets.forEach(socket => {
  17. socket.emit("event:playlist.create", playlist);
  18. });
  19. });
  20. if (playlist.privacy === "public")
  21. IOModule.runJob("EMIT_TO_ROOM", {
  22. room: `profile-${playlist.createdBy}`,
  23. args: ["event:playlist.create", playlist]
  24. });
  25. }
  26. });
  27. CacheModule.runJob("SUB", {
  28. channel: "playlist.delete",
  29. cb: res => {
  30. IOModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(response => {
  31. response.sockets.forEach(socket => {
  32. socket.emit("event:playlist.delete", res.playlistId);
  33. });
  34. });
  35. IOModule.runJob("EMIT_TO_ROOM", {
  36. room: `profile-${res.userId}`,
  37. args: ["event:playlist.delete", res.playlistId]
  38. });
  39. }
  40. });
  41. CacheModule.runJob("SUB", {
  42. channel: "playlist.repositionSongs",
  43. cb: res => {
  44. IOModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(response =>
  45. response.sockets.forEach(socket =>
  46. socket.emit("event:playlist.repositionSongs", {
  47. playlistId: res.playlistId,
  48. songsBeingChanged: res.songsBeingChanged
  49. })
  50. )
  51. );
  52. }
  53. });
  54. CacheModule.runJob("SUB", {
  55. channel: "playlist.addSong",
  56. cb: res => {
  57. IOModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(response => {
  58. response.sockets.forEach(socket => {
  59. socket.emit("event:playlist.addSong", {
  60. playlistId: res.playlistId,
  61. song: res.song
  62. });
  63. });
  64. });
  65. if (res.privacy === "public")
  66. IOModule.runJob("EMIT_TO_ROOM", {
  67. room: `profile-${res.userId}`,
  68. args: [
  69. "event:playlist.addSong",
  70. {
  71. playlistId: res.playlistId,
  72. song: res.song
  73. }
  74. ]
  75. });
  76. }
  77. });
  78. CacheModule.runJob("SUB", {
  79. channel: "playlist.removeSong",
  80. cb: res => {
  81. IOModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(response => {
  82. response.sockets.forEach(socket => {
  83. socket.emit("event:playlist.removeSong", {
  84. playlistId: res.playlistId,
  85. songId: res.songId
  86. });
  87. });
  88. });
  89. if (res.privacy === "public")
  90. IOModule.runJob("EMIT_TO_ROOM", {
  91. room: `profile-${res.userId}`,
  92. args: [
  93. "event:playlist.removeSong",
  94. {
  95. playlistId: res.playlistId,
  96. songId: res.songId
  97. }
  98. ]
  99. });
  100. }
  101. });
  102. CacheModule.runJob("SUB", {
  103. channel: "playlist.updateDisplayName",
  104. cb: res => {
  105. IOModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(response => {
  106. response.sockets.forEach(socket => {
  107. socket.emit("event:playlist.updateDisplayName", {
  108. playlistId: res.playlistId,
  109. displayName: res.displayName
  110. });
  111. });
  112. });
  113. if (res.privacy === "public")
  114. IOModule.runJob("EMIT_TO_ROOM", {
  115. room: `profile-${res.userId}`,
  116. args: [
  117. "event:playlist.updateDisplayName",
  118. {
  119. playlistId: res.playlistId,
  120. displayName: res.displayName
  121. }
  122. ]
  123. });
  124. }
  125. });
  126. CacheModule.runJob("SUB", {
  127. channel: "playlist.updatePrivacy",
  128. cb: res => {
  129. IOModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(response => {
  130. response.sockets.forEach(socket => {
  131. socket.emit("event:playlist.updatePrivacy");
  132. });
  133. });
  134. if (res.playlist.privacy === "public")
  135. return IOModule.runJob("EMIT_TO_ROOM", {
  136. room: `profile-${res.userId}`,
  137. args: ["event:playlist.create", res.playlist]
  138. });
  139. return IOModule.runJob("EMIT_TO_ROOM", {
  140. room: `profile-${res.userId}`,
  141. args: ["event:playlist.delete", res.playlist._id]
  142. });
  143. }
  144. });
  145. export default {
  146. /**
  147. * Gets the first song from a private playlist
  148. *
  149. * @param {object} session - the session object automatically added by socket.io
  150. * @param {string} playlistId - the id of the playlist we are getting the first song from
  151. * @param {Function} cb - gets called with the result
  152. */
  153. getFirstSong: isLoginRequired(function getFirstSong(session, playlistId, cb) {
  154. async.waterfall(
  155. [
  156. next => {
  157. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  158. .then(playlist => {
  159. next(null, playlist);
  160. })
  161. .catch(next);
  162. },
  163. (playlist, next) => {
  164. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found.");
  165. return next(null, playlist.songs[0]);
  166. }
  167. ],
  168. async (err, song) => {
  169. if (err) {
  170. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  171. this.log(
  172. "ERROR",
  173. "PLAYLIST_GET_FIRST_SONG",
  174. `Getting the first song of playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  175. );
  176. return cb({ status: "failure", message: err });
  177. }
  178. this.log(
  179. "SUCCESS",
  180. "PLAYLIST_GET_FIRST_SONG",
  181. `Successfully got the first song of playlist "${playlistId}" for user "${session.userId}".`
  182. );
  183. return cb({
  184. status: "success",
  185. song
  186. });
  187. }
  188. );
  189. }),
  190. /**
  191. * Gets a list of all the playlists for a specific user
  192. *
  193. * @param {object} session - the session object automatically added by socket.io
  194. * @param {string} userId - the user id in question
  195. * @param {Function} cb - gets called with the result
  196. */
  197. indexForUser: async function indexForUser(session, userId, cb) {
  198. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  199. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  200. async.waterfall(
  201. [
  202. next => {
  203. userModel.findById(userId).select({ "preferences.orderOfPlaylists": -1 }).exec(next);
  204. },
  205. ({ preferences }, next) => {
  206. const { orderOfPlaylists } = preferences;
  207. const match = {
  208. createdBy: userId
  209. };
  210. // if a playlist order exists
  211. if (orderOfPlaylists > 0) match._id = { $in: orderOfPlaylists };
  212. playlistModel
  213. .aggregate()
  214. .match(match)
  215. .addFields({
  216. weight: { $indexOfArray: [orderOfPlaylists, "$_id"] }
  217. })
  218. .sort({ weight: 1 })
  219. .exec(next);
  220. },
  221. (playlists, next) => {
  222. if (session.userId === userId) return next(null, playlists); // user requesting playlists is the owner of the playlists
  223. const filteredPlaylists = [];
  224. return async.each(
  225. playlists,
  226. (playlist, nextPlaylist) => {
  227. if (playlist.privacy === "public") filteredPlaylists.push(playlist);
  228. return nextPlaylist();
  229. },
  230. () => next(null, filteredPlaylists)
  231. );
  232. }
  233. ],
  234. async (err, playlists) => {
  235. if (err) {
  236. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  237. this.log(
  238. "ERROR",
  239. "PLAYLIST_INDEX_FOR_USER",
  240. `Indexing playlists for user "${userId}" failed. "${err}"`
  241. );
  242. return cb({ status: "failure", message: err });
  243. }
  244. this.log("SUCCESS", "PLAYLIST_INDEX_FOR_USER", `Successfully indexed playlists for user "${userId}".`);
  245. return cb({
  246. status: "success",
  247. data: playlists
  248. });
  249. }
  250. );
  251. },
  252. /**
  253. * Gets all playlists for the user requesting it
  254. *
  255. * @param {object} session - the session object automatically added by socket.io
  256. * @param {boolean} showNonModifiablePlaylists - whether or not to show non modifiable playlists e.g. liked songs
  257. * @param {Function} cb - gets called with the result
  258. */
  259. indexMyPlaylists: isLoginRequired(async function indexMyPlaylists(session, showNonModifiablePlaylists, cb) {
  260. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  261. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  262. async.waterfall(
  263. [
  264. next => {
  265. userModel.findById(session.userId).select({ "preferences.orderOfPlaylists": -1 }).exec(next);
  266. },
  267. ({ preferences }, next) => {
  268. const { orderOfPlaylists } = preferences;
  269. const match = {
  270. createdBy: session.userId
  271. };
  272. // if non modifiable playlists should be shown as well
  273. if (!showNonModifiablePlaylists) match.isUserModifiable = true;
  274. // if a playlist order exists
  275. if (orderOfPlaylists > 0) match._id = { $in: orderOfPlaylists };
  276. playlistModel
  277. .aggregate()
  278. .match(match)
  279. .addFields({
  280. weight: { $indexOfArray: [orderOfPlaylists, "$_id"] }
  281. })
  282. .sort({ weight: 1 })
  283. .exec(next);
  284. }
  285. ],
  286. async (err, playlists) => {
  287. if (err) {
  288. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  289. this.log(
  290. "ERROR",
  291. "PLAYLIST_INDEX_FOR_ME",
  292. `Indexing playlists for user "${session.userId}" failed. "${err}"`
  293. );
  294. return cb({ status: "failure", message: err });
  295. }
  296. this.log(
  297. "SUCCESS",
  298. "PLAYLIST_INDEX_FOR_ME",
  299. `Successfully indexed playlists for user "${session.userId}".`
  300. );
  301. return cb({
  302. status: "success",
  303. data: playlists
  304. });
  305. }
  306. );
  307. }),
  308. /**
  309. * Creates a new private playlist
  310. *
  311. * @param {object} session - the session object automatically added by socket.io
  312. * @param {object} data - the data for the new private playlist
  313. * @param {Function} cb - gets called with the result
  314. */
  315. create: isLoginRequired(async function create(session, data, cb) {
  316. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  317. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  318. const blacklist = ["liked songs", "likedsongs", "disliked songs", "dislikedsongs"];
  319. async.waterfall(
  320. [
  321. next => (data ? next() : cb({ status: "failure", message: "Invalid data" })),
  322. next => {
  323. const { displayName, songs } = data;
  324. if (blacklist.indexOf(displayName.toLowerCase()) !== -1)
  325. return next("That playlist name is blacklisted. Please use a different name.");
  326. return playlistModel.create(
  327. {
  328. displayName,
  329. songs,
  330. createdBy: session.userId,
  331. createdAt: Date.now()
  332. },
  333. next
  334. );
  335. },
  336. (playlist, next) => {
  337. userModel.updateOne(
  338. { _id: session.userId },
  339. { $push: { "preferences.orderOfPlaylists": playlist._id } },
  340. err => {
  341. if (err) return next(err);
  342. return next(null, playlist);
  343. }
  344. );
  345. }
  346. ],
  347. async (err, playlist) => {
  348. if (err) {
  349. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  350. this.log(
  351. "ERROR",
  352. "PLAYLIST_CREATE",
  353. `Creating private playlist failed for user "${session.userId}". "${err}"`
  354. );
  355. return cb({ status: "failure", message: err });
  356. }
  357. CacheModule.runJob("PUB", {
  358. channel: "playlist.create",
  359. value: playlist
  360. });
  361. ActivitiesModule.runJob("ADD_ACTIVITY", {
  362. userId: session.userId,
  363. activityType: "created_playlist",
  364. payload: [playlist._id]
  365. });
  366. this.log(
  367. "SUCCESS",
  368. "PLAYLIST_CREATE",
  369. `Successfully created private playlist for user "${session.userId}".`
  370. );
  371. return cb({
  372. status: "success",
  373. message: "Successfully created playlist",
  374. data: {
  375. _id: playlist._id
  376. }
  377. });
  378. }
  379. );
  380. }),
  381. /**
  382. * Gets a playlist from id
  383. *
  384. * @param {object} session - the session object automatically added by socket.io
  385. * @param {string} playlistId - the id of the playlist we are getting
  386. * @param {Function} cb - gets called with the result
  387. */
  388. getPlaylist: isLoginRequired(function getPlaylist(session, playlistId, cb) {
  389. async.waterfall(
  390. [
  391. next => {
  392. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  393. .then(playlist => {
  394. next(null, playlist);
  395. })
  396. .catch(next);
  397. },
  398. (playlist, next) => {
  399. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found");
  400. return next(null, playlist);
  401. }
  402. ],
  403. async (err, playlist) => {
  404. if (err) {
  405. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  406. this.log(
  407. "ERROR",
  408. "PLAYLIST_GET",
  409. `Getting private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  410. );
  411. return cb({ status: "failure", message: err });
  412. }
  413. const sortedSongs = playlist.songs.sort((a, b) => a.position - b.position);
  414. playlist.songs = sortedSongs;
  415. this.log(
  416. "SUCCESS",
  417. "PLAYLIST_GET",
  418. `Successfully got private playlist "${playlistId}" for user "${session.userId}".`
  419. );
  420. return cb({
  421. status: "success",
  422. data: playlist
  423. });
  424. }
  425. );
  426. }),
  427. /**
  428. * Obtains basic metadata of a playlist in order to format an activity
  429. *
  430. * @param {object} session - the session object automatically added by socket.io
  431. * @param {string} playlistId - the playlist id
  432. * @param {Function} cb - callback
  433. */
  434. getPlaylistForActivity(session, playlistId, cb) {
  435. async.waterfall(
  436. [
  437. next => {
  438. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  439. .then(playlist => {
  440. next(null, playlist);
  441. })
  442. .catch(next);
  443. }
  444. ],
  445. async (err, playlist) => {
  446. if (err) {
  447. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  448. this.log(
  449. "ERROR",
  450. "PLAYLISTS_GET_PLAYLIST_FOR_ACTIVITY",
  451. `Failed to obtain metadata of playlist ${playlistId} for activity formatting. "${err}"`
  452. );
  453. return cb({ status: "failure", message: err });
  454. }
  455. this.log(
  456. "SUCCESS",
  457. "PLAYLISTS_GET_PLAYLIST_FOR_ACTIVITY",
  458. `Obtained metadata of playlist ${playlistId} for activity formatting successfully.`
  459. );
  460. return cb({
  461. status: "success",
  462. data: {
  463. title: playlist.displayName
  464. }
  465. });
  466. }
  467. );
  468. },
  469. // TODO Remove this
  470. /**
  471. * Updates a private playlist
  472. *
  473. * @param {object} session - the session object automatically added by socket.io
  474. * @param {string} playlistId - the id of the playlist we are updating
  475. * @param {object} playlist - the new private playlist object
  476. * @param {Function} cb - gets called with the result
  477. */
  478. update: isLoginRequired(async function update(session, playlistId, playlist, cb) {
  479. const playlistModel = await DBModule.runJob(
  480. "GET_MODEL",
  481. {
  482. modelName: "playlist"
  483. },
  484. this
  485. );
  486. async.waterfall(
  487. [
  488. next => {
  489. playlistModel.updateOne(
  490. { _id: playlistId, createdBy: session.userId },
  491. playlist,
  492. { runValidators: true },
  493. next
  494. );
  495. },
  496. (res, next) => {
  497. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  498. .then(playlist => {
  499. next(null, playlist);
  500. })
  501. .catch(next);
  502. }
  503. ],
  504. async (err, playlist) => {
  505. if (err) {
  506. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  507. this.log(
  508. "ERROR",
  509. "PLAYLIST_UPDATE",
  510. `Updating private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  511. );
  512. return cb({ status: "failure", message: err });
  513. }
  514. this.log(
  515. "SUCCESS",
  516. "PLAYLIST_UPDATE",
  517. `Successfully updated private playlist "${playlistId}" for user "${session.userId}".`
  518. );
  519. return cb({
  520. status: "success",
  521. data: playlist
  522. });
  523. }
  524. );
  525. }),
  526. /**
  527. * Shuffles songs in a private playlist
  528. *
  529. * @param {object} session - the session object automatically added by socket.io
  530. * @param {string} playlistId - the id of the playlist we are updating
  531. * @param {Function} cb - gets called with the result
  532. */
  533. shuffle: isLoginRequired(async function shuffle(session, playlistId, cb) {
  534. const playlistModel = await DBModule.runJob(
  535. "GET_MODEL",
  536. {
  537. modelName: "playlist"
  538. },
  539. this
  540. );
  541. async.waterfall(
  542. [
  543. next => {
  544. if (!playlistId) return next("No playlist id.");
  545. return playlistModel.findById(playlistId, next);
  546. },
  547. (playlist, next) => {
  548. if (!playlist.isUserModifiable) return next("Playlist cannot be shuffled.");
  549. return UtilsModule.runJob("SHUFFLE", { array: playlist.songs }, this)
  550. .then(result => next(null, result.array))
  551. .catch(next);
  552. },
  553. (songs, next) => {
  554. playlistModel.updateOne({ _id: playlistId }, { $set: { songs } }, { runValidators: true }, next);
  555. },
  556. (res, next) => {
  557. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  558. .then(playlist => {
  559. next(null, playlist);
  560. })
  561. .catch(next);
  562. }
  563. ],
  564. async (err, playlist) => {
  565. if (err) {
  566. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  567. this.log(
  568. "ERROR",
  569. "PLAYLIST_SHUFFLE",
  570. `Updating private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  571. );
  572. return cb({ status: "failure", message: err });
  573. }
  574. this.log(
  575. "SUCCESS",
  576. "PLAYLIST_SHUFFLE",
  577. `Successfully updated private playlist "${playlistId}" for user "${session.userId}".`
  578. );
  579. return cb({
  580. status: "success",
  581. message: "Successfully shuffled playlist.",
  582. data: playlist
  583. });
  584. }
  585. );
  586. }),
  587. /**
  588. * Changes the order of song(s) in a private playlist
  589. *
  590. * @param {object} session - the session object automatically added by socket.io
  591. * @param {string} playlistId - the id of the playlist we are targeting
  592. * @param {Array} songsBeingChanged - the songs to be repositioned, each element contains "songId" and "position" properties
  593. * @param {Function} cb - gets called with the result
  594. */
  595. repositionSongs: isLoginRequired(async function repositionSongs(session, playlistId, songsBeingChanged, cb) {
  596. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  597. async.waterfall(
  598. [
  599. // update playlist object with each song's new position
  600. next =>
  601. async.each(
  602. songsBeingChanged,
  603. (song, nextSong) =>
  604. playlistModel.updateOne(
  605. { _id: playlistId, "songs.songId": song.songId },
  606. {
  607. $set: {
  608. "songs.$.position": song.position
  609. }
  610. },
  611. err => {
  612. if (err) return next(err);
  613. return nextSong();
  614. }
  615. ),
  616. next
  617. ),
  618. // update the cache with the new songs positioning
  619. next => {
  620. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  621. .then(playlist => next(null, playlist))
  622. .catch(next);
  623. }
  624. ],
  625. async err => {
  626. if (err) {
  627. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  628. this.log(
  629. "ERROR",
  630. "PLAYLIST_REPOSITION_SONGS",
  631. `Repositioning songs for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  632. );
  633. return cb({ status: "failure", message: err });
  634. }
  635. this.log(
  636. "SUCCESS",
  637. "PLAYLIST_REPOSITION_SONGS",
  638. `Successfully repositioned songs for private playlist "${playlistId}" for user "${session.userId}".`
  639. );
  640. CacheModule.runJob("PUB", {
  641. channel: "playlist.repositionSongs",
  642. value: {
  643. userId: session.userId,
  644. playlistId,
  645. songsBeingChanged
  646. }
  647. });
  648. return cb({
  649. status: "success",
  650. message: "Order of songs successfully updated"
  651. });
  652. }
  653. );
  654. }),
  655. /**
  656. * Moves a song to the bottom of the list in a private playlist
  657. *
  658. * @param {object} session - the session object automatically added by socket.io
  659. * @param {string} playlistId - the id of the playlist we are moving the song to the bottom from
  660. * @param {string} songId - the id of the song we are moving to the bottom of the list
  661. * @param {Function} cb - gets called with the result
  662. */
  663. moveSongToBottom: isLoginRequired(async function moveSongToBottom(session, playlistId, songId, cb) {
  664. async.waterfall(
  665. [
  666. next => {
  667. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  668. .then(playlist => next(null, playlist))
  669. .catch(next);
  670. },
  671. (playlist, next) => {
  672. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found");
  673. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  674. // sort array by position
  675. playlist.songs.sort((a, b) => a.position - b.position);
  676. // find index of songId
  677. playlist.songs.forEach((song, index) => {
  678. // reorder array (simulates what would be done with a drag and drop interface)
  679. if (song.songId === songId)
  680. playlist.songs.splice(playlist.songs.length, 0, playlist.songs.splice(index, 1)[0]);
  681. });
  682. const songsBeingChanged = [];
  683. playlist.songs.forEach((song, index) => {
  684. // check if position needs updated based on index
  685. if (song.position !== index + 1)
  686. songsBeingChanged.push({
  687. songId: song.songId,
  688. position: index + 1
  689. });
  690. });
  691. // update position property on songs that need to be changed
  692. return IOModule.runJob(
  693. "RUN_ACTION2",
  694. {
  695. session,
  696. namespace: "playlists",
  697. action: "repositionSongs",
  698. args: [playlistId, songsBeingChanged]
  699. },
  700. this
  701. )
  702. .then(res => {
  703. if (res.status === "success") return next();
  704. return next("Unable to reposition song in playlist.");
  705. })
  706. .catch(next);
  707. }
  708. ],
  709. async err => {
  710. if (err) {
  711. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  712. this.log(
  713. "ERROR",
  714. "PLAYLIST_MOVE_SONG_TO_BOTTOM",
  715. `Moving song "${songId}" to the bottom for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  716. );
  717. return cb({ status: "failure", message: err });
  718. }
  719. this.log(
  720. "SUCCESS",
  721. "PLAYLIST_MOVE_SONG_TO_BOTTOM",
  722. `Successfully moved song "${songId}" to the bottom for private playlist "${playlistId}" for user "${session.userId}".`
  723. );
  724. return cb({
  725. status: "success",
  726. message: "Order of songs successfully updated"
  727. });
  728. }
  729. );
  730. }),
  731. /**
  732. * Adds a song to a private playlist
  733. *
  734. * @param {object} session - the session object automatically added by socket.io
  735. * @param {boolean} isSet - is the song part of a set of songs to be added
  736. * @param {string} songId - the id of the song we are trying to add
  737. * @param {string} playlistId - the id of the playlist we are adding the song to
  738. * @param {Function} cb - gets called with the result
  739. */
  740. addSongToPlaylist: isLoginRequired(async function addSongToPlaylist(session, isSet, songId, playlistId, cb) {
  741. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  742. async.waterfall(
  743. [
  744. next => {
  745. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  746. .then(playlist => {
  747. if (!playlist || playlist.createdBy !== session.userId)
  748. return next("Something went wrong when trying to get the playlist");
  749. return async.each(
  750. playlist.songs,
  751. (song, nextSong) => {
  752. if (song.songId === songId) return next("That song is already in the playlist");
  753. return nextSong();
  754. },
  755. err => next(err, playlist.songs.length + 1)
  756. );
  757. })
  758. .catch(next);
  759. },
  760. (position, next) => {
  761. SongsModule.runJob("GET_SONG", { id: songId }, this)
  762. .then(response => {
  763. const { song } = response;
  764. next(null, {
  765. _id: song._id,
  766. songId,
  767. title: song.title,
  768. duration: song.duration,
  769. position
  770. });
  771. })
  772. .catch(() => {
  773. YouTubeModule.runJob("GET_SONG", { songId }, this)
  774. .then(response => next(null, { ...response.song, position }))
  775. .catch(next);
  776. });
  777. },
  778. (newSong, next) => {
  779. playlistModel.updateOne(
  780. { _id: playlistId },
  781. { $push: { songs: newSong } },
  782. { runValidators: true },
  783. err => {
  784. if (err) return next(err);
  785. return PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  786. .then(playlist => next(null, playlist, newSong))
  787. .catch(next);
  788. }
  789. );
  790. }
  791. ],
  792. async (err, playlist, newSong) => {
  793. if (err) {
  794. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  795. this.log(
  796. "ERROR",
  797. "PLAYLIST_ADD_SONG",
  798. `Adding song "${songId}" to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  799. );
  800. return cb({ status: "failure", message: err });
  801. }
  802. this.log(
  803. "SUCCESS",
  804. "PLAYLIST_ADD_SONG",
  805. `Successfully added song "${songId}" to private playlist "${playlistId}" for user "${session.userId}".`
  806. );
  807. if (!isSet)
  808. ActivitiesModule.runJob("ADD_ACTIVITY", {
  809. userId: session.userId,
  810. activityType: "added_song_to_playlist",
  811. payload: [{ songId, playlistId }]
  812. });
  813. CacheModule.runJob("PUB", {
  814. channel: "playlist.addSong",
  815. value: {
  816. playlistId: playlist._id,
  817. song: newSong,
  818. userId: session.userId,
  819. privacy: playlist.privacy
  820. }
  821. });
  822. return cb({
  823. status: "success",
  824. message: "Song has been successfully added to the playlist",
  825. data: playlist.songs
  826. });
  827. }
  828. );
  829. }),
  830. /**
  831. * Adds a set of songs to a private playlist
  832. *
  833. * @param {object} session - the session object automatically added by socket.io
  834. * @param {string} url - the url of the the YouTube playlist
  835. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  836. * @param {boolean} musicOnly - whether to only add music to the playlist
  837. * @param {Function} cb - gets called with the result
  838. */
  839. addSetToPlaylist: isLoginRequired(function addSetToPlaylist(session, url, playlistId, musicOnly, cb) {
  840. let videosInPlaylistTotal = 0;
  841. let songsInPlaylistTotal = 0;
  842. let addSongsStats = null;
  843. const addedSongs = [];
  844. async.waterfall(
  845. [
  846. next => {
  847. YouTubeModule.runJob(
  848. "GET_PLAYLIST",
  849. {
  850. url,
  851. musicOnly
  852. },
  853. this
  854. ).then(response => {
  855. if (response.filteredSongs) {
  856. videosInPlaylistTotal = response.songs.length;
  857. songsInPlaylistTotal = response.filteredSongs.length;
  858. } else {
  859. songsInPlaylistTotal = videosInPlaylistTotal = response.songs.length;
  860. }
  861. next(null, response.songs);
  862. });
  863. },
  864. (songIds, next) => {
  865. let successful = 0;
  866. let failed = 0;
  867. let alreadyInPlaylist = 0;
  868. if (songIds.length === 0) next();
  869. async.eachLimit(
  870. songIds,
  871. 1,
  872. (songId, next) => {
  873. IOModule.runJob(
  874. "RUN_ACTION2",
  875. {
  876. session,
  877. namespace: "playlists",
  878. action: "addSongToPlaylist",
  879. args: [true, songId, playlistId]
  880. },
  881. this
  882. )
  883. .then(res => {
  884. if (res.status === "success") {
  885. successful += 1;
  886. addedSongs.push(songId);
  887. } else failed += 1;
  888. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  889. })
  890. .catch(() => {
  891. failed += 1;
  892. })
  893. .finally(() => {
  894. next();
  895. });
  896. },
  897. () => {
  898. addSongsStats = { successful, failed, alreadyInPlaylist };
  899. next(null);
  900. }
  901. );
  902. },
  903. next => {
  904. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  905. .then(playlist => {
  906. next(null, playlist);
  907. })
  908. .catch(next);
  909. },
  910. (playlist, next) => {
  911. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found.");
  912. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  913. return next(null, playlist);
  914. }
  915. ],
  916. async (err, playlist) => {
  917. if (err) {
  918. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  919. this.log(
  920. "ERROR",
  921. "PLAYLIST_IMPORT",
  922. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  923. );
  924. return cb({ status: "failure", message: err });
  925. }
  926. ActivitiesModule.runJob("ADD_ACTIVITY", {
  927. userId: session.userId,
  928. activityType: "added_songs_to_playlist",
  929. payload: addedSongs
  930. });
  931. this.log(
  932. "SUCCESS",
  933. "PLAYLIST_IMPORT",
  934. `Successfully imported a YouTube playlist to private playlist "${playlistId}" for user "${session.userId}". Videos in playlist: ${videosInPlaylistTotal}, songs in playlist: ${songsInPlaylistTotal}, songs successfully added: ${addSongsStats.successful}, songs failed: ${addSongsStats.failed}, already in playlist: ${addSongsStats.alreadyInPlaylist}.`
  935. );
  936. return cb({
  937. status: "success",
  938. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  939. data: playlist.songs,
  940. stats: {
  941. videosInPlaylistTotal,
  942. songsInPlaylistTotal
  943. }
  944. });
  945. }
  946. );
  947. }),
  948. /**
  949. * Removes a song from a private playlist
  950. *
  951. * @param {object} session - the session object automatically added by socket.io
  952. * @param {string} songId - the id of the song we are removing from the private playlist
  953. * @param {string} playlistId - the id of the playlist we are removing the song from
  954. * @param {Function} cb - gets called with the result
  955. */
  956. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(session, songId, playlistId, cb) {
  957. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  958. async.waterfall(
  959. [
  960. next => {
  961. if (!songId || typeof songId !== "string") return next("Invalid song id.");
  962. if (!playlistId) return next("Invalid playlist id.");
  963. return next();
  964. },
  965. next => {
  966. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  967. .then(playlist => next(null, playlist))
  968. .catch(next);
  969. },
  970. (playlist, next) => {
  971. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found");
  972. // sort array by position
  973. playlist.songs.sort((a, b) => a.position - b.position);
  974. // find index of songId
  975. playlist.songs.forEach((song, ind) => {
  976. // remove song from array
  977. if (song.songId === songId) playlist.songs.splice(ind, 1);
  978. });
  979. const songsBeingChanged = [];
  980. playlist.songs.forEach((song, index) => {
  981. // check if position needs updated based on index
  982. if (song.position !== index + 1)
  983. songsBeingChanged.push({
  984. songId: song.songId,
  985. position: index + 1
  986. });
  987. });
  988. // update position property on songs that need to be changed
  989. return IOModule.runJob(
  990. "RUN_ACTION2",
  991. {
  992. session,
  993. namespace: "playlists",
  994. action: "repositionSongs",
  995. args: [playlistId, songsBeingChanged]
  996. },
  997. this
  998. )
  999. .then(res => {
  1000. if (res.status === "success") return next();
  1001. return next("Unable to reposition song in playlist.");
  1002. })
  1003. .catch(next);
  1004. },
  1005. next => playlistModel.updateOne({ _id: playlistId }, { $pull: { songs: { songId } } }, next),
  1006. (res, next) => {
  1007. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1008. .then(playlist => next(null, playlist))
  1009. .catch(next);
  1010. }
  1011. ],
  1012. async (err, playlist) => {
  1013. if (err) {
  1014. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1015. this.log(
  1016. "ERROR",
  1017. "PLAYLIST_REMOVE_SONG",
  1018. `Removing song "${songId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1019. );
  1020. return cb({ status: "failure", message: err });
  1021. }
  1022. this.log(
  1023. "SUCCESS",
  1024. "PLAYLIST_REMOVE_SONG",
  1025. `Successfully removed song "${songId}" from private playlist "${playlistId}" for user "${session.userId}".`
  1026. );
  1027. CacheModule.runJob("PUB", {
  1028. channel: "playlist.removeSong",
  1029. value: {
  1030. playlistId: playlist._id,
  1031. songId,
  1032. userId: session.userId,
  1033. privacy: playlist.privacy
  1034. }
  1035. });
  1036. return cb({
  1037. status: "success",
  1038. message: "Song has been successfully removed from playlist",
  1039. data: playlist.songs
  1040. });
  1041. }
  1042. );
  1043. }),
  1044. /**
  1045. * Updates the displayName of a private playlist
  1046. *
  1047. * @param {object} session - the session object automatically added by socket.io
  1048. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  1049. * @param {Function} cb - gets called with the result
  1050. */
  1051. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  1052. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1053. async.waterfall(
  1054. [
  1055. next => {
  1056. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1057. .then(playlist => next(null, playlist))
  1058. .catch(next);
  1059. },
  1060. (playlist, next) => {
  1061. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  1062. return next(null);
  1063. },
  1064. next => {
  1065. playlistModel.updateOne(
  1066. { _id: playlistId, createdBy: session.userId },
  1067. { $set: { displayName } },
  1068. { runValidators: true },
  1069. next
  1070. );
  1071. },
  1072. (res, next) => {
  1073. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1074. .then(playlist => {
  1075. next(null, playlist);
  1076. })
  1077. .catch(next);
  1078. }
  1079. ],
  1080. async (err, playlist) => {
  1081. if (err) {
  1082. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1083. this.log(
  1084. "ERROR",
  1085. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1086. `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1087. );
  1088. return cb({ status: "failure", message: err });
  1089. }
  1090. this.log(
  1091. "SUCCESS",
  1092. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1093. `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${session.userId}".`
  1094. );
  1095. CacheModule.runJob("PUB", {
  1096. channel: "playlist.updateDisplayName",
  1097. value: {
  1098. playlistId,
  1099. displayName,
  1100. userId: session.userId,
  1101. privacy: playlist.privacy
  1102. }
  1103. });
  1104. return cb({
  1105. status: "success",
  1106. message: "Playlist has been successfully updated"
  1107. });
  1108. }
  1109. );
  1110. }),
  1111. /**
  1112. * Removes a private playlist
  1113. *
  1114. * @param {object} session - the session object automatically added by socket.io
  1115. * @param {string} playlistId - the id of the playlist we are moving the song to the top from
  1116. * @param {Function} cb - gets called with the result
  1117. */
  1118. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1119. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1120. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1121. async.waterfall(
  1122. [
  1123. next => {
  1124. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1125. .then(playlist => next(null, playlist))
  1126. .catch(next);
  1127. },
  1128. (playlist, next) => {
  1129. if (!playlist.isUserModifiable) return next("Playlist cannot be removed.");
  1130. return next(null, playlist);
  1131. },
  1132. (playlist, next) => {
  1133. userModel.updateOne(
  1134. { _id: playlist.createdBy },
  1135. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1136. err => {
  1137. if (err) return next(err);
  1138. return next(null);
  1139. }
  1140. );
  1141. },
  1142. next => {
  1143. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this).then(next).catch(next);
  1144. },
  1145. next => {
  1146. stationModel.find({ privatePlaylist: playlistId }, (err, res) => {
  1147. next(err, res);
  1148. });
  1149. },
  1150. (stations, next) => {
  1151. async.each(
  1152. stations,
  1153. (station, next) => {
  1154. async.waterfall(
  1155. [
  1156. next => {
  1157. stationModel.updateOne(
  1158. { _id: station._id },
  1159. { $set: { privatePlaylist: null } },
  1160. { runValidators: true },
  1161. next
  1162. );
  1163. },
  1164. (res, next) => {
  1165. if (!station.partyMode) {
  1166. moduleManager.modules.stations
  1167. .runJob(
  1168. "UPDATE_STATION",
  1169. {
  1170. stationId: station._id
  1171. },
  1172. this
  1173. )
  1174. .then(station => next(null, station))
  1175. .catch(next);
  1176. CacheModule.runJob("PUB", {
  1177. channel: "privatePlaylist.selected",
  1178. value: {
  1179. playlistId: null,
  1180. stationId: station._id
  1181. }
  1182. });
  1183. } else next();
  1184. }
  1185. ],
  1186. () => {
  1187. next();
  1188. }
  1189. );
  1190. },
  1191. () => {
  1192. next();
  1193. }
  1194. );
  1195. }
  1196. ],
  1197. async err => {
  1198. if (err) {
  1199. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1200. this.log(
  1201. "ERROR",
  1202. "PLAYLIST_REMOVE",
  1203. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1204. );
  1205. return cb({ status: "failure", message: err });
  1206. }
  1207. this.log(
  1208. "SUCCESS",
  1209. "PLAYLIST_REMOVE",
  1210. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1211. );
  1212. CacheModule.runJob("PUB", {
  1213. channel: "playlist.delete",
  1214. value: {
  1215. userId: session.userId,
  1216. playlistId
  1217. }
  1218. });
  1219. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1220. userId: session.userId,
  1221. activityType: "deleted_playlist",
  1222. payload: [playlistId]
  1223. });
  1224. return cb({
  1225. status: "success",
  1226. message: "Playlist successfully removed"
  1227. });
  1228. }
  1229. );
  1230. }),
  1231. /**
  1232. * Updates the privacy of a private playlist
  1233. *
  1234. * @param {object} session - the session object automatically added by socket.io
  1235. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1236. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1237. * @param {Function} cb - gets called with the result
  1238. */
  1239. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  1240. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1241. async.waterfall(
  1242. [
  1243. next => {
  1244. playlistModel.updateOne(
  1245. { _id: playlistId, createdBy: session.userId },
  1246. { $set: { privacy } },
  1247. { runValidators: true },
  1248. next
  1249. );
  1250. },
  1251. (res, next) => {
  1252. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1253. .then(playlist => {
  1254. next(null, playlist);
  1255. })
  1256. .catch(next);
  1257. }
  1258. ],
  1259. async (err, playlist) => {
  1260. if (err) {
  1261. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1262. this.log(
  1263. "ERROR",
  1264. "PLAYLIST_UPDATE_PRIVACY",
  1265. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1266. );
  1267. return cb({ status: "failure", message: err });
  1268. }
  1269. this.log(
  1270. "SUCCESS",
  1271. "PLAYLIST_UPDATE_PRIVACY",
  1272. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  1273. );
  1274. CacheModule.runJob("PUB", {
  1275. channel: "playlist.updatePrivacy",
  1276. value: {
  1277. userId: session.userId,
  1278. playlist
  1279. }
  1280. });
  1281. return cb({
  1282. status: "success",
  1283. message: "Playlist has been successfully updated"
  1284. });
  1285. }
  1286. );
  1287. })
  1288. };