stations.js 104 KB

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