app.js 43 KB

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