stations.js 83 KB

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