stations.js 104 KB

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