stations.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553
  1. import async from "async";
  2. import mongoose from "mongoose";
  3. import CoreClass from "../core";
  4. let StationsModule;
  5. let CacheModule;
  6. let DBModule;
  7. let UtilsModule;
  8. let IOModule;
  9. let SongsModule;
  10. let PlaylistsModule;
  11. let NotificationsModule;
  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. IOModule = this.moduleManager.modules.io;
  28. SongsModule = this.moduleManager.modules.songs;
  29. PlaylistsModule = this.moduleManager.modules.playlists;
  30. NotificationsModule = this.moduleManager.modules.notifications;
  31. this.defaultSong = {
  32. songId: "60ItHLz5WEA",
  33. title: "Faded - Alan Walker",
  34. duration: 212,
  35. skipDuration: 0,
  36. likes: -1,
  37. dislikes: -1,
  38. requestedAt: Date.now()
  39. };
  40. this.userList = {};
  41. this.usersPerStation = {};
  42. this.usersPerStationCount = {};
  43. // TEMP
  44. CacheModule.runJob("SUB", {
  45. channel: "station.pause",
  46. cb: async stationId => {
  47. NotificationsModule.runJob("REMOVE", {
  48. subscription: `stations.nextSong?id=${stationId}`
  49. }).then();
  50. }
  51. });
  52. CacheModule.runJob("SUB", {
  53. channel: "station.resume",
  54. cb: async stationId => {
  55. StationsModule.runJob("INITIALIZE_STATION", { stationId }).then();
  56. }
  57. });
  58. CacheModule.runJob("SUB", {
  59. channel: "station.queueUpdate",
  60. cb: async stationId => {
  61. StationsModule.runJob("GET_STATION", { stationId }).then(station => {
  62. if (!station.currentSong && station.queue.length > 0) {
  63. StationsModule.runJob("INITIALIZE_STATION", {
  64. stationId
  65. }).then();
  66. }
  67. });
  68. }
  69. });
  70. CacheModule.runJob("SUB", {
  71. channel: "station.newOfficialPlaylist",
  72. cb: async stationId => {
  73. CacheModule.runJob("HGET", {
  74. table: "officialPlaylists",
  75. key: stationId
  76. }).then(playlistObj => {
  77. if (playlistObj) {
  78. IOModule.runJob("EMIT_TO_ROOM", {
  79. room: `station.${stationId}`,
  80. args: ["event:newOfficialPlaylist", playlistObj.songs]
  81. });
  82. }
  83. });
  84. }
  85. });
  86. const stationModel = (this.stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }));
  87. const stationSchema = (this.stationSchema = await CacheModule.runJob("GET_SCHEMA", { schemaName: "station" }));
  88. return new Promise((resolve, reject) =>
  89. async.waterfall(
  90. [
  91. next => {
  92. this.setStage(2);
  93. CacheModule.runJob("HGETALL", { table: "stations" })
  94. .then(stations => {
  95. next(null, stations);
  96. })
  97. .catch(next);
  98. },
  99. (stations, next) => {
  100. this.setStage(3);
  101. if (!stations) return next();
  102. const stationIds = Object.keys(stations);
  103. return async.each(
  104. stationIds,
  105. (stationId, next) => {
  106. stationModel.findOne({ _id: stationId }, (err, station) => {
  107. if (err) next(err);
  108. else if (!station) {
  109. CacheModule.runJob("HDEL", {
  110. table: "stations",
  111. key: stationId
  112. })
  113. .then(() => {
  114. next();
  115. })
  116. .catch(next);
  117. } else next();
  118. });
  119. },
  120. next
  121. );
  122. },
  123. next => {
  124. this.setStage(4);
  125. stationModel.find({}, next);
  126. },
  127. (stations, next) => {
  128. this.setStage(5);
  129. async.each(
  130. stations,
  131. (station, next2) => {
  132. async.waterfall(
  133. [
  134. next => {
  135. CacheModule.runJob("HSET", {
  136. table: "stations",
  137. key: station._id,
  138. value: stationSchema(station)
  139. })
  140. .then(station => next(null, station))
  141. .catch(next);
  142. },
  143. (station, next) => {
  144. StationsModule.runJob(
  145. "INITIALIZE_STATION",
  146. {
  147. stationId: station._id
  148. },
  149. null,
  150. -1
  151. )
  152. .then(() => {
  153. next();
  154. })
  155. .catch(next);
  156. }
  157. ],
  158. err => {
  159. next2(err);
  160. }
  161. );
  162. },
  163. next
  164. );
  165. }
  166. ],
  167. async err => {
  168. if (err) {
  169. err = await UtilsModule.runJob("GET_ERROR", {
  170. error: err
  171. });
  172. reject(new Error(err));
  173. } else {
  174. resolve();
  175. }
  176. }
  177. )
  178. );
  179. }
  180. /**
  181. * Initialises a station
  182. *
  183. * @param {object} payload - object that contains the payload
  184. * @param {string} payload.stationId - id of the station to initialise
  185. * @returns {Promise} - returns a promise (resolve, reject)
  186. */
  187. INITIALIZE_STATION(payload) {
  188. return new Promise((resolve, reject) => {
  189. // if (typeof cb !== 'function') cb = ()=>{};
  190. async.waterfall(
  191. [
  192. next => {
  193. StationsModule.runJob(
  194. "GET_STATION",
  195. {
  196. stationId: payload.stationId
  197. },
  198. this
  199. )
  200. .then(station => {
  201. next(null, station);
  202. })
  203. .catch(next);
  204. },
  205. (station, next) => {
  206. if (!station) return next("Station not found.");
  207. return NotificationsModule.runJob(
  208. "UNSCHEDULE",
  209. {
  210. name: `stations.nextSong?id=${station._id}`
  211. },
  212. this
  213. )
  214. .then()
  215. .catch()
  216. .finally(() => {
  217. NotificationsModule.runJob("SUBSCRIBE", {
  218. name: `stations.nextSong?id=${station._id}`,
  219. cb: () =>
  220. StationsModule.runJob("SKIP_STATION", {
  221. stationId: station._id
  222. }),
  223. unique: true,
  224. station
  225. })
  226. .then()
  227. .catch();
  228. if (station.paused) return next(true, station);
  229. return next(null, station);
  230. });
  231. },
  232. (station, next) => {
  233. if (!station.currentSong) {
  234. return StationsModule.runJob(
  235. "SKIP_STATION",
  236. {
  237. stationId: station._id
  238. },
  239. this
  240. )
  241. .then(station => {
  242. next(true, station);
  243. })
  244. .catch(next)
  245. .finally(() => {});
  246. }
  247. let timeLeft =
  248. station.currentSong.duration * 1000 - (Date.now() - station.startedAt - station.timePaused);
  249. if (Number.isNaN(timeLeft)) timeLeft = -1;
  250. if (station.currentSong.duration * 1000 < timeLeft || timeLeft < 0) {
  251. return StationsModule.runJob(
  252. "SKIP_STATION",
  253. {
  254. stationId: station._id
  255. },
  256. this
  257. )
  258. .then(station => {
  259. next(null, station);
  260. })
  261. .catch(next);
  262. }
  263. // name, time, cb, station
  264. NotificationsModule.runJob("SCHEDULE", {
  265. name: `stations.nextSong?id=${station._id}`,
  266. time: timeLeft,
  267. station
  268. });
  269. return next(null, station);
  270. }
  271. ],
  272. async (err, station) => {
  273. if (err && err !== true) {
  274. err = await UtilsModule.runJob(
  275. "GET_ERROR",
  276. {
  277. error: err
  278. },
  279. this
  280. );
  281. reject(new Error(err));
  282. } else resolve(station);
  283. }
  284. );
  285. });
  286. }
  287. /**
  288. * Attempts to get the station from Redis. If it's not in Redis, get it from Mongo and add it to Redis.
  289. *
  290. * @param {object} payload - object that contains the payload
  291. * @param {string} payload.stationId - id of the station
  292. * @returns {Promise} - returns a promise (resolve, reject)
  293. */
  294. GET_STATION(payload) {
  295. return new Promise((resolve, reject) => {
  296. async.waterfall(
  297. [
  298. next => {
  299. CacheModule.runJob(
  300. "HGET",
  301. {
  302. table: "stations",
  303. key: payload.stationId
  304. },
  305. this
  306. )
  307. .then(station => {
  308. next(null, station);
  309. })
  310. .catch(next);
  311. },
  312. (station, next) => {
  313. if (station) return next(true, station);
  314. return StationsModule.stationModel.findOne({ _id: payload.stationId }, next);
  315. },
  316. (station, next) => {
  317. if (station) {
  318. station = StationsModule.stationSchema(station);
  319. CacheModule.runJob("HSET", {
  320. table: "stations",
  321. key: payload.stationId,
  322. value: station
  323. })
  324. .then()
  325. .catch();
  326. next(true, station);
  327. } else next("Station not found");
  328. }
  329. ],
  330. async (err, station) => {
  331. if (err && err !== true) {
  332. err = await UtilsModule.runJob(
  333. "GET_ERROR",
  334. {
  335. error: err
  336. },
  337. this
  338. );
  339. reject(new Error(err));
  340. } else resolve(station);
  341. }
  342. );
  343. });
  344. }
  345. /**
  346. * 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.
  347. *
  348. * @param {object} payload - object that contains the payload
  349. * @param {string} payload.stationName - the unique name of the station
  350. * @returns {Promise} - returns a promise (resolve, reject)
  351. */
  352. async GET_STATION_BY_NAME(payload) {
  353. return new Promise((resolve, reject) =>
  354. async.waterfall(
  355. [
  356. next => {
  357. StationsModule.stationModel.findOne({ name: payload.stationName }, next);
  358. },
  359. (station, next) => {
  360. if (station) {
  361. station = StationsModule.stationSchema(station);
  362. CacheModule.runJob("HSET", {
  363. table: "stations",
  364. key: station._id,
  365. value: station
  366. });
  367. next(true, station);
  368. } else next("Station not found");
  369. }
  370. ],
  371. (err, station) => {
  372. if (err && err !== true) return reject(new Error(err));
  373. return resolve(station);
  374. }
  375. )
  376. );
  377. }
  378. /**
  379. * Updates the station in cache from mongo or deletes station in cache if no longer in mongo.
  380. *
  381. * @param {object} payload - object that contains the payload
  382. * @param {string} payload.stationId - the id of the station to update
  383. * @returns {Promise} - returns a promise (resolve, reject)
  384. */
  385. UPDATE_STATION(payload) {
  386. return new Promise((resolve, reject) => {
  387. async.waterfall(
  388. [
  389. next => {
  390. StationsModule.stationModel.findOne({ _id: payload.stationId }, next);
  391. },
  392. (station, next) => {
  393. if (!station) {
  394. CacheModule.runJob("HDEL", {
  395. table: "stations",
  396. key: payload.stationId
  397. })
  398. .then()
  399. .catch();
  400. return next("Station not found");
  401. }
  402. return CacheModule.runJob(
  403. "HSET",
  404. {
  405. table: "stations",
  406. key: payload.stationId,
  407. value: station
  408. },
  409. this
  410. )
  411. .then(station => {
  412. next(null, station);
  413. })
  414. .catch(next);
  415. }
  416. ],
  417. async (err, station) => {
  418. if (err && err !== true) {
  419. err = await UtilsModule.runJob(
  420. "GET_ERROR",
  421. {
  422. error: err
  423. },
  424. this
  425. );
  426. reject(new Error(err));
  427. } else resolve(station);
  428. }
  429. );
  430. });
  431. }
  432. /**
  433. * Fills up the official station playlist queue using the songs from the official station playlist
  434. *
  435. * @param {object} payload - object that contains the payload
  436. * @param {string} payload.stationId - the id of the station
  437. * @returns {Promise} - returns a promise (resolve, reject)
  438. */
  439. FILL_UP_OFFICIAL_STATION_PLAYLIST_QUEUE(payload) {
  440. return new Promise((resolve, reject) => {
  441. const { stationId } = payload;
  442. async.waterfall(
  443. [
  444. next => {
  445. PlaylistsModule.runJob("GET_STATION_PLAYLIST", { stationId, includeSongs: true }, this)
  446. .then(response => {
  447. next(null, response.playlist);
  448. })
  449. .catch(next);
  450. },
  451. (playlist, next) => {
  452. UtilsModule.runJob("SHUFFLE", { array: playlist.songs }, this)
  453. .then(response => {
  454. next(null, response.array);
  455. })
  456. .catch(next);
  457. },
  458. (playlistSongs, next) => {
  459. StationsModule.runJob("GET_STATION", { stationId }, this)
  460. .then(station => {
  461. next(null, playlistSongs, station);
  462. })
  463. .catch(next);
  464. },
  465. (playlistSongs, station, next) => {
  466. const songsStillNeeded = 50 - station.playlist.length;
  467. const currentSongs = station.playlist;
  468. const currentSongIds = station.playlist.map(song => song._id);
  469. const songsToAdd = [];
  470. playlistSongs
  471. .map(song => song._doc)
  472. .forEach(song => {
  473. if (
  474. songsToAdd.length < songsStillNeeded &&
  475. currentSongIds.indexOf(song._id.toString()) === -1
  476. )
  477. songsToAdd.push(song);
  478. });
  479. next(null, [...currentSongs, ...songsToAdd]);
  480. },
  481. (newPlaylist, next) => {
  482. StationsModule.stationModel.updateOne(
  483. { _id: stationId },
  484. { $set: { playlist: newPlaylist } },
  485. { runValidators: true },
  486. () => {
  487. StationsModule.runJob(
  488. "UPDATE_STATION",
  489. {
  490. stationId
  491. },
  492. this
  493. )
  494. .then(() => {
  495. next(null);
  496. })
  497. .catch(next);
  498. }
  499. );
  500. }
  501. ],
  502. err => {
  503. if (err) reject(err);
  504. else resolve();
  505. }
  506. );
  507. });
  508. }
  509. /**
  510. * Gets next official station song
  511. *
  512. * @param {object} payload - object that contains the payload
  513. * @param {string} payload.stationId - the id of the station
  514. * @returns {Promise} - returns a promise (resolve, reject)
  515. */
  516. GET_NEXT_OFFICIAL_STATION_SONG(payload) {
  517. return new Promise((resolve, reject) => {
  518. const { stationId } = payload;
  519. async.waterfall(
  520. [
  521. next => {
  522. StationsModule.runJob("GET_STATION", { stationId }, this)
  523. .then(station => {
  524. next(null, station);
  525. })
  526. .catch(next);
  527. },
  528. (station, next) => {
  529. if (station.playlist.length === 0) next("No songs available.");
  530. else {
  531. next(null, station.playlist[0]);
  532. }
  533. },
  534. (song, next) => {
  535. console.log(44444, song, song._id);
  536. SongsModule.runJob("GET_SONG", { id: song._id }, this)
  537. .then(response => {
  538. const { song } = response;
  539. if (song) {
  540. const newSong = {
  541. _id: song._id,
  542. songId: song.songId,
  543. title: song.title,
  544. artists: song.artists,
  545. duration: song.duration,
  546. thumbnail: song.thumbnail,
  547. requestedAt: song.requestedAt
  548. };
  549. next(null, newSong);
  550. } else {
  551. next(null, song);
  552. }
  553. })
  554. .catch(next);
  555. }
  556. ],
  557. (err, song) => {
  558. if (err) console.log(33333, err, payload);
  559. if (err) reject(err);
  560. else resolve({ song });
  561. }
  562. );
  563. });
  564. }
  565. /**
  566. * Removes first official playlist queue song
  567. *
  568. * @param {object} payload - object that contains the payload
  569. * @param {string} payload.stationId - the id of the station
  570. * @returns {Promise} - returns a promise (resolve, reject)
  571. */
  572. REMOVE_FIRST_OFFICIAL_PLAYLIST_QUEUE_SONG(payload) {
  573. return new Promise((resolve, reject) => {
  574. const { stationId } = payload;
  575. async.waterfall(
  576. [
  577. next => {
  578. StationsModule.stationModel.updateOne(
  579. { _id: stationId },
  580. { $pop: { playlist: -1 } },
  581. { runValidators: true },
  582. err => {
  583. if (err) next(err);
  584. else
  585. StationsModule.runJob(
  586. "UPDATE_STATION",
  587. {
  588. stationId
  589. },
  590. this
  591. )
  592. .then(() => {
  593. next(null);
  594. })
  595. .catch(next);
  596. }
  597. );
  598. }
  599. ],
  600. err => {
  601. if (err) reject(err);
  602. else resolve();
  603. }
  604. );
  605. });
  606. }
  607. /**
  608. * Skips a station
  609. *
  610. * @param {object} payload - object that contains the payload
  611. * @param {string} payload.stationId - the id of the station to skip
  612. * @returns {Promise} - returns a promise (resolve, reject)
  613. */
  614. SKIP_STATION(payload) {
  615. return new Promise((resolve, reject) => {
  616. StationsModule.log("INFO", `Skipping station ${payload.stationId}.`);
  617. StationsModule.log("STATION_ISSUE", `SKIP_STATION_CB - Station ID: ${payload.stationId}.`);
  618. async.waterfall(
  619. [
  620. next => {
  621. NotificationsModule.runJob("UNSCHEDULE", {
  622. name: `stations.nextSong?id=${payload.stationId}`
  623. })
  624. .then(() => {
  625. next();
  626. })
  627. .catch(next);
  628. },
  629. next => {
  630. StationsModule.runJob(
  631. "GET_STATION",
  632. {
  633. stationId: payload.stationId
  634. },
  635. this
  636. )
  637. .then(station => {
  638. next(null, station);
  639. })
  640. .catch(() => {});
  641. },
  642. // eslint-disable-next-line consistent-return
  643. (station, next) => {
  644. if (!station) return next("Station not found.");
  645. if (station.type === "community" && station.partyMode && station.queue.length === 0)
  646. return next(null, null, -11, station); // Community station with party mode enabled and no songs in the queue
  647. if (station.type === "community" && station.partyMode && station.queue.length > 0) {
  648. // Community station with party mode enabled and songs in the queue
  649. if (station.paused) return next(null, null, -19, station);
  650. return StationsModule.stationModel.updateOne(
  651. { _id: payload.stationId },
  652. {
  653. $pull: {
  654. queue: {
  655. _id: station.queue[0]._id
  656. }
  657. }
  658. },
  659. err => {
  660. if (err) return next(err);
  661. return next(null, station.queue[0], -12, station);
  662. }
  663. );
  664. }
  665. if (station.type === "community" && !station.partyMode) {
  666. return DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this).then(playlistModel =>
  667. playlistModel.findOne({ _id: station.privatePlaylist }, (err, playlist) => {
  668. if (err) return next(err);
  669. if (!playlist) return next(null, null, -13, station);
  670. playlist = playlist.songs;
  671. if (playlist.length > 0) {
  672. let currentSongIndex;
  673. if (station.currentSongIndex < playlist.length - 1)
  674. currentSongIndex = station.currentSongIndex + 1;
  675. else currentSongIndex = 0;
  676. const callback = (err, song) => {
  677. if (err) return next(err);
  678. if (song) return next(null, song, currentSongIndex, station);
  679. const currentSong = {
  680. songId: playlist[currentSongIndex].songId,
  681. title: playlist[currentSongIndex].title,
  682. duration: playlist[currentSongIndex].duration,
  683. likes: -1,
  684. dislikes: -1,
  685. requestedAt: playlist[currentSongIndex].requestedAt
  686. };
  687. return next(null, currentSong, currentSongIndex, station);
  688. };
  689. if (mongoose.Types.ObjectId.isValid(playlist[currentSongIndex]._id))
  690. return SongsModule.runJob(
  691. "GET_SONG",
  692. {
  693. id: playlist[currentSongIndex]._id
  694. },
  695. this
  696. )
  697. .then(response => callback(null, response.song))
  698. .catch(callback);
  699. return SongsModule.runJob(
  700. "GET_SONG_FROM_ID",
  701. {
  702. songId: playlist[currentSongIndex].songId
  703. },
  704. this
  705. )
  706. .then(response => callback(null, response.song))
  707. .catch(callback);
  708. }
  709. return next(null, null, -14, station);
  710. })
  711. );
  712. }
  713. if (station.type === "official") {
  714. StationsModule.runJob(
  715. "REMOVE_FIRST_OFFICIAL_PLAYLIST_QUEUE_SONG",
  716. { stationId: station._id },
  717. this
  718. )
  719. .then(() => {
  720. StationsModule.runJob(
  721. "FILL_UP_OFFICIAL_STATION_PLAYLIST_QUEUE",
  722. { stationId: station._id },
  723. this
  724. )
  725. .then(() => {
  726. StationsModule.runJob(
  727. "GET_NEXT_OFFICIAL_STATION_SONG",
  728. { stationId: station._id },
  729. this
  730. )
  731. .then(response => {
  732. next(null, response.song, 0, station);
  733. })
  734. .catch(err => {
  735. if (err === "No songs available.") next(null, null, 0, station);
  736. else next(err);
  737. });
  738. })
  739. .catch(next);
  740. })
  741. .catch(next);
  742. }
  743. },
  744. (song, currentSongIndex, station, next) => {
  745. const $set = {};
  746. if (song === null) $set.currentSong = null;
  747. else if (song.likes === -1 && song.dislikes === -1) {
  748. $set.currentSong = {
  749. songId: song.songId,
  750. title: song.title,
  751. duration: song.duration,
  752. skipDuration: 0,
  753. likes: -1,
  754. dislikes: -1,
  755. requestedAt: song.requestedAt
  756. };
  757. } else {
  758. $set.currentSong = {
  759. _id: song._id,
  760. songId: song.songId,
  761. title: song.title,
  762. artists: song.artists,
  763. duration: song.duration,
  764. likes: song.likes,
  765. dislikes: song.dislikes,
  766. skipDuration: song.skipDuration,
  767. thumbnail: song.thumbnail,
  768. requestedAt: song.requestedAt
  769. };
  770. }
  771. if (currentSongIndex >= 0) $set.currentSongIndex = currentSongIndex;
  772. $set.startedAt = Date.now();
  773. $set.timePaused = 0;
  774. if (station.paused) $set.pausedAt = Date.now();
  775. next(null, $set, station);
  776. },
  777. ($set, station, next) => {
  778. StationsModule.stationModel.updateOne({ _id: station._id }, { $set }, err => {
  779. if (err) return next(err);
  780. return StationsModule.runJob(
  781. "UPDATE_STATION",
  782. {
  783. stationId: station._id
  784. },
  785. this
  786. )
  787. .then(station => {
  788. if (station.type === "community" && station.partyMode === true)
  789. CacheModule.runJob("PUB", {
  790. channel: "station.queueUpdate",
  791. value: payload.stationId
  792. })
  793. .then()
  794. .catch();
  795. next(null, station);
  796. })
  797. .catch(next);
  798. });
  799. }
  800. ],
  801. async (err, station) => {
  802. if (err) {
  803. console.log(123, err);
  804. err = await UtilsModule.runJob(
  805. "GET_ERROR",
  806. {
  807. error: err
  808. },
  809. this
  810. );
  811. StationsModule.log("ERROR", `Skipping station "${payload.stationId}" failed. "${err}"`);
  812. return;
  813. reject(new Error(err));
  814. } else {
  815. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  816. station.currentSong.skipVotes = 0;
  817. }
  818. // TODO Pub/Sub this
  819. IOModule.runJob("EMIT_TO_ROOM", {
  820. room: `station.${station._id}`,
  821. args: [
  822. "event:songs.next",
  823. {
  824. currentSong: station.currentSong,
  825. startedAt: station.startedAt,
  826. paused: station.paused,
  827. timePaused: 0
  828. }
  829. ]
  830. })
  831. .then()
  832. .catch();
  833. if (station.privacy === "public") {
  834. IOModule.runJob("EMIT_TO_ROOM", {
  835. room: "home",
  836. args: ["event:station.nextSong", station._id, station.currentSong]
  837. })
  838. .then()
  839. .catch();
  840. } else {
  841. const sockets = await IOModule.runJob("GET_ROOM_SOCKETS", { room: "home" }, this);
  842. Object.keys(sockets).forEach(socketKey => {
  843. const socket = sockets[socketKey];
  844. const { session } = socket;
  845. if (session.sessionId) {
  846. CacheModule.runJob(
  847. "HGET",
  848. {
  849. table: "sessions",
  850. key: session.sessionId
  851. },
  852. this
  853. // eslint-disable-next-line no-loop-func
  854. ).then(session => {
  855. if (session) {
  856. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(
  857. userModel => {
  858. userModel.findOne(
  859. {
  860. _id: session.userId
  861. },
  862. (err, user) => {
  863. if (!err && user) {
  864. if (user.role === "admin")
  865. socket.emit(
  866. "event:station.nextSong",
  867. station._id,
  868. station.currentSong
  869. );
  870. else if (
  871. station.type === "community" &&
  872. station.owner === session.userId
  873. )
  874. socket.emit(
  875. "event:station.nextSong",
  876. station._id,
  877. station.currentSong
  878. );
  879. }
  880. }
  881. );
  882. }
  883. );
  884. }
  885. });
  886. }
  887. });
  888. }
  889. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  890. IOModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  891. sockets: await IOModule.runJob(
  892. "GET_ROOM_SOCKETS",
  893. {
  894. room: `station.${station._id}`
  895. },
  896. this
  897. ),
  898. room: `song.${station.currentSong.songId}`
  899. });
  900. if (!station.paused) {
  901. NotificationsModule.runJob("SCHEDULE", {
  902. name: `stations.nextSong?id=${station._id}`,
  903. time: station.currentSong.duration * 1000,
  904. station
  905. });
  906. }
  907. } else {
  908. IOModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", {
  909. sockets: await IOModule.runJob(
  910. "GET_ROOM_SOCKETS",
  911. {
  912. room: `station.${station._id}`
  913. },
  914. this
  915. )
  916. })
  917. .then()
  918. .catch();
  919. }
  920. resolve({ station });
  921. }
  922. }
  923. );
  924. });
  925. }
  926. /**
  927. * Checks if a user can view/access a station
  928. *
  929. * @param {object} payload - object that contains the payload
  930. * @param {object} payload.station - the station object of the station in question
  931. * @param {string} payload.userId - the id of the user in question
  932. * @param {boolean} payload.hideUnlisted - whether the user is allowed to see unlisted stations or not
  933. * @returns {Promise} - returns a promise (resolve, reject)
  934. */
  935. CAN_USER_VIEW_STATION(payload) {
  936. return new Promise((resolve, reject) => {
  937. async.waterfall(
  938. [
  939. next => {
  940. if (payload.station.privacy === "public") return next(true);
  941. if (payload.station.privacy === "unlisted")
  942. if (payload.hideUnlisted === true) return next();
  943. else return next(true);
  944. if (!payload.userId) return next("Not allowed");
  945. return next();
  946. },
  947. next => {
  948. DBModule.runJob(
  949. "GET_MODEL",
  950. {
  951. modelName: "user"
  952. },
  953. this
  954. ).then(userModel => {
  955. userModel.findOne({ _id: payload.userId }, next);
  956. });
  957. },
  958. (user, next) => {
  959. if (!user) return next("Not allowed");
  960. if (user.role === "admin") return next(true);
  961. if (payload.station.type === "official") return next("Not allowed");
  962. if (payload.station.owner === payload.userId) return next(true);
  963. return next("Not allowed");
  964. }
  965. ],
  966. async errOrResult => {
  967. if (errOrResult !== true && errOrResult !== "Not allowed") {
  968. errOrResult = await UtilsModule.runJob(
  969. "GET_ERROR",
  970. {
  971. error: errOrResult
  972. },
  973. this
  974. );
  975. reject(new Error(errOrResult));
  976. } else {
  977. resolve(errOrResult === true);
  978. }
  979. }
  980. );
  981. });
  982. }
  983. /**
  984. * Checks if a user has favorited a station or not
  985. *
  986. * @param {object} payload - object that contains the payload
  987. * @param {object} payload.stationId - the id of the station in question
  988. * @param {string} payload.userId - the id of the user in question
  989. * @returns {Promise} - returns a promise (resolve, reject)
  990. */
  991. HAS_USER_FAVORITED_STATION(payload) {
  992. return new Promise((resolve, reject) => {
  993. async.waterfall(
  994. [
  995. next => {
  996. DBModule.runJob(
  997. "GET_MODEL",
  998. {
  999. modelName: "user"
  1000. },
  1001. this
  1002. ).then(userModel => {
  1003. userModel.findOne({ _id: payload.userId }, next);
  1004. });
  1005. },
  1006. (user, next) => {
  1007. if (!user) return next("User not found.");
  1008. if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
  1009. return next(null, false);
  1010. }
  1011. ],
  1012. async (err, isStationFavorited) => {
  1013. if (err && err !== true) {
  1014. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1015. return reject(new Error(err));
  1016. }
  1017. return resolve(isStationFavorited);
  1018. }
  1019. );
  1020. });
  1021. }
  1022. /**
  1023. * Returns a list of sockets in a room that can and can't know about a station
  1024. *
  1025. * @param {object} payload - the payload object
  1026. * @param {object} payload.station - the station object
  1027. * @param {string} payload.room - the socket.io room to get the sockets from
  1028. * @returns {Promise} - returns a promise (resolve, reject)
  1029. */
  1030. GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION(payload) {
  1031. return new Promise((resolve, reject) => {
  1032. IOModule.runJob("GET_ROOM_SOCKETS", { room: payload.room }, this)
  1033. .then(socketsObject => {
  1034. const sockets = Object.keys(socketsObject).map(socketKey => socketsObject[socketKey]);
  1035. let socketsThatCan = [];
  1036. const socketsThatCannot = [];
  1037. if (payload.station.privacy === "public") {
  1038. socketsThatCan = sockets;
  1039. resolve({ socketsThatCan, socketsThatCannot });
  1040. } else {
  1041. async.eachLimit(
  1042. sockets,
  1043. 1,
  1044. (socket, next) => {
  1045. const { session } = socket;
  1046. async.waterfall(
  1047. [
  1048. next => {
  1049. if (!session.sessionId) next("No session id");
  1050. else next();
  1051. },
  1052. next => {
  1053. CacheModule.runJob(
  1054. "HGET",
  1055. {
  1056. table: "sessions",
  1057. key: session.sessionId
  1058. },
  1059. this
  1060. )
  1061. .then(response => {
  1062. next(null, response);
  1063. })
  1064. .catch(next);
  1065. },
  1066. (session, next) => {
  1067. if (!session) next("No session");
  1068. else {
  1069. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1070. .then(userModel => {
  1071. next(null, userModel);
  1072. })
  1073. .catch(next);
  1074. }
  1075. },
  1076. (userModel, next) => {
  1077. if (!userModel) next("No user model");
  1078. else
  1079. userModel.findOne(
  1080. {
  1081. _id: session.userId
  1082. },
  1083. next
  1084. );
  1085. },
  1086. (user, next) => {
  1087. if (!user) next("No user found");
  1088. else if (user.role === "admin") {
  1089. socketsThatCan.push(socket);
  1090. next();
  1091. } else if (
  1092. payload.station.type === "community" &&
  1093. payload.station.owner === session.userId
  1094. ) {
  1095. socketsThatCan.push(socket);
  1096. next();
  1097. }
  1098. }
  1099. ],
  1100. err => {
  1101. if (err) socketsThatCannot.push(socket);
  1102. next();
  1103. }
  1104. );
  1105. },
  1106. err => {
  1107. if (err) reject(err);
  1108. else resolve({ socketsThatCan, socketsThatCannot });
  1109. }
  1110. );
  1111. }
  1112. })
  1113. .catch(reject);
  1114. });
  1115. }
  1116. /**
  1117. * Adds a playlist to be included in a station
  1118. *
  1119. * @param {object} payload - object that contains the payload
  1120. * @param {object} payload.stationId - the id of the station to include the playlist in
  1121. * @param {object} payload.playlistId - the id of the playlist to be included
  1122. * @returns {Promise} - returns a promise (resolve, reject)
  1123. */
  1124. INCLUDE_PLAYLIST(payload) {
  1125. return new Promise((resolve, reject) => {
  1126. async.waterfall(
  1127. [
  1128. next => {
  1129. if (!payload.stationId) next("Please specify a station id");
  1130. else if (!payload.playlistId) next("Please specify a playlist id");
  1131. else next();
  1132. },
  1133. next => {
  1134. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1135. .then(station => {
  1136. next(null, station);
  1137. })
  1138. .catch(next);
  1139. },
  1140. (station, next) => {
  1141. if (station.playlist2 === payload.playlistId) next("You cannot include the station playlist");
  1142. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1143. next("This playlist is already included");
  1144. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1145. next(
  1146. "This playlist is currently excluded, please remove it from there before including it"
  1147. );
  1148. else
  1149. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1150. .then(() => {
  1151. next(null);
  1152. })
  1153. .catch(next);
  1154. },
  1155. next => {
  1156. DBModule.runJob(
  1157. "GET_MODEL",
  1158. {
  1159. modelName: "station"
  1160. },
  1161. this
  1162. ).then(stationModel => {
  1163. stationModel.updateOne(
  1164. { _id: payload.stationId },
  1165. { $push: { includedPlaylists: payload.playlistId } },
  1166. next
  1167. );
  1168. });
  1169. },
  1170. (res, next) => {
  1171. StationsModule.runJob(
  1172. "UPDATE_STATION",
  1173. {
  1174. stationId: payload.stationId
  1175. },
  1176. this
  1177. )
  1178. .then(() => {
  1179. next();
  1180. })
  1181. .catch(next);
  1182. }
  1183. ],
  1184. async err => {
  1185. if (err && err !== true) {
  1186. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1187. return reject(new Error(err));
  1188. }
  1189. return resolve();
  1190. }
  1191. );
  1192. });
  1193. }
  1194. /**
  1195. * Removes a playlist that is included in a station
  1196. *
  1197. * @param {object} payload - object that contains the payload
  1198. * @param {object} payload.stationId - the id of the station
  1199. * @param {object} payload.playlistId - the id of the playlist
  1200. * @returns {Promise} - returns a promise (resolve, reject)
  1201. */
  1202. REMOVE_INCLUDED_PLAYLIST(payload) {
  1203. return new Promise((resolve, reject) => {
  1204. async.waterfall(
  1205. [
  1206. next => {
  1207. if (!payload.stationId) next("Please specify a station id");
  1208. else if (!payload.playlistId) next("Please specify a playlist id");
  1209. else next();
  1210. },
  1211. next => {
  1212. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1213. .then(station => {
  1214. next(null, station);
  1215. })
  1216. .catch(next);
  1217. },
  1218. (station, next) => {
  1219. if (station.includedPlaylists.indexOf(payload.playlistId) === -1)
  1220. next("This playlist isn't included");
  1221. else next();
  1222. },
  1223. next => {
  1224. DBModule.runJob(
  1225. "GET_MODEL",
  1226. {
  1227. modelName: "station"
  1228. },
  1229. this
  1230. ).then(stationModel => {
  1231. stationModel.updateOne(
  1232. { _id: payload.stationId },
  1233. { $pull: { includedPlaylists: payload.playlistId } },
  1234. next
  1235. );
  1236. });
  1237. },
  1238. (res, next) => {
  1239. StationsModule.runJob(
  1240. "UPDATE_STATION",
  1241. {
  1242. stationId: payload.stationId
  1243. },
  1244. this
  1245. )
  1246. .then(() => {
  1247. next();
  1248. })
  1249. .catch(next);
  1250. }
  1251. ],
  1252. async err => {
  1253. if (err && err !== true) {
  1254. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1255. return reject(new Error(err));
  1256. }
  1257. return resolve();
  1258. }
  1259. );
  1260. });
  1261. }
  1262. /**
  1263. * Adds a playlist to be excluded in a station
  1264. *
  1265. * @param {object} payload - object that contains the payload
  1266. * @param {object} payload.stationId - the id of the station
  1267. * @param {object} payload.playlistId - the id of the playlist
  1268. * @returns {Promise} - returns a promise (resolve, reject)
  1269. */
  1270. EXCLUDE_PLAYLIST(payload) {
  1271. return new Promise((resolve, reject) => {
  1272. async.waterfall(
  1273. [
  1274. next => {
  1275. if (!payload.stationId) next("Please specify a station id");
  1276. else if (!payload.playlistId) next("Please specify a playlist id");
  1277. else next();
  1278. },
  1279. next => {
  1280. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1281. .then(station => {
  1282. next(null, station);
  1283. })
  1284. .catch(next);
  1285. },
  1286. (station, next) => {
  1287. if (station.playlist2 === payload.playlistId) next("You cannot exclude the station playlist");
  1288. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1289. next("This playlist is already excluded");
  1290. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1291. next(
  1292. "This playlist is currently included, please remove it from there before excluding it"
  1293. );
  1294. else
  1295. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1296. .then(() => {
  1297. next(null);
  1298. })
  1299. .catch(next);
  1300. },
  1301. next => {
  1302. DBModule.runJob(
  1303. "GET_MODEL",
  1304. {
  1305. modelName: "station"
  1306. },
  1307. this
  1308. ).then(stationModel => {
  1309. stationModel.updateOne(
  1310. { _id: payload.stationId },
  1311. { $push: { excludedPlaylists: payload.playlistId } },
  1312. next
  1313. );
  1314. });
  1315. },
  1316. (res, next) => {
  1317. StationsModule.runJob(
  1318. "UPDATE_STATION",
  1319. {
  1320. stationId: payload.stationId
  1321. },
  1322. this
  1323. )
  1324. .then(() => {
  1325. next();
  1326. })
  1327. .catch(next);
  1328. }
  1329. ],
  1330. async err => {
  1331. if (err && err !== true) {
  1332. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1333. return reject(new Error(err));
  1334. }
  1335. return resolve();
  1336. }
  1337. );
  1338. });
  1339. }
  1340. /**
  1341. * Removes a playlist that is excluded in a station
  1342. *
  1343. * @param {object} payload - object that contains the payload
  1344. * @param {object} payload.stationId - the id of the station
  1345. * @param {object} payload.playlistId - the id of the playlist
  1346. * @returns {Promise} - returns a promise (resolve, reject)
  1347. */
  1348. REMOVE_EXCLUDED_PLAYLIST(payload) {
  1349. return new Promise((resolve, reject) => {
  1350. console.log(112, payload);
  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.excludedPlaylists.indexOf(payload.playlistId) === -1)
  1367. next("This playlist isn't excluded");
  1368. else next();
  1369. },
  1370. next => {
  1371. DBModule.runJob(
  1372. "GET_MODEL",
  1373. {
  1374. modelName: "station"
  1375. },
  1376. this
  1377. ).then(stationModel => {
  1378. stationModel.updateOne(
  1379. { _id: payload.stationId },
  1380. { $pull: { excludedPlaylists: payload.playlistId } },
  1381. next
  1382. );
  1383. });
  1384. },
  1385. (res, next) => {
  1386. StationsModule.runJob(
  1387. "UPDATE_STATION",
  1388. {
  1389. stationId: payload.stationId
  1390. },
  1391. this
  1392. )
  1393. .then(() => {
  1394. next();
  1395. })
  1396. .catch(next);
  1397. }
  1398. ],
  1399. async err => {
  1400. if (err && err !== true) {
  1401. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1402. return reject(new Error(err));
  1403. }
  1404. return resolve();
  1405. }
  1406. );
  1407. });
  1408. }
  1409. /**
  1410. * Gets stations that include or exclude a specific playlist
  1411. *
  1412. * @param {object} payload - object that contains the payload
  1413. * @param {string} payload.playlistId - the playlist id
  1414. * @returns {Promise} - returns promise (reject, resolve)
  1415. */
  1416. GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST(payload) {
  1417. return new Promise((resolve, reject) => {
  1418. DBModule.runJob(
  1419. "GET_MODEL",
  1420. {
  1421. modelName: "station"
  1422. },
  1423. this
  1424. ).then(stationModel => {
  1425. stationModel.find(
  1426. { $or: [{ includedPlaylists: payload.playlistId }, { excludedPlaylists: payload.playlistId }] },
  1427. (err, stations) => {
  1428. if (err) reject(err);
  1429. else resolve({ stationIds: stations.map(station => station._id) });
  1430. }
  1431. );
  1432. });
  1433. });
  1434. }
  1435. }
  1436. export default new _StationsModule();