stations.js 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090
  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_SKIP_VOTES(payload) {
  713. return new Promise((resolve, reject) => {
  714. StationsModule.log("INFO", `Processing skip votes 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. if (session && session.userId)
  963. StationsModule.runJob(
  964. "CAN_USER_VIEW_STATION",
  965. { station, userId: session.userId },
  966. this
  967. )
  968. .then(canView => {
  969. if (canView)
  970. socket.dispatch("event:station.nextSong", {
  971. data: {
  972. stationId: station._id,
  973. currentSong
  974. }
  975. });
  976. })
  977. .catch(() => {});
  978. }
  979. );
  980. }
  981. });
  982. }
  983. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }).then(sockets => {
  984. if (station.currentSong !== null && station.currentSong.youtubeId !== undefined) {
  985. WSModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  986. sockets,
  987. room: `song.${station.currentSong.youtubeId}`
  988. });
  989. if (!station.paused) {
  990. NotificationsModule.runJob("SCHEDULE", {
  991. name: `stations.nextSong?id=${station._id}`,
  992. time: station.currentSong.duration * 1000,
  993. station
  994. });
  995. }
  996. } else WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", { sockets });
  997. });
  998. return resolve({ station });
  999. }
  1000. );
  1001. });
  1002. }
  1003. /**
  1004. * Checks if a user can view/access a station
  1005. *
  1006. * @param {object} payload - object that contains the payload
  1007. * @param {object} payload.station - the station object of the station in question
  1008. * @param {string} payload.userId - the id of the user in question
  1009. * @returns {Promise} - returns a promise (resolve, reject)
  1010. */
  1011. CAN_USER_VIEW_STATION(payload) {
  1012. return new Promise((resolve, reject) => {
  1013. async.waterfall(
  1014. [
  1015. next => {
  1016. if (payload.station.privacy === "public" || payload.station.privacy === "unlisted")
  1017. return next(true);
  1018. if (!payload.userId) return next("Not allowed");
  1019. return next();
  1020. },
  1021. next => {
  1022. hasPermission("stations.view", payload.userId, payload.station._id)
  1023. .then(() => next(true))
  1024. .catch(() => next("Not allowed"));
  1025. }
  1026. ],
  1027. async errOrResult => {
  1028. if (errOrResult !== true && errOrResult !== "Not allowed") {
  1029. errOrResult = await UtilsModule.runJob(
  1030. "GET_ERROR",
  1031. {
  1032. error: errOrResult
  1033. },
  1034. this
  1035. );
  1036. reject(new Error(errOrResult));
  1037. } else {
  1038. resolve(errOrResult === true);
  1039. }
  1040. }
  1041. );
  1042. });
  1043. }
  1044. /**
  1045. * Checks if a user has favorited a station or not
  1046. *
  1047. * @param {object} payload - object that contains the payload
  1048. * @param {object} payload.stationId - the id of the station in question
  1049. * @param {string} payload.userId - the id of the user in question
  1050. * @returns {Promise} - returns a promise (resolve, reject)
  1051. */
  1052. HAS_USER_FAVORITED_STATION(payload) {
  1053. return new Promise((resolve, reject) => {
  1054. async.waterfall(
  1055. [
  1056. next => {
  1057. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1058. userModel.findOne({ _id: payload.userId }, next);
  1059. });
  1060. },
  1061. (user, next) => {
  1062. if (!user) return next("User not found.");
  1063. if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
  1064. return next(null, false);
  1065. }
  1066. ],
  1067. async (err, isStationFavorited) => {
  1068. if (err && err !== true) {
  1069. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1070. return reject(new Error(err));
  1071. }
  1072. return resolve(isStationFavorited);
  1073. }
  1074. );
  1075. });
  1076. }
  1077. /**
  1078. * Returns a list of sockets in a room that can and can't know about a station
  1079. *
  1080. * @param {object} payload - the payload object
  1081. * @param {object} payload.station - the station object
  1082. * @param {string} payload.room - the websockets room to get the sockets from
  1083. * @returns {Promise} - returns a promise (resolve, reject)
  1084. */
  1085. GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION(payload) {
  1086. return new Promise((resolve, reject) => {
  1087. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: payload.room }, this)
  1088. .then(socketIds => {
  1089. const sockets = [];
  1090. async.eachLimit(
  1091. socketIds,
  1092. 1,
  1093. (socketId, next) => {
  1094. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  1095. .then(socket => {
  1096. if (socket) sockets.push(socket);
  1097. next();
  1098. })
  1099. .catch(err => {
  1100. reject(err);
  1101. });
  1102. },
  1103. err => {
  1104. if (err) reject(err);
  1105. else {
  1106. let socketsThatCan = [];
  1107. const socketsThatCannot = [];
  1108. if (payload.station.privacy === "public") {
  1109. socketsThatCan = sockets;
  1110. resolve({ socketsThatCan, socketsThatCannot });
  1111. } else {
  1112. async.eachLimit(
  1113. sockets,
  1114. 1,
  1115. (socket, next) => {
  1116. if (!(socket.session && socket.session.sessionId)) {
  1117. socketsThatCannot.push(socket);
  1118. next();
  1119. } else
  1120. hasPermission("stations.view", socket.session, payload.station._id)
  1121. .then(() => {
  1122. socketsThatCan.push(socket);
  1123. next();
  1124. })
  1125. .catch(() => {
  1126. socketsThatCannot.push(socket);
  1127. next();
  1128. });
  1129. },
  1130. err => {
  1131. if (err) reject(err);
  1132. else resolve({ socketsThatCan, socketsThatCannot });
  1133. }
  1134. );
  1135. }
  1136. }
  1137. }
  1138. );
  1139. })
  1140. .catch(reject);
  1141. });
  1142. }
  1143. /**
  1144. * Adds a playlist to autofill a station
  1145. *
  1146. * @param {object} payload - object that contains the payload
  1147. * @param {object} payload.stationId - the id of the station
  1148. * @param {object} payload.playlistId - the id of the playlist
  1149. * @returns {Promise} - returns a promise (resolve, reject)
  1150. */
  1151. AUTOFILL_PLAYLIST(payload) {
  1152. return new Promise((resolve, reject) => {
  1153. async.waterfall(
  1154. [
  1155. next => {
  1156. if (!payload.stationId) next("Please specify a station id");
  1157. else if (!payload.playlistId) next("Please specify a playlist id");
  1158. else next();
  1159. },
  1160. next => {
  1161. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1162. .then(station => {
  1163. next(null, station);
  1164. })
  1165. .catch(next);
  1166. },
  1167. (station, next) => {
  1168. if (station.playlist === payload.playlistId) next("You cannot autofill the station playlist");
  1169. else if (station.autofill.playlists.indexOf(payload.playlistId) !== -1)
  1170. next("This playlist is already autofilling");
  1171. else if (station.blacklist.indexOf(payload.playlistId) !== -1)
  1172. next("This playlist is currently blacklisted");
  1173. else
  1174. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1175. .then(() => {
  1176. next(null);
  1177. })
  1178. .catch(next);
  1179. },
  1180. next => {
  1181. StationsModule.stationModel.updateOne(
  1182. { _id: payload.stationId },
  1183. { $push: { "autofill.playlists": payload.playlistId } },
  1184. next
  1185. );
  1186. },
  1187. (res, next) => {
  1188. StationsModule.runJob(
  1189. "UPDATE_STATION",
  1190. {
  1191. stationId: payload.stationId
  1192. },
  1193. this
  1194. )
  1195. .then(() => {
  1196. next();
  1197. })
  1198. .catch(next);
  1199. }
  1200. ],
  1201. async err => {
  1202. if (err && err !== true) {
  1203. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1204. return reject(new Error(err));
  1205. }
  1206. return resolve();
  1207. }
  1208. );
  1209. });
  1210. }
  1211. /**
  1212. * Removes a playlist from autofill
  1213. *
  1214. * @param {object} payload - object that contains the payload
  1215. * @param {object} payload.stationId - the id of the station
  1216. * @param {object} payload.playlistId - the id of the playlist
  1217. * @returns {Promise} - returns a promise (resolve, reject)
  1218. */
  1219. REMOVE_AUTOFILL_PLAYLIST(payload) {
  1220. return new Promise((resolve, reject) => {
  1221. async.waterfall(
  1222. [
  1223. next => {
  1224. if (!payload.stationId) next("Please specify a station id");
  1225. else if (!payload.playlistId) next("Please specify a playlist id");
  1226. else next();
  1227. },
  1228. next => {
  1229. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1230. .then(station => {
  1231. next(null, station);
  1232. })
  1233. .catch(next);
  1234. },
  1235. (station, next) => {
  1236. if (station.autofill.playlists.indexOf(payload.playlistId) === -1)
  1237. next("This playlist isn't autofilling");
  1238. else next();
  1239. },
  1240. next => {
  1241. StationsModule.stationModel.updateOne(
  1242. { _id: payload.stationId },
  1243. { $pull: { "autofill.playlists": payload.playlistId } },
  1244. next
  1245. );
  1246. },
  1247. (res, next) => {
  1248. StationsModule.runJob(
  1249. "UPDATE_STATION",
  1250. {
  1251. stationId: payload.stationId
  1252. },
  1253. this
  1254. )
  1255. .then(() => {
  1256. next();
  1257. })
  1258. .catch(next);
  1259. }
  1260. ],
  1261. async err => {
  1262. if (err && err !== true) {
  1263. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1264. return reject(new Error(err));
  1265. }
  1266. return resolve();
  1267. }
  1268. );
  1269. });
  1270. }
  1271. /**
  1272. * Add a playlist to station blacklist
  1273. *
  1274. * @param {object} payload - object that contains the payload
  1275. * @param {object} payload.stationId - the id of the station
  1276. * @param {object} payload.playlistId - the id of the playlist
  1277. * @returns {Promise} - returns a promise (resolve, reject)
  1278. */
  1279. BLACKLIST_PLAYLIST(payload) {
  1280. return new Promise((resolve, reject) => {
  1281. async.waterfall(
  1282. [
  1283. next => {
  1284. if (!payload.stationId) next("Please specify a station id");
  1285. else if (!payload.playlistId) next("Please specify a playlist id");
  1286. else next();
  1287. },
  1288. next => {
  1289. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1290. .then(station => {
  1291. next(null, station);
  1292. })
  1293. .catch(next);
  1294. },
  1295. (station, next) => {
  1296. if (station.playlist === payload.playlistId) next("You cannot blacklist the station playlist");
  1297. else if (station.blacklist.indexOf(payload.playlistId) !== -1)
  1298. next("This playlist is already blacklisted");
  1299. else if (station.autofill.playlists.indexOf(payload.playlistId) !== -1)
  1300. next(
  1301. "This playlist is currently autofilling, please remove it from there before blacklisting it"
  1302. );
  1303. else
  1304. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1305. .then(() => {
  1306. next(null);
  1307. })
  1308. .catch(next);
  1309. },
  1310. next => {
  1311. StationsModule.stationModel.updateOne(
  1312. { _id: payload.stationId },
  1313. { $push: { blacklist: payload.playlistId } },
  1314. next
  1315. );
  1316. },
  1317. (res, next) => {
  1318. StationsModule.runJob(
  1319. "UPDATE_STATION",
  1320. {
  1321. stationId: payload.stationId
  1322. },
  1323. this
  1324. )
  1325. .then(() => {
  1326. next();
  1327. })
  1328. .catch(next);
  1329. }
  1330. ],
  1331. async err => {
  1332. if (err && err !== true) {
  1333. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1334. return reject(new Error(err));
  1335. }
  1336. return resolve();
  1337. }
  1338. );
  1339. });
  1340. }
  1341. /**
  1342. * Remove a playlist from station blacklist
  1343. *
  1344. * @param {object} payload - object that contains the payload
  1345. * @param {object} payload.stationId - the id of the station
  1346. * @param {object} payload.playlistId - the id of the playlist
  1347. * @returns {Promise} - returns a promise (resolve, reject)
  1348. */
  1349. REMOVE_BLACKLISTED_PLAYLIST(payload) {
  1350. return new Promise((resolve, reject) => {
  1351. async.waterfall(
  1352. [
  1353. next => {
  1354. if (!payload.stationId) next("Please specify a station id");
  1355. else if (!payload.playlistId) next("Please specify a playlist id");
  1356. else next();
  1357. },
  1358. next => {
  1359. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1360. .then(station => {
  1361. next(null, station);
  1362. })
  1363. .catch(next);
  1364. },
  1365. (station, next) => {
  1366. if (station.blacklist.indexOf(payload.playlistId) === -1)
  1367. next("This playlist isn't blacklisted");
  1368. else next();
  1369. },
  1370. next => {
  1371. StationsModule.stationModel.updateOne(
  1372. { _id: payload.stationId },
  1373. { $pull: { blacklist: payload.playlistId } },
  1374. next
  1375. );
  1376. },
  1377. (res, next) => {
  1378. StationsModule.runJob(
  1379. "UPDATE_STATION",
  1380. {
  1381. stationId: payload.stationId
  1382. },
  1383. this
  1384. )
  1385. .then(() => {
  1386. next();
  1387. })
  1388. .catch(next);
  1389. }
  1390. ],
  1391. async err => {
  1392. if (err && err !== true) {
  1393. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1394. return reject(new Error(err));
  1395. }
  1396. return resolve();
  1397. }
  1398. );
  1399. });
  1400. }
  1401. /**
  1402. * Removes autofilled or blacklisted playlist from a station
  1403. *
  1404. * @param {object} payload - object that contains the payload
  1405. * @param {string} payload.playlistId - the playlist id
  1406. * @returns {Promise} - returns promise (reject, resolve)
  1407. */
  1408. REMOVE_AUTOFILLED_OR_BLACKLISTED_PLAYLIST_FROM_STATIONS(payload) {
  1409. return new Promise((resolve, reject) => {
  1410. async.waterfall(
  1411. [
  1412. next => {
  1413. if (!payload.playlistId) next("Please specify a playlist id");
  1414. else next();
  1415. },
  1416. next => {
  1417. StationsModule.stationModel.updateMany(
  1418. {
  1419. $or: [{ "autofill.playlists": payload.playlistId }, { blacklist: payload.playlistId }]
  1420. },
  1421. {
  1422. $pull: {
  1423. "autofill.playlists": payload.playlistId,
  1424. blacklist: payload.playlistId
  1425. }
  1426. },
  1427. err => {
  1428. if (err) next(err);
  1429. else next();
  1430. }
  1431. );
  1432. }
  1433. ],
  1434. async err => {
  1435. if (err && err !== true) {
  1436. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1437. return reject(new Error(err));
  1438. }
  1439. return resolve();
  1440. }
  1441. );
  1442. });
  1443. }
  1444. /**
  1445. * Gets stations that autofill or blacklist a specific playlist
  1446. *
  1447. * @param {object} payload - object that contains the payload
  1448. * @param {string} payload.playlistId - the playlist id
  1449. * @returns {Promise} - returns promise (reject, resolve)
  1450. */
  1451. GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST(payload) {
  1452. return new Promise((resolve, reject) => {
  1453. DBModule.runJob(
  1454. "GET_MODEL",
  1455. {
  1456. modelName: "station"
  1457. },
  1458. this
  1459. ).then(stationModel => {
  1460. stationModel.find(
  1461. {
  1462. $or: [{ "autofill.playlists": payload.playlistId }, { blacklist: payload.playlistId }]
  1463. },
  1464. (err, stations) => {
  1465. if (err) reject(err);
  1466. else resolve({ stationIds: stations.map(station => station._id) });
  1467. }
  1468. );
  1469. });
  1470. });
  1471. }
  1472. /**
  1473. * Clears every queue
  1474. *
  1475. * @returns {Promise} - returns a promise (resolve, reject)
  1476. */
  1477. CLEAR_EVERY_STATION_QUEUE() {
  1478. return new Promise((resolve, reject) => {
  1479. async.waterfall(
  1480. [
  1481. next => {
  1482. StationsModule.stationModel.updateMany({}, { $set: { queue: [] } }, err => {
  1483. if (err) next(err);
  1484. else {
  1485. StationsModule.stationModel.find({}, (err, stations) => {
  1486. if (err) next(err);
  1487. else {
  1488. async.eachLimit(
  1489. stations,
  1490. 1,
  1491. (station, next) => {
  1492. this.publishProgress({
  1493. status: "update",
  1494. message: `Updating station "${station._id}"`
  1495. });
  1496. StationsModule.runJob("UPDATE_STATION", {
  1497. stationId: station._id
  1498. })
  1499. .then(() => next())
  1500. .catch(next);
  1501. CacheModule.runJob("PUB", {
  1502. channel: "station.queueUpdate",
  1503. value: station._id
  1504. })
  1505. .then()
  1506. .catch();
  1507. },
  1508. next
  1509. );
  1510. }
  1511. });
  1512. }
  1513. });
  1514. }
  1515. ],
  1516. err => {
  1517. if (err) reject(err);
  1518. else resolve();
  1519. }
  1520. );
  1521. });
  1522. }
  1523. /**
  1524. * Resets a station queue
  1525. *
  1526. * @param {object} payload - object that contains the payload
  1527. * @param {string} payload.stationId - the station id
  1528. * @returns {Promise} - returns a promise (resolve, reject)
  1529. */
  1530. RESET_QUEUE(payload) {
  1531. return new Promise((resolve, reject) => {
  1532. async.waterfall(
  1533. [
  1534. next => {
  1535. StationsModule.runJob(
  1536. "AUTOFILL_STATION",
  1537. { stationId: payload.stationId, ignoreExistingQueue: true },
  1538. this
  1539. )
  1540. .then(() => {
  1541. CacheModule.runJob("PUB", {
  1542. channel: "station.queueUpdate",
  1543. value: payload.stationId
  1544. })
  1545. .then()
  1546. .catch();
  1547. next();
  1548. })
  1549. .catch(err => {
  1550. if (err === "Autofill is disabled in this station" || err === "Autofill limit reached")
  1551. StationsModule.stationModel
  1552. .updateOne({ _id: payload.stationId }, { $set: { queue: [] } }, this)
  1553. .then(() => next())
  1554. .catch(next);
  1555. else next(err);
  1556. });
  1557. },
  1558. next => {
  1559. StationsModule.runJob("UPDATE_STATION", { stationId: payload.stationId }, this)
  1560. .then(() => next())
  1561. .catch(next);
  1562. },
  1563. next => {
  1564. CacheModule.runJob("PUB", {
  1565. channel: "station.queueUpdate",
  1566. value: payload.stationId
  1567. })
  1568. .then(() => next())
  1569. .catch(next);
  1570. }
  1571. ],
  1572. err => {
  1573. if (err) reject(err);
  1574. else resolve();
  1575. }
  1576. );
  1577. });
  1578. }
  1579. /**
  1580. * Add to a station queue
  1581. *
  1582. * @param {object} payload - object that contains the payload
  1583. * @param {string} payload.stationId - the station id
  1584. * @param {string} payload.youtubeId - the youtube id
  1585. * @param {string} payload.requestUser - the requesting user id
  1586. * @returns {Promise} - returns a promise (resolve, reject)
  1587. */
  1588. ADD_TO_QUEUE(payload) {
  1589. return new Promise((resolve, reject) => {
  1590. const { stationId, youtubeId, requestUser } = payload;
  1591. async.waterfall(
  1592. [
  1593. next => {
  1594. StationsModule.runJob("GET_STATION", { stationId }, this)
  1595. .then(station => {
  1596. next(null, station);
  1597. })
  1598. .catch(next);
  1599. },
  1600. (station, next) => {
  1601. if (!station) return next("Station not found.");
  1602. if (!station.requests.enabled) return next("Requests are disabled in this station.");
  1603. if (station.currentSong && station.currentSong.youtubeId === youtubeId)
  1604. return next("That song is currently playing.");
  1605. if (station.queue.find(song => song.youtubeId === youtubeId))
  1606. return next("That song is already in the queue.");
  1607. return next(null, station);
  1608. },
  1609. (station, next) => {
  1610. MediaModule.runJob("GET_MEDIA", { youtubeId }, this)
  1611. .then(response => {
  1612. const { song } = response;
  1613. const { _id, title, skipDuration, artists, thumbnail, duration, verified } = song;
  1614. next(
  1615. null,
  1616. {
  1617. _id,
  1618. youtubeId,
  1619. title,
  1620. skipDuration,
  1621. artists,
  1622. thumbnail,
  1623. duration,
  1624. verified
  1625. },
  1626. station
  1627. );
  1628. })
  1629. .catch(next);
  1630. },
  1631. (song, station, next) => {
  1632. const blacklist = [];
  1633. async.eachLimit(
  1634. station.blacklist,
  1635. 1,
  1636. (playlistId, next) => {
  1637. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1638. .then(playlist => {
  1639. blacklist.push(playlist);
  1640. next();
  1641. })
  1642. .catch(next);
  1643. },
  1644. err => {
  1645. next(err, song, station, blacklist);
  1646. }
  1647. );
  1648. },
  1649. (song, station, blacklist, next) => {
  1650. const blacklistedSongs = blacklist
  1651. .flatMap(blacklistedPlaylist => blacklistedPlaylist.songs)
  1652. .reduce(
  1653. (items, item) =>
  1654. items.find(x => x.youtubeId === item.youtubeId) ? [...items] : [...items, item],
  1655. []
  1656. );
  1657. if (blacklistedSongs.find(blacklistedSong => blacklistedSong.youtubeId === song.youtubeId))
  1658. next("That song is in an blacklisted playlist and cannot be played.");
  1659. else next(null, song, station);
  1660. },
  1661. (song, station, next) => {
  1662. song.requestedBy = requestUser;
  1663. song.requestedAt = Date.now();
  1664. if (station.queue.length === 0) return next(null, song);
  1665. if (
  1666. requestUser &&
  1667. station.queue.filter(queueSong => queueSong.requestedBy === song.requestedBy).length >=
  1668. station.requests.limit
  1669. )
  1670. return next(`The max amount of songs per user is ${station.requests.limit}.`);
  1671. return next(null, song);
  1672. },
  1673. // (song, station, next) => {
  1674. // song.requestedBy = session.userId;
  1675. // song.requestedAt = Date.now();
  1676. // let totalDuration = 0;
  1677. // station.queue.forEach(song => {
  1678. // totalDuration += song.duration;
  1679. // });
  1680. // if (totalDuration >= 3600 * 3) return next("The max length of the queue is 3 hours.");
  1681. // return next(null, song, station);
  1682. // },
  1683. // (song, station, next) => {
  1684. // if (station.queue.length === 0) return next(null, song, station);
  1685. // let totalDuration = 0;
  1686. // const userId = station.queue[station.queue.length - 1].requestedBy;
  1687. // station.queue.forEach(song => {
  1688. // if (userId === song.requestedBy) {
  1689. // totalDuration += song.duration;
  1690. // }
  1691. // });
  1692. // if (totalDuration >= 900) return next("The max length of songs per user is 15 minutes.");
  1693. // return next(null, song, station);
  1694. // },
  1695. // (song, station, next) => {
  1696. // if (station.queue.length === 0) return next(null, song);
  1697. // let totalSongs = 0;
  1698. // const userId = station.queue[station.queue.length - 1].requestedBy;
  1699. // station.queue.forEach(song => {
  1700. // if (userId === song.requestedBy) {
  1701. // totalSongs += 1;
  1702. // }
  1703. // });
  1704. // if (totalSongs <= 2) return next(null, song);
  1705. // if (totalSongs > 3)
  1706. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1707. // if (
  1708. // station.queue[station.queue.length - 2].requestedBy !== userId ||
  1709. // station.queue[station.queue.length - 3] !== userId
  1710. // )
  1711. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1712. // return next(null, song);
  1713. // },
  1714. (song, next) => {
  1715. StationsModule.stationModel.updateOne(
  1716. { _id: stationId },
  1717. { $push: { queue: song } },
  1718. { runValidators: true },
  1719. next
  1720. );
  1721. },
  1722. (res, next) => {
  1723. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1724. .then(() => next())
  1725. .catch(next);
  1726. },
  1727. next => {
  1728. CacheModule.runJob(
  1729. "PUB",
  1730. {
  1731. channel: "station.queueUpdate",
  1732. value: stationId
  1733. },
  1734. this
  1735. )
  1736. .then(() => next())
  1737. .catch(next);
  1738. }
  1739. ],
  1740. err => {
  1741. if (err) reject(err);
  1742. else resolve();
  1743. }
  1744. );
  1745. });
  1746. }
  1747. /**
  1748. * Remove from a station queue
  1749. *
  1750. * @param {object} payload - object that contains the payload
  1751. * @param {string} payload.stationId - the station id
  1752. * @param {string} payload.youtubeId - the youtube id
  1753. * @returns {Promise} - returns a promise (resolve, reject)
  1754. */
  1755. REMOVE_FROM_QUEUE(payload) {
  1756. return new Promise((resolve, reject) => {
  1757. const { stationId, youtubeId } = payload;
  1758. async.waterfall(
  1759. [
  1760. next => {
  1761. StationsModule.runJob("GET_STATION", { stationId }, this)
  1762. .then(station => {
  1763. next(null, station);
  1764. })
  1765. .catch(next);
  1766. },
  1767. (station, next) => {
  1768. if (!station) return next("Station not found.");
  1769. if (!station.queue.find(song => song.youtubeId === youtubeId))
  1770. return next("That song is not currently in the queue.");
  1771. return StationsModule.stationModel.updateOne(
  1772. { _id: stationId },
  1773. { $pull: { queue: { youtubeId } } },
  1774. next
  1775. );
  1776. },
  1777. (res, next) => {
  1778. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1779. .then(station => {
  1780. if (station.autofill.enabled)
  1781. StationsModule.runJob("AUTOFILL_STATION", { stationId }, this)
  1782. .then(() => next())
  1783. .catch(err => {
  1784. if (
  1785. err === "Autofill is disabled in this station" ||
  1786. err === "Autofill limit reached"
  1787. )
  1788. return next();
  1789. return next(err);
  1790. });
  1791. else next();
  1792. })
  1793. .catch(next);
  1794. },
  1795. next =>
  1796. CacheModule.runJob(
  1797. "PUB",
  1798. {
  1799. channel: "station.queueUpdate",
  1800. value: stationId
  1801. },
  1802. this
  1803. )
  1804. .then(() => next())
  1805. .catch(next)
  1806. ],
  1807. err => {
  1808. if (err) reject(err);
  1809. else resolve();
  1810. }
  1811. );
  1812. });
  1813. }
  1814. /**
  1815. * Add DJ to station
  1816. *
  1817. * @param {object} payload - object that contains the payload
  1818. * @param {string} payload.stationId - the station id
  1819. * @param {string} payload.userId - the dj user id
  1820. * @returns {Promise} - returns a promise (resolve, reject)
  1821. */
  1822. ADD_DJ(payload) {
  1823. return new Promise((resolve, reject) => {
  1824. const { stationId, userId } = payload;
  1825. async.waterfall(
  1826. [
  1827. next => {
  1828. StationsModule.runJob("GET_STATION", { stationId }, this)
  1829. .then(station => {
  1830. next(null, station);
  1831. })
  1832. .catch(next);
  1833. },
  1834. (station, next) => {
  1835. if (!station) return next("Station not found.");
  1836. if (station.djs.find(dj => dj === userId)) return next("That user is already a DJ.");
  1837. return StationsModule.stationModel.updateOne(
  1838. { _id: stationId },
  1839. { $push: { djs: userId } },
  1840. next
  1841. );
  1842. },
  1843. (res, next) => {
  1844. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1845. .then(() => next())
  1846. .catch(next);
  1847. },
  1848. next =>
  1849. CacheModule.runJob(
  1850. "PUB",
  1851. {
  1852. channel: "station.djs.added",
  1853. value: { stationId, userId }
  1854. },
  1855. this
  1856. )
  1857. .then(() => next())
  1858. .catch(next)
  1859. ],
  1860. err => {
  1861. if (err) reject(err);
  1862. else resolve();
  1863. }
  1864. );
  1865. });
  1866. }
  1867. /**
  1868. * Remove DJ from station
  1869. *
  1870. * @param {object} payload - object that contains the payload
  1871. * @param {string} payload.stationId - the station id
  1872. * @param {string} payload.userId - the dj user id
  1873. * @returns {Promise} - returns a promise (resolve, reject)
  1874. */
  1875. REMOVE_DJ(payload) {
  1876. return new Promise((resolve, reject) => {
  1877. const { stationId, userId } = payload;
  1878. async.waterfall(
  1879. [
  1880. next => {
  1881. StationsModule.runJob("GET_STATION", { stationId }, this)
  1882. .then(station => {
  1883. next(null, station);
  1884. })
  1885. .catch(next);
  1886. },
  1887. (station, next) => {
  1888. if (!station) return next("Station not found.");
  1889. if (!station.djs.find(dj => dj === userId)) return next("That user is not currently a DJ.");
  1890. return StationsModule.stationModel.updateOne(
  1891. { _id: stationId },
  1892. { $pull: { djs: userId } },
  1893. next
  1894. );
  1895. },
  1896. (res, next) => {
  1897. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1898. .then(() => next())
  1899. .catch(next);
  1900. },
  1901. next =>
  1902. CacheModule.runJob(
  1903. "PUB",
  1904. {
  1905. channel: "station.djs.removed",
  1906. value: { stationId, userId }
  1907. },
  1908. this
  1909. )
  1910. .then(() => next())
  1911. .catch(next)
  1912. ],
  1913. err => {
  1914. if (err) reject(err);
  1915. else resolve();
  1916. }
  1917. );
  1918. });
  1919. }
  1920. }
  1921. export default new _StationsModule();