stations.js 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003
  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) {
  1252. StationsModule.runJob("SKIP_STATION", { stationId, natural: false });
  1253. }
  1254. return cb({
  1255. status: "success",
  1256. message: "Successfully voted to skip the song."
  1257. });
  1258. }
  1259. );
  1260. }),
  1261. /**
  1262. * Force skips a station
  1263. *
  1264. * @param session
  1265. * @param stationId - the station id
  1266. * @param cb
  1267. */
  1268. forceSkip: isOwnerRequired(function forceSkip(session, stationId, cb) {
  1269. async.waterfall(
  1270. [
  1271. next => {
  1272. StationsModule.runJob("GET_STATION", { stationId }, this)
  1273. .then(station => {
  1274. next(null, station);
  1275. })
  1276. .catch(next);
  1277. },
  1278. (station, next) => {
  1279. if (!station) return next("Station not found.");
  1280. return next();
  1281. }
  1282. ],
  1283. async err => {
  1284. if (err) {
  1285. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1286. this.log("ERROR", "STATIONS_FORCE_SKIP", `Force skipping station "${stationId}" failed. "${err}"`);
  1287. return cb({ status: "error", message: err });
  1288. }
  1289. StationsModule.runJob("SKIP_STATION", { stationId, natural: false });
  1290. this.log("SUCCESS", "STATIONS_FORCE_SKIP", `Force skipped station "${stationId}" successfully.`);
  1291. return cb({
  1292. status: "success",
  1293. message: "Successfully skipped station."
  1294. });
  1295. }
  1296. );
  1297. }),
  1298. /**
  1299. * Leaves the user's current station
  1300. *
  1301. * @param {object} session - user session
  1302. * @param {string} stationId - id of station to leave
  1303. * @param {Function} cb - callback
  1304. */
  1305. leave(session, stationId, cb) {
  1306. async.waterfall(
  1307. [
  1308. next => {
  1309. StationsModule.runJob("GET_STATION", { stationId }, this)
  1310. .then(station => next(null, station))
  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_ROOM", { socketId: session.socketId, room: `station.${stationId}` });
  1326. WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", { sockets: [session.socketId] });
  1327. delete StationsModule.userList[session.socketId];
  1328. return cb({
  1329. status: "success",
  1330. message: "Successfully left station.",
  1331. data: { userCount }
  1332. });
  1333. }
  1334. );
  1335. },
  1336. /**
  1337. * Updates a station's name
  1338. *
  1339. * @param session
  1340. * @param stationId - the station id
  1341. * @param newName - the new station name
  1342. * @param cb
  1343. */
  1344. updateName: isOwnerRequired(async function updateName(session, stationId, newName, cb) {
  1345. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1346. async.waterfall(
  1347. [
  1348. next => {
  1349. stationModel.updateOne(
  1350. { _id: stationId },
  1351. { $set: { name: newName } },
  1352. { runValidators: true },
  1353. next
  1354. );
  1355. },
  1356. (res, next) => {
  1357. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1358. .then(station => next(null, station))
  1359. .catch(next);
  1360. }
  1361. ],
  1362. async (err, station) => {
  1363. if (err) {
  1364. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1365. this.log(
  1366. "ERROR",
  1367. "STATIONS_UPDATE_NAME",
  1368. `Updating station "${stationId}" name to "${newName}" failed. "${err}"`
  1369. );
  1370. return cb({ status: "error", message: err });
  1371. }
  1372. this.log(
  1373. "SUCCESS",
  1374. "STATIONS_UPDATE_NAME",
  1375. `Updated station "${stationId}" name to "${newName}" successfully.`
  1376. );
  1377. CacheModule.runJob("PUB", {
  1378. channel: "station.nameUpdate",
  1379. value: { stationId, name: newName }
  1380. });
  1381. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1382. userId: session.userId,
  1383. type: "station__edit_name",
  1384. payload: {
  1385. message: `Changed name of station <stationId>${station.displayName}</stationId> to ${newName}`,
  1386. stationId
  1387. }
  1388. });
  1389. return cb({
  1390. status: "success",
  1391. message: "Successfully updated the name."
  1392. });
  1393. }
  1394. );
  1395. }),
  1396. /**
  1397. * Updates a station's display name
  1398. *
  1399. * @param session
  1400. * @param stationId - the station id
  1401. * @param newDisplayName - the new station display name
  1402. * @param cb
  1403. */
  1404. updateDisplayName: isOwnerRequired(async function updateDisplayName(session, stationId, newDisplayName, cb) {
  1405. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1406. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1407. async.waterfall(
  1408. [
  1409. next => {
  1410. stationModel.updateOne(
  1411. { _id: stationId },
  1412. { $set: { displayName: newDisplayName } },
  1413. { runValidators: true },
  1414. next
  1415. );
  1416. },
  1417. (res, next) => {
  1418. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1419. .then(station => next(null, station))
  1420. .catch(next);
  1421. },
  1422. (station, next) => {
  1423. playlistModel.updateOne(
  1424. { _id: station.playlist },
  1425. { $set: { displayName: `Station - ${station.displayName}` } },
  1426. err => {
  1427. next(err, station);
  1428. }
  1429. );
  1430. }
  1431. ],
  1432. async err => {
  1433. if (err) {
  1434. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1435. this.log(
  1436. "ERROR",
  1437. "STATIONS_UPDATE_DISPLAY_NAME",
  1438. `Updating station "${stationId}" displayName to "${newDisplayName}" failed. "${err}"`
  1439. );
  1440. return cb({ status: "error", message: err });
  1441. }
  1442. this.log(
  1443. "SUCCESS",
  1444. "STATIONS_UPDATE_DISPLAY_NAME",
  1445. `Updated station "${stationId}" displayName to "${newDisplayName}" successfully.`
  1446. );
  1447. CacheModule.runJob("PUB", {
  1448. channel: "station.displayNameUpdate",
  1449. value: { stationId, displayName: newDisplayName }
  1450. });
  1451. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1452. userId: session.userId,
  1453. type: "station__edit_display_name",
  1454. payload: {
  1455. message: `Changed display name of station <stationId>${newDisplayName}</stationId>`,
  1456. stationId
  1457. }
  1458. });
  1459. return cb({
  1460. status: "success",
  1461. message: "Successfully updated the display name."
  1462. });
  1463. }
  1464. );
  1465. }),
  1466. /**
  1467. * Updates a station's description
  1468. *
  1469. * @param session
  1470. * @param stationId - the station id
  1471. * @param newDescription - the new station description
  1472. * @param cb
  1473. */
  1474. updateDescription: isOwnerRequired(async function updateDescription(session, stationId, newDescription, cb) {
  1475. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1476. async.waterfall(
  1477. [
  1478. next => {
  1479. stationModel.updateOne(
  1480. { _id: stationId },
  1481. { $set: { description: newDescription } },
  1482. { runValidators: true },
  1483. next
  1484. );
  1485. },
  1486. (res, next) => {
  1487. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1488. .then(station => next(null, station))
  1489. .catch(next);
  1490. }
  1491. ],
  1492. async (err, station) => {
  1493. if (err) {
  1494. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1495. this.log(
  1496. "ERROR",
  1497. "STATIONS_UPDATE_DESCRIPTION",
  1498. `Updating station "${stationId}" description to "${newDescription}" failed. "${err}"`
  1499. );
  1500. return cb({ status: "error", message: err });
  1501. }
  1502. this.log(
  1503. "SUCCESS",
  1504. "STATIONS_UPDATE_DESCRIPTION",
  1505. `Updated station "${stationId}" description to "${newDescription}" successfully.`
  1506. );
  1507. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1508. userId: session.userId,
  1509. type: "station__edit_description",
  1510. payload: {
  1511. message: `Changed description of station <stationId>${station.displayName}</stationId> to ${newDescription}`,
  1512. stationId
  1513. }
  1514. });
  1515. CacheModule.runJob("PUB", {
  1516. channel: "station.descriptionUpdate",
  1517. value: { stationId, description: newDescription }
  1518. });
  1519. return cb({
  1520. status: "success",
  1521. message: "Successfully updated the description."
  1522. });
  1523. }
  1524. );
  1525. }),
  1526. /**
  1527. * Updates a station's privacy
  1528. *
  1529. * @param session
  1530. * @param stationId - the station id
  1531. * @param newPrivacy - the new station privacy
  1532. * @param cb
  1533. */
  1534. updatePrivacy: isOwnerRequired(async function updatePrivacy(session, stationId, newPrivacy, cb) {
  1535. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1536. let previousPrivacy = null;
  1537. async.waterfall(
  1538. [
  1539. next => {
  1540. stationModel.findOne({ _id: stationId }, next);
  1541. },
  1542. (station, next) => {
  1543. if (!station) next("No station found.");
  1544. else {
  1545. previousPrivacy = station.privacy;
  1546. next();
  1547. }
  1548. },
  1549. next => {
  1550. stationModel.updateOne(
  1551. { _id: stationId },
  1552. { $set: { privacy: newPrivacy } },
  1553. { runValidators: true },
  1554. next
  1555. );
  1556. },
  1557. (res, next) => {
  1558. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1559. .then(station => next(null, station))
  1560. .catch(next);
  1561. }
  1562. ],
  1563. async (err, station) => {
  1564. if (err) {
  1565. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1566. this.log(
  1567. "ERROR",
  1568. "STATIONS_UPDATE_PRIVACY",
  1569. `Updating station "${stationId}" privacy to "${newPrivacy}" failed. "${err}"`
  1570. );
  1571. return cb({ status: "error", message: err });
  1572. }
  1573. this.log(
  1574. "SUCCESS",
  1575. "STATIONS_UPDATE_PRIVACY",
  1576. `Updated station "${stationId}" privacy to "${newPrivacy}" successfully.`
  1577. );
  1578. CacheModule.runJob("PUB", {
  1579. channel: "station.privacyUpdate",
  1580. value: { stationId, previousPrivacy }
  1581. });
  1582. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1583. userId: session.userId,
  1584. type: "station__edit_privacy",
  1585. payload: {
  1586. message: `Changed privacy of station <stationId>${station.displayName}</stationId> to ${newPrivacy}`,
  1587. stationId
  1588. }
  1589. });
  1590. return cb({
  1591. status: "success",
  1592. message: "Successfully updated the privacy."
  1593. });
  1594. }
  1595. );
  1596. }),
  1597. /**
  1598. * Updates a station's genres
  1599. *
  1600. * @param session
  1601. * @param stationId - the station id
  1602. * @param newGenres - the new station genres
  1603. * @param cb
  1604. */
  1605. updateGenres: isOwnerRequired(async function updateGenres(session, stationId, newGenres, cb) {
  1606. async.waterfall(
  1607. [
  1608. next => {
  1609. StationsModule.runJob("GET_STATION", { stationId }, this)
  1610. .then(station => {
  1611. next(null, station);
  1612. })
  1613. .catch(next);
  1614. },
  1615. (station, next) => {
  1616. const playlists = [];
  1617. async.eachLimit(
  1618. newGenres,
  1619. 1,
  1620. (genre, next) => {
  1621. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre, includeSongs: false }, this)
  1622. .then(response => {
  1623. playlists.push(response.playlist);
  1624. next();
  1625. })
  1626. .catch(err => {
  1627. if (err.message === "Playlist not found")
  1628. next(
  1629. `The genre playlist for "${genre}" was not found. Please ensure that this genre playlist exists.`
  1630. );
  1631. else next(err);
  1632. });
  1633. },
  1634. err => {
  1635. next(
  1636. err,
  1637. station,
  1638. playlists.map(playlist => playlist._id.toString())
  1639. );
  1640. }
  1641. );
  1642. },
  1643. (station, playlists, next) => {
  1644. const playlistsToRemoveFromExcluded = playlists.filter(
  1645. playlistId => station.excludedPlaylists.indexOf(playlistId) !== -1
  1646. );
  1647. console.log(
  1648. `playlistsToRemoveFromExcluded: ${playlistsToRemoveFromExcluded.length}`,
  1649. playlistsToRemoveFromExcluded
  1650. );
  1651. async.eachLimit(
  1652. playlistsToRemoveFromExcluded,
  1653. 1,
  1654. (playlistId, next) => {
  1655. StationsModule.runJob("REMOVE_EXCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1656. .then(() => {
  1657. next();
  1658. })
  1659. .catch(next);
  1660. },
  1661. err => {
  1662. next(err, station, playlists);
  1663. }
  1664. );
  1665. },
  1666. (station, playlists, next) => {
  1667. const playlistsToRemoveFromIncluded = station.includedPlaylists.filter(
  1668. playlistId => playlists.indexOf(playlistId) === -1
  1669. );
  1670. console.log(
  1671. `playlistsToRemoveFromIncluded: ${playlistsToRemoveFromIncluded.length}`,
  1672. playlistsToRemoveFromIncluded
  1673. );
  1674. async.eachLimit(
  1675. playlistsToRemoveFromIncluded,
  1676. 1,
  1677. (playlistId, next) => {
  1678. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1679. .then(() => {
  1680. next();
  1681. })
  1682. .catch(next);
  1683. },
  1684. err => {
  1685. next(err, station, playlists);
  1686. }
  1687. );
  1688. },
  1689. (station, playlists, next) => {
  1690. const playlistsToAddToIncluded = playlists.filter(
  1691. playlistId => station.includedPlaylists.indexOf(playlistId) === -1
  1692. );
  1693. console.log(
  1694. `playlistsToAddToIncluded: ${playlistsToAddToIncluded.length}`,
  1695. playlistsToAddToIncluded
  1696. );
  1697. async.eachLimit(
  1698. playlistsToAddToIncluded,
  1699. 1,
  1700. (playlistId, next) => {
  1701. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  1702. .then(() => {
  1703. next();
  1704. })
  1705. .catch(next);
  1706. },
  1707. err => {
  1708. next(err);
  1709. }
  1710. );
  1711. },
  1712. next => {
  1713. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1714. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1715. .then(station => next(null, station))
  1716. .catch(next);
  1717. }
  1718. ],
  1719. async (err, station) => {
  1720. if (err) {
  1721. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1722. this.log(
  1723. "ERROR",
  1724. "STATIONS_UPDATE_GENRES",
  1725. `Updating station "${stationId}" genres to "${newGenres}" failed. "${err}"`
  1726. );
  1727. return cb({ status: "error", message: err });
  1728. }
  1729. this.log(
  1730. "SUCCESS",
  1731. "STATIONS_UPDATE_GENRES",
  1732. `Updated station "${stationId}" genres to "${newGenres}" successfully.`
  1733. );
  1734. if (newGenres.length > 0) {
  1735. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1736. userId: session.userId,
  1737. type: "station__edit_genres",
  1738. payload: {
  1739. message: `Updated genres of station <stationId>${station.displayName}</stationId> to
  1740. ${newGenres.join(", ")}`,
  1741. stationId
  1742. }
  1743. });
  1744. } else {
  1745. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1746. userId: session.userId,
  1747. type: "station__edit_genres",
  1748. payload: {
  1749. message: `Removed all genres of station <stationId>${station.displayName}</stationId>`,
  1750. stationId
  1751. }
  1752. });
  1753. }
  1754. return cb({
  1755. status: "success",
  1756. message: "Successfully updated the genres."
  1757. });
  1758. }
  1759. );
  1760. }),
  1761. /**
  1762. * Updates a station's blacklisted genres
  1763. *
  1764. * @param session
  1765. * @param stationId - the station id
  1766. * @param newBlacklistedGenres - the new station blacklisted genres
  1767. * @param cb
  1768. */
  1769. updateBlacklistedGenres: isOwnerRequired(async function updateBlacklistedGenres(
  1770. session,
  1771. stationId,
  1772. newBlacklistedGenres,
  1773. cb
  1774. ) {
  1775. async.waterfall(
  1776. [
  1777. next => {
  1778. StationsModule.runJob("GET_STATION", { stationId }, this)
  1779. .then(station => {
  1780. next(null, station);
  1781. })
  1782. .catch(next);
  1783. },
  1784. (station, next) => {
  1785. const playlists = [];
  1786. async.eachLimit(
  1787. newBlacklistedGenres,
  1788. 1,
  1789. (genre, next) => {
  1790. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre, includeSongs: false }, this)
  1791. .then(response => {
  1792. playlists.push(response.playlist);
  1793. next();
  1794. })
  1795. .catch(err => {
  1796. if (err.message === "Playlist not found")
  1797. next(
  1798. `The genre playlist for "${genre}" was not found. Please ensure that this genre playlist exists.`
  1799. );
  1800. else next(err);
  1801. });
  1802. },
  1803. err => {
  1804. next(
  1805. err,
  1806. station,
  1807. playlists.map(playlist => playlist._id.toString())
  1808. );
  1809. }
  1810. );
  1811. },
  1812. (station, playlists, next) => {
  1813. const playlistsToRemoveFromIncluded = playlists.filter(
  1814. playlistId => station.includedPlaylists.indexOf(playlistId) !== -1
  1815. );
  1816. console.log(
  1817. `playlistsToRemoveFromIncluded: ${playlistsToRemoveFromIncluded.length}`,
  1818. playlistsToRemoveFromIncluded
  1819. );
  1820. async.eachLimit(
  1821. playlistsToRemoveFromIncluded,
  1822. 1,
  1823. (playlistId, next) => {
  1824. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1825. .then(() => {
  1826. next();
  1827. })
  1828. .catch(next);
  1829. },
  1830. err => {
  1831. next(err, station, playlists);
  1832. }
  1833. );
  1834. },
  1835. (station, playlists, next) => {
  1836. const playlistsToRemoveFromExcluded = station.excludedPlaylists.filter(
  1837. playlistId => playlists.indexOf(playlistId) === -1
  1838. );
  1839. console.log(
  1840. `playlistsToRemoveFromExcluded: ${playlistsToRemoveFromExcluded.length}`,
  1841. playlistsToRemoveFromExcluded
  1842. );
  1843. async.eachLimit(
  1844. playlistsToRemoveFromExcluded,
  1845. 1,
  1846. (playlistId, next) => {
  1847. StationsModule.runJob("REMOVE_EXCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1848. .then(() => {
  1849. next();
  1850. })
  1851. .catch(next);
  1852. },
  1853. err => {
  1854. next(err, station, playlists);
  1855. }
  1856. );
  1857. },
  1858. (station, playlists, next) => {
  1859. const playlistsToAddToExcluded = playlists.filter(
  1860. playlistId => station.excludedPlaylists.indexOf(playlistId) === -1
  1861. );
  1862. console.log(
  1863. `playlistsToAddToExcluded: ${playlistsToAddToExcluded.length}`,
  1864. playlistsToAddToExcluded
  1865. );
  1866. async.eachLimit(
  1867. playlistsToAddToExcluded,
  1868. 1,
  1869. (playlistId, next) => {
  1870. StationsModule.runJob("EXCLUDE_PLAYLIST", { stationId, playlistId }, this)
  1871. .then(() => {
  1872. next();
  1873. })
  1874. .catch(next);
  1875. },
  1876. err => {
  1877. next(err);
  1878. }
  1879. );
  1880. },
  1881. next => {
  1882. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1883. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1884. .then(station => next(null, station))
  1885. .catch(next);
  1886. }
  1887. ],
  1888. async (err, station) => {
  1889. if (err) {
  1890. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1891. this.log(
  1892. "ERROR",
  1893. "STATIONS_UPDATE_BLACKLISTED_GENRES",
  1894. `Updating station "${stationId}" blacklisted genres to "${newBlacklistedGenres}" failed. "${err}"`
  1895. );
  1896. return cb({ status: "error", message: err });
  1897. }
  1898. this.log(
  1899. "SUCCESS",
  1900. "STATIONS_UPDATE_BLACKLISTED_GENRES",
  1901. `Updated station "${stationId}" blacklisted genres to "${newBlacklistedGenres}" successfully.`
  1902. );
  1903. if (newBlacklistedGenres.length > 0) {
  1904. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1905. userId: session.userId,
  1906. type: "station__edit_blacklisted_genres",
  1907. payload: {
  1908. message: `Updated blacklisted genres of station <stationId>${
  1909. station.displayName
  1910. }</stationId> to ${newBlacklistedGenres.join(", ")}`,
  1911. stationId
  1912. }
  1913. });
  1914. } else {
  1915. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1916. userId: session.userId,
  1917. type: "station__edit_blacklisted_genres",
  1918. payload: {
  1919. message: `Removed all blacklisted genres of station <stationId>${station.displayName}</stationId>`,
  1920. stationId
  1921. }
  1922. });
  1923. }
  1924. return cb({
  1925. status: "success",
  1926. message: "Successfully updated the blacklisted genres."
  1927. });
  1928. }
  1929. );
  1930. }),
  1931. /**
  1932. * Updates a station's party mode
  1933. *
  1934. * @param session
  1935. * @param stationId - the station id
  1936. * @param newPartyMode - the new station party mode
  1937. * @param cb
  1938. */
  1939. updatePartyMode: isOwnerRequired(async function updatePartyMode(session, stationId, newPartyMode, cb) {
  1940. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1941. async.waterfall(
  1942. [
  1943. next => {
  1944. StationsModule.runJob("GET_STATION", { stationId }, this)
  1945. .then(station => next(null, station))
  1946. .catch(next);
  1947. },
  1948. (station, next) => {
  1949. if (!station) return next("Station not found.");
  1950. if (station.partyMode === newPartyMode)
  1951. return next(`The party mode was already ${newPartyMode ? "enabled." : "disabled."}`);
  1952. return stationModel.updateOne(
  1953. { _id: stationId },
  1954. { $set: { partyMode: newPartyMode, queue: [] } },
  1955. { runValidators: true },
  1956. next
  1957. );
  1958. },
  1959. (res, next) => {
  1960. CacheModule.runJob("PUB", {
  1961. channel: "station.queueUpdate",
  1962. value: stationId
  1963. })
  1964. .then(() => {})
  1965. .catch(next);
  1966. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1967. .then(station => next(null, station))
  1968. .catch(next);
  1969. }
  1970. ],
  1971. async err => {
  1972. if (err) {
  1973. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1974. this.log(
  1975. "ERROR",
  1976. "STATIONS_UPDATE_PARTY_MODE",
  1977. `Updating station "${stationId}" party mode to "${newPartyMode}" failed. "${err}"`
  1978. );
  1979. return cb({ status: "error", message: err });
  1980. }
  1981. this.log(
  1982. "SUCCESS",
  1983. "STATIONS_UPDATE_PARTY_MODE",
  1984. `Updated station "${stationId}" party mode to "${newPartyMode}" successfully.`
  1985. );
  1986. CacheModule.runJob("PUB", {
  1987. channel: "station.updatePartyMode",
  1988. value: {
  1989. stationId,
  1990. partyMode: newPartyMode
  1991. }
  1992. });
  1993. StationsModule.runJob("SKIP_STATION", { stationId, natural: false });
  1994. return cb({
  1995. status: "success",
  1996. message: "Successfully updated the party mode."
  1997. });
  1998. }
  1999. );
  2000. }),
  2001. /**
  2002. * Updates a station's play mode
  2003. *
  2004. * @param session
  2005. * @param stationId - the station id
  2006. * @param newPlayMode - the new station play mode
  2007. * @param cb
  2008. */
  2009. updatePlayMode: isOwnerRequired(async function updatePartyMode(session, stationId, newPlayMode, cb) {
  2010. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2011. async.waterfall(
  2012. [
  2013. next => {
  2014. StationsModule.runJob("GET_STATION", { stationId }, this)
  2015. .then(station => {
  2016. next(null, station);
  2017. })
  2018. .catch(next);
  2019. },
  2020. (station, next) => {
  2021. if (!station) return next("Station not found.");
  2022. if (station.newPlayMode === newPlayMode) return next(`The play mode was already ${newPlayMode}`);
  2023. return stationModel.updateOne(
  2024. { _id: stationId },
  2025. { $set: { playMode: newPlayMode, queue: [] } },
  2026. { runValidators: true },
  2027. next
  2028. );
  2029. },
  2030. (res, next) => {
  2031. CacheModule.runJob("PUB", {
  2032. channel: "station.queueUpdate",
  2033. value: stationId
  2034. })
  2035. .then()
  2036. .catch();
  2037. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2038. .then(station => {
  2039. next(null, station);
  2040. })
  2041. .catch(next);
  2042. }
  2043. ],
  2044. async err => {
  2045. if (err) {
  2046. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2047. this.log(
  2048. "ERROR",
  2049. "STATIONS_UPDATE_PLAY_MODE",
  2050. `Updating station "${stationId}" play mode to "${newPlayMode}" failed. "${err}"`
  2051. );
  2052. return cb({ status: "error", message: err });
  2053. }
  2054. this.log(
  2055. "SUCCESS",
  2056. "STATIONS_UPDATE_PLAY_MODE",
  2057. `Updated station "${stationId}" play mode to "${newPlayMode}" successfully.`
  2058. );
  2059. CacheModule.runJob("PUB", {
  2060. channel: "station.newPlayMode",
  2061. value: {
  2062. stationId,
  2063. playMode: newPlayMode
  2064. }
  2065. });
  2066. StationsModule.runJob("SKIP_STATION", { stationId, natural: false });
  2067. return cb({
  2068. status: "success",
  2069. message: "Successfully updated the play mode."
  2070. });
  2071. }
  2072. );
  2073. }),
  2074. /**
  2075. * Updates a station's theme
  2076. *
  2077. * @param session
  2078. * @param stationId - the station id
  2079. * @param newTheme - the new station theme
  2080. * @param cb
  2081. */
  2082. updateTheme: isOwnerRequired(async function updateTheme(session, stationId, newTheme, cb) {
  2083. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2084. async.waterfall(
  2085. [
  2086. next => {
  2087. StationsModule.runJob("GET_STATION", { stationId }, this)
  2088. .then(station => {
  2089. next(null, station);
  2090. })
  2091. .catch(next);
  2092. },
  2093. (station, next) => {
  2094. if (!station) return next("Station not found.");
  2095. if (station.theme === newTheme) return next("No change in theme.");
  2096. return stationModel.updateOne(
  2097. { _id: stationId },
  2098. { $set: { theme: newTheme } },
  2099. { runValidators: true },
  2100. next
  2101. );
  2102. },
  2103. (res, next) => {
  2104. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2105. .then(station => next(null, station))
  2106. .catch(next);
  2107. }
  2108. ],
  2109. async (err, station) => {
  2110. if (err) {
  2111. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2112. this.log(
  2113. "ERROR",
  2114. "STATIONS_UPDATE_THEME",
  2115. `Updating station "${stationId}" theme to "${newTheme}" failed. "${err}"`
  2116. );
  2117. return cb({ status: "error", message: err });
  2118. }
  2119. this.log(
  2120. "SUCCESS",
  2121. "STATIONS_UPDATE_THEME",
  2122. `Updated station "${stationId}" theme to "${newTheme}" successfully.`
  2123. );
  2124. CacheModule.runJob("PUB", {
  2125. channel: "station.themeUpdate",
  2126. value: { stationId }
  2127. });
  2128. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2129. userId: session.userId,
  2130. type: "station__edit_theme",
  2131. payload: {
  2132. message: `Changed theme of station <stationId>${station.displayName}</stationId> to ${newTheme}`,
  2133. stationId
  2134. }
  2135. });
  2136. return cb({
  2137. status: "success",
  2138. message: "Successfully updated the theme."
  2139. });
  2140. }
  2141. );
  2142. }),
  2143. /**
  2144. * Pauses a station
  2145. *
  2146. * @param session
  2147. * @param stationId - the station id
  2148. * @param cb
  2149. */
  2150. pause: isOwnerRequired(async function pause(session, stationId, cb) {
  2151. const stationModel = await DBModule.runJob(
  2152. "GET_MODEL",
  2153. {
  2154. modelName: "station"
  2155. },
  2156. this
  2157. );
  2158. async.waterfall(
  2159. [
  2160. next => {
  2161. StationsModule.runJob("GET_STATION", { stationId }, this)
  2162. .then(station => {
  2163. next(null, station);
  2164. })
  2165. .catch(next);
  2166. },
  2167. (station, next) => {
  2168. if (!station) return next("Station not found.");
  2169. if (station.paused) return next("That station was already paused.");
  2170. return stationModel.updateOne(
  2171. { _id: stationId },
  2172. { $set: { paused: true, pausedAt: Date.now() } },
  2173. next
  2174. );
  2175. },
  2176. (res, next) => {
  2177. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2178. .then(station => {
  2179. next(null, station);
  2180. })
  2181. .catch(next);
  2182. }
  2183. ],
  2184. async err => {
  2185. if (err) {
  2186. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2187. this.log("ERROR", "STATIONS_PAUSE", `Pausing station "${stationId}" failed. "${err}"`);
  2188. return cb({ status: "error", message: err });
  2189. }
  2190. this.log("SUCCESS", "STATIONS_PAUSE", `Paused station "${stationId}" successfully.`);
  2191. CacheModule.runJob("PUB", {
  2192. channel: "station.pause",
  2193. value: stationId
  2194. });
  2195. NotificationsModule.runJob("UNSCHEDULE", {
  2196. name: `stations.nextSong?id=${stationId}`
  2197. });
  2198. return cb({
  2199. status: "success",
  2200. message: "Successfully paused."
  2201. });
  2202. }
  2203. );
  2204. }),
  2205. /**
  2206. * Resumes a station
  2207. *
  2208. * @param session
  2209. * @param stationId - the station id
  2210. * @param cb
  2211. */
  2212. resume: isOwnerRequired(async function resume(session, stationId, cb) {
  2213. const stationModel = await DBModule.runJob(
  2214. "GET_MODEL",
  2215. {
  2216. modelName: "station"
  2217. },
  2218. this
  2219. );
  2220. async.waterfall(
  2221. [
  2222. next => {
  2223. StationsModule.runJob("GET_STATION", { stationId }, this)
  2224. .then(station => {
  2225. next(null, station);
  2226. })
  2227. .catch(next);
  2228. },
  2229. (station, next) => {
  2230. if (!station) return next("Station not found.");
  2231. if (!station.paused) return next("That station is not paused.");
  2232. station.timePaused += Date.now() - station.pausedAt;
  2233. return stationModel.updateOne(
  2234. { _id: stationId },
  2235. {
  2236. $set: { paused: false },
  2237. $inc: { timePaused: Date.now() - station.pausedAt }
  2238. },
  2239. next
  2240. );
  2241. },
  2242. (res, next) => {
  2243. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2244. .then(station => {
  2245. next(null, station);
  2246. })
  2247. .catch(next);
  2248. }
  2249. ],
  2250. async err => {
  2251. if (err) {
  2252. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2253. this.log("ERROR", "STATIONS_RESUME", `Resuming station "${stationId}" failed. "${err}"`);
  2254. return cb({ status: "error", message: err });
  2255. }
  2256. this.log("SUCCESS", "STATIONS_RESUME", `Resuming station "${stationId}" successfully.`);
  2257. CacheModule.runJob("PUB", {
  2258. channel: "station.resume",
  2259. value: stationId
  2260. });
  2261. return cb({
  2262. status: "success",
  2263. message: "Successfully resumed."
  2264. });
  2265. }
  2266. );
  2267. }),
  2268. /**
  2269. * Removes a station
  2270. *
  2271. * @param session
  2272. * @param stationId - the station id
  2273. * @param cb
  2274. */
  2275. remove: isOwnerRequired(async function remove(session, stationId, cb) {
  2276. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2277. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2278. async.waterfall(
  2279. [
  2280. next => {
  2281. stationModel.findById(stationId, (err, station) => {
  2282. if (err) return next(err);
  2283. return next(null, station);
  2284. });
  2285. },
  2286. (station, next) => {
  2287. stationModel.deleteOne({ _id: stationId }, err => next(err, station));
  2288. },
  2289. (station, next) => {
  2290. CacheModule.runJob("HDEL", { table: "stations", key: stationId }, this)
  2291. .then(() => next(null, station))
  2292. .catch(next);
  2293. },
  2294. // remove the playlist for the station
  2295. (station, next) => {
  2296. if (station.playlist)
  2297. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: station.playlist })
  2298. .then(() => {})
  2299. .catch(next);
  2300. next(null, station);
  2301. },
  2302. // remove reference to the station id in any array of a user's favorite stations
  2303. (station, next) => {
  2304. userModel.updateMany(
  2305. { favoriteStations: stationId },
  2306. { $pull: { favoriteStations: stationId } },
  2307. err => next(err, station)
  2308. );
  2309. }
  2310. ],
  2311. async (err, station) => {
  2312. if (err) {
  2313. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2314. this.log("ERROR", "STATIONS_REMOVE", `Removing station "${stationId}" failed. "${err}"`);
  2315. return cb({ status: "error", message: err });
  2316. }
  2317. this.log("SUCCESS", "STATIONS_REMOVE", `Removing station "${stationId}" successfully.`);
  2318. CacheModule.runJob("PUB", {
  2319. channel: "station.remove",
  2320. value: stationId
  2321. });
  2322. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2323. userId: session.userId,
  2324. type: "station__remove",
  2325. payload: { message: `Removed a station named ${station.displayName}` }
  2326. });
  2327. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "stationId", stationId });
  2328. return cb({
  2329. status: "success",
  2330. message: "Successfully removed."
  2331. });
  2332. }
  2333. );
  2334. }),
  2335. /**
  2336. * Create a station
  2337. *
  2338. * @param session
  2339. * @param data - the station data
  2340. * @param cb
  2341. */
  2342. create: isLoginRequired(async function create(session, data, cb) {
  2343. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2344. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2345. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  2346. data.name = data.name.toLowerCase();
  2347. const blacklist = [
  2348. "country",
  2349. "edm",
  2350. "musare",
  2351. "hip-hop",
  2352. "rap",
  2353. "top-hits",
  2354. "todays-hits",
  2355. "old-school",
  2356. "christmas",
  2357. "about",
  2358. "support",
  2359. "staff",
  2360. "help",
  2361. "news",
  2362. "terms",
  2363. "privacy",
  2364. "profile",
  2365. "c",
  2366. "community",
  2367. "tos",
  2368. "login",
  2369. "register",
  2370. "p",
  2371. "official",
  2372. "o",
  2373. "trap",
  2374. "faq",
  2375. "team",
  2376. "donate",
  2377. "buy",
  2378. "shop",
  2379. "forums",
  2380. "explore",
  2381. "settings",
  2382. "admin",
  2383. "auth",
  2384. "reset_password",
  2385. "backend",
  2386. "api",
  2387. "songs",
  2388. "playlists",
  2389. "playlist"
  2390. ];
  2391. async.waterfall(
  2392. [
  2393. next => {
  2394. if (!data) return next("Invalid data.");
  2395. return next();
  2396. },
  2397. next => {
  2398. stationModel.findOne(
  2399. {
  2400. $or: [
  2401. { name: data.name },
  2402. {
  2403. displayName: new RegExp(`^${data.displayName}$`, "i")
  2404. }
  2405. ]
  2406. },
  2407. next
  2408. );
  2409. },
  2410. // eslint-disable-next-line consistent-return
  2411. (station, next) => {
  2412. this.log(station);
  2413. if (station) return next("A station with that name or display name already exists.");
  2414. const { name, displayName, description, /* playlist, */ type, genres, blacklistedGenres } = data;
  2415. const stationId = mongoose.Types.ObjectId();
  2416. if (type === "official") {
  2417. return userModel.findOne({ _id: session.userId }, (err, user) => {
  2418. if (err) return next(err);
  2419. if (!user) return next("User not found.");
  2420. if (user.role !== "admin") return next("Admin required.");
  2421. return async.waterfall(
  2422. [
  2423. next => {
  2424. const playlists = [];
  2425. async.eachLimit(
  2426. genres,
  2427. 1,
  2428. (genre, next) => {
  2429. PlaylistsModule.runJob(
  2430. "GET_GENRE_PLAYLIST",
  2431. { genre, includeSongs: false },
  2432. this
  2433. )
  2434. .then(response => {
  2435. playlists.push(response.playlist);
  2436. next();
  2437. })
  2438. .catch(err => {
  2439. next(
  2440. `An error occurred when trying to get genre playlist for genre ${genre}. Error: ${err}.`
  2441. );
  2442. });
  2443. },
  2444. err => {
  2445. next(
  2446. err,
  2447. playlists.map(playlist => playlist._id.toString())
  2448. );
  2449. }
  2450. );
  2451. },
  2452. (genrePlaylistIds, next) => {
  2453. const playlists = [];
  2454. async.eachLimit(
  2455. blacklistedGenres,
  2456. 1,
  2457. (genre, next) => {
  2458. PlaylistsModule.runJob(
  2459. "GET_GENRE_PLAYLIST",
  2460. { genre, includeSongs: false },
  2461. this
  2462. )
  2463. .then(response => {
  2464. playlists.push(response.playlist);
  2465. next();
  2466. })
  2467. .catch(err => {
  2468. next(
  2469. `An error occurred when trying to get genre playlist for genre ${genre}. Error: ${err}.`
  2470. );
  2471. });
  2472. },
  2473. err => {
  2474. next(
  2475. err,
  2476. genrePlaylistIds,
  2477. playlists.map(playlist => playlist._id.toString())
  2478. );
  2479. }
  2480. );
  2481. },
  2482. (genrePlaylistIds, blacklistedGenrePlaylistIds, next) => {
  2483. const duplicateGenre =
  2484. genrePlaylistIds.length !== new Set(genrePlaylistIds).size;
  2485. const duplicateBlacklistedGenre =
  2486. genrePlaylistIds.length !== new Set(genrePlaylistIds).size;
  2487. const duplicateCross =
  2488. genrePlaylistIds.length + blacklistedGenrePlaylistIds.length !==
  2489. new Set([...genrePlaylistIds, ...blacklistedGenrePlaylistIds]).size;
  2490. if (duplicateGenre)
  2491. return next("You cannot have the same genre included twice.");
  2492. if (duplicateBlacklistedGenre)
  2493. return next("You cannot have the same blacklisted genre included twice.");
  2494. if (duplicateCross)
  2495. return next(
  2496. "You cannot have the same genre included and blacklisted at the same time."
  2497. );
  2498. return next(null, genrePlaylistIds, blacklistedGenrePlaylistIds);
  2499. }
  2500. ],
  2501. (err, genrePlaylistIds, blacklistedGenrePlaylistIds) => {
  2502. if (err) return next(err);
  2503. return playlistModel.create(
  2504. {
  2505. isUserModifiable: false,
  2506. displayName: `Station - ${displayName}`,
  2507. songs: [],
  2508. createdBy: "Musare",
  2509. createdFor: `${stationId}`,
  2510. createdAt: Date.now(),
  2511. type: "station"
  2512. },
  2513. (err, playlist) => {
  2514. if (err) next(err);
  2515. else {
  2516. stationModel.create(
  2517. {
  2518. _id: stationId,
  2519. name,
  2520. displayName,
  2521. description,
  2522. type,
  2523. privacy: "private",
  2524. playlist: playlist._id,
  2525. currentSong: null,
  2526. partyMode: false,
  2527. playMode: "random"
  2528. },
  2529. (err, station) => {
  2530. next(
  2531. err,
  2532. station,
  2533. genrePlaylistIds,
  2534. blacklistedGenrePlaylistIds
  2535. );
  2536. }
  2537. );
  2538. }
  2539. }
  2540. );
  2541. }
  2542. );
  2543. });
  2544. }
  2545. if (type === "community") {
  2546. if (blacklist.indexOf(name) !== -1)
  2547. return next("That name is blacklisted. Please use a different name.");
  2548. return playlistModel.create(
  2549. {
  2550. isUserModifiable: false,
  2551. displayName: `Station - ${name}`,
  2552. songs: [],
  2553. createdBy: session.userId,
  2554. createdFor: `${stationId}`,
  2555. createdAt: Date.now(),
  2556. type: "station"
  2557. },
  2558. (err, playlist) => {
  2559. if (err) next(err);
  2560. else {
  2561. stationModel.create(
  2562. {
  2563. _id: stationId,
  2564. name,
  2565. displayName,
  2566. description,
  2567. playlist: playlist._id,
  2568. type,
  2569. privacy: "private",
  2570. owner: session.userId,
  2571. queue: [],
  2572. currentSong: null,
  2573. partyMode: true,
  2574. playMode: "random"
  2575. },
  2576. (err, station) => {
  2577. next(err, station, null, null);
  2578. }
  2579. );
  2580. }
  2581. }
  2582. );
  2583. }
  2584. },
  2585. (station, genrePlaylistIds, blacklistedGenrePlaylistIds, next) => {
  2586. if (station.type !== "official") return next(null, station);
  2587. const stationId = station._id;
  2588. console.log(111, station, genrePlaylistIds, blacklistedGenrePlaylistIds, next);
  2589. return async.waterfall(
  2590. [
  2591. next => {
  2592. async.eachLimit(
  2593. genrePlaylistIds,
  2594. 1,
  2595. (playlistId, next) => {
  2596. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  2597. .then(() => {
  2598. next();
  2599. })
  2600. .catch(next);
  2601. },
  2602. next
  2603. );
  2604. },
  2605. next => {
  2606. async.eachLimit(
  2607. blacklistedGenrePlaylistIds,
  2608. 1,
  2609. (playlistId, next) => {
  2610. StationsModule.runJob("EXCLUDE_PLAYLIST", { stationId, playlistId }, this)
  2611. .then(() => {
  2612. next();
  2613. })
  2614. .catch(next);
  2615. },
  2616. next
  2617. );
  2618. },
  2619. next => {
  2620. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2621. next();
  2622. }
  2623. ],
  2624. async err => {
  2625. if (err) {
  2626. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2627. this.log(
  2628. "ERROR",
  2629. "STATIONS_CREATE",
  2630. `Created station ${stationId} successfully, but an error occurred during playing including/excluding. Error: ${err}`
  2631. );
  2632. }
  2633. next(null, station, err);
  2634. }
  2635. );
  2636. }
  2637. ],
  2638. async (err, station, extraError) => {
  2639. if (err) {
  2640. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2641. this.log("ERROR", "STATIONS_CREATE", `Creating station failed. "${err}"`);
  2642. cb({ status: "error", message: err });
  2643. } else {
  2644. this.log("SUCCESS", "STATIONS_CREATE", `Created station "${station._id}" successfully.`);
  2645. CacheModule.runJob("PUB", {
  2646. channel: "station.create",
  2647. value: station._id
  2648. });
  2649. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2650. userId: session.userId,
  2651. type: "station__create",
  2652. payload: {
  2653. message: `Created a station named <stationId>${station.displayName}</stationId>`,
  2654. stationId: station._id
  2655. }
  2656. });
  2657. if (!extraError) {
  2658. cb({
  2659. status: "success",
  2660. message: "Successfully created station."
  2661. });
  2662. } else {
  2663. cb({
  2664. status: "success",
  2665. message: `Successfully created station, but with one error at the end: ${extraError}`
  2666. });
  2667. }
  2668. }
  2669. }
  2670. );
  2671. }),
  2672. /**
  2673. * Adds song to station queue
  2674. *
  2675. * @param session
  2676. * @param stationId - the station id
  2677. * @param youtubeId - the song id
  2678. * @param cb
  2679. */
  2680. addToQueue: isLoginRequired(async function addToQueue(session, stationId, youtubeId, cb) {
  2681. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2682. const stationModel = await DBModule.runJob(
  2683. "GET_MODEL",
  2684. {
  2685. modelName: "station"
  2686. },
  2687. this
  2688. );
  2689. async.waterfall(
  2690. [
  2691. next => {
  2692. StationsModule.runJob("GET_STATION", { stationId }, this)
  2693. .then(station => {
  2694. next(null, station);
  2695. })
  2696. .catch(next);
  2697. },
  2698. (station, next) => {
  2699. if (!station) return next("Station not found.");
  2700. if (!station.partyMode) return next("Station is not in party mode.");
  2701. if (station.locked) {
  2702. return userModel.findOne({ _id: session.userId }, (err, user) => {
  2703. if (user.role !== "admin" && station.owner !== session.userId)
  2704. return next("Only owners and admins can add songs to a locked queue.");
  2705. return next(null, station);
  2706. });
  2707. }
  2708. return next(null, station);
  2709. },
  2710. (station, next) => {
  2711. if (station.type !== "community") return next("That station is not a community station.");
  2712. return StationsModule.runJob(
  2713. "CAN_USER_VIEW_STATION",
  2714. {
  2715. station,
  2716. userId: session.userId
  2717. },
  2718. this
  2719. )
  2720. .then(canView => {
  2721. if (canView) return next(null, station);
  2722. return next("Insufficient permissions.");
  2723. })
  2724. .catch(err => next(err));
  2725. },
  2726. (station, next) => {
  2727. if (station.currentSong && station.currentSong.youtubeId === youtubeId)
  2728. return next("That song is currently playing.");
  2729. return async.each(
  2730. station.queue,
  2731. (queueSong, next) => {
  2732. if (queueSong.youtubeId === youtubeId) return next("That song is already in the queue.");
  2733. return next();
  2734. },
  2735. err => next(err, station)
  2736. );
  2737. },
  2738. (station, next) => {
  2739. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  2740. .then(UserModel => {
  2741. UserModel.findOne(
  2742. { _id: session.userId },
  2743. { "preferences.anonymousSongRequests": 1 },
  2744. (err, user) => next(err, station, user)
  2745. );
  2746. })
  2747. .catch(next);
  2748. },
  2749. (station, user, next) => {
  2750. SongsModule.runJob(
  2751. "ENSURE_SONG_EXISTS_BY_YOUTUBE_ID",
  2752. {
  2753. youtubeId,
  2754. userId: user.preferences.anonymousSongRequests ? null : session.userId,
  2755. automaticallyRequested: true
  2756. },
  2757. this
  2758. )
  2759. .then(response => {
  2760. const { song } = response;
  2761. const { _id, title, artists, thumbnail, duration, status } = song;
  2762. next(
  2763. null,
  2764. {
  2765. _id,
  2766. youtubeId,
  2767. title,
  2768. artists,
  2769. thumbnail,
  2770. duration,
  2771. status
  2772. },
  2773. station
  2774. );
  2775. })
  2776. .catch(next);
  2777. },
  2778. (song, station, next) => {
  2779. const excludedPlaylists = [];
  2780. async.eachLimit(
  2781. station.excludedPlaylists,
  2782. 1,
  2783. (playlistId, next) => {
  2784. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  2785. .then(playlist => {
  2786. excludedPlaylists.push(playlist);
  2787. next();
  2788. })
  2789. .catch(next);
  2790. },
  2791. err => {
  2792. next(err, song, station, excludedPlaylists);
  2793. }
  2794. );
  2795. },
  2796. (song, station, excludedPlaylists, next) => {
  2797. const excludedSongs = excludedPlaylists
  2798. .flatMap(excludedPlaylist => excludedPlaylist.songs)
  2799. .reduce(
  2800. (items, item) =>
  2801. items.find(x => x.youtubeId === item.youtubeId) ? [...items] : [...items, item],
  2802. []
  2803. );
  2804. if (excludedSongs.find(excludedSong => excludedSong._id.toString() === song._id.toString()))
  2805. next("That song is in an excluded playlist and cannot be played.");
  2806. else next(null, song, station);
  2807. },
  2808. (song, station, next) => {
  2809. song.requestedBy = session.userId;
  2810. song.requestedAt = Date.now();
  2811. let totalDuration = 0;
  2812. station.queue.forEach(song => {
  2813. totalDuration += song.duration;
  2814. });
  2815. if (totalDuration >= 3600 * 3) return next("The max length of the queue is 3 hours.");
  2816. return next(null, song, station);
  2817. },
  2818. (song, station, next) => {
  2819. if (station.queue.length === 0) return next(null, song, station);
  2820. let totalDuration = 0;
  2821. const userId = station.queue[station.queue.length - 1].requestedBy;
  2822. station.queue.forEach(song => {
  2823. if (userId === song.requestedBy) {
  2824. totalDuration += song.duration;
  2825. }
  2826. });
  2827. if (totalDuration >= 900) return next("The max length of songs per user is 15 minutes.");
  2828. return next(null, song, station);
  2829. },
  2830. (song, station, next) => {
  2831. if (station.queue.length === 0) return next(null, song);
  2832. let totalSongs = 0;
  2833. const userId = station.queue[station.queue.length - 1].requestedBy;
  2834. station.queue.forEach(song => {
  2835. if (userId === song.requestedBy) {
  2836. totalSongs += 1;
  2837. }
  2838. });
  2839. if (totalSongs <= 2) return next(null, song);
  2840. if (totalSongs > 3)
  2841. return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  2842. if (
  2843. station.queue[station.queue.length - 2].requestedBy !== userId ||
  2844. station.queue[station.queue.length - 3] !== userId
  2845. )
  2846. return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  2847. return next(null, song);
  2848. },
  2849. (song, next) => {
  2850. stationModel.updateOne(
  2851. { _id: stationId },
  2852. { $push: { queue: song } },
  2853. { runValidators: true },
  2854. next
  2855. );
  2856. },
  2857. (res, next) => {
  2858. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2859. .then(station => next(null, station))
  2860. .catch(next);
  2861. }
  2862. // (res, next) => {
  2863. // StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2864. // .then(station => {
  2865. // next(null, station);
  2866. // })
  2867. // .catch(next);
  2868. // }
  2869. ],
  2870. async err => {
  2871. if (err) {
  2872. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2873. this.log(
  2874. "ERROR",
  2875. "STATIONS_ADD_SONG_TO_QUEUE",
  2876. `Adding song "${youtubeId}" to station "${stationId}" queue failed. "${err}"`
  2877. );
  2878. return cb({ status: "error", message: err });
  2879. }
  2880. this.log(
  2881. "SUCCESS",
  2882. "STATIONS_ADD_SONG_TO_QUEUE",
  2883. `Added song "${youtubeId}" to station "${stationId}" successfully.`
  2884. );
  2885. CacheModule.runJob("PUB", {
  2886. channel: "station.queueUpdate",
  2887. value: stationId
  2888. });
  2889. return cb({
  2890. status: "success",
  2891. message: "Successfully added song to queue."
  2892. });
  2893. }
  2894. );
  2895. }),
  2896. /**
  2897. * Removes song from station queue
  2898. *
  2899. * @param session
  2900. * @param stationId - the station id
  2901. * @param youtubeId - the youtube id
  2902. * @param cb
  2903. */
  2904. removeFromQueue: isOwnerRequired(async function removeFromQueue(session, stationId, youtubeId, cb) {
  2905. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2906. async.waterfall(
  2907. [
  2908. next => {
  2909. if (!youtubeId) return next("Invalid youtube id.");
  2910. return StationsModule.runJob("GET_STATION", { stationId }, this)
  2911. .then(station => next(null, station))
  2912. .catch(next);
  2913. },
  2914. (station, next) => {
  2915. if (!station) return next("Station not found.");
  2916. return async.each(
  2917. station.queue,
  2918. (queueSong, next) => {
  2919. if (queueSong.youtubeId === youtubeId) return next(true);
  2920. return next();
  2921. },
  2922. err => {
  2923. if (err === true) return next();
  2924. return next("Song is not currently in the queue.");
  2925. }
  2926. );
  2927. },
  2928. next => {
  2929. stationModel.updateOne({ _id: stationId }, { $pull: { queue: { youtubeId } } }, next);
  2930. },
  2931. (res, next) => {
  2932. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2933. .then(station => next(null, station))
  2934. .catch(next);
  2935. }
  2936. ],
  2937. async err => {
  2938. if (err) {
  2939. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2940. this.log(
  2941. "ERROR",
  2942. "STATIONS_REMOVE_SONG_TO_QUEUE",
  2943. `Removing song "${youtubeId}" from station "${stationId}" queue failed. "${err}"`
  2944. );
  2945. return cb({ status: "error", message: err });
  2946. }
  2947. this.log(
  2948. "SUCCESS",
  2949. "STATIONS_REMOVE_SONG_TO_QUEUE",
  2950. `Removed song "${youtubeId}" from station "${stationId}" successfully.`
  2951. );
  2952. CacheModule.runJob("PUB", {
  2953. channel: "station.queueUpdate",
  2954. value: stationId
  2955. });
  2956. return cb({
  2957. status: "success",
  2958. message: "Successfully removed song from queue."
  2959. });
  2960. }
  2961. );
  2962. }),
  2963. /**
  2964. * Gets the queue from a station
  2965. *
  2966. * @param {object} session - user session
  2967. * @param {string} stationId - the station id
  2968. * @param {Function} cb - callback
  2969. */
  2970. getQueue(session, stationId, cb) {
  2971. async.waterfall(
  2972. [
  2973. next => {
  2974. StationsModule.runJob("GET_STATION", { stationId }, this)
  2975. .then(station => next(null, station))
  2976. .catch(next);
  2977. },
  2978. (station, next) => {
  2979. if (!station) return next("Station not found.");
  2980. return next(null, station);
  2981. },
  2982. (station, next) => {
  2983. StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  2984. .then(canView => {
  2985. if (canView) return next(null, station);
  2986. return next("Insufficient permissions.");
  2987. })
  2988. .catch(err => next(err));
  2989. },
  2990. (station, next) => {
  2991. if (station.type === "official") next(null, station.queue);
  2992. else next(null, station.queue);
  2993. }
  2994. ],
  2995. async (err, queue) => {
  2996. if (err) {
  2997. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2998. this.log(
  2999. "ERROR",
  3000. "STATIONS_GET_QUEUE",
  3001. `Getting queue for station "${stationId}" failed. "${err}"`
  3002. );
  3003. return cb({ status: "error", message: err });
  3004. }
  3005. this.log("SUCCESS", "STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  3006. return cb({
  3007. status: "success",
  3008. message: "Successfully got queue.",
  3009. data: { queue }
  3010. });
  3011. }
  3012. );
  3013. },
  3014. /**
  3015. * Reposition a song in station queue
  3016. *
  3017. * @param {object} session - user session
  3018. * @param {object} song - contains details about the song that is to be repositioned
  3019. * @param {string} song.youtubeId - the youtube id of the song
  3020. * @param {number} song.newIndex - the new position for the song in the queue
  3021. * @param {number} song.oldIndex - the old position of the song in the queue
  3022. * @param {string} stationId - the station id
  3023. * @param {Function} cb - callback
  3024. */
  3025. repositionSongInQueue: isOwnerRequired(async function repositionQueue(session, stationId, song, cb) {
  3026. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  3027. async.waterfall(
  3028. [
  3029. next => {
  3030. if (!song || !song.youtubeId) return next("You must provide a song to reposition.");
  3031. return next();
  3032. },
  3033. // remove song from queue
  3034. next => {
  3035. stationModel.updateOne(
  3036. { _id: stationId },
  3037. { $pull: { queue: { youtubeId: song.youtubeId } } },
  3038. next
  3039. );
  3040. },
  3041. // add song back to queue (in new position)
  3042. (res, next) => {
  3043. stationModel.updateOne(
  3044. { _id: stationId },
  3045. { $push: { queue: { $each: [song], $position: song.newIndex } } },
  3046. err => next(err)
  3047. );
  3048. },
  3049. // update the cache representation of the station
  3050. next => {
  3051. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  3052. .then(station => next(null, station))
  3053. .catch(next);
  3054. }
  3055. ],
  3056. async err => {
  3057. if (err) {
  3058. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3059. this.log(
  3060. "ERROR",
  3061. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  3062. `Repositioning song ${song.youtubeId} in queue of station "${stationId}" failed. "${err}"`
  3063. );
  3064. return cb({ status: "error", message: err });
  3065. }
  3066. this.log(
  3067. "SUCCESS",
  3068. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  3069. `Repositioned song ${song.youtubeId} in queue of station "${stationId}" successfully.`
  3070. );
  3071. CacheModule.runJob("PUB", {
  3072. channel: "station.repositionSongInQueue",
  3073. value: {
  3074. song: {
  3075. youtubeId: song.youtubeId,
  3076. oldIndex: song.oldIndex,
  3077. newIndex: song.newIndex
  3078. },
  3079. stationId
  3080. }
  3081. });
  3082. return cb({
  3083. status: "success",
  3084. message: "Successfully repositioned song in queue."
  3085. });
  3086. }
  3087. );
  3088. }),
  3089. /**
  3090. * Includes a playlist in a station
  3091. *
  3092. * @param session
  3093. * @param stationId - the station id
  3094. * @param playlistId - the playlist id
  3095. * @param cb
  3096. */
  3097. includePlaylist: isOwnerRequired(async function includePlaylist(session, stationId, playlistId, cb) {
  3098. async.waterfall(
  3099. [
  3100. next => {
  3101. StationsModule.runJob("GET_STATION", { stationId }, this)
  3102. .then(station => next(null, station))
  3103. .catch(next);
  3104. },
  3105. (station, next) => {
  3106. if (!station) return next("Station not found.");
  3107. if (station.includedPlaylists.indexOf(playlistId) !== -1)
  3108. return next("That playlist is already included.");
  3109. if (station.playMode === "sequential" && station.includedPlaylists.length > 0)
  3110. return next("Error: Only 1 playlist can be included in sequential play mode.");
  3111. return next();
  3112. },
  3113. next => {
  3114. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  3115. .then(() => {
  3116. next();
  3117. })
  3118. .catch(next);
  3119. }
  3120. ],
  3121. async err => {
  3122. if (err) {
  3123. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3124. this.log(
  3125. "ERROR",
  3126. "STATIONS_INCLUDE_PLAYLIST",
  3127. `Including playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3128. );
  3129. return cb({ status: "error", message: err });
  3130. }
  3131. this.log(
  3132. "SUCCESS",
  3133. "STATIONS_INCLUDE_PLAYLIST",
  3134. `Including playlist "${playlistId}" for station "${stationId}" successfully.`
  3135. );
  3136. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3137. CacheModule.runJob("PUB", {
  3138. channel: "station.includedPlaylist",
  3139. value: {
  3140. playlistId,
  3141. stationId
  3142. }
  3143. });
  3144. return cb({
  3145. status: "success",
  3146. message: "Successfully included playlist."
  3147. });
  3148. }
  3149. );
  3150. }),
  3151. /**
  3152. * Remove included a playlist from a station
  3153. *
  3154. * @param session
  3155. * @param stationId - the station id
  3156. * @param playlistId - the playlist id
  3157. * @param cb
  3158. */
  3159. removeIncludedPlaylist: isOwnerRequired(async function removeIncludedPlaylist(session, stationId, playlistId, cb) {
  3160. async.waterfall(
  3161. [
  3162. next => {
  3163. StationsModule.runJob("GET_STATION", { stationId }, this)
  3164. .then(station => next(null, station))
  3165. .catch(next);
  3166. },
  3167. (station, next) => {
  3168. if (!station) return next("Station not found.");
  3169. if (station.includedPlaylists.indexOf(playlistId) === -1)
  3170. return next("That playlist is not included.");
  3171. return next();
  3172. },
  3173. next => {
  3174. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  3175. .then(() => {
  3176. next();
  3177. })
  3178. .catch(next);
  3179. }
  3180. ],
  3181. async err => {
  3182. if (err) {
  3183. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3184. this.log(
  3185. "ERROR",
  3186. "STATIONS_REMOVE_INCLUDED_PLAYLIST",
  3187. `Removing included playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3188. );
  3189. return cb({ status: "error", message: err });
  3190. }
  3191. this.log(
  3192. "SUCCESS",
  3193. "STATIONS_REMOVE_INCLUDED_PLAYLIST",
  3194. `Removing included playlist "${playlistId}" for station "${stationId}" successfully.`
  3195. );
  3196. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3197. CacheModule.runJob("PUB", {
  3198. channel: "station.removedIncludedPlaylist",
  3199. value: {
  3200. playlistId,
  3201. stationId
  3202. }
  3203. });
  3204. return cb({
  3205. status: "success",
  3206. message: "Successfully removed included playlist."
  3207. });
  3208. }
  3209. );
  3210. }),
  3211. /**
  3212. * Excludes a playlist in a station
  3213. *
  3214. * @param session
  3215. * @param stationId - the station id
  3216. * @param playlistId - the playlist id
  3217. * @param cb
  3218. */
  3219. excludePlaylist: isOwnerRequired(async function excludePlaylist(session, stationId, playlistId, cb) {
  3220. async.waterfall(
  3221. [
  3222. next => {
  3223. StationsModule.runJob("GET_STATION", { stationId }, this)
  3224. .then(station => next(null, station))
  3225. .catch(next);
  3226. },
  3227. (station, next) => {
  3228. if (!station) return next("Station not found.");
  3229. if (station.excludedPlaylists.indexOf(playlistId) !== -1)
  3230. return next("That playlist is already excluded.");
  3231. return next();
  3232. },
  3233. next => {
  3234. StationsModule.runJob("EXCLUDE_PLAYLIST", { stationId, playlistId }, this)
  3235. .then(() => {
  3236. next();
  3237. })
  3238. .catch(next);
  3239. }
  3240. ],
  3241. async err => {
  3242. if (err) {
  3243. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3244. this.log(
  3245. "ERROR",
  3246. "STATIONS_EXCLUDE_PLAYLIST",
  3247. `Excluding playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3248. );
  3249. return cb({ status: "error", message: err });
  3250. }
  3251. this.log(
  3252. "SUCCESS",
  3253. "STATIONS_EXCLUDE_PLAYLIST",
  3254. `Excluding playlist "${playlistId}" for station "${stationId}" successfully.`
  3255. );
  3256. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3257. CacheModule.runJob("PUB", {
  3258. channel: "station.excludedPlaylist",
  3259. value: {
  3260. playlistId,
  3261. stationId
  3262. }
  3263. });
  3264. return cb({
  3265. status: "success",
  3266. message: "Successfully excluded playlist."
  3267. });
  3268. }
  3269. );
  3270. }),
  3271. /**
  3272. * Remove excluded a playlist from a station
  3273. *
  3274. * @param session
  3275. * @param stationId - the station id
  3276. * @param playlistId - the playlist id
  3277. * @param cb
  3278. */
  3279. removeExcludedPlaylist: isOwnerRequired(async function removeExcludedPlaylist(session, stationId, playlistId, cb) {
  3280. async.waterfall(
  3281. [
  3282. next => {
  3283. StationsModule.runJob("GET_STATION", { stationId }, this)
  3284. .then(station => next(null, station))
  3285. .catch(next);
  3286. },
  3287. (station, next) => {
  3288. if (!station) return next("Station not found.");
  3289. if (station.excludedPlaylists.indexOf(playlistId) === -1)
  3290. return next("That playlist is not excluded.");
  3291. return next();
  3292. },
  3293. next => {
  3294. StationsModule.runJob("REMOVE_EXCLUDED_PLAYLIST", { stationId, playlistId }, this)
  3295. .then(() => {
  3296. next();
  3297. })
  3298. .catch(next);
  3299. }
  3300. ],
  3301. async err => {
  3302. if (err) {
  3303. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3304. this.log(
  3305. "ERROR",
  3306. "STATIONS_REMOVE_EXCLUDED_PLAYLIST",
  3307. `Removing excluded playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3308. );
  3309. return cb({ status: "error", message: err });
  3310. }
  3311. this.log(
  3312. "SUCCESS",
  3313. "STATIONS_REMOVE_EXCLUDED_PLAYLIST",
  3314. `Removing excluded playlist "${playlistId}" for station "${stationId}" successfully.`
  3315. );
  3316. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3317. CacheModule.runJob("PUB", {
  3318. channel: "station.removedExcludedPlaylist",
  3319. value: {
  3320. playlistId,
  3321. stationId
  3322. }
  3323. });
  3324. return cb({
  3325. status: "success",
  3326. message: "Successfully removed excluded playlist."
  3327. });
  3328. }
  3329. );
  3330. }),
  3331. /**
  3332. * Selects a private playlist for a station
  3333. *
  3334. * @param session
  3335. * @param stationId - the station id
  3336. * @param playlistId - the private playlist id
  3337. * @param cb
  3338. */
  3339. selectPrivatePlaylist: isOwnerRequired(async function selectPrivatePlaylist(session, stationId, playlistId, cb) {
  3340. async.waterfall(
  3341. [
  3342. next => {
  3343. StationsModule.runJob("GET_STATION", { stationId }, this)
  3344. .then(station => next(null, station))
  3345. .catch(next);
  3346. },
  3347. (station, next) => {
  3348. if (!station) return next("Station not found.");
  3349. if (station.type !== "community") return next("Station is not a community station.");
  3350. if (station.includedPlaylists.indexOf(playlistId) !== -1)
  3351. return next("That playlist is already included.");
  3352. return next();
  3353. },
  3354. next => {
  3355. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  3356. .then(() => {
  3357. next();
  3358. })
  3359. .catch(next);
  3360. }
  3361. ],
  3362. async err => {
  3363. if (err) {
  3364. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3365. this.log(
  3366. "ERROR",
  3367. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  3368. `Selecting private playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  3369. );
  3370. return cb({ status: "error", message: err });
  3371. }
  3372. this.log(
  3373. "SUCCESS",
  3374. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  3375. `Selected private playlist "${playlistId}" for station "${stationId}" successfully.`
  3376. );
  3377. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3378. // CacheModule.runJob("PUB", {
  3379. // channel: "privatePlaylist.selected",
  3380. // value: {
  3381. // playlistId,
  3382. // stationId
  3383. // }
  3384. // });
  3385. return cb({
  3386. status: "success",
  3387. message: "Successfully selected playlist."
  3388. });
  3389. }
  3390. );
  3391. }),
  3392. /**
  3393. * Deselects the private playlist selected in a station
  3394. *
  3395. * @param session
  3396. * @param stationId - the station id
  3397. * @param cb
  3398. */
  3399. deselectPrivatePlaylist: isOwnerRequired(async function deselectPrivatePlaylist(
  3400. session,
  3401. stationId,
  3402. playlistId,
  3403. cb
  3404. ) {
  3405. async.waterfall(
  3406. [
  3407. next => {
  3408. StationsModule.runJob("GET_STATION", { stationId }, this)
  3409. .then(station => {
  3410. next(null, station);
  3411. })
  3412. .catch(next);
  3413. },
  3414. (station, next) => {
  3415. if (!station) return next("Station not found.");
  3416. if (station.type !== "community") return next("Station is not a community station.");
  3417. if (station.includedPlaylists.indexOf(playlistId) === -1)
  3418. return next("That playlist is not included.");
  3419. return next();
  3420. },
  3421. next => {
  3422. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  3423. .then(() => {
  3424. next();
  3425. })
  3426. .catch(next);
  3427. }
  3428. ],
  3429. async err => {
  3430. if (err) {
  3431. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3432. this.log(
  3433. "ERROR",
  3434. "STATIONS_DESELECT_PRIVATE_PLAYLIST",
  3435. `Deselecting private playlist for station "${stationId}" failed. "${err}"`
  3436. );
  3437. return cb({ status: "error", message: err });
  3438. }
  3439. this.log(
  3440. "SUCCESS",
  3441. "STATIONS_DESELECT_PRIVATE_PLAYLIST",
  3442. `Deselected private playlist for station "${stationId}" successfully.`
  3443. );
  3444. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3445. // CacheModule.runJob("PUB", {
  3446. // channel: "privatePlaylist.deselected",
  3447. // value: {
  3448. // stationId
  3449. // }
  3450. // });
  3451. return cb({
  3452. status: "success",
  3453. message: "Successfully deselected playlist."
  3454. });
  3455. }
  3456. );
  3457. }),
  3458. favoriteStation: isLoginRequired(async function favoriteStation(session, stationId, cb) {
  3459. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  3460. async.waterfall(
  3461. [
  3462. next => {
  3463. StationsModule.runJob("GET_STATION", { stationId }, this)
  3464. .then(station => next(null, station))
  3465. .catch(next);
  3466. },
  3467. (station, next) => {
  3468. if (!station) return next("Station not found.");
  3469. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  3470. .then(canView => {
  3471. if (canView) return next(null, station);
  3472. return next("Insufficient permissions.");
  3473. })
  3474. .catch(err => next(err));
  3475. },
  3476. (station, next) => {
  3477. userModel.updateOne(
  3478. { _id: session.userId },
  3479. { $addToSet: { favoriteStations: stationId } },
  3480. (err, res) => next(err, station, res)
  3481. );
  3482. },
  3483. (station, res, next) => {
  3484. if (res.nModified === 0) return next("The station was already favorited.");
  3485. return next(null, station);
  3486. }
  3487. ],
  3488. async (err, station) => {
  3489. if (err) {
  3490. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3491. this.log("ERROR", "FAVORITE_STATION", `Favoriting station "${stationId}" failed. "${err}"`);
  3492. return cb({ status: "error", message: err });
  3493. }
  3494. this.log("SUCCESS", "FAVORITE_STATION", `Favorited station "${stationId}" successfully.`);
  3495. CacheModule.runJob("PUB", {
  3496. channel: "user.favoritedStation",
  3497. value: {
  3498. userId: session.userId,
  3499. stationId
  3500. }
  3501. });
  3502. ActivitiesModule.runJob("ADD_ACTIVITY", {
  3503. userId: session.userId,
  3504. type: "station__favorite",
  3505. payload: {
  3506. message: `Favorited station <stationId>${station.displayName}</stationId>`,
  3507. stationId
  3508. }
  3509. });
  3510. return cb({
  3511. status: "success",
  3512. message: "Succesfully favorited station."
  3513. });
  3514. }
  3515. );
  3516. }),
  3517. unfavoriteStation: isLoginRequired(async function unfavoriteStation(session, stationId, cb) {
  3518. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  3519. async.waterfall(
  3520. [
  3521. next => {
  3522. userModel.updateOne({ _id: session.userId }, { $pull: { favoriteStations: stationId } }, next);
  3523. },
  3524. (res, next) => {
  3525. if (res.nModified === 0) return next("The station wasn't favorited.");
  3526. return next();
  3527. },
  3528. next => {
  3529. StationsModule.runJob("GET_STATION", { stationId }, this)
  3530. .then(station => next(null, station))
  3531. .catch(next);
  3532. }
  3533. ],
  3534. async (err, station) => {
  3535. if (err) {
  3536. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3537. this.log("ERROR", "UNFAVORITE_STATION", `Unfavoriting station "${stationId}" failed. "${err}"`);
  3538. return cb({ status: "error", message: err });
  3539. }
  3540. this.log("SUCCESS", "UNFAVORITE_STATION", `Unfavorited station "${stationId}" successfully.`);
  3541. CacheModule.runJob("PUB", {
  3542. channel: "user.unfavoritedStation",
  3543. value: {
  3544. userId: session.userId,
  3545. stationId
  3546. }
  3547. });
  3548. ActivitiesModule.runJob("ADD_ACTIVITY", {
  3549. userId: session.userId,
  3550. type: "station__unfavorite",
  3551. payload: {
  3552. message: `Unfavorited station <stationId>${station.displayName}</stationId>`,
  3553. stationId
  3554. }
  3555. });
  3556. return cb({
  3557. status: "success",
  3558. message: "Succesfully unfavorited station."
  3559. });
  3560. }
  3561. );
  3562. }),
  3563. /**
  3564. * Clears every station queue
  3565. *
  3566. * @param {object} session - the session object automatically added by socket.io
  3567. * @param {Function} cb - gets called with the result
  3568. */
  3569. clearEveryStationQueue: isAdminRequired(async function clearEveryStationQueue(session, cb) {
  3570. async.waterfall(
  3571. [
  3572. next => {
  3573. StationsModule.runJob("CLEAR_EVERY_STATION_QUEUE", {}, this)
  3574. .then(() => next())
  3575. .catch(next);
  3576. }
  3577. ],
  3578. async err => {
  3579. if (err) {
  3580. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3581. this.log("ERROR", "CLEAR_EVERY_STATION_QUEUE", `Clearing every station queue failed. "${err}"`);
  3582. return cb({ status: "error", message: err });
  3583. }
  3584. this.log("SUCCESS", "CLEAR_EVERY_STATION_QUEUE", "Clearing every station queue was successful.");
  3585. return cb({ status: "success", message: "Successfully cleared every station queue." });
  3586. }
  3587. );
  3588. }),
  3589. /**
  3590. * Clears and refills a station queue
  3591. *
  3592. * @param {object} session - the session object automatically added by socket.io
  3593. * @param {string} stationId - the station id
  3594. * @param {Function} cb - gets called with the result
  3595. */
  3596. clearAndRefillStationQueue: isAdminRequired(async function clearAndRefillStationQueue(session, stationId, cb) {
  3597. async.waterfall(
  3598. [
  3599. next => {
  3600. StationsModule.runJob("CLEAR_AND_REFILL_STATION_QUEUE", { stationId }, this)
  3601. .then(() => next())
  3602. .catch(next);
  3603. }
  3604. ],
  3605. async err => {
  3606. if (err) {
  3607. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3608. this.log(
  3609. "ERROR",
  3610. "CLEAR_AND_REFILL_STATION_QUEUE",
  3611. `Clearing and refilling station queue failed. "${err}"`
  3612. );
  3613. return cb({ status: "error", message: err });
  3614. }
  3615. this.log(
  3616. "SUCCESS",
  3617. "CLEAR_AND_REFILL_STATION_QUEUE",
  3618. "Clearing and refilling station queue was successful."
  3619. );
  3620. return cb({ status: "success", message: "Successfully cleared and refilled station queue." });
  3621. }
  3622. );
  3623. })
  3624. };