<commit_before>function isInArray(value, array) {
  return array.indexOf(value) > -1;
}

function sleep(time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

function updatePage(title, header, buttons) {
  document.title = title + " | PS4 Exploit Host by Al-Azif";
  document.getElementById("title").innerHTML = title;
  document.getElementById("header").innerHTML = header;
  document.getElementById("buttons").innerHTML = buttons;
}

function resetPage() {
  history.pushState("", document.title, window.location.pathname + window.location.search);
  updatePage("Firmware Selection", "Firmware", firmwares);
}

function getFirmwares() {
  var firmwareSpoofs = {
    "5.51": "4.55",
    "5.07": "5.05"
  };
  var ua = navigator.userAgent;
  var currentFirmware = ua.substring(ua.indexOf("5.0 (") + 19, ua.indexOf(") Apple"));
  if (firmwareSpoofs.hasOwnProperty(currentFirmware)) {
    currentFirmware = firmwareSpoofs[currentFirmware];
  }
  var firmwares = "";
  x = 0;
  if (data["firmwares"].length == 1 && data["firmwares"][0] != "No Exploits Found" && data["firmwares"][0] != "I/O Error on Host") {
    window.location.hash = data["firmwares"][0];
  }
  for (var i = 0, len = data["firmwares"].length; i < len; i++) {
    if (data[data["firmwares"][i]].length > 1) {
      x += 1;
      if (currentFirmware == data["firmwares"][i]) {
        if(navigator.onLine) {
          firmwares += "<button class=\"btn btn-main\" onclick=\"window.location.hash = '" + data["firmwares"][i].replace(/ /g, "%20") + "'\">" + data["firmwares"][i] + "</button>
<button class=\"btn btn-dropdown\">
▼
</button>
Cache

";
        } else {
          firmwares += "<button class=\"btn btn-main btn-full\" onclick=\"window.location.hash = '" + data["firmwares"][i].replace(/ /g, "%20") + "'\">" + data["firmwares"][i] + "</button>";
        }
      } else {
        if(navigator.onLine) {
          firmwares += "<button class=\"btn btn-disabled\" onclick=\"window.location.hash = '" + data["firmwares"][i].replace(/ /g, "%20") + "'\">" + data["firmwares"][i] + "</button>
<button class=\"btn btn-dropdown-disabled\">
▼
</button>
Cache

";
        } else {
          firmwares += "<button class=\"btn btn-disabled btn-full\" onclick=\"window.location.hash = '" + data["firmwares"][i].replace(/ /g, "%20") + "'\">" + data["firmwares"][i] + "</button>";
        }
      }
      if (x >= 3) {
        firmwares += "
";
        x = 0;
      }
    }
  }
  return firmwares;
}

function getExploits() {
  var hash = window.location.hash.substr(1).replace(/\%20/g, " ");
  var exploits = "";
  x = 0;
  for (var i = 0, len = data[hash].length; i < len; i++) {
    x += 1;
    if (data[hash][i] == "[Back]") {
      exploits += "<button class=\"btn btn-main btn-full\" onclick=\"window.location.hash = 'back'\">[Back]</button>";
    }  else {
      if (navigator.onLine) {
        exploits += "<button class=\"btn btn-main\" onClick=\"loadExploit('" + hash + "', '" + data[hash][i] + "');\">" + data[hash][i] + "</button>
<button class=\"btn btn-dropdown\">
▼
</button>
CacheAutoloadAbout

";
      } else {
        exploits += "<button class=\"btn btn-main\" onClick=\"loadExploit('" + hash + "', '" + data[hash][i] + "');\">" + data[hash][i] + "</button>
<button class=\"btn btn-dropdown\">
▼
</button>
AutoloadAbout

";
      }
    }
    if (x >= 3) {
      exploits += "
";
      x = 0;
    }
  }
  return exploits;
}

function cacheFirmware(firmware) {
  document.getElementById("ifr").setAttribute("src", "/cache/firmware/" + firmware + "/index.html");
}

function cacheExploit(firmware, exploit) {
  document.getElementById("ifr").setAttribute("src", "/cache/exploit/" + firmware + "/" + exploit + "/index.html");
}

function getExploitInfo(firmware, exploit) {
  var modal = document.getElementById("infoModal");
  var closer = document.getElementsByClassName("close")[0];

  closer.onclick = function() {
    modal.style.display = "none";
  };

  window.onclick = function(event) {
    if (event.target == modal) {
      modal.style.display = "none";
    }
  };

  var url = "/exploits/" + firmware + "/" + exploit + "/meta.json";
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, false);
  xhr.send(null);

  if (xhr.status === 200) {
    var metadata = JSON.parse(xhr.responseText);
    document.getElementById("modalTitle").innerHTML = metadata["Name"] + " Metadata";
    var description = metadata["Description"]["default"];
    if (metadata["Description"][lang] !== null) {
      description = metadata["Description"][lang];
    }
    document.getElementsByClassName("modalBody")[0].innerHTML = "

Version:

" + metadata["Version"] + "

Device:

" + metadata["Device"] + "

Firmware:

" + metadata["Firmware"] + "

Description:

" + description + "

URL:

" + metadata["URL"] + "

";
    modal.style.display = "block";
  } else {
    alert("Error retrieving metadata!");
  }
}

