stations.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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) {
  269. if (station.queue.length > 0) {
  270. db.models.station.update({_id: stationId}, {$pull: {queue: {songId: station.queue[0]._id}}}, (err) => {
  271. if (err) return next(err);
  272. let $set = {};
  273. $set.currentSong = station.queue[0];
  274. $set.startedAt = Date.now();
  275. $set.timePaused = 0;
  276. if (station.paused) {
  277. $set.pausedAt = Date.now();
  278. }
  279. next(null, $set);
  280. });
  281. } else {
  282. next(null, {currentSong: null});
  283. }
  284. } else {
  285. db.models.playlist.findOne({_id: station.privatePlaylist}, (err, playlist) => {
  286. if (err || !playlist) return next(null, {currentSong: null});
  287. playlist = playlist.songs;
  288. if (playlist.length > 0) {
  289. let $set = {};
  290. if (station.currentSongIndex < playlist.length - 1) $set.currentSongIndex = station.currentSongIndex + 1;
  291. else $set.currentSongIndex = 0;
  292. songs.getSong(playlist[$set.currentSongIndex]._id, (err, song) => {
  293. if (!err && song) {
  294. $set.currentSong = {
  295. _id: song._id,
  296. title: song.title,
  297. artists: song.artists,
  298. duration: song.duration,
  299. likes: song.likes,
  300. dislikes: song.dislikes,
  301. skipDuration: song.skipDuration,
  302. thumbnail: song.thumbnail
  303. };
  304. } else {
  305. let song = playlist[$set.currentSongIndex];
  306. $set.currentSong = {
  307. _id: song._id,
  308. title: song.title,
  309. duration: song.duration,
  310. likes: -1,
  311. dislikes: -1
  312. };
  313. }
  314. $set.startedAt = Date.now();
  315. $set.timePaused = 0;
  316. next(null, $set);
  317. });
  318. } else next(null, {currentSong: null});
  319. });
  320. }
  321. }
  322. },
  323. ($set, next) => {
  324. db.models.station.update({_id: station._id}, {$set}, (err) => {
  325. _this.updateStation(station._id, (err, station) => {
  326. if (station.type === 'community' && station.partyMode === true)
  327. cache.pub('station.queueUpdate', stationId);
  328. next(null, station);
  329. });
  330. });
  331. },
  332. ], (err, station) => {
  333. if (!err) {
  334. if (station.currentSong !== null && station.currentSong._id !== undefined) {
  335. station.currentSong.skipVotes = 0;
  336. }
  337. utils.emitToRoom(`station.${station._id}`, "event:songs.next", {
  338. currentSong: station.currentSong,
  339. startedAt: station.startedAt,
  340. paused: station.paused,
  341. timePaused: 0
  342. });
  343. if (station.currentSong !== null && station.currentSong._id !== undefined) {
  344. utils.socketsJoinSongRoom(utils.getRoomSockets(`station.${station._id}`), `song.${station.currentSong._id}`);
  345. if (!station.paused) {
  346. notifications.schedule(`stations.nextSong?id=${station._id}`, station.currentSong.duration * 1000);
  347. }
  348. } else {
  349. utils.socketsLeaveSongRooms(utils.getRoomSockets(`station.${station._id}`), `song.${station.currentSong._id}`);
  350. }
  351. cb(null, station);
  352. } else cb(err);
  353. });
  354. }
  355. // the station doesn't exist anymore, unsubscribe from it
  356. else {
  357. cb("Station not found.");
  358. }
  359. });
  360. }
  361. },
  362. defaultSong: {
  363. _id: '60ItHLz5WEA',
  364. title: 'Faded - Alan Walker',
  365. duration: 212,
  366. likes: -1,
  367. dislikes: -1
  368. }
  369. };