TeaWeb/shared/js/text/chat.ts

74 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-12-07 14:07:47 +00:00
import UrlKnife from 'url-knife';
import {Settings, settings} from "../settings";
import {renderMarkdownAsBBCode} from "../text/markdown";
import {escapeBBCode} from "../text/bbcode";
2020-07-19 14:34:08 +00:00
2020-12-07 14:07:47 +00:00
interface UrlKnifeUrl {
value: {
url: string,
},
area: string,
index: {
start: number,
end: number
}
}
2020-07-19 14:34:08 +00:00
2020-12-07 14:07:47 +00:00
function bbcodeLinkUrls(message: string) : string {
const urls: UrlKnifeUrl[] = UrlKnife.TextArea.extractAllUrls(message, {
'ip_v4' : true,
'ip_v6' : false,
'localhost' : false,
'intranet' : true
});
2020-07-19 14:34:08 +00:00
2020-12-07 14:07:47 +00:00
/* we want to go through the urls from the back to the front */
urls.sort((a, b) => b.index.start - a.index.start);
for(const url of urls) {
const prefix = message.substr(0, url.index.start);
const suffix = message.substr(url.index.end);
const urlPath = message.substring(url.index.start, url.index.end);
let bbcodeUrl;
let colonIndex = urlPath.indexOf(":");
if(colonIndex === -1 || colonIndex + 2 < urlPath.length || urlPath[colonIndex + 1] !== "/" || urlPath[colonIndex + 2] !== "/") {
bbcodeUrl = "[url=https://" + urlPath + "]" + urlPath + "[/url]";
} else {
bbcodeUrl = "[url]" + urlPath + "[/url]";
2020-07-19 14:34:08 +00:00
}
2020-12-07 14:07:47 +00:00
message = prefix + bbcodeUrl + suffix;
2020-07-19 14:34:08 +00:00
}
2020-12-07 14:07:47 +00:00
return message;
2020-07-19 14:34:08 +00:00
}
export function preprocessChatMessageForSend(message: string) : string {
2020-12-07 14:07:47 +00:00
const processUrls = settings.static_global(Settings.KEY_CHAT_TAG_URLS);
const parseMarkdown = settings.static_global(Settings.KEY_CHAT_ENABLE_MARKDOWN);
const escapeBBCodes = !settings.static_global(Settings.KEY_CHAT_ENABLE_BBCODE);
2020-07-19 14:34:08 +00:00
2020-12-07 14:07:47 +00:00
if(parseMarkdown) {
2020-07-19 14:34:08 +00:00
return renderMarkdownAsBBCode(message, text => {
2020-12-07 14:07:47 +00:00
if(escapeBBCodes) {
2020-07-19 14:34:08 +00:00
text = escapeBBCode(text);
2020-12-07 14:07:47 +00:00
}
2020-07-19 14:34:08 +00:00
2020-12-07 14:07:47 +00:00
if(processUrls) {
text = bbcodeLinkUrls(text);
}
2020-07-19 14:34:08 +00:00
return text;
});
2020-12-07 14:07:47 +00:00
} else {
if(escapeBBCodes) {
message = escapeBBCode(message);
}
2020-07-19 14:34:08 +00:00
2020-12-07 14:07:47 +00:00
if(processUrls) {
message = bbcodeLinkUrls(message);
}
2020-07-19 14:34:08 +00:00
2020-12-07 14:07:47 +00:00
return message;
}
2020-07-19 14:34:08 +00:00
}