Commit e5a82376 authored by Grant's avatar Grant
Browse files

format the messages better

parent cef9117d
Loading
Loading
Loading
Loading
+22 −1
Original line number Diff line number Diff line
@@ -14,12 +14,14 @@
        "discord.js": "^14.15.3",
        "eventemitter3": "^5.0.1",
        "express": "^4.19.2",
        "morgan": "^1.10.0"
        "morgan": "^1.10.0",
        "turndown": "^7.2.0"
      },
      "devDependencies": {
        "@tsconfig/recommended": "^1.0.6",
        "@types/express": "^4.17.21",
        "@types/morgan": "^1.9.9",
        "@types/turndown": "^5.0.4",
        "@typescript-eslint/eslint-plugin": "^7.12.0",
        "@typescript-eslint/parser": "^7.12.0",
        "dotenv": "^16.4.5",
@@ -650,6 +652,11 @@
      "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==",
      "dev": true
    },
    "node_modules/@mixmark-io/domino": {
      "version": "2.2.0",
      "resolved": "https://registry.npmjs.org/@mixmark-io/domino/-/domino-2.2.0.tgz",
      "integrity": "sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw=="
    },
    "node_modules/@nodelib/fs.scandir": {
      "version": "2.1.5",
      "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
@@ -888,6 +895,12 @@
        "@types/send": "*"
      }
    },
    "node_modules/@types/turndown": {
      "version": "5.0.4",
      "resolved": "https://registry.npmjs.org/@types/turndown/-/turndown-5.0.4.tgz",
      "integrity": "sha512-28GI33lCCkU4SGH1GvjDhFgOVr+Tym4PXGBIU1buJUa6xQolniPArtUT+kv42RR2N9MsMLInkr904Aq+ESHBJg==",
      "dev": true
    },
    "node_modules/@types/ws": {
      "version": "8.5.10",
      "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.10.tgz",
@@ -3181,6 +3194,14 @@
        "fsevents": "~2.3.3"
      }
    },
    "node_modules/turndown": {
      "version": "7.2.0",
      "resolved": "https://registry.npmjs.org/turndown/-/turndown-7.2.0.tgz",
      "integrity": "sha512-eCZGBN4nNNqM9Owkv9HAtWRYfLA4h909E/WGAWWBpmB275ehNhZyk87/Tpvjbp0jjNl9XwCsbe6bm6CqFsgD+A==",
      "dependencies": {
        "@mixmark-io/domino": "^2.2.0"
      }
    },
    "node_modules/type-check": {
      "version": "0.4.0",
      "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
+3 −1
Original line number Diff line number Diff line
@@ -15,6 +15,7 @@
    "@tsconfig/recommended": "^1.0.6",
    "@types/express": "^4.17.21",
    "@types/morgan": "^1.9.9",
    "@types/turndown": "^5.0.4",
    "@typescript-eslint/eslint-plugin": "^7.12.0",
    "@typescript-eslint/parser": "^7.12.0",
    "dotenv": "^16.4.5",
@@ -30,6 +31,7 @@
    "discord.js": "^14.15.3",
    "eventemitter3": "^5.0.1",
    "express": "^4.19.2",
    "morgan": "^1.10.0"
    "morgan": "^1.10.0",
    "turndown": "^7.2.0"
  }
}
+21 −15
Original line number Diff line number Diff line
@@ -29,6 +29,7 @@ import {
} from "./types/matrix";
import { Matrix } from "./lib/matrix";
import { FriendlyError } from "./lib/utils";
import { Turndown } from "./lib/turndown";

