stations.js 49 KB

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