stations.js 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211
  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") &&
  519. config.get("experimental.weight_stations").indexOf(stationId) !== -1
  520. ) {
  521. const weightMap = {};
  522. const getYoutubeIds = playlistSongs
  523. .map(playlistSong => playlistSong.youtubeId)
  524. .filter(youtubeId => currentYoutubeIds.indexOf(youtubeId) === -1);
  525. const { songs } = await SongsModule.runJob("GET_SONGS", { youtubeIds: getYoutubeIds });
  526. songs.forEach(song => {
  527. let weight = 1;
  528. song.tags.forEach(tag => {
  529. const regexResponse = /weight\[(\d+)\]/.exec(tag);
  530. if (regexResponse) weight = Number(regexResponse[1]);
  531. });
  532. if (Number.isNaN(weight)) weight = 1;
  533. weight = Math.round(weight);
  534. weight = Math.max(1, weight);
  535. weight = Math.min(10000, weight);
  536. weightMap[song.youtubeId] = weight;
  537. });
  538. const adjustedPlaylistSongs = [];
  539. playlistSongs.forEach(playlistSong => {
  540. Array.from({ length: weightMap[playlistSong.youtubeId] }).forEach(() => {
  541. adjustedPlaylistSongs.push(playlistSong);
  542. });
  543. });
  544. const { array } = await UtilsModule.runJob(
  545. "SHUFFLE",
  546. { array: adjustedPlaylistSongs },
  547. this
  548. );
  549. playlistSongs = array;
  550. }
  551. playlistSongs.every(song => {
  552. if (
  553. songsToAdd.length < songsStillNeeded &&
  554. currentYoutubeIds.indexOf(song.youtubeId) === -1
  555. ) {
  556. lastSongAdded = song;
  557. songsToAdd.push(song);
  558. return true;
  559. }
  560. if (songsToAdd.length >= songsStillNeeded) return false;
  561. return true;
  562. });
  563. let { currentSongIndex } = station;
  564. if (station.autofill.mode === "sequential" && lastSongAdded) {
  565. const indexOfLastSong = _playlistSongs
  566. .map(song => song.youtubeId)
  567. .indexOf(lastSongAdded.youtubeId);
  568. if (indexOfLastSong !== -1) currentSongIndex = indexOfLastSong;
  569. }
  570. return { currentSongs, songsToAdd, currentSongIndex };
  571. },
  572. ({ currentSongs, songsToAdd, currentSongIndex }, next) => {
  573. const songs = [];
  574. async.eachLimit(
  575. songsToAdd.map(song => song.youtubeId),
  576. 2,
  577. (youtubeId, next) => {
  578. MediaModule.runJob("GET_MEDIA", { youtubeId }, this)
  579. .then(response => {
  580. const { song } = response;
  581. const { _id, title, artists, thumbnail, duration, skipDuration, verified } =
  582. song;
  583. songs.push({
  584. _id,
  585. youtubeId,
  586. title,
  587. artists,
  588. thumbnail,
  589. duration,
  590. skipDuration,
  591. verified
  592. });
  593. next();
  594. })
  595. .catch(next);
  596. },
  597. err => {
  598. if (err) next(err);
  599. else {
  600. const newSongsToAdd = songsToAdd.map(song =>
  601. songs.find(newSong => newSong.youtubeId === song.youtubeId)
  602. );
  603. next(null, currentSongs, newSongsToAdd, currentSongIndex);
  604. }
  605. }
  606. );
  607. },
  608. (currentSongs, songsToAdd, currentSongIndex, next) => {
  609. const newPlaylist = [...currentSongs, ...songsToAdd].map(song => {
  610. if (!song._id) song._id = null;
  611. if (!song.requestedAt) song.requestedAt = Date.now();
  612. return song;
  613. });
  614. next(null, newPlaylist, currentSongIndex);
  615. },
  616. (newPlaylist, currentSongIndex, next) => {
  617. StationsModule.stationModel.updateOne(
  618. { _id: stationId },
  619. { $set: { queue: newPlaylist, currentSongIndex } },
  620. { runValidators: true },
  621. err => {
  622. if (err) next(err);
  623. else
  624. StationsModule.runJob(
  625. "UPDATE_STATION",
  626. {
  627. stationId
  628. },
  629. this
  630. )
  631. .then(() => {
  632. next(null);
  633. })
  634. .catch(next);
  635. }
  636. );
  637. }
  638. ],
  639. err => {
  640. if (err) reject(err);
  641. else resolve();
  642. }
  643. );
  644. });
  645. }
  646. /**
  647. * Gets next station song
  648. *
  649. * @param {object} payload - object that contains the payload
  650. * @param {string} payload.stationId - the id of the station
  651. * @returns {Promise} - returns a promise (resolve, reject)
  652. */
  653. GET_NEXT_STATION_SONG(payload) {
  654. return new Promise((resolve, reject) => {
  655. const { stationId } = payload;
  656. async.waterfall(
  657. [
  658. next => {
  659. StationsModule.runJob("GET_STATION", { stationId }, this)
  660. .then(station => {
  661. next(null, station);
  662. })
  663. .catch(next);
  664. },
  665. (station, next) => {
  666. if (station.queue.length === 0) next("No songs available.");
  667. else {
  668. next(null, station.queue[0]);
  669. }
  670. },
  671. (queueSong, next) => {
  672. MediaModule.runJob(
  673. "GET_MEDIA",
  674. {
  675. youtubeId: queueSong.youtubeId
  676. },
  677. this
  678. )
  679. .then(response => {
  680. const { song } = response;
  681. const { _id, youtubeId, title, skipDuration, artists, thumbnail, duration, verified } =
  682. song;
  683. next(null, {
  684. _id,
  685. youtubeId,
  686. title,
  687. skipDuration,
  688. artists,
  689. thumbnail,
  690. duration,
  691. verified,
  692. requestedAt: queueSong.requestedAt,
  693. requestedBy: queueSong.requestedBy,
  694. likes: song.likes || 0,
  695. dislikes: song.dislikes || 0
  696. });
  697. })
  698. .catch(next);
  699. }
  700. ],
  701. (err, song) => {
  702. if (err) reject(err);
  703. else resolve({ song });
  704. }
  705. );
  706. });
  707. }
  708. /**
  709. * Removes first station queue song
  710. *
  711. * @param {object} payload - object that contains the payload
  712. * @param {string} payload.stationId - the id of the station
  713. * @returns {Promise} - returns a promise (resolve, reject)
  714. */
  715. REMOVE_FIRST_QUEUE_SONG(payload) {
  716. return new Promise((resolve, reject) => {
  717. const { stationId } = payload;
  718. async.waterfall(
  719. [
  720. next => {
  721. StationsModule.stationModel.updateOne(
  722. { _id: stationId },
  723. { $pop: { queue: -1 } },
  724. { runValidators: true },
  725. err => {
  726. if (err) next(err);
  727. else
  728. StationsModule.runJob(
  729. "UPDATE_STATION",
  730. {
  731. stationId
  732. },
  733. this
  734. )
  735. .then(() => {
  736. next(null);
  737. })
  738. .catch(next);
  739. }
  740. );
  741. }
  742. ],
  743. err => {
  744. if (err) reject(err);
  745. else resolve();
  746. }
  747. );
  748. });
  749. }
  750. /**
  751. * Process vote to skips for a station
  752. *
  753. * @param {object} payload - object that contains the payload
  754. * @param {string} payload.stationId - the id of the station to process
  755. * @returns {Promise} - returns a promise (resolve, reject)
  756. */
  757. PROCESS_SKIP_VOTES(payload) {
  758. return new Promise((resolve, reject) => {
  759. StationsModule.log("INFO", `Processing skip votes for station ${payload.stationId}.`);
  760. async.waterfall(
  761. [
  762. next => {
  763. StationsModule.runJob(
  764. "GET_STATION",
  765. {
  766. stationId: payload.stationId
  767. },
  768. this
  769. )
  770. .then(station => next(null, station))
  771. .catch(next);
  772. },
  773. (station, next) => {
  774. if (!station) return next("Station not found.");
  775. return next(null, station);
  776. },
  777. (station, next) => {
  778. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }, this)
  779. .then(sockets => next(null, station, sockets))
  780. .catch(next);
  781. },
  782. (station, sockets, next) => {
  783. const skipVotes =
  784. station.currentSong && station.currentSong.skipVotes
  785. ? station.currentSong.skipVotes.length
  786. : 0;
  787. let shouldSkip = false;
  788. if (skipVotes === 0) {
  789. if (!station.paused && !station.currentSong && station.queue.length > 0) shouldSkip = true;
  790. return next(null, shouldSkip);
  791. }
  792. const users = [];
  793. return async.each(
  794. sockets,
  795. (socketId, next) => {
  796. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  797. .then(socket => {
  798. if (socket && socket.session && socket.session.userId) {
  799. if (!users.includes(socket.session.userId))
  800. users.push(socket.session.userId);
  801. }
  802. return next();
  803. })
  804. .catch(next);
  805. },
  806. err => {
  807. if (err) return next(err);
  808. if (!station.paused && users.length <= skipVotes) shouldSkip = true;
  809. return next(null, shouldSkip);
  810. }
  811. );
  812. },
  813. (shouldSkip, next) => {
  814. if (shouldSkip)
  815. StationsModule.runJob(
  816. "SKIP_STATION",
  817. {
  818. stationId: payload.stationId,
  819. natural: false
  820. },
  821. this
  822. )
  823. .then(() => next())
  824. .catch(next);
  825. else next();
  826. }
  827. ],
  828. err => {
  829. if (err) reject(err);
  830. else resolve();
  831. }
  832. );
  833. });
  834. }
  835. /**
  836. * Skips a station
  837. *
  838. * @param {object} payload - object that contains the payload
  839. * @param {string} payload.stationId - the id of the station to skip
  840. * @param {string} payload.natural - whether to skip naturally or forcefully
  841. * @returns {Promise} - returns a promise (resolve, reject)
  842. */
  843. SKIP_STATION(payload) {
  844. return new Promise((resolve, reject) => {
  845. StationsModule.log("INFO", `Skipping station ${payload.stationId}.`);
  846. StationsModule.log("STATION_ISSUE", `SKIP_STATION_CB - Station ID: ${payload.stationId}.`);
  847. async.waterfall(
  848. [
  849. // Clears up any existing timers that would skip the station if the song ends
  850. next => {
  851. NotificationsModule.runJob("UNSCHEDULE", {
  852. name: `stations.nextSong?id=${payload.stationId}`
  853. })
  854. .then(() => {
  855. next();
  856. })
  857. .catch(next);
  858. },
  859. // Gets the station object
  860. next => {
  861. StationsModule.runJob(
  862. "GET_STATION",
  863. {
  864. stationId: payload.stationId
  865. },
  866. this
  867. )
  868. .then(station => next(null, station))
  869. .catch(next);
  870. },
  871. (station, next) => {
  872. if (!station) return next("Station not found.");
  873. if (station.autofill.enabled)
  874. return StationsModule.runJob("AUTOFILL_STATION", { stationId: station._id }, this)
  875. .then(() => next(null, station))
  876. .catch(err => {
  877. if (
  878. err === "Autofill is disabled in this station" ||
  879. err === "Autofill limit reached"
  880. )
  881. return next(null, station);
  882. return next(err);
  883. });
  884. return next(null, station);
  885. },
  886. (station, next) => {
  887. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  888. .then(response => {
  889. StationsModule.runJob("REMOVE_FIRST_QUEUE_SONG", { stationId: station._id }, this)
  890. .then(() => {
  891. next(null, response.song, station);
  892. })
  893. .catch(next);
  894. })
  895. .catch(err => {
  896. if (err === "No songs available.") next(null, null, station);
  897. else next(err);
  898. });
  899. },
  900. async (song, station) => {
  901. const $set = {};
  902. if (song === null) $set.currentSong = null;
  903. else {
  904. // Block for experiment: queue_autofill_skip_last_x_played
  905. if (config.has(`experimental.queue_autofill_skip_last_x_played.${payload.stationId}`)) {
  906. const redisList = `experimental:queue_autofill_skip_last_x_played:${payload.stationId}`;
  907. const maxListLength = Number(
  908. config.get(`experimental.queue_autofill_skip_last_x_played.${payload.stationId}`)
  909. );
  910. // Add youtubeId to list for this station in Redis list
  911. await CacheModule.runJob(
  912. "LPUSH",
  913. {
  914. key: `experimental:queue_autofill_skip_last_x_played:${payload.stationId}`,
  915. value: song.youtubeId
  916. },
  917. this
  918. );
  919. const currentListLength = await CacheModule.runJob("LLEN", { key: redisList }, this);
  920. // Removes oldest youtubeId from list for this station in Redis list
  921. if (currentListLength > maxListLength) {
  922. const amount = currentListLength - maxListLength;
  923. const promises = Array.from({ length: amount }).map(() =>
  924. CacheModule.runJob(
  925. "RPOP",
  926. {
  927. key: `experimental:queue_autofill_skip_last_x_played:${payload.stationId}`
  928. },
  929. this
  930. )
  931. );
  932. await Promise.all(promises);
  933. }
  934. }
  935. $set.currentSong = {
  936. _id: song._id,
  937. youtubeId: song.youtubeId,
  938. title: song.title,
  939. artists: song.artists,
  940. duration: song.duration,
  941. skipDuration: song.skipDuration,
  942. thumbnail: song.thumbnail,
  943. requestedAt: song.requestedAt,
  944. requestedBy: song.requestedBy,
  945. verified: song.verified
  946. };
  947. }
  948. $set.startedAt = Date.now();
  949. $set.timePaused = 0;
  950. if (station.paused) $set.pausedAt = Date.now();
  951. return { $set, station };
  952. },
  953. ({ $set, station }, next) => {
  954. StationsModule.stationModel.updateOne({ _id: station._id }, { $set }, err => {
  955. if (err) return next(err);
  956. return StationsModule.runJob("UPDATE_STATION", { stationId: station._id }, this)
  957. .then(station => {
  958. next(null, station);
  959. })
  960. .catch(next);
  961. });
  962. },
  963. (station, next) => {
  964. if (station.currentSong !== null && station.currentSong.youtubeId !== undefined) {
  965. station.currentSong.skipVotes = 0;
  966. }
  967. next(null, station);
  968. },
  969. (station, next) => {
  970. if (station.autofill.enabled)
  971. return StationsModule.runJob("AUTOFILL_STATION", { stationId: station._id }, this)
  972. .then(() => next(null, station))
  973. .catch(err => {
  974. if (
  975. err === "Autofill is disabled in this station" ||
  976. err === "Autofill limit reached"
  977. )
  978. return next(null, station);
  979. return next(err);
  980. });
  981. return next(null, station);
  982. },
  983. (station, next) =>
  984. StationsModule.runJob("UPDATE_STATION", { stationId: station._id }, this)
  985. .then(station => {
  986. CacheModule.runJob("PUB", {
  987. channel: "station.queueUpdate",
  988. value: payload.stationId
  989. })
  990. .then()
  991. .catch();
  992. next(null, station);
  993. })
  994. .catch(next)
  995. ],
  996. async (err, station) => {
  997. if (err === "Autofill limit reached") return resolve({ station });
  998. if (err) {
  999. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1000. StationsModule.log("ERROR", `Skipping station "${payload.stationId}" failed. "${err}"`);
  1001. return reject(new Error(err));
  1002. }
  1003. // TODO Pub/Sub this
  1004. const { currentSong } = station;
  1005. WSModule.runJob("EMIT_TO_ROOM", {
  1006. room: `station.${station._id}`,
  1007. args: [
  1008. "event:station.nextSong",
  1009. {
  1010. data: {
  1011. currentSong,
  1012. startedAt: station.startedAt,
  1013. paused: station.paused,
  1014. timePaused: 0,
  1015. natural: payload.natural
  1016. }
  1017. }
  1018. ]
  1019. });
  1020. WSModule.runJob("EMIT_TO_ROOM", {
  1021. room: `manage-station.${station._id}`,
  1022. args: ["event:station.nextSong", { data: { stationId: station._id, currentSong } }]
  1023. });
  1024. if (station.privacy === "public")
  1025. WSModule.runJob("EMIT_TO_ROOM", {
  1026. room: "home",
  1027. args: ["event:station.nextSong", { data: { stationId: station._id, currentSong } }]
  1028. });
  1029. else {
  1030. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: "home" }, this);
  1031. sockets.forEach(async socketId => {
  1032. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId });
  1033. if (!socket) return;
  1034. const { session } = socket;
  1035. if (session.sessionId) {
  1036. CacheModule.runJob("HGET", { table: "sessions", key: session.sessionId }).then(
  1037. session => {
  1038. const dispatchNextSong = () => {
  1039. socket.dispatch("event:station.nextSong", {
  1040. data: {
  1041. stationId: station._id,
  1042. currentSong
  1043. }
  1044. });
  1045. };
  1046. hasPermission("stations.index", session, station._id)
  1047. .then(() => dispatchNextSong())
  1048. .catch(() => {
  1049. hasPermission("stations.index.other", session)
  1050. .then(() => dispatchNextSong())
  1051. .catch(() => {});
  1052. });
  1053. }
  1054. );
  1055. }
  1056. });
  1057. }
  1058. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }).then(sockets => {
  1059. if (station.currentSong !== null && station.currentSong.youtubeId !== undefined) {
  1060. WSModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  1061. sockets,
  1062. room: `song.${station.currentSong.youtubeId}`
  1063. });
  1064. if (!station.paused) {
  1065. NotificationsModule.runJob("SCHEDULE", {
  1066. name: `stations.nextSong?id=${station._id}`,
  1067. time: station.currentSong.duration * 1000,
  1068. station
  1069. });
  1070. }
  1071. } else WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", { sockets });
  1072. });
  1073. return resolve({ station });
  1074. }
  1075. );
  1076. });
  1077. }
  1078. /**
  1079. * Checks if a user can view/access a station
  1080. *
  1081. * @param {object} payload - object that contains the payload
  1082. * @param {object} payload.station - the station object of the station in question
  1083. * @param {string} payload.userId - the id of the user in question
  1084. * @returns {Promise} - returns a promise (resolve, reject)
  1085. */
  1086. CAN_USER_VIEW_STATION(payload) {
  1087. return new Promise((resolve, reject) => {
  1088. async.waterfall(
  1089. [
  1090. next => {
  1091. if (payload.station.privacy === "public" || payload.station.privacy === "unlisted")
  1092. return next(true);
  1093. if (!payload.userId) return next("Not allowed");
  1094. return next();
  1095. },
  1096. next => {
  1097. hasPermission("stations.view", payload.userId, payload.station._id)
  1098. .then(() => next(true))
  1099. .catch(() => 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. if (!(socket.session && socket.session.sessionId)) {
  1192. socketsThatCannot.push(socket);
  1193. next();
  1194. } else
  1195. hasPermission("stations.view", socket.session, payload.station._id)
  1196. .then(() => {
  1197. socketsThatCan.push(socket);
  1198. next();
  1199. })
  1200. .catch(() => {
  1201. socketsThatCannot.push(socket);
  1202. next();
  1203. });
  1204. },
  1205. err => {
  1206. if (err) reject(err);
  1207. else resolve({ socketsThatCan, socketsThatCannot });
  1208. }
  1209. );
  1210. }
  1211. }
  1212. }
  1213. );
  1214. })
  1215. .catch(reject);
  1216. });
  1217. }
  1218. /**
  1219. * Adds a playlist to autofill a station
  1220. *
  1221. * @param {object} payload - object that contains the payload
  1222. * @param {object} payload.stationId - the id of the station
  1223. * @param {object} payload.playlistId - the id of the playlist
  1224. * @returns {Promise} - returns a promise (resolve, reject)
  1225. */
  1226. AUTOFILL_PLAYLIST(payload) {
  1227. return new Promise((resolve, reject) => {
  1228. async.waterfall(
  1229. [
  1230. next => {
  1231. if (!payload.stationId) next("Please specify a station id");
  1232. else if (!payload.playlistId) next("Please specify a playlist id");
  1233. else next();
  1234. },
  1235. next => {
  1236. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1237. .then(station => {
  1238. next(null, station);
  1239. })
  1240. .catch(next);
  1241. },
  1242. (station, next) => {
  1243. if (station.playlist === payload.playlistId) next("You cannot autofill the station playlist");
  1244. else if (station.autofill.playlists.indexOf(payload.playlistId) !== -1)
  1245. next("This playlist is already autofilling");
  1246. else if (station.blacklist.indexOf(payload.playlistId) !== -1)
  1247. next("This playlist is currently blacklisted");
  1248. else
  1249. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1250. .then(() => {
  1251. next(null);
  1252. })
  1253. .catch(next);
  1254. },
  1255. next => {
  1256. StationsModule.stationModel.updateOne(
  1257. { _id: payload.stationId },
  1258. { $push: { "autofill.playlists": payload.playlistId } },
  1259. next
  1260. );
  1261. },
  1262. (res, next) => {
  1263. StationsModule.runJob(
  1264. "UPDATE_STATION",
  1265. {
  1266. stationId: payload.stationId
  1267. },
  1268. this
  1269. )
  1270. .then(() => {
  1271. next();
  1272. })
  1273. .catch(next);
  1274. }
  1275. ],
  1276. async err => {
  1277. if (err && err !== true) {
  1278. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1279. return reject(new Error(err));
  1280. }
  1281. return resolve();
  1282. }
  1283. );
  1284. });
  1285. }
  1286. /**
  1287. * Removes a playlist from autofill
  1288. *
  1289. * @param {object} payload - object that contains the payload
  1290. * @param {object} payload.stationId - the id of the station
  1291. * @param {object} payload.playlistId - the id of the playlist
  1292. * @returns {Promise} - returns a promise (resolve, reject)
  1293. */
  1294. REMOVE_AUTOFILL_PLAYLIST(payload) {
  1295. return new Promise((resolve, reject) => {
  1296. async.waterfall(
  1297. [
  1298. next => {
  1299. if (!payload.stationId) next("Please specify a station id");
  1300. else if (!payload.playlistId) next("Please specify a playlist id");
  1301. else next();
  1302. },
  1303. next => {
  1304. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1305. .then(station => {
  1306. next(null, station);
  1307. })
  1308. .catch(next);
  1309. },
  1310. (station, next) => {
  1311. if (station.autofill.playlists.indexOf(payload.playlistId) === -1)
  1312. next("This playlist isn't autofilling");
  1313. else next();
  1314. },
  1315. next => {
  1316. StationsModule.stationModel.updateOne(
  1317. { _id: payload.stationId },
  1318. { $pull: { "autofill.playlists": payload.playlistId } },
  1319. next
  1320. );
  1321. },
  1322. (res, next) => {
  1323. StationsModule.runJob(
  1324. "UPDATE_STATION",
  1325. {
  1326. stationId: payload.stationId
  1327. },
  1328. this
  1329. )
  1330. .then(() => {
  1331. next();
  1332. })
  1333. .catch(next);
  1334. }
  1335. ],
  1336. async err => {
  1337. if (err && err !== true) {
  1338. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1339. return reject(new Error(err));
  1340. }
  1341. return resolve();
  1342. }
  1343. );
  1344. });
  1345. }
  1346. /**
  1347. * Add a playlist to station blacklist
  1348. *
  1349. * @param {object} payload - object that contains the payload
  1350. * @param {object} payload.stationId - the id of the station
  1351. * @param {object} payload.playlistId - the id of the playlist
  1352. * @returns {Promise} - returns a promise (resolve, reject)
  1353. */
  1354. BLACKLIST_PLAYLIST(payload) {
  1355. return new Promise((resolve, reject) => {
  1356. async.waterfall(
  1357. [
  1358. next => {
  1359. if (!payload.stationId) next("Please specify a station id");
  1360. else if (!payload.playlistId) next("Please specify a playlist id");
  1361. else next();
  1362. },
  1363. next => {
  1364. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1365. .then(station => {
  1366. next(null, station);
  1367. })
  1368. .catch(next);
  1369. },
  1370. (station, next) => {
  1371. if (station.playlist === payload.playlistId) next("You cannot blacklist the station playlist");
  1372. else if (station.blacklist.indexOf(payload.playlistId) !== -1)
  1373. next("This playlist is already blacklisted");
  1374. else if (station.autofill.playlists.indexOf(payload.playlistId) !== -1)
  1375. next(
  1376. "This playlist is currently autofilling, please remove it from there before blacklisting it"
  1377. );
  1378. else
  1379. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1380. .then(() => {
  1381. next(null);
  1382. })
  1383. .catch(next);
  1384. },
  1385. next => {
  1386. StationsModule.stationModel.updateOne(
  1387. { _id: payload.stationId },
  1388. { $push: { blacklist: payload.playlistId } },
  1389. next
  1390. );
  1391. },
  1392. (res, next) => {
  1393. StationsModule.runJob(
  1394. "UPDATE_STATION",
  1395. {
  1396. stationId: payload.stationId
  1397. },
  1398. this
  1399. )
  1400. .then(() => {
  1401. next();
  1402. })
  1403. .catch(next);
  1404. }
  1405. ],
  1406. async err => {
  1407. if (err && err !== true) {
  1408. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1409. return reject(new Error(err));
  1410. }
  1411. return resolve();
  1412. }
  1413. );
  1414. });
  1415. }
  1416. /**
  1417. * Remove a playlist from station blacklist
  1418. *
  1419. * @param {object} payload - object that contains the payload
  1420. * @param {object} payload.stationId - the id of the station
  1421. * @param {object} payload.playlistId - the id of the playlist
  1422. * @returns {Promise} - returns a promise (resolve, reject)
  1423. */
  1424. REMOVE_BLACKLISTED_PLAYLIST(payload) {
  1425. return new Promise((resolve, reject) => {
  1426. async.waterfall(
  1427. [
  1428. next => {
  1429. if (!payload.stationId) next("Please specify a station id");
  1430. else if (!payload.playlistId) next("Please specify a playlist id");
  1431. else next();
  1432. },
  1433. next => {
  1434. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1435. .then(station => {
  1436. next(null, station);
  1437. })
  1438. .catch(next);
  1439. },
  1440. (station, next) => {
  1441. if (station.blacklist.indexOf(payload.playlistId) === -1)
  1442. next("This playlist isn't blacklisted");
  1443. else next();
  1444. },
  1445. next => {
  1446. StationsModule.stationModel.updateOne(
  1447. { _id: payload.stationId },
  1448. { $pull: { blacklist: payload.playlistId } },
  1449. next
  1450. );
  1451. },
  1452. (res, next) => {
  1453. StationsModule.runJob(
  1454. "UPDATE_STATION",
  1455. {
  1456. stationId: payload.stationId
  1457. },
  1458. this
  1459. )
  1460. .then(() => {
  1461. next();
  1462. })
  1463. .catch(next);
  1464. }
  1465. ],
  1466. async err => {
  1467. if (err && err !== true) {
  1468. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1469. return reject(new Error(err));
  1470. }
  1471. return resolve();
  1472. }
  1473. );
  1474. });
  1475. }
  1476. /**
  1477. * Removes autofilled or blacklisted playlist from a station
  1478. *
  1479. * @param {object} payload - object that contains the payload
  1480. * @param {string} payload.playlistId - the playlist id
  1481. * @returns {Promise} - returns promise (reject, resolve)
  1482. */
  1483. REMOVE_AUTOFILLED_OR_BLACKLISTED_PLAYLIST_FROM_STATIONS(payload) {
  1484. return new Promise((resolve, reject) => {
  1485. async.waterfall(
  1486. [
  1487. next => {
  1488. if (!payload.playlistId) next("Please specify a playlist id");
  1489. else next();
  1490. },
  1491. next => {
  1492. StationsModule.stationModel.updateMany(
  1493. {
  1494. $or: [{ "autofill.playlists": payload.playlistId }, { blacklist: payload.playlistId }]
  1495. },
  1496. {
  1497. $pull: {
  1498. "autofill.playlists": payload.playlistId,
  1499. blacklist: payload.playlistId
  1500. }
  1501. },
  1502. err => {
  1503. if (err) next(err);
  1504. else next();
  1505. }
  1506. );
  1507. }
  1508. ],
  1509. async err => {
  1510. if (err && err !== true) {
  1511. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1512. return reject(new Error(err));
  1513. }
  1514. return resolve();
  1515. }
  1516. );
  1517. });
  1518. }
  1519. /**
  1520. * Gets stations that autofill or blacklist a specific playlist
  1521. *
  1522. * @param {object} payload - object that contains the payload
  1523. * @param {string} payload.playlistId - the playlist id
  1524. * @returns {Promise} - returns promise (reject, resolve)
  1525. */
  1526. GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST(payload) {
  1527. return new Promise((resolve, reject) => {
  1528. DBModule.runJob(
  1529. "GET_MODEL",
  1530. {
  1531. modelName: "station"
  1532. },
  1533. this
  1534. ).then(stationModel => {
  1535. stationModel.find(
  1536. {
  1537. $or: [{ "autofill.playlists": payload.playlistId }, { blacklist: payload.playlistId }]
  1538. },
  1539. (err, stations) => {
  1540. if (err) reject(err);
  1541. else resolve({ stationIds: stations.map(station => station._id) });
  1542. }
  1543. );
  1544. });
  1545. });
  1546. }
  1547. /**
  1548. * Clears every queue
  1549. *
  1550. * @returns {Promise} - returns a promise (resolve, reject)
  1551. */
  1552. CLEAR_EVERY_STATION_QUEUE() {
  1553. return new Promise((resolve, reject) => {
  1554. async.waterfall(
  1555. [
  1556. next => {
  1557. StationsModule.stationModel.updateMany({}, { $set: { queue: [] } }, err => {
  1558. if (err) next(err);
  1559. else {
  1560. StationsModule.stationModel.find({}, (err, stations) => {
  1561. if (err) next(err);
  1562. else {
  1563. async.eachLimit(
  1564. stations,
  1565. 1,
  1566. (station, next) => {
  1567. this.publishProgress({
  1568. status: "update",
  1569. message: `Updating station "${station._id}"`
  1570. });
  1571. StationsModule.runJob("UPDATE_STATION", {
  1572. stationId: station._id
  1573. })
  1574. .then(() => next())
  1575. .catch(next);
  1576. CacheModule.runJob("PUB", {
  1577. channel: "station.queueUpdate",
  1578. value: station._id
  1579. })
  1580. .then()
  1581. .catch();
  1582. },
  1583. next
  1584. );
  1585. }
  1586. });
  1587. }
  1588. });
  1589. }
  1590. ],
  1591. err => {
  1592. if (err) reject(err);
  1593. else resolve();
  1594. }
  1595. );
  1596. });
  1597. }
  1598. /**
  1599. * Resets a station queue
  1600. *
  1601. * @param {object} payload - object that contains the payload
  1602. * @param {string} payload.stationId - the station id
  1603. * @returns {Promise} - returns a promise (resolve, reject)
  1604. */
  1605. RESET_QUEUE(payload) {
  1606. return new Promise((resolve, reject) => {
  1607. async.waterfall(
  1608. [
  1609. next => {
  1610. StationsModule.runJob(
  1611. "AUTOFILL_STATION",
  1612. { stationId: payload.stationId, ignoreExistingQueue: true },
  1613. this
  1614. )
  1615. .then(() => {
  1616. CacheModule.runJob("PUB", {
  1617. channel: "station.queueUpdate",
  1618. value: payload.stationId
  1619. })
  1620. .then()
  1621. .catch();
  1622. next();
  1623. })
  1624. .catch(err => {
  1625. if (err === "Autofill is disabled in this station" || err === "Autofill limit reached")
  1626. StationsModule.stationModel
  1627. .updateOne({ _id: payload.stationId }, { $set: { queue: [] } }, this)
  1628. .then(() => next())
  1629. .catch(next);
  1630. else next(err);
  1631. });
  1632. },
  1633. next => {
  1634. StationsModule.runJob("UPDATE_STATION", { stationId: payload.stationId }, this)
  1635. .then(() => next())
  1636. .catch(next);
  1637. },
  1638. next => {
  1639. CacheModule.runJob("PUB", {
  1640. channel: "station.queueUpdate",
  1641. value: payload.stationId
  1642. })
  1643. .then(() => next())
  1644. .catch(next);
  1645. }
  1646. ],
  1647. err => {
  1648. if (err) reject(err);
  1649. else resolve();
  1650. }
  1651. );
  1652. });
  1653. }
  1654. /**
  1655. * Add to a station queue
  1656. *
  1657. * @param {object} payload - object that contains the payload
  1658. * @param {string} payload.stationId - the station id
  1659. * @param {string} payload.youtubeId - the youtube id
  1660. * @param {string} payload.requestUser - the requesting user id
  1661. * @returns {Promise} - returns a promise (resolve, reject)
  1662. */
  1663. ADD_TO_QUEUE(payload) {
  1664. return new Promise((resolve, reject) => {
  1665. const { stationId, youtubeId, requestUser } = payload;
  1666. async.waterfall(
  1667. [
  1668. next => {
  1669. StationsModule.runJob("GET_STATION", { stationId }, this)
  1670. .then(station => {
  1671. next(null, station);
  1672. })
  1673. .catch(next);
  1674. },
  1675. (station, next) => {
  1676. if (!station) return next("Station not found.");
  1677. if (!station.requests.enabled) return next("Requests are disabled in this station.");
  1678. if (station.currentSong && station.currentSong.youtubeId === youtubeId)
  1679. return next("That song is currently playing.");
  1680. if (station.queue.find(song => song.youtubeId === youtubeId))
  1681. return next("That song is already in the queue.");
  1682. return next(null, station);
  1683. },
  1684. (station, next) => {
  1685. MediaModule.runJob("GET_MEDIA", { youtubeId }, this)
  1686. .then(response => {
  1687. const { song } = response;
  1688. const { _id, title, skipDuration, artists, thumbnail, duration, verified } = song;
  1689. next(
  1690. null,
  1691. {
  1692. _id,
  1693. youtubeId,
  1694. title,
  1695. skipDuration,
  1696. artists,
  1697. thumbnail,
  1698. duration,
  1699. verified
  1700. },
  1701. station
  1702. );
  1703. })
  1704. .catch(next);
  1705. },
  1706. (song, station, next) => {
  1707. const blacklist = [];
  1708. async.eachLimit(
  1709. station.blacklist,
  1710. 1,
  1711. (playlistId, next) => {
  1712. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1713. .then(playlist => {
  1714. blacklist.push(playlist);
  1715. next();
  1716. })
  1717. .catch(next);
  1718. },
  1719. err => {
  1720. next(err, song, station, blacklist);
  1721. }
  1722. );
  1723. },
  1724. (song, station, blacklist, next) => {
  1725. const blacklistedSongs = blacklist
  1726. .flatMap(blacklistedPlaylist => blacklistedPlaylist.songs)
  1727. .reduce(
  1728. (items, item) =>
  1729. items.find(x => x.youtubeId === item.youtubeId) ? [...items] : [...items, item],
  1730. []
  1731. );
  1732. if (blacklistedSongs.find(blacklistedSong => blacklistedSong.youtubeId === song.youtubeId))
  1733. next("That song is in an blacklisted playlist and cannot be played.");
  1734. else next(null, song, station);
  1735. },
  1736. (song, station, next) => {
  1737. song.requestedBy = requestUser;
  1738. song.requestedAt = Date.now();
  1739. if (station.queue.length === 0) return next(null, song, station);
  1740. if (
  1741. requestUser &&
  1742. station.queue.filter(queueSong => queueSong.requestedBy === song.requestedBy).length >=
  1743. station.requests.limit
  1744. )
  1745. return next(`The max amount of songs per user is ${station.requests.limit}.`);
  1746. return next(null, song, station);
  1747. },
  1748. // (song, station, next) => {
  1749. // song.requestedBy = session.userId;
  1750. // song.requestedAt = Date.now();
  1751. // let totalDuration = 0;
  1752. // station.queue.forEach(song => {
  1753. // totalDuration += song.duration;
  1754. // });
  1755. // if (totalDuration >= 3600 * 3) return next("The max length of the queue is 3 hours.");
  1756. // return next(null, song, station);
  1757. // },
  1758. // (song, station, next) => {
  1759. // if (station.queue.length === 0) return next(null, song, station);
  1760. // let totalDuration = 0;
  1761. // const userId = station.queue[station.queue.length - 1].requestedBy;
  1762. // station.queue.forEach(song => {
  1763. // if (userId === song.requestedBy) {
  1764. // totalDuration += song.duration;
  1765. // }
  1766. // });
  1767. // if (totalDuration >= 900) return next("The max length of songs per user is 15 minutes.");
  1768. // return next(null, song, station);
  1769. // },
  1770. // (song, station, next) => {
  1771. // if (station.queue.length === 0) return next(null, song);
  1772. // let totalSongs = 0;
  1773. // const userId = station.queue[station.queue.length - 1].requestedBy;
  1774. // station.queue.forEach(song => {
  1775. // if (userId === song.requestedBy) {
  1776. // totalSongs += 1;
  1777. // }
  1778. // });
  1779. // if (totalSongs <= 2) return next(null, song);
  1780. // if (totalSongs > 3)
  1781. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1782. // if (
  1783. // station.queue[station.queue.length - 2].requestedBy !== userId ||
  1784. // station.queue[station.queue.length - 3] !== userId
  1785. // )
  1786. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1787. // return next(null, song);
  1788. // },
  1789. (song, station, next) => {
  1790. if (config.has(`experimental.queue_add_before_autofilled`)) {
  1791. const queueAddBeforeAutofilled = config.get(`experimental.queue_add_before_autofilled`);
  1792. if (
  1793. queueAddBeforeAutofilled === true ||
  1794. queueAddBeforeAutofilled.indexOf(stationId) !== -1
  1795. ) {
  1796. let position = station.queue.length;
  1797. if (station.autofill.enabled && station.queue.length >= station.autofill.limit) {
  1798. position = -station.autofill.limit;
  1799. }
  1800. StationsModule.stationModel.updateOne(
  1801. { _id: stationId },
  1802. {
  1803. $push: {
  1804. queue: {
  1805. $each: [song],
  1806. $position: position
  1807. }
  1808. }
  1809. },
  1810. { runValidators: true },
  1811. next
  1812. );
  1813. return;
  1814. }
  1815. }
  1816. StationsModule.stationModel.updateOne(
  1817. { _id: stationId },
  1818. { $push: { queue: song } },
  1819. { runValidators: true },
  1820. next
  1821. );
  1822. },
  1823. (res, next) => {
  1824. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1825. .then(() => next())
  1826. .catch(next);
  1827. },
  1828. next => {
  1829. CacheModule.runJob(
  1830. "PUB",
  1831. {
  1832. channel: "station.queueUpdate",
  1833. value: stationId
  1834. },
  1835. this
  1836. )
  1837. .then(() => next())
  1838. .catch(next);
  1839. }
  1840. ],
  1841. err => {
  1842. if (err) reject(err);
  1843. else resolve();
  1844. }
  1845. );
  1846. });
  1847. }
  1848. /**
  1849. * Remove from a station queue
  1850. *
  1851. * @param {object} payload - object that contains the payload
  1852. * @param {string} payload.stationId - the station id
  1853. * @param {string} payload.youtubeId - the youtube id
  1854. * @returns {Promise} - returns a promise (resolve, reject)
  1855. */
  1856. REMOVE_FROM_QUEUE(payload) {
  1857. return new Promise((resolve, reject) => {
  1858. const { stationId, youtubeId } = payload;
  1859. async.waterfall(
  1860. [
  1861. next => {
  1862. StationsModule.runJob("GET_STATION", { stationId }, this)
  1863. .then(station => {
  1864. next(null, station);
  1865. })
  1866. .catch(next);
  1867. },
  1868. (station, next) => {
  1869. if (!station) return next("Station not found.");
  1870. if (!station.queue.find(song => song.youtubeId === youtubeId))
  1871. return next("That song is not currently in the queue.");
  1872. return StationsModule.stationModel.updateOne(
  1873. { _id: stationId },
  1874. { $pull: { queue: { youtubeId } } },
  1875. next
  1876. );
  1877. },
  1878. (res, next) => {
  1879. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1880. .then(station => {
  1881. if (station.autofill.enabled)
  1882. StationsModule.runJob("AUTOFILL_STATION", { stationId }, this)
  1883. .then(() => next())
  1884. .catch(err => {
  1885. if (
  1886. err === "Autofill is disabled in this station" ||
  1887. err === "Autofill limit reached"
  1888. )
  1889. return next();
  1890. return next(err);
  1891. });
  1892. else next();
  1893. })
  1894. .catch(next);
  1895. },
  1896. next =>
  1897. CacheModule.runJob(
  1898. "PUB",
  1899. {
  1900. channel: "station.queueUpdate",
  1901. value: stationId
  1902. },
  1903. this
  1904. )
  1905. .then(() => next())
  1906. .catch(next)
  1907. ],
  1908. err => {
  1909. if (err) reject(err);
  1910. else resolve();
  1911. }
  1912. );
  1913. });
  1914. }
  1915. /**
  1916. * Add DJ to station
  1917. *
  1918. * @param {object} payload - object that contains the payload
  1919. * @param {string} payload.stationId - the station id
  1920. * @param {string} payload.userId - the dj user id
  1921. * @returns {Promise} - returns a promise (resolve, reject)
  1922. */
  1923. ADD_DJ(payload) {
  1924. return new Promise((resolve, reject) => {
  1925. const { stationId, userId } = payload;
  1926. async.waterfall(
  1927. [
  1928. next => {
  1929. StationsModule.runJob("GET_STATION", { stationId }, this)
  1930. .then(station => {
  1931. next(null, station);
  1932. })
  1933. .catch(next);
  1934. },
  1935. (station, next) => {
  1936. if (!station) return next("Station not found.");
  1937. if (station.djs.find(dj => dj === userId)) return next("That user is already a DJ.");
  1938. return StationsModule.stationModel.updateOne(
  1939. { _id: stationId },
  1940. { $push: { djs: userId } },
  1941. next
  1942. );
  1943. },
  1944. (res, next) => {
  1945. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1946. .then(() => next())
  1947. .catch(next);
  1948. },
  1949. next =>
  1950. CacheModule.runJob(
  1951. "PUB",
  1952. {
  1953. channel: "station.djs.added",
  1954. value: { stationId, userId }
  1955. },
  1956. this
  1957. )
  1958. .then(() => next())
  1959. .catch(next)
  1960. ],
  1961. err => {
  1962. if (err) reject(err);
  1963. else resolve();
  1964. }
  1965. );
  1966. });
  1967. }
  1968. /**
  1969. * Remove DJ from station
  1970. *
  1971. * @param {object} payload - object that contains the payload
  1972. * @param {string} payload.stationId - the station id
  1973. * @param {string} payload.userId - the dj user id
  1974. * @returns {Promise} - returns a promise (resolve, reject)
  1975. */
  1976. REMOVE_DJ(payload) {
  1977. return new Promise((resolve, reject) => {
  1978. const { stationId, userId } = payload;
  1979. async.waterfall(
  1980. [
  1981. next => {
  1982. StationsModule.runJob("GET_STATION", { stationId }, this)
  1983. .then(station => {
  1984. next(null, station);
  1985. })
  1986. .catch(next);
  1987. },
  1988. (station, next) => {
  1989. if (!station) return next("Station not found.");
  1990. if (!station.djs.find(dj => dj === userId)) return next("That user is not currently a DJ.");
  1991. return StationsModule.stationModel.updateOne(
  1992. { _id: stationId },
  1993. { $pull: { djs: userId } },
  1994. next
  1995. );
  1996. },
  1997. (res, next) => {
  1998. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1999. .then(() => next())
  2000. .catch(next);
  2001. },
  2002. next =>
  2003. CacheModule.runJob(
  2004. "PUB",
  2005. {
  2006. channel: "station.djs.removed",
  2007. value: { stationId, userId }
  2008. },
  2009. this
  2010. )
  2011. .then(() => next())
  2012. .catch(next)
  2013. ],
  2014. err => {
  2015. if (err) reject(err);
  2016. else resolve();
  2017. }
  2018. );
  2019. });
  2020. }
  2021. }
  2022. export default new _StationsModule();