playlists.js 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667
  1. import async from "async";
  2. import config from "config";
  3. import { isAdminRequired, isLoginRequired } from "./hooks";
  4. import moduleManager from "../../index";
  5. const DBModule = moduleManager.modules.db;
  6. const UtilsModule = moduleManager.modules.utils;
  7. const WSModule = moduleManager.modules.ws;
  8. const SongsModule = moduleManager.modules.songs;
  9. const StationsModule = moduleManager.modules.stations;
  10. const CacheModule = moduleManager.modules.cache;
  11. const PlaylistsModule = moduleManager.modules.playlists;
  12. const YouTubeModule = moduleManager.modules.youtube;
  13. const ActivitiesModule = moduleManager.modules.activities;
  14. CacheModule.runJob("SUB", {
  15. channel: "playlist.create",
  16. cb: playlist => {
  17. WSModule.runJob("SOCKETS_FROM_USER", { userId: playlist.createdBy }, this).then(sockets =>
  18. sockets.forEach(socket => socket.dispatch("event:playlist.created", { data: { playlist } }))
  19. );
  20. if (playlist.privacy === "public")
  21. WSModule.runJob("EMIT_TO_ROOM", {
  22. room: `profile.${playlist.createdBy}.playlists`,
  23. args: ["event:playlist.created", { data: { playlist } }]
  24. });
  25. WSModule.runJob("EMIT_TO_ROOM", {
  26. room: "admin.playlists",
  27. args: ["event:admin.playlist.created", { data: { playlist } }]
  28. });
  29. }
  30. });
  31. CacheModule.runJob("SUB", {
  32. channel: "playlist.delete",
  33. cb: res => {
  34. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(sockets => {
  35. sockets.forEach(socket => {
  36. socket.dispatch("event:playlist.deleted", { data: { playlistId: res.playlistId } });
  37. });
  38. });
  39. WSModule.runJob("EMIT_TO_ROOM", {
  40. room: `profile.${res.userId}.playlists`,
  41. args: ["event:playlist.deleted", { data: { playlistId: res.playlistId } }]
  42. });
  43. WSModule.runJob("EMIT_TO_ROOM", {
  44. room: "admin.playlists",
  45. args: ["event:admin.playlist.deleted", { data: { playlistId: res.playlistId } }]
  46. });
  47. }
  48. });
  49. CacheModule.runJob("SUB", {
  50. channel: "playlist.repositionSong",
  51. cb: res => {
  52. const { userId, playlistId, song } = res;
  53. WSModule.runJob("SOCKETS_FROM_USER", { userId }, this).then(sockets =>
  54. sockets.forEach(socket =>
  55. socket.dispatch("event:playlist.song.repositioned", {
  56. data: { playlistId, song }
  57. })
  58. )
  59. );
  60. }
  61. });
  62. CacheModule.runJob("SUB", {
  63. channel: "playlist.addSong",
  64. cb: res => {
  65. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(sockets => {
  66. sockets.forEach(socket => {
  67. socket.dispatch("event:playlist.song.added", {
  68. data: {
  69. playlistId: res.playlistId,
  70. song: res.song
  71. }
  72. });
  73. });
  74. });
  75. if (res.privacy === "public")
  76. WSModule.runJob("EMIT_TO_ROOM", {
  77. room: `profile.${res.userId}.playlists`,
  78. args: [
  79. "event:playlist.song.added",
  80. {
  81. data: {
  82. playlistId: res.playlistId,
  83. song: res.song
  84. }
  85. }
  86. ]
  87. });
  88. WSModule.runJob("EMIT_TO_ROOM", {
  89. room: "admin.playlists",
  90. args: ["event:admin.playlist.song.added", { data: { playlistId: res.playlistId, song: res.song } }]
  91. });
  92. }
  93. });
  94. CacheModule.runJob("SUB", {
  95. channel: "playlist.removeSong",
  96. cb: res => {
  97. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(sockets => {
  98. sockets.forEach(socket => {
  99. socket.dispatch("event:playlist.song.removed", {
  100. data: {
  101. playlistId: res.playlistId,
  102. youtubeId: res.youtubeId
  103. }
  104. });
  105. });
  106. });
  107. if (res.privacy === "public")
  108. WSModule.runJob("EMIT_TO_ROOM", {
  109. room: `profile.${res.userId}.playlists`,
  110. args: [
  111. "event:playlist.song.removed",
  112. {
  113. data: {
  114. playlistId: res.playlistId,
  115. youtubeId: res.youtubeId
  116. }
  117. }
  118. ]
  119. });
  120. WSModule.runJob("EMIT_TO_ROOM", {
  121. room: "admin.playlists",
  122. args: [
  123. "event:admin.playlist.song.removed",
  124. { data: { playlistId: res.playlistId, youtubeId: res.youtubeId } }
  125. ]
  126. });
  127. }
  128. });
  129. CacheModule.runJob("SUB", {
  130. channel: "playlist.updateDisplayName",
  131. cb: res => {
  132. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(sockets => {
  133. sockets.forEach(socket => {
  134. socket.dispatch("event:playlist.displayName.updated", {
  135. data: {
  136. playlistId: res.playlistId,
  137. displayName: res.displayName
  138. }
  139. });
  140. });
  141. });
  142. if (res.privacy === "public")
  143. WSModule.runJob("EMIT_TO_ROOM", {
  144. room: `profile.${res.userId}.playlists`,
  145. args: [
  146. "event:playlist.displayName.updated",
  147. {
  148. data: {
  149. playlistId: res.playlistId,
  150. displayName: res.displayName
  151. }
  152. }
  153. ]
  154. });
  155. WSModule.runJob("EMIT_TO_ROOM", {
  156. room: "admin.playlists",
  157. args: [
  158. "event:admin.playlist.displayName.updated",
  159. { data: { playlistId: res.playlistId, displayName: res.displayName } }
  160. ]
  161. });
  162. }
  163. });
  164. CacheModule.runJob("SUB", {
  165. channel: "playlist.updatePrivacy",
  166. cb: res => {
  167. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(sockets => {
  168. sockets.forEach(socket => {
  169. socket.dispatch("event:playlist.privacy.updated", {
  170. data: {
  171. playlist: res.playlist
  172. }
  173. });
  174. });
  175. });
  176. WSModule.runJob("EMIT_TO_ROOM", {
  177. room: "admin.playlists",
  178. args: [
  179. "event:admin.playlist.privacy.updated",
  180. { data: { playlistId: res.playlist._id, privacy: res.playlist.privacy } }
  181. ]
  182. });
  183. if (res.playlist.privacy === "public")
  184. return WSModule.runJob("EMIT_TO_ROOM", {
  185. room: `profile.${res.userId}.playlists`,
  186. args: [
  187. "event:playlist.created",
  188. {
  189. data: {
  190. playlist: res.playlist
  191. }
  192. }
  193. ]
  194. });
  195. return WSModule.runJob("EMIT_TO_ROOM", {
  196. room: `profile.${res.userId}.playlists`,
  197. args: [
  198. "event:playlist.deleted",
  199. {
  200. data: {
  201. playlistId: res.playlist._id
  202. }
  203. }
  204. ]
  205. });
  206. }
  207. });
  208. CacheModule.runJob("SUB", {
  209. channel: "playlist.updated",
  210. cb: async data => {
  211. const playlistModel = await DBModule.runJob("GET_MODEL", {
  212. modelName: "playlist"
  213. });
  214. playlistModel.findOne(
  215. { _id: data.playlistId },
  216. ["_id", "displayName", "type", "privacy", "songs", "createdBy", "createdAt", "createdFor"],
  217. (err, playlist) => {
  218. const newPlaylist = {
  219. ...playlist._doc,
  220. songsCount: playlist.songs.length,
  221. songsLength: playlist.songs.reduce(
  222. (previous, current) => ({
  223. duration: previous.duration + current.duration
  224. }),
  225. { duration: 0 }
  226. ).duration
  227. };
  228. delete newPlaylist.songs;
  229. WSModule.runJob("EMIT_TO_ROOMS", {
  230. rooms: ["admin.playlists"],
  231. args: ["event:admin.playlist.updated", { data: { playlist: newPlaylist } }]
  232. });
  233. }
  234. );
  235. }
  236. });
  237. export default {
  238. /**
  239. * Gets playlists, used in the admin playlists page by the AdvancedTable component
  240. *
  241. * @param {object} session - the session object automatically added by the websocket
  242. * @param page - the page
  243. * @param pageSize - the size per page
  244. * @param properties - the properties to return for each playlist
  245. * @param sort - the sort object
  246. * @param queries - the queries array
  247. * @param operator - the operator for queries
  248. * @param cb
  249. */
  250. getData: isAdminRequired(async function getSet(session, page, pageSize, properties, sort, queries, operator, cb) {
  251. async.waterfall(
  252. [
  253. next => {
  254. DBModule.runJob(
  255. "GET_DATA",
  256. {
  257. page,
  258. pageSize,
  259. properties,
  260. sort,
  261. queries,
  262. operator,
  263. modelName: "playlist",
  264. blacklistedProperties: [],
  265. specialProperties: {
  266. totalLength: [
  267. {
  268. $addFields: {
  269. totalLength: { $sum: "$songs.duration" }
  270. }
  271. }
  272. ],
  273. songsCount: [
  274. {
  275. $addFields: {
  276. songsCount: { $size: "$songs" }
  277. }
  278. }
  279. ],
  280. createdBy: [
  281. {
  282. $addFields: {
  283. createdByOID: {
  284. $convert: {
  285. input: "$createdBy",
  286. to: "objectId",
  287. onError: "unknown",
  288. onNull: "unknown"
  289. }
  290. }
  291. }
  292. },
  293. {
  294. $lookup: {
  295. from: "users",
  296. localField: "createdByOID",
  297. foreignField: "_id",
  298. as: "createdByUser"
  299. }
  300. },
  301. {
  302. $unwind: {
  303. path: "$createdByUser",
  304. preserveNullAndEmptyArrays: true
  305. }
  306. },
  307. {
  308. $addFields: {
  309. createdByUsername: {
  310. $cond: [
  311. { $eq: ["$createdBy", "Musare"] },
  312. "Musare",
  313. { $ifNull: ["$createdByUser.username", "unknown"] }
  314. ]
  315. }
  316. }
  317. },
  318. {
  319. $project: {
  320. createdByOID: 0,
  321. createdByUser: 0
  322. }
  323. }
  324. ]
  325. },
  326. specialQueries: {
  327. createdBy: newQuery => ({ $or: [newQuery, { createdByUsername: newQuery.createdBy }] })
  328. }
  329. },
  330. this
  331. )
  332. .then(response => {
  333. next(null, response);
  334. })
  335. .catch(err => {
  336. next(err);
  337. });
  338. }
  339. ],
  340. async (err, response) => {
  341. if (err) {
  342. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  343. this.log("ERROR", "PLAYLISTS_GET_DATA", `Failed to get data from playlists. "${err}"`);
  344. return cb({ status: "error", message: err });
  345. }
  346. this.log("SUCCESS", "PLAYLISTS_GET_DATA", `Got data from playlists successfully.`);
  347. return cb({ status: "success", message: "Successfully got data from playlists.", data: response });
  348. }
  349. );
  350. }),
  351. /**
  352. * Searches through all playlists that can be included in a community station
  353. *
  354. * @param {object} session - the session object automatically added by the websocket
  355. * @param {string} query - the query
  356. * @param {string} query - the page
  357. * @param {Function} cb - gets called with the result
  358. */
  359. searchCommunity: isLoginRequired(async function searchCommunity(session, query, page, cb) {
  360. async.waterfall(
  361. [
  362. next => {
  363. if ((!query && query !== "") || typeof query !== "string") next("Invalid query.");
  364. else next();
  365. },
  366. next => {
  367. PlaylistsModule.runJob("SEARCH", {
  368. query,
  369. includeUser: true,
  370. includeGenre: true,
  371. includeArtist: 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. async.each(
  1018. playlist.songs,
  1019. (song, nextSong) => {
  1020. if (song.youtubeId === youtubeId) return next("That song is already in the playlist");
  1021. return nextSong();
  1022. },
  1023. err => next(err, playlist)
  1024. );
  1025. },
  1026. (playlist, next) => {
  1027. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1028. const oppositeType = playlist.type === "user-liked" ? "user-disliked" : "user-liked";
  1029. const oppositePlaylistName = oppositeType === "user-liked" ? "Liked Songs" : "Disliked Songs";
  1030. playlistModel.count(
  1031. { type: oppositeType, createdBy: session.userId, "songs.youtubeId": youtubeId },
  1032. (err, results) => {
  1033. if (err) next(err);
  1034. else if (results > 0)
  1035. next(
  1036. `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.`
  1037. );
  1038. else next();
  1039. }
  1040. );
  1041. } else next();
  1042. },
  1043. next => {
  1044. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1045. .then(UserModel => {
  1046. UserModel.findOne(
  1047. { _id: session.userId },
  1048. { "preferences.anonymousSongRequests": 1 },
  1049. next
  1050. );
  1051. })
  1052. .catch(next);
  1053. },
  1054. (user, next) => {
  1055. SongsModule.runJob(
  1056. "ENSURE_SONG_EXISTS_BY_YOUTUBE_ID",
  1057. {
  1058. youtubeId,
  1059. userId: user.preferences.anonymousSongRequests ? null : session.userId,
  1060. automaticallyRequested: true
  1061. },
  1062. this
  1063. )
  1064. .then(response => {
  1065. const { song } = response;
  1066. const { _id, title, artists, thumbnail, duration, status } = song;
  1067. next(null, {
  1068. _id,
  1069. youtubeId,
  1070. title,
  1071. artists,
  1072. thumbnail,
  1073. duration,
  1074. status
  1075. });
  1076. })
  1077. .catch(next);
  1078. },
  1079. (newSong, next) => {
  1080. playlistModel.updateOne(
  1081. { _id: playlistId },
  1082. { $push: { songs: newSong } },
  1083. { runValidators: true },
  1084. err => {
  1085. if (err) return next(err);
  1086. return PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1087. .then(playlist => next(null, playlist, newSong))
  1088. .catch(next);
  1089. }
  1090. );
  1091. },
  1092. (playlist, newSong, next) => {
  1093. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1094. SongsModule.runJob("RECALCULATE_SONG_RATINGS", {
  1095. songId: newSong._id,
  1096. youtubeId: newSong.youtubeId
  1097. })
  1098. .then(ratings => next(null, playlist, newSong, ratings))
  1099. .catch(next);
  1100. } else {
  1101. next(null, playlist, newSong, null);
  1102. }
  1103. }
  1104. ],
  1105. async (err, playlist, newSong, ratings) => {
  1106. if (err) {
  1107. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1108. this.log(
  1109. "ERROR",
  1110. "PLAYLIST_ADD_SONG",
  1111. `Adding song "${youtubeId}" to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1112. );
  1113. return cb({ status: "error", message: err });
  1114. }
  1115. this.log(
  1116. "SUCCESS",
  1117. "PLAYLIST_ADD_SONG",
  1118. `Successfully added song "${youtubeId}" to private playlist "${playlistId}" for user "${session.userId}".`
  1119. );
  1120. if (!isSet && playlist.type === "user" && playlist.privacy === "public") {
  1121. const songName = newSong.artists
  1122. ? `${newSong.title} by ${newSong.artists.join(", ")}`
  1123. : newSong.title;
  1124. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1125. userId: session.userId,
  1126. type: "playlist__add_song",
  1127. payload: {
  1128. message: `Added <youtubeId>${songName}</youtubeId> to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1129. thumbnail: newSong.thumbnail,
  1130. playlistId,
  1131. youtubeId
  1132. }
  1133. });
  1134. }
  1135. StationsModule.runJob("GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST", { playlistId })
  1136. .then(response => {
  1137. response.stationIds.forEach(stationId => {
  1138. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1139. });
  1140. })
  1141. .catch();
  1142. CacheModule.runJob("PUB", {
  1143. channel: "playlist.addSong",
  1144. value: {
  1145. playlistId: playlist._id,
  1146. song: newSong,
  1147. userId: session.userId,
  1148. privacy: playlist.privacy
  1149. }
  1150. });
  1151. CacheModule.runJob("PUB", {
  1152. channel: "playlist.updated",
  1153. value: { playlistId }
  1154. });
  1155. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1156. const { _id, youtubeId, title, artists, thumbnail } = newSong;
  1157. const { likes, dislikes } = ratings;
  1158. SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1159. if (playlist.type === "user-liked") {
  1160. CacheModule.runJob("PUB", {
  1161. channel: "song.like",
  1162. value: JSON.stringify({
  1163. youtubeId,
  1164. userId: session.userId,
  1165. likes,
  1166. dislikes
  1167. })
  1168. });
  1169. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1170. userId: session.userId,
  1171. type: "song__like",
  1172. payload: {
  1173. message: `Liked song <youtubeId>${title} by ${artists.join(", ")}</youtubeId>`,
  1174. youtubeId,
  1175. thumbnail
  1176. }
  1177. });
  1178. } else {
  1179. CacheModule.runJob("PUB", {
  1180. channel: "song.dislike",
  1181. value: JSON.stringify({
  1182. youtubeId,
  1183. userId: session.userId,
  1184. likes,
  1185. dislikes
  1186. })
  1187. });
  1188. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1189. userId: session.userId,
  1190. type: "song__dislike",
  1191. payload: {
  1192. message: `Disliked song <youtubeId>${title} by ${artists.join(", ")}</youtubeId>`,
  1193. youtubeId,
  1194. thumbnail
  1195. }
  1196. });
  1197. }
  1198. }
  1199. return cb({
  1200. status: "success",
  1201. message: "Song has been successfully added to the playlist",
  1202. data: { songs: playlist.songs }
  1203. });
  1204. }
  1205. );
  1206. }),
  1207. /**
  1208. * Adds a set of songs to a private playlist
  1209. *
  1210. * @param {object} session - the session object automatically added by the websocket
  1211. * @param {string} url - the url of the the YouTube playlist
  1212. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  1213. * @param {boolean} musicOnly - whether to only add music to the playlist
  1214. * @param {Function} cb - gets called with the result
  1215. */
  1216. addSetToPlaylist: isLoginRequired(function addSetToPlaylist(session, url, playlistId, musicOnly, cb) {
  1217. let videosInPlaylistTotal = 0;
  1218. let songsInPlaylistTotal = 0;
  1219. let addSongsStats = null;
  1220. const addedSongs = [];
  1221. async.waterfall(
  1222. [
  1223. next => {
  1224. YouTubeModule.runJob("GET_PLAYLIST", { url, musicOnly }, this)
  1225. .then(res => {
  1226. if (res.filteredSongs) {
  1227. videosInPlaylistTotal = res.songs.length;
  1228. songsInPlaylistTotal = res.filteredSongs.length;
  1229. } else {
  1230. songsInPlaylistTotal = videosInPlaylistTotal = res.songs.length;
  1231. }
  1232. next(null, res.songs);
  1233. })
  1234. .catch(err => {
  1235. next(err);
  1236. });
  1237. },
  1238. (youtubeIds, next) => {
  1239. let successful = 0;
  1240. let failed = 0;
  1241. let alreadyInPlaylist = 0;
  1242. let alreadyInLikedPlaylist = 0;
  1243. let alreadyInDislikedPlaylist = 0;
  1244. if (youtubeIds.length === 0) next();
  1245. async.eachLimit(
  1246. youtubeIds,
  1247. 1,
  1248. (youtubeId, next) => {
  1249. WSModule.runJob(
  1250. "RUN_ACTION2",
  1251. {
  1252. session,
  1253. namespace: "playlists",
  1254. action: "addSongToPlaylist",
  1255. args: [true, youtubeId, playlistId]
  1256. },
  1257. this
  1258. )
  1259. .then(res => {
  1260. if (res.status === "success") {
  1261. successful += 1;
  1262. addedSongs.push(youtubeId);
  1263. } else failed += 1;
  1264. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  1265. else if (
  1266. res.message ===
  1267. "That song is already in your Liked Songs playlist. " +
  1268. "A song cannot be in both the Liked Songs playlist" +
  1269. " and the Disliked Songs playlist at the same time."
  1270. )
  1271. alreadyInLikedPlaylist += 1;
  1272. else if (
  1273. res.message ===
  1274. "That song is already in your Disliked Songs playlist. " +
  1275. "A song cannot be in both the Liked Songs playlist " +
  1276. "and the Disliked Songs playlist at the same time."
  1277. )
  1278. alreadyInDislikedPlaylist += 1;
  1279. })
  1280. .catch(() => {
  1281. failed += 1;
  1282. })
  1283. .finally(() => next());
  1284. },
  1285. () => {
  1286. addSongsStats = {
  1287. successful,
  1288. failed,
  1289. alreadyInPlaylist,
  1290. alreadyInLikedPlaylist,
  1291. alreadyInDislikedPlaylist
  1292. };
  1293. next(null);
  1294. }
  1295. );
  1296. },
  1297. next => {
  1298. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1299. .then(playlist => next(null, playlist))
  1300. .catch(next);
  1301. },
  1302. (playlist, next) => {
  1303. if (!playlist || playlist.createdBy !== session.userId) {
  1304. return DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1305. userModel.findOne({ _id: session.userId }, (err, user) => {
  1306. if (user && user.role === "admin") return next(null, playlist);
  1307. return next("Something went wrong when trying to get the playlist");
  1308. });
  1309. });
  1310. }
  1311. return next(null, playlist);
  1312. }
  1313. ],
  1314. async (err, playlist) => {
  1315. if (err) {
  1316. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1317. this.log(
  1318. "ERROR",
  1319. "PLAYLIST_IMPORT",
  1320. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1321. );
  1322. return cb({ status: "error", message: err });
  1323. }
  1324. if (playlist.privacy === "public")
  1325. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1326. userId: session.userId,
  1327. type: "playlist__import_playlist",
  1328. payload: {
  1329. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1330. playlistId
  1331. }
  1332. });
  1333. this.log(
  1334. "SUCCESS",
  1335. "PLAYLIST_IMPORT",
  1336. `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}.`
  1337. );
  1338. return cb({
  1339. status: "success",
  1340. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  1341. data: {
  1342. songs: playlist.songs,
  1343. stats: {
  1344. videosInPlaylistTotal,
  1345. songsInPlaylistTotal,
  1346. alreadyInLikedPlaylist: addSongsStats.alreadyInLikedPlaylist,
  1347. alreadyInDislikedPlaylist: addSongsStats.alreadyInDislikedPlaylist
  1348. }
  1349. }
  1350. });
  1351. }
  1352. );
  1353. }),
  1354. /**
  1355. * Removes a song from a private playlist
  1356. *
  1357. * @param {object} session - the session object automatically added by the websocket
  1358. * @param {string} youtubeId - the youtube id of the song we are removing from the private playlist
  1359. * @param {string} playlistId - the id of the playlist we are removing the song from
  1360. * @param {Function} cb - gets called with the result
  1361. */
  1362. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(session, youtubeId, playlistId, cb) {
  1363. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1364. async.waterfall(
  1365. [
  1366. next => {
  1367. if (!youtubeId || typeof youtubeId !== "string") return next("Invalid song id.");
  1368. if (!playlistId || typeof youtubeId !== "string") return next("Invalid playlist id.");
  1369. return next();
  1370. },
  1371. next => {
  1372. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1373. .then(playlist => {
  1374. if (!playlist || playlist.createdBy !== session.userId) {
  1375. return DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1376. userModel.findOne({ _id: session.userId }, (err, user) => {
  1377. if (user && user.role === "admin") return next();
  1378. return next("Something went wrong when trying to get the playlist");
  1379. });
  1380. });
  1381. }
  1382. return next();
  1383. })
  1384. .catch(next);
  1385. },
  1386. // remove song from playlist
  1387. next => playlistModel.updateOne({ _id: playlistId }, { $pull: { songs: { youtubeId } } }, next),
  1388. // update cache representation of the playlist
  1389. (res, next) => {
  1390. if (res.modifiedCount === 1)
  1391. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1392. .then(playlist => next(null, playlist))
  1393. .catch(next);
  1394. else next("Song wasn't in playlist.");
  1395. },
  1396. (playlist, next) => {
  1397. StationsModule.runJob("GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST", { playlistId })
  1398. .then(response => {
  1399. response.stationIds.forEach(stationId => {
  1400. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1401. });
  1402. })
  1403. .catch();
  1404. SongsModule.runJob("GET_SONG_FROM_YOUTUBE_ID", { youtubeId }, this)
  1405. .then(res =>
  1406. next(null, playlist, {
  1407. _id: res.song._id,
  1408. title: res.song.title,
  1409. thumbnail: res.song.thumbnail,
  1410. artists: res.song.artists,
  1411. youtubeId: res.song.youtubeId
  1412. })
  1413. )
  1414. .catch(() => {
  1415. YouTubeModule.runJob("GET_SONG", { youtubeId }, this)
  1416. .then(response => next(null, playlist, response.song))
  1417. .catch(next);
  1418. });
  1419. },
  1420. (playlist, newSong, next) => {
  1421. if (playlist.type === "user-liked" || playlist.type === "user-disliked") {
  1422. SongsModule.runJob("RECALCULATE_SONG_RATINGS", {
  1423. songId: newSong._id,
  1424. youtubeId: newSong.youtubeId
  1425. })
  1426. .then(ratings => next(null, playlist, newSong, ratings))
  1427. .catch(next);
  1428. } else {
  1429. next(null, playlist, newSong, null);
  1430. }
  1431. },
  1432. (playlist, newSong, ratings, next) => {
  1433. const { _id, title, artists, thumbnail } = newSong;
  1434. const songName = artists ? `${title} by ${artists.join(", ")}` : title;
  1435. if (playlist.type === "user" && playlist.privacy === "public") {
  1436. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1437. userId: session.userId,
  1438. type: "playlist__remove_song",
  1439. payload: {
  1440. message: `Removed <youtubeId>${songName}</youtubeId> from playlist <playlistId>${playlist.displayName}</playlistId>`,
  1441. thumbnail,
  1442. playlistId,
  1443. youtubeId: newSong.youtubeId
  1444. }
  1445. });
  1446. }
  1447. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1448. const { likes, dislikes } = ratings;
  1449. SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1450. if (playlist.type === "user-liked") {
  1451. CacheModule.runJob("PUB", {
  1452. channel: "song.unlike",
  1453. value: JSON.stringify({
  1454. youtubeId: newSong.youtubeId,
  1455. userId: session.userId,
  1456. likes,
  1457. dislikes
  1458. })
  1459. });
  1460. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1461. userId: session.userId,
  1462. type: "song__unlike",
  1463. payload: {
  1464. message: `Removed <youtubeId>${title} by ${artists.join(
  1465. ", "
  1466. )}</youtubeId> from your Liked Songs`,
  1467. youtubeId: newSong.youtubeId,
  1468. thumbnail
  1469. }
  1470. });
  1471. } else {
  1472. CacheModule.runJob("PUB", {
  1473. channel: "song.undislike",
  1474. value: JSON.stringify({
  1475. youtubeId: newSong.youtubeId,
  1476. userId: session.userId,
  1477. likes,
  1478. dislikes
  1479. })
  1480. });
  1481. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1482. userId: session.userId,
  1483. type: "song__undislike",
  1484. payload: {
  1485. message: `Removed <youtubeId>${title} by ${artists.join(
  1486. ", "
  1487. )}</youtubeId> from your Disliked Songs`,
  1488. youtubeId: newSong.youtubeId,
  1489. thumbnail
  1490. }
  1491. });
  1492. }
  1493. }
  1494. return next(null, playlist);
  1495. }
  1496. ],
  1497. async (err, playlist) => {
  1498. if (err) {
  1499. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1500. this.log(
  1501. "ERROR",
  1502. "PLAYLIST_REMOVE_SONG",
  1503. `Removing song "${youtubeId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1504. );
  1505. return cb({ status: "error", message: err });
  1506. }
  1507. this.log(
  1508. "SUCCESS",
  1509. "PLAYLIST_REMOVE_SONG",
  1510. `Successfully removed song "${youtubeId}" from private playlist "${playlistId}" for user "${session.userId}".`
  1511. );
  1512. CacheModule.runJob("PUB", {
  1513. channel: "playlist.removeSong",
  1514. value: {
  1515. playlistId: playlist._id,
  1516. youtubeId,
  1517. userId: session.userId,
  1518. privacy: playlist.privacy
  1519. }
  1520. });
  1521. CacheModule.runJob("PUB", {
  1522. channel: "playlist.updated",
  1523. value: { playlistId }
  1524. });
  1525. return cb({
  1526. status: "success",
  1527. message: "Song has been successfully removed from playlist",
  1528. data: { songs: playlist.songs }
  1529. });
  1530. }
  1531. );
  1532. }),
  1533. /**
  1534. * Updates the displayName of a private playlist
  1535. *
  1536. * @param {object} session - the session object automatically added by the websocket
  1537. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  1538. * @param {Function} cb - gets called with the result
  1539. */
  1540. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  1541. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1542. async.waterfall(
  1543. [
  1544. next => {
  1545. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1546. .then(playlist => next(null, playlist))
  1547. .catch(next);
  1548. },
  1549. (playlist, next) => {
  1550. if (playlist.type !== "user") return next("Playlist cannot be modified.");
  1551. return next(null);
  1552. },
  1553. next => {
  1554. playlistModel.updateOne(
  1555. { _id: playlistId, createdBy: session.userId },
  1556. { $set: { displayName } },
  1557. { runValidators: true },
  1558. next
  1559. );
  1560. },
  1561. (res, next) => {
  1562. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1563. .then(playlist => next(null, playlist))
  1564. .catch(next);
  1565. }
  1566. ],
  1567. async (err, playlist) => {
  1568. if (err) {
  1569. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1570. this.log(
  1571. "ERROR",
  1572. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1573. `Updating display name to "${displayName}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1574. );
  1575. return cb({ status: "error", message: err });
  1576. }
  1577. this.log(
  1578. "SUCCESS",
  1579. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1580. `Successfully updated display name to "${displayName}" for private playlist "${playlistId}" for user "${session.userId}".`
  1581. );
  1582. CacheModule.runJob("PUB", {
  1583. channel: "playlist.updateDisplayName",
  1584. value: {
  1585. playlistId,
  1586. displayName,
  1587. userId: session.userId,
  1588. privacy: playlist.privacy
  1589. }
  1590. });
  1591. CacheModule.runJob("PUB", {
  1592. channel: "playlist.updated",
  1593. value: { playlistId }
  1594. });
  1595. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1596. userId: session.userId,
  1597. type: "playlist__edit_display_name",
  1598. payload: {
  1599. message: `Changed display name of playlist <playlistId>${displayName}</playlistId>`,
  1600. playlistId
  1601. }
  1602. });
  1603. return cb({
  1604. status: "success",
  1605. message: "Playlist has been successfully updated"
  1606. });
  1607. }
  1608. );
  1609. }),
  1610. /**
  1611. * Removes a user's own modifiable user playlist
  1612. *
  1613. * @param {object} session - the session object automatically added by the websocket
  1614. * @param {string} playlistId - the id of the playlist we are removing
  1615. * @param {Function} cb - gets called with the result
  1616. */
  1617. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1618. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1619. async.waterfall(
  1620. [
  1621. next => {
  1622. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1623. .then(playlist => next(null, playlist))
  1624. .catch(next);
  1625. },
  1626. (playlist, next) => {
  1627. if (playlist.createdBy !== session.userId) return next("You do not own this playlist.");
  1628. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1629. return next(null, playlist);
  1630. },
  1631. (playlist, next) => {
  1632. userModel.updateOne(
  1633. { _id: playlist.createdBy },
  1634. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1635. err => next(err, playlist)
  1636. );
  1637. },
  1638. (playlist, next) => {
  1639. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1640. .then(() => next(null, playlist))
  1641. .catch(next);
  1642. }
  1643. ],
  1644. async (err, playlist) => {
  1645. if (err) {
  1646. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1647. this.log(
  1648. "ERROR",
  1649. "PLAYLIST_REMOVE",
  1650. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1651. );
  1652. return cb({ status: "error", message: err });
  1653. }
  1654. this.log(
  1655. "SUCCESS",
  1656. "PLAYLIST_REMOVE",
  1657. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1658. );
  1659. CacheModule.runJob("PUB", {
  1660. channel: "playlist.delete",
  1661. value: {
  1662. userId: session.userId,
  1663. playlistId
  1664. }
  1665. });
  1666. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1667. userId: playlist.createdBy,
  1668. type: "playlist__remove",
  1669. payload: {
  1670. message: `Removed playlist ${playlist.displayName}`
  1671. }
  1672. });
  1673. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1674. return cb({
  1675. status: "success",
  1676. message: "Playlist successfully removed"
  1677. });
  1678. }
  1679. );
  1680. }),
  1681. /**
  1682. * Removes a user's modifiable user playlist as an admin
  1683. *
  1684. * @param {object} session - the session object automatically added by the websocket
  1685. * @param {string} playlistId - the id of the playlist we are removing
  1686. * @param {Function} cb - gets called with the result
  1687. */
  1688. removeAdmin: isAdminRequired(async function removeAdmin(session, playlistId, cb) {
  1689. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1690. async.waterfall(
  1691. [
  1692. next => {
  1693. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1694. .then(playlist => next(null, playlist))
  1695. .catch(next);
  1696. },
  1697. (playlist, next) => {
  1698. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1699. return next(null, playlist);
  1700. },
  1701. (playlist, next) => {
  1702. userModel.updateOne(
  1703. { _id: playlist.createdBy },
  1704. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1705. err => next(err, playlist, playlist.createdBy)
  1706. );
  1707. },
  1708. (playlist, playlistCreator, next) => {
  1709. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1710. .then(() => next(null, playlistCreator))
  1711. .catch(next);
  1712. }
  1713. ],
  1714. async (err, playlistCreator) => {
  1715. if (err) {
  1716. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1717. this.log(
  1718. "ERROR",
  1719. "PLAYLIST_REMOVE_ADMIN",
  1720. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1721. );
  1722. return cb({ status: "error", message: err });
  1723. }
  1724. this.log(
  1725. "SUCCESS",
  1726. "PLAYLIST_REMOVE_ADMIN",
  1727. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1728. );
  1729. CacheModule.runJob("PUB", {
  1730. channel: "playlist.delete",
  1731. value: {
  1732. userId: playlistCreator,
  1733. playlistId
  1734. }
  1735. });
  1736. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1737. return cb({
  1738. status: "success",
  1739. message: "Playlist successfully removed"
  1740. });
  1741. }
  1742. );
  1743. }),
  1744. /**
  1745. * Updates the privacy of a private playlist
  1746. *
  1747. * @param {object} session - the session object automatically added by the websocket
  1748. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1749. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1750. * @param {Function} cb - gets called with the result
  1751. */
  1752. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  1753. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1754. async.waterfall(
  1755. [
  1756. next => {
  1757. playlistModel.updateOne(
  1758. { _id: playlistId, createdBy: session.userId },
  1759. { $set: { privacy } },
  1760. { runValidators: true },
  1761. next
  1762. );
  1763. },
  1764. (res, next) => {
  1765. if (res.n === 0) next("No user playlist found with that id and owned by you.");
  1766. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1767. else {
  1768. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1769. .then(playlist => next(null, playlist))
  1770. .catch(next);
  1771. }
  1772. }
  1773. ],
  1774. async (err, playlist) => {
  1775. if (err) {
  1776. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1777. this.log(
  1778. "ERROR",
  1779. "PLAYLIST_UPDATE_PRIVACY",
  1780. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1781. );
  1782. return cb({ status: "error", message: err });
  1783. }
  1784. this.log(
  1785. "SUCCESS",
  1786. "PLAYLIST_UPDATE_PRIVACY",
  1787. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  1788. );
  1789. CacheModule.runJob("PUB", {
  1790. channel: "playlist.updatePrivacy",
  1791. value: {
  1792. userId: session.userId,
  1793. playlist
  1794. }
  1795. });
  1796. CacheModule.runJob("PUB", {
  1797. channel: "playlist.updated",
  1798. value: { playlistId }
  1799. });
  1800. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1801. userId: session.userId,
  1802. type: "playlist__edit_privacy",
  1803. payload: {
  1804. message: `Changed privacy of playlist <playlistId>${playlist.displayName}</playlistId> to ${privacy}`,
  1805. playlistId
  1806. }
  1807. });
  1808. return cb({
  1809. status: "success",
  1810. message: "Playlist has been successfully updated"
  1811. });
  1812. }
  1813. );
  1814. }),
  1815. /**
  1816. * Updates the privacy of a playlist
  1817. *
  1818. * @param {object} session - the session object automatically added by the websocket
  1819. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  1820. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  1821. * @param {Function} cb - gets called with the result
  1822. */
  1823. updatePrivacyAdmin: isAdminRequired(async function updatePrivacyAdmin(session, playlistId, privacy, cb) {
  1824. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1825. async.waterfall(
  1826. [
  1827. next => {
  1828. playlistModel.updateOne({ _id: playlistId }, { $set: { privacy } }, { runValidators: true }, next);
  1829. },
  1830. (res, next) => {
  1831. if (res.n === 0) next("No playlist found with that id.");
  1832. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  1833. else {
  1834. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1835. .then(playlist => next(null, playlist))
  1836. .catch(next);
  1837. }
  1838. }
  1839. ],
  1840. async (err, playlist) => {
  1841. if (err) {
  1842. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1843. this.log(
  1844. "ERROR",
  1845. "PLAYLIST_UPDATE_PRIVACY_ADMIN",
  1846. `Updating privacy to "${privacy}" for playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1847. );
  1848. return cb({ status: "error", message: err });
  1849. }
  1850. this.log(
  1851. "SUCCESS",
  1852. "PLAYLIST_UPDATE_PRIVACY_ADMIn",
  1853. `Successfully updated privacy to "${privacy}" for playlist "${playlistId}" for user "${session.userId}".`
  1854. );
  1855. if (playlist.type === "user") {
  1856. CacheModule.runJob("PUB", {
  1857. channel: "playlist.updatePrivacy",
  1858. value: {
  1859. userId: playlist.createdBy,
  1860. playlist
  1861. }
  1862. });
  1863. }
  1864. CacheModule.runJob("PUB", {
  1865. channel: "playlist.updated",
  1866. value: { playlistId }
  1867. });
  1868. return cb({
  1869. status: "success",
  1870. message: "Playlist has been successfully updated"
  1871. });
  1872. }
  1873. );
  1874. }),
  1875. /**
  1876. * Deletes all orphaned station playlists
  1877. *
  1878. * @param {object} session - the session object automatically added by socket.io
  1879. * @param {Function} cb - gets called with the result
  1880. */
  1881. deleteOrphanedStationPlaylists: isAdminRequired(async function index(session, cb) {
  1882. async.waterfall(
  1883. [
  1884. next => {
  1885. PlaylistsModule.runJob("DELETE_ORPHANED_STATION_PLAYLISTS", {}, this)
  1886. .then(() => next())
  1887. .catch(next);
  1888. }
  1889. ],
  1890. async err => {
  1891. if (err) {
  1892. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1893. this.log(
  1894. "ERROR",
  1895. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1896. `Deleting orphaned station playlists failed. "${err}"`
  1897. );
  1898. return cb({ status: "error", message: err });
  1899. }
  1900. this.log(
  1901. "SUCCESS",
  1902. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  1903. "Deleting orphaned station playlists successful."
  1904. );
  1905. return cb({ status: "success", message: "Successfully deleted orphaned station playlists." });
  1906. }
  1907. );
  1908. }),
  1909. /**
  1910. * Deletes all orphaned genre playlists
  1911. *
  1912. * @param {object} session - the session object automatically added by socket.io
  1913. * @param {Function} cb - gets called with the result
  1914. */
  1915. deleteOrphanedGenrePlaylists: isAdminRequired(async function index(session, cb) {
  1916. async.waterfall(
  1917. [
  1918. next => {
  1919. PlaylistsModule.runJob("DELETE_ORPHANED_GENRE_PLAYLISTS", {}, this)
  1920. .then(() => next())
  1921. .catch(next);
  1922. }
  1923. ],
  1924. async err => {
  1925. if (err) {
  1926. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1927. this.log(
  1928. "ERROR",
  1929. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1930. `Deleting orphaned genre playlists failed. "${err}"`
  1931. );
  1932. return cb({ status: "error", message: err });
  1933. }
  1934. this.log(
  1935. "SUCCESS",
  1936. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  1937. "Deleting orphaned genre playlists successful."
  1938. );
  1939. return cb({ status: "success", message: "Successfully deleted orphaned genre playlists." });
  1940. }
  1941. );
  1942. }),
  1943. /**
  1944. * Deletes all orphaned artist playlists
  1945. *
  1946. * @param {object} session - the session object automatically added by socket.io
  1947. * @param {Function} cb - gets called with the result
  1948. */
  1949. deleteOrphanedArtistPlaylists: isAdminRequired(async function index(session, cb) {
  1950. async.waterfall(
  1951. [
  1952. next => {
  1953. PlaylistsModule.runJob("DELETE_ORPHANED_ARTIST_PLAYLISTS", {}, this)
  1954. .then(() => next())
  1955. .catch(next);
  1956. }
  1957. ],
  1958. async err => {
  1959. if (err) {
  1960. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1961. this.log(
  1962. "ERROR",
  1963. "PLAYLISTS_DELETE_ORPHANED_ARTIST_PLAYLISTS",
  1964. `Deleting orphaned artist playlists failed. "${err}"`
  1965. );
  1966. return cb({ status: "error", message: err });
  1967. }
  1968. this.log(
  1969. "SUCCESS",
  1970. "PLAYLISTS_DELETE_ORPHANED_ARTIST_PLAYLISTS",
  1971. "Deleting orphaned artist playlists successful."
  1972. );
  1973. return cb({ status: "success", message: "Successfully deleted orphaned artist playlists." });
  1974. }
  1975. );
  1976. }),
  1977. /**
  1978. * Requests orpahned playlist songs
  1979. *
  1980. * @param {object} session - the session object automatically added by socket.io
  1981. * @param {Function} cb - gets called with the result
  1982. */
  1983. requestOrphanedPlaylistSongs: isAdminRequired(async function index(session, cb) {
  1984. async.waterfall(
  1985. [
  1986. next => {
  1987. SongsModule.runJob("REQUEST_ORPHANED_PLAYLIST_SONGS", {}, this)
  1988. .then(() => next())
  1989. .catch(next);
  1990. }
  1991. ],
  1992. async err => {
  1993. if (err) {
  1994. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1995. this.log(
  1996. "ERROR",
  1997. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  1998. `Requesting orphaned playlist songs failed. "${err}"`
  1999. );
  2000. return cb({ status: "error", message: err });
  2001. }
  2002. this.log(
  2003. "SUCCESS",
  2004. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  2005. "Requesting orphaned playlist songs was successful."
  2006. );
  2007. return cb({ status: "success", message: "Successfully requested orphaned playlist songs." });
  2008. }
  2009. );
  2010. }),
  2011. /**
  2012. * Clears and refills a station playlist
  2013. *
  2014. * @param {object} session - the session object automatically added by socket.io
  2015. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  2016. * @param {Function} cb - gets called with the result
  2017. */
  2018. clearAndRefillStationPlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  2019. async.waterfall(
  2020. [
  2021. next => {
  2022. if (!playlistId) next("Please specify a playlist id");
  2023. else {
  2024. PlaylistsModule.runJob("CLEAR_AND_REFILL_STATION_PLAYLIST", { playlistId }, this)
  2025. .then(() => {
  2026. next();
  2027. })
  2028. .catch(err => {
  2029. next(err);
  2030. });
  2031. }
  2032. }
  2033. ],
  2034. async err => {
  2035. if (err) {
  2036. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2037. this.log(
  2038. "ERROR",
  2039. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  2040. `Clearing and refilling station playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2041. );
  2042. return cb({ status: "error", message: err });
  2043. }
  2044. this.log(
  2045. "SUCCESS",
  2046. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  2047. `Successfully cleared and refilled station playlist "${playlistId}" for user "${session.userId}".`
  2048. );
  2049. return cb({
  2050. status: "success",
  2051. message: "Playlist has been successfully cleared and refilled"
  2052. });
  2053. }
  2054. );
  2055. }),
  2056. /**
  2057. * Clears and refills a genre playlist
  2058. *
  2059. * @param {object} session - the session object automatically added by socket.io
  2060. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  2061. * @param {Function} cb - gets called with the result
  2062. */
  2063. clearAndRefillGenrePlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  2064. async.waterfall(
  2065. [
  2066. next => {
  2067. if (!playlistId) next("Please specify a playlist id");
  2068. else {
  2069. PlaylistsModule.runJob("CLEAR_AND_REFILL_GENRE_PLAYLIST", { playlistId }, this)
  2070. .then(() => {
  2071. next();
  2072. })
  2073. .catch(err => {
  2074. next(err);
  2075. });
  2076. }
  2077. }
  2078. ],
  2079. async err => {
  2080. if (err) {
  2081. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2082. this.log(
  2083. "ERROR",
  2084. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2085. `Clearing and refilling genre playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2086. );
  2087. return cb({ status: "error", message: err });
  2088. }
  2089. this.log(
  2090. "SUCCESS",
  2091. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2092. `Successfully cleared and refilled genre playlist "${playlistId}" for user "${session.userId}".`
  2093. );
  2094. return cb({
  2095. status: "success",
  2096. message: "Playlist has been successfully cleared and refilled"
  2097. });
  2098. }
  2099. );
  2100. }),
  2101. /**
  2102. * Clears and refills a artist playlist
  2103. *
  2104. * @param {object} session - the session object automatically added by socket.io
  2105. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  2106. * @param {Function} cb - gets called with the result
  2107. */
  2108. clearAndRefillArtistPlaylist: isAdminRequired(async function index(session, playlistId, cb) {
  2109. async.waterfall(
  2110. [
  2111. next => {
  2112. if (!playlistId) next("Please specify a playlist id");
  2113. else {
  2114. PlaylistsModule.runJob("CLEAR_AND_REFILL_ARTIST_PLAYLIST", { playlistId }, this)
  2115. .then(() => {
  2116. next();
  2117. })
  2118. .catch(err => {
  2119. next(err);
  2120. });
  2121. }
  2122. }
  2123. ],
  2124. async err => {
  2125. if (err) {
  2126. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2127. this.log(
  2128. "ERROR",
  2129. "PLAYLIST_CLEAR_AND_REFILL_ARTIST_PLAYLIST",
  2130. `Clearing and refilling artist playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2131. );
  2132. return cb({ status: "error", message: err });
  2133. }
  2134. this.log(
  2135. "SUCCESS",
  2136. "PLAYLIST_CLEAR_AND_REFILL_ARTIST_PLAYLIST",
  2137. `Successfully cleared and refilled artist playlist "${playlistId}" for user "${session.userId}".`
  2138. );
  2139. return cb({
  2140. status: "success",
  2141. message: "Playlist has been successfully cleared and refilled"
  2142. });
  2143. }
  2144. );
  2145. }),
  2146. /**
  2147. * Clears and refills all station playlists
  2148. *
  2149. * @param {object} session - the session object automatically added by socket.io
  2150. * @param {Function} cb - gets called with the result
  2151. */
  2152. clearAndRefillAllStationPlaylists: isAdminRequired(async function index(session, cb) {
  2153. async.waterfall(
  2154. [
  2155. next => {
  2156. PlaylistsModule.runJob("GET_ALL_STATION_PLAYLISTS", {}, this)
  2157. .then(response => {
  2158. next(null, response.playlists);
  2159. })
  2160. .catch(err => {
  2161. next(err);
  2162. });
  2163. },
  2164. (playlists, next) => {
  2165. async.eachLimit(
  2166. playlists,
  2167. 1,
  2168. (playlist, next) => {
  2169. PlaylistsModule.runJob(
  2170. "CLEAR_AND_REFILL_STATION_PLAYLIST",
  2171. { playlistId: playlist._id },
  2172. this
  2173. )
  2174. .then(() => {
  2175. next();
  2176. })
  2177. .catch(err => {
  2178. next(err);
  2179. });
  2180. },
  2181. next
  2182. );
  2183. }
  2184. ],
  2185. async err => {
  2186. if (err) {
  2187. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2188. this.log(
  2189. "ERROR",
  2190. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2191. `Clearing and refilling all station playlists failed for user "${session.userId}". "${err}"`
  2192. );
  2193. return cb({ status: "error", message: err });
  2194. }
  2195. this.log(
  2196. "SUCCESS",
  2197. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2198. `Successfully cleared and refilled all station playlists for user "${session.userId}".`
  2199. );
  2200. return cb({
  2201. status: "success",
  2202. message: "Playlists have been successfully cleared and refilled"
  2203. });
  2204. }
  2205. );
  2206. }),
  2207. /**
  2208. * Clears and refills all genre playlists
  2209. *
  2210. * @param {object} session - the session object automatically added by socket.io
  2211. * @param {Function} cb - gets called with the result
  2212. */
  2213. clearAndRefillAllGenrePlaylists: isAdminRequired(async function index(session, cb) {
  2214. async.waterfall(
  2215. [
  2216. next => {
  2217. PlaylistsModule.runJob("GET_ALL_GENRE_PLAYLISTS", {}, this)
  2218. .then(response => {
  2219. next(null, response.playlists);
  2220. })
  2221. .catch(err => {
  2222. next(err);
  2223. });
  2224. },
  2225. (playlists, next) => {
  2226. async.eachLimit(
  2227. playlists,
  2228. 1,
  2229. (playlist, next) => {
  2230. PlaylistsModule.runJob(
  2231. "CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2232. { playlistId: playlist._id },
  2233. this
  2234. )
  2235. .then(() => {
  2236. next();
  2237. })
  2238. .catch(err => {
  2239. next(err);
  2240. });
  2241. },
  2242. next
  2243. );
  2244. }
  2245. ],
  2246. async err => {
  2247. if (err) {
  2248. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2249. this.log(
  2250. "ERROR",
  2251. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2252. `Clearing and refilling all genre playlists failed for user "${session.userId}". "${err}"`
  2253. );
  2254. return cb({ status: "error", message: err });
  2255. }
  2256. this.log(
  2257. "SUCCESS",
  2258. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2259. `Successfully cleared and refilled all genre playlists for user "${session.userId}".`
  2260. );
  2261. return cb({
  2262. status: "success",
  2263. message: "Playlists have been successfully cleared and refilled"
  2264. });
  2265. }
  2266. );
  2267. }),
  2268. /**
  2269. * Clears and refills all artist playlists
  2270. *
  2271. * @param {object} session - the session object automatically added by socket.io
  2272. * @param {Function} cb - gets called with the result
  2273. */
  2274. clearAndRefillAllArtistPlaylists: isAdminRequired(async function index(session, cb) {
  2275. async.waterfall(
  2276. [
  2277. next => {
  2278. PlaylistsModule.runJob("GET_ALL_ARTIST_PLAYLISTS", {}, this)
  2279. .then(response => {
  2280. next(null, response.playlists);
  2281. })
  2282. .catch(err => {
  2283. next(err);
  2284. });
  2285. },
  2286. (playlists, next) => {
  2287. async.eachLimit(
  2288. playlists,
  2289. 1,
  2290. (playlist, next) => {
  2291. PlaylistsModule.runJob(
  2292. "CLEAR_AND_REFILL_ARTIST_PLAYLIST",
  2293. { playlistId: playlist._id },
  2294. this
  2295. )
  2296. .then(() => {
  2297. next();
  2298. })
  2299. .catch(err => {
  2300. next(err);
  2301. });
  2302. },
  2303. next
  2304. );
  2305. }
  2306. // next => {
  2307. // // PlaylistsModule.runJob("CREATE_MISSING_ARTIST_PLAYLISTS", {}, null)
  2308. // // .then()
  2309. // // .catch()
  2310. // // .finally(() => {
  2311. // // SongsModule.runJob("GET_ALL_ARTISTS", {}, null)
  2312. // // .then(response => {
  2313. // // const { artists } = response;
  2314. // // artists.forEach(artist => {
  2315. // // PlaylistsModule.runJob("AUTOFILL_ARTIST_PLAYLIST", { artist }, null).then().catch();
  2316. // // });
  2317. // // })
  2318. // // .catch();
  2319. // // });
  2320. // PlaylistsModule.runJob("GET_MISSING_ARTIST_PLAYLISTS", {}, this).then(response => {
  2321. // console.log(response);
  2322. // });
  2323. // }
  2324. ],
  2325. async err => {
  2326. if (err) {
  2327. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2328. this.log(
  2329. "ERROR",
  2330. "PLAYLIST_CLEAR_AND_REFILL_ALL_ARTIST_PLAYLISTS",
  2331. `Clearing and refilling all artist playlists failed for user "${session.userId}". "${err}"`
  2332. );
  2333. return cb({ status: "error", message: err });
  2334. }
  2335. this.log(
  2336. "SUCCESS",
  2337. "PLAYLIST_CLEAR_AND_REFILL_ALL_ARTIST_PLAYLISTS",
  2338. `Successfully cleared and refilled all artist playlists for user "${session.userId}".`
  2339. );
  2340. return cb({
  2341. status: "success",
  2342. message: "Playlists have been successfully cleared and refilled"
  2343. });
  2344. }
  2345. );
  2346. }),
  2347. /**
  2348. * Create missing genre playlists
  2349. *
  2350. * @param {object} session - the session object automatically added by socket.io
  2351. * @param {Function} cb - gets called with the result
  2352. */
  2353. createMissingGenrePlaylists: isAdminRequired(async function index(session, cb) {
  2354. async.waterfall(
  2355. [
  2356. next => {
  2357. PlaylistsModule.runJob("CREATE_MISSING_GENRE_PLAYLISTS", this)
  2358. .then(() => {
  2359. next();
  2360. })
  2361. .catch(err => {
  2362. next(err);
  2363. });
  2364. }
  2365. ],
  2366. async err => {
  2367. if (err) {
  2368. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2369. this.log(
  2370. "ERROR",
  2371. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2372. `Creating missing genre playlists failed for user "${session.userId}". "${err}"`
  2373. );
  2374. return cb({ status: "error", message: err });
  2375. }
  2376. this.log(
  2377. "SUCCESS",
  2378. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2379. `Successfully created missing genre playlists for user "${session.userId}".`
  2380. );
  2381. return cb({
  2382. status: "success",
  2383. message: "Missing genre playlists have been successfully created"
  2384. });
  2385. }
  2386. );
  2387. }),
  2388. /**
  2389. * Create missing artist playlists
  2390. *
  2391. * @param {object} session - the session object automatically added by socket.io
  2392. * @param {Function} cb - gets called with the result
  2393. */
  2394. createMissingArtistPlaylists: isAdminRequired(async function index(session, cb) {
  2395. async.waterfall(
  2396. [
  2397. next => {
  2398. PlaylistsModule.runJob("CREATE_MISSING_ARTIST_PLAYLISTS", this)
  2399. .then(() => {
  2400. next();
  2401. })
  2402. .catch(err => {
  2403. next(err);
  2404. });
  2405. }
  2406. ],
  2407. async err => {
  2408. if (err) {
  2409. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2410. this.log(
  2411. "ERROR",
  2412. "PLAYLIST_CREATE_MISSING_ARTIST_PLAYLISTS",
  2413. `Creating missing artist playlists failed for user "${session.userId}". "${err}"`
  2414. );
  2415. return cb({ status: "error", message: err });
  2416. }
  2417. this.log(
  2418. "SUCCESS",
  2419. "PLAYLIST_CREATE_MISSING_ARTIST_PLAYLISTS",
  2420. `Successfully created missing artist playlists for user "${session.userId}".`
  2421. );
  2422. return cb({
  2423. status: "success",
  2424. message: "Missing artist playlists have been successfully created"
  2425. });
  2426. }
  2427. );
  2428. })
  2429. };