stations.js 68 KB

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