stations.js 85 KB

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