app.js 47 KB

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