stations.js 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107
  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. getNextSongInfo(session, stationId, songId, cb) {
  903. async.waterfall(
  904. [
  905. next => {
  906. StationsModule.runJob("GET_STATION", { stationId }, this)
  907. .then(station => next(null, station))
  908. .catch(err => {
  909. next(err);
  910. });
  911. },
  912. (station, next) => {
  913. if (!station) return next("Station not found.");
  914. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  915. .then(canView => {
  916. if (!canView) next("Not allowed to get info about station.");
  917. else next(null, station);
  918. })
  919. .catch(err => {
  920. console.log(stationId, station, songId);
  921. next(err);
  922. });
  923. },
  924. (station, next) => {
  925. if (
  926. station.currentSong._id === songId ||
  927. (station.queue.length > 0 && station.queue[0]._id === songId) ||
  928. (station.queue.length > 1 && station.queue[1]._id === songId)
  929. ) {
  930. next(null);
  931. } else next("That song is not next.");
  932. },
  933. next => {
  934. SongsModule.runJob("GET_SONG", { songId }, this)
  935. .then(response => {
  936. const { song } = response;
  937. const nextSong = {
  938. _id: song._id,
  939. youtubeId: song.youtubeId,
  940. title: song.title,
  941. artists: song.artists,
  942. duration: song.duration,
  943. likes: song.likes,
  944. dislikes: song.dislikes,
  945. skipDuration: song.skipDuration,
  946. thumbnail: song.thumbnail,
  947. requestedAt: song.requestedAt,
  948. requestedBy: song.requestedBy,
  949. status: song.status
  950. };
  951. next(null, { nextSong });
  952. })
  953. .catch(err => {
  954. next(err);
  955. });
  956. }
  957. ],
  958. async (err, data) => {
  959. if (err) {
  960. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  961. this.log(
  962. "ERROR",
  963. "STATIONS_GET_NEXT_SONG_INFO",
  964. `Getting next song info for station "${stationId}" failed. "${err}"`
  965. );
  966. return cb({ status: "error", message: err });
  967. }
  968. this.log(
  969. "SUCCESS",
  970. "STATIONS_GET_NEXT_SONG_INFO",
  971. `Got next song info for station "${stationId}" successfully.`
  972. );
  973. return cb({ status: "success", data });
  974. }
  975. );
  976. },
  977. /**
  978. * Gets a station by id
  979. *
  980. * @param {object} session - user session
  981. * @param {string} stationId - the station id
  982. * @param {Function} cb - callback
  983. */
  984. getStationById(session, stationId, cb) {
  985. async.waterfall(
  986. [
  987. next => {
  988. StationsModule.runJob("GET_STATION", { stationId }, this)
  989. .then(station => {
  990. next(null, station);
  991. })
  992. .catch(next);
  993. },
  994. (station, next) => {
  995. if (!station) return next("Station not found.");
  996. return StationsModule.runJob(
  997. "CAN_USER_VIEW_STATION",
  998. {
  999. station,
  1000. userId: session.userId
  1001. },
  1002. this
  1003. )
  1004. .then(canView => {
  1005. if (!canView) next("Not allowed to get station.");
  1006. else next(null, station);
  1007. })
  1008. .catch(err => next(err));
  1009. },
  1010. (station, next) => {
  1011. const data = {
  1012. _id: station._id,
  1013. type: station.type,
  1014. description: station.description,
  1015. displayName: station.displayName,
  1016. name: station.name,
  1017. privacy: station.privacy,
  1018. locked: station.locked,
  1019. partyMode: station.partyMode,
  1020. playMode: station.playMode,
  1021. owner: station.owner,
  1022. // privatePlaylist: station.privatePlaylist,
  1023. // genres: station.genres,
  1024. // blacklistedGenres: station.blacklistedGenres,
  1025. theme: station.theme,
  1026. paused: station.paused,
  1027. currentSong: station.currentSong
  1028. };
  1029. next(null, data);
  1030. }
  1031. ],
  1032. async (err, data) => {
  1033. if (err) {
  1034. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1035. this.log("ERROR", "GET_STATION_BY_ID", `Getting station "${stationId}" failed. "${err}"`);
  1036. return cb({ status: "error", message: err });
  1037. }
  1038. this.log("SUCCESS", "GET_STATION_BY_ID", `Got station "${stationId}" successfully.`);
  1039. return cb({ status: "success", data: { station: data } });
  1040. }
  1041. );
  1042. },
  1043. getStationIncludedPlaylistsById(session, stationId, cb) {
  1044. async.waterfall(
  1045. [
  1046. next => {
  1047. StationsModule.runJob("GET_STATION", { stationId }, this)
  1048. .then(station => {
  1049. next(null, station);
  1050. })
  1051. .catch(next);
  1052. },
  1053. (station, next) => {
  1054. if (!station) return next("Station not found.");
  1055. return StationsModule.runJob(
  1056. "CAN_USER_VIEW_STATION",
  1057. {
  1058. station,
  1059. userId: session.userId
  1060. },
  1061. this
  1062. )
  1063. .then(canView => {
  1064. if (!canView) next("Not allowed to get station.");
  1065. else next(null, station);
  1066. })
  1067. .catch(err => next(err));
  1068. },
  1069. (station, next) => {
  1070. const playlists = [];
  1071. async.eachLimit(
  1072. station.includedPlaylists,
  1073. 1,
  1074. (playlistId, next) => {
  1075. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1076. .then(playlist => {
  1077. playlists.push(playlist);
  1078. next();
  1079. })
  1080. .catch(() => {
  1081. playlists.push(null);
  1082. next();
  1083. });
  1084. },
  1085. err => {
  1086. next(err, playlists);
  1087. }
  1088. );
  1089. }
  1090. ],
  1091. async (err, playlists) => {
  1092. if (err) {
  1093. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1094. this.log(
  1095. "ERROR",
  1096. "GET_STATION_INCLUDED_PLAYLISTS_BY_ID",
  1097. `Getting station "${stationId}"'s included playlists failed. "${err}"`
  1098. );
  1099. return cb({ status: "error", message: err });
  1100. }
  1101. this.log(
  1102. "SUCCESS",
  1103. "GET_STATION_INCLUDED_PLAYLISTS_BY_ID",
  1104. `Got station "${stationId}"'s included playlists successfully.`
  1105. );
  1106. return cb({ status: "success", data: { playlists } });
  1107. }
  1108. );
  1109. },
  1110. getStationExcludedPlaylistsById(session, stationId, cb) {
  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. if (!station) return next("Station not found.");
  1122. return StationsModule.runJob(
  1123. "CAN_USER_VIEW_STATION",
  1124. {
  1125. station,
  1126. userId: session.userId
  1127. },
  1128. this
  1129. )
  1130. .then(canView => {
  1131. if (!canView) next("Not allowed to get station.");
  1132. else next(null, station);
  1133. })
  1134. .catch(err => next(err));
  1135. },
  1136. (station, next) => {
  1137. const playlists = [];
  1138. async.eachLimit(
  1139. station.excludedPlaylists,
  1140. 1,
  1141. (playlistId, next) => {
  1142. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1143. .then(playlist => {
  1144. playlists.push(playlist);
  1145. next();
  1146. })
  1147. .catch(() => {
  1148. playlists.push(null);
  1149. next();
  1150. });
  1151. },
  1152. err => {
  1153. next(err, playlists);
  1154. }
  1155. );
  1156. }
  1157. ],
  1158. async (err, playlists) => {
  1159. if (err) {
  1160. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1161. this.log(
  1162. "ERROR",
  1163. "GET_STATION_EXCLUDED_PLAYLISTS_BY_ID",
  1164. `Getting station "${stationId}"'s excluded playlists failed. "${err}"`
  1165. );
  1166. return cb({ status: "error", message: err });
  1167. }
  1168. this.log(
  1169. "SUCCESS",
  1170. "GET_STATION_EXCLUDED_PLAYLISTS_BY_ID",
  1171. `Got station "${stationId}"'s excluded playlists successfully.`
  1172. );
  1173. return cb({ status: "success", data: { playlists } });
  1174. }
  1175. );
  1176. },
  1177. /**
  1178. * Toggles if a station is locked
  1179. *
  1180. * @param session
  1181. * @param stationId - the station id
  1182. * @param cb
  1183. */
  1184. toggleLock: isOwnerRequired(async function toggleLock(session, stationId, cb) {
  1185. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1186. async.waterfall(
  1187. [
  1188. next => {
  1189. StationsModule.runJob("GET_STATION", { stationId }, this)
  1190. .then(station => {
  1191. next(null, station);
  1192. })
  1193. .catch(next);
  1194. },
  1195. (station, next) => {
  1196. stationModel.updateOne({ _id: stationId }, { $set: { locked: !station.locked } }, next);
  1197. },
  1198. (res, next) => {
  1199. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1200. .then(station => {
  1201. next(null, station);
  1202. })
  1203. .catch(next);
  1204. }
  1205. ],
  1206. async (err, station) => {
  1207. if (err) {
  1208. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1209. this.log(
  1210. "ERROR",
  1211. "STATIONS_UPDATE_LOCKED_STATUS",
  1212. `Toggling the queue lock for station "${stationId}" failed. "${err}"`
  1213. );
  1214. return cb({ status: "error", message: err });
  1215. }
  1216. this.log(
  1217. "SUCCESS",
  1218. "STATIONS_UPDATE_LOCKED_STATUS",
  1219. `Toggled the queue lock for station "${stationId}" successfully to "${station.locked}".`
  1220. );
  1221. CacheModule.runJob("PUB", {
  1222. channel: "station.queueLockToggled",
  1223. value: {
  1224. stationId,
  1225. locked: station.locked
  1226. }
  1227. });
  1228. return cb({ status: "success", data: { locked: station.locked } });
  1229. }
  1230. );
  1231. }),
  1232. /**
  1233. * Votes to skip a station
  1234. *
  1235. * @param session
  1236. * @param stationId - the station id
  1237. * @param cb
  1238. */
  1239. voteSkip: isLoginRequired(async function voteSkip(session, stationId, cb) {
  1240. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1241. let skipVotes = 0;
  1242. let shouldSkip = false;
  1243. async.waterfall(
  1244. [
  1245. next => {
  1246. StationsModule.runJob("GET_STATION", { stationId }, this)
  1247. .then(station => next(null, station))
  1248. .catch(next);
  1249. },
  1250. (station, next) => {
  1251. if (!station) return next("Station not found.");
  1252. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  1253. .then(canView => {
  1254. if (canView) return next(null, station);
  1255. return next("Insufficient permissions.");
  1256. })
  1257. .catch(err => next(err));
  1258. },
  1259. (station, next) => {
  1260. if (!station.currentSong) return next("There is currently no song to skip.");
  1261. if (station.currentSong.skipVotes.indexOf(session.userId) !== -1)
  1262. return next("You have already voted to skip this song.");
  1263. return next(null, station);
  1264. },
  1265. (station, next) => {
  1266. stationModel.updateOne(
  1267. { _id: stationId },
  1268. { $push: { "currentSong.skipVotes": session.userId } },
  1269. next
  1270. );
  1271. },
  1272. (res, next) => {
  1273. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1274. .then(station => {
  1275. next(null, station);
  1276. })
  1277. .catch(next);
  1278. },
  1279. (station, next) => {
  1280. if (!station) return next("Station not found.");
  1281. return next(null, station);
  1282. },
  1283. (station, next) => {
  1284. skipVotes = station.currentSong.skipVotes.length;
  1285. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${stationId}` }, this)
  1286. .then(sockets => next(null, station, sockets))
  1287. .catch(next);
  1288. },
  1289. (station, sockets, next) => {
  1290. if (sockets.length <= skipVotes) {
  1291. shouldSkip = true;
  1292. return next(null, station);
  1293. }
  1294. const users = [];
  1295. return async.each(
  1296. sockets,
  1297. (socketId, next) => {
  1298. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  1299. .then(socket => {
  1300. if (socket.session && socket.session.userId) {
  1301. if (!users.includes(socket.session.userId)) users.push(socket.session.userId);
  1302. } else users.push(socketId);
  1303. return next();
  1304. })
  1305. .catch(next);
  1306. },
  1307. err => {
  1308. if (err) return next(err);
  1309. if (users.length <= skipVotes) shouldSkip = true;
  1310. return next(null, station);
  1311. }
  1312. );
  1313. }
  1314. ],
  1315. async (err, station) => {
  1316. if (err) {
  1317. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1318. this.log("ERROR", "STATIONS_VOTE_SKIP", `Vote skipping station "${stationId}" failed. "${err}"`);
  1319. return cb({ status: "error", message: err });
  1320. }
  1321. this.log("SUCCESS", "STATIONS_VOTE_SKIP", `Vote skipping "${stationId}" successful.`);
  1322. CacheModule.runJob("PUB", {
  1323. channel: "station.voteSkipSong",
  1324. value: stationId
  1325. });
  1326. if (shouldSkip) {
  1327. console.log(111, station);
  1328. WSModule.runJob("EMIT_TO_ROOM", {
  1329. room: `station.${station._id}`,
  1330. args: [
  1331. "event:songs.skip",
  1332. {
  1333. data: {
  1334. skippedSong: station.currentSong
  1335. }
  1336. }
  1337. ]
  1338. });
  1339. StationsModule.runJob("SKIP_STATION", { stationId });
  1340. }
  1341. return cb({
  1342. status: "success",
  1343. message: "Successfully voted to skip the song."
  1344. });
  1345. }
  1346. );
  1347. }),
  1348. /**
  1349. * Force skips a station
  1350. *
  1351. * @param session
  1352. * @param stationId - the station id
  1353. * @param cb
  1354. */
  1355. forceSkip: isOwnerRequired(function forceSkip(session, stationId, cb) {
  1356. async.waterfall(
  1357. [
  1358. next => {
  1359. StationsModule.runJob("GET_STATION", { stationId }, this)
  1360. .then(station => {
  1361. next(null, station);
  1362. })
  1363. .catch(next);
  1364. },
  1365. (station, next) => {
  1366. if (!station) return next("Station not found.");
  1367. return next(null, station);
  1368. }
  1369. ],
  1370. async (err, station) => {
  1371. if (err) {
  1372. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1373. this.log("ERROR", "STATIONS_FORCE_SKIP", `Force skipping station "${stationId}" failed. "${err}"`);
  1374. return cb({ status: "error", message: err });
  1375. }
  1376. WSModule.runJob("EMIT_TO_ROOM", {
  1377. room: `station.${station._id}`,
  1378. args: [
  1379. "event:songs.skip",
  1380. {
  1381. data: {
  1382. skippedSong: station.currentSong
  1383. }
  1384. }
  1385. ]
  1386. });
  1387. StationsModule.runJob("SKIP_STATION", { stationId });
  1388. this.log("SUCCESS", "STATIONS_FORCE_SKIP", `Force skipped station "${stationId}" successfully.`);
  1389. return cb({
  1390. status: "success",
  1391. message: "Successfully skipped station."
  1392. });
  1393. }
  1394. );
  1395. }),
  1396. /**
  1397. * Leaves the user's current station
  1398. *
  1399. * @param {object} session - user session
  1400. * @param {string} stationId - id of station to leave
  1401. * @param {Function} cb - callback
  1402. */
  1403. leave(session, stationId, cb) {
  1404. async.waterfall(
  1405. [
  1406. next => {
  1407. StationsModule.runJob("GET_STATION", { stationId }, this)
  1408. .then(station => {
  1409. next(null, station);
  1410. })
  1411. .catch(next);
  1412. },
  1413. (station, next) => {
  1414. if (!station) return next("Station not found.");
  1415. return next();
  1416. }
  1417. ],
  1418. async (err, userCount) => {
  1419. if (err) {
  1420. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1421. this.log("ERROR", "STATIONS_LEAVE", `Leaving station "${stationId}" failed. "${err}"`);
  1422. return cb({ status: "error", message: err });
  1423. }
  1424. this.log("SUCCESS", "STATIONS_LEAVE", `Left station "${stationId}" successfully.`);
  1425. WSModule.runJob("SOCKET_LEAVE_ROOM", { socketId: session.socketId, room: `station.${stationId}` });
  1426. delete StationsModule.userList[session.socketId];
  1427. return cb({
  1428. status: "success",
  1429. message: "Successfully left station.",
  1430. data: { userCount }
  1431. });
  1432. }
  1433. );
  1434. },
  1435. /**
  1436. * Updates a station's name
  1437. *
  1438. * @param session
  1439. * @param stationId - the station id
  1440. * @param newName - the new station name
  1441. * @param cb
  1442. */
  1443. updateName: isOwnerRequired(async function updateName(session, stationId, newName, cb) {
  1444. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1445. async.waterfall(
  1446. [
  1447. next => {
  1448. stationModel.updateOne(
  1449. { _id: stationId },
  1450. { $set: { name: newName } },
  1451. { runValidators: true },
  1452. next
  1453. );
  1454. },
  1455. (res, next) => {
  1456. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1457. .then(station => next(null, station))
  1458. .catch(next);
  1459. }
  1460. ],
  1461. async (err, station) => {
  1462. if (err) {
  1463. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1464. this.log(
  1465. "ERROR",
  1466. "STATIONS_UPDATE_NAME",
  1467. `Updating station "${stationId}" name to "${newName}" failed. "${err}"`
  1468. );
  1469. return cb({ status: "error", message: err });
  1470. }
  1471. this.log(
  1472. "SUCCESS",
  1473. "STATIONS_UPDATE_NAME",
  1474. `Updated station "${stationId}" name to "${newName}" successfully.`
  1475. );
  1476. CacheModule.runJob("PUB", {
  1477. channel: "station.nameUpdate",
  1478. value: { stationId, name: newName }
  1479. });
  1480. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1481. userId: session.userId,
  1482. type: "station__edit_name",
  1483. payload: {
  1484. message: `Changed name of station <stationId>${station.displayName}</stationId> to ${newName}`,
  1485. stationId
  1486. }
  1487. });
  1488. return cb({
  1489. status: "success",
  1490. message: "Successfully updated the name."
  1491. });
  1492. }
  1493. );
  1494. }),
  1495. /**
  1496. * Updates a station's display name
  1497. *
  1498. * @param session
  1499. * @param stationId - the station id
  1500. * @param newDisplayName - the new station display name
  1501. * @param cb
  1502. */
  1503. updateDisplayName: isOwnerRequired(async function updateDisplayName(session, stationId, newDisplayName, cb) {
  1504. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1505. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1506. async.waterfall(
  1507. [
  1508. next => {
  1509. stationModel.updateOne(
  1510. { _id: stationId },
  1511. { $set: { displayName: newDisplayName } },
  1512. { runValidators: true },
  1513. next
  1514. );
  1515. },
  1516. (res, next) => {
  1517. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1518. .then(station => next(null, station))
  1519. .catch(next);
  1520. },
  1521. (station, next) => {
  1522. playlistModel.updateOne(
  1523. { _id: station.playlist },
  1524. { $set: { displayName: `Station - ${station.displayName}` } },
  1525. err => {
  1526. next(err, station);
  1527. }
  1528. );
  1529. }
  1530. ],
  1531. async err => {
  1532. if (err) {
  1533. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1534. this.log(
  1535. "ERROR",
  1536. "STATIONS_UPDATE_DISPLAY_NAME",
  1537. `Updating station "${stationId}" displayName to "${newDisplayName}" failed. "${err}"`
  1538. );
  1539. return cb({ status: "error", message: err });
  1540. }
  1541. this.log(
  1542. "SUCCESS",
  1543. "STATIONS_UPDATE_DISPLAY_NAME",
  1544. `Updated station "${stationId}" displayName to "${newDisplayName}" successfully.`
  1545. );
  1546. CacheModule.runJob("PUB", {
  1547. channel: "station.displayNameUpdate",
  1548. value: { stationId, displayName: newDisplayName }
  1549. });
  1550. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1551. userId: session.userId,
  1552. type: "station__edit_display_name",
  1553. payload: {
  1554. message: `Changed display name of station <stationId>${newDisplayName}</stationId>`,
  1555. stationId
  1556. }
  1557. });
  1558. return cb({
  1559. status: "success",
  1560. message: "Successfully updated the display name."
  1561. });
  1562. }
  1563. );
  1564. }),
  1565. /**
  1566. * Updates a station's description
  1567. *
  1568. * @param session
  1569. * @param stationId - the station id
  1570. * @param newDescription - the new station description
  1571. * @param cb
  1572. */
  1573. updateDescription: isOwnerRequired(async function updateDescription(session, stationId, newDescription, cb) {
  1574. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1575. async.waterfall(
  1576. [
  1577. next => {
  1578. stationModel.updateOne(
  1579. { _id: stationId },
  1580. { $set: { description: newDescription } },
  1581. { runValidators: true },
  1582. next
  1583. );
  1584. },
  1585. (res, next) => {
  1586. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1587. .then(station => next(null, station))
  1588. .catch(next);
  1589. }
  1590. ],
  1591. async (err, station) => {
  1592. if (err) {
  1593. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1594. this.log(
  1595. "ERROR",
  1596. "STATIONS_UPDATE_DESCRIPTION",
  1597. `Updating station "${stationId}" description to "${newDescription}" failed. "${err}"`
  1598. );
  1599. return cb({ status: "error", message: err });
  1600. }
  1601. this.log(
  1602. "SUCCESS",
  1603. "STATIONS_UPDATE_DESCRIPTION",
  1604. `Updated station "${stationId}" description to "${newDescription}" successfully.`
  1605. );
  1606. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1607. userId: session.userId,
  1608. type: "station__edit_description",
  1609. payload: {
  1610. message: `Changed description of station <stationId>${station.displayName}</stationId> to ${newDescription}`,
  1611. stationId
  1612. }
  1613. });
  1614. CacheModule.runJob("PUB", {
  1615. channel: "station.descriptionUpdate",
  1616. value: { stationId, description: newDescription }
  1617. });
  1618. return cb({
  1619. status: "success",
  1620. message: "Successfully updated the description."
  1621. });
  1622. }
  1623. );
  1624. }),
  1625. /**
  1626. * Updates a station's privacy
  1627. *
  1628. * @param session
  1629. * @param stationId - the station id
  1630. * @param newPrivacy - the new station privacy
  1631. * @param cb
  1632. */
  1633. updatePrivacy: isOwnerRequired(async function updatePrivacy(session, stationId, newPrivacy, cb) {
  1634. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1635. let previousPrivacy = null;
  1636. async.waterfall(
  1637. [
  1638. next => {
  1639. stationModel.findOne({ _id: stationId }, next);
  1640. },
  1641. (station, next) => {
  1642. if (!station) next("No station found.");
  1643. else {
  1644. previousPrivacy = station.privacy;
  1645. next();
  1646. }
  1647. },
  1648. next => {
  1649. stationModel.updateOne(
  1650. { _id: stationId },
  1651. { $set: { privacy: newPrivacy } },
  1652. { runValidators: true },
  1653. next
  1654. );
  1655. },
  1656. (res, next) => {
  1657. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1658. .then(station => next(null, station))
  1659. .catch(next);
  1660. }
  1661. ],
  1662. async (err, station) => {
  1663. if (err) {
  1664. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1665. this.log(
  1666. "ERROR",
  1667. "STATIONS_UPDATE_PRIVACY",
  1668. `Updating station "${stationId}" privacy to "${newPrivacy}" failed. "${err}"`
  1669. );
  1670. return cb({ status: "error", message: err });
  1671. }
  1672. this.log(
  1673. "SUCCESS",
  1674. "STATIONS_UPDATE_PRIVACY",
  1675. `Updated station "${stationId}" privacy to "${newPrivacy}" successfully.`
  1676. );
  1677. CacheModule.runJob("PUB", {
  1678. channel: "station.privacyUpdate",
  1679. value: { stationId, previousPrivacy }
  1680. });
  1681. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1682. userId: session.userId,
  1683. type: "station__edit_privacy",
  1684. payload: {
  1685. message: `Changed privacy of station <stationId>${station.displayName}</stationId> to ${newPrivacy}`,
  1686. stationId
  1687. }
  1688. });
  1689. return cb({
  1690. status: "success",
  1691. message: "Successfully updated the privacy."
  1692. });
  1693. }
  1694. );
  1695. }),
  1696. /**
  1697. * Updates a station's genres
  1698. *
  1699. * @param session
  1700. * @param stationId - the station id
  1701. * @param newGenres - the new station genres
  1702. * @param cb
  1703. */
  1704. updateGenres: isOwnerRequired(async function updateGenres(session, stationId, newGenres, cb) {
  1705. async.waterfall(
  1706. [
  1707. next => {
  1708. StationsModule.runJob("GET_STATION", { stationId }, this)
  1709. .then(station => {
  1710. next(null, station);
  1711. })
  1712. .catch(next);
  1713. },
  1714. (station, next) => {
  1715. const playlists = [];
  1716. async.eachLimit(
  1717. newGenres,
  1718. 1,
  1719. (genre, next) => {
  1720. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre, includeSongs: false }, this)
  1721. .then(response => {
  1722. playlists.push(response.playlist);
  1723. next();
  1724. })
  1725. .catch(err => {
  1726. if (err.message === "Playlist not found")
  1727. next(
  1728. `The genre playlist for "${genre}" was not found. Please ensure that this genre playlist exists.`
  1729. );
  1730. else next(err);
  1731. });
  1732. },
  1733. err => {
  1734. next(
  1735. err,
  1736. station,
  1737. playlists.map(playlist => playlist._id.toString())
  1738. );
  1739. }
  1740. );
  1741. },
  1742. (station, playlists, next) => {
  1743. const playlistsToRemoveFromExcluded = playlists.filter(
  1744. playlistId => station.excludedPlaylists.indexOf(playlistId) !== -1
  1745. );
  1746. console.log(
  1747. `playlistsToRemoveFromExcluded: ${playlistsToRemoveFromExcluded.length}`,
  1748. playlistsToRemoveFromExcluded
  1749. );
  1750. async.eachLimit(
  1751. playlistsToRemoveFromExcluded,
  1752. 1,
  1753. (playlistId, next) => {
  1754. StationsModule.runJob("REMOVE_EXCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1755. .then(() => {
  1756. next();
  1757. })
  1758. .catch(next);
  1759. },
  1760. err => {
  1761. next(err, station, playlists);
  1762. }
  1763. );
  1764. },
  1765. (station, playlists, next) => {
  1766. const playlistsToRemoveFromIncluded = station.includedPlaylists.filter(
  1767. playlistId => playlists.indexOf(playlistId) === -1
  1768. );
  1769. console.log(
  1770. `playlistsToRemoveFromIncluded: ${playlistsToRemoveFromIncluded.length}`,
  1771. playlistsToRemoveFromIncluded
  1772. );
  1773. async.eachLimit(
  1774. playlistsToRemoveFromIncluded,
  1775. 1,
  1776. (playlistId, next) => {
  1777. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1778. .then(() => {
  1779. next();
  1780. })
  1781. .catch(next);
  1782. },
  1783. err => {
  1784. next(err, station, playlists);
  1785. }
  1786. );
  1787. },
  1788. (station, playlists, next) => {
  1789. const playlistsToAddToIncluded = playlists.filter(
  1790. playlistId => station.includedPlaylists.indexOf(playlistId) === -1
  1791. );
  1792. console.log(
  1793. `playlistsToAddToIncluded: ${playlistsToAddToIncluded.length}`,
  1794. playlistsToAddToIncluded
  1795. );
  1796. async.eachLimit(
  1797. playlistsToAddToIncluded,
  1798. 1,
  1799. (playlistId, next) => {
  1800. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  1801. .then(() => {
  1802. next();
  1803. })
  1804. .catch(next);
  1805. },
  1806. err => {
  1807. next(err);
  1808. }
  1809. );
  1810. },
  1811. next => {
  1812. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1813. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1814. .then(station => next(null, station))
  1815. .catch(next);
  1816. }
  1817. ],
  1818. async (err, station) => {
  1819. if (err) {
  1820. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1821. this.log(
  1822. "ERROR",
  1823. "STATIONS_UPDATE_GENRES",
  1824. `Updating station "${stationId}" genres to "${newGenres}" failed. "${err}"`
  1825. );
  1826. return cb({ status: "error", message: err });
  1827. }
  1828. this.log(
  1829. "SUCCESS",
  1830. "STATIONS_UPDATE_GENRES",
  1831. `Updated station "${stationId}" genres to "${newGenres}" successfully.`
  1832. );
  1833. if (newGenres.length > 0) {
  1834. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1835. userId: session.userId,
  1836. type: "station__edit_genres",
  1837. payload: {
  1838. message: `Updated genres of station <stationId>${station.displayName}</stationId> to
  1839. ${newGenres.join(", ")}`,
  1840. stationId
  1841. }
  1842. });
  1843. } else {
  1844. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1845. userId: session.userId,
  1846. type: "station__edit_genres",
  1847. payload: {
  1848. message: `Removed all genres of station <stationId>${station.displayName}</stationId>`,
  1849. stationId
  1850. }
  1851. });
  1852. }
  1853. return cb({
  1854. status: "success",
  1855. message: "Successfully updated the genres."
  1856. });
  1857. }
  1858. );
  1859. }),
  1860. /**
  1861. * Updates a station's blacklisted genres
  1862. *
  1863. * @param session
  1864. * @param stationId - the station id
  1865. * @param newBlacklistedGenres - the new station blacklisted genres
  1866. * @param cb
  1867. */
  1868. updateBlacklistedGenres: isOwnerRequired(async function updateBlacklistedGenres(
  1869. session,
  1870. stationId,
  1871. newBlacklistedGenres,
  1872. cb
  1873. ) {
  1874. async.waterfall(
  1875. [
  1876. next => {
  1877. StationsModule.runJob("GET_STATION", { stationId }, this)
  1878. .then(station => {
  1879. next(null, station);
  1880. })
  1881. .catch(next);
  1882. },
  1883. (station, next) => {
  1884. const playlists = [];
  1885. async.eachLimit(
  1886. newBlacklistedGenres,
  1887. 1,
  1888. (genre, next) => {
  1889. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre, includeSongs: false }, this)
  1890. .then(response => {
  1891. playlists.push(response.playlist);
  1892. next();
  1893. })
  1894. .catch(err => {
  1895. if (err.message === "Playlist not found")
  1896. next(
  1897. `The genre playlist for "${genre}" was not found. Please ensure that this genre playlist exists.`
  1898. );
  1899. else next(err);
  1900. });
  1901. },
  1902. err => {
  1903. next(
  1904. err,
  1905. station,
  1906. playlists.map(playlist => playlist._id.toString())
  1907. );
  1908. }
  1909. );
  1910. },
  1911. (station, playlists, next) => {
  1912. const playlistsToRemoveFromIncluded = playlists.filter(
  1913. playlistId => station.includedPlaylists.indexOf(playlistId) !== -1
  1914. );
  1915. console.log(
  1916. `playlistsToRemoveFromIncluded: ${playlistsToRemoveFromIncluded.length}`,
  1917. playlistsToRemoveFromIncluded
  1918. );
  1919. async.eachLimit(
  1920. playlistsToRemoveFromIncluded,
  1921. 1,
  1922. (playlistId, next) => {
  1923. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1924. .then(() => {
  1925. next();
  1926. })
  1927. .catch(next);
  1928. },
  1929. err => {
  1930. next(err, station, playlists);
  1931. }
  1932. );
  1933. },
  1934. (station, playlists, next) => {
  1935. const playlistsToRemoveFromExcluded = station.excludedPlaylists.filter(
  1936. playlistId => playlists.indexOf(playlistId) === -1
  1937. );
  1938. console.log(
  1939. `playlistsToRemoveFromExcluded: ${playlistsToRemoveFromExcluded.length}`,
  1940. playlistsToRemoveFromExcluded
  1941. );
  1942. async.eachLimit(
  1943. playlistsToRemoveFromExcluded,
  1944. 1,
  1945. (playlistId, next) => {
  1946. StationsModule.runJob("REMOVE_EXCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1947. .then(() => {
  1948. next();
  1949. })
  1950. .catch(next);
  1951. },
  1952. err => {
  1953. next(err, station, playlists);
  1954. }
  1955. );
  1956. },
  1957. (station, playlists, next) => {
  1958. const playlistsToAddToExcluded = playlists.filter(
  1959. playlistId => station.excludedPlaylists.indexOf(playlistId) === -1
  1960. );
  1961. console.log(
  1962. `playlistsToAddToExcluded: ${playlistsToAddToExcluded.length}`,
  1963. playlistsToAddToExcluded
  1964. );
  1965. async.eachLimit(
  1966. playlistsToAddToExcluded,
  1967. 1,
  1968. (playlistId, next) => {
  1969. StationsModule.runJob("EXCLUDE_PLAYLIST", { stationId, playlistId }, this)
  1970. .then(() => {
  1971. next();
  1972. })
  1973. .catch(next);
  1974. },
  1975. err => {
  1976. next(err);
  1977. }
  1978. );
  1979. },
  1980. next => {
  1981. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1982. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1983. .then(station => next(null, station))
  1984. .catch(next);
  1985. }
  1986. ],
  1987. async (err, station) => {
  1988. if (err) {
  1989. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1990. this.log(
  1991. "ERROR",
  1992. "STATIONS_UPDATE_BLACKLISTED_GENRES",
  1993. `Updating station "${stationId}" blacklisted genres to "${newBlacklistedGenres}" failed. "${err}"`
  1994. );
  1995. return cb({ status: "error", message: err });
  1996. }
  1997. this.log(
  1998. "SUCCESS",
  1999. "STATIONS_UPDATE_BLACKLISTED_GENRES",
  2000. `Updated station "${stationId}" blacklisted genres to "${newBlacklistedGenres}" successfully.`
  2001. );
  2002. if (newBlacklistedGenres.length > 0) {
  2003. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2004. userId: session.userId,
  2005. type: "station__edit_blacklisted_genres",
  2006. payload: {
  2007. message: `Updated blacklisted genres of station <stationId>${
  2008. station.displayName
  2009. }</stationId> to ${newBlacklistedGenres.join(", ")}`,
  2010. stationId
  2011. }
  2012. });
  2013. } else {
  2014. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2015. userId: session.userId,
  2016. type: "station__edit_blacklisted_genres",
  2017. payload: {
  2018. message: `Removed all blacklisted genres of station <stationId>${station.displayName}</stationId>`,
  2019. stationId
  2020. }
  2021. });
  2022. }
  2023. return cb({
  2024. status: "success",
  2025. message: "Successfully updated the blacklisted genres."
  2026. });
  2027. }
  2028. );
  2029. }),
  2030. /**
  2031. * Updates a station's party mode
  2032. *
  2033. * @param session
  2034. * @param stationId - the station id
  2035. * @param newPartyMode - the new station party mode
  2036. * @param cb
  2037. */
  2038. updatePartyMode: isOwnerRequired(async function updatePartyMode(session, stationId, newPartyMode, cb) {
  2039. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2040. async.waterfall(
  2041. [
  2042. next => {
  2043. StationsModule.runJob("GET_STATION", { stationId }, this)
  2044. .then(station => next(null, station))
  2045. .catch(next);
  2046. },
  2047. (station, next) => {
  2048. if (!station) return next("Station not found.");
  2049. if (station.partyMode === newPartyMode)
  2050. return next(`The party mode was already ${newPartyMode ? "enabled." : "disabled."}`);
  2051. return stationModel.updateOne(
  2052. { _id: stationId },
  2053. { $set: { partyMode: newPartyMode, queue: [] } },
  2054. { runValidators: true },
  2055. next
  2056. );
  2057. },
  2058. (res, next) => {
  2059. CacheModule.runJob("PUB", {
  2060. channel: "station.queueUpdate",
  2061. value: stationId
  2062. })
  2063. .then(() => {})
  2064. .catch(next);
  2065. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2066. .then(station => next(null, station))
  2067. .catch(next);
  2068. }
  2069. ],
  2070. async err => {
  2071. if (err) {
  2072. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2073. this.log(
  2074. "ERROR",
  2075. "STATIONS_UPDATE_PARTY_MODE",
  2076. `Updating station "${stationId}" party mode to "${newPartyMode}" failed. "${err}"`
  2077. );
  2078. return cb({ status: "error", message: err });
  2079. }
  2080. this.log(
  2081. "SUCCESS",
  2082. "STATIONS_UPDATE_PARTY_MODE",
  2083. `Updated station "${stationId}" party mode to "${newPartyMode}" successfully.`
  2084. );
  2085. CacheModule.runJob("PUB", {
  2086. channel: "station.updatePartyMode",
  2087. value: {
  2088. stationId,
  2089. partyMode: newPartyMode
  2090. }
  2091. });
  2092. StationsModule.runJob("SKIP_STATION", { stationId });
  2093. return cb({
  2094. status: "success",
  2095. message: "Successfully updated the party mode."
  2096. });
  2097. }
  2098. );
  2099. }),
  2100. /**
  2101. * Updates a station's play mode
  2102. *
  2103. * @param session
  2104. * @param stationId - the station id
  2105. * @param newPlayMode - the new station play mode
  2106. * @param cb
  2107. */
  2108. updatePlayMode: isOwnerRequired(async function updatePartyMode(session, stationId, newPlayMode, cb) {
  2109. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2110. async.waterfall(
  2111. [
  2112. next => {
  2113. StationsModule.runJob("GET_STATION", { stationId }, this)
  2114. .then(station => {
  2115. next(null, station);
  2116. })
  2117. .catch(next);
  2118. },
  2119. (station, next) => {
  2120. if (!station) return next("Station not found.");
  2121. if (station.newPlayMode === newPlayMode) return next(`The play mode was already ${newPlayMode}`);
  2122. return stationModel.updateOne(
  2123. { _id: stationId },
  2124. { $set: { playMode: newPlayMode, queue: [] } },
  2125. { runValidators: true },
  2126. next
  2127. );
  2128. },
  2129. (res, next) => {
  2130. CacheModule.runJob("PUB", {
  2131. channel: "station.queueUpdate",
  2132. value: stationId
  2133. })
  2134. .then()
  2135. .catch();
  2136. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2137. .then(station => {
  2138. next(null, station);
  2139. })
  2140. .catch(next);
  2141. }
  2142. ],
  2143. async err => {
  2144. if (err) {
  2145. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2146. this.log(
  2147. "ERROR",
  2148. "STATIONS_UPDATE_PLAY_MODE",
  2149. `Updating station "${stationId}" play mode to "${newPlayMode}" failed. "${err}"`
  2150. );
  2151. return cb({ status: "error", message: err });
  2152. }
  2153. this.log(
  2154. "SUCCESS",
  2155. "STATIONS_UPDATE_PLAY_MODE",
  2156. `Updated station "${stationId}" play mode to "${newPlayMode}" successfully.`
  2157. );
  2158. CacheModule.runJob("PUB", {
  2159. channel: "station.newPlayMode",
  2160. value: {
  2161. stationId,
  2162. playMode: newPlayMode
  2163. }
  2164. });
  2165. StationsModule.runJob("SKIP_STATION", { stationId });
  2166. return cb({
  2167. status: "success",
  2168. message: "Successfully updated the play mode."
  2169. });
  2170. }
  2171. );
  2172. }),
  2173. /**
  2174. * Updates a station's theme
  2175. *
  2176. * @param session
  2177. * @param stationId - the station id
  2178. * @param newTheme - the new station theme
  2179. * @param cb
  2180. */
  2181. updateTheme: isOwnerRequired(async function updateTheme(session, stationId, newTheme, cb) {
  2182. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2183. async.waterfall(
  2184. [
  2185. next => {
  2186. StationsModule.runJob("GET_STATION", { stationId }, this)
  2187. .then(station => {
  2188. next(null, station);
  2189. })
  2190. .catch(next);
  2191. },
  2192. (station, next) => {
  2193. if (!station) return next("Station not found.");
  2194. if (station.theme === newTheme) return next("No change in theme.");
  2195. return stationModel.updateOne(
  2196. { _id: stationId },
  2197. { $set: { theme: newTheme } },
  2198. { runValidators: true },
  2199. next
  2200. );
  2201. },
  2202. (res, next) => {
  2203. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2204. .then(station => next(null, station))
  2205. .catch(next);
  2206. }
  2207. ],
  2208. async (err, station) => {
  2209. if (err) {
  2210. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2211. this.log(
  2212. "ERROR",
  2213. "STATIONS_UPDATE_THEME",
  2214. `Updating station "${stationId}" theme to "${newTheme}" failed. "${err}"`
  2215. );
  2216. return cb({ status: "error", message: err });
  2217. }
  2218. this.log(
  2219. "SUCCESS",
  2220. "STATIONS_UPDATE_THEME",
  2221. `Updated station "${stationId}" theme to "${newTheme}" successfully.`
  2222. );
  2223. CacheModule.runJob("PUB", {
  2224. channel: "station.themeUpdate",
  2225. value: { stationId }
  2226. });
  2227. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2228. userId: session.userId,
  2229. type: "station__edit_theme",
  2230. payload: {
  2231. message: `Changed theme of station <stationId>${station.displayName}</stationId> to ${newTheme}`,
  2232. stationId
  2233. }
  2234. });
  2235. return cb({
  2236. status: "success",
  2237. message: "Successfully updated the theme."
  2238. });
  2239. }
  2240. );
  2241. }),
  2242. /**
  2243. * Pauses a station
  2244. *
  2245. * @param session
  2246. * @param stationId - the station id
  2247. * @param cb
  2248. */
  2249. pause: isOwnerRequired(async function pause(session, stationId, cb) {
  2250. const stationModel = await DBModule.runJob(
  2251. "GET_MODEL",
  2252. {
  2253. modelName: "station"
  2254. },
  2255. this
  2256. );
  2257. async.waterfall(
  2258. [
  2259. next => {
  2260. StationsModule.runJob("GET_STATION", { stationId }, this)
  2261. .then(station => {
  2262. next(null, station);
  2263. })
  2264. .catch(next);
  2265. },
  2266. (station, next) => {
  2267. if (!station) return next("Station not found.");
  2268. if (station.paused) return next("That station was already paused.");
  2269. return stationModel.updateOne(
  2270. { _id: stationId },
  2271. { $set: { paused: true, pausedAt: Date.now() } },
  2272. next
  2273. );
  2274. },
  2275. (res, next) => {
  2276. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2277. .then(station => {
  2278. next(null, station);
  2279. })
  2280. .catch(next);
  2281. }
  2282. ],
  2283. async err => {
  2284. if (err) {
  2285. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2286. this.log("ERROR", "STATIONS_PAUSE", `Pausing station "${stationId}" failed. "${err}"`);
  2287. return cb({ status: "error", message: err });
  2288. }
  2289. this.log("SUCCESS", "STATIONS_PAUSE", `Paused station "${stationId}" successfully.`);
  2290. CacheModule.runJob("PUB", {
  2291. channel: "station.pause",
  2292. value: stationId
  2293. });
  2294. NotificationsModule.runJob("UNSCHEDULE", {
  2295. name: `stations.nextSong?id=${stationId}`
  2296. });
  2297. return cb({
  2298. status: "success",
  2299. message: "Successfully paused."
  2300. });
  2301. }
  2302. );
  2303. }),
  2304. /**
  2305. * Resumes a station
  2306. *
  2307. * @param session
  2308. * @param stationId - the station id
  2309. * @param cb
  2310. */
  2311. resume: isOwnerRequired(async function resume(session, stationId, cb) {
  2312. const stationModel = await DBModule.runJob(
  2313. "GET_MODEL",
  2314. {
  2315. modelName: "station"
  2316. },
  2317. this
  2318. );
  2319. async.waterfall(
  2320. [
  2321. next => {
  2322. StationsModule.runJob("GET_STATION", { stationId }, this)
  2323. .then(station => {
  2324. next(null, station);
  2325. })
  2326. .catch(next);
  2327. },
  2328. (station, next) => {
  2329. if (!station) return next("Station not found.");
  2330. if (!station.paused) return next("That station is not paused.");
  2331. station.timePaused += Date.now() - station.pausedAt;
  2332. return stationModel.updateOne(
  2333. { _id: stationId },
  2334. {
  2335. $set: { paused: false },
  2336. $inc: { timePaused: Date.now() - station.pausedAt }
  2337. },
  2338. next
  2339. );
  2340. },
  2341. (res, next) => {
  2342. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2343. .then(station => {
  2344. next(null, station);
  2345. })
  2346. .catch(next);
  2347. }
  2348. ],
  2349. async err => {
  2350. if (err) {
  2351. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2352. this.log("ERROR", "STATIONS_RESUME", `Resuming station "${stationId}" failed. "${err}"`);
  2353. return cb({ status: "error", message: err });
  2354. }
  2355. this.log("SUCCESS", "STATIONS_RESUME", `Resuming station "${stationId}" successfully.`);
  2356. CacheModule.runJob("PUB", {
  2357. channel: "station.resume",
  2358. value: stationId
  2359. });
  2360. return cb({
  2361. status: "success",
  2362. message: "Successfully resumed."
  2363. });
  2364. }
  2365. );
  2366. }),
  2367. /**
  2368. * Removes a station
  2369. *
  2370. * @param session
  2371. * @param stationId - the station id
  2372. * @param cb
  2373. */
  2374. remove: isOwnerRequired(async function remove(session, stationId, cb) {
  2375. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2376. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2377. async.waterfall(
  2378. [
  2379. next => {
  2380. stationModel.findById(stationId, (err, station) => {
  2381. if (err) return next(err);
  2382. return next(null, station);
  2383. });
  2384. },
  2385. (station, next) => {
  2386. stationModel.deleteOne({ _id: stationId }, err => next(err, station));
  2387. },
  2388. (station, next) => {
  2389. CacheModule.runJob("HDEL", { table: "stations", key: stationId }, this)
  2390. .then(() => next(null, station))
  2391. .catch(next);
  2392. },
  2393. // remove the playlist for the station
  2394. (station, next) => {
  2395. if (station.playlist)
  2396. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: station.playlist })
  2397. .then(() => {})
  2398. .catch(next);
  2399. next(null, station);
  2400. },
  2401. // remove reference to the station id in any array of a user's favorite stations
  2402. (station, next) => {
  2403. userModel.updateMany(
  2404. { favoriteStations: stationId },
  2405. { $pull: { favoriteStations: stationId } },
  2406. err => next(err, station)
  2407. );
  2408. }
  2409. ],
  2410. async (err, station) => {
  2411. if (err) {
  2412. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2413. this.log("ERROR", "STATIONS_REMOVE", `Removing station "${stationId}" failed. "${err}"`);
  2414. return cb({ status: "error", message: err });
  2415. }
  2416. this.log("SUCCESS", "STATIONS_REMOVE", `Removing station "${stationId}" successfully.`);
  2417. CacheModule.runJob("PUB", {
  2418. channel: "station.remove",
  2419. value: stationId
  2420. });
  2421. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2422. userId: session.userId,
  2423. type: "station__remove",
  2424. payload: { message: `Removed a station named ${station.displayName}` }
  2425. });
  2426. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "stationId", stationId });
  2427. return cb({
  2428. status: "success",
  2429. message: "Successfully removed."
  2430. });
  2431. }
  2432. );
  2433. }),
  2434. /**
  2435. * Create a station
  2436. *
  2437. * @param session
  2438. * @param data - the station data
  2439. * @param cb
  2440. */
  2441. create: isLoginRequired(async function create(session, data, cb) {
  2442. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2443. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2444. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  2445. data.name = data.name.toLowerCase();
  2446. const blacklist = [
  2447. "country",
  2448. "edm",
  2449. "musare",
  2450. "hip-hop",
  2451. "rap",
  2452. "top-hits",
  2453. "todays-hits",
  2454. "old-school",
  2455. "christmas",
  2456. "about",
  2457. "support",
  2458. "staff",
  2459. "help",
  2460. "news",
  2461. "terms",
  2462. "privacy",
  2463. "profile",
  2464. "c",
  2465. "community",
  2466. "tos",
  2467. "login",
  2468. "register",
  2469. "p",
  2470. "official",
  2471. "o",
  2472. "trap",
  2473. "faq",
  2474. "team",
  2475. "donate",
  2476. "buy",
  2477. "shop",
  2478. "forums",
  2479. "explore",
  2480. "settings",
  2481. "admin",
  2482. "auth",
  2483. "reset_password",
  2484. "backend",
  2485. "api",
  2486. "songs",
  2487. "playlists",
  2488. "playlist"
  2489. ];
  2490. async.waterfall(
  2491. [
  2492. next => {
  2493. if (!data) return next("Invalid data.");
  2494. return next();
  2495. },
  2496. next => {
  2497. stationModel.findOne(
  2498. {
  2499. $or: [
  2500. { name: data.name },
  2501. {
  2502. displayName: new RegExp(`^${data.displayName}$`, "i")
  2503. }
  2504. ]
  2505. },
  2506. next
  2507. );
  2508. },
  2509. // eslint-disable-next-line consistent-return
  2510. (station, next) => {
  2511. this.log(station);
  2512. if (station) return next("A station with that name or display name already exists.");
  2513. const { name, displayName, description, /* playlist, */ type, genres, blacklistedGenres } = data;
  2514. const stationId = mongoose.Types.ObjectId();
  2515. if (type === "official") {
  2516. return userModel.findOne({ _id: session.userId }, (err, user) => {
  2517. if (err) return next(err);
  2518. if (!user) return next("User not found.");
  2519. if (user.role !== "admin") return next("Admin required.");
  2520. return async.waterfall(
  2521. [
  2522. next => {
  2523. const playlists = [];
  2524. async.eachLimit(
  2525. genres,
  2526. 1,
  2527. (genre, next) => {
  2528. PlaylistsModule.runJob(
  2529. "GET_GENRE_PLAYLIST",
  2530. { genre, includeSongs: false },
  2531. this
  2532. )
  2533. .then(response => {
  2534. playlists.push(response.playlist);
  2535. next();
  2536. })
  2537. .catch(err => {
  2538. next(
  2539. `An error occurred when trying to get genre playlist for genre ${genre}. Error: ${err}.`
  2540. );
  2541. });
  2542. },
  2543. err => {
  2544. next(
  2545. err,
  2546. playlists.map(playlist => playlist._id.toString())
  2547. );
  2548. }
  2549. );
  2550. },
  2551. (genrePlaylistIds, next) => {
  2552. const playlists = [];
  2553. async.eachLimit(
  2554. blacklistedGenres,
  2555. 1,
  2556. (genre, next) => {
  2557. PlaylistsModule.runJob(
  2558. "GET_GENRE_PLAYLIST",
  2559. { genre, includeSongs: false },
  2560. this
  2561. )
  2562. .then(response => {
  2563. playlists.push(response.playlist);
  2564. next();
  2565. })
  2566. .catch(err => {
  2567. next(
  2568. `An error occurred when trying to get genre playlist for genre ${genre}. Error: ${err}.`
  2569. );
  2570. });
  2571. },
  2572. err => {
  2573. next(
  2574. err,
  2575. genrePlaylistIds,
  2576. playlists.map(playlist => playlist._id.toString())
  2577. );
  2578. }
  2579. );
  2580. },
  2581. (genrePlaylistIds, blacklistedGenrePlaylistIds, next) => {
  2582. const duplicateGenre =
  2583. genrePlaylistIds.length !== new Set(genrePlaylistIds).size;
  2584. const duplicateBlacklistedGenre =
  2585. genrePlaylistIds.length !== new Set(genrePlaylistIds).size;
  2586. const duplicateCross =
  2587. genrePlaylistIds.length + blacklistedGenrePlaylistIds.length !==
  2588. new Set([...genrePlaylistIds, ...blacklistedGenrePlaylistIds]).size;
  2589. if (duplicateGenre)
  2590. return next("You cannot have the same genre included twice.");
  2591. if (duplicateBlacklistedGenre)
  2592. return next("You cannot have the same blacklisted genre included twice.");
  2593. if (duplicateCross)
  2594. return next(
  2595. "You cannot have the same genre included and blacklisted at the same time."
  2596. );
  2597. return next(null, genrePlaylistIds, blacklistedGenrePlaylistIds);
  2598. }
  2599. ],
  2600. (err, genrePlaylistIds, blacklistedGenrePlaylistIds) => {
  2601. if (err) return next(err);
  2602. return playlistModel.create(
  2603. {
  2604. isUserModifiable: false,
  2605. displayName: `Station - ${displayName}`,
  2606. songs: [],
  2607. createdBy: "Musare",
  2608. createdFor: `${stationId}`,
  2609. createdAt: Date.now(),
  2610. type: "station"
  2611. },
  2612. (err, playlist) => {
  2613. if (err) next(err);
  2614. else {
  2615. stationModel.create(
  2616. {
  2617. _id: stationId,
  2618. name,
  2619. displayName,
  2620. description,
  2621. type,
  2622. privacy: "private",
  2623. playlist: playlist._id,
  2624. currentSong: null,
  2625. partyMode: false,
  2626. playMode: "random"
  2627. },
  2628. (err, station) => {
  2629. next(
  2630. err,
  2631. station,
  2632. genrePlaylistIds,
  2633. blacklistedGenrePlaylistIds
  2634. );
  2635. }
  2636. );
  2637. }
  2638. }
  2639. );
  2640. }
  2641. );
  2642. });
  2643. }
  2644. if (type === "community") {
  2645. if (blacklist.indexOf(name) !== -1)
  2646. return next("That name is blacklisted. Please use a different name.");
  2647. return playlistModel.create(
  2648. {
  2649. isUserModifiable: false,
  2650. displayName: `Station - ${name}`,
  2651. songs: [],
  2652. createdBy: session.userId,
  2653. createdFor: `${stationId}`,
  2654. createdAt: Date.now(),
  2655. type: "station"
  2656. },
  2657. (err, playlist) => {
  2658. if (err) next(err);
  2659. else {
  2660. stationModel.create(
  2661. {
  2662. _id: stationId,
  2663. name,
  2664. displayName,
  2665. description,
  2666. playlist: playlist._id,
  2667. type,
  2668. privacy: "private",
  2669. owner: session.userId,
  2670. queue: [],
  2671. currentSong: null,
  2672. partyMode: true,
  2673. playMode: "random"
  2674. },
  2675. (err, station) => {
  2676. next(err, station, null, null);
  2677. }
  2678. );
  2679. }
  2680. }
  2681. );
  2682. }
  2683. },
  2684. (station, genrePlaylistIds, blacklistedGenrePlaylistIds, next) => {
  2685. if (station.type !== "official") return next(null, station);
  2686. const stationId = station._id;
  2687. console.log(111, station, genrePlaylistIds, blacklistedGenrePlaylistIds, next);
  2688. return async.waterfall(
  2689. [
  2690. next => {
  2691. async.eachLimit(
  2692. genrePlaylistIds,
  2693. 1,
  2694. (playlistId, next) => {
  2695. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  2696. .then(() => {
  2697. next();
  2698. })
  2699. .catch(next);
  2700. },
  2701. next
  2702. );
  2703. },
  2704. next => {
  2705. async.eachLimit(
  2706. blacklistedGenrePlaylistIds,
  2707. 1,
  2708. (playlistId, next) => {
  2709. StationsModule.runJob("EXCLUDE_PLAYLIST", { stationId, playlistId }, this)
  2710. .then(() => {
  2711. next();
  2712. })
  2713. .catch(next);
  2714. },
  2715. next
  2716. );
  2717. },
  2718. next => {
  2719. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2720. next();
  2721. }
  2722. ],
  2723. async err => {
  2724. if (err) {
  2725. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2726. this.log(
  2727. "ERROR",
  2728. "STATIONS_CREATE",
  2729. `Created station ${stationId} successfully, but an error occurred during playing including/excluding. Error: ${err}`
  2730. );
  2731. }
  2732. next(null, station, err);
  2733. }
  2734. );
  2735. }
  2736. ],
  2737. async (err, station, extraError) => {
  2738. if (err) {
  2739. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2740. this.log("ERROR", "STATIONS_CREATE", `Creating station failed. "${err}"`);
  2741. cb({ status: "error", message: err });
  2742. } else {
  2743. this.log("SUCCESS", "STATIONS_CREATE", `Created station "${station._id}" successfully.`);
  2744. CacheModule.runJob("PUB", {
  2745. channel: "station.create",
  2746. value: station._id
  2747. });
  2748. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2749. userId: session.userId,
  2750. type: "station__create",
  2751. payload: {
  2752. message: `Created a station named <stationId>${station.displayName}</stationId>`,
  2753. stationId: station._id
  2754. }
  2755. });
  2756. if (!extraError) {
  2757. cb({
  2758. status: "success",
  2759. message: "Successfully created station."
  2760. });
  2761. } else {
  2762. cb({
  2763. status: "success",
  2764. message: `Successfully created station, but with one error at the end: ${extraError}`
  2765. });
  2766. }
  2767. }
  2768. }
  2769. );
  2770. }),
  2771. /**
  2772. * Adds song to station queue
  2773. *
  2774. * @param session
  2775. * @param stationId - the station id
  2776. * @param youtubeId - the song id
  2777. * @param cb
  2778. */
  2779. addToQueue: isLoginRequired(async function addToQueue(session, stationId, youtubeId, cb) {
  2780. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2781. const stationModel = await DBModule.runJob(
  2782. "GET_MODEL",
  2783. {
  2784. modelName: "station"
  2785. },
  2786. this
  2787. );
  2788. async.waterfall(
  2789. [
  2790. next => {
  2791. StationsModule.runJob("GET_STATION", { stationId }, this)
  2792. .then(station => {
  2793. next(null, station);
  2794. })
  2795. .catch(next);
  2796. },
  2797. (station, next) => {
  2798. if (!station) return next("Station not found.");
  2799. if (!station.partyMode) return next("Station is not in party mode.");
  2800. if (station.locked) {
  2801. return userModel.findOne({ _id: session.userId }, (err, user) => {
  2802. if (user.role !== "admin" && station.owner !== session.userId)
  2803. return next("Only owners and admins can add songs to a locked queue.");
  2804. return next(null, station);
  2805. });
  2806. }
  2807. return next(null, station);
  2808. },
  2809. (station, next) => {
  2810. if (station.type !== "community") return next("That station is not a community station.");
  2811. return StationsModule.runJob(
  2812. "CAN_USER_VIEW_STATION",
  2813. {
  2814. station,
  2815. userId: session.userId
  2816. },
  2817. this
  2818. )
  2819. .then(canView => {
  2820. if (canView) return next(null, station);
  2821. return next("Insufficient permissions.");
  2822. })
  2823. .catch(err => next(err));
  2824. },
  2825. (station, next) => {
  2826. if (station.currentSong && station.currentSong.youtubeId === youtubeId)
  2827. return next("That song is currently playing.");
  2828. return async.each(
  2829. station.queue,
  2830. (queueSong, next) => {
  2831. if (queueSong.youtubeId === youtubeId) return next("That song is already in the queue.");
  2832. return next();
  2833. },
  2834. err => next(err, station)
  2835. );
  2836. },
  2837. (station, next) => {
  2838. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  2839. .then(UserModel => {
  2840. UserModel.findOne(
  2841. { _id: session.userId },
  2842. { "preferences.anonymousSongRequests": 1 },
  2843. (err, user) => next(err, station, user)
  2844. );
  2845. })
  2846. .catch(next);
  2847. },
  2848. (station, user, next) => {
  2849. SongsModule.runJob(
  2850. "ENSURE_SONG_EXISTS_BY_YOUTUBE_ID",
  2851. {
  2852. youtubeId,
  2853. userId: user.preferences.anonymousSongRequests ? null : session.userId,
  2854. automaticallyRequested: true
  2855. },
  2856. this
  2857. )
  2858. .then(response => {
  2859. const { song } = response;
  2860. const { _id, title, artists, thumbnail, duration, status } = song;
  2861. next(
  2862. null,
  2863. {
  2864. _id,
  2865. youtubeId,
  2866. title,
  2867. artists,
  2868. thumbnail,
  2869. duration,
  2870. status
  2871. },
  2872. station
  2873. );
  2874. })
  2875. .catch(next);
  2876. },
  2877. (song, station, next) => {
  2878. const excludedPlaylists = [];
  2879. async.eachLimit(
  2880. station.excludedPlaylists,
  2881. 1,
  2882. (playlistId, next) => {
  2883. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  2884. .then(playlist => {
  2885. excludedPlaylists.push(playlist);
  2886. next();
  2887. })
  2888. .catch(next);
  2889. },
  2890. err => {
  2891. next(err, song, station, excludedPlaylists);
  2892. }
  2893. );
  2894. },
  2895. (song, station, excludedPlaylists, next) => {
  2896. const excludedSongs = excludedPlaylists
  2897. .flatMap(excludedPlaylist => excludedPlaylist.songs)
  2898. .reduce(
  2899. (items, item) =>
  2900. items.find(x => x.youtubeId === item.youtubeId) ? [...items] : [...items, item],
  2901. []
  2902. );
  2903. if (excludedSongs.find(excludedSong => excludedSong._id.toString() === song._id.toString()))
  2904. next("That song is in an excluded playlist and cannot be played.");
  2905. else next(null, song, station);
  2906. },
  2907. (song, station, next) => {
  2908. song.requestedBy = session.userId;
  2909. song.requestedAt = Date.now();
  2910. let totalDuration = 0;
  2911. station.queue.forEach(song => {
  2912. totalDuration += song.duration;
  2913. });
  2914. if (totalDuration >= 3600 * 3) return next("The max length of the queue is 3 hours.");
  2915. return next(null, song, station);
  2916. },
  2917. (song, station, next) => {
  2918. if (station.queue.length === 0) return next(null, song, station);
  2919. let totalDuration = 0;
  2920. const userId = station.queue[station.queue.length - 1].requestedBy;
  2921. station.queue.forEach(song => {
  2922. if (userId === song.requestedBy) {
  2923. totalDuration += song.duration;
  2924. }
  2925. });
  2926. if (totalDuration >= 900) return next("The max length of songs per user is 15 minutes.");
  2927. return next(null, song, station);
  2928. },
  2929. (song, station, next) => {
  2930. if (station.queue.length === 0) return next(null, song);
  2931. let totalSongs = 0;
  2932. const userId = station.queue[station.queue.length - 1].requestedBy;
  2933. station.queue.forEach(song => {
  2934. if (userId === song.requestedBy) {
  2935. totalSongs += 1;
  2936. }
  2937. });
  2938. if (totalSongs <= 2) return next(null, song);
  2939. if (totalSongs > 3)
  2940. return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  2941. if (
  2942. station.queue[station.queue.length - 2].requestedBy !== userId ||
  2943. station.queue[station.queue.length - 3] !== userId
  2944. )
  2945. return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  2946. return next(null, song);
  2947. },
  2948. (song, next) => {
  2949. stationModel.updateOne(
  2950. { _id: stationId },
  2951. { $push: { queue: song } },
  2952. { runValidators: true },
  2953. next
  2954. );
  2955. },
  2956. (res, next) => {
  2957. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2958. .then(station => next(null, station))
  2959. .catch(next);
  2960. }
  2961. // (res, next) => {
  2962. // StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2963. // .then(station => {
  2964. // next(null, station);
  2965. // })
  2966. // .catch(next);
  2967. // }
  2968. ],
  2969. async err => {
  2970. if (err) {
  2971. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2972. this.log(
  2973. "ERROR",
  2974. "STATIONS_ADD_SONG_TO_QUEUE",
  2975. `Adding song "${youtubeId}" to station "${stationId}" queue failed. "${err}"`
  2976. );
  2977. return cb({ status: "error", message: err });
  2978. }
  2979. this.log(
  2980. "SUCCESS",
  2981. "STATIONS_ADD_SONG_TO_QUEUE",
  2982. `Added song "${youtubeId}" to station "${stationId}" successfully.`
  2983. );
  2984. CacheModule.runJob("PUB", {
  2985. channel: "station.queueUpdate",
  2986. value: stationId
  2987. });
  2988. return cb({
  2989. status: "success",
  2990. message: "Successfully added song to queue."
  2991. });
  2992. }
  2993. );
  2994. }),
  2995. /**
  2996. * Removes song from station queue
  2997. *
  2998. * @param session
  2999. * @param stationId - the station id
  3000. * @param youtubeId - the youtube id
  3001. * @param cb
  3002. */
  3003. removeFromQueue: isOwnerRequired(async function removeFromQueue(session, stationId, youtubeId, cb) {
  3004. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  3005. async.waterfall(
  3006. [
  3007. next => {
  3008. if (!youtubeId) return next("Invalid youtube id.");
  3009. return StationsModule.runJob("GET_STATION", { stationId }, this)
  3010. .then(station => next(null, station))
  3011. .catch(next);
  3012. },
  3013. (station, next) => {
  3014. if (!station) return next("Station not found.");
  3015. return async.each(
  3016. station.queue,
  3017. (queueSong, next) => {
  3018. if (queueSong.youtubeId === youtubeId) return next(true);
  3019. return next();
  3020. },
  3021. err => {
  3022. if (err === true) return next();
  3023. return next("Song is not currently in the queue.");
  3024. }
  3025. );
  3026. },
  3027. next => {
  3028. stationModel.updateOne({ _id: stationId }, { $pull: { queue: { youtubeId } } }, next);
  3029. },
  3030. (res, next) => {
  3031. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  3032. .then(station => next(null, station))
  3033. .catch(next);
  3034. }
  3035. ],
  3036. async err => {
  3037. if (err) {
  3038. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3039. this.log(
  3040. "ERROR",
  3041. "STATIONS_REMOVE_SONG_TO_QUEUE",
  3042. `Removing song "${youtubeId}" from station "${stationId}" queue failed. "${err}"`
  3043. );
  3044. return cb({ status: "error", message: err });
  3045. }
  3046. this.log(
  3047. "SUCCESS",
  3048. "STATIONS_REMOVE_SONG_TO_QUEUE",
  3049. `Removed song "${youtubeId}" from station "${stationId}" successfully.`
  3050. );
  3051. CacheModule.runJob("PUB", {
  3052. channel: "station.queueUpdate",
  3053. value: stationId
  3054. });
  3055. return cb({
  3056. status: "success",
  3057. message: "Successfully removed song from queue."
  3058. });
  3059. }
  3060. );
  3061. }),
  3062. /**
  3063. * Gets the queue from a station
  3064. *
  3065. * @param {object} session - user session
  3066. * @param {string} stationId - the station id
  3067. * @param {Function} cb - callback
  3068. */
  3069. getQueue(session, stationId, cb) {
  3070. async.waterfall(
  3071. [
  3072. next => {
  3073. StationsModule.runJob("GET_STATION", { stationId }, this)
  3074. .then(station => next(null, station))
  3075. .catch(next);
  3076. },
  3077. (station, next) => {
  3078. if (!station) return next("Station not found.");
  3079. return next(null, station);
  3080. },
  3081. (station, next) => {
  3082. StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  3083. .then(canView => {
  3084. if (canView) return next(null, station);
  3085. return next("Insufficient permissions.");
  3086. })
  3087. .catch(err => next(err));
  3088. },
  3089. (station, next) => {
  3090. if (station.type === "official") next(null, station.queue);
  3091. else next(null, station.queue);
  3092. }
  3093. ],
  3094. async (err, queue) => {
  3095. if (err) {
  3096. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3097. this.log(
  3098. "ERROR",
  3099. "STATIONS_GET_QUEUE",
  3100. `Getting queue for station "${stationId}" failed. "${err}"`
  3101. );
  3102. return cb({ status: "error", message: err });
  3103. }
  3104. this.log("SUCCESS", "STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  3105. return cb({
  3106. status: "success",
  3107. message: "Successfully got queue.",
  3108. data: { queue }
  3109. });
  3110. }
  3111. );
  3112. },
  3113. /**
  3114. * Reposition a song in station queue
  3115. *
  3116. * @param {object} session - user session
  3117. * @param {object} song - contains details about the song that is to be repositioned
  3118. * @param {string} song.youtubeId - the youtube id of the song
  3119. * @param {number} song.newIndex - the new position for the song in the queue
  3120. * @param {number} song.oldIndex - the old position of the song in the queue
  3121. * @param {string} stationId - the station id
  3122. * @param {Function} cb - callback
  3123. */
  3124. repositionSongInQueue: isOwnerRequired(async function repositionQueue(session, stationId, song, cb) {
  3125. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  3126. async.waterfall(
  3127. [
  3128. next => {
  3129. if (!song || !song.youtubeId) return next("You must provide a song to reposition.");
  3130. return next();
  3131. },
  3132. // remove song from queue
  3133. next => {
  3134. stationModel.updateOne(
  3135. { _id: stationId },
  3136. { $pull: { queue: { youtubeId: song.youtubeId } } },
  3137. next
  3138. );
  3139. },
  3140. // add song back to queue (in new position)
  3141. (res, next) => {
  3142. stationModel.updateOne(
  3143. { _id: stationId },
  3144. { $push: { queue: { $each: [song], $position: song.newIndex } } },
  3145. err => next(err)
  3146. );
  3147. },
  3148. // update the cache representation of the station
  3149. next => {
  3150. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  3151. .then(station => next(null, station))
  3152. .catch(next);
  3153. }
  3154. ],
  3155. async err => {
  3156. if (err) {
  3157. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3158. this.log(
  3159. "ERROR",
  3160. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  3161. `Repositioning song ${song.youtubeId} in queue of station "${stationId}" failed. "${err}"`
  3162. );
  3163. return cb({ status: "error", message: err });
  3164. }
  3165. this.log(
  3166. "SUCCESS",
  3167. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  3168. `Repositioned song ${song.youtubeId} in queue of station "${stationId}" successfully.`
  3169. );
  3170. CacheModule.runJob("PUB", {
  3171. channel: "station.repositionSongInQueue",
  3172. value: {
  3173. song: {
  3174. youtubeId: song.youtubeId,
  3175. oldIndex: song.oldIndex,
  3176. newIndex: song.newIndex
  3177. },
  3178. stationId
  3179. }
  3180. });
  3181. return cb({
  3182. status: "success",
  3183. message: "Successfully repositioned song in queue."
  3184. });
  3185. }
  3186. );
  3187. }),
  3188. /**
  3189. * Includes a playlist in a station
  3190. *
  3191. * @param session
  3192. * @param stationId - the station id
  3193. * @param playlistId - the playlist id
  3194. * @param cb
  3195. */
  3196. includePlaylist: isOwnerRequired(async function includePlaylist(session, stationId, playlistId, cb) {
  3197. async.waterfall(
  3198. [
  3199. next => {
  3200. StationsModule.runJob("GET_STATION", { stationId }, this)
  3201. .then(station => next(null, station))
  3202. .catch(next);
  3203. },
  3204. (station, next) => {
  3205. if (!station) return next("Station not found.");
  3206. if (station.includedPlaylists.indexOf(playlistId) !== -1)
  3207. return next("That playlist is already included.");
  3208. if (station.playMode === "sequential" && station.includedPlaylists.length > 0)
  3209. return next("Error: Only 1 playlist can be included in sequential play mode.");
  3210. return next();
  3211. },
  3212. next => {
  3213. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  3214. .then(() => {
  3215. next();
  3216. })
  3217. .catch(next);
  3218. }
  3219. ],
  3220. async err => {
  3221. if (err) {
  3222. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3223. this.log(
  3224. "ERROR",
  3225. "STATIONS_INCLUDE_PLAYLIST",
  3226. `Including playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3227. );
  3228. return cb({ status: "error", message: err });
  3229. }
  3230. this.log(
  3231. "SUCCESS",
  3232. "STATIONS_INCLUDE_PLAYLIST",
  3233. `Including playlist "${playlistId}" for station "${stationId}" successfully.`
  3234. );
  3235. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3236. CacheModule.runJob("PUB", {
  3237. channel: "station.includedPlaylist",
  3238. value: {
  3239. playlistId,
  3240. stationId
  3241. }
  3242. });
  3243. return cb({
  3244. status: "success",
  3245. message: "Successfully included playlist."
  3246. });
  3247. }
  3248. );
  3249. }),
  3250. /**
  3251. * Remove included a playlist from a station
  3252. *
  3253. * @param session
  3254. * @param stationId - the station id
  3255. * @param playlistId - the playlist id
  3256. * @param cb
  3257. */
  3258. removeIncludedPlaylist: isOwnerRequired(async function removeIncludedPlaylist(session, stationId, playlistId, cb) {
  3259. async.waterfall(
  3260. [
  3261. next => {
  3262. StationsModule.runJob("GET_STATION", { stationId }, this)
  3263. .then(station => next(null, station))
  3264. .catch(next);
  3265. },
  3266. (station, next) => {
  3267. if (!station) return next("Station not found.");
  3268. if (station.includedPlaylists.indexOf(playlistId) === -1)
  3269. return next("That playlist is not included.");
  3270. return next();
  3271. },
  3272. next => {
  3273. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  3274. .then(() => {
  3275. next();
  3276. })
  3277. .catch(next);
  3278. }
  3279. ],
  3280. async err => {
  3281. if (err) {
  3282. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3283. this.log(
  3284. "ERROR",
  3285. "STATIONS_REMOVE_INCLUDED_PLAYLIST",
  3286. `Removing included playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3287. );
  3288. return cb({ status: "error", message: err });
  3289. }
  3290. this.log(
  3291. "SUCCESS",
  3292. "STATIONS_REMOVE_INCLUDED_PLAYLIST",
  3293. `Removing included playlist "${playlistId}" for station "${stationId}" successfully.`
  3294. );
  3295. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3296. CacheModule.runJob("PUB", {
  3297. channel: "station.removedIncludedPlaylist",
  3298. value: {
  3299. playlistId,
  3300. stationId
  3301. }
  3302. });
  3303. return cb({
  3304. status: "success",
  3305. message: "Successfully removed included playlist."
  3306. });
  3307. }
  3308. );
  3309. }),
  3310. /**
  3311. * Excludes a playlist in a station
  3312. *
  3313. * @param session
  3314. * @param stationId - the station id
  3315. * @param playlistId - the playlist id
  3316. * @param cb
  3317. */
  3318. excludePlaylist: isOwnerRequired(async function excludePlaylist(session, stationId, playlistId, cb) {
  3319. async.waterfall(
  3320. [
  3321. next => {
  3322. StationsModule.runJob("GET_STATION", { stationId }, this)
  3323. .then(station => next(null, station))
  3324. .catch(next);
  3325. },
  3326. (station, next) => {
  3327. if (!station) return next("Station not found.");
  3328. if (station.excludedPlaylists.indexOf(playlistId) !== -1)
  3329. return next("That playlist is already excluded.");
  3330. return next();
  3331. },
  3332. next => {
  3333. StationsModule.runJob("EXCLUDE_PLAYLIST", { stationId, playlistId }, this)
  3334. .then(() => {
  3335. next();
  3336. })
  3337. .catch(next);
  3338. }
  3339. ],
  3340. async err => {
  3341. if (err) {
  3342. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3343. this.log(
  3344. "ERROR",
  3345. "STATIONS_EXCLUDE_PLAYLIST",
  3346. `Excluding playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3347. );
  3348. return cb({ status: "error", message: err });
  3349. }
  3350. this.log(
  3351. "SUCCESS",
  3352. "STATIONS_EXCLUDE_PLAYLIST",
  3353. `Excluding playlist "${playlistId}" for station "${stationId}" successfully.`
  3354. );
  3355. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3356. CacheModule.runJob("PUB", {
  3357. channel: "station.excludedPlaylist",
  3358. value: {
  3359. playlistId,
  3360. stationId
  3361. }
  3362. });
  3363. return cb({
  3364. status: "success",
  3365. message: "Successfully excluded playlist."
  3366. });
  3367. }
  3368. );
  3369. }),
  3370. /**
  3371. * Remove excluded a playlist from a station
  3372. *
  3373. * @param session
  3374. * @param stationId - the station id
  3375. * @param playlistId - the playlist id
  3376. * @param cb
  3377. */
  3378. removeExcludedPlaylist: isOwnerRequired(async function removeExcludedPlaylist(session, stationId, playlistId, cb) {
  3379. async.waterfall(
  3380. [
  3381. next => {
  3382. StationsModule.runJob("GET_STATION", { stationId }, this)
  3383. .then(station => next(null, station))
  3384. .catch(next);
  3385. },
  3386. (station, next) => {
  3387. if (!station) return next("Station not found.");
  3388. if (station.excludedPlaylists.indexOf(playlistId) === -1)
  3389. return next("That playlist is not excluded.");
  3390. return next();
  3391. },
  3392. next => {
  3393. StationsModule.runJob("REMOVE_EXCLUDED_PLAYLIST", { stationId, playlistId }, this)
  3394. .then(() => {
  3395. next();
  3396. })
  3397. .catch(next);
  3398. }
  3399. ],
  3400. async err => {
  3401. if (err) {
  3402. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3403. this.log(
  3404. "ERROR",
  3405. "STATIONS_REMOVE_EXCLUDED_PLAYLIST",
  3406. `Removing excluded playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3407. );
  3408. return cb({ status: "error", message: err });
  3409. }
  3410. this.log(
  3411. "SUCCESS",
  3412. "STATIONS_REMOVE_EXCLUDED_PLAYLIST",
  3413. `Removing excluded playlist "${playlistId}" for station "${stationId}" successfully.`
  3414. );
  3415. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3416. CacheModule.runJob("PUB", {
  3417. channel: "station.removedExcludedPlaylist",
  3418. value: {
  3419. playlistId,
  3420. stationId
  3421. }
  3422. });
  3423. return cb({
  3424. status: "success",
  3425. message: "Successfully removed excluded playlist."
  3426. });
  3427. }
  3428. );
  3429. }),
  3430. /**
  3431. * Selects a private playlist for a station
  3432. *
  3433. * @param session
  3434. * @param stationId - the station id
  3435. * @param playlistId - the private playlist id
  3436. * @param cb
  3437. */
  3438. selectPrivatePlaylist: isOwnerRequired(async function selectPrivatePlaylist(session, stationId, playlistId, cb) {
  3439. async.waterfall(
  3440. [
  3441. next => {
  3442. StationsModule.runJob("GET_STATION", { stationId }, this)
  3443. .then(station => next(null, station))
  3444. .catch(next);
  3445. },
  3446. (station, next) => {
  3447. if (!station) return next("Station not found.");
  3448. if (station.type !== "community") return next("Station is not a community station.");
  3449. if (station.includedPlaylists.indexOf(playlistId) !== -1)
  3450. return next("That playlist is already included.");
  3451. return next();
  3452. },
  3453. next => {
  3454. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  3455. .then(() => {
  3456. next();
  3457. })
  3458. .catch(next);
  3459. }
  3460. ],
  3461. async err => {
  3462. if (err) {
  3463. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3464. this.log(
  3465. "ERROR",
  3466. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  3467. `Selecting private playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3468. );
  3469. return cb({ status: "error", message: err });
  3470. }
  3471. this.log(
  3472. "SUCCESS",
  3473. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  3474. `Selected private playlist "${playlistId}" for station "${stationId}" successfully.`
  3475. );
  3476. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3477. // CacheModule.runJob("PUB", {
  3478. // channel: "privatePlaylist.selected",
  3479. // value: {
  3480. // playlistId,
  3481. // stationId
  3482. // }
  3483. // });
  3484. return cb({
  3485. status: "success",
  3486. message: "Successfully selected playlist."
  3487. });
  3488. }
  3489. );
  3490. }),
  3491. /**
  3492. * Deselects the private playlist selected in a station
  3493. *
  3494. * @param session
  3495. * @param stationId - the station id
  3496. * @param cb
  3497. */
  3498. deselectPrivatePlaylist: isOwnerRequired(async function deselectPrivatePlaylist(
  3499. session,
  3500. stationId,
  3501. playlistId,
  3502. cb
  3503. ) {
  3504. async.waterfall(
  3505. [
  3506. next => {
  3507. StationsModule.runJob("GET_STATION", { stationId }, this)
  3508. .then(station => {
  3509. next(null, station);
  3510. })
  3511. .catch(next);
  3512. },
  3513. (station, next) => {
  3514. if (!station) return next("Station not found.");
  3515. if (station.type !== "community") return next("Station is not a community station.");
  3516. if (station.includedPlaylists.indexOf(playlistId) === -1)
  3517. return next("That playlist is not included.");
  3518. return next();
  3519. },
  3520. next => {
  3521. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  3522. .then(() => {
  3523. next();
  3524. })
  3525. .catch(next);
  3526. }
  3527. ],
  3528. async err => {
  3529. if (err) {
  3530. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3531. this.log(
  3532. "ERROR",
  3533. "STATIONS_DESELECT_PRIVATE_PLAYLIST",
  3534. `Deselecting private playlist for station "${stationId}" failed. "${err}"`
  3535. );
  3536. return cb({ status: "error", message: err });
  3537. }
  3538. this.log(
  3539. "SUCCESS",
  3540. "STATIONS_DESELECT_PRIVATE_PLAYLIST",
  3541. `Deselected private playlist for station "${stationId}" successfully.`
  3542. );
  3543. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3544. // CacheModule.runJob("PUB", {
  3545. // channel: "privatePlaylist.deselected",
  3546. // value: {
  3547. // stationId
  3548. // }
  3549. // });
  3550. return cb({
  3551. status: "success",
  3552. message: "Successfully deselected playlist."
  3553. });
  3554. }
  3555. );
  3556. }),
  3557. favoriteStation: isLoginRequired(async function favoriteStation(session, stationId, cb) {
  3558. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  3559. async.waterfall(
  3560. [
  3561. next => {
  3562. StationsModule.runJob("GET_STATION", { stationId }, this)
  3563. .then(station => next(null, station))
  3564. .catch(next);
  3565. },
  3566. (station, next) => {
  3567. if (!station) return next("Station not found.");
  3568. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  3569. .then(canView => {
  3570. if (canView) return next(null, station);
  3571. return next("Insufficient permissions.");
  3572. })
  3573. .catch(err => next(err));
  3574. },
  3575. (station, next) => {
  3576. userModel.updateOne(
  3577. { _id: session.userId },
  3578. { $addToSet: { favoriteStations: stationId } },
  3579. (err, res) => next(err, station, res)
  3580. );
  3581. },
  3582. (station, res, next) => {
  3583. if (res.nModified === 0) return next("The station was already favorited.");
  3584. return next(null, station);
  3585. }
  3586. ],
  3587. async (err, station) => {
  3588. if (err) {
  3589. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3590. this.log("ERROR", "FAVORITE_STATION", `Favoriting station "${stationId}" failed. "${err}"`);
  3591. return cb({ status: "error", message: err });
  3592. }
  3593. this.log("SUCCESS", "FAVORITE_STATION", `Favorited station "${stationId}" successfully.`);
  3594. CacheModule.runJob("PUB", {
  3595. channel: "user.favoritedStation",
  3596. value: {
  3597. userId: session.userId,
  3598. stationId
  3599. }
  3600. });
  3601. ActivitiesModule.runJob("ADD_ACTIVITY", {
  3602. userId: session.userId,
  3603. type: "station__favorite",
  3604. payload: {
  3605. message: `Favorited station <stationId>${station.displayName}</stationId>`,
  3606. stationId
  3607. }
  3608. });
  3609. return cb({
  3610. status: "success",
  3611. message: "Succesfully favorited station."
  3612. });
  3613. }
  3614. );
  3615. }),
  3616. unfavoriteStation: isLoginRequired(async function unfavoriteStation(session, stationId, cb) {
  3617. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  3618. async.waterfall(
  3619. [
  3620. next => {
  3621. userModel.updateOne({ _id: session.userId }, { $pull: { favoriteStations: stationId } }, next);
  3622. },
  3623. (res, next) => {
  3624. if (res.nModified === 0) return next("The station wasn't favorited.");
  3625. return next();
  3626. },
  3627. next => {
  3628. StationsModule.runJob("GET_STATION", { stationId }, this)
  3629. .then(station => next(null, station))
  3630. .catch(next);
  3631. }
  3632. ],
  3633. async (err, station) => {
  3634. if (err) {
  3635. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3636. this.log("ERROR", "UNFAVORITE_STATION", `Unfavoriting station "${stationId}" failed. "${err}"`);
  3637. return cb({ status: "error", message: err });
  3638. }
  3639. this.log("SUCCESS", "UNFAVORITE_STATION", `Unfavorited station "${stationId}" successfully.`);
  3640. CacheModule.runJob("PUB", {
  3641. channel: "user.unfavoritedStation",
  3642. value: {
  3643. userId: session.userId,
  3644. stationId
  3645. }
  3646. });
  3647. ActivitiesModule.runJob("ADD_ACTIVITY", {
  3648. userId: session.userId,
  3649. type: "station__unfavorite",
  3650. payload: {
  3651. message: `Unfavorited station <stationId>${station.displayName}</stationId>`,
  3652. stationId
  3653. }
  3654. });
  3655. return cb({
  3656. status: "success",
  3657. message: "Succesfully unfavorited station."
  3658. });
  3659. }
  3660. );
  3661. }),
  3662. /**
  3663. * Clears every station queue
  3664. *
  3665. * @param {object} session - the session object automatically added by socket.io
  3666. * @param {Function} cb - gets called with the result
  3667. */
  3668. clearEveryStationQueue: isAdminRequired(async function clearEveryStationQueue(session, cb) {
  3669. async.waterfall(
  3670. [
  3671. next => {
  3672. StationsModule.runJob("CLEAR_EVERY_STATION_QUEUE", {}, this)
  3673. .then(() => next())
  3674. .catch(next);
  3675. }
  3676. ],
  3677. async err => {
  3678. if (err) {
  3679. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3680. this.log("ERROR", "CLEAR_EVERY_STATION_QUEUE", `Clearing every station queue failed. "${err}"`);
  3681. return cb({ status: "error", message: err });
  3682. }
  3683. this.log("SUCCESS", "CLEAR_EVERY_STATION_QUEUE", "Clearing every station queue was successful.");
  3684. return cb({ status: "success", message: "Successfully cleared every station queue." });
  3685. }
  3686. );
  3687. }),
  3688. /**
  3689. * Clears and refills a station queue
  3690. *
  3691. * @param {object} session - the session object automatically added by socket.io
  3692. * @param {string} stationId - the station id
  3693. * @param {Function} cb - gets called with the result
  3694. */
  3695. clearAndRefillStationQueue: isAdminRequired(async function clearAndRefillStationQueue(session, stationId, cb) {
  3696. async.waterfall(
  3697. [
  3698. next => {
  3699. StationsModule.runJob("CLEAR_AND_REFILL_STATION_QUEUE", { stationId }, this)
  3700. .then(() => next())
  3701. .catch(next);
  3702. }
  3703. ],
  3704. async err => {
  3705. if (err) {
  3706. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3707. this.log(
  3708. "ERROR",
  3709. "CLEAR_AND_REFILL_STATION_QUEUE",
  3710. `Clearing and refilling station queue failed. "${err}"`
  3711. );
  3712. return cb({ status: "error", message: err });
  3713. }
  3714. this.log(
  3715. "SUCCESS",
  3716. "CLEAR_AND_REFILL_STATION_QUEUE",
  3717. "Clearing and refilling station queue was successful."
  3718. );
  3719. return cb({ status: "success", message: "Successfully cleared and refilled station queue." });
  3720. }
  3721. );
  3722. })
  3723. };