playlists.js 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610
  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("ENSURE_SONG_EXISTS_BY_SONG_ID", { songId }, this)
  791. .then(response => {
  792. const { song } = response;
  793. const { _id, title, thumbnail, duration, verified } = song;
  794. next(null, {
  795. _id,
  796. songId,
  797. title,
  798. thumbnail,
  799. duration,
  800. verified
  801. });
  802. })
  803. .catch(next);
  804. },
  805. (newSong, next) => {
  806. playlistModel.updateOne(
  807. { _id: playlistId },
  808. { $push: { songs: newSong } },
  809. { runValidators: true },
  810. err => {
  811. if (err) return next(err);
  812. return PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  813. .then(playlist => next(null, playlist, newSong))
  814. .catch(next);
  815. }
  816. );
  817. }
  818. ],
  819. async (err, playlist, newSong) => {
  820. if (err) {
  821. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  822. this.log(
  823. "ERROR",
  824. "PLAYLIST_ADD_SONG",
  825. `Adding song "${songId}" to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  826. );
  827. return cb({ status: "failure", message: err });
  828. }
  829. this.log(
  830. "SUCCESS",
  831. "PLAYLIST_ADD_SONG",
  832. `Successfully added song "${songId}" to private playlist "${playlistId}" for user "${session.userId}".`
  833. );
  834. if (!isSet && playlist.displayName !== "Liked Songs" && playlist.displayName !== "Disliked Songs") {
  835. const songName = newSong.artists
  836. ? `${newSong.title} by ${newSong.artists.join(", ")}`
  837. : newSong.title;
  838. ActivitiesModule.runJob("ADD_ACTIVITY", {
  839. userId: session.userId,
  840. type: "playlist__add_song",
  841. payload: {
  842. message: `Added <songId>${songName}</songId> to playlist <playlistId>${playlist.displayName}</playlistId>`,
  843. thumbnail: newSong.thumbnail,
  844. playlistId,
  845. songId
  846. }
  847. });
  848. }
  849. CacheModule.runJob("PUB", {
  850. channel: "playlist.addSong",
  851. value: {
  852. playlistId: playlist._id,
  853. song: newSong,
  854. userId: session.userId,
  855. privacy: playlist.privacy
  856. }
  857. });
  858. return cb({
  859. status: "success",
  860. message: "Song has been successfully added to the playlist",
  861. data: playlist.songs
  862. });
  863. }
  864. );
  865. }),
  866. /**
  867. * Adds a set of songs to a private playlist
  868. *
  869. * @param {object} session - the session object automatically added by the websocket
  870. * @param {string} url - the url of the the YouTube playlist
  871. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  872. * @param {boolean} musicOnly - whether to only add music to the playlist
  873. * @param {Function} cb - gets called with the result
  874. */
  875. addSetToPlaylist: isLoginRequired(function addSetToPlaylist(session, url, playlistId, musicOnly, cb) {
  876. let videosInPlaylistTotal = 0;
  877. let songsInPlaylistTotal = 0;
  878. let addSongsStats = null;
  879. const addedSongs = [];
  880. async.waterfall(
  881. [
  882. next => {
  883. YouTubeModule.runJob("GET_PLAYLIST", { url, musicOnly }, this).then(res => {
  884. if (res.filteredSongs) {
  885. videosInPlaylistTotal = res.songs.length;
  886. songsInPlaylistTotal = res.filteredSongs.length;
  887. } else {
  888. songsInPlaylistTotal = videosInPlaylistTotal = res.songs.length;
  889. }
  890. next(null, res.songs);
  891. });
  892. },
  893. (songIds, next) => {
  894. let successful = 0;
  895. let failed = 0;
  896. let alreadyInPlaylist = 0;
  897. if (songIds.length === 0) next();
  898. console.log(songIds);
  899. async.eachLimit(
  900. songIds,
  901. 1,
  902. (songId, next) => {
  903. WSModule.runJob(
  904. "RUN_ACTION2",
  905. {
  906. session,
  907. namespace: "playlists",
  908. action: "addSongToPlaylist",
  909. args: [true, songId, playlistId]
  910. },
  911. this
  912. )
  913. .then(res => {
  914. if (res.status === "success") {
  915. successful += 1;
  916. addedSongs.push(songId);
  917. } else failed += 1;
  918. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  919. })
  920. .catch(() => {
  921. failed += 1;
  922. })
  923. .finally(() => next());
  924. },
  925. () => {
  926. addSongsStats = { successful, failed, alreadyInPlaylist };
  927. next(null);
  928. }
  929. );
  930. },
  931. next => {
  932. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  933. .then(playlist => next(null, playlist))
  934. .catch(next);
  935. },
  936. (playlist, next) => {
  937. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found.");
  938. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  939. return next(null, playlist);
  940. }
  941. ],
  942. async (err, playlist) => {
  943. if (err) {
  944. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  945. this.log(
  946. "ERROR",
  947. "PLAYLIST_IMPORT",
  948. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  949. );
  950. return cb({ status: "failure", message: err });
  951. }
  952. ActivitiesModule.runJob("ADD_ACTIVITY", {
  953. userId: session.userId,
  954. type: "playlist__import_playlist",
  955. payload: {
  956. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  957. playlistId
  958. }
  959. });
  960. this.log(
  961. "SUCCESS",
  962. "PLAYLIST_IMPORT",
  963. `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}.`
  964. );
  965. return cb({
  966. status: "success",
  967. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  968. data: playlist.songs,
  969. stats: {
  970. videosInPlaylistTotal,
  971. songsInPlaylistTotal
  972. }
  973. });
  974. }
  975. );
  976. }),
  977. /**
  978. * Removes a song from a private playlist
  979. *
  980. * @param {object} session - the session object automatically added by the websocket
  981. * @param {string} songId - the id of the song we are removing from the private playlist
  982. * @param {string} playlistId - the id of the playlist we are removing the song from
  983. * @param {Function} cb - gets called with the result
  984. */
  985. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(session, songId, playlistId, cb) {
  986. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  987. async.waterfall(
  988. [
  989. next => {
  990. if (!songId || typeof songId !== "string") return next("Invalid song id.");
  991. if (!playlistId) return next("Invalid playlist id.");
  992. return next();
  993. },
  994. next => {
  995. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  996. .then(playlist => next(null, playlist))
  997. .catch(next);
  998. },
  999. (playlist, next) => {
  1000. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found");
  1001. // sort array by position
  1002. playlist.songs.sort((a, b) => a.position - b.position);
  1003. // find index of songId
  1004. playlist.songs.forEach((song, ind) => {
  1005. // remove song from array
  1006. if (song.songId === songId) playlist.songs.splice(ind, 1);
  1007. });
  1008. const songsBeingChanged = [];
  1009. playlist.songs.forEach((song, index) => {
  1010. // check if position needs updated based on index
  1011. if (song.position !== index + 1)
  1012. songsBeingChanged.push({
  1013. songId: song.songId,
  1014. position: index + 1
  1015. });
  1016. });
  1017. // update position property on songs that need to be changed
  1018. return WSModule.runJob(
  1019. "RUN_ACTION2",
  1020. {
  1021. session,
  1022. namespace: "playlists",
  1023. action: "repositionSongs",
  1024. args: [playlistId, songsBeingChanged]
  1025. },
  1026. this
  1027. )
  1028. .then(res => {
  1029. if (res.status === "success") return next();
  1030. return next("Unable to reposition song in playlist.");
  1031. })
  1032. .catch(next);
  1033. },
  1034. next => playlistModel.updateOne({ _id: playlistId }, { $pull: { songs: { songId } } }, next),
  1035. (res, next) => {
  1036. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1037. .then(playlist => next(null, playlist))
  1038. .catch(next);
  1039. },
  1040. (playlist, next) => {
  1041. SongsModule.runJob("GET_SONG_FROM_ID", { songId }, this)
  1042. .then(res =>
  1043. next(null, playlist, {
  1044. title: res.song.title,
  1045. thumbnail: res.song.thumbnail,
  1046. artists: res.song.artists
  1047. })
  1048. )
  1049. .catch(() => {
  1050. YouTubeModule.runJob("GET_SONG", { songId }, this)
  1051. .then(response => next(null, playlist, response.song))
  1052. .catch(next);
  1053. });
  1054. },
  1055. (playlist, song, next) => {
  1056. const songName = song.artists ? `${song.title} by ${song.artists.join(", ")}` : song.title;
  1057. if (playlist.displayName !== "Liked Songs" && playlist.displayName !== "Disliked Songs") {
  1058. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1059. userId: session.userId,
  1060. type: "playlist__remove_song",
  1061. payload: {
  1062. message: `Removed <songId>${songName}</songId> from playlist <playlistId>${playlist.displayName}</playlistId>`,
  1063. thumbnail: song.thumbnail,
  1064. playlistId,
  1065. songId
  1066. }
  1067. });
  1068. }
  1069. return next(null, playlist);
  1070. }
  1071. ],
  1072. async (err, playlist) => {
  1073. if (err) {
  1074. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1075. this.log(
  1076. "ERROR",
  1077. "PLAYLIST_REMOVE_SONG",
  1078. `Removing song "${songId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1079. );
  1080. return cb({ status: "failure", message: err });
  1081. }
  1082. this.log(
  1083. "SUCCESS",
  1084. "PLAYLIST_REMOVE_SONG",
  1085. `Successfully removed song "${songId}" from private playlist "${playlistId}" for user "${session.userId}".`
  1086. );
  1087. CacheModule.runJob("PUB", {
  1088. channel: "playlist.removeSong",
  1089. value: {
  1090. playlistId: playlist._id,
  1091. songId,
  1092. userId: session.userId,
  1093. privacy: playlist.privacy
  1094. }
  1095. });
  1096. return cb({
  1097. status: "success",
  1098. message: "Song has been successfully removed from playlist",
  1099. data: playlist.songs
  1100. });
  1101. }
  1102. );
  1103. }),
  1104. /**
  1105. * Updates the displayName of a private playlist
  1106. *
  1107. * @param {object} session - the session object automatically added by the websocket
  1108. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  1109. * @param {Function} cb - gets called with the result
  1110. */
  1111. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  1112. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1113. async.waterfall(
  1114. [
  1115. next => {
  1116. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1117. .then(playlist => next(null, playlist))
  1118. .catch(next);
  1119. },
  1120. (playlist, next) => {
  1121. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  1122. return next(null);
  1123. },
  1124. next => {
  1125. playlistModel.updateOne(
  1126. { _id: playlistId, createdBy: session.userId },
  1127. { $set: { displayName } },
  1128. { runValidators: true },
  1129. next
  1130. );
  1131. },
  1132. (res, next) => {
  1133. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1134. .then(playlist => next(null, playlist))
  1135. .catch(next);
  1136. }
  1137. ],
  1138. async (err, playlist) => {
  1139. if (err) {
  1140. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1141. this.log(
  1142. "ERROR",
  1143. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1144. `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1145. );
  1146. return cb({ status: "failure", message: err });
  1147. }
  1148. this.log(
  1149. "SUCCESS",
  1150. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1151. `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${session.userId}".`
  1152. );
  1153. CacheModule.runJob("PUB", {
  1154. channel: "playlist.updateDisplayName",
  1155. value: {
  1156. playlistId,
  1157. displayName,
  1158. userId: session.userId,
  1159. privacy: playlist.privacy
  1160. }
  1161. });
  1162. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1163. userId: session.userId,
  1164. type: "playlist__edit_display_name",
  1165. payload: {
  1166. message: `Changed display name of playlist <playlistId>${displayName}</playlistId>`,
  1167. playlistId
  1168. }
  1169. });
  1170. return cb({
  1171. status: "success",
  1172. message: "Playlist has been successfully updated"
  1173. });
  1174. }
  1175. );
  1176. }),
  1177. /**
  1178. * Removes a private playlist
  1179. *
  1180. * @param {object} session - the session object automatically added by the websocket
  1181. * @param {string} playlistId - the id of the playlist we are moving the song to the top from
  1182. * @param {Function} cb - gets called with the result
  1183. */
  1184. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1185. // const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1186. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1187. async.waterfall(
  1188. [
  1189. next => {
  1190. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1191. .then(playlist => next(null, playlist))
  1192. .catch(next);
  1193. },
  1194. (playlist, next) => {
  1195. if (!playlist.isUserModifiable) return next("Playlist cannot be removed.");
  1196. return next(null, playlist);
  1197. },
  1198. (playlist, next) => {
  1199. userModel.updateOne(
  1200. { _id: playlist.createdBy },
  1201. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1202. err => next(err, playlist)
  1203. );
  1204. },
  1205. (playlist, next) => {
  1206. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1207. .then(() => next(null, playlist))
  1208. .catch(next);
  1209. }
  1210. // (playlist, next) => {
  1211. // stationModel.find({ privatePlaylist: playlistId }, (err, res) => {
  1212. // next(err, playlist, res);
  1213. // });
  1214. // },
  1215. // (playlist, stations, next) => {
  1216. // async.each(
  1217. // stations,
  1218. // (station, next) => {
  1219. // async.waterfall(
  1220. // [
  1221. // next => {
  1222. // stationModel.updateOne(
  1223. // { _id: station._id },
  1224. // { $set: { privatePlaylist: null } },
  1225. // { runValidators: true },
  1226. // next
  1227. // );
  1228. // },
  1229. // (res, next) => {
  1230. // if (!station.partyMode) {
  1231. // moduleManager.modules.stations
  1232. // .runJob("UPDATE_STATION", { stationId: station._id }, this)
  1233. // .then(station => next(null, station))
  1234. // .catch(next);
  1235. // CacheModule.runJob("PUB", {
  1236. // channel: "privatePlaylist.selected",
  1237. // value: {
  1238. // playlistId: null,
  1239. // stationId: station._id
  1240. // }
  1241. // });
  1242. // } else next();
  1243. // }
  1244. // ],
  1245. // () => next()
  1246. // );
  1247. // },
  1248. // () => next(null, playlist)
  1249. // );
  1250. // }
  1251. ],
  1252. async (err, playlist) => {
  1253. if (err) {
  1254. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1255. this.log(
  1256. "ERROR",
  1257. "PLAYLIST_REMOVE",
  1258. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1259. );
  1260. return cb({ status: "failure", message: err });
  1261. }
  1262. this.log(
  1263. "SUCCESS",
  1264. "PLAYLIST_REMOVE",
  1265. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1266. );
  1267. CacheModule.runJob("PUB", {
  1268. channel: "playlist.delete",
  1269. value: {
  1270. userId: session.userId,
  1271. playlistId
  1272. }
  1273. });
  1274. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1275. userId: playlist.createdBy,
  1276. type: "playlist__remove",
  1277. payload: {
  1278. message: `Removed playlist ${playlist.displayName}`
  1279. }
  1280. });
  1281. return cb({
  1282. status: "success",
  1283. message: "Playlist successfully removed"
  1284. });
  1285. }
  1286. );
  1287. }),
  1288. /**
  1289. * Updates the privacy of a private playlist
  1290. *
  1291. * @param {object} session - the session object automatically added by the websocket
  1292. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1293. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1294. * @param {Function} cb - gets called with the result
  1295. */
  1296. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  1297. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1298. async.waterfall(
  1299. [
  1300. next => {
  1301. playlistModel.updateOne(
  1302. { _id: playlistId, createdBy: session.userId },
  1303. { $set: { privacy } },
  1304. { runValidators: true },
  1305. next
  1306. );
  1307. },
  1308. (res, next) => {
  1309. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1310. .then(playlist => next(null, playlist))
  1311. .catch(next);
  1312. }
  1313. ],
  1314. async (err, playlist) => {
  1315. if (err) {
  1316. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1317. this.log(
  1318. "ERROR",
  1319. "PLAYLIST_UPDATE_PRIVACY",
  1320. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1321. );
  1322. return cb({ status: "failure", message: err });
  1323. }
  1324. this.log(
  1325. "SUCCESS",
  1326. "PLAYLIST_UPDATE_PRIVACY",
  1327. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  1328. );
  1329. CacheModule.runJob("PUB", {
  1330. channel: "playlist.updatePrivacy",
  1331. value: {
  1332. userId: session.userId,
  1333. playlist
  1334. }
  1335. });
  1336. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1337. userId: session.userId,
  1338. type: "playlist__edit_privacy",
  1339. payload: {
  1340. message: `Changed privacy of playlist <playlistId>${playlist.displayName}</playlistId> to ${privacy}`,
  1341. playlistId
  1342. }
  1343. });
  1344. return cb({
  1345. status: "success",
  1346. message: "Playlist has been successfully updated"
  1347. });
  1348. }
  1349. );
  1350. }),
  1351. /**
  1352. * Deletes all orphaned station playlists
  1353. *
  1354. * @param {object} session - the session object automatically added by socket.io
  1355. * @param {Function} cb - gets called with the result
  1356. */
  1357. deleteOrphanedStationPlaylists: isAdminRequired(async function index(session, cb) {
  1358. async.waterfall(
  1359. [
  1360. next => {
  1361. PlaylistsModule.runJob("DELETE_ORPHANED_STATION_PLAYLISTS", {}, this)
  1362. .then(() => next())
  1363. .catch(next);
  1364. }
  1365. ],
  1366. async err => {
  1367. if (err) {
  1368. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1369. this.log(
  1370. "ERROR",
  1371. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1372. `Deleting orphaned station playlists failed. "${err}"`
  1373. );
  1374. return cb({ status: "failure", message: err });
  1375. }
  1376. this.log(
  1377. "SUCCESS",
  1378. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1379. "Deleting orphaned station playlists successfull."
  1380. );
  1381. return cb({ status: "success", message: "Success" });
  1382. }
  1383. );
  1384. }),
  1385. /**
  1386. * Deletes all orphaned genre playlists
  1387. *
  1388. * @param {object} session - the session object automatically added by socket.io
  1389. * @param {Function} cb - gets called with the result
  1390. */
  1391. deleteOrphanedGenrePlaylists: isAdminRequired(async function index(session, cb) {
  1392. async.waterfall(
  1393. [
  1394. next => {
  1395. PlaylistsModule.runJob("DELETE_ORPHANED_GENRE_PLAYLISTS", {}, this)
  1396. .then(() => next())
  1397. .catch(next);
  1398. }
  1399. ],
  1400. async err => {
  1401. if (err) {
  1402. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1403. this.log(
  1404. "ERROR",
  1405. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1406. `Deleting orphaned genre playlists failed. "${err}"`
  1407. );
  1408. return cb({ status: "failure", message: err });
  1409. }
  1410. this.log(
  1411. "SUCCESS",
  1412. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1413. "Deleting orphaned genre playlists successfull."
  1414. );
  1415. return cb({ status: "success", message: "Success" });
  1416. }
  1417. );
  1418. }),
  1419. /**
  1420. * Requests orpahned playlist songs
  1421. *
  1422. * @param {object} session - the session object automatically added by socket.io
  1423. * @param {Function} cb - gets called with the result
  1424. */
  1425. requestOrphanedPlaylistSongs: isAdminRequired(async function index(session, cb) {
  1426. async.waterfall(
  1427. [
  1428. next => {
  1429. SongsModule.runJob("REQUEST_ORPHANED_PLAYLIST_SONGS", {}, this)
  1430. .then(() => next())
  1431. .catch(next);
  1432. }
  1433. ],
  1434. async err => {
  1435. if (err) {
  1436. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1437. this.log(
  1438. "ERROR",
  1439. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1440. `Requesting orphaned playlist songs failed. "${err}"`
  1441. );
  1442. return cb({ status: "failure", message: err });
  1443. }
  1444. this.log(
  1445. "SUCCESS",
  1446. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1447. "Requesting orphaned playlist songs was successfull."
  1448. );
  1449. return cb({ status: "success", message: "Success" });
  1450. }
  1451. );
  1452. })
  1453. };