playlists.js 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445
  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. (user, next) => {
  493. if (!user) next("User not found");
  494. else {
  495. const { preferences } = user;
  496. const { orderOfPlaylists } = preferences;
  497. const match = {
  498. createdBy: userId,
  499. type: { $in: ["user", "user-liked", "user-disliked"] }
  500. };
  501. // if a playlist order exists
  502. if (orderOfPlaylists > 0) match._id = { $in: orderOfPlaylists };
  503. playlistModel
  504. .aggregate()
  505. .match(match)
  506. .addFields({
  507. weight: { $indexOfArray: [orderOfPlaylists, "$_id"] }
  508. })
  509. .sort({ weight: 1 })
  510. .exec(next);
  511. }
  512. },
  513. (playlists, next) => {
  514. if (session.userId === userId) return next(null, playlists); // user requesting playlists is the owner of the playlists
  515. const filteredPlaylists = [];
  516. return async.each(
  517. playlists,
  518. (playlist, nextPlaylist) => {
  519. if (playlist.privacy === "public") filteredPlaylists.push(playlist);
  520. return nextPlaylist();
  521. },
  522. () => next(null, filteredPlaylists)
  523. );
  524. }
  525. ],
  526. async (err, playlists) => {
  527. if (err) {
  528. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  529. this.log(
  530. "ERROR",
  531. "PLAYLIST_INDEX_FOR_USER",
  532. `Indexing playlists for user "${userId}" failed. "${err}"`
  533. );
  534. return cb({ status: "error", message: err });
  535. }
  536. this.log("SUCCESS", "PLAYLIST_INDEX_FOR_USER", `Successfully indexed playlists for user "${userId}".`);
  537. return cb({
  538. status: "success",
  539. data: { playlists }
  540. });
  541. }
  542. );
  543. },
  544. /**
  545. * Gets all playlists for the user requesting it
  546. *
  547. * @param {object} session - the session object automatically added by the websocket
  548. * @param {Function} cb - gets called with the result
  549. */
  550. indexMyPlaylists: isLoginRequired(async function indexMyPlaylists(session, cb) {
  551. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  552. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  553. async.waterfall(
  554. [
  555. next => {
  556. userModel.findById(session.userId).select({ "preferences.orderOfPlaylists": -1 }).exec(next);
  557. },
  558. (user, next) => {
  559. if (!user) next("User not found");
  560. else {
  561. const { preferences } = user;
  562. const { orderOfPlaylists } = preferences;
  563. const match = {
  564. createdBy: session.userId,
  565. type: { $in: ["user", "user-liked", "user-disliked"] }
  566. };
  567. // if a playlist order exists
  568. if (orderOfPlaylists > 0) match._id = { $in: orderOfPlaylists };
  569. playlistModel
  570. .aggregate()
  571. .match(match)
  572. .addFields({
  573. weight: { $indexOfArray: [orderOfPlaylists, "$_id"] }
  574. })
  575. .sort({ weight: 1 })
  576. .exec(next);
  577. }
  578. }
  579. ],
  580. async (err, playlists) => {
  581. if (err) {
  582. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  583. this.log(
  584. "ERROR",
  585. "PLAYLIST_INDEX_FOR_ME",
  586. `Indexing playlists for user "${session.userId}" failed. "${err}"`
  587. );
  588. return cb({ status: "error", message: err });
  589. }
  590. this.log(
  591. "SUCCESS",
  592. "PLAYLIST_INDEX_FOR_ME",
  593. `Successfully indexed playlists for user "${session.userId}".`
  594. );
  595. return cb({
  596. status: "success",
  597. data: { playlists }
  598. });
  599. }
  600. );
  601. }),
  602. /**
  603. * Gets all playlists playlists
  604. *
  605. * @param {object} session - the session object automatically added by the websocket
  606. * @param {Function} cb - gets called with the result
  607. */
  608. indexFeaturedPlaylists: isLoginRequired(async function indexMyPlaylists(session, cb) {
  609. async.waterfall(
  610. [
  611. next => {
  612. const featuredPlaylistIds = config.get("featuredPlaylists");
  613. if (featuredPlaylistIds.length === 0) next(true, []);
  614. else next(null, featuredPlaylistIds);
  615. },
  616. (featuredPlaylistIds, next) => {
  617. const featuredPlaylists = [];
  618. async.eachLimit(
  619. featuredPlaylistIds,
  620. 1,
  621. (playlistId, next) => {
  622. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  623. .then(playlist => {
  624. if (playlist.privacy === "public") featuredPlaylists.push(playlist);
  625. next();
  626. })
  627. .catch(next);
  628. },
  629. err => {
  630. next(err, featuredPlaylists);
  631. }
  632. );
  633. }
  634. ],
  635. async (err, playlists) => {
  636. if (err && err !== true) {
  637. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  638. this.log("ERROR", "PLAYLIST_INDEX_FEATURED", `Indexing featured playlists failed. "${err}"`);
  639. return cb({ status: "error", message: err });
  640. }
  641. this.log("SUCCESS", "PLAYLIST_INDEX_FEATURED", `Successfully indexed featured playlists.`);
  642. return cb({
  643. status: "success",
  644. data: { playlists }
  645. });
  646. }
  647. );
  648. }),
  649. /**
  650. * Creates a new private playlist
  651. *
  652. * @param {object} session - the session object automatically added by the websocket
  653. * @param {object} data - the data for the new private playlist
  654. * @param {Function} cb - gets called with the result
  655. */
  656. create: isLoginRequired(async function create(session, data, cb) {
  657. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  658. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  659. const blacklist = ["liked songs", "likedsongs", "disliked songs", "dislikedsongs"];
  660. async.waterfall(
  661. [
  662. next => (data ? next() : cb({ status: "error", message: "Invalid data" })),
  663. next => {
  664. const { displayName, songs, privacy } = data;
  665. if (blacklist.indexOf(displayName.toLowerCase()) !== -1)
  666. return next("That playlist name is blacklisted. Please use a different name.");
  667. return playlistModel.create(
  668. {
  669. displayName,
  670. songs,
  671. privacy,
  672. createdBy: session.userId,
  673. createdAt: Date.now(),
  674. createdFor: null,
  675. type: "user"
  676. },
  677. next
  678. );
  679. },
  680. (playlist, next) => {
  681. userModel.updateOne(
  682. { _id: session.userId },
  683. { $push: { "preferences.orderOfPlaylists": playlist._id } },
  684. err => {
  685. if (err) return next(err);
  686. return next(null, playlist);
  687. }
  688. );
  689. }
  690. ],
  691. async (err, playlist) => {
  692. if (err) {
  693. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  694. this.log(
  695. "ERROR",
  696. "PLAYLIST_CREATE",
  697. `Creating private playlist failed for user "${session.userId}". "${err}"`
  698. );
  699. return cb({ status: "error", message: err });
  700. }
  701. CacheModule.runJob("PUB", {
  702. channel: "playlist.create",
  703. value: playlist
  704. });
  705. ActivitiesModule.runJob("ADD_ACTIVITY", {
  706. userId: playlist.createdBy,
  707. type: "playlist__create",
  708. payload: {
  709. message: `Created playlist <playlistId>${playlist.displayName}</playlistId>`,
  710. playlistId: playlist._id
  711. }
  712. });
  713. this.log(
  714. "SUCCESS",
  715. "PLAYLIST_CREATE",
  716. `Successfully created private playlist for user "${session.userId}".`
  717. );
  718. return cb({
  719. status: "success",
  720. message: "Successfully created playlist",
  721. data: {
  722. playlistId: playlist._id
  723. }
  724. });
  725. }
  726. );
  727. }),
  728. /**
  729. * Gets a playlist from id
  730. *
  731. * @param {object} session - the session object automatically added by the websocket
  732. * @param {string} playlistId - the id of the playlist we are getting
  733. * @param {Function} cb - gets called with the result
  734. */
  735. getPlaylist: function getPlaylist(session, playlistId, cb) {
  736. async.waterfall(
  737. [
  738. next => {
  739. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  740. .then(playlist => next(null, playlist))
  741. .catch(next);
  742. },
  743. (playlist, next) => {
  744. if (!playlist) return next("Playlist not found");
  745. if (playlist.privacy !== "public" && playlist.createdBy !== session.userId) {
  746. if (session)
  747. // check if user requested to get a playlist is an admin
  748. return DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  749. userModel.findOne({ _id: session.userId }, (err, user) => {
  750. if (user && user.role === "admin") return next(null, playlist);
  751. return next("User unauthorised to view playlist.");
  752. });
  753. });
  754. return next("User unauthorised to view playlist.");
  755. }
  756. return next(null, playlist);
  757. }
  758. ],
  759. async (err, playlist) => {
  760. if (err) {
  761. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  762. this.log(
  763. "ERROR",
  764. "PLAYLIST_GET",
  765. `Getting private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  766. );
  767. return cb({ status: "error", message: err });
  768. }
  769. this.log(
  770. "SUCCESS",
  771. "PLAYLIST_GET",
  772. `Successfully got private playlist "${playlistId}" for user "${session.userId}".`
  773. );
  774. return cb({
  775. status: "success",
  776. data: { playlist }
  777. });
  778. }
  779. );
  780. },
  781. /**
  782. * Gets a playlist from station id
  783. *
  784. * @param {object} session - the session object automatically added by the websocket
  785. * @param {string} stationId - the id of the station we are getting
  786. * @param {string} includeSongs - include songs
  787. * @param {Function} cb - gets called with the result
  788. */
  789. getPlaylistForStation: function getPlaylist(session, stationId, includeSongs, cb) {
  790. async.waterfall(
  791. [
  792. next => {
  793. PlaylistsModule.runJob("GET_STATION_PLAYLIST", { stationId, includeSongs }, this)
  794. .then(response => next(null, response.playlist))
  795. .catch(next);
  796. },
  797. (playlist, next) => {
  798. if (!playlist) return next("Playlist not found");
  799. if (playlist.privacy !== "public" && playlist.createdBy !== session.userId) {
  800. if (session)
  801. // check if user requested to get a playlist is an admin
  802. return DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  803. userModel.findOne({ _id: session.userId }, (err, user) => {
  804. if (user && user.role === "admin") return next(null, playlist);
  805. return next("User unauthorised to view playlist.");
  806. });
  807. });
  808. return next("User unauthorised to view playlist.");
  809. }
  810. return next(null, playlist);
  811. }
  812. ],
  813. async (err, playlist) => {
  814. if (err) {
  815. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  816. this.log(
  817. "ERROR",
  818. "PLAYLIST_GET",
  819. `Getting playlist for station "${stationId}" failed for user "${session.userId}". "${err}"`
  820. );
  821. return cb({ status: "error", message: err });
  822. }
  823. this.log(
  824. "SUCCESS",
  825. "PLAYLIST_GET",
  826. `Successfully got playlist for station "${stationId}" for user "${session.userId}".`
  827. );
  828. return cb({
  829. status: "success",
  830. data: { playlist }
  831. });
  832. }
  833. );
  834. },
  835. /**
  836. * Shuffles songs in a private playlist
  837. *
  838. * @param {object} session - the session object automatically added by the websocket
  839. * @param {string} playlistId - the id of the playlist we are updating
  840. * @param {Function} cb - gets called with the result
  841. */
  842. shuffle: isLoginRequired(async function shuffle(session, playlistId, cb) {
  843. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  844. async.waterfall(
  845. [
  846. next => {
  847. if (!playlistId) return next("No playlist id.");
  848. return next();
  849. },
  850. next => {
  851. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  852. .then(playlist => {
  853. if (!playlist || playlist.createdBy !== session.userId)
  854. return next("Something went wrong when trying to get the playlist");
  855. return next(null, playlist);
  856. })
  857. .catch(next);
  858. },
  859. (playlist, next) => {
  860. if (!playlist.isUserModifiable) return next("Playlist cannot be shuffled.");
  861. return UtilsModule.runJob("SHUFFLE_SONG_POSITIONS", { array: playlist.songs }, this)
  862. .then(result => next(null, result.array))
  863. .catch(next);
  864. },
  865. (songs, next) => {
  866. playlistModel.updateOne({ _id: playlistId }, { $set: { songs } }, { runValidators: true }, next);
  867. },
  868. (res, next) => {
  869. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  870. .then(playlist => next(null, playlist))
  871. .catch(next);
  872. }
  873. ],
  874. async (err, playlist) => {
  875. if (err) {
  876. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  877. this.log(
  878. "ERROR",
  879. "PLAYLIST_SHUFFLE",
  880. `Updating 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_SHUFFLE",
  887. `Successfully updated private playlist "${playlistId}" for user "${session.userId}".`
  888. );
  889. return cb({
  890. status: "success",
  891. message: "Successfully shuffled playlist.",
  892. data: { playlist }
  893. });
  894. }
  895. );
  896. }),
  897. /**
  898. * Changes the order (position) of a song in a playlist
  899. *
  900. * @param {object} session - the session object automatically added by the websocket
  901. * @param {string} playlistId - the id of the playlist we are targeting
  902. * @param {object} song - the song to be repositioned
  903. * @param {string} song.youtubeId - the youtube id of the song being repositioned
  904. * @param {string} song.newIndex - the new position of the song in the playlist
  905. * @param {...any} song.args - any other elements that would be included with a song item in a playlist
  906. * @param {Function} cb - gets called with the result
  907. */
  908. repositionSong: isLoginRequired(async function repositionSong(session, playlistId, song, cb) {
  909. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  910. async.waterfall(
  911. [
  912. next => {
  913. if (!playlistId) return next("Please provide a playlist.");
  914. if (!song || !song.youtubeId) return next("You must provide a song to reposition.");
  915. return next();
  916. },
  917. next => {
  918. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  919. .then(playlist => {
  920. if (!playlist || playlist.createdBy !== session.userId) {
  921. return DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  922. userModel.findOne({ _id: session.userId }, (err, user) => {
  923. if (user && user.role === "admin") return next();
  924. return next("Something went wrong when trying to get the playlist");
  925. });
  926. });
  927. }
  928. return next();
  929. })
  930. .catch(next);
  931. },
  932. // remove song from playlist
  933. next => {
  934. playlistModel.updateOne(
  935. { _id: playlistId },
  936. { $pull: { songs: { youtubeId: song.youtubeId } } },
  937. next
  938. );
  939. },
  940. // add song back to playlist (in new position)
  941. (res, next) => {
  942. playlistModel.updateOne(
  943. { _id: playlistId },
  944. { $push: { songs: { $each: [song], $position: song.newIndex } } },
  945. err => next(err)
  946. );
  947. },
  948. // update the cache with the new songs positioning
  949. next => {
  950. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  951. .then(playlist => next(null, playlist))
  952. .catch(next);
  953. }
  954. ],
  955. async err => {
  956. if (err) {
  957. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  958. this.log(
  959. "ERROR",
  960. "PLAYLIST_REPOSITION_SONG",
  961. `Repositioning song ${song.youtubeId} for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  962. );
  963. return cb({ status: "error", message: err });
  964. }
  965. this.log(
  966. "SUCCESS",
  967. "PLAYLIST_REPOSITION_SONG",
  968. `Successfully repositioned song ${song.youtubeId} for private playlist "${playlistId}" for user "${session.userId}".`
  969. );
  970. CacheModule.runJob("PUB", {
  971. channel: "playlist.repositionSong",
  972. value: {
  973. userId: session.userId,
  974. playlistId,
  975. song
  976. }
  977. });
  978. return cb({
  979. status: "success",
  980. message: "Successfully repositioned song"
  981. });
  982. }
  983. );
  984. }),
  985. /**
  986. * Adds a song to a private playlist
  987. *
  988. * @param {object} session - the session object automatically added by the websocket
  989. * @param {boolean} isSet - is the song part of a set of songs to be added
  990. * @param {string} youtubeId - the youtube id of the song we are trying to add
  991. * @param {string} playlistId - the id of the playlist we are adding the song to
  992. * @param {Function} cb - gets called with the result
  993. */
  994. addSongToPlaylist: isLoginRequired(async function addSongToPlaylist(session, isSet, youtubeId, playlistId, cb) {
  995. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  996. async.waterfall(
  997. [
  998. next => {
  999. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1000. .then(playlist => {
  1001. if (!playlist || playlist.createdBy !== session.userId) {
  1002. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1003. userModel.findOne({ _id: session.userId }, (err, user) => {
  1004. if (user && user.role === "admin") return next(null, playlist);
  1005. return next("Something went wrong when trying to get the playlist");
  1006. });
  1007. });
  1008. } else next(null, playlist);
  1009. })
  1010. .catch(next);
  1011. },
  1012. (playlist, next) => {
  1013. async.each(
  1014. playlist.songs,
  1015. (song, nextSong) => {
  1016. if (song.youtubeId === youtubeId) return next("That song is already in the playlist");
  1017. return nextSong();
  1018. },
  1019. err => next(err, playlist)
  1020. );
  1021. },
  1022. (playlist, next) => {
  1023. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1024. const oppositeType = playlist.type === "user-liked" ? "user-disliked" : "user-liked";
  1025. const oppositePlaylistName = oppositeType === "user-liked" ? "Liked Songs" : "Disliked Songs";
  1026. playlistModel.count(
  1027. { type: oppositeType, createdBy: session.userId, "songs.youtubeId": youtubeId },
  1028. (err, results) => {
  1029. if (err) next(err);
  1030. else if (results > 0)
  1031. next(
  1032. `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.`
  1033. );
  1034. else next();
  1035. }
  1036. );
  1037. } else next();
  1038. },
  1039. next => {
  1040. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1041. .then(UserModel => {
  1042. UserModel.findOne(
  1043. { _id: session.userId },
  1044. { "preferences.anonymousSongRequests": 1 },
  1045. next
  1046. );
  1047. })
  1048. .catch(next);
  1049. },
  1050. (user, next) => {
  1051. SongsModule.runJob(
  1052. "ENSURE_SONG_EXISTS_BY_YOUTUBE_ID",
  1053. {
  1054. youtubeId,
  1055. userId: user.preferences.anonymousSongRequests ? null : session.userId,
  1056. automaticallyRequested: true
  1057. },
  1058. this
  1059. )
  1060. .then(response => {
  1061. const { song } = response;
  1062. const { _id, title, artists, thumbnail, duration, status } = song;
  1063. next(null, {
  1064. _id,
  1065. youtubeId,
  1066. title,
  1067. artists,
  1068. thumbnail,
  1069. duration,
  1070. status
  1071. });
  1072. })
  1073. .catch(next);
  1074. },
  1075. (newSong, next) => {
  1076. playlistModel.updateOne(
  1077. { _id: playlistId },
  1078. { $push: { songs: newSong } },
  1079. { runValidators: true },
  1080. err => {
  1081. if (err) return next(err);
  1082. return PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1083. .then(playlist => next(null, playlist, newSong))
  1084. .catch(next);
  1085. }
  1086. );
  1087. },
  1088. (playlist, newSong, next) => {
  1089. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1090. SongsModule.runJob("RECALCULATE_SONG_RATINGS", {
  1091. songId: newSong._id,
  1092. youtubeId: newSong.youtubeId
  1093. })
  1094. .then(ratings => next(null, playlist, newSong, ratings))
  1095. .catch(next);
  1096. } else {
  1097. next(null, playlist, newSong, null);
  1098. }
  1099. }
  1100. ],
  1101. async (err, playlist, newSong, ratings) => {
  1102. if (err) {
  1103. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1104. this.log(
  1105. "ERROR",
  1106. "PLAYLIST_ADD_SONG",
  1107. `Adding song "${youtubeId}" to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1108. );
  1109. return cb({ status: "error", message: err });
  1110. }
  1111. this.log(
  1112. "SUCCESS",
  1113. "PLAYLIST_ADD_SONG",
  1114. `Successfully added song "${youtubeId}" to private playlist "${playlistId}" for user "${session.userId}".`
  1115. );
  1116. if (!isSet && playlist.type === "user" && playlist.privacy === "public") {
  1117. const songName = newSong.artists
  1118. ? `${newSong.title} by ${newSong.artists.join(", ")}`
  1119. : newSong.title;
  1120. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1121. userId: session.userId,
  1122. type: "playlist__add_song",
  1123. payload: {
  1124. message: `Added <youtubeId>${songName}</youtubeId> to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1125. thumbnail: newSong.thumbnail,
  1126. playlistId,
  1127. youtubeId
  1128. }
  1129. });
  1130. }
  1131. StationsModule.runJob("GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST", { playlistId })
  1132. .then(response => {
  1133. response.stationIds.forEach(stationId => {
  1134. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1135. });
  1136. })
  1137. .catch();
  1138. CacheModule.runJob("PUB", {
  1139. channel: "playlist.addSong",
  1140. value: {
  1141. playlistId: playlist._id,
  1142. song: newSong,
  1143. userId: session.userId,
  1144. privacy: playlist.privacy
  1145. }
  1146. });
  1147. CacheModule.runJob("PUB", {
  1148. channel: "playlist.updated",
  1149. value: { playlistId }
  1150. });
  1151. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1152. const { _id, youtubeId, title, artists, thumbnail } = newSong;
  1153. const { likes, dislikes } = ratings;
  1154. SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1155. if (playlist.type === "user-liked") {
  1156. CacheModule.runJob("PUB", {
  1157. channel: "song.like",
  1158. value: JSON.stringify({
  1159. youtubeId,
  1160. userId: session.userId,
  1161. likes,
  1162. dislikes
  1163. })
  1164. });
  1165. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1166. userId: session.userId,
  1167. type: "song__like",
  1168. payload: {
  1169. message: `Liked song <youtubeId>${title} by ${artists.join(", ")}</youtubeId>`,
  1170. youtubeId,
  1171. thumbnail
  1172. }
  1173. });
  1174. } else {
  1175. CacheModule.runJob("PUB", {
  1176. channel: "song.dislike",
  1177. value: JSON.stringify({
  1178. youtubeId,
  1179. userId: session.userId,
  1180. likes,
  1181. dislikes
  1182. })
  1183. });
  1184. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1185. userId: session.userId,
  1186. type: "song__dislike",
  1187. payload: {
  1188. message: `Disliked song <youtubeId>${title} by ${artists.join(", ")}</youtubeId>`,
  1189. youtubeId,
  1190. thumbnail
  1191. }
  1192. });
  1193. }
  1194. }
  1195. return cb({
  1196. status: "success",
  1197. message: "Song has been successfully added to the playlist",
  1198. data: { songs: playlist.songs }
  1199. });
  1200. }
  1201. );
  1202. }),
  1203. /**
  1204. * Adds a set of songs to a private playlist
  1205. *
  1206. * @param {object} session - the session object automatically added by the websocket
  1207. * @param {string} url - the url of the the YouTube playlist
  1208. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  1209. * @param {boolean} musicOnly - whether to only add music to the playlist
  1210. * @param {Function} cb - gets called with the result
  1211. */
  1212. addSetToPlaylist: isLoginRequired(function addSetToPlaylist(session, url, playlistId, musicOnly, cb) {
  1213. let videosInPlaylistTotal = 0;
  1214. let songsInPlaylistTotal = 0;
  1215. let addSongsStats = null;
  1216. const addedSongs = [];
  1217. async.waterfall(
  1218. [
  1219. next => {
  1220. YouTubeModule.runJob("GET_PLAYLIST", { url, musicOnly }, this)
  1221. .then(res => {
  1222. if (res.filteredSongs) {
  1223. videosInPlaylistTotal = res.songs.length;
  1224. songsInPlaylistTotal = res.filteredSongs.length;
  1225. } else {
  1226. songsInPlaylistTotal = videosInPlaylistTotal = res.songs.length;
  1227. }
  1228. next(null, res.songs);
  1229. })
  1230. .catch(err => {
  1231. next(err);
  1232. });
  1233. },
  1234. (youtubeIds, next) => {
  1235. let successful = 0;
  1236. let failed = 0;
  1237. let alreadyInPlaylist = 0;
  1238. let alreadyInLikedPlaylist = 0;
  1239. let alreadyInDislikedPlaylist = 0;
  1240. if (youtubeIds.length === 0) next();
  1241. async.eachLimit(
  1242. youtubeIds,
  1243. 1,
  1244. (youtubeId, next) => {
  1245. WSModule.runJob(
  1246. "RUN_ACTION2",
  1247. {
  1248. session,
  1249. namespace: "playlists",
  1250. action: "addSongToPlaylist",
  1251. args: [true, youtubeId, playlistId]
  1252. },
  1253. this
  1254. )
  1255. .then(res => {
  1256. if (res.status === "success") {
  1257. successful += 1;
  1258. addedSongs.push(youtubeId);
  1259. } else failed += 1;
  1260. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  1261. else if (
  1262. res.message ===
  1263. "That song is already in your Liked 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. alreadyInLikedPlaylist += 1;
  1268. else if (
  1269. res.message ===
  1270. "That song is already in your Disliked Songs playlist. " +
  1271. "A song cannot be in both the Liked Songs playlist " +
  1272. "and the Disliked Songs playlist at the same time."
  1273. )
  1274. alreadyInDislikedPlaylist += 1;
  1275. })
  1276. .catch(() => {
  1277. failed += 1;
  1278. })
  1279. .finally(() => next());
  1280. },
  1281. () => {
  1282. addSongsStats = {
  1283. successful,
  1284. failed,
  1285. alreadyInPlaylist,
  1286. alreadyInLikedPlaylist,
  1287. alreadyInDislikedPlaylist
  1288. };
  1289. next(null);
  1290. }
  1291. );
  1292. },
  1293. next => {
  1294. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1295. .then(playlist => next(null, playlist))
  1296. .catch(next);
  1297. },
  1298. (playlist, next) => {
  1299. if (!playlist || playlist.createdBy !== session.userId) {
  1300. return DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1301. userModel.findOne({ _id: session.userId }, (err, user) => {
  1302. if (user && user.role === "admin") return next(null, playlist);
  1303. return next("Something went wrong when trying to get the playlist");
  1304. });
  1305. });
  1306. }
  1307. return next(null, playlist);
  1308. }
  1309. ],
  1310. async (err, playlist) => {
  1311. if (err) {
  1312. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1313. this.log(
  1314. "ERROR",
  1315. "PLAYLIST_IMPORT",
  1316. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1317. );
  1318. return cb({ status: "error", message: err });
  1319. }
  1320. if (playlist.privacy === "public")
  1321. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1322. userId: session.userId,
  1323. type: "playlist__import_playlist",
  1324. payload: {
  1325. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1326. playlistId
  1327. }
  1328. });
  1329. this.log(
  1330. "SUCCESS",
  1331. "PLAYLIST_IMPORT",
  1332. `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}.`
  1333. );
  1334. return cb({
  1335. status: "success",
  1336. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  1337. data: {
  1338. songs: playlist.songs,
  1339. stats: {
  1340. videosInPlaylistTotal,
  1341. songsInPlaylistTotal,
  1342. alreadyInLikedPlaylist: addSongsStats.alreadyInLikedPlaylist,
  1343. alreadyInDislikedPlaylist: addSongsStats.alreadyInDislikedPlaylist
  1344. }
  1345. }
  1346. });
  1347. }
  1348. );
  1349. }),
  1350. /**
  1351. * Removes a song from a private playlist
  1352. *
  1353. * @param {object} session - the session object automatically added by the websocket
  1354. * @param {string} youtubeId - the youtube id of the song we are removing from the private playlist
  1355. * @param {string} playlistId - the id of the playlist we are removing the song from
  1356. * @param {Function} cb - gets called with the result
  1357. */
  1358. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(session, youtubeId, playlistId, cb) {
  1359. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1360. async.waterfall(
  1361. [
  1362. next => {
  1363. if (!youtubeId || typeof youtubeId !== "string") return next("Invalid song id.");
  1364. if (!playlistId || typeof youtubeId !== "string") return next("Invalid playlist id.");
  1365. return next();
  1366. },
  1367. next => {
  1368. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1369. .then(playlist => {
  1370. if (!playlist || playlist.createdBy !== session.userId) {
  1371. return DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1372. userModel.findOne({ _id: session.userId }, (err, user) => {
  1373. if (user && user.role === "admin") return next();
  1374. return next("Something went wrong when trying to get the playlist");
  1375. });
  1376. });
  1377. }
  1378. return next();
  1379. })
  1380. .catch(next);
  1381. },
  1382. // remove song from playlist
  1383. next => playlistModel.updateOne({ _id: playlistId }, { $pull: { songs: { youtubeId } } }, next),
  1384. // update cache representation of the playlist
  1385. (res, next) => {
  1386. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1387. .then(playlist => next(null, playlist))
  1388. .catch(next);
  1389. },
  1390. (playlist, next) => {
  1391. StationsModule.runJob("GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST", { playlistId })
  1392. .then(response => {
  1393. response.stationIds.forEach(stationId => {
  1394. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1395. });
  1396. })
  1397. .catch();
  1398. SongsModule.runJob("GET_SONG_FROM_YOUTUBE_ID", { youtubeId }, this)
  1399. .then(res =>
  1400. next(null, playlist, {
  1401. _id: res.song._id,
  1402. title: res.song.title,
  1403. thumbnail: res.song.thumbnail,
  1404. artists: res.song.artists,
  1405. youtubeId: res.song.youtubeId
  1406. })
  1407. )
  1408. .catch(() => {
  1409. YouTubeModule.runJob("GET_SONG", { youtubeId }, this)
  1410. .then(response => next(null, playlist, response.song))
  1411. .catch(next);
  1412. });
  1413. },
  1414. (playlist, newSong, next) => {
  1415. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1416. SongsModule.runJob("RECALCULATE_SONG_RATINGS", {
  1417. songId: newSong._id,
  1418. youtubeId: newSong.youtubeId
  1419. })
  1420. .then(ratings => next(null, playlist, newSong, ratings))
  1421. .catch(next);
  1422. } else {
  1423. next(null, playlist, newSong, null);
  1424. }
  1425. },
  1426. (playlist, newSong, ratings, next) => {
  1427. const { _id, title, artists, thumbnail } = newSong;
  1428. const songName = artists ? `${title} by ${artists.join(", ")}` : title;
  1429. if (playlist.type === "user" && playlist.privacy === "public") {
  1430. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1431. userId: session.userId,
  1432. type: "playlist__remove_song",
  1433. payload: {
  1434. message: `Removed <youtubeId>${songName}</youtubeId> from playlist <playlistId>${playlist.displayName}</playlistId>`,
  1435. thumbnail,
  1436. playlistId,
  1437. youtubeId: newSong.youtubeId
  1438. }
  1439. });
  1440. }
  1441. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1442. const { likes, dislikes } = ratings;
  1443. SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1444. if (playlist.type === "user-liked") {
  1445. CacheModule.runJob("PUB", {
  1446. channel: "song.unlike",
  1447. value: JSON.stringify({
  1448. youtubeId: newSong.youtubeId,
  1449. userId: session.userId,
  1450. likes,
  1451. dislikes
  1452. })
  1453. });
  1454. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1455. userId: session.userId,
  1456. type: "song__unlike",
  1457. payload: {
  1458. message: `Removed <youtubeId>${title} by ${artists.join(
  1459. ", "
  1460. )}</youtubeId> from your Liked Songs`,
  1461. youtubeId: newSong.youtubeId,
  1462. thumbnail
  1463. }
  1464. });
  1465. } else {
  1466. CacheModule.runJob("PUB", {
  1467. channel: "song.undislike",
  1468. value: JSON.stringify({
  1469. youtubeId: newSong.youtubeId,
  1470. userId: session.userId,
  1471. likes,
  1472. dislikes
  1473. })
  1474. });
  1475. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1476. userId: session.userId,
  1477. type: "song__undislike",
  1478. payload: {
  1479. message: `Removed <youtubeId>${title} by ${artists.join(
  1480. ", "
  1481. )}</youtubeId> from your Disliked Songs`,
  1482. youtubeId: newSong.youtubeId,
  1483. thumbnail
  1484. }
  1485. });
  1486. }
  1487. }
  1488. return next(null, playlist);
  1489. }
  1490. ],
  1491. async (err, playlist) => {
  1492. if (err) {
  1493. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1494. this.log(
  1495. "ERROR",
  1496. "PLAYLIST_REMOVE_SONG",
  1497. `Removing song "${youtubeId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1498. );
  1499. return cb({ status: "error", message: err });
  1500. }
  1501. this.log(
  1502. "SUCCESS",
  1503. "PLAYLIST_REMOVE_SONG",
  1504. `Successfully removed song "${youtubeId}" from private playlist "${playlistId}" for user "${session.userId}".`
  1505. );
  1506. CacheModule.runJob("PUB", {
  1507. channel: "playlist.removeSong",
  1508. value: {
  1509. playlistId: playlist._id,
  1510. youtubeId,
  1511. userId: session.userId,
  1512. privacy: playlist.privacy
  1513. }
  1514. });
  1515. CacheModule.runJob("PUB", {
  1516. channel: "playlist.updated",
  1517. value: { playlistId }
  1518. });
  1519. return cb({
  1520. status: "success",
  1521. message: "Song has been successfully removed from playlist",
  1522. data: { songs: playlist.songs }
  1523. });
  1524. }
  1525. );
  1526. }),
  1527. /**
  1528. * Updates the displayName of a private playlist
  1529. *
  1530. * @param {object} session - the session object automatically added by the websocket
  1531. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  1532. * @param {Function} cb - gets called with the result
  1533. */
  1534. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  1535. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1536. async.waterfall(
  1537. [
  1538. next => {
  1539. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1540. .then(playlist => next(null, playlist))
  1541. .catch(next);
  1542. },
  1543. (playlist, next) => {
  1544. if (playlist.type !== "user") return next("Playlist cannot be modified.");
  1545. return next(null);
  1546. },
  1547. next => {
  1548. playlistModel.updateOne(
  1549. { _id: playlistId, createdBy: session.userId },
  1550. { $set: { displayName } },
  1551. { runValidators: true },
  1552. next
  1553. );
  1554. },
  1555. (res, next) => {
  1556. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1557. .then(playlist => next(null, playlist))
  1558. .catch(next);
  1559. }
  1560. ],
  1561. async (err, playlist) => {
  1562. if (err) {
  1563. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1564. this.log(
  1565. "ERROR",
  1566. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1567. `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1568. );
  1569. return cb({ status: "error", message: err });
  1570. }
  1571. this.log(
  1572. "SUCCESS",
  1573. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1574. `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${session.userId}".`
  1575. );
  1576. CacheModule.runJob("PUB", {
  1577. channel: "playlist.updateDisplayName",
  1578. value: {
  1579. playlistId,
  1580. displayName,
  1581. userId: session.userId,
  1582. privacy: playlist.privacy
  1583. }
  1584. });
  1585. CacheModule.runJob("PUB", {
  1586. channel: "playlist.updated",
  1587. value: { playlistId }
  1588. });
  1589. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1590. userId: session.userId,
  1591. type: "playlist__edit_display_name",
  1592. payload: {
  1593. message: `Changed display name of playlist <playlistId>${displayName}</playlistId>`,
  1594. playlistId
  1595. }
  1596. });
  1597. return cb({
  1598. status: "success",
  1599. message: "Playlist has been successfully updated"
  1600. });
  1601. }
  1602. );
  1603. }),
  1604. /**
  1605. * Removes a user's own modifiable user playlist
  1606. *
  1607. * @param {object} session - the session object automatically added by the websocket
  1608. * @param {string} playlistId - the id of the playlist we are removing
  1609. * @param {Function} cb - gets called with the result
  1610. */
  1611. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1612. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1613. async.waterfall(
  1614. [
  1615. next => {
  1616. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1617. .then(playlist => next(null, playlist))
  1618. .catch(next);
  1619. },
  1620. (playlist, next) => {
  1621. if (playlist.createdBy !== session.userId) return next("You do not own this playlist.");
  1622. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1623. return next(null, playlist);
  1624. },
  1625. (playlist, next) => {
  1626. userModel.updateOne(
  1627. { _id: playlist.createdBy },
  1628. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1629. err => next(err, playlist)
  1630. );
  1631. },
  1632. (playlist, next) => {
  1633. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1634. .then(() => next(null, playlist))
  1635. .catch(next);
  1636. }
  1637. ],
  1638. async (err, playlist) => {
  1639. if (err) {
  1640. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1641. this.log(
  1642. "ERROR",
  1643. "PLAYLIST_REMOVE",
  1644. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1645. );
  1646. return cb({ status: "error", message: err });
  1647. }
  1648. this.log(
  1649. "SUCCESS",
  1650. "PLAYLIST_REMOVE",
  1651. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1652. );
  1653. CacheModule.runJob("PUB", {
  1654. channel: "playlist.delete",
  1655. value: {
  1656. userId: session.userId,
  1657. playlistId
  1658. }
  1659. });
  1660. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1661. userId: playlist.createdBy,
  1662. type: "playlist__remove",
  1663. payload: {
  1664. message: `Removed playlist ${playlist.displayName}`
  1665. }
  1666. });
  1667. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1668. return cb({
  1669. status: "success",
  1670. message: "Playlist successfully removed"
  1671. });
  1672. }
  1673. );
  1674. }),
  1675. /**
  1676. * Removes a user's modifiable user playlist as an admin
  1677. *
  1678. * @param {object} session - the session object automatically added by the websocket
  1679. * @param {string} playlistId - the id of the playlist we are removing
  1680. * @param {Function} cb - gets called with the result
  1681. */
  1682. removeAdmin: isAdminRequired(async function removeAdmin(session, playlistId, cb) {
  1683. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1684. async.waterfall(
  1685. [
  1686. next => {
  1687. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1688. .then(playlist => next(null, playlist))
  1689. .catch(next);
  1690. },
  1691. (playlist, next) => {
  1692. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1693. return next(null, playlist);
  1694. },
  1695. (playlist, next) => {
  1696. userModel.updateOne(
  1697. { _id: playlist.createdBy },
  1698. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1699. err => next(err, playlist, playlist.createdBy)
  1700. );
  1701. },
  1702. (playlist, playlistCreator, next) => {
  1703. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1704. .then(() => next(null, playlistCreator))
  1705. .catch(next);
  1706. }
  1707. ],
  1708. async (err, playlistCreator) => {
  1709. if (err) {
  1710. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1711. this.log(
  1712. "ERROR",
  1713. "PLAYLIST_REMOVE_ADMIN",
  1714. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1715. );
  1716. return cb({ status: "error", message: err });
  1717. }
  1718. this.log(
  1719. "SUCCESS",
  1720. "PLAYLIST_REMOVE_ADMIN",
  1721. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1722. );
  1723. CacheModule.runJob("PUB", {
  1724. channel: "playlist.delete",
  1725. value: {
  1726. userId: playlistCreator,
  1727. playlistId
  1728. }
  1729. });
  1730. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1731. return cb({
  1732. status: "success",
  1733. message: "Playlist successfully removed"
  1734. });
  1735. }
  1736. );
  1737. }),
  1738. /**
  1739. * Updates the privacy of a private playlist
  1740. *
  1741. * @param {object} session - the session object automatically added by the websocket
  1742. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1743. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1744. * @param {Function} cb - gets called with the result
  1745. */
  1746. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  1747. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1748. async.waterfall(
  1749. [
  1750. next => {
  1751. playlistModel.updateOne(
  1752. { _id: playlistId, createdBy: session.userId },
  1753. { $set: { privacy } },
  1754. { runValidators: true },
  1755. next
  1756. );
  1757. },
  1758. (res, next) => {
  1759. if (res.n === 0) next("No user playlist found with that id and owned by you.");
  1760. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1761. else {
  1762. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1763. .then(playlist => next(null, playlist))
  1764. .catch(next);
  1765. }
  1766. }
  1767. ],
  1768. async (err, playlist) => {
  1769. if (err) {
  1770. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1771. this.log(
  1772. "ERROR",
  1773. "PLAYLIST_UPDATE_PRIVACY",
  1774. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1775. );
  1776. return cb({ status: "error", message: err });
  1777. }
  1778. this.log(
  1779. "SUCCESS",
  1780. "PLAYLIST_UPDATE_PRIVACY",
  1781. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  1782. );
  1783. CacheModule.runJob("PUB", {
  1784. channel: "playlist.updatePrivacy",
  1785. value: {
  1786. userId: session.userId,
  1787. playlist
  1788. }
  1789. });
  1790. CacheModule.runJob("PUB", {
  1791. channel: "playlist.updated",
  1792. value: { playlistId }
  1793. });
  1794. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1795. userId: session.userId,
  1796. type: "playlist__edit_privacy",
  1797. payload: {
  1798. message: `Changed privacy of playlist <playlistId>${playlist.displayName}</playlistId> to ${privacy}`,
  1799. playlistId
  1800. }
  1801. });
  1802. return cb({
  1803. status: "success",
  1804. message: "Playlist has been successfully updated"
  1805. });
  1806. }
  1807. );
  1808. }),
  1809. /**
  1810. * Updates the privacy of a playlist
  1811. *
  1812. * @param {object} session - the session object automatically added by the websocket
  1813. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1814. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1815. * @param {Function} cb - gets called with the result
  1816. */
  1817. updatePrivacyAdmin: isAdminRequired(async function updatePrivacyAdmin(session, playlistId, privacy, cb) {
  1818. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1819. async.waterfall(
  1820. [
  1821. next => {
  1822. playlistModel.updateOne({ _id: playlistId }, { $set: { privacy } }, { runValidators: true }, next);
  1823. },
  1824. (res, next) => {
  1825. if (res.n === 0) next("No playlist found with that id.");
  1826. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1827. else {
  1828. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1829. .then(playlist => next(null, playlist))
  1830. .catch(next);
  1831. }
  1832. }
  1833. ],
  1834. async (err, playlist) => {
  1835. if (err) {
  1836. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1837. this.log(
  1838. "ERROR",
  1839. "PLAYLIST_UPDATE_PRIVACY_ADMIN",
  1840. `Updating privacy to "${privacy}" for playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1841. );
  1842. return cb({ status: "error", message: err });
  1843. }
  1844. this.log(
  1845. "SUCCESS",
  1846. "PLAYLIST_UPDATE_PRIVACY_ADMIn",
  1847. `Successfully updated privacy to "${privacy}" for playlist "${playlistId}" for user "${session.userId}".`
  1848. );
  1849. if (playlist.type === "user") {
  1850. CacheModule.runJob("PUB", {
  1851. channel: "playlist.updatePrivacy",
  1852. value: {
  1853. userId: playlist.createdBy,
  1854. playlist
  1855. }
  1856. });
  1857. }
  1858. CacheModule.runJob("PUB", {
  1859. channel: "playlist.updated",
  1860. value: { playlistId }
  1861. });
  1862. return cb({
  1863. status: "success",
  1864. message: "Playlist has been successfully updated"
  1865. });
  1866. }
  1867. );
  1868. }),
  1869. /**
  1870. * Deletes all orphaned station playlists
  1871. *
  1872. * @param {object} session - the session object automatically added by socket.io
  1873. * @param {Function} cb - gets called with the result
  1874. */
  1875. deleteOrphanedStationPlaylists: isAdminRequired(async function index(session, cb) {
  1876. async.waterfall(
  1877. [
  1878. next => {
  1879. PlaylistsModule.runJob("DELETE_ORPHANED_STATION_PLAYLISTS", {}, this)
  1880. .then(() => next())
  1881. .catch(next);
  1882. }
  1883. ],
  1884. async err => {
  1885. if (err) {
  1886. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1887. this.log(
  1888. "ERROR",
  1889. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1890. `Deleting orphaned station playlists failed. "${err}"`
  1891. );
  1892. return cb({ status: "error", message: err });
  1893. }
  1894. this.log(
  1895. "SUCCESS",
  1896. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1897. "Deleting orphaned station playlists successful."
  1898. );
  1899. return cb({ status: "success", message: "Successfully deleted orphaned station playlists." });
  1900. }
  1901. );
  1902. }),
  1903. /**
  1904. * Deletes all orphaned genre playlists
  1905. *
  1906. * @param {object} session - the session object automatically added by socket.io
  1907. * @param {Function} cb - gets called with the result
  1908. */
  1909. deleteOrphanedGenrePlaylists: isAdminRequired(async function index(session, cb) {
  1910. async.waterfall(
  1911. [
  1912. next => {
  1913. PlaylistsModule.runJob("DELETE_ORPHANED_GENRE_PLAYLISTS", {}, this)
  1914. .then(() => next())
  1915. .catch(next);
  1916. }
  1917. ],
  1918. async err => {
  1919. if (err) {
  1920. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1921. this.log(
  1922. "ERROR",
  1923. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1924. `Deleting orphaned genre playlists failed. "${err}"`
  1925. );
  1926. return cb({ status: "error", message: err });
  1927. }
  1928. this.log(
  1929. "SUCCESS",
  1930. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1931. "Deleting orphaned genre playlists successful."
  1932. );
  1933. return cb({ status: "success", message: "Successfully deleted orphaned genre playlists." });
  1934. }
  1935. );
  1936. }),
  1937. /**
  1938. * Requests orpahned playlist songs
  1939. *
  1940. * @param {object} session - the session object automatically added by socket.io
  1941. * @param {Function} cb - gets called with the result
  1942. */
  1943. requestOrphanedPlaylistSongs: isAdminRequired(async function index(session, cb) {
  1944. async.waterfall(
  1945. [
  1946. next => {
  1947. SongsModule.runJob("REQUEST_ORPHANED_PLAYLIST_SONGS", {}, this)
  1948. .then(() => next())
  1949. .catch(next);
  1950. }
  1951. ],
  1952. async err => {
  1953. if (err) {
  1954. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1955. this.log(
  1956. "ERROR",
  1957. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1958. `Requesting orphaned playlist songs failed. "${err}"`
  1959. );
  1960. return cb({ status: "error", message: err });
  1961. }
  1962. this.log(
  1963. "SUCCESS",
  1964. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1965. "Requesting orphaned playlist songs was successful."
  1966. );
  1967. return cb({ status: "success", message: "Successfully requested orphaned playlist songs." });
  1968. }
  1969. );
  1970. }),
  1971. /**
  1972. * Clears and refills a station playlist
  1973. *
  1974. * @param {object} session - the session object automatically added by socket.io
  1975. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  1976. * @param {Function} cb - gets called with the result
  1977. */
  1978. clearAndRefillStationPlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  1979. async.waterfall(
  1980. [
  1981. next => {
  1982. if (!playlistId) next("Please specify a playlist id");
  1983. else {
  1984. PlaylistsModule.runJob("CLEAR_AND_REFILL_STATION_PLAYLIST", { playlistId }, this)
  1985. .then(() => {
  1986. next();
  1987. })
  1988. .catch(err => {
  1989. next(err);
  1990. });
  1991. }
  1992. }
  1993. ],
  1994. async err => {
  1995. if (err) {
  1996. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1997. this.log(
  1998. "ERROR",
  1999. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  2000. `Clearing and refilling station playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2001. );
  2002. return cb({ status: "error", message: err });
  2003. }
  2004. this.log(
  2005. "SUCCESS",
  2006. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  2007. `Successfully cleared and refilled station playlist "${playlistId}" for user "${session.userId}".`
  2008. );
  2009. return cb({
  2010. status: "success",
  2011. message: "Playlist has been successfully cleared and refilled"
  2012. });
  2013. }
  2014. );
  2015. }),
  2016. /**
  2017. * Clears and refills a genre playlist
  2018. *
  2019. * @param {object} session - the session object automatically added by socket.io
  2020. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  2021. * @param {Function} cb - gets called with the result
  2022. */
  2023. clearAndRefillGenrePlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  2024. async.waterfall(
  2025. [
  2026. next => {
  2027. if (!playlistId) next("Please specify a playlist id");
  2028. else {
  2029. PlaylistsModule.runJob("CLEAR_AND_REFILL_GENRE_PLAYLIST", { playlistId }, this)
  2030. .then(() => {
  2031. next();
  2032. })
  2033. .catch(err => {
  2034. next(err);
  2035. });
  2036. }
  2037. }
  2038. ],
  2039. async err => {
  2040. if (err) {
  2041. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2042. this.log(
  2043. "ERROR",
  2044. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2045. `Clearing and refilling genre playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2046. );
  2047. return cb({ status: "error", message: err });
  2048. }
  2049. this.log(
  2050. "SUCCESS",
  2051. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2052. `Successfully cleared and refilled genre playlist "${playlistId}" for user "${session.userId}".`
  2053. );
  2054. return cb({
  2055. status: "success",
  2056. message: "Playlist has been successfully cleared and refilled"
  2057. });
  2058. }
  2059. );
  2060. }),
  2061. /**
  2062. * Clears and refills all station playlists
  2063. *
  2064. * @param {object} session - the session object automatically added by socket.io
  2065. * @param {Function} cb - gets called with the result
  2066. */
  2067. clearAndRefillAllStationPlaylists: isAdminRequired(async function index(session, cb) {
  2068. async.waterfall(
  2069. [
  2070. next => {
  2071. PlaylistsModule.runJob("GET_ALL_STATION_PLAYLISTS", {}, this)
  2072. .then(response => {
  2073. next(null, response.playlists);
  2074. })
  2075. .catch(err => {
  2076. next(err);
  2077. });
  2078. },
  2079. (playlists, next) => {
  2080. async.eachLimit(
  2081. playlists,
  2082. 1,
  2083. (playlist, next) => {
  2084. PlaylistsModule.runJob(
  2085. "CLEAR_AND_REFILL_STATION_PLAYLIST",
  2086. { playlistId: playlist._id },
  2087. this
  2088. )
  2089. .then(() => {
  2090. next();
  2091. })
  2092. .catch(err => {
  2093. next(err);
  2094. });
  2095. },
  2096. next
  2097. );
  2098. }
  2099. ],
  2100. async err => {
  2101. if (err) {
  2102. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2103. this.log(
  2104. "ERROR",
  2105. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2106. `Clearing and refilling all station playlists failed for user "${session.userId}". "${err}"`
  2107. );
  2108. return cb({ status: "error", message: err });
  2109. }
  2110. this.log(
  2111. "SUCCESS",
  2112. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2113. `Successfully cleared and refilled all station playlists for user "${session.userId}".`
  2114. );
  2115. return cb({
  2116. status: "success",
  2117. message: "Playlists have been successfully cleared and refilled"
  2118. });
  2119. }
  2120. );
  2121. }),
  2122. /**
  2123. * Clears and refills all genre playlists
  2124. *
  2125. * @param {object} session - the session object automatically added by socket.io
  2126. * @param {Function} cb - gets called with the result
  2127. */
  2128. clearAndRefillAllGenrePlaylists: isAdminRequired(async function index(session, cb) {
  2129. async.waterfall(
  2130. [
  2131. next => {
  2132. PlaylistsModule.runJob("GET_ALL_GENRE_PLAYLISTS", {}, this)
  2133. .then(response => {
  2134. next(null, response.playlists);
  2135. })
  2136. .catch(err => {
  2137. next(err);
  2138. });
  2139. },
  2140. (playlists, next) => {
  2141. async.eachLimit(
  2142. playlists,
  2143. 1,
  2144. (playlist, next) => {
  2145. PlaylistsModule.runJob(
  2146. "CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2147. { playlistId: playlist._id },
  2148. this
  2149. )
  2150. .then(() => {
  2151. next();
  2152. })
  2153. .catch(err => {
  2154. next(err);
  2155. });
  2156. },
  2157. next
  2158. );
  2159. }
  2160. ],
  2161. async err => {
  2162. if (err) {
  2163. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2164. this.log(
  2165. "ERROR",
  2166. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2167. `Clearing and refilling all genre playlists failed for user "${session.userId}". "${err}"`
  2168. );
  2169. return cb({ status: "error", message: err });
  2170. }
  2171. this.log(
  2172. "SUCCESS",
  2173. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2174. `Successfully cleared and refilled all genre playlists for user "${session.userId}".`
  2175. );
  2176. return cb({
  2177. status: "success",
  2178. message: "Playlists have been successfully cleared and refilled"
  2179. });
  2180. }
  2181. );
  2182. }),
  2183. /**
  2184. * Create missing genre playlists
  2185. *
  2186. * @param {object} session - the session object automatically added by socket.io
  2187. * @param {Function} cb - gets called with the result
  2188. */
  2189. createMissingGenrePlaylists: isAdminRequired(async function index(session, cb) {
  2190. async.waterfall(
  2191. [
  2192. next => {
  2193. PlaylistsModule.runJob("CREATE_MISSING_GENRE_PLAYLISTS", this)
  2194. .then(() => {
  2195. next();
  2196. })
  2197. .catch(err => {
  2198. next(err);
  2199. });
  2200. }
  2201. ],
  2202. async err => {
  2203. if (err) {
  2204. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2205. this.log(
  2206. "ERROR",
  2207. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2208. `Creating missing genre playlists failed for user "${session.userId}". "${err}"`
  2209. );
  2210. return cb({ status: "error", message: err });
  2211. }
  2212. this.log(
  2213. "SUCCESS",
  2214. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2215. `Successfully created missing genre playlists for user "${session.userId}".`
  2216. );
  2217. return cb({
  2218. status: "success",
  2219. message: "Missing genre playlists have been successfully created"
  2220. });
  2221. }
  2222. );
  2223. })
  2224. };