stations.js 103 KB

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