playlists.js 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343
  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 CacheModule = moduleManager.modules.cache;
  11. const PlaylistsModule = moduleManager.modules.playlists;
  12. const YouTubeModule = moduleManager.modules.youtube;
  13. const ActivitiesModule = moduleManager.modules.activities;
  14. const MediaModule = moduleManager.modules.media;
  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. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1018. const oppositeType = playlist.type === "user-liked" ? "user-disliked" : "user-liked";
  1019. const oppositePlaylistName = oppositeType === "user-liked" ? "Liked Songs" : "Disliked Songs";
  1020. playlistModel.count(
  1021. { type: oppositeType, createdBy: session.userId, "songs.youtubeId": youtubeId },
  1022. (err, results) => {
  1023. if (err) next(err);
  1024. else if (results > 0)
  1025. next(
  1026. `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.`
  1027. );
  1028. else next();
  1029. }
  1030. );
  1031. } else next();
  1032. },
  1033. next => {
  1034. PlaylistsModule.runJob("ADD_SONG_TO_PLAYLIST", { playlistId, youtubeId }, this)
  1035. .then(res => {
  1036. const { playlist, song, ratings } = res;
  1037. next(null, playlist, song, ratings);
  1038. })
  1039. .catch(next);
  1040. }
  1041. ],
  1042. async (err, playlist, newSong, ratings) => {
  1043. if (err) {
  1044. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1045. this.log(
  1046. "ERROR",
  1047. "PLAYLIST_ADD_SONG",
  1048. `Adding song "${youtubeId}" to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1049. );
  1050. return cb({ status: "error", message: err });
  1051. }
  1052. this.log(
  1053. "SUCCESS",
  1054. "PLAYLIST_ADD_SONG",
  1055. `Successfully added song "${youtubeId}" to private playlist "${playlistId}" for user "${session.userId}".`
  1056. );
  1057. if (!isSet && playlist.type === "user" && playlist.privacy === "public") {
  1058. const songName = newSong.artists
  1059. ? `${newSong.title} by ${newSong.artists.join(", ")}`
  1060. : newSong.title;
  1061. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1062. userId: session.userId,
  1063. type: "playlist__add_song",
  1064. payload: {
  1065. message: `Added <youtubeId>${songName}</youtubeId> to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1066. thumbnail: newSong.thumbnail,
  1067. playlistId,
  1068. youtubeId
  1069. }
  1070. });
  1071. }
  1072. CacheModule.runJob("PUB", {
  1073. channel: "playlist.addSong",
  1074. value: {
  1075. playlistId: playlist._id,
  1076. song: newSong,
  1077. userId: session.userId,
  1078. privacy: playlist.privacy
  1079. }
  1080. });
  1081. CacheModule.runJob("PUB", {
  1082. channel: "playlist.updated",
  1083. value: { playlistId }
  1084. });
  1085. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1086. const { _id, youtubeId, title, artists, thumbnail } = newSong;
  1087. const { likes, dislikes } = ratings;
  1088. SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1089. if (playlist.type === "user-liked") {
  1090. CacheModule.runJob("PUB", {
  1091. channel: "song.like",
  1092. value: JSON.stringify({
  1093. youtubeId,
  1094. userId: session.userId,
  1095. likes,
  1096. dislikes
  1097. })
  1098. });
  1099. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1100. userId: session.userId,
  1101. type: "song__like",
  1102. payload: {
  1103. message: `Liked song <youtubeId>${title} by ${artists.join(", ")}</youtubeId>`,
  1104. youtubeId,
  1105. thumbnail
  1106. }
  1107. });
  1108. } else {
  1109. CacheModule.runJob("PUB", {
  1110. channel: "song.dislike",
  1111. value: JSON.stringify({
  1112. youtubeId,
  1113. userId: session.userId,
  1114. likes,
  1115. dislikes
  1116. })
  1117. });
  1118. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1119. userId: session.userId,
  1120. type: "song__dislike",
  1121. payload: {
  1122. message: `Disliked song <youtubeId>${title} by ${artists.join(", ")}</youtubeId>`,
  1123. youtubeId,
  1124. thumbnail
  1125. }
  1126. });
  1127. }
  1128. }
  1129. return cb({
  1130. status: "success",
  1131. message: "Song has been successfully added to the playlist",
  1132. data: { songs: playlist.songs }
  1133. });
  1134. }
  1135. );
  1136. }),
  1137. /**
  1138. * Adds a set of songs to a private playlist
  1139. *
  1140. * @param {object} session - the session object automatically added by the websocket
  1141. * @param {string} url - the url of the the YouTube playlist
  1142. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  1143. * @param {boolean} musicOnly - whether to only add music to the playlist
  1144. * @param {Function} cb - gets called with the result
  1145. */
  1146. addSetToPlaylist: isLoginRequired(function addSetToPlaylist(session, url, playlistId, musicOnly, cb) {
  1147. let videosInPlaylistTotal = 0;
  1148. let songsInPlaylistTotal = 0;
  1149. let addSongsStats = null;
  1150. const addedSongs = [];
  1151. async.waterfall(
  1152. [
  1153. next => {
  1154. YouTubeModule.runJob("GET_PLAYLIST", { url, musicOnly }, this)
  1155. .then(res => {
  1156. if (res.filteredSongs) {
  1157. videosInPlaylistTotal = res.songs.length;
  1158. songsInPlaylistTotal = res.filteredSongs.length;
  1159. } else {
  1160. songsInPlaylistTotal = videosInPlaylistTotal = res.songs.length;
  1161. }
  1162. next(null, res.songs);
  1163. })
  1164. .catch(err => {
  1165. next(err);
  1166. });
  1167. },
  1168. (youtubeIds, next) => {
  1169. let successful = 0;
  1170. let failed = 0;
  1171. let alreadyInPlaylist = 0;
  1172. let alreadyInLikedPlaylist = 0;
  1173. let alreadyInDislikedPlaylist = 0;
  1174. if (youtubeIds.length === 0) next();
  1175. async.eachLimit(
  1176. youtubeIds,
  1177. 1,
  1178. (youtubeId, next) => {
  1179. WSModule.runJob(
  1180. "RUN_ACTION2",
  1181. {
  1182. session,
  1183. namespace: "playlists",
  1184. action: "addSongToPlaylist",
  1185. args: [true, youtubeId, playlistId]
  1186. },
  1187. this
  1188. )
  1189. .then(res => {
  1190. if (res.status === "success") {
  1191. successful += 1;
  1192. addedSongs.push(youtubeId);
  1193. } else failed += 1;
  1194. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  1195. else if (
  1196. res.message ===
  1197. "That song is already in your Liked Songs playlist. " +
  1198. "A song cannot be in both the Liked Songs playlist" +
  1199. " and the Disliked Songs playlist at the same time."
  1200. )
  1201. alreadyInLikedPlaylist += 1;
  1202. else if (
  1203. res.message ===
  1204. "That song is already in your Disliked Songs playlist. " +
  1205. "A song cannot be in both the Liked Songs playlist " +
  1206. "and the Disliked Songs playlist at the same time."
  1207. )
  1208. alreadyInDislikedPlaylist += 1;
  1209. })
  1210. .catch(() => {
  1211. failed += 1;
  1212. })
  1213. .finally(() => next());
  1214. },
  1215. () => {
  1216. addSongsStats = {
  1217. successful,
  1218. failed,
  1219. alreadyInPlaylist,
  1220. alreadyInLikedPlaylist,
  1221. alreadyInDislikedPlaylist
  1222. };
  1223. next(null);
  1224. }
  1225. );
  1226. },
  1227. next => {
  1228. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1229. .then(playlist => next(null, playlist))
  1230. .catch(next);
  1231. },
  1232. (playlist, next) => {
  1233. if (!playlist || playlist.createdBy !== session.userId) {
  1234. return DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1235. userModel.findOne({ _id: session.userId }, (err, user) => {
  1236. if (user && user.role === "admin") return next(null, playlist);
  1237. return next("Something went wrong when trying to get the playlist");
  1238. });
  1239. });
  1240. }
  1241. return next(null, playlist);
  1242. }
  1243. ],
  1244. async (err, playlist) => {
  1245. if (err) {
  1246. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1247. this.log(
  1248. "ERROR",
  1249. "PLAYLIST_IMPORT",
  1250. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1251. );
  1252. return cb({ status: "error", message: err });
  1253. }
  1254. if (playlist.privacy === "public")
  1255. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1256. userId: session.userId,
  1257. type: "playlist__import_playlist",
  1258. payload: {
  1259. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1260. playlistId
  1261. }
  1262. });
  1263. this.log(
  1264. "SUCCESS",
  1265. "PLAYLIST_IMPORT",
  1266. `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}.`
  1267. );
  1268. return cb({
  1269. status: "success",
  1270. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  1271. data: {
  1272. songs: playlist.songs,
  1273. stats: {
  1274. videosInPlaylistTotal,
  1275. songsInPlaylistTotal,
  1276. alreadyInLikedPlaylist: addSongsStats.alreadyInLikedPlaylist,
  1277. alreadyInDislikedPlaylist: addSongsStats.alreadyInDislikedPlaylist
  1278. }
  1279. }
  1280. });
  1281. }
  1282. );
  1283. }),
  1284. /**
  1285. * Removes a song from a private playlist
  1286. *
  1287. * @param {object} session - the session object automatically added by the websocket
  1288. * @param {string} youtubeId - the youtube id of the song we are removing from the private playlist
  1289. * @param {string} playlistId - the id of the playlist we are removing the song from
  1290. * @param {Function} cb - gets called with the result
  1291. */
  1292. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(session, youtubeId, playlistId, cb) {
  1293. async.waterfall(
  1294. [
  1295. next => {
  1296. if (!youtubeId || typeof youtubeId !== "string") return next("Invalid song id.");
  1297. if (!playlistId || typeof youtubeId !== "string") return next("Invalid playlist id.");
  1298. return next();
  1299. },
  1300. next => {
  1301. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1302. .then(playlist => {
  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. .catch(next);
  1314. },
  1315. (playlist, next) => {
  1316. MediaModule.runJob("GET_MEDIA", { youtubeId }, this)
  1317. .then(res =>
  1318. next(null, playlist, {
  1319. _id: res.song._id,
  1320. title: res.song.title,
  1321. thumbnail: res.song.thumbnail,
  1322. artists: res.song.artists,
  1323. youtubeId: res.song.youtubeId
  1324. })
  1325. )
  1326. .catch(next);
  1327. },
  1328. (playlist, newSong, next) => {
  1329. PlaylistsModule.runJob("REMOVE_FROM_PLAYLIST", { playlistId, youtubeId }, this)
  1330. .then(res => {
  1331. const { ratings } = res;
  1332. next(null, playlist, newSong, ratings);
  1333. })
  1334. .catch(next);
  1335. },
  1336. (playlist, newSong, ratings, next) => {
  1337. const { _id, title, artists, thumbnail } = newSong;
  1338. const songName = artists ? `${title} by ${artists.join(", ")}` : title;
  1339. if (playlist.type === "user" && playlist.privacy === "public") {
  1340. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1341. userId: session.userId,
  1342. type: "playlist__remove_song",
  1343. payload: {
  1344. message: `Removed <youtubeId>${songName}</youtubeId> from playlist <playlistId>${playlist.displayName}</playlistId>`,
  1345. thumbnail,
  1346. playlistId,
  1347. youtubeId: newSong.youtubeId
  1348. }
  1349. });
  1350. }
  1351. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1352. const { likes, dislikes } = ratings;
  1353. SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1354. if (playlist.type === "user-liked") {
  1355. CacheModule.runJob("PUB", {
  1356. channel: "ratings.unlike",
  1357. value: JSON.stringify({
  1358. youtubeId: newSong.youtubeId,
  1359. userId: session.userId,
  1360. likes,
  1361. dislikes
  1362. })
  1363. });
  1364. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1365. userId: session.userId,
  1366. type: "song__unlike",
  1367. payload: {
  1368. message: `Removed <youtubeId>${title} by ${artists.join(
  1369. ", "
  1370. )}</youtubeId> from your Liked Songs`,
  1371. youtubeId: newSong.youtubeId,
  1372. thumbnail
  1373. }
  1374. });
  1375. } else {
  1376. CacheModule.runJob("PUB", {
  1377. channel: "song.undislike",
  1378. value: JSON.stringify({
  1379. youtubeId: newSong.youtubeId,
  1380. userId: session.userId,
  1381. likes,
  1382. dislikes
  1383. })
  1384. });
  1385. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1386. userId: session.userId,
  1387. type: "song__undislike",
  1388. payload: {
  1389. message: `Removed <youtubeId>${title} by ${artists.join(
  1390. ", "
  1391. )}</youtubeId> from your Disliked Songs`,
  1392. youtubeId: newSong.youtubeId,
  1393. thumbnail
  1394. }
  1395. });
  1396. }
  1397. }
  1398. return next(null, playlist);
  1399. }
  1400. ],
  1401. async (err, playlist) => {
  1402. if (err) {
  1403. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1404. this.log(
  1405. "ERROR",
  1406. "PLAYLIST_REMOVE_SONG",
  1407. `Removing song "${youtubeId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1408. );
  1409. return cb({ status: "error", message: err });
  1410. }
  1411. this.log(
  1412. "SUCCESS",
  1413. "PLAYLIST_REMOVE_SONG",
  1414. `Successfully removed song "${youtubeId}" from private playlist "${playlistId}" for user "${session.userId}".`
  1415. );
  1416. CacheModule.runJob("PUB", {
  1417. channel: "playlist.removeSong",
  1418. value: {
  1419. playlistId: playlist._id,
  1420. youtubeId,
  1421. userId: session.userId,
  1422. privacy: playlist.privacy
  1423. }
  1424. });
  1425. return cb({
  1426. status: "success",
  1427. message: "Song has been successfully removed from playlist",
  1428. data: { songs: playlist.songs }
  1429. });
  1430. }
  1431. );
  1432. }),
  1433. /**
  1434. * Updates the displayName of a private playlist
  1435. *
  1436. * @param {object} session - the session object automatically added by the websocket
  1437. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  1438. * @param {Function} cb - gets called with the result
  1439. */
  1440. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  1441. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1442. async.waterfall(
  1443. [
  1444. next => {
  1445. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1446. .then(playlist => next(null, playlist))
  1447. .catch(next);
  1448. },
  1449. (playlist, next) => {
  1450. if (playlist.type !== "user") return next("Playlist cannot be modified.");
  1451. return next(null);
  1452. },
  1453. next => {
  1454. playlistModel.updateOne(
  1455. { _id: playlistId, createdBy: session.userId },
  1456. { $set: { displayName } },
  1457. { runValidators: true },
  1458. next
  1459. );
  1460. },
  1461. (res, next) => {
  1462. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1463. .then(playlist => next(null, playlist))
  1464. .catch(next);
  1465. }
  1466. ],
  1467. async (err, playlist) => {
  1468. if (err) {
  1469. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1470. this.log(
  1471. "ERROR",
  1472. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1473. `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1474. );
  1475. return cb({ status: "error", message: err });
  1476. }
  1477. this.log(
  1478. "SUCCESS",
  1479. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1480. `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${session.userId}".`
  1481. );
  1482. CacheModule.runJob("PUB", {
  1483. channel: "playlist.updateDisplayName",
  1484. value: {
  1485. playlistId,
  1486. displayName,
  1487. userId: session.userId,
  1488. privacy: playlist.privacy
  1489. }
  1490. });
  1491. CacheModule.runJob("PUB", {
  1492. channel: "playlist.updated",
  1493. value: { playlistId }
  1494. });
  1495. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1496. userId: session.userId,
  1497. type: "playlist__edit_display_name",
  1498. payload: {
  1499. message: `Changed display name of playlist <playlistId>${displayName}</playlistId>`,
  1500. playlistId
  1501. }
  1502. });
  1503. return cb({
  1504. status: "success",
  1505. message: "Playlist has been successfully updated"
  1506. });
  1507. }
  1508. );
  1509. }),
  1510. /**
  1511. * Removes a user's own modifiable user playlist
  1512. *
  1513. * @param {object} session - the session object automatically added by the websocket
  1514. * @param {string} playlistId - the id of the playlist we are removing
  1515. * @param {Function} cb - gets called with the result
  1516. */
  1517. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1518. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1519. async.waterfall(
  1520. [
  1521. next => {
  1522. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1523. .then(playlist => next(null, playlist))
  1524. .catch(next);
  1525. },
  1526. (playlist, next) => {
  1527. if (playlist.createdBy !== session.userId) return next("You do not own this playlist.");
  1528. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1529. return next(null, playlist);
  1530. },
  1531. (playlist, next) => {
  1532. userModel.updateOne(
  1533. { _id: playlist.createdBy },
  1534. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1535. err => next(err, playlist)
  1536. );
  1537. },
  1538. (playlist, next) => {
  1539. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1540. .then(() => next(null, playlist))
  1541. .catch(next);
  1542. }
  1543. ],
  1544. async (err, playlist) => {
  1545. if (err) {
  1546. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1547. this.log(
  1548. "ERROR",
  1549. "PLAYLIST_REMOVE",
  1550. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1551. );
  1552. return cb({ status: "error", message: err });
  1553. }
  1554. this.log(
  1555. "SUCCESS",
  1556. "PLAYLIST_REMOVE",
  1557. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1558. );
  1559. CacheModule.runJob("PUB", {
  1560. channel: "playlist.delete",
  1561. value: {
  1562. userId: session.userId,
  1563. playlistId
  1564. }
  1565. });
  1566. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1567. userId: playlist.createdBy,
  1568. type: "playlist__remove",
  1569. payload: {
  1570. message: `Removed playlist ${playlist.displayName}`
  1571. }
  1572. });
  1573. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1574. return cb({
  1575. status: "success",
  1576. message: "Playlist successfully removed"
  1577. });
  1578. }
  1579. );
  1580. }),
  1581. /**
  1582. * Removes a user's modifiable user playlist as an admin
  1583. *
  1584. * @param {object} session - the session object automatically added by the websocket
  1585. * @param {string} playlistId - the id of the playlist we are removing
  1586. * @param {Function} cb - gets called with the result
  1587. */
  1588. removeAdmin: isAdminRequired(async function removeAdmin(session, playlistId, cb) {
  1589. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1590. async.waterfall(
  1591. [
  1592. next => {
  1593. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1594. .then(playlist => next(null, playlist))
  1595. .catch(next);
  1596. },
  1597. (playlist, next) => {
  1598. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1599. return next(null, playlist);
  1600. },
  1601. (playlist, next) => {
  1602. userModel.updateOne(
  1603. { _id: playlist.createdBy },
  1604. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1605. err => next(err, playlist, playlist.createdBy)
  1606. );
  1607. },
  1608. (playlist, playlistCreator, next) => {
  1609. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1610. .then(() => next(null, playlistCreator))
  1611. .catch(next);
  1612. }
  1613. ],
  1614. async (err, playlistCreator) => {
  1615. if (err) {
  1616. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1617. this.log(
  1618. "ERROR",
  1619. "PLAYLIST_REMOVE_ADMIN",
  1620. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1621. );
  1622. return cb({ status: "error", message: err });
  1623. }
  1624. this.log(
  1625. "SUCCESS",
  1626. "PLAYLIST_REMOVE_ADMIN",
  1627. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1628. );
  1629. CacheModule.runJob("PUB", {
  1630. channel: "playlist.delete",
  1631. value: {
  1632. userId: playlistCreator,
  1633. playlistId
  1634. }
  1635. });
  1636. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1637. return cb({
  1638. status: "success",
  1639. message: "Playlist successfully removed"
  1640. });
  1641. }
  1642. );
  1643. }),
  1644. /**
  1645. * Updates the privacy of a private playlist
  1646. *
  1647. * @param {object} session - the session object automatically added by the websocket
  1648. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1649. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1650. * @param {Function} cb - gets called with the result
  1651. */
  1652. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  1653. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1654. async.waterfall(
  1655. [
  1656. next => {
  1657. playlistModel.updateOne(
  1658. { _id: playlistId, createdBy: session.userId },
  1659. { $set: { privacy } },
  1660. { runValidators: true },
  1661. next
  1662. );
  1663. },
  1664. (res, next) => {
  1665. if (res.n === 0) next("No user playlist found with that id and owned by you.");
  1666. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1667. else {
  1668. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1669. .then(playlist => next(null, playlist))
  1670. .catch(next);
  1671. }
  1672. }
  1673. ],
  1674. async (err, playlist) => {
  1675. if (err) {
  1676. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1677. this.log(
  1678. "ERROR",
  1679. "PLAYLIST_UPDATE_PRIVACY",
  1680. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1681. );
  1682. return cb({ status: "error", message: err });
  1683. }
  1684. this.log(
  1685. "SUCCESS",
  1686. "PLAYLIST_UPDATE_PRIVACY",
  1687. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  1688. );
  1689. CacheModule.runJob("PUB", {
  1690. channel: "playlist.updatePrivacy",
  1691. value: {
  1692. userId: session.userId,
  1693. playlist
  1694. }
  1695. });
  1696. CacheModule.runJob("PUB", {
  1697. channel: "playlist.updated",
  1698. value: { playlistId }
  1699. });
  1700. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1701. userId: session.userId,
  1702. type: "playlist__edit_privacy",
  1703. payload: {
  1704. message: `Changed privacy of playlist <playlistId>${playlist.displayName}</playlistId> to ${privacy}`,
  1705. playlistId
  1706. }
  1707. });
  1708. return cb({
  1709. status: "success",
  1710. message: "Playlist has been successfully updated"
  1711. });
  1712. }
  1713. );
  1714. }),
  1715. /**
  1716. * Updates the privacy of a playlist
  1717. *
  1718. * @param {object} session - the session object automatically added by the websocket
  1719. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1720. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1721. * @param {Function} cb - gets called with the result
  1722. */
  1723. updatePrivacyAdmin: isAdminRequired(async function updatePrivacyAdmin(session, playlistId, privacy, cb) {
  1724. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1725. async.waterfall(
  1726. [
  1727. next => {
  1728. playlistModel.updateOne({ _id: playlistId }, { $set: { privacy } }, { runValidators: true }, next);
  1729. },
  1730. (res, next) => {
  1731. if (res.n === 0) next("No playlist found with that id.");
  1732. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1733. else {
  1734. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1735. .then(playlist => next(null, playlist))
  1736. .catch(next);
  1737. }
  1738. }
  1739. ],
  1740. async (err, playlist) => {
  1741. if (err) {
  1742. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1743. this.log(
  1744. "ERROR",
  1745. "PLAYLIST_UPDATE_PRIVACY_ADMIN",
  1746. `Updating privacy to "${privacy}" for playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1747. );
  1748. return cb({ status: "error", message: err });
  1749. }
  1750. this.log(
  1751. "SUCCESS",
  1752. "PLAYLIST_UPDATE_PRIVACY_ADMIn",
  1753. `Successfully updated privacy to "${privacy}" for playlist "${playlistId}" for user "${session.userId}".`
  1754. );
  1755. if (playlist.type === "user") {
  1756. CacheModule.runJob("PUB", {
  1757. channel: "playlist.updatePrivacy",
  1758. value: {
  1759. userId: playlist.createdBy,
  1760. playlist
  1761. }
  1762. });
  1763. }
  1764. CacheModule.runJob("PUB", {
  1765. channel: "playlist.updated",
  1766. value: { playlistId }
  1767. });
  1768. return cb({
  1769. status: "success",
  1770. message: "Playlist has been successfully updated"
  1771. });
  1772. }
  1773. );
  1774. }),
  1775. /**
  1776. * Deletes all orphaned station playlists
  1777. *
  1778. * @param {object} session - the session object automatically added by socket.io
  1779. * @param {Function} cb - gets called with the result
  1780. */
  1781. deleteOrphanedStationPlaylists: isAdminRequired(async function index(session, cb) {
  1782. async.waterfall(
  1783. [
  1784. next => {
  1785. PlaylistsModule.runJob("DELETE_ORPHANED_STATION_PLAYLISTS", {}, this)
  1786. .then(() => next())
  1787. .catch(next);
  1788. }
  1789. ],
  1790. async err => {
  1791. if (err) {
  1792. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1793. this.log(
  1794. "ERROR",
  1795. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1796. `Deleting orphaned station playlists failed. "${err}"`
  1797. );
  1798. return cb({ status: "error", message: err });
  1799. }
  1800. this.log(
  1801. "SUCCESS",
  1802. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1803. "Deleting orphaned station playlists successful."
  1804. );
  1805. return cb({ status: "success", message: "Successfully deleted orphaned station playlists." });
  1806. }
  1807. );
  1808. }),
  1809. /**
  1810. * Deletes all orphaned genre playlists
  1811. *
  1812. * @param {object} session - the session object automatically added by socket.io
  1813. * @param {Function} cb - gets called with the result
  1814. */
  1815. deleteOrphanedGenrePlaylists: isAdminRequired(async function index(session, cb) {
  1816. async.waterfall(
  1817. [
  1818. next => {
  1819. PlaylistsModule.runJob("DELETE_ORPHANED_GENRE_PLAYLISTS", {}, this)
  1820. .then(() => next())
  1821. .catch(next);
  1822. }
  1823. ],
  1824. async err => {
  1825. if (err) {
  1826. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1827. this.log(
  1828. "ERROR",
  1829. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1830. `Deleting orphaned genre playlists failed. "${err}"`
  1831. );
  1832. return cb({ status: "error", message: err });
  1833. }
  1834. this.log(
  1835. "SUCCESS",
  1836. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1837. "Deleting orphaned genre playlists successful."
  1838. );
  1839. return cb({ status: "success", message: "Successfully deleted orphaned genre playlists." });
  1840. }
  1841. );
  1842. }),
  1843. /**
  1844. * Requests orpahned playlist songs
  1845. *
  1846. * @param {object} session - the session object automatically added by socket.io
  1847. * @param {Function} cb - gets called with the result
  1848. */
  1849. requestOrphanedPlaylistSongs: isAdminRequired(async function index(session, cb) {
  1850. async.waterfall(
  1851. [
  1852. next => {
  1853. SongsModule.runJob("REQUEST_ORPHANED_PLAYLIST_SONGS", {}, this)
  1854. .then(() => next())
  1855. .catch(next);
  1856. }
  1857. ],
  1858. async err => {
  1859. if (err) {
  1860. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1861. this.log(
  1862. "ERROR",
  1863. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1864. `Requesting orphaned playlist songs failed. "${err}"`
  1865. );
  1866. return cb({ status: "error", message: err });
  1867. }
  1868. this.log(
  1869. "SUCCESS",
  1870. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1871. "Requesting orphaned playlist songs was successful."
  1872. );
  1873. return cb({ status: "success", message: "Successfully requested orphaned playlist songs." });
  1874. }
  1875. );
  1876. }),
  1877. /**
  1878. * Clears and refills a station playlist
  1879. *
  1880. * @param {object} session - the session object automatically added by socket.io
  1881. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  1882. * @param {Function} cb - gets called with the result
  1883. */
  1884. clearAndRefillStationPlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  1885. async.waterfall(
  1886. [
  1887. next => {
  1888. if (!playlistId) next("Please specify a playlist id");
  1889. else {
  1890. PlaylistsModule.runJob("CLEAR_AND_REFILL_STATION_PLAYLIST", { playlistId }, this)
  1891. .then(() => {
  1892. next();
  1893. })
  1894. .catch(err => {
  1895. next(err);
  1896. });
  1897. }
  1898. }
  1899. ],
  1900. async err => {
  1901. if (err) {
  1902. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1903. this.log(
  1904. "ERROR",
  1905. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  1906. `Clearing and refilling station playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1907. );
  1908. return cb({ status: "error", message: err });
  1909. }
  1910. this.log(
  1911. "SUCCESS",
  1912. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  1913. `Successfully cleared and refilled station playlist "${playlistId}" for user "${session.userId}".`
  1914. );
  1915. return cb({
  1916. status: "success",
  1917. message: "Playlist has been successfully cleared and refilled"
  1918. });
  1919. }
  1920. );
  1921. }),
  1922. /**
  1923. * Clears and refills a genre playlist
  1924. *
  1925. * @param {object} session - the session object automatically added by socket.io
  1926. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  1927. * @param {Function} cb - gets called with the result
  1928. */
  1929. clearAndRefillGenrePlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  1930. async.waterfall(
  1931. [
  1932. next => {
  1933. if (!playlistId) next("Please specify a playlist id");
  1934. else {
  1935. PlaylistsModule.runJob("CLEAR_AND_REFILL_GENRE_PLAYLIST", { playlistId }, this)
  1936. .then(() => {
  1937. next();
  1938. })
  1939. .catch(err => {
  1940. next(err);
  1941. });
  1942. }
  1943. }
  1944. ],
  1945. async err => {
  1946. if (err) {
  1947. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1948. this.log(
  1949. "ERROR",
  1950. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  1951. `Clearing and refilling genre playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1952. );
  1953. return cb({ status: "error", message: err });
  1954. }
  1955. this.log(
  1956. "SUCCESS",
  1957. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  1958. `Successfully cleared and refilled genre playlist "${playlistId}" for user "${session.userId}".`
  1959. );
  1960. return cb({
  1961. status: "success",
  1962. message: "Playlist has been successfully cleared and refilled"
  1963. });
  1964. }
  1965. );
  1966. }),
  1967. /**
  1968. * Clears and refills all station playlists
  1969. *
  1970. * @param {object} session - the session object automatically added by socket.io
  1971. * @param {Function} cb - gets called with the result
  1972. */
  1973. clearAndRefillAllStationPlaylists: isAdminRequired(async function index(session, cb) {
  1974. async.waterfall(
  1975. [
  1976. next => {
  1977. PlaylistsModule.runJob("GET_ALL_STATION_PLAYLISTS", {}, this)
  1978. .then(response => {
  1979. next(null, response.playlists);
  1980. })
  1981. .catch(err => {
  1982. next(err);
  1983. });
  1984. },
  1985. (playlists, next) => {
  1986. async.eachLimit(
  1987. playlists,
  1988. 1,
  1989. (playlist, next) => {
  1990. PlaylistsModule.runJob(
  1991. "CLEAR_AND_REFILL_STATION_PLAYLIST",
  1992. { playlistId: playlist._id },
  1993. this
  1994. )
  1995. .then(() => {
  1996. next();
  1997. })
  1998. .catch(err => {
  1999. next(err);
  2000. });
  2001. },
  2002. next
  2003. );
  2004. }
  2005. ],
  2006. async err => {
  2007. if (err) {
  2008. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2009. this.log(
  2010. "ERROR",
  2011. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2012. `Clearing and refilling all station playlists failed for user "${session.userId}". "${err}"`
  2013. );
  2014. return cb({ status: "error", message: err });
  2015. }
  2016. this.log(
  2017. "SUCCESS",
  2018. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2019. `Successfully cleared and refilled all station playlists for user "${session.userId}".`
  2020. );
  2021. return cb({
  2022. status: "success",
  2023. message: "Playlists have been successfully cleared and refilled"
  2024. });
  2025. }
  2026. );
  2027. }),
  2028. /**
  2029. * Clears and refills all genre playlists
  2030. *
  2031. * @param {object} session - the session object automatically added by socket.io
  2032. * @param {Function} cb - gets called with the result
  2033. */
  2034. clearAndRefillAllGenrePlaylists: isAdminRequired(async function index(session, cb) {
  2035. async.waterfall(
  2036. [
  2037. next => {
  2038. PlaylistsModule.runJob("GET_ALL_GENRE_PLAYLISTS", {}, this)
  2039. .then(response => {
  2040. next(null, response.playlists);
  2041. })
  2042. .catch(err => {
  2043. next(err);
  2044. });
  2045. },
  2046. (playlists, next) => {
  2047. async.eachLimit(
  2048. playlists,
  2049. 1,
  2050. (playlist, next) => {
  2051. PlaylistsModule.runJob(
  2052. "CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2053. { playlistId: playlist._id },
  2054. this
  2055. )
  2056. .then(() => {
  2057. next();
  2058. })
  2059. .catch(err => {
  2060. next(err);
  2061. });
  2062. },
  2063. next
  2064. );
  2065. }
  2066. ],
  2067. async err => {
  2068. if (err) {
  2069. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2070. this.log(
  2071. "ERROR",
  2072. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2073. `Clearing and refilling all genre playlists failed for user "${session.userId}". "${err}"`
  2074. );
  2075. return cb({ status: "error", message: err });
  2076. }
  2077. this.log(
  2078. "SUCCESS",
  2079. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2080. `Successfully cleared and refilled all genre playlists for user "${session.userId}".`
  2081. );
  2082. return cb({
  2083. status: "success",
  2084. message: "Playlists have been successfully cleared and refilled"
  2085. });
  2086. }
  2087. );
  2088. }),
  2089. /**
  2090. * Create missing genre playlists
  2091. *
  2092. * @param {object} session - the session object automatically added by socket.io
  2093. * @param {Function} cb - gets called with the result
  2094. */
  2095. createMissingGenrePlaylists: isAdminRequired(async function index(session, cb) {
  2096. async.waterfall(
  2097. [
  2098. next => {
  2099. PlaylistsModule.runJob("CREATE_MISSING_GENRE_PLAYLISTS", this)
  2100. .then(() => {
  2101. next();
  2102. })
  2103. .catch(err => {
  2104. next(err);
  2105. });
  2106. }
  2107. ],
  2108. async err => {
  2109. if (err) {
  2110. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2111. this.log(
  2112. "ERROR",
  2113. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2114. `Creating missing genre playlists failed for user "${session.userId}". "${err}"`
  2115. );
  2116. return cb({ status: "error", message: err });
  2117. }
  2118. this.log(
  2119. "SUCCESS",
  2120. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2121. `Successfully created missing genre playlists for user "${session.userId}".`
  2122. );
  2123. return cb({
  2124. status: "success",
  2125. message: "Missing genre playlists have been successfully created"
  2126. });
  2127. }
  2128. );
  2129. })
  2130. };