The desktop app reads the folder locally and only asks the server for a name. A photo already read is not read again. While a folder is still read on the server, face processes keep being added until the CPU is full.
989 lines
43 KiB
TypeScript
989 lines
43 KiB
TypeScript
import type { BundleInput, BundleSummary, PressAccountInput, PressAccountSummary, PressStatement, NotificationView, AffiliateInput, AffiliateSummary, EarningsOverview, EarningsSettings, MemberPayoutInput, MyEarnings, PayeeAccount, PayoutInput, PayoutView, CodeGeneratorSettings, CodeLine, ConfirmFaceGroup, DeliveryItemSummary, DevelopState, EditLogEntry, FaceGroupSummary, GalleryInput, GalleryPhotosChange, GallerySummary, Module, OrderView, PhotoPatch, PhotoSummary, PostEdits, PrinterSummary, PrintEventInput, PrintEventSummary, PrintJobSummary, ProductInput, ProofingReport, ProductSummary, SiteInfo, SiteInput, StationSummary } from "@photoreport/contracts";
|
|
import type { AgendaEntry, ArchiveStorage, CardScan, FaceIdentify, CloudFolderSummary, CloudSource, InvoiceSummary, AutopilotStyle, DeliveryTarget, DeliveryTargetInput, JerseySample, JerseyStats, PersonSummary, PhotoFace, PhotoLookup, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, FtpPlan, EventInput, EventSquads, EventSummary, FtpTargetAccount, IptcIssue, SportsCompetition, SportsFixture, SportsPlayer, SportsTeam, Me, Member, PhotoQuery, Role, ZerozeroGame } from "./types.js";
|
|
|
|
/**
|
|
* Where the refresh token lives. The web app leaves it in an httpOnly cookie (no store); the desktop app keeps it
|
|
* in the OS keychain through Tauri.
|
|
*/
|
|
export interface RefreshTokenStore {
|
|
get(): Promise<string | null>;
|
|
set(token: string): Promise<void>;
|
|
clear(): Promise<void>;
|
|
}
|
|
|
|
/** True when a JWT expires within `seconds` (or cannot be read). Reads the payload only, no verification. */
|
|
export function expiresWithin(token: string, seconds: number, now = Date.now()): boolean {
|
|
try {
|
|
const payload = token.split(".")[1] ?? "";
|
|
const json = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/"))) as { exp?: number };
|
|
return typeof json.exp !== "number" || json.exp * 1000 - now < seconds * 1000;
|
|
} catch {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
export class ApiError extends Error {
|
|
constructor(
|
|
readonly status: number,
|
|
readonly code: string,
|
|
readonly body: unknown,
|
|
) {
|
|
super(code);
|
|
}
|
|
}
|
|
|
|
interface TokenResponse {
|
|
accessToken: string;
|
|
expiresIn: number;
|
|
refreshToken?: string;
|
|
}
|
|
|
|
export type DevicePollResult =
|
|
| { status: "approved" }
|
|
| { status: "pending" | "slow_down" }
|
|
| { status: "expired" | "denied" | "invalid" };
|
|
|
|
export interface ApiClientOptions {
|
|
baseUrl: string;
|
|
/** Present on desktop; absent on web (cookie). */
|
|
refreshStore?: RefreshTokenStore;
|
|
fetch?: typeof fetch;
|
|
onSessionLost?: () => void;
|
|
}
|
|
|
|
export class ApiClient {
|
|
private accessToken: string | null = null;
|
|
private refreshing: Promise<boolean> | null = null;
|
|
private readonly fetchImpl: typeof fetch;
|
|
|
|
constructor(private readonly opts: ApiClientOptions) {
|
|
this.fetchImpl = opts.fetch ?? globalThis.fetch.bind(globalThis);
|
|
}
|
|
|
|
get client(): "web" | "desktop" {
|
|
return this.opts.refreshStore ? "desktop" : "web";
|
|
}
|
|
|
|
get isAuthenticated(): boolean {
|
|
return this.accessToken !== null;
|
|
}
|
|
|
|
get baseUrl(): string {
|
|
return this.opts.baseUrl;
|
|
}
|
|
|
|
/** Absolute URL for an API path such as a signed photo URL. */
|
|
absolute(path: string): string {
|
|
return path.startsWith("http") || path.startsWith("blob:") || path.startsWith("data:") ? path : `${this.opts.baseUrl}${path}`;
|
|
}
|
|
|
|
/**
|
|
* An access token valid for at least another minute, for connections the client makes itself (realtime,
|
|
* uploads with progress through XMLHttpRequest).
|
|
*/
|
|
async realtimeToken(): Promise<string> {
|
|
if ((!this.accessToken || expiresWithin(this.accessToken, 60)) && !(await this.refresh())) throw new ApiError(401, "not_signed_in", null);
|
|
return this.accessToken as string;
|
|
}
|
|
|
|
// ---- originals kept on a desktop -----------------------------------------------------------------------
|
|
|
|
/** Asks the desktop app that keeps this photo's original to send it. `stored: true` when it is already here. */
|
|
requestOriginal(photoId: string): Promise<{ stored: boolean }> {
|
|
return this.request("POST", `/v1/photos/${photoId}/original/request`);
|
|
}
|
|
|
|
/**
|
|
* Desktop app: the original of a photo that only has its preview on the server, when the file here changed since
|
|
* it arrived (captions written into it by another app). Refused (409 `not_the_same_photo`) when it is not.
|
|
*/
|
|
sendOriginal(photoId: string, file: Blob, name = "original.jpg") {
|
|
const form = new FormData();
|
|
form.append("file", file, name);
|
|
return this.request<{ stored: boolean }>("POST", `/v1/photos/${photoId}/original`, form);
|
|
}
|
|
|
|
/** Desktop app: takes the deliveries waiting for this computer's folders (rendered on the server). */
|
|
claimLocalDeliveries(orgId: string, machine: string) {
|
|
return this.request<{ items: { id: string; folder: string; path: string; byteSize: number | null }[] }>("POST", `/v1/orgs/${orgId}/deliveries/local/claim`, { machine });
|
|
}
|
|
|
|
/** The rendered file of a delivery this computer took. */
|
|
async localDeliveryFile(orgId: string, itemId: string): Promise<ArrayBuffer> {
|
|
const res = await this.fetchImpl(this.absolute(`/v1/orgs/${orgId}/deliveries/${itemId}/local-file`), {
|
|
headers: { authorization: `Bearer ${await this.realtimeToken()}` },
|
|
credentials: "include",
|
|
});
|
|
if (!res.ok) throw new ApiError(res.status, `http_${res.status}`, null);
|
|
return res.arrayBuffer();
|
|
}
|
|
|
|
/** Saved (and where), or why not. */
|
|
localDeliveryResult(orgId: string, itemId: string, result: { ok: boolean; path?: string; error?: string }) {
|
|
return this.request<DeliveryItemSummary>("POST", `/v1/orgs/${orgId}/deliveries/${itemId}/local-result`, result);
|
|
}
|
|
|
|
/** The full-resolution original, or null while it is still only on the photographer's computer. */
|
|
async originalBytes(photoId: string): Promise<ArrayBuffer | null> {
|
|
const res = await this.fetchImpl(this.absolute(`/v1/photos/${photoId}/original`), {
|
|
headers: { authorization: `Bearer ${await this.realtimeToken()}` },
|
|
credentials: "include",
|
|
});
|
|
if (res.status === 409) return null;
|
|
if (!res.ok) throw new ApiError(res.status, `http_${res.status}`, null);
|
|
return res.arrayBuffer();
|
|
}
|
|
|
|
// ---- auth -------------------------------------------------------------------------------------------
|
|
|
|
async login(email: string, password: string, deviceLabel?: string): Promise<void> {
|
|
const tokens = await this.raw<TokenResponse>("POST", "/v1/auth/login", {
|
|
email,
|
|
password,
|
|
client: this.client,
|
|
...(deviceLabel ? { deviceLabel } : {}),
|
|
});
|
|
await this.acceptTokens(tokens);
|
|
}
|
|
|
|
/** Restores a session from the cookie (web) or keychain (desktop). Returns false when signed out. */
|
|
async resume(): Promise<boolean> {
|
|
return this.refresh();
|
|
}
|
|
|
|
async logout(): Promise<void> {
|
|
const refreshToken = await this.opts.refreshStore?.get();
|
|
try {
|
|
await this.raw("POST", "/v1/auth/logout", refreshToken ? { refreshToken } : {});
|
|
} finally {
|
|
this.accessToken = null;
|
|
await this.opts.refreshStore?.clear();
|
|
}
|
|
}
|
|
|
|
/** Desktop sign-in through the browser: start, then poll until the user approves on the web. */
|
|
startDeviceLogin(clientLabel?: string): Promise<DeviceGrant> {
|
|
return this.raw<DeviceGrant>("POST", "/v1/auth/device", clientLabel ? { clientLabel } : {});
|
|
}
|
|
|
|
async pollDeviceLogin(deviceCode: string): Promise<DevicePollResult> {
|
|
try {
|
|
await this.acceptTokens(await this.raw<TokenResponse>("POST", "/v1/auth/device/token", { deviceCode }));
|
|
return { status: "approved" };
|
|
} catch (err) {
|
|
if (!(err instanceof ApiError) || err.status !== 400) throw err;
|
|
switch (err.code) {
|
|
case "authorization_pending":
|
|
return { status: "pending" };
|
|
case "slow_down":
|
|
return { status: "slow_down" };
|
|
case "expired_token":
|
|
return { status: "expired" };
|
|
case "access_denied":
|
|
return { status: "denied" };
|
|
default:
|
|
return { status: "invalid" };
|
|
}
|
|
}
|
|
}
|
|
|
|
getDeviceGrant(userCode: string) {
|
|
return this.request<{ userCode: string; clientLabel: string | null; expiresAt: string }>(
|
|
"GET",
|
|
`/v1/auth/device/${encodeURIComponent(userCode)}`,
|
|
);
|
|
}
|
|
|
|
approveDevice(userCode: string, approve: boolean) {
|
|
return this.request<{ ok: true; approved: boolean }>("POST", "/v1/auth/device/approve", { userCode, approve });
|
|
}
|
|
|
|
// ---- account ----------------------------------------------------------------------------------------
|
|
|
|
me(): Promise<Me> {
|
|
return this.request<Me>("GET", "/v1/me");
|
|
}
|
|
|
|
updateEditorModules(editorModules: Module[]) {
|
|
return this.request<{ editorModules: Module[] }>("PUT", "/v1/me/preferences", { editorModules });
|
|
}
|
|
|
|
/** Whether the person connected their calendar (its secret iCal address). */
|
|
calendarStatus() {
|
|
return this.request<{ connected: boolean }>("GET", "/v1/me/calendar");
|
|
}
|
|
|
|
/** Connect a calendar by its secret iCal address (checked first), or forget it with null. */
|
|
connectCalendar(url: string | null) {
|
|
return this.request<{ connected: boolean; events: number }>("PUT", "/v1/me/calendar", { url });
|
|
}
|
|
|
|
/** The agenda entries of one day ("YYYY-MM-DD", Lisbon; default today). */
|
|
agenda(date?: string) {
|
|
return this.request<{ date: string; events: AgendaEntry[] }>("GET", `/v1/me/calendar/events${date ? `?date=${date}` : ""}`);
|
|
}
|
|
|
|
// ---- organizations ----------------------------------------------------------------------------------
|
|
|
|
listMembers(orgId: string): Promise<Member[]> {
|
|
return this.request<Member[]>("GET", `/v1/orgs/${orgId}/members`);
|
|
}
|
|
|
|
addMember(orgId: string, input: { email: string; role: Role; name?: string; password?: string }) {
|
|
return this.request<Member>("POST", `/v1/orgs/${orgId}/members`, input);
|
|
}
|
|
|
|
updateMemberRole(orgId: string, userId: string, role: Role) {
|
|
return this.request<{ userId: string; role: Role }>("PATCH", `/v1/orgs/${orgId}/members/${userId}`, { role });
|
|
}
|
|
|
|
listPeople(orgId: string) {
|
|
return this.request<{ people: { id: string; name: string; role: Role }[] }>("GET", `/v1/orgs/${orgId}/people`);
|
|
}
|
|
|
|
removeMember(orgId: string, userId: string) {
|
|
return this.request<void>("DELETE", `/v1/orgs/${orgId}/members/${userId}`);
|
|
}
|
|
|
|
// ---- library ---------------------------------------------------------------------------------------
|
|
|
|
listEvents(orgId: string, opts: { includeArchived?: boolean; archived?: boolean } = {}) {
|
|
const q = opts.archived ? "?archived=true" : opts.includeArchived ? "?includeArchived=true" : "";
|
|
return this.request<{ events: EventSummary[]; inboxCount: number }>("GET", `/v1/orgs/${orgId}/events${q}`);
|
|
}
|
|
|
|
createEvent(orgId: string, input: EventInput) {
|
|
return this.request<EventSummary>("POST", `/v1/orgs/${orgId}/events`, input);
|
|
}
|
|
|
|
updateEvent(eventId: string, input: Partial<EventInput> & { archived?: boolean }) {
|
|
return this.request<EventSummary>("PATCH", `/v1/events/${eventId}`, input);
|
|
}
|
|
|
|
/** Deletes the event; its photos go back to "Sem evento". */
|
|
deleteEvent(eventId: string) {
|
|
return this.request<{ deleted: string; photos: number }>("DELETE", `/v1/events/${eventId}`);
|
|
}
|
|
|
|
/** The FTP logins one may point at this event, and where each sends its photos now. */
|
|
ftpTargets(eventId: string) {
|
|
return this.request<{ accounts: FtpTargetAccount[] }>("GET", `/v1/events/${eventId}/ftp-target`);
|
|
}
|
|
|
|
/** "Receber FTP aqui": these logins send everything to this event until `until` (null: until switched off). */
|
|
setFtpTarget(eventId: string, input: { accountIds: string[]; until?: string | null }) {
|
|
return this.request<EventSummary>("PUT", `/v1/events/${eventId}/ftp-target`, input);
|
|
}
|
|
|
|
// ---- sports data ----------------------------------------------------------------------------------------
|
|
|
|
sportsCompetitions() {
|
|
return this.request<{ competitions: SportsCompetition[] }>("GET", "/v1/sports/competitions");
|
|
}
|
|
|
|
/** Follow an FPF competition by its resultados.fpf.pt link (admins). */
|
|
addFpfCompetition(url: string) {
|
|
return this.request<{ competition: SportsCompetition }>("POST", "/v1/sports/competitions", { url });
|
|
}
|
|
|
|
refreshSportsCompetition(id: string) {
|
|
return this.request<{ competitions: number; teams: number; players: number; fixtures: number; errors: string[] }>("POST", `/v1/sports/competitions/${id}/refresh`);
|
|
}
|
|
|
|
sportsTeams(query: { competitionId?: string; q?: string } = {}) {
|
|
const params = new URLSearchParams(Object.entries(query).filter(([, v]) => v) as [string, string][]);
|
|
return this.request<{ teams: SportsTeam[] }>("GET", `/v1/sports/teams${params.size ? `?${params}` : ""}`);
|
|
}
|
|
|
|
sportsPlayers(teamId: string) {
|
|
return this.request<{ players: SportsPlayer[] }>("GET", `/v1/sports/teams/${teamId}/players`);
|
|
}
|
|
|
|
sportsFixtures(query: { from?: string; to?: string; q?: string; sport?: string; competitionId?: string } = {}) {
|
|
const params = new URLSearchParams(Object.entries(query).filter(([, v]) => v) as [string, string][]);
|
|
return this.request<{ fixtures: SportsFixture[] }>("GET", `/v1/sports/fixtures${params.size ? `?${params}` : ""}`);
|
|
}
|
|
|
|
codeGenerator(orgId: string) {
|
|
return this.request<{ settings: CodeGeneratorSettings; presets: readonly { id: string; label: string; template: string }[] }>("GET", `/v1/orgs/${orgId}/code-generator`);
|
|
}
|
|
|
|
saveCodeGenerator(orgId: string, settings: CodeGeneratorSettings) {
|
|
return this.request<{ settings: CodeGeneratorSettings }>("PUT", `/v1/orgs/${orgId}/code-generator`, settings);
|
|
}
|
|
|
|
previewCodes(orgId: string, settings?: CodeGeneratorSettings) {
|
|
return this.request<{ lines: CodeLine[]; clashes: { code: string; values: string[] }[]; teams: number; tsv: string; csv: string }>(
|
|
"POST",
|
|
`/v1/orgs/${orgId}/code-generator/preview`,
|
|
settings ?? {},
|
|
);
|
|
}
|
|
|
|
applyCodes(orgId: string, settings?: CodeGeneratorSettings) {
|
|
return this.request<{ generated: number; teams: number; entries: number; clashes: { code: string; values: string[] }[]; issues: { line: number; message: string }[] }>(
|
|
"POST",
|
|
`/v1/orgs/${orgId}/code-generator/apply`,
|
|
settings ?? {},
|
|
);
|
|
}
|
|
|
|
eventSquads(eventId: string) {
|
|
return this.request<EventSquads>("GET", `/v1/events/${eventId}/squads`);
|
|
}
|
|
|
|
syncEventSquads(eventId: string) {
|
|
return this.request<{ created: number; updated: number; headshots: number }>("POST", `/v1/events/${eventId}/squads/sync`);
|
|
}
|
|
|
|
listPhotos(orgId: string, query: PhotoQuery = {}) {
|
|
const params = new URLSearchParams();
|
|
for (const [key, value] of Object.entries(query)) if (value !== undefined) params.set(key, String(value));
|
|
const qs = params.size ? `?${params}` : "";
|
|
return this.request<{ total: number; offset: number; photos: PhotoSummary[] }>("GET", `/v1/orgs/${orgId}/photos${qs}`);
|
|
}
|
|
|
|
updatePhotos(orgId: string, ids: string[], patch: PhotoPatch) {
|
|
return this.request<{ updated: number }>("PATCH", `/v1/orgs/${orgId}/photos`, { ids, patch });
|
|
}
|
|
|
|
photoIptc(photoId: string) {
|
|
return this.request<{
|
|
values: Record<string, string | string[]>;
|
|
issues: IptcIssue[];
|
|
embedded: Record<string, string | string[]> | null;
|
|
/** What this photo sets on top of its event's template (the Info window), and the template itself. */
|
|
overrides?: Record<string, string | string[]>;
|
|
template?: Record<string, string | string[]>;
|
|
}>("GET", `/v1/photos/${photoId}/iptc`);
|
|
}
|
|
|
|
/** Sets IPTC fields on many photos; null puts a field back to the event's template. */
|
|
setPhotosIptc(orgId: string, ids: string[], set: Record<string, string | string[] | null>) {
|
|
return this.request<{ updated: number }>("PUT", `/v1/orgs/${orgId}/photos/iptc`, { ids, set });
|
|
}
|
|
|
|
getCodeList(orgId: string) {
|
|
return this.request<{ content: string; issues: { line: number; message: string }[] }>("GET", `/v1/orgs/${orgId}/code-list`);
|
|
}
|
|
|
|
saveCodeList(orgId: string, content: string) {
|
|
return this.request<{ content: string; entries: number; issues: { line: number; message: string }[] }>("PUT", `/v1/orgs/${orgId}/code-list`, { content });
|
|
}
|
|
|
|
// ---- shop -------------------------------------------------------------------------------------------
|
|
|
|
listGalleries(orgId: string) {
|
|
return this.request<{ galleries: GallerySummary[] }>("GET", `/v1/orgs/${orgId}/galleries`);
|
|
}
|
|
|
|
createGallery(orgId: string, input: GalleryInput) {
|
|
return this.request<GallerySummary>("POST", `/v1/orgs/${orgId}/galleries`, input);
|
|
}
|
|
|
|
updateGallery(id: string, input: Partial<GalleryInput>) {
|
|
return this.request<GallerySummary>("PATCH", `/v1/galleries/${id}`, input);
|
|
}
|
|
|
|
deleteGallery(id: string) {
|
|
return this.request<void>("DELETE", `/v1/galleries/${id}`);
|
|
}
|
|
|
|
changeGalleryPhotos(id: string, change: Partial<GalleryPhotosChange>) {
|
|
return this.request<GallerySummary>("POST", `/v1/galleries/${id}/photos`, { add: [], remove: [], ...change });
|
|
}
|
|
|
|
galleryPhotoIds(id: string) {
|
|
return this.request<{ photoIds: string[] }>("GET", `/v1/galleries/${id}/photos`);
|
|
}
|
|
|
|
/** Clients' favourites and comments on a gallery. */
|
|
proofingReport(galleryId: string) {
|
|
return this.request<ProofingReport>("GET", `/v1/galleries/${galleryId}/proofing`);
|
|
}
|
|
|
|
moderateComment(commentId: string, status: "PENDING" | "APPROVED" | "REJECTED") {
|
|
return this.request<{ id: string; status: string }>("PATCH", `/v1/gallery-comments/${commentId}`, { status });
|
|
}
|
|
|
|
/** Colour-labels the favourites in the library (all visitors, or one). */
|
|
labelFavorites(galleryId: string, label: "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE", visitorId?: string) {
|
|
return this.request<{ labelled: number }>("POST", `/v1/galleries/${galleryId}/proofing/label`, { label, ...(visitorId && { visitorId }) });
|
|
}
|
|
|
|
/** What the autopilot learnt from a photographer's corrections (default: the signed-in user). */
|
|
autopilotStyle(orgId: string, venue?: string | null) {
|
|
return this.request<{ photographerId: string; style: AutopilotStyle | null }>("GET", `/v1/orgs/${orgId}/autopilot/style${venue ? `?venue=${encodeURIComponent(venue)}` : ""}`);
|
|
}
|
|
|
|
forgetAutopilotStyle(orgId: string) {
|
|
return this.request<{ forgotten: number }>("DELETE", `/v1/orgs/${orgId}/autopilot/style`);
|
|
}
|
|
|
|
publishGallery(id: string, published: boolean) {
|
|
return this.request<GallerySummary>("POST", `/v1/galleries/${id}/publish`, { published });
|
|
}
|
|
|
|
// ---- notifications ----
|
|
|
|
notifications(opts: { unread?: boolean; limit?: number } = {}) {
|
|
const q = new URLSearchParams({ ...(opts.unread && { unread: "1" }), ...(opts.limit && { limit: String(opts.limit) }) }).toString();
|
|
return this.request<{ unreadCount: number; notifications: NotificationView[] }>("GET", `/v1/me/notifications${q ? `?${q}` : ""}`);
|
|
}
|
|
|
|
markNotificationRead(id: string | "all") {
|
|
return this.request<{ marked: number }>("POST", `/v1/me/notifications/${id}/read`);
|
|
}
|
|
|
|
// ---- earnings: photographer shares, affiliates, payouts ----
|
|
|
|
earnings(orgId: string) {
|
|
return this.request<EarningsOverview>("GET", `/v1/orgs/${orgId}/earnings`);
|
|
}
|
|
|
|
saveEarningsSettings(orgId: string, settings: EarningsSettings) {
|
|
return this.request<EarningsOverview["settings"]>("PUT", `/v1/orgs/${orgId}/earnings/settings`, settings);
|
|
}
|
|
|
|
setMemberPayout(orgId: string, userId: string, input: MemberPayoutInput) {
|
|
return this.request<{ sharePct: number | null; account: PayeeAccount }>("PATCH", `/v1/orgs/${orgId}/members/${userId}/payout`, input);
|
|
}
|
|
|
|
pay(orgId: string, input: PayoutInput) {
|
|
return this.request<PayoutView>("POST", `/v1/orgs/${orgId}/payouts`, input);
|
|
}
|
|
|
|
retryPayout(id: string) {
|
|
return this.request<PayoutView>("POST", `/v1/payouts/${id}/retry`);
|
|
}
|
|
|
|
markRefunded(orderId: string) {
|
|
return this.request<{ cancelled: number; alreadyPaid: number }>("POST", `/v1/orders/${orderId}/refunded`);
|
|
}
|
|
|
|
listAffiliates(orgId: string) {
|
|
return this.request<{ affiliates: AffiliateSummary[] }>("GET", `/v1/orgs/${orgId}/affiliates`);
|
|
}
|
|
|
|
createAffiliate(orgId: string, input: Partial<AffiliateInput> & Pick<AffiliateInput, "name" | "code">) {
|
|
return this.request<AffiliateSummary>("POST", `/v1/orgs/${orgId}/affiliates`, input);
|
|
}
|
|
|
|
updateAffiliate(id: string, patch: Partial<AffiliateInput>) {
|
|
return this.request<AffiliateSummary>("PATCH", `/v1/affiliates/${id}`, patch);
|
|
}
|
|
|
|
/** Stripe's onboarding page for your own payouts account (or an affiliate's, for admins). */
|
|
connectLink(orgId: string, affiliateId?: string) {
|
|
return this.request<{ url: string }>("POST", `/v1/orgs/${orgId}/connect`, affiliateId ? { affiliateId } : {});
|
|
}
|
|
|
|
refreshConnect(orgId: string, affiliateId?: string) {
|
|
return this.request<{ ready: boolean }>("POST", `/v1/orgs/${orgId}/connect/refresh`, affiliateId ? { affiliateId } : {});
|
|
}
|
|
|
|
myEarnings(orgId: string) {
|
|
return this.request<MyEarnings>("GET", `/v1/orgs/${orgId}/my-earnings`);
|
|
}
|
|
|
|
setMyIban(orgId: string, payoutIban: string | null) {
|
|
return this.request<PayeeAccount>("PUT", `/v1/orgs/${orgId}/my-earnings/iban`, { payoutIban });
|
|
}
|
|
|
|
listProducts(orgId: string) {
|
|
return this.request<{ products: ProductSummary[] }>("GET", `/v1/orgs/${orgId}/products`);
|
|
}
|
|
|
|
createProduct(orgId: string, input: ProductInput) {
|
|
return this.request<ProductSummary>("POST", `/v1/orgs/${orgId}/products`, input);
|
|
}
|
|
|
|
updateProduct(id: string, patch: Partial<Pick<ProductSummary, "name" | "priceCents" | "active" | "position" | "leadDays" | "longEdge" | "printSize">>) {
|
|
return this.request<ProductSummary>("PATCH", `/v1/products/${id}`, patch);
|
|
}
|
|
|
|
deleteProduct(id: string) {
|
|
return this.request<void>("DELETE", `/v1/products/${id}`);
|
|
}
|
|
|
|
listSites(orgId: string) {
|
|
return this.request<{ sites: SiteInfo[] }>("GET", `/v1/orgs/${orgId}/sites`);
|
|
}
|
|
|
|
createSite(orgId: string, input: SiteInput) {
|
|
return this.request<SiteInfo>("POST", `/v1/orgs/${orgId}/sites`, input);
|
|
}
|
|
|
|
updateSite(id: string, input: Partial<SiteInput>) {
|
|
return this.request<SiteInfo>("PATCH", `/v1/sites/${id}`, input);
|
|
}
|
|
|
|
deleteSite(id: string) {
|
|
return this.request<void>("DELETE", `/v1/sites/${id}`);
|
|
}
|
|
|
|
listOrders(orgId: string, status?: OrderView["status"]) {
|
|
return this.request<{ orders: OrderView[] }>("GET", `/v1/orgs/${orgId}/orders${status ? `?status=${status}` : ""}`);
|
|
}
|
|
|
|
markShipped(orderId: string, itemId: string) {
|
|
return this.request<OrderView>("POST", `/v1/orders/${orderId}/items/${itemId}/shipped`);
|
|
}
|
|
|
|
retryOrder(orderId: string) {
|
|
return this.request<OrderView>("POST", `/v1/orders/${orderId}/retry`);
|
|
}
|
|
|
|
getShopSettings(orgId: string) {
|
|
return this.request<ShopSettings>("GET", `/v1/orgs/${orgId}/shop-settings`);
|
|
}
|
|
|
|
updateShopSettings(
|
|
orgId: string,
|
|
input: Partial<{ legalName: string | null; vatNumber: string | null; country: string; vatRate: number; stripeSecretKey: string; stripeWebhookSecret: string; invoicingProvider: "none" | "invoicexpress"; invoicingAccount: string | null; invoicingApiKey: string; invoicingEmail: boolean; reverseChargeCode: string; maxDownloads: number }>,
|
|
) {
|
|
return this.request<{ ok: true }>("PUT", `/v1/orgs/${orgId}/shop-settings`, input);
|
|
}
|
|
|
|
listBundles(orgId: string) {
|
|
return this.request<{ bundles: BundleSummary[] }>("GET", `/v1/orgs/${orgId}/bundles`);
|
|
}
|
|
|
|
createBundle(orgId: string, input: Partial<BundleInput> & Pick<BundleInput, "name" | "productId" | "photoCount" | "priceCents">) {
|
|
return this.request<BundleSummary>("POST", `/v1/orgs/${orgId}/bundles`, input);
|
|
}
|
|
|
|
updateBundle(id: string, patch: Partial<BundleInput>) {
|
|
return this.request<BundleSummary>("PATCH", `/v1/bundles/${id}`, patch);
|
|
}
|
|
|
|
deleteBundle(id: string) {
|
|
return this.request<void>("DELETE", `/v1/bundles/${id}`);
|
|
}
|
|
|
|
listPressAccounts(orgId: string) {
|
|
return this.request<{ period: string; accounts: PressAccountSummary[] }>("GET", `/v1/orgs/${orgId}/press-accounts`);
|
|
}
|
|
|
|
/** The new account and its password, shown this once. */
|
|
createPressAccount(orgId: string, input: Partial<PressAccountInput> & Pick<PressAccountInput, "name" | "email">) {
|
|
return this.request<{ account: PressAccountSummary; password: string }>("POST", `/v1/orgs/${orgId}/press-accounts`, input);
|
|
}
|
|
|
|
updatePressAccount(id: string, patch: Partial<PressAccountInput>) {
|
|
return this.request<PressAccountSummary>("PATCH", `/v1/press-accounts/${id}`, patch);
|
|
}
|
|
|
|
resetPressPassword(id: string) {
|
|
return this.request<{ password: string }>("POST", `/v1/press-accounts/${id}/password`);
|
|
}
|
|
|
|
pressStatements(id: string) {
|
|
return this.request<{ statements: PressStatement[] }>("GET", `/v1/press-accounts/${id}/statements`);
|
|
}
|
|
|
|
listInvoices(orgId: string, status?: InvoiceSummary["status"]) {
|
|
return this.request<{ invoices: InvoiceSummary[] }>("GET", `/v1/orgs/${orgId}/invoices${status ? `?status=${status}` : ""}`);
|
|
}
|
|
|
|
retryInvoice(id: string) {
|
|
return this.request<InvoiceSummary>("POST", `/v1/invoices/${id}/retry`);
|
|
}
|
|
|
|
checkInvoicing(orgId: string) {
|
|
return this.request<{ ok: true }>("POST", `/v1/orgs/${orgId}/invoicing/check`);
|
|
}
|
|
|
|
/** Across events: names, teams, competition, file name, dates, or a person (with face suggestions apart). */
|
|
search(orgId: string, q: { q?: string; personId?: string; from?: string; to?: string; limit?: number }) {
|
|
const params = new URLSearchParams(Object.entries(q).filter(([, v]) => v !== undefined && v !== "").map(([k, v]) => [k, String(v)]));
|
|
return this.request<{ photos: PhotoSummary[]; suggested: PhotoSummary[]; total: number }>("GET", `/v1/orgs/${orgId}/search?${params}`);
|
|
}
|
|
|
|
// ---- shirt numbers (training data) -------------------------------------------------------------------
|
|
|
|
jerseySamples(orgId: string, status: JerseySample["status"] = "PENDING", limit = 60) {
|
|
return this.request<{ collected: number; samples: JerseySample[]; stats: JerseyStats }>("GET", `/v1/orgs/${orgId}/jersey/samples?status=${status}&limit=${limit}`);
|
|
}
|
|
|
|
reviewJerseySample(id: string, status: JerseySample["status"], label?: string | null) {
|
|
return this.request<JerseySample>("POST", `/v1/jersey/samples/${id}/review`, { status, ...(label !== undefined && { label }) });
|
|
}
|
|
|
|
/** Teaching starts over: every answer is dropped, the samples are to review again. */
|
|
resetJerseySamples(orgId: string) {
|
|
return this.request<{ reset: number }>("POST", `/v1/orgs/${orgId}/jersey/reset`);
|
|
}
|
|
|
|
/** The checked dataset as a JSON file (crops by signed URL), for workers/ml/jersey. */
|
|
jerseyDatasetUrl(orgId: string) {
|
|
return `/v1/orgs/${orgId}/jersey/dataset`;
|
|
}
|
|
|
|
// ---- printing ---------------------------------------------------------------------------------------
|
|
|
|
listPrintEvents(orgId: string) {
|
|
return this.request<{ events: PrintEventSummary[] }>("GET", `/v1/orgs/${orgId}/print-events`);
|
|
}
|
|
|
|
createPrintEvent(orgId: string, input: PrintEventInput) {
|
|
return this.request<PrintEventSummary>("POST", `/v1/orgs/${orgId}/print-events`, input);
|
|
}
|
|
|
|
/** A new kiosk link (path with its secret, shown once); the previous one stops working. */
|
|
enablePrintKiosk(id: string) {
|
|
return this.request<{ path: string }>("POST", `/v1/print-events/${id}/kiosk`);
|
|
}
|
|
|
|
disablePrintKiosk(id: string) {
|
|
return this.request<void>("DELETE", `/v1/print-events/${id}/kiosk`);
|
|
}
|
|
|
|
updatePrintEvent(id: string, input: Partial<PrintEventInput>) {
|
|
return this.request<PrintEventSummary>("PATCH", `/v1/print-events/${id}`, input);
|
|
}
|
|
|
|
printJobs(eventId: string) {
|
|
return this.request<{ jobs: PrintJobSummary[] }>("GET", `/v1/print-events/${eventId}/jobs`);
|
|
}
|
|
|
|
printPhotos(eventId: string, photoIds: string[], copies = 1) {
|
|
return this.request<{ jobs: PrintJobSummary[] }>("POST", `/v1/print-events/${eventId}/jobs`, { photoIds, copies });
|
|
}
|
|
|
|
printJobAction(jobId: string, action: "approve" | "cancel" | "reprint", printerId?: string | null) {
|
|
return this.request<PrintJobSummary>("POST", `/v1/print-jobs/${jobId}/${action}`, printerId !== undefined ? { printerId } : {});
|
|
}
|
|
|
|
listPrinters(orgId: string) {
|
|
return this.request<{ printers: PrinterSummary[]; stations: StationSummary[] }>("GET", `/v1/orgs/${orgId}/printers`);
|
|
}
|
|
|
|
updatePrinter(id: string, patch: Partial<Pick<PrinterSummary, "name" | "sizes" | "enabled">>) {
|
|
return this.request<PrinterSummary>("PATCH", `/v1/printers/${id}`, patch);
|
|
}
|
|
|
|
createStation(orgId: string, name: string) {
|
|
return this.request<{ station: StationSummary; code: string }>("POST", `/v1/orgs/${orgId}/print-stations`, { name });
|
|
}
|
|
|
|
stationPairingCode(stationId: string) {
|
|
return this.request<{ code: string }>("POST", `/v1/print-stations/${stationId}/pairing-code`);
|
|
}
|
|
|
|
// ---- develop ----------------------------------------------------------------------------------------
|
|
|
|
/** Snapshot plus the ops after it; with `since`, only the ops after that op-log position. */
|
|
developState(photoId: string, since?: number) {
|
|
return this.request<DevelopState>("GET", `/v1/photos/${photoId}/develop${since !== undefined ? `?since=${since}` : ""}`);
|
|
}
|
|
|
|
postEdits(photoId: string, body: PostEdits) {
|
|
return this.request<{ developSeq: number; ops: EditLogEntry[] }>("POST", `/v1/photos/${photoId}/edits`, body);
|
|
}
|
|
|
|
// ---- faces ------------------------------------------------------------------------------------------
|
|
|
|
faceGroups(eventId: string) {
|
|
return this.request<{ groups: FaceGroupSummary[]; pending: number; unclear: number; available?: boolean }>("GET", `/v1/events/${eventId}/face-groups`);
|
|
}
|
|
|
|
confirmFaceGroup(groupId: string, who: ConfirmFaceGroup) {
|
|
return this.request<{ person: PersonSummary }>("POST", `/v1/face-groups/${groupId}/confirm`, who);
|
|
}
|
|
|
|
mergeFaceGroups(groupId: string, into: string) {
|
|
return this.request<{ ok: true }>("POST", `/v1/face-groups/${groupId}/merge`, { into });
|
|
}
|
|
|
|
ignoreFaceGroup(groupId: string, ignored: boolean) {
|
|
return this.request<{ ok: true }>("POST", `/v1/face-groups/${groupId}/ignore`, { ignored });
|
|
}
|
|
|
|
photoFaces(photoId: string) {
|
|
return this.request<{ status: string; faces: PhotoFace[] }>("GET", `/v1/photos/${photoId}/faces`);
|
|
}
|
|
|
|
listPersons(orgId: string) {
|
|
return this.request<{ people: SquadPerson[] }>("GET", `/v1/orgs/${orgId}/persons`);
|
|
}
|
|
|
|
createPerson(orgId: string, person: { name: string; club?: string | null; number?: string | null }) {
|
|
return this.request<PersonSummary>("POST", `/v1/orgs/${orgId}/persons`, person);
|
|
}
|
|
|
|
updatePerson(personId: string, patch: { name?: string; club?: string | null; number?: string | null }) {
|
|
return this.request<PersonSummary>("PATCH", `/v1/persons/${personId}`, patch);
|
|
}
|
|
|
|
/** A photo from a card: faces and shirt numbers, compared with known people. The file is not stored. */
|
|
scanCard(orgId: string, file: Blob, eventId?: string) {
|
|
const form = new FormData();
|
|
form.append("file", file, "card.jpg");
|
|
return this.request<CardScan>("POST", `/v1/orgs/${orgId}/faces/scan${eventId ? `?eventId=${eventId}` : ""}`, form);
|
|
}
|
|
|
|
/** Names for faces already read on this computer. The photo is not uploaded. */
|
|
identifyFaces(orgId: string, input: { eventId?: string; model?: string; faces: { embedding: number[] }[] }) {
|
|
return this.request<FaceIdentify>("POST", `/v1/orgs/${orgId}/faces/identify`, input);
|
|
}
|
|
|
|
/**
|
|
* Search the library by a photo: who that face is and every photo with it (all events, or one). `face` picks
|
|
* another face of the photo (0: the largest). The photo is not kept on the server.
|
|
*/
|
|
lookupByPhoto(orgId: string, file: Blob, opts: { face?: number; eventId?: string } = {}) {
|
|
const form = new FormData();
|
|
form.append("file", file, "search.jpg");
|
|
const params = new URLSearchParams();
|
|
if (opts.face) params.set("face", String(opts.face));
|
|
if (opts.eventId) params.set("eventId", opts.eventId);
|
|
return this.request<PhotoLookup>("POST", `/v1/orgs/${orgId}/faces/lookup${params.size ? `?${params}` : ""}`, form);
|
|
}
|
|
|
|
/** Squad headshot: the worker reads the face so the person is suggested from their first match. */
|
|
setPersonReference(personId: string, file: Blob, name = "reference.jpg") {
|
|
const form = new FormData();
|
|
form.append("file", file, name);
|
|
return this.request<{ status: string; url: string }>("PUT", `/v1/persons/${personId}/reference`, form);
|
|
}
|
|
|
|
getBiometrics(orgId: string) {
|
|
return this.request<{ enabled: boolean; legalBasis: string | null }>("GET", `/v1/orgs/${orgId}/biometrics`);
|
|
}
|
|
|
|
setBiometrics(orgId: string, enabled: boolean, legalBasis?: string) {
|
|
return this.request<{ enabled: boolean; legalBasis: string | null }>("PUT", `/v1/orgs/${orgId}/biometrics`, { enabled, ...(legalBasis ? { legalBasis } : {}) });
|
|
}
|
|
|
|
analyseEventFaces(eventId: string) {
|
|
return this.request<{ queued: number }>("POST", `/v1/events/${eventId}/faces/analyse`);
|
|
}
|
|
|
|
// ---- archive (clouds) ------------------------------------------------------------------------------
|
|
|
|
listCloudSources(orgId: string) {
|
|
return this.request<{ sources: CloudSource[]; storage: ArchiveStorage | null }>("GET", `/v1/orgs/${orgId}/cloud-sources`);
|
|
}
|
|
|
|
/** Starts connecting a cloud: open `loginUrl` and poll `getCloudSource` until it is READY. */
|
|
connectCloud(orgId: string, input: { name: string; baseUrl: string; rootPath: string }) {
|
|
return this.request<CloudSource>("POST", `/v1/orgs/${orgId}/cloud-sources`, input);
|
|
}
|
|
|
|
getCloudSource(sourceId: string) {
|
|
return this.request<CloudSource>("GET", `/v1/cloud-sources/${sourceId}`);
|
|
}
|
|
|
|
reloginCloud(sourceId: string) {
|
|
return this.request<CloudSource>("POST", `/v1/cloud-sources/${sourceId}/login`);
|
|
}
|
|
|
|
updateCloudSource(sourceId: string, input: { name?: string; rootPath?: string; paused?: boolean; look?: "liga" | "fpa" | null }) {
|
|
return this.request<CloudSource>("PATCH", `/v1/cloud-sources/${sourceId}`, input);
|
|
}
|
|
|
|
scanCloudSource(sourceId: string) {
|
|
return this.request<CloudSource>("POST", `/v1/cloud-sources/${sourceId}/scan`);
|
|
}
|
|
|
|
/** Checks the cloud's galleries again now (official games by default, everything with `all`) and says what changed. */
|
|
rematchCloudSource(sourceId: string, all = false) {
|
|
return this.request<{ checked: number; moved: number; changes: { path: string; from: string | null; to: string | null }[]; errors: { path: string; error: string }[] }>(
|
|
"POST",
|
|
`/v1/cloud-sources/${sourceId}/rematch${all ? "?all=1" : ""}`,
|
|
);
|
|
}
|
|
|
|
deleteCloudSource(sourceId: string) {
|
|
return this.request<void>("DELETE", `/v1/cloud-sources/${sourceId}`);
|
|
}
|
|
|
|
listCloudFolders(sourceId: string, query: { state?: "all" | "games" | "named" | "events" | "unmatched" | "folders"; q?: string; limit?: number } = {}) {
|
|
const qs = new URLSearchParams(Object.entries(query).filter(([, v]) => v !== undefined && v !== "").map(([k, v]) => [k, String(v)]));
|
|
return this.request<{ folders: CloudFolderSummary[] }>("GET", `/v1/cloud-sources/${sourceId}/folders${qs.size ? `?${qs}` : ""}`);
|
|
}
|
|
|
|
setCloudFolderEvent(folderId: string, target: { eventId: string } | { fixtureId: string }) {
|
|
return this.request<Pick<CloudFolderSummary, "id" | "matchedBy" | "event">>("PUT", `/v1/cloud-folders/${folderId}/event`, target);
|
|
}
|
|
|
|
// ---- delivery --------------------------------------------------------------------------------------
|
|
|
|
listDeliveryTargets(orgId: string) {
|
|
return this.request<{ targets: DeliveryTarget[] }>("GET", `/v1/orgs/${orgId}/delivery-targets`);
|
|
}
|
|
|
|
createDeliveryTarget(orgId: string, input: DeliveryTargetInput) {
|
|
return this.request<DeliveryTarget & { example: { folder: string; fileName: string } }>("POST", `/v1/orgs/${orgId}/delivery-targets`, input);
|
|
}
|
|
|
|
/** A copy of a target with another name (and folder): same server and credentials. */
|
|
duplicateDeliveryTarget(orgId: string, targetId: string, input: { name: string; folderTemplate?: string }) {
|
|
return this.request<DeliveryTarget & { example: { folder: string; fileName: string } }>("POST", `/v1/orgs/${orgId}/delivery-targets/${targetId}/duplicate`, input);
|
|
}
|
|
|
|
/** Rename on arrival (Photo Mechanic's Live Ingest "Rename as"), for the organisation. */
|
|
renameTemplate(orgId: string) {
|
|
return this.request<{ template: string | null; example: string | null }>("GET", `/v1/orgs/${orgId}/rename-template`);
|
|
}
|
|
|
|
setRenameTemplate(orgId: string, template: string | null) {
|
|
return this.request<{ template: string | null; example: string | null }>("PUT", `/v1/orgs/${orgId}/rename-template`, { template });
|
|
}
|
|
|
|
previewRename(orgId: string, template: string) {
|
|
return this.request<{ example: string }>("POST", `/v1/orgs/${orgId}/rename-template/preview`, { template });
|
|
}
|
|
|
|
/** Connects with the saved settings; an SFTP server's host key is remembered on the first test. */
|
|
testDeliveryTarget(orgId: string, targetId: string) {
|
|
return this.request<{ ok: true; account?: string; fingerprint?: string }>("POST", `/v1/orgs/${orgId}/delivery-targets/${targetId}/test`);
|
|
}
|
|
|
|
updateDeliveryTarget(orgId: string, targetId: string, input: Partial<DeliveryTargetInput> & { disabled?: boolean; resetHostKey?: boolean }) {
|
|
return this.request<DeliveryTarget & { example: { folder: string; fileName: string } }>("PATCH", `/v1/orgs/${orgId}/delivery-targets/${targetId}`, input);
|
|
}
|
|
|
|
listFtpAccounts(orgId: string) {
|
|
return this.request<{ accounts: FtpAccount[] }>("GET", `/v1/orgs/${orgId}/ftp-accounts`);
|
|
}
|
|
|
|
listFtpPlans(orgId: string) {
|
|
return this.request<{ plans: FtpPlan[] }>("GET", `/v1/orgs/${orgId}/ftp-plans`);
|
|
}
|
|
|
|
createFtpPlan(orgId: string, input: { name: string; description?: string | null; days?: number; quotaMb?: number; quotaFiles?: number; sortOrder?: number }) {
|
|
return this.request<FtpPlan>("POST", `/v1/orgs/${orgId}/ftp-plans`, input);
|
|
}
|
|
|
|
updateFtpPlan(orgId: string, planId: string, input: Partial<{ name: string; description: string | null; days: number; quotaMb: number; quotaFiles: number; sortOrder: number }>) {
|
|
return this.request<FtpPlan>("PATCH", `/v1/orgs/${orgId}/ftp-plans/${planId}`, input);
|
|
}
|
|
|
|
deleteFtpPlan(orgId: string, planId: string) {
|
|
return this.request<void>("DELETE", `/v1/orgs/${orgId}/ftp-plans/${planId}`);
|
|
}
|
|
|
|
/** Another period of the login's plan, from its end date or from now. */
|
|
renewFtpAccount(orgId: string, accountId: string) {
|
|
return this.request<{ expiresAt: string | null }>("POST", `/v1/orgs/${orgId}/ftp-accounts/${accountId}/renew`);
|
|
}
|
|
|
|
createFtpAccount(orgId: string, input: { userId: string; login: string; clockOffsetSec?: number; planId?: string | null }) {
|
|
return this.request<FtpAccount & { password: string }>("POST", `/v1/orgs/${orgId}/ftp-accounts`, input);
|
|
}
|
|
|
|
/** A new FTP password (shown once). */
|
|
resetFtpPassword(orgId: string, accountId: string) {
|
|
return this.request<{ password: string }>("POST", `/v1/orgs/${orgId}/ftp-accounts/${accountId}/password`);
|
|
}
|
|
|
|
updateFtpAccount(orgId: string, accountId: string, input: { clockOffsetSec?: number; renameTemplate?: string | null; planId?: string | null; expiresAt?: string | null }) {
|
|
return this.request<FtpAccount>("PATCH", `/v1/orgs/${orgId}/ftp-accounts/${accountId}`, input);
|
|
}
|
|
|
|
deleteFtpAccount(orgId: string, accountId: string) {
|
|
return this.request<void>("DELETE", `/v1/orgs/${orgId}/ftp-accounts/${accountId}`);
|
|
}
|
|
|
|
/** Only the best of an event (game moments spread over the match); `dryRun` only works out the choice. */
|
|
deliverBest(orgId: string, input: { targetId: string; eventId: string; count: number; dryRun?: boolean; again?: boolean }) {
|
|
return this.request<{ chosen: string[]; queued: DeliveryItemSummary[]; skipped: { photoId: string; reason: string }[] }>("POST", `/v1/orgs/${orgId}/deliveries/best`, input);
|
|
}
|
|
|
|
/** ZeroZero: the event's game on the photo desk (the chosen one, or the one found by teams and time). */
|
|
zerozeroGame(orgId: string, targetId: string, eventId: string) {
|
|
return this.request<{ game: ZerozeroGame | null; chosen: boolean }>("GET", `/v1/orgs/${orgId}/delivery-targets/${targetId}/zerozero-game?eventId=${encodeURIComponent(eventId)}`);
|
|
}
|
|
|
|
/** Chooses the event's game from a link or id on fotos.zerozero.pt (null: forget it and look it up again). */
|
|
setZerozeroGame(orgId: string, targetId: string, eventId: string, game: string | null) {
|
|
return this.request<{ game: ZerozeroGame | null; chosen: boolean }>("PUT", `/v1/orgs/${orgId}/delivery-targets/${targetId}/zerozero-game`, { eventId, game });
|
|
}
|
|
|
|
deliver(orgId: string, targetId: string, photoIds: string[], again = false) {
|
|
return this.request<{ queued: DeliveryItemSummary[]; skipped: { photoId: string; reason: string }[] }>("POST", `/v1/orgs/${orgId}/deliveries`, { targetId, photoIds, again });
|
|
}
|
|
|
|
listDeliveries(orgId: string, query: { targetId?: string; eventId?: string; status?: string } = {}) {
|
|
const params = new URLSearchParams(Object.entries(query).filter(([, v]) => v) as [string, string][]);
|
|
const qs = params.size ? `?${params}` : "";
|
|
return this.request<{ items: DeliveryItemSummary[]; counts: Partial<Record<DeliveryItemSummary["status"], number>> }>("GET", `/v1/orgs/${orgId}/deliveries${qs}`);
|
|
}
|
|
|
|
retryDelivery(orgId: string, itemId: string) {
|
|
return this.request<DeliveryItemSummary>("POST", `/v1/orgs/${orgId}/deliveries/${itemId}/retry`);
|
|
}
|
|
|
|
shareEventFolder(orgId: string, targetId: string, eventId: string) {
|
|
return this.request<{ folder: string; url: string }>("POST", `/v1/orgs/${orgId}/delivery-targets/${targetId}/share`, { eventId });
|
|
}
|
|
|
|
// ---- plumbing ---------------------------------------------------------------------------------------
|
|
|
|
/** Authenticated request; refreshes once on 401 and retries. */
|
|
async request<T>(method: string, path: string, body?: unknown): Promise<T> {
|
|
if (!this.accessToken && !(await this.refresh())) throw new ApiError(401, "not_signed_in", null);
|
|
try {
|
|
return await this.raw<T>(method, path, body, true);
|
|
} catch (err) {
|
|
if (!(err instanceof ApiError) || err.status !== 401) throw err;
|
|
if (!(await this.refresh())) throw err;
|
|
return this.raw<T>(method, path, body, true);
|
|
}
|
|
}
|
|
|
|
/** Single-flight refresh: concurrent 401s share one refresh call (rotation would otherwise trip reuse detection). */
|
|
private refresh(): Promise<boolean> {
|
|
this.refreshing ??= this.doRefresh().finally(() => {
|
|
this.refreshing = null;
|
|
});
|
|
return this.refreshing;
|
|
}
|
|
|
|
private async doRefresh(): Promise<boolean> {
|
|
try {
|
|
const stored = await this.opts.refreshStore?.get();
|
|
if (this.opts.refreshStore && !stored) return false;
|
|
await this.acceptTokens(await this.raw<TokenResponse>("POST", "/v1/auth/refresh", stored ? { refreshToken: stored } : {}));
|
|
return true;
|
|
} catch (err) {
|
|
const hadSession = this.accessToken !== null;
|
|
this.accessToken = null;
|
|
if (err instanceof ApiError && err.status === 401) {
|
|
await this.opts.refreshStore?.clear();
|
|
if (hadSession) this.opts.onSessionLost?.();
|
|
return false;
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
private async acceptTokens(tokens: TokenResponse): Promise<void> {
|
|
this.accessToken = tokens.accessToken;
|
|
if (tokens.refreshToken) await this.opts.refreshStore?.set(tokens.refreshToken);
|
|
}
|
|
|
|
private async raw<T>(method: string, path: string, body?: unknown, auth = false): Promise<T> {
|
|
const headers: Record<string, string> = {};
|
|
const form = typeof FormData !== "undefined" && body instanceof FormData;
|
|
if (body !== undefined && !form) headers["content-type"] = "application/json";
|
|
if (auth && this.accessToken) headers.authorization = `Bearer ${this.accessToken}`;
|
|
const res = await this.fetchImpl(`${this.opts.baseUrl}${path}`, {
|
|
method,
|
|
headers,
|
|
credentials: "include",
|
|
...(body !== undefined ? { body: form ? (body as FormData) : JSON.stringify(body) } : {}),
|
|
});
|
|
if (res.status === 204) return undefined as T;
|
|
const text = await res.text();
|
|
const data: unknown = text ? JSON.parse(text) : null;
|
|
if (!res.ok) {
|
|
const code = (data as { error?: string } | null)?.error ?? `http_${res.status}`;
|
|
throw new ApiError(res.status, code, data);
|
|
}
|
|
return data as T;
|
|
}
|
|
}
|