Dedupe native transfer/notification code and split ServerProvider into focused controllers
Build APK / build (push) Successful in 5m20s
Build APK / build (push) Successful in 5m20s
Consolidates duplicated GET/PUT/notification-channel logic across DownloadService/ShareUploadService/SyncEngine into shared Kotlin helpers, gives upload/download real batch queueing instead of dropping a second concurrent batch, and dedupes repeated Dart channel-argument boilerplate. Replaces the 2300+ line ServerProvider god object with ten focused ChangeNotifiers (SessionController, SettingsController, FilesController, PhotosController, FavoritesController, TrashController, SharesController, RecentController, SyncStatusController, PickController) plus ItemOperations, a plain coordinator for cross-domain item mutations - fixing the coupling where device-sync status, per-tab data, and global UI prefs all lived in one object. Updates every view/widget call site accordingly and refreshes the architecture/server/standards/styling docs to match. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -8,7 +8,9 @@ lib/
|
||||
# MainShellView (bottom-nav shell), share-intent listener
|
||||
models/ # plain data classes (NextcloudItem, NextcloudShare,
|
||||
# SavedAccount, AppTab, ...)
|
||||
providers/ # ServerProvider — the single app-wide ChangeNotifier
|
||||
providers/ # per-domain ChangeNotifiers (SessionController,
|
||||
# FilesController, PhotosController, ...) plus
|
||||
# ItemOperations, a plain cross-domain coordinator
|
||||
services/ # network/IO: NextcloudService, LoginFlowService,
|
||||
# AccountStore, AppLockService
|
||||
theme/ # AppTheme (Material 3 ThemeData)
|
||||
@@ -23,91 +25,119 @@ lib/
|
||||
`views/` files are screens routed to directly (a tab, or pushed via
|
||||
`Navigator`). `widgets/` files are building blocks used by more than one
|
||||
view (or complex enough to warrant their own file) — nothing in `widgets/`
|
||||
owns app state itself; it reads it from the `ServerProvider` passed down or
|
||||
read via `context.watch`/`context.read`.
|
||||
owns app state itself; it reads whichever controller(s) it needs via
|
||||
`context.watch`/`context.read`.
|
||||
|
||||
## State management
|
||||
|
||||
There is exactly one `ChangeNotifier`: [`ServerProvider`](../../lib/providers/server_provider.dart)
|
||||
(~1500 lines). It is created once in `main()` and provided at the root with
|
||||
`provider`'s `ChangeNotifierProvider`. It owns:
|
||||
State used to live in one 2300+ line `ServerProvider` god object. It's now
|
||||
split into ten focused `ChangeNotifier`s plus one plain coordinator, all
|
||||
registered in `main()`'s `MultiProvider` in dependency order (later
|
||||
providers read earlier ones via `context.read` in their `create` callback —
|
||||
safe since none of these providers are ever recreated for the app's
|
||||
lifetime; account switching is internal state on `SessionController`, not a
|
||||
new provider instance):
|
||||
|
||||
- **Multi-account state**: the list of saved accounts (`accounts`), which one
|
||||
is active (`activeAccountId`/`activeAccount`), and a `_sessionGeneration`
|
||||
counter incremented on every account switch so an in-flight fetch from the
|
||||
account just left can recognize it's stale and discard its result instead
|
||||
of writing into the newly-active account's state — every method that
|
||||
writes fetched data into a shared field (`refreshData`, `fetchAllMedia`,
|
||||
`fetchTrash`, `fetchShares`, `fetchRecent`,
|
||||
`_applyCredentialsForAccount`) captures the generation at entry and checks
|
||||
it before each write. See `server.md` for the full account-switch/storage
|
||||
story.
|
||||
- auth/session state for whichever account is active (`isLoggedIn`,
|
||||
`isRestoringSession`, login-flow status)
|
||||
- the active `NextcloudService` instance (null until logged in)
|
||||
- all fetched data, scoped to the active account (`items`, `quota`,
|
||||
`activities`, `photoItems`, `trashItems`, `shares`, `recentItems`) — all
|
||||
torn down and refetched fresh on every account switch (no simultaneous
|
||||
multi-account state; only one account's content is ever live in memory)
|
||||
- navigation-within-files state (`currentFolderPath`, `pathStack`), plus an
|
||||
in-memory `_directoryCache` keyed by folder path (see `CachePolicy`)
|
||||
- UI settings that persist across launches — split into **global** (theme
|
||||
mode, seed color, dynamic-color toggle, bottom-bar opacity/blur,
|
||||
tap-tab-to-scroll-top, seek bar style, tab order/visibility/default, swipe
|
||||
actions, login lock, sync-on-cellular — see below) and **per-account**
|
||||
(grid/list view, favorites-only, show-hidden, storage scope, Photos sort,
|
||||
Files' per-folder sort map, cache policy, synced folders) — see
|
||||
`server.md` for exactly which is which and why
|
||||
- **Login lock** (`loginLockEnabled`/`lockAccountSwitching`/
|
||||
`lockHiddenFiles`/`needsUnlock`): an app-wide PIN/biometric gate via
|
||||
`AppLockService` (a thin wrapper over `local_auth` — this app never
|
||||
stores or hashes a PIN itself, it delegates entirely to whatever
|
||||
credential the OS already has configured). `needsUnlock` is
|
||||
`loginLockEnabled && !_isUnlocked`, where `_isUnlocked` is transient
|
||||
(never persisted) and reset to `false` on every backgrounding
|
||||
(`didChangeAppLifecycleState`, `AppLifecycleState.paused`) so the lock has
|
||||
real value rather than only firing once per cold start. `switchAccount`/
|
||||
`cycleToNextAccount`/`cycleToPreviousAccount` and *enabling* (not
|
||||
disabling) `showHiddenFiles`/`showHiddenPhotos` each call the shared
|
||||
`_passGate` helper, which no-ops unless both `loginLockEnabled` and the
|
||||
relevant per-feature toggle are on.
|
||||
- [`SessionController`](../../lib/providers/session_controller.dart) — the
|
||||
foundation everything else depends on. Owns multi-account state (the
|
||||
saved-accounts list, which one is active, `sessionGeneration` — see
|
||||
below), auth/login-flow state (`isLoggedIn`, `isRestoringSession`,
|
||||
`loginFlowStatus`), the active `NextcloudService` instance, and login lock
|
||||
(`loginLockEnabled`/`lockAccountSwitching`/`lockHiddenFiles`/
|
||||
`needsUnlock`/`passGate`). Exposes `addAccountClearedListener`/
|
||||
`addAccountActivatedListener` (plain `List<VoidCallback>`) so sibling
|
||||
controllers — constructed after `SessionController` and unable to hold a
|
||||
forward reference to it — can react to login/logout/account-switch
|
||||
without a circular dependency.
|
||||
- [`SettingsController`](../../lib/providers/settings_controller.dart) —
|
||||
global UI prefs independent of login state: theme mode/seed color/dynamic
|
||||
color, bottom-bar opacity/blur, tap-tab-to-scroll-top, seek bar style, tab
|
||||
order/visibility/default (`requestedTab`/`requestTab`/
|
||||
`consumeRequestedTab`), swipe actions.
|
||||
- [`FilesController`](../../lib/providers/files_controller.dart) — the
|
||||
Files tab: `items`/`currentFolderPath`/`pathStack`, the in-memory
|
||||
`_directoryCache` (see `CachePolicy`), per-account display prefs
|
||||
(grid/list, hidden files, storage scope, sort field/order, per-folder
|
||||
sort map), and the shared `applyCommonFilters`/`applyFilesDisplayPrefs`
|
||||
helpers Photos/Favorites reuse rather than duplicating the same
|
||||
filter/sort logic.
|
||||
- [`PhotosController`](../../lib/providers/photos_controller.dart) /
|
||||
[`FavoritesController`](../../lib/providers/favorites_controller.dart) —
|
||||
each depends on `FilesController` for the shared storage-scope toggle and
|
||||
display-prefs helpers, but owns its own account-wide item list and
|
||||
independent favorites-only/hidden/sort state.
|
||||
- [`TrashController`](../../lib/providers/trash_controller.dart) /
|
||||
[`SharesController`](../../lib/providers/shares_controller.dart) /
|
||||
[`RecentController`](../../lib/providers/recent_controller.dart) — one
|
||||
per remaining tab, each just `items`/`isLoading`/`errorMessage` plus that
|
||||
tab's own fetch/mutate methods. All three (plus Photos/Favorites) share
|
||||
one shape: capture `session.sessionGeneration` at fetch entry, set
|
||||
loading/clear error, fetch, check the generation before writing the
|
||||
result, `notifyListeners()`.
|
||||
- [`SyncStatusController`](../../lib/providers/sync_status_controller.dart)
|
||||
— device-sync settings and live status (`syncStatusFor(item)`,
|
||||
`syncHeaderStatus`, conflicts), subscribed to `SyncService`'s status
|
||||
stream directly rather than living inside the same object as the item
|
||||
lists it decorates.
|
||||
- [`PickController`](../../lib/providers/pick_controller.dart) — "being
|
||||
picked by another app" state (`pickRequest`/`isPicking`/`confirmPick`/
|
||||
`itemMatchesPickFilter`) — see `server.md`.
|
||||
- [`ItemOperations`](../../lib/providers/item_operations.dart) — not a
|
||||
`ChangeNotifier`; a plain, `const`-constructible class holding direct
|
||||
references to `SessionController`/`FilesController`/`PhotosController`/
|
||||
`FavoritesController`. The one place that knows how a mutation
|
||||
(delete/rename/move/copy/favorite-toggle/create-folder) ripples across
|
||||
those three tabs' independent item lists — deliberately direct
|
||||
references rather than a generic event bus, so a caller can `await` a
|
||||
mutation and know every affected list has already been reconciled by the
|
||||
time it returns, the same guarantee the old god object gave for free.
|
||||
Also home to the file-details sheet's per-item pass-throughs
|
||||
(shares/activity/versions/restore) — stateless, so they don't need a
|
||||
controller of their own.
|
||||
|
||||
New **global** state belongs on `ServerProvider` as a private field + getter
|
||||
+ a method that mutates it, calls `notifyListeners()`, and persists via
|
||||
`_prefsFuture`. New **per-account** state follows the same shape but
|
||||
persists through `_persistAccountPref` (namespaces the pref key under
|
||||
`sessionGeneration` (on `SessionController`, read by every other
|
||||
controller) is incremented on every account switch so an in-flight fetch
|
||||
from the account just left can recognize it's stale and discard its result
|
||||
instead of writing into the newly-active account's state — see `server.md`
|
||||
for the full account-switch/storage story.
|
||||
|
||||
New **global** state belongs on `SettingsController` as a private field +
|
||||
getter + a method that mutates it, calls `notifyListeners()`, and persists
|
||||
via its own prefs future. New **per-account** state follows the same shape
|
||||
on whichever controller owns that domain, but persists through
|
||||
`_persistAccountPref` (namespaces the pref key under
|
||||
`acct_<activeAccountId>_...` via `AccountStore.accountPrefKey`) and must be
|
||||
reset/reloaded in `_applyAccountPrefs` so it's correct after a switch.
|
||||
Screen-local state (e.g. a `TextEditingController`, an expanded/collapsed
|
||||
flag) stays in that view's own `State` class — see `standards.md` for the
|
||||
split.
|
||||
reset/reloaded on `SessionController`'s account-activated listener so it's
|
||||
correct after a switch. Screen-local state (e.g. a `TextEditingController`,
|
||||
an expanded/collapsed flag) stays in that view's own `State` class — see
|
||||
`standards.md` for the split.
|
||||
|
||||
There's no separate repository/data layer: views call `ServerProvider`
|
||||
methods directly, which call `NextcloudService`/`LoginFlowService`/
|
||||
`AccountStore`/`AppLockService`.
|
||||
There's no separate repository/data layer: views call controller methods
|
||||
directly, which call `NextcloudService`/`LoginFlowService`/`AccountStore`/
|
||||
`AppLockService`.
|
||||
|
||||
## Navigation / screen flow
|
||||
|
||||
`main.dart`'s `NextcloudApp` picks the app's `home` screen from provider
|
||||
state, no named routes:
|
||||
`main.dart`'s `NextcloudApp` picks the app's `home` screen from
|
||||
`SessionController` state, no named routes:
|
||||
|
||||
- `provider.isRestoringSession` → `_SplashView` (monochrome app icon,
|
||||
- `session.isRestoringSession` → `_SplashView` (monochrome app icon,
|
||||
tinted via `ColorFiltered` to the theme's `onSurface` so it works in both
|
||||
light/dark, plus a small spinner, while `flutter_secure_storage`/
|
||||
`shared_preferences` are read on startup)
|
||||
- else `!provider.isLoggedIn` → `LoginView` (server-address entry + Login
|
||||
- else `!session.isLoggedIn` → `LoginView` (server-address entry + Login
|
||||
Flow v2) — `isLoggedIn` is only ever false here or after the last saved
|
||||
account is removed; switching between multiple saved accounts never
|
||||
routes through this screen (see `server.md`)
|
||||
- else `provider.needsUnlock` → `LockScreenView` (login lock — see above)
|
||||
- else `session.needsUnlock` → `LockScreenView` (login lock — see above)
|
||||
- else `MainShellView`
|
||||
|
||||
`MainShellView` is a bottom-nav `IndexedStack` over up to 7 tabs — Files,
|
||||
Photos, Favorites, Activity, Trash, Shares, Recent — user-configurable
|
||||
(order, visibility up to `maxVisibleTabs`, default tab) via
|
||||
`AppTab`/`ServerProvider` and rendered through `buildAppTabView`
|
||||
`AppTab`/`SettingsController` and rendered through `buildAppTabView`
|
||||
(`widgets/app_tab_view_builder.dart`). `maxVisibleTabs` (5) is less than the
|
||||
total tab count, and `ServerProvider._enforceMaxVisibleTabs` already
|
||||
total tab count, and `SettingsController._enforceMaxVisibleTabs` already
|
||||
auto-hides overflow on load (fresh install, or - as when Favorites was
|
||||
added - an existing saved tab order from before a new tab existed), so
|
||||
adding a tab to the `AppTab` enum needs no extra migration.
|
||||
@@ -125,7 +155,7 @@ result `Uri`s instead of a share intent's) rather than a separate
|
||||
in-app-only upload, so both entry points get the same destination picker
|
||||
and the same durable background-service upload. It similarly owns the pick-intent listener
|
||||
(`PickIntentService` - see `server.md` for the full "being picked by
|
||||
another app" story) that feeds `ServerProvider.pickRequest`; while
|
||||
another app" story) that feeds `PickController.pickRequest`; while
|
||||
`isPicking`, the visible tab list is overridden to just Files and Photos
|
||||
regardless of the user's own hidden/reordered tab settings, since those
|
||||
are the only two views that know how to handle a picking-mode tap and the
|
||||
@@ -170,9 +200,9 @@ The Move/Copy destination picker
|
||||
pushed from Files/Photos' selection toolbar - see `server.md` for the
|
||||
backend side) visually mirrors `ShareUploadView`'s browser the same way,
|
||||
but is a deliberately different case for state: it does **not** reuse
|
||||
`ServerProvider`'s shared `currentFolderPath`/`pathStack`/`items`, and
|
||||
`FilesController`'s shared `currentFolderPath`/`pathStack`/`items`, and
|
||||
owns its own local navigation state instead, fetching through the
|
||||
stateless `ServerProvider.fetchFolderListing`/`applyFilesDisplayPrefs`
|
||||
stateless `FilesController.fetchFolderListing`/`applyFilesDisplayPrefs`
|
||||
pair. `ShareUploadView` can get away with hijacking the shared state
|
||||
because it always resets to root on entry and pops all the way to the
|
||||
app's root route on completion - fine for a cold share-intent launch with
|
||||
|
||||
+62
-49
@@ -35,9 +35,9 @@ via [`LoginFlowService`](../../lib/services/login_flow_service.dart):
|
||||
credentials (the same class of bug the Custom-Tab-reuse issue above
|
||||
was, just recurring one layer down once everything moved to the owned
|
||||
WebView).
|
||||
3. `ServerProvider` polls `LoginFlowService.poll(pollEndpoint, token)` every
|
||||
3. `SessionController` polls `LoginFlowService.poll(pollEndpoint, token)` every
|
||||
2 seconds (`Timer.periodic`, see `_pollTimer`/`_pollTimeoutTimer` in
|
||||
`server_provider.dart`) until it gets a 200 with `server`/`loginName`/
|
||||
`session_controller.dart`) until it gets a 200 with `server`/`loginName`/
|
||||
`appPassword`, a non-404 error, or a 10-minute timeout. A single dropped
|
||||
connection mid-poll (`http.ClientException`) is swallowed and retried on
|
||||
the next tick rather than aborting the whole flow.
|
||||
@@ -62,7 +62,7 @@ below.
|
||||
[`NextcloudService`](../../lib/services/nextcloud_service.dart) is the
|
||||
client for an authenticated session — constructed with `serverUrl` +
|
||||
`username` + the app password, one instance per login (held as
|
||||
`ServerProvider.service`, recreated on every login/switch/logout). It's
|
||||
`SessionController.service`, recreated on every login/switch/logout). It's
|
||||
effectively stateless per-instance (three final fields, headers rebuilt per
|
||||
request), which is what makes it trivial to have one saved per account
|
||||
rather than needing a rewrite for multi-account support.
|
||||
@@ -80,22 +80,24 @@ rather than needing a rewrite for multi-account support.
|
||||
for the Favorites tab) is WebDAV instead - the same `SEARCH` mechanism
|
||||
`fetchAllMedia`/`fetchRecentFiles` use, filtered by `oc:favorite` instead
|
||||
of mimetype/date. Favorites is a real tab
|
||||
(`views/favorites_view.dart`/`ServerProvider.favoriteItems`/
|
||||
`fetchAllFavorites`/`_allFavorites`), not a filter toggle scoped to
|
||||
(`views/favorites_view.dart`/`FavoritesController.items`/
|
||||
`fetchAll`/`_allFavorites`), not a filter toggle scoped to
|
||||
whatever folder the Files tab happens to be browsing (that's what it
|
||||
used to be - see the note below on why that didn't work). It shares
|
||||
Files' own sort/hidden/storage-scope/grid-list display prefs
|
||||
(`applyFilesDisplayPrefs`, also used by the Move/Copy destination
|
||||
picker) rather than a separate parallel settings dimension. Tapping a
|
||||
favorited folder switches to the Files tab, navigated there
|
||||
(`navigateToAbsoluteFolder` + `requestTab`); a favorited file opens
|
||||
directly from the Favorites tab itself. `deleteItem`/`renameItem`/move/
|
||||
copy all re-sync `_allFavorites` afterward via `_syncFavoritesIfLoaded`
|
||||
(only once Favorites has actually been opened this session, tracked by
|
||||
`_favoritesEverFetched`, so those actions don't pay for an extra request
|
||||
on every edit for an account that's never visited the tab) since none of
|
||||
them know how to patch `_allFavorites` in place the way
|
||||
`toggleItemFavorite` does (added/removed/updated by id, right inline).
|
||||
(`FilesController.navigateToAbsoluteFolder` +
|
||||
`SettingsController.requestTab`); a favorited file opens directly from
|
||||
the Favorites tab itself. `ItemOperations.deleteItem`/`renameItem`/move/
|
||||
copy all re-sync `FavoritesController._allFavorites` afterward via
|
||||
`FavoritesController.syncIfLoaded` (only once Favorites has actually been
|
||||
opened this session, tracked by `_everFetched`, so those actions don't
|
||||
pay for an extra request on every edit for an account that's never
|
||||
visited the tab) since none of them know how to patch `_allFavorites` in
|
||||
place the way `ItemOperations.toggleItemFavorite` does (added/removed/
|
||||
updated by id, right inline via `FavoritesController.applyFavoriteToggle`).
|
||||
**Note**: this used to be a "favorites-only" filter toggle on the Files
|
||||
tab's controls row instead of its own tab, filtering the currently
|
||||
browsed folder's `_items`. That had two real bugs in sequence: first,
|
||||
@@ -144,9 +146,9 @@ rather than needing a rewrite for multi-account support.
|
||||
for a folder ("collection"), so no extra `Depth` header is needed. They
|
||||
return the raw HTTP status rather than a bool: `412 Precondition Failed`
|
||||
is WebDAV's standard signal for "something's already there" when
|
||||
`Overwrite: F`, which is exactly the conflict `ServerProvider.moveItems`/
|
||||
`Overwrite: F`, which is exactly the conflict `ItemOperations.moveItems`/
|
||||
`copyItems` need to detect without a separate existence-check request
|
||||
per item. `ServerProvider` attempts every item in the batch first,
|
||||
per item. `ItemOperations` attempts every item in the batch first,
|
||||
collects conflicts into `MoveCopyResult.conflicts`
|
||||
(`models/move_copy_result.dart`), and only then shows one summary
|
||||
(`MoveCopyConflictSheet`) instead of prompting per conflict as they're
|
||||
@@ -157,11 +159,11 @@ rather than needing a rewrite for multi-account support.
|
||||
(`views/move_copy_destination_picker.dart`) is covered in
|
||||
`architecture.md`, including why it can't reuse the Files tab's shared
|
||||
navigation state the way `ShareUploadView` does.
|
||||
- **Uploads**: there's no more in-app-only upload path - `NextcloudService`/
|
||||
`ServerProvider.uploadFileFromPath` were removed once the Files tab's "+"
|
||||
→ "Upload File" was unified with the share-to-upload flow (below). Every
|
||||
upload, however it's triggered, now goes through `ShareUploadView`
|
||||
(caller-chosen destination via `navigateToAbsoluteFolder`, then
|
||||
- **Uploads**: there's no more in-app-only upload path - `NextcloudService`'s
|
||||
own `uploadFileFromPath` was removed once the Files tab's "+" → "Upload
|
||||
File" was unified with the share-to-upload flow (below). Every upload,
|
||||
however it's triggered, now goes through `ShareUploadView` (caller-chosen
|
||||
destination via `FilesController.navigateToAbsoluteFolder`, then
|
||||
`UploadService`/`ShareUploadService.kt`).
|
||||
- **Receiving a shared file from another app**: hand-rolled in
|
||||
`MainActivity.kt` (Android `ACTION_SEND`/`ACTION_SEND_MULTIPLE`,
|
||||
@@ -178,7 +180,7 @@ rather than needing a rewrite for multi-account support.
|
||||
story. The fix: `getInitialShare`/`onNewShare` only ever query cheap Uri
|
||||
metadata (name/size/mime, not content) so `ShareUploadView`'s destination
|
||||
picker - which mirrors the Files tab's own controls/filters/listing,
|
||||
reusing the same `ServerProvider` fields and `widgets/item_icon.dart` -
|
||||
reusing the same `FilesController` fields and `widgets/item_icon.dart` -
|
||||
always appears instantly regardless of file size.
|
||||
- **Uploading a shared file**: once the user picks a destination in
|
||||
`ShareUploadView`, [`UploadService`](../../lib/services/upload_service.dart)
|
||||
@@ -218,7 +220,7 @@ Google Drive/Instagram's "choose a file" flow), the reverse direction of
|
||||
([`PickIntentService`](../../lib/services/pick_intent_service.dart)/
|
||||
[`PickRequest`](../../lib/models/pick_request.dart)) - same
|
||||
cold-start-vs-already-running split as the share-intent channels.
|
||||
- `ServerProvider.pickRequest`/`isPicking` drive picking mode app-wide once
|
||||
- `PickController.pickRequest`/`isPicking` drive picking mode app-wide once
|
||||
`MainShellView` learns about a request at startup or via
|
||||
`onNewPickRequest`. While picking, `MainShellView` restricts the visible
|
||||
bottom-nav tabs to just Files and Photos (see `architecture.md`) -
|
||||
@@ -227,7 +229,7 @@ Google Drive/Instagram's "choose a file" flow), the reverse direction of
|
||||
open/select behavior (folders still navigate; a mime-mismatched file is
|
||||
rejected with a snackbar; matching files toggle-select or immediately
|
||||
confirm depending on `PickRequest.allowMultiple`).
|
||||
- `ServerProvider.confirmPick` downloads the selected item(s) to a
|
||||
- `PickController.confirmPick` downloads the selected item(s) to a
|
||||
`picker/` scratch subfolder in the app's cache dir (`downloadToFile`,
|
||||
same as any other download) - each item into its own `picker/<item.id>/`
|
||||
subfolder, keeping the on-disk filename as plain `item.name` rather than
|
||||
@@ -297,9 +299,9 @@ the whole engine is plain Kotlin using Android's WorkManager directly.
|
||||
from `SyncEngine`'s durable per-account state map
|
||||
(`SyncEngine.loadState(accountId).keys`) each time a snapshot is built,
|
||||
so there's one source of truth for "synced" instead of two that could
|
||||
drift. `SyncService.getStatus()` (one-shot, seeds `ServerProvider` right
|
||||
after login/account-switch) and `SyncService.statusStream` (live) both
|
||||
return the same snapshot shape. `ServerProvider.syncHeaderStatus`
|
||||
drift. `SyncService.getStatus()` (one-shot, seeds `SyncStatusController`
|
||||
right after login/account-switch) and `SyncService.statusStream` (live)
|
||||
both return the same snapshot shape. `SyncStatusController.syncHeaderStatus`
|
||||
(off/syncing/done/alert - drives `SyncedHeaderScaffold`'s persistent
|
||||
chip/panel, replacing what used to be the WebDAV-refresh-loading
|
||||
indicator there) and `syncStatusFor(item)` (none/syncing/synced/conflict
|
||||
@@ -310,8 +312,8 @@ the whole engine is plain Kotlin using Android's WorkManager directly.
|
||||
shared companion function; `SyncConflictReceiver` (the notification
|
||||
action) and `MainActivity.kt`'s `resolveConflict` MethodChannel method
|
||||
(the sync header's "Keep local"/"Use server" buttons,
|
||||
`ServerProvider.resolveSyncConflict`) both just call it, so there's one
|
||||
resolution code path regardless of which surface triggered it.
|
||||
`SyncStatusController.resolveSyncConflict`) both just call it, so there's
|
||||
one resolution code path regardless of which surface triggered it.
|
||||
- **Conflicts are never auto-resolved.** The notification's "Keep local"/
|
||||
"Use server" actions are `PendingIntent.getBroadcast`s (same shape as the
|
||||
Cancel action on upload/download notifications, just broadcast instead of
|
||||
@@ -329,12 +331,13 @@ the whole engine is plain Kotlin using Android's WorkManager directly.
|
||||
so changing the synced-folder list, the active account, or the Wi-Fi-only
|
||||
setting means cancelling and re-enqueueing, not updating in place.
|
||||
[`SyncService`](../../lib/services/sync_service.dart) (Dart) wraps this -
|
||||
`ServerProvider` calls `reschedule` after every successful login/account
|
||||
switch and every synced-folder/`syncOnCellular` change, and `cancel` on
|
||||
logout/last-account-removed. The network constraint is
|
||||
`NetworkType.UNMETERED` by default (`!syncOnCellular`, Wi-Fi only) or
|
||||
`NetworkType.CONNECTED` if the user's opted into cellular sync.
|
||||
- Synced-path list (`ServerProvider.syncedPaths` - files or folders, not
|
||||
`SyncStatusController` calls `SyncService.reschedule` after every
|
||||
successful login/account switch and every synced-folder/`syncOnCellular`
|
||||
change, and `SyncService.cancel` on logout/last-account-removed. The
|
||||
network constraint is `NetworkType.UNMETERED` by default
|
||||
(`!syncOnCellular`, Wi-Fi only) or `NetworkType.CONNECTED` if the user's
|
||||
opted into cellular sync.
|
||||
- Synced-path list (`SyncStatusController.syncedPaths` - files or folders, not
|
||||
just folders despite the name of the underlying pref/native `Data` key,
|
||||
which stayed `ui_synced_folders`/`folders` to avoid a storage-key
|
||||
migration for a rename) follows the standard per-account-pref pattern
|
||||
@@ -383,7 +386,7 @@ the whole engine is plain Kotlin using Android's WorkManager directly.
|
||||
landed via `adb shell run-as`/a rooted shell, not a regular file
|
||||
manager UI.
|
||||
- **Already-synced files skip the network** in two places:
|
||||
`ServerProvider.localSyncedFilePath(item)` is a pure function of the
|
||||
`SyncStatusController.localSyncedFilePath(item)` is a pure function of the
|
||||
remote path (mirrors `SyncEngine.kt`'s `syncRoot` layout exactly, so Dart
|
||||
never needs to read the native sync-state `SharedPreferences`) that
|
||||
returns the local mirror path if it exists on disk. `ShareSheet`'s "Share
|
||||
@@ -394,7 +397,7 @@ the whole engine is plain Kotlin using Android's WorkManager directly.
|
||||
## Multi-account storage & session persistence
|
||||
|
||||
[`AccountStore`](../../lib/services/account_store.dart) owns everything
|
||||
account-identity-related; `ServerProvider` owns everything about which
|
||||
account-identity-related; `SessionController` owns everything about which
|
||||
account is *currently* live (see `architecture.md`).
|
||||
|
||||
- **Per-account secrets**: one `flutter_secure_storage` key per account,
|
||||
@@ -413,26 +416,36 @@ account is *currently* live (see `architecture.md`).
|
||||
storage scope, show-hidden ×2, Photos sort field/ascending, Files'
|
||||
per-folder sort map, cache policy/interval — the full list is
|
||||
`AccountStore.perAccountPrefKeys`) are namespaced `acct_<accountId>_<key>`
|
||||
and reloaded on every switch via `ServerProvider._applyAccountPrefs`.
|
||||
and owned by whichever controller that domain belongs to (e.g.
|
||||
`FilesController` for grid/list/storage-scope/sort,
|
||||
`PhotosController` for Photos' own sort/filter). Each reloads its own
|
||||
slice in its `_onAccountActivated` listener, registered via
|
||||
`SessionController.addAccountActivatedListener` in its constructor -
|
||||
there's no longer one central method that reloads every domain's prefs at
|
||||
once; `SessionController` just fires the notification, and every sibling
|
||||
controller reacts independently.
|
||||
- **Legacy migration**: `AccountStore.migrateLegacyIfNeeded` runs once ever
|
||||
(guarded by the `account_migration_v1_done` flag), turning a pre-multi-
|
||||
account install's 3 flat secure-storage keys + flat browsing prefs into
|
||||
the first saved (and active) account, so upgrading users are never logged
|
||||
out. Never assume the legacy keys are gone — always check the migration
|
||||
flag rather than the keys' absence.
|
||||
- On startup, `ServerProvider._init()` awaits the migration, loads the
|
||||
account list + active id, then `_restoreSession()` looks up the active
|
||||
account's password and calls `_applyCredentialsForAccount` (the renamed,
|
||||
generation-guarded, account-aware version of what used to be
|
||||
`_applyCredentials`) to rebuild the session without re-hitting the login
|
||||
flow.
|
||||
- On startup, `SessionController`'s constructor awaits the migration, loads
|
||||
the account list + active id, then `_restoreSession()` looks up the
|
||||
active account's password and calls `_applyCredentialsForAccount`
|
||||
(generation-guarded, account-aware) to rebuild the session without
|
||||
re-hitting the login flow - firing `_notifyAccountActivated()` on
|
||||
success, which is what triggers every sibling controller's own initial
|
||||
fetch.
|
||||
- **Switching accounts** (`switchAccount`/`cycleToNextAccount`/
|
||||
`cycleToPreviousAccount`/`removeAccount`'s fallback, plus landing on a
|
||||
freshly-added account) all funnel through the single `_activateAccount`
|
||||
engine: bump `_sessionGeneration`, cancel any pending login flow, clear
|
||||
every content field *without* ever setting `isLoggedIn` false (that's the
|
||||
detail that keeps `main.dart`'s root routing from bouncing through
|
||||
`LoginView` mid-switch), reload the target account's prefs, then verify
|
||||
engine: bump `sessionGeneration`, cancel any pending login flow, call
|
||||
`_notifyAccountCleared()` (every sibling controller's registered
|
||||
`addAccountClearedListener` callback resets that controller's own state)
|
||||
*without* ever setting `isLoggedIn` false (that's the detail that keeps
|
||||
`main.dart`'s root routing from bouncing through `LoginView` mid-switch),
|
||||
then verify
|
||||
its credentials and refetch everything. This is a full teardown-and-reload
|
||||
every time — there is deliberately no simultaneous multi-account state or
|
||||
background sync; only one account's content is ever live.
|
||||
@@ -454,7 +467,7 @@ account is *currently* live (see `architecture.md`).
|
||||
that's actually destructive/irreversible - UI call sites (`AccountView`)
|
||||
gate it behind a confirmation dialog; `logout()` doesn't need one.
|
||||
- Any UI code that calls either and might have ended the session should
|
||||
check `!provider.isLoggedIn` afterward and `Navigator.popUntil((r) =>
|
||||
check `!session.isLoggedIn` afterward and `Navigator.popUntil((r) =>
|
||||
r.isFirst)` if so — otherwise a screen pushed on top (Settings) is left
|
||||
stranded over a root route that's silently swapped to `LoginView`
|
||||
underneath it. Don't pop unconditionally — removing a *non-active*
|
||||
@@ -470,7 +483,7 @@ app. [`AppLockService`](../../lib/services/app_lock_service.dart) wraps
|
||||
`authenticate()` always delegates to whatever the OS already has configured
|
||||
(biometric, or device PIN/pattern/password as fallback, via
|
||||
`biometricOnly: false`). Never build a custom in-app PIN screen for this —
|
||||
extend `AppLockService`/the `ServerProvider` gates described in
|
||||
extend `AppLockService`/the `SessionController` gates described in
|
||||
`architecture.md` instead.
|
||||
|
||||
**Android native requirements** (both already done, keep them if you touch
|
||||
|
||||
@@ -29,28 +29,35 @@ class/method already makes obvious.
|
||||
- Private helpers/widgets are prefixed with `_` and live in the same file as
|
||||
their one caller; promote to `widgets/` only once something is reused
|
||||
across files.
|
||||
- Read provider state with `context.watch<ServerProvider>()` in `build`,
|
||||
and `context.read<ServerProvider>()` for one-off calls from callbacks
|
||||
(matches `LoginView._handleContinue`).
|
||||
- Read controller state with `context.watch<XController>()` in `build`, and
|
||||
`context.read<XController>()` for one-off calls from callbacks (matches
|
||||
`LoginView._handleContinue`). Pull in only the specific controller(s) a
|
||||
widget actually needs (e.g. `FilesController` + `SyncStatusController`
|
||||
for a Files tile), not a catch-all — see `architecture.md`'s "State
|
||||
management" section for the full controller split and what each one owns.
|
||||
|
||||
## `ServerProvider` conventions
|
||||
## Controller conventions
|
||||
|
||||
- Any method that fetches data and writes it into a shared field
|
||||
(`refreshData`, `fetchAllMedia`, `fetchTrash`, `fetchShares`,
|
||||
`fetchRecent`, `_applyCredentialsForAccount`) must guard against a stale
|
||||
write from an account the user has since switched away from: capture
|
||||
`final gen = _sessionGeneration;` at entry, and check
|
||||
`if (gen != _sessionGeneration) return;` immediately after each `await`
|
||||
before touching any field or calling `notifyListeners()`. Follow this
|
||||
pattern for any new fetch method added to the provider.
|
||||
- New persisted state on `ServerProvider` must be classified global vs.
|
||||
per-account (see `architecture.md`/`server.md`) up front — global state
|
||||
uses a plain `_prefsFuture.then((p) => p.setX(key, value))`; per-account
|
||||
state goes through `_persistAccountPref(key, (p, namespacedKey) =>
|
||||
p.setX(namespacedKey, value))` and must also be handled in
|
||||
`_applyAccountPrefs` (both the "reset to default when no account" and the
|
||||
"load for this account" branches) so it's correct immediately after a
|
||||
switch, not just at startup.
|
||||
(`FilesController.refreshData`, `PhotosController.fetchAllMedia`,
|
||||
`TrashController.fetchAll`, `SharesController.fetchAll`,
|
||||
`RecentController.fetchAll`, `SessionController._applyCredentialsForAccount`)
|
||||
must guard against a stale write from an account the user has since
|
||||
switched away from: capture `final gen = session.sessionGeneration;` at
|
||||
entry, and check `if (gen != session.sessionGeneration) return;`
|
||||
immediately after each `await` before touching any field or calling
|
||||
`notifyListeners()`. Follow this pattern for any new fetch method added
|
||||
to any controller.
|
||||
- New persisted state must be classified global vs. per-account (see
|
||||
`architecture.md`/`server.md`) up front and live on whichever controller
|
||||
owns that domain — global state (`SettingsController`) uses a plain
|
||||
`_prefsFuture.then((p) => p.setX(key, value))`; per-account state goes
|
||||
through `_persistAccountPref(key, (p, namespacedKey) =>
|
||||
p.setX(namespacedKey, value))` and must also be handled in that
|
||||
controller's own `_onAccountCleared`/`_onAccountActivated` listeners
|
||||
(registered via `SessionController.addAccountClearedListener`/
|
||||
`addAccountActivatedListener` in the controller's constructor) so it's
|
||||
correct immediately after a switch, not just at startup.
|
||||
|
||||
## Testing
|
||||
|
||||
@@ -59,7 +66,7 @@ class/method already makes obvious.
|
||||
`MethodChannel('plugins.it_nomads.com/flutter_secure_storage')` handler —
|
||||
and disable Google Fonts network fetching
|
||||
(`GoogleFonts.config.allowRuntimeFetching = false`) in `setUpAll`. Without
|
||||
these, `ServerProvider`'s session restore never resolves in the test
|
||||
these, `SessionController`'s session restore never resolves in the test
|
||||
sandbox (no plugin implementation is registered, so the read future just
|
||||
never completes) and the app stays on `_SplashView`'s indeterminate
|
||||
spinner, which makes `pumpAndSettle()` hang until its own timeout instead
|
||||
|
||||
@@ -57,15 +57,15 @@ widgets. Key points:
|
||||
new blur/shadow combo.
|
||||
- [`FloatingBottomNavBar`](../../lib/widgets/floating_bottom_bar.dart) — the
|
||||
main tab bar; opacity/blur are user-adjustable settings
|
||||
(`ServerProvider.bottomBarOpacity`/`bottomBarBlur`), not constants — pull
|
||||
new adjustable visual knobs from the provider the same way rather than
|
||||
hardcoding them.
|
||||
(`SettingsController.bottomBarOpacity`/`bottomBarBlur`), not constants —
|
||||
pull new adjustable visual knobs from `SettingsController` the same way
|
||||
rather than hardcoding them.
|
||||
- [`SyncedHeaderScaffold`](../../lib/widgets/synced_header_scaffold.dart) —
|
||||
the pull-to-sync `CustomScrollView` header shared by 5 of the 6 tabs (see
|
||||
`architecture.md`); also where the pull-to-refresh gesture thresholds and
|
||||
the classic Material refresh spinner live. Its persistent chip/panel
|
||||
(icon + "Sync off"/"Syncing…"/"Synced"/"Sync issue") reflects device-sync
|
||||
status (`ServerProvider.syncHeaderStatus`), not the WebDAV-refresh
|
||||
status (`SyncStatusController.syncHeaderStatus`), not the WebDAV-refresh
|
||||
loading state the pull gesture itself triggers - that has its own,
|
||||
separate floating spinner bubble, so nothing was lost by handing the
|
||||
persistent text/icon over.
|
||||
|
||||
Reference in New Issue
Block a user