stations.js 102 KB

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