stations.js 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857
  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. /**
  797. * Toggles if a station is locked
  798. *
  799. * @param session
  800. * @param stationId - the station id
  801. * @param cb
  802. */
  803. toggleLock: isOwnerRequired(async function toggleLock(session, stationId, cb) {
  804. const stationModel = await DBModule.runJob(
  805. "GET_MODEL",
  806. {
  807. modelName: "station"
  808. },
  809. this
  810. );
  811. async.waterfall(
  812. [
  813. next => {
  814. StationsModule.runJob("GET_STATION", { stationId }, this)
  815. .then(station => {
  816. next(null, station);
  817. })
  818. .catch(next);
  819. },
  820. (station, next) => {
  821. stationModel.updateOne({ _id: stationId }, { $set: { locked: !station.locked } }, next);
  822. },
  823. (res, next) => {
  824. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  825. .then(station => {
  826. next(null, station);
  827. })
  828. .catch(next);
  829. }
  830. ],
  831. async (err, station) => {
  832. if (err) {
  833. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  834. this.log(
  835. "ERROR",
  836. "STATIONS_UPDATE_LOCKED_STATUS",
  837. `Toggling the queue lock for station "${stationId}" failed. "${err}"`
  838. );
  839. return cb({ status: "failure", message: err });
  840. }
  841. this.log(
  842. "SUCCESS",
  843. "STATIONS_UPDATE_LOCKED_STATUS",
  844. `Toggled the queue lock for station "${stationId}" successfully to "${station.locked}".`
  845. );
  846. CacheModule.runJob("PUB", {
  847. channel: "station.queueLockToggled",
  848. value: {
  849. stationId,
  850. locked: station.locked
  851. }
  852. });
  853. return cb({ status: "success", data: station.locked });
  854. }
  855. );
  856. }),
  857. /**
  858. * Votes to skip a station
  859. *
  860. * @param session
  861. * @param stationId - the station id
  862. * @param cb
  863. */
  864. voteSkip: isLoginRequired(async function voteSkip(session, stationId, cb) {
  865. const stationModel = await DBModule.runJob(
  866. "GET_MODEL",
  867. {
  868. modelName: "station"
  869. },
  870. this
  871. );
  872. let skipVotes = 0;
  873. let shouldSkip = false;
  874. async.waterfall(
  875. [
  876. next => {
  877. StationsModule.runJob("GET_STATION", { stationId }, this)
  878. .then(station => {
  879. next(null, station);
  880. })
  881. .catch(next);
  882. },
  883. (station, next) => {
  884. if (!station) return next("Station not found.");
  885. return StationsModule.runJob(
  886. "CAN_USER_VIEW_STATION",
  887. {
  888. station,
  889. userId: session.userId
  890. },
  891. this
  892. )
  893. .then(canView => {
  894. if (canView) return next(null, station);
  895. return next("Insufficient permissions.");
  896. })
  897. .catch(err => next(err));
  898. },
  899. (station, next) => {
  900. if (!station.currentSong) return next("There is currently no song to skip.");
  901. if (station.currentSong.skipVotes.indexOf(session.userId) !== -1)
  902. return next("You have already voted to skip this song.");
  903. return next(null, station);
  904. },
  905. (station, next) => {
  906. stationModel.updateOne(
  907. { _id: stationId },
  908. { $push: { "currentSong.skipVotes": session.userId } },
  909. next
  910. );
  911. },
  912. (res, next) => {
  913. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  914. .then(station => {
  915. next(null, station);
  916. })
  917. .catch(next);
  918. },
  919. (station, next) => {
  920. if (!station) return next("Station not found.");
  921. return next(null, station);
  922. },
  923. (station, next) => {
  924. skipVotes = station.currentSong.skipVotes.length;
  925. IOModule.runJob(
  926. "GET_ROOM_SOCKETS",
  927. {
  928. room: `station.${stationId}`
  929. },
  930. this
  931. )
  932. .then(sockets => {
  933. next(null, sockets);
  934. })
  935. .catch(next);
  936. },
  937. (sockets, next) => {
  938. if (sockets.length <= skipVotes) shouldSkip = true;
  939. next();
  940. }
  941. ],
  942. async err => {
  943. if (err) {
  944. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  945. this.log("ERROR", "STATIONS_VOTE_SKIP", `Vote skipping station "${stationId}" failed. "${err}"`);
  946. return cb({ status: "failure", message: err });
  947. }
  948. this.log("SUCCESS", "STATIONS_VOTE_SKIP", `Vote skipping "${stationId}" successful.`);
  949. CacheModule.runJob("PUB", {
  950. channel: "station.voteSkipSong",
  951. value: stationId
  952. });
  953. if (shouldSkip) StationsModule.runJob("SKIP_STATION", { stationId });
  954. return cb({
  955. status: "success",
  956. message: "Successfully voted to skip the song."
  957. });
  958. }
  959. );
  960. }),
  961. /**
  962. * Force skips a station
  963. *
  964. * @param session
  965. * @param stationId - the station id
  966. * @param cb
  967. */
  968. forceSkip: isOwnerRequired(function forceSkip(session, stationId, cb) {
  969. async.waterfall(
  970. [
  971. next => {
  972. StationsModule.runJob("GET_STATION", { stationId }, this)
  973. .then(station => {
  974. next(null, station);
  975. })
  976. .catch(next);
  977. },
  978. (station, next) => {
  979. if (!station) return next("Station not found.");
  980. return next();
  981. }
  982. ],
  983. async err => {
  984. if (err) {
  985. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  986. this.log("ERROR", "STATIONS_FORCE_SKIP", `Force skipping station "${stationId}" failed. "${err}"`);
  987. return cb({ status: "failure", message: err });
  988. }
  989. StationsModule.runJob("SKIP_STATION", { stationId });
  990. this.log("SUCCESS", "STATIONS_FORCE_SKIP", `Force skipped station "${stationId}" successfully.`);
  991. return cb({
  992. status: "success",
  993. message: "Successfully skipped station."
  994. });
  995. }
  996. );
  997. }),
  998. /**
  999. * Leaves the user's current station
  1000. *
  1001. * @param {object} session - user session
  1002. * @param {string} stationId - id of station to leave
  1003. * @param {Function} cb - callback
  1004. */
  1005. leave(session, stationId, cb) {
  1006. async.waterfall(
  1007. [
  1008. next => {
  1009. StationsModule.runJob("GET_STATION", { stationId }, this)
  1010. .then(station => {
  1011. next(null, station);
  1012. })
  1013. .catch(next);
  1014. },
  1015. (station, next) => {
  1016. if (!station) return next("Station not found.");
  1017. return next();
  1018. }
  1019. ],
  1020. async (err, userCount) => {
  1021. if (err) {
  1022. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1023. this.log("ERROR", "STATIONS_LEAVE", `Leaving station "${stationId}" failed. "${err}"`);
  1024. return cb({ status: "failure", message: err });
  1025. }
  1026. this.log("SUCCESS", "STATIONS_LEAVE", `Left station "${stationId}" successfully.`);
  1027. IOModule.runJob("SOCKET_LEAVE_ROOMS", { socketId: session });
  1028. delete StationsModule.userList[session.socketId];
  1029. return cb({
  1030. status: "success",
  1031. message: "Successfully left station.",
  1032. userCount
  1033. });
  1034. }
  1035. );
  1036. },
  1037. /**
  1038. * Updates a station's name
  1039. *
  1040. * @param session
  1041. * @param stationId - the station id
  1042. * @param newName - the new station name
  1043. * @param cb
  1044. */
  1045. updateName: isOwnerRequired(async function updateName(session, stationId, newName, cb) {
  1046. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1047. async.waterfall(
  1048. [
  1049. next => {
  1050. stationModel.updateOne(
  1051. { _id: stationId },
  1052. { $set: { name: newName } },
  1053. { runValidators: true },
  1054. next
  1055. );
  1056. },
  1057. (res, next) => {
  1058. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1059. .then(station => next(null, station))
  1060. .catch(next);
  1061. }
  1062. ],
  1063. async (err, station) => {
  1064. if (err) {
  1065. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1066. this.log(
  1067. "ERROR",
  1068. "STATIONS_UPDATE_NAME",
  1069. `Updating station "${stationId}" name to "${newName}" failed. "${err}"`
  1070. );
  1071. return cb({ status: "failure", message: err });
  1072. }
  1073. this.log(
  1074. "SUCCESS",
  1075. "STATIONS_UPDATE_NAME",
  1076. `Updated station "${stationId}" name to "${newName}" successfully.`
  1077. );
  1078. CacheModule.runJob("PUB", {
  1079. channel: "station.nameUpdate",
  1080. value: { stationId, name: newName }
  1081. });
  1082. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1083. userId: session.userId,
  1084. type: "station__edit_name",
  1085. payload: {
  1086. message: `Changed name of station <stationId>${station.displayName}</stationId> to ${newName}`,
  1087. stationId
  1088. }
  1089. });
  1090. return cb({
  1091. status: "success",
  1092. message: "Successfully updated the name."
  1093. });
  1094. }
  1095. );
  1096. }),
  1097. /**
  1098. * Updates a station's display name
  1099. *
  1100. * @param session
  1101. * @param stationId - the station id
  1102. * @param newDisplayName - the new station display name
  1103. * @param cb
  1104. */
  1105. updateDisplayName: isOwnerRequired(async function updateDisplayName(session, stationId, newDisplayName, cb) {
  1106. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1107. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1108. async.waterfall(
  1109. [
  1110. next => {
  1111. stationModel.updateOne(
  1112. { _id: stationId },
  1113. { $set: { displayName: newDisplayName } },
  1114. { runValidators: true },
  1115. next
  1116. );
  1117. },
  1118. (res, next) => {
  1119. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1120. .then(station => next(null, station))
  1121. .catch(next);
  1122. },
  1123. (station, next) => {
  1124. playlistModel.updateOne(
  1125. { _id: station.playlist2 },
  1126. { $set: { displayName: `Station - ${station.displayName}` } },
  1127. err => {
  1128. next(err, station);
  1129. }
  1130. );
  1131. }
  1132. ],
  1133. async err => {
  1134. if (err) {
  1135. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1136. this.log(
  1137. "ERROR",
  1138. "STATIONS_UPDATE_DISPLAY_NAME",
  1139. `Updating station "${stationId}" displayName to "${newDisplayName}" failed. "${err}"`
  1140. );
  1141. return cb({ status: "failure", message: err });
  1142. }
  1143. this.log(
  1144. "SUCCESS",
  1145. "STATIONS_UPDATE_DISPLAY_NAME",
  1146. `Updated station "${stationId}" displayName to "${newDisplayName}" successfully.`
  1147. );
  1148. CacheModule.runJob("PUB", {
  1149. channel: "station.displayNameUpdate",
  1150. value: { stationId, displayName: newDisplayName }
  1151. });
  1152. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1153. userId: session.userId,
  1154. type: "station__edit_display_name",
  1155. payload: {
  1156. message: `Changed display name of station <stationId>${newDisplayName}</stationId>`,
  1157. stationId
  1158. }
  1159. });
  1160. return cb({
  1161. status: "success",
  1162. message: "Successfully updated the display name."
  1163. });
  1164. }
  1165. );
  1166. }),
  1167. /**
  1168. * Updates a station's description
  1169. *
  1170. * @param session
  1171. * @param stationId - the station id
  1172. * @param newDescription - the new station description
  1173. * @param cb
  1174. */
  1175. updateDescription: isOwnerRequired(async function updateDescription(session, stationId, newDescription, cb) {
  1176. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1177. async.waterfall(
  1178. [
  1179. next => {
  1180. stationModel.updateOne(
  1181. { _id: stationId },
  1182. { $set: { description: newDescription } },
  1183. { runValidators: true },
  1184. next
  1185. );
  1186. },
  1187. (res, next) => {
  1188. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1189. .then(station => next(null, station))
  1190. .catch(next);
  1191. }
  1192. ],
  1193. async (err, station) => {
  1194. if (err) {
  1195. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1196. this.log(
  1197. "ERROR",
  1198. "STATIONS_UPDATE_DESCRIPTION",
  1199. `Updating station "${stationId}" description to "${newDescription}" failed. "${err}"`
  1200. );
  1201. return cb({ status: "failure", message: err });
  1202. }
  1203. this.log(
  1204. "SUCCESS",
  1205. "STATIONS_UPDATE_DESCRIPTION",
  1206. `Updated station "${stationId}" description to "${newDescription}" successfully.`
  1207. );
  1208. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1209. userId: session.userId,
  1210. type: "station__edit_description",
  1211. payload: {
  1212. message: `Changed description of station <stationId>${station.displayName}</stationId> to ${newDescription}`,
  1213. stationId
  1214. }
  1215. });
  1216. CacheModule.runJob("PUB", {
  1217. channel: "station.descriptionUpdate",
  1218. value: { stationId, description: newDescription }
  1219. });
  1220. return cb({
  1221. status: "success",
  1222. message: "Successfully updated the description."
  1223. });
  1224. }
  1225. );
  1226. }),
  1227. /**
  1228. * Updates a station's privacy
  1229. *
  1230. * @param session
  1231. * @param stationId - the station id
  1232. * @param newPrivacy - the new station privacy
  1233. * @param cb
  1234. */
  1235. updatePrivacy: isOwnerRequired(async function updatePrivacy(session, stationId, newPrivacy, cb) {
  1236. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1237. let previousPrivacy = null;
  1238. async.waterfall(
  1239. [
  1240. next => {
  1241. stationModel.findOne({ _id: stationId }, next);
  1242. },
  1243. (station, next) => {
  1244. if (!station) next("No station found.");
  1245. else {
  1246. previousPrivacy = station.privacy;
  1247. next();
  1248. }
  1249. },
  1250. next => {
  1251. stationModel.updateOne(
  1252. { _id: stationId },
  1253. { $set: { privacy: newPrivacy } },
  1254. { runValidators: true },
  1255. next
  1256. );
  1257. },
  1258. (res, next) => {
  1259. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1260. .then(station => next(null, station))
  1261. .catch(next);
  1262. }
  1263. ],
  1264. async (err, station) => {
  1265. if (err) {
  1266. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1267. this.log(
  1268. "ERROR",
  1269. "STATIONS_UPDATE_PRIVACY",
  1270. `Updating station "${stationId}" privacy to "${newPrivacy}" failed. "${err}"`
  1271. );
  1272. return cb({ status: "failure", message: err });
  1273. }
  1274. this.log(
  1275. "SUCCESS",
  1276. "STATIONS_UPDATE_PRIVACY",
  1277. `Updated station "${stationId}" privacy to "${newPrivacy}" successfully.`
  1278. );
  1279. CacheModule.runJob("PUB", {
  1280. channel: "station.privacyUpdate",
  1281. value: { stationId, previousPrivacy }
  1282. });
  1283. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1284. userId: session.userId,
  1285. type: "station__edit_privacy",
  1286. payload: {
  1287. message: `Changed privacy of station <stationId>${station.displayName}</stationId> to ${newPrivacy}`,
  1288. stationId
  1289. }
  1290. });
  1291. return cb({
  1292. status: "success",
  1293. message: "Successfully updated the privacy."
  1294. });
  1295. }
  1296. );
  1297. }),
  1298. /**
  1299. * Updates a station's genres
  1300. *
  1301. * @param session
  1302. * @param stationId - the station id
  1303. * @param newGenres - the new station genres
  1304. * @param cb
  1305. */
  1306. updateGenres: isOwnerRequired(async function updateGenres(session, stationId, newGenres, cb) {
  1307. async.waterfall(
  1308. [
  1309. next => {
  1310. StationsModule.runJob("GET_STATION", { stationId }, this)
  1311. .then(station => {
  1312. next(null, station);
  1313. })
  1314. .catch(next);
  1315. },
  1316. (station, next) => {
  1317. const playlists = [];
  1318. async.eachLimit(
  1319. newGenres,
  1320. 1,
  1321. (genre, next) => {
  1322. PlaylistsModule.runJob("GET_GENRE_PLAYLIST", { genre, includeSongs: false }, this).then(
  1323. response => {
  1324. playlists.push(response.playlist);
  1325. next();
  1326. }
  1327. );
  1328. },
  1329. err => {
  1330. next(
  1331. err,
  1332. station,
  1333. playlists.map(playlist => playlist._id.toString())
  1334. );
  1335. }
  1336. );
  1337. },
  1338. (station, playlists, next) => {
  1339. const playlistsToRemoveFromExcluded = playlists.filter(
  1340. playlistId => station.excludedPlaylists.indexOf(playlistId) !== -1
  1341. );
  1342. console.log(
  1343. `playlistsToRemoveFromExcluded: ${playlistsToRemoveFromExcluded.length}`,
  1344. playlistsToRemoveFromExcluded
  1345. );
  1346. async.eachLimit(
  1347. playlistsToRemoveFromExcluded,
  1348. 1,
  1349. (playlistId, next) => {
  1350. StationsModule.runJob("REMOVE_EXCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1351. .then(() => {
  1352. next();
  1353. })
  1354. .catch(next);
  1355. },
  1356. err => {
  1357. next(err, station, playlists);
  1358. }
  1359. );
  1360. },
  1361. (station, playlists, next) => {
  1362. const playlistsToRemoveFromIncluded = station.includedPlaylists.filter(
  1363. playlistId => playlists.indexOf(playlistId) === -1
  1364. );
  1365. console.log(
  1366. `playlistsToRemoveFromIncluded: ${playlistsToRemoveFromIncluded.length}`,
  1367. playlistsToRemoveFromIncluded
  1368. );
  1369. async.eachLimit(
  1370. playlistsToRemoveFromIncluded,
  1371. 1,
  1372. (playlistId, next) => {
  1373. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  1374. .then(() => {
  1375. next();
  1376. })
  1377. .catch(next);
  1378. },
  1379. err => {
  1380. next(err, station, playlists);
  1381. }
  1382. );
  1383. },
  1384. (station, playlists, next) => {
  1385. const playlistsToAddToIncluded = playlists.filter(
  1386. playlistId => station.includedPlaylists.indexOf(playlistId) === -1
  1387. );
  1388. console.log(
  1389. `playlistsToAddToIncluded: ${playlistsToAddToIncluded.length}`,
  1390. playlistsToAddToIncluded
  1391. );
  1392. async.eachLimit(
  1393. playlistsToAddToIncluded,
  1394. 1,
  1395. (playlistId, next) => {
  1396. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  1397. .then(() => {
  1398. next();
  1399. })
  1400. .catch(next);
  1401. },
  1402. err => {
  1403. next(err);
  1404. }
  1405. );
  1406. },
  1407. next => {
  1408. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1409. .then(station => next(null, station))
  1410. .catch(next);
  1411. }
  1412. ],
  1413. async (err, station) => {
  1414. if (err) {
  1415. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1416. this.log(
  1417. "ERROR",
  1418. "STATIONS_UPDATE_GENRES",
  1419. `Updating station "${stationId}" genres to "${newGenres}" failed. "${err}"`
  1420. );
  1421. return cb({ status: "failure", message: err });
  1422. }
  1423. this.log(
  1424. "SUCCESS",
  1425. "STATIONS_UPDATE_GENRES",
  1426. `Updated station "${stationId}" genres to "${newGenres}" successfully.`
  1427. );
  1428. if (newGenres.length > 0) {
  1429. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1430. userId: session.userId,
  1431. type: "station__edit_genres",
  1432. payload: {
  1433. message: `Updated genres of station <stationId>${station.displayName}</stationId> to
  1434. ${newGenres.join(", ")}`,
  1435. stationId
  1436. }
  1437. });
  1438. } else {
  1439. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1440. userId: session.userId,
  1441. type: "station__edit_genres",
  1442. payload: {
  1443. message: `Removed all genres of station <stationId>${station.displayName}</stationId>`,
  1444. stationId
  1445. }
  1446. });
  1447. }
  1448. return cb({
  1449. status: "success",
  1450. message: "Successfully updated the genres."
  1451. });
  1452. }
  1453. );
  1454. }),
  1455. /**
  1456. * Updates a station's blacklisted genres
  1457. *
  1458. * @param session
  1459. * @param stationId - the station id
  1460. * @param newBlacklistedGenres - the new station blacklisted genres
  1461. * @param cb
  1462. */
  1463. updateBlacklistedGenres: isOwnerRequired(async function updateBlacklistedGenres(
  1464. session,
  1465. stationId,
  1466. newBlacklistedGenres,
  1467. cb
  1468. ) {
  1469. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1470. async.waterfall(
  1471. [
  1472. next => {
  1473. stationModel.updateOne(
  1474. { _id: stationId },
  1475. {
  1476. $set: {
  1477. blacklistedGenres: newBlacklistedGenres
  1478. }
  1479. },
  1480. { runValidators: true },
  1481. next
  1482. );
  1483. },
  1484. (res, next) => {
  1485. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1486. .then(station => next(null, station))
  1487. .catch(next);
  1488. }
  1489. ],
  1490. async (err, station) => {
  1491. if (err) {
  1492. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1493. this.log(
  1494. "ERROR",
  1495. "STATIONS_UPDATE_BLACKLISTED_GENRES",
  1496. `Updating station "${stationId}" blacklisted genres to "${newBlacklistedGenres}" failed. "${err}"`
  1497. );
  1498. return cb({ status: "failure", message: err });
  1499. }
  1500. this.log(
  1501. "SUCCESS",
  1502. "STATIONS_UPDATE_BLACKLISTED_GENRES",
  1503. `Updated station "${stationId}" blacklisted genres to "${newBlacklistedGenres}" successfully.`
  1504. );
  1505. if (newBlacklistedGenres.length > 0) {
  1506. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1507. userId: session.userId,
  1508. type: "station__edit_blacklisted_genres",
  1509. payload: {
  1510. message: `Updated blacklisted genres of station <stationId>${
  1511. station.displayName
  1512. }</stationId> to ${newBlacklistedGenres.join(", ")}`,
  1513. stationId
  1514. }
  1515. });
  1516. } else {
  1517. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1518. userId: session.userId,
  1519. type: "station__edit_blacklisted_genres",
  1520. payload: {
  1521. message: `Removed all blacklisted genres of station <stationId>${station.displayName}</stationId>`,
  1522. stationId
  1523. }
  1524. });
  1525. }
  1526. return cb({
  1527. status: "success",
  1528. message: "Successfully updated the blacklisted genres."
  1529. });
  1530. }
  1531. );
  1532. }),
  1533. /**
  1534. * Updates a station's party mode
  1535. *
  1536. * @param session
  1537. * @param stationId - the station id
  1538. * @param newPartyMode - the new station party mode
  1539. * @param cb
  1540. */
  1541. updatePartyMode: isOwnerRequired(async function updatePartyMode(session, stationId, newPartyMode, cb) {
  1542. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1543. async.waterfall(
  1544. [
  1545. next => {
  1546. StationsModule.runJob("GET_STATION", { stationId }, this)
  1547. .then(station => {
  1548. next(null, station);
  1549. })
  1550. .catch(next);
  1551. },
  1552. (station, next) => {
  1553. if (!station) return next("Station not found.");
  1554. if (station.partyMode === newPartyMode)
  1555. return next(`The party mode was already ${newPartyMode ? "enabled." : "disabled."}`);
  1556. return stationModel.updateOne(
  1557. { _id: stationId },
  1558. { $set: { partyMode: newPartyMode } },
  1559. { runValidators: true },
  1560. next
  1561. );
  1562. },
  1563. (res, next) => {
  1564. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1565. .then(station => {
  1566. next(null, station);
  1567. })
  1568. .catch(next);
  1569. }
  1570. ],
  1571. async err => {
  1572. if (err) {
  1573. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1574. this.log(
  1575. "ERROR",
  1576. "STATIONS_UPDATE_PARTY_MODE",
  1577. `Updating station "${stationId}" party mode to "${newPartyMode}" failed. "${err}"`
  1578. );
  1579. return cb({ status: "failure", message: err });
  1580. }
  1581. this.log(
  1582. "SUCCESS",
  1583. "STATIONS_UPDATE_PARTY_MODE",
  1584. `Updated station "${stationId}" party mode to "${newPartyMode}" successfully.`
  1585. );
  1586. CacheModule.runJob("PUB", {
  1587. channel: "station.updatePartyMode",
  1588. value: {
  1589. stationId,
  1590. partyMode: newPartyMode
  1591. }
  1592. });
  1593. StationsModule.runJob("SKIP_STATION", { stationId });
  1594. return cb({
  1595. status: "success",
  1596. message: "Successfully updated the party mode."
  1597. });
  1598. }
  1599. );
  1600. }),
  1601. /**
  1602. * Updates a station's theme
  1603. *
  1604. * @param session
  1605. * @param stationId - the station id
  1606. * @param newTheme - the new station theme
  1607. * @param cb
  1608. */
  1609. updateTheme: isOwnerRequired(async function updateTheme(session, stationId, newTheme, cb) {
  1610. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1611. async.waterfall(
  1612. [
  1613. next => {
  1614. StationsModule.runJob("GET_STATION", { stationId }, this)
  1615. .then(station => {
  1616. next(null, station);
  1617. })
  1618. .catch(next);
  1619. },
  1620. (station, next) => {
  1621. if (!station) return next("Station not found.");
  1622. if (station.theme === newTheme) return next("No change in theme.");
  1623. return stationModel.updateOne(
  1624. { _id: stationId },
  1625. { $set: { theme: newTheme } },
  1626. { runValidators: true },
  1627. next
  1628. );
  1629. },
  1630. (res, next) => {
  1631. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1632. .then(station => next(null, station))
  1633. .catch(next);
  1634. }
  1635. ],
  1636. async (err, station) => {
  1637. if (err) {
  1638. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1639. this.log(
  1640. "ERROR",
  1641. "STATIONS_UPDATE_THEME",
  1642. `Updating station "${stationId}" theme to "${newTheme}" failed. "${err}"`
  1643. );
  1644. return cb({ status: "failure", message: err });
  1645. }
  1646. this.log(
  1647. "SUCCESS",
  1648. "STATIONS_UPDATE_THEME",
  1649. `Updated station "${stationId}" theme to "${newTheme}" successfully.`
  1650. );
  1651. CacheModule.runJob("PUB", {
  1652. channel: "station.themeUpdate",
  1653. value: { stationId }
  1654. });
  1655. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1656. userId: session.userId,
  1657. type: "station__edit_theme",
  1658. payload: {
  1659. message: `Changed theme of station <stationId>${station.displayName}</stationId> to ${newTheme}`,
  1660. stationId
  1661. }
  1662. });
  1663. return cb({
  1664. status: "success",
  1665. message: "Successfully updated the theme."
  1666. });
  1667. }
  1668. );
  1669. }),
  1670. /**
  1671. * Pauses a station
  1672. *
  1673. * @param session
  1674. * @param stationId - the station id
  1675. * @param cb
  1676. */
  1677. pause: isOwnerRequired(async function pause(session, stationId, cb) {
  1678. const stationModel = await DBModule.runJob(
  1679. "GET_MODEL",
  1680. {
  1681. modelName: "station"
  1682. },
  1683. this
  1684. );
  1685. async.waterfall(
  1686. [
  1687. next => {
  1688. StationsModule.runJob("GET_STATION", { stationId }, this)
  1689. .then(station => {
  1690. next(null, station);
  1691. })
  1692. .catch(next);
  1693. },
  1694. (station, next) => {
  1695. if (!station) return next("Station not found.");
  1696. if (station.paused) return next("That station was already paused.");
  1697. return stationModel.updateOne(
  1698. { _id: stationId },
  1699. { $set: { paused: true, pausedAt: Date.now() } },
  1700. next
  1701. );
  1702. },
  1703. (res, next) => {
  1704. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1705. .then(station => {
  1706. next(null, station);
  1707. })
  1708. .catch(next);
  1709. }
  1710. ],
  1711. async err => {
  1712. if (err) {
  1713. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1714. this.log("ERROR", "STATIONS_PAUSE", `Pausing station "${stationId}" failed. "${err}"`);
  1715. return cb({ status: "failure", message: err });
  1716. }
  1717. this.log("SUCCESS", "STATIONS_PAUSE", `Paused station "${stationId}" successfully.`);
  1718. CacheModule.runJob("PUB", {
  1719. channel: "station.pause",
  1720. value: stationId
  1721. });
  1722. NotificationsModule.runJob("UNSCHEDULE", {
  1723. name: `stations.nextSong?id=${stationId}`
  1724. });
  1725. return cb({
  1726. status: "success",
  1727. message: "Successfully paused."
  1728. });
  1729. }
  1730. );
  1731. }),
  1732. /**
  1733. * Resumes a station
  1734. *
  1735. * @param session
  1736. * @param stationId - the station id
  1737. * @param cb
  1738. */
  1739. resume: isOwnerRequired(async function resume(session, stationId, cb) {
  1740. const stationModel = await DBModule.runJob(
  1741. "GET_MODEL",
  1742. {
  1743. modelName: "station"
  1744. },
  1745. this
  1746. );
  1747. async.waterfall(
  1748. [
  1749. next => {
  1750. StationsModule.runJob("GET_STATION", { stationId }, this)
  1751. .then(station => {
  1752. next(null, station);
  1753. })
  1754. .catch(next);
  1755. },
  1756. (station, next) => {
  1757. if (!station) return next("Station not found.");
  1758. if (!station.paused) return next("That station is not paused.");
  1759. station.timePaused += Date.now() - station.pausedAt;
  1760. return stationModel.updateOne(
  1761. { _id: stationId },
  1762. {
  1763. $set: { paused: false },
  1764. $inc: { timePaused: Date.now() - station.pausedAt }
  1765. },
  1766. next
  1767. );
  1768. },
  1769. (res, next) => {
  1770. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1771. .then(station => {
  1772. next(null, station);
  1773. })
  1774. .catch(next);
  1775. }
  1776. ],
  1777. async err => {
  1778. if (err) {
  1779. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1780. this.log("ERROR", "STATIONS_RESUME", `Resuming station "${stationId}" failed. "${err}"`);
  1781. return cb({ status: "failure", message: err });
  1782. }
  1783. this.log("SUCCESS", "STATIONS_RESUME", `Resuming station "${stationId}" successfully.`);
  1784. CacheModule.runJob("PUB", {
  1785. channel: "station.resume",
  1786. value: stationId
  1787. });
  1788. return cb({
  1789. status: "success",
  1790. message: "Successfully resumed."
  1791. });
  1792. }
  1793. );
  1794. }),
  1795. /**
  1796. * Removes a station
  1797. *
  1798. * @param session
  1799. * @param stationId - the station id
  1800. * @param cb
  1801. */
  1802. remove: isOwnerRequired(async function remove(session, stationId, cb) {
  1803. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1804. async.waterfall(
  1805. [
  1806. next => {
  1807. stationModel.findById(stationId, (err, station) => {
  1808. if (err) return next(err);
  1809. return next(null, station);
  1810. });
  1811. },
  1812. (station, next) => {
  1813. stationModel.deleteOne({ _id: stationId }, err => next(err, station));
  1814. },
  1815. (station, next) => {
  1816. CacheModule.runJob("HDEL", { table: "stations", key: stationId }, this)
  1817. .then(next(null, station))
  1818. .catch(next);
  1819. },
  1820. (station, next) => {
  1821. if (station.playlist2)
  1822. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: station.playlist2 }).then().catch();
  1823. next(null, station);
  1824. }
  1825. ],
  1826. async (err, station) => {
  1827. if (err) {
  1828. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1829. this.log("ERROR", "STATIONS_REMOVE", `Removing station "${stationId}" failed. "${err}"`);
  1830. return cb({ status: "failure", message: err });
  1831. }
  1832. this.log("SUCCESS", "STATIONS_REMOVE", `Removing station "${stationId}" successfully.`);
  1833. CacheModule.runJob("PUB", {
  1834. channel: "station.remove",
  1835. value: stationId
  1836. });
  1837. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1838. userId: session.userId,
  1839. type: "station__remove",
  1840. payload: { message: `Removed a station named <stationId>${station.displayName}</stationId>` }
  1841. });
  1842. return cb({
  1843. status: "success",
  1844. message: "Successfully removed."
  1845. });
  1846. }
  1847. );
  1848. }),
  1849. /**
  1850. * Create a station
  1851. *
  1852. * @param session
  1853. * @param data - the station data
  1854. * @param cb
  1855. */
  1856. create: isLoginRequired(async function create(session, data, cb) {
  1857. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1858. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1859. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1860. data.name = data.name.toLowerCase();
  1861. const blacklist = [
  1862. "country",
  1863. "edm",
  1864. "musare",
  1865. "hip-hop",
  1866. "rap",
  1867. "top-hits",
  1868. "todays-hits",
  1869. "old-school",
  1870. "christmas",
  1871. "about",
  1872. "support",
  1873. "staff",
  1874. "help",
  1875. "news",
  1876. "terms",
  1877. "privacy",
  1878. "profile",
  1879. "c",
  1880. "community",
  1881. "tos",
  1882. "login",
  1883. "register",
  1884. "p",
  1885. "official",
  1886. "o",
  1887. "trap",
  1888. "faq",
  1889. "team",
  1890. "donate",
  1891. "buy",
  1892. "shop",
  1893. "forums",
  1894. "explore",
  1895. "settings",
  1896. "admin",
  1897. "auth",
  1898. "reset_password"
  1899. ];
  1900. async.waterfall(
  1901. [
  1902. next => {
  1903. if (!data) return next("Invalid data.");
  1904. return next();
  1905. },
  1906. next => {
  1907. stationModel.findOne(
  1908. {
  1909. $or: [
  1910. { name: data.name },
  1911. {
  1912. displayName: new RegExp(`^${data.displayName}$`, "i")
  1913. }
  1914. ]
  1915. },
  1916. next
  1917. );
  1918. },
  1919. // eslint-disable-next-line consistent-return
  1920. (station, next) => {
  1921. this.log(station);
  1922. if (station) return next("A station with that name or display name already exists.");
  1923. const { name, displayName, description, genres, playlist, type, blacklistedGenres } = data;
  1924. const stationId = mongoose.Types.ObjectId();
  1925. if (type === "official") {
  1926. return userModel.findOne({ _id: session.userId }, (err, user) => {
  1927. if (err) return next(err);
  1928. if (!user) return next("User not found.");
  1929. if (user.role !== "admin") return next("Admin required.");
  1930. return playlistModel.create(
  1931. {
  1932. isUserModifiable: false,
  1933. displayName: `Station - ${displayName}`,
  1934. songs: [],
  1935. createdBy: "Musare",
  1936. createdFor: `${stationId}`,
  1937. createdAt: Date.now(),
  1938. type: "station"
  1939. },
  1940. (err, playlist2) => {
  1941. if (err) next(err);
  1942. else {
  1943. stationModel.create(
  1944. {
  1945. _id: stationId,
  1946. name,
  1947. displayName,
  1948. description,
  1949. type,
  1950. privacy: "private",
  1951. playlist2: playlist2._id,
  1952. playlist,
  1953. genres,
  1954. blacklistedGenres,
  1955. currentSong: StationsModule.defaultSong
  1956. },
  1957. next
  1958. );
  1959. }
  1960. }
  1961. );
  1962. });
  1963. }
  1964. if (type === "community") {
  1965. if (blacklist.indexOf(name) !== -1)
  1966. return next("That name is blacklisted. Please use a different name.");
  1967. return playlistModel.create(
  1968. {
  1969. isUserModifiable: false,
  1970. displayName: `Station - ${name}`,
  1971. songs: [],
  1972. createdBy: session.userId,
  1973. createdFor: `${stationId}`,
  1974. createdAt: Date.now(),
  1975. type: "station"
  1976. },
  1977. (err, playlist2) => {
  1978. if (err) next(err);
  1979. else {
  1980. stationModel.create(
  1981. {
  1982. name,
  1983. displayName,
  1984. description,
  1985. playlist2: playlist2._id,
  1986. type,
  1987. privacy: "private",
  1988. owner: session.userId,
  1989. queue: [],
  1990. currentSong: null
  1991. },
  1992. next
  1993. );
  1994. }
  1995. }
  1996. );
  1997. }
  1998. }
  1999. ],
  2000. async (err, station) => {
  2001. if (err) {
  2002. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2003. this.log("ERROR", "STATIONS_CREATE", `Creating station failed. "${err}"`);
  2004. return cb({ status: "failure", message: err });
  2005. }
  2006. this.log("SUCCESS", "STATIONS_CREATE", `Created station "${station._id}" successfully.`);
  2007. CacheModule.runJob("PUB", {
  2008. channel: "station.create",
  2009. value: station._id
  2010. });
  2011. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2012. userId: session.userId,
  2013. type: "station__create",
  2014. payload: {
  2015. message: `Created a station named <stationId>${station.displayName}</stationId>`,
  2016. stationId: station._id
  2017. }
  2018. });
  2019. return cb({
  2020. status: "success",
  2021. message: "Successfully created station."
  2022. });
  2023. }
  2024. );
  2025. }),
  2026. /**
  2027. * Adds song to station queue
  2028. *
  2029. * @param session
  2030. * @param stationId - the station id
  2031. * @param songId - the song id
  2032. * @param cb
  2033. */
  2034. addToQueue: isLoginRequired(async function addToQueue(session, stationId, songId, cb) {
  2035. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2036. const playlistModel = await DBModule.runJob(
  2037. "GET_MODEL",
  2038. {
  2039. modelName: "playlist"
  2040. },
  2041. this
  2042. );
  2043. async.waterfall(
  2044. [
  2045. next => {
  2046. StationsModule.runJob("GET_STATION", { stationId }, this)
  2047. .then(station => {
  2048. next(null, station);
  2049. })
  2050. .catch(next);
  2051. },
  2052. (station, next) => {
  2053. if (!station) return next("Station not found.");
  2054. if (!station.partyMode) return next("Station is not in party mode.");
  2055. if (station.locked) {
  2056. return userModel.findOne({ _id: session.userId }, (err, user) => {
  2057. if (user.role !== "admin" && station.owner !== session.userId)
  2058. return next("Only owners and admins can add songs to a locked queue.");
  2059. return next(null, station);
  2060. });
  2061. }
  2062. return next(null, station);
  2063. },
  2064. (station, next) => {
  2065. if (station.type !== "community") return next("That station is not a community station.");
  2066. return StationsModule.runJob(
  2067. "CAN_USER_VIEW_STATION",
  2068. {
  2069. station,
  2070. userId: session.userId
  2071. },
  2072. this
  2073. )
  2074. .then(canView => {
  2075. if (canView) return next(null, station);
  2076. return next("Insufficient permissions.");
  2077. })
  2078. .catch(err => next(err));
  2079. },
  2080. (station, next) => {
  2081. if (station.currentSong && station.currentSong.songId === songId)
  2082. return next("That song is currently playing.");
  2083. return playlistModel.findOne({ _id: station.playlist2 }, (err, playlist) => {
  2084. console.log(111, station, err, playlist);
  2085. next(err, station, playlist);
  2086. });
  2087. },
  2088. (station, playlist, next) => {
  2089. async.each(
  2090. playlist.songs,
  2091. (song, next) => {
  2092. if (song.songId === songId) return next("That song is already in the queue.");
  2093. return next();
  2094. },
  2095. err => next(err, station, playlist)
  2096. );
  2097. },
  2098. (station, playlist, next) => {
  2099. SongsModule.runJob("GET_SONG_FROM_ID", { songId }, this)
  2100. .then(res => {
  2101. if (res.song) return next(null, res.song, station, playlist);
  2102. return YouTubeModule.runJob("GET_SONG", { songId }, this)
  2103. .then(response => {
  2104. const { song } = response;
  2105. song.artists = [];
  2106. song.skipDuration = 0;
  2107. song.likes = -1;
  2108. song.dislikes = -1;
  2109. song.thumbnail = "empty";
  2110. song.explicit = false;
  2111. return next(null, song, station, playlist);
  2112. })
  2113. .catch(err => {
  2114. console.log(11111, err);
  2115. next(err);
  2116. });
  2117. })
  2118. .catch(err => {
  2119. console.log(11122, err);
  2120. next(err);
  2121. });
  2122. },
  2123. (song, station, playlist, next) => {
  2124. song.requestedBy = session.userId;
  2125. song.requestedAt = Date.now();
  2126. let totalDuration = 0;
  2127. playlist.songs.forEach(song => {
  2128. totalDuration += song.duration;
  2129. });
  2130. if (totalDuration >= 3600 * 3) return next("The max length of the queue is 3 hours.");
  2131. return next(null, song, station, playlist);
  2132. },
  2133. (song, station, playlist, next) => {
  2134. console.log(333, song, station, playlist);
  2135. if (playlist.songs.length === 0) return next(null, song, station, playlist);
  2136. let totalDuration = 0;
  2137. const userId = playlist.songs[playlist.songs.length - 1].requestedBy;
  2138. playlist.songs.forEach(song => {
  2139. if (userId === song.requestedBy) {
  2140. totalDuration += song.duration;
  2141. }
  2142. });
  2143. if (totalDuration >= 900) return next("The max length of songs per user is 15 minutes.");
  2144. return next(null, song, station, playlist);
  2145. },
  2146. (song, station, playlist, next) => {
  2147. console.log(444, song, station, playlist);
  2148. if (playlist.songs.length === 0) return next(null, song, station);
  2149. let totalSongs = 0;
  2150. const userId = playlist.songs[playlist.songs.length - 1].requestedBy;
  2151. playlist.songs.forEach(song => {
  2152. if (userId === song.requestedBy) {
  2153. totalSongs += 1;
  2154. }
  2155. });
  2156. if (totalSongs <= 2) return next(null, song, station);
  2157. if (totalSongs > 3)
  2158. return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  2159. if (
  2160. playlist.songs[playlist.songs.length - 2].requestedBy !== userId ||
  2161. playlist.songs[playlist.songs.length - 3] !== userId
  2162. )
  2163. return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  2164. return next(null, song, station);
  2165. },
  2166. (song, station, next) => {
  2167. playlistModel.updateOne(
  2168. { _id: station.playlist2 },
  2169. { $push: { songs: song } },
  2170. { runValidators: true },
  2171. next
  2172. );
  2173. }
  2174. // (res, next) => {
  2175. // StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2176. // .then(station => next(null, station))
  2177. // .catch(next);
  2178. // }
  2179. // (res, next) => {
  2180. // StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2181. // .then(station => {
  2182. // next(null, station);
  2183. // })
  2184. // .catch(next);
  2185. // }
  2186. ],
  2187. async err => {
  2188. if (err) {
  2189. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2190. this.log(
  2191. "ERROR",
  2192. "STATIONS_ADD_SONG_TO_QUEUE",
  2193. `Adding song "${songId}" to station "${stationId}" queue failed. "${err}"`
  2194. );
  2195. return cb({ status: "failure", message: err });
  2196. }
  2197. this.log(
  2198. "SUCCESS",
  2199. "STATIONS_ADD_SONG_TO_QUEUE",
  2200. `Added song "${songId}" to station "${stationId}" successfully.`
  2201. );
  2202. CacheModule.runJob("PUB", {
  2203. channel: "station.queueUpdate",
  2204. value: stationId
  2205. });
  2206. return cb({
  2207. status: "success",
  2208. message: "Successfully added song to queue."
  2209. });
  2210. }
  2211. );
  2212. }),
  2213. /**
  2214. * Removes song from station queue
  2215. *
  2216. * @param session
  2217. * @param stationId - the station id
  2218. * @param songId - the song id
  2219. * @param cb
  2220. */
  2221. removeFromQueue: isOwnerRequired(async function removeFromQueue(session, stationId, songId, cb) {
  2222. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2223. async.waterfall(
  2224. [
  2225. next => {
  2226. if (!songId) return next("Invalid song id.");
  2227. return StationsModule.runJob("GET_STATION", { stationId }, this)
  2228. .then(station => next(null, station))
  2229. .catch(next);
  2230. },
  2231. (station, next) => {
  2232. if (!station) return next("Station not found.");
  2233. if (station.type !== "community") return next("Station is not a community station.");
  2234. return async.each(
  2235. station.queue,
  2236. (queueSong, next) => {
  2237. if (queueSong.songId === songId) return next(true);
  2238. return next();
  2239. },
  2240. err => {
  2241. if (err === true) return next();
  2242. return next("Song is not currently in the queue.");
  2243. }
  2244. );
  2245. },
  2246. next => {
  2247. stationModel.updateOne({ _id: stationId }, { $pull: { queue: { songId } } }, next);
  2248. },
  2249. (res, next) => {
  2250. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2251. .then(station => next(null, station))
  2252. .catch(next);
  2253. }
  2254. ],
  2255. async err => {
  2256. if (err) {
  2257. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2258. this.log(
  2259. "ERROR",
  2260. "STATIONS_REMOVE_SONG_TO_QUEUE",
  2261. `Removing song "${songId}" from station "${stationId}" queue failed. "${err}"`
  2262. );
  2263. return cb({ status: "failure", message: err });
  2264. }
  2265. this.log(
  2266. "SUCCESS",
  2267. "STATIONS_REMOVE_SONG_TO_QUEUE",
  2268. `Removed song "${songId}" from station "${stationId}" successfully.`
  2269. );
  2270. CacheModule.runJob("PUB", {
  2271. channel: "station.queueUpdate",
  2272. value: stationId
  2273. });
  2274. return cb({
  2275. status: "success",
  2276. message: "Successfully removed song from queue."
  2277. });
  2278. }
  2279. );
  2280. }),
  2281. /**
  2282. * Gets the queue from a station
  2283. *
  2284. * @param {object} session - user session
  2285. * @param {string} stationId - the station id
  2286. * @param {Function} cb - callback
  2287. */
  2288. getQueue(session, stationId, cb) {
  2289. async.waterfall(
  2290. [
  2291. next => {
  2292. StationsModule.runJob("GET_STATION", { stationId }, this)
  2293. .then(station => next(null, station))
  2294. .catch(next);
  2295. },
  2296. (station, next) => {
  2297. if (!station) return next("Station not found.");
  2298. if (station.type !== "community") return next("Station is not a community station.");
  2299. return next(null, station);
  2300. },
  2301. (station, next) => {
  2302. StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  2303. .then(canView => {
  2304. if (canView) return next(null, station);
  2305. return next("Insufficient permissions.");
  2306. })
  2307. .catch(err => next(err));
  2308. }
  2309. ],
  2310. async (err, station) => {
  2311. if (err) {
  2312. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2313. this.log(
  2314. "ERROR",
  2315. "STATIONS_GET_QUEUE",
  2316. `Getting queue for station "${stationId}" failed. "${err}"`
  2317. );
  2318. return cb({ status: "failure", message: err });
  2319. }
  2320. this.log("SUCCESS", "STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  2321. return cb({
  2322. status: "success",
  2323. message: "Successfully got queue.",
  2324. queue: station.queue
  2325. });
  2326. }
  2327. );
  2328. },
  2329. /**
  2330. * Selects a private playlist for a station
  2331. *
  2332. * @param session
  2333. * @param stationId - the station id
  2334. * @param playlistId - the private playlist id
  2335. * @param cb
  2336. */
  2337. selectPrivatePlaylist: isOwnerRequired(async function selectPrivatePlaylist(session, stationId, playlistId, cb) {
  2338. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2339. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  2340. async.waterfall(
  2341. [
  2342. next => {
  2343. StationsModule.runJob("GET_STATION", { stationId }, this)
  2344. .then(station => next(null, station))
  2345. .catch(next);
  2346. },
  2347. (station, next) => {
  2348. if (!station) return next("Station not found.");
  2349. if (station.type !== "community") return next("Station is not a community station.");
  2350. if (station.privatePlaylist === playlistId)
  2351. return next("That private playlist is already selected.");
  2352. return playlistModel.findOne({ _id: playlistId }, next);
  2353. },
  2354. (playlist, next) => {
  2355. if (!playlist) return next("Playlist not found.");
  2356. const currentSongIndex = playlist.songs.length > 0 ? playlist.songs.length - 1 : 0;
  2357. return stationModel.updateOne(
  2358. { _id: stationId },
  2359. {
  2360. $set: {
  2361. privatePlaylist: playlistId,
  2362. currentSongIndex
  2363. }
  2364. },
  2365. { runValidators: true },
  2366. next
  2367. );
  2368. },
  2369. (res, next) => {
  2370. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2371. .then(station => next(null, station))
  2372. .catch(next);
  2373. }
  2374. ],
  2375. async (err, station) => {
  2376. if (err) {
  2377. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2378. this.log(
  2379. "ERROR",
  2380. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  2381. `Selecting private playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  2382. );
  2383. return cb({ status: "failure", message: err });
  2384. }
  2385. this.log(
  2386. "SUCCESS",
  2387. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  2388. `Selected private playlist "${playlistId}" for station "${stationId}" successfully.`
  2389. );
  2390. NotificationsModule.runJob("UNSCHEDULE", {
  2391. name: `stations.nextSong?id${stationId}`
  2392. });
  2393. if (!station.partyMode) StationsModule.runJob("SKIP_STATION", { stationId });
  2394. CacheModule.runJob("PUB", {
  2395. channel: "privatePlaylist.selected",
  2396. value: {
  2397. playlistId,
  2398. stationId
  2399. }
  2400. });
  2401. return cb({
  2402. status: "success",
  2403. message: "Successfully selected playlist."
  2404. });
  2405. }
  2406. );
  2407. }),
  2408. /**
  2409. * Deselects the private playlist selected in a station
  2410. *
  2411. * @param session
  2412. * @param stationId - the station id
  2413. * @param cb
  2414. */
  2415. deselectPrivatePlaylist: isOwnerRequired(async function deselectPrivatePlaylist(session, stationId, cb) {
  2416. const stationModel = await DBModule.runJob(
  2417. "GET_MODEL",
  2418. {
  2419. modelName: "station"
  2420. },
  2421. this
  2422. );
  2423. async.waterfall(
  2424. [
  2425. next => {
  2426. StationsModule.runJob("GET_STATION", { stationId }, this)
  2427. .then(station => {
  2428. next(null, station);
  2429. })
  2430. .catch(next);
  2431. },
  2432. (station, next) => {
  2433. if (!station) return next("Station not found.");
  2434. if (station.type !== "community") return next("Station is not a community station.");
  2435. if (!station.privatePlaylist) return next("No private playlist is currently selected.");
  2436. return stationModel.updateOne(
  2437. { _id: stationId },
  2438. {
  2439. $set: {
  2440. privatePlaylist: null,
  2441. currentSongIndex: 0
  2442. }
  2443. },
  2444. { runValidators: true },
  2445. next
  2446. );
  2447. },
  2448. (res, next) => {
  2449. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2450. .then(station => {
  2451. next(null, station);
  2452. })
  2453. .catch(next);
  2454. }
  2455. ],
  2456. async (err, station) => {
  2457. if (err) {
  2458. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2459. this.log(
  2460. "ERROR",
  2461. "STATIONS_DESELECT_PRIVATE_PLAYLIST",
  2462. `Deselecting private playlist for station "${stationId}" failed. "${err}"`
  2463. );
  2464. return cb({ status: "failure", message: err });
  2465. }
  2466. this.log(
  2467. "SUCCESS",
  2468. "STATIONS_DESELECT_PRIVATE_PLAYLIST",
  2469. `Deselected private playlist for station "${stationId}" successfully.`
  2470. );
  2471. NotificationsModule.runJob("UNSCHEDULE", {
  2472. name: `stations.nextSong?id${stationId}`
  2473. });
  2474. if (!station.partyMode) StationsModule.runJob("SKIP_STATION", { stationId });
  2475. CacheModule.runJob("PUB", {
  2476. channel: "privatePlaylist.deselected",
  2477. value: {
  2478. stationId
  2479. }
  2480. });
  2481. return cb({
  2482. status: "success",
  2483. message: "Successfully deselected playlist."
  2484. });
  2485. }
  2486. );
  2487. }),
  2488. favoriteStation: isLoginRequired(async function favoriteStation(session, stationId, cb) {
  2489. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2490. async.waterfall(
  2491. [
  2492. next => {
  2493. StationsModule.runJob("GET_STATION", { stationId }, this)
  2494. .then(station => next(null, station))
  2495. .catch(next);
  2496. },
  2497. (station, next) => {
  2498. if (!station) return next("Station not found.");
  2499. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  2500. .then(canView => {
  2501. if (canView) return next(null, station);
  2502. return next("Insufficient permissions.");
  2503. })
  2504. .catch(err => next(err));
  2505. },
  2506. (station, next) => {
  2507. userModel.updateOne(
  2508. { _id: session.userId },
  2509. { $addToSet: { favoriteStations: stationId } },
  2510. (err, res) => next(err, station, res)
  2511. );
  2512. },
  2513. (station, res, next) => {
  2514. if (res.nModified === 0) return next("The station was already favorited.");
  2515. return next(null, station);
  2516. }
  2517. ],
  2518. async (err, station) => {
  2519. if (err) {
  2520. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2521. this.log("ERROR", "FAVORITE_STATION", `Favoriting station "${stationId}" failed. "${err}"`);
  2522. return cb({ status: "failure", message: err });
  2523. }
  2524. this.log("SUCCESS", "FAVORITE_STATION", `Favorited station "${stationId}" successfully.`);
  2525. CacheModule.runJob("PUB", {
  2526. channel: "user.favoritedStation",
  2527. value: {
  2528. userId: session.userId,
  2529. stationId
  2530. }
  2531. });
  2532. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2533. userId: session.userId,
  2534. type: "station__favorite",
  2535. payload: {
  2536. message: `Favorited station <stationId>${station.displayName}</stationId>`,
  2537. stationId
  2538. }
  2539. });
  2540. return cb({
  2541. status: "success",
  2542. message: "Succesfully favorited station."
  2543. });
  2544. }
  2545. );
  2546. }),
  2547. unfavoriteStation: isLoginRequired(async function unfavoriteStation(session, stationId, cb) {
  2548. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2549. async.waterfall(
  2550. [
  2551. next => {
  2552. userModel.updateOne({ _id: session.userId }, { $pull: { favoriteStations: stationId } }, next);
  2553. },
  2554. (res, next) => {
  2555. if (res.nModified === 0) return next("The station wasn't favorited.");
  2556. return next();
  2557. },
  2558. next => {
  2559. StationsModule.runJob("GET_STATION", { stationId }, this)
  2560. .then(station => next(null, station))
  2561. .catch(next);
  2562. }
  2563. ],
  2564. async (err, station) => {
  2565. if (err) {
  2566. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2567. this.log("ERROR", "UNFAVORITE_STATION", `Unfavoriting station "${stationId}" failed. "${err}"`);
  2568. return cb({ status: "failure", message: err });
  2569. }
  2570. this.log("SUCCESS", "UNFAVORITE_STATION", `Unfavorited station "${stationId}" successfully.`);
  2571. CacheModule.runJob("PUB", {
  2572. channel: "user.unfavoritedStation",
  2573. value: {
  2574. userId: session.userId,
  2575. stationId
  2576. }
  2577. });
  2578. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2579. userId: session.userId,
  2580. type: "station__unfavorite",
  2581. payload: {
  2582. message: `Unfavorited station <stationId>${station.displayName}</stationId>`,
  2583. stationId
  2584. }
  2585. });
  2586. return cb({
  2587. status: "success",
  2588. message: "Succesfully unfavorited station."
  2589. });
  2590. }
  2591. );
  2592. })
  2593. };