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