diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d4de05a..1f81177 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -10,7 +10,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
- module: [Server, Web-App]
+ module: [Server, Web-App, Media]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
@@ -151,6 +151,9 @@ jobs:
curl="docker run --rm --network ${COMPOSE_PROJECT_NAME}_default curlimages/curl:8.11.1 -fsS"
$curl http://server:8080/readyz
$curl http://web:3000/ | grep -q '
'
+ # docwell-media sits on an internal network only the server reaches.
+ docker compose exec -T server wget -qO- http://media:8090/healthz | grep -q ok
+ if $curl --max-time 5 http://media:8090/healthz; then echo "media is reachable from the default network"; exit 1; fi
- name: Stop the compose stack
if: always()
working-directory: Docker
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 322e80a..4a2a8a1 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -50,6 +50,9 @@ jobs:
- name: docwell-web
context: .
dockerfile: Web-App/Dockerfile
+ - name: docwell-media
+ context: .
+ dockerfile: Media/Dockerfile
- name: docwell
context: .
dockerfile: Docker-AIO/Dockerfile
diff --git a/Docker-AIO/Dockerfile b/Docker-AIO/Dockerfile
index af5d0e6..abfe43f 100644
--- a/Docker-AIO/Dockerfile
+++ b/Docker-AIO/Dockerfile
@@ -39,7 +39,8 @@ RUN cd Web-App && go build -trimpath -ldflags "-s -w -X main.Version=${VERSION}"
FROM alpine:3.22
ARG PB_VERSION=0.40.6
ARG TARGETARCH
-# ffmpeg cuts long recordings into pieces for transcription (ADR-15).
+# ffmpeg cuts long recordings for transcription (ADR-15). The split stacks run
+# it in docwell-media instead; here it stays in, to keep this one container.
RUN apk add --no-cache ca-certificates unzip wget ffmpeg \
&& wget -q "https://github.com/pocketbase/pocketbase/releases/download/v${PB_VERSION}/pocketbase_${PB_VERSION}_linux_${TARGETARCH:-amd64}.zip" -O /tmp/pb.zip \
&& unzip /tmp/pb.zip pocketbase -d /usr/local/bin && rm /tmp/pb.zip && apk del unzip
diff --git a/Docker/.env.example b/Docker/.env.example
index a8c5233..4f00cf9 100644
--- a/Docker/.env.example
+++ b/Docker/.env.example
@@ -20,6 +20,12 @@ DOCWELL_DRAWIO_URL=
# Largest attachment in MB (1-100).
DOCWELL_MAX_UPLOAD_MB=50
+# Recordings over 25 MB are cut for transcription by the media service
+# (docwell-media, ffmpeg in a container of its own). Optional shared secret
+# between it and docwell-server. To run without it, remove the media service
+# and set DOCWELL_MEDIA_URL= (blank): MP3 and WAV are then cut by the server.
+DOCWELL_MEDIA_TOKEN=
+
# Sign-up defaults; the admin panel can change them later.
# The first account always can sign up and becomes the instance admin.
DOCWELL_SIGNUP_ENABLED=true
diff --git a/Docker/.env.prod.example b/Docker/.env.prod.example
index dd06481..6d58ec9 100644
--- a/Docker/.env.prod.example
+++ b/Docker/.env.prod.example
@@ -61,6 +61,12 @@ DOCWELL_ADMIN_NAME=
# Largest attachment in MB (1-100).
DOCWELL_MAX_UPLOAD_MB=50
+
+# Recordings over 25 MB are cut for transcription by the media service
+# (docwell-media, ffmpeg in a container of its own). Optional shared secret
+# between it and docwell-server. To run without it, remove the media service
+# and set DOCWELL_MEDIA_URL= (blank): MP3 and WAV are then cut by the server.
+DOCWELL_MEDIA_TOKEN=
# Days to keep audit log entries. Blank = 365, 0 = forever.
DOCWELL_AUDIT_RETENTION_DAYS=
diff --git a/Docker/.env.prod.s3.example b/Docker/.env.prod.s3.example
index 35d7c67..1afbe8f 100644
--- a/Docker/.env.prod.s3.example
+++ b/Docker/.env.prod.s3.example
@@ -61,6 +61,12 @@ DOCWELL_ADMIN_NAME=
# Largest attachment in MB (1-100).
DOCWELL_MAX_UPLOAD_MB=50
+
+# Recordings over 25 MB are cut for transcription by the media service
+# (docwell-media, ffmpeg in a container of its own). Optional shared secret
+# between it and docwell-server. To run without it, remove the media service
+# and set DOCWELL_MEDIA_URL= (blank): MP3 and WAV are then cut by the server.
+DOCWELL_MEDIA_TOKEN=
# Days to keep audit log entries. Blank = 365, 0 = forever.
DOCWELL_AUDIT_RETENTION_DAYS=
diff --git a/Docker/.env.prod.seaweedfs.example b/Docker/.env.prod.seaweedfs.example
index 9c393f2..0622b19 100644
--- a/Docker/.env.prod.seaweedfs.example
+++ b/Docker/.env.prod.seaweedfs.example
@@ -61,6 +61,12 @@ DOCWELL_ADMIN_NAME=
# Largest attachment in MB (1-100).
DOCWELL_MAX_UPLOAD_MB=50
+
+# Recordings over 25 MB are cut for transcription by the media service
+# (docwell-media, ffmpeg in a container of its own). Optional shared secret
+# between it and docwell-server. To run without it, remove the media service
+# and set DOCWELL_MEDIA_URL= (blank): MP3 and WAV are then cut by the server.
+DOCWELL_MEDIA_TOKEN=
# Days to keep audit log entries. Blank = 365, 0 = forever.
DOCWELL_AUDIT_RETENTION_DAYS=
diff --git a/Docker/.env.prod.seaweedfs.split.example b/Docker/.env.prod.seaweedfs.split.example
index 1f7f80b..e3d34c4 100644
--- a/Docker/.env.prod.seaweedfs.split.example
+++ b/Docker/.env.prod.seaweedfs.split.example
@@ -61,6 +61,12 @@ DOCWELL_ADMIN_NAME=
# Largest attachment in MB (1-100).
DOCWELL_MAX_UPLOAD_MB=50
+
+# Recordings over 25 MB are cut for transcription by the media service
+# (docwell-media, ffmpeg in a container of its own). Optional shared secret
+# between it and docwell-server. To run without it, remove the media service
+# and set DOCWELL_MEDIA_URL= (blank): MP3 and WAV are then cut by the server.
+DOCWELL_MEDIA_TOKEN=
# Days to keep audit log entries. Blank = 365, 0 = forever.
DOCWELL_AUDIT_RETENTION_DAYS=
diff --git a/Docker/README.md b/Docker/README.md
index bebb2ee..ed2395f 100644
--- a/Docker/README.md
+++ b/Docker/README.md
@@ -1,6 +1,8 @@
# Docwell: separate services
-docwell-db (PocketBase), docwell-server and docwell-web, each in its own container.
+docwell-db (PocketBase), docwell-server and docwell-web, each in its own container, plus docwell-media: ffmpeg,
+which cuts recordings over 25 MB for transcription, on an internal network only docwell-server reaches. Remove the
+`media` service and set `DOCWELL_MEDIA_URL=` (blank) to run without it; the server then cuts only MP3 and WAV.
For everything in one container, see [`../Docker-AIO`](../Docker-AIO/README.md).
| Compose file | Env template | Uploaded files live in | Use it for |
diff --git a/Docker/docker-compose.prod.s3.yml b/Docker/docker-compose.prod.s3.yml
index 8a5ec04..7681848 100644
--- a/Docker/docker-compose.prod.s3.yml
+++ b/Docker/docker-compose.prod.s3.yml
@@ -115,6 +115,10 @@ services:
DOCWELL_SMTP_USERNAME: "${DOCWELL_SMTP_USERNAME:-}"
DOCWELL_SMTP_PASSWORD: "${DOCWELL_SMTP_PASSWORD:-}"
DOCWELL_SMTP_TLS: "${DOCWELL_SMTP_TLS:-false}"
+ # docwell-media cuts recordings over 25 MB for transcription. Blank =
+ # the server cuts MP3 and WAV itself and refuses other long formats.
+ DOCWELL_MEDIA_URL: "${DOCWELL_MEDIA_URL-http://media:8090}"
+ DOCWELL_MEDIA_TOKEN: "${DOCWELL_MEDIA_TOKEN:-}"
# --- File storage: external S3 --------------------------------------
# Applied by docwell-server on every start, so these win over the
# admin panel's Storage screen. Only uploaded files move to the bucket;
@@ -128,6 +132,7 @@ services:
DOCWELL_S3_SECRET: "${DOCWELL_S3_SECRET:?set DOCWELL_S3_SECRET in .env}"
# true for SeaweedFS and MinIO, false for AWS S3 proper.
DOCWELL_S3_FORCE_PATH_STYLE: "${DOCWELL_S3_FORCE_PATH_STYLE:-true}"
+ networks: [default, media]
volumes:
# The search index only; rebuilt from the database when missing, so it
# needs no backup.
@@ -143,6 +148,31 @@ services:
retries: 12
start_period: 20s
+ media:
+ # ffmpeg behind a small API, apart from the database and secrets: it
+ # parses uploaded recordings. Only docwell-server reaches it, on a
+ # network with no way out.
+ image: "${MEDIA_IMAGE:-${DOCWELL_REGISTRY:-ghcr.io/docwell}/docwell-media:${DOCWELL_VERSION:-latest}}"
+ container_name: docwell-media
+ restart: unless-stopped
+ environment:
+ DOCWELL_MEDIA_TOKEN: "${DOCWELL_MEDIA_TOKEN:-}"
+ # Recordings re-encoded at the same time; later ones wait.
+ DOCWELL_MEDIA_JOBS: "${DOCWELL_MEDIA_JOBS:-2}"
+ networks: [media]
+ read_only: true
+ cap_drop: [ALL]
+ security_opt: ["no-new-privileges:true"]
+ volumes:
+ # Scratch space for one recording (up to 1 GB) while it is cut.
+ - media_tmp:/tmp
+ healthcheck:
+ test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8090/healthz || exit 1"]
+ interval: 10s
+ timeout: 3s
+ retries: 12
+ start_period: 5s
+
web:
image: "${WEB_IMAGE:-${DOCWELL_REGISTRY:-ghcr.io/docwell}/docwell-web:${DOCWELL_VERSION:-latest}}"
container_name: docwell-web
@@ -168,3 +198,9 @@ services:
volumes:
pb_data:
server_data:
+ media_tmp:
+
+networks:
+ default:
+ media:
+ internal: true
diff --git a/Docker/docker-compose.prod.seaweedfs.split.yml b/Docker/docker-compose.prod.seaweedfs.split.yml
index 49505df..07b8234 100644
--- a/Docker/docker-compose.prod.seaweedfs.split.yml
+++ b/Docker/docker-compose.prod.seaweedfs.split.yml
@@ -283,6 +283,10 @@ services:
DOCWELL_SMTP_USERNAME: "${DOCWELL_SMTP_USERNAME:-}"
DOCWELL_SMTP_PASSWORD: "${DOCWELL_SMTP_PASSWORD:-}"
DOCWELL_SMTP_TLS: "${DOCWELL_SMTP_TLS:-false}"
+ # docwell-media cuts recordings over 25 MB for transcription. Blank =
+ # the server cuts MP3 and WAV itself and refuses other long formats.
+ DOCWELL_MEDIA_URL: "${DOCWELL_MEDIA_URL-http://media:8090}"
+ DOCWELL_MEDIA_TOKEN: "${DOCWELL_MEDIA_TOKEN:-}"
# --- File storage: the SeaweedFS in this stack ------------------------
# Applied by docwell-server on every start, so these win over
# the admin panel's Storage screen. Only uploaded files move to the
@@ -297,6 +301,7 @@ services:
DOCWELL_S3_SECRET: "${DOCWELL_S3_SECRET:?set DOCWELL_S3_SECRET in .env}"
# Path style: a self-hosted gateway has no per-bucket DNS names.
DOCWELL_S3_FORCE_PATH_STYLE: "true"
+ networks: [default, media]
volumes:
# The search index only; rebuilt from the database when missing, so it
# needs no backup.
@@ -312,6 +317,31 @@ services:
retries: 12
start_period: 20s
+ media:
+ # ffmpeg behind a small API, apart from the database and secrets: it
+ # parses uploaded recordings. Only docwell-server reaches it, on a
+ # network with no way out.
+ image: "${MEDIA_IMAGE:-${DOCWELL_REGISTRY:-ghcr.io/docwell}/docwell-media:${DOCWELL_VERSION:-latest}}"
+ container_name: docwell-media
+ restart: unless-stopped
+ environment:
+ DOCWELL_MEDIA_TOKEN: "${DOCWELL_MEDIA_TOKEN:-}"
+ # Recordings re-encoded at the same time; later ones wait.
+ DOCWELL_MEDIA_JOBS: "${DOCWELL_MEDIA_JOBS:-2}"
+ networks: [media]
+ read_only: true
+ cap_drop: [ALL]
+ security_opt: ["no-new-privileges:true"]
+ volumes:
+ # Scratch space for one recording (up to 1 GB) while it is cut.
+ - media_tmp:/tmp
+ healthcheck:
+ test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8090/healthz || exit 1"]
+ interval: 10s
+ timeout: 3s
+ retries: 12
+ start_period: 5s
+
web:
image: "${WEB_IMAGE:-${DOCWELL_REGISTRY:-ghcr.io/docwell}/docwell-web:${DOCWELL_VERSION:-latest}}"
container_name: docwell-web
@@ -339,3 +369,9 @@ volumes:
server_data:
seaweed_data:
seaweed_admin:
+ media_tmp:
+
+networks:
+ default:
+ media:
+ internal: true
diff --git a/Docker/docker-compose.prod.seaweedfs.yml b/Docker/docker-compose.prod.seaweedfs.yml
index fd209c0..ad2b0dd 100644
--- a/Docker/docker-compose.prod.seaweedfs.yml
+++ b/Docker/docker-compose.prod.seaweedfs.yml
@@ -159,6 +159,10 @@ services:
DOCWELL_SMTP_USERNAME: "${DOCWELL_SMTP_USERNAME:-}"
DOCWELL_SMTP_PASSWORD: "${DOCWELL_SMTP_PASSWORD:-}"
DOCWELL_SMTP_TLS: "${DOCWELL_SMTP_TLS:-false}"
+ # docwell-media cuts recordings over 25 MB for transcription. Blank =
+ # the server cuts MP3 and WAV itself and refuses other long formats.
+ DOCWELL_MEDIA_URL: "${DOCWELL_MEDIA_URL-http://media:8090}"
+ DOCWELL_MEDIA_TOKEN: "${DOCWELL_MEDIA_TOKEN:-}"
# --- File storage: the SeaweedFS in this stack ------------------------
# Applied by docwell-server on every start, so these win over
# the admin panel's Storage screen. Only uploaded files move to the
@@ -173,6 +177,7 @@ services:
DOCWELL_S3_SECRET: "${DOCWELL_S3_SECRET:?set DOCWELL_S3_SECRET in .env}"
# Path style: a self-hosted gateway has no per-bucket DNS names.
DOCWELL_S3_FORCE_PATH_STYLE: "true"
+ networks: [default, media]
volumes:
# The search index only; rebuilt from the database when missing, so it
# needs no backup.
@@ -188,6 +193,31 @@ services:
retries: 12
start_period: 20s
+ media:
+ # ffmpeg behind a small API, apart from the database and secrets: it
+ # parses uploaded recordings. Only docwell-server reaches it, on a
+ # network with no way out.
+ image: "${MEDIA_IMAGE:-${DOCWELL_REGISTRY:-ghcr.io/docwell}/docwell-media:${DOCWELL_VERSION:-latest}}"
+ container_name: docwell-media
+ restart: unless-stopped
+ environment:
+ DOCWELL_MEDIA_TOKEN: "${DOCWELL_MEDIA_TOKEN:-}"
+ # Recordings re-encoded at the same time; later ones wait.
+ DOCWELL_MEDIA_JOBS: "${DOCWELL_MEDIA_JOBS:-2}"
+ networks: [media]
+ read_only: true
+ cap_drop: [ALL]
+ security_opt: ["no-new-privileges:true"]
+ volumes:
+ # Scratch space for one recording (up to 1 GB) while it is cut.
+ - media_tmp:/tmp
+ healthcheck:
+ test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8090/healthz || exit 1"]
+ interval: 10s
+ timeout: 3s
+ retries: 12
+ start_period: 5s
+
web:
image: "${WEB_IMAGE:-${DOCWELL_REGISTRY:-ghcr.io/docwell}/docwell-web:${DOCWELL_VERSION:-latest}}"
container_name: docwell-web
@@ -214,3 +244,9 @@ volumes:
pb_data:
server_data:
seaweed_data:
+ media_tmp:
+
+networks:
+ default:
+ media:
+ internal: true
diff --git a/Docker/docker-compose.prod.yml b/Docker/docker-compose.prod.yml
index 6df4c6b..9875c83 100644
--- a/Docker/docker-compose.prod.yml
+++ b/Docker/docker-compose.prod.yml
@@ -102,6 +102,11 @@ services:
DOCWELL_SMTP_USERNAME: "${DOCWELL_SMTP_USERNAME:-}"
DOCWELL_SMTP_PASSWORD: "${DOCWELL_SMTP_PASSWORD:-}"
DOCWELL_SMTP_TLS: "${DOCWELL_SMTP_TLS:-false}"
+ # docwell-media cuts recordings over 25 MB for transcription. Blank =
+ # the server cuts MP3 and WAV itself and refuses other long formats.
+ DOCWELL_MEDIA_URL: "${DOCWELL_MEDIA_URL-http://media:8090}"
+ DOCWELL_MEDIA_TOKEN: "${DOCWELL_MEDIA_TOKEN:-}"
+ networks: [default, media]
volumes:
# The search index only; rebuilt from the database when missing, so it
# needs no backup.
@@ -117,6 +122,31 @@ services:
retries: 12
start_period: 20s
+ media:
+ # ffmpeg behind a small API, apart from the database and secrets: it
+ # parses uploaded recordings. Only docwell-server reaches it, on a
+ # network with no way out.
+ image: "${MEDIA_IMAGE:-${DOCWELL_REGISTRY:-ghcr.io/docwell}/docwell-media:${DOCWELL_VERSION:-latest}}"
+ container_name: docwell-media
+ restart: unless-stopped
+ environment:
+ DOCWELL_MEDIA_TOKEN: "${DOCWELL_MEDIA_TOKEN:-}"
+ # Recordings re-encoded at the same time; later ones wait.
+ DOCWELL_MEDIA_JOBS: "${DOCWELL_MEDIA_JOBS:-2}"
+ networks: [media]
+ read_only: true
+ cap_drop: [ALL]
+ security_opt: ["no-new-privileges:true"]
+ volumes:
+ # Scratch space for one recording (up to 1 GB) while it is cut.
+ - media_tmp:/tmp
+ healthcheck:
+ test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8090/healthz || exit 1"]
+ interval: 10s
+ timeout: 3s
+ retries: 12
+ start_period: 5s
+
web:
image: "${WEB_IMAGE:-${DOCWELL_REGISTRY:-ghcr.io/docwell}/docwell-web:${DOCWELL_VERSION:-latest}}"
container_name: docwell-web
@@ -142,3 +172,9 @@ services:
volumes:
pb_data:
server_data:
+ media_tmp:
+
+networks:
+ default:
+ media:
+ internal: true
diff --git a/Docker/docker-compose.yml b/Docker/docker-compose.yml
index bce9c21..61f676a 100644
--- a/Docker/docker-compose.yml
+++ b/Docker/docker-compose.yml
@@ -54,12 +54,38 @@ services:
DOCWELL_SMTP_USERNAME: ${DOCWELL_SMTP_USERNAME:-}
DOCWELL_SMTP_PASSWORD: ${DOCWELL_SMTP_PASSWORD:-}
DOCWELL_SMTP_TLS: ${DOCWELL_SMTP_TLS:-false}
+ # docwell-media cuts recordings over 25 MB for transcription. Blank =
+ # the server cuts MP3 and WAV itself and refuses other long formats.
+ DOCWELL_MEDIA_URL: ${DOCWELL_MEDIA_URL-http://media:8090}
+ DOCWELL_MEDIA_TOKEN: ${DOCWELL_MEDIA_TOKEN:-}
+ networks: [default, media]
volumes:
# The search index (rebuilt from the database when missing).
- server_data:/data
ports:
- "8080:8080"
+ media:
+ # ffmpeg behind a small API, apart from the database and secrets: it
+ # parses uploaded recordings. Only docwell-server reaches it, on a
+ # network with no way out.
+ image: ${DOCWELL_REGISTRY:-ghcr.io/docwell}/docwell-media:${DOCWELL_VERSION:-latest}
+ build:
+ context: ..
+ dockerfile: Media/Dockerfile
+ restart: unless-stopped
+ environment:
+ DOCWELL_MEDIA_TOKEN: ${DOCWELL_MEDIA_TOKEN:-}
+ # Recordings re-encoded at the same time; later ones wait.
+ DOCWELL_MEDIA_JOBS: ${DOCWELL_MEDIA_JOBS:-2}
+ networks: [media]
+ read_only: true
+ cap_drop: [ALL]
+ security_opt: ["no-new-privileges:true"]
+ volumes:
+ # Scratch space for one recording (up to 1 GB) while it is cut.
+ - media_tmp:/tmp
+
web:
image: ${DOCWELL_REGISTRY:-ghcr.io/docwell}/docwell-web:${DOCWELL_VERSION:-latest}
build:
@@ -87,3 +113,9 @@ services:
volumes:
pb_data:
server_data:
+ media_tmp:
+
+networks:
+ default:
+ media:
+ internal: true
diff --git a/Docs-Site/guide/administration.md b/Docs-Site/guide/administration.md
index dee7caa..2c9270a 100644
--- a/Docs-Site/guide/administration.md
+++ b/Docs-Site/guide/administration.md
@@ -51,8 +51,9 @@ Docwell brings no AI of its own: you choose a provider, and nothing is sent anyw
API (OpenAI, Azure, OpenRouter, LiteLLM, vLLM, LocalAI…), Anthropic, or Ollama, with a chat model and, except
for Anthropic, optionally an embedding model; OpenAI-compatible providers can also have a speech-to-text model
(for example `whisper-1`, or a self-hosted faster-whisper or LocalAI server) for transcribing recordings;
- Anthropic and Ollama have no speech-to-text API. Recordings over 25 MB are cut into pieces with ffmpeg (in the
- Docker images; without it only MP3 and WAV can be cut). Providers are tried from the top: when one fails, the next one
+ Anthropic and Ollama have no speech-to-text API. Recordings over 25 MB are cut into pieces with ffmpeg, which runs
+ in the docwell-media container of the compose stacks (or inside the all-in-one image); without it only MP3 and
+ WAV can be cut. Providers are tried from the top: when one fails, the next one
answers. **Test** checks a provider; requests and tokens are counted per provider.
- **Search by meaning.** *Index pages for AI* in a workspace's settings sends every page's text to the first
provider with an embedding model and keeps the vectors in `DOCWELL_DATA_DIR`. Without it, the chat finds sources
diff --git a/Docs-Site/guide/configuration.md b/Docs-Site/guide/configuration.md
index b1a7e17..43a0db1 100644
--- a/Docs-Site/guide/configuration.md
+++ b/Docs-Site/guide/configuration.md
@@ -32,6 +32,8 @@ Docwell's collections in it when it starts. Change the image with `DB_IMAGE`.
| `DOCWELL_MAX_UPLOAD_MB` | `50` | Largest attachment, 1 to 100. |
| `DOCWELL_DATA_DIR` | `./data` (`/data` in the image) | The search index and the AI vectors (`ai.db`). Both are rebuilt from the database when missing, so a volume is optional but makes restarts faster (and saves embedding every page again). |
| `DOCWELL_SECRET_KEY` | — | Encrypts the API keys of AI providers. Without it, a key derived from `DOCWELL_PB_PASSWORD` is used; changing whichever is in use means entering the provider keys again. |
+| `DOCWELL_MEDIA_URL` | — (`http://media:8090` in the compose stacks) | docwell-media, which cuts recordings over 25 MB into pieces for transcription with ffmpeg. Blank: the server uses its own ffmpeg if it has one (the all-in-one image does), and otherwise cuts only MP3 and WAV. If docwell-media cannot be reached, the server falls back the same way. |
+| `DOCWELL_MEDIA_TOKEN` | — | Shared secret between docwell-server and docwell-media; set the same value on both, or leave both blank. |
| `DOCWELL_SHUTDOWN_TIMEOUT` | `15s` | How long to wait for requests and open pages to finish saving on shutdown. |
| `DOCWELL_AUDIT_RETENTION_DAYS` | `365` | How long the audit log keeps entries. `0` keeps them forever. |
| `DOCWELL_WEBHOOKS_ALLOW_LOCAL` | `false` | Let webhooks, and the AI providers of workspaces, call loopback and link-local addresses. For development only (AI providers set up in the admin panel may always use local addresses). |
diff --git a/Media/Dockerfile b/Media/Dockerfile
new file mode 100644
index 0000000..70d991d
--- /dev/null
+++ b/Media/Dockerfile
@@ -0,0 +1,20 @@
+# docwell-media: ffmpeg behind a small HTTP API; docwell-server sends it the
+# recordings over 25 MB to cut into pieces for transcription (ADR-15).
+# Build from the repository root: docker build -f Media/Dockerfile .
+
+FROM --platform=$BUILDPLATFORM golang:1.26-alpine AS build
+ARG TARGETOS TARGETARCH
+WORKDIR /src/Media
+COPY Media/ ./
+ARG VERSION=dev
+RUN CGO_ENABLED=0 GOWORK=off GOOS=$TARGETOS GOARCH=$TARGETARCH go build -trimpath -ldflags "-s -w -X main.Version=${VERSION}" \
+ -o /out/docwell-media ./cmd/docwell-media
+
+FROM alpine:3.22
+RUN apk add --no-cache ffmpeg && adduser -D -u 10001 docwell
+COPY --from=build /out/docwell-media /usr/local/bin/docwell-media
+USER docwell
+EXPOSE 8090
+HEALTHCHECK --interval=10s --timeout=3s --retries=5 \
+ CMD wget -qO- http://127.0.0.1:8090/healthz >/dev/null || exit 1
+ENTRYPOINT ["docwell-media"]
diff --git a/Media/cmd/docwell-media/main.go b/Media/cmd/docwell-media/main.go
new file mode 100644
index 0000000..b9758cd
--- /dev/null
+++ b/Media/cmd/docwell-media/main.go
@@ -0,0 +1,187 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+// docwell-media cuts long recordings into pieces for docwell-server's
+// speech-to-text calls (ADR-15). It wraps ffmpeg so that ffmpeg, which parses
+// untrusted uploads, runs in a container of its own with no access to the
+// database, the data folder or secrets.
+//
+// POST /v1/split?name=meeting.m4a[&segment=1200]
+// Authorization: Bearer (when one is set)
+// body: the recording
+//
+// 200 returns multipart/mixed, one audio/mpeg part per piece in order; 422
+// returns text/plain when ffmpeg cannot read the recording.
+package main
+
+import (
+ "context"
+ "crypto/subtle"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "mime/multipart"
+ "net/http"
+ "net/textproto"
+ "os"
+ "os/exec"
+ "os/signal"
+ "path/filepath"
+ "strconv"
+ "syscall"
+ "time"
+)
+
+// Version is set at build time.
+var Version = "dev"
+
+type config struct {
+ addr string
+ token string
+ maxMB int64
+ jobs int
+ timeout time.Duration
+ ffmpeg string
+}
+
+func loadConfig() (config, error) {
+ get := func(k, def string) string {
+ if v := os.Getenv(k); v != "" {
+ return v
+ }
+ return def
+ }
+ c := config{addr: get("DOCWELL_MEDIA_ADDR", ":8090"), token: os.Getenv("DOCWELL_MEDIA_TOKEN")}
+ var err error
+ if c.maxMB, err = strconv.ParseInt(get("DOCWELL_MEDIA_MAX_MB", "1024"), 10, 64); err != nil || c.maxMB < 1 {
+ return c, errors.New("DOCWELL_MEDIA_MAX_MB must be a positive number")
+ }
+ if c.jobs, err = strconv.Atoi(get("DOCWELL_MEDIA_JOBS", "2")); err != nil || c.jobs < 1 {
+ return c, errors.New("DOCWELL_MEDIA_JOBS must be a positive number")
+ }
+ if c.timeout, err = time.ParseDuration(get("DOCWELL_MEDIA_TIMEOUT", "30m")); err != nil || c.timeout <= 0 {
+ return c, errors.New("DOCWELL_MEDIA_TIMEOUT must be a duration such as 30m")
+ }
+ if c.ffmpeg, err = exec.LookPath(get("DOCWELL_MEDIA_FFMPEG", "ffmpeg")); err != nil {
+ return c, fmt.Errorf("ffmpeg not found: %w", err)
+ }
+ return c, nil
+}
+
+func main() {
+ log := slog.New(slog.NewTextHandler(os.Stderr, nil))
+ c, err := loadConfig()
+ if err != nil {
+ log.Error("docwell-media: config", "err", err)
+ os.Exit(1)
+ }
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+ srv := &http.Server{Addr: c.addr, Handler: newHandler(c, log), ReadHeaderTimeout: 10 * time.Second}
+ go func() {
+ <-ctx.Done()
+ shut, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+ _ = srv.Shutdown(shut)
+ }()
+ log.Info("docwell-media listening", "addr", c.addr, "version", Version, "jobs", c.jobs)
+ if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ log.Error("docwell-media", "err", err)
+ os.Exit(1)
+ }
+}
+
+func newHandler(c config, log *slog.Logger) http.Handler {
+ slots := make(chan struct{}, c.jobs)
+ mux := http.NewServeMux()
+ mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = io.WriteString(w, "ok")
+ })
+ mux.HandleFunc("POST /v1/split", func(w http.ResponseWriter, r *http.Request) {
+ if c.token != "" {
+ want := "Bearer " + c.token
+ if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte(want)) != 1 {
+ http.Error(w, "unauthorized", http.StatusUnauthorized)
+ return
+ }
+ }
+ segment := 1200
+ if v := r.URL.Query().Get("segment"); v != "" {
+ n, err := strconv.Atoi(v)
+ if err != nil || n < 10 || n > 3600 {
+ http.Error(w, "segment must be 10 to 3600 seconds", http.StatusBadRequest)
+ return
+ }
+ segment = n
+ }
+ // One ffmpeg per slot; later requests wait their turn.
+ select {
+ case slots <- struct{}{}:
+ defer func() { <-slots }()
+ case <-r.Context().Done():
+ return
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), c.timeout)
+ defer cancel()
+
+ dir, err := os.MkdirTemp("", "docwell-media-")
+ if err != nil {
+ log.Error("media: temp dir", "err", err)
+ http.Error(w, "internal error", http.StatusInternalServerError)
+ return
+ }
+ defer os.RemoveAll(dir)
+ in := filepath.Join(dir, "in"+inputExt(r.URL.Query().Get("name")))
+ if err := save(in, http.MaxBytesReader(w, r.Body, c.maxMB<<20)); err != nil {
+ var tooBig *http.MaxBytesError
+ if errors.As(err, &tooBig) {
+ http.Error(w, fmt.Sprintf("recordings up to %d MB", c.maxMB), http.StatusRequestEntityTooLarge)
+ return
+ }
+ log.Warn("media: upload", "err", err)
+ http.Error(w, "upload failed", http.StatusBadRequest)
+ return
+ }
+ start := time.Now()
+ pieces, err := split(ctx, c.ffmpeg, in, segment)
+ if err != nil {
+ var bad errUnreadable
+ if errors.As(err, &bad) {
+ http.Error(w, bad.msg, http.StatusUnprocessableEntity)
+ return
+ }
+ log.Error("media: ffmpeg", "err", err)
+ http.Error(w, "internal error", http.StatusInternalServerError)
+ return
+ }
+ log.Info("media: split", "pieces", len(pieces), "took", time.Since(start).Round(time.Millisecond))
+ mw := multipart.NewWriter(w)
+ w.Header().Set("Content-Type", "multipart/mixed; boundary="+mw.Boundary())
+ for i, p := range pieces {
+ part, err := mw.CreatePart(textproto.MIMEHeader{
+ "Content-Type": {"audio/mpeg"},
+ "Content-Disposition": {fmt.Sprintf(`attachment; filename="part%03d.mp3"`, i+1)},
+ })
+ if err != nil {
+ return
+ }
+ if _, err := part.Write(p); err != nil {
+ return
+ }
+ }
+ _ = mw.Close()
+ })
+ return mux
+}
+
+func save(path string, body io.Reader) error {
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0o600) // #nosec G304 G703 -- path is in our temp dir
+ if err != nil {
+ return err
+ }
+ if _, err := io.Copy(f, body); err != nil {
+ _ = f.Close()
+ return err
+ }
+ return f.Close()
+}
diff --git a/Media/cmd/docwell-media/main_test.go b/Media/cmd/docwell-media/main_test.go
new file mode 100644
index 0000000..0998ef4
--- /dev/null
+++ b/Media/cmd/docwell-media/main_test.go
@@ -0,0 +1,108 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package main
+
+import (
+ "bytes"
+ "io"
+ "log/slog"
+ "mime"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestInputExt(t *testing.T) {
+ for name, want := range map[string]string{
+ "a.M4A": ".m4a", "a.mp3": ".mp3", "x": ".bin", "a.m3u8": ".m3u8",
+ "a.toolongext": ".bin", "a.m-a": ".bin", "../../etc/passwd": ".bin",
+ } {
+ if got := inputExt(name); got != want {
+ t.Errorf("inputExt(%q) = %q, want %q", name, got, want)
+ }
+ }
+}
+
+func testConfig(t *testing.T) config {
+ ffmpeg, err := exec.LookPath("ffmpeg")
+ if err != nil {
+ t.Skip("no ffmpeg")
+ }
+ return config{token: "secret", maxMB: 50, jobs: 1, timeout: time.Minute, ffmpeg: ffmpeg}
+}
+
+func TestSplitEndpoint(t *testing.T) {
+ c := testConfig(t)
+ wav, err := exec.Command(c.ffmpeg, "-loglevel", "error", "-f", "lavfi", "-i", "sine=frequency=440:duration=30",
+ "-f", "wav", "-").Output() // #nosec G204 -- test
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := httptest.NewServer(newHandler(c, slog.New(slog.DiscardHandler)))
+ defer srv.Close()
+
+ post := func(token, query string, body []byte) *http.Response {
+ req, _ := http.NewRequest("POST", srv.URL+"/v1/split?"+query, bytes.NewReader(body))
+ req.Header.Set("Authorization", "Bearer "+token)
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return res
+ }
+
+ res := post("wrong", "name=tone.wav", wav)
+ res.Body.Close()
+ if res.StatusCode != http.StatusUnauthorized {
+ t.Fatalf("wrong token: %d", res.StatusCode)
+ }
+
+ res = post("secret", "name=tone.wav&segment=10", wav)
+ defer res.Body.Close()
+ if res.StatusCode != http.StatusOK {
+ b, _ := io.ReadAll(res.Body)
+ t.Fatalf("split: %d %s", res.StatusCode, b)
+ }
+ _, params, err := mime.ParseMediaType(res.Header.Get("Content-Type"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ mr := multipart.NewReader(res.Body, params["boundary"])
+ n := 0
+ for {
+ p, err := mr.NextPart()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, _ := io.ReadAll(p)
+ if len(b) == 0 || p.Header.Get("Content-Type") != "audio/mpeg" {
+ t.Fatalf("part %d: %d bytes, %q", n, len(b), p.Header.Get("Content-Type"))
+ }
+ n++
+ }
+ // Cuts land on frame boundaries, so a short tail piece may follow.
+ if n < 3 || n > 4 {
+ t.Fatalf("30 s cut every 10 s gave %d pieces", n)
+ }
+
+ res = post("secret", "name=junk.mp3", []byte(strings.Repeat("not audio ", 100)))
+ b, _ := io.ReadAll(res.Body)
+ res.Body.Close()
+ if res.StatusCode != http.StatusUnprocessableEntity || !strings.Contains(string(b), "could not be read") {
+ t.Fatalf("junk: %d %s", res.StatusCode, b)
+ }
+
+ // A playlist pointing at a local file is refused (no hls/concat demuxer).
+ res = post("secret", "name=x.m3u8", []byte("#EXTM3U\n#EXTINF:10,\nfile:///etc/passwd\n"))
+ res.Body.Close()
+ if res.StatusCode != http.StatusUnprocessableEntity {
+ t.Fatalf("playlist: %d", res.StatusCode)
+ }
+}
diff --git a/Media/cmd/docwell-media/split.go b/Media/cmd/docwell-media/split.go
new file mode 100644
index 0000000..6863e46
--- /dev/null
+++ b/Media/cmd/docwell-media/split.go
@@ -0,0 +1,86 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package main
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "sort"
+ "strings"
+)
+
+// errUnreadable wraps ffmpeg's complaint about a recording it cannot decode.
+type errUnreadable struct{ msg string }
+
+func (e errUnreadable) Error() string { return e.msg }
+
+// inputFormats are the demuxers ffmpeg may use on an upload. Playlists
+// (hls, concat, …) and image sequences are left out: they open other files.
+const inputFormats = "mov,mp4,m4a,3gp,mp3,wav,ogg,matroska,webm,flac,aac,mpeg,mpegts,asf,amr,caf,aiff,au,w64"
+
+// inputExt returns the extension ffmpeg sees for the upload: only short,
+// plain ones, so a file name cannot pass anything else to ffmpeg.
+func inputExt(name string) string {
+ ext := strings.ToLower(filepath.Ext(name))
+ if len(ext) < 2 || len(ext) > 6 {
+ return ".bin"
+ }
+ for _, r := range ext[1:] {
+ if (r < 'a' || r > 'z') && (r < '0' || r > '9') {
+ return ".bin"
+ }
+ }
+ return ext
+}
+
+// split re-encodes the recording in dir/in to 16 kHz mono MP3 and cuts
+// it every segment seconds. It returns the pieces in order.
+func split(ctx context.Context, ffmpeg, in string, segment int) ([][]byte, error) {
+ dir := filepath.Dir(in)
+ // #nosec G204 G702 -- ffmpeg from the config, fixed arguments, paths in our temp dir
+ cmd := exec.CommandContext(ctx, ffmpeg, "-nostdin", "-hide_banner", "-loglevel", "error",
+ "-protocol_whitelist", "file", "-format_whitelist", inputFormats,
+ "-i", in, "-vn", "-ac", "1", "-ar", "16000", "-c:a", "libmp3lame", "-b:a", "32k",
+ "-f", "segment", "-segment_time", fmt.Sprint(segment), "-reset_timestamps", "1",
+ filepath.Join(dir, "part%03d.mp3"))
+ var stderr bytes.Buffer
+ cmd.Stderr = &stderr
+ if err := cmd.Run(); err != nil {
+ if ctx.Err() != nil {
+ return nil, ctx.Err()
+ }
+ var exit *exec.ExitError
+ if errors.As(err, &exit) {
+ msg := strings.TrimSpace(stderr.String())
+ if len(msg) > 200 {
+ msg = msg[:200]
+ }
+ return nil, errUnreadable{msg: "The recording could not be read: " + msg}
+ }
+ return nil, err
+ }
+ files, err := filepath.Glob(filepath.Join(dir, "part*.mp3"))
+ if err != nil {
+ return nil, err
+ }
+ sort.Strings(files)
+ var out [][]byte
+ for _, f := range files {
+ b, err := os.ReadFile(f) // #nosec G304 G703 -- a file ffmpeg wrote into our temp dir
+ if err != nil {
+ return nil, err
+ }
+ if len(b) > 0 {
+ out = append(out, b)
+ }
+ }
+ if len(out) == 0 {
+ return nil, errUnreadable{msg: "The recording has no sound to transcribe."}
+ }
+ return out, nil
+}
diff --git a/Media/go.mod b/Media/go.mod
new file mode 100644
index 0000000..e79792f
--- /dev/null
+++ b/Media/go.mod
@@ -0,0 +1,3 @@
+module docwell/media
+
+go 1.26
diff --git a/Server/Dockerfile b/Server/Dockerfile
index a820566..b6beae4 100644
--- a/Server/Dockerfile
+++ b/Server/Dockerfile
@@ -31,8 +31,8 @@ RUN CGO_ENABLED=0 GOWORK=off GOOS=$TARGETOS GOARCH=$TARGETARCH go build -trimpat
-o /out/docwell-server ./cmd/docwell-server
FROM alpine:3.22
-# ffmpeg cuts long recordings into pieces for transcription (ADR-15).
-RUN apk add --no-cache ca-certificates su-exec ffmpeg && adduser -D -u 10001 docwell && mkdir /data && chown docwell /data
+# No ffmpeg here: long recordings are cut in docwell-media (Media/, ADR-15).
+RUN apk add --no-cache ca-certificates su-exec && adduser -D -u 10001 docwell && mkdir /data && chown docwell /data
COPY --from=build /out/docwell-server /usr/local/bin/docwell-server
# Starts as root, fixes the ownership of /data (a bind mount arrives owned by
# root), then runs the server as docwell. See entrypoint.sh.
diff --git a/Server/cmd/docwell-server/main.go b/Server/cmd/docwell-server/main.go
index c86e3d5..743e9c1 100644
--- a/Server/cmd/docwell-server/main.go
+++ b/Server/cmd/docwell-server/main.go
@@ -164,7 +164,8 @@ func run(log *slog.Logger) error {
if secret == "" {
secret = "pb:" + cfg.PocketBasePassword
}
- aiSvc, err := ai.New(db, dirSvc, log, ai.Options{Secret: secret, DataDir: cfg.DataDir, AllowLocal: cfg.WebhooksAllowLocal})
+ aiSvc, err := ai.New(db, dirSvc, log, ai.Options{Secret: secret, DataDir: cfg.DataDir, AllowLocal: cfg.WebhooksAllowLocal,
+ MediaURL: cfg.MediaURL, MediaToken: cfg.MediaToken})
if err != nil {
return err
}
diff --git a/Server/internal/ai/audio.go b/Server/internal/ai/audio.go
index 5aab68c..dc328fb 100644
--- a/Server/internal/ai/audio.go
+++ b/Server/internal/ai/audio.go
@@ -20,10 +20,12 @@ import (
// ---- Long recordings ---------------------------------------------------------------
//
// Speech-to-text APIs take files up to 25 MB. Longer recordings are cut into
-// pieces that are transcribed one after another. With ffmpeg on the server
-// (it is in the Docker image), any audio or video is re-encoded to 16 kHz
-// mono MP3 — what speech models work at anyway — and cut every 20 minutes.
-// Without it, MP3 is cut at frame boundaries and WAV at sample boundaries.
+// pieces that are transcribed one after another. ffmpeg re-encodes any audio
+// or video to 16 kHz mono MP3 — what speech models work at anyway — and cuts
+// it every 20 minutes. It runs in docwell-media (DOCWELL_MEDIA_URL, media.go),
+// which parses uploads away from the database and secrets, or else locally
+// when the server has ffmpeg (the all-in-one image). Without either, MP3 is
+// cut at frame boundaries and WAV at sample boundaries.
// audioPiece is one piece of a recording.
type audioPiece struct {
@@ -42,7 +44,7 @@ var ffmpegPath = func() string {
return p
}()
-var errNeedsFFmpeg = apperr.Invalid("Recordings over 25 MB need ffmpeg on the server to be cut into pieces (the Docker image has it); MP3 and WAV files work without it.")
+var errNeedsFFmpeg = apperr.Invalid("Recordings over 25 MB need ffmpeg to be cut into pieces: run the docwell-media service (DOCWELL_MEDIA_URL) or install ffmpeg on the server. MP3 and WAV files work without it.")
// splitAudio returns the recording as pieces of at most max bytes.
func splitAudio(ctx context.Context, name string, data []byte, max int) ([]audioPiece, error) {
@@ -89,13 +91,22 @@ func splitWithFFmpeg(ctx context.Context, ffmpeg, name string, data []byte, max
return nil, err
}
sort.Strings(files)
- base := strings.TrimSuffix(name, filepath.Ext(name))
- var out []audioPiece
- for i, f := range files {
+ var parts [][]byte
+ for _, f := range files {
b, err := os.ReadFile(f)
if err != nil {
return nil, err
}
+ parts = append(parts, b)
+ }
+ return mp3Pieces(name, parts, max)
+}
+
+// mp3Pieces names the MP3 pieces ffmpeg made, after the recording.
+func mp3Pieces(name string, parts [][]byte, max int) ([]audioPiece, error) {
+ base := strings.TrimSuffix(name, filepath.Ext(name))
+ var out []audioPiece
+ for i, b := range parts {
if len(b) == 0 {
continue
}
diff --git a/Server/internal/ai/media.go b/Server/internal/ai/media.go
new file mode 100644
index 0000000..5fb6a1e
--- /dev/null
+++ b/Server/internal/ai/media.go
@@ -0,0 +1,126 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package ai
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "mime"
+ "mime/multipart"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+
+ "docwell/server/internal/apperr"
+)
+
+// ---- docwell-media ------------------------------------------------------------------
+//
+// docwell-media (Media/ in the repository) is ffmpeg behind a small HTTP API,
+// in a container of its own. The server sends it a recording and gets back
+// the MP3 pieces in order (multipart/mixed).
+
+// mediaClient calls docwell-media; nil when DOCWELL_MEDIA_URL is not set.
+type mediaClient struct {
+ url string // base URL, no trailing slash
+ token string
+ http *http.Client
+}
+
+func newMediaClient(base, token string) *mediaClient {
+ if base == "" {
+ return nil
+ }
+ // No response timeout: a long recording takes minutes to re-encode, and
+ // the request's context ends the call.
+ return &mediaClient{url: strings.TrimRight(base, "/"), token: token, http: &http.Client{
+ Transport: &http.Transport{TLSHandshakeTimeout: 15 * time.Second, IdleConnTimeout: 90 * time.Second},
+ }}
+}
+
+// errMediaUnavailable means docwell-media could not be used (not reachable,
+// or failed); the server then cuts the recording itself where it can.
+var errMediaUnavailable = errors.New("media service unavailable")
+
+// split sends the recording to docwell-media and returns its MP3 pieces.
+func (m *mediaClient) split(ctx context.Context, name string, data []byte) ([][]byte, error) {
+ q := url.Values{"name": {name}, "segment": {fmt.Sprint(segmentSeconds)}}
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, m.url+"/v1/split?"+q.Encode(), bytes.NewReader(data))
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Content-Type", "application/octet-stream")
+ if m.token != "" {
+ req.Header.Set("Authorization", "Bearer "+m.token)
+ }
+ res, err := m.http.Do(req)
+ if err != nil {
+ if ctx.Err() != nil {
+ return nil, ctx.Err()
+ }
+ return nil, fmt.Errorf("%w: %w", errMediaUnavailable, err)
+ }
+ defer res.Body.Close()
+ switch res.StatusCode {
+ case http.StatusOK:
+ case http.StatusUnprocessableEntity: // ffmpeg could not read it
+ b, _ := io.ReadAll(io.LimitReader(res.Body, 1024))
+ return nil, apperr.Invalid(strings.TrimSpace(string(b)))
+ case http.StatusRequestEntityTooLarge:
+ return nil, apperr.Invalid("The recording is larger than the media service accepts.")
+ default:
+ b, _ := io.ReadAll(io.LimitReader(res.Body, 512))
+ return nil, fmt.Errorf("%w: %s %s", errMediaUnavailable, res.Status, strings.TrimSpace(string(b)))
+ }
+ mt, params, err := mime.ParseMediaType(res.Header.Get("Content-Type"))
+ if err != nil || mt != "multipart/mixed" || params["boundary"] == "" {
+ return nil, fmt.Errorf("%w: unexpected response %q", errMediaUnavailable, res.Header.Get("Content-Type"))
+ }
+ mr := multipart.NewReader(res.Body, params["boundary"])
+ var parts [][]byte
+ total := 0
+ for {
+ p, err := mr.NextPart()
+ if errors.Is(err, io.EOF) {
+ break
+ }
+ if err != nil {
+ return nil, fmt.Errorf("%w: %w", errMediaUnavailable, err)
+ }
+ // The pieces are smaller than the recording; a bigger answer is wrong.
+ b, err := io.ReadAll(io.LimitReader(p, int64(MaxRecordingBytes-total)+1))
+ if err != nil {
+ return nil, fmt.Errorf("%w: %w", errMediaUnavailable, err)
+ }
+ if total += len(b); total > MaxRecordingBytes {
+ return nil, fmt.Errorf("%w: response too large", errMediaUnavailable)
+ }
+ parts = append(parts, b)
+ }
+ return parts, nil
+}
+
+// splitRecording cuts a recording into pieces of at most max bytes: in
+// docwell-media when it is set up, else on the server (splitAudio).
+func (s *Service) splitRecording(ctx context.Context, name string, data []byte, max int) ([]audioPiece, error) {
+ if len(data) <= max || s.media == nil {
+ return splitAudio(ctx, name, data, max)
+ }
+ parts, err := s.media.split(ctx, name, data)
+ if err == nil {
+ return mp3Pieces(name, parts, max)
+ }
+ if !errors.Is(err, errMediaUnavailable) {
+ return nil, err
+ }
+ s.log.Warn("ai: media service failed, cutting the recording on the server", "err", err)
+ pieces, lerr := splitAudio(ctx, name, data, max)
+ if errors.Is(lerr, errNeedsFFmpeg) {
+ return nil, apperr.Invalid("The media service that cuts long recordings is not reachable. Try again later, or ask an administrator.")
+ }
+ return pieces, lerr
+}
diff --git a/Server/internal/ai/media_test.go b/Server/internal/ai/media_test.go
new file mode 100644
index 0000000..7eeded2
--- /dev/null
+++ b/Server/internal/ai/media_test.go
@@ -0,0 +1,83 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package ai
+
+import (
+ "context"
+ "io"
+ "log/slog"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "net/textproto"
+ "strings"
+ "testing"
+
+ "docwell/server/internal/apperr"
+)
+
+func TestSplitRecordingWithMediaService(t *testing.T) {
+ saved := ffmpegPath
+ ffmpegPath = ""
+ defer func() { ffmpegPath = saved }()
+
+ var gotName, gotAuth string
+ var gotLen int
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotName, gotAuth = r.URL.Query().Get("name"), r.Header.Get("Authorization")
+ b, _ := io.ReadAll(r.Body)
+ gotLen = len(b)
+ if strings.HasSuffix(gotName, ".bad") {
+ http.Error(w, "The recording could not be read: junk", http.StatusUnprocessableEntity)
+ return
+ }
+ mw := multipart.NewWriter(w)
+ w.Header().Set("Content-Type", "multipart/mixed; boundary="+mw.Boundary())
+ for _, piece := range [][]byte{fakeMP3(5), fakeMP3(40)} {
+ p, _ := mw.CreatePart(textproto.MIMEHeader{"Content-Type": {"audio/mpeg"}})
+ _, _ = p.Write(piece)
+ }
+ _ = mw.Close()
+ }))
+ defer srv.Close()
+ s := &Service{log: slog.New(slog.DiscardHandler), media: newMediaClient(srv.URL+"/", "tok")}
+
+ rec := make([]byte, 20_000) // an .m4a the server could not cut itself
+ pieces, err := s.splitRecording(context.Background(), "talk.m4a", rec, 417*30+10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if gotName != "talk.m4a" || gotAuth != "Bearer tok" || gotLen != len(rec) {
+ t.Fatalf("request: name %q auth %q len %d", gotName, gotAuth, gotLen)
+ }
+ // The second piece (40 frames) is over max and is cut again.
+ if len(pieces) != 3 || pieces[0].Name != "talk-001.mp3" || pieces[1].Name != "talk-002-001.mp3" {
+ names := []string{}
+ for _, p := range pieces {
+ names = append(names, p.Name)
+ }
+ t.Fatalf("pieces = %v", names)
+ }
+
+ // Small recordings never leave the server.
+ gotName = ""
+ if p, err := s.splitRecording(context.Background(), "a.m4a", rec, len(rec)); err != nil || len(p) != 1 || gotName != "" {
+ t.Fatalf("small: %v %d %q", err, len(p), gotName)
+ }
+
+ // ffmpeg's complaint reaches the user.
+ _, err = s.splitRecording(context.Background(), "x.bad", rec, 10)
+ if e, ok := apperr.As(err); !ok || !strings.Contains(e.Error(), "could not be read") {
+ t.Fatalf("unreadable: %v", err)
+ }
+
+ // Unreachable: MP3 is still cut on the server, other formats get a clear error.
+ srv.Close()
+ if p, err := s.splitRecording(context.Background(), "a.mp3", fakeMP3(100), 417*30+10); err != nil || len(p) != 4 {
+ t.Fatalf("fallback mp3: %v %d", err, len(p))
+ }
+ _, err = s.splitRecording(context.Background(), "a.m4a", rec, 10)
+ if e, ok := apperr.As(err); !ok || !strings.Contains(e.Error(), "not reachable") {
+ t.Fatalf("fallback m4a: %v", err)
+ }
+}
diff --git a/Server/internal/ai/service.go b/Server/internal/ai/service.go
index e4152c3..87ba29f 100644
--- a/Server/internal/ai/service.go
+++ b/Server/internal/ai/service.go
@@ -29,6 +29,11 @@ type Options struct {
// AllowLocal lets workspace profiles reach loopback and private
// addresses, like webhooks. Instance profiles always may.
AllowLocal bool
+ // MediaURL is docwell-media's address (DOCWELL_MEDIA_URL), which cuts
+ // long recordings with ffmpeg; "" cuts them on the server. MediaToken is
+ // its shared secret (DOCWELL_MEDIA_TOKEN), if it has one.
+ MediaURL string
+ MediaToken string
}
// Service is the AI layer.
@@ -40,6 +45,7 @@ type Service struct {
open *http.Client
store *Store
log *slog.Logger
+ media *mediaClient
usageMu sync.Mutex
passMu sync.Mutex // one indexing pass at a time
@@ -75,6 +81,7 @@ func newService(pb *pocketbase.Client, dir *directory.Service, log *slog.Logger,
pb: pb, dir: dir, keys: newSealer(o.Secret), log: log, store: store,
guarded: transport(webhooks.Guard(o.AllowLocal)),
open: transport(nil),
+ media: newMediaClient(o.MediaURL, o.MediaToken),
wakeCh: make(chan struct{}, 1),
status: map[string]*indexState{},
}
diff --git a/Server/internal/ai/transcribe.go b/Server/internal/ai/transcribe.go
index f45fd47..f3810e9 100644
--- a/Server/internal/ai/transcribe.go
+++ b/Server/internal/ai/transcribe.go
@@ -123,7 +123,7 @@ func (s *Service) Transcribe(ctx context.Context, c access.Caller, fileID string
if len(data) > MaxRecordingBytes {
return Transcript{}, apperr.Invalid("Recordings up to 1 GB can be transcribed.")
}
- pieces, err := splitAudio(ctx, dl.Name, data, MaxTranscribeBytes)
+ pieces, err := s.splitRecording(ctx, dl.Name, data, MaxTranscribeBytes)
if err != nil {
return Transcript{}, err
}
diff --git a/Server/internal/config/config.go b/Server/internal/config/config.go
index 0aeb37d..43e77ec 100644
--- a/Server/internal/config/config.go
+++ b/Server/internal/config/config.go
@@ -5,6 +5,7 @@ package config
import (
"errors"
+ "net/url"
"os"
"strconv"
"strings"
@@ -43,6 +44,10 @@ type Config struct {
SecretKey string
// MaxUploadMB caps one attachment.
MaxUploadMB int
+ // MediaURL is docwell-media, which cuts long recordings with ffmpeg; ""
+ // cuts them on the server. MediaToken is its shared secret, if any.
+ MediaURL string
+ MediaToken string
ShutdownTimeout time.Duration
@@ -109,6 +114,8 @@ func fromLookup(lookup func(string) (string, bool)) (Config, error) {
AdminName: get("DOCWELL_ADMIN_NAME", ""),
DataDir: get("DOCWELL_DATA_DIR", "./data"),
SecretKey: get("DOCWELL_SECRET_KEY", ""),
+ MediaURL: strings.TrimRight(get("DOCWELL_MEDIA_URL", ""), "/"),
+ MediaToken: get("DOCWELL_MEDIA_TOKEN", ""),
ShutdownTimeout: 15 * time.Second,
WebhooksAllowLocal: get("DOCWELL_WEBHOOKS_ALLOW_LOCAL", "false") == "true",
}
@@ -167,6 +174,13 @@ func fromLookup(lookup func(string) (string, bool)) (Config, error) {
cfg.MaxUploadMB = n
}
+ if cfg.MediaURL != "" {
+ u, err := url.Parse(cfg.MediaURL)
+ if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
+ return Config{}, errors.New("DOCWELL_MEDIA_URL must be an http(s) URL, e.g. http://media:8090")
+ }
+ }
+
if (cfg.AdminEmail == "") != (cfg.AdminPassword == "") {
return Config{}, errors.New("set both DOCWELL_ADMIN_EMAIL and DOCWELL_ADMIN_PASSWORD, or neither")
}
diff --git a/go.work b/go.work
index 8ec5fbd..2637381 100644
--- a/go.work
+++ b/go.work
@@ -2,6 +2,7 @@ go 1.26.0
use (
./Desktop-App
+ ./Media
./Server
./Web-App
)