Compare commits
222
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a1e16c5f9 | ||
|
|
9492869349 | ||
|
|
7fab350b94 | ||
|
|
3138c25327 | ||
|
|
45179d3fc2 | ||
|
|
515e53390b | ||
|
|
386e13d479 | ||
|
|
354c4245b8 | ||
|
|
82e77b466e | ||
|
|
68ff6dc85d | ||
|
|
0dd7d4ee04 | ||
|
|
8cf778db26 | ||
|
|
68f7922f91 | ||
|
|
4d5d28713e | ||
|
|
40642a755e | ||
|
|
850ffcdfa3 | ||
|
|
ac78c56e03 | ||
|
|
8c960cff17 | ||
|
|
f6c7e3a385 | ||
|
|
4201ef6abe | ||
|
|
878a99bb39 | ||
|
|
4d70732278 | ||
|
|
0fabb6cd58 | ||
|
|
91c6593ceb | ||
|
|
1938991a6b | ||
|
|
624eb4bfed | ||
|
|
42c1df84bd | ||
|
|
1c59c5e409 | ||
|
|
1787580a48 | ||
|
|
4044d0c37f | ||
|
|
86b09708f2 | ||
|
|
9f11adf63b | ||
|
|
6a0bc6ab70 | ||
|
|
74d6be61f2 | ||
|
|
acf482246b | ||
|
|
5f308b47c5 | ||
|
|
cda03e7d6e | ||
|
|
eaa8f3ec74 | ||
|
|
d8b64fb3e1 | ||
|
|
a0fb9e5c72 | ||
|
|
4ed54f6c7e | ||
|
|
8e124fdb0e | ||
|
|
61324a0072 | ||
|
|
220c18170f | ||
|
|
38ef42c280 | ||
|
|
023378ff19 | ||
|
|
0bb465392b | ||
|
|
8c40faee55 | ||
|
|
f3477e096c | ||
|
|
385b2b33ea | ||
|
|
131579271e | ||
|
|
24187503ee | ||
|
|
92899dfd5e | ||
|
|
1417667d07 | ||
|
|
8cdf3ad709 | ||
|
|
d4e1756069 | ||
|
|
e91499529b | ||
|
|
efa71cdb3c | ||
|
|
12dd6b2dec | ||
|
|
9cb5ad2942 | ||
|
|
e1097e9093 | ||
|
|
ad27624188 | ||
|
|
5a464a2212 | ||
|
|
bb7d36385f | ||
|
|
fe63653690 | ||
|
|
82bfda2533 | ||
|
|
96c94eeec3 | ||
|
|
b77311dff7 | ||
|
|
4d833a4da6 | ||
|
|
8dcc48b0ba | ||
|
|
69edcb2b71 | ||
|
|
6352ae3f30 | ||
|
|
64646ffa7b | ||
|
|
05c0199647 | ||
|
|
5e204a43f4 | ||
|
|
a5accc5fef | ||
|
|
8cc9567984 | ||
|
|
7d7ce3d662 | ||
|
|
22b95298e2 | ||
|
|
1a83dedff9 | ||
|
|
f42553d43a | ||
|
|
3cbeff7bdc | ||
|
|
46cd126bf1 | ||
|
|
95cc8cd0dd | ||
|
|
2ce375bb85 | ||
|
|
a82fa01b71 | ||
|
|
d74831c607 | ||
|
|
fd28ffc451 | ||
|
|
d6425124ee | ||
|
|
b71f75dcd2 | ||
|
|
401191658b | ||
|
|
ba45aef1cd | ||
|
|
6d88e9a228 | ||
|
|
514783522b | ||
|
|
94805c5d91 | ||
|
|
5d45647005 | ||
|
|
bf8aaf38a0 | ||
|
|
4796cf9856 | ||
|
|
415622797d | ||
|
|
3b94af47a8 | ||
|
|
e4bb254512 | ||
|
|
b957b20f10 | ||
|
|
33466dc6d9 | ||
|
|
4765344d50 | ||
|
|
c835c13b49 | ||
|
|
3531e169cf | ||
|
|
235d16a6f0 | ||
|
|
d3c382dd63 | ||
|
|
0ea6878a7c | ||
|
|
4992446acf | ||
|
|
dd1a801560 | ||
|
|
9b178fc80b | ||
|
|
450179ffc4 | ||
|
|
ebe3bcc5a8 | ||
|
|
31a62d4c08 | ||
|
|
983af59c7a | ||
|
|
c852e3a8d1 | ||
|
|
4bb48555b0 | ||
|
|
55f149d0f3 | ||
|
|
544c2f4835 | ||
|
|
43f13f682c | ||
|
|
d95fb9c5f9 | ||
|
|
d04ef3d612 | ||
|
|
e3a2d974c7 | ||
|
|
fc72aaf561 | ||
|
|
8138ae4454 | ||
|
|
3adfeb16a5 | ||
|
|
bae04e1839 | ||
|
|
953ded977b | ||
|
|
ce39c6aec0 | ||
|
|
7642c49ef6 | ||
|
|
367e04fa72 | ||
|
|
d59d4a3d44 | ||
|
|
47a79413b1 | ||
|
|
761f3f5b3d | ||
|
|
634a89224c | ||
|
|
a3024c8a24 | ||
|
|
457ebadd7b | ||
|
|
b0885169e7 | ||
|
|
a94b5be885 | ||
|
|
0e9923fcbd | ||
|
|
75e0adfaa8 | ||
|
|
4a98c2eef6 | ||
|
|
4c261cdb9d | ||
|
|
fe59ee6e59 | ||
|
|
70df9c8a4d | ||
|
|
3fecd313f5 | ||
|
|
51fbe1f5f9 | ||
|
|
1ccbd003ac | ||
|
|
9618431f64 | ||
|
|
2e7b5cf3f8 | ||
|
|
4a6879d4b9 | ||
|
|
3f009666c2 | ||
|
|
82f087a73c | ||
|
|
150f10eead | ||
|
|
1f8d8d230d | ||
|
|
711db920d2 | ||
|
|
410a86159a | ||
|
|
8fa15c282f | ||
|
|
8c0aa64202 | ||
|
|
a1bd03eae8 | ||
|
|
f999fb076c | ||
|
|
b9f452adf7 | ||
|
|
5639124fb0 | ||
|
|
dd9911e7dd | ||
|
|
a67d43edda | ||
|
|
4376a48b1e | ||
|
|
867ba6c109 | ||
|
|
d7dfc4da06 | ||
|
|
aa6182b991 | ||
|
|
3347bb13cd | ||
|
|
5c619b8de9 | ||
|
|
1463b08d6f | ||
|
|
3e34c60577 | ||
|
|
caf4357cee | ||
|
|
97164feb39 | ||
|
|
8a521d32f9 | ||
|
|
b68582177b | ||
|
|
05f43d6f76 | ||
|
|
7498ffb37e | ||
|
|
7bcac70cec | ||
|
|
023c0e0157 | ||
|
|
efcd641ea8 | ||
|
|
7d072d0bf7 | ||
|
|
bda1a60959 | ||
|
|
2d7b6309c0 | ||
|
|
78b1cfbaed | ||
|
|
2887176e88 | ||
|
|
44da66bb85 | ||
|
|
c194984a8b | ||
|
|
8f06f24112 | ||
|
|
fb678d008b | ||
|
|
0770158b02 | ||
|
|
d64a770164 | ||
|
|
ff0cc28465 | ||
|
|
6a1733d97b | ||
|
|
7a94ee6786 | ||
|
|
7b5bf86cfa | ||
|
|
ddff57e8fe | ||
|
|
150e5c5f2c | ||
|
|
75ad41c41e | ||
|
|
08c297f30a | ||
|
|
1d6c2a0d59 | ||
|
|
2a1230c0ca | ||
|
|
cd3b33c959 | ||
|
|
8175d58dcd | ||
|
|
05696b2991 | ||
|
|
23f6156e71 | ||
|
|
c1b65c0c86 | ||
|
|
b5ac279b94 | ||
|
|
8fba3f01a4 | ||
|
|
3b73dd4c53 | ||
|
|
01850a7b74 | ||
|
|
28e646fb31 | ||
|
|
6e3cc4bdbd | ||
|
|
b6185ed53c | ||
|
|
9338c64dc7 | ||
|
|
9a72fb0880 | ||
|
|
24e978efc3 | ||
|
|
2740dd5562 | ||
|
|
8dbfd07d10 | ||
|
|
3e1a84ab7d |
No files matched your search
@@ -127,11 +127,13 @@ jobs:
|
|||||||
|
|
||||||
- name: Setup Java
|
- name: Setup Java
|
||||||
if: steps.scope.outputs.code == 'true'
|
if: steps.scope.outputs.code == 'true'
|
||||||
# JetBrains 21 is what gradle-daemon-jvm.properties asks for; installing it
|
# Temurin only launches Gradle: its versions come from Adoptium, while the
|
||||||
# here keeps Gradle from downloading it via foojay.
|
# jetbrains distribution resolves through the GitHub API with the forge's
|
||||||
uses: actions/setup-java@v4
|
# token ("Bad credentials"). Gradle fetches the JBR that
|
||||||
|
# gradle-daemon-jvm.properties pins straight from JetBrains' CDN.
|
||||||
|
uses: actions/setup-java@v5
|
||||||
with:
|
with:
|
||||||
distribution: 'jetbrains'
|
distribution: 'temurin'
|
||||||
java-version: '21'
|
java-version: '21'
|
||||||
|
|
||||||
# Fully qualified on purpose. Codeberg resolves bare `uses:` refs against
|
# Fully qualified on purpose. Codeberg resolves bare `uses:` refs against
|
||||||
@@ -170,6 +172,7 @@ jobs:
|
|||||||
path: |
|
path: |
|
||||||
~/.gradle/caches
|
~/.gradle/caches
|
||||||
~/.gradle/wrapper
|
~/.gradle/wrapper
|
||||||
|
~/.gradle/jdks
|
||||||
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', 'gradle/libs.versions.toml') }}
|
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', 'gradle/libs.versions.toml') }}
|
||||||
restore-keys: |
|
restore-keys: |
|
||||||
${{ runner.os }}-gradle-
|
${{ runner.os }}-gradle-
|
||||||
@@ -195,6 +198,15 @@ jobs:
|
|||||||
if: steps.scope.outputs.code == 'true'
|
if: steps.scope.outputs.code == 'true'
|
||||||
run: ./gradlew assembleDebug
|
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
|
- name: Trivy filesystem scan
|
||||||
if: steps.scope.outputs.code == 'true'
|
if: steps.scope.outputs.code == 'true'
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -70,11 +70,13 @@ jobs:
|
|||||||
submodules: recursive
|
submodules: recursive
|
||||||
|
|
||||||
- name: Setup Java
|
- name: Setup Java
|
||||||
# JetBrains 21 is what gradle-daemon-jvm.properties asks for; installing it
|
# Temurin only launches Gradle: its versions come from Adoptium, while the
|
||||||
# here keeps Gradle from downloading it via foojay.
|
# jetbrains distribution resolves through the GitHub API with the forge's
|
||||||
uses: actions/setup-java@v4
|
# token ("Bad credentials"). Gradle fetches the JBR that
|
||||||
|
# gradle-daemon-jvm.properties pins straight from JetBrains' CDN.
|
||||||
|
uses: actions/setup-java@v5
|
||||||
with:
|
with:
|
||||||
distribution: 'jetbrains'
|
distribution: 'temurin'
|
||||||
java-version: '21'
|
java-version: '21'
|
||||||
|
|
||||||
- name: Setup Android SDK
|
- name: Setup Android SDK
|
||||||
@@ -102,6 +104,7 @@ jobs:
|
|||||||
path: |
|
path: |
|
||||||
~/.gradle/caches
|
~/.gradle/caches
|
||||||
~/.gradle/wrapper
|
~/.gradle/wrapper
|
||||||
|
~/.gradle/jdks
|
||||||
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', 'gradle/libs.versions.toml') }}
|
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', 'gradle/libs.versions.toml') }}
|
||||||
restore-keys: |
|
restore-keys: |
|
||||||
${{ runner.os }}-gradle-
|
${{ runner.os }}-gradle-
|
||||||
|
|||||||
@@ -120,11 +120,13 @@ jobs:
|
|||||||
submodules: recursive
|
submodules: recursive
|
||||||
|
|
||||||
- name: Setup Java
|
- name: Setup Java
|
||||||
# JetBrains 21 is what gradle-daemon-jvm.properties asks for; installing it
|
# Temurin only launches Gradle: its versions come from Adoptium, while the
|
||||||
# here keeps Gradle from downloading it via foojay.
|
# jetbrains distribution resolves through the GitHub API with the forge's
|
||||||
uses: actions/setup-java@v4
|
# token ("Bad credentials"). Gradle fetches the JBR that
|
||||||
|
# gradle-daemon-jvm.properties pins straight from JetBrains' CDN.
|
||||||
|
uses: actions/setup-java@v5
|
||||||
with:
|
with:
|
||||||
distribution: 'jetbrains'
|
distribution: 'temurin'
|
||||||
java-version: '21'
|
java-version: '21'
|
||||||
|
|
||||||
- name: Setup Android SDK
|
- name: Setup Android SDK
|
||||||
@@ -152,6 +154,7 @@ jobs:
|
|||||||
path: |
|
path: |
|
||||||
~/.gradle/caches
|
~/.gradle/caches
|
||||||
~/.gradle/wrapper
|
~/.gradle/wrapper
|
||||||
|
~/.gradle/jdks
|
||||||
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', 'gradle/libs.versions.toml') }}
|
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', 'gradle/libs.versions.toml') }}
|
||||||
restore-keys: |
|
restore-keys: |
|
||||||
${{ runner.os }}-gradle-
|
${{ runner.os }}-gradle-
|
||||||
|
|||||||
+223
@@ -7,6 +7,229 @@ All notable changes to this project are documented here. The format follows
|
|||||||
|
|
||||||
## [Unreleased]
|
## [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).
|
||||||
|
|
||||||
|
### 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
|
## [1.1.0] - 2026-10-10
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
@@ -54,7 +54,8 @@ many small *florets* — so the two apps are florets of one bloom.)
|
|||||||
this and the following ones, or the whole series.
|
this and the following ones, or the whole series.
|
||||||
- **Reminders** that fire at the exact time: several per task, separate defaults
|
- **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
|
for timed and all-day tasks (globally and per list), Done and Snooze right on
|
||||||
the notification, and they survive reboots.
|
the notification, and they survive reboots. They sync as standard `VALARM`s,
|
||||||
|
so they also ring in other CalDAV clients, and theirs ring here.
|
||||||
- **iCalendar import and export** — open an `.ics` or a zip of them, or write any
|
- **iCalendar import and export** — open an `.ics` or a zip of them, or write any
|
||||||
list out as standard `.ics` files.
|
list out as standard `.ics` files.
|
||||||
- A **home-screen widget**, launcher shortcuts, a Quick Settings tile, and
|
- A **home-screen widget**, launcher shortcuts, a Quick Settings tile, and
|
||||||
@@ -101,6 +102,10 @@ 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,
|
OpenTasks rather than replacing it**. If you already sync through a provider,
|
||||||
Agendula can work on top of it exactly as before.
|
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
|
Switching between the two moves nothing — each store keeps its own tasks — so
|
||||||
**Settings → Storage** asks before it switches, and offers to **copy** a
|
**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
|
provider's tasks into Agendula's own store when you want to move over. The copy
|
||||||
@@ -163,7 +168,7 @@ Agendula's own database go with it, so sync them to a CalDAV account first.
|
|||||||
Each Codeberg release also carries `agendula-offline_v<version>.apk`: Agendula
|
Each Codeberg release also carries `agendula-offline_v<version>.apk`: Agendula
|
||||||
without CalDAV sync and **without the network permission**, so it cannot
|
without CalDAV sync and **without the network permission**, so it cannot
|
||||||
connect to anything. It installs alongside the regular app rather than replacing
|
connect to anything. It installs alongside the regular app rather than replacing
|
||||||
it; move tasks between the two with Settings → Storage → Export / Import. In
|
it; move tasks between the two with Settings → Backup & restore → Export / Import. In
|
||||||
Obtainium, pick it with *Filter APKs by regular expression* set to
|
Obtainium, pick it with *Filter APKs by regular expression* set to
|
||||||
`^agendula-offline_v`.
|
`^agendula-offline_v`.
|
||||||
|
|
||||||
|
|||||||
@@ -33,8 +33,8 @@ android {
|
|||||||
// (1.0.x: 1.0.0 -> 10000; from 1.1.0: 1.1.0-beta.1 -> 1010001,
|
// (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.
|
// 1.1.0 -> 1010099), and CI fails if the committed one doesn't match.
|
||||||
// See docs/RELEASING.md.
|
// See docs/RELEASING.md.
|
||||||
versionCode = 1010099
|
versionCode = 1040099
|
||||||
versionName = "1.1.0"
|
versionName = "1.4.0"
|
||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
|
|
||||||
|
|||||||
Vendored
+2
-2
@@ -7,8 +7,8 @@
|
|||||||
# nothing calls it directly — Room then throws InstantiationException, reported
|
# nothing calls it directly — Room then throws InstantiationException, reported
|
||||||
# as "Failed to create an instance of ...". This first bit us through a
|
# as "Failed to create an instance of ...". This first bit us through a
|
||||||
# transitive Room (Glance -> WorkManager -> WorkDatabase, built at startup:
|
# transitive Room (Glance -> WorkManager -> WorkDatabase, built at startup:
|
||||||
# issue #1); Glance is gone and Room is now our own task store, so the rule
|
# issue #1); Room is now also our own task store, so the rule matters more,
|
||||||
# matters more, not less — TasksDatabase is built on the first store read.
|
# not less — TasksDatabase is built on the first store read.
|
||||||
-keep class * extends androidx.room.RoomDatabase { <init>(); }
|
-keep class * extends androidx.room.RoomDatabase { <init>(); }
|
||||||
|
|
||||||
# Compose Compiler may keep its own; defaults are fine
|
# Compose Compiler may keep its own; defaults are fine
|
||||||
|
|||||||
@@ -0,0 +1,548 @@
|
|||||||
|
{
|
||||||
|
"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')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,553 @@
|
|||||||
|
{
|
||||||
|
"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')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,768 @@
|
|||||||
|
{
|
||||||
|
"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')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,775 @@
|
|||||||
|
{
|
||||||
|
"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')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,866 @@
|
|||||||
|
{
|
||||||
|
"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')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
+76
@@ -0,0 +1,76 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
+361
@@ -0,0 +1,361 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
+162
@@ -0,0 +1,162 @@
|
|||||||
|
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() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+214
@@ -0,0 +1,214 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
+827
@@ -0,0 +1,827 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
+141
@@ -0,0 +1,141 @@
|
|||||||
|
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) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+1093
-32
File diff suppressed because it is too large.
Load diff
+143
@@ -75,6 +75,149 @@ class TasksDatabaseMigrationTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@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 {
|
private companion object {
|
||||||
const val TEST_DB = "migration-test.db"
|
const val TEST_DB = "migration-test.db"
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-8
@@ -11,7 +11,7 @@ import com.google.common.truth.Truth.assertThat
|
|||||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderEnvironment
|
import de.jeanlucmakiola.agendula.data.tasks.ProviderEnvironment
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.TaskQuery
|
import de.jeanlucmakiola.agendula.data.tasks.TaskQuery
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.TaskReminder
|
import de.jeanlucmakiola.agendula.domain.TaskReminder
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
|
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.room.AlarmReference
|
import de.jeanlucmakiola.agendula.data.tasks.room.AlarmReference
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase
|
import de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase
|
||||||
@@ -294,23 +294,25 @@ private class FakeExternalStore : TasksDataSource {
|
|||||||
return tasks[listId].orEmpty()
|
return tasks[listId].orEmpty()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun alarms(): Map<Long, TaskReminder> = alarms
|
override fun reminders(): Map<Long, List<TaskReminder>> = alarms.mapValues { listOf(it.value) }
|
||||||
|
|
||||||
override fun tasks(query: TaskQuery): List<Task> = unused()
|
override fun tasks(query: TaskQuery): List<Task> = unused()
|
||||||
override fun task(taskId: Long): Task? = unused()
|
override fun task(taskId: Long): Task? = unused()
|
||||||
override fun subtasks(parentTaskId: Long): List<Task> = unused()
|
override fun subtasks(parentTaskId: Long): List<Task> = unused()
|
||||||
override fun insertTask(form: TaskForm): Long = unused()
|
override fun insertTask(form: TaskForm, reminders: List<TaskReminder>?): Long = unused()
|
||||||
override fun updateTask(taskId: Long, form: TaskForm) = unused()
|
override fun updateTask(taskId: Long, form: TaskForm, reminders: List<TaskReminder>?) = unused()
|
||||||
override fun updateInstance(taskId: Long, occurrenceStart: Instant, form: TaskForm) = unused()
|
override fun updateInstance(taskId: Long, occurrenceStart: Instant, form: TaskForm, reminders: List<TaskReminder>?) =
|
||||||
override fun setAlarm(taskId: Long, minutesBeforeDue: Int?) = unused()
|
unused()
|
||||||
override fun setReminders(taskId: Long, reminders: List<TaskReminder>) = unused()
|
override fun setReminders(taskId: Long, reminders: List<TaskReminder>) = unused()
|
||||||
override fun setCompleted(taskId: Long, completed: Boolean) = unused()
|
override fun setCompleted(taskId: Long, completed: Boolean) = unused()
|
||||||
override fun setCompletedInstance(taskId: Long, occurrenceStart: Instant, completed: Boolean) = unused()
|
override fun setCompletedInstance(taskId: Long, occurrenceStart: Instant, completed: Boolean) = unused()
|
||||||
override fun deleteTask(taskId: Long) = unused()
|
override fun deleteTask(taskId: Long) = unused()
|
||||||
override fun setCancelled(taskId: Long, cancelled: Boolean) = unused()
|
override fun setCancelled(taskId: Long, cancelled: Boolean) = unused()
|
||||||
override fun setCancelledInstance(taskId: Long, occurrenceStart: Instant, cancelled: Boolean) = unused()
|
override fun setCancelledInstance(taskId: Long, occurrenceStart: Instant, cancelled: Boolean) = unused()
|
||||||
override fun updateSeries(seriesId: Long, occurrenceStart: Instant, form: TaskForm) = unused()
|
override fun updateSeries(seriesId: Long, occurrenceStart: Instant, form: TaskForm, reminders: List<TaskReminder>?) =
|
||||||
override fun splitSeries(seriesId: Long, occurrenceStart: Instant, form: TaskForm): Long = unused()
|
unused()
|
||||||
|
override fun splitSeries(seriesId: Long, occurrenceStart: Instant, form: TaskForm, reminders: List<TaskReminder>?): Long =
|
||||||
|
unused()
|
||||||
override fun deleteOccurrence(seriesId: Long, occurrenceStart: Instant) = unused()
|
override fun deleteOccurrence(seriesId: Long, occurrenceStart: Instant) = unused()
|
||||||
override fun deleteFollowing(seriesId: Long, occurrenceStart: Instant) = unused()
|
override fun deleteFollowing(seriesId: Long, occurrenceStart: Instant) = unused()
|
||||||
override fun createLocalList(name: String, color: Int): Long = unused()
|
override fun createLocalList(name: String, color: Int): Long = unused()
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
+90
@@ -0,0 +1,90 @@
|
|||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,10 +13,13 @@ import dagger.hilt.components.SingletonComponent
|
|||||||
import dagger.multibindings.IntoSet
|
import dagger.multibindings.IntoSet
|
||||||
import de.jeanlucmakiola.agendula.data.sync.AccountCreator
|
import de.jeanlucmakiola.agendula.data.sync.AccountCreator
|
||||||
import de.jeanlucmakiola.agendula.data.sync.AccountRepository
|
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.CalDavGateway
|
||||||
import de.jeanlucmakiola.agendula.data.sync.LoginFlowRecord
|
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.OkHttpCalDavGateway
|
||||||
import de.jeanlucmakiola.agendula.data.sync.PendingLoginFlowStore
|
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.RemoteListRepository
|
||||||
import de.jeanlucmakiola.agendula.data.sync.RemoteLists
|
import de.jeanlucmakiola.agendula.data.sync.RemoteLists
|
||||||
import de.jeanlucmakiola.agendula.data.sync.SyncNoticeNotifier
|
import de.jeanlucmakiola.agendula.data.sync.SyncNoticeNotifier
|
||||||
@@ -79,7 +82,11 @@ abstract class SyncBindModule {
|
|||||||
|
|
||||||
@Binds
|
@Binds
|
||||||
@Singleton
|
@Singleton
|
||||||
abstract fun bindSyncRequests(impl: SyncTrigger): SyncRequests
|
abstract fun bindSyncRequests(impl: AccountSyncRequests): SyncRequests
|
||||||
|
|
||||||
|
@Binds
|
||||||
|
@Singleton
|
||||||
|
abstract fun bindManualSync(impl: PullSync): ManualSync
|
||||||
|
|
||||||
@Binds
|
@Binds
|
||||||
@IntoSet
|
@IntoSet
|
||||||
|
|||||||
@@ -3,10 +3,12 @@ package de.jeanlucmakiola.agendula.data.sync
|
|||||||
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
|
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
|
||||||
import de.jeanlucmakiola.agendula.data.sync.push.PushRegistrar
|
import de.jeanlucmakiola.agendula.data.sync.push.PushRegistrar
|
||||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
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.AccountEntity
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.room.TaskListEntity
|
import de.jeanlucmakiola.agendula.data.tasks.room.TaskListEntity
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase
|
import de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase
|
||||||
import de.jeanlucmakiola.caldav.CalDavDiscovery
|
import de.jeanlucmakiola.caldav.CalDavDiscovery
|
||||||
|
import de.jeanlucmakiola.caldav.ServerTrust
|
||||||
import de.jeanlucmakiola.caldav.TaskCollection
|
import de.jeanlucmakiola.caldav.TaskCollection
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
@@ -16,6 +18,7 @@ import kotlinx.coroutines.flow.first
|
|||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import okhttp3.HttpUrl
|
import okhttp3.HttpUrl
|
||||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||||
|
import java.io.IOException
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
@@ -35,7 +38,12 @@ interface AccountCreator {
|
|||||||
selected: Set<TaskCollection>,
|
selected: Set<TaskCollection>,
|
||||||
/** An existing account to sign in again, instead of creating one. */
|
/** An existing account to sign in again, instead of creating one. */
|
||||||
reauthenticating: Long? = null,
|
reauthenticating: Long? = null,
|
||||||
|
/** What the user agreed to trust on the way here; saved with the account. */
|
||||||
|
trust: ServerTrust = ServerTrust.DEFAULT,
|
||||||
): AccountRepository.Outcome
|
): AccountRepository.Outcome
|
||||||
|
|
||||||
|
/** What [accountId] was set up trusting, so signing in again starts from it. */
|
||||||
|
suspend fun trustFor(accountId: Long): ServerTrust
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -59,6 +67,7 @@ class AccountRepository @Inject constructor(
|
|||||||
private val quarantine: QuarantineStore,
|
private val quarantine: QuarantineStore,
|
||||||
private val notices: SyncNoticeStore,
|
private val notices: SyncNoticeStore,
|
||||||
private val collectionSupport: CollectionSupportStore,
|
private val collectionSupport: CollectionSupportStore,
|
||||||
|
private val serverTrust: ServerTrustStore,
|
||||||
private val gateway: CalDavGateway,
|
private val gateway: CalDavGateway,
|
||||||
private val availability: SyncAvailability,
|
private val availability: SyncAvailability,
|
||||||
private val settings: SettingsPrefs,
|
private val settings: SettingsPrefs,
|
||||||
@@ -97,6 +106,11 @@ class AccountRepository @Inject constructor(
|
|||||||
/** The accounts, observed, so a sync landing updates a screen that is open. */
|
/** The accounts, observed, so a sync landing updates a screen that is open. */
|
||||||
fun observeAll(): Flow<List<AccountEntity>> = database.accounts().observeAll()
|
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. */
|
/** Every account's synced lists. */
|
||||||
fun observeSyncedLists(): Flow<List<TaskListEntity>> = database.taskLists().observeSynced()
|
fun observeSyncedLists(): Flow<List<TaskListEntity>> = database.taskLists().observeSynced()
|
||||||
|
|
||||||
@@ -115,6 +129,7 @@ class AccountRepository @Inject constructor(
|
|||||||
found: CalDavDiscovery.Outcome.Found,
|
found: CalDavDiscovery.Outcome.Found,
|
||||||
selected: Set<TaskCollection>,
|
selected: Set<TaskCollection>,
|
||||||
reauthenticating: Long?,
|
reauthenticating: Long?,
|
||||||
|
trust: ServerTrust,
|
||||||
): Outcome = withContext(io) {
|
): Outcome = withContext(io) {
|
||||||
if (!availability.accountsUsable()) return@withContext Outcome.ExternalStorage
|
if (!availability.accountsUsable()) return@withContext Outcome.ExternalStorage
|
||||||
// "Sign in again" names its account, so a login name the server spells
|
// "Sign in again" names its account, so a login name the server spells
|
||||||
@@ -122,7 +137,7 @@ class AccountRepository @Inject constructor(
|
|||||||
// Only on the same server: anything else is a different account.
|
// Only on the same server: anything else is a different account.
|
||||||
val target = reauthenticating?.let { database.accounts().account(it) }
|
val target = reauthenticating?.let { database.accounts().account(it) }
|
||||||
if (target != null && sameServer(target, found)) {
|
if (target != null && sameServer(target, found)) {
|
||||||
return@withContext reauthenticate(target, target.displayName, username, appPassword, found, selected)
|
return@withContext reauthenticate(target, target.displayName, username, appPassword, found, selected, trust)
|
||||||
}
|
}
|
||||||
// Both stores, not just one. There is no unique index on
|
// Both stores, not just one. There is no unique index on
|
||||||
// accounts.display_name and nothing prunes Room when the system account
|
// accounts.display_name and nothing prunes Room when the system account
|
||||||
@@ -139,7 +154,7 @@ class AccountRepository @Inject constructor(
|
|||||||
// same name is still a duplicate, so this can never silently overwrite a
|
// same name is still a duplicate, so this can never silently overwrite a
|
||||||
// working credential.
|
// working credential.
|
||||||
if (existing != null && accountState.needsSignIn(existing.id)) {
|
if (existing != null && accountState.needsSignIn(existing.id)) {
|
||||||
return@withContext reauthenticate(existing, displayName, username, appPassword, found, selected)
|
return@withContext reauthenticate(existing, displayName, username, appPassword, found, selected, trust)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (existing != null) return@withContext Outcome.AlreadyExists
|
if (existing != null) return@withContext Outcome.AlreadyExists
|
||||||
@@ -180,6 +195,15 @@ class AccountRepository @Inject constructor(
|
|||||||
inserted += attach(id, selected)
|
inserted += attach(id, selected)
|
||||||
id
|
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)) {
|
if (!credentials.put(accountId, appPassword)) {
|
||||||
// Never leave a half-made account behind: without a credential it
|
// Never leave a half-made account behind: without a credential it
|
||||||
@@ -207,6 +231,8 @@ class AccountRepository @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun trustFor(accountId: Long): ServerTrust = serverTrust.get(accountId)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Points [selected] at [accountId], re-attaching what a previous removal
|
* Points [selected] at [accountId], re-attaching what a previous removal
|
||||||
* left behind rather than inserting a second copy.
|
* left behind rather than inserting a second copy.
|
||||||
@@ -298,6 +324,7 @@ class AccountRepository @Inject constructor(
|
|||||||
val outcome = gateway.discover(
|
val outcome = gateway.discover(
|
||||||
principal.toString(),
|
principal.toString(),
|
||||||
CalDavGateway.Credentials(username, password, principal),
|
CalDavGateway.Credentials(username, password, principal),
|
||||||
|
serverTrust.get(accountId),
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
is CalDavDiscovery.Outcome.Found -> Collections.Found(outcome.collections, attached)
|
is CalDavDiscovery.Outcome.Found -> Collections.Found(outcome.collections, attached)
|
||||||
@@ -306,6 +333,10 @@ class AccountRepository @Inject constructor(
|
|||||||
-> Collections.NeedsSignIn
|
-> Collections.NeedsSignIn
|
||||||
is CalDavDiscovery.Outcome.NotCalDav -> Collections.Failed(outcome.cause)
|
is CalDavDiscovery.Outcome.NotCalDav -> Collections.Failed(outcome.cause)
|
||||||
is CalDavDiscovery.Outcome.Failed -> 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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -345,6 +376,7 @@ class AccountRepository @Inject constructor(
|
|||||||
cadence.forget(dropped)
|
cadence.forget(dropped)
|
||||||
quarantine.forget(dropped)
|
quarantine.forget(dropped)
|
||||||
change.drop.forEach { notices.forgetList(accountId, it.name) }
|
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)
|
if (change.attach.isNotEmpty()) syncTrigger.enqueue(account.displayName, expedited = true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -386,6 +418,7 @@ class AccountRepository @Inject constructor(
|
|||||||
appPassword: String,
|
appPassword: String,
|
||||||
found: CalDavDiscovery.Outcome.Found,
|
found: CalDavDiscovery.Outcome.Found,
|
||||||
selected: Set<TaskCollection>,
|
selected: Set<TaskCollection>,
|
||||||
|
trust: ServerTrust,
|
||||||
): Outcome {
|
): Outcome {
|
||||||
val accountId = existing.id
|
val accountId = existing.id
|
||||||
if (!credentials.put(accountId, appPassword)) {
|
if (!credentials.put(accountId, appPassword)) {
|
||||||
@@ -394,6 +427,11 @@ class AccountRepository @Inject constructor(
|
|||||||
"the device keystore would not store the password",
|
"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) {
|
withContext(NonCancellable) {
|
||||||
database.runInTransaction {
|
database.runInTransaction {
|
||||||
database.accounts().update(
|
database.accounts().update(
|
||||||
@@ -437,11 +475,23 @@ class AccountRepository @Inject constructor(
|
|||||||
* and holds the user's tasks; `SET NULL` returns it to being device-only,
|
* and holds the user's tasks; `SET NULL` returns it to being device-only,
|
||||||
* which is exactly where it came from.
|
* which is exactly where it came from.
|
||||||
*/
|
*/
|
||||||
private fun rollback(accountId: Long, inserted: List<Long>) = database.runInTransaction {
|
private suspend fun rollback(accountId: Long, inserted: List<Long>) {
|
||||||
inserted.forEach { database.taskLists().delete(it) }
|
database.runInTransaction {
|
||||||
database.accounts().delete(accountId)
|
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 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.
|
* Puts every existing account back on the periodic schedule.
|
||||||
*
|
*
|
||||||
@@ -520,7 +570,11 @@ class AccountRepository @Inject constructor(
|
|||||||
// no Agendula account to delete — but "I want it gone from this
|
// 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
|
// device too" is a reasonable thing to want, and it is the only
|
||||||
// way to get the tasks off the device without also uninstalling.
|
// way to get the tasks off the device without also uninstalling.
|
||||||
if (deleteLocalData) database.taskLists().deleteForAccount(accountId)
|
if (deleteLocalData) {
|
||||||
|
val deleted = database.taskLists().idsForAccount(accountId)
|
||||||
|
database.taskLists().deleteForAccount(accountId)
|
||||||
|
runCatching { settings.forgetDeletedLists(deleted, StorageMode.OWN) }
|
||||||
|
}
|
||||||
|
|
||||||
accountState.setNeedsSignIn(accountId, false)
|
accountState.setNeedsSignIn(accountId, false)
|
||||||
// Keyed by account id, exactly like the flag above, and just as
|
// Keyed by account id, exactly like the flag above, and just as
|
||||||
@@ -530,6 +584,7 @@ class AccountRepository @Inject constructor(
|
|||||||
// The same reasoning, for what the server said it would let us
|
// The same reasoning, for what the server said it would let us
|
||||||
// create: keyed by an id nothing will ever mention again.
|
// create: keyed by an id nothing will ever mention again.
|
||||||
collectionSupport.forget(accountId)
|
collectionSupport.forget(accountId)
|
||||||
|
serverTrust.forget(accountId)
|
||||||
credentials.clear(accountId)
|
credentials.clear(accountId)
|
||||||
database.accounts().delete(accountId)
|
database.accounts().delete(accountId)
|
||||||
accounts.find(displayName)?.let { accounts.remove(it) }
|
accounts.find(displayName)?.let { accounts.remove(it) }
|
||||||
@@ -557,6 +612,7 @@ class AccountRepository @Inject constructor(
|
|||||||
try {
|
try {
|
||||||
gateway.revokeAppPassword(
|
gateway.revokeAppPassword(
|
||||||
CalDavGateway.Credentials(username, password, origin),
|
CalDavGateway.Credentials(username, password, origin),
|
||||||
|
serverTrust.get(accountId),
|
||||||
)
|
)
|
||||||
} catch (_: CancellationException) {
|
} catch (_: CancellationException) {
|
||||||
// Deliberately swallowed. If the caller went away mid-revoke we still
|
// Deliberately swallowed. If the caller went away mid-revoke we still
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,9 +4,10 @@ import de.jeanlucmakiola.agendula.data.di.IoDispatcher
|
|||||||
import de.jeanlucmakiola.caldav.AppPassword
|
import de.jeanlucmakiola.caldav.AppPassword
|
||||||
import de.jeanlucmakiola.caldav.CalDavDiscovery
|
import de.jeanlucmakiola.caldav.CalDavDiscovery
|
||||||
import de.jeanlucmakiola.caldav.CalDavHttp
|
import de.jeanlucmakiola.caldav.CalDavHttp
|
||||||
import de.jeanlucmakiola.caldav.DnsJavaResolver
|
|
||||||
import de.jeanlucmakiola.caldav.NextcloudLoginFlow
|
import de.jeanlucmakiola.caldav.NextcloudLoginFlow
|
||||||
|
import de.jeanlucmakiola.caldav.ServerTrust
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.job
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import okhttp3.HttpUrl
|
import okhttp3.HttpUrl
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
@@ -25,12 +26,22 @@ import javax.inject.Singleton
|
|||||||
interface CalDavGateway {
|
interface CalDavGateway {
|
||||||
|
|
||||||
/** Discovery against [target], optionally carrying credentials. */
|
/** Discovery against [target], optionally carrying credentials. */
|
||||||
suspend fun discover(target: String, credentials: Credentials? = null): CalDavDiscovery.Outcome
|
suspend fun discover(
|
||||||
|
target: String,
|
||||||
|
credentials: Credentials? = null,
|
||||||
|
trust: ServerTrust = ServerTrust.DEFAULT,
|
||||||
|
): CalDavDiscovery.Outcome
|
||||||
|
|
||||||
/** Starts Nextcloud Login Flow v2, or returns null if this is not a Nextcloud. */
|
/** Starts Nextcloud Login Flow v2, or returns null if this is not a Nextcloud. */
|
||||||
suspend fun startLoginFlow(server: HttpUrl): NextcloudLoginFlow.Flow?
|
suspend fun startLoginFlow(
|
||||||
|
server: HttpUrl,
|
||||||
|
trust: ServerTrust = ServerTrust.DEFAULT,
|
||||||
|
): NextcloudLoginFlow.Flow?
|
||||||
|
|
||||||
suspend fun pollLoginFlow(flow: NextcloudLoginFlow.Flow): NextcloudLoginFlow.PollResult
|
suspend fun pollLoginFlow(
|
||||||
|
flow: NextcloudLoginFlow.Flow,
|
||||||
|
trust: ServerTrust = ServerTrust.DEFAULT,
|
||||||
|
): NextcloudLoginFlow.PollResult
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Hands an app password back to the server, best effort.
|
* Hands an app password back to the server, best effort.
|
||||||
@@ -38,7 +49,10 @@ interface CalDavGateway {
|
|||||||
* Without it, uninstalling never revokes anything — the credential we minted
|
* Without it, uninstalling never revokes anything — the credential we minted
|
||||||
* outlives the app in the user's device list.
|
* outlives the app in the user's device list.
|
||||||
*/
|
*/
|
||||||
suspend fun revokeAppPassword(credentials: Credentials): Boolean
|
suspend fun revokeAppPassword(
|
||||||
|
credentials: Credentials,
|
||||||
|
trust: ServerTrust = ServerTrust.DEFAULT,
|
||||||
|
): Boolean
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The same, for a password the login flow just minted.
|
* The same, for a password the login flow just minted.
|
||||||
@@ -49,7 +63,10 @@ interface CalDavGateway {
|
|||||||
* principal, and a subpath install's `https://host/nextcloud/` would collapse
|
* principal, and a subpath install's `https://host/nextcloud/` would collapse
|
||||||
* to `https://host/` — a DELETE that 404s on every one of them.
|
* to `https://host/` — a DELETE that 404s on every one of them.
|
||||||
*/
|
*/
|
||||||
suspend fun revokeIssuedAppPassword(credentials: Credentials): Boolean
|
suspend fun revokeIssuedAppPassword(
|
||||||
|
credentials: Credentials,
|
||||||
|
trust: ServerTrust = ServerTrust.DEFAULT,
|
||||||
|
): Boolean
|
||||||
|
|
||||||
/** Credentials, and the origin whose registrable domain they are scoped to. */
|
/** Credentials, and the origin whose registrable domain they are scoped to. */
|
||||||
data class Credentials(val username: String, val password: String, val origin: HttpUrl)
|
data class Credentials(val username: String, val password: String, val origin: HttpUrl)
|
||||||
@@ -71,16 +88,19 @@ class OkHttpCalDavGateway @Inject constructor(
|
|||||||
override suspend fun discover(
|
override suspend fun discover(
|
||||||
target: String,
|
target: String,
|
||||||
credentials: CalDavGateway.Credentials?,
|
credentials: CalDavGateway.Credentials?,
|
||||||
|
trust: ServerTrust,
|
||||||
): CalDavDiscovery.Outcome = withContext(io) {
|
): CalDavDiscovery.Outcome = withContext(io) {
|
||||||
val client = credentials?.let {
|
val client = credentials?.let {
|
||||||
CalDavHttp.authenticated(userAgent, it.username, it.password, it.origin)
|
CalDavHttp.authenticated(userAgent, it.username, it.password, it.origin, trust)
|
||||||
} ?: CalDavHttp.anonymous(userAgent)
|
} ?: CalDavHttp.anonymous(userAgent, trust)
|
||||||
CalDavDiscovery(client, DnsJavaResolver()).discover(target)
|
val job = coroutineContext.job
|
||||||
|
CalDavDiscovery(client, SystemDnsResolver { !job.isActive }, allowCleartext = trust.allowCleartext)
|
||||||
|
.discover(target)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun startLoginFlow(server: HttpUrl): NextcloudLoginFlow.Flow? =
|
override suspend fun startLoginFlow(server: HttpUrl, trust: ServerTrust): NextcloudLoginFlow.Flow? =
|
||||||
withContext(io) {
|
withContext(io) {
|
||||||
NextcloudLoginFlow(CalDavHttp.anonymous(userAgent), userAgent)
|
NextcloudLoginFlow(CalDavHttp.anonymous(userAgent, trust), userAgent)
|
||||||
.start(server, now())
|
.start(server, now())
|
||||||
.getOrNull()
|
.getOrNull()
|
||||||
}
|
}
|
||||||
@@ -92,9 +112,12 @@ class OkHttpCalDavGateway @Inject constructor(
|
|||||||
* the shared client's ceiling is sized for a multiget, not for a two-second
|
* 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.
|
* poll loop against a server that answered a moment ago.
|
||||||
*/
|
*/
|
||||||
override suspend fun pollLoginFlow(flow: NextcloudLoginFlow.Flow): NextcloudLoginFlow.PollResult =
|
override suspend fun pollLoginFlow(
|
||||||
|
flow: NextcloudLoginFlow.Flow,
|
||||||
|
trust: ServerTrust,
|
||||||
|
): NextcloudLoginFlow.PollResult =
|
||||||
withContext(io) {
|
withContext(io) {
|
||||||
val client = CalDavHttp.anonymous(userAgent).newBuilder()
|
val client = CalDavHttp.anonymous(userAgent, trust).newBuilder()
|
||||||
.callTimeout(POLL_TIMEOUT_SECONDS, TimeUnit.SECONDS)
|
.callTimeout(POLL_TIMEOUT_SECONDS, TimeUnit.SECONDS)
|
||||||
.build()
|
.build()
|
||||||
NextcloudLoginFlow(client, userAgent).poll(flow, now())
|
NextcloudLoginFlow(client, userAgent).poll(flow, now())
|
||||||
@@ -102,18 +125,20 @@ class OkHttpCalDavGateway @Inject constructor(
|
|||||||
|
|
||||||
override suspend fun revokeAppPassword(
|
override suspend fun revokeAppPassword(
|
||||||
credentials: CalDavGateway.Credentials,
|
credentials: CalDavGateway.Credentials,
|
||||||
|
trust: ServerTrust,
|
||||||
): Boolean = withContext(io) {
|
): Boolean = withContext(io) {
|
||||||
val client = CalDavHttp.authenticated(
|
val client = CalDavHttp.authenticated(
|
||||||
userAgent, credentials.username, credentials.password, credentials.origin,
|
userAgent, credentials.username, credentials.password, credentials.origin, trust,
|
||||||
)
|
)
|
||||||
AppPassword.revoke(client, credentials.origin)
|
AppPassword.revoke(client, credentials.origin)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun revokeIssuedAppPassword(
|
override suspend fun revokeIssuedAppPassword(
|
||||||
credentials: CalDavGateway.Credentials,
|
credentials: CalDavGateway.Credentials,
|
||||||
|
trust: ServerTrust,
|
||||||
): Boolean = withContext(io) {
|
): Boolean = withContext(io) {
|
||||||
val client = CalDavHttp.authenticated(
|
val client = CalDavHttp.authenticated(
|
||||||
userAgent, credentials.username, credentials.password, credentials.origin,
|
userAgent, credentials.username, credentials.password, credentials.origin, trust,
|
||||||
)
|
)
|
||||||
AppPassword.revokeAt(client, credentials.origin)
|
AppPassword.revokeAt(client, credentials.origin)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
package de.jeanlucmakiola.agendula.data.sync
|
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.CalendarResource
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.ical.ResourceValidator
|
import de.jeanlucmakiola.agendula.data.tasks.ical.ResourceValidator
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.ical.VTodoMapper
|
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.TaskEntity
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.room.TaskListEntity
|
import de.jeanlucmakiola.agendula.data.tasks.room.TaskListEntity
|
||||||
import at.bitfire.dav4jvm.exception.UnauthorizedException
|
import at.bitfire.dav4jvm.exception.UnauthorizedException
|
||||||
@@ -415,15 +417,22 @@ class CollectionSyncer(
|
|||||||
return@forEach
|
return@forEach
|
||||||
}
|
}
|
||||||
|
|
||||||
val body = serialize(local) ?: return@forEach
|
if (href == null) {
|
||||||
if (href == null) createResource(local, body) else updateResource(local, href, body)
|
val body = serialize(local) ?: return@forEach
|
||||||
|
createResource(local, body)
|
||||||
|
} else {
|
||||||
|
val revised = local.revised()
|
||||||
|
val body = serialize(revised) ?: return@forEach
|
||||||
|
updateResource(revised, href, body)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Null when the resource was rejected before it left the device. */
|
/** Null when the resource was rejected before it left the device. */
|
||||||
private fun serialize(local: LocalResource): String? {
|
private fun serialize(local: LocalResource): String? {
|
||||||
|
val alarms = store.alarmsFor(local.live.map { it.id })
|
||||||
val todos = local.live.map { row ->
|
val todos = local.live.map { row ->
|
||||||
VTodoMapper.write(row, parentUidOf(row), now())
|
VTodoMapper.write(row, parentUidOf(row), now(), alarms[row.id].orEmpty())
|
||||||
}
|
}
|
||||||
val calendar = CalendarResource.build(todos)
|
val calendar = CalendarResource.build(todos)
|
||||||
|
|
||||||
@@ -490,7 +499,9 @@ class CollectionSyncer(
|
|||||||
val existing = fetched.resources.firstOrNull()
|
val existing = fetched.resources.firstOrNull()
|
||||||
val sameTask = existing != null && uidOf(existing.iCalendar) == local.uid
|
val sameTask = existing != null && uidOf(existing.iCalendar) == local.uid
|
||||||
if (sameTask) {
|
if (sameTask) {
|
||||||
updateResource(local, outcome.href.toString(), body)
|
// An update now, so SEQUENCE goes up as on any other (#137).
|
||||||
|
val revised = local.revised()
|
||||||
|
updateResource(revised, outcome.href.toString(), serialize(revised) ?: return)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
name = ResourceNames.random()
|
name = ResourceNames.random()
|
||||||
@@ -606,7 +617,7 @@ class CollectionSyncer(
|
|||||||
// via `master_id`.
|
// via `master_id`.
|
||||||
val (buried, kept) = local.rows.partition { it.isDeleted && it.recurrenceId != null }
|
val (buried, kept) = local.rows.partition { it.isDeleted && it.recurrenceId != null }
|
||||||
if (buried.isNotEmpty()) store.deleteAll(buried.map { it.id })
|
if (buried.isNotEmpty()) store.deleteAll(buried.map { it.id })
|
||||||
store.markSynced(kept.map { it.id }, key, eTag)
|
store.markSynced(kept, key, eTag)
|
||||||
// Both, because a resource that failed as a create was counted under
|
// 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
|
// its UID and is now counted under its href. Clearing one would leak
|
||||||
// the other into the store forever.
|
// the other into the store forever.
|
||||||
@@ -778,14 +789,17 @@ class CollectionSyncer(
|
|||||||
val losing = existing.values.firstOrNull { it.isDirty }
|
val losing = existing.values.firstOrNull { it.isDirty }
|
||||||
|
|
||||||
val master = mapped.firstOrNull { it.entity.recurrenceId == null } ?: mapped.first()
|
val master = mapped.firstOrNull { it.entity.recurrenceId == null } ?: mapped.first()
|
||||||
val masterRow = upsert(master.entity, existing[master.entity.recurrenceId], null, href, eTag)
|
val masterRow = upsert(master, existing[master.entity.recurrenceId], null, href, eTag)
|
||||||
val masterId = masterRow.id
|
val masterId = masterRow.id
|
||||||
parents[uid] = master.parentUid
|
parents[uid] = master.parentUid
|
||||||
|
|
||||||
val written = mutableListOf(masterRow)
|
val written = mutableListOf(masterRow)
|
||||||
mapped.filter { it !== master }.forEach { override ->
|
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(
|
written += upsert(
|
||||||
override.entity, existing[override.entity.recurrenceId], masterId, href, eTag,
|
override, existing[override.entity.recurrenceId], masterId, href, eTag,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
val kept = written.map { it.recurrenceId }.toSet()
|
val kept = written.map { it.recurrenceId }.toSet()
|
||||||
@@ -819,6 +833,7 @@ class CollectionSyncer(
|
|||||||
}
|
}
|
||||||
|
|
||||||
pendingDiscard.remove(href)?.let { cause ->
|
pendingDiscard.remove(href)?.let { cause ->
|
||||||
|
store.dropAdvances(masterId)
|
||||||
report = report.copy(
|
report = report.copy(
|
||||||
discardedEdits = report.discardedEdits +
|
discardedEdits = report.discardedEdits +
|
||||||
DiscardedEdit(uid, losing?.title, cause),
|
DiscardedEdit(uid, losing?.title, cause),
|
||||||
@@ -832,12 +847,13 @@ class CollectionSyncer(
|
|||||||
|
|
||||||
/** @return the row as it now stands, so the caller can index it. */
|
/** @return the row as it now stands, so the caller can index it. */
|
||||||
private fun upsert(
|
private fun upsert(
|
||||||
incoming: TaskEntity,
|
mapped: VTodoMapper.Mapped,
|
||||||
existing: TaskEntity?,
|
existing: TaskEntity?,
|
||||||
masterId: Long?,
|
masterId: Long?,
|
||||||
href: String,
|
href: String,
|
||||||
eTag: String?,
|
eTag: String?,
|
||||||
): TaskEntity {
|
): TaskEntity {
|
||||||
|
val incoming = mapped.entity
|
||||||
// Local-only columns the server has no opinion about. Taking the
|
// Local-only columns the server has no opinion about. Taking the
|
||||||
// mapper's defaults here would silently reset the user's ordering and
|
// mapper's defaults here would silently reset the user's ordering and
|
||||||
// per-task colour on every download.
|
// per-task colour on every download.
|
||||||
@@ -854,12 +870,42 @@ class CollectionSyncer(
|
|||||||
// set uploads what was just downloaded.
|
// set uploads what was just downloaded.
|
||||||
isDirty = false,
|
isDirty = false,
|
||||||
isDeleted = false,
|
isDeleted = false,
|
||||||
|
// The store's to change, from what the alarms do.
|
||||||
|
remindersOff = existing?.remindersOff ?: false,
|
||||||
)
|
)
|
||||||
return if (existing == null) {
|
// The server's alarms replace ours, as every other field does: a
|
||||||
row.copy(id = store.insert(row))
|
// dirty row is never downloaded except to discard its edit.
|
||||||
} else {
|
val alarms = existing?.let { keepLocalPrecision(mapped.alarms, it, row) } ?: mapped.alarms
|
||||||
store.update(row)
|
return row.copy(id = store.upsertWithAlarms(row, alarms))
|
||||||
row
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [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
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1043,6 +1089,16 @@ class CollectionSyncer(
|
|||||||
|
|
||||||
/** What gets serialised: a deleted override is simply absent. */
|
/** What gets serialised: a deleted override is simply absent. */
|
||||||
val live: List<TaskEntity> = rows.filterNot { it.isDeleted }
|
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 {
|
private companion object {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import androidx.datastore.preferences.core.longPreferencesKey
|
|||||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||||
import de.jeanlucmakiola.agendula.data.di.SyncStateDataStore
|
import de.jeanlucmakiola.agendula.data.di.SyncStateDataStore
|
||||||
import de.jeanlucmakiola.caldav.NextcloudLoginFlow
|
import de.jeanlucmakiola.caldav.NextcloudLoginFlow
|
||||||
|
import de.jeanlucmakiola.caldav.ServerTrust
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.sync.Mutex
|
import kotlinx.coroutines.sync.Mutex
|
||||||
import kotlinx.coroutines.sync.withLock
|
import kotlinx.coroutines.sync.withLock
|
||||||
@@ -23,8 +24,8 @@ import javax.inject.Singleton
|
|||||||
*/
|
*/
|
||||||
interface LoginFlowRecord {
|
interface LoginFlowRecord {
|
||||||
|
|
||||||
/** Called **before** the browser is handed the URL. */
|
/** Called **before** the browser is handed the URL; [trust] is what reaching it took. */
|
||||||
suspend fun remember(flow: NextcloudLoginFlow.Flow)
|
suspend fun remember(flow: NextcloudLoginFlow.Flow, trust: ServerTrust = ServerTrust.DEFAULT)
|
||||||
|
|
||||||
/** The flow is over, however it ended. */
|
/** The flow is over, however it ended. */
|
||||||
suspend fun forget()
|
suspend fun forget()
|
||||||
@@ -58,12 +59,13 @@ class PendingLoginFlowStore @Inject constructor(
|
|||||||
private var reclaimed = false
|
private var reclaimed = false
|
||||||
|
|
||||||
/** Records [flow] so a process that dies mid-approval can still finish with it. */
|
/** Records [flow] so a process that dies mid-approval can still finish with it. */
|
||||||
override suspend fun remember(flow: NextcloudLoginFlow.Flow) {
|
override suspend fun remember(flow: NextcloudLoginFlow.Flow, trust: ServerTrust) {
|
||||||
dataStore.edit { prefs ->
|
dataStore.edit { prefs ->
|
||||||
prefs[LOGIN_URL] = flow.loginUrl.toString()
|
prefs[LOGIN_URL] = flow.loginUrl.toString()
|
||||||
prefs[POLL_ENDPOINT] = flow.pollEndpoint.toString()
|
prefs[POLL_ENDPOINT] = flow.pollEndpoint.toString()
|
||||||
prefs[POLL_TOKEN] = flow.pollToken
|
prefs[POLL_TOKEN] = flow.pollToken
|
||||||
prefs[DEADLINE] = flow.deadlineEpochSeconds
|
prefs[DEADLINE] = flow.deadlineEpochSeconds
|
||||||
|
TRUST.write(prefs, trust)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,6 +76,7 @@ class PendingLoginFlowStore @Inject constructor(
|
|||||||
prefs.remove(POLL_ENDPOINT)
|
prefs.remove(POLL_ENDPOINT)
|
||||||
prefs.remove(POLL_TOKEN)
|
prefs.remove(POLL_TOKEN)
|
||||||
prefs.remove(DEADLINE)
|
prefs.remove(DEADLINE)
|
||||||
|
TRUST.remove(prefs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,7 +101,8 @@ class PendingLoginFlowStore @Inject constructor(
|
|||||||
reclaimed = true
|
reclaimed = true
|
||||||
}
|
}
|
||||||
val flow = pending() ?: return
|
val flow = pending() ?: return
|
||||||
when (val result = gateway.pollLoginFlow(flow)) {
|
val trust = trust()
|
||||||
|
when (val result = gateway.pollLoginFlow(flow, trust)) {
|
||||||
is NextcloudLoginFlow.PollResult.Approved -> {
|
is NextcloudLoginFlow.PollResult.Approved -> {
|
||||||
// Cleared first: a revocation that fails must not leave a token
|
// Cleared first: a revocation that fails must not leave a token
|
||||||
// that would be polled again, and the 200 is already spent.
|
// that would be polled again, and the 200 is already spent.
|
||||||
@@ -109,6 +113,7 @@ class PendingLoginFlowStore @Inject constructor(
|
|||||||
password = result.credentials.appPassword,
|
password = result.credentials.appPassword,
|
||||||
origin = result.credentials.server,
|
origin = result.credentials.server,
|
||||||
),
|
),
|
||||||
|
trust,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -136,10 +141,13 @@ class PendingLoginFlowStore @Inject constructor(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private suspend fun trust(): ServerTrust = TRUST.read(dataStore.data.first())
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
val LOGIN_URL = stringPreferencesKey("login_flow_url")
|
val LOGIN_URL = stringPreferencesKey("login_flow_url")
|
||||||
val POLL_ENDPOINT = stringPreferencesKey("login_flow_poll_endpoint")
|
val POLL_ENDPOINT = stringPreferencesKey("login_flow_poll_endpoint")
|
||||||
val POLL_TOKEN = stringPreferencesKey("login_flow_poll_token")
|
val POLL_TOKEN = stringPreferencesKey("login_flow_poll_token")
|
||||||
val DEADLINE = longPreferencesKey("login_flow_deadline")
|
val DEADLINE = longPreferencesKey("login_flow_deadline")
|
||||||
|
val TRUST = ServerTrustKeys("login_flow_trusted_certificates", "login_flow_cleartext")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
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,5 +1,6 @@
|
|||||||
package de.jeanlucmakiola.agendula.data.sync
|
package de.jeanlucmakiola.agendula.data.sync
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.agendula.data.CollectionHref
|
||||||
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
|
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
|
||||||
import de.jeanlucmakiola.agendula.data.sync.RemoteLists.Outcome
|
import de.jeanlucmakiola.agendula.data.sync.RemoteLists.Outcome
|
||||||
import de.jeanlucmakiola.agendula.data.sync.push.PushStore
|
import de.jeanlucmakiola.agendula.data.sync.push.PushStore
|
||||||
@@ -13,7 +14,9 @@ import de.jeanlucmakiola.caldav.CollectionAdmin
|
|||||||
import de.jeanlucmakiola.caldav.CollectionOutcome
|
import de.jeanlucmakiola.caldav.CollectionOutcome
|
||||||
import de.jeanlucmakiola.caldav.CollectionSupport
|
import de.jeanlucmakiola.caldav.CollectionSupport
|
||||||
import de.jeanlucmakiola.caldav.DavCollectionAdmin
|
import de.jeanlucmakiola.caldav.DavCollectionAdmin
|
||||||
|
import de.jeanlucmakiola.caldav.HomeSets
|
||||||
import de.jeanlucmakiola.caldav.ResourceNames
|
import de.jeanlucmakiola.caldav.ResourceNames
|
||||||
|
import de.jeanlucmakiola.caldav.ServerTrust
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.NonCancellable
|
import kotlinx.coroutines.NonCancellable
|
||||||
import kotlinx.coroutines.async
|
import kotlinx.coroutines.async
|
||||||
@@ -53,6 +56,7 @@ class RemoteListRepository @Inject constructor(
|
|||||||
private val accountState: AccountStateStore,
|
private val accountState: AccountStateStore,
|
||||||
private val resolver: ProviderResolver,
|
private val resolver: ProviderResolver,
|
||||||
private val push: PushStore,
|
private val push: PushStore,
|
||||||
|
private val trust: ServerTrustStore,
|
||||||
@IoDispatcher private val io: CoroutineDispatcher,
|
@IoDispatcher private val io: CoroutineDispatcher,
|
||||||
) : RemoteLists {
|
) : RemoteLists {
|
||||||
|
|
||||||
@@ -203,7 +207,18 @@ class RemoteListRepository @Inject constructor(
|
|||||||
val url = list.href?.toHttpUrlOrNull() ?: return@withContext Outcome.NoAccount
|
val url = list.href?.toHttpUrlOrNull() ?: return@withContext Outcome.NoAccount
|
||||||
val account = list.accountId?.let { database.accounts().account(it) }
|
val account = list.accountId?.let { database.accounts().account(it) }
|
||||||
?: return@withContext Outcome.NoAccount
|
?: return@withContext Outcome.NoAccount
|
||||||
|
if (CollectionHref.same(list.href, account.homeSetUrl)) return@withContext Outcome.AccountHome
|
||||||
val admin = adminFor(account) ?: return@withContext Outcome.NoAccount
|
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)) {
|
when (val outcome = admin.delete(url)) {
|
||||||
CollectionOutcome.Updated -> {
|
CollectionOutcome.Updated -> {
|
||||||
@@ -252,11 +267,11 @@ class RemoteListRepository @Inject constructor(
|
|||||||
val origin = account.principalUrl?.toHttpUrlOrNull() ?: return null
|
val origin = account.principalUrl?.toHttpUrlOrNull() ?: return null
|
||||||
val password = (credentials.get(account.id) as? CredentialStore.Secret.Present)?.value
|
val password = (credentials.get(account.id) as? CredentialStore.Secret.Present)?.value
|
||||||
?: return null
|
?: return null
|
||||||
return DavCollectionAdmin(client(username, password, origin))
|
return DavCollectionAdmin(client(username, password, origin, trust.get(account.id)))
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun client(username: String, password: String, origin: HttpUrl): OkHttpClient =
|
private fun client(username: String, password: String, origin: HttpUrl, trust: ServerTrust): OkHttpClient =
|
||||||
CalDavHttp.authenticated(USER_AGENT, username, password, origin)
|
CalDavHttp.authenticated(USER_AGENT, username, password, origin, trust)
|
||||||
|
|
||||||
private suspend fun forgetPerListState(listId: Long) {
|
private suspend fun forgetPerListState(listId: Long) {
|
||||||
val ids = setOf(listId)
|
val ids = setOf(listId)
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
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")
|
||||||
|
}
|
||||||
@@ -33,6 +33,7 @@ class SyncEngine @Inject constructor(
|
|||||||
private val notices: SyncNoticeStore,
|
private val notices: SyncNoticeStore,
|
||||||
private val availability: SyncAvailability,
|
private val availability: SyncAvailability,
|
||||||
private val push: PushRegistrar,
|
private val push: PushRegistrar,
|
||||||
|
private val trust: ServerTrustStore,
|
||||||
@IoDispatcher private val io: CoroutineDispatcher,
|
@IoDispatcher private val io: CoroutineDispatcher,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
@@ -90,7 +91,7 @@ class SyncEngine @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val client = CalDavHttp.authenticated(USER_AGENT, username, password, origin)
|
val client = CalDavHttp.authenticated(USER_AGENT, username, password, origin, trust.get(account.id))
|
||||||
val subscriptions = push.subscriptionsByHref(account.id)
|
val subscriptions = push.subscriptionsByHref(account.id)
|
||||||
val reports = syncCollections(account) { url ->
|
val reports = syncCollections(account) { url ->
|
||||||
CalendarCollection(client, url, pushRegistration = subscriptions[url.toString()])
|
CalendarCollection(client, url, pushRegistration = subscriptions[url.toString()])
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ data class SyncFailure(val kind: Kind, val httpCode: Int? = null) {
|
|||||||
private val TLS = listOf(
|
private val TLS = listOf(
|
||||||
"SSLHandshakeException",
|
"SSLHandshakeException",
|
||||||
"SSLPeerUnverifiedException",
|
"SSLPeerUnverifiedException",
|
||||||
|
"UntrustedHostException",
|
||||||
"CertPathValidatorException",
|
"CertPathValidatorException",
|
||||||
"CertificateException",
|
"CertificateException",
|
||||||
"SSLException",
|
"SSLException",
|
||||||
|
|||||||
@@ -1,20 +1,18 @@
|
|||||||
package de.jeanlucmakiola.agendula.data.sync
|
package de.jeanlucmakiola.agendula.data.sync
|
||||||
|
|
||||||
import android.Manifest
|
|
||||||
import android.annotation.SuppressLint
|
import android.annotation.SuppressLint
|
||||||
import android.app.NotificationChannel
|
import android.app.NotificationChannel
|
||||||
import android.app.NotificationManager
|
import android.app.NotificationManager
|
||||||
import android.app.PendingIntent
|
import android.app.PendingIntent
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.content.pm.PackageManager
|
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import androidx.core.app.NotificationCompat
|
import androidx.core.app.NotificationCompat
|
||||||
import androidx.core.app.NotificationManagerCompat
|
import androidx.core.app.NotificationManagerCompat
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
import de.jeanlucmakiola.agendula.MainActivity
|
import de.jeanlucmakiola.agendula.MainActivity
|
||||||
import de.jeanlucmakiola.agendula.data.di.ChannelRefresher
|
import de.jeanlucmakiola.agendula.data.di.ChannelRefresher
|
||||||
|
import de.jeanlucmakiola.agendula.data.reminders.canPostNotifications
|
||||||
import de.jeanlucmakiola.agendula.R
|
import de.jeanlucmakiola.agendula.R
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
@@ -37,10 +35,7 @@ class SyncNoticeNotifier @Inject constructor(
|
|||||||
) : ChannelRefresher {
|
) : ChannelRefresher {
|
||||||
|
|
||||||
fun canPost(): Boolean {
|
fun canPost(): Boolean {
|
||||||
val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
|
return context.canPostNotifications()
|
||||||
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().
|
// canPost() checks POST_NOTIFICATIONS before we ever call notify().
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
package de.jeanlucmakiola.agendula.data.sync
|
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.TaskEntity
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.room.TasksDatabase
|
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
|
import javax.inject.Inject
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -11,26 +15,51 @@ import javax.inject.Inject
|
|||||||
* discovery: the reconciliation above this interface is where local edits are
|
* discovery: the reconciliation above this interface is where local edits are
|
||||||
* discarded, tombstones swept and conflicts resolved, and every one of those is
|
* 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
|
* a decision that should be provable without a device. Room's test double is
|
||||||
* Robolectric plus an in-memory database; this is eight methods.
|
* Robolectric plus an in-memory database; this is a dozen methods.
|
||||||
*/
|
*/
|
||||||
interface SyncStore {
|
interface SyncStore {
|
||||||
|
|
||||||
/** Every row in a list, **tombstones included**. */
|
/** Every row in a list, **tombstones included**. */
|
||||||
fun rowsIn(listId: Long): List<TaskEntity>
|
fun rowsIn(listId: Long): List<TaskEntity>
|
||||||
|
|
||||||
fun insert(row: TaskEntity): Long
|
|
||||||
|
|
||||||
fun update(row: 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>)
|
fun deleteAll(taskIds: List<Long>)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Records href and ETag on a resource's rows, clearing `is_dirty`.
|
* 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,
|
* The caller excludes any row it left out of the body — that row is deleted,
|
||||||
* not marked synced.
|
* not marked synced.
|
||||||
*/
|
*/
|
||||||
fun markSynced(taskIds: List<Long>, href: String?, eTag: String?)
|
fun markSynced(rows: List<TaskEntity>, href: String?, eTag: String?)
|
||||||
|
|
||||||
fun setParent(taskId: Long, parentId: Long?)
|
fun setParent(taskId: Long, parentId: Long?)
|
||||||
|
|
||||||
@@ -56,18 +85,67 @@ class RoomSyncStore @Inject constructor(
|
|||||||
|
|
||||||
override fun rowsIn(listId: Long) = database.tasks().allIn(listId)
|
override fun rowsIn(listId: Long) = database.tasks().allIn(listId)
|
||||||
|
|
||||||
override fun insert(row: TaskEntity) = database.tasks().insert(row)
|
|
||||||
|
|
||||||
override fun update(row: TaskEntity) {
|
override fun update(row: TaskEntity) {
|
||||||
database.tasks().update(row)
|
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>) {
|
override fun deleteAll(taskIds: List<Long>) {
|
||||||
if (taskIds.isNotEmpty()) database.tasks().deleteAll(taskIds)
|
if (taskIds.isNotEmpty()) database.tasks().deleteAll(taskIds)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun markSynced(taskIds: List<Long>, href: String?, eTag: String?) {
|
override fun dropAdvances(masterId: Long) = database.runInTransaction {
|
||||||
if (taskIds.isNotEmpty()) database.tasks().markSynced(taskIds, href, eTag)
|
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?) {
|
override fun setParent(taskId: Long, parentId: Long?) {
|
||||||
|
|||||||
@@ -35,11 +35,7 @@ import kotlin.time.Duration.Companion.seconds
|
|||||||
@Singleton
|
@Singleton
|
||||||
class SyncTrigger @Inject constructor(
|
class SyncTrigger @Inject constructor(
|
||||||
@ApplicationContext private val context: Context,
|
@ApplicationContext private val context: Context,
|
||||||
) : SyncRequests {
|
) {
|
||||||
|
|
||||||
override fun syncNow(accountName: String) {
|
|
||||||
enqueue(accountName)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Starts a sync now.
|
* Starts a sync now.
|
||||||
|
|||||||
@@ -56,8 +56,8 @@ class SyncWorker @AssistedInject constructor(
|
|||||||
// log line is the same as saying nothing. Only what is new: the
|
// log line is the same as saying nothing. Only what is new: the
|
||||||
// store has already dropped whatever the user has been told.
|
// store has already dropped whatever the user has been told.
|
||||||
noticeNotifier.post(accountName, outcome.notices)
|
noticeNotifier.post(accountName, outcome.notices)
|
||||||
// Nothing else re-arms reminders for what a sync pulled in: in our
|
// Here rather than left to ReminderRefresher's debounce: once
|
||||||
// own store no provider broadcast fires.
|
// the worker returns, nothing keeps the process alive for it.
|
||||||
if (outcome.reports.any { it.hadWork || it.discardedEdits.isNotEmpty() }) {
|
if (outcome.reports.any { it.hadWork || it.discardedEdits.isNotEmpty() }) {
|
||||||
runCatching { reminderScheduler.sync() }
|
runCatching { reminderScheduler.sync() }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
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>()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ import dagger.hilt.android.qualifiers.ApplicationContext
|
|||||||
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
|
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
|
||||||
import de.jeanlucmakiola.agendula.data.sync.AccountStateStore
|
import de.jeanlucmakiola.agendula.data.sync.AccountStateStore
|
||||||
import de.jeanlucmakiola.agendula.data.sync.CredentialStore
|
import de.jeanlucmakiola.agendula.data.sync.CredentialStore
|
||||||
|
import de.jeanlucmakiola.agendula.data.sync.ServerTrustStore
|
||||||
import de.jeanlucmakiola.agendula.data.sync.SyncAvailability
|
import de.jeanlucmakiola.agendula.data.sync.SyncAvailability
|
||||||
import de.jeanlucmakiola.agendula.data.sync.SyncReport
|
import de.jeanlucmakiola.agendula.data.sync.SyncReport
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.room.AccountEntity
|
import de.jeanlucmakiola.agendula.data.tasks.room.AccountEntity
|
||||||
@@ -48,6 +49,7 @@ class PushRegistrar @Inject constructor(
|
|||||||
private val credentials: CredentialStore,
|
private val credentials: CredentialStore,
|
||||||
private val accountState: AccountStateStore,
|
private val accountState: AccountStateStore,
|
||||||
private val availability: SyncAvailability,
|
private val availability: SyncAvailability,
|
||||||
|
private val trust: ServerTrustStore,
|
||||||
@IoDispatcher private val io: CoroutineDispatcher,
|
@IoDispatcher private val io: CoroutineDispatcher,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
@@ -231,7 +233,7 @@ class PushRegistrar @Inject constructor(
|
|||||||
val username = account.username ?: return null
|
val username = account.username ?: return null
|
||||||
val origin = account.principalUrl?.toHttpUrlOrNull() ?: return null
|
val origin = account.principalUrl?.toHttpUrlOrNull() ?: return null
|
||||||
val password = (credentials.get(account.id) as? CredentialStore.Secret.Present)?.value ?: return null
|
val password = (credentials.get(account.id) as? CredentialStore.Secret.Present)?.value ?: return null
|
||||||
return CalDavHttp.authenticated(USER_AGENT, username, password, origin)
|
return CalDavHttp.authenticated(USER_AGENT, username, password, origin, trust.get(account.id))
|
||||||
.newBuilder()
|
.newBuilder()
|
||||||
.callTimeout(CALL_TIMEOUT_SECONDS, TimeUnit.SECONDS)
|
.callTimeout(CALL_TIMEOUT_SECONDS, TimeUnit.SECONDS)
|
||||||
.build()
|
.build()
|
||||||
|
|||||||
@@ -15,9 +15,12 @@ import androidx.compose.material.icons.rounded.Check
|
|||||||
import androidx.compose.material.icons.rounded.Bolt
|
import androidx.compose.material.icons.rounded.Bolt
|
||||||
import androidx.compose.material.icons.rounded.CloudSync
|
import androidx.compose.material.icons.rounded.CloudSync
|
||||||
import androidx.compose.material.icons.rounded.DeleteOutline
|
import androidx.compose.material.icons.rounded.DeleteOutline
|
||||||
|
import androidx.compose.material.icons.rounded.Edit
|
||||||
|
import androidx.compose.material.icons.rounded.GppMaybe
|
||||||
import androidx.compose.material.icons.rounded.History
|
import androidx.compose.material.icons.rounded.History
|
||||||
import androidx.compose.material.icons.rounded.HistoryToggleOff
|
import androidx.compose.material.icons.rounded.HistoryToggleOff
|
||||||
import androidx.compose.material.icons.rounded.Inventory2
|
import androidx.compose.material.icons.rounded.Inventory2
|
||||||
|
import androidx.compose.material.icons.rounded.LockOpen
|
||||||
import androidx.compose.material.icons.rounded.Refresh
|
import androidx.compose.material.icons.rounded.Refresh
|
||||||
import androidx.compose.material.icons.rounded.SyncProblem
|
import androidx.compose.material.icons.rounded.SyncProblem
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
@@ -26,6 +29,7 @@ import androidx.compose.material3.Icon
|
|||||||
import androidx.compose.material3.IconButton
|
import androidx.compose.material3.IconButton
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
@@ -46,9 +50,13 @@ import de.jeanlucmakiola.agendula.data.sync.DiscardedEdit
|
|||||||
import de.jeanlucmakiola.agendula.data.sync.SyncNotice
|
import de.jeanlucmakiola.agendula.data.sync.SyncNotice
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.room.AccountEntity
|
import de.jeanlucmakiola.agendula.data.tasks.room.AccountEntity
|
||||||
import de.jeanlucmakiola.agendula.ui.accounts.add.message
|
import de.jeanlucmakiola.agendula.ui.accounts.add.message
|
||||||
|
import de.jeanlucmakiola.agendula.ui.common.NameField
|
||||||
import de.jeanlucmakiola.agendula.ui.common.OnResume
|
import de.jeanlucmakiola.agendula.ui.common.OnResume
|
||||||
|
import de.jeanlucmakiola.caldav.ServerCertificate
|
||||||
|
import de.jeanlucmakiola.caldav.ServerTrust
|
||||||
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
import de.jeanlucmakiola.floret.components.CollapsingScaffold
|
||||||
import de.jeanlucmakiola.floret.components.FullScreenPicker
|
import de.jeanlucmakiola.floret.components.FullScreenPicker
|
||||||
|
import de.jeanlucmakiola.floret.components.GroupedHint
|
||||||
import de.jeanlucmakiola.floret.components.GroupedListInset
|
import de.jeanlucmakiola.floret.components.GroupedListInset
|
||||||
import de.jeanlucmakiola.floret.components.GroupedRow
|
import de.jeanlucmakiola.floret.components.GroupedRow
|
||||||
import de.jeanlucmakiola.floret.components.Position
|
import de.jeanlucmakiola.floret.components.Position
|
||||||
@@ -70,10 +78,13 @@ internal fun AccountDetailScreen(
|
|||||||
onSignInAgain: (AccountEntity) -> Unit,
|
onSignInAgain: (AccountEntity) -> Unit,
|
||||||
onOpenStorage: () -> Unit,
|
onOpenStorage: () -> Unit,
|
||||||
viewModel: AccountsViewModel,
|
viewModel: AccountsViewModel,
|
||||||
|
visible: Boolean,
|
||||||
) {
|
) {
|
||||||
val accounts by viewModel.accounts.collectAsStateWithLifecycle()
|
val accounts by viewModel.accounts.collectAsStateWithLifecycle()
|
||||||
val usable by viewModel.accountsUsable.collectAsStateWithLifecycle()
|
val usable by viewModel.accountsUsable.collectAsStateWithLifecycle()
|
||||||
val push by viewModel.push.collectAsStateWithLifecycle()
|
val push by viewModel.push.collectAsStateWithLifecycle()
|
||||||
|
val trust by remember(accountId) { viewModel.trust(accountId) }
|
||||||
|
.collectAsStateWithLifecycle(ServerTrust.DEFAULT)
|
||||||
OnResume(viewModel::refreshPush)
|
OnResume(viewModel::refreshPush)
|
||||||
val row = accounts?.firstOrNull { it.account.id == accountId }
|
val row = accounts?.firstOrNull { it.account.id == accountId }
|
||||||
|
|
||||||
@@ -89,12 +100,34 @@ internal fun AccountDetailScreen(
|
|||||||
// The confirmation sheet. The removal it starts outlives this screen, and is
|
// The confirmation sheet. The removal it starts outlives this screen, and is
|
||||||
// shown on the accounts list rather than here.
|
// shown on the accounts list rather than here.
|
||||||
var confirming by remember { mutableStateOf(false) }
|
var confirming by remember { mutableStateOf(false) }
|
||||||
|
var renaming by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
CollapsingScaffold(title = identity.title, onBack = onBack) {
|
if (renaming) {
|
||||||
|
AccountNamePicker(
|
||||||
|
current = account.label.orEmpty(),
|
||||||
|
defaultTitle = account.defaultTitle(),
|
||||||
|
onSave = { name ->
|
||||||
|
viewModel.rename(account, name)
|
||||||
|
renaming = false
|
||||||
|
},
|
||||||
|
onDismiss = { renaming = false },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
CollapsingScaffold(title = identity.title, onBack = onBack, predictiveBack = true, visible = visible) {
|
||||||
AccountHero(identity)
|
AccountHero(identity)
|
||||||
Spacer(Modifier.height(24.dp))
|
Spacer(Modifier.height(24.dp))
|
||||||
|
|
||||||
val actions = buildList<@Composable (Position) -> Unit> {
|
val actions = buildList<@Composable (Position) -> Unit> {
|
||||||
|
add { position ->
|
||||||
|
GroupedRow(
|
||||||
|
title = stringResource(R.string.accounts_name),
|
||||||
|
summary = identity.title,
|
||||||
|
position = position,
|
||||||
|
leading = { Icon(Icons.Rounded.Edit, contentDescription = null) },
|
||||||
|
onClick = { renaming = true },
|
||||||
|
)
|
||||||
|
}
|
||||||
add { position ->
|
add { position ->
|
||||||
GroupedRow(
|
GroupedRow(
|
||||||
title = stringResource(R.string.accounts_last_sync),
|
title = stringResource(R.string.accounts_last_sync),
|
||||||
@@ -103,6 +136,28 @@ internal fun AccountDetailScreen(
|
|||||||
leading = { Icon(Icons.Rounded.History, contentDescription = null) },
|
leading = { Icon(Icons.Rounded.History, contentDescription = null) },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
if (trust.allowCleartext) {
|
||||||
|
add { position ->
|
||||||
|
GroupedRow(
|
||||||
|
title = stringResource(R.string.accounts_connection),
|
||||||
|
summary = stringResource(R.string.accounts_connection_cleartext),
|
||||||
|
position = position,
|
||||||
|
leading = { Icon(Icons.Rounded.LockOpen, contentDescription = null) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (trust.pinnedCertificates.isNotEmpty()) {
|
||||||
|
add { position ->
|
||||||
|
GroupedRow(
|
||||||
|
title = stringResource(R.string.accounts_trusted_certificate),
|
||||||
|
summary = trust.pinnedCertificates.sorted().joinToString("\n") {
|
||||||
|
ServerCertificate.formatFingerprint(it.take(PINNED_PREFIX_CHARS)) + ":\u2026"
|
||||||
|
},
|
||||||
|
position = position,
|
||||||
|
leading = { Icon(Icons.Rounded.GppMaybe, contentDescription = null) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
if (!usable) return@buildList
|
if (!usable) return@buildList
|
||||||
push?.let { pushState ->
|
push?.let { pushState ->
|
||||||
add { position ->
|
add { position ->
|
||||||
@@ -114,7 +169,7 @@ internal fun AccountDetailScreen(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (shown.needsSignIn) {
|
if (shown.offersSignIn) {
|
||||||
add { position ->
|
add { position ->
|
||||||
GroupedRow(
|
GroupedRow(
|
||||||
title = stringResource(R.string.accounts_sign_in_again),
|
title = stringResource(R.string.accounts_sign_in_again),
|
||||||
@@ -123,7 +178,8 @@ internal fun AccountDetailScreen(
|
|||||||
onClick = { onSignInAgain(account) },
|
onClick = { onSignInAgain(account) },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
|
if (!shown.needsSignIn) {
|
||||||
add { position ->
|
add { position ->
|
||||||
GroupedRow(
|
GroupedRow(
|
||||||
title = stringResource(R.string.accounts_sync_now),
|
title = stringResource(R.string.accounts_sync_now),
|
||||||
@@ -479,3 +535,33 @@ private fun errorTitle(text: String): AnnotatedString {
|
|||||||
buildAnnotatedString { withStyle(SpanStyle(color = error)) { append(text) } }
|
buildAnnotatedString { withStyle(SpanStyle(color = error)) { append(text) } }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Names an account on screen (#105); left empty, it goes back to [defaultTitle]. */
|
||||||
|
@Composable
|
||||||
|
private fun AccountNamePicker(
|
||||||
|
current: String,
|
||||||
|
defaultTitle: String,
|
||||||
|
onSave: (String) -> Unit,
|
||||||
|
onDismiss: () -> Unit,
|
||||||
|
) {
|
||||||
|
var name by remember { mutableStateOf(current) }
|
||||||
|
FullScreenPicker(
|
||||||
|
title = stringResource(R.string.accounts_name),
|
||||||
|
onDismiss = onDismiss,
|
||||||
|
actions = {
|
||||||
|
TextButton(onClick = { onSave(name) }) { Text(stringResource(R.string.save)) }
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
NameField(
|
||||||
|
name = name,
|
||||||
|
placeholder = defaultTitle,
|
||||||
|
autoFocus = true,
|
||||||
|
onNameChange = { name = it },
|
||||||
|
onImeAction = { onSave(name) },
|
||||||
|
)
|
||||||
|
GroupedHint(stringResource(R.string.accounts_name_hint, defaultTitle))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The first eight bytes of a pinned fingerprint, enough to compare at a glance. */
|
||||||
|
private const val PINNED_PREFIX_CHARS = 16
|
||||||
@@ -44,6 +44,14 @@ internal data class AccountIdentity(
|
|||||||
val user: String?,
|
val user: String?,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/** The title an account has without a [AccountEntity.label]. */
|
||||||
|
internal fun AccountEntity.defaultTitle(): String {
|
||||||
|
val url = principalUrl?.toHttpUrlOrNull()
|
||||||
|
val provider = url?.let { CalDavProvider.forPrincipal(it) }
|
||||||
|
val host = url?.host?.removePrefix("www.")
|
||||||
|
return if (provider?.hosted == true) provider.label else host ?: displayName
|
||||||
|
}
|
||||||
|
|
||||||
internal fun AccountEntity.identity(): AccountIdentity {
|
internal fun AccountEntity.identity(): AccountIdentity {
|
||||||
val url = principalUrl?.toHttpUrlOrNull()
|
val url = principalUrl?.toHttpUrlOrNull()
|
||||||
val provider = url?.let { CalDavProvider.forPrincipal(it) }
|
val provider = url?.let { CalDavProvider.forPrincipal(it) }
|
||||||
@@ -53,7 +61,7 @@ internal fun AccountEntity.identity(): AccountIdentity {
|
|||||||
provider = provider,
|
provider = provider,
|
||||||
// The fallback is the stored name: an account with no principal URL
|
// The fallback is the stored name: an account with no principal URL
|
||||||
// never got past discovery, so there is nothing better to call it.
|
// never got past discovery, so there is nothing better to call it.
|
||||||
title = if (hosted) provider.label else host ?: displayName,
|
title = label ?: defaultTitle(),
|
||||||
secondary = if (hosted) host else provider?.label,
|
secondary = if (hosted) host else provider?.label,
|
||||||
user = username?.takeIf { it.isNotBlank() },
|
user = username?.takeIf { it.isNotBlank() },
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ internal fun AccountsScreen(
|
|||||||
onOpenStorage: () -> Unit,
|
onOpenStorage: () -> Unit,
|
||||||
onBack: () -> Unit,
|
onBack: () -> Unit,
|
||||||
viewModel: AccountsViewModel,
|
viewModel: AccountsViewModel,
|
||||||
|
visible: Boolean,
|
||||||
) {
|
) {
|
||||||
val accounts by viewModel.accounts.collectAsStateWithLifecycle()
|
val accounts by viewModel.accounts.collectAsStateWithLifecycle()
|
||||||
val usable by viewModel.accountsUsable.collectAsStateWithLifecycle()
|
val usable by viewModel.accountsUsable.collectAsStateWithLifecycle()
|
||||||
@@ -60,6 +61,8 @@ internal fun AccountsScreen(
|
|||||||
CollapsingScaffold(
|
CollapsingScaffold(
|
||||||
title = stringResource(R.string.settings_section_accounts),
|
title = stringResource(R.string.settings_section_accounts),
|
||||||
onBack = onBack,
|
onBack = onBack,
|
||||||
|
predictiveBack = true,
|
||||||
|
visible = visible,
|
||||||
) {
|
) {
|
||||||
val loaded = accounts ?: return@CollapsingScaffold
|
val loaded = accounts ?: return@CollapsingScaffold
|
||||||
|
|
||||||
@@ -116,7 +119,7 @@ internal fun AccountsScreen(
|
|||||||
when {
|
when {
|
||||||
row.removing -> CircularProgressIndicator(Modifier.size(20.dp))
|
row.removing -> CircularProgressIndicator(Modifier.size(20.dp))
|
||||||
!usable -> Unit
|
!usable -> Unit
|
||||||
row.needsSignIn -> IconButton(onClick = { onSignInAgain(account) }) {
|
row.offersSignIn -> IconButton(onClick = { onSignInAgain(account) }) {
|
||||||
Icon(
|
Icon(
|
||||||
Icons.AutoMirrored.Rounded.Login,
|
Icons.AutoMirrored.Rounded.Login,
|
||||||
contentDescription = stringResource(R.string.accounts_sign_in_again),
|
contentDescription = stringResource(R.string.accounts_sign_in_again),
|
||||||
|
|||||||
@@ -8,7 +8,9 @@ import de.jeanlucmakiola.agendula.data.prefs.DEFAULT_SYNC_INTERVAL_MINUTES
|
|||||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||||
import de.jeanlucmakiola.agendula.data.sync.AccountRepository
|
import de.jeanlucmakiola.agendula.data.sync.AccountRepository
|
||||||
import de.jeanlucmakiola.agendula.data.sync.AccountStateStore
|
import de.jeanlucmakiola.agendula.data.sync.AccountStateStore
|
||||||
|
import de.jeanlucmakiola.agendula.data.sync.ServerTrustStore
|
||||||
import de.jeanlucmakiola.agendula.data.sync.SyncAvailability
|
import de.jeanlucmakiola.agendula.data.sync.SyncAvailability
|
||||||
|
import de.jeanlucmakiola.agendula.data.sync.SyncFailure
|
||||||
import de.jeanlucmakiola.agendula.data.sync.SyncNotice
|
import de.jeanlucmakiola.agendula.data.sync.SyncNotice
|
||||||
import de.jeanlucmakiola.agendula.data.sync.SyncNoticeStore
|
import de.jeanlucmakiola.agendula.data.sync.SyncNoticeStore
|
||||||
import de.jeanlucmakiola.agendula.data.sync.SyncTrigger
|
import de.jeanlucmakiola.agendula.data.sync.SyncTrigger
|
||||||
@@ -30,6 +32,7 @@ import kotlinx.coroutines.flow.stateIn
|
|||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import de.jeanlucmakiola.caldav.CalDavDiscovery
|
import de.jeanlucmakiola.caldav.CalDavDiscovery
|
||||||
|
import de.jeanlucmakiola.caldav.ServerTrust
|
||||||
import de.jeanlucmakiola.caldav.TaskCollection
|
import de.jeanlucmakiola.caldav.TaskCollection
|
||||||
import okhttp3.HttpUrl
|
import okhttp3.HttpUrl
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
@@ -43,6 +46,7 @@ class AccountsViewModel @Inject constructor(
|
|||||||
private val settings: SettingsPrefs,
|
private val settings: SettingsPrefs,
|
||||||
private val distributors: PushDistributors,
|
private val distributors: PushDistributors,
|
||||||
private val pushRegistrar: PushRegistrar,
|
private val pushRegistrar: PushRegistrar,
|
||||||
|
private val serverTrust: ServerTrustStore,
|
||||||
pushStore: PushStore,
|
pushStore: PushStore,
|
||||||
availability: SyncAvailability,
|
availability: SyncAvailability,
|
||||||
@IoDispatcher io: CoroutineDispatcher,
|
@IoDispatcher io: CoroutineDispatcher,
|
||||||
@@ -188,7 +192,18 @@ class AccountsViewModel @Inject constructor(
|
|||||||
*/
|
*/
|
||||||
val notices: List<SyncNotice> = emptyList(),
|
val notices: List<SyncNotice> = emptyList(),
|
||||||
val lists: ListPush = ListPush.NONE,
|
val lists: ListPush = ListPush.NONE,
|
||||||
)
|
) {
|
||||||
|
/**
|
||||||
|
* The last sync was refused over the server's certificate — typically a
|
||||||
|
* pinned one that was renewed. Nothing sets [needsSignIn] for that, yet
|
||||||
|
* signing in again is the only route that can trust the new one.
|
||||||
|
*/
|
||||||
|
val certificateRefused: Boolean
|
||||||
|
get() = account.lastSyncError?.let { SyncFailure.of(it).kind == SyncFailure.Kind.CERTIFICATE } == true
|
||||||
|
|
||||||
|
/** Whether "Sign in again" is the way forward for this account. */
|
||||||
|
val offersSignIn: Boolean get() = needsSignIn || certificateRefused
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Accounts whose removal has started and not finished.
|
* Accounts whose removal has started and not finished.
|
||||||
@@ -248,6 +263,13 @@ class AccountsViewModel @Inject constructor(
|
|||||||
syncTrigger.enqueue(account.displayName, expedited = true)
|
syncTrigger.enqueue(account.displayName, expedited = true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun rename(account: AccountEntity, label: String) {
|
||||||
|
viewModelScope.launch { repository.setLabel(account.id, label) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the user agreed to trust for [accountId] beyond the platform's defaults. */
|
||||||
|
fun trust(accountId: Long): Flow<ServerTrust> = serverTrust.observe(accountId)
|
||||||
|
|
||||||
/** The user has read what the last sync changed. */
|
/** The user has read what the last sync changed. */
|
||||||
fun dismissNotices(account: AccountEntity) {
|
fun dismissNotices(account: AccountEntity) {
|
||||||
viewModelScope.launch { notices.dismiss(account.id) }
|
viewModelScope.launch { notices.dismiss(account.id) }
|
||||||
|
|||||||
@@ -17,7 +17,9 @@ import androidx.compose.material.icons.automirrored.rounded.ArrowBack
|
|||||||
import androidx.compose.material.icons.rounded.Checklist
|
import androidx.compose.material.icons.rounded.Checklist
|
||||||
import androidx.compose.material.icons.rounded.CloudOff
|
import androidx.compose.material.icons.rounded.CloudOff
|
||||||
import androidx.compose.material.icons.rounded.CloudSync
|
import androidx.compose.material.icons.rounded.CloudSync
|
||||||
|
import androidx.compose.material.icons.rounded.GppMaybe
|
||||||
import androidx.compose.material.icons.rounded.Lock
|
import androidx.compose.material.icons.rounded.Lock
|
||||||
|
import androidx.compose.material.icons.rounded.LockOpen
|
||||||
import androidx.compose.material.icons.rounded.OpenInBrowser
|
import androidx.compose.material.icons.rounded.OpenInBrowser
|
||||||
import androidx.compose.material.icons.rounded.Warning
|
import androidx.compose.material.icons.rounded.Warning
|
||||||
import androidx.compose.material3.Icon
|
import androidx.compose.material3.Icon
|
||||||
@@ -179,6 +181,8 @@ internal fun AddAccountScreen(
|
|||||||
is AddAccountStep.Working -> WorkingStep(step)
|
is AddAccountStep.Working -> WorkingStep(step)
|
||||||
is AddAccountStep.EnterCredentials -> CredentialsStep(step, viewModel)
|
is AddAccountStep.EnterCredentials -> CredentialsStep(step, viewModel)
|
||||||
is AddAccountStep.ConfirmBrowser -> ConfirmBrowserStep(step)
|
is AddAccountStep.ConfirmBrowser -> ConfirmBrowserStep(step)
|
||||||
|
is AddAccountStep.ConfirmCleartext -> ConfirmCleartextStep(step)
|
||||||
|
is AddAccountStep.TrustCertificate -> TrustCertificateStep(step)
|
||||||
is AddAccountStep.WaitingForBrowser -> BrowserStep(step)
|
is AddAccountStep.WaitingForBrowser -> BrowserStep(step)
|
||||||
is AddAccountStep.ChooseLists -> ListsStep(step, viewModel)
|
is AddAccountStep.ChooseLists -> ListsStep(step, viewModel)
|
||||||
is AddAccountStep.Summary -> SummaryStep(step)
|
is AddAccountStep.Summary -> SummaryStep(step)
|
||||||
@@ -228,7 +232,11 @@ private fun AddAccountStep.position(hasSetup: Boolean): Int? {
|
|||||||
return when (this) {
|
return when (this) {
|
||||||
is AddAccountStep.ChooseProvider -> 1
|
is AddAccountStep.ChooseProvider -> 1
|
||||||
is AddAccountStep.PrepareAccess -> 2
|
is AddAccountStep.PrepareAccess -> 2
|
||||||
is AddAccountStep.EnterAddress -> 2 + errand
|
// Both are about reaching the server, so they keep the address's slot.
|
||||||
|
is AddAccountStep.EnterAddress,
|
||||||
|
is AddAccountStep.ConfirmCleartext,
|
||||||
|
is AddAccountStep.TrustCertificate,
|
||||||
|
-> 2 + errand
|
||||||
// One slot, because only one of the three ever happens: a server either
|
// One slot, because only one of the three ever happens: a server either
|
||||||
// hands the sign-in to a browser — asking first, where the URL needs
|
// hands the sign-in to a browser — asking first, where the URL needs
|
||||||
// confirming — or asks for a password.
|
// confirming — or asks for a password.
|
||||||
@@ -272,6 +280,8 @@ private fun StepHero(state: AddAccountUiState) {
|
|||||||
// The warning is the screen, so it is the mark too — the browser icon
|
// The warning is the screen, so it is the mark too — the browser icon
|
||||||
// would say "this is going fine", which is the opposite of the point.
|
// would say "this is going fine", which is the opposite of the point.
|
||||||
state.step is AddAccountStep.ConfirmBrowser -> Icons.Rounded.Warning
|
state.step is AddAccountStep.ConfirmBrowser -> Icons.Rounded.Warning
|
||||||
|
state.step is AddAccountStep.ConfirmCleartext -> Icons.Rounded.LockOpen
|
||||||
|
state.step is AddAccountStep.TrustCertificate -> Icons.Rounded.GppMaybe
|
||||||
state.step is AddAccountStep.WaitingForBrowser -> Icons.Rounded.OpenInBrowser
|
state.step is AddAccountStep.WaitingForBrowser -> Icons.Rounded.OpenInBrowser
|
||||||
state.step is AddAccountStep.ChooseLists -> Icons.Rounded.Checklist
|
state.step is AddAccountStep.ChooseLists -> Icons.Rounded.Checklist
|
||||||
else -> Icons.Rounded.CloudSync
|
else -> Icons.Rounded.CloudSync
|
||||||
@@ -300,7 +310,9 @@ private fun StepTitle(step: AddAccountStep) {
|
|||||||
R.string.add_account_provider_title to R.string.add_account_provider_body
|
R.string.add_account_provider_title to R.string.add_account_provider_body
|
||||||
is AddAccountStep.PrepareAccess ->
|
is AddAccountStep.PrepareAccess ->
|
||||||
step.quirk.setupTitle to R.string.add_account_setup_body
|
step.quirk.setupTitle to R.string.add_account_setup_body
|
||||||
is AddAccountStep.EnterAddress -> if (step.choice.provider?.hosted == true) {
|
is AddAccountStep.EnterAddress -> if (step.manualServer) {
|
||||||
|
R.string.add_account_server_title to R.string.add_account_server_fallback_body
|
||||||
|
} else if (step.asksForEmail) {
|
||||||
R.string.add_account_email_title to R.string.add_account_email_body
|
R.string.add_account_email_title to R.string.add_account_email_body
|
||||||
} else {
|
} else {
|
||||||
R.string.add_account_server_title to R.string.add_account_server_body
|
R.string.add_account_server_title to R.string.add_account_server_body
|
||||||
@@ -309,6 +321,10 @@ private fun StepTitle(step: AddAccountStep) {
|
|||||||
R.string.add_account_credentials_title to R.string.add_account_credentials_body
|
R.string.add_account_credentials_title to R.string.add_account_credentials_body
|
||||||
is AddAccountStep.ConfirmBrowser ->
|
is AddAccountStep.ConfirmBrowser ->
|
||||||
R.string.add_account_browser_confirm_title to R.string.add_account_browser_confirm_body
|
R.string.add_account_browser_confirm_title to R.string.add_account_browser_confirm_body
|
||||||
|
is AddAccountStep.ConfirmCleartext ->
|
||||||
|
R.string.add_account_cleartext_title to R.string.add_account_cleartext_body
|
||||||
|
is AddAccountStep.TrustCertificate ->
|
||||||
|
R.string.add_account_certificate_title to R.string.add_account_certificate_body
|
||||||
is AddAccountStep.ChooseLists ->
|
is AddAccountStep.ChooseLists ->
|
||||||
R.string.add_account_lists_title to R.string.add_account_lists_body
|
R.string.add_account_lists_title to R.string.add_account_lists_body
|
||||||
is AddAccountStep.Summary ->
|
is AddAccountStep.Summary ->
|
||||||
@@ -410,6 +426,34 @@ private fun ColumnScope.StepActions(state: AddAccountUiState, viewModel: AddAcco
|
|||||||
) { Text(stringResource(R.string.add_account_browser_use_password)) }
|
) { Text(stringResource(R.string.add_account_browser_use_password)) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Plain http stays a deliberate choice: going forward is primary, as it
|
||||||
|
// is for the browser warning, and changing the address is right below.
|
||||||
|
is AddAccountStep.ConfirmCleartext -> {
|
||||||
|
PrimaryAction(
|
||||||
|
label = stringResource(R.string.add_account_cleartext_connect),
|
||||||
|
enabled = true,
|
||||||
|
onClick = viewModel::onCleartextConfirmed,
|
||||||
|
)
|
||||||
|
TextButton(
|
||||||
|
onClick = { viewModel.onBackWithin() },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
) { Text(stringResource(R.string.add_account_change_address)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
// The safe answer stays visible, as it does for plain http: back is
|
||||||
|
// not something every user knows to look for on a security prompt.
|
||||||
|
is AddAccountStep.TrustCertificate -> {
|
||||||
|
PrimaryAction(
|
||||||
|
label = stringResource(R.string.add_account_certificate_trust),
|
||||||
|
enabled = true,
|
||||||
|
onClick = viewModel::onCertificateTrusted,
|
||||||
|
)
|
||||||
|
TextButton(
|
||||||
|
onClick = { viewModel.onBackWithin() },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
) { Text(stringResource(R.string.add_account_certificate_decline)) }
|
||||||
|
}
|
||||||
|
|
||||||
is AddAccountStep.WaitingForBrowser -> {
|
is AddAccountStep.WaitingForBrowser -> {
|
||||||
// A failed flow is retried by default. With no browser a retry
|
// A failed flow is retried by default. With no browser a retry
|
||||||
// cannot help; while the server throttles or is in maintenance an
|
// cannot help; while the server throttles or is in maintenance an
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ internal val CalDavDiscovery.Outcome.Cause.message: Int
|
|||||||
CalDavDiscovery.Outcome.Cause.NOT_A_DAV_SERVER -> R.string.add_account_error_not_dav
|
CalDavDiscovery.Outcome.Cause.NOT_A_DAV_SERVER -> R.string.add_account_error_not_dav
|
||||||
CalDavDiscovery.Outcome.Cause.NO_CALENDAR_SUPPORT -> R.string.add_account_error_no_calendar
|
CalDavDiscovery.Outcome.Cause.NO_CALENDAR_SUPPORT -> R.string.add_account_error_no_calendar
|
||||||
CalDavDiscovery.Outcome.Cause.UNREACHABLE -> R.string.add_account_error_unreachable
|
CalDavDiscovery.Outcome.Cause.UNREACHABLE -> R.string.add_account_error_unreachable
|
||||||
|
CalDavDiscovery.Outcome.Cause.TLS -> R.string.add_account_error_tls
|
||||||
CalDavDiscovery.Outcome.Cause.INSECURE -> R.string.add_account_error_insecure
|
CalDavDiscovery.Outcome.Cause.INSECURE -> R.string.add_account_error_insecure
|
||||||
CalDavDiscovery.Outcome.Cause.NO_CALENDARS -> R.string.add_account_error_no_calendars
|
CalDavDiscovery.Outcome.Cause.NO_CALENDARS -> R.string.add_account_error_no_calendars
|
||||||
CalDavDiscovery.Outcome.Cause.SERVER_ERROR -> R.string.add_account_error_server
|
CalDavDiscovery.Outcome.Cause.SERVER_ERROR -> R.string.add_account_error_server
|
||||||
|
|||||||
+312
-68
@@ -8,13 +8,18 @@ import de.jeanlucmakiola.agendula.data.sync.AccountCreator
|
|||||||
import de.jeanlucmakiola.agendula.data.sync.AccountRepository
|
import de.jeanlucmakiola.agendula.data.sync.AccountRepository
|
||||||
import de.jeanlucmakiola.agendula.data.sync.CalDavGateway
|
import de.jeanlucmakiola.agendula.data.sync.CalDavGateway
|
||||||
import de.jeanlucmakiola.agendula.data.sync.LoginFlowRecord
|
import de.jeanlucmakiola.agendula.data.sync.LoginFlowRecord
|
||||||
|
import de.jeanlucmakiola.agendula.data.sync.ServerTrustKeys
|
||||||
import de.jeanlucmakiola.caldav.CalDavDiscovery
|
import de.jeanlucmakiola.caldav.CalDavDiscovery
|
||||||
import de.jeanlucmakiola.caldav.CalDavProvider
|
import de.jeanlucmakiola.caldav.CalDavProvider
|
||||||
import de.jeanlucmakiola.caldav.NextcloudLoginFlow
|
import de.jeanlucmakiola.caldav.NextcloudLoginFlow
|
||||||
|
import de.jeanlucmakiola.caldav.ServerCertificate
|
||||||
import de.jeanlucmakiola.caldav.ServerQuirk
|
import de.jeanlucmakiola.caldav.ServerQuirk
|
||||||
|
import de.jeanlucmakiola.caldav.ServerTrust
|
||||||
import de.jeanlucmakiola.caldav.ServiceDiscovery
|
import de.jeanlucmakiola.caldav.ServiceDiscovery
|
||||||
import de.jeanlucmakiola.caldav.TaskCollection
|
import de.jeanlucmakiola.caldav.TaskCollection
|
||||||
import de.jeanlucmakiola.agendula.data.di.ApplicationScope
|
import de.jeanlucmakiola.agendula.data.di.ApplicationScope
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.NonCancellable
|
import kotlinx.coroutines.NonCancellable
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
@@ -77,7 +82,12 @@ sealed interface AddAccountStep {
|
|||||||
val input: String = "",
|
val input: String = "",
|
||||||
/** A cause, not a message — the screen owns the wording. */
|
/** A cause, not a message — the screen owns the wording. */
|
||||||
val error: CalDavDiscovery.Outcome.Cause? = null,
|
val error: CalDavDiscovery.Outcome.Cause? = null,
|
||||||
) : AddAccountStep
|
/** The email address found no server, so a hosted choice asks for its URL instead. */
|
||||||
|
val manualServer: Boolean = false,
|
||||||
|
) : AddAccountStep {
|
||||||
|
/** Whether the field takes an email address rather than a server URL. */
|
||||||
|
val asksForEmail: Boolean get() = choice.provider?.hosted == true && !manualServer
|
||||||
|
}
|
||||||
|
|
||||||
data class Working(val message: AddAccountMessage.Progress) : AddAccountStep
|
data class Working(val message: AddAccountMessage.Progress) : AddAccountStep
|
||||||
|
|
||||||
@@ -111,6 +121,12 @@ sealed interface AddAccountStep {
|
|||||||
val insecure: Boolean = false,
|
val insecure: Boolean = false,
|
||||||
) : AddAccountStep
|
) : AddAccountStep
|
||||||
|
|
||||||
|
/** The typed address is plain http; the user has to accept that before anything is sent. */
|
||||||
|
data class ConfirmCleartext(val address: String) : AddAccountStep
|
||||||
|
|
||||||
|
/** The server's certificate is not trusted by the platform; the user may pin it. */
|
||||||
|
data class TrustCertificate(val certificate: ServerCertificate) : AddAccountStep
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The browser has the flow. We poll until the user approves, and offer an
|
* The browser has the flow. We poll until the user approves, and offer an
|
||||||
* explicit way out — Custom Tabs return **no result** when dismissed, and
|
* explicit way out — Custom Tabs return **no result** when dismissed, and
|
||||||
@@ -279,6 +295,11 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
get() = handle[KEY_REAUTH_ACCOUNT]
|
get() = handle[KEY_REAUTH_ACCOUNT]
|
||||||
set(value) { handle[KEY_REAUTH_ACCOUNT] = value }
|
set(value) { handle[KEY_REAUTH_ACCOUNT] = value }
|
||||||
|
|
||||||
|
/** The email that found no server; Back returns to it from the server field. */
|
||||||
|
private var fallbackEmail: String?
|
||||||
|
get() = handle[KEY_FALLBACK_EMAIL]
|
||||||
|
set(value) { handle[KEY_FALLBACK_EMAIL] = value }
|
||||||
|
|
||||||
/** The username the credentials step starts with on a re-authentication. */
|
/** The username the credentials step starts with on a re-authentication. */
|
||||||
private var suggestedUsername: String
|
private var suggestedUsername: String
|
||||||
get() = handle[KEY_SUGGESTED_USERNAME] ?: ""
|
get() = handle[KEY_SUGGESTED_USERNAME] ?: ""
|
||||||
@@ -317,6 +338,36 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
/** The flow the browser was last sent to, for a retry while it is still open. */
|
/** The flow the browser was last sent to, for a retry while it is still open. */
|
||||||
private var browserFlow: NextcloudLoginFlow.Flow? = null
|
private var browserFlow: NextcloudLoginFlow.Flow? = null
|
||||||
|
|
||||||
|
/** What the user agreed to trust in this flow, handed to every gateway call. */
|
||||||
|
private var trust: ServerTrust
|
||||||
|
get() = TRUST_KEYS.read(handle)
|
||||||
|
set(value) = TRUST_KEYS.write(handle, value)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The address [trust] was given for. Pins and plain http both belong to it,
|
||||||
|
* so submitting any other address starts from nothing.
|
||||||
|
*/
|
||||||
|
private var trustAddress: String?
|
||||||
|
get() = handle[KEY_TRUST_ADDRESS]
|
||||||
|
set(value) { handle[KEY_TRUST_ADDRESS] = value }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The pins in [trust] came from the account being signed in to, not from
|
||||||
|
* this flow. The first certificate trusted now replaces them, so a renewed
|
||||||
|
* certificate retires the one it renews instead of joining it.
|
||||||
|
*/
|
||||||
|
private var inheritedPins: Boolean
|
||||||
|
get() = handle[KEY_INHERITED_PINS] ?: false
|
||||||
|
set(value) { handle[KEY_INHERITED_PINS] = value }
|
||||||
|
|
||||||
|
/** Loading a re-authenticated account's stored trust, which discovery waits for. */
|
||||||
|
private var trustLoad: Job? = null
|
||||||
|
|
||||||
|
/** The open [AddAccountStep.TrustCertificate] question, and where declining it goes. */
|
||||||
|
private class TrustPrompt(val answer: CompletableDeferred<Unit>, val back: AddAccountStep)
|
||||||
|
|
||||||
|
private var trustPrompt: TrustPrompt? = null
|
||||||
|
|
||||||
/** Which hosts asked for credentials, for the cross-domain diagnostic. */
|
/** Which hosts asked for credentials, for the cross-domain diagnostic. */
|
||||||
private var hostsNeedingAuth: List<String>
|
private var hostsNeedingAuth: List<String>
|
||||||
get() = handle.get<ArrayList<String>>(KEY_HOSTS_NEEDING_AUTH).orEmpty()
|
get() = handle.get<ArrayList<String>>(KEY_HOSTS_NEEDING_AUTH).orEmpty()
|
||||||
@@ -370,6 +421,7 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
// one is not an answer to this one.
|
// one is not an answer to this one.
|
||||||
if (picked != choice) addressInput = ""
|
if (picked != choice) addressInput = ""
|
||||||
choice = picked
|
choice = picked
|
||||||
|
clearFallback()
|
||||||
val quirk = picked.provider?.let(ServerQuirk::forProvider)
|
val quirk = picked.provider?.let(ServerQuirk::forProvider)
|
||||||
val setup = quirk?.hasSetupSteps == true
|
val setup = quirk?.hasSetupSteps == true
|
||||||
updateState {
|
updateState {
|
||||||
@@ -413,6 +465,15 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
reauthenticating = true,
|
reauthenticating = true,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
// Starts from what the account already trusts, so a renewed certificate
|
||||||
|
// is the only thing asked about again.
|
||||||
|
val address = addressInput
|
||||||
|
trustLoad = viewModelScope.launch {
|
||||||
|
val stored = runCatching { repository.trustFor(accountId) }.getOrDefault(ServerTrust.DEFAULT)
|
||||||
|
trust = stored
|
||||||
|
trustAddress = address
|
||||||
|
inheritedPins = stored.pinnedCertificates.isNotEmpty()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The errand is read; on to the address. */
|
/** The errand is read; on to the address. */
|
||||||
@@ -430,11 +491,10 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
addressInput = value
|
addressInput = value
|
||||||
updateState {
|
updateState {
|
||||||
it.copy(
|
it.copy(
|
||||||
step = AddAccountStep.EnterAddress(picked, value),
|
step = addressStep(value),
|
||||||
// The service's own rule outranks the one the typed host implies:
|
// The service's own rule outranks the one the typed host implies:
|
||||||
// it was chosen deliberately, and it is known before a key is hit.
|
// it was chosen deliberately, and it is known before a key is hit.
|
||||||
quirk = picked.provider?.let(ServerQuirk::forProvider)
|
quirk = quirkFor(value),
|
||||||
?: ServerQuirk.forInput(value),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -488,10 +548,25 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
serverRoot = ServiceDiscovery.serverRootFor(input)
|
serverRoot = ServiceDiscovery.serverRootFor(input)
|
||||||
|
discoverAddress()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Discovery for the submitted address, without credentials. */
|
||||||
|
private fun discoverAddress() {
|
||||||
working(AddAccountMessage.Progress.Discovering)
|
working(AddAccountMessage.Progress.Discovering)
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
when (val outcome = gateway.discover(typedInput)) {
|
// ⚠️ After the stored trust has landed, not before: reset first and
|
||||||
|
// the load would put the old address's trust back on top.
|
||||||
|
trustLoad?.join()
|
||||||
|
if (typedInput != trustAddress) {
|
||||||
|
trust = ServerTrust.DEFAULT
|
||||||
|
inheritedPins = false
|
||||||
|
trustAddress = typedInput
|
||||||
|
}
|
||||||
|
val outcome = discoverTrusting(addressStep(typedInput), AddAccountMessage.Progress.Discovering) {
|
||||||
|
gateway.discover(typedInput, trust = trust)
|
||||||
|
} ?: return@launch
|
||||||
|
when (outcome) {
|
||||||
is CalDavDiscovery.Outcome.Found -> onDiscovered(outcome)
|
is CalDavDiscovery.Outcome.Found -> onDiscovered(outcome)
|
||||||
|
|
||||||
is CalDavDiscovery.Outcome.NeedsAuthentication -> {
|
is CalDavDiscovery.Outcome.NeedsAuthentication -> {
|
||||||
@@ -505,20 +580,117 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
// would make it permanently unreachable.
|
// would make it permanently unreachable.
|
||||||
CalDavDiscovery.Outcome.Unauthenticated -> offerSignIn()
|
CalDavDiscovery.Outcome.Unauthenticated -> offerSignIn()
|
||||||
|
|
||||||
is CalDavDiscovery.Outcome.NotCalDav -> backToAddress(outcome.cause)
|
is CalDavDiscovery.Outcome.NotCalDav -> backToAddressOrServer(outcome.cause)
|
||||||
|
|
||||||
is CalDavDiscovery.Outcome.Failed -> backToAddress(outcome.cause)
|
is CalDavDiscovery.Outcome.Failed -> if (needsCleartextConsent(outcome.cause)) {
|
||||||
|
updateState { it.copy(step = AddAccountStep.ConfirmCleartext(typedInput)) }
|
||||||
|
} else {
|
||||||
|
backToAddressOrServer(outcome.cause)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Asked about inside discoverTrusting, which only returns it declined.
|
||||||
|
is CalDavDiscovery.Outcome.UntrustedCertificate -> Unit
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A typed http:// address the user has not yet accepted as unencrypted. */
|
||||||
|
private fun needsCleartextConsent(cause: CalDavDiscovery.Outcome.Cause): Boolean =
|
||||||
|
cause == CalDavDiscovery.Outcome.Cause.INSECURE && !trust.allowCleartext &&
|
||||||
|
typedInput.toHttpUrlOrNull()?.isHttps == false
|
||||||
|
|
||||||
|
/** The warning is read and plain http is wanted anyway. */
|
||||||
|
fun onCleartextConfirmed() {
|
||||||
|
if (current.step !is AddAccountStep.ConfirmCleartext) return
|
||||||
|
trust = trust.copy(allowCleartext = true)
|
||||||
|
trustAddress = typedInput
|
||||||
|
discoverAddress()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The fingerprint is checked; pin it and re-run what it stopped. */
|
||||||
|
fun onCertificateTrusted() {
|
||||||
|
val step = current.step as? AddAccountStep.TrustCertificate ?: return
|
||||||
|
val prompt = trustPrompt ?: return
|
||||||
|
trustPrompt = null
|
||||||
|
val fingerprint = step.certificate.fingerprint
|
||||||
|
trust = if (inheritedPins) {
|
||||||
|
trust.copy(pinnedCertificates = setOf(fingerprint.lowercase()))
|
||||||
|
} else {
|
||||||
|
trust.withCertificate(fingerprint)
|
||||||
|
}
|
||||||
|
inheritedPins = false
|
||||||
|
prompt.answer.complete(Unit)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs [discover], and on a certificate the user could trust asks about it
|
||||||
|
* and runs it again once they have. Null when they declined; the step is
|
||||||
|
* then already [back].
|
||||||
|
*/
|
||||||
|
private suspend fun discoverTrusting(
|
||||||
|
back: AddAccountStep,
|
||||||
|
progress: AddAccountMessage.Progress,
|
||||||
|
discover: suspend () -> CalDavDiscovery.Outcome,
|
||||||
|
): CalDavDiscovery.Outcome? {
|
||||||
|
while (true) {
|
||||||
|
val outcome = discover()
|
||||||
|
if (outcome !is CalDavDiscovery.Outcome.UntrustedCertificate) return outcome
|
||||||
|
val prompt = TrustPrompt(CompletableDeferred(), back)
|
||||||
|
trustPrompt = prompt
|
||||||
|
updateState { it.copy(step = AddAccountStep.TrustCertificate(outcome.certificate), openInBrowser = null) }
|
||||||
|
try {
|
||||||
|
prompt.answer.await()
|
||||||
|
} catch (_: CancellationException) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
working(progress)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An email address whose domain has no CalDAV server goes straight to the
|
||||||
|
* server field rather than an error with nowhere to go; the email stays as
|
||||||
|
* the username. A domain nothing answered for may also be a typo or no
|
||||||
|
* network, so that message stays visible on the server field. Any other
|
||||||
|
* failure keeps its own message on the email field.
|
||||||
|
*/
|
||||||
|
private fun backToAddressOrServer(cause: CalDavDiscovery.Outcome.Cause) {
|
||||||
|
val email = ServiceDiscovery.emailOf(typedInput)
|
||||||
|
if (fallbackEmail != null || email == null || cause !in NO_SERVER_FOUND) {
|
||||||
|
return backToAddress(cause)
|
||||||
|
}
|
||||||
|
fallbackEmail = email
|
||||||
|
addressInput = ""
|
||||||
|
updateState {
|
||||||
|
it.copy(
|
||||||
|
step = addressStep("", cause.takeIf { it == CalDavDiscovery.Outcome.Cause.UNREACHABLE }),
|
||||||
|
quirk = quirkFor(""),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun clearFallback() {
|
||||||
|
fallbackEmail = null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The username the credentials step starts with: a re-authentication's, else
|
||||||
|
* the email that fell back to the server field — or one typed into it.
|
||||||
|
*/
|
||||||
|
private fun prefilledUsername(): String = suggestedUsername.ifBlank {
|
||||||
|
fallbackEmail?.let { ServiceDiscovery.emailOf(typedInput) ?: it }.orEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
/** Step 3a → re-run discovery with the password the user typed. */
|
/** Step 3a → re-run discovery with the password the user typed. */
|
||||||
fun onCredentialsSubmitted() {
|
fun onCredentialsSubmitted() {
|
||||||
val step = current.step as? AddAccountStep.EnterCredentials ?: return
|
val step = current.step as? AddAccountStep.EnterCredentials ?: return
|
||||||
if (step.username.isBlank() || step.password.isEmpty()) return
|
if (step.username.isBlank() || step.password.isEmpty()) return
|
||||||
username = step.username.trim()
|
username = step.username.trim()
|
||||||
appPassword = step.password
|
appPassword = step.password
|
||||||
|
discoverWithCredentials()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun discoverWithCredentials() {
|
||||||
working(AddAccountMessage.Progress.SigningIn)
|
working(AddAccountMessage.Progress.SigningIn)
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
// ⚠️ An error, not a silent unauthenticated retry. serverRootFor
|
// ⚠️ An error, not a silent unauthenticated retry. serverRootFor
|
||||||
@@ -529,7 +701,11 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
val root = serverRoot
|
val root = serverRoot
|
||||||
?: return@launch backToAddress(CalDavDiscovery.Outcome.Cause.NOT_AN_ADDRESS)
|
?: return@launch backToAddress(CalDavDiscovery.Outcome.Cause.NOT_AN_ADDRESS)
|
||||||
val credentials = CalDavGateway.Credentials(username, appPassword, root)
|
val credentials = CalDavGateway.Credentials(username, appPassword, root)
|
||||||
when (val outcome = gateway.discover(typedInput, credentials)) {
|
val outcome = discoverTrusting(
|
||||||
|
AddAccountStep.EnterCredentials(username = username),
|
||||||
|
AddAccountMessage.Progress.SigningIn,
|
||||||
|
) { gateway.discover(typedInput, credentials, trust) } ?: return@launch
|
||||||
|
when (outcome) {
|
||||||
is CalDavDiscovery.Outcome.Found -> onDiscovered(outcome)
|
is CalDavDiscovery.Outcome.Found -> onDiscovered(outcome)
|
||||||
|
|
||||||
// A second rejection is the point at which naming the provider's
|
// A second rejection is the point at which naming the provider's
|
||||||
@@ -549,8 +725,9 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
|
|
||||||
CalDavDiscovery.Outcome.Unauthenticated -> credentialsRejected()
|
CalDavDiscovery.Outcome.Unauthenticated -> credentialsRejected()
|
||||||
|
|
||||||
is CalDavDiscovery.Outcome.NotCalDav -> backToAddress(outcome.cause)
|
is CalDavDiscovery.Outcome.NotCalDav -> backToAddressOrServer(outcome.cause)
|
||||||
is CalDavDiscovery.Outcome.Failed -> backToAddress(outcome.cause)
|
is CalDavDiscovery.Outcome.Failed -> backToAddressOrServer(outcome.cause)
|
||||||
|
is CalDavDiscovery.Outcome.UntrustedCertificate -> Unit
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -569,7 +746,7 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
/** Step 3b → the browser flow, if this looks like a Nextcloud. */
|
/** Step 3b → the browser flow, if this looks like a Nextcloud. */
|
||||||
private suspend fun offerSignIn() {
|
private suspend fun offerSignIn() {
|
||||||
val root = serverRoot ?: return backToAddress(CalDavDiscovery.Outcome.Cause.NOT_AN_ADDRESS)
|
val root = serverRoot ?: return backToAddress(CalDavDiscovery.Outcome.Cause.NOT_AN_ADDRESS)
|
||||||
val flow = gateway.startLoginFlow(root)
|
val flow = gateway.startLoginFlow(root, trust)
|
||||||
|
|
||||||
if (flow == null) {
|
if (flow == null) {
|
||||||
// Not a Nextcloud, or its login flow is unavailable. Ask for a
|
// Not a Nextcloud, or its login flow is unavailable. Ask for a
|
||||||
@@ -577,7 +754,7 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
updateState {
|
updateState {
|
||||||
it.copy(
|
it.copy(
|
||||||
step = AddAccountStep.EnterCredentials(
|
step = AddAccountStep.EnterCredentials(
|
||||||
username = suggestedUsername,
|
username = prefilledUsername(),
|
||||||
error = quirkHint(),
|
error = quirkHint(),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -630,7 +807,7 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
*/
|
*/
|
||||||
private suspend fun launchBrowser(flow: NextcloudLoginFlow.Flow) {
|
private suspend fun launchBrowser(flow: NextcloudLoginFlow.Flow) {
|
||||||
browserFlow = flow
|
browserFlow = flow
|
||||||
runCatching { pendingFlow.remember(flow) }
|
runCatching { pendingFlow.remember(flow, trust) }
|
||||||
updateState {
|
updateState {
|
||||||
it.copy(
|
it.copy(
|
||||||
step = AddAccountStep.WaitingForBrowser(hostMismatch = flow.hostMismatch),
|
step = AddAccountStep.WaitingForBrowser(hostMismatch = flow.hostMismatch),
|
||||||
@@ -659,7 +836,7 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
// later poll can only report expiry. Bounded by the gateway's
|
// later poll can only report expiry. Bounded by the gateway's
|
||||||
// own per-call budget, and the delay above stays cancellable, so
|
// own per-call budget, and the delay above stays cancellable, so
|
||||||
// the loop still stops promptly.
|
// the loop still stops promptly.
|
||||||
val result = withContext(NonCancellable) { gateway.pollLoginFlow(flow) }
|
val result = withContext(NonCancellable) { gateway.pollLoginFlow(flow, trust) }
|
||||||
when (result) {
|
when (result) {
|
||||||
is NextcloudLoginFlow.PollResult.Approved -> {
|
is NextcloudLoginFlow.PollResult.Approved -> {
|
||||||
// ⚠️ Uncancellable. The 200 that carried this password is
|
// ⚠️ Uncancellable. The 200 that carried this password is
|
||||||
@@ -698,47 +875,7 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
result.hostMismatch?.let { mismatch ->
|
result.hostMismatch?.let { mismatch ->
|
||||||
updateState { it.copy(originMismatch = mismatch) }
|
updateState { it.copy(originMismatch = mismatch) }
|
||||||
}
|
}
|
||||||
working(AddAccountMessage.Progress.ReadingLists)
|
discoverApproved(result.credentials.server)
|
||||||
val outcome = gateway.discover(
|
|
||||||
// The server the credentials were *issued by*, not the
|
|
||||||
// host the user typed — the two differ in exactly the
|
|
||||||
// host-mismatch case this flow already models, and
|
|
||||||
// getting it wrong burns the one-shot app password.
|
|
||||||
target = result.credentials.server.toString(),
|
|
||||||
credentials = CalDavGateway.Credentials(
|
|
||||||
username,
|
|
||||||
appPassword,
|
|
||||||
result.credentials.server,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
when (outcome) {
|
|
||||||
is CalDavDiscovery.Outcome.Found -> onDiscovered(outcome)
|
|
||||||
// ⚠️ Forward what actually happened. Reporting every
|
|
||||||
// outcome as NO_CALENDARS tells someone whose server
|
|
||||||
// named an unresolvable host that their account holds
|
|
||||||
// no task lists, which is both wrong and unactionable.
|
|
||||||
is CalDavDiscovery.Outcome.Failed -> backToAddress(outcome.cause)
|
|
||||||
is CalDavDiscovery.Outcome.NotCalDav -> backToAddress(outcome.cause)
|
|
||||||
// ⚠️ These two carry no Cause, so they used to land
|
|
||||||
// on "signed in, but no task lists" — said of a
|
|
||||||
// credential the server had just rejected. A 401 here
|
|
||||||
// is either a home set outside the domain the
|
|
||||||
// credential is scoped to, which retrying cannot fix
|
|
||||||
// and which only mints a second password, or the
|
|
||||||
// server having a moment.
|
|
||||||
is CalDavDiscovery.Outcome.NeedsAuthentication -> {
|
|
||||||
hostsNeedingAuth = outcome.hosts
|
|
||||||
val stranger = outsideCredentialScope(outcome.hosts)
|
|
||||||
if (stranger != null) {
|
|
||||||
fatal(AddAccountMessage.OutsideCredentialScope(stranger))
|
|
||||||
} else {
|
|
||||||
backToAddress(CalDavDiscovery.Outcome.Cause.SERVER_ERROR)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
CalDavDiscovery.Outcome.Unauthenticated ->
|
|
||||||
backToAddress(CalDavDiscovery.Outcome.Cause.SERVER_ERROR)
|
|
||||||
}
|
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -771,6 +908,52 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Discovery with a password the login flow just minted, at the server that issued it. */
|
||||||
|
private suspend fun discoverApproved(server: HttpUrl) {
|
||||||
|
working(AddAccountMessage.Progress.ReadingLists)
|
||||||
|
val outcome = discoverTrusting(addressStep(typedInput), AddAccountMessage.Progress.ReadingLists) {
|
||||||
|
gateway.discover(
|
||||||
|
// The server the credentials were *issued by*, not the
|
||||||
|
// host the user typed — the two differ in exactly the
|
||||||
|
// host-mismatch case this flow already models, and
|
||||||
|
// getting it wrong burns the one-shot app password.
|
||||||
|
target = server.toString(),
|
||||||
|
credentials = CalDavGateway.Credentials(username, appPassword, server),
|
||||||
|
trust = trust,
|
||||||
|
)
|
||||||
|
} ?: return
|
||||||
|
when (outcome) {
|
||||||
|
is CalDavDiscovery.Outcome.Found -> onDiscovered(outcome)
|
||||||
|
// ⚠️ Forward what actually happened. Reporting every
|
||||||
|
// outcome as NO_CALENDARS tells someone whose server
|
||||||
|
// named an unresolvable host that their account holds
|
||||||
|
// no task lists, which is both wrong and unactionable.
|
||||||
|
is CalDavDiscovery.Outcome.Failed -> backToAddress(outcome.cause)
|
||||||
|
is CalDavDiscovery.Outcome.NotCalDav -> backToAddress(outcome.cause)
|
||||||
|
// ⚠️ These two carry no Cause, so they used to land
|
||||||
|
// on "signed in, but no task lists" — said of a
|
||||||
|
// credential the server had just rejected. A 401 here
|
||||||
|
// is either a home set outside the domain the
|
||||||
|
// credential is scoped to, which retrying cannot fix
|
||||||
|
// and which only mints a second password, or the
|
||||||
|
// server having a moment.
|
||||||
|
is CalDavDiscovery.Outcome.NeedsAuthentication -> {
|
||||||
|
hostsNeedingAuth = outcome.hosts
|
||||||
|
val stranger = outsideCredentialScope(outcome.hosts)
|
||||||
|
if (stranger != null) {
|
||||||
|
fatal(AddAccountMessage.OutsideCredentialScope(stranger))
|
||||||
|
} else {
|
||||||
|
backToAddress(CalDavDiscovery.Outcome.Cause.SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
CalDavDiscovery.Outcome.Unauthenticated ->
|
||||||
|
backToAddress(CalDavDiscovery.Outcome.Cause.SERVER_ERROR)
|
||||||
|
|
||||||
|
is CalDavDiscovery.Outcome.UntrustedCertificate -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Another go after the browser sign-in failed.
|
* Another go after the browser sign-in failed.
|
||||||
*
|
*
|
||||||
@@ -803,7 +986,7 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
pollJob?.cancel()
|
pollJob?.cancel()
|
||||||
updateState {
|
updateState {
|
||||||
it.copy(
|
it.copy(
|
||||||
step = AddAccountStep.EnterCredentials(username = suggestedUsername, error = null),
|
step = AddAccountStep.EnterCredentials(username = prefilledUsername(), error = null),
|
||||||
openInBrowser = null,
|
openInBrowser = null,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -854,6 +1037,7 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
found = discovered,
|
found = discovered,
|
||||||
selected = chosen,
|
selected = chosen,
|
||||||
reauthenticating = reauthAccountId,
|
reauthenticating = reauthAccountId,
|
||||||
|
trust = trust,
|
||||||
)
|
)
|
||||||
}.getOrElse {
|
}.getOrElse {
|
||||||
// A constraint violation or an IO failure in DataStore must not
|
// A constraint violation or an IO failure in DataStore must not
|
||||||
@@ -916,7 +1100,17 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
// Back into the errand when there was one, so the steps can be re-read
|
// Back into the errand when there was one, so the steps can be re-read
|
||||||
// without starting the flow again — that is the screen people return to.
|
// without starting the flow again — that is the screen people return to.
|
||||||
is AddAccountStep.EnterAddress -> {
|
is AddAccountStep.EnterAddress -> {
|
||||||
updateState { it.copy(step = providerOrSetupStep(), fatal = null) }
|
val email = fallbackEmail
|
||||||
|
if (email != null) {
|
||||||
|
clearFallback()
|
||||||
|
addressInput = email
|
||||||
|
typedInput = email
|
||||||
|
updateState {
|
||||||
|
it.copy(step = addressStep(email), fatal = null, quirk = quirkFor(email))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
updateState { it.copy(step = providerOrSetupStep(), fatal = null) }
|
||||||
|
}
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -950,6 +1144,19 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
is AddAccountStep.ConfirmCleartext -> {
|
||||||
|
updateState { it.copy(step = addressStep(typedInput), fatal = null) }
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
is AddAccountStep.TrustCertificate -> {
|
||||||
|
val prompt = trustPrompt
|
||||||
|
trustPrompt = null
|
||||||
|
prompt?.answer?.cancel()
|
||||||
|
updateState { it.copy(step = prompt?.back ?: addressStep(typedInput), fatal = null) }
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
else -> false
|
else -> false
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -990,6 +1197,14 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
hostsNeedingAuth = emptyList()
|
hostsNeedingAuth = emptyList()
|
||||||
reauthAccountId = null
|
reauthAccountId = null
|
||||||
suggestedUsername = ""
|
suggestedUsername = ""
|
||||||
|
fallbackEmail = null
|
||||||
|
trustLoad?.cancel()
|
||||||
|
trustLoad = null
|
||||||
|
trust = ServerTrust.DEFAULT
|
||||||
|
trustAddress = null
|
||||||
|
inheritedPins = false
|
||||||
|
trustPrompt?.answer?.cancel()
|
||||||
|
trustPrompt = null
|
||||||
current = AddAccountUiState()
|
current = AddAccountUiState()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1013,9 +1228,10 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
private fun discardMintedPassword() {
|
private fun discardMintedPassword() {
|
||||||
val credentials = minted ?: return
|
val credentials = minted ?: return
|
||||||
minted = null
|
minted = null
|
||||||
|
val trust = trust
|
||||||
// The scope has no exception handler, so anything escaping here takes the
|
// The scope has no exception handler, so anything escaping here takes the
|
||||||
// app down — for a courtesy call whose failures are deliberately silent.
|
// app down — for a courtesy call whose failures are deliberately silent.
|
||||||
appScope.launch { runCatching { gateway.revokeIssuedAppPassword(credentials) } }
|
appScope.launch { runCatching { gateway.revokeIssuedAppPassword(credentials, trust) } }
|
||||||
}
|
}
|
||||||
|
|
||||||
// -------------------------------------------------------- saved state
|
// -------------------------------------------------------- saved state
|
||||||
@@ -1040,6 +1256,8 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
// what deals with that on the next open. Recording them as
|
// what deals with that on the next open. Recording them as
|
||||||
// themselves would only mean deciding the same thing twice.
|
// themselves would only mean deciding the same thing twice.
|
||||||
is AddAccountStep.ConfirmBrowser, is AddAccountStep.WaitingForBrowser -> STEP_ADDRESS
|
is AddAccountStep.ConfirmBrowser, is AddAccountStep.WaitingForBrowser -> STEP_ADDRESS
|
||||||
|
// Both re-ask on the next submit, which is where a restore puts them.
|
||||||
|
is AddAccountStep.ConfirmCleartext, is AddAccountStep.TrustCertificate -> STEP_ADDRESS
|
||||||
is AddAccountStep.Working -> STEP_WORKING
|
is AddAccountStep.Working -> STEP_WORKING
|
||||||
is AddAccountStep.ChooseLists -> STEP_LISTS
|
is AddAccountStep.ChooseLists -> STEP_LISTS
|
||||||
is AddAccountStep.Summary -> STEP_SUMMARY
|
is AddAccountStep.Summary -> STEP_SUMMARY
|
||||||
@@ -1119,8 +1337,7 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
reauthenticating = reauthAccountId != null,
|
reauthenticating = reauthAccountId != null,
|
||||||
// Derived rather than saved: it is a pure function of the choice and the
|
// Derived rather than saved: it is a pure function of the choice and the
|
||||||
// address, both of which are.
|
// address, both of which are.
|
||||||
quirk = choice?.provider?.let(ServerQuirk::forProvider)
|
quirk = quirkFor(addressInput),
|
||||||
?: ServerQuirk.forInput(addressInput),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1146,10 +1363,13 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
)
|
)
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
val credentials = CalDavGateway.Credentials(username, appPassword, root)
|
val credentials = CalDavGateway.Credentials(username, appPassword, root)
|
||||||
when (val outcome = gateway.discover(target, credentials)) {
|
val outcome = discoverTrusting(addressStep(addressInput), AddAccountMessage.Progress.ReadingLists) {
|
||||||
|
gateway.discover(target, credentials, trust)
|
||||||
|
} ?: return@launch
|
||||||
|
when (outcome) {
|
||||||
is CalDavDiscovery.Outcome.Found -> onDiscovered(outcome, selection)
|
is CalDavDiscovery.Outcome.Found -> onDiscovered(outcome, selection)
|
||||||
is CalDavDiscovery.Outcome.NotCalDav -> backToAddress(outcome.cause)
|
is CalDavDiscovery.Outcome.NotCalDav -> backToAddressOrServer(outcome.cause)
|
||||||
is CalDavDiscovery.Outcome.Failed -> backToAddress(outcome.cause)
|
is CalDavDiscovery.Outcome.Failed -> backToAddressOrServer(outcome.cause)
|
||||||
// The credential we were holding is no longer accepted, which on
|
// The credential we were holding is no longer accepted, which on
|
||||||
// this path is indistinguishable from never having had one.
|
// this path is indistinguishable from never having had one.
|
||||||
is CalDavDiscovery.Outcome.NeedsAuthentication -> {
|
is CalDavDiscovery.Outcome.NeedsAuthentication -> {
|
||||||
@@ -1157,6 +1377,7 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
credentialsRejected()
|
credentialsRejected()
|
||||||
}
|
}
|
||||||
CalDavDiscovery.Outcome.Unauthenticated -> credentialsRejected()
|
CalDavDiscovery.Outcome.Unauthenticated -> credentialsRejected()
|
||||||
|
is CalDavDiscovery.Outcome.UntrustedCertificate -> Unit
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1250,6 +1471,7 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
choice = choice ?: ProviderChoice.OtherServer,
|
choice = choice ?: ProviderChoice.OtherServer,
|
||||||
input = input,
|
input = input,
|
||||||
error = error,
|
error = error,
|
||||||
|
manualServer = fallbackEmail != null,
|
||||||
)
|
)
|
||||||
|
|
||||||
/** What was actually set up, named the way the accounts list will name it. */
|
/** What was actually set up, named the way the accounts list will name it. */
|
||||||
@@ -1286,12 +1508,13 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
updateState { it.copy(step = transform(step)) }
|
updateState { it.copy(step = transform(step)) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The chosen service's quirk, else the one the typed host implies. */
|
||||||
|
private fun quirkFor(input: String): ServerQuirk? =
|
||||||
|
choice?.provider?.let(ServerQuirk::forProvider) ?: ServerQuirk.forInput(input)
|
||||||
|
|
||||||
/** The provider-specific reason a correct-looking password gets rejected. */
|
/** The provider-specific reason a correct-looking password gets rejected. */
|
||||||
private fun quirkHint(): AddAccountMessage? =
|
private fun quirkHint(): AddAccountMessage? =
|
||||||
when (
|
when (val quirk = quirkFor(typedInput)) {
|
||||||
val quirk = choice?.provider?.let(ServerQuirk::forProvider)
|
|
||||||
?: ServerQuirk.forInput(typedInput)
|
|
||||||
) {
|
|
||||||
ServerQuirk.FASTMAIL_APP_PASSWORD,
|
ServerQuirk.FASTMAIL_APP_PASSWORD,
|
||||||
ServerQuirk.ICLOUD_APP_SPECIFIC_PASSWORD,
|
ServerQuirk.ICLOUD_APP_SPECIFIC_PASSWORD,
|
||||||
-> AddAccountMessage.Quirk(quirk)
|
-> AddAccountMessage.Quirk(quirk)
|
||||||
@@ -1330,10 +1553,14 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The port is part of the name: two servers on one host are two accounts (#105).
|
||||||
private fun accountName(): String =
|
private fun accountName(): String =
|
||||||
username.takeIf { it.isNotBlank() }?.let { "$it@${serverRoot?.host.orEmpty()}" }
|
username.takeIf { it.isNotBlank() }?.let { "$it@${serverRoot?.authority().orEmpty()}" }
|
||||||
?: typedInput
|
?: typedInput
|
||||||
|
|
||||||
|
private fun HttpUrl.authority(): String =
|
||||||
|
if (port == HttpUrl.defaultPort(scheme)) host else "$host:$port"
|
||||||
|
|
||||||
internal companion object {
|
internal companion object {
|
||||||
const val POLL_INTERVAL_MILLIS = 2_000L
|
const val POLL_INTERVAL_MILLIS = 2_000L
|
||||||
|
|
||||||
@@ -1377,6 +1604,23 @@ class AddAccountViewModel @Inject constructor(
|
|||||||
const val KEY_SUMMARY_LISTS = "add_account.summary_lists"
|
const val KEY_SUMMARY_LISTS = "add_account.summary_lists"
|
||||||
const val KEY_REAUTH_ACCOUNT = "add_account.reauth_account"
|
const val KEY_REAUTH_ACCOUNT = "add_account.reauth_account"
|
||||||
const val KEY_SUGGESTED_USERNAME = "add_account.suggested_username"
|
const val KEY_SUGGESTED_USERNAME = "add_account.suggested_username"
|
||||||
|
const val KEY_FALLBACK_EMAIL = "add_account.fallback_email"
|
||||||
|
const val KEY_TRUSTED_CERTIFICATES = "add_account.trusted_certificates"
|
||||||
|
const val KEY_CLEARTEXT = "add_account.cleartext"
|
||||||
|
const val KEY_TRUST_ADDRESS = "add_account.trust_address"
|
||||||
|
const val KEY_INHERITED_PINS = "add_account.inherited_pins"
|
||||||
|
|
||||||
|
val TRUST_KEYS = ServerTrustKeys(KEY_TRUSTED_CERTIFICATES, KEY_CLEARTEXT)
|
||||||
|
|
||||||
|
/** What sends an email to the server field: no CalDAV on its domain, or nothing answering for it. */
|
||||||
|
val NO_SERVER_FOUND = setOf(
|
||||||
|
CalDavDiscovery.Outcome.Cause.NOT_A_DAV_SERVER,
|
||||||
|
CalDavDiscovery.Outcome.Cause.NO_CALENDAR_SUPPORT,
|
||||||
|
CalDavDiscovery.Outcome.Cause.UNREACHABLE,
|
||||||
|
// The domain's own host would not set up TLS: usually its website,
|
||||||
|
// not a CalDAV server, so the server field is the way on.
|
||||||
|
CalDavDiscovery.Outcome.Cause.TLS,
|
||||||
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* What to type for a server, from the principal an account stored.
|
* What to type for a server, from the principal an account stored.
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ import de.jeanlucmakiola.agendula.R
|
|||||||
*/
|
*/
|
||||||
@Composable
|
@Composable
|
||||||
internal fun AddressStep(step: AddAccountStep.EnterAddress, viewModel: AddAccountViewModel) {
|
internal fun AddressStep(step: AddAccountStep.EnterAddress, viewModel: AddAccountViewModel) {
|
||||||
val hosted = step.choice.provider?.hosted == true
|
val hosted = step.asksForEmail
|
||||||
Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
|
Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
|
||||||
FieldRow(
|
FieldRow(
|
||||||
label = if (hosted) {
|
label = if (hosted) {
|
||||||
@@ -30,7 +30,7 @@ internal fun AddressStep(step: AddAccountStep.EnterAddress, viewModel: AddAccoun
|
|||||||
},
|
},
|
||||||
value = step.input,
|
value = step.input,
|
||||||
onValueChange = viewModel::onAddressChanged,
|
onValueChange = viewModel::onAddressChanged,
|
||||||
placeholder = step.choice.provider?.primaryDomain?.let { "you@$it" }
|
placeholder = step.choice.provider?.primaryDomain?.takeIf { hosted }?.let { "you@$it" }
|
||||||
?: stringResource(R.string.add_account_server_hint),
|
?: stringResource(R.string.add_account_server_hint),
|
||||||
error = step.error?.let { stringResource(it.message) },
|
error = step.error?.let { stringResource(it.message) },
|
||||||
// An email address is still typed with the URI keyboard: it is the
|
// An email address is still typed with the URI keyboard: it is the
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
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))
|
||||||
|
}
|
||||||
@@ -31,8 +31,8 @@ internal fun AccountSections(
|
|||||||
// Which account the detail screen is showing; the section alone cannot say.
|
// Which account the detail screen is showing; the section alone cannot say.
|
||||||
var openAccount by rememberSaveable(initialAccountId) { mutableStateOf(initialAccountId) }
|
var openAccount by rememberSaveable(initialAccountId) { mutableStateOf(initialAccountId) }
|
||||||
|
|
||||||
// Accounts stays composed under Add account, for the same reason Storage
|
// Accounts stays composed under Add account, for the same reason Backup
|
||||||
// stays composed under Export: the deeper screen slides over it.
|
// stays composed under export and import: the deeper screen slides over it.
|
||||||
val accountsOpen = section == SettingsSection.Accounts ||
|
val accountsOpen = section == SettingsSection.Accounts ||
|
||||||
section?.parent == SettingsSection.Accounts
|
section?.parent == SettingsSection.Accounts
|
||||||
SlideInSection(visible = accountsOpen) {
|
SlideInSection(visible = accountsOpen) {
|
||||||
@@ -50,9 +50,11 @@ internal fun AccountSections(
|
|||||||
onOpenStorage = { onSection(SettingsSection.Storage) },
|
onOpenStorage = { onSection(SettingsSection.Storage) },
|
||||||
onBack = { onSection(null) },
|
onBack = { onSection(null) },
|
||||||
viewModel = accountsViewModel,
|
viewModel = accountsViewModel,
|
||||||
|
visible = accountsOpen,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
SlideInSection(visible = section == SettingsSection.Account) {
|
val accountOpen = section == SettingsSection.Account
|
||||||
|
SlideInSection(visible = accountOpen) {
|
||||||
openAccount?.let { id ->
|
openAccount?.let { id ->
|
||||||
AccountDetailScreen(
|
AccountDetailScreen(
|
||||||
accountId = id,
|
accountId = id,
|
||||||
@@ -61,6 +63,7 @@ internal fun AccountSections(
|
|||||||
onSignInAgain = signInAgain,
|
onSignInAgain = signInAgain,
|
||||||
onOpenStorage = { onSection(SettingsSection.Storage) },
|
onOpenStorage = { onSection(SettingsSection.Storage) },
|
||||||
viewModel = accountsViewModel,
|
viewModel = accountsViewModel,
|
||||||
|
visible = accountOpen,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,11 +5,14 @@
|
|||||||
default trust anchors. That breaks exactly the self-hosting audience this app
|
default trust anchors. That breaks exactly the self-hosting audience this app
|
||||||
is for, so they are added back here.
|
is for, so they are added back here.
|
||||||
|
|
||||||
Cleartext stays off. It has been the default since API 28, and CalDavDiscovery
|
Cleartext is permitted here and gated in code instead, per account: every
|
||||||
refuses a typed http:// address for the same reason: credentials are never
|
client CalDavHttp builds leaves ConnectionSpec.CLEARTEXT out unless the user
|
||||||
sent over an unencrypted connection. Any escape hatch has to be a narrow,
|
opted that account into plain http behind an explicit warning, so OkHttp
|
||||||
warned, per-account opt-in — Play's User Data policy requires modern
|
itself refuses an http:// URL for everyone else. This file cannot express a
|
||||||
cryptography in transit — and this file is not the place for it.
|
per-account choice, only a per-host one, and the hosts are the user's.
|
||||||
|
|
||||||
|
⚠️ That makes CalDavHttp the only gate. A client built any other way would
|
||||||
|
speak http silently, so HttpClientConstructionTest fails the build on one.
|
||||||
|
|
||||||
⚠️ KNOWN TRADE-OFF, and it is the widest form of this. base-config applies to
|
⚠️ KNOWN TRADE-OFF, and it is the widest form of this. base-config applies to
|
||||||
*all* traffic, so any CA in the user store — a corporate MDM profile, a "free
|
*all* traffic, so any CA in the user store — a corporate MDM profile, a "free
|
||||||
@@ -25,7 +28,7 @@
|
|||||||
sit alongside it.
|
sit alongside it.
|
||||||
-->
|
-->
|
||||||
<network-security-config>
|
<network-security-config>
|
||||||
<base-config cleartextTrafficPermitted="false">
|
<base-config cleartextTrafficPermitted="true">
|
||||||
<trust-anchors>
|
<trust-anchors>
|
||||||
<certificates src="system" />
|
<certificates src="system" />
|
||||||
<certificates src="user" />
|
<certificates src="user" />
|
||||||
|
|||||||
@@ -9,13 +9,26 @@
|
|||||||
selected External mode. Both are dangerous-level.
|
selected External mode. Both are dangerous-level.
|
||||||
|
|
||||||
StorageMode.OWN needs nothing here: it is a Room database in our own data
|
StorageMode.OWN needs nothing here: it is a Room database in our own data
|
||||||
directory. Agendula publishes no ContentProvider and declares no
|
directory. -->
|
||||||
permissions of its own. -->
|
|
||||||
<uses-permission android:name="org.dmfs.permission.READ_TASKS" />
|
<uses-permission android:name="org.dmfs.permission.READ_TASKS" />
|
||||||
<uses-permission android:name="org.dmfs.permission.WRITE_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.READ_TASKS" />
|
||||||
<uses-permission android:name="org.tasks.permission.WRITE_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" />
|
||||||
|
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||||
<!-- Exact due-time reminders. User-granted: USE_EXACT_ALARM is reserved for
|
<!-- Exact due-time reminders. User-granted: USE_EXACT_ALARM is reserved for
|
||||||
@@ -37,6 +50,7 @@
|
|||||||
<application
|
<application
|
||||||
android:name=".AgendulaApp"
|
android:name=".AgendulaApp"
|
||||||
android:allowBackup="true"
|
android:allowBackup="true"
|
||||||
|
android:enableOnBackInvokedCallback="true"
|
||||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||||
android:fullBackupContent="@xml/backup_rules"
|
android:fullBackupContent="@xml/backup_rules"
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_launcher"
|
||||||
@@ -51,10 +65,8 @@
|
|||||||
android:exported="true"
|
android:exported="true"
|
||||||
android:launchMode="singleTop"
|
android:launchMode="singleTop"
|
||||||
android:windowSoftInputMode="adjustResize">
|
android:windowSoftInputMode="adjustResize">
|
||||||
<intent-filter>
|
<!-- MAIN/LAUNCHER lives on the two aliases below, so the launcher
|
||||||
<action android:name="android.intent.action.MAIN" />
|
name can be switched at runtime (#104). -->
|
||||||
<category android:name="android.intent.category.LAUNCHER" />
|
|
||||||
</intent-filter>
|
|
||||||
<!-- Shared text becomes a new task's title. -->
|
<!-- Shared text becomes a new task's title. -->
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.intent.action.SEND" />
|
<action android:name="android.intent.action.SEND" />
|
||||||
@@ -75,6 +87,32 @@
|
|||||||
<data android:mimeType="text/calendar" />
|
<data android:mimeType="text/calendar" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
</activity>
|
</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. -->
|
<!-- Quick Settings "New task" tile. Only the system QS host can bind it. -->
|
||||||
<service
|
<service
|
||||||
@@ -233,6 +271,16 @@
|
|||||||
</intent-filter>
|
</intent-filter>
|
||||||
</receiver>
|
</receiver>
|
||||||
|
|
||||||
|
<!-- The own store under the OpenTasks contract. Empty, and refusing
|
||||||
|
writes, while External mode is active. -->
|
||||||
|
<provider
|
||||||
|
android:name=".data.tasks.provider.AgendulaTaskProvider"
|
||||||
|
android:authorities="${applicationId}.tasks"
|
||||||
|
android:exported="true"
|
||||||
|
android:readPermission="${applicationId}.permission.READ_TASKS"
|
||||||
|
android:writePermission="${applicationId}.permission.WRITE_TASKS"
|
||||||
|
tools:ignore="SystemPermissionTypo" />
|
||||||
|
|
||||||
<!-- WorkManager's on-demand initialisation. Removing the default
|
<!-- WorkManager's on-demand initialisation. Removing the default
|
||||||
initializer is what lets AgendulaApp supply a HiltWorkerFactory, so
|
initializer is what lets AgendulaApp supply a HiltWorkerFactory, so
|
||||||
@HiltWorker workers can take injected dependencies. -->
|
@HiltWorker workers can take injected dependencies. -->
|
||||||
|
|||||||
@@ -9,13 +9,16 @@ import dagger.hilt.InstallIn
|
|||||||
import dagger.hilt.android.EntryPointAccessors
|
import dagger.hilt.android.EntryPointAccessors
|
||||||
import dagger.hilt.android.HiltAndroidApp
|
import dagger.hilt.android.HiltAndroidApp
|
||||||
import dagger.hilt.components.SingletonComponent
|
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.ApplicationScope
|
||||||
import de.jeanlucmakiola.agendula.data.di.ChannelRefresher
|
import de.jeanlucmakiola.agendula.data.di.ChannelRefresher
|
||||||
import de.jeanlucmakiola.agendula.data.reminders.ReminderMaintenanceWorker
|
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.ReminderScheduler
|
||||||
import de.jeanlucmakiola.agendula.data.reminders.TaskNotifier
|
import de.jeanlucmakiola.agendula.data.reminders.TaskNotifier
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.StartupGate
|
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.data.tasks.room.DatabaseCheckpoint
|
||||||
import de.jeanlucmakiola.agendula.widget.TaskWidgetUpdater
|
import de.jeanlucmakiola.agendula.widget.TaskWidgetUpdater
|
||||||
import de.jeanlucmakiola.floret.crash.CrashConfig
|
import de.jeanlucmakiola.floret.crash.CrashConfig
|
||||||
@@ -64,17 +67,15 @@ class AgendulaApp : Application(), Configuration.Provider {
|
|||||||
// v0.3.x install's tasks, both before anything reads a store.
|
// v0.3.x install's tasks, both before anything reads a store.
|
||||||
val startupGate = entryPoint.startupGate()
|
val startupGate = entryPoint.startupGate()
|
||||||
val scope = entryPoint.applicationScope()
|
val scope = entryPoint.applicationScope()
|
||||||
// An alarm is armed off whichever store was active when it was scheduled,
|
// A switch rebuilds the alarms through ReminderRefresher, which hears it
|
||||||
// so a switch has to rebuild the set. Armed only once startup's own
|
// as a store change. Channels only once startup's own null -> stored
|
||||||
// null -> stored transition is past, which the launch sync below covers.
|
// transition is past, which the launch sync below covers.
|
||||||
val started = AtomicBoolean(false)
|
val started = AtomicBoolean(false)
|
||||||
entryPoint.providerResolver().onModeChanged {
|
entryPoint.providerResolver().onModeChanged {
|
||||||
if (started.get()) {
|
if (started.get()) runCatching { entryPoint.taskNotifier().refreshChannel() }
|
||||||
scope.launch { runCatching { scheduler.sync() } }
|
|
||||||
runCatching { entryPoint.taskNotifier().refreshChannel() }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
startupGate.start()
|
startupGate.start()
|
||||||
|
entryPoint.autoBackupScheduler().start()
|
||||||
refreshNotificationChannels()
|
refreshNotificationChannels()
|
||||||
ProcessLifecycleOwner.get().lifecycle.addObserver(entryPoint.databaseCheckpoint())
|
ProcessLifecycleOwner.get().lifecycle.addObserver(entryPoint.databaseCheckpoint())
|
||||||
scope.launch {
|
scope.launch {
|
||||||
@@ -87,6 +88,8 @@ class AgendulaApp : Application(), Configuration.Provider {
|
|||||||
scheduler.sync()
|
scheduler.sync()
|
||||||
}
|
}
|
||||||
runCatching { entryPoint.taskWidgetUpdater().start() }
|
runCatching { entryPoint.taskWidgetUpdater().start() }
|
||||||
|
runCatching { entryPoint.reminderRefresher().start() }
|
||||||
|
runCatching { entryPoint.providerSnapshotSource().start() }
|
||||||
runCatching { ReminderMaintenanceWorker.schedule(this@AgendulaApp) }
|
runCatching { ReminderMaintenanceWorker.schedule(this@AgendulaApp) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -122,5 +125,8 @@ class AgendulaApp : Application(), Configuration.Provider {
|
|||||||
fun taskNotifier(): TaskNotifier
|
fun taskNotifier(): TaskNotifier
|
||||||
fun channelRefreshers(): Set<@JvmSuppressWildcards ChannelRefresher>
|
fun channelRefreshers(): Set<@JvmSuppressWildcards ChannelRefresher>
|
||||||
fun taskWidgetUpdater(): TaskWidgetUpdater
|
fun taskWidgetUpdater(): TaskWidgetUpdater
|
||||||
|
fun reminderRefresher(): ReminderRefresher
|
||||||
|
fun providerSnapshotSource(): ProviderSnapshotSource
|
||||||
|
fun autoBackupScheduler(): AutoBackupScheduler
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -16,6 +16,7 @@ import androidx.compose.runtime.setValue
|
|||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.core.net.toUri
|
import androidx.core.net.toUri
|
||||||
|
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||||
import de.jeanlucmakiola.agendula.data.prefs.is24Hour
|
import de.jeanlucmakiola.agendula.data.prefs.is24Hour
|
||||||
import de.jeanlucmakiola.agendula.ui.common.LocalFirstDayOfWeek
|
import de.jeanlucmakiola.agendula.ui.common.LocalFirstDayOfWeek
|
||||||
import de.jeanlucmakiola.agendula.ui.common.LocalUse24HourFormat
|
import de.jeanlucmakiola.agendula.ui.common.LocalUse24HourFormat
|
||||||
@@ -26,17 +27,20 @@ import androidx.lifecycle.lifecycleScope
|
|||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import de.jeanlucmakiola.agendula.data.di.LaunchHook
|
import de.jeanlucmakiola.agendula.data.di.LaunchHook
|
||||||
import de.jeanlucmakiola.agendula.domain.SmartList
|
import de.jeanlucmakiola.agendula.domain.SmartList
|
||||||
|
import de.jeanlucmakiola.agendula.domain.smartListNamed
|
||||||
import de.jeanlucmakiola.agendula.ui.imports.importIntentUri
|
import de.jeanlucmakiola.agendula.ui.imports.importIntentUri
|
||||||
import de.jeanlucmakiola.agendula.ui.navigation.AppShortcuts
|
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.RootScreen
|
||||||
import de.jeanlucmakiola.agendula.ui.crash.CrashReportActivity
|
import de.jeanlucmakiola.agendula.ui.crash.CrashReportActivity
|
||||||
import de.jeanlucmakiola.agendula.ui.navigation.NavRequest
|
import de.jeanlucmakiola.agendula.ui.navigation.NavRequest
|
||||||
import de.jeanlucmakiola.agendula.ui.settings.SettingsViewModel
|
import de.jeanlucmakiola.agendula.ui.settings.SettingsViewModel
|
||||||
import de.jeanlucmakiola.agendula.ui.theme.AgendulaTheme
|
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.CrashReportDialog
|
||||||
import de.jeanlucmakiola.floret.crash.CrashReporter
|
import de.jeanlucmakiola.floret.crash.CrashReporter
|
||||||
import de.jeanlucmakiola.floret.crash.submitCrashReport
|
import de.jeanlucmakiola.floret.crash.submitCrashReport
|
||||||
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@@ -50,6 +54,8 @@ class MainActivity : ComponentActivity() {
|
|||||||
|
|
||||||
@Inject lateinit var launchHooks: Set<@JvmSuppressWildcards LaunchHook>
|
@Inject lateinit var launchHooks: Set<@JvmSuppressWildcards LaunchHook>
|
||||||
|
|
||||||
|
@Inject lateinit var settingsPrefs: SettingsPrefs
|
||||||
|
|
||||||
// A captured crash report awaiting the user's decision, surfaced as a dialog
|
// 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
|
// over the app on the next launch (the single-crash path). A startup
|
||||||
// crash-loop is handled out of band, before setContent — see below.
|
// crash-loop is handled out of band, before setContent — see below.
|
||||||
@@ -73,6 +79,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
enableEdgeToEdge()
|
enableEdgeToEdge()
|
||||||
AppShortcuts.publish(this)
|
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
|
// 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.
|
// 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
|
val fromHistory = intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0
|
||||||
@@ -88,15 +101,15 @@ class MainActivity : ComponentActivity() {
|
|||||||
setContent {
|
setContent {
|
||||||
val settingsViewModel: SettingsViewModel = hiltViewModel()
|
val settingsViewModel: SettingsViewModel = hiltViewModel()
|
||||||
val ui by settingsViewModel.state.collectAsStateWithLifecycle()
|
val ui by settingsViewModel.state.collectAsStateWithLifecycle()
|
||||||
val darkTheme = when (ui.settings.themeMode) {
|
val darkTheme = ui.settings.themeMode.isDark(isSystemInDarkTheme())
|
||||||
ThemeMode.SYSTEM -> isSystemInDarkTheme()
|
|
||||||
ThemeMode.LIGHT -> false
|
|
||||||
ThemeMode.DARK -> true
|
|
||||||
}
|
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val use24Hour = ui.settings.timeFormat.is24Hour(DateFormat.is24HourFormat(context))
|
val use24Hour = ui.settings.timeFormat.is24Hour(DateFormat.is24HourFormat(context))
|
||||||
val firstDayOfWeek = ui.settings.weekStart ?: localeFirstDayOfWeek()
|
val firstDayOfWeek = ui.settings.weekStart ?: localeFirstDayOfWeek()
|
||||||
AgendulaTheme(darkTheme = darkTheme, dynamicColor = ui.settings.dynamicColor) {
|
AgendulaTheme(
|
||||||
|
darkTheme = darkTheme,
|
||||||
|
dynamicColor = ui.settings.dynamicColor,
|
||||||
|
pureBlack = ui.settings.themeMode.isPureBlack,
|
||||||
|
) {
|
||||||
CompositionLocalProvider(
|
CompositionLocalProvider(
|
||||||
LocalUse24HourFormat provides use24Hour,
|
LocalUse24HourFormat provides use24Hour,
|
||||||
LocalFirstDayOfWeek provides firstDayOfWeek,
|
LocalFirstDayOfWeek provides firstDayOfWeek,
|
||||||
@@ -105,6 +118,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
modifier = Modifier.fillMaxSize(),
|
modifier = Modifier.fillMaxSize(),
|
||||||
navRequest = navRequest,
|
navRequest = navRequest,
|
||||||
onNavRequestConsumed = { navRequest = null },
|
onNavRequestConsumed = { navRequest = null },
|
||||||
|
onReturnHome = ::finish,
|
||||||
)
|
)
|
||||||
pendingCrashReport?.let { report ->
|
pendingCrashReport?.let { report ->
|
||||||
CrashReportDialog(
|
CrashReportDialog(
|
||||||
@@ -142,6 +156,7 @@ class MainActivity : ComponentActivity() {
|
|||||||
const val EXTRA_TASK_ID = "de.jeanlucmakiola.agendula.extra.TASK_ID"
|
const val EXTRA_TASK_ID = "de.jeanlucmakiola.agendula.extra.TASK_ID"
|
||||||
const val EXTRA_OCCURRENCE_START = "de.jeanlucmakiola.agendula.extra.OCCURRENCE_START"
|
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 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. */
|
/** 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 EXTRA_SIGN_IN_ACCOUNT_ID = "de.jeanlucmakiola.agendula.extra.SIGN_IN_ACCOUNT_ID"
|
||||||
@@ -153,7 +168,9 @@ class MainActivity : ComponentActivity() {
|
|||||||
private const val EXTRA_FILTER_ID = "de.jeanlucmakiola.agendula.extra.FILTER_ID"
|
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_SMART_LIST = "de.jeanlucmakiola.agendula.extra.SMART_LIST"
|
||||||
private const val EXTRA_LIST_ID = "de.jeanlucmakiola.agendula.extra.LIST_ID"
|
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_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 SHARED_TITLE_LIMIT = 500
|
||||||
private const val NO_OCCURRENCE = -1L
|
private const val NO_OCCURRENCE = -1L
|
||||||
|
|
||||||
@@ -161,10 +178,16 @@ class MainActivity : ComponentActivity() {
|
|||||||
* Opens a task's detail (reminder taps). [occurrenceStart] (epoch millis)
|
* Opens a task's detail (reminder taps). [occurrenceStart] (epoch millis)
|
||||||
* picks the occurrence of a recurring task.
|
* picks the occurrence of a recurring task.
|
||||||
*/
|
*/
|
||||||
fun taskIntent(context: Context, taskId: Long, occurrenceStart: Long? = null): Intent =
|
fun taskIntent(
|
||||||
|
context: Context,
|
||||||
|
taskId: Long,
|
||||||
|
occurrenceStart: Long? = null,
|
||||||
|
returnHome: Boolean = false,
|
||||||
|
): Intent =
|
||||||
Intent(context, MainActivity::class.java).apply {
|
Intent(context, MainActivity::class.java).apply {
|
||||||
putExtra(EXTRA_TASK_ID, taskId)
|
putExtra(EXTRA_TASK_ID, taskId)
|
||||||
putExtra(EXTRA_OCCURRENCE_START, occurrenceStart ?: NO_OCCURRENCE)
|
putExtra(EXTRA_OCCURRENCE_START, occurrenceStart ?: NO_OCCURRENCE)
|
||||||
|
putExtra(EXTRA_RETURN_HOME, returnHome)
|
||||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -174,15 +197,34 @@ class MainActivity : ComponentActivity() {
|
|||||||
.putExtra(EXTRA_OPEN_ACCOUNTS, true)
|
.putExtra(EXTRA_OPEN_ACCOUNTS, true)
|
||||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
.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)
|
||||||
|
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The launcher shortcut's, Quick Settings tile's and a widget's "New
|
* The launcher shortcut's, Quick Settings tile's and a widget's "New
|
||||||
* task". [listId] preset the list when it names exactly one; the data
|
* task". [listId] preset the list when it names exactly one, [filterId]
|
||||||
* URI keeps each widget's PendingIntent apart from the others.
|
* 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): Intent =
|
fun newTaskIntent(
|
||||||
Intent(ACTION_NEW_TASK, listId?.let { "agendula://newtask/$it".toUri() }, context, MainActivity::class.java)
|
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_PRESET_LIST_ID, listId ?: -1L)
|
||||||
|
.putExtra(EXTRA_SMART_LIST, smartList?.name)
|
||||||
|
.putExtra(EXTRA_FILTER_ID, filterId ?: -1L)
|
||||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
}
|
||||||
|
|
||||||
fun todayIntent(context: Context): Intent =
|
fun todayIntent(context: Context): Intent =
|
||||||
Intent(ACTION_TODAY, null, context, MainActivity::class.java)
|
Intent(ACTION_TODAY, null, context, MainActivity::class.java)
|
||||||
@@ -216,10 +258,15 @@ class MainActivity : ComponentActivity() {
|
|||||||
when (intent.action) {
|
when (intent.action) {
|
||||||
ACTION_NEW_TASK -> return NavRequest.NewTask(
|
ACTION_NEW_TASK -> return NavRequest.NewTask(
|
||||||
listId = intent.getLongExtra(EXTRA_PRESET_LIST_ID, -1L).takeIf { it > 0L },
|
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_TODAY -> return NavRequest.OpenSmart(SmartList.TODAY)
|
ACTION_TODAY -> return NavRequest.OpenSmart(SmartList.TODAY)
|
||||||
ACTION_OPEN_SMART -> intent.getStringExtra(EXTRA_SMART_LIST)
|
ACTION_OPEN_BACKUP -> return NavRequest.OpenBackup
|
||||||
?.let { name -> SmartList.entries.firstOrNull { it.name == name } }
|
ACTION_OPEN_SMART -> smartListNamed(intent.getStringExtra(EXTRA_SMART_LIST))
|
||||||
?.let { return NavRequest.OpenSmart(it) }
|
?.let { return NavRequest.OpenSmart(it) }
|
||||||
ACTION_OPEN_LIST -> intent.getLongExtra(EXTRA_LIST_ID, -1L).takeIf { it > 0L }
|
ACTION_OPEN_LIST -> intent.getLongExtra(EXTRA_LIST_ID, -1L).takeIf { it > 0L }
|
||||||
?.let { return NavRequest.OpenList(it) }
|
?.let { return NavRequest.OpenList(it) }
|
||||||
@@ -230,12 +277,12 @@ class MainActivity : ComponentActivity() {
|
|||||||
if (intent.action == Intent.ACTION_SEND && intent.type?.startsWith("text/plain") == true) {
|
if (intent.action == Intent.ACTION_SEND && intent.type?.startsWith("text/plain") == true) {
|
||||||
val shared = intent.getStringExtra(Intent.EXTRA_SUBJECT)?.takeIf { it.isNotBlank() }
|
val shared = intent.getStringExtra(Intent.EXTRA_SUBJECT)?.takeIf { it.isNotBlank() }
|
||||||
?: intent.getStringExtra(Intent.EXTRA_TEXT)
|
?: intent.getStringExtra(Intent.EXTRA_TEXT)
|
||||||
return NavRequest.NewTask(shared?.trim()?.take(SHARED_TITLE_LIMIT))
|
return NavRequest.NewTask(shared?.trim()?.take(SHARED_TITLE_LIMIT), returnHome = true)
|
||||||
}
|
}
|
||||||
val taskId = intent.getLongExtra(EXTRA_TASK_ID, -1L).takeIf { it > 0L } ?: return null
|
val taskId = intent.getLongExtra(EXTRA_TASK_ID, -1L).takeIf { it > 0L } ?: return null
|
||||||
val occurrence = intent.getLongExtra(EXTRA_OCCURRENCE_START, NO_OCCURRENCE)
|
val occurrence = intent.getLongExtra(EXTRA_OCCURRENCE_START, NO_OCCURRENCE)
|
||||||
.takeIf { it != NO_OCCURRENCE }
|
.takeIf { it != NO_OCCURRENCE }
|
||||||
return NavRequest.OpenTask(taskId, occurrence)
|
return NavRequest.OpenTask(taskId, occurrence, intent.getBooleanExtra(EXTRA_RETURN_HOME, false))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
@@ -89,7 +89,7 @@ object DataProvideModule {
|
|||||||
// backed-up `.db` does not. The backup rules carry all three files and
|
// backed-up `.db` does not. The backup rules carry all three files and
|
||||||
// the app checkpoints on ON_STOP.
|
// the app checkpoints on ON_STOP.
|
||||||
.setJournalMode(RoomDatabase.JournalMode.WRITE_AHEAD_LOGGING)
|
.setJournalMode(RoomDatabase.JournalMode.WRITE_AHEAD_LOGGING)
|
||||||
.addMigrations(TasksDatabase.MIGRATION_1_2)
|
.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()
|
.build()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.agendula.data.export
|
|||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
|
import android.provider.DocumentsContract
|
||||||
import androidx.documentfile.provider.DocumentFile
|
import androidx.documentfile.provider.DocumentFile
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
|
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
|
||||||
@@ -71,10 +72,8 @@ class ExportWriter @Inject constructor(
|
|||||||
*/
|
*/
|
||||||
suspend fun writeToTree(treeUri: Uri, documents: List<ExportDocument>): ExportResult =
|
suspend fun writeToTree(treeUri: Uri, documents: List<ExportDocument>): ExportResult =
|
||||||
withContext(io) {
|
withContext(io) {
|
||||||
|
val tree = openTree(treeUri)
|
||||||
runCatching {
|
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 }
|
val existing = tree.listFiles().associateBy { it.name }
|
||||||
|
|
||||||
documents.forEach { document ->
|
documents.forEach { document ->
|
||||||
@@ -83,7 +82,7 @@ class ExportWriter @Inject constructor(
|
|||||||
?: throw ExportFailedException(ExportFailure.CANNOT_CREATE_FILE)
|
?: throw ExportFailedException(ExportFailure.CANNOT_CREATE_FILE)
|
||||||
write(file.uri, document.content)
|
write(file.uri, document.content)
|
||||||
}
|
}
|
||||||
}.getOrElse { throw asExportFailure(it) }
|
}.getOrElse { throw failureIn(tree, it) }
|
||||||
ExportResult(documents.size, documents.map { it.fileName })
|
ExportResult(documents.size, documents.map { it.fileName })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,20 +94,150 @@ class ExportWriter @Inject constructor(
|
|||||||
*/
|
*/
|
||||||
suspend fun writeZip(target: Uri, documents: List<ExportDocument>): ExportResult =
|
suspend fun writeZip(target: Uri, documents: List<ExportDocument>): ExportResult =
|
||||||
withContext(io) {
|
withContext(io) {
|
||||||
runCatching {
|
runCatching { zipInto(target, documents) }.getOrElse { throw asExportFailure(it) }
|
||||||
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 })
|
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) {
|
private fun write(target: Uri, bytes: ByteArray) {
|
||||||
runCatching {
|
runCatching {
|
||||||
// "wt" truncates. Without it a shorter export leaves the tail of the
|
// "wt" truncates. Without it a shorter export leaves the tail of the
|
||||||
@@ -129,5 +258,9 @@ class ExportWriter @Inject constructor(
|
|||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
const val MIME_ICALENDAR = "text/calendar"
|
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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -38,6 +38,18 @@ internal object SavedFilterCodec {
|
|||||||
return updated.joinToString("\n")
|
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")
|
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 lines(raw: String?): List<String> = raw.orEmpty().split('\n').filter { it.isNotBlank() }
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package de.jeanlucmakiola.agendula.data.prefs
|
package de.jeanlucmakiola.agendula.data.prefs
|
||||||
|
|
||||||
import androidx.datastore.core.DataStore
|
import androidx.datastore.core.DataStore
|
||||||
|
import androidx.datastore.preferences.core.MutablePreferences
|
||||||
import androidx.datastore.preferences.core.Preferences
|
import androidx.datastore.preferences.core.Preferences
|
||||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||||
import androidx.datastore.preferences.core.edit
|
import androidx.datastore.preferences.core.edit
|
||||||
@@ -10,11 +11,28 @@ import androidx.datastore.preferences.core.stringPreferencesKey
|
|||||||
import androidx.datastore.preferences.core.stringSetPreferencesKey
|
import androidx.datastore.preferences.core.stringSetPreferencesKey
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.StorageMode
|
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.SavedFilter
|
||||||
|
import de.jeanlucmakiola.agendula.domain.newTaskDates
|
||||||
import de.jeanlucmakiola.agendula.domain.Task
|
import de.jeanlucmakiola.agendula.domain.Task
|
||||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
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.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.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.ReminderOverride
|
||||||
import de.jeanlucmakiola.floret.reminders.ReminderOverrideCodec
|
import de.jeanlucmakiola.floret.reminders.ReminderOverrideCodec
|
||||||
import de.jeanlucmakiola.floret.reminders.applyReminderOverride
|
import de.jeanlucmakiola.floret.reminders.applyReminderOverride
|
||||||
@@ -22,12 +40,28 @@ import de.jeanlucmakiola.floret.reminders.normalizeReminders
|
|||||||
import de.jeanlucmakiola.floret.reminders.reminderLeadsFor
|
import de.jeanlucmakiola.floret.reminders.reminderLeadsFor
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
import java.time.DayOfWeek
|
import java.time.DayOfWeek
|
||||||
|
import java.time.ZoneId
|
||||||
|
import java.time.LocalDate
|
||||||
import kotlinx.coroutines.flow.map
|
import kotlinx.coroutines.flow.map
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
import kotlin.time.Clock
|
||||||
|
import kotlin.time.Instant
|
||||||
|
|
||||||
enum class ThemeMode { SYSTEM, LIGHT, DARK }
|
/** [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
|
||||||
|
}
|
||||||
|
|
||||||
/** Clock convention: AUTO follows the device's 24-hour switch. */
|
/** Clock convention: AUTO follows the device's 24-hour switch. */
|
||||||
enum class TimeFormatPref { AUTO, TWELVE_HOUR, TWENTY_FOUR_HOUR }
|
enum class TimeFormatPref { AUTO, TWELVE_HOUR, TWENTY_FOUR_HOUR }
|
||||||
@@ -38,7 +72,18 @@ fun TimeFormatPref.is24Hour(systemIs24Hour: Boolean): Boolean = when (this) {
|
|||||||
TimeFormatPref.TWENTY_FOUR_HOUR -> true
|
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
|
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. */
|
/** The snooze lengths Settings offers. */
|
||||||
val SNOOZE_PRESETS = listOf(5, 10, 15, 30, 60)
|
val SNOOZE_PRESETS = listOf(5, 10, 15, 30, 60)
|
||||||
@@ -57,14 +102,16 @@ data class Settings(
|
|||||||
val dynamicColor: Boolean = true,
|
val dynamicColor: Boolean = true,
|
||||||
/** The list a new task defaults to; `null` = first available. */
|
/** The list a new task defaults to; `null` = first available. */
|
||||||
val defaultListId: Long? = null,
|
val defaultListId: Long? = null,
|
||||||
/** Default reminders, as minutes before due (0 = at due time); empty = none. */
|
/** Default reminders (0 before due = at due time); empty = none. */
|
||||||
val defaultReminderMinutes: List<Int> = listOf(0),
|
val defaultReminders: List<ReminderLead> = listOf(ReminderLead(0)),
|
||||||
/** Default reminders for all-day tasks, as days-scale minutes before [allDayReminderMinuteOfDay]. */
|
/** Default reminders for all-day tasks, in whole days, rung at [allDayReminderMinuteOfDay]. */
|
||||||
val defaultAllDayReminderMinutes: List<Int> = listOf(0),
|
val defaultAllDayReminders: List<ReminderLead> = listOf(ReminderLead(0)),
|
||||||
/** Local time (minutes from midnight) an all-day task's reminder counts back from. */
|
/** Local time (minutes from midnight) an all-day task's reminder counts back from. */
|
||||||
val allDayReminderMinuteOfDay: Int = DEFAULT_ALL_DAY_REMINDER_MINUTE,
|
val allDayReminderMinuteOfDay: Int = DEFAULT_ALL_DAY_REMINDER_MINUTE,
|
||||||
/** Master switch for due reminders; off clears every scheduled alarm. */
|
/** Master switch for due reminders; off clears every scheduled alarm. */
|
||||||
val remindersEnabled: Boolean = true,
|
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. */
|
/** Whether the inline "add a subtask" row shows on expanded task-list groups. */
|
||||||
val showAddSubtaskRow: Boolean = true,
|
val showAddSubtaskRow: Boolean = true,
|
||||||
/**
|
/**
|
||||||
@@ -74,18 +121,23 @@ data class Settings(
|
|||||||
*/
|
*/
|
||||||
val bottomAddBar: Boolean = false,
|
val bottomAddBar: Boolean = false,
|
||||||
/**
|
/**
|
||||||
* Per-list overrides of [defaultReminderMinutes]: a list present in the map
|
* Per-list overrides of [defaultReminders]: a list present in the map
|
||||||
* overrides the global default (an empty list = no reminder); absent =
|
* overrides the global default (an empty list = no reminder); absent =
|
||||||
* inherit.
|
* inherit.
|
||||||
*/
|
*/
|
||||||
val perListReminderOverride: Map<Long, List<Int>> = emptyMap(),
|
val perListReminderOverride: Map<Long, List<ReminderLead>> = emptyMap(),
|
||||||
/** Per-list overrides of [defaultAllDayReminderMinutes], same shape as [perListReminderOverride]. */
|
/** Per-list overrides of [defaultAllDayReminders], same shape as [perListReminderOverride]. */
|
||||||
val perListAllDayReminderOverride: Map<Long, List<Int>> = emptyMap(),
|
val perListAllDayReminderOverride: Map<Long, List<ReminderLead>> = emptyMap(),
|
||||||
/** Optional edit-form fields shown by default; the rest sit behind "More fields". */
|
/** Optional edit-form fields shown by default; the rest sit behind "More fields". */
|
||||||
val defaultEditFields: Set<TaskFormField> = emptySet(),
|
val defaultEditFields: Set<TaskFormField> = emptySet(),
|
||||||
val sortOrder: TaskSortOrder = TaskSortOrder.DUE,
|
val sortOrder: TaskSortOrder = TaskSortOrder.DUE,
|
||||||
/** How long a reminder's "Snooze" action puts it off. */
|
/** How long a reminder's "Snooze" action puts it off. */
|
||||||
val snoozeMinutes: Int = DEFAULT_SNOOZE_MINUTES,
|
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,
|
val timeFormat: TimeFormatPref = TimeFormatPref.AUTO,
|
||||||
/** The first day of the week; `null` follows the locale. */
|
/** The first day of the week; `null` follows the locale. */
|
||||||
val weekStart: DayOfWeek? = null,
|
val weekStart: DayOfWeek? = null,
|
||||||
@@ -97,24 +149,123 @@ data class Settings(
|
|||||||
val pushEnabled: Boolean = true,
|
val pushEnabled: Boolean = true,
|
||||||
/** Lists of the current store whose tasks the smart lists (and their counts) leave out. */
|
/** Lists of the current store whose tasks the smart lists (and their counts) leave out. */
|
||||||
val hiddenFromSmartLists: Set<Long> = emptySet(),
|
val hiddenFromSmartLists: Set<Long> = emptySet(),
|
||||||
/** Pre-fill a new task's start with today's date. */
|
/** The due date a new task's form starts with. */
|
||||||
val defaultStartToday: Boolean = false,
|
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,
|
||||||
) {
|
) {
|
||||||
/** [tasks] as [filter] shows them: a smart list drops the lists kept out of it. */
|
/** Whether a save rings the reminders it puts in the past (#106). */
|
||||||
fun visibleIn(filter: TaskFilter, tasks: List<Task>): List<Task> =
|
val ringsPastOnSave: Boolean get() = remindersEnabled && remindPastOnSave
|
||||||
if (filter is TaskFilter.Smart && hiddenFromSmartLists.isNotEmpty()) {
|
|
||||||
tasks.filter { it.listId !in hiddenFromSmartLists }
|
fun groupingFor(filter: TaskFilter): TaskGrouping =
|
||||||
} else {
|
filter.groupingKey()?.let { groupings[it] } ?: TaskGrouping.DUE
|
||||||
tasks
|
|
||||||
|
/**
|
||||||
|
* [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 }
|
||||||
}
|
}
|
||||||
|
return SmartView(kept, hiddenByRange)
|
||||||
|
}
|
||||||
|
|
||||||
/** The lead times for a task in [listId]: its override if set, else the global default. */
|
/** The lead times for a task in [listId]: its override if set, else the global default. */
|
||||||
fun reminderLeadsFor(listId: Long): List<Int> =
|
fun reminderLeadsFor(listId: Long): List<ReminderLead> =
|
||||||
perListReminderOverride.reminderLeadsFor(listId, defaultReminderMinutes)
|
perListReminderOverride.reminderLeadsFor(listId, defaultReminders)
|
||||||
|
|
||||||
/** The lead times for an all-day task in [listId]. */
|
/** The lead times for an all-day task in [listId]. */
|
||||||
fun allDayReminderLeadsFor(listId: Long): List<Int> =
|
fun allDayReminderLeadsFor(listId: Long): List<ReminderLead> =
|
||||||
perListAllDayReminderOverride.reminderLeadsFor(listId, defaultAllDayReminderMinutes)
|
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** App preferences, backed by DataStore. Mirrors Calendula's prefs shape. */
|
/** App preferences, backed by DataStore. Mirrors Calendula's prefs shape. */
|
||||||
@@ -124,54 +275,164 @@ class SettingsPrefs @Inject constructor(
|
|||||||
private val resolver: ProviderResolver,
|
private val resolver: ProviderResolver,
|
||||||
) {
|
) {
|
||||||
val settings: Flow<Settings> = dataStore.data.map { p ->
|
val settings: Flow<Settings> = dataStore.data.map { p ->
|
||||||
|
val scope = scopeOf(p)
|
||||||
Settings(
|
Settings(
|
||||||
themeMode = p[THEME_MODE]?.let { runCatching { ThemeMode.valueOf(it) }.getOrNull() }
|
themeMode = p[THEME_MODE]?.let { runCatching { ThemeMode.valueOf(it) }.getOrNull() }
|
||||||
?: ThemeMode.SYSTEM,
|
?: ThemeMode.SYSTEM,
|
||||||
dynamicColor = p[DYNAMIC_COLOR] ?: true,
|
dynamicColor = p[DYNAMIC_COLOR] ?: true,
|
||||||
defaultListId = p[DEFAULT_LIST_ID]?.takeIf { it > 0 },
|
defaultListId = p[DEFAULT_LIST_ID]?.takeIf { it > 0 },
|
||||||
// The single lead of earlier versions carries over until a list is saved.
|
// The single lead of earlier versions carries over until a list is saved.
|
||||||
defaultReminderMinutes = p[DEFAULT_REMINDERS]?.let(::parseMinutes)
|
defaultReminders = p[DEFAULT_REMINDERS]?.let(::parseLeads)
|
||||||
?: listOf(p[REMINDER_LEAD] ?: 0),
|
?: listOf(ReminderLead(p[REMINDER_LEAD] ?: 0)),
|
||||||
defaultAllDayReminderMinutes = p[DEFAULT_ALL_DAY_REMINDERS]?.let(::parseMinutes) ?: listOf(0),
|
defaultAllDayReminders = p[DEFAULT_ALL_DAY_REMINDERS]?.let(::parseLeads)?.inWholeDays()
|
||||||
|
?: listOf(ReminderLead(0)),
|
||||||
allDayReminderMinuteOfDay = p[ALL_DAY_REMINDER_MINUTE]?.takeIf { it in 0 until 24 * 60 }
|
allDayReminderMinuteOfDay = p[ALL_DAY_REMINDER_MINUTE]?.takeIf { it in 0 until 24 * 60 }
|
||||||
?: DEFAULT_ALL_DAY_REMINDER_MINUTE,
|
?: DEFAULT_ALL_DAY_REMINDER_MINUTE,
|
||||||
remindersEnabled = p[REMINDERS_ENABLED] ?: true,
|
remindersEnabled = p[REMINDERS_ENABLED] ?: true,
|
||||||
|
remindPastOnSave = p[REMIND_PAST_ON_SAVE] ?: false,
|
||||||
showAddSubtaskRow = p[SHOW_ADD_SUBTASK_ROW] ?: true,
|
showAddSubtaskRow = p[SHOW_ADD_SUBTASK_ROW] ?: true,
|
||||||
bottomAddBar = p[BOTTOM_ADD_BAR] ?: false,
|
bottomAddBar = p[BOTTOM_ADD_BAR] ?: false,
|
||||||
perListReminderOverride = reminderCodec.parse(p[LIST_REMINDER_OVERRIDE]),
|
perListReminderOverride = reminderCodec.parseLeads(p[LIST_REMINDER_OVERRIDE]),
|
||||||
perListAllDayReminderOverride = reminderCodec.parse(p[LIST_ALL_DAY_REMINDER_OVERRIDE]),
|
perListAllDayReminderOverride = reminderCodec.parseLeads(p[LIST_ALL_DAY_REMINDER_OVERRIDE])
|
||||||
|
.mapValues { it.value.inWholeDays() },
|
||||||
defaultEditFields = p[DEFAULT_EDIT_FIELDS].orEmpty()
|
defaultEditFields = p[DEFAULT_EDIT_FIELDS].orEmpty()
|
||||||
.mapNotNull { name -> runCatching { TaskFormField.valueOf(name) }.getOrNull() }
|
.mapNotNull { name -> runCatching { TaskFormField.valueOf(name) }.getOrNull() }
|
||||||
.toSet(),
|
.toSet(),
|
||||||
sortOrder = p[SORT_ORDER]?.let { runCatching { TaskSortOrder.valueOf(it) }.getOrNull() }
|
sortOrder = p[SORT_ORDER]?.let { runCatching { TaskSortOrder.valueOf(it) }.getOrNull() }
|
||||||
?: TaskSortOrder.DUE,
|
?: TaskSortOrder.DUE,
|
||||||
snoozeMinutes = p[SNOOZE_MINUTES]?.takeIf { it > 0 } ?: DEFAULT_SNOOZE_MINUTES,
|
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() }
|
timeFormat = p[TIME_FORMAT]?.let { runCatching { TimeFormatPref.valueOf(it) }.getOrNull() }
|
||||||
?: TimeFormatPref.AUTO,
|
?: TimeFormatPref.AUTO,
|
||||||
autofocusTitle = p[AUTOFOCUS_TITLE] ?: true,
|
autofocusTitle = p[AUTOFOCUS_TITLE] ?: true,
|
||||||
syncIntervalMinutes = p[SYNC_INTERVAL]?.takeIf { it == 0 || it >= 15 } ?: DEFAULT_SYNC_INTERVAL_MINUTES,
|
syncIntervalMinutes = p[SYNC_INTERVAL]?.takeIf { it == 0 || it >= 15 } ?: DEFAULT_SYNC_INTERVAL_MINUTES,
|
||||||
weekStart = p[WEEK_START]?.let { runCatching { DayOfWeek.valueOf(it) }.getOrNull() },
|
weekStart = p[WEEK_START]?.let { runCatching { DayOfWeek.valueOf(it) }.getOrNull() },
|
||||||
pushEnabled = p[PUSH_ENABLED] ?: true,
|
pushEnabled = p[PUSH_ENABLED] ?: true,
|
||||||
hiddenFromSmartLists = modeOf(p).name.let { mode ->
|
hiddenFromSmartLists = scope.let { mode ->
|
||||||
p[SMART_LIST_HIDDEN].orEmpty()
|
p[SMART_LIST_HIDDEN].orEmpty()
|
||||||
.mapNotNull { entry -> entry.substringAfter("$mode:", "").toLongOrNull() }
|
.mapNotNull { entry -> entry.substringAfter("$mode:", "").toLongOrNull() }
|
||||||
.toSet()
|
.toSet()
|
||||||
},
|
},
|
||||||
defaultStartToday = p[DEFAULT_START_TODAY] ?: false,
|
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 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 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 setSyncIntervalMinutes(minutes: Int) = dataStore.edit { it[SYNC_INTERVAL] = minutes }
|
||||||
|
|
||||||
suspend fun setPushEnabled(enabled: Boolean) = dataStore.edit { it[PUSH_ENABLED] = enabled }
|
suspend fun setPushEnabled(enabled: Boolean) = dataStore.edit { it[PUSH_ENABLED] = enabled }
|
||||||
|
|
||||||
suspend fun setAutofocusTitle(enabled: Boolean) = dataStore.edit { it[AUTOFOCUS_TITLE] = enabled }
|
suspend fun setAutofocusTitle(enabled: Boolean) = dataStore.edit { it[AUTOFOCUS_TITLE] = enabled }
|
||||||
|
|
||||||
suspend fun setDefaultStartToday(enabled: Boolean) = dataStore.edit { it[DEFAULT_START_TODAY] = 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 setTimeFormat(pref: TimeFormatPref) = dataStore.edit { it[TIME_FORMAT] = pref.name }
|
||||||
|
|
||||||
@@ -185,12 +446,12 @@ class SettingsPrefs @Inject constructor(
|
|||||||
if (id == null) it.remove(DEFAULT_LIST_ID) else it[DEFAULT_LIST_ID] = id
|
if (id == null) it.remove(DEFAULT_LIST_ID) else it[DEFAULT_LIST_ID] = id
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun setDefaultReminderMinutes(minutes: List<Int>) = dataStore.edit {
|
suspend fun setDefaultReminders(leads: List<ReminderLead>) = dataStore.edit {
|
||||||
it[DEFAULT_REMINDERS] = minutes.normalizeReminders().joinToString(",")
|
it[DEFAULT_REMINDERS] = leads.normalizeReminders().joinToString(",") { lead -> lead.toToken() }
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun setDefaultAllDayReminderMinutes(minutes: List<Int>) = dataStore.edit {
|
suspend fun setDefaultAllDayReminders(leads: List<ReminderLead>) = dataStore.edit {
|
||||||
it[DEFAULT_ALL_DAY_REMINDERS] = minutes.normalizeReminders().joinToString(",")
|
it[DEFAULT_ALL_DAY_REMINDERS] = leads.normalizeReminders().joinToString(",") { lead -> lead.toToken() }
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun setAllDayReminderMinuteOfDay(minuteOfDay: Int) =
|
suspend fun setAllDayReminderMinuteOfDay(minuteOfDay: Int) =
|
||||||
@@ -222,6 +483,51 @@ class SettingsPrefs @Inject constructor(
|
|||||||
/** The store list ids belong to; each store numbers its lists on its own. */
|
/** 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()
|
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 }
|
suspend fun setStorageMode(mode: StorageMode) = dataStore.edit { it[STORAGE_MODE] = mode.name }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -243,20 +549,20 @@ class SettingsPrefs @Inject constructor(
|
|||||||
|
|
||||||
/** Set (or clear, via [ReminderOverride.Inherit]) a list's reminder override. */
|
/** Set (or clear, via [ReminderOverride.Inherit]) a list's reminder override. */
|
||||||
suspend fun setListReminderOverride(listId: Long, override: ReminderOverride) = dataStore.edit { p ->
|
suspend fun setListReminderOverride(listId: Long, override: ReminderOverride) = dataStore.edit { p ->
|
||||||
val current = reminderCodec.parse(p[LIST_REMINDER_OVERRIDE]).toMutableMap()
|
val current = reminderCodec.parseLeads(p[LIST_REMINDER_OVERRIDE]).toMutableMap()
|
||||||
current.applyReminderOverride(listId, override)
|
current.applyReminderOverride(listId, override)
|
||||||
p[LIST_REMINDER_OVERRIDE] = reminderCodec.serialize(current)
|
p[LIST_REMINDER_OVERRIDE] = reminderCodec.serializeLeads(current)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Set (or clear) a list's all-day reminder override. */
|
/** Set (or clear) a list's all-day reminder override. */
|
||||||
suspend fun setListAllDayReminderOverride(listId: Long, override: ReminderOverride) = dataStore.edit { p ->
|
suspend fun setListAllDayReminderOverride(listId: Long, override: ReminderOverride) = dataStore.edit { p ->
|
||||||
val current = reminderCodec.parse(p[LIST_ALL_DAY_REMINDER_OVERRIDE]).toMutableMap()
|
val current = reminderCodec.parseLeads(p[LIST_ALL_DAY_REMINDER_OVERRIDE]).toMutableMap()
|
||||||
current.applyReminderOverride(listId, override)
|
current.applyReminderOverride(listId, override)
|
||||||
p[LIST_ALL_DAY_REMINDER_OVERRIDE] = reminderCodec.serialize(current)
|
p[LIST_ALL_DAY_REMINDER_OVERRIDE] = reminderCodec.serializeLeads(current)
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun setHiddenFromSmartLists(listId: Long, hidden: Boolean) = dataStore.edit { p ->
|
suspend fun setHiddenFromSmartLists(listId: Long, hidden: Boolean) = dataStore.edit { p ->
|
||||||
val entry = "${modeOf(p).name}:$listId"
|
val entry = "${claimedScope(p)}:$listId"
|
||||||
val current = p[SMART_LIST_HIDDEN].orEmpty()
|
val current = p[SMART_LIST_HIDDEN].orEmpty()
|
||||||
p[SMART_LIST_HIDDEN] = if (hidden) current + entry else current - entry
|
p[SMART_LIST_HIDDEN] = if (hidden) current + entry else current - entry
|
||||||
}
|
}
|
||||||
@@ -287,6 +593,8 @@ class SettingsPrefs @Inject constructor(
|
|||||||
|
|
||||||
suspend fun deleteFilter(id: Long) = dataStore.edit { p ->
|
suspend fun deleteFilter(id: Long) = dataStore.edit { p ->
|
||||||
p[SAVED_FILTERS] = SavedFilterCodec.remove(p[SAVED_FILTERS], id)
|
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 {
|
suspend fun setDefaultEditFields(fields: Set<TaskFormField>) = dataStore.edit {
|
||||||
@@ -307,10 +615,16 @@ class SettingsPrefs @Inject constructor(
|
|||||||
val BOTTOM_ADD_BAR = booleanPreferencesKey("bottom_add_bar")
|
val BOTTOM_ADD_BAR = booleanPreferencesKey("bottom_add_bar")
|
||||||
val ONBOARDING_DONE = booleanPreferencesKey("reminder_onboarding_done")
|
val ONBOARDING_DONE = booleanPreferencesKey("reminder_onboarding_done")
|
||||||
val STORAGE_MODE = stringPreferencesKey("storage_mode")
|
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 LIST_REMINDER_OVERRIDE = stringPreferencesKey("list_reminder_override")
|
||||||
val DEFAULT_EDIT_FIELDS = stringSetPreferencesKey("default_edit_fields")
|
val DEFAULT_EDIT_FIELDS = stringSetPreferencesKey("default_edit_fields")
|
||||||
val SORT_ORDER = stringPreferencesKey("sort_order")
|
val SORT_ORDER = stringPreferencesKey("sort_order")
|
||||||
val SNOOZE_MINUTES = intPreferencesKey("snooze_minutes")
|
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 TIME_FORMAT = stringPreferencesKey("time_format")
|
||||||
val WEEK_START = stringPreferencesKey("week_start")
|
val WEEK_START = stringPreferencesKey("week_start")
|
||||||
val AUTOFOCUS_TITLE = booleanPreferencesKey("autofocus_title")
|
val AUTOFOCUS_TITLE = booleanPreferencesKey("autofocus_title")
|
||||||
@@ -318,6 +632,12 @@ class SettingsPrefs @Inject constructor(
|
|||||||
val PUSH_ENABLED = booleanPreferencesKey("push_enabled")
|
val PUSH_ENABLED = booleanPreferencesKey("push_enabled")
|
||||||
val SMART_LIST_HIDDEN = stringSetPreferencesKey("smart_list_hidden")
|
val SMART_LIST_HIDDEN = stringSetPreferencesKey("smart_list_hidden")
|
||||||
val DEFAULT_START_TODAY = booleanPreferencesKey("default_start_today")
|
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_FILTERS = stringPreferencesKey("saved_filters")
|
||||||
val SAVED_FILTER_NEXT_ID = longPreferencesKey("saved_filter_next_id")
|
val SAVED_FILTER_NEXT_ID = longPreferencesKey("saved_filter_next_id")
|
||||||
}
|
}
|
||||||
@@ -330,6 +650,100 @@ class SettingsPrefs @Inject constructor(
|
|||||||
*/
|
*/
|
||||||
private val reminderCodec = ReminderOverrideCodec.DEFAULT
|
private val reminderCodec = ReminderOverrideCodec.DEFAULT
|
||||||
|
|
||||||
/** `5,30` → [5, 30]; an empty string is an explicit "no reminder". */
|
private fun listPersistencePrefix(mode: String, listId: Long) = "$mode:$listId="
|
||||||
private fun parseMinutes(stored: String): List<Int> =
|
|
||||||
stored.split(',').mapNotNull { it.trim().toIntOrNull()?.takeIf { m -> m >= 0 } }.normalizeReminders()
|
/** `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)
|
||||||
|
}
|
||||||
@@ -29,7 +29,7 @@ class BootReceiver : BroadcastReceiver() {
|
|||||||
val pending = goAsync()
|
val pending = goAsync()
|
||||||
scope.launch {
|
scope.launch {
|
||||||
try {
|
try {
|
||||||
runCatching { scheduler.sync(rearmAll = true) }
|
runCatching { scheduler.syncFromBroadcast(rearmAll = true) }
|
||||||
} finally {
|
} finally {
|
||||||
pending.finish()
|
pending.finish()
|
||||||
}
|
}
|
||||||
@@ -49,8 +49,9 @@ class BootReceiver : BroadcastReceiver() {
|
|||||||
val pending = goAsync()
|
val pending = goAsync()
|
||||||
scope.launch {
|
scope.launch {
|
||||||
try {
|
try {
|
||||||
runCatching { scheduler.sync(afterReboot = afterReboot) }
|
|
||||||
if (afterReboot) runCatching { snoozeScheduler.rearm() }
|
if (afterReboot) runCatching { snoozeScheduler.rearm() }
|
||||||
|
// Also restores the persistent reminders the reboot took down.
|
||||||
|
runCatching { scheduler.syncFromBroadcast(afterReboot = afterReboot) }
|
||||||
} finally {
|
} finally {
|
||||||
pending.finish()
|
pending.finish()
|
||||||
}
|
}
|
||||||
|
|||||||
+90
-12
@@ -6,6 +6,7 @@ import android.content.Intent
|
|||||||
import androidx.core.net.toUri
|
import androidx.core.net.toUri
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
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.TaskQuery
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
|
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
|
||||||
import de.jeanlucmakiola.agendula.domain.Task
|
import de.jeanlucmakiola.agendula.domain.Task
|
||||||
@@ -14,7 +15,9 @@ import kotlinx.coroutines.Dispatchers
|
|||||||
import kotlinx.coroutines.SupervisorJob
|
import kotlinx.coroutines.SupervisorJob
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withTimeoutOrNull
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
import kotlin.time.Instant
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fires when a task's reminder alarm goes off. Re-reads the task (it may have
|
* Fires when a task's reminder alarm goes off. Re-reads the task (it may have
|
||||||
@@ -28,6 +31,7 @@ class DueReminderReceiver : BroadcastReceiver() {
|
|||||||
@Inject lateinit var notifier: TaskNotifier
|
@Inject lateinit var notifier: TaskNotifier
|
||||||
@Inject lateinit var settingsPrefs: SettingsPrefs
|
@Inject lateinit var settingsPrefs: SettingsPrefs
|
||||||
@Inject lateinit var scheduler: ReminderScheduler
|
@Inject lateinit var scheduler: ReminderScheduler
|
||||||
|
@Inject lateinit var startupGate: StartupGate
|
||||||
|
|
||||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||||
|
|
||||||
@@ -44,8 +48,12 @@ class DueReminderReceiver : BroadcastReceiver() {
|
|||||||
}
|
}
|
||||||
val settings = settingsPrefs.settings.first()
|
val settings = settingsPrefs.settings.first()
|
||||||
if (!settings.remindersEnabled) return@launch
|
if (!settings.remindersEnabled) return@launch
|
||||||
val task = runCatching { dataSource.occurrence(taskId, occurrence) }.getOrNull()
|
// Before the gate the store is a guess; past this wait the broadcast's time runs short.
|
||||||
if (task != null && !task.isClosed) notifier.postDue(task, settings)
|
if (withTimeoutOrNull(ReminderScheduler.BROADCAST_GATE_WAIT_MS) { startupGate.awaitReady() } == null) {
|
||||||
|
runCatching { DueReminderWorker.enqueue(context, taskId, occurrence) }
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
runCatching { notifier.postIfOpen(dataSource, taskId, occurrence) }
|
||||||
} finally {
|
} finally {
|
||||||
pending.finish()
|
pending.finish()
|
||||||
}
|
}
|
||||||
@@ -74,17 +82,87 @@ class DueReminderReceiver : BroadcastReceiver() {
|
|||||||
/**
|
/**
|
||||||
* The occurrence of [taskId] anchored at [occurrenceStart] (epoch millis), or the
|
* 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.
|
* task's current one when there is no anchor or it can no longer be found.
|
||||||
* [TasksDataSource.task] alone resolves a series to whichever occurrence is
|
*
|
||||||
* current, which is not necessarily the one a reminder was armed for.
|
* ⚠️ 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.
|
||||||
*/
|
*/
|
||||||
internal fun TasksDataSource.occurrence(taskId: Long, occurrenceStart: Long): Task? {
|
internal fun TasksDataSource.occurrence(taskId: Long, occurrenceStart: Long): Task? {
|
||||||
val current = task(taskId) ?: return null
|
val anchor = occurrenceStart.takeIf { it != ScheduledReminder.NO_OCCURRENCE }?.let(Instant::fromEpochMilliseconds)
|
||||||
if (occurrenceStart == ScheduledReminder.NO_OCCURRENCE ||
|
val found = task(taskId, anchor) ?: return null
|
||||||
current.occurrenceStart?.toEpochMilliseconds() == occurrenceStart
|
if (anchor == null || found.occurrenceStart == anchor) return found
|
||||||
) {
|
return tasks(TaskQuery(listId = found.listId, includeCompleted = true))
|
||||||
return current
|
.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
|
||||||
}
|
}
|
||||||
return tasks(TaskQuery(listId = current.listId, includeCompleted = true))
|
found(taskId, occurrenceStart)
|
||||||
.firstOrNull { it.taskId == taskId && it.occurrenceStart?.toEpochMilliseconds() == occurrenceStart }
|
if (task.isClosed || (exact && !task.isOccurrence(occurrenceStart)) || (restoring != null && task.postponedSince(restoring))) {
|
||||||
?: current
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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())
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
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()
|
||||||
|
}
|
||||||
+105
@@ -0,0 +1,105 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -44,7 +44,7 @@ class ProviderChangeReceiver : BroadcastReceiver() {
|
|||||||
val pending = goAsync()
|
val pending = goAsync()
|
||||||
scope.launch {
|
scope.launch {
|
||||||
try {
|
try {
|
||||||
scheduler.sync()
|
scheduler.syncFromBroadcast()
|
||||||
} finally {
|
} finally {
|
||||||
pending.finish()
|
pending.finish()
|
||||||
}
|
}
|
||||||
|
|||||||
+82
-9
@@ -22,17 +22,18 @@ import kotlin.time.Instant
|
|||||||
* elapses. All app-internal intents, so the receiver is not exported.
|
* elapses. All app-internal intents, so the receiver is not exported.
|
||||||
*
|
*
|
||||||
* - **Done** completes the task — only the reminded occurrence, for a series.
|
* - **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
|
* - **Snooze** hides the notification and arms [ReminderSnoozeScheduler]'s
|
||||||
* alarm, which lives outside [ScheduledReminderStore] so no scheduler pass
|
* alarm, which lives outside [ScheduledReminderStore] so no scheduler pass
|
||||||
* can cancel it.
|
* can cancel it.
|
||||||
* - **Show** re-posts it, if the task is still open by then.
|
* - **Show** re-posts it, if the task is still open by then.
|
||||||
|
* - **Dismissed** puts a persistent reminder straight back, silently.
|
||||||
*/
|
*/
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class ReminderActionReceiver : BroadcastReceiver() {
|
class ReminderActionReceiver : BroadcastReceiver() {
|
||||||
|
|
||||||
@Inject lateinit var notifier: TaskNotifier
|
@Inject lateinit var notifier: TaskNotifier
|
||||||
@Inject lateinit var snoozeScheduler: ReminderSnoozeScheduler
|
@Inject lateinit var snoozeScheduler: ReminderSnoozeScheduler
|
||||||
@Inject lateinit var reminderScheduler: ReminderScheduler
|
|
||||||
@Inject lateinit var repository: TasksRepository
|
@Inject lateinit var repository: TasksRepository
|
||||||
@Inject lateinit var dataSource: TasksDataSource
|
@Inject lateinit var dataSource: TasksDataSource
|
||||||
@Inject lateinit var settingsPrefs: SettingsPrefs
|
@Inject lateinit var settingsPrefs: SettingsPrefs
|
||||||
@@ -44,22 +45,30 @@ class ReminderActionReceiver : BroadcastReceiver() {
|
|||||||
val taskId = intent.getLongExtra(EXTRA_TASK_ID, -1L).takeIf { it > 0L } ?: return
|
val taskId = intent.getLongExtra(EXTRA_TASK_ID, -1L).takeIf { it > 0L } ?: return
|
||||||
val occurrence = intent.getLongExtra(EXTRA_OCCURRENCE, ScheduledReminder.NO_OCCURRENCE)
|
val occurrence = intent.getLongExtra(EXTRA_OCCURRENCE, ScheduledReminder.NO_OCCURRENCE)
|
||||||
val action = intent.action ?: return
|
val action = intent.action ?: return
|
||||||
if (action == ACTION_DONE || action == ACTION_SNOOZE) notifier.cancel(taskId)
|
// 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)
|
||||||
val pending = goAsync()
|
val pending = goAsync()
|
||||||
scope.launch {
|
scope.launch {
|
||||||
try {
|
try {
|
||||||
when (action) {
|
when (action) {
|
||||||
ACTION_DONE -> runCatching {
|
ACTION_DONE -> runCatching {
|
||||||
startupGate.awaitReady()
|
if (!forgetPersistent(taskId, occurrence, store)) return@runCatching
|
||||||
val anchor = occurrence.takeIf { it != ScheduledReminder.NO_OCCURRENCE }
|
val anchor = occurrence.takeIf { it != ScheduledReminder.NO_OCCURRENCE }
|
||||||
?.let(Instant::fromEpochMilliseconds)
|
?.let(Instant::fromEpochMilliseconds)
|
||||||
repository.setCompleted(taskId, anchor, completed = true)
|
repository.setCompleted(taskId, anchor, completed = true)
|
||||||
reminderScheduler.sync()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ACTION_SNOOZE -> runCatching {
|
ACTION_SNOOZE -> runCatching {
|
||||||
val minutes = settingsPrefs.settings.first().snoozeMinutes
|
snoozeArmedFirst(
|
||||||
snoozeScheduler.schedule(taskId, occurrence, System.currentTimeMillis() + minutes * 60_000L)
|
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) },
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
ACTION_SHOW -> runCatching {
|
ACTION_SHOW -> runCatching {
|
||||||
@@ -67,8 +76,19 @@ class ReminderActionReceiver : BroadcastReceiver() {
|
|||||||
val settings = settingsPrefs.settings.first()
|
val settings = settingsPrefs.settings.first()
|
||||||
if (!settings.remindersEnabled) return@runCatching
|
if (!settings.remindersEnabled) return@runCatching
|
||||||
startupGate.awaitReady()
|
startupGate.awaitReady()
|
||||||
val task = dataSource.occurrence(taskId, occurrence)
|
notifier.postIfOpen(dataSource, taskId, occurrence)
|
||||||
if (task != null && !task.isClosed) notifier.postDue(task, settings)
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
@@ -77,23 +97,76 @@ 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 {
|
companion object {
|
||||||
const val ACTION_DONE = "de.jeanlucmakiola.agendula.reminders.DONE"
|
const val ACTION_DONE = "de.jeanlucmakiola.agendula.reminders.DONE"
|
||||||
const val ACTION_SNOOZE = "de.jeanlucmakiola.agendula.reminders.SNOOZE"
|
const val ACTION_SNOOZE = "de.jeanlucmakiola.agendula.reminders.SNOOZE"
|
||||||
const val ACTION_SHOW = "de.jeanlucmakiola.agendula.reminders.SHOW"
|
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_TASK_ID = "de.jeanlucmakiola.agendula.extra.TASK_ID"
|
||||||
private const val EXTRA_OCCURRENCE = "de.jeanlucmakiola.agendula.extra.OCCURRENCE_START"
|
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 —
|
* The data URI is what keeps two reminders' PendingIntents apart —
|
||||||
* `filterEquals` never compares extras.
|
* `filterEquals` never compares extras.
|
||||||
*/
|
*/
|
||||||
fun intent(context: Context, action: String, taskId: Long, occurrenceStart: Long): Intent =
|
fun intent(context: Context, action: String, taskId: Long, occurrenceStart: Long, store: String? = null): Intent =
|
||||||
Intent(context, ReminderActionReceiver::class.java)
|
Intent(context, ReminderActionReceiver::class.java)
|
||||||
.setAction(action)
|
.setAction(action)
|
||||||
.setData("agendula://reminder-action/$taskId/$occurrenceStart".toUri())
|
.setData("agendula://reminder-action/$taskId/$occurrenceStart".toUri())
|
||||||
.putExtra(EXTRA_TASK_ID, taskId)
|
.putExtra(EXTRA_TASK_ID, taskId)
|
||||||
.putExtra(EXTRA_OCCURRENCE, occurrenceStart)
|
.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,7 +21,9 @@ internal data class ReminderDiff(
|
|||||||
fired: Set<ScheduledReminder> = emptySet(),
|
fired: Set<ScheduledReminder> = emptySet(),
|
||||||
isArmed: (ScheduledReminder) -> Boolean,
|
isArmed: (ScheduledReminder) -> Boolean,
|
||||||
): ReminderDiff {
|
): ReminderDiff {
|
||||||
val live = previous.filterTo(HashSet()) { it in fired || isArmed(it) }
|
// 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
|
||||||
return ReminderDiff(
|
return ReminderDiff(
|
||||||
cancel = live - desired,
|
cancel = live - desired,
|
||||||
arm = desired - live,
|
arm = desired - live,
|
||||||
|
|||||||
@@ -1,9 +1,15 @@
|
|||||||
package de.jeanlucmakiola.agendula.data.reminders
|
package de.jeanlucmakiola.agendula.data.reminders
|
||||||
|
|
||||||
import de.jeanlucmakiola.agendula.data.prefs.Settings
|
import de.jeanlucmakiola.agendula.data.prefs.Settings
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.TaskReminder
|
import de.jeanlucmakiola.agendula.domain.AllDayReminder
|
||||||
import de.jeanlucmakiola.agendula.domain.Task
|
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.calendarDate
|
||||||
|
import de.jeanlucmakiola.agendula.domain.forDates
|
||||||
|
import java.time.LocalDate
|
||||||
import java.time.LocalTime
|
import java.time.LocalTime
|
||||||
import java.time.ZoneId
|
import java.time.ZoneId
|
||||||
import kotlin.time.Instant
|
import kotlin.time.Instant
|
||||||
@@ -16,6 +22,8 @@ internal object ReminderPlanner {
|
|||||||
/** How long after its trigger a missed reminder is still worth firing. */
|
/** How long after its trigger a missed reminder is still worth firing. */
|
||||||
const val MISSED_GRACE_MS = 6L * 60 * 60 * 1000 // 6 hours
|
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.
|
* Alarms this app will hold at once.
|
||||||
*
|
*
|
||||||
@@ -36,35 +44,7 @@ internal object ReminderPlanner {
|
|||||||
// One reminder per *occurrence* and lead: a recurring series yields a row
|
// 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
|
// per occurrence, all sharing a taskId, so this is a Set rather than a
|
||||||
// taskId-keyed Map.
|
// taskId-keyed Map.
|
||||||
.filter { !it.isClosed && it.due != null }
|
.flatMap { triggers(it, perTask[it.taskId], settings, zone, now = now) }
|
||||||
.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
|
// The lower bound trails `now` so a reminder missed while the device was
|
||||||
// off still fires once on boot instead of being silently dropped.
|
// off still fires once on boot instead of being silently dropped.
|
||||||
.filter { it.triggerAt in (now - MISSED_GRACE_MS)..(now + WINDOW_MS) }
|
.filter { it.triggerAt in (now - MISSED_GRACE_MS)..(now + WINDOW_MS) }
|
||||||
@@ -75,13 +55,143 @@ internal object ReminderPlanner {
|
|||||||
.take(MAX_ALARMS)
|
.take(MAX_ALARMS)
|
||||||
.toSet()
|
.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.
|
* When a reminder [leadMinutes] before [anchor] fires.
|
||||||
*
|
*
|
||||||
* ⚠️ An all-day anchor is UTC midnight of its date (see `AllDayTime.kt`), a
|
* ⚠️ 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
|
* 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
|
* Berlin and the evening before in New York. It is read as its calendar
|
||||||
* at [allDayMinuteOfDay] local time instead, and the lead counts back from that.
|
* date instead, and the lead as [TaskReminder.allDay]: whole days ring at
|
||||||
|
* [allDayMinuteOfDay] local time, anything else at the time it names.
|
||||||
*/
|
*/
|
||||||
fun triggerAt(
|
fun triggerAt(
|
||||||
anchor: Instant,
|
anchor: Instant,
|
||||||
@@ -90,12 +200,11 @@ internal object ReminderPlanner {
|
|||||||
allDayMinuteOfDay: Int,
|
allDayMinuteOfDay: Int,
|
||||||
zone: ZoneId,
|
zone: ZoneId,
|
||||||
): Long {
|
): Long {
|
||||||
val base = if (allDay) {
|
if (!allDay) return anchor.toEpochMilliseconds() - leadMinutes.coerceAtLeast(0) * 60_000L
|
||||||
val time = LocalTime.of(allDayMinuteOfDay / 60 % 24, allDayMinuteOfDay % 60)
|
val (days, minuteOfDay) = AllDayReminder.of(leadMinutes)
|
||||||
anchor.calendarDate(allDay = true).atTime(time).atZone(zone).toInstant().toEpochMilli()
|
return atMinuteOfDay(anchor.calendarDate(allDay = true).minusDays(days.toLong()), minuteOfDay ?: allDayMinuteOfDay, zone)
|
||||||
} 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()
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
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,13 +8,16 @@ import dagger.hilt.android.qualifiers.ApplicationContext
|
|||||||
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
|
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
|
||||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
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.TaskQuery
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
|
import de.jeanlucmakiola.agendula.data.tasks.TasksDataSource
|
||||||
|
import de.jeanlucmakiola.agendula.domain.TaskReminder
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.sync.Mutex
|
import kotlinx.coroutines.sync.Mutex
|
||||||
import kotlinx.coroutines.sync.withLock
|
import kotlinx.coroutines.sync.withLock
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlinx.coroutines.withTimeoutOrNull
|
||||||
import java.time.ZoneId
|
import java.time.ZoneId
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
@@ -23,8 +26,9 @@ import javax.inject.Singleton
|
|||||||
* The self-scheduled due-reminder engine. Nothing else delivers task reminders —
|
* The self-scheduled due-reminder engine. Nothing else delivers task reminders —
|
||||||
* not the platform, not a tasks provider — so Agendula reads upcoming due tasks
|
* 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
|
* 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 an external provider change;
|
* on app start, on boot, on a store switch and on every change to the store (see
|
||||||
* it diffs against [ScheduledReminderStore] so only changed alarms move.
|
* [ReminderRefresher]); it diffs against [ScheduledReminderStore] so only changed
|
||||||
|
* alarms move, and takes down posted reminders whose task is done with.
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class ReminderScheduler @Inject constructor(
|
class ReminderScheduler @Inject constructor(
|
||||||
@@ -34,6 +38,8 @@ class ReminderScheduler @Inject constructor(
|
|||||||
private val store: ScheduledReminderStore,
|
private val store: ScheduledReminderStore,
|
||||||
private val providerResolver: ProviderResolver,
|
private val providerResolver: ProviderResolver,
|
||||||
private val snoozeScheduler: ReminderSnoozeScheduler,
|
private val snoozeScheduler: ReminderSnoozeScheduler,
|
||||||
|
private val notifier: TaskNotifier,
|
||||||
|
private val startupGate: StartupGate,
|
||||||
@IoDispatcher private val io: CoroutineDispatcher,
|
@IoDispatcher private val io: CoroutineDispatcher,
|
||||||
) {
|
) {
|
||||||
private val syncLock = Mutex()
|
private val syncLock = Mutex()
|
||||||
@@ -47,13 +53,57 @@ class ReminderScheduler @Inject constructor(
|
|||||||
* the whole truth, leaving the other's alarms armed but unrecorded — never
|
* the whole truth, leaving the other's alarms armed but unrecorded — never
|
||||||
* cancelled, and firing against the wrong store's task ids.
|
* cancelled, and firing against the wrong store's task ids.
|
||||||
*/
|
*/
|
||||||
suspend fun sync(afterReboot: Boolean = false, rearmAll: Boolean = false) =
|
suspend fun sync(afterReboot: Boolean = false, rearmAll: Boolean = false) = withContext(io) {
|
||||||
withContext(io) { syncLock.withLock { syncLocked(afterReboot, rearmAll) } }
|
// 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)
|
||||||
|
}
|
||||||
|
|
||||||
/** Record that [reminder] went off, so a later pass neither re-arms nor re-fires it. */
|
/** Record that [reminder] went off, so a later pass neither re-arms nor re-fires it. */
|
||||||
suspend fun markFired(reminder: ScheduledReminder) =
|
suspend fun markFired(reminder: ScheduledReminder) =
|
||||||
withContext(io) { syncLock.withLock { store.markFired(reminder) } }
|
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;
|
* @param afterReboot every alarm is gone, so nothing in the store is armed;
|
||||||
* skips asking the system about each one.
|
* skips asking the system about each one.
|
||||||
@@ -65,19 +115,27 @@ class ReminderScheduler @Inject constructor(
|
|||||||
// Gate on whether the store is readable, not on whether a provider
|
// Gate on whether the store is readable, not on whether a provider
|
||||||
// resolves: our own store deliberately resolves to no provider, so the
|
// resolves: our own store deliberately resolves to no provider, so the
|
||||||
// latter clears every reminder in the default mode.
|
// latter clears every reminder in the default mode.
|
||||||
if (!settings.remindersEnabled || !providerResolver.canReadStore()) {
|
val readable = providerResolver.canReadStore()
|
||||||
|
if (!settings.remindersEnabled || !readable) {
|
||||||
clearAll()
|
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
|
return
|
||||||
}
|
}
|
||||||
val tasks = runCatching { dataSource.tasks(TaskQuery(includeCompleted = false)) }
|
val tasks = runCatching { dataSource.tasks(TaskQuery(includeCompleted = false)) }
|
||||||
.getOrElse { return }
|
.getOrElse { return }
|
||||||
// Per-task leads. One query for all of them.
|
// Per-task leads. One query for all of them.
|
||||||
val perTask = runCatching { dataSource.reminders() }.getOrElse { emptyMap() }
|
val perTask = runCatching { dataSource.reminders() }.getOrElse { emptyMap() }
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
val desired = ReminderPlanner.plan(
|
val desired = ReminderPlanner.plan(
|
||||||
tasks = tasks,
|
tasks = tasks,
|
||||||
perTask = perTask,
|
perTask = perTask,
|
||||||
settings = settings,
|
settings = settings,
|
||||||
now = System.currentTimeMillis(),
|
now = now,
|
||||||
zone = ZoneId.systemDefault(),
|
zone = ZoneId.systemDefault(),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -92,7 +150,10 @@ class ReminderScheduler @Inject constructor(
|
|||||||
|
|
||||||
// ⚠️ The store survives reboot, force-stop and restore; the alarms don't.
|
// ⚠️ The store survives reboot, force-stop and restore; the alarms don't.
|
||||||
// Trusting it alone left every reminder after a reboot unarmed for good.
|
// Trusting it alone left every reminder after a reboot unarmed for good.
|
||||||
val fired = store.fired()
|
// ⚠️ 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 diff = ReminderDiff.of(store.all(), desired, fired) { !afterReboot && !rearm && isArmed(it) }
|
val diff = ReminderDiff.of(store.all(), desired, fired) { !afterReboot && !rearm && isArmed(it) }
|
||||||
diff.cancel.forEach { cancel(it) }
|
diff.cancel.forEach { cancel(it) }
|
||||||
// ⚠️ Only what was actually armed. A throw mid-loop used to skip the
|
// ⚠️ Only what was actually armed. A throw mid-loop used to skip the
|
||||||
@@ -100,7 +161,32 @@ class ReminderScheduler @Inject constructor(
|
|||||||
// — uncancellable, and firing for tasks that no longer exist — and the
|
// — uncancellable, and firing for tasks that no longer exist — and the
|
||||||
// exception escaped into BootReceiver's goAsync().
|
// exception escaped into BootReceiver's goAsync().
|
||||||
val armed = diff.arm.filter { schedule(it) }
|
val armed = diff.arm.filter { schedule(it) }
|
||||||
store.replace(diff.keep + armed, fired = fired intersect desired, exact = canExact)
|
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()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Whether the system still holds this alarm's PendingIntent. */
|
/** Whether the system still holds this alarm's PendingIntent. */
|
||||||
@@ -152,6 +238,11 @@ 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() {
|
private suspend fun clearAll() {
|
||||||
store.all().forEach { cancel(it) }
|
store.all().forEach { cancel(it) }
|
||||||
store.replace(emptySet(), fired = emptySet())
|
store.replace(emptySet(), fired = emptySet())
|
||||||
|
|||||||
+14
-6
@@ -41,6 +41,12 @@ 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() {
|
suspend fun rearm() {
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
dataStore.data.first()[KEY].orEmpty().forEach { entry ->
|
dataStore.data.first()[KEY].orEmpty().forEach { entry ->
|
||||||
@@ -52,12 +58,7 @@ class ReminderSnoozeScheduler @Inject constructor(
|
|||||||
|
|
||||||
private fun arm(taskId: Long, occurrenceStart: Long, triggerAtMillis: Long) {
|
private fun arm(taskId: Long, occurrenceStart: Long, triggerAtMillis: Long) {
|
||||||
val alarmManager = context.getSystemService(AlarmManager::class.java) ?: return
|
val alarmManager = context.getSystemService(AlarmManager::class.java) ?: return
|
||||||
val pendingIntent = PendingIntent.getBroadcast(
|
val pendingIntent = showIntent(taskId, occurrenceStart)
|
||||||
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()
|
val canExact = Build.VERSION.SDK_INT < Build.VERSION_CODES.S || alarmManager.canScheduleExactAlarms()
|
||||||
try {
|
try {
|
||||||
if (canExact) {
|
if (canExact) {
|
||||||
@@ -70,6 +71,13 @@ 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 {
|
private companion object {
|
||||||
/** `taskId|occurrenceStart|triggerAt` per pending snooze. */
|
/** `taskId|occurrenceStart|triggerAt` per pending snooze. */
|
||||||
val KEY = stringSetPreferencesKey("pending_snoozes")
|
val KEY = stringSetPreferencesKey("pending_snoozes")
|
||||||
|
|||||||
+4
-2
@@ -61,9 +61,11 @@ class ScheduledReminderStore @Inject constructor(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun markFired(reminder: ScheduledReminder) {
|
suspend fun markFired(reminder: ScheduledReminder) = markFired(setOf(reminder))
|
||||||
|
|
||||||
|
suspend fun markFired(reminders: Set<ScheduledReminder>) {
|
||||||
dataStore.edit { prefs ->
|
dataStore.edit { prefs ->
|
||||||
prefs[FIRED_KEY] = prefs[FIRED_KEY].orEmpty() + encode(setOf(reminder))
|
prefs[FIRED_KEY] = prefs[FIRED_KEY].orEmpty() + encode(reminders)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,33 +1,41 @@
|
|||||||
package de.jeanlucmakiola.agendula.data.reminders
|
package de.jeanlucmakiola.agendula.data.reminders
|
||||||
|
|
||||||
import android.Manifest
|
|
||||||
import android.annotation.SuppressLint
|
import android.annotation.SuppressLint
|
||||||
|
import android.app.Notification
|
||||||
import android.app.NotificationChannel
|
import android.app.NotificationChannel
|
||||||
import android.app.NotificationChannelGroup
|
import android.app.NotificationChannelGroup
|
||||||
import android.app.NotificationManager
|
import android.app.NotificationManager
|
||||||
import android.app.PendingIntent
|
import android.app.PendingIntent
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.content.pm.PackageManager
|
import android.os.Bundle
|
||||||
import android.os.Build
|
|
||||||
import android.text.format.DateFormat
|
import android.text.format.DateFormat
|
||||||
|
import android.util.TypedValue
|
||||||
import androidx.core.app.NotificationCompat
|
import androidx.core.app.NotificationCompat
|
||||||
import androidx.core.app.NotificationManagerCompat
|
import androidx.core.app.NotificationManagerCompat
|
||||||
import androidx.core.content.ContextCompat
|
|
||||||
import androidx.core.content.edit
|
import androidx.core.content.edit
|
||||||
import de.jeanlucmakiola.agendula.MainActivity
|
import de.jeanlucmakiola.agendula.MainActivity
|
||||||
import de.jeanlucmakiola.agendula.R
|
import de.jeanlucmakiola.agendula.R
|
||||||
|
import de.jeanlucmakiola.agendula.data.prefs.ReminderDescription
|
||||||
import de.jeanlucmakiola.agendula.data.prefs.Settings
|
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.prefs.is24Hour
|
||||||
import de.jeanlucmakiola.agendula.data.di.ApplicationScope
|
import de.jeanlucmakiola.agendula.data.di.ApplicationScope
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
import de.jeanlucmakiola.agendula.data.tasks.ProviderResolver
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.StartupGate
|
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.data.tasks.TasksDataSource
|
||||||
import de.jeanlucmakiola.agendula.domain.Task
|
import de.jeanlucmakiola.agendula.domain.Task
|
||||||
import de.jeanlucmakiola.agendula.domain.calendarDate
|
import de.jeanlucmakiola.agendula.domain.calendarDate
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.launch
|
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.Instant as JInstant
|
||||||
import java.time.LocalDate
|
import java.time.LocalDate
|
||||||
import java.time.ZoneId
|
import java.time.ZoneId
|
||||||
@@ -43,7 +51,9 @@ import kotlin.time.Instant
|
|||||||
* Posts one notification per due task on its list's channel, so each list can
|
* 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
|
* 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
|
* replaces rather than duplicates. Tapping opens the task's detail screen (see
|
||||||
* [MainActivity.taskIntent]).
|
* [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.
|
||||||
*/
|
*/
|
||||||
@Singleton
|
@Singleton
|
||||||
class TaskNotifier @Inject constructor(
|
class TaskNotifier @Inject constructor(
|
||||||
@@ -52,29 +62,63 @@ class TaskNotifier @Inject constructor(
|
|||||||
private val dataSource: TasksDataSource,
|
private val dataSource: TasksDataSource,
|
||||||
private val startupGate: StartupGate,
|
private val startupGate: StartupGate,
|
||||||
@ApplicationScope private val scope: CoroutineScope,
|
@ApplicationScope private val scope: CoroutineScope,
|
||||||
|
private val records: PersistentReminderStore,
|
||||||
|
private val settingsPrefs: SettingsPrefs,
|
||||||
) {
|
) {
|
||||||
private val manager get() = context.getSystemService(NotificationManager::class.java)
|
private val manager get() = context.getSystemService(NotificationManager::class.java)
|
||||||
private val channelPrefs get() = context.getSharedPreferences(CHANNEL_PREFS, Context.MODE_PRIVATE)
|
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 {
|
fun canPost(): Boolean {
|
||||||
val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
|
return context.canPostNotifications()
|
||||||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) ==
|
}
|
||||||
PackageManager.PERMISSION_GRANTED
|
|
||||||
return granted && NotificationManagerCompat.from(context).areNotificationsEnabled()
|
/**
|
||||||
|
* 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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// canPost() checks POST_NOTIFICATIONS before we ever call notify().
|
// canPost() checks POST_NOTIFICATIONS before we ever call notify().
|
||||||
@SuppressLint("MissingPermission")
|
@SuppressLint("MissingPermission")
|
||||||
fun postDue(task: Task, settings: Settings) {
|
private suspend fun post(task: Task, settings: Settings, alert: Boolean, postedAt: Long?, persistent: Boolean) {
|
||||||
if (!canPost()) return
|
val store = settingsPrefs.claimStoreScope()
|
||||||
|
val occurrence = task.occurrenceStart?.toEpochMilliseconds() ?: ScheduledReminder.NO_OCCURRENCE
|
||||||
|
val shownAt = postedAt ?: System.currentTimeMillis()
|
||||||
val channelId = ensureListChannel(task.listId, task.listName)
|
val channelId = ensureListChannel(task.listId, task.listName)
|
||||||
val title = task.title.ifBlank { context.getString(R.string.task_untitled) }
|
val title = task.title.ifBlank { context.getString(R.string.task_untitled) }
|
||||||
val text = task.due?.let { due ->
|
val text = task.shownValue(TaskEnd.DUE)?.let { due ->
|
||||||
context.getString(
|
context.getString(
|
||||||
R.string.reminder_due_at,
|
R.string.reminder_due_at,
|
||||||
formatReminderDue(
|
formatReminderDue(
|
||||||
due.toEpochMilliseconds(),
|
due.toEpochMilliseconds(),
|
||||||
task.isAllDay,
|
!task.hasTime(TaskEnd.DUE),
|
||||||
is24Hour = settings.timeFormat.is24Hour(DateFormat.is24HourFormat(context)),
|
is24Hour = settings.timeFormat.is24Hour(DateFormat.is24HourFormat(context)),
|
||||||
relative = RelativeDays(
|
relative = RelativeDays(
|
||||||
today = context.getString(R.string.reminder_day_today),
|
today = context.getString(R.string.reminder_day_today),
|
||||||
@@ -84,6 +128,9 @@ class TaskNotifier @Inject constructor(
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
val description = reminderBody(settings.reminderDescription, lineChars()) {
|
||||||
|
task.description?.readableDescription()
|
||||||
|
}
|
||||||
val tapIntent = PendingIntent.getActivity(
|
val tapIntent = PendingIntent.getActivity(
|
||||||
context,
|
context,
|
||||||
task.taskId.toInt(),
|
task.taskId.toInt(),
|
||||||
@@ -93,34 +140,236 @@ class TaskNotifier @Inject constructor(
|
|||||||
val notification = NotificationCompat.Builder(context, channelId)
|
val notification = NotificationCompat.Builder(context, channelId)
|
||||||
.setSmallIcon(R.drawable.ic_notification)
|
.setSmallIcon(R.drawable.ic_notification)
|
||||||
.setContentTitle(title)
|
.setContentTitle(title)
|
||||||
.apply { if (text != null) setContentText(text) }
|
.apply { (text ?: description)?.let(::setContentText) }
|
||||||
|
.apply {
|
||||||
|
expandedText(text, description)?.let { setStyle(NotificationCompat.BigTextStyle().bigText(it)) }
|
||||||
|
}
|
||||||
.setCategory(NotificationCompat.CATEGORY_REMINDER)
|
.setCategory(NotificationCompat.CATEGORY_REMINDER)
|
||||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||||
.setAutoCancel(true)
|
.setWhen(shownAt)
|
||||||
|
.setAutoCancel(!persistent)
|
||||||
|
.setSilent(!alert)
|
||||||
|
.apply { groupFor(task.taskId, persistent, alert)?.let(::setGroup) }
|
||||||
|
.setDeleteIntent(if (persistent) dismissedIntent(task.taskId, occurrence, store) else null)
|
||||||
.setContentIntent(tapIntent)
|
.setContentIntent(tapIntent)
|
||||||
.addAction(0, context.getString(R.string.reminder_action_done), actionIntent(task, ReminderActionReceiver.ACTION_DONE))
|
.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(
|
.addAction(
|
||||||
0,
|
0,
|
||||||
context.getString(R.string.reminder_action_snooze, settings.snoozeMinutes),
|
context.getString(R.string.reminder_action_snooze, settings.snoozeMinutes),
|
||||||
actionIntent(task, ReminderActionReceiver.ACTION_SNOOZE),
|
actionIntent(task, ReminderActionReceiver.ACTION_SNOOZE, store),
|
||||||
)
|
)
|
||||||
.build()
|
.build()
|
||||||
NotificationManagerCompat.from(context).notify(task.taskId.toString(), NOTIFICATION_ID, notification)
|
NotificationManagerCompat.from(context).notify(task.taskId.toString(), NOTIFICATION_ID, notification)
|
||||||
|
remember(store, task.taskId, occurrence, task.due?.toEpochMilliseconds(), shownAt, persistent)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun cancel(taskId: Long) {
|
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) {
|
||||||
NotificationManagerCompat.from(context).cancel(taskId.toString(), NOTIFICATION_ID)
|
NotificationManagerCompat.from(context).cancel(taskId.toString(), NOTIFICATION_ID)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun actionIntent(task: Task, action: String): PendingIntent = PendingIntent.getBroadcast(
|
suspend fun cancel(taskId: Long, store: String? = null) {
|
||||||
context,
|
dismiss(taskId)
|
||||||
task.taskId.toInt(),
|
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,
|
||||||
ReminderActionReceiver.intent(
|
ReminderActionReceiver.intent(
|
||||||
context,
|
context,
|
||||||
action,
|
action,
|
||||||
task.taskId,
|
task.taskId,
|
||||||
task.occurrenceStart?.toEpochMilliseconds() ?: ScheduledReminder.NO_OCCURRENCE,
|
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,
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -132,7 +381,7 @@ class TaskNotifier @Inject constructor(
|
|||||||
*/
|
*/
|
||||||
fun ensureListChannel(listId: Long, listName: String?): String {
|
fun ensureListChannel(listId: Long, listName: String?): String {
|
||||||
ensureGroup()
|
ensureGroup()
|
||||||
val id = "$LIST_CHANNEL_PREFIX${resolver.mode().name.lowercase()}_$listId"
|
val id = "$LIST_CHANNEL_PREFIX${channelStore}_$listId"
|
||||||
val importance = manager.getNotificationChannel(id)?.importance ?: legacyImportance()
|
val importance = manager.getNotificationChannel(id)?.importance ?: legacyImportance()
|
||||||
manager.createNotificationChannel(
|
manager.createNotificationChannel(
|
||||||
NotificationChannel(
|
NotificationChannel(
|
||||||
@@ -167,7 +416,7 @@ class TaskNotifier @Inject constructor(
|
|||||||
startupGate.awaitReady()
|
startupGate.awaitReady()
|
||||||
val lists = dataSource.taskLists()
|
val lists = dataSource.taskLists()
|
||||||
lists.forEach { ensureListChannel(it.id, it.name) }
|
lists.forEach { ensureListChannel(it.id, it.name) }
|
||||||
val prefix = "$LIST_CHANNEL_PREFIX${resolver.mode().name.lowercase()}_"
|
val prefix = "$LIST_CHANNEL_PREFIX${channelStore}_"
|
||||||
val live = lists.map { "$prefix${it.id}" }.toSet()
|
val live = lists.map { "$prefix${it.id}" }.toSet()
|
||||||
manager.notificationChannels
|
manager.notificationChannels
|
||||||
.filter { it.id.startsWith(prefix) && it.id !in live }
|
.filter { it.id.startsWith(prefix) && it.id !in live }
|
||||||
@@ -185,8 +434,14 @@ class TaskNotifier @Inject constructor(
|
|||||||
private const val LEGACY_CHANNEL_ID = "task_reminders"
|
private const val LEGACY_CHANNEL_ID = "task_reminders"
|
||||||
private const val LIST_CHANNEL_PREFIX = "reminders_"
|
private const val LIST_CHANNEL_PREFIX = "reminders_"
|
||||||
private const val NOTIFICATION_ID = 1
|
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 CHANNEL_PREFS = "reminder_channels"
|
||||||
private const val KEY_LEGACY_IMPORTANCE = "legacy_importance"
|
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
|
* Whether a reminder can sound anywhere: the group is not blocked and at
|
||||||
@@ -240,3 +495,170 @@ private fun relativeDay(date: LocalDate, today: LocalDate, words: RelativeDays,
|
|||||||
else -> null
|
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,
|
||||||
|
)
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,6 +25,9 @@ interface RemoteLists {
|
|||||||
/** Ours is a read-only share; the write belongs to whoever owns it. */
|
/** Ours is a read-only share; the write belongs to whoever owns it. */
|
||||||
data object ReadOnly : Outcome
|
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. */
|
/** The account is gone, stopped, or has no credential we can decrypt. */
|
||||||
data object NoAccount : Outcome
|
data object NoAccount : Outcome
|
||||||
|
|
||||||
|
|||||||
@@ -2,5 +2,5 @@ package de.jeanlucmakiola.agendula.data.sync
|
|||||||
|
|
||||||
/** Asks for an account to be synced now. A no-op in the `offline` flavor. */
|
/** Asks for an account to be synced now. A no-op in the `offline` flavor. */
|
||||||
fun interface SyncRequests {
|
fun interface SyncRequests {
|
||||||
fun syncNow(accountName: String)
|
suspend fun syncNow(accountId: Long)
|
||||||
}
|
}
|
||||||
+748
-111
File diff suppressed because it is too large.
Load diff
@@ -3,9 +3,9 @@ package de.jeanlucmakiola.agendula.data.tasks
|
|||||||
import android.database.Cursor
|
import android.database.Cursor
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Domain-shaped seam over a row of provider data, so the mappers can be
|
* Domain-shaped seam over a row of provider data, read from a [Cursor] by
|
||||||
* unit-tested with a Map instead of a real [Cursor] (see MapColumnReader in
|
* [CursorColumnReader] or from a Map by [MapColumnReader], which also lets the
|
||||||
* test sources). Mirrors Calendula's ColumnReader.
|
* mappers be unit-tested without a cursor. Mirrors Calendula's ColumnReader.
|
||||||
*/
|
*/
|
||||||
interface ColumnReader {
|
interface ColumnReader {
|
||||||
fun getLong(name: String): Long?
|
fun getLong(name: String): Long?
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package de.jeanlucmakiola.agendula.data.tasks
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Agendula's own order for an external provider's lists, which the provider has
|
||||||
|
* no column for. Stored as `id=position` pairs. A list without one counts as
|
||||||
|
* position 0, as a new list does in Agendula's own store.
|
||||||
|
*/
|
||||||
|
object ListOrder {
|
||||||
|
|
||||||
|
fun decode(raw: String?): Map<Long, Int> = raw.orEmpty().split(',').mapNotNull { pair ->
|
||||||
|
val (id, position) = pair.split('=').takeIf { it.size == 2 } ?: return@mapNotNull null
|
||||||
|
id.toLongOrNull()?.let { key -> position.toIntOrNull()?.let { key to it } }
|
||||||
|
}.toMap()
|
||||||
|
|
||||||
|
fun encode(order: Map<Long, Int>): String = order.entries.joinToString(",") { "${it.key}=${it.value}" }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Positions for every list in [shown] — the lists in their current order —
|
||||||
|
* after one account's [listIds] were rearranged: those take each other's
|
||||||
|
* slots in their new order, and every other list keeps its own.
|
||||||
|
*/
|
||||||
|
fun reordered(shown: List<Long>, listIds: List<Long>): Map<Long, Int> {
|
||||||
|
val moved = listIds.iterator()
|
||||||
|
val moving = listIds.toSet()
|
||||||
|
val result = shown.map { if (it in moving && moved.hasNext()) moved.next() else it }.toMutableList()
|
||||||
|
moved.forEachRemaining { if (it !in result) result += it }
|
||||||
|
return result.withIndex().associate { it.value to it.index }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun sorted(lists: List<TaskList>, order: Map<Long, Int>): List<TaskList> = lists.sortedWith(
|
||||||
|
compareBy<TaskList>({ it.accountName.lowercase() }, { order[it.id] ?: 0 }, { it.name.lowercase() })
|
||||||
|
.thenBy { it.name },
|
||||||
|
)
|
||||||
|
}
|
||||||
+4
-1
@@ -1,6 +1,9 @@
|
|||||||
package de.jeanlucmakiola.agendula.data.tasks
|
package de.jeanlucmakiola.agendula.data.tasks
|
||||||
|
|
||||||
/** A [ColumnReader] backed by a Map, so mappers test without a real Cursor. */
|
/**
|
||||||
|
* A [ColumnReader] over a Map of column values, such as the series columns a
|
||||||
|
* tick records, read with the same mappers as a cursor. Tests use it too.
|
||||||
|
*/
|
||||||
class MapColumnReader(private val values: Map<String, Any?>) : ColumnReader {
|
class MapColumnReader(private val values: Map<String, Any?>) : ColumnReader {
|
||||||
override fun getLong(name: String): Long? = (values[name] as? Number)?.toLong()
|
override fun getLong(name: String): Long? = (values[name] as? Number)?.toLong()
|
||||||
override fun getInt(name: String): Int? = (values[name] as? Number)?.toInt()
|
override fun getInt(name: String): Int? = (values[name] as? Number)?.toInt()
|
||||||
+23
-13
@@ -1,5 +1,6 @@
|
|||||||
package de.jeanlucmakiola.agendula.data.tasks
|
package de.jeanlucmakiola.agendula.data.tasks
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.agendula.domain.TaskReminder
|
||||||
import de.jeanlucmakiola.agendula.data.tasks.room.RoomTasksDataSource
|
import de.jeanlucmakiola.agendula.data.tasks.room.RoomTasksDataSource
|
||||||
import de.jeanlucmakiola.agendula.domain.Task
|
import de.jeanlucmakiola.agendula.domain.Task
|
||||||
import de.jeanlucmakiola.agendula.domain.TaskForm
|
import de.jeanlucmakiola.agendula.domain.TaskForm
|
||||||
@@ -34,24 +35,26 @@ class ModeRoutingTasksDataSource(
|
|||||||
override fun tasks(query: TaskQuery): List<Task> = active().tasks(query)
|
override fun tasks(query: TaskQuery): List<Task> = active().tasks(query)
|
||||||
override fun task(taskId: Long): Task? = active().task(taskId)
|
override fun task(taskId: Long): Task? = active().task(taskId)
|
||||||
override fun task(taskId: Long, occurrenceStart: Instant?): Task? = active().task(taskId, occurrenceStart)
|
override fun task(taskId: Long, occurrenceStart: Instant?): Task? = active().task(taskId, occurrenceStart)
|
||||||
override fun updateSeries(seriesId: Long, occurrenceStart: Instant, form: TaskForm) =
|
override fun updateSeries(seriesId: Long, occurrenceStart: Instant, form: TaskForm, reminders: List<TaskReminder>?) =
|
||||||
active().updateSeries(seriesId, occurrenceStart, form)
|
active().updateSeries(seriesId, occurrenceStart, form, reminders)
|
||||||
override fun splitSeries(seriesId: Long, occurrenceStart: Instant, form: TaskForm): Long =
|
override fun splitSeries(seriesId: Long, occurrenceStart: Instant, form: TaskForm, reminders: List<TaskReminder>?): Long =
|
||||||
active().splitSeries(seriesId, occurrenceStart, form)
|
active().splitSeries(seriesId, occurrenceStart, form, reminders)
|
||||||
override fun deleteOccurrence(seriesId: Long, occurrenceStart: Instant) =
|
override fun deleteOccurrence(seriesId: Long, occurrenceStart: Instant) =
|
||||||
active().deleteOccurrence(seriesId, occurrenceStart)
|
active().deleteOccurrence(seriesId, occurrenceStart)
|
||||||
override fun deleteFollowing(seriesId: Long, occurrenceStart: Instant) =
|
override fun deleteFollowing(seriesId: Long, occurrenceStart: Instant) =
|
||||||
active().deleteFollowing(seriesId, occurrenceStart)
|
active().deleteFollowing(seriesId, occurrenceStart)
|
||||||
override fun subtasks(parentTaskId: Long): List<Task> = active().subtasks(parentTaskId)
|
override fun subtasks(parentTaskId: Long): List<Task> = active().subtasks(parentTaskId)
|
||||||
override fun insertTask(form: TaskForm): Long = active().insertTask(form)
|
override fun subtaskIds(parentTaskId: Long): List<Long> = active().subtaskIds(parentTaskId)
|
||||||
override fun updateTask(taskId: Long, form: TaskForm) = active().updateTask(taskId, form)
|
override fun deleteWithSubtasks(taskId: Long) = active().deleteWithSubtasks(taskId)
|
||||||
|
override fun insertTask(form: TaskForm, reminders: List<TaskReminder>?): Long = active().insertTask(form, reminders)
|
||||||
|
override fun updateTask(taskId: Long, form: TaskForm, reminders: List<TaskReminder>?) =
|
||||||
|
active().updateTask(taskId, form, reminders)
|
||||||
|
|
||||||
override fun updateInstance(taskId: Long, occurrenceStart: Instant, form: TaskForm) =
|
override fun updateInstance(taskId: Long, occurrenceStart: Instant, form: TaskForm, reminders: List<TaskReminder>?) =
|
||||||
active().updateInstance(taskId, occurrenceStart, form)
|
active().updateInstance(taskId, occurrenceStart, form, reminders)
|
||||||
|
|
||||||
override fun setAlarm(taskId: Long, minutesBeforeDue: Int?) = active().setAlarm(taskId, minutesBeforeDue)
|
|
||||||
override fun alarms(): Map<Long, TaskReminder> = active().alarms()
|
|
||||||
override fun reminders(): Map<Long, List<TaskReminder>> = active().reminders()
|
override fun reminders(): Map<Long, List<TaskReminder>> = active().reminders()
|
||||||
|
override fun reminders(taskId: Long): List<TaskReminder>? = active().reminders(taskId)
|
||||||
override fun setReminders(taskId: Long, reminders: List<TaskReminder>) =
|
override fun setReminders(taskId: Long, reminders: List<TaskReminder>) =
|
||||||
active().setReminders(taskId, reminders)
|
active().setReminders(taskId, reminders)
|
||||||
override fun exportTasks(listId: Long): List<ExportTask> = active().exportTasks(listId)
|
override fun exportTasks(listId: Long): List<ExportTask> = active().exportTasks(listId)
|
||||||
@@ -65,6 +68,7 @@ class ModeRoutingTasksDataSource(
|
|||||||
active().setCancelledInstance(taskId, occurrenceStart, cancelled)
|
active().setCancelledInstance(taskId, occurrenceStart, cancelled)
|
||||||
|
|
||||||
override fun deleteTask(taskId: Long) = active().deleteTask(taskId)
|
override fun deleteTask(taskId: Long) = active().deleteTask(taskId)
|
||||||
|
override fun deleteOverride(taskId: Long, occurrenceStart: Instant) = active().deleteOverride(taskId, occurrenceStart)
|
||||||
override fun createLocalList(name: String, color: Int): Long = active().createLocalList(name, color)
|
override fun createLocalList(name: String, color: Int): Long = active().createLocalList(name, color)
|
||||||
override fun updateList(listId: Long, name: String, color: Int) = active().updateList(listId, name, color)
|
override fun updateList(listId: Long, name: String, color: Int) = active().updateList(listId, name, color)
|
||||||
override fun deleteList(listId: Long) = active().deleteList(listId)
|
override fun deleteList(listId: Long) = active().deleteList(listId)
|
||||||
@@ -79,16 +83,22 @@ class ModeRoutingTasksDataSource(
|
|||||||
* So the registration moves with the mode, and the switch itself counts as a
|
* So the registration moves with the mode, and the switch itself counts as a
|
||||||
* change: the data underneath every live flow has just been replaced.
|
* change: the data underneath every live flow has just been replaced.
|
||||||
*/
|
*/
|
||||||
override fun registerObserver(onChange: () -> Unit): AutoCloseable {
|
override fun registerObserver(onChange: () -> Unit): AutoCloseable =
|
||||||
|
follow(onChange) { it.registerObserver(onChange) }
|
||||||
|
|
||||||
|
override fun registerTaskObserver(onChange: () -> Unit): AutoCloseable =
|
||||||
|
follow(onChange) { it.registerTaskObserver(onChange) }
|
||||||
|
|
||||||
|
private fun follow(onChange: () -> Unit, register: (TasksDataSource) -> AutoCloseable): AutoCloseable {
|
||||||
val lock = Any()
|
val lock = Any()
|
||||||
var closed = false
|
var closed = false
|
||||||
var handle: AutoCloseable? = runCatching { active().registerObserver(onChange) }.getOrNull()
|
var handle: AutoCloseable? = runCatching { register(active()) }.getOrNull()
|
||||||
|
|
||||||
val modeHandle = resolver.onModeChanged {
|
val modeHandle = resolver.onModeChanged {
|
||||||
synchronized(lock) {
|
synchronized(lock) {
|
||||||
if (!closed) {
|
if (!closed) {
|
||||||
handle?.let { runCatching { it.close() } }
|
handle?.let { runCatching { it.close() } }
|
||||||
handle = runCatching { active().registerObserver(onChange) }.getOrNull()
|
handle = runCatching { register(active()) }.getOrNull()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
onChange()
|
onChange()
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
package de.jeanlucmakiola.agendula.data.tasks
|
package de.jeanlucmakiola.agendula.data.tasks
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.IntentFilter
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
@@ -26,6 +29,9 @@ interface ProviderEnvironment {
|
|||||||
|
|
||||||
/** [packageName]'s own app name, or null when it cannot be read. */
|
/** [packageName]'s own app name, or null when it cannot be read. */
|
||||||
fun appLabel(packageName: String): String?
|
fun appLabel(packageName: String): String?
|
||||||
|
|
||||||
|
/** Calls [listener] whenever an app is installed, updated or removed, which may change [packageDeclaring]'s answer. */
|
||||||
|
fun onPackagesChanged(listener: () -> Unit) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Singleton
|
@Singleton
|
||||||
@@ -43,4 +49,19 @@ class AndroidProviderEnvironment @Inject constructor(
|
|||||||
val pm = context.packageManager
|
val pm = context.packageManager
|
||||||
pm.getApplicationLabel(pm.getApplicationInfo(packageName, 0)).toString()
|
pm.getApplicationLabel(pm.getApplicationInfo(packageName, 0)).toString()
|
||||||
}.getOrNull()
|
}.getOrNull()
|
||||||
|
|
||||||
|
override fun onPackagesChanged(listener: () -> Unit) {
|
||||||
|
val filter = IntentFilter().apply {
|
||||||
|
addAction(Intent.ACTION_PACKAGE_ADDED)
|
||||||
|
addAction(Intent.ACTION_PACKAGE_REMOVED)
|
||||||
|
addAction(Intent.ACTION_PACKAGE_REPLACED)
|
||||||
|
addAction(Intent.ACTION_PACKAGE_CHANGED)
|
||||||
|
addDataScheme("package")
|
||||||
|
}
|
||||||
|
val receiver = object : BroadcastReceiver() {
|
||||||
|
override fun onReceive(context: Context, intent: Intent) = listener()
|
||||||
|
}
|
||||||
|
// System broadcasts still reach a receiver that is not exported.
|
||||||
|
ContextCompat.registerReceiver(context, receiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
package de.jeanlucmakiola.agendula.data.tasks
|
package de.jeanlucmakiola.agendula.data.tasks
|
||||||
|
|
||||||
import java.util.concurrent.CopyOnWriteArrayList
|
import java.util.concurrent.CopyOnWriteArrayList
|
||||||
|
import java.util.concurrent.atomic.AtomicLong
|
||||||
|
import java.util.concurrent.atomic.AtomicReference
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
@@ -34,6 +36,14 @@ class ProviderResolver @Inject constructor(
|
|||||||
|
|
||||||
private val modeListeners = CopyOnWriteArrayList<() -> Unit>()
|
private val modeListeners = CopyOnWriteArrayList<() -> Unit>()
|
||||||
|
|
||||||
|
/** Bumped by every install, update or removal; a cached lookup of an older one is stale. */
|
||||||
|
private val packagesGeneration = AtomicLong()
|
||||||
|
private val external = AtomicReference<Pair<Long, TaskProvider?>?>(null)
|
||||||
|
|
||||||
|
init {
|
||||||
|
environment.onPackagesChanged { packagesGeneration.incrementAndGet() }
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The user's explicit choice, or `null` while they have not made one (which is
|
* The user's explicit choice, or `null` while they have not made one (which is
|
||||||
* the normal state — most people never open Settings). Kept as a plain field
|
* the normal state — most people never open Settings). Kept as a plain field
|
||||||
@@ -93,13 +103,32 @@ class ProviderResolver @Inject constructor(
|
|||||||
* Deliberately cheap and synchronous: a PackageManager lookup and a permission
|
* Deliberately cheap and synchronous: a PackageManager lookup and a permission
|
||||||
* check, no database probe. Settings overrides it either way.
|
* check, no database probe. Settings overrides it either way.
|
||||||
*/
|
*/
|
||||||
fun autoMode(): StorageMode {
|
fun autoMode(external: TaskProvider? = resolveExternal()): StorageMode =
|
||||||
|
if (external != null && hasPermission(external)) StorageMode.EXTERNAL else StorageMode.OWN
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The store [stored] names, or [autoMode]'s when none, with the external
|
||||||
|
* provider's authority when that is the store; one lookup at most.
|
||||||
|
*/
|
||||||
|
fun active(stored: StorageMode? = storageMode): Pair<StorageMode, String?> {
|
||||||
|
if (stored == StorageMode.OWN) return StorageMode.OWN to null
|
||||||
val external = resolveExternal()
|
val external = resolveExternal()
|
||||||
return if (external != null && hasPermission(external)) StorageMode.EXTERNAL else StorageMode.OWN
|
val mode = stored ?: autoMode(external)
|
||||||
|
return mode to external?.authority?.takeIf { mode == StorageMode.EXTERNAL }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The first installed external candidate, or `null` when none is present. */
|
/**
|
||||||
|
* The first installed external candidate, or `null` when none is present.
|
||||||
|
* Looked up once per change of the installed apps, as every read of the
|
||||||
|
* active store, its scope included, asks it.
|
||||||
|
*/
|
||||||
fun resolveExternal(): TaskProvider? {
|
fun resolveExternal(): TaskProvider? {
|
||||||
|
val generation = packagesGeneration.get()
|
||||||
|
external.get()?.takeIf { it.first == generation }?.let { return it.second }
|
||||||
|
return lookupExternal().also { external.set(generation to it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun lookupExternal(): TaskProvider? {
|
||||||
for (candidate in EXTERNAL_CANDIDATES) {
|
for (candidate in EXTERNAL_CANDIDATES) {
|
||||||
val packageName = environment.packageDeclaring(candidate.authority) ?: continue
|
val packageName = environment.packageDeclaring(candidate.authority) ?: continue
|
||||||
return candidate.copy(packageName = packageName)
|
return candidate.copy(packageName = packageName)
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package de.jeanlucmakiola.agendula.data.tasks
|
||||||
|
|
||||||
|
/** SQLite's default bound-argument limit on older Android releases. */
|
||||||
|
internal const val MAX_SQL_ARGS = 999
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `idColumn IN (…)` selections over [ids], each with its arguments and
|
||||||
|
* [filterArgs] after them, in chunks that keep every query within [limit]
|
||||||
|
* bound arguments.
|
||||||
|
*/
|
||||||
|
internal fun inSelections(
|
||||||
|
idColumn: String,
|
||||||
|
ids: Collection<Long>,
|
||||||
|
filter: String? = null,
|
||||||
|
filterArgs: List<String> = emptyList(),
|
||||||
|
limit: Int = MAX_SQL_ARGS,
|
||||||
|
): List<Pair<String, Array<String>>> = ids.distinct().chunked(limit - filterArgs.size).map { chunk ->
|
||||||
|
val selection = buildString {
|
||||||
|
append("$idColumn IN (${chunk.joinToString(",") { "?" }})")
|
||||||
|
if (filter != null) append(" AND ($filter)")
|
||||||
|
}
|
||||||
|
selection to (chunk.map(Long::toString) + filterArgs).toTypedArray()
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package de.jeanlucmakiola.agendula.data.tasks
|
||||||
|
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.FlowPreview
|
||||||
|
import kotlinx.coroutines.channels.Channel
|
||||||
|
import kotlinx.coroutines.flow.debounce
|
||||||
|
import kotlinx.coroutines.flow.receiveAsFlow
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs [action] once per burst of store changes: [register] hooks the store's
|
||||||
|
* observer, and [request] asks for a pass without one. Started at most once.
|
||||||
|
*/
|
||||||
|
class StoreChangeDebouncer(
|
||||||
|
private val scope: CoroutineScope,
|
||||||
|
private val delayMillis: Long,
|
||||||
|
private val register: (onChange: () -> Unit) -> AutoCloseable,
|
||||||
|
private val action: suspend () -> Unit,
|
||||||
|
) {
|
||||||
|
private val requests = Channel<Unit>(Channel.CONFLATED)
|
||||||
|
private val started = AtomicBoolean(false)
|
||||||
|
|
||||||
|
/** @return whether this call started it; false when it already was. */
|
||||||
|
@OptIn(FlowPreview::class)
|
||||||
|
fun start(): Boolean {
|
||||||
|
if (!started.compareAndSet(false, true)) return false
|
||||||
|
runCatching { register { requests.trySend(Unit) } }
|
||||||
|
scope.launch(Dispatchers.IO) {
|
||||||
|
requests.receiveAsFlow().debounce(delayMillis).collect { runCatching { action() } }
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun request() {
|
||||||
|
requests.trySend(Unit)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
package de.jeanlucmakiola.agendula.data.tasks
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.agendula.data.prefs.Settings
|
||||||
|
import de.jeanlucmakiola.agendula.data.reminders.ReminderPlanner
|
||||||
|
import de.jeanlucmakiola.agendula.domain.Task
|
||||||
|
import de.jeanlucmakiola.agendula.domain.TaskDates
|
||||||
|
import de.jeanlucmakiola.agendula.domain.TaskEnd
|
||||||
|
import de.jeanlucmakiola.agendula.domain.TaskForm
|
||||||
|
import de.jeanlucmakiola.agendula.domain.TaskReminder
|
||||||
|
import de.jeanlucmakiola.agendula.domain.calendarDate
|
||||||
|
import de.jeanlucmakiola.agendula.domain.forDates
|
||||||
|
import java.time.ZoneId
|
||||||
|
import kotlin.time.Instant
|
||||||
|
|
||||||
|
internal object StoredReminders {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The reminders to store for [form], given the task as it was.
|
||||||
|
*
|
||||||
|
* A date the task gets in this write brings the list's or the app's
|
||||||
|
* default for it *as the task's own reminders*. The default is this
|
||||||
|
* device's setting, which nothing else can see; stored on the task, it
|
||||||
|
* travels with it to the server and fires on every client. The cost is
|
||||||
|
* tasks.org's: changing the default later does not reach the tasks that
|
||||||
|
* already have it.
|
||||||
|
*
|
||||||
|
* A task getting its first date takes the defaults only when the form
|
||||||
|
* names no reminder; one that already had a date takes those of the new
|
||||||
|
* date that no reminder of the form counts from, and those of a date
|
||||||
|
* whose defaults had all rung when it moved — see [revived]. Otherwise the form is
|
||||||
|
* kept, so an edit that clears every reminder means "use the default
|
||||||
|
* here" as before.
|
||||||
|
*
|
||||||
|
* The form's reminders are already of its kind, timed or all-day — see
|
||||||
|
* [switched]. Reminders the editor [chose][TaskForm.remindersChosen] are
|
||||||
|
* kept as they are: it showed these defaults already.
|
||||||
|
*/
|
||||||
|
fun of(form: TaskForm, current: Task?, settings: Settings, now: Long, zone: ZoneId): List<TaskReminder> =
|
||||||
|
forSave(form, current, settings, now, zone).reminders
|
||||||
|
|
||||||
|
/** [of] and [pastDefaults] for one save, from one reading of the defaults. */
|
||||||
|
fun forSave(form: TaskForm, current: Task?, settings: Settings, now: Long, zone: ZoneId): ForSave {
|
||||||
|
val past = if (form.remindersChosen) {
|
||||||
|
ForSave(form.reminders.map { it.lead }.distinct(), form.pastReminders)
|
||||||
|
} else {
|
||||||
|
// In the frame the form holds them in, so an untouched untimed end does not read as moved.
|
||||||
|
val defaulted = defaulted(
|
||||||
|
form,
|
||||||
|
current?.formValueOf(TaskEnd.START),
|
||||||
|
current?.formValueOf(TaskEnd.DUE),
|
||||||
|
current?.isAllDay ?: form.isAllDay,
|
||||||
|
settings,
|
||||||
|
now,
|
||||||
|
zone,
|
||||||
|
current?.untimed,
|
||||||
|
)
|
||||||
|
ForSave(defaulted.reminders, defaulted.past)
|
||||||
|
}
|
||||||
|
return past.copy(pastDefaults = past.pastDefaults.filterNot { form.startsNow && it.fromStart })
|
||||||
|
}
|
||||||
|
|
||||||
|
/** See [forSave]. */
|
||||||
|
data class ForSave(val reminders: List<TaskReminder>, val pastDefaults: List<TaskReminder>)
|
||||||
|
|
||||||
|
/** [of] for a task whose dates were [start] and [due], whatever the form chose. */
|
||||||
|
fun withDefaults(
|
||||||
|
form: TaskForm,
|
||||||
|
start: Instant?,
|
||||||
|
due: Instant?,
|
||||||
|
wasAllDay: Boolean,
|
||||||
|
settings: Settings,
|
||||||
|
now: Long,
|
||||||
|
zone: ZoneId,
|
||||||
|
wasUntimed: TaskEnd? = null,
|
||||||
|
): List<TaskReminder> = defaulted(form, start, due, wasAllDay, settings, now, zone, wasUntimed).reminders
|
||||||
|
|
||||||
|
/** The defaults [withDefaults] leaves out of [form] as already past. */
|
||||||
|
fun leftOutAsPast(
|
||||||
|
form: TaskForm,
|
||||||
|
start: Instant?,
|
||||||
|
due: Instant?,
|
||||||
|
wasAllDay: Boolean,
|
||||||
|
settings: Settings,
|
||||||
|
now: Long,
|
||||||
|
zone: ZoneId,
|
||||||
|
wasUntimed: TaskEnd? = null,
|
||||||
|
): List<TaskReminder> = defaulted(form, start, due, wasAllDay, settings, now, zone, wasUntimed).past
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What the defaults make of [form] for a task whose dates were [start] and
|
||||||
|
* [due]: [withDefaults], [leftOutAsPast], and whether any defaults applied
|
||||||
|
* ([freshAnchors] not empty), from one reading.
|
||||||
|
*/
|
||||||
|
fun defaulted(
|
||||||
|
form: TaskForm,
|
||||||
|
start: Instant?,
|
||||||
|
due: Instant?,
|
||||||
|
wasAllDay: Boolean,
|
||||||
|
settings: Settings,
|
||||||
|
now: Long,
|
||||||
|
zone: ZoneId,
|
||||||
|
wasUntimed: TaskEnd? = null,
|
||||||
|
): Defaulted {
|
||||||
|
val fresh = freshAnchors(form, start, due, wasAllDay, settings, now, zone, wasUntimed)
|
||||||
|
val reminders = withDefaults(form, start, due, fresh, settings, now, zone, keepPast = false)
|
||||||
|
val all = withDefaults(form, start, due, fresh, settings, now, zone, keepPast = true)
|
||||||
|
return Defaulted(reminders, all - reminders.toSet(), applied = fresh.isNotEmpty())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** See [defaulted]. */
|
||||||
|
data class Defaulted(val reminders: List<TaskReminder>, val past: List<TaskReminder>, val applied: Boolean)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The defaults [of] leaves out of [form] as already past, for a save to ring
|
||||||
|
* at once instead (#106): those the editor noted, or for a form it did not
|
||||||
|
* choose, the ones [withDefaults] leaves out. Not those from a start of
|
||||||
|
* [now][TaskForm.startsNow]: that start was never the user's to be reminded of.
|
||||||
|
*/
|
||||||
|
fun pastDefaults(form: TaskForm, current: Task?, settings: Settings, now: Long, zone: ZoneId): List<TaskReminder> =
|
||||||
|
forSave(form, current, settings, now, zone).pastDefaults
|
||||||
|
|
||||||
|
private fun withDefaults(
|
||||||
|
form: TaskForm,
|
||||||
|
start: Instant?,
|
||||||
|
due: Instant?,
|
||||||
|
fresh: Set<Boolean>,
|
||||||
|
settings: Settings,
|
||||||
|
now: Long,
|
||||||
|
zone: ZoneId,
|
||||||
|
keepPast: Boolean,
|
||||||
|
): List<TaskReminder> {
|
||||||
|
val wanted = form.reminders.map { it.lead }.distinct()
|
||||||
|
if (fresh.isEmpty()) return wanted
|
||||||
|
val defaults = defaultsFor(form, settings, now, zone, keepPast)
|
||||||
|
if (anchorsOf(start, due).isEmpty() || wanted.isEmpty()) return wanted.ifEmpty { defaults }
|
||||||
|
val named = namedEnds(form, wanted)
|
||||||
|
return wanted + defaults.filter { it.fromStart in fresh && it.fromStart !in named }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The dates whose defaults [withDefaults] brings in, as [TaskReminder.fromStart]:
|
||||||
|
* those the task gains, and those [revived]. Empty = the defaults play no part.
|
||||||
|
*/
|
||||||
|
fun freshAnchors(
|
||||||
|
form: TaskForm,
|
||||||
|
start: Instant?,
|
||||||
|
due: Instant?,
|
||||||
|
wasAllDay: Boolean,
|
||||||
|
settings: Settings,
|
||||||
|
now: Long,
|
||||||
|
zone: ZoneId,
|
||||||
|
wasUntimed: TaskEnd? = null,
|
||||||
|
): Set<Boolean> {
|
||||||
|
val wanted = form.reminders.map { it.lead }.distinct()
|
||||||
|
val gained = anchorsOf(form.start, form.due) - anchorsOf(start, due)
|
||||||
|
val was = TaskDates(start, due, wasAllDay, wasUntimed)
|
||||||
|
return gained + revived(form, was, wanted, settings, now, zone)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [reminders] for [form] once it has switched between timed and all-day.
|
||||||
|
* Reminders that are exactly the old kind's default become the new kind's;
|
||||||
|
* the rest keep what still means something: whole days, rounded to them on
|
||||||
|
* an all-day task.
|
||||||
|
*/
|
||||||
|
fun switched(
|
||||||
|
reminders: List<TaskReminder>,
|
||||||
|
form: TaskForm,
|
||||||
|
settings: Settings,
|
||||||
|
now: Long,
|
||||||
|
zone: ZoneId,
|
||||||
|
): List<TaskReminder> {
|
||||||
|
if (reminders.isEmpty()) return reminders
|
||||||
|
return keptAcrossSwitch(reminders, form, settings) ?: defaultsFor(form, settings, now, zone)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What [switched] keeps of [reminders], or null when it swaps in the new kind's defaults. */
|
||||||
|
fun keptAcrossSwitch(reminders: List<TaskReminder>, form: TaskForm, settings: Settings): List<TaskReminder>? {
|
||||||
|
val oldDefaults = settings.defaultRemindersFor(form.listId, !form.isAllDay)
|
||||||
|
val ofItsDates = oldDefaults.forDates(form.start != null, form.due != null)
|
||||||
|
if (reminders.toSet().let { it == oldDefaults.toSet() || it == ofItsDates.toSet() }) return null
|
||||||
|
val kept = if (form.isAllDay) {
|
||||||
|
reminders.map { it.inWholeDays() }
|
||||||
|
} else {
|
||||||
|
reminders.filter { it.allDay.minuteOfDay == null }
|
||||||
|
}
|
||||||
|
return kept.distinct().ifEmpty { null }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The dates of a one-off task that moved after every default of theirs
|
||||||
|
* had rung: a task saved then was left without them as past (#121), so
|
||||||
|
* the new date brings them like a date the task gains. Only on a task
|
||||||
|
* with reminders of its own and none from that date — no reminders at
|
||||||
|
* all is the planner's default or turned off, and either holds.
|
||||||
|
*/
|
||||||
|
private fun revived(
|
||||||
|
form: TaskForm,
|
||||||
|
was: TaskDates,
|
||||||
|
wanted: List<TaskReminder>,
|
||||||
|
settings: Settings,
|
||||||
|
now: Long,
|
||||||
|
zone: ZoneId,
|
||||||
|
): Set<Boolean> {
|
||||||
|
if (form.rrule != null || wanted.isEmpty()) return emptySet()
|
||||||
|
val named = namedEnds(form, wanted)
|
||||||
|
val defaults = settings.defaultRemindersFor(form.listId, was.isAllDay).forDates(was.start != null, was.due != null)
|
||||||
|
fun revived(fromStart: Boolean, before: Instant?, isNow: Instant?): Boolean {
|
||||||
|
if (before == null || isNow == null || fromStart in named) return false
|
||||||
|
val moved = if (was.isAllDay == form.isAllDay) {
|
||||||
|
isNow != before
|
||||||
|
} else {
|
||||||
|
isNow.calendarDate(form.isAllDay, zone) != before.calendarDate(was.isAllDay, zone)
|
||||||
|
}
|
||||||
|
val leads = defaults.filter { it.fromStart == fromStart }
|
||||||
|
return moved && leads.isNotEmpty() && leads.all {
|
||||||
|
ReminderPlanner.ringsAt(was, fromStart, it.minutesBefore, settings.allDayReminderMinuteOfDay, zone) < now
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return setOfNotNull(
|
||||||
|
true.takeIf { revived(true, was.start, form.start) },
|
||||||
|
false.takeIf { revived(false, was.due, form.due) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The dates a reminder can count from, as [TaskReminder.fromStart]. */
|
||||||
|
private fun anchorsOf(start: Any?, due: Any?): Set<Boolean> =
|
||||||
|
setOfNotNull(true.takeIf { start != null }, false.takeIf { due != null })
|
||||||
|
|
||||||
|
/** The dates [wanted] count from on [form], as [TaskReminder.fromStart]. */
|
||||||
|
private fun namedEnds(form: TaskForm, wanted: List<TaskReminder>): Set<Boolean> {
|
||||||
|
val dates = TaskDates(form.start, form.due, form.isAllDay)
|
||||||
|
return wanted.map { dates.reminderEnd(it.fromStart) == TaskEnd.START }.toSet()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The defaults [form] takes, of the dates it has (see [forDates]). A one-off
|
||||||
|
* task leaves out what is already past and any from a start of
|
||||||
|
* [now][TaskForm.startsNow], which would ring at once.
|
||||||
|
*/
|
||||||
|
private fun defaultsFor(
|
||||||
|
form: TaskForm,
|
||||||
|
settings: Settings,
|
||||||
|
now: Long,
|
||||||
|
zone: ZoneId,
|
||||||
|
keepPast: Boolean = false,
|
||||||
|
): List<TaskReminder> =
|
||||||
|
settings.defaultRemindersFor(form.listId, form.isAllDay)
|
||||||
|
.forDates(form.start != null, form.due != null)
|
||||||
|
.filter { reminder ->
|
||||||
|
if (form.startsNow && reminder.fromStart && form.rrule == null) return@filter false
|
||||||
|
keepPast || form.rrule != null || ReminderPlanner.ringsAt(
|
||||||
|
TaskDates(form.start, form.due, form.isAllDay, form.untimed),
|
||||||
|
reminder.fromStart,
|
||||||
|
reminder.minutesBefore,
|
||||||
|
settings.allDayReminderMinuteOfDay,
|
||||||
|
zone,
|
||||||
|
) >= now
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,320 @@
|
|||||||
|
package de.jeanlucmakiola.agendula.data.tasks
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.agendula.data.tasks.TasksContract.Tasks
|
||||||
|
import de.jeanlucmakiola.agendula.domain.TaskEnd
|
||||||
|
import de.jeanlucmakiola.agendula.domain.TaskStatus
|
||||||
|
import de.jeanlucmakiola.agendula.domain.isClosed
|
||||||
|
import de.jeanlucmakiola.agendula.domain.recurrence.ExpansionWindow
|
||||||
|
import de.jeanlucmakiola.agendula.domain.recurrence.RecurrenceExpander
|
||||||
|
import de.jeanlucmakiola.agendula.domain.recurrence.RecurrenceSpec
|
||||||
|
import de.jeanlucmakiola.agendula.domain.recurrence.dateZone
|
||||||
|
import de.jeanlucmakiola.agendula.domain.statusFromInt
|
||||||
|
import de.jeanlucmakiola.agendula.domain.untimedMoved
|
||||||
|
import de.jeanlucmakiola.agendula.domain.zoneOr
|
||||||
|
import java.time.Duration
|
||||||
|
import java.time.LocalDateTime
|
||||||
|
import java.time.ZoneId
|
||||||
|
import java.time.temporal.ChronoUnit
|
||||||
|
import kotlin.time.Duration.Companion.days
|
||||||
|
import kotlin.time.Instant
|
||||||
|
|
||||||
|
private const val MILLIS_PER_SECOND = 1000L
|
||||||
|
private const val MILLIS_PER_DAY = 24L * 60 * 60 * 1000
|
||||||
|
|
||||||
|
/** A sub-task's progress, which a routine's next occurrence starts without. */
|
||||||
|
internal data class SubtaskState(val status: TaskStatus, val percent: Int?, val completedAt: Long?) {
|
||||||
|
/** Open with nothing done yet: what a reset leaves. */
|
||||||
|
val isFresh: Boolean get() = status == TaskStatus.NEEDS_ACTION && (percent ?: 0) == 0 && completedAt == null
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val FRESH = SubtaskState(TaskStatus.NEEDS_ACTION, null, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A sub-task's own start and due, as epoch millis. */
|
||||||
|
internal data class SubtaskDates(val start: Long?, val due: Long?) {
|
||||||
|
val isEmpty: Boolean get() = start == null && due == null
|
||||||
|
|
||||||
|
/** The same dates as a store keeps them: to the second, or for an all-day task to the day. */
|
||||||
|
fun sameAs(other: SubtaskDates, isAllDay: Boolean): Boolean {
|
||||||
|
fun unit(at: Long?) = at?.let { Math.floorDiv(it, if (isAllDay) MILLIS_PER_DAY else MILLIS_PER_SECOND) }
|
||||||
|
return unit(start) == unit(other.start) && unit(due) == unit(other.due)
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val NONE = SubtaskDates(null, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A sub-task as [SubtaskReset] sees it; [recurring] also covers a copy a tick of
|
||||||
|
* a recurring one left. [lastModified] dates progress that has no completion time.
|
||||||
|
*/
|
||||||
|
internal class SubtaskNode(
|
||||||
|
val id: Long,
|
||||||
|
val recurring: Boolean,
|
||||||
|
val state: SubtaskState,
|
||||||
|
val dates: SubtaskDates = SubtaskDates.NONE,
|
||||||
|
val isAllDay: Boolean = false,
|
||||||
|
val lastModified: Long? = null,
|
||||||
|
val untimed: TaskEnd? = null,
|
||||||
|
val timeZone: String? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** A sub-task [SubtaskReset] reset: its state and dates before, and the dates the reset gave it. */
|
||||||
|
internal data class ResetSubtask(
|
||||||
|
val id: Long,
|
||||||
|
val prior: SubtaskState,
|
||||||
|
val priorDates: SubtaskDates = SubtaskDates.NONE,
|
||||||
|
val dates: SubtaskDates = priorDates,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** A reset sub-task as it is now, for [SubtaskReset.toRestore]. */
|
||||||
|
internal class SubtaskNow(val state: SubtaskState, val dates: SubtaskDates, val isAllDay: Boolean)
|
||||||
|
|
||||||
|
/** What moving back writes to one sub-task: its [state] and its [dates], each only where non-null. */
|
||||||
|
internal data class SubtaskBack(val id: Long, val state: SubtaskState?, val dates: SubtaskDates?)
|
||||||
|
|
||||||
|
/** What moving a series back does with its reset sub-tasks, and which ones changed since and keep that. */
|
||||||
|
internal class SubtaskRestore(val restore: List<SubtaskBack>, val changed: List<Long>)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How far a series moved in [seriesZone]. A timed sub-task moves by the series'
|
||||||
|
* wall-clock change in [timedZone], so it keeps its offset to the routine across
|
||||||
|
* a DST change whatever zone it is stored in; an all-day one moves by the change
|
||||||
|
* of the series' calendar date.
|
||||||
|
*/
|
||||||
|
internal class SeriesShift(from: Long, to: Long, seriesZone: ZoneId, private val timedZone: ZoneId = seriesZone) {
|
||||||
|
private val delta = Duration.between(local(from, seriesZone), local(to, seriesZone))
|
||||||
|
private val days = ChronoUnit.DAYS.between(local(from, seriesZone).toLocalDate(), local(to, seriesZone).toLocalDate())
|
||||||
|
|
||||||
|
/** [at] moved along. */
|
||||||
|
fun apply(at: Long, isAllDay: Boolean): Long {
|
||||||
|
val zone = if (isAllDay) dateZone(isAllDay = true, timeZone = null) else timedZone
|
||||||
|
val moved = if (isAllDay) local(at, zone).plusDays(days) else local(at, zone).plus(delta)
|
||||||
|
return moved.atZone(zone).toInstant().toEpochMilli()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An untimed [end] at [at], stored in [timeZone], moved by whole days: the series' change of date. */
|
||||||
|
fun applyUntimed(end: TaskEnd, at: Long, timeZone: String?): Long =
|
||||||
|
untimedMoved(end, Instant.fromEpochMilliseconds(at), days, timeZone, zoneOr(timeZone)).toEpochMilliseconds()
|
||||||
|
|
||||||
|
/** [at] on [end] of a sub-task moved along, by whole days where that end has no time. */
|
||||||
|
fun apply(at: Long, end: TaskEnd, node: SubtaskNode): Long =
|
||||||
|
if (!node.isAllDay && node.untimed == end) applyUntimed(end, at, node.timeZone) else apply(at, node.isAllDay)
|
||||||
|
|
||||||
|
private fun local(at: Long, zone: ZoneId) = LocalDateTime.ofInstant(java.time.Instant.ofEpochMilli(at), zone)
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
/**
|
||||||
|
* The shift of a series read in its own zone ([dateZone]). An all-day
|
||||||
|
* series' is UTC, where a timed sub-task would drift across DST, so
|
||||||
|
* that one moves in [floating], the device's zone.
|
||||||
|
*/
|
||||||
|
fun of(from: Long, to: Long, isAllDay: Boolean, timeZone: String?, floating: ZoneId): SeriesShift {
|
||||||
|
val seriesZone = dateZone(isAllDay, timeZone, floating)
|
||||||
|
return SeriesShift(from, to, seriesZone, timedZone = if (isAllDay) floating else seriesZone)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a routine's sub-tasks do when its series moves on to the next occurrence
|
||||||
|
* (#160): the ones completed or in progress start over, as in tasks.org, dated
|
||||||
|
* ones move along with the routine, and moving the series back gives them their
|
||||||
|
* state and dates again.
|
||||||
|
*/
|
||||||
|
internal object SubtaskReset {
|
||||||
|
|
||||||
|
/** Only bounds the search for a next occurrence. */
|
||||||
|
private val LOOKAHEAD = (366 * 1000).days
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The `X-` property Agendula puts on the copy a provider tick of a recurring
|
||||||
|
* sub-task left, valued with the UID of the parent it sits under, so any
|
||||||
|
* device knows it for one while it stays there.
|
||||||
|
*/
|
||||||
|
const val COPY_MARKER = "X-AGENDULA-TICK-COPY"
|
||||||
|
|
||||||
|
/** The provider `properties` mimetype DAVx5 keeps unknown properties under, and round-trips. */
|
||||||
|
const val UNKNOWN_PROPERTY_MIMETYPE = "vnd.android.cursor.item/vnd.ical4android.unknown-property"
|
||||||
|
|
||||||
|
private val MARKER_JSON = Regex("""^\s*\[\s*"$COPY_MARKER"\s*,\s*"((?:[^"\\]|\\.)*)"""", RegexOption.IGNORE_CASE)
|
||||||
|
|
||||||
|
/** The marker for a copy under the parent [parentUid], as DAVx5 stores an unknown property: a JSON array of name and value. */
|
||||||
|
fun copyMarkerJson(parentUid: String): String =
|
||||||
|
"[\"$COPY_MARKER\",\"${parentUid.replace("\\", "\\\\").replace("\"", "\\\"")}\"]"
|
||||||
|
|
||||||
|
/** The parent UID an unknown-property row's JSON marks its task a copy under, or null when it is no marker. */
|
||||||
|
fun markerParentFromJson(json: String?): String? =
|
||||||
|
json?.let(MARKER_JSON::find)?.groupValues?.get(1)?.replace(Regex("""\\(.)"""), "$1")
|
||||||
|
|
||||||
|
/** The parent UID a stored residue's marker names, as a copy synced in from a provider install carries it. */
|
||||||
|
fun markerParentFromResidue(residue: String?): String? = residue?.lines()?.firstNotNullOfOrNull {
|
||||||
|
val line = it.trim()
|
||||||
|
val next = line.getOrNull(COPY_MARKER.length)
|
||||||
|
if (!line.startsWith(COPY_MARKER, ignoreCase = true) || (next != ':' && next != ';')) return@firstNotNullOfOrNull null
|
||||||
|
line.substringAfter(':').replace(Regex("""\\([\\;,])"""), "$1")
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether a record naming [copyParent] makes a task under [parentUid] a copy: only under the parent it came from. */
|
||||||
|
fun isCopyOf(copyParent: String?, parentUid: String?): Boolean = copyParent != null && copyParent == parentUid
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a provider row under [parentUid] is left alone as recurring: it has
|
||||||
|
* a rule, or it is a copy a tick of a recurring sibling left, known by the
|
||||||
|
* parent this install recorded for it ([knownParent]) or by its marker
|
||||||
|
* ([markerParent]), either only while it sits under that parent.
|
||||||
|
*/
|
||||||
|
fun recursOrCopy(rrule: String?, rdate: String?, knownParent: String?, markerParent: String?, parentUid: String?): Boolean =
|
||||||
|
!rrule.isNullOrBlank() || !rdate.isNullOrBlank() || isCopyOf(knownParent, parentUid) || isCopyOf(markerParent, parentUid)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [rows] grown by what [fetch] finds under the ids reached from [root] so
|
||||||
|
* far, asked once per id, until nothing new turns up: the sub-tasks filed in
|
||||||
|
* other lists than the one [rows] came from.
|
||||||
|
*/
|
||||||
|
fun <R> mergeSubtree(root: Long, rows: List<R>, id: (R) -> Long, parent: (R) -> Long?, fetch: (Set<Long>) -> List<R>): List<R> {
|
||||||
|
val all = LinkedHashMap<Long, R>().apply { rows.forEach { put(id(it), it) } }
|
||||||
|
val asked = HashSet<Long>()
|
||||||
|
while (true) {
|
||||||
|
val children = all.values.groupBy(parent)
|
||||||
|
val reached = linkedSetOf(root)
|
||||||
|
val queue = ArrayDeque(listOf(root))
|
||||||
|
while (queue.isNotEmpty()) {
|
||||||
|
children[queue.removeFirst()].orEmpty().map(id).filter(reached::add).forEach(queue::addLast)
|
||||||
|
}
|
||||||
|
val toAsk = reached - asked
|
||||||
|
if (toAsk.isEmpty()) return all.values.toList()
|
||||||
|
asked += toAsk
|
||||||
|
fetch(toAsk).forEach { all.putIfAbsent(id(it), it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where the occurrence a move closes began, for [toReset]'s `since`: one
|
||||||
|
* step of the move before its old anchor [from], [to] being the new one.
|
||||||
|
*/
|
||||||
|
fun cycleStart(from: Long, to: Long): Long = from - (to - from)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The sub-tasks under [parentId], all the way down, to reset: started ones,
|
||||||
|
* and with a [shift], dated ones too. A recurring one has a series of its
|
||||||
|
* own and is left alone with everything under it; a cancelled one stays as
|
||||||
|
* it is.
|
||||||
|
*
|
||||||
|
* With [since], a started one is only reset when it was completed, or for
|
||||||
|
* one in progress last changed, at or after it: during the cycle the move
|
||||||
|
* closes. A copy an earlier cycle left, which nothing marks as one, is left
|
||||||
|
* alone that way, and so is one with neither time to go by.
|
||||||
|
*/
|
||||||
|
fun toReset(
|
||||||
|
parentId: Long,
|
||||||
|
shift: SeriesShift? = null,
|
||||||
|
since: Long? = null,
|
||||||
|
children: (Long) -> List<SubtaskNode>,
|
||||||
|
): List<ResetSubtask> {
|
||||||
|
val seen = mutableSetOf(parentId)
|
||||||
|
val reset = mutableListOf<ResetSubtask>()
|
||||||
|
fun walk(id: Long) {
|
||||||
|
children(id).filter { !it.recurring && seen.add(it.id) }.forEach {
|
||||||
|
val started = !it.state.isFresh
|
||||||
|
val stamp = it.state.completedAt ?: it.lastModified
|
||||||
|
val earlier = started && since != null && (stamp == null || stamp < since)
|
||||||
|
val moves = shift != null && !it.dates.isEmpty
|
||||||
|
if (it.state.status != TaskStatus.CANCELLED && !earlier && (started || moves)) {
|
||||||
|
val dates = if (shift == null) it.dates else SubtaskDates(
|
||||||
|
it.dates.start?.let { at -> shift.apply(at, TaskEnd.START, it) },
|
||||||
|
it.dates.due?.let { at -> shift.apply(at, TaskEnd.DUE, it) },
|
||||||
|
)
|
||||||
|
reset += ResetSubtask(it.id, it.state, it.dates, dates)
|
||||||
|
}
|
||||||
|
walk(it.id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
walk(parentId)
|
||||||
|
return reset
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What moving back gives each reset sub-task: its state where it is still
|
||||||
|
* fresh, and its dates where they are still the ones the reset wrote. What
|
||||||
|
* changed since keeps the user's version and is listed as changed; a
|
||||||
|
* deleted sub-task is neither.
|
||||||
|
*/
|
||||||
|
fun toRestore(reset: List<ResetSubtask>, current: (Long) -> SubtaskNow?): SubtaskRestore {
|
||||||
|
val restore = mutableListOf<SubtaskBack>()
|
||||||
|
val changed = mutableListOf<Long>()
|
||||||
|
reset.forEach { entry ->
|
||||||
|
val now = current(entry.id) ?: return@forEach
|
||||||
|
val state = entry.prior.takeIf { now.state.isFresh }
|
||||||
|
val datesMoved = entry.dates != entry.priorDates
|
||||||
|
val dates = entry.priorDates.takeIf { datesMoved && now.dates.sameAs(entry.dates, now.isAllDay) }
|
||||||
|
if (state != null || dates != null) restore += SubtaskBack(entry.id, state, dates)
|
||||||
|
if (state == null || (datesMoved && dates == null)) changed += entry.id
|
||||||
|
}
|
||||||
|
return SubtaskRestore(restore, changed)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun encode(reset: List<ResetSubtask>): String = reset.joinToString(";") {
|
||||||
|
listOf(
|
||||||
|
it.id, it.prior.status.name, it.prior.percent, it.prior.completedAt,
|
||||||
|
it.priorDates.start, it.priorDates.due, it.dates.start, it.dates.due,
|
||||||
|
).joinToString(",") { value -> value?.toString().orEmpty() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun decode(raw: String?): List<ResetSubtask> = raw.orEmpty().split(';').mapNotNull { entry ->
|
||||||
|
val parts = entry.split(',')
|
||||||
|
if (parts.size != 8) return@mapNotNull null
|
||||||
|
val id = parts[0].toLongOrNull() ?: return@mapNotNull null
|
||||||
|
val status = TaskStatus.entries.firstOrNull { it.name == parts[1] } ?: return@mapNotNull null
|
||||||
|
ResetSubtask(
|
||||||
|
id,
|
||||||
|
SubtaskState(status, parts[2].toIntOrNull(), parts[3].toLongOrNull()),
|
||||||
|
SubtaskDates(parts[4].toLongOrNull(), parts[5].toLongOrNull()),
|
||||||
|
SubtaskDates(parts[6].toLongOrNull(), parts[7].toLongOrNull()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A provider series' rule set from its columns. */
|
||||||
|
fun specOf(state: Map<String, Any?>): RecurrenceSpec? = TaskMapper.seriesSpec(MapColumnReader(state))
|
||||||
|
|
||||||
|
/** How the series moved from [before] to [after], read in the zone its rule is expanded in. */
|
||||||
|
fun shiftOf(before: Map<String, Any?>, after: Map<String, Any?>, floating: ZoneId = ZoneId.systemDefault()): SeriesShift? {
|
||||||
|
val from = anchor(before) ?: return null
|
||||||
|
val to = anchor(after) ?: return null
|
||||||
|
val reader = MapColumnReader(after)
|
||||||
|
return SeriesShift.of(from, to, reader.getBoolean(Tasks.IS_ALLDAY), reader.getString(Tasks.TZ), floating)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a provider tick moved the series on, judged by its columns
|
||||||
|
* [before] and [after]: its start (or due) moved later and it is still open,
|
||||||
|
* with [next], its rule set as it now stands, generating an occurrence from
|
||||||
|
* there. An `EXDATE` or a status alone is no move; a series whose rule ran
|
||||||
|
* out is finished.
|
||||||
|
*/
|
||||||
|
fun movedOn(before: Map<String, Any?>?, after: Map<String, Any?>?, next: RecurrenceSpec? = after?.let(::specOf)): Boolean {
|
||||||
|
val was = anchor(before ?: return false) ?: return false
|
||||||
|
val now = anchor(after ?: return false) ?: return false
|
||||||
|
if (now <= was) return false
|
||||||
|
if (statusFromInt((after[Tasks.STATUS] as? Number)?.toInt()).isClosed) return false
|
||||||
|
val spec = next ?: return false
|
||||||
|
if (spec.rrule == null && spec.rdate == null) return false
|
||||||
|
val parts = spec.rrule?.split(';')?.map { it.trim() }?.filter { it.isNotEmpty() }
|
||||||
|
val count = parts?.firstOrNull { it.startsWith("COUNT=", ignoreCase = true) }?.substringAfter('=')?.toIntOrNull()
|
||||||
|
if (count != null && count <= 0) return false
|
||||||
|
// Expanded from the old start, as an expansion always yields its own start
|
||||||
|
// even past UNTIL. COUNT is left out: it was spent before the new start.
|
||||||
|
val probe = spec.copy(
|
||||||
|
rrule = parts?.filterNot { it.startsWith("COUNT=", ignoreCase = true) }?.joinToString(";"),
|
||||||
|
anchor = Instant.fromEpochMilliseconds(was),
|
||||||
|
)
|
||||||
|
val from = Instant.fromEpochMilliseconds(now)
|
||||||
|
return RecurrenceExpander.expand(probe, ExpansionWindow(from = from, until = from + LOOKAHEAD, maxOccurrences = 1)).isNotEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The anchor a series' columns put it at: its start, or else its due date. */
|
||||||
|
fun anchor(state: Map<String, Any?>): Long? =
|
||||||
|
(state[Tasks.DTSTART] as? Number)?.toLong() ?: (state[Tasks.DUE] as? Number)?.toLong()
|
||||||
|
}
|
||||||
@@ -8,25 +8,29 @@ import de.jeanlucmakiola.agendula.domain.TaskList
|
|||||||
import de.jeanlucmakiola.agendula.domain.export.ExportTask
|
import de.jeanlucmakiola.agendula.domain.export.ExportTask
|
||||||
import de.jeanlucmakiola.agendula.domain.priorityFromICal
|
import de.jeanlucmakiola.agendula.domain.priorityFromICal
|
||||||
import de.jeanlucmakiola.agendula.domain.statusFromInt
|
import de.jeanlucmakiola.agendula.domain.statusFromInt
|
||||||
|
import de.jeanlucmakiola.agendula.domain.recurrence.RecurrenceSpec
|
||||||
import kotlin.time.Instant
|
import kotlin.time.Instant
|
||||||
|
|
||||||
/** Maps a provider row (via [ColumnReader]) to a domain model. Pure + testable. */
|
/** Maps a provider row (via [ColumnReader]) to a domain model. Pure + testable. */
|
||||||
object TaskMapper {
|
object TaskMapper {
|
||||||
|
|
||||||
fun task(r: ColumnReader): Task {
|
/**
|
||||||
|
* Maps an `instances` row, without its series' rule: the dmfs instances view
|
||||||
|
* (DB 22 and 23) masks `rrule`/`rdate` with `NULL`, so the row alone cannot
|
||||||
|
* tell a series from a one-off on tasks.org's bundled provider (DB 22), which
|
||||||
|
* also lacks `is_recurring`. [withRule] completes it with the rule read from
|
||||||
|
* the master's `tasks` row. An override names its master in
|
||||||
|
* `original_instance_id`.
|
||||||
|
*/
|
||||||
|
fun instance(r: ColumnReader): InstanceRow {
|
||||||
fun instant(name: String): Instant? =
|
fun instant(name: String): Instant? =
|
||||||
r.getLong(name)?.let { Instant.fromEpochMilliseconds(it) }
|
r.getLong(name)?.let { Instant.fromEpochMilliseconds(it) }
|
||||||
|
|
||||||
val rowId = r.getLong(Tasks.ID) ?: 0L
|
val rowId = r.getLong(Tasks.ID) ?: 0L
|
||||||
// Derived from the rule columns rather than the `is_recurring` column
|
val masterId = r.getLong(Tasks.ORIGINAL_INSTANCE_ID)
|
||||||
// alone: that column only exists from OpenTasks 1.4.0 (DB 23) and is
|
val recurring = masterId != null || r.getBoolean(Instances.IS_RECURRING)
|
||||||
// absent on tasks.org's bundled provider (DB 22), where reading it
|
val anchor = occurrenceAnchor(r)
|
||||||
// would silently report every recurring task as one-off — and route
|
val task = Task(
|
||||||
// its edits onto the series anchor.
|
|
||||||
val recurring = r.getString(Tasks.RRULE) != null ||
|
|
||||||
r.getString(Tasks.RDATE) != null ||
|
|
||||||
r.getBoolean(Instances.IS_RECURRING)
|
|
||||||
return Task(
|
|
||||||
taskId = r.getLong(Instances.TASK_ID) ?: rowId,
|
taskId = r.getLong(Instances.TASK_ID) ?: rowId,
|
||||||
listId = r.getLong(Tasks.LIST_ID) ?: 0L,
|
listId = r.getLong(Tasks.LIST_ID) ?: 0L,
|
||||||
title = r.getString(Tasks.TITLE).orEmpty(),
|
title = r.getString(Tasks.TITLE).orEmpty(),
|
||||||
@@ -47,12 +51,44 @@ object TaskMapper {
|
|||||||
accountName = r.getString(Tasks.ACCOUNT_NAME),
|
accountName = r.getString(Tasks.ACCOUNT_NAME),
|
||||||
parentId = r.getLong(Tasks.PARENT_ID),
|
parentId = r.getLong(Tasks.PARENT_ID),
|
||||||
isRecurring = recurring,
|
isRecurring = recurring,
|
||||||
occurrenceStart = if (recurring) occurrenceAnchor(r) else null,
|
occurrenceStart = if (recurring) anchor else null,
|
||||||
distanceFromCurrent = r.getInt(Instances.DISTANCE_FROM_CURRENT),
|
distanceFromCurrent = r.getInt(Instances.DISTANCE_FROM_CURRENT),
|
||||||
created = instant(Tasks.CREATED),
|
created = instant(Tasks.CREATED),
|
||||||
lastModified = instant(Tasks.LAST_MODIFIED),
|
lastModified = instant(Tasks.LAST_MODIFIED),
|
||||||
seriesId = if (recurring) r.getLong(Instances.TASK_ID) ?: rowId else null,
|
seriesId = if (recurring) masterId ?: r.getLong(Instances.TASK_ID) ?: rowId else null,
|
||||||
recurrenceRule = r.getString(Tasks.RRULE),
|
)
|
||||||
|
return InstanceRow(task, ruleOwner = masterId ?: task.taskId, anchor = anchor)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** [row]'s task as an occurrence of the series [rule] belongs to, or as it is without one. */
|
||||||
|
fun withRule(row: InstanceRow, rule: SeriesRule?): Task {
|
||||||
|
if (rule == null) return row.task
|
||||||
|
return row.task.copy(
|
||||||
|
isRecurring = true,
|
||||||
|
occurrenceStart = row.task.occurrenceStart ?: row.anchor,
|
||||||
|
seriesId = row.task.seriesId ?: row.ruleOwner,
|
||||||
|
recurrenceRule = rule.rrule,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The rule columns of a `tasks` row, or null when it does not recur. */
|
||||||
|
fun seriesRule(r: ColumnReader): SeriesRule? {
|
||||||
|
val rrule = r.getString(Tasks.RRULE)?.ifBlank { null }
|
||||||
|
val rdate = r.getString(Tasks.RDATE)?.ifBlank { null }
|
||||||
|
return if (rrule == null && rdate == null) null else SeriesRule(rrule, rdate)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The rule set of a `tasks` row, anchored on its start or else its due date; null without either date. */
|
||||||
|
fun seriesSpec(r: ColumnReader): RecurrenceSpec? {
|
||||||
|
val rule = seriesRule(r)
|
||||||
|
val anchor = r.getLong(Tasks.DTSTART) ?: r.getLong(Tasks.DUE) ?: return null
|
||||||
|
return RecurrenceSpec(
|
||||||
|
rrule = rule?.rrule,
|
||||||
|
rdate = rule?.rdate,
|
||||||
|
exdate = r.getString(Tasks.EXDATE),
|
||||||
|
anchor = Instant.fromEpochMilliseconds(anchor),
|
||||||
|
isAllDay = r.getBoolean(Tasks.IS_ALLDAY),
|
||||||
|
timeZone = r.getString(Tasks.TZ),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,3 +155,12 @@ object TaskMapper {
|
|||||||
owner = r.getString(Lists.OWNER),
|
owner = r.getString(Lists.OWNER),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A series' recurrence as stored on its master row. */
|
||||||
|
data class SeriesRule(val rrule: String?, val rdate: String?)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An instance row's task before its series' rule is applied. [ruleOwner] is the
|
||||||
|
* task whose `tasks` row carries that rule: the master, for an override.
|
||||||
|
*/
|
||||||
|
data class InstanceRow(val task: Task, val ruleOwner: Long, val anchor: Instant?)
|
||||||
@@ -17,6 +17,20 @@ private fun Instant.forAllDay(allDay: Boolean): Instant =
|
|||||||
Math.floorDiv(toEpochMilliseconds(), MILLIS_PER_DAY) * MILLIS_PER_DAY,
|
Math.floorDiv(toEpochMilliseconds(), MILLIS_PER_DAY) * MILLIS_PER_DAY,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whole seconds, as iCalendar stores times. The provider expands a series from
|
||||||
|
* second-precision instants, so a DTSTART carrying milliseconds never matches its
|
||||||
|
* own first occurrence: completing it detaches a copy but leaves the series where
|
||||||
|
* it was, and the same occurrence comes straight back.
|
||||||
|
*/
|
||||||
|
fun providerMillis(epochMillis: Long): Long = Math.floorDiv(epochMillis, 1000L) * 1000L
|
||||||
|
|
||||||
|
/** [at] cut to its whole second, as [providerMillis] does. */
|
||||||
|
fun wholeSecond(at: Instant): Instant = Instant.fromEpochMilliseconds(providerMillis(at.toEpochMilliseconds()))
|
||||||
|
|
||||||
|
/** True when [a] and [b] fall in the same whole second. */
|
||||||
|
fun sameSecond(a: Instant, b: Instant): Boolean = wholeSecond(a) == wholeSecond(b)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Turns a [TaskForm] / mutation into a name→value map. Pure (no ContentValues),
|
* Turns a [TaskForm] / mutation into a name→value map. Pure (no ContentValues),
|
||||||
* so it unit-tests on the JVM; [AndroidTasksDataSource] converts the map to
|
* so it unit-tests on the JVM; [AndroidTasksDataSource] converts the map to
|
||||||
@@ -57,8 +71,8 @@ object TaskWriteMapper {
|
|||||||
// through DateTime.toAllDay(), which drops the time-of-day and resolves the
|
// through DateTime.toAllDay(), which drops the time-of-day and resolves the
|
||||||
// remaining date against UTC — so a local-midnight instant lands on the
|
// remaining date against UTC — so a local-midnight instant lands on the
|
||||||
// previous day for anyone west of UTC. Pin all-day values to UTC midnight.
|
// previous day for anyone west of UTC. Pin all-day values to UTC midnight.
|
||||||
put(Tasks.DTSTART, form.start?.forAllDay(form.isAllDay)?.toEpochMilliseconds())
|
put(Tasks.DTSTART, form.start?.forAllDay(form.isAllDay)?.toEpochMilliseconds()?.let(::providerMillis))
|
||||||
put(Tasks.DUE, form.due?.forAllDay(form.isAllDay)?.toEpochMilliseconds())
|
put(Tasks.DUE, form.due?.forAllDay(form.isAllDay)?.toEpochMilliseconds()?.let(::providerMillis))
|
||||||
// DUE and DURATION are mutually exclusive. The provider's Validating
|
// DUE and DURATION are mutually exclusive. The provider's Validating
|
||||||
// processor evaluates the *merged* row (supplied values over the stored
|
// processor evaluates the *merged* row (supplied values over the stored
|
||||||
// ones), so writing DUE onto a task that already carries a DURATION throws
|
// ones), so writing DUE onto a task that already carries a DURATION throws
|
||||||
|
|||||||
@@ -86,6 +86,12 @@ object TasksContract {
|
|||||||
|
|
||||||
const val UID = "_uid"
|
const val UID = "_uid"
|
||||||
const val DELETED = "_deleted"
|
const val DELETED = "_deleted"
|
||||||
|
|
||||||
|
const val HAS_ALARMS = "has_alarms"
|
||||||
|
const val ORIGINAL_INSTANCE_ALLDAY = "original_instance_allday"
|
||||||
|
const val LIST_OWNER = "list_owner"
|
||||||
|
const val LIST_ACCESS_LEVEL = "list_access_level"
|
||||||
|
const val VISIBLE = "visible"
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -103,6 +109,7 @@ object TasksContract {
|
|||||||
const val INSTANCE_DUE_SORTING = "instance_due_sorting"
|
const val INSTANCE_DUE_SORTING = "instance_due_sorting"
|
||||||
const val DISTANCE_FROM_CURRENT = "distance_from_current"
|
const val DISTANCE_FROM_CURRENT = "distance_from_current"
|
||||||
const val IS_RECURRING = "is_recurring"
|
const val IS_RECURRING = "is_recurring"
|
||||||
|
const val INSTANCE_DURATION = "instance_duration"
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The occurrence's `RECURRENCE-ID` — the time this occurrence was
|
* The occurrence's `RECURRENCE-ID` — the time this occurrence was
|
||||||
@@ -118,6 +125,10 @@ object TasksContract {
|
|||||||
const val PROPERTY_ID = "property_id"
|
const val PROPERTY_ID = "property_id"
|
||||||
const val TASK_ID = "task_id"
|
const val TASK_ID = "task_id"
|
||||||
const val MIMETYPE = "mimetype"
|
const val MIMETYPE = "mimetype"
|
||||||
|
const val DATA0 = "data0"
|
||||||
|
const val DATA1 = "data1"
|
||||||
|
const val DATA2 = "data2"
|
||||||
|
const val DATA3 = "data3"
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -164,6 +175,9 @@ object TasksContract {
|
|||||||
|
|
||||||
/** `data1` — the tag as spelled. */
|
/** `data1` — the tag as spelled. */
|
||||||
const val NAME = "data1"
|
const val NAME = "data1"
|
||||||
|
|
||||||
|
/** `data2` — the tag's colour, if any. */
|
||||||
|
const val COLOR = "data2"
|
||||||
}
|
}
|
||||||
|
|
||||||
fun propertiesUri(authority: String): Uri = "content://$authority/${Properties.PATH}".toUri()
|
fun propertiesUri(authority: String): Uri = "content://$authority/${Properties.PATH}".toUri()
|
||||||
|
|||||||
@@ -3,26 +3,9 @@ package de.jeanlucmakiola.agendula.data.tasks
|
|||||||
import de.jeanlucmakiola.agendula.domain.Task
|
import de.jeanlucmakiola.agendula.domain.Task
|
||||||
import de.jeanlucmakiola.agendula.domain.TaskForm
|
import de.jeanlucmakiola.agendula.domain.TaskForm
|
||||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||||
|
import de.jeanlucmakiola.agendula.domain.TaskReminder
|
||||||
import kotlin.time.Instant
|
import kotlin.time.Instant
|
||||||
|
|
||||||
/**
|
|
||||||
* A stored reminder: how long before, and what it counts back from.
|
|
||||||
*
|
|
||||||
* [fromStart] matters because both stores can hold a `START`-referenced alarm —
|
|
||||||
* the dmfs import preserves one, and an external provider's other clients write
|
|
||||||
* them — while Agendula's own UI only ever sets a before-due lead. Collapsing it
|
|
||||||
* to a number here is what silently fired those reminders off the wrong anchor.
|
|
||||||
*/
|
|
||||||
data class TaskReminder(val minutesBefore: Int, val fromStart: Boolean = false)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The one reminder Agendula's single-reminder editor shows and writes: the last
|
|
||||||
* before-due one, which is where a write lands, so it stays the same one across
|
|
||||||
* saves. Anything else a task carries — a start-relative alarm, or the extra ones
|
|
||||||
* another client or the dmfs import brought — is left to ride along.
|
|
||||||
*/
|
|
||||||
fun List<TaskReminder>.editable(): TaskReminder? = lastOrNull { !it.fromStart }
|
|
||||||
|
|
||||||
/** What to fetch from the provider. Smart-list date logic is applied above this. */
|
/** What to fetch from the provider. Smart-list date logic is applied above this. */
|
||||||
data class TaskQuery(
|
data class TaskQuery(
|
||||||
val listId: Long? = null,
|
val listId: Long? = null,
|
||||||
@@ -46,8 +29,38 @@ interface TasksDataSource {
|
|||||||
fun task(taskId: Long, occurrenceStart: Instant?): Task? = task(taskId)
|
fun task(taskId: Long, occurrenceStart: Instant?): Task? = task(taskId)
|
||||||
fun subtasks(parentTaskId: Long): List<Task>
|
fun subtasks(parentTaskId: Long): List<Task>
|
||||||
|
|
||||||
fun insertTask(form: TaskForm): Long
|
/**
|
||||||
fun updateTask(taskId: Long, form: TaskForm)
|
* The task rows directly under [parentTaskId]: one id per subtask, its series
|
||||||
|
* master when it recurs, whether or not any occurrence falls in the window
|
||||||
|
* [subtasks] expands.
|
||||||
|
*/
|
||||||
|
fun subtaskIds(parentTaskId: Long): List<Long> =
|
||||||
|
subtasks(parentTaskId).map { it.seriesId ?: it.taskId }.distinct().filter { it != parentTaskId }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete [taskId] and its subtasks, all the way down; left behind they would
|
||||||
|
* hang off a tombstone. Each task once, so a parent loop an import brought in
|
||||||
|
* ends instead of recursing forever.
|
||||||
|
*/
|
||||||
|
fun deleteWithSubtasks(taskId: Long) {
|
||||||
|
val seen = HashSet<Long>()
|
||||||
|
fun delete(id: Long) {
|
||||||
|
if (!seen.add(id)) return
|
||||||
|
subtaskIds(id).forEach(::delete)
|
||||||
|
deleteTask(id)
|
||||||
|
}
|
||||||
|
delete(taskId)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The write paths take the task's reminders in the same write as the task
|
||||||
|
* itself, so a sync can never upload one without the other.
|
||||||
|
*
|
||||||
|
* Each takes the task's whole set of [reminders], before-start and
|
||||||
|
* before-due alike, and `null` leaves the stored ones alone.
|
||||||
|
*/
|
||||||
|
fun insertTask(form: TaskForm, reminders: List<TaskReminder>? = null): Long
|
||||||
|
fun updateTask(taskId: Long, form: TaskForm, reminders: List<TaskReminder>? = null)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update a single occurrence of a recurring task, addressed by the task row and
|
* Update a single occurrence of a recurring task, addressed by the task row and
|
||||||
@@ -60,27 +73,19 @@ interface TasksDataSource {
|
|||||||
* instance row id keeps this seam independent of any one store's row
|
* instance row id keeps this seam independent of any one store's row
|
||||||
* numbering; External mode maps it back to an instance row itself.
|
* numbering; External mode maps it back to an instance row itself.
|
||||||
*/
|
*/
|
||||||
fun updateInstance(taskId: Long, occurrenceStart: Instant, form: TaskForm)
|
fun updateInstance(taskId: Long, occurrenceStart: Instant, form: TaskForm, reminders: List<TaskReminder>? = null)
|
||||||
/**
|
|
||||||
* Set (or clear, with `null`) the task's [editable] reminder lead, stored as an
|
|
||||||
* Alarm property row. Every other reminder on the task is left untouched. The
|
|
||||||
* provider never fires it — [de.jeanlucmakiola.agendula.data.reminders
|
|
||||||
* .ReminderScheduler] does — but persisting it here is what syncs the lead and
|
|
||||||
* shares it with other OpenTasks clients.
|
|
||||||
*/
|
|
||||||
fun setAlarm(taskId: Long, minutesBeforeDue: Int?)
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Edit the whole series [seriesId] through its occurrence at [occurrenceStart]:
|
* Edit the whole series [seriesId] through its occurrence at [occurrenceStart]:
|
||||||
* content from [form], and the series moved by however far that occurrence moved.
|
* content from [form], and the series moved by however far that occurrence moved.
|
||||||
*/
|
*/
|
||||||
fun updateSeries(seriesId: Long, occurrenceStart: Instant, form: TaskForm)
|
fun updateSeries(seriesId: Long, occurrenceStart: Instant, form: TaskForm, reminders: List<TaskReminder>? = null)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* "This and following": end [seriesId] before [occurrenceStart] and continue
|
* "This and following": end [seriesId] before [occurrenceStart] and continue
|
||||||
* from there as a new series built from [form]. Returns the new series' id.
|
* from there as a new series built from [form]. Returns the new series' id.
|
||||||
*/
|
*/
|
||||||
fun splitSeries(seriesId: Long, occurrenceStart: Instant, form: TaskForm): Long
|
fun splitSeries(seriesId: Long, occurrenceStart: Instant, form: TaskForm, reminders: List<TaskReminder>? = null): Long
|
||||||
|
|
||||||
/** Delete one generated occurrence of [seriesId] (an `EXDATE`). */
|
/** Delete one generated occurrence of [seriesId] (an `EXDATE`). */
|
||||||
fun deleteOccurrence(seriesId: Long, occurrenceStart: Instant)
|
fun deleteOccurrence(seriesId: Long, occurrenceStart: Instant)
|
||||||
@@ -89,14 +94,18 @@ interface TasksDataSource {
|
|||||||
fun deleteFollowing(seriesId: Long, occurrenceStart: Instant)
|
fun deleteFollowing(seriesId: Long, occurrenceStart: Instant)
|
||||||
|
|
||||||
|
|
||||||
/** Replace every reminder on [taskId] with [reminders], in order. */
|
/** Make [taskId]'s reminders exactly [reminders]. A synced task is owed a PUT for it. */
|
||||||
fun setReminders(taskId: Long, reminders: List<TaskReminder>)
|
fun setReminders(taskId: Long, reminders: List<TaskReminder>)
|
||||||
|
|
||||||
/** Every task's reminders, by task id, in stored order. One query, for the scheduler. */
|
/**
|
||||||
fun reminders(): Map<Long, List<TaskReminder>> = alarms().mapValues { listOf(it.value) }
|
* Every task's reminders, by task id, in stored order. One query, for the
|
||||||
|
* scheduler. A task missing from the map takes the default; one present
|
||||||
|
* with an empty list has none (see `TaskEntity.remindersOff`).
|
||||||
|
*/
|
||||||
|
fun reminders(): Map<Long, List<TaskReminder>>
|
||||||
|
|
||||||
/** Every task's [editable] reminder, by task id. */
|
/** [reminders] for [taskId] alone, without reading every task's. */
|
||||||
fun alarms(): Map<Long, TaskReminder>
|
fun reminders(taskId: Long): List<TaskReminder>? = reminders()[taskId]
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Every task in [listId] read from the **`tasks` table**, for export. Masters,
|
* Every task in [listId] read from the **`tasks` table**, for export. Masters,
|
||||||
@@ -118,13 +127,17 @@ interface TasksDataSource {
|
|||||||
*
|
*
|
||||||
* Implementations fall back to [setCompleted] when the row turns out not to
|
* Implementations fall back to [setCompleted] when the row turns out not to
|
||||||
* be a series master — an override, or a plain task the caller happened to
|
* be a series master — an override, or a plain task the caller happened to
|
||||||
* hand an anchor for — so the routing above cannot get this wrong.
|
* hand an anchor for. A series whose occurrence cannot be found fails with
|
||||||
|
* [TaskWriteFailedException] instead: the plain write would close all of it.
|
||||||
*/
|
*/
|
||||||
fun setCompletedInstance(taskId: Long, occurrenceStart: Instant, completed: Boolean)
|
fun setCompletedInstance(taskId: Long, occurrenceStart: Instant, completed: Boolean)
|
||||||
|
|
||||||
/** Cancel (or restore) one occurrence of a series; the counterpart of [setCompletedInstance]. */
|
/** Cancel (or restore) one occurrence of a series; the counterpart of [setCompletedInstance]. */
|
||||||
fun setCancelledInstance(taskId: Long, occurrenceStart: Instant, cancelled: Boolean)
|
fun setCancelledInstance(taskId: Long, occurrenceStart: Instant, cancelled: Boolean)
|
||||||
fun deleteTask(taskId: Long)
|
fun deleteTask(taskId: Long)
|
||||||
|
|
||||||
|
/** Delete the override [taskId] standing for one occurrence, excluding that occurrence from its series. */
|
||||||
|
fun deleteOverride(taskId: Long, occurrenceStart: Instant) = deleteTask(taskId)
|
||||||
fun createLocalList(name: String, color: Int): Long
|
fun createLocalList(name: String, color: Int): Long
|
||||||
|
|
||||||
/** Rename and recolour [listId]. */
|
/** Rename and recolour [listId]. */
|
||||||
@@ -146,4 +159,7 @@ interface TasksDataSource {
|
|||||||
|
|
||||||
/** Observe any change to tasks/lists; [onChange] fires on a background thread. */
|
/** Observe any change to tasks/lists; [onChange] fires on a background thread. */
|
||||||
fun registerObserver(onChange: () -> Unit): AutoCloseable
|
fun registerObserver(onChange: () -> Unit): AutoCloseable
|
||||||
|
|
||||||
|
/** Like [registerObserver], but only for changes to tasks, lists and alarms — not account bookkeeping. */
|
||||||
|
fun registerTaskObserver(onChange: () -> Unit): AutoCloseable = registerObserver(onChange)
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package de.jeanlucmakiola.agendula.data.tasks
|
package de.jeanlucmakiola.agendula.data.tasks
|
||||||
|
|
||||||
|
import de.jeanlucmakiola.agendula.domain.TaskReminder
|
||||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||||
import de.jeanlucmakiola.agendula.domain.Task
|
import de.jeanlucmakiola.agendula.domain.Task
|
||||||
import de.jeanlucmakiola.agendula.domain.TaskDetail
|
import de.jeanlucmakiola.agendula.domain.TaskDetail
|
||||||
@@ -82,13 +83,6 @@ interface TasksRepository {
|
|||||||
scope: RecurringScope = RecurringScope.AllOccurrences,
|
scope: RecurringScope = RecurringScope.AllOccurrences,
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
|
||||||
* The per-task reminder lead in minutes before due, or `null` if the task has
|
|
||||||
* none (in which case the list's / global setting applies). Read when the edit
|
|
||||||
* form loads so saving can't silently drop it.
|
|
||||||
*/
|
|
||||||
suspend fun reminderFor(taskId: Long): Int?
|
|
||||||
|
|
||||||
/** Every reminder stored on the task, in order — including start-relative ones. */
|
/** Every reminder stored on the task, in order — including start-relative ones. */
|
||||||
suspend fun remindersFor(taskId: Long): List<TaskReminder>
|
suspend fun remindersFor(taskId: Long): List<TaskReminder>
|
||||||
|
|
||||||
@@ -105,4 +99,12 @@ interface TasksRepository {
|
|||||||
|
|
||||||
/** Synchronous snapshot for the permission/onboarding gate. */
|
/** Synchronous snapshot for the permission/onboarding gate. */
|
||||||
fun providerStatus(): ProviderStatus
|
fun providerStatus(): ProviderStatus
|
||||||
|
|
||||||
|
/** Whether the active store can repeat a series from completion (#79): only Agendula's own. */
|
||||||
|
fun supportsRepeatFromCompletion(): Boolean = false
|
||||||
|
/**
|
||||||
|
* Whether the store keeps one end of a timed task without a time (#101).
|
||||||
|
* A provider's single `IS_ALLDAY` cannot, so there both ends go together.
|
||||||
|
*/
|
||||||
|
fun supportsUntimedEnds(): Boolean = true
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,14 @@
|
|||||||
package de.jeanlucmakiola.agendula.data.tasks
|
package de.jeanlucmakiola.agendula.data.tasks
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import de.jeanlucmakiola.agendula.domain.TaskReminder
|
||||||
|
import de.jeanlucmakiola.agendula.data.di.ApplicationScope
|
||||||
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
|
import de.jeanlucmakiola.agendula.data.di.IoDispatcher
|
||||||
|
import de.jeanlucmakiola.agendula.data.prefs.Settings
|
||||||
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
|
||||||
|
import de.jeanlucmakiola.agendula.data.reminders.ReminderPlanner
|
||||||
|
import de.jeanlucmakiola.agendula.data.reminders.ReminderScheduler
|
||||||
|
import de.jeanlucmakiola.agendula.data.reminders.ScheduledReminder
|
||||||
import de.jeanlucmakiola.floret.time.DayWindow
|
import de.jeanlucmakiola.floret.time.DayWindow
|
||||||
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
import de.jeanlucmakiola.agendula.domain.SavedFilter
|
||||||
import de.jeanlucmakiola.agendula.domain.SeriesCollapse
|
import de.jeanlucmakiola.agendula.domain.SeriesCollapse
|
||||||
@@ -9,24 +16,29 @@ import de.jeanlucmakiola.agendula.domain.Task
|
|||||||
import de.jeanlucmakiola.agendula.domain.TaskDetail
|
import de.jeanlucmakiola.agendula.domain.TaskDetail
|
||||||
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
import de.jeanlucmakiola.agendula.domain.TaskFilter
|
||||||
import de.jeanlucmakiola.agendula.domain.TaskFiltering
|
import de.jeanlucmakiola.agendula.domain.TaskFiltering
|
||||||
|
import de.jeanlucmakiola.agendula.domain.TaskEnd
|
||||||
import de.jeanlucmakiola.agendula.domain.TaskForm
|
import de.jeanlucmakiola.agendula.domain.TaskForm
|
||||||
import de.jeanlucmakiola.agendula.domain.TaskList
|
import de.jeanlucmakiola.agendula.domain.TaskList
|
||||||
import de.jeanlucmakiola.agendula.domain.TaskSorting
|
import de.jeanlucmakiola.agendula.domain.TaskSorting
|
||||||
import de.jeanlucmakiola.agendula.domain.TaskStatus
|
import de.jeanlucmakiola.agendula.domain.TaskStatus
|
||||||
import de.jeanlucmakiola.agendula.domain.recurrence.RecurringScope
|
import de.jeanlucmakiola.agendula.domain.recurrence.RecurringScope
|
||||||
|
import kotlinx.coroutines.CancellationException
|
||||||
import kotlinx.coroutines.CoroutineDispatcher
|
import kotlinx.coroutines.CoroutineDispatcher
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.channels.Channel
|
import kotlinx.coroutines.channels.Channel
|
||||||
import kotlinx.coroutines.channels.awaitClose
|
import kotlinx.coroutines.channels.awaitClose
|
||||||
import kotlinx.coroutines.channels.consumeEach
|
import kotlinx.coroutines.channels.consumeEach
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||||
import kotlinx.coroutines.flow.callbackFlow
|
import kotlinx.coroutines.flow.callbackFlow
|
||||||
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.flow.flatMapLatest
|
import kotlinx.coroutines.flow.flatMapLatest
|
||||||
import kotlinx.coroutines.flow.flowOf
|
import kotlinx.coroutines.flow.flowOf
|
||||||
import kotlinx.coroutines.flow.flowOn
|
import kotlinx.coroutines.flow.flowOn
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import java.time.ZoneId
|
import java.time.ZoneId
|
||||||
|
import java.util.concurrent.atomic.AtomicReference
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
import kotlin.time.Clock
|
import kotlin.time.Clock
|
||||||
@@ -38,10 +50,35 @@ class TasksRepositoryImpl @Inject constructor(
|
|||||||
private val providerResolver: ProviderResolver,
|
private val providerResolver: ProviderResolver,
|
||||||
private val startupGate: StartupGate,
|
private val startupGate: StartupGate,
|
||||||
private val settingsPrefs: SettingsPrefs,
|
private val settingsPrefs: SettingsPrefs,
|
||||||
|
private val reminderScheduler: ReminderScheduler,
|
||||||
|
@ApplicationScope private val appScope: CoroutineScope,
|
||||||
@IoDispatcher private val io: CoroutineDispatcher,
|
@IoDispatcher private val io: CoroutineDispatcher,
|
||||||
) : TasksRepository {
|
) : TasksRepository {
|
||||||
|
|
||||||
override fun taskLists(): Flow<List<TaskList>> = observing { dataSource.taskLists() }
|
override fun taskLists(): Flow<List<TaskList>> = observing {
|
||||||
|
// The store read, auto mode and provider included: a switch meanwhile leaves the lists of the other.
|
||||||
|
val store = providerResolver.active()
|
||||||
|
dataSource.taskLists().also { lists -> if (providerResolver.active() == store) forgetGoneLists(store, lists) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private val listsPrunedFor = AtomicReference<Pair<Pair<StorageMode, String?>, Set<Long>>?>(null)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Forgets the settings of [store]'s lists a read no longer found, once per
|
||||||
|
* change of what it finds. A read finding no list proves nothing.
|
||||||
|
*/
|
||||||
|
private fun forgetGoneLists(store: Pair<StorageMode, String?>, lists: List<TaskList>) {
|
||||||
|
if (lists.isEmpty()) return
|
||||||
|
val read = store to lists.mapTo(HashSet()) { it.id }
|
||||||
|
if (listsPrunedFor.getAndSet(read) == read) return
|
||||||
|
appScope.launch(io) {
|
||||||
|
runCatching { settingsPrefs.forgetListsExcept(store.first, store.second, read.second) }
|
||||||
|
.onFailure {
|
||||||
|
listsPrunedFor.compareAndSet(read, null)
|
||||||
|
Log.w(TAG, "Forgetting gone lists failed", it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@OptIn(ExperimentalCoroutinesApi::class)
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
override fun filteredTasks(filter: TaskFilter): Flow<FilteredTasks> = when (filter) {
|
override fun filteredTasks(filter: TaskFilter): Flow<FilteredTasks> = when (filter) {
|
||||||
@@ -61,14 +98,16 @@ class TasksRepositoryImpl @Inject constructor(
|
|||||||
override fun subtasks(parentId: Long): Flow<List<Task>> = observing {
|
override fun subtasks(parentId: Long): Flow<List<Task>> = observing {
|
||||||
SeriesCollapse.visible(dataSource.subtasks(parentId))
|
SeriesCollapse.visible(dataSource.subtasks(parentId))
|
||||||
.filter { it.taskId != parentId }
|
.filter { it.taskId != parentId }
|
||||||
.sortedWith(TaskSorting.DEFAULT)
|
.sortedWith(TaskSorting.default())
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun taskDetail(taskId: Long, occurrenceStart: Instant?): Flow<TaskDetail?> = observing {
|
override fun taskDetail(taskId: Long, occurrenceStart: Instant?): Flow<TaskDetail?> = observing {
|
||||||
dataSource.task(taskId, occurrenceStart)?.let { task ->
|
dataSource.task(taskId, occurrenceStart)?.let { task ->
|
||||||
|
// A series' subtasks hang off its master, also when this occurrence is an override.
|
||||||
|
val owner = task.seriesId ?: resolvedRow(task, taskId)
|
||||||
TaskDetail(
|
TaskDetail(
|
||||||
task = task,
|
task = task,
|
||||||
subtasks = SeriesCollapse.visible(dataSource.subtasks(taskId)).filter { it.taskId != taskId },
|
subtasks = SeriesCollapse.visible(dataSource.subtasks(owner)).filter { it.taskId != owner },
|
||||||
parent = task.parentId?.takeIf { it > 0 }?.let { dataSource.task(it) },
|
parent = task.parentId?.takeIf { it > 0 }?.let { dataSource.task(it) },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -104,16 +143,22 @@ class TasksRepositoryImpl @Inject constructor(
|
|||||||
task.copy(subtaskDone = done, subtaskTotal = total)
|
task.copy(subtaskDone = done, subtaskTotal = total)
|
||||||
} ?: task
|
} ?: task
|
||||||
}
|
}
|
||||||
.sortedWith(TaskSorting.DEFAULT)
|
.sortedWith(TaskSorting.default())
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun createTask(form: TaskForm): Long =
|
override suspend fun createTask(form: TaskForm): Long =
|
||||||
withContext(io) {
|
withContext(io) {
|
||||||
val id = dataSource.insertTask(form)
|
val settings = settingsPrefs.settings.first()
|
||||||
writeReminders(id, form)
|
val now = Clock.System.now().toEpochMilliseconds()
|
||||||
id
|
val before = remindersBeforeSave(form, current = null, settings)
|
||||||
|
val reminders = storedRemindersFor(form, current = null, settings, now)
|
||||||
|
dataSource.insertTask(form, reminders.reminders)
|
||||||
|
.also { id -> before?.let { remindPastOnSave(id, it, form, reminders.pastDefaults, settings) } }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun storedRemindersFor(form: TaskForm, current: Task?, settings: Settings, now: Long): StoredReminders.ForSave =
|
||||||
|
StoredReminders.forSave(form, current, settings, now, ZoneId.systemDefault())
|
||||||
|
|
||||||
override suspend fun duplicateTask(taskId: Long, occurrenceStart: Instant?): Long =
|
override suspend fun duplicateTask(taskId: Long, occurrenceStart: Instant?): Long =
|
||||||
withContext(io) {
|
withContext(io) {
|
||||||
val task = checkNotNull(dataSource.task(taskId, occurrenceStart)) { "Task $taskId is gone" }
|
val task = checkNotNull(dataSource.task(taskId, occurrenceStart)) { "Task $taskId is gone" }
|
||||||
@@ -121,23 +166,26 @@ class TasksRepositoryImpl @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun copyOf(task: Task, parentId: Long?, depth: Int): Long {
|
private fun copyOf(task: Task, parentId: Long?, depth: Int): Long {
|
||||||
|
// In the same write as the copy: inserted first and given its reminders
|
||||||
|
// after, a sync landing in between uploads the copy without them.
|
||||||
|
val reminders = dataSource.reminders(task.taskId).orEmpty().map { it.lead }
|
||||||
val id = dataSource.insertTask(
|
val id = dataSource.insertTask(
|
||||||
TaskForm(
|
TaskForm(
|
||||||
title = task.title,
|
title = task.title,
|
||||||
listId = task.listId,
|
listId = task.listId,
|
||||||
description = task.description,
|
description = task.description,
|
||||||
start = task.start,
|
start = task.formValueOf(TaskEnd.START),
|
||||||
due = task.due,
|
due = task.formValueOf(TaskEnd.DUE),
|
||||||
isAllDay = task.isAllDay,
|
isAllDay = task.isAllDay,
|
||||||
|
untimed = task.untimed,
|
||||||
priority = task.priority,
|
priority = task.priority,
|
||||||
parentId = parentId,
|
parentId = parentId,
|
||||||
location = task.location,
|
location = task.location,
|
||||||
url = task.url,
|
url = task.url,
|
||||||
tags = task.tags,
|
tags = task.tags,
|
||||||
),
|
),
|
||||||
|
reminders,
|
||||||
)
|
)
|
||||||
val reminders = dataSource.reminders()[task.taskId].orEmpty()
|
|
||||||
if (reminders.isNotEmpty()) dataSource.setReminders(id, reminders)
|
|
||||||
if (depth < MAX_COPY_DEPTH) {
|
if (depth < MAX_COPY_DEPTH) {
|
||||||
SeriesCollapse.visible(dataSource.subtasks(task.taskId))
|
SeriesCollapse.visible(dataSource.subtasks(task.taskId))
|
||||||
.filter { it.taskId != task.taskId && it.status != TaskStatus.CANCELLED }
|
.filter { it.taskId != task.taskId && it.status != TaskStatus.CANCELLED }
|
||||||
@@ -146,11 +194,8 @@ class TasksRepositoryImpl @Inject constructor(
|
|||||||
return id
|
return id
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun reminderFor(taskId: Long): Int? =
|
|
||||||
withContext(io) { runCatching { dataSource.alarms()[taskId]?.minutesBefore }.getOrNull() }
|
|
||||||
|
|
||||||
override suspend fun remindersFor(taskId: Long): List<TaskReminder> =
|
override suspend fun remindersFor(taskId: Long): List<TaskReminder> =
|
||||||
withContext(io) { runCatching { dataSource.reminders()[taskId].orEmpty() }.getOrDefault(emptyList()) }
|
withContext(io) { runCatching { dataSource.reminders(taskId).orEmpty() }.getOrDefault(emptyList()) }
|
||||||
|
|
||||||
override suspend fun setReminders(taskId: Long, reminders: List<TaskReminder>) =
|
override suspend fun setReminders(taskId: Long, reminders: List<TaskReminder>) =
|
||||||
withContext(io) { dataSource.setReminders(taskId, reminders) }
|
withContext(io) { dataSource.setReminders(taskId, reminders) }
|
||||||
@@ -164,7 +209,9 @@ class TasksRepositoryImpl @Inject constructor(
|
|||||||
) = withContext(io) {
|
) = withContext(io) {
|
||||||
// Re-read just before writing: it settles the conflict check *and* tells
|
// Re-read just before writing: it settles the conflict check *and* tells
|
||||||
// us which URI to write through.
|
// us which URI to write through.
|
||||||
|
// An occurrence that is gone is not written through to its series.
|
||||||
val current = dataSource.task(taskId, occurrenceStart)
|
val current = dataSource.task(taskId, occurrenceStart)
|
||||||
|
?: if (occurrenceStart != null) throw TaskWriteFailedException("update task $taskId@$occurrenceStart: gone") else null
|
||||||
// Conflict-safe overwrite: bail if the provider's last_modified moved
|
// Conflict-safe overwrite: bail if the provider's last_modified moved
|
||||||
// since the form captured it (external sync / another app). A null
|
// since the form captured it (external sync / another app). A null
|
||||||
// baseline means "force / overwrite anyway".
|
// baseline means "force / overwrite anyway".
|
||||||
@@ -172,18 +219,20 @@ class TasksRepositoryImpl @Inject constructor(
|
|||||||
val seen = current?.lastModified
|
val seen = current?.lastModified
|
||||||
if (seen != null && seen != expectedLastModified) throw TaskConflictException(taskId)
|
if (seen != null && seen != expectedLastModified) throw TaskConflictException(taskId)
|
||||||
}
|
}
|
||||||
|
val settings = settingsPrefs.settings.first()
|
||||||
|
val now = Clock.System.now().toEpochMilliseconds()
|
||||||
|
val stored = storedRemindersFor(form, current, settings, now)
|
||||||
|
val reminders = stored.reminders
|
||||||
val seriesId = current?.seriesId
|
val seriesId = current?.seriesId
|
||||||
val occurrence = current?.occurrenceStart
|
val occurrence = current?.occurrenceStart
|
||||||
if (seriesId != null && occurrence != null) {
|
if (seriesId != null && occurrence != null) {
|
||||||
when (scope) {
|
when (scope) {
|
||||||
RecurringScope.AllOccurrences -> {
|
RecurringScope.AllOccurrences -> {
|
||||||
writeReminders(seriesId, form)
|
dataSource.updateSeries(seriesId, occurrence, form, reminders)
|
||||||
dataSource.updateSeries(seriesId, occurrence, form)
|
|
||||||
return@withContext
|
return@withContext
|
||||||
}
|
}
|
||||||
RecurringScope.ThisAndFollowing -> {
|
RecurringScope.ThisAndFollowing -> {
|
||||||
val created = dataSource.splitSeries(seriesId, occurrence, form)
|
dataSource.splitSeries(seriesId, occurrence, form, reminders)
|
||||||
writeReminders(created, form)
|
|
||||||
return@withContext
|
return@withContext
|
||||||
}
|
}
|
||||||
RecurringScope.ThisOccurrence -> Unit
|
RecurringScope.ThisOccurrence -> Unit
|
||||||
@@ -191,31 +240,18 @@ class TasksRepositoryImpl @Inject constructor(
|
|||||||
}
|
}
|
||||||
// A recurring task's start/due are one occurrence's resolved times, so
|
// A recurring task's start/due are one occurrence's resolved times, so
|
||||||
// writing them back to the task row would re-anchor the whole series.
|
// writing them back to the task row would re-anchor the whole series.
|
||||||
// Going through the occurrence forks an override instead.
|
// Going through the occurrence forks an override instead, which takes
|
||||||
|
// the reminders on its own row and leaves the series' alone.
|
||||||
val instance = current?.takeIf { it.isRecurring }?.occurrenceStart
|
val instance = current?.takeIf { it.isRecurring }?.occurrenceStart
|
||||||
if (instance == null) {
|
if (instance == null) {
|
||||||
writeReminders(taskId, form)
|
// A task that could not be read has no baseline to tell its new reminders by.
|
||||||
dataSource.updateTask(taskId, form)
|
val before = current?.let { remindersBeforeSave(form, it, settings) }
|
||||||
return@withContext
|
val row = resolvedRow(current, taskId)
|
||||||
|
dataSource.updateTask(row, form, reminders)
|
||||||
|
before?.let { remindPastOnSave(row, it, form, stored.pastDefaults, settings) }
|
||||||
|
} else {
|
||||||
|
dataSource.updateInstance(taskId, instance, form, reminders)
|
||||||
}
|
}
|
||||||
// ⚠️ Written to the series, and then put back. Forking an occurrence
|
|
||||||
// copies the task's *current* properties onto the new override row,
|
|
||||||
// so setting the alarm beforehand is the only way to carry it
|
|
||||||
// across — and leaving it there would silently give every other
|
|
||||||
// occurrence in the series the reminder the user set on one of them.
|
|
||||||
val seriesReminders = dataSource.reminders()[taskId].orEmpty()
|
|
||||||
writeReminders(taskId, form)
|
|
||||||
try {
|
|
||||||
dataSource.updateInstance(taskId, instance, form)
|
|
||||||
} finally {
|
|
||||||
dataSource.setReminders(taskId, seriesReminders)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The form's before-due reminders; a start-relative one from elsewhere is kept as it was. */
|
|
||||||
private fun writeReminders(taskId: Long, form: TaskForm) {
|
|
||||||
val kept = dataSource.reminders()[taskId].orEmpty().filter { it.fromStart }
|
|
||||||
dataSource.setReminders(taskId, kept + form.reminders.distinct().sorted().map { TaskReminder(it) })
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun setCancelled(taskId: Long, occurrenceStart: Instant?, cancelled: Boolean) =
|
override suspend fun setCancelled(taskId: Long, occurrenceStart: Instant?, cancelled: Boolean) =
|
||||||
@@ -246,28 +282,22 @@ class TasksRepositoryImpl @Inject constructor(
|
|||||||
override suspend fun deleteTask(taskId: Long, occurrenceStart: Instant?, scope: RecurringScope) =
|
override suspend fun deleteTask(taskId: Long, occurrenceStart: Instant?, scope: RecurringScope) =
|
||||||
withContext(io) {
|
withContext(io) {
|
||||||
val current = dataSource.task(taskId, occurrenceStart)
|
val current = dataSource.task(taskId, occurrenceStart)
|
||||||
|
// An occurrence that is gone leaves nothing to delete; its series stays.
|
||||||
|
if (current == null && occurrenceStart != null) return@withContext
|
||||||
val seriesId = current?.seriesId
|
val seriesId = current?.seriesId
|
||||||
val occurrence = current?.occurrenceStart
|
val occurrence = current?.occurrenceStart
|
||||||
if (seriesId == null || occurrence == null) return@withContext deleteWithSubtasks(taskId)
|
if (seriesId == null || occurrence == null) return@withContext dataSource.deleteWithSubtasks(resolvedRow(current, taskId))
|
||||||
when (scope) {
|
when (scope) {
|
||||||
RecurringScope.ThisOccurrence ->
|
RecurringScope.ThisOccurrence ->
|
||||||
// An override row deletes itself into an EXDATE; a generated
|
// An override row deletes itself into an EXDATE; a generated
|
||||||
// occurrence has no row to delete.
|
// occurrence has no row to delete.
|
||||||
if (current.taskId != seriesId) dataSource.deleteTask(current.taskId)
|
if (current.taskId != seriesId) dataSource.deleteOverride(current.taskId, occurrence)
|
||||||
else dataSource.deleteOccurrence(seriesId, occurrence)
|
else dataSource.deleteOccurrence(seriesId, occurrence)
|
||||||
RecurringScope.ThisAndFollowing -> dataSource.deleteFollowing(seriesId, occurrence)
|
RecurringScope.ThisAndFollowing -> dataSource.deleteFollowing(seriesId, occurrence)
|
||||||
RecurringScope.AllOccurrences -> deleteWithSubtasks(seriesId)
|
RecurringScope.AllOccurrences -> dataSource.deleteWithSubtasks(seriesId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A parent goes with its subtasks; left behind they would hang off a tombstone. */
|
|
||||||
private fun deleteWithSubtasks(taskId: Long) {
|
|
||||||
dataSource.subtasks(taskId).map { it.taskId }.distinct()
|
|
||||||
.filter { it != taskId }
|
|
||||||
.forEach { dataSource.deleteTask(it) }
|
|
||||||
dataSource.deleteTask(taskId)
|
|
||||||
}
|
|
||||||
|
|
||||||
override suspend fun createLocalList(name: String, color: Int): Long =
|
override suspend fun createLocalList(name: String, color: Int): Long =
|
||||||
withContext(io) { dataSource.createLocalList(name, color) }
|
withContext(io) { dataSource.createLocalList(name, color) }
|
||||||
|
|
||||||
@@ -275,11 +305,20 @@ class TasksRepositoryImpl @Inject constructor(
|
|||||||
withContext(io) { dataSource.updateList(listId, name, color) }
|
withContext(io) { dataSource.updateList(listId, name, color) }
|
||||||
|
|
||||||
override suspend fun deleteList(listId: Long) =
|
override suspend fun deleteList(listId: Long) =
|
||||||
withContext(io) { dataSource.deleteList(listId) }
|
withContext(io) {
|
||||||
|
val store = providerResolver.mode()
|
||||||
|
dataSource.deleteList(listId)
|
||||||
|
runCatching { settingsPrefs.forgetDeletedLists(listOf(listId), store) }
|
||||||
|
.onFailure { Log.w(TAG, "Forgetting a deleted list failed", it) }
|
||||||
|
Unit
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun reorderLists(listIds: List<Long>) =
|
override suspend fun reorderLists(listIds: List<Long>) =
|
||||||
withContext(io) { dataSource.reorderLists(listIds) }
|
withContext(io) { dataSource.reorderLists(listIds) }
|
||||||
|
|
||||||
|
override fun supportsRepeatFromCompletion(): Boolean = providerResolver.mode() == StorageMode.OWN
|
||||||
|
override fun supportsUntimedEnds(): Boolean = providerResolver.mode() == StorageMode.OWN
|
||||||
|
|
||||||
override fun providerStatus(): ProviderStatus {
|
override fun providerStatus(): ProviderStatus {
|
||||||
// Our own store is always ready: it ships with the app, needs no provider
|
// Our own store is always ready: it ships with the app, needs no provider
|
||||||
// and no grant. The permission gate only ever applied to External mode —
|
// and no grant. The permission gate only ever applied to External mode —
|
||||||
@@ -312,7 +351,72 @@ class TasksRepositoryImpl @Inject constructor(
|
|||||||
ticks.close()
|
ticks.close()
|
||||||
}
|
}
|
||||||
}.flowOn(io)
|
}.flowOn(io)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The row a read for [taskId] resolved to — a past occurrence the series moved
|
||||||
|
* past is a task of its own — which is the one a write has to address.
|
||||||
|
*/
|
||||||
|
private fun resolvedRow(resolved: Task?, taskId: Long): Long = resolved?.taskId ?: taskId
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The reminders [current] (null: a new task) has before a save of [form],
|
||||||
|
* past ones and defaults older than the task included; null when the save
|
||||||
|
* rings nothing at once (#106) — as for a task that had a reminder go off
|
||||||
|
* already: it rang for that, and moving an overdue task about is no news.
|
||||||
|
*/
|
||||||
|
private fun remindersBeforeSave(form: TaskForm, current: Task?, settings: Settings): List<ScheduledReminder>? {
|
||||||
|
if (!settings.ringsPastOnSave || form.rrule != null || (form.start == null && form.due == null)) return null
|
||||||
|
if (current == null) return emptyList()
|
||||||
|
if (current.isRecurring) return null
|
||||||
|
return logFailure("Reading the reminders before a save failed") {
|
||||||
|
val own = dataSource.reminders(current.taskId)
|
||||||
|
val now = Clock.System.now().toEpochMilliseconds()
|
||||||
|
val zone = ZoneId.systemDefault()
|
||||||
|
if (ReminderPlanner.anyRung(current, own, settings, zone, now)) return null
|
||||||
|
ReminderPlanner.triggers(current, own, settings, zone, sinceCreated = false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rings [taskId] for the reminders its save put at or before now that it
|
||||||
|
* did not have [before], [pastDefaults] being the defaults it left out as
|
||||||
|
* past. Worked out here, against the task as this save
|
||||||
|
* left it, so a later save cannot change what this one rings; the ringing
|
||||||
|
* itself runs off the save's path, which neither waits on a scheduler pass
|
||||||
|
* nor fails with it.
|
||||||
|
*/
|
||||||
|
private fun remindPastOnSave(
|
||||||
|
taskId: Long,
|
||||||
|
before: List<ScheduledReminder>,
|
||||||
|
form: TaskForm,
|
||||||
|
pastDefaults: List<TaskReminder>,
|
||||||
|
settings: Settings,
|
||||||
|
) {
|
||||||
|
logFailure("Ringing a reminder on save failed") {
|
||||||
|
val zone = ZoneId.systemDefault()
|
||||||
|
val saved = dataSource.task(taskId) ?: return@logFailure
|
||||||
|
val after = ReminderPlanner.afterSave(saved, dataSource.reminders(taskId), pastDefaults, settings, zone, form.startsNow)
|
||||||
|
val past = ReminderPlanner.pastOnSave(before, after, Clock.System.now().toEpochMilliseconds())
|
||||||
|
if (past.isEmpty()) return@logFailure
|
||||||
|
appScope.launch {
|
||||||
|
logFailure("Ringing a reminder on save failed") { reminderScheduler.remindPastOnSave(taskId, past, pastDefaults, form.startsNow) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private inline fun <T> logFailure(what: String, block: () -> T): T? =
|
||||||
|
try {
|
||||||
|
block()
|
||||||
|
} catch (e: CancellationException) {
|
||||||
|
throw e
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, what, e)
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private const val TAG = "TasksRepository"
|
||||||
|
|
||||||
/** Subtask levels a duplicate follows; deeper than any real list, short of a cycle. */
|
/** Subtask levels a duplicate follows; deeper than any real list, short of a cycle. */
|
||||||
private const val MAX_COPY_DEPTH = 8
|
private const val MAX_COPY_DEPTH = 8
|
||||||
Loaded 100 of 358 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user