app.js 35 KB

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