playlists.js 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811
  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. includeArtist: true,
  373. includeOwn: true,
  374. includeSongs: true,
  375. userId: session.userId,
  376. page
  377. })
  378. .then(response => {
  379. next(null, response);
  380. })
  381. .catch(err => {
  382. next(err);
  383. });
  384. }
  385. ],
  386. async (err, data) => {
  387. if (err) {
  388. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  389. this.log("ERROR", "PLAYLISTS_SEARCH_COMMUNITY", `Searching playlists failed. "${err}"`);
  390. return cb({ status: "error", message: err });
  391. }
  392. this.log("SUCCESS", "PLAYLISTS_SEARCH_COMMUNITY", "Searching playlists successful.");
  393. return cb({ status: "success", data });
  394. }
  395. );
  396. }),
  397. /**
  398. * Searches through all playlists that can be included in an official station
  399. *
  400. * @param {object} session - the session object automatically added by the websocket
  401. * @param {string} query - the query
  402. * @param {string} query - the page
  403. * @param {Function} cb - gets called with the result
  404. */
  405. searchOfficial: isAdminRequired(async function searchOfficial(session, query, page, cb) {
  406. async.waterfall(
  407. [
  408. next => {
  409. if ((!query && query !== "") || typeof query !== "string") next("Invalid query.");
  410. else next();
  411. },
  412. next => {
  413. PlaylistsModule.runJob("SEARCH", {
  414. query,
  415. includeGenre: true,
  416. includePrivate: true,
  417. includeSongs: true,
  418. page
  419. })
  420. .then(response => {
  421. next(null, response);
  422. })
  423. .catch(err => {
  424. next(err);
  425. });
  426. }
  427. ],
  428. async (err, data) => {
  429. if (err) {
  430. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  431. this.log("ERROR", "PLAYLISTS_SEARCH_OFFICIAL", `Searching playlists failed. "${err}"`);
  432. return cb({ status: "error", message: err });
  433. }
  434. this.log("SUCCESS", "PLAYLISTS_SEARCH_OFFICIAL", "Searching playlists successful.");
  435. return cb({ status: "success", data });
  436. }
  437. );
  438. }),
  439. /**
  440. * Gets the first song from a private playlist
  441. *
  442. * @param {object} session - the session object automatically added by the websocket
  443. * @param {string} playlistId - the id of the playlist we are getting the first song from
  444. * @param {Function} cb - gets called with the result
  445. */
  446. getFirstSong: isLoginRequired(function getFirstSong(session, playlistId, cb) {
  447. async.waterfall(
  448. [
  449. next => {
  450. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  451. .then(playlist => next(null, playlist))
  452. .catch(next);
  453. },
  454. (playlist, next) => {
  455. if (!playlist || playlist.createdBy !== session.userId) return next("Playlist not found.");
  456. playlist.songs.sort((a, b) => a.position - b.position);
  457. return next(null, playlist.songs[0]);
  458. }
  459. ],
  460. async (err, song) => {
  461. if (err) {
  462. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  463. this.log(
  464. "ERROR",
  465. "PLAYLIST_GET_FIRST_SONG",
  466. `Getting the first song of playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  467. );
  468. return cb({ status: "error", message: err });
  469. }
  470. this.log(
  471. "SUCCESS",
  472. "PLAYLIST_GET_FIRST_SONG",
  473. `Successfully got the first song of playlist "${playlistId}" for user "${session.userId}".`
  474. );
  475. return cb({
  476. status: "success",
  477. data: { song }
  478. });
  479. }
  480. );
  481. }),
  482. /**
  483. * Gets a list of all the playlists for a specific user
  484. *
  485. * @param {object} session - the session object automatically added by the websocket
  486. * @param {string} userId - the user id in question
  487. * @param {Function} cb - gets called with the result
  488. */
  489. indexForUser: async function indexForUser(session, userId, cb) {
  490. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  491. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  492. async.waterfall(
  493. [
  494. next => {
  495. userModel.findById(userId).select({ "preferences.orderOfPlaylists": -1 }).exec(next);
  496. },
  497. (user, next) => {
  498. if (!user) next("User not found");
  499. else {
  500. const { preferences } = user;
  501. const { orderOfPlaylists } = preferences;
  502. const match = {
  503. createdBy: userId,
  504. type: { $in: ["user", "user-liked", "user-disliked"] }
  505. };
  506. // if a playlist order exists
  507. if (orderOfPlaylists > 0) match._id = { $in: orderOfPlaylists };
  508. playlistModel
  509. .aggregate()
  510. .match(match)
  511. .addFields({
  512. weight: { $indexOfArray: [orderOfPlaylists, "$_id"] }
  513. })
  514. .sort({ weight: 1 })
  515. .exec(next);
  516. }
  517. },
  518. (playlists, next) => {
  519. if (session.userId === userId) return next(null, playlists); // user requesting playlists is the owner of the playlists
  520. const filteredPlaylists = [];
  521. return async.each(
  522. playlists,
  523. (playlist, nextPlaylist) => {
  524. if (playlist.privacy === "public") filteredPlaylists.push(playlist);
  525. return nextPlaylist();
  526. },
  527. () => next(null, filteredPlaylists)
  528. );
  529. }
  530. ],
  531. async (err, playlists) => {
  532. if (err) {
  533. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  534. this.log(
  535. "ERROR",
  536. "PLAYLIST_INDEX_FOR_USER",
  537. `Indexing playlists for user "${userId}" failed. "${err}"`
  538. );
  539. return cb({ status: "error", message: err });
  540. }
  541. this.log("SUCCESS", "PLAYLIST_INDEX_FOR_USER", `Successfully indexed playlists for user "${userId}".`);
  542. return cb({
  543. status: "success",
  544. data: { playlists }
  545. });
  546. }
  547. );
  548. },
  549. /**
  550. * Gets all playlists for the user requesting it
  551. *
  552. * @param {object} session - the session object automatically added by the websocket
  553. * @param {Function} cb - gets called with the result
  554. */
  555. indexMyPlaylists: isLoginRequired(async function indexMyPlaylists(session, cb) {
  556. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  557. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  558. async.waterfall(
  559. [
  560. next => {
  561. userModel.findById(session.userId).select({ "preferences.orderOfPlaylists": -1 }).exec(next);
  562. },
  563. (user, next) => {
  564. if (!user) next("User not found");
  565. else {
  566. const { preferences } = user;
  567. const { orderOfPlaylists } = preferences;
  568. const match = {
  569. createdBy: session.userId,
  570. type: { $in: ["user", "user-liked", "user-disliked"] }
  571. };
  572. // if a playlist order exists
  573. if (orderOfPlaylists > 0) match._id = { $in: orderOfPlaylists };
  574. playlistModel
  575. .aggregate()
  576. .match(match)
  577. .addFields({
  578. weight: { $indexOfArray: [orderOfPlaylists, "$_id"] }
  579. })
  580. .sort({ weight: 1 })
  581. .exec(next);
  582. }
  583. }
  584. ],
  585. async (err, playlists) => {
  586. if (err) {
  587. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  588. this.log(
  589. "ERROR",
  590. "PLAYLIST_INDEX_FOR_ME",
  591. `Indexing playlists for user "${session.userId}" failed. "${err}"`
  592. );
  593. return cb({ status: "error", message: err });
  594. }
  595. this.log(
  596. "SUCCESS",
  597. "PLAYLIST_INDEX_FOR_ME",
  598. `Successfully indexed playlists for user "${session.userId}".`
  599. );
  600. return cb({
  601. status: "success",
  602. data: { playlists }
  603. });
  604. }
  605. );
  606. }),
  607. /**
  608. * Gets all playlists playlists
  609. *
  610. * @param {object} session - the session object automatically added by the websocket
  611. * @param {Function} cb - gets called with the result
  612. */
  613. indexFeaturedPlaylists: isLoginRequired(async function indexMyPlaylists(session, cb) {
  614. async.waterfall(
  615. [
  616. next => {
  617. const featuredPlaylistIds = config.get("featuredPlaylists");
  618. if (featuredPlaylistIds.length === 0) next(true, []);
  619. else next(null, featuredPlaylistIds);
  620. },
  621. (featuredPlaylistIds, next) => {
  622. const featuredPlaylists = [];
  623. async.eachLimit(
  624. featuredPlaylistIds,
  625. 1,
  626. (playlistId, next) => {
  627. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  628. .then(playlist => {
  629. if (playlist.privacy === "public") featuredPlaylists.push(playlist);
  630. next();
  631. })
  632. .catch(next);
  633. },
  634. err => {
  635. next(err, featuredPlaylists);
  636. }
  637. );
  638. }
  639. ],
  640. async (err, playlists) => {
  641. if (err && err !== true) {
  642. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  643. this.log("ERROR", "PLAYLIST_INDEX_FEATURED", `Indexing featured playlists failed. "${err}"`);
  644. return cb({ status: "error", message: err });
  645. }
  646. this.log("SUCCESS", "PLAYLIST_INDEX_FEATURED", `Successfully indexed featured playlists.`);
  647. return cb({
  648. status: "success",
  649. data: { playlists }
  650. });
  651. }
  652. );
  653. }),
  654. /**
  655. * Creates a new private playlist
  656. *
  657. * @param {object} session - the session object automatically added by the websocket
  658. * @param {object} data - the data for the new private playlist
  659. * @param {Function} cb - gets called with the result
  660. */
  661. create: isLoginRequired(async function create(session, data, cb) {
  662. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  663. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  664. const blacklist = ["liked songs", "likedsongs", "disliked songs", "dislikedsongs"];
  665. async.waterfall(
  666. [
  667. next => (data ? next() : cb({ status: "error", message: "Invalid data" })),
  668. next => {
  669. const { displayName, songs, privacy } = data;
  670. if (blacklist.indexOf(displayName.toLowerCase()) !== -1)
  671. return next("That playlist name is blacklisted. Please use a different name.");
  672. return playlistModel.create(
  673. {
  674. displayName,
  675. songs,
  676. privacy,
  677. createdBy: session.userId,
  678. createdAt: Date.now(),
  679. createdFor: null,
  680. type: "user"
  681. },
  682. next
  683. );
  684. },
  685. (playlist, next) => {
  686. userModel.updateOne(
  687. { _id: session.userId },
  688. { $push: { "preferences.orderOfPlaylists": playlist._id } },
  689. err => {
  690. if (err) return next(err);
  691. return next(null, playlist);
  692. }
  693. );
  694. }
  695. ],
  696. async (err, playlist) => {
  697. if (err) {
  698. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  699. this.log(
  700. "ERROR",
  701. "PLAYLIST_CREATE",
  702. `Creating private playlist failed for user "${session.userId}". "${err}"`
  703. );
  704. return cb({ status: "error", message: err });
  705. }
  706. CacheModule.runJob("PUB", {
  707. channel: "playlist.create",
  708. value: playlist
  709. });
  710. ActivitiesModule.runJob("ADD_ACTIVITY", {
  711. userId: playlist.createdBy,
  712. type: "playlist__create",
  713. payload: {
  714. message: `Created playlist <playlistId>${playlist.displayName}</playlistId>`,
  715. playlistId: playlist._id
  716. }
  717. });
  718. this.log(
  719. "SUCCESS",
  720. "PLAYLIST_CREATE",
  721. `Successfully created private playlist for user "${session.userId}".`
  722. );
  723. return cb({
  724. status: "success",
  725. message: "Successfully created playlist",
  726. data: {
  727. playlistId: playlist._id
  728. }
  729. });
  730. }
  731. );
  732. }),
  733. /**
  734. * Gets a playlist from id
  735. *
  736. * @param {object} session - the session object automatically added by the websocket
  737. * @param {string} playlistId - the id of the playlist we are getting
  738. * @param {Function} cb - gets called with the result
  739. */
  740. getPlaylist: function getPlaylist(session, playlistId, cb) {
  741. async.waterfall(
  742. [
  743. next => {
  744. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  745. .then(playlist => next(null, playlist))
  746. .catch(next);
  747. },
  748. (playlist, next) => {
  749. if (!playlist) return next("Playlist not found");
  750. if (playlist.privacy !== "public" && playlist.createdBy !== session.userId) {
  751. if (session)
  752. // check if user requested to get a playlist is an admin
  753. return DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  754. userModel.findOne({ _id: session.userId }, (err, user) => {
  755. if (user && user.role === "admin") return next(null, playlist);
  756. return next("User unauthorised to view playlist.");
  757. });
  758. });
  759. return next("User unauthorised to view playlist.");
  760. }
  761. return next(null, playlist);
  762. }
  763. ],
  764. async (err, playlist) => {
  765. if (err) {
  766. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  767. this.log(
  768. "ERROR",
  769. "PLAYLIST_GET",
  770. `Getting private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  771. );
  772. return cb({ status: "error", message: err });
  773. }
  774. this.log(
  775. "SUCCESS",
  776. "PLAYLIST_GET",
  777. `Successfully got private playlist "${playlistId}" for user "${session.userId}".`
  778. );
  779. return cb({
  780. status: "success",
  781. data: { playlist }
  782. });
  783. }
  784. );
  785. },
  786. /**
  787. * Gets a playlist from station id
  788. *
  789. * @param {object} session - the session object automatically added by the websocket
  790. * @param {string} stationId - the id of the station we are getting
  791. * @param {string} includeSongs - include songs
  792. * @param {Function} cb - gets called with the result
  793. */
  794. getPlaylistForStation: function getPlaylist(session, stationId, includeSongs, cb) {
  795. async.waterfall(
  796. [
  797. next => {
  798. PlaylistsModule.runJob("GET_STATION_PLAYLIST", { stationId, includeSongs }, this)
  799. .then(response => next(null, response.playlist))
  800. .catch(next);
  801. },
  802. (playlist, next) => {
  803. if (!playlist) return next("Playlist not found");
  804. if (playlist.privacy !== "public" && playlist.createdBy !== session.userId) {
  805. if (session)
  806. // check if user requested to get a playlist is an admin
  807. return DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  808. userModel.findOne({ _id: session.userId }, (err, user) => {
  809. if (user && user.role === "admin") return next(null, playlist);
  810. return next("User unauthorised to view playlist.");
  811. });
  812. });
  813. return next("User unauthorised to view playlist.");
  814. }
  815. return next(null, playlist);
  816. }
  817. ],
  818. async (err, playlist) => {
  819. if (err) {
  820. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  821. this.log(
  822. "ERROR",
  823. "PLAYLIST_GET",
  824. `Getting playlist for station "${stationId}" failed for user "${session.userId}". "${err}"`
  825. );
  826. return cb({ status: "error", message: err });
  827. }
  828. this.log(
  829. "SUCCESS",
  830. "PLAYLIST_GET",
  831. `Successfully got playlist for station "${stationId}" for user "${session.userId}".`
  832. );
  833. return cb({
  834. status: "success",
  835. data: { playlist }
  836. });
  837. }
  838. );
  839. },
  840. /**
  841. * Shuffles songs in a private playlist
  842. *
  843. * @param {object} session - the session object automatically added by the websocket
  844. * @param {string} playlistId - the id of the playlist we are updating
  845. * @param {Function} cb - gets called with the result
  846. */
  847. shuffle: isLoginRequired(async function shuffle(session, playlistId, cb) {
  848. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  849. async.waterfall(
  850. [
  851. next => {
  852. if (!playlistId) return next("No playlist id.");
  853. return next();
  854. },
  855. next => {
  856. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  857. .then(playlist => {
  858. if (!playlist || playlist.createdBy !== session.userId)
  859. return next("Something went wrong when trying to get the playlist");
  860. return next(null, playlist);
  861. })
  862. .catch(next);
  863. },
  864. (playlist, next) => {
  865. if (!playlist.isUserModifiable) return next("Playlist cannot be shuffled.");
  866. return UtilsModule.runJob("SHUFFLE_SONG_POSITIONS", { array: playlist.songs }, this)
  867. .then(result => next(null, result.array))
  868. .catch(next);
  869. },
  870. (songs, next) => {
  871. playlistModel.updateOne({ _id: playlistId }, { $set: { songs } }, { runValidators: true }, next);
  872. },
  873. (res, next) => {
  874. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  875. .then(playlist => next(null, playlist))
  876. .catch(next);
  877. }
  878. ],
  879. async (err, playlist) => {
  880. if (err) {
  881. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  882. this.log(
  883. "ERROR",
  884. "PLAYLIST_SHUFFLE",
  885. `Updating private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  886. );
  887. return cb({ status: "error", message: err });
  888. }
  889. this.log(
  890. "SUCCESS",
  891. "PLAYLIST_SHUFFLE",
  892. `Successfully updated private playlist "${playlistId}" for user "${session.userId}".`
  893. );
  894. return cb({
  895. status: "success",
  896. message: "Successfully shuffled playlist.",
  897. data: { playlist }
  898. });
  899. }
  900. );
  901. }),
  902. /**
  903. * Changes the order (position) of a song in a playlist
  904. *
  905. * @param {object} session - the session object automatically added by the websocket
  906. * @param {string} playlistId - the id of the playlist we are targeting
  907. * @param {object} song - the song to be repositioned
  908. * @param {string} song.youtubeId - the youtube id of the song being repositioned
  909. * @param {string} song.newIndex - the new position of the song in the playlist
  910. * @param {...any} song.args - any other elements that would be included with a song item in a playlist
  911. * @param {Function} cb - gets called with the result
  912. */
  913. repositionSong: isLoginRequired(async function repositionSong(session, playlistId, song, cb) {
  914. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  915. async.waterfall(
  916. [
  917. next => {
  918. if (!playlistId) return next("Please provide a playlist.");
  919. if (!song || !song.youtubeId) return next("You must provide a song to reposition.");
  920. return next();
  921. },
  922. next => {
  923. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  924. .then(playlist => {
  925. if (!playlist || playlist.createdBy !== session.userId) {
  926. return DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  927. userModel.findOne({ _id: session.userId }, (err, user) => {
  928. if (user && user.role === "admin") return next();
  929. return next("Something went wrong when trying to get the playlist");
  930. });
  931. });
  932. }
  933. return next();
  934. })
  935. .catch(next);
  936. },
  937. // remove song from playlist
  938. next => {
  939. playlistModel.updateOne(
  940. { _id: playlistId },
  941. { $pull: { songs: { youtubeId: song.youtubeId } } },
  942. next
  943. );
  944. },
  945. // add song back to playlist (in new position)
  946. (res, next) => {
  947. playlistModel.updateOne(
  948. { _id: playlistId },
  949. { $push: { songs: { $each: [song], $position: song.newIndex } } },
  950. err => next(err)
  951. );
  952. },
  953. // update the cache with the new songs positioning
  954. next => {
  955. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  956. .then(playlist => next(null, playlist))
  957. .catch(next);
  958. }
  959. ],
  960. async err => {
  961. if (err) {
  962. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  963. this.log(
  964. "ERROR",
  965. "PLAYLIST_REPOSITION_SONG",
  966. `Repositioning song ${song.youtubeId} for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  967. );
  968. return cb({ status: "error", message: err });
  969. }
  970. this.log(
  971. "SUCCESS",
  972. "PLAYLIST_REPOSITION_SONG",
  973. `Successfully repositioned song ${song.youtubeId} for private playlist "${playlistId}" for user "${session.userId}".`
  974. );
  975. CacheModule.runJob("PUB", {
  976. channel: "playlist.repositionSong",
  977. value: {
  978. userId: session.userId,
  979. playlistId,
  980. song
  981. }
  982. });
  983. return cb({
  984. status: "success",
  985. message: "Successfully repositioned song"
  986. });
  987. }
  988. );
  989. }),
  990. /**
  991. * Adds a song to a private playlist
  992. *
  993. * @param {object} session - the session object automatically added by the websocket
  994. * @param {boolean} isSet - is the song part of a set of songs to be added
  995. * @param {string} youtubeId - the youtube id of the song we are trying to add
  996. * @param {string} playlistId - the id of the playlist we are adding the song to
  997. * @param {Function} cb - gets called with the result
  998. */
  999. addSongToPlaylist: isLoginRequired(async function addSongToPlaylist(session, isSet, youtubeId, playlistId, cb) {
  1000. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1001. async.waterfall(
  1002. [
  1003. next => {
  1004. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1005. .then(playlist => {
  1006. if (!playlist || playlist.createdBy !== session.userId) {
  1007. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1008. userModel.findOne({ _id: session.userId }, (err, user) => {
  1009. if (user && user.role === "admin") return next(null, playlist);
  1010. return next("Something went wrong when trying to get the playlist");
  1011. });
  1012. });
  1013. } else next(null, playlist);
  1014. })
  1015. .catch(next);
  1016. },
  1017. (playlist, next) => {
  1018. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1019. const oppositeType = playlist.type === "user-liked" ? "user-disliked" : "user-liked";
  1020. const oppositePlaylistName = oppositeType === "user-liked" ? "Liked Songs" : "Disliked Songs";
  1021. playlistModel.count(
  1022. { type: oppositeType, createdBy: session.userId, "songs.youtubeId": youtubeId },
  1023. (err, results) => {
  1024. if (err) next(err);
  1025. else if (results > 0)
  1026. next(
  1027. `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.`
  1028. );
  1029. else next();
  1030. }
  1031. );
  1032. } else next();
  1033. },
  1034. next => {
  1035. PlaylistsModule.runJob("ADD_SONG_TO_PLAYLIST", { playlistId, youtubeId }, this)
  1036. .then(res => {
  1037. const { playlist, song, ratings } = res;
  1038. next(null, playlist, song, ratings);
  1039. })
  1040. .catch(next);
  1041. }
  1042. ],
  1043. async (err, playlist, newSong, ratings) => {
  1044. if (err) {
  1045. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1046. this.log(
  1047. "ERROR",
  1048. "PLAYLIST_ADD_SONG",
  1049. `Adding song "${youtubeId}" to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1050. );
  1051. return cb({ status: "error", message: err });
  1052. }
  1053. this.log(
  1054. "SUCCESS",
  1055. "PLAYLIST_ADD_SONG",
  1056. `Successfully added song "${youtubeId}" to private playlist "${playlistId}" for user "${session.userId}".`
  1057. );
  1058. if (!isSet && playlist.type === "user" && playlist.privacy === "public") {
  1059. const songName = newSong.artists
  1060. ? `${newSong.title} by ${newSong.artists.join(", ")}`
  1061. : newSong.title;
  1062. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1063. userId: session.userId,
  1064. type: "playlist__add_song",
  1065. payload: {
  1066. message: `Added <youtubeId>${songName}</youtubeId> to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1067. thumbnail: newSong.thumbnail,
  1068. playlistId,
  1069. youtubeId
  1070. }
  1071. });
  1072. }
  1073. CacheModule.runJob("PUB", {
  1074. channel: "playlist.addSong",
  1075. value: {
  1076. playlistId: playlist._id,
  1077. song: newSong,
  1078. userId: session.userId,
  1079. privacy: playlist.privacy
  1080. }
  1081. });
  1082. CacheModule.runJob("PUB", {
  1083. channel: "playlist.updated",
  1084. value: { playlistId }
  1085. });
  1086. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1087. const { _id, youtubeId, title, artists, thumbnail } = newSong;
  1088. const { likes, dislikes } = ratings;
  1089. SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1090. if (playlist.type === "user-liked") {
  1091. CacheModule.runJob("PUB", {
  1092. channel: "song.like",
  1093. value: JSON.stringify({
  1094. youtubeId,
  1095. userId: session.userId,
  1096. likes,
  1097. dislikes
  1098. })
  1099. });
  1100. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1101. userId: session.userId,
  1102. type: "song__like",
  1103. payload: {
  1104. message: `Liked song <youtubeId>${title} by ${artists.join(", ")}</youtubeId>`,
  1105. youtubeId,
  1106. thumbnail
  1107. }
  1108. });
  1109. } else {
  1110. CacheModule.runJob("PUB", {
  1111. channel: "song.dislike",
  1112. value: JSON.stringify({
  1113. youtubeId,
  1114. userId: session.userId,
  1115. likes,
  1116. dislikes
  1117. })
  1118. });
  1119. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1120. userId: session.userId,
  1121. type: "song__dislike",
  1122. payload: {
  1123. message: `Disliked song <youtubeId>${title} by ${artists.join(", ")}</youtubeId>`,
  1124. youtubeId,
  1125. thumbnail
  1126. }
  1127. });
  1128. }
  1129. }
  1130. return cb({
  1131. status: "success",
  1132. message: "Song has been successfully added to the playlist",
  1133. data: { songs: playlist.songs }
  1134. });
  1135. }
  1136. );
  1137. }),
  1138. /**
  1139. * Adds a set of songs to a private playlist
  1140. *
  1141. * @param {object} session - the session object automatically added by the websocket
  1142. * @param {string} url - the url of the the YouTube playlist
  1143. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  1144. * @param {boolean} musicOnly - whether to only add music to the playlist
  1145. * @param {Function} cb - gets called with the result
  1146. */
  1147. addSetToPlaylist: isLoginRequired(async function addSetToPlaylist(session, url, playlistId, musicOnly, cb) {
  1148. let videosInPlaylistTotal = 0;
  1149. let songsInPlaylistTotal = 0;
  1150. let addSongsStats = null;
  1151. const addedSongs = [];
  1152. this.keepLongJob();
  1153. this.publishProgress({
  1154. status: "started",
  1155. title: "Import YouTube playlist",
  1156. message: "Importing YouTube playlist.",
  1157. id: this.toString()
  1158. });
  1159. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1160. await CacheModule.runJob(
  1161. "PUB",
  1162. {
  1163. channel: "longJob.added",
  1164. value: { jobId: this.toString(), userId: session.userId }
  1165. },
  1166. this
  1167. );
  1168. async.waterfall(
  1169. [
  1170. next => {
  1171. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1172. userModel.findOne({ _id: session.userId }, (err, user) => {
  1173. if (user && user.role === "admin") return next(null, true);
  1174. return next(null, false);
  1175. });
  1176. });
  1177. },
  1178. (isAdmin, next) => {
  1179. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 1)` });
  1180. const playlistRegex = /[\\?&]list=([^&#]*)/;
  1181. const channelRegex =
  1182. /\.[\w]+\/(?:(?:channel\/(UC[0-9A-Za-z_-]{21}[AQgw]))|(?:user\/?([\w-]+))|(?:c\/?([\w-]+))|(?:\/?([\w-]+)))/;
  1183. if (playlistRegex.exec(url) || channelRegex.exec(url))
  1184. YouTubeModule.runJob(
  1185. playlistRegex.exec(url) ? "GET_PLAYLIST" : "GET_CHANNEL",
  1186. {
  1187. url,
  1188. musicOnly,
  1189. disableSearch: !isAdmin
  1190. },
  1191. this
  1192. )
  1193. .then(res => {
  1194. if (res.filteredSongs) {
  1195. videosInPlaylistTotal = res.songs.length;
  1196. songsInPlaylistTotal = res.filteredSongs.length;
  1197. } else {
  1198. songsInPlaylistTotal = videosInPlaylistTotal = res.songs.length;
  1199. }
  1200. next(null, res.songs);
  1201. })
  1202. .catch(next);
  1203. else next("Invalid YouTube URL.");
  1204. },
  1205. (youtubeIds, next) => {
  1206. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 2)` });
  1207. let successful = 0;
  1208. let failed = 0;
  1209. let alreadyInPlaylist = 0;
  1210. let alreadyInLikedPlaylist = 0;
  1211. let alreadyInDislikedPlaylist = 0;
  1212. if (youtubeIds.length === 0) next();
  1213. async.eachLimit(
  1214. youtubeIds,
  1215. 1,
  1216. (youtubeId, next) => {
  1217. WSModule.runJob(
  1218. "RUN_ACTION2",
  1219. {
  1220. session,
  1221. namespace: "playlists",
  1222. action: "addSongToPlaylist",
  1223. args: [true, youtubeId, playlistId]
  1224. },
  1225. this
  1226. )
  1227. .then(res => {
  1228. if (res.status === "success") {
  1229. successful += 1;
  1230. addedSongs.push(youtubeId);
  1231. } else failed += 1;
  1232. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  1233. else if (
  1234. res.message ===
  1235. "That song is already in your Liked Songs playlist. " +
  1236. "A song cannot be in both the Liked Songs playlist" +
  1237. " and the Disliked Songs playlist at the same time."
  1238. )
  1239. alreadyInLikedPlaylist += 1;
  1240. else if (
  1241. res.message ===
  1242. "That song is already in your Disliked Songs playlist. " +
  1243. "A song cannot be in both the Liked Songs playlist " +
  1244. "and the Disliked Songs playlist at the same time."
  1245. )
  1246. alreadyInDislikedPlaylist += 1;
  1247. })
  1248. .catch(() => {
  1249. failed += 1;
  1250. })
  1251. .finally(() => next());
  1252. },
  1253. () => {
  1254. addSongsStats = {
  1255. successful,
  1256. failed,
  1257. alreadyInPlaylist,
  1258. alreadyInLikedPlaylist,
  1259. alreadyInDislikedPlaylist
  1260. };
  1261. next(null);
  1262. }
  1263. );
  1264. },
  1265. next => {
  1266. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 3)` });
  1267. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1268. .then(playlist => next(null, playlist))
  1269. .catch(next);
  1270. },
  1271. (playlist, next) => {
  1272. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 4)` });
  1273. if (!playlist || playlist.createdBy !== session.userId) {
  1274. return DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1275. userModel.findOne({ _id: session.userId }, (err, user) => {
  1276. if (user && user.role === "admin") return next(null, playlist);
  1277. return next("Something went wrong when trying to get the playlist");
  1278. });
  1279. });
  1280. }
  1281. return next(null, playlist);
  1282. }
  1283. ],
  1284. async (err, playlist) => {
  1285. if (err) {
  1286. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1287. this.log(
  1288. "ERROR",
  1289. "PLAYLIST_IMPORT",
  1290. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1291. );
  1292. this.publishProgress({
  1293. status: "error",
  1294. message: err
  1295. });
  1296. return cb({ status: "error", message: err });
  1297. }
  1298. if (playlist.privacy === "public")
  1299. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1300. userId: session.userId,
  1301. type: "playlist__import_playlist",
  1302. payload: {
  1303. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1304. playlistId
  1305. }
  1306. });
  1307. this.log(
  1308. "SUCCESS",
  1309. "PLAYLIST_IMPORT",
  1310. `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}.`
  1311. );
  1312. this.publishProgress({
  1313. status: "success",
  1314. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`
  1315. });
  1316. return cb({
  1317. status: "success",
  1318. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  1319. data: {
  1320. songs: playlist.songs,
  1321. stats: {
  1322. videosInPlaylistTotal,
  1323. songsInPlaylistTotal,
  1324. alreadyInLikedPlaylist: addSongsStats.alreadyInLikedPlaylist,
  1325. alreadyInDislikedPlaylist: addSongsStats.alreadyInDislikedPlaylist
  1326. }
  1327. }
  1328. });
  1329. }
  1330. );
  1331. }),
  1332. /**
  1333. * Removes a song from a private playlist
  1334. *
  1335. * @param {object} session - the session object automatically added by the websocket
  1336. * @param {string} youtubeId - the youtube id of the song we are removing from the private playlist
  1337. * @param {string} playlistId - the id of the playlist we are removing the song from
  1338. * @param {Function} cb - gets called with the result
  1339. */
  1340. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(session, youtubeId, playlistId, cb) {
  1341. async.waterfall(
  1342. [
  1343. next => {
  1344. if (!youtubeId || typeof youtubeId !== "string") return next("Invalid song id.");
  1345. if (!playlistId || typeof youtubeId !== "string") return next("Invalid playlist id.");
  1346. return next();
  1347. },
  1348. next => {
  1349. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1350. .then(playlist => {
  1351. if (!playlist || playlist.createdBy !== session.userId) {
  1352. return DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1353. userModel.findOne({ _id: session.userId }, (err, user) => {
  1354. if (user && user.role === "admin") return next(null, playlist);
  1355. return next("Something went wrong when trying to get the playlist");
  1356. });
  1357. });
  1358. }
  1359. return next(null, playlist);
  1360. })
  1361. .catch(next);
  1362. },
  1363. (playlist, next) => {
  1364. MediaModule.runJob("GET_MEDIA", { youtubeId }, this)
  1365. .then(res =>
  1366. next(null, playlist, {
  1367. _id: res.song._id,
  1368. title: res.song.title,
  1369. thumbnail: res.song.thumbnail,
  1370. artists: res.song.artists,
  1371. youtubeId: res.song.youtubeId
  1372. })
  1373. )
  1374. .catch(next);
  1375. },
  1376. (playlist, newSong, next) => {
  1377. PlaylistsModule.runJob("REMOVE_FROM_PLAYLIST", { playlistId, youtubeId }, this)
  1378. .then(res => {
  1379. const { ratings } = res;
  1380. next(null, playlist, newSong, ratings);
  1381. })
  1382. .catch(next);
  1383. },
  1384. (playlist, newSong, ratings, next) => {
  1385. const { _id, title, artists, thumbnail } = newSong;
  1386. const songName = artists ? `${title} by ${artists.join(", ")}` : title;
  1387. if (playlist.type === "user" && playlist.privacy === "public") {
  1388. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1389. userId: session.userId,
  1390. type: "playlist__remove_song",
  1391. payload: {
  1392. message: `Removed <youtubeId>${songName}</youtubeId> from playlist <playlistId>${playlist.displayName}</playlistId>`,
  1393. thumbnail,
  1394. playlistId,
  1395. youtubeId: newSong.youtubeId
  1396. }
  1397. });
  1398. }
  1399. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1400. const { likes, dislikes } = ratings;
  1401. SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1402. if (playlist.type === "user-liked") {
  1403. CacheModule.runJob("PUB", {
  1404. channel: "ratings.unlike",
  1405. value: JSON.stringify({
  1406. youtubeId: newSong.youtubeId,
  1407. userId: session.userId,
  1408. likes,
  1409. dislikes
  1410. })
  1411. });
  1412. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1413. userId: session.userId,
  1414. type: "song__unlike",
  1415. payload: {
  1416. message: `Removed <youtubeId>${title} by ${artists.join(
  1417. ", "
  1418. )}</youtubeId> from your Liked Songs`,
  1419. youtubeId: newSong.youtubeId,
  1420. thumbnail
  1421. }
  1422. });
  1423. } else {
  1424. CacheModule.runJob("PUB", {
  1425. channel: "song.undislike",
  1426. value: JSON.stringify({
  1427. youtubeId: newSong.youtubeId,
  1428. userId: session.userId,
  1429. likes,
  1430. dislikes
  1431. })
  1432. });
  1433. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1434. userId: session.userId,
  1435. type: "song__undislike",
  1436. payload: {
  1437. message: `Removed <youtubeId>${title} by ${artists.join(
  1438. ", "
  1439. )}</youtubeId> from your Disliked Songs`,
  1440. youtubeId: newSong.youtubeId,
  1441. thumbnail
  1442. }
  1443. });
  1444. }
  1445. }
  1446. return next(null, playlist);
  1447. }
  1448. ],
  1449. async (err, playlist) => {
  1450. if (err) {
  1451. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1452. this.log(
  1453. "ERROR",
  1454. "PLAYLIST_REMOVE_SONG",
  1455. `Removing song "${youtubeId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1456. );
  1457. return cb({ status: "error", message: err });
  1458. }
  1459. this.log(
  1460. "SUCCESS",
  1461. "PLAYLIST_REMOVE_SONG",
  1462. `Successfully removed song "${youtubeId}" from private playlist "${playlistId}" for user "${session.userId}".`
  1463. );
  1464. CacheModule.runJob("PUB", {
  1465. channel: "playlist.removeSong",
  1466. value: {
  1467. playlistId: playlist._id,
  1468. youtubeId,
  1469. userId: session.userId,
  1470. privacy: playlist.privacy
  1471. }
  1472. });
  1473. return cb({
  1474. status: "success",
  1475. message: "Song has been successfully removed from playlist",
  1476. data: { songs: playlist.songs }
  1477. });
  1478. }
  1479. );
  1480. }),
  1481. /**
  1482. * Updates the displayName of a private playlist
  1483. *
  1484. * @param {object} session - the session object automatically added by the websocket
  1485. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  1486. * @param {Function} cb - gets called with the result
  1487. */
  1488. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  1489. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1490. async.waterfall(
  1491. [
  1492. next => {
  1493. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1494. .then(playlist => next(null, playlist))
  1495. .catch(next);
  1496. },
  1497. (playlist, next) => {
  1498. if (playlist.type !== "user") return next("Playlist cannot be modified.");
  1499. return next(null);
  1500. },
  1501. next => {
  1502. playlistModel.updateOne(
  1503. { _id: playlistId, createdBy: session.userId },
  1504. { $set: { displayName } },
  1505. { runValidators: true },
  1506. next
  1507. );
  1508. },
  1509. (res, next) => {
  1510. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1511. .then(playlist => next(null, playlist))
  1512. .catch(next);
  1513. }
  1514. ],
  1515. async (err, playlist) => {
  1516. if (err) {
  1517. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1518. this.log(
  1519. "ERROR",
  1520. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1521. `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1522. );
  1523. return cb({ status: "error", message: err });
  1524. }
  1525. this.log(
  1526. "SUCCESS",
  1527. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1528. `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${session.userId}".`
  1529. );
  1530. CacheModule.runJob("PUB", {
  1531. channel: "playlist.updateDisplayName",
  1532. value: {
  1533. playlistId,
  1534. displayName,
  1535. userId: session.userId,
  1536. privacy: playlist.privacy
  1537. }
  1538. });
  1539. CacheModule.runJob("PUB", {
  1540. channel: "playlist.updated",
  1541. value: { playlistId }
  1542. });
  1543. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1544. userId: session.userId,
  1545. type: "playlist__edit_display_name",
  1546. payload: {
  1547. message: `Changed display name of playlist <playlistId>${displayName}</playlistId>`,
  1548. playlistId
  1549. }
  1550. });
  1551. return cb({
  1552. status: "success",
  1553. message: "Playlist has been successfully updated"
  1554. });
  1555. }
  1556. );
  1557. }),
  1558. /**
  1559. * Removes a user's own modifiable user playlist
  1560. *
  1561. * @param {object} session - the session object automatically added by the websocket
  1562. * @param {string} playlistId - the id of the playlist we are removing
  1563. * @param {Function} cb - gets called with the result
  1564. */
  1565. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1566. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1567. async.waterfall(
  1568. [
  1569. next => {
  1570. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1571. .then(playlist => next(null, playlist))
  1572. .catch(next);
  1573. },
  1574. (playlist, next) => {
  1575. if (playlist.createdBy !== session.userId) return next("You do not own this playlist.");
  1576. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1577. return next(null, playlist);
  1578. },
  1579. (playlist, next) => {
  1580. userModel.updateOne(
  1581. { _id: playlist.createdBy },
  1582. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1583. err => next(err, playlist)
  1584. );
  1585. },
  1586. (playlist, next) => {
  1587. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1588. .then(() => next(null, playlist))
  1589. .catch(next);
  1590. }
  1591. ],
  1592. async (err, playlist) => {
  1593. if (err) {
  1594. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1595. this.log(
  1596. "ERROR",
  1597. "PLAYLIST_REMOVE",
  1598. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1599. );
  1600. return cb({ status: "error", message: err });
  1601. }
  1602. this.log(
  1603. "SUCCESS",
  1604. "PLAYLIST_REMOVE",
  1605. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1606. );
  1607. CacheModule.runJob("PUB", {
  1608. channel: "playlist.delete",
  1609. value: {
  1610. userId: session.userId,
  1611. playlistId
  1612. }
  1613. });
  1614. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1615. userId: playlist.createdBy,
  1616. type: "playlist__remove",
  1617. payload: {
  1618. message: `Removed playlist ${playlist.displayName}`
  1619. }
  1620. });
  1621. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1622. return cb({
  1623. status: "success",
  1624. message: "Playlist successfully removed"
  1625. });
  1626. }
  1627. );
  1628. }),
  1629. /**
  1630. * Removes a user's modifiable user playlist as an admin
  1631. *
  1632. * @param {object} session - the session object automatically added by the websocket
  1633. * @param {string} playlistId - the id of the playlist we are removing
  1634. * @param {Function} cb - gets called with the result
  1635. */
  1636. removeAdmin: isAdminRequired(async function removeAdmin(session, playlistId, cb) {
  1637. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1638. async.waterfall(
  1639. [
  1640. next => {
  1641. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1642. .then(playlist => next(null, playlist))
  1643. .catch(next);
  1644. },
  1645. (playlist, next) => {
  1646. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1647. return next(null, playlist);
  1648. },
  1649. (playlist, next) => {
  1650. userModel.updateOne(
  1651. { _id: playlist.createdBy },
  1652. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1653. err => next(err, playlist, playlist.createdBy)
  1654. );
  1655. },
  1656. (playlist, playlistCreator, next) => {
  1657. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1658. .then(() => next(null, playlistCreator))
  1659. .catch(next);
  1660. }
  1661. ],
  1662. async (err, playlistCreator) => {
  1663. if (err) {
  1664. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1665. this.log(
  1666. "ERROR",
  1667. "PLAYLIST_REMOVE_ADMIN",
  1668. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1669. );
  1670. return cb({ status: "error", message: err });
  1671. }
  1672. this.log(
  1673. "SUCCESS",
  1674. "PLAYLIST_REMOVE_ADMIN",
  1675. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1676. );
  1677. CacheModule.runJob("PUB", {
  1678. channel: "playlist.delete",
  1679. value: {
  1680. userId: playlistCreator,
  1681. playlistId
  1682. }
  1683. });
  1684. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1685. return cb({
  1686. status: "success",
  1687. message: "Playlist successfully removed"
  1688. });
  1689. }
  1690. );
  1691. }),
  1692. /**
  1693. * Updates the privacy of a private playlist
  1694. *
  1695. * @param {object} session - the session object automatically added by the websocket
  1696. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1697. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1698. * @param {Function} cb - gets called with the result
  1699. */
  1700. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  1701. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1702. async.waterfall(
  1703. [
  1704. next => {
  1705. playlistModel.updateOne(
  1706. { _id: playlistId, createdBy: session.userId },
  1707. { $set: { privacy } },
  1708. { runValidators: true },
  1709. next
  1710. );
  1711. },
  1712. (res, next) => {
  1713. if (res.n === 0) next("No user playlist found with that id and owned by you.");
  1714. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1715. else {
  1716. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1717. .then(playlist => next(null, playlist))
  1718. .catch(next);
  1719. }
  1720. }
  1721. ],
  1722. async (err, playlist) => {
  1723. if (err) {
  1724. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1725. this.log(
  1726. "ERROR",
  1727. "PLAYLIST_UPDATE_PRIVACY",
  1728. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1729. );
  1730. return cb({ status: "error", message: err });
  1731. }
  1732. this.log(
  1733. "SUCCESS",
  1734. "PLAYLIST_UPDATE_PRIVACY",
  1735. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  1736. );
  1737. CacheModule.runJob("PUB", {
  1738. channel: "playlist.updatePrivacy",
  1739. value: {
  1740. userId: session.userId,
  1741. playlist
  1742. }
  1743. });
  1744. CacheModule.runJob("PUB", {
  1745. channel: "playlist.updated",
  1746. value: { playlistId }
  1747. });
  1748. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1749. userId: session.userId,
  1750. type: "playlist__edit_privacy",
  1751. payload: {
  1752. message: `Changed privacy of playlist <playlistId>${playlist.displayName}</playlistId> to ${privacy}`,
  1753. playlistId
  1754. }
  1755. });
  1756. return cb({
  1757. status: "success",
  1758. message: "Playlist has been successfully updated"
  1759. });
  1760. }
  1761. );
  1762. }),
  1763. /**
  1764. * Updates the privacy of a playlist
  1765. *
  1766. * @param {object} session - the session object automatically added by the websocket
  1767. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1768. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1769. * @param {Function} cb - gets called with the result
  1770. */
  1771. updatePrivacyAdmin: isAdminRequired(async function updatePrivacyAdmin(session, playlistId, privacy, cb) {
  1772. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1773. async.waterfall(
  1774. [
  1775. next => {
  1776. playlistModel.updateOne({ _id: playlistId }, { $set: { privacy } }, { runValidators: true }, next);
  1777. },
  1778. (res, next) => {
  1779. if (res.n === 0) next("No playlist found with that id.");
  1780. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1781. else {
  1782. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1783. .then(playlist => next(null, playlist))
  1784. .catch(next);
  1785. }
  1786. }
  1787. ],
  1788. async (err, playlist) => {
  1789. if (err) {
  1790. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1791. this.log(
  1792. "ERROR",
  1793. "PLAYLIST_UPDATE_PRIVACY_ADMIN",
  1794. `Updating privacy to "${privacy}" for playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1795. );
  1796. return cb({ status: "error", message: err });
  1797. }
  1798. this.log(
  1799. "SUCCESS",
  1800. "PLAYLIST_UPDATE_PRIVACY_ADMIn",
  1801. `Successfully updated privacy to "${privacy}" for playlist "${playlistId}" for user "${session.userId}".`
  1802. );
  1803. if (playlist.type === "user") {
  1804. CacheModule.runJob("PUB", {
  1805. channel: "playlist.updatePrivacy",
  1806. value: {
  1807. userId: playlist.createdBy,
  1808. playlist
  1809. }
  1810. });
  1811. }
  1812. CacheModule.runJob("PUB", {
  1813. channel: "playlist.updated",
  1814. value: { playlistId }
  1815. });
  1816. return cb({
  1817. status: "success",
  1818. message: "Playlist has been successfully updated"
  1819. });
  1820. }
  1821. );
  1822. }),
  1823. /**
  1824. * Deletes all orphaned station playlists
  1825. *
  1826. * @param {object} session - the session object automatically added by socket.io
  1827. * @param {Function} cb - gets called with the result
  1828. */
  1829. deleteOrphanedStationPlaylists: isAdminRequired(async function index(session, cb) {
  1830. this.keepLongJob();
  1831. this.publishProgress({
  1832. status: "started",
  1833. title: "Delete orphaned station playlists",
  1834. message: "Deleting orphaned station playlists.",
  1835. id: this.toString()
  1836. });
  1837. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1838. await CacheModule.runJob(
  1839. "PUB",
  1840. {
  1841. channel: "longJob.added",
  1842. value: { jobId: this.toString(), userId: session.userId }
  1843. },
  1844. this
  1845. );
  1846. async.waterfall(
  1847. [
  1848. next => {
  1849. PlaylistsModule.runJob("DELETE_ORPHANED_STATION_PLAYLISTS", {}, this)
  1850. .then(() => next())
  1851. .catch(next);
  1852. }
  1853. ],
  1854. async err => {
  1855. if (err) {
  1856. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1857. this.log(
  1858. "ERROR",
  1859. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1860. `Deleting orphaned station playlists failed. "${err}"`
  1861. );
  1862. this.publishProgress({
  1863. status: "error",
  1864. message: err
  1865. });
  1866. return cb({ status: "error", message: err });
  1867. }
  1868. this.log(
  1869. "SUCCESS",
  1870. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1871. "Deleting orphaned station playlists successful."
  1872. );
  1873. this.publishProgress({
  1874. status: "success",
  1875. message: "Successfully deleted orphaned station playlists."
  1876. });
  1877. return cb({ status: "success", message: "Successfully deleted orphaned station playlists." });
  1878. }
  1879. );
  1880. }),
  1881. /**
  1882. * Deletes all orphaned genre playlists
  1883. *
  1884. * @param {object} session - the session object automatically added by socket.io
  1885. * @param {Function} cb - gets called with the result
  1886. */
  1887. deleteOrphanedGenrePlaylists: isAdminRequired(async function index(session, cb) {
  1888. this.keepLongJob();
  1889. this.publishProgress({
  1890. status: "started",
  1891. title: "Delete orphaned genre playlists",
  1892. message: "Deleting orphaned genre playlists.",
  1893. id: this.toString()
  1894. });
  1895. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1896. await CacheModule.runJob(
  1897. "PUB",
  1898. {
  1899. channel: "longJob.added",
  1900. value: { jobId: this.toString(), userId: session.userId }
  1901. },
  1902. this
  1903. );
  1904. async.waterfall(
  1905. [
  1906. next => {
  1907. PlaylistsModule.runJob("DELETE_ORPHANED_GENRE_PLAYLISTS", {}, this)
  1908. .then(() => next())
  1909. .catch(next);
  1910. }
  1911. ],
  1912. async err => {
  1913. if (err) {
  1914. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1915. this.log(
  1916. "ERROR",
  1917. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1918. `Deleting orphaned genre playlists failed. "${err}"`
  1919. );
  1920. this.publishProgress({
  1921. status: "error",
  1922. message: err
  1923. });
  1924. return cb({ status: "error", message: err });
  1925. }
  1926. this.log(
  1927. "SUCCESS",
  1928. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1929. "Deleting orphaned genre playlists successful."
  1930. );
  1931. this.publishProgress({
  1932. status: "success",
  1933. message: "Successfully deleted orphaned genre playlists."
  1934. });
  1935. return cb({ status: "success", message: "Successfully deleted orphaned genre playlists." });
  1936. }
  1937. );
  1938. }),
  1939. /**
  1940. * Deletes all orphaned artist playlists
  1941. *
  1942. * @param {object} session - the session object automatically added by socket.io
  1943. * @param {Function} cb - gets called with the result
  1944. */
  1945. deleteOrphanedArtistPlaylists: isAdminRequired(async function index(session, cb) {
  1946. async.waterfall(
  1947. [
  1948. next => {
  1949. PlaylistsModule.runJob("DELETE_ORPHANED_ARTIST_PLAYLISTS", {}, this)
  1950. .then(() => next())
  1951. .catch(next);
  1952. }
  1953. ],
  1954. async err => {
  1955. if (err) {
  1956. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1957. this.log(
  1958. "ERROR",
  1959. "PLAYLISTS_DELETE_ORPHANED_ARTIST_PLAYLISTS",
  1960. `Deleting orphaned artist playlists failed. "${err}"`
  1961. );
  1962. return cb({ status: "error", message: err });
  1963. }
  1964. this.log(
  1965. "SUCCESS",
  1966. "PLAYLISTS_DELETE_ORPHANED_ARTIST_PLAYLISTS",
  1967. "Deleting orphaned artist playlists successful."
  1968. );
  1969. return cb({ status: "success", message: "Successfully deleted orphaned artist playlists." });
  1970. }
  1971. );
  1972. }),
  1973. /**
  1974. * Requests orpahned playlist songs
  1975. *
  1976. * @param {object} session - the session object automatically added by socket.io
  1977. * @param {Function} cb - gets called with the result
  1978. */
  1979. requestOrphanedPlaylistSongs: isAdminRequired(async function index(session, cb) {
  1980. this.keepLongJob();
  1981. this.publishProgress({
  1982. status: "started",
  1983. title: "Request orphaned playlist songs",
  1984. message: "Requesting orphaned playlist songs.",
  1985. id: this.toString()
  1986. });
  1987. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1988. await CacheModule.runJob(
  1989. "PUB",
  1990. {
  1991. channel: "longJob.added",
  1992. value: { jobId: this.toString(), userId: session.userId }
  1993. },
  1994. this
  1995. );
  1996. async.waterfall(
  1997. [
  1998. next => {
  1999. SongsModule.runJob("REQUEST_ORPHANED_PLAYLIST_SONGS", {}, this)
  2000. .then(() => next())
  2001. .catch(next);
  2002. }
  2003. ],
  2004. async err => {
  2005. if (err) {
  2006. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2007. this.log(
  2008. "ERROR",
  2009. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  2010. `Requesting orphaned playlist songs failed. "${err}"`
  2011. );
  2012. this.publishProgress({
  2013. status: "error",
  2014. message: err
  2015. });
  2016. return cb({ status: "error", message: err });
  2017. }
  2018. this.log(
  2019. "SUCCESS",
  2020. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  2021. "Requesting orphaned playlist songs was successful."
  2022. );
  2023. this.publishProgress({
  2024. status: "success",
  2025. message: "Successfully requested orphaned playlist songs."
  2026. });
  2027. return cb({ status: "success", message: "Successfully requested orphaned playlist songs." });
  2028. }
  2029. );
  2030. }),
  2031. /**
  2032. * Clears and refills a station playlist
  2033. *
  2034. * @param {object} session - the session object automatically added by socket.io
  2035. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  2036. * @param {Function} cb - gets called with the result
  2037. */
  2038. clearAndRefillStationPlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  2039. async.waterfall(
  2040. [
  2041. next => {
  2042. if (!playlistId) next("Please specify a playlist id");
  2043. else {
  2044. PlaylistsModule.runJob("CLEAR_AND_REFILL_STATION_PLAYLIST", { playlistId }, this)
  2045. .then(() => {
  2046. next();
  2047. })
  2048. .catch(err => {
  2049. next(err);
  2050. });
  2051. }
  2052. }
  2053. ],
  2054. async err => {
  2055. if (err) {
  2056. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2057. this.log(
  2058. "ERROR",
  2059. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  2060. `Clearing and refilling station playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2061. );
  2062. return cb({ status: "error", message: err });
  2063. }
  2064. this.log(
  2065. "SUCCESS",
  2066. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  2067. `Successfully cleared and refilled station playlist "${playlistId}" for user "${session.userId}".`
  2068. );
  2069. return cb({
  2070. status: "success",
  2071. message: "Playlist has been successfully cleared and refilled"
  2072. });
  2073. }
  2074. );
  2075. }),
  2076. /**
  2077. * Clears and refills a genre playlist
  2078. *
  2079. * @param {object} session - the session object automatically added by socket.io
  2080. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  2081. * @param {Function} cb - gets called with the result
  2082. */
  2083. clearAndRefillGenrePlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  2084. async.waterfall(
  2085. [
  2086. next => {
  2087. if (!playlistId) next("Please specify a playlist id");
  2088. else {
  2089. PlaylistsModule.runJob("CLEAR_AND_REFILL_GENRE_PLAYLIST", { playlistId }, this)
  2090. .then(() => {
  2091. next();
  2092. })
  2093. .catch(err => {
  2094. next(err);
  2095. });
  2096. }
  2097. }
  2098. ],
  2099. async err => {
  2100. if (err) {
  2101. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2102. this.log(
  2103. "ERROR",
  2104. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2105. `Clearing and refilling genre playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2106. );
  2107. return cb({ status: "error", message: err });
  2108. }
  2109. this.log(
  2110. "SUCCESS",
  2111. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2112. `Successfully cleared and refilled genre playlist "${playlistId}" for user "${session.userId}".`
  2113. );
  2114. return cb({
  2115. status: "success",
  2116. message: "Playlist has been successfully cleared and refilled"
  2117. });
  2118. }
  2119. );
  2120. }),
  2121. /**
  2122. * Clears and refills a artist playlist
  2123. *
  2124. * @param {object} session - the session object automatically added by socket.io
  2125. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  2126. * @param {Function} cb - gets called with the result
  2127. */
  2128. clearAndRefillArtistPlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  2129. async.waterfall(
  2130. [
  2131. next => {
  2132. if (!playlistId) next("Please specify a playlist id");
  2133. else {
  2134. PlaylistsModule.runJob("CLEAR_AND_REFILL_ARTIST_PLAYLIST", { playlistId }, this)
  2135. .then(() => {
  2136. next();
  2137. })
  2138. .catch(err => {
  2139. next(err);
  2140. });
  2141. }
  2142. }
  2143. ],
  2144. async err => {
  2145. if (err) {
  2146. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2147. this.log(
  2148. "ERROR",
  2149. "PLAYLIST_CLEAR_AND_REFILL_ARTIST_PLAYLIST",
  2150. `Clearing and refilling artist playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2151. );
  2152. return cb({ status: "error", message: err });
  2153. }
  2154. this.log(
  2155. "SUCCESS",
  2156. "PLAYLIST_CLEAR_AND_REFILL_ARTIST_PLAYLIST",
  2157. `Successfully cleared and refilled artist playlist "${playlistId}" for user "${session.userId}".`
  2158. );
  2159. return cb({
  2160. status: "success",
  2161. message: "Playlist has been successfully cleared and refilled"
  2162. });
  2163. }
  2164. );
  2165. }),
  2166. /**
  2167. * Clears and refills all station playlists
  2168. *
  2169. * @param {object} session - the session object automatically added by socket.io
  2170. * @param {Function} cb - gets called with the result
  2171. */
  2172. clearAndRefillAllStationPlaylists: isAdminRequired(async function index(session, cb) {
  2173. this.keepLongJob();
  2174. this.publishProgress({
  2175. status: "started",
  2176. title: "Clear and refill all station playlists",
  2177. message: "Clearing and refilling all station playlists.",
  2178. id: this.toString()
  2179. });
  2180. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2181. await CacheModule.runJob(
  2182. "PUB",
  2183. {
  2184. channel: "longJob.added",
  2185. value: { jobId: this.toString(), userId: session.userId }
  2186. },
  2187. this
  2188. );
  2189. async.waterfall(
  2190. [
  2191. next => {
  2192. PlaylistsModule.runJob("GET_ALL_STATION_PLAYLISTS", {}, this)
  2193. .then(response => {
  2194. next(null, response.playlists);
  2195. })
  2196. .catch(err => {
  2197. next(err);
  2198. });
  2199. },
  2200. (playlists, next) => {
  2201. async.eachLimit(
  2202. playlists,
  2203. 1,
  2204. (playlist, next) => {
  2205. this.publishProgress({
  2206. status: "update",
  2207. message: `Clearing and refilling "${playlist._id}"`
  2208. });
  2209. PlaylistsModule.runJob(
  2210. "CLEAR_AND_REFILL_STATION_PLAYLIST",
  2211. { playlistId: playlist._id },
  2212. this
  2213. )
  2214. .then(() => {
  2215. next();
  2216. })
  2217. .catch(err => {
  2218. next(err);
  2219. });
  2220. },
  2221. next
  2222. );
  2223. }
  2224. ],
  2225. async err => {
  2226. if (err) {
  2227. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2228. this.log(
  2229. "ERROR",
  2230. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2231. `Clearing and refilling all station playlists failed for user "${session.userId}". "${err}"`
  2232. );
  2233. this.publishProgress({
  2234. status: "error",
  2235. message: err
  2236. });
  2237. return cb({ status: "error", message: err });
  2238. }
  2239. this.log(
  2240. "SUCCESS",
  2241. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2242. `Successfully cleared and refilled all station playlists for user "${session.userId}".`
  2243. );
  2244. this.publishProgress({
  2245. status: "success",
  2246. message: "Playlists have been successfully cleared and refilled."
  2247. });
  2248. return cb({
  2249. status: "success",
  2250. message: "Playlists have been successfully cleared and refilled"
  2251. });
  2252. }
  2253. );
  2254. }),
  2255. /**
  2256. * Clears and refills all genre playlists
  2257. *
  2258. * @param {object} session - the session object automatically added by socket.io
  2259. * @param {Function} cb - gets called with the result
  2260. */
  2261. clearAndRefillAllGenrePlaylists: isAdminRequired(async function index(session, cb) {
  2262. this.keepLongJob();
  2263. this.publishProgress({
  2264. status: "started",
  2265. title: "Clear and refill all genre playlists",
  2266. message: "Clearing and refilling all genre playlists.",
  2267. id: this.toString()
  2268. });
  2269. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2270. await CacheModule.runJob(
  2271. "PUB",
  2272. {
  2273. channel: "longJob.added",
  2274. value: { jobId: this.toString(), userId: session.userId }
  2275. },
  2276. this
  2277. );
  2278. async.waterfall(
  2279. [
  2280. next => {
  2281. PlaylistsModule.runJob("GET_ALL_GENRE_PLAYLISTS", {}, this)
  2282. .then(response => {
  2283. next(null, response.playlists);
  2284. })
  2285. .catch(err => {
  2286. next(err);
  2287. });
  2288. },
  2289. (playlists, next) => {
  2290. async.eachLimit(
  2291. playlists,
  2292. 1,
  2293. (playlist, next) => {
  2294. this.publishProgress({
  2295. status: "update",
  2296. message: `Clearing and refilling "${playlist._id}"`
  2297. });
  2298. PlaylistsModule.runJob(
  2299. "CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2300. { playlistId: playlist._id },
  2301. this
  2302. )
  2303. .then(() => {
  2304. next();
  2305. })
  2306. .catch(err => {
  2307. next(err);
  2308. });
  2309. },
  2310. next
  2311. );
  2312. }
  2313. ],
  2314. async err => {
  2315. if (err) {
  2316. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2317. this.log(
  2318. "ERROR",
  2319. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2320. `Clearing and refilling all genre playlists failed for user "${session.userId}". "${err}"`
  2321. );
  2322. this.publishProgress({
  2323. status: "error",
  2324. message: err
  2325. });
  2326. return cb({ status: "error", message: err });
  2327. }
  2328. this.log(
  2329. "SUCCESS",
  2330. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2331. `Successfully cleared and refilled all genre playlists for user "${session.userId}".`
  2332. );
  2333. this.publishProgress({
  2334. status: "success",
  2335. message: "Playlists have been successfully cleared and refilled."
  2336. });
  2337. return cb({
  2338. status: "success",
  2339. message: "Playlists have been successfully cleared and refilled"
  2340. });
  2341. }
  2342. );
  2343. }),
  2344. /**
  2345. * Clears and refills all artist playlists
  2346. *
  2347. * @param {object} session - the session object automatically added by socket.io
  2348. * @param {Function} cb - gets called with the result
  2349. */
  2350. clearAndRefillAllArtistPlaylists: isAdminRequired(async function index(session, cb) {
  2351. this.keepLongJob();
  2352. this.publishProgress({
  2353. status: "started",
  2354. title: "Clear and refill all artist playlists",
  2355. message: "Clearing and refilling all artist playlists.",
  2356. id: this.toString()
  2357. });
  2358. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2359. await CacheModule.runJob(
  2360. "PUB",
  2361. {
  2362. channel: "longJob.added",
  2363. value: { jobId: this.toString(), userId: session.userId }
  2364. },
  2365. this
  2366. );
  2367. async.waterfall(
  2368. [
  2369. next => {
  2370. PlaylistsModule.runJob("GET_ALL_ARTIST_PLAYLISTS", {}, this)
  2371. .then(response => {
  2372. next(null, response.playlists);
  2373. })
  2374. .catch(err => {
  2375. next(err);
  2376. });
  2377. },
  2378. (playlists, next) => {
  2379. async.eachLimit(
  2380. playlists,
  2381. 1,
  2382. (playlist, next) => {
  2383. this.publishProgress({
  2384. status: "update",
  2385. message: `Clearing and refilling "${playlist._id}"`
  2386. });
  2387. PlaylistsModule.runJob(
  2388. "CLEAR_AND_REFILL_ARTIST_PLAYLIST",
  2389. { playlistId: playlist._id },
  2390. this
  2391. )
  2392. .then(() => {
  2393. next();
  2394. })
  2395. .catch(err => {
  2396. next(err);
  2397. });
  2398. },
  2399. next
  2400. );
  2401. }
  2402. // next => {
  2403. // // PlaylistsModule.runJob("CREATE_MISSING_ARTIST_PLAYLISTS", {}, null)
  2404. // // .then()
  2405. // // .catch()
  2406. // // .finally(() => {
  2407. // // SongsModule.runJob("GET_ALL_ARTISTS", {}, null)
  2408. // // .then(response => {
  2409. // // const { artists } = response;
  2410. // // artists.forEach(artist => {
  2411. // // PlaylistsModule.runJob("AUTOFILL_ARTIST_PLAYLIST", { artist }, null).then().catch();
  2412. // // });
  2413. // // })
  2414. // // .catch();
  2415. // // });
  2416. // PlaylistsModule.runJob("GET_MISSING_ARTIST_PLAYLISTS", {}, this).then(response => {
  2417. // console.log(response);
  2418. // });
  2419. // }
  2420. ],
  2421. async err => {
  2422. if (err) {
  2423. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2424. this.log(
  2425. "ERROR",
  2426. "PLAYLIST_CLEAR_AND_REFILL_ALL_ARTIST_PLAYLISTS",
  2427. `Clearing and refilling all artist playlists failed for user "${session.userId}". "${err}"`
  2428. );
  2429. this.publishProgress({
  2430. status: "error",
  2431. message: err
  2432. });
  2433. return cb({ status: "error", message: err });
  2434. }
  2435. this.log(
  2436. "SUCCESS",
  2437. "PLAYLIST_CLEAR_AND_REFILL_ALL_ARTIST_PLAYLISTS",
  2438. `Successfully cleared and refilled all artist playlists for user "${session.userId}".`
  2439. );
  2440. this.publishProgress({
  2441. status: "success",
  2442. message: "Playlists have been successfully cleared and refilled."
  2443. });
  2444. return cb({
  2445. status: "success",
  2446. message: "Playlists have been successfully cleared and refilled"
  2447. });
  2448. }
  2449. );
  2450. }),
  2451. /**
  2452. * Create missing genre playlists
  2453. *
  2454. * @param {object} session - the session object automatically added by socket.io
  2455. * @param {Function} cb - gets called with the result
  2456. */
  2457. createMissingGenrePlaylists: isAdminRequired(async function index(session, cb) {
  2458. this.keepLongJob();
  2459. this.publishProgress({
  2460. status: "started",
  2461. title: "Create missing genre playlists",
  2462. message: "Creating missing genre playlists.",
  2463. id: this.toString()
  2464. });
  2465. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2466. await CacheModule.runJob(
  2467. "PUB",
  2468. {
  2469. channel: "longJob.added",
  2470. value: { jobId: this.toString(), userId: session.userId }
  2471. },
  2472. this
  2473. );
  2474. async.waterfall(
  2475. [
  2476. next => {
  2477. PlaylistsModule.runJob("CREATE_MISSING_GENRE_PLAYLISTS", this)
  2478. .then(() => {
  2479. next();
  2480. })
  2481. .catch(err => {
  2482. next(err);
  2483. });
  2484. }
  2485. ],
  2486. async err => {
  2487. if (err) {
  2488. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2489. this.log(
  2490. "ERROR",
  2491. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2492. `Creating missing genre playlists failed for user "${session.userId}". "${err}"`
  2493. );
  2494. this.publishProgress({
  2495. status: "error",
  2496. message: err
  2497. });
  2498. return cb({ status: "error", message: err });
  2499. }
  2500. this.log(
  2501. "SUCCESS",
  2502. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2503. `Successfully created missing genre playlists for user "${session.userId}".`
  2504. );
  2505. this.publishProgress({
  2506. status: "success",
  2507. message: "Missing genre playlists have been successfully created."
  2508. });
  2509. return cb({
  2510. status: "success",
  2511. message: "Missing genre playlists have been successfully created"
  2512. });
  2513. }
  2514. );
  2515. }),
  2516. /**
  2517. * Create missing artist playlists
  2518. *
  2519. * @param {object} session - the session object automatically added by socket.io
  2520. * @param {Function} cb - gets called with the result
  2521. */
  2522. createMissingArtistPlaylists: isAdminRequired(async function index(session, cb) {
  2523. this.keepLongJob();
  2524. this.publishProgress({
  2525. status: "started",
  2526. title: "Create missing artist playlists",
  2527. message: "Creating missing artist playlists.",
  2528. id: this.toString()
  2529. });
  2530. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2531. await CacheModule.runJob(
  2532. "PUB",
  2533. {
  2534. channel: "longJob.added",
  2535. value: { jobId: this.toString(), userId: session.userId }
  2536. },
  2537. this
  2538. );
  2539. async.waterfall(
  2540. [
  2541. next => {
  2542. PlaylistsModule.runJob("CREATE_MISSING_ARTIST_PLAYLISTS", this)
  2543. .then(() => {
  2544. next();
  2545. })
  2546. .catch(err => {
  2547. next(err);
  2548. });
  2549. }
  2550. ],
  2551. async err => {
  2552. if (err) {
  2553. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2554. this.log(
  2555. "ERROR",
  2556. "PLAYLIST_CREATE_MISSING_ARTIST_PLAYLISTS",
  2557. `Creating missing artist playlists failed for user "${session.userId}". "${err}"`
  2558. );
  2559. this.publishProgress({
  2560. status: "error",
  2561. message: err
  2562. });
  2563. return cb({ status: "error", message: err });
  2564. }
  2565. this.log(
  2566. "SUCCESS",
  2567. "PLAYLIST_CREATE_MISSING_ARTIST_PLAYLISTS",
  2568. `Successfully created missing artist playlists for user "${session.userId}".`
  2569. );
  2570. this.publishProgress({
  2571. status: "success",
  2572. message: "Missing artist playlists have been successfully created."
  2573. });
  2574. return cb({
  2575. status: "success",
  2576. message: "Missing artist playlists have been successfully created"
  2577. });
  2578. }
  2579. );
  2580. })
  2581. };