playlists.js 82 KB

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