stations.js 54 KB

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