playlists.js 46 KB

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