chat.ts 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. import { CACHE_URL_PREFIX, UPLOAD_URL } from "@/app/constant";
  2. // import heic2any from "heic2any";
  3. import { RequestMessage } from "@/app/client/api";
  4. export function compressImage(file: Blob, maxSize: number): Promise<string> {
  5. return new Promise((resolve, reject) => {
  6. const reader = new FileReader();
  7. reader.onload = (readerEvent: any) => {
  8. const image = new Image();
  9. image.onload = () => {
  10. let canvas = document.createElement("canvas");
  11. let ctx = canvas.getContext("2d");
  12. let width = image.width;
  13. let height = image.height;
  14. let quality = 0.9;
  15. let dataUrl;
  16. do {
  17. canvas.width = width;
  18. canvas.height = height;
  19. ctx?.clearRect(0, 0, canvas.width, canvas.height);
  20. ctx?.drawImage(image, 0, 0, width, height);
  21. dataUrl = canvas.toDataURL("image/jpeg", quality);
  22. if (dataUrl.length < maxSize) break;
  23. if (quality > 0.5) {
  24. // Prioritize quality reduction
  25. quality -= 0.1;
  26. } else {
  27. // Then reduce the size
  28. width *= 0.9;
  29. height *= 0.9;
  30. }
  31. } while (dataUrl.length > maxSize);
  32. resolve(dataUrl);
  33. };
  34. image.onerror = reject;
  35. image.src = readerEvent.target.result;
  36. };
  37. reader.onerror = reject;
  38. if (file.type.includes("heic")) {
  39. const heic2any = require("heic2any");
  40. heic2any({ blob: file, toType: "image/jpeg" })
  41. .then((blob: Blob) => {
  42. reader.readAsDataURL(blob);
  43. })
  44. .catch((e: any) => {
  45. reject(e);
  46. });
  47. }
  48. reader.readAsDataURL(file);
  49. });
  50. }
  51. export async function preProcessImageContent(
  52. content: RequestMessage["content"],
  53. ) {
  54. if (typeof content === "string") {
  55. return content;
  56. }
  57. const result = [];
  58. for (const part of content) {
  59. if (part?.type == "image_url" && part?.image_url?.url) {
  60. const url = await cacheImageToBase64Image(part?.image_url?.url);
  61. result.push({ type: part.type, image_url: { url } });
  62. } else {
  63. result.push({ ...part });
  64. }
  65. }
  66. return result;
  67. }
  68. const imageCaches: Record<string, string> = {};
  69. export function cacheImageToBase64Image(imageUrl: string) {
  70. if (imageUrl.includes(CACHE_URL_PREFIX)) {
  71. if (!imageCaches[imageUrl]) {
  72. const reader = new FileReader();
  73. return fetch(imageUrl, {
  74. method: "GET",
  75. mode: "cors",
  76. credentials: "include",
  77. })
  78. .then((res) => res.blob())
  79. .then(
  80. async (blob) =>
  81. (imageCaches[imageUrl] = await compressImage(blob, 256 * 1024)),
  82. ); // compressImage
  83. }
  84. return Promise.resolve(imageCaches[imageUrl]);
  85. }
  86. return imageUrl;
  87. }
  88. export function base64Image2Blob(base64Data: string, contentType: string) {
  89. const byteCharacters = atob(base64Data);
  90. const byteNumbers = new Array(byteCharacters.length);
  91. for (let i = 0; i < byteCharacters.length; i++) {
  92. byteNumbers[i] = byteCharacters.charCodeAt(i);
  93. }
  94. const byteArray = new Uint8Array(byteNumbers);
  95. return new Blob([byteArray], { type: contentType });
  96. }
  97. export function uploadImage(file: File): Promise<string> {
  98. if (!window._SW_ENABLED) {
  99. // if serviceWorker register error, using compressImage
  100. return compressImage(file, 256 * 1024);
  101. }
  102. const body = new FormData();
  103. body.append("file", file);
  104. return fetch(UPLOAD_URL, {
  105. method: "post",
  106. body,
  107. mode: "cors",
  108. credentials: "include",
  109. })
  110. .then((res) => res.json())
  111. .then((res) => {
  112. console.log("res", res);
  113. if (res?.code == 0 && res?.data) {
  114. return res?.data;
  115. }
  116. throw Error(`upload Error: ${res?.msg}`);
  117. });
  118. }
  119. export function removeImage(imageUrl: string) {
  120. return fetch(imageUrl, {
  121. method: "DELETE",
  122. mode: "cors",
  123. credentials: "include",
  124. });
  125. }