stations.js 53 KB

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