stations.js 101 KB

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