Compare commits

..
Author SHA1 Message Date
makiolaj b9e29ad46c Release 1.0.1
Re-release of 1.0.0 under a fresh versionCode for the first Play upload.
2026-09-25 13:06:20 +02:00
493 changed files with 3424 additions and 38951 deletions

No files matched your search

+2 -2
View File
@@ -26,14 +26,14 @@ Which of these ran green, and anything you exercised by hand. On-device notes
are especially useful for UI changes, and for anything touching the provider
read/write paths (OpenTasks / tasks.org installed).
./gradlew lintFullDebug lintOfflineDebug :app:testFullDebugUnitTest :app:testOfflineDebugUnitTest :app:assembleDebug
./gradlew lintDebug :app:testDebugUnitTest :app:assembleDebug
python3 scripts/check_translations.py
-->
### Checklist
- [ ] `./gradlew lintFullDebug lintOfflineDebug :app:testFullDebugUnitTest :app:testOfflineDebugUnitTest :app:assembleDebug` passes locally
- [ ] `./gradlew lintDebug :app:testDebugUnitTest :app:assembleDebug` passes locally
- [ ] New domain logic comes with JVM unit tests under `app/src/test/`
- [ ] Provider details stay inside `data/tasks/`
- [ ] No `values-*/strings.xml` touched (Weblate owns those; new English strings in `values/` are fine)
+8 -40
View File
@@ -37,29 +37,11 @@ jobs:
- name: Reproducible-release invariant
run: bash scripts/check_reproducible_release.sh
# The committed versionName must parse (X.Y.Z or X.Y.Z-beta.N) and the
# committed versionCode must be the one it derives: the official F-Droid
# repo builds the tag as committed. And a beta must never reach main,
# where the release pipeline would ship it to F-Droid and Play; betas are
# cut from release/* branches (docs/RELEASING.md).
- name: Committed version is well-formed
env:
BASE: ${{ github.base_ref }}
run: |
set -e
bash scripts/version_info.sh --check
if [ "${BASE#refs/heads/}" = "main" ] && [ "$(bash scripts/version_info.sh channel)" = "beta" ]; then
echo "ERROR: versionName $(bash scripts/version_info.sh version) is a beta." >&2
echo "Set the stable version (and its versionCode) before merging into main." >&2
exit 1
fi
# Also cheap, also always-on. Two failures in one: the script exits
# non-zero if this version's changelog is over the 500-character limit,
# and the porcelain check below catches a version with no committed
# changelog, which would otherwise ship the CHANGELOG.md section instead
# of a hand-written summary. A beta version passes both: it ships no
# What's New, so the script writes nothing for it.
# of a hand-written summary.
- name: Changelog fits the stores, and is committed
run: |
set -e
@@ -127,14 +109,10 @@ jobs:
- name: Setup Java
if: steps.scope.outputs.code == 'true'
# Temurin only launches Gradle: its versions come from Adoptium, while the
# jetbrains distribution resolves through the GitHub API with the forge's
# token ("Bad credentials"). Gradle fetches the JBR that
# gradle-daemon-jvm.properties pins straight from JetBrains' CDN.
uses: actions/setup-java@v5
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '21'
distribution: 'zulu'
java-version: '17'
# Fully qualified on purpose. Codeberg resolves bare `uses:` refs against
# data.forgejo.org, Forgejo's own action mirror — actions/checkout,
@@ -172,7 +150,6 @@ jobs:
path: |
~/.gradle/caches
~/.gradle/wrapper
~/.gradle/jdks
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', 'gradle/libs.versions.toml') }}
restore-keys: |
${{ runner.os }}-gradle-
@@ -183,30 +160,21 @@ jobs:
# No --no-daemon: the daemon lives only as long as this job container
# and lets the following steps skip JVM startup + reconfiguration.
- name: Lint (debug variants only)
- name: Lint (debug variant only)
if: steps.scope.outputs.code == 'true'
run: ./gradlew lintFullDebug lintOfflineDebug
run: ./gradlew lintDebug
# :dav is a plain JVM module, so it has no testDebugUnitTest — naming only
# that task would compile the vendored suite and run none of it, which is
# the whole safety argument in dav/PROVENANCE.md.
- name: Unit tests
if: steps.scope.outputs.code == 'true'
run: ./gradlew testFullDebugUnitTest testOfflineDebugUnitTest :dav:test :caldav:test
run: ./gradlew testDebugUnitTest :dav:test :caldav:test
- name: Assemble debug APKs
- name: Assemble debug APK
if: steps.scope.outputs.code == 'true'
run: ./gradlew assembleDebug
# Debug builds aren't minified, so a keep rule that drops a reflectively
# created class's constructor only breaks release builds (#1, #75). The
# releaseTest twin is R8-shrunk with the release rules and debug-signed.
- name: R8 keeps reflective constructors
if: steps.scope.outputs.code == 'true'
run: |
./gradlew assembleFullReleaseTest
python3 scripts/check_r8_keeps.py
- name: Trivy filesystem scan
if: steps.scope.outputs.code == 'true'
run: |
+1 -1
View File
@@ -2,7 +2,7 @@ name: Translations
# Fast, SDK-free parity check for translation resources, so Weblate PRs (which
# only touch values-*/strings.xml) get quick feedback without the full Android
# build. The deeper checks still run in CI via lintFullDebug (ExtraTranslation).
# build. The deeper checks still run in CI via lintDebug (ExtraTranslation).
#
# Runs on every PR (no path filter) so the required "Translations / check"
# status is always reported — like the `ci` job. A path-filtered workflow is
-184
View File
@@ -1,184 +0,0 @@
name: Beta — Codeberg pre-release
# A beta is cut by pushing a release branch whose committed versionName is
# X.Y.Z-beta.N (see docs/RELEASING.md). Same model as release.yaml: the
# committed version is the trigger and the vX.Y.Z-beta.N tag is an output. If
# its Codeberg pre-release doesn't carry the APK yet, this runs the unit tests, builds and
# signs the APK with the app key, records a Gitea pre-release (with the R8
# mapping) and publishes a Codeberg pre-release with the APK + SHA-256.
#
# Deliberately nothing else. A beta never reaches the F-Droid repos or Play:
# Obtainium hides pre-releases unless a user opts in, the official F-Droid
# recipe only picks up `^v[0-9.]+$` tags, and Codeberg's "latest release"
# skips pre-releases. Pushes of a release branch carrying a stable version
# (the usual state) fall through `detect` and do nothing.
#
# Lives in .gitea/workflows next to release.yaml for the same reason: it needs
# the app signing key, which only the self-hosted Gitea instance holds.
on:
push:
branches: ['release/**']
concurrency:
group: beta
cancel-in-progress: false
jobs:
detect:
# Gitea only; see the same guard in release.yaml.
if: github.repository_owner == 'makiolaj'
runs-on: light
outputs:
is_beta: ${{ steps.v.outputs.is_beta }}
version: ${{ steps.v.outputs.version }}
version_code: ${{ steps.v.outputs.version_code }}
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Resolve version and whether it still needs publishing
id: v
run: |
set -e
INFO=$(bash scripts/version_info.sh)
echo "$INFO"
echo "$INFO" >> "$GITHUB_OUTPUT"
if [ "$(bash scripts/version_info.sh channel)" != beta ]; then
echo "Not a beta — nothing to do."
echo "is_beta=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# Done only once its Codeberg pre-release carries the APK, so a failed
# publish is redone by the next push; refused unless newer than the
# latest stable release.
GATE=$(bash scripts/release_gate.sh)
echo "is_beta=${GATE#cut=}" >> "$GITHUB_OUTPUT"
beta:
needs: detect
if: needs.detect.outputs.is_beta == 'true'
runs-on: gradle
env:
ANDROID_HOME: /opt/android-sdk
ANDROID_SDK_ROOT: /opt/android-sdk
VERSION: ${{ needs.detect.outputs.version }}
VERSION_CODE: ${{ needs.detect.outputs.version_code }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
submodules: recursive
- name: Setup Java
# Temurin only launches Gradle: its versions come from Adoptium, while the
# jetbrains distribution resolves through the GitHub API with the forge's
# token ("Bad credentials"). Gradle fetches the JBR that
# gradle-daemon-jvm.properties pins straight from JetBrains' CDN.
uses: actions/setup-java@v5
with:
distribution: 'temurin'
java-version: '21'
- name: Setup Android SDK
uses: android-actions/setup-android@v3
with:
packages: ''
- name: Setup Android SDK cache
uses: actions/cache@v4
with:
path: /opt/android-sdk
key: ${{ runner.os }}-android-sdk-37-36.0.0
- name: Install Android SDK packages
run: |
yes | sdkmanager --licenses >/dev/null || true
sdkmanager \
"platform-tools" \
"platforms;android-37.0" \
"build-tools;36.0.0"
- name: Setup Gradle cache
uses: actions/cache@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
~/.gradle/jdks
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', 'gradle/libs.versions.toml') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: Install jq
run: |
set -e
SUDO=""
if command -v sudo >/dev/null 2>&1; then SUDO="sudo"; fi
if command -v apt-get >/dev/null 2>&1; then
$SUDO apt-get update
$SUDO apt-get install -y jq
elif command -v apk >/dev/null 2>&1; then
$SUDO apk add --no-cache jq
fi
- name: Grant execute permission for gradlew
run: chmod +x ./gradlew
- name: Pin versionCode to versionName
run: |
set -e
sed -i "s/versionCode = .*/versionCode = $VERSION_CODE/" app/build.gradle.kts
grep -E 'versionName|versionCode' app/build.gradle.kts
- name: Unit tests
run: ./gradlew testFullDebugUnitTest
# The real app key, same as a stable release: a beta has to update in
# place to the next beta and to the stable version.
- name: Setup Android Keystore
env:
KEYSTORE_BASE64: ${{ secrets.KEYSTORE_BASE64 }}
KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
run: |
mkdir -p app
echo "$KEYSTORE_BASE64" | base64 --decode > app/upload-keystore.jks
cat > key.properties <<EOF
storePassword=$KEY_PASSWORD
keyPassword=$KEY_PASSWORD
keyAlias=$KEY_ALIAS
storeFile=upload-keystore.jks
EOF
# Both flavors; the offline one goes to Codeberg only (issue #39).
- name: Build release APKs
run: ./gradlew assembleRelease
# Notes = a `## [X.Y.Z-beta.N]` section if there is one, else
# `## [Unreleased]`. Gitea creates the tag at this commit.
- name: Create tag + Gitea pre-release
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
SHA: ${{ github.sha }}
run: |
set -e
bash scripts/release_notes.sh "$VERSION" > release-notes.md
cat release-notes.md
TAG="v$VERSION" PRERELEASE=true NOTES_FILE=release-notes.md \
MAPPING=app/build/outputs/mapping/fullRelease/mapping.txt \
MAPPING_OFFLINE=app/build/outputs/mapping/offlineRelease/mapping.txt \
bash scripts/publish_gitea_release.sh
# The point of the whole workflow, so NOT continue-on-error.
- name: Publish pre-release to Codeberg
env:
TOKEN: ${{ secrets.CODEBERG_RELEASE_TOKEN }}
API: https://codeberg.org/api/v1/repos/jlmakiola/agendula
SHA: ${{ github.sha }}
run: |
set -e
TAG="v$VERSION" PRERELEASE=true NOTES_FILE=release-notes.md \
APK=app/build/outputs/apk/full/release/app-full-release.apk \
APK_OFFLINE=app/build/outputs/apk/offline/release/app-offline-release.apk \
bash scripts/publish_codeberg_release.sh
+223 -59
View File
@@ -7,9 +7,7 @@ name: Release — F-Droid repo + Gitea/Codeberg release + Play
# the release on Codeberg with the signed APK + a SHA-256 checksum as a
# direct-download channel — the tag is an output of the pipeline, not its
# trigger. Ordinary merges (no version bump) fall through `detect` and do
# nothing. Betas (X.Y.Z-beta.N) never come through here: beta.yaml cuts them
# from release/* branches as Codeberg-only pre-releases, and `detect` refuses
# one that reaches main.
# nothing.
#
# A trailing `play` job then uploads the App Bundle to Google Play. It is last
# and separate because Play can reject a good build for reasons the pipeline
@@ -48,7 +46,7 @@ jobs:
# secrets. repository_owner differs between the two forges regardless of
# URL, proxy or instance rename, so this closes it permanently.
if: github.repository_owner == 'makiolaj'
runs-on: light
runs-on: docker
outputs:
is_release: ${{ steps.v.outputs.is_release }}
version: ${{ steps.v.outputs.version }}
@@ -62,32 +60,60 @@ jobs:
- name: Resolve version and whether it is a new release
id: v
env:
# Tags are read from Codeberg, which is canonical — deliberately NOT
# from the Gitea API this workflow runs on. The Codeberg -> Gitea sync
# is a push mirror, i.e. `git push --mirror`, which deletes refs the
# source does not have. A tag minted here on Gitea is therefore wiped
# by the next sync (Codeberg does not have it yet) and only reappears
# once the tag push at the end of this workflow propagates back.
# Asking Gitea inside that window would report "no tag" for a release
# that already shipped, and cut it a second time.
# Public repo, so this read needs no token.
TAG_API: https://codeberg.org/api/v1/repos/jlmakiola/agendula
run: |
set -e
# versionName -> versionCode, channel and the pre-release flag (set
# while MAJOR was 0) all come from the one script beta.yaml uses too.
INFO=$(bash scripts/version_info.sh)
echo "$INFO"
echo "$INFO" >> "$GITHUB_OUTPUT"
VERSION=$(echo "$INFO" | sed -n 's/^version=//p')
CHANNEL=$(echo "$INFO" | sed -n 's/^channel=//p')
VERSION=$(grep -oP 'versionName\s*=\s*"\K[^"]+' app/build.gradle.kts)
if [ -z "$VERSION" ]; then echo "No versionName in app/build.gradle.kts" >&2; exit 1; fi
MAJOR=$(echo "$VERSION" | cut -d. -f1); MINOR=$(echo "$VERSION" | cut -d. -f2); PATCH=$(echo "$VERSION" | cut -d. -f3)
MAJOR=${MAJOR:-0}; MINOR=${MINOR:-0}; PATCH=${PATCH:-0}
VERSION_CODE=$(( MAJOR * 10000 + MINOR * 100 + PATCH ))
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
echo "version_code=$VERSION_CODE" >> "$GITHUB_OUTPUT"
# Pre-1.0 is not stable yet: mark the Gitea release as a pre-release
# while MAJOR is 0. Graduates to a stable release automatically at 1.0.0.
if [ "$MAJOR" = "0" ]; then PRERELEASE=true; else PRERELEASE=false; fi
echo "prerelease=$PRERELEASE" >> "$GITHUB_OUTPUT"
echo "Resolved version $VERSION (code $VERSION_CODE, prerelease=$PRERELEASE)"
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
echo "Manual dispatch — re-sign path, not a release."
echo "is_release=false" >> "$GITHUB_OUTPUT"
exit 0
fi
# Betas ship from release/* branches via beta.yaml and must never be
# cut here: this path publishes to F-Droid and Play. CI blocks such a
# PR into main; this is the backstop if one gets through anyway.
if [ "$CHANNEL" != "stable" ]; then
echo "versionName $VERSION on main is a beta. Set the stable version before merging to main." >&2
exit 1
fi
# Tags are read from Codeberg, the canonical forge, by exact name: its
# git/refs/tags API matches by prefix, so v1.1.0-beta.1 would read as
# v1.1.0. A lookup error is fatal rather than read as "no tag".
GATE=$(bash scripts/release_gate.sh)
echo "is_release=${GATE#cut=}" >> "$GITHUB_OUTPUT"
# A tag for this version already existing means the release shipped on
# an earlier push; do nothing. Absent => this merge cuts the release.
#
# Anything other than a clean 200/404 is treated as fatal rather than
# as "no tag". A Codeberg outage or a network blip would otherwise
# read as absent and re-cut a release that has already shipped —
# republishing to F-Droid. Failing here is recoverable; a duplicate
# release is not.
STATUS=$(curl -s -o /dev/null -w '%{http_code}' "$TAG_API/git/refs/tags/v$VERSION" || echo 000)
case "$STATUS" in
200)
echo "Tag v$VERSION already exists on Codeberg — nothing to release."
echo "is_release=false" >> "$GITHUB_OUTPUT"
;;
404)
echo "No tag for v$VERSION on Codeberg yet — cutting the release."
echo "is_release=true" >> "$GITHUB_OUTPUT"
;;
*)
echo "Codeberg tag lookup for v$VERSION returned HTTP $STATUS." >&2
echo "Refusing to guess: treating this as 'no tag' could re-cut a shipped release." >&2
exit 1
;;
esac
# Before a single Gradle task runs: F-Droid truncates the in-client
# changelog, so an over-long one would reach users cut off mid-sentence.
@@ -105,7 +131,7 @@ jobs:
release:
needs: detect
if: needs.detect.outputs.is_release == 'true' || github.event_name == 'workflow_dispatch'
runs-on: gradle
runs-on: docker
env:
ANDROID_HOME: /opt/android-sdk
ANDROID_SDK_ROOT: /opt/android-sdk
@@ -120,14 +146,10 @@ jobs:
submodules: recursive
- name: Setup Java
# Temurin only launches Gradle: its versions come from Adoptium, while the
# jetbrains distribution resolves through the GitHub API with the forge's
# token ("Bad credentials"). Gradle fetches the JBR that
# gradle-daemon-jvm.properties pins straight from JetBrains' CDN.
uses: actions/setup-java@v5
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '21'
distribution: 'zulu'
java-version: '17'
- name: Setup Android SDK
uses: android-actions/setup-android@v3
@@ -154,7 +176,6 @@ jobs:
path: |
~/.gradle/caches
~/.gradle/wrapper
~/.gradle/jdks
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', 'gradle/libs.versions.toml') }}
restore-keys: |
${{ runner.os }}-gradle-
@@ -175,8 +196,8 @@ jobs:
run: chmod +x ./gradlew
# The committed versionName is the source of truth. Pin versionCode to the
# value scripts/version_info.sh derives from it, so the published APK's
# code follows the scheme even if the committed code was forgotten.
# value derived from it so the published APK's code is always
# MAJOR*10000 + MINOR*100 + PATCH even if the committed code was forgotten.
- name: Pin versionCode to versionName
if: env.IS_RELEASE == 'true'
run: |
@@ -187,7 +208,7 @@ jobs:
# Test the exact commit being shipped (only on a real release).
- name: Unit tests
if: env.IS_RELEASE == 'true'
run: ./gradlew testFullDebugUnitTest
run: ./gradlew testDebugUnitTest
- name: Setup Android Keystore
if: env.IS_RELEASE == 'true'
@@ -205,9 +226,7 @@ jobs:
storeFile=upload-keystore.jks
EOF
# Both flavors. Only full goes to F-Droid and Play; the offline one
# (issue #39) is a Codeberg release asset and nothing else.
- name: Build release APKs
- name: Build release APK
if: env.IS_RELEASE == 'true'
run: ./gradlew assembleRelease
@@ -263,7 +282,7 @@ jobs:
run: |
set -e
mkdir -p fdroid/repo
cp app/build/outputs/apk/full/release/app-full-release.apk "fdroid/repo/agendula_v${VERSION}.apk"
cp app/build/outputs/apk/release/app-release.apk "fdroid/repo/agendula_v${VERSION}.apk"
# Per-version "What's New": ensure this version's changelog exists in the
# fastlane tree (committed at release-cut time for the official repo; this
@@ -313,8 +332,6 @@ jobs:
# Creating it with target_commitish makes Gitea create the vX.Y.Z tag at
# this commit, so the tag only ever marks a fully-shipped release (and a
# failure before here leaves no tag, so re-running the workflow retries).
# Also attaches the R8 mapping (best-effort) so user crash stacktraces
# stay deobfuscatable. Notes = this version's CHANGELOG section.
- name: Create tag + Gitea release
if: env.IS_RELEASE == 'true'
env:
@@ -323,18 +340,85 @@ jobs:
SHA: ${{ github.sha }}
run: |
set -e
bash scripts/release_notes.sh "$VERSION" > release-notes.md
TAG="v$VERSION" NOTES_FILE=release-notes.md \
MAPPING=app/build/outputs/mapping/fullRelease/mapping.txt \
MAPPING_OFFLINE=app/build/outputs/mapping/offlineRelease/mapping.txt \
bash scripts/publish_gitea_release.sh
TAG="v$VERSION"
# Notes = this version's CHANGELOG section.
awk -v ver="$VERSION" '
$0 ~ "^## \\[" ver "\\]" { flag = 1; next }
/^## \[/ { flag = 0 }
flag' CHANGELOG.md > release-notes.md
sed -i -e '/./,$!d' release-notes.md
if [ ! -s release-notes.md ]; then
echo "_No changelog entry for ${VERSION} — see CHANGELOG.md._" > release-notes.md
fi
python3 - "$TAG" "$SHA" "$PRERELEASE" <<'PY' > payload.json
import json, sys
print(json.dumps({
"tag_name": sys.argv[1],
"target_commitish": sys.argv[2],
"name": sys.argv[1],
"body": open("release-notes.md").read(),
"draft": False,
# Pre-1.0 releases are flagged as pre-releases (see detect job).
"prerelease": sys.argv[3] == "true",
}))
PY
# Upsert (re-run safe): PATCH if a release for the tag already exists,
# else POST a new one (which also creates the tag at target_commitish).
curl -s -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" > existing.json
ID=$(jq -r '.id // empty' existing.json 2>/dev/null || true)
if [ -n "$ID" ]; then
CODE=$(curl -s -o response.json -w '%{http_code}' -X PATCH \
-H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
-d @payload.json "$API/releases/$ID")
OK=200
else
CODE=$(curl -s -o response.json -w '%{http_code}' -X POST \
-H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
-d @payload.json "$API/releases")
OK=201
fi
cat response.json
if [ "$CODE" != "$OK" ]; then
echo "Release upsert failed with HTTP $CODE (expected $OK)" >&2
exit 1
fi
echo "Created/updated release $TAG at $SHA"
# Archive the R8 mapping so user crash stacktraces stay deobfuscatable.
# Attached to the release (it's not an APK, so it fits the no-binaries
# rule). Best-effort: never fail a release over it.
- name: Attach R8 mapping to Gitea release
if: env.IS_RELEASE == 'true'
continue-on-error: true
env:
TOKEN: ${{ secrets.GITHUB_TOKEN }}
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
run: |
set -e
MAP="app/build/outputs/mapping/release/mapping.txt"
if [ ! -f "$MAP" ]; then echo "No mapping.txt (R8 off?) — skipping."; exit 0; fi
TAG="v$VERSION"
ASSET="mapping-${VERSION}.txt.gz"
gzip -c "$MAP" > "/tmp/$ASSET"
ID=$(curl -s -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" | jq -r '.id // empty')
if [ -z "$ID" ]; then echo "Could not resolve release id — skipping."; exit 0; fi
# Replace any prior asset of the same name (re-run safe).
OLD=$(curl -s -H "Authorization: token $TOKEN" "$API/releases/$ID/assets" \
| jq -r --arg n "$ASSET" '.[] | select(.name==$n) | .id')
[ -n "$OLD" ] && curl -s -X DELETE -H "Authorization: token $TOKEN" "$API/releases/$ID/assets/$OLD" >/dev/null || true
curl -s -X POST -H "Authorization: token $TOKEN" \
-F "attachment=@/tmp/$ASSET" \
"$API/releases/$ID/assets?name=$ASSET" -o /dev/null -w "asset upload HTTP %{http_code}\n"
# Publish the release on Codeberg, which is canonical for tags and
# releases (see docs/RELEASING.md): push the tag there and attach the
# signed APK plus a SHA-256 checksum as the direct-download channel for
# users who don't want F-Droid. The APK is identical to the F-Droid one
# (same app key), so this adds no trust surface. Needs the
# CODEBERG_RELEASE_TOKEN secret; skips cleanly if unset.
# releases (see docs/RELEASING.md). Codeberg push-mirrors branches + tags
# to Gitea, but releases aren't git objects and don't sync in either
# direction — so this step pushes the tag straight to Codeberg and creates
# the release there over the API, attaching the signed APK plus a SHA-256
# checksum as the direct-download channel for users who don't want
# F-Droid. The APK is identical to the F-Droid one (same app key), so this
# adds no trust surface. Needs the CODEBERG_RELEASE_TOKEN secret; skips
# cleanly if unset.
- name: Publish release to Codeberg
if: env.IS_RELEASE == 'true'
# NOT continue-on-error: this step reported green through 0.2.1, 0.2.2,
@@ -347,11 +431,91 @@ jobs:
SHA: ${{ github.sha }}
run: |
set -e
[ -s release-notes.md ] || bash scripts/release_notes.sh "$VERSION" > release-notes.md
TAG="v$VERSION" NOTES_FILE=release-notes.md \
APK=app/build/outputs/apk/full/release/app-full-release.apk \
APK_OFFLINE=app/build/outputs/apk/offline/release/app-offline-release.apk \
bash scripts/publish_codeberg_release.sh
if [ -z "${TOKEN:-}" ]; then
echo "CODEBERG_RELEASE_TOKEN not set — skipping Codeberg publish."
exit 0
fi
TAG="v$VERSION"
APK="app/build/outputs/apk/release/app-release.apk"
if [ ! -f "$APK" ]; then echo "No release APK found — skipping." >&2; exit 1; fi
ASSET_APK="agendula_v${VERSION}.apk"
ASSET_SUM="${ASSET_APK}.sha256"
cp "$APK" "/tmp/$ASSET_APK"
( cd /tmp && sha256sum "$ASSET_APK" > "$ASSET_SUM" )
# Release notes: reuse the section extracted for the Gitea release,
# fall back to the CHANGELOG entry if that step's file is gone.
if [ ! -s release-notes.md ]; then
awk -v ver="$VERSION" '
$0 ~ "^## \\[" ver "\\]" { flag = 1; next }
/^## \[/ { flag = 0 }
flag' CHANGELOG.md > release-notes.md
sed -i -e '/./,$!d' release-notes.md
fi
[ -s release-notes.md ] || echo "_See CHANGELOG.md for ${VERSION}._" > release-notes.md
# Push the tag to Codeberg ourselves. Under Codeberg-canonical the
# mirror runs Codeberg -> Gitea, so waiting for a tag to arrive here
# from Gitea (what 0.3.2 did) would wait forever. The tag this
# pipeline minted on Gitea is in fact *deleted* by the next mirror
# sync until Codeberg has it — so pushing it here is what makes it
# durable on both forges.
#
# Pushing the ref first and attaching with NO target_commitish is
# deliberate: a release POST carrying a target_commitish for a commit
# or tag Codeberg hasn't received yet is what produced the
# empty-bodied 500s. Attaching to a ref that already exists doesn't
# need the API to write one.
git tag -f "$TAG" "$SHA"
git push -f "https://jlmakiola:${TOKEN}@codeberg.org/jlmakiola/agendula.git" \
"refs/tags/$TAG"
python3 - "$TAG" "$PRERELEASE" <<'PY' > cb-payload.json
import json, sys
tag, pre = sys.argv[1:3]
print(json.dumps({
"tag_name": tag,
"name": tag,
"body": open("release-notes.md").read(),
"draft": False,
# Pre-1.0 releases are flagged as pre-releases (see detect job).
"prerelease": pre == "true",
}))
PY
# Create (or update) the release. Codeberg 500s on a POST/GET against a
# tag it has only just received — the release request outruns the
# indexing of the ref we pushed a moment ago — so a single attempt can
# fail even though the very same call succeeds seconds later. Retry
# with backoff, and PATCH in place if a release already exists (re-run
# safe, so re-running never disturbs a published release). A 5xx body
# still exits curl 0, so the loop, not `set -e`, controls the flow.
ID=""
for attempt in 1 2 3 4 5 6; do
EXIST=$(curl -s -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" | jq -r '.id // empty' 2>/dev/null || true)
if [ -n "$EXIST" ]; then
curl -s -o /dev/null -w "release PATCH HTTP %{http_code}\n" -X PATCH \
-H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
-d @cb-payload.json "$API/releases/$EXIST"
ID="$EXIST"; break
fi
CODE=$(curl -s -o cb-response.json -w "%{http_code}" -X POST \
-H "Authorization: token $TOKEN" -H "Content-Type: application/json" \
-d @cb-payload.json "$API/releases")
echo "release POST attempt $attempt HTTP $CODE"
ID=$(jq -r '.id // empty' cb-response.json 2>/dev/null || true)
[ -n "$ID" ] && break
sleep $((attempt * 10))
done
if [ -z "$ID" ]; then echo "Could not resolve Codeberg release id after retries." >&2; exit 1; fi
# Attach APK + checksum, replacing any prior asset of the same name.
for A in "$ASSET_APK" "$ASSET_SUM"; do
OLD=$(curl -s -H "Authorization: token $TOKEN" "$API/releases/$ID/assets" \
| jq -r --arg n "$A" '.[] | select(.name==$n) | .id')
[ -n "$OLD" ] && curl -s -X DELETE -H "Authorization: token $TOKEN" "$API/releases/$ID/assets/$OLD" >/dev/null || true
curl -s -X POST -H "Authorization: token $TOKEN" \
-F "attachment=@/tmp/$A" \
"$API/releases/$ID/assets?name=$A" -o /dev/null -w "asset $A HTTP %{http_code}\n"
done
echo "Published $TAG to Codeberg."
# Play takes an App Bundle, not the APK: a second artifact from the same
# source and signing config. Play treats the release key only as the
@@ -365,7 +529,7 @@ jobs:
- name: Build release AAB
if: env.IS_RELEASE == 'true'
continue-on-error: true
run: ./gradlew bundleFullRelease
run: ./gradlew bundleRelease
# NOT actions/upload-artifact@v4: its client refuses any non-github.com
# server as unsupported GHES (go-gitea/gitea#36024). This fork drops that
@@ -377,7 +541,7 @@ jobs:
uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
with:
name: release-aab-${{ needs.detect.outputs.version }}
path: app/build/outputs/bundle/fullRelease/app-full-release.aab
path: app/build/outputs/bundle/release/app-release.aab
if-no-files-found: error
retention-days: 14
@@ -471,7 +635,7 @@ jobs:
run: |
set -euo pipefail
# Absolute: a lane body runs from fastlane/, not the workspace root.
AAB="$GITHUB_WORKSPACE/dist/app-full-release.aab"
AAB="$GITHUB_WORKSPACE/dist/app-release.aab"
test -f "$AAB" || { echo "No AAB at $AAB — the artifact handoff failed." >&2; ls -la dist || true; exit 1; }
bundle exec fastlane deploy \
aab:"$AAB" \
+2 -11
View File
@@ -1,17 +1,8 @@
name: Renovate
on:
# Every merge to main. Mirror syncs from Codeberg fire push events here (the
# same trigger release.yaml relies on), so a merged Renovate PR is followed
# within minutes by a run that rebases the sibling PRs it just conflicted —
# most bumps touch gradle/libs.versions.toml. Outside renovate.json5's
# `schedule` window such a run only maintains existing branches
# (updateNotScheduled), it never opens new PRs. Renovate's own rebases push
# to renovate/* branches, not main, so this cannot loop.
push:
branches: [main]
# Weekly sweep for new updates. Mondays 05:00 UTC, inside the schedule window
# in renovate.json5 — keep the two in step.
# Weekly sweep. Mondays 05:00 UTC — this cron owns the cadence; the repo's
# renovate.json5 deliberately has no internal schedule (avoids double-gating).
schedule:
- cron: '0 5 * * 1'
# Manual run for an on-demand sweep from the Actions tab.
+2 -257
View File
@@ -7,265 +7,10 @@ All notable changes to this project are documented here. The format follows
## [Unreleased]
## [1.4.0] - 2026-11-25
### Added
- Automatic backup. Settings → Backup & restore can save all your lists as a
dated zip into a folder you pick, every few hours, days or weeks, and keeps
only the latest few (7 by default). Restore one with Import tasks. A
notification says so if backups keep failing (#77).
- A repeating task can repeat from its completion date, as in tasks.org:
ticking it off moves the next date on from the day you did it rather than
from the schedule, so watering a plant a week after you last did is due a
week later even when you were late. Pick "Completion date" under "Repeat
from" in the repeat picker. With Agendula's own storage only; over CalDAV
the choice syncs between Agendula installs, and other apps see the moved
task with its plain rule (#79).
- Upcoming can be limited to tasks due within the next week, two weeks,
month, three months or year, from its view options. The home count and
preview and Upcoming widgets follow; tasks due further ahead stay in All
(#128).
- Default due and start dates for new tasks, under Settings → New task form. A new
task can be due today, tomorrow, the day after, in a week or in a month, and
start today, on its due date, or a day or a week before it. The old "Default
start to today" switch carries over (#107).
- A "Persistent reminders" setting under Notifications brings a swiped-away
reminder straight back, silently, until the task is marked done or snoozed.
Persistent reminders also come back after a reboot. Each list can follow
that setting or keep its reminders always or never persistent, under
Per-list reminders (#100).
- A "Remind right away when past" setting under Notifications: saving a task
whose reminder time has already passed, such as one starting now, notifies
at once instead of leaving the reminder out (#106).
- A list can be searched from its top bar by title, notes or location,
completed tasks included. A completed match can be reopened with its
checkbox, and a title the list doesn't have yet can be added straight from
the search; pressing enter reopens or adds the typed task (#95).
- Task lists can be grouped by due date (Overdue, Today, Upcoming), by day,
by priority or, in smart lists, tags and filters, by list. Pick it under
"Group by" in the list's sort and filter options; each list and view
remembers its own choice. Folded groups stay folded across views, as the
due-date sections already did (#71).
## [1.0.1] - 2026-09-25
### Changed
- Start and due dates are picked in one full-screen sheet with quick dates
(today, tomorrow, next week) and preset times (morning, noon, afternoon,
evening), so the date or the time can be changed on its own without walking
through both pickers. A calendar and a clock are still there for anything
else (#101).
- Start and due each have their own "No time", so one can be a plain date
while the other keeps its time; it replaces the all-day switch, and both
without a time is an all-day task as before. A date without a time beside a
timed one syncs as the start or the end of its day, marked so Agendula reads
it back as a date; other apps show that time. Reminders for it ring at the
all-day reminder time. With a tasks app as the store, both ends gain or
drop their time together (#101).
### Fixed
- CalDAV accounts on servers that give each calendar its own account, such as
all-inkl.com, find their task list instead of reporting none. That list is
the account's calendar itself, so Agendula doesn't offer to delete it or to
create new lists there (#180).
- A task with only a start date gets the default reminder too, counted from
its start, when none of the default reminders is set from the start. Likewise
a task with only a due date gets reminders set from the start, counted from
its due date. This reaches tasks you already have that have no reminders of
their own. A new task starting "now" still takes none from its start, which
would ring at once (#178).
- Closing the keyboard with the back gesture no longer leaves the task lists
squeezed into the top half of the screen, as if the keyboard were still open,
until it was opened again. The editor, task details and pickers kept the same
keyboard-sized gap at the bottom (#177).
## [1.3.2] - 2026-11-13
### Added
- A "Description in reminders" setting under Notifications sets how much of a
task's description a reminder shows: none, a short preview of up to three
lines (the new default), or all of it as before (#156).
### Changed
- A list with its own default reminders is easier to spot. The task editor
notes when the reminders it adds come from the list's defaults rather than
the general one, and Settings → Notifications counts the lists that use
their own and marks them in Per-list reminders (#121).
### Fixed
- With 3-button navigation, the navigation bar no longer covers the last home
search results, and in landscape it no longer covers the home screen, the
task list or the home top bar's buttons. The task details and editor no
longer leave an empty gap between the open keyboard and the text, nor does
the task list while typing in the quick-add bar. On tablets and in landscape
the screens now keep to a centred, readable width as intended (#152).
- Tapping into a long task description in the editor scrolls the line you
tapped above the keyboard as soon as it opens, instead of leaving it hidden
until you start typing (#158).
- Removing a task's last date also removes its reminders, so the task can be
saved again. Reminders you picked yourself come back when you set a new date
(#159).
- With CalDAV sync, ticking off a repeating task should now also move it on in
Apple Reminders, instead of leaving the old occurrence open next to the
completed copy. Edits Agendula uploads raise the task's `SEQUENCE`, which
Apple's apps use to tell a newer version; tasks with an organiser keep
theirs (#137).
- Sub-tasks of a repeating task start over when ticking off its current
occurrence moves it on to its next date, as in tasks.org: completed and
half-done ones open again, and dated ones move along with the task. Before,
the next occurrence showed them already ticked. Unticking gives them back
their state and dates, and repeating sub-tasks keep their own schedule
(#160).
## [1.3.1] - 2026-11-09
### Changed
- Ticking off the current occurrence of a repeating task moves the series on
to its next date and keeps a completed copy, as tasks.org and Apple
Reminders do. Other apps and the web views of servers such as Infomaniak now
see it as done instead of still open. Unticking it moves the series back,
as long as the series hasn't moved on or changed its start since (#137).
### Fixed
- With tasks.org as the storage provider, recurring tasks are recognised as
recurring. Before, editing one removed its recurrence and ticking it off
closed the whole series. With tasks.org and OpenTasks alike, the editor now
shows the task's repeat rule instead of none, and an occurrence changed on
its own stays part of its series (#135).
- With tasks.org or OpenTasks as the storage provider, the order you give your
lists is kept instead of snapping back (#136).
## [1.3.0] - 2026-11-02
### Added
- Self-hosted servers with a self-signed certificate can be added: Agendula
shows the certificate's fingerprint and asks whether to trust it. A server
reached over plain http can be added too, after a warning. If a trusted
certificate is later renewed, "Sign in again" on the account asks about the
new one (#68).
- An account can be given its own name (#105).
- Pull down on the task list to sync (#73).
- Task list sections can be collapsed (#91).
- A pure black theme for AMOLED screens (#99).
- Agendula can show up as "Tasks" in your launcher, picked from launcher
previews as in Calendula (#104).
- Reminder notifications show the task's description (#94).
### Changed
- Adding or opening a task from a widget returns you to the home screen
afterwards (#93).
- A swipe that starts at the screen edge no longer swipes the task (#90).
- Today also lists tasks that start today, and keeps the ones completed today
in a Completed section (#123).
### Fixed
- A task created from Today, or from a Today widget, is due today, so it shows
up there (#122).
- Completing a task from the list, a widget or another device now cancels its
upcoming reminder and clears one already showing (#127, #129).
- The splash screen follows the app's theme, including Black and dynamic
colour, instead of flashing white in dark mode (#119).
- A task saved without its default start or due reminder because it had
already rung (a start of "now", say) gets it once that date is moved later,
if the task has no reminder from that date (#121).
## [1.2.0] - 2026-10-26
### Added
- A reminder can count from the task's start as well as from its due date, and
tasks with only a start date get reminders too. Default reminders can mix
both, e.g. a day before the start and an hour before the due date; each
applies to tasks that have its date (#72).
- An all-day task's reminders can each have their own time, so one task can
remind you at 09:00 and again at 17:00 (#78).
- Other apps can read the tasks kept in Agendula's own database through an
OpenTasks-compatible provider, once you grant them permission. Apps that
already support OpenTasks or tasks.org need only a small change to support
Agendula too (#43).
- With a second permission, other apps can also add, edit, complete and delete
those tasks, including their reminders and tags. They can tick off a single
occurrence of a recurring task. Task lists stay read-only for them (#63).
### Changed
- A new task no longer takes a default reminder whose time has already
passed, so a start of "today" does not ring the moment the task is saved.
- All-day default reminders are whole days; one set in hours rounds to the
nearest day.
- Switching a task between timed and all-day converts its reminders right
away in the editor, so what you see is what gets saved.
- The editor shows the default reminders a new task, or a newly added date,
will get, before you save. Removing them leaves the task without a reminder
instead of falling back to the default.
- Reminders now sync. A reminder set on a task is uploaded as a standard alarm
(`VALARM`), so it also notifies in macOS and iOS Reminders, Thunderbird,
tasks.org and jtx Board, and alarms set in those apps now fire in Agendula
instead of the default reminder. Removing a task's alarm in another app
turns it off here too, rather than falling back to the default (#52).
- A new task with a date, or one that gets a new date, takes the default
reminder for that date as its own, so it travels with the task to the server.
Changing the default later no longer changes those tasks; tasks that rely on
the default today are left as they are.
- On upgrade, reminders on open, synced tasks that so far stayed on this
device are uploaded once.
- Alarms imported from an `.ics` file become reminders on the task.
- Screens now open and close the way they do in Calendula: they slide in, and
a back swipe previews the screen behind before closing (#66).
- Settings now use Calendula's names and layout. Reminders is now
Notifications, Task form is now New task form, and export and import moved
out of Storage into a new Backup & restore section (#66).
### Fixed
- Fixed a crash when a task's date was shown in Russian and other languages
whose dates put a word after the year (#70).
- Widgets no longer turn into the Today widget or show "Can't load content"
after a task is ticked off (#92).
- Ticking off a task in the Tasks and Up next widgets now works in release
builds; until now the tap did nothing (#75).
- The Tasks widget leaves the same gap under its header as its preview (#86).
- The Starts and Due labels in the task form no longer get cut off at large
font sizes (#76).
- Adding an account by email address finds the server again for providers
that publish it in DNS, such as mailbox.org and Posteo. The DNS lookup never
reached the network, so they ended in "isn't a CalDAV server". It now goes
through Android's resolver and respects Private DNS (#97).
- When the server can't be found from your email address, account setup asks
for the server address straight away and keeps your email as the username,
instead of stopping at an error (#97).
## [1.1.0] - 2026-10-10
### Added
- Four new home-screen widgets: Today, Up next, Lists and Week.
- A widget can show tasks from several lists at once, optionally grouped by
list.
- A setting under Settings → Task form pre-fills a new task's start with today.
- An offline version of Agendula with no sync and no network access at all,
published as a separate APK on Codeberg (#39).
- Tags. Add them while editing a task, see them on the task and in lists,
browse them from the home screen and filter any list by them. They are saved
as `CATEGORIES`, so they sync with Nextcloud Tasks, tasks.org and DAVx⁵ (#35).
- Filters. Save your own view of the open tasks by due date (overdue, today,
upcoming, no date, in any combination), lists, tags and minimum priority.
They live on the home screen and can be shown in the Tasks widget, so today
and overdue tasks can now share one widget (#47).
### Changed
- The Tasks widget has agenda-style rows, an optional row colour and an "All
caught up" state. Ticking a task in any widget shows it as done for a moment
before it disappears.
- The "At a glance" widget is gone; the Tasks and Today widgets cover what it
showed.
- Synced lists can be renamed and deleted, not only device-only ones. A
read-only share shows the edit button greyed out and explains why on tap.
- The sort button in task lists now opens "Sort and filter", which can also
filter by tag.
- While editing a task, its title moves into the top bar once you scroll past
it.
### Fixed
- The list editor's Where and smart-lists rows no longer have double padding.
- A field you tap now scrolls fully above the keyboard, and the "add subtask"
row in task lists no longer ends up hidden behind it.
- All-day tasks west of UTC no longer show up a day early in Overdue, Today
and Upcoming.
- First release on Google Play. No changes to the app since 1.0.0.
## [1.0.0] - 2026-09-21
+3 -3
View File
@@ -28,9 +28,9 @@ layer.
## Build, test, lint
```sh
./gradlew :app:assembleDebug # build the debug APKs (full + offline)
./gradlew :app:testFullDebugUnitTest # JVM unit tests (JUnit5 + Truth + Turbine)
./gradlew lintFullDebug lintOfflineDebug # Android lint (CI runs this on every PR)
./gradlew :app:assembleDebug # build the debug APK
./gradlew :app:testDebugUnitTest # JVM unit tests (JUnit5 + Truth + Turbine)
./gradlew lintDebug # Android lint (CI runs this on every PR)
```
CI (`.forgejo/workflows/ci.yaml`, on Codeberg) runs a reproducible-release invariant check,
+6 -67
View File
@@ -15,23 +15,11 @@ required.</p>
</p>
<p>
<a href="https://f-droid.org/packages/de.jeanlucmakiola.agendula/"><img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png" alt="Get it on F-Droid" height="56"></a>
&nbsp;
<a href="https://play.google.com/store/apps/details?id=de.jeanlucmakiola.agendula"><img src="https://play.google.com/intl/en_us/badges/static/images/badges/en_badge_web_generic.png" alt="Get it on Google Play" height="56"></a>
&nbsp;
<a href="https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://codeberg.org/jlmakiola/agendula"><img src="https://github.com/ImranR98/Obtainium/blob/main/assets/graphics/badge_obtainium.png?raw=true" alt="Get it on Obtainium" height="56"></a>
&nbsp;
<a href="https://ko-fi.com/jeanlucmakiola"><img src="https://storage.ko-fi.com/cdn/brandasset/v2/support_me_on_kofi_badge_beige.png" alt="Support me on Ko-fi" height="56"></a>
</p>
<p>
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/01.png" alt="Home screen: today's progress, overdue and upcoming tasks, and your lists" width="18%">
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/02.png" alt="Onboarding: sync with your own CalDAV server" width="18%">
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/03.png" alt="Upcoming list with a task expanded into its subtasks" width="18%">
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/04.png" alt="Task detail: a monthly recurring task with a reminder and priority" width="18%">
<img src="fastlane/metadata/android/en-US/images/phoneScreenshots/05.png" alt="Reminder notification with Done and Snooze actions" width="18%">
</p>
</div>
Agendula is the task-list sibling to [Calendula](https://codeberg.org/jlmakiola/calendula).
@@ -54,8 +42,7 @@ many small *florets* — so the two apps are florets of one bloom.)
this and the following ones, or the whole series.
- **Reminders** that fire at the exact time: several per task, separate defaults
for timed and all-day tasks (globally and per list), Done and Snooze right on
the notification, and they survive reboots. They sync as standard `VALARM`s,
so they also ring in other CalDAV clients, and theirs ring here.
the notification, and they survive reboots.
- **iCalendar import and export** — open an `.ics` or a zip of them, or write any
list out as standard `.ics` files.
- A **home-screen widget**, launcher shortcuts, a Quick Settings tile, and
@@ -81,16 +68,6 @@ back to a full comparison where it does not. Everything the store does not model
is kept verbatim and sent back unchanged, so passing your tasks through Agendula
does not quietly lose fields another client wrote.
### Tested With
The following CalDAV Services have been Tested
| Service | Version | Date | Status | User |
|---|---|---|---|---|
| **Nextcloud** | 25.0.0 | Oct 9th 2026 | ✅ | [@jlmakiola](https://codeberg.org/jlmakiola) [@Schanbro](https://codeberg.org/Schanbro)
## Where your tasks live
| | Where | Sync | Needs |
@@ -102,10 +79,6 @@ Agendula's own store is an ordinary app database, so it **coexists with
OpenTasks rather than replacing it**. If you already sync through a provider,
Agendula can work on top of it exactly as before.
Other apps can read and write the tasks in Agendula's own store through an
OpenTasks-compatible provider, once you grant them permission. See
[docs/CONTENT_PROVIDER.md](docs/CONTENT_PROVIDER.md).
Switching between the two moves nothing — each store keeps its own tasks — so
**Settings → Storage** asks before it switches, and offers to **copy** a
provider's tasks into Agendula's own store when you want to move over. The copy
@@ -116,20 +89,10 @@ proprietary, and open standards — CalDAV and iCalendar — are the lane.
## Install
### F-Droid (recommended)
### F-Droid repository
Agendula is in the official [F-Droid](https://f-droid.org) repository. Search
for Agendula in any F-Droid client, or
[install it from f-droid.org](https://f-droid.org/packages/de.jeanlucmakiola.agendula/).
F-Droid builds from source on its own schedule, so a new version usually shows
up there a few days after release.
### Self-hosted F-Droid repo (fastest updates)
The release pipeline builds, signs and publishes every release to a
self-hosted F-Droid repository, so new versions land there first. Add it once
and your F-Droid client handles updates from then on:
Every release is built, signed and published to a self-hosted F-Droid
repository. Add it once and your F-Droid client handles updates from then on:
1. In your F-Droid client, open *Settings → Repositories → Add* (or open the
link below on your phone):
@@ -148,29 +111,6 @@ APK and a `.sha256` checksum attached — the same APK the F-Droid repository
serves. For automatic updates from there, use
**[Obtainium](https://github.com/ImranR98/Obtainium)** and
**[add Agendula in one tap](https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://codeberg.org/jlmakiola/agendula)**.
Each release carries two APKs (see [Offline version](#offline-version)), so set
*Filter APKs by regular expression* to `^agendula_v` to always get the regular
app.
Betas of upcoming versions are published there too, as pre-releases; to test
them, switch on *Include prereleases* for Agendula in Obtainium.
### Google Play
Agendula is on
[Google Play](https://play.google.com/store/apps/details?id=de.jeanlucmakiola.agendula).
Play builds are signed with Google's key rather than mine, so switching between
Play and any other channel means uninstalling first. Tasks kept only in
Agendula's own database go with it, so sync them to a CalDAV account first.
### Offline version
Each Codeberg release also carries `agendula-offline_v<version>.apk`: Agendula
without CalDAV sync and **without the network permission**, so it cannot
connect to anything. It installs alongside the regular app rather than replacing
it; move tasks between the two with Settings → Backup & restore → Export / Import. In
Obtainium, pick it with *Filter APKs by regular expression* set to
`^agendula-offline_v`.
### Build from source
@@ -186,9 +126,8 @@ JDK 17 and the Android SDK are all it needs; see
## Translations
Translations are managed on a self-hosted **Weblate**, and partial ones are
fine — an untranslated string simply falls back to English.
<a href="https://weblate.dev.jeanlucmakiola.de/engage/agendula/"><img src="https://weblate.dev.jeanlucmakiola.de/widget/agendula/multi-auto.svg" alt="Translation status" width="600"></a>
fine — an untranslated string simply falls back to English. Agendula ships in
English, German and Brazilian Portuguese so far.
**→ [Help translate Agendula](https://weblate.dev.jeanlucmakiola.de/engage/agendula/)**
+11 -60
View File
@@ -1,4 +1,3 @@
import com.android.build.api.artifact.SingleArtifact
import java.util.Properties
import java.io.FileInputStream
@@ -27,14 +26,12 @@ android {
// These committed values ARE the source of truth for a release: merging
// a bumped versionName into main triggers .gitea/workflows/release.yaml,
// which builds this version and then creates the matching vX.Y.Z tag +
// release itself. A versionName of X.Y.Z-beta.N pushed to a release/*
// branch instead cuts a Codeberg-only pre-release (beta.yaml).
// versionCode is derived from versionName by scripts/version_info.sh
// (1.0.x: 1.0.0 -> 10000; from 1.1.0: 1.1.0-beta.1 -> 1010001,
// 1.1.0 -> 1010099), and CI fails if the committed one doesn't match.
// See docs/RELEASING.md.
versionCode = 1040099
versionName = "1.4.0"
// release itself (versionCode is pinned to MAJOR*10000 + MINOR*100 +
// PATCH from versionName, e.g. 1.0.0 -> 10000). Releases were flagged as
// pre-releases while MAJOR was 0; 1.0.0 is the first stable one, and the
// pipeline graduates it on its own. See docs/RELEASING.md.
versionCode = 10001
versionName = "1.0.1"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
@@ -47,20 +44,6 @@ android {
resValue("string", "sync_authority", "de.jeanlucmakiola.agendula.sync")
}
// `offline` (#39): no sync code, network libraries or network permission.
flavorDimensions += "network"
productFlavors {
create("full") {
dimension = "network"
buildConfigField("boolean", "SYNC_ENABLED", "true")
}
create("offline") {
dimension = "network"
applicationIdSuffix = ".offline"
buildConfigField("boolean", "SYNC_ENABLED", "false")
}
}
signingConfigs {
if (keystorePropertiesFile.exists()) {
create("release") {
@@ -223,26 +206,26 @@ dependencies {
// @HiltWorker plumbing.
implementation(libs.androidx.work.runtime.ktx)
// Custom Tabs: the Nextcloud login flow hands the browser an approval page.
"fullImplementation"(libs.androidx.browser)
implementation(libs.androidx.browser)
implementation(libs.androidx.hilt.work)
ksp(libs.androidx.hilt.compiler)
// Push sync: a UnifiedPush distributor delivers the server's WebDAV-Push messages.
"fullImplementation"(libs.unifiedpush.connector)
implementation(libs.unifiedpush.connector)
// RFC 5545 recurrence expansion, in-process; see the catalog for the pin.
implementation(libs.dmfs.lib.recur)
// Vendored dav4jvm — the CalDAV protocol layer. See dav/PROVENANCE.md.
"fullImplementation"(project(":dav"))
implementation(project(":dav"))
// Discovery, auth and Nextcloud Login Flow v2.
"fullImplementation"(project(":caldav"))
implementation(project(":caldav"))
// :dav gets org.xmlpull.v1 from the Android framework at runtime and declares
// xpp3 compileOnly, which is not transitive. Unit tests run on a plain JVM
// with no framework, and android.jar's stub factory returns null under
// isReturnDefaultValues — so anything touching XmlUtils would NPE without a
// real implementation here.
"testFullImplementation"(libs.xpp3)
testImplementation(libs.xpp3)
implementation(libs.androidx.room.runtime)
implementation(libs.androidx.room.ktx)
@@ -261,7 +244,6 @@ dependencies {
implementation(libs.floret.core.crash)
implementation(libs.floret.identity)
implementation(libs.floret.components)
implementation(libs.floret.glance)
debugImplementation(libs.androidx.ui.tooling)
debugImplementation(libs.androidx.ui.test.manifest)
@@ -281,34 +263,3 @@ dependencies {
androidTestImplementation(platform(libs.androidx.compose.bom))
androidTestImplementation(libs.androidx.ui.test.junit4)
}
/** Fails the build if the offline flavor's merged manifest asks for the network. */
abstract class VerifyNoNetworkPermissions : DefaultTask() {
@get:InputFile
@get:PathSensitive(PathSensitivity.NONE)
abstract val manifest: RegularFileProperty
@TaskAction
fun verify() {
val text = manifest.get().asFile.readText()
val found = listOf("INTERNET", "ACCESS_NETWORK_STATE", "ACCESS_WIFI_STATE", "CHANGE_NETWORK_STATE")
.filter { "\"android.permission.$it\"" in text }
if (found.isNotEmpty()) {
throw GradleException(
"The offline flavor's merged manifest declares ${found.joinToString()}. " +
"Remove it in app/src/offline/AndroidManifest.xml with tools:node=\"remove\".",
)
}
}
}
androidComponents {
onVariants(selector().withFlavor("network" to "offline")) { variant ->
val name = variant.name.replaceFirstChar { it.uppercase() }
val verify = tasks.register<VerifyNoNetworkPermissions>("verify${name}Manifest") {
manifest.set(variant.artifacts.get(SingleArtifact.MERGED_MANIFEST))
}
tasks.matching { it.name in setOf("package$name", "package${name}Bundle", "check") }
.configureEach { dependsOn(verify) }
}
}
+2 -2
View File
@@ -7,8 +7,8 @@
# nothing calls it directly — Room then throws InstantiationException, reported
# as "Failed to create an instance of ...". This first bit us through a
# transitive Room (Glance -> WorkManager -> WorkDatabase, built at startup:
# issue #1); Room is now also our own task store, so the rule matters more,
# not less — TasksDatabase is built on the first store read.
# issue #1); Glance is gone and Room is now our own task store, so the rule
# matters more, not less — TasksDatabase is built on the first store read.
-keep class * extends androidx.room.RoomDatabase { <init>(); }
# Compose Compiler may keep its own; defaults are fine
@@ -1,529 +0,0 @@
{
"formatVersion": 1,
"database": {
"version": 2,
"identityHash": "14b159c51416ba27653f6320ac7f6f03",
"entities": [
{
"tableName": "accounts",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `display_name` TEXT NOT NULL, `principal_url` TEXT, `home_set_url` TEXT, `username` TEXT, `last_sync_at` INTEGER, `last_sync_error` TEXT)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "displayName",
"columnName": "display_name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "principalUrl",
"columnName": "principal_url",
"affinity": "TEXT"
},
{
"fieldPath": "homeSetUrl",
"columnName": "home_set_url",
"affinity": "TEXT"
},
{
"fieldPath": "username",
"columnName": "username",
"affinity": "TEXT"
},
{
"fieldPath": "lastSyncAt",
"columnName": "last_sync_at",
"affinity": "INTEGER"
},
{
"fieldPath": "lastSyncError",
"columnName": "last_sync_error",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
}
},
{
"tableName": "task_lists",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `color` INTEGER NOT NULL, `account_id` INTEGER, `is_visible` INTEGER NOT NULL DEFAULT 1, `is_synced` INTEGER NOT NULL DEFAULT 1, `owner` TEXT, `is_read_only` INTEGER NOT NULL DEFAULT 0, `sort_order` INTEGER NOT NULL DEFAULT 0, `href` TEXT, `ctag` TEXT, `sync_token` TEXT, `is_dirty` INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(`account_id`) REFERENCES `accounts`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "color",
"columnName": "color",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "account_id",
"affinity": "INTEGER"
},
{
"fieldPath": "isVisible",
"columnName": "is_visible",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "1"
},
{
"fieldPath": "isSynced",
"columnName": "is_synced",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "1"
},
{
"fieldPath": "owner",
"columnName": "owner",
"affinity": "TEXT"
},
{
"fieldPath": "isReadOnly",
"columnName": "is_read_only",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "sortOrder",
"columnName": "sort_order",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "href",
"columnName": "href",
"affinity": "TEXT"
},
{
"fieldPath": "ctag",
"columnName": "ctag",
"affinity": "TEXT"
},
{
"fieldPath": "syncToken",
"columnName": "sync_token",
"affinity": "TEXT"
},
{
"fieldPath": "isDirty",
"columnName": "is_dirty",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_task_lists_account_id",
"unique": false,
"columnNames": [
"account_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_task_lists_account_id` ON `${TABLE_NAME}` (`account_id`)"
}
],
"foreignKeys": [
{
"table": "accounts",
"onDelete": "SET NULL",
"onUpdate": "NO ACTION",
"columns": [
"account_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "tasks",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `list_id` INTEGER NOT NULL, `uid` TEXT NOT NULL, `href` TEXT, `etag` TEXT, `title` TEXT, `description` TEXT, `location` TEXT, `url` TEXT, `color` INTEGER, `categories` TEXT NOT NULL DEFAULT '', `status` INTEGER NOT NULL DEFAULT 0, `percent_complete` INTEGER, `completed_at` INTEGER, `priority` INTEGER NOT NULL DEFAULT 0, `classification` INTEGER, `dtstart` INTEGER, `due` INTEGER, `duration` TEXT, `is_all_day` INTEGER NOT NULL DEFAULT 0, `timezone` TEXT, `rrule` TEXT, `rdate` TEXT, `exdate` TEXT, `recurrence_id` INTEGER, `master_id` INTEGER, `parent_id` INTEGER, `sort_order` INTEGER NOT NULL DEFAULT 0, `created_at` INTEGER, `last_modified` INTEGER, `sequence` INTEGER NOT NULL DEFAULT 0, `is_dirty` INTEGER NOT NULL DEFAULT 0, `is_deleted` INTEGER NOT NULL DEFAULT 0, `unknown_properties` TEXT, FOREIGN KEY(`list_id`) REFERENCES `task_lists`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`master_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`parent_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "listId",
"columnName": "list_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "uid",
"columnName": "uid",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "href",
"columnName": "href",
"affinity": "TEXT"
},
{
"fieldPath": "etag",
"columnName": "etag",
"affinity": "TEXT"
},
{
"fieldPath": "title",
"columnName": "title",
"affinity": "TEXT"
},
{
"fieldPath": "description",
"columnName": "description",
"affinity": "TEXT"
},
{
"fieldPath": "location",
"columnName": "location",
"affinity": "TEXT"
},
{
"fieldPath": "url",
"columnName": "url",
"affinity": "TEXT"
},
{
"fieldPath": "color",
"columnName": "color",
"affinity": "INTEGER"
},
{
"fieldPath": "categories",
"columnName": "categories",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "percentComplete",
"columnName": "percent_complete",
"affinity": "INTEGER"
},
{
"fieldPath": "completedAt",
"columnName": "completed_at",
"affinity": "INTEGER"
},
{
"fieldPath": "priority",
"columnName": "priority",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "classification",
"columnName": "classification",
"affinity": "INTEGER"
},
{
"fieldPath": "dtstart",
"columnName": "dtstart",
"affinity": "INTEGER"
},
{
"fieldPath": "due",
"columnName": "due",
"affinity": "INTEGER"
},
{
"fieldPath": "duration",
"columnName": "duration",
"affinity": "TEXT"
},
{
"fieldPath": "isAllDay",
"columnName": "is_all_day",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "timezone",
"columnName": "timezone",
"affinity": "TEXT"
},
{
"fieldPath": "rrule",
"columnName": "rrule",
"affinity": "TEXT"
},
{
"fieldPath": "rdate",
"columnName": "rdate",
"affinity": "TEXT"
},
{
"fieldPath": "exdate",
"columnName": "exdate",
"affinity": "TEXT"
},
{
"fieldPath": "recurrenceId",
"columnName": "recurrence_id",
"affinity": "INTEGER"
},
{
"fieldPath": "masterId",
"columnName": "master_id",
"affinity": "INTEGER"
},
{
"fieldPath": "parentId",
"columnName": "parent_id",
"affinity": "INTEGER"
},
{
"fieldPath": "sortOrder",
"columnName": "sort_order",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER"
},
{
"fieldPath": "lastModified",
"columnName": "last_modified",
"affinity": "INTEGER"
},
{
"fieldPath": "sequence",
"columnName": "sequence",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "isDirty",
"columnName": "is_dirty",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "isDeleted",
"columnName": "is_deleted",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "unknownProperties",
"columnName": "unknown_properties",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_tasks_list_id_is_deleted",
"unique": false,
"columnNames": [
"list_id",
"is_deleted"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_list_id_is_deleted` ON `${TABLE_NAME}` (`list_id`, `is_deleted`)"
},
{
"name": "index_tasks_parent_id",
"unique": false,
"columnNames": [
"parent_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_parent_id` ON `${TABLE_NAME}` (`parent_id`)"
},
{
"name": "index_tasks_master_id_recurrence_id",
"unique": false,
"columnNames": [
"master_id",
"recurrence_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_master_id_recurrence_id` ON `${TABLE_NAME}` (`master_id`, `recurrence_id`)"
},
{
"name": "index_tasks_is_dirty",
"unique": false,
"columnNames": [
"is_dirty"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_is_dirty` ON `${TABLE_NAME}` (`is_dirty`)"
},
{
"name": "index_tasks_list_id_uid_recurrence_id",
"unique": true,
"columnNames": [
"list_id",
"uid",
"recurrence_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_tasks_list_id_uid_recurrence_id` ON `${TABLE_NAME}` (`list_id`, `uid`, `recurrence_id`)"
}
],
"foreignKeys": [
{
"table": "task_lists",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"list_id"
],
"referencedColumns": [
"id"
]
},
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"master_id"
],
"referencedColumns": [
"id"
]
},
{
"table": "tasks",
"onDelete": "SET NULL",
"onUpdate": "NO ACTION",
"columns": [
"parent_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "task_alarms",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task_id` INTEGER NOT NULL, `minutes_before` INTEGER NOT NULL, `reference` TEXT NOT NULL DEFAULT 'DUE', `message` TEXT, FOREIGN KEY(`task_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "taskId",
"columnName": "task_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "minutesBefore",
"columnName": "minutes_before",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "reference",
"columnName": "reference",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "'DUE'"
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_task_alarms_task_id",
"unique": false,
"columnNames": [
"task_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_task_alarms_task_id` ON `${TABLE_NAME}` (`task_id`)"
}
],
"foreignKeys": [
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"task_id"
],
"referencedColumns": [
"id"
]
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '14b159c51416ba27653f6320ac7f6f03')"
]
}
}
@@ -1,548 +0,0 @@
{
"formatVersion": 1,
"database": {
"version": 3,
"identityHash": "725292b38bce25ce9032c4650573ae85",
"entities": [
{
"tableName": "accounts",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `display_name` TEXT NOT NULL, `principal_url` TEXT, `home_set_url` TEXT, `username` TEXT, `last_sync_at` INTEGER, `last_sync_error` TEXT)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "displayName",
"columnName": "display_name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "principalUrl",
"columnName": "principal_url",
"affinity": "TEXT"
},
{
"fieldPath": "homeSetUrl",
"columnName": "home_set_url",
"affinity": "TEXT"
},
{
"fieldPath": "username",
"columnName": "username",
"affinity": "TEXT"
},
{
"fieldPath": "lastSyncAt",
"columnName": "last_sync_at",
"affinity": "INTEGER"
},
{
"fieldPath": "lastSyncError",
"columnName": "last_sync_error",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
}
},
{
"tableName": "task_lists",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `color` INTEGER NOT NULL, `account_id` INTEGER, `is_visible` INTEGER NOT NULL DEFAULT 1, `is_synced` INTEGER NOT NULL DEFAULT 1, `owner` TEXT, `is_read_only` INTEGER NOT NULL DEFAULT 0, `sort_order` INTEGER NOT NULL DEFAULT 0, `href` TEXT, `ctag` TEXT, `sync_token` TEXT, `is_dirty` INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(`account_id`) REFERENCES `accounts`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "color",
"columnName": "color",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "account_id",
"affinity": "INTEGER"
},
{
"fieldPath": "isVisible",
"columnName": "is_visible",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "1"
},
{
"fieldPath": "isSynced",
"columnName": "is_synced",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "1"
},
{
"fieldPath": "owner",
"columnName": "owner",
"affinity": "TEXT"
},
{
"fieldPath": "isReadOnly",
"columnName": "is_read_only",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "sortOrder",
"columnName": "sort_order",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "href",
"columnName": "href",
"affinity": "TEXT"
},
{
"fieldPath": "ctag",
"columnName": "ctag",
"affinity": "TEXT"
},
{
"fieldPath": "syncToken",
"columnName": "sync_token",
"affinity": "TEXT"
},
{
"fieldPath": "isDirty",
"columnName": "is_dirty",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_task_lists_account_id",
"unique": false,
"columnNames": [
"account_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_task_lists_account_id` ON `${TABLE_NAME}` (`account_id`)"
}
],
"foreignKeys": [
{
"table": "accounts",
"onDelete": "SET NULL",
"onUpdate": "NO ACTION",
"columns": [
"account_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "tasks",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `list_id` INTEGER NOT NULL, `uid` TEXT NOT NULL, `href` TEXT, `etag` TEXT, `title` TEXT, `description` TEXT, `location` TEXT, `url` TEXT, `color` INTEGER, `categories` TEXT NOT NULL DEFAULT '', `status` INTEGER NOT NULL DEFAULT 0, `percent_complete` INTEGER, `completed_at` INTEGER, `priority` INTEGER NOT NULL DEFAULT 0, `classification` INTEGER, `dtstart` INTEGER, `due` INTEGER, `duration` TEXT, `is_all_day` INTEGER NOT NULL DEFAULT 0, `timezone` TEXT, `rrule` TEXT, `rdate` TEXT, `exdate` TEXT, `recurrence_id` INTEGER, `master_id` INTEGER, `parent_id` INTEGER, `sort_order` INTEGER NOT NULL DEFAULT 0, `created_at` INTEGER, `last_modified` INTEGER, `sequence` INTEGER NOT NULL DEFAULT 0, `is_dirty` INTEGER NOT NULL DEFAULT 0, `is_deleted` INTEGER NOT NULL DEFAULT 0, `unknown_properties` TEXT, `reminders_off` INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(`list_id`) REFERENCES `task_lists`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`master_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`parent_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "listId",
"columnName": "list_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "uid",
"columnName": "uid",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "href",
"columnName": "href",
"affinity": "TEXT"
},
{
"fieldPath": "etag",
"columnName": "etag",
"affinity": "TEXT"
},
{
"fieldPath": "title",
"columnName": "title",
"affinity": "TEXT"
},
{
"fieldPath": "description",
"columnName": "description",
"affinity": "TEXT"
},
{
"fieldPath": "location",
"columnName": "location",
"affinity": "TEXT"
},
{
"fieldPath": "url",
"columnName": "url",
"affinity": "TEXT"
},
{
"fieldPath": "color",
"columnName": "color",
"affinity": "INTEGER"
},
{
"fieldPath": "categories",
"columnName": "categories",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "percentComplete",
"columnName": "percent_complete",
"affinity": "INTEGER"
},
{
"fieldPath": "completedAt",
"columnName": "completed_at",
"affinity": "INTEGER"
},
{
"fieldPath": "priority",
"columnName": "priority",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "classification",
"columnName": "classification",
"affinity": "INTEGER"
},
{
"fieldPath": "dtstart",
"columnName": "dtstart",
"affinity": "INTEGER"
},
{
"fieldPath": "due",
"columnName": "due",
"affinity": "INTEGER"
},
{
"fieldPath": "duration",
"columnName": "duration",
"affinity": "TEXT"
},
{
"fieldPath": "isAllDay",
"columnName": "is_all_day",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "timezone",
"columnName": "timezone",
"affinity": "TEXT"
},
{
"fieldPath": "rrule",
"columnName": "rrule",
"affinity": "TEXT"
},
{
"fieldPath": "rdate",
"columnName": "rdate",
"affinity": "TEXT"
},
{
"fieldPath": "exdate",
"columnName": "exdate",
"affinity": "TEXT"
},
{
"fieldPath": "recurrenceId",
"columnName": "recurrence_id",
"affinity": "INTEGER"
},
{
"fieldPath": "masterId",
"columnName": "master_id",
"affinity": "INTEGER"
},
{
"fieldPath": "parentId",
"columnName": "parent_id",
"affinity": "INTEGER"
},
{
"fieldPath": "sortOrder",
"columnName": "sort_order",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER"
},
{
"fieldPath": "lastModified",
"columnName": "last_modified",
"affinity": "INTEGER"
},
{
"fieldPath": "sequence",
"columnName": "sequence",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "isDirty",
"columnName": "is_dirty",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "isDeleted",
"columnName": "is_deleted",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "unknownProperties",
"columnName": "unknown_properties",
"affinity": "TEXT"
},
{
"fieldPath": "remindersOff",
"columnName": "reminders_off",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_tasks_list_id_is_deleted",
"unique": false,
"columnNames": [
"list_id",
"is_deleted"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_list_id_is_deleted` ON `${TABLE_NAME}` (`list_id`, `is_deleted`)"
},
{
"name": "index_tasks_parent_id",
"unique": false,
"columnNames": [
"parent_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_parent_id` ON `${TABLE_NAME}` (`parent_id`)"
},
{
"name": "index_tasks_master_id_recurrence_id",
"unique": false,
"columnNames": [
"master_id",
"recurrence_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_master_id_recurrence_id` ON `${TABLE_NAME}` (`master_id`, `recurrence_id`)"
},
{
"name": "index_tasks_is_dirty",
"unique": false,
"columnNames": [
"is_dirty"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_is_dirty` ON `${TABLE_NAME}` (`is_dirty`)"
},
{
"name": "index_tasks_list_id_uid_recurrence_id",
"unique": true,
"columnNames": [
"list_id",
"uid",
"recurrence_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_tasks_list_id_uid_recurrence_id` ON `${TABLE_NAME}` (`list_id`, `uid`, `recurrence_id`)"
}
],
"foreignKeys": [
{
"table": "task_lists",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"list_id"
],
"referencedColumns": [
"id"
]
},
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"master_id"
],
"referencedColumns": [
"id"
]
},
{
"table": "tasks",
"onDelete": "SET NULL",
"onUpdate": "NO ACTION",
"columns": [
"parent_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "task_alarms",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task_id` INTEGER NOT NULL, `minutes_before` INTEGER NOT NULL, `reference` TEXT NOT NULL DEFAULT 'DUE', `message` TEXT, `uid` TEXT NOT NULL DEFAULT '', `raw` TEXT, FOREIGN KEY(`task_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "taskId",
"columnName": "task_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "minutesBefore",
"columnName": "minutes_before",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "reference",
"columnName": "reference",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "'DUE'"
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT"
},
{
"fieldPath": "uid",
"columnName": "uid",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "raw",
"columnName": "raw",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_task_alarms_task_id",
"unique": false,
"columnNames": [
"task_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_task_alarms_task_id` ON `${TABLE_NAME}` (`task_id`)"
}
],
"foreignKeys": [
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"task_id"
],
"referencedColumns": [
"id"
]
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '725292b38bce25ce9032c4650573ae85')"
]
}
}
@@ -1,553 +0,0 @@
{
"formatVersion": 1,
"database": {
"version": 4,
"identityHash": "47f3bedbfbf4ddd1db32864c718de83a",
"entities": [
{
"tableName": "accounts",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `display_name` TEXT NOT NULL, `principal_url` TEXT, `home_set_url` TEXT, `username` TEXT, `last_sync_at` INTEGER, `last_sync_error` TEXT, `label` TEXT)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "displayName",
"columnName": "display_name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "principalUrl",
"columnName": "principal_url",
"affinity": "TEXT"
},
{
"fieldPath": "homeSetUrl",
"columnName": "home_set_url",
"affinity": "TEXT"
},
{
"fieldPath": "username",
"columnName": "username",
"affinity": "TEXT"
},
{
"fieldPath": "lastSyncAt",
"columnName": "last_sync_at",
"affinity": "INTEGER"
},
{
"fieldPath": "lastSyncError",
"columnName": "last_sync_error",
"affinity": "TEXT"
},
{
"fieldPath": "label",
"columnName": "label",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
}
},
{
"tableName": "task_lists",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `color` INTEGER NOT NULL, `account_id` INTEGER, `is_visible` INTEGER NOT NULL DEFAULT 1, `is_synced` INTEGER NOT NULL DEFAULT 1, `owner` TEXT, `is_read_only` INTEGER NOT NULL DEFAULT 0, `sort_order` INTEGER NOT NULL DEFAULT 0, `href` TEXT, `ctag` TEXT, `sync_token` TEXT, `is_dirty` INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(`account_id`) REFERENCES `accounts`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "color",
"columnName": "color",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "account_id",
"affinity": "INTEGER"
},
{
"fieldPath": "isVisible",
"columnName": "is_visible",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "1"
},
{
"fieldPath": "isSynced",
"columnName": "is_synced",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "1"
},
{
"fieldPath": "owner",
"columnName": "owner",
"affinity": "TEXT"
},
{
"fieldPath": "isReadOnly",
"columnName": "is_read_only",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "sortOrder",
"columnName": "sort_order",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "href",
"columnName": "href",
"affinity": "TEXT"
},
{
"fieldPath": "ctag",
"columnName": "ctag",
"affinity": "TEXT"
},
{
"fieldPath": "syncToken",
"columnName": "sync_token",
"affinity": "TEXT"
},
{
"fieldPath": "isDirty",
"columnName": "is_dirty",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_task_lists_account_id",
"unique": false,
"columnNames": [
"account_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_task_lists_account_id` ON `${TABLE_NAME}` (`account_id`)"
}
],
"foreignKeys": [
{
"table": "accounts",
"onDelete": "SET NULL",
"onUpdate": "NO ACTION",
"columns": [
"account_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "tasks",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `list_id` INTEGER NOT NULL, `uid` TEXT NOT NULL, `href` TEXT, `etag` TEXT, `title` TEXT, `description` TEXT, `location` TEXT, `url` TEXT, `color` INTEGER, `categories` TEXT NOT NULL DEFAULT '', `status` INTEGER NOT NULL DEFAULT 0, `percent_complete` INTEGER, `completed_at` INTEGER, `priority` INTEGER NOT NULL DEFAULT 0, `classification` INTEGER, `dtstart` INTEGER, `due` INTEGER, `duration` TEXT, `is_all_day` INTEGER NOT NULL DEFAULT 0, `timezone` TEXT, `rrule` TEXT, `rdate` TEXT, `exdate` TEXT, `recurrence_id` INTEGER, `master_id` INTEGER, `parent_id` INTEGER, `sort_order` INTEGER NOT NULL DEFAULT 0, `created_at` INTEGER, `last_modified` INTEGER, `sequence` INTEGER NOT NULL DEFAULT 0, `is_dirty` INTEGER NOT NULL DEFAULT 0, `is_deleted` INTEGER NOT NULL DEFAULT 0, `unknown_properties` TEXT, `reminders_off` INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(`list_id`) REFERENCES `task_lists`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`master_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`parent_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "listId",
"columnName": "list_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "uid",
"columnName": "uid",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "href",
"columnName": "href",
"affinity": "TEXT"
},
{
"fieldPath": "etag",
"columnName": "etag",
"affinity": "TEXT"
},
{
"fieldPath": "title",
"columnName": "title",
"affinity": "TEXT"
},
{
"fieldPath": "description",
"columnName": "description",
"affinity": "TEXT"
},
{
"fieldPath": "location",
"columnName": "location",
"affinity": "TEXT"
},
{
"fieldPath": "url",
"columnName": "url",
"affinity": "TEXT"
},
{
"fieldPath": "color",
"columnName": "color",
"affinity": "INTEGER"
},
{
"fieldPath": "categories",
"columnName": "categories",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "percentComplete",
"columnName": "percent_complete",
"affinity": "INTEGER"
},
{
"fieldPath": "completedAt",
"columnName": "completed_at",
"affinity": "INTEGER"
},
{
"fieldPath": "priority",
"columnName": "priority",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "classification",
"columnName": "classification",
"affinity": "INTEGER"
},
{
"fieldPath": "dtstart",
"columnName": "dtstart",
"affinity": "INTEGER"
},
{
"fieldPath": "due",
"columnName": "due",
"affinity": "INTEGER"
},
{
"fieldPath": "duration",
"columnName": "duration",
"affinity": "TEXT"
},
{
"fieldPath": "isAllDay",
"columnName": "is_all_day",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "timezone",
"columnName": "timezone",
"affinity": "TEXT"
},
{
"fieldPath": "rrule",
"columnName": "rrule",
"affinity": "TEXT"
},
{
"fieldPath": "rdate",
"columnName": "rdate",
"affinity": "TEXT"
},
{
"fieldPath": "exdate",
"columnName": "exdate",
"affinity": "TEXT"
},
{
"fieldPath": "recurrenceId",
"columnName": "recurrence_id",
"affinity": "INTEGER"
},
{
"fieldPath": "masterId",
"columnName": "master_id",
"affinity": "INTEGER"
},
{
"fieldPath": "parentId",
"columnName": "parent_id",
"affinity": "INTEGER"
},
{
"fieldPath": "sortOrder",
"columnName": "sort_order",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER"
},
{
"fieldPath": "lastModified",
"columnName": "last_modified",
"affinity": "INTEGER"
},
{
"fieldPath": "sequence",
"columnName": "sequence",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "isDirty",
"columnName": "is_dirty",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "isDeleted",
"columnName": "is_deleted",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "unknownProperties",
"columnName": "unknown_properties",
"affinity": "TEXT"
},
{
"fieldPath": "remindersOff",
"columnName": "reminders_off",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_tasks_list_id_is_deleted",
"unique": false,
"columnNames": [
"list_id",
"is_deleted"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_list_id_is_deleted` ON `${TABLE_NAME}` (`list_id`, `is_deleted`)"
},
{
"name": "index_tasks_parent_id",
"unique": false,
"columnNames": [
"parent_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_parent_id` ON `${TABLE_NAME}` (`parent_id`)"
},
{
"name": "index_tasks_master_id_recurrence_id",
"unique": false,
"columnNames": [
"master_id",
"recurrence_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_master_id_recurrence_id` ON `${TABLE_NAME}` (`master_id`, `recurrence_id`)"
},
{
"name": "index_tasks_is_dirty",
"unique": false,
"columnNames": [
"is_dirty"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_is_dirty` ON `${TABLE_NAME}` (`is_dirty`)"
},
{
"name": "index_tasks_list_id_uid_recurrence_id",
"unique": true,
"columnNames": [
"list_id",
"uid",
"recurrence_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_tasks_list_id_uid_recurrence_id` ON `${TABLE_NAME}` (`list_id`, `uid`, `recurrence_id`)"
}
],
"foreignKeys": [
{
"table": "task_lists",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"list_id"
],
"referencedColumns": [
"id"
]
},
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"master_id"
],
"referencedColumns": [
"id"
]
},
{
"table": "tasks",
"onDelete": "SET NULL",
"onUpdate": "NO ACTION",
"columns": [
"parent_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "task_alarms",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task_id` INTEGER NOT NULL, `minutes_before` INTEGER NOT NULL, `reference` TEXT NOT NULL DEFAULT 'DUE', `message` TEXT, `uid` TEXT NOT NULL DEFAULT '', `raw` TEXT, FOREIGN KEY(`task_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "taskId",
"columnName": "task_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "minutesBefore",
"columnName": "minutes_before",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "reference",
"columnName": "reference",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "'DUE'"
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT"
},
{
"fieldPath": "uid",
"columnName": "uid",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "raw",
"columnName": "raw",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_task_alarms_task_id",
"unique": false,
"columnNames": [
"task_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_task_alarms_task_id` ON `${TABLE_NAME}` (`task_id`)"
}
],
"foreignKeys": [
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"task_id"
],
"referencedColumns": [
"id"
]
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '47f3bedbfbf4ddd1db32864c718de83a')"
]
}
}
@@ -1,768 +0,0 @@
{
"formatVersion": 1,
"database": {
"version": 5,
"identityHash": "fcb14ff68d892c72fa7459204276abb6",
"entities": [
{
"tableName": "accounts",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `display_name` TEXT NOT NULL, `principal_url` TEXT, `home_set_url` TEXT, `username` TEXT, `last_sync_at` INTEGER, `last_sync_error` TEXT, `label` TEXT)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "displayName",
"columnName": "display_name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "principalUrl",
"columnName": "principal_url",
"affinity": "TEXT"
},
{
"fieldPath": "homeSetUrl",
"columnName": "home_set_url",
"affinity": "TEXT"
},
{
"fieldPath": "username",
"columnName": "username",
"affinity": "TEXT"
},
{
"fieldPath": "lastSyncAt",
"columnName": "last_sync_at",
"affinity": "INTEGER"
},
{
"fieldPath": "lastSyncError",
"columnName": "last_sync_error",
"affinity": "TEXT"
},
{
"fieldPath": "label",
"columnName": "label",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
}
},
{
"tableName": "task_lists",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `color` INTEGER NOT NULL, `account_id` INTEGER, `is_visible` INTEGER NOT NULL DEFAULT 1, `is_synced` INTEGER NOT NULL DEFAULT 1, `owner` TEXT, `is_read_only` INTEGER NOT NULL DEFAULT 0, `sort_order` INTEGER NOT NULL DEFAULT 0, `href` TEXT, `ctag` TEXT, `sync_token` TEXT, `is_dirty` INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(`account_id`) REFERENCES `accounts`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "color",
"columnName": "color",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "account_id",
"affinity": "INTEGER"
},
{
"fieldPath": "isVisible",
"columnName": "is_visible",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "1"
},
{
"fieldPath": "isSynced",
"columnName": "is_synced",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "1"
},
{
"fieldPath": "owner",
"columnName": "owner",
"affinity": "TEXT"
},
{
"fieldPath": "isReadOnly",
"columnName": "is_read_only",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "sortOrder",
"columnName": "sort_order",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "href",
"columnName": "href",
"affinity": "TEXT"
},
{
"fieldPath": "ctag",
"columnName": "ctag",
"affinity": "TEXT"
},
{
"fieldPath": "syncToken",
"columnName": "sync_token",
"affinity": "TEXT"
},
{
"fieldPath": "isDirty",
"columnName": "is_dirty",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_task_lists_account_id",
"unique": false,
"columnNames": [
"account_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_task_lists_account_id` ON `${TABLE_NAME}` (`account_id`)"
}
],
"foreignKeys": [
{
"table": "accounts",
"onDelete": "SET NULL",
"onUpdate": "NO ACTION",
"columns": [
"account_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "tasks",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `list_id` INTEGER NOT NULL, `uid` TEXT NOT NULL, `href` TEXT, `etag` TEXT, `title` TEXT, `description` TEXT, `location` TEXT, `url` TEXT, `color` INTEGER, `categories` TEXT NOT NULL DEFAULT '', `status` INTEGER NOT NULL DEFAULT 0, `percent_complete` INTEGER, `completed_at` INTEGER, `priority` INTEGER NOT NULL DEFAULT 0, `classification` INTEGER, `dtstart` INTEGER, `due` INTEGER, `duration` TEXT, `is_all_day` INTEGER NOT NULL DEFAULT 0, `timezone` TEXT, `rrule` TEXT, `rdate` TEXT, `exdate` TEXT, `recurrence_id` INTEGER, `master_id` INTEGER, `parent_id` INTEGER, `sort_order` INTEGER NOT NULL DEFAULT 0, `created_at` INTEGER, `last_modified` INTEGER, `sequence` INTEGER NOT NULL DEFAULT 0, `is_dirty` INTEGER NOT NULL DEFAULT 0, `is_deleted` INTEGER NOT NULL DEFAULT 0, `unknown_properties` TEXT, `reminders_off` INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(`list_id`) REFERENCES `task_lists`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`master_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`parent_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "listId",
"columnName": "list_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "uid",
"columnName": "uid",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "href",
"columnName": "href",
"affinity": "TEXT"
},
{
"fieldPath": "etag",
"columnName": "etag",
"affinity": "TEXT"
},
{
"fieldPath": "title",
"columnName": "title",
"affinity": "TEXT"
},
{
"fieldPath": "description",
"columnName": "description",
"affinity": "TEXT"
},
{
"fieldPath": "location",
"columnName": "location",
"affinity": "TEXT"
},
{
"fieldPath": "url",
"columnName": "url",
"affinity": "TEXT"
},
{
"fieldPath": "color",
"columnName": "color",
"affinity": "INTEGER"
},
{
"fieldPath": "categories",
"columnName": "categories",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "percentComplete",
"columnName": "percent_complete",
"affinity": "INTEGER"
},
{
"fieldPath": "completedAt",
"columnName": "completed_at",
"affinity": "INTEGER"
},
{
"fieldPath": "priority",
"columnName": "priority",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "classification",
"columnName": "classification",
"affinity": "INTEGER"
},
{
"fieldPath": "dtstart",
"columnName": "dtstart",
"affinity": "INTEGER"
},
{
"fieldPath": "due",
"columnName": "due",
"affinity": "INTEGER"
},
{
"fieldPath": "duration",
"columnName": "duration",
"affinity": "TEXT"
},
{
"fieldPath": "isAllDay",
"columnName": "is_all_day",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "timezone",
"columnName": "timezone",
"affinity": "TEXT"
},
{
"fieldPath": "rrule",
"columnName": "rrule",
"affinity": "TEXT"
},
{
"fieldPath": "rdate",
"columnName": "rdate",
"affinity": "TEXT"
},
{
"fieldPath": "exdate",
"columnName": "exdate",
"affinity": "TEXT"
},
{
"fieldPath": "recurrenceId",
"columnName": "recurrence_id",
"affinity": "INTEGER"
},
{
"fieldPath": "masterId",
"columnName": "master_id",
"affinity": "INTEGER"
},
{
"fieldPath": "parentId",
"columnName": "parent_id",
"affinity": "INTEGER"
},
{
"fieldPath": "sortOrder",
"columnName": "sort_order",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER"
},
{
"fieldPath": "lastModified",
"columnName": "last_modified",
"affinity": "INTEGER"
},
{
"fieldPath": "sequence",
"columnName": "sequence",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "isDirty",
"columnName": "is_dirty",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "isDeleted",
"columnName": "is_deleted",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "unknownProperties",
"columnName": "unknown_properties",
"affinity": "TEXT"
},
{
"fieldPath": "remindersOff",
"columnName": "reminders_off",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_tasks_list_id_is_deleted",
"unique": false,
"columnNames": [
"list_id",
"is_deleted"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_list_id_is_deleted` ON `${TABLE_NAME}` (`list_id`, `is_deleted`)"
},
{
"name": "index_tasks_parent_id",
"unique": false,
"columnNames": [
"parent_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_parent_id` ON `${TABLE_NAME}` (`parent_id`)"
},
{
"name": "index_tasks_master_id_recurrence_id",
"unique": false,
"columnNames": [
"master_id",
"recurrence_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_master_id_recurrence_id` ON `${TABLE_NAME}` (`master_id`, `recurrence_id`)"
},
{
"name": "index_tasks_is_dirty",
"unique": false,
"columnNames": [
"is_dirty"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_is_dirty` ON `${TABLE_NAME}` (`is_dirty`)"
},
{
"name": "index_tasks_list_id_uid_recurrence_id",
"unique": true,
"columnNames": [
"list_id",
"uid",
"recurrence_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_tasks_list_id_uid_recurrence_id` ON `${TABLE_NAME}` (`list_id`, `uid`, `recurrence_id`)"
}
],
"foreignKeys": [
{
"table": "task_lists",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"list_id"
],
"referencedColumns": [
"id"
]
},
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"master_id"
],
"referencedColumns": [
"id"
]
},
{
"table": "tasks",
"onDelete": "SET NULL",
"onUpdate": "NO ACTION",
"columns": [
"parent_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "task_alarms",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task_id` INTEGER NOT NULL, `minutes_before` INTEGER NOT NULL, `reference` TEXT NOT NULL DEFAULT 'DUE', `message` TEXT, `uid` TEXT NOT NULL DEFAULT '', `raw` TEXT, FOREIGN KEY(`task_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "taskId",
"columnName": "task_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "minutesBefore",
"columnName": "minutes_before",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "reference",
"columnName": "reference",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "'DUE'"
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT"
},
{
"fieldPath": "uid",
"columnName": "uid",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "raw",
"columnName": "raw",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_task_alarms_task_id",
"unique": false,
"columnNames": [
"task_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_task_alarms_task_id` ON `${TABLE_NAME}` (`task_id`)"
}
],
"foreignKeys": [
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"task_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "advanced_occurrences",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`copy_id` INTEGER NOT NULL, `master_id` INTEGER NOT NULL, `anchor` INTEGER NOT NULL, `advanced_to` INTEGER NOT NULL, `prior_dtstart` INTEGER, `prior_due` INTEGER, `prior_status` INTEGER NOT NULL, `prior_percent_complete` INTEGER, `prior_completed_at` INTEGER, `spent` INTEGER NOT NULL, `rule_after` TEXT, `dropped_exdates` TEXT NOT NULL DEFAULT '', `from_override` INTEGER NOT NULL, `undoable` INTEGER NOT NULL DEFAULT 1, `settled` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`copy_id`), FOREIGN KEY(`copy_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`master_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "copyId",
"columnName": "copy_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "masterId",
"columnName": "master_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "anchor",
"columnName": "anchor",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "advancedTo",
"columnName": "advanced_to",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "priorDtstart",
"columnName": "prior_dtstart",
"affinity": "INTEGER"
},
{
"fieldPath": "priorDue",
"columnName": "prior_due",
"affinity": "INTEGER"
},
{
"fieldPath": "priorStatus",
"columnName": "prior_status",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "priorPercentComplete",
"columnName": "prior_percent_complete",
"affinity": "INTEGER"
},
{
"fieldPath": "priorCompletedAt",
"columnName": "prior_completed_at",
"affinity": "INTEGER"
},
{
"fieldPath": "spent",
"columnName": "spent",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "ruleAfter",
"columnName": "rule_after",
"affinity": "TEXT"
},
{
"fieldPath": "droppedExdates",
"columnName": "dropped_exdates",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "fromOverride",
"columnName": "from_override",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "undoable",
"columnName": "undoable",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "1"
},
{
"fieldPath": "settled",
"columnName": "settled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"copy_id"
]
},
"indices": [
{
"name": "index_advanced_occurrences_master_id_anchor",
"unique": false,
"columnNames": [
"master_id",
"anchor"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_advanced_occurrences_master_id_anchor` ON `${TABLE_NAME}` (`master_id`, `anchor`)"
}
],
"foreignKeys": [
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"copy_id"
],
"referencedColumns": [
"id"
]
},
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"master_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "advanced_detached",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `copy_id` INTEGER NOT NULL, `anchor` INTEGER NOT NULL, `task_id` INTEGER, FOREIGN KEY(`copy_id`) REFERENCES `advanced_occurrences`(`copy_id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`task_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "copyId",
"columnName": "copy_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "anchor",
"columnName": "anchor",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "taskId",
"columnName": "task_id",
"affinity": "INTEGER"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_advanced_detached_copy_id",
"unique": false,
"columnNames": [
"copy_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_advanced_detached_copy_id` ON `${TABLE_NAME}` (`copy_id`)"
},
{
"name": "index_advanced_detached_task_id",
"unique": false,
"columnNames": [
"task_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_advanced_detached_task_id` ON `${TABLE_NAME}` (`task_id`)"
}
],
"foreignKeys": [
{
"table": "advanced_occurrences",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"copy_id"
],
"referencedColumns": [
"copy_id"
]
},
{
"table": "tasks",
"onDelete": "SET NULL",
"onUpdate": "NO ACTION",
"columns": [
"task_id"
],
"referencedColumns": [
"id"
]
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'fcb14ff68d892c72fa7459204276abb6')"
]
}
}
@@ -1,775 +0,0 @@
{
"formatVersion": 1,
"database": {
"version": 6,
"identityHash": "6c8058a22084f0af602bc2f23c949b3c",
"entities": [
{
"tableName": "accounts",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `display_name` TEXT NOT NULL, `principal_url` TEXT, `home_set_url` TEXT, `username` TEXT, `last_sync_at` INTEGER, `last_sync_error` TEXT, `label` TEXT)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "displayName",
"columnName": "display_name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "principalUrl",
"columnName": "principal_url",
"affinity": "TEXT"
},
{
"fieldPath": "homeSetUrl",
"columnName": "home_set_url",
"affinity": "TEXT"
},
{
"fieldPath": "username",
"columnName": "username",
"affinity": "TEXT"
},
{
"fieldPath": "lastSyncAt",
"columnName": "last_sync_at",
"affinity": "INTEGER"
},
{
"fieldPath": "lastSyncError",
"columnName": "last_sync_error",
"affinity": "TEXT"
},
{
"fieldPath": "label",
"columnName": "label",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
}
},
{
"tableName": "task_lists",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `color` INTEGER NOT NULL, `account_id` INTEGER, `is_visible` INTEGER NOT NULL DEFAULT 1, `is_synced` INTEGER NOT NULL DEFAULT 1, `owner` TEXT, `is_read_only` INTEGER NOT NULL DEFAULT 0, `sort_order` INTEGER NOT NULL DEFAULT 0, `href` TEXT, `ctag` TEXT, `sync_token` TEXT, `is_dirty` INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(`account_id`) REFERENCES `accounts`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "color",
"columnName": "color",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "account_id",
"affinity": "INTEGER"
},
{
"fieldPath": "isVisible",
"columnName": "is_visible",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "1"
},
{
"fieldPath": "isSynced",
"columnName": "is_synced",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "1"
},
{
"fieldPath": "owner",
"columnName": "owner",
"affinity": "TEXT"
},
{
"fieldPath": "isReadOnly",
"columnName": "is_read_only",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "sortOrder",
"columnName": "sort_order",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "href",
"columnName": "href",
"affinity": "TEXT"
},
{
"fieldPath": "ctag",
"columnName": "ctag",
"affinity": "TEXT"
},
{
"fieldPath": "syncToken",
"columnName": "sync_token",
"affinity": "TEXT"
},
{
"fieldPath": "isDirty",
"columnName": "is_dirty",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_task_lists_account_id",
"unique": false,
"columnNames": [
"account_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_task_lists_account_id` ON `${TABLE_NAME}` (`account_id`)"
}
],
"foreignKeys": [
{
"table": "accounts",
"onDelete": "SET NULL",
"onUpdate": "NO ACTION",
"columns": [
"account_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "tasks",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `list_id` INTEGER NOT NULL, `uid` TEXT NOT NULL, `href` TEXT, `etag` TEXT, `title` TEXT, `description` TEXT, `location` TEXT, `url` TEXT, `color` INTEGER, `categories` TEXT NOT NULL DEFAULT '', `status` INTEGER NOT NULL DEFAULT 0, `percent_complete` INTEGER, `completed_at` INTEGER, `priority` INTEGER NOT NULL DEFAULT 0, `classification` INTEGER, `dtstart` INTEGER, `due` INTEGER, `duration` TEXT, `is_all_day` INTEGER NOT NULL DEFAULT 0, `timezone` TEXT, `rrule` TEXT, `rdate` TEXT, `exdate` TEXT, `recurrence_id` INTEGER, `master_id` INTEGER, `parent_id` INTEGER, `sort_order` INTEGER NOT NULL DEFAULT 0, `created_at` INTEGER, `last_modified` INTEGER, `sequence` INTEGER NOT NULL DEFAULT 0, `is_dirty` INTEGER NOT NULL DEFAULT 0, `is_deleted` INTEGER NOT NULL DEFAULT 0, `unknown_properties` TEXT, `reminders_off` INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(`list_id`) REFERENCES `task_lists`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`master_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`parent_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "listId",
"columnName": "list_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "uid",
"columnName": "uid",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "href",
"columnName": "href",
"affinity": "TEXT"
},
{
"fieldPath": "etag",
"columnName": "etag",
"affinity": "TEXT"
},
{
"fieldPath": "title",
"columnName": "title",
"affinity": "TEXT"
},
{
"fieldPath": "description",
"columnName": "description",
"affinity": "TEXT"
},
{
"fieldPath": "location",
"columnName": "location",
"affinity": "TEXT"
},
{
"fieldPath": "url",
"columnName": "url",
"affinity": "TEXT"
},
{
"fieldPath": "color",
"columnName": "color",
"affinity": "INTEGER"
},
{
"fieldPath": "categories",
"columnName": "categories",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "percentComplete",
"columnName": "percent_complete",
"affinity": "INTEGER"
},
{
"fieldPath": "completedAt",
"columnName": "completed_at",
"affinity": "INTEGER"
},
{
"fieldPath": "priority",
"columnName": "priority",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "classification",
"columnName": "classification",
"affinity": "INTEGER"
},
{
"fieldPath": "dtstart",
"columnName": "dtstart",
"affinity": "INTEGER"
},
{
"fieldPath": "due",
"columnName": "due",
"affinity": "INTEGER"
},
{
"fieldPath": "duration",
"columnName": "duration",
"affinity": "TEXT"
},
{
"fieldPath": "isAllDay",
"columnName": "is_all_day",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "timezone",
"columnName": "timezone",
"affinity": "TEXT"
},
{
"fieldPath": "rrule",
"columnName": "rrule",
"affinity": "TEXT"
},
{
"fieldPath": "rdate",
"columnName": "rdate",
"affinity": "TEXT"
},
{
"fieldPath": "exdate",
"columnName": "exdate",
"affinity": "TEXT"
},
{
"fieldPath": "recurrenceId",
"columnName": "recurrence_id",
"affinity": "INTEGER"
},
{
"fieldPath": "masterId",
"columnName": "master_id",
"affinity": "INTEGER"
},
{
"fieldPath": "parentId",
"columnName": "parent_id",
"affinity": "INTEGER"
},
{
"fieldPath": "sortOrder",
"columnName": "sort_order",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER"
},
{
"fieldPath": "lastModified",
"columnName": "last_modified",
"affinity": "INTEGER"
},
{
"fieldPath": "sequence",
"columnName": "sequence",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "isDirty",
"columnName": "is_dirty",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "isDeleted",
"columnName": "is_deleted",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "unknownProperties",
"columnName": "unknown_properties",
"affinity": "TEXT"
},
{
"fieldPath": "remindersOff",
"columnName": "reminders_off",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_tasks_list_id_is_deleted",
"unique": false,
"columnNames": [
"list_id",
"is_deleted"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_list_id_is_deleted` ON `${TABLE_NAME}` (`list_id`, `is_deleted`)"
},
{
"name": "index_tasks_parent_id",
"unique": false,
"columnNames": [
"parent_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_parent_id` ON `${TABLE_NAME}` (`parent_id`)"
},
{
"name": "index_tasks_master_id_recurrence_id",
"unique": false,
"columnNames": [
"master_id",
"recurrence_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_master_id_recurrence_id` ON `${TABLE_NAME}` (`master_id`, `recurrence_id`)"
},
{
"name": "index_tasks_is_dirty",
"unique": false,
"columnNames": [
"is_dirty"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_is_dirty` ON `${TABLE_NAME}` (`is_dirty`)"
},
{
"name": "index_tasks_list_id_uid_recurrence_id",
"unique": true,
"columnNames": [
"list_id",
"uid",
"recurrence_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_tasks_list_id_uid_recurrence_id` ON `${TABLE_NAME}` (`list_id`, `uid`, `recurrence_id`)"
}
],
"foreignKeys": [
{
"table": "task_lists",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"list_id"
],
"referencedColumns": [
"id"
]
},
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"master_id"
],
"referencedColumns": [
"id"
]
},
{
"table": "tasks",
"onDelete": "SET NULL",
"onUpdate": "NO ACTION",
"columns": [
"parent_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "task_alarms",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task_id` INTEGER NOT NULL, `minutes_before` INTEGER NOT NULL, `reference` TEXT NOT NULL DEFAULT 'DUE', `message` TEXT, `uid` TEXT NOT NULL DEFAULT '', `raw` TEXT, FOREIGN KEY(`task_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "taskId",
"columnName": "task_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "minutesBefore",
"columnName": "minutes_before",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "reference",
"columnName": "reference",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "'DUE'"
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT"
},
{
"fieldPath": "uid",
"columnName": "uid",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "raw",
"columnName": "raw",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_task_alarms_task_id",
"unique": false,
"columnNames": [
"task_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_task_alarms_task_id` ON `${TABLE_NAME}` (`task_id`)"
}
],
"foreignKeys": [
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"task_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "advanced_occurrences",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`copy_id` INTEGER NOT NULL, `master_id` INTEGER NOT NULL, `anchor` INTEGER NOT NULL, `advanced_to` INTEGER NOT NULL, `prior_dtstart` INTEGER, `prior_due` INTEGER, `prior_status` INTEGER NOT NULL, `prior_percent_complete` INTEGER, `prior_completed_at` INTEGER, `spent` INTEGER NOT NULL, `rule_after` TEXT, `dropped_exdates` TEXT NOT NULL DEFAULT '', `from_override` INTEGER NOT NULL, `undoable` INTEGER NOT NULL DEFAULT 1, `settled` INTEGER NOT NULL DEFAULT 0, `reset_subtasks` TEXT NOT NULL DEFAULT '', PRIMARY KEY(`copy_id`), FOREIGN KEY(`copy_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`master_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "copyId",
"columnName": "copy_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "masterId",
"columnName": "master_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "anchor",
"columnName": "anchor",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "advancedTo",
"columnName": "advanced_to",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "priorDtstart",
"columnName": "prior_dtstart",
"affinity": "INTEGER"
},
{
"fieldPath": "priorDue",
"columnName": "prior_due",
"affinity": "INTEGER"
},
{
"fieldPath": "priorStatus",
"columnName": "prior_status",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "priorPercentComplete",
"columnName": "prior_percent_complete",
"affinity": "INTEGER"
},
{
"fieldPath": "priorCompletedAt",
"columnName": "prior_completed_at",
"affinity": "INTEGER"
},
{
"fieldPath": "spent",
"columnName": "spent",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "ruleAfter",
"columnName": "rule_after",
"affinity": "TEXT"
},
{
"fieldPath": "droppedExdates",
"columnName": "dropped_exdates",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "fromOverride",
"columnName": "from_override",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "undoable",
"columnName": "undoable",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "1"
},
{
"fieldPath": "settled",
"columnName": "settled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "resetSubtasks",
"columnName": "reset_subtasks",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"copy_id"
]
},
"indices": [
{
"name": "index_advanced_occurrences_master_id_anchor",
"unique": false,
"columnNames": [
"master_id",
"anchor"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_advanced_occurrences_master_id_anchor` ON `${TABLE_NAME}` (`master_id`, `anchor`)"
}
],
"foreignKeys": [
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"copy_id"
],
"referencedColumns": [
"id"
]
},
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"master_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "advanced_detached",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `copy_id` INTEGER NOT NULL, `anchor` INTEGER NOT NULL, `task_id` INTEGER, FOREIGN KEY(`copy_id`) REFERENCES `advanced_occurrences`(`copy_id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`task_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "copyId",
"columnName": "copy_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "anchor",
"columnName": "anchor",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "taskId",
"columnName": "task_id",
"affinity": "INTEGER"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_advanced_detached_copy_id",
"unique": false,
"columnNames": [
"copy_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_advanced_detached_copy_id` ON `${TABLE_NAME}` (`copy_id`)"
},
{
"name": "index_advanced_detached_task_id",
"unique": false,
"columnNames": [
"task_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_advanced_detached_task_id` ON `${TABLE_NAME}` (`task_id`)"
}
],
"foreignKeys": [
{
"table": "advanced_occurrences",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"copy_id"
],
"referencedColumns": [
"copy_id"
]
},
{
"table": "tasks",
"onDelete": "SET NULL",
"onUpdate": "NO ACTION",
"columns": [
"task_id"
],
"referencedColumns": [
"id"
]
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '6c8058a22084f0af602bc2f23c949b3c')"
]
}
}
@@ -1,866 +0,0 @@
{
"formatVersion": 1,
"database": {
"version": 7,
"identityHash": "8c3b7fe8ad462e6667c4cfd355ac4f22",
"entities": [
{
"tableName": "accounts",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `display_name` TEXT NOT NULL, `principal_url` TEXT, `home_set_url` TEXT, `username` TEXT, `last_sync_at` INTEGER, `last_sync_error` TEXT, `label` TEXT)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "displayName",
"columnName": "display_name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "principalUrl",
"columnName": "principal_url",
"affinity": "TEXT"
},
{
"fieldPath": "homeSetUrl",
"columnName": "home_set_url",
"affinity": "TEXT"
},
{
"fieldPath": "username",
"columnName": "username",
"affinity": "TEXT"
},
{
"fieldPath": "lastSyncAt",
"columnName": "last_sync_at",
"affinity": "INTEGER"
},
{
"fieldPath": "lastSyncError",
"columnName": "last_sync_error",
"affinity": "TEXT"
},
{
"fieldPath": "label",
"columnName": "label",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
}
},
{
"tableName": "task_lists",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `color` INTEGER NOT NULL, `account_id` INTEGER, `is_visible` INTEGER NOT NULL DEFAULT 1, `is_synced` INTEGER NOT NULL DEFAULT 1, `owner` TEXT, `is_read_only` INTEGER NOT NULL DEFAULT 0, `sort_order` INTEGER NOT NULL DEFAULT 0, `href` TEXT, `ctag` TEXT, `sync_token` TEXT, `is_dirty` INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(`account_id`) REFERENCES `accounts`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "color",
"columnName": "color",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "accountId",
"columnName": "account_id",
"affinity": "INTEGER"
},
{
"fieldPath": "isVisible",
"columnName": "is_visible",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "1"
},
{
"fieldPath": "isSynced",
"columnName": "is_synced",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "1"
},
{
"fieldPath": "owner",
"columnName": "owner",
"affinity": "TEXT"
},
{
"fieldPath": "isReadOnly",
"columnName": "is_read_only",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "sortOrder",
"columnName": "sort_order",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "href",
"columnName": "href",
"affinity": "TEXT"
},
{
"fieldPath": "ctag",
"columnName": "ctag",
"affinity": "TEXT"
},
{
"fieldPath": "syncToken",
"columnName": "sync_token",
"affinity": "TEXT"
},
{
"fieldPath": "isDirty",
"columnName": "is_dirty",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_task_lists_account_id",
"unique": false,
"columnNames": [
"account_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_task_lists_account_id` ON `${TABLE_NAME}` (`account_id`)"
}
],
"foreignKeys": [
{
"table": "accounts",
"onDelete": "SET NULL",
"onUpdate": "NO ACTION",
"columns": [
"account_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "tasks",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `list_id` INTEGER NOT NULL, `uid` TEXT NOT NULL, `href` TEXT, `etag` TEXT, `title` TEXT, `description` TEXT, `location` TEXT, `url` TEXT, `color` INTEGER, `categories` TEXT NOT NULL DEFAULT '', `status` INTEGER NOT NULL DEFAULT 0, `percent_complete` INTEGER, `completed_at` INTEGER, `priority` INTEGER NOT NULL DEFAULT 0, `classification` INTEGER, `dtstart` INTEGER, `due` INTEGER, `duration` TEXT, `is_all_day` INTEGER NOT NULL DEFAULT 0, `untimed` TEXT, `timezone` TEXT, `rrule` TEXT, `rdate` TEXT, `exdate` TEXT, `recurrence_id` INTEGER, `master_id` INTEGER, `parent_id` INTEGER, `sort_order` INTEGER NOT NULL DEFAULT 0, `created_at` INTEGER, `last_modified` INTEGER, `sequence` INTEGER NOT NULL DEFAULT 0, `is_dirty` INTEGER NOT NULL DEFAULT 0, `is_deleted` INTEGER NOT NULL DEFAULT 0, `unknown_properties` TEXT, `reminders_off` INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(`list_id`) REFERENCES `task_lists`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`master_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`parent_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "listId",
"columnName": "list_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "uid",
"columnName": "uid",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "href",
"columnName": "href",
"affinity": "TEXT"
},
{
"fieldPath": "etag",
"columnName": "etag",
"affinity": "TEXT"
},
{
"fieldPath": "title",
"columnName": "title",
"affinity": "TEXT"
},
{
"fieldPath": "description",
"columnName": "description",
"affinity": "TEXT"
},
{
"fieldPath": "location",
"columnName": "location",
"affinity": "TEXT"
},
{
"fieldPath": "url",
"columnName": "url",
"affinity": "TEXT"
},
{
"fieldPath": "color",
"columnName": "color",
"affinity": "INTEGER"
},
{
"fieldPath": "categories",
"columnName": "categories",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "percentComplete",
"columnName": "percent_complete",
"affinity": "INTEGER"
},
{
"fieldPath": "completedAt",
"columnName": "completed_at",
"affinity": "INTEGER"
},
{
"fieldPath": "priority",
"columnName": "priority",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "classification",
"columnName": "classification",
"affinity": "INTEGER"
},
{
"fieldPath": "dtstart",
"columnName": "dtstart",
"affinity": "INTEGER"
},
{
"fieldPath": "due",
"columnName": "due",
"affinity": "INTEGER"
},
{
"fieldPath": "duration",
"columnName": "duration",
"affinity": "TEXT"
},
{
"fieldPath": "isAllDay",
"columnName": "is_all_day",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "untimed",
"columnName": "untimed",
"affinity": "TEXT"
},
{
"fieldPath": "timezone",
"columnName": "timezone",
"affinity": "TEXT"
},
{
"fieldPath": "rrule",
"columnName": "rrule",
"affinity": "TEXT"
},
{
"fieldPath": "rdate",
"columnName": "rdate",
"affinity": "TEXT"
},
{
"fieldPath": "exdate",
"columnName": "exdate",
"affinity": "TEXT"
},
{
"fieldPath": "recurrenceId",
"columnName": "recurrence_id",
"affinity": "INTEGER"
},
{
"fieldPath": "masterId",
"columnName": "master_id",
"affinity": "INTEGER"
},
{
"fieldPath": "parentId",
"columnName": "parent_id",
"affinity": "INTEGER"
},
{
"fieldPath": "sortOrder",
"columnName": "sort_order",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "createdAt",
"columnName": "created_at",
"affinity": "INTEGER"
},
{
"fieldPath": "lastModified",
"columnName": "last_modified",
"affinity": "INTEGER"
},
{
"fieldPath": "sequence",
"columnName": "sequence",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "isDirty",
"columnName": "is_dirty",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "isDeleted",
"columnName": "is_deleted",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "unknownProperties",
"columnName": "unknown_properties",
"affinity": "TEXT"
},
{
"fieldPath": "remindersOff",
"columnName": "reminders_off",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_tasks_list_id_is_deleted",
"unique": false,
"columnNames": [
"list_id",
"is_deleted"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_list_id_is_deleted` ON `${TABLE_NAME}` (`list_id`, `is_deleted`)"
},
{
"name": "index_tasks_parent_id",
"unique": false,
"columnNames": [
"parent_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_parent_id` ON `${TABLE_NAME}` (`parent_id`)"
},
{
"name": "index_tasks_master_id_recurrence_id",
"unique": false,
"columnNames": [
"master_id",
"recurrence_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_master_id_recurrence_id` ON `${TABLE_NAME}` (`master_id`, `recurrence_id`)"
},
{
"name": "index_tasks_is_dirty",
"unique": false,
"columnNames": [
"is_dirty"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_tasks_is_dirty` ON `${TABLE_NAME}` (`is_dirty`)"
},
{
"name": "index_tasks_list_id_uid_recurrence_id",
"unique": true,
"columnNames": [
"list_id",
"uid",
"recurrence_id"
],
"orders": [],
"createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_tasks_list_id_uid_recurrence_id` ON `${TABLE_NAME}` (`list_id`, `uid`, `recurrence_id`)"
}
],
"foreignKeys": [
{
"table": "task_lists",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"list_id"
],
"referencedColumns": [
"id"
]
},
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"master_id"
],
"referencedColumns": [
"id"
]
},
{
"table": "tasks",
"onDelete": "SET NULL",
"onUpdate": "NO ACTION",
"columns": [
"parent_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "task_alarms",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task_id` INTEGER NOT NULL, `minutes_before` INTEGER NOT NULL, `reference` TEXT NOT NULL DEFAULT 'DUE', `message` TEXT, `uid` TEXT NOT NULL DEFAULT '', `raw` TEXT, FOREIGN KEY(`task_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "taskId",
"columnName": "task_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "minutesBefore",
"columnName": "minutes_before",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "reference",
"columnName": "reference",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "'DUE'"
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT"
},
{
"fieldPath": "uid",
"columnName": "uid",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "raw",
"columnName": "raw",
"affinity": "TEXT"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_task_alarms_task_id",
"unique": false,
"columnNames": [
"task_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_task_alarms_task_id` ON `${TABLE_NAME}` (`task_id`)"
}
],
"foreignKeys": [
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"task_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "advanced_occurrences",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`copy_id` INTEGER NOT NULL, `master_id` INTEGER NOT NULL, `anchor` INTEGER NOT NULL, `advanced_to` INTEGER NOT NULL, `prior_dtstart` INTEGER, `prior_due` INTEGER, `prior_status` INTEGER NOT NULL, `prior_percent_complete` INTEGER, `prior_completed_at` INTEGER, `spent` INTEGER NOT NULL, `rule_after` TEXT, `dropped_exdates` TEXT NOT NULL DEFAULT '', `from_override` INTEGER NOT NULL, `undoable` INTEGER NOT NULL DEFAULT 1, `settled` INTEGER NOT NULL DEFAULT 0, `reset_subtasks` TEXT NOT NULL DEFAULT '', PRIMARY KEY(`copy_id`), FOREIGN KEY(`copy_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`master_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "copyId",
"columnName": "copy_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "masterId",
"columnName": "master_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "anchor",
"columnName": "anchor",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "advancedTo",
"columnName": "advanced_to",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "priorDtstart",
"columnName": "prior_dtstart",
"affinity": "INTEGER"
},
{
"fieldPath": "priorDue",
"columnName": "prior_due",
"affinity": "INTEGER"
},
{
"fieldPath": "priorStatus",
"columnName": "prior_status",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "priorPercentComplete",
"columnName": "prior_percent_complete",
"affinity": "INTEGER"
},
{
"fieldPath": "priorCompletedAt",
"columnName": "prior_completed_at",
"affinity": "INTEGER"
},
{
"fieldPath": "spent",
"columnName": "spent",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "ruleAfter",
"columnName": "rule_after",
"affinity": "TEXT"
},
{
"fieldPath": "droppedExdates",
"columnName": "dropped_exdates",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
},
{
"fieldPath": "fromOverride",
"columnName": "from_override",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "undoable",
"columnName": "undoable",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "1"
},
{
"fieldPath": "settled",
"columnName": "settled",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "resetSubtasks",
"columnName": "reset_subtasks",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"copy_id"
]
},
"indices": [
{
"name": "index_advanced_occurrences_master_id_anchor",
"unique": false,
"columnNames": [
"master_id",
"anchor"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_advanced_occurrences_master_id_anchor` ON `${TABLE_NAME}` (`master_id`, `anchor`)"
}
],
"foreignKeys": [
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"copy_id"
],
"referencedColumns": [
"id"
]
},
{
"table": "tasks",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"master_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "advanced_detached",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `copy_id` INTEGER NOT NULL, `anchor` INTEGER NOT NULL, `task_id` INTEGER, FOREIGN KEY(`copy_id`) REFERENCES `advanced_occurrences`(`copy_id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`task_id`) REFERENCES `tasks`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "copyId",
"columnName": "copy_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "anchor",
"columnName": "anchor",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "taskId",
"columnName": "task_id",
"affinity": "INTEGER"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_advanced_detached_copy_id",
"unique": false,
"columnNames": [
"copy_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_advanced_detached_copy_id` ON `${TABLE_NAME}` (`copy_id`)"
},
{
"name": "index_advanced_detached_task_id",
"unique": false,
"columnNames": [
"task_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_advanced_detached_task_id` ON `${TABLE_NAME}` (`task_id`)"
}
],
"foreignKeys": [
{
"table": "advanced_occurrences",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"copy_id"
],
"referencedColumns": [
"copy_id"
]
},
{
"table": "tasks",
"onDelete": "SET NULL",
"onUpdate": "NO ACTION",
"columns": [
"task_id"
],
"referencedColumns": [
"id"
]
}
]
},
{
"tableName": "advanced_deleted",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `copy_id` INTEGER NOT NULL, `anchor` INTEGER NOT NULL, `vtodo` TEXT NOT NULL, `color` INTEGER, `sort_order` INTEGER NOT NULL DEFAULT 0, `reminders_off` INTEGER NOT NULL DEFAULT 0, `alarms` TEXT NOT NULL DEFAULT '', FOREIGN KEY(`copy_id`) REFERENCES `advanced_occurrences`(`copy_id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "copyId",
"columnName": "copy_id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "anchor",
"columnName": "anchor",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "vtodo",
"columnName": "vtodo",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "color",
"columnName": "color",
"affinity": "INTEGER"
},
{
"fieldPath": "sortOrder",
"columnName": "sort_order",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "remindersOff",
"columnName": "reminders_off",
"affinity": "INTEGER",
"notNull": true,
"defaultValue": "0"
},
{
"fieldPath": "alarms",
"columnName": "alarms",
"affinity": "TEXT",
"notNull": true,
"defaultValue": "''"
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_advanced_deleted_copy_id",
"unique": false,
"columnNames": [
"copy_id"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_advanced_deleted_copy_id` ON `${TABLE_NAME}` (`copy_id`)"
}
],
"foreignKeys": [
{
"table": "advanced_occurrences",
"onDelete": "CASCADE",
"onUpdate": "NO ACTION",
"columns": [
"copy_id"
],
"referencedColumns": [
"copy_id"
]
}
]
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '8c3b7fe8ad462e6667c4cfd355ac4f22')"
]
}
}
Binary file not shown.
@@ -1,76 +0,0 @@
package de.jeanlucmakiola.agendula.data.tasks
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Assume.assumeTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/**
* List order against a real external provider (#136). Skipped unless one is
* installed and its permissions are granted.
*/
@RunWith(AndroidJUnit4::class)
class ExternalProviderListOrderTest {
private val context = ApplicationProvider.getApplicationContext<Context>()
private val resolver = ProviderResolver(AndroidProviderEnvironment(context)).apply {
storageMode = StorageMode.EXTERNAL
}
private val source = AndroidTasksDataSource(context, resolver)
private val created = mutableListOf<Long>()
@Before
fun setUp() {
val provider = resolver.resolve()
assumeTrue("no external tasks provider, or not granted", provider != null && resolver.hasPermission(provider))
listOf("Order A", "Order B", "Order C").forEach { created += source.createLocalList(it, 0) }
}
@After
fun tearDown() = created.forEach { runCatching { source.deleteList(it) } }
private fun ours() = source.taskLists().map { it.id }.filter { it in created }
/** Waits until the provider has gone quiet, so a change seen afterwards is the test's own. */
private fun settle() {
var last = System.currentTimeMillis()
val observer = source.registerObserver { last = System.currentTimeMillis() }
while (System.currentTimeMillis() - last < 1_500) Thread.sleep(100)
observer.close()
}
@Test
fun aReorderIsKeptAndReported() {
val (a, b, c) = created
settle()
val changed = CountDownLatch(1)
val observer = source.registerObserver { changed.countDown() }
source.reorderLists(listOf(c, a, b))
assertThat(changed.await(5, TimeUnit.SECONDS)).isTrue()
observer.close()
assertThat(ours()).containsExactly(c, a, b).inOrder()
assertThat(AndroidTasksDataSource(context, resolver).taskLists().map { it.id }.filter { it in created })
.containsExactly(c, a, b).inOrder()
}
@Test
fun aDeletedListLeavesNoPositionBehind() {
val (a, b, c) = created
source.reorderLists(listOf(c, a, b))
source.deleteList(c)
created -= c
source.taskLists()
assertThat(source.storedListOrder().keys).doesNotContain(c)
}
}
@@ -1,361 +0,0 @@
package de.jeanlucmakiola.agendula.data.tasks
import android.content.ContentValues
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Tasks
import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.TaskForm
import de.jeanlucmakiola.agendula.domain.TaskReminder
import org.junit.After
import org.junit.Assert.assertThrows
import org.junit.Assume.assumeTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.time.Clock
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Instant
/**
* Recurrence against a real external provider (#135). Skipped unless one is
* installed and its permissions are granted, so it only runs where set up:
* `pm grant <app> org.tasks.permission.READ_TASKS` (and WRITE_TASKS).
*/
@RunWith(AndroidJUnit4::class)
class ExternalProviderRecurrenceTest {
private val context = ApplicationProvider.getApplicationContext<Context>()
private val resolver = ProviderResolver(AndroidProviderEnvironment(context)).apply {
storageMode = StorageMode.EXTERNAL
}
private val source = AndroidTasksDataSource(context, resolver)
private var listId = 0L
@Before
fun setUp() {
val provider = resolver.resolve()
assumeTrue("no external tasks provider, or not granted", provider != null && resolver.hasPermission(provider))
listId = source.createLocalList("Recurrence test", 0)
}
@After
fun tearDown() {
if (listId != 0L) source.deleteList(listId)
}
private fun dailyTask(): Long {
// Milliseconds and all, as the "start today" default gives.
val start = Clock.System.now() + 1.hours
return source.insertTask(
TaskForm(title = "Daily", listId = listId, start = start, due = start + 1.hours, rrule = "FREQ=DAILY"),
reminders = null,
)
}
private fun storedRule(taskId: Long): String? = context.contentResolver.query(
TasksContract.tasksUri(resolver.resolve()!!.authority),
arrayOf(Tasks.RRULE),
"${Tasks.ID} = ?",
arrayOf(taskId.toString()),
null,
)?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
private fun setRule(taskId: Long, rule: String) {
context.contentResolver.update(
TasksContract.tasksUri(resolver.resolve()!!.authority),
ContentValues().apply { put(Tasks.RRULE, rule) },
"${Tasks.ID} = ?",
arrayOf(taskId.toString()),
)
}
@Test
fun aSeriesReadsAsRecurringWithItsRule() {
val id = dailyTask()
val listed = source.tasks(TaskQuery(listId = listId)).filter { it.taskId == id }.minBy { it.occurrenceStart!! }
assertThat(listed.isRecurring).isTrue()
assertThat(listed.isOccurrence).isTrue()
assertThat(listed.recurrenceRule).isEqualTo("FREQ=DAILY")
val opened = source.task(id)!!
assertThat(opened.recurrenceRule).isEqualTo("FREQ=DAILY")
}
@Test
fun savingTheSeriesKeepsItsRule() {
val id = dailyTask()
val task = source.task(id)!!
source.updateSeries(
id,
task.occurrenceStart!!,
TaskForm(title = "Daily, renamed", listId = listId, start = task.start, due = task.due, rrule = task.recurrenceRule),
reminders = null,
)
assertThat(storedRule(id)).isEqualTo("FREQ=DAILY")
}
@Test
fun completingAnOccurrenceMovesTheSeriesOn() {
val id = dailyTask()
val task = source.task(id)!!
source.setCompletedInstance(id, task.occurrenceStart!!, completed = true)
assertSeriesMovedOn(id, task.occurrenceStart!!)
}
@Test
fun aTickedOccurrenceReadsAsItsCopy() {
val id = dailyTask()
val anchor = source.task(id)!!.occurrenceStart!!
source.setCompletedInstance(id, anchor, completed = true)
val read = source.task(id, anchor)!!
assertThat(read.taskId).isNotEqualTo(id)
assertThat(read.isClosed).isTrue()
}
@Test
fun undoingATickMovesTheSeriesBack() {
val id = dailyTask()
val anchor = source.task(id)!!.occurrenceStart!!
source.setCompletedInstance(id, anchor, completed = true)
val copy = source.task(id, anchor)!!.taskId
source.setCompletedInstance(id, anchor, completed = false)
val read = source.task(id, anchor)!!
assertThat(read.taskId).isEqualTo(id)
assertThat(read.isClosed).isFalse()
assertThat(source.task(copy)).isNull()
}
@Test
fun reopeningTheCopyItselfMovesTheSeriesBack() {
val id = dailyTask()
val anchor = source.task(id)!!.occurrenceStart!!
source.setCompletedInstance(id, anchor, completed = true)
val copy = source.task(id, anchor)!!.taskId
source.setCompleted(copy, completed = false)
assertThat(source.task(id, anchor)!!.taskId).isEqualTo(id)
assertThat(source.task(copy)).isNull()
}
@Test
fun aSeriesChangedSinceTheTickReopensOnlyTheCopy() {
val id = dailyTask()
val anchor = source.task(id)!!.occurrenceStart!!
source.setCompletedInstance(id, anchor, completed = true)
val copy = source.task(id, anchor)!!.taskId
setRule(id, "FREQ=WEEKLY")
source.setCompletedInstance(id, anchor, completed = false)
assertThat(source.task(copy)!!.isClosed).isFalse()
assertThat(storedRule(id)).isEqualTo("FREQ=WEEKLY")
}
@Test
fun anOccurrenceThatIsGoneReadsAsNothing() {
val id = dailyTask()
val anchor = source.task(id)!!.occurrenceStart!!
assertThat(source.task(id, anchor + 30.hours)).isNull()
}
@Test
fun aSeriesStoredWithMillisecondsStillMovesOn() {
val id = legacySeries()
val task = source.task(id)!!
source.setCompletedInstance(id, task.occurrenceStart!!, completed = true)
assertSeriesMovedOn(id, task.occurrenceStart)
}
@Test
fun anUnknownOccurrenceDoesNotCloseTheSeries() {
val id = dailyTask()
val anchor = source.task(id)!!.occurrenceStart!!
assertThrows(TaskWriteFailedException::class.java) {
source.setCompletedInstance(id, anchor + 30.hours, completed = true)
}
assertThat(source.task(id)!!.isClosed).isFalse()
}
@Test
fun roundingALegacySeriesLeavesItUnmodified() {
val id = legacySeries()
val before = storedColumn(id, Tasks.LAST_MODIFIED)
source.task(id)
assertThat(storedStart(id)!! % 1000).isEqualTo(0L)
assertThat(storedColumn(id, Tasks.LAST_MODIFIED)).isEqualTo(before)
}
/** A daily series as builds before whole-second writes left it, already in sync with its server. */
private fun legacySeries(): Long {
val start = (Clock.System.now() + 1.hours).toEpochMilliseconds() / 1000 * 1000
return insertAsSyncAdapter(
Tasks.LIST_ID to listId,
Tasks.TITLE to "Old daily",
Tasks.DTSTART to start + 345,
Tasks.DUE to start + 3_600_345,
Tasks.TZ to "UTC",
Tasks.RRULE to "FREQ=DAILY",
).also {
// The app's own reads may already have run the one-time rounding.
context.getSharedPreferences("provider_migrations", Context.MODE_PRIVATE).edit().clear().commit()
}
}
private fun insertAsSyncAdapter(vararg values: Pair<String, Any>): Long {
val uri = TasksContract.asSyncAdapter(
TasksContract.tasksUri(resolver.resolve()!!.authority),
TasksContract.LOCAL_ACCOUNT_NAME,
TasksContract.LOCAL_ACCOUNT_TYPE,
)
val cv = ContentValues().apply {
values.forEach { (k, v) -> if (v is Long) put(k, v) else put(k, v.toString()) }
}
return context.contentResolver.insert(uri, cv)!!.lastPathSegment!!.toLong()
}
/** Edits the series' first occurrence on its own and returns the override that makes. */
private fun overrideOf(id: Long): Task {
val task = source.task(id)!!
source.updateInstance(
id,
task.occurrenceStart!!,
TaskForm(title = "Just this once", listId = listId, start = task.start, due = task.due),
reminders = null,
)
return source.tasks(TaskQuery(listId = listId)).single { it.seriesId == id && it.taskId != id }
}
@Test
fun anOverrideBelongsToItsSeries() {
val id = dailyTask()
val anchor = source.task(id)!!.occurrenceStart
val override = overrideOf(id)
assertThat(override.title).isEqualTo("Just this once")
assertThat(override.isOccurrence).isTrue()
assertThat(override.occurrenceStart).isEqualTo(anchor)
assertThat(override.recurrenceRule).isEqualTo("FREQ=DAILY")
assertThat(source.task(override.taskId, override.occurrenceStart)?.taskId).isEqualTo(override.taskId)
}
@Test
fun anAllDayDueAddedToTheSeriesStaysOnItsDay() {
val day = Clock.System.now().toEpochMilliseconds() / 86_400_000 * 86_400_000
val id = source.insertTask(
TaskForm(title = "All day", listId = listId, start = Instant.fromEpochMilliseconds(day), isAllDay = true, rrule = "FREQ=DAILY"),
reminders = null,
)
val task = source.task(id)!!
// Local midnight the next day, as the date picker hands it over.
val localMidnight = Instant.fromEpochMilliseconds(day + 86_400_000 - java.util.TimeZone.getDefault().getOffset(day))
source.updateSeries(
id,
task.occurrenceStart!!,
TaskForm(title = "All day", listId = listId, start = task.start, due = localMidnight, isAllDay = true, rrule = "FREQ=DAILY"),
reminders = null,
)
assertThat(storedColumn(id, Tasks.DUE)!!.toLong() % 86_400_000).isEqualTo(0L)
}
@Test
fun savingAllFromAnOverrideKeepsTheSeriesWhereItIs() {
val id = dailyTask()
val before = storedStart(id)
val override = overrideOf(id)
source.updateSeries(
id,
override.occurrenceStart!!,
TaskForm(title = "Renamed", listId = listId, start = override.start, due = override.due, rrule = override.recurrenceRule),
reminders = null,
)
assertThat(storedStart(id)).isEqualTo(before)
assertThat(storedRule(id)).isEqualTo("FREQ=DAILY")
}
@Test
fun deletingAnOverrideExcludesItsOccurrence() {
val id = dailyTask()
val override = overrideOf(id)
source.deleteOverride(override.taskId, override.occurrenceStart!!)
// Excluded on the master, not just the override dropped.
assertThat(storedColumn(id, Tasks.EXDATE)).isNotNull()
val open = source.tasks(TaskQuery(listId = listId)).filter { it.seriesId == id }
assertThat(open.map { it.occurrenceStart }).doesNotContain(override.occurrenceStart)
assertThat(storedRule(id)).isEqualTo("FREQ=DAILY")
}
@Test
fun editingAnOverrideAgainKeepsItsNewTagsAndReminders() {
val id = dailyTask()
val override = overrideOf(id)
val form = TaskForm(
title = override.title,
listId = listId,
start = override.start,
due = override.due,
tags = listOf("urgent"),
reminders = listOf(TaskReminder(minutesBefore = 15)),
)
source.updateInstance(override.taskId, override.occurrenceStart!!, form, form.reminders)
assertThat(source.task(override.taskId)!!.tags).containsExactly("urgent")
assertThat(source.reminders()[override.taskId]).containsExactly(TaskReminder(minutesBefore = 15))
assertThat(source.task(id)?.tags.orEmpty()).isEmpty()
}
@Test
fun anOccurrenceIsFoundByItsAnchorToTheSecond() {
val id = dailyTask()
val override = overrideOf(id)
val found = source.task(id, override.occurrenceStart!! + 345.milliseconds)
assertThat(found?.taskId).isEqualTo(override.taskId)
}
private fun storedStart(taskId: Long): Long? = storedColumn(taskId, Tasks.DTSTART)?.toLong()
private fun storedColumn(taskId: Long, column: String): String? = context.contentResolver.query(
TasksContract.tasksUri(resolver.resolve()!!.authority),
arrayOf(column),
"${Tasks.ID} = ?",
arrayOf(taskId.toString()),
null,
)?.use { c -> if (c.moveToFirst()) c.getString(0) else null }
private fun assertSeriesMovedOn(id: Long, completed: Instant) {
assertThat(storedRule(id)).isNotNull()
val open = source.tasks(TaskQuery(listId = listId)).filter { it.seriesId == id }
assertThat(open).isNotEmpty()
assertThat(open.minOf { it.occurrenceStart!! }).isGreaterThan(completed)
}
}
@@ -212,15 +212,6 @@ class OneShotImportTest {
assertThat(db.alarms().all().map { it.message }).doesNotContain("Errands")
}
@Test
fun importsCategoryPropertiesAsTags() {
importer.importFrom(fixture())
val tasks = taskRows()
assertThat(tasks.getValue("Buy milk").categories).containsExactly("Errands")
assertThat(tasks.getValue("Ship the release").categories).isEmpty()
}
// --- running it -----------------------------------------------------------
@Test
@@ -1,162 +0,0 @@
package de.jeanlucmakiola.agendula.data.tasks.provider
import android.content.ContentProviderOperation
import android.content.ContentValues
import android.content.Context
import android.content.pm.PermissionInfo
import android.os.Build
import android.os.ParcelFileDescriptor
import androidx.core.net.toUri
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.google.common.truth.Truth.assertThat
import org.junit.Assert.assertThrows
import org.junit.Assume.assumeTrue
import org.junit.Test
import org.junit.runner.RunWith
/** The provider as another app meets it: manifest, permission, URIs. */
@RunWith(AndroidJUnit4::class)
class AgendulaTaskProviderTest {
private val context = ApplicationProvider.getApplicationContext<Context>()
private val authority = "${context.packageName}.tasks"
private val readPermission = "${context.packageName}.permission.READ_TASKS"
private val writePermission = "${context.packageName}.permission.WRITE_TASKS"
private val resolver = context.contentResolver
private fun uri(path: String) = "content://$authority/$path".toUri()
@Test
fun isExportedUnderItsPermissions() {
val info = requireNotNull(context.packageManager.resolveContentProvider(authority, 0))
assertThat(info.name).isEqualTo(AgendulaTaskProvider::class.java.name)
assertThat(info.exported).isTrue()
assertThat(info.readPermission).isEqualTo(readPermission)
assertThat(info.writePermission).isEqualTo(writePermission)
}
@Test
fun bothPermissionsAreDangerous() {
listOf(readPermission, writePermission).forEach { permission ->
val info = context.packageManager.getPermissionInfo(permission, 0)
assertThat(info.protection).isEqualTo(PermissionInfo.PROTECTION_DANGEROUS)
assertThat(info.loadLabel(context.packageManager).toString()).isNotEmpty()
assertThat(info.loadDescription(context.packageManager)?.toString()).isNotEmpty()
}
}
@Test
fun anAppWithoutThePermissionIsDenied() {
assumeTrue(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
// The shell is another uid that was never granted it.
val output = shell("content query --uri content://$authority/tasks")
assertThat(output).contains("Permission Denial")
}
@Test
fun anAppWithoutTheWritePermissionCannotWrite() {
assumeTrue(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
val output = shell("content insert --uri content://$authority/tasks --bind title:s:x --bind list_id:i:1")
assertThat(output).contains("Permission Denial")
assertThat(output).contains(writePermission)
}
@Test
fun reportsOpenTasksMimeTypes() {
ProviderTable.entries.forEach { table ->
assertThat(resolver.getType(uri(table.path))).isEqualTo(table.mimeType(single = false))
assertThat(resolver.getType(uri("${table.path}/3"))).isEqualTo(table.mimeType(single = true))
}
}
@Test
fun everyTableAnswersWithItsColumns() {
ProviderTable.entries.forEach { table ->
resolver.query(uri(table.path), null, null, null, null)!!.use {
assertThat(it.columnNames.toList()).containsExactlyElementsIn(table.columns.map { c -> c.first }).inOrder()
}
}
}
@Test
fun aCursorWatchesTheUriItWasQueriedFor() {
val tasks = uri("tasks")
resolver.query(tasks, null, null, null, null)!!.use { assertThat(it.notificationUri).isEqualTo(tasks) }
}
@Test
fun aRowUriReadsOnlyThatRow() {
// Ids start at 1, so 0 names nothing whatever the store holds.
resolver.query(uri("tasks/0"), null, null, null, null)!!.use { assertThat(it.count).isEqualTo(0) }
resolver.query(uri("tasks/0"), null, "1 = 1 OR 1 = 1", null, null)!!.use { assertThat(it.count).isEqualTo(0) }
}
@Test
fun anUnknownUriIsRejected() {
assertThrows(IllegalArgumentException::class.java) { resolver.query(uri("events"), null, null, null, null) }
// ContentResolver.getType swallows the provider's exception and answers null.
assertThat(runCatching { resolver.getType(uri("tasks/abc")) }.getOrNull()).isNull()
}
@Test
fun listsAreReadOnly() {
val values = ContentValues().apply { put("list_name", "x") }
assertThrows(UnsupportedOperationException::class.java) { resolver.insert(uri("tasklists"), values) }
assertThrows(UnsupportedOperationException::class.java) { resolver.update(uri("tasklists/1"), values, null, null) }
assertThrows(UnsupportedOperationException::class.java) { resolver.delete(uri("tasklists/1"), null, null) }
}
@Test
fun aRowUriTakesNoInsert() {
assertThrows(IllegalArgumentException::class.java) {
resolver.insert(uri("tasks/1"), ContentValues().apply { put("title", "x") })
}
}
@Test
fun aBadWriteReachesTheClientAsIllegalArgument() {
assumeTrue("Agendula is running on an external provider", ownStore())
// No list has this id, so nothing in the app's real store is touched.
val values = ContentValues().apply {
put("list_id", Long.MAX_VALUE)
put("title", "x")
}
assertThrows(IllegalArgumentException::class.java) { resolver.insert(uri("tasks"), values) }
}
@Test
fun aFailingBatchWritesNothing() {
assumeTrue("Agendula is running on an external provider", ownStore())
val missingList = Long.MAX_VALUE
val operations = arrayListOf(
ContentProviderOperation.newInsert(uri("tasks")).withValue("list_id", missingList).withValue("title", "a").build(),
)
assertThrows(IllegalArgumentException::class.java) { resolver.applyBatch(authority, operations) }
resolver.query(uri("tasks"), arrayOf("_id"), "list_id = ?", arrayOf(missingList.toString()), null)!!
.use { assertThat(it.count).isEqualTo(0) }
}
/** Whether the app's own store is active: only then does the provider take writes at all. */
private fun ownStore() = runCatching { resolver.delete(uri("tasks"), "_id = -1", null) }.isSuccess
/** stdout and stderr of [command]; the denial lands on stderr. */
private fun shell(command: String): String {
val (stdout, stdin, stderr) = InstrumentationRegistry.getInstrumentation().uiAutomation
.executeShellCommandRwe(command)
stdin.close()
return listOf(stdout, stderr).joinToString("\n") { pfd ->
ParcelFileDescriptor.AutoCloseInputStream(pfd).bufferedReader().use { it.readText() }
}
}
}
@@ -1,214 +0,0 @@
package de.jeanlucmakiola.agendula.data.tasks.provider
import android.content.Context
import android.database.ContentObserver
import android.database.Cursor
import android.net.Uri
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.agendula.data.tasks.ProviderEnvironment
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
import de.jeanlucmakiola.agendula.data.tasks.StorageMode
import de.jeanlucmakiola.agendula.data.tasks.TasksContract
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Instances
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Lists
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Tasks
import de.jeanlucmakiola.agendula.data.tasks.room.TaskAlarmEntity
import de.jeanlucmakiola.agendula.data.tasks.room.TaskEntity
import de.jeanlucmakiola.agendula.data.tasks.room.TaskListEntity
import de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import kotlin.time.Clock
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Instant
/** The snapshot follows the Room store, the storage mode and the clock, and says when it moved. */
@RunWith(AndroidJUnit4::class)
class ProviderSnapshotSourceTest {
private val context = ApplicationProvider.getApplicationContext<Context>()
private lateinit var db: TasksDatabase
private lateinit var resolver: ProviderResolver
private lateinit var source: ProviderSnapshotSource
private val clock = MutableClock(Instant.parse("2026-10-10T08:00:00Z"))
private val changes = LinkedBlockingQueue<Uri>()
private val observer = object : ContentObserver(null) {
override fun onChange(selfChange: Boolean, uri: Uri?) {
changes += uri ?: Uri.EMPTY
}
}
private var listId = 0L
@Before
fun setUp() {
db = Room.inMemoryDatabaseBuilder(context, TasksDatabase::class.java).allowMainThreadQueries().build()
resolver = ProviderResolver(NoProviderInstalled)
source = ProviderSnapshotSource(context, db, resolver, awaitStartup = {}, clock = clock)
listId = db.taskLists().insert(TaskListEntity(name = "Home", color = 0xFF112233.toInt()))
context.contentResolver.registerContentObserver(TasksContract.authorityUri(source.authority), true, observer)
}
@After
fun tearDown() {
context.contentResolver.unregisterContentObserver(observer)
db.close()
}
private fun query(table: ProviderTable, selection: String? = null, args: Array<String>? = null): Cursor =
source.query(table, null, selection, args, null)
private fun titles(): List<String?> = query(ProviderTable.TASKS).use { cursor ->
val index = cursor.getColumnIndexOrThrow(Tasks.TITLE)
buildList { while (cursor.moveToNext()) add(cursor.getString(index)) }
}
private fun insert(title: String, due: Instant? = null, rrule: String? = null): Long =
db.tasks().insert(TaskEntity(listId = listId, uid = title, title = title, due = due, rrule = rrule, timezone = "UTC"))
/** Waits for the coalesced notification, then drains any stragglers. */
private fun awaitChange() {
assertThat(changes.poll(5, TimeUnit.SECONDS)).isNotNull()
Thread.sleep(700)
changes.clear()
}
private fun assertNoChange() {
assertThat(changes.poll(1500, TimeUnit.MILLISECONDS)).isNull()
}
@Test
fun servesTheOwnStore() {
val id = insert("Milk")
db.alarms().insert(TaskAlarmEntity(taskId = id, minutesBefore = 10))
assertThat(titles()).containsExactly("Milk")
query(ProviderTable.LISTS).use {
it.moveToFirst()
assertThat(it.getString(it.getColumnIndexOrThrow(Lists.NAME))).isEqualTo("Home")
}
query(ProviderTable.INSTANCES).use { assertThat(it.count).isEqualTo(1) }
query(ProviderTable.PROPERTIES).use { assertThat(it.count).isEqualTo(1) }
}
@Test
fun aDeletedTaskIsNotPublished() {
val id = insert("Gone")
insert("Kept")
db.tasks().markDeleted(id, clock.now())
assertThat(titles()).containsExactly("Kept")
}
@Test
fun aWriteNotifiesObserversAndIsServedNext() {
source.start()
assertThat(titles()).isEmpty()
insert("Later")
awaitChange()
assertThat(titles()).containsExactly("Later")
}
@Test
fun aBurstOfWritesNotifiesOnce() {
source.start()
titles()
repeat(5) { insert("t$it") }
assertThat(changes.poll(5, TimeUnit.SECONDS)).isNotNull()
assertNoChange()
}
@Test
fun externalModeServesNothing() {
insert("Mine")
resolver.storageMode = StorageMode.EXTERNAL
ProviderTable.entries.forEach { table -> query(table).use { assertThat(it.count).isEqualTo(0) } }
}
@Test
fun switchingModeNotifiesAndRebuilds() {
source.start()
insert("Mine")
assertThat(titles()).containsExactly("Mine")
changes.clear()
resolver.storageMode = StorageMode.EXTERNAL
awaitChange()
assertThat(titles()).isEmpty()
resolver.storageMode = StorageMode.OWN
awaitChange()
assertThat(titles()).containsExactly("Mine")
}
@Test
fun writesInExternalModeDoNotNotify() {
resolver.storageMode = StorageMode.EXTERNAL
source.start()
titles()
insert("Hidden")
assertNoChange()
}
@Test
fun aClientSelectionNarrowsTheRows() {
insert("a")
insert("b")
query(ProviderTable.TASKS, "${Tasks.TITLE} = ?", arrayOf("b")).use { assertThat(it.count).isEqualTo(1) }
}
@Test
fun anHourOldSnapshotIsRebuiltAgainstTheClock() {
source.start()
insert("Daily", due = Instant.parse("2026-10-10T09:00:00Z"), rrule = "FREQ=DAILY;COUNT=3")
awaitChange()
assertThat(currentOriginalTime()).isEqualTo(Instant.parse("2026-10-10T09:00:00Z").toEpochMilliseconds())
clock.current += 1.days
assertThat(currentOriginalTime()).isEqualTo(Instant.parse("2026-10-11T09:00:00Z").toEpochMilliseconds())
awaitChange()
}
@Test
fun aFreshSnapshotIsReused() {
insert("a")
titles()
clock.current += 30.minutes
query(ProviderTable.INSTANCES).use { assertThat(it.count).isEqualTo(1) }
assertNoChange()
}
private fun currentOriginalTime(): Long =
query(ProviderTable.INSTANCES, "${Instances.DISTANCE_FROM_CURRENT} = 0").use {
assertThat(it.moveToFirst()).isTrue()
it.getLong(it.getColumnIndexOrThrow(Instances.INSTANCE_ORIGINAL_TIME))
}
}
private class MutableClock(var current: Instant) : Clock {
override fun now(): Instant = current
}
private object NoProviderInstalled : ProviderEnvironment {
override fun packageDeclaring(authority: String): String? = null
override fun isGranted(permission: String): Boolean = false
override fun appLabel(packageName: String): String? = null
}
@@ -1,827 +0,0 @@
package de.jeanlucmakiola.agendula.data.tasks.provider
import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.agendula.data.tasks.ProviderEnvironment
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
import de.jeanlucmakiola.agendula.data.tasks.StorageMode
import de.jeanlucmakiola.agendula.data.tasks.TasksContract
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Alarm
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Category
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Instances
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Properties
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Tasks
import de.jeanlucmakiola.agendula.data.tasks.room.AccountEntity
import de.jeanlucmakiola.agendula.data.tasks.room.AlarmReference
import de.jeanlucmakiola.agendula.data.tasks.room.RoomTasksDataSource
import de.jeanlucmakiola.agendula.data.tasks.room.TaskAlarmEntity
import de.jeanlucmakiola.agendula.data.tasks.room.TaskEntity
import de.jeanlucmakiola.agendula.data.tasks.room.TaskListEntity
import de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase
import de.jeanlucmakiola.agendula.domain.TaskStatus
import org.junit.After
import org.junit.Assert.assertThrows
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.time.Clock
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.milliseconds
import kotlinx.coroutines.awaitCancellation
import kotlin.time.Instant
/** Writes from another app, applied to the own store through the published tables. */
@RunWith(AndroidJUnit4::class)
class ProviderWriterTest {
private val context = ApplicationProvider.getApplicationContext<Context>()
private lateinit var db: TasksDatabase
private lateinit var resolver: ProviderResolver
private lateinit var source: ProviderSnapshotSource
private lateinit var writer: ProviderWriter
private var afterWrites = 0
private var home = 0L
/** Truncated to the store's granularity, and on the hour so occurrences land on round times. */
private val today = Instant.fromEpochMilliseconds(Clock.System.now().toEpochMilliseconds() / 3_600_000 * 3_600_000)
@Before
fun setUp() {
db = Room.inMemoryDatabaseBuilder(context, TasksDatabase::class.java).allowMainThreadQueries().build()
resolver = ProviderResolver(NoProvider)
source = ProviderSnapshotSource(context, db, resolver, awaitStartup = {})
writer = ProviderWriter(db, RoomTasksDataSource(db), source, resolver, afterWrite = { afterWrites++ })
home = db.taskLists().insert(TaskListEntity(name = "Home", color = 0))
}
@After
fun tearDown() = db.close()
private fun task(id: Long) = db.tasks().entity(id)
private fun insert(vararg values: Pair<String, Any?>): Long =
writer.insert(ProviderTable.TASKS, mapOf(Tasks.LIST_ID to home, *values))
private fun byId(table: ProviderTable, id: Long) = "${table.idColumn} = $id"
private fun synced(readOnly: Boolean = false): Long {
val account = db.accounts().insert(AccountEntity(displayName = "me", username = "me"))
return db.taskLists().insert(
TaskListEntity(name = "Work", color = 0, accountId = account, href = "https://s/w/", isReadOnly = readOnly),
)
}
private fun dailySeries(title: String = "Daily"): Long = db.tasks().insert(
TaskEntity(listId = home, uid = title, title = title, dtstart = today - 1.days, due = today - 1.days + 1.hours,
rrule = "FREQ=DAILY;COUNT=5", timezone = "UTC"),
)
/** Each instance of [taskId]'s series by its original time, with its task row and status. */
private fun instances(): List<Triple<Long, Long, Int>> =
source.rows(
ProviderTable.INSTANCES,
listOf(Instances.INSTANCE_ORIGINAL_TIME, Instances.TASK_ID, Tasks.STATUS),
null,
null,
).map { (original, taskId, status) -> Triple(original as Long, taskId as Long, (status as Long).toInt()) }
private fun instanceId(original: Instant): Long =
source.rows(
ProviderTable.INSTANCES,
listOf(Tasks.ID),
"${Instances.INSTANCE_ORIGINAL_TIME} = ?",
arrayOf(original.toEpochMilliseconds().toString()),
).single().single() as Long
// --- inserts ----------------------------------------------------------------
@Test
fun anInsertedTaskIsPublishedAndOwedASync() {
val id = insert(Tasks.TITLE to "Milk", Tasks.PRIORITY to 1)
val stored = task(id)!!
assertThat(stored.title).isEqualTo("Milk")
assertThat(stored.priority).isEqualTo(1)
assertThat(stored.isDirty).isTrue()
assertThat(source.rows(ProviderTable.TASKS, listOf(Tasks.TITLE), byId(ProviderTable.TASKS, id), null))
.containsExactly(listOf("Milk"))
assertThat(afterWrites).isEqualTo(1)
}
@Test
fun anInsertNeedsAListThatExistsAndIsWritable() {
assertThrows(IllegalArgumentException::class.java) { writer.insert(ProviderTable.TASKS, mapOf(Tasks.TITLE to "x")) }
assertThrows(IllegalArgumentException::class.java) { insert(Tasks.LIST_ID to 999L) }
val readOnly = synced(readOnly = true)
assertThrows(UnsupportedOperationException::class.java) { insert(Tasks.LIST_ID to readOnly) }
assertThat(db.tasks().live()).isEmpty()
}
@Test
fun anOccurrenceCannotBeInsertedAsATask() {
val series = dailySeries()
assertThrows(IllegalArgumentException::class.java) {
insert(Tasks.ORIGINAL_INSTANCE_ID to series, Tasks.ORIGINAL_INSTANCE_TIME to today.toEpochMilliseconds())
}
}
@Test
fun aDuplicateUidIsRejected() {
insert(Tasks.UID to "same")
assertThrows(IllegalArgumentException::class.java) { insert(Tasks.UID to "same") }
}
@Test
fun listsAndInstancesTakeNoInserts() {
assertThrows(UnsupportedOperationException::class.java) {
writer.insert(ProviderTable.LISTS, mapOf(TasksContract.Lists.NAME to "New"))
}
assertThrows(UnsupportedOperationException::class.java) { writer.insert(ProviderTable.INSTANCES, emptyMap()) }
assertThrows(UnsupportedOperationException::class.java) {
writer.update(ProviderTable.LISTS, mapOf(TasksContract.Lists.NAME to "x"), null, null)
}
assertThrows(UnsupportedOperationException::class.java) { writer.delete(ProviderTable.LISTS, null, null) }
}
@Test
fun anUnknownColumnIsRejected() {
assertThrows(IllegalArgumentException::class.java) { insert("etag" to "x") }
}
@Test
fun nothingIsWrittenInExternalMode() {
val id = insert(Tasks.TITLE to "Mine")
resolver.storageMode = StorageMode.EXTERNAL
assertThrows(IllegalStateException::class.java) { insert() }
assertThrows(IllegalStateException::class.java) {
writer.update(ProviderTable.TASKS, mapOf(Tasks.TITLE to "x"), null, null)
}
assertThat(task(id)!!.title).isEqualTo("Mine")
}
// --- updates ----------------------------------------------------------------
@Test
fun anUpdateChangesTheRowsItsSelectionMatches() {
val a = insert(Tasks.TITLE to "a")
val b = insert(Tasks.TITLE to "b")
val count = writer.update(ProviderTable.TASKS, mapOf(Tasks.STATUS to 2), "${Tasks.TITLE} = ?", arrayOf("b"))
assertThat(count).isEqualTo(1)
assertThat(task(a)!!.status).isEqualTo(TaskStatus.NEEDS_ACTION)
assertThat(task(b)!!.status).isEqualTo(TaskStatus.COMPLETED)
assertThat(task(b)!!.completedAt).isNotNull()
}
@Test
fun anUpdateMatchingNothingChangesNothing() {
insert(Tasks.TITLE to "a")
assertThat(writer.update(ProviderTable.TASKS, mapOf(Tasks.TITLE to "x"), "${Tasks.TITLE} = 'zzz'", null)).isEqualTo(0)
}
@Test
fun aTaskInAReadOnlyListCannotChange() {
val readOnly = synced(readOnly = true)
val id = db.tasks().insert(TaskEntity(listId = readOnly, uid = "r", title = "theirs"))
assertThrows(UnsupportedOperationException::class.java) {
writer.update(ProviderTable.TASKS, mapOf(Tasks.TITLE to "mine"), byId(ProviderTable.TASKS, id), null)
}
assertThrows(UnsupportedOperationException::class.java) {
writer.delete(ProviderTable.TASKS, byId(ProviderTable.TASKS, id), null)
}
assertThat(task(id)!!.title).isEqualTo("theirs")
}
@Test
fun aTaskMovesBetweenLists() {
val work = synced()
val id = insert(Tasks.TITLE to "t")
writer.update(ProviderTable.TASKS, mapOf(Tasks.LIST_ID to work), byId(ProviderTable.TASKS, id), null)
assertThat(db.tasks().live().single { it.title == "t" }.listId).isEqualTo(work)
}
@Test
fun aParentMustBeInTheSameListAndNotADescendant() {
val work = synced()
val parent = insert(Tasks.TITLE to "parent")
val child = insert(Tasks.TITLE to "child", Tasks.PARENT_ID to parent)
val elsewhere = insert(Tasks.LIST_ID to work, Tasks.TITLE to "elsewhere")
assertThat(task(child)!!.parentId).isEqualTo(parent)
assertThrows(IllegalArgumentException::class.java) {
writer.update(ProviderTable.TASKS, mapOf(Tasks.PARENT_ID to elsewhere), byId(ProviderTable.TASKS, child), null)
}
assertThrows(IllegalArgumentException::class.java) {
writer.update(ProviderTable.TASKS, mapOf(Tasks.PARENT_ID to child), byId(ProviderTable.TASKS, parent), null)
}
assertThrows(IllegalArgumentException::class.java) { insert(Tasks.PARENT_ID to 999L) }
}
@Test
fun movingASeriesDropsTheOverridesItNoLongerGenerates() {
val series = dailySeries()
writer.update(ProviderTable.INSTANCES, mapOf(Tasks.STATUS to 2), byId(ProviderTable.INSTANCES, instanceId(today)), null)
assertThat(db.tasks().overrides(series)).hasSize(1)
writer.update(
ProviderTable.TASKS,
mapOf(Tasks.DTSTART to (today + 2.hours).toEpochMilliseconds(), Tasks.DUE to (today + 3.hours).toEpochMilliseconds()),
byId(ProviderTable.TASKS, series),
null,
)
assertThat(db.tasks().overrides(series)).isEmpty()
}
@Test
fun aClientCannotTouchSyncState() {
val work = synced()
val id = db.tasks().insert(
TaskEntity(listId = work, uid = "s", title = "t", href = "/s.ics", etag = "e", sequence = 2, unknownProperties = "X-A:1"),
)
writer.update(ProviderTable.TASKS, mapOf(Tasks.TITLE to "new", "_sync_id" to "x", "sync1" to "y"), byId(ProviderTable.TASKS, id), null)
val stored = task(id)!!
assertThat(stored.title).isEqualTo("new")
assertThat(stored.href).isEqualTo("/s.ics")
assertThat(stored.etag).isEqualTo("e")
assertThat(stored.sequence).isEqualTo(2)
assertThat(stored.unknownProperties).isEqualTo("X-A:1")
assertThat(stored.isDirty).isTrue()
}
// --- instances --------------------------------------------------------------
@Test
fun completingAnOccurrenceTicksOffOnlyThatOne() {
val series = dailySeries()
val count = writer.update(ProviderTable.INSTANCES, mapOf(Tasks.STATUS to 2), byId(ProviderTable.INSTANCES, instanceId(today)), null)
assertThat(count).isEqualTo(1)
assertThat(task(series)!!.status).isEqualTo(TaskStatus.NEEDS_ACTION)
val override = db.tasks().overrides(series).single()
assertThat(override.recurrenceId).isEqualTo(today)
assertThat(override.status).isEqualTo(TaskStatus.COMPLETED)
val statuses = instances().associate { it.first to it.third }
assertThat(statuses[today.toEpochMilliseconds()]).isEqualTo(TasksContract.STATUS_COMPLETED)
assertThat(statuses.filterKeys { it != today.toEpochMilliseconds() }.values.toSet())
.containsExactly(TasksContract.STATUS_NEEDS_ACTION)
}
@Test
fun anOccurrenceCanBeCancelledAndReopened() {
val series = dailySeries()
writer.update(ProviderTable.INSTANCES, mapOf(Tasks.STATUS to 3), byId(ProviderTable.INSTANCES, instanceId(today)), null)
assertThat(db.tasks().overrides(series).single().status).isEqualTo(TaskStatus.CANCELLED)
writer.update(ProviderTable.INSTANCES, mapOf(Tasks.PERCENT_COMPLETE to 0), byId(ProviderTable.INSTANCES, instanceId(today)), null)
assertThat(db.tasks().overrides(series).single().status).isEqualTo(TaskStatus.NEEDS_ACTION)
}
@Test
fun contentWrittenToAnOccurrenceEditsTheSeries() {
val series = dailySeries()
writer.update(ProviderTable.INSTANCES, mapOf(Tasks.TITLE to "Renamed"), byId(ProviderTable.INSTANCES, instanceId(today)), null)
assertThat(task(series)!!.title).isEqualTo("Renamed")
assertThat(db.tasks().overrides(series)).isEmpty()
}
@Test
fun anOccurrenceCannotBeMoved() {
dailySeries()
assertThrows(IllegalArgumentException::class.java) {
writer.update(ProviderTable.INSTANCES, mapOf(Tasks.DUE to 0L), byId(ProviderTable.INSTANCES, instanceId(today)), null)
}
}
@Test
fun anOccurrenceHasNoPartialProgress() {
dailySeries()
assertThrows(IllegalArgumentException::class.java) {
writer.update(ProviderTable.INSTANCES, mapOf(Tasks.PERCENT_COMPLETE to 50), byId(ProviderTable.INSTANCES, instanceId(today)), null)
}
}
@Test
fun aPlainTaskInstanceWritesTheTask() {
val id = insert(Tasks.TITLE to "t", Tasks.DUE to today.toEpochMilliseconds())
val instance = source.rows(ProviderTable.INSTANCES, listOf(Tasks.ID), "${Instances.TASK_ID} = $id", null).single().single() as Long
writer.update(ProviderTable.INSTANCES, mapOf(Tasks.PERCENT_COMPLETE to 50, Tasks.DUE to (today + 1.days).toEpochMilliseconds()), byId(ProviderTable.INSTANCES, instance), null)
assertThat(task(id)!!.status).isEqualTo(TaskStatus.IN_PROCESS)
assertThat(task(id)!!.due).isEqualTo(today + 1.days)
}
@Test
fun deletingAnOccurrenceExceptsIt() {
val series = dailySeries()
assertThat(writer.delete(ProviderTable.INSTANCES, byId(ProviderTable.INSTANCES, instanceId(today)), null)).isEqualTo(1)
assertThat(task(series)!!.exdate).isNotNull()
assertThat(instances().map { it.first }).doesNotContain(today.toEpochMilliseconds())
assertThat(instances()).hasSize(4)
}
@Test
fun deletingAModifiedOccurrenceExceptsItToo() {
val series = dailySeries()
writer.update(ProviderTable.INSTANCES, mapOf(Tasks.STATUS to 2), byId(ProviderTable.INSTANCES, instanceId(today)), null)
writer.delete(ProviderTable.INSTANCES, byId(ProviderTable.INSTANCES, instanceId(today)), null)
assertThat(db.tasks().overrides(series)).isEmpty()
assertThat(instances().map { it.first }).doesNotContain(today.toEpochMilliseconds())
}
// --- deletes ----------------------------------------------------------------
@Test
fun aParentGoesWithItsSubtasks() {
val parent = insert(Tasks.TITLE to "parent")
val child = insert(Tasks.TITLE to "child", Tasks.PARENT_ID to parent)
val grandchild = insert(Tasks.TITLE to "grandchild", Tasks.PARENT_ID to child)
val other = insert(Tasks.TITLE to "other")
assertThat(writer.delete(ProviderTable.TASKS, byId(ProviderTable.TASKS, parent), null)).isEqualTo(1)
assertThat(task(parent)).isNull()
assertThat(task(child)).isNull()
assertThat(task(grandchild)).isNull()
assertThat(task(other)).isNotNull()
}
@Test
fun aSyncedTaskLeavesATombstone() {
val work = synced()
val id = insert(Tasks.LIST_ID to work, Tasks.TITLE to "t")
writer.delete(ProviderTable.TASKS, byId(ProviderTable.TASKS, id), null)
assertThat(task(id)!!.isDeleted).isTrue()
assertThat(source.rows(ProviderTable.TASKS, listOf(Tasks.ID), null, null)).isEmpty()
assertThat(writer.update(ProviderTable.TASKS, mapOf(Tasks.TITLE to "x"), byId(ProviderTable.TASKS, id), null)).isEqualTo(0)
}
@Test
fun deletingAnOverrideThroughTasksExceptsTheOccurrence() {
val series = dailySeries()
writer.update(ProviderTable.INSTANCES, mapOf(Tasks.STATUS to 2), byId(ProviderTable.INSTANCES, instanceId(today)), null)
val override = db.tasks().overrides(series).single().id
writer.delete(ProviderTable.TASKS, byId(ProviderTable.TASKS, override), null)
assertThat(task(series)).isNotNull()
assertThat(task(series)!!.exdate).isNotNull()
assertThat(instances()).hasSize(4)
}
// --- properties -------------------------------------------------------------
@Test
fun anAlarmCanBeAddedChangedAndRemoved() {
val id = insert(Tasks.TITLE to "t", Tasks.DUE to (today + 1.days).toEpochMilliseconds())
db.tasks().update(task(id)!!.copy(isDirty = false))
val propertyId = writer.insert(
ProviderTable.PROPERTIES,
mapOf(Properties.TASK_ID to id, Properties.MIMETYPE to Alarm.MIMETYPE, Alarm.MINUTES_BEFORE to "15", Alarm.REFERENCE to "1"),
)
val alarm = db.alarms().forTask(id).single()
assertThat(alarm.minutesBefore).isEqualTo(15)
assertThat(alarm.reference).isEqualTo(AlarmReference.DUE)
assertThat(task(id)!!.isDirty).isTrue()
assertThat(propertyId).isEqualTo(ProviderIds.alarm(alarm.id))
writer.update(ProviderTable.PROPERTIES, mapOf(Alarm.MINUTES_BEFORE to 60, Alarm.REFERENCE to 2), byId(ProviderTable.PROPERTIES, propertyId), null)
assertThat(db.alarms().forTask(id).single().minutesBefore).isEqualTo(60)
assertThat(db.alarms().forTask(id).single().reference).isEqualTo(AlarmReference.START)
writer.delete(ProviderTable.PROPERTIES, "${Properties.MIMETYPE} = ?", arrayOf(Alarm.MIMETYPE))
assertThat(db.alarms().forTask(id)).isEmpty()
}
@Test
fun tagsCanBeAddedRenamedAndRemoved() {
val id = insert(Tasks.TITLE to "t")
val propertyId = writer.insert(
ProviderTable.PROPERTIES,
mapOf(Properties.TASK_ID to id, Properties.MIMETYPE to Category.MIMETYPE, Category.NAME to " errand "),
)
assertThat(task(id)!!.categories).containsExactly("errand")
writer.update(ProviderTable.PROPERTIES, mapOf(Category.NAME to "shopping"), byId(ProviderTable.PROPERTIES, propertyId), null)
assertThat(task(id)!!.categories).containsExactly("shopping")
writer.insert(ProviderTable.PROPERTIES, mapOf(Properties.TASK_ID to id, Properties.MIMETYPE to Category.MIMETYPE, Category.NAME to "shopping"))
assertThat(task(id)!!.categories).containsExactly("shopping")
writer.delete(ProviderTable.PROPERTIES, "${Category.NAME} = ?", arrayOf("shopping"))
assertThat(task(id)!!.categories).isEmpty()
}
@Test
fun aPropertyCannotChangeItsKindOrTask() {
val id = insert(Tasks.TITLE to "t")
val other = insert(Tasks.TITLE to "o")
db.alarms().insert(TaskAlarmEntity(taskId = id, minutesBefore = 5))
val propertyId = source.rows(ProviderTable.PROPERTIES, listOf(Properties.PROPERTY_ID), null, null).single().single() as Long
assertThrows(IllegalArgumentException::class.java) {
writer.update(ProviderTable.PROPERTIES, mapOf(Properties.MIMETYPE to Category.MIMETYPE), byId(ProviderTable.PROPERTIES, propertyId), null)
}
assertThrows(IllegalArgumentException::class.java) {
writer.update(ProviderTable.PROPERTIES, mapOf(Properties.TASK_ID to other), byId(ProviderTable.PROPERTIES, propertyId), null)
}
}
@Test
fun onlyAlarmsAndTagsCanBeWritten() {
val id = insert(Tasks.TITLE to "t")
assertThrows(IllegalArgumentException::class.java) {
writer.insert(ProviderTable.PROPERTIES, mapOf(Properties.TASK_ID to id, Properties.MIMETYPE to "vnd.android.cursor.item/comment"))
}
assertThrows(IllegalArgumentException::class.java) {
writer.insert(ProviderTable.PROPERTIES, mapOf(Properties.TASK_ID to id, Properties.MIMETYPE to Alarm.MIMETYPE))
}
}
// --- batches ----------------------------------------------------------------
@Test
fun aBatchIsAllOrNothing() {
assertThrows(IllegalArgumentException::class.java) {
writer.batch {
insert(Tasks.TITLE to "first")
insert(Tasks.TITLE to "second")
insert(Tasks.LIST_ID to 999L)
}
}
assertThat(db.tasks().live()).isEmpty()
assertThat(source.rows(ProviderTable.TASKS, listOf(Tasks.ID), null, null)).isEmpty()
}
@Test
fun aBatchSeesItsOwnWritesAndReArmsRemindersOnce() {
writer.batch {
insert(Tasks.TITLE to "first")
writer.update(ProviderTable.TASKS, mapOf(Tasks.STATUS to 2), "${Tasks.TITLE} = ?", arrayOf("first"))
}
assertThat(db.tasks().live().single().status).isEqualTo(TaskStatus.COMPLETED)
assertThat(afterWrites).isEqualTo(1)
}
// --- review regressions -----------------------------------------------------
@Test
fun aBatchDeletingTwoPropertiesDeletesThoseTwo() {
val a = insert(Tasks.TITLE to "a")
val b = insert(Tasks.TITLE to "b")
listOf(5, 10).forEach { db.alarms().insert(TaskAlarmEntity(taskId = a, minutesBefore = it)) }
db.alarms().insert(TaskAlarmEntity(taskId = b, minutesBefore = 15))
val ids = source.rows(ProviderTable.PROPERTIES, listOf(Properties.PROPERTY_ID), "${Properties.TASK_ID} = $a", null)
.map { it.single() as Long }
writer.batch { ids.forEach { writer.delete(ProviderTable.PROPERTIES, byId(ProviderTable.PROPERTIES, it), null) } }
assertThat(db.alarms().forTask(a)).isEmpty()
assertThat(db.alarms().forTask(b).map { it.minutesBefore }).containsExactly(15)
}
@Test
fun aBatchDeletingTwoOccurrencesDeletesThoseTwo() {
dailySeries()
val first = instanceId(today)
val second = instanceId(today + 1.days)
writer.batch {
writer.delete(ProviderTable.INSTANCES, byId(ProviderTable.INSTANCES, first), null)
writer.delete(ProviderTable.INSTANCES, byId(ProviderTable.INSTANCES, second), null)
}
assertThat(instances().map { it.first }).containsExactly(
(today - 1.days).toEpochMilliseconds(),
(today + 2.days).toEpochMilliseconds(),
(today + 3.days).toEpochMilliseconds(),
)
}
@Test
fun anInstanceIdOutlivesAnotherOccurrencesDeletion() {
dailySeries()
val later = instanceId(today + 2.days)
writer.delete(ProviderTable.INSTANCES, byId(ProviderTable.INSTANCES, instanceId(today)), null)
assertThat(instanceId(today + 2.days)).isEqualTo(later)
assertThat(writer.update(ProviderTable.INSTANCES, mapOf(Tasks.STATUS to 2), byId(ProviderTable.INSTANCES, later), null))
.isEqualTo(1)
assertThat(instances().single { it.third == TasksContract.STATUS_COMPLETED }.first)
.isEqualTo((today + 2.days).toEpochMilliseconds())
}
@Test
fun aRecurringSubtaskOutsideTheWindowGoesWithItsParent() {
val parent = insert(Tasks.TITLE to "parent")
val longAgo = today - 1000.days
val subtask = db.tasks().insert(
TaskEntity(listId = home, uid = "old", title = "old", dtstart = longAgo, rrule = "FREQ=DAILY;COUNT=2",
timezone = "UTC", parentId = parent),
)
writer.delete(ProviderTable.TASKS, byId(ProviderTable.TASKS, parent), null)
assertThat(task(subtask)).isNull()
}
@Test
fun anOverriddenRecurringSubtaskGoesWholeWithItsParent() {
val parent = insert(Tasks.TITLE to "parent")
val subtask = dailySeries("sub")
db.tasks().update(task(subtask)!!.copy(parentId = parent))
writer.update(ProviderTable.INSTANCES, mapOf(Tasks.STATUS to 2), byId(ProviderTable.INSTANCES, instanceId(today)), null)
writer.delete(ProviderTable.TASKS, byId(ProviderTable.TASKS, parent), null)
assertThat(task(subtask)).isNull()
assertThat(db.tasks().live()).isEmpty()
}
@Test
fun aModifiedOccurrenceCanBeWrittenBackAsRead() {
val series = dailySeries()
writer.update(ProviderTable.INSTANCES, mapOf(Tasks.STATUS to 2), byId(ProviderTable.INSTANCES, instanceId(today)), null)
val override = db.tasks().overrides(series).single().id
val row = readRow(ProviderTable.TASKS, override)
writer.update(ProviderTable.TASKS, row + (Tasks.TITLE to "Renamed"), byId(ProviderTable.TASKS, override), null)
assertThat(task(override)!!.title).isEqualTo("Renamed")
}
@Test
fun anInstanceCanBeWrittenBackAsReadToCompleteIt() {
val series = dailySeries()
val instance = instanceId(today)
val row = readRow(ProviderTable.INSTANCES, instance)
writer.update(ProviderTable.INSTANCES, row + (Tasks.STATUS to 2), byId(ProviderTable.INSTANCES, instance), null)
assertThat(db.tasks().overrides(series).single().status).isEqualTo(TaskStatus.COMPLETED)
assertThat(task(series)!!.dtstart).isEqualTo(today - 1.days)
}
@Test
fun movingASubtreeMovesItsSubtasks() {
val work = synced()
val parent = insert(Tasks.TITLE to "parent")
val child = insert(Tasks.TITLE to "child", Tasks.PARENT_ID to parent)
val grandchild = insert(Tasks.TITLE to "grandchild", Tasks.PARENT_ID to child)
writer.update(ProviderTable.TASKS, mapOf(Tasks.LIST_ID to work), byId(ProviderTable.TASKS, parent), null)
assertThat(listOf(parent, child, grandchild).map { task(it)!!.listId }).containsExactly(work, work, work)
assertThat(task(child)!!.parentId).isEqualTo(parent)
assertThat(task(grandchild)!!.parentId).isEqualTo(child)
}
@Test
fun aMoveOntoATakenUidIsRejected() {
val work = synced()
insert(Tasks.LIST_ID to work, Tasks.UID to "same")
val id = insert(Tasks.UID to "same")
assertThrows(IllegalArgumentException::class.java) {
writer.update(ProviderTable.TASKS, mapOf(Tasks.LIST_ID to work), byId(ProviderTable.TASKS, id), null)
}
assertThat(task(id)!!.listId).isEqualTo(home)
}
@Test
fun contentOnAModifiedOccurrenceStillEditsTheSeries() {
val series = dailySeries()
writer.update(ProviderTable.INSTANCES, mapOf(Tasks.STATUS to 2), byId(ProviderTable.INSTANCES, instanceId(today)), null)
val override = db.tasks().overrides(series).single().id
writer.update(ProviderTable.INSTANCES, mapOf(Tasks.TITLE to "Renamed"), byId(ProviderTable.INSTANCES, instanceId(today)), null)
assertThat(task(series)!!.title).isEqualTo("Renamed")
assertThat(task(override)!!.title).isEqualTo("Renamed")
assertThat(task(override)!!.status).isEqualTo(TaskStatus.COMPLETED)
}
@Test
fun aWriteThatChangesNothingOwesNoSync() {
val id = insert(Tasks.TITLE to "t")
db.tasks().update(task(id)!!.copy(isDirty = false))
val modified = task(id)!!.lastModified
writer.update(ProviderTable.TASKS, readRow(ProviderTable.TASKS, id), byId(ProviderTable.TASKS, id), null)
writer.update(ProviderTable.TASKS, emptyMap(), byId(ProviderTable.TASKS, id), null)
assertThat(task(id)!!.isDirty).isFalse()
assertThat(task(id)!!.lastModified).isEqualTo(modified)
}
@Test
fun reopeningAnOpenOccurrenceForksNothing() {
val series = dailySeries()
writer.update(ProviderTable.INSTANCES, mapOf(Tasks.STATUS to 0), byId(ProviderTable.INSTANCES, instanceId(today)), null)
assertThat(db.tasks().overrides(series)).isEmpty()
}
@Test
fun aWriteBeforeStartupSettlesIsRefused() {
val stuck = ProviderSnapshotSource(context, db, resolver, awaitStartup = { awaitCancellation() }, startupWait = 50.milliseconds)
val early = ProviderWriter(db, RoomTasksDataSource(db), stuck, resolver, afterWrite = {})
assertThrows(IllegalStateException::class.java) { early.insert(ProviderTable.TASKS, mapOf(Tasks.LIST_ID to home)) }
assertThat(db.tasks().live()).isEmpty()
}
@Test
fun aSingleRowWriteNeedsNoSnapshot() {
val id = insert(Tasks.TITLE to "t")
val unknown = 987_654L
assertThat(writer.update(ProviderTable.TASKS, mapOf(Tasks.TITLE to "x"), byId(ProviderTable.TASKS, unknown), null)).isEqualTo(0)
assertThat(writer.update(ProviderTable.TASKS, mapOf(Tasks.TITLE to "x"), byId(ProviderTable.TASKS, id), null)).isEqualTo(1)
assertThat(writer.update(ProviderTable.INSTANCES, mapOf(Tasks.TITLE to "x"), byId(ProviderTable.INSTANCES, unknown), null)).isEqualTo(0)
assertThat(writer.delete(ProviderTable.PROPERTIES, byId(ProviderTable.PROPERTIES, unknown), null)).isEqualTo(0)
}
// --- second review regressions -----------------------------------------------
@Test
fun tickingOffAModifiedOccurrenceAsReadLeavesTheSeriesAlone() {
val series = dailySeries("Standup")
// Reopening forks an override, which then gets its own title as the app's "this occurrence" edit would.
store().setCompletedInstance(series, today, false)
val override = db.tasks().overrides(series).single()
db.tasks().update(override.copy(title = "Standup (moved room)"))
val row = readRow(ProviderTable.INSTANCES, instanceId(today))
writer.update(ProviderTable.INSTANCES, row + (Tasks.STATUS to 2), byId(ProviderTable.INSTANCES, instanceId(today)), null)
assertThat(task(series)!!.title).isEqualTo("Standup")
assertThat(task(override.id)!!.title).isEqualTo("Standup (moved room)")
assertThat(task(override.id)!!.status).isEqualTo(TaskStatus.COMPLETED)
}
@Test
fun anInstanceWrittenBackWithOnlyProgressChangedIsCompleted() {
val series = dailySeries()
val row = readRow(ProviderTable.INSTANCES, instanceId(today))
writer.update(ProviderTable.INSTANCES, row + (Tasks.PERCENT_COMPLETE to 100), byId(ProviderTable.INSTANCES, instanceId(today)), null)
assertThat(db.tasks().overrides(series).single().status).isEqualTo(TaskStatus.COMPLETED)
}
@Test
fun aBadZoneOnAnInstanceReportsTheZone() {
dailySeries()
val instance = instanceId(today)
val error = assertThrows(IllegalArgumentException::class.java) {
writer.update(ProviderTable.INSTANCES, mapOf(Tasks.TZ to "Europe/Berln"), byId(ProviderTable.INSTANCES, instance), null)
}
assertThat(error).hasMessageThat().contains("Unknown time zone")
}
@Test
fun anInProcessSeriesCanBeWrittenBackAsRead() {
val series = dailySeries()
db.tasks().update(task(series)!!.copy(status = TaskStatus.IN_PROCESS, percentComplete = 50))
val row = readRow(ProviderTable.INSTANCES, instanceId(today))
writer.update(ProviderTable.INSTANCES, row + (Tasks.TITLE to "Renamed"), byId(ProviderTable.INSTANCES, instanceId(today)), null)
assertThat(task(series)!!.title).isEqualTo("Renamed")
assertThat(task(series)!!.status).isEqualTo(TaskStatus.IN_PROCESS)
assertThat(db.tasks().overrides(series)).isEmpty()
}
@Test
fun aFloatingSeriesCanBeWrittenBackAsRead() {
val series = db.tasks().insert(
TaskEntity(listId = home, uid = "f", title = "Floating", due = today, rrule = "FREQ=DAILY;COUNT=3", timezone = null),
)
// The second occurrence: ticking the first moves the series on instead.
val second = today + 1.days
val row = readRow(ProviderTable.INSTANCES, instanceId(second))
writer.update(ProviderTable.INSTANCES, row + (Tasks.STATUS to 2), byId(ProviderTable.INSTANCES, instanceId(second)), null)
writer.update(ProviderTable.TASKS, mapOf(Tasks.TITLE to "Still floating"), byId(ProviderTable.TASKS, series), null)
assertThat(db.tasks().overrides(series).single().status).isEqualTo(TaskStatus.COMPLETED)
assertThat(task(series)!!.timezone).isNull()
}
@Test
fun aParentLoopDeletesInsteadOfRecursingForever() {
val a = insert(Tasks.TITLE to "a")
val b = insert(Tasks.TITLE to "b", Tasks.PARENT_ID to a)
db.tasks().update(task(a)!!.copy(parentId = b))
writer.delete(ProviderTable.TASKS, byId(ProviderTable.TASKS, a), null)
assertThat(task(a)).isNull()
assertThat(task(b)).isNull()
}
@Test
fun aBulkMoveWorksWhicheverOrderTheRowsComeIn() {
val work = synced()
// The subtask gets the lower id, so it comes first unless the writer reorders.
val child = insert(Tasks.TITLE to "child")
val parent = insert(Tasks.TITLE to "parent")
db.tasks().update(task(child)!!.copy(parentId = parent))
val count = writer.update(ProviderTable.TASKS, mapOf(Tasks.LIST_ID to work), "${Tasks.LIST_ID} = ?", arrayOf(home.toString()))
assertThat(count).isEqualTo(2)
assertThat(task(child)!!.listId).isEqualTo(work)
assertThat(task(parent)!!.listId).isEqualTo(work)
assertThat(task(child)!!.parentId).isEqualTo(parent)
}
@Test
fun aRowSelectedWithAnArgumentIsWritten() {
val a = insert(Tasks.TITLE to "a")
val b = insert(Tasks.TITLE to "b")
assertThat(writer.update(ProviderTable.TASKS, mapOf(Tasks.TITLE to "x"), "${Tasks.ID}=?", arrayOf(b.toString()))).isEqualTo(1)
assertThat(writer.update(ProviderTable.TASKS, mapOf(Tasks.TITLE to "x"), "${Tasks.ID} = ?", arrayOf("987654"))).isEqualTo(0)
assertThat(task(a)!!.title).isEqualTo("a")
assertThat(task(b)!!.title).isEqualTo("x")
}
@Test
fun garbageExceptionDatesAreRejected() {
val series = dailySeries()
assertThrows(IllegalArgumentException::class.java) {
writer.update(ProviderTable.TASKS, mapOf(Tasks.EXDATE to "tomorrow"), byId(ProviderTable.TASKS, series), null)
}
assertThat(task(series)!!.exdate).isNull()
}
private fun store() = RoomTasksDataSource(db)
@Test
fun reopeningATickedOccurrencesCopyMovesTheSeriesBack() {
val series = db.tasks().insert(
TaskEntity(listId = home, uid = "w", title = "Weekly", dtstart = today, rrule = "FREQ=WEEKLY", timezone = "UTC"),
)
store().setCompletedInstance(series, today, true)
val copy = db.tasks().allIn(home).single { it.id != series }
writer.update(ProviderTable.TASKS, mapOf(Tasks.STATUS to 0), byId(ProviderTable.TASKS, copy.id), null)
assertThat(task(series)!!.dtstart).isEqualTo(today)
assertThat(task(copy.id)).isNull()
}
/** Every column of one published row, as a client that read it would write it back. */
private fun readRow(table: ProviderTable, id: Long): Map<String, Any?> {
val columns = table.columns.map { it.first }
val row = source.rows(table, columns, byId(table, id), null).single()
return columns.zip(row).toMap() - table.idColumn
}
}
private object NoProvider : ProviderEnvironment {
override fun packageDeclaring(authority: String): String? = null
override fun isGranted(permission: String): Boolean = false
override fun appLabel(packageName: String): String? = null
}
@@ -1,141 +0,0 @@
package de.jeanlucmakiola.agendula.data.tasks.provider
import android.database.Cursor
import android.os.Build
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Lists
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Tasks
import org.junit.Assert.assertThrows
import org.junit.Assume.assumeTrue
import org.junit.Test
import org.junit.runner.RunWith
/** The SQL a client sends runs against the snapshot as it would against OpenTasks. */
@RunWith(AndroidJUnit4::class)
class SnapshotDatabaseTest {
private val db = SnapshotDatabase()
private fun task(id: Long, title: String?, due: Long? = null): ProviderRow =
mapOf(Tasks.ID to id, Tasks.LIST_ID to 1L, Tasks.TITLE to title, Tasks.DUE to due, Tasks.PRIORITY to 0)
private fun load(vararg tasks: ProviderRow, lists: List<ProviderRow> = emptyList()) = db.load(
ProviderSnapshot(
ProviderTable.entries.associateWith {
when (it) {
ProviderTable.TASKS -> tasks.toList()
ProviderTable.LISTS -> lists
else -> emptyList()
}
},
),
)
private fun Cursor.strings(column: String): List<String?> = use {
val index = getColumnIndexOrThrow(column)
buildList { while (moveToNext()) add(if (isNull(index)) null else getString(index)) }
}
@Test
fun aNullProjectionReturnsEveryColumnInTableOrder() {
load(task(1, "a"))
db.query(ProviderTable.TASKS, null, null, null, null).use {
assertThat(it.columnNames.toList()).containsExactlyElementsIn(ProviderTable.TASKS.columns.map { c -> c.first })
.inOrder()
assertThat(it.count).isEqualTo(1)
}
}
@Test
fun selectionArgumentsAndSortOrderApply() {
load(task(1, "b", due = 30), task(2, "a", due = 10), task(3, "c", due = 20), task(4, "skip", due = 5))
val titles = db.query(ProviderTable.TASKS, arrayOf(Tasks.TITLE), "${Tasks.TITLE} != ?", arrayOf("skip"), "${Tasks.DUE} ASC")
.strings(Tasks.TITLE)
assertThat(titles).containsExactly("a", "c", "b").inOrder()
}
@Test
fun typesSurviveTheCopy() {
load(task(1, null, due = 1_700_000_000_000))
db.query(ProviderTable.TASKS, arrayOf(Tasks.TITLE, Tasks.DUE, Tasks.PRIORITY), null, null, null).use {
it.moveToFirst()
assertThat(it.isNull(0)).isTrue()
assertThat(it.getType(1)).isEqualTo(Cursor.FIELD_TYPE_INTEGER)
assertThat(it.getLong(1)).isEqualTo(1_700_000_000_000)
assertThat(it.getInt(2)).isEqualTo(0)
}
}
@Test
fun anUnsupportedColumnReadsAsNull() {
load(task(1, "a"))
assertThat(db.query(ProviderTable.TASKS, arrayOf("_sync_id"), null, null, null).strings("_sync_id"))
.containsExactly(null)
}
@Test
fun anUnknownProjectionColumnIsRejected() {
load(task(1, "a"))
assertThrows(IllegalArgumentException::class.java) {
db.query(ProviderTable.TASKS, arrayOf("no_such_column"), null, null, null)
}
}
@Test
fun anUnknownSelectionColumnIsRejected() {
assumeTrue(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
load(task(1, "a"))
assertThrows(IllegalArgumentException::class.java) {
db.query(ProviderTable.TASKS, null, "sqlite_master.name IS NOT NULL", null, null)
}
}
@Test
fun aSelectionCannotBreakOutOfItsWhereClause() {
load(task(1, "a"))
assertThrows(IllegalArgumentException::class.java) {
db.query(ProviderTable.TASKS, null, "1) UNION SELECT name FROM sqlite_master --", null, null)
}
}
@Test
fun eachTableAnswersOnlyForItsOwnRows() {
load(task(1, "a"), lists = listOf(mapOf(Lists.ID to 7L, Lists.NAME to "Home")))
assertThat(db.query(ProviderTable.LISTS, arrayOf(Lists.NAME), null, null, null).strings(Lists.NAME))
.containsExactly("Home")
db.query(ProviderTable.INSTANCES, null, null, null, null).use { assertThat(it.count).isEqualTo(0) }
}
@Test
fun aReloadReplacesTheRowsButNotAnOpenCursor() {
load(task(1, "old"))
val before = db.query(ProviderTable.TASKS, arrayOf(Tasks.TITLE), null, null, null)
load(task(2, "new"))
assertThat(before.strings(Tasks.TITLE)).containsExactly("old")
assertThat(db.query(ProviderTable.TASKS, arrayOf(Tasks.TITLE), null, null, null).strings(Tasks.TITLE))
.containsExactly("new")
}
@Test
fun anEmptySnapshotEmptiesEveryTable() {
load(task(1, "a"))
db.load(ProviderSnapshot.EMPTY)
ProviderTable.entries.forEach { table ->
db.query(table, null, null, null, null).use { assertThat(it.count).isEqualTo(0) }
}
}
}
@@ -8,7 +8,27 @@ import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/** Migrations, proven against the committed schemas in `app/schemas/`. */
/**
* The migration harness, proven against the committed schema in `app/schemas/`.
*
* There is one schema version today, so all there is to assert is that the helper
* can build v1 from the exported JSON, seed it, and validate it back — i.e. the
* export, the assets wiring and the identity hash all line up. That is the point:
* the first real migration only has to add its own case.
*
* **Adding a v1 → v2 case.** When sync adds columns, bump [TasksDatabase]'s
* `version`, let KSP export `2.json`, declare the `Migration(1, 2)` next to the
* database, and add a test here shaped like this:
*
* ```
* helper.createDatabase(TEST_DB, 1).use { db ->
* db.execSQL("INSERT INTO task_lists (name, color) VALUES ('Groceries', 0)")
* }
* helper.runMigrationsAndValidate(TEST_DB, 2, true, MIGRATION_1_2).use { db ->
* // read the seeded rows back — validation proves the shape, not the data
* }
* ```
*/
@RunWith(AndroidJUnit4::class)
class TasksDatabaseMigrationTest {
@@ -42,182 +62,6 @@ class TasksDatabaseMigrationTest {
}
}
@Test
fun liftsCategoriesOutOfTheResidueWithoutDirtyingTheTask() {
helper.createDatabase(TEST_DB, 1).use { db ->
db.execSQL("INSERT INTO task_lists (id, name, color) VALUES (1, 'Work', 0)")
db.execSQL(
"INSERT INTO tasks (id, list_id, uid, title, unknown_properties) VALUES (?, 1, ?, ?, ?)",
arrayOf<Any?>(1, "uid-1", "Claimed", "X-FOO:bar\r\nCATEGORIES:Work,Home\r\n"),
)
db.execSQL(
"INSERT INTO tasks (id, list_id, uid, title, unknown_properties) VALUES (?, 1, ?, ?, ?)",
arrayOf<Any?>(2, "uid-2", "Split", "CATEGORIES:a\r\nCATEGORIES:b\r\n"),
)
db.execSQL("INSERT INTO tasks (id, list_id, uid, title) VALUES (3, 1, 'uid-3', 'Untagged')")
}
helper.runMigrationsAndValidate(TEST_DB, 2, true, TasksDatabase.MIGRATION_1_2).use { db ->
db.query("SELECT categories, unknown_properties, is_dirty FROM tasks ORDER BY id").use { c ->
c.moveToNext()
assertThat(c.getString(0)).isEqualTo("Work,Home")
assertThat(c.getString(1)).doesNotContain("CATEGORIES")
assertThat(c.getString(1)).contains("X-FOO:bar")
assertThat(c.getInt(2)).isEqualTo(0)
c.moveToNext()
assertThat(c.getString(0)).isEqualTo("a,b")
assertThat(c.getString(1)).isEqualTo("CATEGORIES:a\r\nCATEGORIES:b\r\n")
c.moveToNext()
assertThat(c.getString(0)).isEmpty()
}
}
}
@Test
fun liftsClaimableAlarmsAndPushesRemindersThatNeverLeftTheDevice() {
val future = System.currentTimeMillis() + 7L * 24 * 60 * 60 * 1000
val past = System.currentTimeMillis() - 7L * 24 * 60 * 60 * 1000
val claimable = "X-FOO:bar\r\nBEGIN:VALARM\r\nACTION:DISPLAY\r\nX-WR-ALARMUID:srv\r\n" +
"TRIGGER;RELATED=END:-PT15M\r\nEND:VALARM\r\n"
val appleDefault = "BEGIN:VALARM\r\nACTION:DISPLAY\r\nX-APPLE-DEFAULT-ALARM:TRUE\r\n" +
"TRIGGER;RELATED=END:-PT30M\r\nEND:VALARM\r\n"
helper.createDatabase(TEST_DB, 2).use { db ->
db.execSQL("INSERT INTO accounts (id, display_name) VALUES (1, 'me')")
db.execSQL("INSERT INTO task_lists (id, name, color, account_id) VALUES (1, 'Synced', 0, 1)")
db.execSQL("INSERT INTO task_lists (id, name, color) VALUES (2, 'Local', 0)")
db.execSQL("INSERT INTO task_lists (id, name, color, account_id, is_read_only) VALUES (3, 'Shared', 0, 1, 1)")
fun task(id: Int, list: Int, due: Long, residue: String? = null) = db.execSQL(
"INSERT INTO tasks (id, list_id, uid, title, due, unknown_properties) VALUES (?, ?, ?, ?, ?, ?)",
arrayOf<Any?>(id, list, "uid-$id", "Task $id", due, residue),
)
fun alarm(task: Int, minutes: Int) =
db.execSQL("INSERT INTO task_alarms (task_id, minutes_before) VALUES (?, ?)", arrayOf<Any?>(task, minutes))
// A server alarm, and the same lead copied locally by a fork.
task(1, 1, future, claimable)
alarm(1, 15)
// Set in Agendula, never uploaded — still to fire, already past, device-only.
task(2, 1, future)
alarm(2, 30)
task(3, 1, past)
alarm(3, 30)
task(4, 2, future)
alarm(4, 30)
// Somebody else's default alarm: not ours to claim.
task(5, 1, future, appleDefault)
// A read-only share: dirty would freeze it, never sent and never refreshed.
task(6, 3, future)
alarm(6, 30)
}
helper.runMigrationsAndValidate(TEST_DB, 3, true, TasksDatabase.MIGRATION_2_3).use { db ->
db.query("SELECT task_id, minutes_before, uid, raw FROM task_alarms ORDER BY task_id").use { c ->
val rows = buildList { while (c.moveToNext()) add(listOf(c.getLong(0), c.getInt(1), c.getString(2), c.getString(3))) }
// One for task 1: the lifted copy won and the local duplicate went.
assertThat(rows.map { it[0] }).containsExactly(1L, 2L, 3L, 4L, 6L).inOrder()
assertThat(rows[0][2]).isEqualTo("srv")
assertThat(rows[0][3] as String).contains("TRIGGER;RELATED=END:-PT15M")
// Every pre-existing row got an identity of its own, shaped as a UUID.
assertThat(rows.drop(1).map { it[2] as String }.toSet()).hasSize(4)
rows.drop(1).forEach {
assertThat(it[2] as String).matches("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}")
}
assertThat(rows.drop(1).all { (it[2] as String).isNotEmpty() && it[3] == null }).isTrue()
}
db.query("SELECT id, unknown_properties, is_dirty, last_modified, reminders_off FROM tasks ORDER BY id").use { c ->
c.moveToNext()
assertThat(c.getString(1)).isEqualTo("X-FOO:bar\r\n")
assertThat(c.getInt(2)).isEqualTo(0)
assertThat(c.getInt(4)).isEqualTo(0)
c.moveToNext()
assertThat(c.getInt(2)).isEqualTo(1)
// The body changes, so its modification stamp does too.
assertThat(c.isNull(3)).isFalse()
c.moveToNext()
assertThat(c.getInt(2)).isEqualTo(0)
c.moveToNext()
assertThat(c.getInt(2)).isEqualTo(0)
c.moveToNext()
assertThat(c.getString(1)).contains("X-APPLE-DEFAULT-ALARM:TRUE")
assertThat(c.getInt(2)).isEqualTo(0)
c.moveToNext()
assertThat(c.getInt(2)).isEqualTo(0)
}
}
}
@Test
fun addsAnEmptyAccountLabel() {
helper.createDatabase(TEST_DB, 3).use { db ->
db.execSQL("INSERT INTO accounts (id, display_name) VALUES (1, 'me@example.org')")
}
helper.runMigrationsAndValidate(TEST_DB, 4, true, TasksDatabase.MIGRATION_3_4).use { db ->
db.query("SELECT display_name, label FROM accounts").use { c ->
assertThat(c.moveToFirst()).isTrue()
assertThat(c.getString(0)).isEqualTo("me@example.org")
assertThat(c.isNull(1)).isTrue()
}
}
}
@Test
fun addsTheAdvancedOccurrencesTable() {
helper.createDatabase(TEST_DB, 4).close()
helper.runMigrationsAndValidate(TEST_DB, 5, true, TasksDatabase.MIGRATION_4_5).use { db ->
db.query("SELECT COUNT(*) FROM advanced_occurrences").use { c ->
assertThat(c.moveToFirst()).isTrue()
assertThat(c.getInt(0)).isEqualTo(0)
}
}
}
@Test
fun addsAnEmptyResetSubtasksRecord() {
helper.createDatabase(TEST_DB, 5).use { db ->
db.execSQL("INSERT INTO task_lists (id, name, color) VALUES (1, 'Personal', 0)")
db.execSQL("INSERT INTO tasks (id, list_id, uid) VALUES (1, 1, 'a'), (2, 1, 'b')")
db.execSQL(
"INSERT INTO advanced_occurrences (copy_id, master_id, anchor, advanced_to, prior_status, spent, from_override) " +
"VALUES (2, 1, 0, 1, 0, 1, 0)",
)
}
helper.runMigrationsAndValidate(TEST_DB, 6, true, TasksDatabase.MIGRATION_5_6).use { db ->
db.query("SELECT reset_subtasks FROM advanced_occurrences").use { c ->
assertThat(c.moveToFirst()).isTrue()
assertThat(c.getString(0)).isEmpty()
}
}
}
@Test
fun keepsExistingTasksAndAddsAnEmptyTableForDeletedOverrides() {
helper.createDatabase(TEST_DB, 6).use { db ->
db.execSQL("INSERT INTO task_lists (id, name, color) VALUES (1, 'Personal', 0)")
db.execSQL("INSERT INTO tasks (id, list_id, uid, dtstart, due, is_all_day) VALUES (1, 1, 'a', 0, 3600000, 0)")
}
helper.runMigrationsAndValidate(TEST_DB, 7, true, TasksDatabase.MIGRATION_6_7).use { db ->
db.query("SELECT untimed, dtstart, due FROM tasks").use { c ->
assertThat(c.moveToFirst()).isTrue()
assertThat(c.isNull(0)).isTrue()
assertThat(c.getLong(1)).isEqualTo(0L)
assertThat(c.getLong(2)).isEqualTo(3_600_000L)
}
db.query("SELECT COUNT(*) FROM advanced_deleted").use { c ->
assertThat(c.moveToFirst()).isTrue()
assertThat(c.getInt(0)).isEqualTo(0)
}
val columns = db.query("SELECT name FROM pragma_table_info('advanced_deleted')").use { c ->
buildList { while (c.moveToNext()) add(c.getString(0)) }
}
assertThat(columns).containsExactly("id", "copy_id", "anchor", "vtodo", "color", "sort_order", "reminders_off", "alarms")
}
}
private companion object {
const val TEST_DB = "migration-test.db"
}
@@ -11,7 +11,7 @@ import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.agendula.data.tasks.ProviderEnvironment
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
import de.jeanlucmakiola.agendula.data.tasks.TaskQuery
import de.jeanlucmakiola.agendula.domain.TaskReminder
import de.jeanlucmakiola.agendula.data.tasks.TaskReminder
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
import de.jeanlucmakiola.agendula.data.tasks.room.AlarmReference
import de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase
@@ -107,17 +107,6 @@ class ExternalImportTest {
assertThat(importer.hasRun.first()).isTrue()
}
@Test
fun copiesTagsCleanedUp() = runBlocking {
source.lists = listOf(list(7, "Errands"))
source.tasks = mapOf(7L to listOf(task(100, "Milk", tags = listOf("Shop", " Shop ", "", "Home"))))
importer.run()
assertThat(db.tasks().tasks(listId = null, includeCompleted = true).single().task.categories)
.containsExactly("Shop", "Home").inOrder()
}
/** Every list arrives device-only: the account belongs to the sync app. */
@Test
fun importedListsAreDeviceOnly() = runBlocking {
@@ -252,7 +241,6 @@ class ExternalImportTest {
title: String,
uid: String? = "uid-$id",
parentId: Long? = null,
tags: List<String> = emptyList(),
) = ExportTask(
taskId = id,
uid = uid,
@@ -272,7 +260,6 @@ class ExternalImportTest {
rrule = null,
rdate = null,
parentId = parentId,
tags = tags,
)
private companion object {
@@ -294,25 +281,23 @@ private class FakeExternalStore : TasksDataSource {
return tasks[listId].orEmpty()
}
override fun reminders(): Map<Long, List<TaskReminder>> = alarms.mapValues { listOf(it.value) }
override fun alarms(): Map<Long, TaskReminder> = alarms
override fun tasks(query: TaskQuery): List<Task> = unused()
override fun task(taskId: Long): Task? = unused()
override fun subtasks(parentTaskId: Long): List<Task> = unused()
override fun insertTask(form: TaskForm, reminders: List<TaskReminder>?): Long = unused()
override fun updateTask(taskId: Long, form: TaskForm, reminders: List<TaskReminder>?) = unused()
override fun updateInstance(taskId: Long, occurrenceStart: Instant, form: TaskForm, reminders: List<TaskReminder>?) =
unused()
override fun insertTask(form: TaskForm): Long = unused()
override fun updateTask(taskId: Long, form: TaskForm) = unused()
override fun updateInstance(taskId: Long, occurrenceStart: Instant, form: TaskForm) = unused()
override fun setAlarm(taskId: Long, minutesBeforeDue: Int?) = unused()
override fun setReminders(taskId: Long, reminders: List<TaskReminder>) = unused()
override fun setCompleted(taskId: Long, completed: Boolean) = unused()
override fun setCompletedInstance(taskId: Long, occurrenceStart: Instant, completed: Boolean) = unused()
override fun deleteTask(taskId: Long) = unused()
override fun setCancelled(taskId: Long, cancelled: Boolean) = unused()
override fun setCancelledInstance(taskId: Long, occurrenceStart: Instant, cancelled: Boolean) = unused()
override fun updateSeries(seriesId: Long, occurrenceStart: Instant, form: TaskForm, reminders: List<TaskReminder>?) =
unused()
override fun splitSeries(seriesId: Long, occurrenceStart: Instant, form: TaskForm, reminders: List<TaskReminder>?): Long =
unused()
override fun updateSeries(seriesId: Long, occurrenceStart: Instant, form: TaskForm) = unused()
override fun splitSeries(seriesId: Long, occurrenceStart: Instant, form: TaskForm): Long = unused()
override fun deleteOccurrence(seriesId: Long, occurrenceStart: Instant) = unused()
override fun deleteFollowing(seriesId: Long, occurrenceStart: Instant) = unused()
override fun createLocalList(name: String, color: Int): Long = unused()
@@ -1,121 +0,0 @@
package de.jeanlucmakiola.agendula.ui
import android.graphics.Insets
import android.view.View
import android.view.WindowInsets
import android.view.WindowInsetsAnimation
import androidx.activity.ComponentActivity
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.WindowInsets as ComposeInsets
import androidx.compose.foundation.layout.ime
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SdkSuppress
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.agendula.ui.theme.AgendulaTheme
import de.jeanlucmakiola.floret.components.FullScreenPicker
import de.jeanlucmakiola.agendula.ui.theme.AgendulaDarkFallback
import de.jeanlucmakiola.agendula.ui.theme.AgendulaLightFallback
import de.jeanlucmakiola.floret.identity.FloretExpressiveTheme
import de.jeanlucmakiola.floret.identity.ImeInsetsResync
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* A keyboard hidden by a predictive back gesture runs an insets animation without a
* duration; Compose then keeps the last keyboard height it saw (#177).
*/
@RunWith(AndroidJUnit4::class)
@SdkSuppress(minSdkVersion = 35)
class ImeInsetsResyncTest {
@get:Rule
val rule = createAndroidComposeRule<ComponentActivity>()
@Volatile
private var imeBottom = -1
@Volatile
private var root: View? = null
@Test
fun themeSettlesKeyboardInsetsAfterUserDrivenAnimation() {
setContent { AgendulaTheme { ImeReader() } }
runUserDrivenKeyboardAnimation()
rule.waitUntil(TIMEOUT_MS) { imeBottom == 0 }
}
@Test
fun pickerSettlesKeyboardInsetsAfterUserDrivenAnimation() {
setContent { FullScreenPicker(title = "", onDismiss = {}) { ImeReader() } }
runUserDrivenKeyboardAnimation()
rule.waitUntil(TIMEOUT_MS) { imeBottom == 0 }
}
@Test
fun themeWithoutResyncLeavesKeyboardInsetsAlone() {
setContent {
FloretExpressiveTheme(AgendulaLightFallback, AgendulaDarkFallback, resyncImeInsets = false) { ImeReader() }
}
runUserDrivenKeyboardAnimation()
assertStaysStale()
}
/** Shows the Compose behaviour [ImeInsetsResync] works around; drop it and this once this fails. */
@Test
fun withoutResyncKeyboardInsetsStayStale() {
setContent { ImeReader() }
runUserDrivenKeyboardAnimation()
assertStaysStale()
}
private fun assertStaysStale() {
val settled = runCatching { rule.waitUntil(STALE_WINDOW_MS) { imeBottom != KEYBOARD_PX } }.isSuccess
assertThat(settled).isFalse()
}
private fun setContent(content: @Composable () -> Unit) {
rule.runOnUiThread { rule.activity.enableEdgeToEdge() }
rule.setContent(content)
rule.waitUntil(TIMEOUT_MS) { root != null }
}
/** Reports the keyboard insets, and the window it sits in, as Compose sees them. */
@Composable
private fun ImeReader() {
val view = LocalView.current
val bottom = ComposeInsets.ime.getBottom(LocalDensity.current)
SideEffect {
imeBottom = bottom
root = view.rootView
}
}
private fun runUserDrivenKeyboardAnimation() {
val ime = WindowInsets.Type.ime()
val animation = WindowInsetsAnimation(ime, null, -1)
val keyboard = Insets.of(0, 0, 0, KEYBOARD_PX)
val decor = checkNotNull(root)
rule.runOnUiThread {
val midway = WindowInsets.Builder().setInsets(ime, keyboard).setVisible(ime, true).build()
decor.dispatchWindowInsetsAnimationPrepare(animation)
decor.dispatchWindowInsetsAnimationStart(animation, WindowInsetsAnimation.Bounds(Insets.NONE, keyboard))
decor.dispatchWindowInsetsAnimationProgress(midway, listOf(animation))
}
rule.waitForIdle()
assertThat(imeBottom).isEqualTo(KEYBOARD_PX)
rule.runOnUiThread { decor.dispatchWindowInsetsAnimationEnd(animation) }
rule.waitForIdle()
}
private companion object {
const val KEYBOARD_PX = 500
const val TIMEOUT_MS = 10_000L
const val STALE_WINDOW_MS = 2_000L
}
}
@@ -1,90 +0,0 @@
package de.jeanlucmakiola.agendula.data.sync
import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.agendula.data.tasks.room.RoomTasksDataSource
import de.jeanlucmakiola.agendula.data.tasks.room.TaskEntity
import de.jeanlucmakiola.agendula.data.tasks.room.TaskListEntity
import de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase
import org.junit.After
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.time.Clock
import kotlin.time.Duration.Companion.seconds
import kotlin.time.Instant
/** A server version replacing a moved series takes the moves' copies with it (#137). */
@RunWith(AndroidJUnit4::class)
class RoomSyncStoreAdvancesTest {
private val db = Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext<Context>(), TasksDatabase::class.java)
.allowMainThreadQueries().build()
@After
fun tearDown() = db.close()
@Test
fun droppingAdvancesDeletesTheirCopies() {
val list = db.taskLists().insert(TaskListEntity(name = "Home", color = 0))
val at = Instant.fromEpochSeconds(Clock.System.now().epochSeconds)
val series = db.tasks().insert(TaskEntity(listId = list, uid = "s", title = "Weekly", dtstart = at, rrule = "FREQ=WEEKLY"))
RoomTasksDataSource(db).setCompletedInstance(series, at, true)
val copy = db.tasks().allIn(list).single { it.id != series }
db.tasks().update(copy.copy(href = "copy.ics"))
RoomSyncStore(db).dropAdvances(series)
assertThat(db.advancedOccurrences().forMaster(series)).isEmpty()
assertThat(db.tasks().entity(copy.id)!!.isDeleted).isTrue()
}
@Test
fun movesTheServerAlreadyHasStay() {
val list = db.taskLists().insert(TaskListEntity(name = "Home", color = 0))
val at = Instant.fromEpochSeconds(Clock.System.now().epochSeconds)
val series = db.tasks().insert(TaskEntity(listId = list, uid = "s", title = "Weekly", dtstart = at, rrule = "FREQ=WEEKLY"))
RoomTasksDataSource(db).setCompletedInstance(series, at, true)
val copy = db.tasks().allIn(list).single { it.id != series }
val store = RoomSyncStore(db)
store.markSynced(listOf(db.tasks().entity(series)!!), "s.ics", "1")
store.dropAdvances(series)
assertThat(db.tasks().entity(copy.id)!!.isDeleted).isFalse()
}
@Test
fun aCopyGivenASubtaskSurvivesTheServerWinning() {
val list = db.taskLists().insert(TaskListEntity(name = "Home", color = 0))
val at = Instant.fromEpochSeconds(Clock.System.now().epochSeconds)
val series = db.tasks().insert(TaskEntity(listId = list, uid = "s", title = "Weekly", dtstart = at, rrule = "FREQ=WEEKLY"))
RoomTasksDataSource(db).setCompletedInstance(series, at, true)
val copy = db.tasks().allIn(list).single { it.id != series }
db.tasks().insert(TaskEntity(listId = list, uid = "p", title = "Part", parentId = copy.id))
RoomSyncStore(db).dropAdvances(series)
assertThat(db.tasks().entity(copy.id)).isNotNull()
assertThat(db.tasks().entity(copy.id)!!.isDeleted).isFalse()
}
@Test
fun aTickDuringTheUploadIsNotSettled() {
val list = db.taskLists().insert(TaskListEntity(name = "Home", color = 0))
val at = Instant.fromEpochSeconds(Clock.System.now().epochSeconds)
val series = db.tasks().insert(
TaskEntity(listId = list, uid = "s", title = "Weekly", dtstart = at, rrule = "FREQ=WEEKLY", lastModified = at - 1.seconds),
)
val uploaded = db.tasks().entity(series)!!
RoomTasksDataSource(db).setCompletedInstance(series, at, true)
val store = RoomSyncStore(db)
store.markSynced(listOf(uploaded), "s.ics", "1")
assertThat(db.tasks().entity(series)!!.isDirty).isTrue()
assertThat(db.advancedOccurrences().forMaster(series).single().settled).isFalse()
}
}
-88
View File
@@ -1,88 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- CalDAV sync and UnifiedPush; everything here needs the network. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- CalDAV sync. ACCESS_NETWORK_STATE is merged in by work-runtime anyway,
but it shows in F-Droid's permission diff, so declare it deliberately
rather than letting it appear from nowhere.
READ_SYNC_SETTINGS / WRITE_SYNC_SETTINGS are what the ContentResolver
sync APIs need. No FOREGROUND_SERVICE: sync is a plain worker, and the
dataSync FGS type would bring the Android 15 six-hours-per-24 budget
(whose failure mode is a fatal RemoteServiceException) and a Play
requirement for a video demo.
Two more permissions appear in the merged manifest without being
declared here, and both come from work-runtime: WAKE_LOCK, and
FOREGROUND_SERVICE. The latter is not us taking the FGS route — below
API 31 WorkManager implements expedited work with a foreground service,
and minSdk is 29, so it is load-bearing for the "Sync now" button.
Removing it with tools:node="remove" would break expedited work on
exactly the older devices that need it most. Noted because it shows in
F-Droid's permission diff and would otherwise look unexplained. -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<queries>
<!-- Custom Tabs provider detection. Without this entry it silently finds
nothing on API 30+, and the Nextcloud login flow falls back to an
external browser for no visible reason. -->
<intent>
<action android:name="android.support.customtabs.action.CustomTabsService" />
</intent>
</queries>
<application android:networkSecurityConfig="@xml/network_security_config">
<!-- Sync plumbing. The stub provider exists only to give the sync
adapter an authority to register against: Agendula publishes no real
ContentProvider since :provider was deleted, and without an authority
ContentService.hasAuthorityAccess() makes every ContentResolver sync
call a silent no-op at targetSdk >= 34. -->
<provider
android:name=".data.sync.SyncStubProvider"
android:authorities="${applicationId}.sync"
android:exported="false"
android:syncable="true" />
<!-- Exported and guarded by ACCOUNT_MANAGER. Note that
android.permission.ACCOUNT_AUTHENTICATOR does not exist. -->
<service
android:name=".data.sync.AuthenticatorService"
android:exported="true"
android:permission="android.permission.ACCOUNT_MANAGER">
<intent-filter>
<action android:name="android.accounts.AccountAuthenticator" />
</intent-filter>
<meta-data
android:name="android.accounts.AccountAuthenticator"
android:resource="@xml/authenticator" />
</service>
<service
android:name=".data.sync.SyncAdapterService"
android:exported="true"
android:permission="android.permission.BIND_SYNC_ADAPTER">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="@xml/sync_adapter" />
</service>
<!-- UnifiedPush: the connector binds this to deliver endpoints and
WebDAV-Push messages. Not exported; the connector's own receiver is
what distributors talk to. -->
<service
android:name=".data.sync.push.AgendulaPushService"
android:exported="false">
<intent-filter>
<action android:name="org.unifiedpush.android.connector.PUSH_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
@@ -1,138 +0,0 @@
package de.jeanlucmakiola.agendula.data.di
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStore
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import dagger.multibindings.IntoSet
import de.jeanlucmakiola.agendula.data.sync.AccountCreator
import de.jeanlucmakiola.agendula.data.sync.AccountRepository
import de.jeanlucmakiola.agendula.data.sync.AccountSyncRequests
import de.jeanlucmakiola.agendula.data.sync.CalDavGateway
import de.jeanlucmakiola.agendula.data.sync.LoginFlowRecord
import de.jeanlucmakiola.agendula.data.sync.ManualSync
import de.jeanlucmakiola.agendula.data.sync.OkHttpCalDavGateway
import de.jeanlucmakiola.agendula.data.sync.PendingLoginFlowStore
import de.jeanlucmakiola.agendula.data.sync.PullSync
import de.jeanlucmakiola.agendula.data.sync.RemoteListRepository
import de.jeanlucmakiola.agendula.data.sync.RemoteLists
import de.jeanlucmakiola.agendula.data.sync.SyncNoticeNotifier
import de.jeanlucmakiola.agendula.data.sync.SyncOnEdit
import de.jeanlucmakiola.agendula.data.sync.SyncRequests
import de.jeanlucmakiola.agendula.data.sync.SyncTrigger
import de.jeanlucmakiola.agendula.data.sync.push.PushRegistrar
import de.jeanlucmakiola.agendula.data.tasks.room.LocalWriteListener
import javax.inject.Provider
import javax.inject.Singleton
/** See [CredentialsDataStore] for why this is a separate file. */
private val Context.credentialsDataStore: DataStore<Preferences> by preferencesDataStore(
name = CREDENTIALS_DATASTORE,
corruptionHandler = replaceCorrupted(),
)
/** See [SyncStateDataStore] for why this is a separate file. */
private val Context.syncStateDataStore: DataStore<Preferences> by preferencesDataStore(
name = SYNC_STATE_DATASTORE,
corruptionHandler = replaceCorrupted(),
)
/**
* Named here and in `backup_rules.xml` / `data_extraction_rules.xml`, which
* exclude `datastore/$CREDENTIALS_DATASTORE.preferences_pb` by this name.
*/
const val CREDENTIALS_DATASTORE = "agendula_credentials"
/**
* Named here and in `backup_rules.xml` / `data_extraction_rules.xml`, which
* exclude `datastore/$SYNC_STATE_DATASTORE.preferences_pb` by this name.
*/
const val SYNC_STATE_DATASTORE = "agendula_sync_state"
/** CalDAV sync: the `full` flavor's side of the seams `main` declares. */
@Module
@InstallIn(SingletonComponent::class)
abstract class SyncBindModule {
@Binds
@Singleton
abstract fun bindCalDavGateway(impl: OkHttpCalDavGateway): CalDavGateway
@Binds
@Singleton
abstract fun bindAccountCreator(impl: AccountRepository): AccountCreator
@Binds
@Singleton
abstract fun bindLoginFlowRecord(impl: PendingLoginFlowStore): LoginFlowRecord
@Binds
@Singleton
abstract fun bindLocalWriteListener(impl: SyncOnEdit): LocalWriteListener
@Binds
@Singleton
abstract fun bindRemoteLists(impl: RemoteListRepository): RemoteLists
@Binds
@Singleton
abstract fun bindSyncRequests(impl: AccountSyncRequests): SyncRequests
@Binds
@Singleton
abstract fun bindManualSync(impl: PullSync): ManualSync
@Binds
@IntoSet
abstract fun bindSyncNoticeChannel(impl: SyncNoticeNotifier): ChannelRefresher
}
@Module
@InstallIn(SingletonComponent::class)
object SyncProvideModule {
@Provides
@Singleton
@CredentialsDataStore
fun provideCredentialsDataStore(@ApplicationContext context: Context): DataStore<Preferences> =
context.credentialsDataStore
@Provides
@Singleton
@SyncStateDataStore
fun provideSyncStateDataStore(@ApplicationContext context: Context): DataStore<Preferences> =
context.syncStateDataStore
/**
* Sync hard on app open: the periodic worker's interval is a floor, and in
* the `rare` and `restricted` App Standby buckets it may not have run at
* all. `KEEP` makes rescheduling idempotent, so this also repairs a schedule
* lost to "clear app data" or to a restore.
*/
@Provides
@IntoSet
fun syncOnOpenHook(
accounts: Provider<AccountRepository>,
syncTrigger: Provider<SyncTrigger>,
pendingLoginFlows: Provider<PendingLoginFlowStore>,
push: Provider<PushRegistrar>,
): LaunchHook = LaunchHook {
runCatching {
accounts.get().rescheduleAll()
accounts.get().syncable().forEach { syncTrigger.get().enqueue(it.displayName) }
// A login flow the previous process died in the middle of.
// Its password, if the user approved, exists nowhere else.
pendingLoginFlows.get().reclaim()
}
// Last and on its own: it waits on the network, and must not hold up
// the reclaim above. Re-registering on open is what the connector
// recommends.
runCatching { push.get().updateAll() }
}
}
@@ -1,34 +0,0 @@
package de.jeanlucmakiola.agendula.data.di
import javax.inject.Qualifier
/**
* Marks the DataStore holding **only** the Keystore-encrypted app passwords.
*
* A separate file from `agendula_prefs` on purpose: Auto Backup includes
* `datastore/`, and a restored ciphertext is permanently undecryptable because
* Keystore keys are non-exportable. Its own file is what lets the backup rules
* exclude the credentials and nothing else — excluding the whole database or
* all of DataStore would trade a latent bug for a live one.
*/
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class CredentialsDataStore
/**
* Marks the DataStore holding per-device **sync bookkeeping** — the quarantine
* counters and the full-reconciliation clock.
*
* Its own file for the same reason the credentials have one: Auto Backup
* includes `datastore/`, and every value in here is a statement about *this*
* device's conversation with a server. Restored onto a new install they are all
* lies, and two of them are dangerous — a restored "reconciled recently" makes
* the engine trust a sync token for another day, which is precisely the silently
* pruned change log the full path exists to catch, and a restored quarantine
* count silently skips resources that were never tried here.
*
* Not user data, so nothing is lost by excluding it.
*/
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class SyncStateDataStore
@@ -1,20 +0,0 @@
package de.jeanlucmakiola.agendula.data.sync
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
import de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
import javax.inject.Inject
/** [SyncRequests] by account id; [SyncTrigger] keys on the account's stable display name. */
class AccountSyncRequests @Inject constructor(
private val database: TasksDatabase,
private val trigger: SyncTrigger,
@IoDispatcher private val io: CoroutineDispatcher,
) : SyncRequests {
override suspend fun syncNow(accountId: Long) {
val name = withContext(io) { database.accounts().account(accountId)?.displayName } ?: return
trigger.enqueue(name)
}
}
@@ -1,76 +0,0 @@
package de.jeanlucmakiola.agendula.data.sync
import android.content.Context
import androidx.work.WorkInfo
import androidx.work.WorkManager
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.agendula.data.di.ApplicationScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
/**
* Pull to sync over [SyncTrigger]: an expedited sync per account, and
* [syncing] held until they finish.
*
* A sync waiting on its network constraint never starts, so if none is running
* after [START_GRACE] the indicator lets go; the work stays queued and runs
* once the device is back online.
*/
@Singleton
class PullSync @Inject constructor(
@ApplicationContext private val context: Context,
private val accounts: AccountRepository,
private val trigger: SyncTrigger,
availability: SyncAvailability,
@ApplicationScope private val scope: CoroutineScope,
) : ManualSync {
override val available: Flow<Boolean> =
combine(availability.observe(), accounts.observeAll()) { usable, all -> usable && all.isNotEmpty() }
private val _syncing = MutableStateFlow(false)
override val syncing: StateFlow<Boolean> = _syncing
override fun syncAll() {
if (_syncing.value) return
_syncing.value = true
scope.launch {
try {
val names = accounts.syncable().map { trigger.enqueue(it.displayName, expedited = true) }
if (names.isNotEmpty()) awaitSyncs(names)
} finally {
_syncing.value = false
}
}
}
private suspend fun awaitSyncs(names: List<String>) {
val workManager = WorkManager.getInstance(context)
val states = combine(names.map { workManager.getWorkInfosForUniqueWorkFlow(it) }) { infos ->
infos.flatMap { it }.map { it.state }
}
withTimeoutOrNull(MAX_WAIT) {
val started = withTimeoutOrNull(START_GRACE) {
states.first { all -> WorkInfo.State.RUNNING in all || all.all { it.isFinished } }
} ?: return@withTimeoutOrNull
if (started.all { it.isFinished }) return@withTimeoutOrNull
states.map { all -> WorkInfo.State.RUNNING in all }.first { running -> !running }
}
}
private companion object {
val START_GRACE = 3.seconds
val MAX_WAIT = 2.minutes
}
}
@@ -1,44 +0,0 @@
package de.jeanlucmakiola.agendula.data.sync
import androidx.datastore.preferences.core.MutablePreferences
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.stringSetPreferencesKey
import androidx.lifecycle.SavedStateHandle
import de.jeanlucmakiola.caldav.ServerTrust
/**
* The one mapping between a [ServerTrust] and the key-value stores it is kept
* in, so a field added to it cannot be dropped by one of them.
*/
class ServerTrustKeys(private val certificatesName: String, private val cleartextName: String) {
private val certificates = stringSetPreferencesKey(certificatesName)
private val cleartext = booleanPreferencesKey(cleartextName)
fun read(prefs: Preferences) = ServerTrust(
pinnedCertificates = prefs[certificates].orEmpty(),
allowCleartext = prefs[cleartext] ?: false,
)
fun write(prefs: MutablePreferences, trust: ServerTrust) {
if (trust.pinnedCertificates.isEmpty()) {
prefs.remove(certificates)
} else {
prefs[certificates] = trust.pinnedCertificates
}
if (trust.allowCleartext) prefs[cleartext] = true else prefs.remove(cleartext)
}
fun remove(prefs: MutablePreferences) = write(prefs, ServerTrust.DEFAULT)
fun read(handle: SavedStateHandle) = ServerTrust(
pinnedCertificates = handle.get<ArrayList<String>>(certificatesName).orEmpty().toSet(),
allowCleartext = handle[cleartextName] ?: false,
)
fun write(handle: SavedStateHandle, trust: ServerTrust) {
handle[certificatesName] = ArrayList(trust.pinnedCertificates)
handle[cleartextName] = trust.allowCleartext
}
}
@@ -1,38 +0,0 @@
package de.jeanlucmakiola.agendula.data.sync
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import de.jeanlucmakiola.agendula.data.di.SyncStateDataStore
import de.jeanlucmakiola.caldav.ServerTrust
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton
/** What each account's user agreed to trust: pinned certificates and plain http. */
@Singleton
class ServerTrustStore @Inject constructor(
@SyncStateDataStore private val dataStore: DataStore<Preferences>,
) {
suspend fun get(accountId: Long): ServerTrust = read(dataStore.data.first(), accountId)
fun observe(accountId: Long): Flow<ServerTrust> =
dataStore.data.map { read(it, accountId) }.distinctUntilChanged()
suspend fun put(accountId: Long, trust: ServerTrust) {
dataStore.edit { keys(accountId).write(it, trust) }
}
suspend fun forget(accountId: Long) {
dataStore.edit { keys(accountId).remove(it) }
}
private fun read(prefs: Preferences, accountId: Long) = keys(accountId).read(prefs)
private fun keys(accountId: Long) =
ServerTrustKeys("server_trust_certs_$accountId", "server_trust_cleartext_$accountId")
}
@@ -1,166 +0,0 @@
package de.jeanlucmakiola.agendula.data.sync
import de.jeanlucmakiola.agendula.data.tasks.room.TaskAlarmEntity
import de.jeanlucmakiola.agendula.data.tasks.room.TaskEntity
import de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase
import de.jeanlucmakiola.agendula.data.tasks.room.recurrenceAnchor
import de.jeanlucmakiola.agendula.data.tasks.wholeSecond
import kotlin.time.Duration.Companion.seconds
import javax.inject.Inject
/**
* The database, as [CollectionSyncer] needs it.
*
* A seam, and the reason is the same one that put [CalDavGateway] in front of
* discovery: the reconciliation above this interface is where local edits are
* discarded, tombstones swept and conflicts resolved, and every one of those is
* a decision that should be provable without a device. Room's test double is
* Robolectric plus an in-memory database; this is a dozen methods.
*/
interface SyncStore {
/** Every row in a list, **tombstones included**. */
fun rowsIn(listId: Long): List<TaskEntity>
fun update(row: TaskEntity)
/** The reminders of [taskIds] — one resource's rows — by task id, for the body that uploads them. */
fun alarmsFor(taskIds: List<Long>): Map<Long, List<TaskAlarmEntity>>
/**
* Writes a downloaded row — inserted when its id is 0 — and makes its
* reminders exactly [alarms], in one transaction.
*
* ⚠️ One transaction, not an [update] and a second call. The row lands clean
* with the server's ETag, so if the process died between the two, nothing
* would ever download it again and the reminders would stay stale for good.
*
* A row that is gone by the time it is written — deleted on the device
* while the sync ran — stays gone, reminders and all.
*
* @return the row's id.
*/
fun upsertWithAlarms(row: TaskEntity, alarms: List<TaskAlarmEntity>): Long
fun deleteAll(taskIds: List<Long>)
/**
* Forgets how ticking occurrences moved [masterId]'s series, and deletes the
* copies that left: the server's version replaced the moved series, and its
* own overrides stand for those occurrences again. A row given a life of its
* own since stays.
*/
fun dropAdvances(masterId: Long) = Unit
/**
* Records href and ETag on a resource's [rows], as they were serialised,
* clearing `is_dirty` on those that did not change since.
*
* The caller excludes any row it left out of the body — that row is deleted,
* not marked synced.
*/
fun markSynced(rows: List<TaskEntity>, href: String?, eTag: String?)
fun setParent(taskId: Long, parentId: Long?)
/** The master row for a UID — the one with no `RECURRENCE-ID`. */
fun masterByUid(listId: Long, uid: String): TaskEntity?
fun row(taskId: Long): TaskEntity?
/**
* One column, deliberately. A whole-entity update would carry the row as it
* looked when the sync started and revert anything the user changed while it
* ran.
*/
fun setListReadOnly(listId: Long, readOnly: Boolean)
/** The RFC 6578 cursor. Null resets the collection to a full reconciliation. */
fun setSyncToken(listId: Long, token: String?)
}
class RoomSyncStore @Inject constructor(
private val database: TasksDatabase,
) : SyncStore {
override fun rowsIn(listId: Long) = database.tasks().allIn(listId)
override fun update(row: TaskEntity) {
database.tasks().update(row)
}
override fun alarmsFor(taskIds: List<Long>) =
if (taskIds.isEmpty()) emptyMap() else database.alarms().forTasks(taskIds).groupBy { it.taskId }
override fun upsertWithAlarms(row: TaskEntity, alarms: List<TaskAlarmEntity>): Long =
database.runInTransaction<Long> {
if (row.id == 0L) {
database.tasks().insert(row).also { database.alarms().replaceFromServer(it, alarms) }
} else {
// ⚠️ Zero rows means the row was deleted under us. Its alarms
// would then name a task that does not exist, and the foreign
// key would fail the whole transaction.
if (database.tasks().update(row) > 0) database.alarms().replaceFromServer(row.id, alarms)
row.id
}
}
override fun deleteAll(taskIds: List<Long>) {
if (taskIds.isNotEmpty()) database.tasks().deleteAll(taskIds)
}
override fun dropAdvances(masterId: Long) = database.runInTransaction {
val advanced = database.advancedOccurrences()
val tasks = database.tasks()
val master = tasks.entity(masterId)
// Only moves the server never saw, on copies that are still just that.
advanced.forMaster(masterId).filter { !it.settled && it.undoable }.forEach { record ->
// An edited detached row was unlinked already, so only untouched ones are named.
val rows = advanced.detachedFor(record.copyId).mapNotNull { it.taskId } + record.copyId
advanced.delete(record.copyId)
rows.mapNotNull { tasks.entity(it) }
.filter { row ->
!row.isDeleted && tasks.subtasks(row.id).isEmpty() &&
(master == null || row.listId == master.listId && row.parentId == master.parentId)
}
.forEach { row ->
// Never uploaded: nobody to tell. Uploaded: a tombstone the next run deletes.
if (row.href == null) tasks.delete(row.id)
else tasks.update(row.copy(isDeleted = true, isDirty = true))
}
}
}
override fun markSynced(rows: List<TaskEntity>, href: String?, eTag: String?) {
if (rows.isEmpty()) return
database.runInTransaction {
database.tasks().markSynced(rows.map { it.id }, href, eTag)
rows.forEach { database.tasks().raiseSequence(it.id, it.sequence) }
// Changed while the body was on its way, by a tick or an edit: still owed to the server.
rows.forEach { database.tasks().dirtyIfChangedSince(it.id, it.lastModified) }
// The server now holds each series as far as the body moved it; a tick
// since is still the device's own.
rows.filter { it.recurrenceId == null }.forEach { row ->
val anchor = row.recurrenceAnchor
if (anchor == null) database.advancedOccurrences().settle(listOf(row.id))
else database.advancedOccurrences().settleUpTo(row.id, wholeSecond(anchor) + 1.seconds)
}
}
}
override fun setParent(taskId: Long, parentId: Long?) {
database.tasks().setParent(taskId, parentId)
}
override fun masterByUid(listId: Long, uid: String) = database.tasks().byUid(listId, uid)
override fun row(taskId: Long) = database.tasks().entity(taskId)
override fun setListReadOnly(listId: Long, readOnly: Boolean) {
database.taskLists().setReadOnly(listId, readOnly)
}
override fun setSyncToken(listId: Long, token: String?) {
database.taskLists().setSyncToken(listId, token)
}
}
@@ -1,103 +0,0 @@
package de.jeanlucmakiola.agendula.data.sync
import android.net.DnsResolver as PlatformDnsResolver
import android.os.CancellationSignal
import android.os.Looper
import de.jeanlucmakiola.caldav.DnsAnswers
import de.jeanlucmakiola.caldav.DnsRecords
import de.jeanlucmakiola.caldav.DnsResolver
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
/**
* SRV/TXT lookups through the system resolver, so discovery uses the current
* network's DNS and honours Private DNS rather than sending plain queries of
* its own. A failed or timed-out lookup reads as no records.
*
* The platform delivers answers through the main looper, so this must run on a
* worker thread; waiting on the main one would deadlock until the timeout.
* The wait gives up as soon as [isCancelled] says so, and answered lookups are
* kept briefly so the authenticated walk does not ask again.
*/
class SystemDnsResolver(
private val isCancelled: () -> Boolean = { false },
) : DnsResolver {
override fun lookup(name: String): DnsRecords {
check(!Looper.getMainLooper().isCurrentThread) { "DNS lookup on the main thread" }
val now = System.nanoTime()
cache[name]?.takeIf { now - it.at < CACHE_NANOS }?.let { return it.records }
val srv = Query(name, DnsAnswers.TYPE_SRV)
val txt = Query(name, DnsAnswers.TYPE_TXT)
val answered = try {
val deadline = now + TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS)
srv.await(deadline, isCancelled) && txt.await(deadline, isCancelled)
} finally {
srv.cancel()
txt.cancel()
}
val records = DnsRecords(
srv.answer()?.let(DnsAnswers::srv).orEmpty(),
txt.answer()?.let(DnsAnswers::txt).orEmpty(),
)
if (answered) cache[name] = Cached(now, records)
return records
}
private class Cached(val at: Long, val records: DnsRecords)
private class Query(name: String, type: Int) {
private val done = CountDownLatch(1)
private val signal = CancellationSignal()
private val result = AtomicReference<ByteArray?>()
init {
try {
PlatformDnsResolver.getInstance().rawQuery(
null,
name,
PlatformDnsResolver.CLASS_IN,
type,
PlatformDnsResolver.FLAG_EMPTY,
Runnable::run,
signal,
object : PlatformDnsResolver.Callback<ByteArray> {
override fun onAnswer(answer: ByteArray, rcode: Int) {
result.set(answer)
done.countDown()
}
override fun onError(error: PlatformDnsResolver.DnsException) {
done.countDown()
}
},
)
} catch (e: RuntimeException) {
done.countDown()
}
}
/** Whether the query finished before [deadline] and before [isCancelled]. */
fun await(deadline: Long, isCancelled: () -> Boolean): Boolean {
while (!isCancelled()) {
val left = deadline - System.nanoTime()
if (left <= 0) return false
if (done.await(minOf(left, SLICE_NANOS), TimeUnit.NANOSECONDS)) return true
}
return false
}
fun cancel() = signal.cancel()
fun answer(): ByteArray? = result.get()
}
private companion object {
const val TIMEOUT_SECONDS = 10L
val SLICE_NANOS = TimeUnit.MILLISECONDS.toNanos(100)
val CACHE_NANOS = TimeUnit.MINUTES.toNanos(1)
val cache = ConcurrentHashMap<String, Cached>()
}
}
@@ -1,76 +0,0 @@
package de.jeanlucmakiola.agendula.ui.accounts.add
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Badge
import androidx.compose.material.icons.rounded.Event
import androidx.compose.material.icons.rounded.Fingerprint
import androidx.compose.material.icons.rounded.LockOpen
import androidx.compose.material.icons.rounded.Verified
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import de.jeanlucmakiola.agendula.R
import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.Position
import de.jeanlucmakiola.floret.components.positionOf
import java.text.DateFormat
import java.util.Date
/** The typed address is plain http: what that exposes, before anything is sent. */
@Composable
internal fun ConfirmCleartextStep(step: AddAccountStep.ConfirmCleartext) {
GroupedRow(
title = step.address,
position = Position.Alone,
leading = { Icon(Icons.Rounded.LockOpen, contentDescription = null) },
)
Spacer(Modifier.height(16.dp))
QuirkNote(text = stringResource(R.string.add_account_cleartext_note))
}
/**
* A certificate the phone does not trust, laid out for comparing against the
* server's own. The fingerprint is the part that matters, so it comes first and
* can be selected.
*/
@Composable
internal fun TrustCertificateStep(step: AddAccountStep.TrustCertificate) {
val certificate = step.certificate
val locale = LocalConfiguration.current.locales[0]
val expires = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(Date(certificate.notAfterMillis))
val rows = listOf(
Triple(Icons.Rounded.Fingerprint, R.string.add_account_certificate_fingerprint, certificate.displayFingerprint),
Triple(Icons.Rounded.Badge, R.string.add_account_certificate_subject, certificate.subject),
Triple(Icons.Rounded.Verified, R.string.add_account_certificate_issuer, certificate.issuer),
Triple(Icons.Rounded.Event, R.string.add_account_certificate_expires, expires),
)
SelectionContainer {
Column {
rows.forEachIndexed { index, (icon, title, value) ->
GroupedRow(
title = AnnotatedString(stringResource(title)),
summary = if (index == 0) {
buildAnnotatedString { withStyle(SpanStyle(fontFamily = FontFamily.Monospace)) { append(value) } }
} else {
AnnotatedString(value)
},
position = positionOf(index, rows.size),
leading = { Icon(icon, contentDescription = null) },
)
}
}
}
Spacer(Modifier.height(16.dp))
}
@@ -1,35 +0,0 @@
package de.jeanlucmakiola.agendula.ui.onboarding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import de.jeanlucmakiola.agendula.ui.accounts.add.ADD_ACCOUNT_STEPS
import de.jeanlucmakiola.agendula.ui.accounts.add.AddAccountScreen
import de.jeanlucmakiola.agendula.ui.accounts.add.AddAccountViewModel
/** The inline wizard's shortest length, before a provider is picked. */
internal const val ACCOUNT_STEP_SLOTS = ADD_ACCOUNT_STEPS
/** [OnboardingStep.Account]: the add-account wizard, given the whole screen. */
@Composable
internal fun AccountStep(state: OnboardingUiState, viewModel: OnboardingViewModel) {
// The same instance the wizard resolves for itself, so its length can be
// read here without keeping a second copy of its state.
val account: AddAccountViewModel = hiltViewModel()
val accountState by account.state.collectAsStateWithLifecycle()
// ⚠️ The wizard grows a step for a provider that needs an app password
// minted first, and the outer bar has to grow with it — otherwise first
// run counts one flow while the screen inside it counts another.
LaunchedEffect(accountState.totalSteps) {
viewModel.onAccountStepsChanged(accountState.totalSteps)
}
AddAccountScreen(
onDone = { viewModel.onAccountFinished(added = true) },
onBack = { viewModel.onAccountFinished(added = false) },
stepOffset = state.position - 1,
totalSteps = state.total,
viewModel = account,
)
}
@@ -1,81 +0,0 @@
package de.jeanlucmakiola.agendula.ui.settings
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import de.jeanlucmakiola.agendula.data.tasks.room.AccountEntity
import de.jeanlucmakiola.agendula.ui.accounts.AccountDetailScreen
import de.jeanlucmakiola.agendula.ui.accounts.AccountsScreen
import de.jeanlucmakiola.agendula.ui.accounts.AccountsViewModel
import de.jeanlucmakiola.agendula.ui.accounts.add.AddAccountScreen
import de.jeanlucmakiola.agendula.ui.accounts.add.AddAccountViewModel
/** Settings → Accounts and the screens under it, layered over the hub. */
@Composable
internal fun AccountSections(
section: SettingsSection?,
initialAccountId: Long?,
onSection: (SettingsSection?) -> Unit,
) {
// Hoisted so the add flow can refresh the list it returns to.
val accountsViewModel: AccountsViewModel = hiltViewModel()
// Shared with the add flow's own lookup, so "sign in again" can prefill it.
val addAccountViewModel: AddAccountViewModel = hiltViewModel()
val signInAgain: (AccountEntity) -> Unit = { account ->
addAccountViewModel.startReauthentication(account.id, account.principalUrl, account.username)
onSection(SettingsSection.AddAccount)
}
// Which account the detail screen is showing; the section alone cannot say.
var openAccount by rememberSaveable(initialAccountId) { mutableStateOf(initialAccountId) }
// Accounts stays composed under Add account, for the same reason Backup
// stays composed under export and import: the deeper screen slides over it.
val accountsOpen = section == SettingsSection.Accounts ||
section?.parent == SettingsSection.Accounts
SlideInSection(visible = accountsOpen) {
AccountsScreen(
onAddAccount = {
// A sign-in abandoned half-way must not turn this into one.
if (addAccountViewModel.state.value.reauthenticating) addAccountViewModel.onStartOver()
onSection(SettingsSection.AddAccount)
},
onSignInAgain = signInAgain,
onOpenAccount = {
openAccount = it
onSection(SettingsSection.Account)
},
onOpenStorage = { onSection(SettingsSection.Storage) },
onBack = { onSection(null) },
viewModel = accountsViewModel,
visible = accountsOpen,
)
}
val accountOpen = section == SettingsSection.Account
SlideInSection(visible = accountOpen) {
openAccount?.let { id ->
AccountDetailScreen(
accountId = id,
onBack = { onSection(SettingsSection.Accounts) },
onRemoved = { onSection(SettingsSection.Accounts) },
onSignInAgain = signInAgain,
onOpenStorage = { onSection(SettingsSection.Storage) },
viewModel = accountsViewModel,
visible = accountOpen,
)
}
}
SlideInSection(visible = section == SettingsSection.AddAccount) {
AddAccountScreen(
// The list stays composed underneath, so nothing re-runs its
// init and OnResume never fires on a section change. It no longer
// needs to: the accounts come from an observed query, so a new
// account — and every later sync — arrives on its own.
onDone = { onSection(SettingsSection.Accounts) },
onBack = { onSection(SettingsSection.Accounts) },
viewModel = addAccountViewModel,
)
}
}
+80 -102
View File
@@ -9,25 +9,35 @@
selected External mode. Both are dangerous-level.
StorageMode.OWN needs nothing here: it is a Room database in our own data
directory. -->
directory. Agendula publishes no ContentProvider and declares no
permissions of its own. -->
<uses-permission android:name="org.dmfs.permission.READ_TASKS" />
<uses-permission android:name="org.dmfs.permission.WRITE_TASKS" />
<uses-permission android:name="org.tasks.permission.READ_TASKS" />
<uses-permission android:name="org.tasks.permission.WRITE_TASKS" />
<!-- What another app requests to read or write the own store through
AgendulaTaskProvider. Dangerous, like OpenTasks' own: the user grants
them per app. Suffixed per build, so debug and release can coexist. -->
<permission
android:name="${applicationId}.permission.READ_TASKS"
android:description="@string/permission_read_tasks_description"
android:label="@string/permission_read_tasks_label"
android:protectionLevel="dangerous" />
<permission
android:name="${applicationId}.permission.WRITE_TASKS"
android:description="@string/permission_write_tasks_description"
android:label="@string/permission_write_tasks_label"
android:protectionLevel="dangerous" />
<!-- CalDAV sync. ACCESS_NETWORK_STATE is merged in by work-runtime anyway,
but it shows in F-Droid's permission diff, so declare it deliberately
rather than letting it appear from nowhere.
READ_SYNC_SETTINGS / WRITE_SYNC_SETTINGS are what the ContentResolver
sync APIs need. No FOREGROUND_SERVICE: sync is a plain worker, and the
dataSync FGS type would bring the Android 15 six-hours-per-24 budget
(whose failure mode is a fatal RemoteServiceException) and a Play
requirement for a video demo.
Two more permissions appear in the merged manifest without being
declared here, and both come from work-runtime: WAKE_LOCK, and
FOREGROUND_SERVICE. The latter is not us taking the FGS route — below
API 31 WorkManager implements expedited work with a foreground service,
and minSdk is 29, so it is load-bearing for the "Sync now" button.
Removing it with tools:node="remove" would break expedited work on
exactly the older devices that need it most. Noted because it shows in
F-Droid's permission diff and would otherwise look unexplained. -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
@@ -45,17 +55,23 @@
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent>
<!-- Custom Tabs provider detection. Without this entry it silently finds
nothing on API 30+, and the Nextcloud login flow falls back to an
external browser for no visible reason. -->
<intent>
<action android:name="android.support.customtabs.action.CustomTabsService" />
</intent>
</queries>
<application
android:name=".AgendulaApp"
android:allowBackup="true"
android:enableOnBackInvokedCallback="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:localeConfig="@xml/locales_config"
android:networkSecurityConfig="@xml/network_security_config"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Agendula"
@@ -65,8 +81,10 @@
android:exported="true"
android:launchMode="singleTop"
android:windowSoftInputMode="adjustResize">
<!-- MAIN/LAUNCHER lives on the two aliases below, so the launcher
name can be switched at runtime (#104). -->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- Shared text becomes a new task's title. -->
<intent-filter>
<action android:name="android.intent.action.SEND" />
@@ -87,32 +105,6 @@
<data android:mimeType="text/calendar" />
</intent-filter>
</activity>
<activity-alias
android:name=".DefaultNameAlias"
android:enabled="true"
android:exported="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:targetActivity=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias
android:name=".TasksNameAlias"
android:enabled="false"
android:exported="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name_tasks_alias"
android:roundIcon="@mipmap/ic_launcher_round"
android:targetActivity=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<!-- Quick Settings "New task" tile. Only the system QS host can bind it. -->
<service
@@ -193,58 +185,6 @@
android:resource="@xml/appwidget_info_tasks" />
</receiver>
<!-- "Today" home-screen widget (Glance): a progress ring for today's tasks. -->
<receiver
android:name=".widget.TodayWidgetReceiver"
android:label="@string/widget_today_label"
android:exported="true">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/appwidget_info_today" />
</receiver>
<!-- "Up next" home-screen widget (Glance): the single nearest due task. -->
<receiver
android:name=".widget.UpNextWidgetReceiver"
android:label="@string/widget_up_next_label"
android:exported="true">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/appwidget_info_up_next" />
</receiver>
<!-- "Lists" home-screen widget (Glance): one shortcut tile per list. -->
<receiver
android:name=".widget.ListsWidgetReceiver"
android:label="@string/widget_lists_label"
android:exported="true">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/appwidget_info_lists" />
</receiver>
<!-- "Week" home-screen widget (Glance): a seven-day strip of task counts. -->
<receiver
android:name=".widget.WeekWidgetReceiver"
android:label="@string/widget_week_label"
android:exported="true">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/appwidget_info_week" />
</receiver>
<!-- Per-widget list picker, launched by the host on placement / reconfigure. -->
<activity
android:name=".widget.TaskWidgetConfigActivity"
@@ -271,15 +211,53 @@
</intent-filter>
</receiver>
<!-- The own store under the OpenTasks contract. Empty, and refusing
writes, while External mode is active. -->
<!-- Sync plumbing. The stub provider exists only to give the sync
adapter an authority to register against: Agendula publishes no real
ContentProvider since :provider was deleted, and without an authority
ContentService.hasAuthorityAccess() makes every ContentResolver sync
call a silent no-op at targetSdk >= 34. -->
<provider
android:name=".data.tasks.provider.AgendulaTaskProvider"
android:authorities="${applicationId}.tasks"
android:name=".data.sync.SyncStubProvider"
android:authorities="${applicationId}.sync"
android:exported="false"
android:syncable="true" />
<!-- Exported and guarded by ACCOUNT_MANAGER. Note that
android.permission.ACCOUNT_AUTHENTICATOR does not exist. -->
<service
android:name=".data.sync.AuthenticatorService"
android:exported="true"
android:readPermission="${applicationId}.permission.READ_TASKS"
android:writePermission="${applicationId}.permission.WRITE_TASKS"
tools:ignore="SystemPermissionTypo" />
android:permission="android.permission.ACCOUNT_MANAGER">
<intent-filter>
<action android:name="android.accounts.AccountAuthenticator" />
</intent-filter>
<meta-data
android:name="android.accounts.AccountAuthenticator"
android:resource="@xml/authenticator" />
</service>
<service
android:name=".data.sync.SyncAdapterService"
android:exported="true"
android:permission="android.permission.BIND_SYNC_ADAPTER">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="@xml/sync_adapter" />
</service>
<!-- UnifiedPush: the connector binds this to deliver endpoints and
WebDAV-Push messages. Not exported; the connector's own receiver is
what distributors talk to. -->
<service
android:name=".data.sync.push.AgendulaPushService"
android:exported="false">
<intent-filter>
<action android:name="org.unifiedpush.android.connector.PUSH_EVENT" />
</intent-filter>
</service>
<!-- WorkManager's on-demand initialisation. Removing the default
initializer is what lets AgendulaApp supply a HiltWorkerFactory, so
@@ -9,16 +9,13 @@ import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.android.HiltAndroidApp
import dagger.hilt.components.SingletonComponent
import de.jeanlucmakiola.agendula.data.backup.AutoBackupScheduler
import de.jeanlucmakiola.agendula.data.di.ApplicationScope
import de.jeanlucmakiola.agendula.data.di.ChannelRefresher
import de.jeanlucmakiola.agendula.data.reminders.ReminderMaintenanceWorker
import de.jeanlucmakiola.agendula.data.reminders.ReminderRefresher
import de.jeanlucmakiola.agendula.data.reminders.ReminderScheduler
import de.jeanlucmakiola.agendula.data.reminders.TaskNotifier
import de.jeanlucmakiola.agendula.data.sync.SyncNoticeNotifier
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
import de.jeanlucmakiola.agendula.data.tasks.StartupGate
import de.jeanlucmakiola.agendula.data.tasks.provider.ProviderSnapshotSource
import de.jeanlucmakiola.agendula.data.tasks.room.DatabaseCheckpoint
import de.jeanlucmakiola.agendula.widget.TaskWidgetUpdater
import de.jeanlucmakiola.floret.crash.CrashConfig
@@ -67,15 +64,17 @@ class AgendulaApp : Application(), Configuration.Provider {
// v0.3.x install's tasks, both before anything reads a store.
val startupGate = entryPoint.startupGate()
val scope = entryPoint.applicationScope()
// A switch rebuilds the alarms through ReminderRefresher, which hears it
// as a store change. Channels only once startup's own null -> stored
// transition is past, which the launch sync below covers.
// An alarm is armed off whichever store was active when it was scheduled,
// so a switch has to rebuild the set. Armed only once startup's own
// null -> stored transition is past, which the launch sync below covers.
val started = AtomicBoolean(false)
entryPoint.providerResolver().onModeChanged {
if (started.get()) runCatching { entryPoint.taskNotifier().refreshChannel() }
if (started.get()) {
scope.launch { runCatching { scheduler.sync() } }
runCatching { entryPoint.taskNotifier().refreshChannel() }
}
}
startupGate.start()
entryPoint.autoBackupScheduler().start()
refreshNotificationChannels()
ProcessLifecycleOwner.get().lifecycle.addObserver(entryPoint.databaseCheckpoint())
scope.launch {
@@ -88,8 +87,6 @@ class AgendulaApp : Application(), Configuration.Provider {
scheduler.sync()
}
runCatching { entryPoint.taskWidgetUpdater().start() }
runCatching { entryPoint.reminderRefresher().start() }
runCatching { entryPoint.providerSnapshotSource().start() }
runCatching { ReminderMaintenanceWorker.schedule(this@AgendulaApp) }
}
}
@@ -108,7 +105,7 @@ class AgendulaApp : Application(), Configuration.Provider {
val entryPoint = EntryPointAccessors.fromApplication(this, AppEntryPoint::class.java)
runCatching {
entryPoint.taskNotifier().refreshChannel()
entryPoint.channelRefreshers().forEach { it.refreshChannel() }
entryPoint.syncNoticeNotifier().refreshChannel()
}
}
@@ -123,10 +120,7 @@ class AgendulaApp : Application(), Configuration.Provider {
fun applicationScope(): CoroutineScope
fun databaseCheckpoint(): DatabaseCheckpoint
fun taskNotifier(): TaskNotifier
fun channelRefreshers(): Set<@JvmSuppressWildcards ChannelRefresher>
fun syncNoticeNotifier(): SyncNoticeNotifier
fun taskWidgetUpdater(): TaskWidgetUpdater
fun reminderRefresher(): ReminderRefresher
fun providerSnapshotSource(): ProviderSnapshotSource
fun autoBackupScheduler(): AutoBackupScheduler
}
}
@@ -16,7 +16,6 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.core.net.toUri
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.data.prefs.is24Hour
import de.jeanlucmakiola.agendula.ui.common.LocalFirstDayOfWeek
import de.jeanlucmakiola.agendula.ui.common.LocalUse24HourFormat
@@ -26,21 +25,23 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
import dagger.hilt.android.AndroidEntryPoint
import de.jeanlucmakiola.agendula.data.di.LaunchHook
import de.jeanlucmakiola.agendula.data.sync.SyncNoticeNotifier
import de.jeanlucmakiola.agendula.domain.SmartList
import de.jeanlucmakiola.agendula.domain.smartListNamed
import de.jeanlucmakiola.agendula.ui.imports.importIntentUri
import de.jeanlucmakiola.agendula.ui.navigation.AppShortcuts
import de.jeanlucmakiola.agendula.data.prefs.ThemeMode
import de.jeanlucmakiola.agendula.ui.RootScreen
import de.jeanlucmakiola.agendula.ui.crash.CrashReportActivity
import de.jeanlucmakiola.agendula.ui.navigation.NavRequest
import de.jeanlucmakiola.agendula.data.sync.AccountRepository
import de.jeanlucmakiola.agendula.data.sync.PendingLoginFlowStore
import de.jeanlucmakiola.agendula.data.sync.SyncTrigger
import de.jeanlucmakiola.agendula.data.sync.push.PushRegistrar
import de.jeanlucmakiola.agendula.ui.settings.SettingsViewModel
import de.jeanlucmakiola.agendula.ui.theme.AgendulaTheme
import de.jeanlucmakiola.agendula.ui.theme.SystemTheme
import de.jeanlucmakiola.floret.crash.CrashReportDialog
import de.jeanlucmakiola.floret.crash.CrashReporter
import de.jeanlucmakiola.floret.crash.submitCrashReport
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import javax.inject.Inject
@@ -54,7 +55,13 @@ class MainActivity : ComponentActivity() {
@Inject lateinit var launchHooks: Set<@JvmSuppressWildcards LaunchHook>
@Inject lateinit var settingsPrefs: SettingsPrefs
@Inject lateinit var accounts: AccountRepository
@Inject lateinit var syncTrigger: SyncTrigger
@Inject lateinit var pendingLoginFlows: PendingLoginFlowStore
@Inject lateinit var push: PushRegistrar
// A captured crash report awaiting the user's decision, surfaced as a dialog
// over the app on the next launch (the single-crash path). A startup
@@ -79,13 +86,6 @@ class MainActivity : ComponentActivity() {
enableEdgeToEdge()
AppShortcuts.publish(this)
// The stored setting, never the view model's placeholder: a night mode
// that flips back and forth would recreate the activity each time.
lifecycleScope.launch {
settingsPrefs.settings.map { it.themeMode to it.dynamicColor }.distinctUntilChanged()
.collect { (mode, dynamicColor) -> SystemTheme.apply(this@MainActivity, mode, dynamicColor) }
}
// Only on a fresh launch: after a rotation or process restore the intent
// is the same old one and the back stack already holds its destination.
val fromHistory = intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0
@@ -94,22 +94,47 @@ class MainActivity : ComponentActivity() {
// Surface a single captured crash as a dialog on the next launch.
if (CrashReporter.shouldPrompt(this)) pendingCrashReport = CrashReporter.pendingReport(this)
// Each hook on its own, so one waiting on the network holds up no other.
// Sync hard on app open: the periodic worker's interval is a floor, and
// in the `rare` and `restricted` App Standby buckets it may not have run
// at all. `KEEP` makes rescheduling idempotent, so this also repairs a
// schedule lost to "clear app data" or to a restore.
//
// ⚠️ Only on a genuine open. This activity declares no `configChanges`,
// so onCreate runs again on every rotation, theme switch, locale change
// and font-scale change — each of which would otherwise start a fresh
// network sync the moment the previous one finished.
if (savedInstanceState == null) {
launchHooks.forEach { hook -> lifecycleScope.launch { runCatching { hook.onLaunch(intent) } } }
lifecycleScope.launch {
runCatching {
accounts.rescheduleAll()
accounts.syncable().forEach { syncTrigger.enqueue(it.displayName) }
// A login flow the previous process died in the middle of.
// Its password, if the user approved, exists nowhere else.
pendingLoginFlows.reclaim()
}
// Last and on its own: it waits on the network, and must not
// hold up the reclaim above. Re-registering on open is what
// the connector recommends.
runCatching { push.updateAll() }
}
}
// Variant hooks: the demo seeder in debug builds, nothing in release.
if (savedInstanceState == null) {
lifecycleScope.launch { launchHooks.forEach { runCatching { it.onLaunch(intent) } } }
}
setContent {
val settingsViewModel: SettingsViewModel = hiltViewModel()
val ui by settingsViewModel.state.collectAsStateWithLifecycle()
val darkTheme = ui.settings.themeMode.isDark(isSystemInDarkTheme())
val darkTheme = when (ui.settings.themeMode) {
ThemeMode.SYSTEM -> isSystemInDarkTheme()
ThemeMode.LIGHT -> false
ThemeMode.DARK -> true
}
val context = LocalContext.current
val use24Hour = ui.settings.timeFormat.is24Hour(DateFormat.is24HourFormat(context))
val firstDayOfWeek = ui.settings.weekStart ?: localeFirstDayOfWeek()
AgendulaTheme(
darkTheme = darkTheme,
dynamicColor = ui.settings.dynamicColor,
pureBlack = ui.settings.themeMode.isPureBlack,
) {
AgendulaTheme(darkTheme = darkTheme, dynamicColor = ui.settings.dynamicColor) {
CompositionLocalProvider(
LocalUse24HourFormat provides use24Hour,
LocalFirstDayOfWeek provides firstDayOfWeek,
@@ -118,7 +143,6 @@ class MainActivity : ComponentActivity() {
modifier = Modifier.fillMaxSize(),
navRequest = navRequest,
onNavRequestConsumed = { navRequest = null },
onReturnHome = ::finish,
)
pendingCrashReport?.let { report ->
CrashReportDialog(
@@ -156,21 +180,12 @@ class MainActivity : ComponentActivity() {
const val EXTRA_TASK_ID = "de.jeanlucmakiola.agendula.extra.TASK_ID"
const val EXTRA_OCCURRENCE_START = "de.jeanlucmakiola.agendula.extra.OCCURRENCE_START"
private const val EXTRA_OPEN_ACCOUNTS = "de.jeanlucmakiola.agendula.extra.OPEN_ACCOUNTS"
private const val ACTION_OPEN_BACKUP = "de.jeanlucmakiola.agendula.action.OPEN_BACKUP"
/** The account a sign-in notification is about, on the intent it opens. */
const val EXTRA_SIGN_IN_ACCOUNT_ID = "de.jeanlucmakiola.agendula.extra.SIGN_IN_ACCOUNT_ID"
const val ACTION_NEW_TASK = "de.jeanlucmakiola.agendula.action.NEW_TASK"
const val ACTION_TODAY = "de.jeanlucmakiola.agendula.action.TODAY"
private const val ACTION_OPEN_SMART = "de.jeanlucmakiola.agendula.action.OPEN_SMART"
private const val ACTION_OPEN_LIST = "de.jeanlucmakiola.agendula.action.OPEN_LIST"
private const val ACTION_OPEN_FILTER = "de.jeanlucmakiola.agendula.action.OPEN_FILTER"
private const val EXTRA_FILTER_ID = "de.jeanlucmakiola.agendula.extra.FILTER_ID"
private const val EXTRA_SMART_LIST = "de.jeanlucmakiola.agendula.extra.SMART_LIST"
private const val EXTRA_LIST_ID = "de.jeanlucmakiola.agendula.extra.LIST_ID"
private const val EXTRA_RETURN_HOME = "de.jeanlucmakiola.agendula.extra.RETURN_HOME"
private const val EXTRA_PRESET_LIST_ID = "de.jeanlucmakiola.agendula.extra.PRESET_LIST_ID"
private const val EXTRA_DUE_TODAY = "de.jeanlucmakiola.agendula.extra.DUE_TODAY"
private const val SHARED_TITLE_LIMIT = 500
private const val NO_OCCURRENCE = -1L
@@ -178,16 +193,10 @@ class MainActivity : ComponentActivity() {
* Opens a task's detail (reminder taps). [occurrenceStart] (epoch millis)
* picks the occurrence of a recurring task.
*/
fun taskIntent(
context: Context,
taskId: Long,
occurrenceStart: Long? = null,
returnHome: Boolean = false,
): Intent =
fun taskIntent(context: Context, taskId: Long, occurrenceStart: Long? = null): Intent =
Intent(context, MainActivity::class.java).apply {
putExtra(EXTRA_TASK_ID, taskId)
putExtra(EXTRA_OCCURRENCE_START, occurrenceStart ?: NO_OCCURRENCE)
putExtra(EXTRA_RETURN_HOME, returnHome)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
@@ -197,35 +206,11 @@ class MainActivity : ComponentActivity() {
.putExtra(EXTRA_OPEN_ACCOUNTS, true)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
/** Opens Settings → Backup & restore, where a failing automatic backup is fixed. */
fun backupIntent(context: Context): Intent =
Intent(ACTION_OPEN_BACKUP, null, context, MainActivity::class.java)
/** The launcher shortcut's and Quick Settings tile's "New task". */
fun newTaskIntent(context: Context): Intent =
Intent(ACTION_NEW_TASK, null, context, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
/**
* The launcher shortcut's, Quick Settings tile's and a widget's "New
* task". [listId] preset the list when it names exactly one, [filterId]
* or [smartList] what a widget showing one fills in; the data URI keeps
* each widget's PendingIntent apart from the others.
*/
fun newTaskIntent(
context: Context,
listId: Long? = null,
smartList: SmartList? = null,
filterId: Long? = null,
): Intent {
val path = listOfNotNull(
listId?.toString(),
smartList?.name?.lowercase(),
filterId?.let { "filter$it" },
).joinToString("/")
return Intent(ACTION_NEW_TASK, path.ifEmpty { null }?.let { "agendula://newtask/$it".toUri() }, context, MainActivity::class.java)
.putExtra(EXTRA_PRESET_LIST_ID, listId ?: -1L)
.putExtra(EXTRA_SMART_LIST, smartList?.name)
.putExtra(EXTRA_FILTER_ID, filterId ?: -1L)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
fun todayIntent(context: Context): Intent =
Intent(ACTION_TODAY, null, context, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
@@ -242,47 +227,30 @@ class MainActivity : ComponentActivity() {
.putExtra(EXTRA_LIST_ID, listId)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
/** Opens one saved filter. */
fun filterIntent(context: Context, filterId: Long): Intent =
Intent(ACTION_OPEN_FILTER, "agendula://filter/$filterId".toUri(), context, MainActivity::class.java)
.putExtra(EXTRA_FILTER_ID, filterId)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
internal fun navRequestOf(intent: Intent?): NavRequest? {
if (intent == null) return null
if (BuildConfig.SYNC_ENABLED) {
intent.getLongExtra(EXTRA_SIGN_IN_ACCOUNT_ID, -1L).takeIf { it > 0L }
?.let { return NavRequest.OpenAccount(it) }
if (intent.getBooleanExtra(EXTRA_OPEN_ACCOUNTS, false)) return NavRequest.OpenAccounts
}
intent.getLongExtra(SyncNoticeNotifier.EXTRA_SIGN_IN_ACCOUNT_ID, -1L).takeIf { it > 0L }
?.let { return NavRequest.OpenAccount(it) }
if (intent.getBooleanExtra(EXTRA_OPEN_ACCOUNTS, false)) return NavRequest.OpenAccounts
when (intent.action) {
ACTION_NEW_TASK -> return NavRequest.NewTask(
listId = intent.getLongExtra(EXTRA_PRESET_LIST_ID, -1L).takeIf { it > 0L },
filterId = intent.getLongExtra(EXTRA_FILTER_ID, -1L).takeIf { it > 0L },
// Widgets placed before 1.4 still carry the old flag.
smartList = smartListNamed(intent.getStringExtra(EXTRA_SMART_LIST))
?: SmartList.TODAY.takeIf { intent.getBooleanExtra(EXTRA_DUE_TODAY, false) },
returnHome = true,
)
ACTION_NEW_TASK -> return NavRequest.NewTask()
ACTION_TODAY -> return NavRequest.OpenSmart(SmartList.TODAY)
ACTION_OPEN_BACKUP -> return NavRequest.OpenBackup
ACTION_OPEN_SMART -> smartListNamed(intent.getStringExtra(EXTRA_SMART_LIST))
ACTION_OPEN_SMART -> intent.getStringExtra(EXTRA_SMART_LIST)
?.let { name -> SmartList.entries.firstOrNull { it.name == name } }
?.let { return NavRequest.OpenSmart(it) }
ACTION_OPEN_LIST -> intent.getLongExtra(EXTRA_LIST_ID, -1L).takeIf { it > 0L }
?.let { return NavRequest.OpenList(it) }
ACTION_OPEN_FILTER -> intent.getLongExtra(EXTRA_FILTER_ID, -1L).takeIf { it > 0L }
?.let { return NavRequest.OpenFilter(it) }
}
importIntentUri(intent)?.let { return NavRequest.Import(it) }
if (intent.action == Intent.ACTION_SEND && intent.type?.startsWith("text/plain") == true) {
val shared = intent.getStringExtra(Intent.EXTRA_SUBJECT)?.takeIf { it.isNotBlank() }
?: intent.getStringExtra(Intent.EXTRA_TEXT)
return NavRequest.NewTask(shared?.trim()?.take(SHARED_TITLE_LIMIT), returnHome = true)
return NavRequest.NewTask(shared?.trim()?.take(SHARED_TITLE_LIMIT))
}
val taskId = intent.getLongExtra(EXTRA_TASK_ID, -1L).takeIf { it > 0L } ?: return null
val occurrence = intent.getLongExtra(EXTRA_OCCURRENCE_START, NO_OCCURRENCE)
.takeIf { it != NO_OCCURRENCE }
return NavRequest.OpenTask(taskId, occurrence, intent.getBooleanExtra(EXTRA_RETURN_HOME, false))
return NavRequest.OpenTask(taskId, occurrence)
}
}
}
@@ -1,62 +0,0 @@
package de.jeanlucmakiola.agendula.data
import java.net.URI
import java.util.concurrent.ConcurrentHashMap
/** Compares collection URLs the way a server means them, not the way it spells them. */
object CollectionHref {
/** Whether [a] and [b] name the same collection: case, default port, escaping and a trailing slash aside. */
fun same(a: String?, b: String?): Boolean {
if (a == null || b == null) return false
return key(a) == key(b)
}
/** Memoised: the lists flow maps every row on every sync, and hrefs rarely change. */
private fun key(href: String): String {
keys[href]?.let { return it }
if (keys.size > MAX_CACHED) keys.clear()
return parse(href).also { keys[href] = it }
}
private fun parse(href: String): String = runCatching {
val uri = URI(URI(escapePath(href)).toASCIIString())
val scheme = uri.scheme.lowercase()
val authority = uri.rawAuthority.substringAfterLast('@')
val host = (uri.host ?: authority.substringBeforeLast(':')).lowercase()
val explicitPort = if (uri.host != null) uri.port else authority.substringAfterLast(':', "").toIntOrNull() ?: -1
val port = when {
explicitPort != -1 -> explicitPort
scheme == "https" -> HTTPS_PORT
scheme == "http" -> HTTP_PORT
else -> -1
}
"$scheme://$host:$port${normalizeEscapes(uri.rawPath.orEmpty()).trimEnd('/')}"
}.getOrElse { href.lowercase().trimEnd('/') }
/** Escapes what servers leave raw in paths but [URI] refuses, such as `[` and a space. */
private fun escapePath(href: String): String {
val pathStart = href.indexOf('/', href.indexOf("://").let { if (it < 0) 0 else it + SCHEME_SEPARATOR })
if (pathStart < 0) return href
val path = href.substring(pathStart).map { c ->
if (c in UNSAFE) "%" + c.code.toString(HEX).uppercase().padStart(2, '0') else c.toString()
}
return href.substring(0, pathStart) + path.joinToString("")
}
/** Decodes escaped ASCII but `%2F`, which is part of a segment, not a separator. */
private fun normalizeEscapes(path: String): String = ESCAPE.replace(path) { match ->
val code = match.groupValues[1].toInt(HEX)
if (code == '/'.code || code >= ASCII_END) match.value.uppercase() else code.toChar().toString()
}
private val keys = ConcurrentHashMap<String, String>()
private val ESCAPE = Regex("%([0-9A-Fa-f]{2})")
private const val UNSAFE = " \"<>[]\\^`{|}"
private const val SCHEME_SEPARATOR = 3
private const val MAX_CACHED = 512
private const val HEX = 16
private const val ASCII_END = 0x80
private const val HTTPS_PORT = 443
private const val HTTP_PORT = 80
}
@@ -1,86 +0,0 @@
package de.jeanlucmakiola.agendula.data.appname
import android.content.ComponentName
import android.content.Context
import android.content.pm.PackageManager
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.agendula.ui.navigation.AppShortcuts
import javax.inject.Inject
import javax.inject.Singleton
/** The label the launcher shows for the app (#104). */
enum class LauncherName { AGENDULA, TASKS }
/** The two launcher aliases declared in the manifest. */
enum class LauncherAlias { DEFAULT, TASKS }
/** One component-enable change in an [aliasWritePlan]. */
data class AliasStateChange(val alias: LauncherAlias, val enabled: Boolean)
/**
* Reads the `TasksNameAlias` enabled state as a [LauncherName]. Only an explicit
* enable means "Tasks"; never toggled and disabled both mean the manifest default.
*/
fun launcherNameFor(tasksAliasState: Int): LauncherName =
if (tasksAliasState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
LauncherName.TASKS
} else {
LauncherName.AGENDULA
}
/**
* The steps to switch to [target]: enable the target alias first, then disable
* the other, so the launcher can briefly see two entries but never none.
*/
fun aliasWritePlan(target: LauncherName): List<AliasStateChange> = when (target) {
LauncherName.TASKS -> listOf(
AliasStateChange(LauncherAlias.TASKS, enabled = true),
AliasStateChange(LauncherAlias.DEFAULT, enabled = false),
)
LauncherName.AGENDULA -> listOf(
AliasStateChange(LauncherAlias.DEFAULT, enabled = true),
AliasStateChange(LauncherAlias.TASKS, enabled = false),
)
}
/**
* Switches the launcher label by enabling one of the two `<activity-alias>`
* components. The component state is the only source of truth; nothing is
* stored in prefs.
*/
@Singleton
class LauncherNameManager @Inject constructor(
@ApplicationContext private val context: Context,
) {
private val packageManager: PackageManager get() = context.packageManager
// The package is the (suffixed) applicationId, the class is namespace-qualified.
private fun component(alias: LauncherAlias): ComponentName {
val simpleName = when (alias) {
LauncherAlias.DEFAULT -> "DefaultNameAlias"
LauncherAlias.TASKS -> "TasksNameAlias"
}
return ComponentName(context.packageName, "$NAMESPACE.$simpleName")
}
fun current(): LauncherName =
launcherNameFor(packageManager.getComponentEnabledSetting(component(LauncherAlias.TASKS)))
fun set(name: LauncherName) {
for (change in aliasWritePlan(name)) {
val state = if (change.enabled) {
PackageManager.COMPONENT_ENABLED_STATE_ENABLED
} else {
PackageManager.COMPONENT_ENABLED_STATE_DISABLED
}
packageManager.setComponentEnabledSetting(component(change.alias), state, PackageManager.DONT_KILL_APP)
}
// Dynamic shortcuts hang off the launcher activity, which just changed.
AppShortcuts.publish(context)
}
private companion object {
/** `namespace` in app/build.gradle.kts, not the suffixed applicationId. */
const val NAMESPACE = "de.jeanlucmakiola.agendula"
}
}
@@ -1,86 +0,0 @@
package de.jeanlucmakiola.agendula.data.backup
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.util.Locale
/**
* The rules of the automatic backup that need no Android: how a backup file is
* named, which ones rotation removes, and the bounds of the user's choices.
*
* Names carry UTC, so a time-zone change or the DST fall-back can never make a
* new backup sort before an older one and get rotated out. Rotation only ever
* touches files matching [fileName]'s pattern (or their [partialName]), so
* anything else the user keeps in the same folder is safe.
*/
object AutoBackupPolicy {
const val DEFAULT_INTERVAL_MINUTES = 1_440
const val MIN_INTERVAL_MINUTES = 60
const val MAX_INTERVAL_MINUTES = 999 * 10_080
/** Every 6 and 12 hours, daily, weekly. */
val INTERVAL_PRESETS = listOf(360, 720, 1_440, 10_080)
const val DEFAULT_KEEP = 7
const val MAX_KEEP = 999
val KEEP_PRESETS = listOf(3, 7, 14, 30)
private const val PREFIX = "agendula-backup-"
private const val EXTENSION = ".zip"
private const val PARTIAL_SUFFIX = ".partial"
private val STAMP = DateTimeFormatter.ofPattern("uuuu-MM-dd-HHmmss'Z'", Locale.ROOT)
private val NAME = Regex("""agendula-backup-(\d{4}-\d{2}-\d{2}-\d{6}Z)(?:-([1-9]\d{0,5}))?\.zip""")
/**
* `agendula-backup-2026-11-17-143005Z.zip`: sortable, and readable in a
* file manager. The [n]th backup taken in one second gets `-n`.
*/
fun fileName(at: Instant, n: Int = 0): String =
PREFIX + STAMP.format(at.atOffset(ZoneOffset.UTC)) + (if (n > 0) "-$n" else "") + EXTENSION
/** The first name for a backup taken [at] that neither it nor its [partialName] has in [taken]. */
fun freeName(at: Instant, taken: Set<String>): String =
generateSequence(0) { it + 1 }.map { fileName(at, it) }.first { it !in taken && partialName(it) !in taken }
/** The name a backup is written under until it is complete. */
fun partialName(fileName: String): String = fileName + PARTIAL_SUFFIX
/** When the backup named [name] was taken, or null when it is not one of ours. */
fun timestampOf(name: String): Instant? = rankOf(name)?.first
private fun rankOf(name: String): Pair<Instant, Int>? =
NAME.matchEntire(name)?.let { match ->
val at = runCatching { LocalDateTime.parse(match.groupValues[1], STAMP).toInstant(ZoneOffset.UTC) }.getOrNull()
at?.let { it to (match.groupValues[2].toIntOrNull() ?: 0) }
}
/**
* The backups in [names] beyond the newest [keep], newest first. [current],
* the backup just written, always ranks first, so one dated ahead by a
* skewed clock can never rotate it away. Any other of the same second goes:
* it may be one a run never finished, and must not take a good one's place.
*/
fun staleBackups(names: Collection<String>, keep: Int, current: String): List<String> {
val at = timestampOf(current)
val (sameSecond, others) = names.filter { it != current }
.mapNotNull { name -> rankOf(name)?.let { name to it } }
.partition { it.second.first == at }
val older = others
.sortedWith(compareByDescending<Pair<String, Pair<Instant, Int>>> { it.second.first }.thenByDescending { it.second.second })
.map { it.first }
.drop(clampKeep(keep) - 1)
return sameSecond.map { it.first } + older
}
/** Backups a run never finished, e.g. because the process was killed mid-write. */
fun abandonedPartials(names: Collection<String>): List<String> =
names.filter { it.endsWith(PARTIAL_SUFFIX) && timestampOf(it.removeSuffix(PARTIAL_SUFFIX)) != null }
/** Whole hours, within bounds. */
fun clampInterval(minutes: Int): Int = (minutes / 60 * 60).coerceIn(MIN_INTERVAL_MINUTES, MAX_INTERVAL_MINUTES)
fun clampKeep(count: Int): Int = count.coerceIn(1, MAX_KEEP)
}
@@ -1,140 +0,0 @@
package de.jeanlucmakiola.agendula.data.backup
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import de.jeanlucmakiola.agendula.data.export.ExportFailure
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton
/** What the automatic backup does: [folderUri] is a persisted SAF tree grant. */
data class AutoBackupConfig(
val enabled: Boolean = false,
val folderUri: String? = null,
val intervalMinutes: Int = AutoBackupPolicy.DEFAULT_INTERVAL_MINUTES,
val keepCount: Int = AutoBackupPolicy.DEFAULT_KEEP,
) {
/** Whether there is anything to schedule. */
val active: Boolean get() = enabled && folderUri != null
}
/**
* Why an automatic backup failed: the export's write failures ([export]), plus
* the two that happen before anything is written. [transient] ones are retried.
*/
enum class BackupFailure(val export: ExportFailure?, val transient: Boolean) {
FOLDER_UNAVAILABLE(ExportFailure.FOLDER_UNAVAILABLE, transient = true),
FOLDER_NOT_WRITABLE(ExportFailure.FOLDER_NOT_WRITABLE, transient = false),
CANNOT_CREATE_FILE(ExportFailure.CANNOT_CREATE_FILE, transient = true),
LOST_ACCESS(ExportFailure.LOST_ACCESS, transient = false),
WRITE_FAILED(ExportFailure.WRITE_FAILED, transient = true),
READ_FAILED(null, transient = true),
NO_LISTS(null, transient = false),
;
companion object {
fun of(failure: ExportFailure): BackupFailure = entries.firstOrNull { it.export == failure } ?: WRITE_FAILED
}
}
/**
* How the automatic backup has gone: [lastRunMillis] 0 = never ran, [failure]
* null = the last run worked, [lastSuccessMillis] 0 = none has yet.
*/
data class AutoBackupStatus(
val lastRunMillis: Long = 0L,
val failure: BackupFailure? = null,
val lastSuccessMillis: Long = 0L,
)
/** The automatic backup's settings and last outcome, in the app's DataStore. */
@Singleton
class AutoBackupPrefs @Inject constructor(
private val dataStore: DataStore<Preferences>,
) {
val config: Flow<AutoBackupConfig> = dataStore.data.map { p ->
AutoBackupConfig(
enabled = p[ENABLED] ?: false,
folderUri = p[FOLDER],
intervalMinutes = p[INTERVAL]?.let(AutoBackupPolicy::clampInterval)
?: AutoBackupPolicy.DEFAULT_INTERVAL_MINUTES,
keepCount = p[KEEP]?.let(AutoBackupPolicy::clampKeep) ?: AutoBackupPolicy.DEFAULT_KEEP,
)
}.distinctUntilChanged()
val status: Flow<AutoBackupStatus> = dataStore.data.map { p ->
AutoBackupStatus(
lastRunMillis = p[LAST_RUN] ?: 0L,
lastSuccessMillis = p[LAST_SUCCESS_AT] ?: 0L,
failure = p[FAILURE_REASON]?.let {
runCatching { BackupFailure.valueOf(it) }.getOrDefault(BackupFailure.WRITE_FAILED)
},
)
}.distinctUntilChanged()
/** A fresh start, on or off, also restarts the count towards the failure notification. */
suspend fun setEnabled(enabled: Boolean) = dataStore.edit {
it[ENABLED] = enabled
it.remove(FAILURES)
}
/** Points the backup at [uri] and turns it on; the caller has taken the grant. */
suspend fun setFolder(uri: String) = dataStore.edit {
it[FOLDER] = uri
it[ENABLED] = true
it.remove(FAILURES)
}
/** Forgets a folder this install holds no grant for, e.g. settings restored onto a new device. */
suspend fun forgetFolder(uri: String) = dataStore.edit {
if (it[FOLDER] != uri) return@edit
it.remove(FOLDER)
it[ENABLED] = false
listOf(LAST_RUN, LAST_SUCCESS_AT, FAILURES, FAILURE_REASON).forEach { key -> it.remove(key) }
}
suspend fun setIntervalMinutes(minutes: Int) =
dataStore.edit { it[INTERVAL] = AutoBackupPolicy.clampInterval(minutes) }
suspend fun setKeepCount(count: Int) = dataStore.edit { it[KEEP] = AutoBackupPolicy.clampKeep(count) }
suspend fun recordSuccess(atMillis: Long) = dataStore.edit {
it[LAST_RUN] = atMillis
it[LAST_SUCCESS_AT] = atMillis
it[FAILURES] = 0
it.remove(FAILURE_REASON)
}
/**
* Records a failed attempt. Only [final] attempts — no retry left — count
* towards the failure notification; returns how many runs in a row have failed.
*/
suspend fun recordFailure(atMillis: Long, reason: BackupFailure, final: Boolean): Int {
var failures = 0
dataStore.edit {
failures = (it[FAILURES] ?: 0) + if (final) 1 else 0
it[LAST_RUN] = atMillis
it[FAILURES] = failures
it[FAILURE_REASON] = reason.name
}
return failures
}
private companion object {
val ENABLED = booleanPreferencesKey("auto_backup_enabled")
val FOLDER = stringPreferencesKey("auto_backup_folder")
val INTERVAL = intPreferencesKey("auto_backup_interval_minutes")
val KEEP = intPreferencesKey("auto_backup_keep")
val LAST_RUN = longPreferencesKey("auto_backup_last_run")
val LAST_SUCCESS_AT = longPreferencesKey("auto_backup_last_success_at")
val FAILURES = intPreferencesKey("auto_backup_failures")
val FAILURE_REASON = stringPreferencesKey("auto_backup_failure_reason")
}
}
@@ -1,121 +0,0 @@
package de.jeanlucmakiola.agendula.data.backup
import android.content.Context
import androidx.work.BackoffPolicy
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkInfo
import androidx.work.WorkManager
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.agendula.data.di.ApplicationScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
/**
* Keeps WorkManager in step with [AutoBackupPrefs]: a unique periodic request
* while the backup is on and has a folder, nothing otherwise. Reactive, so every
* settings change (and every launch) reconciles without the caller having to.
* Turning the backup on, or pointing it at a new folder, also takes one backup
* at once — here rather than at the call site, so it is ordered after any
* cancellation an earlier "off" caused.
*/
@Singleton
class AutoBackupScheduler @Inject constructor(
@ApplicationContext private val context: Context,
private val prefs: AutoBackupPrefs,
private val notifier: BackupNotifier,
@ApplicationScope private val scope: CoroutineScope,
) {
private data class Plan(val folderUri: String, val intervalMinutes: Int)
/** Call once, first thing in `Application.onCreate`, so no settings change predates the collector. */
fun start() {
scope.launch {
runCatching { forgetUngrantedFolder() }
var previous: Plan? = null
var first = true
prefs.config
.map { config -> config.folderUri?.takeIf { config.active }?.let { Plan(it, config.intervalMinutes) } }
.distinctUntilChanged()
.collect { plan ->
runCatching {
apply(plan?.intervalMinutes)
if (!first && plan != null && plan.folderUri != previous?.folderUri) runNow()
}
previous = plan
first = false
}
}
}
/** One backup now. A newer request replaces a queued or running one, so it runs on the current settings. */
fun runNow() {
WorkManager.getInstance(context).enqueueUniqueWork(
WORK_NAME_NOW,
ExistingWorkPolicy.REPLACE,
OneTimeWorkRequestBuilder<AutoBackupWorker>()
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, BACKOFF_MINUTES, TimeUnit.MINUTES)
.build(),
)
}
/**
* Whether a backup is running, or a [runNow] one is about to; a periodic one
* waiting for its time, or any run waiting out a retry, does not count.
*/
val running: Flow<Boolean> = WorkManager.getInstance(context).let { workManager ->
combine(
workManager.getWorkInfosForUniqueWorkFlow(WORK_NAME_NOW),
workManager.getWorkInfosForUniqueWorkFlow(WORK_NAME),
) { now, periodic ->
now.any { it.state == WorkInfo.State.RUNNING || (it.state == WorkInfo.State.ENQUEUED && it.runAttemptCount == 0) } ||
periodic.any { it.state == WorkInfo.State.RUNNING }
}.distinctUntilChanged()
}
/**
* Settings restored onto another device (Android's own backup) bring the
* folder along but not the grant to write to it; every run would fail.
*/
private suspend fun forgetUngrantedFolder() {
val folder = prefs.config.first().folderUri ?: return
val granted = context.contentResolver.persistedUriPermissions.any {
it.uri.toString() == folder && it.isWritePermission
}
if (!granted) prefs.forgetFolder(folder)
}
/** [intervalMinutes] null cancels. The first periodic run waits one interval. */
private fun apply(intervalMinutes: Int?) {
val workManager = WorkManager.getInstance(context)
if (intervalMinutes == null) {
workManager.cancelUniqueWork(WORK_NAME)
workManager.cancelUniqueWork(WORK_NAME_NOW)
notifier.cancelFailure()
return
}
val minutes = intervalMinutes.toLong()
val request = PeriodicWorkRequestBuilder<AutoBackupWorker>(minutes, TimeUnit.MINUTES)
.setInitialDelay(minutes, TimeUnit.MINUTES)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, BACKOFF_MINUTES, TimeUnit.MINUTES)
.build()
workManager.enqueueUniquePeriodicWork(WORK_NAME, ExistingPeriodicWorkPolicy.UPDATE, request)
}
private companion object {
const val WORK_NAME = "auto-backup"
const val WORK_NAME_NOW = "auto-backup-now"
const val BACKOFF_MINUTES = 10L
}
}
@@ -1,106 +0,0 @@
package de.jeanlucmakiola.agendula.data.backup
import android.content.Context
import android.util.Log
import androidx.core.net.toUri
import androidx.hilt.work.HiltWorker
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import de.jeanlucmakiola.agendula.data.export.ExportFailedException
import de.jeanlucmakiola.agendula.data.export.ExportWriter
import de.jeanlucmakiola.agendula.data.export.TaskExporter
import de.jeanlucmakiola.agendula.data.tasks.StartupGate
import de.jeanlucmakiola.agendula.domain.export.ExportDocument
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.time.Instant
import kotlin.coroutines.cancellation.CancellationException
/**
* One automatic backup: every list of the current store, as the export's zip,
* into a new dated file in the chosen folder, then rotation down to the kept
* count. A transient failure is retried a few times with backoff; every
* failure is recorded for the settings status line, and a run that has given
* up twice in a row raises a notification. A periodic request runs again next
* interval either way.
*/
@HiltWorker
class AutoBackupWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val prefs: AutoBackupPrefs,
private val startupGate: StartupGate,
private val exporter: TaskExporter,
private val writer: ExportWriter,
private val notifier: BackupNotifier,
) : CoroutineWorker(context, params) {
// One at a time across the periodic and "now" chains.
override suspend fun doWork(): Result = runLock.withLock { backUp() }
private suspend fun backUp(): Result {
val config = prefs.config.first()
val folder = config.folderUri?.takeIf { config.enabled } ?: return Result.success()
val now = System.currentTimeMillis()
return try {
startupGate.awaitReady()
val documents = readLists()
val tree = folder.toUri()
val stamp = Instant.ofEpochMilli(now)
writer.writeZipToTree(
tree,
documents,
name = { taken -> AutoBackupPolicy.freeName(stamp, taken) },
partialName = AutoBackupPolicy::partialName,
) { names, written ->
AutoBackupPolicy.staleBackups(names, config.keepCount, written) + AutoBackupPolicy.abandonedPartials(names)
}
prefs.recordSuccess(now)
notifier.cancelFailure()
Result.success()
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Exception) {
Log.w(TAG, "Automatic backup failed", error)
// The user moved the backup elsewhere mid-run; the old folder's failure is not theirs.
if (prefs.config.first().folderUri != folder) return Result.success()
val reason = when (error) {
is BackupFailedException -> error.failure
is ExportFailedException -> BackupFailure.of(error.failure)
else -> BackupFailure.WRITE_FAILED
}
val retry = reason.transient && runAttemptCount < MAX_RETRIES
val failures = prefs.recordFailure(now, reason, final = !retry)
if (!retry && failures >= FAILURE_NOTIFY_THRESHOLD) notifier.postFailure()
if (retry) Result.retry() else Result.failure()
}
}
/**
* No lists is a failure, not an empty backup: it is what an unreachable task
* app looks like, and an empty zip would rotate the real backups out.
*/
private suspend fun readLists(): List<ExportDocument> {
val documents = try {
exporter.export()
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Exception) {
throw BackupFailedException(BackupFailure.READ_FAILED, error)
}
return documents.ifEmpty { throw BackupFailedException(BackupFailure.NO_LISTS) }
}
private class BackupFailedException(val failure: BackupFailure, cause: Throwable? = null) :
Exception(failure.name, cause)
private companion object {
const val TAG = "AutoBackupWorker"
const val FAILURE_NOTIFY_THRESHOLD = 2
const val MAX_RETRIES = 3
val runLock = Mutex()
}
}
@@ -1,89 +0,0 @@
package de.jeanlucmakiola.agendula.data.backup
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import dagger.multibindings.IntoSet
import de.jeanlucmakiola.agendula.MainActivity
import de.jeanlucmakiola.agendula.R
import de.jeanlucmakiola.agendula.data.di.ChannelRefresher
import de.jeanlucmakiola.agendula.data.reminders.canPostNotifications
import javax.inject.Inject
import javax.inject.Singleton
/**
* Says so when automatic backups keep failing — a revoked folder grant or an
* unmounted SD card would otherwise go unnoticed until the backup is needed.
* Its own low-importance channel, so it can be silenced on its own.
*/
@Singleton
class BackupNotifier @Inject constructor(
@ApplicationContext private val context: Context,
) : ChannelRefresher {
// canPostNotifications() checks POST_NOTIFICATIONS before we ever call notify().
@SuppressLint("MissingPermission")
fun postFailure() {
if (!context.canPostNotifications()) return
ensureChannel()
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(context.getString(R.string.backup_failed_title))
.setContentText(context.getString(R.string.backup_failed_text))
.setCategory(NotificationCompat.CATEGORY_ERROR)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setAutoCancel(true)
.setContentIntent(
PendingIntent.getActivity(
context,
NOTIFICATION_ID,
MainActivity.backupIntent(context),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
),
)
.build()
runCatching { NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, notification) }
}
fun cancelFailure() {
NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID)
}
private fun ensureChannel() {
context.getSystemService(NotificationManager::class.java).createNotificationChannel(
NotificationChannel(
CHANNEL_ID,
context.getString(R.string.backup_channel_name),
NotificationManager.IMPORTANCE_LOW,
).apply { description = context.getString(R.string.backup_channel_description) },
)
}
/** Re-create the channel, if it exists, in the current language. */
override fun refreshChannel() {
val manager = context.getSystemService(NotificationManager::class.java)
if (manager.getNotificationChannel(CHANNEL_ID) != null) ensureChannel()
}
private companion object {
const val CHANNEL_ID = "auto_backup"
const val NOTIFICATION_ID = 5
}
}
@Module
@InstallIn(SingletonComponent::class)
abstract class BackupModule {
@Binds
@IntoSet
abstract fun bindBackupChannel(impl: BackupNotifier): ChannelRefresher
}
@@ -1,22 +0,0 @@
package de.jeanlucmakiola.agendula.data.di
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dagger.multibindings.Multibinds
/**
* A notification channel a build variant adds, re-created in the current
* language on start and on a configuration change. The `full` flavor
* contributes the sync notices; `offline` has none.
*/
fun interface ChannelRefresher {
fun refreshChannel()
}
@Module
@InstallIn(SingletonComponent::class)
abstract class ChannelRefresherModule {
@Multibinds
abstract fun channelRefreshers(): Set<ChannelRefresher>
}
@@ -12,6 +12,13 @@ import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import de.jeanlucmakiola.agendula.data.sync.AccountCreator
import de.jeanlucmakiola.agendula.data.sync.AccountRepository
import de.jeanlucmakiola.agendula.data.sync.CalDavGateway
import de.jeanlucmakiola.agendula.data.sync.LoginFlowRecord
import de.jeanlucmakiola.agendula.data.sync.PendingLoginFlowStore
import de.jeanlucmakiola.agendula.data.sync.SyncOnEdit
import de.jeanlucmakiola.agendula.data.sync.OkHttpCalDavGateway
import de.jeanlucmakiola.agendula.data.tasks.AndroidProviderEnvironment
import de.jeanlucmakiola.agendula.data.tasks.AndroidTasksDataSource
import de.jeanlucmakiola.agendula.data.tasks.ModeRoutingTasksDataSource
@@ -20,6 +27,7 @@ import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
import de.jeanlucmakiola.agendula.data.tasks.TasksRepository
import de.jeanlucmakiola.agendula.data.tasks.TasksRepositoryImpl
import de.jeanlucmakiola.agendula.data.tasks.room.LocalWriteListener
import de.jeanlucmakiola.agendula.data.tasks.room.RoomTasksDataSource
import de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase
import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler
@@ -43,13 +51,37 @@ import javax.inject.Singleton
* reconciled", and the credential store to accounts that ask to be signed in
* again — all states the app already knows how to be in, unlike a launch loop.
*/
internal fun replaceCorrupted() = ReplaceFileCorruptionHandler { emptyPreferences() }
private fun replaceCorrupted() = ReplaceFileCorruptionHandler { emptyPreferences() }
private val Context.agendulaDataStore: DataStore<Preferences> by preferencesDataStore(
name = "agendula_prefs",
corruptionHandler = replaceCorrupted(),
)
/** See [CredentialsDataStore] for why this is a separate file. */
private val Context.credentialsDataStore: DataStore<Preferences> by preferencesDataStore(
name = CREDENTIALS_DATASTORE,
corruptionHandler = replaceCorrupted(),
)
/** See [SyncStateDataStore] for why this is a separate file. */
private val Context.syncStateDataStore: DataStore<Preferences> by preferencesDataStore(
name = SYNC_STATE_DATASTORE,
corruptionHandler = replaceCorrupted(),
)
/**
* Named here and in `backup_rules.xml` / `data_extraction_rules.xml`, which
* exclude `datastore/$CREDENTIALS_DATASTORE.preferences_pb` by this name.
*/
const val CREDENTIALS_DATASTORE = "agendula_credentials"
/**
* Named here and in `backup_rules.xml` / `data_extraction_rules.xml`, which
* exclude `datastore/$SYNC_STATE_DATASTORE.preferences_pb` by this name.
*/
const val SYNC_STATE_DATASTORE = "agendula_sync_state"
@Module
@InstallIn(SingletonComponent::class)
abstract class DataBindModule {
@@ -62,6 +94,22 @@ abstract class DataBindModule {
@Singleton
abstract fun bindProviderEnvironment(impl: AndroidProviderEnvironment): ProviderEnvironment
@Binds
@Singleton
abstract fun bindCalDavGateway(impl: OkHttpCalDavGateway): CalDavGateway
@Binds
@Singleton
abstract fun bindAccountCreator(impl: AccountRepository): AccountCreator
@Binds
@Singleton
abstract fun bindLoginFlowRecord(impl: PendingLoginFlowStore): LoginFlowRecord
@Binds
@Singleton
abstract fun bindLocalWriteListener(impl: SyncOnEdit): LocalWriteListener
// Deliberately unqualified-free of the routing above: this is the external
// store itself, for the one caller that has to read it while another store is
// the active one.
@@ -80,6 +128,18 @@ object DataProvideModule {
fun provideDataStore(@ApplicationContext context: Context): DataStore<Preferences> =
context.agendulaDataStore
@Provides
@Singleton
@CredentialsDataStore
fun provideCredentialsDataStore(@ApplicationContext context: Context): DataStore<Preferences> =
context.credentialsDataStore
@Provides
@Singleton
@SyncStateDataStore
fun provideSyncStateDataStore(@ApplicationContext context: Context): DataStore<Preferences> =
context.syncStateDataStore
@Provides
@Singleton
fun provideTasksDatabase(@ApplicationContext context: Context): TasksDatabase =
@@ -89,7 +149,6 @@ object DataProvideModule {
// backed-up `.db` does not. The backup rules carry all three files and
// the app checkpoints on ON_STOP.
.setJournalMode(RoomDatabase.JournalMode.WRITE_AHEAD_LOGGING)
.addMigrations(TasksDatabase.MIGRATION_1_2, TasksDatabase.MIGRATION_2_3, TasksDatabase.MIGRATION_3_4, TasksDatabase.MIGRATION_4_5, TasksDatabase.MIGRATION_5_6, TasksDatabase.MIGRATION_6_7)
.build()
/**
@@ -7,8 +7,9 @@ import dagger.hilt.components.SingletonComponent
import dagger.multibindings.Multibinds
/**
* Something a build variant runs on a genuine app open (not on a configuration
* change): sync in the `full` flavor, the demo seeder in debug builds.
* Something a build variant wants to run when the app is launched with [Intent].
* Release builds contribute none; the debug source set adds the demo seeder, so
* that class never ships.
*/
fun interface LaunchHook {
suspend fun onLaunch(intent: Intent)
@@ -17,6 +17,37 @@ annotation class IoDispatcher
@Retention(AnnotationRetention.BINARY)
annotation class ApplicationScope
/**
* Marks the DataStore holding **only** the Keystore-encrypted app passwords.
*
* A separate file from `agendula_prefs` on purpose: Auto Backup includes
* `datastore/`, and a restored ciphertext is permanently undecryptable because
* Keystore keys are non-exportable. Its own file is what lets the backup rules
* exclude the credentials and nothing else — excluding the whole database or
* all of DataStore would trade a latent bug for a live one.
*/
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class CredentialsDataStore
/**
* Marks the DataStore holding per-device **sync bookkeeping** — the quarantine
* counters and the full-reconciliation clock.
*
* Its own file for the same reason the credentials have one: Auto Backup
* includes `datastore/`, and every value in here is a statement about *this*
* device's conversation with a server. Restored onto a new install they are all
* lies, and two of them are dangerous — a restored "reconciled recently" makes
* the engine trust a sync token for another day, which is precisely the silently
* pruned change log the full path exists to catch, and a restored quarantine
* count silently skips resources that were never tried here.
*
* Not user data, so nothing is lost by excluding it.
*/
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class SyncStateDataStore
/**
* Marks the **external** provider's [de.jeanlucmakiola.agendula.data.tasks
* .TasksDataSource] — the OpenTasks/tasks.org path specifically, rather than
@@ -2,7 +2,6 @@ package de.jeanlucmakiola.agendula.data.export
import android.content.Context
import android.net.Uri
import android.provider.DocumentsContract
import androidx.documentfile.provider.DocumentFile
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
@@ -72,8 +71,10 @@ class ExportWriter @Inject constructor(
*/
suspend fun writeToTree(treeUri: Uri, documents: List<ExportDocument>): ExportResult =
withContext(io) {
val tree = openTree(treeUri)
runCatching {
val tree = DocumentFile.fromTreeUri(context, treeUri)
?: throw ExportFailedException(ExportFailure.FOLDER_UNAVAILABLE)
if (!tree.canWrite()) throw ExportFailedException(ExportFailure.FOLDER_NOT_WRITABLE)
val existing = tree.listFiles().associateBy { it.name }
documents.forEach { document ->
@@ -82,7 +83,7 @@ class ExportWriter @Inject constructor(
?: throw ExportFailedException(ExportFailure.CANNOT_CREATE_FILE)
write(file.uri, document.content)
}
}.getOrElse { throw failureIn(tree, it) }
}.getOrElse { throw asExportFailure(it) }
ExportResult(documents.size, documents.map { it.fileName })
}
@@ -94,150 +95,20 @@ class ExportWriter @Inject constructor(
*/
suspend fun writeZip(target: Uri, documents: List<ExportDocument>): ExportResult =
withContext(io) {
runCatching { zipInto(target, documents) }.getOrElse { throw asExportFailure(it) }
runCatching {
context.contentResolver.openOutputStream(target, "wt")?.use { raw ->
ZipOutputStream(raw.buffered()).use { zip ->
documents.forEach { document ->
zip.putNextEntry(ZipEntry(document.fileName))
zip.write(document.content)
zip.closeEntry()
}
}
} ?: throw ExportFailedException(ExportFailure.WRITE_FAILED)
}.getOrElse { throw asExportFailure(it) }
ExportResult(documents.size, documents.map { it.fileName })
}
/**
* Writes every document into a new zip inside [treeUri], under the [name]
* it picks given the folder's names, then deletes the files [prune] picks
* from those names and the one written (best effort: a file that will not
* go is left, and the write still counts). Only a file the folder held
* before the write can be pruned.
*
* Where the provider can rename, the zip is written under its [partialName]
* and renamed once complete, so a run that fails — or a process killed
* mid-write — never leaves a truncated file under a finished name.
* Elsewhere it is written under its name directly.
*/
suspend fun writeZipToTree(
treeUri: Uri,
documents: List<ExportDocument>,
name: (taken: Set<String>) -> String,
partialName: (String) -> String,
prune: (names: Set<String>, written: String) -> Collection<String> = { _, _ -> emptyList() },
): ExportResult = withContext(io) {
val tree = openTree(treeUri)
val (children, written) = runCatching {
val children = childDocuments(treeUri)
val fileName = name(children.keys)
check(fileName !in children) { "The name picked is taken" }
children to writeViaPartial(tree, fileName, partialName(fileName), documents)
}.getOrElse { throw failureIn(tree, it) }
prune(children.keys + written, written).forEach { pruned ->
val uri = children[pruned] ?: return@forEach
runCatching { DocumentsContract.deleteDocument(context.contentResolver, uri) }
}
ExportResult(documents.size, documents.map { it.fileName })
}
/** Writes the zip as [writeZipToTree] describes and returns the name the provider gave it. */
private fun writeViaPartial(
tree: DocumentFile,
fileName: String,
partialName: String,
documents: List<ExportDocument>,
): String {
val partial = tree.createFile(MIME_PARTIAL, partialName)
if (partial == null || !partial.supportsRename()) {
partial?.let { runCatching { it.delete() } }
return createAndZip(tree, MIME_ZIP, fileName, documents).name ?: fileName
}
zipOrDelete(partial, documents)
if (!runCatching { partial.renameTo(fileName) }.getOrDefault(false)) {
runCatching { partial.delete() }
return createAndZip(tree, MIME_ZIP, fileName, documents).name ?: fileName
}
return partial.name ?: fileName
}
private fun DocumentFile.supportsRename(): Boolean = runCatching {
context.contentResolver.query(uri, arrayOf(DocumentsContract.Document.COLUMN_FLAGS), null, null, null)
?.use { cursor ->
cursor.moveToFirst() &&
cursor.getInt(0) and DocumentsContract.Document.FLAG_SUPPORTS_RENAME != 0
} ?: false
}.getOrDefault(false)
private fun createAndZip(
tree: DocumentFile,
mime: String,
name: String,
documents: List<ExportDocument>,
): DocumentFile {
val file = tree.createFile(mime, name) ?: throw ExportFailedException(ExportFailure.CANNOT_CREATE_FILE)
zipOrDelete(file, documents)
return file
}
private fun zipOrDelete(file: DocumentFile, documents: List<ExportDocument>) {
try {
zipInto(file.uri, documents)
} catch (error: Exception) {
runCatching { file.delete() }
throw error
}
}
/** The folder's files by name, in one provider query rather than one per file. */
private fun childDocuments(treeUri: Uri): Map<String, Uri> {
val children = DocumentsContract.buildChildDocumentsUriUsingTree(
treeUri,
DocumentsContract.getTreeDocumentId(treeUri),
)
val projection = arrayOf(
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
)
return context.contentResolver.query(children, projection, null, null, null)?.use { cursor ->
buildMap {
while (cursor.moveToNext()) {
val name = cursor.getString(1) ?: continue
put(name, DocumentsContract.buildDocumentUriUsingTree(treeUri, cursor.getString(0)))
}
}
}.orEmpty()
}
/** [treeUri]'s folder; one that names no tree is as unavailable as a folder that is gone. */
private fun openTree(treeUri: Uri): DocumentFile {
val tree = try {
DocumentFile.fromTreeUri(context, treeUri)
} catch (e: IllegalArgumentException) {
throw ExportFailedException(ExportFailure.FOLDER_UNAVAILABLE, e)
}
return tree ?: throw ExportFailedException(ExportFailure.FOLDER_UNAVAILABLE)
}
/**
* [cause], a write into [tree] that failed, told apart by asking the folder
* only now: some providers answer no query on the folder itself yet take its
* files. An unmounted volume or a dead provider answers none.
*/
private fun failureIn(tree: DocumentFile, cause: Throwable): Throwable {
val failure = asExportFailure(cause)
// A revoked grant answers no query either, and stays lost access.
val exists = tree.exists()
return when {
exists && !tree.canWrite() -> ExportFailedException(ExportFailure.FOLDER_NOT_WRITABLE, cause)
failure is ExportFailedException && failure.failure == ExportFailure.LOST_ACCESS -> failure
!exists -> ExportFailedException(ExportFailure.FOLDER_UNAVAILABLE, cause)
else -> failure
}
}
private fun zipInto(target: Uri, documents: List<ExportDocument>) {
context.contentResolver.openOutputStream(target, "wt")?.use { raw ->
ZipOutputStream(raw.buffered()).use { zip ->
documents.forEach { document ->
zip.putNextEntry(ZipEntry(document.fileName))
zip.write(document.content)
zip.closeEntry()
}
}
} ?: throw ExportFailedException(ExportFailure.WRITE_FAILED)
}
private fun write(target: Uri, bytes: ByteArray) {
runCatching {
// "wt" truncates. Without it a shorter export leaves the tail of the
@@ -258,9 +129,5 @@ class ExportWriter @Inject constructor(
private companion object {
const val MIME_ICALENDAR = "text/calendar"
const val MIME_ZIP = "application/zip"
// Not a zip MIME type, so the provider keeps the suffix rather than adding ".zip".
const val MIME_PARTIAL = "application/octet-stream"
}
}
@@ -1,95 +0,0 @@
package de.jeanlucmakiola.agendula.data.prefs
import de.jeanlucmakiola.agendula.domain.DueWindow
import de.jeanlucmakiola.agendula.domain.Priority
import de.jeanlucmakiola.agendula.domain.SavedFilter
import de.jeanlucmakiola.agendula.domain.TagMatch
import java.net.URLDecoder
import java.net.URLEncoder
/**
* Stored form of the saved filters: one line per filter,
* `id|name|due|lists|tags|match|priority`, with name and tags URL-encoded and
* list ids qualified by the store they belong to (`OWN:3`), since each store
* numbers its lists on its own. Fixed once released — don't change without a
* data migration.
*/
internal object SavedFilterCodec {
/** The filters in [raw], with only the list ids of [mode]'s store. */
fun decode(raw: String?, mode: String): List<SavedFilter> =
lines(raw).mapNotNull { runCatching { decodeLine(it, mode) }.getOrNull() }
/** [raw] with [filter] replacing the line of the same id, or appended. */
fun upsert(raw: String?, filter: SavedFilter, mode: String): String {
val existing = lines(raw)
val index = existing.indexOfFirst { idOf(it) == filter.id }
// Keep the lists another store contributed, so switching stores and back
// doesn't widen a filter that was edited in between, unless "any list"
// was chosen here, which drops them on purpose.
val foreign = if (filter.anyList) {
emptyList()
} else {
existing.getOrNull(index)?.let(::fields)?.getOrNull(3)
?.let(::splitList)?.filterNot { it.startsWith("$mode:") }.orEmpty()
}
val line = encodeLine(filter, mode, foreign)
val updated = if (index >= 0) existing.toMutableList().also { it[index] = line } else existing + line
return updated.joinToString("\n")
}
/**
* [raw] without the lists of [mode]'s store [gone] names. A filter left
* without lists matches any, as a read of it already did with them gone.
*/
fun withoutLists(raw: String?, mode: String, gone: (Long) -> Boolean): String =
lines(raw).joinToString("\n") { line ->
val f = fields(line)
if (f.size < 7) return@joinToString line
val kept = splitList(f[3]).filterNot { it.startsWith("$mode:") && it.removePrefix("$mode:").toLongOrNull()?.let(gone) == true }
f.toMutableList().also { it[3] = kept.joinToString(",") }.joinToString("|")
}
fun remove(raw: String?, id: Long): String = lines(raw).filterNot { idOf(it) == id }.joinToString("\n")
private fun lines(raw: String?): List<String> = raw.orEmpty().split('\n').filter { it.isNotBlank() }
private fun fields(line: String): List<String> = line.split('|')
private fun idOf(line: String): Long? = fields(line).firstOrNull()?.toLongOrNull()
private fun splitList(value: String): List<String> = value.split(',').filter { it.isNotEmpty() }
private fun encodeLine(filter: SavedFilter, mode: String, foreignLists: List<String>): String =
listOf(
filter.id.toString(),
encode(filter.name),
filter.due.sorted().joinToString(",") { it.name },
(filter.listIds.sorted().map { "$mode:$it" } + foreignLists).joinToString(","),
filter.tags.sorted().joinToString(",") { encode(it) },
filter.tagMatch.name,
filter.minPriority.name,
).joinToString("|")
private fun decodeLine(line: String, mode: String): SavedFilter? {
val f = fields(line)
if (f.size < 7) return null
val id = f[0].toLongOrNull() ?: return null
val lists = splitList(f[3])
val here = lists.filter { it.startsWith("$mode:") }.mapNotNull { it.removePrefix("$mode:").toLongOrNull() }.toSet()
return SavedFilter(
id = id,
name = decode(f[1]),
due = splitList(f[2]).mapNotNull { runCatching { DueWindow.valueOf(it) }.getOrNull() }.toSet(),
listIds = here,
listsElsewhere = lists.any { !it.startsWith("$mode:") },
tags = splitList(f[4]).map(::decode).toSet(),
tagMatch = runCatching { TagMatch.valueOf(f[5]) }.getOrDefault(TagMatch.ANY),
minPriority = runCatching { Priority.valueOf(f[6]) }.getOrDefault(Priority.NONE),
)
}
private fun encode(value: String): String = URLEncoder.encode(value, Charsets.UTF_8.name())
private fun decode(value: String): String = URLDecoder.decode(value, Charsets.UTF_8.name())
}
@@ -1,7 +1,6 @@
package de.jeanlucmakiola.agendula.data.prefs
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.MutablePreferences
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
@@ -11,57 +10,22 @@ import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.core.stringSetPreferencesKey
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
import de.jeanlucmakiola.agendula.data.tasks.StorageMode
import de.jeanlucmakiola.agendula.domain.DefaultDueDate
import de.jeanlucmakiola.agendula.domain.DefaultStartDate
import de.jeanlucmakiola.agendula.domain.NewTaskDates
import de.jeanlucmakiola.agendula.domain.SavedFilter
import de.jeanlucmakiola.agendula.domain.newTaskDates
import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.TaskFilter
import de.jeanlucmakiola.agendula.domain.TaskForm
import de.jeanlucmakiola.agendula.domain.calendarDate
import de.jeanlucmakiola.agendula.domain.TaskFormField
import de.jeanlucmakiola.agendula.domain.TaskReminder
import de.jeanlucmakiola.agendula.domain.TaskGroupKey
import de.jeanlucmakiola.agendula.domain.TaskGrouping
import de.jeanlucmakiola.agendula.domain.TaskSection
import de.jeanlucmakiola.agendula.domain.groupingKey
import de.jeanlucmakiola.agendula.domain.asTaskReminder
import de.jeanlucmakiola.agendula.domain.asReminderLead
import de.jeanlucmakiola.agendula.domain.TaskSortOrder
import de.jeanlucmakiola.agendula.domain.SmartList
import de.jeanlucmakiola.agendula.domain.UpcomingRange
import de.jeanlucmakiola.agendula.domain.withinUpcoming
import de.jeanlucmakiola.floret.reminders.ReminderLead
import de.jeanlucmakiola.floret.reminders.ReminderOverride
import de.jeanlucmakiola.floret.reminders.ReminderOverrideCodec
import de.jeanlucmakiola.floret.reminders.applyReminderOverride
import de.jeanlucmakiola.floret.reminders.normalizeReminders
import de.jeanlucmakiola.floret.reminders.reminderLeadsFor
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import java.time.DayOfWeek
import java.time.ZoneId
import java.time.LocalDate
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.time.Clock
import kotlin.time.Instant
/** [BLACK] is dark with pure-black surfaces, for AMOLED screens. */
enum class ThemeMode {
SYSTEM, LIGHT, DARK, BLACK;
fun isDark(systemDark: Boolean): Boolean = when (this) {
SYSTEM -> systemDark
LIGHT -> false
DARK, BLACK -> true
}
val isPureBlack: Boolean get() = this == BLACK
}
enum class ThemeMode { SYSTEM, LIGHT, DARK }
/** Clock convention: AUTO follows the device's 24-hour switch. */
enum class TimeFormatPref { AUTO, TWELVE_HOUR, TWENTY_FOUR_HOUR }
@@ -72,18 +36,7 @@ fun TimeFormatPref.is24Hour(systemIs24Hour: Boolean): Boolean = when (this) {
TimeFormatPref.TWENTY_FOUR_HOUR -> true
}
/** What [Settings.viewOf] shows of a view's tasks, and whether the Upcoming range left some out. */
data class SmartView(val tasks: List<Task>, val hiddenByRange: Boolean)
/** A list's own take on [Settings.persistentReminders]; [INHERIT] follows the app setting. */
enum class ListPersistence { INHERIT, ALWAYS, NEVER }
/** How much of a task's description a due reminder shows when expanded. */
enum class ReminderDescription { HIDDEN, SHORT, FULL }
const val DEFAULT_SNOOZE_MINUTES = 10
/** Done starts folded away, to keep the open tasks in focus. */
val DEFAULT_COLLAPSED_GROUPS: Set<String> = setOf(TaskGroupKey.Section(TaskSection.COMPLETED).id)
/** The snooze lengths Settings offers. */
val SNOOZE_PRESETS = listOf(5, 10, 15, 30, 60)
@@ -102,16 +55,14 @@ data class Settings(
val dynamicColor: Boolean = true,
/** The list a new task defaults to; `null` = first available. */
val defaultListId: Long? = null,
/** Default reminders (0 before due = at due time); empty = none. */
val defaultReminders: List<ReminderLead> = listOf(ReminderLead(0)),
/** Default reminders for all-day tasks, in whole days, rung at [allDayReminderMinuteOfDay]. */
val defaultAllDayReminders: List<ReminderLead> = listOf(ReminderLead(0)),
/** Default reminders, as minutes before due (0 = at due time); empty = none. */
val defaultReminderMinutes: List<Int> = listOf(0),
/** Default reminders for all-day tasks, as days-scale minutes before [allDayReminderMinuteOfDay]. */
val defaultAllDayReminderMinutes: List<Int> = listOf(0),
/** Local time (minutes from midnight) an all-day task's reminder counts back from. */
val allDayReminderMinuteOfDay: Int = DEFAULT_ALL_DAY_REMINDER_MINUTE,
/** Master switch for due reminders; off clears every scheduled alarm. */
val remindersEnabled: Boolean = true,
/** Ring at once when a save puts a task's reminder in the past, instead of leaving it out (#106). */
val remindPastOnSave: Boolean = false,
/** Whether the inline "add a subtask" row shows on expanded task-list groups. */
val showAddSubtaskRow: Boolean = true,
/**
@@ -121,23 +72,18 @@ data class Settings(
*/
val bottomAddBar: Boolean = false,
/**
* Per-list overrides of [defaultReminders]: a list present in the map
* Per-list overrides of [defaultReminderMinutes]: a list present in the map
* overrides the global default (an empty list = no reminder); absent =
* inherit.
*/
val perListReminderOverride: Map<Long, List<ReminderLead>> = emptyMap(),
/** Per-list overrides of [defaultAllDayReminders], same shape as [perListReminderOverride]. */
val perListAllDayReminderOverride: Map<Long, List<ReminderLead>> = emptyMap(),
val perListReminderOverride: Map<Long, List<Int>> = emptyMap(),
/** Per-list overrides of [defaultAllDayReminderMinutes], same shape as [perListReminderOverride]. */
val perListAllDayReminderOverride: Map<Long, List<Int>> = emptyMap(),
/** Optional edit-form fields shown by default; the rest sit behind "More fields". */
val defaultEditFields: Set<TaskFormField> = emptySet(),
val sortOrder: TaskSortOrder = TaskSortOrder.DUE,
/** How long a reminder's "Snooze" action puts it off. */
val snoozeMinutes: Int = DEFAULT_SNOOZE_MINUTES,
val reminderDescription: ReminderDescription = ReminderDescription.SHORT,
/** A swiped-away reminder comes straight back until the task is done or snoozed. */
val persistentReminders: Boolean = false,
/** Lists of the current store that override [persistentReminders]; [ListPersistence.INHERIT] is never stored. */
val perListPersistentReminders: Map<Long, ListPersistence> = emptyMap(),
val timeFormat: TimeFormatPref = TimeFormatPref.AUTO,
/** The first day of the week; `null` follows the locale. */
val weekStart: DayOfWeek? = null,
@@ -149,123 +95,22 @@ data class Settings(
val pushEnabled: Boolean = true,
/** Lists of the current store whose tasks the smart lists (and their counts) leave out. */
val hiddenFromSmartLists: Set<Long> = emptySet(),
/** The due date a new task's form starts with. */
val defaultDueDate: DefaultDueDate = DefaultDueDate.NONE,
/** The start date a new task's form starts with. */
val defaultStartDate: DefaultStartDate = DefaultStartDate.NONE,
/** Ids of the task-list groups folded away ([TaskGroupKey.id]); Done starts folded. */
val collapsedGroups: Set<String> = DEFAULT_COLLAPSED_GROUPS,
/** Each view's chosen grouping, keyed by [groupingKey]; absent = [TaskGrouping.DUE]. */
val groupings: Map<String, TaskGrouping> = emptyMap(),
/** How far ahead the Upcoming smart list reaches. */
val upcomingRange: UpcomingRange = UpcomingRange.ALL,
) {
/** Whether a save rings the reminders it puts in the past (#106). */
val ringsPastOnSave: Boolean get() = remindersEnabled && remindPastOnSave
fun groupingFor(filter: TaskFilter): TaskGrouping =
filter.groupingKey()?.let { groupings[it] } ?: TaskGrouping.DUE
/**
* [tasks] as [filter] shows them: a smart list drops the lists kept out of it,
* and Upcoming whatever is due past [upcomingRange].
*/
fun visibleIn(
filter: TaskFilter,
tasks: List<Task>,
now: Instant = Clock.System.now(),
zone: ZoneId = ZoneId.systemDefault(),
): List<Task> = viewOf(filter, tasks, now, zone).tasks
/** [visibleIn], and whether [upcomingRange] kept any of [tasks] out, in one pass. */
fun viewOf(
filter: TaskFilter,
tasks: List<Task>,
now: Instant = Clock.System.now(),
zone: ZoneId = ZoneId.systemDefault(),
): SmartView {
if (filter !is TaskFilter.Smart) return SmartView(tasks, hiddenByRange = false)
val end = if (filter.list == SmartList.UPCOMING) upcomingRange.end(now, zone) else null
if (hiddenFromSmartLists.isEmpty() && end == null) return SmartView(tasks, hiddenByRange = false)
var hiddenByRange = false
val kept = tasks.filter { task ->
if (task.listId in hiddenFromSmartLists) return@filter false
withinUpcoming(task, end, zone).also { if (!it) hiddenByRange = true }
/** [tasks] as [filter] shows them: a smart list drops the lists kept out of it. */
fun visibleIn(filter: TaskFilter, tasks: List<Task>): List<Task> =
if (filter is TaskFilter.Smart && hiddenFromSmartLists.isNotEmpty()) {
tasks.filter { it.listId !in hiddenFromSmartLists }
} else {
tasks
}
return SmartView(kept, hiddenByRange)
}
/** The lead times for a task in [listId]: its override if set, else the global default. */
fun reminderLeadsFor(listId: Long): List<ReminderLead> =
perListReminderOverride.reminderLeadsFor(listId, defaultReminders)
fun reminderLeadsFor(listId: Long): List<Int> =
perListReminderOverride.reminderLeadsFor(listId, defaultReminderMinutes)
/** The lead times for an all-day task in [listId]. */
fun allDayReminderLeadsFor(listId: Long): List<ReminderLead> =
perListAllDayReminderOverride.reminderLeadsFor(listId, defaultAllDayReminders)
/** The default reminders a task in [listId] takes — the one rule for which default applies. */
fun defaultRemindersFor(listId: Long, allDay: Boolean): List<TaskReminder> =
(if (allDay) allDayReminderLeadsFor(listId) else reminderLeadsFor(listId)).map { it.asTaskReminder() }
/** Whether [listId] has its own default reminders for [allDay] tasks (an override, "none" included). */
fun hasOwnReminders(listId: Long, allDay: Boolean): Boolean =
listId in (if (allDay) perListAllDayReminderOverride else perListReminderOverride)
/**
* The dates a new task starts with, given the [presetDue] of the view it is
* added from and whether that view would [show] it. A subtask takes no
* default due, which could land after its parent's.
*/
fun defaultNewTaskDates(
today: LocalDate,
now: Instant,
presetDue: LocalDate? = null,
subtask: Boolean = false,
show: (NewTaskDates) -> Boolean = { true },
): NewTaskDates =
newTaskDates(if (subtask) DefaultDueDate.NONE else defaultDueDate, defaultStartDate, presetDue, today, now, show)
/** A title-only task for [listId], optionally under [parentId], with the default dates. */
fun quickTask(
title: String,
listId: Long,
parentId: Long? = null,
now: Instant = Clock.System.now(),
today: LocalDate = now.calendarDate(allDay = false),
): TaskForm {
val dates = defaultNewTaskDates(today, now, subtask = parentId != null)
return TaskForm(
title = title,
listId = listId,
parentId = parentId,
start = dates.start,
due = dates.due,
isAllDay = dates.isAllDay,
startsNow = dates.start == now,
)
}
fun persistenceFor(listId: Long): ListPersistence = perListPersistentReminders[listId] ?: ListPersistence.INHERIT
/** Whether a reminder for a task in [listId] is persistent: its list's override, else the app setting. */
fun persistentRemindersFor(listId: Long): Boolean = remindersEnabled && when (persistenceFor(listId)) {
ListPersistence.INHERIT -> persistentReminders
ListPersistence.ALWAYS -> true
ListPersistence.NEVER -> false
}
/** Whether any list's reminders can be persistent. */
val anyPersistentReminders: Boolean
get() = remindersEnabled &&
(persistentReminders || perListPersistentReminders.containsValue(ListPersistence.ALWAYS))
/** [anyPersistentReminders], counting a list's own [ListPersistence.ALWAYS] only for one of [present]. */
fun anyPersistentReminders(present: Set<Long>): Boolean = remindersEnabled &&
(persistentReminders || perListPersistentReminders.any { (id, p) -> p == ListPersistence.ALWAYS && id in present })
/** Whether [listId] has its own default reminders for timed or all-day tasks. */
fun hasOwnReminders(listId: Long): Boolean =
hasOwnReminders(listId, allDay = false) || hasOwnReminders(listId, allDay = true)
fun allDayReminderLeadsFor(listId: Long): List<Int> =
perListAllDayReminderOverride.reminderLeadsFor(listId, defaultAllDayReminderMinutes)
}
/** App preferences, backed by DataStore. Mirrors Calendula's prefs shape. */
@@ -275,165 +120,52 @@ class SettingsPrefs @Inject constructor(
private val resolver: ProviderResolver,
) {
val settings: Flow<Settings> = dataStore.data.map { p ->
val scope = scopeOf(p)
Settings(
themeMode = p[THEME_MODE]?.let { runCatching { ThemeMode.valueOf(it) }.getOrNull() }
?: ThemeMode.SYSTEM,
dynamicColor = p[DYNAMIC_COLOR] ?: true,
defaultListId = p[DEFAULT_LIST_ID]?.takeIf { it > 0 },
// The single lead of earlier versions carries over until a list is saved.
defaultReminders = p[DEFAULT_REMINDERS]?.let(::parseLeads)
?: listOf(ReminderLead(p[REMINDER_LEAD] ?: 0)),
defaultAllDayReminders = p[DEFAULT_ALL_DAY_REMINDERS]?.let(::parseLeads)?.inWholeDays()
?: listOf(ReminderLead(0)),
defaultReminderMinutes = p[DEFAULT_REMINDERS]?.let(::parseMinutes)
?: listOf(p[REMINDER_LEAD] ?: 0),
defaultAllDayReminderMinutes = p[DEFAULT_ALL_DAY_REMINDERS]?.let(::parseMinutes) ?: listOf(0),
allDayReminderMinuteOfDay = p[ALL_DAY_REMINDER_MINUTE]?.takeIf { it in 0 until 24 * 60 }
?: DEFAULT_ALL_DAY_REMINDER_MINUTE,
remindersEnabled = p[REMINDERS_ENABLED] ?: true,
remindPastOnSave = p[REMIND_PAST_ON_SAVE] ?: false,
showAddSubtaskRow = p[SHOW_ADD_SUBTASK_ROW] ?: true,
bottomAddBar = p[BOTTOM_ADD_BAR] ?: false,
perListReminderOverride = reminderCodec.parseLeads(p[LIST_REMINDER_OVERRIDE]),
perListAllDayReminderOverride = reminderCodec.parseLeads(p[LIST_ALL_DAY_REMINDER_OVERRIDE])
.mapValues { it.value.inWholeDays() },
perListReminderOverride = reminderCodec.parse(p[LIST_REMINDER_OVERRIDE]),
perListAllDayReminderOverride = reminderCodec.parse(p[LIST_ALL_DAY_REMINDER_OVERRIDE]),
defaultEditFields = p[DEFAULT_EDIT_FIELDS].orEmpty()
.mapNotNull { name -> runCatching { TaskFormField.valueOf(name) }.getOrNull() }
.toSet(),
sortOrder = p[SORT_ORDER]?.let { runCatching { TaskSortOrder.valueOf(it) }.getOrNull() }
?: TaskSortOrder.DUE,
snoozeMinutes = p[SNOOZE_MINUTES]?.takeIf { it > 0 } ?: DEFAULT_SNOOZE_MINUTES,
reminderDescription = p[REMINDER_DESCRIPTION]
?.let { runCatching { ReminderDescription.valueOf(it) }.getOrNull() }
?: ReminderDescription.SHORT,
persistentReminders = p[PERSISTENT_REMINDERS] ?: false,
perListPersistentReminders = parseListPersistence(p[LIST_PERSISTENT_REMINDERS].orEmpty(), scope),
timeFormat = p[TIME_FORMAT]?.let { runCatching { TimeFormatPref.valueOf(it) }.getOrNull() }
?: TimeFormatPref.AUTO,
autofocusTitle = p[AUTOFOCUS_TITLE] ?: true,
syncIntervalMinutes = p[SYNC_INTERVAL]?.takeIf { it == 0 || it >= 15 } ?: DEFAULT_SYNC_INTERVAL_MINUTES,
weekStart = p[WEEK_START]?.let { runCatching { DayOfWeek.valueOf(it) }.getOrNull() },
pushEnabled = p[PUSH_ENABLED] ?: true,
hiddenFromSmartLists = scope.let { mode ->
hiddenFromSmartLists = modeOf(p).name.let { mode ->
p[SMART_LIST_HIDDEN].orEmpty()
.mapNotNull { entry -> entry.substringAfter("$mode:", "").toLongOrNull() }
.toSet()
},
defaultDueDate = p[DEFAULT_DUE_DATE]?.let { runCatching { DefaultDueDate.valueOf(it) }.getOrNull() }
?: DefaultDueDate.NONE,
// The "start today" switch of earlier versions carries over until a start is picked.
defaultStartDate = p[DEFAULT_START_DATE]?.let { runCatching { DefaultStartDate.valueOf(it) }.getOrNull() }
?: if (p[DEFAULT_START_TODAY] == true) DefaultStartDate.TODAY else DefaultStartDate.NONE,
collapsedGroups = (p[COLLAPSED_SECTIONS] ?: DEFAULT_COLLAPSED_GROUPS)
.mapNotNullTo(HashSet()) { unscopeListKey(it, scope) },
groupings = decodeGroupings(p[GROUPINGS].orEmpty(), scope),
upcomingRange = p[UPCOMING_RANGE]?.let { runCatching { UpcomingRange.valueOf(it) }.getOrNull() }
?: UpcomingRange.ALL,
)
}.distinctUntilChanged() // Other stores write this DataStore too.
/** Folds or unfolds the group with [id]; day groups that have passed are dropped on the way. */
suspend fun setGroupCollapsed(id: String, collapsed: Boolean) = dataStore.edit { p ->
val stored = scopeListKey(id, claimedScope(p))
val current = dropPastDays(p[COLLAPSED_SECTIONS] ?: DEFAULT_COLLAPSED_GROUPS, LocalDate.now())
p[COLLAPSED_SECTIONS] = if (collapsed) current + stored else current - stored
}
/** Remembers [grouping] for [filter]'s view. */
suspend fun setGrouping(filter: TaskFilter, grouping: TaskGrouping) = dataStore.edit { p ->
val key = filter.groupingKey()?.let { scopeListKey(it, claimedScope(p)) } ?: return@edit
val kept = p[GROUPINGS].orEmpty().filterTo(HashSet()) { it.substringAfter(GROUPING_SEPARATOR) != key }
p[GROUPINGS] = if (grouping == TaskGrouping.DUE) kept else kept + "${grouping.name}$GROUPING_SEPARATOR$key"
}
suspend fun setUpcomingRange(range: UpcomingRange) = dataStore.edit { it[UPCOMING_RANGE] = range.name }
suspend fun setSortOrder(order: TaskSortOrder) = dataStore.edit { it[SORT_ORDER] = order.name }
suspend fun setSnoozeMinutes(minutes: Int) = dataStore.edit { it[SNOOZE_MINUTES] = minutes.coerceAtLeast(1) }
suspend fun setReminderDescription(pref: ReminderDescription) =
dataStore.edit { it[REMINDER_DESCRIPTION] = pref.name }
suspend fun setPersistentReminders(enabled: Boolean) = dataStore.edit { it[PERSISTENT_REMINDERS] = enabled }
/** Sets (or clears, via [ListPersistence.INHERIT]) a list's persistent-reminder override in the current store. */
suspend fun setListPersistence(listId: Long, persistence: ListPersistence) = dataStore.edit { p ->
val prefix = listPersistencePrefix(claimedScope(p), listId)
val rest = p[LIST_PERSISTENT_REMINDERS].orEmpty().filterNotTo(HashSet()) { it.startsWith(prefix) }
p[LIST_PERSISTENT_REMINDERS] = if (persistence == ListPersistence.INHERIT) rest else rest + "$prefix${persistence.name}"
}
/**
* Drops what was remembered about [listIds], deleted from [store], so a later
* list given one of their ids starts fresh. The one way to forget a list
* explicitly: [forgetListsExcept], run on every read of the lists, cannot see
* the last list deleted (a read finding none proves nothing) nor an account's
* lists removed while another store is current. The reminder overrides are
* keyed by bare id, shared by every store, so they stay.
*/
suspend fun forgetDeletedLists(listIds: Collection<Long>, store: StorageMode) = dataStore.edit { p ->
val mode = claimedScope(p, withAuthority(store))
val prefixes = listIds.map { listPersistencePrefix(mode, it) }
val hidden = listIds.mapTo(HashSet()) { "$mode:$it" }
val keys = listIds.mapTo(HashSet()) { scopeListKey("${TaskGroupKey.LIST_PREFIX}$it", mode) }
fun drop(key: Preferences.Key<Set<String>>, gone: (String) -> Boolean) {
val entries = p[key] ?: return
val kept = entries.filterNotTo(HashSet(), gone)
if (kept.size != entries.size) p[key] = kept
}
drop(LIST_PERSISTENT_REMINDERS) { entry -> prefixes.any(entry::startsWith) }
drop(SMART_LIST_HIDDEN) { it in hidden }
drop(GROUPINGS) { it.substringAfter(GROUPING_SEPARATOR) in keys }
drop(COLLAPSED_SECTIONS) { it in keys }
forgetInFilters(p, store, mode) { it in listIds }
}
/**
* Drops what was remembered about [store]'s lists other than [present], the
* ones a successful read of it, through [authority] for an external one,
* just found. Another store's or provider's entries, and the reminder
* overrides keyed by bare id, stay.
*/
suspend fun forgetListsExcept(store: StorageMode, authority: String?, present: Set<Long>) = dataStore.edit { p ->
val mode = claimedScope(p, store to authority)
fun prune(key: Preferences.Key<Set<String>>, kind: ListEntry) {
val entries = p[key] ?: return
val kept = withoutGoneLists(entries, kind, mode, present)
if (kept.size != entries.size) p[key] = kept
}
prune(LIST_PERSISTENT_REMINDERS, ListEntry.PERSISTENCE)
prune(SMART_LIST_HIDDEN, ListEntry.HIDDEN)
prune(GROUPINGS, ListEntry.GROUPING)
prune(COLLAPSED_SECTIONS, ListEntry.COLLAPSED)
forgetInFilters(p, store, mode) { it !in present }
}
/**
* Drops the lists [gone] names from the saved filters. Those keep a store's
* lists by its bare name, so only the store that owns the bare entries, as
* [mode] says, prunes them.
*/
private fun forgetInFilters(p: MutablePreferences, store: StorageMode, mode: String, gone: (Long) -> Boolean) {
if (mode != store.name) return
val raw = p[SAVED_FILTERS] ?: return
val kept = SavedFilterCodec.withoutLists(raw, store.name, gone)
if (kept != raw) p[SAVED_FILTERS] = kept
}
suspend fun setSyncIntervalMinutes(minutes: Int) = dataStore.edit { it[SYNC_INTERVAL] = minutes }
suspend fun setPushEnabled(enabled: Boolean) = dataStore.edit { it[PUSH_ENABLED] = enabled }
suspend fun setAutofocusTitle(enabled: Boolean) = dataStore.edit { it[AUTOFOCUS_TITLE] = enabled }
suspend fun setDefaultDueDate(due: DefaultDueDate) = dataStore.edit { it[DEFAULT_DUE_DATE] = due.name }
suspend fun setDefaultStartDate(start: DefaultStartDate) = dataStore.edit {
it[DEFAULT_START_DATE] = start.name
it.remove(DEFAULT_START_TODAY)
}
suspend fun setRemindPastOnSave(enabled: Boolean) = dataStore.edit { it[REMIND_PAST_ON_SAVE] = enabled }
suspend fun setTimeFormat(pref: TimeFormatPref) = dataStore.edit { it[TIME_FORMAT] = pref.name }
suspend fun setWeekStart(day: DayOfWeek?) = dataStore.edit {
@@ -446,12 +178,12 @@ class SettingsPrefs @Inject constructor(
if (id == null) it.remove(DEFAULT_LIST_ID) else it[DEFAULT_LIST_ID] = id
}
suspend fun setDefaultReminders(leads: List<ReminderLead>) = dataStore.edit {
it[DEFAULT_REMINDERS] = leads.normalizeReminders().joinToString(",") { lead -> lead.toToken() }
suspend fun setDefaultReminderMinutes(minutes: List<Int>) = dataStore.edit {
it[DEFAULT_REMINDERS] = minutes.normalizeReminders().joinToString(",")
}
suspend fun setDefaultAllDayReminders(leads: List<ReminderLead>) = dataStore.edit {
it[DEFAULT_ALL_DAY_REMINDERS] = leads.normalizeReminders().joinToString(",") { lead -> lead.toToken() }
suspend fun setDefaultAllDayReminderMinutes(minutes: List<Int>) = dataStore.edit {
it[DEFAULT_ALL_DAY_REMINDERS] = minutes.normalizeReminders().joinToString(",")
}
suspend fun setAllDayReminderMinuteOfDay(minuteOfDay: Int) =
@@ -483,51 +215,6 @@ class SettingsPrefs @Inject constructor(
/** The store list ids belong to; each store numbers its lists on its own. */
private fun modeOf(p: Preferences): StorageMode = storedMode(p[STORAGE_MODE]) ?: resolver.autoMode()
/**
* What the current store's list entries are stored under; see [listScope].
* Asks the resolver, a PackageManager lookup, only when the answer depends
* on it: every write to this file maps the settings again.
*/
private fun scopeOf(p: Preferences): String {
val stored = storedMode(p[STORAGE_MODE])
val owner = p[EXTERNAL_LISTS_OWNER]
if (stored == StorageMode.OWN || (stored == StorageMode.EXTERNAL && owner == null)) return stored.name
val (store, authority) = resolver.active(stored)
return listScope(store, authority, owner)
}
/** The store [p] names, or the resolver's guess, with its provider. */
private fun activeIn(p: Preferences): Pair<StorageMode, String?> = resolver.active(storedMode(p[STORAGE_MODE]))
/** [store]'s scope, first making its provider the owner of the bare external entries if none is yet. */
private fun claimedScope(p: MutablePreferences, store: Pair<StorageMode, String?> = activeIn(p)): String {
val (mode, authority) = store
if (mode == StorageMode.EXTERNAL && authority != null && p[EXTERNAL_LISTS_OWNER] == null) p[EXTERNAL_LISTS_OWNER] = authority
return listScope(mode, authority, p[EXTERNAL_LISTS_OWNER])
}
private fun withAuthority(store: StorageMode): Pair<StorageMode, String?> =
store to if (store == StorageMode.EXTERNAL) resolver.resolveExternal()?.authority else null
/**
* What tells the current store's task ids apart from another store's or
* provider's, as persistent reminders and reminder actions record it: the
* list scope, lower-cased, so the bare `own` and `external` of earlier
* versions stay their store's.
*/
suspend fun storeScope(): String = scopeOf(dataStore.data.first()).lowercase()
/** [storeScope], first making the current provider the owner of the bare external entries if none is yet. */
suspend fun claimStoreScope(): String {
val p = dataStore.data.first()
if (p[EXTERNAL_LISTS_OWNER] != null) return scopeOf(p).lowercase()
val store = activeIn(p)
if (store.first != StorageMode.EXTERNAL || store.second == null) return store.first.name.lowercase()
var scope = ""
dataStore.edit { scope = claimedScope(it, store) }
return scope.lowercase()
}
suspend fun setStorageMode(mode: StorageMode) = dataStore.edit { it[STORAGE_MODE] = mode.name }
/**
@@ -549,54 +236,24 @@ class SettingsPrefs @Inject constructor(
/** Set (or clear, via [ReminderOverride.Inherit]) a list's reminder override. */
suspend fun setListReminderOverride(listId: Long, override: ReminderOverride) = dataStore.edit { p ->
val current = reminderCodec.parseLeads(p[LIST_REMINDER_OVERRIDE]).toMutableMap()
val current = reminderCodec.parse(p[LIST_REMINDER_OVERRIDE]).toMutableMap()
current.applyReminderOverride(listId, override)
p[LIST_REMINDER_OVERRIDE] = reminderCodec.serializeLeads(current)
p[LIST_REMINDER_OVERRIDE] = reminderCodec.serialize(current)
}
/** Set (or clear) a list's all-day reminder override. */
suspend fun setListAllDayReminderOverride(listId: Long, override: ReminderOverride) = dataStore.edit { p ->
val current = reminderCodec.parseLeads(p[LIST_ALL_DAY_REMINDER_OVERRIDE]).toMutableMap()
val current = reminderCodec.parse(p[LIST_ALL_DAY_REMINDER_OVERRIDE]).toMutableMap()
current.applyReminderOverride(listId, override)
p[LIST_ALL_DAY_REMINDER_OVERRIDE] = reminderCodec.serializeLeads(current)
p[LIST_ALL_DAY_REMINDER_OVERRIDE] = reminderCodec.serialize(current)
}
suspend fun setHiddenFromSmartLists(listId: Long, hidden: Boolean) = dataStore.edit { p ->
val entry = "${claimedScope(p)}:$listId"
val entry = "${modeOf(p).name}:$listId"
val current = p[SMART_LIST_HIDDEN].orEmpty()
p[SMART_LIST_HIDDEN] = if (hidden) current + entry else current - entry
}
/** The saved filters, oldest first, with the list ids of the current store. */
val savedFilters: Flow<List<SavedFilter>> =
dataStore.data.map { p -> p[SAVED_FILTERS] to p[STORAGE_MODE] }
.distinctUntilChanged()
.map { (raw, mode) -> SavedFilterCodec.decode(raw, (storedMode(mode) ?: resolver.autoMode()).name) }
.distinctUntilChanged()
/** One saved filter; `null` while it doesn't exist. */
fun savedFilter(id: Long): Flow<SavedFilter?> =
savedFilters.map { all -> all.firstOrNull { it.id == id } }.distinctUntilChanged()
/** Store [filter]; an id of 0 makes a new one. Returns the filter's id. */
suspend fun saveFilter(filter: SavedFilter): Long {
var id = filter.id
dataStore.edit { p ->
if (id <= 0) {
id = p[SAVED_FILTER_NEXT_ID] ?: 1L
p[SAVED_FILTER_NEXT_ID] = id + 1
}
p[SAVED_FILTERS] = SavedFilterCodec.upsert(p[SAVED_FILTERS], filter.copy(id = id), modeOf(p).name)
}
return id
}
suspend fun deleteFilter(id: Long) = dataStore.edit { p ->
p[SAVED_FILTERS] = SavedFilterCodec.remove(p[SAVED_FILTERS], id)
val key = TaskFilter.Saved(id).groupingKey()
p[GROUPINGS] = p[GROUPINGS].orEmpty().filterTo(HashSet()) { it.substringAfter(GROUPING_SEPARATOR) != key }
}
suspend fun setDefaultEditFields(fields: Set<TaskFormField>) = dataStore.edit {
it[DEFAULT_EDIT_FIELDS] = fields.mapTo(mutableSetOf()) { field -> field.name }
}
@@ -615,31 +272,16 @@ class SettingsPrefs @Inject constructor(
val BOTTOM_ADD_BAR = booleanPreferencesKey("bottom_add_bar")
val ONBOARDING_DONE = booleanPreferencesKey("reminder_onboarding_done")
val STORAGE_MODE = stringPreferencesKey("storage_mode")
/** The external provider the bare `EXTERNAL` list entries belong to. */
val EXTERNAL_LISTS_OWNER = stringPreferencesKey("external_lists_owner")
val LIST_REMINDER_OVERRIDE = stringPreferencesKey("list_reminder_override")
val DEFAULT_EDIT_FIELDS = stringSetPreferencesKey("default_edit_fields")
val SORT_ORDER = stringPreferencesKey("sort_order")
val SNOOZE_MINUTES = intPreferencesKey("snooze_minutes")
val REMINDER_DESCRIPTION = stringPreferencesKey("reminder_description")
val PERSISTENT_REMINDERS = booleanPreferencesKey("persistent_reminders")
val LIST_PERSISTENT_REMINDERS = stringSetPreferencesKey("list_persistent_reminders")
val TIME_FORMAT = stringPreferencesKey("time_format")
val WEEK_START = stringPreferencesKey("week_start")
val AUTOFOCUS_TITLE = booleanPreferencesKey("autofocus_title")
val SYNC_INTERVAL = intPreferencesKey("sync_interval_minutes")
val PUSH_ENABLED = booleanPreferencesKey("push_enabled")
val SMART_LIST_HIDDEN = stringSetPreferencesKey("smart_list_hidden")
val DEFAULT_START_TODAY = booleanPreferencesKey("default_start_today")
val DEFAULT_START_DATE = stringPreferencesKey("default_start_date")
val DEFAULT_DUE_DATE = stringPreferencesKey("default_due_date")
val REMIND_PAST_ON_SAVE = booleanPreferencesKey("remind_past_on_save")
val COLLAPSED_SECTIONS = stringSetPreferencesKey("collapsed_sections")
val UPCOMING_RANGE = stringPreferencesKey("upcoming_range")
val GROUPINGS = stringSetPreferencesKey("task_groupings")
val SAVED_FILTERS = stringPreferencesKey("saved_filters")
val SAVED_FILTER_NEXT_ID = longPreferencesKey("saved_filter_next_id")
}
}
@@ -650,100 +292,6 @@ class SettingsPrefs @Inject constructor(
*/
private val reminderCodec = ReminderOverrideCodec.DEFAULT
private fun listPersistencePrefix(mode: String, listId: Long) = "$mode:$listId="
/** `MODE:listId=ALWAYS|NEVER` entries, [mode]'s only. */
internal fun parseListPersistence(entries: Set<String>, mode: String): Map<Long, ListPersistence> =
entries.mapNotNull { entry ->
val (id, value) = entry.removePrefix("$mode:").takeIf { it != entry }?.split('=')
?.takeIf { it.size == 2 } ?: return@mapNotNull null
val listId = id.toLongOrNull() ?: return@mapNotNull null
when (value) {
ListPersistence.ALWAYS.name -> listId to ListPersistence.ALWAYS
ListPersistence.NEVER.name -> listId to ListPersistence.NEVER
else -> null
}
}.toMap()
/** `s5,30` → [5 before start, 30 before due]; an empty string is an explicit "no reminder". */
private fun parseLeads(stored: String): List<ReminderLead> =
stored.split(',').mapNotNull { ReminderLead.parse(it)?.takeIf { lead -> lead.minutes >= 0 } }.normalizeReminders()
/**
* All-day defaults as whole days. Before 1.2 an all-day default could be hours
* before the all-day time; a lead that is not whole days now names a time of day.
*/
private fun List<ReminderLead>.inWholeDays(): List<ReminderLead> =
map { it.asTaskReminder().inWholeDays().asReminderLead() }.normalizeReminders()
private const val GROUPING_SEPARATOR = '|'
/**
* What a store's list entries are stored under. A provider's list ids mean
* nothing to another, so an external provider other than [owner], the one the
* bare `EXTERNAL` entries of earlier versions belong to, gets its own:
* `EXTERNAL@org.tasks.opentasks`.
*/
internal fun listScope(store: StorageMode, authority: String?, owner: String?): String =
if (store != StorageMode.EXTERNAL || authority == null || owner == null || owner == authority) store.name
else "${store.name}@$authority"
/** List ids belong to one store, so a stored list key carries the store's [mode]: `list:5` → `list:OWN:5`. */
private fun scopeListKey(key: String, mode: String): String =
if (key.startsWith(TaskGroupKey.LIST_PREFIX)) "${TaskGroupKey.LIST_PREFIX}$mode:${key.removePrefix(TaskGroupKey.LIST_PREFIX)}" else key
/** The reverse of [scopeListKey]; `null` for a list of another store. */
internal fun unscopeListKey(stored: String, mode: String): String? {
if (!stored.startsWith(TaskGroupKey.LIST_PREFIX)) return stored
val id = stored.removePrefix("${TaskGroupKey.LIST_PREFIX}$mode:").takeIf { it != stored } ?: return null
return "${TaskGroupKey.LIST_PREFIX}$id"
}
/** The shapes a stored set entry naming a list of one store comes in. */
internal enum class ListEntry {
/** `MODE:id=ALWAYS` */
PERSISTENCE,
/** `MODE:id` */
HIDDEN,
/** `GROUPING|list:MODE:id` */
GROUPING,
/** `list:MODE:id` */
COLLAPSED;
/** The list of [mode] [entry] names; null for another store's, or an entry naming no list. */
fun listId(entry: String, mode: String): Long? = when (this) {
PERSISTENCE -> storedListId(entry.substringBefore('='), mode)
HIDDEN -> storedListId(entry, mode)
GROUPING -> scopedListId(entry.substringAfter(GROUPING_SEPARATOR), mode)
COLLAPSED -> scopedListId(entry, mode)
}
}
/** [entries] without those naming a list of [mode] that is not [present]. */
internal fun withoutGoneLists(entries: Set<String>, kind: ListEntry, mode: String, present: Set<Long>): Set<String> =
entries.filterTo(HashSet()) { entry -> kind.listId(entry, mode)?.let { it in present } ?: true }
private fun storedListId(entry: String, mode: String): Long? =
entry.removePrefix("$mode:").takeIf { it != entry }?.toLongOrNull()
private fun scopedListId(stored: String, mode: String): Long? =
stored.removePrefix(TaskGroupKey.LIST_PREFIX).takeIf { it != stored }?.let { storedListId(it, mode) }
/** `GROUPING|key` entries → view key to grouping, keeping only the lists of the current [mode]. */
internal fun decodeGroupings(entries: Set<String>, mode: String): Map<String, TaskGrouping> =
entries.mapNotNull { entry ->
val grouping = runCatching { TaskGrouping.valueOf(entry.substringBefore(GROUPING_SEPARATOR)) }
.getOrNull() ?: return@mapNotNull null
val stored = entry.substringAfter(GROUPING_SEPARATOR, "")
stored.takeIf { it.isNotEmpty() }?.let { unscopeListKey(it, mode) }?.let { it to grouping }
}.toMap()
/** [collapsed] without the day groups before [today], which can never show again. */
internal fun dropPastDays(collapsed: Set<String>, today: LocalDate): Set<String> =
collapsed.filterTo(HashSet()) { entry ->
if (!entry.startsWith(TaskGroupKey.DAY_PREFIX)) return@filterTo true
runCatching { !LocalDate.parse(entry.removePrefix(TaskGroupKey.DAY_PREFIX)).isBefore(today) }.getOrDefault(false)
}
/** `5,30` → [5, 30]; an empty string is an explicit "no reminder". */
private fun parseMinutes(stored: String): List<Int> =
stored.split(',').mapNotNull { it.trim().toIntOrNull()?.takeIf { m -> m >= 0 } }.normalizeReminders()
@@ -29,7 +29,7 @@ class BootReceiver : BroadcastReceiver() {
val pending = goAsync()
scope.launch {
try {
runCatching { scheduler.syncFromBroadcast(rearmAll = true) }
runCatching { scheduler.sync(rearmAll = true) }
} finally {
pending.finish()
}
@@ -49,9 +49,8 @@ class BootReceiver : BroadcastReceiver() {
val pending = goAsync()
scope.launch {
try {
runCatching { scheduler.sync(afterReboot = afterReboot) }
if (afterReboot) runCatching { snoozeScheduler.rearm() }
// Also restores the persistent reminders the reboot took down.
runCatching { scheduler.syncFromBroadcast(afterReboot = afterReboot) }
} finally {
pending.finish()
}
@@ -6,7 +6,6 @@ import android.content.Intent
import androidx.core.net.toUri
import dagger.hilt.android.AndroidEntryPoint
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.data.tasks.StartupGate
import de.jeanlucmakiola.agendula.data.tasks.TaskQuery
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
import de.jeanlucmakiola.agendula.domain.Task
@@ -15,9 +14,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import javax.inject.Inject
import kotlin.time.Instant
/**
* Fires when a task's reminder alarm goes off. Re-reads the task (it may have
@@ -31,7 +28,6 @@ class DueReminderReceiver : BroadcastReceiver() {
@Inject lateinit var notifier: TaskNotifier
@Inject lateinit var settingsPrefs: SettingsPrefs
@Inject lateinit var scheduler: ReminderScheduler
@Inject lateinit var startupGate: StartupGate
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
@@ -48,12 +44,8 @@ class DueReminderReceiver : BroadcastReceiver() {
}
val settings = settingsPrefs.settings.first()
if (!settings.remindersEnabled) return@launch
// Before the gate the store is a guess; past this wait the broadcast's time runs short.
if (withTimeoutOrNull(ReminderScheduler.BROADCAST_GATE_WAIT_MS) { startupGate.awaitReady() } == null) {
runCatching { DueReminderWorker.enqueue(context, taskId, occurrence) }
return@launch
}
runCatching { notifier.postIfOpen(dataSource, taskId, occurrence) }
val task = runCatching { dataSource.occurrence(taskId, occurrence) }.getOrNull()
if (task != null && !task.isClosed) notifier.postDue(task, settings)
} finally {
pending.finish()
}
@@ -82,87 +74,17 @@ class DueReminderReceiver : BroadcastReceiver() {
/**
* The occurrence of [taskId] anchored at [occurrenceStart] (epoch millis), or the
* task's current one when there is no anchor or it can no longer be found.
*
* ⚠️ A ticked or edited occurrence is a row of its own with its own id, so
* matching list rows on [taskId] misses it; [TasksDataSource.task] with the
* anchor finds it by start. The list scan is for a provider whose exception
* rows that lookup does not reach.
* [TasksDataSource.task] alone resolves a series to whichever occurrence is
* current, which is not necessarily the one a reminder was armed for.
*/
internal fun TasksDataSource.occurrence(taskId: Long, occurrenceStart: Long): Task? {
val anchor = occurrenceStart.takeIf { it != ScheduledReminder.NO_OCCURRENCE }?.let(Instant::fromEpochMilliseconds)
val found = task(taskId, anchor) ?: return null
if (anchor == null || found.occurrenceStart == anchor) return found
return tasks(TaskQuery(listId = found.listId, includeCompleted = true))
.firstOrNull { (it.taskId == taskId || it.seriesId == taskId) && it.occurrenceStart == anchor }
?: found
}
/**
* Whether a reminder posted for [occurrenceStart] is done with, given [current]
* as [occurrence] resolved it.
*
* - No task: gone, but only when [missingMeansGone] — a provider that fails a
* read hands back nothing rather than throwing.
* - [occurrenceStart] null: posted before reminders recorded their occurrence,
* so only a task that does not recur can be judged.
* - A lookup that fell back to another occurrence says nothing about the
* reminded one, so it stays.
*/
internal fun reminderIsStale(occurrenceStart: Long?, current: Task?, missingMeansGone: Boolean): Boolean {
if (current == null) return missingMeansGone
return current.isOccurrence(occurrenceStart) && current.isClosed
}
/** Whether this is the occurrence a reminder recorded; [ScheduledReminder.NO_OCCURRENCE] matches any. */
internal fun Task.isOccurrence(occurrenceStart: Long?): Boolean = when (occurrenceStart) {
null -> this.occurrenceStart == null
ScheduledReminder.NO_OCCURRENCE -> true
else -> this.occurrenceStart?.toEpochMilliseconds() == occurrenceStart
}
/**
* Posts the reminder for [taskId]'s occurrence if it is still open, then checks
* once more: a completion landing between the read and the post may already
* have had its withdrawal pass, which ran before there was anything to withdraw.
* With [exact], a lookup that fell back to another occurrence posts nothing.
*
* [restoring] brings back a persistent reminder, unless its task was moved to a
* later due since or its list stopped being persistent (see [TaskNotifier.postDue]).
* A persistent reminder that won't come back is forgotten; one whose task an
* external store just failed to find is kept for a while.
*/
internal suspend fun TaskNotifier.postIfOpen(
dataSource: TasksDataSource,
taskId: Long,
occurrenceStart: Long,
alert: Boolean = true,
exact: Boolean = false,
postedAt: Long? = null,
restoring: PersistentRecord? = null,
) {
val task = dataSource.occurrence(taskId, occurrenceStart)
if (task == null) {
if (missingMeansGone()) forget(taskId, occurrence = occurrenceStart) else missed(taskId, occurrenceStart)
return
}
found(taskId, occurrenceStart)
if (task.isClosed || (exact && !task.isOccurrence(occurrenceStart)) || (restoring != null && task.postponedSince(restoring))) {
forget(taskId, occurrence = occurrenceStart)
if (task.taskId != taskId) forget(task.taskId, occurrence = occurrenceStart)
return
}
postDue(task, alert, postedAt, restoring)
// An edited occurrence is a row of its own, posted and remembered under its own id.
if (task.taskId != taskId) forget(taskId, occurrence = occurrenceStart)
val now = runCatching { dataSource.occurrence(taskId, occurrenceStart) }.getOrElse { return }
when {
now?.isClosed == true -> cancel(task.taskId)
now == null -> if (missingMeansGone()) cancel(task.taskId) else dismiss(task.taskId)
val current = task(taskId) ?: return null
if (occurrenceStart == ScheduledReminder.NO_OCCURRENCE ||
current.occurrenceStart?.toEpochMilliseconds() == occurrenceStart
) {
return current
}
}
/** Whether the task now falls due later than when [record]'s reminder went off, and not yet. */
private fun Task.postponedSince(record: PersistentRecord): Boolean {
val due = due?.toEpochMilliseconds()
return due != record.due && (due == null || due > System.currentTimeMillis())
return tasks(TaskQuery(listId = current.listId, includeCompleted = true))
.firstOrNull { it.taskId == taskId && it.occurrenceStart?.toEpochMilliseconds() == occurrenceStart }
?: current
}
@@ -1,53 +0,0 @@
package de.jeanlucmakiola.agendula.data.reminders
import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.CoroutineWorker
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.data.tasks.StartupGate
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
import kotlinx.coroutines.flow.first
/**
* Posts a reminder whose alarm went off before the store was known, once it
* is: [DueReminderReceiver] can only wait for that within its broadcast.
*/
@HiltWorker
class DueReminderWorker @AssistedInject constructor(
@Assisted context: Context,
@Assisted params: WorkerParameters,
private val dataSource: TasksDataSource,
private val notifier: TaskNotifier,
private val settingsPrefs: SettingsPrefs,
private val startupGate: StartupGate,
) : CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
val taskId = inputData.getLong(KEY_TASK_ID, -1L).takeIf { it >= 0L } ?: return Result.success()
val occurrence = inputData.getLong(KEY_OCCURRENCE, ScheduledReminder.NO_OCCURRENCE)
startupGate.awaitReady()
if (!settingsPrefs.settings.first().remindersEnabled) return Result.success()
runCatching { notifier.postIfOpen(dataSource, taskId, occurrence) }
return Result.success()
}
companion object {
private const val KEY_TASK_ID = "task_id"
private const val KEY_OCCURRENCE = "occurrence"
fun enqueue(context: Context, taskId: Long, occurrence: Long) {
val request = OneTimeWorkRequestBuilder<DueReminderWorker>()
.setInputData(workDataOf(KEY_TASK_ID to taskId, KEY_OCCURRENCE to occurrence))
.build()
WorkManager.getInstance(context)
.enqueueUniqueWork("due-reminder-$taskId-$occurrence", ExistingWorkPolicy.KEEP, request)
}
}
}
@@ -1,16 +0,0 @@
package de.jeanlucmakiola.agendula.data.reminders
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
/** Whether a notification posted now would show: the runtime permission (13+) and the app-wide switch. */
fun Context.canPostNotifications(): Boolean {
val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==
PackageManager.PERMISSION_GRANTED
return granted && NotificationManagerCompat.from(this).areNotificationsEnabled()
}
@@ -1,105 +0,0 @@
package de.jeanlucmakiola.agendula.data.reminders
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringSetPreferencesKey
import kotlinx.coroutines.flow.first
import javax.inject.Inject
import javax.inject.Singleton
/**
* A persistent reminder that is up: its store and task, the occurrence and due
* it was shown for, when it was first shown, and since when its task can't be
* found (0 while it can).
*/
data class PersistentRecord(
val store: String,
val taskId: Long,
val occurrence: Long,
val due: Long?,
val postedAt: Long,
val missingSince: Long = 0L,
) {
fun encode(): String = "$store|$taskId|$occurrence|${due ?: ""}|$postedAt|$missingSince"
companion object {
fun decode(value: String): PersistentRecord? {
val parts = value.split('|').takeIf { it.size == 6 } ?: return null
return PersistentRecord(
store = parts[0].ifEmpty { return null },
taskId = parts[1].toLongOrNull() ?: return null,
occurrence = parts[2].toLongOrNull() ?: return null,
due = if (parts[3].isEmpty()) null else parts[3].toLongOrNull() ?: return null,
postedAt = parts[4].toLongOrNull() ?: return null,
missingSince = parts[5].toLongOrNull() ?: return null,
)
}
}
}
/**
* The persistent reminders on screen, so a reboot or a re-post that couldn't
* read its task can bring them back. One per task and store.
*/
@Singleton
class PersistentReminderStore @Inject constructor(
private val dataStore: DataStore<Preferences>,
) {
suspend fun all(): List<PersistentRecord> = dataStore.data.first()[KEY].orEmpty().mapNotNull(PersistentRecord::decode)
suspend fun find(store: String, taskId: Long, occurrence: Long): PersistentRecord? =
all().firstOrNull { it.store == store && it.taskId == taskId && it.occurrence == occurrence }
suspend fun put(record: PersistentRecord) = edit { records ->
records.filterNot { it.store == record.store && it.taskId == record.taskId } + record
}
suspend fun removeIf(predicate: (PersistentRecord) -> Boolean) {
if (all().any(predicate)) edit { records -> records.filterNot(predicate) }
}
/**
* Notes that [taskId]'s occurrence wasn't found at [now]; one missing for
* longer than [MISSING_GRACE_MS] is dropped. Time, not a count, as a sync
* can run several times in a second.
*/
suspend fun missed(store: String, taskId: Long, occurrence: Long, now: Long) {
find(store, taskId, occurrence) ?: return
edit { records ->
records.mapNotNull { record ->
when {
record.store != store || record.taskId != taskId || record.occurrence != occurrence -> record
record.missingSince == 0L -> record.copy(missingSince = now)
now - record.missingSince >= MISSING_GRACE_MS -> null
else -> record
}
}
}
}
/** Notes that [taskId]'s occurrence was found again: an earlier miss no longer counts toward dropping it. */
suspend fun found(store: String, taskId: Long, occurrence: Long) {
val missing = { record: PersistentRecord ->
record.store == store && record.taskId == taskId && record.occurrence == occurrence && record.missingSince != 0L
}
if (all().none(missing)) return
edit { records -> records.map { if (missing(it)) it.copy(missingSince = 0L) else it } }
}
suspend fun clear() {
dataStore.edit { it.remove(KEY) }
}
private suspend fun edit(transform: (List<PersistentRecord>) -> List<PersistentRecord>) {
dataStore.edit { p ->
p[KEY] = transform(p[KEY].orEmpty().mapNotNull(PersistentRecord::decode)).mapTo(HashSet()) { it.encode() }
}
}
private companion object {
/** Not `persistent_reminders`: that is the setting's key in the same file. */
val KEY = stringSetPreferencesKey("persistent_reminder_records")
const val MISSING_GRACE_MS = 24 * 60 * 60 * 1000L
}
}
@@ -44,7 +44,7 @@ class ProviderChangeReceiver : BroadcastReceiver() {
val pending = goAsync()
scope.launch {
try {
scheduler.syncFromBroadcast()
scheduler.sync()
} finally {
pending.finish()
}
@@ -22,18 +22,17 @@ import kotlin.time.Instant
* elapses. All app-internal intents, so the receiver is not exported.
*
* - **Done** completes the task — only the reminded occurrence, for a series.
* Done and Snooze from a reminder of another store only take it down.
* - **Snooze** hides the notification and arms [ReminderSnoozeScheduler]'s
* alarm, which lives outside [ScheduledReminderStore] so no scheduler pass
* can cancel it.
* - **Show** re-posts it, if the task is still open by then.
* - **Dismissed** puts a persistent reminder straight back, silently.
*/
@AndroidEntryPoint
class ReminderActionReceiver : BroadcastReceiver() {
@Inject lateinit var notifier: TaskNotifier
@Inject lateinit var snoozeScheduler: ReminderSnoozeScheduler
@Inject lateinit var reminderScheduler: ReminderScheduler
@Inject lateinit var repository: TasksRepository
@Inject lateinit var dataSource: TasksDataSource
@Inject lateinit var settingsPrefs: SettingsPrefs
@@ -45,30 +44,22 @@ class ReminderActionReceiver : BroadcastReceiver() {
val taskId = intent.getLongExtra(EXTRA_TASK_ID, -1L).takeIf { it > 0L } ?: return
val occurrence = intent.getLongExtra(EXTRA_OCCURRENCE, ScheduledReminder.NO_OCCURRENCE)
val action = intent.action ?: return
// The store the reminder was posted in; known before the startup gate, unlike the current one.
val store = intent.getStringExtra(EXTRA_STORE)
if (action == ACTION_DONE || action == ACTION_SNOOZE) notifier.dismiss(taskId)
if (action == ACTION_DONE || action == ACTION_SNOOZE) notifier.cancel(taskId)
val pending = goAsync()
scope.launch {
try {
when (action) {
ACTION_DONE -> runCatching {
if (!forgetPersistent(taskId, occurrence, store)) return@runCatching
startupGate.awaitReady()
val anchor = occurrence.takeIf { it != ScheduledReminder.NO_OCCURRENCE }
?.let(Instant::fromEpochMilliseconds)
repository.setCompleted(taskId, anchor, completed = true)
reminderScheduler.sync()
}
ACTION_SNOOZE -> runCatching {
snoozeArmedFirst(
forget = { forgetKnown(taskId, occurrence, store) },
arm = {
val minutes = settingsPrefs.settings.first().snoozeMinutes
snoozeScheduler.schedule(taskId, occurrence, System.currentTimeMillis() + minutes * 60_000L)
},
actsHere = { forgetGated(taskId, occurrence, store) },
disarm = { snoozeScheduler.cancel(taskId, occurrence) },
)
val minutes = settingsPrefs.settings.first().snoozeMinutes
snoozeScheduler.schedule(taskId, occurrence, System.currentTimeMillis() + minutes * 60_000L)
}
ACTION_SHOW -> runCatching {
@@ -76,19 +67,8 @@ class ReminderActionReceiver : BroadcastReceiver() {
val settings = settingsPrefs.settings.first()
if (!settings.remindersEnabled) return@runCatching
startupGate.awaitReady()
notifier.postIfOpen(dataSource, taskId, occurrence)
}
ACTION_DISMISSED -> runCatching {
if (store == null) return@runCatching
val settings = settingsPrefs.settings.first()
startupGate.awaitReady()
// Whether its list is still persistent is the re-post's call, on the task's list.
if (settings.anyPersistentReminders && notifier.isCurrentStore(store)) {
notifier.repostRemembered(taskId, occurrence)
} else {
notifier.forget(taskId, store, occurrence)
}
val task = dataSource.occurrence(taskId, occurrence)
if (task != null && !task.isClosed) notifier.postDue(task, settings)
}
}
} finally {
@@ -97,76 +77,23 @@ class ReminderActionReceiver : BroadcastReceiver() {
}
}
/**
* Before the action's own work, so a restore running meanwhile finds nothing
* to bring back. False when the reminder was posted from another store,
* whose task ids name other tasks here: the action then stops at this.
*/
private suspend fun forgetPersistent(taskId: Long, occurrence: Long, store: String?): Boolean {
forgetKnown(taskId, occurrence, store)
return forgetGated(taskId, occurrence, store)
}
/** The record of a reminder whose store it names; needs no startup gate. */
private suspend fun forgetKnown(taskId: Long, occurrence: Long, store: String?) {
if (store != null) notifier.forget(taskId, store, occurrence)
}
/** The rest of [forgetPersistent], once the current store is known. */
private suspend fun forgetGated(taskId: Long, occurrence: Long, store: String?): Boolean {
startupGate.awaitReady()
if (store == null) notifier.forget(taskId, occurrence = occurrence)
return actsHere(store, notifier::isCurrentStore)
}
companion object {
const val ACTION_DONE = "de.jeanlucmakiola.agendula.reminders.DONE"
const val ACTION_SNOOZE = "de.jeanlucmakiola.agendula.reminders.SNOOZE"
const val ACTION_SHOW = "de.jeanlucmakiola.agendula.reminders.SHOW"
const val ACTION_DISMISSED = "de.jeanlucmakiola.agendula.reminders.DISMISSED"
private const val EXTRA_TASK_ID = "de.jeanlucmakiola.agendula.extra.TASK_ID"
private const val EXTRA_OCCURRENCE = "de.jeanlucmakiola.agendula.extra.OCCURRENCE_START"
private const val EXTRA_STORE = "de.jeanlucmakiola.agendula.extra.STORE"
/**
* Whether a reminder posted from [postedIn] may act on its task id in the
* current store; one from before the store was recorded may.
*/
internal suspend fun actsHere(postedIn: String?, isCurrentStore: suspend (String) -> Boolean): Boolean =
postedIn == null || isCurrentStore(postedIn)
/**
* Drops the persistent record first, so no restore re-posts what is being
* snoozed, then arms the snooze before anything waits on the startup gate,
* which may outlast the receiver's window; disarms it once the reminder
* turns out to be another store's.
*/
internal suspend fun snoozeArmedFirst(
forget: suspend () -> Unit,
arm: suspend () -> Unit,
actsHere: suspend () -> Boolean,
disarm: suspend () -> Unit,
) {
forget()
arm()
if (!actsHere()) disarm()
}
/**
* The data URI is what keeps two reminders' PendingIntents apart —
* `filterEquals` never compares extras.
*/
fun intent(context: Context, action: String, taskId: Long, occurrenceStart: Long, store: String? = null): Intent =
fun intent(context: Context, action: String, taskId: Long, occurrenceStart: Long): Intent =
Intent(context, ReminderActionReceiver::class.java)
.setAction(action)
.setData("agendula://reminder-action/$taskId/$occurrenceStart".toUri())
.putExtra(EXTRA_TASK_ID, taskId)
.putExtra(EXTRA_OCCURRENCE, occurrenceStart)
.apply { if (store != null) putExtra(EXTRA_STORE, store) }
/** A persistent reminder's delete intent, naming the store its task id belongs to. */
fun dismissedIntent(context: Context, taskId: Long, occurrenceStart: Long, store: String): Intent =
intent(context, ACTION_DISMISSED, taskId, occurrenceStart, store)
}
}
@@ -21,9 +21,7 @@ internal data class ReminderDiff(
fired: Set<ScheduledReminder> = emptySet(),
isArmed: (ScheduledReminder) -> Boolean,
): ReminderDiff {
// A fired entry counts even once the store dropped it, so a task
// reopened within the grace does not ring again.
val live = previous.filterTo(HashSet()) { it in fired || isArmed(it) } + fired
val live = previous.filterTo(HashSet()) { it in fired || isArmed(it) }
return ReminderDiff(
cancel = live - desired,
arm = desired - live,
@@ -1,15 +1,9 @@
package de.jeanlucmakiola.agendula.data.reminders
import de.jeanlucmakiola.agendula.data.prefs.Settings
import de.jeanlucmakiola.agendula.domain.AllDayReminder
import de.jeanlucmakiola.agendula.data.tasks.TaskReminder
import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.TaskDates
import de.jeanlucmakiola.agendula.domain.TaskEnd
import de.jeanlucmakiola.agendula.domain.untimedDate
import de.jeanlucmakiola.agendula.domain.TaskReminder
import de.jeanlucmakiola.agendula.domain.calendarDate
import de.jeanlucmakiola.agendula.domain.forDates
import java.time.LocalDate
import java.time.LocalTime
import java.time.ZoneId
import kotlin.time.Instant
@@ -22,8 +16,6 @@ internal object ReminderPlanner {
/** How long after its trigger a missed reminder is still worth firing. */
const val MISSED_GRACE_MS = 6L * 60 * 60 * 1000 // 6 hours
private const val CREATED_SLACK_MS = 1_000L
/**
* Alarms this app will hold at once.
*
@@ -44,7 +36,35 @@ internal object ReminderPlanner {
// One reminder per *occurrence* and lead: a recurring series yields a row
// per occurrence, all sharing a taskId, so this is a Set rather than a
// taskId-keyed Map.
.flatMap { triggers(it, perTask[it.taskId], settings, zone, now = now) }
.filter { !it.isClosed && it.due != null }
.flatMap { task ->
// Reminders set on the task itself win — every one of them, not just
// the one the editor shows; otherwise the task's list may override the
// global lead, or opt out entirely (override = null). All-day tasks
// have their own day-scale defaults.
val reminders = perTask[task.taskId].orEmpty().ifEmpty {
val leads = if (task.isAllDay) settings.allDayReminderLeadsFor(task.listId)
else settings.reminderLeadsFor(task.listId)
leads.map { TaskReminder(it) }
}
reminders.map { reminder ->
// A stored reminder says what it counts back from. Ours are always
// before due, but an imported dmfs alarm or another client's can be
// before *start*.
val anchor = if (reminder.fromStart) task.start ?: task.due!! else task.due!!
ScheduledReminder(
taskId = task.taskId,
triggerAt = triggerAt(
anchor,
task.isAllDay,
reminder.minutesBefore,
settings.allDayReminderMinuteOfDay,
zone,
),
occurrenceStart = task.occurrenceStart?.toEpochMilliseconds() ?: ScheduledReminder.NO_OCCURRENCE,
)
}
}
// The lower bound trails `now` so a reminder missed while the device was
// off still fires once on boot instead of being silently dropped.
.filter { it.triggerAt in (now - MISSED_GRACE_MS)..(now + WINDOW_MS) }
@@ -55,143 +75,13 @@ internal object ReminderPlanner {
.take(MAX_ALARMS)
.toSet()
/**
* When a reminder [leadMinutes] before the end [fromStart] picks (see
* [TaskDates.reminderEnd]) fires. An end without a time beside a timed one
* counts back from the all-day reminder time of its date, read in the
* task's zone, not from the first or last second it is stored as (#101).
*/
fun ringsAt(dates: TaskDates, fromStart: Boolean, leadMinutes: Int, allDayMinuteOfDay: Int, zone: ZoneId): Long {
val anchor = checkNotNull(dates.valueOf(dates.reminderEnd(fromStart))) { "A reminder needs a date" }
if (!dates.countsFromUntimed(fromStart)) return triggerAt(anchor, dates.isAllDay, leadMinutes, allDayMinuteOfDay, zone)
val date = anchor.untimedDate(dates.timeZone, zone)
return atMinuteOfDay(date, allDayMinuteOfDay, zone) - leadMinutes.coerceAtLeast(0) * 60_000L
}
/**
* Every reminder of [task] not yet dismissed, past ones included: [own] if it
* has reminders of its own, else its list's or the app's default — of which
* [sinceCreated] keeps only those after the task was created, and with
* [now], none due by then from a start no later than that.
*/
fun triggers(
task: Task,
own: List<TaskReminder>?,
settings: Settings,
zone: ZoneId,
sinceCreated: Boolean = true,
now: Long? = null,
): List<ScheduledReminder> {
if (task.isClosed || (task.due == null && task.start == null)) return emptyList()
// Reminders set on the task itself win — every one of them;
// otherwise the task's list may override the global lead, or opt
// out entirely (override = null). All-day tasks have their own
// day-scale defaults.
//
// ⚠️ Present-but-empty is "none", not "the default": the store's
// answer for a task whose alarms another client turned off. A
// default here would keep ringing for what the user switched off.
// A default counts from a date the task has, or from its one date when
// no default does (#178); its own reminders stand in each date for the
// other when the task lacks it.
val reminders = own ?: defaultsFor(task, settings)
val created = task.created?.toEpochMilliseconds()
val dates = task.dates
return reminders.mapNotNull { reminder ->
val anchor = dates.valueOf(dates.reminderEnd(reminder.fromStart))!!
val trigger = ringsAt(dates, reminder.fromStart, reminder.minutesBefore, settings.allDayReminderMinuteOfDay, zone)
// A default never rings for a moment before the task existed:
// that is a task saved after its default had passed, not a
// reminder missed while the device was off.
if (sinceCreated && own == null && created != null && trigger < created) return@mapNotNull null
// Nor, late, does any from a start the task was created at or
// after, its own included: a start of "now" (#178). Whether one
// rings on save is up to #106. One still ahead stays, in case
// [created] is another client's clock running fast.
if (sinceCreated && created != null && now != null && trigger <= now && startsByCreation(dates, reminder.fromStart, created)) {
return@mapNotNull null
}
// Dismissed on another client already: firing it here within
// the missed-reminder grace would ring for something done with.
//
// ⚠️ An all-day reminder without a time of its own is compared
// from the start of its day, not from this device's time of
// day: other clients ring it at midnight, or at their own hour,
// so a dismissal at 07:00 must still silence the 09:00 this
// device would ring it at.
// Likewise one from a date without a time, which others ring as stored.
val earliest = when {
task.isAllDay && reminder.allDay.minuteOfDay == null ->
triggerAt(anchor, true, reminder.minutesBefore, 0, zone)
dates.countsFromUntimed(reminder.fromStart) ->
minOf(trigger, triggerAt(anchor, false, reminder.minutesBefore, 0, zone))
else -> trigger
}
val acknowledged = reminder.acknowledgedAt?.let { earliest <= it.toEpochMilliseconds() } == true
if (acknowledged) return@mapNotNull null
ScheduledReminder(
taskId = task.taskId,
triggerAt = trigger,
occurrenceStart = task.occurrenceStart?.toEpochMilliseconds() ?: ScheduledReminder.NO_OCCURRENCE,
)
}
}
/**
* Whether a reminder [fromStart] counts from a timed start no later than
* [created], give or take [CREATED_SLACK_MS] for one stored in whole seconds.
*/
private fun startsByCreation(dates: TaskDates, fromStart: Boolean, created: Long): Boolean {
if (dates.reminderEnd(fromStart) != TaskEnd.START || !dates.hasTime(TaskEnd.START)) return false
val start = dates.start ?: return false
return start.toEpochMilliseconds() <= created + CREATED_SLACK_MS
}
/** The list's or the app's default reminders for [task], of the dates it has. */
private fun defaultsFor(task: Task, settings: Settings): List<TaskReminder> =
settings.defaultRemindersFor(task.listId, task.isAllDay).forDates(task.start != null, task.due != null)
/**
* [task]'s reminders once saved: its [own], with defaults older than the
* task, and the [pastDefaults] the save left out of them. With [startsNow]
* (see [de.jeanlucmakiola.agendula.domain.TaskForm.startsNow]) no default
* counts from the start.
*/
fun afterSave(
task: Task,
own: List<TaskReminder>?,
pastDefaults: List<TaskReminder>,
settings: Settings,
zone: ZoneId,
startsNow: Boolean = false,
): Set<ScheduledReminder> {
val kept = own ?: defaultsFor(task, settings).filterNot { startsNow && it.fromStart }
return triggers(task, kept + pastDefaults, settings, zone, sinceCreated = false).toSet()
}
/**
* Whether a reminder of [task] has rung by [now], as far as a save can tell
* (#106): any of [own], which a save rang if the planner did not; else a
* default the planner rang.
*/
fun anyRung(task: Task, own: List<TaskReminder>?, settings: Settings, zone: ZoneId, now: Long): Boolean =
triggers(task, own, settings, zone, sinceCreated = own == null, now = now).any { it.triggerAt <= now }
/**
* The reminders a save just put at or before [now] (#106): those of [after]
* that [before], the task as it was, did not have already.
*/
fun pastOnSave(before: Collection<ScheduledReminder>, after: Collection<ScheduledReminder>, now: Long): Set<ScheduledReminder> =
after.filterTo(HashSet()) { it.triggerAt <= now } - before.toSet()
/**
* When a reminder [leadMinutes] before [anchor] fires.
*
* ⚠️ An all-day anchor is UTC midnight of its date (see `AllDayTime.kt`), a
* storage convention and not a moment — firing off it rang at 02:00 in
* Berlin and the evening before in New York. It is read as its calendar
* date instead, and the lead as [TaskReminder.allDay]: whole days ring at
* [allDayMinuteOfDay] local time, anything else at the time it names.
* Berlin and the evening before in New York. It is read as its calendar date
* at [allDayMinuteOfDay] local time instead, and the lead counts back from that.
*/
fun triggerAt(
anchor: Instant,
@@ -200,11 +90,12 @@ internal object ReminderPlanner {
allDayMinuteOfDay: Int,
zone: ZoneId,
): Long {
if (!allDay) return anchor.toEpochMilliseconds() - leadMinutes.coerceAtLeast(0) * 60_000L
val (days, minuteOfDay) = AllDayReminder.of(leadMinutes)
return atMinuteOfDay(anchor.calendarDate(allDay = true).minusDays(days.toLong()), minuteOfDay ?: allDayMinuteOfDay, zone)
val base = if (allDay) {
val time = LocalTime.of(allDayMinuteOfDay / 60 % 24, allDayMinuteOfDay % 60)
anchor.calendarDate(allDay = true).atTime(time).atZone(zone).toInstant().toEpochMilli()
} else {
anchor.toEpochMilliseconds()
}
return base - leadMinutes.coerceAtLeast(0) * 60_000L
}
private fun atMinuteOfDay(date: LocalDate, minuteOfDay: Int, zone: ZoneId): Long =
date.atTime(LocalTime.of(minuteOfDay / 60 % 24, minuteOfDay % 60)).atZone(zone).toInstant().toEpochMilli()
}
@@ -1,35 +0,0 @@
package de.jeanlucmakiola.agendula.data.reminders
import de.jeanlucmakiola.agendula.data.di.ApplicationScope
import de.jeanlucmakiola.agendula.data.tasks.StoreChangeDebouncer
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
import kotlinx.coroutines.CoroutineScope
import javax.inject.Inject
import javax.inject.Singleton
/**
* Keeps reminders in step with the store: any change to tasks, lists or alarms —
* a tick in the list or on a widget, a sync pulling in a completion from another
* device, an edit, a store switch — runs one debounced [ReminderScheduler.sync].
* Started once from `AgendulaApp`, after the startup gate, so it observes the
* right store.
*/
@Singleton
class ReminderRefresher @Inject constructor(
dataSource: TasksDataSource,
scheduler: ReminderScheduler,
@ApplicationScope scope: CoroutineScope,
) {
private val changes = StoreChangeDebouncer(scope, DEBOUNCE_MILLIS, dataSource::registerTaskObserver) { scheduler.sync() }
fun start() {
changes.start()
}
/** Re-sync soon, folded into any pass a store change already asked for. */
fun requestRefresh() = changes.request()
private companion object {
const val DEBOUNCE_MILLIS = 1_000L
}
}
@@ -8,16 +8,13 @@ import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
import de.jeanlucmakiola.agendula.data.tasks.StartupGate
import de.jeanlucmakiola.agendula.data.tasks.TaskQuery
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
import de.jeanlucmakiola.agendula.domain.TaskReminder
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import java.time.ZoneId
import javax.inject.Inject
import javax.inject.Singleton
@@ -26,9 +23,8 @@ import javax.inject.Singleton
* The self-scheduled due-reminder engine. Nothing else delivers task reminders —
* not the platform, not a tasks provider — so Agendula reads upcoming due tasks
* and arms one exact [AlarmManager] alarm per reminder, within a rolling window. Re-run
* on app start, on boot, on a store switch and on every change to the store (see
* [ReminderRefresher]); it diffs against [ScheduledReminderStore] so only changed
* alarms move, and takes down posted reminders whose task is done with.
* on app start, on boot, on a store switch, and on an external provider change;
* it diffs against [ScheduledReminderStore] so only changed alarms move.
*/
@Singleton
class ReminderScheduler @Inject constructor(
@@ -38,8 +34,6 @@ class ReminderScheduler @Inject constructor(
private val store: ScheduledReminderStore,
private val providerResolver: ProviderResolver,
private val snoozeScheduler: ReminderSnoozeScheduler,
private val notifier: TaskNotifier,
private val startupGate: StartupGate,
@IoDispatcher private val io: CoroutineDispatcher,
) {
private val syncLock = Mutex()
@@ -53,57 +47,13 @@ class ReminderScheduler @Inject constructor(
* the whole truth, leaving the other's alarms armed but unrecorded — never
* cancelled, and firing against the wrong store's task ids.
*/
suspend fun sync(afterReboot: Boolean = false, rearmAll: Boolean = false) = withContext(io) {
// Outside the lock, which a reminder going off takes to mark itself fired.
startupGate.awaitReady()
syncLock.withLock { syncLocked(afterReboot, rearmAll) }
}
/**
* [sync] from a broadcast, which gives up when the store isn't known within
* [BROADCAST_GATE_WAIT_MS]: the launch sync, once it is, covers the pass.
*/
suspend fun syncFromBroadcast(afterReboot: Boolean = false, rearmAll: Boolean = false) {
if (withTimeoutOrNull(BROADCAST_GATE_WAIT_MS) { startupGate.awaitReady() } == null) return
sync(afterReboot, rearmAll)
}
suspend fun sync(afterReboot: Boolean = false, rearmAll: Boolean = false) =
withContext(io) { syncLock.withLock { syncLocked(afterReboot, rearmAll) } }
/** Record that [reminder] went off, so a later pass neither re-arms nor re-fires it. */
suspend fun markFired(reminder: ScheduledReminder) =
withContext(io) { syncLock.withLock { store.markFired(reminder) } }
/**
* Rings [taskId] at once for [past], the reminders its save put at or before
* now (#106), and marks them fired so [sync] does not arm them again within
* the missed-reminder grace. [pastDefaults] are the defaults the save left
* out of the task's own as past; [startsNow] that its start was the "now" it was given.
*/
suspend fun remindPastOnSave(taskId: Long, past: Set<ScheduledReminder>, pastDefaults: List<TaskReminder>, startsNow: Boolean) =
withContext(io) {
syncLock.withLock {
// Read under the lock, as a reminder going off would.
val settings = settingsPrefs.settings.first()
if (!settings.ringsPastOnSave) return@withLock
val task = dataSource.task(taskId)?.takeUnless { it.isRecurring } ?: return@withLock
val still = ReminderPlanner.afterSave(task, dataSource.reminders(taskId), pastDefaults, settings, ZoneId.systemDefault(), startsNow)
val due = past intersect still
if (due.isEmpty()) return@withLock
val fired = store.fired()
if (due.any { it in fired }) {
store.markFired(due)
return@withLock
}
// Armed by a pass that got in first: only an exact alarm is sure to go off at once.
val armed = store.all().intersect(due)
val ringing = if (store.armedExact() == true) armed else emptySet()
if (ringing.isEmpty()) {
armed.forEach { cancel(it) }
notifier.postIfOpen(dataSource, taskId, ScheduledReminder.NO_OCCURRENCE)
}
store.markFired(due - ringing)
}
}
/**
* @param afterReboot every alarm is gone, so nothing in the store is armed;
* skips asking the system about each one.
@@ -115,27 +65,19 @@ class ReminderScheduler @Inject constructor(
// Gate on whether the store is readable, not on whether a provider
// resolves: our own store deliberately resolves to no provider, so the
// latter clears every reminder in the default mode.
val readable = providerResolver.canReadStore()
if (!settings.remindersEnabled || !readable) {
if (!settings.remindersEnabled || !providerResolver.canReadStore()) {
clearAll()
// Switched off, a reminder already up still goes when its task does.
if (readable) {
val store = settingsPrefs.storeScope()
val shown = withdrawStale(store)
runCatching { notifier.restorePersistent(settings, store, shown) }
}
return
}
val tasks = runCatching { dataSource.tasks(TaskQuery(includeCompleted = false)) }
.getOrElse { return }
// Per-task leads. One query for all of them.
val perTask = runCatching { dataSource.reminders() }.getOrElse { emptyMap() }
val now = System.currentTimeMillis()
val desired = ReminderPlanner.plan(
tasks = tasks,
perTask = perTask,
settings = settings,
now = now,
now = System.currentTimeMillis(),
zone = ZoneId.systemDefault(),
)
@@ -150,10 +92,7 @@ class ReminderScheduler @Inject constructor(
// ⚠️ The store survives reboot, force-stop and restore; the alarms don't.
// Trusting it alone left every reminder after a reboot unarmed for good.
// ⚠️ Kept through the missed-reminder grace even once it drops out of
// the plan: a tick undone a moment later would otherwise re-arm a
// trigger in the past, and the reminder would ring a second time.
val fired = store.fired().filterTo(HashSet()) { it in desired || it.triggerAt >= now - ReminderPlanner.MISSED_GRACE_MS }
val fired = store.fired()
val diff = ReminderDiff.of(store.all(), desired, fired) { !afterReboot && !rearm && isArmed(it) }
diff.cancel.forEach { cancel(it) }
// ⚠️ Only what was actually armed. A throw mid-loop used to skip the
@@ -161,32 +100,7 @@ class ReminderScheduler @Inject constructor(
// — uncancellable, and firing for tasks that no longer exist — and the
// exception escaped into BootReceiver's goAsync().
val armed = diff.arm.filter { schedule(it) }
store.replace(diff.keep + armed, fired = fired, exact = canExact)
val store = settingsPrefs.storeScope()
val shown = withdrawStale(store)
if (shown?.isNotEmpty() != false || runCatching { notifier.hasRemembered() }.getOrDefault(true)) {
// Catches a task moved to a list that is persistent differently.
runCatching { notifier.restyleActive(tasks.associate { it.taskId to it.listId }, store) }
runCatching { notifier.restorePersistent(settings, store, shown) }
}
}
/**
* A reminder already on screen outlives its alarm: completing the task in
* the list, on a widget or on another device has to take it down too.
* Returns the tasks of [store]'s reminders still shown, null when unknown.
*/
private suspend fun withdrawStale(store: String): Set<Long>? {
val missingMeansGone = notifier.missingMeansGone()
return runCatching {
notifier.withdrawStale(store) { taskId, occurrence ->
runCatching {
val current = dataSource.occurrence(taskId, occurrence ?: ScheduledReminder.NO_OCCURRENCE)
if (current != null && occurrence != null) notifier.found(taskId, occurrence, store)
reminderIsStale(occurrence, current, missingMeansGone)
}.getOrDefault(false)
}
}.getOrNull()
store.replace(diff.keep + armed, fired = fired intersect desired, exact = canExact)
}
/** Whether the system still holds this alarm's PendingIntent. */
@@ -238,11 +152,6 @@ class ReminderScheduler @Inject constructor(
}
}
companion object {
/** How long a broadcast waits for the store to be known: well inside the ten seconds it gets. */
const val BROADCAST_GATE_WAIT_MS = 4_000L
}
private suspend fun clearAll() {
store.all().forEach { cancel(it) }
store.replace(emptySet(), fired = emptySet())
@@ -41,12 +41,6 @@ class ReminderSnoozeScheduler @Inject constructor(
}
}
/** Calls off a snooze that has not re-shown yet. */
suspend fun cancel(taskId: Long, occurrenceStart: Long) {
clear(taskId, occurrenceStart)
context.getSystemService(AlarmManager::class.java)?.cancel(showIntent(taskId, occurrenceStart))
}
suspend fun rearm() {
val now = System.currentTimeMillis()
dataStore.data.first()[KEY].orEmpty().forEach { entry ->
@@ -58,7 +52,12 @@ class ReminderSnoozeScheduler @Inject constructor(
private fun arm(taskId: Long, occurrenceStart: Long, triggerAtMillis: Long) {
val alarmManager = context.getSystemService(AlarmManager::class.java) ?: return
val pendingIntent = showIntent(taskId, occurrenceStart)
val pendingIntent = PendingIntent.getBroadcast(
context,
taskId.toInt(),
ReminderActionReceiver.intent(context, ReminderActionReceiver.ACTION_SHOW, taskId, occurrenceStart),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
val canExact = Build.VERSION.SDK_INT < Build.VERSION_CODES.S || alarmManager.canScheduleExactAlarms()
try {
if (canExact) {
@@ -71,13 +70,6 @@ class ReminderSnoozeScheduler @Inject constructor(
}
}
private fun showIntent(taskId: Long, occurrenceStart: Long): PendingIntent = PendingIntent.getBroadcast(
context,
taskId.toInt(),
ReminderActionReceiver.intent(context, ReminderActionReceiver.ACTION_SHOW, taskId, occurrenceStart),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
private companion object {
/** `taskId|occurrenceStart|triggerAt` per pending snooze. */
val KEY = stringSetPreferencesKey("pending_snoozes")
@@ -61,11 +61,9 @@ class ScheduledReminderStore @Inject constructor(
}
}
suspend fun markFired(reminder: ScheduledReminder) = markFired(setOf(reminder))
suspend fun markFired(reminders: Set<ScheduledReminder>) {
suspend fun markFired(reminder: ScheduledReminder) {
dataStore.edit { prefs ->
prefs[FIRED_KEY] = prefs[FIRED_KEY].orEmpty() + encode(reminders)
prefs[FIRED_KEY] = prefs[FIRED_KEY].orEmpty() + encode(setOf(reminder))
}
}
@@ -1,41 +1,33 @@
package de.jeanlucmakiola.agendula.data.reminders
import android.Manifest
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationChannelGroup
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.content.pm.PackageManager
import android.os.Build
import android.text.format.DateFormat
import android.util.TypedValue
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import de.jeanlucmakiola.agendula.MainActivity
import de.jeanlucmakiola.agendula.R
import de.jeanlucmakiola.agendula.data.prefs.ReminderDescription
import de.jeanlucmakiola.agendula.data.prefs.Settings
import de.jeanlucmakiola.agendula.domain.TaskEnd
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.domain.readableDescription
import de.jeanlucmakiola.agendula.data.prefs.is24Hour
import de.jeanlucmakiola.agendula.data.di.ApplicationScope
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
import de.jeanlucmakiola.agendula.data.tasks.StartupGate
import de.jeanlucmakiola.agendula.data.tasks.StorageMode
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.calendarDate
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.text.BreakIterator
import java.time.Instant as JInstant
import java.time.LocalDate
import java.time.ZoneId
@@ -51,9 +43,7 @@ import kotlin.time.Instant
* Posts one notification per due task on its list's channel, so each list can
* have its own sound and importance. The tag is the task id, so a re-fired alarm
* replaces rather than duplicates. Tapping opens the task's detail screen (see
* [MainActivity.taskIntent]). A reminder whose list is persistent (see
* [Settings.persistentRemindersFor]) re-posts silently when swiped away and is
* remembered so a reboot brings it back.
* [MainActivity.taskIntent]).
*/
@Singleton
class TaskNotifier @Inject constructor(
@@ -62,63 +52,29 @@ class TaskNotifier @Inject constructor(
private val dataSource: TasksDataSource,
private val startupGate: StartupGate,
@ApplicationScope private val scope: CoroutineScope,
private val records: PersistentReminderStore,
private val settingsPrefs: SettingsPrefs,
) {
private val manager get() = context.getSystemService(NotificationManager::class.java)
private val channelPrefs get() = context.getSharedPreferences(CHANNEL_PREFS, Context.MODE_PRIVATE)
/** The store the channels belong to; records and actions tell providers apart too, see [SettingsPrefs.storeScope]. */
private val channelStore get() = resolver.mode().name.lowercase()
/** Keeps a post and a restyle from overwriting each other with a stale snapshot. */
private val postLock = Mutex()
fun canPost(): Boolean {
return context.canPostNotifications()
}
/**
* Posts [task]'s reminder with the settings read under the lock, so a list
* that just stopped being persistent is never posted persistent. This is
* where a restore of a no longer persistent reminder is forgotten.
*/
suspend fun postDue(
task: Task,
alert: Boolean = true,
postedAt: Long? = null,
restoring: PersistentRecord? = null,
) {
postLock.withLock {
val settings = settingsPrefs.settings.first()
val persistent = settings.persistentRemindersFor(task.listId)
if (restoring != null && !persistent) {
forget(restoring.taskId, restoring.store, restoring.occurrence)
return
}
if (!canPost()) return
// A restore yields to a reminder already up and to a Done or Snooze that dropped the record meanwhile.
if (restoring != null) {
if (postedReminders(restoring.store).any { it.taskId == task.taskId }) return
records.find(restoring.store, restoring.taskId, restoring.occurrence) ?: return
}
post(task, settings, alert, postedAt, persistent)
}
val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) ==
PackageManager.PERMISSION_GRANTED
return granted && NotificationManagerCompat.from(context).areNotificationsEnabled()
}
// canPost() checks POST_NOTIFICATIONS before we ever call notify().
@SuppressLint("MissingPermission")
private suspend fun post(task: Task, settings: Settings, alert: Boolean, postedAt: Long?, persistent: Boolean) {
val store = settingsPrefs.claimStoreScope()
val occurrence = task.occurrenceStart?.toEpochMilliseconds() ?: ScheduledReminder.NO_OCCURRENCE
val shownAt = postedAt ?: System.currentTimeMillis()
fun postDue(task: Task, settings: Settings) {
if (!canPost()) return
val channelId = ensureListChannel(task.listId, task.listName)
val title = task.title.ifBlank { context.getString(R.string.task_untitled) }
val text = task.shownValue(TaskEnd.DUE)?.let { due ->
val text = task.due?.let { due ->
context.getString(
R.string.reminder_due_at,
formatReminderDue(
due.toEpochMilliseconds(),
!task.hasTime(TaskEnd.DUE),
task.isAllDay,
is24Hour = settings.timeFormat.is24Hour(DateFormat.is24HourFormat(context)),
relative = RelativeDays(
today = context.getString(R.string.reminder_day_today),
@@ -128,9 +84,6 @@ class TaskNotifier @Inject constructor(
),
)
}
val description = reminderBody(settings.reminderDescription, lineChars()) {
task.description?.readableDescription()
}
val tapIntent = PendingIntent.getActivity(
context,
task.taskId.toInt(),
@@ -140,236 +93,34 @@ class TaskNotifier @Inject constructor(
val notification = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.apply { (text ?: description)?.let(::setContentText) }
.apply {
expandedText(text, description)?.let { setStyle(NotificationCompat.BigTextStyle().bigText(it)) }
}
.apply { if (text != null) setContentText(text) }
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setWhen(shownAt)
.setAutoCancel(!persistent)
.setSilent(!alert)
.apply { groupFor(task.taskId, persistent, alert)?.let(::setGroup) }
.setDeleteIntent(if (persistent) dismissedIntent(task.taskId, occurrence, store) else null)
.setAutoCancel(true)
.setContentIntent(tapIntent)
.addExtras(
Bundle().apply {
putLong(EXTRA_OCCURRENCE, occurrence)
putLong(EXTRA_DUE, task.due?.toEpochMilliseconds() ?: NO_DUE)
putString(EXTRA_STORE, store)
},
)
.addAction(0, context.getString(R.string.reminder_action_done), actionIntent(task, ReminderActionReceiver.ACTION_DONE, store))
.addAction(0, context.getString(R.string.reminder_action_done), actionIntent(task, ReminderActionReceiver.ACTION_DONE))
.addAction(
0,
context.getString(R.string.reminder_action_snooze, settings.snoozeMinutes),
actionIntent(task, ReminderActionReceiver.ACTION_SNOOZE, store),
actionIntent(task, ReminderActionReceiver.ACTION_SNOOZE),
)
.build()
NotificationManagerCompat.from(context).notify(task.taskId.toString(), NOTIFICATION_ID, notification)
remember(store, task.taskId, occurrence, task.due?.toEpochMilliseconds(), shownAt, persistent)
}
private suspend fun remember(store: String, taskId: Long, occurrence: Long, due: Long?, postedAt: Long, persistent: Boolean) {
if (persistent) records.put(PersistentRecord(store, taskId, occurrence, due, postedAt)) else forget(taskId, store)
}
/** Characters per line of an expanded notification on this screen, at the user's font size. */
private fun lineChars(): Int {
val res = context.resources
val widthDp = (res.configuration.screenWidthDp - NOTIFICATION_INSET_DP).toFloat()
return notificationLineChars(
textWidthPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, widthDp, res.displayMetrics),
textSizePx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, NOTIFICATION_TEXT_SP, res.displayMetrics),
)
}
/** Takes [taskId]'s reminder down without touching its record; safe before the startup gate. */
fun dismiss(taskId: Long) {
fun cancel(taskId: Long) {
NotificationManagerCompat.from(context).cancel(taskId.toString(), NOTIFICATION_ID)
}
suspend fun cancel(taskId: Long, store: String? = null) {
dismiss(taskId)
forget(taskId, store)
}
/**
* Drops [taskId]'s remembered persistent reminder in [store]; with
* [occurrence], only when it is that occurrence's.
*/
suspend fun forget(taskId: Long, store: String? = null, occurrence: Long? = null) {
val from = store ?: settingsPrefs.storeScope()
records.removeIf { it.store == from && it.taskId == taskId && (occurrence == null || it.occurrence == occurrence) }
}
/** Notes that a remembered reminder's task wasn't found; one gone long enough is dropped. */
suspend fun missed(taskId: Long, occurrence: Long) =
records.missed(settingsPrefs.storeScope(), taskId, occurrence, System.currentTimeMillis())
/** Notes that a remembered reminder's task was read, so an earlier miss no longer counts. */
suspend fun found(taskId: Long, occurrence: Long, store: String? = null) =
records.found(store ?: settingsPrefs.storeScope(), taskId, occurrence)
suspend fun isCurrentStore(store: String?): Boolean = store == settingsPrefs.storeScope()
/** Whether a task the store can't find is really gone; an external provider that fails a read finds nothing too. */
fun missingMeansGone(): Boolean = resolver.mode() == StorageMode.OWN
/**
* Takes down every reminder of [store] posted that [isStale] says is done
* with — completed, cancelled or deleted since it went off, here or on
* another device — and returns the tasks of those still shown. The
* occurrence is null for a reminder posted before it was recorded.
*/
suspend fun withdrawStale(store: String, isStale: suspend (taskId: Long, occurrenceStart: Long?) -> Boolean): Set<Long> {
val (stale, kept) = postedReminders(store).partition { isStale(it.taskId, it.occurrence) }
stale.forEach { cancel(it.taskId, store) }
return kept.mapTo(HashSet()) { it.taskId }
}
/**
* Turns the shown reminders persistent or back, in place: the update doesn't
* alert again and keeps each reminder's content and time. One posted before
* occurrence and due were recorded is left alone, as a re-post couldn't tell
* its occurrence. Reads the settings under the lock, so the latest wins
* however fast they flip. Each goes by its list in [taskLists] when known
* (a sync passes the tasks it read, catching moves), else by the list it
* was posted in; one already styled right is left alone. [store] is the
* current store's scope when the caller has it.
*/
suspend fun restyleActive(taskLists: Map<Long, Long> = emptyMap(), store: String? = null) = postLock.withLock {
val shown = postedReminders(store ?: settingsPrefs.storeScope()).ifEmpty { return@withLock }
val settings = settingsPrefs.settings.first()
var claimed: String? = null
shown.forEach { posted ->
val occurrence = posted.occurrence ?: return@forEach
if (!posted.notification.extras.containsKey(EXTRA_DUE)) return@forEach
val listId = taskLists[posted.taskId] ?: posted.listId ?: return@forEach
val persistent = settings.persistentRemindersFor(listId)
if ((posted.notification.deleteIntent != null) == persistent) return@forEach
val scope = claimed ?: settingsPrefs.claimStoreScope().also { claimed = it }
val due = posted.notification.extras.getLong(EXTRA_DUE).takeIf { it != NO_DUE }
val notification = Notification.Builder.recoverBuilder(context, posted.notification)
.setAutoCancel(!persistent)
.setOnlyAlertOnce(true)
.setGroup(groupFor(posted.taskId, persistent, alert = true))
.setDeleteIntent(if (persistent) dismissedIntent(posted.taskId, occurrence, scope) else null)
.build()
manager.notify(posted.taskId.toString(), NOTIFICATION_ID, notification)
remember(scope, posted.taskId, occurrence, due, posted.postedAt, persistent)
}
}
/** Re-posts the shown reminders silently, so a changed snooze length or description shows on them. */
suspend fun refreshShown() {
startupGate.awaitReady()
postedReminders(settingsPrefs.storeScope()).forEach { posted ->
val occurrence = posted.occurrence ?: return@forEach
runCatching {
postIfOpen(dataSource, posted.taskId, occurrence, alert = false, exact = true, postedAt = posted.postedAt)
}
}
}
/** Re-posts [taskId]'s persistent reminder after a swipe, if it is still remembered. */
suspend fun repostRemembered(taskId: Long, occurrence: Long) {
val record = records.find(settingsPrefs.storeScope(), taskId, occurrence) ?: return
repost(record)
}
private suspend fun repost(record: PersistentRecord) = postIfOpen(
dataSource,
record.taskId,
record.occurrence,
alert = false,
exact = true,
postedAt = record.postedAt,
restoring = record,
)
/**
* Brings back, silently and at their old time, the persistent reminders no
* longer shown: taken down by a reboot or a force-stop, or by a swipe whose
* re-post couldn't read the task. Another store's or provider's are dropped:
* their ids name other tasks here. [store] and the tasks [shown] are the
* caller's when it has them.
*/
suspend fun restorePersistent(settings: Settings, store: String? = null, shown: Set<Long>? = null) {
val all = records.all().ifEmpty { return }
if (!settings.anyPersistentReminders) return records.clear()
// Before it, the store is a guess, and a wrong one would drop every record.
startupGate.awaitReady()
// A list deleted elsewhere leaves its setting behind; a read finding no list proves nothing.
val lists = runCatching { dataSource.taskLists().mapTo(HashSet()) { it.id } }.getOrNull()?.takeIf { it.isNotEmpty() }
if (lists != null && !settings.anyPersistentReminders(lists)) return records.clear()
val scope = store ?: settingsPrefs.storeScope()
val here = all.filter { it.store == scope }
if (here.size != all.size) records.removeIf { it.store != scope }
// Nothing could be shown; trying anyway would re-read every record on each sync.
if (!canPost()) return
val up = shown ?: postedReminders(scope).mapTo(HashSet()) { it.taskId }
here.filter { it.taskId !in up }.forEach { runCatching { repost(it) } }
}
/** Whether a persistent reminder is remembered. */
suspend fun hasRemembered(): Boolean = records.all().isNotEmpty()
private class Posted(
val taskId: Long,
val listId: Long?,
val occurrence: Long?,
val postedAt: Long,
val notification: Notification,
)
/**
* [store]'s posted reminders; another store's or provider's ids name other
* tasks. One posted before the provider was recorded is the bare store's.
*/
private fun postedReminders(store: String): List<Posted> {
val prefix = "$LIST_CHANNEL_PREFIX${channelStore}_"
return manager.activeNotifications
.filter { it.id == NOTIFICATION_ID && it.notification.channelId?.startsWith(prefix) == true }
.filter { (it.notification.extras.getString(EXTRA_STORE) ?: channelStore) == store }
.mapNotNull { posted ->
val taskId = posted.tag?.toLongOrNull() ?: return@mapNotNull null
val extras = posted.notification.extras
val occurrence = if (extras.containsKey(EXTRA_OCCURRENCE)) extras.getLong(EXTRA_OCCURRENCE) else null
val listId = posted.notification.channelId.removePrefix(prefix).toLongOrNull()
Posted(taskId, listId, occurrence, posted.notification.`when`, posted.notification)
}
}
/**
* A persistent reminder keeps a group of its own; a fresh one goes ungrouped so
* Android may bundle it, and a silent re-post shares [SILENT_GROUP] rather than
* NotificationCompat's implicit "silent" group.
*/
private fun groupFor(taskId: Long, persistent: Boolean, alert: Boolean): String? = when {
persistent -> "$PERSISTENT_GROUP_PREFIX$taskId"
alert -> null
else -> SILENT_GROUP
}
private fun dismissedIntent(taskId: Long, occurrence: Long, store: String): PendingIntent =
broadcast(taskId, ReminderActionReceiver.dismissedIntent(context, taskId, occurrence, store))
private fun actionIntent(task: Task, action: String, store: String): PendingIntent = broadcast(
task.taskId,
private fun actionIntent(task: Task, action: String): PendingIntent = PendingIntent.getBroadcast(
context,
task.taskId.toInt(),
ReminderActionReceiver.intent(
context,
action,
task.taskId,
task.occurrenceStart?.toEpochMilliseconds() ?: ScheduledReminder.NO_OCCURRENCE,
store = store,
),
)
private fun broadcast(taskId: Long, intent: Intent): PendingIntent = PendingIntent.getBroadcast(
context,
taskId.toInt(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
@@ -381,7 +132,7 @@ class TaskNotifier @Inject constructor(
*/
fun ensureListChannel(listId: Long, listName: String?): String {
ensureGroup()
val id = "$LIST_CHANNEL_PREFIX${channelStore}_$listId"
val id = "$LIST_CHANNEL_PREFIX${resolver.mode().name.lowercase()}_$listId"
val importance = manager.getNotificationChannel(id)?.importance ?: legacyImportance()
manager.createNotificationChannel(
NotificationChannel(
@@ -416,7 +167,7 @@ class TaskNotifier @Inject constructor(
startupGate.awaitReady()
val lists = dataSource.taskLists()
lists.forEach { ensureListChannel(it.id, it.name) }
val prefix = "$LIST_CHANNEL_PREFIX${channelStore}_"
val prefix = "$LIST_CHANNEL_PREFIX${resolver.mode().name.lowercase()}_"
val live = lists.map { "$prefix${it.id}" }.toSet()
manager.notificationChannels
.filter { it.id.startsWith(prefix) && it.id !in live }
@@ -434,14 +185,8 @@ class TaskNotifier @Inject constructor(
private const val LEGACY_CHANNEL_ID = "task_reminders"
private const val LIST_CHANNEL_PREFIX = "reminders_"
private const val NOTIFICATION_ID = 1
private const val EXTRA_OCCURRENCE = "de.jeanlucmakiola.agendula.extra.OCCURRENCE_START"
private const val CHANNEL_PREFS = "reminder_channels"
private const val KEY_LEGACY_IMPORTANCE = "legacy_importance"
private const val EXTRA_DUE = "de.jeanlucmakiola.agendula.extra.DUE"
private const val EXTRA_STORE = "de.jeanlucmakiola.agendula.extra.STORE"
private const val NO_DUE = Long.MIN_VALUE
private const val PERSISTENT_GROUP_PREFIX = "reminder_"
private const val SILENT_GROUP = "reminders"
/**
* Whether a reminder can sound anywhere: the group is not blocked and at
@@ -495,170 +240,3 @@ private fun relativeDay(date: LocalDate, today: LocalDate, words: RelativeDays,
else -> null
}
}
/** The expanded body of a due reminder: the due line, then the task's description. */
internal fun expandedText(dueLine: String?, description: String?): String? = when {
description == null -> null
dueLine == null -> description
else -> "$dueLine\n\n$description"
}
/** Characters per line assumed when the screen is not known. */
internal const val NOTIFICATION_LINE_CHARS = 40
/** A notification's body text size. */
internal const val NOTIFICATION_TEXT_SP = 14f
/** Width the expanded text doesn't get: the shade's margins, the template's padding and its icon column. */
internal const val NOTIFICATION_INSET_DP = 2 * 16 + 2 * 16 + 40
/** Average glyph advance as a share of the text size, for Latin body text. */
private const val AVERAGE_CHAR_EM = 0.52f
/** How many average characters fit on a [textWidthPx] wide line of [textSizePx] text. */
internal fun notificationLineChars(textWidthPx: Float, textSizePx: Float): Int =
if (textWidthPx <= 0f || textSizePx <= 0f) NOTIFICATION_LINE_CHARS
else (textWidthPx / (textSizePx * AVERAGE_CHAR_EM)).toInt().coerceAtLeast(10)
/**
* The description a reminder shows, as [mode] asks; null when there is none to
* show. [description] is only read when the mode shows it.
*/
internal fun reminderBody(
mode: ReminderDescription,
lineChars: Int = NOTIFICATION_LINE_CHARS,
description: () -> String?,
): String? {
if (mode == ReminderDescription.HIDDEN) return null
val text = description()?.trim()?.takeIf { it.isNotBlank() } ?: return null
return when (mode) {
ReminderDescription.HIDDEN -> null
ReminderDescription.SHORT -> shortDescription(text, lineChars = lineChars)
ReminderDescription.FULL -> text
}
}
/**
* [description] cut to about [maxLines] lines of an expanded notification,
* ending in an ellipsis when anything was left out. A long line counts as the
* lines it wraps to and a blank line as one; text that fits comes back unchanged.
*/
internal fun shortDescription(
description: String,
maxLines: Int = 3,
lineChars: Int = NOTIFICATION_LINE_CHARS,
): String {
val perLine = lineChars.coerceAtLeast(2)
val kept = mutableListOf<String>()
var rowsLeft = maxLines
val lines = description.lineSequence().iterator()
while (lines.hasNext()) {
val line = lines.next()
val last = !lines.hasNext()
val width = displayWidth(line)
val rows = ((width + perLine - 1) / perLine).coerceAtLeast(1)
// The ellipsis after a line that ends the budget needs a cell of its own.
val fits = rows < rowsLeft || (rows == rowsLeft && (last || width < rows * perLine))
if (fits) {
if (last) return description
kept += line
rowsLeft -= rows
if (rowsLeft == 0) return ellipsize(kept)
continue
}
if (rowsLeft > 0) kept += cutAtWord(line, rowsLeft * perLine - 1)
return ellipsize(kept)
}
return description
}
private fun ellipsize(lines: List<String>): String =
lines.joinToString("\n").trimEnd { it.isWhitespace() || it in ".,;:" } + "…"
/** [line] cut to at most [max] cells, at a word break when there is one, never inside a character. */
private fun cutAtWord(line: String, max: Int): String {
var end = 0
var width = 0
forEachGrapheme(line) { _, clusterEnd, cells ->
width += cells
if (width > max) return@forEachGrapheme false
end = clusterEnd
true
}
if (end >= line.length || line[end].isWhitespace()) return line.substring(0, end)
val cut = line.substring(0, end)
val space = cut.indexOfLast { it.isWhitespace() }
return if (space > end / 2) cut.substring(0, space) else cut
}
/** How many cells [text] takes; see [clusterCells]. */
internal fun displayWidth(text: String): Int {
var width = 0
forEachGrapheme(text) { _, _, cells ->
width += cells
true
}
return width
}
/** Calls [action] with each grapheme cluster's bounds and cells, until it returns false. */
private inline fun forEachGrapheme(text: String, action: (start: Int, end: Int, cells: Int) -> Boolean) {
val clusters = BreakIterator.getCharacterInstance()
clusters.setText(text)
var start = clusters.first()
var end = clusters.next()
while (end != BreakIterator.DONE) {
if (!action(start, end, clusterCells(text, start, end))) return
start = end
end = clusters.next()
}
}
/**
* Cells one grapheme cluster takes: none for lone marks and selectors, two for
* emoji and East Asian wide characters, one otherwise.
*/
private fun clusterCells(text: String, start: Int, end: Int): Int {
var base = -1
var emoji = false
var i = start
while (i < end) {
val codePoint = text.codePointAt(i)
if (codePoint == EMOJI_PRESENTATION || isPictographic(codePoint)) emoji = true
if (base < 0 && !isZeroWidth(codePoint)) base = codePoint
i += Character.charCount(codePoint)
}
return when {
base < 0 -> 0
emoji || WIDE_RANGES.any { base in it } -> 2
else -> 1
}
}
private const val EMOJI_PRESENTATION = 0xFE0F
private fun isZeroWidth(codePoint: Int): Boolean = when (Character.getType(codePoint).toByte()) {
Character.NON_SPACING_MARK, Character.ENCLOSING_MARK, Character.FORMAT -> true
else -> codePoint in 0xFE00..0xFE0F || codePoint in 0xE0100..0xE01EF
}
/** Emoji blocks, approximating Extended_Pictographic without ICU. */
private fun isPictographic(codePoint: Int): Boolean =
codePoint in 0x1F000..0x1FAFF || codePoint in 0x2600..0x27BF ||
codePoint in 0x2300..0x23FF || codePoint in 0x2B00..0x2BFF
/** East Asian Wide and Fullwidth: Hangul, CJK punctuation, kana, Han, fullwidth forms. */
private val WIDE_RANGES = listOf(
0x1100..0x115F,
0x2E80..0x303E,
0x3041..0x33FF,
0x3400..0x4DBF,
0x4E00..0x9FFF,
0xA000..0xA4CF,
0xAC00..0xD7A3,
0xF900..0xFAFF,
0xFE30..0xFE4F,
0xFF00..0xFF60,
0xFFE0..0xFFE6,
0x20000..0x3FFFD,
)
@@ -3,12 +3,10 @@ package de.jeanlucmakiola.agendula.data.sync
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
import de.jeanlucmakiola.agendula.data.sync.push.PushRegistrar
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.data.tasks.StorageMode
import de.jeanlucmakiola.agendula.data.tasks.room.AccountEntity
import de.jeanlucmakiola.agendula.data.tasks.room.TaskListEntity
import de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase
import de.jeanlucmakiola.caldav.CalDavDiscovery
import de.jeanlucmakiola.caldav.ServerTrust
import de.jeanlucmakiola.caldav.TaskCollection
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
@@ -18,7 +16,6 @@ import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import java.io.IOException
import javax.inject.Inject
import javax.inject.Singleton
@@ -38,12 +35,7 @@ interface AccountCreator {
selected: Set<TaskCollection>,
/** An existing account to sign in again, instead of creating one. */
reauthenticating: Long? = null,
/** What the user agreed to trust on the way here; saved with the account. */
trust: ServerTrust = ServerTrust.DEFAULT,
): AccountRepository.Outcome
/** What [accountId] was set up trusting, so signing in again starts from it. */
suspend fun trustFor(accountId: Long): ServerTrust
}
/**
@@ -67,7 +59,6 @@ class AccountRepository @Inject constructor(
private val quarantine: QuarantineStore,
private val notices: SyncNoticeStore,
private val collectionSupport: CollectionSupportStore,
private val serverTrust: ServerTrustStore,
private val gateway: CalDavGateway,
private val availability: SyncAvailability,
private val settings: SettingsPrefs,
@@ -106,11 +97,6 @@ class AccountRepository @Inject constructor(
/** The accounts, observed, so a sync landing updates a screen that is open. */
fun observeAll(): Flow<List<AccountEntity>> = database.accounts().observeAll()
/** Names the account on screen; blank goes back to the default (#105). */
suspend fun setLabel(accountId: Long, label: String) = withContext(io) {
database.accounts().setLabel(accountId, label.trim().ifEmpty { null })
}
/** Every account's synced lists. */
fun observeSyncedLists(): Flow<List<TaskListEntity>> = database.taskLists().observeSynced()
@@ -129,7 +115,6 @@ class AccountRepository @Inject constructor(
found: CalDavDiscovery.Outcome.Found,
selected: Set<TaskCollection>,
reauthenticating: Long?,
trust: ServerTrust,
): Outcome = withContext(io) {
if (!availability.accountsUsable()) return@withContext Outcome.ExternalStorage
// "Sign in again" names its account, so a login name the server spells
@@ -137,7 +122,7 @@ class AccountRepository @Inject constructor(
// Only on the same server: anything else is a different account.
val target = reauthenticating?.let { database.accounts().account(it) }
if (target != null && sameServer(target, found)) {
return@withContext reauthenticate(target, target.displayName, username, appPassword, found, selected, trust)
return@withContext reauthenticate(target, target.displayName, username, appPassword, found, selected)
}
// Both stores, not just one. There is no unique index on
// accounts.display_name and nothing prunes Room when the system account
@@ -154,7 +139,7 @@ class AccountRepository @Inject constructor(
// same name is still a duplicate, so this can never silently overwrite a
// working credential.
if (existing != null && accountState.needsSignIn(existing.id)) {
return@withContext reauthenticate(existing, displayName, username, appPassword, found, selected, trust)
return@withContext reauthenticate(existing, displayName, username, appPassword, found, selected)
}
if (existing != null) return@withContext Outcome.AlreadyExists
@@ -195,15 +180,6 @@ class AccountRepository @Inject constructor(
inserted += attach(id, selected)
id
}
// Inside the rollback's reach: a DataStore failure here would otherwise
// leave the row with no credential, the hazard the comment above names.
if (!saveTrust(accountId, trust)) {
rollback(accountId, inserted)
return@withContext Outcome.CredentialFailed(
Outcome.Cause.NOT_SAVED,
"the server trust could not be stored",
)
}
if (!credentials.put(accountId, appPassword)) {
// Never leave a half-made account behind: without a credential it
@@ -231,8 +207,6 @@ class AccountRepository @Inject constructor(
}
}
override suspend fun trustFor(accountId: Long): ServerTrust = serverTrust.get(accountId)
/**
* Points [selected] at [accountId], re-attaching what a previous removal
* left behind rather than inserting a second copy.
@@ -324,7 +298,6 @@ class AccountRepository @Inject constructor(
val outcome = gateway.discover(
principal.toString(),
CalDavGateway.Credentials(username, password, principal),
serverTrust.get(accountId),
)
) {
is CalDavDiscovery.Outcome.Found -> Collections.Found(outcome.collections, attached)
@@ -333,10 +306,6 @@ class AccountRepository @Inject constructor(
-> Collections.NeedsSignIn
is CalDavDiscovery.Outcome.NotCalDav -> Collections.Failed(outcome.cause)
is CalDavDiscovery.Outcome.Failed -> Collections.Failed(outcome.cause)
// A certificate that changed since it was trusted. The account offers
// "Sign in again" for a certificate failure, and that flow re-asks.
is CalDavDiscovery.Outcome.UntrustedCertificate ->
Collections.Failed(CalDavDiscovery.Outcome.Cause.TLS)
}
}
@@ -376,7 +345,6 @@ class AccountRepository @Inject constructor(
cadence.forget(dropped)
quarantine.forget(dropped)
change.drop.forEach { notices.forgetList(accountId, it.name) }
if (!keepUnticked) runCatching { settings.forgetDeletedLists(change.drop.map { it.id }, StorageMode.OWN) }
if (change.attach.isNotEmpty()) syncTrigger.enqueue(account.displayName, expedited = true)
}
}
@@ -418,7 +386,6 @@ class AccountRepository @Inject constructor(
appPassword: String,
found: CalDavDiscovery.Outcome.Found,
selected: Set<TaskCollection>,
trust: ServerTrust,
): Outcome {
val accountId = existing.id
if (!credentials.put(accountId, appPassword)) {
@@ -427,11 +394,6 @@ class AccountRepository @Inject constructor(
"the device keystore would not store the password",
)
}
// Before anything else changes, so a failure leaves the account stopped
// and the sign-in retryable rather than signed in with the old trust.
if (!withContext(NonCancellable) { saveTrust(accountId, trust) }) {
return Outcome.CredentialFailed(Outcome.Cause.NOT_SAVED, "the server trust could not be stored")
}
withContext(NonCancellable) {
database.runInTransaction {
database.accounts().update(
@@ -475,23 +437,11 @@ class AccountRepository @Inject constructor(
* and holds the user's tasks; `SET NULL` returns it to being device-only,
* which is exactly where it came from.
*/
private suspend fun rollback(accountId: Long, inserted: List<Long>) {
database.runInTransaction {
inserted.forEach { database.taskLists().delete(it) }
database.accounts().delete(accountId)
}
// Ids are never reused, and a later create overwrites the keys anyway.
runCatching { serverTrust.forget(accountId) }
private fun rollback(accountId: Long, inserted: List<Long>) = database.runInTransaction {
inserted.forEach { database.taskLists().delete(it) }
database.accounts().delete(accountId)
}
private suspend fun saveTrust(accountId: Long, trust: ServerTrust): Boolean =
try {
serverTrust.put(accountId, trust)
true
} catch (_: IOException) {
false
}
/**
* Puts every existing account back on the periodic schedule.
*
@@ -570,11 +520,7 @@ class AccountRepository @Inject constructor(
// no Agendula account to delete — but "I want it gone from this
// device too" is a reasonable thing to want, and it is the only
// way to get the tasks off the device without also uninstalling.
if (deleteLocalData) {
val deleted = database.taskLists().idsForAccount(accountId)
database.taskLists().deleteForAccount(accountId)
runCatching { settings.forgetDeletedLists(deleted, StorageMode.OWN) }
}
if (deleteLocalData) database.taskLists().deleteForAccount(accountId)
accountState.setNeedsSignIn(accountId, false)
// Keyed by account id, exactly like the flag above, and just as
@@ -584,7 +530,6 @@ class AccountRepository @Inject constructor(
// The same reasoning, for what the server said it would let us
// create: keyed by an id nothing will ever mention again.
collectionSupport.forget(accountId)
serverTrust.forget(accountId)
credentials.clear(accountId)
database.accounts().delete(accountId)
accounts.find(displayName)?.let { accounts.remove(it) }
@@ -612,7 +557,6 @@ class AccountRepository @Inject constructor(
try {
gateway.revokeAppPassword(
CalDavGateway.Credentials(username, password, origin),
serverTrust.get(accountId),
)
} catch (_: CancellationException) {
// Deliberately swallowed. If the caller went away mid-revoke we still
@@ -4,10 +4,9 @@ import de.jeanlucmakiola.agendula.data.di.IoDispatcher
import de.jeanlucmakiola.caldav.AppPassword
import de.jeanlucmakiola.caldav.CalDavDiscovery
import de.jeanlucmakiola.caldav.CalDavHttp
import de.jeanlucmakiola.caldav.DnsJavaResolver
import de.jeanlucmakiola.caldav.NextcloudLoginFlow
import de.jeanlucmakiola.caldav.ServerTrust
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.job
import kotlinx.coroutines.withContext
import okhttp3.HttpUrl
import java.util.concurrent.TimeUnit
@@ -26,22 +25,12 @@ import javax.inject.Singleton
interface CalDavGateway {
/** Discovery against [target], optionally carrying credentials. */
suspend fun discover(
target: String,
credentials: Credentials? = null,
trust: ServerTrust = ServerTrust.DEFAULT,
): CalDavDiscovery.Outcome
suspend fun discover(target: String, credentials: Credentials? = null): CalDavDiscovery.Outcome
/** Starts Nextcloud Login Flow v2, or returns null if this is not a Nextcloud. */
suspend fun startLoginFlow(
server: HttpUrl,
trust: ServerTrust = ServerTrust.DEFAULT,
): NextcloudLoginFlow.Flow?
suspend fun startLoginFlow(server: HttpUrl): NextcloudLoginFlow.Flow?
suspend fun pollLoginFlow(
flow: NextcloudLoginFlow.Flow,
trust: ServerTrust = ServerTrust.DEFAULT,
): NextcloudLoginFlow.PollResult
suspend fun pollLoginFlow(flow: NextcloudLoginFlow.Flow): NextcloudLoginFlow.PollResult
/**
* Hands an app password back to the server, best effort.
@@ -49,10 +38,7 @@ interface CalDavGateway {
* Without it, uninstalling never revokes anything — the credential we minted
* outlives the app in the user's device list.
*/
suspend fun revokeAppPassword(
credentials: Credentials,
trust: ServerTrust = ServerTrust.DEFAULT,
): Boolean
suspend fun revokeAppPassword(credentials: Credentials): Boolean
/**
* The same, for a password the login flow just minted.
@@ -63,10 +49,7 @@ interface CalDavGateway {
* principal, and a subpath install's `https://host/nextcloud/` would collapse
* to `https://host/` — a DELETE that 404s on every one of them.
*/
suspend fun revokeIssuedAppPassword(
credentials: Credentials,
trust: ServerTrust = ServerTrust.DEFAULT,
): Boolean
suspend fun revokeIssuedAppPassword(credentials: Credentials): Boolean
/** Credentials, and the origin whose registrable domain they are scoped to. */
data class Credentials(val username: String, val password: String, val origin: HttpUrl)
@@ -88,19 +71,16 @@ class OkHttpCalDavGateway @Inject constructor(
override suspend fun discover(
target: String,
credentials: CalDavGateway.Credentials?,
trust: ServerTrust,
): CalDavDiscovery.Outcome = withContext(io) {
val client = credentials?.let {
CalDavHttp.authenticated(userAgent, it.username, it.password, it.origin, trust)
} ?: CalDavHttp.anonymous(userAgent, trust)
val job = coroutineContext.job
CalDavDiscovery(client, SystemDnsResolver { !job.isActive }, allowCleartext = trust.allowCleartext)
.discover(target)
CalDavHttp.authenticated(userAgent, it.username, it.password, it.origin)
} ?: CalDavHttp.anonymous(userAgent)
CalDavDiscovery(client, DnsJavaResolver()).discover(target)
}
override suspend fun startLoginFlow(server: HttpUrl, trust: ServerTrust): NextcloudLoginFlow.Flow? =
override suspend fun startLoginFlow(server: HttpUrl): NextcloudLoginFlow.Flow? =
withContext(io) {
NextcloudLoginFlow(CalDavHttp.anonymous(userAgent, trust), userAgent)
NextcloudLoginFlow(CalDavHttp.anonymous(userAgent), userAgent)
.start(server, now())
.getOrNull()
}
@@ -112,12 +92,9 @@ class OkHttpCalDavGateway @Inject constructor(
* the shared client's ceiling is sized for a multiget, not for a two-second
* poll loop against a server that answered a moment ago.
*/
override suspend fun pollLoginFlow(
flow: NextcloudLoginFlow.Flow,
trust: ServerTrust,
): NextcloudLoginFlow.PollResult =
override suspend fun pollLoginFlow(flow: NextcloudLoginFlow.Flow): NextcloudLoginFlow.PollResult =
withContext(io) {
val client = CalDavHttp.anonymous(userAgent, trust).newBuilder()
val client = CalDavHttp.anonymous(userAgent).newBuilder()
.callTimeout(POLL_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.build()
NextcloudLoginFlow(client, userAgent).poll(flow, now())
@@ -125,20 +102,18 @@ class OkHttpCalDavGateway @Inject constructor(
override suspend fun revokeAppPassword(
credentials: CalDavGateway.Credentials,
trust: ServerTrust,
): Boolean = withContext(io) {
val client = CalDavHttp.authenticated(
userAgent, credentials.username, credentials.password, credentials.origin, trust,
userAgent, credentials.username, credentials.password, credentials.origin,
)
AppPassword.revoke(client, credentials.origin)
}
override suspend fun revokeIssuedAppPassword(
credentials: CalDavGateway.Credentials,
trust: ServerTrust,
): Boolean = withContext(io) {
val client = CalDavHttp.authenticated(
userAgent, credentials.username, credentials.password, credentials.origin, trust,
userAgent, credentials.username, credentials.password, credentials.origin,
)
AppPassword.revokeAt(client, credentials.origin)
}
@@ -1,10 +1,8 @@
package de.jeanlucmakiola.agendula.data.sync
import de.jeanlucmakiola.agendula.data.tasks.ical.AlarmCodec
import de.jeanlucmakiola.agendula.data.tasks.ical.CalendarResource
import de.jeanlucmakiola.agendula.data.tasks.ical.ResourceValidator
import de.jeanlucmakiola.agendula.data.tasks.ical.VTodoMapper
import de.jeanlucmakiola.agendula.data.tasks.room.TaskAlarmEntity
import de.jeanlucmakiola.agendula.data.tasks.room.TaskEntity
import de.jeanlucmakiola.agendula.data.tasks.room.TaskListEntity
import at.bitfire.dav4jvm.exception.UnauthorizedException
@@ -417,22 +415,15 @@ class CollectionSyncer(
return@forEach
}
if (href == null) {
val body = serialize(local) ?: return@forEach
createResource(local, body)
} else {
val revised = local.revised()
val body = serialize(revised) ?: return@forEach
updateResource(revised, href, body)
}
val body = serialize(local) ?: return@forEach
if (href == null) createResource(local, body) else updateResource(local, href, body)
}
}
/** Null when the resource was rejected before it left the device. */
private fun serialize(local: LocalResource): String? {
val alarms = store.alarmsFor(local.live.map { it.id })
val todos = local.live.map { row ->
VTodoMapper.write(row, parentUidOf(row), now(), alarms[row.id].orEmpty())
VTodoMapper.write(row, parentUidOf(row), now())
}
val calendar = CalendarResource.build(todos)
@@ -499,9 +490,7 @@ class CollectionSyncer(
val existing = fetched.resources.firstOrNull()
val sameTask = existing != null && uidOf(existing.iCalendar) == local.uid
if (sameTask) {
// An update now, so SEQUENCE goes up as on any other (#137).
val revised = local.revised()
updateResource(revised, outcome.href.toString(), serialize(revised) ?: return)
updateResource(local, outcome.href.toString(), body)
return
}
name = ResourceNames.random()
@@ -617,7 +606,7 @@ class CollectionSyncer(
// via `master_id`.
val (buried, kept) = local.rows.partition { it.isDeleted && it.recurrenceId != null }
if (buried.isNotEmpty()) store.deleteAll(buried.map { it.id })
store.markSynced(kept, key, eTag)
store.markSynced(kept.map { it.id }, key, eTag)
// Both, because a resource that failed as a create was counted under
// its UID and is now counted under its href. Clearing one would leak
// the other into the store forever.
@@ -789,17 +778,14 @@ class CollectionSyncer(
val losing = existing.values.firstOrNull { it.isDirty }
val master = mapped.firstOrNull { it.entity.recurrenceId == null } ?: mapped.first()
val masterRow = upsert(master, existing[master.entity.recurrenceId], null, href, eTag)
val masterRow = upsert(master.entity, existing[master.entity.recurrenceId], null, href, eTag)
val masterId = masterRow.id
parents[uid] = master.parentUid
val written = mutableListOf(masterRow)
mapped.filter { it !== master }.forEach { override ->
// ⚠️ An override's alarms are its own: RFC 5545 has an override
// replace the component, so one the server sends without a
// VALARM has none, whatever its master carries.
written += upsert(
override, existing[override.entity.recurrenceId], masterId, href, eTag,
override.entity, existing[override.entity.recurrenceId], masterId, href, eTag,
)
}
val kept = written.map { it.recurrenceId }.toSet()
@@ -833,7 +819,6 @@ class CollectionSyncer(
}
pendingDiscard.remove(href)?.let { cause ->
store.dropAdvances(masterId)
report = report.copy(
discardedEdits = report.discardedEdits +
DiscardedEdit(uid, losing?.title, cause),
@@ -847,13 +832,12 @@ class CollectionSyncer(
/** @return the row as it now stands, so the caller can index it. */
private fun upsert(
mapped: VTodoMapper.Mapped,
incoming: TaskEntity,
existing: TaskEntity?,
masterId: Long?,
href: String,
eTag: String?,
): TaskEntity {
val incoming = mapped.entity
// Local-only columns the server has no opinion about. Taking the
// mapper's defaults here would silently reset the user's ordering and
// per-task colour on every download.
@@ -870,42 +854,12 @@ class CollectionSyncer(
// set uploads what was just downloaded.
isDirty = false,
isDeleted = false,
// The store's to change, from what the alarms do.
remindersOff = existing?.remindersOff ?: false,
)
// The server's alarms replace ours, as every other field does: a
// dirty row is never downloaded except to discard its edit.
val alarms = existing?.let { keepLocalPrecision(mapped.alarms, it, row) } ?: mapped.alarms
return row.copy(id = store.upsertWithAlarms(row, alarms))
}
/**
* [incoming] with each alarm we uploaded ourselves put back to the lead
* we hold for it.
*
* ⚠️ The wire is coarser than the row: a lead past the end of its
* anchor is clamped, and a before-start reminder on a task without a
* start goes out before-due. Taking the round trip at its word would
* quietly turn a before-start reminder into a before-due one the first
* time the task is downloaded again.
* An alarm that comes back as exactly what we would have sent has not
* been changed, so the row's own lead stands.
*/
private fun keepLocalPrecision(
incoming: List<TaskAlarmEntity>,
existing: TaskEntity,
task: TaskEntity,
): List<TaskAlarmEntity> {
val local = store.alarmsFor(listOf(existing.id))[existing.id].orEmpty()
if (local.isEmpty()) return incoming
return incoming.map { alarm ->
val mine = local.firstOrNull { it.uid == alarm.uid } ?: return@map alarm
val sent = AlarmCodec.wireLead(mine, task)
if (sent == AlarmCodec.Lead(alarm.minutesBefore, alarm.reference)) {
alarm.copy(minutesBefore = mine.minutesBefore, reference = mine.reference)
} else {
alarm
}
return if (existing == null) {
row.copy(id = store.insert(row))
} else {
store.update(row)
row
}
}
@@ -1089,16 +1043,6 @@ class CollectionSyncer(
/** What gets serialised: a deleted override is simply absent. */
val live: List<TaskEntity> = rows.filterNot { it.isDeleted }
/**
* With `SEQUENCE` raised on each changed row. Apple's clients keep their
* cached copy of a task whose `SEQUENCE` did not move (#137).
*/
fun revised(): LocalResource = copy(
rows = rows.map { row ->
if (row.isDirty && !row.isDeleted && VTodoMapper.revisesSequence(row)) row.copy(sequence = row.sequence + 1) else row
},
)
}
private companion object {
@@ -1,23 +0,0 @@
package de.jeanlucmakiola.agendula.data.sync
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.flowOf
/** Pull to sync (#73): syncs every account at once. Inert in the `offline` flavor. */
interface ManualSync {
/** Whether there is anything to sync: our own store, with at least one account. */
val available: Flow<Boolean>
/** True from [syncAll] until the syncs it started have finished. */
val syncing: StateFlow<Boolean>
fun syncAll()
object None : ManualSync {
override val available: Flow<Boolean> = flowOf(false)
override val syncing: StateFlow<Boolean> = MutableStateFlow(false)
override fun syncAll() = Unit
}
}
@@ -7,7 +7,6 @@ import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import de.jeanlucmakiola.agendula.data.di.SyncStateDataStore
import de.jeanlucmakiola.caldav.NextcloudLoginFlow
import de.jeanlucmakiola.caldav.ServerTrust
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
@@ -24,8 +23,8 @@ import javax.inject.Singleton
*/
interface LoginFlowRecord {
/** Called **before** the browser is handed the URL; [trust] is what reaching it took. */
suspend fun remember(flow: NextcloudLoginFlow.Flow, trust: ServerTrust = ServerTrust.DEFAULT)
/** Called **before** the browser is handed the URL. */
suspend fun remember(flow: NextcloudLoginFlow.Flow)
/** The flow is over, however it ended. */
suspend fun forget()
@@ -59,13 +58,12 @@ class PendingLoginFlowStore @Inject constructor(
private var reclaimed = false
/** Records [flow] so a process that dies mid-approval can still finish with it. */
override suspend fun remember(flow: NextcloudLoginFlow.Flow, trust: ServerTrust) {
override suspend fun remember(flow: NextcloudLoginFlow.Flow) {
dataStore.edit { prefs ->
prefs[LOGIN_URL] = flow.loginUrl.toString()
prefs[POLL_ENDPOINT] = flow.pollEndpoint.toString()
prefs[POLL_TOKEN] = flow.pollToken
prefs[DEADLINE] = flow.deadlineEpochSeconds
TRUST.write(prefs, trust)
}
}
@@ -76,7 +74,6 @@ class PendingLoginFlowStore @Inject constructor(
prefs.remove(POLL_ENDPOINT)
prefs.remove(POLL_TOKEN)
prefs.remove(DEADLINE)
TRUST.remove(prefs)
}
}
@@ -101,8 +98,7 @@ class PendingLoginFlowStore @Inject constructor(
reclaimed = true
}
val flow = pending() ?: return
val trust = trust()
when (val result = gateway.pollLoginFlow(flow, trust)) {
when (val result = gateway.pollLoginFlow(flow)) {
is NextcloudLoginFlow.PollResult.Approved -> {
// Cleared first: a revocation that fails must not leave a token
// that would be polled again, and the 200 is already spent.
@@ -113,7 +109,6 @@ class PendingLoginFlowStore @Inject constructor(
password = result.credentials.appPassword,
origin = result.credentials.server,
),
trust,
)
}
@@ -141,13 +136,10 @@ class PendingLoginFlowStore @Inject constructor(
)
}
private suspend fun trust(): ServerTrust = TRUST.read(dataStore.data.first())
private companion object {
val LOGIN_URL = stringPreferencesKey("login_flow_url")
val POLL_ENDPOINT = stringPreferencesKey("login_flow_poll_endpoint")
val POLL_TOKEN = stringPreferencesKey("login_flow_poll_token")
val DEADLINE = longPreferencesKey("login_flow_deadline")
val TRUST = ServerTrustKeys("login_flow_trusted_certificates", "login_flow_cleartext")
}
}
@@ -1,8 +1,6 @@
package de.jeanlucmakiola.agendula.data.sync
import de.jeanlucmakiola.agendula.data.CollectionHref
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
import de.jeanlucmakiola.agendula.data.sync.RemoteLists.Outcome
import de.jeanlucmakiola.agendula.data.sync.push.PushStore
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
import de.jeanlucmakiola.agendula.data.tasks.StorageMode
@@ -14,9 +12,7 @@ import de.jeanlucmakiola.caldav.CollectionAdmin
import de.jeanlucmakiola.caldav.CollectionOutcome
import de.jeanlucmakiola.caldav.CollectionSupport
import de.jeanlucmakiola.caldav.DavCollectionAdmin
import de.jeanlucmakiola.caldav.HomeSets
import de.jeanlucmakiola.caldav.ResourceNames
import de.jeanlucmakiola.caldav.ServerTrust
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.async
@@ -56,9 +52,39 @@ class RemoteListRepository @Inject constructor(
private val accountState: AccountStateStore,
private val resolver: ProviderResolver,
private val push: PushStore,
private val trust: ServerTrustStore,
@IoDispatcher private val io: CoroutineDispatcher,
) : RemoteLists {
) {
/** Why a collection write did not happen, in a form the UI can translate. */
sealed interface Outcome {
data object Done : Outcome
/** The server said no, and will say no again. */
data class Refused(val code: Int) : Outcome
/** The server could not be reached. Worth another try. */
data object Unreachable : Outcome
/** This account cannot make collections at all — iCloud, Posteo, Google. */
data object Unsupported : Outcome
/** Ours is a read-only share; the write belongs to whoever owns it. */
data object ReadOnly : Outcome
/** The account is gone, stopped, or has no credential we can decrypt. */
data object NoAccount : Outcome
/**
* The server answered something this call cannot make sense of.
*
* ⚠️ Not [Unreachable]. `CollectionOutcome` is one type across create,
* update and delete, so each of them has branches the other's method
* can return and its own cannot — and mapping those to [Unreachable]
* told someone sitting on wifi that they were offline. Unreachable is a
* claim about the network, and this is not one.
*/
data object Unexpected : Outcome
}
/**
* The accounts a new list may be created on, freshest answer first.
@@ -69,7 +95,7 @@ class RemoteListRepository @Inject constructor(
* able to say so, and the only moment that costs nothing is while the user
* is looking at the picker.
*/
override suspend fun creatableAccounts(): List<AccountEntity> = withContext(io) {
suspend fun creatableAccounts(): List<AccountEntity> = withContext(io) {
// ⚠️ Empty in External mode, whatever the accounts table holds. The
// lists on screen then come from a third-party provider, so a row
// inserted into ours would exist, sync, and be visible to nobody.
@@ -94,7 +120,7 @@ class RemoteListRepository @Inject constructor(
*
* @return the new list's local id, or why there is none.
*/
override suspend fun create(
suspend fun create(
accountId: Long,
name: String,
color: Int,
@@ -163,7 +189,7 @@ class RemoteListRepository @Inject constructor(
* a row that has already been renamed locally by then reads as a rename that
* worked and then quietly reverted on the next sync.
*/
override suspend fun rename(listId: Long, name: String, color: Int): Outcome = withContext(io) {
suspend fun rename(listId: Long, name: String, color: Int): Outcome = withContext(io) {
val list = database.taskLists().entity(listId) ?: return@withContext Outcome.NoAccount
if (list.isReadOnly) return@withContext Outcome.ReadOnly
val url = list.href?.toHttpUrlOrNull() ?: return@withContext Outcome.NoAccount
@@ -201,24 +227,13 @@ class RemoteListRepository @Inject constructor(
* grades 404 and 410 that way — because otherwise a collection someone
* removed from another client leaves a row here that nothing can get rid of.
*/
override suspend fun delete(listId: Long): Outcome = withContext(io) {
suspend fun delete(listId: Long): Outcome = withContext(io) {
val list = database.taskLists().entity(listId) ?: return@withContext Outcome.Done
if (list.isReadOnly) return@withContext Outcome.ReadOnly
val url = list.href?.toHttpUrlOrNull() ?: return@withContext Outcome.NoAccount
val account = list.accountId?.let { database.accounts().account(it) }
?: return@withContext Outcome.NoAccount
if (CollectionHref.same(list.href, account.homeSetUrl)) return@withContext Outcome.AccountHome
val admin = adminFor(account) ?: return@withContext Outcome.NoAccount
// Only the first home set is stored, so the others are asked for. A
// principal that does not answer leaves the stored check above as the
// guard, rather than blocking every delete on this account (#180).
when (val homeSets = account.principalUrl?.toHttpUrlOrNull()?.let(admin::homeSets)) {
is HomeSets.Listed -> if (homeSets.urls.any { CollectionHref.same(it.toString(), list.href) }) {
return@withContext Outcome.AccountHome
}
is HomeSets.Refused -> return@withContext Outcome.Refused(homeSets.code)
HomeSets.Unknown, null -> Unit
}
when (val outcome = admin.delete(url)) {
CollectionOutcome.Updated -> {
@@ -267,11 +282,11 @@ class RemoteListRepository @Inject constructor(
val origin = account.principalUrl?.toHttpUrlOrNull() ?: return null
val password = (credentials.get(account.id) as? CredentialStore.Secret.Present)?.value
?: return null
return DavCollectionAdmin(client(username, password, origin, trust.get(account.id)))
return DavCollectionAdmin(client(username, password, origin))
}
private fun client(username: String, password: String, origin: HttpUrl, trust: ServerTrust): OkHttpClient =
CalDavHttp.authenticated(USER_AGENT, username, password, origin, trust)
private fun client(username: String, password: String, origin: HttpUrl): OkHttpClient =
CalDavHttp.authenticated(USER_AGENT, username, password, origin)
private suspend fun forgetPerListState(listId: Long) {
val ids = setOf(listId)
@@ -1,55 +0,0 @@
package de.jeanlucmakiola.agendula.data.sync
import de.jeanlucmakiola.agendula.data.tasks.room.AccountEntity
/**
* Task lists that live on a server: making, renaming, recolouring and deleting
* them. The `full` flavor talks CalDAV; the `offline` one has no accounts, so
* every list is device-only and none of this is ever reached with a real one.
*/
interface RemoteLists {
/** Why a collection write did not happen, in a form the UI can translate. */
sealed interface Outcome {
data object Done : Outcome
/** The server said no, and will say no again. */
data class Refused(val code: Int) : Outcome
/** The server could not be reached. Worth another try. */
data object Unreachable : Outcome
/** This account cannot make collections at all — iCloud, Posteo, Google. */
data object Unsupported : Outcome
/** Ours is a read-only share; the write belongs to whoever owns it. */
data object ReadOnly : Outcome
/** The list is the account's home set itself, which the app never deletes (#180). */
data object AccountHome : Outcome
/** The account is gone, stopped, or has no credential we can decrypt. */
data object NoAccount : Outcome
/**
* The server answered something this call cannot make sense of.
*
* ⚠️ Not [Unreachable]. `CollectionOutcome` is one type across create,
* update and delete, so each of them has branches the other's method
* can return and its own cannot — and mapping those to [Unreachable]
* told someone sitting on wifi that they were offline. Unreachable is a
* claim about the network, and this is not one.
*/
data object Unexpected : Outcome
}
/** The accounts a new list may be created on. */
suspend fun creatableAccounts(): List<AccountEntity>
/** Makes a collection on [accountId]'s home set and a row pointing at it. */
suspend fun create(accountId: Long, name: String, color: Int): Outcome
suspend fun rename(listId: Long, name: String, color: Int): Outcome
suspend fun delete(listId: Long): Outcome
}
@@ -33,7 +33,6 @@ class SyncEngine @Inject constructor(
private val notices: SyncNoticeStore,
private val availability: SyncAvailability,
private val push: PushRegistrar,
private val trust: ServerTrustStore,
@IoDispatcher private val io: CoroutineDispatcher,
) {
@@ -91,7 +90,7 @@ class SyncEngine @Inject constructor(
}
}
val client = CalDavHttp.authenticated(USER_AGENT, username, password, origin, trust.get(account.id))
val client = CalDavHttp.authenticated(USER_AGENT, username, password, origin)
val subscriptions = push.subscriptionsByHref(account.id)
val reports = syncCollections(account) { url ->
CalendarCollection(client, url, pushRegistration = subscriptions[url.toString()])
@@ -49,7 +49,6 @@ data class SyncFailure(val kind: Kind, val httpCode: Int? = null) {
private val TLS = listOf(
"SSLHandshakeException",
"SSLPeerUnverifiedException",
"UntrustedHostException",
"CertPathValidatorException",
"CertificateException",
"SSLException",
@@ -1,18 +1,19 @@
package de.jeanlucmakiola.agendula.data.sync
import android.Manifest
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.agendula.MainActivity
import de.jeanlucmakiola.agendula.data.di.ChannelRefresher
import de.jeanlucmakiola.agendula.data.reminders.canPostNotifications
import de.jeanlucmakiola.agendula.R
import javax.inject.Inject
import javax.inject.Singleton
@@ -32,10 +33,13 @@ import javax.inject.Singleton
@Singleton
class SyncNoticeNotifier @Inject constructor(
@ApplicationContext private val context: Context,
) : ChannelRefresher {
) {
fun canPost(): Boolean {
return context.canPostNotifications()
val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) ==
PackageManager.PERMISSION_GRANTED
return granted && NotificationManagerCompat.from(context).areNotificationsEnabled()
}
// canPost() checks POST_NOTIFICATIONS before we ever call notify().
@@ -119,7 +123,7 @@ class SyncNoticeNotifier @Inject constructor(
* extra names the account for routing to Settings → Accounts → it.
*/
private fun signInIntent(accountId: Long): Intent =
MainActivity.openIntent(context).putExtra(MainActivity.EXTRA_SIGN_IN_ACCOUNT_ID, accountId)
MainActivity.openIntent(context).putExtra(EXTRA_SIGN_IN_ACCOUNT_ID, accountId)
private fun ensureSignInChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
@@ -166,13 +170,16 @@ class SyncNoticeNotifier @Inject constructor(
}
/** Re-create the channel, if it exists, in the current language. */
override fun refreshChannel() {
fun refreshChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val manager = context.getSystemService(NotificationManager::class.java)
if (manager.getNotificationChannel(CHANNEL_ID) != null) ensureChannel()
}
companion object {
/** The account a sign-in notification is about, on the intent it opens. */
const val EXTRA_SIGN_IN_ACCOUNT_ID = "de.jeanlucmakiola.agendula.extra.SIGN_IN_ACCOUNT_ID"
private const val CHANNEL_ID = "sync_notices"
private const val NOTIFICATION_ID = 2
private const val SIGN_IN_CHANNEL_ID = "account_sign_in"
@@ -1,6 +0,0 @@
package de.jeanlucmakiola.agendula.data.sync
/** Asks for an account to be synced now. A no-op in the `offline` flavor. */
fun interface SyncRequests {
suspend fun syncNow(accountId: Long)
}
@@ -0,0 +1,88 @@
package de.jeanlucmakiola.agendula.data.sync
import de.jeanlucmakiola.agendula.data.tasks.room.TaskEntity
import de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase
import javax.inject.Inject
/**
* The database, as [CollectionSyncer] needs it.
*
* A seam, and the reason is the same one that put [CalDavGateway] in front of
* discovery: the reconciliation above this interface is where local edits are
* discarded, tombstones swept and conflicts resolved, and every one of those is
* a decision that should be provable without a device. Room's test double is
* Robolectric plus an in-memory database; this is eight methods.
*/
interface SyncStore {
/** Every row in a list, **tombstones included**. */
fun rowsIn(listId: Long): List<TaskEntity>
fun insert(row: TaskEntity): Long
fun update(row: TaskEntity)
fun deleteAll(taskIds: List<Long>)
/**
* Records href and ETag on a resource's rows, clearing `is_dirty`.
*
* The caller excludes any row it left out of the body — that row is deleted,
* not marked synced.
*/
fun markSynced(taskIds: List<Long>, href: String?, eTag: String?)
fun setParent(taskId: Long, parentId: Long?)
/** The master row for a UID — the one with no `RECURRENCE-ID`. */
fun masterByUid(listId: Long, uid: String): TaskEntity?
fun row(taskId: Long): TaskEntity?
/**
* One column, deliberately. A whole-entity update would carry the row as it
* looked when the sync started and revert anything the user changed while it
* ran.
*/
fun setListReadOnly(listId: Long, readOnly: Boolean)
/** The RFC 6578 cursor. Null resets the collection to a full reconciliation. */
fun setSyncToken(listId: Long, token: String?)
}
class RoomSyncStore @Inject constructor(
private val database: TasksDatabase,
) : SyncStore {
override fun rowsIn(listId: Long) = database.tasks().allIn(listId)
override fun insert(row: TaskEntity) = database.tasks().insert(row)
override fun update(row: TaskEntity) {
database.tasks().update(row)
}
override fun deleteAll(taskIds: List<Long>) {
if (taskIds.isNotEmpty()) database.tasks().deleteAll(taskIds)
}
override fun markSynced(taskIds: List<Long>, href: String?, eTag: String?) {
if (taskIds.isNotEmpty()) database.tasks().markSynced(taskIds, href, eTag)
}
override fun setParent(taskId: Long, parentId: Long?) {
database.tasks().setParent(taskId, parentId)
}
override fun masterByUid(listId: Long, uid: String) = database.tasks().byUid(listId, uid)
override fun row(taskId: Long) = database.tasks().entity(taskId)
override fun setListReadOnly(listId: Long, readOnly: Boolean) {
database.taskLists().setReadOnly(listId, readOnly)
}
override fun setSyncToken(listId: Long, token: String?) {
database.taskLists().setSyncToken(listId, token)
}
}
Loaded 100 of 493 files, more files were not shown because too many files have changed in this diff. Show more