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

84 lines
1.4 KiB
TypeScript
Raw Normal View History

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