playlists.js 70 KB

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