stations.js 103 KB

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