playlists.js 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949
  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. youtubeId: res.youtubeId
  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. youtubeId: res.youtubeId
  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, youtubeId: res.youtubeId } }
  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.youtubeId - the youtube id 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.youtubeId) 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: { youtubeId: song.youtubeId } } },
  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.youtubeId} 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.youtubeId} 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} youtubeId - the youtube id 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, youtubeId, 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.youtubeId": youtubeId },
  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, youtubeId }, 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 "${youtubeId}" 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 "${youtubeId}" 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 <youtubeId>${songName}</youtubeId> to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1118. thumbnail: newSong.thumbnail,
  1119. playlistId,
  1120. youtubeId
  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, youtubeId, 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. youtubeId,
  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 <youtubeId>${title} by ${artists.join(", ")}</youtubeId>`,
  1156. youtubeId,
  1157. thumbnail
  1158. }
  1159. });
  1160. } else {
  1161. CacheModule.runJob("PUB", {
  1162. channel: "ratings.dislike",
  1163. value: JSON.stringify({
  1164. youtubeId,
  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 <youtubeId>${title} by ${artists.join(", ")}</youtubeId>`,
  1175. youtubeId,
  1176. thumbnail
  1177. }
  1178. });
  1179. }
  1180. }
  1181. return cb({
  1182. status: "success",
  1183. message: "Song has been successfully added to the playlist",
  1184. data: { songs: playlist.songs }
  1185. });
  1186. }
  1187. );
  1188. }),
  1189. /**
  1190. * Adds songs to a playlist
  1191. *
  1192. * @param {object} session - the session object automatically added by the websocket
  1193. * @param {string} playlistId - the id of the playlist we are adding the songs to
  1194. * @param {Array} youtubeIds - the YouTube ids of the songs we are trying to add
  1195. * @param {Function} cb - gets called with the result
  1196. */
  1197. addSongsToPlaylist: useHasPermission(
  1198. "playlists.songs.add",
  1199. async function addSongsToPlaylist(session, playlistId, youtubeIds, cb) {
  1200. const successful = [];
  1201. const existing = [];
  1202. const failed = {};
  1203. const errors = {};
  1204. const lastYoutubeId = "none";
  1205. const addError = message => {
  1206. if (!errors[message]) errors[message] = 1;
  1207. else errors[message] += 1;
  1208. };
  1209. this.keepLongJob();
  1210. this.publishProgress({
  1211. status: "started",
  1212. title: "Bulk add songs to playlist",
  1213. message: "Adding songs to playlist.",
  1214. id: this.toString()
  1215. });
  1216. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1217. await CacheModule.runJob(
  1218. "PUB",
  1219. {
  1220. channel: "longJob.added",
  1221. value: { jobId: this.toString(), userId: session.userId }
  1222. },
  1223. this
  1224. );
  1225. async.waterfall(
  1226. [
  1227. next => {
  1228. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1229. .then(playlist => {
  1230. if (!playlist) return next("Playlist not found.");
  1231. return next(null, playlist);
  1232. })
  1233. .catch(next);
  1234. },
  1235. (playlist, next) => {
  1236. if (playlist.type !== "admin") return next("Playlist must be of type admin.");
  1237. return next();
  1238. },
  1239. next => {
  1240. async.eachLimit(
  1241. youtubeIds,
  1242. 1,
  1243. (youtubeId, next) => {
  1244. this.publishProgress({ status: "update", message: `Adding song "${youtubeId}"` });
  1245. PlaylistsModule.runJob("ADD_SONG_TO_PLAYLIST", { playlistId, youtubeId }, this)
  1246. .then(() => {
  1247. successful.push(youtubeId);
  1248. next();
  1249. })
  1250. .catch(async err => {
  1251. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1252. if (err === "That song is already in the playlist.") {
  1253. existing.push(youtubeId);
  1254. next();
  1255. } else {
  1256. addError(err);
  1257. failed[youtubeId] = err;
  1258. next();
  1259. }
  1260. });
  1261. },
  1262. err => {
  1263. if (err) next(err);
  1264. else next();
  1265. }
  1266. );
  1267. },
  1268. next => {
  1269. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1270. .then(playlist => {
  1271. if (!playlist) return next("Playlist not found.");
  1272. return next(null, playlist);
  1273. })
  1274. .catch(next);
  1275. }
  1276. ],
  1277. async (err, playlist) => {
  1278. if (err) {
  1279. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1280. this.log(
  1281. "ERROR",
  1282. "PLAYLIST_ADD_SONGS",
  1283. `Adding songs to playlist "${playlistId}" failed for user "${
  1284. session.userId
  1285. }". "${err}". Stats: successful:${successful.length}, existing:${existing.length}, failed:${
  1286. Object.keys(failed).length
  1287. }, last youtubeId:${lastYoutubeId}, youtubeIds length:${
  1288. youtubeIds ? youtubeIds.length : null
  1289. }`
  1290. );
  1291. return cb({
  1292. status: "error",
  1293. message: err,
  1294. data: {
  1295. stats: {
  1296. successful,
  1297. existing,
  1298. failed,
  1299. errors
  1300. }
  1301. }
  1302. });
  1303. }
  1304. this.log(
  1305. "SUCCESS",
  1306. "PLAYLIST_ADD_SONGS",
  1307. `Successfully added songs to playlist "${playlistId}" for user "${
  1308. session.userId
  1309. }". Stats: successful:${successful.length}, existing:${existing.length}, failed:${
  1310. Object.keys(failed).length
  1311. }, youtubeIds length:${youtubeIds ? youtubeIds.length : null}`
  1312. );
  1313. CacheModule.runJob("PUB", {
  1314. channel: "playlist.updated",
  1315. value: { playlistId }
  1316. });
  1317. const message = `Done adding songs. Succesful: ${successful.length}, failed: ${
  1318. Object.keys(failed).length
  1319. }, existing: ${existing.length}.`;
  1320. this.publishProgress({
  1321. status: "success",
  1322. message
  1323. });
  1324. return cb({
  1325. status: "success",
  1326. message,
  1327. data: {
  1328. songs: playlist.songs,
  1329. stats: {
  1330. successful,
  1331. existing,
  1332. failed,
  1333. errors
  1334. }
  1335. }
  1336. });
  1337. }
  1338. );
  1339. }
  1340. ),
  1341. /**
  1342. * Removes songs from a playlist
  1343. *
  1344. * @param {object} session - the session object automatically added by the websocket
  1345. * @param {string} playlistId - the id of the playlist we are removing the songs from
  1346. * @param {Array} youtubeIds - the YouTube ids of the songs we are trying to remove
  1347. * @param {Function} cb - gets called with the result
  1348. */
  1349. removeSongsFromPlaylist: useHasPermission(
  1350. "playlists.songs.remove",
  1351. async function removeSongsFromPlaylist(session, playlistId, youtubeIds, cb) {
  1352. const successful = [];
  1353. const notInPlaylist = [];
  1354. const failed = {};
  1355. const errors = {};
  1356. const lastYoutubeId = "none";
  1357. const addError = message => {
  1358. if (!errors[message]) errors[message] = 1;
  1359. else errors[message] += 1;
  1360. };
  1361. this.keepLongJob();
  1362. this.publishProgress({
  1363. status: "started",
  1364. title: "Bulk remove songs from playlist",
  1365. message: "Removing songs from playlist.",
  1366. id: this.toString()
  1367. });
  1368. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1369. await CacheModule.runJob(
  1370. "PUB",
  1371. {
  1372. channel: "longJob.added",
  1373. value: { jobId: this.toString(), userId: session.userId }
  1374. },
  1375. this
  1376. );
  1377. async.waterfall(
  1378. [
  1379. next => {
  1380. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1381. .then(playlist => {
  1382. if (!playlist) return next("Playlist not found.");
  1383. return next(null, playlist);
  1384. })
  1385. .catch(next);
  1386. },
  1387. (playlist, next) => {
  1388. if (playlist.type !== "admin") return next("Playlist must be of type admin.");
  1389. return next();
  1390. },
  1391. next => {
  1392. async.eachLimit(
  1393. youtubeIds,
  1394. 1,
  1395. (youtubeId, next) => {
  1396. this.publishProgress({ status: "update", message: `Removing song "${youtubeId}"` });
  1397. PlaylistsModule.runJob("REMOVE_FROM_PLAYLIST", { playlistId, youtubeId }, this)
  1398. .then(() => {
  1399. successful.push(youtubeId);
  1400. next();
  1401. })
  1402. .catch(async err => {
  1403. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1404. if (err === "That song is not currently in the playlist.") {
  1405. notInPlaylist.push(youtubeId);
  1406. next();
  1407. } else {
  1408. addError(err);
  1409. failed[youtubeId] = err;
  1410. next();
  1411. }
  1412. });
  1413. },
  1414. err => {
  1415. if (err) next(err);
  1416. else next();
  1417. }
  1418. );
  1419. },
  1420. next => {
  1421. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1422. .then(playlist => {
  1423. if (!playlist) return next("Playlist not found.");
  1424. return next(null, playlist);
  1425. })
  1426. .catch(next);
  1427. }
  1428. ],
  1429. async (err, playlist) => {
  1430. if (err) {
  1431. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1432. this.log(
  1433. "ERROR",
  1434. "PLAYLIST_REMOVE_SONGS",
  1435. `Removing songs from playlist "${playlistId}" failed for user "${
  1436. session.userId
  1437. }". "${err}". Stats: successful:${successful.length}, notInPlaylist:${
  1438. notInPlaylist.length
  1439. }, failed:${
  1440. Object.keys(failed).length
  1441. }, last youtubeId:${lastYoutubeId}, youtubeIds length:${
  1442. youtubeIds ? youtubeIds.length : null
  1443. }`
  1444. );
  1445. return cb({
  1446. status: "error",
  1447. message: err,
  1448. data: {
  1449. stats: {
  1450. successful,
  1451. notInPlaylist,
  1452. failed,
  1453. errors
  1454. }
  1455. }
  1456. });
  1457. }
  1458. this.log(
  1459. "SUCCESS",
  1460. "PLAYLIST_REMOVE_SONGS",
  1461. `Successfully removed songs from playlist "${playlistId}" for user "${
  1462. session.userId
  1463. }". Stats: successful:${successful.length}, notInPlaylist:${notInPlaylist.length}, failed:${
  1464. Object.keys(failed).length
  1465. }, youtubeIds length:${youtubeIds ? youtubeIds.length : null}`
  1466. );
  1467. CacheModule.runJob("PUB", {
  1468. channel: "playlist.updated",
  1469. value: { playlistId }
  1470. });
  1471. const message = `Done removing songs. Succesful: ${successful.length}, failed: ${
  1472. Object.keys(failed).length
  1473. }, not in playlist: ${notInPlaylist.length}.`;
  1474. this.publishProgress({
  1475. status: "success",
  1476. message
  1477. });
  1478. return cb({
  1479. status: "success",
  1480. message,
  1481. data: {
  1482. songs: playlist.songs,
  1483. stats: {
  1484. successful,
  1485. notInPlaylist,
  1486. failed,
  1487. errors
  1488. }
  1489. }
  1490. });
  1491. }
  1492. );
  1493. }
  1494. ),
  1495. /**
  1496. * Adds a set of songs to a private playlist
  1497. *
  1498. * @param {object} session - the session object automatically added by the websocket
  1499. * @param {string} url - the url of the the YouTube playlist
  1500. * @param {string} playlistId - the id of the playlist we are adding the set of songs to
  1501. * @param {boolean} musicOnly - whether to only add music to the playlist
  1502. * @param {Function} cb - gets called with the result
  1503. */
  1504. addSetToPlaylist: isLoginRequired(async function addSetToPlaylist(session, url, playlistId, musicOnly, cb) {
  1505. let videosInPlaylistTotal = 0;
  1506. let songsInPlaylistTotal = 0;
  1507. let addSongsStats = null;
  1508. const addedSongs = [];
  1509. this.keepLongJob();
  1510. this.publishProgress({
  1511. status: "started",
  1512. title: "Import YouTube playlist",
  1513. message: "Importing YouTube playlist.",
  1514. id: this.toString()
  1515. });
  1516. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  1517. await CacheModule.runJob(
  1518. "PUB",
  1519. {
  1520. channel: "longJob.added",
  1521. value: { jobId: this.toString(), userId: session.userId }
  1522. },
  1523. this
  1524. );
  1525. async.waterfall(
  1526. [
  1527. next => {
  1528. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1529. userModel.findOne({ _id: session.userId }, (err, user) => {
  1530. if (user && user.role === "admin") return next(null, true);
  1531. return next(null, false);
  1532. });
  1533. });
  1534. },
  1535. (isAdmin, next) => {
  1536. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 1)` });
  1537. const playlistRegex = /[\\?&]list=([^&#]*)/;
  1538. const channelRegex =
  1539. /\.[\w]+\/(?:(?:channel\/(UC[0-9A-Za-z_-]{21}[AQgw]))|(?:user\/?([\w-]+))|(?:c\/?([\w-]+))|(?:\/?([\w-]+)))/;
  1540. if (playlistRegex.exec(url) || channelRegex.exec(url))
  1541. YouTubeModule.runJob(
  1542. playlistRegex.exec(url) ? "GET_PLAYLIST" : "GET_CHANNEL",
  1543. {
  1544. url,
  1545. musicOnly,
  1546. disableSearch: !isAdmin
  1547. },
  1548. this
  1549. )
  1550. .then(res => {
  1551. if (res.filteredSongs) {
  1552. videosInPlaylistTotal = res.songs.length;
  1553. songsInPlaylistTotal = res.filteredSongs.length;
  1554. } else {
  1555. songsInPlaylistTotal = videosInPlaylistTotal = res.songs.length;
  1556. }
  1557. next(null, res.songs);
  1558. })
  1559. .catch(next);
  1560. else next("Invalid YouTube URL.");
  1561. },
  1562. (youtubeIds, next) => {
  1563. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 2)` });
  1564. let successful = 0;
  1565. let failed = 0;
  1566. let alreadyInPlaylist = 0;
  1567. let alreadyInLikedPlaylist = 0;
  1568. let alreadyInDislikedPlaylist = 0;
  1569. if (youtubeIds.length === 0) next();
  1570. async.eachLimit(
  1571. youtubeIds,
  1572. 1,
  1573. (youtubeId, next) => {
  1574. WSModule.runJob(
  1575. "RUN_ACTION2",
  1576. {
  1577. session,
  1578. namespace: "playlists",
  1579. action: "addSongToPlaylist",
  1580. args: [true, youtubeId, playlistId]
  1581. },
  1582. this
  1583. )
  1584. .then(res => {
  1585. if (res.status === "success") {
  1586. successful += 1;
  1587. addedSongs.push(youtubeId);
  1588. } else failed += 1;
  1589. if (res.message === "That song is already in the playlist") alreadyInPlaylist += 1;
  1590. else if (
  1591. res.message ===
  1592. "That song is already in your Liked Songs playlist. " +
  1593. "A song cannot be in both the Liked Songs playlist" +
  1594. " and the Disliked Songs playlist at the same time."
  1595. )
  1596. alreadyInLikedPlaylist += 1;
  1597. else if (
  1598. res.message ===
  1599. "That song is already in your Disliked Songs playlist. " +
  1600. "A song cannot be in both the Liked Songs playlist " +
  1601. "and the Disliked Songs playlist at the same time."
  1602. )
  1603. alreadyInDislikedPlaylist += 1;
  1604. })
  1605. .catch(() => {
  1606. failed += 1;
  1607. })
  1608. .finally(() => next());
  1609. },
  1610. () => {
  1611. addSongsStats = {
  1612. successful,
  1613. failed,
  1614. alreadyInPlaylist,
  1615. alreadyInLikedPlaylist,
  1616. alreadyInDislikedPlaylist
  1617. };
  1618. next(null);
  1619. }
  1620. );
  1621. },
  1622. next => {
  1623. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 3)` });
  1624. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1625. .then(playlist => next(null, playlist))
  1626. .catch(next);
  1627. },
  1628. (playlist, next) => {
  1629. this.publishProgress({ status: "update", message: `Importing YouTube playlist (stage 4)` });
  1630. if (!playlist) return next("Playlist not found.");
  1631. if (playlist.createdBy !== session.userId)
  1632. return hasPermission("playlists.songs.add", session)
  1633. .then(() => next(null, playlist))
  1634. .catch(() => next("Invalid permissions."));
  1635. return next(null, playlist);
  1636. }
  1637. ],
  1638. async (err, playlist) => {
  1639. if (err) {
  1640. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1641. this.log(
  1642. "ERROR",
  1643. "PLAYLIST_IMPORT",
  1644. `Importing a YouTube playlist to private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1645. );
  1646. this.publishProgress({
  1647. status: "error",
  1648. message: err
  1649. });
  1650. return cb({ status: "error", message: err });
  1651. }
  1652. if (playlist.privacy === "public")
  1653. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1654. userId: session.userId,
  1655. type: "playlist__import_playlist",
  1656. payload: {
  1657. message: `Imported ${addSongsStats.successful} songs to playlist <playlistId>${playlist.displayName}</playlistId>`,
  1658. playlistId
  1659. }
  1660. });
  1661. this.log(
  1662. "SUCCESS",
  1663. "PLAYLIST_IMPORT",
  1664. `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}.`
  1665. );
  1666. this.publishProgress({
  1667. status: "success",
  1668. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`
  1669. });
  1670. return cb({
  1671. status: "success",
  1672. message: `Playlist has been imported. ${addSongsStats.successful} were added successfully, ${addSongsStats.failed} failed (${addSongsStats.alreadyInPlaylist} were already in the playlist)`,
  1673. data: {
  1674. songs: playlist.songs,
  1675. stats: {
  1676. videosInPlaylistTotal,
  1677. songsInPlaylistTotal,
  1678. alreadyInLikedPlaylist: addSongsStats.alreadyInLikedPlaylist,
  1679. alreadyInDislikedPlaylist: addSongsStats.alreadyInDislikedPlaylist
  1680. }
  1681. }
  1682. });
  1683. }
  1684. );
  1685. }),
  1686. /**
  1687. * Removes a song from a private playlist
  1688. *
  1689. * @param {object} session - the session object automatically added by the websocket
  1690. * @param {string} youtubeId - the youtube id of the song we are removing from the private playlist
  1691. * @param {string} playlistId - the id of the playlist we are removing the song from
  1692. * @param {Function} cb - gets called with the result
  1693. */
  1694. removeSongFromPlaylist: isLoginRequired(async function removeSongFromPlaylist(session, youtubeId, playlistId, cb) {
  1695. async.waterfall(
  1696. [
  1697. next => {
  1698. if (!youtubeId || typeof youtubeId !== "string") return next("Invalid song id.");
  1699. if (!playlistId || typeof youtubeId !== "string") return next("Invalid playlist id.");
  1700. return next();
  1701. },
  1702. next => {
  1703. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1704. .then(playlist => {
  1705. if (!playlist) return next("Playlist not found.");
  1706. if (playlist.createdBy !== session.userId)
  1707. return hasPermission("playlists.songs.remove", session)
  1708. .then(() => next(null, playlist))
  1709. .catch(() => next("Invalid permissions."));
  1710. return next(null, playlist);
  1711. })
  1712. .catch(next);
  1713. },
  1714. (playlist, next) => {
  1715. MediaModule.runJob("GET_MEDIA", { youtubeId }, this)
  1716. .then(res =>
  1717. next(null, playlist, {
  1718. _id: res.song._id,
  1719. title: res.song.title,
  1720. thumbnail: res.song.thumbnail,
  1721. artists: res.song.artists,
  1722. youtubeId: res.song.youtubeId
  1723. })
  1724. )
  1725. .catch(next);
  1726. },
  1727. (playlist, newSong, next) => {
  1728. PlaylistsModule.runJob("REMOVE_FROM_PLAYLIST", { playlistId, youtubeId }, this)
  1729. .then(res => {
  1730. const { ratings } = res;
  1731. next(null, playlist, newSong, ratings);
  1732. })
  1733. .catch(next);
  1734. },
  1735. (playlist, newSong, ratings, next) => {
  1736. const { _id, title, artists, thumbnail } = newSong;
  1737. const songName = artists ? `${title} by ${artists.join(", ")}` : title;
  1738. if (playlist.type === "user" && playlist.privacy === "public") {
  1739. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1740. userId: session.userId,
  1741. type: "playlist__remove_song",
  1742. payload: {
  1743. message: `Removed <youtubeId>${songName}</youtubeId> from playlist <playlistId>${playlist.displayName}</playlistId>`,
  1744. thumbnail,
  1745. playlistId,
  1746. youtubeId: newSong.youtubeId
  1747. }
  1748. });
  1749. }
  1750. if (ratings && (playlist.type === "user-liked" || playlist.type === "user-disliked")) {
  1751. const { likes, dislikes } = ratings;
  1752. if (_id) SongsModule.runJob("UPDATE_SONG", { songId: _id });
  1753. if (playlist.type === "user-liked") {
  1754. CacheModule.runJob("PUB", {
  1755. channel: "ratings.unlike",
  1756. value: JSON.stringify({
  1757. youtubeId: newSong.youtubeId,
  1758. userId: session.userId,
  1759. likes,
  1760. dislikes
  1761. })
  1762. });
  1763. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1764. userId: session.userId,
  1765. type: "song__unlike",
  1766. payload: {
  1767. message: `Removed <youtubeId>${title} by ${artists.join(
  1768. ", "
  1769. )}</youtubeId> from your Liked Songs`,
  1770. youtubeId: newSong.youtubeId,
  1771. thumbnail
  1772. }
  1773. });
  1774. } else {
  1775. CacheModule.runJob("PUB", {
  1776. channel: "ratings.undislike",
  1777. value: JSON.stringify({
  1778. youtubeId: newSong.youtubeId,
  1779. userId: session.userId,
  1780. likes,
  1781. dislikes
  1782. })
  1783. });
  1784. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1785. userId: session.userId,
  1786. type: "song__undislike",
  1787. payload: {
  1788. message: `Removed <youtubeId>${title} by ${artists.join(
  1789. ", "
  1790. )}</youtubeId> from your Disliked Songs`,
  1791. youtubeId: newSong.youtubeId,
  1792. thumbnail
  1793. }
  1794. });
  1795. }
  1796. }
  1797. return next(null, playlist);
  1798. }
  1799. ],
  1800. async (err, playlist) => {
  1801. if (err) {
  1802. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1803. this.log(
  1804. "ERROR",
  1805. "PLAYLIST_REMOVE_SONG",
  1806. `Removing song "${youtubeId}" from private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1807. );
  1808. return cb({ status: "error", message: err });
  1809. }
  1810. this.log(
  1811. "SUCCESS",
  1812. "PLAYLIST_REMOVE_SONG",
  1813. `Successfully removed song "${youtubeId}" from private playlist "${playlistId}" for user "${session.userId}".`
  1814. );
  1815. CacheModule.runJob("PUB", {
  1816. channel: "playlist.removeSong",
  1817. value: {
  1818. playlistId: playlist._id,
  1819. youtubeId,
  1820. createdBy: playlist.createdBy,
  1821. privacy: playlist.privacy
  1822. }
  1823. });
  1824. return cb({
  1825. status: "success",
  1826. message: "Song has been successfully removed from playlist",
  1827. data: { songs: playlist.songs }
  1828. });
  1829. }
  1830. );
  1831. }),
  1832. /**
  1833. * Updates the displayName of a private playlist
  1834. *
  1835. * @param {object} session - the session object automatically added by the websocket
  1836. * @param {string} playlistId - the id of the playlist we are updating the displayName for
  1837. * @param {Function} cb - gets called with the result
  1838. */
  1839. updateDisplayName: isLoginRequired(async function updateDisplayName(session, playlistId, displayName, cb) {
  1840. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1841. async.waterfall(
  1842. [
  1843. next => {
  1844. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1845. .then(playlist => next(null, playlist))
  1846. .catch(next);
  1847. },
  1848. (playlist, next) => {
  1849. if (playlist.type === "admin")
  1850. hasPermission("playlists.update.displayName", session)
  1851. .then(() => next())
  1852. .catch(() => next("Invalid permissions."));
  1853. else if (playlist.type !== "user" || playlist.createdBy !== session.userId)
  1854. next("Playlist cannot be modified.");
  1855. else next(null);
  1856. },
  1857. next => {
  1858. playlistModel.updateOne(
  1859. { _id: playlistId },
  1860. { $set: { displayName } },
  1861. { runValidators: true },
  1862. next
  1863. );
  1864. },
  1865. (res, next) => {
  1866. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  1867. .then(playlist => next(null, playlist))
  1868. .catch(next);
  1869. }
  1870. ],
  1871. async (err, playlist) => {
  1872. if (err) {
  1873. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1874. this.log(
  1875. "ERROR",
  1876. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1877. `Updating display name to "${displayName}" for playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1878. );
  1879. return cb({ status: "error", message: err });
  1880. }
  1881. this.log(
  1882. "SUCCESS",
  1883. "PLAYLIST_UPDATE_DISPLAY_NAME",
  1884. `Successfully updated display name to "${displayName}" for playlist "${playlistId}" for user "${session.userId}".`
  1885. );
  1886. CacheModule.runJob("PUB", {
  1887. channel: "playlist.updateDisplayName",
  1888. value: {
  1889. playlistId,
  1890. displayName,
  1891. createdBy: playlist.createdBy,
  1892. privacy: playlist.privacy
  1893. }
  1894. });
  1895. CacheModule.runJob("PUB", {
  1896. channel: "playlist.updated",
  1897. value: { playlistId }
  1898. });
  1899. if (playlist.type !== "admin")
  1900. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1901. userId: session.userId,
  1902. type: "playlist__edit_display_name",
  1903. payload: {
  1904. message: `Changed display name of playlist <playlistId>${displayName}</playlistId>`,
  1905. playlistId
  1906. }
  1907. });
  1908. return cb({
  1909. status: "success",
  1910. message: "Playlist has been successfully updated"
  1911. });
  1912. }
  1913. );
  1914. }),
  1915. /**
  1916. * Removes a user's own modifiable user playlist
  1917. *
  1918. * @param {object} session - the session object automatically added by the websocket
  1919. * @param {string} playlistId - the id of the playlist we are removing
  1920. * @param {Function} cb - gets called with the result
  1921. */
  1922. remove: isLoginRequired(async function remove(session, playlistId, cb) {
  1923. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1924. async.waterfall(
  1925. [
  1926. next => {
  1927. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1928. .then(playlist => next(null, playlist))
  1929. .catch(next);
  1930. },
  1931. (playlist, next) => {
  1932. if (playlist.createdBy !== session.userId) return next("You do not own this playlist.");
  1933. if (playlist.type !== "user") return next("Playlist cannot be removed.");
  1934. return next(null, playlist);
  1935. },
  1936. (playlist, next) => {
  1937. userModel.updateOne(
  1938. { _id: playlist.createdBy },
  1939. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  1940. err => next(err, playlist)
  1941. );
  1942. },
  1943. (playlist, next) => {
  1944. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  1945. .then(() => next(null, playlist))
  1946. .catch(next);
  1947. }
  1948. ],
  1949. async (err, playlist) => {
  1950. if (err) {
  1951. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1952. this.log(
  1953. "ERROR",
  1954. "PLAYLIST_REMOVE",
  1955. `Removing private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  1956. );
  1957. return cb({ status: "error", message: err });
  1958. }
  1959. this.log(
  1960. "SUCCESS",
  1961. "PLAYLIST_REMOVE",
  1962. `Successfully removed private playlist "${playlistId}" for user "${session.userId}".`
  1963. );
  1964. CacheModule.runJob("PUB", {
  1965. channel: "playlist.delete",
  1966. value: {
  1967. createdBy: playlist.createdBy,
  1968. playlistId
  1969. }
  1970. });
  1971. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1972. userId: playlist.createdBy,
  1973. type: "playlist__remove",
  1974. payload: {
  1975. message: `Removed playlist ${playlist.displayName}`
  1976. }
  1977. });
  1978. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  1979. return cb({
  1980. status: "success",
  1981. message: "Playlist successfully removed"
  1982. });
  1983. }
  1984. );
  1985. }),
  1986. /**
  1987. * Removes a user's modifiable user playlist as an admin
  1988. *
  1989. * @param {object} session - the session object automatically added by the websocket
  1990. * @param {string} playlistId - the id of the playlist we are removing
  1991. * @param {Function} cb - gets called with the result
  1992. */
  1993. removeAdmin: useHasPermission("playlists.removeAdmin", async function removeAdmin(session, playlistId, cb) {
  1994. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1995. async.waterfall(
  1996. [
  1997. next => {
  1998. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1999. .then(playlist => next(null, playlist))
  2000. .catch(next);
  2001. },
  2002. (playlist, next) => {
  2003. if (playlist.type !== "user" && playlist.type !== "admin")
  2004. return next("Playlist cannot be removed.");
  2005. return next(null, playlist);
  2006. },
  2007. (playlist, next) => {
  2008. if (playlist.type === "admin") next(null, null);
  2009. else
  2010. userModel.updateOne(
  2011. { _id: playlist.createdBy },
  2012. { $pull: { "preferences.orderOfPlaylists": playlist._id } },
  2013. err => next(err, playlist.createdBy)
  2014. );
  2015. },
  2016. (playlistCreator, next) => {
  2017. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId }, this)
  2018. .then(() => next(null, playlistCreator))
  2019. .catch(next);
  2020. }
  2021. ],
  2022. async (err, playlistCreator) => {
  2023. if (err) {
  2024. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2025. this.log(
  2026. "ERROR",
  2027. "PLAYLIST_REMOVE_ADMIN",
  2028. `Removing playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2029. );
  2030. return cb({ status: "error", message: err });
  2031. }
  2032. this.log(
  2033. "SUCCESS",
  2034. "PLAYLIST_REMOVE_ADMIN",
  2035. `Successfully removed playlist "${playlistId}" for user "${session.userId}".`
  2036. );
  2037. CacheModule.runJob("PUB", {
  2038. channel: "playlist.delete",
  2039. value: {
  2040. createdBy: playlistCreator,
  2041. playlistId
  2042. }
  2043. });
  2044. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "playlistId", playlistId });
  2045. return cb({
  2046. status: "success",
  2047. message: "Playlist successfully removed"
  2048. });
  2049. }
  2050. );
  2051. }),
  2052. /**
  2053. * Updates the privacy of a private playlist
  2054. *
  2055. * @param {object} session - the session object automatically added by the websocket
  2056. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  2057. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  2058. * @param {Function} cb - gets called with the result
  2059. */
  2060. updatePrivacy: isLoginRequired(async function updatePrivacy(session, playlistId, privacy, cb) {
  2061. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  2062. async.waterfall(
  2063. [
  2064. next => {
  2065. playlistModel.updateOne(
  2066. { _id: playlistId, createdBy: session.userId },
  2067. { $set: { privacy } },
  2068. { runValidators: true },
  2069. next
  2070. );
  2071. },
  2072. (res, next) => {
  2073. if (res.n === 0) next("No user playlist found with that id and owned by you.");
  2074. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  2075. else {
  2076. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  2077. .then(playlist => next(null, playlist))
  2078. .catch(next);
  2079. }
  2080. }
  2081. ],
  2082. async (err, playlist) => {
  2083. if (err) {
  2084. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2085. this.log(
  2086. "ERROR",
  2087. "PLAYLIST_UPDATE_PRIVACY",
  2088. `Updating privacy to "${privacy}" for private playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2089. );
  2090. return cb({ status: "error", message: err });
  2091. }
  2092. this.log(
  2093. "SUCCESS",
  2094. "PLAYLIST_UPDATE_PRIVACY",
  2095. `Successfully updated privacy to "${privacy}" for private playlist "${playlistId}" for user "${session.userId}".`
  2096. );
  2097. CacheModule.runJob("PUB", {
  2098. channel: "playlist.updatePrivacy",
  2099. value: {
  2100. createdBy: playlist.createdBy,
  2101. playlist
  2102. }
  2103. });
  2104. CacheModule.runJob("PUB", {
  2105. channel: "playlist.updated",
  2106. value: { playlistId }
  2107. });
  2108. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2109. userId: session.userId,
  2110. type: "playlist__edit_privacy",
  2111. payload: {
  2112. message: `Changed privacy of playlist <playlistId>${playlist.displayName}</playlistId> to ${privacy}`,
  2113. playlistId
  2114. }
  2115. });
  2116. return cb({
  2117. status: "success",
  2118. message: "Playlist has been successfully updated"
  2119. });
  2120. }
  2121. );
  2122. }),
  2123. /**
  2124. * Updates the privacy of a playlist
  2125. *
  2126. * @param {object} session - the session object automatically added by the websocket
  2127. * @param {string} playlistId - the id of the playlist we are updating the privacy for
  2128. * @param {string} privacy - what the new privacy of the playlist should be e.g. public
  2129. * @param {Function} cb - gets called with the result
  2130. */
  2131. updatePrivacyAdmin: useHasPermission(
  2132. "playlists.update.privacy",
  2133. async function updatePrivacyAdmin(session, playlistId, privacy, cb) {
  2134. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  2135. async.waterfall(
  2136. [
  2137. next => {
  2138. playlistModel.updateOne(
  2139. { _id: playlistId },
  2140. { $set: { privacy } },
  2141. { runValidators: true },
  2142. next
  2143. );
  2144. },
  2145. (res, next) => {
  2146. if (res.n === 0) next("No playlist found with that id.");
  2147. else if (res.nModified === 0) next(`Nothing changed, the playlist was already ${privacy}.`);
  2148. else {
  2149. PlaylistsModule.runJob("UPDATE_PLAYLIST", { playlistId }, this)
  2150. .then(playlist => next(null, playlist))
  2151. .catch(next);
  2152. }
  2153. }
  2154. ],
  2155. async (err, playlist) => {
  2156. if (err) {
  2157. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2158. this.log(
  2159. "ERROR",
  2160. "PLAYLIST_UPDATE_PRIVACY_ADMIN",
  2161. `Updating privacy to "${privacy}" for playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2162. );
  2163. return cb({ status: "error", message: err });
  2164. }
  2165. this.log(
  2166. "SUCCESS",
  2167. "PLAYLIST_UPDATE_PRIVACY_ADMIn",
  2168. `Successfully updated privacy to "${privacy}" for playlist "${playlistId}" for user "${session.userId}".`
  2169. );
  2170. if (playlist.type === "user") {
  2171. CacheModule.runJob("PUB", {
  2172. channel: "playlist.updatePrivacy",
  2173. value: {
  2174. userId: playlist.createdBy,
  2175. playlist
  2176. }
  2177. });
  2178. }
  2179. CacheModule.runJob("PUB", {
  2180. channel: "playlist.updated",
  2181. value: { playlistId }
  2182. });
  2183. return cb({
  2184. status: "success",
  2185. message: "Playlist has been successfully updated"
  2186. });
  2187. }
  2188. );
  2189. }
  2190. ),
  2191. /**
  2192. * Deletes all orphaned station playlists
  2193. *
  2194. * @param {object} session - the session object automatically added by socket.io
  2195. * @param {Function} cb - gets called with the result
  2196. */
  2197. deleteOrphanedStationPlaylists: useHasPermission("playlists.deleteOrphaned", async function index(session, cb) {
  2198. this.keepLongJob();
  2199. this.publishProgress({
  2200. status: "started",
  2201. title: "Delete orphaned station playlists",
  2202. message: "Deleting orphaned station playlists.",
  2203. id: this.toString()
  2204. });
  2205. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2206. await CacheModule.runJob(
  2207. "PUB",
  2208. {
  2209. channel: "longJob.added",
  2210. value: { jobId: this.toString(), userId: session.userId }
  2211. },
  2212. this
  2213. );
  2214. async.waterfall(
  2215. [
  2216. next => {
  2217. PlaylistsModule.runJob("DELETE_ORPHANED_STATION_PLAYLISTS", {}, this)
  2218. .then(() => next())
  2219. .catch(next);
  2220. }
  2221. ],
  2222. async err => {
  2223. if (err) {
  2224. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2225. this.log(
  2226. "ERROR",
  2227. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  2228. `Deleting orphaned station playlists failed. "${err}"`
  2229. );
  2230. this.publishProgress({
  2231. status: "error",
  2232. message: err
  2233. });
  2234. return cb({ status: "error", message: err });
  2235. }
  2236. this.log(
  2237. "SUCCESS",
  2238. "PLAYLISTS_DELETE_ORPHANED_STATION_PLAYLISTS",
  2239. "Deleting orphaned station playlists successful."
  2240. );
  2241. this.publishProgress({
  2242. status: "success",
  2243. message: "Successfully deleted orphaned station playlists."
  2244. });
  2245. return cb({ status: "success", message: "Successfully deleted orphaned station playlists." });
  2246. }
  2247. );
  2248. }),
  2249. /**
  2250. * Deletes all orphaned genre playlists
  2251. *
  2252. * @param {object} session - the session object automatically added by socket.io
  2253. * @param {Function} cb - gets called with the result
  2254. */
  2255. deleteOrphanedGenrePlaylists: useHasPermission("playlists.deleteOrphaned", async function index(session, cb) {
  2256. this.keepLongJob();
  2257. this.publishProgress({
  2258. status: "started",
  2259. title: "Delete orphaned genre playlists",
  2260. message: "Deleting orphaned genre playlists.",
  2261. id: this.toString()
  2262. });
  2263. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2264. await CacheModule.runJob(
  2265. "PUB",
  2266. {
  2267. channel: "longJob.added",
  2268. value: { jobId: this.toString(), userId: session.userId }
  2269. },
  2270. this
  2271. );
  2272. async.waterfall(
  2273. [
  2274. next => {
  2275. PlaylistsModule.runJob("DELETE_ORPHANED_GENRE_PLAYLISTS", {}, this)
  2276. .then(() => next())
  2277. .catch(next);
  2278. }
  2279. ],
  2280. async err => {
  2281. if (err) {
  2282. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2283. this.log(
  2284. "ERROR",
  2285. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  2286. `Deleting orphaned genre playlists failed. "${err}"`
  2287. );
  2288. this.publishProgress({
  2289. status: "error",
  2290. message: err
  2291. });
  2292. return cb({ status: "error", message: err });
  2293. }
  2294. this.log(
  2295. "SUCCESS",
  2296. "PLAYLISTS_DELETE_ORPHANED_GENRE_PLAYLISTS",
  2297. "Deleting orphaned genre playlists successful."
  2298. );
  2299. this.publishProgress({
  2300. status: "success",
  2301. message: "Successfully deleted orphaned genre playlists."
  2302. });
  2303. return cb({ status: "success", message: "Successfully deleted orphaned genre playlists." });
  2304. }
  2305. );
  2306. }),
  2307. /**
  2308. * Requests orpahned playlist songs
  2309. *
  2310. * @param {object} session - the session object automatically added by socket.io
  2311. * @param {Function} cb - gets called with the result
  2312. */
  2313. requestOrphanedPlaylistSongs: useHasPermission(
  2314. "playlists.requestOrphanedPlaylistSongs",
  2315. async function index(session, cb) {
  2316. this.keepLongJob();
  2317. this.publishProgress({
  2318. status: "started",
  2319. title: "Request orphaned playlist songs",
  2320. message: "Requesting orphaned playlist songs.",
  2321. id: this.toString()
  2322. });
  2323. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2324. await CacheModule.runJob(
  2325. "PUB",
  2326. {
  2327. channel: "longJob.added",
  2328. value: { jobId: this.toString(), userId: session.userId }
  2329. },
  2330. this
  2331. );
  2332. async.waterfall(
  2333. [
  2334. next => {
  2335. SongsModule.runJob("REQUEST_ORPHANED_PLAYLIST_SONGS", {}, this)
  2336. .then(() => next())
  2337. .catch(next);
  2338. }
  2339. ],
  2340. async err => {
  2341. if (err) {
  2342. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2343. this.log(
  2344. "ERROR",
  2345. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  2346. `Requesting orphaned playlist songs failed. "${err}"`
  2347. );
  2348. this.publishProgress({
  2349. status: "error",
  2350. message: err
  2351. });
  2352. return cb({ status: "error", message: err });
  2353. }
  2354. this.log(
  2355. "SUCCESS",
  2356. "REQUEST_ORPHANED_PLAYLIST_SONGS",
  2357. "Requesting orphaned playlist songs was successful."
  2358. );
  2359. this.publishProgress({
  2360. status: "success",
  2361. message: "Successfully requested orphaned playlist songs."
  2362. });
  2363. return cb({ status: "success", message: "Successfully requested orphaned playlist songs." });
  2364. }
  2365. );
  2366. }
  2367. ),
  2368. /**
  2369. * Clears and refills a station playlist
  2370. *
  2371. * @param {object} session - the session object automatically added by socket.io
  2372. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  2373. * @param {Function} cb - gets called with the result
  2374. */
  2375. clearAndRefillStationPlaylist: useHasPermission(
  2376. "playlists.clearAndRefill",
  2377. async function index(session, playlistId, cb) {
  2378. async.waterfall(
  2379. [
  2380. next => {
  2381. if (!playlistId) next("Please specify a playlist id");
  2382. else {
  2383. PlaylistsModule.runJob("CLEAR_AND_REFILL_STATION_PLAYLIST", { playlistId }, this)
  2384. .then(() => {
  2385. next();
  2386. })
  2387. .catch(err => {
  2388. next(err);
  2389. });
  2390. }
  2391. }
  2392. ],
  2393. async err => {
  2394. if (err) {
  2395. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2396. this.log(
  2397. "ERROR",
  2398. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  2399. `Clearing and refilling station playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2400. );
  2401. return cb({ status: "error", message: err });
  2402. }
  2403. this.log(
  2404. "SUCCESS",
  2405. "PLAYLIST_CLEAR_AND_REFILL_STATION_PLAYLIST",
  2406. `Successfully cleared and refilled station playlist "${playlistId}" for user "${session.userId}".`
  2407. );
  2408. return cb({
  2409. status: "success",
  2410. message: "Playlist has been successfully cleared and refilled"
  2411. });
  2412. }
  2413. );
  2414. }
  2415. ),
  2416. /**
  2417. * Clears and refills a genre playlist
  2418. *
  2419. * @param {object} session - the session object automatically added by socket.io
  2420. * @param {string} playlistId - the id of the playlist we are clearing and refilling
  2421. * @param {Function} cb - gets called with the result
  2422. */
  2423. clearAndRefillGenrePlaylist: useHasPermission(
  2424. "playlists.clearAndRefill",
  2425. async function index(session, playlistId, cb) {
  2426. async.waterfall(
  2427. [
  2428. next => {
  2429. if (!playlistId) next("Please specify a playlist id");
  2430. else {
  2431. PlaylistsModule.runJob("CLEAR_AND_REFILL_GENRE_PLAYLIST", { playlistId }, this)
  2432. .then(() => {
  2433. next();
  2434. })
  2435. .catch(err => {
  2436. next(err);
  2437. });
  2438. }
  2439. }
  2440. ],
  2441. async err => {
  2442. if (err) {
  2443. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2444. this.log(
  2445. "ERROR",
  2446. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2447. `Clearing and refilling genre playlist "${playlistId}" failed for user "${session.userId}". "${err}"`
  2448. );
  2449. return cb({ status: "error", message: err });
  2450. }
  2451. this.log(
  2452. "SUCCESS",
  2453. "PLAYLIST_CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2454. `Successfully cleared and refilled genre playlist "${playlistId}" for user "${session.userId}".`
  2455. );
  2456. return cb({
  2457. status: "success",
  2458. message: "Playlist has been successfully cleared and refilled"
  2459. });
  2460. }
  2461. );
  2462. }
  2463. ),
  2464. /**
  2465. * Clears and refills all station playlists
  2466. *
  2467. * @param {object} session - the session object automatically added by socket.io
  2468. * @param {Function} cb - gets called with the result
  2469. */
  2470. clearAndRefillAllStationPlaylists: useHasPermission(
  2471. "playlists.clearAndRefillAll",
  2472. async function index(session, cb) {
  2473. this.keepLongJob();
  2474. this.publishProgress({
  2475. status: "started",
  2476. title: "Clear and refill all station playlists",
  2477. message: "Clearing and refilling all station playlists.",
  2478. id: this.toString()
  2479. });
  2480. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2481. await CacheModule.runJob(
  2482. "PUB",
  2483. {
  2484. channel: "longJob.added",
  2485. value: { jobId: this.toString(), userId: session.userId }
  2486. },
  2487. this
  2488. );
  2489. async.waterfall(
  2490. [
  2491. next => {
  2492. PlaylistsModule.runJob("GET_ALL_STATION_PLAYLISTS", {}, this)
  2493. .then(response => {
  2494. next(null, response.playlists);
  2495. })
  2496. .catch(err => {
  2497. next(err);
  2498. });
  2499. },
  2500. (playlists, next) => {
  2501. async.eachLimit(
  2502. playlists,
  2503. 1,
  2504. (playlist, next) => {
  2505. this.publishProgress({
  2506. status: "update",
  2507. message: `Clearing and refilling "${playlist._id}"`
  2508. });
  2509. PlaylistsModule.runJob(
  2510. "CLEAR_AND_REFILL_STATION_PLAYLIST",
  2511. { playlistId: playlist._id },
  2512. this
  2513. )
  2514. .then(() => {
  2515. next();
  2516. })
  2517. .catch(err => {
  2518. next(err);
  2519. });
  2520. },
  2521. next
  2522. );
  2523. }
  2524. ],
  2525. async err => {
  2526. if (err) {
  2527. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2528. this.log(
  2529. "ERROR",
  2530. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2531. `Clearing and refilling all station playlists failed for user "${session.userId}". "${err}"`
  2532. );
  2533. this.publishProgress({
  2534. status: "error",
  2535. message: err
  2536. });
  2537. return cb({ status: "error", message: err });
  2538. }
  2539. this.log(
  2540. "SUCCESS",
  2541. "PLAYLIST_CLEAR_AND_REFILL_ALL_STATION_PLAYLISTS",
  2542. `Successfully cleared and refilled all station playlists for user "${session.userId}".`
  2543. );
  2544. this.publishProgress({
  2545. status: "success",
  2546. message: "Playlists have been successfully cleared and refilled."
  2547. });
  2548. return cb({
  2549. status: "success",
  2550. message: "Playlists have been successfully cleared and refilled"
  2551. });
  2552. }
  2553. );
  2554. }
  2555. ),
  2556. /**
  2557. * Clears and refills all genre playlists
  2558. *
  2559. * @param {object} session - the session object automatically added by socket.io
  2560. * @param {Function} cb - gets called with the result
  2561. */
  2562. clearAndRefillAllGenrePlaylists: useHasPermission("playlists.clearAndRefillAll", async function index(session, cb) {
  2563. this.keepLongJob();
  2564. this.publishProgress({
  2565. status: "started",
  2566. title: "Clear and refill all genre playlists",
  2567. message: "Clearing and refilling all genre playlists.",
  2568. id: this.toString()
  2569. });
  2570. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2571. await CacheModule.runJob(
  2572. "PUB",
  2573. {
  2574. channel: "longJob.added",
  2575. value: { jobId: this.toString(), userId: session.userId }
  2576. },
  2577. this
  2578. );
  2579. async.waterfall(
  2580. [
  2581. next => {
  2582. PlaylistsModule.runJob("GET_ALL_GENRE_PLAYLISTS", {}, this)
  2583. .then(response => {
  2584. next(null, response.playlists);
  2585. })
  2586. .catch(err => {
  2587. next(err);
  2588. });
  2589. },
  2590. (playlists, next) => {
  2591. async.eachLimit(
  2592. playlists,
  2593. 1,
  2594. (playlist, next) => {
  2595. this.publishProgress({
  2596. status: "update",
  2597. message: `Clearing and refilling "${playlist._id}"`
  2598. });
  2599. PlaylistsModule.runJob(
  2600. "CLEAR_AND_REFILL_GENRE_PLAYLIST",
  2601. { playlistId: playlist._id },
  2602. this
  2603. )
  2604. .then(() => {
  2605. next();
  2606. })
  2607. .catch(err => {
  2608. next(err);
  2609. });
  2610. },
  2611. next
  2612. );
  2613. }
  2614. ],
  2615. async err => {
  2616. if (err) {
  2617. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2618. this.log(
  2619. "ERROR",
  2620. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2621. `Clearing and refilling all genre playlists failed for user "${session.userId}". "${err}"`
  2622. );
  2623. this.publishProgress({
  2624. status: "error",
  2625. message: err
  2626. });
  2627. return cb({ status: "error", message: err });
  2628. }
  2629. this.log(
  2630. "SUCCESS",
  2631. "PLAYLIST_CLEAR_AND_REFILL_ALL_GENRE_PLAYLISTS",
  2632. `Successfully cleared and refilled all genre playlists for user "${session.userId}".`
  2633. );
  2634. this.publishProgress({
  2635. status: "success",
  2636. message: "Playlists have been successfully cleared and refilled."
  2637. });
  2638. return cb({
  2639. status: "success",
  2640. message: "Playlists have been successfully cleared and refilled"
  2641. });
  2642. }
  2643. );
  2644. }),
  2645. /**
  2646. * Create missing genre playlists
  2647. *
  2648. * @param {object} session - the session object automatically added by socket.io
  2649. * @param {Function} cb - gets called with the result
  2650. */
  2651. createMissingGenrePlaylists: useHasPermission("playlists.createMissing", async function index(session, cb) {
  2652. this.keepLongJob();
  2653. this.publishProgress({
  2654. status: "started",
  2655. title: "Create missing genre playlists",
  2656. message: "Creating missing genre playlists.",
  2657. id: this.toString()
  2658. });
  2659. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2660. await CacheModule.runJob(
  2661. "PUB",
  2662. {
  2663. channel: "longJob.added",
  2664. value: { jobId: this.toString(), userId: session.userId }
  2665. },
  2666. this
  2667. );
  2668. async.waterfall(
  2669. [
  2670. next => {
  2671. PlaylistsModule.runJob("CREATE_MISSING_GENRE_PLAYLISTS", this)
  2672. .then(() => {
  2673. next();
  2674. })
  2675. .catch(err => {
  2676. next(err);
  2677. });
  2678. }
  2679. ],
  2680. async err => {
  2681. if (err) {
  2682. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2683. this.log(
  2684. "ERROR",
  2685. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2686. `Creating missing genre playlists failed for user "${session.userId}". "${err}"`
  2687. );
  2688. this.publishProgress({
  2689. status: "error",
  2690. message: err
  2691. });
  2692. return cb({ status: "error", message: err });
  2693. }
  2694. this.log(
  2695. "SUCCESS",
  2696. "PLAYLIST_CREATE_MISSING_GENRE_PLAYLISTS",
  2697. `Successfully created missing genre playlists for user "${session.userId}".`
  2698. );
  2699. this.publishProgress({
  2700. status: "success",
  2701. message: "Missing genre playlists have been successfully created."
  2702. });
  2703. return cb({
  2704. status: "success",
  2705. message: "Missing genre playlists have been successfully created"
  2706. });
  2707. }
  2708. );
  2709. })
  2710. };