playlists.js 82 KB

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