app.js 40 KB

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