image-storage.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. /**
  2. * Image Storage Utilities
  3. *
  4. * Store PDF images in IndexedDB to avoid sessionStorage 5MB limit.
  5. * Images are stored as Blobs for efficient storage.
  6. */
  7. import { db, type ImageFileRecord } from './database';
  8. import { nanoid } from 'nanoid';
  9. import { createLogger } from '@/lib/logger';
  10. const log = createLogger('ImageStorage');
  11. /**
  12. * Convert base64 data URL to Blob
  13. */
  14. function base64ToBlob(base64DataUrl: string): Blob {
  15. const parts = base64DataUrl.split(',');
  16. const mimeMatch = parts[0].match(/:(.*?);/);
  17. const mimeType = mimeMatch ? mimeMatch[1] : 'image/png';
  18. const base64Data = parts[1];
  19. const byteString = atob(base64Data);
  20. const arrayBuffer = new ArrayBuffer(byteString.length);
  21. const uint8Array = new Uint8Array(arrayBuffer);
  22. for (let i = 0; i < byteString.length; i++) {
  23. uint8Array[i] = byteString.charCodeAt(i);
  24. }
  25. return new Blob([uint8Array], { type: mimeType });
  26. }
  27. /**
  28. * Convert Blob to base64 data URL
  29. */
  30. async function blobToBase64(blob: Blob): Promise<string> {
  31. return new Promise((resolve, reject) => {
  32. const reader = new FileReader();
  33. reader.onloadend = () => resolve(reader.result as string);
  34. reader.onerror = reject;
  35. reader.readAsDataURL(blob);
  36. });
  37. }
  38. /**
  39. * Store images in IndexedDB
  40. * Returns array of stored image IDs
  41. */
  42. export async function storeImages(
  43. images: Array<{ id: string; src: string; pageNumber?: number }>,
  44. ): Promise<string[]> {
  45. const sessionId = nanoid(10);
  46. const storedIds: string[] = [];
  47. for (const img of images) {
  48. try {
  49. const blob = base64ToBlob(img.src);
  50. const mimeMatch = img.src.match(/data:(.*?);/);
  51. const mimeType = mimeMatch ? mimeMatch[1] : 'image/png';
  52. // Use session-prefixed ID to allow cleanup
  53. const storageId = `session_${sessionId}_${img.id}`;
  54. const record: ImageFileRecord = {
  55. id: storageId,
  56. blob,
  57. filename: `${img.id}.png`,
  58. mimeType,
  59. size: blob.size,
  60. createdAt: Date.now(),
  61. };
  62. await db.imageFiles.put(record);
  63. storedIds.push(storageId);
  64. } catch (error) {
  65. log.error(`Failed to store image ${img.id}:`, error);
  66. }
  67. }
  68. return storedIds;
  69. }
  70. /**
  71. * Load images from IndexedDB and return as imageMapping
  72. * @param imageIds - Array of storage IDs (session_xxx_img_1 format)
  73. * @returns ImageMapping { img_1: "data:image/png;base64,..." }
  74. */
  75. export async function loadImageMapping(imageIds: string[]): Promise<Record<string, string>> {
  76. const mapping: Record<string, string> = {};
  77. for (const storageId of imageIds) {
  78. try {
  79. const record = await db.imageFiles.get(storageId);
  80. if (record) {
  81. const base64 = await blobToBase64(record.blob);
  82. // Extract original ID (img_1) from storage ID (session_xxx_img_1)
  83. const originalId = storageId.replace(/^session_[^_]+_/, '');
  84. mapping[originalId] = base64;
  85. }
  86. } catch (error) {
  87. log.error(`Failed to load image ${storageId}:`, error);
  88. }
  89. }
  90. return mapping;
  91. }
  92. /**
  93. * Clean up images by session prefix
  94. */
  95. export async function cleanupSessionImages(sessionId: string): Promise<void> {
  96. try {
  97. const prefix = `session_${sessionId}_`;
  98. const allImages = await db.imageFiles.toArray();
  99. const toDelete = allImages.filter((img) => img.id.startsWith(prefix));
  100. for (const img of toDelete) {
  101. await db.imageFiles.delete(img.id);
  102. }
  103. log.info(`Cleaned up ${toDelete.length} images for session ${sessionId}`);
  104. } catch (error) {
  105. log.error('Failed to cleanup session images:', error);
  106. }
  107. }
  108. /**
  109. * Clean up old images (older than specified hours)
  110. */
  111. export async function cleanupOldImages(hoursOld: number = 24): Promise<void> {
  112. try {
  113. const cutoff = Date.now() - hoursOld * 60 * 60 * 1000;
  114. await db.imageFiles.where('createdAt').below(cutoff).delete();
  115. log.info(`Cleaned up images older than ${hoursOld} hours`);
  116. } catch (error) {
  117. log.error('Failed to cleanup old images:', error);
  118. }
  119. }
  120. /**
  121. * Get total size of stored images
  122. */
  123. export async function getImageStorageSize(): Promise<number> {
  124. const images = await db.imageFiles.toArray();
  125. return images.reduce((total, img) => total + img.size, 0);
  126. }
  127. /**
  128. * Store a PDF file as a Blob in IndexedDB.
  129. * Returns a storage key that can be used to retrieve the blob later.
  130. */
  131. export async function storePdfBlob(file: File): Promise<string> {
  132. const storageKey = `pdf_${nanoid(10)}`;
  133. const blob = new Blob([await file.arrayBuffer()], {
  134. type: file.type || 'application/pdf',
  135. });
  136. const record: ImageFileRecord = {
  137. id: storageKey,
  138. blob,
  139. filename: file.name,
  140. mimeType: file.type || 'application/pdf',
  141. size: blob.size,
  142. createdAt: Date.now(),
  143. };
  144. await db.imageFiles.put(record);
  145. return storageKey;
  146. }
  147. /**
  148. * Load a PDF Blob from IndexedDB by its storage key.
  149. */
  150. export async function loadPdfBlob(key: string): Promise<Blob | null> {
  151. const record = await db.imageFiles.get(key);
  152. return record?.blob ?? null;
  153. }