forked from jordanlambrecht/tracker-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathonlyimage.ts
More file actions
68 lines (56 loc) · 1.93 KB
/
onlyimage.ts
File metadata and controls
68 lines (56 loc) · 1.93 KB
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
// src/lib/image-hosting/onlyimage.ts
import { safeImageUrl, validateImageUrl } from "@/lib/validators"
import type { ImageHostAdapter, UploadOptions, UploadResult } from "./types"
const UPLOAD_URL = "https://onlyimage.org/api/1/upload/"
interface CheveretoResponse {
status_code: number
image: {
url: string
url_viewer: string
thumb?: { url: string }
medium?: { url: string }
}
error?: { message: string }
}
/** Convert seconds to an ISO 8601 duration string */
export function secondsToIsoDuration(seconds: number): string {
if (seconds >= 86400 && seconds % 86400 === 0) return `P${seconds / 86400}D`
if (seconds >= 3600 && seconds % 3600 === 0) return `PT${seconds / 3600}H`
if (seconds >= 60 && seconds % 60 === 0) return `PT${seconds / 60}M`
return `PT${seconds}S`
}
export const onlyimageAdapter: ImageHostAdapter = {
id: "onlyimage",
async upload(
fileBuffer: Buffer,
fileName: string,
apiKey: string,
options?: UploadOptions
): Promise<UploadResult> {
const form = new FormData()
form.set("source", new Blob([new Uint8Array(fileBuffer)]), fileName)
form.set("format", "json")
if (options?.expirationSeconds && options.expirationSeconds > 0) {
form.set("expiration_date", secondsToIsoDuration(options.expirationSeconds))
}
const response = await fetch(UPLOAD_URL, {
method: "POST",
headers: { "X-API-Key": apiKey },
body: form,
signal: AbortSignal.timeout(30_000),
})
if (!response.ok) {
throw new Error(`OnlyImage upload failed (${response.status})`)
}
const data = (await response.json()) as CheveretoResponse
if (!data.image?.url) {
throw new Error("OnlyImage returned unexpected response — no image URL")
}
return {
url: validateImageUrl(data.image.url),
viewerUrl: safeImageUrl(data.image.url_viewer),
thumbUrl: safeImageUrl(data.image.thumb?.url),
host: "onlyimage",
}
},
}