stations.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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.getStation(stationId, (err, station) => {})
  16. });
  17. module.exports = {
  18. init: function(cb) {
  19. let _this = this;
  20. //TODO Add async waterfall
  21. db.models.station.find({}, (err, stations) => {
  22. if (!err) {
  23. stations.forEach((station) => {
  24. console.info("Initializing Station: " + station._id);
  25. _this.initializeStation(station);
  26. });
  27. cb();
  28. }
  29. });
  30. },
  31. initializeStation: function(_station, cb) {
  32. if (typeof cb !== 'function') cb = ()=>{};
  33. let _this = this;
  34. _this.getStation(_station._id, (err, station) => {
  35. if (!err) {
  36. if (station) {
  37. let notification = notifications.subscribe(`stations.nextSong?id=${station._id}`, () => {
  38. console.log("NOTIFICATION!!!");
  39. _this.getStation(_station._id, (err, station) => {
  40. if (station) {
  41. // notify all the sockets on this station to go to the next song
  42. async.waterfall([
  43. (next) => {
  44. if (station.playlist.length > 0) {
  45. function func() {
  46. if (station.currentSongIndex < station.playlist.length - 1) {
  47. station.currentSongIndex++;
  48. songs.getSong(station.playlist[station.currentSongIndex], (err, song) => {
  49. if (!err) {
  50. let $set = {};
  51. $set.currentSong = {
  52. _id: song._id,
  53. title: song.title,
  54. artists: song.artists,
  55. duration: song.duration,
  56. likes: song.likes,
  57. dislikes: song.dislikes,
  58. skipDuration: song.skipDuration,
  59. thumbnail: song.thumbnail
  60. };
  61. $set.startedAt = Date.now();
  62. $set.timePaused = 0;
  63. next(null, $set);
  64. } else {
  65. db.models.station.update({_id: station._id}, {$inc: {currentSongIndex: 1}}, (err) => {
  66. _this.updateStation(station._id, () => {
  67. func();
  68. });
  69. });
  70. }
  71. });
  72. } else {
  73. db.models.station.update({_id: station._id}, {$set: {currentSongIndex: 0}}, (err) => {
  74. _this.updateStation(station._id, (err, station) => {
  75. console.log(12345678, err, station);
  76. _this.calculateSongForStation(station, (err, newPlaylist) => {
  77. console.log('New playlist: ', newPlaylist);
  78. if (!err) {
  79. songs.getSong(newPlaylist[0], (err, song) => {
  80. let $set = {};
  81. if (song) {
  82. $set.currentSong = {
  83. _id: song._id,
  84. title: song.title,
  85. artists: song.artists,
  86. duration: song.duration,
  87. likes: song.likes,
  88. dislikes: song.dislikes,
  89. skipDuration: song.skipDuration,
  90. thumbnail: song.thumbnail
  91. };
  92. station.playlist = newPlaylist;
  93. } else {
  94. $set.currentSong = _this.defaultSong;
  95. }
  96. $set.startedAt = Date.now();
  97. $set.timePaused = 0;
  98. next(null, $set);
  99. });
  100. } else {
  101. let $set = {};
  102. $set.currentSong = _this.defaultSong;
  103. $set.startedAt = Date.now();
  104. $set.timePaused = 0;
  105. next(null, $set);
  106. }
  107. })
  108. });
  109. });
  110. }
  111. }
  112. func();
  113. } else {
  114. _this.calculateSongForStation(station, (err, playlist) => {
  115. if (!err && playlist.length === 0) {
  116. let $set = {};
  117. $set.currentSongIndex = 0;
  118. $set.currentSong = _this.defaultSong;
  119. $set.startedAt = Date.now();
  120. $set.timePaused = 0;
  121. next(null, $set);
  122. } else {
  123. songs.getSong(playlist[0], (err, song) => {
  124. let $set = {};
  125. if (!err) {
  126. $set.currentSong = {
  127. _id: song._id,
  128. title: song.title,
  129. artists: song.artists,
  130. duration: song.duration,
  131. likes: song.likes,
  132. dislikes: song.dislikes,
  133. skipDuration: song.skipDuration,
  134. thumbnail: song.thumbnail
  135. };
  136. } else {
  137. $set.currentSong = _this.defaultSong;
  138. }
  139. $set.currentSongIndex = 0;
  140. $set.startedAt = Date.now();
  141. $set.timePaused = 0;
  142. next(null, $set);
  143. });
  144. }
  145. });
  146. }
  147. },
  148. ($set, next) => {
  149. db.models.station.update({_id: station._id}, {$set}, (err) => {
  150. _this.updateStation(station._id, (err, station) => {
  151. console.log(err, station);
  152. next(null, station);
  153. });
  154. });
  155. },
  156. ], (err, station) => {
  157. console.log(err, station);
  158. io.io.to(`station.${station._id}`).emit("event:songs.next", {
  159. currentSong: station.currentSong,
  160. startedAt: station.startedAt,
  161. paused: station.paused,
  162. timePaused: 0
  163. });
  164. utils.socketsJoinSongRoom(io.io.to(`station.${station._id}`).sockets, `song.${station.currentSong._id}`);
  165. // schedule a notification to be dispatched when the next song ends
  166. console.log("NEXT SONG!!!");
  167. if (!station.paused) {
  168. notifications.schedule(`stations.nextSong?id=${station._id}`, station.currentSong.duration * 1000);
  169. }
  170. cb(err, station);
  171. });
  172. }
  173. // the station doesn't exist anymore, unsubscribe from it
  174. else {
  175. notifications.remove(notification);
  176. }
  177. });
  178. }, true);
  179. if (!station.paused) {
  180. /*if (!station.startedAt) {
  181. station.startedAt = Date.now();
  182. station.timePaused = 0;
  183. cache.hset('stations', stationId, station);
  184. }*/
  185. let timeLeft = ((station.currentSong.duration * 1000) - (Date.now() - station.startedAt - station.timePaused));
  186. if (isNaN(timeLeft)) timeLeft = -1;
  187. if (station.currentSong.duration * 1000 < timeLeft || timeLeft < 0) {
  188. console.log("Test");
  189. notifications.schedule(`stations.nextSong?id=${station._id}`, 1);
  190. } else {
  191. notifications.schedule(`stations.nextSong?id=${station._id}`, timeLeft);
  192. }
  193. } else {
  194. notifications.unschedule(`stations.nextSong?id${station._id}`);
  195. }
  196. }
  197. }
  198. });
  199. },
  200. calculateSongForStation: function(station, cb) {
  201. let _this = this;
  202. let songList = [];
  203. async.waterfall([
  204. (next) => {
  205. let genresDone = [];
  206. station.genres.forEach((genre) => {
  207. db.models.song.find({genres: genre}, (err, songs) => {
  208. if (!err) {
  209. songs.forEach((song) => {
  210. if (songList.indexOf(song._id) === -1) songList.push(song._id);
  211. });
  212. }
  213. genresDone.push(genre);
  214. if (genresDone.length === station.genres.length) {
  215. next();
  216. }
  217. });
  218. });
  219. },
  220. (next) => {
  221. let playlist = [];
  222. songList.forEach(function(songId) {
  223. if(station.playlist.indexOf(songId) === -1) playlist.push(songId);
  224. });
  225. station.playlist.filter((songId) => {
  226. if (songList.indexOf(songId) !== -1) playlist.push(songId);
  227. });
  228. db.models.station.update({_id: station._id}, {$set: {playlist: playlist}}, (err) => {
  229. _this.updateStation(station._id, () => {
  230. next(err, playlist);
  231. });
  232. });
  233. }
  234. ], (err, newPlaylist) => {
  235. cb(err, newPlaylist);
  236. });
  237. },
  238. // Attempts to get the station from Redis. If it's not in Redis, get it from Mongo and add it to Redis.
  239. getStation: function(stationId, cb) {
  240. async.waterfall([
  241. (next) => {
  242. cache.hget('stations', stationId, next);
  243. },
  244. (station, next) => {
  245. if (station) return next(true, station);
  246. db.models.station.findOne({ _id: stationId }, next);
  247. },
  248. (station, next) => {
  249. if (station) {
  250. station = cache.schemas.station(station);
  251. cache.hset('stations', stationId, station);
  252. next(true, station);
  253. } else next('Station not found.');
  254. },
  255. ], (err, station) => {
  256. if (err && err !== true) cb(err);
  257. cb(null, station);
  258. });
  259. },
  260. updateStation: (stationId, cb) => {
  261. async.waterfall([
  262. (next) => {
  263. db.models.station.findOne({ _id: stationId }, next);
  264. },
  265. (station, next) => {
  266. if (!station) return next('Station not found.');
  267. cache.hset('stations', stationId, station, (err) => {
  268. if (err) return next(err);
  269. next(null, station);
  270. });
  271. }
  272. ], (err, station) => {
  273. if (err && err !== true) cb(err);
  274. cb(null, station);
  275. });
  276. },
  277. defaultSong: {
  278. _id: '60ItHLz5WEA',
  279. title: 'Faded',
  280. artists: ['Alan Walker'],
  281. duration: 212,
  282. skipDuration: 0,
  283. thumbnail: 'https://i.scdn.co/image/2ddde58427f632037093857ebb71a67ddbdec34b'
  284. }
  285. };