stations.js 98 KB

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