app.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  1. History = new Mongo.Collection("history");
  2. Playlists = new Mongo.Collection("playlists");
  3. Rooms = new Mongo.Collection("rooms");
  4. Queues = new Mongo.Collection("queues");
  5. Chat = new Mongo.Collection("chat");
  6. function htmlEntities(str) {
  7. return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  8. }
  9. if (Meteor.isClient) {
  10. Meteor.startup(function() {
  11. reCAPTCHA.config({
  12. publickey: '6LcVxg0TAAAAAE18vBiH00UAyaJggsmLm890SjZl'
  13. });
  14. });
  15. Meteor.subscribe("queues");
  16. var hpSound = undefined;
  17. var songsArr = [];
  18. var ytArr = [];
  19. var _sound = undefined;
  20. var parts = location.href.split('/');
  21. var id = parts.pop();
  22. var type = id.toLowerCase();
  23. function getSpotifyInfo(title, cb) {
  24. $.ajax({
  25. type: "GET",
  26. url: 'https://api.spotify.com/v1/search?q=' + encodeURIComponent(title.toLowerCase()) + '&type=track',
  27. applicationType: "application/json",
  28. contentType: "json",
  29. success: function (data) {
  30. cb(data);
  31. }
  32. });
  33. }
  34. function getSpotifyArtist(data) {
  35. var temp = "";
  36. var artist;
  37. if(data.artists.length >= 2){
  38. for(var k in data.artists){
  39. temp = temp + data.artists[k].name + ", ";
  40. }
  41. } else{
  42. for(var k in data.artists){
  43. temp = temp + data.artists[k].name;
  44. }
  45. }
  46. if(temp[temp.length-2] === ","){
  47. artist = temp.substr(0,temp.length-2);
  48. } else{
  49. artist = temp;
  50. }
  51. return artist;
  52. }
  53. curPath=function(){var c=window.location.pathname;var b=c.slice(0,-1);var a=c.slice(-1);if(b==""){return"/"}else{if(a=="/"){return b}else{return c}}};
  54. Handlebars.registerHelper('active', function(path) {
  55. return curPath() == path ? 'active' : '';
  56. });
  57. Template.header.helpers({
  58. currentUser: function() {
  59. return Meteor.user();
  60. },
  61. isAdmin: function() {
  62. if (Meteor.user() && Meteor.user().profile) {
  63. return Meteor.user().profile.rank === "admin";
  64. } else {
  65. return false;
  66. }
  67. }
  68. });
  69. Template.header.events({
  70. "click .logout": function(e){
  71. e.preventDefault();
  72. Meteor.logout();
  73. if (hpSound !== undefined) {
  74. hpSound.stop();
  75. }
  76. }
  77. });
  78. Template.register.events({
  79. "submit form": function(e){
  80. e.preventDefault();
  81. var username = e.target.registerUsername.value;
  82. var email = e.target.registerEmail.value;
  83. var password = e.target.registerPassword.value;
  84. var captchaData = grecaptcha.getResponse();
  85. Meteor.call("createUserMethod", {username: username, email: email, password: password}, captchaData, function(err, res) {
  86. grecaptcha.reset();
  87. console.log(username, password, err, res);
  88. if (err) {
  89. console.log(err);
  90. $(".container").after('<div class="alert alert-danger" role="alert"><strong>Oh Snap!</strong> ' + err.reason + '</div>')
  91. } else {
  92. console.log();
  93. Meteor.loginWithPassword(username, password);
  94. }
  95. });
  96. },
  97. "click #facebook-login": function(){
  98. Meteor.loginWithFacebook()
  99. },
  100. "click #github-login": function(){
  101. Meteor.loginWithGithub()
  102. },
  103. "click #login": function(){
  104. $("#register-view").hide();
  105. $("#login-view").show();
  106. }
  107. });
  108. Template.login.events({
  109. "submit form": function(e){
  110. e.preventDefault();
  111. var username = e.target.loginUsername.value;
  112. var password = e.target.loginPassword.value;
  113. Meteor.loginWithPassword(username, password);
  114. Accounts.onLoginFailure(function(){
  115. $("input").css("background-color","indianred").addClass("animated shake");
  116. $("input").on("click",function(){
  117. $("input").css({
  118. "background-color": "transparent",
  119. "width": "250px"
  120. });
  121. })
  122. });
  123. },
  124. "click #facebook-login": function(){
  125. Meteor.loginWithFacebook()
  126. },
  127. "click #github-login": function(){
  128. Meteor.loginWithGithub()
  129. },
  130. "click #register": function(){
  131. $("#login-view").hide();
  132. $("#register-view").show();
  133. }
  134. });
  135. Template.dashboard.events({
  136. "click #croom_create": function() {
  137. Meteor.call("createRoom", $("#croom").val(), function (err, res) {
  138. if (err) {
  139. alert("Error " + err.error + ": " + err.reason);
  140. } else {
  141. window.location = "/" + $("#croom").val();
  142. }
  143. });
  144. }
  145. });
  146. Template.dashboard.helpers({
  147. rooms: function() {
  148. return Rooms.find({});
  149. }
  150. })
  151. Template.room.events({
  152. "click #add-song-button": function(e){
  153. e.preventDefault();
  154. parts = location.href.split('/');
  155. id = parts.pop();
  156. var genre = id.toLowerCase();
  157. var type = $("#type").val();
  158. id = $("#id").val();
  159. var title = $("#title").val();
  160. var artist = $("#artist").val();
  161. var img = $("#img").val();
  162. var songData = {type: type, id: id, title: title, artist: artist, img: img};
  163. Meteor.call("addSongToQueue", genre, songData, function(err, res) {
  164. console.log(err, res);
  165. });
  166. },
  167. "click #return": function(e){
  168. $("#add-info").hide();
  169. $("#search-info").show();
  170. },
  171. "click #search-song": function(){
  172. $("#song-results").empty();
  173. var search_type = $("#search_type").val();
  174. if (search_type === "YouTube") {
  175. $.ajax({
  176. type: "GET",
  177. url: "https://www.googleapis.com/youtube/v3/search?part=snippet&q=" + $("#song-input").val() + "&key=AIzaSyAgBdacEWrHCHVPPM4k-AFM7uXg-Q__YXY",
  178. applicationType: "application/json",
  179. contentType: "json",
  180. success: function(data){
  181. for(var i in data.items){
  182. $("#song-results").append("<p>" + data.items[i].snippet.title + "</p>");
  183. ytArr.push({title: data.items[i].snippet.title, id: data.items[i].id.videoId});
  184. }
  185. $("#song-results p").click(function(){
  186. $("#search-info").hide();
  187. $("#add-info").show();
  188. var title = $(this).text();
  189. for(var i in ytArr){
  190. if(ytArr[i].title === title){
  191. var songObj = {
  192. id: ytArr[i].id,
  193. title: ytArr[i].title,
  194. type: "youtube"
  195. };
  196. $("#title").val(songObj.title);
  197. $("#artist").val("");
  198. $("#id").val(songObj.id);
  199. $("#type").val("YouTube");
  200. getSpotifyInfo(songObj.title.replace(/\[.*\]/g, ""), function(data) {
  201. if (data.tracks.items.length > 0) {
  202. $("#title").val(data.tracks.items[0].name);
  203. var artists = [];
  204. $("#img").val(data.tracks.items[0].album.images[1].url);
  205. data.tracks.items[0].artists.forEach(function(artist) {
  206. artists.push(artist.name);
  207. });
  208. $("#artist").val(artists.join(", "));
  209. }
  210. });
  211. }
  212. }
  213. })
  214. }
  215. })
  216. } else if (search_type === "SoundCloud") {
  217. SC.get('/tracks', { q: $("#song-input").val()}, function(tracks) {
  218. for(var i in tracks){
  219. $("#song-results").append("<p>" + tracks[i].title + "</p>")
  220. songsArr.push({title: tracks[i].title, id: tracks[i].id, duration: tracks[i].duration / 1000});
  221. }
  222. $("#song-results p").click(function(){
  223. $("#search-info").hide();
  224. $("#add-info").show();
  225. var title = $(this).text();
  226. for(var i in songsArr){
  227. if(songsArr[i].title === title){
  228. var id = songsArr[i].id;
  229. var duration = songsArr[i].duration;
  230. var songObj = {
  231. title: songsArr[i].title,
  232. id: id,
  233. duration: duration,
  234. type: "soundcloud"
  235. }
  236. $("#title").val(songObj.title);
  237. // Set ID field
  238. $("#id").val(songObj.id);
  239. $("#type").val("SoundCloud");
  240. getSpotifyInfo(songObj.title.replace(/\[.*\]/g, ""), function(data) {
  241. if (data.tracks.items.length > 0) {
  242. $("#title").val(data.tracks.items[0].name);
  243. var artists = [];
  244. data.tracks.items[0].artists.forEach(function(artist) {
  245. artists.push(artist.name);
  246. });
  247. $("#artist").val(artists.join(", "));
  248. }
  249. // Set title field again if possible
  250. // Set artist if possible
  251. });
  252. }
  253. }
  254. })
  255. });
  256. }
  257. },
  258. "click #add-songs": function(){
  259. $("#add-songs-modal").show();
  260. },
  261. "click #close-modal": function(){
  262. $("#search-info").show();
  263. $("#add-info").hide();
  264. },
  265. "click #submit-message": function(){
  266. var message = $("#chat-input").val();
  267. Meteor.call("sendMessage", type, message);
  268. }
  269. });
  270. Template.room.helpers({
  271. type: function() {
  272. var parts = location.href.split('/');
  273. var id = parts.pop();
  274. return id.toUpperCase();
  275. },
  276. title: function(){
  277. return Session.get("title");
  278. },
  279. artist: function(){
  280. return Session.get("artist");
  281. },
  282. title_next: function(){
  283. return Session.get("title_next");
  284. },
  285. artist_next: function(){
  286. return Session.get("artist_next");
  287. },
  288. title_after: function(){
  289. return Session.get("title_after");
  290. },
  291. artist_after: function(){
  292. return Session.get("artist_after");
  293. },
  294. loaded: function() {
  295. return Session.get("loaded");
  296. },
  297. chat: function() {
  298. var chatArr = Chat.find({type: type}).fetch();
  299. if (chatArr.length === 0) {
  300. return [];
  301. } else {
  302. return chatArr[0].messages;
  303. }
  304. }
  305. });
  306. Template.admin.helpers({
  307. queues: function() {
  308. return Queues.find({});
  309. }
  310. });
  311. var yt_player = undefined;
  312. var _sound = undefined;
  313. Template.admin.events({
  314. "click .preview-button": function(e){
  315. Session.set("song", this);
  316. },
  317. "click #add-song-button": function(e){
  318. var genre = $(e.toElement).data("genre") || $(e.toElement).parent().data("genre");
  319. Meteor.call("addSongToPlaylist", genre, this);
  320. },
  321. "click #deny-song-button": function(e){
  322. var genre = $(e.toElement).data("genre") || $(e.toElement).parent().data("genre");
  323. Meteor.call("removeSongFromQueue", genre, this.id);
  324. },
  325. "click #play": function() {
  326. $("#play").attr("disabled", true);
  327. $("#stop").attr("disabled", false);
  328. var song = Session.get("song");
  329. var id = song.id;
  330. var type = song.type;
  331. if (type === "YouTube") {
  332. if (yt_player === undefined) {
  333. yt_player = new YT.Player("previewPlayer", {
  334. height: 540,
  335. width: 568,
  336. videoId: id,
  337. playerVars: {autoplay: 1, controls: 0, iv_load_policy: 3},
  338. events: {
  339. 'onReady': function(event) {
  340. event.target.playVideo();
  341. }
  342. }
  343. });
  344. } else {
  345. yt_player.loadVideoById(id);
  346. }
  347. $("#previewPlayer").show();
  348. } else if (type === "SoundCloud") {
  349. SC.stream("/tracks/" + song.id, function(sound) {
  350. _sound = sound;
  351. sound._player._volume = 0.3;
  352. sound.play();
  353. });
  354. }
  355. },
  356. "click #stop": function() {
  357. $("#play").attr("disabled", false);
  358. $("#stop").attr("disabled", true);
  359. if (yt_player !== undefined) {
  360. yt_player.stopVideo();
  361. }
  362. if (_sound !== undefined) {
  363. _sound.stop();
  364. }
  365. }
  366. });
  367. Template.admin.onCreated(function() {
  368. var tag = document.createElement("script");
  369. tag.src = "https://www.youtube.com/iframe_api";
  370. var firstScriptTag = document.getElementsByTagName('script')[0];
  371. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  372. });
  373. Template.admin.onRendered(function() {
  374. $("#previewModal").on("hidden.bs.modal", function() {
  375. if (yt_player !== undefined) {
  376. $("#play").attr("disabled", false);
  377. $("#stop").attr("disabled", true);
  378. $("#previewPlayer").hide();
  379. yt_player.loadVideoById("", 0);
  380. yt_player.seekTo(0);
  381. yt_player.stopVideo();
  382. }
  383. if (_sound !== undefined) {
  384. _sound.stop();
  385. $("#play").attr("disabled", false);
  386. $("#stop").attr("disabled", true);
  387. }
  388. });
  389. });
  390. Template.playlist.helpers({
  391. playlist_songs: function() {
  392. var data = Playlists.find({type: type}).fetch();
  393. if (data !== undefined && data.length > 0) {
  394. return data[0].songs;
  395. } else {
  396. return [];
  397. }
  398. }
  399. });
  400. Meteor.subscribe("rooms");
  401. Meteor.subscribe("chat");
  402. Template.room.onCreated(function () {
  403. var tag = document.createElement("script");
  404. tag.src = "https://www.youtube.com/iframe_api";
  405. var firstScriptTag = document.getElementsByTagName('script')[0];
  406. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  407. var currentSong = undefined;
  408. var nextSong = undefined;
  409. var afterSong = undefined;
  410. var _sound = undefined;
  411. var yt_player = undefined;
  412. var size = 0;
  413. var artistStr;
  414. var temp = "";
  415. var currentArt;
  416. function getTimeElapsed() {
  417. if (currentSong !== undefined) {
  418. return Date.now() - currentSong.started;
  419. }
  420. return 0;
  421. }
  422. function getSongInfo(songData){
  423. Session.set("title", songData.title);
  424. Session.set("artist", songData.artist);
  425. $("#song-img").attr("src", songData.img);
  426. Session.set("duration", songData.duration);
  427. }
  428. function resizeSeekerbar() {
  429. $("#seeker-bar").width(((getTimeElapsed() / 1000) / Session.get("duration") * 100) + "%");
  430. }
  431. function startSong() {
  432. if (currentSong !== undefined) {
  433. if (_sound !== undefined) _sound.stop();
  434. if (yt_player !== undefined && yt_player.stopVideo !== undefined) yt_player.stopVideo();
  435. if (currentSong.type === "soundcloud") {
  436. $("#player").attr("src", "")
  437. getSongInfo(currentSong);
  438. SC.stream("/tracks/" + currentSong.id + "#t=20s", function(sound){
  439. _sound = sound;
  440. sound._player._volume = 0.3;
  441. sound.play();
  442. var interval = setInterval(function() {
  443. if (sound.getState() === "playing") {
  444. sound.seek(getTimeElapsed());
  445. window.clearInterval(interval);
  446. }
  447. }, 200);
  448. // Session.set("title", currentSong.title || "Title");
  449. // Session.set("artist", currentSong.artist || "Artist");
  450. Session.set("duration", currentSong.duration);
  451. resizeSeekerbar();
  452. });
  453. } else {
  454. if (yt_player === undefined) {
  455. yt_player = new YT.Player("player", {
  456. height: 540,
  457. width: 960,
  458. videoId: currentSong.id,
  459. events: {
  460. 'onReady': function(event) {
  461. event.target.seekTo(getTimeElapsed() / 1000);
  462. event.target.playVideo();
  463. resizeSeekerbar();
  464. },
  465. 'onStateChange': function(event){
  466. if (event.data == YT.PlayerState.PAUSED) {
  467. event.target.seekTo(getTimeElapsed() / 1000);
  468. event.target.playVideo();
  469. }
  470. }
  471. }
  472. });
  473. } else {
  474. yt_player.loadVideoById(currentSong.id);
  475. }
  476. // Session.set("title", currentSong.title || "Title");
  477. // Session.set("artist", currentSong.artist || "Artist");
  478. getSongInfo(currentSong);
  479. //Session.set("duration", currentSong.duration);
  480. }
  481. }
  482. }
  483. Meteor.subscribe("history");
  484. Meteor.subscribe("playlists");
  485. Session.set("loaded", false);
  486. Meteor.subscribe("rooms", function() {
  487. var parts = location.href.split('/');
  488. var id = parts.pop();
  489. var type = id.toLowerCase();
  490. if (Rooms.find({type: type}).count() !== 1) {
  491. window.location = "/";
  492. } else {
  493. Session.set("loaded", true);
  494. Meteor.setInterval(function () {
  495. var data = undefined;
  496. var dataCursorH = History.find({type: type});
  497. var dataCursorP = Playlists.find({type: type});
  498. dataCursorH.forEach(function (doc) {
  499. if (data === undefined) {
  500. data = doc;
  501. }
  502. });
  503. if (data !== undefined && data.history.length > size) {
  504. //currentSong = data.history[data.history.length - 1];
  505. var songArray = Playlists.find({type: type}).fetch()[0].songs;
  506. var historyObj = data.history[data.history.length - 1];
  507. songArray.forEach(function(song) {
  508. if (song.id === historyObj.song.id) {
  509. currentSong = song;
  510. }
  511. });
  512. currentSong.started = historyObj.started;
  513. var songs = dataCursorP.fetch()[0].songs;
  514. songs.forEach(function(song, index) {
  515. if (currentSong.title === song.title) {
  516. if (index + 1 < songs.length) {
  517. nextSong = songs[index + 1];
  518. } else {
  519. nextSong = songs[0];
  520. }
  521. Session.set("title_next", nextSong.title);
  522. Session.set("artist_next", nextSong.artist);
  523. $("#song-img-next").attr("src", nextSong.img);
  524. if (index + 2 < songs.length) {
  525. afterSong = songs[index + 2];
  526. } else if (songs.length === index + 1 && songs.length > 1 ) {
  527. afterSong = songs[1];
  528. } else {
  529. afterSong = songs[0];
  530. }
  531. Session.set("title_after", afterSong.title);
  532. Session.set("artist_after", afterSong.artist);
  533. $("#song-img-after").attr("src",afterSong.img);
  534. }
  535. });
  536. size = data.history.length;
  537. startSong();
  538. }
  539. }, 1000);
  540. Meteor.setInterval(function () {
  541. resizeSeekerbar();
  542. }, 50);
  543. }
  544. });
  545. });
  546. }
  547. if (Meteor.isServer) {
  548. Meteor.startup(function() {
  549. reCAPTCHA.config({
  550. privatekey: '6LcVxg0TAAAAAI2fgIEEWHFxwNXeVIs8mzq5cfRM'
  551. });
  552. });
  553. Meteor.users.deny({update: function () { return true; }});
  554. Meteor.users.deny({insert: function () { return true; }});
  555. Meteor.users.deny({remove: function () { return true; }});
  556. function getSongDuration(query){
  557. var duration;
  558. var search = query;
  559. query = query.toLowerCase().split(" ").join("%20");
  560. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + query + '&type=track');
  561. for(var i in res.data){
  562. for(var j in res.data[i].items){
  563. if(search.indexOf(res.data[i].items[j].name) !== -1){
  564. duration = res.data[i].items[j].duration_ms / 1000;
  565. return duration;
  566. }
  567. }
  568. }
  569. }
  570. function getSongAlbumArt(query){
  571. var albumart;
  572. var search = query;
  573. query = query.toLowerCase().split(" ").join("%20");
  574. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + query + '&type=track');
  575. for(var i in res.data){
  576. for(var j in res.data[i].items){
  577. if(search.indexOf(res.data[i].items[j].name) !== -1){
  578. albumart = res.data[i].items[j].album.images[1].url
  579. return albumart;
  580. }
  581. }
  582. }
  583. }
  584. //var room_types = ["edm", "nightcore"];
  585. var songsArr = [];
  586. function getSongsByType(type) {
  587. if (type === "edm") {
  588. return [
  589. {id: "aE2GCa-_nyU", title: "Radioactive - Lindsey Stirling and Pentatonix", duration: getSongDuration("Radioactive - Lindsey Stirling and Pentatonix"), artist: "Lindsey Stirling, Pentatonix", type: "youtube", img: "https://i.scdn.co/image/62167a9007cef2e8ef13ab1d93019312b9b03655"},
  590. {id: "aHjpOzsQ9YI", title: "Crystallize", artist: "Lindsey Stirling", duration: getSongDuration("Crystallize"), type: "youtube", img: "https://i.scdn.co/image/b0c1ccdd0cd7bcda741ccc1c3e036f4ed2e52312"}
  591. ];
  592. } else if (type === "nightcore") {
  593. return [{id: "f7RKOP87tt4", title: "Monster (DotEXE Remix)", duration: getSongDuration("Monster (DotEXE Remix)"), artist: "Meg & Dia", type: "youtube", img: "https://i.scdn.co/image/35ecdfba9c31a6c54ee4c73dcf1ad474c560cd00"}];
  594. } else {
  595. return [{id: "dQw4w9WgXcQ", title: "Never Gonna Give You Up", duration: getSongDuration("Never Gonna Give You Up"), artist: "Rick Astley", type: "youtube", img: "https://i.scdn.co/image/5246898e19195715e65e261899baba890a2c1ded"}];
  596. }
  597. }
  598. Rooms.find({}).fetch().forEach(function(room) {
  599. var type = room.type;
  600. if (Playlists.find({type: type}).count() === 0) {
  601. if (type === "edm") {
  602. Playlists.insert({type: type, songs: getSongsByType(type)});
  603. } else if (type === "nightcore") {
  604. Playlists.insert({type: type, songs: getSongsByType(type)});
  605. } else {
  606. Playlists.insert({type: type, songs: getSongsByType(type)});
  607. }
  608. }
  609. if (History.find({type: type}).count() === 0) {
  610. History.insert({type: type, history: []});
  611. }
  612. if (Playlists.find({type: type}).fetch()[0].songs.length === 0) {
  613. // Add a global video to Playlist so it can proceed
  614. } else {
  615. var startedAt = Date.now();
  616. var playlist = Playlists.find({type: type}).fetch()[0];
  617. var songs = playlist.songs;
  618. if (playlist.lastSong === undefined) {
  619. Playlists.update({type: type}, {$set: {lastSong: 0}});
  620. playlist = Playlists.find({type: type}).fetch()[0];
  621. songs = playlist.songs;
  622. }
  623. var currentSong = playlist.lastSong;
  624. addToHistory(songs[currentSong], startedAt);
  625. function addToHistory(song, startedAt) {
  626. History.update({type: type}, {$push: {history: {song: song, started: startedAt}}});
  627. }
  628. function skipSong() {
  629. songs = Playlists.find({type: type}).fetch()[0].songs;
  630. if (currentSong < (songs.length - 1)) {
  631. currentSong++;
  632. } else currentSong = 0;
  633. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  634. songTimer();
  635. addToHistory(songs[currentSong], startedAt);
  636. }
  637. function songTimer() {
  638. startedAt = Date.now();
  639. Meteor.setTimeout(function() {
  640. skipSong();
  641. }, songs[currentSong].duration * 1000);
  642. }
  643. songTimer();
  644. }
  645. });
  646. Accounts.onCreateUser(function(options, user) {
  647. var username;
  648. if (user.services) {
  649. if (user.services.github) {
  650. username = user.services.github.username;
  651. } else if (user.services.facebook) {
  652. //username = user.services.facebook.username;
  653. } else if (user.services.password) {
  654. username = user.username;
  655. }
  656. }
  657. user.profile = {username: username, rank: "default"};
  658. return user;
  659. });
  660. ServiceConfiguration.configurations.remove({
  661. service: "facebook"
  662. });
  663. ServiceConfiguration.configurations.insert({
  664. service: "facebook",
  665. appId: "1496014310695890",
  666. secret: "9a039f254a08a1488c08bb0737dbd2a6"
  667. });
  668. ServiceConfiguration.configurations.remove({
  669. service: "github"
  670. });
  671. ServiceConfiguration.configurations.insert({
  672. service: "github",
  673. clientId: "dcecd720f47c0e4001f7",
  674. secret: "375939d001ef1a0ca67c11dbf8fb9aeaa551e01b"
  675. });
  676. Meteor.publish("history", function() {
  677. return History.find({})
  678. });
  679. Meteor.publish("playlists", function() {
  680. return Playlists.find({})
  681. });
  682. Meteor.publish("rooms", function() {
  683. return Rooms.find({});
  684. });
  685. Meteor.publish("queues", function() {
  686. return Queues.find({});
  687. });
  688. Meteor.publish("chat", function() {
  689. return Chat.find({});
  690. });
  691. Meteor.publish("isAdmin", function() {
  692. return Meteor.users.find({_id: this.userId, "profile.rank": "admin"});
  693. });
  694. Meteor.methods({
  695. createUserMethod: function(formData, captchaData) {
  696. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  697. if (!verifyCaptchaResponse.success) {
  698. console.log('reCAPTCHA check failed!', verifyCaptchaResponse);
  699. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  700. } else {
  701. console.log('reCAPTCHA verification passed!');
  702. Accounts.createUser({
  703. username: formData.username,
  704. email: formData.email,
  705. password: formData.password
  706. });
  707. }
  708. return true;
  709. },
  710. sendMessage: function(type, message) {
  711. if (Chat.find({type: type}).count() === 0) {
  712. Chat.insert({type: type, messages: []});
  713. }
  714. Chat.update({type: type}, {$push: {messages: {message: message, userid: "Kris"}}})
  715. },
  716. addSongToQueue: function(type, songData) {
  717. type = type.toLowerCase();
  718. if (Rooms.find({type: type}).count() === 1) {
  719. if (Queues.find({type: type}).count() === 0) {
  720. Queues.insert({type: type, songs: []});
  721. }
  722. if (songData !== undefined && Object.keys(songData).length === 5 && songData.type !== undefined && songData.title !== undefined && songData.title !== undefined && songData.artist !== undefined && songData.img !== undefined) {
  723. songData.duration = getSongDuration(songData.title);
  724. Queues.update({type: type}, {$push: {songs: {id: songData.id, title: songData.title, artist: songData.artist, duration: songData.duration, img: songData.img, type: songData.type}}});
  725. return true;
  726. } else {
  727. throw new Meteor.error(403, "Invalid data.");
  728. }
  729. } else {
  730. throw new Meteor.error(403, "Invalid genre.");
  731. }
  732. },
  733. removeSongFromQueue: function(type, songId) {
  734. type = type.toLowerCase();
  735. Queues.update({type: type}, {$pull: {songs: {id: songId}}});
  736. },
  737. addSongToPlaylist: function(type, songData) {
  738. type = type.toLowerCase();
  739. if (Rooms.find({type: type}).count() === 1) {
  740. if (Playlists.find({type: type}).count() === 0) {
  741. Playlists.insert({type: type, songs: []});
  742. }
  743. if (songData !== undefined && Object.keys(songData).length === 6 && songData.type !== undefined && songData.title !== undefined && songData.title !== undefined && songData.artist !== undefined && songData.duration !== undefined && songData.img !== undefined) {
  744. Playlists.update({type: type}, {$push: {songs: {id: songData.id, title: songData.title, artist: songData.artist, duration: songData.duration, img: songData.img, type: songData.type}}});
  745. Queues.update({type: type}, {$pull: {songs: {id: songData.id}}});
  746. return true;
  747. } else {
  748. throw new Meteor.error(403, "Invalid data.");
  749. }
  750. } else {
  751. throw new Meteor.error(403, "Invalid genre.");
  752. }
  753. },
  754. createRoom: function(type) {
  755. if (Rooms.find({type: type}).count() === 0) {
  756. Rooms.insert({type: type}, function(err) {
  757. if (err) {
  758. throw err;
  759. } else {
  760. if (Playlists.find({type: type}).count() === 1) {
  761. if (History.find({type: type}).count() === 0) {
  762. History.insert({type: type, history: []}, function(err3) {
  763. if (err3) {
  764. throw err3;
  765. } else {
  766. startStation();
  767. return true;
  768. }
  769. });
  770. } else {
  771. startStation();
  772. return true;
  773. }
  774. } else {
  775. Playlists.insert({type: type, songs: getSongsByType(type)}, function (err2) {
  776. if (err2) {
  777. throw err2;
  778. } else {
  779. if (History.find({type: type}).count() === 0) {
  780. History.insert({type: type, history: []}, function(err3) {
  781. if (err3) {
  782. throw err3;
  783. } else {
  784. startStation();
  785. return true;
  786. }
  787. });
  788. } else {
  789. startStation();
  790. return true;
  791. }
  792. }
  793. });
  794. }
  795. }
  796. });
  797. } else {
  798. throw "Room already exists";
  799. }
  800. function startStation() {
  801. var startedAt = Date.now();
  802. var songs = Playlists.find({type: type}).fetch()[0].songs;
  803. var currentSong = 0;
  804. addToHistory(songs[currentSong], startedAt);
  805. function addToHistory(song, startedAt) {
  806. History.update({type: type}, {$push: {history: {song: song, started: startedAt}}});
  807. }
  808. function skipSong() {
  809. songs = Playlists.find({type: type}).fetch()[0].songs;
  810. if (currentSong < (songs.length - 1)) {
  811. currentSong++;
  812. } else currentSong = 0;
  813. songTimer();
  814. addToHistory(songs[currentSong], startedAt);
  815. }
  816. function songTimer() {
  817. startedAt = Date.now();
  818. Meteor.setTimeout(function() {
  819. skipSong();
  820. }, songs[currentSong].duration * 1000);
  821. }
  822. songTimer();
  823. }
  824. }
  825. });
  826. }
  827. /*Router.waitOn(function() {
  828. Meteor.subscribe("isAdmin", Meteor.userId());
  829. });*/
  830. /*Router.onBeforeAction(function() {
  831. /*Meteor.autorun(function () {
  832. if (admin.ready()) {
  833. this.next();
  834. }
  835. });*/
  836. /*this.next();
  837. });*/
  838. Router.route("/", {
  839. template: "home"
  840. });
  841. Router.route("/terms", {
  842. template: "terms"
  843. });
  844. Router.route("/privacy", {
  845. template: "privacy"
  846. });
  847. Router.route("/admin", {
  848. waitOn: function() {
  849. return Meteor.subscribe("isAdmin", Meteor.userId());
  850. },
  851. action: function() {
  852. var user = Meteor.users.find({}).fetch();
  853. if (user[0] !== undefined && user[0].profile !== undefined && user[0].profile.rank === "admin") {
  854. this.render("admin");
  855. } else {
  856. this.redirect("/");
  857. }
  858. }
  859. });
  860. Router.route("/:type", {
  861. template: "room"
  862. });