app.js 42 KB

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