stations.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. console.log(112233, stationId, cb);
  40. if (typeof cb !== 'function') cb = ()=>{};
  41. let _this = this;
  42. _this.getStation(stationId, (err, station) => {
  43. if (!err) {
  44. console.log("###");
  45. if (station) {
  46. console.log("###1");
  47. let notification = notifications.subscribe(`stations.nextSong?id=${station._id}`, _this.skipStation(station._id), true);
  48. if (!station.paused ) {
  49. /*if (!station.startedAt) {
  50. station.startedAt = Date.now();
  51. station.timePaused = 0;
  52. cache.hset('stations', stationId, station);
  53. }*/
  54. if (station.currentSong) {
  55. let timeLeft = ((station.currentSong.duration * 1000) - (Date.now() - station.startedAt - station.timePaused));
  56. if (isNaN(timeLeft)) timeLeft = -1;
  57. if (station.currentSong.duration * 1000 < timeLeft || timeLeft < 0) {
  58. console.log("Test");
  59. this.skipStation(station._id)((err, station) => {
  60. console.log(45, err, station);
  61. cb(err, station);
  62. });
  63. } else {
  64. notifications.schedule(`stations.nextSong?id=${station._id}`, timeLeft);
  65. cb(null, station);
  66. }
  67. } else {
  68. _this.skipStation(station._id)((err, station) => {
  69. console.log(47, err, station);
  70. cb(err, station);
  71. });
  72. }
  73. } else {
  74. notifications.unschedule(`stations.nextSong?id${station._id}`);
  75. cb(null, station);
  76. }
  77. } else cb("Station not found.");
  78. } else cb(err);
  79. });
  80. },
  81. calculateSongForStation: function(station, cb) {
  82. let _this = this;
  83. let songList = [];
  84. async.waterfall([
  85. (next) => {
  86. let genresDone = [];
  87. station.genres.forEach((genre) => {
  88. db.models.song.find({genres: genre}, (err, songs) => {
  89. if (!err) {
  90. songs.forEach((song) => {
  91. if (songList.indexOf(song._id) === -1) songList.push(song._id);
  92. });
  93. }
  94. genresDone.push(genre);
  95. if (genresDone.length === station.genres.length) {
  96. next();
  97. }
  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. console.log(1234321, stationId);
  133. cache.hset('stations', stationId, station);
  134. next(true, station);
  135. } else next('Station not found.');
  136. },
  137. ], (err, station) => {
  138. if (err && err !== true) cb(err);
  139. cb(null, station);
  140. });
  141. },
  142. updateStation: (stationId, cb) => {
  143. async.waterfall([
  144. (next) => {
  145. db.models.station.findOne({ _id: stationId }, next);
  146. },
  147. (station, next) => {
  148. if (!station) return next('Station not found.');
  149. console.log(123444321, stationId);
  150. cache.hset('stations', stationId, station, (err) => {
  151. if (err) return next(err);
  152. next(null, station);
  153. });
  154. }
  155. ], (err, station) => {
  156. if (err && err !== true) cb(err);
  157. cb(null, station);
  158. });
  159. },
  160. skipStation: function(stationId) {
  161. let _this = this;
  162. return (cb) => {
  163. if (typeof cb !== 'function') cb = ()=>{};
  164. console.log("###2");
  165. console.log("NOTIFICATION!!!");
  166. _this.getStation(stationId, (err, station) => {
  167. console.log("###3");
  168. if (station) {
  169. console.log("###4");
  170. // notify all the sockets on this station to go to the next song
  171. async.waterfall([
  172. (next) => {
  173. console.log("###5");
  174. if (station.type === "official") {
  175. if (station.playlist.length > 0) {
  176. function func() {
  177. if (station.currentSongIndex < station.playlist.length - 1) {
  178. songs.getSong(station.playlist[station.currentSongIndex + 1], (err, song) => {
  179. if (!err) {
  180. let $set = {};
  181. $set.currentSong = {
  182. _id: song._id,
  183. title: song.title,
  184. artists: song.artists,
  185. duration: song.duration,
  186. likes: song.likes,
  187. dislikes: song.dislikes,
  188. skipDuration: song.skipDuration,
  189. thumbnail: song.thumbnail
  190. };
  191. $set.startedAt = Date.now();
  192. $set.timePaused = 0;
  193. $set.currentSongIndex = station.currentSongIndex + 1;
  194. next(null, $set);
  195. } else {
  196. db.models.station.update({_id: station._id}, {$inc: {currentSongIndex: 1}}, (err) => {
  197. _this.updateStation(station._id, () => {
  198. func();
  199. });
  200. });
  201. }
  202. });
  203. } else {
  204. db.models.station.update({_id: station._id}, {$set: {currentSongIndex: 0}}, (err) => {
  205. _this.updateStation(station._id, (err, station) => {
  206. console.log(12345678, err, station);
  207. _this.calculateSongForStation(station, (err, newPlaylist) => {
  208. console.log('New playlist: ', newPlaylist);
  209. if (!err) {
  210. songs.getSong(newPlaylist[0], (err, song) => {
  211. let $set = {};
  212. if (song) {
  213. $set.currentSong = {
  214. _id: song._id,
  215. title: song.title,
  216. artists: song.artists,
  217. duration: song.duration,
  218. likes: song.likes,
  219. dislikes: song.dislikes,
  220. skipDuration: song.skipDuration,
  221. thumbnail: song.thumbnail
  222. };
  223. station.playlist = newPlaylist;
  224. } else {
  225. $set.currentSong = _this.defaultSong;
  226. }
  227. $set.startedAt = Date.now();
  228. $set.timePaused = 0;
  229. next(null, $set);
  230. });
  231. } else {
  232. let $set = {};
  233. $set.currentSong = _this.defaultSong;
  234. $set.startedAt = Date.now();
  235. $set.timePaused = 0;
  236. next(null, $set);
  237. }
  238. })
  239. });
  240. });
  241. }
  242. }
  243. func();
  244. } else {
  245. _this.calculateSongForStation(station, (err, playlist) => {
  246. if (!err && playlist.length === 0) {
  247. let $set = {};
  248. $set.currentSongIndex = 0;
  249. $set.currentSong = _this.defaultSong;
  250. $set.startedAt = Date.now();
  251. $set.timePaused = 0;
  252. next(null, $set);
  253. } else {
  254. songs.getSong(playlist[0], (err, song) => {
  255. let $set = {};
  256. if (!err) {
  257. $set.currentSong = {
  258. _id: song._id,
  259. title: song.title,
  260. artists: song.artists,
  261. duration: song.duration,
  262. likes: song.likes,
  263. dislikes: song.dislikes,
  264. skipDuration: song.skipDuration,
  265. thumbnail: song.thumbnail
  266. };
  267. } else {
  268. $set.currentSong = _this.defaultSong;
  269. }
  270. $set.currentSongIndex = 0;
  271. $set.startedAt = Date.now();
  272. $set.timePaused = 0;
  273. next(null, $set);
  274. });
  275. }
  276. });
  277. }
  278. } else {
  279. if (station.queue.length > 0) {
  280. console.log("##");
  281. db.models.station.update({_id: stationId}, {$pull: {queue: {songId: station.queue[0]._id}}}, (err) => {
  282. console.log("##1", err);
  283. if (err) return next(err);
  284. let $set = {};
  285. $set.currentSong = station.queue[0];
  286. $set.startedAt = Date.now();
  287. $set.timePaused = 0;
  288. if (station.paused) {
  289. $set.pausedAt = Date.now();
  290. }
  291. next(null, $set);
  292. });
  293. } else {
  294. console.log("##2");
  295. next(null, {currentSong: null});
  296. }
  297. }
  298. },
  299. ($set, next) => {
  300. console.log("$set", $set);
  301. db.models.station.update({_id: station._id}, {$set}, (err) => {
  302. console.log("##2.5", err);
  303. _this.updateStation(station._id, (err, station) => {
  304. console.log("##2.6", err);
  305. if (station.type === 'community') {
  306. cache.pub('station.queueUpdate', stationId);
  307. }
  308. next(null, station);
  309. });
  310. });
  311. },
  312. ], (err, station) => {
  313. console.log("##3", err);
  314. if (!err) {
  315. io.io.to(`station.${station._id}`).emit("event:songs.next", {
  316. currentSong: station.currentSong,
  317. startedAt: station.startedAt,
  318. paused: station.paused,
  319. timePaused: 0
  320. });
  321. if (station.currentSong !== null && station.currentSong._id !== undefined) {
  322. utils.socketsJoinSongRoom(io.io.to(`station.${station._id}`).sockets, `song.${station.currentSong._id}`);
  323. console.log("NEXT SONG!!!", station.currentSong);
  324. if (!station.paused) {
  325. notifications.schedule(`stations.nextSong?id=${station._id}`, station.currentSong.duration * 1000);
  326. }
  327. } else {
  328. console.log("22", !!(station.currentSong));
  329. utils.socketsLeaveSongRooms(io.io.to(`station.${station._id}`).sockets, `song.${station.currentSong._id}`);
  330. }
  331. console.log(33, null, station, cb);
  332. cb(null, station);
  333. } else cb(err);
  334. });
  335. }
  336. // the station doesn't exist anymore, unsubscribe from it
  337. else {
  338. console.log(112233445566, "REMOVE NOTIFICATION");
  339. notifications.remove(notification);
  340. cb("Station not found.");
  341. }
  342. });
  343. }
  344. },
  345. defaultSong: {
  346. _id: '60ItHLz5WEA',
  347. title: 'Faded',
  348. artists: ['Alan Walker'],
  349. duration: 212,
  350. skipDuration: 0,
  351. thumbnail: 'https://i.scdn.co/image/2ddde58427f632037093857ebb71a67ddbdec34b'
  352. }
  353. };