summaryrefslogblamecommitdiff
path: root/bairadio.js
blob: 2e1eafe45f8f7bf1b4b6c990a3b157f68f4eb7ac (plain) (tree)





















































































































































































































































































































































                                                                                                                             
var radionum = 0;

function updateSelect() {
  var req = new XMLHttpRequest();
  var url = "https://bienvenidoainternet.org:8443";
  req.open("GET", url+"/status-json.xsl", true);
  req.send();
  req.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
      var resp = JSON.parse(req.response);
      resp = resp.icestats.source;
      
      var sel = document.getElementById("server_name");
      sel.innerHTML = "";
      if (resp.length > 1) {
        for (var i = -1; ++i < resp.length;) {
          var o = document.createElement("option");
          o.value = i;
          o.textContent = resp[i].server_name;
          if (resp[i].server_description) {
            o.textContent += ": " + resp[i].server_description;
          }
          if (i == radionum) { o.defaultSelected = true; }
          sel.appendChild(o);
        }
        resp = resp[radionum];
      } else {
        var o = document.createElement("option");
        o.value = 0;
        o.textContent = resp.server_name;
        if (resp.server_description) {
          o.textContent += ": " + resp.server_description;
        }
        sel.appendChild(o);
      }
    }
  }
}

function update(first) {
  var first = first || false;
  
  var req = new XMLHttpRequest();
  var url = "https://bienvenidoainternet.org:8443";
  req.open("GET", url+"/status-json.xsl", true);
  req.send();
  req.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
      if (first) { document.getElementById("status").textContent = ""; }

      var resp = JSON.parse(req.response);
      resp = resp.icestats.source;
      if (resp.length > 1) {
        resp = resp[radionum];
      }
      
      var audio = document.getElementById("stream");
      resp.listenurl = resp.listenurl.replace("http://bienvenidoainternet.org:8000", "https://bienvenidoainternet.org:8443");
      if (audio.src != resp.listenurl) {
        audio.src = resp.listenurl;
        if (!first) { playPause(); }
      }
      
      var current = document.getElementById("artist").textContent + document.getElementById("title").textContent;
      
      if (resp.artist) {
        resp.artist = resp.artist.trim();
        var artist = document.getElementById("artist");
        if (!artist.textContent.startsWith(resp.artist)) {
          artist.textContent = resp.artist + " - ";
        }
      } else {
        document.getElementById("artist").textContent = "";
      }

      if (resp.title) {
        resp.title = resp.title.trim();
        var title = document.getElementById("title");
        if (title.textContent != resp.title) {
          if (title.textContent != "" && title.textContent != resp.title) {
            var history = document.getElementById("history");
            history.innerHTML += '<div class="pastsong">' + current + '</div>';
            history.scrollTop = history.scrollHeight;
          }
          
          title.textContent = resp.title;
          document.title = resp.title + ((resp.artist) ? (" - "+resp.artist) : "") + " @ Radio B.a.I.";
          
          checkLong();
        }
      } else {
        document.getElementById("title").textContent = "(Sin título)";
        document.title = "(Sin título) @ Radio B.a.I.";
      }
      
      if (resp.listeners) {
        var listeners = document.getElementById("listeners");
        if (listeners.textContent != resp.listeners) {
          listeners.textContent = resp.listeners;
        }
      }
      
      if (resp["ice-bitrate"]) {
        var bitrate = document.getElementById("bitrate");
        if (bitrate.textContent != resp["ice-bitrate"]) {
          bitrate.textContent = resp["ice-bitrate"];
        }
      }
      
      if (resp.audio_samplerate) {
        var audio_samplerate = document.getElementById("audio_samplerate");
        audio_samplerate.textContent = Math.round(resp.audio_samplerate / 1000);
      }
    }
  }
}

function startVisualization() {
  var ctx = new AudioContext();  
  var audio = document.getElementById("stream");
  var src = ctx.createMediaElementSource(audio);
  var anal = ctx.createAnalyser();
  src.connect(anal);
  src.connect(ctx.destination);
  var freq = new Uint8Array(anal.frequencyBinCount);
  
  function renderVis() {
    requestAnimationFrame(renderVis);
    anal.getByteFrequencyData(freq);
    
    var vis = document.getElementById("vis");
    vis.innerHTML = "";
    var div = 3;
    
    for (var i = 0; i < 900; i += 20) {
      var h = (freq[i] / div);
      vis.innerHTML += '<rect class="bar"' +
        'height="' + h + '" ' +
        'width="1"' +
        'x="' + (i / 10) + '" ' +
        'y="' + ((255 / div) - h) + '" />';
    }
  }
  
  renderVis();
}

function checkLong() {
  var strip = document.getElementById("nowplaying-txt");
  
  var marquee = document.getElementById("marqueeStyle");
  if (marquee) marquee.parentElement.removeChild(marquee);
  
  if (strip.clientWidth > 480) { // #nowplaying width = 480px
    var travel = strip.clientWidth - 475;
    var style = document.createElement("style");
    style.id = "marqueeStyle";
    style.textContent = "#nowplaying-txt {animation: marquee " + Math.round(travel/10) + "s linear infinite;}";
    style.textContent += "@keyframes marquee {";
    style.textContent += "10% { transform: translateX(0); }";
    style.textContent += "45% { transform: translateX(-" + travel + "px); }";
    style.textContent += "55% { transform: translateX(-" + travel + "px); }";
    style.textContent += "90% { transform: translateX(0); }";
    style.textContent += "}";
    document.getElementsByTagName("head")[0].appendChild(style);
  }
}

