stations.js 103 KB

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