app.js 58 KB

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