stations.js 91 KB

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