stations.js 98 KB

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