stations.js 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002
  1. import async from "async";
  2. import mongoose from "mongoose";
  3. import { isLoginRequired, isOwnerRequired, isAdminRequired } from "./hooks";
  4. import moduleManager from "../../index";
  5. const DBModule = moduleManager.modules.db;
  6. const UtilsModule = moduleManager.modules.utils;
  7. const WSModule = moduleManager.modules.ws;
  8. const SongsModule = moduleManager.modules.songs;
  9. const PlaylistsModule = moduleManager.modules.playlists;
  10. const CacheModule = moduleManager.modules.cache;
  11. const NotificationsModule = moduleManager.modules.notifications;
  12. const StationsModule = moduleManager.modules.stations;
  13. const ActivitiesModule = moduleManager.modules.activities;
  14. CacheModule.runJob("SUB", {
  15. channel: "station.updateUsers",
  16. cb: ({ stationId, usersPerStation }) => {
  17. WSModule.runJob("EMIT_TO_ROOM", {
  18. room: `station.${stationId}`,
  19. args: ["event:users.updated", { data: { users: usersPerStation } }]
  20. });
  21. }
  22. });
  23. CacheModule.runJob("SUB", {
  24. channel: "station.updateUserCount",
  25. cb: ({ stationId, usersPerStationCount }) => {
  26. const count = usersPerStationCount || 0;
  27. WSModule.runJob("EMIT_TO_ROOM", {
  28. room: `station.${stationId}`,
  29. args: ["event:userCount.updated", { data: { userCount: count } }]
  30. });
  31. StationsModule.runJob("GET_STATION", { stationId }).then(async station => {
  32. if (station.privacy === "public")
  33. WSModule.runJob("EMIT_TO_ROOM", {
  34. room: "home",
  35. args: ["event:userCount.updated", { data: { stationId, userCount: count } }]
  36. });
  37. else {
  38. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", {
  39. room: "home"
  40. });
  41. sockets.forEach(async socketId => {
  42. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this);
  43. const { session } = socket;
  44. if (session.sessionId) {
  45. CacheModule.runJob("HGET", {
  46. table: "sessions",
  47. key: session.sessionId
  48. }).then(session => {
  49. if (session)
  50. DBModule.runJob(
  51. "GET_MODEL",
  52. {
  53. modelName: "user"
  54. },
  55. this
  56. ).then(userModel =>
  57. userModel.findOne({ _id: session.userId }, (err, user) => {
  58. if (user.role === "admin")
  59. socket.dispatch("event:userCount.updated", { data: { stationId, count } });
  60. else if (station.type === "community" && station.owner === session.userId)
  61. socket.dispatch("event:userCount.updated", { data: { stationId, count } });
  62. })
  63. );
  64. });
  65. }
  66. });
  67. }
  68. });
  69. }
  70. });
  71. CacheModule.runJob("SUB", {
  72. channel: "station.queueLockToggled",
  73. cb: data => {
  74. const { stationId, locked } = data;
  75. WSModule.runJob("EMIT_TO_ROOM", {
  76. room: `station.${stationId}`,
  77. args: ["event:queueLockToggled", { data: { locked } }]
  78. });
  79. WSModule.runJob("EMIT_TO_ROOM", {
  80. room: `manage-station.${stationId}`,
  81. args: ["event:queueLockToggled", { data: { stationId, locked } }]
  82. });
  83. }
  84. });
  85. CacheModule.runJob("SUB", {
  86. channel: "station.updatePartyMode",
  87. cb: data => {
  88. const { stationId, partyMode } = data;
  89. StationsModule.runJob("GET_STATION", { stationId }).then(station => {
  90. WSModule.runJob("EMIT_TO_ROOM", {
  91. room: `station.${stationId}`,
  92. args: ["event:partyMode.updated", { data: { partyMode } }]
  93. });
  94. WSModule.runJob("EMIT_TO_ROOM", {
  95. room: `manage-station.${stationId}`,
  96. args: ["event:partyMode.updated", { data: { stationId, partyMode } }]
  97. });
  98. StationsModule.runJob("GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION", {
  99. room: `home`,
  100. station
  101. }).then(response => {
  102. const { socketsThatCan } = response;
  103. socketsThatCan.forEach(socket => {
  104. socket.dispatch("event:station.updatePartyMode", { data: { stationId, partyMode } });
  105. });
  106. });
  107. });
  108. }
  109. });
  110. CacheModule.runJob("SUB", {
  111. channel: "station.newPlayMode",
  112. cb: data => {
  113. const { stationId, playMode } = data;
  114. WSModule.runJob("EMIT_TO_ROOM", {
  115. room: `station.${stationId}`,
  116. args: ["event:playMode.updated", { data: { playMode } }]
  117. });
  118. WSModule.runJob("EMIT_TO_ROOM", {
  119. room: `manage-station.${stationId}`,
  120. args: ["event:playMode.updated", { data: { stationId, playMode } }]
  121. });
  122. }
  123. });
  124. // CacheModule.runJob("SUB", {
  125. // channel: "privatePlaylist.selected",
  126. // cb: data => {
  127. // WSModule.runJob("EMIT_TO_ROOM", {
  128. // room: `station.${data.stationId}`,
  129. // args: ["event:privatePlaylist.selected", {data: {playlistId: data.playlistId}}]
  130. // });
  131. // }
  132. // });
  133. // CacheModule.runJob("SUB", {
  134. // channel: "privatePlaylist.deselected",
  135. // cb: data => {
  136. // WSModule.runJob("EMIT_TO_ROOM", {
  137. // room: `station.${data.stationId}`,
  138. // args: ["event:privatePlaylist.deselected"]
  139. // });
  140. // }
  141. // });
  142. CacheModule.runJob("SUB", {
  143. channel: "station.includedPlaylist",
  144. cb: data => {
  145. const { stationId, playlistId } = data;
  146. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }).then(playlist => {
  147. WSModule.runJob("EMIT_TO_ROOM", {
  148. room: `station.${stationId}`,
  149. args: ["event:station.includedPlaylist", { data: { stationId, playlist } }]
  150. });
  151. WSModule.runJob("EMIT_TO_ROOM", {
  152. room: `manage-station.${stationId}`,
  153. args: ["event:station.includedPlaylist", { data: { stationId, playlist } }]
  154. });
  155. });
  156. }
  157. });
  158. CacheModule.runJob("SUB", {
  159. channel: "station.excludedPlaylist",
  160. cb: data => {
  161. const { stationId, playlistId } = data;
  162. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }).then(playlist => {
  163. WSModule.runJob("EMIT_TO_ROOM", {
  164. room: `station.${stationId}`,
  165. args: ["event:station.excludedPlaylist", { data: { stationId, playlist } }]
  166. });
  167. WSModule.runJob("EMIT_TO_ROOM", {
  168. room: `manage-station.${stationId}`,
  169. args: ["event:station.excludedPlaylist", { data: { stationId, playlist } }]
  170. });
  171. });
  172. }
  173. });
  174. CacheModule.runJob("SUB", {
  175. channel: "station.removedIncludedPlaylist",
  176. cb: data => {
  177. const { stationId, playlistId } = data;
  178. WSModule.runJob("EMIT_TO_ROOM", {
  179. room: `station.${stationId}`,
  180. args: ["event:station.removedIncludedPlaylist", { data: { stationId, playlistId } }]
  181. });
  182. WSModule.runJob("EMIT_TO_ROOM", {
  183. room: `manage-station.${stationId}`,
  184. args: ["event:station.removedIncludedPlaylist", { data: { stationId, playlistId } }]
  185. });
  186. }
  187. });
  188. CacheModule.runJob("SUB", {
  189. channel: "station.removedExcludedPlaylist",
  190. cb: data => {
  191. const { stationId, playlistId } = data;
  192. WSModule.runJob("EMIT_TO_ROOM", {
  193. room: `station.${stationId}`,
  194. args: ["event:station.removedExcludedPlaylist", { data: { stationId, playlistId } }]
  195. });
  196. WSModule.runJob("EMIT_TO_ROOM", {
  197. room: `manage-station.${stationId}`,
  198. args: ["event:station.removedExcludedPlaylist", { data: { stationId, playlistId } }]
  199. });
  200. }
  201. });
  202. CacheModule.runJob("SUB", {
  203. channel: "station.pause",
  204. cb: stationId => {
  205. StationsModule.runJob("GET_STATION", { stationId }).then(station => {
  206. WSModule.runJob("EMIT_TO_ROOM", {
  207. room: `station.${stationId}`,
  208. args: ["event:stations.pause", { data: { pausedAt: station.pausedAt } }]
  209. });
  210. WSModule.runJob("EMIT_TO_ROOM", {
  211. room: `manage-station.${stationId}`,
  212. args: ["event:stations.pause", { data: { stationId, pausedAt: station.pausedAt } }]
  213. });
  214. StationsModule.runJob("GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION", {
  215. room: `home`,
  216. station
  217. }).then(response => {
  218. const { socketsThatCan } = response;
  219. socketsThatCan.forEach(socket => {
  220. socket.dispatch("event:station.pause", { data: { stationId } });
  221. });
  222. });
  223. });
  224. }
  225. });
  226. CacheModule.runJob("SUB", {
  227. channel: "station.resume",
  228. cb: stationId => {
  229. StationsModule.runJob("GET_STATION", { stationId }).then(station => {
  230. WSModule.runJob("EMIT_TO_ROOM", {
  231. room: `station.${stationId}`,
  232. args: ["event:stations.resume", { data: { timePaused: station.timePaused } }]
  233. });
  234. WSModule.runJob("EMIT_TO_ROOM", {
  235. room: `manage-station.${stationId}`,
  236. args: ["event:stations.resume", { data: { stationId, timePaused: station.timePaused } }]
  237. });
  238. StationsModule.runJob("GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION", {
  239. room: `home`,
  240. station
  241. })
  242. .then(response => {
  243. const { socketsThatCan } = response;
  244. socketsThatCan.forEach(socket => {
  245. socket.dispatch("event:station.resume", { data: { stationId } });
  246. });
  247. })
  248. .catch(console.log);
  249. });
  250. }
  251. });
  252. CacheModule.runJob("SUB", {
  253. channel: "station.privacyUpdate",
  254. cb: response => {
  255. const { stationId, previousPrivacy } = response;
  256. StationsModule.runJob("GET_STATION", { stationId }).then(station => {
  257. if (previousPrivacy !== station.privacy) {
  258. if (station.privacy === "public") {
  259. // Station became public
  260. WSModule.runJob("EMIT_TO_ROOM", {
  261. room: "home",
  262. args: ["event:stations.created", { data: { station } }]
  263. });
  264. } else if (previousPrivacy === "public") {
  265. // Station became hidden
  266. StationsModule.runJob("GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION", {
  267. room: `home`,
  268. station
  269. }).then(response => {
  270. const { socketsThatCan, socketsThatCannot } = response;
  271. socketsThatCan.forEach(socket => {
  272. socket.dispatch("event:station.updatePrivacy", {
  273. data: { stationId, privacy: station.privacy }
  274. });
  275. });
  276. socketsThatCannot.forEach(socket => {
  277. socket.dispatch("event:station.removed", { data: { stationId } });
  278. });
  279. });
  280. } else {
  281. // Station was hidden and is still hidden
  282. StationsModule.runJob("GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION", {
  283. room: `home`,
  284. station
  285. }).then(response => {
  286. const { socketsThatCan } = response;
  287. socketsThatCan.forEach(socket => {
  288. socket.dispatch("event:station.updatePrivacy", {
  289. data: { stationId, privacy: station.privacy }
  290. });
  291. });
  292. });
  293. }
  294. }
  295. WSModule.runJob("EMIT_TO_ROOM", {
  296. room: `station.${stationId}`,
  297. args: ["event:station.updatePrivacy", { data: { privacy: station.privacy } }]
  298. });
  299. WSModule.runJob("EMIT_TO_ROOM", {
  300. room: `manage-station.${stationId}`,
  301. args: ["event:station.updatePrivacy", { data: { stationId, privacy: station.privacy } }]
  302. });
  303. });
  304. }
  305. });
  306. CacheModule.runJob("SUB", {
  307. channel: "station.nameUpdate",
  308. cb: res => {
  309. const { stationId, name } = res;
  310. StationsModule.runJob("GET_STATION", { stationId }).then(station => {
  311. StationsModule.runJob("GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION", {
  312. room: `home`,
  313. station
  314. }).then(response => {
  315. const { socketsThatCan } = response;
  316. socketsThatCan.forEach(socket =>
  317. socket.dispatch("event:station.updateName", { data: { stationId, name } })
  318. );
  319. });
  320. });
  321. WSModule.runJob("EMIT_TO_ROOM", {
  322. room: `station.${stationId}`,
  323. args: ["event:station.updateName", { data: { stationId, name } }]
  324. });
  325. WSModule.runJob("EMIT_TO_ROOM", {
  326. room: `manage-station.${stationId}`,
  327. args: ["event:station.updateName", { data: { stationId, name } }]
  328. });
  329. }
  330. });
  331. CacheModule.runJob("SUB", {
  332. channel: "station.displayNameUpdate",
  333. cb: response => {
  334. const { stationId, displayName } = response;
  335. StationsModule.runJob("GET_STATION", { stationId }).then(station =>
  336. StationsModule.runJob("GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION", {
  337. room: `home`,
  338. station
  339. }).then(response => {
  340. const { socketsThatCan } = response;
  341. socketsThatCan.forEach(socket =>
  342. socket.dispatch("event:station.updateDisplayName", { data: { stationId, displayName } })
  343. );
  344. })
  345. );
  346. WSModule.runJob("EMIT_TO_ROOM", {
  347. room: `station.${stationId}`,
  348. args: ["event:station.updateDisplayName", { data: { stationId, displayName } }]
  349. });
  350. WSModule.runJob("EMIT_TO_ROOM", {
  351. room: `manage-station.${stationId}`,
  352. args: ["event:station.updateDisplayName", { data: { stationId, displayName } }]
  353. });
  354. }
  355. });
  356. CacheModule.runJob("SUB", {
  357. channel: "station.descriptionUpdate",
  358. cb: response => {
  359. const { stationId, description } = response;
  360. StationsModule.runJob("GET_STATION", { stationId }).then(station =>
  361. StationsModule.runJob("GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION", {
  362. room: `home`,
  363. station
  364. }).then(response => {
  365. const { socketsThatCan } = response;
  366. socketsThatCan.forEach(socket =>
  367. socket.dispatch("event:station.updateDescription", { data: { stationId, description } })
  368. );
  369. })
  370. );
  371. WSModule.runJob("EMIT_TO_ROOM", {
  372. room: `station.${stationId}`,
  373. args: ["event:station.updateDescription", { data: { stationId, description } }]
  374. });
  375. WSModule.runJob("EMIT_TO_ROOM", {
  376. room: `manage-station.${stationId}`,
  377. args: ["event:station.updateDescription", { data: { stationId, description } }]
  378. });
  379. }
  380. });
  381. CacheModule.runJob("SUB", {
  382. channel: "station.themeUpdate",
  383. cb: res => {
  384. const { stationId } = res;
  385. StationsModule.runJob("GET_STATION", { stationId }).then(station => {
  386. WSModule.runJob("EMIT_TO_ROOM", {
  387. room: `station.${stationId}`,
  388. args: ["event:station.themeUpdated", { data: { theme: station.theme } }]
  389. });
  390. WSModule.runJob("EMIT_TO_ROOM", {
  391. room: `manage-station.${stationId}`,
  392. args: ["event:station.themeUpdated", { data: { stationId, theme: station.theme } }]
  393. });
  394. StationsModule.runJob("GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION", {
  395. room: `home`,
  396. station
  397. }).then(res => {
  398. const { socketsThatCan } = res;
  399. socketsThatCan.forEach(socket => {
  400. socket.dispatch("event:station.updateTheme", { data: { stationId, theme: station.theme } });
  401. });
  402. });
  403. });
  404. }
  405. });
  406. CacheModule.runJob("SUB", {
  407. channel: "station.queueUpdate",
  408. cb: stationId => {
  409. StationsModule.runJob("GET_STATION", { stationId }).then(station => {
  410. WSModule.runJob("EMIT_TO_ROOM", {
  411. room: `station.${stationId}`,
  412. args: ["event:queue.update", { data: { queue: station.queue } }]
  413. });
  414. WSModule.runJob("EMIT_TO_ROOM", {
  415. room: `manage-station.${stationId}`,
  416. args: ["event:queue.update", { data: { stationId, queue: station.queue } }]
  417. });
  418. });
  419. }
  420. });
  421. CacheModule.runJob("SUB", {
  422. channel: "station.repositionSongInQueue",
  423. cb: res => {
  424. WSModule.runJob("EMIT_TO_ROOM", {
  425. room: `station.${res.stationId}`,
  426. args: ["event:queue.repositionSong", { data: { song: res.song } }]
  427. });
  428. WSModule.runJob("EMIT_TO_ROOM", {
  429. room: `manage-station.${res.stationId}`,
  430. args: ["event:queue.repositionSong", { data: { song: res.song } }]
  431. });
  432. }
  433. });
  434. CacheModule.runJob("SUB", {
  435. channel: "station.voteSkipSong",
  436. cb: stationId => {
  437. WSModule.runJob("EMIT_TO_ROOM", {
  438. room: `station.${stationId}`,
  439. args: ["event:song.voteSkipSong"]
  440. });
  441. }
  442. });
  443. CacheModule.runJob("SUB", {
  444. channel: "station.remove",
  445. cb: stationId => {
  446. WSModule.runJob("EMIT_TO_ROOM", {
  447. room: `station.${stationId}`,
  448. args: ["event:stations.remove"]
  449. });
  450. WSModule.runJob("EMIT_TO_ROOM", {
  451. room: `home`,
  452. args: ["event:station.removed", { data: { stationId } }]
  453. });
  454. WSModule.runJob("EMIT_TO_ROOM", {
  455. room: "admin.stations",
  456. args: ["event:admin.station.removed", { data: { stationId } }]
  457. });
  458. }
  459. });
  460. CacheModule.runJob("SUB", {
  461. channel: "station.create",
  462. cb: async stationId => {
  463. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" });
  464. StationsModule.runJob("INITIALIZE_STATION", { stationId }).then(async response => {
  465. const { station } = response;
  466. station.userCount = StationsModule.usersPerStationCount[stationId] || 0;
  467. WSModule.runJob("EMIT_TO_ROOM", {
  468. room: "admin.stations",
  469. args: ["event:admin.station.added", { data: { station } }]
  470. }).then(() => {});
  471. // TODO If community, check if on whitelist
  472. if (station.privacy === "public")
  473. WSModule.runJob("EMIT_TO_ROOM", {
  474. room: "home",
  475. args: ["event:stations.created", { data: { station } }]
  476. }).then(() => {});
  477. else {
  478. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", {
  479. room: "home"
  480. });
  481. sockets.forEach(async socketId => {
  482. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this);
  483. const { session } = socket;
  484. if (session.sessionId) {
  485. CacheModule.runJob("HGET", {
  486. table: "sessions",
  487. key: session.sessionId
  488. }).then(session => {
  489. if (session) {
  490. userModel.findOne({ _id: session.userId }, (err, user) => {
  491. if (user.role === "admin")
  492. socket.dispatch("event:stations.created", { data: { station } });
  493. else if (station.type === "community" && station.owner === session.userId)
  494. socket.dispatch("event:stations.created", { data: { station } });
  495. });
  496. }
  497. });
  498. }
  499. });
  500. }
  501. });
  502. }
  503. });
  504. export default {
  505. /**
  506. * Get a list of all the stations
  507. *
  508. * @param {object} session - user session
  509. * @param {Function} cb - callback
  510. */
  511. async index(session, cb) {
  512. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" });
  513. async.waterfall(
  514. [
  515. // get array of the ids of the user's favorite stations
  516. next => {
  517. if (session.userId)
  518. return userModel.findById(session.userId).select({ favoriteStations: -1 }).exec(next);
  519. return next(null, { favoriteStations: [] });
  520. },
  521. ({ favoriteStations }, next) => {
  522. CacheModule.runJob("HGETALL", { table: "stations" }, this).then(stations =>
  523. next(null, stations, favoriteStations)
  524. );
  525. },
  526. (stations, favorited, next) => {
  527. const filteredStations = [];
  528. async.eachLimit(
  529. stations,
  530. 1,
  531. (station, nextStation) => {
  532. async.waterfall(
  533. [
  534. callback => {
  535. // only relevant if user logged in
  536. if (session.userId) {
  537. if (favorited.indexOf(station._id) !== -1) station.isFavorited = true;
  538. return callback();
  539. }
  540. return callback();
  541. },
  542. callback => {
  543. StationsModule.runJob(
  544. "CAN_USER_VIEW_STATION",
  545. {
  546. station,
  547. userId: session.userId,
  548. hideUnlisted: true
  549. },
  550. this
  551. )
  552. .then(exists => callback(null, exists))
  553. .catch(callback);
  554. }
  555. ],
  556. (err, exists) => {
  557. if (err) return this.log("ERROR", "STATIONS_INDEX", err);
  558. station.userCount = StationsModule.usersPerStationCount[station._id] || 0;
  559. if (exists) filteredStations.push(station);
  560. return nextStation();
  561. }
  562. );
  563. },
  564. () => next(null, filteredStations, favorited)
  565. );
  566. }
  567. ],
  568. async (err, stations, favorited) => {
  569. if (err) {
  570. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  571. this.log("ERROR", "STATIONS_INDEX", `Indexing stations failed. "${err}"`);
  572. return cb({ status: "error", message: err });
  573. }
  574. this.log("SUCCESS", "STATIONS_INDEX", `Indexing stations successful.`, false);
  575. return cb({ status: "success", data: { stations, favorited } });
  576. }
  577. );
  578. },
  579. /**
  580. * Obtains basic metadata of a station in order to format an activity
  581. *
  582. * @param {object} session - user session
  583. * @param {string} stationId - the station id
  584. * @param {Function} cb - callback
  585. */
  586. getStationForActivity(session, stationId, cb) {
  587. async.waterfall(
  588. [
  589. next => {
  590. StationsModule.runJob("GET_STATION", { stationId }, this)
  591. .then(station => {
  592. next(null, station);
  593. })
  594. .catch(next);
  595. }
  596. ],
  597. async (err, station) => {
  598. if (err) {
  599. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  600. this.log(
  601. "ERROR",
  602. "STATIONS_GET_STATION_FOR_ACTIVITY",
  603. `Failed to obtain metadata of station ${stationId} for activity formatting. "${err}"`
  604. );
  605. return cb({ status: "error", message: err });
  606. }
  607. this.log(
  608. "SUCCESS",
  609. "STATIONS_GET_STATION_FOR_ACTIVITY",
  610. `Obtained metadata of station ${stationId} for activity formatting successfully.`
  611. );
  612. return cb({
  613. status: "success",
  614. data: {
  615. title: station.displayName,
  616. thumbnail: station.currentSong ? station.currentSong.thumbnail : ""
  617. }
  618. });
  619. }
  620. );
  621. },
  622. /**
  623. * Verifies that a station exists from its name
  624. *
  625. * @param {object} session - user session
  626. * @param {string} stationName - the station name
  627. * @param {Function} cb - callback
  628. */
  629. existsByName(session, stationName, cb) {
  630. async.waterfall(
  631. [
  632. next => {
  633. StationsModule.runJob("GET_STATION_BY_NAME", { stationName }, this)
  634. .then(station => next(null, station))
  635. .catch(next);
  636. },
  637. (station, next) => {
  638. if (!station) return next(null, false);
  639. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  640. .then(exists => next(null, exists))
  641. .catch(next);
  642. }
  643. ],
  644. async (err, exists) => {
  645. if (err) {
  646. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  647. this.log(
  648. "ERROR",
  649. "STATION_EXISTS_BY_NAME",
  650. `Checking if station "${stationName}" exists failed. "${err}"`
  651. );
  652. return cb({ status: "error", message: err });
  653. }
  654. this.log(
  655. "SUCCESS",
  656. "STATION_EXISTS_BY_NAME",
  657. `Station "${stationName}" exists successfully.` /* , false */
  658. );
  659. return cb({ status: "success", data: { exists } });
  660. }
  661. );
  662. },
  663. /**
  664. * Verifies that a station exists from its id
  665. *
  666. * @param {object} session - user session
  667. * @param {string} stationId - the station id
  668. * @param {Function} cb - callback
  669. */
  670. existsById(session, stationId, cb) {
  671. async.waterfall(
  672. [
  673. next => {
  674. StationsModule.runJob("GET_STATION", { stationId }, this)
  675. .then(station => next(null, station))
  676. .catch(next);
  677. },
  678. (station, next) => {
  679. if (!station) return next(null, false);
  680. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  681. .then(exists => next(null, exists))
  682. .catch(next);
  683. }
  684. ],
  685. async (err, exists) => {
  686. if (err) {
  687. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  688. this.log(
  689. "ERROR",
  690. "STATION_EXISTS_BY_ID",
  691. `Checking if station "${stationId}" exists failed. "${err}"`
  692. );
  693. return cb({ status: "error", message: err });
  694. }
  695. this.log(
  696. "SUCCESS",
  697. "STATION_EXISTS_BY_ID",
  698. `Station "${stationId}" exists successfully.` /* , false */
  699. );
  700. return cb({ status: "success", data: { exists } });
  701. }
  702. );
  703. },
  704. /**
  705. * Gets the official playlist for a station
  706. *
  707. * @param {object} session - user session
  708. * @param {string} stationId - the station id
  709. * @param {Function} cb - callback
  710. */
  711. getPlaylist(session, stationId, cb) {
  712. async.waterfall(
  713. [
  714. next => {
  715. StationsModule.runJob("GET_STATION", { stationId }, this)
  716. .then(station => {
  717. next(null, station);
  718. })
  719. .catch(next);
  720. },
  721. (station, next) => {
  722. StationsModule.runJob(
  723. "CAN_USER_VIEW_STATION",
  724. {
  725. station,
  726. userId: session.userId
  727. },
  728. this
  729. )
  730. .then(canView => {
  731. if (canView) return next(null, station);
  732. return next("Insufficient permissions.");
  733. })
  734. .catch(err => next(err));
  735. },
  736. (station, next) => {
  737. if (!station) return next("Station not found.");
  738. if (station.type !== "official") return next("This is not an official station.");
  739. return next();
  740. },
  741. next => {
  742. CacheModule.runJob(
  743. "HGET",
  744. {
  745. table: "officialPlaylists",
  746. key: stationId
  747. },
  748. this
  749. )
  750. .then(playlist => {
  751. next(null, playlist);
  752. })
  753. .catch(next);
  754. },
  755. (playlist, next) => {
  756. if (!playlist) return next("Playlist not found.");
  757. return next(null, playlist);
  758. }
  759. ],
  760. async (err, playlist) => {
  761. if (err) {
  762. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  763. this.log(
  764. "ERROR",
  765. "STATIONS_GET_PLAYLIST",
  766. `Getting playlist for station "${stationId}" failed. "${err}"`
  767. );
  768. return cb({ status: "error", message: err });
  769. }
  770. this.log(
  771. "SUCCESS",
  772. "STATIONS_GET_PLAYLIST",
  773. `Got playlist for station "${stationId}" successfully.`,
  774. false
  775. );
  776. return cb({ status: "success", data: { songs: playlist.songs } });
  777. }
  778. );
  779. },
  780. /**
  781. * Joins the station by its name
  782. *
  783. * @param {object} session - user session
  784. * @param {string} stationIdentifier - the station name or station id
  785. * @param {Function} cb - callback
  786. */
  787. join(session, stationIdentifier, cb) {
  788. async.waterfall(
  789. [
  790. next => {
  791. StationsModule.runJob("GET_STATION_BY_NAME", { stationName: stationIdentifier }, this)
  792. .then(station => next(null, station))
  793. .catch(() =>
  794. // station identifier may be using stationid instead
  795. StationsModule.runJob("GET_STATION", { stationId: stationIdentifier }, this)
  796. .then(station => next(null, station))
  797. .catch(next)
  798. );
  799. },
  800. (station, next) => {
  801. if (!station) return next("Station not found.");
  802. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  803. .then(canView => {
  804. if (!canView) next("Not allowed to join station.");
  805. else next(null, station);
  806. })
  807. .catch(err => next(err));
  808. },
  809. (station, next) => {
  810. WSModule.runJob("SOCKET_JOIN_ROOM", {
  811. socketId: session.socketId,
  812. room: `station.${station._id}`
  813. });
  814. const data = {
  815. _id: station._id,
  816. type: station.type,
  817. currentSong: station.currentSong,
  818. startedAt: station.startedAt,
  819. paused: station.paused,
  820. timePaused: station.timePaused,
  821. pausedAt: station.pausedAt,
  822. description: station.description,
  823. displayName: station.displayName,
  824. name: station.name,
  825. privacy: station.privacy,
  826. locked: station.locked,
  827. partyMode: station.partyMode,
  828. playMode: station.playMode,
  829. owner: station.owner,
  830. // privatePlaylist: station.privatePlaylist,
  831. includedPlaylists: station.includedPlaylists,
  832. excludedPlaylists: station.excludedPlaylists,
  833. // genres: station.genres,
  834. // blacklistedGenres: station.blacklistedGenres,
  835. theme: station.theme
  836. };
  837. StationsModule.userList[session.socketId] = station._id;
  838. next(null, data);
  839. },
  840. (data, next) => {
  841. data = JSON.parse(JSON.stringify(data));
  842. data.userCount = StationsModule.usersPerStationCount[data._id] || 0;
  843. data.users = StationsModule.usersPerStation[data._id] || [];
  844. if (!data.currentSong || !data.currentSong.title) return next(null, data);
  845. WSModule.runJob("SOCKET_JOIN_SONG_ROOM", {
  846. socketId: session.socketId,
  847. room: `song.${data.currentSong.youtubeId}`
  848. });
  849. data.currentSong.skipVotes = data.currentSong.skipVotes.length;
  850. return SongsModule.runJob(
  851. "GET_SONG_FROM_YOUTUBE_ID",
  852. { youtubeId: data.currentSong.youtubeId },
  853. this
  854. )
  855. .then(response => {
  856. const { song } = response;
  857. if (song) {
  858. data.currentSong.likes = song.likes;
  859. data.currentSong.dislikes = song.dislikes;
  860. } else {
  861. data.currentSong.likes = -1;
  862. data.currentSong.dislikes = -1;
  863. }
  864. })
  865. .catch(() => {
  866. data.currentSong.likes = -1;
  867. data.currentSong.dislikes = -1;
  868. })
  869. .finally(() => next(null, data));
  870. },
  871. (data, next) => {
  872. // only relevant if user logged in
  873. if (session.userId) {
  874. return StationsModule.runJob(
  875. "HAS_USER_FAVORITED_STATION",
  876. {
  877. userId: session.userId,
  878. stationId: data._id
  879. },
  880. this
  881. )
  882. .then(isStationFavorited => {
  883. data.isFavorited = isStationFavorited;
  884. return next(null, data);
  885. })
  886. .catch(err => next(err));
  887. }
  888. return next(null, data);
  889. }
  890. ],
  891. async (err, data) => {
  892. if (err) {
  893. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  894. this.log("ERROR", "STATIONS_JOIN", `Joining station "${stationIdentifier}" failed. "${err}"`);
  895. return cb({ status: "error", message: err });
  896. }
  897. this.log("SUCCESS", "STATIONS_JOIN", `Joined station "${data._id}" successfully.`);
  898. return cb({ status: "success", data });
  899. }
  900. );
  901. },
  902. /**
  903. * Gets a station by id
  904. *
  905. * @param {object} session - user session
  906. * @param {string} stationId - the station id
  907. * @param {Function} cb - callback
  908. */
  909. getStationById(session, stationId, cb) {
  910. async.waterfall(
  911. [
  912. next => {
  913. StationsModule.runJob("GET_STATION", { stationId }, this)
  914. .then(station => {
  915. next(null, station);
  916. })
  917. .catch(next);
  918. },
  919. (station, next) => {
  920. if (!station) return next("Station not found.");
  921. return StationsModule.runJob(
  922. "CAN_USER_VIEW_STATION",
  923. {
  924. station,
  925. userId: session.userId
  926. },
  927. this
  928. )
  929. .then(canView => {
  930. if (!canView) next("Not allowed to get station.");
  931. else next(null, station);
  932. })
  933. .catch(err => next(err));
  934. },
  935. (station, next) => {
  936. const data = {
  937. _id: station._id,
  938. type: station.type,
  939. description: station.description,
  940. displayName: station.displayName,
  941. name: station.name,
  942. privacy: station.privacy,
  943. locked: station.locked,
  944. partyMode: station.partyMode,
  945. playMode: station.playMode,
  946. owner: station.owner,
  947. // privatePlaylist: station.privatePlaylist,
  948. // genres: station.genres,
  949. // blacklistedGenres: station.blacklistedGenres,
  950. theme: station.theme,
  951. paused: station.paused,
  952. currentSong: station.currentSong
  953. };
  954. next(null, data);
  955. }
  956. ],
  957. async (err, data) => {
  958. if (err) {
  959. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  960. this.log("ERROR", "GET_STATION_BY_ID", `Getting station "${stationId}" failed. "${err}"`);
  961. return cb({ status: "error", message: err });
  962. }
  963. this.log("SUCCESS", "GET_STATION_BY_ID", `Got station "${stationId}" successfully.`);
  964. return cb({ status: "success", data: { station: data } });
  965. }
  966. );
  967. },
  968. getStationIncludedPlaylistsById(session, stationId, cb) {
  969. async.waterfall(
  970. [
  971. next => {
  972. StationsModule.runJob("GET_STATION", { stationId }, this)
  973. .then(station => {
  974. next(null, station);
  975. })
  976. .catch(next);
  977. },
  978. (station, next) => {
  979. if (!station) return next("Station not found.");
  980. return StationsModule.runJob(
  981. "CAN_USER_VIEW_STATION",
  982. {
  983. station,
  984. userId: session.userId
  985. },
  986. this
  987. )
  988. .then(canView => {
  989. if (!canView) next("Not allowed to get station.");
  990. else next(null, station);
  991. })
  992. .catch(err => next(err));
  993. },
  994. (station, next) => {
  995. const playlists = [];
  996. async.eachLimit(
  997. station.includedPlaylists,
  998. 1,
  999. (playlistId, next) => {
  1000. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1001. .then(playlist => {
  1002. playlists.push(playlist);
  1003. next();
  1004. })
  1005. .catch(() => {
  1006. playlists.push(null);
  1007. next();
  1008. });
  1009. },
  1010. err => {
  1011. next(err, playlists);
  1012. }
  1013. );
  1014. }
  1015. ],
  1016. async (err, playlists) => {
  1017. if (err) {
  1018. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1019. this.log(
  1020. "ERROR",
  1021. "GET_STATION_INCLUDED_PLAYLISTS_BY_ID",
  1022. `Getting station "${stationId}"'s included playlists failed. "${err}"`
  1023. );
  1024. return cb({ status: "error", message: err });
  1025. }
  1026. this.log(
  1027. "SUCCESS",
  1028. "GET_STATION_INCLUDED_PLAYLISTS_BY_ID",
  1029. `Got station "${stationId}"'s included playlists successfully.`
  1030. );
  1031. return cb({ status: "success", data: { playlists } });
  1032. }
  1033. );
  1034. },
  1035. getStationExcludedPlaylistsById(session, stationId, cb) {
  1036. async.waterfall(
  1037. [
  1038. next => {
  1039. StationsModule.runJob("GET_STATION", { stationId }, this)
  1040. .then(station => {
  1041. next(null, station);
  1042. })
  1043. .catch(next);
  1044. },
  1045. (station, next) => {
  1046. if (!station) return next("Station not found.");
  1047. return StationsModule.runJob(
  1048. "CAN_USER_VIEW_STATION",
  1049. {
  1050. station,
  1051. userId: session.userId
  1052. },
  1053. this
  1054. )
  1055. .then(canView => {
  1056. if (!canView) next("Not allowed to get station.");
  1057. else next(null, station);
  1058. })
  1059. .catch(err => next(err));
  1060. },
  1061. (station, next) => {
  1062. const playlists = [];
  1063. async.eachLimit(
  1064. station.excludedPlaylists,
  1065. 1,
  1066. (playlistId, next) => {
  1067. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1068. .then(playlist => {
  1069. playlists.push(playlist);
  1070. next();
  1071. })
  1072. .catch(() => {
  1073. playlists.push(null);
  1074. next();
  1075. });
  1076. },
  1077. err => {
  1078. next(err, playlists);
  1079. }
  1080. );
  1081. }
  1082. ],
  1083. async (err, playlists) => {
  1084. if (err) {
  1085. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1086. this.log(
  1087. "ERROR",
  1088. "GET_STATION_EXCLUDED_PLAYLISTS_BY_ID",
  1089. `Getting station "${stationId}"'s excluded playlists failed. "${err}"`
  1090. );
  1091. return cb({ status: "error", message: err });
  1092. }
  1093. this.log(
  1094. "SUCCESS",
  1095. "GET_STATION_EXCLUDED_PLAYLISTS_BY_ID",
  1096. `Got station "${stationId}"'s excluded playlists successfully.`
  1097. );
  1098. return cb({ status: "success", data: { playlists } });
  1099. }
  1100. );
  1101. },
  1102. /**
  1103. * Toggles if a station is locked
  1104. *
  1105. * @param session
  1106. * @param stationId - the station id
  1107. * @param cb
  1108. */
  1109. toggleLock: isOwnerRequired(async function toggleLock(session, stationId, cb) {
  1110. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1111. async.waterfall(
  1112. [
  1113. next => {
  1114. StationsModule.runJob("GET_STATION", { stationId }, this)
  1115. .then(station => {
  1116. next(null, station);
  1117. })
  1118. .catch(next);
  1119. },
  1120. (station, next) => {
  1121. stationModel.updateOne({ _id: stationId }, { $set: { locked: !station.locked } }, next);
  1122. },
  1123. (res, next) => {
  1124. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1125. .then(station => {
  1126. next(null, station);
  1127. })
  1128. .catch(next);
  1129. }
  1130. ],
  1131. async (err, station) => {
  1132. if (err) {
  1133. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1134. this.log(
  1135. "ERROR",
  1136. "STATIONS_UPDATE_LOCKED_STATUS",
  1137. `Toggling the queue lock for station "${stationId}" failed. "${err}"`
  1138. );
  1139. return cb({ status: "error", message: err });
  1140. }
  1141. this.log(
  1142. "SUCCESS",
  1143. "STATIONS_UPDATE_LOCKED_STATUS",
  1144. `Toggled the queue lock for station "${stationId}" successfully to "${station.locked}".`
  1145. );
  1146. CacheModule.runJob("PUB", {
  1147. channel: "station.queueLockToggled",
  1148. value: {
  1149. stationId,
  1150. locked: station.locked
  1151. }
  1152. });
  1153. return cb({ status: "success", data: { locked: station.locked } });
  1154. }
  1155. );
  1156. }),
  1157. /**
  1158. * Votes to skip a station
  1159. *
  1160. * @param session
  1161. * @param stationId - the station id
  1162. * @param cb
  1163. */
  1164. voteSkip: isLoginRequired(async function voteSkip(session, stationId, cb) {
  1165. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1166. let skipVotes = 0;
  1167. let shouldSkip = false;
  1168. async.waterfall(
  1169. [
  1170. next => {
  1171. StationsModule.runJob("GET_STATION", { stationId }, this)
  1172. .then(station => next(null, station))
  1173. .catch(next);
  1174. },
  1175. (station, next) => {
  1176. if (!station) return next("Station not found.");
  1177. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  1178. .then(canView => {
  1179. if (canView) return next(null, station);
  1180. return next("Insufficient permissions.");
  1181. })
  1182. .catch(err => next(err));
  1183. },
  1184. (station, next) => {
  1185. if (!station.currentSong) return next("There is currently no song to skip.");
  1186. if (station.currentSong.skipVotes.indexOf(session.userId) !== -1)
  1187. return next("You have already voted to skip this song.");
  1188. return next(null, station);
  1189. },
  1190. (station, next) => {
  1191. stationModel.updateOne(
  1192. { _id: stationId },
  1193. { $push: { "currentSong.skipVotes": session.userId } },
  1194. next
  1195. );
  1196. },
  1197. (res, next) => {
  1198. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1199. .then(station => {
  1200. next(null, station);
  1201. })
  1202. .catch(next);
  1203. },
  1204. (station, next) => {
  1205. if (!station) return next("Station not found.");
  1206. return next(null, station);
  1207. },
  1208. (station, next) => {
  1209. skipVotes = station.currentSong.skipVotes.length;
  1210. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${stationId}` }, this)
  1211. .then(sockets => next(null, sockets))
  1212. .catch(next);
  1213. },
  1214. (sockets, next) => {
  1215. if (sockets.length <= skipVotes) {
  1216. shouldSkip = true;
  1217. return next();
  1218. }
  1219. const users = [];
  1220. return async.each(
  1221. sockets,
  1222. (socketId, next) => {
  1223. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  1224. .then(socket => {
  1225. if (socket.session && socket.session.userId) {
  1226. if (!users.includes(socket.session.userId)) users.push(socket.session.userId);
  1227. } else users.push(socketId);
  1228. return next();
  1229. })
  1230. .catch(next);
  1231. },
  1232. err => {
  1233. if (err) return next(err);
  1234. if (users.length <= skipVotes) shouldSkip = true;
  1235. return next();
  1236. }
  1237. );
  1238. }
  1239. ],
  1240. async err => {
  1241. if (err) {
  1242. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1243. this.log("ERROR", "STATIONS_VOTE_SKIP", `Vote skipping station "${stationId}" failed. "${err}"`);
  1244. return cb({ status: "error", message: err });
  1245. }
  1246. this.log("SUCCESS", "STATIONS_VOTE_SKIP", `Vote skipping "${stationId}" successful.`);
  1247. CacheModule.runJob("PUB", {
  1248. channel: "station.voteSkipSong",
  1249. value: stationId
  1250. });
  1251. if (shouldSkip) StationsModule.runJob("SKIP_STATION", { stationId });
  1252. return cb({
  1253. status: "success",
  1254. message: "Successfully voted to skip the song."
  1255. });
  1256. }
  1257. );
  1258. }),
  1259. /**
  1260. * Force skips a station
  1261. *
  1262. * @param session
  1263. * @param stationId - the station id
  1264. * @param cb
  1265. */
  1266. forceSkip: isOwnerRequired(function forceSkip(session, stationId, cb) {
  1267. async.waterfall(
  1268. [
  1269. next => {
  1270. StationsModule.runJob("GET_STATION", { stationId }, this)
  1271. .then(station => {
  1272. next(null, station);
  1273. })
  1274. .catch(next);
  1275. },
  1276. (station, next) => {
  1277. if (!station) return next("Station not found.");
  1278. return next();
  1279. }
  1280. ],
  1281. async err => {
  1282. if (err) {
  1283. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1284. this.log("ERROR", "STATIONS_FORCE_SKIP", `Force skipping station "${stationId}" failed. "${err}"`);
  1285. return cb({ status: "error", message: err });
  1286. }
  1287. StationsModule.runJob("SKIP_STATION", { stationId });
  1288. this.log("SUCCESS", "STATIONS_FORCE_SKIP", `Force skipped station "${stationId}" successfully.`);
  1289. return cb({
  1290. status: "success",
  1291. message: "Successfully skipped station."
  1292. });
  1293. }
  1294. );
  1295. }),
  1296. /**
  1297. * Leaves the user's current station
  1298. *
  1299. * @param {object} session - user session
  1300. * @param {string} stationId - id of station to leave
  1301. * @param {Function} cb - callback
  1302. */
  1303. leave(session, stationId, cb) {
  1304. async.waterfall(
  1305. [
  1306. next => {
  1307. StationsModule.runJob("GET_STATION", { stationId }, this)
  1308. .then(station => {
  1309. next(null, station);
  1310. })
  1311. .catch(next);
  1312. },
  1313. (station, next) => {
  1314. if (!station) return next("Station not found.");
  1315. return next();
  1316. }
  1317. ],
  1318. async (err, userCount) => {
  1319. if (err) {
  1320. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1321. this.log("ERROR", "STATIONS_LEAVE", `Leaving station "${stationId}" failed. "${err}"`);
  1322. return cb({ status: "error", message: err });
  1323. }
  1324. this.log("SUCCESS", "STATIONS_LEAVE", `Left station "${stationId}" successfully.`);
  1325. WSModule.runJob("SOCKET_LEAVE_ROOM", { socketId: session.socketId, room: `station.${stationId}` });
  1326. delete StationsModule.userList[session.socketId];
  1327. return cb({
  1328. status: "success",
  1329. message: "Successfully left station.",
  1330. data: { userCount }
  1331. });
  1332. }
  1333. );
  1334. },
  1335. /**
  1336. * Updates a station's name
  1337. *
  1338. * @param session
  1339. * @param stationId - the station id
  1340. * @param newName - the new station name
  1341. * @param cb
  1342. */
  1343. updateName: isOwnerRequired(async function updateName(session, stationId, newName, cb) {
  1344. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1345. async.waterfall(
  1346. [
  1347. next => {
  1348. stationModel.updateOne(
  1349. { _id: stationId },
  1350. { $set: { name: newName } },
  1351. { runValidators: true },
  1352. next
  1353. );
  1354. },
  1355. (res, next) => {
  1356. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1357. .then(station => next(null, station))
  1358. .catch(next);
  1359. }
  1360. ],
  1361. async (err, station) => {
  1362. if (err) {
  1363. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1364. this.log(
  1365. "ERROR",
  1366. "STATIONS_UPDATE_NAME",
  1367. `Updating station "${stationId}" name to "${newName}" failed. "${err}"`
  1368. );
  1369. return cb({ status: "error", message: err });
  1370. }
  1371. this.log(
  1372. "SUCCESS",
  1373. "STATIONS_UPDATE_NAME",
  1374. `Updated station "${stationId}" name to "${newName}" successfully.`
  1375. );
  1376. CacheModule.runJob("PUB", {
  1377. channel: "station.nameUpdate",
  1378. value: { stationId, name: newName }
  1379. });
  1380. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1381. userId: session.userId,
  1382. type: "station__edit_name",
  1383. payload: {
  1384. message: `Changed name of station <stationId>${station.displayName}</stationId> to ${newName}`,
  1385. stationId
  1386. }
  1387. });
  1388. return cb({
  1389. status: "success",
  1390. message: "Successfully updated the name."
  1391. });
  1392. }
  1393. );
  1394. }),
  1395. /**
  1396. * Updates a station's display name
  1397. *
  1398. * @param session
  1399. * @param stationId - the station id
  1400. * @param newDisplayName - the new station display name
  1401. * @param cb
  1402. */
  1403. updateDisplayName: isOwnerRequired(async function updateDisplayName(session, stationId, newDisplayName, cb) {
  1404. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1405. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1406. async.waterfall(
  1407. [
  1408. next => {
  1409. stationModel.updateOne(
  1410. { _id: stationId },
  1411. { $set: { displayName: newDisplayName } },
  1412. { runValidators: true },
  1413. next
  1414. );
  1415. },
  1416. (res, next) => {
  1417. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1418. .then(station => next(null, station))
  1419. .catch(next);
  1420. },
  1421. (station, next) => {
  1422. playlistModel.updateOne(
  1423. { _id: station.playlist },
  1424. { $set: { displayName: `Station - ${station.displayName}` } },
  1425. err => {
  1426. next(err, station);
  1427. }
  1428. );
  1429. }
  1430. ],
  1431. async err => {
  1432. if (err) {
  1433. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1434. this.log(
  1435. "ERROR",
  1436. "STATIONS_UPDATE_DISPLAY_NAME",
  1437. `Updating station "${stationId}" displayName to "${newDisplayName}" failed. "${err}"`
  1438. );
  1439. return cb({ status: "error", message: err });
  1440. }
  1441. this.log(
  1442. "SUCCESS",
  1443. "STATIONS_UPDATE_DISPLAY_NAME",
  1444. `Updated station "${stationId}" displayName to "${newDisplayName}" successfully.`
  1445. );
  1446. CacheModule.runJob("PUB", {
  1447. channel: "station.displayNameUpdate",
  1448. value: { stationId, displayName: newDisplayName }
  1449. });
  1450. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1451. userId: session.userId,
  1452. type: "station__edit_display_name",
  1453. payload: {
  1454. message: `Changed display name of station <stationId>${newDisplayName}</stationId>`,
  1455. stationId
  1456. }
  1457. });
  1458. return cb({
  1459. status: "success",
  1460. message: "Successfully updated the display name."
  1461. });
  1462. }
  1463. );
  1464. }),
  1465. /**
  1466. * Updates a station's description
  1467. *
  1468. * @param session
  1469. * @param stationId - the station id
  1470. * @param newDescription - the new station description
  1471. * @param cb
  1472. */
  1473. updateDescription: isOwnerRequired(async function updateDescription(session, stationId, newDescription, cb) {
  1474. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1475. async.waterfall(
  1476. [
  1477. next => {
  1478. stationModel.updateOne(
  1479. { _id: stationId },
  1480. { $set: { description: newDescription } },
  1481. { runValidators: true },
  1482. next
  1483. );
  1484. },
  1485. (res, next) => {
  1486. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1487. .then(station => next(null, station))
  1488. .catch(next);
  1489. }
  1490. ],
  1491. async (err, station) => {
  1492. if (err) {
  1493. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1494. this.log(
  1495. "ERROR",
  1496. "STATIONS_UPDATE_DESCRIPTION",
  1497. `Updating station "${stationId}" description to "${newDescription}" failed. "${err}"`
  1498. );
  1499. return cb({ status: "error", message: err });
  1500. }
  1501. this.log(
  1502. "SUCCESS",
  1503. "STATIONS_UPDATE_DESCRIPTION",
  1504. `Updated station "${stationId}" description to "${newDescription}" successfully.`
  1505. );
  1506. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1507. userId: session.userId,
  1508. type: "station__edit_description",
  1509. payload: {
  1510. message: `Changed description of station <stationId>${station.displayName}</stationId> to ${newDescription}`,
  1511. stationId
  1512. }
  1513. });
  1514. CacheModule.runJob("PUB", {
  1515. channel: "station.descriptionUpdate",
  1516. value: { stationId, description: newDescription }
  1517. });
  1518. return cb({
  1519. status: "success",
  1520. message: "Successfully updated the description."
  1521. });
  1522. }
  1523. );
  1524. }),
  1525. /**
  1526. * Updates a station's privacy
  1527. *
  1528. * @param session
  1529. * @param stationId - the station id
  1530. * @param newPrivacy - the new station privacy
  1531. * @param cb
  1532. */
  1533. updatePrivacy: isOwnerRequired(async function updatePrivacy(session, stationId, newPrivacy, cb) {
  1534. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1535. let previousPrivacy = null;
  1536. async.waterfall(
  1537. [
  1538. next => {
  1539. stationModel.findOne({ _id: stationId }, next);
  1540. },
  1541. (station, next) => {
  1542. if (!station) next("No station found.");
  1543. else {
  1544. previousPrivacy = station.privacy;
  1545. next();
  1546. }
  1547. },
  1548. next => {
  1549. stationModel.updateOne(
  1550. { _id: stationId },
  1551. { $set: { privacy: newPrivacy } },
  1552. { runValidators: true },
  1553. next
  1554. );
  1555. },
  1556. (res, next) => {
  1557. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1558. .then(station => next(null, station))
  1559. .catch(next);
  1560. }
  1561. ],
  1562. async (err, station) => {
  1563. if (err) {
  1564. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1565. this.log(
  1566. "ERROR",
  1567. "STATIONS_UPDATE_PRIVACY",
  1568. `Updating station "${stationId}" privacy to "${newPrivacy}" failed. "${err}"`
  1569. );
  1570. return cb({ status: "error", message: err });
  1571. }
  1572. this.log(
  1573. "SUCCESS",
  1574. "STATIONS_UPDATE_PRIVACY",
  1575. `Updated station "${stationId}" privacy to "${newPrivacy}" successfully.`
  1576. );
  1577. CacheModule.runJob("PUB", {
  1578. channel: "station.privacyUpdate",
  1579. value: { stationId, previousPrivacy }
  1580. });
  1581. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1582. userId: session.userId,
  1583. type: "station__edit_privacy",
  1584. payload: {
  1585. message: `Changed privacy of station <stationId>${station.displayName}</stationId> to ${newPrivacy}`,
  1586. stationId
  1587. }
  1588. });
  1589. return cb({
  1590. status: "success",
  1591. message: "Successfully updated the privacy."
  1592. });
  1593. }
  1594. );
  1595. }),
  1596. /**
  1597. * Updates a station's genres
  1598. *
  1599. * @param session
  1600. * @param stationId - the station id
  1601. * @param newGenres - the new station genres
  1602. * @param cb
  1603. */
  1604. updateGenres: isOwnerRequired(async function updateGenres(session, stationId, newGenres, cb) {
  1605. async.waterfall(
  1606. [
  1607. next => {
  1608. StationsModule.runJob("GET_STATION", { stationId }, this)
  1609. .then(station => {
  1610. next(null, station);
  1611. })
  1612. .catch(next);
  1613. },
  1614. (station, next) => {
  1615. const playlists = [];
  1616. async.eachLimit(
  1617. newGenres,
  1618. 1,
  1619. (genre, next) => {
  1620. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre, includeSongs: false }, this)
  1621. .then(response => {
  1622. playlists.push(response.playlist);
  1623. next();
  1624. })
  1625. .catch(err => {
  1626. if (err.message === "Playlist not found")
  1627. next(
  1628. `The genre playlist for "${genre}" was not found. Please ensure that this genre playlist exists.`
  1629. );
  1630. else next(err);
  1631. });
  1632. },
  1633. err => {
  1634. next(
  1635. err,
  1636. station,
  1637. playlists.map(playlist => playlist._id.toString())
  1638. );
  1639. }
  1640. );
  1641. },
  1642. (station, playlists, next) => {
  1643. const playlistsToRemoveFromExcluded = playlists.filter(
  1644. playlistId => station.excludedPlaylists.indexOf(playlistId) !== -1
  1645. );
  1646. console.log(
  1647. `playlistsToRemoveFromExcluded: ${playlistsToRemoveFromExcluded.length}`,
  1648. playlistsToRemoveFromExcluded
  1649. );
  1650. async.eachLimit(
  1651. playlistsToRemoveFromExcluded,
  1652. 1,
  1653. (playlistId, next) => {
  1654. StationsModule.runJob("REMOVE_EXCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1655. .then(() => {
  1656. next();
  1657. })
  1658. .catch(next);
  1659. },
  1660. err => {
  1661. next(err, station, playlists);
  1662. }
  1663. );
  1664. },
  1665. (station, playlists, next) => {
  1666. const playlistsToRemoveFromIncluded = station.includedPlaylists.filter(
  1667. playlistId => playlists.indexOf(playlistId) === -1
  1668. );
  1669. console.log(
  1670. `playlistsToRemoveFromIncluded: ${playlistsToRemoveFromIncluded.length}`,
  1671. playlistsToRemoveFromIncluded
  1672. );
  1673. async.eachLimit(
  1674. playlistsToRemoveFromIncluded,
  1675. 1,
  1676. (playlistId, next) => {
  1677. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1678. .then(() => {
  1679. next();
  1680. })
  1681. .catch(next);
  1682. },
  1683. err => {
  1684. next(err, station, playlists);
  1685. }
  1686. );
  1687. },
  1688. (station, playlists, next) => {
  1689. const playlistsToAddToIncluded = playlists.filter(
  1690. playlistId => station.includedPlaylists.indexOf(playlistId) === -1
  1691. );
  1692. console.log(
  1693. `playlistsToAddToIncluded: ${playlistsToAddToIncluded.length}`,
  1694. playlistsToAddToIncluded
  1695. );
  1696. async.eachLimit(
  1697. playlistsToAddToIncluded,
  1698. 1,
  1699. (playlistId, next) => {
  1700. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  1701. .then(() => {
  1702. next();
  1703. })
  1704. .catch(next);
  1705. },
  1706. err => {
  1707. next(err);
  1708. }
  1709. );
  1710. },
  1711. next => {
  1712. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1713. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1714. .then(station => next(null, station))
  1715. .catch(next);
  1716. }
  1717. ],
  1718. async (err, station) => {
  1719. if (err) {
  1720. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1721. this.log(
  1722. "ERROR",
  1723. "STATIONS_UPDATE_GENRES",
  1724. `Updating station "${stationId}" genres to "${newGenres}" failed. "${err}"`
  1725. );
  1726. return cb({ status: "error", message: err });
  1727. }
  1728. this.log(
  1729. "SUCCESS",
  1730. "STATIONS_UPDATE_GENRES",
  1731. `Updated station "${stationId}" genres to "${newGenres}" successfully.`
  1732. );
  1733. if (newGenres.length > 0) {
  1734. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1735. userId: session.userId,
  1736. type: "station__edit_genres",
  1737. payload: {
  1738. message: `Updated genres of station <stationId>${station.displayName}</stationId> to
  1739. ${newGenres.join(", ")}`,
  1740. stationId
  1741. }
  1742. });
  1743. } else {
  1744. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1745. userId: session.userId,
  1746. type: "station__edit_genres",
  1747. payload: {
  1748. message: `Removed all genres of station <stationId>${station.displayName}</stationId>`,
  1749. stationId
  1750. }
  1751. });
  1752. }
  1753. return cb({
  1754. status: "success",
  1755. message: "Successfully updated the genres."
  1756. });
  1757. }
  1758. );
  1759. }),
  1760. /**
  1761. * Updates a station's blacklisted genres
  1762. *
  1763. * @param session
  1764. * @param stationId - the station id
  1765. * @param newBlacklistedGenres - the new station blacklisted genres
  1766. * @param cb
  1767. */
  1768. updateBlacklistedGenres: isOwnerRequired(async function updateBlacklistedGenres(
  1769. session,
  1770. stationId,
  1771. newBlacklistedGenres,
  1772. cb
  1773. ) {
  1774. async.waterfall(
  1775. [
  1776. next => {
  1777. StationsModule.runJob("GET_STATION", { stationId }, this)
  1778. .then(station => {
  1779. next(null, station);
  1780. })
  1781. .catch(next);
  1782. },
  1783. (station, next) => {
  1784. const playlists = [];
  1785. async.eachLimit(
  1786. newBlacklistedGenres,
  1787. 1,
  1788. (genre, next) => {
  1789. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre, includeSongs: false }, this)
  1790. .then(response => {
  1791. playlists.push(response.playlist);
  1792. next();
  1793. })
  1794. .catch(err => {
  1795. if (err.message === "Playlist not found")
  1796. next(
  1797. `The genre playlist for "${genre}" was not found. Please ensure that this genre playlist exists.`
  1798. );
  1799. else next(err);
  1800. });
  1801. },
  1802. err => {
  1803. next(
  1804. err,
  1805. station,
  1806. playlists.map(playlist => playlist._id.toString())
  1807. );
  1808. }
  1809. );
  1810. },
  1811. (station, playlists, next) => {
  1812. const playlistsToRemoveFromIncluded = playlists.filter(
  1813. playlistId => station.includedPlaylists.indexOf(playlistId) !== -1
  1814. );
  1815. console.log(
  1816. `playlistsToRemoveFromIncluded: ${playlistsToRemoveFromIncluded.length}`,
  1817. playlistsToRemoveFromIncluded
  1818. );
  1819. async.eachLimit(
  1820. playlistsToRemoveFromIncluded,
  1821. 1,
  1822. (playlistId, next) => {
  1823. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1824. .then(() => {
  1825. next();
  1826. })
  1827. .catch(next);
  1828. },
  1829. err => {
  1830. next(err, station, playlists);
  1831. }
  1832. );
  1833. },
  1834. (station, playlists, next) => {
  1835. const playlistsToRemoveFromExcluded = station.excludedPlaylists.filter(
  1836. playlistId => playlists.indexOf(playlistId) === -1
  1837. );
  1838. console.log(
  1839. `playlistsToRemoveFromExcluded: ${playlistsToRemoveFromExcluded.length}`,
  1840. playlistsToRemoveFromExcluded
  1841. );
  1842. async.eachLimit(
  1843. playlistsToRemoveFromExcluded,
  1844. 1,
  1845. (playlistId, next) => {
  1846. StationsModule.runJob("REMOVE_EXCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1847. .then(() => {
  1848. next();
  1849. })
  1850. .catch(next);
  1851. },
  1852. err => {
  1853. next(err, station, playlists);
  1854. }
  1855. );
  1856. },
  1857. (station, playlists, next) => {
  1858. const playlistsToAddToExcluded = playlists.filter(
  1859. playlistId => station.excludedPlaylists.indexOf(playlistId) === -1
  1860. );
  1861. console.log(
  1862. `playlistsToAddToExcluded: ${playlistsToAddToExcluded.length}`,
  1863. playlistsToAddToExcluded
  1864. );
  1865. async.eachLimit(
  1866. playlistsToAddToExcluded,
  1867. 1,
  1868. (playlistId, next) => {
  1869. StationsModule.runJob("EXCLUDE_PLAYLIST", { stationId, playlistId }, this)
  1870. .then(() => {
  1871. next();
  1872. })
  1873. .catch(next);
  1874. },
  1875. err => {
  1876. next(err);
  1877. }
  1878. );
  1879. },
  1880. next => {
  1881. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1882. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1883. .then(station => next(null, station))
  1884. .catch(next);
  1885. }
  1886. ],
  1887. async (err, station) => {
  1888. if (err) {
  1889. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1890. this.log(
  1891. "ERROR",
  1892. "STATIONS_UPDATE_BLACKLISTED_GENRES",
  1893. `Updating station "${stationId}" blacklisted genres to "${newBlacklistedGenres}" failed. "${err}"`
  1894. );
  1895. return cb({ status: "error", message: err });
  1896. }
  1897. this.log(
  1898. "SUCCESS",
  1899. "STATIONS_UPDATE_BLACKLISTED_GENRES",
  1900. `Updated station "${stationId}" blacklisted genres to "${newBlacklistedGenres}" successfully.`
  1901. );
  1902. if (newBlacklistedGenres.length > 0) {
  1903. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1904. userId: session.userId,
  1905. type: "station__edit_blacklisted_genres",
  1906. payload: {
  1907. message: `Updated blacklisted genres of station <stationId>${
  1908. station.displayName
  1909. }</stationId> to ${newBlacklistedGenres.join(", ")}`,
  1910. stationId
  1911. }
  1912. });
  1913. } else {
  1914. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1915. userId: session.userId,
  1916. type: "station__edit_blacklisted_genres",
  1917. payload: {
  1918. message: `Removed all blacklisted genres of station <stationId>${station.displayName}</stationId>`,
  1919. stationId
  1920. }
  1921. });
  1922. }
  1923. return cb({
  1924. status: "success",
  1925. message: "Successfully updated the blacklisted genres."
  1926. });
  1927. }
  1928. );
  1929. }),
  1930. /**
  1931. * Updates a station's party mode
  1932. *
  1933. * @param session
  1934. * @param stationId - the station id
  1935. * @param newPartyMode - the new station party mode
  1936. * @param cb
  1937. */
  1938. updatePartyMode: isOwnerRequired(async function updatePartyMode(session, stationId, newPartyMode, cb) {
  1939. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1940. async.waterfall(
  1941. [
  1942. next => {
  1943. StationsModule.runJob("GET_STATION", { stationId }, this)
  1944. .then(station => next(null, station))
  1945. .catch(next);
  1946. },
  1947. (station, next) => {
  1948. if (!station) return next("Station not found.");
  1949. if (station.partyMode === newPartyMode)
  1950. return next(`The party mode was already ${newPartyMode ? "enabled." : "disabled."}`);
  1951. return stationModel.updateOne(
  1952. { _id: stationId },
  1953. { $set: { partyMode: newPartyMode, queue: [] } },
  1954. { runValidators: true },
  1955. next
  1956. );
  1957. },
  1958. (res, next) => {
  1959. CacheModule.runJob("PUB", {
  1960. channel: "station.queueUpdate",
  1961. value: stationId
  1962. })
  1963. .then(() => {})
  1964. .catch(next);
  1965. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1966. .then(station => next(null, station))
  1967. .catch(next);
  1968. }
  1969. ],
  1970. async err => {
  1971. if (err) {
  1972. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1973. this.log(
  1974. "ERROR",
  1975. "STATIONS_UPDATE_PARTY_MODE",
  1976. `Updating station "${stationId}" party mode to "${newPartyMode}" failed. "${err}"`
  1977. );
  1978. return cb({ status: "error", message: err });
  1979. }
  1980. this.log(
  1981. "SUCCESS",
  1982. "STATIONS_UPDATE_PARTY_MODE",
  1983. `Updated station "${stationId}" party mode to "${newPartyMode}" successfully.`
  1984. );
  1985. CacheModule.runJob("PUB", {
  1986. channel: "station.updatePartyMode",
  1987. value: {
  1988. stationId,
  1989. partyMode: newPartyMode
  1990. }
  1991. });
  1992. StationsModule.runJob("SKIP_STATION", { stationId });
  1993. return cb({
  1994. status: "success",
  1995. message: "Successfully updated the party mode."
  1996. });
  1997. }
  1998. );
  1999. }),
  2000. /**
  2001. * Updates a station's play mode
  2002. *
  2003. * @param session
  2004. * @param stationId - the station id
  2005. * @param newPlayMode - the new station play mode
  2006. * @param cb
  2007. */
  2008. updatePlayMode: isOwnerRequired(async function updatePartyMode(session, stationId, newPlayMode, cb) {
  2009. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2010. async.waterfall(
  2011. [
  2012. next => {
  2013. StationsModule.runJob("GET_STATION", { stationId }, this)
  2014. .then(station => {
  2015. next(null, station);
  2016. })
  2017. .catch(next);
  2018. },
  2019. (station, next) => {
  2020. if (!station) return next("Station not found.");
  2021. if (station.newPlayMode === newPlayMode) return next(`The play mode was already ${newPlayMode}`);
  2022. return stationModel.updateOne(
  2023. { _id: stationId },
  2024. { $set: { playMode: newPlayMode, queue: [] } },
  2025. { runValidators: true },
  2026. next
  2027. );
  2028. },
  2029. (res, next) => {
  2030. CacheModule.runJob("PUB", {
  2031. channel: "station.queueUpdate",
  2032. value: stationId
  2033. })
  2034. .then()
  2035. .catch();
  2036. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2037. .then(station => {
  2038. next(null, station);
  2039. })
  2040. .catch(next);
  2041. }
  2042. ],
  2043. async err => {
  2044. if (err) {
  2045. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2046. this.log(
  2047. "ERROR",
  2048. "STATIONS_UPDATE_PLAY_MODE",
  2049. `Updating station "${stationId}" play mode to "${newPlayMode}" failed. "${err}"`
  2050. );
  2051. return cb({ status: "error", message: err });
  2052. }
  2053. this.log(
  2054. "SUCCESS",
  2055. "STATIONS_UPDATE_PLAY_MODE",
  2056. `Updated station "${stationId}" play mode to "${newPlayMode}" successfully.`
  2057. );
  2058. CacheModule.runJob("PUB", {
  2059. channel: "station.newPlayMode",
  2060. value: {
  2061. stationId,
  2062. playMode: newPlayMode
  2063. }
  2064. });
  2065. StationsModule.runJob("SKIP_STATION", { stationId });
  2066. return cb({
  2067. status: "success",
  2068. message: "Successfully updated the play mode."
  2069. });
  2070. }
  2071. );
  2072. }),
  2073. /**
  2074. * Updates a station's theme
  2075. *
  2076. * @param session
  2077. * @param stationId - the station id
  2078. * @param newTheme - the new station theme
  2079. * @param cb
  2080. */
  2081. updateTheme: isOwnerRequired(async function updateTheme(session, stationId, newTheme, cb) {
  2082. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2083. async.waterfall(
  2084. [
  2085. next => {
  2086. StationsModule.runJob("GET_STATION", { stationId }, this)
  2087. .then(station => {
  2088. next(null, station);
  2089. })
  2090. .catch(next);
  2091. },
  2092. (station, next) => {
  2093. if (!station) return next("Station not found.");
  2094. if (station.theme === newTheme) return next("No change in theme.");
  2095. return stationModel.updateOne(
  2096. { _id: stationId },
  2097. { $set: { theme: newTheme } },
  2098. { runValidators: true },
  2099. next
  2100. );
  2101. },
  2102. (res, next) => {
  2103. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2104. .then(station => next(null, station))
  2105. .catch(next);
  2106. }
  2107. ],
  2108. async (err, station) => {
  2109. if (err) {
  2110. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2111. this.log(
  2112. "ERROR",
  2113. "STATIONS_UPDATE_THEME",
  2114. `Updating station "${stationId}" theme to "${newTheme}" failed. "${err}"`
  2115. );
  2116. return cb({ status: "error", message: err });
  2117. }
  2118. this.log(
  2119. "SUCCESS",
  2120. "STATIONS_UPDATE_THEME",
  2121. `Updated station "${stationId}" theme to "${newTheme}" successfully.`
  2122. );
  2123. CacheModule.runJob("PUB", {
  2124. channel: "station.themeUpdate",
  2125. value: { stationId }
  2126. });
  2127. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2128. userId: session.userId,
  2129. type: "station__edit_theme",
  2130. payload: {
  2131. message: `Changed theme of station <stationId>${station.displayName}</stationId> to ${newTheme}`,
  2132. stationId
  2133. }
  2134. });
  2135. return cb({
  2136. status: "success",
  2137. message: "Successfully updated the theme."
  2138. });
  2139. }
  2140. );
  2141. }),
  2142. /**
  2143. * Pauses a station
  2144. *
  2145. * @param session
  2146. * @param stationId - the station id
  2147. * @param cb
  2148. */
  2149. pause: isOwnerRequired(async function pause(session, stationId, cb) {
  2150. const stationModel = await DBModule.runJob(
  2151. "GET_MODEL",
  2152. {
  2153. modelName: "station"
  2154. },
  2155. this
  2156. );
  2157. async.waterfall(
  2158. [
  2159. next => {
  2160. StationsModule.runJob("GET_STATION", { stationId }, this)
  2161. .then(station => {
  2162. next(null, station);
  2163. })
  2164. .catch(next);
  2165. },
  2166. (station, next) => {
  2167. if (!station) return next("Station not found.");
  2168. if (station.paused) return next("That station was already paused.");
  2169. return stationModel.updateOne(
  2170. { _id: stationId },
  2171. { $set: { paused: true, pausedAt: Date.now() } },
  2172. next
  2173. );
  2174. },
  2175. (res, next) => {
  2176. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2177. .then(station => {
  2178. next(null, station);
  2179. })
  2180. .catch(next);
  2181. }
  2182. ],
  2183. async err => {
  2184. if (err) {
  2185. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2186. this.log("ERROR", "STATIONS_PAUSE", `Pausing station "${stationId}" failed. "${err}"`);
  2187. return cb({ status: "error", message: err });
  2188. }
  2189. this.log("SUCCESS", "STATIONS_PAUSE", `Paused station "${stationId}" successfully.`);
  2190. CacheModule.runJob("PUB", {
  2191. channel: "station.pause",
  2192. value: stationId
  2193. });
  2194. NotificationsModule.runJob("UNSCHEDULE", {
  2195. name: `stations.nextSong?id=${stationId}`
  2196. });
  2197. return cb({
  2198. status: "success",
  2199. message: "Successfully paused."
  2200. });
  2201. }
  2202. );
  2203. }),
  2204. /**
  2205. * Resumes a station
  2206. *
  2207. * @param session
  2208. * @param stationId - the station id
  2209. * @param cb
  2210. */
  2211. resume: isOwnerRequired(async function resume(session, stationId, cb) {
  2212. const stationModel = await DBModule.runJob(
  2213. "GET_MODEL",
  2214. {
  2215. modelName: "station"
  2216. },
  2217. this
  2218. );
  2219. async.waterfall(
  2220. [
  2221. next => {
  2222. StationsModule.runJob("GET_STATION", { stationId }, this)
  2223. .then(station => {
  2224. next(null, station);
  2225. })
  2226. .catch(next);
  2227. },
  2228. (station, next) => {
  2229. if (!station) return next("Station not found.");
  2230. if (!station.paused) return next("That station is not paused.");
  2231. station.timePaused += Date.now() - station.pausedAt;
  2232. return stationModel.updateOne(
  2233. { _id: stationId },
  2234. {
  2235. $set: { paused: false },
  2236. $inc: { timePaused: Date.now() - station.pausedAt }
  2237. },
  2238. next
  2239. );
  2240. },
  2241. (res, next) => {
  2242. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2243. .then(station => {
  2244. next(null, station);
  2245. })
  2246. .catch(next);
  2247. }
  2248. ],
  2249. async err => {
  2250. if (err) {
  2251. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2252. this.log("ERROR", "STATIONS_RESUME", `Resuming station "${stationId}" failed. "${err}"`);
  2253. return cb({ status: "error", message: err });
  2254. }
  2255. this.log("SUCCESS", "STATIONS_RESUME", `Resuming station "${stationId}" successfully.`);
  2256. CacheModule.runJob("PUB", {
  2257. channel: "station.resume",
  2258. value: stationId
  2259. });
  2260. return cb({
  2261. status: "success",
  2262. message: "Successfully resumed."
  2263. });
  2264. }
  2265. );
  2266. }),
  2267. /**
  2268. * Removes a station
  2269. *
  2270. * @param session
  2271. * @param stationId - the station id
  2272. * @param cb
  2273. */
  2274. remove: isOwnerRequired(async function remove(session, stationId, cb) {
  2275. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2276. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2277. async.waterfall(
  2278. [
  2279. next => {
  2280. stationModel.findById(stationId, (err, station) => {
  2281. if (err) return next(err);
  2282. return next(null, station);
  2283. });
  2284. },
  2285. (station, next) => {
  2286. stationModel.deleteOne({ _id: stationId }, err => next(err, station));
  2287. },
  2288. (station, next) => {
  2289. CacheModule.runJob("HDEL", { table: "stations", key: stationId }, this)
  2290. .then(() => next(null, station))
  2291. .catch(next);
  2292. },
  2293. // remove the playlist for the station
  2294. (station, next) => {
  2295. if (station.playlist)
  2296. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: station.playlist })
  2297. .then(() => {})
  2298. .catch(next);
  2299. next(null, station);
  2300. },
  2301. // remove reference to the station id in any array of a user's favorite stations
  2302. (station, next) => {
  2303. userModel.updateMany(
  2304. { favoriteStations: stationId },
  2305. { $pull: { favoriteStations: stationId } },
  2306. err => next(err, station)
  2307. );
  2308. }
  2309. ],
  2310. async (err, station) => {
  2311. if (err) {
  2312. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2313. this.log("ERROR", "STATIONS_REMOVE", `Removing station "${stationId}" failed. "${err}"`);
  2314. return cb({ status: "error", message: err });
  2315. }
  2316. this.log("SUCCESS", "STATIONS_REMOVE", `Removing station "${stationId}" successfully.`);
  2317. CacheModule.runJob("PUB", {
  2318. channel: "station.remove",
  2319. value: stationId
  2320. });
  2321. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2322. userId: session.userId,
  2323. type: "station__remove",
  2324. payload: { message: `Removed a station named ${station.displayName}` }
  2325. });
  2326. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "stationId", stationId });
  2327. return cb({
  2328. status: "success",
  2329. message: "Successfully removed."
  2330. });
  2331. }
  2332. );
  2333. }),
  2334. /**
  2335. * Create a station
  2336. *
  2337. * @param session
  2338. * @param data - the station data
  2339. * @param cb
  2340. */
  2341. create: isLoginRequired(async function create(session, data, cb) {
  2342. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2343. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2344. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  2345. data.name = data.name.toLowerCase();
  2346. const blacklist = [
  2347. "country",
  2348. "edm",
  2349. "musare",
  2350. "hip-hop",
  2351. "rap",
  2352. "top-hits",
  2353. "todays-hits",
  2354. "old-school",
  2355. "christmas",
  2356. "about",
  2357. "support",
  2358. "staff",
  2359. "help",
  2360. "news",
  2361. "terms",
  2362. "privacy",
  2363. "profile",
  2364. "c",
  2365. "community",
  2366. "tos",
  2367. "login",
  2368. "register",
  2369. "p",
  2370. "official",
  2371. "o",
  2372. "trap",
  2373. "faq",
  2374. "team",
  2375. "donate",
  2376. "buy",
  2377. "shop",
  2378. "forums",
  2379. "explore",
  2380. "settings",
  2381. "admin",
  2382. "auth",
  2383. "reset_password",
  2384. "backend",
  2385. "api",
  2386. "songs",
  2387. "playlists",
  2388. "playlist"
  2389. ];
  2390. async.waterfall(
  2391. [
  2392. next => {
  2393. if (!data) return next("Invalid data.");
  2394. return next();
  2395. },
  2396. next => {
  2397. stationModel.findOne(
  2398. {
  2399. $or: [
  2400. { name: data.name },
  2401. {
  2402. displayName: new RegExp(`^${data.displayName}$`, "i")
  2403. }
  2404. ]
  2405. },
  2406. next
  2407. );
  2408. },
  2409. // eslint-disable-next-line consistent-return
  2410. (station, next) => {
  2411. this.log(station);
  2412. if (station) return next("A station with that name or display name already exists.");
  2413. const { name, displayName, description, /* playlist, */ type, genres, blacklistedGenres } = data;
  2414. const stationId = mongoose.Types.ObjectId();
  2415. if (type === "official") {
  2416. return userModel.findOne({ _id: session.userId }, (err, user) => {
  2417. if (err) return next(err);
  2418. if (!user) return next("User not found.");
  2419. if (user.role !== "admin") return next("Admin required.");
  2420. return async.waterfall(
  2421. [
  2422. next => {
  2423. const playlists = [];
  2424. async.eachLimit(
  2425. genres,
  2426. 1,
  2427. (genre, next) => {
  2428. PlaylistsModule.runJob(
  2429. "GET_GENRE_PLAYLIST",
  2430. { genre, includeSongs: false },
  2431. this
  2432. )
  2433. .then(response => {
  2434. playlists.push(response.playlist);
  2435. next();
  2436. })
  2437. .catch(err => {
  2438. next(
  2439. `An error occurred when trying to get genre playlist for genre ${genre}. Error: ${err}.`
  2440. );
  2441. });
  2442. },
  2443. err => {
  2444. next(
  2445. err,
  2446. playlists.map(playlist => playlist._id.toString())
  2447. );
  2448. }
  2449. );
  2450. },
  2451. (genrePlaylistIds, next) => {
  2452. const playlists = [];
  2453. async.eachLimit(
  2454. blacklistedGenres,
  2455. 1,
  2456. (genre, next) => {
  2457. PlaylistsModule.runJob(
  2458. "GET_GENRE_PLAYLIST",
  2459. { genre, includeSongs: false },
  2460. this
  2461. )
  2462. .then(response => {
  2463. playlists.push(response.playlist);
  2464. next();
  2465. })
  2466. .catch(err => {
  2467. next(
  2468. `An error occurred when trying to get genre playlist for genre ${genre}. Error: ${err}.`
  2469. );
  2470. });
  2471. },
  2472. err => {
  2473. next(
  2474. err,
  2475. genrePlaylistIds,
  2476. playlists.map(playlist => playlist._id.toString())
  2477. );
  2478. }
  2479. );
  2480. },
  2481. (genrePlaylistIds, blacklistedGenrePlaylistIds, next) => {
  2482. const duplicateGenre =
  2483. genrePlaylistIds.length !== new Set(genrePlaylistIds).size;
  2484. const duplicateBlacklistedGenre =
  2485. genrePlaylistIds.length !== new Set(genrePlaylistIds).size;
  2486. const duplicateCross =
  2487. genrePlaylistIds.length + blacklistedGenrePlaylistIds.length !==
  2488. new Set([...genrePlaylistIds, ...blacklistedGenrePlaylistIds]).size;
  2489. if (duplicateGenre)
  2490. return next("You cannot have the same genre included twice.");
  2491. if (duplicateBlacklistedGenre)
  2492. return next("You cannot have the same blacklisted genre included twice.");
  2493. if (duplicateCross)
  2494. return next(
  2495. "You cannot have the same genre included and blacklisted at the same time."
  2496. );
  2497. return next(null, genrePlaylistIds, blacklistedGenrePlaylistIds);
  2498. }
  2499. ],
  2500. (err, genrePlaylistIds, blacklistedGenrePlaylistIds) => {
  2501. if (err) return next(err);
  2502. return playlistModel.create(
  2503. {
  2504. isUserModifiable: false,
  2505. displayName: `Station - ${displayName}`,
  2506. songs: [],
  2507. createdBy: "Musare",
  2508. createdFor: `${stationId}`,
  2509. createdAt: Date.now(),
  2510. type: "station"
  2511. },
  2512. (err, playlist) => {
  2513. if (err) next(err);
  2514. else {
  2515. stationModel.create(
  2516. {
  2517. _id: stationId,
  2518. name,
  2519. displayName,
  2520. description,
  2521. type,
  2522. privacy: "private",
  2523. playlist: playlist._id,
  2524. currentSong: null,
  2525. partyMode: false,
  2526. playMode: "random"
  2527. },
  2528. (err, station) => {
  2529. next(
  2530. err,
  2531. station,
  2532. genrePlaylistIds,
  2533. blacklistedGenrePlaylistIds
  2534. );
  2535. }
  2536. );
  2537. }
  2538. }
  2539. );
  2540. }
  2541. );
  2542. });
  2543. }
  2544. if (type === "community") {
  2545. if (blacklist.indexOf(name) !== -1)
  2546. return next("That name is blacklisted. Please use a different name.");
  2547. return playlistModel.create(
  2548. {
  2549. isUserModifiable: false,
  2550. displayName: `Station - ${name}`,
  2551. songs: [],
  2552. createdBy: session.userId,
  2553. createdFor: `${stationId}`,
  2554. createdAt: Date.now(),
  2555. type: "station"
  2556. },
  2557. (err, playlist) => {
  2558. if (err) next(err);
  2559. else {
  2560. stationModel.create(
  2561. {
  2562. _id: stationId,
  2563. name,
  2564. displayName,
  2565. description,
  2566. playlist: playlist._id,
  2567. type,
  2568. privacy: "private",
  2569. owner: session.userId,
  2570. queue: [],
  2571. currentSong: null,
  2572. partyMode: true,
  2573. playMode: "random"
  2574. },
  2575. (err, station) => {
  2576. next(err, station, null, null);
  2577. }
  2578. );
  2579. }
  2580. }
  2581. );
  2582. }
  2583. },
  2584. (station, genrePlaylistIds, blacklistedGenrePlaylistIds, next) => {
  2585. if (station.type !== "official") return next(null, station);
  2586. const stationId = station._id;
  2587. console.log(111, station, genrePlaylistIds, blacklistedGenrePlaylistIds, next);
  2588. return async.waterfall(
  2589. [
  2590. next => {
  2591. async.eachLimit(
  2592. genrePlaylistIds,
  2593. 1,
  2594. (playlistId, next) => {
  2595. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  2596. .then(() => {
  2597. next();
  2598. })
  2599. .catch(next);
  2600. },
  2601. next
  2602. );
  2603. },
  2604. next => {
  2605. async.eachLimit(
  2606. blacklistedGenrePlaylistIds,
  2607. 1,
  2608. (playlistId, next) => {
  2609. StationsModule.runJob("EXCLUDE_PLAYLIST", { stationId, playlistId }, this)
  2610. .then(() => {
  2611. next();
  2612. })
  2613. .catch(next);
  2614. },
  2615. next
  2616. );
  2617. },
  2618. next => {
  2619. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2620. next();
  2621. }
  2622. ],
  2623. async err => {
  2624. if (err) {
  2625. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2626. this.log(
  2627. "ERROR",
  2628. "STATIONS_CREATE",
  2629. `Created station ${stationId} successfully, but an error occurred during playing including/excluding. Error: ${err}`
  2630. );
  2631. }
  2632. next(null, station, err);
  2633. }
  2634. );
  2635. }
  2636. ],
  2637. async (err, station, extraError) => {
  2638. if (err) {
  2639. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2640. this.log("ERROR", "STATIONS_CREATE", `Creating station failed. "${err}"`);
  2641. cb({ status: "error", message: err });
  2642. } else {
  2643. this.log("SUCCESS", "STATIONS_CREATE", `Created station "${station._id}" successfully.`);
  2644. CacheModule.runJob("PUB", {
  2645. channel: "station.create",
  2646. value: station._id
  2647. });
  2648. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2649. userId: session.userId,
  2650. type: "station__create",
  2651. payload: {
  2652. message: `Created a station named <stationId>${station.displayName}</stationId>`,
  2653. stationId: station._id
  2654. }
  2655. });
  2656. if (!extraError) {
  2657. cb({
  2658. status: "success",
  2659. message: "Successfully created station."
  2660. });
  2661. } else {
  2662. cb({
  2663. status: "success",
  2664. message: `Successfully created station, but with one error at the end: ${extraError}`
  2665. });
  2666. }
  2667. }
  2668. }
  2669. );
  2670. }),
  2671. /**
  2672. * Adds song to station queue
  2673. *
  2674. * @param session
  2675. * @param stationId - the station id
  2676. * @param youtubeId - the song id
  2677. * @param cb
  2678. */
  2679. addToQueue: isLoginRequired(async function addToQueue(session, stationId, youtubeId, cb) {
  2680. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2681. const stationModel = await DBModule.runJob(
  2682. "GET_MODEL",
  2683. {
  2684. modelName: "station"
  2685. },
  2686. this
  2687. );
  2688. async.waterfall(
  2689. [
  2690. next => {
  2691. StationsModule.runJob("GET_STATION", { stationId }, this)
  2692. .then(station => {
  2693. next(null, station);
  2694. })
  2695. .catch(next);
  2696. },
  2697. (station, next) => {
  2698. if (!station) return next("Station not found.");
  2699. if (!station.partyMode) return next("Station is not in party mode.");
  2700. if (station.locked) {
  2701. return userModel.findOne({ _id: session.userId }, (err, user) => {
  2702. if (user.role !== "admin" && station.owner !== session.userId)
  2703. return next("Only owners and admins can add songs to a locked queue.");
  2704. return next(null, station);
  2705. });
  2706. }
  2707. return next(null, station);
  2708. },
  2709. (station, next) => {
  2710. if (station.type !== "community") return next("That station is not a community station.");
  2711. return StationsModule.runJob(
  2712. "CAN_USER_VIEW_STATION",
  2713. {
  2714. station,
  2715. userId: session.userId
  2716. },
  2717. this
  2718. )
  2719. .then(canView => {
  2720. if (canView) return next(null, station);
  2721. return next("Insufficient permissions.");
  2722. })
  2723. .catch(err => next(err));
  2724. },
  2725. (station, next) => {
  2726. if (station.currentSong && station.currentSong.youtubeId === youtubeId)
  2727. return next("That song is currently playing.");
  2728. return async.each(
  2729. station.queue,
  2730. (queueSong, next) => {
  2731. if (queueSong.youtubeId === youtubeId) return next("That song is already in the queue.");
  2732. return next();
  2733. },
  2734. err => next(err, station)
  2735. );
  2736. },
  2737. (station, next) => {
  2738. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  2739. .then(UserModel => {
  2740. UserModel.findOne(
  2741. { _id: session.userId },
  2742. { "preferences.anonymousSongRequests": 1 },
  2743. (err, user) => next(err, station, user)
  2744. );
  2745. })
  2746. .catch(next);
  2747. },
  2748. (station, user, next) => {
  2749. SongsModule.runJob(
  2750. "ENSURE_SONG_EXISTS_BY_YOUTUBE_ID",
  2751. {
  2752. youtubeId,
  2753. userId: user.preferences.anonymousSongRequests ? null : session.userId,
  2754. automaticallyRequested: true
  2755. },
  2756. this
  2757. )
  2758. .then(response => {
  2759. const { song } = response;
  2760. const { _id, title, artists, thumbnail, duration, status } = song;
  2761. next(
  2762. null,
  2763. {
  2764. _id,
  2765. youtubeId,
  2766. title,
  2767. artists,
  2768. thumbnail,
  2769. duration,
  2770. status
  2771. },
  2772. station
  2773. );
  2774. })
  2775. .catch(next);
  2776. },
  2777. (song, station, next) => {
  2778. const excludedPlaylists = [];
  2779. async.eachLimit(
  2780. station.excludedPlaylists,
  2781. 1,
  2782. (playlistId, next) => {
  2783. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  2784. .then(playlist => {
  2785. excludedPlaylists.push(playlist);
  2786. next();
  2787. })
  2788. .catch(next);
  2789. },
  2790. err => {
  2791. next(err, song, station, excludedPlaylists);
  2792. }
  2793. );
  2794. },
  2795. (song, station, excludedPlaylists, next) => {
  2796. const excludedSongs = excludedPlaylists
  2797. .flatMap(excludedPlaylist => excludedPlaylist.songs)
  2798. .reduce(
  2799. (items, item) =>
  2800. items.find(x => x.youtubeId === item.youtubeId) ? [...items] : [...items, item],
  2801. []
  2802. );
  2803. if (excludedSongs.find(excludedSong => excludedSong._id.toString() === song._id.toString()))
  2804. next("That song is in an excluded playlist and cannot be played.");
  2805. else next(null, song, station);
  2806. },
  2807. (song, station, next) => {
  2808. song.requestedBy = session.userId;
  2809. song.requestedAt = Date.now();
  2810. let totalDuration = 0;
  2811. station.queue.forEach(song => {
  2812. totalDuration += song.duration;
  2813. });
  2814. if (totalDuration >= 3600 * 3) return next("The max length of the queue is 3 hours.");
  2815. return next(null, song, station);
  2816. },
  2817. (song, station, next) => {
  2818. if (station.queue.length === 0) return next(null, song, station);
  2819. let totalDuration = 0;
  2820. const userId = station.queue[station.queue.length - 1].requestedBy;
  2821. station.queue.forEach(song => {
  2822. if (userId === song.requestedBy) {
  2823. totalDuration += song.duration;
  2824. }
  2825. });
  2826. if (totalDuration >= 900) return next("The max length of songs per user is 15 minutes.");
  2827. return next(null, song, station);
  2828. },
  2829. (song, station, next) => {
  2830. if (station.queue.length === 0) return next(null, song);
  2831. let totalSongs = 0;
  2832. const userId = station.queue[station.queue.length - 1].requestedBy;
  2833. station.queue.forEach(song => {
  2834. if (userId === song.requestedBy) {
  2835. totalSongs += 1;
  2836. }
  2837. });
  2838. if (totalSongs <= 2) return next(null, song);
  2839. if (totalSongs > 3)
  2840. return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  2841. if (
  2842. station.queue[station.queue.length - 2].requestedBy !== userId ||
  2843. station.queue[station.queue.length - 3] !== userId
  2844. )
  2845. return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  2846. return next(null, song);
  2847. },
  2848. (song, next) => {
  2849. stationModel.updateOne(
  2850. { _id: stationId },
  2851. { $push: { queue: song } },
  2852. { runValidators: true },
  2853. next
  2854. );
  2855. },
  2856. (res, next) => {
  2857. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2858. .then(station => next(null, station))
  2859. .catch(next);
  2860. }
  2861. // (res, next) => {
  2862. // StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2863. // .then(station => {
  2864. // next(null, station);
  2865. // })
  2866. // .catch(next);
  2867. // }
  2868. ],
  2869. async err => {
  2870. if (err) {
  2871. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2872. this.log(
  2873. "ERROR",
  2874. "STATIONS_ADD_SONG_TO_QUEUE",
  2875. `Adding song "${youtubeId}" to station "${stationId}" queue failed. "${err}"`
  2876. );
  2877. return cb({ status: "error", message: err });
  2878. }
  2879. this.log(
  2880. "SUCCESS",
  2881. "STATIONS_ADD_SONG_TO_QUEUE",
  2882. `Added song "${youtubeId}" to station "${stationId}" successfully.`
  2883. );
  2884. CacheModule.runJob("PUB", {
  2885. channel: "station.queueUpdate",
  2886. value: stationId
  2887. });
  2888. return cb({
  2889. status: "success",
  2890. message: "Successfully added song to queue."
  2891. });
  2892. }
  2893. );
  2894. }),
  2895. /**
  2896. * Removes song from station queue
  2897. *
  2898. * @param session
  2899. * @param stationId - the station id
  2900. * @param youtubeId - the youtube id
  2901. * @param cb
  2902. */
  2903. removeFromQueue: isOwnerRequired(async function removeFromQueue(session, stationId, youtubeId, cb) {
  2904. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2905. async.waterfall(
  2906. [
  2907. next => {
  2908. if (!youtubeId) return next("Invalid youtube id.");
  2909. return StationsModule.runJob("GET_STATION", { stationId }, this)
  2910. .then(station => next(null, station))
  2911. .catch(next);
  2912. },
  2913. (station, next) => {
  2914. if (!station) return next("Station not found.");
  2915. return async.each(
  2916. station.queue,
  2917. (queueSong, next) => {
  2918. if (queueSong.youtubeId === youtubeId) return next(true);
  2919. return next();
  2920. },
  2921. err => {
  2922. if (err === true) return next();
  2923. return next("Song is not currently in the queue.");
  2924. }
  2925. );
  2926. },
  2927. next => {
  2928. stationModel.updateOne({ _id: stationId }, { $pull: { queue: { youtubeId } } }, next);
  2929. },
  2930. (res, next) => {
  2931. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2932. .then(station => next(null, station))
  2933. .catch(next);
  2934. }
  2935. ],
  2936. async err => {
  2937. if (err) {
  2938. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2939. this.log(
  2940. "ERROR",
  2941. "STATIONS_REMOVE_SONG_TO_QUEUE",
  2942. `Removing song "${youtubeId}" from station "${stationId}" queue failed. "${err}"`
  2943. );
  2944. return cb({ status: "error", message: err });
  2945. }
  2946. this.log(
  2947. "SUCCESS",
  2948. "STATIONS_REMOVE_SONG_TO_QUEUE",
  2949. `Removed song "${youtubeId}" from station "${stationId}" successfully.`
  2950. );
  2951. CacheModule.runJob("PUB", {
  2952. channel: "station.queueUpdate",
  2953. value: stationId
  2954. });
  2955. return cb({
  2956. status: "success",
  2957. message: "Successfully removed song from queue."
  2958. });
  2959. }
  2960. );
  2961. }),
  2962. /**
  2963. * Gets the queue from a station
  2964. *
  2965. * @param {object} session - user session
  2966. * @param {string} stationId - the station id
  2967. * @param {Function} cb - callback
  2968. */
  2969. getQueue(session, stationId, cb) {
  2970. async.waterfall(
  2971. [
  2972. next => {
  2973. StationsModule.runJob("GET_STATION", { stationId }, this)
  2974. .then(station => next(null, station))
  2975. .catch(next);
  2976. },
  2977. (station, next) => {
  2978. if (!station) return next("Station not found.");
  2979. return next(null, station);
  2980. },
  2981. (station, next) => {
  2982. StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  2983. .then(canView => {
  2984. if (canView) return next(null, station);
  2985. return next("Insufficient permissions.");
  2986. })
  2987. .catch(err => next(err));
  2988. },
  2989. (station, next) => {
  2990. if (station.type === "official") next(null, station.queue);
  2991. else next(null, station.queue);
  2992. }
  2993. ],
  2994. async (err, queue) => {
  2995. if (err) {
  2996. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2997. this.log(
  2998. "ERROR",
  2999. "STATIONS_GET_QUEUE",
  3000. `Getting queue for station "${stationId}" failed. "${err}"`
  3001. );
  3002. return cb({ status: "error", message: err });
  3003. }
  3004. this.log("SUCCESS", "STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  3005. return cb({
  3006. status: "success",
  3007. message: "Successfully got queue.",
  3008. data: { queue }
  3009. });
  3010. }
  3011. );
  3012. },
  3013. /**
  3014. * Reposition a song in station queue
  3015. *
  3016. * @param {object} session - user session
  3017. * @param {object} song - contains details about the song that is to be repositioned
  3018. * @param {string} song.youtubeId - the youtube id of the song
  3019. * @param {number} song.newIndex - the new position for the song in the queue
  3020. * @param {number} song.oldIndex - the old position of the song in the queue
  3021. * @param {string} stationId - the station id
  3022. * @param {Function} cb - callback
  3023. */
  3024. repositionSongInQueue: isOwnerRequired(async function repositionQueue(session, stationId, song, cb) {
  3025. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  3026. async.waterfall(
  3027. [
  3028. next => {
  3029. if (!song || !song.youtubeId) return next("You must provide a song to reposition.");
  3030. return next();
  3031. },
  3032. // remove song from queue
  3033. next => {
  3034. stationModel.updateOne(
  3035. { _id: stationId },
  3036. { $pull: { queue: { youtubeId: song.youtubeId } } },
  3037. next
  3038. );
  3039. },
  3040. // add song back to queue (in new position)
  3041. (res, next) => {
  3042. stationModel.updateOne(
  3043. { _id: stationId },
  3044. { $push: { queue: { $each: [song], $position: song.newIndex } } },
  3045. err => next(err)
  3046. );
  3047. },
  3048. // update the cache representation of the station
  3049. next => {
  3050. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  3051. .then(station => next(null, station))
  3052. .catch(next);
  3053. }
  3054. ],
  3055. async err => {
  3056. if (err) {
  3057. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3058. this.log(
  3059. "ERROR",
  3060. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  3061. `Repositioning song ${song.youtubeId} in queue of station "${stationId}" failed. "${err}"`
  3062. );
  3063. return cb({ status: "error", message: err });
  3064. }
  3065. this.log(
  3066. "SUCCESS",
  3067. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  3068. `Repositioned song ${song.youtubeId} in queue of station "${stationId}" successfully.`
  3069. );
  3070. CacheModule.runJob("PUB", {
  3071. channel: "station.repositionSongInQueue",
  3072. value: {
  3073. song: {
  3074. youtubeId: song.youtubeId,
  3075. oldIndex: song.oldIndex,
  3076. newIndex: song.newIndex
  3077. },
  3078. stationId
  3079. }
  3080. });
  3081. return cb({
  3082. status: "success",
  3083. message: "Successfully repositioned song in queue."
  3084. });
  3085. }
  3086. );
  3087. }),
  3088. /**
  3089. * Includes a playlist in a station
  3090. *
  3091. * @param session
  3092. * @param stationId - the station id
  3093. * @param playlistId - the playlist id
  3094. * @param cb
  3095. */
  3096. includePlaylist: isOwnerRequired(async function includePlaylist(session, stationId, playlistId, cb) {
  3097. async.waterfall(
  3098. [
  3099. next => {
  3100. StationsModule.runJob("GET_STATION", { stationId }, this)
  3101. .then(station => next(null, station))
  3102. .catch(next);
  3103. },
  3104. (station, next) => {
  3105. if (!station) return next("Station not found.");
  3106. if (station.includedPlaylists.indexOf(playlistId) !== -1)
  3107. return next("That playlist is already included.");
  3108. if (station.playMode === "sequential" && station.includedPlaylists.length > 0)
  3109. return next("Error: Only 1 playlist can be included in sequential play mode.");
  3110. return next();
  3111. },
  3112. next => {
  3113. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  3114. .then(() => {
  3115. next();
  3116. })
  3117. .catch(next);
  3118. }
  3119. ],
  3120. async err => {
  3121. if (err) {
  3122. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3123. this.log(
  3124. "ERROR",
  3125. "STATIONS_INCLUDE_PLAYLIST",
  3126. `Including playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3127. );
  3128. return cb({ status: "error", message: err });
  3129. }
  3130. this.log(
  3131. "SUCCESS",
  3132. "STATIONS_INCLUDE_PLAYLIST",
  3133. `Including playlist "${playlistId}" for station "${stationId}" successfully.`
  3134. );
  3135. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3136. CacheModule.runJob("PUB", {
  3137. channel: "station.includedPlaylist",
  3138. value: {
  3139. playlistId,
  3140. stationId
  3141. }
  3142. });
  3143. return cb({
  3144. status: "success",
  3145. message: "Successfully included playlist."
  3146. });
  3147. }
  3148. );
  3149. }),
  3150. /**
  3151. * Remove included a playlist from a station
  3152. *
  3153. * @param session
  3154. * @param stationId - the station id
  3155. * @param playlistId - the playlist id
  3156. * @param cb
  3157. */
  3158. removeIncludedPlaylist: isOwnerRequired(async function removeIncludedPlaylist(session, stationId, playlistId, cb) {
  3159. async.waterfall(
  3160. [
  3161. next => {
  3162. StationsModule.runJob("GET_STATION", { stationId }, this)
  3163. .then(station => next(null, station))
  3164. .catch(next);
  3165. },
  3166. (station, next) => {
  3167. if (!station) return next("Station not found.");
  3168. if (station.includedPlaylists.indexOf(playlistId) === -1)
  3169. return next("That playlist is not included.");
  3170. return next();
  3171. },
  3172. next => {
  3173. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  3174. .then(() => {
  3175. next();
  3176. })
  3177. .catch(next);
  3178. }
  3179. ],
  3180. async err => {
  3181. if (err) {
  3182. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3183. this.log(
  3184. "ERROR",
  3185. "STATIONS_REMOVE_INCLUDED_PLAYLIST",
  3186. `Removing included playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3187. );
  3188. return cb({ status: "error", message: err });
  3189. }
  3190. this.log(
  3191. "SUCCESS",
  3192. "STATIONS_REMOVE_INCLUDED_PLAYLIST",
  3193. `Removing included playlist "${playlistId}" for station "${stationId}" successfully.`
  3194. );
  3195. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3196. CacheModule.runJob("PUB", {
  3197. channel: "station.removedIncludedPlaylist",
  3198. value: {
  3199. playlistId,
  3200. stationId
  3201. }
  3202. });
  3203. return cb({
  3204. status: "success",
  3205. message: "Successfully removed included playlist."
  3206. });
  3207. }
  3208. );
  3209. }),
  3210. /**
  3211. * Excludes a playlist in a station
  3212. *
  3213. * @param session
  3214. * @param stationId - the station id
  3215. * @param playlistId - the playlist id
  3216. * @param cb
  3217. */
  3218. excludePlaylist: isOwnerRequired(async function excludePlaylist(session, stationId, playlistId, cb) {
  3219. async.waterfall(
  3220. [
  3221. next => {
  3222. StationsModule.runJob("GET_STATION", { stationId }, this)
  3223. .then(station => next(null, station))
  3224. .catch(next);
  3225. },
  3226. (station, next) => {
  3227. if (!station) return next("Station not found.");
  3228. if (station.excludedPlaylists.indexOf(playlistId) !== -1)
  3229. return next("That playlist is already excluded.");
  3230. return next();
  3231. },
  3232. next => {
  3233. StationsModule.runJob("EXCLUDE_PLAYLIST", { stationId, playlistId }, this)
  3234. .then(() => {
  3235. next();
  3236. })
  3237. .catch(next);
  3238. }
  3239. ],
  3240. async err => {
  3241. if (err) {
  3242. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3243. this.log(
  3244. "ERROR",
  3245. "STATIONS_EXCLUDE_PLAYLIST",
  3246. `Excluding playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3247. );
  3248. return cb({ status: "error", message: err });
  3249. }
  3250. this.log(
  3251. "SUCCESS",
  3252. "STATIONS_EXCLUDE_PLAYLIST",
  3253. `Excluding playlist "${playlistId}" for station "${stationId}" successfully.`
  3254. );
  3255. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3256. CacheModule.runJob("PUB", {
  3257. channel: "station.excludedPlaylist",
  3258. value: {
  3259. playlistId,
  3260. stationId
  3261. }
  3262. });
  3263. return cb({
  3264. status: "success",
  3265. message: "Successfully excluded playlist."
  3266. });
  3267. }
  3268. );
  3269. }),
  3270. /**
  3271. * Remove excluded a playlist from a station
  3272. *
  3273. * @param session
  3274. * @param stationId - the station id
  3275. * @param playlistId - the playlist id
  3276. * @param cb
  3277. */
  3278. removeExcludedPlaylist: isOwnerRequired(async function removeExcludedPlaylist(session, stationId, playlistId, cb) {
  3279. async.waterfall(
  3280. [
  3281. next => {
  3282. StationsModule.runJob("GET_STATION", { stationId }, this)
  3283. .then(station => next(null, station))
  3284. .catch(next);
  3285. },
  3286. (station, next) => {
  3287. if (!station) return next("Station not found.");
  3288. if (station.excludedPlaylists.indexOf(playlistId) === -1)
  3289. return next("That playlist is not excluded.");
  3290. return next();
  3291. },
  3292. next => {
  3293. StationsModule.runJob("REMOVE_EXCLUDED_PLAYLIST", { stationId, playlistId }, this)
  3294. .then(() => {
  3295. next();
  3296. })
  3297. .catch(next);
  3298. }
  3299. ],
  3300. async err => {
  3301. if (err) {
  3302. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3303. this.log(
  3304. "ERROR",
  3305. "STATIONS_REMOVE_EXCLUDED_PLAYLIST",
  3306. `Removing excluded playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3307. );
  3308. return cb({ status: "error", message: err });
  3309. }
  3310. this.log(
  3311. "SUCCESS",
  3312. "STATIONS_REMOVE_EXCLUDED_PLAYLIST",
  3313. `Removing excluded playlist "${playlistId}" for station "${stationId}" successfully.`
  3314. );
  3315. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3316. CacheModule.runJob("PUB", {
  3317. channel: "station.removedExcludedPlaylist",
  3318. value: {
  3319. playlistId,
  3320. stationId
  3321. }
  3322. });
  3323. return cb({
  3324. status: "success",
  3325. message: "Successfully removed excluded playlist."
  3326. });
  3327. }
  3328. );
  3329. }),
  3330. /**
  3331. * Selects a private playlist for a station
  3332. *
  3333. * @param session
  3334. * @param stationId - the station id
  3335. * @param playlistId - the private playlist id
  3336. * @param cb
  3337. */
  3338. selectPrivatePlaylist: isOwnerRequired(async function selectPrivatePlaylist(session, stationId, playlistId, cb) {
  3339. async.waterfall(
  3340. [
  3341. next => {
  3342. StationsModule.runJob("GET_STATION", { stationId }, this)
  3343. .then(station => next(null, station))
  3344. .catch(next);
  3345. },
  3346. (station, next) => {
  3347. if (!station) return next("Station not found.");
  3348. if (station.type !== "community") return next("Station is not a community station.");
  3349. if (station.includedPlaylists.indexOf(playlistId) !== -1)
  3350. return next("That playlist is already included.");
  3351. return next();
  3352. },
  3353. next => {
  3354. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  3355. .then(() => {
  3356. next();
  3357. })
  3358. .catch(next);
  3359. }
  3360. ],
  3361. async err => {
  3362. if (err) {
  3363. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3364. this.log(
  3365. "ERROR",
  3366. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  3367. `Selecting private playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3368. );
  3369. return cb({ status: "error", message: err });
  3370. }
  3371. this.log(
  3372. "SUCCESS",
  3373. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  3374. `Selected private playlist "${playlistId}" for station "${stationId}" successfully.`
  3375. );
  3376. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3377. // CacheModule.runJob("PUB", {
  3378. // channel: "privatePlaylist.selected",
  3379. // value: {
  3380. // playlistId,
  3381. // stationId
  3382. // }
  3383. // });
  3384. return cb({
  3385. status: "success",
  3386. message: "Successfully selected playlist."
  3387. });
  3388. }
  3389. );
  3390. }),
  3391. /**
  3392. * Deselects the private playlist selected in a station
  3393. *
  3394. * @param session
  3395. * @param stationId - the station id
  3396. * @param cb
  3397. */
  3398. deselectPrivatePlaylist: isOwnerRequired(async function deselectPrivatePlaylist(
  3399. session,
  3400. stationId,
  3401. playlistId,
  3402. cb
  3403. ) {
  3404. async.waterfall(
  3405. [
  3406. next => {
  3407. StationsModule.runJob("GET_STATION", { stationId }, this)
  3408. .then(station => {
  3409. next(null, station);
  3410. })
  3411. .catch(next);
  3412. },
  3413. (station, next) => {
  3414. if (!station) return next("Station not found.");
  3415. if (station.type !== "community") return next("Station is not a community station.");
  3416. if (station.includedPlaylists.indexOf(playlistId) === -1)
  3417. return next("That playlist is not included.");
  3418. return next();
  3419. },
  3420. next => {
  3421. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  3422. .then(() => {
  3423. next();
  3424. })
  3425. .catch(next);
  3426. }
  3427. ],
  3428. async err => {
  3429. if (err) {
  3430. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3431. this.log(
  3432. "ERROR",
  3433. "STATIONS_DESELECT_PRIVATE_PLAYLIST",
  3434. `Deselecting private playlist for station "${stationId}" failed. "${err}"`
  3435. );
  3436. return cb({ status: "error", message: err });
  3437. }
  3438. this.log(
  3439. "SUCCESS",
  3440. "STATIONS_DESELECT_PRIVATE_PLAYLIST",
  3441. `Deselected private playlist for station "${stationId}" successfully.`
  3442. );
  3443. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3444. // CacheModule.runJob("PUB", {
  3445. // channel: "privatePlaylist.deselected",
  3446. // value: {
  3447. // stationId
  3448. // }
  3449. // });
  3450. return cb({
  3451. status: "success",
  3452. message: "Successfully deselected playlist."
  3453. });
  3454. }
  3455. );
  3456. }),
  3457. favoriteStation: isLoginRequired(async function favoriteStation(session, stationId, cb) {
  3458. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  3459. async.waterfall(
  3460. [
  3461. next => {
  3462. StationsModule.runJob("GET_STATION", { stationId }, this)
  3463. .then(station => next(null, station))
  3464. .catch(next);
  3465. },
  3466. (station, next) => {
  3467. if (!station) return next("Station not found.");
  3468. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  3469. .then(canView => {
  3470. if (canView) return next(null, station);
  3471. return next("Insufficient permissions.");
  3472. })
  3473. .catch(err => next(err));
  3474. },
  3475. (station, next) => {
  3476. userModel.updateOne(
  3477. { _id: session.userId },
  3478. { $addToSet: { favoriteStations: stationId } },
  3479. (err, res) => next(err, station, res)
  3480. );
  3481. },
  3482. (station, res, next) => {
  3483. if (res.nModified === 0) return next("The station was already favorited.");
  3484. return next(null, station);
  3485. }
  3486. ],
  3487. async (err, station) => {
  3488. if (err) {
  3489. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3490. this.log("ERROR", "FAVORITE_STATION", `Favoriting station "${stationId}" failed. "${err}"`);
  3491. return cb({ status: "error", message: err });
  3492. }
  3493. this.log("SUCCESS", "FAVORITE_STATION", `Favorited station "${stationId}" successfully.`);
  3494. CacheModule.runJob("PUB", {
  3495. channel: "user.favoritedStation",
  3496. value: {
  3497. userId: session.userId,
  3498. stationId
  3499. }
  3500. });
  3501. ActivitiesModule.runJob("ADD_ACTIVITY", {
  3502. userId: session.userId,
  3503. type: "station__favorite",
  3504. payload: {
  3505. message: `Favorited station <stationId>${station.displayName}</stationId>`,
  3506. stationId
  3507. }
  3508. });
  3509. return cb({
  3510. status: "success",
  3511. message: "Succesfully favorited station."
  3512. });
  3513. }
  3514. );
  3515. }),
  3516. unfavoriteStation: isLoginRequired(async function unfavoriteStation(session, stationId, cb) {
  3517. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  3518. async.waterfall(
  3519. [
  3520. next => {
  3521. userModel.updateOne({ _id: session.userId }, { $pull: { favoriteStations: stationId } }, next);
  3522. },
  3523. (res, next) => {
  3524. if (res.nModified === 0) return next("The station wasn't favorited.");
  3525. return next();
  3526. },
  3527. next => {
  3528. StationsModule.runJob("GET_STATION", { stationId }, this)
  3529. .then(station => next(null, station))
  3530. .catch(next);
  3531. }
  3532. ],
  3533. async (err, station) => {
  3534. if (err) {
  3535. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3536. this.log("ERROR", "UNFAVORITE_STATION", `Unfavoriting station "${stationId}" failed. "${err}"`);
  3537. return cb({ status: "error", message: err });
  3538. }
  3539. this.log("SUCCESS", "UNFAVORITE_STATION", `Unfavorited station "${stationId}" successfully.`);
  3540. CacheModule.runJob("PUB", {
  3541. channel: "user.unfavoritedStation",
  3542. value: {
  3543. userId: session.userId,
  3544. stationId
  3545. }
  3546. });
  3547. ActivitiesModule.runJob("ADD_ACTIVITY", {
  3548. userId: session.userId,
  3549. type: "station__unfavorite",
  3550. payload: {
  3551. message: `Unfavorited station <stationId>${station.displayName}</stationId>`,
  3552. stationId
  3553. }
  3554. });
  3555. return cb({
  3556. status: "success",
  3557. message: "Succesfully unfavorited station."
  3558. });
  3559. }
  3560. );
  3561. }),
  3562. /**
  3563. * Clears every station queue
  3564. *
  3565. * @param {object} session - the session object automatically added by socket.io
  3566. * @param {Function} cb - gets called with the result
  3567. */
  3568. clearEveryStationQueue: isAdminRequired(async function clearEveryStationQueue(session, cb) {
  3569. async.waterfall(
  3570. [
  3571. next => {
  3572. StationsModule.runJob("CLEAR_EVERY_STATION_QUEUE", {}, this)
  3573. .then(() => next())
  3574. .catch(next);
  3575. }
  3576. ],
  3577. async err => {
  3578. if (err) {
  3579. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3580. this.log("ERROR", "CLEAR_EVERY_STATION_QUEUE", `Clearing every station queue failed. "${err}"`);
  3581. return cb({ status: "error", message: err });
  3582. }
  3583. this.log("SUCCESS", "CLEAR_EVERY_STATION_QUEUE", "Clearing every station queue was successful.");
  3584. return cb({ status: "success", message: "Successfully cleared every station queue." });
  3585. }
  3586. );
  3587. }),
  3588. /**
  3589. * Clears and refills a station queue
  3590. *
  3591. * @param {object} session - the session object automatically added by socket.io
  3592. * @param {string} stationId - the station id
  3593. * @param {Function} cb - gets called with the result
  3594. */
  3595. clearAndRefillStationQueue: isAdminRequired(async function clearAndRefillStationQueue(session, stationId, cb) {
  3596. async.waterfall(
  3597. [
  3598. next => {
  3599. StationsModule.runJob("CLEAR_AND_REFILL_STATION_QUEUE", { stationId }, this)
  3600. .then(() => next())
  3601. .catch(next);
  3602. }
  3603. ],
  3604. async err => {
  3605. if (err) {
  3606. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3607. this.log(
  3608. "ERROR",
  3609. "CLEAR_AND_REFILL_STATION_QUEUE",
  3610. `Clearing and refilling station queue failed. "${err}"`
  3611. );
  3612. return cb({ status: "error", message: err });
  3613. }
  3614. this.log(
  3615. "SUCCESS",
  3616. "CLEAR_AND_REFILL_STATION_QUEUE",
  3617. "Clearing and refilling station queue was successful."
  3618. );
  3619. return cb({ status: "success", message: "Successfully cleared and refilled station queue." });
  3620. }
  3621. );
  3622. })
  3623. };