stations.js 83 KB

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