app.js 41 KB

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