function loadExploit(firmware, exploit) {
  // iFrame Method
  // showLoader();
  // document.getElementById("ifr").setAttribute("src", "/exploits/" + firmware + "/" + exploit +"/index.html");

  // Redirect Method
  window.location.replace("/exploits/" + firmware + "/" + exploit +"/index.html");
}

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(";");
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == " ") {
      c = c.substring(1);
    }
    if (c.indexOf(name) === 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function setAutoload(firmware, exploit) {
  document.cookie = "autoload=/exploits/" + firmware + "/" + exploit + "/index.html;";

  // iFrame Method
  //showLoader();
  //document.getElementById("ifr").setAttribute("src", exploit);

  //Redirect Method
  window.location.replace("/exploits/" + firmware + "/" + exploit +"/index.html");
}

function firmwareSelected() {
  var hash = window.location.hash.substr(1);
  if (!isInArray(hash, firmwares)) {
    resetPage();
  } else {
    updatePage("Exploit Selection", hash.replace(/\%20/g, " "), getExploits());
  }
}

function clearFrame() {
  document.getElementById("ifr").setAttribute("src", "");
}

function clearOverlays() {
  document.getElementById("cacheOverlay").style.display = "none";
  document.getElementById("barText").style.display = "none";
  document.getElementById("barBack").style.display = "none";
  document.getElementById("barLoad").style.display = "none";
  document.getElementById("exploitOverlay").style.display = "none";
  document.getElementById("exploitMessage").innerHTML = "";
  document.getElementById("exploitMessage").style.display = "none";
  document.getElementById("exploitLoader").style.display = "none";
}

function showCaching() {
  document.getElementById("cacheOverlay").style.display = "block";
  document.getElementById("barText").style.display = "block";
  document.getElementById("barBack").style.display = "block";
  document.getElementById("barLoad").style.display = "block";
}

function showLoader() {
  document.getElementById("exploitMessage").innerHTML = "";
  document.getElementById("exploitOverlay").style.display = "block";
  document.getElementById("exploitLoader").style.display = "block";
  document.getElementById("exploitMessage").style.display = "block";
}

function ondownloading() {
  showCaching();
}

function onprogress(percent) {
  document.getElementById("barLoad").style.width = percent + "%";
  document.getElementById("barLoad").innerHTML = percent + "%";
}

function oncached() {
  clearFrame();
  clearOverlays();
  alert("Application cached successfully!");
}

function onupdateready() {
  clearFrame();
  clearOverlays();
  alert("Cache updated! Press Ok to reload the page.");
}

function onnoupdate() {
  clearFrame();
  clearOverlays();
  alert("No update available");
}

function onerror() {
  clearFrame();
  clearOverlays();
  alert("Error caching resources!");
}

function onobsolete() {
  clearFrame();
  clearOverlays();
  alert("Manifest returned a 404, cache was deleted");
}

function hideLoader(message, wait) {
  document.getElementById("exploitLoader").style.display = "none";
  document.getElementById("exploitMessage").innerHTML = message;
  sleep(wait).then(() => {
    if (document.getElementById("exploitMessage").innerHTML == "Success") {
      document.getElementById("forceRefresh").value = 1;
      window.location.reload();
    } else if (document.getElementById("exploitMessage").innerHTML == "Waiting..." || document.getElementById("exploitMessage").innerHTML == "Awaiting payload...") {
      // Just sit here
    } else {
      clearFrame();
      clearOverlays();
    }
  });
}

function autoloadCookie() {
  if (getCookie("autoload")) {
    var autoload = getCookie("autoload");
    try {
      if (!isInArray(autoload.split("/")[3], data[autoload.split("/")[2]])) {
        document.cookie = "autoload=;";
        alert("The exploit being autoloaded no longer exists! Cookie cleared");
      } else {
        // iFrame Method
        // showLoader();
        // document.getElementById("ifr").setAttribute("src", autoload);

        // Redirect Method
        window.location.replace(autoload);
      }
    } catch(e) {
      document.cookie = "autoload=;";
      alert("The exploit being autoloaded no longer exists! Cookie cleared");
    }
  }
}

function checkForceRefresh() {
  if (document.getElementById("forceRefresh").value == 1) {
    window.location.replace("./");
  }
}

function bootstrap(input) {
  data = input;
  if (data["Lang_Code"] !== undefined) {
    lang = data["Lang_Code"];
  } else if (localStorage.getItem("language") === null) {
    localStorage.setItem("language", "en");
    lang = "en";
  } else {
    lang = localStorage.getItem("language");
  }
  firmwares = getFirmwares();

  window.onload = function () {
    if (window.location.hash) {
      firmwareSelected();
    } else {
      resetPage();
    }
  };

  window.document.addEventListener("keyup", function (event) {
    if (event.keyCode === 27) {
      if (window.getComputedStyle(document.getElementById("infoModal")).getPropertyValue("display") == "block") {
        document.getElementById("infoModal").style.display = "none";
      } else if (window.getComputedStyle(document.getElementById("exploitOverlay")).getPropertyValue("display") == "none" && document.getElementById("title").innerHTML != "Firmware Selection") {
        window.location.hash = "back";
      }
      clearFrame();
      clearOverlays();
    }
  });

  window.applicationCache.onupdateready = function (n) {
    window.location.reload(true);
  };
}
/*
Copyright (c) 2017-2018 Al Azif, https://github.com/Al-Azif/ps4-exploit-host

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
<commit_msg>Check scope<commit_after>function isInArray(value, array) {
  return array.indexOf(value) > -1;
}

function sleep(time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

function updatePage(title, header, buttons) {
  document.title = title + " | PS4 Exploit Host by Al-Azif";
  document.getElementById("title").innerHTML = title;
  document.getElementById("header").innerHTML = header;
  document.getElementById("buttons").innerHTML = buttons;
}

function resetPage() {
  history.pushState("", document.title, window.location.pathname + window.location.search);
  updatePage("Firmware Selection", "Firmware", firmwares);
}

function getFirmwares() {
  var firmwareSpoofs = {
    "5.51": "4.55",
    "5.07": "5.05"
  };
  var ua = navigator.userAgent;
  var currentFirmware = ua.substring(ua.indexOf("5.0 (") + 19, ua.indexOf(") Apple"));
  if (firmwareSpoofs.hasOwnProperty(currentFirmware)) {
    currentFirmware = firmwareSpoofs[currentFirmware];
  }
  var firmwares = "";
  var x = 0;
  if (data["firmwares"].length == 1 && data["firmwares"][0] != "No Exploits Found" && data["firmwares"][0] != "I/O Error on Host") {
    window.location.hash = data["firmwares"][0];
  }
  for (var i = 0, len = data["firmwares"].length; i < len; i++) {
    if (data[data["firmwares"][i]].length > 1) {
      x += 1;
      if (currentFirmware == data["firmwares"][i]) {
        if(navigator.onLine) {
          firmwares += "<button class=\"btn btn-main\" onclick=\"window.location.hash = '" + data["firmwares"][i].replace(/ /g, "%20") + "'\">" + data["firmwares"][i] + "</button>
<button class=\"btn btn-dropdown\">
▼
</button>
Cache

";
        } else {
          firmwares += "<button class=\"btn btn-main btn-full\" onclick=\"window.location.hash = '" + data["firmwares"][i].replace(/ /g, "%20") + "'\">" + data["firmwares"][i] + "</button>";
        }
      } else {
        if(navigator.onLine) {
          firmwares += "<button class=\"btn btn-disabled\" onclick=\"window.location.hash = '" + data["firmwares"][i].replace(/ /g, "%20") + "'\">" + data["firmwares"][i] + "</button>
<button class=\"btn btn-dropdown-disabled\">
▼
</button>
Cache

";
        } else {
          firmwares += "<button class=\"btn btn-disabled btn-full\" onclick=\"window.location.hash = '" + data["firmwares"][i].replace(/ /g, "%20") + "'\">" + data["firmwares"][i] + "</button>";
        }
      }
      if (x >= 3) {
        firmwares += "
";
        x = 0;
      }
    }
  }
  return firmwares;
}

function getExploits() {
  var hash = window.location.hash.substr(1).replace(/\%20/g, " ");
  var exploits = "";
  var x = 0;
  for (var i = 0, len = data[hash].length; i < len; i++) {
    x += 1;
    if (data[hash][i] == "[Back]") {
      exploits += "<button class=\"btn btn-main btn-full\" onclick=\"window.location.hash = 'back'\">[Back]</button>";
    }  else {
      if (navigator.onLine) {
        exploits += "<button class=\"btn btn-main\" onClick=\"loadExploit('" + hash + "', '" + data[hash][i] + "');\">" + data[hash][i] + "</button>
<button class=\"btn btn-dropdown\">
▼
</button>
CacheAutoloadAbout

";
      } else {
        exploits += "<button class=\"btn btn-main\" onClick=\"loadExploit('" + hash + "', '" + data[hash][i] + "');\">" + data[hash][i] + "</button>
<button class=\"btn btn-dropdown\">
▼
</button>
AutoloadAbout

";
      }
    }
    if (x >= 3) {
      exploits += "
";
      x = 0;
    }
  }
  return exploits;
}

function cacheFirmware(firmware) {
  document.getElementById("ifr").setAttribute("src", "/cache/firmware/" + firmware + "/index.html");
}

function cacheExploit(firmware, exploit) {
  document.getElementById("ifr").setAttribute("src", "/cache/exploit/" + firmware + "/" + exploit + "/index.html");
}

function getExploitInfo(firmware, exploit) {
  var modal = document.getElementById("infoModal");
  var closer = document.getElementsByClassName("close")[0];

  closer.onclick = function() {
    modal.style.display = "none";
  };

  window.onclick = function(event) {
    if (event.target == modal) {
      modal.style.display = "none";
    }
  };

  var url = "/exploits/" + firmware + "/" + exploit + "/meta.json";
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, false);
  xhr.send(null);

  if (xhr.status === 200) {
    var metadata = JSON.parse(xhr.responseText);
    document.getElementById("modalTitle").innerHTML = metadata["Name"] + " Metadata";
    var description = metadata["Description"]["default"];
    if (metadata["Description"][lang] !== null) {
      description = metadata["Description"][lang];
    }
    document.getElementsByClassName("modalBody")[0].innerHTML = "

Version:

" + metadata["Version"] + "

Device:

" + metadata["Device"] + "

Firmware:

" + metadata["Firmware"] + "

Description:

" + description + "

URL:

" + metadata["URL"] + "

";
    modal.style.display = "block";
  } else {
    alert("Error retrieving metadata!");
  }
}

function loadExploit(firmware, exploit) {
  // iFrame Method
  // showLoader();
  // document.getElementById("ifr").setAttribute("src", "/exploits/" + firmware + "/" + exploit +"/index.html");

  // Redirect Method
  window.location.replace("/exploits/" + firmware + "/" + exploit +"/index.html");
}

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(";");
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == " ") {
      c = c.substring(1);
    }
    if (c.indexOf(name) === 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function setAutoload(firmware, exploit) {
  document.cookie = "autoload=/exploits/" + firmware + "/" + exploit + "/index.html;";

  // iFrame Method
  //showLoader();
  //document.getElementById("ifr").setAttribute("src", exploit);

  //Redirect Method
  window.location.replace("/exploits/" + firmware + "/" + exploit +"/index.html");
}

function firmwareSelected() {
  var hash = window.location.hash.substr(1);
  if (!isInArray(hash, firmwares)) {
    resetPage();
  } else {
    updatePage("Exploit Selection", hash.replace(/\%20/g, " "), getExploits());
  }
}

function clearFrame() {
  document.getElementById("ifr").setAttribute("src", "");
}

function clearOverlays() {
  document.getElementById("cacheOverlay").style.display = "none";
  document.getElementById("barText").style.display = "none";
  document.getElementById("barBack").style.display = "none";
  document.getElementById("barLoad").style.display = "none";
  document.getElementById("exploitOverlay").style.display = "none";
  document.getElementById("exploitMessage").innerHTML = "";
  document.getElementById("exploitMessage").style.display = "none";
  document.getElementById("exploitLoader").style.display = "none";
}

function showCaching() {
  document.getElementById("cacheOverlay").style.display = "block";
  document.getElementById("barText").style.display = "block";
  document.getElementById("barBack").style.display = "block";
  document.getElementById("barLoad").style.display = "block";
}

function showLoader() {
  document.getElementById("exploitMessage").innerHTML = "";
  document.getElementById("exploitOverlay").style.display = "block";
  document.getElementById("exploitLoader").style.display = "block";
  document.getElementById("exploitMessage").style.display = "block";
}

function ondownloading() {
  showCaching();
}

function onprogress(percent) {
  document.getElementById("barLoad").style.width = percent + "%";
  document.getElementById("barLoad").innerHTML = percent + "%";
}

function oncached() {
  clearFrame();
  clearOverlays();
  alert("Application cached successfully!");
}

function onupdateready() {
  clearFrame();
  clearOverlays();
  alert("Cache updated! Press Ok to reload the page.");
}

function onnoupdate() {
  clearFrame();
  clearOverlays();
  alert("No update available");
}

function onerror() {
  clearFrame();
  clearOverlays();
  alert("Error caching resources!");
}

function onobsolete() {
  clearFrame();
  clearOverlays();
  alert("Manifest returned a 404, cache was deleted");
}

function hideLoader(message, wait) {
  document.getElementById("exploitLoader").style.display = "none";
  document.getElementById("exploitMessage").innerHTML = message;
  sleep(wait).then(() => {
    if (document.getElementById("exploitMessage").innerHTML == "Success") {
      document.getElementById("forceRefresh").value = 1;
      window.location.reload();
    } else if (document.getElementById("exploitMessage").innerHTML == "Waiting..." || document.getElementById("exploitMessage").innerHTML == "Awaiting payload...") {
      // Just sit here
    } else {
      clearFrame();
      clearOverlays();
    }
  });
}

function autoloadCookie() {
  if (getCookie("autoload")) {
    var autoload = getCookie("autoload");
    try {
      if (!isInArray(autoload.split("/")[3], data[autoload.split("/")[2]])) {
        document.cookie = "autoload=;";
        alert("The exploit being autoloaded no longer exists! Cookie cleared");
      } else {
        // iFrame Method
        // showLoader();
        // document.getElementById("ifr").setAttribute("src", autoload);

        // Redirect Method
        window.location.replace(autoload);
      }
    } catch(e) {
      document.cookie = "autoload=;";
      alert("The exploit being autoloaded no longer exists! Cookie cleared");
    }
  }
}

function checkForceRefresh() {
  if (document.getElementById("forceRefresh").value == 1) {
    window.location.replace("./");
  }
}

function bootstrap(input) {
  data = input;
  if (data["Lang_Code"] !== undefined) {
    lang = data["Lang_Code"];
  } else if (localStorage.getItem("language") === null) {
    localStorage.setItem("language", "en");
    lang = "en";
  } else {
    lang = localStorage.getItem("language");
  }
  firmwares = getFirmwares();

  window.onload = function () {
    if (window.location.hash) {
      firmwareSelected();
    } else {
      resetPage();
    }
  };

  window.document.addEventListener("keyup", function (event) {
    if (event.keyCode === 27) {
      if (window.getComputedStyle(document.getElementById("infoModal")).getPropertyValue("display") == "block") {
        document.getElementById("infoModal").style.display = "none";
      } else if (window.getComputedStyle(document.getElementById("exploitOverlay")).getPropertyValue("display") == "none" && document.getElementById("title").innerHTML != "Firmware Selection") {
        window.location.hash = "back";
      }
      clearFrame();
      clearOverlays();
    }
  });

  window.applicationCache.onupdateready = function (n) {
    window.location.reload(true);
  };
}
/*
Copyright (c) 2017-2018 Al Azif, https://github.com/Al-Azif/ps4-exploit-host

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
<|endoftext|>


<commit_before>'use strict';

let fs = require('fs');
let path = require('path');
let fse = require('fs-extra');
let shell = require('shelljs');
let colors = require('colors');
let inline = require('inline-source').sync;
let inquirer = require('inquirer');

const port = 8080;
const sourcePath = path.join(__dirname, '../src');
const outputPath = path.join(__dirname, '../dist');

let cmd;

let start = () => {
    let task = process.argv[2].substring(1);
    if (task == 'dev') {
        cmd = `webpack-dev-server --inline --quiet --devtool eval --progress --colors --content-base ./src/ --hot --config ./webpack/webpack.dev.js --host 0.0.0.0 --port ${ port }`;
        step3().then(step4).catch(( err ) => {
            if (/listen EADDRINUSE/.test(err.toString())) {
                step6().then(step7).then(step8).catch(( err ) => {
                    console.log(err.toString().red);
                }).then(start);
            } else {
                console.log(err.toString().red);
            }
        });
    }
    if (task == 'build') {
        cmd = 'webpack --progress --colors --config ./webpack/webpack.build.js';
        if (process.argv[3] && process.argv[3] == 'js') {
            step3().then(step9).then(step10).then(( option ) => cmd += option).then(step1).then(step4).then(() => {
                console.log('build complete!'.green);
            }).catch((err) => {
                console.log(err.toString().red);
            });
        } else {
            step1().then(step2).then(step3).then(step4).then(step5).then(() => {
                console.log('build complete!'.green);
            }).catch(( err ) => {
                console.log(err.toString().red);
            });
        }
    }
};

/**
 * [step1] fse.remove -- Remove old files
 * @return {Promise} remove_success
 */
let step1 = () => new Promise(( resolve, reject ) => {
    fse.remove(path.join(outputPath, '*'), ( err ) => {
        if (err) {
            reject(err);
            return;
        }
        resolve();
    });
});

/**
 * [step2] fse.copySync -- Copy files like `html` or `images`
 * @return {Promise} copy_success
 */
let step2 = () => new Promise(( resolve, reject ) => {
    fs.readdir(sourcePath, ( err, files ) => {
        if (err) {
            reject(err);
            return;
        }
        files.forEach(( filename ) => {
            let file = path.join(sourcePath, filename);
            if (filename[0] === '.') {
                return;
            }
            if (fs.statSync(file).isDirectory() && filename == 'entry') {
                return;
            }
            fse.copySync(file, path.join(outputPath, filename));
        });
        resolve();
    });
});

/**
 * [step3] fse.outputJson -- Create `webpack.entry.json` dynamically
 * @return {Promise} create_entry_success
 */
let step3 = () => new Promise(( resolve, reject ) => {
    let entry = {};
    let entryPath = path.join(sourcePath, 'entry');
    fs.readdir(entryPath, ( err, files ) => {
        if (err) {
            reject(err);
            return;
        }
        files.forEach(( filename ) => {
            let file = path.join(entryPath, filename);
            if (fs.statSync(file).isFile() && path.extname(file) == '.js') {
                entry[path.basename(filename, '.js')] = file;
            }
        });
        fse.outputJson(path.join(__dirname, 'webpack.entry.json'), entry, ( err ) => {
            if (err) {
                reject(err);
                return;
            }
            resolve(entry);
        });
    });
});

/**
 * [step4] shell.exec -- Run webpack
 * @return {Promise} run_webpack_success
 */
let step4 = () => new Promise(( resolve, reject ) => {
    let result = shell.exec(cmd);
    if (result.code === 0) {
        resolve();
    } else {
        reject(result.stderr);
    }
});

/**
 * [step5] inline -- According to `inline` attribute and replace the code of file
 * @return {Promise} inline_success
 */
let step5 = () => new Promise(( resolve, reject ) => {
    fs.readdir(outputPath, ( err, files ) => {
        if (err) {
            reject(err);
            return;
        };
        files.forEach(( filename ) => {
            let file = path.join(outputPath, filename);
            if (fs.statSync(file).isFile() && path.extname(file) == '.html') {
                let html = inline(file, {
                    compress : false,
                    rootpath : path.resolve('dist'),
                    handlers ( source, context ) {
                        if (source && source.fileContent && !source.content) {
                            if (source.extension == 'css') {
                                source.tag = 'style';
                                source.content = source.fileContent.replace(/url\(.*?\)/g, function ( match ) {
                                    let url = match.substring(0, match.length - 1).substring(4);
                                    if (/^http(s?):\/\/|data:image/.test(url)) {
                                        return match;
                                    } else {
                                        if (url.indexOf('?')) {
                                            url = url.split('?')[0];
                                        }
                                        return `url(${ path.join('dist', url) })`;
                                    }
                                });
                            }
                            if (source.extension == 'js') {
                                source.content = source.fileContent.trim();
                            }
                        }
                    },
                });
                fs.writeFileSync(file, html);
            }
        });
        resolve();
    });
});

/**
 * [step6] shell.exec -- List open files
 * @return {Promise} list_files_success
 */
let step6 = () => new Promise(( resolve, reject ) => {
    console.log(`\n${ port } is aleary in use. Ctrl+C to leave or input a PID to kill：`.green);
    let result = shell.exec(`lsof -i tcp:${ port }`);
    if (result.code === 0) {
        resolve();
    } else {
        reject(result.stderr);
    }
});

/**
 * [step7] inquirer.prompt -- Get PID
 * @return {Promise} get_pid_success
 */
let step7 = () => new Promise(( resolve, reject ) => {
    inquirer.prompt([{
        type : 'input',
        name : 'pid',
        message : 'PID:',
    }]).then(( answers ) => {
        resolve(answers.pid);
    }).catch(( err ) => {
        reject(err);
    });
});

/**
 * [step8] shell.exec -- Kill PID
 * @return {Promise} kill_pid_success
 */
let step8 = ( pid ) => new Promise(( resolve, reject ) => {
    let result = shell.exec(`kill ${ pid }`);
    if (result.code === 0) {
        resolve();
    } else {
        reject(result.stderr);
    }
});

/**
 * [step9] inquirer.prompt -- Get js file
 * @return {Promise} get_js_success
 */
let step9 = ( entry ) => new Promise(( resolve, reject ) => {
    let choices = Object.keys(entry);
    if (choices.length) {
        choices.forEach(( file, index ) => {
            choices[index] = file + '.js';
        });
        inquirer.prompt([{
            type : 'list',
            name : 'file',
            message : 'Select a file to pack:',
            choices,
        }]).then(( answers ) => {
            let file = path.basename(answers.file, '.js');
            let js = {};
            js[file] = entry[file];
            fse.outputJson(path.join(__dirname, 'webpack.entry.json'), js, ( err ) => {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(js[file]);
            });
        }).catch(( err ) => {
            reject(err);
        });
    } else {
        reject('There is any js file in entry.');
    }
});

/**
 * [step10] fs.readFile -- Get js webpack config
 * @return {Promise} get_config_success
 */
let step10 = ( filepath ) => new Promise(( resolve, reject ) => {
    fs.readFile(filepath, (err, buffer) => {
        if (err) {
            reject(err);
            return;
        }
        let result = '';
        let match = buffer.toString().match(/\/\*(.|\n)*?\*\//);
        if (match) {
            let comments = match[0].match(/@.*/g);
            if (comments && comments[0].trim().substring('1') == 'webpack') {
                if (comments[1] && /^@library\b/.test(comments[1]) && !/^@library$/.test(comments[1].trim())) {
                    result += comments[1].trim().replace(' ', '=').replace(/\s/g, '').replace('@', ' --');
                }
                if (comments[2] && /^@libraryTarget\b/.test(comments[2]) && !/^@library$/.test(comments[2].trim())) {
                    result += comments[2].trim().replace(' ', '=').replace(/\s/g, '').replace('@', ' --');
                }
            }
        }
        resolve(result + ' --build=js');
    });
});

start();
<commit_msg>update<commit_after>'use strict';

let fs = require('fs');
let path = require('path');
let fse = require('fs-extra');
let shell = require('shelljs');
let colors = require('colors');
let inline = require('inline-source').sync;
let inquirer = require('inquirer');

const port = 8080;
const sourcePath = path.join(__dirname, '../src');
const outputPath = path.join(__dirname, '../dist');

let cmd;

let start = () => {
    let task = process.argv[2].substring(1);
    if (task == 'dev') {
        cmd = `webpack-dev-server --inline --quiet --devtool eval --progress --colors --content-base ./src/ --hot --config ./webpack/webpack.dev.js --host 0.0.0.0 --port ${ port }`;
        step3().then(step4).catch(( err ) => {
            if (/listen EADDRINUSE/.test(err.toString())) {
                console.log(`\n${ port } is aleary in use. Ctrl+C to leave or input a PID to kill：`.green);
                cmd = `lsof -i tcp:${ port }`;
                step4().then(step6).then(( pid ) => cmd = `kill ${ pid }`).then(step4).catch(( err ) => {
                    console.log(err.toString().red);
                }).then(start);
            } else {
                console.log(err.toString().red);
            }
        });
    }
    if (task == 'build') {
        cmd = 'webpack --progress --colors --config ./webpack/webpack.build.js';
        if (process.argv[3] && process.argv[3] == 'js') {
            step3().then(step7).then(step8).then(( option ) => cmd += option).then(step1).then(step4).then(() => {
                console.log('build complete!'.green);
            }).catch((err) => {
                console.log(err.toString().red);
            });
        } else {
            step1().then(step2).then(step3).then(step4).then(step5).then(() => {
                console.log('build complete!'.green);
            }).catch(( err ) => {
                console.log(err.toString().red);
            });
        }
    }
};

/**
 * [step1] fse.remove -- Remove old files
 * @return {Promise} remove_success
 */
let step1 = () => new Promise(( resolve, reject ) => {
    fse.remove(path.join(outputPath, '*'), ( err ) => {
        if (err) {
            reject(err);
            return;
        }
        resolve();
    });
});

/**
 * [step2] fse.copySync -- Copy files like `html` or `images`
 * @return {Promise} copy_success
 */
let step2 = () => new Promise(( resolve, reject ) => {
    fs.readdir(sourcePath, ( err, files ) => {
        if (err) {
            reject(err);
            return;
        }
        files.forEach(( filename ) => {
            let file = path.join(sourcePath, filename);
            if (filename[0] === '.') {
                return;
            }
            if (fs.statSync(file).isDirectory() && filename == 'entry') {
                return;
            }
            fse.copySync(file, path.join(outputPath, filename));
        });
        resolve();
    });
});

/**
 * [step3] fse.outputJson -- Create `webpack.entry.json` dynamically
 * @return {Promise} create_entry_success
 */
let step3 = () => new Promise(( resolve, reject ) => {
    let entry = {};
    let entryPath = path.join(sourcePath, 'entry');
    fs.readdir(entryPath, ( err, files ) => {
        if (err) {
            reject(err);
            return;
        }
        files.forEach(( filename ) => {
            let file = path.join(entryPath, filename);
            if (fs.statSync(file).isFile() && path.extname(file) == '.js') {
                entry[path.basename(filename, '.js')] = file;
            }
        });
        fse.outputJson(path.join(__dirname, 'webpack.entry.json'), entry, ( err ) => {
            if (err) {
                reject(err);
                return;
            }
            resolve(entry);
        });
    });
});

/**
 * [step4] shell.exec -- Exec command
 * @return {Promise} exec_command_success
 */
let step4 = () => new Promise(( resolve, reject ) => {
    let result = shell.exec(cmd);
    if (result.code === 0) {
        resolve();
    } else {
        reject(result.stderr);
    }
});

/**
 * [step5] inline -- According to `inline` attribute and replace the code of file
 * @return {Promise} inline_success
 */
let step5 = () => new Promise(( resolve, reject ) => {
    fs.readdir(outputPath, ( err, files ) => {
        if (err) {
            reject(err);
            return;
        };
        files.forEach(( filename ) => {
            let file = path.join(outputPath, filename);
            if (fs.statSync(file).isFile() && path.extname(file) == '.html') {
                let html = inline(file, {
                    compress : false,
                    rootpath : path.resolve('dist'),
                    handlers ( source, context ) {
                        if (source && source.fileContent && !source.content) {
                            if (source.extension == 'css') {
                                source.tag = 'style';
                                source.content = source.fileContent.replace(/url\(.*?\)/g, function ( match ) {
                                    let url = match.substring(0, match.length - 1).substring(4);
                                    if (/^http(s?):\/\/|data:image/.test(url)) {
                                        return match;
                                    } else {
                                        if (url.indexOf('?')) {
                                            url = url.split('?')[0];
                                        }
                                        return `url(${ path.join('dist', url) })`;
                                    }
                                });
                            }
                            if (source.extension == 'js') {
                                source.content = source.fileContent.trim();
                            }
                        }
                    },
                });
                fs.writeFileSync(file, html);
            }
        });
        resolve();
    });
});

/**
 * [step6] inquirer.prompt -- Get PID
 * @return {Promise} get_pid_success
 */
let step6 = () => new Promise(( resolve, reject ) => {
    inquirer.prompt([{
        type : 'input',
        name : 'pid',
        message : 'PID:',
    }]).then(( answers ) => {
        resolve(answers.pid);
    }).catch(( err ) => {
        reject(err);
    });
});

/**
 * [step7] inquirer.prompt -- Get js file
 * @return {Promise} get_js_success
 */
let step7 = ( entry ) => new Promise(( resolve, reject ) => {
    let choices = Object.keys(entry);
    if (choices.length) {
        choices.forEach(( file, index ) => {
            choices[index] = file + '.js';
        });
        inquirer.prompt([{
            type : 'list',
            name : 'file',
            message : 'Select a file to pack:',
            choices,
        }]).then(( answers ) => {
            let file = path.basename(answers.file, '.js');
            let js = {};
            js[file] = entry[file];
            fse.outputJson(path.join(__dirname, 'webpack.entry.json'), js, ( err ) => {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(js[file]);
            });
        }).catch(( err ) => {
            reject(err);
        });
    } else {
        reject('There is any js file in entry.');
    }
});

/**
 * [step8] fs.readFile -- Get js webpack config
 * @return {Promise} get_config_success
 */
let step8 = ( filepath ) => new Promise(( resolve, reject ) => {
    fs.readFile(filepath, (err, buffer) => {
        if (err) {
            reject(err);
            return;
        }
        let result = '';
        let match = buffer.toString().match(/\/\*(.|\n)*?\*\//);
        if (match) {
            let comments = match[0].match(/@.*/g);
            if (comments && comments[0].trim().substring('1') == 'webpack') {
                if (comments[1] && /^@library\b/.test(comments[1]) && !/^@library$/.test(comments[1].trim())) {
                    result += comments[1].trim().replace(' ', '=').replace(/\s/g, '').replace('@', ' --');
                }
                if (comments[2] && /^@libraryTarget\b/.test(comments[2]) && !/^@library$/.test(comments[2].trim())) {
                    result += comments[2].trim().replace(' ', '=').replace(/\s/g, '').replace('@', ' --');
                }
            }
        }
        resolve(result + ' --build=js');
    });
});

start();
<|endoftext|>


<commit_before>var bittorrentTracker = require('bittorrent-tracker');
var LRU               = require('lru-cache');
var parseTorrent      = require('parse-torrent');

// ----------------------------------------------------------------------------

exports.cache = new LRU({
  max:    7500,
  maxAge: 60 * 60 * 1000,
  scrape: true
});

// ----------------------------------------------------------------------------

function scrape(magnetLink, callback) {
  try {
    var client = new bittorrentTracker(new Buffer('01234567890123456789'), 6881, parseTorrent(magnetLink));

    // client.on('error', function(err) {
    //   console.log(err);
    //   client.destroy();
    //   callback(err, null);
    // });

    // client.on('warning', function(err) {
    //   console.log(err);
    //   client.destroy();
    //   callback(err, null);
    // });

    client.on('scrape', function(data) {
      client.destroy();
      callback(null, { seeds: data.complete, peers: data.incomplete });
    });

    client.scrape();
  } catch (err)
  {
    callback(err, null);
  }
}

// ----------------------------------------------------------------------------

exports.scrape = function(magnetLink, callback) {
  var startTime        = new Date().getTime();
  var parsedMagnedLink = parseTorrent(magnetLink);

  var key   = parsedMagnedLink.infoHash;
  var value = exports.cache.peek(key);

  // Value doesn't exist in cache, force update
  if (!value) {
    scrape(magnetLink, function(err, results) {
      if (err) {
        console.log('[BTRT][ERR][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn);
        callback(err, null);
      } else {
        console.log('[BTRT][NET][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn + ' (S:' + results.seeds + ' P:' + results.peers + ')');
        exports.cache.set(key, results);
        callback(null, results);
      }
    });
  } else {
    var getValue = exports.cache.get(key);
    if (!getValue) {
      // Value is outdated, try and update it
      scrape(magnetLink, function(err, results) {
        if (err) {
          // Failed to update, return previous value
          console.log('[BTRT][FLB][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn + ' (S:' + value.seeds + ' P:' + value.peers + ')');
          exports.cache.set(key, value);
          callback(null, value);
        } else {
          // Update cache and return new value
          console.log('[BTRT][NET][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn + ' (S:' + results.seeds + ' P:' + results.peers + ')');
          exports.cache.set(key, results);
          callback(null, results);
        }
      });
    } else {
      // Value is still in cache
      // console.log('[BTRT][MEM][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn + ' (S:' + getValue.seeds + ' P:' + getValue.peers + ')');
      callback(null, getValue);
    }
  }
}

// ----------------------------------------------------------------------------

function getDuration(startTime) {
  var duration = ((new Date().getTime() - startTime) / 1000.0).toFixed(1);
  if (duration < 10.0) {
    duration = '0' + duration;
  }
  return duration;
}
<commit_msg>Added timeout in scraper<commit_after>var bittorrentTracker = require('bittorrent-tracker');
var LRU               = require('lru-cache');
var parseTorrent      = require('parse-torrent');

// ----------------------------------------------------------------------------

exports.cache = new LRU({
  max:    7500,
  maxAge: 60 * 60 * 1000,
  scrape: true
});

// ----------------------------------------------------------------------------

function scrape(magnetLink, callback) {
  try {
    var client = new bittorrentTracker(new Buffer('01234567890123456789'), 6881, parseTorrent(magnetLink));

    var timeout = setTimeout(function() {
      client.destroy();
      callback('error', null);
    }, 5000);

    client.on('scrape', function(data) {
      clearTimeout(timeout);
      client.destroy();
      callback(null, { seeds: data.complete, peers: data.incomplete });
    });

    client.scrape();
  } catch (err) {
    callback(err, null);
  }
}

// ----------------------------------------------------------------------------

exports.scrape = function(magnetLink, callback) {
  var startTime        = new Date().getTime();
  var parsedMagnedLink = parseTorrent(magnetLink);

  var key   = parsedMagnedLink.infoHash;
  var value = exports.cache.peek(key);

  // Value doesn't exist in cache, force update
  if (!value) {
    scrape(magnetLink, function(err, results) {
      if (err) {
        console.log('[BTRT][ERR][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn);
        callback(err, null);
      } else {
        console.log('[BTRT][NET][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn + ' (S:' + results.seeds + ' P:' + results.peers + ')');
        exports.cache.set(key, results);
        callback(null, results);
      }
    });
  } else {
    var getValue = exports.cache.get(key);
    if (!getValue) {
      // Value is outdated, try and update it
      scrape(magnetLink, function(err, results) {
        if (err) {
          // Failed to update, return previous value
          console.log('[BTRT][FLB][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn + ' (S:' + value.seeds + ' P:' + value.peers + ')');
          exports.cache.set(key, value);
          callback(null, value);
        } else {
          // Update cache and return new value
          console.log('[BTRT][NET][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn + ' (S:' + results.seeds + ' P:' + results.peers + ')');
          exports.cache.set(key, results);
          callback(null, results);
        }
      });
    } else {
      // Value is still in cache
      // console.log('[BTRT][MEM][' + getDuration(startTime) + 's] ' + parsedMagnedLink.dn + ' (S:' + getValue.seeds + ' P:' + getValue.peers + ')');
      callback(null, getValue);
    }
  }
}

// ----------------------------------------------------------------------------

function getDuration(startTime) {
  var duration = ((new Date().getTime() - startTime) / 1000.0).toFixed(1);
  if (duration < 10.0) {
    duration = '0' + duration;
  }
  return duration;
}
<|endoftext|>


<commit_before>var N3 = require("n3");
var N3Util = N3.Util;
var ShExUtil = require("../lib/ShExUtil");

var MapExt = "http://shex.io/extensions/Map/#";
  var pattern = /^ *(?:<([^>]*)>|([^:]*):([^:]*)) *$/;
function register (validator) {
  var prefixes = validator.schema.prefixes;

  validator.semActHandler.results[MapExt] = {};
  validator.semActHandler.register(
    MapExt,
    {
      dispatch: function (code, ctx) {
        var m = code.match(pattern);
        if (!m) {
          throw Error("Invocation error: " + MapExt + " code \"" + code + "\" didn't match " + pattern);
        }
        var arg = m[1] ? m[1] : prefixes[m[2]] + m[3];
        validator.semActHandler.results[MapExt][arg] = ctx.object;
        return true;
      }
    }
  );
  return validator.semActHandler.results[MapExt];
}

function done (validator) {
  if (Object.keys(validator.semActHandler.results[MapExt]).length === 0)
    delete validator.semActHandler.results[MapExt];
}

function materializer (schema) {
  return {
    materialize: function (bindings, createRoot) {
      var ret = N3.Store();
      var blankNodeCount = 0;
      ret.addPrefixes(schema.prefixes); // not used, but seems polite

      // utility functions for e.g. s = add(B(), P(":value"), L("70", P("xsd:float")))
      function P (pname) { return N3Util.expandPrefixedName(pname, schema.prefixes); }
      function L (value, modifier) { return N3Util.createLiteral(value, modifier); }
      function B () { return '_:b' + blankNodeCount++; }
      function add (s, p, o) { ret.addTriple({ subject: s, predicate: p, object: o }); return s; }

      var curSubject = createRoot || B();

      var v = ShExUtil.Visitor();

      v.visitReference = function (r) {
        this.visitShape(schema.shapes[r], r);
        return this._visitValue(r);
      };

      v.visitTripleConstraint = function (expr) {
        var mapExts = (expr.semActs || []).filter(function (ext) { return ext.name === MapExt; });
        if (mapExts.length) {
          mapExts.forEach(function (ext) {
            var code = ext.code;
            var m = code.match(pattern);
            if (!m) {
              throw Error("Invocation error: " + MapExt + " code \"" + code + "\" didn't match " + pattern);
            }
            var arg = m[1] ? m[1] : P(m[2] + ":" + m[3]);
            add(curSubject, expr.predicate, bindings[arg]);
          });
        } else if ("values" in expr.valueExpr && expr.valueExpr.values.length === 1) {
          add(curSubject, expr.predicate, expr.valueExpr.values[0]);
        } else {
          var oldSubject = curSubject;
          curSubject = B();
          add(oldSubject, expr.predicate, curSubject);
          this._maybeSet(expr, { type: "TripleConstraint" }, "TripleConstraint",
                         ["inverse", "negated", "predicate", "valueExprRef", "valueExpr",
                          "min", "max", "annotations", "semActs"])
          curSubject = oldSubject;
        }
      };

      v.visitShape(schema.shapes[schema.start], schema.start);
      return ret;
    }
  };
}

module.exports = {
  register: register,
  done: done,
  materializer: materializer,
  url: MapExt
};
<commit_msg>~ Map.materialize takes an optional target<commit_after>var N3 = require("n3");
var N3Util = N3.Util;
var ShExUtil = require("../lib/ShExUtil");

var MapExt = "http://shex.io/extensions/Map/#";
var pattern = /^ *(?:<([^>]*)>|([^:]*):([^ ]*)) *$/;
function register (validator) {
  var prefixes = validator.schema.prefixes;

  validator.semActHandler.results[MapExt] = {};
  validator.semActHandler.register(
    MapExt,
    {
      dispatch: function (code, ctx) {
        var m = code.match(pattern);
        if (!m) {
          throw Error("Invocation error: " + MapExt + " code \"" + code + "\" didn't match " + pattern);
        }
        var arg = m[1] ? m[1] : prefixes[m[2]] + m[3];
        validator.semActHandler.results[MapExt][arg] = ctx.object;
        return true;
      }
    }
  );
  return validator.semActHandler.results[MapExt];
}

function done (validator) {
  if (Object.keys(validator.semActHandler.results[MapExt]).length === 0)
    delete validator.semActHandler.results[MapExt];
}

function materializer (schema) {
  return {
    materialize: function (bindings, createRoot, target) {
      target = target || N3.Store();
      var blankNodeCount = 0;
      target.addPrefixes(schema.prefixes); // not used, but seems polite

      // utility functions for e.g. s = add(B(), P(":value"), L("70", P("xsd:float")))
      function P (pname) { return N3Util.expandPrefixedName(pname, schema.prefixes); }
      function L (value, modifier) { return N3Util.createLiteral(value, modifier); }
      function B () { return '_:b' + blankNodeCount++; }
      function add (s, p, o) { target.addTriple({ subject: s, predicate: p, object: o }); return s; }

      var curSubject = createRoot || B();

      var v = ShExUtil.Visitor();

      v.visitReference = function (r) {
        this.visitShape(schema.shapes[r], r);
        return this._visitValue(r);
      };

      v.visitTripleConstraint = function (expr) {
        var mapExts = (expr.semActs || []).filter(function (ext) { return ext.name === MapExt; });
        if (mapExts.length) {
          mapExts.forEach(function (ext) {
            var code = ext.code;
            var m = code.match(pattern);
            if (!m) {
              throw Error("Invocation error: " + MapExt + " code \"" + code + "\" didn't match " + pattern);
            }
            var arg = m[1] ? m[1] : P(m[2] + ":" + m[3]);
            add(curSubject, expr.predicate, bindings[arg]);
          });
        } else if ("values" in expr.valueExpr && expr.valueExpr.values.length === 1) {
          add(curSubject, expr.predicate, expr.valueExpr.values[0]);
        } else {
          var oldSubject = curSubject;
          curSubject = B();
          add(oldSubject, expr.predicate, curSubject);
          this._maybeSet(expr, { type: "TripleConstraint" }, "TripleConstraint",
                         ["inverse", "negated", "predicate", "valueExprRef", "valueExpr",
                          "min", "max", "annotations", "semActs"])
          curSubject = oldSubject;
        }
      };

      v.visitShape(schema.shapes[schema.start], schema.start);
      return target;
    }
  };
}

module.exports = {
  register: register,
  done: done,
  materializer: materializer,
  url: MapExt
};
<|endoftext|>


<commit_before>/* By Luke Cahill - 10/11/15*/

$(document).ready(function() {

	var lastMessage = 0, $welcome = $('.welcome'), $chatbox = $('#chatbox'), $name = $('#name'), re = new RegExp("\s+");
	$('.welcome').hide();
	checkForNewMessage();

	function getMessages() {
		// get the message here

		$.ajax({
			method: 'POST',
			url: 'get.php',
			data: { lastmessage: lastMessage}
		}).done(function(message) {
			$chatbox.append(message);
			$chatbox.animate({ scrollTop: $chatbox.prop('scrollHeight')}, 750)
		});
	};

	function checkForNewMessage() {
		$.ajax({
			method: 'POST',
			url: 'check.php',
			data: { lastmessage: lastMessage }
		}).done(function(data) {
			var recievedData = $.parseJSON(data);
			$('.loading').hide();
			if(recievedData.result == true) {
				getMessages();
				lastMessage = (recievedData.rownumber);
				recievedData = '';
			}

		}).fail(function() {
			console.log("Failed to check for new messages");
		});
	};

	function sendMessage() {
		// post the message here
		var message = $('#message').val()
		var name = $name.val();

		$.ajax({
		   method: 'POST',
		   url: 'post.php',
		   data: { message: message, name: name}
		}).done(function(done) {
		   checkForNewMessage();
		});
	};

	// Get the new messages every 2.5 seconds. Trying to reduce the database load.
	var getMessageInterval = setInterval(function() {
		checkForNewMessage();
	}, 2500);

	var stop = function() {
		clearInterval(getMessageInterval);
	};

	// Used to clear the message box.
	var clearTextbox = function() {
		$('#message').val('');
		$('#wordCount').html('');
	};

	var checkForName = function() {
		var nameCheck = $.trim($name.val());
		if(nameCheck == '') {
			return false;
		} else {
			return true;
		}
	};

	var setName = function() {
		var setName = $.trim($name.val());
		if($name !== '') {
			$welcome.html('Welcome, ' + setName + '');
			$('#setYourName').hide();
			$welcome.show();
		} else {
			alert('Name cannot be blank!');
		}
	};

	// When the send message button is clicked.
    $('#sendMessage').on('click', function() {
		if(checkForName()) {
			sendMessage();
			clearTextbox();
		} else {
			alert("Please enter your name");
		}
    });

	// When the enter key is clicked.
	$('#message').on('keyup', function(event) {
		if(event.keyCode == 13) {
			if(checkForName()) {
				sendMessage();
				clearTextbox();
			} else {
				alert("Please enter your name");
			}
		}

		var $message = $('#message');
		if($message.val().indexOf(' ') > -1) {
			var split = $message.val().split(' ');
			var length = split.length - 1;
			$('#wordCount').html('Current length: ' + length);
		}
	});

	// Set your chat name
	$('#setName').on('click', function() {
		setName();
	});

	$name.on('keyup', function(event) {
		if(event.keyCode == 13) {
			setName();
		}
	});

	$('#aboutButton').on('click', function() {
		alert('Created using HTML, CSS using bootstrap, JavaScript with jQuery, and PHP for the backend to post into the MySQL database.\n\nGets the new messages every 2.5 seconds, this could be improved, but this is mostly just a prototype.');
	});

	$chatbox.delegate('.unread', 'mouseover', function() {
		$(this).removeClass('unread');
	});
});<commit_msg>Changed word count to a character count<commit_after>/* By Luke Cahill - 10/11/15*/

$(document).ready(function() {

	var lastMessage = 0, $welcome = $('.welcome'), $chatbox = $('#chatbox'), $name = $('#name'), re = new RegExp("\s+");
	$('.welcome').hide();
	checkForNewMessage();
	var maximum = 500;
	$wordCount = $('#wordCount');

	$wordCount.html(maximum + ' characters remaining');

	function getMessages() {
		// get the message here

		$.ajax({
			method: 'POST',
			url: 'get.php',
			data: { lastmessage: lastMessage}
		}).done(function(message) {
			$chatbox.append(message);
			$chatbox.animate({ scrollTop: $chatbox.prop('scrollHeight')}, 750)
		});
	};

	function checkForNewMessage() {
		$.ajax({
			method: 'POST',
			url: 'check.php',
			data: { lastmessage: lastMessage }
		}).done(function(data) {
			var recievedData = $.parseJSON(data);
			$('.loading').hide();
			if(recievedData.result == true) {
				getMessages();
				lastMessage = (recievedData.rownumber);
				recievedData = '';
			}

		}).fail(function() {
			console.log("Failed to check for new messages");
		});
	};

	function sendMessage() {
		// post the message here
		var message = $('#message').val()
		var name = $name.val();

		$.ajax({
		   method: 'POST',
		   url: 'post.php',
		   data: { message: message, name: name}
		}).done(function(done) {
		   checkForNewMessage();
		});
	};

	// Get the new messages every 2.5 seconds. Trying to reduce the database load.
	var getMessageInterval = setInterval(function() {
		checkForNewMessage();
	}, 2500);

	var stop = function() {
		clearInterval(getMessageInterval);
	};

	// Used to clear the message box.
	var clearTextbox = function() {
		$('#message').val('');
		$('#wordCount').html('');
	};

	var checkForName = function() {
		var nameCheck = $.trim($name.val());
		if(nameCheck == '') {
			return false;
		} else {
			return true;
		}
	};

	var setName = function() {
		var setName = $.trim($name.val());
		if($name !== '') {
			$welcome.html('Welcome, ' + setName + '');
			$('#setYourName').hide();
			$welcome.show();
		} else {
			alert('Name cannot be blank!');
		}
	};

	// When the send message button is clicked.
    $('#sendMessage').on('click', function() {
		if(checkForName()) {
			sendMessage();
			clearTextbox();
		} else {
			alert("Please enter your name");
		}
    });

	// When the enter key is clicked.
	$('#message').on('keyup', function(event) {
		if(event.keyCode == 13) {
			if(checkForName()) {
				sendMessage();
				clearTextbox();
			} else {
				alert("Please enter your name");
			}
		}

		var $message = $('#message');
		var remaining = (maximum - $message.val().length);

		$wordCount.html(remaining + ' characters remaining');
	});

	// Set your chat name
	$('#setName').on('click', function() {
		setName();
	});

	$name.on('keyup', function(event) {
		if(event.keyCode == 13) {
			setName();
		}
	});

	$('#aboutButton').on('click', function() {
		alert('Created using HTML, CSS using bootstrap, JavaScript with jQuery, and PHP for the backend to post into the MySQL database.\n\nGets the new messages every 2.5 seconds, this could be improved, but this is mostly just a prototype.');
	});

	$chatbox.delegate('.unread', 'mouseover', function() {
		$(this).removeClass('unread');
	});
});<|endoftext|>


<commit_before>function isInArray(value, array) {
  return array.indexOf(value) > -1;
}

function sleep(time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

function updatePage(title, header, buttons) {
  document.title = title + " | PS4 Exploit Host by Al-Azif";
  document.getElementById("title").innerHTML = title;
  document.getElementById("header").innerHTML = header;
  document.getElementById("buttons").innerHTML = buttons;
}

function resetPage() {
  history.pushState("", document.title, window.location.pathname + window.location.search);
  updatePage("Firmware Selection", "Firmware", firmwares);
}

function getFirmwares() {
  var firmwareSpoofs = {
    "5.51": "4.55",
    "5.07": "5.05"
  };
  var ua = navigator.userAgent;
  var currentFirmware = ua.substring(ua.indexOf("5.0 (") + 19, ua.indexOf(") Apple"));
  if (firmwareSpoofs.hasOwnProperty(currentFirmware)) {
    currentFirmware = firmwareSpoofs[currentFirmware];
  }
  var firmwares = "";
  var x = 0;
  if (data["firmwares"].length == 1 && data["firmwares"][0] != "No Exploits Found" && data["firmwares"][0] != "I/O Error on Host") {
    window.location.hash = data["firmwares"][0];
  }
  for (var i = 0, len = data["firmwares"].length; i < len; i++) {
    if (data[data["firmwares"][i]].length > 1) {
      x += 1;
      if (currentFirmware == data["firmwares"][i]) {
        if(navigator.onLine) {
          firmwares += "<button class=\"btn btn-main\" onclick=\"window.location.hash = '" + data["firmwares"][i].replace(/ /g, "%20") + "'\">" + data["firmwares"][i] + "</button>
<button class=\"btn btn-dropdown\">
▼
</button>
Cache

";
        } else {
          firmwares += "<button class=\"btn btn-main btn-full\" onclick=\"window.location.hash = '" + data["firmwares"][i].replace(/ /g, "%20") + "'\">" + data["firmwares"][i] + "</button>";
        }
      } else {
        if(navigator.onLine) {
          firmwares += "<button class=\"btn btn-disabled\" onclick=\"window.location.hash = '" + data["firmwares"][i].replace(/ /g, "%20") + "'\">" + data["firmwares"][i] + "</button>
<button class=\"btn btn-dropdown-disabled\">
▼
</button>
Cache

";
        } else {
          firmwares += "<button class=\"btn btn-disabled btn-full\" onclick=\"window.location.hash = '" + data["firmwares"][i].replace(/ /g, "%20") + "'\">" + data["firmwares"][i] + "</button>";
        }
      }
      if (x >= 3) {
        firmwares += "
";
        x = 0;
      }
    }
  }
  return firmwares;
}

function getExploits() {
  var hash = window.location.hash.substr(1).replace(/\%20/g, " ");
  var exploits = "";
  var x = 0;
  for (var i = 0, len = data[hash].length; i < len; i++) {
    x += 1;
    if (data[hash][i] == "[Back]") {
      exploits += "<button class=\"btn btn-main btn-full\" onclick=\"window.location.hash = 'back'\">[Back]</button>";
    }  else {
      if (navigator.onLine) {
        exploits += "<button class=\"btn btn-main\" onClick=\"loadExploit('" + hash + "', '" + data[hash][i] + "');\">" + data[hash][i] + "</button>
<button class=\"btn btn-dropdown\">
▼
</button>
CacheAutoloadAbout

";
      } else {
        exploits += "<button class=\"btn btn-main\" onClick=\"loadExploit('" + hash + "', '" + data[hash][i] + "');\">" + data[hash][i] + "</button>
<button class=\"btn btn-dropdown\">
▼
</button>
AutoloadAbout

";
      }
    }
    if (x >= 3) {
      exploits += "
";
      x = 0;
    }
  }
  return exploits;
}

function cacheFirmware(firmware) {
  document.getElementById("ifr").setAttribute("src", "/cache/firmware/" + firmware + "/index.html");
}

function cacheExploit(firmware, exploit) {
  document.getElementById("ifr").setAttribute("src", "/cache/exploit/" + firmware + "/" + exploit + "/index.html");
}

function getExploitInfo(firmware, exploit) {
  var modal = document.getElementById("infoModal");
  var closer = document.getElementsByClassName("close")[0];

  closer.onclick = function() {
    modal.style.display = "none";
  };

  window.onclick = function(event) {
    if (event.target == modal) {
      modal.style.display = "none";
    }
  };

  var url = "/exploits/" + firmware + "/" + exploit + "/meta.json";
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, false);
  xhr.send(null);

  if (xhr.status === 200) {
    var metadata = JSON.parse(xhr.responseText);
    document.getElementById("modalTitle").innerHTML = metadata["Name"] + " Metadata";
    var description = metadata["Description"]["default"];
    if (metadata["Description"][lang] !== null) {
      description = metadata["Description"][lang];
    }
    document.getElementsByClassName("modalBody")[0].innerHTML = "

Version:

" + metadata["Version"] + "

Device:

" + metadata["Device"] + "

Firmware:

" + metadata["Firmware"] + "

Description:

" + description + "

URL:

" + metadata["URL"] + "

";
    modal.style.display = "block";
  } else {
    alert("Error retrieving metadata!");
  }
}

function loadExploit(firmware, exploit) {
  // iFrame Method
  // showLoader();
  // document.getElementById("ifr").setAttribute("src", "/exploits/" + firmware + "/" + exploit +"/index.html");

  // Redirect Method
  window.location.replace("/exploits/" + firmware + "/" + exploit +"/index.html");
}

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(";");
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == " ") {
      c = c.substring(1);
    }
    if (c.indexOf(name) === 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function setAutoload(firmware, exploit) {
  document.cookie = "autoload=/exploits/" + firmware + "/" + exploit + "/index.html;";

  // iFrame Method
  //showLoader();
  //document.getElementById("ifr").setAttribute("src", exploit);

  //Redirect Method
  window.location.replace("/exploits/" + firmware + "/" + exploit +"/index.html");
}

function firmwareSelected() {
  var hash = window.location.hash.substr(1);
  if (!isInArray(hash, firmwares)) {
    resetPage();
  } else {
    updatePage("Exploit Selection", hash.replace(/\%20/g, " "), getExploits());
  }
}

function clearFrame() {
  document.getElementById("ifr").setAttribute("src", "");
}

function clearOverlays() {
  document.getElementById("cacheOverlay").style.display = "none";
  document.getElementById("barText").style.display = "none";
  document.getElementById("barBack").style.display = "none";
  document.getElementById("barLoad").style.display = "none";
  document.getElementById("exploitOverlay").style.display = "none";
  document.getElementById("exploitMessage").innerHTML = "";
  document.getElementById("exploitMessage").style.display = "none";
  document.getElementById("exploitLoader").style.display = "none";
}

function showCaching() {
  document.getElementById("cacheOverlay").style.display = "block";
  document.getElementById("barText").style.display = "block";
  document.getElementById("barBack").style.display = "block";
  document.getElementById("barLoad").style.display = "block";
}

function showLoader() {
  document.getElementById("exploitMessage").innerHTML = "";
  document.getElementById("exploitOverlay").style.display = "block";
  document.getElementById("exploitLoader").style.display = "block";
  document.getElementById("exploitMessage").style.display = "block";
}

function ondownloading() {
  showCaching();
}

function onprogress(percent) {
  document.getElementById("barLoad").style.width = percent + "%";
  document.getElementById("barLoad").innerHTML = percent + "%";
}

function oncached() {
  clearFrame();
  clearOverlays();
  alert("Application cached successfully!");
}

function onupdateready() {
  clearFrame();
  clearOverlays();
  alert("Cache updated! Press Ok to reload the page.");
}

function onnoupdate() {
  clearFrame();
  clearOverlays();
  alert("No update available");
}

function onerror() {
  clearFrame();
  clearOverlays();
  alert("Error caching resources!");
}

function onobsolete() {
  clearFrame();
  clearOverlays();
  alert("Manifest returned a 404, cache was deleted");
}

function hideLoader(message, wait) {
  document.getElementById("exploitLoader").style.display = "none";
  document.getElementById("exploitMessage").innerHTML = message;
  sleep(wait).then(() => {
    if (document.getElementById("exploitMessage").innerHTML == "Success") {
      document.getElementById("forceRefresh").value = 1;
      window.location.reload();
    } else if (document.getElementById("exploitMessage").innerHTML == "Waiting..." || document.getElementById("exploitMessage").innerHTML == "Awaiting payload...") {
      // Just sit here
    } else {
      clearFrame();
      clearOverlays();
    }
  });
}

function autoloadCookie() {
  if (getCookie("autoload")) {
    var autoload = getCookie("autoload");
    try {
      if (!isInArray(autoload.split("/")[3], data[autoload.split("/")[2]])) {
        document.cookie = "autoload=;";
        alert("The exploit being autoloaded no longer exists! Cookie cleared");
      } else {
        // iFrame Method
        // showLoader();
        // document.getElementById("ifr").setAttribute("src", autoload);

        // Redirect Method
        window.location.replace(autoload);
      }
    } catch(e) {
      document.cookie = "autoload=;";
      alert("The exploit being autoloaded no longer exists! Cookie cleared");
    }
  }
}

function checkForceRefresh() {
  if (document.getElementById("forceRefresh").value == 1) {
    window.location.replace("./");
  }
}

function bootstrap(input) {
  data = input;
  if (data["Lang_Code"] !== undefined) {
    lang = data["Lang_Code"];
  } else if (localStorage.getItem("language") === null) {
    localStorage.setItem("language", "en");
    lang = "en";
  } else {
    lang = localStorage.getItem("language");
  }
  firmwares = getFirmwares();

  window.onload = function () {
    if (window.location.hash) {
      firmwareSelected();
    } else {
      resetPage();
    }
  };

  window.document.addEventListener("keyup", function (event) {
    if (event.keyCode === 27) {
      if (window.getComputedStyle(document.getElementById("infoModal")).getPropertyValue("display") == "block") {
        document.getElementById("infoModal").style.display = "none";
      } else if (window.getComputedStyle(document.getElementById("exploitOverlay")).getPropertyValue("display") == "none" && document.getElementById("title").innerHTML != "Firmware Selection") {
        window.location.hash = "back";
      }
      clearFrame();
      clearOverlays();
    }
  });

  window.applicationCache.onupdateready = function (n) {
    window.location.reload(true);
  };
}
/*
Copyright (c) 2017-2018 Al Azif, https://github.com/Al-Azif/ps4-exploit-host

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
<commit_msg>Stop code from running more than once. Fix weird recaching issue<commit_after>function isInArray(value, array) {
  return array.indexOf(value) > -1;
}

function sleep(time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

function updatePage(title, header, buttons) {
  document.title = title + " | PS4 Exploit Host by Al-Azif";
  document.getElementById("title").innerHTML = title;
  document.getElementById("header").innerHTML = header;
  document.getElementById("buttons").innerHTML = buttons;
}

function resetPage() {
  clearFrame();
  history.pushState("", document.title, window.location.pathname + window.location.search);
  updatePage("Firmware Selection", "Firmware", firmwares);
}

function getFirmwares() {
  var firmwareSpoofs = {
    "5.51": "4.55",
    "5.07": "5.05"
  };
  var ua = navigator.userAgent;
  var currentFirmware = ua.substring(ua.indexOf("5.0 (") + 19, ua.indexOf(") Apple"));
  if (firmwareSpoofs.hasOwnProperty(currentFirmware)) {
    currentFirmware = firmwareSpoofs[currentFirmware];
  }
  var firmwares = "";
  var x = 0;
  if (data["firmwares"].length == 1 && data["firmwares"][0] != "No Exploits Found" && data["firmwares"][0] != "I/O Error on Host") {
    window.location.hash = data["firmwares"][0];
  }
  for (var i = 0, len = data["firmwares"].length; i < len; i++) {
    if (data[data["firmwares"][i]].length > 1) {
      x += 1;
      if (currentFirmware == data["firmwares"][i]) {
        if(navigator.onLine) {
          firmwares += "<button class=\"btn btn-main\" onclick=\"window.location.hash = '" + data["firmwares"][i].replace(/ /g, "%20") + "'\">" + data["firmwares"][i] + "</button>
<button class=\"btn btn-dropdown\">
▼
</button>
Cache

";
        } else {
          firmwares += "<button class=\"btn btn-main btn-full\" onclick=\"window.location.hash = '" + data["firmwares"][i].replace(/ /g, "%20") + "'\">" + data["firmwares"][i] + "</button>";
        }
      } else {
        if(navigator.onLine) {
          firmwares += "<button class=\"btn btn-disabled\" onclick=\"window.location.hash = '" + data["firmwares"][i].replace(/ /g, "%20") + "'\">" + data["firmwares"][i] + "</button>
<button class=\"btn btn-dropdown-disabled\">
▼
</button>
Cache

";
        } else {
          firmwares += "<button class=\"btn btn-disabled btn-full\" onclick=\"window.location.hash = '" + data["firmwares"][i].replace(/ /g, "%20") + "'\">" + data["firmwares"][i] + "</button>";
        }
      }
      if (x >= 3) {
        firmwares += "
";
        x = 0;
      }
    }
  }
  return firmwares;
}

function getExploits() {
  var hash = window.location.hash.substr(1).replace(/\%20/g, " ");
  var exploits = "";
  var x = 0;
  for (var i = 0, len = data[hash].length; i < len; i++) {
    x += 1;
    if (data[hash][i] == "[Back]") {
      exploits += "<button class=\"btn btn-main btn-full\" onclick=\"window.location.hash = 'back'\">[Back]</button>";
    }  else {
      if (navigator.onLine) {
        exploits += "<button class=\"btn btn-main\" onClick=\"loadExploit('" + hash + "', '" + data[hash][i] + "');\">" + data[hash][i] + "</button>
<button class=\"btn btn-dropdown\">
▼
</button>
CacheAutoloadAbout

";
      } else {
        exploits += "<button class=\"btn btn-main\" onClick=\"loadExploit('" + hash + "', '" + data[hash][i] + "');\">" + data[hash][i] + "</button>
<button class=\"btn btn-dropdown\">
▼
</button>
AutoloadAbout

";
      }
    }
    if (x >= 3) {
      exploits += "
";
      x = 0;
    }
  }
  return exploits;
}

function cacheFirmware(firmware) {
  document.getElementById("ifr").setAttribute("src", "/cache/firmware/" + firmware + "/index.html");
}

function cacheExploit(firmware, exploit) {
  document.getElementById("ifr").setAttribute("src", "/cache/exploit/" + firmware + "/" + exploit + "/index.html");
}

function getExploitInfo(firmware, exploit) {
  var modal = document.getElementById("infoModal");
  var closer = document.getElementsByClassName("close")[0];

  closer.onclick = function() {
    modal.style.display = "none";
  };

  window.onclick = function(event) {
    if (event.target == modal) {
      modal.style.display = "none";
    }
  };

  var url = "/exploits/" + firmware + "/" + exploit + "/meta.json";
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, false);
  xhr.send(null);

  if (xhr.status === 200) {
    var metadata = JSON.parse(xhr.responseText);
    document.getElementById("modalTitle").innerHTML = metadata["Name"] + " Metadata";
    var description = metadata["Description"]["default"];
    if (metadata["Description"][lang] !== null) {
      description = metadata["Description"][lang];
    }
    document.getElementsByClassName("modalBody")[0].innerHTML = "

Version:

" + metadata["Version"] + "

Device:

" + metadata["Device"] + "

Firmware:

" + metadata["Firmware"] + "

Description:

" + description + "

URL:

" + metadata["URL"] + "

";
    modal.style.display = "block";
  } else {
    alert("Error retrieving metadata!");
  }
}

function loadExploit(firmware, exploit) {
  // iFrame Method
  // showLoader();
  // document.getElementById("ifr").setAttribute("src", "/exploits/" + firmware + "/" + exploit +"/index.html");

  // Redirect Method
  window.location.replace("/exploits/" + firmware + "/" + exploit +"/index.html");
}

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(";");
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == " ") {
      c = c.substring(1);
    }
    if (c.indexOf(name) === 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function setAutoload(firmware, exploit) {
  document.cookie = "autoload=/exploits/" + firmware + "/" + exploit + "/index.html;";

  // iFrame Method
  //showLoader();
  //document.getElementById("ifr").setAttribute("src", exploit);

  //Redirect Method
  window.location.replace("/exploits/" + firmware + "/" + exploit +"/index.html");
}

function firmwareSelected() {
  var hash = window.location.hash.substr(1);
  if (!isInArray(hash, firmwares)) {
    resetPage();
  } else {
    updatePage("Exploit Selection", hash.replace(/\%20/g, " "), getExploits());
  }
}

function clearFrame() {
  document.getElementById("ifr").setAttribute("src", "");
}

function clearOverlays() {
  document.getElementById("cacheOverlay").style.display = "none";
  document.getElementById("barText").style.display = "none";
  document.getElementById("barBack").style.display = "none";
  document.getElementById("barLoad").style.display = "none";
  document.getElementById("exploitOverlay").style.display = "none";
  document.getElementById("exploitMessage").innerHTML = "";
  document.getElementById("exploitMessage").style.display = "none";
  document.getElementById("exploitLoader").style.display = "none";
}

function showCaching() {
  document.getElementById("cacheOverlay").style.display = "block";
  document.getElementById("barText").style.display = "block";
  document.getElementById("barBack").style.display = "block";
  document.getElementById("barLoad").style.display = "block";
}

function showLoader() {
  document.getElementById("exploitMessage").innerHTML = "";
  document.getElementById("exploitOverlay").style.display = "block";
  document.getElementById("exploitLoader").style.display = "block";
  document.getElementById("exploitMessage").style.display = "block";
}

function ondownloading() {
  showCaching();
}

function onprogress(percent) {
  document.getElementById("barLoad").style.width = percent + "%";
  document.getElementById("barLoad").innerHTML = percent + "%";
}

function oncached() {
  clearFrame();
  clearOverlays();
  alert("Application cached successfully!");
}

function onupdateready() {
  clearFrame();
  clearOverlays();
  alert("Cache updated! Press Ok to reload the page.");
}

function onnoupdate() {
  clearFrame();
  clearOverlays();
  alert("No update available");
}

function onerror() {
  clearFrame();
  clearOverlays();
  alert("Error caching resources!");
}

function onobsolete() {
  clearFrame();
  clearOverlays();
  alert("Manifest returned a 404, cache was deleted");
}

function hideLoader(message, wait) {
  document.getElementById("exploitLoader").style.display = "none";
  document.getElementById("exploitMessage").innerHTML = message;
  sleep(wait).then(() => {
    if (document.getElementById("exploitMessage").innerHTML == "Success") {
      document.getElementById("forceRefresh").value = 1;
      window.location.reload();
    } else if (document.getElementById("exploitMessage").innerHTML == "Waiting..." || document.getElementById("exploitMessage").innerHTML == "Awaiting payload...") {
      // Just sit here
    } else {
      clearFrame();
      clearOverlays();
    }
  });
}

function autoloadCookie() {
  if (getCookie("autoload")) {
    var autoload = getCookie("autoload");
    try {
      if (!isInArray(autoload.split("/")[3], data[autoload.split("/")[2]])) {
        document.cookie = "autoload=;";
        alert("The exploit being autoloaded no longer exists! Cookie cleared");
      } else {
        // iFrame Method
        // showLoader();
        // document.getElementById("ifr").setAttribute("src", autoload);

        // Redirect Method
        window.location.replace(autoload);
      }
    } catch(e) {
      document.cookie = "autoload=;";
      alert("The exploit being autoloaded no longer exists! Cookie cleared");
    }
  }
}

function checkForceRefresh() {
  if (document.getElementById("forceRefresh").value == 1) {
    window.location.replace("./");
  }
}

function bootstrap(input) {
  if (!window.bootstrapped) {
    data = input;
    if (data["Lang_Code"] !== undefined) {
      lang = data["Lang_Code"];
    } else if (localStorage.getItem("language") === null) {
      localStorage.setItem("language", "en");
      lang = "en";
    } else {
      lang = localStorage.getItem("language");
    }
    firmwares = getFirmwares();

    window.onload = function () {
      if (window.location.hash) {
        firmwareSelected();
      } else {
        resetPage();
      }
    };

    window.document.addEventListener("keyup", function (event) {
      if (event.keyCode === 27) {
        if (window.getComputedStyle(document.getElementById("infoModal")).getPropertyValue("display") == "block") {
          document.getElementById("infoModal").style.display = "none";
        } else if (window.getComputedStyle(document.getElementById("exploitOverlay")).getPropertyValue("display") == "none" && document.getElementById("title").innerHTML != "Firmware Selection") {
          window.location.hash = "back";
        }
        clearFrame();
        clearOverlays();
      }
    });

    window.applicationCache.onupdateready = function (n) {
      window.location.reload(true);
    };
  }
  bootstrapped = true;
}
/*
Copyright (c) 2017-2018 Al Azif, https://github.com/Al-Azif/ps4-exploit-host

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
<|endoftext|>