stations.js 83 KB

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