app.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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. if (val.value === 0) {
  353. $("#volume-icon").removeClass("fa-volume-down").addClass("fa-volume-off")
  354. } else {
  355. $("#volume-icon").removeClass("fa-volume-off").addClass("fa-volume-down")
  356. }
  357. if (yt_player !== undefined) {
  358. yt_player.setVolume(val.value);
  359. localStorage.setItem("volume", val.value);
  360. } else if (_sound !== undefined) {
  361. //_sound
  362. var volume = val.value / 100;
  363. _sound.setVolume(volume);
  364. localStorage.setItem("volume", val.value);
  365. }
  366. });
  367. }
  368. }
  369. makeSlider();
  370. });
  371. });
  372. Template.room.helpers({
  373. type: function() {
  374. var parts = location.href.split('/');
  375. var id = parts.pop();
  376. return id.toUpperCase();
  377. },
  378. title: function(){
  379. return Session.get("title");
  380. },
  381. artist: function(){
  382. return Session.get("artist");
  383. },
  384. title_next: function(){
  385. return Session.get("title_next");
  386. },
  387. artist_next: function(){
  388. return Session.get("artist_next");
  389. },
  390. title_after: function(){
  391. return Session.get("title_after");
  392. },
  393. artist_after: function(){
  394. return Session.get("artist_after");
  395. },
  396. loaded: function() {
  397. return Session.get("loaded");
  398. }
  399. });
  400. Template.admin.helpers({
  401. queues: function() {
  402. return Queues.find({});
  403. }
  404. });
  405. var yt_player = undefined;
  406. var _sound = undefined;
  407. Template.admin.events({
  408. "click .preview-button": function(e){
  409. Session.set("song", this);
  410. },
  411. "click .edit-button": function(e){
  412. Session.set("song", this);
  413. Session.set("genre", $(e.toElement).data("genre"));
  414. $("#type").val(this.type);
  415. $("#artist").val(this.artist);
  416. $("#title").val(this.title);
  417. $("#img").val(this.img);
  418. $("#id").val(this.id);
  419. $("#duration").val(this.duration);
  420. },
  421. "click #add-song-button": function(e){
  422. var genre = $(e.toElement).data("genre") || $(e.toElement).parent().data("genre");
  423. Meteor.call("addSongToPlaylist", genre, this);
  424. },
  425. "click #deny-song-button": function(e){
  426. var genre = $(e.toElement).data("genre") || $(e.toElement).parent().data("genre");
  427. Meteor.call("removeSongFromQueue", genre, this.id);
  428. },
  429. "click #play": function() {
  430. $("#play").attr("disabled", true);
  431. $("#stop").attr("disabled", false);
  432. var song = Session.get("song");
  433. var id = song.id;
  434. var type = song.type;
  435. var volume = localStorage.getItem("volume") || 20;
  436. if (type === "YouTube") {
  437. if (yt_player === undefined) {
  438. yt_player = new YT.Player("previewPlayer", {
  439. height: 540,
  440. width: 568,
  441. videoId: id,
  442. playerVars: {autoplay: 1, controls: 0, iv_load_policy: 3, showinfo: 0},
  443. events: {
  444. 'onReady': function(event) {
  445. event.target.playVideo();
  446. event.target.setVolume(volume);
  447. },
  448. 'onStateChange': function(event){
  449. if (event.data == YT.PlayerState.PAUSED) {
  450. event.target.playVideo();
  451. }
  452. if (event.data == YT.PlayerState.PLAYING) {
  453. $("#play").attr("disabled", true);
  454. $("#stop").attr("disabled", false);
  455. } else {
  456. $("#play").attr("disabled", false);
  457. $("#stop").attr("disabled", true);
  458. }
  459. }
  460. }
  461. });
  462. } else {
  463. yt_player.loadVideoById(id);
  464. }
  465. $("#previewPlayer").show();
  466. } else if (type === "SoundCloud") {
  467. SC.stream("/tracks/" + song.id, function(sound) {
  468. _sound = sound;
  469. sound.setVolume(volume / 100);
  470. sound.play();
  471. });
  472. }
  473. },
  474. "click #stop": function() {
  475. $("#play").attr("disabled", false);
  476. $("#stop").attr("disabled", true);
  477. if (yt_player !== undefined) {
  478. yt_player.stopVideo();
  479. }
  480. if (_sound !== undefined) {
  481. _sound.stop();
  482. }
  483. },
  484. "click #croom_create": function() {
  485. Meteor.call("createRoom", $("#croom").val(), function (err, res) {
  486. if (err) {
  487. alert("Error " + err.error + ": " + err.reason);
  488. } else {
  489. window.location = "/" + $("#croom").val();
  490. }
  491. });
  492. },
  493. "click #find-img-button": function() {
  494. getSpotifyInfo($("#title").val().replace(/\[.*\]/g, ""), function(data) {
  495. if (data.tracks.items.length > 0) {
  496. $("#img").val(data.tracks.items[0].album.images[1].url);
  497. }
  498. }, $("#artist").val());
  499. },
  500. "click #save-song-button": function() {
  501. var newSong = {};
  502. newSong.title = $("#title").val();
  503. newSong.artist = $("#artist").val();
  504. newSong.img = $("#img").val();
  505. newSong.type = $("#type").val();
  506. newSong.duration = $("#duration").val();
  507. Meteor.call("updateQueueSong", Session.get("genre"), Session.get("song"), newSong, function() {
  508. $('#editModal').modal('hide');
  509. });
  510. }
  511. });
  512. Template.admin.onCreated(function() {
  513. var tag = document.createElement("script");
  514. tag.src = "https://www.youtube.com/iframe_api";
  515. var firstScriptTag = document.getElementsByTagName('script')[0];
  516. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  517. });
  518. Template.admin.onRendered(function() {
  519. $("#previewModal").on("hidden.bs.modal", function() {
  520. if (yt_player !== undefined) {
  521. $("#play").attr("disabled", false);
  522. $("#stop").attr("disabled", true);
  523. $("#previewPlayer").hide();
  524. yt_player.loadVideoById("", 0);
  525. yt_player.seekTo(0);
  526. yt_player.stopVideo();
  527. }
  528. if (_sound !== undefined) {
  529. _sound.stop();
  530. $("#play").attr("disabled", false);
  531. $("#stop").attr("disabled", true);
  532. }
  533. });
  534. $(document).ready(function() {
  535. function makeSlider(){
  536. var slider = $("#volume-slider").slider();
  537. var volume = localStorage.getItem("volume") || 20;
  538. $("#volume-slider").slider("setValue", volume);
  539. if (slider.length === 0) {
  540. Meteor.setTimeout(function() {
  541. makeSlider();
  542. }, 500);
  543. } else {
  544. slider.on("slide", function(val) {
  545. localStorage.setItem("volume", val.value);
  546. if (yt_player !== undefined) {
  547. yt_player.setVolume(val.value);
  548. } else if (_sound !== undefined) {
  549. var volume = val.value / 100;
  550. _sound.setVolume(volume);
  551. }
  552. });
  553. }
  554. }
  555. makeSlider();
  556. });
  557. });
  558. Template.playlist.helpers({
  559. playlist_songs: function() {
  560. parts = location.href.split('/');
  561. id = parts.pop();
  562. type = id.toLowerCase();
  563. var data = Playlists.find({type: type}).fetch();
  564. if (data !== undefined && data.length > 0) {
  565. data[0].songs.map(function(song) {
  566. if (song.title === Session.get("title")) {
  567. song.current = true;
  568. } else {
  569. song.current = false;
  570. }
  571. return song;
  572. });
  573. return data[0].songs;
  574. } else {
  575. return [];
  576. }
  577. }
  578. });
  579. Meteor.subscribe("rooms");
  580. Meteor.subscribe("chat");
  581. Template.room.onCreated(function () {
  582. if (resizeSeekerbarInterval !== undefined) {
  583. Meteor.clearInterval(resizeSeekerbarInterval);
  584. resizeSeekerbarInterval = undefined;
  585. }
  586. yt_player = undefined;
  587. _sound = undefined;
  588. Session.set("videoHidden", false)
  589. var tag = document.createElement("script");
  590. tag.src = "https://www.youtube.com/iframe_api";
  591. var firstScriptTag = document.getElementsByTagName('script')[0];
  592. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag)
  593. var currentSong = undefined;
  594. var nextSong = undefined;
  595. var afterSong = undefined;
  596. var size = 0;
  597. var artistStr;
  598. var temp = "";
  599. var currentArt;
  600. function getTimeElapsed() {
  601. if (currentSong !== undefined) {
  602. return Date.now() - currentSong.started;
  603. }
  604. return 0;
  605. }
  606. function getSongInfo(songData){
  607. Session.set("title", songData.title);
  608. Session.set("artist", songData.artist);
  609. $("#song-img").attr("src", songData.img);
  610. Session.set("duration", songData.duration);
  611. }
  612. function resizeSeekerbar() {
  613. $("#seeker-bar").width(((getTimeElapsed() / 1000) / Session.get("duration") * 100) + "%");
  614. }
  615. function startSong() {
  616. if (currentSong !== undefined) {
  617. if (_sound !== undefined) _sound.stop();
  618. if (yt_player !== undefined && yt_player.stopVideo !== undefined) yt_player.stopVideo();
  619. var volume = localStorage.getItem("volume") || 20;
  620. $("#media-container").empty();
  621. yt_player = undefined;
  622. if (currentSong.type === "SoundCloud") {
  623. $("#media-container").append('<img src="/soundcloud-image.png" class="embed-responsive-item" />');
  624. getSongInfo(currentSong);
  625. SC.stream("/tracks/" + currentSong.id, function(sound){
  626. _sound = sound;
  627. sound.setVolume(volume / 100);
  628. sound.play();
  629. var interval = setInterval(function() {
  630. if (sound.getState() === "playing") {
  631. sound.seek(getTimeElapsed());
  632. window.clearInterval(interval);
  633. }
  634. }, 200);
  635. // Session.set("title", currentSong.title || "Title");
  636. // Session.set("artist", currentSong.artist || "Artist");
  637. Session.set("duration", currentSong.duration);
  638. resizeSeekerbar();
  639. });
  640. } else {
  641. $("#media-container").append('<div id="player" class="embed-responsive-item"></div>');
  642. if (yt_player === undefined) {
  643. yt_player = new YT.Player("player", {
  644. height: 540,
  645. width: 960,
  646. videoId: currentSong.id,
  647. playerVars: {controls: 0, iv_load_policy: 3, rel: 0, showinfo: 0},
  648. events: {
  649. 'onReady': function(event) {
  650. event.target.seekTo(getTimeElapsed() / 1000);
  651. event.target.playVideo();
  652. event.target.setVolume(volume);
  653. resizeSeekerbar();
  654. },
  655. 'onStateChange': function(event){
  656. if (event.data == YT.PlayerState.PAUSED) {
  657. event.target.seekTo(getTimeElapsed() / 1000);
  658. event.target.playVideo();
  659. }
  660. }
  661. }
  662. });
  663. } else {
  664. yt_player.loadVideoById(currentSong.id);
  665. }
  666. // Session.set("title", currentSong.title || "Title");
  667. // Session.set("artist", currentSong.artist || "Artist");
  668. getSongInfo(currentSong);
  669. //Session.set("duration", currentSong.duration);
  670. }
  671. }
  672. }
  673. Meteor.subscribe("history");
  674. Meteor.subscribe("playlists");
  675. Session.set("loaded", false);
  676. Meteor.subscribe("rooms", function() {
  677. var parts = location.href.split('/');
  678. var id = parts.pop();
  679. var type = id.toLowerCase();
  680. if (Rooms.find({type: type}).count() !== 1) {
  681. window.location = "/";
  682. } else {
  683. Session.set("loaded", true);
  684. minterval = Meteor.setInterval(function () {
  685. var data = undefined;
  686. var dataCursorH = History.find({type: type});
  687. var dataCursorP = Playlists.find({type: type});
  688. dataCursorH.forEach(function (doc) {
  689. if (data === undefined) {
  690. data = doc;
  691. }
  692. });
  693. if (data !== undefined && data.history.length > size) {
  694. //currentSong = data.history[data.history.length - 1];
  695. var songArray = Playlists.find({type: type}).fetch()[0].songs;
  696. var historyObj = data.history[data.history.length - 1];
  697. songArray.forEach(function(song) {
  698. if (song.id === historyObj.song.id) {
  699. currentSong = song;
  700. }
  701. });
  702. currentSong.started = historyObj.started;
  703. var songs = dataCursorP.fetch()[0].songs;
  704. songs.forEach(function(song, index) {
  705. if (currentSong.title === song.title) {
  706. if (index + 1 < songs.length) {
  707. nextSong = songs[index + 1];
  708. } else {
  709. nextSong = songs[0];
  710. }
  711. Session.set("title_next", nextSong.title);
  712. Session.set("artist_next", nextSong.artist);
  713. $("#song-img-next").attr("src", nextSong.img);
  714. if (index + 2 < songs.length) {
  715. afterSong = songs[index + 2];
  716. } else if (songs.length === index + 1 && songs.length > 1 ) {
  717. afterSong = songs[1];
  718. } else {
  719. afterSong = songs[0];
  720. }
  721. Session.set("title_after", afterSong.title);
  722. Session.set("artist_after", afterSong.artist);
  723. $("#song-img-after").attr("src",afterSong.img);
  724. }
  725. });
  726. size = data.history.length;
  727. startSong();
  728. }
  729. }, 1000);
  730. resizeSeekerbarInterval = Meteor.setInterval(function () {
  731. resizeSeekerbar();
  732. }, 500);
  733. }
  734. });
  735. });
  736. }
  737. if (Meteor.isServer) {
  738. Meteor.startup(function() {
  739. reCAPTCHA.config({
  740. privatekey: '6LcVxg0TAAAAAI2fgIEEWHFxwNXeVIs8mzq5cfRM'
  741. });
  742. var stations = ["edm", "pop"]; //Rooms to be set on server startup
  743. for(var i in stations){
  744. if(Rooms.find({type: stations[i]}).count() === 0){
  745. createRoom(stations[i]);
  746. }
  747. }
  748. });
  749. function createRoom(type) {
  750. if (Rooms.find({type: type}).count() === 0) {
  751. Rooms.insert({type: type}, function(err) {
  752. if (err) {
  753. throw err;
  754. } else {
  755. if (Playlists.find({type: type}).count() === 1) {
  756. if (History.find({type: type}).count() === 0) {
  757. History.insert({type: type, history: []}, function(err3) {
  758. if (err3) {
  759. throw err3;
  760. } else {
  761. startStation();
  762. return true;
  763. }
  764. });
  765. } else {
  766. startStation();
  767. return true;
  768. }
  769. } else {
  770. Playlists.insert({type: type, songs: getSongsByType(type)}, function (err2) {
  771. if (err2) {
  772. throw err2;
  773. } else {
  774. if (History.find({type: type}).count() === 0) {
  775. History.insert({type: type, history: []}, function(err3) {
  776. if (err3) {
  777. throw err3;
  778. } else {
  779. startStation();
  780. return true;
  781. }
  782. });
  783. } else {
  784. startStation();
  785. return true;
  786. }
  787. }
  788. });
  789. }
  790. }
  791. });
  792. } else {
  793. throw "Room already exists";
  794. }
  795. function startStation() {
  796. var startedAt = Date.now();
  797. var songs = Playlists.find({type: type}).fetch()[0].songs;
  798. var currentSong = 0;
  799. addToHistory(songs[currentSong], startedAt);
  800. function addToHistory(song, startedAt) {
  801. History.update({type: type}, {$push: {history: {song: song, started: startedAt}}});
  802. }
  803. function skipSong() {
  804. songs = Playlists.find({type: type}).fetch()[0].songs;
  805. if (currentSong < (songs.length - 1)) {
  806. currentSong++;
  807. } else currentSong = 0;
  808. songTimer();
  809. addToHistory(songs[currentSong], startedAt);
  810. }
  811. function songTimer() {
  812. startedAt = Date.now();
  813. Meteor.setTimeout(function() {
  814. skipSong();
  815. }, songs[currentSong].duration * 1000);
  816. }
  817. songTimer();
  818. }
  819. }
  820. Meteor.users.deny({update: function () { return true; }});
  821. Meteor.users.deny({insert: function () { return true; }});
  822. Meteor.users.deny({remove: function () { return true; }});
  823. function getSongDuration(query, artistName){
  824. var duration;
  825. var search = query;
  826. query = query.toLowerCase().split(" ").join("%20");
  827. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + query + '&type=track');
  828. for(var i in res.data){
  829. for(var j in res.data[i].items){
  830. if(search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1){
  831. duration = res.data[i].items[j].duration_ms / 1000;
  832. return duration;
  833. }
  834. }
  835. }
  836. }
  837. function getSongAlbumArt(query, artistName){
  838. var albumart;
  839. var search = query;
  840. query = query.toLowerCase().split(" ").join("%20");
  841. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + query + '&type=track');
  842. for(var i in res.data){
  843. for(var j in res.data[i].items){
  844. if(search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1){
  845. albumart = res.data[i].items[j].album.images[1].url
  846. return albumart;
  847. }
  848. }
  849. }
  850. }
  851. //var room_types = ["edm", "nightcore"];
  852. var songsArr = [];
  853. function getSongsByType(type) {
  854. if (type === "edm") {
  855. return [
  856. {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"},
  857. {id: "aHjpOzsQ9YI", title: "Crystallize", artist: "Lindsey Stirling", duration: getSongDuration("Crystallize", "Lindsey Stirling"), type: "youtube", img: "https://i.scdn.co/image/b0c1ccdd0cd7bcda741ccc1c3e036f4ed2e52312"}
  858. ];
  859. } else if (type === "nightcore") {
  860. 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"}];
  861. } else {
  862. 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"}];
  863. }
  864. }
  865. Rooms.find({}).fetch().forEach(function(room) {
  866. var type = room.type;
  867. if (Playlists.find({type: type}).count() === 0) {
  868. if (type === "edm") {
  869. Playlists.insert({type: type, songs: getSongsByType(type)});
  870. } else if (type === "nightcore") {
  871. Playlists.insert({type: type, songs: getSongsByType(type)});
  872. } else {
  873. Playlists.insert({type: type, songs: getSongsByType(type)});
  874. }
  875. }
  876. if (History.find({type: type}).count() === 0) {
  877. History.insert({type: type, history: []});
  878. }
  879. if (Playlists.find({type: type}).fetch()[0].songs.length === 0) {
  880. // Add a global video to Playlist so it can proceed
  881. } else {
  882. var startedAt = Date.now();
  883. var playlist = Playlists.find({type: type}).fetch()[0];
  884. var songs = playlist.songs;
  885. if (playlist.lastSong === undefined) {
  886. Playlists.update({type: type}, {$set: {lastSong: 0}});
  887. playlist = Playlists.find({type: type}).fetch()[0];
  888. songs = playlist.songs;
  889. }
  890. var currentSong = playlist.lastSong;
  891. addToHistory(songs[currentSong], startedAt);
  892. function addToHistory(song, startedAt) {
  893. History.update({type: type}, {$push: {history: {song: song, started: startedAt}}});
  894. }
  895. function skipSong() {
  896. songs = Playlists.find({type: type}).fetch()[0].songs;
  897. if (currentSong < (songs.length - 1)) {
  898. currentSong++;
  899. } else currentSong = 0;
  900. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  901. songTimer();
  902. addToHistory(songs[currentSong], startedAt);
  903. }
  904. function songTimer() {
  905. startedAt = Date.now();
  906. Meteor.setTimeout(function() {
  907. skipSong();
  908. }, songs[currentSong].duration * 1000);
  909. }
  910. songTimer();
  911. }
  912. });
  913. Accounts.onCreateUser(function(options, user) {
  914. var username;
  915. if (user.services) {
  916. if (user.services.github) {
  917. username = user.services.github.username;
  918. } else if (user.services.facebook) {
  919. username = user.services.facebook.first_name;
  920. } else if (user.services.password) {
  921. username = user.username;
  922. }
  923. }
  924. user.profile = {username: username, usernameL: username.toLowerCase(), rank: "default"};
  925. return user;
  926. });
  927. ServiceConfiguration.configurations.remove({
  928. service: "facebook"
  929. });
  930. ServiceConfiguration.configurations.insert({
  931. service: "facebook",
  932. appId: "1496014310695890",
  933. secret: "9a039f254a08a1488c08bb0737dbd2a6"
  934. });
  935. ServiceConfiguration.configurations.remove({
  936. service: "github"
  937. });
  938. ServiceConfiguration.configurations.insert({
  939. service: "github",
  940. clientId: "dcecd720f47c0e4001f7",
  941. secret: "375939d001ef1a0ca67c11dbf8fb9aeaa551e01b"
  942. });
  943. Meteor.publish("history", function() {
  944. return History.find({})
  945. });
  946. Meteor.publish("playlists", function() {
  947. return Playlists.find({})
  948. });
  949. Meteor.publish("rooms", function() {
  950. return Rooms.find({});
  951. });
  952. Meteor.publish("queues", function() {
  953. return Queues.find({});
  954. });
  955. Meteor.publish("chat", function() {
  956. return Chat.find({});
  957. });
  958. Meteor.publish("userProfiles", function() {
  959. //console.log(Meteor.users.find({}, {profile: 1, createdAt: 1, services: 0, username: 0, emails: 0})).fetch();
  960. return Meteor.users.find({}, {fields: {profile: 1, createdAt: 1}});
  961. });
  962. Meteor.publish("isAdmin", function() {
  963. return Meteor.users.find({_id: this.userId, "profile.rank": "admin"});
  964. });
  965. Meteor.methods({
  966. createUserMethod: function(formData, captchaData) {
  967. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  968. if (!verifyCaptchaResponse.success) {
  969. console.log('reCAPTCHA check failed!', verifyCaptchaResponse);
  970. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  971. } else {
  972. console.log('reCAPTCHA verification passed!');
  973. Accounts.createUser({
  974. username: formData.username,
  975. email: formData.email,
  976. password: formData.password
  977. });
  978. }
  979. return true;
  980. },
  981. addSongToQueue: function(type, songData) {
  982. if (Meteor.userId()) {
  983. type = type.toLowerCase();
  984. if (Rooms.find({type: type}).count() === 1) {
  985. if (Queues.find({type: type}).count() === 0) {
  986. Queues.insert({type: type, songs: []});
  987. }
  988. if (songData !== undefined && Object.keys(songData).length === 5 && songData.type !== undefined && songData.title !== undefined && songData.title !== undefined && songData.artist !== undefined && songData.img !== undefined) {
  989. songData.duration = getSongDuration(songData.title, songData.artist);
  990. songData.img = getSongAlbumArt(songData.title, songData.artist);
  991. Queues.update({type: type}, {
  992. $push: {
  993. songs: {
  994. id: songData.id,
  995. title: songData.title,
  996. artist: songData.artist,
  997. duration: songData.duration,
  998. img: songData.img,
  999. type: songData.type
  1000. }
  1001. }
  1002. });
  1003. return true;
  1004. } else {
  1005. throw new Meteor.error(403, "Invalid data.");
  1006. }
  1007. } else {
  1008. throw new Meteor.error(403, "Invalid genre.");
  1009. }
  1010. } else {
  1011. throw new Meteor.error(403, "Invalid permissions.");
  1012. }
  1013. },
  1014. updateQueueSong: function(genre, oldSong, newSong) {
  1015. var userData = Meteor.users.find(Meteor.userId());
  1016. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  1017. newSong.id = oldSong.id;
  1018. Queues.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  1019. return true;
  1020. } else {
  1021. throw new Meteor.error(403, "Invalid permissions.");
  1022. }
  1023. },
  1024. removeSongFromQueue: function(type, songId) {
  1025. var userData = Meteor.users.find(Meteor.userId());
  1026. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  1027. type = type.toLowerCase();
  1028. Queues.update({type: type}, {$pull: {songs: {id: songId}}});
  1029. } else {
  1030. throw new Meteor.error(403, "Invalid permissions.");
  1031. }
  1032. },
  1033. addSongToPlaylist: function(type, songData) {
  1034. var userData = Meteor.users.find(Meteor.userId());
  1035. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  1036. type = type.toLowerCase();
  1037. if (Rooms.find({type: type}).count() === 1) {
  1038. if (Playlists.find({type: type}).count() === 0) {
  1039. Playlists.insert({type: type, songs: []});
  1040. }
  1041. 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) {
  1042. Playlists.update({type: type}, {
  1043. $push: {
  1044. songs: {
  1045. id: songData.id,
  1046. title: songData.title,
  1047. artist: songData.artist,
  1048. duration: songData.duration,
  1049. img: songData.img,
  1050. type: songData.type
  1051. }
  1052. }
  1053. });
  1054. Queues.update({type: type}, {$pull: {songs: {id: songData.id}}});
  1055. return true;
  1056. } else {
  1057. throw new Meteor.error(403, "Invalid data.");
  1058. }
  1059. } else {
  1060. throw new Meteor.error(403, "Invalid genre.");
  1061. }
  1062. } else {
  1063. throw new Meteor.error(403, "Invalid permissions.");
  1064. }
  1065. },
  1066. createRoom: function(type) {
  1067. var userData = Meteor.users.find(Meteor.userId());
  1068. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  1069. createRoom(type);
  1070. } else {
  1071. return false;
  1072. }
  1073. }
  1074. });
  1075. }
  1076. /*Router.waitOn(function() {
  1077. Meteor.subscribe("isAdmin", Meteor.userId());
  1078. });*/
  1079. /*Router.onBeforeAction(function() {
  1080. /*Meteor.autorun(function () {
  1081. if (admin.ready()) {
  1082. this.next();
  1083. }
  1084. });*/
  1085. /*this.next();
  1086. });*/
  1087. Router.route("/", {
  1088. template: "home"
  1089. });
  1090. Router.route("/terms", {
  1091. template: "terms"
  1092. });
  1093. Router.route("/privacy", {
  1094. template: "privacy"
  1095. });
  1096. Router.route("/about", {
  1097. template: "about"
  1098. });
  1099. Router.route("/admin", {
  1100. waitOn: function() {
  1101. return Meteor.subscribe("isAdmin", Meteor.userId());
  1102. },
  1103. action: function() {
  1104. var user = Meteor.users.find({}).fetch();
  1105. if (user[0] !== undefined && user[0].profile !== undefined && user[0].profile.rank === "admin") {
  1106. this.render("admin");
  1107. } else {
  1108. this.redirect("/");
  1109. }
  1110. }
  1111. });
  1112. Router.route("/vis", {
  1113. template: "visualizer"
  1114. });
  1115. Router.route("/:type", {
  1116. template: "room"
  1117. });
  1118. Router.route("/u/:user", {
  1119. template: "profile"
  1120. });