stations.js 16 KB

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