stations.js 54 KB

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