Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript

Bundle ffmpeg in release binaries; add in-app update pop-up; pool tile client (#19)

OsintMeThat311beded3ebe
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 1eb6e31..e784a54 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -75,6 +75,26 @@ jobs:
run: |
uv sync --frozen --no-dev
uv pip install . pyinstaller
+ # ffmpeg is a native program, not a Python dep, so it isn't in the wheel.
+ # Vendor a static ffmpeg + ffprobe per-OS so the binary works out of the
+ # box (packaging/azimut.spec picks them up; engine/ffmpeg.py finds them at
+ # runtime). One host, one arch per runner; each zip holds a single binary.
+ - name: Vendor static ffmpeg + ffprobe into the binary
+ shell: bash
+ run: |
+ case "${{ runner.os }}" in
+ Linux) plat=linux/amd64 ;;
+ Windows) plat=windows/amd64 ;;
+ macOS) plat=macos/arm64 ;;
+ esac
+ mkdir -p packaging/vendor
+ base="https://ffmpeg.martin-riedl.de/redirect/latest/$plat/release"
+ for tool in ffmpeg ffprobe; do
+ curl -fL "$base/$tool.zip" -o "$tool.zip"
+ uv run python -c "import sys, zipfile; zipfile.ZipFile(sys.argv[1]).extractall('packaging/vendor')" "$tool.zip"
+ done
+ chmod +x packaging/vendor/* 2>/dev/null || true
+ ls -l packaging/vendor
- name: Build single-file binary
run: uv run pyinstaller packaging/azimut.spec --distpath dist-bin --workpath build-bin
- name: Smoke-test the binary
diff --git a/README.md b/README.md
index 590bae3..c429673 100644
--- a/README.md
+++ b/README.md
@@ -72,8 +72,12 @@ release is out and links the download; replace the old file with the new one.
To uninstall, delete the file. Either way `~/Azimut` stays put, so your cases
open unchanged in the new version.
-Optional: install **ffmpeg** on your `PATH` for video thumbnails and video
-metadata (dimensions/duration). Everything else works without it.
+The downloadable binaries bundle a static **ffmpeg** (and ffprobe), so video
+thumbnails, frame scans, video enhancement, and downloads that merge separate
+audio+video streams work out of the box. If you `pip install azimut` instead,
+put ffmpeg on your `PATH` for those features — everything else works without it.
+The bundled ffmpeg is redistributed under its own license; see
+[ffmpeg.org/legal.html](https://ffmpeg.org/legal.html).
From source:
diff --git a/docs/SPEC.md b/docs/SPEC.md
index 40d0c6b..e7dfca7 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -30,7 +30,9 @@ their outputs into the case.
1. **Local-first, privacy-first.** No account, no telemetry, no upload. Network
only when a tool inherently needs it (tiles, geocoding, download), always to
- third parties directly, never through an Azimut server.
+ third parties directly, never through an Azimut server. One exception: an
+ opt-out check to GitHub's public releases feed on load, so binary users hear
+ about updates (Settings → Updates turns it off).
2. **The case is the product.** Tools are how you work; the case folder is what
you keep — plain JSON + media, human-readable, versionable, portable.
3. **One tab = one tool, useful in 30 seconds.** Every tool works one-shot with
@@ -237,10 +239,13 @@ firms up; delete when it stops making sense.
tools are tabs inside them (see [UI.md](UI.md)).
- **Settings & secrets** ✅: in-app tabs (Preferences / Imagery / About), keys
stored locally and never bundled into a shared case, monthly usage counters,
- backup export/import. Display prefs are presentation only — artifacts keep
+ backup export/import, opt-out "new release is live" pop-up on load (per-version
+ "don't show again"). Display prefs are presentation only — artifacts keep
decimal degrees + metres on disk.
-- **Distribution**: `pip install azimut` + PyInstaller single-file binaries
- (Windows/Linux/macOS).
+- **Distribution** ✅: `pip install azimut` + PyInstaller single-file binaries
+ (Windows/Linux/macOS) that bundle a static ffmpeg/ffprobe (works out of the
+ box; pip installs still want ffmpeg on `PATH`) and carry the app icon on the
+ Windows `.exe`.
- **Dependencies** ✅: ranges in `pyproject.toml`, exact pins in `uv.lock`; yt-dlp
+ gallery-dl unbounded on purpose; scraper self-update keeps an old binary useful.
- **Storage**: plain files (§3); SQLite only for rebuildable caches.
@@ -248,7 +253,9 @@ firms up; delete when it stops making sense.
guard (DNS rebinding), 0600/0700 perms, 100 MP Pillow clamp, token-gated ingest
island for the extension. Accepted risks recorded here: cleartext keys over
localhost, the hash-verified scraper updater, and tile/media URL fetches (SSRF
- only matters if the localhost assumption breaks).
+ only matters if the localhost assumption breaks). The startup update check is
+ the one on-mount network call — opt-out, read-only against GitHub's releases
+ feed, notes rendered as text (no HTML injection).
## 10. Open questions
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index 7d27760..62f31af 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -1,5 +1,13 @@
<script>
- import { uiState, initSession, caseState, reloadCase, toast } from './lib/state.svelte.js';
+ import {
+ uiState,
+ initSession,
+ caseState,
+ reloadCase,
+ toast,
+ updateState,
+ checkForUpdateOnStart,
+ } from './lib/state.svelte.js';
import { startEvents, onEvent } from './lib/events.js';
import { WORKSPACES, workspaceOf, toolFromHash } from './lib/workspaces.js';
import Icon from './components/Icon.svelte';
@@ -15,6 +23,7 @@
import PostComposer from './tools/PostComposer.svelte';
import Inspector from './tools/Inspector.svelte';
import Settings from './tools/Settings.svelte';
+ import UpdateModal from './components/UpdateModal.svelte';
// The rail holds workspaces (docs/UI.md §3); tools are tabs inside them.
// Settings lives behind the topbar gear instead — app plumbing, not part
@@ -61,8 +70,13 @@
visited[uiState.tool] = true;
});
- // Load the case list and reopen the last-used case (survives reloads).
- initSession().catch(() => {});
+ // Load the case list and reopen the last-used case (survives reloads), then
+ // — once preferences have landed — see whether a newer release is out and
+ // pop a notice. The check reads prefs.updateCheckOnStart, so it must follow
+ // initSession, which loads them.
+ initSession()
+ .catch(() => {})
+ .finally(() => checkForUpdateOnStart());
// Live nudges from our own backend (SSE, same-origin — still local-first):
// the capture extension files screenshots while this tab just sits here, and
@@ -151,6 +165,10 @@
<Toasts />
+{#if updateState.show}
+ <UpdateModal />
+{/if}
+
<style>
.shell {
display: flex;
diff --git a/frontend/src/components/UpdateModal.svelte b/frontend/src/components/UpdateModal.svelte
new file mode 100644
index 0000000..9939f24
--- /dev/null
+++ b/frontend/src/components/UpdateModal.svelte
@@ -0,0 +1,82 @@
+<script>
+ import Modal from './Modal.svelte';
+ import Icon from './Icon.svelte';
+ import { updateState, dismissUpdate } from '../lib/state.svelte.js';
+
+ let mute = $state(false);
+
+ function close() {
+ dismissUpdate(mute);
+ }
+</script>
+
+<Modal title="{updateState.latest} is live" onclose={close} width="520px">
+ <p class="lead">A newer version of Azimut is out. Grab it to stay current.</p>
+
+ {#if updateState.notes}
+ <!-- release body from our own GitHub release; rendered as plain text, never
+ as HTML, so there is nothing to inject -->
+ <pre class="notes">{updateState.notes}</pre>
+ {/if}
+
+ <div class="actions">
+ <label class="mute">
+ <input type="checkbox" bind:checked={mute} />
+ Don't show this again
+ </label>
+ <a
+ class="btn btn-sm btn-primary"
+ href={updateState.url}
+ target="_blank"
+ rel="noreferrer"
+ onclick={close}
+ >
+ <Icon name="download" size={13} /> Download {updateState.latest}
+ <Icon name="external" size={11} />
+ </a>
+ </div>
+
+ <p class="note">
+ You can always update later from Settings → Updates.
+ </p>
+</Modal>
+
+<style>
+ .lead {
+ color: var(--text-2);
+ font-size: var(--fs-sm);
+ }
+ .notes {
+ margin: 12px 0;
+ padding: 10px 12px;
+ max-height: 40vh;
+ overflow: auto;
+ background: var(--bg-0);
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ color: var(--text-2);
+ font-size: var(--fs-sm);
+ line-height: 1.5;
+ white-space: pre-wrap;
+ word-break: break-word;
+ }
+ .actions {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ margin-top: 14px;
+ }
+ .mute {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ }
+ .note {
+ margin-top: 12px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+</style>
diff --git a/frontend/src/lib/appUpdate.js b/frontend/src/lib/appUpdate.js
new file mode 100644
index 0000000..18e0598
--- /dev/null
+++ b/frontend/src/lib/appUpdate.js
@@ -0,0 +1,18 @@
+/**
+ * The startup update pop-up's one decision: given the update check and the tag
+ * the user muted, should we surface the notice?
+ *
+ * Kept pure (no runes, no fetch) so it's the part worth unit-testing — the
+ * network call and the modal state live in state.svelte.js around it.
+ */
+
+/**
+ * @param {{ update_available?: boolean, latest?: string|null } | null} check
+ * The GET /api/settings/update?check=true payload.
+ * @param {string} dismissedVersion The tag "don't show again" muted, or ''.
+ * @returns {boolean}
+ */
+export function shouldShowUpdate(check, dismissedVersion) {
+ if (!check || !check.update_available || !check.latest) return false;
+ return check.latest !== dismissedVersion;
+}
diff --git a/frontend/src/lib/appUpdate.test.js b/frontend/src/lib/appUpdate.test.js
new file mode 100644
index 0000000..4b5824f
--- /dev/null
+++ b/frontend/src/lib/appUpdate.test.js
@@ -0,0 +1,26 @@
+import { describe, it, expect } from 'vitest';
+import { shouldShowUpdate } from './appUpdate.js';
+
+describe('shouldShowUpdate', () => {
+ it('shows when a newer release is available and nothing is muted', () => {
+ expect(shouldShowUpdate({ update_available: true, latest: 'v0.2.0' }, '')).toBe(true);
+ });
+
+ it('stays quiet on the up-to-date check', () => {
+ expect(shouldShowUpdate({ update_available: false, latest: 'v0.1.2' }, '')).toBe(false);
+ });
+
+ it('stays quiet for the exact tag the user muted', () => {
+ expect(shouldShowUpdate({ update_available: true, latest: 'v0.2.0' }, 'v0.2.0')).toBe(false);
+ });
+
+ it('shows again once a newer tag than the muted one ships', () => {
+ expect(shouldShowUpdate({ update_available: true, latest: 'v0.3.0' }, 'v0.2.0')).toBe(true);
+ });
+
+ it('handles a missing or failed check', () => {
+ expect(shouldShowUpdate(null, '')).toBe(false);
+ expect(shouldShowUpdate({ error: 'offline' }, '')).toBe(false);
+ expect(shouldShowUpdate({ update_available: true, latest: null }, '')).toBe(false);
+ });
+});
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index 3ab226b..82cba9e 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -8,6 +8,7 @@
import { api } from './api.js';
import { formatCoords as renderCoords } from './coords.js';
import { loadWidth, saveWidth, clampWidth } from './sidebar.js';
+import { shouldShowUpdate } from './appUpdate.js';
/**
* App-wide display preferences (Settings → Preferences), mirrored from
@@ -19,6 +20,19 @@ export const prefs = $state({
units: 'metric', // 'metric' | 'imperial'
homeView: { lat: 48.8584, lon: 2.2945, zoom: 16 }, // where Satellite opens
postMention: '@GeoConfirmed', // handle a fresh post draft is addressed to
+ updateCheckOnStart: true, // ask GitHub for a newer release when the page loads
+ updateDismissedVersion: '', // the release tag muted with "don't show again"
+});
+
+/**
+ * The startup update pop-up (App.svelte). `show` is flipped on once a check
+ * comes back with a newer, non-muted release; the modal reads the rest.
+ */
+export const updateState = $state({
+ show: false,
+ latest: '', // the newer release tag, e.g. "v0.2.0"
+ url: '', // where to download it
+ notes: '', // the release body (rendered as plain text)
});
/** Render a lat/lon the way the user asked for it. The tools' one entry point. */
@@ -50,6 +64,43 @@ export function applyPrefs(s) {
if (s.units) prefs.units = s.units;
if (s.home_view) prefs.homeView = s.home_view;
if (s.post_mention !== undefined) prefs.postMention = s.post_mention; // '' = none
+ if (s.update_check_on_start !== undefined) prefs.updateCheckOnStart = s.update_check_on_start;
+ if (s.update_dismissed_version !== undefined)
+ prefs.updateDismissedVersion = s.update_dismissed_version;
+}
+
+/**
+ * On page load, ask GitHub whether a newer release is out and pop a notice if
+ * so. The one network call Azimut makes on mount — gated on the user's
+ * `updateCheckOnStart` preference (Settings turns it off), so with it disabled
+ * opening the app still phones nowhere. Never throws: a failed or muted check
+ * simply leaves the pop-up closed.
+ */
+export async function checkForUpdateOnStart() {
+ if (!prefs.updateCheckOnStart) return;
+ try {
+ const check = await api.get('/api/settings/update?check=true');
+ if (shouldShowUpdate(check, prefs.updateDismissedVersion)) {
+ updateState.latest = check.latest;
+ updateState.url = check.url;
+ updateState.notes = check.notes ?? '';
+ updateState.show = true;
+ }
+ } catch {
+ /* offline, rate-limited, whatever — the pop-up is a courtesy, not a gate */
+ }
+}
+
+/** Close the update pop-up. `mute` remembers the tag so it won't show again. */
+export async function dismissUpdate(mute = false) {
+ updateState.show = false;
+ if (mute && updateState.latest) {
+ try {
+ applyPrefs(await api.put('/api/settings/prefs', { update_dismissed_version: updateState.latest }));
+ } catch {
+ /* the mute is a nicety; failing to persist it just means it re-shows */
+ }
+ }
}
export const caseState = $state({
diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelte
index b272fe7..bd2f0cd 100644
--- a/frontend/src/tools/Settings.svelte
+++ b/frontend/src/tools/Settings.svelte
@@ -162,6 +162,9 @@
let tiers = $state(null);
let tierEdits = $state(perProvider(() => ''));
let about = $state({ version: '', workspace_root: '', extension_version: '' });
+ // ffmpeg powers video thumbnails, frame scans and merged-stream downloads.
+ // The binaries bundle it; a pip install uses a system copy on PATH. Read-only.
+ let ffmpeg = $state({ available: false, version: null, source: null, path: null });
// --- capture extension: pairing token + detection (lib/extBridge.js) ---
let ingestToken = $state('');
@@ -205,6 +208,7 @@
// fought by the number parser mid-keystroke; committed on change
let home = $state({ lat: '', lon: '', zoom: '' });
let mention = $state('');
+ let updateOnStart = $state(true); // pop a notice on load when a release is out
// the analyst's logo: app-wide like the API keys, and under the same rule —
// it lives beside settings.json and only ever reaches a case as pixels in a
// rendered proof PNG. `sigBust` re-fetches the <img> after a replace.
@@ -344,8 +348,11 @@
ingestToken = s.ingest_token ?? '';
home = { lat: String(s.home_view.lat), lon: String(s.home_view.lon), zoom: String(s.home_view.zoom) };
mention = s.post_mention ?? '';
+ updateOnStart = s.update_check_on_start ?? true;
applyPrefs(s); // the rest of the app reads these live
await loadScrapers().catch(() => {}); // local disk read; never blocks Settings
+ // shells out to `ffmpeg -version`; non-blocking, About tab only reads it
+ api.get('/api/settings/ffmpeg').then((r) => (ffmpeg = r)).catch(() => {});
}
// Every preference saves on change — no "Save" button to forget. The server's
@@ -1002,6 +1009,15 @@
<dd class="mono">{about.version || '—'}</dd>
<dt>Workspace</dt>
<dd class="mono">{about.workspace_root || '—'}</dd>
+ <dt>ffmpeg</dt>
+ <dd class="mono" title={ffmpeg.path || ''}>
+ {#if ffmpeg.available}
+ {ffmpeg.version || 'installed'}
+ <span class="sub">· {ffmpeg.source === 'bundled' ? 'bundled' : 'system PATH'}</span>
+ {:else}
+ not found <span class="sub">· install ffmpeg on your PATH</span>
+ {/if}
+ </dd>
<dt>License</dt>
<dd>AGPL-3.0-or-later</dd>
</dl>
@@ -1046,6 +1062,21 @@
</button>
{/if}
</div>
+ <div class="row">
+ <div class="row-label">
+ <span>Tell me on startup</span>
+ <span class="row-hint">
+ Checks GitHub when the app loads and pops a notice if a newer
+ release is out. The only network call Azimut makes on its own.
+ </span>
+ </div>
+ <input
+ type="checkbox"
+ bind:checked={updateOnStart}
+ onchange={() => savePrefs({ update_check_on_start: updateOnStart })}
+ aria-label="Check for updates on startup"
+ />
+ </div>
<p class="note">
A <span class="mono">pip</span> or <span class="mono">pipx</span> install updates with
<span class="mono">pipx upgrade azimut</span>. For the standalone binary, download the new
diff --git a/packaging/azimut.ico b/packaging/azimut.ico
new file mode 100644
index 0000000..4f4b8fe
Binary files /dev/null and b/packaging/azimut.ico differ
diff --git a/packaging/azimut.spec b/packaging/azimut.spec
index bd8afde..97b1941 100644
--- a/packaging/azimut.spec
+++ b/packaging/azimut.spec
@@ -9,6 +9,8 @@
# are collected explicitly because they are loaded dynamically and PyInstaller
# can't see them.
+from pathlib import Path
+
from PyInstaller.utils.hooks import collect_data_files, collect_submodules
hiddenimports = (
@@ -21,10 +23,22 @@ hiddenimports = (
# Grabs azimut/static/** (index.html, assets, favicon) from the installed package.
datas = collect_data_files("azimut")
+# Static ffmpeg / ffprobe, when the release CI has dropped them in
+# packaging/vendor/. They land at the bundle root, where engine/ffmpeg.py looks
+# for them (sys._MEIPASS). Absent (a plain local build), the binary just falls
+# back to a system ffmpeg on PATH — same as a pip install. See docs/SPEC.md.
+vendor = Path(SPECPATH) / "vendor"
+binaries = [
+ (str(p), ".")
+ for name in ("ffmpeg", "ffprobe", "ffmpeg.exe", "ffprobe.exe")
+ for p in [vendor / name]
+ if p.is_file()
+]
+
a = Analysis(
["entry.py"],
pathex=[],
- binaries=[],
+ binaries=binaries,
datas=datas,
hiddenimports=hiddenimports,
hookspath=[],
@@ -35,6 +49,14 @@ a = Analysis(
pyz = PYZ(a.pure)
+# The .exe icon. Windows is the only shipped artifact that embeds one: Linux
+# binaries can't, and our macOS artifact is a raw binary (not an .app bundle),
+# so Finder shows no custom icon there either. PyInstaller wants a .ico.
+import sys
+
+ico = Path(SPECPATH) / "azimut.ico"
+icon = str(ico) if sys.platform == "win32" and ico.is_file() else None
+
exe = EXE(
pyz,
a.scripts,
@@ -45,4 +67,5 @@ exe = EXE(
console=True, # it's a local server; the console shows the URL
disable_windowed_traceback=False,
upx=False,
+ icon=icon,
)
diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.py
index 642874c..26d1157 100644
--- a/src/azimut/api/satellite.py
+++ b/src/azimut/api/satellite.py
@@ -27,6 +27,26 @@ from .cases import delete_by_path, get_case
router = APIRouter(prefix="/api", tags=["satellite"])
+# A live map pans through dozens of tiles at once, all proxied through here. A
+# fresh connection per tile means a TCP + TLS handshake per tile — the dominant
+# cost, and worst on Windows, where the loopback hop and Defender's per-request
+# scan pile on. One pooled client keeps connections alive across tiles instead.
+# httpx.Client is safe to share across the threadpool the sync routes run in.
+_tile_client: httpx.Client | None = None
+
+
+def _client() -> httpx.Client:
+ global _tile_client
+ if _tile_client is None:
+ _tile_client = httpx.Client(
+ follow_redirects=True,
+ timeout=20,
+ limits=httpx.Limits(max_keepalive_connections=16, max_connections=32),
+ headers={"User-Agent": tiles.USER_AGENT},
+ )
+ return _tile_client
+
+
class CaptureIn(BaseModel):
lat: float = Field(ge=-90, le=90) # crop frame center
lon: float = Field(ge=-180, le=180)
@@ -208,10 +228,7 @@ def _serve_tile(
config.record_provider_status(provider.meter, False, str(exc.__cause__))
raise HTTPException(status_code=502, detail=str(exc)) from exc
try:
- upstream = httpx.get(
- url, headers={"User-Agent": tiles.USER_AGENT}, timeout=20,
- follow_redirects=True,
- )
+ upstream = _client().get(url)
except httpx.HTTPError as exc:
raise HTTPException(status_code=502, detail=f"tile fetch failed: {exc}") from exc
# a stale Google session token answers 401/403 — re-mint once, transparently
diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.py
index 0fabd83..532eed9 100644
--- a/src/azimut/api/settings.py
+++ b/src/azimut/api/settings.py
@@ -19,7 +19,7 @@ from fastapi.responses import FileResponse
from pydantic import BaseModel, Field
from .. import __version__, config
-from ..engine import google_tiles, scrapers, sentinel, tiles, updates
+from ..engine import ffmpeg, google_tiles, scrapers, sentinel, tiles, updates
from .ingest import bundled_extension_version
router = APIRouter(prefix="/api", tags=["settings"])
@@ -74,6 +74,10 @@ class PrefsIn(BaseModel):
units: str | None = None # one of config.UNIT_SYSTEMS
home_view: HomeView | None = None # where the Satellite tab opens
post_mention: str | None = None # handle a new post draft is addressed to
+ # app self-update pop-up (engine/updates.py) — check on load, and the tag
+ # the user muted with "don't show again"
+ update_check_on_start: bool | None = None
+ update_dismissed_version: str | None = None
def _prefs(settings: dict[str, Any]) -> dict[str, Any]:
@@ -90,6 +94,8 @@ def _prefs(settings: dict[str, Any]) -> dict[str, Any]:
"units": settings.get("units", "metric"),
"home_view": settings.get("home_view", DEFAULT_HOME_VIEW),
"post_mention": settings.get("post_mention", DEFAULT_POST_MENTION),
+ "update_check_on_start": bool(settings.get("update_check_on_start", True)),
+ "update_dismissed_version": settings.get("update_dismissed_version", ""),
}
@@ -129,6 +135,13 @@ def get_settings() -> dict[str, Any]:
}
[email protected]("/settings/ffmpeg")
+def ffmpeg_info() -> dict[str, Any]:
+ """About tab: ffmpeg version + where it resolves from. Separate from the
+ hot /settings poll because it shells out to ``ffmpeg -version``."""
+ return ffmpeg.info()
+
+
@router.put("/settings/prefs")
def put_prefs(body: PrefsIn) -> dict[str, Any]:
# validate before taking the settings lock — a 422 must not hold it
@@ -183,6 +196,10 @@ def _apply_prefs(settings: dict[str, Any], body: PrefsIn) -> None:
settings["home_view"] = body.home_view.model_dump()
if body.post_mention is not None:
settings["post_mention"] = body.post_mention.strip()[:64]
+ if body.update_check_on_start is not None:
+ settings["update_check_on_start"] = bool(body.update_check_on_start)
+ if body.update_dismissed_version is not None:
+ settings["update_dismissed_version"] = body.update_dismissed_version.strip()[:64]
@router.put("/settings/keys")
diff --git a/src/azimut/config.py b/src/azimut/config.py
index f90c540..561de2a 100644
--- a/src/azimut/config.py
+++ b/src/azimut/config.py
@@ -89,6 +89,15 @@ DEFAULT_SETTINGS: dict[str, Any] = {
# lazily on first use, shown once in Settings, pasted into the extension.
# Empty means "not minted yet" — never a valid credential.
"ingest_token": "",
+ # App self-update pop-up (frontend App.svelte + engine/updates.py):
+ # - update_check_on_start: ask GitHub for the latest release when the page
+ # loads, and pop a notice if one is newer. On by default so a binary user
+ # (no package manager behind them) hears about releases; the one network
+ # call Azimut makes on mount, and the toggle in Settings turns it off.
+ # - update_dismissed_version: the release the user chose "don't show again"
+ # for. The pop-up stays quiet for that exact tag; a newer one shows again.
+ "update_check_on_start": True,
+ "update_dismissed_version": "",
}
# Accepted values for the display preferences above — mirror of
diff --git a/src/azimut/engine/ffmpeg.py b/src/azimut/engine/ffmpeg.py
new file mode 100644
index 0000000..755e89a
--- /dev/null
+++ b/src/azimut/engine/ffmpeg.py
@@ -0,0 +1,117 @@
+"""Locate the ffmpeg / ffprobe binaries the media and inspect engines shell out to.
+
+ffmpeg is a native program, not a Python package, so a plain ``pip install
+azimut`` relies on a system copy on ``PATH``. The release binaries instead
+bundle a static ffmpeg + ffprobe alongside the executable — PyInstaller drops
+them at the root of ``sys._MEIPASS`` (see packaging/azimut.spec) — so the app
+works out of the box with no separate install.
+
+Everything that runs ffmpeg resolves through here, so the bundled copy is
+preferred and a system copy on ``PATH`` is the fallback. yt-dlp, which finds
+ffmpeg on ``PATH`` by itself, is pointed at the bundled directory via
+``location_for_ytdlp()`` when there is one.
+"""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+
+def _bundled(name: str) -> str | None:
+ """Path to *name* bundled beside the frozen executable, or None.
+
+ Only a frozen build has ``sys._MEIPASS``; a source/pip run never does, so
+ this is a no-op there and resolution falls straight through to ``PATH``.
+ """
+ base = getattr(sys, "_MEIPASS", None)
+ if base is None:
+ return None
+ exe = name + (".exe" if sys.platform == "win32" else "")
+ candidate = Path(base) / exe
+ return str(candidate) if candidate.is_file() else None
+
+
+def _resolve(name: str) -> str | None:
+ return _bundled(name) or shutil.which(name)
+
+
+def ffmpeg_path() -> str | None:
+ """Full path to a usable ffmpeg, or None if neither bundled nor on PATH."""
+ return _resolve("ffmpeg")
+
+
+def ffprobe_path() -> str | None:
+ """Full path to a usable ffprobe, or None if neither bundled nor on PATH."""
+ return _resolve("ffprobe")
+
+
+def ffmpeg_exe() -> str:
+ """Argv[0] for an ffmpeg subprocess: the resolved path, else the bare name
+ so a system copy on PATH is still tried."""
+ return ffmpeg_path() or "ffmpeg"
+
+
+def ffprobe_exe() -> str:
+ """Argv[0] for an ffprobe subprocess (see :func:`ffmpeg_exe`)."""
+ return ffprobe_path() or "ffprobe"
+
+
+def ffmpeg_available() -> bool:
+ return ffmpeg_path() is not None
+
+
+def ffprobe_available() -> bool:
+ return ffprobe_path() is not None
+
+
+def _version(exe: str) -> str | None:
+ """The version token from ``<exe> -version``, e.g. ``n7.1`` or ``6.1.1``."""
+ try:
+ proc = subprocess.run([exe, "-version"], capture_output=True, timeout=10)
+ except (OSError, subprocess.SubprocessError):
+ return None
+ if proc.returncode != 0:
+ return None
+ lines = (proc.stdout or b"").decode("utf-8", "replace").splitlines()
+ if not lines:
+ return None
+ # first line: "ffmpeg version n7.1 Copyright (c) ..."
+ parts = lines[0].split()
+ if len(parts) >= 3 and parts[1] == "version":
+ return parts[2]
+ return lines[0].strip() or None
+
+
+def info() -> dict[str, str | bool | None]:
+ """About-tab readout: is ffmpeg present, from where, which version.
+
+ ``source`` is ``"bundled"`` (shipped in the binary), ``"path"`` (a system
+ copy), or ``None`` (missing). Runs ``ffmpeg -version`` once — the caller is
+ a dedicated endpoint, not the hot settings poll.
+ """
+ path = ffmpeg_path()
+ if path is None:
+ return {"available": False, "path": None, "source": None, "version": None}
+ return {
+ "available": True,
+ "path": path,
+ "source": "bundled" if path == _bundled("ffmpeg") else "path",
+ "version": _version(path),
+ }
+
+
+def location_for_ytdlp() -> str | None:
+ """Directory to hand yt-dlp as ``ffmpeg_location``, or None to let it search
+ PATH itself.
+
+ Returned only for a *bundled* ffmpeg: it lives in a directory that is not on
+ PATH, so yt-dlp would otherwise miss it and be unable to merge separate
+ audio+video streams. A PATH copy needs no hint.
+ """
+ base = getattr(sys, "_MEIPASS", None)
+ if base is None:
+ return None
+ return str(Path(base)) if _bundled("ffmpeg") else None
diff --git a/src/azimut/engine/inspect.py b/src/azimut/engine/inspect.py
index 016f4a4..0051c13 100644
--- a/src/azimut/engine/inspect.py
+++ b/src/azimut/engine/inspect.py
@@ -21,7 +21,6 @@ from __future__ import annotations
import base64
import io
import json
-import shutil
import subprocess
from dataclasses import dataclass, field
from datetime import datetime, timezone
@@ -32,6 +31,7 @@ from PIL import Image, ImageChops, ImageEnhance, ImageOps
from PIL.ExifTags import GPSTAGS, TAGS
from ..workspace import Case
+from . import ffmpeg as ffmpeg_engine
from . import media as media_engine
from . import stitch
@@ -318,7 +318,7 @@ def run_analysis(
def ffprobe_available() -> bool:
- return shutil.which("ffprobe") is not None
+ return ffmpeg_engine.ffprobe_available()
def probe(case: Case, rel_path: str) -> dict[str, Any]:
@@ -334,7 +334,7 @@ def probe(case: Case, rel_path: str) -> dict[str, Any]:
if kind == "video" and ffprobe_available():
proc = subprocess.run(
- ["ffprobe", "-v", "error", "-print_format", "json",
+ [ffmpeg_engine.ffprobe_exe(), "-v", "error", "-print_format", "json",
"-show_format", "-show_streams", str(path)],
capture_output=True, timeout=30,
)
@@ -368,7 +368,7 @@ def extract_frame(video_path: Path, time_s: float) -> Image.Image:
if not media_engine.ffmpeg_available():
raise RuntimeError("ffmpeg is required to extract video frames")
proc = subprocess.run(
- ["ffmpeg", "-y", "-loglevel", "error", "-ss", f"{max(time_s, 0):.3f}",
+ [ffmpeg_engine.ffmpeg_exe(), "-y", "-loglevel", "error", "-ss", f"{max(time_s, 0):.3f}",
"-i", str(video_path), "-frames:v", "1", "-f", "image2pipe", "-vcodec", "png", "pipe:1"],
capture_output=True, timeout=60,
)
@@ -470,7 +470,7 @@ def scan_focus(
frame_bytes = w * h
proc = subprocess.Popen(
- ["ffmpeg", "-v", "error", "-i", str(video_path),
+ [ffmpeg_engine.ffmpeg_exe(), "-v", "error", "-i", str(video_path),
"-vf", f"scale={w}:{h}", "-f", "rawvideo", "-pix_fmt", "gray", "pipe:1"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
@@ -841,7 +841,7 @@ def enhance_video(
tmp = case.subdir("media") / f".enhance_{_stamp()}.mp4"
try:
proc = subprocess.run(
- ["ffmpeg", "-y", "-loglevel", "error", "-i", str(src),
+ [ffmpeg_engine.ffmpeg_exe(), "-y", "-loglevel", "error", "-i", str(src),
"-vf", vf, "-c:a", "copy", str(tmp)],
capture_output=True, timeout=600,
)
diff --git a/src/azimut/engine/media.py b/src/azimut/engine/media.py
index f1f4ecb..e60a554 100644
--- a/src/azimut/engine/media.py
+++ b/src/azimut/engine/media.py
@@ -21,6 +21,7 @@ from typing import Any, BinaryIO
from PIL import Image
from ..workspace import Case, ensure_dir
+from . import ffmpeg as ffmpeg_engine
from . import links as link_engine
THUMB_DIR = ".thumbs"
@@ -70,7 +71,7 @@ def unique_path(directory: Path, filename: str) -> Path:
def ffmpeg_available() -> bool:
- return shutil.which("ffmpeg") is not None
+ return ffmpeg_engine.ffmpeg_available()
def make_thumbnail(media_path: Path, thumb_path: Path) -> bool:
@@ -87,7 +88,7 @@ def make_thumbnail(media_path: Path, thumb_path: Path) -> bool:
if kind == "video" and ffmpeg_available():
subprocess.run(
[
- "ffmpeg", "-y", "-loglevel", "error",
+ ffmpeg_engine.ffmpeg_exe(), "-y", "-loglevel", "error",
"-ss", "1", "-i", str(media_path),
"-frames:v", "1", "-vf", f"scale={THUMB_MAX}:-2",
str(thumb_path),
@@ -477,7 +478,13 @@ def download_url(
narrowed = index is not None and not extra_photos
if narrowed:
ydl_opts["playlist_items"] = str(index)
- if not ffmpeg_available():
+ if ffmpeg_available():
+ # a bundled ffmpeg is not on PATH, so yt-dlp can't find it by itself;
+ # point it at the directory (None when ffmpeg is a system PATH copy).
+ location = ffmpeg_engine.location_for_ytdlp()
+ if location:
+ ydl_opts["ffmpeg_location"] = location
+ else:
# without ffmpeg yt-dlp cannot merge separate audio+video streams
ydl_opts["format"] = "best[acodec!=none][vcodec!=none]/best"
if progress_hook:
diff --git a/src/azimut/engine/updates.py b/src/azimut/engine/updates.py
index c5c9d69..61d1b3f 100644
--- a/src/azimut/engine/updates.py
+++ b/src/azimut/engine/updates.py
@@ -17,6 +17,10 @@ import httpx
LATEST_RELEASE_URL = "https://api.github.com/repos/OsintMeThat/azimut/releases/latest"
RELEASES_PAGE_URL = "https://github.com/OsintMeThat/azimut/releases/latest"
+# How much of the release body the pop-up carries. Enough for a changelog,
+# short enough that a runaway release note never bloats the response.
+NOTES_LIMIT = 4000
+
def _parse(version: str) -> tuple[int, ...]:
"""A tag like ``v0.1.2`` (or a bare ``0.1.2``) as a comparable tuple.
@@ -46,6 +50,7 @@ def check(current: str, *, timeout: float = 6.0) -> dict[str, object]:
"latest": None,
"update_available": False,
"url": RELEASES_PAGE_URL,
+ "notes": "",
}
try:
resp = httpx.get(
@@ -64,4 +69,8 @@ def check(current: str, *, timeout: float = 6.0) -> dict[str, object]:
result["update_available"] = is_newer(latest, current)
if body.get("html_url"):
result["url"] = str(body["html_url"])
+ # The release body, shown in the startup pop-up. Markdown from our own
+ # releases; the UI renders it as plain text (no HTML injection), so we
+ # just cap the length to keep the payload sane.
+ result["notes"] = str(body.get("body") or "").strip()[:NOTES_LIMIT]
return result
diff --git a/tests/test_ffmpeg.py b/tests/test_ffmpeg.py
new file mode 100644
index 0000000..d4dc171
--- /dev/null
+++ b/tests/test_ffmpeg.py
@@ -0,0 +1,126 @@
+"""Resolution of the ffmpeg / ffprobe binaries the engines shell out to.
+
+A pip install relies on a system copy on PATH; the release binary bundles one
+beside the executable (sys._MEIPASS). These check both regimes without needing a
+real ffmpeg present.
+"""
+
+from __future__ import annotations
+
+import sys
+
+from azimut.engine import ffmpeg
+
+
+def test_prefers_path_when_not_frozen(monkeypatch):
+ # no sys._MEIPASS (a plain source run) → resolution falls through to PATH
+ monkeypatch.delattr(sys, "_MEIPASS", raising=False)
+ monkeypatch.setattr(ffmpeg.shutil, "which", lambda name: f"/usr/bin/{name}")
+ assert ffmpeg.ffmpeg_path() == "/usr/bin/ffmpeg"
+ assert ffmpeg.ffprobe_path() == "/usr/bin/ffprobe"
+ assert ffmpeg.ffmpeg_available() and ffmpeg.ffprobe_available()
+ # yt-dlp needs no hint for a PATH copy — it searches PATH itself
+ assert ffmpeg.location_for_ytdlp() is None
+
+
+def test_missing_everywhere_is_unavailable(monkeypatch):
+ monkeypatch.delattr(sys, "_MEIPASS", raising=False)
+ monkeypatch.setattr(ffmpeg.shutil, "which", lambda name: None)
+ assert ffmpeg.ffmpeg_path() is None
+ assert not ffmpeg.ffmpeg_available()
+ # the exe helpers still yield the bare name so a subprocess call is well-formed
+ assert ffmpeg.ffmpeg_exe() == "ffmpeg"
+ assert ffmpeg.ffprobe_exe() == "ffprobe"
+
+
+def test_bundled_beats_path(monkeypatch, tmp_path):
+ # simulate a frozen bundle carrying its own ffmpeg + ffprobe
+ exe = ".exe" if sys.platform == "win32" else ""
+ for name in ("ffmpeg", "ffprobe"):
+ (tmp_path / f"{name}{exe}").write_bytes(b"")
+ monkeypatch.setattr(sys, "_MEIPASS", str(tmp_path), raising=False)
+ # PATH also has a copy; the bundled one must win
+ monkeypatch.setattr(ffmpeg.shutil, "which", lambda name: f"/usr/bin/{name}")
+
+ assert ffmpeg.ffmpeg_path() == str(tmp_path / f"ffmpeg{exe}")
+ assert ffmpeg.ffprobe_path() == str(tmp_path / f"ffprobe{exe}")
+ assert ffmpeg.ffmpeg_exe() == str(tmp_path / f"ffmpeg{exe}")
+ # yt-dlp gets pointed at the bundle dir (it isn't on PATH)
+ assert ffmpeg.location_for_ytdlp() == str(tmp_path)
+
+
+def test_frozen_without_bundled_ffmpeg_uses_path(monkeypatch, tmp_path):
+ # a frozen bundle that happens to carry no ffmpeg still falls back to PATH,
+ # and hands yt-dlp no bogus location
+ monkeypatch.setattr(sys, "_MEIPASS", str(tmp_path), raising=False)
+ monkeypatch.setattr(ffmpeg.shutil, "which", lambda name: f"/usr/bin/{name}")
+ assert ffmpeg.ffmpeg_path() == "/usr/bin/ffmpeg"
+ assert ffmpeg.location_for_ytdlp() is None
+
+
+def test_download_points_ytdlp_at_the_bundled_ffmpeg(client, monkeypatch):
+ """A bundled ffmpeg isn't on PATH, so the download opts must carry
+ ``ffmpeg_location`` or yt-dlp can't merge audio+video."""
+ from azimut.engine import media
+ from azimut.workspace import Case
+
+ monkeypatch.setattr(media.ffmpeg_engine, "ffmpeg_available", lambda: True)
+ monkeypatch.setattr(
+ media.ffmpeg_engine, "location_for_ytdlp", lambda: "/bundle/dir"
+ )
+
+ captured: dict = {}
+
+ class _FakeYDL:
+ def __init__(self, opts):
+ captured.update(opts)
+
+ def __enter__(self):
+ raise RuntimeError("stop — we only care about the opts")
+
+ def __exit__(self, *a):
+ return False
+
+ fake_mod = type("m", (), {"YoutubeDL": _FakeYDL})
+ monkeypatch.setitem(sys.modules, "yt_dlp", fake_mod)
+
+ cid = client.post("/api/cases", json={"name": "DL"}).json()["id"]
+ case = Case.open(cid)
+ try:
+ media.download_url(case, "https://example.com/v")
+ except RuntimeError:
+ pass
+ assert captured.get("ffmpeg_location") == "/bundle/dir"
+ # ffmpeg present → no degraded single-stream format forced
+ assert "format" not in captured
+
+
+def test_download_forces_single_stream_without_ffmpeg(client, monkeypatch):
+ from azimut.engine import media
+ from azimut.workspace import Case
+
+ monkeypatch.setattr(media.ffmpeg_engine, "ffmpeg_available", lambda: False)
+
+ captured: dict = {}
+
+ class _FakeYDL:
+ def __init__(self, opts):
+ captured.update(opts)
+
+ def __enter__(self):
+ raise RuntimeError("stop")
+
+ def __exit__(self, *a):
+ return False
+
+ monkeypatch.setitem(sys.modules, "yt_dlp", type("m", (), {"YoutubeDL": _FakeYDL}))
+
+ cid = client.post("/api/cases", json={"name": "DL"}).json()["id"]
+ case = Case.open(cid)
+ try:
+ media.download_url(case, "https://example.com/v")
+ except RuntimeError:
+ pass
+ # no ffmpeg → the degraded muxed-only format is forced, no location hint
+ assert captured.get("format") == "best[acodec!=none][vcodec!=none]/best"
+ assert "ffmpeg_location" not in captured
diff --git a/tests/test_satellite_api.py b/tests/test_satellite_api.py
index 2bd4979..f397468 100644
--- a/tests/test_satellite_api.py
+++ b/tests/test_satellite_api.py
@@ -499,12 +499,46 @@ def test_tile_proxy_rejects_out_of_range_coordinates(client):
assert client.get("/api/tiles/esri-world-imagery/2/0/-1").status_code == 422
+def test_tile_proxy_reuses_one_pooled_client(client, monkeypatch):
+ """Every tile goes through one shared, keep-alive client — not a fresh
+ connection per tile. Several tiles must hit the same client instance."""
+ import httpx
+
+ from azimut.api import satellite
+
+ seen: list[int] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(id(request))
+ return httpx.Response(200, content=_png_bytes(), headers={"content-type": "image/png"})
+
+ pooled = httpx.Client(transport=httpx.MockTransport(handler))
+ monkeypatch.setattr(satellite, "_tile_client", pooled)
+ # spy: the route must fetch through the pooled client, never httpx.get
+ monkeypatch.setattr(httpx, "get", lambda *a, **k: pytest.fail("used a one-shot connection"))
+
+ calls = {"n": 0}
+ real_get = pooled.get
+
+ def counting_get(*a, **k):
+ calls["n"] += 1
+ return real_get(*a, **k)
+
+ monkeypatch.setattr(pooled, "get", counting_get)
+
+ for x in (16600, 16601, 16602):
+ r = client.get(f"/api/tiles/esri-world-imagery/15/{x}/11278")
+ assert r.status_code == 200
+ assert calls["n"] == 3 # three tiles, all served by the one pooled client
+
+
def test_tile_proxy_benches_google_on_a_persistent_403(client, monkeypatch):
"""A 403 that survives the session re-mint names the key (EEA policy,
revoked key) — the basemap must stop being offered, with Google's own
sentence stored as the reason."""
import httpx
+ from azimut.api import satellite
from azimut.engine import google_tiles
client.put("/api/settings/keys", json={"google": "AIza.x"})
@@ -517,13 +551,15 @@ def test_tile_proxy_benches_google_on_a_persistent_403(client, monkeypatch):
b'"Satellite tiles are not available for your account and region."}}'
)
- def forbidden(url, **kwargs):
+ def forbidden(request: httpx.Request) -> httpx.Response:
return httpx.Response(
403, content=eea, headers={"content-type": "application/json"},
- request=httpx.Request("GET", url),
)
- monkeypatch.setattr(httpx, "get", forbidden)
+ # the tile proxy pools one shared client; swap in one with a mock transport
+ monkeypatch.setattr(
+ satellite, "_tile_client", httpx.Client(transport=httpx.MockTransport(forbidden))
+ )
r = client.get("/api/tiles/google-satellite/15/16597/11278")
assert r.status_code == 403 # passthrough, as before
diff --git a/tests/test_settings_api.py b/tests/test_settings_api.py
index 0247586..c6e391d 100644
--- a/tests/test_settings_api.py
+++ b/tests/test_settings_api.py
@@ -13,6 +13,30 @@ def test_get_settings_defaults(client):
assert body["month"] == config.month_key()
+def test_ffmpeg_info_reports_bundled_copy(client, monkeypatch):
+ from azimut.engine import ffmpeg
+
+ monkeypatch.setattr(ffmpeg, "ffmpeg_path", lambda: "/opt/azimut/ffmpeg")
+ monkeypatch.setattr(ffmpeg, "_bundled", lambda name: "/opt/azimut/ffmpeg")
+ monkeypatch.setattr(ffmpeg, "_version", lambda exe: "n7.1")
+
+ body = client.get("/api/settings/ffmpeg").json()
+ assert body == {
+ "available": True,
+ "path": "/opt/azimut/ffmpeg",
+ "source": "bundled",
+ "version": "n7.1",
+ }
+
+
+def test_ffmpeg_info_reports_missing(client, monkeypatch):
+ from azimut.engine import ffmpeg
+
+ monkeypatch.setattr(ffmpeg, "ffmpeg_path", lambda: None)
+ body = client.get("/api/settings/ffmpeg").json()
+ assert body == {"available": False, "path": None, "source": None, "version": None}
+
+
def test_put_keys_lights_up_keyed_providers(client):
saved = client.put("/api/settings/keys", json={"mapbox": "pk.abc"}).json()
assert saved["api_keys"] == {"mapbox": "pk.abc"}
@@ -75,6 +99,22 @@ def _upstream(status=200, content=b"JPEGDATA", headers=None):
return get
+def _use_tile_upstream(monkeypatch, handler):
+ """Route the tile proxy's pooled client through *handler* (``url -> Response``).
+
+ The proxy reuses one shared httpx.Client, so patching module-level
+ ``httpx.get`` no longer intercepts it — swap in a client with a mock
+ transport that calls the same handler the old tests used.
+ """
+ from azimut.api import satellite
+
+ monkeypatch.setattr(
+ satellite,
+ "_tile_client",
+ httpx.Client(transport=httpx.MockTransport(lambda request: handler(str(request.url)))),
+ )
+
+
def _png_bytes(size=512, colour=(10, 120, 10)):
"""A real encoded tile — the overzoom path decodes what it magnifies."""
import io
@@ -89,7 +129,7 @@ def _png_bytes(size=512, colour=(10, 120, 10)):
def test_tile_proxy_serves_and_counts_exactly(client, monkeypatch):
client.put("/api/settings/keys", json={"mapbox": "pk.abc"})
upstream = _upstream(headers={"cache-control": "max-age=43200"})
- monkeypatch.setattr(httpx, "get", upstream)
+ _use_tile_upstream(monkeypatch, upstream)
r = client.get("/api/tiles/mapbox-satellite/14/8298/5639")
assert r.status_code == 200
@@ -108,7 +148,7 @@ def test_tile_proxy_serves_and_counts_exactly(client, monkeypatch):
def test_tile_proxy_does_not_count_errors(client, monkeypatch):
client.put("/api/settings/keys", json={"mapbox": "pk.abc"})
- monkeypatch.setattr(httpx, "get", _upstream(status=404, content=b""))
+ _use_tile_upstream(monkeypatch, _upstream(status=404, content=b""))
r = client.get("/api/tiles/mapbox-satellite/14/0/0")
assert r.status_code == 404
assert client.get("/api/settings").json()["usage"] == {}
@@ -134,7 +174,7 @@ def test_tile_proxy_google_remints_session_on_403(client, monkeypatch):
request=httpx.Request("GET", url),
)
- monkeypatch.setattr(httpx, "get", get)
+ _use_tile_upstream(monkeypatch, get)
r = client.get("/api/tiles/google-satellite/15/16597/11278")
assert r.status_code == 200
assert r.content == b"TILE"
@@ -151,6 +191,22 @@ def test_get_settings_exposes_prefs_and_free_tier(client):
assert body["eco_zoom_fallback"] is True
assert body["providers_enabled"] == {}
assert body["usage_overrides"] == {}
+ # startup update pop-up: on by default, nothing muted yet
+ assert body["update_check_on_start"] is True
+ assert body["update_dismissed_version"] == ""
+
+
+def test_put_prefs_roundtrips_update_popup_prefs(client):
+ saved = client.put(
+ "/api/settings/prefs",
+ json={"update_check_on_start": False, "update_dismissed_version": "v0.2.0"},
+ ).json()
+ assert saved["update_check_on_start"] is False
+ assert saved["update_dismissed_version"] == "v0.2.0"
+ # partial PUT leaves the other one untouched
+ saved = client.put("/api/settings/prefs", json={"update_check_on_start": True}).json()
+ assert saved["update_check_on_start"] is True
+ assert saved["update_dismissed_version"] == "v0.2.0"
def test_put_prefs_roundtrips_and_filters_unknown_providers(client):
@@ -184,7 +240,7 @@ def test_disabled_provider_hidden_but_key_kept(client):
def test_tile_proxy_blocks_at_soft_limit_and_override_lifts(client, monkeypatch):
client.put("/api/settings/keys", json={"mapbox": "pk.abc"})
- monkeypatch.setattr(httpx, "get", _upstream())
+ _use_tile_upstream(monkeypatch, _upstream())
config.record_usage("mapbox", int(config.FREE_TIER["mapbox"] * config.BLOCK_SHARE))
r = client.get("/api/tiles/mapbox-satellite/14/8298/5639")
@@ -198,7 +254,7 @@ def test_tile_proxy_blocks_at_soft_limit_and_override_lifts(client, monkeypatch)
def test_tile_proxy_disk_cache_serves_repeats_without_rebilling(client, monkeypatch):
client.put("/api/settings/keys", json={"mapbox": "pk.abc"})
upstream = _upstream()
- monkeypatch.setattr(httpx, "get", upstream)
+ _use_tile_upstream(monkeypatch, upstream)
assert client.get("/api/tiles/mapbox-satellite/14/8298/5639").status_code == 200
r = client.get("/api/tiles/mapbox-satellite/14/8298/5639")
@@ -215,7 +271,7 @@ def test_tile_proxy_never_caches_google(client, monkeypatch):
google_tiles, "resolve_template", lambda url, **kw: url.replace("{session}", "tok")
)
upstream = _upstream()
- monkeypatch.setattr(httpx, "get", upstream)
+ _use_tile_upstream(monkeypatch, upstream)
client.get("/api/tiles/google-satellite/15/16597/11278")
client.get("/api/tiles/google-satellite/15/16597/11278")
@@ -249,7 +305,7 @@ def test_tile_proxy_overzoom_fills_coverage_gaps(client, monkeypatch):
)
get.urls = []
- monkeypatch.setattr(httpx, "get", get)
+ _use_tile_upstream(monkeypatch, get)
r = client.get("/api/tiles/esri-world-imagery/19/155000/400000")
assert r.status_code == 200
@@ -284,7 +340,7 @@ def test_tile_proxy_placeholder_tile_triggers_overzoom(client, monkeypatch):
request=httpx.Request("GET", url),
)
- monkeypatch.setattr(httpx, "get", get)
+ _use_tile_upstream(monkeypatch, get)
r = client.get("/api/tiles/esri-world-imagery/19/155000/400000")
assert r.status_code == 200
assert r.headers["x-azimut-overzoom"] == "1"
@@ -360,7 +416,7 @@ def test_test_key_sentinelhub_reports_the_services_own_words(client, monkeypatch
def test_sentinel2_tile_proxy_offsets_the_matrix_and_counts_tiles(client, monkeypatch):
client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
upstream = _upstream()
- monkeypatch.setattr(httpx, "get", upstream)
+ _use_tile_upstream(monkeypatch, upstream)
# the frontend asks in grid levels; WMTS wants that level named one higher
assert client.get("/api/tiles/sentinel2/13/4151/2818").status_code == 200
@@ -376,7 +432,7 @@ def test_sentinel2_proxy_never_asks_upstream_past_the_native_ceiling(client, mon
tile magnified instead."""
client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
upstream = _upstream(content=_png_bytes(), headers={"content-type": "image/png"})
- monkeypatch.setattr(httpx, "get", upstream)
+ _use_tile_upstream(monkeypatch, upstream)
# grid 17 == view z18 for a 512px provider; native is grid 13 (TILEMATRIX 14)
r = client.get("/api/tiles/sentinel2/17/66424/45097")
@@ -478,7 +534,7 @@ def test_free_tier_override_moves_the_soft_block(client, monkeypatch):
# the block now measures against the user's figure, not the shipped default
config.record_usage("sentinelhub", 900) # 90% of 1000
- monkeypatch.setattr(httpx, "get", _upstream())
+ _use_tile_upstream(monkeypatch, _upstream())
assert client.get("/api/tiles/sentinel2/13/4151/2818").status_code == 429
# ...and clearing it restores the default, which 900 is nowhere near
diff --git a/tests/test_updates.py b/tests/test_updates.py
index d7309af..5876ecd 100644
--- a/tests/test_updates.py
+++ b/tests/test_updates.py
@@ -59,9 +59,23 @@ def test_check_reports_a_newer_release(monkeypatch):
"latest": "v9.9.9",
"update_available": True,
"url": "https://x/rel",
+ "notes": "",
}
+def test_check_carries_release_notes_capped(monkeypatch):
+ monkeypatch.setattr(
+ updates.httpx,
+ "get",
+ lambda *a, **k: FakeResponse(
+ {"tag_name": "v9.9.9", "body": " ## What's new\n- stuff " + "x" * 9000}
+ ),
+ )
+ result = updates.check("0.1.1")
+ assert result["notes"].startswith("## What's new") # stripped
+ assert len(result["notes"]) == updates.NOTES_LIMIT # capped
+
+
def test_check_up_to_date(monkeypatch):
monkeypatch.setattr(
updates.httpx, "get", lambda *a, **k: FakeResponse({"tag_name": "v0.1.1"})