stations.js 82 KB

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