stations.js 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844
  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. currentSong: station.currentSong
  827. };
  828. next(null, data);
  829. }
  830. ],
  831. async (err, data) => {
  832. if (err) {
  833. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  834. this.log("ERROR", "GET_STATION_BY_ID", `Getting station "${stationId}" failed. "${err}"`);
  835. return cb({ status: "error", message: err });
  836. }
  837. this.log("SUCCESS", "GET_STATION_BY_ID", `Got station "${stationId}" successfully.`);
  838. return cb({ status: "success", data: { station: data } });
  839. }
  840. );
  841. },
  842. getStationIncludedPlaylistsById(session, stationId, cb) {
  843. async.waterfall(
  844. [
  845. next => {
  846. StationsModule.runJob("GET_STATION", { stationId }, this)
  847. .then(station => {
  848. next(null, station);
  849. })
  850. .catch(next);
  851. },
  852. (station, next) => {
  853. if (!station) return next("Station not found.");
  854. return StationsModule.runJob(
  855. "CAN_USER_VIEW_STATION",
  856. {
  857. station,
  858. userId: session.userId
  859. },
  860. this
  861. )
  862. .then(canView => {
  863. if (!canView) next("Not allowed to get station.");
  864. else next(null, station);
  865. })
  866. .catch(err => next(err));
  867. },
  868. (station, next) => {
  869. const playlists = [];
  870. async.eachLimit(
  871. station.includedPlaylists,
  872. 1,
  873. (playlistId, next) => {
  874. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  875. .then(playlist => {
  876. playlists.push(playlist);
  877. next();
  878. })
  879. .catch(() => {
  880. playlists.push(null);
  881. next();
  882. });
  883. },
  884. err => {
  885. next(err, playlists);
  886. }
  887. );
  888. }
  889. ],
  890. async (err, playlists) => {
  891. if (err) {
  892. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  893. this.log(
  894. "ERROR",
  895. "GET_STATION_INCLUDED_PLAYLISTS_BY_ID",
  896. `Getting station "${stationId}"'s included playlists failed. "${err}"`
  897. );
  898. return cb({ status: "error", message: err });
  899. }
  900. this.log(
  901. "SUCCESS",
  902. "GET_STATION_INCLUDED_PLAYLISTS_BY_ID",
  903. `Got station "${stationId}"'s included playlists successfully.`
  904. );
  905. return cb({ status: "success", data: { playlists } });
  906. }
  907. );
  908. },
  909. getStationExcludedPlaylistsById(session, stationId, cb) {
  910. async.waterfall(
  911. [
  912. next => {
  913. StationsModule.runJob("GET_STATION", { stationId }, this)
  914. .then(station => {
  915. next(null, station);
  916. })
  917. .catch(next);
  918. },
  919. (station, next) => {
  920. if (!station) return next("Station not found.");
  921. return StationsModule.runJob(
  922. "CAN_USER_VIEW_STATION",
  923. {
  924. station,
  925. userId: session.userId
  926. },
  927. this
  928. )
  929. .then(canView => {
  930. if (!canView) next("Not allowed to get station.");
  931. else next(null, station);
  932. })
  933. .catch(err => next(err));
  934. },
  935. (station, next) => {
  936. const playlists = [];
  937. async.eachLimit(
  938. station.excludedPlaylists,
  939. 1,
  940. (playlistId, next) => {
  941. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  942. .then(playlist => {
  943. playlists.push(playlist);
  944. next();
  945. })
  946. .catch(() => {
  947. playlists.push(null);
  948. next();
  949. });
  950. },
  951. err => {
  952. next(err, playlists);
  953. }
  954. );
  955. }
  956. ],
  957. async (err, playlists) => {
  958. if (err) {
  959. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  960. this.log(
  961. "ERROR",
  962. "GET_STATION_EXCLUDED_PLAYLISTS_BY_ID",
  963. `Getting station "${stationId}"'s excluded playlists failed. "${err}"`
  964. );
  965. return cb({ status: "error", message: err });
  966. }
  967. this.log(
  968. "SUCCESS",
  969. "GET_STATION_EXCLUDED_PLAYLISTS_BY_ID",
  970. `Got station "${stationId}"'s excluded playlists successfully.`
  971. );
  972. return cb({ status: "success", data: { playlists } });
  973. }
  974. );
  975. },
  976. /**
  977. * Toggles if a station is locked
  978. *
  979. * @param session
  980. * @param stationId - the station id
  981. * @param cb
  982. */
  983. toggleLock: isOwnerRequired(async function toggleLock(session, stationId, cb) {
  984. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  985. async.waterfall(
  986. [
  987. next => {
  988. StationsModule.runJob("GET_STATION", { stationId }, this)
  989. .then(station => {
  990. next(null, station);
  991. })
  992. .catch(next);
  993. },
  994. (station, next) => {
  995. stationModel.updateOne({ _id: stationId }, { $set: { locked: !station.locked } }, next);
  996. },
  997. (res, next) => {
  998. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  999. .then(station => {
  1000. next(null, station);
  1001. })
  1002. .catch(next);
  1003. }
  1004. ],
  1005. async (err, station) => {
  1006. if (err) {
  1007. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1008. this.log(
  1009. "ERROR",
  1010. "STATIONS_UPDATE_LOCKED_STATUS",
  1011. `Toggling the queue lock for station "${stationId}" failed. "${err}"`
  1012. );
  1013. return cb({ status: "error", message: err });
  1014. }
  1015. this.log(
  1016. "SUCCESS",
  1017. "STATIONS_UPDATE_LOCKED_STATUS",
  1018. `Toggled the queue lock for station "${stationId}" successfully to "${station.locked}".`
  1019. );
  1020. CacheModule.runJob("PUB", {
  1021. channel: "station.queueLockToggled",
  1022. value: {
  1023. stationId,
  1024. locked: station.locked
  1025. }
  1026. });
  1027. return cb({ status: "success", data: { locked: station.locked } });
  1028. }
  1029. );
  1030. }),
  1031. /**
  1032. * Votes to skip a station
  1033. *
  1034. * @param session
  1035. * @param stationId - the station id
  1036. * @param cb
  1037. */
  1038. voteSkip: isLoginRequired(async function voteSkip(session, stationId, cb) {
  1039. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1040. let skipVotes = 0;
  1041. let shouldSkip = false;
  1042. async.waterfall(
  1043. [
  1044. next => {
  1045. StationsModule.runJob("GET_STATION", { stationId }, this)
  1046. .then(station => next(null, station))
  1047. .catch(next);
  1048. },
  1049. (station, next) => {
  1050. if (!station) return next("Station not found.");
  1051. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  1052. .then(canView => {
  1053. if (canView) return next(null, station);
  1054. return next("Insufficient permissions.");
  1055. })
  1056. .catch(err => next(err));
  1057. },
  1058. (station, next) => {
  1059. if (!station.currentSong) return next("There is currently no song to skip.");
  1060. if (station.currentSong.skipVotes.indexOf(session.userId) !== -1)
  1061. return next("You have already voted to skip this song.");
  1062. return next(null, station);
  1063. },
  1064. (station, next) => {
  1065. stationModel.updateOne(
  1066. { _id: stationId },
  1067. { $push: { "currentSong.skipVotes": session.userId } },
  1068. next
  1069. );
  1070. },
  1071. (res, next) => {
  1072. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1073. .then(station => {
  1074. next(null, station);
  1075. })
  1076. .catch(next);
  1077. },
  1078. (station, next) => {
  1079. if (!station) return next("Station not found.");
  1080. return next(null, station);
  1081. },
  1082. (station, next) => {
  1083. skipVotes = station.currentSong.skipVotes.length;
  1084. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${stationId}` }, this)
  1085. .then(sockets => next(null, sockets))
  1086. .catch(next);
  1087. },
  1088. (sockets, next) => {
  1089. if (sockets.length <= skipVotes) {
  1090. shouldSkip = true;
  1091. return next();
  1092. }
  1093. const users = [];
  1094. return async.each(
  1095. sockets,
  1096. (socketId, next) => {
  1097. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  1098. .then(socket => {
  1099. if (socket.session && socket.session.userId) {
  1100. if (!users.includes(socket.session.userId)) users.push(socket.session.userId);
  1101. } else users.push(socketId);
  1102. return next();
  1103. })
  1104. .catch(next);
  1105. },
  1106. err => {
  1107. if (err) return next(err);
  1108. if (users.length <= skipVotes) shouldSkip = true;
  1109. return next();
  1110. }
  1111. );
  1112. }
  1113. ],
  1114. async err => {
  1115. if (err) {
  1116. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1117. this.log("ERROR", "STATIONS_VOTE_SKIP", `Vote skipping station "${stationId}" failed. "${err}"`);
  1118. return cb({ status: "error", message: err });
  1119. }
  1120. this.log("SUCCESS", "STATIONS_VOTE_SKIP", `Vote skipping "${stationId}" successful.`);
  1121. CacheModule.runJob("PUB", {
  1122. channel: "station.voteSkipSong",
  1123. value: stationId
  1124. });
  1125. if (shouldSkip) StationsModule.runJob("SKIP_STATION", { stationId });
  1126. return cb({
  1127. status: "success",
  1128. message: "Successfully voted to skip the song."
  1129. });
  1130. }
  1131. );
  1132. }),
  1133. /**
  1134. * Force skips a station
  1135. *
  1136. * @param session
  1137. * @param stationId - the station id
  1138. * @param cb
  1139. */
  1140. forceSkip: isOwnerRequired(function forceSkip(session, stationId, cb) {
  1141. async.waterfall(
  1142. [
  1143. next => {
  1144. StationsModule.runJob("GET_STATION", { stationId }, this)
  1145. .then(station => {
  1146. next(null, station);
  1147. })
  1148. .catch(next);
  1149. },
  1150. (station, next) => {
  1151. if (!station) return next("Station not found.");
  1152. return next();
  1153. }
  1154. ],
  1155. async err => {
  1156. if (err) {
  1157. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1158. this.log("ERROR", "STATIONS_FORCE_SKIP", `Force skipping station "${stationId}" failed. "${err}"`);
  1159. return cb({ status: "error", message: err });
  1160. }
  1161. StationsModule.runJob("SKIP_STATION", { stationId });
  1162. this.log("SUCCESS", "STATIONS_FORCE_SKIP", `Force skipped station "${stationId}" successfully.`);
  1163. return cb({
  1164. status: "success",
  1165. message: "Successfully skipped station."
  1166. });
  1167. }
  1168. );
  1169. }),
  1170. /**
  1171. * Leaves the user's current station
  1172. *
  1173. * @param {object} session - user session
  1174. * @param {string} stationId - id of station to leave
  1175. * @param {Function} cb - callback
  1176. */
  1177. leave(session, stationId, cb) {
  1178. async.waterfall(
  1179. [
  1180. next => {
  1181. StationsModule.runJob("GET_STATION", { stationId }, this)
  1182. .then(station => {
  1183. next(null, station);
  1184. })
  1185. .catch(next);
  1186. },
  1187. (station, next) => {
  1188. if (!station) return next("Station not found.");
  1189. return next();
  1190. }
  1191. ],
  1192. async (err, userCount) => {
  1193. if (err) {
  1194. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1195. this.log("ERROR", "STATIONS_LEAVE", `Leaving station "${stationId}" failed. "${err}"`);
  1196. return cb({ status: "error", message: err });
  1197. }
  1198. this.log("SUCCESS", "STATIONS_LEAVE", `Left station "${stationId}" successfully.`);
  1199. WSModule.runJob("SOCKET_LEAVE_ROOMS", { socketId: session });
  1200. delete StationsModule.userList[session.socketId];
  1201. return cb({
  1202. status: "success",
  1203. message: "Successfully left station.",
  1204. data: { userCount }
  1205. });
  1206. }
  1207. );
  1208. },
  1209. /**
  1210. * Updates a station's name
  1211. *
  1212. * @param session
  1213. * @param stationId - the station id
  1214. * @param newName - the new station name
  1215. * @param cb
  1216. */
  1217. updateName: isOwnerRequired(async function updateName(session, stationId, newName, cb) {
  1218. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1219. async.waterfall(
  1220. [
  1221. next => {
  1222. stationModel.updateOne(
  1223. { _id: stationId },
  1224. { $set: { name: newName } },
  1225. { runValidators: true },
  1226. next
  1227. );
  1228. },
  1229. (res, next) => {
  1230. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1231. .then(station => next(null, station))
  1232. .catch(next);
  1233. }
  1234. ],
  1235. async (err, station) => {
  1236. if (err) {
  1237. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1238. this.log(
  1239. "ERROR",
  1240. "STATIONS_UPDATE_NAME",
  1241. `Updating station "${stationId}" name to "${newName}" failed. "${err}"`
  1242. );
  1243. return cb({ status: "error", message: err });
  1244. }
  1245. this.log(
  1246. "SUCCESS",
  1247. "STATIONS_UPDATE_NAME",
  1248. `Updated station "${stationId}" name to "${newName}" successfully.`
  1249. );
  1250. CacheModule.runJob("PUB", {
  1251. channel: "station.nameUpdate",
  1252. value: { stationId, name: newName }
  1253. });
  1254. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1255. userId: session.userId,
  1256. type: "station__edit_name",
  1257. payload: {
  1258. message: `Changed name of station <stationId>${station.displayName}</stationId> to ${newName}`,
  1259. stationId
  1260. }
  1261. });
  1262. return cb({
  1263. status: "success",
  1264. message: "Successfully updated the name."
  1265. });
  1266. }
  1267. );
  1268. }),
  1269. /**
  1270. * Updates a station's display name
  1271. *
  1272. * @param session
  1273. * @param stationId - the station id
  1274. * @param newDisplayName - the new station display name
  1275. * @param cb
  1276. */
  1277. updateDisplayName: isOwnerRequired(async function updateDisplayName(session, stationId, newDisplayName, cb) {
  1278. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1279. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1280. async.waterfall(
  1281. [
  1282. next => {
  1283. stationModel.updateOne(
  1284. { _id: stationId },
  1285. { $set: { displayName: newDisplayName } },
  1286. { runValidators: true },
  1287. next
  1288. );
  1289. },
  1290. (res, next) => {
  1291. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1292. .then(station => next(null, station))
  1293. .catch(next);
  1294. },
  1295. (station, next) => {
  1296. playlistModel.updateOne(
  1297. { _id: station.playlist },
  1298. { $set: { displayName: `Station - ${station.displayName}` } },
  1299. err => {
  1300. next(err, station);
  1301. }
  1302. );
  1303. }
  1304. ],
  1305. async err => {
  1306. if (err) {
  1307. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1308. this.log(
  1309. "ERROR",
  1310. "STATIONS_UPDATE_DISPLAY_NAME",
  1311. `Updating station "${stationId}" displayName to "${newDisplayName}" failed. "${err}"`
  1312. );
  1313. return cb({ status: "error", message: err });
  1314. }
  1315. this.log(
  1316. "SUCCESS",
  1317. "STATIONS_UPDATE_DISPLAY_NAME",
  1318. `Updated station "${stationId}" displayName to "${newDisplayName}" successfully.`
  1319. );
  1320. CacheModule.runJob("PUB", {
  1321. channel: "station.displayNameUpdate",
  1322. value: { stationId, displayName: newDisplayName }
  1323. });
  1324. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1325. userId: session.userId,
  1326. type: "station__edit_display_name",
  1327. payload: {
  1328. message: `Changed display name of station <stationId>${newDisplayName}</stationId>`,
  1329. stationId
  1330. }
  1331. });
  1332. return cb({
  1333. status: "success",
  1334. message: "Successfully updated the display name."
  1335. });
  1336. }
  1337. );
  1338. }),
  1339. /**
  1340. * Updates a station's description
  1341. *
  1342. * @param session
  1343. * @param stationId - the station id
  1344. * @param newDescription - the new station description
  1345. * @param cb
  1346. */
  1347. updateDescription: isOwnerRequired(async function updateDescription(session, stationId, newDescription, cb) {
  1348. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1349. async.waterfall(
  1350. [
  1351. next => {
  1352. stationModel.updateOne(
  1353. { _id: stationId },
  1354. { $set: { description: newDescription } },
  1355. { runValidators: true },
  1356. next
  1357. );
  1358. },
  1359. (res, next) => {
  1360. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1361. .then(station => next(null, station))
  1362. .catch(next);
  1363. }
  1364. ],
  1365. async (err, station) => {
  1366. if (err) {
  1367. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1368. this.log(
  1369. "ERROR",
  1370. "STATIONS_UPDATE_DESCRIPTION",
  1371. `Updating station "${stationId}" description to "${newDescription}" failed. "${err}"`
  1372. );
  1373. return cb({ status: "error", message: err });
  1374. }
  1375. this.log(
  1376. "SUCCESS",
  1377. "STATIONS_UPDATE_DESCRIPTION",
  1378. `Updated station "${stationId}" description to "${newDescription}" successfully.`
  1379. );
  1380. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1381. userId: session.userId,
  1382. type: "station__edit_description",
  1383. payload: {
  1384. message: `Changed description of station <stationId>${station.displayName}</stationId> to ${newDescription}`,
  1385. stationId
  1386. }
  1387. });
  1388. CacheModule.runJob("PUB", {
  1389. channel: "station.descriptionUpdate",
  1390. value: { stationId, description: newDescription }
  1391. });
  1392. return cb({
  1393. status: "success",
  1394. message: "Successfully updated the description."
  1395. });
  1396. }
  1397. );
  1398. }),
  1399. /**
  1400. * Updates a station's privacy
  1401. *
  1402. * @param session
  1403. * @param stationId - the station id
  1404. * @param newPrivacy - the new station privacy
  1405. * @param cb
  1406. */
  1407. updatePrivacy: isOwnerRequired(async function updatePrivacy(session, stationId, newPrivacy, cb) {
  1408. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1409. let previousPrivacy = null;
  1410. async.waterfall(
  1411. [
  1412. next => {
  1413. stationModel.findOne({ _id: stationId }, next);
  1414. },
  1415. (station, next) => {
  1416. if (!station) next("No station found.");
  1417. else {
  1418. previousPrivacy = station.privacy;
  1419. next();
  1420. }
  1421. },
  1422. next => {
  1423. stationModel.updateOne(
  1424. { _id: stationId },
  1425. { $set: { privacy: newPrivacy } },
  1426. { runValidators: true },
  1427. next
  1428. );
  1429. },
  1430. (res, next) => {
  1431. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1432. .then(station => next(null, station))
  1433. .catch(next);
  1434. }
  1435. ],
  1436. async (err, station) => {
  1437. if (err) {
  1438. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1439. this.log(
  1440. "ERROR",
  1441. "STATIONS_UPDATE_PRIVACY",
  1442. `Updating station "${stationId}" privacy to "${newPrivacy}" failed. "${err}"`
  1443. );
  1444. return cb({ status: "error", message: err });
  1445. }
  1446. this.log(
  1447. "SUCCESS",
  1448. "STATIONS_UPDATE_PRIVACY",
  1449. `Updated station "${stationId}" privacy to "${newPrivacy}" successfully.`
  1450. );
  1451. CacheModule.runJob("PUB", {
  1452. channel: "station.privacyUpdate",
  1453. value: { stationId, previousPrivacy }
  1454. });
  1455. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1456. userId: session.userId,
  1457. type: "station__edit_privacy",
  1458. payload: {
  1459. message: `Changed privacy of station <stationId>${station.displayName}</stationId> to ${newPrivacy}`,
  1460. stationId
  1461. }
  1462. });
  1463. return cb({
  1464. status: "success",
  1465. message: "Successfully updated the privacy."
  1466. });
  1467. }
  1468. );
  1469. }),
  1470. /**
  1471. * Updates a station's genres
  1472. *
  1473. * @param session
  1474. * @param stationId - the station id
  1475. * @param newGenres - the new station genres
  1476. * @param cb
  1477. */
  1478. updateGenres: isOwnerRequired(async function updateGenres(session, stationId, newGenres, cb) {
  1479. async.waterfall(
  1480. [
  1481. next => {
  1482. StationsModule.runJob("GET_STATION", { stationId }, this)
  1483. .then(station => {
  1484. next(null, station);
  1485. })
  1486. .catch(next);
  1487. },
  1488. (station, next) => {
  1489. const playlists = [];
  1490. async.eachLimit(
  1491. newGenres,
  1492. 1,
  1493. (genre, next) => {
  1494. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre, includeSongs: false }, this)
  1495. .then(response => {
  1496. playlists.push(response.playlist);
  1497. next();
  1498. })
  1499. .catch(err => {
  1500. if (err.message === "Playlist not found")
  1501. next(
  1502. `The genre playlist for "${genre}" was not found. Please ensure that this genre playlist exists.`
  1503. );
  1504. else next(err);
  1505. });
  1506. },
  1507. err => {
  1508. next(
  1509. err,
  1510. station,
  1511. playlists.map(playlist => playlist._id.toString())
  1512. );
  1513. }
  1514. );
  1515. },
  1516. (station, playlists, next) => {
  1517. const playlistsToRemoveFromExcluded = playlists.filter(
  1518. playlistId => station.excludedPlaylists.indexOf(playlistId) !== -1
  1519. );
  1520. console.log(
  1521. `playlistsToRemoveFromExcluded: ${playlistsToRemoveFromExcluded.length}`,
  1522. playlistsToRemoveFromExcluded
  1523. );
  1524. async.eachLimit(
  1525. playlistsToRemoveFromExcluded,
  1526. 1,
  1527. (playlistId, next) => {
  1528. StationsModule.runJob("REMOVE_EXCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1529. .then(() => {
  1530. next();
  1531. })
  1532. .catch(next);
  1533. },
  1534. err => {
  1535. next(err, station, playlists);
  1536. }
  1537. );
  1538. },
  1539. (station, playlists, next) => {
  1540. const playlistsToRemoveFromIncluded = station.includedPlaylists.filter(
  1541. playlistId => playlists.indexOf(playlistId) === -1
  1542. );
  1543. console.log(
  1544. `playlistsToRemoveFromIncluded: ${playlistsToRemoveFromIncluded.length}`,
  1545. playlistsToRemoveFromIncluded
  1546. );
  1547. async.eachLimit(
  1548. playlistsToRemoveFromIncluded,
  1549. 1,
  1550. (playlistId, next) => {
  1551. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1552. .then(() => {
  1553. next();
  1554. })
  1555. .catch(next);
  1556. },
  1557. err => {
  1558. next(err, station, playlists);
  1559. }
  1560. );
  1561. },
  1562. (station, playlists, next) => {
  1563. const playlistsToAddToIncluded = playlists.filter(
  1564. playlistId => station.includedPlaylists.indexOf(playlistId) === -1
  1565. );
  1566. console.log(
  1567. `playlistsToAddToIncluded: ${playlistsToAddToIncluded.length}`,
  1568. playlistsToAddToIncluded
  1569. );
  1570. async.eachLimit(
  1571. playlistsToAddToIncluded,
  1572. 1,
  1573. (playlistId, next) => {
  1574. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  1575. .then(() => {
  1576. next();
  1577. })
  1578. .catch(next);
  1579. },
  1580. err => {
  1581. next(err);
  1582. }
  1583. );
  1584. },
  1585. next => {
  1586. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1587. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1588. .then(station => next(null, station))
  1589. .catch(next);
  1590. }
  1591. ],
  1592. async (err, station) => {
  1593. if (err) {
  1594. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1595. this.log(
  1596. "ERROR",
  1597. "STATIONS_UPDATE_GENRES",
  1598. `Updating station "${stationId}" genres to "${newGenres}" failed. "${err}"`
  1599. );
  1600. return cb({ status: "error", message: err });
  1601. }
  1602. this.log(
  1603. "SUCCESS",
  1604. "STATIONS_UPDATE_GENRES",
  1605. `Updated station "${stationId}" genres to "${newGenres}" successfully.`
  1606. );
  1607. if (newGenres.length > 0) {
  1608. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1609. userId: session.userId,
  1610. type: "station__edit_genres",
  1611. payload: {
  1612. message: `Updated genres of station <stationId>${station.displayName}</stationId> to
  1613. ${newGenres.join(", ")}`,
  1614. stationId
  1615. }
  1616. });
  1617. } else {
  1618. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1619. userId: session.userId,
  1620. type: "station__edit_genres",
  1621. payload: {
  1622. message: `Removed all genres of station <stationId>${station.displayName}</stationId>`,
  1623. stationId
  1624. }
  1625. });
  1626. }
  1627. return cb({
  1628. status: "success",
  1629. message: "Successfully updated the genres."
  1630. });
  1631. }
  1632. );
  1633. }),
  1634. /**
  1635. * Updates a station's blacklisted genres
  1636. *
  1637. * @param session
  1638. * @param stationId - the station id
  1639. * @param newBlacklistedGenres - the new station blacklisted genres
  1640. * @param cb
  1641. */
  1642. updateBlacklistedGenres: isOwnerRequired(async function updateBlacklistedGenres(
  1643. session,
  1644. stationId,
  1645. newBlacklistedGenres,
  1646. cb
  1647. ) {
  1648. async.waterfall(
  1649. [
  1650. next => {
  1651. StationsModule.runJob("GET_STATION", { stationId }, this)
  1652. .then(station => {
  1653. next(null, station);
  1654. })
  1655. .catch(next);
  1656. },
  1657. (station, next) => {
  1658. const playlists = [];
  1659. async.eachLimit(
  1660. newBlacklistedGenres,
  1661. 1,
  1662. (genre, next) => {
  1663. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre, includeSongs: false }, this)
  1664. .then(response => {
  1665. playlists.push(response.playlist);
  1666. next();
  1667. })
  1668. .catch(err => {
  1669. if (err.message === "Playlist not found")
  1670. next(
  1671. `The genre playlist for "${genre}" was not found. Please ensure that this genre playlist exists.`
  1672. );
  1673. else next(err);
  1674. });
  1675. },
  1676. err => {
  1677. next(
  1678. err,
  1679. station,
  1680. playlists.map(playlist => playlist._id.toString())
  1681. );
  1682. }
  1683. );
  1684. },
  1685. (station, playlists, next) => {
  1686. const playlistsToRemoveFromIncluded = playlists.filter(
  1687. playlistId => station.includedPlaylists.indexOf(playlistId) !== -1
  1688. );
  1689. console.log(
  1690. `playlistsToRemoveFromIncluded: ${playlistsToRemoveFromIncluded.length}`,
  1691. playlistsToRemoveFromIncluded
  1692. );
  1693. async.eachLimit(
  1694. playlistsToRemoveFromIncluded,
  1695. 1,
  1696. (playlistId, next) => {
  1697. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1698. .then(() => {
  1699. next();
  1700. })
  1701. .catch(next);
  1702. },
  1703. err => {
  1704. next(err, station, playlists);
  1705. }
  1706. );
  1707. },
  1708. (station, playlists, next) => {
  1709. const playlistsToRemoveFromExcluded = station.excludedPlaylists.filter(
  1710. playlistId => playlists.indexOf(playlistId) === -1
  1711. );
  1712. console.log(
  1713. `playlistsToRemoveFromExcluded: ${playlistsToRemoveFromExcluded.length}`,
  1714. playlistsToRemoveFromExcluded
  1715. );
  1716. async.eachLimit(
  1717. playlistsToRemoveFromExcluded,
  1718. 1,
  1719. (playlistId, next) => {
  1720. StationsModule.runJob("REMOVE_EXCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1721. .then(() => {
  1722. next();
  1723. })
  1724. .catch(next);
  1725. },
  1726. err => {
  1727. next(err, station, playlists);
  1728. }
  1729. );
  1730. },
  1731. (station, playlists, next) => {
  1732. const playlistsToAddToExcluded = playlists.filter(
  1733. playlistId => station.excludedPlaylists.indexOf(playlistId) === -1
  1734. );
  1735. console.log(
  1736. `playlistsToAddToExcluded: ${playlistsToAddToExcluded.length}`,
  1737. playlistsToAddToExcluded
  1738. );
  1739. async.eachLimit(
  1740. playlistsToAddToExcluded,
  1741. 1,
  1742. (playlistId, next) => {
  1743. StationsModule.runJob("EXCLUDE_PLAYLIST", { stationId, playlistId }, this)
  1744. .then(() => {
  1745. next();
  1746. })
  1747. .catch(next);
  1748. },
  1749. err => {
  1750. next(err);
  1751. }
  1752. );
  1753. },
  1754. next => {
  1755. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1756. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1757. .then(station => next(null, station))
  1758. .catch(next);
  1759. }
  1760. ],
  1761. async (err, station) => {
  1762. if (err) {
  1763. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1764. this.log(
  1765. "ERROR",
  1766. "STATIONS_UPDATE_BLACKLISTED_GENRES",
  1767. `Updating station "${stationId}" blacklisted genres to "${newBlacklistedGenres}" failed. "${err}"`
  1768. );
  1769. return cb({ status: "error", message: err });
  1770. }
  1771. this.log(
  1772. "SUCCESS",
  1773. "STATIONS_UPDATE_BLACKLISTED_GENRES",
  1774. `Updated station "${stationId}" blacklisted genres to "${newBlacklistedGenres}" successfully.`
  1775. );
  1776. if (newBlacklistedGenres.length > 0) {
  1777. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1778. userId: session.userId,
  1779. type: "station__edit_blacklisted_genres",
  1780. payload: {
  1781. message: `Updated blacklisted genres of station <stationId>${
  1782. station.displayName
  1783. }</stationId> to ${newBlacklistedGenres.join(", ")}`,
  1784. stationId
  1785. }
  1786. });
  1787. } else {
  1788. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1789. userId: session.userId,
  1790. type: "station__edit_blacklisted_genres",
  1791. payload: {
  1792. message: `Removed all blacklisted genres of station <stationId>${station.displayName}</stationId>`,
  1793. stationId
  1794. }
  1795. });
  1796. }
  1797. return cb({
  1798. status: "success",
  1799. message: "Successfully updated the blacklisted genres."
  1800. });
  1801. }
  1802. );
  1803. }),
  1804. /**
  1805. * Updates a station's party mode
  1806. *
  1807. * @param session
  1808. * @param stationId - the station id
  1809. * @param newPartyMode - the new station party mode
  1810. * @param cb
  1811. */
  1812. updatePartyMode: isOwnerRequired(async function updatePartyMode(session, stationId, newPartyMode, cb) {
  1813. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1814. async.waterfall(
  1815. [
  1816. next => {
  1817. StationsModule.runJob("GET_STATION", { stationId }, this)
  1818. .then(station => {
  1819. next(null, station);
  1820. })
  1821. .catch(next);
  1822. },
  1823. (station, next) => {
  1824. if (!station) return next("Station not found.");
  1825. if (station.partyMode === newPartyMode)
  1826. return next(`The party mode was already ${newPartyMode ? "enabled." : "disabled."}`);
  1827. return stationModel.updateOne(
  1828. { _id: stationId },
  1829. { $set: { partyMode: newPartyMode, queue: [] } },
  1830. { runValidators: true },
  1831. next
  1832. );
  1833. },
  1834. (res, next) => {
  1835. CacheModule.runJob("PUB", {
  1836. channel: "station.queueUpdate",
  1837. value: stationId
  1838. })
  1839. .then()
  1840. .catch();
  1841. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1842. .then(station => {
  1843. next(null, station);
  1844. })
  1845. .catch(next);
  1846. }
  1847. ],
  1848. async err => {
  1849. if (err) {
  1850. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1851. this.log(
  1852. "ERROR",
  1853. "STATIONS_UPDATE_PARTY_MODE",
  1854. `Updating station "${stationId}" party mode to "${newPartyMode}" failed. "${err}"`
  1855. );
  1856. return cb({ status: "error", message: err });
  1857. }
  1858. this.log(
  1859. "SUCCESS",
  1860. "STATIONS_UPDATE_PARTY_MODE",
  1861. `Updated station "${stationId}" party mode to "${newPartyMode}" successfully.`
  1862. );
  1863. CacheModule.runJob("PUB", {
  1864. channel: "station.updatePartyMode",
  1865. value: {
  1866. stationId,
  1867. partyMode: newPartyMode
  1868. }
  1869. });
  1870. StationsModule.runJob("SKIP_STATION", { stationId });
  1871. return cb({
  1872. status: "success",
  1873. message: "Successfully updated the party mode."
  1874. });
  1875. }
  1876. );
  1877. }),
  1878. /**
  1879. * Updates a station's play mode
  1880. *
  1881. * @param session
  1882. * @param stationId - the station id
  1883. * @param newPlayMode - the new station play mode
  1884. * @param cb
  1885. */
  1886. updatePlayMode: isOwnerRequired(async function updatePartyMode(session, stationId, newPlayMode, cb) {
  1887. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1888. async.waterfall(
  1889. [
  1890. next => {
  1891. StationsModule.runJob("GET_STATION", { stationId }, this)
  1892. .then(station => {
  1893. next(null, station);
  1894. })
  1895. .catch(next);
  1896. },
  1897. (station, next) => {
  1898. if (!station) return next("Station not found.");
  1899. if (station.newPlayMode === newPlayMode) return next(`The play mode was already ${newPlayMode}`);
  1900. return stationModel.updateOne(
  1901. { _id: stationId },
  1902. { $set: { playMode: newPlayMode, queue: [] } },
  1903. { runValidators: true },
  1904. next
  1905. );
  1906. },
  1907. (res, next) => {
  1908. CacheModule.runJob("PUB", {
  1909. channel: "station.queueUpdate",
  1910. value: stationId
  1911. })
  1912. .then()
  1913. .catch();
  1914. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1915. .then(station => {
  1916. next(null, station);
  1917. })
  1918. .catch(next);
  1919. }
  1920. ],
  1921. async err => {
  1922. if (err) {
  1923. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1924. this.log(
  1925. "ERROR",
  1926. "STATIONS_UPDATE_PLAY_MODE",
  1927. `Updating station "${stationId}" play mode to "${newPlayMode}" failed. "${err}"`
  1928. );
  1929. return cb({ status: "error", message: err });
  1930. }
  1931. this.log(
  1932. "SUCCESS",
  1933. "STATIONS_UPDATE_PLAY_MODE",
  1934. `Updated station "${stationId}" play mode to "${newPlayMode}" successfully.`
  1935. );
  1936. CacheModule.runJob("PUB", {
  1937. channel: "station.newPlayMode",
  1938. value: {
  1939. stationId,
  1940. playMode: newPlayMode
  1941. }
  1942. });
  1943. StationsModule.runJob("SKIP_STATION", { stationId });
  1944. return cb({
  1945. status: "success",
  1946. message: "Successfully updated the play mode."
  1947. });
  1948. }
  1949. );
  1950. }),
  1951. /**
  1952. * Updates a station's theme
  1953. *
  1954. * @param session
  1955. * @param stationId - the station id
  1956. * @param newTheme - the new station theme
  1957. * @param cb
  1958. */
  1959. updateTheme: isOwnerRequired(async function updateTheme(session, stationId, newTheme, cb) {
  1960. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1961. async.waterfall(
  1962. [
  1963. next => {
  1964. StationsModule.runJob("GET_STATION", { stationId }, this)
  1965. .then(station => {
  1966. next(null, station);
  1967. })
  1968. .catch(next);
  1969. },
  1970. (station, next) => {
  1971. if (!station) return next("Station not found.");
  1972. if (station.theme === newTheme) return next("No change in theme.");
  1973. return stationModel.updateOne(
  1974. { _id: stationId },
  1975. { $set: { theme: newTheme } },
  1976. { runValidators: true },
  1977. next
  1978. );
  1979. },
  1980. (res, next) => {
  1981. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1982. .then(station => next(null, station))
  1983. .catch(next);
  1984. }
  1985. ],
  1986. async (err, station) => {
  1987. if (err) {
  1988. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1989. this.log(
  1990. "ERROR",
  1991. "STATIONS_UPDATE_THEME",
  1992. `Updating station "${stationId}" theme to "${newTheme}" failed. "${err}"`
  1993. );
  1994. return cb({ status: "error", message: err });
  1995. }
  1996. this.log(
  1997. "SUCCESS",
  1998. "STATIONS_UPDATE_THEME",
  1999. `Updated station "${stationId}" theme to "${newTheme}" successfully.`
  2000. );
  2001. CacheModule.runJob("PUB", {
  2002. channel: "station.themeUpdate",
  2003. value: { stationId }
  2004. });
  2005. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2006. userId: session.userId,
  2007. type: "station__edit_theme",
  2008. payload: {
  2009. message: `Changed theme of station <stationId>${station.displayName}</stationId> to ${newTheme}`,
  2010. stationId
  2011. }
  2012. });
  2013. return cb({
  2014. status: "success",
  2015. message: "Successfully updated the theme."
  2016. });
  2017. }
  2018. );
  2019. }),
  2020. /**
  2021. * Pauses a station
  2022. *
  2023. * @param session
  2024. * @param stationId - the station id
  2025. * @param cb
  2026. */
  2027. pause: isOwnerRequired(async function pause(session, stationId, cb) {
  2028. const stationModel = await DBModule.runJob(
  2029. "GET_MODEL",
  2030. {
  2031. modelName: "station"
  2032. },
  2033. this
  2034. );
  2035. async.waterfall(
  2036. [
  2037. next => {
  2038. StationsModule.runJob("GET_STATION", { stationId }, this)
  2039. .then(station => {
  2040. next(null, station);
  2041. })
  2042. .catch(next);
  2043. },
  2044. (station, next) => {
  2045. if (!station) return next("Station not found.");
  2046. if (station.paused) return next("That station was already paused.");
  2047. return stationModel.updateOne(
  2048. { _id: stationId },
  2049. { $set: { paused: true, pausedAt: Date.now() } },
  2050. next
  2051. );
  2052. },
  2053. (res, next) => {
  2054. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2055. .then(station => {
  2056. next(null, station);
  2057. })
  2058. .catch(next);
  2059. }
  2060. ],
  2061. async err => {
  2062. if (err) {
  2063. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2064. this.log("ERROR", "STATIONS_PAUSE", `Pausing station "${stationId}" failed. "${err}"`);
  2065. return cb({ status: "error", message: err });
  2066. }
  2067. this.log("SUCCESS", "STATIONS_PAUSE", `Paused station "${stationId}" successfully.`);
  2068. CacheModule.runJob("PUB", {
  2069. channel: "station.pause",
  2070. value: stationId
  2071. });
  2072. NotificationsModule.runJob("UNSCHEDULE", {
  2073. name: `stations.nextSong?id=${stationId}`
  2074. });
  2075. return cb({
  2076. status: "success",
  2077. message: "Successfully paused."
  2078. });
  2079. }
  2080. );
  2081. }),
  2082. /**
  2083. * Resumes a station
  2084. *
  2085. * @param session
  2086. * @param stationId - the station id
  2087. * @param cb
  2088. */
  2089. resume: isOwnerRequired(async function resume(session, stationId, cb) {
  2090. const stationModel = await DBModule.runJob(
  2091. "GET_MODEL",
  2092. {
  2093. modelName: "station"
  2094. },
  2095. this
  2096. );
  2097. async.waterfall(
  2098. [
  2099. next => {
  2100. StationsModule.runJob("GET_STATION", { stationId }, this)
  2101. .then(station => {
  2102. next(null, station);
  2103. })
  2104. .catch(next);
  2105. },
  2106. (station, next) => {
  2107. if (!station) return next("Station not found.");
  2108. if (!station.paused) return next("That station is not paused.");
  2109. station.timePaused += Date.now() - station.pausedAt;
  2110. return stationModel.updateOne(
  2111. { _id: stationId },
  2112. {
  2113. $set: { paused: false },
  2114. $inc: { timePaused: Date.now() - station.pausedAt }
  2115. },
  2116. next
  2117. );
  2118. },
  2119. (res, next) => {
  2120. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2121. .then(station => {
  2122. next(null, station);
  2123. })
  2124. .catch(next);
  2125. }
  2126. ],
  2127. async err => {
  2128. if (err) {
  2129. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2130. this.log("ERROR", "STATIONS_RESUME", `Resuming station "${stationId}" failed. "${err}"`);
  2131. return cb({ status: "error", message: err });
  2132. }
  2133. this.log("SUCCESS", "STATIONS_RESUME", `Resuming station "${stationId}" successfully.`);
  2134. CacheModule.runJob("PUB", {
  2135. channel: "station.resume",
  2136. value: stationId
  2137. });
  2138. return cb({
  2139. status: "success",
  2140. message: "Successfully resumed."
  2141. });
  2142. }
  2143. );
  2144. }),
  2145. /**
  2146. * Removes a station
  2147. *
  2148. * @param session
  2149. * @param stationId - the station id
  2150. * @param cb
  2151. */
  2152. remove: isOwnerRequired(async function remove(session, stationId, cb) {
  2153. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2154. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2155. async.waterfall(
  2156. [
  2157. next => {
  2158. stationModel.findById(stationId, (err, station) => {
  2159. if (err) return next(err);
  2160. return next(null, station);
  2161. });
  2162. },
  2163. (station, next) => {
  2164. stationModel.deleteOne({ _id: stationId }, err => next(err, station));
  2165. },
  2166. (station, next) => {
  2167. CacheModule.runJob("HDEL", { table: "stations", key: stationId }, this)
  2168. .then(() => next(null, station))
  2169. .catch(next);
  2170. },
  2171. (station, next) => {
  2172. if (station.playlist)
  2173. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: station.playlist })
  2174. .then(() => {})
  2175. .catch(next);
  2176. next(null, station);
  2177. },
  2178. // remove reference to the station id in any array of a user's favorite stations
  2179. (station, next) => {
  2180. userModel.updateMany(
  2181. { favoriteStations: stationId },
  2182. { $pull: { favoriteStations: stationId } },
  2183. err => next(err, station)
  2184. );
  2185. }
  2186. ],
  2187. async (err, station) => {
  2188. if (err) {
  2189. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2190. this.log("ERROR", "STATIONS_REMOVE", `Removing station "${stationId}" failed. "${err}"`);
  2191. return cb({ status: "error", message: err });
  2192. }
  2193. this.log("SUCCESS", "STATIONS_REMOVE", `Removing station "${stationId}" successfully.`);
  2194. CacheModule.runJob("PUB", {
  2195. channel: "station.remove",
  2196. value: stationId
  2197. });
  2198. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2199. userId: session.userId,
  2200. type: "station__remove",
  2201. payload: { message: `Removed a station named ${station.displayName}` }
  2202. });
  2203. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "stationId", stationId });
  2204. return cb({
  2205. status: "success",
  2206. message: "Successfully removed."
  2207. });
  2208. }
  2209. );
  2210. }),
  2211. /**
  2212. * Create a station
  2213. *
  2214. * @param session
  2215. * @param data - the station data
  2216. * @param cb
  2217. */
  2218. create: isLoginRequired(async function create(session, data, cb) {
  2219. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2220. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2221. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  2222. data.name = data.name.toLowerCase();
  2223. const blacklist = [
  2224. "country",
  2225. "edm",
  2226. "musare",
  2227. "hip-hop",
  2228. "rap",
  2229. "top-hits",
  2230. "todays-hits",
  2231. "old-school",
  2232. "christmas",
  2233. "about",
  2234. "support",
  2235. "staff",
  2236. "help",
  2237. "news",
  2238. "terms",
  2239. "privacy",
  2240. "profile",
  2241. "c",
  2242. "community",
  2243. "tos",
  2244. "login",
  2245. "register",
  2246. "p",
  2247. "official",
  2248. "o",
  2249. "trap",
  2250. "faq",
  2251. "team",
  2252. "donate",
  2253. "buy",
  2254. "shop",
  2255. "forums",
  2256. "explore",
  2257. "settings",
  2258. "admin",
  2259. "auth",
  2260. "reset_password",
  2261. "backend",
  2262. "api",
  2263. "songs",
  2264. "playlists",
  2265. "playlist"
  2266. ];
  2267. async.waterfall(
  2268. [
  2269. next => {
  2270. if (!data) return next("Invalid data.");
  2271. return next();
  2272. },
  2273. next => {
  2274. stationModel.findOne(
  2275. {
  2276. $or: [
  2277. { name: data.name },
  2278. {
  2279. displayName: new RegExp(`^${data.displayName}$`, "i")
  2280. }
  2281. ]
  2282. },
  2283. next
  2284. );
  2285. },
  2286. // eslint-disable-next-line consistent-return
  2287. (station, next) => {
  2288. this.log(station);
  2289. if (station) return next("A station with that name or display name already exists.");
  2290. const { name, displayName, description, /* playlist, */ type, genres, blacklistedGenres } = data;
  2291. const stationId = mongoose.Types.ObjectId();
  2292. if (type === "official") {
  2293. return userModel.findOne({ _id: session.userId }, (err, user) => {
  2294. if (err) return next(err);
  2295. if (!user) return next("User not found.");
  2296. if (user.role !== "admin") return next("Admin required.");
  2297. return async.waterfall(
  2298. [
  2299. next => {
  2300. const playlists = [];
  2301. async.eachLimit(
  2302. genres,
  2303. 1,
  2304. (genre, next) => {
  2305. PlaylistsModule.runJob(
  2306. "GET_GENRE_PLAYLIST",
  2307. { genre, includeSongs: false },
  2308. this
  2309. )
  2310. .then(response => {
  2311. playlists.push(response.playlist);
  2312. next();
  2313. })
  2314. .catch(err => {
  2315. next(
  2316. `An error occurred when trying to get genre playlist for genre ${genre}. Error: ${err}.`
  2317. );
  2318. });
  2319. },
  2320. err => {
  2321. next(
  2322. err,
  2323. playlists.map(playlist => playlist._id.toString())
  2324. );
  2325. }
  2326. );
  2327. },
  2328. (genrePlaylistIds, next) => {
  2329. const playlists = [];
  2330. async.eachLimit(
  2331. blacklistedGenres,
  2332. 1,
  2333. (genre, next) => {
  2334. PlaylistsModule.runJob(
  2335. "GET_GENRE_PLAYLIST",
  2336. { genre, includeSongs: false },
  2337. this
  2338. )
  2339. .then(response => {
  2340. playlists.push(response.playlist);
  2341. next();
  2342. })
  2343. .catch(err => {
  2344. next(
  2345. `An error occurred when trying to get genre playlist for genre ${genre}. Error: ${err}.`
  2346. );
  2347. });
  2348. },
  2349. err => {
  2350. next(
  2351. err,
  2352. genrePlaylistIds,
  2353. playlists.map(playlist => playlist._id.toString())
  2354. );
  2355. }
  2356. );
  2357. },
  2358. (genrePlaylistIds, blacklistedGenrePlaylistIds, next) => {
  2359. const duplicateGenre =
  2360. genrePlaylistIds.length !== new Set(genrePlaylistIds).size;
  2361. const duplicateBlacklistedGenre =
  2362. genrePlaylistIds.length !== new Set(genrePlaylistIds).size;
  2363. const duplicateCross =
  2364. genrePlaylistIds.length + blacklistedGenrePlaylistIds.length !==
  2365. new Set([...genrePlaylistIds, ...blacklistedGenrePlaylistIds]).size;
  2366. if (duplicateGenre)
  2367. return next("You cannot have the same genre included twice.");
  2368. if (duplicateBlacklistedGenre)
  2369. return next("You cannot have the same blacklisted genre included twice.");
  2370. if (duplicateCross)
  2371. return next(
  2372. "You cannot have the same genre included and blacklisted at the same time."
  2373. );
  2374. return next(null, genrePlaylistIds, blacklistedGenrePlaylistIds);
  2375. }
  2376. ],
  2377. (err, genrePlaylistIds, blacklistedGenrePlaylistIds) => {
  2378. if (err) return next(err);
  2379. return playlistModel.create(
  2380. {
  2381. isUserModifiable: false,
  2382. displayName: `Station - ${displayName}`,
  2383. songs: [],
  2384. createdBy: "Musare",
  2385. createdFor: `${stationId}`,
  2386. createdAt: Date.now(),
  2387. type: "station"
  2388. },
  2389. (err, playlist) => {
  2390. if (err) next(err);
  2391. else {
  2392. stationModel.create(
  2393. {
  2394. _id: stationId,
  2395. name,
  2396. displayName,
  2397. description,
  2398. type,
  2399. privacy: "private",
  2400. playlist: playlist._id,
  2401. currentSong: null
  2402. },
  2403. (err, station) => {
  2404. next(
  2405. err,
  2406. station,
  2407. genrePlaylistIds,
  2408. blacklistedGenrePlaylistIds
  2409. );
  2410. }
  2411. );
  2412. }
  2413. }
  2414. );
  2415. }
  2416. );
  2417. });
  2418. }
  2419. if (type === "community") {
  2420. if (blacklist.indexOf(name) !== -1)
  2421. return next("That name is blacklisted. Please use a different name.");
  2422. return playlistModel.create(
  2423. {
  2424. isUserModifiable: false,
  2425. displayName: `Station - ${name}`,
  2426. songs: [],
  2427. createdBy: session.userId,
  2428. createdFor: `${stationId}`,
  2429. createdAt: Date.now(),
  2430. type: "station"
  2431. },
  2432. (err, playlist) => {
  2433. if (err) next(err);
  2434. else {
  2435. stationModel.create(
  2436. {
  2437. _id: stationId,
  2438. name,
  2439. displayName,
  2440. description,
  2441. playlist: playlist._id,
  2442. type,
  2443. privacy: "private",
  2444. owner: session.userId,
  2445. queue: [],
  2446. currentSong: null
  2447. },
  2448. (err, station) => {
  2449. next(err, station, null, null);
  2450. }
  2451. );
  2452. }
  2453. }
  2454. );
  2455. }
  2456. },
  2457. (station, genrePlaylistIds, blacklistedGenrePlaylistIds, next) => {
  2458. if (station.type !== "official") return next(null, station);
  2459. const stationId = station._id;
  2460. console.log(111, station, genrePlaylistIds, blacklistedGenrePlaylistIds, next);
  2461. return async.waterfall(
  2462. [
  2463. next => {
  2464. async.eachLimit(
  2465. genrePlaylistIds,
  2466. 1,
  2467. (playlistId, next) => {
  2468. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  2469. .then(() => {
  2470. next();
  2471. })
  2472. .catch(next);
  2473. },
  2474. next
  2475. );
  2476. },
  2477. next => {
  2478. async.eachLimit(
  2479. blacklistedGenrePlaylistIds,
  2480. 1,
  2481. (playlistId, next) => {
  2482. StationsModule.runJob("EXCLUDE_PLAYLIST", { stationId, playlistId }, this)
  2483. .then(() => {
  2484. next();
  2485. })
  2486. .catch(next);
  2487. },
  2488. next
  2489. );
  2490. },
  2491. next => {
  2492. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2493. next();
  2494. }
  2495. ],
  2496. async err => {
  2497. if (err) {
  2498. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2499. this.log(
  2500. "ERROR",
  2501. "STATIONS_CREATE",
  2502. `Created station ${stationId} successfully, but an error occurred during playing including/excluding. Error: ${err}`
  2503. );
  2504. }
  2505. next(null, station, err);
  2506. }
  2507. );
  2508. }
  2509. ],
  2510. async (err, station, extraError) => {
  2511. if (err) {
  2512. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2513. this.log("ERROR", "STATIONS_CREATE", `Creating station failed. "${err}"`);
  2514. cb({ status: "error", message: err });
  2515. } else {
  2516. this.log("SUCCESS", "STATIONS_CREATE", `Created station "${station._id}" successfully.`);
  2517. CacheModule.runJob("PUB", {
  2518. channel: "station.create",
  2519. value: station._id
  2520. });
  2521. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2522. userId: session.userId,
  2523. type: "station__create",
  2524. payload: {
  2525. message: `Created a station named <stationId>${station.displayName}</stationId>`,
  2526. stationId: station._id
  2527. }
  2528. });
  2529. if (!extraError) {
  2530. cb({
  2531. status: "success",
  2532. message: "Successfully created station."
  2533. });
  2534. } else {
  2535. cb({
  2536. status: "success",
  2537. message: `Successfully created station, but with one error at the end: ${extraError}`
  2538. });
  2539. }
  2540. }
  2541. }
  2542. );
  2543. }),
  2544. /**
  2545. * Adds song to station queue
  2546. *
  2547. * @param session
  2548. * @param stationId - the station id
  2549. * @param youtubeId - the song id
  2550. * @param cb
  2551. */
  2552. addToQueue: isLoginRequired(async function addToQueue(session, stationId, youtubeId, cb) {
  2553. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2554. const stationModel = await DBModule.runJob(
  2555. "GET_MODEL",
  2556. {
  2557. modelName: "station"
  2558. },
  2559. this
  2560. );
  2561. async.waterfall(
  2562. [
  2563. next => {
  2564. StationsModule.runJob("GET_STATION", { stationId }, this)
  2565. .then(station => {
  2566. next(null, station);
  2567. })
  2568. .catch(next);
  2569. },
  2570. (station, next) => {
  2571. if (!station) return next("Station not found.");
  2572. if (!station.partyMode) return next("Station is not in party mode.");
  2573. if (station.locked) {
  2574. return userModel.findOne({ _id: session.userId }, (err, user) => {
  2575. if (user.role !== "admin" && station.owner !== session.userId)
  2576. return next("Only owners and admins can add songs to a locked queue.");
  2577. return next(null, station);
  2578. });
  2579. }
  2580. return next(null, station);
  2581. },
  2582. (station, next) => {
  2583. if (station.type !== "community") return next("That station is not a community station.");
  2584. return StationsModule.runJob(
  2585. "CAN_USER_VIEW_STATION",
  2586. {
  2587. station,
  2588. userId: session.userId
  2589. },
  2590. this
  2591. )
  2592. .then(canView => {
  2593. if (canView) return next(null, station);
  2594. return next("Insufficient permissions.");
  2595. })
  2596. .catch(err => next(err));
  2597. },
  2598. (station, next) => {
  2599. if (station.currentSong && station.currentSong.youtubeId === youtubeId)
  2600. return next("That song is currently playing.");
  2601. return async.each(
  2602. station.queue,
  2603. (queueSong, next) => {
  2604. if (queueSong.youtubeId === youtubeId) return next("That song is already in the queue.");
  2605. return next();
  2606. },
  2607. err => next(err, station)
  2608. );
  2609. },
  2610. (station, next) => {
  2611. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  2612. .then(UserModel => {
  2613. UserModel.findOne(
  2614. { _id: session.userId },
  2615. { "preferences.anonymousSongRequests": 1 },
  2616. (err, user) => next(err, station, user)
  2617. );
  2618. })
  2619. .catch(next);
  2620. },
  2621. (station, user, next) => {
  2622. SongsModule.runJob(
  2623. "ENSURE_SONG_EXISTS_BY_YOUTUBE_ID",
  2624. {
  2625. youtubeId,
  2626. userId: user.preferences.anonymousSongRequests ? null : session.userId,
  2627. automaticallyRequested: true
  2628. },
  2629. this
  2630. )
  2631. .then(response => {
  2632. const { song } = response;
  2633. const { _id, title, thumbnail, duration, status } = song;
  2634. next(
  2635. null,
  2636. {
  2637. _id,
  2638. youtubeId,
  2639. title,
  2640. thumbnail,
  2641. duration,
  2642. status
  2643. },
  2644. station
  2645. );
  2646. })
  2647. .catch(next);
  2648. },
  2649. (song, station, next) => {
  2650. const excludedPlaylists = [];
  2651. async.eachLimit(
  2652. station.excludedPlaylists,
  2653. 1,
  2654. (playlistId, next) => {
  2655. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  2656. .then(playlist => {
  2657. excludedPlaylists.push(playlist);
  2658. next();
  2659. })
  2660. .catch(next);
  2661. },
  2662. err => {
  2663. next(err, song, station, excludedPlaylists);
  2664. }
  2665. );
  2666. },
  2667. (song, station, excludedPlaylists, next) => {
  2668. const excludedSongs = excludedPlaylists
  2669. .flatMap(excludedPlaylist => excludedPlaylist.songs)
  2670. .reduce(
  2671. (items, item) =>
  2672. items.find(x => x.youtubeId === item.youtubeId) ? [...items] : [...items, item],
  2673. []
  2674. );
  2675. if (excludedSongs.find(excludedSong => excludedSong._id.toString() === song._id.toString()))
  2676. next("That song is in an excluded playlist and cannot be played.");
  2677. else next(null, song, station);
  2678. },
  2679. (song, station, next) => {
  2680. song.requestedBy = session.userId;
  2681. song.requestedAt = Date.now();
  2682. let totalDuration = 0;
  2683. station.queue.forEach(song => {
  2684. totalDuration += song.duration;
  2685. });
  2686. if (totalDuration >= 3600 * 3) return next("The max length of the queue is 3 hours.");
  2687. return next(null, song, station);
  2688. },
  2689. (song, station, next) => {
  2690. if (station.queue.length === 0) return next(null, song, station);
  2691. let totalDuration = 0;
  2692. const userId = station.queue[station.queue.length - 1].requestedBy;
  2693. station.queue.forEach(song => {
  2694. if (userId === song.requestedBy) {
  2695. totalDuration += song.duration;
  2696. }
  2697. });
  2698. if (totalDuration >= 900) return next("The max length of songs per user is 15 minutes.");
  2699. return next(null, song, station);
  2700. },
  2701. (song, station, next) => {
  2702. if (station.queue.length === 0) return next(null, song);
  2703. let totalSongs = 0;
  2704. const userId = station.queue[station.queue.length - 1].requestedBy;
  2705. station.queue.forEach(song => {
  2706. if (userId === song.requestedBy) {
  2707. totalSongs += 1;
  2708. }
  2709. });
  2710. if (totalSongs <= 2) return next(null, song);
  2711. if (totalSongs > 3)
  2712. return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  2713. if (
  2714. station.queue[station.queue.length - 2].requestedBy !== userId ||
  2715. station.queue[station.queue.length - 3] !== userId
  2716. )
  2717. return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  2718. return next(null, song);
  2719. },
  2720. (song, next) => {
  2721. stationModel.updateOne(
  2722. { _id: stationId },
  2723. { $push: { queue: song } },
  2724. { runValidators: true },
  2725. next
  2726. );
  2727. },
  2728. (res, next) => {
  2729. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2730. .then(station => next(null, station))
  2731. .catch(next);
  2732. }
  2733. // (res, next) => {
  2734. // StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2735. // .then(station => {
  2736. // next(null, station);
  2737. // })
  2738. // .catch(next);
  2739. // }
  2740. ],
  2741. async err => {
  2742. if (err) {
  2743. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2744. this.log(
  2745. "ERROR",
  2746. "STATIONS_ADD_SONG_TO_QUEUE",
  2747. `Adding song "${youtubeId}" to station "${stationId}" queue failed. "${err}"`
  2748. );
  2749. return cb({ status: "error", message: err });
  2750. }
  2751. this.log(
  2752. "SUCCESS",
  2753. "STATIONS_ADD_SONG_TO_QUEUE",
  2754. `Added song "${youtubeId}" to station "${stationId}" successfully.`
  2755. );
  2756. CacheModule.runJob("PUB", {
  2757. channel: "station.queueUpdate",
  2758. value: stationId
  2759. });
  2760. return cb({
  2761. status: "success",
  2762. message: "Successfully added song to queue."
  2763. });
  2764. }
  2765. );
  2766. }),
  2767. /**
  2768. * Removes song from station queue
  2769. *
  2770. * @param session
  2771. * @param stationId - the station id
  2772. * @param youtubeId - the youtube id
  2773. * @param cb
  2774. */
  2775. removeFromQueue: isOwnerRequired(async function removeFromQueue(session, stationId, youtubeId, cb) {
  2776. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2777. async.waterfall(
  2778. [
  2779. next => {
  2780. if (!youtubeId) return next("Invalid youtube id.");
  2781. return StationsModule.runJob("GET_STATION", { stationId }, this)
  2782. .then(station => next(null, station))
  2783. .catch(next);
  2784. },
  2785. (station, next) => {
  2786. if (!station) return next("Station not found.");
  2787. return async.each(
  2788. station.queue,
  2789. (queueSong, next) => {
  2790. if (queueSong.youtubeId === youtubeId) return next(true);
  2791. return next();
  2792. },
  2793. err => {
  2794. if (err === true) return next();
  2795. return next("Song is not currently in the queue.");
  2796. }
  2797. );
  2798. },
  2799. next => {
  2800. stationModel.updateOne({ _id: stationId }, { $pull: { queue: { youtubeId } } }, next);
  2801. },
  2802. (res, next) => {
  2803. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2804. .then(station => next(null, station))
  2805. .catch(next);
  2806. }
  2807. ],
  2808. async err => {
  2809. if (err) {
  2810. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2811. this.log(
  2812. "ERROR",
  2813. "STATIONS_REMOVE_SONG_TO_QUEUE",
  2814. `Removing song "${youtubeId}" from station "${stationId}" queue failed. "${err}"`
  2815. );
  2816. return cb({ status: "error", message: err });
  2817. }
  2818. this.log(
  2819. "SUCCESS",
  2820. "STATIONS_REMOVE_SONG_TO_QUEUE",
  2821. `Removed song "${youtubeId}" from station "${stationId}" successfully.`
  2822. );
  2823. CacheModule.runJob("PUB", {
  2824. channel: "station.queueUpdate",
  2825. value: stationId
  2826. });
  2827. return cb({
  2828. status: "success",
  2829. message: "Successfully removed song from queue."
  2830. });
  2831. }
  2832. );
  2833. }),
  2834. /**
  2835. * Gets the queue from a station
  2836. *
  2837. * @param {object} session - user session
  2838. * @param {string} stationId - the station id
  2839. * @param {Function} cb - callback
  2840. */
  2841. getQueue(session, stationId, cb) {
  2842. async.waterfall(
  2843. [
  2844. next => {
  2845. StationsModule.runJob("GET_STATION", { stationId }, this)
  2846. .then(station => next(null, station))
  2847. .catch(next);
  2848. },
  2849. (station, next) => {
  2850. if (!station) return next("Station not found.");
  2851. return next(null, station);
  2852. },
  2853. (station, next) => {
  2854. StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  2855. .then(canView => {
  2856. if (canView) return next(null, station);
  2857. return next("Insufficient permissions.");
  2858. })
  2859. .catch(err => next(err));
  2860. },
  2861. (station, next) => {
  2862. if (station.type === "official") next(null, station.queue);
  2863. else next(null, station.queue);
  2864. }
  2865. ],
  2866. async (err, queue) => {
  2867. if (err) {
  2868. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2869. this.log(
  2870. "ERROR",
  2871. "STATIONS_GET_QUEUE",
  2872. `Getting queue for station "${stationId}" failed. "${err}"`
  2873. );
  2874. return cb({ status: "error", message: err });
  2875. }
  2876. this.log("SUCCESS", "STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  2877. return cb({
  2878. status: "success",
  2879. message: "Successfully got queue.",
  2880. data: { queue }
  2881. });
  2882. }
  2883. );
  2884. },
  2885. /**
  2886. * Reposition a song in station queue
  2887. *
  2888. * @param {object} session - user session
  2889. * @param {object} song - contains details about the song that is to be repositioned
  2890. * @param {string} song.youtubeId - the youtube id of the song
  2891. * @param {number} song.newIndex - the new position for the song in the queue
  2892. * @param {number} song.oldIndex - the old position of the song in the queue
  2893. * @param {string} stationId - the station id
  2894. * @param {Function} cb - callback
  2895. */
  2896. repositionSongInQueue: isOwnerRequired(async function repositionQueue(session, song, stationId, cb) {
  2897. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2898. async.waterfall(
  2899. [
  2900. next => {
  2901. if (!song || !song.youtubeId) return next("You must provide a song to reposition.");
  2902. return next();
  2903. },
  2904. // remove song from queue
  2905. next => {
  2906. stationModel.updateOne(
  2907. { _id: stationId },
  2908. { $pull: { queue: { youtubeId: song.youtubeId } } },
  2909. next
  2910. );
  2911. },
  2912. // add song back to queue (in new position)
  2913. (res, next) => {
  2914. stationModel.updateOne(
  2915. { _id: stationId },
  2916. { $push: { queue: { $each: [song], $position: song.newIndex } } },
  2917. err => next(err)
  2918. );
  2919. },
  2920. // update the cache representation of the station
  2921. next => {
  2922. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2923. .then(station => next(null, station))
  2924. .catch(next);
  2925. }
  2926. ],
  2927. async err => {
  2928. console.log(err);
  2929. if (err) {
  2930. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2931. this.log(
  2932. "ERROR",
  2933. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  2934. `Repositioning song ${song.youtubeId} in queue of station "${stationId}" failed. "${err}"`
  2935. );
  2936. return cb({ status: "error", message: err });
  2937. }
  2938. this.log(
  2939. "SUCCESS",
  2940. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  2941. `Repositioned song ${song.youtubeId} in queue of station "${stationId}" successfully.`
  2942. );
  2943. CacheModule.runJob("PUB", {
  2944. channel: "station.repositionSongInQueue",
  2945. value: {
  2946. song: {
  2947. youtubeId: song.youtubeId,
  2948. oldIndex: song.oldIndex,
  2949. newIndex: song.newIndex
  2950. },
  2951. stationId
  2952. }
  2953. });
  2954. return cb({
  2955. status: "success",
  2956. message: "Successfully repositioned song in queue."
  2957. });
  2958. }
  2959. );
  2960. }),
  2961. /**
  2962. * Includes a playlist in a station
  2963. *
  2964. * @param session
  2965. * @param stationId - the station id
  2966. * @param playlistId - the playlist id
  2967. * @param cb
  2968. */
  2969. includePlaylist: isOwnerRequired(async function includePlaylist(session, stationId, playlistId, cb) {
  2970. async.waterfall(
  2971. [
  2972. next => {
  2973. StationsModule.runJob("GET_STATION", { stationId }, this)
  2974. .then(station => next(null, station))
  2975. .catch(next);
  2976. },
  2977. (station, next) => {
  2978. if (!station) return next("Station not found.");
  2979. if (station.includedPlaylists.indexOf(playlistId) !== -1)
  2980. return next("That playlist is already included.");
  2981. return next();
  2982. },
  2983. next => {
  2984. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  2985. .then(() => {
  2986. next();
  2987. })
  2988. .catch(next);
  2989. }
  2990. ],
  2991. async err => {
  2992. if (err) {
  2993. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2994. this.log(
  2995. "ERROR",
  2996. "STATIONS_INCLUDE_PLAYLIST",
  2997. `Including playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  2998. );
  2999. return cb({ status: "error", message: err });
  3000. }
  3001. this.log(
  3002. "SUCCESS",
  3003. "STATIONS_INCLUDE_PLAYLIST",
  3004. `Including playlist "${playlistId}" for station "${stationId}" successfully.`
  3005. );
  3006. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3007. // CacheModule.runJob("PUB", {
  3008. // channel: "privatePlaylist.selected",
  3009. // value: {
  3010. // playlistId,
  3011. // stationId
  3012. // }
  3013. // });
  3014. return cb({
  3015. status: "success",
  3016. message: "Successfully included playlist."
  3017. });
  3018. }
  3019. );
  3020. }),
  3021. /**
  3022. * Remove included a playlist from a station
  3023. *
  3024. * @param session
  3025. * @param stationId - the station id
  3026. * @param playlistId - the playlist id
  3027. * @param cb
  3028. */
  3029. removeIncludedPlaylist: isOwnerRequired(async function removeIncludedPlaylist(session, stationId, playlistId, cb) {
  3030. async.waterfall(
  3031. [
  3032. next => {
  3033. StationsModule.runJob("GET_STATION", { stationId }, this)
  3034. .then(station => next(null, station))
  3035. .catch(next);
  3036. },
  3037. (station, next) => {
  3038. if (!station) return next("Station not found.");
  3039. if (station.includedPlaylists.indexOf(playlistId) === -1)
  3040. return next("That playlist is not included.");
  3041. return next();
  3042. },
  3043. next => {
  3044. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  3045. .then(() => {
  3046. next();
  3047. })
  3048. .catch(next);
  3049. }
  3050. ],
  3051. async err => {
  3052. if (err) {
  3053. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3054. this.log(
  3055. "ERROR",
  3056. "STATIONS_REMOVE_INCLUDED_PLAYLIST",
  3057. `Removing included playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3058. );
  3059. return cb({ status: "error", message: err });
  3060. }
  3061. this.log(
  3062. "SUCCESS",
  3063. "STATIONS_REMOVE_INCLUDED_PLAYLIST",
  3064. `Removing included playlist "${playlistId}" for station "${stationId}" successfully.`
  3065. );
  3066. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3067. // CacheModule.runJob("PUB", {
  3068. // channel: "privatePlaylist.selected",
  3069. // value: {
  3070. // playlistId,
  3071. // stationId
  3072. // }
  3073. // });
  3074. return cb({
  3075. status: "success",
  3076. message: "Successfully removed included playlist."
  3077. });
  3078. }
  3079. );
  3080. }),
  3081. /**
  3082. * Excludes a playlist in a station
  3083. *
  3084. * @param session
  3085. * @param stationId - the station id
  3086. * @param playlistId - the playlist id
  3087. * @param cb
  3088. */
  3089. excludePlaylist: isOwnerRequired(async function excludePlaylist(session, stationId, playlistId, cb) {
  3090. async.waterfall(
  3091. [
  3092. next => {
  3093. StationsModule.runJob("GET_STATION", { stationId }, this)
  3094. .then(station => next(null, station))
  3095. .catch(next);
  3096. },
  3097. (station, next) => {
  3098. if (!station) return next("Station not found.");
  3099. if (station.excludedPlaylists.indexOf(playlistId) !== -1)
  3100. return next("That playlist is already excluded.");
  3101. return next();
  3102. },
  3103. next => {
  3104. StationsModule.runJob("EXCLUDE_PLAYLIST", { stationId, playlistId }, this)
  3105. .then(() => {
  3106. next();
  3107. })
  3108. .catch(next);
  3109. }
  3110. ],
  3111. async err => {
  3112. if (err) {
  3113. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3114. this.log(
  3115. "ERROR",
  3116. "STATIONS_EXCLUDE_PLAYLIST",
  3117. `Excluding playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3118. );
  3119. return cb({ status: "error", message: err });
  3120. }
  3121. this.log(
  3122. "SUCCESS",
  3123. "STATIONS_EXCLUDE_PLAYLIST",
  3124. `Excluding playlist "${playlistId}" for station "${stationId}" successfully.`
  3125. );
  3126. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3127. // CacheModule.runJob("PUB", {
  3128. // channel: "privatePlaylist.selected",
  3129. // value: {
  3130. // playlistId,
  3131. // stationId
  3132. // }
  3133. // });
  3134. return cb({
  3135. status: "success",
  3136. message: "Successfully excluded playlist."
  3137. });
  3138. }
  3139. );
  3140. }),
  3141. /**
  3142. * Remove excluded a playlist from a station
  3143. *
  3144. * @param session
  3145. * @param stationId - the station id
  3146. * @param playlistId - the playlist id
  3147. * @param cb
  3148. */
  3149. removeExcludedPlaylist: isOwnerRequired(async function removeExcludedPlaylist(session, stationId, playlistId, cb) {
  3150. async.waterfall(
  3151. [
  3152. next => {
  3153. StationsModule.runJob("GET_STATION", { stationId }, this)
  3154. .then(station => next(null, station))
  3155. .catch(next);
  3156. },
  3157. (station, next) => {
  3158. if (!station) return next("Station not found.");
  3159. if (station.excludedPlaylists.indexOf(playlistId) === -1)
  3160. return next("That playlist is not excluded.");
  3161. return next();
  3162. },
  3163. next => {
  3164. StationsModule.runJob("REMOVE_EXCLUDED_PLAYLIST", { stationId, playlistId }, this)
  3165. .then(() => {
  3166. next();
  3167. })
  3168. .catch(next);
  3169. }
  3170. ],
  3171. async err => {
  3172. if (err) {
  3173. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3174. this.log(
  3175. "ERROR",
  3176. "STATIONS_REMOVE_EXCLUDED_PLAYLIST",
  3177. `Removing excluded playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3178. );
  3179. return cb({ status: "error", message: err });
  3180. }
  3181. this.log(
  3182. "SUCCESS",
  3183. "STATIONS_REMOVE_EXCLUDED_PLAYLIST",
  3184. `Removing excluded playlist "${playlistId}" for station "${stationId}" successfully.`
  3185. );
  3186. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3187. // CacheModule.runJob("PUB", {
  3188. // channel: "privatePlaylist.selected",
  3189. // value: {
  3190. // playlistId,
  3191. // stationId
  3192. // }
  3193. // });
  3194. return cb({
  3195. status: "success",
  3196. message: "Successfully removed excluded playlist."
  3197. });
  3198. }
  3199. );
  3200. }),
  3201. /**
  3202. * Selects a private playlist for a station
  3203. *
  3204. * @param session
  3205. * @param stationId - the station id
  3206. * @param playlistId - the private playlist id
  3207. * @param cb
  3208. */
  3209. selectPrivatePlaylist: isOwnerRequired(async function selectPrivatePlaylist(session, stationId, playlistId, cb) {
  3210. async.waterfall(
  3211. [
  3212. next => {
  3213. StationsModule.runJob("GET_STATION", { stationId }, this)
  3214. .then(station => next(null, station))
  3215. .catch(next);
  3216. },
  3217. (station, next) => {
  3218. if (!station) return next("Station not found.");
  3219. if (station.type !== "community") return next("Station is not a community station.");
  3220. if (station.includedPlaylists.indexOf(playlistId) !== -1)
  3221. return next("That playlist is already included.");
  3222. return next();
  3223. },
  3224. next => {
  3225. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  3226. .then(() => {
  3227. next();
  3228. })
  3229. .catch(next);
  3230. }
  3231. ],
  3232. async err => {
  3233. if (err) {
  3234. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3235. this.log(
  3236. "ERROR",
  3237. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  3238. `Selecting private playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3239. );
  3240. return cb({ status: "error", message: err });
  3241. }
  3242. this.log(
  3243. "SUCCESS",
  3244. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  3245. `Selected private playlist "${playlistId}" for station "${stationId}" successfully.`
  3246. );
  3247. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3248. // CacheModule.runJob("PUB", {
  3249. // channel: "privatePlaylist.selected",
  3250. // value: {
  3251. // playlistId,
  3252. // stationId
  3253. // }
  3254. // });
  3255. return cb({
  3256. status: "success",
  3257. message: "Successfully selected playlist."
  3258. });
  3259. }
  3260. );
  3261. }),
  3262. /**
  3263. * Deselects the private playlist selected in a station
  3264. *
  3265. * @param session
  3266. * @param stationId - the station id
  3267. * @param cb
  3268. */
  3269. deselectPrivatePlaylist: isOwnerRequired(async function deselectPrivatePlaylist(
  3270. session,
  3271. stationId,
  3272. playlistId,
  3273. cb
  3274. ) {
  3275. async.waterfall(
  3276. [
  3277. next => {
  3278. StationsModule.runJob("GET_STATION", { stationId }, this)
  3279. .then(station => {
  3280. next(null, station);
  3281. })
  3282. .catch(next);
  3283. },
  3284. (station, next) => {
  3285. if (!station) return next("Station not found.");
  3286. if (station.type !== "community") return next("Station is not a community station.");
  3287. if (station.includedPlaylists.indexOf(playlistId) === -1)
  3288. return next("That playlist is not included.");
  3289. return next();
  3290. },
  3291. next => {
  3292. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  3293. .then(() => {
  3294. next();
  3295. })
  3296. .catch(next);
  3297. }
  3298. ],
  3299. async err => {
  3300. if (err) {
  3301. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3302. this.log(
  3303. "ERROR",
  3304. "STATIONS_DESELECT_PRIVATE_PLAYLIST",
  3305. `Deselecting private playlist for station "${stationId}" failed. "${err}"`
  3306. );
  3307. return cb({ status: "error", message: err });
  3308. }
  3309. this.log(
  3310. "SUCCESS",
  3311. "STATIONS_DESELECT_PRIVATE_PLAYLIST",
  3312. `Deselected private playlist for station "${stationId}" successfully.`
  3313. );
  3314. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3315. // CacheModule.runJob("PUB", {
  3316. // channel: "privatePlaylist.deselected",
  3317. // value: {
  3318. // stationId
  3319. // }
  3320. // });
  3321. return cb({
  3322. status: "success",
  3323. message: "Successfully deselected playlist."
  3324. });
  3325. }
  3326. );
  3327. }),
  3328. favoriteStation: isLoginRequired(async function favoriteStation(session, stationId, cb) {
  3329. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  3330. async.waterfall(
  3331. [
  3332. next => {
  3333. StationsModule.runJob("GET_STATION", { stationId }, this)
  3334. .then(station => next(null, station))
  3335. .catch(next);
  3336. },
  3337. (station, next) => {
  3338. if (!station) return next("Station not found.");
  3339. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  3340. .then(canView => {
  3341. if (canView) return next(null, station);
  3342. return next("Insufficient permissions.");
  3343. })
  3344. .catch(err => next(err));
  3345. },
  3346. (station, next) => {
  3347. userModel.updateOne(
  3348. { _id: session.userId },
  3349. { $addToSet: { favoriteStations: stationId } },
  3350. (err, res) => next(err, station, res)
  3351. );
  3352. },
  3353. (station, res, next) => {
  3354. if (res.nModified === 0) return next("The station was already favorited.");
  3355. return next(null, station);
  3356. }
  3357. ],
  3358. async (err, station) => {
  3359. if (err) {
  3360. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3361. this.log("ERROR", "FAVORITE_STATION", `Favoriting station "${stationId}" failed. "${err}"`);
  3362. return cb({ status: "error", message: err });
  3363. }
  3364. this.log("SUCCESS", "FAVORITE_STATION", `Favorited station "${stationId}" successfully.`);
  3365. CacheModule.runJob("PUB", {
  3366. channel: "user.favoritedStation",
  3367. value: {
  3368. userId: session.userId,
  3369. stationId
  3370. }
  3371. });
  3372. ActivitiesModule.runJob("ADD_ACTIVITY", {
  3373. userId: session.userId,
  3374. type: "station__favorite",
  3375. payload: {
  3376. message: `Favorited station <stationId>${station.displayName}</stationId>`,
  3377. stationId
  3378. }
  3379. });
  3380. return cb({
  3381. status: "success",
  3382. message: "Succesfully favorited station."
  3383. });
  3384. }
  3385. );
  3386. }),
  3387. unfavoriteStation: isLoginRequired(async function unfavoriteStation(session, stationId, cb) {
  3388. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  3389. async.waterfall(
  3390. [
  3391. next => {
  3392. userModel.updateOne({ _id: session.userId }, { $pull: { favoriteStations: stationId } }, next);
  3393. },
  3394. (res, next) => {
  3395. if (res.nModified === 0) return next("The station wasn't favorited.");
  3396. return next();
  3397. },
  3398. next => {
  3399. StationsModule.runJob("GET_STATION", { stationId }, this)
  3400. .then(station => next(null, station))
  3401. .catch(next);
  3402. }
  3403. ],
  3404. async (err, station) => {
  3405. if (err) {
  3406. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3407. this.log("ERROR", "UNFAVORITE_STATION", `Unfavoriting station "${stationId}" failed. "${err}"`);
  3408. return cb({ status: "error", message: err });
  3409. }
  3410. this.log("SUCCESS", "UNFAVORITE_STATION", `Unfavorited station "${stationId}" successfully.`);
  3411. CacheModule.runJob("PUB", {
  3412. channel: "user.unfavoritedStation",
  3413. value: {
  3414. userId: session.userId,
  3415. stationId
  3416. }
  3417. });
  3418. ActivitiesModule.runJob("ADD_ACTIVITY", {
  3419. userId: session.userId,
  3420. type: "station__unfavorite",
  3421. payload: {
  3422. message: `Unfavorited station <stationId>${station.displayName}</stationId>`,
  3423. stationId
  3424. }
  3425. });
  3426. return cb({
  3427. status: "success",
  3428. message: "Succesfully unfavorited station."
  3429. });
  3430. }
  3431. );
  3432. }),
  3433. /**
  3434. * Clears every station queue
  3435. *
  3436. * @param {object} session - the session object automatically added by socket.io
  3437. * @param {Function} cb - gets called with the result
  3438. */
  3439. clearEveryStationQueue: isAdminRequired(async function clearEveryStationQueue(session, cb) {
  3440. async.waterfall(
  3441. [
  3442. next => {
  3443. StationsModule.runJob("CLEAR_EVERY_STATION_QUEUE", {}, this)
  3444. .then(() => next())
  3445. .catch(next);
  3446. }
  3447. ],
  3448. async err => {
  3449. if (err) {
  3450. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3451. this.log("ERROR", "CLEAR_EVERY_STATION_QUEUE", `Clearing every station queue failed. "${err}"`);
  3452. return cb({ status: "error", message: err });
  3453. }
  3454. this.log("SUCCESS", "CLEAR_EVERY_STATION_QUEUE", "Clearing every station queue was successful.");
  3455. return cb({ status: "success", message: "Successfully cleared every station queue." });
  3456. }
  3457. );
  3458. }),
  3459. /**
  3460. * Clears and refills a station queue
  3461. *
  3462. * @param {object} session - the session object automatically added by socket.io
  3463. * @param {string} stationId - the station id
  3464. * @param {Function} cb - gets called with the result
  3465. */
  3466. clearAndRefillStationQueue: isAdminRequired(async function clearAndRefillStationQueue(session, stationId, cb) {
  3467. async.waterfall(
  3468. [
  3469. next => {
  3470. StationsModule.runJob("CLEAR_AND_REFILL_STATION_QUEUE", { stationId }, this)
  3471. .then(() => next())
  3472. .catch(next);
  3473. }
  3474. ],
  3475. async err => {
  3476. if (err) {
  3477. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3478. this.log(
  3479. "ERROR",
  3480. "CLEAR_AND_REFILL_STATION_QUEUE",
  3481. `Clearing and refilling station queue failed. "${err}"`
  3482. );
  3483. return cb({ status: "error", message: err });
  3484. }
  3485. this.log(
  3486. "SUCCESS",
  3487. "CLEAR_AND_REFILL_STATION_QUEUE",
  3488. "Clearing and refilling station queue was successful."
  3489. );
  3490. return cb({ status: "success", message: "Successfully cleared and refilled station queue." });
  3491. }
  3492. );
  3493. })
  3494. };