stations.js 88 KB

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