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. var currentArt;
  208. function getTimeElapsed() {
  209. if (currentSong !== undefined) {
  210. return Date.now() - currentSong.started;
  211. }
  212. return 0;
  213. }
  214. function getSongInfo(query, platform){
  215. var search = query;
  216. var titles = [];
  217. query = query.toLowerCase().split(" ").join("%20");
  218. $.ajax({
  219. type: "GET",
  220. url: 'https://api.spotify.com/v1/search?q=' + query + '&type=track',
  221. applicationType: "application/json",
  222. contentType: "json",
  223. success: function(data){
  224. console.log(data);
  225. for(var i in data){
  226. for(var j in data[i].items){
  227. if(search.indexOf(data[i].items[j].name) !== -1){
  228. console.log(data[i].items[j].name);
  229. var info = data[i].items[j];
  230. Session.set("title", data[i].items[j].name);
  231. console.log("Info: " + info);
  232. if(platform === "youtube"){
  233. Session.set("duration", data[i].items[j].duration_ms / 1000)
  234. console.log(Session.get("duration"));
  235. }
  236. temp = "";
  237. if(data[i].items[j].artists.length >= 2){
  238. for(var k in data[i].items[j].artists){
  239. temp = temp + data[i].items[j].artists[k].name + ", ";
  240. }
  241. } else{
  242. for(var k in data[i].items[j].artists){
  243. temp = temp + data[i].items[j].artists[k].name;
  244. }
  245. }
  246. if(temp[temp.length-2] === ","){
  247. artistStr = temp.substr(0,temp.length-2);
  248. } else{
  249. artistStr = temp;
  250. }
  251. Session.set("artist", artistStr);
  252. $(".current").remove();
  253. $(".room-title").before("<img class='current' src='" + data[i].items[j].album.images[1].url + "' />");
  254. return true;
  255. }
  256. }
  257. //---------------------------------------------------------------//
  258. }
  259. }
  260. })
  261. }
  262. function resizeSeekerbar() {
  263. $("#seeker-bar").width(((getTimeElapsed() / 1000) / Session.get("duration") * 100) + "%");
  264. }
  265. function startSong() {
  266. if (currentSong !== undefined) {
  267. if (_sound !== undefined) _sound.stop();
  268. if (yt_player !== undefined && yt_player.stopVideo !== undefined) yt_player.stopVideo();
  269. if (currentSong.song.type === "soundcloud") {
  270. $("#player").attr("src", "")
  271. getSongInfo(currentSong.song.title);
  272. SC.stream("/tracks/" + currentSong.song.id + "#t=20s", function(sound){
  273. console.log(sound);
  274. _sound = sound;
  275. sound._player._volume = 0.3;
  276. sound.play();
  277. console.log(getTimeElapsed());
  278. var interval = setInterval(function() {
  279. if (sound.getState() === "playing") {
  280. sound.seek(getTimeElapsed());
  281. window.clearInterval(interval);
  282. }
  283. }, 200);
  284. // Session.set("title", currentSong.song.title || "Title");
  285. // Session.set("artist", currentSong.song.artist || "Artist");
  286. Session.set("duration", currentSong.song.duration);
  287. resizeSeekerbar();
  288. });
  289. } else {
  290. if (yt_player === undefined) {
  291. yt_player = new YT.Player("player", {
  292. height: 540,
  293. width: 960,
  294. videoId: currentSong.song.id,
  295. events: {
  296. 'onReady': function(event) {
  297. event.target.seekTo(getTimeElapsed() / 1000);
  298. event.target.playVideo();
  299. resizeSeekerbar();
  300. },
  301. 'onStateChange': function(event){
  302. if (event.data == YT.PlayerState.PAUSED) {
  303. event.target.seekTo(getTimeElapsed() / 1000);
  304. event.target.playVideo();
  305. }
  306. }
  307. }
  308. });
  309. } else {
  310. yt_player.loadVideoById(currentSong.song.id);
  311. }
  312. // Session.set("title", currentSong.song.title || "Title");
  313. // Session.set("artist", currentSong.song.artist || "Artist");
  314. getSongInfo(currentSong.song.title, "youtube");
  315. //Session.set("duration", currentSong.song.duration);
  316. }
  317. }
  318. }
  319. Meteor.subscribe("history");
  320. Meteor.subscribe("playlists");
  321. Session.set("loaded", true);
  322. Meteor.subscribe("rooms", function() {
  323. Session.set("loaded", false);
  324. console.log(Rooms.find({type: type}).fetch().length);
  325. if (Rooms.find({type: type}).count() !== 1) {
  326. window.location = "/";
  327. } else {
  328. Session.set("loaded", true);
  329. Meteor.setInterval(function () {
  330. var data = undefined;
  331. var dataCursor = History.find({type: type});
  332. dataCursor.map(function (doc) {
  333. if (data === undefined) {
  334. data = doc;
  335. }
  336. });
  337. if (data !== undefined && data.history.length > size) {
  338. currentSong = data.history[data.history.length - 1];
  339. size = data.history.length;
  340. startSong();
  341. }
  342. }, 1000);
  343. Meteor.setInterval(function () {
  344. resizeSeekerbar();
  345. }, 50);
  346. }
  347. });
  348. });
  349. Template.admin.events({
  350. "submit form": function(e){
  351. e.preventDefault();
  352. var genre = e.target.genre.value;
  353. var type = e.target.type.value;
  354. var id = e.target.id.value;
  355. var title = e.target.title.value;
  356. var artist = e.target.artist.value;
  357. var songData = {type: type, id: id, title: title, artist: artist};
  358. Meteor.call("addPlaylistSong", genre, songData, function(err, res) {
  359. console.log(err, res);
  360. });
  361. }
  362. });
  363. }
  364. if (Meteor.isServer) {
  365. Meteor.startup(function() {
  366. reCAPTCHA.config({
  367. privatekey: '6LcVxg0TAAAAAI2fgIEEWHFxwNXeVIs8mzq5cfRM'
  368. });
  369. });
  370. Meteor.users.deny({update: function () { return true; }});
  371. Meteor.users.deny({insert: function () { return true; }});
  372. Meteor.users.deny({remove: function () { return true; }});
  373. function getSongDuration(query){
  374. var duration;
  375. var search = query;
  376. query = query.toLowerCase().split(" ").join("%20");
  377. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + query + '&type=track');
  378. for(var i in res.data){
  379. for(var j in res.data[i].items){
  380. if(search.indexOf(res.data[i].items[j].name) !== -1){
  381. duration = res.data[i].items[j].duration_ms / 1000;
  382. console.log(duration);
  383. return duration;
  384. }
  385. }
  386. }
  387. }
  388. function getSongAlbumArt(query){
  389. var albumart;
  390. var search = query;
  391. query = query.toLowerCase().split(" ").join("%20");
  392. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + query + '&type=track');
  393. for(var i in res.data){
  394. for(var j in res.data[i].items){
  395. if(search.indexOf(res.data[i].items[j].name) !== -1){
  396. albumart = res.data[i].items[j].album.images[1].url
  397. return albumart;
  398. }
  399. }
  400. }
  401. }
  402. //var room_types = ["edm", "nightcore"];
  403. var songsArr = [];
  404. function getSongsByType(type) {
  405. if (type === "edm") {
  406. return [
  407. {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"},
  408. {id: "aHjpOzsQ9YI", title: "Crystallize", artist: "Linsdey Stirling", duration: getSongDuration("Crystallize"), albumart: getSongAlbumArt("Crystallize"), type: "youtube"}
  409. ];
  410. } else if (type === "nightcore") {
  411. return [{id: "f7RKOP87tt4", title: "Monster (DotEXE Remix)", duration: getSongDuration("Monster (DotEXE Remix)"), albumart: getSongAlbumArt("Monster (DotEXE Remix)"), type: "youtube"}];
  412. } else {
  413. 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"}];
  414. }
  415. }
  416. Rooms.find({}).fetch().forEach(function(room) {
  417. var type = room.type;
  418. if (Playlists.find({type: type}).count() === 0) {
  419. if (type === "edm") {
  420. Playlists.insert({type: type, songs: getSongsByType(type)});
  421. } else if (type === "nightcore") {
  422. Playlists.insert({type: type, songs: getSongsByType(type)});
  423. } else {
  424. Playlists.insert({type: type, songs: getSongsByType(type)});
  425. }
  426. }
  427. if (History.find({type: type}).count() === 0) {
  428. History.insert({type: type, history: []});
  429. }
  430. if (Playlists.find({type: type}).fetch()[0].songs.length === 0) {
  431. // Add a global video to Playlist so it can proceed
  432. } else {
  433. var startedAt = Date.now();
  434. var songs = Playlists.find({type: type}).fetch()[0].songs;
  435. var currentSong = 0;
  436. addToHistory(songs[currentSong], startedAt);
  437. function addToHistory(song, startedAt) {
  438. History.update({type: type}, {$push: {history: {song: song, started: startedAt}}});
  439. }
  440. function skipSong() {
  441. songs = Playlists.find({type: type}).fetch()[0].songs;
  442. if (currentSong < (songs.length - 1)) {
  443. currentSong++;
  444. } else currentSong = 0;
  445. songTimer();
  446. addToHistory(songs[currentSong], startedAt);
  447. }
  448. function songTimer() {
  449. startedAt = Date.now();
  450. Meteor.setTimeout(function() {
  451. skipSong();
  452. }, songs[currentSong].duration * 1000);
  453. }
  454. songTimer();
  455. }
  456. });
  457. ServiceConfiguration.configurations.remove({
  458. service: "facebook"
  459. });
  460. ServiceConfiguration.configurations.insert({
  461. service: "facebook",
  462. appId: "1496014310695890",
  463. secret: "9a039f254a08a1488c08bb0737dbd2a6"
  464. });
  465. ServiceConfiguration.configurations.remove({
  466. service: "github"
  467. });
  468. ServiceConfiguration.configurations.insert({
  469. service: "github",
  470. clientId: "dcecd720f47c0e4001f7",
  471. secret: "375939d001ef1a0ca67c11dbf8fb9aeaa551e01b"
  472. });
  473. Meteor.publish("history", function() {
  474. return History.find({})
  475. });
  476. Meteor.publish("playlists", function() {
  477. return Playlists.find({})
  478. });
  479. Meteor.publish("rooms", function() {
  480. return Rooms.find()
  481. });
  482. Meteor.methods({
  483. createUserMethod: function(formData, captchaData) {
  484. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  485. if (!verifyCaptchaResponse.success) {
  486. console.log('reCAPTCHA check failed!', verifyCaptchaResponse);
  487. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  488. } else {
  489. console.log('reCAPTCHA verification passed!');
  490. Accounts.createUser({
  491. username: formData.username,
  492. email: formData.email,
  493. password: formData.password
  494. });
  495. }
  496. return true;
  497. },
  498. addPlaylistSong: function(type, songData) {
  499. type = type.toLowerCase();
  500. if (Rooms.find({type: type}).count() === 1) {
  501. if (songData !== undefined && Object.keys(songData).length === 4 && songData.type !== undefined && songData.title !== undefined && songData.title !== undefined && songData.artist !== undefined) {
  502. songData.duration = getSongDuration(songData.title);
  503. Playlists.update({type: type}, {$push: {songs: {id: songData.id, title: songData.title, artist: songData.artist, duration: songData.duration, type: songData.type}}});
  504. return true;
  505. } else {
  506. throw new Meteor.error(403, "Invalid data.");
  507. }
  508. } else {
  509. throw new Meteor.error(403, "Invalid genre.");
  510. }
  511. },
  512. createRoom: function(type) {
  513. if (Rooms.find({type: type}).count() === 0) {
  514. Rooms.insert({type: type}, function(err) {
  515. if (err) {
  516. throw err;
  517. } else {
  518. if (Playlists.find({type: type}).count() === 1) {
  519. if (History.find({type: type}).count() === 0) {
  520. History.insert({type: type, history: []}, function(err3) {
  521. if (err3) {
  522. throw err3;
  523. } else {
  524. startStation();
  525. return true;
  526. }
  527. });
  528. } else {
  529. startStation();
  530. return true;
  531. }
  532. } else {
  533. Playlists.insert({type: type, songs: getSongsByType(type)}, function (err2) {
  534. if (err2) {
  535. throw err2;
  536. } else {
  537. if (History.find({type: type}).count() === 0) {
  538. History.insert({type: type, history: []}, function(err3) {
  539. if (err3) {
  540. throw err3;
  541. } else {
  542. startStation();
  543. return true;
  544. }
  545. });
  546. } else {
  547. startStation();
  548. return true;
  549. }
  550. }
  551. });
  552. }
  553. }
  554. });
  555. } else {
  556. throw "Room already exists";
  557. }
  558. function startStation() {
  559. var startedAt = Date.now();
  560. var songs = Playlists.find({type: type}).fetch()[0].songs;
  561. var currentSong = 0;
  562. addToHistory(songs[currentSong], startedAt);
  563. function addToHistory(song, startedAt) {
  564. History.update({type: type}, {$push: {history: {song: song, started: startedAt}}});
  565. }
  566. function skipSong() {
  567. songs = Playlists.find({type: type}).fetch()[0].songs;
  568. if (currentSong < (songs.length - 1)) {
  569. currentSong++;
  570. } else currentSong = 0;
  571. songTimer();
  572. addToHistory(songs[currentSong], startedAt);
  573. }
  574. function songTimer() {
  575. startedAt = Date.now();
  576. Meteor.setTimeout(function() {
  577. skipSong();
  578. }, songs[currentSong].duration * 1000);
  579. }
  580. songTimer();
  581. }
  582. }
  583. });
  584. }
  585. Router.route("/", {
  586. template: "home"
  587. });
  588. Router.route("/admin", {
  589. template: "admin"
  590. });
  591. Router.route("/:type", {
  592. template: "room"
  593. });