app.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. History = new Mongo.Collection("history");
  2. Playlists = new Mongo.Collection("playlists");
  3. Rooms = new Mongo.Collection("rooms");
  4. if (Meteor.isClient) {
  5. Meteor.startup(function() {
  6. reCAPTCHA.config({
  7. publickey: '6LcVxg0TAAAAAE18vBiH00UAyaJggsmLm890SjZl'
  8. });
  9. });
  10. var hpSound = undefined;
  11. var songsArr = [];
  12. var ytArr = [];
  13. var _sound = undefined;
  14. var parts = location.href.split('/');
  15. var id = parts.pop();
  16. var type = id.toLowerCase();
  17. Template.register.events({
  18. "submit form": function(e){
  19. e.preventDefault();
  20. var username = e.target.registerUsername.value;
  21. var email = e.target.registerEmail.value;
  22. var password = e.target.registerPassword.value;
  23. var captchaData = grecaptcha.getResponse();
  24. Meteor.call("createUserMethod", {username: username, email: email, password: password}, captchaData, function(err, res) {
  25. grecaptcha.reset();
  26. if (err) {
  27. console.log(err);
  28. } else {
  29. Meteor.loginWithPassword(username, password);
  30. }
  31. });
  32. },
  33. "click #facebook-login": function(){
  34. Meteor.loginWithFacebook()
  35. },
  36. "click #github-login": function(){
  37. Meteor.loginWithGithub()
  38. },
  39. "click #login": function(){
  40. $("#register-view").hide();
  41. $("#login-view").show();
  42. }
  43. });
  44. Template.login.events({
  45. "submit form": function(e){
  46. e.preventDefault();
  47. var username = e.target.loginUsername.value;
  48. var password = e.target.loginPassword.value;
  49. Meteor.loginWithPassword(username, password);
  50. Accounts.onLoginFailure(function(){
  51. $("input").css("background-color","indianred").addClass("animated shake");
  52. $("input").on("click",function(){
  53. $("input").css({
  54. "background-color": "transparent",
  55. "width": "250px"
  56. });
  57. })
  58. });
  59. },
  60. "click #facebook-login": function(){
  61. Meteor.loginWithFacebook()
  62. },
  63. "click #github-login": function(){
  64. Meteor.loginWithGithub()
  65. },
  66. "click #register": function(){
  67. $("#login-view").hide();
  68. $("#register-view").show();
  69. }
  70. });
  71. Template.dashboard.events({
  72. "click .logout": function(e){
  73. e.preventDefault();
  74. Meteor.logout();
  75. if (hpSound !== undefined) {
  76. hpSound.stop();
  77. }
  78. },
  79. "click .button-tunein": function(){
  80. SC.stream("/tracks/172055891/", function(sound){
  81. sound._player._volume = 0.3;
  82. sound.play();
  83. });
  84. },
  85. "click #play": function(){
  86. $("#play").hide();
  87. SC.stream("/tracks/172055891/", function(sound){
  88. hpSound = sound;
  89. sound._player._volume = 0.3;
  90. sound.play();
  91. $("#stop").on("click", function(){
  92. $("#stop").hide();
  93. $("#play").show();
  94. sound._player.pause();
  95. })
  96. });
  97. $("#stop").show();
  98. },
  99. "click #croom_create": function() {
  100. Meteor.call("createRoom", $("#croom").val(), function (err, res) {
  101. if (err) {
  102. alert("Error " + err.error + ": " + err.reason);
  103. } else {
  104. window.location = "/" + $("#croom").val();
  105. }
  106. });
  107. }
  108. });
  109. Template.room.events({
  110. "click #search-song": function(){
  111. $("#song-results").empty()
  112. $.ajax({
  113. type: "GET",
  114. url: "https://www.googleapis.com/youtube/v3/search?part=snippet&q=" + $("#song-input").val() + "&key=AIzaSyAgBdacEWrHCHVPPM4k-AFM7uXg-Q__YXY",
  115. applicationType: "application/json",
  116. contentType: "json",
  117. success: function(data){
  118. console.log(data);
  119. for(var i in data.items){
  120. $("#song-results").append("<p>" + data.items[i].snippet.title + "</p>")
  121. ytArr.push({title: data.items[i].snippet.title, id: data.items[i].id.videoId});
  122. }
  123. console.log(ytArr);
  124. $("#song-results p").click(function(){
  125. var title = $(this).text();
  126. for(var i in ytArr){
  127. if(ytArr[i].title === title){
  128. console.log(ytArr[i].title)
  129. var songObj = {
  130. id: ytArr[i].id,
  131. title: ytArr[i].title,
  132. type: "youtube"
  133. }
  134. }
  135. }
  136. })
  137. }
  138. })
  139. SC.get('/tracks', { q: $("#song-input").val()}, function(tracks) {
  140. console.log(tracks);
  141. for(var i in tracks){
  142. $("#song-results").append("<p>" + tracks[i].title + "</p>")
  143. songsArr.push({title: tracks[i].title, id: tracks[i].id, duration: tracks[i].duration / 1000});
  144. }
  145. $("#song-results p").click(function(){
  146. var title = $(this).text();
  147. for(var i in songsArr){
  148. if(songsArr[i].title === title){
  149. var id = songsArr[i].id;
  150. var duration = songsArr[i].duration;
  151. var songObj = {
  152. title: songsArr[i].title,
  153. id: id,
  154. duration: duration,
  155. type: "soundcloud"
  156. }
  157. }
  158. }
  159. console.log(id);
  160. })
  161. });
  162. }
  163. });
  164. Template.room.helpers({
  165. type: function() {
  166. var parts = location.href.split('/');
  167. var id = parts.pop();
  168. return id.toUpperCase();
  169. },
  170. title: function(){
  171. return Session.get("title");
  172. },
  173. artist: function(){
  174. return Session.get("artist");
  175. },
  176. loaded: function() {
  177. return Session.get("loaded");
  178. }
  179. });
  180. Template.admin.helpers({
  181. rooms: function() {
  182. return Rooms.find({});
  183. }
  184. });
  185. Template.playlist.helpers({
  186. playlist_songs: function() {
  187. var data = Playlists.find({type: type}).fetch();
  188. if (data !== undefined && data.length > 0) {
  189. return data[0].songs;
  190. } else {
  191. return [];
  192. }
  193. }
  194. });
  195. Meteor.subscribe("rooms");
  196. Template.room.onCreated(function () {
  197. var tag = document.createElement("script");
  198. tag.src = "https://www.youtube.com/iframe_api";
  199. var firstScriptTag = document.getElementsByTagName('script')[0];
  200. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  201. var currentSong = undefined;
  202. var _sound = undefined;
  203. var yt_player = undefined;
  204. var size = 0;
  205. var artistStr;
  206. var temp = "";
  207. function getTimeElapsed() {
  208. if (currentSong !== undefined) {
  209. return Date.now() - currentSong.started;
  210. }
  211. return 0;
  212. }
  213. function getSongInfo(query, platform){
  214. var search = query;
  215. var titles = [];
  216. query = query.toLowerCase().split(" ").join("%20");
  217. $.ajax({
  218. type: "GET",
  219. url: 'https://api.spotify.com/v1/search?q=' + query + '&type=track',
  220. applicationType: "application/json",
  221. contentType: "json",
  222. success: function(data){
  223. console.log(data);
  224. for(var i in data){
  225. for(var j in data[i].items){
  226. if(search.indexOf(data[i].items[j].name) !== -1){
  227. console.log(data[i].items[j].name);
  228. var info = data[i].items[j];
  229. Session.set("title", data[i].items[j].name);
  230. console.log("Info: " + info);
  231. if(platform === "youtube"){
  232. Session.set("duration", data[i].items[j].duration_ms / 1000)
  233. console.log(Session.get("duration"));
  234. }
  235. temp = "";
  236. if(data[i].items[j].artists.length >= 2){
  237. for(var k in data[i].items[j].artists){
  238. temp = temp + data[i].items[j].artists[k].name + ", ";
  239. }
  240. } else{
  241. for(var k in data[i].items[j].artists){
  242. temp = temp + data[i].items[j].artists[k].name;
  243. }
  244. }
  245. if(temp[temp.length-2] === ","){
  246. artistStr = temp.substr(0,temp.length-2);
  247. } else{
  248. artistStr = temp;
  249. }
  250. Session.set("artist", artistStr);
  251. $(".current").remove();
  252. $(".room-title").before("<img class='current' src='" + data[i].items[j].album.images[1].url + "' />");
  253. return true;
  254. }
  255. }
  256. //---------------------------------------------------------------//
  257. }
  258. }
  259. })
  260. }
  261. function resizeSeekerbar() {
  262. $("#seeker-bar").width(((getTimeElapsed() / 1000) / Session.get("duration") * 100) + "%");
  263. }
  264. function startSong() {
  265. if (currentSong !== undefined) {
  266. if (_sound !== undefined) _sound.stop();
  267. if (yt_player !== undefined && yt_player.stopVideo !== undefined) yt_player.stopVideo();
  268. if (currentSong.song.type === "soundcloud") {
  269. $("#player").attr("src", "")
  270. getSongInfo(currentSong.song.title);
  271. SC.stream("/tracks/" + currentSong.song.id + "#t=20s", function(sound){
  272. console.log(sound);
  273. _sound = sound;
  274. sound._player._volume = 0.3;
  275. sound.play();
  276. console.log(getTimeElapsed());
  277. var interval = setInterval(function() {
  278. if (sound.getState() === "playing") {
  279. sound.seek(getTimeElapsed());
  280. window.clearInterval(interval);
  281. }
  282. }, 200);
  283. // Session.set("title", currentSong.song.title || "Title");
  284. // Session.set("artist", currentSong.song.artist || "Artist");
  285. Session.set("duration", currentSong.song.duration);
  286. resizeSeekerbar();
  287. });
  288. } else {
  289. if (yt_player === undefined) {
  290. yt_player = new YT.Player("player", {
  291. height: 540,
  292. width: 960,
  293. videoId: currentSong.song.id,
  294. events: {
  295. 'onReady': function(event) {
  296. event.target.seekTo(getTimeElapsed() / 1000);
  297. event.target.playVideo();
  298. resizeSeekerbar();
  299. },
  300. 'onStateChange': function(event){
  301. if (event.data == YT.PlayerState.PAUSED) {
  302. event.target.seekTo(getTimeElapsed() / 1000);
  303. event.target.playVideo();
  304. }
  305. }
  306. }
  307. });
  308. } else {
  309. yt_player.loadVideoById(currentSong.song.id);
  310. }
  311. // Session.set("title", currentSong.song.title || "Title");
  312. // Session.set("artist", currentSong.song.artist || "Artist");
  313. getSongInfo(currentSong.song.title, "youtube");
  314. //Session.set("duration", currentSong.song.duration);
  315. }
  316. }
  317. }
  318. Meteor.subscribe("history");
  319. Meteor.subscribe("playlists");
  320. Session.set("loaded", true);
  321. Meteor.subscribe("rooms", function() {
  322. Session.set("loaded", false);
  323. console.log(Rooms.find({type: type}).fetch().length);
  324. if (Rooms.find({type: type}).count() !== 1) {
  325. window.location = "/";
  326. } else {
  327. Session.set("loaded", true);
  328. Meteor.setInterval(function () {
  329. var data = undefined;
  330. var dataCursor = History.find({type: type});
  331. dataCursor.map(function (doc) {
  332. if (data === undefined) {
  333. data = doc;
  334. }
  335. });
  336. if (data !== undefined && data.history.length > size) {
  337. currentSong = data.history[data.history.length - 1];
  338. size = data.history.length;
  339. startSong();
  340. }
  341. }, 1000);
  342. Meteor.setInterval(function () {
  343. resizeSeekerbar();
  344. }, 50);
  345. }
  346. });
  347. });
  348. Template.admin.events({
  349. "submit form": function(e){
  350. e.preventDefault();
  351. var genre = e.target.genre.value;
  352. var type = e.target.type.value;
  353. var id = e.target.id.value;
  354. var title = e.target.title.value;
  355. var artist = e.target.artist.value;
  356. var songData = {type: type, id: id, title: title, artist: artist};
  357. Meteor.call("addPlaylistSong", genre, songData, function(err, res) {
  358. console.log(err, res);
  359. });
  360. }
  361. });
  362. }
  363. if (Meteor.isServer) {
  364. Meteor.startup(function() {
  365. reCAPTCHA.config({
  366. privatekey: '6LcVxg0TAAAAAI2fgIEEWHFxwNXeVIs8mzq5cfRM'
  367. });
  368. });
  369. Meteor.users.deny({update: function () { return true; }});
  370. Meteor.users.deny({insert: function () { return true; }});
  371. Meteor.users.deny({remove: function () { return true; }});
  372. function getSongDuration(query){
  373. var duration;
  374. var search = query;
  375. query = query.toLowerCase().split(" ").join("%20");
  376. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + query + '&type=track');
  377. for(var i in res.data){
  378. for(var j in res.data[i].items){
  379. if(search.indexOf(res.data[i].items[j].name) !== -1){
  380. duration = res.data[i].items[j].duration_ms / 1000;
  381. console.log(duration);
  382. return duration;
  383. }
  384. }
  385. }
  386. }
  387. function getSongAlbumArt(query){
  388. var albumart;
  389. var search = query;
  390. query = query.toLowerCase().split(" ").join("%20");
  391. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + query + '&type=track');
  392. for(var i in res.data){
  393. for(var j in res.data[i].items){
  394. if(search.indexOf(res.data[i].items[j].name) !== -1){
  395. albumart = res.data[i].items[j].album.images[1].url
  396. return albumart;
  397. }
  398. }
  399. }
  400. }
  401. //var room_types = ["edm", "nightcore"];
  402. var songsArr = [];
  403. function getSongsByType(type) {
  404. if (type === "edm") {
  405. return [
  406. {id: "aE2GCa-_nyU", title: "Radioactive - Lindsey Stirling and Pentatonix", duration: getSongDuration("Radioactive - Lindsey Stirling and Pentatonix"), albumart: getSongAlbumArt("Radioactive - Lindsey Stirling and Pentatonix"), type: "youtube"},
  407. {id: "aHjpOzsQ9YI", title: "Crystallize", artist: "Linsdey Stirling", duration: getSongDuration("Crystallize"), albumart: getSongAlbumArt("Crystallize"), type: "youtube"}
  408. ];
  409. } else if (type === "nightcore") {
  410. return [{id: "f7RKOP87tt4", title: "Monster (DotEXE Remix)", duration: getSongDuration("Monster (DotEXE Remix)"), albumart: getSongAlbumArt("Monster (DotEXE Remix)"), type: "youtube"}];
  411. } else {
  412. return [{id: "dQw4w9WgXcQ", title: "Never Gonna Give You Up", duration: getSongDuration("Never Gonna Give You Up"), albumart: getSongAlbumArt("Never Gonna Give You Up"), type: "youtube"}];
  413. }
  414. }
  415. Rooms.find({}).fetch().forEach(function(room) {
  416. var type = room.type;
  417. if (Playlists.find({type: type}).count() === 0) {
  418. if (type === "edm") {
  419. Playlists.insert({type: type, songs: getSongsByType(type)});
  420. } else if (type === "nightcore") {
  421. Playlists.insert({type: type, songs: getSongsByType(type)});
  422. } else {
  423. Playlists.insert({type: type, songs: getSongsByType(type)});
  424. }
  425. }
  426. if (History.find({type: type}).count() === 0) {
  427. History.insert({type: type, history: []});
  428. }
  429. if (Playlists.find({type: type}).fetch()[0].songs.length === 0) {
  430. // Add a global video to Playlist so it can proceed
  431. } else {
  432. var startedAt = Date.now();
  433. var songs = Playlists.find({type: type}).fetch()[0].songs;
  434. var currentSong = 0;
  435. addToHistory(songs[currentSong], startedAt);
  436. function addToHistory(song, startedAt) {
  437. History.update({type: type}, {$push: {history: {song: song, started: startedAt}}});
  438. }
  439. function skipSong() {
  440. songs = Playlists.find({type: type}).fetch()[0].songs;
  441. if (currentSong < (songs.length - 1)) {
  442. currentSong++;
  443. } else currentSong = 0;
  444. songTimer();
  445. addToHistory(songs[currentSong], startedAt);
  446. }
  447. function songTimer() {
  448. startedAt = Date.now();
  449. Meteor.setTimeout(function() {
  450. skipSong();
  451. }, songs[currentSong].duration * 1000);
  452. }
  453. songTimer();
  454. }
  455. });
  456. ServiceConfiguration.configurations.remove({
  457. service: "facebook"
  458. });
  459. ServiceConfiguration.configurations.insert({
  460. service: "facebook",
  461. appId: "1496014310695890",
  462. secret: "9a039f254a08a1488c08bb0737dbd2a6"
  463. });
  464. ServiceConfiguration.configurations.remove({
  465. service: "github"
  466. });
  467. ServiceConfiguration.configurations.insert({
  468. service: "github",
  469. clientId: "dcecd720f47c0e4001f7",
  470. secret: "375939d001ef1a0ca67c11dbf8fb9aeaa551e01b"
  471. });
  472. Meteor.publish("history", function() {
  473. return History.find({})
  474. });
  475. Meteor.publish("playlists", function() {
  476. return Playlists.find({})
  477. });
  478. Meteor.publish("rooms", function() {
  479. return Rooms.find()
  480. });
  481. Meteor.methods({
  482. createUserMethod: function(formData, captchaData) {
  483. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  484. if (!verifyCaptchaResponse.success) {
  485. console.log('reCAPTCHA check failed!', verifyCaptchaResponse);
  486. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  487. } else {
  488. console.log('reCAPTCHA verification passed!');
  489. Accounts.createUser({
  490. username: formData.username,
  491. email: formData.email,
  492. password: formData.password
  493. });
  494. }
  495. return true;
  496. },
  497. addPlaylistSong: function(type, songData) {
  498. type = type.toLowerCase();
  499. if (Rooms.find({type: type}).count() === 1) {
  500. if (songData !== undefined && Object.keys(songData).length === 4 && songData.type !== undefined && songData.title !== undefined && songData.title !== undefined && songData.artist !== undefined) {
  501. songData.duration = getSongDuration(songData.title);
  502. Playlists.update({type: type}, {$push: {songs: {id: songData.id, title: songData.title, artist: songData.artist, duration: songData.duration, type: songData.type}}});
  503. return true;
  504. } else {
  505. throw new Meteor.error(403, "Invalid data.");
  506. }
  507. } else {
  508. throw new Meteor.error(403, "Invalid genre.");
  509. }
  510. },
  511. createRoom: function(type) {
  512. if (Rooms.find({type: type}).count() === 0) {
  513. Rooms.insert({type: type}, function(err) {
  514. if (err) {
  515. throw err;
  516. } else {
  517. if (Playlists.find({type: type}).count() === 1) {
  518. if (History.find({type: type}).count() === 0) {
  519. History.insert({type: type, history: []}, function(err3) {
  520. if (err3) {
  521. throw err3;
  522. } else {
  523. startStation();
  524. return true;
  525. }
  526. });
  527. } else {
  528. startStation();
  529. return true;
  530. }
  531. } else {
  532. Playlists.insert({type: type, songs: getSongsByType(type)}, function (err2) {
  533. if (err2) {
  534. throw err2;
  535. } else {
  536. if (History.find({type: type}).count() === 0) {
  537. History.insert({type: type, history: []}, function(err3) {
  538. if (err3) {
  539. throw err3;
  540. } else {
  541. startStation();
  542. return true;
  543. }
  544. });
  545. } else {
  546. startStation();
  547. return true;
  548. }
  549. }
  550. });
  551. }
  552. }
  553. });
  554. } else {
  555. throw "Room already exists";
  556. }
  557. function startStation() {
  558. var startedAt = Date.now();
  559. var songs = Playlists.find({type: type}).fetch()[0].songs;
  560. var currentSong = 0;
  561. addToHistory(songs[currentSong], startedAt);
  562. function addToHistory(song, startedAt) {
  563. History.update({type: type}, {$push: {history: {song: song, started: startedAt}}});
  564. }
  565. function skipSong() {
  566. songs = Playlists.find({type: type}).fetch()[0].songs;
  567. if (currentSong < (songs.length - 1)) {
  568. currentSong++;
  569. } else currentSong = 0;
  570. songTimer();
  571. addToHistory(songs[currentSong], startedAt);
  572. }
  573. function songTimer() {
  574. startedAt = Date.now();
  575. Meteor.setTimeout(function() {
  576. skipSong();
  577. }, songs[currentSong].duration * 1000);
  578. }
  579. songTimer();
  580. }
  581. }
  582. });
  583. }
  584. Router.route("/", {
  585. template: "home"
  586. });
  587. Router.route("/admin", {
  588. template: "admin"
  589. });
  590. Router.route("/:type", {
  591. template: "room"
  592. });