stations.js 54 KB

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