stations.js 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116
  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. StationsModule.runJob("SKIP_STATION", { stationId });
  792. console.log("SUCCESS", "STATIONS_FORCE_SKIP", `Force skipped station "${stationId}" successfully.`);
  793. return cb({
  794. status: "success",
  795. message: "Successfully skipped station."
  796. });
  797. }
  798. );
  799. }),
  800. /**
  801. * Leaves the user's current station
  802. *
  803. * @param {object} session - user session
  804. * @param {string} stationId - id of station to leave
  805. * @param {Function} cb - callback
  806. */
  807. leave: (session, stationId, cb) => {
  808. async.waterfall(
  809. [
  810. next => {
  811. StationsModule.runJob("GET_STATION", { stationId })
  812. .then(station => {
  813. next(null, station);
  814. })
  815. .catch(next);
  816. },
  817. (station, next) => {
  818. if (!station) return next("Station not found.");
  819. return next();
  820. }
  821. ],
  822. async (err, userCount) => {
  823. if (err) {
  824. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  825. console.log("ERROR", "STATIONS_LEAVE", `Leaving station "${stationId}" failed. "${err}"`);
  826. return cb({ status: "failure", message: err });
  827. }
  828. console.log("SUCCESS", "STATIONS_LEAVE", `Left station "${stationId}" successfully.`);
  829. IOModule.runJob("SOCKET_LEAVE_ROOMS", { socketId: session });
  830. delete userList[session.socketId];
  831. return cb({
  832. status: "success",
  833. message: "Successfully left station.",
  834. userCount
  835. });
  836. }
  837. );
  838. },
  839. /**
  840. * Updates a station's name
  841. *
  842. * @param session
  843. * @param stationId - the station id
  844. * @param newName - the new station name
  845. * @param cb
  846. */
  847. updateName: isOwnerRequired(async (session, stationId, newName, cb) => {
  848. const stationModel = await DBModule.runJob("GET_MODEL", {
  849. modelName: "station"
  850. });
  851. async.waterfall(
  852. [
  853. next => {
  854. stationModel.updateOne(
  855. { _id: stationId },
  856. { $set: { name: newName } },
  857. { runValidators: true },
  858. next
  859. );
  860. },
  861. (res, next) => {
  862. StationsModule.runJob("UPDATE_STATION", { stationId })
  863. .then(station => {
  864. next(null, station);
  865. })
  866. .catch(next);
  867. }
  868. ],
  869. async err => {
  870. if (err) {
  871. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  872. console.log(
  873. "ERROR",
  874. "STATIONS_UPDATE_NAME",
  875. `Updating station "${stationId}" name to "${newName}" failed. "${err}"`
  876. );
  877. return cb({ status: "failure", message: err });
  878. }
  879. console.log(
  880. "SUCCESS",
  881. "STATIONS_UPDATE_NAME",
  882. `Updated station "${stationId}" name to "${newName}" successfully.`
  883. );
  884. return cb({
  885. status: "success",
  886. message: "Successfully updated the name."
  887. });
  888. }
  889. );
  890. }),
  891. /**
  892. * Updates a station's display name
  893. *
  894. * @param session
  895. * @param stationId - the station id
  896. * @param newDisplayName - the new station display name
  897. * @param cb
  898. */
  899. updateDisplayName: isOwnerRequired(async (session, stationId, newDisplayName, cb) => {
  900. const stationModel = await DBModule.runJob("GET_MODEL", {
  901. modelName: "station"
  902. });
  903. async.waterfall(
  904. [
  905. next => {
  906. stationModel.updateOne(
  907. { _id: stationId },
  908. { $set: { displayName: newDisplayName } },
  909. { runValidators: true },
  910. next
  911. );
  912. },
  913. (res, next) => {
  914. StationsModule.runJob("UPDATE_STATION", { stationId })
  915. .then(station => {
  916. next(null, station);
  917. })
  918. .catch(next);
  919. }
  920. ],
  921. async err => {
  922. if (err) {
  923. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  924. console.log(
  925. "ERROR",
  926. "STATIONS_UPDATE_DISPLAY_NAME",
  927. `Updating station "${stationId}" displayName to "${newDisplayName}" failed. "${err}"`
  928. );
  929. return cb({ status: "failure", message: err });
  930. }
  931. console.log(
  932. "SUCCESS",
  933. "STATIONS_UPDATE_DISPLAY_NAME",
  934. `Updated station "${stationId}" displayName to "${newDisplayName}" successfully.`
  935. );
  936. return cb({
  937. status: "success",
  938. message: "Successfully updated the display name."
  939. });
  940. }
  941. );
  942. }),
  943. /**
  944. * Updates a station's description
  945. *
  946. * @param session
  947. * @param stationId - the station id
  948. * @param newDescription - the new station description
  949. * @param cb
  950. */
  951. updateDescription: isOwnerRequired(async (session, stationId, newDescription, cb) => {
  952. const stationModel = await DBModule.runJob("GET_MODEL", {
  953. modelName: "station"
  954. });
  955. async.waterfall(
  956. [
  957. next => {
  958. stationModel.updateOne(
  959. { _id: stationId },
  960. { $set: { description: newDescription } },
  961. { runValidators: true },
  962. next
  963. );
  964. },
  965. (res, next) => {
  966. StationsModule.runJob("UPDATE_STATION", { stationId })
  967. .then(station => {
  968. next(null, station);
  969. })
  970. .catch(next);
  971. }
  972. ],
  973. async err => {
  974. if (err) {
  975. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  976. console.log(
  977. "ERROR",
  978. "STATIONS_UPDATE_DESCRIPTION",
  979. `Updating station "${stationId}" description to "${newDescription}" failed. "${err}"`
  980. );
  981. return cb({ status: "failure", message: err });
  982. }
  983. console.log(
  984. "SUCCESS",
  985. "STATIONS_UPDATE_DESCRIPTION",
  986. `Updated station "${stationId}" description to "${newDescription}" successfully.`
  987. );
  988. return cb({
  989. status: "success",
  990. message: "Successfully updated the description."
  991. });
  992. }
  993. );
  994. }),
  995. /**
  996. * Updates a station's privacy
  997. *
  998. * @param session
  999. * @param stationId - the station id
  1000. * @param newPrivacy - the new station privacy
  1001. * @param cb
  1002. */
  1003. updatePrivacy: isOwnerRequired(async (session, stationId, newPrivacy, cb) => {
  1004. const stationModel = await DBModule.runJob("GET_MODEL", {
  1005. modelName: "station"
  1006. });
  1007. async.waterfall(
  1008. [
  1009. next => {
  1010. stationModel.updateOne(
  1011. { _id: stationId },
  1012. { $set: { privacy: newPrivacy } },
  1013. { runValidators: true },
  1014. next
  1015. );
  1016. },
  1017. (res, next) => {
  1018. StationsModule.runJob("UPDATE_STATION", { stationId })
  1019. .then(station => {
  1020. next(null, station);
  1021. })
  1022. .catch(next);
  1023. }
  1024. ],
  1025. async err => {
  1026. if (err) {
  1027. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1028. console.log(
  1029. "ERROR",
  1030. "STATIONS_UPDATE_PRIVACY",
  1031. `Updating station "${stationId}" privacy to "${newPrivacy}" failed. "${err}"`
  1032. );
  1033. return cb({ status: "failure", message: err });
  1034. }
  1035. console.log(
  1036. "SUCCESS",
  1037. "STATIONS_UPDATE_PRIVACY",
  1038. `Updated station "${stationId}" privacy to "${newPrivacy}" successfully.`
  1039. );
  1040. return cb({
  1041. status: "success",
  1042. message: "Successfully updated the privacy."
  1043. });
  1044. }
  1045. );
  1046. }),
  1047. /**
  1048. * Updates a station's genres
  1049. *
  1050. * @param session
  1051. * @param stationId - the station id
  1052. * @param newGenres - the new station genres
  1053. * @param cb
  1054. */
  1055. updateGenres: isOwnerRequired(async (session, stationId, newGenres, cb) => {
  1056. const stationModel = await DBModule.runJob("GET_MODEL", {
  1057. modelName: "station"
  1058. });
  1059. async.waterfall(
  1060. [
  1061. next => {
  1062. stationModel.updateOne(
  1063. { _id: stationId },
  1064. { $set: { genres: newGenres } },
  1065. { runValidators: true },
  1066. next
  1067. );
  1068. },
  1069. (res, next) => {
  1070. StationsModule.runJob("UPDATE_STATION", { stationId })
  1071. .then(station => {
  1072. next(null, station);
  1073. })
  1074. .catch(next);
  1075. }
  1076. ],
  1077. async err => {
  1078. if (err) {
  1079. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1080. console.log(
  1081. "ERROR",
  1082. "STATIONS_UPDATE_GENRES",
  1083. `Updating station "${stationId}" genres to "${newGenres}" failed. "${err}"`
  1084. );
  1085. return cb({ status: "failure", message: err });
  1086. }
  1087. console.log(
  1088. "SUCCESS",
  1089. "STATIONS_UPDATE_GENRES",
  1090. `Updated station "${stationId}" genres to "${newGenres}" successfully.`
  1091. );
  1092. return cb({
  1093. status: "success",
  1094. message: "Successfully updated the genres."
  1095. });
  1096. }
  1097. );
  1098. }),
  1099. /**
  1100. * Updates a station's blacklisted genres
  1101. *
  1102. * @param session
  1103. * @param stationId - the station id
  1104. * @param newBlacklistedGenres - the new station blacklisted genres
  1105. * @param cb
  1106. */
  1107. updateBlacklistedGenres: isOwnerRequired(async (session, stationId, newBlacklistedGenres, cb) => {
  1108. const stationModel = await DBModule.runJob("GET_MODEL", {
  1109. modelName: "station"
  1110. });
  1111. async.waterfall(
  1112. [
  1113. next => {
  1114. stationModel.updateOne(
  1115. { _id: stationId },
  1116. {
  1117. $set: {
  1118. blacklistedGenres: newBlacklistedGenres
  1119. }
  1120. },
  1121. { runValidators: true },
  1122. next
  1123. );
  1124. },
  1125. (res, next) => {
  1126. StationsModule.runJob("UPDATE_STATION", { stationId })
  1127. .then(station => {
  1128. next(null, station);
  1129. })
  1130. .catch(next);
  1131. }
  1132. ],
  1133. async err => {
  1134. if (err) {
  1135. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1136. console.log(
  1137. "ERROR",
  1138. "STATIONS_UPDATE_BLACKLISTED_GENRES",
  1139. `Updating station "${stationId}" blacklisted genres to "${newBlacklistedGenres}" failed. "${err}"`
  1140. );
  1141. return cb({ status: "failure", message: err });
  1142. }
  1143. console.log(
  1144. "SUCCESS",
  1145. "STATIONS_UPDATE_BLACKLISTED_GENRES",
  1146. `Updated station "${stationId}" blacklisted genres to "${newBlacklistedGenres}" successfully.`
  1147. );
  1148. return cb({
  1149. status: "success",
  1150. message: "Successfully updated the blacklisted genres."
  1151. });
  1152. }
  1153. );
  1154. }),
  1155. /**
  1156. * Updates a station's party mode
  1157. *
  1158. * @param session
  1159. * @param stationId - the station id
  1160. * @param newPartyMode - the new station party mode
  1161. * @param cb
  1162. */
  1163. updatePartyMode: isOwnerRequired(async (session, stationId, newPartyMode, cb) => {
  1164. const stationModel = await DBModule.runJob("GET_MODEL", {
  1165. modelName: "station"
  1166. });
  1167. async.waterfall(
  1168. [
  1169. next => {
  1170. StationsModule.runJob("GET_STATION", { stationId })
  1171. .then(station => {
  1172. next(null, station);
  1173. })
  1174. .catch(next);
  1175. },
  1176. (station, next) => {
  1177. if (!station) return next("Station not found.");
  1178. if (station.partyMode === newPartyMode)
  1179. return next(`The party mode was already ${newPartyMode ? "enabled." : "disabled."}`);
  1180. return stationModel.updateOne(
  1181. { _id: stationId },
  1182. { $set: { partyMode: newPartyMode } },
  1183. { runValidators: true },
  1184. next
  1185. );
  1186. },
  1187. (res, next) => {
  1188. StationsModule.runJob("UPDATE_STATION", { stationId })
  1189. .then(station => {
  1190. next(null, station);
  1191. })
  1192. .catch(next);
  1193. }
  1194. ],
  1195. async err => {
  1196. if (err) {
  1197. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1198. console.log(
  1199. "ERROR",
  1200. "STATIONS_UPDATE_PARTY_MODE",
  1201. `Updating station "${stationId}" party mode to "${newPartyMode}" failed. "${err}"`
  1202. );
  1203. return cb({ status: "failure", message: err });
  1204. }
  1205. console.log(
  1206. "SUCCESS",
  1207. "STATIONS_UPDATE_PARTY_MODE",
  1208. `Updated station "${stationId}" party mode to "${newPartyMode}" successfully.`
  1209. );
  1210. CacheModule.runJob("PUB", {
  1211. channel: "station.updatePartyMode",
  1212. value: {
  1213. stationId,
  1214. partyMode: newPartyMode
  1215. }
  1216. });
  1217. StationsModule.runJob("SKIP_STATION", { stationId });
  1218. return cb({
  1219. status: "success",
  1220. message: "Successfully updated the party mode."
  1221. });
  1222. }
  1223. );
  1224. }),
  1225. /**
  1226. * Pauses a station
  1227. *
  1228. * @param session
  1229. * @param stationId - the station id
  1230. * @param cb
  1231. */
  1232. pause: isOwnerRequired(async (session, stationId, cb) => {
  1233. const stationModel = await DBModule.runJob("GET_MODEL", {
  1234. modelName: "station"
  1235. });
  1236. async.waterfall(
  1237. [
  1238. next => {
  1239. StationsModule.runJob("GET_STATION", { stationId })
  1240. .then(station => {
  1241. next(null, station);
  1242. })
  1243. .catch(next);
  1244. },
  1245. (station, next) => {
  1246. if (!station) return next("Station not found.");
  1247. if (station.paused) return next("That station was already paused.");
  1248. return stationModel.updateOne(
  1249. { _id: stationId },
  1250. { $set: { paused: true, pausedAt: Date.now() } },
  1251. next
  1252. );
  1253. },
  1254. (res, next) => {
  1255. StationsModule.runJob("UPDATE_STATION", { stationId })
  1256. .then(station => {
  1257. next(null, station);
  1258. })
  1259. .catch(next);
  1260. }
  1261. ],
  1262. async err => {
  1263. if (err) {
  1264. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1265. console.log("ERROR", "STATIONS_PAUSE", `Pausing station "${stationId}" failed. "${err}"`);
  1266. return cb({ status: "failure", message: err });
  1267. }
  1268. console.log("SUCCESS", "STATIONS_PAUSE", `Paused station "${stationId}" successfully.`);
  1269. CacheModule.runJob("PUB", {
  1270. channel: "station.pause",
  1271. value: stationId
  1272. });
  1273. NotificationsModule.runJob("UNSCHEDULE", {
  1274. name: `stations.nextSong?id=${stationId}`
  1275. });
  1276. return cb({
  1277. status: "success",
  1278. message: "Successfully paused."
  1279. });
  1280. }
  1281. );
  1282. }),
  1283. /**
  1284. * Resumes a station
  1285. *
  1286. * @param session
  1287. * @param stationId - the station id
  1288. * @param cb
  1289. */
  1290. resume: isOwnerRequired(async (session, stationId, cb) => {
  1291. const stationModel = await DBModule.runJob("GET_MODEL", {
  1292. modelName: "station"
  1293. });
  1294. async.waterfall(
  1295. [
  1296. next => {
  1297. StationsModule.runJob("GET_STATION", { stationId })
  1298. .then(station => {
  1299. next(null, station);
  1300. })
  1301. .catch(next);
  1302. },
  1303. (station, next) => {
  1304. if (!station) return next("Station not found.");
  1305. if (!station.paused) return next("That station is not paused.");
  1306. station.timePaused += Date.now() - station.pausedAt;
  1307. return stationModel.updateOne(
  1308. { _id: stationId },
  1309. {
  1310. $set: { paused: false },
  1311. $inc: { timePaused: Date.now() - station.pausedAt }
  1312. },
  1313. next
  1314. );
  1315. },
  1316. (res, next) => {
  1317. StationsModule.runJob("UPDATE_STATION", { stationId })
  1318. .then(station => {
  1319. next(null, station);
  1320. })
  1321. .catch(next);
  1322. }
  1323. ],
  1324. async err => {
  1325. if (err) {
  1326. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1327. console.log("ERROR", "STATIONS_RESUME", `Resuming station "${stationId}" failed. "${err}"`);
  1328. return cb({ status: "failure", message: err });
  1329. }
  1330. console.log("SUCCESS", "STATIONS_RESUME", `Resuming station "${stationId}" successfully.`);
  1331. CacheModule.runJob("PUB", {
  1332. channel: "station.resume",
  1333. value: stationId
  1334. });
  1335. return cb({
  1336. status: "success",
  1337. message: "Successfully resumed."
  1338. });
  1339. }
  1340. );
  1341. }),
  1342. /**
  1343. * Removes a station
  1344. *
  1345. * @param session
  1346. * @param stationId - the station id
  1347. * @param cb
  1348. */
  1349. remove: isOwnerRequired(async (session, stationId, cb) => {
  1350. const stationModel = await DBModule.runJob("GET_MODEL", {
  1351. modelName: "station"
  1352. });
  1353. async.waterfall(
  1354. [
  1355. next => {
  1356. stationModel.deleteOne({ _id: stationId }, err => next(err));
  1357. },
  1358. next => {
  1359. CacheModule.runJob("HDEL", { table: "stations", key: stationId }).then(next).catch(next);
  1360. }
  1361. ],
  1362. async err => {
  1363. if (err) {
  1364. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1365. console.log("ERROR", "STATIONS_REMOVE", `Removing station "${stationId}" failed. "${err}"`);
  1366. return cb({ status: "failure", message: err });
  1367. }
  1368. console.log("SUCCESS", "STATIONS_REMOVE", `Removing station "${stationId}" successfully.`);
  1369. CacheModule.runJob("PUB", {
  1370. channel: "station.remove",
  1371. value: stationId
  1372. });
  1373. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1374. userId: session.userId,
  1375. activityType: "deleted_station",
  1376. payload: [stationId]
  1377. });
  1378. return cb({
  1379. status: "success",
  1380. message: "Successfully removed."
  1381. });
  1382. }
  1383. );
  1384. }),
  1385. /**
  1386. * Create a station
  1387. *
  1388. * @param session
  1389. * @param data - the station data
  1390. * @param cb
  1391. */
  1392. create: isLoginRequired(async (session, data, cb) => {
  1393. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" });
  1394. const stationModel = await DBModule.runJob("GET_MODEL", {
  1395. modelName: "station"
  1396. });
  1397. data.name = data.name.toLowerCase();
  1398. const blacklist = [
  1399. "country",
  1400. "edm",
  1401. "musare",
  1402. "hip-hop",
  1403. "rap",
  1404. "top-hits",
  1405. "todays-hits",
  1406. "old-school",
  1407. "christmas",
  1408. "about",
  1409. "support",
  1410. "staff",
  1411. "help",
  1412. "news",
  1413. "terms",
  1414. "privacy",
  1415. "profile",
  1416. "c",
  1417. "community",
  1418. "tos",
  1419. "login",
  1420. "register",
  1421. "p",
  1422. "official",
  1423. "o",
  1424. "trap",
  1425. "faq",
  1426. "team",
  1427. "donate",
  1428. "buy",
  1429. "shop",
  1430. "forums",
  1431. "explore",
  1432. "settings",
  1433. "admin",
  1434. "auth",
  1435. "reset_password"
  1436. ];
  1437. async.waterfall(
  1438. [
  1439. next => {
  1440. if (!data) return next("Invalid data.");
  1441. return next();
  1442. },
  1443. next => {
  1444. stationModel.findOne(
  1445. {
  1446. $or: [
  1447. { name: data.name },
  1448. {
  1449. displayName: new RegExp(`^${data.displayName}$`, "i")
  1450. }
  1451. ]
  1452. },
  1453. next
  1454. );
  1455. },
  1456. // eslint-disable-next-line consistent-return
  1457. (station, next) => {
  1458. console.log(station);
  1459. if (station) return next("A station with that name or display name already exists.");
  1460. const { name, displayName, description, genres, playlist, type, blacklistedGenres } = data;
  1461. if (type === "official") {
  1462. return userModel.findOne({ _id: session.userId }, (err, user) => {
  1463. if (err) return next(err);
  1464. if (!user) return next("User not found.");
  1465. if (user.role !== "admin") return next("Admin required.");
  1466. return stationModel.create(
  1467. {
  1468. name,
  1469. displayName,
  1470. description,
  1471. type,
  1472. privacy: "private",
  1473. playlist,
  1474. genres,
  1475. blacklistedGenres,
  1476. currentSong: StationsModule.defaultSong
  1477. },
  1478. next
  1479. );
  1480. });
  1481. }
  1482. if (type === "community") {
  1483. if (blacklist.indexOf(name) !== -1)
  1484. return next("That name is blacklisted. Please use a different name.");
  1485. return stationModel.create(
  1486. {
  1487. name,
  1488. displayName,
  1489. description,
  1490. type,
  1491. privacy: "private",
  1492. owner: session.userId,
  1493. queue: [],
  1494. currentSong: null
  1495. },
  1496. next
  1497. );
  1498. }
  1499. }
  1500. ],
  1501. async (err, station) => {
  1502. if (err) {
  1503. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1504. console.log("ERROR", "STATIONS_CREATE", `Creating station failed. "${err}"`);
  1505. return cb({ status: "failure", message: err });
  1506. }
  1507. console.log("SUCCESS", "STATIONS_CREATE", `Created station "${station._id}" successfully.`);
  1508. CacheModule.runJob("PUB", {
  1509. channel: "station.create",
  1510. value: station._id
  1511. });
  1512. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1513. userId: session.userId,
  1514. activityType: "created_station",
  1515. payload: [station._id]
  1516. });
  1517. return cb({
  1518. status: "success",
  1519. message: "Successfully created station."
  1520. });
  1521. }
  1522. );
  1523. }),
  1524. /**
  1525. * Adds song to station queue
  1526. *
  1527. * @param session
  1528. * @param stationId - the station id
  1529. * @param songId - the song id
  1530. * @param cb
  1531. */
  1532. addToQueue: isLoginRequired(async (session, stationId, songId, cb) => {
  1533. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" });
  1534. const stationModel = await DBModule.runJob("GET_MODEL", {
  1535. modelName: "station"
  1536. });
  1537. async.waterfall(
  1538. [
  1539. next => {
  1540. StationsModule.runJob("GET_STATION", { stationId })
  1541. .then(station => {
  1542. next(null, station);
  1543. })
  1544. .catch(next);
  1545. },
  1546. (station, next) => {
  1547. if (!station) return next("Station not found.");
  1548. if (station.locked) {
  1549. return userModel.findOne({ _id: session.userId }, (err, user) => {
  1550. if (user.role !== "admin" && station.owner !== session.userId)
  1551. return next("Only owners and admins can add songs to a locked queue.");
  1552. return next(null, station);
  1553. });
  1554. }
  1555. return next(null, station);
  1556. },
  1557. (station, next) => {
  1558. if (station.type !== "community") return next("That station is not a community station.");
  1559. return StationsModule.runJob("CAN_USER_VIEW_STATION", {
  1560. station,
  1561. userId: session.userId
  1562. })
  1563. .then(canView => {
  1564. if (canView) return next(null, station);
  1565. return next("Insufficient permissions.");
  1566. })
  1567. .catch(err => next(err));
  1568. },
  1569. (station, next) => {
  1570. if (station.currentSong && station.currentSong.songId === songId)
  1571. return next("That song is currently playing.");
  1572. return async.each(
  1573. station.queue,
  1574. (queueSong, next) => {
  1575. if (queueSong.songId === songId) return next("That song is already in the queue.");
  1576. return next();
  1577. },
  1578. err => next(err, station)
  1579. );
  1580. },
  1581. (station, next) => {
  1582. SongsModule.runJob("GET_SONG_FROM_ID", { songId })
  1583. .then(res => {
  1584. if (res.song) return next(null, res.song, station);
  1585. return YouTubeModule.runJob("GET_SONG", { songId })
  1586. .then(response => {
  1587. const { song } = response;
  1588. song.artists = [];
  1589. song.skipDuration = 0;
  1590. song.likes = -1;
  1591. song.dislikes = -1;
  1592. song.thumbnail = "empty";
  1593. song.explicit = false;
  1594. return next(null, song, station);
  1595. })
  1596. .catch(err => next(err));
  1597. })
  1598. .catch(err => next(err));
  1599. },
  1600. (song, station, next) => {
  1601. const { queue } = station;
  1602. song.requestedBy = session.userId;
  1603. queue.push(song);
  1604. let totalDuration = 0;
  1605. queue.forEach(song => {
  1606. totalDuration += song.duration;
  1607. });
  1608. if (totalDuration >= 3600 * 3) return next("The max length of the queue is 3 hours.");
  1609. return next(null, song, station);
  1610. },
  1611. (song, station, next) => {
  1612. const { queue } = station;
  1613. if (queue.length === 0) return next(null, song, station);
  1614. let totalDuration = 0;
  1615. const userId = queue[queue.length - 1].requestedBy;
  1616. station.queue.forEach(song => {
  1617. if (userId === song.requestedBy) {
  1618. totalDuration += song.duration;
  1619. }
  1620. });
  1621. if (totalDuration >= 900) return next("The max length of songs per user is 15 minutes.");
  1622. return next(null, song, station);
  1623. },
  1624. (song, station, next) => {
  1625. const { queue } = station;
  1626. if (queue.length === 0) return next(null, song);
  1627. let totalSongs = 0;
  1628. const userId = queue[queue.length - 1].requestedBy;
  1629. queue.forEach(song => {
  1630. if (userId === song.requestedBy) {
  1631. totalSongs += 1;
  1632. }
  1633. });
  1634. if (totalSongs <= 2) return next(null, song);
  1635. if (totalSongs > 3)
  1636. return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1637. if (queue[queue.length - 2].requestedBy !== userId || queue[queue.length - 3] !== userId)
  1638. return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1639. return next(null, song);
  1640. },
  1641. (song, next) => {
  1642. stationModel.updateOne(
  1643. { _id: stationId },
  1644. { $push: { queue: song } },
  1645. { runValidators: true },
  1646. next
  1647. );
  1648. },
  1649. (res, next) => {
  1650. StationsModule.runJob("UPDATE_STATION", { stationId })
  1651. .then(station => {
  1652. next(null, station);
  1653. })
  1654. .catch(next);
  1655. }
  1656. ],
  1657. async err => {
  1658. if (err) {
  1659. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1660. console.log(
  1661. "ERROR",
  1662. "STATIONS_ADD_SONG_TO_QUEUE",
  1663. `Adding song "${songId}" to station "${stationId}" queue failed. "${err}"`
  1664. );
  1665. return cb({ status: "failure", message: err });
  1666. }
  1667. console.log(
  1668. "SUCCESS",
  1669. "STATIONS_ADD_SONG_TO_QUEUE",
  1670. `Added song "${songId}" to station "${stationId}" successfully.`
  1671. );
  1672. CacheModule.runJob("PUB", {
  1673. channel: "station.queueUpdate",
  1674. value: stationId
  1675. });
  1676. return cb({
  1677. status: "success",
  1678. message: "Successfully added song to queue."
  1679. });
  1680. }
  1681. );
  1682. }),
  1683. /**
  1684. * Removes song from station queue
  1685. *
  1686. * @param session
  1687. * @param stationId - the station id
  1688. * @param songId - the song id
  1689. * @param cb
  1690. */
  1691. removeFromQueue: isOwnerRequired(async (session, stationId, songId, cb) => {
  1692. const stationModel = await DBModule.runJob("GET_MODEL", {
  1693. modelName: "station"
  1694. });
  1695. async.waterfall(
  1696. [
  1697. next => {
  1698. if (!songId) return next("Invalid song id.");
  1699. return StationsModule.runJob("GET_STATION", { stationId })
  1700. .then(station => {
  1701. next(null, station);
  1702. })
  1703. .catch(next);
  1704. },
  1705. (station, next) => {
  1706. if (!station) return next("Station not found.");
  1707. if (station.type !== "community") return next("Station is not a community station.");
  1708. return async.each(
  1709. station.queue,
  1710. (queueSong, next) => {
  1711. if (queueSong.songId === songId) return next(true);
  1712. return next();
  1713. },
  1714. err => {
  1715. if (err === true) return next();
  1716. return next("Song is not currently in the queue.");
  1717. }
  1718. );
  1719. },
  1720. next => {
  1721. stationModel.updateOne({ _id: stationId }, { $pull: { queue: { songId } } }, next);
  1722. },
  1723. (res, next) => {
  1724. StationsModule.runJob("UPDATE_STATION", { stationId })
  1725. .then(station => {
  1726. next(null, station);
  1727. })
  1728. .catch(next);
  1729. }
  1730. ],
  1731. async err => {
  1732. if (err) {
  1733. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1734. console.log(
  1735. "ERROR",
  1736. "STATIONS_REMOVE_SONG_TO_QUEUE",
  1737. `Removing song "${songId}" from station "${stationId}" queue failed. "${err}"`
  1738. );
  1739. return cb({ status: "failure", message: err });
  1740. }
  1741. console.log(
  1742. "SUCCESS",
  1743. "STATIONS_REMOVE_SONG_TO_QUEUE",
  1744. `Removed song "${songId}" from station "${stationId}" successfully.`
  1745. );
  1746. CacheModule.runJob("PUB", {
  1747. channel: "station.queueUpdate",
  1748. value: stationId
  1749. });
  1750. return cb({
  1751. status: "success",
  1752. message: "Successfully removed song from queue."
  1753. });
  1754. }
  1755. );
  1756. }),
  1757. /**
  1758. * Gets the queue from a station
  1759. *
  1760. * @param {object} session - user session
  1761. * @param {string} stationId - the station id
  1762. * @param {Function} cb - callback
  1763. */
  1764. getQueue: (session, stationId, cb) => {
  1765. async.waterfall(
  1766. [
  1767. next => {
  1768. StationsModule.runJob("GET_STATION", { stationId })
  1769. .then(station => {
  1770. next(null, station);
  1771. })
  1772. .catch(next);
  1773. },
  1774. (station, next) => {
  1775. if (!station) return next("Station not found.");
  1776. if (station.type !== "community") return next("Station is not a community station.");
  1777. return next(null, station);
  1778. },
  1779. (station, next) => {
  1780. StationsModule.runJob("CAN_USER_VIEW_STATION", {
  1781. station,
  1782. userId: session.userId
  1783. })
  1784. .then(canView => {
  1785. if (canView) return next(null, station);
  1786. return next("Insufficient permissions.");
  1787. })
  1788. .catch(err => next(err));
  1789. }
  1790. ],
  1791. async (err, station) => {
  1792. if (err) {
  1793. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1794. console.log(
  1795. "ERROR",
  1796. "STATIONS_GET_QUEUE",
  1797. `Getting queue for station "${stationId}" failed. "${err}"`
  1798. );
  1799. return cb({ status: "failure", message: err });
  1800. }
  1801. console.log("SUCCESS", "STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  1802. return cb({
  1803. status: "success",
  1804. message: "Successfully got queue.",
  1805. queue: station.queue
  1806. });
  1807. }
  1808. );
  1809. },
  1810. /**
  1811. * Selects a private playlist for a station
  1812. *
  1813. * @param session
  1814. * @param stationId - the station id
  1815. * @param playlistId - the private playlist id
  1816. * @param cb
  1817. */
  1818. selectPrivatePlaylist: isOwnerRequired(async (session, stationId, playlistId, cb) => {
  1819. const stationModel = await DBModule.runJob("GET_MODEL", {
  1820. modelName: "station"
  1821. });
  1822. const playlistModel = await DBModule.runJob("GET_MODEL", {
  1823. modelName: "playlist"
  1824. });
  1825. async.waterfall(
  1826. [
  1827. next => {
  1828. StationsModule.runJob("GET_STATION", { stationId })
  1829. .then(station => {
  1830. next(null, station);
  1831. })
  1832. .catch(next);
  1833. },
  1834. (station, next) => {
  1835. if (!station) return next("Station not found.");
  1836. if (station.type !== "community") return next("Station is not a community station.");
  1837. if (station.privatePlaylist === playlistId)
  1838. return next("That private playlist is already selected.");
  1839. return playlistModel.findOne({ _id: playlistId }, next);
  1840. },
  1841. (playlist, next) => {
  1842. if (!playlist) return next("Playlist not found.");
  1843. const currentSongIndex = playlist.songs.length > 0 ? playlist.songs.length - 1 : 0;
  1844. return stationModel.updateOne(
  1845. { _id: stationId },
  1846. {
  1847. $set: {
  1848. privatePlaylist: playlistId,
  1849. currentSongIndex
  1850. }
  1851. },
  1852. { runValidators: true },
  1853. next
  1854. );
  1855. },
  1856. (res, next) => {
  1857. StationsModule.runJob("UPDATE_STATION", { stationId })
  1858. .then(station => {
  1859. next(null, station);
  1860. })
  1861. .catch(next);
  1862. }
  1863. ],
  1864. async (err, station) => {
  1865. if (err) {
  1866. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1867. console.log(
  1868. "ERROR",
  1869. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  1870. `Selecting private playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  1871. );
  1872. return cb({ status: "failure", message: err });
  1873. }
  1874. console.log(
  1875. "SUCCESS",
  1876. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  1877. `Selected private playlist "${playlistId}" for station "${stationId}" successfully.`
  1878. );
  1879. NotificationsModule.runJob("UNSCHEDULE", {
  1880. name: `stations.nextSong?id${stationId}`
  1881. });
  1882. if (!station.partyMode) StationsModule.runJob("SKIP_STATION", { stationId });
  1883. CacheModule.runJob("PUB", {
  1884. channel: "privatePlaylist.selected",
  1885. value: {
  1886. playlistId,
  1887. stationId
  1888. }
  1889. });
  1890. return cb({
  1891. status: "success",
  1892. message: "Successfully selected playlist."
  1893. });
  1894. }
  1895. );
  1896. }),
  1897. favoriteStation: isLoginRequired(async (session, stationId, cb) => {
  1898. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" });
  1899. async.waterfall(
  1900. [
  1901. next => {
  1902. StationsModule.runJob("GET_STATION", { stationId })
  1903. .then(station => {
  1904. next(null, station);
  1905. })
  1906. .catch(next);
  1907. },
  1908. (station, next) => {
  1909. if (!station) return next("Station not found.");
  1910. return StationsModule.runJob("CAN_USER_VIEW_STATION", {
  1911. station,
  1912. userId: session.userId
  1913. })
  1914. .then(canView => {
  1915. if (canView) return next();
  1916. return next("Insufficient permissions.");
  1917. })
  1918. .catch(err => next(err));
  1919. },
  1920. next => {
  1921. userModel.updateOne({ _id: session.userId }, { $addToSet: { favoriteStations: stationId } }, next);
  1922. },
  1923. (res, next) => {
  1924. if (res.nModified === 0) return next("The station was already favorited.");
  1925. return next();
  1926. }
  1927. ],
  1928. async err => {
  1929. if (err) {
  1930. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1931. console.log("ERROR", "FAVORITE_STATION", `Favoriting station "${stationId}" failed. "${err}"`);
  1932. return cb({ status: "failure", message: err });
  1933. }
  1934. console.log("SUCCESS", "FAVORITE_STATION", `Favorited station "${stationId}" successfully.`);
  1935. CacheModule.runJob("PUB", {
  1936. channel: "user.favoritedStation",
  1937. value: {
  1938. userId: session.userId,
  1939. stationId
  1940. }
  1941. });
  1942. return cb({
  1943. status: "success",
  1944. message: "Succesfully favorited station."
  1945. });
  1946. }
  1947. );
  1948. }),
  1949. unfavoriteStation: isLoginRequired(async (session, stationId, cb) => {
  1950. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" });
  1951. async.waterfall(
  1952. [
  1953. next => {
  1954. userModel.updateOne({ _id: session.userId }, { $pull: { favoriteStations: stationId } }, next);
  1955. },
  1956. (res, next) => {
  1957. if (res.nModified === 0) return next("The station wasn't favorited.");
  1958. return next();
  1959. }
  1960. ],
  1961. async err => {
  1962. if (err) {
  1963. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  1964. console.log("ERROR", "UNFAVORITE_STATION", `Unfavoriting station "${stationId}" failed. "${err}"`);
  1965. return cb({ status: "failure", message: err });
  1966. }
  1967. console.log("SUCCESS", "UNFAVORITE_STATION", `Unfavorited station "${stationId}" successfully.`);
  1968. CacheModule.runJob("PUB", {
  1969. channel: "user.unfavoritedStation",
  1970. value: {
  1971. userId: session.userId,
  1972. stationId
  1973. }
  1974. });
  1975. return cb({
  1976. status: "success",
  1977. message: "Succesfully unfavorited station."
  1978. });
  1979. }
  1980. );
  1981. })
  1982. };