stations.js 50 KB

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