const express = require("express");
const request = require("request");
const log = require("./log");
const app = express();
const port = 9000;
const { getDecryptionArray } = require("./decode");
const { Transform } = require("stream");
function xorTransform(decryptionArray) {
  let processedBytes = 0;
  return new Transform({
    transform(chunk, encoding, callback) {
      if (processedBytes < decryptionArray.length) {
        let remaining = Math.min(
          decryptionArray.length - processedBytes,
          chunk.length
        );
        for (let i = 0; i < remaining; i++) {
          chunk[i] = chunk[i] ^ decryptionArray[processedBytes + i];
        }
        processedBytes += remaining;
      }
      this.push(chunk);
      callback();
    },
  });
}
const decode = (url, res, decodeKey) => {
  let xorStream = xorTransform(
    getDecryptionArray(decodeURIComponent(decodeKey))
  );
  const req = request(decodeURIComponent(url));
  req.on("response", (resp) => {
    const headers = resp.headers;
    res.writeHead(200, "ok", headers);
  });
  req.pipe(xorStream).pipe(res);
};
app.get("/download", (req, res) => {
  const { url, decodeKey } = req.query;
  log.info(`download url:${url}`);
  log.info(`download decodeKey:${decodeKey}`);
  decode(url, res, decodeKey);
});

app.listen(port, () => {
  log.info(`Example app listening at http://localhost:${port}`);
});
