app.js 42 KB

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