playlists.js 67 KB

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