The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { downloadAttachmentForPreview } from "./attachmentDownload"; |
| 2 | import { msg } from "gt-react-native"; |
| 3 | import { m } from "../i18n/messages"; |
| 4 | |
| 5 | export function isPdfPreviewUri(uri: string): boolean { |
| 6 | try { |
| 7 | return /\.pdf$/i.test(new URL(uri).pathname); |
| 8 | } catch { |
| 9 | return false; |
| 10 | } |
| 11 | } |
| 12 | |
| 13 | export function pdfInitialPage(uri: string): number { |
| 14 | const page = Number(new URLSearchParams(uri.split("#", 2)[1]).get("page")); |
| 15 | return Number.isSafeInteger(page) && page > 0 ? page : 1; |
| 16 | } |
| 17 | |
| 18 | export function pdfLinkUrl(href: string, sourceUri: string): string | null { |
| 19 | if (href.trim().length === 0) return null; |
| 20 | try { |
| 21 | const url = new URL(href, sourceUri); |
| 22 | return url.protocol === "http:" || url.protocol === "https:" ? url.href : null; |
| 23 | } catch { |
| 24 | return null; |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | export async function preparePdfPreview(uri: string, signal: AbortSignal) { |
| 29 | if (signal.aborted) return null; |
| 30 | const source = uri.split("#", 1)[0]!; |
| 31 | const cached = /^(file|content):/.test(source) |
| 32 | ? { uri: source, dispose: () => {} } |
| 33 | : await downloadAttachmentForPreview({ |
| 34 | url: source, |
| 35 | attachment: { name: "preview.pdf", mimeType: "application/pdf" }, |
| 36 | signal, |
| 37 | }); |
| 38 | if (cached === null) return null; |
| 39 | try { |
| 40 | const { File, FileMode } = await import("expo-file-system"); |
| 41 | const handle = new File(cached.uri).open(FileMode.ReadOnly); |
| 42 | try { |
| 43 | const header = await handle.readBytes(5); |
| 44 | if (String.fromCharCode(...header) !== "%PDF-") { |
| 45 | throw new Error( |
| 46 | m(msg("The server did not return a PDF. Check the connection and try again.")), |
| 47 | ); |
| 48 | } |
| 49 | } finally { |
| 50 | handle.close(); |
| 51 | } |
| 52 | if (signal.aborted) { |
| 53 | cached.dispose(); |
| 54 | return null; |
| 55 | } |
| 56 | return cached; |
| 57 | } catch (error) { |
| 58 | cached.dispose(); |
| 59 | if (signal.aborted) return null; |
| 60 | throw error; |
| 61 | } |
| 62 | } |