stations.js 103 KB

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