stations.js 58 KB

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