playlists.js 44 KB

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