stations.js 101 KB

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