playlists.js 68 KB

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