stations.js 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017
  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. return next(null, song);
  2776. },
  2777. // (song, station, next) => {
  2778. // song.requestedBy = session.userId;
  2779. // song.requestedAt = Date.now();
  2780. // let totalDuration = 0;
  2781. // station.queue.forEach(song => {
  2782. // totalDuration += song.duration;
  2783. // });
  2784. // if (totalDuration >= 3600 * 3) return next("The max length of the queue is 3 hours.");
  2785. // return next(null, song, station);
  2786. // },
  2787. // (song, station, next) => {
  2788. // if (station.queue.length === 0) return next(null, song, station);
  2789. // let totalDuration = 0;
  2790. // const userId = station.queue[station.queue.length - 1].requestedBy;
  2791. // station.queue.forEach(song => {
  2792. // if (userId === song.requestedBy) {
  2793. // totalDuration += song.duration;
  2794. // }
  2795. // });
  2796. // if (totalDuration >= 900) return next("The max length of songs per user is 15 minutes.");
  2797. // return next(null, song, station);
  2798. // },
  2799. // (song, station, next) => {
  2800. // if (station.queue.length === 0) return next(null, song);
  2801. // let totalSongs = 0;
  2802. // const userId = station.queue[station.queue.length - 1].requestedBy;
  2803. // station.queue.forEach(song => {
  2804. // if (userId === song.requestedBy) {
  2805. // totalSongs += 1;
  2806. // }
  2807. // });
  2808. // if (totalSongs <= 2) return next(null, song);
  2809. // if (totalSongs > 3)
  2810. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  2811. // if (
  2812. // station.queue[station.queue.length - 2].requestedBy !== userId ||
  2813. // station.queue[station.queue.length - 3] !== userId
  2814. // )
  2815. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  2816. // return next(null, song);
  2817. // },
  2818. (song, next) => {
  2819. stationModel.updateOne(
  2820. { _id: stationId },
  2821. { $push: { queue: song } },
  2822. { runValidators: true },
  2823. next
  2824. );
  2825. },
  2826. (res, next) => {
  2827. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2828. .then(station => next(null, station))
  2829. .catch(next);
  2830. }
  2831. // (res, next) => {
  2832. // StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2833. // .then(station => {
  2834. // next(null, station);
  2835. // })
  2836. // .catch(next);
  2837. // }
  2838. ],
  2839. async err => {
  2840. if (err) {
  2841. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2842. this.log(
  2843. "ERROR",
  2844. "STATIONS_ADD_SONG_TO_QUEUE",
  2845. `Adding song "${youtubeId}" to station "${stationId}" queue failed. "${err}"`
  2846. );
  2847. return cb({ status: "error", message: err });
  2848. }
  2849. this.log(
  2850. "SUCCESS",
  2851. "STATIONS_ADD_SONG_TO_QUEUE",
  2852. `Added song "${youtubeId}" to station "${stationId}" successfully.`
  2853. );
  2854. CacheModule.runJob("PUB", {
  2855. channel: "station.queueUpdate",
  2856. value: stationId
  2857. });
  2858. return cb({
  2859. status: "success",
  2860. message: "Successfully added song to queue."
  2861. });
  2862. }
  2863. );
  2864. }),
  2865. /**
  2866. * Removes song from station queue
  2867. *
  2868. * @param session
  2869. * @param stationId - the station id
  2870. * @param youtubeId - the youtube id
  2871. * @param cb
  2872. */
  2873. removeFromQueue: isOwnerRequired(async function removeFromQueue(session, stationId, youtubeId, cb) {
  2874. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2875. async.waterfall(
  2876. [
  2877. next => {
  2878. if (!youtubeId) return next("Invalid youtube id.");
  2879. return StationsModule.runJob("GET_STATION", { stationId }, this)
  2880. .then(station => next(null, station))
  2881. .catch(next);
  2882. },
  2883. (station, next) => {
  2884. if (!station) return next("Station not found.");
  2885. return async.each(
  2886. station.queue,
  2887. (queueSong, next) => {
  2888. if (queueSong.youtubeId === youtubeId) return next(true);
  2889. return next();
  2890. },
  2891. err => {
  2892. if (err === true) return next();
  2893. return next("Song is not currently in the queue.");
  2894. }
  2895. );
  2896. },
  2897. next => {
  2898. stationModel.updateOne({ _id: stationId }, { $pull: { queue: { youtubeId } } }, next);
  2899. },
  2900. (res, next) => {
  2901. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2902. .then(station => next(null, station))
  2903. .catch(next);
  2904. }
  2905. ],
  2906. async err => {
  2907. if (err) {
  2908. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2909. this.log(
  2910. "ERROR",
  2911. "STATIONS_REMOVE_SONG_TO_QUEUE",
  2912. `Removing song "${youtubeId}" from station "${stationId}" queue failed. "${err}"`
  2913. );
  2914. return cb({ status: "error", message: err });
  2915. }
  2916. this.log(
  2917. "SUCCESS",
  2918. "STATIONS_REMOVE_SONG_TO_QUEUE",
  2919. `Removed song "${youtubeId}" from station "${stationId}" successfully.`
  2920. );
  2921. CacheModule.runJob("PUB", {
  2922. channel: "station.queueUpdate",
  2923. value: stationId
  2924. });
  2925. return cb({
  2926. status: "success",
  2927. message: "Successfully removed song from queue."
  2928. });
  2929. }
  2930. );
  2931. }),
  2932. /**
  2933. * Gets the queue from a station
  2934. *
  2935. * @param {object} session - user session
  2936. * @param {string} stationId - the station id
  2937. * @param {Function} cb - callback
  2938. */
  2939. getQueue(session, stationId, cb) {
  2940. async.waterfall(
  2941. [
  2942. next => {
  2943. StationsModule.runJob("GET_STATION", { stationId }, this)
  2944. .then(station => next(null, station))
  2945. .catch(next);
  2946. },
  2947. (station, next) => {
  2948. if (!station) return next("Station not found.");
  2949. return next(null, station);
  2950. },
  2951. (station, next) => {
  2952. StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  2953. .then(canView => {
  2954. if (canView) return next(null, station);
  2955. return next("Insufficient permissions.");
  2956. })
  2957. .catch(err => next(err));
  2958. },
  2959. (station, next) => next(null, station.queue)
  2960. ],
  2961. async (err, queue) => {
  2962. if (err) {
  2963. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2964. this.log(
  2965. "ERROR",
  2966. "STATIONS_GET_QUEUE",
  2967. `Getting queue for station "${stationId}" failed. "${err}"`
  2968. );
  2969. return cb({ status: "error", message: err });
  2970. }
  2971. this.log("SUCCESS", "STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  2972. return cb({
  2973. status: "success",
  2974. message: "Successfully got queue.",
  2975. data: { queue }
  2976. });
  2977. }
  2978. );
  2979. },
  2980. /**
  2981. * Reposition a song in station queue
  2982. *
  2983. * @param {object} session - user session
  2984. * @param {object} song - contains details about the song that is to be repositioned
  2985. * @param {string} song.youtubeId - the youtube id of the song
  2986. * @param {number} song.newIndex - the new position for the song in the queue
  2987. * @param {number} song.oldIndex - the old position of the song in the queue
  2988. * @param {string} stationId - the station id
  2989. * @param {Function} cb - callback
  2990. */
  2991. repositionSongInQueue: isOwnerRequired(async function repositionQueue(session, stationId, song, cb) {
  2992. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2993. async.waterfall(
  2994. [
  2995. next => {
  2996. if (!song || !song.youtubeId) return next("You must provide a song to reposition.");
  2997. return next();
  2998. },
  2999. // remove song from queue
  3000. next => {
  3001. stationModel.updateOne(
  3002. { _id: stationId },
  3003. { $pull: { queue: { youtubeId: song.youtubeId } } },
  3004. next
  3005. );
  3006. },
  3007. // add song back to queue (in new position)
  3008. (res, next) => {
  3009. stationModel.updateOne(
  3010. { _id: stationId },
  3011. { $push: { queue: { $each: [song], $position: song.newIndex } } },
  3012. err => next(err)
  3013. );
  3014. },
  3015. // update the cache representation of the station
  3016. next => {
  3017. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  3018. .then(station => next(null, station))
  3019. .catch(next);
  3020. }
  3021. ],
  3022. async err => {
  3023. if (err) {
  3024. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3025. this.log(
  3026. "ERROR",
  3027. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  3028. `Repositioning song ${song.youtubeId} in queue of station "${stationId}" failed. "${err}"`
  3029. );
  3030. return cb({ status: "error", message: err });
  3031. }
  3032. this.log(
  3033. "SUCCESS",
  3034. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  3035. `Repositioned song ${song.youtubeId} in queue of station "${stationId}" successfully.`
  3036. );
  3037. CacheModule.runJob("PUB", {
  3038. channel: "station.repositionSongInQueue",
  3039. value: {
  3040. song: {
  3041. youtubeId: song.youtubeId,
  3042. oldIndex: song.oldIndex,
  3043. newIndex: song.newIndex
  3044. },
  3045. stationId
  3046. }
  3047. });
  3048. return cb({
  3049. status: "success",
  3050. message: "Successfully repositioned song in queue."
  3051. });
  3052. }
  3053. );
  3054. }),
  3055. /**
  3056. * Includes a playlist in a station
  3057. *
  3058. * @param session
  3059. * @param stationId - the station id
  3060. * @param playlistId - the playlist id
  3061. * @param cb
  3062. */
  3063. includePlaylist: isOwnerRequired(async function includePlaylist(session, stationId, playlistId, cb) {
  3064. async.waterfall(
  3065. [
  3066. next => {
  3067. StationsModule.runJob("GET_STATION", { stationId }, this)
  3068. .then(station => next(null, station))
  3069. .catch(next);
  3070. },
  3071. (station, next) => {
  3072. if (!station) return next("Station not found.");
  3073. if (station.includedPlaylists.indexOf(playlistId) !== -1)
  3074. return next("That playlist is already included.");
  3075. if (station.playMode === "sequential" && station.includedPlaylists.length > 0)
  3076. return next("Error: Only 1 playlist can be included in sequential play mode.");
  3077. return next();
  3078. },
  3079. next => {
  3080. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  3081. .then(() => {
  3082. next();
  3083. })
  3084. .catch(next);
  3085. }
  3086. ],
  3087. async err => {
  3088. if (err) {
  3089. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3090. this.log(
  3091. "ERROR",
  3092. "STATIONS_INCLUDE_PLAYLIST",
  3093. `Including playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3094. );
  3095. return cb({ status: "error", message: err });
  3096. }
  3097. this.log(
  3098. "SUCCESS",
  3099. "STATIONS_INCLUDE_PLAYLIST",
  3100. `Including playlist "${playlistId}" for station "${stationId}" successfully.`
  3101. );
  3102. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3103. CacheModule.runJob("PUB", {
  3104. channel: "station.includedPlaylist",
  3105. value: {
  3106. playlistId,
  3107. stationId
  3108. }
  3109. });
  3110. return cb({
  3111. status: "success",
  3112. message: "Successfully included playlist."
  3113. });
  3114. }
  3115. );
  3116. }),
  3117. /**
  3118. * Remove included a playlist from a station
  3119. *
  3120. * @param session
  3121. * @param stationId - the station id
  3122. * @param playlistId - the playlist id
  3123. * @param cb
  3124. */
  3125. removeIncludedPlaylist: isOwnerRequired(async function removeIncludedPlaylist(session, stationId, playlistId, cb) {
  3126. async.waterfall(
  3127. [
  3128. next => {
  3129. StationsModule.runJob("GET_STATION", { stationId }, this)
  3130. .then(station => next(null, station))
  3131. .catch(next);
  3132. },
  3133. (station, next) => {
  3134. if (!station) return next("Station not found.");
  3135. if (station.includedPlaylists.indexOf(playlistId) === -1)
  3136. return next("That playlist is not included.");
  3137. return next();
  3138. },
  3139. next => {
  3140. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  3141. .then(() => {
  3142. next();
  3143. })
  3144. .catch(next);
  3145. }
  3146. ],
  3147. async err => {
  3148. if (err) {
  3149. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3150. this.log(
  3151. "ERROR",
  3152. "STATIONS_REMOVE_INCLUDED_PLAYLIST",
  3153. `Removing included playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3154. );
  3155. return cb({ status: "error", message: err });
  3156. }
  3157. this.log(
  3158. "SUCCESS",
  3159. "STATIONS_REMOVE_INCLUDED_PLAYLIST",
  3160. `Removing included playlist "${playlistId}" for station "${stationId}" successfully.`
  3161. );
  3162. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3163. CacheModule.runJob("PUB", {
  3164. channel: "station.removedIncludedPlaylist",
  3165. value: {
  3166. playlistId,
  3167. stationId
  3168. }
  3169. });
  3170. return cb({
  3171. status: "success",
  3172. message: "Successfully removed included playlist."
  3173. });
  3174. }
  3175. );
  3176. }),
  3177. /**
  3178. * Excludes a playlist in a station
  3179. *
  3180. * @param session
  3181. * @param stationId - the station id
  3182. * @param playlistId - the playlist id
  3183. * @param cb
  3184. */
  3185. excludePlaylist: isOwnerRequired(async function excludePlaylist(session, stationId, playlistId, cb) {
  3186. async.waterfall(
  3187. [
  3188. next => {
  3189. StationsModule.runJob("GET_STATION", { stationId }, this)
  3190. .then(station => next(null, station))
  3191. .catch(next);
  3192. },
  3193. (station, next) => {
  3194. if (!station) return next("Station not found.");
  3195. if (station.excludedPlaylists.indexOf(playlistId) !== -1)
  3196. return next("That playlist is already excluded.");
  3197. return next();
  3198. },
  3199. next => {
  3200. StationsModule.runJob("EXCLUDE_PLAYLIST", { stationId, playlistId }, this)
  3201. .then(() => {
  3202. next();
  3203. })
  3204. .catch(next);
  3205. }
  3206. ],
  3207. async err => {
  3208. if (err) {
  3209. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3210. this.log(
  3211. "ERROR",
  3212. "STATIONS_EXCLUDE_PLAYLIST",
  3213. `Excluding playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3214. );
  3215. return cb({ status: "error", message: err });
  3216. }
  3217. this.log(
  3218. "SUCCESS",
  3219. "STATIONS_EXCLUDE_PLAYLIST",
  3220. `Excluding playlist "${playlistId}" for station "${stationId}" successfully.`
  3221. );
  3222. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3223. CacheModule.runJob("PUB", {
  3224. channel: "station.excludedPlaylist",
  3225. value: {
  3226. playlistId,
  3227. stationId
  3228. }
  3229. });
  3230. return cb({
  3231. status: "success",
  3232. message: "Successfully excluded playlist."
  3233. });
  3234. }
  3235. );
  3236. }),
  3237. /**
  3238. * Remove excluded a playlist from a station
  3239. *
  3240. * @param session
  3241. * @param stationId - the station id
  3242. * @param playlistId - the playlist id
  3243. * @param cb
  3244. */
  3245. removeExcludedPlaylist: isOwnerRequired(async function removeExcludedPlaylist(session, stationId, playlistId, cb) {
  3246. async.waterfall(
  3247. [
  3248. next => {
  3249. StationsModule.runJob("GET_STATION", { stationId }, this)
  3250. .then(station => next(null, station))
  3251. .catch(next);
  3252. },
  3253. (station, next) => {
  3254. if (!station) return next("Station not found.");
  3255. if (station.excludedPlaylists.indexOf(playlistId) === -1)
  3256. return next("That playlist is not excluded.");
  3257. return next();
  3258. },
  3259. next => {
  3260. StationsModule.runJob("REMOVE_EXCLUDED_PLAYLIST", { stationId, playlistId }, this)
  3261. .then(() => {
  3262. next();
  3263. })
  3264. .catch(next);
  3265. }
  3266. ],
  3267. async err => {
  3268. if (err) {
  3269. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3270. this.log(
  3271. "ERROR",
  3272. "STATIONS_REMOVE_EXCLUDED_PLAYLIST",
  3273. `Removing excluded playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3274. );
  3275. return cb({ status: "error", message: err });
  3276. }
  3277. this.log(
  3278. "SUCCESS",
  3279. "STATIONS_REMOVE_EXCLUDED_PLAYLIST",
  3280. `Removing excluded playlist "${playlistId}" for station "${stationId}" successfully.`
  3281. );
  3282. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3283. CacheModule.runJob("PUB", {
  3284. channel: "station.removedExcludedPlaylist",
  3285. value: {
  3286. playlistId,
  3287. stationId
  3288. }
  3289. });
  3290. return cb({
  3291. status: "success",
  3292. message: "Successfully removed excluded playlist."
  3293. });
  3294. }
  3295. );
  3296. }),
  3297. /**
  3298. * Selects a private playlist for a station
  3299. *
  3300. * @param session
  3301. * @param stationId - the station id
  3302. * @param playlistId - the private playlist id
  3303. * @param cb
  3304. */
  3305. selectPrivatePlaylist: isOwnerRequired(async function selectPrivatePlaylist(session, stationId, playlistId, cb) {
  3306. async.waterfall(
  3307. [
  3308. next => {
  3309. StationsModule.runJob("GET_STATION", { stationId }, this)
  3310. .then(station => next(null, station))
  3311. .catch(next);
  3312. },
  3313. (station, next) => {
  3314. if (!station) return next("Station not found.");
  3315. if (station.type !== "community") return next("Station is not a community station.");
  3316. if (station.includedPlaylists.indexOf(playlistId) !== -1)
  3317. return next("That playlist is already included.");
  3318. return next();
  3319. },
  3320. next => {
  3321. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  3322. .then(() => {
  3323. next();
  3324. })
  3325. .catch(next);
  3326. }
  3327. ],
  3328. async err => {
  3329. if (err) {
  3330. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3331. this.log(
  3332. "ERROR",
  3333. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  3334. `Selecting private playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3335. );
  3336. return cb({ status: "error", message: err });
  3337. }
  3338. this.log(
  3339. "SUCCESS",
  3340. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  3341. `Selected private playlist "${playlistId}" for station "${stationId}" successfully.`
  3342. );
  3343. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3344. // CacheModule.runJob("PUB", {
  3345. // channel: "privatePlaylist.selected",
  3346. // value: {
  3347. // playlistId,
  3348. // stationId
  3349. // }
  3350. // });
  3351. return cb({
  3352. status: "success",
  3353. message: "Successfully selected playlist."
  3354. });
  3355. }
  3356. );
  3357. }),
  3358. /**
  3359. * Deselects the private playlist selected in a station
  3360. *
  3361. * @param session
  3362. * @param stationId - the station id
  3363. * @param cb
  3364. */
  3365. deselectPrivatePlaylist: isOwnerRequired(async function deselectPrivatePlaylist(
  3366. session,
  3367. stationId,
  3368. playlistId,
  3369. cb
  3370. ) {
  3371. async.waterfall(
  3372. [
  3373. next => {
  3374. StationsModule.runJob("GET_STATION", { stationId }, this)
  3375. .then(station => {
  3376. next(null, station);
  3377. })
  3378. .catch(next);
  3379. },
  3380. (station, next) => {
  3381. if (!station) return next("Station not found.");
  3382. if (station.type !== "community") return next("Station is not a community station.");
  3383. if (station.includedPlaylists.indexOf(playlistId) === -1)
  3384. return next("That playlist is not included.");
  3385. return next();
  3386. },
  3387. next => {
  3388. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  3389. .then(() => {
  3390. next();
  3391. })
  3392. .catch(next);
  3393. }
  3394. ],
  3395. async err => {
  3396. if (err) {
  3397. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3398. this.log(
  3399. "ERROR",
  3400. "STATIONS_DESELECT_PRIVATE_PLAYLIST",
  3401. `Deselecting private playlist for station "${stationId}" failed. "${err}"`
  3402. );
  3403. return cb({ status: "error", message: err });
  3404. }
  3405. this.log(
  3406. "SUCCESS",
  3407. "STATIONS_DESELECT_PRIVATE_PLAYLIST",
  3408. `Deselected private playlist for station "${stationId}" successfully.`
  3409. );
  3410. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3411. // CacheModule.runJob("PUB", {
  3412. // channel: "privatePlaylist.deselected",
  3413. // value: {
  3414. // stationId
  3415. // }
  3416. // });
  3417. return cb({
  3418. status: "success",
  3419. message: "Successfully deselected playlist."
  3420. });
  3421. }
  3422. );
  3423. }),
  3424. favoriteStation: isLoginRequired(async function favoriteStation(session, stationId, cb) {
  3425. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  3426. async.waterfall(
  3427. [
  3428. next => {
  3429. StationsModule.runJob("GET_STATION", { stationId }, this)
  3430. .then(station => next(null, station))
  3431. .catch(next);
  3432. },
  3433. (station, next) => {
  3434. if (!station) return next("Station not found.");
  3435. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  3436. .then(canView => {
  3437. if (canView) return next(null, station);
  3438. return next("Insufficient permissions.");
  3439. })
  3440. .catch(err => next(err));
  3441. },
  3442. (station, next) => {
  3443. userModel.updateOne(
  3444. { _id: session.userId },
  3445. { $addToSet: { favoriteStations: stationId } },
  3446. (err, res) => next(err, station, res)
  3447. );
  3448. },
  3449. (station, res, next) => {
  3450. if (res.nModified === 0) return next("The station was already favorited.");
  3451. return next(null, station);
  3452. }
  3453. ],
  3454. async (err, station) => {
  3455. if (err) {
  3456. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3457. this.log("ERROR", "FAVORITE_STATION", `Favoriting station "${stationId}" failed. "${err}"`);
  3458. return cb({ status: "error", message: err });
  3459. }
  3460. this.log("SUCCESS", "FAVORITE_STATION", `Favorited station "${stationId}" successfully.`);
  3461. CacheModule.runJob("PUB", {
  3462. channel: "user.favoritedStation",
  3463. value: {
  3464. userId: session.userId,
  3465. stationId
  3466. }
  3467. });
  3468. ActivitiesModule.runJob("ADD_ACTIVITY", {
  3469. userId: session.userId,
  3470. type: "station__favorite",
  3471. payload: {
  3472. message: `Favorited station <stationId>${station.displayName}</stationId>`,
  3473. stationId
  3474. }
  3475. });
  3476. return cb({
  3477. status: "success",
  3478. message: "Succesfully favorited station."
  3479. });
  3480. }
  3481. );
  3482. }),
  3483. unfavoriteStation: isLoginRequired(async function unfavoriteStation(session, stationId, cb) {
  3484. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  3485. async.waterfall(
  3486. [
  3487. next => {
  3488. userModel.updateOne({ _id: session.userId }, { $pull: { favoriteStations: stationId } }, next);
  3489. },
  3490. (res, next) => {
  3491. if (res.nModified === 0) return next("The station wasn't favorited.");
  3492. return next();
  3493. },
  3494. next => {
  3495. StationsModule.runJob("GET_STATION", { stationId }, this)
  3496. .then(station => next(null, station))
  3497. .catch(next);
  3498. }
  3499. ],
  3500. async (err, station) => {
  3501. if (err) {
  3502. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3503. this.log("ERROR", "UNFAVORITE_STATION", `Unfavoriting station "${stationId}" failed. "${err}"`);
  3504. return cb({ status: "error", message: err });
  3505. }
  3506. this.log("SUCCESS", "UNFAVORITE_STATION", `Unfavorited station "${stationId}" successfully.`);
  3507. CacheModule.runJob("PUB", {
  3508. channel: "user.unfavoritedStation",
  3509. value: {
  3510. userId: session.userId,
  3511. stationId
  3512. }
  3513. });
  3514. ActivitiesModule.runJob("ADD_ACTIVITY", {
  3515. userId: session.userId,
  3516. type: "station__unfavorite",
  3517. payload: {
  3518. message: `Unfavorited station <stationId>${station.displayName}</stationId>`,
  3519. stationId
  3520. }
  3521. });
  3522. return cb({
  3523. status: "success",
  3524. message: "Succesfully unfavorited station."
  3525. });
  3526. }
  3527. );
  3528. }),
  3529. /**
  3530. * Clears every station queue
  3531. *
  3532. * @param {object} session - the session object automatically added by socket.io
  3533. * @param {Function} cb - gets called with the result
  3534. */
  3535. clearEveryStationQueue: isAdminRequired(async function clearEveryStationQueue(session, cb) {
  3536. async.waterfall(
  3537. [
  3538. next => {
  3539. StationsModule.runJob("CLEAR_EVERY_STATION_QUEUE", {}, this)
  3540. .then(() => next())
  3541. .catch(next);
  3542. }
  3543. ],
  3544. async err => {
  3545. if (err) {
  3546. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3547. this.log("ERROR", "CLEAR_EVERY_STATION_QUEUE", `Clearing every station queue failed. "${err}"`);
  3548. return cb({ status: "error", message: err });
  3549. }
  3550. this.log("SUCCESS", "CLEAR_EVERY_STATION_QUEUE", "Clearing every station queue was successful.");
  3551. return cb({ status: "success", message: "Successfully cleared every station queue." });
  3552. }
  3553. );
  3554. }),
  3555. /**
  3556. * Clears and refills a station queue
  3557. *
  3558. * @param {object} session - the session object automatically added by socket.io
  3559. * @param {string} stationId - the station id
  3560. * @param {Function} cb - gets called with the result
  3561. */
  3562. clearAndRefillStationQueue: isAdminRequired(async function clearAndRefillStationQueue(session, stationId, cb) {
  3563. async.waterfall(
  3564. [
  3565. next => {
  3566. StationsModule.runJob("CLEAR_AND_REFILL_STATION_QUEUE", { stationId }, this)
  3567. .then(() => next())
  3568. .catch(next);
  3569. }
  3570. ],
  3571. async err => {
  3572. if (err) {
  3573. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3574. this.log(
  3575. "ERROR",
  3576. "CLEAR_AND_REFILL_STATION_QUEUE",
  3577. `Clearing and refilling station queue failed. "${err}"`
  3578. );
  3579. return cb({ status: "error", message: err });
  3580. }
  3581. this.log(
  3582. "SUCCESS",
  3583. "CLEAR_AND_REFILL_STATION_QUEUE",
  3584. "Clearing and refilling station queue was successful."
  3585. );
  3586. return cb({ status: "success", message: "Successfully cleared and refilled station queue." });
  3587. }
  3588. );
  3589. }),
  3590. /**
  3591. * Gets skip votes for a station
  3592. *
  3593. * @param session
  3594. * @param stationId - the station id
  3595. * @param stationId - the song id to get skipvotes for
  3596. * @param cb
  3597. */
  3598. getSkipVotes: isLoginRequired(async function getSkipVotes(session, stationId, songId, cb) {
  3599. async.waterfall(
  3600. [
  3601. next => {
  3602. StationsModule.runJob("GET_STATION", { stationId }, this)
  3603. .then(res => next(null, res.currentSong))
  3604. .catch(console.log);
  3605. },
  3606. (currentSong, next) => {
  3607. if (currentSong && currentSong._id === songId)
  3608. next(null, {
  3609. skipVotes: currentSong.skipVotes.length,
  3610. skipVotesCurrent: true
  3611. });
  3612. else
  3613. next(null, {
  3614. skipVotes: 0,
  3615. skipVotesCurrent: false
  3616. });
  3617. }
  3618. ],
  3619. async (err, data) => {
  3620. if (err) {
  3621. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3622. this.log(
  3623. "ERROR",
  3624. "STATIONS_GET_SKIP_VOTES",
  3625. `User "${session.userId}" failed to get skip votes for ${stationId}. "${err}"`
  3626. );
  3627. return cb({ status: "error", message: err });
  3628. }
  3629. const { skipVotes, skipVotesCurrent } = data;
  3630. return cb({
  3631. status: "success",
  3632. data: {
  3633. skipVotes,
  3634. skipVotesCurrent
  3635. }
  3636. });
  3637. }
  3638. );
  3639. })
  3640. };