playlists.js 51 KB

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