1
0

stations.js 103 KB

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