> For the complete documentation index, see [llms.txt](https://diffio.ai/llms.txt). This page is also available as HTML at https://diffio.ai/docs/developers/guides/saas-podcast-cleanup/.

# Podcast cleanup in a SaaS app

Your users upload episodes from the browser straight to Diffio, your server keeps the API key and each user's projects apart, and a signed webhook tells you when the cleaned audio is ready to play.

## How it works

1. Browser → Your server: `POST /api/uploads`, file name and size
2. Your server → Diffio API: `POST /projects`, Diffio-End-User from your session
3. Diffio API → Your server: `upload`, upload_token, upload.requests
4. Your server → Browser: `upload`, never the API key
5. Browser → Media host: `start, parts, complete`, Bearer upload_token
6. Browser → Your server: `POST …/{id}/complete`, your route
7. Your server → Diffio API: `POST …/upload/complete`, the restore starts
8. Diffio API → Your server: `generation.completed`, signed; matched to one job
9. Browser → Your server: `GET /api/uploads/{id}`, your route
10. Your server → Diffio API: `GET …/media`, as the signed-in user, 6 hour URLs

**Solid arrows are requests and webhook deliveries; dashed arrows are answers.**

## Build it

### 1. Set up

Install the SDK and a web framework. Set the API key, the endpoint's `whsec_` signing secret (step 4) and a session secret, on the server only.

**Terminal**

```bash
pip install diffio flask                     # Python
npm install diffio express express-session   # or Node.js
export DIFFIO_API_KEY="diffio_..."
export DIFFIO_WEBHOOK_SECRET="whsec_..."
export SESSION_SECRET="..."
```

### 2. Create the project for the signed-in user

`create_upload` takes the user id from your session, never from the request body, and sends it as `Diffio-End-User`. `generation` queues the restore now; it starts once the file lands. The browser's `upload_key` becomes the `Idempotency-Key`, so a retried request returns the same project. The job row keeps the project, its first `generation_id` and the user.

### 3. Upload from the browser

The server returns only `upload`. The browser follows `upload.requests` (start, parts, complete) with the `upload_token` as a bearer token; the media host accepts these four requests from any origin. The token is scoped to this one project's file and works for 24 hours (`upload.expires_at`); [POST .../upload](https://diffio.ai/docs/api-reference/reopen-project-upload/) gives a new one. Keep the `uploadKey` with the file: a retry with the same key gets the same project, and `upload: null` when its file already arrived.

**upload.js (browser)**

```javascript
// Runs in the browser: the file goes straight to Diffio's media host with the upload token.
// Pass the same uploadKey when you retry the same file (keep it with the file, for example in sessionStorage), so a
// retry after a lost answer reuses its project instead of creating another.
export async function uploadEpisode(file, uploadKey) {
  const created = await fetch("/api/uploads", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ upload_key: uploadKey, file_name: file.name, size_bytes: file.size }),
  });
  if (!created.ok) throw new Error(`Could not start the upload (${created.status})`);
  const { project_id, upload } = await created.json();

  if (upload) { // null: the file already arrived on an earlier try
    const { start, part, complete } = upload.requests;
    const send = async (request, url, body, headers = request.headers) => {
      const response = await fetch(url, { method: request.method, headers, body });
      if (!response.ok) throw new Error(`Upload failed (${response.status})`);
      return response.json();
    };
    const { uploadId, partSizeBytes } = await send(start, start.url);
    const parts = [];
    for (let number = 1, offset = 0; offset < file.size; number += 1, offset += partSizeBytes) {
      const url = part.url.replace("{part_number}", number).replace("{upload_id}", encodeURIComponent(uploadId));
      // The browser sets Content-Length itself; only the Authorization header is copied.
      const chunk = file.slice(offset, offset + partSizeBytes);
      const { etag } = await send(part, url, chunk, { Authorization: part.headers.Authorization });
      parts.push({ partNumber: number, etag });
    }
    await send(complete, complete.url, JSON.stringify({ uploadId, parts }));
  }

  const completed = await fetch(`/api/uploads/${project_id}/complete`, { method: "POST" }); // safe to repeat
  if (!completed.ok) throw new Error(`Could not finish the upload (${completed.status})`);
  return project_id; // poll GET /api/uploads/<project_id> until status is "complete"
}
```

### 4. Verify and record the webhook

Open the portal with `python app.py portal` or `node app.mjs portal` (an account-wide client, no end user) and add `https://your-app.example/webhooks/diffio` for `generation.completed` and `generation.failed`.

- **Verify**: the signature with the SDK, on the raw body.
- **One transaction:**: record `event.id` (a repeat changes nothing) and update the job.
- **Match the job**: on `data.id` = its `generation_id` and `data.end_user` = its user. A second restore or an edit of the same project, or another user's event, changes nothing.
- **Answer `204` after the commit**, with no API calls in the delivery; an error answers 500 and the delivery is retried.

Payloads and retries: [Webhooks](https://diffio.ai/docs/developers/webhooks/).

### 5. Fetch media on read

`GET /api/uploads/<id>` asks Diffio for media as the signed-in user once the job is complete, and again when the stored URL has less than 5 minutes of its 6 hours left.

### The complete server

**Run it locally:** the [example folder](https://diffio.ai/docs/examples/saas-podcast-cleanup/README.md) adds a development sign-in for two users, a page with a file input and player, and a signed sample webhook, with the commands and results to expect.

**app.py**

```python
"""Podcast cleanup in a SaaS app: browser uploads, one Diffio end user per customer, signed webhooks.

python app.py          serves on http://localhost:3000
python app.py portal   prints a link to the webhook portal
"""
import os
import sqlite3
import sys
from datetime import datetime, timedelta, timezone

from diffio import DiffioClient, WebhookVerificationError, verify_webhook_signature
from flask import Flask, abort, g, jsonify, request, session

DB_PATH = "podcasts.db"
app = Flask(__name__)
app.secret_key = os.environ["SESSION_SECRET"]  # signs the session cookie your sign-in sets

with sqlite3.connect(DB_PATH) as setup:
    setup.executescript("""
        create table if not exists jobs (
            project_id text primary key, user_id text not null, generation_id text not null,
            status text not null, error_code text, audio_url text, expires_at text);
        create table if not exists webhook_events (id text primary key, type text, created_at text);
    """)


def db():
    """One connection per request, so each delivery runs its own transaction."""
    if "db" not in g:
        g.db = sqlite3.connect(DB_PATH, timeout=10)
    return g.db


@app.teardown_appcontext
def close_db(_error):
    if "db" in g:
        g.pop("db").close()


def diffio_for(user_id):
    """A client that acts for one of your users: every call sends Diffio-End-User."""
    return DiffioClient(end_user=user_id)


def signed_in_user():
    user_id = session.get("user_id")  # set by your own sign-in, never by the request body
    if not user_id:
        abort(401)
    return user_id


@app.post("/api/uploads")
def create_upload():
    user_id = signed_in_user()
    body = request.get_json()
    with diffio_for(user_id) as diffio:
        project = diffio.projects.create(
            file_name=body["file_name"],
            size_bytes=body["size_bytes"],
            generation={"model": "diffio-flash"},  # starts by itself once the file lands
            idempotency_key=f"upload-{body['upload_key']}",  # a retried request gets the same project
        )
    with db() as conn:
        conn.execute("insert or ignore into jobs (project_id, user_id, generation_id, status) values (?, ?, ?, ?)",
                     (project.id, user_id, project.latest_generation.id, "processing"))
    # Only the upload descriptors go to the browser; the API key stays here.
    return jsonify(project_id=project.id, upload=project.upload.to_dict() if project.upload else None)


@app.post("/api/uploads/<project_id>/complete")
def complete_upload(project_id):
    with diffio_for(signed_in_user()) as diffio:
        project = diffio.projects.complete_upload(project_id)  # 404 unless it is this user's project
    return jsonify(status=project.status)


@app.get("/api/uploads/<project_id>")
def get_upload(project_id):
    user_id = signed_in_user()
    conn = db()
    job = conn.execute("select generation_id, status, error_code, audio_url, expires_at from jobs"
                       " where project_id = ? and user_id = ?", (project_id, user_id)).fetchone()
    if job is None:
        abort(404)
    generation_id, status, error_code, audio_url, expires_at = job
    soon = datetime.now(timezone.utc) + timedelta(minutes=5)
    if status == "complete" and (not expires_at or datetime.fromisoformat(expires_at.replace("Z", "+00:00")) < soon):
        # Media is fetched here, on read: media URLs last 6 hours.
        with diffio_for(user_id) as diffio:
            media = diffio.generations.media(project_id, generation_id)
        audio_url, expires_at = media.files["audio"], media.expires_at
        with conn:
            conn.execute("update jobs set audio_url = ?, expires_at = ? where project_id = ?",
                         (audio_url, expires_at, project_id))
    return jsonify(status=status, error_code=error_code, audio_url=audio_url, expires_at=expires_at)


@app.post("/webhooks/diffio")
def diffio_webhook():
    try:
        event = verify_webhook_signature(request.get_data(), request.headers, os.environ["DIFFIO_WEBHOOK_SECRET"])
    except WebhookVerificationError:
        return "", 400
    data = event.data
    with db() as conn:  # one transaction: the receipt and the job update commit together, or neither does
        first = conn.execute("insert or ignore into webhook_events (id, type, created_at) values (?, ?, ?)",
                             (event.id, event.type, event.created_at)).rowcount
        if first and event.type in ("generation.completed", "generation.failed"):
            # Only the job this generation started, for the user the event names.
            conn.execute("update jobs set status = ?, error_code = ?"
                         " where project_id = ? and generation_id = ? and user_id = ?",
                         ("complete" if event.type == "generation.completed" else "failed", data.error_code,
                          data.project_id, data.id, data.end_user))
    return "", 204  # after the commit; an exception above answers 500 and Svix retries


if __name__ == "__main__":
    if sys.argv[1:] == ["portal"]:
        # The webhook portal belongs to the whole account: a client with no end user.
        account = DiffioClient()
        print(account.webhooks.portal().url)
    else:
        app.run(port=3000)
```

**app.mjs**

```javascript
// Podcast cleanup in a SaaS app: browser uploads, one Diffio end user per customer, signed webhooks.
// node app.mjs          serves on http://localhost:3000 (Node 22.13 or later, for node:sqlite)
// node app.mjs portal   prints a link to the webhook portal
import { DatabaseSync } from "node:sqlite";
import express from "express";
import session from "express-session";
import { DiffioClient, DiffioWebhookVerificationError, verifyWebhookSignature } from "diffio";

const db = new DatabaseSync("podcasts.db");
db.exec(`
  create table if not exists jobs (
    project_id text primary key, user_id text not null, generation_id text not null,
    status text not null, error_code text, audio_url text, expires_at text);
  create table if not exists webhook_events (id text primary key, type text, created_at text);
`);

// A client that acts for one of your users: every call sends Diffio-End-User.
const diffioFor = (userId) => new DiffioClient({ endUser: userId });

if (process.argv[2] === "portal") {
  // The webhook portal belongs to the whole account: a client with no end user.
  const account = new DiffioClient();
  console.log((await account.webhooks.portal()).url);
  process.exit(0);
}

const app = express();

// Registered before express.json(): the signature covers the raw body.
app.post("/webhooks/diffio", express.raw({ type: "*/*" }), (req, res) => {
  let event;
  try {
    event = verifyWebhookSignature(req.body, req.headers, process.env.DIFFIO_WEBHOOK_SECRET);
  } catch (error) {
    if (error instanceof DiffioWebhookVerificationError) return res.sendStatus(400);
    throw error;
  }
  const { data } = event;
  // One transaction: the receipt and the job update commit together, or neither does. node:sqlite is
  // synchronous, so no other delivery runs between begin and commit.
  db.exec("begin immediate");
  try {
    const { changes } = db.prepare("insert or ignore into webhook_events (id, type, created_at) values (?, ?, ?)")
      .run(event.id, event.type, event.created_at);
    if (changes && (event.type === "generation.completed" || event.type === "generation.failed")) {
      // Only the job this generation started, for the user the event names.
      db.prepare("update jobs set status = ?, error_code = ? where project_id = ? and generation_id = ? and user_id = ?")
        .run(event.type === "generation.completed" ? "complete" : "failed", data.error_code ?? null,
          data.project_id, data.id, data.end_user ?? null);
    }
    db.exec("commit");
  } catch (error) {
    db.exec("rollback");
    throw error; // answers 500, and Svix retries
  }
  res.sendStatus(204); // after the commit
});

app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false }));
app.use(express.json());

// Your own sign-in sets req.session.userId; the request body never names the user.
function signedInUser(req) {
  if (!req.session.userId) throw Object.assign(new Error("Sign in first"), { status: 401 });
  return req.session.userId;
}

app.post("/api/uploads", async (req, res) => {
  const userId = signedInUser(req);
  const { upload_key, file_name, size_bytes } = req.body;
  const project = await diffioFor(userId).projects.create(
    { file_name, size_bytes, generation: { model: "diffio-flash" } }, // starts by itself once the file lands
    { idempotencyKey: `upload-${upload_key}` } // a retried request gets the same project
  );
  db.prepare("insert or ignore into jobs (project_id, user_id, generation_id, status) values (?, ?, ?, 'processing')")
    .run(project.id, userId, project.latest_generation.id);
  // Only the upload descriptors go to the browser; the API key stays here.
  res.json({ project_id: project.id, upload: project.upload });
});

app.post("/api/uploads/:projectId/complete", async (req, res) => {
  // 404 unless it is this user's project.
  const project = await diffioFor(signedInUser(req)).projects.completeUpload(req.params.projectId);
  res.json({ status: project.status });
});

app.get("/api/uploads/:projectId", async (req, res) => {
  const userId = signedInUser(req);
  const job = db.prepare("select * from jobs where project_id = ? and user_id = ?").get(req.params.projectId, userId);
  if (!job) return res.sendStatus(404);
  if (job.status === "complete" && !(Date.parse(job.expires_at) > Date.now() + 5 * 60_000)) {
    // Media is fetched here, on read: media URLs last 6 hours.
    const media = await diffioFor(userId).generations.media(job.project_id, job.generation_id);
    [job.audio_url, job.expires_at] = [media.files.audio, media.expires_at];
    db.prepare("update jobs set audio_url = ?, expires_at = ? where project_id = ?")
      .run(job.audio_url, job.expires_at, job.project_id);
  }
  res.json({ status: job.status, error_code: job.error_code, audio_url: job.audio_url, expires_at: job.expires_at });
});

app.listen(3000);
```

## What you get

![A finished Diffio project: the project title, the restored waveform, the play control, the Restored switch and the Background amount slider](https://diffio.ai/media/recording-rescue/flash-result-mobile-stack.jpg)

Uploaded

[Uploaded (MP3)](https://diffio.ai/media/recording-rescue/original.mp3)

Restored by Diffio 4.7 Flash

[Restored by Diffio 4.7 Flash (MP3)](https://diffio.ai/media/recording-rescue/flash.mp3)

**What a user uploads and gets back: the first 60 seconds of an archival lecture, and the finished project in the Diffio app. [How this recording was restored](https://diffio.ai/recording-rescue/).**

- Each customer's projects live under their own end user: another customer's project id answers `404`.
- Files go from the browser to Diffio; your server never handles the audio.
- A restored MP3 URL for each finished episode, renewed before its 6 hours run out.

**Response of `GET /api/uploads/<project_id>`**

**JSON**

```json
{
  "status": "complete",
  "error_code": null,
  "audio_url": "https://media.diffio.io/m/v1.REDACTED/generations/ce832a32-a1ce-516a-b8bd-75457bd8517f/restored.mp3",
  "expires_at": "2026-11-13T06:33:47Z"
}
```

## API reference

- POST [Create a project](https://diffio.ai/docs/api-reference/create-project/) (`/projects`): Project, first generation and upload descriptors.
- POST [Get new upload instructions](https://diffio.ai/docs/api-reference/reopen-project-upload/) (`/projects/{project_id}/upload`): A new upload token when the old one expired.
- POST [Complete a project's upload](https://diffio.ai/docs/api-reference/complete-project-upload/) (`/projects/{project_id}/upload/complete`): Check the file now instead of waiting.
- GET [Get a playback grant](https://diffio.ai/docs/api-reference/get-generation-media/) (`/projects/{project_id}/generations/{generation_id}/media`): Fresh playback and download URLs.
- POST [Open the webhook portal](https://diffio.ai/docs/api-reference/open-webhook-portal/) (`/webhooks/portal`): Add endpoints and copy the signing secret.

## Related pages

- Previous: [Bill your users from usage](https://diffio.ai/docs/developers/guides/bill-users-from-usage/): Usage per end user → invoice
- Next: [Edit a transcript](https://diffio.ai/docs/developers/guides/edit-transcript/): Transcript → estimate → edit
