app.js 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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. var currentTitle = songs[currentSong].title;
  866. addToHistory(songs[currentSong], startedAt);
  867. function addToHistory(song, startedAt) {
  868. History.update({type: type}, {$push: {history: {song: song, started: startedAt}}});
  869. }
  870. function skipSong() {
  871. songs = Playlists.find({type: type}).fetch()[0].songs;
  872. songs.forEach(function(song, index) {
  873. if (song.title === currentTitle) {
  874. currentSong = index;
  875. }
  876. });
  877. if (currentSong < (songs.length - 1)) {
  878. currentSong++;
  879. } else currentSong = 0;
  880. if (songs)
  881. currentTitle = songs[currentSong].title;
  882. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  883. songTimer();
  884. addToHistory(songs[currentSong], startedAt);
  885. }
  886. function songTimer() {
  887. startedAt = Date.now();
  888. var ctimer = Meteor.setTimeout(function() {
  889. skipSong();
  890. Meteor.clearTimeout(ctimer);
  891. }, songs[currentSong].duration * 1000);
  892. }
  893. songTimer();
  894. }
  895. Meteor.users.deny({update: function () { return true; }});
  896. Meteor.users.deny({insert: function () { return true; }});
  897. Meteor.users.deny({remove: function () { return true; }});
  898. function getSongDuration(query, artistName){
  899. var duration;
  900. var search = query;
  901. query = query.toLowerCase().split(" ").join("%20");
  902. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + query + '&type=track');
  903. for(var i in res.data){
  904. for(var j in res.data[i].items){
  905. if(search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1){
  906. duration = res.data[i].items[j].duration_ms / 1000;
  907. return duration;
  908. }
  909. }
  910. }
  911. }
  912. function getSongAlbumArt(query, artistName){
  913. var albumart;
  914. var search = query;
  915. query = query.toLowerCase().split(" ").join("%20");
  916. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + query + '&type=track');
  917. for(var i in res.data){
  918. for(var j in res.data[i].items){
  919. if(search.indexOf(res.data[i].items[j].name) !== -1 && artistName.indexOf(res.data[i].items[j].artists[0].name) !== -1){
  920. albumart = res.data[i].items[j].album.images[1].url
  921. return albumart;
  922. }
  923. }
  924. }
  925. }
  926. //var room_types = ["edm", "nightcore"];
  927. var songsArr = [];
  928. function getSongsByType(type) {
  929. if (type === "edm") {
  930. return [
  931. {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"},
  932. {id: "aHjpOzsQ9YI", title: "Crystallize", artist: "Lindsey Stirling", duration: getSongDuration("Crystallize", "Lindsey Stirling"), type: "YouTube", img: "https://i.scdn.co/image/b0c1ccdd0cd7bcda741ccc1c3e036f4ed2e52312"}
  933. ];
  934. } else if (type === "nightcore") {
  935. 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"}];
  936. } else {
  937. 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"}];
  938. }
  939. }
  940. Rooms.find({}).fetch().forEach(function(room) {
  941. var type = room.type;
  942. if (Playlists.find({type: type}).count() === 0) {
  943. if (type === "edm") {
  944. Playlists.insert({type: type, songs: getSongsByType(type)});
  945. } else if (type === "nightcore") {
  946. Playlists.insert({type: type, songs: getSongsByType(type)});
  947. } else {
  948. Playlists.insert({type: type, songs: getSongsByType(type)});
  949. }
  950. }
  951. if (History.find({type: type}).count() === 0) {
  952. History.insert({type: type, history: []});
  953. }
  954. if (Playlists.find({type: type}).fetch()[0].songs.length === 0) {
  955. // Add a global video to Playlist so it can proceed
  956. } else {
  957. startStation(type);
  958. }
  959. });
  960. Accounts.onCreateUser(function(options, user) {
  961. var username;
  962. if (user.services) {
  963. if (user.services.github) {
  964. username = user.services.github.username;
  965. } else if (user.services.facebook) {
  966. username = user.services.facebook.first_name;
  967. } else if (user.services.password) {
  968. username = user.username;
  969. }
  970. }
  971. user.profile = {username: username, usernameL: username.toLowerCase(), rank: "default"};
  972. return user;
  973. });
  974. ServiceConfiguration.configurations.remove({
  975. service: "facebook"
  976. });
  977. ServiceConfiguration.configurations.insert({
  978. service: "facebook",
  979. appId: "1496014310695890",
  980. secret: "9a039f254a08a1488c08bb0737dbd2a6"
  981. });
  982. ServiceConfiguration.configurations.remove({
  983. service: "github"
  984. });
  985. ServiceConfiguration.configurations.insert({
  986. service: "github",
  987. clientId: "dcecd720f47c0e4001f7",
  988. secret: "375939d001ef1a0ca67c11dbf8fb9aeaa551e01b"
  989. });
  990. Meteor.publish("history", function() {
  991. return History.find({})
  992. });
  993. Meteor.publish("playlists", function() {
  994. return Playlists.find({})
  995. });
  996. Meteor.publish("rooms", function() {
  997. return Rooms.find({});
  998. });
  999. Meteor.publish("queues", function() {
  1000. return Queues.find({});
  1001. });
  1002. Meteor.publish("chat", function() {
  1003. return Chat.find({});
  1004. });
  1005. Meteor.publish("userProfiles", function() {
  1006. //console.log(Meteor.users.find({}, {profile: 1, createdAt: 1, services: 0, username: 0, emails: 0})).fetch();
  1007. return Meteor.users.find({}, {fields: {profile: 1, createdAt: 1}});
  1008. });
  1009. Meteor.publish("isAdmin", function() {
  1010. return Meteor.users.find({_id: this.userId, "profile.rank": "admin"});
  1011. });
  1012. Meteor.methods({
  1013. createUserMethod: function(formData, captchaData) {
  1014. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  1015. if (!verifyCaptchaResponse.success) {
  1016. console.log('reCAPTCHA check failed!', verifyCaptchaResponse);
  1017. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  1018. } else {
  1019. console.log('reCAPTCHA verification passed!');
  1020. Accounts.createUser({
  1021. username: formData.username,
  1022. email: formData.email,
  1023. password: formData.password
  1024. });
  1025. }
  1026. return true;
  1027. },
  1028. addSongToQueue: function(type, songData) {
  1029. if (Meteor.userId()) {
  1030. type = type.toLowerCase();
  1031. if (Rooms.find({type: type}).count() === 1) {
  1032. if (Queues.find({type: type}).count() === 0) {
  1033. Queues.insert({type: type, songs: []});
  1034. }
  1035. if (songData !== undefined && Object.keys(songData).length === 5 && songData.type !== undefined && songData.title !== undefined && songData.title !== undefined && songData.artist !== undefined && songData.img !== undefined) {
  1036. songData.duration = getSongDuration(songData.title, songData.artist);
  1037. songData.img = getSongAlbumArt(songData.title, songData.artist);
  1038. Queues.update({type: type}, {
  1039. $push: {
  1040. songs: {
  1041. id: songData.id,
  1042. title: songData.title,
  1043. artist: songData.artist,
  1044. duration: songData.duration,
  1045. img: songData.img,
  1046. type: songData.type
  1047. }
  1048. }
  1049. });
  1050. return true;
  1051. } else {
  1052. throw new Meteor.error(403, "Invalid data.");
  1053. }
  1054. } else {
  1055. throw new Meteor.error(403, "Invalid genre.");
  1056. }
  1057. } else {
  1058. throw new Meteor.error(403, "Invalid permissions.");
  1059. }
  1060. },
  1061. updateQueueSong: function(genre, oldSong, newSong) {
  1062. var userData = Meteor.users.find(Meteor.userId());
  1063. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  1064. newSong.id = oldSong.id;
  1065. Queues.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  1066. return true;
  1067. } else {
  1068. throw new Meteor.error(403, "Invalid permissions.");
  1069. }
  1070. },
  1071. updatePlaylistSong: function(genre, oldSong, newSong) {
  1072. var userData = Meteor.users.find(Meteor.userId());
  1073. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  1074. newSong.id = oldSong.id;
  1075. Playlists.update({type: genre, "songs": oldSong}, {$set: {"songs.$": newSong}});
  1076. return true;
  1077. } else {
  1078. throw new Meteor.error(403, "Invalid permissions.");
  1079. }
  1080. },
  1081. removeSongFromQueue: function(type, songId) {
  1082. var userData = Meteor.users.find(Meteor.userId());
  1083. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  1084. type = type.toLowerCase();
  1085. Queues.update({type: type}, {$pull: {songs: {id: songId}}});
  1086. } else {
  1087. throw new Meteor.error(403, "Invalid permissions.");
  1088. }
  1089. },
  1090. removeSongFromPlaylist: function(type, songId) {
  1091. var userData = Meteor.users.find(Meteor.userId());
  1092. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  1093. type = type.toLowerCase();
  1094. Playlists.update({type: type}, {$pull: {songs: {id: songId}}});
  1095. } else {
  1096. throw new Meteor.error(403, "Invalid permissions.");
  1097. }
  1098. },
  1099. addSongToPlaylist: function(type, songData) {
  1100. var userData = Meteor.users.find(Meteor.userId());
  1101. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  1102. type = type.toLowerCase();
  1103. if (Rooms.find({type: type}).count() === 1) {
  1104. if (Playlists.find({type: type}).count() === 0) {
  1105. Playlists.insert({type: type, songs: []});
  1106. }
  1107. 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) {
  1108. Playlists.update({type: type}, {
  1109. $push: {
  1110. songs: {
  1111. id: songData.id,
  1112. title: songData.title,
  1113. artist: songData.artist,
  1114. duration: songData.duration,
  1115. img: songData.img,
  1116. type: songData.type
  1117. }
  1118. }
  1119. });
  1120. Queues.update({type: type}, {$pull: {songs: {id: songData.id}}});
  1121. return true;
  1122. } else {
  1123. throw new Meteor.error(403, "Invalid data.");
  1124. }
  1125. } else {
  1126. throw new Meteor.error(403, "Invalid genre.");
  1127. }
  1128. } else {
  1129. throw new Meteor.error(403, "Invalid permissions.");
  1130. }
  1131. },
  1132. createRoom: function(type) {
  1133. var userData = Meteor.users.find(Meteor.userId());
  1134. if (Meteor.userId() && userData.count !== 0 && userData.fetch()[0].profile.rank === "admin") {
  1135. createRoom(type);
  1136. } else {
  1137. return false;
  1138. }
  1139. }
  1140. });
  1141. }
  1142. /*Router.waitOn(function() {
  1143. Meteor.subscribe("isAdmin", Meteor.userId());
  1144. });*/
  1145. /*Router.onBeforeAction(function() {
  1146. /*Meteor.autorun(function () {
  1147. if (admin.ready()) {
  1148. this.next();
  1149. }
  1150. });*/
  1151. /*this.next();
  1152. });*/
  1153. Router.route("/", {
  1154. template: "home"
  1155. });
  1156. Router.route("/login", {
  1157. template: "login"
  1158. })
  1159. Router.route("/signup", {
  1160. template: "register"
  1161. })
  1162. Router.route("/terms", {
  1163. template: "terms"
  1164. });
  1165. Router.route("/privacy", {
  1166. template: "privacy"
  1167. });
  1168. Router.route("/about", {
  1169. template: "about"
  1170. });
  1171. Router.route("/admin", {
  1172. waitOn: function() {
  1173. return Meteor.subscribe("isAdmin", Meteor.userId());
  1174. },
  1175. action: function() {
  1176. var user = Meteor.users.find({}).fetch();
  1177. if (user[0] !== undefined && user[0].profile !== undefined && user[0].profile.rank === "admin") {
  1178. this.render("admin");
  1179. } else {
  1180. this.redirect("/");
  1181. }
  1182. }
  1183. });
  1184. Router.route("/vis", {
  1185. template: "visualizer"
  1186. });
  1187. Router.route("/:type", {
  1188. template: "room"
  1189. });
  1190. Router.route("/u/:user", {
  1191. template: "profile"
  1192. });