File size: 3,674 Bytes
008947a
 
 
 
7604e0d
 
 
 
 
 
 
 
 
008947a
 
 
 
 
 
 
 
 
 
 
 
 
 
4fb118c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
008947a
7604e0d
008947a
 
 
4fb118c
7604e0d
008947a
 
 
7604e0d
008947a
 
 
 
7604e0d
008947a
 
 
7604e0d
008947a
 
 
 
7604e0d
008947a
 
 
 
c45cbe3
7604e0d
008947a
 
 
c45cbe3
7604e0d
008947a
 
4fb118c
008947a
 
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
import type { LocationResult, PosterRequest, StylePreset } from './types'

const API_ROOT = import.meta.env.VITE_API_URL ?? '/api/v1'

async function request(url: string, init: RequestInit | undefined, networkError: string): Promise<Response> {
  try {
    return await fetch(url, init)
  } catch (reason) {
    if (reason instanceof Error && reason.name === 'AbortError') throw reason
    throw new Error(networkError)
  }
}

async function readError(response: Response): Promise<string> {
  try {
    const payload = await response.json() as { detail?: string }
    return payload.detail ?? `Request failed (${response.status})`
  } catch {
    return `Request failed (${response.status})`
  }
}

async function expectJson<T>(response: Response): Promise<T> {
  if (!response.ok) throw new Error(await readError(response))
  return response.json() as Promise<T>
}

function decodeRfc5987(value: string): string | null {
  const match = /^(?:UTF-8|utf-8)''(.+)$/.exec(value.trim().replace(/^"|"$/g, ''))
  if (!match) return null
  try {
    return decodeURIComponent(match[1])
  } catch {
    return null
  }
}

function parseDownloadFilename(disposition: string, fallback: string): string {
  const extended = /filename\*\s*=\s*([^;]+)/i.exec(disposition)
  if (extended) {
    const decoded = decodeRfc5987(extended[1])
    if (decoded) return decoded
  }
  const basic = /filename\s*=\s*"?([^";]+)"?/i.exec(disposition)
  return basic?.[1] ?? fallback
}

export async function getStyles(signal?: AbortSignal): Promise<StylePreset[]> {
  return expectJson(await request(`${API_ROOT}/styles`, { signal }, 'Could not reach the MapToPoster server. Please retry.'))
}

export async function searchPlaces(query: string, signal?: AbortSignal): Promise<LocationResult[]> {
  const params = new URLSearchParams({ q: query, lang: navigator.language.startsWith('zh') ? 'cn' : 'en' })
  return expectJson(await request(`${API_ROOT}/locations/search?${params}`, { signal }, 'Place search was interrupted. Please retry.'))
}

export async function prepareMap(poster: PosterRequest, signal?: AbortSignal): Promise<{ map_data_id: string; cache_hit: boolean }> {
  return expectJson(await request(`${API_ROOT}/map-data/prepare`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(poster),
    signal,
  }, 'The map request was interrupted. Please retry or zoom in to a smaller area.'))
}

export async function renderPreview(mapDataId: string, poster: PosterRequest, signal?: AbortSignal): Promise<Blob> {
  const response = await request(`${API_ROOT}/posters/preview`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ map_data_id: mapDataId, poster }),
    signal,
  }, 'The preview connection was interrupted. Please retry.')
  if (!response.ok) throw new Error(await readError(response))
  return response.blob()
}

export async function exportPoster(mapDataId: string, poster: PosterRequest, format: 'png' | 'svg' | 'pdf', dpi: number, signal?: AbortSignal): Promise<{ blob: Blob; filename: string }> {
  const response = await request(`${API_ROOT}/posters/export`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ map_data_id: mapDataId, poster, format, dpi }),
    signal,
  }, `The ${format.toUpperCase()} export connection was interrupted. Please retry.`)
  if (!response.ok) throw new Error(await readError(response))
  const disposition = response.headers.get('Content-Disposition') ?? ''
  const filename = parseDownloadFilename(disposition, `maptoposter.${format}`)
  return { blob: await response.blob(), filename }
}