Newer
Older
taehui / taehui-www / src / Utility.ts
@Taehui Taehui on 1 Feb 2 KB v1.0.0
import { Parser } from "htmlparser2";
import { promisify } from "util";
import { createHash, pbkdf2 } from "crypto";

const shaComputer = createHash("sha1");
const pw = promisify(pbkdf2);

export const getLanguage = (
  language: string,
  { title, title1042 }: { title: string; title1042: string },
) => {
  switch (language) {
    case "ko-KR":
      return title1042;
    default:
      return title;
  }
};

export const getFileNames = (text: string) => {
  const fileNames: [string, string][] = [];
  let lastText = "";
  const lastHrefs: string[] = [];
  const textHtml = new Parser({
    onopentag: (name, { href, src }) => {
      switch (name) {
        case "img":
        case "audio":
        case "video":
          if (!src.includes("/")) {
            fileNames.push([src, ""]);
          }
          break;
      }
      lastHrefs.push(href);
    },
    ontext(data) {
      if (lastHrefs.length > 0) {
        lastText += data;
      }
    },
    onclosetag: (name) => {
      const lastHref = lastHrefs.pop();
      if (lastHref?.includes("/") === false && name === "a") {
        fileNames.push([lastHref, lastText]);
      }
      lastText = "";
    },
  });
  textHtml.write(text);
  textHtml.end();
  return fileNames;
};

export const equalCipher = async (
  avatarCipher: string,
  pendingAvatarCipher: string,
) => {
  if (avatarCipher.startsWith("*")) {
    if (
      !(
        avatarCipher ===
        (await shaComputer
          .update(shaComputer.update(pendingAvatarCipher).digest("hex"))
          .digest("hex"))
      )
    ) {
      return false;
    }
  } else {
    const data = avatarCipher.split(":");
    if (
      !(
        data.length === 4 &&
        data[3] ===
          Buffer.from(
            await pw(
              pendingAvatarCipher,
              data[2],
              Number(data[1]),
              Buffer.from(data[3], "base64").length,
              data[0],
            ),
          ).toString("base64")
      )
    ) {
      return false;
    }
  }

  return true;
};

export const isBannedIP = (avatarIP: string) => {
  return /(^127\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)/.test(
    avatarIP,
  );
};

export const getTitle = (
  language: string,
  { title, title1042 }: { title: string; title1042: string },
) => {
  switch (language) {
    case "ko-KR":
      return title1042;
    default:
      return title;
  }
};

export const isTaehui = (level: number) => level === 2;