app.js 48 KB

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