playlists.js 71 KB

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