playlists.js 56 KB

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