playlists.js 43 KB

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