stations.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 {
  216. $set.currentSong = _this.defaultSong;
  217. }
  218. $set.startedAt = Date.now();
  219. $set.timePaused = 0;
  220. next(null, $set);
  221. });
  222. } else {
  223. let $set = {};
  224. $set.currentSong = _this.defaultSong;
  225. $set.startedAt = Date.now();
  226. $set.timePaused = 0;
  227. next(null, $set);
  228. }
  229. })
  230. });
  231. });
  232. }
  233. }
  234. func();
  235. } else {
  236. _this.calculateSongForStation(station, (err, playlist) => {
  237. if (!err && playlist.length === 0) {
  238. let $set = {};
  239. $set.currentSongIndex = 0;
  240. $set.currentSong = _this.defaultSong;
  241. $set.startedAt = Date.now();
  242. $set.timePaused = 0;
  243. next(null, $set);
  244. } else {
  245. songs.getSong(playlist[0], (err, song) => {
  246. let $set = {};
  247. if (!err) {
  248. $set.currentSong = {
  249. _id: song._id,
  250. title: song.title,
  251. artists: song.artists,
  252. duration: song.duration,
  253. likes: song.likes,
  254. dislikes: song.dislikes,
  255. skipDuration: song.skipDuration,
  256. thumbnail: song.thumbnail
  257. };
  258. } else {
  259. $set.currentSong = _this.defaultSong;
  260. }
  261. $set.currentSongIndex = 0;
  262. $set.startedAt = Date.now();
  263. $set.timePaused = 0;
  264. next(null, $set);
  265. });
  266. }
  267. });
  268. }
  269. } else {
  270. if (station.partyMode === true) {
  271. if (station.queue.length > 0) {
  272. db.models.station.update({_id: stationId}, {$pull: {queue: {songId: station.queue[0]._id}}}, (err) => {
  273. if (err) return next(err);
  274. let $set = {};
  275. $set.currentSong = station.queue[0];
  276. $set.startedAt = Date.now();
  277. $set.timePaused = 0;
  278. if (station.paused) {
  279. $set.pausedAt = Date.now();
  280. }
  281. next(null, $set);
  282. });
  283. } else {
  284. next(null, {currentSong: null});
  285. }
  286. } else {
  287. db.models.playlist.findOne({_id: station.privatePlaylist}, (err, playlist) => {
  288. if (err || !playlist) return next(null, {currentSong: null});
  289. playlist = playlist.songs;
  290. if (playlist.length > 0) {
  291. let $set = {};
  292. if (station.currentSongIndex < playlist.length - 1) $set.currentSongIndex = station.currentSongIndex + 1;
  293. else $set.currentSongIndex = 0;
  294. songs.getSong(playlist[$set.currentSongIndex]._id, (err, song) => {
  295. if (!err && song) {
  296. $set.currentSong = {
  297. _id: song._id,
  298. title: song.title,
  299. artists: song.artists,
  300. duration: song.duration,
  301. likes: song.likes,
  302. dislikes: song.dislikes,
  303. skipDuration: song.skipDuration,
  304. thumbnail: song.thumbnail
  305. };
  306. } else {
  307. let song = playlist[$set.currentSongIndex];
  308. $set.currentSong = {
  309. _id: song._id,
  310. title: song.title,
  311. duration: song.duration,
  312. likes: -1,
  313. dislikes: -1
  314. };
  315. }
  316. $set.startedAt = Date.now();
  317. $set.timePaused = 0;
  318. next(null, $set);
  319. });
  320. } else next(null, {currentSong: null});
  321. });
  322. }
  323. }
  324. },
  325. ($set, next) => {
  326. db.models.station.update({_id: station._id}, {$set}, (err) => {
  327. _this.updateStation(station._id, (err, station) => {
  328. if (station.type === 'community' && station.partyMode === true)
  329. cache.pub('station.queueUpdate', stationId);
  330. next(null, station);
  331. });
  332. });
  333. },
  334. ], (err, station) => {
  335. if (!err) {
  336. if (station.currentSong !== null && station.currentSong._id !== undefined) {
  337. station.currentSong.skipVotes = 0;
  338. }
  339. utils.emitToRoom(`station.${station._id}`, "event:songs.next", {
  340. currentSong: station.currentSong,
  341. startedAt: station.startedAt,
  342. paused: station.paused,
  343. timePaused: 0
  344. });
  345. if (station.currentSong !== null && station.currentSong._id !== undefined) {
  346. utils.socketsJoinSongRoom(utils.getRoomSockets(`station.${station._id}`), `song.${station.currentSong._id}`);
  347. if (!station.paused) {
  348. notifications.schedule(`stations.nextSong?id=${station._id}`, station.currentSong.duration * 1000);
  349. }
  350. } else {
  351. utils.socketsLeaveSongRooms(utils.getRoomSockets(`station.${station._id}`), `song.${station.currentSong._id}`);
  352. }
  353. cb(null, station);
  354. } else cb(err);
  355. });
  356. }
  357. // the station doesn't exist anymore, unsubscribe from it
  358. else {
  359. cb("Station not found.");
  360. }
  361. });
  362. }
  363. },
  364. defaultSong: {
  365. _id: '60ItHLz5WEA',
  366. title: 'Faded',
  367. artists: ['Alan Walker'],
  368. duration: 212,
  369. skipDuration: 0,
  370. thumbnail: 'https://i.scdn.co/image/2ddde58427f632037093857ebb71a67ddbdec34b'
  371. }
  372. };