playlists.js 100 KB

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