stations.js 101 KB

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