app.js 46 KB

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