Skip to content

Home Information - Your home, your data, organized.

Python

Add Immich integration (#381) + picker error-channel refactor (#383)

Tony Cc752b411391d
diff --git a/docs/Integrations.md b/docs/Integrations.md
index a3679527..5108e728 100644
--- a/docs/Integrations.md
+++ b/docs/Integrations.md
@@ -15,10 +15,10 @@ enter it.
## Enabling an integration
Most integrations are configured from the **Connectors** tab on the
-Configure page. Paperless-ngx is configured from the **Content
-Sources** tab instead, because it contributes searchable document
-references rather than importing items — see its own page for the
-walkthrough.
+Configure page. Content-source integrations (Paperless-ngx and
+Immich) are configured from the **Content Sources** tab instead,
+because they contribute searchable references rather than importing
+items — see each integration's own page for the walkthrough.
For a Connectors-tab integration:
@@ -47,6 +47,11 @@ For a Connectors-tab integration:
- **[HomeBox](integrations/homebox.md)** — home inventory tracking.
Imports HomeBox items as read-only HI items with custom fields and
attached files (manuals, receipts, photos).
+- **[Immich](integrations/immich.md)** — self-hosted photo and video
+ library. Does not import items; instead lets you search Immich
+ from inside HI and attach matching assets (appliance photos, room
+ snapshots, serial-plate shots) as link references on items and
+ Locations you already have.
- **[Paperless-ngx](integrations/paperless-ngx.md)** — document
management. Does not import items; instead lets you search
paperless from inside HI and attach matching documents (warranty
@@ -61,9 +66,10 @@ real-world fixes over time — start there if something is not working.
Most integrations on this page are live: HI mirrors the upstream
system continuously and changes flow in via the update action.
-Paperless-ngx is a different shape — it contributes attachable
-document references rather than importing items, and it talks to
-paperless only when the operator opens the picker.
+Content-source integrations (Paperless-ngx, Immich) are a different
+shape — they contribute attachable references rather than importing
+items, and they talk to the upstream service only when the operator
+opens the picker.
A separate feature, [Data Import](DataImport.md), is a one-time
copy with no ongoing upstream link. Some integrations (HomeBox
diff --git a/docs/dev/integrations/immich.md b/docs/dev/integrations/immich.md
new file mode 100644
index 00000000..7adabff2
--- /dev/null
+++ b/docs/dev/integrations/immich.md
@@ -0,0 +1,124 @@
+# Immich
+
+## Overview
+
+Immich declares only the `ATTRIBUTE_REFERENCE` capability — no
+connector, no importer, no manager singleton, no monitors. The
+gateway returns a referencer, and the referencer translates Immich's
+smart-search response into `AttributeReferenceResult` rows. Per-search
+HTTP happens inline; there is no cached client. The integration
+mirrors the paperless-ngx shape almost exactly — same file layout,
+same lifecycle, same thumbnail-proxy pattern — with the differences
+documented under [Implementation notes](#implementation-notes).
+
+## Key modules
+
+- `src/hi/services/immich/integration.py` — `ImmichGateway`. Gateway
+ entry point; `validate_access` lives here.
+- `src/hi/services/immich/im_referencer.py` —
+ `ImmichAttributeReferencer`. Smart-search dispatch + asset
+ translation + secondary-text builder.
+- `src/hi/services/immich/im_client.py` — `ImmichClient` and
+ `build_client`. Thin `requests.Session` wrapper.
+- `src/hi/services/immich/im_models.py` — `ImmichApi`. Wire-format
+ string centralization (paths, header name, JSON keys).
+- `src/hi/services/immich/views.py` — `ImmichThumbnailProxyView`.
+ Server-side thumbnail fetcher.
+- `src/hi/services/immich/im_validation.py` — schema-only attribute
+ validation shared by gateway + referencer.
+- `src/hi/simulator/services/immich/` — Immich API simulator (smart
+ search, metadata-probe stub, thumbnail, photo preview).
+
+## API patterns
+
+Auth: `x-api-key: <value>` on every upstream call. Keys are scoped
+in Immich; `asset.read` is the only scope the integration requires.
+
+Endpoints touched at runtime:
+
+- `POST /api/search/smart` — body `{"query": ..., "size": N}`. Used
+ for every picker search.
+- `GET /api/assets/<id>/thumbnail?size=thumbnail` — streamed through
+ `ImmichThumbnailProxyView`.
+- `<base>/photos/<id>` — Immich's per-asset web URL. Persisted
+ unchanged as `source_url`; the picker links to it.
+
+Endpoint touched at config time only:
+
+- `POST /api/search/metadata` with body `{"size": 1}` — the
+ `validate_access` probe. Cheap (no CLIP embedding) and exercises
+ the same `asset.read` scope as the runtime smart endpoint.
+
+No rate limiting or polling cadence considerations — the integration
+makes one search call per picker query, no background loop.
+
+## Implementation notes
+
+- **Smart search only, no metadata mode.** The earlier design
+ exposed `SEARCH_MODE = metadata | smart` as a config attribute.
+ The `/api/search/metadata` endpoint accepts only structured filters
+ (`originalFileName`, `city`, dates, camera, etc.) — there is no
+ free-text `query` field, and Immich silently ignores unknown body
+ keys, so an apparent "metadata text search" returned the default
+ recency list regardless of input. Smart (CLIP) matches what
+ Immich's own web UI search bar does, so it is the only exposed
+ mode. The metadata endpoint is retained as the probe target
+ because it is cheap.
+- **No `_extract_snippet` analogue.** Paperless's search response
+ carries full document `content`; Immich assets have nothing
+ equivalent (no description field on `MetadataSearchDto`, no OCR
+ text in the smart-search response). `_build_secondary_text`
+ composes a short blurb from `fileCreatedAt` + `exifInfo.city` /
+ `country` instead; returns `None` when neither is present so the
+ picker template omits the snippet row entirely.
+- **Error channel via `AttributeReferenceSearchResult.error_message`.**
+ Each failure path (no config, HTTP 401, HTTP 403, generic HTTP
+ failure, connectivity, unexpected) returns the dataclass with a
+ named user-facing message instead of raising or returning an empty
+ list. The `validate_access` probe and `search_references` use
+ consistent wording for the same root causes, so operators see the
+ same fix in both the configure modal and the picker banner.
+- **Nested response shape.** Immich's smart-search response wraps
+ results one level deeper than typical REST APIs:
+ `{"assets": {"items": [...], "total": N, "count": N,
+ "nextPage": null}, "albums": {...}}`. The referencer defends
+ against missing `assets` and missing `items` so a shape drift
+ yields an empty result list, not a crash.
+- **Asset IDs are UUID strings.** The thumbnail proxy URL uses
+ `<str:asset_id>`, not `<int:>` like paperless's document id.
+- **Source URL is NOT proxied.** Same reasoning as paperless: the
+ persisted `source_url` is Immich's own per-asset web URL.
+ Operators authenticate with Immich's own session when they click.
+- **No manager singleton.** Same as paperless. The client is built
+ per-call from the stored attributes; `build_client` is the entry
+ point to refactor through if a reason to cache emerges.
+- **Single deployment.** One Immich integration per app directory.
+ Multiple Immich instances are not supported.
+
+## Testing approach
+
+Tests live in `src/hi/services/immich/tests/` and mock all upstream
+HTTP. Coverage spans client (URL/body/header shape, factory
+disabled/missing/empty paths), gateway (`validate_access` 200 / 401
+/ 403 / 5xx / connectivity / schema-invalid short-circuit), referencer
+(search dispatch, asset translation, `_build_secondary_text` variants,
+error-message paths for each failure mode), and the thumbnail proxy
+view (success / upstream 404 / upstream 401 / connectivity).
+
+For end-to-end exercise without a real Immich install, use the
+simulator at `src/hi/simulator/services/immich/`. It supports
+parametric response shapes (result count, EXIF on/off, artificial
+latency) and a `/photos/<id>` preview page so saved source links
+land somewhere instead of 404ing. Auth-failure simulation goes
+through the framework-wide `ServiceFaultMode` — `AUTH_FAIL` returns
+401 (key unrecognized), `FORBIDDEN` returns 403 (key lacks
+`asset.read`); both exercise the corresponding distinct error
+messages the integration produces.
+
+## References
+
+- Upstream API: <https://docs.immich.app/api/>
+- Smart search semantics: <https://docs.immich.app/features/searching>
+- Capability framework: [Integration Guidelines](integration-guidelines.md)
+- Related: [paperless-ngx integration](paperless-ngx.md) — same
+ capability shape; many design choices carry over.
diff --git a/docs/dev/integrations/integration-guidelines.md b/docs/dev/integrations/integration-guidelines.md
index fa5b2a2a..a6c5f599 100644
--- a/docs/dev/integrations/integration-guidelines.md
+++ b/docs/dev/integrations/integration-guidelines.md
@@ -14,7 +14,7 @@ Each integration declares its `IntegrationCapability` set on `IntegrationMetaDat
- **`CONNECT`** — live mirror of an upstream system. Realized by an `IntegrationConnector` subclass returned from `IntegrationGateway.get_connector()`. All four "Connectors"-tab integrations (HA, ZM, Frigate, HomeBox) declare CONNECT.
- **`IMPORT`** — one-shot copy of upstream items into HI as locally-owned entities. Realized by an `IntegrationImporter` subclass returned from `IntegrationGateway.get_importer()`. HomeBox is the only integration to declare IMPORT alongside CONNECT today (see [`docs/dev/integrations/data-import.md`](data-import.md) for the developer surface).
-- **`ATTRIBUTE_REFERENCE`** — search-and-attach surface that contributes URL attributes to existing Entity / Location records (no entity import, no live mirror). Realized by an `IntegrationAttributeReferencer` subclass returned from `IntegrationGateway.get_attribute_referencer()`. Paperless-ngx is the only integration to declare ATTRIBUTE_REFERENCE today. ATTRIBUTE_REFERENCE-only integrations are configured on a sibling tab labeled "Content Sources" instead of "Connectors" — the page chrome differs because there's no monitor / sync lifecycle.
+- **`ATTRIBUTE_REFERENCE`** — search-and-attach surface that contributes URL attributes to existing Entity / Location records (no entity import, no live mirror). Realized by an `IntegrationAttributeReferencer` subclass returned from `IntegrationGateway.get_attribute_referencer()`. Paperless-ngx and Immich declare ATTRIBUTE_REFERENCE today. ATTRIBUTE_REFERENCE-only integrations are configured on a sibling tab labeled "Content Sources" instead of "Connectors" — the page chrome differs because there's no monitor / sync lifecycle.
The three per-capability classes (`IntegrationConnector`, `IntegrationImporter`, `IntegrationAttributeReferencer`) share a common base `CapabilityGateway` (`hi/integrations/capability_gateway.py`). Each declares a `capability` class attribute identifying the `IntegrationCapability` it realizes, and overrides cross-capability concerns: `get_metadata()` (abstract), `get_description()` (operator-facing one-line description), and `get_attribute_actions_template_name()` (optional template fragment for the attribute form's action bar). Capability-specific concerns (sync, import, search) stay on the subclass. Adding a new capability means subclassing `CapabilityGateway`, declaring the `capability` class attribute, and overriding only the methods that apply to the new shape.
@@ -82,9 +82,9 @@ Each integration is a self-contained Django app under `hi/services/<integration_
- `monitors.py` — `PeriodicMonitor` subclass(es) for polling and health probes
- `apps.py`, `urls.py`, `views.py` — standard Django wiring
-`<prefix>` is a short integration mnemonic (`hass_`, `zm_`, `hb_`, `pl_`). Keep it consistent across all files within the integration.
+`<prefix>` is a short integration mnemonic (`hass_`, `zm_`, `hb_`, `pl_`, `im_`). Keep it consistent across all files within the integration.
-ATTRIBUTE_REFERENCE-only integrations (paperless-ngx today) don't need all the role-files above — they have no monitors, no sync, no converter, and no manager singleton (the capability has no live state to own). They still ship `integration.py`, `<prefix>_metadata.py`, `<prefix>_client.py`, plus a `<prefix>_referencer.py` for the `IntegrationAttributeReferencer` subclass and `<prefix>_models.py` (or `_constants.py`) for the wire-format strings.
+ATTRIBUTE_REFERENCE-only integrations (paperless-ngx and Immich today) don't need all the role-files above — they have no monitors, no sync, no converter, and no manager singleton (the capability has no live state to own). They still ship `integration.py`, `<prefix>_metadata.py`, `<prefix>_client.py`, plus a `<prefix>_referencer.py` for the `IntegrationAttributeReferencer` subclass and `<prefix>_models.py` (or `_constants.py`) for the wire-format strings.
### Centralize wire-format strings
Every integration centralizes its wire-format strings — domain/endpoint names, attribute keys, device-class names, service names, special-state sentinels — in a single class per integration. The exemplar is `HassApi` in `hi/services/hass/hass_models.py`; ZoneMinder's equivalent is `hi/services/zoneminder/constants.py`. The converter, sync, controller, and service composer all import their wire strings from this single source.
@@ -208,6 +208,7 @@ Custom exception hierarchy (`hi/integrations/exceptions.py`):
- `hi.services.frigate/` — Frigate (CONNECT).
- `hi.services.homebox/` — HomeBox (CONNECT + IMPORT).
- `hi.services.paperless/` — paperless-ngx (ATTRIBUTE_REFERENCE-only). Slimmer file layout — no manager singleton, no monitors, no converter — because the capability has no live state to own.
+- `hi.services.immich/` — Immich (ATTRIBUTE_REFERENCE-only). Same slimmer layout as paperless-ngx.
## Related Documentation
- [Service Patterns](service-patterns.md)
diff --git a/docs/dev/shared/commenting-guidelines.md b/docs/dev/shared/commenting-guidelines.md
index 9a33f116..92793aa6 100644
--- a/docs/dev/shared/commenting-guidelines.md
+++ b/docs/dev/shared/commenting-guidelines.md
@@ -102,6 +102,7 @@ Remove comments that fall into any of these categories. These are the patterns o
- "Previously we Z, but we changed it because…"
- "This fixes the bug where…" (the fix is the code; the bug story is the commit).
- "Mirrors how X does it" / "Same pattern as Y."
+- **Parallel-integration archeology**: "Like the paperless simulator…" / "Same shape as the homebox integration…" / "(same lifecycle as `_fault_mode` on the base class)" / "Same approach HomeBox uses for Z." Recurs heavily when a new integration is written by mirroring a sister integration — the parallel is real *for the author*, but the cold reader only needs the current file's contract, not a pointer to chase the sister file. Strip the cross-reference; keep any standalone substance the surrounding sentence carries.
- "Without this, Z happens" / "We use A rather than B because of bug C."
These narrate the path to the current code. The reader only needs the current code.
diff --git a/docs/integrations/immich.md b/docs/integrations/immich.md
new file mode 100644
index 00000000..ee9051a0
--- /dev/null
+++ b/docs/integrations/immich.md
@@ -0,0 +1,148 @@
+<img src="../../src/hi/static/img/hi-logo-w-tagline-197x96.png" alt="Home Information Logo" width="128">
+
+# Immich
+
+## Overview
+
+This integration lets **Home Information (HI)** search an **Immich**
+self-hosted photo and video library and attach individual assets from it as
+references on existing HI items and Locations. Immich does not import any
+items into HI — it contributes references that get saved as links on items
+you already have. Typical use cases: link an appliance's serial-plate
+photo to its HI item, attach a room photo to a Location, or save a
+before/after maintenance shot to the relevant HI item or location.
+
+## Prerequisites
+
+- A reachable Immich server. The HI server must be able to reach
+ Immich over HTTP or HTTPS at the URL you will configure;
+ cross-origin browser fetches are not used, so reverse proxies are
+ fine as long as the HI server can reach the address.
+- An Immich user account, signed in to the Immich web UI.
+- The ability to create API keys for that account.
+
+## Obtaining credentials
+
+1. Sign in to Immich as the user whose photo visibility you want to
+ expose through HI. The API key inherits that user's visibility —
+ shared and partner-shared assets are included, anything outside
+ the user's view is not.
+2. Click your profile picture (top-right) and choose **Account
+ Settings**.
+3. Open the **API Keys** section and click **New API Key**.
+4. Grant at least the **`asset.read`** permission. No other scopes
+ are required for this integration. Name the key something you
+ will recognize later (e.g. "Home Information") and copy the
+ generated key.
+
+## Configuration values
+
+| Field | What to enter | Notes |
+|-------|---------------|-------|
+| API URL | Base URL of your Immich server, e.g. `https://immich.example.com/` | Either form works (trailing slash optional). Use the same scheme + host you use in the browser. The integration appends `/api/...` paths internally. |
+| API Key | The key copied from Immich's Account Settings → API Keys | Sent as the `x-api-key` header on every upstream call. Treated as a secret. |
+
+## Setup walkthrough
+
+Immich is configured from the **Content Sources** tab on the
+Configure page (it is not on the Connectors tab — see
+[Integrations](../Integrations.md) for the distinction).
+
+1. In HI, click **CONFIGURE** at the bottom of the screen.
+2. Select the **Content Sources** tab.
+3. Choose **Immich** and fill in the two configuration values above.
+ **Test Connection** issues a small probe against your Immich
+ server and reports back; **Save** records the values.
+
+Once Immich is configured, use it from any item or Location edit
+page:
+
+1. Click **Link Content** in the action bar to open the picker.
+2. Type a query (e.g. "kitchen faucet", "serial plate", "summer
+ sunset"), tick the assets you want, and click **Add Links** (the
+ button shows the running count, e.g. "Add 3 Links").
+
+Each selection becomes a new attribute on the item — the attribute's
+name is the asset's filename and its value is the per-asset URL on
+your Immich server. Clicking the saved link later takes you to
+Immich directly (you authenticate with Immich's own session).
+
+Search is powered by Immich's **Smart Search** (CLIP semantic
+search), the same engine that drives Immich's own web UI search bar.
+Natural-language queries work — you do not need to remember filenames.
+
+## Troubleshooting
+
+### Test Connection fails with "Immich API key not recognized"
+
+The key was rejected (HTTP 401). Verify the key in Immich's Account
+Settings → API Keys and re-paste it. Keys are sensitive to
+leading/trailing whitespace. If the key was deleted in Immich, create
+a new one and update the field.
+
+### Test Connection fails with "missing the `asset.read` permission"
+
+The key is valid but lacks the required scope (HTTP 403). Open the
+key in Immich's Account Settings → API Keys and confirm `asset.read`
+is granted; recreate the key if the scope cannot be added after the
+fact.
+
+### Test Connection fails with "Immich unreachable"
+
+The HI server cannot reach the configured URL. Check the scheme
+(`http` vs. `https`), hostname, and port; from a shell on the HI
+server, try `curl -I <API URL>` to confirm reachability.
+
+### Picker returns no results
+
+Confirm the query against Immich's own web search bar as the same
+user whose key you configured. If Immich's search returns nothing
+for the same query, the key's user lacks visibility into the assets
+you expect — try the same query while signed into Immich as that
+user. Smart search is semantic, so try simpler or more concrete
+terms ("blue car", "kitchen sink") rather than long descriptions.
+
+### Picker shows a red error banner
+
+The integration could not complete the search (auth rejected, server
+unreachable, or unexpected upstream response). The banner names the
+specific failure mode; use the corresponding entry above to resolve
+it. The picker stays usable — you can retry after fixing the
+configuration.
+
+### Thumbnails do not load in the picker
+
+Thumbnails are fetched through HI so the browser does not need an
+Immich session. If thumbnails appear broken, check the HI logs for
+`Immich thumb proxy` warnings — the upstream URL or key is likely
+misconfigured. The picker still works without thumbnails; the
+fallback icon is used.
+
+### Saved links open Immich's login page
+
+The saved link points to Immich's per-asset URL; clicking it takes
+you to Immich directly, not through HI. You authenticate with
+Immich's own session. If you are not signed in to Immich when you
+click, Immich will prompt you.
+
+## Known limitations
+
+- Search uses Immich's Smart Search exclusively. Filename-only or
+ strictly-structured metadata search is not exposed; Immich's own
+ `/api/search/metadata` endpoint has no free-text query field, so
+ there is no second mode that would meaningfully behave differently
+ for typed queries.
+- Videos and images both appear in results. HI only stores the
+ resulting link, so the linked asset's type is Immich's concern.
+- No album browsing or album-scoped search. The picker queries
+ Immich's whole searchable corpus for the configured key.
+- A single thumbnail size is used. The picker's responsive layout
+ scales it to fit; thumbnails do not adapt per-result.
+- Saved attribute links point to your Immich server's URL. If you
+ later reconfigure Immich at a different host, those saved links
+ will not automatically follow.
+- There is no continuous sync. The integration only fetches when an
+ operator opens the picker and searches. No background polling, no
+ monitor health UI.
+- The integration does not create HI items of its own. Assets are
+ only attachable to items / Locations that already exist in HI.
diff --git a/docs/integrations/paperless-ngx.md b/docs/integrations/paperless-ngx.md
index d93e62ab..12c5febc 100644
--- a/docs/integrations/paperless-ngx.md
+++ b/docs/integrations/paperless-ngx.md
@@ -4,14 +4,13 @@
## Overview
-This integration lets **Home Information (HI)** search a
-**paperless-ngx (paperless)** server and attach documents from it as
-references on existing HI items and Locations. Unlike the other
-integrations on the integrations page, paperless does not import any
-items into HI — it contributes searchable references that get saved
-as link attributes (title + URL) on items you already have. Typical
-use case: link a dishwasher's warranty PDF, a thermostat's manual,
-or a property's deed to the matching HI item or Location.
+This integration lets **Home Information (HI)** search a **paperless-ngx
+(paperless)** server and attach documents from it as references on existing
+HI items and Locations. Unlike the other integrations on the integrations
+page, paperless does not import any items into HI — it contributes
+references that get saved as link on items you already have. Typical use
+case: link a dishwasher's warranty PDF, a thermostat's manual, or a
+property's deed to the matching HI item or Location.
## Prerequisites
diff --git a/src/hi/integrations/referencer/integration_referencer.py b/src/hi/integrations/referencer/integration_referencer.py
index ac440db1..2da29e8d 100644
--- a/src/hi/integrations/referencer/integration_referencer.py
+++ b/src/hi/integrations/referencer/integration_referencer.py
@@ -17,7 +17,7 @@ from hi.integrations.enums import IntegrationCapability
from hi.integrations.models import IntegrationAttribute
from hi.integrations.transient_models import IntegrationValidationResult
-from .transient_models import AttributeReferenceResult
+from .transient_models import AttributeReferenceSearchResult
class IntegrationAttributeReferencer( CapabilityGateway ):
@@ -42,20 +42,28 @@ class IntegrationAttributeReferencer( CapabilityGateway ):
self,
query: str,
limit: int = 20,
- ) -> List[AttributeReferenceResult]:
+ ) -> AttributeReferenceSearchResult:
"""Query the upstream corpus and return up to ``limit``
- candidates. Operators see the returned list rendered as
- cards (thumbnail/mime-icon + title + snippet + clickable
- source URL); multi-selecting any subset attaches them as
- TEXT attributes on the host Entity or Location.
+ candidates wrapped in an
+ ``AttributeReferenceSearchResult``. Operators see the
+ returned list rendered as cards (thumbnail/mime-icon +
+ title + snippet + clickable source URL); multi-selecting
+ any subset attaches them as TEXT attributes on the host
+ Entity or Location.
Implementations should:
- - Return an empty list when the query yields no matches.
+ - Return ``AttributeReferenceSearchResult(results=[])``
+ when the query yields no matches (no ``error_message``).
+ - Populate ``error_message`` when the upstream call fails
+ (auth rejected, unreachable, etc.) so the picker
+ surfaces a banner instead of "No results.". The picker
+ stays usable across failures; do not raise.
- Honor ``limit`` as an upper bound (the picker uses a
user-selectable page-size 20/50/100).
- Order results by upstream relevance (most-relevant
first); the picker preserves this order.
- - Not raise on empty/whitespace queries; return [].
+ - Not raise on empty/whitespace queries; return
+ ``AttributeReferenceSearchResult(results=[])``.
"""
raise NotImplementedError('Subclasses must override this method')
diff --git a/src/hi/integrations/referencer/transient_models.py b/src/hi/integrations/referencer/transient_models.py
index d2ff3935..1a9522bd 100644
--- a/src/hi/integrations/referencer/transient_models.py
+++ b/src/hi/integrations/referencer/transient_models.py
@@ -9,14 +9,21 @@ selected by the operator, and discarded once the resulting
``title`` and ``source_url`` survive into persistent storage; the
remaining fields exist solely for picker UX.
+``AttributeReferenceSearchResult`` is the wrapper returned by
+``IntegrationAttributeReferencer.search_references``. It carries the
+result list plus an optional ``error_message`` so the picker can
+distinguish a legitimately-empty search from an upstream failure
+(auth rejected, unreachable, etc.) and surface a banner instead of
+the "No results." string.
+
Wire-format strings (form field names, JSON record keys) shared
between the picker views, templates, and ``attr-picker.js`` live in
``hi.constants.DIVID`` (mirrored in ``static/js/main.js``). See the
``ATTR_PICKER_*`` entries there.
"""
-from dataclasses import dataclass
-from typing import Optional
+from dataclasses import dataclass, field
+from typing import List, Optional
@dataclass(frozen=True)
@@ -32,3 +39,12 @@ class AttributeReferenceResult:
thumbnail_url: Optional[str] = None
mime_type: Optional[str] = None
snippet: Optional[str] = None
+
+
+@dataclass(frozen=True)
+class AttributeReferenceSearchResult:
+ """``error_message`` is None on success, including the legitimate
+ empty-results case. A non-None value signals upstream failure
+ even when ``results`` is empty."""
+ results: List[AttributeReferenceResult] = field(default_factory=list)
+ error_message: Optional[str] = None
diff --git a/src/hi/integrations/referencer/views.py b/src/hi/integrations/referencer/views.py
index 7cd17a4d..0aefd8e6 100644
--- a/src/hi/integrations/referencer/views.py
+++ b/src/hi/integrations/referencer/views.py
@@ -64,7 +64,7 @@ from hi.integrations.integration_manager import IntegrationManager
from hi.integrations.view_mixins import IntegrationViewMixin
from .integration_referencer import IntegrationAttributeReferencer
-from .transient_models import AttributeReferenceResult
+from .transient_models import AttributeReferenceSearchResult
logger = logging.getLogger(__name__)
@@ -167,14 +167,33 @@ def _search_upstream(
referencer: IntegrationAttributeReferencer,
query: str,
limit: int,
-) -> List[ AttributeReferenceResult ]:
+) -> AttributeReferenceSearchResult:
if not query:
- return []
+ return AttributeReferenceSearchResult( results = [] )
try:
- return referencer.search_references( query=query, limit=limit )
+ return referencer.search_references( query = query, limit = limit )
except Exception:
+ # The contract asks referencers to populate ``error_message``
+ # instead of raising, so reaching this branch means the
+ # referencer itself is broken. Surface a labeled message so
+ # operators with multiple referencers know which one to look
+ # at; the stack lands in the server log.
logger.exception( 'Attribute-reference search failed.' )
- return []
+ label = _safe_label( referencer )
+ return AttributeReferenceSearchResult(
+ results = [],
+ error_message = f'{label} search failed — see server logs.',
+ )
+
+
+def _safe_label( referencer: IntegrationAttributeReferencer ) -> str:
+ # Defensive: a referencer broken enough to raise from search may
+ # also raise from get_metadata. Fall back to a generic label so
+ # the banner never compounds the failure.
+ try:
+ return referencer.get_metadata().label
+ except Exception:
+ return 'Integration'
def _parse_selections_json(raw: str) -> List[ Dict[str, str] ]:
@@ -263,12 +282,15 @@ class AttributeReferencePickerView( HiModalView ):
# what they're already configuring.
query = owner.name
referencer = integration_data.integration_gateway.get_attribute_referencer()
- results = _search_upstream(
- referencer=referencer,
- query=query,
- limit=_DEFAULT_LIMIT,
- ) if referencer is not None else []
-
+ if referencer is not None:
+ search_result = _search_upstream(
+ referencer = referencer,
+ query = query,
+ limit = _DEFAULT_LIMIT,
+ )
+ else:
+ search_result = AttributeReferenceSearchResult( results = [] )
+
context = {
'integration_data_list': integration_data_list,
'integration_data': integration_data,
@@ -277,7 +299,8 @@ class AttributeReferencePickerView( HiModalView ):
'limit': _DEFAULT_LIMIT,
'page_size_choices': _PAGE_SIZE_CHOICES,
'query': query,
- 'results': results,
+ 'results': search_result.results,
+ 'error_message': search_result.error_message,
}
return self.modal_response( request, context=context )
@@ -310,16 +333,17 @@ class AttributeReferenceSearchView( View ):
limit = _parse_limit(
request.POST.get( DIVID['ATTR_PICKER_LIMIT_FIELD'] ),
)
- results = _search_upstream(
- referencer=referencer, query=query, limit=limit,
+ search_result = _search_upstream(
+ referencer = referencer, query = query, limit = limit,
)
html = render_to_string(
self.RESULTS_TEMPLATE_NAME,
{
'query': query,
- 'results': results,
+ 'results': search_result.results,
+ 'error_message': search_result.error_message,
},
- request=request,
+ request = request,
)
return HttpResponse( html )
diff --git a/src/hi/integrations/templates/integrations/referencer/panes/attr_picker_results.html b/src/hi/integrations/templates/integrations/referencer/panes/attr_picker_results.html
index 56187c13..832a8c60 100644
--- a/src/hi/integrations/templates/integrations/referencer/panes/attr_picker_results.html
+++ b/src/hi/integrations/templates/integrations/referencer/panes/attr_picker_results.html
@@ -9,11 +9,16 @@ DOM classes / data-attribute names come from ``hi.constants.DIVID``
(mirrored in ``static/js/main.js`` under ``Hi.ATTR_PICKER_*``).
Context:
- query : str (the search query that produced these results;
- used only for the no-results message)
- results : list[AttributeReferenceResult]
+ query : str (the search query that produced these results;
+ used only for the no-results message)
+ results : list[AttributeReferenceResult]
+ error_message : Optional[str] (upstream failure banner; when set,
+ suppresses the no-results message
+ for an empty result list)
{% endcomment %}
-{% if query and not results %}
+{% if error_message %}
+<div class="alert alert-danger small mb-2" role="alert">{{ error_message }}</div>
+{% elif query and not results %}
<div class="text-muted small">No results.</div>
{% endif %}
{% if results %}
diff --git a/src/hi/integrations/tests/test_referencer_views.py b/src/hi/integrations/tests/test_referencer_views.py
index d3a89e46..56050f16 100644
--- a/src/hi/integrations/tests/test_referencer_views.py
+++ b/src/hi/integrations/tests/test_referencer_views.py
@@ -36,6 +36,7 @@ from hi.integrations.referencer.integration_referencer import (
from hi.constants import DIVID
from hi.integrations.referencer.transient_models import (
AttributeReferenceResult,
+ AttributeReferenceSearchResult,
)
from hi.integrations.transient_models import (
ConnectionTestResult,
@@ -63,11 +64,12 @@ class _StubReferencer(IntegrationAttributeReferencer):
Captures search args so tests can assert dispatch shape."""
def __init__(self, integration_id='ref', label='Ref Test',
- results=None, raises=None):
+ results=None, raises=None, error_message=None):
self._integration_id = integration_id
self._label = label
self._results = results or []
self._raises = raises
+ self._error_message = error_message
self.last_query = None
self.last_limit = None
@@ -88,7 +90,10 @@ class _StubReferencer(IntegrationAttributeReferencer):
self.last_limit = limit
if self._raises is not None:
raise self._raises
- return list(self._results)
+ return AttributeReferenceSearchResult(
+ results=list(self._results),
+ error_message=self._error_message,
+ )
class _ReferencerCapableGateway(IntegrationGateway):
@@ -360,7 +365,11 @@ class TestAttributeReferenceSearchView(ViewTestBase):
)
self.assertEqual(response.status_code, 400)
- def test_search_referencer_exception_yields_empty_results(self):
+ def test_search_referencer_exception_renders_labeled_banner(self):
+ # Raised exceptions are the "referencer is broken" path; the
+ # framework catches and surfaces a banner naming the
+ # integration so the picker stays usable and the operator
+ # knows which referencer to look at.
self.referencer._raises = RuntimeError('upstream down')
response = self.client.post(
self._url(),
@@ -368,9 +377,22 @@ class TestAttributeReferenceSearchView(ViewTestBase):
**self.async_http_headers,
)
self.assertEqual(response.status_code, 200)
- # Failure path renders the no-results message rather than
- # surfacing a 5xx — the picker stays usable.
- self.assertIn('No results', response.content.decode())
+ body = response.content.decode()
+ self.assertIn('Ref Test search failed', body)
+ self.assertNotIn('No results', body)
+
+ def test_search_referencer_error_message_renders_banner(self):
+ # Referencers that populate ``error_message`` instead of
+ # raising should also surface as a banner, not "no results".
+ self.referencer._error_message = 'Upstream auth rejected.'
+ response = self.client.post(
+ self._url(),
+ data=self._payload(query='q'),
+ **self.async_http_headers,
+ )
+ body = response.content.decode()
+ self.assertIn('Upstream auth rejected.', body)
+ self.assertNotIn('No results', body)
# ---- attach endpoint ----------------------------------------------
diff --git a/src/hi/services/immich/__init__.py b/src/hi/services/immich/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/services/immich/apps.py b/src/hi/services/immich/apps.py
new file mode 100644
index 00000000..f8eb5c67
--- /dev/null
+++ b/src/hi/services/immich/apps.py
@@ -0,0 +1,6 @@
+from django.apps import AppConfig
+
+
+class ImmichConfig(AppConfig):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'hi.services.immich'
diff --git a/src/hi/services/immich/enums.py b/src/hi/services/immich/enums.py
new file mode 100644
index 00000000..fdc8e445
--- /dev/null
+++ b/src/hi/services/immich/enums.py
@@ -0,0 +1,25 @@
+from hi.apps.attribute.enums import AttributeValueType
+
+from hi.integrations.enums import IntegrationAttributeType
+
+
+class ImAttributeType( IntegrationAttributeType ):
+
+ API_URL = (
+ 'API URL',
+ 'e.g., https://immich.example.com/',
+ AttributeValueType.TEXT,
+ None,
+ True,
+ True,
+ )
+ API_KEY = (
+ 'API Key',
+ 'Immich API key sent as x-api-key on every request. Create '
+ 'one in the Immich web UI under Account Settings → API Keys '
+ 'with at least the asset.read permission.',
+ AttributeValueType.SECRET,
+ None,
+ True,
+ True,
+ )
diff --git a/src/hi/services/immich/im_client.py b/src/hi/services/immich/im_client.py
new file mode 100644
index 00000000..df6d242e
--- /dev/null
+++ b/src/hi/services/immich/im_client.py
@@ -0,0 +1,135 @@
+import logging
+from typing import Any, Dict, Optional
+from urllib.parse import urljoin
+
+import requests
+
+from hi.integrations.exceptions import IntegrationAttributeError
+from hi.integrations.models import Integration
+from hi.integrations.transient_models import IntegrationKey
+
+from .enums import ImAttributeType
+from .im_metadata import ImmichMetaData
+from .im_models import ImmichApi
+
+
+logger = logging.getLogger(__name__)
+
+
+class ImmichClient:
+
+ DEFAULT_TIMEOUT_SECS = 5.0
+
+ def __init__(
+ self,
+ api_url : str,
+ api_key : str,
+ timeout_secs : Optional[float] = None,
+ ):
+ # Normalize once at construction so the API_URL is forgiving
+ # whether the operator pasted with or without a trailing
+ # slash. urljoin then composes paths predictably.
+ self.api_url = api_url.rstrip('/') + '/'
+ self.api_key = api_key
+ self._timeout_secs = (
+ timeout_secs if timeout_secs is not None
+ else self.DEFAULT_TIMEOUT_SECS
+ )
+ self._session = requests.Session()
+ self._session.headers.update({
+ ImmichApi.AUTH_HEADER: self.api_key,
+ })
+
+ def search_smart(
+ self,
+ query : str,
+ size : int,
+ ) -> Dict[str, Any]:
+ """``POST /api/search/smart`` -- Immich's CLIP semantic search,
+ the same endpoint Immich's own web UI search bar drives. The
+ sister ``/api/search/metadata`` endpoint accepts only
+ structured filters (filename, EXIF, dates) and is intentionally
+ not exposed here."""
+ url = urljoin( self.api_url, ImmichApi.SEARCH_SMART_PATH )
+ body = {
+ ImmichApi.REQUEST_QUERY: query,
+ ImmichApi.REQUEST_SIZE: size,
+ }
+ response = self._session.post(
+ url, json = body, timeout = self._timeout_secs,
+ )
+ response.raise_for_status()
+ return response.json()
+
+ def download_thumbnail( self, asset_id : str ) -> Dict[str, Any]:
+ """Fetch the per-asset thumbnail bytes. Returns
+ ``{'content': bytes, 'mime_type': str}``."""
+ path = ImmichApi.ASSET_THUMBNAIL_PATH.format( id = asset_id )
+ url = urljoin( self.api_url, path )
+ response = self._session.get(
+ url,
+ params = { ImmichApi.THUMBNAIL_SIZE_PARAM: ImmichApi.THUMBNAIL_SIZE_VALUE },
+ timeout = self._timeout_secs,
+ )
+ response.raise_for_status()
+ return {
+ 'content': response.content,
+ 'mime_type': response.headers.get(
+ 'Content-Type', 'application/octet-stream',
+ ),
+ }
+
+ def build_asset_web_url( self, asset_id : str ) -> str:
+ """Per-asset web UI URL on the configured Immich server.
+ Persisted as the saved attribute's value so an operator
+ clicking the link later goes directly to Immich (no HI proxy
+ in the path)."""
+ path = ImmichApi.ASSET_WEB_PATH.format( id = asset_id )
+ return urljoin( self.api_url, path )
+
+
+def build_client( timeout_secs : Optional[float] = None ) -> ImmichClient:
+ """Construct an ImmichClient from the configured Immich
+ Integration row.
+
+ Raises:
+ Integration.DoesNotExist -- Immich integration never configured.
+ IntegrationAttributeError -- required attribute missing or empty,
+ or integration disabled.
+ """
+ integration = Integration.objects.get(
+ integration_id = ImmichMetaData.integration_id,
+ )
+ if not integration.is_enabled:
+ raise IntegrationAttributeError(
+ 'Immich integration is disabled.'
+ )
+
+ attrs_by_key = integration.attributes_by_integration_key
+ api_url = _required_attribute_value(
+ attrs_by_key, ImAttributeType.API_URL,
+ )
+ api_key = _required_attribute_value(
+ attrs_by_key, ImAttributeType.API_KEY,
+ )
+ return ImmichClient(
+ api_url = api_url,
+ api_key = api_key,
+ timeout_secs = timeout_secs,
+ )
+
+
+def _required_attribute_value(
+ attrs_by_key : Dict[IntegrationKey, Any],
+ attr_type : ImAttributeType,
+) -> str:
+ key = IntegrationKey(
+ integration_id = ImmichMetaData.integration_id,
+ integration_name = str( attr_type ),
+ )
+ attr = attrs_by_key.get( key )
+ if attr is None or not (attr.value or '').strip():
+ raise IntegrationAttributeError(
+ f'Missing Immich attribute: {attr_type.label}'
+ )
+ return attr.value.strip()
diff --git a/src/hi/services/immich/im_metadata.py b/src/hi/services/immich/im_metadata.py
new file mode 100644
index 00000000..875e443d
--- /dev/null
+++ b/src/hi/services/immich/im_metadata.py
@@ -0,0 +1,17 @@
+from hi.integrations.enums import IntegrationCapability
+from hi.integrations.transient_models import IntegrationMetaData
+
+from .enums import ImAttributeType
+
+
+ImmichMetaData = IntegrationMetaData(
+ integration_id = 'immich',
+ label = 'Immich',
+ attribute_type = ImAttributeType,
+ allow_entity_deletion = False,
+ allow_internal_attributes = False,
+ logo_static_path = 'img/integrations/immich.png',
+ capabilities = frozenset({
+ IntegrationCapability.ATTRIBUTE_REFERENCE,
+ }),
+)
diff --git a/src/hi/services/immich/im_models.py b/src/hi/services/immich/im_models.py
new file mode 100644
index 00000000..a0b391de
--- /dev/null
+++ b/src/hi/services/immich/im_models.py
@@ -0,0 +1,55 @@
+class ImmichApi:
+ """Wire-format strings shared by the client, referencer, gateway,
+ and proxy view. Paths are appended to the configured ``API_URL``
+ base; ``{id}`` is the per-asset substitution token."""
+
+ # ---- URL paths (relative to the configured API_URL) ----
+
+ SEARCH_SMART_PATH = 'api/search/smart'
+ # Probe-only target for ``validate_access``: structured-filter
+ # endpoint that's cheap to call (no CLIP embedding) and exercises
+ # the same ``asset.read`` scope as the smart endpoint used at
+ # search time. We don't expose this as a search mode because it
+ # has no free-text query field.
+ SEARCH_METADATA_PROBE_PATH = 'api/search/metadata'
+ ASSET_THUMBNAIL_PATH = 'api/assets/{id}/thumbnail'
+ # Per-asset web UI route. Used unchanged as the persisted attribute
+ # value; operators clicking the saved link land on Immich's own
+ # page (authenticated by their Immich session, not by HI).
+ ASSET_WEB_PATH = 'photos/{id}'
+
+ # ---- Query parameters ----
+
+ THUMBNAIL_SIZE_PARAM = 'size'
+ THUMBNAIL_SIZE_VALUE = 'thumbnail'
+
+ # ---- Search request body keys ----
+
+ REQUEST_QUERY = 'query'
+ REQUEST_SIZE = 'size'
+
+ # ---- Authentication ----
+
+ AUTH_HEADER = 'x-api-key'
+
+ # ---- Search response JSON keys ----
+ # Immich nests results one level deeper than typical REST APIs:
+ # { "assets": { "items": [...], "total": N, "count": N,
+ # "nextPage": null }, "albums": {...} }
+
+ RESPONSE_ASSETS = 'assets'
+ RESPONSE_ITEMS = 'items'
+ RESPONSE_TOTAL = 'total'
+ RESPONSE_COUNT = 'count'
+
+ # ---- Per-asset JSON keys ----
+
+ ASSET_ID = 'id'
+ ASSET_ORIGINAL_FILE_NAME = 'originalFileName'
+ ASSET_ORIGINAL_MIME_TYPE = 'originalMimeType'
+ ASSET_TYPE = 'type'
+ ASSET_FILE_CREATED_AT = 'fileCreatedAt'
+ ASSET_EXIF_INFO = 'exifInfo'
+
+ EXIF_CITY = 'city'
+ EXIF_COUNTRY = 'country'
diff --git a/src/hi/services/immich/im_referencer.py b/src/hi/services/immich/im_referencer.py
new file mode 100644
index 00000000..f3a52fc9
--- /dev/null
+++ b/src/hi/services/immich/im_referencer.py
@@ -0,0 +1,174 @@
+import logging
+from typing import Optional
+
+from django.urls import reverse
+from requests import HTTPError
+
+from hi.integrations.exceptions import IntegrationAttributeError
+from hi.integrations.referencer.integration_referencer import (
+ IntegrationAttributeReferencer,
+)
+from hi.integrations.referencer.transient_models import (
+ AttributeReferenceResult,
+ AttributeReferenceSearchResult,
+)
+from hi.integrations.transient_models import (
+ IntegrationMetaData,
+ IntegrationValidationResult,
+)
+
+from .im_client import ImmichClient, build_client
+from .im_metadata import ImmichMetaData
+from .im_models import ImmichApi
+from .im_validation import validate_attributes
+
+
+logger = logging.getLogger(__name__)
+
+
+class ImmichAttributeReferencer( IntegrationAttributeReferencer ):
+
+ def get_metadata( self ) -> IntegrationMetaData:
+ return ImmichMetaData
+
+ def validate_configuration(
+ self,
+ integration_attributes,
+ ) -> IntegrationValidationResult:
+ return validate_attributes( integration_attributes )
+
+ def search_references(
+ self,
+ query : str,
+ limit : int = 20,
+ ) -> AttributeReferenceSearchResult:
+ if not query or not query.strip():
+ return AttributeReferenceSearchResult( results = [] )
+ try:
+ client = build_client()
+ except IntegrationAttributeError as e:
+ logger.warning( f'Immich search aborted: {e}' )
+ return AttributeReferenceSearchResult(
+ results = [],
+ error_message = 'Immich integration is not configured.',
+ )
+ except Exception as e:
+ logger.exception( f'Immich client build failed: {e}' )
+ return AttributeReferenceSearchResult(
+ results = [],
+ error_message = 'Immich integration error — see server logs.',
+ )
+
+ try:
+ envelope = client.search_smart(
+ query = query.strip(), size = limit,
+ )
+ except HTTPError as e:
+ status = getattr( e.response, 'status_code', None )
+ logger.warning(
+ f'Immich search HTTP {status} for query '
+ f'{query!r}: {e}'
+ )
+ return AttributeReferenceSearchResult(
+ results = [],
+ error_message = self._http_error_message( status ),
+ )
+ except Exception as e:
+ logger.warning(
+ f'Immich search failed for query {query!r}: {e}'
+ )
+ return AttributeReferenceSearchResult(
+ results = [],
+ error_message = 'Immich search failed — see server logs.',
+ )
+
+ items = (
+ envelope.get( ImmichApi.RESPONSE_ASSETS, {} )
+ or {}
+ ).get( ImmichApi.RESPONSE_ITEMS, []) or []
+ try:
+ results = [
+ self._translate( client = client, asset = asset )
+ for asset in items
+ ]
+ except Exception as e:
+ # Per-asset translation can fail on shape drift (missing
+ # id, etc.). Surface as the same unexpected-response
+ # signal the HTTP layer uses so the picker banner names
+ # the integration instead of falling to the framework's
+ # generic fallback message.
+ logger.warning(
+ f'Immich asset translation failed for query '
+ f'{query!r}: {e}'
+ )
+ return AttributeReferenceSearchResult(
+ results = [],
+ error_message = self._http_error_message( None ),
+ )
+ return AttributeReferenceSearchResult( results = results )
+
+ @staticmethod
+ def _http_error_message( status : Optional[int] ) -> str:
+ if status == 401:
+ return 'Immich API key not recognized (HTTP 401).'
+ if status == 403:
+ return ( 'Immich API key is missing the asset.read '
+ 'permission (HTTP 403).' )
+ if status is None:
+ return 'Immich returned an unexpected response.'
+ return f'Immich returned HTTP {status}.'
+
+ def _translate(
+ self,
+ client : ImmichClient,
+ asset : dict,
+ ) -> AttributeReferenceResult:
+ asset_id = asset.get( ImmichApi.ASSET_ID )
+ title = (
+ asset.get( ImmichApi.ASSET_ORIGINAL_FILE_NAME )
+ or asset_id
+ or ''
+ )
+ return AttributeReferenceResult(
+ title = title,
+ source_url = client.build_asset_web_url( asset_id ),
+ thumbnail_url = self._proxy_thumbnail_url( asset_id ),
+ mime_type = asset.get( ImmichApi.ASSET_ORIGINAL_MIME_TYPE ),
+ snippet = self._build_secondary_text( asset ),
+ )
+
+ @staticmethod
+ def _proxy_thumbnail_url( asset_id : str ) -> str:
+ return reverse(
+ 'immich_thumbnail',
+ kwargs = { 'asset_id': asset_id },
+ )
+
+ @staticmethod
+ def _build_secondary_text( asset : dict ) -> Optional[str]:
+ """Compose a short secondary-text line from the asset's
+ created-date and EXIF city/country. Returns None when neither
+ signal is present -- the picker template omits the snippet row
+ entirely on None. Photos have no full-text content, so the
+ snippet exists to give the operator something to disambiguate
+ otherwise-identical filenames."""
+ parts = []
+ created_at = asset.get( ImmichApi.ASSET_FILE_CREATED_AT )
+ if created_at:
+ # Immich emits ISO 8601; keep just the date portion. We
+ # avoid datetime parsing -- defensiveness against shape
+ # drift matters more than perfect formatting here.
+ parts.append( str(created_at)[:10] )
+
+ exif = asset.get( ImmichApi.ASSET_EXIF_INFO ) or {}
+ place = [
+ exif.get( ImmichApi.EXIF_CITY ),
+ exif.get( ImmichApi.EXIF_COUNTRY ),
+ ]
+ place_str = ', '.join( p for p in place if p )
+ if place_str:
+ parts.append( place_str )
+
+ if not parts:
+ return None
+ return ' · '.join( parts )
diff --git a/src/hi/services/immich/im_validation.py b/src/hi/services/immich/im_validation.py
new file mode 100644
index 00000000..442bc5ce
--- /dev/null
+++ b/src/hi/services/immich/im_validation.py
@@ -0,0 +1,70 @@
+from typing import Dict, List
+from urllib.parse import urlparse
+
+from hi.apps.system.enums import HealthStatusType
+from hi.integrations.models import IntegrationAttribute
+from hi.integrations.transient_models import (
+ IntegrationKey,
+ IntegrationValidationResult,
+)
+
+from .enums import ImAttributeType
+from .im_metadata import ImmichMetaData
+
+
+_VALID_SCHEMES = frozenset({ 'http', 'https' })
+
+
+def validate_attributes(
+ integration_attributes : List[ IntegrationAttribute ],
+) -> IntegrationValidationResult:
+ """Schema-only validation: required attributes present and
+ non-empty; API_URL has http(s) scheme and a netloc. Does NOT
+ perform network operations."""
+ attrs_by_key = _attributes_by_key( integration_attributes )
+
+ api_url = _value( attrs_by_key, ImAttributeType.API_URL )
+ if not api_url:
+ return IntegrationValidationResult.error(
+ status = HealthStatusType.WARNING,
+ error_message = f'Missing required attribute: {ImAttributeType.API_URL.label}',
+ )
+
+ parsed = urlparse( api_url )
+ if parsed.scheme not in _VALID_SCHEMES or not parsed.netloc:
+ return IntegrationValidationResult.error(
+ status = HealthStatusType.WARNING,
+ error_message = (
+ f'{ImAttributeType.API_URL.label} must be an http(s) URL '
+ f'with a hostname; got {api_url!r}.'
+ ),
+ )
+
+ api_key = _value( attrs_by_key, ImAttributeType.API_KEY )
+ if not api_key:
+ return IntegrationValidationResult.error(
+ status = HealthStatusType.WARNING,
+ error_message = f'Missing required attribute: {ImAttributeType.API_KEY.label}',
+ )
+
+ return IntegrationValidationResult.success()
+
+
+def _attributes_by_key(
+ integration_attributes : List[ IntegrationAttribute ],
+) -> Dict[ IntegrationKey, IntegrationAttribute ]:
+ return { attr.integration_key: attr for attr in integration_attributes }
+
+
+def _value(
+ attrs_by_key : Dict[ IntegrationKey, IntegrationAttribute ],
+ attr_type : ImAttributeType,
+) -> str:
+ key = IntegrationKey(
+ integration_id = ImmichMetaData.integration_id,
+ integration_name = str( attr_type ),
+ )
+ attr = attrs_by_key.get( key )
+ if attr is None:
+ return ''
+ return ( attr.value or '' ).strip()
diff --git a/src/hi/services/immich/integration.py b/src/hi/services/immich/integration.py
new file mode 100644
index 00000000..ec9b2980
--- /dev/null
+++ b/src/hi/services/immich/integration.py
@@ -0,0 +1,104 @@
+import logging
+from typing import List, Optional
+from urllib.parse import urljoin
+
+import requests
+
+from hi.integrations.integration_gateway import IntegrationGateway
+from hi.integrations.models import IntegrationAttribute
+from hi.integrations.referencer.integration_referencer import (
+ IntegrationAttributeReferencer,
+)
+from hi.integrations.transient_models import (
+ ConnectionTestResult,
+ IntegrationKey,
+ IntegrationMetaData,
+ IntegrationValidationResult,
+)
+
+from .enums import ImAttributeType
+from .im_metadata import ImmichMetaData
+from .im_models import ImmichApi
+from .im_referencer import ImmichAttributeReferencer
+from .im_validation import validate_attributes
+
+
+logger = logging.getLogger(__name__)
+
+
+class ImmichGateway( IntegrationGateway ):
+
+ def get_metadata( self ) -> IntegrationMetaData:
+ return ImmichMetaData
+
+ def get_attribute_referencer( self ) -> IntegrationAttributeReferencer:
+ return ImmichAttributeReferencer()
+
+ def validate_configuration(
+ self,
+ integration_attributes : List[ IntegrationAttribute ],
+ ) -> IntegrationValidationResult:
+ return validate_attributes( integration_attributes )
+
+ def validate_access(
+ self,
+ integration_attributes : List[ IntegrationAttribute ],
+ timeout_secs : Optional[float],
+ ) -> ConnectionTestResult:
+ """Live access probe: ``POST /api/search/metadata`` with body
+ ``{"size": 1}``. The metadata endpoint is cheap (no CLIP
+ embedding) and exercises the same ``asset.read`` scope the
+ referencer needs at search time, so a green probe predicts a
+ working integration. Returns success on 200, distinguishing
+ 401 (unrecognized key) from 403 (key lacks ``asset.read``) so
+ operators can fix the right thing."""
+ schema_result = validate_attributes( integration_attributes )
+ if not schema_result.is_valid:
+ return ConnectionTestResult.failure( schema_result.error_message )
+
+ attrs_by_key = {
+ attr.integration_key: attr for attr in integration_attributes
+ }
+ api_url = self._attribute_value( attrs_by_key, ImAttributeType.API_URL )
+ api_key = self._attribute_value( attrs_by_key, ImAttributeType.API_KEY )
+ normalized = api_url.rstrip('/') + '/'
+ probe_url = urljoin( normalized, ImmichApi.SEARCH_METADATA_PROBE_PATH )
+ try:
+ response = requests.post(
+ probe_url,
+ json = { ImmichApi.REQUEST_SIZE: 1 },
+ headers = { ImmichApi.AUTH_HEADER: api_key },
+ timeout = timeout_secs if timeout_secs is not None else 5.0,
+ )
+ except requests.RequestException as e:
+ return ConnectionTestResult.failure(
+ f'Immich unreachable: {e}'
+ )
+ if response.status_code == 200:
+ return ConnectionTestResult.success()
+ if response.status_code == 401:
+ return ConnectionTestResult.failure(
+ 'Immich API key not recognized (HTTP 401). Check the '
+ 'key value, or create a new key in Immich → Account '
+ 'Settings → API Keys.'
+ )
+ if response.status_code == 403:
+ return ConnectionTestResult.failure(
+ 'Immich API key is missing the asset.read permission '
+ '(HTTP 403). Re-create the key in Immich → Account '
+ 'Settings → API Keys with asset.read granted.'
+ )
+ return ConnectionTestResult.failure(
+ f'Immich responded HTTP {response.status_code}.'
+ )
+
+ @staticmethod
+ def _attribute_value( attrs_by_key, attr_type : ImAttributeType ) -> str:
+ key = IntegrationKey(
+ integration_id = ImmichMetaData.integration_id,
+ integration_name = str( attr_type ),
+ )
+ attr = attrs_by_key.get( key )
+ if attr is None:
+ return ''
+ return ( attr.value or '' ).strip()
diff --git a/src/hi/services/immich/tests/__init__.py b/src/hi/services/immich/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/services/immich/tests/test_im_client.py b/src/hi/services/immich/tests/test_im_client.py
new file mode 100644
index 00000000..f0140aca
--- /dev/null
+++ b/src/hi/services/immich/tests/test_im_client.py
@@ -0,0 +1,143 @@
+import logging
+from unittest.mock import Mock, patch
+
+import requests
+from django.test import TestCase
+
+from hi.apps.attribute.enums import AttributeValueType
+from hi.integrations.exceptions import IntegrationAttributeError
+from hi.integrations.models import Integration, IntegrationAttribute
+from hi.integrations.transient_models import IntegrationKey
+
+from hi.services.immich.enums import ImAttributeType
+from hi.services.immich.im_client import ImmichClient, build_client
+from hi.services.immich.im_metadata import ImmichMetaData
+
+
+logging.disable(logging.CRITICAL)
+
+
+def _make_attr(integration, attr_type, value):
+ attr = IntegrationAttribute(
+ integration = integration,
+ name = attr_type.label,
+ value = value,
+ value_type_str = str(AttributeValueType.TEXT),
+ attribute_type_str = 'PREDEFINED',
+ )
+ attr.integration_key = IntegrationKey(
+ integration_id = ImmichMetaData.integration_id,
+ integration_name = str(attr_type),
+ )
+ attr.save()
+ return attr
+
+
+class TestImmichClient(TestCase):
+
+ def test_trailing_slash_normalized(self):
+ c1 = ImmichClient(api_url = 'https://im.example.com', api_key = 'k')
+ c2 = ImmichClient(api_url = 'https://im.example.com/', api_key = 'k')
+ self.assertEqual(c1.api_url, 'https://im.example.com/')
+ self.assertEqual(c2.api_url, 'https://im.example.com/')
+
+ def test_api_key_carries_on_outbound_requests(self):
+ # Verify the contract (every outbound request carries the
+ # x-api-key) via Session.prepare_request rather than poking
+ # the private session.headers dict.
+ client = ImmichClient(api_url = 'https://im.example.com', api_key = 'abc')
+ prepared = client._session.prepare_request(
+ requests.Request('GET', 'https://im.example.com/api/probe'),
+ )
+ self.assertEqual(prepared.headers.get('x-api-key'), 'abc')
+
+ def test_search_smart_posts_json_to_smart_endpoint(self):
+ client = ImmichClient(api_url = 'https://im.example.com/', api_key = 'k')
+ envelope = {'assets': {'items': [], 'total': 0, 'count': 0}}
+ response = Mock()
+ response.json.return_value = envelope
+ response.raise_for_status = Mock()
+ with patch.object(client._session, 'post', return_value = response) as mock_post:
+ result = client.search_smart(query = 'sunset on the beach', size = 10)
+
+ self.assertEqual(result, envelope)
+ args, kwargs = mock_post.call_args
+ self.assertEqual(args[0], 'https://im.example.com/api/search/smart')
+ self.assertEqual(kwargs['json'], {'query': 'sunset on the beach', 'size': 10})
+
+ def test_download_thumbnail_returns_bytes_and_mime(self):
+ client = ImmichClient(api_url = 'https://im.example.com/', api_key = 'k')
+ response = Mock()
+ response.content = b'JPEG-BYTES'
+ response.headers = {'Content-Type': 'image/jpeg'}
+ response.raise_for_status = Mock()
+ with patch.object(client._session, 'get', return_value = response) as mock_get:
+ result = client.download_thumbnail(asset_id = 'abc-uuid')
+
+ self.assertEqual(result, {'content': b'JPEG-BYTES', 'mime_type': 'image/jpeg'})
+ args, kwargs = mock_get.call_args
+ self.assertEqual(args[0], 'https://im.example.com/api/assets/abc-uuid/thumbnail')
+ self.assertEqual(kwargs['params']['size'], 'thumbnail')
+
+ def test_download_thumbnail_default_mime_when_missing(self):
+ client = ImmichClient(api_url = 'https://im.example.com/', api_key = 'k')
+ response = Mock()
+ response.content = b'raw'
+ response.headers = {}
+ response.raise_for_status = Mock()
+ with patch.object(client._session, 'get', return_value = response):
+ result = client.download_thumbnail(asset_id = 'abc')
+ self.assertEqual(result['mime_type'], 'application/octet-stream')
+
+ def test_build_asset_web_url(self):
+ client = ImmichClient(api_url = 'https://im.example.com/', api_key = 'k')
+ self.assertEqual(
+ client.build_asset_web_url(asset_id = 'abc-uuid'),
+ 'https://im.example.com/photos/abc-uuid',
+ )
+
+
+class TestBuildClient(TestCase):
+
+ def setUp(self):
+ self.integration = Integration.objects.create(
+ integration_id = ImmichMetaData.integration_id,
+ is_enabled = True,
+ )
+
+ def test_returns_configured_client(self):
+ _make_attr(self.integration, ImAttributeType.API_URL,
+ 'https://immich.example.com')
+ _make_attr(self.integration, ImAttributeType.API_KEY, 'abc')
+ client = build_client()
+ self.assertIsInstance(client, ImmichClient)
+ self.assertEqual(client.api_url, 'https://immich.example.com/')
+ self.assertEqual(client.api_key, 'abc')
+
+ def test_no_integration_row_raises(self):
+ Integration.objects.all().delete()
+ with self.assertRaises(Integration.DoesNotExist):
+ build_client()
+
+ def test_disabled_integration_raises(self):
+ self.integration.is_enabled = False
+ self.integration.save()
+ _make_attr(self.integration, ImAttributeType.API_URL,
+ 'https://immich.example.com')
+ _make_attr(self.integration, ImAttributeType.API_KEY, 'abc')
+ with self.assertRaises(IntegrationAttributeError):
+ build_client()
+
+ def test_missing_attribute_raises(self):
+ _make_attr(self.integration, ImAttributeType.API_URL,
+ 'https://immich.example.com')
+ # API_KEY deliberately omitted.
+ with self.assertRaises(IntegrationAttributeError):
+ build_client()
+
+ def test_empty_attribute_value_raises(self):
+ _make_attr(self.integration, ImAttributeType.API_URL,
+ 'https://immich.example.com')
+ _make_attr(self.integration, ImAttributeType.API_KEY, ' ')
+ with self.assertRaises(IntegrationAttributeError):
+ build_client()
diff --git a/src/hi/services/immich/tests/test_im_gateway.py b/src/hi/services/immich/tests/test_im_gateway.py
new file mode 100644
index 00000000..21c515dd
--- /dev/null
+++ b/src/hi/services/immich/tests/test_im_gateway.py
@@ -0,0 +1,118 @@
+import logging
+from unittest.mock import Mock, patch
+
+from django.test import TestCase
+from requests import RequestException
+
+from hi.apps.attribute.enums import AttributeValueType
+from hi.integrations.models import Integration, IntegrationAttribute
+from hi.integrations.transient_models import IntegrationKey
+
+from hi.services.immich.enums import ImAttributeType
+from hi.services.immich.integration import ImmichGateway
+from hi.services.immich.im_metadata import ImmichMetaData
+
+
+logging.disable(logging.CRITICAL)
+
+
+def _make_attr(integration, attr_type, value):
+ attr = IntegrationAttribute(
+ integration = integration,
+ name = attr_type.label,
+ value = value,
+ value_type_str = str(AttributeValueType.TEXT),
+ attribute_type_str = 'PREDEFINED',
+ )
+ attr.integration_key = IntegrationKey(
+ integration_id = ImmichMetaData.integration_id,
+ integration_name = str(attr_type),
+ )
+ return attr
+
+
+class TestValidateAccess(TestCase):
+
+ def setUp(self):
+ self.integration = Integration.objects.create(
+ integration_id = ImmichMetaData.integration_id,
+ is_enabled = True,
+ )
+ self.attrs = [
+ _make_attr(self.integration, ImAttributeType.API_URL,
+ 'https://immich.example.com'),
+ _make_attr(self.integration, ImAttributeType.API_KEY, 'key-abc'),
+ ]
+
+ @patch('hi.services.immich.integration.requests.post')
+ def test_200_response_returns_success(self, mock_post):
+ mock_post.return_value = Mock(status_code = 200)
+ result = ImmichGateway().validate_access(
+ integration_attributes = self.attrs,
+ timeout_secs = 1.0,
+ )
+ self.assertTrue(result.is_success)
+ args, kwargs = mock_post.call_args
+ # Probe hits the cheap metadata endpoint (no CLIP embedding)
+ # but exercises the same asset.read scope as smart search.
+ self.assertEqual(args[0], 'https://immich.example.com/api/search/metadata')
+ self.assertEqual(kwargs['json'], {'size': 1})
+ self.assertEqual(kwargs['headers']['x-api-key'], 'key-abc')
+ self.assertEqual(kwargs['timeout'], 1.0)
+
+ @patch('hi.services.immich.integration.requests.post')
+ def test_401_returns_key_not_recognized(self, mock_post):
+ mock_post.return_value = Mock(status_code = 401)
+ result = ImmichGateway().validate_access(
+ integration_attributes = self.attrs, timeout_secs = 1.0,
+ )
+ self.assertFalse(result.is_success)
+ self.assertIn('not recognized', result.message)
+
+ @patch('hi.services.immich.integration.requests.post')
+ def test_403_names_asset_read_scope(self, mock_post):
+ mock_post.return_value = Mock(status_code = 403)
+ result = ImmichGateway().validate_access(
+ integration_attributes = self.attrs, timeout_secs = 1.0,
+ )
+ self.assertFalse(result.is_success)
+ self.assertIn('asset.read', result.message)
+
+ @patch('hi.services.immich.integration.requests.post')
+ def test_5xx_returns_status_code(self, mock_post):
+ mock_post.return_value = Mock(status_code = 503)
+ result = ImmichGateway().validate_access(
+ integration_attributes = self.attrs, timeout_secs = 1.0,
+ )
+ self.assertFalse(result.is_success)
+ self.assertIn('503', result.message)
+
+ @patch('hi.services.immich.integration.requests.post',
+ side_effect = RequestException('refused'))
+ def test_unreachable_returns_failure(self, _mock_post):
+ result = ImmichGateway().validate_access(
+ integration_attributes = self.attrs, timeout_secs = 1.0,
+ )
+ self.assertFalse(result.is_success)
+ self.assertIn('unreachable', result.message.lower())
+
+ def test_schema_invalid_short_circuits_no_network_call(self):
+ bad_attrs = [
+ _make_attr(self.integration, ImAttributeType.API_URL, ''),
+ _make_attr(self.integration, ImAttributeType.API_KEY, 'k'),
+ ]
+ with patch('hi.services.immich.integration.requests.post') as mock_post:
+ result = ImmichGateway().validate_access(
+ integration_attributes = bad_attrs, timeout_secs = 1.0,
+ )
+ self.assertFalse(result.is_success)
+ mock_post.assert_not_called()
+
+ @patch('hi.services.immich.integration.requests.post')
+ def test_default_timeout_when_none(self, mock_post):
+ mock_post.return_value = Mock(status_code = 200)
+ ImmichGateway().validate_access(
+ integration_attributes = self.attrs, timeout_secs = None,
+ )
+ _, kwargs = mock_post.call_args
+ self.assertEqual(kwargs['timeout'], 5.0)
diff --git a/src/hi/services/immich/tests/test_im_proxy_views.py b/src/hi/services/immich/tests/test_im_proxy_views.py
new file mode 100644
index 00000000..a7287345
--- /dev/null
+++ b/src/hi/services/immich/tests/test_im_proxy_views.py
@@ -0,0 +1,84 @@
+import logging
+from unittest.mock import Mock, patch
+
+from django.test import TestCase
+from django.urls import reverse
+from requests import HTTPError, RequestException
+
+from hi.integrations.exceptions import IntegrationAttributeError
+
+
+logging.disable(logging.CRITICAL)
+
+
+class TestImmichThumbnailProxyView(TestCase):
+
+ def _url(self, asset_id: str = 'abc-uuid') -> str:
+ return reverse(
+ 'immich_thumbnail',
+ kwargs = {'asset_id': asset_id},
+ )
+
+ @patch('hi.services.immich.views.build_client',
+ side_effect = IntegrationAttributeError('not configured'))
+ def test_unconfigured_returns_404(self, _mock_build):
+ response = self.client.get(self._url())
+ self.assertEqual(response.status_code, 404)
+
+ @patch('hi.services.immich.views.build_client')
+ def test_successful_download_returns_bytes_and_mime(self, mock_build):
+ client = Mock()
+ client.download_thumbnail.return_value = {
+ 'content': b'JPEG-BYTES',
+ 'mime_type': 'image/jpeg',
+ }
+ mock_build.return_value = client
+
+ response = self.client.get(self._url(asset_id = 'asset-42'))
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.content, b'JPEG-BYTES')
+ self.assertEqual(response['Content-Type'], 'image/jpeg')
+ client.download_thumbnail.assert_called_once_with(asset_id = 'asset-42')
+
+ @patch('hi.services.immich.views.build_client')
+ def test_upstream_404_returns_404(self, mock_build):
+ client = Mock()
+ response = Mock()
+ response.status_code = 404
+ client.download_thumbnail.side_effect = HTTPError('404', response = response)
+ mock_build.return_value = client
+
+ result = self.client.get(self._url())
+ self.assertEqual(result.status_code, 404)
+
+ @patch('hi.services.immich.views.build_client')
+ def test_upstream_401_returns_502(self, mock_build):
+ client = Mock()
+ response = Mock()
+ response.status_code = 401
+ client.download_thumbnail.side_effect = HTTPError('401', response = response)
+ mock_build.return_value = client
+
+ result = self.client.get(self._url())
+ self.assertEqual(result.status_code, 502)
+
+ @patch('hi.services.immich.views.build_client')
+ def test_upstream_500_returns_502(self, mock_build):
+ client = Mock()
+ response = Mock()
+ response.status_code = 500
+ client.download_thumbnail.side_effect = HTTPError('500', response = response)
+ mock_build.return_value = client
+
+ result = self.client.get(self._url())
+ self.assertEqual(result.status_code, 502)
+
+ @patch('hi.services.immich.views.build_client')
+ def test_connection_error_returns_502(self, mock_build):
+ client = Mock()
+ client.download_thumbnail.side_effect = RequestException('boom')
+ mock_build.return_value = client
+
+ result = self.client.get(self._url())
+ self.assertEqual(result.status_code, 502)
diff --git a/src/hi/services/immich/tests/test_im_referencer.py b/src/hi/services/immich/tests/test_im_referencer.py
new file mode 100644
index 00000000..1a4746f8
--- /dev/null
+++ b/src/hi/services/immich/tests/test_im_referencer.py
@@ -0,0 +1,289 @@
+import logging
+from unittest.mock import Mock, patch
+
+from django.test import TestCase
+from requests import HTTPError
+
+from hi.integrations.exceptions import IntegrationAttributeError
+
+from hi.services.immich.im_referencer import ImmichAttributeReferencer
+
+
+logging.disable(logging.CRITICAL)
+
+
+def _envelope(*assets):
+ return {
+ 'assets': {
+ 'items': list(assets),
+ 'total': len(assets),
+ 'count': len(assets),
+ 'nextPage': None,
+ },
+ 'albums': {'items': [], 'total': 0, 'count': 0, 'nextPage': None},
+ }
+
+
+def _asset(asset_id='abc', **kwargs):
+ a = {
+ 'id': asset_id,
+ 'originalFileName': f'{asset_id}.jpg',
+ 'originalMimeType': 'image/jpeg',
+ 'type': 'IMAGE',
+ 'fileCreatedAt': '2025-08-14T10:32:00.000Z',
+ 'exifInfo': {'city': 'Portland', 'country': 'USA'},
+ }
+ a.update(kwargs)
+ return a
+
+
+def _make_client(envelope):
+ client = Mock()
+ client.search_smart.return_value = envelope
+ client.build_asset_web_url.side_effect = (
+ lambda asset_id: f'https://im.example.com/photos/{asset_id}'
+ )
+ return client
+
+
+class TestSearchReferencesShortCircuits(TestCase):
+ """Empty / whitespace queries must not provoke an upstream call."""
+
+ @patch('hi.services.immich.im_referencer.build_client')
+ def test_empty_query_returns_empty(self, mock_build):
+ result = ImmichAttributeReferencer().search_references(
+ query = '', limit = 20,
+ )
+ self.assertEqual(result.results, [])
+ self.assertIsNone(result.error_message)
+ mock_build.assert_not_called()
+
+ @patch('hi.services.immich.im_referencer.build_client')
+ def test_whitespace_query_returns_empty(self, mock_build):
+ result = ImmichAttributeReferencer().search_references(
+ query = ' ', limit = 20,
+ )
+ self.assertEqual(result.results, [])
+ self.assertIsNone(result.error_message)
+ mock_build.assert_not_called()
+
+
+class TestSearchReferences(TestCase):
+
+ @patch('hi.services.immich.im_referencer.build_client')
+ def test_calls_smart_search_with_trimmed_query(self, mock_build):
+ client = _make_client(_envelope(_asset('a1')))
+ mock_build.return_value = client
+
+ ImmichAttributeReferencer().search_references(
+ query = ' dishwasher ', limit = 10,
+ )
+
+ client.search_smart.assert_called_once_with(
+ query = 'dishwasher', size = 10,
+ )
+
+ @patch('hi.services.immich.im_referencer.build_client')
+ def test_translates_assets_to_results(self, mock_build):
+ client = _make_client(_envelope(
+ _asset('a1', originalFileName = 'fridge.jpg'),
+ _asset('a2', originalFileName = 'dishwasher.png',
+ originalMimeType = 'image/png'),
+ ))
+ mock_build.return_value = client
+
+ result = ImmichAttributeReferencer().search_references(
+ query = 'q', limit = 20,
+ )
+
+ self.assertIsNone(result.error_message)
+ self.assertEqual(len(result.results), 2)
+ self.assertEqual(result.results[0].title, 'fridge.jpg')
+ self.assertEqual(
+ result.results[0].source_url,
+ 'https://im.example.com/photos/a1',
+ )
+ # Thumbnail is the HI proxy URL, NOT the upstream — browser
+ # fetches via HI's session, HI fetches upstream with the
+ # configured key.
+ self.assertIn('/integration/services/immich/assets/a1/thumb/',
+ result.results[0].thumbnail_url)
+ self.assertEqual(result.results[0].mime_type, 'image/jpeg')
+ self.assertEqual(result.results[1].mime_type, 'image/png')
+
+ @patch('hi.services.immich.im_referencer.build_client')
+ def test_title_falls_back_to_id_when_filename_missing(self, mock_build):
+ client = _make_client(_envelope(
+ _asset('a1', originalFileName = None),
+ ))
+ mock_build.return_value = client
+
+ result = ImmichAttributeReferencer().search_references(
+ query = 'q', limit = 20,
+ )
+ self.assertEqual(result.results[0].title, 'a1')
+
+ @patch('hi.services.immich.im_referencer.build_client')
+ def test_limit_passes_through_as_size(self, mock_build):
+ client = _make_client(_envelope())
+ mock_build.return_value = client
+
+ ImmichAttributeReferencer().search_references(query = 'q', limit = 50)
+ client.search_smart.assert_called_once_with(query = 'q', size = 50)
+
+ @patch('hi.services.immich.im_referencer.build_client')
+ def test_missing_assets_key_yields_empty(self, mock_build):
+ # Defensive: don't blow up if upstream's envelope omits the
+ # assets wrapper.
+ client = _make_client({'albums': {}})
+ mock_build.return_value = client
+ result = ImmichAttributeReferencer().search_references(
+ query = 'q', limit = 20,
+ )
+ self.assertEqual(result.results, [])
+ self.assertIsNone(result.error_message)
+
+ @patch('hi.services.immich.im_referencer.build_client')
+ def test_missing_items_inside_assets_yields_empty(self, mock_build):
+ client = _make_client({'assets': {}, 'albums': {}})
+ mock_build.return_value = client
+ result = ImmichAttributeReferencer().search_references(
+ query = 'q', limit = 20,
+ )
+ self.assertEqual(result.results, [])
+ self.assertIsNone(result.error_message)
+
+
+class TestSearchReferencesErrorMessages(TestCase):
+ """Failure paths must surface ``error_message`` (not raise) so
+ the picker can render a distinct banner instead of falling back
+ to "no results."""
+
+ @patch('hi.services.immich.im_referencer.build_client',
+ side_effect = IntegrationAttributeError('not configured'))
+ def test_unconfigured_integration(self, _mock_build):
+ result = ImmichAttributeReferencer().search_references(
+ query = 'q', limit = 20,
+ )
+ self.assertEqual(result.results, [])
+ self.assertIn('not configured', result.error_message)
+
+ @patch('hi.services.immich.im_referencer.build_client',
+ side_effect = RuntimeError('boom in build'))
+ def test_unexpected_client_build_error(self, _mock_build):
+ result = ImmichAttributeReferencer().search_references(
+ query = 'q', limit = 20,
+ )
+ self.assertEqual(result.results, [])
+ self.assertIn('Immich integration error', result.error_message)
+
+ @patch('hi.services.immich.im_referencer.build_client')
+ def test_http_401_names_unrecognized_key(self, mock_build):
+ client = _make_client(_envelope())
+ response = Mock()
+ response.status_code = 401
+ client.search_smart.side_effect = HTTPError('401', response = response)
+ mock_build.return_value = client
+ result = ImmichAttributeReferencer().search_references(
+ query = 'q', limit = 20,
+ )
+ self.assertEqual(result.results, [])
+ self.assertIn('not recognized', result.error_message)
+
+ @patch('hi.services.immich.im_referencer.build_client')
+ def test_http_403_names_asset_read_scope(self, mock_build):
+ client = _make_client(_envelope())
+ response = Mock()
+ response.status_code = 403
+ client.search_smart.side_effect = HTTPError('403', response = response)
+ mock_build.return_value = client
+ result = ImmichAttributeReferencer().search_references(
+ query = 'q', limit = 20,
+ )
+ self.assertIn('asset.read', result.error_message)
+
+ @patch('hi.services.immich.im_referencer.build_client')
+ def test_http_500_surfaces_status_code(self, mock_build):
+ client = _make_client(_envelope())
+ response = Mock()
+ response.status_code = 500
+ client.search_smart.side_effect = HTTPError('500', response = response)
+ mock_build.return_value = client
+ result = ImmichAttributeReferencer().search_references(
+ query = 'q', limit = 20,
+ )
+ self.assertIn('500', result.error_message)
+
+ @patch('hi.services.immich.im_referencer.build_client')
+ def test_unexpected_search_exception(self, mock_build):
+ client = _make_client(_envelope())
+ client.search_smart.side_effect = RuntimeError('boom')
+ mock_build.return_value = client
+ result = ImmichAttributeReferencer().search_references(
+ query = 'q', limit = 20,
+ )
+ self.assertEqual(result.results, [])
+ self.assertIn('Immich search failed', result.error_message)
+
+ @patch('hi.services.immich.im_referencer.build_client')
+ def test_translation_failure_surfaces_unexpected_response(self, mock_build):
+ # A non-dict item in the assets list makes _translate's
+ # ``asset.get(...)`` raise AttributeError. The referencer
+ # must report it as an Immich-named error instead of letting
+ # the exception escape to the framework's generic fallback.
+ client = _make_client(_envelope('not-a-dict'))
+ mock_build.return_value = client
+ result = ImmichAttributeReferencer().search_references(
+ query = 'q', limit = 20,
+ )
+ self.assertEqual(result.results, [])
+ self.assertIn('Immich', result.error_message)
+ self.assertIn('unexpected', result.error_message.lower())
+
+
+class TestBuildSecondaryText(TestCase):
+ """The snippet replacement for photos. Returns None when nothing
+ useful — template omits the snippet row in that case."""
+
+ def test_returns_none_when_no_date_no_exif(self):
+ self.assertIsNone(
+ ImmichAttributeReferencer._build_secondary_text({})
+ )
+
+ def test_date_only(self):
+ result = ImmichAttributeReferencer._build_secondary_text({
+ 'fileCreatedAt': '2025-08-14T10:32:00.000Z',
+ })
+ self.assertEqual(result, '2025-08-14')
+
+ def test_city_and_country(self):
+ result = ImmichAttributeReferencer._build_secondary_text({
+ 'exifInfo': {'city': 'Portland', 'country': 'USA'},
+ })
+ self.assertEqual(result, 'Portland, USA')
+
+ def test_city_only(self):
+ result = ImmichAttributeReferencer._build_secondary_text({
+ 'exifInfo': {'city': 'Portland'},
+ })
+ self.assertEqual(result, 'Portland')
+
+ def test_country_only(self):
+ result = ImmichAttributeReferencer._build_secondary_text({
+ 'exifInfo': {'country': 'USA'},
+ })
+ self.assertEqual(result, 'USA')
+
+ def test_date_and_place(self):
+ result = ImmichAttributeReferencer._build_secondary_text({
+ 'fileCreatedAt': '2025-08-14T10:32:00.000Z',
+ 'exifInfo': {'city': 'Portland', 'country': 'USA'},
+ })
+ self.assertEqual(result, '2025-08-14 · Portland, USA')
+
+ def test_null_exif_treated_as_empty(self):
+ result = ImmichAttributeReferencer._build_secondary_text({
+ 'fileCreatedAt': '2025-08-14T10:32:00.000Z',
+ 'exifInfo': None,
+ })
+ self.assertEqual(result, '2025-08-14')
diff --git a/src/hi/services/immich/tests/test_im_validation.py b/src/hi/services/immich/tests/test_im_validation.py
new file mode 100644
index 00000000..6fa878c4
--- /dev/null
+++ b/src/hi/services/immich/tests/test_im_validation.py
@@ -0,0 +1,96 @@
+import logging
+
+from django.test import TestCase
+
+from hi.apps.attribute.enums import AttributeValueType
+from hi.apps.system.enums import HealthStatusType
+from hi.integrations.models import Integration, IntegrationAttribute
+from hi.integrations.transient_models import IntegrationKey
+
+from hi.services.immich.enums import ImAttributeType
+from hi.services.immich.im_metadata import ImmichMetaData
+from hi.services.immich.im_validation import validate_attributes
+
+
+logging.disable(logging.CRITICAL)
+
+
+def _make_attr(integration, attr_type, value):
+ attr = IntegrationAttribute(
+ integration = integration,
+ name = attr_type.label,
+ value = value,
+ value_type_str = str(AttributeValueType.TEXT),
+ attribute_type_str = 'PREDEFINED',
+ )
+ attr.integration_key = IntegrationKey(
+ integration_id = ImmichMetaData.integration_id,
+ integration_name = str(attr_type),
+ )
+ return attr
+
+
+class TestValidateAttributes(TestCase):
+
+ def setUp(self):
+ self.integration = Integration.objects.create(
+ integration_id = ImmichMetaData.integration_id,
+ is_enabled = True,
+ )
+
+ def _all_valid(self):
+ return [
+ _make_attr(self.integration, ImAttributeType.API_URL,
+ 'https://immich.example.com/'),
+ _make_attr(self.integration, ImAttributeType.API_KEY, 'key-abc'),
+ ]
+
+ def test_all_present_and_valid_returns_success(self):
+ result = validate_attributes(self._all_valid())
+ self.assertTrue(result.is_valid)
+ self.assertEqual(result.status, HealthStatusType.HEALTHY)
+
+ def test_missing_api_url_returns_error(self):
+ attrs = [
+ _make_attr(self.integration, ImAttributeType.API_KEY, 'key-abc'),
+ ]
+ result = validate_attributes(attrs)
+ self.assertFalse(result.is_valid)
+ self.assertIn('API URL', result.error_message)
+
+ def test_missing_api_key_returns_error(self):
+ attrs = [
+ _make_attr(self.integration, ImAttributeType.API_URL,
+ 'https://immich.example.com/'),
+ ]
+ result = validate_attributes(attrs)
+ self.assertFalse(result.is_valid)
+ self.assertIn('API Key', result.error_message)
+
+ def test_empty_value_treated_as_missing(self):
+ attrs = [
+ _make_attr(self.integration, ImAttributeType.API_URL, ' '),
+ _make_attr(self.integration, ImAttributeType.API_KEY, 'key-abc'),
+ ]
+ result = validate_attributes(attrs)
+ self.assertFalse(result.is_valid)
+ self.assertIn('API URL', result.error_message)
+
+ def test_invalid_scheme_returns_error(self):
+ attrs = [
+ _make_attr(self.integration, ImAttributeType.API_URL,
+ 'ftp://immich.example.com/'),
+ _make_attr(self.integration, ImAttributeType.API_KEY, 'key-abc'),
+ ]
+ result = validate_attributes(attrs)
+ self.assertFalse(result.is_valid)
+ self.assertIn('http(s)', result.error_message)
+
+ def test_missing_netloc_returns_error(self):
+ attrs = [
+ _make_attr(self.integration, ImAttributeType.API_URL, 'https://'),
+ _make_attr(self.integration, ImAttributeType.API_KEY, 'key-abc'),
+ ]
+ result = validate_attributes(attrs)
+ self.assertFalse(result.is_valid)
+ self.assertIn('hostname', result.error_message)
diff --git a/src/hi/services/immich/urls.py b/src/hi/services/immich/urls.py
new file mode 100644
index 00000000..502e0819
--- /dev/null
+++ b/src/hi/services/immich/urls.py
@@ -0,0 +1,12 @@
+from django.urls import path
+
+from .views import ImmichThumbnailProxyView
+
+
+urlpatterns = [
+ path(
+ 'assets/<str:asset_id>/thumb/',
+ ImmichThumbnailProxyView.as_view(),
+ name = 'immich_thumbnail',
+ ),
+]
diff --git a/src/hi/services/immich/views.py b/src/hi/services/immich/views.py
new file mode 100644
index 00000000..1b16105e
--- /dev/null
+++ b/src/hi/services/immich/views.py
@@ -0,0 +1,49 @@
+import logging
+
+from django.http import Http404, HttpResponse
+from django.views import View
+from requests import HTTPError
+
+from hi.integrations.exceptions import IntegrationAttributeError
+from hi.integrations.models import Integration
+
+from .im_client import build_client
+
+
+logger = logging.getLogger(__name__)
+
+
+class ImmichThumbnailProxyView( View ):
+
+ def get( self, request, asset_id : str ):
+ try:
+ client = build_client()
+ except (Integration.DoesNotExist, IntegrationAttributeError):
+ raise Http404('Immich integration not configured.')
+
+ try:
+ downloaded = client.download_thumbnail( asset_id = asset_id )
+ except HTTPError as e:
+ status = getattr( e.response, 'status_code', None )
+ if status == 404:
+ raise Http404('Thumbnail not found.')
+ logger.warning(
+ f'Immich thumb proxy HTTP {status} '
+ f'for asset {asset_id}: {e}'
+ )
+ return HttpResponse(
+ status = 502, content = 'Immich upstream error.',
+ )
+ except Exception as e:
+ logger.warning(
+ f'Immich thumb proxy failed '
+ f'for asset {asset_id}: {e}'
+ )
+ return HttpResponse(
+ status = 502, content = 'Immich upstream error.',
+ )
+
+ return HttpResponse(
+ content = downloaded['content'],
+ content_type = downloaded['mime_type'],
+ )
diff --git a/src/hi/services/paperless/pl_referencer.py b/src/hi/services/paperless/pl_referencer.py
index e34630d3..94f619e9 100644
--- a/src/hi/services/paperless/pl_referencer.py
+++ b/src/hi/services/paperless/pl_referencer.py
@@ -23,7 +23,7 @@ Translates each paperless documents-search hit into a single
persist or display the whole document text.
"""
import logging
-from typing import List, Optional
+from typing import Optional
from django.urls import reverse
from requests import HTTPError
@@ -34,6 +34,7 @@ from hi.integrations.referencer.integration_referencer import (
)
from hi.integrations.referencer.transient_models import (
AttributeReferenceResult,
+ AttributeReferenceSearchResult,
)
from hi.integrations.transient_models import (
IntegrationMetaData,
@@ -73,17 +74,23 @@ class PaperlessAttributeReferencer( IntegrationAttributeReferencer ):
self,
query : str,
limit : int = 20,
- ) -> List[ AttributeReferenceResult ]:
+ ) -> AttributeReferenceSearchResult:
if not query or not query.strip():
- return []
+ return AttributeReferenceSearchResult( results = [] )
try:
client = build_client()
except IntegrationAttributeError as e:
logger.warning( f'Paperless search aborted: {e}' )
- return []
+ return AttributeReferenceSearchResult(
+ results = [],
+ error_message = 'Paperless integration is not configured.',
+ )
except Exception as e:
logger.exception( f'Paperless client build failed: {e}' )
- return []
+ return AttributeReferenceSearchResult(
+ results = [],
+ error_message = 'Paperless integration error — see server logs.',
+ )
try:
envelope = client.search_documents(
@@ -95,18 +102,35 @@ class PaperlessAttributeReferencer( IntegrationAttributeReferencer ):
f'Paperless search HTTP {status} for query '
f'{query!r}: {e}'
)
- return []
+ return AttributeReferenceSearchResult(
+ results = [],
+ error_message = self._http_error_message( status ),
+ )
except Exception as e:
logger.warning(
f'Paperless search failed for query {query!r}: {e}'
)
- return []
+ return AttributeReferenceSearchResult(
+ results = [],
+ error_message = 'Paperless search failed — see server logs.',
+ )
documents = envelope.get( PaperlessApi.RESPONSE_RESULTS, [] ) or []
- return [
- self._translate( client = client, document = doc, query = query )
- for doc in documents
- ]
+ return AttributeReferenceSearchResult(
+ results = [
+ self._translate( client = client, document = doc, query = query )
+ for doc in documents
+ ],
+ )
+
+ @staticmethod
+ def _http_error_message( status : Optional[int] ) -> str:
+ if status in (401, 403):
+ return ( f'Paperless rejected the request (HTTP {status}). '
+ f'Check the API token.' )
+ if status is None:
+ return 'Paperless returned an unexpected response.'
+ return f'Paperless returned HTTP {status}.'
def _translate(
self,
diff --git a/src/hi/services/paperless/tests/test_pl_referencer.py b/src/hi/services/paperless/tests/test_pl_referencer.py
index b0a7e679..6ef6df33 100644
--- a/src/hi/services/paperless/tests/test_pl_referencer.py
+++ b/src/hi/services/paperless/tests/test_pl_referencer.py
@@ -113,13 +113,15 @@ class TestSearchReferences(TestCase):
# Short-circuit so the picker can render a blank initial
# modal without provoking an upstream call.
result = self.referencer.search_references(query = '', limit = 20)
- self.assertEqual(result, [])
+ self.assertEqual(result.results, [])
+ self.assertIsNone(result.error_message)
mock_build.assert_not_called()
@patch('hi.services.paperless.pl_referencer.build_client')
def test_whitespace_query_returns_empty(self, mock_build):
result = self.referencer.search_references(query = ' ', limit = 20)
- self.assertEqual(result, [])
+ self.assertEqual(result.results, [])
+ self.assertIsNone(result.error_message)
mock_build.assert_not_called()
@patch('hi.services.paperless.pl_referencer.build_client')
@@ -136,23 +138,24 @@ class TestSearchReferences(TestCase):
)
mock_build.return_value = client
- results = self.referencer.search_references(
+ result = self.referencer.search_references(
query = 'warranty', limit = 20,
)
- self.assertEqual(len(results), 2)
- self.assertEqual(results[0].title, 'Warranty')
+ self.assertIsNone(result.error_message)
+ self.assertEqual(len(result.results), 2)
+ self.assertEqual(result.results[0].title, 'Warranty')
self.assertEqual(
- results[0].source_url,
+ result.results[0].source_url,
'https://p.example.com/documents/1/details/',
)
# Thumbnail is the HI proxy URL, NOT the upstream URL — the
# browser fetches via HI's session and HI fetches upstream
# with the configured token.
self.assertIn('/integration/services/paperless/documents/1/thumb/',
- results[0].thumbnail_url)
- self.assertEqual(results[0].mime_type, 'application/pdf')
- self.assertIn('Warranty', results[0].snippet)
+ result.results[0].thumbnail_url)
+ self.assertEqual(result.results[0].mime_type, 'application/pdf')
+ self.assertIn('Warranty', result.results[0].snippet)
@patch('hi.services.paperless.pl_referencer.build_client')
def test_limit_is_passed_through_as_page_size(self, mock_build):
@@ -178,44 +181,63 @@ class TestSearchReferences(TestCase):
lambda id: f'https://p.example.com/documents/{id}/details/'
)
mock_build.return_value = client
- self.assertEqual(
- self.referencer.search_references(query = 'q', limit = 20),
- [],
- )
+ result = self.referencer.search_references(query = 'q', limit = 20)
+ self.assertEqual(result.results, [])
+ self.assertIsNone(result.error_message)
+
+
+class TestSearchReferencesErrorMessages(TestCase):
+ """Failure paths must surface ``error_message`` (not raise) so
+ the picker can render a distinct banner instead of falling back
+ to "no results."""
+
+ def setUp(self):
+ self.referencer = PaperlessAttributeReferencer()
@patch('hi.services.paperless.pl_referencer.build_client',
side_effect = IntegrationAttributeError('not configured'))
- def test_unconfigured_integration_returns_empty(self, _mock_build):
- # Operator opens the picker before configuring the
- # integration — referencer must fail soft so the modal can
- # render an empty result list rather than 500.
- self.assertEqual(
- self.referencer.search_references(query = 'q', limit = 20),
- [],
- )
+ def test_unconfigured_integration(self, _mock_build):
+ result = self.referencer.search_references(query = 'q', limit = 20)
+ self.assertEqual(result.results, [])
+ self.assertIn('not configured', result.error_message)
+
+ @patch('hi.services.paperless.pl_referencer.build_client',
+ side_effect = RuntimeError('boom in build'))
+ def test_unexpected_client_build_error(self, _mock_build):
+ result = self.referencer.search_references(query = 'q', limit = 20)
+ self.assertEqual(result.results, [])
+ self.assertIn('Paperless integration error', result.error_message)
@patch('hi.services.paperless.pl_referencer.build_client')
- def test_upstream_http_error_returns_empty(self, mock_build):
+ def test_http_401_names_token(self, mock_build):
client = Mock()
response = Mock()
response.status_code = 401
- error = HTTPError('401', response = response)
- client.search_documents.side_effect = error
+ client.search_documents.side_effect = HTTPError('401', response = response)
mock_build.return_value = client
- self.assertEqual(
- self.referencer.search_references(query = 'q', limit = 20),
- [],
- )
+ result = self.referencer.search_references(query = 'q', limit = 20)
+ self.assertEqual(result.results, [])
+ self.assertIn('401', result.error_message)
+ self.assertIn('token', result.error_message.lower())
+
+ @patch('hi.services.paperless.pl_referencer.build_client')
+ def test_http_500_surfaces_status_code(self, mock_build):
+ client = Mock()
+ response = Mock()
+ response.status_code = 500
+ client.search_documents.side_effect = HTTPError('500', response = response)
+ mock_build.return_value = client
+ result = self.referencer.search_references(query = 'q', limit = 20)
+ self.assertIn('500', result.error_message)
@patch('hi.services.paperless.pl_referencer.build_client')
- def test_unexpected_exception_returns_empty(self, mock_build):
+ def test_unexpected_search_exception(self, mock_build):
client = Mock()
client.search_documents.side_effect = RuntimeError('boom')
mock_build.return_value = client
- self.assertEqual(
- self.referencer.search_references(query = 'q', limit = 20),
- [],
- )
+ result = self.referencer.search_references(query = 'q', limit = 20)
+ self.assertEqual(result.results, [])
+ self.assertIn('Paperless search failed', result.error_message)
class TestValidateConfiguration(TestCase):
diff --git a/src/hi/settings/base.py b/src/hi/settings/base.py
index bcf60c9a..7782e6f5 100644
--- a/src/hi/settings/base.py
+++ b/src/hi/settings/base.py
@@ -129,6 +129,7 @@ INSTALLED_APPS = [
'hi.services.homebox',
'hi.services.frigate',
'hi.services.paperless',
+ 'hi.services.immich',
'hi.apps.profiles',
]
diff --git a/src/hi/settings/simulator.py b/src/hi/settings/simulator.py
index 98503307..a87dae70 100644
--- a/src/hi/settings/simulator.py
+++ b/src/hi/settings/simulator.py
@@ -22,6 +22,7 @@ INSTALLED_APPS = [
'hi.simulator.services.hass',
'hi.simulator.services.homebox',
'hi.simulator.services.paperless',
+ 'hi.simulator.services.immich',
'hi.simulator.services.zoneminder',
'hi.simulator.weather_sources.nws',
]
diff --git a/src/hi/simulator/services/enums.py b/src/hi/simulator/services/enums.py
index 8c81cef0..1397a4f1 100644
--- a/src/hi/simulator/services/enums.py
+++ b/src/hi/simulator/services/enums.py
@@ -51,6 +51,7 @@ class ServiceFaultMode(LabeledEnum):
HEALTHY = ( 'Healthy' , 'Pass requests through normally (default).' )
AUTH_FAIL = ( 'Auth Fail' , 'Return 401 from every API request.' )
+ FORBIDDEN = ( 'Forbidden' , 'Return 403 from every API request (credentials recognized, action forbidden — e.g., scope or role missing).' )
SERVER_ERROR = ( 'Server Error' , 'Return 500 from every API request.' )
SLOW = ( 'Slow' , 'Sleep past the integration probe timeout, then pass through.' )
NON_JSON = ( 'Non-JSON' , 'Return 200 with text/html body (simulates wrong base URL / proxy).' )
diff --git a/src/hi/simulator/services/immich/__init__.py b/src/hi/simulator/services/immich/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/src/hi/simulator/services/immich/apps.py b/src/hi/simulator/services/immich/apps.py
new file mode 100644
index 00000000..0114b42f
--- /dev/null
+++ b/src/hi/simulator/services/immich/apps.py
@@ -0,0 +1,7 @@
+from django.apps import AppConfig
+
+
+class ImmichConfig( AppConfig ):
+ default_auto_field = 'django.db.models.BigAutoField'
+ name = 'hi.simulator.services.immich'
+ simulator_module_label = 'Immich'
diff --git a/src/hi/simulator/services/immich/simulator.py b/src/hi/simulator/services/immich/simulator.py
new file mode 100644
index 00000000..397267a7
--- /dev/null
+++ b/src/hi/simulator/services/immich/simulator.py
@@ -0,0 +1,87 @@
+"""Immich simulator: parametric smart-search responses.
+
+Contributes only the ATTRIBUTE_REFERENCE capability -- TEXT
+attributes on existing Entity / Location records, no SimEntities of
+its own. Search results are generated on the fly, shaped by
+operator-tuned knobs on the singleton.
+
+Auth-failure simulation is handled framework-wide via
+``ServiceFaultMode``; this simulator does not enforce API keys of
+its own.
+
+Knobs:
+ - result_count : how many assets each smart search returns
+ (0/1/3/10/50 -- exercises empty / single / multi
+ picker rendering paths).
+ - include_exif : whether generated assets carry EXIF city /
+ country (drives the snippet on / off path in the
+ referencer's ``_build_secondary_text``).
+ - latency_ms : artificial latency on the smart-search endpoint,
+ for surfacing debounce or loading issues in the
+ picker.
+"""
+from dataclasses import dataclass
+from typing import Dict, List
+
+from hi.simulator.services.base_models import SimEntityDefinition
+from hi.simulator.services.service_simulator import ServiceSimulator
+
+
+# Discrete result counts the operator can pick; exercises distinct
+# picker rendering paths.
+RESULT_COUNT_CHOICES = ( 0, 1, 3, 10, 50 )
+
+
+@dataclass
+class ImmichSimSettings:
+ """Knobs that parametrize every response. Held on the
+ ImmichSimulator singleton; ephemeral."""
+
+ result_count : int = 3
+ include_exif : bool = True
+ latency_ms : int = 0
+
+
+class ImmichSimulator( ServiceSimulator ):
+
+ def __init_singleton__( self ):
+ # Set BEFORE initialize() so a SimProfile switch does NOT
+ # reset operator-tuned settings.
+ self._settings = ImmichSimSettings()
+ super().__init_singleton__()
+ return
+
+ @property
+ def id(self) -> str:
+ return 'immich'
+
+ @property
+ def label(self) -> str:
+ return 'Immich'
+
+ @property
+ def integration_urls(self) -> List[ tuple ]:
+ return [ ( 'Immich API base', 'services/immich/' ) ]
+
+ @property
+ def settings(self) -> ImmichSimSettings:
+ return self._settings
+
+ def set_settings( self, settings : ImmichSimSettings ) -> None:
+ self._settings = settings
+ return
+
+ @property
+ def sim_entity_definition_list(self) -> List[ SimEntityDefinition ]:
+ return []
+
+ @property
+ def extras_template_name(self) -> str:
+ return 'immich/panes/settings_form.html'
+
+ @property
+ def extras_context(self) -> Dict:
+ return {
+ 'settings' : self._settings,
+ 'result_count_choices' : RESULT_COUNT_CHOICES,
+ }
diff --git a/src/hi/simulator/services/immich/templates/immich/pages/photo_preview.html b/src/hi/simulator/services/immich/templates/immich/pages/photo_preview.html
new file mode 100644
index 00000000..e954a2dd
--- /dev/null
+++ b/src/hi/simulator/services/immich/templates/immich/pages/photo_preview.html
@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>Immich Simulator — Photo {{ asset_id }}</title>
+ <style>
+ body { font-family: sans-serif; max-width: 40em; margin: 4em auto; color: #212529; }
+ .asset-id { font-size: 1.6em; color: #6c757d; word-break: break-all; }
+ .hint { color: #6c757d; margin-top: 2em; font-size: 0.9em; }
+ </style>
+</head>
+<body>
+ <div class="asset-id">Photo {{ asset_id }}</div>
+ <p>This is the Immich simulator's stand-in for the per-asset view. The real Immich web UI would show the photo, EXIF, albums, and tags here.</p>
+ <p class="hint">Source URLs from the ATTRIBUTE_REFERENCE picker link to pages like this one; close the tab to return to the picker modal.</p>
+</body>
+</html>
diff --git a/src/hi/simulator/services/immich/templates/immich/panes/settings_form.html b/src/hi/simulator/services/immich/templates/immich/panes/settings_form.html
new file mode 100644
index 00000000..2bd2db4a
--- /dev/null
+++ b/src/hi/simulator/services/immich/templates/immich/panes/settings_form.html
@@ -0,0 +1,66 @@
+{% comment %}
+ Operator-tuned knobs for the Immich simulator. Each control submits
+ the form on change (no submit button) so toggles take effect
+ immediately. Antinode swap-in-place via data-async.
+
+ Context:
+ settings : ImmichSimSettings
+ result_count_choices : tuple[int]
+{% endcomment %}
+<form id="hi-immich-settings-form"
+ method="post"
+ action="{% url 'immich_settings_set' %}"
+ class="mb-3"
+ data-async data-mode="replace">
+ {% csrf_token %}
+
+ <div class="form-row align-items-end">
+
+ <div class="form-group col-auto">
+ <label for="hi-immich-result-count" class="small text-muted mb-1">
+ Result count
+ </label>
+ <select id="hi-immich-result-count"
+ name="result_count"
+ class="form-control form-control-sm"
+ onchange="this.form.requestSubmit ? this.form.requestSubmit() : this.form.submit()">
+ {% for choice in result_count_choices %}
+ <option value="{{ choice }}"
+ {% if choice == settings.result_count %}selected{% endif %}>
+ {{ choice }}
+ </option>
+ {% endfor %}
+ </select>
+ </div>
+
+ <div class="form-group col-auto">
+ <label for="hi-immich-latency" class="small text-muted mb-1">
+ Latency (ms)
+ </label>
+ <input type="number"
+ id="hi-immich-latency"
+ name="latency_ms"
+ value="{{ settings.latency_ms }}"
+ min="0" max="10000" step="50"
+ class="form-control form-control-sm"
+ style="width: 8em;"
+ onchange="this.form.requestSubmit ? this.form.requestSubmit() : this.form.submit()">
+ </div>
+
+ <div class="form-group col-auto mb-0">
+ <div class="form-check">
+ <input type="checkbox"
+ id="hi-immich-include-exif"
+ name="include_exif"
+ value="on"
+ class="form-check-input"
+ {% if settings.include_exif %}checked{% endif %}
+ onchange="this.form.requestSubmit ? this.form.requestSubmit() : this.form.submit()">
+ <label class="form-check-label small" for="hi-immich-include-exif">
+ Include EXIF city/country
+ </label>
+ </div>
+ </div>
+
+ </div>
+</form>
diff --git a/src/hi/simulator/services/immich/urls.py b/src/hi/simulator/services/immich/urls.py
new file mode 100644
index 00000000..e69ba670
--- /dev/null
+++ b/src/hi/simulator/services/immich/urls.py
@@ -0,0 +1,27 @@
+from django.urls import path
+
+from . import views
+
+
+urlpatterns = [
+
+ path( 'api/search/smart',
+ views.SmartSearchView.as_view(),
+ name = 'immich_search_smart' ),
+
+ path( 'api/search/metadata',
+ views.MetadataSearchView.as_view(),
+ name = 'immich_search_metadata' ),
+
+ path( 'api/assets/<str:asset_id>/thumbnail',
+ views.ThumbnailView.as_view(),
+ name = 'immich_asset_thumbnail' ),
+
+ path( 'photos/<str:asset_id>',
+ views.PhotoPreviewView.as_view(),
+ name = 'immich_photo_preview' ),
+
+ path( 'settings/set/',
+ views.SetSettingsView.as_view(),
+ name = 'immich_settings_set' ),
+]
diff --git a/src/hi/simulator/services/immich/views.py b/src/hi/simulator/services/immich/views.py
new file mode 100644
index 00000000..7a850ed4
--- /dev/null
+++ b/src/hi/simulator/services/immich/views.py
@@ -0,0 +1,253 @@
+"""Immich simulator views.
+
+Endpoint families:
+
+ - ``SmartSearchView`` -- ``POST /api/search/smart``: the smart
+ CLIP endpoint the integration's
+ referencer hits for every search. Body:
+ ``{"query": ..., "size": N}``.
+ - ``MetadataSearchView`` -- ``POST /api/search/metadata``: the
+ probe-only endpoint hit by the
+ integration's ``validate_access``.
+ Returns a minimal envelope.
+ - ``ThumbnailView`` -- ``GET /api/assets/<id>/thumbnail``:
+ serves an SVG placeholder.
+ - ``SetSettingsView`` -- POST target for the extras form;
+ mutates the singleton's
+ ``ImmichSimSettings`` and re-renders the
+ form fragment.
+
+Auth failures are simulated framework-wide via ``ServiceFaultMode``;
+these views do not inspect the ``x-api-key`` header themselves.
+"""
+import hashlib
+import json
+import time
+from dataclasses import replace
+from datetime import datetime, timezone
+from typing import List, Optional
+
+from django.core.exceptions import BadRequest
+from django.http import HttpResponse, JsonResponse
+from django.shortcuts import render
+from django.utils.decorators import method_decorator
+from django.views import View
+from django.views.decorators.csrf import csrf_exempt
+
+from .simulator import (
+ ImmichSimSettings,
+ ImmichSimulator,
+ RESULT_COUNT_CHOICES,
+)
+
+
+# ---- asset generator --------------------------------------------
+
+
+_CITY_COUNTRY_CYCLE = (
+ ( 'Portland', 'USA' ),
+ ( 'Seattle', 'USA' ),
+ ( 'Vancouver', 'Canada' ),
+ ( None, None ), # exercise the no-EXIF row
+)
+
+
+def _stable_asset_id( query : str, index : int ) -> str:
+ """Map (query, index) to a stable UUID-shaped string. Different
+ queries produce distinct ids; same query -> same ids."""
+ digest = hashlib.sha256( f'{query}\x00{index}'.encode() ).hexdigest()
+ # UUID v4 layout: 8-4-4-4-12 hex. Borrow the first 32 digest chars.
+ return (
+ f'{digest[0:8]}-{digest[8:12]}-{digest[12:16]}-'
+ f'{digest[16:20]}-{digest[20:32]}'
+ )
+
+
+def _generate_assets(
+ settings : ImmichSimSettings, query : str,
+) -> List[dict]:
+ """Build ``settings.result_count`` synthetic Immich assets for the
+ given query. (query, index) -> asset_id is stable so the picker
+ sees the same asset on repeat searches."""
+ now_iso = datetime.now(timezone.utc).isoformat()
+ assets = []
+ for index in range( settings.result_count ):
+ asset_id = _stable_asset_id( query or '', index )
+ # Filename bakes in the query so operators can visually trace
+ # what was searched.
+ filename = f'{(query or "asset").strip().replace(" ", "-")}-{index + 1}.jpg'
+ asset = {
+ 'id' : asset_id,
+ 'originalFileName' : filename,
+ 'originalMimeType' : 'image/jpeg',
+ 'type' : 'IMAGE',
+ 'fileCreatedAt' : now_iso,
+ }
+ if settings.include_exif:
+ city, country = _CITY_COUNTRY_CYCLE[ index % len(_CITY_COUNTRY_CYCLE) ]
+ asset['exifInfo'] = {
+ 'city': city,
+ 'country': country,
+ }
+ else:
+ asset['exifInfo'] = None
+ assets.append( asset )
+ return assets
+
+
+def _search_envelope( assets : List[dict] ) -> dict:
+ return {
+ 'assets': {
+ 'items' : assets,
+ 'total' : len( assets ),
+ 'count' : len( assets ),
+ 'nextPage' : None,
+ },
+ 'albums': {
+ 'items' : [],
+ 'total' : 0,
+ 'count' : 0,
+ 'nextPage' : None,
+ },
+ }
+
+
+# ---- endpoints --------------------------------------------------
+
+
+@method_decorator(csrf_exempt, name='dispatch')
+class SmartSearchView( View ):
+
+ def post( self, request, *args, **kwargs ):
+ simulator = ImmichSimulator()
+ settings = simulator.settings
+ if settings.latency_ms > 0:
+ time.sleep( settings.latency_ms / 1000.0 )
+ # Body is JSON: {"query": "...", "size": N}. Query is read for
+ # stable id generation and filename baking only; size isn't
+ # honored because the operator-chosen result_count is the
+ # source of truth for the simulator.
+ try:
+ payload = _safe_json( request.body )
+ except ValueError:
+ return JsonResponse({ 'message': 'Invalid JSON.' }, status = 400)
+ query = ( payload.get( 'query' ) or '' ).strip()
+ return JsonResponse(
+ _search_envelope( _generate_assets( settings, query )),
+ )
+
+
+@method_decorator(csrf_exempt, name='dispatch')
+class MetadataSearchView( View ):
+ """Probe-only endpoint. The integration uses it for
+ ``validate_access``; it never appears on the search path. Returns
+ a minimal envelope."""
+
+ def post( self, request, *args, **kwargs ):
+ return JsonResponse( _search_envelope( assets = [] ))
+
+
+def _thumbnail_svg( asset_id : str ) -> bytes:
+ short = asset_id.split('-')[0]
+ return (
+ f'<svg xmlns="http://www.w3.org/2000/svg" width="160" height="160" '
+ f'viewBox="0 0 160 160">'
+ f'<rect width="160" height="160" fill="#cfe2ff" stroke="#0d6efd"/>'
+ f'<text x="80" y="86" text-anchor="middle" font-family="sans-serif" '
+ f'font-size="18" fill="#084298">{short}</text>'
+ f'</svg>'
+ ).encode('utf-8')
+
+
+class ThumbnailView( View ):
+
+ def get( self, request, *args, **kwargs ):
+ asset_id = kwargs.get( 'asset_id' ) or ''
+ return HttpResponse(
+ _thumbnail_svg( asset_id ),
+ content_type = 'image/svg+xml',
+ )
+
+
+class PhotoPreviewView( View ):
+ """``GET /photos/<id>`` -- minimal preview page representing the
+ per-asset view in Immich's web UI. The picker links here as the
+ result's persisted source URL."""
+
+ TEMPLATE_NAME = 'immich/pages/photo_preview.html'
+
+ def get( self, request, *args, **kwargs ):
+ asset_id = kwargs.get( 'asset_id' ) or ''
+ return render(
+ request,
+ self.TEMPLATE_NAME,
+ { 'asset_id': asset_id },
+ )
+
+
+class SetSettingsView( View ):
+ """POST target for the extras form. Validates each field, updates
+ the singleton, and re-renders the settings fragment."""
+
+ TEMPLATE_NAME = 'immich/panes/settings_form.html'
+
+ def post( self, request, *args, **kwargs ):
+ simulator = ImmichSimulator()
+ current = simulator.settings
+ new_settings = replace(
+ current,
+ result_count = self._parse_result_count(
+ request.POST.get( 'result_count' ), current.result_count,
+ ),
+ include_exif = self._parse_bool(
+ request.POST.get( 'include_exif' ),
+ ),
+ latency_ms = self._parse_latency_ms(
+ request.POST.get( 'latency_ms' ), current.latency_ms,
+ ),
+ )
+ simulator.set_settings( new_settings )
+ return render(
+ request,
+ self.TEMPLATE_NAME,
+ {
+ 'settings' : new_settings,
+ 'result_count_choices' : RESULT_COUNT_CHOICES,
+ },
+ )
+
+ @staticmethod
+ def _parse_result_count( raw : Optional[str], fallback : int ) -> int:
+ try:
+ value = int( raw )
+ except (TypeError, ValueError):
+ return fallback
+ if value not in RESULT_COUNT_CHOICES:
+ raise BadRequest( f'Invalid result_count: {raw!r}' )
+ return value
+
+ @staticmethod
+ def _parse_bool( raw : Optional[str] ) -> bool:
+ # An unchecked checkbox is absent from the POST body, so the
+ # mere presence of the field name (with any truthy value) is
+ # the signal.
+ return bool( raw )
+
+ @staticmethod
+ def _parse_latency_ms( raw : Optional[str], fallback : int ) -> int:
+ try:
+ value = int( raw )
+ except (TypeError, ValueError):
+ return fallback
+ if value < 0 or value > 10000:
+ raise BadRequest( f'latency_ms out of range: {raw!r}' )
+ return value
+
+
+# ---- helpers ----------------------------------------------------
+
+
+def _safe_json( body : bytes ) -> dict:
+ if not body:
+ return {}
+ return json.loads( body.decode('utf-8') )
diff --git a/src/hi/simulator/services/middleware.py b/src/hi/simulator/services/middleware.py
index 7119f987..a5e9033a 100644
--- a/src/hi/simulator/services/middleware.py
+++ b/src/hi/simulator/services/middleware.py
@@ -56,6 +56,12 @@ class ServiceFaultInjectionMiddleware:
status = 401,
)
+ if fault_mode == ServiceFaultMode.FORBIDDEN:
+ return JsonResponse(
+ { 'message': 'Forbidden' },
+ status = 403,
+ )
+
if fault_mode == ServiceFaultMode.SERVER_ERROR:
return JsonResponse(
{ 'message': 'Internal server error' },
diff --git a/src/hi/static/img/integrations/immich.png b/src/hi/static/img/integrations/immich.png
new file mode 100644
index 00000000..fb52bbb5
Binary files /dev/null and b/src/hi/static/img/integrations/immich.png differ