File size: 9,615 Bytes
4e1096a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | import { BookFormat } from '@/types/book';
import { Collection, Contributor, Identifier, LanguageMap } from '@/utils/book';
import { configureZip } from '@/utils/zip';
import * as epubcfi from 'foliate-js/epubcfi.js';
export const CFI = epubcfi;
export type DocumentFile = File;
export type Location = {
current: number;
next: number;
total: number;
};
export interface TOCItem {
id: number;
label: string;
href: string;
index: number; // Page index for PDF books
cfi?: string;
location?: Location;
subitems?: TOCItem[];
}
export interface SectionItem {
id: string;
cfi: string;
size: number;
linear: string;
href?: string;
location?: Location;
pageSpread?: 'left' | 'right' | 'center' | '';
subitems?: Array<SectionItem>;
createDocument: () => Promise<Document>;
}
export type BookMetadata = {
// NOTE: the title and author fields should be formatted
title: string | LanguageMap;
author: string | Contributor;
language: string | string[];
editor?: string;
publisher?: string;
published?: string;
description?: string;
subject?: string | string[] | Contributor;
identifier?: string;
altIdentifier?: string | string[] | Identifier;
belongsTo?: {
collection?: Array<Collection> | Collection;
series?: Array<Collection> | Collection;
};
subtitle?: string;
series?: string;
seriesIndex?: number;
seriesTotal?: number;
coverImageFile?: string;
coverImageUrl?: string;
coverImageBlobUrl?: string;
};
export interface BookDoc {
metadata: BookMetadata;
rendition?: {
layout?: 'pre-paginated' | 'reflowable';
spread?: 'auto' | 'none';
viewport?: { width: number; height: number };
};
dir: string;
toc?: Array<TOCItem>;
sections?: Array<SectionItem>;
transformTarget?: EventTarget;
splitTOCHref(href: string): Array<string | number>;
getCover(): Promise<Blob | null>;
}
export const EXTS: Record<BookFormat, string> = {
EPUB: 'epub',
PDF: 'pdf',
MOBI: 'mobi',
AZW: 'azw',
AZW3: 'azw3',
CBZ: 'cbz',
FB2: 'fb2',
FBZ: 'fbz',
TXT: 'txt',
MD: 'md',
};
export const MIMETYPES: Record<BookFormat, string[]> = {
EPUB: ['application/epub+zip'],
PDF: ['application/pdf'],
MOBI: ['application/x-mobipocket-ebook'],
AZW: ['application/vnd.amazon.ebook'],
AZW3: ['application/vnd.amazon.mobi8-ebook', 'application/x-mobi8-ebook'],
CBZ: ['application/vnd.comicbook+zip', 'application/zip', 'application/x-cbz'],
FB2: ['application/x-fictionbook+xml', 'text/xml', 'application/xml'],
FBZ: ['application/x-zip-compressed-fb2', 'application/zip'],
TXT: ['text/plain'],
MD: ['text/markdown', 'text/x-markdown'],
};
export class DocumentLoader {
private file: File;
constructor(file: File) {
this.file = file;
}
private async isZip(): Promise<boolean> {
const arr = new Uint8Array(await this.file.slice(0, 4).arrayBuffer());
return arr[0] === 0x50 && arr[1] === 0x4b && arr[2] === 0x03 && arr[3] === 0x04;
}
private async isPDF(): Promise<boolean> {
const arr = new Uint8Array(await this.file.slice(0, 5).arrayBuffer());
return (
arr[0] === 0x25 && arr[1] === 0x50 && arr[2] === 0x44 && arr[3] === 0x46 && arr[4] === 0x2d
);
}
private async makeZipLoader() {
const getComment = async (): Promise<string | null> => {
const EOCD_SIGNATURE = [0x50, 0x4b, 0x05, 0x06];
const maxEOCDSearch = 1024 * 64;
const sliceSize = Math.min(maxEOCDSearch, this.file.size);
const tail = await this.file.slice(this.file.size - sliceSize, this.file.size).arrayBuffer();
const bytes = new Uint8Array(tail);
for (let i = bytes.length - 22; i >= 0; i--) {
if (
bytes[i] === EOCD_SIGNATURE[0] &&
bytes[i + 1] === EOCD_SIGNATURE[1] &&
bytes[i + 2] === EOCD_SIGNATURE[2] &&
bytes[i + 3] === EOCD_SIGNATURE[3]
) {
const commentLength = bytes[i + 20]! + (bytes[i + 21]! << 8);
const commentStart = i + 22;
const commentBytes = bytes.slice(commentStart, commentStart + commentLength);
return new TextDecoder().decode(commentBytes);
}
}
return null;
};
await configureZip();
const { ZipReader, BlobReader, TextWriter, BlobWriter } = await import('@zip.js/zip.js');
type Entry = import('@zip.js/zip.js').Entry;
const reader = new ZipReader(new BlobReader(this.file));
const entries = await reader.getEntries();
const map = new Map(entries.map((entry) => [entry.filename, entry]));
const load =
(f: (entry: Entry, type?: string) => Promise<string | Blob> | null) =>
(name: string, ...args: [string?]) =>
map.has(name) ? f(map.get(name)!, ...args) : null;
const loadText = load((entry: Entry) =>
!entry.directory ? entry.getData(new TextWriter()) : null,
);
const loadBlob = load((entry: Entry, type?: string) =>
!entry.directory ? entry.getData(new BlobWriter(type!)) : null,
);
const getSize = (name: string) => map.get(name)?.uncompressedSize ?? 0;
return { entries, loadText, loadBlob, getSize, getComment, sha1: undefined };
}
private isCBZ(): boolean {
return (
this.file.type === 'application/vnd.comicbook+zip' || this.file.name.endsWith(`.${EXTS.CBZ}`)
);
}
private isFB2(): boolean {
return (
this.file.type === 'application/x-fictionbook+xml' || this.file.name.endsWith(`.${EXTS.FB2}`)
);
}
private isFBZ(): boolean {
return (
this.file.type === 'application/x-zip-compressed-fb2' ||
this.file.name.endsWith('.fb.zip') ||
this.file.name.endsWith('.fb2.zip') ||
this.file.name.endsWith(`.${EXTS.FBZ}`)
);
}
public async open(): Promise<{ book: BookDoc; format: BookFormat }> {
let book = null;
let format: BookFormat = 'EPUB';
if (!this.file.size) {
throw new Error('File is empty');
}
try {
if (await this.isZip()) {
const loader = await this.makeZipLoader();
const { entries } = loader;
if (this.isCBZ()) {
const { makeComicBook } = await import('foliate-js/comic-book.js');
book = await makeComicBook(loader, this.file);
format = 'CBZ';
} else if (this.isFBZ()) {
const entry = entries.find((entry) => entry.filename.endsWith(`.${EXTS.FB2}`));
const blob = await loader.loadBlob((entry ?? entries[0]!).filename);
const { makeFB2 } = await import('foliate-js/fb2.js');
book = await makeFB2(blob);
format = 'FBZ';
} else {
const { EPUB } = await import('foliate-js/epub.js');
book = await new EPUB(loader).init();
format = 'EPUB';
}
} else if (await this.isPDF()) {
const { makePDF } = await import('foliate-js/pdf.js');
book = await makePDF(this.file);
format = 'PDF';
} else if (await (await import('foliate-js/mobi.js')).isMOBI(this.file)) {
const fflate = await import('foliate-js/vendor/fflate.js');
const { MOBI } = await import('foliate-js/mobi.js');
book = await new MOBI({ unzlib: fflate.unzlibSync }).open(this.file);
const ext = this.file.name.split('.').pop()?.toLowerCase();
switch (ext) {
case 'azw':
format = 'AZW';
break;
case 'azw3':
format = 'AZW3';
break;
default:
format = 'MOBI';
}
} else if (this.isFB2()) {
const { makeFB2 } = await import('foliate-js/fb2.js');
book = await makeFB2(this.file);
format = 'FB2';
}
} catch (e: unknown) {
console.error('Failed to open document:', e);
if (e instanceof Error && e.message?.includes('not a valid zip')) {
throw new Error('Unsupported or corrupted book file');
}
throw e;
}
return { book, format } as { book: BookDoc; format: BookFormat };
}
}
export const getDirection = (doc: Document) => {
const { defaultView } = doc;
const { writingMode, direction } = defaultView!.getComputedStyle(doc.body);
const vertical = writingMode === 'vertical-rl' || writingMode === 'vertical-lr';
const rtl = doc.body.dir === 'rtl' || direction === 'rtl' || doc.documentElement.dir === 'rtl';
return { vertical, rtl };
};
export const getFileExtFromMimeType = (mimeType?: string): string => {
if (!mimeType) return '';
for (const format in MIMETYPES) {
const list = MIMETYPES[format as BookFormat];
if (list.includes(mimeType)) {
return EXTS[format as BookFormat];
}
}
return '';
};
export const getMimeTypeFromFileExt = (ext: string): string => {
ext = ext.toLowerCase();
for (const format in EXTS) {
if (EXTS[format as BookFormat] === ext) {
const mimeTypes = MIMETYPES[format as BookFormat];
return mimeTypes[0] || 'application/octet-stream';
}
}
return 'application/octet-stream';
};
export const convertBlobUrlToDataUrl = async (blobUrl: string): Promise<string> => {
try {
const response = await fetch(blobUrl);
if (!response.ok) {
throw new Error(
`Failed to fetch blob from "${blobUrl}": ${response.status} ${response.statusText}`,
);
}
const blob = await response.blob();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result as string);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
} catch (error) {
console.error('Failed to convert blob to data URL:', error);
throw error;
}
};
|