diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawHttp.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawHttp.java new file mode 100644 index 00000000..9f9287a9 --- /dev/null +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawHttp.java @@ -0,0 +1,42 @@ +package com.faceclaw.app; + +import java.io.IOException; + +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + +/** + * Shared HTTP identity for the Java networking helpers. The version lives in + * app/version.ts, so the TypeScript side pushes the real string in at startup + * (see installNativeUserAgent in app/util/http.ts); the default below is only + * a fallback for requests that somehow beat that call. + */ +public final class FaceclawHttp { + private static volatile String userAgent = "Faceclaw"; + + private FaceclawHttp() {} + + public static void setUserAgent(String value) { + if (value != null && !value.trim().isEmpty()) { + userAgent = value.trim(); + } + } + + public static String getUserAgent() { + return userAgent; + } + + /** Stamps our User-Agent on any request that doesn't already carry one. */ + public static Interceptor userAgentInterceptor() { + return new Interceptor() { + @Override public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + if (request.header("User-Agent") != null) { + return chain.proceed(request); + } + return chain.proceed(request.newBuilder().header("User-Agent", userAgent).build()); + } + }; + } +} diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawModelDownloader.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawModelDownloader.java index 64b93219..02f50bb5 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawModelDownloader.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawModelDownloader.java @@ -63,6 +63,7 @@ public class FaceclawModelDownloader { sharedClient = new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) + .addInterceptor(FaceclawHttp.userAgentInterceptor()) .build(); } } diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawSseRequest.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawSseRequest.java index e6e8e5c5..5ec20fe9 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawSseRequest.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawSseRequest.java @@ -134,6 +134,7 @@ public class FaceclawSseRequest { sharedClient = new OkHttpClient.Builder() .connectTimeout(15, TimeUnit.SECONDS) .readTimeout(180, TimeUnit.SECONDS) + .addInterceptor(FaceclawHttp.userAgentInterceptor()) .build(); } client = sharedClient; diff --git a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawWebSocket.java b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawWebSocket.java index 97f2a631..f228ed7a 100644 --- a/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawWebSocket.java +++ b/App_Resources/Android/src/main/java/com/faceclaw/app/FaceclawWebSocket.java @@ -112,6 +112,7 @@ public class FaceclawWebSocket { if (sharedClient == null) { sharedClient = new OkHttpClient.Builder() .pingInterval(20, TimeUnit.SECONDS) + .addInterceptor(FaceclawHttp.userAgentInterceptor()) .build(); } client = sharedClient; diff --git a/app/app.ts b/app/app.ts index afcedc98..b1f9e59b 100644 --- a/app/app.ts +++ b/app/app.ts @@ -6,7 +6,9 @@ purpose of the file is to pass control to the app’s first module. import { Application } from '@nativescript/core' import { registerShareIntentHandler } from './native/share-intents' +import { installNativeUserAgent } from './util/http' +installNativeUserAgent() registerShareIntentHandler() Application.run({ moduleName: 'app-root' }) diff --git a/app/apps/evenhub/even-api.ts b/app/apps/evenhub/even-api.ts index bc548eeb..1a099207 100644 --- a/app/apps/evenhub/even-api.ts +++ b/app/apps/evenhub/even-api.ts @@ -7,6 +7,7 @@ */ import { Application } from "@nativescript/core"; import { evenHubEmailSetting, evenHubPasswordSetting, hasEvenHubCredentials } from "./credentials"; +import { fetchWithUserAgent } from "../../util/http"; declare const android: any; @@ -325,7 +326,7 @@ async function fetchWithTimeout(url: string, init: RequestInit, timeoutMs = REQU timeoutHandle = setTimeout(() => reject(new Error("EvenHub request timed out.")), timeoutMs); }); try { - return await Promise.race([fetch(url, init), timeout]); + return await Promise.race([fetchWithUserAgent(url, init), timeout]); } finally { if (timeoutHandle) clearTimeout(timeoutHandle); } diff --git a/app/apps/evenhub/privacy-policy.ts b/app/apps/evenhub/privacy-policy.ts index e2a0592a..53fc2681 100644 --- a/app/apps/evenhub/privacy-policy.ts +++ b/app/apps/evenhub/privacy-policy.ts @@ -1,4 +1,5 @@ import { Application } from "@nativescript/core"; +import { fetchWithUserAgent } from "../../util/http"; declare const android: any; declare const androidx: any; @@ -74,7 +75,7 @@ async function downloadAndOpenPdf(url: string, appName: string, activity: any): }); let response: Response; try { - response = await Promise.race([fetch(url), timeout]); + response = await Promise.race([fetchWithUserAgent(url), timeout]); } finally { if (timeoutHandle) clearTimeout(timeoutHandle); } diff --git a/app/apps/roam/roam-api.ts b/app/apps/roam/roam-api.ts index 379da5f5..70c7dd39 100644 --- a/app/apps/roam/roam-api.ts +++ b/app/apps/roam/roam-api.ts @@ -6,6 +6,7 @@ * worker via fetch. */ import { roamApiTokenSetting, roamGraphNameSetting } from "../../ui/dashboard-settings"; +import { fetchWithUserAgent } from "../../util/http"; const API_BASE = "https://api.roamresearch.com"; const FETCH_TIMEOUT_MS = 12_000; @@ -145,7 +146,7 @@ async function roamPost(endpoint: "q" | "pull" | "write", body: object): Promise async function fetchWithTimeout(url: string, payload: string, token: string): Promise { let timeoutHandle: ReturnType | null = null; - const request = fetch(url, { + const request = fetchWithUserAgent(url, { method: "POST", headers: { "Content-Type": "application/json; charset=utf-8", diff --git a/app/g2/firmware-builder.ts b/app/g2/firmware-builder.ts index e7178142..01efe859 100644 --- a/app/g2/firmware-builder.ts +++ b/app/g2/firmware-builder.ts @@ -18,6 +18,7 @@ import { extractEvenHubFontAsset, isEvenHubFontAsset, } from "./firmware-fonts"; +import { fetchWithUserAgent } from "../util/http"; declare const com: any; @@ -157,7 +158,7 @@ async function downloadAndVerifyBase(report: (progress: FirmwareProgress) => voi async function downloadFirmware(): Promise { let response: Response; try { - response = await fetch(FIRMWARE_URL); + response = await fetchWithUserAgent(FIRMWARE_URL); } catch (error) { throw new FirmwareBuildError(`Could not reach Even's firmware CDN: ${(error as Error)?.message ?? error}`); } diff --git a/app/native/mapbox.ts b/app/native/mapbox.ts index 647b605f..a8336f31 100644 --- a/app/native/mapbox.ts +++ b/app/native/mapbox.ts @@ -7,6 +7,7 @@ import { GrayImage } from "../graphics/image"; import { getStringSetting } from "./settings-store"; import { grayImageFromPacket } from "./image-files"; +import { fetchWithUserAgent } from "../util/http"; declare const com: any; declare const global: any; @@ -268,7 +269,7 @@ async function fetchJson(url: string, label: string): Promise { } async function fetchWithTimeout(url: string, label: string): Promise { - const request = fetch(url); + const request = fetchWithUserAgent(url); let timeoutHandle: ReturnType | null = null; const timeout = new Promise((_resolve, reject) => { timeoutHandle = setTimeout(() => reject(new Error(`${label} timed out.`)), FETCH_TIMEOUT_MS); diff --git a/app/native/nightscout-bridge.ts b/app/native/nightscout-bridge.ts index 8be3f272..8ce2a38e 100644 --- a/app/native/nightscout-bridge.ts +++ b/app/native/nightscout-bridge.ts @@ -1,4 +1,5 @@ import { loadNightscoutSettings, nightscoutApiTokenSetting, nightscoutSiteUrlSetting } from "../ui/dashboard-settings"; +import { fetchWithUserAgent } from "../util/http"; export type NightscoutPoint = { timestampMs: number; @@ -292,7 +293,7 @@ export class NightscoutBridge { } async function fetchJson(url: string): Promise { - const response = await fetch(url); + const response = await fetchWithUserAgent(url); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } diff --git a/app/native/weather.ts b/app/native/weather.ts index 7daab13b..8cc073e9 100644 --- a/app/native/weather.ts +++ b/app/native/weather.ts @@ -1,5 +1,7 @@ import { hasLocationPermission } from "../g2/android-permissions"; import { getCurrentLocation, type CurrentLocation } from "./location"; +import { fetchWithUserAgent } from "../util/http"; +import { USER_AGENT } from "../version"; export type WeatherPhase = "permission-required" | "locating" | "loading" | "ready" | "error"; @@ -87,7 +89,8 @@ type NwsMeasure = { const NWS_API_ROOT = "https://api.weather.gov"; const NWS_HEADERS = { Accept: "application/geo+json", - "User-Agent": "Faceclaw/1.0 (https://github.com/jimrandomh/faceclaw)", + // NWS asks callers to identify themselves with a contact address. + "User-Agent": `${USER_AGENT} (https://github.com/jimrandomh/faceclaw)`, }; const WEATHER_REFRESH_MS = 30 * 60 * 1000; const FETCH_TIMEOUT_MS = 20_000; @@ -230,7 +233,7 @@ async function loadLatestObservation(stationsUrl: string): Promise(url: string): Promise { - const request = fetch(url, { headers: NWS_HEADERS }); + const request = fetchWithUserAgent(url, { headers: NWS_HEADERS }); let timeoutHandle: ReturnType | null = null; const timeout = new Promise((_resolve, reject) => { timeoutHandle = setTimeout(() => reject(new Error("Weather request timed out.")), FETCH_TIMEOUT_MS); diff --git a/app/util/http.ts b/app/util/http.ts new file mode 100644 index 00000000..9e0a087b --- /dev/null +++ b/app/util/http.ts @@ -0,0 +1,49 @@ +import { USER_AGENT } from "../version"; + +declare const com: any; + +/** + * fetch() with our User-Agent attached. Every outbound HTTP request in the app + * should go through this instead of calling fetch() directly, so servers see a + * consistent, identifiable client string. A User-Agent the caller supplies + * explicitly wins (e.g. an API that wants contact details appended). + * + * Requests made from the Java side (FaceclawSseRequest, FaceclawWebSocket, + * FaceclawModelDownloader) get the same header from FaceclawHttp's okhttp + * interceptor. + */ +export function fetchWithUserAgent(url: string, init?: RequestInit): Promise { + return fetch(url, { ...init, headers: withUserAgent(init?.headers) }); +} + +/** Copies headers into a plain record, adding our User-Agent if absent. */ +export function withUserAgent(headers?: HeadersInit): Record { + const merged: Record = {}; + if (headers) { + if (Array.isArray(headers)) { + for (const [name, value] of headers) merged[name!] = value!; + } else if (typeof (headers as Headers).forEach === "function") { + (headers as Headers).forEach((value, name) => { + merged[name] = value; + }); + } else { + Object.assign(merged, headers as Record); + } + } + const hasUserAgent = Object.keys(merged).some((name) => name.toLowerCase() === "user-agent"); + if (!hasUserAgent) merged["User-Agent"] = USER_AGENT; + return merged; +} + +/** + * Hands our User-Agent to the Java networking helpers. Called once during app + * startup; the value is a process-wide static, so workers pick it up too. + */ +export function installNativeUserAgent(): void { + if (!global.isAndroid) return; + try { + com.faceclaw.app.FaceclawHttp.setUserAgent(USER_AGENT); + } catch { + // Non-fatal: okhttp falls back to FaceclawHttp's built-in default. + } +} diff --git a/app/version.ts b/app/version.ts index 03b7b1ff..33cc77a9 100644 --- a/app/version.ts +++ b/app/version.ts @@ -1 +1,2 @@ -export const FACECLAW_VERSION = "0.4.0"; +export const FACECLAW_VERSION = "0.4.1"; +export const USER_AGENT = "Faceclaw/"+FACECLAW_VERSION;