function playPause() {
  var radio = document.getElementById("stream");
  var vis = document.getElementById("vis");
  if (radio.paused) {
    radio.play();
    vis.removeAttribute("class")
  } else {
    vis.setAttribute("class", "show-play-btn");
    radio.pause();
  }
}

function changeVolume(e) {
  var mousepos = e.x;
  document.addEventListener("mousemove", setVolume);
  document.addEventListener("mouseup", function() {
    document.removeEventListener("mousemove", setVolume);
  });
  
  function setVolume(e) {
    var audio = document.getElementById("stream");
    var dx = mousepos - e.x;
    mousepos = e.x;

    var vol = document.getElementById("volume");
    var newvol = Math.round(parseInt(vol.textContent) + (dx * -1));
    if (newvol < 0) { newvol = 0; }
    else if (newvol > 100) { newvol = 100; }
    
    vol.textContent = (newvol < 10) ? ("0" + newvol) : newvol;
    audio.volume = newvol / 100;
    
    removeSel();
  }
}

function collapseHistory() {
  var box = document.getElementById("box-history");
  
  if (box.className == "outer") {
    box.classList.add("collapse");
  } else {
    box.classList.remove("collapse");
  }
  
  removeSel();
}

function resizeChat(e) {
  var mousepos = e.y;
  document.addEventListener("mousemove", calcResize);
  document.addEventListener("mouseup", function() {
    document.removeEventListener("mousemove", calcResize);
  });
  
  function calcResize(e) {
    var chat = document.getElementById("chat-all");
    var dx = mousepos - e.y;
    mousepos = e.y;
    chat.style.height = (parseInt(getComputedStyle(chat, "").height) - dx) + "px";
    chat.scrollTop = chat.scrollHeight;
    removeSel();
  }
}

function removeSel() {
  if (document.selection) { document.selection.empty(); }
  else { window.getSelection().removeAllRanges(); }
}

var chatConnected = false;
var antiFlood = false;
const chatMaxChar = 80;
const chatFloodTime = 1100;

function connect() {
  sock = new WebSocket("wss://tv.bienvenidoainternet.org/daemon/");
  sock.addEventListener("open", function(e) {
    addMsg("Conectado al chat.");
    chatConnected = true;
    enableChat();
  });
  sock.addEventListener("message", function(e) {
    interpretNewMsg(e.data);
  });
  sock.addEventListener("close", function(e) {
    addMsg("Desconectado del chat. " + (e.reason ? "Razón: "+e.reason : "Código: "+e.code));
    document.getElementById("chat-count").textContent = "";
    chatConnected = false;
  });
  
  document.getElementById("msg_send").addEventListener("click", checkSend);
}

function enableChat() {
  antiFlood = false;
  document.getElementById("msg_send").disabled = false;
}

function interpretNewMsg(info) {
  console.log("<<< " + info);
  var arg = info.split(":");
  
  if (arg[0] == "MSG") {
    var msg = unescapeColon(arg[2]);
    addMsg(msg);
  } else if (arg[0] == "COUNT") {
    document.getElementById("chat-count").textContent = " (Usuarios: " + arg[1] + ")";
  }
}

function checkSend(e) {
  e.preventDefault();
  if (!chatConnected) return;
  if (antiFlood) return;
  
  var msgField = document.getElementById("msg_type");
  var msg = msgField.value.trim().substr(0, chatMaxChar);
  if (!msg) return;
  
  if (chatConnected) {
    sendMsg("MSG:0:" + escapeColon(msg));
    addMsg(msg);
  } else return;
  
  msgField.value = "";
  antiFlood = true;
  document.getElementById("msg_send").disabled = true;
  setTimeout(enableChat, chatFloodTime);
}

function escapeColon(msg) {
  return msg ? msg.replace(/:/g, "%3A") : "";
}
function unescapeColon(msg) {
  return msg ? msg.replace(/%3A/g, ":") : "";
}

function sendMsg(msg) {
  console.log(">>> " + msg);
  sock.send(msg);
}

function addMsg(msg) {
  var chat = document.getElementById("chat-all");
  
  var line = document.createElement("div");
  line.className = "msg";
  var presentTime = new Date();
  var hh = presentTime.getHours();
  hh = (hh < 10) ? ("0" + hh) : hh;
  var mm = presentTime.getMinutes();
  mm = (mm < 10) ? ("0" + mm) : mm;
  line.textContent = "[" + hh + ":" + mm + "] ";
  line.textContent += msg;

  chat.appendChild(line);
  chat.scrollTop = chat.scrollHeight;
}

document.addEventListener("DOMContentLoaded", function() {
  document.getElementById("vis").addEventListener("click", playPause);
  document.getElementById("volume").addEventListener("mousedown", changeVolume);
  document.getElementById("server_name").addEventListener("change", function(e) { radionum = this.value; });
  document.getElementById("box-history-title").addEventListener("dblclick", collapseHistory);
  document.getElementById("resize").addEventListener("mousedown", resizeChat);

  update(true);
  updateSelect();
  startVisualization();
  setInterval(update, 1000);
  setInterval(updateSelect, 10000);
  connect();
});