stations.js 100 KB

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