stations.js 104 KB

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