stations.js 98 KB

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