stations.js 15 KB

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