thelounge/client/js/helpers/ircmessageparser/findLinks.ts

86 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-05-02 09:50:13 +02:00
import LinkifyIt, {Match} from "linkify-it";
2022-05-15 00:18:06 +02:00
import {Part} from "./merge";
2022-05-02 09:50:13 +02:00
type OurMatch = Match & {
noschema?: boolean;
};
LinkifyIt.prototype.normalize = function normalize(match: OurMatch) {
if (!match.schema) {
2018-06-09 08:07:37 +02:00
match.schema = "http:";
match.url = "http://" + match.url;
2022-05-03 08:50:59 +02:00
// @ts-ignore
match.noschema = true;
}
if (match.schema === "//") {
2018-06-09 08:07:37 +02:00
match.schema = "http:";
match.url = "http:" + match.url;
2022-05-03 08:50:59 +02:00
// @ts-ignore
match.noschema = true;
}
if (match.schema === "mailto:" && !/^mailto:/i.test(match.url)) {
match.url = "mailto:" + match.url;
}
};
2022-05-15 00:18:06 +02:00
import tlds from "tlds";
const linkify = LinkifyIt().tlds(tlds).tlds("onion", true);
2018-04-26 18:03:33 +02:00
// Known schemes to detect in text
const commonSchemes = [
2018-04-26 18:03:33 +02:00
"sftp",
2019-07-17 11:33:59 +02:00
"smb",
"file",
"irc",
"ircs",
"svn",
"git",
"steam",
"mumble",
"ts3server",
"svn+ssh",
"ssh",
"gopher",
"gemini",
];
2018-04-26 18:03:33 +02:00
for (const schema of commonSchemes) {
linkify.add(schema + ":", "http:");
}
2022-05-02 09:50:13 +02:00
function findLinks(text: string) {
const matches = linkify.match(text) as OurMatch[];
2018-04-26 18:03:33 +02:00
if (!matches) {
return [];
2017-10-05 22:44:20 +02:00
}
return matches.map(returnUrl);
}
2022-05-02 09:50:13 +02:00
function findLinksWithSchema(text: string) {
const matches = linkify.match(text) as OurMatch[];
if (!matches) {
return [];
}
return matches.filter((url) => !url.noschema).map(returnUrl);
}
2022-05-15 00:18:06 +02:00
function returnUrl(url: OurMatch): LinkPart {
return {
start: url.index,
end: url.lastIndex,
link: url.url,
};
}
2022-05-15 00:18:06 +02:00
export type LinkPart = Part & {
link: string;
};
2022-05-02 09:50:13 +02:00
export {findLinks, findLinksWithSchema};