stations.js 90 KB

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