ChatUtils.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import FaceUtils from "@/utils/FaceUtils";
  2. const ChatUtils = {
  3. ErrorType: {
  4. TIMEOUT_ERROR: 9, //超时
  5. TOKEN_ERROR: 401, //token 失效错误
  6. PARAM_ERROR: 400, //参数错误
  7. FLUSH_TOKEN_ERROR: 7, //刷新token错误
  8. SERVER_ERROR: 500, //服务器错误
  9. NET_ERROR: "TypeError: Failed to fetch", //网络链接不通
  10. },
  11. // 生成uuid
  12. uuid: (): string => {
  13. return `${new Date().getTime()}`;
  14. },
  15. /**
  16. * 消息内容转换
  17. * @param content 要转换的内容
  18. */
  19. transform: (content: string) => {
  20. // 支持的html标签
  21. const fa = FaceUtils.faces()
  22. if (content) {
  23. content = content.replace(/face\[([^\s\\[\]]+?)]/g, function (face: string) {
  24. // 转义表情
  25. const alt = face.replace(/^face/g, '')
  26. return `<img data-face="true" alt="${alt}" src="${fa.get(alt)}">`
  27. })
  28. }
  29. return content
  30. },
  31. /**
  32. * 消息内容转换
  33. * @param content 要转换的内容
  34. */
  35. transformXss: (content: string) => {
  36. // 支持的html标签
  37. const html = (end?: string) => {
  38. return new RegExp(
  39. '\\n*\\[' +
  40. (end || '') +
  41. '(code|pre|div|span|p|table|thead|th|tbody|tr|td|ul|li|ol|li|dl|dt|dd|h2|h3|h4|h5)([\\s\\S]*?)]\\n*',
  42. 'g'
  43. )
  44. }
  45. const fa = FaceUtils.faces()
  46. if (content) {
  47. content = content
  48. .replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
  49. .replace(/</g, '&lt;')
  50. .replace(/>/g, '&gt;')
  51. .replace(/'/g, '&#39;')
  52. .replace(/"/g, '&quot;') // XSS
  53. // .replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;">$1</a>$2')
  54. .replace(/\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»""'']))/gi, (match) => `<a href="${match}" target="_blank">${match}</a>`)
  55. .replace(/face\[([^\s\\[\]]+?)]/g, function (face: string) {
  56. // 转义表情
  57. const alt = face.replace(/^face/g, '')
  58. return (
  59. '<img alt="' + fa.get(alt) + '" title="' + fa.get(alt) + '" src="' + fa.get(alt) + '">'
  60. )
  61. })
  62. .replace(html(), '<$1 $2>')
  63. .replace(html('/'), '</$1>') // 转移HTML代码
  64. .replace(/\n/g, '<br>') // 转义换行
  65. }
  66. return content
  67. }
  68. };
  69. export default ChatUtils;