app.js 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  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. Meteor.subscribe("playlists");
  14. var minterval;
  15. var hpSound = undefined;
  16. var songsArr = [];
  17. var ytArr = [];
  18. var _sound = undefined;
  19. var parts = location.href.split('/');
  20. var id = parts.pop();
  21. var type = id.toLowerCase();
  22. var resizeSeekerbarInterval;
  23. function getSpotifyInfo(title, cb, artist) {
  24. var q = "";
  25. q = title;
  26. if (artist !== undefined) {
  27. q += " artist:" + artist;
  28. }
  29. $.ajax({
  30. type: "GET",
  31. url: 'https://api.spotify.com/v1/search?q=' + encodeURIComponent(q) + '&type=track',
  32. applicationType: "application/json",
  33. contentType: "json",
  34. success: function (data) {
  35. cb(data);
  36. }
  37. });
  38. }
  39. function getSpotifyArtist(data) {
  40. var temp = "";
  41. var artist;
  42. if(data.artists.length >= 2){
  43. for(var k in data.artists){
  44. temp = temp + data.artists[k].name + ", ";
  45. }
  46. } else{
  47. for(var k in data.artists){
  48. temp = temp + data.artists[k].name;
  49. }
  50. }
  51. if(temp[temp.length-2] === ","){
  52. artist = temp.substr(0,temp.length-2);
  53. } else{
  54. artist = temp;
  55. }
  56. return artist;
  57. }
  58. Template.profile.helpers({
  59. "username": function() {
  60. return Session.get("username");
  61. },
  62. "first_joined": function() {
  63. return moment(Session.get("first_joined")).format("DD/MM/YYYY HH:mm:ss");
  64. },
  65. "rank": function() {
  66. return Session.get("rank");
  67. },
  68. loaded: function() {
  69. return Session.get("loaded");
  70. }
  71. });
  72. Template.profile.onCreated(function() {
  73. var parts = location.href.split('/');
  74. var username = parts.pop();
  75. Session.set("loaded", false);
  76. Meteor.subscribe("userProfiles", function() {
  77. if (Meteor.users.find({"profile.usernameL": username.toLowerCase()}).count() === 0) {
  78. window.location = "/";
  79. } else {
  80. var data = Meteor.users.find({"profile.usernameL": username.toLowerCase()}).fetch()[0];
  81. Session.set("username", data.profile.username);
  82. Session.set("first_joined", data.createdAt);
  83. Session.set("rank", data.profile.rank);
  84. Session.set("loaded", true);
  85. }
  86. });
  87. });
  88. 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}}};
  89. Handlebars.registerHelper('active', function(path) {
  90. return curPath() == path ? 'active' : '';
  91. });
  92. Template.header.helpers({
  93. currentUser: function() {
  94. return Meteor.user();
  95. },
  96. isAdmin: function() {
  97. if (Meteor.user() && Meteor.user().profile) {
  98. return Meteor.user().profile.rank === "admin";
  99. } else {
  100. return false;
  101. }
  102. }
  103. });
  104. Template.header.events({
  105. "click .logout": function(e){
  106. e.preventDefault();
  107. Meteor.logout();
  108. if (hpSound !== undefined) {
  109. hpSound.stop();
  110. }
  111. }
  112. });
  113. Template.register.events({
  114. "submit form": function(e){
  115. e.preventDefault();
  116. var username = e.target.registerUsername.value;
  117. var email = e.target.registerEmail.value;
  118. var password = e.target.registerPassword.value;
  119. var captchaData = grecaptcha.getResponse();
  120. Meteor.call("createUserMethod", {username: username, email: email, password: password}, captchaData, function(err, res) {
  121. grecaptcha.reset();
  122. console.log(username, password, err, res);
  123. if (err) {
  124. console.log(err);
  125. var errAlert = $('<div class="alert alert-danger" role="alert"><strong>Oh Snap!</strong> ' + err.reason + '</div>');
  126. $("#login").after(errAlert);
  127. errAlert.fadeOut(20000, function() {
  128. errAlert.remove();
  129. });
  130. } else {
  131. console.log();
  132. Meteor.loginWithPassword(username, password);
  133. Accounts.onLogin(function(){
  134. window.location.href = "/";
  135. })
  136. }
  137. });
  138. },
  139. "click #github-login": function(){
  140. Meteor.loginWithGithub()
  141. Accounts.onLogin(function(){
  142. window.location.href = "/"
  143. });
  144. }
  145. });
  146. Template.login.events({
  147. "submit form": function(e){
  148. e.preventDefault();
  149. var username = e.target.loginUsername.value;
  150. var password = e.target.loginPassword.value;
  151. Meteor.loginWithPassword(username, password);
  152. Accounts.onLogin(function(){
  153. window.location.href = "/";
  154. })
  155. Accounts.onLoginFailure(function(){
  156. $("input").css("background-color","indianred");
  157. $("input").on("click",function(){
  158. $("input").css({
  159. "-webkit-appearance": "none",
  160. " -moz-appearance": "none",
  161. " appearance": "none",
  162. "outline": "0",
  163. "border": "1px solid rgba(255, 255, 255, 0.4)",
  164. "background-color": "rgba(255, 255, 255, 0.2)",
  165. "width": "304px",
  166. "border-radius": "3px",
  167. "padding": "10px 15px",
  168. "margin": "0 auto 10px auto",
  169. "display": "block",
  170. "text-align": "center",
  171. "font-size": "18px",
  172. "color": "white",
  173. "-webkit-transition-duration": "0.25s",
  174. " transition-duration": "0.25s",
  175. "font-weight": "300"
  176. });
  177. $("input:focus").css({
  178. "width": "354px",
  179. "color": "white"
  180. })
  181. $("input").on("blur", function(){
  182. $(this).css("width", "304px");
  183. })
  184. })
  185. });
  186. },
  187. "click #github-login": function(){
  188. Meteor.loginWithGithub()
  189. Accounts.onLogin(function(){
  190. window.location.href = "/"
  191. });
  192. }
  193. });
  194. Template.dashboard.helpers({
  195. rooms: function() {
  196. return Rooms.find({});
  197. },
  198. currentSong: function() {
  199. var history = History.find({type: this.type}).fetch();
  200. if (history.length < 1) {
  201. return {};
  202. } else {
  203. history = history[0];
  204. return history.history[history.history.length - 1];
  205. }
  206. }
  207. });
  208. Template.dashboard.onCreated(function() {
  209. if (_sound !== undefined) _sound.stop();
  210. if (minterval !== undefined) {
  211. Meteor.clearInterval(minterval);
  212. }
  213. if (resizeSeekerbarInterval !== undefined) {
  214. Meteor.clearInterval(resizeSeekerbarInterval);
  215. resizeSeekerbarInterval = undefined;
  216. }
  217. Meteor.subscribe("history");
  218. });
  219. Template.room.events({
  220. "click #add-song-button": function(e){
  221. e.preventDefault();
  222. parts = location.href.split('/');
  223. id = parts.pop();
  224. var genre = id.toLowerCase();
  225. var type = $("#type").val();
  226. id = $("#id").val();
  227. var title = $("#title").val();
  228. var artist = $("#artist").val();
  229. var img = $("#img").val();
  230. var songData = {type: type, id: id, title: title, artist: artist, img: img};
  231. Meteor.call("addSongToQueue", genre, songData, function(err, res) {
  232. console.log(err, res);
  233. });
  234. $("#close-modal").click();
  235. },
  236. "click #toggle-video": function(e){
  237. e.preventDefault();
  238. if (Session.get("mediaHidden")) {
  239. $("#media-container").removeClass("hidden");
  240. $("#toggle-video").text("Hide video");
  241. Session.set("mediaHidden", false);
  242. } else {
  243. $("#media-container").addClass("hidden");
  244. $("#toggle-video").text("Show video");
  245. Session.set("mediaHidden", true);
  246. }
  247. },
  248. "click #return": function(e){
  249. $("#add-info").hide();
  250. $("#search-info").show();
  251. },
  252. "click #search-song": function(){
  253. $("#song-results").empty();
  254. var search_type = $("#search_type").val();
  255. if (search_type === "YouTube") {
  256. $.ajax({
  257. type: "GET",
  258. url: "https://www.googleapis.com/youtube/v3/search?part=snippet&q=" + $("#song-input").val() + "&key=AIzaSyAgBdacEWrHCHVPPM4k-AFM7uXg-Q__YXY",
  259. applicationType: "application/json",
  260. contentType: "json",
  261. success: function(data){
  262. for(var i in data.items){
  263. $("#song-results").append("<p>" + data.items[i].snippet.title + "</p>");
  264. ytArr.push({title: data.items[i].snippet.title, id: data.items[i].id.videoId});
  265. }
  266. $("#song-results p").click(function(){
  267. $("#search-info").hide();
  268. $("#add-info").show();
  269. var title = $(this).text();
  270. for(var i in ytArr){
  271. if(ytArr[i].title === title){
  272. var songObj = {
  273. id: ytArr[i].id,
  274. title: ytArr[i].title,
  275. type: "youtube"
  276. };
  277. $("#title").val(songObj.title);
  278. $("#artist").val("");
  279. $("#id").val(songObj.id);
  280. $("#type").val("YouTube");
  281. getSpotifyInfo(songObj.title.replace(/\[.*\]/g, ""), function(data) {
  282. if (data.tracks.items.length > 0) {
  283. $("#title").val(data.tracks.items[0].name);
  284. var artists = [];
  285. $("#img").val(data.tracks.items[0].album.images[1].url);
  286. data.tracks.items[0].artists.forEach(function(artist) {
  287. artists.push(artist.name);
  288. });
  289. $("#artist").val(artists.join(", "));
  290. }
  291. });
  292. }
  293. }
  294. })
  295. }
  296. })
  297. } else if (search_type === "SoundCloud") {
  298. SC.get('/tracks', { q: $("#song-input").val()}, function(tracks) {
  299. for(var i in tracks){
  300. $("#song-results").append("<p>" + tracks[i].title + "</p>")
  301. songsArr.push({title: tracks[i].title, id: tracks[i].id, duration: tracks[i].duration / 1000});
  302. }
  303. $("#song-results p").click(function(){
  304. $("#search-info").hide();
  305. $("#add-info").show();
  306. var title = $(this).text();
  307. for(var i in songsArr){
  308. if(songsArr[i].title === title){
  309. var id = songsArr[i].id;
  310. var duration = songsArr[i].duration;
  311. var songObj = {
  312. title: songsArr[i].title,
  313. id: id,
  314. duration: duration,
  315. type: "soundcloud"
  316. }
  317. $("#title").val(songObj.title);
  318. // Set ID field
  319. $("#id").val(songObj.id);
  320. $("#type").val("SoundCloud");
  321. getSpotifyInfo(songObj.title.replace(/\[.*\]/g, ""), function(data) {
  322. if (data.tracks.items.length > 0) {
  323. $("#title").val(data.tracks.items[0].name);
  324. var artists = [];
  325. data.tracks.items[0].artists.forEach(function(artist) {
  326. artists.push(artist.name);
  327. });
  328. $("#artist").val(artists.join(", "));
  329. }
  330. // Set title field again if possible
  331. // Set artist if possible
  332. });
  333. }
  334. }
  335. })
  336. });
  337. }
  338. },
  339. "click #add-songs": function(){
  340. $("#add-songs-modal").show();
  341. },
  342. "click #close-modal": function(){
  343. $("#search-info").show();
  344. $("#add-info").hide();
  345. },
  346. "click #submit-message": function(){
  347. var message = $("#chat-input").val();
  348. $("#chat-ul").scrollTop(1000000);
  349. $("#chat-input").val("");
  350. Meteor.call("sendMessage", type, message);
  351. },
  352. "click #volume-icon": function(){
  353. var volume = 0;
  354. var slider = $("#volume-slider").slider();
  355. $("#volume-icon").removeClass("fa-volume-down").addClass("fa-volume-off")
  356. if (yt_player !== undefined) {
  357. yt_player.setVolume(volume);
  358. localStorage.setItem("volume", volume);
  359. $("#volume-slider").slider("setValue", volume);
  360. } else if (_sound !== undefined) {
  361. _sound.setVolume(volume);
  362. localStorage.setItem("volume", volume);
  363. $("#volume-slider").slider("setValue", volume);
  364. }
  365. }
  366. });
  367. Template.room.onRendered(function() {
  368. $(document).ready(function() {
  369. function makeSlider(){
  370. var slider = $("#volume-slider").slider();
  371. var volume = localStorage.getItem("volume") || 20;
  372. $("#volume-slider").slider("setValue", volume);
  373. if (slider.length === 0) {
  374. Meteor.setTimeout(function() {
  375. makeSlider();
  376. }, 500);
  377. } else {
  378. slider.on("slide", function(val) {
  379. if (val.value === 0) {
  380. $("#volume-icon").removeClass("fa-volume-down").addClass("fa-volume-off")
  381. } else {
  382. $("#volume-icon").removeClass("fa-volume-off").addClass("fa-volume-down")
  383. }
  384. if (yt_player !== undefined) {
  385. yt_player.setVolume(val.value);
  386. localStorage.setItem("volume", val.value);
  387. } else if (_sound !== undefined) {
  388. //_sound
  389. var volume = val.value / 100;
  390. _sound.setVolume(volume);
  391. localStorage.setItem("volume", val.value);
  392. }
  393. });
  394. }
  395. }
  396. makeSlider();
  397. });
  398. });
  399. Template.room.helpers({
  400. type: function() {
  401. var parts = location.href.split('/');
  402. var id = parts.pop();
  403. return id.toUpperCase();
  404. },
  405. title: function(){
  406. return Session.get("title");
  407. },
  408. artist: function(){
  409. return Session.get("artist");
  410. },
  411. title_next: function(){
  412. return Session.get("title_next");
  413. },
  414. artist_next: function(){
  415. return Session.get("artist_next");
  416. },
  417. title_after: function(){
  418. return Session.get("title_after");
  419. },
  420. artist_after: function(){
  421. return Session.get("artist_after");
  422. },
  423. loaded: function() {
  424. return Session.get("loaded");
  425. }
  426. });
  427. Template.admin.helpers({
  428. queues: function() {
  429. return Queues.find({});
  430. },
  431. playlists: function() {
  432. return Playlists.find({});
  433. }
  434. });
  435. var yt_player = undefined;
  436. var _sound = undefined;
  437. Template.admin.events({
  438. "click .preview-button": function(e){
  439. Session.set("song", this);
  440. },
  441. "click .edit-queue-button": function(e){
  442. Session.set("song", this);
  443. Session.set("genre", $(e.toElement).data("genre"));
  444. Session.set("type", "queue");
  445. $("#type").val(this.type);
  446. $("#artist").val(this.artist);
  447. $("#title").val(this.title);
  448. $("#img").val(this.img);
  449. $("#id").val(this.id);
  450. $("#duration").val(this.duration);
  451. },
  452. "click .edit-playlist-button": function(e){
  453. Session.set("song", this);
  454. Session.set("genre", $(e.toElement).data("genre"));
  455. Session.set("type", "playlist");
  456. $("#type").val(this.type);
  457. $("#artist").val(this.artist);
  458. $("#title").val(this.title);
  459. $("#img").val(this.img);
  460. $("#id").val(this.id);
  461. $("#duration").val(this.duration);
  462. },
  463. "click .add-song-button": function(e){
  464. var genre = $(e.toElement).data("genre") || $(e.toElement).parent().data("genre");
  465. Meteor.call("addSongToPlaylist", genre, this);
  466. },
  467. "click .deny-song-button": function(e){
  468. var genre = $(e.toElement).data("genre") || $(e.toElement).parent().data("genre");
  469. Meteor.call("removeSongFromQueue", genre, this.id);
  470. },
  471. "click .remove-song-button": function(e){
  472. var genre = $(e.toElement).data("genre") || $(e.toElement).parent().data("genre");
  473. Meteor.call("removeSongFromPlaylist", genre, this.id);
  474. },
  475. "click #play": function() {
  476. $("#play").attr("disabled", true);
  477. $("#stop").attr("disabled", false);
  478. var song = Session.get("song");
  479. var id = song.id;
  480. var type = song.type;
  481. var volume = localStorage.getItem("volume") || 20;
  482. if (type === "YouTube") {
  483. if (yt_player === undefined) {
  484. yt_player = new YT.Player("previewPlayer", {
  485. height: 540,
  486. width: 568,
  487. videoId: id,
  488. playerVars: {autoplay: 1, controls: 0, iv_load_policy: 3, showinfo: 0},
  489. events: {
  490. 'onReady': function(event) {
  491. event.target.playVideo();
  492. event.target.setVolume(volume);
  493. },
  494. 'onStateChange': function(event){
  495. if (event.data == YT.PlayerState.PAUSED) {
  496. event.target.playVideo();
  497. }
  498. if (event.data == YT.PlayerState.PLAYING) {
  499. $("#play").attr("disabled", true);
  500. $("#stop").attr("disabled", false);
  501. } else {
  502. $("#play").attr("disabled", false);
  503. $("#stop").attr("disabled", true);
  504. }
  505. }
  506. }
  507. });
  508. } else {
  509. yt_player.loadVideoById(id);
  510. }
  511. $("#previewPlayer").show();
  512. } else if (type === "SoundCloud") {
  513. SC.stream("/tracks/" + song.id, function(sound) {
  514. _sound = sound;
  515. sound.setVolume(volume / 100);
  516. sound.play();
  517. });
  518. }
  519. },
  520. "click #stop": function() {
  521. $("#play").attr("disabled", false);
  522. $("#stop").attr("disabled", true);
  523. if (yt_player !== undefined) {
  524. yt_player.stopVideo();
  525. }
  526. if (_sound !== undefined) {
  527. _sound.stop();
  528. }
  529. },
  530. "click #croom_create": function() {
  531. Meteor.call("createRoom", $("#croom").val(), function (err, res) {
  532. if (err) {
  533. alert("Error " + err.error + ": " + err.reason);
  534. } else {
  535. window.location = "/" + $("#croom").val();
  536. }
  537. });
  538. },
  539. "click #get-spotify-info": function() {
  540. var search = $("#title").val();
  541. var artistName = $("#artist").val();
  542. console.log(artistName)
  543. getSpotifyInfo(search, function(data) {
  544. console.log(data);
  545. for(var i in data){
  546. for(var j in data[i].items){
  547. if(search.indexOf(data[i].items[j].name) !== -1 && artistName.indexOf(data[i].items[j].artists[0].name) !== -1){
  548. $("#img").val(data[i].items[j].album.images[1].url);
  549. $("#duration").val(data[i].items[j].duration_ms / 1000);
  550. }
  551. }
  552. }
  553. }, artistName);
  554. },
  555. "click #save-song-button": function() {
  556. var newSong = {};
  557. newSong.title = $("#title").val();
  558. newSong.artist = $("#artist").val();
  559. newSong.img = $("#img").val();
  560. newSong.type = $("#type").val();
  561. newSong.duration = $("#duration").val();
  562. if (Session.get("type") === "playlist") {
  563. Meteor.call("updatePlaylistSong", Session.get("genre"), Session.get("song"), newSong, function() {
  564. $('#editModal').modal('hide');
  565. });
  566. } else {
  567. Meteor.call("updateQueueSong", Session.get("genre"), Session.get("song"), newSong, function() {
  568. $('#editModal').modal('hide');
  569. });
  570. }
  571. }
  572. });
  573. Template.admin.onCreated(function() {
  574. var tag = document.createElement("script");
  575. tag.src = "https://www.youtube.com/iframe_api";
  576. var firstScriptTag = document.getElementsByTagName('script')[0];
  577. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  578. });
  579. Template.admin.onRendered(function() {
  580. $("#previewModal").on("hidden.bs.modal", function() {
  581. if (yt_player !== undefined) {
  582. $("#play").attr("disabled", false);
  583. $("#stop").attr("disabled", true);
  584. $("#previewPlayer").hide();
  585. yt_player.loadVideoById("", 0);
  586. yt_player.seekTo(0);
  587. yt_player.stopVideo();
  588. }
  589. if (_sound !== undefined) {
  590. _sound.stop();
  591. $("#play").attr("disabled", false);
  592. $("#stop").attr("disabled", true);
  593. }
  594. });
  595. $(document).ready(function() {
  596. function makeSlider(){
  597. var slider = $("#volume-slider").slider();
  598. var volume = localStorage.getItem("volume") || 20;
  599. $("#volume-slider").slider("setValue", volume);
  600. if (slider.length === 0) {
  601. Meteor.setTimeout(function() {
  602. makeSlider();
  603. }, 500);
  604. } else {
  605. slider.on("slide", function(val) {
  606. localStorage.setItem("volume", val.value);
  607. if (yt_player !== undefined) {
  608. yt_player.setVolume(val.value);
  609. } else if (_sound !== undefined) {
  610. var volume = val.value / 100;
  611. _sound.setVolume(volume);
  612. }
  613. });
  614. }
  615. }
  616. makeSlider();
  617. });
  618. });
  619. Template.playlist.helpers({
  620. playlist_songs: function() {
  621. parts = location.href.split('/');
  622. id = parts.pop();
  623. type = id.toLowerCase();
  624. var data = Playlists.find({type: type}).fetch();
  625. if (data !== undefined && data.length > 0) {
  626. data[0].songs.map(function(song) {
  627. if (song.title === Session.get("title")) {
  628. song.current = true;
  629. } else {
  630. song.current = false;
  631. }
  632. return song;
  633. });
  634. return data[0].songs;
  635. } else {
  636. return [];
  637. }
  638. }
  639. });
  640. Meteor.subscribe("rooms");
  641. Template.room.onCreated(function () {
  642. if (resizeSeekerbarInterval !== undefined) {
  643. Meteor.clearInterval(resizeSeekerbarInterval);
  644. resizeSeekerbarInterval = undefined;
  645. }
  646. yt_player = undefined;
  647. _sound = undefined;
  648. Session.set("videoHidden", false)
  649. var tag = document.createElement("script");
  650. tag.src = "https://www.youtube.com/iframe_api";
  651. var firstScriptTag = document.getElementsByTagName('script')[0];
  652. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag)
  653. var currentSong = undefined;
  654. var nextSong = undefined;
  655. var afterSong = undefined;
  656. var size = 0;
  657. var artistStr;
  658. var temp = "";
  659. var currentArt;
  660. function getTimeElapsed() {
  661. if (currentSong !== undefined) {
  662. return Date.now() - currentSong.started;
  663. }
  664. return 0;
  665. }
  666. function getSongInfo(songData){
  667. Session.set("title", songData.title);
  668. Session.set("artist", songData.artist);
  669. $("#song-img").attr("src", songData.img);
  670. Session.set("duration", songData.duration);
  671. }
  672. function resizeSeekerbar() {
  673. $("#seeker-bar").width(((getTimeElapsed() / 1000) / Session.get("duration") * 100) + "%");
  674. }
  675. function startSong() {
  676. if (currentSong !== undefined) {
  677. if (_sound !== undefined) _sound.stop();
  678. if (yt_player !== undefined && yt_player.stopVideo !== undefined) yt_player.stopVideo();
  679. var volume = localStorage.getItem("volume") || 20;
  680. $("#media-container").empty();
  681. yt_player = undefined;
  682. if (currentSong.type === "SoundCloud") {
  683. $("#media-container").append('<img src="/soundcloud-image.png" class="embed-responsive-item" />');
  684. getSongInfo(currentSong);
  685. SC.stream("/tracks/" + currentSong.id, function(sound){
  686. _sound = sound;
  687. sound.setVolume(volume / 100);
  688. sound.play();
  689. var interval = setInterval(function() {
  690. if (sound.getState() === "playing") {
  691. sound.seek(getTimeElapsed());
  692. window.clearInterval(interval);
  693. }
  694. }, 200);
  695. // Session.set("title", currentSong.title || "Title");
  696. // Session.set("artist", currentSong.artist || "Artist");
  697. Session.set("duration", currentSong.duration);
  698. resizeSeekerbar();
  699. });
  700. } else {
  701. $("#media-container").append('<div id="player" class="embed-responsive-item"></div>');
  702. if (yt_player === undefined) {
  703. yt_player = new YT.Player("player", {
  704. height: 540,
  705. width: 960,
  706. videoId: currentSong.id,
  707. playerVars: {controls: 0, iv_load_policy: 3, rel: 0, showinfo: 0},
  708. events: {
  709. 'onReady': function(event) {
  710. event.target.seekTo(getTimeElapsed() / 1000);
  711. event.target.playVideo();
  712. event.target.setVolume(volume);
  713. resizeSeekerbar();
  714. },
  715. 'onStateChange': function(event){
  716. if (event.data == YT.PlayerState.PAUSED) {
  717. event.target.seekTo(getTimeElapsed() / 1000);
  718. event.target.playVideo();
  719. }
  720. }
  721. }
  722. });
  723. } else {
  724. yt_player.loadVideoById(currentSong.id);
  725. }
  726. // Session.set("title", currentSong.title || "Title");
  727. // Session.set("artist", currentSong.artist || "Artist");
  728. getSongInfo(currentSong);
  729. //Session.set("duration", currentSong.duration);
  730. }
  731. }
  732. }
  733. Meteor.subscribe("history");
  734. Session.set("loaded", false);
  735. Meteor.subscribe("rooms", function() {
  736. var parts = location.href.split('/');
  737. var id = parts.pop();
  738. var type = id.toLowerCase();
  739. if (Rooms.find({type: type}).count() !== 1) {
  740. window.location = "/";
  741. } else {
  742. Session.set("loaded", true);
  743. minterval = Meteor.setInterval(function () {
  744. var data = undefined;
  745. var dataCursorH = History.find({type: type});
  746. var dataCursorP = Playlists.find({type: type});
  747. dataCursorH.forEach(function (doc) {
  748. if (data === undefined) {
  749. data = doc;
  750. }
  751. });
  752. if (data !== undefined && data.history.length > size) {
  753. //currentSong = data.history[data.history.length - 1];
  754. var songArray = Playlists.find({type: type}).fetch()[0].songs;
  755. var historyObj = data.history[data.history.length - 1];
  756. songArray.forEach(function(song) {
  757. if (song.id === historyObj.song.id) {
  758. currentSong = song;
  759. }
  760. });
  761. currentSong.started = historyObj.started;
  762. var songs = dataCursorP.fetch()[0].songs;
  763. songs.forEach(function(song, index) {
  764. if (currentSong.title === song.title) {
  765. if (index + 1 < songs.length) {
  766. nextSong = songs[index + 1];
  767. } else {
  768. nextSong = songs[0];
  769. }
  770. Session.set("title_next", nextSong.title);
  771. Session.set("artist_next", nextSong.artist);
  772. $("#song-img-next").attr("src", nextSong.img);
  773. if (index + 2 < songs.length) {
  774. afterSong = songs[index + 2];
  775. } else if (songs.length === index + 1 && songs.length > 1 ) {
  776. afterSong = songs[1];
  777. } else {
  778. afterSong = songs[0];
  779. }
  780. Session.set("title_after", afterSong.title);
  781. Session.set("artist_after", afterSong.artist);
  782. $("#song-img-after").attr("src",afterSong.img);
  783. }
  784. });
  785. size = data.history.length;
  786. startSong();
  787. }
  788. }, 1000);
  789. resizeSeekerbarInterval = Meteor.setInterval(function () {
  790. resizeSeekerbar();
  791. }, 500);
  792. }
  793. });
  794. });
  795. }
  796. if (Meteor.isServer) {
  797. Meteor.startup(function() {
  798. reCAPTCHA.config({
  799. privatekey: '6LcVxg0TAAAAAI2fgIEEWHFxwNXeVIs8mzq5cfRM'
  800. });
  801. var stations = ["edm", "pop"]; //Rooms to be set on server startup
  802. for(var i in stations){
  803. if(Rooms.find({type: stations[i]}).count() === 0){
  804. createRoom(stations[i]);
  805. }
  806. }
  807. });
  808. function createRoom(type) {
  809. if (Rooms.find({type: type}).count() === 0) {
  810. Rooms.insert({type: type}, function(err) {
  811. if (err) {
  812. throw err;
  813. } else {
  814. if (Playlists.find({type: type}).count() === 1) {
  815. if (History.find({type: type}).count() === 0) {
  816. History.insert({type: type, history: []}, function(err3) {
  817. if (err3) {
  818. throw err3;
  819. } else {
  820. startStation();
  821. return true;
  822. }
  823. });
  824. } else {
  825. startStation();
  826. return true;
  827. }
  828. } else {
  829. Playlists.insert({type: type, songs: getSongsByType(type)}, function (err2) {
  830. if (err2) {
  831. throw err2;
  832. } else {
  833. if (History.find({type: type}).count() === 0) {
  834. History.insert({type: type, history: []}, function(err3) {
  835. if (err3) {
  836. throw err3;
  837. } else {
  838. startStation();
  839. return true;
  840. }
  841. });
  842. } else {
  843. startStation(type);
  844. return true;
  845. }
  846. }
  847. });
  848. }
  849. }
  850. });
  851. } else {
  852. throw "Room already exists";
  853. }
  854. }
  855. function startStation(type) {
  856. var startedAt = Date.now();
  857. var playlist = Playlists.find({type: type}).fetch()[0];
  858. var songs = playlist.songs;
  859. if (playlist.lastSong === undefined) {
  860. Playlists.update({type: type}, {$set: {lastSong: 0}});
  861. playlist = Playlists.find({type: type}).fetch()[0];
  862. songs = playlist.songs;
  863. }
  864. var currentSong = playlist.lastSong;
  865. addToHistory(songs[currentSong], startedAt);
  866. function addToHistory(song, startedAt) {
  867. History.update({type: type}, {$push: {history: {song: song, started: startedAt}}});
  868. }
  869. function skipSong() {
  870. songs = Playlists.find({type: type}).fetch()[0].songs;
  871. if (currentSong < (songs.length - 1)) {
  872. currentSong++;
  873. } else currentSong = 0;
  874. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  875. songTimer();
  876. addToHistory(songs[currentSong], startedAt);
  877. }
  878. function songTimer() {
  879. startedAt = Date.now();
  880. var ctimer = Meteor.setTimeout(function() {
  881. skipSong();
  882. Meteor.clearTimeout(ctimer);
  883. }, songs[currentSong].duration * 1000);
  884. }
  885. songTimer();
  886. }
  887. Meteor.users.deny({update: function () { return true; }});
  888. Meteor.users.deny({insert: function () { return true; }});
  889. Meteor.users.deny({remove: function () { return true; }});
  890. function getSongDuration(query, artistName){
  891. var duration;
  892. var search = query;
  893. query = query.toLowerCase().split(" ").join("%20");
  894. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + query + '&type=track');
  895. for(var i in res.data){
  896. for(var j in res.data[i].items){
  897. if(search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1){
  898. duration = res.data[i].items[j].duration_ms / 1000;
  899. return duration;
  900. }
  901. }
  902. }
  903. }
  904. function getSongAlbumArt(query, artistName){
  905. var albumart;
  906. var search = query;
  907. query = query.toLowerCase().split(" ").join("%20");
  908. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + query + '&type=track');
  909. for(var i in res.data){
  910. for(var j in res.data[i].items){
  911. if(search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1){
  912. albumart = res.data[i].items[j].album.images[1].url
  913. return albumart;
  914. }
  915. }
  916. }
  917. }
  918. //var room_types = ["edm", "nightcore"];
  919. var songsArr = [];
  920. function getSongsByType(type) {
  921. if (type === "edm") {
  922. return [
  923. {id: "aE2GCa-_nyU", title: "Radioactive", duration: getSongDuration("Radioactive - Lindsey Stirling and Pentatonix", "Lindsey Stirling, Pentatonix"), artist: "Lindsey Stirling, Pentatonix", type: "YouTube", img: "https://i.scdn.co/image/62167a9007cef2e8ef13ab1d93019312b9b03655"},
  924. {id: "aHjpOzsQ9YI", title: "Crystallize", artist: "Lindsey Stirling", duration: getSongDuration("Crystallize", "Lindsey Stirling"), type: "YouTube", img: "https://i.scdn.co/image/b0c1ccdd0cd7bcda741ccc1c3e036f4ed2e52312"}
  925. ];
  926. } else if (type === "nightcore") {
  927. 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"}];
  928. } else {
  929. 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"}];
  930. }
  931. }
  932. Rooms.find({}).fetch().forEach(function(room) {
  933. var type = room.type;
  934. if (Playlists.find({type: type}).count() === 0) {
  935. if (type === "edm") {
  936. Playlists.insert({type: type, songs: getSongsByType(type)});
  937. } else if (type === "nightcore") {
  938. Playlists.insert({type: type, songs: getSongsByType(type)});
  939. } else {
  940. Playlists.insert({type: type, songs: getSongsByType(type)});
  941. }
  942. }
  943. if (History.find({type: type}).count() === 0) {
  944. History.insert({type: type, history: []});
  945. }
  946. if (Playlists.find({type: type}).fetch()[0].songs.length === 0) {
  947. // Add a global video to Playlist so it can proceed
  948. } else {
  949. startStation(type);
  950. }
  951. });
  952. Accounts.onCreateUser(function(options, user) {
  953. var username;
  954. if (user.services) {
  955. if (user.services.github) {
  956. username = user.services.github.username;
  957. } else if (user.services.facebook) {
  958. username = user.services.facebook.first_name;
  959. } else if (user.services.password) {
  960. username = user.username;
  961. }
  962. }
  963. user.profile = {username: username, usernameL: username.toLowerCase(), rank: "default"};
  964. return user;
  965. });
  966. ServiceConfiguration.configurations.remove({
  967. service: "facebook"
  968. });
  969. ServiceConfiguration.configurations.insert({
  970. service: "facebook",
  971. appId: "1496014310695890",
  972. secret: "9a039f254a08a1488c08bb0737dbd2a6"
  973. });
  974. ServiceConfiguration.configurations.remove({
  975. service: "github"
  976. });
  977. ServiceConfiguration.configurations.insert({
  978. service: "github",
  979. clientId: "dcecd720f47c0e4001f7",
  980. secret: "375939d001ef1a0ca67c11dbf8fb9aeaa551e01b"
  981. });
  982. Meteor.publish("history", function() {
  983. return History.find({})
  984. });
  985. Meteor.publish("playlists", function() {
  986. return Playlists.find({})
  987. });
  988. Meteor.publish("rooms", function() {
  989. return Rooms.find({});
  990. });
  991. Meteor.publish("queues", function() {
  992. return Queues.find({});
  993. });
  994. Meteor.publish("chat", function() {
  995. return Chat.find({});
  996. });
  997. Meteor.publish("userProfiles", function() {
  998. //console.log(Meteor.users.find({}, {profile: 1, createdAt: 1, services: 0, username: 0, emails: 0})).fetch();
  999. return Meteor.users.find({}, {fields: {profile: 1, createdAt: 1}});
  1000. });
  1001. Meteor.publish("isAdmin", function() {
  1002. return Meteor.users.find({_id: this.userId, "profile.rank": "admin"});
  1003. });
  1004. Meteor.methods({
  1005. createUserMethod: function(formData, captchaData) {
  1006. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  1007. if (!verifyCaptchaResponse.success) {
  1008. console.log('reCAPTCHA check failed!', verifyCaptchaResponse);
  1009. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  1010. } else {
  1011. console.log('reCAPTCHA verification passed!');
  1012. Accounts.createUser({
  1013. username: formData.username,
  1014. email: formData.email,
  1015. password: formData.password
  1016. });
  1017. }
  1018. return true;
  1019. },
  1020. addSongToQueue: function(type, songData) {
  1021. if (Meteor.userId()) {
  1022. type = type.toLowerCase();
  1023. if (Rooms.find({type: type}).count() === 1) {
  1024. if (Queues.find({type: type}).count() === 0) {
  1025. Queues.insert({type: type, songs: []});
  1026. }
  1027. if (songData !== undefined && Object.keys(songData).length === 5 && songData.type !== undefined && songData.title !== undefined && songData.title !== undefined && songData.artist !== undefined && songData.img !== undefined) {
  1028. songData.duration = getSongDuration(songData.title, songData.artist);
  1029. songData.img = getSongAlbumArt(songData.title, songData.artist);
  1030. Queues.update({type: type}, {
  1031. $push: {
  1032. songs: {
  1033. id: songData.id,
  1034. title: songData.title,
  1035. artist: songData.artist,
  1036. duration: songData.duration,
  1037. img: songData.img,
  1038. type: songData.type
  1039. }
  1040. }
  1041. });
  1042. return true;
  1043. } else {
  1044. throw new Meteor.error(403, "Invalid data.");
  1045. }
  1046. } else {
  1047. throw new Meteor.error(403, "Invalid genre.");
  1048. }
  1049. } else {
  1050. throw new Meteor.error(403, "Invalid permissions.");
  1051. }
  1052. },
  1053. updateQueueSong: function(genre, oldSong, newSong) {
  1054. var userData = Meteor.users.find(Meteor.userId());
  1055. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  1056. newSong.id = oldSong.id;
  1057. Queues.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  1058. return true;
  1059. } else {
  1060. throw new Meteor.error(403, "Invalid permissions.");
  1061. }
  1062. },
  1063. updatePlaylistSong: function(genre, oldSong, newSong) {
  1064. var userData = Meteor.users.find(Meteor.userId());
  1065. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  1066. newSong.id = oldSong.id;
  1067. Playlists.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  1068. return true;
  1069. } else {
  1070. throw new Meteor.error(403, "Invalid permissions.");
  1071. }
  1072. },
  1073. removeSongFromQueue: function(type, songId) {
  1074. var userData = Meteor.users.find(Meteor.userId());
  1075. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  1076. type = type.toLowerCase();
  1077. Queues.update({type: type}, {$pull: {songs: {id: songId}}});
  1078. } else {
  1079. throw new Meteor.error(403, "Invalid permissions.");
  1080. }
  1081. },
  1082. removeSongFromPlaylist: function(type, songId) {
  1083. var userData = Meteor.users.find(Meteor.userId());
  1084. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  1085. type = type.toLowerCase();
  1086. Playlists.update({type: type}, {$pull: {songs: {id: songId}}});
  1087. } else {
  1088. throw new Meteor.error(403, "Invalid permissions.");
  1089. }
  1090. },
  1091. addSongToPlaylist: function(type, songData) {
  1092. var userData = Meteor.users.find(Meteor.userId());
  1093. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  1094. type = type.toLowerCase();
  1095. if (Rooms.find({type: type}).count() === 1) {
  1096. if (Playlists.find({type: type}).count() === 0) {
  1097. Playlists.insert({type: type, songs: []});
  1098. }
  1099. 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) {
  1100. Playlists.update({type: type}, {
  1101. $push: {
  1102. songs: {
  1103. id: songData.id,
  1104. title: songData.title,
  1105. artist: songData.artist,
  1106. duration: songData.duration,
  1107. img: songData.img,
  1108. type: songData.type
  1109. }
  1110. }
  1111. });
  1112. Queues.update({type: type}, {$pull: {songs: {id: songData.id}}});
  1113. return true;
  1114. } else {
  1115. throw new Meteor.error(403, "Invalid data.");
  1116. }
  1117. } else {
  1118. throw new Meteor.error(403, "Invalid genre.");
  1119. }
  1120. } else {
  1121. throw new Meteor.error(403, "Invalid permissions.");
  1122. }
  1123. },
  1124. createRoom: function(type) {
  1125. var userData = Meteor.users.find(Meteor.userId());
  1126. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  1127. createRoom(type);
  1128. } else {
  1129. return false;
  1130. }
  1131. }
  1132. });
  1133. }
  1134. /*Router.waitOn(function() {
  1135. Meteor.subscribe("isAdmin", Meteor.userId());
  1136. });*/
  1137. /*Router.onBeforeAction(function() {
  1138. /*Meteor.autorun(function () {
  1139. if (admin.ready()) {
  1140. this.next();
  1141. }
  1142. });*/
  1143. /*this.next();
  1144. });*/
  1145. Router.route("/", {
  1146. template: "home"
  1147. });
  1148. Router.route("/login", {
  1149. template: "login"
  1150. })
  1151. Router.route("/signup", {
  1152. template: "register"
  1153. })
  1154. Router.route("/terms", {
  1155. template: "terms"
  1156. });
  1157. Router.route("/privacy", {
  1158. template: "privacy"
  1159. });
  1160. Router.route("/about", {
  1161. template: "about"
  1162. });
  1163. Router.route("/admin", {
  1164. waitOn: function() {
  1165. return Meteor.subscribe("isAdmin", Meteor.userId());
  1166. },
  1167. action: function() {
  1168. var user = Meteor.users.find({}).fetch();
  1169. if (user[0] !== undefined && user[0].profile !== undefined && user[0].profile.rank === "admin") {
  1170. this.render("admin");
  1171. } else {
  1172. this.redirect("/");
  1173. }
  1174. }
  1175. });
  1176. Router.route("/vis", {
  1177. template: "visualizer"
  1178. });
  1179. Router.route("/:type", {
  1180. template: "room"
  1181. });
  1182. Router.route("/u/:user", {
  1183. template: "profile"
  1184. });