chat.ts 3.9 KB

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