stations.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. 'use strict';
  2. const cache = require('./cache');
  3. const db = require('./db');
  4. const io = require('./io');
  5. const utils = require('./utils');
  6. const logger = require('./logger');
  7. const songs = require('./songs');
  8. const notifications = require('./notifications');
  9. const async = require('async');
  10. //TEMP
  11. cache.sub('station.pause', (stationId) => {
  12. notifications.remove(`stations.nextSong?id=${stationId}`);
  13. });
  14. cache.sub('station.resume', (stationId) => {
  15. module.exports.initializeStation(stationId)
  16. });
  17. cache.sub('station.queueUpdate', (stationId) => {
  18. module.exports.getStation(stationId, (err, station) => {
  19. if (!station.currentSong && station.queue.length > 0) {
  20. module.exports.initializeStation(stationId);
  21. }
  22. });
  23. });
  24. cache.sub('station.newOfficialPlaylist', (stationId) => {
  25. cache.hget("officialPlaylists", stationId, (err, playlistObj) => {
  26. if (!err && playlistObj) {
  27. utils.emitToRoom(`station.${stationId}`, "event:newOfficialPlaylist", playlistObj.songs);
  28. }
  29. })
  30. });
  31. module.exports = {
  32. init: function(cb) {
  33. async.waterfall([
  34. (next) => {
  35. cache.hgetall('stations', next);
  36. },
  37. (stations, next) => {
  38. if (!stations) return next();
  39. let stationIds = Object.keys(stations);
  40. async.each(stationIds, (stationId, next) => {
  41. db.models.station.findOne({_id: stationId}, (err, station) => {
  42. if (err) next(err);
  43. else if (!station) {
  44. cache.hdel('stations', stationId, next);
  45. } else next();
  46. });
  47. }, next);
  48. },
  49. (next) => {
  50. db.models.station.find({}, next);
  51. },
  52. (stations, next) => {
  53. async.each(stations, (station, next) => {
  54. async.waterfall([
  55. (next) => {
  56. cache.hset('stations', station._id, cache.schemas.station(station), next);
  57. },
  58. (station, next) => {
  59. this.initializeStation(station._id, next);
  60. }
  61. ], (err) => {
  62. next(err);
  63. });
  64. }, next);
  65. }
  66. ], (err) => {
  67. if (err) {
  68. console.log(`FAILED TO INITIALIZE STATIONS. ABORTING. "${err.message}"`);
  69. process.exit();
  70. } else cb();
  71. });
  72. },
  73. initializeStation: function(stationId, cb) {
  74. if (typeof cb !== 'function') cb = () => {};
  75. async.waterfall([
  76. (next) => {
  77. this.getStation(stationId, next);
  78. },
  79. (station, next) => {
  80. if (!station) return next('Station not found.');
  81. if (station.type === 'official') {
  82. cache.hget('officialPlaylists', stationId, (err, playlist) => {
  83. if (err) return next(err);
  84. if (playlist) return next(null, station, null);
  85. next(null, station, playlist);
  86. });
  87. } else next(null, station, null);
  88. },
  89. (station, playlist, next) => {
  90. if (playlist) {
  91. this.calculateOfficialPlaylistList(stationId, station.playlist, () => {
  92. next(station);
  93. });
  94. } else next(station);
  95. },
  96. (station, next) => {
  97. if (!station.paused) next(true, station);
  98. else {
  99. notifications.unschedule(`stations.nextSong?id${station._id}`);
  100. next(true, station);
  101. }
  102. },
  103. (station, next) => {
  104. if (station.currentSong) {
  105. let timeLeft = ((station.currentSong.duration * 1000) - (Date.now() - station.startedAt - station.timePaused));
  106. if (isNaN(timeLeft)) timeLeft = -1;
  107. timeLeft = Math.floor(timeLeft);
  108. if (station.currentSong.duration * 1000 < timeLeft || timeLeft < 0) {
  109. this.skipStation(station._id)(next);
  110. } else {
  111. notifications.schedule(`stations.nextSong?id=${station._id}`, timeLeft, (err) => {
  112. next(err, station);
  113. });
  114. cb(null, station);
  115. }
  116. } else {
  117. this.skipStation(station._id)(next);
  118. }
  119. }
  120. ], (station, err) => {
  121. if (err && err !== true) {
  122. let error = 'An error occurred.';
  123. if (typeof err === "string") error = err;
  124. else if (err.message) error = err.message;
  125. logger.log("INITIALIZE_STATION", "ERROR", `Station initialization failed for "${stationId}". "${error}"`);
  126. }
  127. logger.log("INITIALIZE_STATION", "SUCCESS", `Station "${stationId}" initialized.`);
  128. cb(err, station);
  129. });
  130. },
  131. calculateSongForStation: function(station, cb) {
  132. let _this = this;
  133. let songList = [];
  134. async.waterfall([
  135. (next) => {
  136. let genresDone = [];
  137. station.genres.forEach((genre) => {
  138. db.models.song.find({genres: genre}, (err, songs) => {
  139. if (!err) {
  140. songs.forEach((song) => {
  141. if (songList.indexOf(song._id) === -1) {
  142. let found = false;
  143. song.genres.forEach((songGenre) => {
  144. if (station.blacklistedGenres.indexOf(songGenre) !== -1) found = true;
  145. });
  146. if (!found) {
  147. songList.push(song._id);
  148. }
  149. }
  150. });
  151. }
  152. genresDone.push(genre);
  153. if (genresDone.length === station.genres.length) next();
  154. });
  155. });
  156. },
  157. (next) => {
  158. let playlist = [];
  159. songList.forEach(function(songId) {
  160. if(station.playlist.indexOf(songId) === -1) playlist.push(songId);
  161. });
  162. station.playlist.filter((songId) => {
  163. if (songList.indexOf(songId) !== -1) playlist.push(songId);
  164. });
  165. _this.calculateOfficialPlaylistList(station._id, playlist, () => {
  166. next(null, playlist);
  167. });
  168. },
  169. (playlist, next) => {
  170. db.models.station.update({_id: station._id}, {$set: {playlist: playlist}}, (err) => {
  171. _this.updateStation(station._id, () => {
  172. next(err, playlist);
  173. });
  174. });
  175. }
  176. ], (err, newPlaylist) => {
  177. cb(err, newPlaylist);
  178. });
  179. },
  180. // Attempts to get the station from Redis. If it's not in Redis, get it from Mongo and add it to Redis.
  181. getStation: function(stationId, cb) {
  182. let _this = this;
  183. async.waterfall([
  184. (next) => {
  185. cache.hget('stations', stationId, next);
  186. },
  187. (station, next) => {
  188. if (station) return next(true, station);
  189. db.models.station.findOne({ _id: stationId }, next);
  190. },
  191. (station, next) => {
  192. if (station) {
  193. if (station.type === 'official') {
  194. _this.calculateOfficialPlaylistList(station._id, station.playlist, ()=>{});
  195. }
  196. station = cache.schemas.station(station);
  197. cache.hset('stations', stationId, station);
  198. next(true, station);
  199. } else next('Station not found');
  200. },
  201. ], (err, station) => {
  202. if (err && err !== true) cb(err);
  203. cb(null, station);
  204. });
  205. },
  206. updateStation: function(stationId, cb) {
  207. let _this = this;
  208. async.waterfall([
  209. (next) => {
  210. db.models.station.findOne({ _id: stationId }, next);
  211. },
  212. (station, next) => {
  213. if (!station) return next('Station not found');
  214. cache.hset('stations', stationId, station, (err) => {
  215. if (err) return next(err);
  216. next(null, station);
  217. });
  218. }
  219. ], (err, station) => {
  220. if (err && err !== true) cb(err);
  221. cb(null, station);
  222. });
  223. },
  224. calculateOfficialPlaylistList: (stationId, songList, cb) => {
  225. let lessInfoPlaylist = [];
  226. function getSongInfo(index) {
  227. if (songList.length > index) {
  228. songs.getSong(songList[index], (err, song) => {
  229. if (!err && song) {
  230. let newSong = {
  231. _id: song._id,
  232. title: song.title,
  233. artists: song.artists,
  234. duration: song.duration
  235. };
  236. lessInfoPlaylist.push(newSong);
  237. }
  238. getSongInfo(index + 1);
  239. })
  240. } else {
  241. cache.hset("officialPlaylists", stationId, cache.schemas.officialPlaylist(stationId, lessInfoPlaylist), () => {
  242. cache.pub("station.newOfficialPlaylist", stationId);
  243. cb();
  244. });
  245. }
  246. }
  247. getSongInfo(0);
  248. },
  249. skipStation: function(stationId) {
  250. let _this = this;
  251. return (cb) => {
  252. if (typeof cb !== 'function') cb = ()=>{};
  253. _this.getStation(stationId, (err, station) => {
  254. if (station) {
  255. // notify all the sockets on this station to go to the next song
  256. async.waterfall([
  257. (next) => {
  258. if (station.type === "official") {
  259. if (station.playlist.length > 0) {
  260. function setCurrentSong() {
  261. if (station.currentSongIndex < station.playlist.length - 1) {
  262. songs.getSong(station.playlist[station.currentSongIndex + 1], (err, song) => {
  263. if (!err) {
  264. let $set = {};
  265. $set.currentSong = {
  266. _id: song._id,
  267. title: song.title,
  268. artists: song.artists,
  269. duration: song.duration,
  270. likes: song.likes,
  271. dislikes: song.dislikes,
  272. skipDuration: song.skipDuration,
  273. thumbnail: song.thumbnail
  274. };
  275. $set.startedAt = Date.now();
  276. $set.timePaused = 0;
  277. $set.currentSongIndex = station.currentSongIndex + 1;
  278. next(null, $set);
  279. } else {
  280. db.models.station.update({ _id: station._id }, { $inc: { currentSongIndex: 1 } }, (err) => {
  281. _this.updateStation(station._id, () => {
  282. setCurrentSong();
  283. });
  284. });
  285. }
  286. });
  287. } else {
  288. db.models.station.update({_id: station._id}, {$set: {currentSongIndex: 0}}, (err) => {
  289. _this.updateStation(station._id, (err, station) => {
  290. _this.calculateSongForStation(station, (err, newPlaylist) => {
  291. if (!err) {
  292. songs.getSong(newPlaylist[0], (err, song) => {
  293. let $set = {};
  294. if (song) {
  295. $set.currentSong = {
  296. _id: song._id,
  297. title: song.title,
  298. artists: song.artists,
  299. duration: song.duration,
  300. likes: song.likes,
  301. dislikes: song.dislikes,
  302. skipDuration: song.skipDuration,
  303. thumbnail: song.thumbnail
  304. };
  305. station.playlist = newPlaylist;
  306. } else $set.currentSong = _this.defaultSong;
  307. $set.startedAt = Date.now();
  308. $set.timePaused = 0;
  309. next(null, $set);
  310. });
  311. } else {
  312. let $set = {};
  313. $set.currentSong = _this.defaultSong;
  314. $set.startedAt = Date.now();
  315. $set.timePaused = 0;
  316. next(null, $set);
  317. }
  318. })
  319. });
  320. });
  321. }
  322. }
  323. setCurrentSong();
  324. } else {
  325. _this.calculateSongForStation(station, (err, playlist) => {
  326. if (!err && playlist.length === 0) {
  327. let $set = {};
  328. $set.currentSongIndex = 0;
  329. $set.currentSong = _this.defaultSong;
  330. $set.startedAt = Date.now();
  331. $set.timePaused = 0;
  332. next(null, $set);
  333. } else {
  334. songs.getSong(playlist[0], (err, song) => {
  335. let $set = {};
  336. if (!err) {
  337. $set.currentSong = {
  338. _id: song._id,
  339. title: song.title,
  340. artists: song.artists,
  341. duration: song.duration,
  342. likes: song.likes,
  343. dislikes: song.dislikes,
  344. skipDuration: song.skipDuration,
  345. thumbnail: song.thumbnail
  346. };
  347. } else {
  348. $set.currentSong = _this.defaultSong;
  349. }
  350. $set.currentSongIndex = 0;
  351. $set.startedAt = Date.now();
  352. $set.timePaused = 0;
  353. next(null, $set);
  354. });
  355. }
  356. });
  357. }
  358. } else {
  359. if (station.partyMode === true) if (station.queue.length > 0) {
  360. db.models.station.update({ _id: stationId }, { $pull: { queue: { _id: station.queue[0]._id } } }, (err) => {
  361. if (err) return next(err);
  362. let $set = {};
  363. $set.currentSong = station.queue[0];
  364. $set.startedAt = Date.now();
  365. $set.timePaused = 0;
  366. if (station.paused) $set.pausedAt = Date.now();
  367. next(null, $set);
  368. });
  369. } else next(null, {currentSong: null});
  370. else {
  371. db.models.playlist.findOne({_id: station.privatePlaylist}, (err, playlist) => {
  372. if (err || !playlist) return next(null, {currentSong: null});
  373. playlist = playlist.songs;
  374. if (playlist.length > 0) {
  375. let $set = {};
  376. if (station.currentSongIndex < playlist.length - 1) $set.currentSongIndex = station.currentSongIndex + 1;
  377. else $set.currentSongIndex = 0;
  378. songs.getSong(playlist[$set.currentSongIndex]._id, (err, song) => {
  379. if (!err && song) {
  380. $set.currentSong = {
  381. _id: song._id,
  382. title: song.title,
  383. artists: song.artists,
  384. duration: song.duration,
  385. likes: song.likes,
  386. dislikes: song.dislikes,
  387. skipDuration: song.skipDuration,
  388. thumbnail: song.thumbnail
  389. };
  390. } else {
  391. let song = playlist[$set.currentSongIndex];
  392. $set.currentSong = {
  393. _id: song._id,
  394. title: song.title,
  395. duration: song.duration,
  396. likes: -1,
  397. dislikes: -1
  398. };
  399. }
  400. $set.startedAt = Date.now();
  401. $set.timePaused = 0;
  402. next(null, $set);
  403. });
  404. } else next(null, {currentSong: null});
  405. });
  406. }
  407. }
  408. },
  409. ($set, next) => {
  410. db.models.station.update({_id: station._id}, {$set}, (err) => {
  411. _this.updateStation(station._id, (err, station) => {
  412. if (station.type === 'community' && station.partyMode === true)
  413. cache.pub('station.queueUpdate', stationId);
  414. next(null, station);
  415. });
  416. });
  417. },
  418. ], (err, station) => {
  419. if (!err) {
  420. if (station.currentSong !== null && station.currentSong._id !== undefined) {
  421. station.currentSong.skipVotes = 0;
  422. }
  423. //TODO Pub/Sub this
  424. utils.emitToRoom(`station.${station._id}`, "event:songs.next", {
  425. currentSong: station.currentSong,
  426. startedAt: station.startedAt,
  427. paused: station.paused,
  428. timePaused: 0
  429. });
  430. if (station.privacy === 'public') utils.emitToRoom('home', "event:station.nextSong", station._id, station.currentSong);
  431. else {
  432. let sockets = utils.getRoomSockets('home');
  433. for (let socketId in sockets) {
  434. let socket = sockets[socketId];
  435. let session = sockets[socketId].session;
  436. if (session.sessionId) {
  437. cache.hget('sessions', session.sessionId, (err, session) => {
  438. if (!err && session) {
  439. db.models.user.findOne({_id: session.userId}, (err, user) => {
  440. if (!err && user) {
  441. if (user.role === 'admin') socket.emit("event:station.nextSong", station._id, station.currentSong);
  442. else if (station.type === "community" && station.owner === session.userId) socket.emit("event:station.nextSong", station._id, station.currentSong);
  443. }
  444. });
  445. }
  446. });
  447. }
  448. }
  449. }
  450. console.log(Date.now(), station._id, station.currentSong !== null && station.currentSong._id !== undefined, station.currentSong !== null, station.currentSong._id !== undefined);
  451. if (station.currentSong !== null && station.currentSong._id !== undefined) {
  452. utils.socketsJoinSongRoom(utils.getRoomSockets(`station.${station._id}`), `song.${station.currentSong._id}`);
  453. if (!station.paused) {
  454. notifications.schedule(`stations.nextSong?id=${station._id}`, station.currentSong.duration * 1000);
  455. }
  456. } else {
  457. utils.socketsLeaveSongRooms(utils.getRoomSockets(`station.${station._id}`), `song.${station.currentSong._id}`);
  458. }
  459. cb(null, station);
  460. } else cb(err);
  461. });
  462. }
  463. // the station doesn't exist anymore, unsubscribe from it
  464. else {
  465. cb("Station not found.");
  466. }
  467. });
  468. }
  469. },
  470. defaultSong: {
  471. _id: '60ItHLz5WEA',
  472. title: 'Faded - Alan Walker',
  473. duration: 212,
  474. likes: -1,
  475. dislikes: -1
  476. }
  477. };