Compare commits
No commits in common. "main" and "v1.0.36" have entirely different histories.
@ -1,5 +0,0 @@
|
|||||||
{
|
|
||||||
"enabledPlugins": {
|
|
||||||
"dart-flutter@dart-flutter": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,2 +0,0 @@
|
|||||||
# Dependency freshness runs locally only (pre-commit hook); no GitHub Actions
|
|
||||||
# workflow. This marker stops the fleet installer from re-adding it.
|
|
||||||
62
.github/workflows/dependency-freshness.yml
vendored
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
name: dependency freshness
|
||||||
|
|
||||||
|
# Every dependency on its ecosystem's newest STABLE release, enforced on push
|
||||||
|
# as well as at commit time. The local pre-commit hook only sees the manifests
|
||||||
|
# in a commit and can be skipped entirely by a fresh clone that never ran
|
||||||
|
# `pre-commit install`; this runs `--all` over the whole repo.
|
||||||
|
#
|
||||||
|
# `--strict` is CI-only. Offline the gate degrades to its cached answer and
|
||||||
|
# passes, because `--no-verify` is banned locally and a hook that hard-failed
|
||||||
|
# on a flaky connection would leave no way to commit. A runner is always
|
||||||
|
# online, so here an undeterminable answer is a real failure.
|
||||||
|
#
|
||||||
|
# Expect this to go red for reasons this repo's commit did not cause: an
|
||||||
|
# upstream release overnight is enough. That is the chosen behaviour -- the
|
||||||
|
# alternative is a gate that only notices staleness when someone remembers to
|
||||||
|
# look.
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
dependency-freshness:
|
||||||
|
name: dependencies on newest stable
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# The gate lives in the shared utils repo so every repo resolves the
|
||||||
|
# same "latest stable" the same way. Checking it out beats vendoring a
|
||||||
|
# copy, which is exactly how a gate and its survey start disagreeing.
|
||||||
|
- name: Check out the shared gate
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
repository: kuhyx/utils
|
||||||
|
path: .utils
|
||||||
|
|
||||||
|
# "3.x", never a pinned minor: the Python target IS the interpreter the
|
||||||
|
# gate runs under (registries/toolchain.python_installed), so a runner
|
||||||
|
# held a release behind this machine reports a repo's `requires-python`
|
||||||
|
# as excluding "latest" while the same check passes locally. flax-docs-mcp
|
||||||
|
# hit exactly that -- `>=3.14` green here, red on a 3.13 runner.
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: "3.x"
|
||||||
|
|
||||||
|
- name: Install the gate's two runtime dependencies
|
||||||
|
run: python -m pip install --upgrade pyyaml packaging
|
||||||
|
|
||||||
|
- name: Cache registry lookups
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ~/.cache/dep-freshness
|
||||||
|
key: dep-freshness-${{ hashFiles('**/pubspec.yaml', '**/pyproject.toml',
|
||||||
|
'**/requirements*.txt', '**/package.json', '**/Cargo.toml', '**/go.mod') }}
|
||||||
|
restore-keys: dep-freshness-
|
||||||
|
|
||||||
|
- name: Every dependency is on newest stable
|
||||||
|
run: bash .utils/scripts/check_dependency_freshness.sh --all --strict
|
||||||
6
.github/workflows/release-apk.yml
vendored
@ -47,7 +47,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: subosito/flutter-action@v2
|
- uses: subosito/flutter-action@v2
|
||||||
with:
|
with:
|
||||||
flutter-version: 3.50.1
|
flutter-version: 3.47.4
|
||||||
channel: stable
|
channel: stable
|
||||||
cache: true
|
cache: true
|
||||||
|
|
||||||
@ -110,9 +110,7 @@ jobs:
|
|||||||
flutter build apk --release \
|
flutter build apk --release \
|
||||||
--target-platform android-arm64 \
|
--target-platform android-arm64 \
|
||||||
--build-name="${{ steps.ver.outputs.semver }}" \
|
--build-name="${{ steps.ver.outputs.semver }}" \
|
||||||
--build-number="${{ steps.vc.outputs.code }}" \
|
--build-number="${{ steps.vc.outputs.code }}"
|
||||||
--dart-define=APP_BUILD="${{ steps.vc.outputs.code }}" \
|
|
||||||
--dart-define=APP_VERSION="${{ steps.ver.outputs.semver }}"
|
|
||||||
|
|
||||||
# Fail closed. `findByName("release") ?: debug` silently falls back to
|
# Fail closed. `findByName("release") ?: debug` silently falls back to
|
||||||
# the debug key if key.properties is misplaced, producing a green build
|
# the debug key if key.properties is misplaced, producing a green build
|
||||||
|
|||||||
25
.github/workflows/repo-contract.yml
vendored
@ -1,25 +0,0 @@
|
|||||||
name: repo-contract
|
|
||||||
|
|
||||||
# The local pre-commit hook can be skipped (a fresh clone has no hooks), so the
|
|
||||||
# contract is enforced on push too. Mirrors md-naming.yml.
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [main]
|
|
||||||
pull_request:
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
repo-contract:
|
|
||||||
name: repo contract
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Check out the shared gate
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
repository: kuhyx/utils
|
|
||||||
path: .utils
|
|
||||||
|
|
||||||
- name: Enforce the repo contract
|
|
||||||
run: bash .utils/scripts/check_repo_contract.sh
|
|
||||||
@ -1,11 +1,10 @@
|
|||||||
{
|
{
|
||||||
"mcpServers": {
|
"mcpServers": {
|
||||||
"todo": {
|
"todo": {
|
||||||
"type": "http",
|
"type": "stdio",
|
||||||
"url": "http://127.0.0.1:8735/mcp",
|
"command": "${HOME}/.venvs/todo-mcp/bin/python",
|
||||||
"headers": {
|
"args": ["-m", "todo_mcp._mcp"],
|
||||||
"Authorization": "Bearer ${TODO_MCP_TOKEN}"
|
"env": {}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -73,30 +73,6 @@ repos:
|
|||||||
language: system
|
language: system
|
||||||
files: \.(md|markdown)$
|
files: \.(md|markdown)$
|
||||||
|
|
||||||
- id: todo-closer
|
|
||||||
name: close Todo trailer tasks
|
|
||||||
entry: scripts/todo_hooks.sh closer
|
|
||||||
language: system
|
|
||||||
stages: [post-commit]
|
|
||||||
always_run: true
|
|
||||||
pass_filenames: false
|
|
||||||
|
|
||||||
- id: todo-import-pr-merge
|
|
||||||
name: import PR Todo sections (pull)
|
|
||||||
entry: scripts/todo_hooks.sh import-pr post-merge
|
|
||||||
language: system
|
|
||||||
stages: [post-merge]
|
|
||||||
always_run: true
|
|
||||||
pass_filenames: false
|
|
||||||
|
|
||||||
- id: todo-import-pr-rewrite
|
|
||||||
name: import PR Todo sections (pull --rebase)
|
|
||||||
entry: scripts/todo_hooks.sh import-pr post-rewrite
|
|
||||||
language: system
|
|
||||||
stages: [post-rewrite]
|
|
||||||
always_run: true
|
|
||||||
pass_filenames: false
|
|
||||||
|
|
||||||
# Every dependency on its ecosystem's newest STABLE release, exact-pinned
|
# Every dependency on its ecosystem's newest STABLE release, exact-pinned
|
||||||
# so the question is mechanically answerable at all.
|
# so the question is mechanically answerable at all.
|
||||||
#
|
#
|
||||||
@ -106,7 +82,7 @@ repos:
|
|||||||
# Runs WITHOUT --strict on purpose. Offline it degrades to the cached
|
# Runs WITHOUT --strict on purpose. Offline it degrades to the cached
|
||||||
# answer and passes with a loud banner; `--no-verify` is banned here, so
|
# answer and passes with a loud banner; `--no-verify` is banned here, so
|
||||||
# a hook that hard-failed on a flaky connection would leave no way to
|
# a hook that hard-failed on a flaky connection would leave no way to
|
||||||
# commit at all. Local only: no CI workflow runs this.
|
# commit at all. CI, always online, is the strict authority.
|
||||||
- id: dependency-freshness
|
- id: dependency-freshness
|
||||||
name: dependencies on newest stable
|
name: dependencies on newest stable
|
||||||
entry: scripts/check_dependency_freshness.sh
|
entry: scripts/check_dependency_freshness.sh
|
||||||
@ -117,9 +93,3 @@ repos:
|
|||||||
|package\.json|package-lock\.json|pnpm-lock\.yaml
|
|package\.json|package-lock\.json|pnpm-lock\.yaml
|
||||||
|Cargo\.(toml|lock)|go\.(mod|sum)
|
|Cargo\.(toml|lock)|go\.(mod|sum)
|
||||||
|\.fvmrc|\.nvmrc|\.python-version)$
|
|\.fvmrc|\.nvmrc|\.python-version)$
|
||||||
- id: repo-contract
|
|
||||||
name: repo contract (CLAUDE.md Commands + test_changed)
|
|
||||||
entry: scripts/check_repo_contract.sh
|
|
||||||
language: system
|
|
||||||
pass_filenames: false
|
|
||||||
files: ^(CLAUDE\.md|AGENTS\.md|scripts/test_changed\.sh)$|(^|/)(AndroidManifest\.xml|build\.gradle(\.kts)?|strings\.xml|pubspec\.yaml|repo-contract\.toml|[^/]+\.desktop|assets/icon/[^/]+\.png)$
|
|
||||||
|
|||||||
81
AGENTS.md
@ -43,14 +43,6 @@ and sync peer-to-peer through a GitHub repo used as dumb storage.
|
|||||||
- Release APK: `flutter build apk --release` (signs with the debug key; debug
|
- Release APK: `flutter build apk --release` (signs with the debug key; debug
|
||||||
builds are janky — always measure smoothness on a release build).
|
builds are janky — always measure smoothness on a release build).
|
||||||
- Sync smoke test (hits real GitHub, needs a token): `dart run tool/sync_smoke.dart`.
|
- Sync smoke test (hits real GitHub, needs a token): `dart run tool/sync_smoke.dart`.
|
||||||
- MCP server (`lib/mcp/`, :8735): tests `flutter test test/mcp/`, deploy `mcp/install.sh`; see `mcp/README.md`.
|
|
||||||
- run: `./run.sh` (desktop; mobile: `flutter run`)
|
|
||||||
- test: `flutter test --reporter=compact`
|
|
||||||
- test-changed: `scripts/test_changed.sh`
|
|
||||||
- lint: `flutter analyze`
|
|
||||||
- coverage: `flutter test --coverage --reporter=compact`
|
|
||||||
- coverage-gaps: `coverage-gaps coverage/lcov.info`
|
|
||||||
- deploy: `scripts/deploy.sh` (MCP service, desktop pacman package, phone release; exits non-zero unless every health check passes)
|
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
@ -59,15 +51,10 @@ Three layers under `lib/`, each single-purpose:
|
|||||||
- `data/` — domain + local storage.
|
- `data/` — domain + local storage.
|
||||||
- `note.dart`: `Note` model; `Priority` enum (low/medium/high, **default
|
- `note.dart`: `Note` model; `Priority` enum (low/medium/high, **default
|
||||||
medium**, no "none"); `Status` enum (todo/inProgress/done/abandoned).
|
medium**, no "none"); `Status` enum (todo/inProgress/done/abandoned).
|
||||||
Optional repo-task fields `repo`/`doneCheck`/`by`/`evidence`: a note
|
- `note_repository.dart`: CRDT storage over `sqlite_crdt`. Schema is at
|
||||||
with `repo` is a repo task, one without is a plain idea.
|
**version 3** with `onCreate`/`onUpgrade` migrations (v1→v2 adds the
|
||||||
- `note_repository.dart`: CRDT storage over the schemaless `crdt_sync`
|
`status` column; v2→v3 backfills legacy priority `0`→medium). Also defines
|
||||||
`LogStore`; `note_record.dart` maps a note to record fields `text`,
|
`NoteFilter` (query / priorities / statuses / created+updated date ranges,
|
||||||
`priority`, `status`, `created_at`, `updated_at` (+ `repo`, `done_check`,
|
|
||||||
`by`, `evidence`, written only when set, so an idea's record stays
|
|
||||||
v3-identical: `note_repository_sync_compat_test.dart`). The old sqlite
|
|
||||||
schema (v3) survives only in `legacy_sqlite_migration.dart`. Also defines
|
|
||||||
`NoteFilter` (query / priorities / statuses / repo / date ranges,
|
|
||||||
AND-combined), `NoteSort`, `watchNotes`/`watchCount` streams, and
|
AND-combined), `NoteSort`, `watchNotes`/`watchCount` streams, and
|
||||||
`importNotes` (safe newer-wins merge by id).
|
`importNotes` (safe newer-wins merge by id).
|
||||||
- `sync/` — GitHub-as-storage sync.
|
- `sync/` — GitHub-as-storage sync.
|
||||||
@ -81,17 +68,12 @@ Three layers under `lib/`, each single-purpose:
|
|||||||
token. `sync_settings.dart`: persisted owner/repo/token/clientId.
|
token. `sync_settings.dart`: persisted owner/repo/token/clientId.
|
||||||
- `notes_markdown.dart`: round-trippable single-file export/import format
|
- `notes_markdown.dart`: round-trippable single-file export/import format
|
||||||
(HTML-comment `<!-- @note id=… priority=… status=… … -->` markers).
|
(HTML-comment `<!-- @note id=… priority=… status=… … -->` markers).
|
||||||
- `images/` + `attachments/` — attached images and files (see "Images and other attachments" below).
|
|
||||||
- `ui/` — screens, all take an injected `NoteRepository`.
|
- `ui/` — screens, all take an injected `NoteRepository`.
|
||||||
- `capture_screen.dart`: landing screen; always-focused text box pre-filled
|
- `capture_screen.dart`: landing screen; always-focused text box pre-filled
|
||||||
with the structured template; lazy note creation on first keystroke.
|
with the structured template; lazy note creation on first keystroke.
|
||||||
- `notes_list_screen.dart`: list + search + sort + filter sheet + per-note
|
- `notes_list_screen.dart`: list + search + sort + filter sheet + per-note
|
||||||
sheet. One open note per repo (`data/repo_note.dart`). **Default view hides Done/Abandoned and shows no filter badge**
|
sheet. **Default view hides Done/Abandoned and shows no filter badge**
|
||||||
(looks unfiltered). Under 600dp wide (`kNotesGridMaxWidth`) the notes are
|
(looks unfiltered).
|
||||||
a 2-column `NotesGrid` of compact `NoteGridTile`s (title + priority/status
|
|
||||||
cues; body and dates are in the long-press sheet). The tile height is
|
|
||||||
derived so whole rows exactly fill the viewport; past one screenful it
|
|
||||||
scrolls vertically (no paging). Wider windows (desktop) keep the list.
|
|
||||||
- `settings_screen.dart`: GitHub connect/test, device-flow auth, and the
|
- `settings_screen.dart`: GitHub connect/test, device-flow auth, and the
|
||||||
Export/Import backup actions.
|
Export/Import backup actions.
|
||||||
- `main.dart`: bootstrap only (`// coverage:ignore-file`) — wires platform DB
|
- `main.dart`: bootstrap only (`// coverage:ignore-file`) — wires platform DB
|
||||||
@ -116,41 +98,11 @@ that, the stepper would fold a retired section into its neighbour on the next
|
|||||||
save. `tool/migrate_backlog.dart` converts an old export (Settings → Export →
|
save. `tool/migrate_backlog.dart` converts an old export (Settings → Export →
|
||||||
migrate → Settings → Import).
|
migrate → Settings → Import).
|
||||||
|
|
||||||
### Images and other attachments
|
|
||||||
|
|
||||||
A note never holds attachment bytes, only a line pointing at
|
|
||||||
`https://kuhy-cloud.duckdns.org/todo-images/<noteId>/<uuid>.<ext>`: an image
|
|
||||||
as ``, any other file as `[name](…)` (`lib/images/attachment_ref.dart`
|
|
||||||
owns the path, `attachment_links.dart` the links), so sync and older builds are
|
|
||||||
untouched. Anything picked or dropped goes through `AttachmentIngest`: a
|
|
||||||
JPEG/PNG/GIF/WebP/BMP/TIFF of at most 64 MB is re-encoded (≤2560 px, JPEG q85,
|
|
||||||
EXIF stripped after applying its rotation — `image_processing.dart`); every
|
|
||||||
other file, of any size, is kept byte-for-byte. There is deliberately **no
|
|
||||||
size cap**, so nothing may hold a file in memory: uploads and downloads stream
|
|
||||||
(`DufsImageClient`), the desktop page POSTs the browser's own Blob with
|
|
||||||
`fetch` (`file_post_web.dart`), and writes land in a `.tmp` renamed when whole.
|
|
||||||
`ImageCacheStore` keeps every linked attachment on-device (offline) plus a
|
|
||||||
`.pending` marker per queued upload, and `reconcile` uploads, prefetches and
|
|
||||||
evicts (never an empty ref set, never within 10 min; stale `.tmp`s too).
|
|
||||||
Android talks to dufs directly with the `todo` login's password (Settings →
|
|
||||||
Cloud images) and opens files with `open_file`; the desktop page never talks
|
|
||||||
to dufs — the wrapper's `/images/*` routes do, with
|
|
||||||
`~/.config/dufs/logins/todo.env`, created by
|
|
||||||
`~/src/dufs-cloud/scripts/add_dufs_login.sh todo /todo-images rw`. The wrapper
|
|
||||||
serves attachments from the same origin as the notes and the GitHub token, so
|
|
||||||
only script-free types (raster images, PDF, plain text, audio, video) are shown
|
|
||||||
inline, always `nosniff`; everything else is a download
|
|
||||||
(`wrapper_attachment_serving.dart`). Attachment routes run concurrently, the
|
|
||||||
rest of the wrapper one request at a time. BACKLOG.md rewrites links to
|
|
||||||
`~/data/cloud/todo-images/…` so an agent can open them.
|
|
||||||
|
|
||||||
## Testing
|
## Testing
|
||||||
|
|
||||||
- **The suite must stay quick and fully green.** It is currently **604 tests at
|
- **The suite must stay quick and fully green.** It is currently **313 tests at
|
||||||
100% line coverage** (3305 lines), ~40s on this machine with
|
100% line coverage** (2005 lines), running well under a minute on this
|
||||||
`--concurrency=3` (unbounded concurrency under `capped.sh`'s 4 GiB gets its
|
machine. Don't regress either.
|
||||||
test processes SIGTERMed while the wrapper still exits 0 — check the last
|
|
||||||
line says "All tests passed"). Don't regress either.
|
|
||||||
(The "~5s" figure this file used to quote had drifted well before the port
|
(The "~5s" figure this file used to quote had drifted well before the port
|
||||||
guard was added; measure before quoting a new one.)
|
guard was added; measure before quoting a new one.)
|
||||||
- Widget tests use `test/fake_note_repository.dart` — a `FakeNoteRepository`
|
- Widget tests use `test/fake_note_repository.dart` — a `FakeNoteRepository`
|
||||||
@ -218,18 +170,3 @@ about *this repo*:
|
|||||||
|
|
||||||
Sourced from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md)
|
Sourced from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md)
|
||||||
via `~/.claude/CLAUDE.md`'s Flutter AI tooling setup. Re-fetch periodically.
|
via `~/.claude/CLAUDE.md`'s Flutter AI tooling setup. Re-fetch periodically.
|
||||||
|
|
||||||
## Driving the app on the phone
|
|
||||||
|
|
||||||
Tap and type by label, never by coordinate, with `android_ui` from
|
|
||||||
`~/src/testsAndMisc` (not copied here):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd ~/src/testsAndMisc && .venv/bin/python -m python_pkg.android_ui \
|
|
||||||
-s 23181JEGR08034 --display self dump
|
|
||||||
```
|
|
||||||
|
|
||||||
The same driver is the `android-ui` MCP server
|
|
||||||
(`.venv/bin/python -m python_pkg.android_ui.mcp_server`, in that repo's
|
|
||||||
`.mcp.json`). Tools and error contract:
|
|
||||||
`~/src/testsAndMisc/python_pkg/android_ui/README.md`.
|
|
||||||
|
|||||||
37
README.md
@ -15,40 +15,3 @@ A few resources to get you started if this is your first Flutter project:
|
|||||||
For help getting started with Flutter development, view the
|
For help getting started with Flutter development, view the
|
||||||
[online documentation](https://docs.flutter.dev/), which offers tutorials,
|
[online documentation](https://docs.flutter.dev/), which offers tutorials,
|
||||||
samples, guidance on mobile development, and a full API reference.
|
samples, guidance on mobile development, and a full API reference.
|
||||||
|
|
||||||
## Headless note CLI
|
|
||||||
|
|
||||||
`bin/todo_note.dart` adds, lists, reads and deletes notes from the PC without
|
|
||||||
the app, as one more sync node (own `node_id` and CRDT log under
|
|
||||||
`$XDG_DATA_HOME/todo-cli`, or `~/.local/share/todo-cli`). It needs the desktop
|
|
||||||
Firebase session at `~/.config/todo/firebase_auth.json` (seed it with
|
|
||||||
`python3 ~/src/utils/crdt-sync/tool/seed_session.py --app todo`).
|
|
||||||
|
|
||||||
```sh
|
|
||||||
dart run bin/todo_note.dart --text "Title
|
|
||||||
|
|
||||||
body" --priority high --status in_progress # prints the new note id
|
|
||||||
echo "Title" | dart run bin/todo_note.dart # text from stdin
|
|
||||||
dart run bin/todo_note.dart --list # id, priority, status, title
|
|
||||||
dart run bin/todo_note.dart --get <id> # full note
|
|
||||||
dart run bin/todo_note.dart --delete <id>
|
|
||||||
```
|
|
||||||
|
|
||||||
`--list` and `--get` never push; `--data-dir <dir>` selects a throwaway node.
|
|
||||||
Exit codes: 0 ok, 1 sync/auth failure or note not found, 2 bad arguments.
|
|
||||||
All logic is in `lib/cli/` (tested in `test/cli/`); `--help` lists every flag.
|
|
||||||
|
|
||||||
## Driving the app on the phone
|
|
||||||
|
|
||||||
Tap and type by label, never by coordinate, with `android_ui` from
|
|
||||||
`~/src/testsAndMisc` (not copied here):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd ~/src/testsAndMisc && .venv/bin/python -m python_pkg.android_ui \
|
|
||||||
-s 23181JEGR08034 --display self dump
|
|
||||||
```
|
|
||||||
|
|
||||||
The same driver is the `android-ui` MCP server
|
|
||||||
(`.venv/bin/python -m python_pkg.android_ui.mcp_server`, in that repo's
|
|
||||||
`.mcp.json`). Tools and error contract:
|
|
||||||
`~/src/testsAndMisc/python_pkg/android_ui/README.md`.
|
|
||||||
|
|||||||
91
TODO-design-audit.md
Normal file
@ -0,0 +1,91 @@
|
|||||||
|
# Design audit — todo
|
||||||
|
|
||||||
|
Generated against safe-design-rules (anthonyhobday.com/sideprojects/saferules).
|
||||||
|
Report only — nothing in this repo was changed by the audit itself.
|
||||||
|
|
||||||
|
## Flutter app (lib/)
|
||||||
|
|
||||||
|
Theme entry point: `lib/main.dart:36-39` — a single inline `ThemeData` with
|
||||||
|
`ColorScheme.fromSeed(seedColor: Colors.deepPurple)` and `useMaterial3: true`.
|
||||||
|
No dedicated theme file, no `darkTheme`, no `textTheme`/component-theme
|
||||||
|
overrides, no custom shadows or corner radii anywhere in `lib/` (confirmed by
|
||||||
|
grepping for `BoxShadow`, `elevation`, `BorderRadius`, `Card(` — zero hits
|
||||||
|
outside framework defaults). This means almost every token rule is satisfied
|
||||||
|
*by deferring to Material 3's generated palette/type scale*, which is itself a
|
||||||
|
coherent, deliberately-designed system — that counts as Pass, not as an
|
||||||
|
absence-of-system finding (contrast the web/Tkinter case where hardcoded
|
||||||
|
per-file values have no source of truth at all).
|
||||||
|
|
||||||
|
### Violations
|
||||||
|
|
||||||
|
- **Rule 4 (everything deliberate) / color consistency** — `lib/ui/settings_screen.dart:410` —
|
||||||
|
`Text(_error!, style: const TextStyle(color: Colors.red))` hardcodes a raw
|
||||||
|
`Colors.red` instead of the theme's error color. Every other error-state
|
||||||
|
text in the app uses `theme.colorScheme.error`
|
||||||
|
(`lib/ui/capture_screen.dart:522`, `lib/ui/notes_list_screen.dart:375`) —
|
||||||
|
this is the one place that breaks the pattern → change to
|
||||||
|
`Theme.of(context).colorScheme.error`.
|
||||||
|
- **Rule 11 (mathematically related measurements)** — the app's spacing is
|
||||||
|
overwhelmingly on a 4px scale (4/8/12/16/20/24/96 all appear repeatedly),
|
||||||
|
but a few values break it: `SizedBox(height: 6)` at
|
||||||
|
`lib/ui/notes_list_screen.dart:411,574,646`; `SizedBox(height: 10)` at
|
||||||
|
`lib/ui/markdown_view.dart:29`; `EdgeInsets.only(top: 8, bottom: 2)` /
|
||||||
|
`EdgeInsets.only(bottom: 4)` / `EdgeInsets.only(left: 4, top: 2)` at
|
||||||
|
`lib/ui/markdown_view.dart:35,49,78` (the `2`s). Round these to the nearest
|
||||||
|
4px step (6→8, 10→8 or 12, 2→4) for consistency.
|
||||||
|
- **Rule 21 (line length ~70 chars)** — `lib/ui/markdown_view.dart` (the
|
||||||
|
rendered-note view) and the raw-mode `TextField` in
|
||||||
|
`lib/ui/note_editor.dart:520-535` have no max-width constraint; both sit
|
||||||
|
directly in a `SingleChildScrollView`/`Expanded` that fills the available
|
||||||
|
width. Per this repo's own `CLAUDE.md`, the desktop build is a Chrome
|
||||||
|
`--app` window (potentially 4K), so body text lines run the full window
|
||||||
|
width, far past the 60-80 char readable range. Constrain text columns with
|
||||||
|
a `ConstrainedBox(maxWidth: ~640)` (or similar) centered in the available
|
||||||
|
space on wide viewports; mobile widths are already narrow enough to be fine.
|
||||||
|
|
||||||
|
### Pass (defers to Material 3 defaults from `main.dart:36-39`, or otherwise verified)
|
||||||
|
|
||||||
|
- **Rule 1** (near-black/near-white) — M3's generated tonal palette, not pure black/white.
|
||||||
|
- **Rule 2** (saturate neutrals) — M3's seed-derived neutrals carry the seed hue.
|
||||||
|
- **Rule 3** (high contrast for important elements) — `FilledButton`/`IconButton` get M3's on-primary contrast automatically.
|
||||||
|
- **Rule 6** (letter-spacing/line-height by size) — M3 `TextTheme` scale.
|
||||||
|
- **Rule 7** (container border contrast) — `OutlineInputBorder()` used throughout (e.g. `lib/ui/settings_screen.dart:244,252,268,278`) resolves via theme, no custom borders.
|
||||||
|
- **Rule 8** (align with something else) — screen-level body padding is a consistent `EdgeInsets.all(16)` across `lib/ui/capture_screen.dart:451`, `lib/ui/note_detail_screen.dart:67`, `lib/ui/settings_screen.dart:221`.
|
||||||
|
- **Rule 9** (distinct brightness per palette color) — M3 tonal palette assigns each role a distinct tone.
|
||||||
|
- **Rule 10** (warm OR cool, not both) — single seed color (`Colors.deepPurple`) drives the whole palette.
|
||||||
|
- **Rule 14** (space between high-contrast points) — standard Material component spacing, no bounding-box vs. visual-edge mismatches found.
|
||||||
|
- **Rule 17** (simple on complex) — all surfaces are plain `Scaffold`/`ListView` backgrounds, no background imagery/texture.
|
||||||
|
- **Rule 19** (outer padding ≥ inner padding) — e.g. `lib/ui/settings_screen.dart:318-331` (Export/Import button row: 12px gap between buttons) sits inside the screen's 16px outer padding; same pattern in `capture_screen.dart`'s priority/status row (12px gap inside 16px body padding).
|
||||||
|
- **Rule 20** (body text ≥16px) — `bodyLarge` (16px, M3 default) is used for all primary editable/read text (`lib/ui/note_editor.dart:528`, `lib/ui/markdown_view.dart:82-95`); `bodySmall` (12px) is reserved for secondary captions/timestamps only (`lib/ui/capture_screen.dart:511`, `lib/ui/settings_screen.dart:231`), which is the sanctioned M3 caption use, not body text.
|
||||||
|
- **Rule 22** (button padding horizontal = 2x vertical) — no custom `ButtonStyle` padding overrides found; `FilledButton`/`OutlinedButton` use M3 defaults, which follow this ratio.
|
||||||
|
- **Rule 23** (two typefaces max) — single default Material/Roboto family; `pubspec.yaml` declares no custom fonts, no `google_fonts` dependency.
|
||||||
|
- **Rule 25** (avoid adjacent hard divides) — the one `Divider` in the list (`lib/ui/notes_list_screen.dart:232`, `height: 1`) separates list rows only, no stacked borders; the settings-screen `Divider()` (`lib/ui/settings_screen.dart:308`) has 8-24px spacing on both sides, not adjacent to another edge.
|
||||||
|
- **Rule 27** (don't mix depth techniques) — no custom shadow/elevation overrides anywhere in `lib/`; consistent flat M3 default depth throughout.
|
||||||
|
- **Rule 28** (icon contrast vs. text) — icons use the default M3 `IconTheme` (tied to `onSurfaceVariant`-class roles), no hardcoded full-contrast icon colors placed next to text were found.
|
||||||
|
|
||||||
|
### Not applicable
|
||||||
|
|
||||||
|
- **Rule 5** (optical alignment) — no custom-drawn shapes/icons with off-center mass; all icons are stock `Icons.*` glyphs, whose optical centering Material already handles.
|
||||||
|
- **Rule 12** (order by visual weight) — standard `AppBar` + list/form layouts, not a composition with deliberately varied visual weights to order.
|
||||||
|
- **Rule 13** (12-column grid) — single-column mobile/narrow-desktop layouts throughout; no multi-column grid exists to check.
|
||||||
|
- **Rule 15** (closer elements lighter, light+dark) — no custom z-stacked/elevated surfaces with tuned lightness, and no `darkTheme` exists to check the dark-mode half of this rule.
|
||||||
|
- **Rule 16** (shadow blur ≈ 2x distance) — zero custom `BoxShadow` usage in the codebase (confirmed by grep); nothing to check.
|
||||||
|
- **Rule 18** (container brightness limits, light/dark) — no custom nested-container brightness steps defined; M3 default surface tones apply, and there is no dark theme to check the 12%-dark-interface half.
|
||||||
|
- **Rule 24** (nest corners properly) — no custom corner radii anywhere; all components use M3 default shapes.
|
||||||
|
- **Rule 26** (no shadows in dark interfaces) — no dark theme exists, and no shadows exist in light mode either, so this rule has nothing to trigger on.
|
||||||
|
|
||||||
|
### Notes
|
||||||
|
|
||||||
|
- No dedicated theme file exists (`ThemeData` is inline in `lib/main.dart`,
|
||||||
|
32 `.dart` files total) — this is fine at the current size but worth
|
||||||
|
extracting to `lib/ui/theme.dart` if the theme grows beyond the current
|
||||||
|
3-line `ThemeData(...)`.
|
||||||
|
- No `darkTheme` is provided. The 28 rules don't mandate one, so its absence
|
||||||
|
is not a violation — but if a dark theme is added later, re-check rules 15,
|
||||||
|
18, and 26 (shadow/lightness/brightness-limit rules only bite once a dark
|
||||||
|
surface exists).
|
||||||
|
- The single hardcoded-color violation (`Colors.red`) is also the app's only
|
||||||
|
spot where a raw `Colors.*` constant appears outside `main.dart`'s seed —
|
||||||
|
fixing it removes the last non-theme-derived color reference in the app.
|
||||||
|
|
||||||
|
REMOVE ME AFTER FINISH
|
||||||
@ -4,7 +4,7 @@
|
|||||||
lose all network access. -->
|
lose all network access. -->
|
||||||
<uses-permission android:name="android.permission.INTERNET"/>
|
<uses-permission android:name="android.permission.INTERNET"/>
|
||||||
<application
|
<application
|
||||||
android:label="Todo"
|
android:label="todo"
|
||||||
android:name="${applicationName}"
|
android:name="${applicationName}"
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_launcher"
|
||||||
android:allowBackup="true"
|
android:allowBackup="true"
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 3.2 KiB After Width: | Height: | Size: 3.1 KiB |
|
Before Width: | Height: | Size: 3.1 KiB After Width: | Height: | Size: 3.0 KiB |
|
Before Width: | Height: | Size: 2.1 KiB After Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 2.0 KiB After Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 4.2 KiB After Width: | Height: | Size: 4.0 KiB |
|
Before Width: | Height: | Size: 3.9 KiB After Width: | Height: | Size: 3.7 KiB |
|
Before Width: | Height: | Size: 6.1 KiB After Width: | Height: | Size: 5.8 KiB |
|
Before Width: | Height: | Size: 5.5 KiB After Width: | Height: | Size: 5.3 KiB |
|
Before Width: | Height: | Size: 8.2 KiB After Width: | Height: | Size: 7.9 KiB |
|
Before Width: | Height: | Size: 7.3 KiB After Width: | Height: | Size: 7.1 KiB |
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 815 B After Width: | Height: | Size: 778 B |
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 2.4 KiB After Width: | Height: | Size: 2.3 KiB |
|
Before Width: | Height: | Size: 2.7 KiB After Width: | Height: | Size: 2.7 KiB |
@ -1,7 +1,4 @@
|
|||||||
org.gradle.jvmargs=-Xmx2G -XX:MaxMetaspaceSize=1G -XX:ReservedCodeCacheSize=256m -XX:+UseSerialGC -XX:TieredStopAtLevel=1
|
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
|
||||||
org.gradle.caching=true
|
|
||||||
org.gradle.parallel=true
|
|
||||||
kotlin.compiler.execution.strategy=in-process
|
|
||||||
android.useAndroidX=true
|
android.useAndroidX=true
|
||||||
# This newDsl flag was added by the Flutter template
|
# This newDsl flag was added by the Flutter template
|
||||||
android.newDsl=false
|
android.newDsl=false
|
||||||
|
|||||||
@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
|
|||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.1-all.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-all.zip
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 16 KiB |
@ -1,6 +1,6 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
||||||
<rect width="1024" height="1024" fill="#211D1B"/>
|
<rect width="1024" height="1024" fill="#211D1B"/>
|
||||||
<g fill="none" stroke="#B8862E" stroke-width="66.2544" stroke-linecap="round" stroke-linejoin="round" transform="translate(-44.4008,-35.7071) scale(1.08672)">
|
<g fill="none" stroke="#B8862E" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,8)">
|
||||||
<path d="M 272 372 L 346 446 L 478 314"/>
|
<path d="M 272 372 L 346 446 L 478 314"/>
|
||||||
<path d="M 594 400 L 752 400"/>
|
<path d="M 594 400 L 752 400"/>
|
||||||
<path d="M 272 620 L 346 694 L 478 562"/>
|
<path d="M 272 620 L 346 694 L 478 562"/>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 483 B After Width: | Height: | Size: 449 B |
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 16 KiB |
@ -1,5 +1,5 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
||||||
<g fill="none" stroke="#B8862E" stroke-width="66.2544" stroke-linecap="round" stroke-linejoin="round" transform="translate(-44.4008,-35.7071) scale(1.08672)">
|
<g fill="none" stroke="#B8862E" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,8)">
|
||||||
<path d="M 272 372 L 346 446 L 478 314"/>
|
<path d="M 272 372 L 346 446 L 478 314"/>
|
||||||
<path d="M 594 400 L 752 400"/>
|
<path d="M 594 400 L 752 400"/>
|
||||||
<path d="M 272 620 L 346 694 L 478 562"/>
|
<path d="M 272 620 L 346 694 L 478 562"/>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 431 B After Width: | Height: | Size: 397 B |
|
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 14 KiB |
@ -1,5 +1,5 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
|
||||||
<g fill="none" stroke="#FFFFFF" stroke-width="66.2544" stroke-linecap="round" stroke-linejoin="round" transform="translate(-44.4008,-35.7071) scale(1.08672)">
|
<g fill="none" stroke="#FFFFFF" stroke-width="72" stroke-linecap="round" stroke-linejoin="round" transform="translate(0,8)">
|
||||||
<path d="M 272 372 L 346 446 L 478 314"/>
|
<path d="M 272 372 L 346 446 L 478 314"/>
|
||||||
<path d="M 594 400 L 752 400"/>
|
<path d="M 594 400 L 752 400"/>
|
||||||
<path d="M 272 620 L 346 694 L 478 562"/>
|
<path d="M 272 620 L 346 694 L 478 562"/>
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 431 B After Width: | Height: | Size: 397 B |
@ -1,16 +0,0 @@
|
|||||||
// One-time: one open note per repo, holding all of that repo's todos.
|
|
||||||
//
|
|
||||||
// dart run bin/merge_repo_notes.dart # dry run, prints the map
|
|
||||||
// dart run bin/merge_repo_notes.dart --apply # does it and pushes
|
|
||||||
import 'dart:io';
|
|
||||||
|
|
||||||
import 'package:todo/cli/merge_repo_notes.dart';
|
|
||||||
|
|
||||||
Future<void> main(List<String> argv) async {
|
|
||||||
exitCode = await runMergeRepoNotes(
|
|
||||||
argv,
|
|
||||||
env: Platform.environment,
|
|
||||||
out: stdout,
|
|
||||||
err: stderr,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,21 +0,0 @@
|
|||||||
// Headless note CLI: add, list, search, get, close or delete notes from the PC.
|
|
||||||
//
|
|
||||||
// dart run bin/todo_note.dart --text "Title" --repo kuhyx/todo --by claude
|
|
||||||
// dart run bin/todo_note.dart --list --repo kuhyx/todo
|
|
||||||
// dart run bin/todo_note.dart --close <id> --evidence "<sha> exit 0"
|
|
||||||
//
|
|
||||||
// See `kUsage` in lib/cli/cli_args.dart for every flag. All behaviour lives
|
|
||||||
// in lib/cli/cli_runner.dart, where the tests reach it.
|
|
||||||
import 'dart:io';
|
|
||||||
|
|
||||||
import 'package:todo/cli/cli_runner.dart';
|
|
||||||
|
|
||||||
Future<void> main(List<String> argv) async {
|
|
||||||
exitCode = await runCli(
|
|
||||||
argv,
|
|
||||||
env: Platform.environment,
|
|
||||||
out: stdout,
|
|
||||||
err: stderr,
|
|
||||||
readStdin: () => readInput(stdin, hasTerminal: stdin.hasTerminal),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# todo's own additions to the fleet-wide allowlist
|
|
||||||
# (~/src/utils/dependency-freshness.allowlist.yaml).
|
|
||||||
|
|
||||||
exceptions: []
|
|
||||||
|
Before Width: | Height: | Size: 1.9 KiB After Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 309 B After Width: | Height: | Size: 308 B |
|
Before Width: | Height: | Size: 439 B After Width: | Height: | Size: 470 B |
|
Before Width: | Height: | Size: 3.7 KiB After Width: | Height: | Size: 3.4 KiB |
|
Before Width: | Height: | Size: 579 B After Width: | Height: | Size: 574 B |
|
Before Width: | Height: | Size: 778 B After Width: | Height: | Size: 788 B |
|
Before Width: | Height: | Size: 7.4 KiB After Width: | Height: | Size: 6.9 KiB |
|
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 1023 B |
@ -83,7 +83,7 @@ install_desktop_entry() {
|
|||||||
cat > "$DESKTOP_DIR/$ICON_NAME.desktop" <<EOF
|
cat > "$DESKTOP_DIR/$ICON_NAME.desktop" <<EOF
|
||||||
[Desktop Entry]
|
[Desktop Entry]
|
||||||
Type=Application
|
Type=Application
|
||||||
Name=Todo
|
Name=todo
|
||||||
Comment=Offline-first, CRDT-synced notes
|
Comment=Offline-first, CRDT-synced notes
|
||||||
Exec=$LAUNCH_CMD
|
Exec=$LAUNCH_CMD
|
||||||
Icon=$ICON_NAME
|
Icon=$ICON_NAME
|
||||||
|
|||||||
@ -29,10 +29,8 @@ echo "==> Compiling the desktop wrapper..."
|
|||||||
# `dart build cli`, not `dart compile exe`: the package pulls in dependencies
|
# `dart build cli`, not `dart compile exe`: the package pulls in dependencies
|
||||||
# with native build hooks (sqlite3, objective_c), which `dart compile` refuses
|
# with native build hooks (sqlite3, objective_c), which `dart compile` refuses
|
||||||
# to handle even though the wrapper itself uses none of them.
|
# to handle even though the wrapper itself uses none of them.
|
||||||
# --target is required since bin/ also holds the todo_note CLI: with two
|
|
||||||
# entry points `dart build cli` refuses to guess and the install aborts.
|
|
||||||
rm -rf "$SCRIPT_DIR/build/cli"
|
rm -rf "$SCRIPT_DIR/build/cli"
|
||||||
dart build cli -t "$SCRIPT_DIR/bin/todo_desktop.dart" -o "$SCRIPT_DIR/build/cli"
|
dart build cli -o "$SCRIPT_DIR/build/cli"
|
||||||
|
|
||||||
echo "==> Generating PKGBUILD..."
|
echo "==> Generating PKGBUILD..."
|
||||||
# pkgname is 'todo-flutter', NOT 'todo': the AUR already ships an unrelated
|
# pkgname is 'todo-flutter', NOT 'todo': the AUR already ships an unrelated
|
||||||
|
|||||||
@ -1,6 +0,0 @@
|
|||||||
/// `postFile` for the current platform: the browser's own `fetch` on the
|
|
||||||
/// desktop web build, so a picked file streams from disk to the wrapper
|
|
||||||
/// without ever becoming a Dart byte list.
|
|
||||||
library;
|
|
||||||
|
|
||||||
export 'file_post_io.dart' if (dart.library.js_interop) 'file_post_web.dart';
|
|
||||||
@ -1,9 +0,0 @@
|
|||||||
/// Off the web nothing posts files to the wrapper: Android stores them
|
|
||||||
/// itself.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:todo/attachments/image_store_api.dart';
|
|
||||||
|
|
||||||
/// Always throws; only the desktop page posts files.
|
|
||||||
Future<({int status, String body})> postFile(Uri url, XFile file) =>
|
|
||||||
throw UnsupportedError('Only the desktop page posts files');
|
|
||||||
@ -1,23 +0,0 @@
|
|||||||
/// POSTs a picked or dropped file to the desktop wrapper with `fetch`.
|
|
||||||
///
|
|
||||||
/// `package:http`'s browser client buffers a request body whole, and
|
|
||||||
/// `XFile.readAsBytes` copies the file into Dart: either would put a
|
|
||||||
/// multi-gigabyte attachment in the page's memory. Handing the file's own
|
|
||||||
/// Blob to `fetch` lets the browser stream it from disk instead.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'dart:js_interop';
|
|
||||||
|
|
||||||
import 'package:todo/attachments/image_store_api.dart';
|
|
||||||
import 'package:web/web.dart' as web;
|
|
||||||
|
|
||||||
/// POSTs [file] to [url]. [file]'s path is the object URL that file_selector
|
|
||||||
/// or the drop listener created for it.
|
|
||||||
Future<({int status, String body})> postFile(Uri url, XFile file) async {
|
|
||||||
final source = await web.window.fetch(file.path.toJS).toDart;
|
|
||||||
final blob = await source.blob().toDart;
|
|
||||||
final response = await web.window
|
|
||||||
.fetch(url.toString().toJS, web.RequestInit(method: 'POST', body: blob))
|
|
||||||
.toDart;
|
|
||||||
return (status: response.status, body: (await response.text().toDart).toDart);
|
|
||||||
}
|
|
||||||
@ -1,56 +0,0 @@
|
|||||||
/// The phone's copy of the `todo` dufs login password, in the OS keystore.
|
|
||||||
///
|
|
||||||
/// Created on the PC by `add_dufs_login.sh todo /todo-images rw` and pasted
|
|
||||||
/// into Settings → Cloud images. The desktop never uses this: its wrapper
|
|
||||||
/// reads `~/.config/dufs/logins/todo.env` instead.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
|
||||||
|
|
||||||
import 'package:todo/images/dufs_image_client.dart';
|
|
||||||
|
|
||||||
/// The login name `add_dufs_login.sh` was run with.
|
|
||||||
const kDufsImagesUser = 'todo';
|
|
||||||
|
|
||||||
/// Reads and writes the password; failures read as "no password".
|
|
||||||
class ImagePasswordStore {
|
|
||||||
/// Creates a store over [storage] (injectable for tests).
|
|
||||||
const ImagePasswordStore({FlutterSecureStorage? storage})
|
|
||||||
: _storage = storage ?? const FlutterSecureStorage();
|
|
||||||
|
|
||||||
final FlutterSecureStorage _storage;
|
|
||||||
|
|
||||||
static const _key = 'dufsImagesPassword';
|
|
||||||
|
|
||||||
/// The saved password, or '' when none is set or the keystore is
|
|
||||||
/// unavailable.
|
|
||||||
Future<String> read() async {
|
|
||||||
try {
|
|
||||||
return await _storage.read(key: _key) ?? '';
|
|
||||||
} on Exception {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Saves [password] (an empty one deletes it); false if the keystore is
|
|
||||||
/// unavailable.
|
|
||||||
Future<bool> write(String password) async {
|
|
||||||
try {
|
|
||||||
if (password.isEmpty) {
|
|
||||||
await _storage.delete(key: _key);
|
|
||||||
} else {
|
|
||||||
await _storage.write(key: _key, value: password);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
} on Exception {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The full login, or null when no password is saved.
|
|
||||||
Future<DufsLogin?> login() async {
|
|
||||||
final password = await read();
|
|
||||||
if (password.isEmpty) return null;
|
|
||||||
return DufsLogin(user: kDufsImagesUser, password: password);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,7 +0,0 @@
|
|||||||
/// `openImageStore()` for the current platform: app storage + direct dufs on
|
|
||||||
/// Android, the local wrapper's `/images/*` routes on the desktop web build.
|
|
||||||
library;
|
|
||||||
|
|
||||||
export 'image_store_api.dart';
|
|
||||||
export 'image_store_io.dart'
|
|
||||||
if (dart.library.js_interop) 'image_store_web.dart';
|
|
||||||
@ -1,133 +0,0 @@
|
|||||||
/// What the UI asks of attachments (images and any other file),
|
|
||||||
/// independent of platform.
|
|
||||||
///
|
|
||||||
/// Android keeps attachments itself (an `ImageCacheStore` in app storage,
|
|
||||||
/// talking to dufs directly); the desktop web page delegates everything to
|
|
||||||
/// the local wrapper's `/images/*` routes. Both implement [ImageStore],
|
|
||||||
/// picked by the conditional export in `image_store.dart`.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:file_selector/file_selector.dart' show XFile;
|
|
||||||
import 'package:flutter/foundation.dart';
|
|
||||||
|
|
||||||
import 'package:todo/images/attachment_links.dart';
|
|
||||||
import 'package:todo/images/attachment_ref.dart';
|
|
||||||
|
|
||||||
export 'package:file_selector/file_selector.dart' show XFile;
|
|
||||||
|
|
||||||
/// Where to draw an image from right now.
|
|
||||||
sealed class ImageSource {
|
|
||||||
const ImageSource();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A file on this device.
|
|
||||||
final class LocalImageSource extends ImageSource {
|
|
||||||
/// Creates a source for the file at [path].
|
|
||||||
const LocalImageSource(this.path);
|
|
||||||
|
|
||||||
/// Absolute path of the cached JPEG.
|
|
||||||
final String path;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A same-origin URL served by the desktop wrapper.
|
|
||||||
final class NetworkImageSource extends ImageSource {
|
|
||||||
/// Creates a source for [url].
|
|
||||||
const NetworkImageSource(this.url);
|
|
||||||
|
|
||||||
/// The wrapper URL, e.g. `http://localhost:8730/images/<noteId>/<uuid>.jpg`.
|
|
||||||
final String url;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Not on this device yet (it downloads on the next reconcile).
|
|
||||||
final class MissingImageSource extends ImageSource {
|
|
||||||
/// The one instance.
|
|
||||||
const MissingImageSource();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Summary for the settings screen.
|
|
||||||
class ImageStoreStatus {
|
|
||||||
/// Creates a status.
|
|
||||||
const ImageStoreStatus({required this.configured, required this.pending});
|
|
||||||
|
|
||||||
/// Whether a dufs login is available to this device.
|
|
||||||
final bool configured;
|
|
||||||
|
|
||||||
/// Images waiting to upload.
|
|
||||||
final int pending;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Thrown by [ImageStore.attach] when the image could not be stored at all.
|
|
||||||
class ImageStoreException implements Exception {
|
|
||||||
/// Creates an exception carrying [message].
|
|
||||||
const ImageStoreException(this.message);
|
|
||||||
|
|
||||||
/// What went wrong, shown to the user.
|
|
||||||
final String message;
|
|
||||||
|
|
||||||
@override
|
|
||||||
String toString() => message;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Stores, shows and syncs the attachments notes link to. Notifies when one
|
|
||||||
/// becomes available or changes state, so embeds can redraw.
|
|
||||||
abstract class ImageStore extends ChangeNotifier {
|
|
||||||
/// Stores [bytes] (any image format) for [noteId] and queues the upload.
|
|
||||||
///
|
|
||||||
/// Returns the new ref, or null when [bytes] is not an image. Throws
|
|
||||||
/// [ImageStoreException] when it cannot be stored.
|
|
||||||
Future<AttachmentRef?> attach(String noteId, Uint8List bytes);
|
|
||||||
|
|
||||||
/// Stores the picked or dropped [file] for [noteId] — re-encoded when it is
|
|
||||||
/// an image, byte-for-byte otherwise, whatever its size — and queues the
|
|
||||||
/// upload. Throws [ImageStoreException] when it cannot be stored.
|
|
||||||
Future<Attachment> attachFile(String noteId, XFile file);
|
|
||||||
|
|
||||||
/// Uploads the queue, fetches every attachment [noteTexts] link to that
|
|
||||||
/// this device lacks, and evicts cached ones no note links to.
|
|
||||||
Future<void> reconcile(Iterable<String> noteTexts);
|
|
||||||
|
|
||||||
/// Where to draw [ref] from.
|
|
||||||
ImageSource sourceFor(AttachmentRef ref);
|
|
||||||
|
|
||||||
/// Whether [ref] is still waiting to upload (always false when unknown).
|
|
||||||
bool isPending(AttachmentRef ref);
|
|
||||||
|
|
||||||
/// Size in bytes of [ref] on this device, or null when it is not here yet.
|
|
||||||
Future<int?> sizeOf(AttachmentRef ref);
|
|
||||||
|
|
||||||
/// Login and queue summary.
|
|
||||||
Future<ImageStoreStatus> status();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every attachment ref across [noteTexts].
|
|
||||||
Set<AttachmentRef> attachmentRefsAcross(Iterable<String> noteTexts) => {
|
|
||||||
for (final text in noteTexts) ...attachmentRefsIn(text),
|
|
||||||
};
|
|
||||||
|
|
||||||
/// The store used where none was provided (tests, and any screen built
|
|
||||||
/// outside the app root): attaching is refused, nothing is ever available.
|
|
||||||
class NoImageStore extends ImageStore {
|
|
||||||
@override
|
|
||||||
Future<AttachmentRef?> attach(String noteId, Uint8List bytes) async =>
|
|
||||||
throw const ImageStoreException('Images are not available here');
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<Attachment> attachFile(String noteId, XFile file) async =>
|
|
||||||
throw const ImageStoreException('Attachments are not available here');
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> reconcile(Iterable<String> noteTexts) async {}
|
|
||||||
|
|
||||||
@override
|
|
||||||
ImageSource sourceFor(AttachmentRef ref) => const MissingImageSource();
|
|
||||||
|
|
||||||
@override
|
|
||||||
bool isPending(AttachmentRef ref) => false;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<int?> sizeOf(AttachmentRef ref) async => null;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<ImageStoreStatus> status() async =>
|
|
||||||
const ImageStoreStatus(configured: false, pending: 0);
|
|
||||||
}
|
|
||||||
@ -1,139 +0,0 @@
|
|||||||
/// Android: attachments live in app storage and sync with dufs directly.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'dart:async';
|
|
||||||
import 'dart:io';
|
|
||||||
import 'dart:typed_data';
|
|
||||||
|
|
||||||
import 'package:http/http.dart' as http;
|
|
||||||
import 'package:path/path.dart' as p;
|
|
||||||
import 'package:path_provider/path_provider.dart';
|
|
||||||
import 'package:todo/attachments/image_password_store.dart';
|
|
||||||
import 'package:todo/attachments/image_store_api.dart';
|
|
||||||
import 'package:todo/images/attachment_ingest.dart';
|
|
||||||
import 'package:todo/images/attachment_ref.dart';
|
|
||||||
import 'package:todo/images/dufs_image_client.dart';
|
|
||||||
import 'package:todo/images/image_cache_store.dart';
|
|
||||||
import 'package:todo/images/image_processing.dart';
|
|
||||||
|
|
||||||
/// Opens the store under the app-support directory's `images/`.
|
|
||||||
// coverage:ignore-start
|
|
||||||
// Platform wiring only: path_provider has no binding in unit tests, which
|
|
||||||
// construct [IoImageStore] over a temp directory instead.
|
|
||||||
Future<ImageStore> openImageStore() async {
|
|
||||||
final support = await getApplicationSupportDirectory();
|
|
||||||
final root = Directory(p.join(support.path, 'images'));
|
|
||||||
// Both pickers copy what they return into the cache directory.
|
|
||||||
final pickerCopies = (await getTemporaryDirectory()).path;
|
|
||||||
return IoImageStore(ImageCacheStore(root), pickerCopies: pickerCopies);
|
|
||||||
}
|
|
||||||
// coverage:ignore-end
|
|
||||||
|
|
||||||
/// [ImageStore] over a local [ImageCacheStore], uploading with the login
|
|
||||||
/// from [ImagePasswordStore].
|
|
||||||
class IoImageStore extends ImageStore {
|
|
||||||
/// Creates a store over [cache]. Picked files under [pickerCopies] are the
|
|
||||||
/// pickers' private copies and are moved rather than copied. The rest is
|
|
||||||
/// injectable for tests.
|
|
||||||
IoImageStore(
|
|
||||||
this.cache, {
|
|
||||||
this.pickerCopies,
|
|
||||||
this._passwords = const ImagePasswordStore(),
|
|
||||||
http.Client Function()? httpClient,
|
|
||||||
Future<Uint8List?> Function(Uint8List)? prepare,
|
|
||||||
}) : _httpClient = httpClient ?? http.Client.new,
|
|
||||||
_prepare = prepare ?? prepareImageInBackground,
|
|
||||||
_ingest = AttachmentIngest(
|
|
||||||
cache,
|
|
||||||
prepare: prepare ?? prepareImageInBackground,
|
|
||||||
);
|
|
||||||
|
|
||||||
/// The on-device attachments and upload queue.
|
|
||||||
final ImageCacheStore cache;
|
|
||||||
|
|
||||||
/// Directory the pickers copy their results into, if known.
|
|
||||||
final String? pickerCopies;
|
|
||||||
|
|
||||||
final ImagePasswordStore _passwords;
|
|
||||||
final http.Client Function() _httpClient;
|
|
||||||
final Future<Uint8List?> Function(Uint8List) _prepare;
|
|
||||||
final AttachmentIngest _ingest;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<AttachmentRef?> attach(String noteId, Uint8List bytes) async {
|
|
||||||
final jpeg = await _prepare(bytes);
|
|
||||||
if (jpeg == null) return null;
|
|
||||||
final ref = AttachmentRef.create(noteId);
|
|
||||||
try {
|
|
||||||
await cache.put(ref, jpeg);
|
|
||||||
} on FileSystemException catch (e) {
|
|
||||||
throw ImageStoreException('Could not save the image: ${e.message}');
|
|
||||||
}
|
|
||||||
notifyListeners();
|
|
||||||
// Upload right away when online. An empty ref set never evicts, so this
|
|
||||||
// cannot race the link reaching the note.
|
|
||||||
unawaited(_sync(const {}));
|
|
||||||
return ref;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<Attachment> attachFile(String noteId, XFile file) async {
|
|
||||||
final copies = pickerCopies;
|
|
||||||
final Attachment attachment;
|
|
||||||
try {
|
|
||||||
attachment = await _ingest.fromFile(
|
|
||||||
noteId,
|
|
||||||
file.name,
|
|
||||||
File(file.path),
|
|
||||||
move: copies != null && p.isWithin(copies, file.path),
|
|
||||||
);
|
|
||||||
} on FileSystemException catch (e) {
|
|
||||||
throw ImageStoreException('Could not save ${file.name}: ${e.message}');
|
|
||||||
}
|
|
||||||
notifyListeners();
|
|
||||||
unawaited(_sync(const {}));
|
|
||||||
return attachment;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> reconcile(Iterable<String> noteTexts) =>
|
|
||||||
_sync(attachmentRefsAcross(noteTexts));
|
|
||||||
|
|
||||||
Future<void> _sync(Set<AttachmentRef> refs) async {
|
|
||||||
final login = await _passwords.login();
|
|
||||||
final client = login == null
|
|
||||||
? null
|
|
||||||
: DufsImageClient(login, httpClient: _httpClient());
|
|
||||||
try {
|
|
||||||
final report = await cache.reconcile(refs, client);
|
|
||||||
if (report.uploaded + report.downloaded + report.evicted > 0) {
|
|
||||||
notifyListeners();
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
client?.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
ImageSource sourceFor(AttachmentRef ref) {
|
|
||||||
final file = cache.fileFor(ref);
|
|
||||||
return file.existsSync()
|
|
||||||
? LocalImageSource(file.path)
|
|
||||||
: const MissingImageSource();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
bool isPending(AttachmentRef ref) => cache.isPending(ref);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<int?> sizeOf(AttachmentRef ref) async {
|
|
||||||
final file = cache.fileFor(ref);
|
|
||||||
return file.existsSync() ? await file.length() : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<ImageStoreStatus> status() async => ImageStoreStatus(
|
|
||||||
configured: await _passwords.login() != null,
|
|
||||||
pending: cache.pending().length,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,29 +0,0 @@
|
|||||||
import 'package:flutter/widgets.dart';
|
|
||||||
|
|
||||||
import 'package:todo/attachments/image_store_api.dart';
|
|
||||||
|
|
||||||
/// Makes the app's one [ImageStore] reachable from any widget below it,
|
|
||||||
/// without threading it through every screen constructor.
|
|
||||||
///
|
|
||||||
/// Screens built without a scope (most widget tests) get a shared
|
|
||||||
/// [NoImageStore], so they render and simply cannot attach.
|
|
||||||
class ImageStoreScope extends InheritedNotifier<ImageStore> {
|
|
||||||
/// Provides [store] to [child].
|
|
||||||
const ImageStoreScope({
|
|
||||||
required ImageStore store,
|
|
||||||
required super.child,
|
|
||||||
super.key,
|
|
||||||
}) : super(notifier: store);
|
|
||||||
|
|
||||||
static final ImageStore _none = NoImageStore();
|
|
||||||
|
|
||||||
/// The nearest store, subscribing [context] to its changes.
|
|
||||||
static ImageStore of(BuildContext context) =>
|
|
||||||
context.dependOnInheritedWidgetOfExactType<ImageStoreScope>()?.notifier ??
|
|
||||||
_none;
|
|
||||||
|
|
||||||
/// The nearest store, without subscribing (for callbacks).
|
|
||||||
static ImageStore read(BuildContext context) =>
|
|
||||||
context.getInheritedWidgetOfExactType<ImageStoreScope>()?.notifier ??
|
|
||||||
_none;
|
|
||||||
}
|
|
||||||
@ -1,158 +0,0 @@
|
|||||||
/// Desktop (web build): every attachment operation goes through the local
|
|
||||||
/// wrapper's `/images/*` routes; the page never sees the dufs password.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'dart:async';
|
|
||||||
import 'dart:convert';
|
|
||||||
import 'dart:typed_data';
|
|
||||||
|
|
||||||
import 'package:http/http.dart' as http;
|
|
||||||
|
|
||||||
import 'package:todo/attachments/file_post.dart' as file_post;
|
|
||||||
import 'package:todo/attachments/image_store_api.dart';
|
|
||||||
import 'package:todo/images/attachment_ref.dart';
|
|
||||||
import 'package:todo/sync/desktop_wrapper.dart';
|
|
||||||
|
|
||||||
/// Opens the store against the wrapper that served this page.
|
|
||||||
Future<ImageStore> openImageStore() async =>
|
|
||||||
WebImageStore(origin: servingWrapperOrigin());
|
|
||||||
|
|
||||||
/// Sends a file to the wrapper and returns its answer; injectable for tests.
|
|
||||||
typedef FilePost =
|
|
||||||
Future<({int status, String body})> Function(Uri url, XFile file);
|
|
||||||
|
|
||||||
/// [ImageStore] backed by the desktop wrapper at [origin].
|
|
||||||
class WebImageStore extends ImageStore {
|
|
||||||
/// Creates a store talking to [origin]; [httpClient] and [postFile] are
|
|
||||||
/// injectable.
|
|
||||||
WebImageStore({
|
|
||||||
required this.origin,
|
|
||||||
http.Client? httpClient,
|
|
||||||
FilePost? postFile,
|
|
||||||
}) : _http = httpClient ?? http.Client(),
|
|
||||||
_postFile = postFile ?? file_post.postFile;
|
|
||||||
|
|
||||||
/// The wrapper's origin, e.g. `http://localhost:8730`.
|
|
||||||
final String origin;
|
|
||||||
|
|
||||||
final http.Client _http;
|
|
||||||
final FilePost _postFile;
|
|
||||||
|
|
||||||
// Sizes the wrapper reported. A ref's bytes never change (a fresh uuid per
|
|
||||||
// attachment), so a known size never goes stale.
|
|
||||||
final Map<AttachmentRef, int> _sizes = {};
|
|
||||||
|
|
||||||
// Bumped whenever the wrapper may hold new bytes, so an image that failed
|
|
||||||
// to load (not downloaded yet) is requested again under a fresh URL.
|
|
||||||
int _revision = 0;
|
|
||||||
|
|
||||||
Uri _images(String rest) => Uri.parse('$origin/images/$rest');
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<AttachmentRef?> attach(String noteId, Uint8List bytes) async {
|
|
||||||
final ref = AttachmentRef.create(noteId);
|
|
||||||
final http.Response response;
|
|
||||||
try {
|
|
||||||
response = await _http.post(_images(ref.relativePath), body: bytes);
|
|
||||||
} on Exception {
|
|
||||||
throw const ImageStoreException(
|
|
||||||
'The desktop helper is not running; the image was not saved',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (response.statusCode == 415) return null;
|
|
||||||
if (response.statusCode != 204) {
|
|
||||||
throw ImageStoreException(
|
|
||||||
'The desktop helper refused the image (${response.statusCode})',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
_revision++;
|
|
||||||
notifyListeners();
|
|
||||||
unawaited(_reconcile(const {}));
|
|
||||||
return ref;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<Attachment> attachFile(String noteId, XFile file) async {
|
|
||||||
final url = _images(
|
|
||||||
'attach',
|
|
||||||
).replace(queryParameters: {'note': noteId, 'name': file.name});
|
|
||||||
final ({int status, String body}) response;
|
|
||||||
try {
|
|
||||||
response = await _postFile(url, file);
|
|
||||||
} on Object {
|
|
||||||
throw ImageStoreException(
|
|
||||||
'The desktop helper is not running; ${file.name} was not saved',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (response.status != 200) {
|
|
||||||
throw ImageStoreException(
|
|
||||||
'The desktop helper refused ${file.name} (${response.status})',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
final attachment = Attachment.fromJson(jsonDecode(response.body));
|
|
||||||
_revision++;
|
|
||||||
notifyListeners();
|
|
||||||
unawaited(_reconcile(const {}));
|
|
||||||
return attachment;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> reconcile(Iterable<String> noteTexts) =>
|
|
||||||
_reconcile(attachmentRefsAcross(noteTexts));
|
|
||||||
|
|
||||||
Future<void> _reconcile(Set<AttachmentRef> refs) async {
|
|
||||||
try {
|
|
||||||
final response = await _http.post(
|
|
||||||
_images('reconcile'),
|
|
||||||
headers: {'content-type': 'application/json'},
|
|
||||||
body: jsonEncode({
|
|
||||||
'refs': [for (final ref in refs) ref.relativePath],
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
if (response.statusCode != 200) return;
|
|
||||||
final report = jsonDecode(response.body) as Map<String, dynamic>;
|
|
||||||
if ((report['downloaded'] as int? ?? 0) > 0) {
|
|
||||||
_revision++;
|
|
||||||
notifyListeners();
|
|
||||||
}
|
|
||||||
} on Exception {
|
|
||||||
// Best-effort: the next sync, resume or attach reconciles again.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
ImageSource sourceFor(AttachmentRef ref) =>
|
|
||||||
NetworkImageSource('$origin/images/${ref.relativePath}?r=$_revision');
|
|
||||||
|
|
||||||
@override
|
|
||||||
bool isPending(AttachmentRef ref) => false;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<int?> sizeOf(AttachmentRef ref) async {
|
|
||||||
if (_sizes[ref] case final known?) return known;
|
|
||||||
try {
|
|
||||||
final response = await _http.head(_images(ref.relativePath));
|
|
||||||
final length = response.statusCode == 200
|
|
||||||
? int.tryParse(response.headers['content-length'] ?? '')
|
|
||||||
: null;
|
|
||||||
if (length != null) _sizes[ref] = length;
|
|
||||||
return length;
|
|
||||||
} on Exception {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<ImageStoreStatus> status() async {
|
|
||||||
try {
|
|
||||||
final response = await _http.get(_images('status'));
|
|
||||||
final body = jsonDecode(response.body) as Map<String, dynamic>;
|
|
||||||
return ImageStoreStatus(
|
|
||||||
configured: body['configured'] as bool? ?? false,
|
|
||||||
pending: body['pending'] as int? ?? 0,
|
|
||||||
);
|
|
||||||
} on Exception {
|
|
||||||
return const ImageStoreStatus(configured: false, pending: 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,226 +0,0 @@
|
|||||||
/// Hand-rolled argument parsing for `bin/todo_note.dart`.
|
|
||||||
///
|
|
||||||
/// Deliberately not `package:args`: a handful of flags do not justify a new
|
|
||||||
/// exact-pinned dependency under the freshness gate.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:todo/cli/cli_mode.dart';
|
|
||||||
import 'package:todo/data/note.dart';
|
|
||||||
|
|
||||||
export 'package:todo/cli/cli_mode.dart';
|
|
||||||
export 'package:todo/cli/cli_usage.dart';
|
|
||||||
|
|
||||||
/// The parsed command line.
|
|
||||||
class CliArgs {
|
|
||||||
/// Creates parsed arguments; see [parse].
|
|
||||||
const CliArgs({
|
|
||||||
required this.mode,
|
|
||||||
this.text,
|
|
||||||
this.id,
|
|
||||||
this.priority = Priority.medium,
|
|
||||||
this.status,
|
|
||||||
this.dataDir,
|
|
||||||
this.newNote = false,
|
|
||||||
this.dryRun = false,
|
|
||||||
this.opts = (
|
|
||||||
repo: null,
|
|
||||||
query: null,
|
|
||||||
doneCheck: null,
|
|
||||||
by: null,
|
|
||||||
evidence: null,
|
|
||||||
),
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Parses [argv]. Throws [UsageError] on anything it does not understand.
|
|
||||||
factory CliArgs.parse(List<String> argv) {
|
|
||||||
final opts = <String, String>{};
|
|
||||||
String? id;
|
|
||||||
final modes = <CliMode>{};
|
|
||||||
for (var i = 0; i < argv.length; i++) {
|
|
||||||
final arg = argv[i];
|
|
||||||
String value() {
|
|
||||||
if (i + 1 >= argv.length) throw UsageError('$arg needs a value');
|
|
||||||
return argv[++i];
|
|
||||||
}
|
|
||||||
|
|
||||||
switch (arg) {
|
|
||||||
case '--new-note':
|
|
||||||
opts[arg] = '';
|
|
||||||
case '-h' || '--help':
|
|
||||||
modes.add(CliMode.help);
|
|
||||||
case '--text' || '--priority' || '--status' || '--data-dir':
|
|
||||||
case '--repo' || '--done-check' || '--by' || '--evidence':
|
|
||||||
opts[arg] = value();
|
|
||||||
case '--list':
|
|
||||||
modes.add(CliMode.list);
|
|
||||||
case '--backfill-created-by':
|
|
||||||
modes.add(CliMode.backfill);
|
|
||||||
case '--dry-run':
|
|
||||||
opts[arg] = 'true';
|
|
||||||
case '--search':
|
|
||||||
modes.add(CliMode.search);
|
|
||||||
opts[arg] = value();
|
|
||||||
case '--get' || '--delete' || '--close':
|
|
||||||
modes.add(CliMode.values.byName(arg.substring(2)));
|
|
||||||
id = value();
|
|
||||||
case '--set-text':
|
|
||||||
modes.add(CliMode.setText);
|
|
||||||
id = value();
|
|
||||||
case '--set-status':
|
|
||||||
modes.add(CliMode.setStatus);
|
|
||||||
id = value();
|
|
||||||
opts[arg] = value();
|
|
||||||
default:
|
|
||||||
throw UsageError('unknown argument: $arg');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (modes.contains(CliMode.help)) return const CliArgs(mode: CliMode.help);
|
|
||||||
if (modes.length > 1) {
|
|
||||||
throw UsageError(
|
|
||||||
'--list, --search, --get, --delete, --set-status, --set-text, '
|
|
||||||
'--close and '
|
|
||||||
'--backfill-created-by are mutually exclusive',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
final mode = modes.isEmpty ? CliMode.add : modes.single;
|
|
||||||
_checkScopes(opts.keys, mode);
|
|
||||||
final rawStatus = opts['--set-status'] ?? opts['--status'];
|
|
||||||
return CliArgs(
|
|
||||||
mode: mode,
|
|
||||||
text: opts['--text'],
|
|
||||||
id: id,
|
|
||||||
priority: opts['--priority'] == null
|
|
||||||
? Priority.medium
|
|
||||||
: _byName(Priority.values, opts['--priority']!, '--priority'),
|
|
||||||
status: rawStatus == null
|
|
||||||
? null
|
|
||||||
: _byName(Status.values, rawStatus, '--status', _statusName),
|
|
||||||
dataDir: opts['--data-dir'],
|
|
||||||
newNote:
|
|
||||||
opts.containsKey('--new-note') &&
|
|
||||||
(opts['--repo'] != null ||
|
|
||||||
(throw UsageError('--new-note needs --repo'))),
|
|
||||||
dryRun: opts.containsKey('--dry-run'),
|
|
||||||
opts: (
|
|
||||||
repo: _repo(opts['--repo']),
|
|
||||||
query: _nonBlank(opts['--search'], '--search'),
|
|
||||||
doneCheck: _nonBlank(opts['--done-check'], '--done-check'),
|
|
||||||
by: opts['--by'] == null ? null : _by(opts['--by']!),
|
|
||||||
evidence: _evidence(opts['--evidence'], mode),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The selected mode.
|
|
||||||
final CliMode mode;
|
|
||||||
|
|
||||||
/// Note text from `--text`; null means "read stdin" in [CliMode.add] and
|
|
||||||
/// [CliMode.setText].
|
|
||||||
final String? text;
|
|
||||||
|
|
||||||
/// Full id or 8+ character prefix of the note an id mode acts on.
|
|
||||||
final String? id;
|
|
||||||
|
|
||||||
/// Priority of a new note.
|
|
||||||
final Priority priority;
|
|
||||||
|
|
||||||
/// New note's status, [CliMode.setStatus]'s target, or a list filter.
|
|
||||||
final Status? status;
|
|
||||||
|
|
||||||
/// Overrides the default data dir (a second, independent node).
|
|
||||||
final String? dataDir;
|
|
||||||
|
|
||||||
/// `--new-note`: the `--repo` task gets its own note.
|
|
||||||
final bool newNote;
|
|
||||||
|
|
||||||
/// Whether `--dry-run` was given: report what would change, change nothing.
|
|
||||||
final bool dryRun;
|
|
||||||
|
|
||||||
/// `--repo`, `--search`, `--done-check`, `--by` and `--evidence` values.
|
|
||||||
final ({
|
|
||||||
String? repo,
|
|
||||||
String? query,
|
|
||||||
String? doneCheck,
|
|
||||||
String? by,
|
|
||||||
String? evidence,
|
|
||||||
})
|
|
||||||
opts;
|
|
||||||
|
|
||||||
/// The command-line spelling of [status] (`in_progress`, not `inProgress`).
|
|
||||||
static String statusName(Status status) => _statusName(status);
|
|
||||||
|
|
||||||
static const _adding = 'when adding a note';
|
|
||||||
static const Map<String, (String, Set<CliMode>)> _scopes = {
|
|
||||||
'--text': ('$_adding or to --set-text', {CliMode.add, CliMode.setText}),
|
|
||||||
'--done-check': (_adding, {CliMode.add}),
|
|
||||||
'--by': (_adding, {CliMode.add}),
|
|
||||||
'--repo': (
|
|
||||||
'$_adding, to --list or to --search',
|
|
||||||
{CliMode.add, CliMode.list, CliMode.search},
|
|
||||||
),
|
|
||||||
'--evidence': ('to --close', {CliMode.close}),
|
|
||||||
'--new-note': (_adding, {CliMode.add}),
|
|
||||||
'--dry-run': ('to --backfill-created-by', {CliMode.backfill}),
|
|
||||||
};
|
|
||||||
|
|
||||||
static void _checkScopes(Iterable<String> flags, CliMode mode) {
|
|
||||||
for (final flag in flags) {
|
|
||||||
final scope = _scopes[flag];
|
|
||||||
if (scope != null && !scope.$2.contains(mode)) {
|
|
||||||
throw UsageError('$flag only applies ${scope.$1}');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static final _repoShape = RegExp(r'^[\w.-]+/[\w.-]+$');
|
|
||||||
|
|
||||||
static String? _repo(String? raw) {
|
|
||||||
if (raw == null || _repoShape.hasMatch(raw)) return raw;
|
|
||||||
throw UsageError(
|
|
||||||
'--repo must look like owner/name (e.g. kuhyx/todo), got "$raw"',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
static String _by(String raw) {
|
|
||||||
if (kNoteAuthors.contains(raw)) return raw;
|
|
||||||
throw UsageError(
|
|
||||||
'--by must be one of ${kNoteAuthors.join('|')}, got "$raw"',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
static String? _evidence(String? raw, CliMode mode) {
|
|
||||||
if (mode == CliMode.close && (raw == null || raw.trim().isEmpty)) {
|
|
||||||
throw UsageError(
|
|
||||||
'--close needs --evidence <commit sha + done check exit code>: '
|
|
||||||
'a task is only closed with proof',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return raw;
|
|
||||||
}
|
|
||||||
|
|
||||||
static String? _nonBlank(String? raw, String flag) {
|
|
||||||
if (raw != null && raw.trim().isEmpty) {
|
|
||||||
throw UsageError('$flag must not be empty');
|
|
||||||
}
|
|
||||||
return raw;
|
|
||||||
}
|
|
||||||
|
|
||||||
static String _statusName(Enum value) =>
|
|
||||||
value == Status.inProgress ? 'in_progress' : value.name;
|
|
||||||
|
|
||||||
static T _byName<T extends Enum>(
|
|
||||||
List<T> values,
|
|
||||||
String raw,
|
|
||||||
String flag, [
|
|
||||||
String Function(Enum) nameOf = _plainName,
|
|
||||||
]) {
|
|
||||||
for (final v in values) {
|
|
||||||
if (nameOf(v) == raw) return v;
|
|
||||||
}
|
|
||||||
throw UsageError(
|
|
||||||
'$flag must be one of ${values.map(nameOf).join('|')}, got "$raw"',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
static String _plainName(Enum value) => value.name;
|
|
||||||
}
|
|
||||||
@ -1,206 +0,0 @@
|
|||||||
import 'package:todo/cli/cli_args.dart';
|
|
||||||
import 'package:todo/cli/cli_session.dart';
|
|
||||||
import 'package:todo/cli/note_lookup.dart';
|
|
||||||
import 'package:todo/data/note.dart';
|
|
||||||
import 'package:todo/data/note_repository.dart';
|
|
||||||
import 'package:todo/data/repo_note.dart';
|
|
||||||
import 'package:todo/data/repo_note_split.dart';
|
|
||||||
import 'package:todo/sync/sync_service.dart';
|
|
||||||
import 'package:uuid/uuid.dart';
|
|
||||||
|
|
||||||
/// One CLI command per method over an open [CliSession]; each returns the
|
|
||||||
/// exit code. Id arguments are resolved by [findNote].
|
|
||||||
class CliCommands {
|
|
||||||
/// Writes results to the first sink, errors and warnings to the second.
|
|
||||||
CliCommands(this.session, this._out, this._err);
|
|
||||||
|
|
||||||
/// The open session the commands act on.
|
|
||||||
final CliSession session;
|
|
||||||
|
|
||||||
final StringSink _out;
|
|
||||||
final StringSink _err;
|
|
||||||
|
|
||||||
/// Creates a note and pushes it. A `--repo` add joins the repo's open note.
|
|
||||||
Future<int> add(CliArgs args, String text) async {
|
|
||||||
final repo = args.opts.repo;
|
|
||||||
final status = args.status ?? Status.todo;
|
|
||||||
if (repo != null && kOpenStatuses.contains(status)) {
|
|
||||||
return await _addRepoTask(args, repo, text);
|
|
||||||
}
|
|
||||||
final now = DateTime.now();
|
|
||||||
final note = Note(
|
|
||||||
id: const Uuid().v4(),
|
|
||||||
text: text,
|
|
||||||
priority: args.priority,
|
|
||||||
status: status,
|
|
||||||
createdAt: now,
|
|
||||||
updatedAt: now,
|
|
||||||
repo: repo,
|
|
||||||
doneCheck: args.opts.doneCheck,
|
|
||||||
by: args.opts.by,
|
|
||||||
createdBy: 'claude',
|
|
||||||
);
|
|
||||||
await session.repository.upsert(note);
|
|
||||||
if (!await _push('note')) return 1;
|
|
||||||
_out.writeln(note.id);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<int> _addRepoTask(CliArgs args, String repo, String text) async {
|
|
||||||
_report(await session.sync(push: true));
|
|
||||||
final (:title, :body) = splitNote(text);
|
|
||||||
if (args.newNote) return await _addSeparate(args, repo, title, body);
|
|
||||||
final added = await addRepoTask(
|
|
||||||
session.repository,
|
|
||||||
repo: repo,
|
|
||||||
title: title,
|
|
||||||
body: body,
|
|
||||||
doneCheck: args.opts.doneCheck,
|
|
||||||
priority: args.priority,
|
|
||||||
by: args.opts.by,
|
|
||||||
createdBy: 'claude',
|
|
||||||
);
|
|
||||||
await _save(added.note);
|
|
||||||
if (!await _push('note')) return 1;
|
|
||||||
if (added.appended) _err.writeln('appended to the open note for $repo');
|
|
||||||
_out.writeln(added.note.id);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<int> _addSeparate(
|
|
||||||
CliArgs args,
|
|
||||||
String repo,
|
|
||||||
String title,
|
|
||||||
String body,
|
|
||||||
) async {
|
|
||||||
final added = await addSeparateTask(
|
|
||||||
session.repository,
|
|
||||||
repo: repo,
|
|
||||||
title: title,
|
|
||||||
body: body,
|
|
||||||
doneCheck: args.opts.doneCheck,
|
|
||||||
priority: args.priority,
|
|
||||||
by: args.opts.by,
|
|
||||||
createdBy: 'claude',
|
|
||||||
);
|
|
||||||
await _save(added.note);
|
|
||||||
if (!await _push('note')) return 1;
|
|
||||||
if (added.kind == SplitKind.merged) {
|
|
||||||
_err.writeln(
|
|
||||||
'merged into the separate note with that title; '
|
|
||||||
'click Start on the board by hand',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
_out.writeln(added.note.id);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Prints [listLine] for each note matching the filters in [args].
|
|
||||||
Future<int> list(CliArgs args) async {
|
|
||||||
_report(await session.sync(push: false));
|
|
||||||
final notes = await session.repository.listNotes(
|
|
||||||
filter: NoteFilter(
|
|
||||||
query: args.opts.query ?? '',
|
|
||||||
statuses: {?args.status},
|
|
||||||
repo: args.opts.repo,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
notes.map(listLine).forEach(_out.writeln);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Prints one note in full.
|
|
||||||
Future<int> get(String ref) async {
|
|
||||||
_report(await session.sync(push: false));
|
|
||||||
_out.writeln(
|
|
||||||
noteDetail(findNote(await session.repository.listNotes(), ref)),
|
|
||||||
);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Tombstones a note and pushes the deletion.
|
|
||||||
Future<int> delete(String ref) async {
|
|
||||||
final note = await _pullAndFind(ref);
|
|
||||||
await session.repository.delete(note.id);
|
|
||||||
if (!await _push('deletion')) return 1;
|
|
||||||
_out.writeln('deleted ${note.id}');
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Changes a note's status and pushes it.
|
|
||||||
Future<int> setStatus(String ref, Status status) async {
|
|
||||||
final note = await _pullAndFind(ref);
|
|
||||||
await _save(note.copyWith(status: status));
|
|
||||||
if (!await _push('status change')) return 1;
|
|
||||||
_out.writeln('${note.id}\t${CliArgs.statusName(status)}');
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Replaces a note's whole text (title is its first line) and pushes it.
|
|
||||||
Future<int> setText(String ref, String text) async {
|
|
||||||
final note = await _pullAndFind(ref);
|
|
||||||
await _save(note.copyWith(text: text));
|
|
||||||
if (!await _push('text change')) return 1;
|
|
||||||
_out.writeln('${note.id}\ttext');
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Marks a note done with [evidence], keeping it, and pushes it.
|
|
||||||
Future<int> close(String ref, String evidence) async {
|
|
||||||
final note = await _pullAndFind(ref);
|
|
||||||
await _save(note.copyWith(status: Status.done, evidence: evidence));
|
|
||||||
if (!await _push('close')) return 1;
|
|
||||||
_out.writeln('closed ${note.id}');
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets `created_by` where unset (see [NoteRepository.backfillCreatedBy]).
|
|
||||||
/// Prints one `<id>\t<value>\t<title>` line per note, then the totals. With
|
|
||||||
/// [dryRun] nothing is written or pushed, and peers are only read.
|
|
||||||
Future<int> backfillCreatedBy(
|
|
||||||
Set<String> claudeNodes, {
|
|
||||||
required bool dryRun,
|
|
||||||
}) async {
|
|
||||||
_report(await session.sync(push: !dryRun));
|
|
||||||
final plan = await session.repository.backfillCreatedBy(
|
|
||||||
claudeNodes,
|
|
||||||
dryRun: dryRun,
|
|
||||||
);
|
|
||||||
final titles = {
|
|
||||||
for (final n in await session.repository.listNotes()) n.id: n,
|
|
||||||
};
|
|
||||||
for (final MapEntry(:key, :value) in plan.entries) {
|
|
||||||
final note = titles[key];
|
|
||||||
final title = note == null ? '' : note.text.split('\n').first;
|
|
||||||
_out.writeln(
|
|
||||||
'${key.substring(0, key.length.clamp(0, 8))}\t$value\t$title',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
final claude = plan.values.where((v) => v == 'claude').length;
|
|
||||||
final kuhy = plan.length - claude;
|
|
||||||
_out.writeln('${dryRun ? 'dry run' : 'set'}: claude $claude, kuhy $kuhy');
|
|
||||||
if (dryRun || plan.isEmpty) return 0;
|
|
||||||
return await _push('backfill') ? 0 : 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<Note> _pullAndFind(String ref) async {
|
|
||||||
_report(await session.sync(push: true));
|
|
||||||
return findNote(await session.repository.listNotes(), ref);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _save(Note note) =>
|
|
||||||
session.repository.upsert(note.copyWith(updatedAt: DateTime.now()));
|
|
||||||
|
|
||||||
Future<bool> _push(String what) async {
|
|
||||||
if (_report(await session.sync(push: true)).pushed) return true;
|
|
||||||
_err.writeln('error: $what saved locally but nothing was pushed');
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
SyncResult _report(SyncResult result) {
|
|
||||||
for (final name in result.skippedFiles) {
|
|
||||||
_err.writeln('warning: could not merge peer file $name');
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,47 +0,0 @@
|
|||||||
/// What the CLI can be asked to do, and how a bad command line is reported.
|
|
||||||
library;
|
|
||||||
|
|
||||||
/// What the CLI was asked to do.
|
|
||||||
enum CliMode {
|
|
||||||
/// Create a note and push it.
|
|
||||||
add,
|
|
||||||
|
|
||||||
/// Print every live note, one per line.
|
|
||||||
list,
|
|
||||||
|
|
||||||
/// Print one note in full.
|
|
||||||
get,
|
|
||||||
|
|
||||||
/// Tombstone one note and push the deletion.
|
|
||||||
delete,
|
|
||||||
|
|
||||||
/// Change one note's status and push it.
|
|
||||||
setStatus,
|
|
||||||
|
|
||||||
/// Replace one note's whole text and push it.
|
|
||||||
setText,
|
|
||||||
|
|
||||||
/// Set a task done with evidence and push it.
|
|
||||||
close,
|
|
||||||
|
|
||||||
/// Print the notes matching a query, as [list] does.
|
|
||||||
search,
|
|
||||||
|
|
||||||
/// Set `created_by` on notes that lack it.
|
|
||||||
backfill,
|
|
||||||
|
|
||||||
/// Print usage.
|
|
||||||
help,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Thrown for a malformed command line; maps to exit code 2.
|
|
||||||
class UsageError implements Exception {
|
|
||||||
/// Creates a [UsageError] carrying [message].
|
|
||||||
UsageError(this.message);
|
|
||||||
|
|
||||||
/// What was wrong with the arguments.
|
|
||||||
final String message;
|
|
||||||
|
|
||||||
@override
|
|
||||||
String toString() => message;
|
|
||||||
}
|
|
||||||
@ -1,26 +0,0 @@
|
|||||||
import 'dart:io';
|
|
||||||
|
|
||||||
import 'package:path/path.dart' as p;
|
|
||||||
import 'package:todo/cli/cli_session.dart' show CliSession;
|
|
||||||
|
|
||||||
/// Default data dir: `$XDG_DATA_HOME/todo-cli`, else `~/.local/share/todo-cli`.
|
|
||||||
String defaultDataDir(Map<String, String> env) {
|
|
||||||
final xdg = env['XDG_DATA_HOME'] ?? '';
|
|
||||||
final base = xdg.isNotEmpty
|
|
||||||
? xdg
|
|
||||||
: p.join(env['HOME'] ?? '', '.local', 'share');
|
|
||||||
return p.join(base, 'todo-cli');
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Node ids of the installs Claude files notes through: the MCP server and
|
|
||||||
/// the CLI under the same data root as [defaultDataDir]. Missing ones are
|
|
||||||
/// skipped.
|
|
||||||
Set<String> claudeNodeIds(Map<String, String> env) {
|
|
||||||
final cli = defaultDataDir(env);
|
|
||||||
return {
|
|
||||||
for (final dir in [cli, p.join(p.dirname(cli), 'todo-mcp')])
|
|
||||||
if (File(p.join(dir, CliSession.nodeIdFileName)) case final f
|
|
||||||
when f.existsSync())
|
|
||||||
f.readAsStringSync().trim(),
|
|
||||||
}..remove('');
|
|
||||||
}
|
|
||||||
@ -1,103 +0,0 @@
|
|||||||
/// The body of `bin/todo_note.dart`, with every side effect injected.
|
|
||||||
///
|
|
||||||
/// Lives in `lib/` so the tests can drive it with a fake RTDB, a temp data
|
|
||||||
/// dir and in-memory output sinks; the `bin/` entrypoint only wires the real
|
|
||||||
/// process streams and environment into [runCli].
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'dart:convert';
|
|
||||||
import 'dart:io';
|
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
import 'package:path/path.dart' as p;
|
|
||||||
import 'package:todo/cli/cli_args.dart';
|
|
||||||
import 'package:todo/cli/cli_commands.dart';
|
|
||||||
import 'package:todo/cli/cli_session.dart';
|
|
||||||
import 'package:todo/cli/note_lookup.dart';
|
|
||||||
|
|
||||||
/// Opens a [CliSession]; swapped in tests to point it at a fake backend.
|
|
||||||
typedef SessionOpener =
|
|
||||||
Future<CliSession> Function(
|
|
||||||
String dataDir, {
|
|
||||||
required String seedCredentials,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Reads all of [input] as text, or '' when it is an interactive terminal.
|
|
||||||
Future<String> readInput(
|
|
||||||
Stream<List<int>> input, {
|
|
||||||
required bool hasTerminal,
|
|
||||||
}) async {
|
|
||||||
if (hasTerminal) return '';
|
|
||||||
return (await input.transform(utf8.decoder).join()).trimRight();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Runs the CLI for [argv] and returns its exit code.
|
|
||||||
Future<int> runCli(
|
|
||||||
List<String> argv, {
|
|
||||||
required Map<String, String> env,
|
|
||||||
required StringSink out,
|
|
||||||
required StringSink err,
|
|
||||||
required Future<String> Function() readStdin,
|
|
||||||
SessionOpener open = CliSession.open,
|
|
||||||
}) async {
|
|
||||||
final CliArgs args;
|
|
||||||
try {
|
|
||||||
args = CliArgs.parse(argv);
|
|
||||||
} on UsageError catch (error) {
|
|
||||||
err
|
|
||||||
..writeln('error: $error')
|
|
||||||
..writeln(kUsage);
|
|
||||||
return 2;
|
|
||||||
}
|
|
||||||
if (args.mode == CliMode.help) {
|
|
||||||
out.writeln(kUsage);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
String? text;
|
|
||||||
if (args.mode == CliMode.add || args.mode == CliMode.setText) {
|
|
||||||
text = args.text ?? await readStdin();
|
|
||||||
if (text.trim().isEmpty) {
|
|
||||||
err.writeln('error: empty note (pass --text or pipe text on stdin)');
|
|
||||||
return 2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
CliSession? session;
|
|
||||||
try {
|
|
||||||
session = await open(
|
|
||||||
args.dataDir ?? defaultDataDir(env),
|
|
||||||
seedCredentials: p.join(
|
|
||||||
env['HOME'] ?? '',
|
|
||||||
'.config',
|
|
||||||
'todo',
|
|
||||||
'firebase_auth.json',
|
|
||||||
),
|
|
||||||
);
|
|
||||||
final cli = CliCommands(session, out, err);
|
|
||||||
return switch (args.mode) {
|
|
||||||
CliMode.add => await cli.add(args, text!),
|
|
||||||
CliMode.list || CliMode.search => await cli.list(args),
|
|
||||||
CliMode.get => await cli.get(args.id!),
|
|
||||||
CliMode.setStatus => await cli.setStatus(args.id!, args.status!),
|
|
||||||
CliMode.setText => await cli.setText(args.id!, text!),
|
|
||||||
CliMode.close => await cli.close(args.id!, args.opts.evidence!),
|
|
||||||
CliMode.backfill => await cli.backfillCreatedBy(
|
|
||||||
claudeNodeIds(env),
|
|
||||||
dryRun: args.dryRun,
|
|
||||||
),
|
|
||||||
// Only delete is left: help returned above.
|
|
||||||
_ => await cli.delete(args.id!),
|
|
||||||
};
|
|
||||||
} on NoteLookupError catch (error) {
|
|
||||||
err.writeln('error: $error');
|
|
||||||
return 1;
|
|
||||||
} on RemoteSyncError catch (error) {
|
|
||||||
err.writeln('error: $error');
|
|
||||||
return 1;
|
|
||||||
} on IOException catch (error) {
|
|
||||||
err.writeln('error: $error');
|
|
||||||
return 1;
|
|
||||||
} finally {
|
|
||||||
await session?.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,235 +0,0 @@
|
|||||||
/// One headless CLI run: a local note log, its node id, and a Firebase client.
|
|
||||||
///
|
|
||||||
/// Built only from Flutter-free pieces of the app (the [NoteRepository], the
|
|
||||||
/// [SyncService] every device runs, and [kProject]) so `dart run` works with
|
|
||||||
/// no Flutter engine — the same constraint `tool/sync_smoke.dart` lives under.
|
|
||||||
/// The writes are therefore ordinary CRDT changes from one more device, never
|
|
||||||
/// records hand-written into RTDB.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'dart:convert';
|
|
||||||
import 'dart:io';
|
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
import 'package:crdt_sync/crdt_sync_io.dart';
|
|
||||||
import 'package:http/http.dart' as http;
|
|
||||||
import 'package:path/path.dart' as p;
|
|
||||||
import 'package:todo/cli/file_credential_store.dart';
|
|
||||||
import 'package:todo/cli/pull_only_store.dart';
|
|
||||||
import 'package:todo/cli/timeout_client.dart';
|
|
||||||
import 'package:todo/data/note_repository.dart';
|
|
||||||
import 'package:todo/sync/firebase_project.dart';
|
|
||||||
import 'package:todo/sync/sync_service.dart';
|
|
||||||
import 'package:uuid/uuid.dart';
|
|
||||||
|
|
||||||
export 'package:todo/cli/cli_paths.dart';
|
|
||||||
|
|
||||||
/// The open state of one CLI invocation. Call [close] when done.
|
|
||||||
class CliSession {
|
|
||||||
/// Wraps already-open parts; [open] is the normal way in. Public so a test
|
|
||||||
/// can subclass the session and script [sync]'s outcome.
|
|
||||||
CliSession(
|
|
||||||
this.dataDir,
|
|
||||||
this.repository,
|
|
||||||
this._firebase, {
|
|
||||||
this.passphraseFile,
|
|
||||||
this.sharedPasswordFile,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// The fleet-wide crdt-sync password the Python daemons read too
|
|
||||||
/// (`~/.config/crdt-sync/password`), found from the seed's config root.
|
|
||||||
final File? sharedPasswordFile;
|
|
||||||
|
|
||||||
/// Where the passphrase is read from besides the environment: next to the
|
|
||||||
/// seeded Firebase session, e.g. `~/.config/todo/e2e_passphrase`.
|
|
||||||
final File? passphraseFile;
|
|
||||||
|
|
||||||
/// File holding this install's persisted CRDT node id.
|
|
||||||
static const nodeIdFileName = 'node_id';
|
|
||||||
|
|
||||||
/// File holding the per-peer revision cache (see [SyncService.stateStore]).
|
|
||||||
static const syncStateFileName = 'sync_state.json';
|
|
||||||
|
|
||||||
/// The CLI's private copy of the Firebase session.
|
|
||||||
static const credentialsFileName = 'firebase_auth.json';
|
|
||||||
|
|
||||||
/// Where the local log, node id and session copy live.
|
|
||||||
final String dataDir;
|
|
||||||
|
|
||||||
/// The note store, exactly the class the app uses.
|
|
||||||
final NoteRepository repository;
|
|
||||||
|
|
||||||
final FirebaseRestClient _firebase;
|
|
||||||
|
|
||||||
/// Opens (creating on first use) the session rooted at [dataDir].
|
|
||||||
///
|
|
||||||
/// [seedCredentials] is todo's desktop session, read once and never written.
|
|
||||||
/// [httpClient] replaces the real network client (tests only). Either way
|
|
||||||
/// every request is bounded by [requestTimeout] (see [TimeoutClient]).
|
|
||||||
static Future<CliSession> open(
|
|
||||||
String dataDir, {
|
|
||||||
required String seedCredentials,
|
|
||||||
String seedApp = 'todo',
|
|
||||||
http.Client? httpClient,
|
|
||||||
Duration requestTimeout = const Duration(seconds: 30),
|
|
||||||
}) async {
|
|
||||||
final network = TimeoutClient(
|
|
||||||
httpClient ?? http.Client(),
|
|
||||||
timeout: requestTimeout,
|
|
||||||
);
|
|
||||||
final dir = Directory(dataDir);
|
|
||||||
await dir.create(recursive: true);
|
|
||||||
// Holds a database-write credential: owner-only, like ~/.config/todo.
|
|
||||||
await Process.run('chmod', ['700', dir.path]);
|
|
||||||
final repository = await NoteRepository.openWith(
|
|
||||||
persistence: FileLogPersistence(
|
|
||||||
File(p.join(dataDir, NoteRepository.logFileName)),
|
|
||||||
),
|
|
||||||
nodeId: await _nodeId(dataDir),
|
|
||||||
);
|
|
||||||
final auth = FirebaseTokenProvider(
|
|
||||||
apiKey: kProject.apiKey,
|
|
||||||
httpClient: network,
|
|
||||||
store: FileCredentialStore(
|
|
||||||
file: File(p.join(dataDir, credentialsFileName)),
|
|
||||||
seedFile: File(seedCredentials),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
if (!await auth.hasSession()) {
|
|
||||||
await repository.close();
|
|
||||||
throw FirebaseAuthError(
|
|
||||||
'no Firebase session: $seedCredentials is missing; re-seed it with '
|
|
||||||
'`python3 ~/src/utils/crdt-sync/tool/seed_session.py --app $seedApp`',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
final firebase = FirebaseRestClient(
|
|
||||||
databaseUrl: kProject.databaseUrl,
|
|
||||||
auth: auth,
|
|
||||||
httpClient: network,
|
|
||||||
);
|
|
||||||
return CliSession(
|
|
||||||
dataDir,
|
|
||||||
repository,
|
|
||||||
firebase,
|
|
||||||
passphraseFile: File(
|
|
||||||
p.join(p.dirname(seedCredentials), e2ePassphraseFileName),
|
|
||||||
),
|
|
||||||
sharedPasswordFile: File(
|
|
||||||
p.join(p.dirname(p.dirname(seedCredentials)), 'crdt-sync', 'password'),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Pull every peer's log and merge it; with [push], also publish this
|
|
||||||
/// node's merged log and its revision, exactly as a device's sync tick does.
|
|
||||||
///
|
|
||||||
/// Without [push] nothing is written anywhere remote, and the revision cache
|
|
||||||
/// is bypassed so a read always sees every peer's current log.
|
|
||||||
Future<SyncResult> sync({required bool push}) async {
|
|
||||||
final plainService = SyncService(
|
|
||||||
stateStore: push
|
|
||||||
? PersistedSyncStateStore(
|
|
||||||
FileLogPersistence(File(p.join(dataDir, syncStateFileName))),
|
|
||||||
)
|
|
||||||
: null,
|
|
||||||
);
|
|
||||||
final e2e = await openEncryptedStore(
|
|
||||||
store: _remote(push: push),
|
|
||||||
oldPrefix: plainService.notesDir,
|
|
||||||
readPassphrase: _readPassphrase,
|
|
||||||
// Argon2id once per install, not on every CLI/MCP call.
|
|
||||||
keyCache: E2eKeyCache(read: _readCachedKey, write: _writeCachedKey),
|
|
||||||
);
|
|
||||||
if (!push) {
|
|
||||||
// Read-only during the migration: old builds still write the plaintext
|
|
||||||
// prefix, so merge it, then the encrypted one when this host has a key.
|
|
||||||
final plain = await const SyncService().sync(
|
|
||||||
repository,
|
|
||||||
_remote(push: false),
|
|
||||||
);
|
|
||||||
if (e2e is! E2eReady) return plain;
|
|
||||||
final layout = E2eLayout.of(plainService.notesDir);
|
|
||||||
return await SyncService(
|
|
||||||
notesDir: layout.prefix,
|
|
||||||
revsPath: layout.revsPath,
|
|
||||||
).sync(repository, e2e.store);
|
|
||||||
}
|
|
||||||
if (e2e is! E2eReady) {
|
|
||||||
throw StateError(
|
|
||||||
'sync is locked: put the crdt-sync passphrase in '
|
|
||||||
'$e2ePassphraseEnv or ${passphraseFile?.path ?? e2ePassphraseFileName}',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
final layout = E2eLayout.of(plainService.notesDir);
|
|
||||||
return await SyncService(
|
|
||||||
notesDir: layout.prefix,
|
|
||||||
revsPath: layout.revsPath,
|
|
||||||
stateStore: plainService.stateStore,
|
|
||||||
).sync(repository, e2e.store);
|
|
||||||
}
|
|
||||||
|
|
||||||
RemoteStore _remote({required bool push}) =>
|
|
||||||
push ? _firebase : PullOnlyStore(_firebase);
|
|
||||||
|
|
||||||
/// Owner-only file in the data dir caching the derived E2E key.
|
|
||||||
static const e2eKeyFileName = 'e2e_key';
|
|
||||||
|
|
||||||
File get _keyFile => File(p.join(dataDir, e2eKeyFileName));
|
|
||||||
|
|
||||||
Future<List<int>?> _readCachedKey() async {
|
|
||||||
final file = _keyFile;
|
|
||||||
if (!file.existsSync()) return null;
|
|
||||||
try {
|
|
||||||
return base64.decode((await file.readAsString()).trim());
|
|
||||||
} on FormatException {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _writeCachedKey(List<int> bytes) async {
|
|
||||||
final file = _keyFile;
|
|
||||||
// Restrict before the key is written, never after.
|
|
||||||
await file.writeAsString('');
|
|
||||||
await Process.run('chmod', ['600', file.path]);
|
|
||||||
await file.writeAsString(base64.encode(bytes), flush: true);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Environment variable holding the shared crdt-sync passphrase.
|
|
||||||
static const e2ePassphraseEnv = 'TODO_E2E_PASSPHRASE';
|
|
||||||
|
|
||||||
/// File name of the passphrase, beside the seeded Firebase session.
|
|
||||||
static const e2ePassphraseFileName = 'e2e_passphrase';
|
|
||||||
|
|
||||||
Future<String?> _readPassphrase() async {
|
|
||||||
final fromEnv = Platform.environment[e2ePassphraseEnv];
|
|
||||||
if (fromEnv != null && fromEnv.isNotEmpty) return fromEnv;
|
|
||||||
for (final file in [passphraseFile, sharedPasswordFile]) {
|
|
||||||
if (file != null && file.existsSync()) {
|
|
||||||
final text = (await file.readAsString()).trim();
|
|
||||||
if (text.isNotEmpty) return text;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Releases the log and the HTTP client.
|
|
||||||
Future<void> close() async {
|
|
||||||
_firebase.close();
|
|
||||||
await repository.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reads this install's node id, minting and persisting a uuid on first run.
|
|
||||||
///
|
|
||||||
/// Never a fixed name: two installs sharing an id would overwrite each
|
|
||||||
/// other's file under `todo-sync/notes/` and lose writes.
|
|
||||||
static Future<String> _nodeId(String dataDir) async {
|
|
||||||
final file = File(p.join(dataDir, nodeIdFileName));
|
|
||||||
if (file.existsSync()) {
|
|
||||||
final stored = (await file.readAsString()).trim();
|
|
||||||
if (stored.isNotEmpty) return stored;
|
|
||||||
}
|
|
||||||
final minted = const Uuid().v4();
|
|
||||||
await file.writeAsString('$minted\n');
|
|
||||||
return minted;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,39 +0,0 @@
|
|||||||
/// Usage text printed by `--help` and after a usage error.
|
|
||||||
const kUsage = r'''
|
|
||||||
Usage: dart run bin/todo_note.dart [options]
|
|
||||||
|
|
||||||
Adds a note to the todo app headlessly: pulls from Firebase RTDB, writes an
|
|
||||||
ordinary CRDT change as this install's own node, pushes, and prints the id.
|
|
||||||
A note with --repo is a repo task; one without is a plain idea.
|
|
||||||
|
|
||||||
--text <markdown> note text (first line = title); default: read stdin
|
|
||||||
--priority <p> low|medium|high (default medium)
|
|
||||||
--status <s> todo|in_progress|done|abandoned (default todo);
|
|
||||||
with --list/--search: show only that status
|
|
||||||
--repo <owner/name> repo task's repository, e.g. kuhyx/todo;
|
|
||||||
with --list/--search: show only that repo's tasks
|
|
||||||
--done-check <cmd> shell command, run from the repo root, exit 0 = done
|
|
||||||
--new-note with --repo: own note, not the shared one (an exact
|
|
||||||
title in another separate note merges into it)
|
|
||||||
--by <who> claude|kuhy
|
|
||||||
--list pull, then print live notes, one per line:
|
|
||||||
8-char id, status, priority, repo (- for none), title
|
|
||||||
--search <q> as --list, only notes whose text or repo contains q
|
|
||||||
--get <id> pull, then print one note in full (exit 1 if absent)
|
|
||||||
--delete <id> pull, tombstone the note, push
|
|
||||||
--set-status <id> <s> pull, change the note's status (as --status), push
|
|
||||||
--set-text <id> pull, replace the note's whole text with --text (or
|
|
||||||
stdin; first line = title), keep its other fields, push
|
|
||||||
--close <id> --evidence <s>
|
|
||||||
pull, set status done + evidence (commit sha + done
|
|
||||||
check exit code), push; refused without --evidence
|
|
||||||
--backfill-created-by [--dry-run]
|
|
||||||
pull, set created_by (claude|kuhy) on every note that
|
|
||||||
has none, push; --dry-run prints the plan only
|
|
||||||
--data-dir <dir> local log + node id (default
|
|
||||||
$XDG_DATA_HOME/todo-cli or ~/.local/share/todo-cli)
|
|
||||||
-h, --help this text
|
|
||||||
|
|
||||||
<id> is a full id or a unique prefix of at least 8 characters.
|
|
||||||
--list, --search and --get never push.
|
|
||||||
Exit codes: 0 ok, 1 sync/auth failure or note not found, 2 bad arguments.''';
|
|
||||||
@ -1,52 +0,0 @@
|
|||||||
/// The headless CLI's Firebase session, kept in a file of its own.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'dart:convert';
|
|
||||||
import 'dart:io';
|
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
|
|
||||||
/// A file-backed [FirebaseCredentialStore], seeded once from [seedFile].
|
|
||||||
///
|
|
||||||
/// [seedFile] is todo's desktop session (`~/.config/todo/firebase_auth.json`,
|
|
||||||
/// written by `crdt-sync/tool/seed_session.py --app todo`) and is only ever
|
|
||||||
/// read. Every write goes to [file], a private copy in the CLI's data dir.
|
|
||||||
/// That split matters: [FirebaseTokenProvider] clears its store when a refresh
|
|
||||||
/// token is revoked, and a shared file would let one bad CLI run delete the
|
|
||||||
/// seed the desktop wrapper provisions itself from.
|
|
||||||
class FileCredentialStore implements FirebaseCredentialStore {
|
|
||||||
/// Creates a store that persists to [file], falling back to [seedFile].
|
|
||||||
FileCredentialStore({required this.file, required this.seedFile});
|
|
||||||
|
|
||||||
/// The CLI's own copy, written on every token refresh.
|
|
||||||
final File file;
|
|
||||||
|
|
||||||
/// The read-only seed used until [file] exists.
|
|
||||||
final File seedFile;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<FirebaseCredentials?> load() async {
|
|
||||||
final source = file.existsSync() ? file : seedFile;
|
|
||||||
if (!source.existsSync()) return null;
|
|
||||||
final decoded = jsonDecode(await source.readAsString());
|
|
||||||
if (decoded is! Map<String, dynamic>) return null;
|
|
||||||
return FirebaseCredentials.fromJson(decoded);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> save(FirebaseCredentials credentials) async {
|
|
||||||
await file.parent.create(recursive: true);
|
|
||||||
final tmp = File('${file.path}.$pid.tmp');
|
|
||||||
// Owner-only before the token is written, not after: dart:io has no
|
|
||||||
// chmod, and a umask-default file would briefly expose a DB credential.
|
|
||||||
await tmp.writeAsString('');
|
|
||||||
await Process.run('chmod', ['600', tmp.path]);
|
|
||||||
await tmp.writeAsString(jsonEncode(credentials.toJson()));
|
|
||||||
await tmp.rename(file.path);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> clear() async {
|
|
||||||
if (file.existsSync()) await file.delete();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,78 +0,0 @@
|
|||||||
/// `bin/merge_repo_notes.dart`: collapse each repo's open notes into one.
|
|
||||||
/// Dry run unless `--apply`; stdout is the `old_id<TAB>kept_id<TAB>repo` map.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
import 'package:path/path.dart' as p;
|
|
||||||
import 'package:todo/cli/cli_runner.dart';
|
|
||||||
import 'package:todo/cli/cli_session.dart';
|
|
||||||
import 'package:todo/data/repo_note_merge.dart';
|
|
||||||
|
|
||||||
const _usage = 'usage: merge_repo_notes [--dry-run|--apply] [--data-dir D]';
|
|
||||||
|
|
||||||
/// Runs the merge for [argv]; returns the exit code.
|
|
||||||
Future<int> runMergeRepoNotes(
|
|
||||||
List<String> argv, {
|
|
||||||
required Map<String, String> env,
|
|
||||||
required StringSink out,
|
|
||||||
required StringSink err,
|
|
||||||
SessionOpener open = CliSession.open,
|
|
||||||
}) async {
|
|
||||||
var apply = false;
|
|
||||||
String? dataDir;
|
|
||||||
for (var i = 0; i < argv.length; i++) {
|
|
||||||
switch (argv[i]) {
|
|
||||||
case '--apply':
|
|
||||||
apply = true;
|
|
||||||
case '--dry-run':
|
|
||||||
apply = false;
|
|
||||||
case '--data-dir' when i + 1 < argv.length:
|
|
||||||
dataDir = argv[++i];
|
|
||||||
default:
|
|
||||||
err.writeln(_usage);
|
|
||||||
return 2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
CliSession? session;
|
|
||||||
try {
|
|
||||||
session = await open(
|
|
||||||
dataDir ?? defaultDataDir(env),
|
|
||||||
seedCredentials: p.join(
|
|
||||||
env['HOME'] ?? '',
|
|
||||||
'.config',
|
|
||||||
'todo',
|
|
||||||
'firebase_auth.json',
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await session.sync(push: apply);
|
|
||||||
final plan = planRepoMerges(await session.repository.listNotes());
|
|
||||||
for (final (:kept, :removed) in plan) {
|
|
||||||
if (apply) {
|
|
||||||
await session.repository.upsert(
|
|
||||||
kept.copyWith(updatedAt: DateTime.now()),
|
|
||||||
);
|
|
||||||
for (final n in removed) {
|
|
||||||
await session.repository.delete(n.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (final n in removed) {
|
|
||||||
out.writeln('${n.id}\t${kept.id}\t${kept.repo}');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
final deleted = plan.fold(0, (sum, m) => sum + m.removed.length);
|
|
||||||
err.writeln(
|
|
||||||
'${apply ? 'applied' : 'dry run'}: ${plan.length} repos, '
|
|
||||||
'$deleted notes deleted',
|
|
||||||
);
|
|
||||||
if (apply && plan.isNotEmpty && !(await session.sync(push: true)).pushed) {
|
|
||||||
err.writeln('error: saved locally but nothing was pushed');
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
} on RemoteSyncError catch (error) {
|
|
||||||
err.writeln('error: $error');
|
|
||||||
return 1;
|
|
||||||
} finally {
|
|
||||||
await session?.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,64 +0,0 @@
|
|||||||
import 'package:todo/cli/cli_args.dart';
|
|
||||||
import 'package:todo/data/note.dart';
|
|
||||||
|
|
||||||
const _minPrefix = 8;
|
|
||||||
|
|
||||||
/// No note, or more than one, matches an id argument; [message] says which.
|
|
||||||
class NoteLookupError extends FormatException {
|
|
||||||
NoteLookupError._(super.message);
|
|
||||||
|
|
||||||
@override
|
|
||||||
String toString() => message;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The note with id [ref], else the only one whose id starts with [ref].
|
|
||||||
Note findNote(Iterable<Note> notes, String ref) {
|
|
||||||
final exact = notes.where((n) => n.id == ref).firstOrNull;
|
|
||||||
if (exact != null) return exact;
|
|
||||||
if (ref.length < _minPrefix) {
|
|
||||||
throw NoteLookupError._(
|
|
||||||
'no live note with id $ref (an id prefix needs at least '
|
|
||||||
'$_minPrefix characters)',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
final matches = notes.where((n) => n.id.startsWith(ref)).toList();
|
|
||||||
if (matches.isEmpty) throw NoteLookupError._('no live note with id $ref');
|
|
||||||
if (matches.length > 1) {
|
|
||||||
throw NoteLookupError._(
|
|
||||||
'id prefix $ref matches ${matches.length} notes; give more of the id:\n'
|
|
||||||
'${matches.map((n) => ' ${n.id} ${_title(n)}').join('\n')}',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return matches.single;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `<8-char id>\t<status>\t<priority>\t<repo or ->\t<title>\t<created_by>`.
|
|
||||||
String listLine(Note note) => [
|
|
||||||
if (note.id.length <= _minPrefix)
|
|
||||||
note.id
|
|
||||||
else
|
|
||||||
note.id.substring(0, _minPrefix),
|
|
||||||
CliArgs.statusName(note.status),
|
|
||||||
note.priority.name,
|
|
||||||
note.repo ?? '-',
|
|
||||||
_title(note),
|
|
||||||
note.createdBy ?? 'kuhy',
|
|
||||||
].join('\t');
|
|
||||||
|
|
||||||
String _title(Note note) => note.text.split('\n').first;
|
|
||||||
|
|
||||||
/// The note's metadata lines, `---`, then its text.
|
|
||||||
String noteDetail(Note note) => [
|
|
||||||
'id: ${note.id}',
|
|
||||||
'priority: ${note.priority.name}',
|
|
||||||
'status: ${CliArgs.statusName(note.status)}',
|
|
||||||
'created: ${note.createdAt.toIso8601String()}',
|
|
||||||
'updated: ${note.updatedAt.toIso8601String()}',
|
|
||||||
if (note.repo case final v?) 'repo: $v',
|
|
||||||
if (note.doneCheck case final v?) 'done_check: $v',
|
|
||||||
if (note.by case final v?) 'by: $v',
|
|
||||||
if (note.evidence case final v?) 'evidence: $v',
|
|
||||||
'created_by: ${note.createdBy ?? 'kuhy'}',
|
|
||||||
'---',
|
|
||||||
note.text,
|
|
||||||
].join('\n');
|
|
||||||
@ -1,44 +0,0 @@
|
|||||||
/// A read-only view of a [RemoteStore], for the CLI's verification modes.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
|
|
||||||
/// Delegates every read to [inner] and silently drops every write.
|
|
||||||
///
|
|
||||||
/// Lets `--list` / `--get` run the app's own [SyncService] merge path without
|
|
||||||
/// publishing anything. Without it, each throwaway data dir (a fresh node id)
|
|
||||||
/// would leave a permanent full-log peer file in RTDB that every device then
|
|
||||||
/// downloads on every sync.
|
|
||||||
class PullOnlyStore implements RemoteStore, BulkMapReader {
|
|
||||||
/// Wraps [inner], which must also be able to read revision maps.
|
|
||||||
PullOnlyStore(this.inner);
|
|
||||||
|
|
||||||
/// The real backend reads go to.
|
|
||||||
final FirebaseRestClient inner;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<List<String>> listDirectory(String path) => inner.listDirectory(path);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<String?> getFileText(String path) => inner.getFileText(path);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<Map<String, String>> getStringMap(String path) =>
|
|
||||||
inner.getStringMap(path);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> putFileText(
|
|
||||||
String path,
|
|
||||||
String text, {
|
|
||||||
required String message,
|
|
||||||
}) async {}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> deleteFile(String path, {String message = ''}) async {}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<bool> canAccessRemote() => inner.canAccessRemote();
|
|
||||||
|
|
||||||
@override
|
|
||||||
void close() => inner.close();
|
|
||||||
}
|
|
||||||
@ -1,58 +0,0 @@
|
|||||||
import 'dart:async';
|
|
||||||
|
|
||||||
import 'package:http/http.dart' as http;
|
|
||||||
|
|
||||||
/// An HTTP client whose every request is bounded.
|
|
||||||
///
|
|
||||||
/// `package:http` has no timeout of its own, and neither do the Firebase and
|
|
||||||
/// token clients built on it: one dead connection (after boot, a network
|
|
||||||
/// blip) made a sync wait forever and wedged the MCP server's serial queue.
|
|
||||||
/// [timeout] bounds the wait for the response headers and then each gap
|
|
||||||
/// between body chunks, so a large body that keeps moving is never cut off.
|
|
||||||
class TimeoutClient extends http.BaseClient {
|
|
||||||
/// Wraps [_inner]; each wait fails with a [TimeoutException] after [timeout].
|
|
||||||
TimeoutClient(this._inner, {this.timeout = const Duration(seconds: 30)});
|
|
||||||
|
|
||||||
final http.Client _inner;
|
|
||||||
|
|
||||||
/// Longest wait for the headers, and for the next body chunk.
|
|
||||||
final Duration timeout;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<http.StreamedResponse> send(http.BaseRequest request) async {
|
|
||||||
final response = await _inner
|
|
||||||
.send(request)
|
|
||||||
.timeout(
|
|
||||||
timeout,
|
|
||||||
onTimeout: () => throw TimeoutException(
|
|
||||||
'${request.method} ${request.url.host} got no response',
|
|
||||||
timeout,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return http.StreamedResponse(
|
|
||||||
response.stream.timeout(
|
|
||||||
timeout,
|
|
||||||
onTimeout: (sink) {
|
|
||||||
sink
|
|
||||||
..addError(
|
|
||||||
TimeoutException(
|
|
||||||
'${request.method} ${request.url.host} body stalled',
|
|
||||||
timeout,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
..close();
|
|
||||||
},
|
|
||||||
),
|
|
||||||
response.statusCode,
|
|
||||||
contentLength: response.contentLength,
|
|
||||||
request: response.request,
|
|
||||||
headers: response.headers,
|
|
||||||
isRedirect: response.isRedirect,
|
|
||||||
persistentConnection: response.persistentConnection,
|
|
||||||
reasonPhrase: response.reasonPhrase,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
void close() => _inner.close();
|
|
||||||
}
|
|
||||||
@ -19,14 +19,10 @@ import 'package:shared_preferences/shared_preferences.dart';
|
|||||||
/// sibling to `changesets/<nodeId>.json`.
|
/// sibling to `changesets/<nodeId>.json`.
|
||||||
const String kAdvancedModeRemotePath = 'settings/advancedMode';
|
const String kAdvancedModeRemotePath = 'settings/advancedMode';
|
||||||
|
|
||||||
/// App-wide, non-sync preferences (`advancedMode`, `showClaudeNotes`).
|
/// App-wide, non-sync preferences (currently just `advancedMode`).
|
||||||
class AppSettings {
|
class AppSettings {
|
||||||
/// Creates an [AppSettings] from its stored fields.
|
/// Creates an [AppSettings] from its stored fields.
|
||||||
const AppSettings({
|
const AppSettings({required this.advancedMode, this.advancedModeUpdatedAt});
|
||||||
required this.advancedMode,
|
|
||||||
this.advancedModeUpdatedAt,
|
|
||||||
this.showClaudeNotes = false,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Whether the priority/status/template/mode chrome and the routine
|
/// Whether the priority/status/template/mode chrome and the routine
|
||||||
/// save/sync status text are shown. Off by default: casual capture needs
|
/// save/sync status text are shown. Off by default: casual capture needs
|
||||||
@ -39,11 +35,6 @@ class AppSettings {
|
|||||||
/// a value that has never round-tripped through Firebase.
|
/// a value that has never round-tripped through Firebase.
|
||||||
final DateTime? advancedModeUpdatedAt;
|
final DateTime? advancedModeUpdatedAt;
|
||||||
|
|
||||||
/// Whether the notes list shows notes Claude filed. Per device: it lives
|
|
||||||
/// only in this device's preferences and is never mirrored to Firebase.
|
|
||||||
final bool showClaudeNotes;
|
|
||||||
|
|
||||||
static const _kShowClaude = 'app.showClaudeNotes';
|
|
||||||
static const _kAdvancedMode = 'app.advancedMode';
|
static const _kAdvancedMode = 'app.advancedMode';
|
||||||
static const _kAdvancedModeUpdatedAt = 'app.advancedMode.updatedAt';
|
static const _kAdvancedModeUpdatedAt = 'app.advancedMode.updatedAt';
|
||||||
|
|
||||||
@ -53,7 +44,6 @@ class AppSettings {
|
|||||||
final updatedAtMillis = prefs.getInt(_kAdvancedModeUpdatedAt);
|
final updatedAtMillis = prefs.getInt(_kAdvancedModeUpdatedAt);
|
||||||
return AppSettings(
|
return AppSettings(
|
||||||
advancedMode: prefs.getBool(_kAdvancedMode) ?? false,
|
advancedMode: prefs.getBool(_kAdvancedMode) ?? false,
|
||||||
showClaudeNotes: prefs.getBool(_kShowClaude) ?? false,
|
|
||||||
advancedModeUpdatedAt: updatedAtMillis == null
|
advancedModeUpdatedAt: updatedAtMillis == null
|
||||||
? null
|
? null
|
||||||
: DateTime.fromMillisecondsSinceEpoch(updatedAtMillis),
|
: DateTime.fromMillisecondsSinceEpoch(updatedAtMillis),
|
||||||
@ -81,7 +71,6 @@ class AppSettings {
|
|||||||
final updated = AppSettings(
|
final updated = AppSettings(
|
||||||
advancedMode: value,
|
advancedMode: value,
|
||||||
advancedModeUpdatedAt: updatedAt,
|
advancedModeUpdatedAt: updatedAt,
|
||||||
showClaudeNotes: showClaudeNotes,
|
|
||||||
);
|
);
|
||||||
if (client != null) {
|
if (client != null) {
|
||||||
try {
|
try {
|
||||||
@ -100,17 +89,6 @@ class AppSettings {
|
|||||||
return updated;
|
return updated;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Persists the per-device Claude-notes choice; nothing leaves the device.
|
|
||||||
Future<AppSettings> withShowClaudeNotes({required bool value}) async {
|
|
||||||
final prefs = await SharedPreferences.getInstance();
|
|
||||||
await prefs.setBool(_kShowClaude, value);
|
|
||||||
return AppSettings(
|
|
||||||
advancedMode: advancedMode,
|
|
||||||
advancedModeUpdatedAt: advancedModeUpdatedAt,
|
|
||||||
showClaudeNotes: value,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Pulls the remote value from [client] and, if it is newer than the
|
/// Pulls the remote value from [client] and, if it is newer than the
|
||||||
/// local one, applies it locally and returns the reconciled settings.
|
/// local one, applies it locally and returns the reconciled settings.
|
||||||
/// Returns this instance unchanged when [client] is null, there is
|
/// Returns this instance unchanged when [client] is null, there is
|
||||||
@ -122,7 +100,9 @@ class AppSettings {
|
|||||||
try {
|
try {
|
||||||
final remote = await client.getStringMap(kAdvancedModeRemotePath);
|
final remote = await client.getStringMap(kAdvancedModeRemotePath);
|
||||||
if (!remote.containsKey('value')) return this;
|
if (!remote.containsKey('value')) return this;
|
||||||
final remoteUpdatedMillis = int.tryParse(remote['updatedAtMillis'] ?? '');
|
final remoteUpdatedMillis = int.tryParse(
|
||||||
|
remote['updatedAtMillis'] ?? '',
|
||||||
|
);
|
||||||
if (remoteUpdatedMillis == null) return this;
|
if (remoteUpdatedMillis == null) return this;
|
||||||
final remoteUpdatedAt = DateTime.fromMillisecondsSinceEpoch(
|
final remoteUpdatedAt = DateTime.fromMillisecondsSinceEpoch(
|
||||||
remoteUpdatedMillis,
|
remoteUpdatedMillis,
|
||||||
@ -130,7 +110,6 @@ class AppSettings {
|
|||||||
final candidate = AppSettings(
|
final candidate = AppSettings(
|
||||||
advancedMode: remote['value'] == 'true',
|
advancedMode: remote['value'] == 'true',
|
||||||
advancedModeUpdatedAt: remoteUpdatedAt,
|
advancedModeUpdatedAt: remoteUpdatedAt,
|
||||||
showClaudeNotes: showClaudeNotes,
|
|
||||||
);
|
);
|
||||||
final adopted = adopt(candidate);
|
final adopted = adopt(candidate);
|
||||||
if (identical(adopted, this)) return this;
|
if (identical(adopted, this)) return this;
|
||||||
|
|||||||
@ -1,44 +0,0 @@
|
|||||||
/// Who filed a note, for notes written before `created_by` existed.
|
|
||||||
///
|
|
||||||
/// The `created_at` field's clock names the node that last wrote it. The MCP
|
|
||||||
/// and the CLI are the only nodes Claude writes through, so a note created
|
|
||||||
/// there carries one of their node ids; anything else came from kuhy's own
|
|
||||||
/// devices.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
import 'package:todo/data/note_record.dart';
|
|
||||||
|
|
||||||
const _createdAt = 'created_at';
|
|
||||||
|
|
||||||
/// `claude` when [record]'s `created_at` was written by one of [claudeNodes],
|
|
||||||
/// else `kuhy`.
|
|
||||||
String classifyCreatedBy(Record record, Set<String> claudeNodes) {
|
|
||||||
final node = record.fields[_createdAt]?.$2.nodeId;
|
|
||||||
return node != null && claudeNodes.contains(node) ? 'claude' : 'kuhy';
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Live records of [log] with no `created_by` yet, mapped to their value.
|
|
||||||
Map<String, String> planCreatedByBackfill(Log log, Set<String> claudeNodes) => {
|
|
||||||
for (final record in log.values)
|
|
||||||
if (!record.deleted &&
|
|
||||||
((record.fields[kCreatedByField]?.$1 as String?) ?? '').isEmpty)
|
|
||||||
record.id: classifyCreatedBy(record, claudeNodes),
|
|
||||||
};
|
|
||||||
|
|
||||||
/// [incoming], carrying [existing]'s `created_by` when [incoming] has none.
|
|
||||||
///
|
|
||||||
/// A store replaces a record wholesale, so an edit that does not know the
|
|
||||||
/// field (an import of an old backup) would otherwise drop it locally.
|
|
||||||
Record keepCreatedBy(Record incoming, Record? existing) {
|
|
||||||
final kept = existing?.fields[kCreatedByField];
|
|
||||||
if (kept == null || incoming.fields.containsKey(kCreatedByField)) {
|
|
||||||
return incoming;
|
|
||||||
}
|
|
||||||
return Record(
|
|
||||||
id: incoming.id,
|
|
||||||
fields: {...incoming.fields, kCreatedByField: kept},
|
|
||||||
deleted: incoming.deleted,
|
|
||||||
deletedHlc: incoming.deletedHlc,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -73,7 +73,11 @@ class LegacySqliteMigration {
|
|||||||
}
|
}
|
||||||
// coverage:ignore-end
|
// coverage:ignore-end
|
||||||
|
|
||||||
static Future<void> _onUpgrade(CrdtTableExecutor db, int from, int to) async {
|
static Future<void> _onUpgrade(
|
||||||
|
CrdtTableExecutor db,
|
||||||
|
int from,
|
||||||
|
int to,
|
||||||
|
) async {
|
||||||
if (from < 2) {
|
if (from < 2) {
|
||||||
await db.execute(
|
await db.execute(
|
||||||
'ALTER TABLE notes ADD COLUMN status INTEGER NOT NULL DEFAULT 0',
|
'ALTER TABLE notes ADD COLUMN status INTEGER NOT NULL DEFAULT 0',
|
||||||
|
|||||||
@ -1,38 +0,0 @@
|
|||||||
/// A seeded, coalesced stream over the note log's change events.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'dart:async';
|
|
||||||
|
|
||||||
/// A stream that emits `compute()` when first listened to (the seed), then
|
|
||||||
/// again after [changes] fires. Seeding in `onListen` -- rather than lazily in
|
|
||||||
/// an `async*` body -- avoids a race where a write between `listen` and the
|
|
||||||
/// first generator tick would swallow the initial snapshot.
|
|
||||||
///
|
|
||||||
/// Re-emits are coalesced: the first change of a burst arms one
|
|
||||||
/// zero-duration timer and every further change before it fires is absorbed,
|
|
||||||
/// so N back-to-back changes cost ONE `compute()` carrying the latest state
|
|
||||||
/// instead of N full re-queries (each of which repaints the whole list).
|
|
||||||
/// The timer fires on the next event-loop turn, so tests stay deterministic
|
|
||||||
/// under `pumpEventQueue` and the widget tester's `pump`.
|
|
||||||
Stream<T> watchLog<T>(Stream<void> changes, T Function() compute) {
|
|
||||||
StreamSubscription<void>? sub;
|
|
||||||
Timer? pending;
|
|
||||||
late final StreamController<T> controller;
|
|
||||||
controller = StreamController<T>(
|
|
||||||
onListen: () {
|
|
||||||
controller.add(compute());
|
|
||||||
sub = changes.listen((_) {
|
|
||||||
pending ??= Timer(Duration.zero, () {
|
|
||||||
pending = null;
|
|
||||||
controller.add(compute());
|
|
||||||
});
|
|
||||||
});
|
|
||||||
},
|
|
||||||
onCancel: () {
|
|
||||||
pending?.cancel();
|
|
||||||
pending = null;
|
|
||||||
return sub?.cancel();
|
|
||||||
},
|
|
||||||
);
|
|
||||||
return controller.stream;
|
|
||||||
}
|
|
||||||
@ -1,8 +1,9 @@
|
|||||||
/// Domain model for a single idea/note.
|
/// Domain model for a single idea/note.
|
||||||
///
|
///
|
||||||
/// Notes are stored as crdt_sync records (see [NoteRepository] and
|
/// Notes are stored locally in a CRDT-backed SQLite table (see
|
||||||
/// `note_record.dart`); the clocks and tombstones live there, the fields
|
/// [NoteRepository]). The CRDT layer manages its own metadata columns
|
||||||
/// here are the user-facing data only.
|
/// (`hlc`, `node_id`, `modified`, `is_deleted`); the fields here are the
|
||||||
|
/// user-facing data only.
|
||||||
library;
|
library;
|
||||||
|
|
||||||
/// Priority tier for a note, used for sorting and visual grouping.
|
/// Priority tier for a note, used for sorting and visual grouping.
|
||||||
@ -76,16 +77,7 @@ enum Status {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The values the optional `by` and `created_by` fields may hold.
|
|
||||||
const Set<String> kNoteAuthors = {'claude', 'kuhy'};
|
|
||||||
|
|
||||||
/// An immutable idea/note record.
|
/// An immutable idea/note record.
|
||||||
///
|
|
||||||
/// A note with a [repo] is a *repo task* (an outstanding piece of work in
|
|
||||||
/// that repository, closable with [evidence]); one without is a plain idea.
|
|
||||||
/// The four task fields are optional and set-once in practice: they are
|
|
||||||
/// written only when a user or the CLI sets them, never by ordinary edits of
|
|
||||||
/// an idea, which keeps such edits wire-identical to the v3 build.
|
|
||||||
class Note {
|
class Note {
|
||||||
/// Creates a [Note] from its stored fields.
|
/// Creates a [Note] from its stored fields.
|
||||||
const Note({
|
const Note({
|
||||||
@ -95,11 +87,6 @@ class Note {
|
|||||||
required this.status,
|
required this.status,
|
||||||
required this.createdAt,
|
required this.createdAt,
|
||||||
required this.updatedAt,
|
required this.updatedAt,
|
||||||
this.repo,
|
|
||||||
this.doneCheck,
|
|
||||||
this.by,
|
|
||||||
this.evidence,
|
|
||||||
this.createdBy,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
/// Builds a [Note] from a raw CRDT query row.
|
/// Builds a [Note] from a raw CRDT query row.
|
||||||
@ -135,41 +122,12 @@ class Note {
|
|||||||
/// When the note's content was last modified locally.
|
/// When the note's content was last modified locally.
|
||||||
final DateTime updatedAt;
|
final DateTime updatedAt;
|
||||||
|
|
||||||
/// Repository a task belongs to (`kuhyx/<name>`); null for a plain idea.
|
|
||||||
final String? repo;
|
|
||||||
|
|
||||||
/// Shell command, run from the repo root, whose exit 0 proves the task done.
|
|
||||||
final String? doneCheck;
|
|
||||||
|
|
||||||
/// Who does the task: one of [kNoteAuthors].
|
|
||||||
final String? by;
|
|
||||||
|
|
||||||
/// Proof the task was closed (commit sha + the done check's exit code).
|
|
||||||
final String? evidence;
|
|
||||||
|
|
||||||
/// Who filed the note: one of [kNoteAuthors]; null (older notes) means kuhy.
|
|
||||||
final String? createdBy;
|
|
||||||
|
|
||||||
/// Whether Claude filed this note (hidden by default, sorted last).
|
|
||||||
bool get isClaudeMade => createdBy == 'claude';
|
|
||||||
|
|
||||||
/// Whether this note is a repo task rather than a plain idea.
|
|
||||||
bool get isRepoTask => repo != null;
|
|
||||||
|
|
||||||
/// The repo without its owner ("kartka" for "kuhyx/kartka"), or null.
|
|
||||||
String? get repoName => repo?.split('/').last;
|
|
||||||
|
|
||||||
/// Returns a copy with selected fields replaced.
|
/// Returns a copy with selected fields replaced.
|
||||||
Note copyWith({
|
Note copyWith({
|
||||||
String? text,
|
String? text,
|
||||||
Priority? priority,
|
Priority? priority,
|
||||||
Status? status,
|
Status? status,
|
||||||
DateTime? updatedAt,
|
DateTime? updatedAt,
|
||||||
String? repo,
|
|
||||||
String? doneCheck,
|
|
||||||
String? by,
|
|
||||||
String? evidence,
|
|
||||||
String? createdBy,
|
|
||||||
}) {
|
}) {
|
||||||
return Note(
|
return Note(
|
||||||
id: id,
|
id: id,
|
||||||
@ -178,11 +136,6 @@ class Note {
|
|||||||
status: status ?? this.status,
|
status: status ?? this.status,
|
||||||
createdAt: createdAt,
|
createdAt: createdAt,
|
||||||
updatedAt: updatedAt ?? this.updatedAt,
|
updatedAt: updatedAt ?? this.updatedAt,
|
||||||
repo: repo ?? this.repo,
|
|
||||||
doneCheck: doneCheck ?? this.doneCheck,
|
|
||||||
by: by ?? this.by,
|
|
||||||
evidence: evidence ?? this.evidence,
|
|
||||||
createdBy: createdBy ?? this.createdBy,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,63 +0,0 @@
|
|||||||
/// Partial logs for the multi-note writes: merged in one store write.
|
|
||||||
///
|
|
||||||
/// Each write re-serialises the whole log (over a megabyte on a real
|
|
||||||
/// device), so a bulk action must be one partial log merged once, never one
|
|
||||||
/// upsert per note. Merging is per field, so a field left out keeps its value
|
|
||||||
/// and its clock (`created_by` included).
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
import 'package:todo/data/note.dart';
|
|
||||||
import 'package:todo/data/note_record.dart';
|
|
||||||
|
|
||||||
/// Partial records setting [priority] and/or [status] on the live notes of
|
|
||||||
/// [log] among [ids], all at [hlc].
|
|
||||||
///
|
|
||||||
/// Only fields whose value changes are written, plus `updated_at` = [now]
|
|
||||||
/// (so "last updated" sorting and newer-wins import see the edit). A note
|
|
||||||
/// with nothing to change, an unknown id and a deleted note are left out.
|
|
||||||
Log planBulkUpdate(
|
|
||||||
Log log,
|
|
||||||
Set<String> ids, {
|
|
||||||
required Hlc hlc,
|
|
||||||
required DateTime now,
|
|
||||||
Priority? priority,
|
|
||||||
Status? status,
|
|
||||||
}) {
|
|
||||||
final plan = <String, Record>{};
|
|
||||||
for (final id in ids) {
|
|
||||||
final current = log[id];
|
|
||||||
if (current == null || current.deleted) continue;
|
|
||||||
final note = noteFromRecord(current);
|
|
||||||
final next = note.copyWith(priority: priority, status: status);
|
|
||||||
if (next.priority == note.priority && next.status == note.status) continue;
|
|
||||||
// Generated against generated, never against the stored text: a peer's
|
|
||||||
// `...00Z` (or a web build's millisecond date) would otherwise read as
|
|
||||||
// a change and get a fresh clock, erasing the `created_at` node signal.
|
|
||||||
final before = noteFields(note, hlc);
|
|
||||||
plan[id] = Record(
|
|
||||||
id: id,
|
|
||||||
fields: {
|
|
||||||
for (final MapEntry(:key, :value) in noteFields(
|
|
||||||
next.copyWith(updatedAt: now),
|
|
||||||
hlc,
|
|
||||||
).entries)
|
|
||||||
if (before[key]?.$1 != value.$1) key: value,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return plan;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// [note] at [hlc] plus a tombstone for each live note of [log] in
|
|
||||||
/// [removed] (other than [note] itself).
|
|
||||||
///
|
|
||||||
/// A merge, not a replace: a field [note] leaves unset keeps its stored
|
|
||||||
/// value, so this suits notes that only gain content (the repo note an
|
|
||||||
/// assign appends to), not edits that clear a field.
|
|
||||||
Log planReplace(Log log, Note note, Iterable<String> removed, Hlc hlc) => {
|
|
||||||
for (final id in removed)
|
|
||||||
if (log[id] case final r? when !r.deleted && id != note.id)
|
|
||||||
id: Record(id: id, fields: const {}, deleted: true, deletedHlc: hlc),
|
|
||||||
note.id: Record(id: note.id, fields: noteFields(note, hlc)),
|
|
||||||
};
|
|
||||||
@ -35,9 +35,6 @@ class NoteFilter {
|
|||||||
this.query = '',
|
this.query = '',
|
||||||
this.priorities = const {},
|
this.priorities = const {},
|
||||||
this.statuses = const {},
|
this.statuses = const {},
|
||||||
this.repo,
|
|
||||||
this.repoTasksOnly = false,
|
|
||||||
this.hideClaude = false,
|
|
||||||
this.createdFrom,
|
this.createdFrom,
|
||||||
this.createdTo,
|
this.createdTo,
|
||||||
this.updatedFrom,
|
this.updatedFrom,
|
||||||
@ -53,16 +50,6 @@ class NoteFilter {
|
|||||||
/// Notes must have one of these statuses. Empty means "any status".
|
/// Notes must have one of these statuses. Empty means "any status".
|
||||||
final Set<Status> statuses;
|
final Set<Status> statuses;
|
||||||
|
|
||||||
/// Only notes whose repo equals this. Null means any repo (or none).
|
|
||||||
final String? repo;
|
|
||||||
|
|
||||||
/// Only notes that have a repo (repo tasks). Ideas are excluded.
|
|
||||||
final bool repoTasksOnly;
|
|
||||||
|
|
||||||
/// Leave out notes Claude filed. A view preference rather than a user
|
|
||||||
/// facet, so it never counts toward [isEmpty] or [activeCount].
|
|
||||||
final bool hideClaude;
|
|
||||||
|
|
||||||
/// Inclusive lower bound (by calendar day) on the creation date.
|
/// Inclusive lower bound (by calendar day) on the creation date.
|
||||||
final DateTime? createdFrom;
|
final DateTime? createdFrom;
|
||||||
|
|
||||||
@ -80,8 +67,6 @@ class NoteFilter {
|
|||||||
query.trim().isEmpty &&
|
query.trim().isEmpty &&
|
||||||
priorities.isEmpty &&
|
priorities.isEmpty &&
|
||||||
statuses.isEmpty &&
|
statuses.isEmpty &&
|
||||||
repo == null &&
|
|
||||||
!repoTasksOnly &&
|
|
||||||
createdFrom == null &&
|
createdFrom == null &&
|
||||||
createdTo == null &&
|
createdTo == null &&
|
||||||
updatedFrom == null &&
|
updatedFrom == null &&
|
||||||
@ -93,8 +78,6 @@ class NoteFilter {
|
|||||||
if (query.trim().isNotEmpty) n++;
|
if (query.trim().isNotEmpty) n++;
|
||||||
if (priorities.isNotEmpty) n++;
|
if (priorities.isNotEmpty) n++;
|
||||||
if (statuses.isNotEmpty) n++;
|
if (statuses.isNotEmpty) n++;
|
||||||
if (repo != null) n++;
|
|
||||||
if (repoTasksOnly) n++;
|
|
||||||
if (createdFrom != null || createdTo != null) n++;
|
if (createdFrom != null || createdTo != null) n++;
|
||||||
if (updatedFrom != null || updatedTo != null) n++;
|
if (updatedFrom != null || updatedTo != null) n++;
|
||||||
return n;
|
return n;
|
||||||
@ -107,9 +90,6 @@ class NoteFilter {
|
|||||||
String? query,
|
String? query,
|
||||||
Set<Priority>? priorities,
|
Set<Priority>? priorities,
|
||||||
Set<Status>? statuses,
|
Set<Status>? statuses,
|
||||||
String? repo,
|
|
||||||
bool? repoTasksOnly,
|
|
||||||
bool? hideClaude,
|
|
||||||
DateTime? createdFrom,
|
DateTime? createdFrom,
|
||||||
DateTime? createdTo,
|
DateTime? createdTo,
|
||||||
DateTime? updatedFrom,
|
DateTime? updatedFrom,
|
||||||
@ -121,9 +101,6 @@ class NoteFilter {
|
|||||||
query: query ?? this.query,
|
query: query ?? this.query,
|
||||||
priorities: priorities ?? this.priorities,
|
priorities: priorities ?? this.priorities,
|
||||||
statuses: statuses ?? this.statuses,
|
statuses: statuses ?? this.statuses,
|
||||||
repo: repo ?? this.repo,
|
|
||||||
repoTasksOnly: repoTasksOnly ?? this.repoTasksOnly,
|
|
||||||
hideClaude: hideClaude ?? this.hideClaude,
|
|
||||||
createdFrom: clearCreated ? null : (createdFrom ?? this.createdFrom),
|
createdFrom: clearCreated ? null : (createdFrom ?? this.createdFrom),
|
||||||
createdTo: clearCreated ? null : (createdTo ?? this.createdTo),
|
createdTo: clearCreated ? null : (createdTo ?? this.createdTo),
|
||||||
updatedFrom: clearUpdated ? null : (updatedFrom ?? this.updatedFrom),
|
updatedFrom: clearUpdated ? null : (updatedFrom ?? this.updatedFrom),
|
||||||
@ -138,14 +115,9 @@ class NoteFilter {
|
|||||||
/// empty priority set means "any priority", not "no priorities".
|
/// empty priority set means "any priority", not "no priorities".
|
||||||
bool matchesFilter(Note note, NoteFilter filter) {
|
bool matchesFilter(Note note, NoteFilter filter) {
|
||||||
final query = filter.query.trim().toLowerCase();
|
final query = filter.query.trim().toLowerCase();
|
||||||
if (query.isNotEmpty &&
|
if (query.isNotEmpty && !note.text.toLowerCase().contains(query)) {
|
||||||
!note.text.toLowerCase().contains(query) &&
|
|
||||||
!(note.repo?.toLowerCase().contains(query) ?? false)) {
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (filter.repo != null && note.repo != filter.repo) return false;
|
|
||||||
if (filter.repoTasksOnly && note.repo == null) return false;
|
|
||||||
if (filter.hideClaude && note.isClaudeMade) return false;
|
|
||||||
if (filter.priorities.isNotEmpty &&
|
if (filter.priorities.isNotEmpty &&
|
||||||
!filter.priorities.contains(note.priority)) {
|
!filter.priorities.contains(note.priority)) {
|
||||||
return false;
|
return false;
|
||||||
@ -173,17 +145,8 @@ bool _withinDays(DateTime value, DateTime? from, DateTime? to) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The comparator implementing [sort]: human-made notes first, Claude-made
|
/// The comparator implementing [sort].
|
||||||
/// ones after, and [sort] orders each group.
|
|
||||||
Comparator<Note> comparatorFor(NoteSort sort) {
|
Comparator<Note> comparatorFor(NoteSort sort) {
|
||||||
final within = _within(sort);
|
|
||||||
return (a, b) {
|
|
||||||
if (a.isClaudeMade != b.isClaudeMade) return a.isClaudeMade ? 1 : -1;
|
|
||||||
return within(a, b);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
Comparator<Note> _within(NoteSort sort) {
|
|
||||||
switch (sort) {
|
switch (sort) {
|
||||||
case NoteSort.createdDesc:
|
case NoteSort.createdDesc:
|
||||||
return (a, b) => b.createdAt.compareTo(a.createdAt);
|
return (a, b) => b.createdAt.compareTo(a.createdAt);
|
||||||
|
|||||||
@ -1,60 +0,0 @@
|
|||||||
/// Note <-> crdt_sync [Record] mapping; re-exported by `note_repository.dart`.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
|
||||||
import 'package:todo/data/note.dart';
|
|
||||||
|
|
||||||
const _text = 'text';
|
|
||||||
const _priority = 'priority';
|
|
||||||
const _status = 'status';
|
|
||||||
const _createdAt = 'created_at';
|
|
||||||
const _updatedAt = 'updated_at';
|
|
||||||
const _repo = 'repo';
|
|
||||||
const _doneCheck = 'done_check';
|
|
||||||
const _by = 'by';
|
|
||||||
const _evidence = 'evidence';
|
|
||||||
|
|
||||||
/// Record field naming who filed the note (`kuhy` or `claude`).
|
|
||||||
const kCreatedByField = 'created_by';
|
|
||||||
|
|
||||||
/// Record fields for [note], all at [hlc]. Unset task fields are omitted, so
|
|
||||||
/// an idea's record is exactly the v3 field set (and cannot clear a peer's).
|
|
||||||
Map<String, Field> noteFields(Note note, Hlc hlc) => {
|
|
||||||
_text: (note.text, hlc),
|
|
||||||
_priority: (note.priority.value, hlc),
|
|
||||||
_status: (note.status.value, hlc),
|
|
||||||
_createdAt: (note.createdAt.toIso8601String(), hlc),
|
|
||||||
_updatedAt: (note.updatedAt.toIso8601String(), hlc),
|
|
||||||
if (note.repo case final v?) _repo: (v, hlc),
|
|
||||||
if (note.doneCheck case final v?) _doneCheck: (v, hlc),
|
|
||||||
if (note.by case final v?) _by: (v, hlc),
|
|
||||||
if (note.evidence case final v?) _evidence: (v, hlc),
|
|
||||||
if (note.createdBy case final v?) kCreatedByField: (v, hlc),
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Reads [record] as a [Note], ignoring unknown fields.
|
|
||||||
Note noteFromRecord(Record record) {
|
|
||||||
final fields = record.fields;
|
|
||||||
String? str(String name) => fields[name]?.$1 as String?;
|
|
||||||
// '' is how a peer clears a task field: omitting it never clears.
|
|
||||||
String? task(String name) => switch (str(name)) {
|
|
||||||
'' => null,
|
|
||||||
final v => v,
|
|
||||||
};
|
|
||||||
return Note(
|
|
||||||
id: record.id,
|
|
||||||
text: str(_text) ?? '',
|
|
||||||
priority: Priority.fromValue(fields[_priority]?.$1 as int?),
|
|
||||||
status: Status.fromValue(fields[_status]?.$1 as int?),
|
|
||||||
createdAt: _parseDate(str(_createdAt)),
|
|
||||||
updatedAt: _parseDate(str(_updatedAt)),
|
|
||||||
repo: task(_repo),
|
|
||||||
doneCheck: task(_doneCheck),
|
|
||||||
by: task(_by),
|
|
||||||
evidence: task(_evidence),
|
|
||||||
createdBy: task(kCreatedByField),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
DateTime _parseDate(String? iso) =>
|
|
||||||
iso == null ? DateTime.fromMillisecondsSinceEpoch(0) : DateTime.parse(iso);
|
|
||||||
@ -1,15 +1,12 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
import 'package:todo/data/created_by_backfill.dart';
|
|
||||||
import 'package:todo/data/log_watch.dart';
|
|
||||||
import 'package:todo/data/note.dart';
|
import 'package:todo/data/note.dart';
|
||||||
import 'package:todo/data/note_bulk.dart';
|
|
||||||
import 'package:todo/data/note_import.dart';
|
import 'package:todo/data/note_import.dart';
|
||||||
import 'package:todo/data/note_query.dart';
|
import 'package:todo/data/note_query.dart';
|
||||||
import 'package:todo/data/note_record.dart';
|
|
||||||
|
|
||||||
export 'package:todo/data/note_import.dart';
|
export 'package:todo/data/note_import.dart';
|
||||||
export 'package:todo/data/note_query.dart';
|
export 'package:todo/data/note_query.dart';
|
||||||
export 'package:todo/data/note_record.dart';
|
|
||||||
|
|
||||||
// Deliberately free of `dart:io`: the desktop app is a web build, and a single
|
// Deliberately free of `dart:io`: the desktop app is a web build, and a single
|
||||||
// `dart:io` import anywhere in the graph makes the whole app fail to compile
|
// `dart:io` import anywhere in the graph makes the whole app fail to compile
|
||||||
@ -38,6 +35,14 @@ class NoteRepository {
|
|||||||
/// transitively [importNotes]). Emits `void` — pull the data on demand.
|
/// transitively [importNotes]). Emits `void` — pull the data on demand.
|
||||||
Stream<void> get changes => _store.changes;
|
Stream<void> get changes => _store.changes;
|
||||||
|
|
||||||
|
// Field names inside each note [Record]; kept identical to the legacy SQL
|
||||||
|
// column names so a migrated log round-trips through the same [Note] mapping.
|
||||||
|
static const _fText = 'text';
|
||||||
|
static const _fPriority = 'priority';
|
||||||
|
static const _fStatus = 'status';
|
||||||
|
static const _fCreatedAt = 'created_at';
|
||||||
|
static const _fUpdatedAt = 'updated_at';
|
||||||
|
|
||||||
/// SharedPreferences key holding this device's stable CRDT node id.
|
/// SharedPreferences key holding this device's stable CRDT node id.
|
||||||
static const kNodeId = 'crdt.nodeId';
|
static const kNodeId = 'crdt.nodeId';
|
||||||
|
|
||||||
@ -103,7 +108,7 @@ class NoteRepository {
|
|||||||
);
|
);
|
||||||
return Record(
|
return Record(
|
||||||
id: note.id,
|
id: note.id,
|
||||||
fields: noteFields(note, hlc),
|
fields: _fieldsFor(note, hlc),
|
||||||
deleted: deleted,
|
deleted: deleted,
|
||||||
deletedHlc: deleted ? hlc : null,
|
deletedHlc: deleted ? hlc : null,
|
||||||
);
|
);
|
||||||
@ -115,57 +120,9 @@ class NoteRepository {
|
|||||||
/// character-by-character autosave: it is cheap and idempotent. All fields
|
/// character-by-character autosave: it is cheap and idempotent. All fields
|
||||||
/// share one fresh monotonic clock (they are written together).
|
/// share one fresh monotonic clock (they are written together).
|
||||||
Future<void> upsert(Note note) async {
|
Future<void> upsert(Note note) async {
|
||||||
await _put(Record(id: note.id, fields: noteFields(note, _store.nextHlc())));
|
await _store.upsert(
|
||||||
}
|
Record(id: note.id, fields: _fieldsFor(note, _store.nextHlc())),
|
||||||
|
);
|
||||||
Future<void> _put(Record record) =>
|
|
||||||
_store.upsert(keepCreatedBy(record, _store.get(record.id)));
|
|
||||||
|
|
||||||
/// Sets `created_by` on every live note that has none, from the node that
|
|
||||||
/// wrote its `created_at` (see [classifyCreatedBy]); returns id -> value.
|
|
||||||
///
|
|
||||||
/// Writes only that field, at a fresh clock, so no other field's clock
|
|
||||||
/// moves (a rewrite of `created_at` would erase the signal itself). With
|
|
||||||
/// [dryRun] nothing is written.
|
|
||||||
Future<Map<String, String>> backfillCreatedBy(
|
|
||||||
Set<String> claudeNodes, {
|
|
||||||
bool dryRun = false,
|
|
||||||
}) async {
|
|
||||||
final plan = planCreatedByBackfill(_store.snapshot(), claudeNodes);
|
|
||||||
if (dryRun || plan.isEmpty) return plan;
|
|
||||||
final hlc = _store.nextHlc();
|
|
||||||
await _patch({
|
|
||||||
for (final e in plan.entries)
|
|
||||||
e.key: Record(id: e.key, fields: {kCreatedByField: (e.value, hlc)}),
|
|
||||||
});
|
|
||||||
return plan;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets [priority] and/or [status] on the live notes [ids] in ONE store
|
|
||||||
/// write (see [planBulkUpdate]); a no-op when nothing changes.
|
|
||||||
Future<void> bulkUpdate(
|
|
||||||
Set<String> ids, {
|
|
||||||
Priority? priority,
|
|
||||||
Status? status,
|
|
||||||
}) => _patch(
|
|
||||||
planBulkUpdate(
|
|
||||||
_store.snapshot(),
|
|
||||||
ids,
|
|
||||||
hlc: _store.nextHlc(),
|
|
||||||
now: DateTime.now(),
|
|
||||||
priority: priority,
|
|
||||||
status: status,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
/// Saves [note] and deletes [removed] in ONE store write ([planReplace]).
|
|
||||||
Future<void> saveReplacing(Note note, Iterable<String> removed) =>
|
|
||||||
_patch(planReplace(_store.snapshot(), note, removed, _store.nextHlc()));
|
|
||||||
|
|
||||||
/// Merges a partial log in one write: untouched fields keep their clocks.
|
|
||||||
Future<void> _patch(Log partial) async {
|
|
||||||
if (partial.isEmpty) return;
|
|
||||||
await _store.replaceAll(mergeLogs(_store.snapshot(), partial));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Soft-deletes a note. The log keeps a sticky tombstone so the deletion
|
/// Soft-deletes a note. The log keeps a sticky tombstone so the deletion
|
||||||
@ -191,10 +148,10 @@ class NoteRepository {
|
|||||||
// the import wins locally; the clock decides whether it wins on *other*
|
// the import wins locally; the clock decides whether it wins on *other*
|
||||||
// devices, and an import must not win there simply by being recent.
|
// devices, and an import must not win there simply by being recent.
|
||||||
if (local == null) {
|
if (local == null) {
|
||||||
await _put(recordAtNoteTime(note, _nodeId));
|
await _store.upsert(recordAtNoteTime(note, _nodeId));
|
||||||
added++;
|
added++;
|
||||||
} else if (note.updatedAt.isAfter(local.updatedAt)) {
|
} else if (note.updatedAt.isAfter(local.updatedAt)) {
|
||||||
await _put(recordAtNoteTime(note, _nodeId));
|
await _store.upsert(recordAtNoteTime(note, _nodeId));
|
||||||
updated++;
|
updated++;
|
||||||
} else {
|
} else {
|
||||||
skipped++;
|
skipped++;
|
||||||
@ -214,10 +171,27 @@ class NoteRepository {
|
|||||||
Stream<List<Note>> watchNotes({
|
Stream<List<Note>> watchNotes({
|
||||||
NoteSort sort = NoteSort.priorityDesc,
|
NoteSort sort = NoteSort.priorityDesc,
|
||||||
NoteFilter filter = const NoteFilter(),
|
NoteFilter filter = const NoteFilter(),
|
||||||
}) => watchLog(_store.changes, () => _query(sort, filter));
|
}) => _watch(() => _query(sort, filter));
|
||||||
|
|
||||||
/// Emits the live count of non-deleted notes immediately and on each change.
|
/// Emits the live count of non-deleted notes immediately and on each change.
|
||||||
Stream<int> watchCount() => watchLog(_store.changes, _liveCount);
|
Stream<int> watchCount() => _watch(_liveCount);
|
||||||
|
|
||||||
|
/// A stream that emits `compute()` synchronously when first listened to (the
|
||||||
|
/// seed), then again on every log change. Seeding in `onListen` — rather than
|
||||||
|
/// lazily in an `async*` body — avoids a race where a write between `listen`
|
||||||
|
/// and the first generator tick would swallow the initial snapshot.
|
||||||
|
Stream<T> _watch<T>(T Function() compute) {
|
||||||
|
StreamSubscription<void>? sub;
|
||||||
|
late final StreamController<T> controller;
|
||||||
|
controller = StreamController<T>(
|
||||||
|
onListen: () {
|
||||||
|
controller.add(compute());
|
||||||
|
sub = _store.changes.listen((_) => controller.add(compute()));
|
||||||
|
},
|
||||||
|
onCancel: () => sub?.cancel(),
|
||||||
|
);
|
||||||
|
return controller.stream;
|
||||||
|
}
|
||||||
|
|
||||||
/// This device's stable node id. Names its file in the sync repo so two
|
/// This device's stable node id. Names its file in the sync repo so two
|
||||||
/// devices never write the same path.
|
/// devices never write the same path.
|
||||||
@ -235,10 +209,34 @@ class NoteRepository {
|
|||||||
/// Closes the underlying log and its change stream.
|
/// Closes the underlying log and its change stream.
|
||||||
Future<void> close() => _store.close();
|
Future<void> close() => _store.close();
|
||||||
|
|
||||||
// --- querying (the note <-> record mapping is in note_record.dart) --------
|
// --- note <-> record mapping & querying ------------------------------------
|
||||||
|
|
||||||
|
static Map<String, Field> _fieldsFor(Note note, Hlc hlc) => {
|
||||||
|
_fText: (note.text, hlc),
|
||||||
|
_fPriority: (note.priority.value, hlc),
|
||||||
|
_fStatus: (note.status.value, hlc),
|
||||||
|
_fCreatedAt: (note.createdAt.toIso8601String(), hlc),
|
||||||
|
_fUpdatedAt: (note.updatedAt.toIso8601String(), hlc),
|
||||||
|
};
|
||||||
|
|
||||||
|
Note _toNote(Record record) {
|
||||||
|
final fields = record.fields;
|
||||||
|
return Note(
|
||||||
|
id: record.id,
|
||||||
|
text: fields[_fText]?.$1 as String? ?? '',
|
||||||
|
priority: Priority.fromValue(fields[_fPriority]?.$1 as int?),
|
||||||
|
status: Status.fromValue(fields[_fStatus]?.$1 as int?),
|
||||||
|
createdAt: _parseDate(fields[_fCreatedAt]?.$1 as String?),
|
||||||
|
updatedAt: _parseDate(fields[_fUpdatedAt]?.$1 as String?),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static DateTime _parseDate(String? iso) => iso == null
|
||||||
|
? DateTime.fromMillisecondsSinceEpoch(0)
|
||||||
|
: DateTime.parse(iso);
|
||||||
|
|
||||||
Iterable<Note> _liveNotes() =>
|
Iterable<Note> _liveNotes() =>
|
||||||
_store.values.where((r) => !r.deleted).map(noteFromRecord);
|
_store.values.where((r) => !r.deleted).map(_toNote);
|
||||||
|
|
||||||
int _liveCount() => _store.values.where((r) => !r.deleted).length;
|
int _liveCount() => _store.values.where((r) => !r.deleted).length;
|
||||||
|
|
||||||
|
|||||||
@ -17,8 +17,6 @@
|
|||||||
library;
|
library;
|
||||||
|
|
||||||
import 'package:todo/data/note_template.dart';
|
import 'package:todo/data/note_template.dart';
|
||||||
import 'package:todo/images/attachment_links.dart';
|
|
||||||
import 'package:todo/images/attachment_ref.dart';
|
|
||||||
|
|
||||||
/// Matches a single `http(s)://…` token.
|
/// Matches a single `http(s)://…` token.
|
||||||
final RegExp _linkPattern = RegExp(r'^https?://\S+$');
|
final RegExp _linkPattern = RegExp(r'^https?://\S+$');
|
||||||
@ -142,28 +140,14 @@ ParsedNote parse(NoteTemplate template, String text) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The note's display title: the `#` heading text without its `#` marker, or
|
/// The note's display title: the `#` heading text without its `#` marker, or
|
||||||
/// the first non-empty line for freeform notes. Attachment lines are skipped
|
/// the first non-empty line for freeform notes.
|
||||||
/// (a 120-char dufs URL is no title); a note of nothing but attachments is
|
|
||||||
/// titled by their count, or by the file's name when it holds just one.
|
|
||||||
String noteTitle(String text) {
|
String noteTitle(String text) {
|
||||||
final attachments = <Attachment>[];
|
|
||||||
for (final line in text.split('\n')) {
|
for (final line in text.split('\n')) {
|
||||||
final trimmed = line.trim();
|
final trimmed = line.trim();
|
||||||
if (trimmed.isEmpty) continue;
|
if (trimmed.isEmpty) continue;
|
||||||
if (attachmentOfLine(trimmed) case final attachment?) {
|
|
||||||
attachments.add(attachment);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
return trimmed.replaceFirst(RegExp(r'^#+\s*'), '');
|
return trimmed.replaceFirst(RegExp(r'^#+\s*'), '');
|
||||||
}
|
}
|
||||||
final images = attachments.where((a) => a.isImage).length;
|
return '';
|
||||||
return switch ((attachments.length, images)) {
|
|
||||||
(0, _) => '',
|
|
||||||
(1, 1) => 'Image',
|
|
||||||
(1, _) => attachments.single.name,
|
|
||||||
(final n, final i) when i == n => '$n images',
|
|
||||||
(final n, _) => '$n attachments',
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the section whose `## label` heading is on [line], or null. Only
|
/// Returns the section whose `## label` heading is on [line], or null. Only
|
||||||
|
|||||||
@ -1,75 +0,0 @@
|
|||||||
/// Assigning plain notes to a repo from the UI: each becomes a `## title`
|
|
||||||
/// section of the repo's one open note ([addRepoTask]), and the original goes.
|
|
||||||
///
|
|
||||||
/// Only the data layer: nothing here talks to the board or starts a task.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:todo/data/note.dart';
|
|
||||||
import 'package:todo/data/note_repository.dart';
|
|
||||||
import 'package:todo/data/repo_note.dart';
|
|
||||||
|
|
||||||
final _repoShape = RegExp(r'^[\w.-]+/[\w.-]+$');
|
|
||||||
final _heading = RegExp(r'^(#+)(\s.*)$');
|
|
||||||
|
|
||||||
/// Whether [value] looks like `owner/name`.
|
|
||||||
bool isRepoName(String value) => _repoShape.hasMatch(value.trim());
|
|
||||||
|
|
||||||
/// [body] with every heading outside code fences pushed below `##`.
|
|
||||||
///
|
|
||||||
/// A repo note splits into tasks at `##` headings, so a template note's own
|
|
||||||
/// `## what` / `## must` would otherwise turn into tasks of their own.
|
|
||||||
String demoteHeadings(String body) {
|
|
||||||
var fenced = false;
|
|
||||||
final out = <String>[];
|
|
||||||
for (final line in body.split('\n')) {
|
|
||||||
if (line.trimLeft().startsWith('```')) fenced = !fenced;
|
|
||||||
final m = fenced ? null : _heading.firstMatch(line);
|
|
||||||
if (m == null) {
|
|
||||||
out.add(line);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
final level = m.group(1)!.length;
|
|
||||||
out.add('${'#' * (level < 2 ? 3 : level + 1)}${m.group(2)}');
|
|
||||||
}
|
|
||||||
return out.join('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Moves the plain [notes] into [repo]'s open note in one write, creating
|
|
||||||
/// that note when the repo has none; returns the notes refused because
|
|
||||||
/// they already belong to a repo (left untouched).
|
|
||||||
Future<List<Note>> assignToRepo(
|
|
||||||
NoteRepository repository,
|
|
||||||
List<Note> notes,
|
|
||||||
String repo,
|
|
||||||
) async {
|
|
||||||
final refused = [
|
|
||||||
for (final n in notes)
|
|
||||||
if (n.repo != null) n,
|
|
||||||
];
|
|
||||||
final plain = [
|
|
||||||
for (final n in notes)
|
|
||||||
if (n.repo == null) n,
|
|
||||||
];
|
|
||||||
if (plain.isEmpty) return refused;
|
|
||||||
final first = splitNote(plain.first.text);
|
|
||||||
var target = (await addRepoTask(
|
|
||||||
repository,
|
|
||||||
repo: repo,
|
|
||||||
title: first.title,
|
|
||||||
body: demoteHeadings(first.body),
|
|
||||||
priority: plain.first.priority,
|
|
||||||
createdBy: 'kuhy',
|
|
||||||
)).note;
|
|
||||||
for (final n in plain.skip(1)) {
|
|
||||||
final (:title, :body) = splitNote(n.text);
|
|
||||||
target = target.copyWith(
|
|
||||||
text: '${target.text}\n\n${repoSection(title, demoteHeadings(body))}',
|
|
||||||
priority: maxPriority(target.priority, n.priority),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
await repository.saveReplacing(
|
|
||||||
target.copyWith(updatedAt: DateTime.now()),
|
|
||||||
plain.map((n) => n.id),
|
|
||||||
);
|
|
||||||
return refused;
|
|
||||||
}
|
|
||||||
@ -1,107 +0,0 @@
|
|||||||
/// The one-open-note-per-repo invariant. Single add path for the MCP
|
|
||||||
/// `add_task` and the CLI `--repo` add; callers persist and push.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:todo/data/note.dart';
|
|
||||||
import 'package:todo/data/note_repository.dart';
|
|
||||||
import 'package:uuid/uuid.dart';
|
|
||||||
|
|
||||||
/// Statuses that count as open.
|
|
||||||
const Set<Status> kOpenStatuses = {Status.todo, Status.inProgress};
|
|
||||||
|
|
||||||
/// The repo note's title.
|
|
||||||
String repoNoteTitle(String repo) => '${repo.split('/').last} todos';
|
|
||||||
|
|
||||||
/// A `new_note` task's own note title: `<name> todos: <title>`.
|
|
||||||
String separateNoteTitle(String repo, String title) =>
|
|
||||||
'${repoNoteTitle(repo)}: ${title.trim()}';
|
|
||||||
|
|
||||||
/// Whether [note] is a `new_note` note, which the shared add path and the
|
|
||||||
/// one-time merge leave alone.
|
|
||||||
bool isSeparateNote(Note note) {
|
|
||||||
final repo = note.repo;
|
|
||||||
return repo != null &&
|
|
||||||
splitNote(note.text).title.startsWith('${repoNoteTitle(repo)}: ');
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Joins two checks with `&&`; either may be absent.
|
|
||||||
String? composeDoneCheck(String? older, String? newer) {
|
|
||||||
final a = (older ?? '').trim();
|
|
||||||
final b = (newer ?? '').trim();
|
|
||||||
if (a.isEmpty) return b.isEmpty ? null : b;
|
|
||||||
return b.isEmpty ? a : '( $a ) && ( $b )';
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A `## title` section.
|
|
||||||
String repoSection(String title, String body) {
|
|
||||||
final text = body.trim();
|
|
||||||
return text.isEmpty ? '## $title' : '## $title\n$text';
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The higher priority.
|
|
||||||
Priority maxPriority(Priority a, Priority b) => a.value >= b.value ? a : b;
|
|
||||||
|
|
||||||
/// Title line and rest of a note's text.
|
|
||||||
({String title, String body}) splitNote(String text) {
|
|
||||||
final lines = text.split('\n');
|
|
||||||
final first = lines.indexWhere((l) => l.trim().isNotEmpty);
|
|
||||||
if (first < 0) return (title: '', body: '');
|
|
||||||
return (
|
|
||||||
title: lines[first].trim().replaceFirst(RegExp(r'^#+\s*'), ''),
|
|
||||||
body: lines.skip(first + 1).join('\n').trim(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Oldest first; ties broken by id so the choice is deterministic.
|
|
||||||
int byAge(Note a, Note b) {
|
|
||||||
final c = a.createdAt.compareTo(b.createdAt);
|
|
||||||
return c != 0 ? c : a.id.compareTo(b.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The note to save and whether it was appended.
|
|
||||||
typedef RepoAdd = ({Note note, bool appended});
|
|
||||||
|
|
||||||
/// Appends the task to [repo]'s oldest open shared note, or builds that
|
|
||||||
/// note; separate (`new_note`) notes are never joined.
|
|
||||||
Future<RepoAdd> addRepoTask(
|
|
||||||
NoteRepository repository, {
|
|
||||||
required String repo,
|
|
||||||
required String title,
|
|
||||||
String body = '',
|
|
||||||
String? doneCheck,
|
|
||||||
Priority priority = Priority.medium,
|
|
||||||
String? by,
|
|
||||||
String? createdBy,
|
|
||||||
}) async {
|
|
||||||
final section = repoSection(title, body);
|
|
||||||
final open = (await repository.listNotes(
|
|
||||||
filter: NoteFilter(statuses: kOpenStatuses, repo: repo),
|
|
||||||
)).where((n) => !isSeparateNote(n)).toList();
|
|
||||||
if (open.isNotEmpty) {
|
|
||||||
final existing = (open..sort(byAge)).first;
|
|
||||||
return (
|
|
||||||
note: existing.copyWith(
|
|
||||||
text: '${existing.text}\n\n$section',
|
|
||||||
doneCheck: composeDoneCheck(existing.doneCheck, doneCheck),
|
|
||||||
priority: maxPriority(existing.priority, priority),
|
|
||||||
),
|
|
||||||
appended: true,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
final now = DateTime.now();
|
|
||||||
return (
|
|
||||||
note: Note(
|
|
||||||
id: const Uuid().v4(),
|
|
||||||
text: '${repoNoteTitle(repo)}\n\n$section',
|
|
||||||
priority: priority,
|
|
||||||
status: Status.todo,
|
|
||||||
createdAt: now,
|
|
||||||
updatedAt: now,
|
|
||||||
repo: repo,
|
|
||||||
doneCheck: composeDoneCheck(null, doneCheck),
|
|
||||||
by: by,
|
|
||||||
createdBy: createdBy,
|
|
||||||
),
|
|
||||||
appended: false,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,53 +0,0 @@
|
|||||||
/// One-time migration plan: one open note per repo, oldest id kept.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:todo/data/note.dart';
|
|
||||||
import 'package:todo/data/repo_note.dart';
|
|
||||||
|
|
||||||
/// The rewritten oldest note and the originals to delete.
|
|
||||||
typedef RepoMerge = ({Note kept, List<Note> removed});
|
|
||||||
|
|
||||||
/// A merge for every repo whose open notes are not yet one `<name> todos`
|
|
||||||
/// note; running it on its own result yields an empty plan. Separate
|
|
||||||
/// (`new_note`) notes stay out of it.
|
|
||||||
List<RepoMerge> planRepoMerges(Iterable<Note> notes) {
|
|
||||||
final byRepo = <String, List<Note>>{};
|
|
||||||
for (final n in notes) {
|
|
||||||
final repo = n.repo;
|
|
||||||
if (repo != null &&
|
|
||||||
kOpenStatuses.contains(n.status) &&
|
|
||||||
!isSeparateNote(n)) {
|
|
||||||
byRepo.putIfAbsent(repo, () => []).add(n);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
final plan = <RepoMerge>[];
|
|
||||||
for (final MapEntry(key: repo, value: group) in byRepo.entries) {
|
|
||||||
group.sort(byAge);
|
|
||||||
final title = repoNoteTitle(repo);
|
|
||||||
if (group.length == 1 && splitNote(group.single.text).title == title) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
plan.add((kept: _merged(title, group), removed: group.sublist(1)));
|
|
||||||
}
|
|
||||||
return plan;
|
|
||||||
}
|
|
||||||
|
|
||||||
Note _merged(String title, List<Note> group) {
|
|
||||||
var doneCheck = group.first.doneCheck;
|
|
||||||
var priority = group.first.priority;
|
|
||||||
final sections = <String>[];
|
|
||||||
for (final (i, n) in group.indexed) {
|
|
||||||
final (title: t, :body) = splitNote(n.text);
|
|
||||||
// An already-merged note keeps its sections as they are.
|
|
||||||
sections.add(t == title ? body : repoSection(t, body));
|
|
||||||
if (i > 0) {
|
|
||||||
doneCheck = composeDoneCheck(doneCheck, n.doneCheck);
|
|
||||||
priority = maxPriority(priority, n.priority);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return group.first.copyWith(
|
|
||||||
text: '$title\n\n${sections.where((s) => s.isNotEmpty).join('\n\n')}',
|
|
||||||
doneCheck: doneCheck,
|
|
||||||
priority: priority,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -1,122 +0,0 @@
|
|||||||
/// `new_note`: a repo task in its own open note, `<name> todos: <title>`,
|
|
||||||
/// so it can close on its own done_check. A title that already heads an open
|
|
||||||
/// section of another separate note of the repo merges into that note
|
|
||||||
/// instead (it keeps its id); the shared `<name> todos` note never counts.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:todo/data/note.dart';
|
|
||||||
import 'package:todo/data/note_repository.dart';
|
|
||||||
import 'package:todo/data/repo_note.dart';
|
|
||||||
import 'package:uuid/uuid.dart';
|
|
||||||
|
|
||||||
/// How a separate add landed.
|
|
||||||
enum SplitKind {
|
|
||||||
/// A new separate note.
|
|
||||||
added,
|
|
||||||
|
|
||||||
/// Appended to the separate note that already had the title.
|
|
||||||
merged,
|
|
||||||
|
|
||||||
/// A new separate note because the duplicate's note was busy.
|
|
||||||
fellBack,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The note to save, how it landed, and why it fell back.
|
|
||||||
typedef SplitAdd = ({Note note, SplitKind kind, String? why});
|
|
||||||
|
|
||||||
final _heading = RegExp(r'^##\s+(\[x\]\s+)?(.*)$');
|
|
||||||
|
|
||||||
/// Every `## title` heading of [text] outside code fences, open or done.
|
|
||||||
Iterable<RegExpMatch> _sections(String text) sync* {
|
|
||||||
var fenced = false;
|
|
||||||
for (final line in text.split('\n')) {
|
|
||||||
if (line.trimLeft().startsWith('```')) fenced = !fenced;
|
|
||||||
final m = fenced ? null : _heading.firstMatch(line);
|
|
||||||
if (m != null) yield m;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The open `## title` headings of [text], outside code fences.
|
|
||||||
Iterable<String> openSections(String text) => _sections(
|
|
||||||
text,
|
|
||||||
).where((m) => m.group(1) == null).map((m) => m.group(2)!.trim());
|
|
||||||
|
|
||||||
/// How many board items [text] splits into: one per section, done or not.
|
|
||||||
int sectionCount(String text) => _sections(text).length;
|
|
||||||
|
|
||||||
/// The separate open note of [repo] with an open section titled [title].
|
|
||||||
Note? duplicateTarget(Iterable<Note> open, String repo, String title) {
|
|
||||||
final hits =
|
|
||||||
open
|
|
||||||
.where((n) => n.repo == repo && isSeparateNote(n))
|
|
||||||
.where((n) => openSections(n.text).contains(title.trim()))
|
|
||||||
.toList()
|
|
||||||
..sort(byAge);
|
|
||||||
return hits.isEmpty ? null : hits.first;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why a merged task must not be started, or null when it may be.
|
|
||||||
String? startBlock(String? doneCheck, String body) {
|
|
||||||
final check = (doneCheck ?? '').trim().toLowerCase();
|
|
||||||
if (check.isEmpty || check == 'none') return 'done_check is none';
|
|
||||||
final first = body
|
|
||||||
.split('\n')
|
|
||||||
.firstWhere((l) => l.trim().isNotEmpty, orElse: () => '');
|
|
||||||
return first.trim().toLowerCase().startsWith('low priority')
|
|
||||||
? 'marked low priority'
|
|
||||||
: null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Adds the task as its own note, or merges it into the duplicate's note
|
|
||||||
/// unless [busy] says a board session is working on it.
|
|
||||||
Future<SplitAdd> addSeparateTask(
|
|
||||||
NoteRepository repository, {
|
|
||||||
required String repo,
|
|
||||||
required String title,
|
|
||||||
String body = '',
|
|
||||||
String? doneCheck,
|
|
||||||
Priority priority = Priority.medium,
|
|
||||||
String? by,
|
|
||||||
String? createdBy,
|
|
||||||
Future<bool> Function(Note note)? busy,
|
|
||||||
}) async {
|
|
||||||
final section = repoSection(title, body);
|
|
||||||
final open = await repository.listNotes(
|
|
||||||
filter: NoteFilter(statuses: kOpenStatuses, repo: repo),
|
|
||||||
);
|
|
||||||
final target = duplicateTarget(open, repo, title);
|
|
||||||
String? why;
|
|
||||||
if (target != null) {
|
|
||||||
if (busy == null || !await busy(target)) {
|
|
||||||
return (
|
|
||||||
note: target.copyWith(
|
|
||||||
text: '${target.text}\n\n$section',
|
|
||||||
doneCheck: composeDoneCheck(target.doneCheck, doneCheck),
|
|
||||||
priority: maxPriority(target.priority, priority),
|
|
||||||
),
|
|
||||||
kind: SplitKind.merged,
|
|
||||||
why: null,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
why =
|
|
||||||
'not merged into ${target.id.substring(0, 8)}: '
|
|
||||||
'a board session is running on it';
|
|
||||||
}
|
|
||||||
final now = DateTime.now();
|
|
||||||
return (
|
|
||||||
note: Note(
|
|
||||||
id: const Uuid().v4(),
|
|
||||||
text: '${separateNoteTitle(repo, title)}\n\n$section',
|
|
||||||
priority: priority,
|
|
||||||
status: Status.todo,
|
|
||||||
createdAt: now,
|
|
||||||
updatedAt: now,
|
|
||||||
repo: repo,
|
|
||||||
doneCheck: composeDoneCheck(null, doneCheck),
|
|
||||||
by: by,
|
|
||||||
createdBy: createdBy,
|
|
||||||
),
|
|
||||||
kind: why == null ? SplitKind.added : SplitKind.fellBack,
|
|
||||||
why: why,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -14,7 +14,7 @@ Future<NoteRepository> openRepository() async {
|
|||||||
final database = await WebLogPersistence.openDatabase(idbFactoryBrowser);
|
final database = await WebLogPersistence.openDatabase(idbFactoryBrowser);
|
||||||
final persistence = WebLogPersistence(
|
final persistence = WebLogPersistence(
|
||||||
database: database,
|
database: database,
|
||||||
backup: DesktopBackupClient(baseUrl: servingWrapperOrigin()),
|
backup: DesktopBackupClient(baseUrl: desktopWrapperOrigin),
|
||||||
);
|
);
|
||||||
|
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
|||||||
@ -24,14 +24,12 @@ String profileDir(String home) =>
|
|||||||
p.join(home, '.local', 'share', 'todo-desktop', 'profile');
|
p.join(home, '.local', 'share', 'todo-desktop', 'profile');
|
||||||
|
|
||||||
/// Returns the first Chrome-family browser on this machine, or ''.
|
/// Returns the first Chrome-family browser on this machine, or ''.
|
||||||
///
|
String findBrowser() {
|
||||||
/// [override] defaults to `$TODO_BROWSER`; [exists] to a file check.
|
|
||||||
String findBrowser({String? override, bool Function(String path)? exists}) {
|
|
||||||
// Ordered by preference, and deliberately broad: this machine runs Thorium
|
// Ordered by preference, and deliberately broad: this machine runs Thorium
|
||||||
// behind /opt/google/chrome, and has a policy that uninstalls the `chromium`
|
// behind /opt/google/chrome, and has a policy that uninstalls the `chromium`
|
||||||
// package, so assuming any single browser is wrong. TODO_BROWSER overrides.
|
// package, so assuming any single browser is wrong. TODO_BROWSER overrides.
|
||||||
final candidates = [
|
final candidates = [
|
||||||
override ?? Platform.environment['TODO_BROWSER'] ?? '',
|
Platform.environment['TODO_BROWSER'] ?? '',
|
||||||
'/opt/google/chrome/chrome',
|
'/opt/google/chrome/chrome',
|
||||||
'/opt/thorium-browser/thorium-browser',
|
'/opt/thorium-browser/thorium-browser',
|
||||||
'/usr/bin/google-chrome-stable',
|
'/usr/bin/google-chrome-stable',
|
||||||
@ -39,45 +37,17 @@ String findBrowser({String? override, bool Function(String path)? exists}) {
|
|||||||
'/usr/bin/brave',
|
'/usr/bin/brave',
|
||||||
];
|
];
|
||||||
return candidates.firstWhere(
|
return candidates.firstWhere(
|
||||||
(path) => path.isNotEmpty && (exists ?? (p) => File(p).existsSync())(path),
|
(path) => path.isNotEmpty && File(path).existsSync(),
|
||||||
orElse: () => '',
|
orElse: () => '',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Command-line arguments for the app window.
|
|
||||||
List<String> browserArgs(String home) => [
|
|
||||||
'--app=http://localhost:$kWrapperPort',
|
|
||||||
'--user-data-dir=${profileDir(home)}',
|
|
||||||
// Sets WM_CLASS, which the .desktop entry matches on via StartupWMClass.
|
|
||||||
// Without it the window inherits the browser's class and the taskbar shows
|
|
||||||
// a browser icon instead of todo's.
|
|
||||||
'--class=todo',
|
|
||||||
'--no-first-run',
|
|
||||||
// Keep Chrome off the GNOME keyring. While the keyring is locked, Chrome
|
|
||||||
// blocks every non-incognito page load on its first cookie access, and an
|
|
||||||
// "Unlock Keyring" prompt waits on another workspace: the window stays a
|
|
||||||
// blank grey. Nothing in this profile needs OS-level encryption (the
|
|
||||||
// GitHub token is in localStorage, not the password store).
|
|
||||||
'--password-store=basic',
|
|
||||||
// The distro wrapper appends ~/.config/chromium-flags.conf to every launch,
|
|
||||||
// which here carries `--load-extension` for Claude in Chrome. Logged out in
|
|
||||||
// this profile, it opened a claude.ai login tab in a second, normal browser
|
|
||||||
// window on every start. This flag also drops command-line extensions.
|
|
||||||
'--disable-extensions',
|
|
||||||
];
|
|
||||||
|
|
||||||
/// Launches the app in a Chrome-family browser with a **stable** profile
|
/// Launches the app in a Chrome-family browser with a **stable** profile
|
||||||
/// directory, since the token and notes live in that profile.
|
/// directory, since the token and notes live in that profile.
|
||||||
///
|
///
|
||||||
/// Returns true when the browser ran long enough to have owned the session.
|
/// Returns true when the browser ran long enough to have owned the session.
|
||||||
/// [browser] and [start] exist for tests; they default to [findBrowser] and
|
Future<bool> launchBrowser(String home) async {
|
||||||
/// [Process.start].
|
final browser = findBrowser();
|
||||||
Future<bool> launchBrowser(
|
|
||||||
String home, {
|
|
||||||
String? browser,
|
|
||||||
Future<Process> Function(String executable, List<String> args)? start,
|
|
||||||
}) async {
|
|
||||||
browser ??= findBrowser();
|
|
||||||
if (browser.isEmpty) {
|
if (browser.isEmpty) {
|
||||||
stderr.writeln(
|
stderr.writeln(
|
||||||
'No Chrome-family browser found; open '
|
'No Chrome-family browser found; open '
|
||||||
@ -85,7 +55,15 @@ Future<bool> launchBrowser(
|
|||||||
);
|
);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
final process = await (start ?? Process.start)(browser, browserArgs(home));
|
final process = await Process.start(browser, [
|
||||||
|
'--app=http://localhost:$kWrapperPort',
|
||||||
|
'--user-data-dir=${profileDir(home)}',
|
||||||
|
// Sets WM_CLASS, which the .desktop entry matches on via StartupWMClass.
|
||||||
|
// Without it the window inherits the browser's class and the taskbar shows
|
||||||
|
// a browser icon instead of todo's.
|
||||||
|
'--class=todo',
|
||||||
|
'--no-first-run',
|
||||||
|
]);
|
||||||
|
|
||||||
final started = DateTime.now();
|
final started = DateTime.now();
|
||||||
await process.exitCode;
|
await process.exitCode;
|
||||||
|
|||||||
@ -1,37 +0,0 @@
|
|||||||
/// Reads the dufs login `add_dufs_login.sh` wrote for the desktop wrapper.
|
|
||||||
///
|
|
||||||
/// `~/src/dufs-cloud/scripts/add_dufs_login.sh todo /todo-images rw` leaves a
|
|
||||||
/// 0600 `~/.config/dufs/logins/todo.env` of `KEY=value` lines. The wrapper
|
|
||||||
/// re-reads it on every reconcile, so creating or rotating the login takes
|
|
||||||
/// effect without restarting the desktop app.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'dart:io';
|
|
||||||
|
|
||||||
import 'package:path/path.dart' as p;
|
|
||||||
|
|
||||||
import 'package:todo/images/dufs_image_client.dart';
|
|
||||||
|
|
||||||
/// `~/.config/dufs/logins/todo.env` under [home].
|
|
||||||
String defaultDufsLoginEnvPath(String home) =>
|
|
||||||
p.join(home, '.config', 'dufs', 'logins', 'todo.env');
|
|
||||||
|
|
||||||
/// The login in [envFile], or null when it is absent or incomplete.
|
|
||||||
DufsLogin? readDufsLoginEnv(File envFile) {
|
|
||||||
if (!envFile.existsSync()) return null;
|
|
||||||
final values = <String, String>{};
|
|
||||||
for (final line in envFile.readAsLinesSync()) {
|
|
||||||
final eq = line.indexOf('=');
|
|
||||||
if (eq <= 0 || line.startsWith('#')) continue;
|
|
||||||
values[line.substring(0, eq).trim()] = line.substring(eq + 1).trim();
|
|
||||||
}
|
|
||||||
final user = values['DUFS_USER'] ?? '';
|
|
||||||
final password = values['DUFS_PASSWORD'] ?? '';
|
|
||||||
final url = values['DUFS_URL'] ?? '';
|
|
||||||
if (user.isEmpty || password.isEmpty || url.isEmpty) return null;
|
|
||||||
return DufsLogin(
|
|
||||||
user: user,
|
|
||||||
password: password,
|
|
||||||
baseUrl: url.endsWith('/') ? url.substring(0, url.length - 1) : url,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -21,21 +21,12 @@ class LinuxSystemProbe implements SystemProbe {
|
|||||||
/// Creates the default host probe.
|
/// Creates the default host probe.
|
||||||
///
|
///
|
||||||
/// [ssExecutable] exists so a test can point at a missing binary and exercise
|
/// [ssExecutable] exists so a test can point at a missing binary and exercise
|
||||||
/// the "no `ss` on PATH" path. [listProc] lets a test fail the `/proc`
|
/// the "no `ss` on PATH" path.
|
||||||
/// listing on demand.
|
const LinuxSystemProbe({this.ssExecutable = 'ss'});
|
||||||
const LinuxSystemProbe({this.ssExecutable = 'ss', this.listProc = _listProc});
|
|
||||||
|
|
||||||
/// Name of the socket-listing tool used to find the port owner.
|
/// Name of the socket-listing tool used to find the port owner.
|
||||||
final String ssExecutable;
|
final String ssExecutable;
|
||||||
|
|
||||||
/// Lists `/proc`'s entries.
|
|
||||||
final List<FileSystemEntity> Function() listProc;
|
|
||||||
|
|
||||||
/// How many `/proc` listings a process exiting mid-listing may spoil.
|
|
||||||
static const _listAttempts = 3;
|
|
||||||
|
|
||||||
static List<FileSystemEntity> _listProc() => Directory('/proc').listSync();
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<int?> listenerPid(int port) async {
|
Future<int?> listenerPid(int port) async {
|
||||||
try {
|
try {
|
||||||
@ -65,7 +56,7 @@ class LinuxSystemProbe implements SystemProbe {
|
|||||||
@override
|
@override
|
||||||
Future<List<List<String>>> processCmdlines() async {
|
Future<List<List<String>>> processCmdlines() async {
|
||||||
final cmdlines = <List<String>>[];
|
final cmdlines = <List<String>>[];
|
||||||
for (final entry in _listProcRetrying()) {
|
for (final entry in Directory('/proc').listSync()) {
|
||||||
final pid = int.tryParse(p.basename(entry.path));
|
final pid = int.tryParse(p.basename(entry.path));
|
||||||
if (pid == null) continue;
|
if (pid == null) continue;
|
||||||
final cmdline = readCmdline(pid);
|
final cmdline = readCmdline(pid);
|
||||||
@ -74,19 +65,6 @@ class LinuxSystemProbe implements SystemProbe {
|
|||||||
return cmdlines;
|
return cmdlines;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Dart's listing lstat()s some entries, so a pid that exits between
|
|
||||||
/// readdir and that lstat fails the whole listing. A fresh listing no
|
|
||||||
/// longer holds that pid; a few failures in a row mean a real error.
|
|
||||||
List<FileSystemEntity> _listProcRetrying() {
|
|
||||||
for (var attempt = 1; ; attempt++) {
|
|
||||||
try {
|
|
||||||
return listProc();
|
|
||||||
} on PathNotFoundException {
|
|
||||||
if (attempt >= _listAttempts) rethrow;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<bool> portInUse(int port) async {
|
Future<bool> portInUse(int port) async {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@ -1,42 +0,0 @@
|
|||||||
/// Content types for the web build's static assets, served by the wrapper.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'dart:io';
|
|
||||||
|
|
||||||
import 'package:path/path.dart' as p;
|
|
||||||
|
|
||||||
/// Content type for [filePath].
|
|
||||||
///
|
|
||||||
/// Flutter web is strict here: CanvasKit refuses to instantiate a `.wasm`
|
|
||||||
/// served as anything but `application/wasm`, and the app silently fails to
|
|
||||||
/// render if the bootstrap `.js` is mislabelled.
|
|
||||||
ContentType staticContentTypeFor(String filePath) {
|
|
||||||
switch (p.extension(filePath).toLowerCase()) {
|
|
||||||
case '.html':
|
|
||||||
return ContentType.html;
|
|
||||||
case '.js' || '.mjs':
|
|
||||||
return ContentType('text', 'javascript', charset: 'utf-8');
|
|
||||||
case '.json':
|
|
||||||
return ContentType.json;
|
|
||||||
case '.wasm':
|
|
||||||
return ContentType('application', 'wasm');
|
|
||||||
case '.css':
|
|
||||||
return ContentType('text', 'css', charset: 'utf-8');
|
|
||||||
case '.png':
|
|
||||||
return ContentType('image', 'png');
|
|
||||||
case '.jpg' || '.jpeg':
|
|
||||||
return ContentType('image', 'jpeg');
|
|
||||||
case '.svg':
|
|
||||||
return ContentType('image', 'svg+xml');
|
|
||||||
case '.ttf':
|
|
||||||
return ContentType('font', 'ttf');
|
|
||||||
case '.otf':
|
|
||||||
return ContentType('font', 'otf');
|
|
||||||
case '.woff2':
|
|
||||||
return ContentType('font', 'woff2');
|
|
||||||
case '.bin' || '.symbols':
|
|
||||||
return ContentType.binary;
|
|
||||||
default:
|
|
||||||
return ContentType.binary;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,127 +0,0 @@
|
|||||||
/// Serving one cached attachment from the desktop wrapper, for an `<img>` in
|
|
||||||
/// the page or a file opened in a new tab.
|
|
||||||
///
|
|
||||||
/// The wrapper's origin also holds the GitHub token (localStorage) and the
|
|
||||||
/// notes (IndexedDB), so an attached `.html` or `.svg` rendered here would
|
|
||||||
/// run script with access to both. Only types that cannot script are shown
|
|
||||||
/// inline — raster images, PDF, plain text, audio and video — always with
|
|
||||||
/// `nosniff` so the browser cannot second-guess the type; everything else is
|
|
||||||
/// sent as a download.
|
|
||||||
///
|
|
||||||
/// Single byte ranges are honoured so a video can seek.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'dart:io';
|
|
||||||
|
|
||||||
import 'package:todo/images/attachment_ref.dart';
|
|
||||||
|
|
||||||
/// The content type for an attachment with [extension], and whether it may
|
|
||||||
/// be shown inline (see the library comment).
|
|
||||||
({ContentType type, bool inline}) attachmentContentType(String extension) {
|
|
||||||
final type = switch (extension) {
|
|
||||||
'jpg' || 'jpeg' => ContentType('image', 'jpeg'),
|
|
||||||
'png' || 'gif' || 'webp' || 'bmp' => ContentType('image', extension),
|
|
||||||
'pdf' => ContentType('application', 'pdf'),
|
|
||||||
'txt' ||
|
|
||||||
'md' ||
|
|
||||||
'log' ||
|
|
||||||
'csv' => ContentType('text', 'plain', charset: 'utf-8'),
|
|
||||||
'mp4' || 'm4v' => ContentType('video', 'mp4'),
|
|
||||||
'webm' => ContentType('video', 'webm'),
|
|
||||||
'ogv' => ContentType('video', 'ogg'),
|
|
||||||
'mov' => ContentType('video', 'quicktime'),
|
|
||||||
'mp3' => ContentType('audio', 'mpeg'),
|
|
||||||
'm4a' => ContentType('audio', 'mp4'),
|
|
||||||
'ogg' || 'oga' || 'opus' => ContentType('audio', 'ogg'),
|
|
||||||
'wav' => ContentType('audio', 'wav'),
|
|
||||||
'flac' => ContentType('audio', 'flac'),
|
|
||||||
_ => null,
|
|
||||||
};
|
|
||||||
return type == null
|
|
||||||
? (type: ContentType.binary, inline: false)
|
|
||||||
: (type: type, inline: true);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `Content-Disposition` for [fileName]: RFC 6266 with an RFC 5987
|
|
||||||
/// `filename*`, so any name (spaces, Polish letters, quotes) survives.
|
|
||||||
String contentDisposition(String fileName, {required bool inline}) {
|
|
||||||
final encoded = Uri.encodeComponent(fileName).replaceAllMapped(
|
|
||||||
RegExp("[!'()*]"),
|
|
||||||
(m) => '%${m[0]!.codeUnitAt(0).toRadixString(16).toUpperCase()}',
|
|
||||||
);
|
|
||||||
return "${inline ? 'inline' : 'attachment'}; filename*=UTF-8''$encoded";
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Answers a GET or HEAD for [ref] from [file], named [fileName] when the
|
|
||||||
/// page passed one (else the stored name). 404 when it is not cached.
|
|
||||||
Future<void> serveAttachment(
|
|
||||||
HttpRequest request,
|
|
||||||
AttachmentRef ref,
|
|
||||||
File file, {
|
|
||||||
String? fileName,
|
|
||||||
}) async {
|
|
||||||
final response = request.response;
|
|
||||||
if (!file.existsSync()) {
|
|
||||||
response.statusCode = HttpStatus.notFound;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final length = await file.length();
|
|
||||||
final kind = attachmentContentType(ref.extension);
|
|
||||||
response.headers
|
|
||||||
..contentType = kind.type
|
|
||||||
..set('x-content-type-options', 'nosniff')
|
|
||||||
..set(HttpHeaders.acceptRangesHeader, 'bytes')
|
|
||||||
..set(
|
|
||||||
'content-disposition',
|
|
||||||
contentDisposition(fileName ?? ref.file, inline: kind.inline),
|
|
||||||
)
|
|
||||||
// The name is a fresh uuid per attachment, so the bytes never change.
|
|
||||||
..set(HttpHeaders.cacheControlHeader, 'private, max-age=31536000');
|
|
||||||
var start = 0;
|
|
||||||
var end = length - 1;
|
|
||||||
final range = request.headers.value(HttpHeaders.rangeHeader);
|
|
||||||
if (range != null) {
|
|
||||||
final parsed = parseByteRange(range, length);
|
|
||||||
if (parsed == null) {
|
|
||||||
response
|
|
||||||
..statusCode = HttpStatus.requestedRangeNotSatisfiable
|
|
||||||
..headers.set(HttpHeaders.contentRangeHeader, 'bytes */$length');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
(start, end) = parsed;
|
|
||||||
response
|
|
||||||
..statusCode = HttpStatus.partialContent
|
|
||||||
..headers.set(
|
|
||||||
HttpHeaders.contentRangeHeader,
|
|
||||||
'bytes $start-$end/$length',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
response.contentLength = length == 0 ? 0 : end - start + 1;
|
|
||||||
if (request.method == 'HEAD' || length == 0) return;
|
|
||||||
// A client leaving mid-body (a video seek abandons its old range) does not
|
|
||||||
// throw here: dart:io absorbs it and the stream just stops being read.
|
|
||||||
await response.addStream(file.openRead(start, end + 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The inclusive byte range a single-range `Range` header asks for within
|
|
||||||
/// [length] bytes, or null when it is malformed, multi-range or outside the
|
|
||||||
/// file.
|
|
||||||
(int, int)? parseByteRange(String header, int length) {
|
|
||||||
final match = RegExp(r'^bytes=(\d*)-(\d*)$').firstMatch(header.trim());
|
|
||||||
if (match == null) return null;
|
|
||||||
final first = int.tryParse(match[1]!);
|
|
||||||
final last = int.tryParse(match[2]!);
|
|
||||||
final int start;
|
|
||||||
final int end;
|
|
||||||
if (first == null) {
|
|
||||||
// `bytes=-N`: the final N bytes.
|
|
||||||
if (last == null || last == 0) return null;
|
|
||||||
start = last >= length ? 0 : length - last;
|
|
||||||
end = length - 1;
|
|
||||||
} else {
|
|
||||||
start = first;
|
|
||||||
end = last == null || last >= length ? length - 1 : last;
|
|
||||||
}
|
|
||||||
if (start >= length || start > end) return null;
|
|
||||||
return (start, end);
|
|
||||||
}
|
|
||||||
@ -1,185 +0,0 @@
|
|||||||
/// The desktop wrapper's `/images/*` routes: the web page's only way to
|
|
||||||
/// store, show and sync attachments (images and any other file).
|
|
||||||
///
|
|
||||||
/// The page never talks to dufs itself. That keeps the dufs password out of
|
|
||||||
/// the browser, needs no CORS on dufs, and gives the desktop the same offline
|
|
||||||
/// store the phone has (an [ImageCacheStore] on disk). Same-origin with the
|
|
||||||
/// page, so an `<img src="/images/…">` just works.
|
|
||||||
///
|
|
||||||
/// * `POST /images/attach?note=<noteId>&name=<file name>` — a picked or
|
|
||||||
/// dropped file of any size, streamed to disk; stored as a re-encoded image
|
|
||||||
/// when it is one, byte-for-byte otherwise. Answers with the [Attachment].
|
|
||||||
/// * `POST /images/<noteId>/<uuid>.jpg` — raw bytes of a pasted image;
|
|
||||||
/// re-encoded here (the page must not decode on its UI thread), stored,
|
|
||||||
/// queued. 415 when the bytes are not an image.
|
|
||||||
/// * `GET|HEAD /images/<noteId>/<uuid>.<ext>[?name=<file name>]` — the cached
|
|
||||||
/// file (see `wrapper_attachment_serving.dart`), 404 when absent.
|
|
||||||
/// * `POST /images/reconcile` — `{"refs": ["<noteId>/<uuid>.<ext>", …]}`:
|
|
||||||
/// every attachment the notes link to. Uploads the queue, fetches what is
|
|
||||||
/// missing, evicts the rest; answers with the [ReconcileReport].
|
|
||||||
/// * `GET /images/status` — `{"configured": bool, "pending": n}`.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'dart:convert';
|
|
||||||
import 'dart:io';
|
|
||||||
import 'dart:typed_data';
|
|
||||||
|
|
||||||
import 'package:http/http.dart' as http;
|
|
||||||
import 'package:todo/desktop/dufs_login_env.dart';
|
|
||||||
import 'package:todo/desktop/wrapper_attachment_serving.dart';
|
|
||||||
import 'package:todo/desktop/wrapper_paths.dart';
|
|
||||||
import 'package:todo/images/attachment_ingest.dart';
|
|
||||||
import 'package:todo/images/attachment_ref.dart';
|
|
||||||
import 'package:todo/images/dufs_image_client.dart';
|
|
||||||
import 'package:todo/images/image_cache_store.dart';
|
|
||||||
import 'package:todo/images/image_processing.dart';
|
|
||||||
|
|
||||||
/// The routes the real wrapper uses: cache under
|
|
||||||
/// `~/.local/share/todo-desktop/images`, login from `todo.env`.
|
|
||||||
WrapperImageRoutes defaultWrapperImageRoutes(String home) => WrapperImageRoutes(
|
|
||||||
store: ImageCacheStore(Directory(defaultImageCachePath(home))),
|
|
||||||
loginEnvPath: defaultDufsLoginEnvPath(home),
|
|
||||||
);
|
|
||||||
|
|
||||||
/// Handles `/images/*` for the wrapper.
|
|
||||||
class WrapperImageRoutes {
|
|
||||||
/// Creates the routes over [store], reading the dufs login from
|
|
||||||
/// [loginEnvPath]. [httpClient] and [prepare] are injectable for tests.
|
|
||||||
WrapperImageRoutes({
|
|
||||||
required this.store,
|
|
||||||
required this.loginEnvPath,
|
|
||||||
http.Client Function()? httpClient,
|
|
||||||
Future<Uint8List?> Function(Uint8List)? prepare,
|
|
||||||
}) : _httpClient = httpClient ?? http.Client.new,
|
|
||||||
_prepare = prepare ?? prepareImageInBackground,
|
|
||||||
_ingest = AttachmentIngest(
|
|
||||||
store,
|
|
||||||
prepare: prepare ?? prepareImageInBackground,
|
|
||||||
);
|
|
||||||
|
|
||||||
/// The on-disk attachment cache and upload queue.
|
|
||||||
final ImageCacheStore store;
|
|
||||||
|
|
||||||
/// `todo.env` written by `add_dufs_login.sh`.
|
|
||||||
final String loginEnvPath;
|
|
||||||
|
|
||||||
final http.Client Function() _httpClient;
|
|
||||||
final Future<Uint8List?> Function(Uint8List) _prepare;
|
|
||||||
final AttachmentIngest _ingest;
|
|
||||||
|
|
||||||
/// Every path these routes answer starts with this.
|
|
||||||
static const prefix = '/images/';
|
|
||||||
|
|
||||||
/// Answers [request] and returns true when it is an `/images/` route.
|
|
||||||
Future<bool> handle(HttpRequest request) async {
|
|
||||||
final path = request.uri.path;
|
|
||||||
if (!path.startsWith(prefix)) return false;
|
|
||||||
final rest = path.substring(prefix.length);
|
|
||||||
final response = request.response;
|
|
||||||
final method = request.method;
|
|
||||||
if (rest == 'attach' && method == 'POST') {
|
|
||||||
await _attach(request);
|
|
||||||
} else if (rest == 'reconcile' && method == 'POST') {
|
|
||||||
await _reconcile(request);
|
|
||||||
} else if (rest == 'status' && method == 'GET') {
|
|
||||||
_json(response, {
|
|
||||||
'configured': _login() != null,
|
|
||||||
'pending': store.pending().length,
|
|
||||||
});
|
|
||||||
} else if (AttachmentRef.tryParse(rest) case final ref?) {
|
|
||||||
if (method == 'GET' || method == 'HEAD') {
|
|
||||||
await serveAttachment(
|
|
||||||
request,
|
|
||||||
ref,
|
|
||||||
store.fileFor(ref),
|
|
||||||
fileName: request.uri.queryParameters['name'],
|
|
||||||
);
|
|
||||||
} else if (method == 'POST' && ref.extension == 'jpg') {
|
|
||||||
await _put(request, ref);
|
|
||||||
} else {
|
|
||||||
response.statusCode = HttpStatus.methodNotAllowed;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
response.statusCode = HttpStatus.notFound;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
DufsLogin? _login() => readDufsLoginEnv(File(loginEnvPath));
|
|
||||||
|
|
||||||
Future<void> _attach(HttpRequest request) async {
|
|
||||||
final query = request.uri.queryParameters;
|
|
||||||
final noteId = query['note'] ?? '';
|
|
||||||
final response = request.response;
|
|
||||||
if (!isSafeNoteId(noteId)) {
|
|
||||||
// Read the body anyway: answering mid-upload looks like a dropped
|
|
||||||
// connection to the browser, not a 400.
|
|
||||||
await request.drain<void>();
|
|
||||||
response.statusCode = HttpStatus.badRequest;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
final attachment = await _ingest.fromStream(
|
|
||||||
noteId,
|
|
||||||
query['name'] ?? '',
|
|
||||||
request,
|
|
||||||
);
|
|
||||||
_json(response, attachment.toJson());
|
|
||||||
} on FileSystemException catch (e) {
|
|
||||||
response
|
|
||||||
..statusCode = HttpStatus.internalServerError
|
|
||||||
..write(e.message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _put(HttpRequest request, AttachmentRef ref) async {
|
|
||||||
final builder = BytesBuilder(copy: false);
|
|
||||||
var tooLarge = false;
|
|
||||||
// Read to the end even once over the cap: answering while the browser
|
|
||||||
// is still sending makes it see a dropped connection, not the 413.
|
|
||||||
await for (final chunk in request) {
|
|
||||||
tooLarge =
|
|
||||||
tooLarge || builder.length + chunk.length > kMaxImageDecodeBytes;
|
|
||||||
if (!tooLarge) builder.add(chunk);
|
|
||||||
}
|
|
||||||
if (tooLarge) {
|
|
||||||
request.response.statusCode = HttpStatus.requestEntityTooLarge;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final jpeg = await _prepare(builder.takeBytes());
|
|
||||||
if (jpeg == null) {
|
|
||||||
request.response.statusCode = HttpStatus.unsupportedMediaType;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await store.put(ref, jpeg);
|
|
||||||
request.response.statusCode = HttpStatus.noContent;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _reconcile(HttpRequest request) async {
|
|
||||||
final Set<AttachmentRef> refs;
|
|
||||||
try {
|
|
||||||
final body = jsonDecode(await utf8.decodeStream(request));
|
|
||||||
refs = {
|
|
||||||
for (final raw in (body as Map<String, dynamic>)['refs'] as List)
|
|
||||||
?AttachmentRef.tryParse(raw as String),
|
|
||||||
};
|
|
||||||
} on Object {
|
|
||||||
request.response.statusCode = HttpStatus.badRequest;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final login = _login();
|
|
||||||
final client = login == null
|
|
||||||
? null
|
|
||||||
: DufsImageClient(login, httpClient: _httpClient());
|
|
||||||
try {
|
|
||||||
_json(request.response, (await store.reconcile(refs, client)).toJson());
|
|
||||||
} finally {
|
|
||||||
client?.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _json(HttpResponse response, Object body) {
|
|
||||||
response.headers.contentType = ContentType.json;
|
|
||||||
response.write(jsonEncode(body));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,25 +0,0 @@
|
|||||||
/// Default on-disk locations the desktop wrapper reads and writes.
|
|
||||||
///
|
|
||||||
/// Split out of `wrapper_server.dart` (file-length cap); re-exported from
|
|
||||||
/// there, so callers keep importing the server.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:path/path.dart' as p;
|
|
||||||
|
|
||||||
/// The canonical backlog file for [home], i.e. `~/src/todo/BACKLOG.md`.
|
|
||||||
///
|
|
||||||
/// Lives here rather than in `bin/todo_desktop.dart` so it is covered: the
|
|
||||||
/// entry point is `coverage:ignore-file` thin wiring, and this path silently
|
|
||||||
/// broke once already. The 2026-09-11 `~` reorganisation moved every repo
|
|
||||||
/// under `~/src`, but the migration's rewriter only matched *literal*
|
|
||||||
/// `/home/kuhy/todo` strings — a path assembled from segments was invisible
|
|
||||||
/// to it, so the wrapper went on exporting to the dead `~/todo` while the
|
|
||||||
/// `todo` MCP read `~/src/todo`. Every backlog read between 2026-09-11 and
|
|
||||||
/// 2026-09-12 got a stale file.
|
|
||||||
String defaultBacklogPath(String home) =>
|
|
||||||
p.join(home, 'src', 'todo', 'BACKLOG.md');
|
|
||||||
|
|
||||||
/// The wrapper's image cache and upload queue,
|
|
||||||
/// `~/.local/share/todo-desktop/images` — beside the note-log copy.
|
|
||||||
String defaultImageCachePath(String home) =>
|
|
||||||
p.join(home, '.local', 'share', 'todo-desktop', 'images');
|
|
||||||
@ -5,14 +5,6 @@ import 'dart:io';
|
|||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
import 'package:path/path.dart' as p;
|
import 'package:path/path.dart' as p;
|
||||||
|
|
||||||
import 'package:todo/desktop/static_content_type.dart';
|
|
||||||
import 'package:todo/desktop/wrapper_image_routes.dart';
|
|
||||||
import 'package:todo/sync/e2e_passphrase_path.dart';
|
|
||||||
|
|
||||||
export 'package:todo/sync/e2e_passphrase_path.dart';
|
|
||||||
|
|
||||||
export 'wrapper_paths.dart';
|
|
||||||
|
|
||||||
part 'wrapper_sync_routes.dart';
|
part 'wrapper_sync_routes.dart';
|
||||||
|
|
||||||
/// Route serving `todo`'s own seeded Firebase session (a `FirebaseCredentials`
|
/// Route serving `todo`'s own seeded Firebase session (a `FirebaseCredentials`
|
||||||
@ -24,6 +16,19 @@ part 'wrapper_sync_routes.dart';
|
|||||||
/// [kSyncAccountEnvVar] as [kSyncAccountPath].
|
/// [kSyncAccountEnvVar] as [kSyncAccountPath].
|
||||||
const kSyncCredentialsPath = '/sync-credentials';
|
const kSyncCredentialsPath = '/sync-credentials';
|
||||||
|
|
||||||
|
/// The canonical backlog file for [home], i.e. `~/src/todo/BACKLOG.md`.
|
||||||
|
///
|
||||||
|
/// Lives here rather than in `bin/todo_desktop.dart` so it is covered: the
|
||||||
|
/// entry point is `coverage:ignore-file` thin wiring, and this path silently
|
||||||
|
/// broke once already. The 2026-09-11 `~` reorganisation moved every repo
|
||||||
|
/// under `~/src`, but the migration's rewriter only matched *literal*
|
||||||
|
/// `/home/kuhy/todo` strings — a path assembled from segments was invisible
|
||||||
|
/// to it, so the wrapper went on exporting to the dead `~/todo` while the
|
||||||
|
/// `todo` MCP read `~/src/todo`. Every backlog read between 2026-09-11 and
|
||||||
|
/// 2026-09-12 got a stale file.
|
||||||
|
String defaultBacklogPath(String home) =>
|
||||||
|
p.join(home, 'src', 'todo', 'BACKLOG.md');
|
||||||
|
|
||||||
/// Local HTTP server backing the desktop app.
|
/// Local HTTP server backing the desktop app.
|
||||||
///
|
///
|
||||||
/// The desktop app is a Flutter **web** build (Flutter's Linux embedder manages
|
/// The desktop app is a Flutter **web** build (Flutter's Linux embedder manages
|
||||||
@ -50,11 +55,7 @@ class WrapperServer {
|
|||||||
bool? serveSyncAccount,
|
bool? serveSyncAccount,
|
||||||
String? syncConfigDir,
|
String? syncConfigDir,
|
||||||
String? todoCredentialsPath,
|
String? todoCredentialsPath,
|
||||||
WrapperImageRoutes? images,
|
}) : serveSyncAccount =
|
||||||
}) : images =
|
|
||||||
images ??
|
|
||||||
defaultWrapperImageRoutes(Platform.environment['HOME'] ?? ''),
|
|
||||||
serveSyncAccount =
|
|
||||||
serveSyncAccount ??
|
serveSyncAccount ??
|
||||||
(Platform.environment[kSyncAccountEnvVar] ?? '').isNotEmpty,
|
(Platform.environment[kSyncAccountEnvVar] ?? '').isNotEmpty,
|
||||||
syncConfigDir =
|
syncConfigDir =
|
||||||
@ -69,9 +70,6 @@ class WrapperServer {
|
|||||||
'firebase_auth.json',
|
'firebase_auth.json',
|
||||||
);
|
);
|
||||||
|
|
||||||
/// The `/images/*` routes (attached images; see [WrapperImageRoutes]).
|
|
||||||
final WrapperImageRoutes images;
|
|
||||||
|
|
||||||
/// Whether the sync-account route answers; off unless explicitly enabled.
|
/// Whether the sync-account route answers; off unless explicitly enabled.
|
||||||
final bool serveSyncAccount;
|
final bool serveSyncAccount;
|
||||||
|
|
||||||
@ -89,9 +87,6 @@ class WrapperServer {
|
|||||||
/// wrappers also serve, which stays opt-in.
|
/// wrappers also serve, which stays opt-in.
|
||||||
bool _todoCredentialsServed = false;
|
bool _todoCredentialsServed = false;
|
||||||
|
|
||||||
/// Whether [kSyncE2ePassphrasePath] has served the passphrase yet.
|
|
||||||
bool _e2ePassphraseServed = false;
|
|
||||||
|
|
||||||
/// `todo`'s own seeded Firebase session, written by
|
/// `todo`'s own seeded Firebase session, written by
|
||||||
/// `crdt-sync/tool/seed_session.py --app todo` in the same
|
/// `crdt-sync/tool/seed_session.py --app todo` in the same
|
||||||
/// `{id_token, refresh_token, expires_at}` shape every other app's
|
/// `{id_token, refresh_token, expires_at}` shape every other app's
|
||||||
@ -134,46 +129,13 @@ class WrapperServer {
|
|||||||
|
|
||||||
Future<void> _serve(HttpServer server) async {
|
Future<void> _serve(HttpServer server) async {
|
||||||
await for (final request in server) {
|
await for (final request in server) {
|
||||||
// Attachment routes can run for minutes (a multi-gigabyte upload, a
|
try {
|
||||||
// video being watched, a reconcile fetching a large file) and are safe
|
|
||||||
// side by side, so they must not hold up the page's own requests.
|
|
||||||
// Everything else stays one at a time: the backup files are
|
|
||||||
// overwritten whole and must not interleave.
|
|
||||||
if (request.uri.path.startsWith(WrapperImageRoutes.prefix)) {
|
|
||||||
unawaited(_respond(request));
|
|
||||||
} else {
|
|
||||||
await _respond(request);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _respond(HttpRequest request) async {
|
|
||||||
try {
|
|
||||||
if (_isCrossSiteWrite(request)) {
|
|
||||||
// Read the body anyway: answering mid-upload looks like a dropped
|
|
||||||
// connection, not a refusal.
|
|
||||||
await request.drain<void>();
|
|
||||||
request.response.statusCode = HttpStatus.forbidden;
|
|
||||||
} else {
|
|
||||||
await _handle(request);
|
await _handle(request);
|
||||||
|
} on Exception {
|
||||||
|
request.response.statusCode = HttpStatus.internalServerError;
|
||||||
}
|
}
|
||||||
} on Exception {
|
await request.response.close();
|
||||||
request.response.statusCode = HttpStatus.internalServerError;
|
|
||||||
}
|
}
|
||||||
await request.response.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A write sent by some other site's page. Any website open in the same
|
|
||||||
/// browser can POST here without a preflight (a CORS "simple request"),
|
|
||||||
/// which would let it overwrite the backups or push unbounded files into
|
|
||||||
/// the attachment store and on to dufs. The app's own page always sends its
|
|
||||||
/// own origin; local tools (curl, tests) send none.
|
|
||||||
bool _isCrossSiteWrite(HttpRequest request) {
|
|
||||||
if (request.method == 'GET' || request.method == 'HEAD') return false;
|
|
||||||
final origin = request.headers.value('origin');
|
|
||||||
return origin != null &&
|
|
||||||
origin != 'http://localhost:$port' &&
|
|
||||||
origin != 'http://127.0.0.1:$port';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _handle(HttpRequest request) async {
|
Future<void> _handle(HttpRequest request) async {
|
||||||
@ -190,10 +152,6 @@ class WrapperServer {
|
|||||||
if (path == kSyncCredentialsPath) {
|
if (path == kSyncCredentialsPath) {
|
||||||
return await _syncCredentials(request);
|
return await _syncCredentials(request);
|
||||||
}
|
}
|
||||||
if (path == kSyncE2ePassphrasePath) {
|
|
||||||
return await _syncE2ePassphrase(request);
|
|
||||||
}
|
|
||||||
if (await images.handle(request)) return;
|
|
||||||
return await _static(request, path);
|
return await _static(request, path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -242,7 +200,37 @@ class WrapperServer {
|
|||||||
await request.response.addStream(file.openRead());
|
await request.response.addStream(file.openRead());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Content type for [filePath]; see [staticContentTypeFor].
|
/// Content type for [filePath].
|
||||||
static ContentType contentTypeFor(String filePath) =>
|
///
|
||||||
staticContentTypeFor(filePath);
|
/// Flutter web is strict here: CanvasKit refuses to instantiate a `.wasm`
|
||||||
|
/// served as anything but `application/wasm`, and the app silently fails to
|
||||||
|
/// render if the bootstrap `.js` is mislabelled.
|
||||||
|
static ContentType contentTypeFor(String filePath) {
|
||||||
|
switch (p.extension(filePath).toLowerCase()) {
|
||||||
|
case '.html':
|
||||||
|
return ContentType.html;
|
||||||
|
case '.js' || '.mjs':
|
||||||
|
return ContentType('text', 'javascript', charset: 'utf-8');
|
||||||
|
case '.json':
|
||||||
|
return ContentType.json;
|
||||||
|
case '.wasm':
|
||||||
|
return ContentType('application', 'wasm');
|
||||||
|
case '.css':
|
||||||
|
return ContentType('text', 'css', charset: 'utf-8');
|
||||||
|
case '.png':
|
||||||
|
return ContentType('image', 'png');
|
||||||
|
case '.svg':
|
||||||
|
return ContentType('image', 'svg+xml');
|
||||||
|
case '.ttf':
|
||||||
|
return ContentType('font', 'ttf');
|
||||||
|
case '.otf':
|
||||||
|
return ContentType('font', 'otf');
|
||||||
|
case '.woff2':
|
||||||
|
return ContentType('font', 'woff2');
|
||||||
|
case '.bin' || '.symbols':
|
||||||
|
return ContentType.binary;
|
||||||
|
default:
|
||||||
|
return ContentType.binary;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -121,23 +121,4 @@ extension _SyncRoutes on WrapperServer {
|
|||||||
// through must remain retryable rather than burning the one serve.
|
// through must remain retryable rather than burning the one serve.
|
||||||
_todoCredentialsServed = true;
|
_todoCredentialsServed = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Serves the shared crdt-sync password as the E2E passphrase, once per
|
|
||||||
/// wrapper process, like [_syncCredentials]: the web app stores it in its
|
|
||||||
/// keystore on first sync and never asks for it.
|
|
||||||
Future<void> _syncE2ePassphrase(HttpRequest request) async {
|
|
||||||
final passwordFile = File(p.join(syncConfigDir, 'password'));
|
|
||||||
if (_e2ePassphraseServed || !passwordFile.existsSync()) {
|
|
||||||
request.response.statusCode = HttpStatus.notFound;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
final text = (await passwordFile.readAsString()).trim();
|
|
||||||
if (text.isEmpty) {
|
|
||||||
request.response.statusCode = HttpStatus.notFound;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
request.response.headers.contentType = ContentType.text;
|
|
||||||
request.response.write(text);
|
|
||||||
_e2ePassphraseServed = true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,112 +0,0 @@
|
|||||||
/// Turning an incoming file into a stored attachment: re-encoded as an image
|
|
||||||
/// when it is one, kept byte-for-byte otherwise.
|
|
||||||
///
|
|
||||||
/// The one place that decides, shared by the Android store and the desktop
|
|
||||||
/// wrapper. The file lands on disk first and is classified from there, so its
|
|
||||||
/// size never reaches memory: only something that sniffs as a photo format
|
|
||||||
/// (see `looksLikeImage`) and is at most [kMaxImageDecodeBytes] is read whole,
|
|
||||||
/// to be decoded. An image that fails to decode is kept as a file rather than
|
|
||||||
/// refused.
|
|
||||||
///
|
|
||||||
/// Pure Dart + `dart:io`.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'dart:io';
|
|
||||||
import 'dart:typed_data';
|
|
||||||
|
|
||||||
import 'package:todo/images/attachment_ref.dart';
|
|
||||||
import 'package:todo/images/image_cache_store.dart';
|
|
||||||
import 'package:todo/images/image_processing.dart';
|
|
||||||
|
|
||||||
/// Stores incoming files in [store], queued for upload.
|
|
||||||
class AttachmentIngest {
|
|
||||||
/// Creates an ingest over [store]; [prepare] is injectable for tests.
|
|
||||||
AttachmentIngest(
|
|
||||||
this.store, {
|
|
||||||
Future<Uint8List?> Function(Uint8List)? prepare,
|
|
||||||
}) : _prepare = prepare ?? prepareImageInBackground;
|
|
||||||
|
|
||||||
/// Where attachments are kept.
|
|
||||||
final ImageCacheStore store;
|
|
||||||
|
|
||||||
final Future<Uint8List?> Function(Uint8List) _prepare;
|
|
||||||
|
|
||||||
/// Stores [data], the contents of a file called [name], for [noteId].
|
|
||||||
Future<Attachment> fromStream(
|
|
||||||
String noteId,
|
|
||||||
String name,
|
|
||||||
Stream<List<int>> data,
|
|
||||||
) async {
|
|
||||||
final ref = AttachmentRef.forFile(noteId, name);
|
|
||||||
final tmp = store.tempFor(ref);
|
|
||||||
await tmp.parent.create(recursive: true);
|
|
||||||
return await _guarded(tmp, () async {
|
|
||||||
final sink = tmp.openWrite();
|
|
||||||
try {
|
|
||||||
await sink.addStream(data);
|
|
||||||
} finally {
|
|
||||||
await sink.close();
|
|
||||||
}
|
|
||||||
return await _settle(ref, name, tmp);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Stores the local file [source], called [name], for [noteId].
|
|
||||||
///
|
|
||||||
/// With [move] (a picker's private copy, nobody else's file) it is renamed
|
|
||||||
/// into place, so a multi-gigabyte pick is never on disk twice; otherwise,
|
|
||||||
/// or across filesystems, it is copied.
|
|
||||||
Future<Attachment> fromFile(
|
|
||||||
String noteId,
|
|
||||||
String name,
|
|
||||||
File source, {
|
|
||||||
required bool move,
|
|
||||||
}) async {
|
|
||||||
if (!move) return await fromStream(noteId, name, source.openRead());
|
|
||||||
final ref = AttachmentRef.forFile(noteId, name);
|
|
||||||
final tmp = store.tempFor(ref);
|
|
||||||
await tmp.parent.create(recursive: true);
|
|
||||||
try {
|
|
||||||
await source.rename(tmp.path);
|
|
||||||
} on FileSystemException {
|
|
||||||
final attachment = await fromStream(noteId, name, source.openRead());
|
|
||||||
await source.delete();
|
|
||||||
return attachment;
|
|
||||||
}
|
|
||||||
return await _guarded(tmp, () => _settle(ref, name, tmp));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Runs [body], removing [tmp] if it fails so a failed attach leaves
|
|
||||||
/// nothing behind.
|
|
||||||
Future<Attachment> _guarded(
|
|
||||||
File tmp,
|
|
||||||
Future<Attachment> Function() body,
|
|
||||||
) async {
|
|
||||||
try {
|
|
||||||
return await body();
|
|
||||||
} on Object {
|
|
||||||
if (tmp.existsSync()) await tmp.delete();
|
|
||||||
rethrow;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<Attachment> _settle(AttachmentRef ref, String name, File tmp) async {
|
|
||||||
if (await tmp.length() <= kMaxImageDecodeBytes && await _sniff(tmp)) {
|
|
||||||
final jpeg = await _prepare(await tmp.readAsBytes());
|
|
||||||
if (jpeg != null) {
|
|
||||||
final image = AttachmentRef.create(ref.noteId);
|
|
||||||
await store.put(image, jpeg);
|
|
||||||
await tmp.delete();
|
|
||||||
return Attachment(ref: image, name: name, isImage: true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
await store.adopt(ref, tmp);
|
|
||||||
return Attachment(ref: ref, name: name, isImage: false);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<bool> _sniff(File file) async {
|
|
||||||
final head = <int>[];
|
|
||||||
await file.openRead(0, kImageSniffBytes).forEach(head.addAll);
|
|
||||||
return looksLikeImage(head);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,65 +0,0 @@
|
|||||||
/// Finding attachment links in a note's text, and rewriting them for
|
|
||||||
/// `BACKLOG.md`.
|
|
||||||
///
|
|
||||||
/// One regex reads both shapes: `` is an image, `[name](url)` a file.
|
|
||||||
/// Matching them together (rather than a file regex beside an image regex)
|
|
||||||
/// is what keeps an image link, which contains `[](url)`, from also counting
|
|
||||||
/// as a file.
|
|
||||||
///
|
|
||||||
/// Pure Dart: the desktop wrapper imports it.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:todo/images/attachment_ref.dart';
|
|
||||||
|
|
||||||
final String _base = RegExp.escape('$kDufsBaseUrl/$kImagesDir/');
|
|
||||||
const _label = r'\[[^\]\n]*\]\(';
|
|
||||||
const _link = r'(!?)\[([^\]\n]*)\]\(';
|
|
||||||
final _anyLink = RegExp('$_link$_base($kAttachmentPathPattern)\\)');
|
|
||||||
final _wholeLine = RegExp('^\\s*${_anyLink.pattern}\\s*\$');
|
|
||||||
final _urlLink = RegExp('($_label)$_base($kAttachmentPathPattern\\))');
|
|
||||||
final _backlogLink = RegExp(
|
|
||||||
'($_label)${RegExp.escape('$kBacklogImagesRoot/')}'
|
|
||||||
'($kAttachmentPathPattern\\))',
|
|
||||||
);
|
|
||||||
|
|
||||||
Attachment _attachment(RegExpMatch match) => Attachment(
|
|
||||||
ref: AttachmentRef.tryParse(match.group(3)!)!,
|
|
||||||
name: match.group(2)!,
|
|
||||||
isImage: match.group(1)!.isNotEmpty,
|
|
||||||
);
|
|
||||||
|
|
||||||
/// Every attachment [text] links to, in order, each ref once.
|
|
||||||
List<Attachment> attachmentsIn(String text) {
|
|
||||||
final seen = <AttachmentRef>{};
|
|
||||||
final found = <Attachment>[];
|
|
||||||
for (final match in _anyLink.allMatches(text)) {
|
|
||||||
final attachment = _attachment(match);
|
|
||||||
if (seen.add(attachment.ref)) found.add(attachment);
|
|
||||||
}
|
|
||||||
return found;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every ref [text] links to, images and files alike.
|
|
||||||
Set<AttachmentRef> attachmentRefsIn(String text) => {
|
|
||||||
for (final attachment in attachmentsIn(text)) attachment.ref,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// The attachment when [line] is nothing but one attachment link, else null.
|
|
||||||
Attachment? attachmentOfLine(String line) {
|
|
||||||
final match = _wholeLine.firstMatch(line);
|
|
||||||
return match == null ? null : _attachment(match);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Rewrites attachment links to their on-disk path under
|
|
||||||
/// [kBacklogImagesRoot].
|
|
||||||
String toBacklogAttachmentPaths(String text) => text.replaceAllMapped(
|
|
||||||
_urlLink,
|
|
||||||
(m) => '${m[1]}$kBacklogImagesRoot/${m[2]}',
|
|
||||||
);
|
|
||||||
|
|
||||||
/// Exact inverse of [toBacklogAttachmentPaths], so an exported backlog
|
|
||||||
/// imports back with its links intact.
|
|
||||||
String fromBacklogAttachmentPaths(String text) => text.replaceAllMapped(
|
|
||||||
_backlogLink,
|
|
||||||
(m) => '${m[1]}$kDufsBaseUrl/$kImagesDir/${m[2]}',
|
|
||||||
);
|
|
||||||
@ -1,153 +0,0 @@
|
|||||||
/// Where a note's attachment lives on dufs.
|
|
||||||
///
|
|
||||||
/// A note never stores attachment bytes: it carries a plain markdown link to
|
|
||||||
/// `https://kuhy-cloud.duckdns.org/todo-images/<noteId>/<uuid>.<ext>` — an
|
|
||||||
/// image as ``, any other file as `[name](…)` — so the CRDT log, the
|
|
||||||
/// sync format and every older build stay untouched (an old build just shows
|
|
||||||
/// the link as text). This file owns the stored path's shape;
|
|
||||||
/// `attachment_links.dart` owns the links that point at it.
|
|
||||||
///
|
|
||||||
/// Pure Dart: the desktop wrapper (`bin/todo_desktop.dart`) imports it.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'package:uuid/uuid.dart';
|
|
||||||
|
|
||||||
/// Public origin of kuhy's dufs server (Caddy → dufs on 127.0.0.1:5000).
|
|
||||||
const kDufsBaseUrl = 'https://kuhy-cloud.duckdns.org';
|
|
||||||
|
|
||||||
/// The dufs folder the `todo` login is scoped to. Named for images, which
|
|
||||||
/// came first; it holds every kind of attachment.
|
|
||||||
const kImagesDir = 'todo-images';
|
|
||||||
|
|
||||||
/// Where the same folder sits on kuhy's PC, as written into `BACKLOG.md` so an
|
|
||||||
/// agent reading the backlog can open the attachment straight from disk.
|
|
||||||
const kBacklogImagesRoot = '~/data/cloud/$kImagesDir';
|
|
||||||
|
|
||||||
/// Extension given to a file whose name has none usable.
|
|
||||||
const kUnknownExtension = 'bin';
|
|
||||||
|
|
||||||
// Segments are restricted to URL- and filesystem-safe characters, which is
|
|
||||||
// what makes a ref safe to join onto a cache directory without a traversal
|
|
||||||
// check of its own. The single, dot-free extension also keeps the cache's
|
|
||||||
// `.pending` and `.tmp` companions from ever parsing as refs.
|
|
||||||
const _segment = '[A-Za-z0-9_-]+';
|
|
||||||
const _extension = '[a-z0-9]{1,10}';
|
|
||||||
|
|
||||||
/// The pattern of a stored path, `<noteId>/<uuid>.<ext>`, for link regexes.
|
|
||||||
const kAttachmentPathPattern = '$_segment/$_segment\\.$_extension';
|
|
||||||
|
|
||||||
final _refPath = RegExp('^$kAttachmentPathPattern\$');
|
|
||||||
final _usableExtension = RegExp('^$_extension\$');
|
|
||||||
final _noteId = RegExp('^$_segment\$');
|
|
||||||
|
|
||||||
/// Whether [noteId] can name an attachment folder.
|
|
||||||
bool isSafeNoteId(String noteId) => _noteId.hasMatch(noteId);
|
|
||||||
|
|
||||||
/// One stored attachment, addressed as `<noteId>/<file>` under [kImagesDir].
|
|
||||||
///
|
|
||||||
/// An extension type over that relative path: equality and hashing are the
|
|
||||||
/// string's, so refs drop straight into sets.
|
|
||||||
extension type const AttachmentRef._(String relativePath) {
|
|
||||||
/// A new, unique ref for an image being attached to [noteId]. Images are
|
|
||||||
/// always stored re-encoded, hence always `.jpg`.
|
|
||||||
factory AttachmentRef.create(String noteId) => _fresh(noteId, 'jpg');
|
|
||||||
|
|
||||||
/// A new, unique ref for the file [fileName] being attached to [noteId],
|
|
||||||
/// keeping its extension when that is short and plain, else
|
|
||||||
/// [kUnknownExtension].
|
|
||||||
factory AttachmentRef.forFile(String noteId, String fileName) =>
|
|
||||||
_fresh(noteId, extensionOf(fileName));
|
|
||||||
|
|
||||||
static AttachmentRef _fresh(String noteId, String extension) {
|
|
||||||
final ref = tryParse('$noteId/${const Uuid().v4()}.$extension');
|
|
||||||
if (ref == null) throw ArgumentError.value(noteId, 'noteId');
|
|
||||||
return ref;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Parses `<noteId>/<file>.<ext>`, or null when it is not a safe path.
|
|
||||||
static AttachmentRef? tryParse(String relativePath) =>
|
|
||||||
_refPath.hasMatch(relativePath) ? AttachmentRef._(relativePath) : null;
|
|
||||||
|
|
||||||
/// The note the attachment was added to (it names the folder only).
|
|
||||||
String get noteId => relativePath.substring(0, relativePath.indexOf('/'));
|
|
||||||
|
|
||||||
/// `<uuid>.<ext>`.
|
|
||||||
String get file => relativePath.substring(relativePath.indexOf('/') + 1);
|
|
||||||
|
|
||||||
/// The lower-case extension, without its dot.
|
|
||||||
String get extension =>
|
|
||||||
relativePath.substring(relativePath.lastIndexOf('.') + 1);
|
|
||||||
|
|
||||||
/// The public dufs URL stored in the note.
|
|
||||||
String get url => '$kDufsBaseUrl/$kImagesDir/$relativePath';
|
|
||||||
|
|
||||||
/// The markdown line that shows this as an inline image.
|
|
||||||
String get imageMarkdown => '';
|
|
||||||
|
|
||||||
/// The markdown line that links this as the file [name].
|
|
||||||
String fileMarkdown(String name) => '[${linkLabel(name)}]($url)';
|
|
||||||
}
|
|
||||||
|
|
||||||
/// [fileName]'s extension, lower-cased, when it is 1–10 letters or digits;
|
|
||||||
/// otherwise [kUnknownExtension].
|
|
||||||
String extensionOf(String fileName) {
|
|
||||||
final dot = fileName.lastIndexOf('.');
|
|
||||||
if (dot <= 0) return kUnknownExtension;
|
|
||||||
final extension = fileName.substring(dot + 1).toLowerCase();
|
|
||||||
return _usableExtension.hasMatch(extension) ? extension : kUnknownExtension;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// [name] made safe as a markdown link label: brackets would end the label
|
|
||||||
/// early and a line break would split the link, so both are replaced.
|
|
||||||
String linkLabel(String name) {
|
|
||||||
final label = name
|
|
||||||
.replaceAll('[', '(')
|
|
||||||
.replaceAll(']', ')')
|
|
||||||
.replaceAll(RegExp(r'[\r\n]+'), ' ')
|
|
||||||
.trim();
|
|
||||||
return label.isEmpty ? 'file' : label;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An attachment as inserted into a note: the stored ref, the name it was
|
|
||||||
/// picked under, and whether it is shown as an image.
|
|
||||||
class Attachment {
|
|
||||||
/// Creates an attachment.
|
|
||||||
const Attachment({
|
|
||||||
required this.ref,
|
|
||||||
required this.name,
|
|
||||||
required this.isImage,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Where it is stored.
|
|
||||||
final AttachmentRef ref;
|
|
||||||
|
|
||||||
/// The file name it was picked or dropped under.
|
|
||||||
final String name;
|
|
||||||
|
|
||||||
/// True for a re-encoded image (``), false for a plain file.
|
|
||||||
final bool isImage;
|
|
||||||
|
|
||||||
/// The line inserted into the note.
|
|
||||||
String get markdown => isImage ? ref.imageMarkdown : ref.fileMarkdown(name);
|
|
||||||
|
|
||||||
/// JSON form, the desktop wrapper's answer to an attach.
|
|
||||||
Map<String, Object> toJson() => {
|
|
||||||
'ref': ref.relativePath,
|
|
||||||
'name': name,
|
|
||||||
'image': isImage,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Parses [toJson]'s output; throws [FormatException] on anything else.
|
|
||||||
static Attachment fromJson(Object? json) {
|
|
||||||
if (json case {
|
|
||||||
'ref': final String path,
|
|
||||||
'name': final String name,
|
|
||||||
'image': final bool isImage,
|
|
||||||
}) {
|
|
||||||
if (AttachmentRef.tryParse(path) case final ref?) {
|
|
||||||
return Attachment(ref: ref, name: name, isImage: isImage);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw FormatException('Not an attachment: $json');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,145 +0,0 @@
|
|||||||
/// The three WebDAV calls attachment sync needs, against kuhy's dufs.
|
|
||||||
///
|
|
||||||
/// Deliberately not dufs-cloud's full `DufsClient` (~700 lines with listing,
|
|
||||||
/// moves, streaming progress and an xml parser): todo only ever puts, gets and
|
|
||||||
/// checks one folder. dufs creates missing parent folders on PUT (verified
|
|
||||||
/// against dufs 0.46.0), so there is no MKCOL step.
|
|
||||||
///
|
|
||||||
/// Bodies stream both ways: an attachment can be gigabytes, and neither the
|
|
||||||
/// phone nor the wrapper may hold one in memory.
|
|
||||||
///
|
|
||||||
/// Pure Dart: the desktop wrapper imports it.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'dart:convert';
|
|
||||||
|
|
||||||
import 'package:http/http.dart' as http;
|
|
||||||
|
|
||||||
import 'package:todo/images/attachment_ref.dart';
|
|
||||||
|
|
||||||
/// A scoped dufs login, e.g. `todo` → `/todo-images`.
|
|
||||||
class DufsLogin {
|
|
||||||
/// Creates a login for [user] with [password] against [baseUrl].
|
|
||||||
const DufsLogin({
|
|
||||||
required this.user,
|
|
||||||
required this.password,
|
|
||||||
this.baseUrl = kDufsBaseUrl,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// The login name (`add_dufs_login.sh`'s first argument).
|
|
||||||
final String user;
|
|
||||||
|
|
||||||
/// Its generated password.
|
|
||||||
final String password;
|
|
||||||
|
|
||||||
/// The dufs origin, without a trailing slash.
|
|
||||||
final String baseUrl;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Outcome of [DufsImageClient.check], for the settings screen.
|
|
||||||
enum DufsCheck {
|
|
||||||
/// The login can see its folder.
|
|
||||||
ok,
|
|
||||||
|
|
||||||
/// dufs refused the login (401/403).
|
|
||||||
rejected,
|
|
||||||
|
|
||||||
/// dufs answered something else, or could not be reached.
|
|
||||||
unreachable,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Upload / download / check for attachments under [kImagesDir].
|
|
||||||
class DufsImageClient {
|
|
||||||
/// Creates a client for [login]; [httpClient] is injectable for tests.
|
|
||||||
DufsImageClient(this.login, {http.Client? httpClient})
|
|
||||||
: _http = httpClient ?? http.Client();
|
|
||||||
|
|
||||||
/// The credentials every request carries.
|
|
||||||
final DufsLogin login;
|
|
||||||
|
|
||||||
final http.Client _http;
|
|
||||||
|
|
||||||
Map<String, String> get _auth {
|
|
||||||
final pair = utf8.encode('${login.user}:${login.password}');
|
|
||||||
return {'authorization': 'Basic ${base64.encode(pair)}'};
|
|
||||||
}
|
|
||||||
|
|
||||||
Uri _uri(String relative) =>
|
|
||||||
Uri.parse('${login.baseUrl}/$kImagesDir/$relative');
|
|
||||||
|
|
||||||
/// PUTs the [length] bytes of [body] as [ref]; true on a 2xx.
|
|
||||||
///
|
|
||||||
/// [body] is only listened to once the connection is up, so a file stream
|
|
||||||
/// passed here is never read when dufs is unreachable.
|
|
||||||
Future<bool> upload(
|
|
||||||
AttachmentRef ref,
|
|
||||||
Stream<List<int>> body,
|
|
||||||
int length,
|
|
||||||
) async {
|
|
||||||
try {
|
|
||||||
final request = _StreamBodyRequest('PUT', _uri(ref.relativePath), body)
|
|
||||||
..contentLength = length
|
|
||||||
..headers.addAll({
|
|
||||||
..._auth,
|
|
||||||
'content-type': ref.extension == 'jpg'
|
|
||||||
? 'image/jpeg'
|
|
||||||
: 'application/octet-stream',
|
|
||||||
});
|
|
||||||
final response = await _http.send(request);
|
|
||||||
await response.stream.drain<void>();
|
|
||||||
return response.statusCode >= 200 && response.statusCode < 300;
|
|
||||||
} on Exception {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// GETs [ref], returning its body as a stream, or null when it is missing
|
|
||||||
/// or unreachable. The caller must consume the stream.
|
|
||||||
Future<Stream<List<int>>?> openDownload(AttachmentRef ref) async {
|
|
||||||
try {
|
|
||||||
final request = http.Request('GET', _uri(ref.relativePath))
|
|
||||||
..headers.addAll(_auth);
|
|
||||||
final response = await _http.send(request);
|
|
||||||
if (response.statusCode == 200) return response.stream;
|
|
||||||
await response.stream.drain<void>();
|
|
||||||
return null;
|
|
||||||
} on Exception {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the login can see its folder (PROPFIND, depth 0).
|
|
||||||
Future<DufsCheck> check() async {
|
|
||||||
try {
|
|
||||||
final request = http.Request('PROPFIND', _uri(''))
|
|
||||||
..headers.addAll({..._auth, 'depth': '0'});
|
|
||||||
final response = await _http.send(request);
|
|
||||||
await response.stream.drain<void>();
|
|
||||||
return switch (response.statusCode) {
|
|
||||||
207 => DufsCheck.ok,
|
|
||||||
401 || 403 => DufsCheck.rejected,
|
|
||||||
_ => DufsCheck.unreachable,
|
|
||||||
};
|
|
||||||
} on Exception {
|
|
||||||
return DufsCheck.unreachable;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Releases the underlying HTTP client.
|
|
||||||
void close() => _http.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A request whose body is an existing stream, pulled by the client as it
|
|
||||||
/// sends. Unlike `http.StreamedRequest`, nothing is buffered when the
|
|
||||||
/// connection fails before the body is wanted.
|
|
||||||
class _StreamBodyRequest extends http.BaseRequest {
|
|
||||||
_StreamBodyRequest(super.method, super.url, this._body);
|
|
||||||
|
|
||||||
final Stream<List<int>> _body;
|
|
||||||
|
|
||||||
@override
|
|
||||||
http.ByteStream finalize() {
|
|
||||||
super.finalize();
|
|
||||||
return http.ByteStream(_body);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,219 +0,0 @@
|
|||||||
/// The on-device copy of every attachment a note links to, plus the upload
|
|
||||||
/// queue.
|
|
||||||
///
|
|
||||||
/// One directory, `<root>/<noteId>/<uuid>.<ext>`, mirrors dufs'
|
|
||||||
/// `todo-images/`. An attachment added while offline gets a
|
|
||||||
/// `<uuid>.<ext>.pending` marker next to it; the marker is the queue, so it
|
|
||||||
/// survives restarts with no separate bookkeeping, and it is only removed
|
|
||||||
/// after dufs has accepted the upload.
|
|
||||||
///
|
|
||||||
/// Files are never held in memory whole: uploads stream from disk and
|
|
||||||
/// downloads stream to a `.tmp` beside the target, renamed only once complete,
|
|
||||||
/// so an interrupted download cannot leave a truncated file that looks done.
|
|
||||||
///
|
|
||||||
/// Used as-is by the Android app and by the desktop wrapper (the web page
|
|
||||||
/// never talks to dufs). Pure Dart + `dart:io`.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'dart:async';
|
|
||||||
import 'dart:io';
|
|
||||||
import 'dart:typed_data';
|
|
||||||
|
|
||||||
import 'package:path/path.dart' as p;
|
|
||||||
import 'package:todo/images/attachment_ref.dart';
|
|
||||||
import 'package:todo/images/dufs_image_client.dart';
|
|
||||||
import 'package:todo/images/reconcile_report.dart';
|
|
||||||
|
|
||||||
export 'package:todo/images/reconcile_report.dart';
|
|
||||||
|
|
||||||
/// How long a cached, unreferenced attachment is kept before eviction, and
|
|
||||||
/// how old an abandoned `.tmp` must be before it is swept.
|
|
||||||
///
|
|
||||||
/// Covers the gap between writing an attachment and its link reaching the
|
|
||||||
/// note store (and, on desktop, the page's next reconcile): without it a
|
|
||||||
/// reconcile landing in that gap would delete a fresh attachment.
|
|
||||||
const kEvictionGrace = Duration(minutes: 10);
|
|
||||||
|
|
||||||
/// Local attachment files and their upload queue under [root].
|
|
||||||
class ImageCacheStore {
|
|
||||||
/// Creates a store rooted at [root]; [now] is injectable for tests.
|
|
||||||
ImageCacheStore(this.root, {DateTime Function()? now})
|
|
||||||
: _now = now ?? DateTime.now;
|
|
||||||
|
|
||||||
/// Directory holding `<noteId>/<uuid>.<ext>`.
|
|
||||||
final Directory root;
|
|
||||||
|
|
||||||
final DateTime Function() _now;
|
|
||||||
|
|
||||||
// Passes run one at a time. Calls arriving before the next pass starts
|
|
||||||
// merge into it (see [reconcile]).
|
|
||||||
Future<void> _tail = Future.value();
|
|
||||||
Future<ReconcileReport>? _scheduled;
|
|
||||||
_Pass? _scheduledPass;
|
|
||||||
|
|
||||||
/// The cached file for [ref] (it may not exist).
|
|
||||||
File fileFor(AttachmentRef ref) =>
|
|
||||||
File(p.join(root.path, ref.noteId, ref.file));
|
|
||||||
|
|
||||||
/// Scratch file next to [ref]'s, for writes that must land whole.
|
|
||||||
File tempFor(AttachmentRef ref) => File('${fileFor(ref).path}.tmp');
|
|
||||||
|
|
||||||
File _marker(AttachmentRef ref) => File('${fileFor(ref).path}.pending');
|
|
||||||
|
|
||||||
/// Whether [ref] is waiting to upload.
|
|
||||||
bool isPending(AttachmentRef ref) => _marker(ref).existsSync();
|
|
||||||
|
|
||||||
/// Stores [bytes] as [ref] and queues it for upload.
|
|
||||||
Future<void> put(AttachmentRef ref, Uint8List bytes) async {
|
|
||||||
final tmp = tempFor(ref);
|
|
||||||
await tmp.parent.create(recursive: true);
|
|
||||||
await tmp.writeAsBytes(bytes, flush: true);
|
|
||||||
await adopt(ref, tmp);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Moves the complete file [tmp] into place as [ref] and queues it for
|
|
||||||
/// upload. [tmp] must be on the same filesystem (see [tempFor]).
|
|
||||||
Future<void> adopt(AttachmentRef ref, File tmp) async {
|
|
||||||
await fileFor(ref).parent.create(recursive: true);
|
|
||||||
// Marker first: a crash between the two then leaves a marker with no
|
|
||||||
// file (skipped by reconcile), never a file that silently never uploads.
|
|
||||||
await _marker(ref).writeAsString('');
|
|
||||||
await tmp.rename(fileFor(ref).path);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every attachment waiting to upload.
|
|
||||||
List<AttachmentRef> pending() => [
|
|
||||||
for (final marker in _files('.pending'))
|
|
||||||
?AttachmentRef.tryParse(_relative(marker).replaceFirst('.pending', '')),
|
|
||||||
];
|
|
||||||
|
|
||||||
/// Uploads the queue, fetches linked attachments this device lacks, and
|
|
||||||
/// evicts cached ones nothing links to any more.
|
|
||||||
///
|
|
||||||
/// Without a [client] (no password set yet) only eviction runs. Eviction is
|
|
||||||
/// skipped entirely when [referenced] is empty — an empty set far more
|
|
||||||
/// likely means "notes not loaded yet" than "everything unlinked" — and it
|
|
||||||
/// never touches a queued attachment or one younger than [kEvictionGrace].
|
|
||||||
///
|
|
||||||
/// Overlapping calls do not run in parallel: calls made before the next
|
|
||||||
/// pass starts share it, with their refs unioned and the newest client.
|
|
||||||
Future<ReconcileReport> reconcile(
|
|
||||||
Set<AttachmentRef> referenced,
|
|
||||||
DufsImageClient? client,
|
|
||||||
) {
|
|
||||||
// Merge into a pass that has not started yet: union the refs (an
|
|
||||||
// upload-only call right after an attach must not wipe a full pass's
|
|
||||||
// refs) and keep the newest client.
|
|
||||||
final waiting = _scheduledPass;
|
|
||||||
_scheduledPass = waiting == null
|
|
||||||
? _Pass(referenced, client)
|
|
||||||
: _Pass({
|
|
||||||
...waiting.referenced,
|
|
||||||
...referenced,
|
|
||||||
}, client ?? waiting.client);
|
|
||||||
final scheduled = _scheduled;
|
|
||||||
if (scheduled != null) return scheduled;
|
|
||||||
final future = _tail.then((_) {
|
|
||||||
final pass = _scheduledPass!;
|
|
||||||
_scheduledPass = null;
|
|
||||||
_scheduled = null;
|
|
||||||
return _run(pass);
|
|
||||||
});
|
|
||||||
_scheduled = future;
|
|
||||||
_tail = future.then<void>((_) {}, onError: (Object _) {});
|
|
||||||
return future;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<ReconcileReport> _run(_Pass pass) async {
|
|
||||||
var uploaded = 0;
|
|
||||||
var downloaded = 0;
|
|
||||||
final client = pass.client;
|
|
||||||
if (client != null) {
|
|
||||||
for (final ref in pending()) {
|
|
||||||
final file = fileFor(ref);
|
|
||||||
if (!file.existsSync()) continue;
|
|
||||||
try {
|
|
||||||
final length = await file.length();
|
|
||||||
if (await client.upload(ref, file.openRead(), length)) {
|
|
||||||
await _marker(ref).delete();
|
|
||||||
uploaded++;
|
|
||||||
}
|
|
||||||
} on FileSystemException {
|
|
||||||
// Deleted mid-pass (note removed, cache cleared): nothing left to
|
|
||||||
// upload. A surviving marker is skipped by the check above next time.
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (final ref in pass.referenced) {
|
|
||||||
if (fileFor(ref).existsSync()) continue;
|
|
||||||
if (await _download(ref, client)) downloaded++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
final evicted = pass.referenced.isEmpty ? 0 : _evict(pass.referenced);
|
|
||||||
return ReconcileReport(
|
|
||||||
uploaded: uploaded,
|
|
||||||
downloaded: downloaded,
|
|
||||||
evicted: evicted,
|
|
||||||
pending: pending().length,
|
|
||||||
missing: pass.referenced.where((r) => !fileFor(r).existsSync()).length,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<bool> _download(AttachmentRef ref, DufsImageClient client) async {
|
|
||||||
final body = await client.openDownload(ref);
|
|
||||||
if (body == null) return false;
|
|
||||||
final tmp = tempFor(ref);
|
|
||||||
try {
|
|
||||||
await tmp.parent.create(recursive: true);
|
|
||||||
final sink = tmp.openWrite();
|
|
||||||
try {
|
|
||||||
await sink.addStream(body);
|
|
||||||
} finally {
|
|
||||||
await sink.close();
|
|
||||||
}
|
|
||||||
await tmp.rename(fileFor(ref).path);
|
|
||||||
return true;
|
|
||||||
} on Exception {
|
|
||||||
// A dropped connection mid-body: retry from scratch next pass.
|
|
||||||
if (tmp.existsSync()) await tmp.delete();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
int _evict(Set<AttachmentRef> referenced) {
|
|
||||||
final cutoff = _now().subtract(kEvictionGrace);
|
|
||||||
var evicted = 0;
|
|
||||||
for (final file in _files('')) {
|
|
||||||
if (file.lastModifiedSync().isAfter(cutoff)) continue;
|
|
||||||
// An abandoned write (killed mid-download or mid-attach): unreachable
|
|
||||||
// by any ref, and possibly gigabytes.
|
|
||||||
if (file.path.endsWith('.tmp')) {
|
|
||||||
file.deleteSync();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
final ref = AttachmentRef.tryParse(_relative(file));
|
|
||||||
if (ref == null || referenced.contains(ref) || isPending(ref)) continue;
|
|
||||||
file.deleteSync();
|
|
||||||
evicted++;
|
|
||||||
}
|
|
||||||
return evicted;
|
|
||||||
}
|
|
||||||
|
|
||||||
List<File> _files(String suffix) {
|
|
||||||
if (!root.existsSync()) return const [];
|
|
||||||
return [
|
|
||||||
for (final entity in root.listSync(recursive: true))
|
|
||||||
if (entity is File && entity.path.endsWith(suffix)) entity,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
String _relative(File file) =>
|
|
||||||
p.split(p.relative(file.path, from: root.path)).join('/');
|
|
||||||
}
|
|
||||||
|
|
||||||
class _Pass {
|
|
||||||
const _Pass(this.referenced, this.client);
|
|
||||||
|
|
||||||
final Set<AttachmentRef> referenced;
|
|
||||||
final DufsImageClient? client;
|
|
||||||
}
|
|
||||||
@ -1,100 +0,0 @@
|
|||||||
/// Shrinks a picked or pasted image to what a note needs, before it is stored
|
|
||||||
/// or uploaded.
|
|
||||||
///
|
|
||||||
/// Phone photos are 3–8 MB with GPS coordinates in their EXIF. Every image is
|
|
||||||
/// re-encoded here: the recorded rotation is applied to the pixels first (so
|
|
||||||
/// dropping EXIF does not leave a portrait photo lying on its side), the long
|
|
||||||
/// side is capped at [kMaxImageSide], and the result is a JPEG with no
|
|
||||||
/// metadata at all.
|
|
||||||
///
|
|
||||||
/// Pure Dart (`package:image`), so the Android app and the desktop wrapper
|
|
||||||
/// run the same code; the web page never decodes images, it hands the raw
|
|
||||||
/// bytes to the wrapper.
|
|
||||||
library;
|
|
||||||
|
|
||||||
import 'dart:isolate';
|
|
||||||
import 'dart:math' as math;
|
|
||||||
import 'dart:typed_data';
|
|
||||||
|
|
||||||
import 'package:image/image.dart' as img;
|
|
||||||
|
|
||||||
/// Longest side, in pixels, of a stored image.
|
|
||||||
const kMaxImageSide = 2560;
|
|
||||||
|
|
||||||
/// JPEG quality of a stored image.
|
|
||||||
const kJpegQuality = 85;
|
|
||||||
|
|
||||||
/// Largest attachment still tried as an image (a raw 50 MP phone photo is
|
|
||||||
/// ~25 MB). Anything bigger is kept as a file: decoding it would need several
|
|
||||||
/// times its size in memory.
|
|
||||||
const int kMaxImageDecodeBytes = 64 * 1024 * 1024;
|
|
||||||
|
|
||||||
/// How many leading bytes [looksLikeImage] needs.
|
|
||||||
const kImageSniffBytes = 12;
|
|
||||||
|
|
||||||
/// Whether [head] starts like a photo or screenshot format: JPEG, PNG, GIF,
|
|
||||||
/// WebP, BMP or TIFF.
|
|
||||||
///
|
|
||||||
/// Only these are re-encoded. `package:image` also decodes PSD, TGA, EXR and
|
|
||||||
/// ICO, but flattening those to a JPEG would destroy what they were attached
|
|
||||||
/// for, so they stay files.
|
|
||||||
bool looksLikeImage(List<int> head) {
|
|
||||||
bool starts(List<int> magic, [int at = 0]) {
|
|
||||||
if (head.length < at + magic.length) return false;
|
|
||||||
for (var i = 0; i < magic.length; i++) {
|
|
||||||
if (head[at + i] != magic[i]) return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const riff = [0x52, 0x49, 0x46, 0x46];
|
|
||||||
const webp = [0x57, 0x45, 0x42, 0x50];
|
|
||||||
return starts(const [0xFF, 0xD8, 0xFF]) ||
|
|
||||||
starts(const [0x89, 0x50, 0x4E, 0x47]) ||
|
|
||||||
starts(const [0x47, 0x49, 0x46, 0x38]) ||
|
|
||||||
(starts(riff) && starts(webp, 8)) ||
|
|
||||||
starts(const [0x42, 0x4D]) ||
|
|
||||||
starts(const [0x49, 0x49, 0x2A, 0x00]) ||
|
|
||||||
starts(const [0x4D, 0x4D, 0x00, 0x2A]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Re-encodes [bytes] as a metadata-free JPEG no larger than [kMaxImageSide]
|
|
||||||
/// on its long side, or returns null when [bytes] is not a decodable image.
|
|
||||||
Uint8List? prepareImage(Uint8List bytes) {
|
|
||||||
final decoded = _decode(bytes);
|
|
||||||
if (decoded == null) return null;
|
|
||||||
var image = img.bakeOrientation(decoded);
|
|
||||||
final longSide = math.max(image.width, image.height);
|
|
||||||
if (longSide > kMaxImageSide) {
|
|
||||||
image = image.width >= image.height
|
|
||||||
? img.copyResize(image, width: kMaxImageSide)
|
|
||||||
: img.copyResize(image, height: kMaxImageSide);
|
|
||||||
}
|
|
||||||
if (image.hasAlpha) image = _flattenOntoWhite(image);
|
|
||||||
image.exif = img.ExifData();
|
|
||||||
return img.encodeJpg(image, quality: kJpegQuality);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// [prepareImage] off the calling isolate: decoding a 12 MP photo takes long
|
|
||||||
/// enough to drop frames if it runs on the UI isolate.
|
|
||||||
Future<Uint8List?> prepareImageInBackground(Uint8List bytes) =>
|
|
||||||
Isolate.run(() => prepareImage(bytes));
|
|
||||||
|
|
||||||
/// `decodeImage` returns null for most non-images but *throws* (a
|
|
||||||
/// RangeError from its PSD sniffer, seen on a 3-byte input) for others; both
|
|
||||||
/// mean "not an image" here.
|
|
||||||
img.Image? _decode(Uint8List bytes) {
|
|
||||||
try {
|
|
||||||
return img.decodeImage(bytes);
|
|
||||||
} on Object {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// JPEG has no alpha: without this a transparent screenshot's clear pixels
|
|
||||||
/// come out as whatever colour their RGB happened to hold, usually black.
|
|
||||||
img.Image _flattenOntoWhite(img.Image image) {
|
|
||||||
final background = img.Image(width: image.width, height: image.height)
|
|
||||||
..clear(img.ColorRgb8(255, 255, 255));
|
|
||||||
return img.compositeImage(background, image);
|
|
||||||
}
|
|
||||||
@ -1,40 +0,0 @@
|
|||||||
/// Counts from one `ImageCacheStore.reconcile` pass.
|
|
||||||
///
|
|
||||||
/// Pure Dart: the desktop wrapper returns it as JSON to the page.
|
|
||||||
library;
|
|
||||||
|
|
||||||
/// Counts from one reconcile pass.
|
|
||||||
class ReconcileReport {
|
|
||||||
/// Creates a report.
|
|
||||||
const ReconcileReport({
|
|
||||||
this.uploaded = 0,
|
|
||||||
this.downloaded = 0,
|
|
||||||
this.evicted = 0,
|
|
||||||
this.pending = 0,
|
|
||||||
this.missing = 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Queued attachments dufs accepted this pass.
|
|
||||||
final int uploaded;
|
|
||||||
|
|
||||||
/// Linked attachments fetched from dufs this pass.
|
|
||||||
final int downloaded;
|
|
||||||
|
|
||||||
/// Unlinked cached attachments deleted.
|
|
||||||
final int evicted;
|
|
||||||
|
|
||||||
/// Attachments still waiting to upload after the pass.
|
|
||||||
final int pending;
|
|
||||||
|
|
||||||
/// Linked attachments still not on this device after the pass.
|
|
||||||
final int missing;
|
|
||||||
|
|
||||||
/// JSON form, for the wrapper's `/images/reconcile` response.
|
|
||||||
Map<String, int> toJson() => {
|
|
||||||
'uploaded': uploaded,
|
|
||||||
'downloaded': downloaded,
|
|
||||||
'evicted': evicted,
|
|
||||||
'pending': pending,
|
|
||||||
'missing': missing,
|
|
||||||
};
|
|
||||||
}
|
|
||||||