app.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  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. function htmlEntities(str) {
  7. return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  8. }
  9. if (Meteor.isClient) {
  10. Meteor.startup(function() {
  11. reCAPTCHA.config({
  12. publickey: '6LcVxg0TAAAAAE18vBiH00UAyaJggsmLm890SjZl'
  13. });
  14. });
  15. Meteor.subscribe("queues");
  16. var hpSound = undefined;
  17. var songsArr = [];
  18. var ytArr = [];
  19. var _sound = undefined;
  20. var parts = location.href.split('/');
  21. var id = parts.pop();
  22. var type = id.toLowerCase();
  23. function getSpotifyInfo(title, cb) {
  24. $.ajax({
  25. type: "GET",
  26. url: 'https://api.spotify.com/v1/search?q=' + encodeURIComponent(title.toLowerCase()) + '&type=track',
  27. applicationType: "application/json",
  28. contentType: "json",
  29. success: function (data) {
  30. cb(data);
  31. }
  32. });
  33. }
  34. function getSpotifyArtist(data) {
  35. var temp = "";
  36. var artist;
  37. if(data.artists.length >= 2){
  38. for(var k in data.artists){
  39. temp = temp + data.artists[k].name + ", ";
  40. }
  41. } else{
  42. for(var k in data.artists){
  43. temp = temp + data.artists[k].name;
  44. }
  45. }
  46. if(temp[temp.length-2] === ","){
  47. artist = temp.substr(0,temp.length-2);
  48. } else{
  49. artist = temp;
  50. }
  51. return artist;
  52. }
  53. Template.profile.helpers({
  54. "username": function() {
  55. return Session.get("username");
  56. },
  57. "first_joined": function() {
  58. return moment(Session.get("first_joined")).format("DD/MM/YYYY HH:mm:ss");
  59. },
  60. "rank": function() {
  61. return Session.get("rank");
  62. }
  63. });
  64. Template.profile.onCreated(function() {
  65. var parts = location.href.split('/');
  66. var username = parts.pop();
  67. Meteor.subscribe("userProfiles", function() {
  68. if (Meteor.users.find({"profile.username": username}).count() === 0) {
  69. // Return to homepage
  70. } else {
  71. var data = Meteor.users.find({"profile.username": username}).fetch()[0];
  72. Session.set("username", username);
  73. Session.set("first_joined", data.createdAt);
  74. Session.set("rank", data.profile.rank);
  75. }
  76. });
  77. });
  78. 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}}};
  79. Handlebars.registerHelper('active', function(path) {
  80. return curPath() == path ? 'active' : '';
  81. });
  82. Template.header.helpers({
  83. currentUser: function() {
  84. return Meteor.user();
  85. },
  86. isAdmin: function() {
  87. if (Meteor.user() && Meteor.user().profile) {
  88. return Meteor.user().profile.rank === "admin";
  89. } else {
  90. return false;
  91. }
  92. }
  93. });
  94. Template.header.events({
  95. "click .logout": function(e){
  96. e.preventDefault();
  97. Meteor.logout();
  98. if (hpSound !== undefined) {
  99. hpSound.stop();
  100. }
  101. }
  102. });
  103. Template.register.events({
  104. "submit form": function(e){
  105. e.preventDefault();
  106. var username = e.target.registerUsername.value;
  107. var email = e.target.registerEmail.value;
  108. var password = e.target.registerPassword.value;
  109. var captchaData = grecaptcha.getResponse();
  110. Meteor.call("createUserMethod", {username: username, email: email, password: password}, captchaData, function(err, res) {
  111. grecaptcha.reset();
  112. console.log(username, password, err, res);
  113. if (err) {
  114. console.log(err);
  115. $(".container").after('<div class="alert alert-danger" role="alert"><strong>Oh Snap!</strong> ' + err.reason + '</div>')
  116. } else {
  117. console.log();
  118. Meteor.loginWithPassword(username, password);
  119. }
  120. });
  121. },
  122. "click #facebook-login": function(){
  123. Meteor.loginWithFacebook()
  124. },
  125. "click #github-login": function(){
  126. Meteor.loginWithGithub()
  127. },
  128. "click #login": function(){
  129. $("#register-view").hide();
  130. $("#login-view").show();
  131. }
  132. });
  133. Template.login.events({
  134. "submit form": function(e){
  135. e.preventDefault();
  136. var username = e.target.loginUsername.value;
  137. var password = e.target.loginPassword.value;
  138. Meteor.loginWithPassword(username, password);
  139. Accounts.onLoginFailure(function(){
  140. $("input").css("background-color","indianred").addClass("animated shake");
  141. $("input").on("click",function(){
  142. $("input").css({
  143. "background-color": "transparent",
  144. "width": "250px"
  145. });
  146. })
  147. });
  148. },
  149. "click #facebook-login": function(){
  150. Meteor.loginWithFacebook()
  151. },
  152. "click #github-login": function(){
  153. Meteor.loginWithGithub()
  154. },
  155. "click #register": function(){
  156. $("#login-view").hide();
  157. $("#register-view").show();
  158. }
  159. });
  160. Template.dashboard.events({
  161. "click #croom_create": function() {
  162. Meteor.call("createRoom", $("#croom").val(), function (err, res) {
  163. if (err) {
  164. alert("Error " + err.error + ": " + err.reason);
  165. } else {
  166. window.location = "/" + $("#croom").val();
  167. }
  168. });
  169. }
  170. });
  171. Template.dashboard.helpers({
  172. rooms: function() {
  173. return Rooms.find({});
  174. }
  175. })
  176. Template.room.events({
  177. "click #add-song-button": function(e){
  178. e.preventDefault();
  179. parts = location.href.split('/');
  180. id = parts.pop();
  181. var genre = id.toLowerCase();
  182. var type = $("#type").val();
  183. id = $("#id").val();
  184. var title = $("#title").val();
  185. var artist = $("#artist").val();
  186. var img = $("#img").val();
  187. var songData = {type: type, id: id, title: title, artist: artist, img: img};
  188. Meteor.call("addSongToQueue", genre, songData, function(err, res) {
  189. console.log(err, res);
  190. });
  191. },
  192. "click #return": function(e){
  193. $("#add-info").hide();
  194. $("#search-info").show();
  195. },
  196. "click #search-song": function(){
  197. $("#song-results").empty();
  198. var search_type = $("#search_type").val();
  199. if (search_type === "YouTube") {
  200. $.ajax({
  201. type: "GET",
  202. url: "https://www.googleapis.com/youtube/v3/search?part=snippet&q=" + $("#song-input").val() + "&key=AIzaSyAgBdacEWrHCHVPPM4k-AFM7uXg-Q__YXY",
  203. applicationType: "application/json",
  204. contentType: "json",
  205. success: function(data){
  206. for(var i in data.items){
  207. $("#song-results").append("<p>" + data.items[i].snippet.title + "</p>");
  208. ytArr.push({title: data.items[i].snippet.title, id: data.items[i].id.videoId});
  209. }
  210. $("#song-results p").click(function(){
  211. $("#search-info").hide();
  212. $("#add-info").show();
  213. var title = $(this).text();
  214. for(var i in ytArr){
  215. if(ytArr[i].title === title){
  216. var songObj = {
  217. id: ytArr[i].id,
  218. title: ytArr[i].title,
  219. type: "youtube"
  220. };
  221. $("#title").val(songObj.title);
  222. $("#artist").val("");
  223. $("#id").val(songObj.id);
  224. $("#type").val("YouTube");
  225. getSpotifyInfo(songObj.title.replace(/\[.*\]/g, ""), function(data) {
  226. if (data.tracks.items.length > 0) {
  227. $("#title").val(data.tracks.items[0].name);
  228. var artists = [];
  229. $("#img").val(data.tracks.items[0].album.images[1].url);
  230. data.tracks.items[0].artists.forEach(function(artist) {
  231. artists.push(artist.name);
  232. });
  233. $("#artist").val(artists.join(", "));
  234. }
  235. });
  236. }
  237. }
  238. })
  239. }
  240. })
  241. } else if (search_type === "SoundCloud") {
  242. SC.get('/tracks', { q: $("#song-input").val()}, function(tracks) {
  243. for(var i in tracks){
  244. $("#song-results").append("<p>" + tracks[i].title + "</p>")
  245. songsArr.push({title: tracks[i].title, id: tracks[i].id, duration: tracks[i].duration / 1000});
  246. }
  247. $("#song-results p").click(function(){
  248. $("#search-info").hide();
  249. $("#add-info").show();
  250. var title = $(this).text();
  251. for(var i in songsArr){
  252. if(songsArr[i].title === title){
  253. var id = songsArr[i].id;
  254. var duration = songsArr[i].duration;
  255. var songObj = {
  256. title: songsArr[i].title,
  257. id: id,
  258. duration: duration,
  259. type: "soundcloud"
  260. }
  261. $("#title").val(songObj.title);
  262. // Set ID field
  263. $("#id").val(songObj.id);
  264. $("#type").val("SoundCloud");
  265. getSpotifyInfo(songObj.title.replace(/\[.*\]/g, ""), function(data) {
  266. if (data.tracks.items.length > 0) {
  267. $("#title").val(data.tracks.items[0].name);
  268. var artists = [];
  269. data.tracks.items[0].artists.forEach(function(artist) {
  270. artists.push(artist.name);
  271. });
  272. $("#artist").val(artists.join(", "));
  273. }
  274. // Set title field again if possible
  275. // Set artist if possible
  276. });
  277. }
  278. }
  279. })
  280. });
  281. }
  282. },
  283. "click #add-songs": function(){
  284. $("#add-songs-modal").show();
  285. },
  286. "click #close-modal": function(){
  287. $("#search-info").show();
  288. $("#add-info").hide();
  289. },
  290. "click #submit-message": function(){
  291. var message = $("#chat-input").val();
  292. Meteor.call("sendMessage", type, message);
  293. }
  294. });
  295. Template.room.helpers({
  296. type: function() {
  297. var parts = location.href.split('/');
  298. var id = parts.pop();
  299. return id.toUpperCase();
  300. },
  301. title: function(){
  302. return Session.get("title");
  303. },
  304. artist: function(){
  305. return Session.get("artist");
  306. },
  307. title_next: function(){
  308. return Session.get("title_next");
  309. },
  310. artist_next: function(){
  311. return Session.get("artist_next");
  312. },
  313. title_after: function(){
  314. return Session.get("title_after");
  315. },
  316. artist_after: function(){
  317. return Session.get("artist_after");
  318. },
  319. loaded: function() {
  320. return Session.get("loaded");
  321. },
  322. chat: function() {
  323. var chatArr = Chat.find({type: type}).fetch();
  324. if (chatArr.length === 0) {
  325. return [];
  326. } else {
  327. return chatArr[0].messages;
  328. }
  329. }
  330. });
  331. Template.admin.helpers({
  332. queues: function() {
  333. return Queues.find({});
  334. }
  335. });
  336. var yt_player = undefined;
  337. var _sound = undefined;
  338. Template.admin.events({
  339. "click .preview-button": function(e){
  340. Session.set("song", this);
  341. },
  342. "click #add-song-button": function(e){
  343. var genre = $(e.toElement).data("genre") || $(e.toElement).parent().data("genre");
  344. Meteor.call("addSongToPlaylist", genre, this);
  345. },
  346. "click #deny-song-button": function(e){
  347. var genre = $(e.toElement).data("genre") || $(e.toElement).parent().data("genre");
  348. Meteor.call("removeSongFromQueue", genre, this.id);
  349. },
  350. "click #play": function() {
  351. $("#play").attr("disabled", true);
  352. $("#stop").attr("disabled", false);
  353. var song = Session.get("song");
  354. var id = song.id;
  355. var type = song.type;
  356. if (type === "YouTube") {
  357. if (yt_player === undefined) {
  358. yt_player = new YT.Player("previewPlayer", {
  359. height: 540,
  360. width: 568,
  361. videoId: id,
  362. playerVars: {autoplay: 1, controls: 0, iv_load_policy: 3},
  363. events: {
  364. 'onReady': function(event) {
  365. event.target.playVideo();
  366. }
  367. }
  368. });
  369. } else {
  370. yt_player.loadVideoById(id);
  371. }
  372. $("#previewPlayer").show();
  373. } else if (type === "SoundCloud") {
  374. SC.stream("/tracks/" + song.id, function(sound) {
  375. _sound = sound;
  376. sound._player._volume = 0.3;
  377. sound.play();
  378. });
  379. }
  380. },
  381. "click #stop": function() {
  382. $("#play").attr("disabled", false);
  383. $("#stop").attr("disabled", true);
  384. if (yt_player !== undefined) {
  385. yt_player.stopVideo();
  386. }
  387. if (_sound !== undefined) {
  388. _sound.stop();
  389. }
  390. }
  391. });
  392. Template.admin.onCreated(function() {
  393. var tag = document.createElement("script");
  394. tag.src = "https://www.youtube.com/iframe_api";
  395. var firstScriptTag = document.getElementsByTagName('script')[0];
  396. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  397. });
  398. Template.admin.onRendered(function() {
  399. $("#previewModal").on("hidden.bs.modal", function() {
  400. if (yt_player !== undefined) {
  401. $("#play").attr("disabled", false);
  402. $("#stop").attr("disabled", true);
  403. $("#previewPlayer").hide();
  404. yt_player.loadVideoById("", 0);
  405. yt_player.seekTo(0);
  406. yt_player.stopVideo();
  407. }
  408. if (_sound !== undefined) {
  409. _sound.stop();
  410. $("#play").attr("disabled", false);
  411. $("#stop").attr("disabled", true);
  412. }
  413. });
  414. });
  415. Template.playlist.helpers({
  416. playlist_songs: function() {
  417. var data = Playlists.find({type: type}).fetch();
  418. if (data !== undefined && data.length > 0) {
  419. return data[0].songs;
  420. } else {
  421. return [];
  422. }
  423. }
  424. });
  425. Meteor.subscribe("rooms");
  426. Meteor.subscribe("chat");
  427. Template.room.onCreated(function () {
  428. var tag = document.createElement("script");
  429. tag.src = "https://www.youtube.com/iframe_api";
  430. var firstScriptTag = document.getElementsByTagName('script')[0];
  431. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  432. var currentSong = undefined;
  433. var nextSong = undefined;
  434. var afterSong = undefined;
  435. var _sound = undefined;
  436. var yt_player = undefined;
  437. var size = 0;
  438. var artistStr;
  439. var temp = "";
  440. var currentArt;
  441. function getTimeElapsed() {
  442. if (currentSong !== undefined) {
  443. return Date.now() - currentSong.started;
  444. }
  445. return 0;
  446. }
  447. function getSongInfo(songData){
  448. Session.set("title", songData.title);
  449. Session.set("artist", songData.artist);
  450. $("#song-img").attr("src", songData.img);
  451. Session.set("duration", songData.duration);
  452. }
  453. function resizeSeekerbar() {
  454. $("#seeker-bar").width(((getTimeElapsed() / 1000) / Session.get("duration") * 100) + "%");
  455. }
  456. function startSong() {
  457. if (currentSong !== undefined) {
  458. if (_sound !== undefined) _sound.stop();
  459. if (yt_player !== undefined && yt_player.stopVideo !== undefined) yt_player.stopVideo();
  460. if (currentSong.type === "soundcloud") {
  461. $("#player").attr("src", "")
  462. getSongInfo(currentSong);
  463. SC.stream("/tracks/" + currentSong.id + "#t=20s", function(sound){
  464. _sound = sound;
  465. sound._player._volume = 0.3;
  466. sound.play();
  467. var interval = setInterval(function() {
  468. if (sound.getState() === "playing") {
  469. sound.seek(getTimeElapsed());
  470. window.clearInterval(interval);
  471. }
  472. }, 200);
  473. // Session.set("title", currentSong.title || "Title");
  474. // Session.set("artist", currentSong.artist || "Artist");
  475. Session.set("duration", currentSong.duration);
  476. resizeSeekerbar();
  477. });
  478. } else {
  479. if (yt_player === undefined) {
  480. yt_player = new YT.Player("player", {
  481. height: 540,
  482. width: 960,
  483. videoId: currentSong.id,
  484. events: {
  485. 'onReady': function(event) {
  486. event.target.seekTo(getTimeElapsed() / 1000);
  487. event.target.playVideo();
  488. resizeSeekerbar();
  489. },
  490. 'onStateChange': function(event){
  491. if (event.data == YT.PlayerState.PAUSED) {
  492. event.target.seekTo(getTimeElapsed() / 1000);
  493. event.target.playVideo();
  494. }
  495. }
  496. }
  497. });
  498. } else {
  499. yt_player.loadVideoById(currentSong.id);
  500. }
  501. // Session.set("title", currentSong.title || "Title");
  502. // Session.set("artist", currentSong.artist || "Artist");
  503. getSongInfo(currentSong);
  504. //Session.set("duration", currentSong.duration);
  505. }
  506. }
  507. }
  508. Meteor.subscribe("history");
  509. Meteor.subscribe("playlists");
  510. Session.set("loaded", false);
  511. Meteor.subscribe("rooms", function() {
  512. var parts = location.href.split('/');
  513. var id = parts.pop();
  514. var type = id.toLowerCase();
  515. if (Rooms.find({type: type}).count() !== 1) {
  516. window.location = "/";
  517. } else {
  518. Session.set("loaded", true);
  519. Meteor.setInterval(function () {
  520. var data = undefined;
  521. var dataCursorH = History.find({type: type});
  522. var dataCursorP = Playlists.find({type: type});
  523. dataCursorH.forEach(function (doc) {
  524. if (data === undefined) {
  525. data = doc;
  526. }
  527. });
  528. if (data !== undefined && data.history.length > size) {
  529. //currentSong = data.history[data.history.length - 1];
  530. var songArray = Playlists.find({type: type}).fetch()[0].songs;
  531. var historyObj = data.history[data.history.length - 1];
  532. songArray.forEach(function(song) {
  533. if (song.id === historyObj.song.id) {
  534. currentSong = song;
  535. }
  536. });
  537. currentSong.started = historyObj.started;
  538. var songs = dataCursorP.fetch()[0].songs;
  539. songs.forEach(function(song, index) {
  540. if (currentSong.title === song.title) {
  541. if (index + 1 < songs.length) {
  542. nextSong = songs[index + 1];
  543. } else {
  544. nextSong = songs[0];
  545. }
  546. Session.set("title_next", nextSong.title);
  547. Session.set("artist_next", nextSong.artist);
  548. $("#song-img-next").attr("src", nextSong.img);
  549. if (index + 2 < songs.length) {
  550. afterSong = songs[index + 2];
  551. } else if (songs.length === index + 1 && songs.length > 1 ) {
  552. afterSong = songs[1];
  553. } else {
  554. afterSong = songs[0];
  555. }
  556. Session.set("title_after", afterSong.title);
  557. Session.set("artist_after", afterSong.artist);
  558. $("#song-img-after").attr("src",afterSong.img);
  559. }
  560. });
  561. size = data.history.length;
  562. startSong();
  563. }
  564. }, 1000);
  565. Meteor.setInterval(function () {
  566. resizeSeekerbar();
  567. }, 50);
  568. }
  569. });
  570. });
  571. }
  572. if (Meteor.isServer) {
  573. Meteor.startup(function() {
  574. reCAPTCHA.config({
  575. privatekey: '6LcVxg0TAAAAAI2fgIEEWHFxwNXeVIs8mzq5cfRM'
  576. });
  577. });
  578. Meteor.users.deny({update: function () { return true; }});
  579. Meteor.users.deny({insert: function () { return true; }});
  580. Meteor.users.deny({remove: function () { return true; }});
  581. function getSongDuration(query){
  582. var duration;
  583. var search = query;
  584. query = query.toLowerCase().split(" ").join("%20");
  585. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + query + '&type=track');
  586. for(var i in res.data){
  587. for(var j in res.data[i].items){
  588. if(search.indexOf(res.data[i].items[j].name) !== -1){
  589. duration = res.data[i].items[j].duration_ms / 1000;
  590. return duration;
  591. }
  592. }
  593. }
  594. }
  595. function getSongAlbumArt(query){
  596. var albumart;
  597. var search = query;
  598. query = query.toLowerCase().split(" ").join("%20");
  599. var res = Meteor.http.get('https://api.spotify.com/v1/search?q=' + query + '&type=track');
  600. for(var i in res.data){
  601. for(var j in res.data[i].items){
  602. if(search.indexOf(res.data[i].items[j].name) !== -1){
  603. albumart = res.data[i].items[j].album.images[1].url
  604. return albumart;
  605. }
  606. }
  607. }
  608. }
  609. //var room_types = ["edm", "nightcore"];
  610. var songsArr = [];
  611. function getSongsByType(type) {
  612. if (type === "edm") {
  613. return [
  614. {id: "aE2GCa-_nyU", title: "Radioactive - Lindsey Stirling and Pentatonix", duration: getSongDuration("Radioactive - Lindsey Stirling and Pentatonix"), artist: "Lindsey Stirling, Pentatonix", type: "youtube", img: "https://i.scdn.co/image/62167a9007cef2e8ef13ab1d93019312b9b03655"},
  615. {id: "aHjpOzsQ9YI", title: "Crystallize", artist: "Lindsey Stirling", duration: getSongDuration("Crystallize"), type: "youtube", img: "https://i.scdn.co/image/b0c1ccdd0cd7bcda741ccc1c3e036f4ed2e52312"}
  616. ];
  617. } else if (type === "nightcore") {
  618. return [{id: "f7RKOP87tt4", title: "Monster (DotEXE Remix)", duration: getSongDuration("Monster (DotEXE Remix)"), artist: "Meg & Dia", type: "youtube", img: "https://i.scdn.co/image/35ecdfba9c31a6c54ee4c73dcf1ad474c560cd00"}];
  619. } else {
  620. return [{id: "dQw4w9WgXcQ", title: "Never Gonna Give You Up", duration: getSongDuration("Never Gonna Give You Up"), artist: "Rick Astley", type: "youtube", img: "https://i.scdn.co/image/5246898e19195715e65e261899baba890a2c1ded"}];
  621. }
  622. }
  623. Rooms.find({}).fetch().forEach(function(room) {
  624. var type = room.type;
  625. if (Playlists.find({type: type}).count() === 0) {
  626. if (type === "edm") {
  627. Playlists.insert({type: type, songs: getSongsByType(type)});
  628. } else if (type === "nightcore") {
  629. Playlists.insert({type: type, songs: getSongsByType(type)});
  630. } else {
  631. Playlists.insert({type: type, songs: getSongsByType(type)});
  632. }
  633. }
  634. if (History.find({type: type}).count() === 0) {
  635. History.insert({type: type, history: []});
  636. }
  637. if (Playlists.find({type: type}).fetch()[0].songs.length === 0) {
  638. // Add a global video to Playlist so it can proceed
  639. } else {
  640. var startedAt = Date.now();
  641. var playlist = Playlists.find({type: type}).fetch()[0];
  642. var songs = playlist.songs;
  643. if (playlist.lastSong === undefined) {
  644. Playlists.update({type: type}, {$set: {lastSong: 0}});
  645. playlist = Playlists.find({type: type}).fetch()[0];
  646. songs = playlist.songs;
  647. }
  648. var currentSong = playlist.lastSong;
  649. addToHistory(songs[currentSong], startedAt);
  650. function addToHistory(song, startedAt) {
  651. History.update({type: type}, {$push: {history: {song: song, started: startedAt}}});
  652. }
  653. function skipSong() {
  654. songs = Playlists.find({type: type}).fetch()[0].songs;
  655. if (currentSong < (songs.length - 1)) {
  656. currentSong++;
  657. } else currentSong = 0;
  658. Playlists.update({type: type}, {$set: {lastSong: currentSong}});
  659. songTimer();
  660. addToHistory(songs[currentSong], startedAt);
  661. }
  662. function songTimer() {
  663. startedAt = Date.now();
  664. Meteor.setTimeout(function() {
  665. skipSong();
  666. }, songs[currentSong].duration * 1000);
  667. }
  668. songTimer();
  669. }
  670. });
  671. Accounts.onCreateUser(function(options, user) {
  672. var username;
  673. if (user.services) {
  674. if (user.services.github) {
  675. username = user.services.github.username;
  676. } else if (user.services.facebook) {
  677. //username = user.services.facebook.username;
  678. } else if (user.services.password) {
  679. username = user.username;
  680. }
  681. }
  682. user.profile = {username: username, rank: "default"};
  683. return user;
  684. });
  685. ServiceConfiguration.configurations.remove({
  686. service: "facebook"
  687. });
  688. ServiceConfiguration.configurations.insert({
  689. service: "facebook",
  690. appId: "1496014310695890",
  691. secret: "9a039f254a08a1488c08bb0737dbd2a6"
  692. });
  693. ServiceConfiguration.configurations.remove({
  694. service: "github"
  695. });
  696. ServiceConfiguration.configurations.insert({
  697. service: "github",
  698. clientId: "dcecd720f47c0e4001f7",
  699. secret: "375939d001ef1a0ca67c11dbf8fb9aeaa551e01b"
  700. });
  701. Meteor.publish("history", function() {
  702. return History.find({})
  703. });
  704. Meteor.publish("playlists", function() {
  705. return Playlists.find({})
  706. });
  707. Meteor.publish("rooms", function() {
  708. return Rooms.find({});
  709. });
  710. Meteor.publish("queues", function() {
  711. return Queues.find({});
  712. });
  713. Meteor.publish("chat", function() {
  714. return Chat.find({});
  715. });
  716. Meteor.publish("userProfiles", function() {
  717. //console.log(Meteor.users.find({}, {profile: 1, createdAt: 1, services: 0, username: 0, emails: 0})).fetch();
  718. return Meteor.users.find({}, {fields: {profile: 1, createdAt: 1}});
  719. });
  720. Meteor.publish("isAdmin", function() {
  721. return Meteor.users.find({_id: this.userId, "profile.rank": "admin"});
  722. });
  723. Meteor.methods({
  724. createUserMethod: function(formData, captchaData) {
  725. var verifyCaptchaResponse = reCAPTCHA.verifyCaptcha(this.connection.clientAddress, captchaData);
  726. if (!verifyCaptchaResponse.success) {
  727. console.log('reCAPTCHA check failed!', verifyCaptchaResponse);
  728. throw new Meteor.Error(422, 'reCAPTCHA Failed: ' + verifyCaptchaResponse.error);
  729. } else {
  730. console.log('reCAPTCHA verification passed!');
  731. Accounts.createUser({
  732. username: formData.username,
  733. email: formData.email,
  734. password: formData.password
  735. });
  736. }
  737. return true;
  738. },
  739. sendMessage: function(type, message) {
  740. if (Chat.find({type: type}).count() === 0) {
  741. Chat.insert({type: type, messages: []});
  742. }
  743. Chat.update({type: type}, {$push: {messages: {message: message, userid: "Kris"}}})
  744. },
  745. addSongToQueue: function(type, songData) {
  746. type = type.toLowerCase();
  747. if (Rooms.find({type: type}).count() === 1) {
  748. if (Queues.find({type: type}).count() === 0) {
  749. Queues.insert({type: type, songs: []});
  750. }
  751. if (songData !== undefined && Object.keys(songData).length === 5 && songData.type !== undefined && songData.title !== undefined && songData.title !== undefined && songData.artist !== undefined && songData.img !== undefined) {
  752. songData.duration = getSongDuration(songData.title);
  753. Queues.update({type: type}, {$push: {songs: {id: songData.id, title: songData.title, artist: songData.artist, duration: songData.duration, img: songData.img, type: songData.type}}});
  754. return true;
  755. } else {
  756. throw new Meteor.error(403, "Invalid data.");
  757. }
  758. } else {
  759. throw new Meteor.error(403, "Invalid genre.");
  760. }
  761. },
  762. removeSongFromQueue: function(type, songId) {
  763. type = type.toLowerCase();
  764. Queues.update({type: type}, {$pull: {songs: {id: songId}}});
  765. },
  766. addSongToPlaylist: function(type, songData) {
  767. type = type.toLowerCase();
  768. if (Rooms.find({type: type}).count() === 1) {
  769. if (Playlists.find({type: type}).count() === 0) {
  770. Playlists.insert({type: type, songs: []});
  771. }
  772. 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) {
  773. Playlists.update({type: type}, {$push: {songs: {id: songData.id, title: songData.title, artist: songData.artist, duration: songData.duration, img: songData.img, type: songData.type}}});
  774. Queues.update({type: type}, {$pull: {songs: {id: songData.id}}});
  775. return true;
  776. } else {
  777. throw new Meteor.error(403, "Invalid data.");
  778. }
  779. } else {
  780. throw new Meteor.error(403, "Invalid genre.");
  781. }
  782. },
  783. createRoom: function(type) {
  784. if (Rooms.find({type: type}).count() === 0) {
  785. Rooms.insert({type: type}, function(err) {
  786. if (err) {
  787. throw err;
  788. } else {
  789. if (Playlists.find({type: type}).count() === 1) {
  790. if (History.find({type: type}).count() === 0) {
  791. History.insert({type: type, history: []}, function(err3) {
  792. if (err3) {
  793. throw err3;
  794. } else {
  795. startStation();
  796. return true;
  797. }
  798. });
  799. } else {
  800. startStation();
  801. return true;
  802. }
  803. } else {
  804. Playlists.insert({type: type, songs: getSongsByType(type)}, function (err2) {
  805. if (err2) {
  806. throw err2;
  807. } else {
  808. if (History.find({type: type}).count() === 0) {
  809. History.insert({type: type, history: []}, function(err3) {
  810. if (err3) {
  811. throw err3;
  812. } else {
  813. startStation();
  814. return true;
  815. }
  816. });
  817. } else {
  818. startStation();
  819. return true;
  820. }
  821. }
  822. });
  823. }
  824. }
  825. });
  826. } else {
  827. throw "Room already exists";
  828. }
  829. function startStation() {
  830. var startedAt = Date.now();
  831. var songs = Playlists.find({type: type}).fetch()[0].songs;
  832. var currentSong = 0;
  833. addToHistory(songs[currentSong], startedAt);
  834. function addToHistory(song, startedAt) {
  835. History.update({type: type}, {$push: {history: {song: song, started: startedAt}}});
  836. }
  837. function skipSong() {
  838. songs = Playlists.find({type: type}).fetch()[0].songs;
  839. if (currentSong < (songs.length - 1)) {
  840. currentSong++;
  841. } else currentSong = 0;
  842. songTimer();
  843. addToHistory(songs[currentSong], startedAt);
  844. }
  845. function songTimer() {
  846. startedAt = Date.now();
  847. Meteor.setTimeout(function() {
  848. skipSong();
  849. }, songs[currentSong].duration * 1000);
  850. }
  851. songTimer();
  852. }
  853. }
  854. });
  855. }
  856. /*Router.waitOn(function() {
  857. Meteor.subscribe("isAdmin", Meteor.userId());
  858. });*/
  859. /*Router.onBeforeAction(function() {
  860. /*Meteor.autorun(function () {
  861. if (admin.ready()) {
  862. this.next();
  863. }
  864. });*/
  865. /*this.next();
  866. });*/
  867. Router.route("/", {
  868. template: "home"
  869. });
  870. Router.route("/terms", {
  871. template: "terms"
  872. });
  873. Router.route("/privacy", {
  874. template: "privacy"
  875. });
  876. Router.route("/admin", {
  877. waitOn: function() {
  878. return Meteor.subscribe("isAdmin", Meteor.userId());
  879. },
  880. action: function() {
  881. var user = Meteor.users.find({}).fetch();
  882. if (user[0] !== undefined && user[0].profile !== undefined && user[0].profile.rank === "admin") {
  883. this.render("admin");
  884. } else {
  885. this.redirect("/");
  886. }
  887. }
  888. });
  889. Router.route("/:type", {
  890. template: "room"
  891. });
  892. Router.route("/u/:user", {
  893. template: "profile"
  894. });