stations.js 98 KB

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