playlists.js 64 KB

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