class Discord_ {
  client = new Client({
@@ -403,24 +404,29 @@ class Discord_ {

    let content = message.content.formatted_body;

    const MATRIX_USER = Matrix.getMatrixUserRegex();
    const matrixMention = new RegExp(
      `<a href="https://matrix\.to/#/(${MATRIX_USER.source})">.*(?!<a)</a>`,
      "gi"
    );
    // const MATRIX_USER = Matrix.getMatrixUserRegex();
    // const matrixMention = new RegExp(
    //   `<a href="https://matrix\.to/#/(${MATRIX_USER.source})">.*(?!<a)</a>`,
    //   "gi"
    // );

    const matches = new Set([...content.matchAll(matrixMention)]);
    // const matches = new Set([...content.matchAll(matrixMention)]);

    for (const [mention, userId] of matches) {
      const discordId = userId
        .replace("@_discord_", "")
        .replace(":" + process.env.MATRIX_HOMESERVER, "");
    // for (const [mention, userId] of matches) {
    //   if (!userId.startsWith("@_discord_")) continue;

      content = content.replace(
        new RegExp(mention, "g"),
        "<@" + discordId + ">"
      );
    }
    //   const discordId = userId
    //     .replace("@_discord_", "")
    //     .replace(":" + process.env.MATRIX_HOMESERVER, "");

    //   content = content.replace(
    //     new RegExp(mention, "g"),
    //     "<@" + discordId + ">"
    //   );
    // }

    content = Turndown.turndown(content);
    content = content.replace(/\bhttps?:\/\/matrix\.to\/[^ )]*/g, "<$&>");

    return content;
  }

src/lib/turndown.ts

0 → 100644
+100 −0
Original line number Diff line number Diff line
import TurndownService from "turndown";

// https://gitdab.com/cadence/out-of-your-element/src/commit/c9aa5b4c64ac9f47dc75059950aee67e8244b575/m2d/converters/event-to-message.js

export const Turndown = new TurndownService({
  hr: "----",
  headingStyle: "atx",
  codeBlockStyle: "fenced",
});

Turndown.remove("mx-reply" as any);

Turndown.addRule("strikethrough", {
  filter: ["del", "s"],
  replacement(content) {
    return `~~${content}~~`;
  },
});

Turndown.addRule("underline", {
  filter: ["u"],
  replacement(content) {
    return `__${content}__`;
  },
});

Turndown.addRule("blockquote", {
  filter: "blockquote",
  replacement(content) {
    content = content.replace(/^\n+|\n+$/g, "");
    content = content.replace(/^/gm, "> ");
    return content;
  },
});

Turndown.addRule("spoiler", {
  filter: function (node, options) {
    return node.tagName === "SPAN" && node.hasAttribute("data-mx-spoiler");
  },

  replacement(content, node_) {
    let node: HTMLElement = node_ as any;

    if (node.getAttribute("data-mx-spoiler")) {
      // escape parentheses so it can't become a link
      return `\\(${node.getAttribute("data-mx-spoiler")}\\) ||${content}||`;
    }

    return `||${content}||`;
  },
});

Turndown.addRule("inlineLink", {
  filter(node, options) {
    return node.nodeName === "A" && !!node.getAttribute("href");
  },

  replacement(content, node_) {
    let node: HTMLElement = node_ as any;

    const href = node.getAttribute("href");
    if (href) {
      if (
        href.startsWith("https://matrix.to/#/@_discord_") &&
        href.indexOf("@_discord_bot") === -1
      ) {
        return `<@${href.replace("https://matrix.to/#/@_discord_", "").replace(":" + process.env.MATRIX_HOMESERVER, "")}>`;
      }

      content = content.replace(/ @.*/, "");
      if (href === content) return href;
      if (href.startsWith("https://matrix.to/#/@") && content[0] !== "@")
        content = "@" + content;
    }

    return "[" + content + "](" + href + ")";
  },
});

Turndown.addRule("listItem", {
  filter: "li",
  replacement: function (content, node_, options) {
    let node: HTMLElement = node_ as any;

    content = content
      .replace(/^\n+/, "") // remove leading newlines
      .replace(/\n+$/, "\n") // replace trailing newlines with just a single one
      .replace(/\n/gm, "\n  "); // indent
    var prefix = options.bulletListMarker + " ";
    var parent = node.parentNode;
    if (parent?.nodeName === "OL" && parent instanceof HTMLElement) {
      var start = parent.getAttribute("start");
      var index = Array.prototype.indexOf.call(parent.children, node);
      prefix = (start ? Number(start) + index : index + 1) + ". ";
    }
    return (
      prefix + content + (node.nextSibling && !/\n$/.test(content) ? "\n" : "")
    );
  },
});