playlists.js 52 KB

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