stations.js 86 KB

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