playlists.js 68 KB

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