stations.js 104 KB

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