stations.js 103 KB

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