playlists.js 65 KB

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