stations.js 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526
  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: "failure", 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: "failure", 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: "failure", 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", 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: "failure", 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", 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: "failure", 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: 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.songId}`
  716. });
  717. data.currentSong.skipVotes = data.currentSong.skipVotes.length;
  718. return SongsModule.runJob("GET_SONG_FROM_ID", { songId: data.currentSong.songId }, this)
  719. .then(response => {
  720. const { song } = response;
  721. if (song) {
  722. data.currentSong.likes = song.likes;
  723. data.currentSong.dislikes = song.dislikes;
  724. } else {
  725. data.currentSong.likes = -1;
  726. data.currentSong.dislikes = -1;
  727. }
  728. })
  729. .catch(() => {
  730. data.currentSong.likes = -1;
  731. data.currentSong.dislikes = -1;
  732. })
  733. .finally(() => next(null, data));
  734. },
  735. (data, next) => {
  736. // only relevant if user logged in
  737. if (session.userId) {
  738. return StationsModule.runJob(
  739. "HAS_USER_FAVORITED_STATION",
  740. {
  741. userId: session.userId,
  742. stationId: data._id
  743. },
  744. this
  745. )
  746. .then(isStationFavorited => {
  747. data.isFavorited = isStationFavorited;
  748. return next(null, data);
  749. })
  750. .catch(err => next(err));
  751. }
  752. return next(null, data);
  753. }
  754. ],
  755. async (err, data) => {
  756. if (err) {
  757. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  758. this.log("ERROR", "STATIONS_JOIN", `Joining station "${stationIdentifier}" failed. "${err}"`);
  759. return cb({ status: "failure", message: err });
  760. }
  761. this.log("SUCCESS", "STATIONS_JOIN", `Joined station "${data._id}" successfully.`);
  762. return cb({ status: "success", data });
  763. }
  764. );
  765. },
  766. /**
  767. * Gets a station by id
  768. *
  769. * @param {object} session - user session
  770. * @param {string} stationId - the station id
  771. * @param {Function} cb - callback
  772. */
  773. getStationById(session, stationId, cb) {
  774. async.waterfall(
  775. [
  776. next => {
  777. StationsModule.runJob("GET_STATION", { stationId }, this)
  778. .then(station => {
  779. next(null, station);
  780. })
  781. .catch(next);
  782. },
  783. (station, next) => {
  784. if (!station) return next("Station not found.");
  785. return StationsModule.runJob(
  786. "CAN_USER_VIEW_STATION",
  787. {
  788. station,
  789. userId: session.userId
  790. },
  791. this
  792. )
  793. .then(canView => {
  794. if (!canView) next("Not allowed to get station.");
  795. else next(null, station);
  796. })
  797. .catch(err => next(err));
  798. },
  799. (station, next) => {
  800. const data = {
  801. _id: station._id,
  802. type: station.type,
  803. description: station.description,
  804. displayName: station.displayName,
  805. name: station.name,
  806. privacy: station.privacy,
  807. locked: station.locked,
  808. partyMode: station.partyMode,
  809. playMode: station.playMode,
  810. owner: station.owner,
  811. // privatePlaylist: station.privatePlaylist,
  812. // genres: station.genres,
  813. // blacklistedGenres: station.blacklistedGenres,
  814. theme: station.theme
  815. };
  816. next(null, data);
  817. }
  818. ],
  819. async (err, data) => {
  820. if (err) {
  821. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  822. this.log("ERROR", "GET_STATION_BY_ID", `Getting station "${stationId}" failed. "${err}"`);
  823. return cb({ status: "failure", message: err });
  824. }
  825. this.log("SUCCESS", "GET_STATION_BY_ID", `Got station "${stationId}" successfully.`);
  826. return cb({ status: "success", station: data });
  827. }
  828. );
  829. },
  830. getStationIncludedPlaylistsById(session, stationId, cb) {
  831. async.waterfall(
  832. [
  833. next => {
  834. StationsModule.runJob("GET_STATION", { stationId }, this)
  835. .then(station => {
  836. next(null, station);
  837. })
  838. .catch(next);
  839. },
  840. (station, next) => {
  841. if (!station) return next("Station not found.");
  842. return StationsModule.runJob(
  843. "CAN_USER_VIEW_STATION",
  844. {
  845. station,
  846. userId: session.userId
  847. },
  848. this
  849. )
  850. .then(canView => {
  851. if (!canView) next("Not allowed to get station.");
  852. else next(null, station);
  853. })
  854. .catch(err => next(err));
  855. },
  856. (station, next) => {
  857. const playlists = [];
  858. async.eachLimit(
  859. station.includedPlaylists,
  860. 1,
  861. (playlistId, next) => {
  862. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  863. .then(playlist => {
  864. playlists.push(playlist);
  865. next();
  866. })
  867. .catch(() => {
  868. playlists.push(null);
  869. next();
  870. });
  871. },
  872. err => {
  873. next(err, playlists);
  874. }
  875. );
  876. }
  877. ],
  878. async (err, playlists) => {
  879. if (err) {
  880. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  881. this.log(
  882. "ERROR",
  883. "GET_STATION_INCLUDED_PLAYLISTS_BY_ID",
  884. `Getting station "${stationId}"'s included playlists failed. "${err}"`
  885. );
  886. return cb({ status: "failure", message: err });
  887. }
  888. this.log(
  889. "SUCCESS",
  890. "GET_STATION_INCLUDED_PLAYLISTS_BY_ID",
  891. `Got station "${stationId}"'s included playlists successfully.`
  892. );
  893. return cb({ status: "success", playlists });
  894. }
  895. );
  896. },
  897. getStationExcludedPlaylistsById(session, stationId, cb) {
  898. async.waterfall(
  899. [
  900. next => {
  901. StationsModule.runJob("GET_STATION", { stationId }, this)
  902. .then(station => {
  903. next(null, station);
  904. })
  905. .catch(next);
  906. },
  907. (station, next) => {
  908. if (!station) return next("Station not found.");
  909. return StationsModule.runJob(
  910. "CAN_USER_VIEW_STATION",
  911. {
  912. station,
  913. userId: session.userId
  914. },
  915. this
  916. )
  917. .then(canView => {
  918. if (!canView) next("Not allowed to get station.");
  919. else next(null, station);
  920. })
  921. .catch(err => next(err));
  922. },
  923. (station, next) => {
  924. const playlists = [];
  925. async.eachLimit(
  926. station.excludedPlaylists,
  927. 1,
  928. (playlistId, next) => {
  929. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  930. .then(playlist => {
  931. playlists.push(playlist);
  932. next();
  933. })
  934. .catch(() => {
  935. playlists.push(null);
  936. next();
  937. });
  938. },
  939. err => {
  940. next(err, playlists);
  941. }
  942. );
  943. }
  944. ],
  945. async (err, playlists) => {
  946. if (err) {
  947. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  948. this.log(
  949. "ERROR",
  950. "GET_STATION_EXCLUDED_PLAYLISTS_BY_ID",
  951. `Getting station "${stationId}"'s excluded playlists failed. "${err}"`
  952. );
  953. return cb({ status: "failure", message: err });
  954. }
  955. this.log(
  956. "SUCCESS",
  957. "GET_STATION_EXCLUDED_PLAYLISTS_BY_ID",
  958. `Got station "${stationId}"'s excluded playlists successfully.`
  959. );
  960. return cb({ status: "success", playlists });
  961. }
  962. );
  963. },
  964. /**
  965. * Toggles if a station is locked
  966. *
  967. * @param session
  968. * @param stationId - the station id
  969. * @param cb
  970. */
  971. toggleLock: isOwnerRequired(async function toggleLock(session, stationId, cb) {
  972. const stationModel = await DBModule.runJob(
  973. "GET_MODEL",
  974. {
  975. modelName: "station"
  976. },
  977. this
  978. );
  979. async.waterfall(
  980. [
  981. next => {
  982. StationsModule.runJob("GET_STATION", { stationId }, this)
  983. .then(station => {
  984. next(null, station);
  985. })
  986. .catch(next);
  987. },
  988. (station, next) => {
  989. stationModel.updateOne({ _id: stationId }, { $set: { locked: !station.locked } }, next);
  990. },
  991. (res, next) => {
  992. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  993. .then(station => {
  994. next(null, station);
  995. })
  996. .catch(next);
  997. }
  998. ],
  999. async (err, station) => {
  1000. if (err) {
  1001. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1002. this.log(
  1003. "ERROR",
  1004. "STATIONS_UPDATE_LOCKED_STATUS",
  1005. `Toggling the queue lock for station "${stationId}" failed. "${err}"`
  1006. );
  1007. return cb({ status: "failure", message: err });
  1008. }
  1009. this.log(
  1010. "SUCCESS",
  1011. "STATIONS_UPDATE_LOCKED_STATUS",
  1012. `Toggled the queue lock for station "${stationId}" successfully to "${station.locked}".`
  1013. );
  1014. CacheModule.runJob("PUB", {
  1015. channel: "station.queueLockToggled",
  1016. value: {
  1017. stationId,
  1018. locked: station.locked
  1019. }
  1020. });
  1021. return cb({ status: "success", data: station.locked });
  1022. }
  1023. );
  1024. }),
  1025. /**
  1026. * Votes to skip a station
  1027. *
  1028. * @param session
  1029. * @param stationId - the station id
  1030. * @param cb
  1031. */
  1032. voteSkip: isLoginRequired(async function voteSkip(session, stationId, cb) {
  1033. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1034. let skipVotes = 0;
  1035. let shouldSkip = false;
  1036. async.waterfall(
  1037. [
  1038. next => {
  1039. StationsModule.runJob("GET_STATION", { stationId }, this)
  1040. .then(station => next(null, station))
  1041. .catch(next);
  1042. },
  1043. (station, next) => {
  1044. if (!station) return next("Station not found.");
  1045. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  1046. .then(canView => {
  1047. if (canView) return next(null, station);
  1048. return next("Insufficient permissions.");
  1049. })
  1050. .catch(err => next(err));
  1051. },
  1052. (station, next) => {
  1053. if (!station.currentSong) return next("There is currently no song to skip.");
  1054. if (station.currentSong.skipVotes.indexOf(session.userId) !== -1)
  1055. return next("You have already voted to skip this song.");
  1056. return next(null, station);
  1057. },
  1058. (station, next) => {
  1059. stationModel.updateOne(
  1060. { _id: stationId },
  1061. { $push: { "currentSong.skipVotes": session.userId } },
  1062. next
  1063. );
  1064. },
  1065. (res, next) => {
  1066. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1067. .then(station => {
  1068. next(null, station);
  1069. })
  1070. .catch(next);
  1071. },
  1072. (station, next) => {
  1073. if (!station) return next("Station not found.");
  1074. return next(null, station);
  1075. },
  1076. (station, next) => {
  1077. skipVotes = station.currentSong.skipVotes.length;
  1078. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${stationId}` }, this)
  1079. .then(sockets => next(null, sockets))
  1080. .catch(next);
  1081. },
  1082. (sockets, next) => {
  1083. if (sockets.length <= skipVotes) {
  1084. shouldSkip = true;
  1085. return next();
  1086. }
  1087. const users = [];
  1088. return async.each(
  1089. sockets,
  1090. (socketId, next) => {
  1091. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  1092. .then(socket => {
  1093. if (socket.session && socket.session.userId) {
  1094. if (!users.includes(socket.session.userId)) users.push(socket.session.userId);
  1095. } else users.push(socketId);
  1096. return next();
  1097. })
  1098. .catch(next);
  1099. },
  1100. err => {
  1101. if (err) return next(err);
  1102. if (users.length <= skipVotes) shouldSkip = true;
  1103. return next();
  1104. }
  1105. );
  1106. }
  1107. ],
  1108. async err => {
  1109. if (err) {
  1110. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1111. this.log("ERROR", "STATIONS_VOTE_SKIP", `Vote skipping station "${stationId}" failed. "${err}"`);
  1112. return cb({ status: "failure", message: err });
  1113. }
  1114. this.log("SUCCESS", "STATIONS_VOTE_SKIP", `Vote skipping "${stationId}" successful.`);
  1115. CacheModule.runJob("PUB", {
  1116. channel: "station.voteSkipSong",
  1117. value: stationId
  1118. });
  1119. if (shouldSkip) StationsModule.runJob("SKIP_STATION", { stationId });
  1120. return cb({
  1121. status: "success",
  1122. message: "Successfully voted to skip the song."
  1123. });
  1124. }
  1125. );
  1126. }),
  1127. /**
  1128. * Force skips a station
  1129. *
  1130. * @param session
  1131. * @param stationId - the station id
  1132. * @param cb
  1133. */
  1134. forceSkip: isOwnerRequired(function forceSkip(session, stationId, cb) {
  1135. async.waterfall(
  1136. [
  1137. next => {
  1138. StationsModule.runJob("GET_STATION", { stationId }, this)
  1139. .then(station => {
  1140. next(null, station);
  1141. })
  1142. .catch(next);
  1143. },
  1144. (station, next) => {
  1145. if (!station) return next("Station not found.");
  1146. return next();
  1147. }
  1148. ],
  1149. async err => {
  1150. if (err) {
  1151. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1152. this.log("ERROR", "STATIONS_FORCE_SKIP", `Force skipping station "${stationId}" failed. "${err}"`);
  1153. return cb({ status: "failure", message: err });
  1154. }
  1155. StationsModule.runJob("SKIP_STATION", { stationId });
  1156. this.log("SUCCESS", "STATIONS_FORCE_SKIP", `Force skipped station "${stationId}" successfully.`);
  1157. return cb({
  1158. status: "success",
  1159. message: "Successfully skipped station."
  1160. });
  1161. }
  1162. );
  1163. }),
  1164. /**
  1165. * Leaves the user's current station
  1166. *
  1167. * @param {object} session - user session
  1168. * @param {string} stationId - id of station to leave
  1169. * @param {Function} cb - callback
  1170. */
  1171. leave(session, stationId, cb) {
  1172. async.waterfall(
  1173. [
  1174. next => {
  1175. StationsModule.runJob("GET_STATION", { stationId }, this)
  1176. .then(station => {
  1177. next(null, station);
  1178. })
  1179. .catch(next);
  1180. },
  1181. (station, next) => {
  1182. if (!station) return next("Station not found.");
  1183. return next();
  1184. }
  1185. ],
  1186. async (err, userCount) => {
  1187. if (err) {
  1188. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1189. this.log("ERROR", "STATIONS_LEAVE", `Leaving station "${stationId}" failed. "${err}"`);
  1190. return cb({ status: "failure", message: err });
  1191. }
  1192. this.log("SUCCESS", "STATIONS_LEAVE", `Left station "${stationId}" successfully.`);
  1193. WSModule.runJob("SOCKET_LEAVE_ROOMS", { socketId: session });
  1194. delete StationsModule.userList[session.socketId];
  1195. return cb({
  1196. status: "success",
  1197. message: "Successfully left station.",
  1198. userCount
  1199. });
  1200. }
  1201. );
  1202. },
  1203. /**
  1204. * Updates a station's name
  1205. *
  1206. * @param session
  1207. * @param stationId - the station id
  1208. * @param newName - the new station name
  1209. * @param cb
  1210. */
  1211. updateName: isOwnerRequired(async function updateName(session, stationId, newName, cb) {
  1212. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1213. async.waterfall(
  1214. [
  1215. next => {
  1216. stationModel.updateOne(
  1217. { _id: stationId },
  1218. { $set: { name: newName } },
  1219. { runValidators: true },
  1220. next
  1221. );
  1222. },
  1223. (res, next) => {
  1224. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1225. .then(station => next(null, station))
  1226. .catch(next);
  1227. }
  1228. ],
  1229. async (err, station) => {
  1230. if (err) {
  1231. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1232. this.log(
  1233. "ERROR",
  1234. "STATIONS_UPDATE_NAME",
  1235. `Updating station "${stationId}" name to "${newName}" failed. "${err}"`
  1236. );
  1237. return cb({ status: "failure", message: err });
  1238. }
  1239. this.log(
  1240. "SUCCESS",
  1241. "STATIONS_UPDATE_NAME",
  1242. `Updated station "${stationId}" name to "${newName}" successfully.`
  1243. );
  1244. CacheModule.runJob("PUB", {
  1245. channel: "station.nameUpdate",
  1246. value: { stationId, name: newName }
  1247. });
  1248. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1249. userId: session.userId,
  1250. type: "station__edit_name",
  1251. payload: {
  1252. message: `Changed name of station <stationId>${station.displayName}</stationId> to ${newName}`,
  1253. stationId
  1254. }
  1255. });
  1256. return cb({
  1257. status: "success",
  1258. message: "Successfully updated the name."
  1259. });
  1260. }
  1261. );
  1262. }),
  1263. /**
  1264. * Updates a station's display name
  1265. *
  1266. * @param session
  1267. * @param stationId - the station id
  1268. * @param newDisplayName - the new station display name
  1269. * @param cb
  1270. */
  1271. updateDisplayName: isOwnerRequired(async function updateDisplayName(session, stationId, newDisplayName, cb) {
  1272. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1273. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1274. async.waterfall(
  1275. [
  1276. next => {
  1277. stationModel.updateOne(
  1278. { _id: stationId },
  1279. { $set: { displayName: newDisplayName } },
  1280. { runValidators: true },
  1281. next
  1282. );
  1283. },
  1284. (res, next) => {
  1285. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1286. .then(station => next(null, station))
  1287. .catch(next);
  1288. },
  1289. (station, next) => {
  1290. playlistModel.updateOne(
  1291. { _id: station.playlist },
  1292. { $set: { displayName: `Station - ${station.displayName}` } },
  1293. err => {
  1294. next(err, station);
  1295. }
  1296. );
  1297. }
  1298. ],
  1299. async err => {
  1300. if (err) {
  1301. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1302. this.log(
  1303. "ERROR",
  1304. "STATIONS_UPDATE_DISPLAY_NAME",
  1305. `Updating station "${stationId}" displayName to "${newDisplayName}" failed. "${err}"`
  1306. );
  1307. return cb({ status: "failure", message: err });
  1308. }
  1309. this.log(
  1310. "SUCCESS",
  1311. "STATIONS_UPDATE_DISPLAY_NAME",
  1312. `Updated station "${stationId}" displayName to "${newDisplayName}" successfully.`
  1313. );
  1314. CacheModule.runJob("PUB", {
  1315. channel: "station.displayNameUpdate",
  1316. value: { stationId, displayName: newDisplayName }
  1317. });
  1318. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1319. userId: session.userId,
  1320. type: "station__edit_display_name",
  1321. payload: {
  1322. message: `Changed display name of station <stationId>${newDisplayName}</stationId>`,
  1323. stationId
  1324. }
  1325. });
  1326. return cb({
  1327. status: "success",
  1328. message: "Successfully updated the display name."
  1329. });
  1330. }
  1331. );
  1332. }),
  1333. /**
  1334. * Updates a station's description
  1335. *
  1336. * @param session
  1337. * @param stationId - the station id
  1338. * @param newDescription - the new station description
  1339. * @param cb
  1340. */
  1341. updateDescription: isOwnerRequired(async function updateDescription(session, stationId, newDescription, cb) {
  1342. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1343. async.waterfall(
  1344. [
  1345. next => {
  1346. stationModel.updateOne(
  1347. { _id: stationId },
  1348. { $set: { description: newDescription } },
  1349. { runValidators: true },
  1350. next
  1351. );
  1352. },
  1353. (res, next) => {
  1354. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1355. .then(station => next(null, station))
  1356. .catch(next);
  1357. }
  1358. ],
  1359. async (err, station) => {
  1360. if (err) {
  1361. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1362. this.log(
  1363. "ERROR",
  1364. "STATIONS_UPDATE_DESCRIPTION",
  1365. `Updating station "${stationId}" description to "${newDescription}" failed. "${err}"`
  1366. );
  1367. return cb({ status: "failure", message: err });
  1368. }
  1369. this.log(
  1370. "SUCCESS",
  1371. "STATIONS_UPDATE_DESCRIPTION",
  1372. `Updated station "${stationId}" description to "${newDescription}" successfully.`
  1373. );
  1374. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1375. userId: session.userId,
  1376. type: "station__edit_description",
  1377. payload: {
  1378. message: `Changed description of station <stationId>${station.displayName}</stationId> to ${newDescription}`,
  1379. stationId
  1380. }
  1381. });
  1382. CacheModule.runJob("PUB", {
  1383. channel: "station.descriptionUpdate",
  1384. value: { stationId, description: newDescription }
  1385. });
  1386. return cb({
  1387. status: "success",
  1388. message: "Successfully updated the description."
  1389. });
  1390. }
  1391. );
  1392. }),
  1393. /**
  1394. * Updates a station's privacy
  1395. *
  1396. * @param session
  1397. * @param stationId - the station id
  1398. * @param newPrivacy - the new station privacy
  1399. * @param cb
  1400. */
  1401. updatePrivacy: isOwnerRequired(async function updatePrivacy(session, stationId, newPrivacy, cb) {
  1402. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1403. let previousPrivacy = null;
  1404. async.waterfall(
  1405. [
  1406. next => {
  1407. stationModel.findOne({ _id: stationId }, next);
  1408. },
  1409. (station, next) => {
  1410. if (!station) next("No station found.");
  1411. else {
  1412. previousPrivacy = station.privacy;
  1413. next();
  1414. }
  1415. },
  1416. next => {
  1417. stationModel.updateOne(
  1418. { _id: stationId },
  1419. { $set: { privacy: newPrivacy } },
  1420. { runValidators: true },
  1421. next
  1422. );
  1423. },
  1424. (res, next) => {
  1425. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1426. .then(station => next(null, station))
  1427. .catch(next);
  1428. }
  1429. ],
  1430. async (err, station) => {
  1431. if (err) {
  1432. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1433. this.log(
  1434. "ERROR",
  1435. "STATIONS_UPDATE_PRIVACY",
  1436. `Updating station "${stationId}" privacy to "${newPrivacy}" failed. "${err}"`
  1437. );
  1438. return cb({ status: "failure", message: err });
  1439. }
  1440. this.log(
  1441. "SUCCESS",
  1442. "STATIONS_UPDATE_PRIVACY",
  1443. `Updated station "${stationId}" privacy to "${newPrivacy}" successfully.`
  1444. );
  1445. CacheModule.runJob("PUB", {
  1446. channel: "station.privacyUpdate",
  1447. value: { stationId, previousPrivacy }
  1448. });
  1449. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1450. userId: session.userId,
  1451. type: "station__edit_privacy",
  1452. payload: {
  1453. message: `Changed privacy of station <stationId>${station.displayName}</stationId> to ${newPrivacy}`,
  1454. stationId
  1455. }
  1456. });
  1457. return cb({
  1458. status: "success",
  1459. message: "Successfully updated the privacy."
  1460. });
  1461. }
  1462. );
  1463. }),
  1464. /**
  1465. * Updates a station's genres
  1466. *
  1467. * @param session
  1468. * @param stationId - the station id
  1469. * @param newGenres - the new station genres
  1470. * @param cb
  1471. */
  1472. updateGenres: isOwnerRequired(async function updateGenres(session, stationId, newGenres, cb) {
  1473. async.waterfall(
  1474. [
  1475. next => {
  1476. StationsModule.runJob("GET_STATION", { stationId }, this)
  1477. .then(station => {
  1478. next(null, station);
  1479. })
  1480. .catch(next);
  1481. },
  1482. (station, next) => {
  1483. const playlists = [];
  1484. async.eachLimit(
  1485. newGenres,
  1486. 1,
  1487. (genre, next) => {
  1488. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre, includeSongs: false }, this)
  1489. .then(response => {
  1490. playlists.push(response.playlist);
  1491. next();
  1492. })
  1493. .catch(err => {
  1494. if (err.message === "Playlist not found")
  1495. next(
  1496. `The genre playlist for "${genre}" was not found. Please ensure that this genre playlist exists.`
  1497. );
  1498. else next(err);
  1499. });
  1500. },
  1501. err => {
  1502. next(
  1503. err,
  1504. station,
  1505. playlists.map(playlist => playlist._id.toString())
  1506. );
  1507. }
  1508. );
  1509. },
  1510. (station, playlists, next) => {
  1511. const playlistsToRemoveFromExcluded = playlists.filter(
  1512. playlistId => station.excludedPlaylists.indexOf(playlistId) !== -1
  1513. );
  1514. console.log(
  1515. `playlistsToRemoveFromExcluded: ${playlistsToRemoveFromExcluded.length}`,
  1516. playlistsToRemoveFromExcluded
  1517. );
  1518. async.eachLimit(
  1519. playlistsToRemoveFromExcluded,
  1520. 1,
  1521. (playlistId, next) => {
  1522. StationsModule.runJob("REMOVE_EXCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1523. .then(() => {
  1524. next();
  1525. })
  1526. .catch(next);
  1527. },
  1528. err => {
  1529. next(err, station, playlists);
  1530. }
  1531. );
  1532. },
  1533. (station, playlists, next) => {
  1534. const playlistsToRemoveFromIncluded = station.includedPlaylists.filter(
  1535. playlistId => playlists.indexOf(playlistId) === -1
  1536. );
  1537. console.log(
  1538. `playlistsToRemoveFromIncluded: ${playlistsToRemoveFromIncluded.length}`,
  1539. playlistsToRemoveFromIncluded
  1540. );
  1541. async.eachLimit(
  1542. playlistsToRemoveFromIncluded,
  1543. 1,
  1544. (playlistId, next) => {
  1545. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1546. .then(() => {
  1547. next();
  1548. })
  1549. .catch(next);
  1550. },
  1551. err => {
  1552. next(err, station, playlists);
  1553. }
  1554. );
  1555. },
  1556. (station, playlists, next) => {
  1557. const playlistsToAddToIncluded = playlists.filter(
  1558. playlistId => station.includedPlaylists.indexOf(playlistId) === -1
  1559. );
  1560. console.log(
  1561. `playlistsToAddToIncluded: ${playlistsToAddToIncluded.length}`,
  1562. playlistsToAddToIncluded
  1563. );
  1564. async.eachLimit(
  1565. playlistsToAddToIncluded,
  1566. 1,
  1567. (playlistId, next) => {
  1568. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  1569. .then(() => {
  1570. next();
  1571. })
  1572. .catch(next);
  1573. },
  1574. err => {
  1575. next(err);
  1576. }
  1577. );
  1578. },
  1579. next => {
  1580. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1581. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1582. .then(station => next(null, station))
  1583. .catch(next);
  1584. }
  1585. ],
  1586. async (err, station) => {
  1587. if (err) {
  1588. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1589. this.log(
  1590. "ERROR",
  1591. "STATIONS_UPDATE_GENRES",
  1592. `Updating station "${stationId}" genres to "${newGenres}" failed. "${err}"`
  1593. );
  1594. return cb({ status: "failure", message: err });
  1595. }
  1596. this.log(
  1597. "SUCCESS",
  1598. "STATIONS_UPDATE_GENRES",
  1599. `Updated station "${stationId}" genres to "${newGenres}" successfully.`
  1600. );
  1601. if (newGenres.length > 0) {
  1602. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1603. userId: session.userId,
  1604. type: "station__edit_genres",
  1605. payload: {
  1606. message: `Updated genres of station <stationId>${station.displayName}</stationId> to
  1607. ${newGenres.join(", ")}`,
  1608. stationId
  1609. }
  1610. });
  1611. } else {
  1612. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1613. userId: session.userId,
  1614. type: "station__edit_genres",
  1615. payload: {
  1616. message: `Removed all genres of station <stationId>${station.displayName}</stationId>`,
  1617. stationId
  1618. }
  1619. });
  1620. }
  1621. return cb({
  1622. status: "success",
  1623. message: "Successfully updated the genres."
  1624. });
  1625. }
  1626. );
  1627. }),
  1628. /**
  1629. * Updates a station's blacklisted genres
  1630. *
  1631. * @param session
  1632. * @param stationId - the station id
  1633. * @param newBlacklistedGenres - the new station blacklisted genres
  1634. * @param cb
  1635. */
  1636. updateBlacklistedGenres: isOwnerRequired(async function updateBlacklistedGenres(
  1637. session,
  1638. stationId,
  1639. newBlacklistedGenres,
  1640. cb
  1641. ) {
  1642. async.waterfall(
  1643. [
  1644. next => {
  1645. StationsModule.runJob("GET_STATION", { stationId }, this)
  1646. .then(station => {
  1647. next(null, station);
  1648. })
  1649. .catch(next);
  1650. },
  1651. (station, next) => {
  1652. const playlists = [];
  1653. async.eachLimit(
  1654. newBlacklistedGenres,
  1655. 1,
  1656. (genre, next) => {
  1657. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre, includeSongs: false }, this)
  1658. .then(response => {
  1659. playlists.push(response.playlist);
  1660. next();
  1661. })
  1662. .catch(err => {
  1663. if (err.message === "Playlist not found")
  1664. next(
  1665. `The genre playlist for "${genre}" was not found. Please ensure that this genre playlist exists.`
  1666. );
  1667. else next(err);
  1668. });
  1669. },
  1670. err => {
  1671. next(
  1672. err,
  1673. station,
  1674. playlists.map(playlist => playlist._id.toString())
  1675. );
  1676. }
  1677. );
  1678. },
  1679. (station, playlists, next) => {
  1680. const playlistsToRemoveFromIncluded = playlists.filter(
  1681. playlistId => station.includedPlaylists.indexOf(playlistId) !== -1
  1682. );
  1683. console.log(
  1684. `playlistsToRemoveFromIncluded: ${playlistsToRemoveFromIncluded.length}`,
  1685. playlistsToRemoveFromIncluded
  1686. );
  1687. async.eachLimit(
  1688. playlistsToRemoveFromIncluded,
  1689. 1,
  1690. (playlistId, next) => {
  1691. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1692. .then(() => {
  1693. next();
  1694. })
  1695. .catch(next);
  1696. },
  1697. err => {
  1698. next(err, station, playlists);
  1699. }
  1700. );
  1701. },
  1702. (station, playlists, next) => {
  1703. const playlistsToRemoveFromExcluded = station.excludedPlaylists.filter(
  1704. playlistId => playlists.indexOf(playlistId) === -1
  1705. );
  1706. console.log(
  1707. `playlistsToRemoveFromExcluded: ${playlistsToRemoveFromExcluded.length}`,
  1708. playlistsToRemoveFromExcluded
  1709. );
  1710. async.eachLimit(
  1711. playlistsToRemoveFromExcluded,
  1712. 1,
  1713. (playlistId, next) => {
  1714. StationsModule.runJob("REMOVE_EXCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1715. .then(() => {
  1716. next();
  1717. })
  1718. .catch(next);
  1719. },
  1720. err => {
  1721. next(err, station, playlists);
  1722. }
  1723. );
  1724. },
  1725. (station, playlists, next) => {
  1726. const playlistsToAddToExcluded = playlists.filter(
  1727. playlistId => station.excludedPlaylists.indexOf(playlistId) === -1
  1728. );
  1729. console.log(
  1730. `playlistsToAddToExcluded: ${playlistsToAddToExcluded.length}`,
  1731. playlistsToAddToExcluded
  1732. );
  1733. async.eachLimit(
  1734. playlistsToAddToExcluded,
  1735. 1,
  1736. (playlistId, next) => {
  1737. StationsModule.runJob("EXCLUDE_PLAYLIST", { stationId, playlistId }, this)
  1738. .then(() => {
  1739. next();
  1740. })
  1741. .catch(next);
  1742. },
  1743. err => {
  1744. next(err);
  1745. }
  1746. );
  1747. },
  1748. next => {
  1749. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1750. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1751. .then(station => next(null, station))
  1752. .catch(next);
  1753. }
  1754. ],
  1755. async (err, station) => {
  1756. if (err) {
  1757. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1758. this.log(
  1759. "ERROR",
  1760. "STATIONS_UPDATE_BLACKLISTED_GENRES",
  1761. `Updating station "${stationId}" blacklisted genres to "${newBlacklistedGenres}" failed. "${err}"`
  1762. );
  1763. return cb({ status: "failure", message: err });
  1764. }
  1765. this.log(
  1766. "SUCCESS",
  1767. "STATIONS_UPDATE_BLACKLISTED_GENRES",
  1768. `Updated station "${stationId}" blacklisted genres to "${newBlacklistedGenres}" successfully.`
  1769. );
  1770. if (newBlacklistedGenres.length > 0) {
  1771. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1772. userId: session.userId,
  1773. type: "station__edit_blacklisted_genres",
  1774. payload: {
  1775. message: `Updated blacklisted genres of station <stationId>${
  1776. station.displayName
  1777. }</stationId> to ${newBlacklistedGenres.join(", ")}`,
  1778. stationId
  1779. }
  1780. });
  1781. } else {
  1782. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1783. userId: session.userId,
  1784. type: "station__edit_blacklisted_genres",
  1785. payload: {
  1786. message: `Removed all blacklisted genres of station <stationId>${station.displayName}</stationId>`,
  1787. stationId
  1788. }
  1789. });
  1790. }
  1791. return cb({
  1792. status: "success",
  1793. message: "Successfully updated the blacklisted genres."
  1794. });
  1795. }
  1796. );
  1797. }),
  1798. /**
  1799. * Updates a station's party mode
  1800. *
  1801. * @param session
  1802. * @param stationId - the station id
  1803. * @param newPartyMode - the new station party mode
  1804. * @param cb
  1805. */
  1806. updatePartyMode: isOwnerRequired(async function updatePartyMode(session, stationId, newPartyMode, cb) {
  1807. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1808. async.waterfall(
  1809. [
  1810. next => {
  1811. StationsModule.runJob("GET_STATION", { stationId }, this)
  1812. .then(station => {
  1813. next(null, station);
  1814. })
  1815. .catch(next);
  1816. },
  1817. (station, next) => {
  1818. if (!station) return next("Station not found.");
  1819. if (station.partyMode === newPartyMode)
  1820. return next(`The party mode was already ${newPartyMode ? "enabled." : "disabled."}`);
  1821. return stationModel.updateOne(
  1822. { _id: stationId },
  1823. { $set: { partyMode: newPartyMode, queue: [] } },
  1824. { runValidators: true },
  1825. next
  1826. );
  1827. },
  1828. (res, next) => {
  1829. CacheModule.runJob("PUB", {
  1830. channel: "station.queueUpdate",
  1831. value: stationId
  1832. })
  1833. .then()
  1834. .catch();
  1835. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1836. .then(station => {
  1837. next(null, station);
  1838. })
  1839. .catch(next);
  1840. }
  1841. ],
  1842. async err => {
  1843. if (err) {
  1844. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1845. this.log(
  1846. "ERROR",
  1847. "STATIONS_UPDATE_PARTY_MODE",
  1848. `Updating station "${stationId}" party mode to "${newPartyMode}" failed. "${err}"`
  1849. );
  1850. return cb({ status: "failure", message: err });
  1851. }
  1852. this.log(
  1853. "SUCCESS",
  1854. "STATIONS_UPDATE_PARTY_MODE",
  1855. `Updated station "${stationId}" party mode to "${newPartyMode}" successfully.`
  1856. );
  1857. CacheModule.runJob("PUB", {
  1858. channel: "station.updatePartyMode",
  1859. value: {
  1860. stationId,
  1861. partyMode: newPartyMode
  1862. }
  1863. });
  1864. StationsModule.runJob("SKIP_STATION", { stationId });
  1865. return cb({
  1866. status: "success",
  1867. message: "Successfully updated the party mode."
  1868. });
  1869. }
  1870. );
  1871. }),
  1872. /**
  1873. * Updates a station's play mode
  1874. *
  1875. * @param session
  1876. * @param stationId - the station id
  1877. * @param newPlayMode - the new station play mode
  1878. * @param cb
  1879. */
  1880. updatePlayMode: isOwnerRequired(async function updatePartyMode(session, stationId, newPlayMode, cb) {
  1881. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1882. async.waterfall(
  1883. [
  1884. next => {
  1885. StationsModule.runJob("GET_STATION", { stationId }, this)
  1886. .then(station => {
  1887. next(null, station);
  1888. })
  1889. .catch(next);
  1890. },
  1891. (station, next) => {
  1892. if (!station) return next("Station not found.");
  1893. if (station.newPlayMode === newPlayMode) return next(`The play mode was already ${newPlayMode}`);
  1894. return stationModel.updateOne(
  1895. { _id: stationId },
  1896. { $set: { playMode: newPlayMode, queue: [] } },
  1897. { runValidators: true },
  1898. next
  1899. );
  1900. },
  1901. (res, next) => {
  1902. CacheModule.runJob("PUB", {
  1903. channel: "station.queueUpdate",
  1904. value: stationId
  1905. })
  1906. .then()
  1907. .catch();
  1908. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1909. .then(station => {
  1910. next(null, station);
  1911. })
  1912. .catch(next);
  1913. }
  1914. ],
  1915. async err => {
  1916. if (err) {
  1917. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1918. this.log(
  1919. "ERROR",
  1920. "STATIONS_UPDATE_PLAY_MODE",
  1921. `Updating station "${stationId}" play mode to "${newPlayMode}" failed. "${err}"`
  1922. );
  1923. return cb({ status: "failure", message: err });
  1924. }
  1925. this.log(
  1926. "SUCCESS",
  1927. "STATIONS_UPDATE_PLAY_MODE",
  1928. `Updated station "${stationId}" play mode to "${newPlayMode}" successfully.`
  1929. );
  1930. CacheModule.runJob("PUB", {
  1931. channel: "station.newPlayMode",
  1932. value: {
  1933. stationId,
  1934. playMode: newPlayMode
  1935. }
  1936. });
  1937. StationsModule.runJob("SKIP_STATION", { stationId });
  1938. return cb({
  1939. status: "success",
  1940. message: "Successfully updated the play mode."
  1941. });
  1942. }
  1943. );
  1944. }),
  1945. /**
  1946. * Updates a station's theme
  1947. *
  1948. * @param session
  1949. * @param stationId - the station id
  1950. * @param newTheme - the new station theme
  1951. * @param cb
  1952. */
  1953. updateTheme: isOwnerRequired(async function updateTheme(session, stationId, newTheme, cb) {
  1954. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1955. async.waterfall(
  1956. [
  1957. next => {
  1958. StationsModule.runJob("GET_STATION", { stationId }, this)
  1959. .then(station => {
  1960. next(null, station);
  1961. })
  1962. .catch(next);
  1963. },
  1964. (station, next) => {
  1965. if (!station) return next("Station not found.");
  1966. if (station.theme === newTheme) return next("No change in theme.");
  1967. return stationModel.updateOne(
  1968. { _id: stationId },
  1969. { $set: { theme: newTheme } },
  1970. { runValidators: true },
  1971. next
  1972. );
  1973. },
  1974. (res, next) => {
  1975. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1976. .then(station => next(null, station))
  1977. .catch(next);
  1978. }
  1979. ],
  1980. async (err, station) => {
  1981. if (err) {
  1982. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1983. this.log(
  1984. "ERROR",
  1985. "STATIONS_UPDATE_THEME",
  1986. `Updating station "${stationId}" theme to "${newTheme}" failed. "${err}"`
  1987. );
  1988. return cb({ status: "failure", message: err });
  1989. }
  1990. this.log(
  1991. "SUCCESS",
  1992. "STATIONS_UPDATE_THEME",
  1993. `Updated station "${stationId}" theme to "${newTheme}" successfully.`
  1994. );
  1995. CacheModule.runJob("PUB", {
  1996. channel: "station.themeUpdate",
  1997. value: { stationId }
  1998. });
  1999. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2000. userId: session.userId,
  2001. type: "station__edit_theme",
  2002. payload: {
  2003. message: `Changed theme of station <stationId>${station.displayName}</stationId> to ${newTheme}`,
  2004. stationId
  2005. }
  2006. });
  2007. return cb({
  2008. status: "success",
  2009. message: "Successfully updated the theme."
  2010. });
  2011. }
  2012. );
  2013. }),
  2014. /**
  2015. * Pauses a station
  2016. *
  2017. * @param session
  2018. * @param stationId - the station id
  2019. * @param cb
  2020. */
  2021. pause: isOwnerRequired(async function pause(session, stationId, cb) {
  2022. const stationModel = await DBModule.runJob(
  2023. "GET_MODEL",
  2024. {
  2025. modelName: "station"
  2026. },
  2027. this
  2028. );
  2029. async.waterfall(
  2030. [
  2031. next => {
  2032. StationsModule.runJob("GET_STATION", { stationId }, this)
  2033. .then(station => {
  2034. next(null, station);
  2035. })
  2036. .catch(next);
  2037. },
  2038. (station, next) => {
  2039. if (!station) return next("Station not found.");
  2040. if (station.paused) return next("That station was already paused.");
  2041. return stationModel.updateOne(
  2042. { _id: stationId },
  2043. { $set: { paused: true, pausedAt: Date.now() } },
  2044. next
  2045. );
  2046. },
  2047. (res, next) => {
  2048. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2049. .then(station => {
  2050. next(null, station);
  2051. })
  2052. .catch(next);
  2053. }
  2054. ],
  2055. async err => {
  2056. if (err) {
  2057. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2058. this.log("ERROR", "STATIONS_PAUSE", `Pausing station "${stationId}" failed. "${err}"`);
  2059. return cb({ status: "failure", message: err });
  2060. }
  2061. this.log("SUCCESS", "STATIONS_PAUSE", `Paused station "${stationId}" successfully.`);
  2062. CacheModule.runJob("PUB", {
  2063. channel: "station.pause",
  2064. value: stationId
  2065. });
  2066. NotificationsModule.runJob("UNSCHEDULE", {
  2067. name: `stations.nextSong?id=${stationId}`
  2068. });
  2069. return cb({
  2070. status: "success",
  2071. message: "Successfully paused."
  2072. });
  2073. }
  2074. );
  2075. }),
  2076. /**
  2077. * Resumes a station
  2078. *
  2079. * @param session
  2080. * @param stationId - the station id
  2081. * @param cb
  2082. */
  2083. resume: isOwnerRequired(async function resume(session, stationId, cb) {
  2084. const stationModel = await DBModule.runJob(
  2085. "GET_MODEL",
  2086. {
  2087. modelName: "station"
  2088. },
  2089. this
  2090. );
  2091. async.waterfall(
  2092. [
  2093. next => {
  2094. StationsModule.runJob("GET_STATION", { stationId }, this)
  2095. .then(station => {
  2096. next(null, station);
  2097. })
  2098. .catch(next);
  2099. },
  2100. (station, next) => {
  2101. if (!station) return next("Station not found.");
  2102. if (!station.paused) return next("That station is not paused.");
  2103. station.timePaused += Date.now() - station.pausedAt;
  2104. return stationModel.updateOne(
  2105. { _id: stationId },
  2106. {
  2107. $set: { paused: false },
  2108. $inc: { timePaused: Date.now() - station.pausedAt }
  2109. },
  2110. next
  2111. );
  2112. },
  2113. (res, next) => {
  2114. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2115. .then(station => {
  2116. next(null, station);
  2117. })
  2118. .catch(next);
  2119. }
  2120. ],
  2121. async err => {
  2122. if (err) {
  2123. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2124. this.log("ERROR", "STATIONS_RESUME", `Resuming station "${stationId}" failed. "${err}"`);
  2125. return cb({ status: "failure", message: err });
  2126. }
  2127. this.log("SUCCESS", "STATIONS_RESUME", `Resuming station "${stationId}" successfully.`);
  2128. CacheModule.runJob("PUB", {
  2129. channel: "station.resume",
  2130. value: stationId
  2131. });
  2132. return cb({
  2133. status: "success",
  2134. message: "Successfully resumed."
  2135. });
  2136. }
  2137. );
  2138. }),
  2139. /**
  2140. * Removes a station
  2141. *
  2142. * @param session
  2143. * @param stationId - the station id
  2144. * @param cb
  2145. */
  2146. remove: isOwnerRequired(async function remove(session, stationId, cb) {
  2147. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2148. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2149. async.waterfall(
  2150. [
  2151. next => {
  2152. stationModel.findById(stationId, (err, station) => {
  2153. if (err) return next(err);
  2154. return next(null, station);
  2155. });
  2156. },
  2157. (station, next) => {
  2158. stationModel.deleteOne({ _id: stationId }, err => next(err, station));
  2159. },
  2160. (station, next) => {
  2161. CacheModule.runJob("HDEL", { table: "stations", key: stationId }, this)
  2162. .then(() => next(null, station))
  2163. .catch(next);
  2164. },
  2165. (station, next) => {
  2166. if (station.playlist)
  2167. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: station.playlist })
  2168. .then(() => {})
  2169. .catch(next);
  2170. next(null, station);
  2171. },
  2172. // remove reference to the station id in any array of a user's favorite stations
  2173. (station, next) => {
  2174. userModel.updateMany(
  2175. { favoriteStations: stationId },
  2176. { $pull: { favoriteStations: stationId } },
  2177. err => next(err, station)
  2178. );
  2179. }
  2180. ],
  2181. async (err, station) => {
  2182. if (err) {
  2183. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2184. this.log("ERROR", "STATIONS_REMOVE", `Removing station "${stationId}" failed. "${err}"`);
  2185. return cb({ status: "failure", message: err });
  2186. }
  2187. this.log("SUCCESS", "STATIONS_REMOVE", `Removing station "${stationId}" successfully.`);
  2188. CacheModule.runJob("PUB", {
  2189. channel: "station.remove",
  2190. value: stationId
  2191. });
  2192. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2193. userId: session.userId,
  2194. type: "station__remove",
  2195. payload: { message: `Removed a station named ${station.displayName}` }
  2196. });
  2197. return cb({
  2198. status: "success",
  2199. message: "Successfully removed."
  2200. });
  2201. }
  2202. );
  2203. }),
  2204. /**
  2205. * Create a station
  2206. *
  2207. * @param session
  2208. * @param data - the station data
  2209. * @param cb
  2210. */
  2211. create: isLoginRequired(async function create(session, data, cb) {
  2212. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2213. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2214. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  2215. data.name = data.name.toLowerCase();
  2216. const blacklist = [
  2217. "country",
  2218. "edm",
  2219. "musare",
  2220. "hip-hop",
  2221. "rap",
  2222. "top-hits",
  2223. "todays-hits",
  2224. "old-school",
  2225. "christmas",
  2226. "about",
  2227. "support",
  2228. "staff",
  2229. "help",
  2230. "news",
  2231. "terms",
  2232. "privacy",
  2233. "profile",
  2234. "c",
  2235. "community",
  2236. "tos",
  2237. "login",
  2238. "register",
  2239. "p",
  2240. "official",
  2241. "o",
  2242. "trap",
  2243. "faq",
  2244. "team",
  2245. "donate",
  2246. "buy",
  2247. "shop",
  2248. "forums",
  2249. "explore",
  2250. "settings",
  2251. "admin",
  2252. "auth",
  2253. "reset_password",
  2254. "backend",
  2255. "api",
  2256. "songs",
  2257. "playlists",
  2258. "playlist"
  2259. ];
  2260. async.waterfall(
  2261. [
  2262. next => {
  2263. if (!data) return next("Invalid data.");
  2264. return next();
  2265. },
  2266. next => {
  2267. stationModel.findOne(
  2268. {
  2269. $or: [
  2270. { name: data.name },
  2271. {
  2272. displayName: new RegExp(`^${data.displayName}$`, "i")
  2273. }
  2274. ]
  2275. },
  2276. next
  2277. );
  2278. },
  2279. // eslint-disable-next-line consistent-return
  2280. (station, next) => {
  2281. this.log(station);
  2282. if (station) return next("A station with that name or display name already exists.");
  2283. const { name, displayName, description, /* playlist, */ type, genres, blacklistedGenres } = data;
  2284. const stationId = mongoose.Types.ObjectId();
  2285. if (type === "official") {
  2286. return userModel.findOne({ _id: session.userId }, (err, user) => {
  2287. if (err) return next(err);
  2288. if (!user) return next("User not found.");
  2289. if (user.role !== "admin") return next("Admin required.");
  2290. return async.waterfall(
  2291. [
  2292. next => {
  2293. const playlists = [];
  2294. async.eachLimit(
  2295. genres,
  2296. 1,
  2297. (genre, next) => {
  2298. PlaylistsModule.runJob(
  2299. "GET_GENRE_PLAYLIST",
  2300. { genre, includeSongs: false },
  2301. this
  2302. )
  2303. .then(response => {
  2304. playlists.push(response.playlist);
  2305. next();
  2306. })
  2307. .catch(err => {
  2308. next(
  2309. `An error occurred when trying to get genre playlist for genre ${genre}. Error: ${err}.`
  2310. );
  2311. });
  2312. },
  2313. err => {
  2314. next(
  2315. err,
  2316. playlists.map(playlist => playlist._id.toString())
  2317. );
  2318. }
  2319. );
  2320. },
  2321. (genrePlaylistIds, next) => {
  2322. const playlists = [];
  2323. async.eachLimit(
  2324. blacklistedGenres,
  2325. 1,
  2326. (genre, next) => {
  2327. PlaylistsModule.runJob(
  2328. "GET_GENRE_PLAYLIST",
  2329. { genre, includeSongs: false },
  2330. this
  2331. )
  2332. .then(response => {
  2333. playlists.push(response.playlist);
  2334. next();
  2335. })
  2336. .catch(err => {
  2337. next(
  2338. `An error occurred when trying to get genre playlist for genre ${genre}. Error: ${err}.`
  2339. );
  2340. });
  2341. },
  2342. err => {
  2343. next(
  2344. err,
  2345. genrePlaylistIds,
  2346. playlists.map(playlist => playlist._id.toString())
  2347. );
  2348. }
  2349. );
  2350. },
  2351. (genrePlaylistIds, blacklistedGenrePlaylistIds, next) => {
  2352. const duplicateGenre =
  2353. genrePlaylistIds.length !== new Set(genrePlaylistIds).size;
  2354. const duplicateBlacklistedGenre =
  2355. genrePlaylistIds.length !== new Set(genrePlaylistIds).size;
  2356. const duplicateCross =
  2357. genrePlaylistIds.length + blacklistedGenrePlaylistIds.length !==
  2358. new Set([...genrePlaylistIds, ...blacklistedGenrePlaylistIds]).size;
  2359. if (duplicateGenre)
  2360. return next("You cannot have the same genre included twice.");
  2361. if (duplicateBlacklistedGenre)
  2362. return next("You cannot have the same blacklisted genre included twice.");
  2363. if (duplicateCross)
  2364. return next(
  2365. "You cannot have the same genre included and blacklisted at the same time."
  2366. );
  2367. return next(null, genrePlaylistIds, blacklistedGenrePlaylistIds);
  2368. }
  2369. ],
  2370. (err, genrePlaylistIds, blacklistedGenrePlaylistIds) => {
  2371. if (err) return next(err);
  2372. return playlistModel.create(
  2373. {
  2374. isUserModifiable: false,
  2375. displayName: `Station - ${displayName}`,
  2376. songs: [],
  2377. createdBy: "Musare",
  2378. createdFor: `${stationId}`,
  2379. createdAt: Date.now(),
  2380. type: "station"
  2381. },
  2382. (err, playlist) => {
  2383. if (err) next(err);
  2384. else {
  2385. stationModel.create(
  2386. {
  2387. _id: stationId,
  2388. name,
  2389. displayName,
  2390. description,
  2391. type,
  2392. privacy: "private",
  2393. playlist: playlist._id,
  2394. currentSong: null
  2395. },
  2396. (err, station) => {
  2397. next(
  2398. err,
  2399. station,
  2400. genrePlaylistIds,
  2401. blacklistedGenrePlaylistIds
  2402. );
  2403. }
  2404. );
  2405. }
  2406. }
  2407. );
  2408. }
  2409. );
  2410. });
  2411. }
  2412. if (type === "community") {
  2413. if (blacklist.indexOf(name) !== -1)
  2414. return next("That name is blacklisted. Please use a different name.");
  2415. return playlistModel.create(
  2416. {
  2417. isUserModifiable: false,
  2418. displayName: `Station - ${name}`,
  2419. songs: [],
  2420. createdBy: session.userId,
  2421. createdFor: `${stationId}`,
  2422. createdAt: Date.now(),
  2423. type: "station"
  2424. },
  2425. (err, playlist) => {
  2426. if (err) next(err);
  2427. else {
  2428. stationModel.create(
  2429. {
  2430. _id: stationId,
  2431. name,
  2432. displayName,
  2433. description,
  2434. playlist: playlist._id,
  2435. type,
  2436. privacy: "private",
  2437. owner: session.userId,
  2438. queue: [],
  2439. currentSong: null
  2440. },
  2441. (err, station) => {
  2442. next(err, station, null, null);
  2443. }
  2444. );
  2445. }
  2446. }
  2447. );
  2448. }
  2449. },
  2450. (station, genrePlaylistIds, blacklistedGenrePlaylistIds, next) => {
  2451. if (station.type !== "official") return next(null, station);
  2452. const stationId = station._id;
  2453. console.log(111, station, genrePlaylistIds, blacklistedGenrePlaylistIds, next);
  2454. return async.waterfall(
  2455. [
  2456. next => {
  2457. async.eachLimit(
  2458. genrePlaylistIds,
  2459. 1,
  2460. (playlistId, next) => {
  2461. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  2462. .then(() => {
  2463. next();
  2464. })
  2465. .catch(next);
  2466. },
  2467. next
  2468. );
  2469. },
  2470. next => {
  2471. async.eachLimit(
  2472. blacklistedGenrePlaylistIds,
  2473. 1,
  2474. (playlistId, next) => {
  2475. StationsModule.runJob("EXCLUDE_PLAYLIST", { stationId, playlistId }, this)
  2476. .then(() => {
  2477. next();
  2478. })
  2479. .catch(next);
  2480. },
  2481. next
  2482. );
  2483. },
  2484. next => {
  2485. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2486. next();
  2487. }
  2488. ],
  2489. async err => {
  2490. if (err) {
  2491. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2492. this.log(
  2493. "ERROR",
  2494. "STATIONS_CREATE",
  2495. `Created station ${stationId} successfully, but an error occurred during playing including/excluding. Error: ${err}`
  2496. );
  2497. }
  2498. next(null, station, err);
  2499. }
  2500. );
  2501. }
  2502. ],
  2503. async (err, station, extraError) => {
  2504. if (err) {
  2505. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2506. this.log("ERROR", "STATIONS_CREATE", `Creating station failed. "${err}"`);
  2507. cb({ status: "failure", message: err });
  2508. } else {
  2509. this.log("SUCCESS", "STATIONS_CREATE", `Created station "${station._id}" successfully.`);
  2510. CacheModule.runJob("PUB", {
  2511. channel: "station.create",
  2512. value: station._id
  2513. });
  2514. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2515. userId: session.userId,
  2516. type: "station__create",
  2517. payload: {
  2518. message: `Created a station named <stationId>${station.displayName}</stationId>`,
  2519. stationId: station._id
  2520. }
  2521. });
  2522. if (!extraError) {
  2523. cb({
  2524. status: "success",
  2525. message: "Successfully created station."
  2526. });
  2527. } else {
  2528. cb({
  2529. status: "success",
  2530. message: `Successfully created station, but with one error at the end: ${extraError}`
  2531. });
  2532. }
  2533. }
  2534. }
  2535. );
  2536. }),
  2537. /**
  2538. * Adds song to station queue
  2539. *
  2540. * @param session
  2541. * @param stationId - the station id
  2542. * @param songId - the song id
  2543. * @param cb
  2544. */
  2545. addToQueue: isLoginRequired(async function addToQueue(session, stationId, songId, cb) {
  2546. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2547. const stationModel = await DBModule.runJob(
  2548. "GET_MODEL",
  2549. {
  2550. modelName: "station"
  2551. },
  2552. this
  2553. );
  2554. async.waterfall(
  2555. [
  2556. next => {
  2557. StationsModule.runJob("GET_STATION", { stationId }, this)
  2558. .then(station => {
  2559. next(null, station);
  2560. })
  2561. .catch(next);
  2562. },
  2563. (station, next) => {
  2564. if (!station) return next("Station not found.");
  2565. if (!station.partyMode) return next("Station is not in party mode.");
  2566. if (station.locked) {
  2567. return userModel.findOne({ _id: session.userId }, (err, user) => {
  2568. if (user.role !== "admin" && station.owner !== session.userId)
  2569. return next("Only owners and admins can add songs to a locked queue.");
  2570. return next(null, station);
  2571. });
  2572. }
  2573. return next(null, station);
  2574. },
  2575. (station, next) => {
  2576. if (station.type !== "community") return next("That station is not a community station.");
  2577. return StationsModule.runJob(
  2578. "CAN_USER_VIEW_STATION",
  2579. {
  2580. station,
  2581. userId: session.userId
  2582. },
  2583. this
  2584. )
  2585. .then(canView => {
  2586. if (canView) return next(null, station);
  2587. return next("Insufficient permissions.");
  2588. })
  2589. .catch(err => next(err));
  2590. },
  2591. (station, next) => {
  2592. if (station.currentSong && station.currentSong.songId === songId)
  2593. return next("That song is currently playing.");
  2594. return async.each(
  2595. station.queue,
  2596. (queueSong, next) => {
  2597. if (queueSong.songId === songId) return next("That song is already in the queue.");
  2598. return next();
  2599. },
  2600. err => next(err, station)
  2601. );
  2602. },
  2603. (station, next) => {
  2604. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  2605. .then(UserModel => {
  2606. UserModel.findOne(
  2607. { _id: session.userId },
  2608. { "preferences.anonymousSongRequests": 1 },
  2609. (err, user) => next(err, station, user)
  2610. );
  2611. })
  2612. .catch(next);
  2613. },
  2614. (station, user, next) => {
  2615. SongsModule.runJob(
  2616. "ENSURE_SONG_EXISTS_BY_SONG_ID",
  2617. {
  2618. songId,
  2619. userId: user.preferences.anonymousSongRequests ? null : session.userId,
  2620. automaticallyRequested: true
  2621. },
  2622. this
  2623. )
  2624. .then(response => {
  2625. const { song } = response;
  2626. const { _id, title, thumbnail, duration, status } = song;
  2627. next(
  2628. null,
  2629. {
  2630. _id,
  2631. songId,
  2632. title,
  2633. thumbnail,
  2634. duration,
  2635. status
  2636. },
  2637. station
  2638. );
  2639. })
  2640. .catch(next);
  2641. },
  2642. (song, station, next) => {
  2643. song.requestedBy = session.userId;
  2644. song.requestedAt = Date.now();
  2645. let totalDuration = 0;
  2646. station.queue.forEach(song => {
  2647. totalDuration += song.duration;
  2648. });
  2649. if (totalDuration >= 3600 * 3) return next("The max length of the queue is 3 hours.");
  2650. return next(null, song, station);
  2651. },
  2652. (song, station, next) => {
  2653. if (station.queue.length === 0) return next(null, song, station);
  2654. let totalDuration = 0;
  2655. const userId = station.queue[station.queue.length - 1].requestedBy;
  2656. station.queue.forEach(song => {
  2657. if (userId === song.requestedBy) {
  2658. totalDuration += song.duration;
  2659. }
  2660. });
  2661. if (totalDuration >= 900) return next("The max length of songs per user is 15 minutes.");
  2662. return next(null, song, station);
  2663. },
  2664. (song, station, next) => {
  2665. if (station.queue.length === 0) return next(null, song);
  2666. let totalSongs = 0;
  2667. const userId = station.queue[station.queue.length - 1].requestedBy;
  2668. station.queue.forEach(song => {
  2669. if (userId === song.requestedBy) {
  2670. totalSongs += 1;
  2671. }
  2672. });
  2673. if (totalSongs <= 2) return next(null, song);
  2674. if (totalSongs > 3)
  2675. return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  2676. if (
  2677. station.queue[station.queue.length - 2].requestedBy !== userId ||
  2678. station.queue[station.queue.length - 3] !== userId
  2679. )
  2680. return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  2681. return next(null, song);
  2682. },
  2683. (song, next) => {
  2684. stationModel.updateOne(
  2685. { _id: stationId },
  2686. { $push: { queue: song } },
  2687. { runValidators: true },
  2688. next
  2689. );
  2690. },
  2691. (res, next) => {
  2692. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2693. .then(station => next(null, station))
  2694. .catch(next);
  2695. }
  2696. // (res, next) => {
  2697. // StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2698. // .then(station => {
  2699. // next(null, station);
  2700. // })
  2701. // .catch(next);
  2702. // }
  2703. ],
  2704. async err => {
  2705. if (err) {
  2706. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2707. this.log(
  2708. "ERROR",
  2709. "STATIONS_ADD_SONG_TO_QUEUE",
  2710. `Adding song "${songId}" to station "${stationId}" queue failed. "${err}"`
  2711. );
  2712. return cb({ status: "failure", message: err });
  2713. }
  2714. this.log(
  2715. "SUCCESS",
  2716. "STATIONS_ADD_SONG_TO_QUEUE",
  2717. `Added song "${songId}" to station "${stationId}" successfully.`
  2718. );
  2719. CacheModule.runJob("PUB", {
  2720. channel: "station.queueUpdate",
  2721. value: stationId
  2722. });
  2723. return cb({
  2724. status: "success",
  2725. message: "Successfully added song to queue."
  2726. });
  2727. }
  2728. );
  2729. }),
  2730. /**
  2731. * Removes song from station queue
  2732. *
  2733. * @param session
  2734. * @param stationId - the station id
  2735. * @param songId - the song id
  2736. * @param cb
  2737. */
  2738. removeFromQueue: isOwnerRequired(async function removeFromQueue(session, stationId, songId, cb) {
  2739. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2740. async.waterfall(
  2741. [
  2742. next => {
  2743. if (!songId) return next("Invalid song id.");
  2744. return StationsModule.runJob("GET_STATION", { stationId }, this)
  2745. .then(station => next(null, station))
  2746. .catch(next);
  2747. },
  2748. (station, next) => {
  2749. if (!station) return next("Station not found.");
  2750. return async.each(
  2751. station.queue,
  2752. (queueSong, next) => {
  2753. if (queueSong.songId === songId) return next(true);
  2754. return next();
  2755. },
  2756. err => {
  2757. if (err === true) return next();
  2758. return next("Song is not currently in the queue.");
  2759. }
  2760. );
  2761. },
  2762. next => {
  2763. stationModel.updateOne({ _id: stationId }, { $pull: { queue: { songId } } }, next);
  2764. },
  2765. (res, next) => {
  2766. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2767. .then(station => next(null, station))
  2768. .catch(next);
  2769. }
  2770. ],
  2771. async err => {
  2772. if (err) {
  2773. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2774. this.log(
  2775. "ERROR",
  2776. "STATIONS_REMOVE_SONG_TO_QUEUE",
  2777. `Removing song "${songId}" from station "${stationId}" queue failed. "${err}"`
  2778. );
  2779. return cb({ status: "failure", message: err });
  2780. }
  2781. this.log(
  2782. "SUCCESS",
  2783. "STATIONS_REMOVE_SONG_TO_QUEUE",
  2784. `Removed song "${songId}" from station "${stationId}" successfully.`
  2785. );
  2786. CacheModule.runJob("PUB", {
  2787. channel: "station.queueUpdate",
  2788. value: stationId
  2789. });
  2790. return cb({
  2791. status: "success",
  2792. message: "Successfully removed song from queue."
  2793. });
  2794. }
  2795. );
  2796. }),
  2797. /**
  2798. * Gets the queue from a station
  2799. *
  2800. * @param {object} session - user session
  2801. * @param {string} stationId - the station id
  2802. * @param {Function} cb - callback
  2803. */
  2804. getQueue(session, stationId, cb) {
  2805. async.waterfall(
  2806. [
  2807. next => {
  2808. StationsModule.runJob("GET_STATION", { stationId }, this)
  2809. .then(station => next(null, station))
  2810. .catch(next);
  2811. },
  2812. (station, next) => {
  2813. if (!station) return next("Station not found.");
  2814. return next(null, station);
  2815. },
  2816. (station, next) => {
  2817. StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  2818. .then(canView => {
  2819. if (canView) return next(null, station);
  2820. return next("Insufficient permissions.");
  2821. })
  2822. .catch(err => next(err));
  2823. },
  2824. (station, next) => {
  2825. if (station.type === "official") next(null, station.queue);
  2826. else next(null, station.queue);
  2827. }
  2828. ],
  2829. async (err, queue) => {
  2830. if (err) {
  2831. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2832. this.log(
  2833. "ERROR",
  2834. "STATIONS_GET_QUEUE",
  2835. `Getting queue for station "${stationId}" failed. "${err}"`
  2836. );
  2837. return cb({ status: "failure", message: err });
  2838. }
  2839. this.log("SUCCESS", "STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  2840. return cb({
  2841. status: "success",
  2842. message: "Successfully got queue.",
  2843. queue
  2844. });
  2845. }
  2846. );
  2847. },
  2848. /**
  2849. * Reposition a song in station queue
  2850. *
  2851. * @param {object} session - user session
  2852. * @param {object} song - contains details about the song that is to be repositioned
  2853. * @param {string} song.songId - the id of the song
  2854. * @param {number} song.newIndex - the new position for the song in the queue
  2855. * @param {number} song.oldIndex - the old position of the song in the queue
  2856. * @param {string} stationId - the station id
  2857. * @param {Function} cb - callback
  2858. */
  2859. repositionSongInQueue: isOwnerRequired(async function repositionQueue(session, song, stationId, cb) {
  2860. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2861. async.waterfall(
  2862. [
  2863. next => {
  2864. if (!song || !song.songId) return next("You must provide a song to reposition.");
  2865. return next();
  2866. },
  2867. // remove song from queue
  2868. next => {
  2869. stationModel.updateOne({ _id: stationId }, { $pull: { queue: { songId: song.songId } } }, next);
  2870. },
  2871. // add song back to queue (in new position)
  2872. (res, next) => {
  2873. stationModel.updateOne(
  2874. { _id: stationId },
  2875. { $push: { queue: { $each: [song], $position: song.newIndex } } },
  2876. err => next(err)
  2877. );
  2878. },
  2879. // update the cache representation of the station
  2880. next => {
  2881. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2882. .then(station => next(null, station))
  2883. .catch(next);
  2884. }
  2885. ],
  2886. async err => {
  2887. console.log(err);
  2888. if (err) {
  2889. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2890. this.log(
  2891. "ERROR",
  2892. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  2893. `Repositioning song ${song.songId} in queue of station "${stationId}" failed. "${err}"`
  2894. );
  2895. return cb({ status: "failure", message: err });
  2896. }
  2897. this.log(
  2898. "SUCCESS",
  2899. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  2900. `Repositioned song ${song.songId} in queue of station "${stationId}" successfully.`
  2901. );
  2902. CacheModule.runJob("PUB", {
  2903. channel: "station.repositionSongInQueue",
  2904. value: {
  2905. song: {
  2906. songId: song.songId,
  2907. oldIndex: song.oldIndex,
  2908. newIndex: song.newIndex
  2909. },
  2910. stationId
  2911. }
  2912. });
  2913. return cb({
  2914. status: "success",
  2915. message: "Successfully repositioned song in queue."
  2916. });
  2917. }
  2918. );
  2919. }),
  2920. /**
  2921. * Selects a private playlist for a station
  2922. *
  2923. * @param session
  2924. * @param stationId - the station id
  2925. * @param playlistId - the private playlist id
  2926. * @param cb
  2927. */
  2928. selectPrivatePlaylist: isOwnerRequired(async function selectPrivatePlaylist(session, stationId, playlistId, cb) {
  2929. async.waterfall(
  2930. [
  2931. next => {
  2932. StationsModule.runJob("GET_STATION", { stationId }, this)
  2933. .then(station => next(null, station))
  2934. .catch(next);
  2935. },
  2936. (station, next) => {
  2937. if (!station) return next("Station not found.");
  2938. if (station.type !== "community") return next("Station is not a community station.");
  2939. if (station.includedPlaylists.indexOf(playlistId) !== -1)
  2940. return next("That playlist is already included.");
  2941. return next();
  2942. },
  2943. next => {
  2944. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  2945. .then(() => {
  2946. next();
  2947. })
  2948. .catch(next);
  2949. }
  2950. ],
  2951. async err => {
  2952. if (err) {
  2953. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2954. this.log(
  2955. "ERROR",
  2956. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  2957. `Selecting private playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  2958. );
  2959. return cb({ status: "failure", message: err });
  2960. }
  2961. this.log(
  2962. "SUCCESS",
  2963. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  2964. `Selected private playlist "${playlistId}" for station "${stationId}" successfully.`
  2965. );
  2966. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2967. // CacheModule.runJob("PUB", {
  2968. // channel: "privatePlaylist.selected",
  2969. // value: {
  2970. // playlistId,
  2971. // stationId
  2972. // }
  2973. // });
  2974. return cb({
  2975. status: "success",
  2976. message: "Successfully selected playlist."
  2977. });
  2978. }
  2979. );
  2980. }),
  2981. /**
  2982. * Deselects the private playlist selected in a station
  2983. *
  2984. * @param session
  2985. * @param stationId - the station id
  2986. * @param cb
  2987. */
  2988. deselectPrivatePlaylist: isOwnerRequired(async function deselectPrivatePlaylist(
  2989. session,
  2990. stationId,
  2991. playlistId,
  2992. cb
  2993. ) {
  2994. async.waterfall(
  2995. [
  2996. next => {
  2997. StationsModule.runJob("GET_STATION", { stationId }, this)
  2998. .then(station => {
  2999. next(null, station);
  3000. })
  3001. .catch(next);
  3002. },
  3003. (station, next) => {
  3004. if (!station) return next("Station not found.");
  3005. if (station.type !== "community") return next("Station is not a community station.");
  3006. if (station.includedPlaylists.indexOf(playlistId) === -1)
  3007. return next("That playlist is not included.");
  3008. return next();
  3009. },
  3010. next => {
  3011. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  3012. .then(() => {
  3013. next();
  3014. })
  3015. .catch(next);
  3016. }
  3017. ],
  3018. async err => {
  3019. if (err) {
  3020. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3021. this.log(
  3022. "ERROR",
  3023. "STATIONS_DESELECT_PRIVATE_PLAYLIST",
  3024. `Deselecting private playlist for station "${stationId}" failed. "${err}"`
  3025. );
  3026. return cb({ status: "failure", message: err });
  3027. }
  3028. this.log(
  3029. "SUCCESS",
  3030. "STATIONS_DESELECT_PRIVATE_PLAYLIST",
  3031. `Deselected private playlist for station "${stationId}" successfully.`
  3032. );
  3033. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  3034. // CacheModule.runJob("PUB", {
  3035. // channel: "privatePlaylist.deselected",
  3036. // value: {
  3037. // stationId
  3038. // }
  3039. // });
  3040. return cb({
  3041. status: "success",
  3042. message: "Successfully deselected playlist."
  3043. });
  3044. }
  3045. );
  3046. }),
  3047. favoriteStation: isLoginRequired(async function favoriteStation(session, stationId, cb) {
  3048. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  3049. async.waterfall(
  3050. [
  3051. next => {
  3052. StationsModule.runJob("GET_STATION", { stationId }, this)
  3053. .then(station => next(null, station))
  3054. .catch(next);
  3055. },
  3056. (station, next) => {
  3057. if (!station) return next("Station not found.");
  3058. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  3059. .then(canView => {
  3060. if (canView) return next(null, station);
  3061. return next("Insufficient permissions.");
  3062. })
  3063. .catch(err => next(err));
  3064. },
  3065. (station, next) => {
  3066. userModel.updateOne(
  3067. { _id: session.userId },
  3068. { $addToSet: { favoriteStations: stationId } },
  3069. (err, res) => next(err, station, res)
  3070. );
  3071. },
  3072. (station, res, next) => {
  3073. if (res.nModified === 0) return next("The station was already favorited.");
  3074. return next(null, station);
  3075. }
  3076. ],
  3077. async (err, station) => {
  3078. if (err) {
  3079. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3080. this.log("ERROR", "FAVORITE_STATION", `Favoriting station "${stationId}" failed. "${err}"`);
  3081. return cb({ status: "failure", message: err });
  3082. }
  3083. this.log("SUCCESS", "FAVORITE_STATION", `Favorited station "${stationId}" successfully.`);
  3084. CacheModule.runJob("PUB", {
  3085. channel: "user.favoritedStation",
  3086. value: {
  3087. userId: session.userId,
  3088. stationId
  3089. }
  3090. });
  3091. ActivitiesModule.runJob("ADD_ACTIVITY", {
  3092. userId: session.userId,
  3093. type: "station__favorite",
  3094. payload: {
  3095. message: `Favorited station <stationId>${station.displayName}</stationId>`,
  3096. stationId
  3097. }
  3098. });
  3099. return cb({
  3100. status: "success",
  3101. message: "Succesfully favorited station."
  3102. });
  3103. }
  3104. );
  3105. }),
  3106. unfavoriteStation: isLoginRequired(async function unfavoriteStation(session, stationId, cb) {
  3107. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  3108. async.waterfall(
  3109. [
  3110. next => {
  3111. userModel.updateOne({ _id: session.userId }, { $pull: { favoriteStations: stationId } }, next);
  3112. },
  3113. (res, next) => {
  3114. if (res.nModified === 0) return next("The station wasn't favorited.");
  3115. return next();
  3116. },
  3117. next => {
  3118. StationsModule.runJob("GET_STATION", { stationId }, this)
  3119. .then(station => next(null, station))
  3120. .catch(next);
  3121. }
  3122. ],
  3123. async (err, station) => {
  3124. if (err) {
  3125. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3126. this.log("ERROR", "UNFAVORITE_STATION", `Unfavoriting station "${stationId}" failed. "${err}"`);
  3127. return cb({ status: "failure", message: err });
  3128. }
  3129. this.log("SUCCESS", "UNFAVORITE_STATION", `Unfavorited station "${stationId}" successfully.`);
  3130. CacheModule.runJob("PUB", {
  3131. channel: "user.unfavoritedStation",
  3132. value: {
  3133. userId: session.userId,
  3134. stationId
  3135. }
  3136. });
  3137. ActivitiesModule.runJob("ADD_ACTIVITY", {
  3138. userId: session.userId,
  3139. type: "station__unfavorite",
  3140. payload: {
  3141. message: `Unfavorited station <stationId>${station.displayName}</stationId>`,
  3142. stationId
  3143. }
  3144. });
  3145. return cb({
  3146. status: "success",
  3147. message: "Succesfully unfavorited station."
  3148. });
  3149. }
  3150. );
  3151. }),
  3152. /**
  3153. * Clears every station queue
  3154. *
  3155. * @param {object} session - the session object automatically added by socket.io
  3156. * @param {Function} cb - gets called with the result
  3157. */
  3158. clearEveryStationQueue: isAdminRequired(async function clearEveryStationQueue(session, cb) {
  3159. async.waterfall(
  3160. [
  3161. next => {
  3162. StationsModule.runJob("CLEAR_EVERY_STATION_QUEUE", {}, this)
  3163. .then(() => next())
  3164. .catch(next);
  3165. }
  3166. ],
  3167. async err => {
  3168. if (err) {
  3169. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3170. this.log("ERROR", "CLEAR_EVERY_STATION_QUEUE", `Clearing every station queue failed. "${err}"`);
  3171. return cb({ status: "failure", message: err });
  3172. }
  3173. this.log("SUCCESS", "CLEAR_EVERY_STATION_QUEUE", "Clearing every station queue was successfull.");
  3174. return cb({ status: "success", message: "Success" });
  3175. }
  3176. );
  3177. }),
  3178. /**
  3179. * Clears and refills a station queue
  3180. *
  3181. * @param {object} session - the session object automatically added by socket.io
  3182. * @param {string} stationId - the station id
  3183. * @param {Function} cb - gets called with the result
  3184. */
  3185. clearAndRefillStationQueue: isAdminRequired(async function clearAndRefillStationQueue(session, stationId, cb) {
  3186. async.waterfall(
  3187. [
  3188. next => {
  3189. StationsModule.runJob("CLEAR_AND_REFILL_STATION_QUEUE", { stationId }, this)
  3190. .then(() => next())
  3191. .catch(next);
  3192. }
  3193. ],
  3194. async err => {
  3195. if (err) {
  3196. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3197. this.log(
  3198. "ERROR",
  3199. "CLEAR_AND_REFILL_STATION_QUEUE",
  3200. `Clearing and refilling station queue failed. "${err}"`
  3201. );
  3202. return cb({ status: "failure", message: err });
  3203. }
  3204. this.log(
  3205. "SUCCESS",
  3206. "CLEAR_AND_REFILL_STATION_QUEUE",
  3207. "Clearing and refilling station queue was successfull."
  3208. );
  3209. return cb({ status: "success", message: "Success" });
  3210. }
  3211. );
  3212. })
  3213. };