stations.js 83 KB

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