app.js 43 KB

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