app.js 46 KB

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