playlists.js 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845
  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. ActivitiesModule.runJob("ADD_ACTIVITY", {
  861. userId: session.userId,
  862. type: "playlist__add_song",
  863. payload: {
  864. message: `Added <youtubeId>${songName}</youtubeId> to playlist <playlistId>${playlist.displayName}</playlistId>`,
  865. thumbnail: newSong.thumbnail,
  866. playlistId,
  867. youtubeId
  868. }
  869. });
  870. }
  871. StationsModule.runJob("GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST", { playlistId })
  872. .then(response => {
  873. response.stationIds.forEach(stationId => {
  874. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  875. });
  876. })
  877. .catch();
  878. CacheModule.runJob("PUB", {
  879. channel: "playlist.addSong",
  880. value: {
  881. playlistId: playlist._id,
  882. song: newSong,
  883. userId: session.userId,
  884. privacy: playlist.privacy
  885. }
  886. });
  887. return cb({
  888. status: "success",
  889. message: "Song has been successfully added to the playlist",
  890. data: { songs: playlist.songs }
  891. });
  892. }
  893. );
  894. }),
  895. /**
  896. * Adds a set of songs to a private playlist
  897. *
  898. * @param {object} session - the session object automatically added by the websocket
  899. * @param {string} url - the url of the the YouTube playlist
  900. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  901. * @param {boolean} musicOnly - whether to only add music to the playlist
  902. * @param {Function} cb - gets called with the result
  903. */
  904. addSetToPlaylist: isLoginRequired(function addSetToPlaylist(session, url, playlistId, musicOnly, cb) {
  905. let videosInPlaylistTotal = 0;
  906. let songsInPlaylistTotal = 0;
  907. let addSongsStats = null;
  908. const addedSongs = [];
  909. async.waterfall(
  910. [
  911. next => {
  912. YouTubeModule.runJob("GET_PLAYLIST", { url, musicOnly }, this)
  913. .then(res => {
  914. if (res.filteredSongs) {
  915. videosInPlaylistTotal = res.songs.length;
  916. songsInPlaylistTotal = res.filteredSongs.length;
  917. } else {
  918. songsInPlaylistTotal = videosInPlaylistTotal = res.songs.length;
  919. }
  920. next(null, res.songs);
  921. })
  922. .catch(err => {
  923. next(err);
  924. });
  925. },
  926. (youtubeIds, next) => {
  927. let successful = 0;
  928. let failed = 0;
  929. let alreadyInPlaylist = 0;
  930. if (youtubeIds.length === 0) next();
  931. async.eachLimit(
  932. youtubeIds,
  933. 1,
  934. (youtubeId, next) => {
  935. WSModule.runJob(
  936. "RUN_ACTION2",
  937. {
  938. session,
  939. namespace: "playlists",
  940. action: "addSongToPlaylist",
  941. args: [true, youtubeId, playlistId]
  942. },
  943. this
  944. )
  945. .then(res => {
  946. if (res.status === "success") {
  947. successful += 1;
  948. addedSongs.push(youtubeId);
  949. } else failed += 1;
  950. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  951. })
  952. .catch(() => {
  953. failed += 1;
  954. })
  955. .finally(() => next());
  956. },
  957. () => {
  958. addSongsStats = { successful, failed, alreadyInPlaylist };
  959. next(null);
  960. }
  961. );
  962. },
  963. next => {
  964. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  965. .then(playlist => next(null, playlist))
  966. .catch(next);
  967. },
  968. (playlist, next) => {
  969. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found.");
  970. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  971. return next(null, playlist);
  972. }
  973. ],
  974. async (err, playlist) => {
  975. if (err) {
  976. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  977. this.log(
  978. "ERROR",
  979. "PLAYLIST_IMPORT",
  980. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  981. );
  982. return cb({ status: "error", message: err });
  983. }
  984. ActivitiesModule.runJob("ADD_ACTIVITY", {
  985. userId: session.userId,
  986. type: "playlist__import_playlist",
  987. payload: {
  988. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  989. playlistId
  990. }
  991. });
  992. this.log(
  993. "SUCCESS",
  994. "PLAYLIST_IMPORT",
  995. `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}.`
  996. );
  997. return cb({
  998. status: "success",
  999. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  1000. data: {
  1001. songs: playlist.songs,
  1002. stats: {
  1003. videosInPlaylistTotal,
  1004. songsInPlaylistTotal
  1005. }
  1006. }
  1007. });
  1008. }
  1009. );
  1010. }),
  1011. /**
  1012. * Removes a song from a private playlist
  1013. *
  1014. * @param {object} session - the session object automatically added by the websocket
  1015. * @param {string} youtubeId - the youtube id of the song we are removing from the private playlist
  1016. * @param {string} playlistId - the id of the playlist we are removing the song from
  1017. * @param {Function} cb - gets called with the result
  1018. */
  1019. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(session, youtubeId, playlistId, cb) {
  1020. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1021. async.waterfall(
  1022. [
  1023. next => {
  1024. if (!youtubeId || typeof youtubeId !== "string") return next("Invalid song id.");
  1025. if (!playlistId || typeof youtubeId !== "string") return next("Invalid playlist id.");
  1026. return next();
  1027. },
  1028. // remove song from playlist
  1029. next => playlistModel.updateOne({ _id: playlistId }, { $pull: { songs: { youtubeId } } }, next),
  1030. // update cache representation of the playlist
  1031. (res, next) => {
  1032. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1033. .then(playlist => next(null, playlist))
  1034. .catch(next);
  1035. },
  1036. (playlist, next) => {
  1037. StationsModule.runJob("GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST", { playlistId })
  1038. .then(response => {
  1039. response.stationIds.forEach(stationId => {
  1040. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1041. });
  1042. })
  1043. .catch();
  1044. SongsModule.runJob("GET_SONG_FROM_YOUTUBE_ID", { youtubeId }, this)
  1045. .then(res =>
  1046. next(null, playlist, {
  1047. title: res.song.title,
  1048. thumbnail: res.song.thumbnail,
  1049. artists: res.song.artists
  1050. })
  1051. )
  1052. .catch(() => {
  1053. YouTubeModule.runJob("GET_SONG", { youtubeId }, this)
  1054. .then(response => next(null, playlist, response.song))
  1055. .catch(next);
  1056. });
  1057. },
  1058. (playlist, youtubeSong, next) => {
  1059. const songName = youtubeSong.artists
  1060. ? `${youtubeSong.title} by ${youtubeSong.artists.join(", ")}`
  1061. : youtubeSong.title;
  1062. if (playlist.displayName !== "Liked Songs" && playlist.displayName !== "Disliked Songs") {
  1063. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1064. userId: session.userId,
  1065. type: "playlist__remove_song",
  1066. payload: {
  1067. message: `Removed <youtubeId>${songName}</youtubeId> from playlist <playlistId>${playlist.displayName}</playlistId>`,
  1068. thumbnail: youtubeSong.thumbnail,
  1069. playlistId,
  1070. youtubeId
  1071. }
  1072. });
  1073. }
  1074. return next(null, playlist);
  1075. }
  1076. ],
  1077. async (err, playlist) => {
  1078. if (err) {
  1079. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1080. this.log(
  1081. "ERROR",
  1082. "PLAYLIST_REMOVE_SONG",
  1083. `Removing song "${youtubeId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1084. );
  1085. return cb({ status: "error", message: err });
  1086. }
  1087. this.log(
  1088. "SUCCESS",
  1089. "PLAYLIST_REMOVE_SONG",
  1090. `Successfully removed song "${youtubeId}" from private playlist "${playlistId}" for user "${session.userId}".`
  1091. );
  1092. CacheModule.runJob("PUB", {
  1093. channel: "playlist.removeSong",
  1094. value: {
  1095. playlistId: playlist._id,
  1096. youtubeId,
  1097. userId: session.userId,
  1098. privacy: playlist.privacy
  1099. }
  1100. });
  1101. return cb({
  1102. status: "success",
  1103. message: "Song has been successfully removed from playlist",
  1104. data: { songs: playlist.songs }
  1105. });
  1106. }
  1107. );
  1108. }),
  1109. /**
  1110. * Updates the displayName of a private playlist
  1111. *
  1112. * @param {object} session - the session object automatically added by the websocket
  1113. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  1114. * @param {Function} cb - gets called with the result
  1115. */
  1116. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  1117. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1118. async.waterfall(
  1119. [
  1120. next => {
  1121. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1122. .then(playlist => next(null, playlist))
  1123. .catch(next);
  1124. },
  1125. (playlist, next) => {
  1126. if (!playlist.isUserModifiable) return next("Playlist cannot be modified.");
  1127. return next(null);
  1128. },
  1129. next => {
  1130. playlistModel.updateOne(
  1131. { _id: playlistId, createdBy: session.userId },
  1132. { $set: { displayName } },
  1133. { runValidators: true },
  1134. next
  1135. );
  1136. },
  1137. (res, next) => {
  1138. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1139. .then(playlist => next(null, playlist))
  1140. .catch(next);
  1141. }
  1142. ],
  1143. async (err, playlist) => {
  1144. if (err) {
  1145. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1146. this.log(
  1147. "ERROR",
  1148. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1149. `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1150. );
  1151. return cb({ status: "error", message: err });
  1152. }
  1153. this.log(
  1154. "SUCCESS",
  1155. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1156. `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${session.userId}".`
  1157. );
  1158. CacheModule.runJob("PUB", {
  1159. channel: "playlist.updateDisplayName",
  1160. value: {
  1161. playlistId,
  1162. displayName,
  1163. userId: session.userId,
  1164. privacy: playlist.privacy
  1165. }
  1166. });
  1167. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1168. userId: session.userId,
  1169. type: "playlist__edit_display_name",
  1170. payload: {
  1171. message: `Changed display name of playlist <playlistId>${displayName}</playlistId>`,
  1172. playlistId
  1173. }
  1174. });
  1175. return cb({
  1176. status: "success",
  1177. message: "Playlist has been successfully updated"
  1178. });
  1179. }
  1180. );
  1181. }),
  1182. /**
  1183. * Removes a private playlist
  1184. *
  1185. * @param {object} session - the session object automatically added by the websocket
  1186. * @param {string} playlistId - the id of the playlist we are moving the song to the top from
  1187. * @param {Function} cb - gets called with the result
  1188. */
  1189. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1190. // const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1191. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1192. async.waterfall(
  1193. [
  1194. next => {
  1195. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1196. .then(playlist => next(null, playlist))
  1197. .catch(next);
  1198. },
  1199. (playlist, next) => {
  1200. if (!playlist.isUserModifiable) return next("Playlist cannot be removed.");
  1201. return next(null, playlist);
  1202. },
  1203. (playlist, next) => {
  1204. userModel.updateOne(
  1205. { _id: playlist.createdBy },
  1206. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1207. err => next(err, playlist)
  1208. );
  1209. },
  1210. (playlist, next) => {
  1211. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1212. .then(() => next(null, playlist))
  1213. .catch(next);
  1214. }
  1215. // (playlist, next) => {
  1216. // stationModel.find({ privatePlaylist: playlistId }, (err, res) => {
  1217. // next(err, playlist, res);
  1218. // });
  1219. // },
  1220. // (playlist, stations, next) => {
  1221. // async.each(
  1222. // stations,
  1223. // (station, next) => {
  1224. // async.waterfall(
  1225. // [
  1226. // next => {
  1227. // stationModel.updateOne(
  1228. // { _id: station._id },
  1229. // { $set: { privatePlaylist: null } },
  1230. // { runValidators: true },
  1231. // next
  1232. // );
  1233. // },
  1234. // (res, next) => {
  1235. // if (!station.partyMode) {
  1236. // moduleManager.modules.stations
  1237. // .runJob("UPDATE_STATION", { stationId: station._id }, this)
  1238. // .then(station => next(null, station))
  1239. // .catch(next);
  1240. // CacheModule.runJob("PUB", {
  1241. // channel: "privatePlaylist.selected",
  1242. // value: {
  1243. // playlistId: null,
  1244. // stationId: station._id
  1245. // }
  1246. // });
  1247. // } else next();
  1248. // }
  1249. // ],
  1250. // () => next()
  1251. // );
  1252. // },
  1253. // () => next(null, playlist)
  1254. // );
  1255. // }
  1256. ],
  1257. async (err, playlist) => {
  1258. if (err) {
  1259. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1260. this.log(
  1261. "ERROR",
  1262. "PLAYLIST_REMOVE",
  1263. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1264. );
  1265. return cb({ status: "error", message: err });
  1266. }
  1267. this.log(
  1268. "SUCCESS",
  1269. "PLAYLIST_REMOVE",
  1270. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1271. );
  1272. CacheModule.runJob("PUB", {
  1273. channel: "playlist.delete",
  1274. value: {
  1275. userId: session.userId,
  1276. playlistId
  1277. }
  1278. });
  1279. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1280. userId: playlist.createdBy,
  1281. type: "playlist__remove",
  1282. payload: {
  1283. message: `Removed playlist ${playlist.displayName}`
  1284. }
  1285. });
  1286. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1287. return cb({
  1288. status: "success",
  1289. message: "Playlist successfully removed"
  1290. });
  1291. }
  1292. );
  1293. }),
  1294. /**
  1295. * Updates the privacy of a private playlist
  1296. *
  1297. * @param {object} session - the session object automatically added by the websocket
  1298. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1299. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1300. * @param {Function} cb - gets called with the result
  1301. */
  1302. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  1303. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1304. async.waterfall(
  1305. [
  1306. next => {
  1307. playlistModel.updateOne(
  1308. { _id: playlistId, createdBy: session.userId },
  1309. { $set: { privacy } },
  1310. { runValidators: true },
  1311. next
  1312. );
  1313. },
  1314. (res, next) => {
  1315. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1316. .then(playlist => next(null, playlist))
  1317. .catch(next);
  1318. }
  1319. ],
  1320. async (err, playlist) => {
  1321. if (err) {
  1322. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1323. this.log(
  1324. "ERROR",
  1325. "PLAYLIST_UPDATE_PRIVACY",
  1326. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1327. );
  1328. return cb({ status: "error", message: err });
  1329. }
  1330. this.log(
  1331. "SUCCESS",
  1332. "PLAYLIST_UPDATE_PRIVACY",
  1333. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  1334. );
  1335. CacheModule.runJob("PUB", {
  1336. channel: "playlist.updatePrivacy",
  1337. value: {
  1338. userId: session.userId,
  1339. playlist
  1340. }
  1341. });
  1342. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1343. userId: session.userId,
  1344. type: "playlist__edit_privacy",
  1345. payload: {
  1346. message: `Changed privacy of playlist <playlistId>${playlist.displayName}</playlistId> to ${privacy}`,
  1347. playlistId
  1348. }
  1349. });
  1350. return cb({
  1351. status: "success",
  1352. message: "Playlist has been successfully updated"
  1353. });
  1354. }
  1355. );
  1356. }),
  1357. /**
  1358. * Deletes all orphaned station playlists
  1359. *
  1360. * @param {object} session - the session object automatically added by socket.io
  1361. * @param {Function} cb - gets called with the result
  1362. */
  1363. deleteOrphanedStationPlaylists: isAdminRequired(async function index(session, cb) {
  1364. async.waterfall(
  1365. [
  1366. next => {
  1367. PlaylistsModule.runJob("DELETE_ORPHANED_STATION_PLAYLISTS", {}, this)
  1368. .then(() => next())
  1369. .catch(next);
  1370. }
  1371. ],
  1372. async err => {
  1373. if (err) {
  1374. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1375. this.log(
  1376. "ERROR",
  1377. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1378. `Deleting orphaned station playlists failed. "${err}"`
  1379. );
  1380. return cb({ status: "error", message: err });
  1381. }
  1382. this.log(
  1383. "SUCCESS",
  1384. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1385. "Deleting orphaned station playlists successful."
  1386. );
  1387. return cb({ status: "success", message: "Successfully deleted orphaned station playlists." });
  1388. }
  1389. );
  1390. }),
  1391. /**
  1392. * Deletes all orphaned genre playlists
  1393. *
  1394. * @param {object} session - the session object automatically added by socket.io
  1395. * @param {Function} cb - gets called with the result
  1396. */
  1397. deleteOrphanedGenrePlaylists: isAdminRequired(async function index(session, cb) {
  1398. async.waterfall(
  1399. [
  1400. next => {
  1401. PlaylistsModule.runJob("DELETE_ORPHANED_GENRE_PLAYLISTS", {}, this)
  1402. .then(() => next())
  1403. .catch(next);
  1404. }
  1405. ],
  1406. async err => {
  1407. if (err) {
  1408. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1409. this.log(
  1410. "ERROR",
  1411. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1412. `Deleting orphaned genre playlists failed. "${err}"`
  1413. );
  1414. return cb({ status: "error", message: err });
  1415. }
  1416. this.log(
  1417. "SUCCESS",
  1418. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1419. "Deleting orphaned genre playlists successful."
  1420. );
  1421. return cb({ status: "success", message: "Successfully deleted orphaned genre playlists." });
  1422. }
  1423. );
  1424. }),
  1425. /**
  1426. * Requests orpahned playlist songs
  1427. *
  1428. * @param {object} session - the session object automatically added by socket.io
  1429. * @param {Function} cb - gets called with the result
  1430. */
  1431. requestOrphanedPlaylistSongs: isAdminRequired(async function index(session, cb) {
  1432. async.waterfall(
  1433. [
  1434. next => {
  1435. SongsModule.runJob("REQUEST_ORPHANED_PLAYLIST_SONGS", {}, this)
  1436. .then(() => next())
  1437. .catch(next);
  1438. }
  1439. ],
  1440. async err => {
  1441. if (err) {
  1442. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1443. this.log(
  1444. "ERROR",
  1445. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1446. `Requesting orphaned playlist songs failed. "${err}"`
  1447. );
  1448. return cb({ status: "error", message: err });
  1449. }
  1450. this.log(
  1451. "SUCCESS",
  1452. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1453. "Requesting orphaned playlist songs was successful."
  1454. );
  1455. return cb({ status: "success", message: "Successfully requested orphaned playlist songs." });
  1456. }
  1457. );
  1458. }),
  1459. /**
  1460. * Clears and refills a station playlist
  1461. *
  1462. * @param {object} session - the session object automatically added by socket.io
  1463. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  1464. * @param {Function} cb - gets called with the result
  1465. */
  1466. clearAndRefillStationPlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  1467. async.waterfall(
  1468. [
  1469. next => {
  1470. if (!playlistId) next("Please specify a playlist id");
  1471. else {
  1472. PlaylistsModule.runJob("CLEAR_AND_REFILL_STATION_PLAYLIST", { playlistId }, this)
  1473. .then(() => {
  1474. next();
  1475. })
  1476. .catch(err => {
  1477. next(err);
  1478. });
  1479. }
  1480. }
  1481. ],
  1482. async err => {
  1483. if (err) {
  1484. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1485. this.log(
  1486. "ERROR",
  1487. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  1488. `Clearing and refilling station playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1489. );
  1490. return cb({ status: "error", message: err });
  1491. }
  1492. this.log(
  1493. "SUCCESS",
  1494. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  1495. `Successfully cleared and refilled station playlist "${playlistId}" for user "${session.userId}".`
  1496. );
  1497. return cb({
  1498. status: "success",
  1499. message: "Playlist has been successfully cleared and refilled"
  1500. });
  1501. }
  1502. );
  1503. }),
  1504. /**
  1505. * Clears and refills a genre playlist
  1506. *
  1507. * @param {object} session - the session object automatically added by socket.io
  1508. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  1509. * @param {Function} cb - gets called with the result
  1510. */
  1511. clearAndRefillGenrePlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  1512. async.waterfall(
  1513. [
  1514. next => {
  1515. if (!playlistId) next("Please specify a playlist id");
  1516. else {
  1517. PlaylistsModule.runJob("CLEAR_AND_REFILL_GENRE_PLAYLIST", { playlistId }, this)
  1518. .then(() => {
  1519. next();
  1520. })
  1521. .catch(err => {
  1522. next(err);
  1523. });
  1524. }
  1525. }
  1526. ],
  1527. async err => {
  1528. if (err) {
  1529. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1530. this.log(
  1531. "ERROR",
  1532. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  1533. `Clearing and refilling genre playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1534. );
  1535. return cb({ status: "error", message: err });
  1536. }
  1537. this.log(
  1538. "SUCCESS",
  1539. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  1540. `Successfully cleared and refilled genre playlist "${playlistId}" for user "${session.userId}".`
  1541. );
  1542. return cb({
  1543. status: "success",
  1544. message: "Playlist has been successfully cleared and refilled"
  1545. });
  1546. }
  1547. );
  1548. }),
  1549. /**
  1550. * Clears and refills all station playlists
  1551. *
  1552. * @param {object} session - the session object automatically added by socket.io
  1553. * @param {Function} cb - gets called with the result
  1554. */
  1555. clearAndRefillAllStationPlaylists: isAdminRequired(async function index(session, cb) {
  1556. async.waterfall(
  1557. [
  1558. next => {
  1559. PlaylistsModule.runJob("GET_ALL_STATION_PLAYLISTS", {}, this)
  1560. .then(response => {
  1561. next(null, response.playlists);
  1562. })
  1563. .catch(err => {
  1564. next(err);
  1565. });
  1566. },
  1567. (playlists, next) => {
  1568. async.eachLimit(
  1569. playlists,
  1570. 1,
  1571. (playlist, next) => {
  1572. PlaylistsModule.runJob(
  1573. "CLEAR_AND_REFILL_STATION_PLAYLIST",
  1574. { playlistId: playlist._id },
  1575. this
  1576. )
  1577. .then(() => {
  1578. next();
  1579. })
  1580. .catch(err => {
  1581. next(err);
  1582. });
  1583. },
  1584. next
  1585. );
  1586. }
  1587. ],
  1588. async err => {
  1589. if (err) {
  1590. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1591. this.log(
  1592. "ERROR",
  1593. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  1594. `Clearing and refilling all station playlists failed for user "${session.userId}". "${err}"`
  1595. );
  1596. return cb({ status: "error", message: err });
  1597. }
  1598. this.log(
  1599. "SUCCESS",
  1600. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  1601. `Successfully cleared and refilled all station playlists for user "${session.userId}".`
  1602. );
  1603. return cb({
  1604. status: "success",
  1605. message: "Playlists have been successfully cleared and refilled"
  1606. });
  1607. }
  1608. );
  1609. }),
  1610. /**
  1611. * Clears and refills all genre playlists
  1612. *
  1613. * @param {object} session - the session object automatically added by socket.io
  1614. * @param {Function} cb - gets called with the result
  1615. */
  1616. clearAndRefillAllGenrePlaylists: isAdminRequired(async function index(session, cb) {
  1617. async.waterfall(
  1618. [
  1619. next => {
  1620. PlaylistsModule.runJob("GET_ALL_GENRE_PLAYLISTS", {}, this)
  1621. .then(response => {
  1622. next(null, response.playlists);
  1623. })
  1624. .catch(err => {
  1625. next(err);
  1626. });
  1627. },
  1628. (playlists, next) => {
  1629. async.eachLimit(
  1630. playlists,
  1631. 1,
  1632. (playlist, next) => {
  1633. PlaylistsModule.runJob(
  1634. "CLEAR_AND_REFILL_GENRE_PLAYLIST",
  1635. { playlistId: playlist._id },
  1636. this
  1637. )
  1638. .then(() => {
  1639. next();
  1640. })
  1641. .catch(err => {
  1642. next(err);
  1643. });
  1644. },
  1645. next
  1646. );
  1647. }
  1648. ],
  1649. async err => {
  1650. if (err) {
  1651. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1652. this.log(
  1653. "ERROR",
  1654. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  1655. `Clearing and refilling all genre playlists failed for user "${session.userId}". "${err}"`
  1656. );
  1657. return cb({ status: "error", message: err });
  1658. }
  1659. this.log(
  1660. "SUCCESS",
  1661. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  1662. `Successfully cleared and refilled all genre playlists for user "${session.userId}".`
  1663. );
  1664. return cb({
  1665. status: "success",
  1666. message: "Playlists have been successfully cleared and refilled"
  1667. });
  1668. }
  1669. );
  1670. })
  1671. };