stations.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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 songs = require('./songs');
  7. const notifications = require('./notifications');
  8. const async = require('async');
  9. let skipTimeout = null;
  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. module.exports = {
  25. init: function(cb) {
  26. let _this = this;
  27. //TODO Add async waterfall
  28. db.models.station.find({}, (err, stations) => {
  29. if (!err) {
  30. stations.forEach((station) => {
  31. console.info("Initializing Station: " + station._id);
  32. _this.initializeStation(station._id);
  33. });
  34. cb();
  35. }
  36. });
  37. },
  38. initializeStation: function(stationId, cb) {
  39. if (typeof cb !== 'function') cb = ()=>{};
  40. let _this = this;
  41. _this.getStation(stationId, (err, station) => {
  42. if (!err) {
  43. if (station) {
  44. let notification = notifications.subscribe(`stations.nextSong?id=${station._id}`, _this.skipStation(station._id), true);
  45. if (!station.paused ) {
  46. /*if (!station.startedAt) {
  47. station.startedAt = Date.now();
  48. station.timePaused = 0;
  49. cache.hset('stations', stationId, station);
  50. }*/
  51. if (station.currentSong) {
  52. let timeLeft = ((station.currentSong.duration * 1000) - (Date.now() - station.startedAt - station.timePaused));
  53. if (isNaN(timeLeft)) timeLeft = -1;
  54. if (station.currentSong.duration * 1000 < timeLeft || timeLeft < 0) {
  55. this.skipStation(station._id)((err, station) => {
  56. cb(err, station);
  57. });
  58. } else {
  59. notifications.schedule(`stations.nextSong?id=${station._id}`, timeLeft);
  60. cb(null, station);
  61. }
  62. } else {
  63. _this.skipStation(station._id)((err, station) => {
  64. cb(err, station);
  65. });
  66. }
  67. } else {
  68. notifications.unschedule(`stations.nextSong?id${station._id}`);
  69. cb(null, station);
  70. }
  71. } else cb("Station not found");
  72. } else cb(err);
  73. });
  74. },
  75. calculateSongForStation: function(station, cb) {
  76. let _this = this;
  77. let songList = [];
  78. async.waterfall([
  79. (next) => {
  80. let genresDone = [];
  81. station.genres.forEach((genre) => {
  82. db.models.song.find({genres: genre}, (err, songs) => {
  83. if (!err) {
  84. songs.forEach((song) => {
  85. if (songList.indexOf(song._id) === -1) {
  86. let found = false;
  87. song.genres.forEach((songGenre) => {
  88. if (station.blacklistedGenres.indexOf(songGenre) !== -1) found = true;
  89. });
  90. if (!found) {
  91. songList.push(song._id);
  92. }
  93. }
  94. });
  95. }
  96. genresDone.push(genre);
  97. if (genresDone.length === station.genres.length) next();
  98. });
  99. });
  100. },
  101. (next) => {
  102. let playlist = [];
  103. songList.forEach(function(songId) {
  104. if(station.playlist.indexOf(songId) === -1) playlist.push(songId);
  105. });
  106. station.playlist.filter((songId) => {
  107. if (songList.indexOf(songId) !== -1) playlist.push(songId);
  108. });
  109. db.models.station.update({_id: station._id}, {$set: {playlist: playlist}}, (err) => {
  110. _this.updateStation(station._id, () => {
  111. next(err, playlist);
  112. });
  113. });
  114. }
  115. ], (err, newPlaylist) => {
  116. cb(err, newPlaylist);
  117. });
  118. },
  119. // Attempts to get the station from Redis. If it's not in Redis, get it from Mongo and add it to Redis.
  120. getStation: function(stationId, cb) {
  121. async.waterfall([
  122. (next) => {
  123. cache.hget('stations', stationId, next);
  124. },
  125. (station, next) => {
  126. if (station) return next(true, station);
  127. db.models.station.findOne({ _id: stationId }, next);
  128. },
  129. (station, next) => {
  130. if (station) {
  131. station = cache.schemas.station(station);
  132. cache.hset('stations', stationId, station);
  133. next(true, station);
  134. } else next('Station not found');
  135. },
  136. ], (err, station) => {
  137. if (err && err !== true) cb(err);
  138. cb(null, station);
  139. });
  140. },
  141. updateStation: (stationId, cb) => {
  142. async.waterfall([
  143. (next) => {
  144. db.models.station.findOne({ _id: stationId }, next);
  145. },
  146. (station, next) => {
  147. if (!station) return next('Station not found');
  148. cache.hset('stations', stationId, station, (err) => {
  149. if (err) return next(err);
  150. next(null, station);
  151. });
  152. }
  153. ], (err, station) => {
  154. if (err && err !== true) cb(err);
  155. cb(null, station);
  156. });
  157. },
  158. skipStation: function(stationId) {
  159. let _this = this;
  160. return (cb) => {
  161. if (typeof cb !== 'function') cb = ()=>{};
  162. _this.getStation(stationId, (err, station) => {
  163. if (station) {
  164. // notify all the sockets on this station to go to the next song
  165. async.waterfall([
  166. (next) => {
  167. if (station.type === "official") {
  168. if (station.playlist.length > 0) {
  169. function func() {
  170. if (station.currentSongIndex < station.playlist.length - 1) {
  171. songs.getSong(station.playlist[station.currentSongIndex + 1], (err, song) => {
  172. if (!err) {
  173. let $set = {};
  174. $set.currentSong = {
  175. _id: song._id,
  176. title: song.title,
  177. artists: song.artists,
  178. duration: song.duration,
  179. likes: song.likes,
  180. dislikes: song.dislikes,
  181. skipDuration: song.skipDuration,
  182. thumbnail: song.thumbnail
  183. };
  184. $set.startedAt = Date.now();
  185. $set.timePaused = 0;
  186. $set.currentSongIndex = station.currentSongIndex + 1;
  187. next(null, $set);
  188. } else {
  189. db.models.station.update({_id: station._id}, {$inc: {currentSongIndex: 1}}, (err) => {
  190. _this.updateStation(station._id, () => {
  191. func();
  192. });
  193. });
  194. }
  195. });
  196. } else {
  197. db.models.station.update({_id: station._id}, {$set: {currentSongIndex: 0}}, (err) => {
  198. _this.updateStation(station._id, (err, station) => {
  199. _this.calculateSongForStation(station, (err, newPlaylist) => {
  200. if (!err) {
  201. songs.getSong(newPlaylist[0], (err, song) => {
  202. let $set = {};
  203. if (song) {
  204. $set.currentSong = {
  205. _id: song._id,
  206. title: song.title,
  207. artists: song.artists,
  208. duration: song.duration,
  209. likes: song.likes,
  210. dislikes: song.dislikes,
  211. skipDuration: song.skipDuration,
  212. thumbnail: song.thumbnail
  213. };
  214. station.playlist = newPlaylist;
  215. } else $set.currentSong = _this.defaultSong;
  216. $set.startedAt = Date.now();
  217. $set.timePaused = 0;
  218. next(null, $set);
  219. });
  220. } else {
  221. let $set = {};
  222. $set.currentSong = _this.defaultSong;
  223. $set.startedAt = Date.now();
  224. $set.timePaused = 0;
  225. next(null, $set);
  226. }
  227. })
  228. });
  229. });
  230. }
  231. }
  232. func();
  233. } else {
  234. _this.calculateSongForStation(station, (err, playlist) => {
  235. if (!err && playlist.length === 0) {
  236. let $set = {};
  237. $set.currentSongIndex = 0;
  238. $set.currentSong = _this.defaultSong;
  239. $set.startedAt = Date.now();
  240. $set.timePaused = 0;
  241. next(null, $set);
  242. } else {
  243. songs.getSong(playlist[0], (err, song) => {
  244. let $set = {};
  245. if (!err) {
  246. $set.currentSong = {
  247. _id: song._id,
  248. title: song.title,
  249. artists: song.artists,
  250. duration: song.duration,
  251. likes: song.likes,
  252. dislikes: song.dislikes,
  253. skipDuration: song.skipDuration,
  254. thumbnail: song.thumbnail
  255. };
  256. } else {
  257. $set.currentSong = _this.defaultSong;
  258. }
  259. $set.currentSongIndex = 0;
  260. $set.startedAt = Date.now();
  261. $set.timePaused = 0;
  262. next(null, $set);
  263. });
  264. }
  265. });
  266. }
  267. } else {
  268. if (station.partyMode === true) if (station.queue.length > 0) {
  269. db.models.station.update({ _id: stationId }, { $pull: { queue: { _id: station.queue[0]._id } } }, (err) => {
  270. if (err) return next(err);
  271. let $set = {};
  272. $set.currentSong = station.queue[0];
  273. $set.startedAt = Date.now();
  274. $set.timePaused = 0;
  275. if (station.paused) $set.pausedAt = Date.now();
  276. next(null, $set);
  277. });
  278. } else next(null, {currentSong: null});
  279. else {
  280. db.models.playlist.findOne({_id: station.privatePlaylist}, (err, playlist) => {
  281. if (err || !playlist) return next(null, {currentSong: null});
  282. playlist = playlist.songs;
  283. if (playlist.length > 0) {
  284. let $set = {};
  285. if (station.currentSongIndex < playlist.length - 1) $set.currentSongIndex = station.currentSongIndex + 1;
  286. else $set.currentSongIndex = 0;
  287. songs.getSong(playlist[$set.currentSongIndex]._id, (err, song) => {
  288. if (!err && song) {
  289. $set.currentSong = {
  290. _id: song._id,
  291. title: song.title,
  292. artists: song.artists,
  293. duration: song.duration,
  294. likes: song.likes,
  295. dislikes: song.dislikes,
  296. skipDuration: song.skipDuration,
  297. thumbnail: song.thumbnail
  298. };
  299. } else {
  300. let song = playlist[$set.currentSongIndex];
  301. $set.currentSong = {
  302. _id: song._id,
  303. title: song.title,
  304. duration: song.duration,
  305. likes: -1,
  306. dislikes: -1
  307. };
  308. }
  309. $set.startedAt = Date.now();
  310. $set.timePaused = 0;
  311. next(null, $set);
  312. });
  313. } else next(null, {currentSong: null});
  314. });
  315. }
  316. }
  317. },
  318. ($set, next) => {
  319. db.models.station.update({_id: station._id}, {$set}, (err) => {
  320. _this.updateStation(station._id, (err, station) => {
  321. if (station.type === 'community' && station.partyMode === true)
  322. cache.pub('station.queueUpdate', stationId);
  323. next(null, station);
  324. });
  325. });
  326. },
  327. ], (err, station) => {
  328. if (!err) {
  329. if (station.currentSong !== null && station.currentSong._id !== undefined) {
  330. station.currentSong.skipVotes = 0;
  331. }
  332. //TODO Pub/Sub this
  333. utils.emitToRoom(`station.${station._id}`, "event:songs.next", {
  334. currentSong: station.currentSong,
  335. startedAt: station.startedAt,
  336. paused: station.paused,
  337. timePaused: 0
  338. });
  339. if (station.privacy === 'public') utils.emitToRoom('home', "event:station.nextSong", station._id, station.currentSong);
  340. else {
  341. let sockets = utils.getRoomSockets('home');
  342. for (let socketId in sockets) {
  343. let socket = sockets[socketId];
  344. let session = sockets[socketId].session;
  345. if (session.sessionId) {
  346. cache.hget('sessions', session.sessionId, (err, session) => {
  347. if (!err && session) {
  348. db.models.user.findOne({_id: session.userId}, (err, user) => {
  349. if (user.role === 'admin') socket.emit("event:station.nextSong", station._id, station.currentSong);
  350. else if (station.type === "community" && station.owner === session.userId) socket.emit("event:station.nextSong", station._id, station.currentSong);
  351. });
  352. }
  353. });
  354. }
  355. }
  356. }
  357. if (station.currentSong !== null && station.currentSong._id !== undefined) {
  358. utils.socketsJoinSongRoom(utils.getRoomSockets(`station.${station._id}`), `song.${station.currentSong._id}`);
  359. if (!station.paused) {
  360. notifications.schedule(`stations.nextSong?id=${station._id}`, station.currentSong.duration * 1000);
  361. }
  362. } else {
  363. utils.socketsLeaveSongRooms(utils.getRoomSockets(`station.${station._id}`), `song.${station.currentSong._id}`);
  364. }
  365. cb(null, station);
  366. } else cb(err);
  367. });
  368. }
  369. // the station doesn't exist anymore, unsubscribe from it
  370. else {
  371. cb("Station not found.");
  372. }
  373. });
  374. }
  375. },
  376. defaultSong: {
  377. _id: '60ItHLz5WEA',
  378. title: 'Faded - Alan Walker',
  379. duration: 212,
  380. likes: -1,
  381. dislikes: -1
  382. }
  383. };