Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
faaec5365f | ||
|
|
722b66f7b1 | ||
|
|
dd0c27035a | ||
|
|
b1400e399f | ||
|
|
44a23c3632 |
@@ -54,10 +54,10 @@ There is exactly one `ChangeNotifier`: [`ServerProvider`](../../lib/providers/se
|
|||||||
- UI settings that persist across launches — split into **global** (theme
|
- UI settings that persist across launches — split into **global** (theme
|
||||||
mode, seed color, dynamic-color toggle, bottom-bar opacity/blur,
|
mode, seed color, dynamic-color toggle, bottom-bar opacity/blur,
|
||||||
tap-tab-to-scroll-top, seek bar style, tab order/visibility/default, swipe
|
tap-tab-to-scroll-top, seek bar style, tab order/visibility/default, swipe
|
||||||
actions, login lock — see below) and **per-account** (grid/list view,
|
actions, login lock, sync-on-cellular — see below) and **per-account**
|
||||||
favorites-only, show-hidden, storage scope, Photos sort, Files'
|
(grid/list view, favorites-only, show-hidden, storage scope, Photos sort,
|
||||||
per-folder sort map, cache policy) — see `server.md` for exactly which is
|
Files' per-folder sort map, cache policy, synced folders) — see
|
||||||
which and why
|
`server.md` for exactly which is which and why
|
||||||
- **Login lock** (`loginLockEnabled`/`lockAccountSwitching`/
|
- **Login lock** (`loginLockEnabled`/`lockAccountSwitching`/
|
||||||
`lockHiddenFiles`/`needsUnlock`): an app-wide PIN/biometric gate via
|
`lockHiddenFiles`/`needsUnlock`): an app-wide PIN/biometric gate via
|
||||||
`AppLockService` (a thin wrapper over `local_auth` — this app never
|
`AppLockService` (a thin wrapper over `local_auth` — this app never
|
||||||
@@ -102,10 +102,15 @@ state, no named routes:
|
|||||||
- else `provider.needsUnlock` → `LockScreenView` (login lock — see above)
|
- else `provider.needsUnlock` → `LockScreenView` (login lock — see above)
|
||||||
- else `MainShellView`
|
- else `MainShellView`
|
||||||
|
|
||||||
`MainShellView` is a bottom-nav `IndexedStack` over up to 6 tabs — Files,
|
`MainShellView` is a bottom-nav `IndexedStack` over up to 7 tabs — Files,
|
||||||
Photos, Activity, Trash, Shares, Recent — user-configurable (order,
|
Photos, Favorites, Activity, Trash, Shares, Recent — user-configurable
|
||||||
visibility up to `maxVisibleTabs`, default tab) via `AppTab`/`ServerProvider`
|
(order, visibility up to `maxVisibleTabs`, default tab) via
|
||||||
and rendered through `buildAppTabView` (`widgets/app_tab_view_builder.dart`).
|
`AppTab`/`ServerProvider` and rendered through `buildAppTabView`
|
||||||
|
(`widgets/app_tab_view_builder.dart`). `maxVisibleTabs` (5) is less than the
|
||||||
|
total tab count, and `ServerProvider._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.
|
||||||
Each tab keeps its own `ScrollController` (survives tab switches via
|
Each tab keeps its own `ScrollController` (survives tab switches via
|
||||||
`IndexedStack`'s built-but-hidden trees) and tapping the already-active tab
|
`IndexedStack`'s built-but-hidden trees) and tapping the already-active tab
|
||||||
scrolls it back to top (`tapTabToScrollTop` setting). `MainShellView` also
|
scrolls it back to top (`tapTabToScrollTop` setting). `MainShellView` also
|
||||||
@@ -113,15 +118,78 @@ owns the app's share-intent listener (`ShareIntentService`, backed by
|
|||||||
hand-rolled native handling in `MainActivity.kt` - see `server.md` for why
|
hand-rolled native handling in `MainActivity.kt` - see `server.md` for why
|
||||||
this isn't the `receive_sharing_intent` plugin): both `getInitialShare()`
|
this isn't the `receive_sharing_intent` plugin): both `getInitialShare()`
|
||||||
(cold start via another app's "Share to...") and `onNewShare` (already
|
(cold start via another app's "Share to...") and `onNewShare` (already
|
||||||
running) push `ShareUploadView`.
|
running) push `ShareUploadView`. `FilesView`'s own "+" → "Upload File"
|
||||||
|
(`_pickAndUploadFile`) reaches the exact same `ShareUploadView` screen
|
||||||
|
through the same `SharedFileRef`-based path (wrapping `file_picker`'s
|
||||||
|
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
|
||||||
|
`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
|
||||||
|
only two that make sense as external "choose a file" sources.
|
||||||
|
`MainShellView` also fires a one-time notification-permission prompt on
|
||||||
|
its first mount (`_maybeRequestNotificationPermission`, gated by a plain
|
||||||
|
`shared_preferences` flag so it only ever asks once, not on every
|
||||||
|
launch): a plain-language `AlertDialog` explaining why Noo wants it
|
||||||
|
(upload/download progress notifications - see `ShareUploadService.kt`/
|
||||||
|
`DownloadService.kt`) before the OS's own `permission_handler`-driven
|
||||||
|
`Permission.notification.request()`, since the bare system prompt gives
|
||||||
|
no context on its own.
|
||||||
|
|
||||||
Five of the six tabs (all but Files) plus each tab's own controls share
|
`FloatingBottomNavBar` (`widgets/floating_bottom_bar.dart`) wraps its
|
||||||
|
pill's item row in a horizontal `SingleChildScrollView` rather than a
|
||||||
|
plain `Row`, so a wide selected-item label plus several icon-only tabs
|
||||||
|
scrolls instead of overflowing on narrower screens.
|
||||||
|
|
||||||
|
All six tabs, plus `ShareUploadView` (the share-to-upload destination
|
||||||
|
picker, pushed rather than a tab - see below), share
|
||||||
[`SyncedHeaderScaffold`](../../lib/widgets/synced_header_scaffold.dart) — a
|
[`SyncedHeaderScaffold`](../../lib/widgets/synced_header_scaffold.dart) — a
|
||||||
`CustomScrollView` with a pull-down "sync status" header (Google
|
`CustomScrollView` with a pull-down "sync status" header (Google
|
||||||
Photos-style) and a classic Material refresh spinner shown during a
|
Photos-style) and a classic Material refresh spinner shown during a
|
||||||
pull-triggered sync. `SearchView`, `AccountView` (Settings), the
|
pull-triggered sync. `ShareUploadView` mirrors the Files tab's own
|
||||||
file-details sheet, the share sheet, and `ShareUploadView` (the
|
controls-row/breadcrumbs sticky header almost exactly, so arriving via
|
||||||
share-to-upload destination picker) are pushed on top via
|
another app's "Share to..." sheet still lands on the same top chrome
|
||||||
|
instead of a plain `AppBar` - its `actions` are `[ProfileAvatarButton()]`
|
||||||
|
only (no `MoreTabsButton`: there's nowhere useful for it to go mid-upload,
|
||||||
|
since jumping to another tab would abandon the destination picker);
|
||||||
|
backing out is the system back gesture/button, not a bespoke close icon in
|
||||||
|
the app bar. Its bottom action - "Upload to
|
||||||
|
{folder}" - and the uploading-file-name summary above it (single line,
|
||||||
|
auto-scrolling via `MarqueeTitle` if it doesn't fit) live together in one
|
||||||
|
rounded-top, elevated `Material` bar as `bottomNavigationBar`, reading as a
|
||||||
|
sheet peeking up from the bottom edge rather than a plain flat bar.
|
||||||
|
[`MarqueeTitle`](../../lib/widgets/marquee_title.dart) (`package:marquee`) is
|
||||||
|
shared with `FileViewerScreen`'s title - falls back to a plain ellipsized
|
||||||
|
`Text` when the content already fits, so short text never marquees.
|
||||||
|
|
||||||
|
The Move/Copy destination picker
|
||||||
|
([`MoveCopyDestinationPicker`](../../lib/views/move_copy_destination_picker.dart),
|
||||||
|
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
|
||||||
|
owns its own local navigation state instead, fetching through the
|
||||||
|
stateless `ServerProvider.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
|
||||||
|
no prior browsing session to preserve. The Move/Copy picker is pushed
|
||||||
|
*while the user is actively browsing a specific Files-tab folder*, so
|
||||||
|
reusing the shared state would strand that folder's `pathStack` under it;
|
||||||
|
its local state means popping back always lands the user exactly where
|
||||||
|
they were, untouched.
|
||||||
|
`SearchView`, `AccountView` (Settings), the file-details sheet, and the
|
||||||
|
share sheet are pushed on top via
|
||||||
`Navigator`/`showModalBottomSheet`/`showGradualBottomSheet` rather than
|
`Navigator`/`showModalBottomSheet`/`showGradualBottomSheet` rather than
|
||||||
being tabs. `ProfileAvatarButton` (top-right on every tab) opens Settings on
|
being tabs. `ProfileAvatarButton` (top-right on every tab) opens Settings on
|
||||||
tap and cycles between saved accounts on a vertical swipe.
|
tap and cycles between saved accounts on a vertical swipe.
|
||||||
|
|
||||||
|
Files and Photos (the two tabs with multi-select) pass their selection
|
||||||
|
toolbar into `SyncedHeaderScaffold`'s `selectionBar` param rather than
|
||||||
|
rendering it as a second sliver app bar inside their own content: while
|
||||||
|
non-null, it fully takes over the pinned top bar in place of the
|
||||||
|
sync-status chip/`actions`/pull-to-reveal quota panel, so selecting reads
|
||||||
|
as replacing the whole top chrome rather than adding a strip beneath it.
|
||||||
|
|||||||
+280
-8
@@ -26,6 +26,15 @@ via [`LoginFlowService`](../../lib/services/login_flow_service.dart):
|
|||||||
Chrome-autofill (Android's own system Autofill framework, e.g. a
|
Chrome-autofill (Android's own system Autofill framework, e.g. a
|
||||||
password manager, may still work in the WebView; Chrome's own
|
password manager, may still work in the WebView; Chrome's own
|
||||||
saved-password autofill specifically cannot, since that's Chrome-only).
|
saved-password autofill specifically cannot, since that's Chrome-only).
|
||||||
|
`LoginWebViewView` also clears cookies (`WebViewCookieManager().
|
||||||
|
clearCookies()`) before every load, not just once - Android's WebView
|
||||||
|
`CookieManager` is a single store shared/persisted across every WebView
|
||||||
|
instance in the app process, not scoped per-controller, so without this
|
||||||
|
a second/"Add Account" login silently reuses whichever account's
|
||||||
|
Nextcloud session cookie is already there instead of prompting for
|
||||||
|
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. `ServerProvider` polls `LoginFlowService.poll(pollEndpoint, token)` every
|
||||||
2 seconds (`Timer.periodic`, see `_pollTimer`/`_pollTimeoutTimer` in
|
2 seconds (`Timer.periodic`, see `_pollTimer`/`_pollTimeoutTimer` in
|
||||||
`server_provider.dart`) until it gets a 200 with `server`/`loginName`/
|
`server_provider.dart`) until it gets a 200 with `server`/`loginName`/
|
||||||
@@ -67,18 +76,93 @@ rather than needing a rewrite for multi-account support.
|
|||||||
- **Everything else** (shares, activity, trash, favorites, quota, user info,
|
- **Everything else** (shares, activity, trash, favorites, quota, user info,
|
||||||
file versions) goes through Nextcloud's OCS APIs (`/ocs/v2.php/...`), JSON
|
file versions) goes through Nextcloud's OCS APIs (`/ocs/v2.php/...`), JSON
|
||||||
in, with the `OCS-APIRequest: true` header required on every OCS call.
|
in, with the `OCS-APIRequest: true` header required on every OCS call.
|
||||||
|
*Toggling* a favorite is OCS; *listing* every favorite (`fetchFavorites`,
|
||||||
|
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
|
||||||
|
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).
|
||||||
|
**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,
|
||||||
|
the filter dropped every non-favorited item *including folders*, so a
|
||||||
|
non-favorited folder (containing a favorited item nested inside)
|
||||||
|
vanished from the listing entirely, with no way to navigate into it;
|
||||||
|
fixing that by exempting folders from the filter was itself wrong,
|
||||||
|
because the actual intent was for favorites-only to show every
|
||||||
|
favorited item *account-wide*, not just direct children of whatever
|
||||||
|
folder was open - a strict filter over the wrong scope. Converting it to
|
||||||
|
a real tab, backed by an account-wide fetch, was the actual fix; keep
|
||||||
|
favorites account-wide rather than reintroducing a current-folder-scoped
|
||||||
|
filter.
|
||||||
- Auth header is HTTP Basic (`username:appPassword`, base64), built in
|
- Auth header is HTTP Basic (`username:appPassword`, base64), built in
|
||||||
`_headers`/exposed as `authHeaders` for widgets that need to hit URLs
|
`_headers`/exposed as `authHeaders` for widgets that need to hit URLs
|
||||||
directly (e.g. `Image.network(url, headers: service.authHeaders)` for
|
directly (e.g. `Image.network(url, headers: service.authHeaders)` for
|
||||||
thumbnails/previews).
|
thumbnails/previews).
|
||||||
- Downloads stream through `Dio` (`downloadToFile`) for progress callbacks;
|
- `NextcloudService.downloadToFile` (`Dio`, progress callbacks) is still
|
||||||
small in-app previews (text/PDF) use `fetchBytes` via `package:http`.
|
used for small in-app-only downloads: text/PDF previews (`fetchBytes` via
|
||||||
- **Uploads** (`uploadFileFromPath(folderPath, fileName, localFilePath,
|
`package:http`) and "open externally" (`FileViewerScreen._downloadToTemp`
|
||||||
{onProgress})`) stream the local file via `Dio().put()` with an explicit
|
streams to the app's own cache dir so `open_file` can hand it to another
|
||||||
`Content-Length` and `onSendProgress`, mirroring the download path. The
|
app). Explicitly saving a file **to the device** - the "Download" action
|
||||||
`ServerProvider` wrapper always uploads into `_currentFolderPath` — the
|
in Files/Photos' selection toolbar and the media viewer's download button
|
||||||
share-to-upload flow (`ShareUploadView`) gets a caller-chosen destination
|
- instead hands off to `DownloadService.kt`, an Android foreground
|
||||||
by navigating there first (`navigateToAbsoluteFolder`), then uploading.
|
service, the same way "Share to Noo" hands its upload off to
|
||||||
|
`ShareUploadService.kt` (see that section below) rather than downloading
|
||||||
|
in Dart and prompting `file_saver` per file: a real Service survives the
|
||||||
|
app being closed mid-download, with one cancellable notification for the
|
||||||
|
whole batch. `DownloadService.kt` re-implements a plain WebDAV GET in
|
||||||
|
Kotlin for the same reason `ShareUploadService.kt`'s PUT does - keep
|
||||||
|
`NextcloudService.downloadToFile` in sync manually if download semantics
|
||||||
|
change - and writes straight into the device's public Downloads
|
||||||
|
collection via `MediaStore.Downloads` (API 29+; a background Service
|
||||||
|
can't prompt `file_saver`'s SAF picker the way the Flutter/Activity side
|
||||||
|
can, so this is the direct equivalent) with a legacy
|
||||||
|
`Environment.DIRECTORY_DOWNLOADS` file-write fallback pre-Android-10.
|
||||||
|
Folders are filtered out client-side before handing off (no recursive/
|
||||||
|
zip download support); `DetailsVersionsTab`'s version-restore download
|
||||||
|
and `ShareSheet`'s "Share file directly" (native OS share, not saved to
|
||||||
|
Downloads) keep using `downloadToFile` directly instead, since both need
|
||||||
|
the bytes in-app rather than saved to Downloads.
|
||||||
|
- **Move/Copy** (`moveItem`/`copyItem(itemPath, destFolderPath, {overwrite,
|
||||||
|
newName})`) share one private `_moveOrCopy` helper with `renameItem`
|
||||||
|
(itself just a same-folder MOVE) - WebDAV `MOVE`/`COPY` are the same
|
||||||
|
request shape, just a different verb, and both are recursive by default
|
||||||
|
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`/
|
||||||
|
`copyItems` need to detect without a separate existence-check request
|
||||||
|
per item. `ServerProvider` 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
|
||||||
|
hit; resolving picks overwrite/keep-both (auto-renamed via
|
||||||
|
`_nextAvailableName` against a fresh listing of the destination, fetched
|
||||||
|
once up front, not per item)/skip per item via `resolveConflicts`. The
|
||||||
|
destination-picker screen behind this
|
||||||
|
(`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
|
||||||
|
`UploadService`/`ShareUploadService.kt`).
|
||||||
- **Receiving a shared file from another app**: hand-rolled in
|
- **Receiving a shared file from another app**: hand-rolled in
|
||||||
`MainActivity.kt` (Android `ACTION_SEND`/`ACTION_SEND_MULTIPLE`,
|
`MainActivity.kt` (Android `ACTION_SEND`/`ACTION_SEND_MULTIPLE`,
|
||||||
`android:launchMode` `singleTask` in the manifest so a second share while
|
`android:launchMode` `singleTask` in the manifest so a second share while
|
||||||
@@ -119,6 +203,194 @@ rather than needing a rewrite for multi-account support.
|
|||||||
`AtomicBoolean` the copy/upload loops poll) - there's no plumbing back to
|
`AtomicBoolean` the copy/upload loops poll) - there's no plumbing back to
|
||||||
the Dart UI, by design, since the app may not even be running.
|
the Dart UI, by design, since the app may not even be running.
|
||||||
|
|
||||||
|
## Being picked by other apps (photo/file picker)
|
||||||
|
|
||||||
|
Noo can also be launched *by* another app as a `GET_CONTENT` picker (e.g.
|
||||||
|
Google Drive/Instagram's "choose a file" flow), the reverse direction of
|
||||||
|
"Share to Noo" above - hand-rolled the same way, not a plugin.
|
||||||
|
|
||||||
|
- `MainActivity.kt` matches `ACTION_GET_CONTENT` (`OPENABLE`, any
|
||||||
|
mimeType - a single `*/*` filter, since Android matches it against
|
||||||
|
whatever the caller actually requested) alongside its existing
|
||||||
|
`ACTION_SEND`/`SEND_MULTIPLE` filters, and exposes the caller's requested
|
||||||
|
mimeType/multi-select flag/app label via the
|
||||||
|
`dev.ayushya.noo/pick_intent` method+event channel pair
|
||||||
|
([`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
|
||||||
|
`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`) -
|
||||||
|
`FilesView`/`PhotosView` route taps through
|
||||||
|
`itemMatchesPickFilter`/`confirmPick` instead of their normal
|
||||||
|
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
|
||||||
|
`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
|
||||||
|
prefixing it with the id to dodge collisions between same-named items;
|
||||||
|
the caller reads that on-disk name back as the display name, so
|
||||||
|
prefixing it there was a real bug (Drive showing e.g. `163332_photo.jpg`
|
||||||
|
instead of `photo.jpg`) - then hands the local paths to
|
||||||
|
`PickIntentService.finishPick`, which calls back into
|
||||||
|
`MainActivity.kt.finishPick`: it wraps each file in a `content://` Uri
|
||||||
|
via this app's own `FileProvider` (`${applicationId}.picker.fileprovider`,
|
||||||
|
scoped to just that cache subfolder - see `android/app/src/main/res/xml/
|
||||||
|
file_paths.xml`) and returns it to the caller via `setResult`. Single
|
||||||
|
file uses `setDataAndType` (never `.data =`/`.type =` as two separate
|
||||||
|
calls - each one silently nulls out the other field on a plain
|
||||||
|
`Intent`); multiple files use `ClipData`. `cancelPick` mirrors this for
|
||||||
|
backing out (system back while picking, or a picked-item mismatch) with
|
||||||
|
`RESULT_CANCELED` instead.
|
||||||
|
|
||||||
|
## Device sync
|
||||||
|
|
||||||
|
Mirrors selected folders to app-private local storage
|
||||||
|
(`getExternalFilesDir(null)/sync/<accountId>/...` - wiped on uninstall, no
|
||||||
|
extra storage permission needed) and keeps them updated in the background,
|
||||||
|
even with the app fully closed. Same rationale as the upload/download
|
||||||
|
services for going native instead of a Dart background-task plugin (see
|
||||||
|
above): a periodic job has to run without the Flutter engine loaded, and a
|
||||||
|
notification action has to resolve without launching the UI. Rather than
|
||||||
|
add `workmanager` (whose Dart `callbackDispatcher` spins up a second,
|
||||||
|
minimal Flutter engine that has to re-register every plugin it touches),
|
||||||
|
the whole engine is plain Kotlin using Android's WorkManager directly.
|
||||||
|
|
||||||
|
- [`SyncEngine.kt`](../../android/app/src/main/kotlin/dev/ayushya/noo/SyncEngine.kt)
|
||||||
|
holds the shared primitives, reused by both workers below: a Depth-1 (or
|
||||||
|
Depth-0, for refreshing one item) PROPFIND (`propfindChildren`/
|
||||||
|
`propfindSelf`) requesting `d:getetag` alongside the usual props - unlike
|
||||||
|
every PROPFIND in `nextcloud_service.dart`, which never requests it
|
||||||
|
(`etag` is a dead field on `NextcloudItem` today); plain
|
||||||
|
`HttpURLConnection` GET/PUT (`downloadFile`/`uploadFile`, same style as
|
||||||
|
`DownloadService.kt`/`ShareUploadService.kt`); and `diffFolder`, which
|
||||||
|
compares one folder's freshly-walked manifest against the persisted
|
||||||
|
per-account sync-state map (native `SharedPreferences`, JSON keyed by
|
||||||
|
`oc:fileid` - stable across renames/moves, unlike `path`) to decide, per
|
||||||
|
file: download (new, or server `etag` changed), upload (local file's
|
||||||
|
mtime/size changed and the server didn't), delete locally (missing
|
||||||
|
server-side, unchanged locally), respect a local deletion (file's gone
|
||||||
|
and the server didn't change either - don't recreate it), or flag a
|
||||||
|
**conflict** (both changed since the last recorded state).
|
||||||
|
- [`SyncWorker.kt`](../../android/app/src/main/kotlin/dev/ayushya/noo/SyncWorker.kt)
|
||||||
|
(`CoroutineWorker`) is both the periodic job and the one-off "Sync now":
|
||||||
|
for each configured path, `propfindSelf`s it first to check whether it's
|
||||||
|
a file or a folder - a folder gets the full recursive
|
||||||
|
`walkRemoteTree`, a file is diffed directly as a one-item list (nothing
|
||||||
|
else about `diffFolder`/download/upload/delete cares whether its entries
|
||||||
|
came from a walk or a single lookup, so single-file sync needed no engine
|
||||||
|
changes, just this one branch) - applies `diffFolder`'s decisions, then
|
||||||
|
posts a summary notification (files updated/uploaded/removed) and, for
|
||||||
|
any conflicts, one notification per file with two actions.
|
||||||
|
- **Live status reaches Dart via a push channel, not polling** -
|
||||||
|
[`SyncStatusBus.kt`](../../android/app/src/main/kotlin/dev/ayushya/noo/SyncStatusBus.kt)
|
||||||
|
is a plain in-process pub/sub (no IPC needed - the workers and
|
||||||
|
`MainActivity` share one process) that `SyncWorker`/`ConflictResolveWorker`
|
||||||
|
publish into (syncing started/stopped, which `fileId`s are mid-transfer
|
||||||
|
right now, new/resolved conflicts) and `MainActivity.kt`'s
|
||||||
|
`dev.ayushya.noo/sync_service/status` `EventChannel` forwards to Dart,
|
||||||
|
same pattern as the share/pick-intent channels. It deliberately does
|
||||||
|
*not* track "which files are already synced" itself - that's read fresh
|
||||||
|
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`
|
||||||
|
(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
|
||||||
|
- drives the small corner badge on Files' tiles, `SyncStatusBadge`) are
|
||||||
|
both computed from this state, not fetched per-item.
|
||||||
|
- **In-app conflict resolution reuses the exact same enqueue path as the
|
||||||
|
notification actions** - `ConflictResolveWorker.enqueue(...)` is a
|
||||||
|
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.
|
||||||
|
- **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
|
||||||
|
service-targeted) to
|
||||||
|
[`SyncConflictReceiver`](../../android/app/src/main/kotlin/dev/ayushya/noo/SyncConflictReceiver.kt)
|
||||||
|
- a manifest-registered `BroadcastReceiver` (works even with the app
|
||||||
|
process dead) that can't itself block on network, so it just dismisses
|
||||||
|
the notification and enqueues a one-shot
|
||||||
|
[`ConflictResolveWorker`](../../android/app/src/main/kotlin/dev/ayushya/noo/ConflictResolveWorker.kt)
|
||||||
|
to actually push the local copy up or pull the server copy down and
|
||||||
|
refresh that file's recorded state.
|
||||||
|
- `MainActivity.kt`'s `dev.ayushya.noo/sync_service` channel
|
||||||
|
(`reschedule`/`cancel`/`syncNow`) is the only bridge from Dart: a periodic
|
||||||
|
`WorkRequest`'s input `Data` and `Constraints` are fixed at enqueue time,
|
||||||
|
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
|
||||||
|
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
|
||||||
|
(JSON-encoded string list, in `AccountStore.perAccountPrefKeys`); so does
|
||||||
|
`syncEverything` (`ui_sync_everything`, per account) - when on,
|
||||||
|
`SyncService` sends `['/']` as the path list instead of `syncedPaths`,
|
||||||
|
mirroring the whole account rather than requiring per-item opt-in.
|
||||||
|
`syncOnCellular` is a plain global pref. All three are managed from
|
||||||
|
Settings → Device Sync (a "Sync everything" switch, the path list with
|
||||||
|
remove buttons - hidden while "Sync everything" is on - the cellular
|
||||||
|
toggle, and a manual "Sync now"); individual files or folders are
|
||||||
|
additionally toggled from Files' selection toolbar ("Sync to device",
|
||||||
|
single-selection, either item type).
|
||||||
|
- **`android/app/proguard-rules.pro` exists specifically for this feature,
|
||||||
|
and keeps `androidx.work.**` wholesale rather than naming individual
|
||||||
|
classes.** Flutter's own Gradle plugin auto-enables R8 minification for
|
||||||
|
release builds (`FlutterPlugin.kt` sets `isMinifyEnabled = true`
|
||||||
|
unconditionally for the `release` build type, and auto-wires this exact
|
||||||
|
file if it exists - nothing in this project's own `build.gradle.kts`
|
||||||
|
opts into it), which broke device sync on real-device testing **twice**
|
||||||
|
in a row: first `WorkDatabase` (WorkManager locates its bundled Room
|
||||||
|
database by reflecting off the abstract database class's own,
|
||||||
|
possibly-renamed, name), then - after narrowly keeping just that class -
|
||||||
|
`OverwritingInputMerger` (WorkManager's default input merger, also
|
||||||
|
reflection-instantiated) broke the exact same way and silently ate every
|
||||||
|
`enqueueUniqueWork` call, including "Sync now", with zero indication
|
||||||
|
beyond a `WM-InputMerger` `NoSuchMethodException` in logcat - no crash,
|
||||||
|
no Dart-visible error, just a folder that stayed empty. R8's member-level
|
||||||
|
shrinking strips whatever a class's *reflection-only* callers don't
|
||||||
|
reference directly, even when the class itself survives a plain `-keep
|
||||||
|
class` with no wildcard, and WorkManager reflects into more of its own
|
||||||
|
internals than any one test pass is likely to exercise - hence the
|
||||||
|
wholesale keep instead of chasing individual classes one crash at a
|
||||||
|
time. If adding another native background component reached only via
|
||||||
|
reflection (not a manifest-declared component, which AGP already keeps
|
||||||
|
automatically), don't assume default AndroidX consumer rules cover it -
|
||||||
|
verify on an actual release build, not just `flutter analyze`/a debug
|
||||||
|
build, since minification only applies to release.
|
||||||
|
- **Files land under `Android/data/<package>/files/sync/...`
|
||||||
|
(`getExternalFilesDir`), which no third-party file manager can browse
|
||||||
|
without root** - Android's scoped storage sandboxes that whole directory
|
||||||
|
tree from other apps by design, same as any app-private storage. This
|
||||||
|
surprised real-device testing (a file manager app logged "Can't read
|
||||||
|
directory ... trying su" and came up empty even though the sync had
|
||||||
|
actually worked) - it's expected, not a bug. Confirm synced files
|
||||||
|
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
|
||||||
|
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
|
||||||
|
file directly" and `FilesView._downloadSelected` (only when *every*
|
||||||
|
selected file is already synced - a mixed selection still goes through
|
||||||
|
the normal `DownloadService` batch) both check it first.
|
||||||
|
|
||||||
## Multi-account storage & session persistence
|
## Multi-account storage & session persistence
|
||||||
|
|
||||||
[`AccountStore`](../../lib/services/account_store.dart) owns everything
|
[`AccountStore`](../../lib/services/account_store.dart) owns everything
|
||||||
|
|||||||
@@ -84,13 +84,19 @@ adb install -r build/app/outputs/flutter-apk/app-release.apk
|
|||||||
```
|
```
|
||||||
|
|
||||||
This only preserves data if the new APK's signature matches what's already
|
This only preserves data if the new APK's signature matches what's already
|
||||||
on the device — a local build's release variant currently reuses the debug
|
on the device. `android/app/build.gradle.kts` picks a release signing key
|
||||||
signing config (`android/app/build.gradle.kts`), so consecutive local
|
in this order: a local `android/key.properties` (gitignored — points at a
|
||||||
builds share a key and `adb install -r` works cleanly. Installing a build
|
gitignored keystore file, e.g. `android/app/release-keystore.jks`), then
|
||||||
signed with a different key (e.g. a CI-signed release APK from the Gitea
|
CI env vars (`RELEASE_KEYSTORE_PATH`/`_PASSWORD`, `RELEASE_KEY_ALIAS`/
|
||||||
release pipeline) over a differently-signed local build forces Android to
|
`_PASSWORD`, set by `.gitea/workflows/build.yml` from repo secrets), then
|
||||||
require a full uninstall regardless of the install method used — there's no
|
falls back to the debug key if neither is configured. As long as the same
|
||||||
way around that from the tooling side.
|
dedicated release keystore backs both `key.properties` locally and the
|
||||||
|
Gitea secrets, local release builds and CI-built release APKs share one
|
||||||
|
signature, so `adb install -r` works cleanly either way. A local checkout
|
||||||
|
with no `key.properties` set up falls back to the (per-machine, ungitted)
|
||||||
|
debug key, which won't match a CI-signed APK — installing one over the
|
||||||
|
other still forces a full uninstall, since there's no way around Android's
|
||||||
|
signature check from the tooling side.
|
||||||
|
|
||||||
## Dependencies
|
## Dependencies
|
||||||
|
|
||||||
|
|||||||
@@ -42,6 +42,14 @@ widgets. Key points:
|
|||||||
`files_view.dart` and `share_upload_view.dart`'s destination picker).
|
`files_view.dart` and `share_upload_view.dart`'s destination picker).
|
||||||
Extend this rather than re-deriving per-type icons/colors at a new call
|
Extend this rather than re-deriving per-type icons/colors at a new call
|
||||||
site.
|
site.
|
||||||
|
- [`DetailsHeader`](../../lib/widgets/details/details_sheet.dart) — the
|
||||||
|
icon-box/name/meta row every per-item bottom sheet opens on
|
||||||
|
(`DetailsSheet`, the media viewer's collapsed peek state, and
|
||||||
|
`ShareSheet`). Takes a `padding` override for callers whose own scroll
|
||||||
|
view already applies horizontal insets (`ShareSheet`'s `ListView`), so it
|
||||||
|
doesn't get doubled up. Reuse this instead of a bare title `Text` for any
|
||||||
|
new per-item sheet - a plain title reads as under-designed next to the
|
||||||
|
other sheets (a real instance: `ShareSheet` used to be just that).
|
||||||
- [`FrostedGlassContainer`](../../lib/widgets/frosted_glass_container.dart) —
|
- [`FrostedGlassContainer`](../../lib/widgets/frosted_glass_container.dart) —
|
||||||
the blurred/translucent pill background shared by all floating chrome
|
the blurred/translucent pill background shared by all floating chrome
|
||||||
(bottom nav bar, media-viewer top/bottom bars and video transport
|
(bottom nav bar, media-viewer top/bottom bars and video transport
|
||||||
@@ -55,7 +63,17 @@ widgets. Key points:
|
|||||||
- [`SyncedHeaderScaffold`](../../lib/widgets/synced_header_scaffold.dart) —
|
- [`SyncedHeaderScaffold`](../../lib/widgets/synced_header_scaffold.dart) —
|
||||||
the pull-to-sync `CustomScrollView` header shared by 5 of the 6 tabs (see
|
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
|
`architecture.md`); also where the pull-to-refresh gesture thresholds and
|
||||||
the classic Material refresh spinner live.
|
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
|
||||||
|
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.
|
||||||
|
- [`SyncStatusBadge`](../../lib/widgets/sync_status_badge.dart) — the small
|
||||||
|
corner badge over a thumbnail showing per-item device-sync status
|
||||||
|
(`cloud_done`/`sync`, nothing for not-synced/conflict); used in Files'
|
||||||
|
list and grid tiles today. Reuse this rather than a new ad hoc badge if
|
||||||
|
another view starts showing sync status per item.
|
||||||
- [`SeekBarPainter`/`SeekBarPreview`](../../lib/widgets/seek_bar_painter.dart)
|
- [`SeekBarPainter`/`SeekBarPreview`](../../lib/widgets/seek_bar_painter.dart)
|
||||||
— the four `MediaProgressBarStyle` presets (Default/Wavy/Slim/Squiggly)
|
— the four `MediaProgressBarStyle` presets (Default/Wavy/Slim/Squiggly)
|
||||||
for the video player's seek bar, plus a perpetually-animated
|
for the video player's seek bar, plus a perpetually-animated
|
||||||
|
|||||||
@@ -43,8 +43,22 @@ jobs:
|
|||||||
- name: Analyze
|
- name: Analyze
|
||||||
run: flutter analyze
|
run: flutter analyze
|
||||||
|
|
||||||
|
- name: Decode release keystore
|
||||||
|
# Keeps every release build - regardless of which runner built it -
|
||||||
|
# signed with the same key, so downloaded updates install cleanly
|
||||||
|
# over a previous release instead of failing with "App not
|
||||||
|
# installed" (mismatched signature). See android/app/build.gradle.kts.
|
||||||
|
run: echo "$RELEASE_KEYSTORE_BASE64" | base64 -d > "${{ runner.temp }}/release-keystore.jks"
|
||||||
|
env:
|
||||||
|
RELEASE_KEYSTORE_BASE64: ${{ secrets.RELEASE_KEYSTORE_BASE64 }}
|
||||||
|
|
||||||
- name: Build release APK
|
- name: Build release APK
|
||||||
run: flutter build apk --release
|
run: flutter build apk --release
|
||||||
|
env:
|
||||||
|
RELEASE_KEYSTORE_PATH: ${{ runner.temp }}/release-keystore.jks
|
||||||
|
RELEASE_KEYSTORE_PASSWORD: ${{ secrets.RELEASE_KEYSTORE_PASSWORD }}
|
||||||
|
RELEASE_KEY_ALIAS: ${{ secrets.RELEASE_KEY_ALIAS }}
|
||||||
|
RELEASE_KEY_PASSWORD: ${{ secrets.RELEASE_KEY_PASSWORD }}
|
||||||
|
|
||||||
- name: Rename APK to Noo-<version>.apk
|
- name: Rename APK to Noo-<version>.apk
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ gradle-wrapper.jar
|
|||||||
/gradlew
|
/gradlew
|
||||||
/gradlew.bat
|
/gradlew.bat
|
||||||
/local.properties
|
/local.properties
|
||||||
|
/build/
|
||||||
GeneratedPluginRegistrant.java
|
GeneratedPluginRegistrant.java
|
||||||
.cxx/
|
.cxx/
|
||||||
|
|
||||||
@@ -12,3 +13,4 @@ GeneratedPluginRegistrant.java
|
|||||||
key.properties
|
key.properties
|
||||||
**/*.keystore
|
**/*.keystore
|
||||||
**/*.jks
|
**/*.jks
|
||||||
|
RELEASE_SIGNING_SECRETS.txt
|
||||||
|
|||||||
@@ -1,9 +1,35 @@
|
|||||||
|
import java.util.Properties
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
id("com.android.application")
|
id("com.android.application")
|
||||||
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
|
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
|
||||||
id("dev.flutter.flutter-gradle-plugin")
|
id("dev.flutter.flutter-gradle-plugin")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Release signing: prefer a local android/key.properties (gitignored, for
|
||||||
|
// a developer machine that has the release keystore), then CI env vars
|
||||||
|
// (set by .gitea/workflows/build.yml from repo secrets), then null - which
|
||||||
|
// falls back to debug signing below so an unconfigured checkout still
|
||||||
|
// builds/runs fine, same as before this existed.
|
||||||
|
val releaseKeystoreProperties = Properties().apply {
|
||||||
|
val propsFile = rootProject.file("key.properties")
|
||||||
|
if (propsFile.exists()) propsFile.inputStream().use { load(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun releaseSigningValue(propertyKey: String, envKey: String): String? =
|
||||||
|
releaseKeystoreProperties.getProperty(propertyKey) ?: System.getenv(envKey)
|
||||||
|
|
||||||
|
val releaseStoreFile = releaseSigningValue("storeFile", "RELEASE_KEYSTORE_PATH")
|
||||||
|
val releaseStorePassword = releaseSigningValue("storePassword", "RELEASE_KEYSTORE_PASSWORD")
|
||||||
|
val releaseKeyAlias = releaseSigningValue("keyAlias", "RELEASE_KEY_ALIAS")
|
||||||
|
val releaseKeyPassword = releaseSigningValue("keyPassword", "RELEASE_KEY_PASSWORD")
|
||||||
|
val hasReleaseSigning = listOf(
|
||||||
|
releaseStoreFile,
|
||||||
|
releaseStorePassword,
|
||||||
|
releaseKeyAlias,
|
||||||
|
releaseKeyPassword,
|
||||||
|
).all { !it.isNullOrBlank() }
|
||||||
|
|
||||||
android {
|
android {
|
||||||
namespace = "dev.ayushya.noo"
|
namespace = "dev.ayushya.noo"
|
||||||
compileSdk = flutter.compileSdkVersion
|
compileSdk = flutter.compileSdkVersion
|
||||||
@@ -27,11 +53,27 @@ android {
|
|||||||
versionName = flutter.versionName
|
versionName = flutter.versionName
|
||||||
}
|
}
|
||||||
|
|
||||||
|
signingConfigs {
|
||||||
|
if (hasReleaseSigning) {
|
||||||
|
create("release") {
|
||||||
|
storeFile = file(releaseStoreFile!!)
|
||||||
|
storePassword = releaseStorePassword
|
||||||
|
keyAlias = releaseKeyAlias
|
||||||
|
keyPassword = releaseKeyPassword
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
buildTypes {
|
buildTypes {
|
||||||
release {
|
release {
|
||||||
// TODO: Add your own signing config for the release build.
|
// Falls back to the debug keystore (so an unconfigured
|
||||||
// Signing with the debug keys for now, so `flutter run --release` works.
|
// checkout can still `flutter run --release`) when no release
|
||||||
signingConfig = signingConfigs.getByName("debug")
|
// signing config is available - see the comment above.
|
||||||
|
signingConfig = if (hasReleaseSigning) {
|
||||||
|
signingConfigs.getByName("release")
|
||||||
|
} else {
|
||||||
|
signingConfigs.getByName("debug")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -42,6 +84,18 @@ kotlin {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
// Device sync's periodic/one-off background jobs (SyncWorker,
|
||||||
|
// ConflictResolveWorker) - see their doc comments for why this is
|
||||||
|
// plain WorkManager rather than a Dart-side background-task plugin.
|
||||||
|
implementation("androidx.work:work-runtime-ktx:2.9.1")
|
||||||
|
// PROPFIND (WebDAV directory listing) - Android's HttpURLConnection
|
||||||
|
// hard-rejects any method outside {OPTIONS,GET,HEAD,POST,PUT,DELETE,
|
||||||
|
// TRACE,PATCH} (ProtocolException), unlike plain OpenJDK. OkHttp has
|
||||||
|
// no such whitelist. See SyncEngine.kt.
|
||||||
|
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||||||
|
}
|
||||||
|
|
||||||
flutter {
|
flutter {
|
||||||
source = "../.."
|
source = "../.."
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+18
@@ -0,0 +1,18 @@
|
|||||||
|
# Device sync (SyncWorker/ConflictResolveWorker) - WorkManager instantiates
|
||||||
|
# a lot of its own internals via reflection (Workers by class name recorded
|
||||||
|
# at enqueue time, its bundled Room database's *_Impl class off the
|
||||||
|
# abstract database class's own name, its default InputMerger, etc). R8's
|
||||||
|
# member-level shrinking silently breaks any of these - e.g. stripping an
|
||||||
|
# "unused" no-arg constructor - even when the class itself survives a
|
||||||
|
# plain `-keep class` with no wildcard, and narrowly keeping only the
|
||||||
|
# classes hit by one test pass just means the next reflection path (a
|
||||||
|
# different WorkManager-internal class) breaks instead. Two separate
|
||||||
|
# instances of this already bit real testing (WorkDatabase, then
|
||||||
|
# OverwritingInputMerger) before landing on this broad keep - see
|
||||||
|
# android/app/build.gradle.kts (androidx.work dependency) and
|
||||||
|
# .claude/context/server.md's "Device sync" section.
|
||||||
|
-keep class androidx.work.** { *; }
|
||||||
|
-keep class * extends androidx.room.RoomDatabase { *; }
|
||||||
|
-keep class dev.ayushya.noo.SyncWorker { *; }
|
||||||
|
-keep class dev.ayushya.noo.ConflictResolveWorker { *; }
|
||||||
|
-keep class dev.ayushya.noo.SyncConflictReceiver { *; }
|
||||||
@@ -2,12 +2,19 @@
|
|||||||
<uses-permission android:name="android.permission.INTERNET"/>
|
<uses-permission android:name="android.permission.INTERNET"/>
|
||||||
<!-- For local_auth's biometric app-lock (Settings > Security). -->
|
<!-- For local_auth's biometric app-lock (Settings > Security). -->
|
||||||
<uses-permission android:name="android.permission.USE_BIOMETRIC"/>
|
<uses-permission android:name="android.permission.USE_BIOMETRIC"/>
|
||||||
<!-- For ShareUploadService, which keeps a "Share to Noo" upload going
|
<!-- For ShareUploadService/DownloadService, which keep a "Share to Noo"
|
||||||
(and cancellable from its notification) even if the app is fully
|
upload/download going (and cancellable from its notification) even
|
||||||
closed - see the service's own doc comment. -->
|
if the app is fully closed - see each service's own doc comment. -->
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC"/>
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC"/>
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||||
|
<!-- DownloadService's pre-Android-10 fallback only (MediaStore.Downloads
|
||||||
|
needs no runtime permission on API 29+, which is what targetSdk
|
||||||
|
actually enforces) - capped with maxSdkVersion so it's not even
|
||||||
|
requested on newer devices. -->
|
||||||
|
<uses-permission
|
||||||
|
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
|
||||||
|
android:maxSdkVersion="28"/>
|
||||||
<application
|
<application
|
||||||
android:label="Noo"
|
android:label="Noo"
|
||||||
android:name="${applicationName}"
|
android:name="${applicationName}"
|
||||||
@@ -49,11 +56,45 @@
|
|||||||
<category android:name="android.intent.category.DEFAULT"/>
|
<category android:name="android.intent.category.DEFAULT"/>
|
||||||
<data android:mimeType="*/*"/>
|
<data android:mimeType="*/*"/>
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
|
<!-- Lets Noo be picked as a source ("Google Photos", "Files", ...)
|
||||||
|
from another app's own file/photo picker chooser - handled by
|
||||||
|
MainActivity.kt/PickIntentService, not a plugin. A single
|
||||||
|
"*/*" filter matches any mimeType the caller requests
|
||||||
|
(image/*, video/*, or a generic file pick). -->
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.GET_CONTENT"/>
|
||||||
|
<category android:name="android.intent.category.DEFAULT"/>
|
||||||
|
<category android:name="android.intent.category.OPENABLE"/>
|
||||||
|
<data android:mimeType="*/*"/>
|
||||||
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
<service
|
<service
|
||||||
android:name=".ShareUploadService"
|
android:name=".ShareUploadService"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
android:foregroundServiceType="dataSync"/>
|
android:foregroundServiceType="dataSync"/>
|
||||||
|
<service
|
||||||
|
android:name=".DownloadService"
|
||||||
|
android:exported="false"
|
||||||
|
android:foregroundServiceType="dataSync"/>
|
||||||
|
<!-- The "Keep local"/"Use server" actions on a sync-conflict
|
||||||
|
notification (SyncWorker/SyncEngine) - must be a manifest-
|
||||||
|
registered receiver, not a runtime-registered one, since it
|
||||||
|
needs to work even when the app process isn't running. -->
|
||||||
|
<receiver
|
||||||
|
android:name=".SyncConflictReceiver"
|
||||||
|
android:exported="false"/>
|
||||||
|
<!-- Hands back the file(s) a caller picked via the GET_CONTENT filter
|
||||||
|
above - only the app's own cache/picker/ subfolder is exposed,
|
||||||
|
see file_paths.xml. -->
|
||||||
|
<provider
|
||||||
|
android:name="androidx.core.content.FileProvider"
|
||||||
|
android:authorities="${applicationId}.picker.fileprovider"
|
||||||
|
android:exported="false"
|
||||||
|
android:grantUriPermissions="true">
|
||||||
|
<meta-data
|
||||||
|
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||||
|
android:resource="@xml/file_paths"/>
|
||||||
|
</provider>
|
||||||
<!-- Don't delete the meta-data below.
|
<!-- Don't delete the meta-data below.
|
||||||
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
|
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
|
||||||
<meta-data
|
<meta-data
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
package dev.ayushya.noo
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.work.CoroutineWorker
|
||||||
|
import androidx.work.OneTimeWorkRequestBuilder
|
||||||
|
import androidx.work.WorkManager
|
||||||
|
import androidx.work.WorkerParameters
|
||||||
|
import androidx.work.workDataOf
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolves one sync conflict, triggered either by [SyncConflictReceiver]
|
||||||
|
* (a notification action) or directly from Dart (in-app resolution via the
|
||||||
|
* `dev.ayushya.noo/sync_service` MethodChannel's `resolveConflict`, see
|
||||||
|
* `MainActivity.kt`) - "local" pushes the on-device copy up (overwriting
|
||||||
|
* the server), "server" pulls the server copy down (overwriting the local
|
||||||
|
* mirror). Either way, the sync-state entry for this file is refreshed
|
||||||
|
* afterward so the next [SyncWorker] pass doesn't immediately re-flag it.
|
||||||
|
*/
|
||||||
|
class ConflictResolveWorker(appContext: Context, params: WorkerParameters) :
|
||||||
|
CoroutineWorker(appContext, params) {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val KEY_ACCOUNT_ID = "accountId"
|
||||||
|
const val KEY_SERVER_URL = "serverUrl"
|
||||||
|
const val KEY_USERNAME = "username"
|
||||||
|
const val KEY_AUTH_HEADER = "authHeader"
|
||||||
|
const val KEY_FILE_ID = "fileId"
|
||||||
|
const val KEY_REMOTE_PATH = "remotePath"
|
||||||
|
const val KEY_REL_PATH = "relPath"
|
||||||
|
const val KEY_RESOLUTION = "resolution"
|
||||||
|
|
||||||
|
/** The one place a resolution gets enqueued - both callers above share it. */
|
||||||
|
fun enqueue(
|
||||||
|
context: Context,
|
||||||
|
accountId: String?,
|
||||||
|
serverUrl: String?,
|
||||||
|
username: String?,
|
||||||
|
authHeader: String?,
|
||||||
|
fileId: String?,
|
||||||
|
remotePath: String?,
|
||||||
|
relPath: String?,
|
||||||
|
resolution: String?,
|
||||||
|
) {
|
||||||
|
val data = workDataOf(
|
||||||
|
KEY_ACCOUNT_ID to accountId,
|
||||||
|
KEY_SERVER_URL to serverUrl,
|
||||||
|
KEY_USERNAME to username,
|
||||||
|
KEY_AUTH_HEADER to authHeader,
|
||||||
|
KEY_FILE_ID to fileId,
|
||||||
|
KEY_REMOTE_PATH to remotePath,
|
||||||
|
KEY_REL_PATH to relPath,
|
||||||
|
KEY_RESOLUTION to resolution,
|
||||||
|
)
|
||||||
|
val request = OneTimeWorkRequestBuilder<ConflictResolveWorker>()
|
||||||
|
.setInputData(data)
|
||||||
|
.build()
|
||||||
|
WorkManager.getInstance(context).enqueue(request)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
|
||||||
|
val accountId = inputData.getString(KEY_ACCOUNT_ID) ?: return@withContext Result.failure()
|
||||||
|
val serverUrl = inputData.getString(KEY_SERVER_URL) ?: return@withContext Result.failure()
|
||||||
|
val username = inputData.getString(KEY_USERNAME) ?: return@withContext Result.failure()
|
||||||
|
val authHeader = inputData.getString(KEY_AUTH_HEADER) ?: return@withContext Result.failure()
|
||||||
|
val fileId = inputData.getString(KEY_FILE_ID) ?: return@withContext Result.failure()
|
||||||
|
val remotePath = inputData.getString(KEY_REMOTE_PATH) ?: return@withContext Result.failure()
|
||||||
|
val relPath = inputData.getString(KEY_REL_PATH) ?: return@withContext Result.failure()
|
||||||
|
val resolution = inputData.getString(KEY_RESOLUTION) ?: return@withContext Result.failure()
|
||||||
|
|
||||||
|
val syncRoot = SyncEngine.syncRoot(applicationContext, accountId)
|
||||||
|
val localFile = File(syncRoot, relPath)
|
||||||
|
val ok = when (resolution) {
|
||||||
|
"local" -> localFile.exists() &&
|
||||||
|
SyncEngine.uploadFile(serverUrl, username, authHeader, remotePath, localFile)
|
||||||
|
"server" -> SyncEngine.downloadFile(serverUrl, username, authHeader, remotePath, localFile)
|
||||||
|
else -> false
|
||||||
|
}
|
||||||
|
if (!ok) return@withContext Result.retry()
|
||||||
|
|
||||||
|
// Refresh the recorded state from the server's post-resolution
|
||||||
|
// etag, so this file isn't immediately re-flagged as a conflict on
|
||||||
|
// the next sync pass.
|
||||||
|
val fresh = SyncEngine.propfindSelf(serverUrl, username, authHeader, remotePath)
|
||||||
|
val state = SyncEngine.loadState(applicationContext, accountId).toMutableMap()
|
||||||
|
state[fileId] = SyncEngine.FileState(
|
||||||
|
relPath = relPath,
|
||||||
|
etag = fresh?.etag ?: "",
|
||||||
|
lastModified = fresh?.lastModified ?: 0L,
|
||||||
|
size = localFile.length(),
|
||||||
|
localMTime = localFile.lastModified(),
|
||||||
|
)
|
||||||
|
SyncEngine.saveState(applicationContext, accountId, state)
|
||||||
|
SyncStatusBus.removeConflict(accountId, fileId)
|
||||||
|
|
||||||
|
Result.success()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,307 @@
|
|||||||
|
package dev.ayushya.noo
|
||||||
|
|
||||||
|
import android.app.Notification
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.app.Service
|
||||||
|
import android.content.ContentValues
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.pm.ServiceInfo
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Environment
|
||||||
|
import android.os.IBinder
|
||||||
|
import android.provider.MediaStore
|
||||||
|
import androidx.core.app.NotificationCompat
|
||||||
|
import androidx.core.app.ServiceCompat
|
||||||
|
import org.json.JSONArray
|
||||||
|
import java.io.File
|
||||||
|
import java.net.HttpURLConnection
|
||||||
|
import java.net.URL
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Foreground service that downloads one or more files over WebDAV straight
|
||||||
|
* into the device's public Downloads folder, independent of MainActivity/
|
||||||
|
* the Flutter engine being alive - the download counterpart of
|
||||||
|
* ShareUploadService.kt (see its doc comment for the full rationale: only
|
||||||
|
* a real Android Service survives the app being closed mid-transfer, the
|
||||||
|
* same guarantee a real file-manager app's download notification gives
|
||||||
|
* you). Re-implements a plain WebDAV GET here in Kotlin for the same
|
||||||
|
* reason uploads do - keep NextcloudService.downloadToFile in sync if
|
||||||
|
* download semantics change.
|
||||||
|
*
|
||||||
|
* Started via the `dev.ayushya.noo/download_service` MethodChannel
|
||||||
|
* (MainActivity.kt). Shows one persistent, cancellable notification for
|
||||||
|
* the whole batch, same UX as ShareUploadService's.
|
||||||
|
*/
|
||||||
|
class DownloadService : Service() {
|
||||||
|
companion object {
|
||||||
|
const val ACTION_CANCEL = "dev.ayushya.noo.action.CANCEL_DOWNLOAD"
|
||||||
|
const val EXTRA_FILES = "files" // JSON array of {path, name, mimeType, size}
|
||||||
|
const val EXTRA_SERVER_URL = "serverUrl"
|
||||||
|
const val EXTRA_USERNAME = "username"
|
||||||
|
const val EXTRA_AUTH_HEADER = "authHeader"
|
||||||
|
|
||||||
|
private const val CHANNEL_ID = "file_downloads"
|
||||||
|
private const val NOTIFICATION_ID = 4301
|
||||||
|
}
|
||||||
|
|
||||||
|
private val cancelled = AtomicBoolean(false)
|
||||||
|
private var downloadThread: Thread? = null
|
||||||
|
|
||||||
|
private data class DownloadFile(
|
||||||
|
val path: String,
|
||||||
|
val name: String,
|
||||||
|
val mimeType: String?,
|
||||||
|
val size: Long?,
|
||||||
|
)
|
||||||
|
|
||||||
|
override fun onBind(intent: Intent?): IBinder? = null
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
if (intent?.action == ACTION_CANCEL) {
|
||||||
|
cancelled.set(true)
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
val filesJson = intent?.getStringExtra(EXTRA_FILES)
|
||||||
|
val serverUrl = intent?.getStringExtra(EXTRA_SERVER_URL)
|
||||||
|
val username = intent?.getStringExtra(EXTRA_USERNAME)
|
||||||
|
val authHeader = intent?.getStringExtra(EXTRA_AUTH_HEADER)
|
||||||
|
if (filesJson == null || serverUrl == null || username == null || authHeader == null) {
|
||||||
|
stopSelf()
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
createNotificationChannel()
|
||||||
|
ServiceCompat.startForeground(
|
||||||
|
this,
|
||||||
|
NOTIFICATION_ID,
|
||||||
|
buildProgressNotification("Preparing to download…", null, indeterminate = true),
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
|
ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
// A second batch arriving mid-download is dropped rather than
|
||||||
|
// queued - same tradeoff ShareUploadService makes, rare in
|
||||||
|
// practice and not worth a real queue for.
|
||||||
|
if (downloadThread == null) {
|
||||||
|
val files = parseFiles(filesJson)
|
||||||
|
downloadThread = Thread {
|
||||||
|
runDownloads(files, serverUrl, username, authHeader)
|
||||||
|
}.also { it.start() }
|
||||||
|
}
|
||||||
|
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseFiles(json: String): List<DownloadFile> {
|
||||||
|
val arr = JSONArray(json)
|
||||||
|
return (0 until arr.length()).map { i ->
|
||||||
|
val obj = arr.getJSONObject(i)
|
||||||
|
DownloadFile(
|
||||||
|
path = obj.getString("path"),
|
||||||
|
name = obj.getString("name"),
|
||||||
|
mimeType = if (obj.isNull("mimeType")) null else obj.getString("mimeType"),
|
||||||
|
size = if (obj.isNull("size")) null else obj.getLong("size"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun runDownloads(
|
||||||
|
files: List<DownloadFile>,
|
||||||
|
serverUrl: String,
|
||||||
|
username: String,
|
||||||
|
authHeader: String,
|
||||||
|
) {
|
||||||
|
var succeeded = 0
|
||||||
|
var failed = 0
|
||||||
|
val cleanServer = serverUrl.trimEnd('/')
|
||||||
|
|
||||||
|
for ((index, file) in files.withIndex()) {
|
||||||
|
if (cancelled.get()) break
|
||||||
|
val label = if (files.size == 1) file.name else "${file.name} (${index + 1}/${files.size})"
|
||||||
|
try {
|
||||||
|
var cleanPath = file.path.trim()
|
||||||
|
if (!cleanPath.startsWith("/")) cleanPath = "/$cleanPath"
|
||||||
|
val encodedPath = cleanPath.split("/").joinToString("/") { Uri.encode(it) }
|
||||||
|
val url = URL("$cleanServer/remote.php/dav/files/$username$encodedPath")
|
||||||
|
val ok = downloadFile(file, url, authHeader) { received, total ->
|
||||||
|
notify(
|
||||||
|
buildProgressNotification(
|
||||||
|
"Downloading $label…",
|
||||||
|
progressFraction(received, total),
|
||||||
|
indeterminate = total == null,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (ok) succeeded++ else failed++
|
||||||
|
} catch (e: Exception) {
|
||||||
|
failed++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||||
|
val finalText = when {
|
||||||
|
cancelled.get() -> "Download cancelled"
|
||||||
|
failed == 0 && files.size == 1 -> "Downloaded ${files.first().name}"
|
||||||
|
failed == 0 -> "Downloaded $succeeded of ${files.size} files"
|
||||||
|
else -> "Downloaded $succeeded of ${files.size} files - $failed failed"
|
||||||
|
}
|
||||||
|
manager.notify(NOTIFICATION_ID, buildFinalNotification(finalText))
|
||||||
|
|
||||||
|
stopForeground(STOP_FOREGROUND_DETACH)
|
||||||
|
stopSelf()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun progressFraction(received: Long, total: Long?): Float? {
|
||||||
|
if (total == null || total <= 0) return null
|
||||||
|
return (received.toFloat() / total.toFloat()).coerceIn(0f, 1f)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Streams the GET response straight into the public Downloads
|
||||||
|
/// collection via MediaStore (API 29+) - scoped storage means a
|
||||||
|
/// background Service can't prompt a SAF picker the way `file_saver`
|
||||||
|
/// does from the Flutter/Activity side, so this writes directly to the
|
||||||
|
/// Downloads collection instead, same place a browser download lands.
|
||||||
|
/// Pre-Q devices fall back to the legacy public Downloads directory.
|
||||||
|
private fun downloadFile(
|
||||||
|
file: DownloadFile,
|
||||||
|
url: URL,
|
||||||
|
authHeader: String,
|
||||||
|
onProgress: (Long, Long?) -> Unit,
|
||||||
|
): Boolean {
|
||||||
|
val connection = url.openConnection() as HttpURLConnection
|
||||||
|
return try {
|
||||||
|
connection.requestMethod = "GET"
|
||||||
|
connection.setRequestProperty("Authorization", authHeader)
|
||||||
|
connection.setRequestProperty("OCS-APIRequest", "true")
|
||||||
|
connection.connectTimeout = 15000
|
||||||
|
connection.readTimeout = 30000
|
||||||
|
connection.connect()
|
||||||
|
|
||||||
|
if (connection.responseCode !in 200..299) return false
|
||||||
|
|
||||||
|
val total = file.size ?: connection.contentLengthLong.takeIf { it > 0 }
|
||||||
|
val mimeType = file.mimeType ?: "application/octet-stream"
|
||||||
|
val outputUri = createDownloadsEntry(file.name, mimeType) ?: return false
|
||||||
|
|
||||||
|
val stream = contentResolver.openOutputStream(outputUri) ?: return false
|
||||||
|
stream.use { output ->
|
||||||
|
connection.inputStream.use { input ->
|
||||||
|
val buffer = ByteArray(256 * 1024)
|
||||||
|
var received = 0L
|
||||||
|
var lastEmit = 0L
|
||||||
|
while (!cancelled.get()) {
|
||||||
|
val read = input.read(buffer)
|
||||||
|
if (read == -1) break
|
||||||
|
output.write(buffer, 0, read)
|
||||||
|
received += read
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
if (now - lastEmit >= 200) {
|
||||||
|
lastEmit = now
|
||||||
|
onProgress(received, total)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
|
val values = ContentValues().apply { put(MediaStore.Downloads.IS_PENDING, 0) }
|
||||||
|
contentResolver.update(outputUri, values, null, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cancelled.get()) {
|
||||||
|
contentResolver.delete(outputUri, null, null)
|
||||||
|
false
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
false
|
||||||
|
} finally {
|
||||||
|
connection.disconnect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createDownloadsEntry(name: String, mimeType: String): Uri? {
|
||||||
|
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
|
val values = ContentValues().apply {
|
||||||
|
put(MediaStore.Downloads.DISPLAY_NAME, name)
|
||||||
|
put(MediaStore.Downloads.MIME_TYPE, mimeType)
|
||||||
|
put(MediaStore.Downloads.IS_PENDING, 1)
|
||||||
|
}
|
||||||
|
contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
|
||||||
|
} else {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
val downloadsDir =
|
||||||
|
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
|
||||||
|
if (!downloadsDir.exists()) downloadsDir.mkdirs()
|
||||||
|
Uri.fromFile(File(downloadsDir, name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun notify(notification: Notification) {
|
||||||
|
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||||
|
manager.notify(NOTIFICATION_ID, notification)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createNotificationChannel() {
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
val channel = NotificationChannel(
|
||||||
|
CHANNEL_ID,
|
||||||
|
"File downloads",
|
||||||
|
NotificationManager.IMPORTANCE_LOW,
|
||||||
|
).apply { description = "Progress for files downloaded from Noo" }
|
||||||
|
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||||
|
manager.createNotificationChannel(channel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildProgressNotification(
|
||||||
|
text: String,
|
||||||
|
progress: Float?,
|
||||||
|
indeterminate: Boolean,
|
||||||
|
): Notification {
|
||||||
|
val cancelIntent = Intent(this, DownloadService::class.java).apply { action = ACTION_CANCEL }
|
||||||
|
val cancelPendingIntent = PendingIntent.getService(
|
||||||
|
this,
|
||||||
|
0,
|
||||||
|
cancelIntent,
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
|
)
|
||||||
|
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
|
||||||
|
.setSmallIcon(android.R.drawable.stat_sys_download)
|
||||||
|
.setContentTitle("Downloading from Noo")
|
||||||
|
.setContentText(text)
|
||||||
|
.setOnlyAlertOnce(true)
|
||||||
|
.setOngoing(true)
|
||||||
|
.addAction(android.R.drawable.ic_menu_close_clear_cancel, "Cancel", cancelPendingIntent)
|
||||||
|
when {
|
||||||
|
indeterminate -> builder.setProgress(100, 0, true)
|
||||||
|
progress != null -> builder.setProgress(100, (progress * 100).toInt(), false)
|
||||||
|
}
|
||||||
|
return builder.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildFinalNotification(text: String): Notification {
|
||||||
|
return NotificationCompat.Builder(this, CHANNEL_ID)
|
||||||
|
.setSmallIcon(android.R.drawable.stat_sys_download_done)
|
||||||
|
.setContentTitle("Noo")
|
||||||
|
.setContentText(text)
|
||||||
|
.setOngoing(false)
|
||||||
|
.setAutoCancel(true)
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
cancelled.set(true)
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package dev.ayushya.noo
|
package dev.ayushya.noo
|
||||||
|
|
||||||
import android.Manifest
|
import android.Manifest
|
||||||
|
import android.content.ClipData
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
@@ -10,11 +11,23 @@ import android.os.Looper
|
|||||||
import android.provider.OpenableColumns
|
import android.provider.OpenableColumns
|
||||||
import androidx.core.app.ActivityCompat
|
import androidx.core.app.ActivityCompat
|
||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
|
import androidx.core.content.FileProvider
|
||||||
|
import androidx.work.Constraints
|
||||||
|
import androidx.work.ExistingPeriodicWorkPolicy
|
||||||
|
import androidx.work.ExistingWorkPolicy
|
||||||
|
import androidx.work.NetworkType
|
||||||
|
import androidx.work.OneTimeWorkRequestBuilder
|
||||||
|
import androidx.work.PeriodicWorkRequestBuilder
|
||||||
|
import androidx.work.WorkManager
|
||||||
|
import androidx.work.workDataOf
|
||||||
import io.flutter.embedding.android.FlutterFragmentActivity
|
import io.flutter.embedding.android.FlutterFragmentActivity
|
||||||
import io.flutter.embedding.engine.FlutterEngine
|
import io.flutter.embedding.engine.FlutterEngine
|
||||||
import io.flutter.plugin.common.EventChannel
|
import io.flutter.plugin.common.EventChannel
|
||||||
import io.flutter.plugin.common.MethodCall
|
import io.flutter.plugin.common.MethodCall
|
||||||
import io.flutter.plugin.common.MethodChannel
|
import io.flutter.plugin.common.MethodChannel
|
||||||
|
import org.json.JSONArray
|
||||||
|
import java.io.File
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
// FlutterFragmentActivity (not the default FlutterActivity) is required by
|
// FlutterFragmentActivity (not the default FlutterActivity) is required by
|
||||||
// local_auth's Android implementation, which hosts its biometric/device
|
// local_auth's Android implementation, which hosts its biometric/device
|
||||||
@@ -38,10 +51,21 @@ class MainActivity : FlutterFragmentActivity() {
|
|||||||
private val shareIntentChannelName = "dev.ayushya.noo/share_intent"
|
private val shareIntentChannelName = "dev.ayushya.noo/share_intent"
|
||||||
private val newShareChannelName = "dev.ayushya.noo/share_intent/new"
|
private val newShareChannelName = "dev.ayushya.noo/share_intent/new"
|
||||||
private val uploadServiceChannelName = "dev.ayushya.noo/upload_service"
|
private val uploadServiceChannelName = "dev.ayushya.noo/upload_service"
|
||||||
|
private val downloadServiceChannelName = "dev.ayushya.noo/download_service"
|
||||||
|
private val pickIntentChannelName = "dev.ayushya.noo/pick_intent"
|
||||||
|
private val newPickChannelName = "dev.ayushya.noo/pick_intent/new"
|
||||||
|
private val syncServiceChannelName = "dev.ayushya.noo/sync_service"
|
||||||
|
private val syncStatusChannelName = "dev.ayushya.noo/sync_service/status"
|
||||||
private val notificationPermissionRequestCode = 4202
|
private val notificationPermissionRequestCode = 4202
|
||||||
|
// Lazy, not a field initializer - `packageName` reads through the
|
||||||
|
// Activity's base Context, which isn't attached yet while this class's
|
||||||
|
// fields are being constructed (crashes with an NPE if evaluated then).
|
||||||
|
private val pickerFileProviderAuthority by lazy { "$packageName.picker.fileprovider" }
|
||||||
|
|
||||||
private val mainHandler = Handler(Looper.getMainLooper())
|
private val mainHandler = Handler(Looper.getMainLooper())
|
||||||
private var newShareSink: EventChannel.EventSink? = null
|
private var newShareSink: EventChannel.EventSink? = null
|
||||||
|
private var newPickSink: EventChannel.EventSink? = null
|
||||||
|
private var syncStatusListener: ((SyncStatusBus.Status) -> Unit)? = null
|
||||||
|
|
||||||
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||||
super.configureFlutterEngine(flutterEngine)
|
super.configureFlutterEngine(flutterEngine)
|
||||||
@@ -73,6 +97,104 @@ class MainActivity : FlutterFragmentActivity() {
|
|||||||
else -> result.notImplemented()
|
else -> result.notImplemented()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, downloadServiceChannelName)
|
||||||
|
.setMethodCallHandler { call, result ->
|
||||||
|
when (call.method) {
|
||||||
|
"startDownload" -> {
|
||||||
|
startDownloadService(call, result)
|
||||||
|
}
|
||||||
|
else -> result.notImplemented()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, pickIntentChannelName)
|
||||||
|
.setMethodCallHandler { call, result ->
|
||||||
|
when (call.method) {
|
||||||
|
"getPickRequest" -> result.success(extractPickRequest(intent))
|
||||||
|
"finishPick" -> finishPick(call, result)
|
||||||
|
"cancelPick" -> cancelPick(result)
|
||||||
|
else -> result.notImplemented()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
EventChannel(flutterEngine.dartExecutor.binaryMessenger, newPickChannelName)
|
||||||
|
.setStreamHandler(object : EventChannel.StreamHandler {
|
||||||
|
override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
|
||||||
|
newPickSink = events
|
||||||
|
}
|
||||||
|
override fun onCancel(arguments: Any?) {
|
||||||
|
newPickSink = null
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, syncServiceChannelName)
|
||||||
|
.setMethodCallHandler { call, result ->
|
||||||
|
when (call.method) {
|
||||||
|
"reschedule" -> rescheduleSyncWork(call, result)
|
||||||
|
"cancel" -> cancelSyncWork(result)
|
||||||
|
"syncNow" -> syncNow(call, result)
|
||||||
|
"getSyncStatus" -> result.success(syncStatusMap(SyncStatusBus.snapshot()))
|
||||||
|
"resolveConflict" -> resolveConflict(call, result)
|
||||||
|
else -> result.notImplemented()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
EventChannel(flutterEngine.dartExecutor.binaryMessenger, syncStatusChannelName)
|
||||||
|
.setStreamHandler(object : EventChannel.StreamHandler {
|
||||||
|
override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
|
||||||
|
val listener: (SyncStatusBus.Status) -> Unit = { status ->
|
||||||
|
mainHandler.post { events.success(syncStatusMap(status)) }
|
||||||
|
}
|
||||||
|
syncStatusListener = listener
|
||||||
|
SyncStatusBus.subscribe(listener)
|
||||||
|
}
|
||||||
|
override fun onCancel(arguments: Any?) {
|
||||||
|
syncStatusListener?.let { SyncStatusBus.unsubscribe(it) }
|
||||||
|
syncStatusListener = null
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun syncStatusMap(status: SyncStatusBus.Status): Map<String, Any?> {
|
||||||
|
val syncedFileIds = status.accountId?.let {
|
||||||
|
SyncEngine.loadState(applicationContext, it).keys.toList()
|
||||||
|
} ?: emptyList()
|
||||||
|
return mapOf(
|
||||||
|
"accountId" to status.accountId,
|
||||||
|
"syncing" to status.syncing,
|
||||||
|
"syncingFileIds" to status.syncingFileIds.toList(),
|
||||||
|
"syncedFileIds" to syncedFileIds,
|
||||||
|
"conflicts" to status.conflicts.map {
|
||||||
|
mapOf(
|
||||||
|
"accountId" to it.accountId,
|
||||||
|
"fileId" to it.fileId,
|
||||||
|
"remotePath" to it.remotePath,
|
||||||
|
"relPath" to it.relPath,
|
||||||
|
"name" to it.name,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// In-app conflict resolution (the header's "Keep local"/"Use server"
|
||||||
|
/// buttons) - shares [ConflictResolveWorker.enqueue] with
|
||||||
|
/// [SyncConflictReceiver], the only other caller, so there's one
|
||||||
|
/// resolution code path regardless of whether it's triggered from a
|
||||||
|
/// notification or from inside the app.
|
||||||
|
private fun resolveConflict(call: MethodCall, result: MethodChannel.Result) {
|
||||||
|
ConflictResolveWorker.enqueue(
|
||||||
|
this,
|
||||||
|
accountId = call.argument<String>("accountId"),
|
||||||
|
serverUrl = call.argument<String>("serverUrl"),
|
||||||
|
username = call.argument<String>("username"),
|
||||||
|
authHeader = call.argument<String>("authHeader"),
|
||||||
|
fileId = call.argument<String>("fileId"),
|
||||||
|
remotePath = call.argument<String>("remotePath"),
|
||||||
|
relPath = call.argument<String>("relPath"),
|
||||||
|
resolution = call.argument<String>("resolution"),
|
||||||
|
)
|
||||||
|
result.success(null)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onNewIntent(intent: Intent) {
|
override fun onNewIntent(intent: Intent) {
|
||||||
@@ -82,6 +204,10 @@ class MainActivity : FlutterFragmentActivity() {
|
|||||||
if (shared.isNotEmpty()) {
|
if (shared.isNotEmpty()) {
|
||||||
mainHandler.post { newShareSink?.success(shared) }
|
mainHandler.post { newShareSink?.success(shared) }
|
||||||
}
|
}
|
||||||
|
val pickRequest = extractPickRequest(intent)
|
||||||
|
if (pickRequest != null) {
|
||||||
|
mainHandler.post { newPickSink?.success(pickRequest) }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Cheap Uri metadata only (display name / size / mime type) via a
|
/// Cheap Uri metadata only (display name / size / mime type) via a
|
||||||
@@ -180,4 +306,188 @@ class MainActivity : FlutterFragmentActivity() {
|
|||||||
ContextCompat.startForegroundService(this, serviceIntent)
|
ContextCompat.startForegroundService(this, serviceIntent)
|
||||||
result.success(null)
|
result.success(null)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Starts DownloadService with everything it needs to run entirely on
|
||||||
|
/// its own (see its doc comment) - same contract shape as
|
||||||
|
/// [startUploadService], kept in sync manually for the same reason.
|
||||||
|
private fun startDownloadService(call: MethodCall, result: MethodChannel.Result) {
|
||||||
|
val filesJson = call.argument<String>("files")
|
||||||
|
val serverUrl = call.argument<String>("serverUrl")
|
||||||
|
val username = call.argument<String>("username")
|
||||||
|
val authHeader = call.argument<String>("authHeader")
|
||||||
|
if (filesJson == null || serverUrl == null || username == null || authHeader == null) {
|
||||||
|
result.error("bad_args", "Missing required download arguments", null)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Build.VERSION.SDK_INT >= 33 &&
|
||||||
|
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) !=
|
||||||
|
PackageManager.PERMISSION_GRANTED
|
||||||
|
) {
|
||||||
|
// Fire-and-forget: the service works fine even if this is denied,
|
||||||
|
// it just won't be able to show progress/cancel in a notification.
|
||||||
|
ActivityCompat.requestPermissions(
|
||||||
|
this,
|
||||||
|
arrayOf(Manifest.permission.POST_NOTIFICATIONS),
|
||||||
|
notificationPermissionRequestCode,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val serviceIntent = Intent(this, DownloadService::class.java).apply {
|
||||||
|
putExtra(DownloadService.EXTRA_FILES, filesJson)
|
||||||
|
putExtra(DownloadService.EXTRA_SERVER_URL, serverUrl)
|
||||||
|
putExtra(DownloadService.EXTRA_USERNAME, username)
|
||||||
|
putExtra(DownloadService.EXTRA_AUTH_HEADER, authHeader)
|
||||||
|
}
|
||||||
|
ContextCompat.startForegroundService(this, serviceIntent)
|
||||||
|
result.success(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shared arg-parsing for `reschedule`/`syncNow` - both need the same
|
||||||
|
/// account/credentials/folder-list shape, just enqueue differently.
|
||||||
|
private fun syncWorkData(call: MethodCall): androidx.work.Data? {
|
||||||
|
val accountId = call.argument<String>("accountId")
|
||||||
|
val serverUrl = call.argument<String>("serverUrl")
|
||||||
|
val username = call.argument<String>("username")
|
||||||
|
val authHeader = call.argument<String>("authHeader")
|
||||||
|
val foldersJson = call.argument<String>("folders")
|
||||||
|
if (accountId == null || serverUrl == null || username == null ||
|
||||||
|
authHeader == null || foldersJson == null
|
||||||
|
) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return workDataOf(
|
||||||
|
SyncWorker.KEY_ACCOUNT_ID to accountId,
|
||||||
|
SyncWorker.KEY_SERVER_URL to serverUrl,
|
||||||
|
SyncWorker.KEY_USERNAME to username,
|
||||||
|
SyncWorker.KEY_AUTH_HEADER to authHeader,
|
||||||
|
SyncWorker.KEY_FOLDERS to foldersJson,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-enqueues (or cancels, if the folder list is now empty) the
|
||||||
|
/// periodic device-sync job - called from Dart whenever the synced-
|
||||||
|
/// folder list, active account, or Wi-Fi-only setting changes, since a
|
||||||
|
/// periodic WorkRequest's input Data/constraints are fixed at enqueue
|
||||||
|
/// time and can only be changed by cancelling and re-enqueueing.
|
||||||
|
private fun rescheduleSyncWork(call: MethodCall, result: MethodChannel.Result) {
|
||||||
|
val data = syncWorkData(call)
|
||||||
|
val foldersJson = call.argument<String>("folders")
|
||||||
|
val wifiOnly = call.argument<Boolean>("wifiOnly") ?: true
|
||||||
|
val workManager = WorkManager.getInstance(this)
|
||||||
|
|
||||||
|
if (data == null || foldersJson == null || JSONArray(foldersJson).length() == 0) {
|
||||||
|
workManager.cancelUniqueWork(SyncWorker.UNIQUE_PERIODIC_NAME)
|
||||||
|
result.success(null)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
val constraints = Constraints.Builder()
|
||||||
|
.setRequiredNetworkType(if (wifiOnly) NetworkType.UNMETERED else NetworkType.CONNECTED)
|
||||||
|
.build()
|
||||||
|
// 1 hour is WorkManager's own practical floor for a "battery-
|
||||||
|
// friendly" cadence well above its hard 15-minute minimum; there's
|
||||||
|
// no per-user interval setting for this in v1.
|
||||||
|
val request = PeriodicWorkRequestBuilder<SyncWorker>(1, TimeUnit.HOURS)
|
||||||
|
.setInputData(data)
|
||||||
|
.setConstraints(constraints)
|
||||||
|
.build()
|
||||||
|
workManager.enqueueUniquePeriodicWork(
|
||||||
|
SyncWorker.UNIQUE_PERIODIC_NAME,
|
||||||
|
ExistingPeriodicWorkPolicy.UPDATE,
|
||||||
|
request,
|
||||||
|
)
|
||||||
|
result.success(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cancelSyncWork(result: MethodChannel.Result) {
|
||||||
|
WorkManager.getInstance(this).cancelUniqueWork(SyncWorker.UNIQUE_PERIODIC_NAME)
|
||||||
|
result.success(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One-off immediate run (Settings' "Sync now"), independent of the
|
||||||
|
/// periodic schedule.
|
||||||
|
private fun syncNow(call: MethodCall, result: MethodChannel.Result) {
|
||||||
|
val data = syncWorkData(call)
|
||||||
|
if (data == null) {
|
||||||
|
result.error("bad_args", "Missing required sync arguments", null)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val request = OneTimeWorkRequestBuilder<SyncWorker>().setInputData(data).build()
|
||||||
|
WorkManager.getInstance(this).enqueueUniqueWork(
|
||||||
|
SyncWorker.UNIQUE_ONE_OFF_NAME,
|
||||||
|
ExistingWorkPolicy.REPLACE,
|
||||||
|
request,
|
||||||
|
)
|
||||||
|
result.success(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Non-null only when this Activity was launched (or re-delivered a new
|
||||||
|
/// Intent) as another app's GET_CONTENT picker - the mimeType filter and
|
||||||
|
/// multi-select flag the caller asked for, plus a best-effort display
|
||||||
|
/// name for the calling app to show in the "picking mode" banner.
|
||||||
|
private fun extractPickRequest(intent: Intent): Map<String, Any?>? {
|
||||||
|
if (intent.action != Intent.ACTION_GET_CONTENT) return null
|
||||||
|
val mimeType = intent.type ?: "*/*"
|
||||||
|
val allowMultiple = intent.getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
|
||||||
|
val callerPackage = callingPackage
|
||||||
|
val callerLabel = callerPackage?.let {
|
||||||
|
try {
|
||||||
|
val appInfo = packageManager.getApplicationInfo(it, 0)
|
||||||
|
packageManager.getApplicationLabel(appInfo).toString()
|
||||||
|
} catch (_: PackageManager.NameNotFoundException) {
|
||||||
|
it
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return mapOf(
|
||||||
|
"mimeType" to mimeType,
|
||||||
|
"allowMultiple" to allowMultiple,
|
||||||
|
"callerLabel" to callerLabel,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hands the already-downloaded local files (see PickIntentService/
|
||||||
|
/// ServerProvider.confirmPick - this Activity never touches the
|
||||||
|
/// Nextcloud server itself) back to the caller as content:// Uris
|
||||||
|
/// through this app's own FileProvider, then closes the picker.
|
||||||
|
private fun finishPick(call: MethodCall, result: MethodChannel.Result) {
|
||||||
|
val paths = call.argument<List<String>>("paths")
|
||||||
|
val mimeTypes = call.argument<List<String>>("mimeTypes") ?: emptyList()
|
||||||
|
if (paths.isNullOrEmpty()) {
|
||||||
|
result.error("no_files", "No files to return to the caller", null)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
val uris = paths.map { path ->
|
||||||
|
FileProvider.getUriForFile(this, pickerFileProviderAuthority, File(path))
|
||||||
|
}
|
||||||
|
val resultIntent = Intent().apply {
|
||||||
|
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||||
|
}
|
||||||
|
// `Intent.setData()` and `.setType()` each silently null out the
|
||||||
|
// other field if called separately (Android framework behavior) -
|
||||||
|
// `setDataAndType` is the only way to have both survive on the same
|
||||||
|
// Intent, which every GET_CONTENT caller expects for `data`.
|
||||||
|
val firstMimeType = mimeTypes.getOrNull(0) ?: "*/*"
|
||||||
|
if (uris.size == 1) {
|
||||||
|
resultIntent.setDataAndType(uris[0], firstMimeType)
|
||||||
|
} else {
|
||||||
|
val clipMimeTypes = mimeTypes.ifEmpty { listOf("*/*") }.toTypedArray()
|
||||||
|
val clipData = ClipData("Noo picked files", clipMimeTypes, ClipData.Item(uris[0]))
|
||||||
|
for (i in 1 until uris.size) clipData.addItem(ClipData.Item(uris[i]))
|
||||||
|
resultIntent.clipData = clipData
|
||||||
|
// Some callers only read `data` even for a multi-item pick, so
|
||||||
|
// this still points at the first file as a fallback.
|
||||||
|
resultIntent.setDataAndType(uris[0], firstMimeType)
|
||||||
|
}
|
||||||
|
setResult(RESULT_OK, resultIntent)
|
||||||
|
result.success(null)
|
||||||
|
finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cancelPick(result: MethodChannel.Result) {
|
||||||
|
setResult(RESULT_CANCELED)
|
||||||
|
result.success(null)
|
||||||
|
finish()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package dev.ayushya.noo
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import androidx.core.app.NotificationManagerCompat
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles the "Keep local" / "Use server" actions on a sync-conflict
|
||||||
|
* notification (see `SyncWorker.notifyConflicts`). A `BroadcastReceiver`
|
||||||
|
* can't block on network itself (~10s execution budget), so this only
|
||||||
|
* dismisses the notification and hands off to a one-shot
|
||||||
|
* [ConflictResolveWorker] for the actual upload/download.
|
||||||
|
*/
|
||||||
|
class SyncConflictReceiver : BroadcastReceiver() {
|
||||||
|
companion object {
|
||||||
|
const val ACTION_RESOLVE = "dev.ayushya.noo.action.RESOLVE_SYNC_CONFLICT"
|
||||||
|
const val EXTRA_ACCOUNT_ID = "accountId"
|
||||||
|
const val EXTRA_SERVER_URL = "serverUrl"
|
||||||
|
const val EXTRA_USERNAME = "username"
|
||||||
|
const val EXTRA_AUTH_HEADER = "authHeader"
|
||||||
|
const val EXTRA_FILE_ID = "fileId"
|
||||||
|
const val EXTRA_REMOTE_PATH = "remotePath"
|
||||||
|
const val EXTRA_REL_PATH = "relPath"
|
||||||
|
const val EXTRA_RESOLUTION = "resolution" // "local" | "server"
|
||||||
|
const val EXTRA_NOTIFICATION_ID = "notificationId"
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onReceive(context: Context, intent: Intent) {
|
||||||
|
if (intent.action != ACTION_RESOLVE) return
|
||||||
|
|
||||||
|
val notificationId = intent.getIntExtra(EXTRA_NOTIFICATION_ID, -1)
|
||||||
|
if (notificationId != -1) {
|
||||||
|
NotificationManagerCompat.from(context).cancel(notificationId)
|
||||||
|
}
|
||||||
|
|
||||||
|
ConflictResolveWorker.enqueue(
|
||||||
|
context,
|
||||||
|
accountId = intent.getStringExtra(EXTRA_ACCOUNT_ID),
|
||||||
|
serverUrl = intent.getStringExtra(EXTRA_SERVER_URL),
|
||||||
|
username = intent.getStringExtra(EXTRA_USERNAME),
|
||||||
|
authHeader = intent.getStringExtra(EXTRA_AUTH_HEADER),
|
||||||
|
fileId = intent.getStringExtra(EXTRA_FILE_ID),
|
||||||
|
remotePath = intent.getStringExtra(EXTRA_REMOTE_PATH),
|
||||||
|
relPath = intent.getStringExtra(EXTRA_REL_PATH),
|
||||||
|
resolution = intent.getStringExtra(EXTRA_RESOLUTION),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,399 @@
|
|||||||
|
package dev.ayushya.noo
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.net.Uri
|
||||||
|
import android.util.Log
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.Request
|
||||||
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
import java.net.HttpURLConnection
|
||||||
|
import java.net.URL
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.Locale
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
import javax.xml.parsers.DocumentBuilderFactory
|
||||||
|
import org.w3c.dom.Element
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The actual WebDAV walk/diff/GET/PUT engine for device sync - shared by
|
||||||
|
* [SyncWorker] (periodic/manual full-folder sync) and
|
||||||
|
* [ConflictResolveWorker] (single-file resolution from a notification
|
||||||
|
* action), since both need the same PROPFIND/GET/PUT primitives and the
|
||||||
|
* same on-disk sync-state bookkeeping.
|
||||||
|
*
|
||||||
|
* Deliberately plain Kotlin over `HttpURLConnection`, not
|
||||||
|
* `NextcloudService`'s Dart/Dio code - this has to run from a
|
||||||
|
* [androidx.work.CoroutineWorker], independent of the Flutter engine even
|
||||||
|
* being loaded, the same reason `DownloadService.kt`/`ShareUploadService.kt`
|
||||||
|
* re-implement GET/PUT natively instead of calling back into Dart.
|
||||||
|
*/
|
||||||
|
object SyncEngine {
|
||||||
|
data class RemoteEntry(
|
||||||
|
val path: String,
|
||||||
|
val fileId: String,
|
||||||
|
val etag: String,
|
||||||
|
val lastModified: Long,
|
||||||
|
val size: Long,
|
||||||
|
val isFolder: Boolean,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class FileState(
|
||||||
|
val relPath: String,
|
||||||
|
val etag: String,
|
||||||
|
val lastModified: Long,
|
||||||
|
val size: Long,
|
||||||
|
val localMTime: Long,
|
||||||
|
)
|
||||||
|
|
||||||
|
sealed class SyncAction {
|
||||||
|
data class Download(val entry: RemoteEntry) : SyncAction()
|
||||||
|
data class Upload(val relPath: String, val fileId: String) : SyncAction()
|
||||||
|
data class Delete(val relPath: String, val fileId: String) : SyncAction()
|
||||||
|
data class Conflict(val entry: RemoteEntry, val relPath: String) : SyncAction()
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val TAG = "NooSync"
|
||||||
|
private const val STATE_PREFS = "noo_sync_state"
|
||||||
|
private val rfc1123 =
|
||||||
|
SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US)
|
||||||
|
|
||||||
|
// Only used for PROPFIND - unlike HttpURLConnection, OkHttp doesn't
|
||||||
|
// reject non-standard HTTP methods.
|
||||||
|
private val httpClient = OkHttpClient.Builder()
|
||||||
|
.connectTimeout(15, TimeUnit.SECONDS)
|
||||||
|
.readTimeout(30, TimeUnit.SECONDS)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
fun syncRoot(context: Context, accountId: String): File {
|
||||||
|
val base = context.getExternalFilesDir(null) ?: context.filesDir
|
||||||
|
return File(base, "sync/$accountId").apply { mkdirs() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stateKey(accountId: String) = "state_$accountId"
|
||||||
|
|
||||||
|
fun loadState(context: Context, accountId: String): MutableMap<String, FileState> {
|
||||||
|
val prefs = context.getSharedPreferences(STATE_PREFS, Context.MODE_PRIVATE)
|
||||||
|
val json = prefs.getString(stateKey(accountId), null) ?: return mutableMapOf()
|
||||||
|
val obj = JSONObject(json)
|
||||||
|
val result = mutableMapOf<String, FileState>()
|
||||||
|
for (fileId in obj.keys()) {
|
||||||
|
val entry = obj.getJSONObject(fileId)
|
||||||
|
result[fileId] = FileState(
|
||||||
|
relPath = entry.getString("relPath"),
|
||||||
|
etag = entry.getString("etag"),
|
||||||
|
lastModified = entry.getLong("lastModified"),
|
||||||
|
size = entry.getLong("size"),
|
||||||
|
localMTime = entry.getLong("localMTime"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
fun saveState(context: Context, accountId: String, state: Map<String, FileState>) {
|
||||||
|
val obj = JSONObject()
|
||||||
|
for ((fileId, s) in state) {
|
||||||
|
obj.put(
|
||||||
|
fileId,
|
||||||
|
JSONObject().apply {
|
||||||
|
put("relPath", s.relPath)
|
||||||
|
put("etag", s.etag)
|
||||||
|
put("lastModified", s.lastModified)
|
||||||
|
put("size", s.size)
|
||||||
|
put("localMTime", s.localMTime)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val prefs = context.getSharedPreferences(STATE_PREFS, Context.MODE_PRIVATE)
|
||||||
|
prefs.edit().putString(stateKey(accountId), obj.toString()).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Depth-1 PROPFIND of [remotePath], returning its direct children only. */
|
||||||
|
fun propfindChildren(
|
||||||
|
serverUrl: String,
|
||||||
|
username: String,
|
||||||
|
authHeader: String,
|
||||||
|
remotePath: String,
|
||||||
|
): List<RemoteEntry> = propfind(serverUrl, username, authHeader, remotePath, depth = "1", skipSelf = true)
|
||||||
|
|
||||||
|
/** Depth-0 PROPFIND of [remotePath] itself (e.g. to refresh its etag after a PUT/GET). */
|
||||||
|
fun propfindSelf(
|
||||||
|
serverUrl: String,
|
||||||
|
username: String,
|
||||||
|
authHeader: String,
|
||||||
|
remotePath: String,
|
||||||
|
): RemoteEntry? = propfind(serverUrl, username, authHeader, remotePath, depth = "0", skipSelf = false).firstOrNull()
|
||||||
|
|
||||||
|
private fun propfind(
|
||||||
|
serverUrl: String,
|
||||||
|
username: String,
|
||||||
|
authHeader: String,
|
||||||
|
remotePath: String,
|
||||||
|
depth: String,
|
||||||
|
skipSelf: Boolean,
|
||||||
|
): List<RemoteEntry> {
|
||||||
|
var cleanPath = remotePath.trim()
|
||||||
|
if (!cleanPath.startsWith("/")) cleanPath = "/$cleanPath"
|
||||||
|
if (depth == "1" && !cleanPath.endsWith("/")) cleanPath = "$cleanPath/"
|
||||||
|
val encodedPath = cleanPath.split("/").joinToString("/") { Uri.encode(it) }
|
||||||
|
val cleanServer = serverUrl.trimEnd('/')
|
||||||
|
val url = "$cleanServer/remote.php/dav/files/$username$encodedPath"
|
||||||
|
|
||||||
|
val body = """<?xml version="1.0" encoding="utf-8" ?>
|
||||||
|
<d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
|
||||||
|
<d:prop>
|
||||||
|
<d:getlastmodified/>
|
||||||
|
<d:getcontentlength/>
|
||||||
|
<d:resourcetype/>
|
||||||
|
<d:getetag/>
|
||||||
|
<oc:fileid/>
|
||||||
|
</d:prop>
|
||||||
|
</d:propfind>"""
|
||||||
|
val request = Request.Builder()
|
||||||
|
.url(url)
|
||||||
|
.method("PROPFIND", body.toRequestBody("application/xml".toMediaType()))
|
||||||
|
.header("Authorization", authHeader)
|
||||||
|
.header("Depth", depth)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
return try {
|
||||||
|
httpClient.newCall(request).execute().use { response ->
|
||||||
|
Log.d(TAG, "PROPFIND $url -> ${response.code}")
|
||||||
|
if (!response.isSuccessful) {
|
||||||
|
Log.w(TAG, "PROPFIND $url failed: ${response.code} ${response.body?.string()}")
|
||||||
|
return emptyList()
|
||||||
|
}
|
||||||
|
|
||||||
|
val doc = DocumentBuilderFactory.newInstance()
|
||||||
|
.apply { isNamespaceAware = true }
|
||||||
|
.newDocumentBuilder()
|
||||||
|
.parse(response.body!!.byteStream())
|
||||||
|
|
||||||
|
parsePropfindResponse(doc, username, cleanPath, skipSelf)
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "PROPFIND $url threw", e)
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parsePropfindResponse(
|
||||||
|
doc: org.w3c.dom.Document,
|
||||||
|
username: String,
|
||||||
|
cleanPath: String,
|
||||||
|
skipSelf: Boolean,
|
||||||
|
): List<RemoteEntry> {
|
||||||
|
val marker = "/remote.php/dav/files/$username"
|
||||||
|
val selfPath = cleanPath.trimEnd('/')
|
||||||
|
val responses = doc.getElementsByTagNameNS("DAV:", "response")
|
||||||
|
val entries = mutableListOf<RemoteEntry>()
|
||||||
|
for (i in 0 until responses.length) {
|
||||||
|
val responseEl = responses.item(i) as? Element ?: continue
|
||||||
|
val hrefRaw = responseEl.getElementsByTagNameNS("DAV:", "href")
|
||||||
|
.item(0)?.textContent ?: continue
|
||||||
|
val decodedHref = Uri.decode(hrefRaw)
|
||||||
|
val idx = decodedHref.indexOf(marker)
|
||||||
|
val hrefPath = if (idx >= 0) decodedHref.substring(idx + marker.length) else decodedHref
|
||||||
|
val hrefPathNorm = (if (hrefPath.isEmpty()) "/" else hrefPath).trimEnd('/')
|
||||||
|
if (skipSelf && hrefPathNorm == selfPath) continue // self entry, not a child
|
||||||
|
|
||||||
|
val propEl = responseEl.getElementsByTagNameNS("DAV:", "prop").item(0) as? Element
|
||||||
|
?: continue
|
||||||
|
val resourceTypeEl =
|
||||||
|
propEl.getElementsByTagNameNS("DAV:", "resourcetype").item(0) as? Element
|
||||||
|
val isFolder =
|
||||||
|
(resourceTypeEl?.getElementsByTagNameNS("DAV:", "collection")?.length ?: 0) > 0
|
||||||
|
val etag = propEl.getElementsByTagNameNS("DAV:", "getetag")
|
||||||
|
.item(0)?.textContent?.trim('"') ?: ""
|
||||||
|
val lastModStr =
|
||||||
|
propEl.getElementsByTagNameNS("DAV:", "getlastmodified").item(0)?.textContent
|
||||||
|
val sizeStr =
|
||||||
|
propEl.getElementsByTagNameNS("DAV:", "getcontentlength").item(0)?.textContent
|
||||||
|
val fileId = propEl.getElementsByTagNameNS("http://owncloud.org/ns", "fileid")
|
||||||
|
.item(0)?.textContent ?: hrefPathNorm
|
||||||
|
|
||||||
|
entries.add(
|
||||||
|
RemoteEntry(
|
||||||
|
path = hrefPathNorm,
|
||||||
|
fileId = fileId,
|
||||||
|
etag = etag,
|
||||||
|
lastModified = lastModStr?.let { runCatching { rfc1123.parse(it)?.time }.getOrNull() } ?: 0L,
|
||||||
|
size = sizeStr?.toLongOrNull() ?: 0L,
|
||||||
|
isFolder = isFolder,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Log.d(TAG, "PROPFIND $cleanPath -> ${entries.size} entries")
|
||||||
|
return entries
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Recursively walks [rootPath] (Depth-1 PROPFINDs, breadth-first) into a flat manifest. */
|
||||||
|
fun walkRemoteTree(
|
||||||
|
serverUrl: String,
|
||||||
|
username: String,
|
||||||
|
authHeader: String,
|
||||||
|
rootPath: String,
|
||||||
|
): List<RemoteEntry> {
|
||||||
|
val result = mutableListOf<RemoteEntry>()
|
||||||
|
val queue = ArrayDeque<String>()
|
||||||
|
queue.add(rootPath)
|
||||||
|
while (queue.isNotEmpty()) {
|
||||||
|
val current = queue.removeFirst()
|
||||||
|
val children = propfindChildren(serverUrl, username, authHeader, current)
|
||||||
|
for (child in children) {
|
||||||
|
result.add(child)
|
||||||
|
if (child.isFolder) queue.add(child.path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
fun downloadFile(
|
||||||
|
serverUrl: String,
|
||||||
|
username: String,
|
||||||
|
authHeader: String,
|
||||||
|
remotePath: String,
|
||||||
|
destination: File,
|
||||||
|
): Boolean {
|
||||||
|
val encodedPath = remotePath.split("/").joinToString("/") { Uri.encode(it) }
|
||||||
|
val url = URL("${serverUrl.trimEnd('/')}/remote.php/dav/files/$username$encodedPath")
|
||||||
|
val connection = url.openConnection() as HttpURLConnection
|
||||||
|
return try {
|
||||||
|
connection.requestMethod = "GET"
|
||||||
|
connection.setRequestProperty("Authorization", authHeader)
|
||||||
|
connection.connectTimeout = 15000
|
||||||
|
connection.readTimeout = 30000
|
||||||
|
connection.connect()
|
||||||
|
val code = connection.responseCode
|
||||||
|
if (code !in 200..299) {
|
||||||
|
Log.w(TAG, "GET $url failed: $code")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
destination.parentFile?.mkdirs()
|
||||||
|
connection.inputStream.use { input ->
|
||||||
|
destination.outputStream().use { output -> input.copyTo(output) }
|
||||||
|
}
|
||||||
|
Log.d(TAG, "GET $url -> saved to ${destination.absolutePath} (${destination.length()} bytes)")
|
||||||
|
true
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "GET $url threw", e)
|
||||||
|
false
|
||||||
|
} finally {
|
||||||
|
connection.disconnect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun uploadFile(
|
||||||
|
serverUrl: String,
|
||||||
|
username: String,
|
||||||
|
authHeader: String,
|
||||||
|
remotePath: String,
|
||||||
|
source: File,
|
||||||
|
): Boolean {
|
||||||
|
val encodedPath = remotePath.split("/").joinToString("/") { Uri.encode(it) }
|
||||||
|
val url = URL("${serverUrl.trimEnd('/')}/remote.php/dav/files/$username$encodedPath")
|
||||||
|
val connection = url.openConnection() as HttpURLConnection
|
||||||
|
return try {
|
||||||
|
connection.requestMethod = "PUT"
|
||||||
|
connection.setRequestProperty("Authorization", authHeader)
|
||||||
|
connection.setFixedLengthStreamingMode(source.length())
|
||||||
|
connection.doOutput = true
|
||||||
|
connection.connectTimeout = 15000
|
||||||
|
connection.readTimeout = 60000
|
||||||
|
connection.connect()
|
||||||
|
source.inputStream().use { input ->
|
||||||
|
connection.outputStream.use { output -> input.copyTo(output) }
|
||||||
|
}
|
||||||
|
connection.responseCode in 200..299
|
||||||
|
} catch (e: Exception) {
|
||||||
|
false
|
||||||
|
} finally {
|
||||||
|
connection.disconnect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Diffs one synced folder's remote manifest against the persisted
|
||||||
|
* state, returning what to do for each item - callers own actually
|
||||||
|
* doing the GET/PUT/delete and updating state afterward, so this stays
|
||||||
|
* pure/testable-in-principle. Also returns entries no longer present
|
||||||
|
* remotely (deleted server-side, relative to the [priorFolderRelPaths]
|
||||||
|
* this folder previously produced) as [SyncAction.Delete].
|
||||||
|
*/
|
||||||
|
fun diffFolder(
|
||||||
|
entries: List<RemoteEntry>,
|
||||||
|
state: Map<String, FileState>,
|
||||||
|
priorFolderFileIds: Set<String>,
|
||||||
|
syncRoot: File,
|
||||||
|
): List<SyncAction> {
|
||||||
|
val actions = mutableListOf<SyncAction>()
|
||||||
|
val seenFileIds = mutableSetOf<String>()
|
||||||
|
|
||||||
|
for (entry in entries) {
|
||||||
|
if (entry.isFolder) continue
|
||||||
|
seenFileIds.add(entry.fileId)
|
||||||
|
val relPath = entry.path.removePrefix("/")
|
||||||
|
val localFile = File(syncRoot, relPath)
|
||||||
|
val prior = state[entry.fileId]
|
||||||
|
|
||||||
|
if (prior == null) {
|
||||||
|
// First time this folder's been walked with sync enabled -
|
||||||
|
// nothing locally recorded yet to protect, so just pull it.
|
||||||
|
actions.add(SyncAction.Download(entry))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
val serverChanged = entry.etag != prior.etag
|
||||||
|
val localExists = localFile.exists()
|
||||||
|
val localChanged = localExists &&
|
||||||
|
(localFile.lastModified() != prior.localMTime || localFile.length() != prior.size)
|
||||||
|
|
||||||
|
when {
|
||||||
|
!localExists && !serverChanged -> {
|
||||||
|
// User deleted the local mirror copy themselves and the
|
||||||
|
// server hasn't changed - respect that deletion rather
|
||||||
|
// than silently re-creating it.
|
||||||
|
actions.add(SyncAction.Delete(relPath, entry.fileId))
|
||||||
|
}
|
||||||
|
serverChanged && localChanged -> actions.add(SyncAction.Conflict(entry, relPath))
|
||||||
|
serverChanged -> actions.add(SyncAction.Download(entry))
|
||||||
|
localChanged -> actions.add(SyncAction.Upload(relPath, entry.fileId))
|
||||||
|
else -> {} // unchanged, nothing to do
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Anything this folder had state for last time but that didn't show
|
||||||
|
// up in this walk at all was deleted server-side.
|
||||||
|
for (fileId in priorFolderFileIds) {
|
||||||
|
if (fileId !in seenFileIds) {
|
||||||
|
val prior = state[fileId] ?: continue
|
||||||
|
actions.add(SyncAction.Delete(prior.relPath, fileId))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Log.d(
|
||||||
|
TAG,
|
||||||
|
"diffFolder: ${entries.size} entries -> " +
|
||||||
|
"${actions.count { it is SyncAction.Download }} downloads, " +
|
||||||
|
"${actions.count { it is SyncAction.Upload }} uploads, " +
|
||||||
|
"${actions.count { it is SyncAction.Delete }} deletes, " +
|
||||||
|
"${actions.count { it is SyncAction.Conflict }} conflicts",
|
||||||
|
)
|
||||||
|
return actions
|
||||||
|
}
|
||||||
|
|
||||||
|
fun folderIsSyncedUnder(itemPath: String, syncedFolders: List<String>): String? {
|
||||||
|
val normalizedItem = itemPath.trimEnd('/')
|
||||||
|
for (folder in syncedFolders) {
|
||||||
|
val normalizedFolder = folder.trimEnd('/')
|
||||||
|
if (normalizedItem == normalizedFolder || normalizedItem.startsWith("$normalizedFolder/")) {
|
||||||
|
return folder
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package dev.ayushya.noo
|
||||||
|
|
||||||
|
/**
|
||||||
|
* In-memory, in-process pub/sub for live device-sync status -
|
||||||
|
* [SyncWorker]/[ConflictResolveWorker] publish into this, `MainActivity`'s
|
||||||
|
* `dev.ayushya.noo/sync_service/status` EventChannel forwards it to Dart.
|
||||||
|
* Plain in-memory state is enough (no IPC/persistence needed) since the
|
||||||
|
* workers and the Activity always run in the same process; contrast with
|
||||||
|
* [SyncEngine]'s on-disk per-account state map, which *is* durable and is
|
||||||
|
* what actually answers "is this file synced" (this bus only ever tracks
|
||||||
|
* the transient "syncing right now" / "unresolved conflict" parts of that
|
||||||
|
* picture).
|
||||||
|
*/
|
||||||
|
object SyncStatusBus {
|
||||||
|
data class Conflict(
|
||||||
|
val accountId: String,
|
||||||
|
val fileId: String,
|
||||||
|
val remotePath: String,
|
||||||
|
val relPath: String,
|
||||||
|
val name: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class Status(
|
||||||
|
val accountId: String?,
|
||||||
|
val syncing: Boolean,
|
||||||
|
val syncingFileIds: Set<String>,
|
||||||
|
val conflicts: List<Conflict>,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var current = Status(accountId = null, syncing = false, syncingFileIds = emptySet(), conflicts = emptyList())
|
||||||
|
private val listeners = mutableListOf<(Status) -> Unit>()
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun subscribe(listener: (Status) -> Unit) {
|
||||||
|
listeners.add(listener)
|
||||||
|
listener(current)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun unsubscribe(listener: (Status) -> Unit) {
|
||||||
|
listeners.remove(listener)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun snapshot(): Status = current
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun setSyncing(accountId: String, syncing: Boolean) {
|
||||||
|
current = current.copy(accountId = accountId, syncing = syncing)
|
||||||
|
if (!syncing) current = current.copy(syncingFileIds = emptySet())
|
||||||
|
publish()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun markFileSyncing(accountId: String, fileId: String, syncing: Boolean) {
|
||||||
|
val ids = current.syncingFileIds.toMutableSet()
|
||||||
|
if (syncing) ids.add(fileId) else ids.remove(fileId)
|
||||||
|
current = current.copy(accountId = accountId, syncingFileIds = ids)
|
||||||
|
publish()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun addConflicts(accountId: String, newConflicts: List<Conflict>) {
|
||||||
|
if (newConflicts.isEmpty()) return
|
||||||
|
val existingIds = current.conflicts.map { it.fileId }.toSet()
|
||||||
|
val merged = current.conflicts + newConflicts.filter { it.fileId !in existingIds }
|
||||||
|
current = current.copy(accountId = accountId, conflicts = merged)
|
||||||
|
publish()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun removeConflict(accountId: String, fileId: String) {
|
||||||
|
current = current.copy(accountId = accountId, conflicts = current.conflicts.filter { it.fileId != fileId })
|
||||||
|
publish()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun publish() {
|
||||||
|
listeners.toList().forEach { it(current) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,272 @@
|
|||||||
|
package dev.ayushya.noo
|
||||||
|
|
||||||
|
import android.app.Notification
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.app.PendingIntent
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Build
|
||||||
|
import android.util.Log
|
||||||
|
import androidx.core.app.NotificationCompat
|
||||||
|
import androidx.work.CoroutineWorker
|
||||||
|
import androidx.work.WorkerParameters
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import org.json.JSONArray
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The periodic (and manual "Sync now") device-sync job. Runs entirely
|
||||||
|
* independent of the Flutter engine (see [SyncEngine]'s doc comment) -
|
||||||
|
* enqueued/re-enqueued from `MainActivity.kt`'s
|
||||||
|
* `dev.ayushya.noo/sync_service` MethodChannel whenever the synced-folder
|
||||||
|
* list, account, or network setting changes, since a periodic
|
||||||
|
* `WorkRequest`'s input `Data` is fixed at enqueue time.
|
||||||
|
*/
|
||||||
|
class SyncWorker(appContext: Context, params: WorkerParameters) :
|
||||||
|
CoroutineWorker(appContext, params) {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val KEY_ACCOUNT_ID = "accountId"
|
||||||
|
const val KEY_SERVER_URL = "serverUrl"
|
||||||
|
const val KEY_USERNAME = "username"
|
||||||
|
const val KEY_AUTH_HEADER = "authHeader"
|
||||||
|
const val KEY_FOLDERS = "folders" // JSON array of remote file/folder paths
|
||||||
|
|
||||||
|
const val UNIQUE_PERIODIC_NAME = "noo_sync_periodic"
|
||||||
|
const val UNIQUE_ONE_OFF_NAME = "noo_sync_now"
|
||||||
|
|
||||||
|
private const val CHANNEL_ID = "device_sync"
|
||||||
|
private const val SUMMARY_NOTIFICATION_ID = 4401
|
||||||
|
private const val CONFLICT_NOTIFICATION_ID_BASE = 4500
|
||||||
|
private const val TAG = "NooSync"
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
|
||||||
|
val accountId = inputData.getString(KEY_ACCOUNT_ID) ?: return@withContext Result.failure()
|
||||||
|
val serverUrl = inputData.getString(KEY_SERVER_URL) ?: return@withContext Result.failure()
|
||||||
|
val username = inputData.getString(KEY_USERNAME) ?: return@withContext Result.failure()
|
||||||
|
val authHeader = inputData.getString(KEY_AUTH_HEADER) ?: return@withContext Result.failure()
|
||||||
|
val foldersJson = inputData.getString(KEY_FOLDERS) ?: "[]"
|
||||||
|
val folders = (0 until JSONArray(foldersJson).length()).map { JSONArray(foldersJson).getString(it) }
|
||||||
|
Log.d(TAG, "doWork: account=$accountId server=$serverUrl user=$username folders=$folders")
|
||||||
|
if (folders.isEmpty()) return@withContext Result.success()
|
||||||
|
|
||||||
|
val syncRoot = SyncEngine.syncRoot(applicationContext, accountId)
|
||||||
|
val state = SyncEngine.loadState(applicationContext, accountId).toMutableMap()
|
||||||
|
|
||||||
|
var downloaded = 0
|
||||||
|
var uploaded = 0
|
||||||
|
var deleted = 0
|
||||||
|
val conflicts = mutableListOf<Pair<SyncEngine.RemoteEntry, String>>()
|
||||||
|
|
||||||
|
SyncStatusBus.setSyncing(accountId, true)
|
||||||
|
try {
|
||||||
|
for (path in folders) {
|
||||||
|
// A configured path can be a file or a folder now - check
|
||||||
|
// which before deciding whether to walk it recursively or
|
||||||
|
// just diff the single item.
|
||||||
|
val self = SyncEngine.propfindSelf(serverUrl, username, authHeader, path)
|
||||||
|
val entries = when {
|
||||||
|
self == null -> emptyList()
|
||||||
|
self.isFolder -> SyncEngine.walkRemoteTree(serverUrl, username, authHeader, path)
|
||||||
|
else -> listOf(self)
|
||||||
|
}
|
||||||
|
val pathPrefix = path.trimEnd('/') + "/"
|
||||||
|
val priorFileIdsForPath = state.filterValues {
|
||||||
|
it.relPath == path.trimStart('/') || it.relPath.startsWith(pathPrefix.trimStart('/'))
|
||||||
|
}.keys
|
||||||
|
|
||||||
|
val actions = SyncEngine.diffFolder(entries, state, priorFileIdsForPath, syncRoot)
|
||||||
|
for (action in actions) {
|
||||||
|
when (action) {
|
||||||
|
is SyncEngine.SyncAction.Download -> {
|
||||||
|
SyncStatusBus.markFileSyncing(accountId, action.entry.fileId, true)
|
||||||
|
val relPath = action.entry.path.removePrefix("/")
|
||||||
|
val dest = File(syncRoot, relPath)
|
||||||
|
if (SyncEngine.downloadFile(serverUrl, username, authHeader, action.entry.path, dest)) {
|
||||||
|
state[action.entry.fileId] = SyncEngine.FileState(
|
||||||
|
relPath = relPath,
|
||||||
|
etag = action.entry.etag,
|
||||||
|
lastModified = action.entry.lastModified,
|
||||||
|
size = action.entry.size,
|
||||||
|
localMTime = dest.lastModified(),
|
||||||
|
)
|
||||||
|
downloaded++
|
||||||
|
}
|
||||||
|
SyncStatusBus.markFileSyncing(accountId, action.entry.fileId, false)
|
||||||
|
}
|
||||||
|
is SyncEngine.SyncAction.Upload -> {
|
||||||
|
SyncStatusBus.markFileSyncing(accountId, action.fileId, true)
|
||||||
|
val localFile = File(syncRoot, action.relPath)
|
||||||
|
val remotePath = "/${action.relPath}"
|
||||||
|
if (localFile.exists() &&
|
||||||
|
SyncEngine.uploadFile(serverUrl, username, authHeader, remotePath, localFile)
|
||||||
|
) {
|
||||||
|
val prior = state[action.fileId]
|
||||||
|
state[action.fileId] = SyncEngine.FileState(
|
||||||
|
relPath = action.relPath,
|
||||||
|
etag = prior?.etag ?: "",
|
||||||
|
lastModified = localFile.lastModified(),
|
||||||
|
size = localFile.length(),
|
||||||
|
localMTime = localFile.lastModified(),
|
||||||
|
)
|
||||||
|
uploaded++
|
||||||
|
}
|
||||||
|
SyncStatusBus.markFileSyncing(accountId, action.fileId, false)
|
||||||
|
}
|
||||||
|
is SyncEngine.SyncAction.Delete -> {
|
||||||
|
File(syncRoot, action.relPath).delete()
|
||||||
|
state.remove(action.fileId)
|
||||||
|
deleted++
|
||||||
|
}
|
||||||
|
is SyncEngine.SyncAction.Conflict -> conflicts.add(action.entry to action.relPath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
SyncStatusBus.setSyncing(accountId, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
SyncEngine.saveState(applicationContext, accountId, state)
|
||||||
|
Log.d(
|
||||||
|
TAG,
|
||||||
|
"doWork done: downloaded=$downloaded uploaded=$uploaded deleted=$deleted conflicts=${conflicts.size}",
|
||||||
|
)
|
||||||
|
|
||||||
|
if (downloaded > 0 || uploaded > 0 || deleted > 0) {
|
||||||
|
notifySummary(downloaded, uploaded, deleted)
|
||||||
|
}
|
||||||
|
if (conflicts.isNotEmpty()) {
|
||||||
|
SyncStatusBus.addConflicts(
|
||||||
|
accountId,
|
||||||
|
conflicts.map { (entry, relPath) ->
|
||||||
|
SyncStatusBus.Conflict(
|
||||||
|
accountId = accountId,
|
||||||
|
fileId = entry.fileId,
|
||||||
|
remotePath = entry.path,
|
||||||
|
relPath = relPath,
|
||||||
|
name = relPath.substringAfterLast('/'),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
notifyConflicts(accountId, serverUrl, username, authHeader, conflicts)
|
||||||
|
}
|
||||||
|
|
||||||
|
Result.success()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun notifySummary(downloaded: Int, uploaded: Int, deleted: Int) {
|
||||||
|
createChannel()
|
||||||
|
val parts = mutableListOf<String>()
|
||||||
|
if (downloaded > 0) parts.add("$downloaded updated")
|
||||||
|
if (uploaded > 0) parts.add("$uploaded uploaded")
|
||||||
|
if (deleted > 0) parts.add("$deleted removed")
|
||||||
|
val text = parts.joinToString(", ")
|
||||||
|
|
||||||
|
val notification = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
|
||||||
|
.setSmallIcon(android.R.drawable.stat_notify_sync)
|
||||||
|
.setContentTitle("Noo sync")
|
||||||
|
.setContentText(text)
|
||||||
|
.setAutoCancel(true)
|
||||||
|
.build()
|
||||||
|
manager().notify(SUMMARY_NOTIFICATION_ID, notification)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun notifyConflicts(
|
||||||
|
accountId: String,
|
||||||
|
serverUrl: String,
|
||||||
|
username: String,
|
||||||
|
authHeader: String,
|
||||||
|
conflicts: List<Pair<SyncEngine.RemoteEntry, String>>,
|
||||||
|
) {
|
||||||
|
createChannel()
|
||||||
|
for ((index, conflict) in conflicts.withIndex()) {
|
||||||
|
val (entry, relPath) = conflict
|
||||||
|
val fileName = relPath.substringAfterLast('/')
|
||||||
|
val notificationId = CONFLICT_NOTIFICATION_ID_BASE + (relPath.hashCode() and 0xFFFF)
|
||||||
|
|
||||||
|
val useLocalIntent = conflictActionIntent(
|
||||||
|
accountId,
|
||||||
|
serverUrl,
|
||||||
|
username,
|
||||||
|
authHeader,
|
||||||
|
entry.fileId,
|
||||||
|
entry.path,
|
||||||
|
relPath,
|
||||||
|
"local",
|
||||||
|
notificationId,
|
||||||
|
)
|
||||||
|
val useServerIntent = conflictActionIntent(
|
||||||
|
accountId,
|
||||||
|
serverUrl,
|
||||||
|
username,
|
||||||
|
authHeader,
|
||||||
|
entry.fileId,
|
||||||
|
entry.path,
|
||||||
|
relPath,
|
||||||
|
"server",
|
||||||
|
notificationId,
|
||||||
|
)
|
||||||
|
|
||||||
|
val notification = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
|
||||||
|
.setSmallIcon(android.R.drawable.stat_notify_error)
|
||||||
|
.setContentTitle("Sync conflict: $fileName")
|
||||||
|
.setContentText("Changed both on this device and on the server.")
|
||||||
|
.setAutoCancel(true)
|
||||||
|
.addAction(0, "Keep local", useLocalIntent)
|
||||||
|
.addAction(0, "Use server", useServerIntent)
|
||||||
|
.build()
|
||||||
|
manager().notify(notificationId, notification)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun conflictActionIntent(
|
||||||
|
accountId: String,
|
||||||
|
serverUrl: String,
|
||||||
|
username: String,
|
||||||
|
authHeader: String,
|
||||||
|
fileId: String,
|
||||||
|
remotePath: String,
|
||||||
|
relPath: String,
|
||||||
|
resolution: String,
|
||||||
|
notificationId: Int,
|
||||||
|
): PendingIntent {
|
||||||
|
val intent = Intent(applicationContext, SyncConflictReceiver::class.java).apply {
|
||||||
|
action = SyncConflictReceiver.ACTION_RESOLVE
|
||||||
|
putExtra(SyncConflictReceiver.EXTRA_ACCOUNT_ID, accountId)
|
||||||
|
putExtra(SyncConflictReceiver.EXTRA_SERVER_URL, serverUrl)
|
||||||
|
putExtra(SyncConflictReceiver.EXTRA_USERNAME, username)
|
||||||
|
putExtra(SyncConflictReceiver.EXTRA_AUTH_HEADER, authHeader)
|
||||||
|
putExtra(SyncConflictReceiver.EXTRA_FILE_ID, fileId)
|
||||||
|
putExtra(SyncConflictReceiver.EXTRA_REMOTE_PATH, remotePath)
|
||||||
|
putExtra(SyncConflictReceiver.EXTRA_REL_PATH, relPath)
|
||||||
|
putExtra(SyncConflictReceiver.EXTRA_RESOLUTION, resolution)
|
||||||
|
putExtra(SyncConflictReceiver.EXTRA_NOTIFICATION_ID, notificationId)
|
||||||
|
}
|
||||||
|
// Request code must be unique per (file, resolution) pair, else the
|
||||||
|
// two actions' PendingIntents collide and only one survives.
|
||||||
|
val requestCode = (relPath + resolution).hashCode()
|
||||||
|
return PendingIntent.getBroadcast(
|
||||||
|
applicationContext,
|
||||||
|
requestCode,
|
||||||
|
intent,
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun manager() =
|
||||||
|
applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||||
|
|
||||||
|
private fun createChannel() {
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
val channel = NotificationChannel(
|
||||||
|
CHANNEL_ID,
|
||||||
|
"Device sync",
|
||||||
|
NotificationManager.IMPORTANCE_DEFAULT,
|
||||||
|
).apply { description = "Updates and conflicts for folders synced to this device" }
|
||||||
|
manager().createNotificationChannel(channel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!-- Exposes only the app's own "picker" cache subfolder as content:// Uris -
|
||||||
|
used to hand a file back to another app that launched Noo as a
|
||||||
|
GET_CONTENT picker (see PickIntentService/MainActivity.kt). -->
|
||||||
|
<paths xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<cache-path name="picker" path="picker/" />
|
||||||
|
</paths>
|
||||||
+116
-2
@@ -1,9 +1,13 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'package:dynamic_color/dynamic_color.dart';
|
import 'package:dynamic_color/dynamic_color.dart';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:permission_handler/permission_handler.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
import 'models/app_tab.dart';
|
import 'models/app_tab.dart';
|
||||||
|
import 'models/pick_request.dart';
|
||||||
import 'providers/server_provider.dart';
|
import 'providers/server_provider.dart';
|
||||||
|
import 'services/pick_intent_service.dart';
|
||||||
import 'services/share_intent_service.dart';
|
import 'services/share_intent_service.dart';
|
||||||
import 'theme/app_theme.dart';
|
import 'theme/app_theme.dart';
|
||||||
import 'views/lock_screen_view.dart';
|
import 'views/lock_screen_view.dart';
|
||||||
@@ -113,6 +117,7 @@ class _MainShellViewState extends State<MainShellView> {
|
|||||||
late AppTab _currentTab;
|
late AppTab _currentTab;
|
||||||
late final Map<AppTab, ScrollController> _scrollControllers;
|
late final Map<AppTab, ScrollController> _scrollControllers;
|
||||||
StreamSubscription<List<SharedFileRef>>? _shareSub;
|
StreamSubscription<List<SharedFileRef>>? _shareSub;
|
||||||
|
StreamSubscription<PickRequest>? _pickSub;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
@@ -133,6 +138,64 @@ class _MainShellViewState extends State<MainShellView> {
|
|||||||
// file's actual bytes, so a large shared file can't block startup.
|
// file's actual bytes, so a large shared file can't block startup.
|
||||||
ShareIntentService.getInitialShare().then(_handleSharedFiles);
|
ShareIntentService.getInitialShare().then(_handleSharedFiles);
|
||||||
_shareSub = ShareIntentService.onNewShare.listen(_handleSharedFiles);
|
_shareSub = ShareIntentService.onNewShare.listen(_handleSharedFiles);
|
||||||
|
|
||||||
|
// Same cold-start-vs-already-running split as the share intent above:
|
||||||
|
// another app may have launched Noo as its GET_CONTENT picker.
|
||||||
|
PickIntentService.getPickRequest().then((request) {
|
||||||
|
if (request != null && mounted) {
|
||||||
|
context.read<ServerProvider>().setPickRequest(request);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
_pickSub = PickIntentService.onNewPickRequest.listen((request) {
|
||||||
|
if (mounted) context.read<ServerProvider>().setPickRequest(request);
|
||||||
|
});
|
||||||
|
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback(
|
||||||
|
(_) => _maybeRequestNotificationPermission(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static const _prefNotificationPermissionAsked =
|
||||||
|
'notification_permission_asked';
|
||||||
|
|
||||||
|
// Asked once, on the app's first launch after login, rather than every
|
||||||
|
// time this shell mounts - a plain-language reason shown before the OS
|
||||||
|
// prompt (which just says "Noo would like to send you notifications"
|
||||||
|
// with no context) so the system dialog doesn't feel unexplained, since
|
||||||
|
// it's what shows upload/download progress for background transfers.
|
||||||
|
Future<void> _maybeRequestNotificationPermission() async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
if (prefs.getBool(_prefNotificationPermissionAsked) ?? false) return;
|
||||||
|
await prefs.setBool(_prefNotificationPermissionAsked, true);
|
||||||
|
|
||||||
|
final status = await Permission.notification.status;
|
||||||
|
if (status.isGranted || status.isPermanentlyDenied) return;
|
||||||
|
if (!mounted) return;
|
||||||
|
|
||||||
|
final shouldRequest = await showDialog<bool>(
|
||||||
|
context: context,
|
||||||
|
barrierDismissible: false,
|
||||||
|
builder: (context) => AlertDialog(
|
||||||
|
title: const Text('Allow notifications?'),
|
||||||
|
content: const Text(
|
||||||
|
'Noo shows upload and download progress as a notification, so '
|
||||||
|
'you can track transfers that keep running in the background.',
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(false),
|
||||||
|
child: const Text('Not now'),
|
||||||
|
),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(true),
|
||||||
|
child: const Text('Allow'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (shouldRequest == true) {
|
||||||
|
await Permission.notification.request();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void _handleSharedFiles(List<SharedFileRef> files) {
|
void _handleSharedFiles(List<SharedFileRef> files) {
|
||||||
@@ -151,6 +214,7 @@ class _MainShellViewState extends State<MainShellView> {
|
|||||||
c.dispose();
|
c.dispose();
|
||||||
}
|
}
|
||||||
_shareSub?.cancel();
|
_shareSub?.cancel();
|
||||||
|
_pickSub?.cancel();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,7 +233,16 @@ class _MainShellViewState extends State<MainShellView> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
final visible = provider.visibleTabs;
|
final pickRequest = provider.pickRequest;
|
||||||
|
// While acting as another app's picker, only Files and Photos make
|
||||||
|
// sense as browsable sources - Trash/Shares/Activity/Recent aren't
|
||||||
|
// real "pick a file from here" destinations, and only these two tabs'
|
||||||
|
// views even know how to handle picking-mode taps. This overrides the
|
||||||
|
// user's own hidden/reordered tab settings rather than respecting
|
||||||
|
// them, since picking is a separate mode from normal browsing.
|
||||||
|
final visible = pickRequest != null
|
||||||
|
? [AppTab.files, AppTab.photos]
|
||||||
|
: provider.visibleTabs;
|
||||||
final selectedTab = visible.contains(_currentTab)
|
final selectedTab = visible.contains(_currentTab)
|
||||||
? _currentTab
|
? _currentTab
|
||||||
: (visible.isNotEmpty ? visible.first : AppTab.files);
|
: (visible.isNotEmpty ? visible.first : AppTab.files);
|
||||||
@@ -181,7 +254,15 @@ class _MainShellViewState extends State<MainShellView> {
|
|||||||
.map((tab) => FloatingNavItem(label: tab.label, icon: tab.icon))
|
.map((tab) => FloatingNavItem(label: tab.label, icon: tab.icon))
|
||||||
.toList();
|
.toList();
|
||||||
|
|
||||||
return Scaffold(
|
return PopScope(
|
||||||
|
// While picking, system back cancels the pick (and tells the caller
|
||||||
|
// nothing was chosen) instead of exiting the app from under it -
|
||||||
|
// there's no Navigator route to pop at this, the root screen.
|
||||||
|
canPop: pickRequest == null,
|
||||||
|
onPopInvokedWithResult: (didPop, result) {
|
||||||
|
if (!didPop && pickRequest != null) provider.cancelPick();
|
||||||
|
},
|
||||||
|
child: Scaffold(
|
||||||
body: Stack(
|
body: Stack(
|
||||||
children: [
|
children: [
|
||||||
IndexedStack(
|
IndexedStack(
|
||||||
@@ -190,6 +271,7 @@ class _MainShellViewState extends State<MainShellView> {
|
|||||||
.map((tab) => buildAppTabView(tab, _scrollControllers[tab]!))
|
.map((tab) => buildAppTabView(tab, _scrollControllers[tab]!))
|
||||||
.toList(),
|
.toList(),
|
||||||
),
|
),
|
||||||
|
if (provider.isDownloadingForPick) const _PickingProgressOverlay(),
|
||||||
// Each tab now renders its own sticky selection toolbar inline
|
// Each tab now renders its own sticky selection toolbar inline
|
||||||
// (right under its sort/filter row) instead of this shell
|
// (right under its sort/filter row) instead of this shell
|
||||||
// swapping in a shared floating bar - the bottom nav stays put
|
// swapping in a shared floating bar - the bottom nav stays put
|
||||||
@@ -226,6 +308,38 @@ class _MainShellViewState extends State<MainShellView> {
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Blocks interaction while the selected file(s) download to a local cache
|
||||||
|
/// folder before being handed back to the caller (see
|
||||||
|
/// `ServerProvider.confirmPick`) - can take a moment for a large file/video.
|
||||||
|
class _PickingProgressOverlay extends StatelessWidget {
|
||||||
|
const _PickingProgressOverlay();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Positioned.fill(
|
||||||
|
child: ColoredBox(
|
||||||
|
color: Colors.black.withValues(alpha: 0.35),
|
||||||
|
child: const Center(
|
||||||
|
child: Card(
|
||||||
|
child: Padding(
|
||||||
|
padding: EdgeInsets.all(24),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
CircularProgressIndicator(),
|
||||||
|
SizedBox(height: 16),
|
||||||
|
Text('Preparing file...'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import 'package:material_symbols_icons/symbols.dart';
|
|||||||
/// Every destination the bottom nav bar can show. Order here is only the
|
/// Every destination the bottom nav bar can show. Order here is only the
|
||||||
/// fallback default — actual order/visibility/default-tab are user
|
/// fallback default — actual order/visibility/default-tab are user
|
||||||
/// configurable and persisted in [ServerProvider].
|
/// configurable and persisted in [ServerProvider].
|
||||||
enum AppTab { files, photos, activity, trash, shares, recent }
|
enum AppTab { files, photos, favorites, activity, trash, shares, recent }
|
||||||
|
|
||||||
/// At most this many tabs may be visible in the bottom nav bar at once —
|
/// At most this many tabs may be visible in the bottom nav bar at once —
|
||||||
/// the rest are reachable through the "more" dropdown instead.
|
/// the rest are reachable through the "more" dropdown instead.
|
||||||
@@ -17,6 +17,8 @@ extension AppTabInfo on AppTab {
|
|||||||
return 'Files';
|
return 'Files';
|
||||||
case AppTab.photos:
|
case AppTab.photos:
|
||||||
return 'Photos';
|
return 'Photos';
|
||||||
|
case AppTab.favorites:
|
||||||
|
return 'Favorites';
|
||||||
case AppTab.activity:
|
case AppTab.activity:
|
||||||
return 'Activity';
|
return 'Activity';
|
||||||
case AppTab.trash:
|
case AppTab.trash:
|
||||||
@@ -34,6 +36,8 @@ extension AppTabInfo on AppTab {
|
|||||||
return Icons.folder_rounded;
|
return Icons.folder_rounded;
|
||||||
case AppTab.photos:
|
case AppTab.photos:
|
||||||
return Icons.photo_library_rounded;
|
return Icons.photo_library_rounded;
|
||||||
|
case AppTab.favorites:
|
||||||
|
return Icons.favorite_rounded;
|
||||||
case AppTab.activity:
|
case AppTab.activity:
|
||||||
return Icons.electric_bolt_rounded;
|
return Icons.electric_bolt_rounded;
|
||||||
case AppTab.trash:
|
case AppTab.trash:
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import 'nextcloud_item.dart';
|
||||||
|
|
||||||
|
/// A resolution choice for one conflicting item in a Move/Copy batch -
|
||||||
|
/// keyed by `item.id` in [ConflictChoice] maps passed to
|
||||||
|
/// `ServerProvider.resolveConflicts`.
|
||||||
|
enum ConflictChoice { overwrite, keepBoth, skip }
|
||||||
|
|
||||||
|
/// One item that couldn't be moved/copied because something with the same
|
||||||
|
/// name already exists at the destination (a WebDAV 412 response).
|
||||||
|
class MoveCopyConflict {
|
||||||
|
final NextcloudItem item;
|
||||||
|
|
||||||
|
const MoveCopyConflict(this.item);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Outcome of a Move/Copy batch (an initial attempt via
|
||||||
|
/// `ServerProvider.moveItems`/`copyItems`, or a follow-up
|
||||||
|
/// `resolveConflicts` call). [blockedReason] is set instead of attempting
|
||||||
|
/// anything at all when the destination itself is invalid (e.g. moving a
|
||||||
|
/// folder into its own subfolder).
|
||||||
|
class MoveCopyResult {
|
||||||
|
final int succeeded;
|
||||||
|
final List<MoveCopyConflict> conflicts;
|
||||||
|
final int failed;
|
||||||
|
final String? blockedReason;
|
||||||
|
|
||||||
|
const MoveCopyResult({
|
||||||
|
this.succeeded = 0,
|
||||||
|
this.conflicts = const [],
|
||||||
|
this.failed = 0,
|
||||||
|
this.blockedReason,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
/// Another app asking Noo (via Android's GET_CONTENT chooser) to pick a
|
||||||
|
/// file/photo and hand it back - see `PickIntentService`/`MainActivity.kt`.
|
||||||
|
class PickRequest {
|
||||||
|
final String mimeType;
|
||||||
|
final bool allowMultiple;
|
||||||
|
final String? callerLabel;
|
||||||
|
|
||||||
|
const PickRequest({
|
||||||
|
required this.mimeType,
|
||||||
|
required this.allowMultiple,
|
||||||
|
this.callerLabel,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory PickRequest.fromMap(Map<dynamic, dynamic> map) {
|
||||||
|
return PickRequest(
|
||||||
|
mimeType: map['mimeType'] as String? ?? '*/*',
|
||||||
|
allowMultiple: map['allowMultiple'] as bool? ?? false,
|
||||||
|
callerLabel: map['callerLabel'] as String?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether an item's mime type satisfies this request's filter (which may
|
||||||
|
/// be a wildcard like `image/*` or the catch-all `*/*`).
|
||||||
|
bool matches(String? itemMimeType) {
|
||||||
|
if (mimeType == '*/*') return true;
|
||||||
|
if (itemMimeType == null) return false;
|
||||||
|
if (mimeType.endsWith('/*')) {
|
||||||
|
return itemMimeType.startsWith(
|
||||||
|
mimeType.substring(0, mimeType.length - 1),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return itemMimeType == mimeType;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,13 +6,11 @@ import 'package:flutter/material.dart';
|
|||||||
class SelectionAction {
|
class SelectionAction {
|
||||||
final IconData icon;
|
final IconData icon;
|
||||||
final String label;
|
final String label;
|
||||||
final Color? color;
|
|
||||||
final VoidCallback onTap;
|
final VoidCallback onTap;
|
||||||
|
|
||||||
const SelectionAction({
|
const SelectionAction({
|
||||||
required this.icon,
|
required this.icon,
|
||||||
required this.label,
|
required this.label,
|
||||||
required this.onTap,
|
required this.onTap,
|
||||||
this.color,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
/// A pending device-sync conflict (a file changed both locally and on the
|
||||||
|
/// server since the last sync) - mirrors `SyncStatusBus.Conflict` on the
|
||||||
|
/// native side exactly, see `SyncEngine.kt`/`server.md`'s "Device sync"
|
||||||
|
/// section.
|
||||||
|
class SyncConflictInfo {
|
||||||
|
final String accountId;
|
||||||
|
final String fileId;
|
||||||
|
final String remotePath;
|
||||||
|
final String relPath;
|
||||||
|
final String name;
|
||||||
|
|
||||||
|
const SyncConflictInfo({
|
||||||
|
required this.accountId,
|
||||||
|
required this.fileId,
|
||||||
|
required this.remotePath,
|
||||||
|
required this.relPath,
|
||||||
|
required this.name,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SyncConflictInfo.fromMap(Map<dynamic, dynamic> map) {
|
||||||
|
return SyncConflictInfo(
|
||||||
|
accountId: map['accountId'] as String? ?? '',
|
||||||
|
fileId: map['fileId'] as String? ?? '',
|
||||||
|
remotePath: map['remotePath'] as String? ?? '',
|
||||||
|
relPath: map['relPath'] as String? ?? '',
|
||||||
|
name: map['name'] as String? ?? '',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A single item's device-sync status, used to badge its tile in the
|
||||||
|
/// Files view.
|
||||||
|
enum SyncItemStatus { none, syncing, synced, conflict }
|
||||||
|
|
||||||
|
/// The persistent header chip/panel's overall status (account-wide, not
|
||||||
|
/// scoped to whatever folder is currently browsed) - see
|
||||||
|
/// `ServerProvider.syncHeaderStatus`.
|
||||||
|
enum SyncHeaderStatus { off, syncing, done, alert }
|
||||||
@@ -1,18 +1,26 @@
|
|||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:path/path.dart' as p;
|
||||||
|
import 'package:path_provider/path_provider.dart';
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
import '../models/app_tab.dart';
|
import '../models/app_tab.dart';
|
||||||
|
import '../models/move_copy_result.dart';
|
||||||
import '../models/nextcloud_file_version.dart';
|
import '../models/nextcloud_file_version.dart';
|
||||||
import '../models/nextcloud_item.dart';
|
import '../models/nextcloud_item.dart';
|
||||||
import '../models/nextcloud_share.dart';
|
import '../models/nextcloud_share.dart';
|
||||||
import '../models/nextcloud_sharee.dart';
|
import '../models/nextcloud_sharee.dart';
|
||||||
|
import '../models/pick_request.dart';
|
||||||
import '../models/saved_account.dart';
|
import '../models/saved_account.dart';
|
||||||
|
import '../models/sync_status.dart';
|
||||||
import '../services/account_store.dart';
|
import '../services/account_store.dart';
|
||||||
import '../services/app_lock_service.dart';
|
import '../services/app_lock_service.dart';
|
||||||
import '../services/login_flow_service.dart';
|
import '../services/login_flow_service.dart';
|
||||||
import '../services/nextcloud_service.dart';
|
import '../services/nextcloud_service.dart';
|
||||||
|
import '../services/pick_intent_service.dart';
|
||||||
|
import '../services/sync_service.dart';
|
||||||
import '../theme/app_theme.dart';
|
import '../theme/app_theme.dart';
|
||||||
|
|
||||||
enum LoginFlowStatus { idle, initiating, awaitingBrowser, error }
|
enum LoginFlowStatus { idle, initiating, awaitingBrowser, error }
|
||||||
@@ -70,7 +78,6 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
static const _prefBottomBarOpacity = 'ui_bottom_bar_opacity';
|
static const _prefBottomBarOpacity = 'ui_bottom_bar_opacity';
|
||||||
static const _prefBottomBarBlur = 'ui_bottom_bar_blur';
|
static const _prefBottomBarBlur = 'ui_bottom_bar_blur';
|
||||||
static const _prefGridView = 'ui_grid_view';
|
static const _prefGridView = 'ui_grid_view';
|
||||||
static const _prefShowFavoritesOnlyFiles = 'ui_show_favorites_only';
|
|
||||||
static const _prefShowFavoritesOnlyPhotos = 'ui_show_favorites_only_photos';
|
static const _prefShowFavoritesOnlyPhotos = 'ui_show_favorites_only_photos';
|
||||||
static const _prefStorageScope = 'ui_storage_scope';
|
static const _prefStorageScope = 'ui_storage_scope';
|
||||||
static const _prefFilesTypeFilter = 'ui_files_type_filter';
|
static const _prefFilesTypeFilter = 'ui_files_type_filter';
|
||||||
@@ -92,6 +99,9 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
static const _prefLoginLockEnabled = 'ui_login_lock_enabled';
|
static const _prefLoginLockEnabled = 'ui_login_lock_enabled';
|
||||||
static const _prefLockAccountSwitching = 'ui_lock_account_switching';
|
static const _prefLockAccountSwitching = 'ui_lock_account_switching';
|
||||||
static const _prefLockHiddenFiles = 'ui_lock_hidden_files';
|
static const _prefLockHiddenFiles = 'ui_lock_hidden_files';
|
||||||
|
static const _prefSyncedFolders = 'ui_synced_folders';
|
||||||
|
static const _prefSyncEverything = 'ui_sync_everything';
|
||||||
|
static const _prefSyncOnCellular = 'ui_sync_on_cellular';
|
||||||
|
|
||||||
final Future<SharedPreferences> _prefsFuture =
|
final Future<SharedPreferences> _prefsFuture =
|
||||||
SharedPreferences.getInstance();
|
SharedPreferences.getInstance();
|
||||||
@@ -122,6 +132,23 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
double _bottomBarBlur = 28;
|
double _bottomBarBlur = 28;
|
||||||
bool _tapTabToScrollTop = true;
|
bool _tapTabToScrollTop = true;
|
||||||
|
|
||||||
|
// Device sync - which remote paths (files or folders, per account) get
|
||||||
|
// mirrored locally by the native SyncWorker, and whether its periodic
|
||||||
|
// background runs are allowed on cellular (default Wi-Fi-only). See
|
||||||
|
// SyncEngine.kt/server.md.
|
||||||
|
List<String> _syncedPaths = [];
|
||||||
|
bool _syncEverything = false;
|
||||||
|
bool _syncOnCellular = false;
|
||||||
|
|
||||||
|
// Live device-sync status, pushed from SyncStatusBus.kt via
|
||||||
|
// SyncService.statusStream (see _subscribeToSyncStatus) - account-wide,
|
||||||
|
// not scoped to whatever folder is currently browsed.
|
||||||
|
bool _isSyncingNow = false;
|
||||||
|
Set<String> _syncingFileIds = {};
|
||||||
|
Set<String> _syncedFileIds = {};
|
||||||
|
List<SyncConflictInfo> _syncConflicts = [];
|
||||||
|
StreamSubscription<SyncStatusSnapshot>? _syncStatusSub;
|
||||||
|
|
||||||
// App lock (PIN/biometric via the device's own credential, not our own
|
// App lock (PIN/biometric via the device's own credential, not our own
|
||||||
// storage - see AppLockService). Global, not per-account: it guards
|
// storage - see AppLockService). Global, not per-account: it guards
|
||||||
// access to the app/its accounts, not any one account's content.
|
// access to the app/its accounts, not any one account's content.
|
||||||
@@ -140,9 +167,14 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
// (e.g. a search result landing on Files) - consumed and cleared by
|
// (e.g. a search result landing on Files) - consumed and cleared by
|
||||||
// MainShellView the next time it builds, not a persisted preference.
|
// MainShellView the next time it builds, not a persisted preference.
|
||||||
AppTab? _requestedTab;
|
AppTab? _requestedTab;
|
||||||
|
|
||||||
|
// Non-null while the app is acting as another app's GET_CONTENT picker
|
||||||
|
// (see PickIntentService/MainActivity.kt) - set at startup/onNewPickRequest
|
||||||
|
// in MainShellView, cleared once the pick is confirmed or cancelled.
|
||||||
|
PickRequest? _pickRequest;
|
||||||
|
bool _isDownloadingForPick = false;
|
||||||
List<String> _pathStack = ['/'];
|
List<String> _pathStack = ['/'];
|
||||||
bool _isGridView = false;
|
bool _isGridView = false;
|
||||||
bool _showFavoritesOnlyFiles = false;
|
|
||||||
bool _showFavoritesOnlyPhotos = false;
|
bool _showFavoritesOnlyPhotos = false;
|
||||||
StorageScope _storageScope = StorageScope.cloud;
|
StorageScope _storageScope = StorageScope.cloud;
|
||||||
FilesTypeFilter _filesTypeFilter = FilesTypeFilter.all;
|
FilesTypeFilter _filesTypeFilter = FilesTypeFilter.all;
|
||||||
@@ -187,6 +219,26 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
bool _isMediaLoading = false;
|
bool _isMediaLoading = false;
|
||||||
String? _mediaErrorMessage;
|
String? _mediaErrorMessage;
|
||||||
|
|
||||||
|
// All-account favorites (the Favorites tab) - same idea as [_allMedia]:
|
||||||
|
// a strict filter (only favorited items) but an account-wide *scope*, so
|
||||||
|
// a favorited item several folders deep still shows up regardless of
|
||||||
|
// whether its parent folders are themselves favorited - which is exactly
|
||||||
|
// why this is its own tab (and its own fetch/loading state, kept
|
||||||
|
// separate from Files' own [_isLoading]/[_errorMessage] since both tabs
|
||||||
|
// are simultaneously mounted in MainShellView's IndexedStack and would
|
||||||
|
// otherwise bleed loading/error state into each other) rather than a
|
||||||
|
// filter toggle scoped to whatever folder the Files tab happens to be
|
||||||
|
// browsing.
|
||||||
|
List<NextcloudItem> _allFavorites = [];
|
||||||
|
bool _isFavoritesLoading = false;
|
||||||
|
String? _favoritesErrorMessage;
|
||||||
|
// True once fetchAllFavorites has run at least once (i.e. the Favorites
|
||||||
|
// tab has been visited) - delete/rename/move/copy re-sync [_allFavorites]
|
||||||
|
// afterward, but only when it's actually been loaded, so those actions
|
||||||
|
// don't pay for an extra network round-trip on every Files/Photos edit
|
||||||
|
// for an account that's never opened the Favorites tab this session.
|
||||||
|
bool _favoritesEverFetched = false;
|
||||||
|
|
||||||
// Trash state — kept separate from the regular folder-loading/error state
|
// Trash state — kept separate from the regular folder-loading/error state
|
||||||
// above so a trash-fetch failure can't bleed a stale error into Files.
|
// above so a trash-fetch failure can't bleed a stale error into Files.
|
||||||
List<NextcloudItem> _trashItems = [];
|
List<NextcloudItem> _trashItems = [];
|
||||||
@@ -225,6 +277,7 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
ServerProvider() {
|
ServerProvider() {
|
||||||
WidgetsBinding.instance.addObserver(this);
|
WidgetsBinding.instance.addObserver(this);
|
||||||
_init();
|
_init();
|
||||||
|
_subscribeToSyncStatus();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _init() async {
|
Future<void> _init() async {
|
||||||
@@ -235,6 +288,29 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
await Future.wait([_loadPreferences(), _restoreSession()]);
|
await Future.wait([_loadPreferences(), _restoreSession()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Live device-sync status for the rest of the app's lifetime (not
|
||||||
|
/// re-subscribed per account switch - each event carries its own
|
||||||
|
/// `accountId`, so events for an account that isn't currently active are
|
||||||
|
/// just ignored below). Seeded once via a one-shot snapshot right after
|
||||||
|
/// every successful login/account-switch instead (see
|
||||||
|
/// `_applyCredentialsForAccount`), since events only arrive on change.
|
||||||
|
void _subscribeToSyncStatus() {
|
||||||
|
_syncStatusSub = SyncService.statusStream.listen((snapshot) {
|
||||||
|
_applySyncStatus(snapshot);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void _applySyncStatus(SyncStatusSnapshot snapshot) {
|
||||||
|
if (snapshot.accountId != null && snapshot.accountId != _activeAccountId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_isSyncingNow = snapshot.syncing;
|
||||||
|
_syncingFileIds = snapshot.syncingFileIds;
|
||||||
|
_syncedFileIds = snapshot.syncedFileIds;
|
||||||
|
_syncConflicts = snapshot.conflicts;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
/// Starts/stops the periodic folder-listing refresh as the app leaves and
|
/// Starts/stops the periodic folder-listing refresh as the app leaves and
|
||||||
/// returns to the foreground - only relevant under [CachePolicy.interval].
|
/// returns to the foreground - only relevant under [CachePolicy.interval].
|
||||||
/// Also re-locks the app on backgrounding when login lock is set up - a
|
/// Also re-locks the app on backgrounding when login lock is set up - a
|
||||||
@@ -293,9 +369,103 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
bool get lockHiddenFiles => _lockHiddenFiles;
|
bool get lockHiddenFiles => _lockHiddenFiles;
|
||||||
bool get needsUnlock => _loginLockEnabled && !_isUnlocked;
|
bool get needsUnlock => _loginLockEnabled && !_isUnlocked;
|
||||||
|
|
||||||
|
List<String> get syncedPaths => List.unmodifiable(_syncedPaths);
|
||||||
|
bool get syncEverything => _syncEverything;
|
||||||
|
bool get syncOnCellular => _syncOnCellular;
|
||||||
|
|
||||||
|
bool get isSyncingNow => _isSyncingNow;
|
||||||
|
List<SyncConflictInfo> get syncConflicts => List.unmodifiable(_syncConflicts);
|
||||||
|
|
||||||
|
SyncHeaderStatus get syncHeaderStatus {
|
||||||
|
if (_syncConflicts.isNotEmpty) return SyncHeaderStatus.alert;
|
||||||
|
if (_isSyncingNow) return SyncHeaderStatus.syncing;
|
||||||
|
if (!_syncEverything && _syncedPaths.isEmpty) return SyncHeaderStatus.off;
|
||||||
|
return SyncHeaderStatus.done;
|
||||||
|
}
|
||||||
|
|
||||||
|
SyncItemStatus syncStatusFor(NextcloudItem item) {
|
||||||
|
if (_syncingFileIds.contains(item.id)) return SyncItemStatus.syncing;
|
||||||
|
if (_syncConflicts.any((c) => c.fileId == item.id)) {
|
||||||
|
return SyncItemStatus.conflict;
|
||||||
|
}
|
||||||
|
if (_syncedFileIds.contains(item.id)) return SyncItemStatus.synced;
|
||||||
|
return SyncItemStatus.none;
|
||||||
|
}
|
||||||
|
|
||||||
String get currentFolderPath => _currentFolderPath;
|
String get currentFolderPath => _currentFolderPath;
|
||||||
AppTab? get requestedTab => _requestedTab;
|
AppTab? get requestedTab => _requestedTab;
|
||||||
|
|
||||||
|
PickRequest? get pickRequest => _pickRequest;
|
||||||
|
bool get isPicking => _pickRequest != null;
|
||||||
|
bool get isDownloadingForPick => _isDownloadingForPick;
|
||||||
|
|
||||||
|
/// Whether [item] can be handed back to the app that's currently picking
|
||||||
|
/// - always true for folders (still browsable), mime-filtered for files.
|
||||||
|
bool itemMatchesPickFilter(NextcloudItem item) {
|
||||||
|
if (item.isFolder) return true;
|
||||||
|
final request = _pickRequest;
|
||||||
|
return request == null || request.matches(item.mimeType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called once (from MainShellView) as soon as a pick request is known -
|
||||||
|
/// either the cold-start request or one that arrived via onNewPickRequest
|
||||||
|
/// while already running.
|
||||||
|
void setPickRequest(PickRequest request) {
|
||||||
|
_pickRequest = request;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Downloads each selected item to a scratch cache folder, then hands the
|
||||||
|
/// local paths back to the caller through PickIntentService, which closes
|
||||||
|
/// the picker Activity on success. Left in [_pickRequest] (i.e. picking
|
||||||
|
/// mode stays visually active) if the download fails partway, so the user
|
||||||
|
/// can see the error and retry rather than the screen finishing under
|
||||||
|
/// them with nothing returned to the caller.
|
||||||
|
Future<bool> confirmPick(List<NextcloudItem> items) async {
|
||||||
|
final service = _service;
|
||||||
|
if (_pickRequest == null || service == null || items.isEmpty) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_isDownloadingForPick = true;
|
||||||
|
notifyListeners();
|
||||||
|
try {
|
||||||
|
final tempDir = await getTemporaryDirectory();
|
||||||
|
final pickDir = Directory(p.join(tempDir.path, 'picker'));
|
||||||
|
final localPaths = <String>[];
|
||||||
|
final mimeTypes = <String>[];
|
||||||
|
for (final item in items) {
|
||||||
|
// Each item gets its own subfolder (keyed by id, not smashed into
|
||||||
|
// the filename) so two different items can share a plain file
|
||||||
|
// name without colliding, while the file on disk - and therefore
|
||||||
|
// the display name the caller sees via the content:// Uri
|
||||||
|
// MainActivity.kt hands back - stays exactly `item.name`.
|
||||||
|
final itemDir = Directory(p.join(pickDir.path, item.id));
|
||||||
|
await itemDir.create(recursive: true);
|
||||||
|
final localPath = p.join(itemDir.path, item.name);
|
||||||
|
await service.downloadToFile(item.path, localPath);
|
||||||
|
localPaths.add(localPath);
|
||||||
|
mimeTypes.add(item.mimeType ?? 'application/octet-stream');
|
||||||
|
}
|
||||||
|
await PickIntentService.finishPick(localPaths, mimeTypes);
|
||||||
|
_pickRequest = null;
|
||||||
|
return true;
|
||||||
|
} catch (_) {
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
_isDownloadingForPick = false;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Backs out of picking mode entirely, telling the caller nothing was
|
||||||
|
/// picked and closing the picker Activity.
|
||||||
|
Future<void> cancelPick() async {
|
||||||
|
if (_pickRequest == null) return;
|
||||||
|
_pickRequest = null;
|
||||||
|
notifyListeners();
|
||||||
|
await PickIntentService.cancelPick();
|
||||||
|
}
|
||||||
|
|
||||||
/// Asks the shell to switch its active bottom-nav tab to [tab] - e.g. so
|
/// Asks the shell to switch its active bottom-nav tab to [tab] - e.g. so
|
||||||
/// tapping a search result lands the user on the Files tab even if they
|
/// tapping a search result lands the user on the Files tab even if they
|
||||||
/// opened search from somewhere else.
|
/// opened search from somewhere else.
|
||||||
@@ -311,7 +481,6 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
|
|
||||||
List<String> get pathStack => _pathStack;
|
List<String> get pathStack => _pathStack;
|
||||||
bool get isGridView => _isGridView;
|
bool get isGridView => _isGridView;
|
||||||
bool get showFavoritesOnlyFiles => _showFavoritesOnlyFiles;
|
|
||||||
bool get showFavoritesOnlyPhotos => _showFavoritesOnlyPhotos;
|
bool get showFavoritesOnlyPhotos => _showFavoritesOnlyPhotos;
|
||||||
StorageScope get storageScope => _storageScope;
|
StorageScope get storageScope => _storageScope;
|
||||||
FilesTypeFilter get filesTypeFilter => _filesTypeFilter;
|
FilesTypeFilter get filesTypeFilter => _filesTypeFilter;
|
||||||
@@ -364,10 +533,11 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
.any((segment) => segment.startsWith('.'));
|
.any((segment) => segment.startsWith('.'));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Applies the shared favorites-only/hidden-files/storage-scope toggles,
|
/// Applies the shared favorites-only/hidden-files/storage-scope toggles.
|
||||||
/// used by both [items] and [photoItems]. `showFavoritesOnly`/`showHidden`
|
/// `showFavoritesOnly` is effectively Photos-only now (`items`/
|
||||||
/// are passed in separately since Files and Photos each have their own
|
/// `favoriteItems` both always pass `false` - see their own doc
|
||||||
/// independent favorites-only and hidden-files toggles.
|
/// comments for why); kept as a parameter here since `photoItems` still
|
||||||
|
/// has its own independent favorites-only toggle.
|
||||||
List<NextcloudItem> _applyCommonFilters(
|
List<NextcloudItem> _applyCommonFilters(
|
||||||
List<NextcloudItem> source, {
|
List<NextcloudItem> source, {
|
||||||
required bool showFavoritesOnly,
|
required bool showFavoritesOnly,
|
||||||
@@ -390,10 +560,31 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
return filtered;
|
return filtered;
|
||||||
}
|
}
|
||||||
|
|
||||||
List<NextcloudItem> get items {
|
List<NextcloudItem> get items => applyFilesDisplayPrefs(_items);
|
||||||
|
|
||||||
|
/// The Favorites tab's content - every favorited item account-wide (see
|
||||||
|
/// `fetchAllFavorites`), run through the exact same hidden/type-filter/
|
||||||
|
/// sort/storage-scope display prefs as the Files tab (deliberately
|
||||||
|
/// shared rather than a separate parallel settings dimension, the same
|
||||||
|
/// way the Move/Copy destination picker reuses them). No favorites
|
||||||
|
/// filter needed here - the source list is already all-favorites.
|
||||||
|
List<NextcloudItem> get favoriteItems =>
|
||||||
|
applyFilesDisplayPrefs(_allFavorites);
|
||||||
|
|
||||||
|
/// Applies the Files tab's current sort/filter display prefs (hidden,
|
||||||
|
/// type filter, storage scope, sort field/direction) to an arbitrary raw
|
||||||
|
/// item list - factored out of the [items] getter so both the Favorites
|
||||||
|
/// tab ([favoriteItems]) and the Move/Copy destination picker (which
|
||||||
|
/// fetches its own listings via [fetchFolderListing] rather than reading
|
||||||
|
/// [items] itself - see that method's doc comment) can render with the
|
||||||
|
/// exact same controls/behavior as the Files tab without duplicating
|
||||||
|
/// this logic.
|
||||||
|
List<NextcloudItem> applyFilesDisplayPrefs(List<NextcloudItem> rawItems) {
|
||||||
var filtered = _applyCommonFilters(
|
var filtered = _applyCommonFilters(
|
||||||
_items,
|
rawItems,
|
||||||
showFavoritesOnly: _showFavoritesOnlyFiles,
|
// Files itself no longer filters by favorite - that's the dedicated
|
||||||
|
// Favorites tab's job now (see `favoriteItems`/`fetchAllFavorites`).
|
||||||
|
showFavoritesOnly: false,
|
||||||
showHidden: _showHiddenFiles,
|
showHidden: _showHiddenFiles,
|
||||||
);
|
);
|
||||||
switch (_filesTypeFilter) {
|
switch (_filesTypeFilter) {
|
||||||
@@ -429,6 +620,8 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
|
|
||||||
bool get isMediaLoading => _isMediaLoading;
|
bool get isMediaLoading => _isMediaLoading;
|
||||||
String? get mediaErrorMessage => _mediaErrorMessage;
|
String? get mediaErrorMessage => _mediaErrorMessage;
|
||||||
|
bool get isFavoritesLoading => _isFavoritesLoading;
|
||||||
|
String? get favoritesErrorMessage => _favoritesErrorMessage;
|
||||||
|
|
||||||
NextcloudUserQuota? get quota => _quota;
|
NextcloudUserQuota? get quota => _quota;
|
||||||
List<NextcloudActivity> get activities => _activities;
|
List<NextcloudActivity> get activities => _activities;
|
||||||
@@ -497,6 +690,7 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
prefs.getBool(_prefLockAccountSwitching) ?? _lockAccountSwitching;
|
prefs.getBool(_prefLockAccountSwitching) ?? _lockAccountSwitching;
|
||||||
_lockHiddenFiles =
|
_lockHiddenFiles =
|
||||||
prefs.getBool(_prefLockHiddenFiles) ?? _lockHiddenFiles;
|
prefs.getBool(_prefLockHiddenFiles) ?? _lockHiddenFiles;
|
||||||
|
_syncOnCellular = prefs.getBool(_prefSyncOnCellular) ?? _syncOnCellular;
|
||||||
_applyAccountPrefs(prefs, _activeAccountId);
|
_applyAccountPrefs(prefs, _activeAccountId);
|
||||||
|
|
||||||
final savedOrderNames = prefs.getStringList(_prefTabOrder);
|
final savedOrderNames = prefs.getStringList(_prefTabOrder);
|
||||||
@@ -576,7 +770,6 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
|
|
||||||
if (accountId == null) {
|
if (accountId == null) {
|
||||||
_isGridView = false;
|
_isGridView = false;
|
||||||
_showFavoritesOnlyFiles = false;
|
|
||||||
_showFavoritesOnlyPhotos = false;
|
_showFavoritesOnlyPhotos = false;
|
||||||
_storageScope = StorageScope.cloud;
|
_storageScope = StorageScope.cloud;
|
||||||
_filesTypeFilter = FilesTypeFilter.all;
|
_filesTypeFilter = FilesTypeFilter.all;
|
||||||
@@ -586,14 +779,14 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
_photosSortAscending = true;
|
_photosSortAscending = true;
|
||||||
_cachePolicy = CachePolicy.never;
|
_cachePolicy = CachePolicy.never;
|
||||||
_cacheIntervalMinutes = 5;
|
_cacheIntervalMinutes = 5;
|
||||||
|
_syncedPaths = [];
|
||||||
|
_syncEverything = false;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
String k(String base) => _accountStore.accountPrefKey(accountId, base);
|
String k(String base) => _accountStore.accountPrefKey(accountId, base);
|
||||||
|
|
||||||
_isGridView = prefs.getBool(k(_prefGridView)) ?? false;
|
_isGridView = prefs.getBool(k(_prefGridView)) ?? false;
|
||||||
_showFavoritesOnlyFiles =
|
|
||||||
prefs.getBool(k(_prefShowFavoritesOnlyFiles)) ?? false;
|
|
||||||
_showFavoritesOnlyPhotos =
|
_showFavoritesOnlyPhotos =
|
||||||
prefs.getBool(k(_prefShowFavoritesOnlyPhotos)) ?? false;
|
prefs.getBool(k(_prefShowFavoritesOnlyPhotos)) ?? false;
|
||||||
|
|
||||||
@@ -646,6 +839,19 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
orElse: () => CachePolicy.never,
|
orElse: () => CachePolicy.never,
|
||||||
);
|
);
|
||||||
_cacheIntervalMinutes = prefs.getInt(k(_prefCacheIntervalMinutes)) ?? 5;
|
_cacheIntervalMinutes = prefs.getInt(k(_prefCacheIntervalMinutes)) ?? 5;
|
||||||
|
|
||||||
|
final syncedFoldersJson = prefs.getString(k(_prefSyncedFolders));
|
||||||
|
if (syncedFoldersJson != null) {
|
||||||
|
try {
|
||||||
|
_syncedPaths = (jsonDecode(syncedFoldersJson) as List).cast<String>();
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('[ServerProvider] Synced folders restore failed: $e');
|
||||||
|
_syncedPaths = [];
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
_syncedPaths = [];
|
||||||
|
}
|
||||||
|
_syncEverything = prefs.getBool(k(_prefSyncEverything)) ?? false;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Verifies [appPassword] for [account] and, on success, makes it the
|
/// Verifies [appPassword] for [account] and, on success, makes it the
|
||||||
@@ -685,15 +891,25 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
if (gen != _sessionGeneration) return false;
|
if (gen != _sessionGeneration) return false;
|
||||||
_isLoading = false;
|
_isLoading = false;
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
|
unawaited(SyncService.reschedule(this));
|
||||||
|
unawaited(SyncService.getStatus().then(_applySyncStatus));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (gen != _sessionGeneration) return false;
|
if (gen != _sessionGeneration) return false;
|
||||||
_errorMessage = e.toString().replaceAll('Exception: ', '');
|
_errorMessage = e.toString().replaceAll('Exception: ', '');
|
||||||
// The stored app password for this account no longer works - drop it
|
// Only drop the stored password on an actual auth rejection (401) -
|
||||||
// so it doesn't keep silently failing on every future restore/switch.
|
// NextcloudService.testConnection also throws for network-level
|
||||||
|
// failures (DNS, timeout, unreachable host), and those are transient:
|
||||||
|
// deleting a still-valid password on a dropped connection would
|
||||||
|
// permanently log the account out with no way back in short of
|
||||||
|
// Login Flow v2 again, since _activeAccountId is never cleared and
|
||||||
|
// switchAccount() no-ops when asked to "switch" to the account
|
||||||
|
// that's already (nominally) active.
|
||||||
|
if (_errorMessage?.contains('401') == true) {
|
||||||
await _accountStore.deletePassword(account.id);
|
await _accountStore.deletePassword(account.id);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (gen != _sessionGeneration) return false;
|
if (gen != _sessionGeneration) return false;
|
||||||
_isLoggedIn = false;
|
_isLoggedIn = false;
|
||||||
@@ -908,15 +1124,24 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
unawaited(fetchRecent());
|
unawaited(fetchRecent());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Switches to an already-saved account. No-op if it's already active or
|
/// Switches to an already-saved account. No-op (returns true) if it's
|
||||||
/// unknown. Gated behind login lock when [lockAccountSwitching] is on.
|
/// already active and logged in; no-op (returns false) if unknown - but
|
||||||
Future<void> switchAccount(String accountId) async {
|
/// if [accountId] is nominally "active" while [isLoggedIn] is false (a
|
||||||
if (accountId == _activeAccountId) return;
|
/// session-restore that failed, e.g. transient network trouble at cold
|
||||||
if (!_accounts.any((a) => a.id == accountId)) return;
|
/// start), this still retries rather than no-op, since that's exactly the
|
||||||
|
/// case LoginView's "Continue as" tile exists to recover from. Gated
|
||||||
|
/// behind login lock when [lockAccountSwitching] is on. Returns whether
|
||||||
|
/// the account ended up logged in, so callers (LoginView's saved-account
|
||||||
|
/// tile) can surface a failure - e.g. a stored app password that no
|
||||||
|
/// longer works and needs the account removed/re-added.
|
||||||
|
Future<bool> switchAccount(String accountId) async {
|
||||||
|
if (accountId == _activeAccountId && _isLoggedIn) return true;
|
||||||
|
if (!_accounts.any((a) => a.id == accountId)) return false;
|
||||||
if (!await _passGate(_lockAccountSwitching, 'Unlock to switch accounts')) {
|
if (!await _passGate(_lockAccountSwitching, 'Unlock to switch accounts')) {
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
await _activateAccount(accountId);
|
await _activateAccount(accountId);
|
||||||
|
return _isLoggedIn;
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<SavedAccount?> _cycleAccount(int direction) async {
|
Future<SavedAccount?> _cycleAccount(int direction) async {
|
||||||
@@ -993,7 +1218,12 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
final prefs = await _prefsFuture;
|
final prefs = await _prefsFuture;
|
||||||
await _accountStore.saveActiveAccountId(prefs, null);
|
await _accountStore.saveActiveAccountId(prefs, null);
|
||||||
_applyAccountPrefs(prefs, null);
|
_applyAccountPrefs(prefs, null);
|
||||||
|
_isSyncingNow = false;
|
||||||
|
_syncingFileIds = {};
|
||||||
|
_syncedFileIds = {};
|
||||||
|
_syncConflicts = [];
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
|
unawaited(SyncService.cancel());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Ends the active session but keeps this account saved - unlike
|
/// Ends the active session but keeps this account saved - unlike
|
||||||
@@ -1097,6 +1327,48 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Loads every favorited item across the whole account for the Favorites
|
||||||
|
/// tab - see [_allFavorites]'s doc comment for why this is a separate
|
||||||
|
/// account-wide fetch rather than a filter over the currently browsed
|
||||||
|
/// folder's [_items].
|
||||||
|
Future<void> fetchAllFavorites() async {
|
||||||
|
if (!_isLoggedIn || _service == null) return;
|
||||||
|
final gen = _sessionGeneration;
|
||||||
|
_favoritesEverFetched = true;
|
||||||
|
|
||||||
|
_isFavoritesLoading = true;
|
||||||
|
_favoritesErrorMessage = null;
|
||||||
|
notifyListeners();
|
||||||
|
|
||||||
|
try {
|
||||||
|
final favorites = await _service!.fetchFavorites();
|
||||||
|
if (gen != _sessionGeneration) return;
|
||||||
|
_allFavorites = favorites;
|
||||||
|
debugPrint('[ServerProvider] Loaded ${_allFavorites.length} favorites');
|
||||||
|
} catch (e) {
|
||||||
|
if (gen != _sessionGeneration) return;
|
||||||
|
debugPrint('[ServerProvider] Error fetching favorites: $e');
|
||||||
|
_favoritesErrorMessage = e.toString().replaceAll('Exception: ', '');
|
||||||
|
} finally {
|
||||||
|
if (gen == _sessionGeneration) {
|
||||||
|
_isFavoritesLoading = false;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-syncs [_allFavorites] after a delete/rename/move/copy elsewhere in
|
||||||
|
/// the app (Files, Photos, or Favorites itself) - those operations don't
|
||||||
|
/// know how to patch [_allFavorites] in place (a move changes an item's
|
||||||
|
/// path; WebDAV COPY's handling of custom properties like `oc:favorite`
|
||||||
|
/// isn't reliable enough to assume the copy is still favorited), so this
|
||||||
|
/// just refetches - but only if Favorites has actually been loaded this
|
||||||
|
/// session, so an account that never opens that tab doesn't pay for an
|
||||||
|
/// extra request on every edit.
|
||||||
|
Future<void> _syncFavoritesIfLoaded() {
|
||||||
|
return _favoritesEverFetched ? fetchAllFavorites() : Future.value();
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> navigateToFolder(String path) async {
|
Future<void> navigateToFolder(String path) async {
|
||||||
_pathStack.add(path);
|
_pathStack.add(path);
|
||||||
await _navigateTo(path);
|
await _navigateTo(path);
|
||||||
@@ -1185,15 +1457,6 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
_persistAccountPref(_prefGridView, (p, key) => p.setBool(key, value));
|
_persistAccountPref(_prefGridView, (p, key) => p.setBool(key, value));
|
||||||
}
|
}
|
||||||
|
|
||||||
void toggleFavoritesFilterFiles() {
|
|
||||||
_showFavoritesOnlyFiles = !_showFavoritesOnlyFiles;
|
|
||||||
notifyListeners();
|
|
||||||
_persistAccountPref(
|
|
||||||
_prefShowFavoritesOnlyFiles,
|
|
||||||
(p, key) => p.setBool(key, _showFavoritesOnlyFiles),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
void toggleFavoritesFilterPhotos() {
|
void toggleFavoritesFilterPhotos() {
|
||||||
_showFavoritesOnlyPhotos = !_showFavoritesOnlyPhotos;
|
_showFavoritesOnlyPhotos = !_showFavoritesOnlyPhotos;
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
@@ -1302,6 +1565,93 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
_persistFolderSort();
|
_persistFolderSort();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void _persistSyncedPaths() {
|
||||||
|
_persistAccountPref(
|
||||||
|
_prefSyncedFolders,
|
||||||
|
(p, key) => p.setString(key, jsonEncode(_syncedPaths)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isPathSynced(String path) => _syncedPaths.contains(path);
|
||||||
|
|
||||||
|
void addSyncedPath(String path) {
|
||||||
|
if (_syncedPaths.contains(path)) return;
|
||||||
|
_syncedPaths = [..._syncedPaths, path];
|
||||||
|
notifyListeners();
|
||||||
|
_persistSyncedPaths();
|
||||||
|
unawaited(SyncService.reschedule(this));
|
||||||
|
}
|
||||||
|
|
||||||
|
void removeSyncedPath(String path) {
|
||||||
|
if (!_syncedPaths.contains(path)) return;
|
||||||
|
_syncedPaths = _syncedPaths.where((f) => f != path).toList();
|
||||||
|
notifyListeners();
|
||||||
|
_persistSyncedPaths();
|
||||||
|
unawaited(SyncService.reschedule(this));
|
||||||
|
}
|
||||||
|
|
||||||
|
void setSyncEverything(bool value) {
|
||||||
|
if (_syncEverything == value) return;
|
||||||
|
_syncEverything = value;
|
||||||
|
notifyListeners();
|
||||||
|
_persistAccountPref(_prefSyncEverything, (p, key) => p.setBool(key, value));
|
||||||
|
unawaited(SyncService.reschedule(this));
|
||||||
|
}
|
||||||
|
|
||||||
|
void setSyncOnCellular(bool value) {
|
||||||
|
if (_syncOnCellular == value) return;
|
||||||
|
_syncOnCellular = value;
|
||||||
|
notifyListeners();
|
||||||
|
_prefsFuture.then((p) => p.setBool(_prefSyncOnCellular, value));
|
||||||
|
unawaited(SyncService.reschedule(this));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// In-app conflict resolution (the sync header's "Keep local"/"Use
|
||||||
|
/// server" buttons) - see `SyncService.resolveConflict`'s doc comment
|
||||||
|
/// for why this shares the exact same native path the notification
|
||||||
|
/// actions use.
|
||||||
|
Future<void> resolveSyncConflict(
|
||||||
|
SyncConflictInfo conflict, {
|
||||||
|
required bool useLocal,
|
||||||
|
}) {
|
||||||
|
return SyncService.resolveConflict(
|
||||||
|
this,
|
||||||
|
conflict,
|
||||||
|
useLocal ? 'local' : 'server',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The local mirror path for [item] if it falls under a synced folder
|
||||||
|
/// *and* has actually been synced down already - a pure function of the
|
||||||
|
/// remote path once a folder's marked synced (mirrors
|
||||||
|
/// `SyncEngine.kt#syncRoot`'s `<externalFilesDir>/sync/<accountId>/...`
|
||||||
|
/// layout exactly), so this never needs to read the native sync-state
|
||||||
|
/// SharedPreferences from Dart. Callers (Share/Download) use this to
|
||||||
|
/// skip a fresh WebDAV fetch when a local copy already exists.
|
||||||
|
Future<String?> localSyncedFilePath(NextcloudItem item) async {
|
||||||
|
final id = activeAccountId;
|
||||||
|
if (id == null) return null;
|
||||||
|
final itemPath = item.path.endsWith('/')
|
||||||
|
? item.path.substring(0, item.path.length - 1)
|
||||||
|
: item.path;
|
||||||
|
final isSynced =
|
||||||
|
_syncEverything ||
|
||||||
|
_syncedPaths.any((folder) {
|
||||||
|
final f = folder.endsWith('/')
|
||||||
|
? folder.substring(0, folder.length - 1)
|
||||||
|
: folder;
|
||||||
|
return itemPath == f || itemPath.startsWith('$f/');
|
||||||
|
});
|
||||||
|
if (!isSynced) return null;
|
||||||
|
final base = await getExternalStorageDirectory();
|
||||||
|
if (base == null) return null;
|
||||||
|
final relPath = item.path.startsWith('/')
|
||||||
|
? item.path.substring(1)
|
||||||
|
: item.path;
|
||||||
|
final file = File(p.join(base.path, 'sync', id, relPath));
|
||||||
|
return file.existsSync() ? file.path : null;
|
||||||
|
}
|
||||||
|
|
||||||
void setTabOrder(List<AppTab> order) {
|
void setTabOrder(List<AppTab> order) {
|
||||||
_tabOrder = order;
|
_tabOrder = order;
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
@@ -1403,30 +1753,13 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
_startCacheRefreshTimerIfNeeded();
|
_startCacheRefreshTimerIfNeeded();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<bool> uploadFileFromPath(
|
|
||||||
String name,
|
|
||||||
String localFilePath, {
|
|
||||||
void Function(int sent, int total)? onProgress,
|
|
||||||
}) async {
|
|
||||||
if (_service == null) return false;
|
|
||||||
final success = await _service!.uploadFileFromPath(
|
|
||||||
_currentFolderPath,
|
|
||||||
name,
|
|
||||||
localFilePath,
|
|
||||||
onProgress: onProgress,
|
|
||||||
);
|
|
||||||
if (success) {
|
|
||||||
await refreshData();
|
|
||||||
}
|
|
||||||
return success;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<bool> deleteItem(String itemPath) async {
|
Future<bool> deleteItem(String itemPath) async {
|
||||||
if (_service == null) return false;
|
if (_service == null) return false;
|
||||||
final success = await _service!.deleteItem(itemPath);
|
final success = await _service!.deleteItem(itemPath);
|
||||||
if (success) {
|
if (success) {
|
||||||
_allMedia = _allMedia.where((i) => i.path != itemPath).toList();
|
_allMedia = _allMedia.where((i) => i.path != itemPath).toList();
|
||||||
await refreshData();
|
await refreshData();
|
||||||
|
await _syncFavoritesIfLoaded();
|
||||||
}
|
}
|
||||||
return success;
|
return success;
|
||||||
}
|
}
|
||||||
@@ -1436,10 +1769,178 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
final success = await _service!.renameItem(item.path, newName);
|
final success = await _service!.renameItem(item.path, newName);
|
||||||
if (success) {
|
if (success) {
|
||||||
await refreshData();
|
await refreshData();
|
||||||
|
await _syncFavoritesIfLoaded();
|
||||||
}
|
}
|
||||||
return success;
|
return success;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A destination-picker-only fetch: the current folder listing state
|
||||||
|
/// (`items`/`currentFolderPath`/`pathStack`/`_directoryCache`) belongs to
|
||||||
|
/// whichever tab is actively browsing (Files), so the Move/Copy
|
||||||
|
/// destination picker deliberately doesn't touch any of it - it fetches
|
||||||
|
/// listings for its own local navigation state through this instead,
|
||||||
|
/// mirroring `searchFiles`'s identical stateless-pass-through shape.
|
||||||
|
Future<List<NextcloudItem>> fetchFolderListing(String path) {
|
||||||
|
return _service?.fetchDirectory(path) ?? Future.value([]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True if [destFolderPath] is [folderPath] itself or one of its own
|
||||||
|
/// descendants - moving/copying a folder into itself (or a subfolder of
|
||||||
|
/// itself) is nonsensical and rejected client-side rather than left to
|
||||||
|
/// the server to (maybe) reject.
|
||||||
|
bool _isSelfOrDescendant(String destFolderPath, String folderPath) {
|
||||||
|
final dest = destFolderPath.endsWith('/')
|
||||||
|
? destFolderPath
|
||||||
|
: '$destFolderPath/';
|
||||||
|
final folder = folderPath.endsWith('/') ? folderPath : '$folderPath/';
|
||||||
|
return dest == folder || dest.startsWith(folder);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<MoveCopyResult> _moveOrCopyItems(
|
||||||
|
List<NextcloudItem> items,
|
||||||
|
String destFolderPath, {
|
||||||
|
required bool copy,
|
||||||
|
}) async {
|
||||||
|
if (_service == null || items.isEmpty) return const MoveCopyResult();
|
||||||
|
for (final item in items) {
|
||||||
|
if (item.isFolder && _isSelfOrDescendant(destFolderPath, item.path)) {
|
||||||
|
return const MoveCopyResult(
|
||||||
|
blockedReason:
|
||||||
|
"Can't move a folder into itself or one of its own subfolders",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var succeeded = 0;
|
||||||
|
var failed = 0;
|
||||||
|
final conflicts = <MoveCopyConflict>[];
|
||||||
|
for (final item in items) {
|
||||||
|
final status = copy
|
||||||
|
? await _service!.copyItem(item.path, destFolderPath)
|
||||||
|
: await _service!.moveItem(item.path, destFolderPath);
|
||||||
|
if (status == 201 || status == 204) {
|
||||||
|
succeeded++;
|
||||||
|
} else if (status == 412) {
|
||||||
|
conflicts.add(MoveCopyConflict(item));
|
||||||
|
} else {
|
||||||
|
failed++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (succeeded > 0) {
|
||||||
|
_directoryCache.clear();
|
||||||
|
await refreshData();
|
||||||
|
await _syncFavoritesIfLoaded();
|
||||||
|
}
|
||||||
|
return MoveCopyResult(
|
||||||
|
succeeded: succeeded,
|
||||||
|
conflicts: conflicts,
|
||||||
|
failed: failed,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves every item in [items] into [destFolderPath], keeping each
|
||||||
|
/// item's own filename. Items that would collide with something already
|
||||||
|
/// there come back in [MoveCopyResult.conflicts] rather than failing
|
||||||
|
/// outright - resolve those with [resolveConflicts].
|
||||||
|
Future<MoveCopyResult> moveItems(
|
||||||
|
List<NextcloudItem> items,
|
||||||
|
String destFolderPath,
|
||||||
|
) {
|
||||||
|
return _moveOrCopyItems(items, destFolderPath, copy: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Same as [moveItems] but duplicates rather than relocates.
|
||||||
|
Future<MoveCopyResult> copyItems(
|
||||||
|
List<NextcloudItem> items,
|
||||||
|
String destFolderPath,
|
||||||
|
) {
|
||||||
|
return _moveOrCopyItems(items, destFolderPath, copy: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finds the first `name (n).ext` not already in [existing] - `existing`
|
||||||
|
/// is mutated as names are claimed, so a batch of "keep both" resolutions
|
||||||
|
/// never picks the same generated name twice.
|
||||||
|
String _nextAvailableName(String name, Set<String> existing) {
|
||||||
|
if (!existing.contains(name)) return name;
|
||||||
|
final dotIndex = name.lastIndexOf('.');
|
||||||
|
final hasExtension = dotIndex > 0 && dotIndex < name.length - 1;
|
||||||
|
final base = hasExtension ? name.substring(0, dotIndex) : name;
|
||||||
|
final ext = hasExtension ? name.substring(dotIndex) : '';
|
||||||
|
var n = 2;
|
||||||
|
while (existing.contains('$base ($n)$ext')) {
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
return '$base ($n)$ext';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves a previous [moveItems]/[copyItems] call's conflicts per
|
||||||
|
/// [choices] (keyed by `item.id`): overwrite the existing item, keep
|
||||||
|
/// both (renamed against a fresh listing of [destFolderPath] so two
|
||||||
|
/// "keep both" picks in the same batch can't collide with each other),
|
||||||
|
/// or skip (left untouched at the source).
|
||||||
|
Future<MoveCopyResult> resolveConflicts(
|
||||||
|
List<MoveCopyConflict> conflicts,
|
||||||
|
String destFolderPath, {
|
||||||
|
required bool copy,
|
||||||
|
required Map<String, ConflictChoice> choices,
|
||||||
|
}) async {
|
||||||
|
if (_service == null || conflicts.isEmpty) return const MoveCopyResult();
|
||||||
|
|
||||||
|
final needsKeepBoth = conflicts.any(
|
||||||
|
(c) => choices[c.item.id] == ConflictChoice.keepBoth,
|
||||||
|
);
|
||||||
|
final existingNames = needsKeepBoth
|
||||||
|
? (await fetchFolderListing(destFolderPath)).map((i) => i.name).toSet()
|
||||||
|
: <String>{};
|
||||||
|
|
||||||
|
var succeeded = 0;
|
||||||
|
var failed = 0;
|
||||||
|
for (final conflict in conflicts) {
|
||||||
|
final choice = choices[conflict.item.id] ?? ConflictChoice.skip;
|
||||||
|
if (choice == ConflictChoice.skip) continue;
|
||||||
|
|
||||||
|
final int status;
|
||||||
|
if (choice == ConflictChoice.overwrite) {
|
||||||
|
status = copy
|
||||||
|
? await _service!.copyItem(
|
||||||
|
conflict.item.path,
|
||||||
|
destFolderPath,
|
||||||
|
overwrite: true,
|
||||||
|
)
|
||||||
|
: await _service!.moveItem(
|
||||||
|
conflict.item.path,
|
||||||
|
destFolderPath,
|
||||||
|
overwrite: true,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
final newName = _nextAvailableName(conflict.item.name, existingNames);
|
||||||
|
existingNames.add(newName);
|
||||||
|
status = copy
|
||||||
|
? await _service!.copyItem(
|
||||||
|
conflict.item.path,
|
||||||
|
destFolderPath,
|
||||||
|
newName: newName,
|
||||||
|
)
|
||||||
|
: await _service!.moveItem(
|
||||||
|
conflict.item.path,
|
||||||
|
destFolderPath,
|
||||||
|
newName: newName,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (status == 201 || status == 204) {
|
||||||
|
succeeded++;
|
||||||
|
} else {
|
||||||
|
failed++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (succeeded > 0) {
|
||||||
|
_directoryCache.clear();
|
||||||
|
await refreshData();
|
||||||
|
await _syncFavoritesIfLoaded();
|
||||||
|
}
|
||||||
|
return MoveCopyResult(succeeded: succeeded, failed: failed);
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> fetchTrash() async {
|
Future<void> fetchTrash() async {
|
||||||
if (!_isLoggedIn || _service == null) return;
|
if (!_isLoggedIn || _service == null) return;
|
||||||
final gen = _sessionGeneration;
|
final gen = _sessionGeneration;
|
||||||
@@ -1574,6 +2075,21 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
if (index != -1) _items[index] = updated;
|
if (index != -1) _items[index] = updated;
|
||||||
final mediaIndex = _allMedia.indexWhere((i) => i.id == item.id);
|
final mediaIndex = _allMedia.indexWhere((i) => i.id == item.id);
|
||||||
if (mediaIndex != -1) _allMedia[mediaIndex] = updated;
|
if (mediaIndex != -1) _allMedia[mediaIndex] = updated;
|
||||||
|
// Keeps the Favorites tab's own list in sync in place (cheap enough
|
||||||
|
// not to need a full refetch, unlike delete/rename/move/copy - see
|
||||||
|
// `_syncFavoritesIfLoaded`) - added if newly favorited, removed if
|
||||||
|
// un-favorited, since [_allFavorites] should only ever hold
|
||||||
|
// favorited items.
|
||||||
|
final favIndex = _allFavorites.indexWhere((i) => i.id == item.id);
|
||||||
|
if (updated.isFavorite) {
|
||||||
|
if (favIndex != -1) {
|
||||||
|
_allFavorites[favIndex] = updated;
|
||||||
|
} else {
|
||||||
|
_allFavorites = [..._allFavorites, updated];
|
||||||
|
}
|
||||||
|
} else if (favIndex != -1) {
|
||||||
|
_allFavorites = [..._allFavorites]..removeAt(favIndex);
|
||||||
|
}
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1817,6 +2333,7 @@ class ServerProvider extends ChangeNotifier with WidgetsBindingObserver {
|
|||||||
_pollTimer?.cancel();
|
_pollTimer?.cancel();
|
||||||
_pollTimeoutTimer?.cancel();
|
_pollTimeoutTimer?.cancel();
|
||||||
_cacheRefreshTimer?.cancel();
|
_cacheRefreshTimer?.cancel();
|
||||||
|
_syncStatusSub?.cancel();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ class AccountStore {
|
|||||||
/// by account switching.
|
/// by account switching.
|
||||||
static const perAccountPrefKeys = [
|
static const perAccountPrefKeys = [
|
||||||
'ui_grid_view',
|
'ui_grid_view',
|
||||||
'ui_show_favorites_only',
|
|
||||||
'ui_show_favorites_only_photos',
|
'ui_show_favorites_only_photos',
|
||||||
'ui_storage_scope',
|
'ui_storage_scope',
|
||||||
'ui_show_hidden',
|
'ui_show_hidden',
|
||||||
@@ -38,6 +37,8 @@ class AccountStore {
|
|||||||
'ui_files_type_filter',
|
'ui_files_type_filter',
|
||||||
'ui_cache_policy',
|
'ui_cache_policy',
|
||||||
'ui_cache_interval_minutes',
|
'ui_cache_interval_minutes',
|
||||||
|
'ui_synced_folders',
|
||||||
|
'ui_sync_everything',
|
||||||
];
|
];
|
||||||
|
|
||||||
String accountPrefKey(String accountId, String baseKey) =>
|
String accountPrefKey(String accountId, String baseKey) =>
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import '../models/nextcloud_item.dart';
|
||||||
|
import '../providers/server_provider.dart';
|
||||||
|
|
||||||
|
/// Hands a download off to `DownloadService.kt`'s Android foreground
|
||||||
|
/// service - the download counterpart of `UploadService`/
|
||||||
|
/// `ShareUploadService.kt` (see that pair's doc comments for why this
|
||||||
|
/// isn't done in Dart/Dio: only a real Android Service survives the
|
||||||
|
/// Flutter engine/Activity being gone, the same guarantee a real
|
||||||
|
/// file-manager app's download notification gives you). Saves straight
|
||||||
|
/// into the device's public Downloads folder with one cancellable
|
||||||
|
/// progress notification for the whole batch, instead of the old
|
||||||
|
/// download-to-app-cache-then-`file_saver`-prompt flow.
|
||||||
|
class DownloadService {
|
||||||
|
static const _channel = MethodChannel('dev.ayushya.noo/download_service');
|
||||||
|
|
||||||
|
/// Starts downloading [items]. Fire-and-forget from Dart's perspective -
|
||||||
|
/// once this returns, the service owns the rest and reports
|
||||||
|
/// progress/completion/cancellation through its own notification, not
|
||||||
|
/// back to the app.
|
||||||
|
static Future<void> startDownload(
|
||||||
|
ServerProvider provider,
|
||||||
|
List<NextcloudItem> items,
|
||||||
|
) async {
|
||||||
|
final service = provider.service;
|
||||||
|
final authHeader = service?.authHeaders['Authorization'];
|
||||||
|
if (service == null || authHeader == null) {
|
||||||
|
throw Exception('Not logged in.');
|
||||||
|
}
|
||||||
|
|
||||||
|
final filesJson = jsonEncode(
|
||||||
|
items
|
||||||
|
.map(
|
||||||
|
(i) => {
|
||||||
|
'path': i.path,
|
||||||
|
'name': i.name,
|
||||||
|
'mimeType': i.mimeType,
|
||||||
|
'size': i.size,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.toList(),
|
||||||
|
);
|
||||||
|
|
||||||
|
await _channel.invokeMethod('startDownload', {
|
||||||
|
'files': filesJson,
|
||||||
|
'serverUrl': provider.serverUrl,
|
||||||
|
'username': provider.username,
|
||||||
|
'authHeader': authHeader,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -699,6 +699,170 @@ class NextcloudService {
|
|||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Finds every favorited file/folder anywhere in the account (not just
|
||||||
|
/// the currently browsed folder) via the same WebDAV SEARCH-REPORT
|
||||||
|
/// mechanism as [fetchAllMedia], filtered by `oc:favorite` instead of
|
||||||
|
/// mimetype. Used by the Files tab's favorites-only toggle: filtering
|
||||||
|
/// should still be strict (only favorited items), but the *scope* is the
|
||||||
|
/// whole account, not whatever folder happens to be open - otherwise a
|
||||||
|
/// favorited item nested a few folders down would never show up just
|
||||||
|
/// because its parent folders aren't favorited themselves.
|
||||||
|
Future<List<NextcloudItem>> fetchFavorites() async {
|
||||||
|
final url = '$_cleanServerUrl/remote.php/dav/';
|
||||||
|
debugPrint('[Nextcloud DAV] SEARCH for favorites from $url');
|
||||||
|
|
||||||
|
final body =
|
||||||
|
'''<?xml version="1.0" encoding="utf-8" ?>
|
||||||
|
<d:searchrequest xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns" xmlns:nc="http://nextcloud.org/ns">
|
||||||
|
<d:basicsearch>
|
||||||
|
<d:select>
|
||||||
|
<d:prop>
|
||||||
|
<d:displayname/>
|
||||||
|
<d:getcontentlength/>
|
||||||
|
<d:getlastmodified/>
|
||||||
|
<d:creationdate/>
|
||||||
|
<d:getcontenttype/>
|
||||||
|
<d:resourcetype/>
|
||||||
|
<oc:favorite/>
|
||||||
|
<oc:fileid/>
|
||||||
|
<nc:mount-type/>
|
||||||
|
</d:prop>
|
||||||
|
</d:select>
|
||||||
|
<d:from>
|
||||||
|
<d:scope>
|
||||||
|
<d:href>/files/$username</d:href>
|
||||||
|
<d:depth>infinity</d:depth>
|
||||||
|
</d:scope>
|
||||||
|
</d:from>
|
||||||
|
<d:where>
|
||||||
|
<d:eq>
|
||||||
|
<d:prop><oc:favorite/></d:prop>
|
||||||
|
<d:literal>1</d:literal>
|
||||||
|
</d:eq>
|
||||||
|
</d:where>
|
||||||
|
<d:orderby>
|
||||||
|
<d:order>
|
||||||
|
<d:prop><d:displayname/></d:prop>
|
||||||
|
<d:ascending/>
|
||||||
|
</d:order>
|
||||||
|
</d:orderby>
|
||||||
|
</d:basicsearch>
|
||||||
|
</d:searchrequest>''';
|
||||||
|
|
||||||
|
final request = http.Request('SEARCH', Uri.parse(url))
|
||||||
|
..headers.addAll({..._headers, 'Content-Type': 'text/xml'})
|
||||||
|
..body = body;
|
||||||
|
|
||||||
|
final streamed = await http.Client().send(request);
|
||||||
|
final responseBody = await streamed.stream.bytesToString();
|
||||||
|
debugPrint(
|
||||||
|
'[Nextcloud DAV] Favorites SEARCH status: ${streamed.statusCode}, bytes: ${responseBody.length}',
|
||||||
|
);
|
||||||
|
|
||||||
|
if (streamed.statusCode != 207 && streamed.statusCode != 200) {
|
||||||
|
throw Exception('Failed to load favorites. HTTP ${streamed.statusCode}');
|
||||||
|
}
|
||||||
|
|
||||||
|
final document = xml.XmlDocument.parse(responseBody);
|
||||||
|
final responses = document.findLocalDescendants('response');
|
||||||
|
|
||||||
|
final results = <NextcloudItem>[];
|
||||||
|
for (var res in responses) {
|
||||||
|
final hrefNode =
|
||||||
|
res.findLocalChildren('href').firstOrNull ??
|
||||||
|
res.findLocalDescendants('href').firstOrNull;
|
||||||
|
final href = hrefNode?.innerText ?? '';
|
||||||
|
if (href.isEmpty) continue;
|
||||||
|
|
||||||
|
final props = res.findLocalDescendants('prop');
|
||||||
|
if (props.isEmpty) continue;
|
||||||
|
|
||||||
|
bool isCollection = false;
|
||||||
|
String? sizeStr;
|
||||||
|
String? lastModStr;
|
||||||
|
String? createdStr;
|
||||||
|
String? mimeType;
|
||||||
|
String? fileId;
|
||||||
|
String? mountType;
|
||||||
|
|
||||||
|
for (var prop in props) {
|
||||||
|
if (!isCollection) {
|
||||||
|
final resTypeNode = prop
|
||||||
|
.findLocalChildren('resourcetype')
|
||||||
|
.firstOrNull;
|
||||||
|
if (resTypeNode != null &&
|
||||||
|
resTypeNode.findLocalChildren('collection').isNotEmpty) {
|
||||||
|
isCollection = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sizeStr ??= prop
|
||||||
|
.findLocalChildren('getcontentlength')
|
||||||
|
.firstOrNull
|
||||||
|
?.innerText;
|
||||||
|
lastModStr ??= prop
|
||||||
|
.findLocalChildren('getlastmodified')
|
||||||
|
.firstOrNull
|
||||||
|
?.innerText;
|
||||||
|
createdStr ??= prop
|
||||||
|
.findLocalChildren('creationdate')
|
||||||
|
.firstOrNull
|
||||||
|
?.innerText;
|
||||||
|
mimeType ??= prop
|
||||||
|
.findLocalChildren('getcontenttype')
|
||||||
|
.firstOrNull
|
||||||
|
?.innerText;
|
||||||
|
fileId ??= prop.findLocalChildren('fileid').firstOrNull?.innerText;
|
||||||
|
mountType ??= prop
|
||||||
|
.findLocalChildren('mount-type')
|
||||||
|
.firstOrNull
|
||||||
|
?.innerText;
|
||||||
|
}
|
||||||
|
|
||||||
|
var decodedHref = Uri.decodeFull(href);
|
||||||
|
if (decodedHref.endsWith('/') && decodedHref.length > 1) {
|
||||||
|
decodedHref = decodedHref.substring(0, decodedHref.length - 1);
|
||||||
|
}
|
||||||
|
final name = decodedHref.split('/').where((s) => s.isNotEmpty).last;
|
||||||
|
if (name.isEmpty) continue;
|
||||||
|
|
||||||
|
// Strip the DAV root prefix so `path` matches what fetchDirectory produces.
|
||||||
|
final marker = '/files/$username';
|
||||||
|
final markerIndex = decodedHref.indexOf(marker);
|
||||||
|
final itemPath = markerIndex >= 0
|
||||||
|
? decodedHref.substring(markerIndex + marker.length)
|
||||||
|
: decodedHref;
|
||||||
|
if (itemPath.isEmpty) continue;
|
||||||
|
|
||||||
|
final size = int.tryParse(sizeStr ?? '0') ?? 0;
|
||||||
|
final lastMod = _parseDavDate(lastModStr) ?? DateTime.now();
|
||||||
|
final created = _parseDavDate(createdStr);
|
||||||
|
final itemType = NextcloudItem.deduceType(name, isCollection, mimeType);
|
||||||
|
final validId = (fileId != null && fileId.isNotEmpty) ? fileId : name;
|
||||||
|
|
||||||
|
results.add(
|
||||||
|
NextcloudItem(
|
||||||
|
id: validId,
|
||||||
|
name: name,
|
||||||
|
path: itemPath,
|
||||||
|
type: itemType,
|
||||||
|
size: size,
|
||||||
|
lastModified: lastMod,
|
||||||
|
dateCreated: created,
|
||||||
|
isFavorite: true,
|
||||||
|
mimeType: mimeType,
|
||||||
|
previewUrl:
|
||||||
|
'$_cleanServerUrl/core/preview?fileId=$validId&x=500&y=500',
|
||||||
|
mountType: mountType,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
debugPrint(
|
||||||
|
'[Nextcloud DAV] Favorites SEARCH found ${results.length} items',
|
||||||
|
);
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
/// Finds recently modified files across the whole account (folders
|
/// Finds recently modified files across the whole account (folders
|
||||||
/// excluded), newest first — same SEARCH-REPORT mechanism as
|
/// excluded), newest first — same SEARCH-REPORT mechanism as
|
||||||
/// [fetchAllMedia], just without the image/video mimetype filter.
|
/// [fetchAllMedia], just without the image/video mimetype filter.
|
||||||
@@ -939,44 +1103,6 @@ class NextcloudService {
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Uploads a file from disk, streaming it so large files don't need to be
|
|
||||||
/// buffered fully in memory, with progress reporting.
|
|
||||||
Future<bool> uploadFileFromPath(
|
|
||||||
String folderPath,
|
|
||||||
String fileName,
|
|
||||||
String localFilePath, {
|
|
||||||
void Function(int sent, int total)? onProgress,
|
|
||||||
}) async {
|
|
||||||
var cleanPath = folderPath.trim();
|
|
||||||
if (!cleanPath.startsWith('/')) cleanPath = '/$cleanPath';
|
|
||||||
if (!cleanPath.endsWith('/')) cleanPath = '$cleanPath/';
|
|
||||||
|
|
||||||
final url =
|
|
||||||
'$_cleanServerUrl/remote.php/dav/files/$username$cleanPath$fileName';
|
|
||||||
debugPrint('[Nextcloud DAV] Streaming upload to $url');
|
|
||||||
|
|
||||||
final file = File(localFilePath);
|
|
||||||
final length = await file.length();
|
|
||||||
final dio = Dio();
|
|
||||||
|
|
||||||
final response = await dio.put<void>(
|
|
||||||
url,
|
|
||||||
data: file.openRead(),
|
|
||||||
options: Options(
|
|
||||||
headers: {..._headers, Headers.contentLengthHeader: length},
|
|
||||||
contentType: 'application/octet-stream',
|
|
||||||
),
|
|
||||||
onSendProgress: onProgress,
|
|
||||||
);
|
|
||||||
|
|
||||||
debugPrint(
|
|
||||||
'[Nextcloud DAV] Streaming upload status: ${response.statusCode}',
|
|
||||||
);
|
|
||||||
return response.statusCode == 201 ||
|
|
||||||
response.statusCode == 204 ||
|
|
||||||
response.statusCode == 200;
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<bool> deleteItem(String itemPath) async {
|
Future<bool> deleteItem(String itemPath) async {
|
||||||
var cleanPath = itemPath.trim();
|
var cleanPath = itemPath.trim();
|
||||||
if (!cleanPath.startsWith('/')) cleanPath = '/$cleanPath';
|
if (!cleanPath.startsWith('/')) cleanPath = '/$cleanPath';
|
||||||
@@ -989,6 +1115,43 @@ class NextcloudService {
|
|||||||
return response.statusCode == 204 || response.statusCode == 200;
|
return response.statusCode == 204 || response.statusCode == 200;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Shared MOVE/COPY request - WebDAV COPY is the same shape as the MOVE
|
||||||
|
/// [renameItem] uses, just a different verb and a caller-controlled
|
||||||
|
/// `Overwrite` rather than always forced off. Returns the raw HTTP status
|
||||||
|
/// rather than a bool so callers can tell a conflict (412 - only
|
||||||
|
/// possible when `overwrite` is false) apart from any other failure
|
||||||
|
/// without a separate existence-check request per item.
|
||||||
|
Future<int> _moveOrCopy(
|
||||||
|
String sourcePath,
|
||||||
|
String destPath, {
|
||||||
|
required bool copy,
|
||||||
|
required bool overwrite,
|
||||||
|
}) async {
|
||||||
|
var cleanSource = sourcePath.trim();
|
||||||
|
if (!cleanSource.startsWith('/')) cleanSource = '/$cleanSource';
|
||||||
|
var cleanDest = destPath.trim();
|
||||||
|
if (!cleanDest.startsWith('/')) cleanDest = '/$cleanDest';
|
||||||
|
|
||||||
|
final sourceUrl =
|
||||||
|
'$_cleanServerUrl/remote.php/dav/files/$username$cleanSource';
|
||||||
|
final destUrl = '$_cleanServerUrl/remote.php/dav/files/$username$cleanDest';
|
||||||
|
debugPrint(
|
||||||
|
'[Nextcloud DAV] ${copy ? 'Copying' : 'Moving'} $sourceUrl -> $destUrl',
|
||||||
|
);
|
||||||
|
|
||||||
|
final request = http.Request(copy ? 'COPY' : 'MOVE', Uri.parse(sourceUrl))
|
||||||
|
..headers.addAll({
|
||||||
|
..._headers,
|
||||||
|
'Destination': Uri.encodeFull(destUrl),
|
||||||
|
'Overwrite': overwrite ? 'T' : 'F',
|
||||||
|
});
|
||||||
|
final response = await http.Client().send(request);
|
||||||
|
debugPrint(
|
||||||
|
'[Nextcloud DAV] ${copy ? 'Copy' : 'Move'} status: ${response.statusCode}',
|
||||||
|
);
|
||||||
|
return response.statusCode;
|
||||||
|
}
|
||||||
|
|
||||||
/// Renames (or moves within the same folder) an item via WebDAV MOVE.
|
/// Renames (or moves within the same folder) an item via WebDAV MOVE.
|
||||||
Future<bool> renameItem(String itemPath, String newName) async {
|
Future<bool> renameItem(String itemPath, String newName) async {
|
||||||
var cleanPath = itemPath.trim();
|
var cleanPath = itemPath.trim();
|
||||||
@@ -997,20 +1160,75 @@ class NextcloudService {
|
|||||||
final segments = cleanPath.split('/')..removeLast();
|
final segments = cleanPath.split('/')..removeLast();
|
||||||
final destPath = '${segments.join('/')}/$newName';
|
final destPath = '${segments.join('/')}/$newName';
|
||||||
|
|
||||||
final sourceUrl =
|
final status = await _moveOrCopy(
|
||||||
'$_cleanServerUrl/remote.php/dav/files/$username$cleanPath';
|
cleanPath,
|
||||||
final destUrl = '$_cleanServerUrl/remote.php/dav/files/$username$destPath';
|
destPath,
|
||||||
debugPrint('[Nextcloud DAV] Renaming $sourceUrl -> $destUrl');
|
copy: false,
|
||||||
|
overwrite: false,
|
||||||
|
);
|
||||||
|
return status == 201 || status == 204;
|
||||||
|
}
|
||||||
|
|
||||||
final request = http.Request('MOVE', Uri.parse(sourceUrl))
|
Future<int> _moveOrCopyToFolder(
|
||||||
..headers.addAll({
|
String itemPath,
|
||||||
..._headers,
|
String destFolderPath, {
|
||||||
'Destination': Uri.encodeFull(destUrl),
|
required bool copy,
|
||||||
'Overwrite': 'F',
|
required bool overwrite,
|
||||||
});
|
String? newName,
|
||||||
final response = await http.Client().send(request);
|
}) {
|
||||||
debugPrint('[Nextcloud DAV] Rename status: ${response.statusCode}');
|
var cleanPath = itemPath.trim();
|
||||||
return response.statusCode == 201 || response.statusCode == 204;
|
if (!cleanPath.startsWith('/')) cleanPath = '/$cleanPath';
|
||||||
|
final name = newName ?? cleanPath.split('/').last;
|
||||||
|
|
||||||
|
var cleanDestFolder = destFolderPath.trim();
|
||||||
|
if (!cleanDestFolder.startsWith('/')) cleanDestFolder = '/$cleanDestFolder';
|
||||||
|
if (cleanDestFolder.endsWith('/') && cleanDestFolder != '/') {
|
||||||
|
cleanDestFolder = cleanDestFolder.substring(
|
||||||
|
0,
|
||||||
|
cleanDestFolder.length - 1,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final destPath = cleanDestFolder == '/'
|
||||||
|
? '/$name'
|
||||||
|
: '$cleanDestFolder/$name';
|
||||||
|
return _moveOrCopy(cleanPath, destPath, copy: copy, overwrite: overwrite);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves [itemPath] into [destFolderPath], keeping its current filename
|
||||||
|
/// unless [newName] is given (used to resolve a "keep both" conflict
|
||||||
|
/// with a renamed destination). Returns the raw HTTP status - 201/204
|
||||||
|
/// success, 412 means an item with the same name already exists there
|
||||||
|
/// ([overwrite] was false).
|
||||||
|
Future<int> moveItem(
|
||||||
|
String itemPath,
|
||||||
|
String destFolderPath, {
|
||||||
|
bool overwrite = false,
|
||||||
|
String? newName,
|
||||||
|
}) {
|
||||||
|
return _moveOrCopyToFolder(
|
||||||
|
itemPath,
|
||||||
|
destFolderPath,
|
||||||
|
copy: false,
|
||||||
|
overwrite: overwrite,
|
||||||
|
newName: newName,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Same as [moveItem] but duplicates the item instead of relocating it -
|
||||||
|
/// WebDAV COPY, recursive for folders by default just like MOVE.
|
||||||
|
Future<int> copyItem(
|
||||||
|
String itemPath,
|
||||||
|
String destFolderPath, {
|
||||||
|
bool overwrite = false,
|
||||||
|
String? newName,
|
||||||
|
}) {
|
||||||
|
return _moveOrCopyToFolder(
|
||||||
|
itemPath,
|
||||||
|
destFolderPath,
|
||||||
|
copy: true,
|
||||||
|
overwrite: overwrite,
|
||||||
|
newName: newName,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<bool> createFolder(String parentPath, String folderName) async {
|
Future<bool> createFolder(String parentPath, String folderName) async {
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import '../models/pick_request.dart';
|
||||||
|
|
||||||
|
/// Talks to `MainActivity.kt`'s hand-rolled GET_CONTENT picker handling
|
||||||
|
/// (mirrors `ShareIntentService`'s split between a cold-start check and a
|
||||||
|
/// stream for an intent arriving while the app is already running - the
|
||||||
|
/// same `singleTask` launch mode applies here).
|
||||||
|
class PickIntentService {
|
||||||
|
static const _methodChannel = MethodChannel('dev.ayushya.noo/pick_intent');
|
||||||
|
static const _newPickChannel = EventChannel(
|
||||||
|
'dev.ayushya.noo/pick_intent/new',
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Non-null if the app was launched cold as another app's file/photo
|
||||||
|
/// picker.
|
||||||
|
static Future<PickRequest?> getPickRequest() async {
|
||||||
|
final result = await _methodChannel.invokeMethod<Map<dynamic, dynamic>>(
|
||||||
|
'getPickRequest',
|
||||||
|
);
|
||||||
|
return result == null ? null : PickRequest.fromMap(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emits whenever the app is asked to act as a picker while already
|
||||||
|
/// running.
|
||||||
|
static Stream<PickRequest> get onNewPickRequest {
|
||||||
|
return _newPickChannel.receiveBroadcastStream().map(
|
||||||
|
(event) => PickRequest.fromMap(event as Map<dynamic, dynamic>),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hands the already-downloaded local files back to the caller and closes
|
||||||
|
/// the picker. [mimeTypes] is parallel to [localPaths].
|
||||||
|
static Future<void> finishPick(
|
||||||
|
List<String> localPaths,
|
||||||
|
List<String> mimeTypes,
|
||||||
|
) {
|
||||||
|
return _methodChannel.invokeMethod('finishPick', {
|
||||||
|
'paths': localPaths,
|
||||||
|
'mimeTypes': mimeTypes,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Backs out of picking mode with no result, closing the picker.
|
||||||
|
static Future<void> cancelPick() {
|
||||||
|
return _methodChannel.invokeMethod('cancelPick');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import '../models/sync_status.dart';
|
||||||
|
import '../providers/server_provider.dart';
|
||||||
|
|
||||||
|
/// A snapshot of native device-sync status - see `SyncStatusBus.kt` (the
|
||||||
|
/// in-process pub/sub it mirrors) and `MainActivity.kt`'s `syncStatusMap`.
|
||||||
|
class SyncStatusSnapshot {
|
||||||
|
final String? accountId;
|
||||||
|
final bool syncing;
|
||||||
|
final Set<String> syncingFileIds;
|
||||||
|
final Set<String> syncedFileIds;
|
||||||
|
final List<SyncConflictInfo> conflicts;
|
||||||
|
|
||||||
|
const SyncStatusSnapshot({
|
||||||
|
required this.accountId,
|
||||||
|
required this.syncing,
|
||||||
|
required this.syncingFileIds,
|
||||||
|
required this.syncedFileIds,
|
||||||
|
required this.conflicts,
|
||||||
|
});
|
||||||
|
|
||||||
|
factory SyncStatusSnapshot.fromMap(Map<dynamic, dynamic> map) {
|
||||||
|
return SyncStatusSnapshot(
|
||||||
|
accountId: map['accountId'] as String?,
|
||||||
|
syncing: map['syncing'] as bool? ?? false,
|
||||||
|
syncingFileIds: ((map['syncingFileIds'] as List?) ?? const [])
|
||||||
|
.cast<String>()
|
||||||
|
.toSet(),
|
||||||
|
syncedFileIds: ((map['syncedFileIds'] as List?) ?? const [])
|
||||||
|
.cast<String>()
|
||||||
|
.toSet(),
|
||||||
|
conflicts: ((map['conflicts'] as List?) ?? const [])
|
||||||
|
.cast<Map<dynamic, dynamic>>()
|
||||||
|
.map(SyncConflictInfo.fromMap)
|
||||||
|
.toList(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Talks to `SyncWorker`/`SyncEngine.kt`'s Android WorkManager-based device
|
||||||
|
/// sync (see `server.md`'s "Device sync" section for the full design) -
|
||||||
|
/// Dart's job here is only to gather what the native side needs, push a
|
||||||
|
/// fresh config whenever it changes, and listen for live status; the actual
|
||||||
|
/// PROPFIND-walk/diff/GET/PUT engine runs entirely in Kotlin, independent
|
||||||
|
/// of the Flutter engine.
|
||||||
|
class SyncService {
|
||||||
|
static const _channel = MethodChannel('dev.ayushya.noo/sync_service');
|
||||||
|
static const _statusChannel = EventChannel(
|
||||||
|
'dev.ayushya.noo/sync_service/status',
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Cancels (if [ServerProvider.syncedPaths] is now empty) or re-enqueues
|
||||||
|
/// the periodic sync job with fresh account/credentials/path-list/
|
||||||
|
/// network-constraint data - call this any time one of those changes,
|
||||||
|
/// since a periodic `WorkRequest`'s input is fixed at enqueue time and
|
||||||
|
/// can only be updated by re-enqueueing.
|
||||||
|
static Future<void> reschedule(ServerProvider provider) async {
|
||||||
|
final accountId = provider.activeAccountId;
|
||||||
|
final service = provider.service;
|
||||||
|
final authHeader = service?.authHeaders['Authorization'];
|
||||||
|
if (accountId == null || service == null || authHeader == null) {
|
||||||
|
return cancel();
|
||||||
|
}
|
||||||
|
|
||||||
|
final paths = provider.syncEverything ? ['/'] : provider.syncedPaths;
|
||||||
|
await _channel.invokeMethod('reschedule', {
|
||||||
|
'accountId': accountId,
|
||||||
|
'serverUrl': provider.serverUrl,
|
||||||
|
'username': provider.username,
|
||||||
|
'authHeader': authHeader,
|
||||||
|
'folders': jsonEncode(paths),
|
||||||
|
'wifiOnly': !provider.syncOnCellular,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
static Future<void> cancel() async {
|
||||||
|
await _channel.invokeMethod('cancel');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs a one-off sync pass immediately (Settings' "Sync now"),
|
||||||
|
/// independent of the periodic schedule.
|
||||||
|
static Future<void> syncNow(ServerProvider provider) async {
|
||||||
|
final accountId = provider.activeAccountId;
|
||||||
|
final service = provider.service;
|
||||||
|
final authHeader = service?.authHeaders['Authorization'];
|
||||||
|
if (accountId == null || service == null || authHeader == null) {
|
||||||
|
throw Exception('Not logged in.');
|
||||||
|
}
|
||||||
|
|
||||||
|
final paths = provider.syncEverything ? ['/'] : provider.syncedPaths;
|
||||||
|
await _channel.invokeMethod('syncNow', {
|
||||||
|
'accountId': accountId,
|
||||||
|
'serverUrl': provider.serverUrl,
|
||||||
|
'username': provider.username,
|
||||||
|
'authHeader': authHeader,
|
||||||
|
'folders': jsonEncode(paths),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One-shot status snapshot - used to seed [ServerProvider]'s state right
|
||||||
|
/// after login/account-switch, before the first [statusStream] event
|
||||||
|
/// arrives.
|
||||||
|
static Future<SyncStatusSnapshot> getStatus() async {
|
||||||
|
final result = await _channel.invokeMethod<Map<dynamic, dynamic>>(
|
||||||
|
'getSyncStatus',
|
||||||
|
);
|
||||||
|
return SyncStatusSnapshot.fromMap(result ?? const {});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Live status updates pushed from `SyncStatusBus` (Kotlin) - syncing
|
||||||
|
/// started/stopped, per-file progress, new/resolved conflicts.
|
||||||
|
static Stream<SyncStatusSnapshot> get statusStream {
|
||||||
|
return _statusChannel.receiveBroadcastStream().map(
|
||||||
|
(event) => SyncStatusSnapshot.fromMap(event as Map<dynamic, dynamic>),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// In-app conflict resolution (the header's "Keep local"/"Use server"
|
||||||
|
/// buttons) - shares the exact same native `ConflictResolveWorker`
|
||||||
|
/// enqueue path the notification actions use, just triggered from Dart
|
||||||
|
/// instead of a `PendingIntent`.
|
||||||
|
static Future<void> resolveConflict(
|
||||||
|
ServerProvider provider,
|
||||||
|
SyncConflictInfo conflict,
|
||||||
|
String resolution,
|
||||||
|
) async {
|
||||||
|
final service = provider.service;
|
||||||
|
final authHeader = service?.authHeaders['Authorization'];
|
||||||
|
if (service == null || authHeader == null) {
|
||||||
|
throw Exception('Not logged in.');
|
||||||
|
}
|
||||||
|
await _channel.invokeMethod('resolveConflict', {
|
||||||
|
'accountId': conflict.accountId,
|
||||||
|
'serverUrl': provider.serverUrl,
|
||||||
|
'username': provider.username,
|
||||||
|
'authHeader': authHeader,
|
||||||
|
'fileId': conflict.fileId,
|
||||||
|
'remotePath': conflict.remotePath,
|
||||||
|
'relPath': conflict.relPath,
|
||||||
|
'resolution': resolution,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
+154
-65
@@ -3,6 +3,7 @@ import 'package:provider/provider.dart';
|
|||||||
import '../models/app_tab.dart';
|
import '../models/app_tab.dart';
|
||||||
import '../models/saved_account.dart';
|
import '../models/saved_account.dart';
|
||||||
import '../providers/server_provider.dart';
|
import '../providers/server_provider.dart';
|
||||||
|
import '../services/sync_service.dart';
|
||||||
import '../theme/app_theme.dart';
|
import '../theme/app_theme.dart';
|
||||||
import '../widgets/frosted_glass_container.dart';
|
import '../widgets/frosted_glass_container.dart';
|
||||||
import '../widgets/seek_bar_painter.dart';
|
import '../widgets/seek_bar_painter.dart';
|
||||||
@@ -80,30 +81,6 @@ class AccountView extends StatelessWidget {
|
|||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
const Divider(height: 1),
|
const Divider(height: 1),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Row(
|
|
||||||
children: [
|
|
||||||
Icon(
|
|
||||||
Icons.public_rounded,
|
|
||||||
size: 18,
|
|
||||||
color: colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Expanded(
|
|
||||||
child: Text(
|
|
||||||
Uri.tryParse(provider.serverUrl)?.host ??
|
|
||||||
provider.serverUrl,
|
|
||||||
maxLines: 1,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
style: theme.textTheme.bodyMedium?.copyWith(
|
|
||||||
color: colorScheme.onSurfaceVariant,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
const Divider(height: 1),
|
|
||||||
const SizedBox(height: 16),
|
|
||||||
Row(
|
Row(
|
||||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||||
children: [
|
children: [
|
||||||
@@ -137,9 +114,22 @@ class AccountView extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Align(
|
Row(
|
||||||
alignment: Alignment.centerRight,
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
child: Text(
|
child: Text(
|
||||||
|
Uri.tryParse(provider.serverUrl)?.host ??
|
||||||
|
provider.serverUrl,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: theme.textTheme.bodySmall?.copyWith(
|
||||||
|
color: colorScheme.onSurfaceVariant,
|
||||||
|
fontSize: 11,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Text(
|
||||||
quota != null
|
quota != null
|
||||||
? (quota.totalBytes > 0
|
? (quota.totalBytes > 0
|
||||||
? '${(quota.usagePercentage * 100).toStringAsFixed(1)}% used'
|
? '${(quota.usagePercentage * 100).toStringAsFixed(1)}% used'
|
||||||
@@ -150,6 +140,7 @@ class AccountView extends StatelessWidget {
|
|||||||
fontSize: 11,
|
fontSize: 11,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
if (quota != null && quota.groups.isNotEmpty) ...[
|
if (quota != null && quota.groups.isNotEmpty) ...[
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
@@ -188,9 +179,11 @@ class AccountView extends StatelessWidget {
|
|||||||
const Divider(height: 1),
|
const Divider(height: 1),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Row(
|
Row(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.end,
|
||||||
children: [
|
children: [
|
||||||
Expanded(
|
IconButton(
|
||||||
child: OutlinedButton(
|
icon: const Icon(Icons.refresh_rounded),
|
||||||
|
tooltip: 'Refresh cached data',
|
||||||
onPressed: () async {
|
onPressed: () async {
|
||||||
await provider.refreshData();
|
await provider.refreshData();
|
||||||
if (context.mounted) {
|
if (context.mounted) {
|
||||||
@@ -202,48 +195,19 @@ class AccountView extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
style: OutlinedButton.styleFrom(
|
|
||||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
|
||||||
),
|
),
|
||||||
child: const Text(
|
IconButton(
|
||||||
'Refresh Cache',
|
icon: const Icon(Icons.logout_rounded),
|
||||||
textAlign: TextAlign.center,
|
tooltip: 'Logout',
|
||||||
style: TextStyle(fontSize: 13),
|
color: Colors.orange.shade700,
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Expanded(
|
|
||||||
child: FilledButton(
|
|
||||||
onPressed: () => _handleLogout(context, provider),
|
onPressed: () => _handleLogout(context, provider),
|
||||||
style: FilledButton.styleFrom(
|
|
||||||
backgroundColor: colorScheme.errorContainer,
|
|
||||||
foregroundColor: colorScheme.onErrorContainer,
|
|
||||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
|
||||||
),
|
),
|
||||||
child: const Text(
|
IconButton(
|
||||||
'Logout',
|
icon: const Icon(Icons.delete_outline_rounded),
|
||||||
textAlign: TextAlign.center,
|
tooltip: 'Remove account',
|
||||||
style: TextStyle(fontSize: 13),
|
color: colorScheme.error,
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Expanded(
|
|
||||||
child: FilledButton(
|
|
||||||
onPressed: () =>
|
onPressed: () =>
|
||||||
_confirmRemoveActive(context, provider),
|
_confirmRemoveActive(context, provider),
|
||||||
style: FilledButton.styleFrom(
|
|
||||||
backgroundColor: colorScheme.error,
|
|
||||||
foregroundColor: colorScheme.onError,
|
|
||||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
|
||||||
),
|
|
||||||
child: const Text(
|
|
||||||
'Remove',
|
|
||||||
textAlign: TextAlign.center,
|
|
||||||
style: TextStyle(fontSize: 13),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -274,6 +238,17 @@ class AccountView extends StatelessWidget {
|
|||||||
const _SecurityCard(),
|
const _SecurityCard(),
|
||||||
const SizedBox(height: 24),
|
const SizedBox(height: 24),
|
||||||
|
|
||||||
|
// Device Sync Section
|
||||||
|
Text(
|
||||||
|
'Device Sync',
|
||||||
|
style: theme.textTheme.titleMedium?.copyWith(
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 10),
|
||||||
|
const _DeviceSyncCard(),
|
||||||
|
const SizedBox(height: 24),
|
||||||
|
|
||||||
// Material You Design Settings
|
// Material You Design Settings
|
||||||
Text(
|
Text(
|
||||||
'Material You Aesthetics',
|
'Material You Aesthetics',
|
||||||
@@ -759,6 +734,120 @@ class _SecurityCard extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class _DeviceSyncCard extends StatefulWidget {
|
||||||
|
const _DeviceSyncCard();
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_DeviceSyncCard> createState() => _DeviceSyncCardState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _DeviceSyncCardState extends State<_DeviceSyncCard> {
|
||||||
|
bool _syncingNow = false;
|
||||||
|
|
||||||
|
Future<void> _syncNow(ServerProvider provider) async {
|
||||||
|
setState(() => _syncingNow = true);
|
||||||
|
try {
|
||||||
|
await SyncService.syncNow(provider);
|
||||||
|
} catch (e) {
|
||||||
|
if (mounted) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text('Could not start sync: $e'),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (mounted) setState(() => _syncingNow = false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final colorScheme = theme.colorScheme;
|
||||||
|
final provider = context.watch<ServerProvider>();
|
||||||
|
final folders = provider.syncedPaths;
|
||||||
|
final everything = provider.syncEverything;
|
||||||
|
|
||||||
|
return Card(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
SwitchListTile(
|
||||||
|
secondary: const Icon(Icons.cloud_sync_rounded),
|
||||||
|
title: const Text('Sync everything'),
|
||||||
|
subtitle: const Text(
|
||||||
|
'Mirror the whole account instead of picking folders',
|
||||||
|
),
|
||||||
|
value: everything,
|
||||||
|
onChanged: provider.setSyncEverything,
|
||||||
|
),
|
||||||
|
const Divider(height: 1, indent: 16, endIndent: 16),
|
||||||
|
if (everything)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 16, 16, 4),
|
||||||
|
child: Text(
|
||||||
|
'Every folder in this account is being synced to this '
|
||||||
|
'device.',
|
||||||
|
style: theme.textTheme.bodySmall?.copyWith(
|
||||||
|
color: colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (folders.isEmpty)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 16, 16, 4),
|
||||||
|
child: Text(
|
||||||
|
'No folders synced yet - select a folder in Files and use '
|
||||||
|
'"Sync to device" to mirror it here for offline access.',
|
||||||
|
style: theme.textTheme.bodySmall?.copyWith(
|
||||||
|
color: colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
for (final folder in folders) ...[
|
||||||
|
ListTile(
|
||||||
|
leading: const Icon(Icons.sync_rounded),
|
||||||
|
title: Text(folder),
|
||||||
|
trailing: IconButton(
|
||||||
|
icon: const Icon(Icons.close_rounded),
|
||||||
|
tooltip: 'Stop syncing',
|
||||||
|
onPressed: () => provider.removeSyncedPath(folder),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const Divider(height: 1, indent: 16, endIndent: 16),
|
||||||
|
],
|
||||||
|
SwitchListTile(
|
||||||
|
secondary: const Icon(Icons.signal_cellular_alt_rounded),
|
||||||
|
title: const Text('Sync on cellular'),
|
||||||
|
subtitle: const Text('Off = background sync only runs on Wi-Fi'),
|
||||||
|
value: provider.syncOnCellular,
|
||||||
|
onChanged: provider.setSyncOnCellular,
|
||||||
|
),
|
||||||
|
const Divider(height: 1, indent: 16, endIndent: 16),
|
||||||
|
ListTile(
|
||||||
|
leading: _syncingNow
|
||||||
|
? const Padding(
|
||||||
|
padding: EdgeInsets.all(2),
|
||||||
|
child: SizedBox(
|
||||||
|
width: 20,
|
||||||
|
height: 20,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: const Icon(Icons.sync_rounded),
|
||||||
|
title: const Text('Sync now'),
|
||||||
|
enabled: (everything || folders.isNotEmpty) && !_syncingNow,
|
||||||
|
onTap: () => _syncNow(provider),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
class _BottomBarAppearanceCard extends StatefulWidget {
|
class _BottomBarAppearanceCard extends StatefulWidget {
|
||||||
const _BottomBarAppearanceCard();
|
const _BottomBarAppearanceCard();
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,804 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:intl/intl.dart';
|
||||||
|
import 'package:material_symbols_icons/symbols.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:share_plus/share_plus.dart';
|
||||||
|
import '../models/app_tab.dart';
|
||||||
|
import '../models/nextcloud_item.dart';
|
||||||
|
import '../models/selection_action.dart';
|
||||||
|
import '../providers/server_provider.dart';
|
||||||
|
import '../services/download_service.dart';
|
||||||
|
import '../widgets/details/details_sheet.dart';
|
||||||
|
import '../widgets/item_icon.dart';
|
||||||
|
import '../widgets/more_tabs_button.dart';
|
||||||
|
import '../widgets/profile_avatar_button.dart';
|
||||||
|
import '../widgets/segmented_icon_toggle.dart';
|
||||||
|
import '../widgets/selectable_thumbnail.dart';
|
||||||
|
import '../widgets/share_sheet.dart';
|
||||||
|
import '../widgets/sort_menu_button.dart';
|
||||||
|
import '../widgets/sticky_header_delegate.dart';
|
||||||
|
import '../widgets/synced_header_scaffold.dart';
|
||||||
|
import 'file_viewer_screen.dart';
|
||||||
|
import 'move_copy_destination_picker.dart';
|
||||||
|
|
||||||
|
/// Every favorited file/folder across the whole account, account-wide - a
|
||||||
|
/// real tab rather than a filter toggle scoped to whatever folder the
|
||||||
|
/// Files tab happens to be browsing (see `ServerProvider.fetchAllFavorites`
|
||||||
|
/// for why: a favorited item several folders deep needs to show up
|
||||||
|
/// regardless of whether its parent folders are themselves favorited,
|
||||||
|
/// which a current-folder-only filter can never do, and a flat account-
|
||||||
|
/// wide list also means the breadcrumb-vs-content mismatch a filter
|
||||||
|
/// toggle had - the trail showing wherever Files was last browsing while
|
||||||
|
/// the content showed something else entirely - simply can't happen).
|
||||||
|
/// Shares Files' own sort/hidden/storage-scope/grid-list display prefs
|
||||||
|
/// (via `ServerProvider.applyFilesDisplayPrefs`) rather than a separate
|
||||||
|
/// parallel settings dimension.
|
||||||
|
class FavoritesView extends StatefulWidget {
|
||||||
|
final ScrollController scrollController;
|
||||||
|
|
||||||
|
const FavoritesView({super.key, required this.scrollController});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<FavoritesView> createState() => _FavoritesViewState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _FavoritesViewState extends State<FavoritesView>
|
||||||
|
with SingleTickerProviderStateMixin {
|
||||||
|
bool _requested = false;
|
||||||
|
final Set<String> _selectedIds = {};
|
||||||
|
final ScrollController _selectionActionsScrollController = ScrollController();
|
||||||
|
final List<AnimationController> _scrollHintControllers = [];
|
||||||
|
|
||||||
|
bool get _isSelecting => _selectedIds.isNotEmpty;
|
||||||
|
|
||||||
|
void _toggleSelection(NextcloudItem item) {
|
||||||
|
HapticFeedback.selectionClick();
|
||||||
|
final enteringSelection = _selectedIds.isEmpty;
|
||||||
|
setState(() {
|
||||||
|
if (!_selectedIds.remove(item.id)) _selectedIds.add(item.id);
|
||||||
|
});
|
||||||
|
if (enteringSelection && _isSelecting) {
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback(
|
||||||
|
(_) => _playScrollHint(_selectionActionsScrollController),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _clearSelection() {
|
||||||
|
setState(_selectedIds.clear);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mirrors `FilesView`/`PhotosView`'s identical scroll-hint - see their
|
||||||
|
/// doc comment: nudges the selection actions row right and back, once,
|
||||||
|
/// the first time a selection starts. No-ops if there's nothing to
|
||||||
|
/// scroll (row already fits).
|
||||||
|
Future<void> _playScrollHint(ScrollController scrollController) async {
|
||||||
|
await Future.delayed(const Duration(milliseconds: 500));
|
||||||
|
if (!mounted || !scrollController.hasClients) return;
|
||||||
|
final maxExtent = scrollController.position.maxScrollExtent;
|
||||||
|
if (maxExtent <= 0) return;
|
||||||
|
final double peak = maxExtent < 36 ? maxExtent : 36;
|
||||||
|
final controller = AnimationController(
|
||||||
|
vsync: this,
|
||||||
|
duration: const Duration(milliseconds: 900),
|
||||||
|
);
|
||||||
|
_scrollHintControllers.add(controller);
|
||||||
|
final hint = TweenSequence<double>([
|
||||||
|
TweenSequenceItem(
|
||||||
|
tween: Tween(
|
||||||
|
begin: 0.0,
|
||||||
|
end: peak,
|
||||||
|
).chain(CurveTween(curve: Curves.easeInOutSine)),
|
||||||
|
weight: 50,
|
||||||
|
),
|
||||||
|
TweenSequenceItem(
|
||||||
|
tween: Tween(
|
||||||
|
begin: peak,
|
||||||
|
end: 0.0,
|
||||||
|
).chain(CurveTween(curve: Curves.easeInOutSine)),
|
||||||
|
weight: 50,
|
||||||
|
),
|
||||||
|
]).animate(controller);
|
||||||
|
void onTick() {
|
||||||
|
if (scrollController.hasClients) {
|
||||||
|
scrollController.jumpTo(hint.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
hint.addListener(onTick);
|
||||||
|
await controller.forward();
|
||||||
|
hint.removeListener(onTick);
|
||||||
|
_scrollHintControllers.remove(controller);
|
||||||
|
controller.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
for (final controller in _scrollHintControllers) {
|
||||||
|
controller.dispose();
|
||||||
|
}
|
||||||
|
_selectionActionsScrollController.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A favorited folder switches to the Files tab, navigated there; a
|
||||||
|
/// favorited file just opens directly from here, like Files/Photos do -
|
||||||
|
/// no need to reposition Files first since dismissing the viewer lands
|
||||||
|
/// back on this tab either way.
|
||||||
|
void _openFavorite(
|
||||||
|
BuildContext context,
|
||||||
|
ServerProvider provider,
|
||||||
|
NextcloudItem item,
|
||||||
|
List<NextcloudItem> siblings,
|
||||||
|
) {
|
||||||
|
if (item.isFolder) {
|
||||||
|
provider.navigateToAbsoluteFolder(item.path);
|
||||||
|
provider.requestTab(AppTab.files);
|
||||||
|
} else {
|
||||||
|
Navigator.push(
|
||||||
|
context,
|
||||||
|
FileViewerScreen.route(item: item, siblings: siblings),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bulk actions shown in the sticky selection toolbar for the
|
||||||
|
/// currently-selected items - same set Files/Photos offer.
|
||||||
|
List<SelectionAction> _buildSelectionActions(
|
||||||
|
ServerProvider provider,
|
||||||
|
List<NextcloudItem> selected,
|
||||||
|
) {
|
||||||
|
return [
|
||||||
|
SelectionAction(
|
||||||
|
icon: Icons.favorite_border_rounded,
|
||||||
|
label: 'Remove from favorites',
|
||||||
|
onTap: () => _unfavoriteSelected(provider, selected),
|
||||||
|
),
|
||||||
|
SelectionAction(
|
||||||
|
icon: Icons.share_rounded,
|
||||||
|
label: 'Share',
|
||||||
|
onTap: () => selected.length == 1
|
||||||
|
? ShareSheet.show(context, selected.single)
|
||||||
|
: _shareSelected(context, provider, selected),
|
||||||
|
),
|
||||||
|
SelectionAction(
|
||||||
|
icon: Icons.download_rounded,
|
||||||
|
label: 'Download',
|
||||||
|
onTap: () => _downloadSelected(context, provider, selected),
|
||||||
|
),
|
||||||
|
SelectionAction(
|
||||||
|
icon: Icons.delete_outline_rounded,
|
||||||
|
label: 'Delete',
|
||||||
|
onTap: () => _confirmDeleteSelected(context, provider, selected),
|
||||||
|
),
|
||||||
|
SelectionAction(
|
||||||
|
icon: Icons.copy_rounded,
|
||||||
|
label: 'Copy',
|
||||||
|
onTap: () => _moveOrCopySelected(provider, selected, copy: true),
|
||||||
|
),
|
||||||
|
SelectionAction(
|
||||||
|
icon: Icons.drive_file_move_rounded,
|
||||||
|
label: 'Move',
|
||||||
|
onTap: () => _moveOrCopySelected(provider, selected, copy: false),
|
||||||
|
),
|
||||||
|
if (selected.length == 1)
|
||||||
|
SelectionAction(
|
||||||
|
icon: Icons.info_outline_rounded,
|
||||||
|
label: 'Details',
|
||||||
|
onTap: () => DetailsSheet.show(context, selected.single),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _unfavoriteSelected(
|
||||||
|
ServerProvider provider,
|
||||||
|
List<NextcloudItem> items,
|
||||||
|
) async {
|
||||||
|
for (final item in items) {
|
||||||
|
await provider.toggleItemFavorite(item);
|
||||||
|
}
|
||||||
|
_clearSelection();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _shareSelected(
|
||||||
|
BuildContext context,
|
||||||
|
ServerProvider provider,
|
||||||
|
List<NextcloudItem> items,
|
||||||
|
) async {
|
||||||
|
final messenger = ScaffoldMessenger.of(context);
|
||||||
|
messenger.showSnackBar(
|
||||||
|
const SnackBar(
|
||||||
|
content: Text('Creating share link(s)…'),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
final lines = <String>[];
|
||||||
|
for (final item in items) {
|
||||||
|
final link = await provider.createShareLink(item);
|
||||||
|
if (link != null) {
|
||||||
|
lines.add(items.length > 1 ? '${item.name}: $link' : link);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mounted) return;
|
||||||
|
messenger.hideCurrentSnackBar();
|
||||||
|
_clearSelection();
|
||||||
|
if (lines.isEmpty) {
|
||||||
|
messenger.showSnackBar(
|
||||||
|
const SnackBar(
|
||||||
|
content: Text('Could not create share link(s)'),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await SharePlus.instance.share(ShareParams(text: lines.join('\n')));
|
||||||
|
} catch (_) {
|
||||||
|
if (!mounted) return;
|
||||||
|
messenger.showSnackBar(
|
||||||
|
const SnackBar(
|
||||||
|
content: Text('Could not open the share sheet'),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hands the whole batch off to `DownloadService.kt` - see
|
||||||
|
/// `FilesView._downloadSelected`'s identical doc comment for why.
|
||||||
|
Future<void> _downloadSelected(
|
||||||
|
BuildContext context,
|
||||||
|
ServerProvider provider,
|
||||||
|
List<NextcloudItem> items,
|
||||||
|
) async {
|
||||||
|
final files = items.where((i) => !i.isFolder).toList();
|
||||||
|
_clearSelection();
|
||||||
|
if (files.isEmpty) return;
|
||||||
|
|
||||||
|
final messenger = ScaffoldMessenger.of(context);
|
||||||
|
try {
|
||||||
|
await DownloadService.startDownload(provider, files);
|
||||||
|
messenger.showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text(
|
||||||
|
files.length == 1
|
||||||
|
? 'Downloading ${files.first.name} - see the notification for progress'
|
||||||
|
: 'Downloading ${files.length} files - see the notification for progress',
|
||||||
|
),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
messenger.showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text('Could not start download: $e'),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _confirmDeleteSelected(
|
||||||
|
BuildContext context,
|
||||||
|
ServerProvider provider,
|
||||||
|
List<NextcloudItem> items,
|
||||||
|
) async {
|
||||||
|
final confirmed = await showDialog<bool>(
|
||||||
|
context: context,
|
||||||
|
builder: (dialogContext) {
|
||||||
|
return AlertDialog(
|
||||||
|
title: const Text('Delete Items'),
|
||||||
|
content: Text(
|
||||||
|
'Delete ${items.length} item(s) from the server? This cannot be undone.',
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.pop(dialogContext, false),
|
||||||
|
child: const Text('Cancel'),
|
||||||
|
),
|
||||||
|
FilledButton(
|
||||||
|
style: FilledButton.styleFrom(
|
||||||
|
backgroundColor: Theme.of(dialogContext).colorScheme.error,
|
||||||
|
),
|
||||||
|
onPressed: () => Navigator.pop(dialogContext, true),
|
||||||
|
child: const Text('Delete'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (confirmed != true || !context.mounted) return;
|
||||||
|
|
||||||
|
final messenger = ScaffoldMessenger.of(context);
|
||||||
|
var succeeded = 0;
|
||||||
|
for (final item in items) {
|
||||||
|
final success = await provider.deleteItem(item.path);
|
||||||
|
if (success) succeeded++;
|
||||||
|
}
|
||||||
|
|
||||||
|
_clearSelection();
|
||||||
|
messenger.showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text('Deleted $succeeded of ${items.length} item(s)'),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _moveOrCopySelected(
|
||||||
|
ServerProvider provider,
|
||||||
|
List<NextcloudItem> items, {
|
||||||
|
required bool copy,
|
||||||
|
}) async {
|
||||||
|
final result = await MoveCopyDestinationPicker.show(
|
||||||
|
context,
|
||||||
|
items,
|
||||||
|
copy: copy,
|
||||||
|
);
|
||||||
|
if (!mounted || result == null) return;
|
||||||
|
_clearSelection();
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text(
|
||||||
|
'${copy ? 'Copied' : 'Moved'} ${result.succeeded} of ${items.length} item(s)',
|
||||||
|
),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildControlsRow(ServerProvider provider) {
|
||||||
|
return SizedBox(
|
||||||
|
height: 44,
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
scrollDirection: Axis.horizontal,
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
IconButton(
|
||||||
|
icon: Icon(
|
||||||
|
provider.filesSortAscending
|
||||||
|
? Icons.arrow_upward_rounded
|
||||||
|
: Icons.arrow_downward_rounded,
|
||||||
|
size: 20,
|
||||||
|
),
|
||||||
|
visualDensity: VisualDensity.compact,
|
||||||
|
tooltip: provider.filesSortAscending ? 'Ascending' : 'Descending',
|
||||||
|
onPressed: provider.toggleFilesSortOrder,
|
||||||
|
),
|
||||||
|
SizedBox(
|
||||||
|
width: 130,
|
||||||
|
child: SortMenuButton(
|
||||||
|
field: provider.filesSortField,
|
||||||
|
onChanged: provider.setFilesSortField,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
ToggleIconButton(
|
||||||
|
icon: provider.showHiddenFiles
|
||||||
|
? Icons.visibility_rounded
|
||||||
|
: Icons.visibility_off_rounded,
|
||||||
|
isSelected: provider.showHiddenFiles,
|
||||||
|
onTap: () => provider.toggleShowHiddenFiles(),
|
||||||
|
tooltip: 'Show hidden files',
|
||||||
|
),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
SegmentedIconGroup(
|
||||||
|
children: [
|
||||||
|
ToggleIconButton(
|
||||||
|
icon: Symbols.circles_rounded,
|
||||||
|
isSelected: provider.storageScope == StorageScope.cloud,
|
||||||
|
onTap: () => provider.setStorageScope(StorageScope.cloud),
|
||||||
|
tooltip: 'Cloud storage',
|
||||||
|
),
|
||||||
|
ToggleIconButton(
|
||||||
|
icon: Symbols.hard_drive_rounded,
|
||||||
|
isSelected: provider.storageScope == StorageScope.external,
|
||||||
|
onTap: () => provider.setStorageScope(StorageScope.external),
|
||||||
|
tooltip: 'External storage',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
SegmentedIconGroup(
|
||||||
|
children: [
|
||||||
|
ToggleIconButton(
|
||||||
|
icon: Icons.view_list_rounded,
|
||||||
|
isSelected: !provider.isGridView,
|
||||||
|
onTap: () => provider.setGridView(false),
|
||||||
|
tooltip: 'List view',
|
||||||
|
),
|
||||||
|
ToggleIconButton(
|
||||||
|
icon: Icons.grid_view_rounded,
|
||||||
|
isSelected: provider.isGridView,
|
||||||
|
onTap: () => provider.setGridView(true),
|
||||||
|
tooltip: 'Grid view',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildListTile(
|
||||||
|
BuildContext context,
|
||||||
|
NextcloudItem item,
|
||||||
|
ServerProvider provider,
|
||||||
|
List<NextcloudItem> siblings,
|
||||||
|
) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final colorScheme = theme.colorScheme;
|
||||||
|
final isSelected = _selectedIds.contains(item.id);
|
||||||
|
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 8),
|
||||||
|
child: ClipRRect(
|
||||||
|
borderRadius: BorderRadius.circular(16),
|
||||||
|
child: Material(
|
||||||
|
color: isSelected
|
||||||
|
? colorScheme.primaryContainer.withValues(alpha: 0.5)
|
||||||
|
: colorScheme.surfaceContainerLow,
|
||||||
|
child: InkWell(
|
||||||
|
onTap: () {
|
||||||
|
if (_isSelecting) {
|
||||||
|
_toggleSelection(item);
|
||||||
|
} else {
|
||||||
|
_openFavorite(context, provider, item, siblings);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onLongPress: () => _toggleSelection(item),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
SelectableThumbnail(
|
||||||
|
isSelected: isSelected,
|
||||||
|
size: 44,
|
||||||
|
checkmarkSize: 24,
|
||||||
|
child: ItemThumbnail(
|
||||||
|
item: item,
|
||||||
|
provider: provider,
|
||||||
|
size: 44,
|
||||||
|
borderRadius: 12,
|
||||||
|
iconSize: 22,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 14),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
item.name,
|
||||||
|
style: theme.textTheme.titleMedium?.copyWith(
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
fontSize: 14,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
Text(
|
||||||
|
item.isFolder
|
||||||
|
? 'Folder'
|
||||||
|
: '${formatBytes(item.size)} • ${DateFormat.yMMMd().format(item.lastModified)}',
|
||||||
|
style: theme.textTheme.bodySmall?.copyWith(
|
||||||
|
color: colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildGridCard(
|
||||||
|
BuildContext context,
|
||||||
|
NextcloudItem item,
|
||||||
|
ServerProvider provider,
|
||||||
|
List<NextcloudItem> siblings,
|
||||||
|
) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final isSelected = _selectedIds.contains(item.id);
|
||||||
|
final isMedia =
|
||||||
|
(item.type == NextcloudItemType.image ||
|
||||||
|
item.type == NextcloudItemType.video) &&
|
||||||
|
item.previewUrl != null;
|
||||||
|
final iconColor = getIconColor(context, item.type);
|
||||||
|
|
||||||
|
return ClipRRect(
|
||||||
|
borderRadius: BorderRadius.circular(20),
|
||||||
|
child: Material(
|
||||||
|
color: theme.colorScheme.surfaceContainerLow,
|
||||||
|
child: InkWell(
|
||||||
|
onTap: () {
|
||||||
|
if (_isSelecting) {
|
||||||
|
_toggleSelection(item);
|
||||||
|
} else {
|
||||||
|
_openFavorite(context, provider, item, siblings);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onLongPress: () => _toggleSelection(item),
|
||||||
|
child: SelectableThumbnail(
|
||||||
|
isSelected: isSelected,
|
||||||
|
checkmarkSize: 32,
|
||||||
|
child: isMedia
|
||||||
|
? Image.network(
|
||||||
|
item.previewUrl!,
|
||||||
|
headers: provider.service?.authHeaders,
|
||||||
|
fit: BoxFit.cover,
|
||||||
|
filterQuality: FilterQuality.low,
|
||||||
|
gaplessPlayback: true,
|
||||||
|
errorBuilder: (ctx, err, stack) => Container(
|
||||||
|
color: theme.colorScheme.secondaryContainer,
|
||||||
|
child: Icon(
|
||||||
|
getItemIcon(item.type),
|
||||||
|
color: theme.colorScheme.onSecondaryContainer,
|
||||||
|
size: 32,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: Padding(
|
||||||
|
padding: const EdgeInsets.all(14),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||||
|
children: [
|
||||||
|
Container(
|
||||||
|
width: 40,
|
||||||
|
height: 40,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: iconColor.withValues(alpha: 0.12),
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
),
|
||||||
|
child: Icon(
|
||||||
|
getItemIcon(item.type),
|
||||||
|
color: iconColor,
|
||||||
|
size: 24,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Text(
|
||||||
|
item.name,
|
||||||
|
maxLines: 2,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: theme.textTheme.titleMedium?.copyWith(
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
fontSize: 13,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final colorScheme = theme.colorScheme;
|
||||||
|
final provider = context.watch<ServerProvider>();
|
||||||
|
|
||||||
|
if (!_requested) {
|
||||||
|
_requested = true;
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback(
|
||||||
|
(_) => provider.fetchAllFavorites(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
final favorites = provider.favoriteItems;
|
||||||
|
final siblings = favorites.where((i) => !i.isFolder).toList();
|
||||||
|
final selectedItems = favorites
|
||||||
|
.where((i) => _selectedIds.contains(i.id))
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
final contentSlivers = <Widget>[
|
||||||
|
SliverPersistentHeader(
|
||||||
|
pinned: !_isSelecting,
|
||||||
|
delegate: StickyHeaderDelegate(
|
||||||
|
height: 60,
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
|
||||||
|
child: _buildControlsRow(provider),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SliverToBoxAdapter(child: SizedBox(height: 8)),
|
||||||
|
if (provider.isFavoritesLoading && favorites.isEmpty)
|
||||||
|
const SliverFillRemaining(
|
||||||
|
hasScrollBody: false,
|
||||||
|
child: Center(child: CircularProgressIndicator()),
|
||||||
|
)
|
||||||
|
else if (provider.favoritesErrorMessage != null)
|
||||||
|
SliverFillRemaining(
|
||||||
|
hasScrollBody: false,
|
||||||
|
child: Center(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(24),
|
||||||
|
child: Column(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.error_outline_rounded,
|
||||||
|
size: 64,
|
||||||
|
color: colorScheme.error,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
Text(
|
||||||
|
'Could not load favorites',
|
||||||
|
style: theme.textTheme.titleLarge?.copyWith(
|
||||||
|
color: colorScheme.error,
|
||||||
|
fontWeight: FontWeight.bold,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Text(
|
||||||
|
provider.favoritesErrorMessage!,
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: theme.textTheme.bodyMedium?.copyWith(
|
||||||
|
color: colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 20),
|
||||||
|
FilledButton.icon(
|
||||||
|
onPressed: provider.fetchAllFavorites,
|
||||||
|
icon: const Icon(Icons.refresh_rounded),
|
||||||
|
label: const Text('Retry'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (favorites.isEmpty)
|
||||||
|
SliverFillRemaining(
|
||||||
|
hasScrollBody: false,
|
||||||
|
child: Center(
|
||||||
|
child: Column(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.favorite_border_rounded,
|
||||||
|
size: 64,
|
||||||
|
color: colorScheme.outlineVariant,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
Text(
|
||||||
|
'No favorites yet',
|
||||||
|
style: theme.textTheme.titleMedium?.copyWith(
|
||||||
|
color: colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (provider.isGridView)
|
||||||
|
SliverPadding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
|
||||||
|
sliver: SliverGrid(
|
||||||
|
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
|
||||||
|
crossAxisCount: 2,
|
||||||
|
childAspectRatio: 1.1,
|
||||||
|
crossAxisSpacing: 12,
|
||||||
|
mainAxisSpacing: 12,
|
||||||
|
),
|
||||||
|
delegate: SliverChildBuilderDelegate((context, index) {
|
||||||
|
return _buildGridCard(
|
||||||
|
context,
|
||||||
|
favorites[index],
|
||||||
|
provider,
|
||||||
|
siblings,
|
||||||
|
);
|
||||||
|
}, childCount: favorites.length),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
SliverPadding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
|
||||||
|
sliver: SliverList(
|
||||||
|
delegate: SliverChildBuilderDelegate((context, index) {
|
||||||
|
return _buildListTile(
|
||||||
|
context,
|
||||||
|
favorites[index],
|
||||||
|
provider,
|
||||||
|
siblings,
|
||||||
|
);
|
||||||
|
}, childCount: favorites.length),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SliverToBoxAdapter(child: SizedBox(height: 100)),
|
||||||
|
const SliverFillRemaining(hasScrollBody: false, child: SizedBox()),
|
||||||
|
];
|
||||||
|
|
||||||
|
return PopScope(
|
||||||
|
canPop: !_isSelecting,
|
||||||
|
onPopInvokedWithResult: (didPop, result) {
|
||||||
|
if (!didPop && _isSelecting) _clearSelection();
|
||||||
|
},
|
||||||
|
child: SyncedHeaderScaffold(
|
||||||
|
scrollController: widget.scrollController,
|
||||||
|
provider: provider,
|
||||||
|
actions: const [MoreTabsButton(), ProfileAvatarButton()],
|
||||||
|
onRefresh: provider.fetchAllFavorites,
|
||||||
|
selectionBar: _isSelecting
|
||||||
|
? _buildSelectionBar(context, theme, provider, selectedItems)
|
||||||
|
: null,
|
||||||
|
contentSlivers: contentSlivers,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replaces the top bar entirely while selecting (see
|
||||||
|
/// `SyncedHeaderScaffold.selectionBar`) - mirrors Files/Photos' identical
|
||||||
|
/// selection bar.
|
||||||
|
Widget _buildSelectionBar(
|
||||||
|
BuildContext context,
|
||||||
|
ThemeData theme,
|
||||||
|
ServerProvider provider,
|
||||||
|
List<NextcloudItem> selectedItems,
|
||||||
|
) {
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
width: MediaQuery.of(context).size.width * 0.5,
|
||||||
|
child: Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.close_rounded, size: 20),
|
||||||
|
tooltip: 'Cancel selection',
|
||||||
|
onPressed: _clearSelection,
|
||||||
|
visualDensity: VisualDensity.compact,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Text(
|
||||||
|
'${selectedItems.length} selected',
|
||||||
|
style: theme.textTheme.titleSmall?.copyWith(
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Expanded(
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
controller: _selectionActionsScrollController,
|
||||||
|
scrollDirection: Axis.horizontal,
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
for (final action in _buildSelectionActions(
|
||||||
|
provider,
|
||||||
|
selectedItems,
|
||||||
|
))
|
||||||
|
IconButton(
|
||||||
|
icon: Icon(action.icon, size: 20),
|
||||||
|
tooltip: action.label,
|
||||||
|
onPressed: action.onTap,
|
||||||
|
visualDensity: VisualDensity.compact,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,7 @@
|
|||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
import 'dart:math' as math;
|
import 'dart:math' as math;
|
||||||
import 'dart:typed_data';
|
import 'dart:typed_data';
|
||||||
import 'package:file_saver/file_saver.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:marquee/marquee.dart';
|
|
||||||
import 'package:open_file/open_file.dart';
|
import 'package:open_file/open_file.dart';
|
||||||
import 'package:path/path.dart' as p;
|
import 'package:path/path.dart' as p;
|
||||||
import 'package:path_provider/path_provider.dart';
|
import 'package:path_provider/path_provider.dart';
|
||||||
@@ -12,8 +10,10 @@ import 'package:provider/provider.dart';
|
|||||||
import 'package:video_player/video_player.dart';
|
import 'package:video_player/video_player.dart';
|
||||||
import '../models/nextcloud_item.dart';
|
import '../models/nextcloud_item.dart';
|
||||||
import '../providers/server_provider.dart';
|
import '../providers/server_provider.dart';
|
||||||
|
import '../services/download_service.dart';
|
||||||
import '../widgets/details/details_sheet.dart';
|
import '../widgets/details/details_sheet.dart';
|
||||||
import '../widgets/frosted_glass_container.dart';
|
import '../widgets/frosted_glass_container.dart';
|
||||||
|
import '../widgets/marquee_title.dart';
|
||||||
import '../widgets/seek_bar_painter.dart';
|
import '../widgets/seek_bar_painter.dart';
|
||||||
import '../widgets/share_sheet.dart';
|
import '../widgets/share_sheet.dart';
|
||||||
|
|
||||||
@@ -189,21 +189,22 @@ class _FileViewerScreenState extends State<FileViewerScreen> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Hands off to `DownloadService.kt` (see its doc comment) rather than
|
||||||
|
/// downloading in Dart then prompting `file_saver` - same reasoning as
|
||||||
|
/// `UploadService`/`ShareUploadService.kt` on the upload side: a real
|
||||||
|
/// Android Service survives the app being closed mid-download, and one
|
||||||
|
/// notification covers progress/cancel instead of blocking this screen.
|
||||||
Future<void> _downloadToDevice(ServerProvider provider) async {
|
Future<void> _downloadToDevice(ServerProvider provider) async {
|
||||||
final item = _currentItem;
|
final item = _currentItem;
|
||||||
setState(() => _isBusy = true);
|
|
||||||
try {
|
try {
|
||||||
final tempPath = await _downloadToTemp(provider, item);
|
await DownloadService.startDownload(provider, [item]);
|
||||||
final ext = p.extension(item.name).replaceFirst('.', '');
|
|
||||||
final baseName = p.basenameWithoutExtension(item.name);
|
|
||||||
await FileSaver.instance.saveFile(
|
|
||||||
name: baseName,
|
|
||||||
filePath: tempPath,
|
|
||||||
ext: ext,
|
|
||||||
);
|
|
||||||
if (mounted) {
|
if (mounted) {
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
SnackBar(content: Text('Saved ${item.name} to Downloads')),
|
SnackBar(
|
||||||
|
content: Text(
|
||||||
|
'Downloading ${item.name} - see the notification for progress',
|
||||||
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -212,8 +213,6 @@ class _FileViewerScreenState extends State<FileViewerScreen> {
|
|||||||
context,
|
context,
|
||||||
).showSnackBar(SnackBar(content: Text('Download failed: $e')));
|
).showSnackBar(SnackBar(content: Text('Download failed: $e')));
|
||||||
}
|
}
|
||||||
} finally {
|
|
||||||
if (mounted) setState(() => _isBusy = false);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -339,7 +338,7 @@ class _FileViewerScreenState extends State<FileViewerScreen> {
|
|||||||
),
|
),
|
||||||
const SizedBox(width: 4),
|
const SizedBox(width: 4),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: _MarqueeTitle(
|
child: MarqueeTitle(
|
||||||
text: _currentItem.name,
|
text: _currentItem.name,
|
||||||
style: Theme.of(context).textTheme.titleSmall
|
style: Theme.of(context).textTheme.titleSmall
|
||||||
?.copyWith(
|
?.copyWith(
|
||||||
@@ -562,53 +561,6 @@ class _ActionIconButton extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The media viewer's title: a plain, single-line ellipsized [Text] for
|
|
||||||
/// names that fit, or an auto-scrolling [Marquee] for names too long for
|
|
||||||
/// the available width - measured once via [TextPainter] rather than
|
|
||||||
/// always marqueeing, so a short filename just sits still like normal.
|
|
||||||
class _MarqueeTitle extends StatelessWidget {
|
|
||||||
final String text;
|
|
||||||
final TextStyle? style;
|
|
||||||
|
|
||||||
const _MarqueeTitle({required this.text, required this.style});
|
|
||||||
|
|
||||||
@override
|
|
||||||
Widget build(BuildContext context) {
|
|
||||||
return LayoutBuilder(
|
|
||||||
builder: (context, constraints) {
|
|
||||||
final painter = TextPainter(
|
|
||||||
text: TextSpan(text: text, style: style),
|
|
||||||
maxLines: 1,
|
|
||||||
textDirection: Directionality.of(context),
|
|
||||||
)..layout(maxWidth: double.infinity);
|
|
||||||
|
|
||||||
if (painter.width <= constraints.maxWidth) {
|
|
||||||
return Text(
|
|
||||||
text,
|
|
||||||
maxLines: 1,
|
|
||||||
overflow: TextOverflow.ellipsis,
|
|
||||||
style: style,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return SizedBox(
|
|
||||||
height: painter.height,
|
|
||||||
child: Marquee(
|
|
||||||
text: text,
|
|
||||||
style: style,
|
|
||||||
blankSpace: 48,
|
|
||||||
velocity: 30,
|
|
||||||
startPadding: 0,
|
|
||||||
pauseAfterRound: const Duration(seconds: 1),
|
|
||||||
fadingEdgeStartFraction: 0.1,
|
|
||||||
fadingEdgeEndFraction: 0.15,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class _ImagePreview extends StatefulWidget {
|
class _ImagePreview extends StatefulWidget {
|
||||||
final String url;
|
final String url;
|
||||||
final Map<String, String> headers;
|
final Map<String, String> headers;
|
||||||
|
|||||||
+336
-165
@@ -5,12 +5,13 @@ import 'package:flutter/services.dart';
|
|||||||
import 'package:intl/intl.dart';
|
import 'package:intl/intl.dart';
|
||||||
import 'package:material_symbols_icons/symbols.dart';
|
import 'package:material_symbols_icons/symbols.dart';
|
||||||
import 'package:path/path.dart' as p;
|
import 'package:path/path.dart' as p;
|
||||||
import 'package:path_provider/path_provider.dart';
|
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
import 'package:share_plus/share_plus.dart';
|
import 'package:share_plus/share_plus.dart';
|
||||||
import '../models/nextcloud_item.dart';
|
import '../models/nextcloud_item.dart';
|
||||||
import '../models/selection_action.dart';
|
import '../models/selection_action.dart';
|
||||||
import '../providers/server_provider.dart';
|
import '../providers/server_provider.dart';
|
||||||
|
import '../services/download_service.dart';
|
||||||
|
import '../services/share_intent_service.dart';
|
||||||
import '../widgets/breadcrumbs.dart';
|
import '../widgets/breadcrumbs.dart';
|
||||||
import '../widgets/details/details_sheet.dart';
|
import '../widgets/details/details_sheet.dart';
|
||||||
import '../widgets/item_icon.dart';
|
import '../widgets/item_icon.dart';
|
||||||
@@ -22,8 +23,11 @@ import '../widgets/share_sheet.dart';
|
|||||||
import '../widgets/sort_menu_button.dart';
|
import '../widgets/sort_menu_button.dart';
|
||||||
import '../widgets/sticky_header_delegate.dart';
|
import '../widgets/sticky_header_delegate.dart';
|
||||||
import '../widgets/swipeable_item.dart';
|
import '../widgets/swipeable_item.dart';
|
||||||
|
import '../widgets/sync_status_badge.dart';
|
||||||
import '../widgets/synced_header_scaffold.dart';
|
import '../widgets/synced_header_scaffold.dart';
|
||||||
import 'file_viewer_screen.dart';
|
import 'file_viewer_screen.dart';
|
||||||
|
import 'move_copy_destination_picker.dart';
|
||||||
|
import 'share_upload_view.dart';
|
||||||
|
|
||||||
class FilesView extends StatefulWidget {
|
class FilesView extends StatefulWidget {
|
||||||
final ScrollController scrollController;
|
final ScrollController scrollController;
|
||||||
@@ -97,10 +101,13 @@ class _FolderEnterAnimationState extends State<_FolderEnterAnimation>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class _FilesViewState extends State<FilesView> {
|
class _FilesViewState extends State<FilesView>
|
||||||
|
with SingleTickerProviderStateMixin {
|
||||||
final Set<String> _selectedIds = {};
|
final Set<String> _selectedIds = {};
|
||||||
int _lastPathDepth = 1;
|
int _lastPathDepth = 1;
|
||||||
final ScrollController _controlsScrollController = ScrollController();
|
final ScrollController _controlsScrollController = ScrollController();
|
||||||
|
final ScrollController _selectionActionsScrollController = ScrollController();
|
||||||
|
final List<AnimationController> _scrollHintControllers = [];
|
||||||
|
|
||||||
bool get _isSelecting => _selectedIds.isNotEmpty;
|
bool get _isSelecting => _selectedIds.isNotEmpty;
|
||||||
|
|
||||||
@@ -108,59 +115,135 @@ class _FilesViewState extends State<FilesView> {
|
|||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
WidgetsBinding.instance.addPostFrameCallback(
|
WidgetsBinding.instance.addPostFrameCallback(
|
||||||
(_) => _playControlsScrollHint(),
|
(_) => _playScrollHint(_controlsScrollController),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A one-shot hint that the controls row scrolls: nudges it a little to
|
/// A one-shot hint that a horizontally-scrollable row actually scrolls:
|
||||||
/// the right and back, once, right after it first appears - a motion cue
|
/// nudges it a little to the right and back, once - a motion cue instead
|
||||||
/// instead of a persistent widget (a chevron badge, an edge fade) sitting
|
/// of a persistent widget (a chevron badge, an edge fade) sitting on top
|
||||||
/// on top of the actual controls the whole time. No-ops if there's
|
/// of the actual controls the whole time. Shared by the controls row
|
||||||
/// nothing to scroll (row already fits).
|
/// (played once it first appears) and the selection actions row (played
|
||||||
Future<void> _playControlsScrollHint() async {
|
/// the first time a selection starts, see `_toggleSelection`). No-ops if
|
||||||
|
/// there's nothing to scroll (row already fits).
|
||||||
|
Future<void> _playScrollHint(ScrollController scrollController) async {
|
||||||
// The delay lets the row's first frame (and its actual layout/max
|
// The delay lets the row's first frame (and its actual layout/max
|
||||||
// scroll extent) settle before nudging it, and reads more like a
|
// scroll extent) settle before nudging it, and reads more like a
|
||||||
// deliberate hint than something that happens to fire on load.
|
// deliberate hint than something that happens to fire on load.
|
||||||
await Future.delayed(const Duration(milliseconds: 500));
|
await Future.delayed(const Duration(milliseconds: 500));
|
||||||
if (!mounted || !_controlsScrollController.hasClients) return;
|
if (!mounted || !scrollController.hasClients) return;
|
||||||
final maxExtent = _controlsScrollController.position.maxScrollExtent;
|
final maxExtent = scrollController.position.maxScrollExtent;
|
||||||
if (maxExtent <= 0) return;
|
if (maxExtent <= 0) return;
|
||||||
await _controlsScrollController.animateTo(
|
final double peak = maxExtent < 36 ? maxExtent : 36;
|
||||||
maxExtent < 36 ? maxExtent : 36,
|
// Driven as a single controller (rather than two chained animateTo
|
||||||
duration: const Duration(milliseconds: 320),
|
// calls) with mirrored ease-in-out halves, so the motion decelerates
|
||||||
curve: Curves.easeOut,
|
// smoothly into the peak and back out instead of visibly changing
|
||||||
);
|
// pace where the two legs meet.
|
||||||
if (!mounted || !_controlsScrollController.hasClients) return;
|
final controller = AnimationController(
|
||||||
await _controlsScrollController.animateTo(
|
vsync: this,
|
||||||
0,
|
duration: const Duration(milliseconds: 900),
|
||||||
duration: const Duration(milliseconds: 320),
|
|
||||||
curve: Curves.easeIn,
|
|
||||||
);
|
);
|
||||||
|
_scrollHintControllers.add(controller);
|
||||||
|
final hint = TweenSequence<double>([
|
||||||
|
TweenSequenceItem(
|
||||||
|
tween: Tween(
|
||||||
|
begin: 0.0,
|
||||||
|
end: peak,
|
||||||
|
).chain(CurveTween(curve: Curves.easeInOutSine)),
|
||||||
|
weight: 50,
|
||||||
|
),
|
||||||
|
TweenSequenceItem(
|
||||||
|
tween: Tween(
|
||||||
|
begin: peak,
|
||||||
|
end: 0.0,
|
||||||
|
).chain(CurveTween(curve: Curves.easeInOutSine)),
|
||||||
|
weight: 50,
|
||||||
|
),
|
||||||
|
]).animate(controller);
|
||||||
|
void onTick() {
|
||||||
|
if (scrollController.hasClients) {
|
||||||
|
scrollController.jumpTo(hint.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
hint.addListener(onTick);
|
||||||
|
await controller.forward();
|
||||||
|
hint.removeListener(onTick);
|
||||||
|
_scrollHintControllers.remove(controller);
|
||||||
|
controller.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
|
for (final controller in _scrollHintControllers) {
|
||||||
|
controller.dispose();
|
||||||
|
}
|
||||||
_controlsScrollController.dispose();
|
_controlsScrollController.dispose();
|
||||||
|
_selectionActionsScrollController.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
void _toggleSelection(NextcloudItem item) {
|
void _toggleSelection(NextcloudItem item) {
|
||||||
HapticFeedback.selectionClick();
|
HapticFeedback.selectionClick();
|
||||||
|
final enteringSelection = _selectedIds.isEmpty;
|
||||||
setState(() {
|
setState(() {
|
||||||
if (!_selectedIds.remove(item.id)) _selectedIds.add(item.id);
|
if (!_selectedIds.remove(item.id)) _selectedIds.add(item.id);
|
||||||
});
|
});
|
||||||
|
if (enteringSelection && _isSelecting) {
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback(
|
||||||
|
(_) => _playScrollHint(_selectionActionsScrollController),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void _clearSelection() {
|
void _clearSelection() {
|
||||||
setState(_selectedIds.clear);
|
setState(_selectedIds.clear);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Routes a tap on an item while Noo is acting as another app's picker:
|
||||||
|
/// folders are still browsable, a matching file either toggles selection
|
||||||
|
/// (multi-select requests) or immediately finishes the pick, and a
|
||||||
|
/// non-matching file (wrong mime type for the caller) is rejected.
|
||||||
|
void _handlePickTap(
|
||||||
|
BuildContext context,
|
||||||
|
ServerProvider provider,
|
||||||
|
NextcloudItem item,
|
||||||
|
) {
|
||||||
|
if (item.isFolder) {
|
||||||
|
provider.navigateToFolder(item.path);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!provider.itemMatchesPickFilter(item)) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
const SnackBar(
|
||||||
|
content: Text("This app can't accept this file type"),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (provider.pickRequest!.allowMultiple) {
|
||||||
|
_toggleSelection(item);
|
||||||
|
} else {
|
||||||
|
provider.confirmPick([item]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The bulk actions shown in the sticky selection toolbar for the
|
/// The bulk actions shown in the sticky selection toolbar for the
|
||||||
/// currently-selected items.
|
/// currently-selected items.
|
||||||
List<SelectionAction> _buildSelectionActions(
|
List<SelectionAction> _buildSelectionActions(
|
||||||
ServerProvider provider,
|
ServerProvider provider,
|
||||||
List<NextcloudItem> selected,
|
List<NextcloudItem> selected,
|
||||||
) {
|
) {
|
||||||
|
if (provider.isPicking) {
|
||||||
|
return [
|
||||||
|
SelectionAction(
|
||||||
|
icon: Icons.check_rounded,
|
||||||
|
label: 'Use ${selected.length} item(s)',
|
||||||
|
onTap: () => provider.confirmPick(selected),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
return [
|
return [
|
||||||
SelectionAction(
|
SelectionAction(
|
||||||
icon: selected.every((i) => i.isFavorite)
|
icon: selected.every((i) => i.isFavorite)
|
||||||
@@ -169,7 +252,6 @@ class _FilesViewState extends State<FilesView> {
|
|||||||
label: selected.every((i) => i.isFavorite)
|
label: selected.every((i) => i.isFavorite)
|
||||||
? 'Remove from favorites'
|
? 'Remove from favorites'
|
||||||
: 'Favorite',
|
: 'Favorite',
|
||||||
color: Colors.red.shade400,
|
|
||||||
onTap: () => _favoriteSelected(provider, selected),
|
onTap: () => _favoriteSelected(provider, selected),
|
||||||
),
|
),
|
||||||
SelectionAction(
|
SelectionAction(
|
||||||
@@ -187,15 +269,36 @@ class _FilesViewState extends State<FilesView> {
|
|||||||
SelectionAction(
|
SelectionAction(
|
||||||
icon: Icons.delete_outline_rounded,
|
icon: Icons.delete_outline_rounded,
|
||||||
label: 'Delete',
|
label: 'Delete',
|
||||||
color: Theme.of(context).colorScheme.error,
|
|
||||||
onTap: () => _confirmDeleteSelected(context, provider, selected),
|
onTap: () => _confirmDeleteSelected(context, provider, selected),
|
||||||
),
|
),
|
||||||
|
SelectionAction(
|
||||||
|
icon: Icons.copy_rounded,
|
||||||
|
label: 'Copy',
|
||||||
|
onTap: () => _moveOrCopySelected(provider, selected, copy: true),
|
||||||
|
),
|
||||||
|
SelectionAction(
|
||||||
|
icon: Icons.drive_file_move_rounded,
|
||||||
|
label: 'Move',
|
||||||
|
onTap: () => _moveOrCopySelected(provider, selected, copy: false),
|
||||||
|
),
|
||||||
if (selected.length == 1)
|
if (selected.length == 1)
|
||||||
SelectionAction(
|
SelectionAction(
|
||||||
icon: Icons.drive_file_rename_outline_rounded,
|
icon: Icons.drive_file_rename_outline_rounded,
|
||||||
label: 'Rename',
|
label: 'Rename',
|
||||||
onTap: () => _renameItem(provider, selected.single),
|
onTap: () => _renameItem(provider, selected.single),
|
||||||
),
|
),
|
||||||
|
if (selected.length == 1)
|
||||||
|
SelectionAction(
|
||||||
|
icon: provider.isPathSynced(selected.single.path)
|
||||||
|
? Icons.sync_rounded
|
||||||
|
: Icons.sync_outlined,
|
||||||
|
label: provider.isPathSynced(selected.single.path)
|
||||||
|
? 'Stop syncing to device'
|
||||||
|
: 'Sync to device',
|
||||||
|
onTap: () => provider.isPathSynced(selected.single.path)
|
||||||
|
? provider.removeSyncedPath(selected.single.path)
|
||||||
|
: provider.addSyncedPath(selected.single.path),
|
||||||
|
),
|
||||||
if (selected.length == 1)
|
if (selected.length == 1)
|
||||||
SelectionAction(
|
SelectionAction(
|
||||||
icon: Icons.info_outline_rounded,
|
icon: Icons.info_outline_rounded,
|
||||||
@@ -363,15 +466,6 @@ class _FilesViewState extends State<FilesView> {
|
|||||||
onChanged: provider.setFilesSortField,
|
onChanged: provider.setFilesSortField,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
ToggleIconButton(
|
|
||||||
icon: provider.showFavoritesOnlyFiles
|
|
||||||
? Icons.favorite_rounded
|
|
||||||
: Icons.favorite_border_rounded,
|
|
||||||
isSelected: provider.showFavoritesOnlyFiles,
|
|
||||||
onTap: provider.toggleFavoritesFilterFiles,
|
|
||||||
tooltip: 'Favorites only',
|
|
||||||
),
|
|
||||||
const SizedBox(width: 4),
|
|
||||||
ToggleIconButton(
|
ToggleIconButton(
|
||||||
icon: provider.showHiddenFiles
|
icon: provider.showHiddenFiles
|
||||||
? Icons.visibility_rounded
|
? Icons.visibility_rounded
|
||||||
@@ -469,8 +563,9 @@ class _FilesViewState extends State<FilesView> {
|
|||||||
);
|
);
|
||||||
|
|
||||||
final List<Widget> contentSlivers = [
|
final List<Widget> contentSlivers = [
|
||||||
// Sticky while browsing; once selecting, the toolbar below takes over
|
// Sticky while browsing; once selecting, the selection bar takes over
|
||||||
// the pinned slot and this is free to scroll away.
|
// the very top of the screen instead (see `selectionBar` below), so
|
||||||
|
// this is free to scroll away rather than staying pinned under it.
|
||||||
SliverPersistentHeader(
|
SliverPersistentHeader(
|
||||||
pinned: !_isSelecting,
|
pinned: !_isSelecting,
|
||||||
delegate: StickyHeaderDelegate(
|
delegate: StickyHeaderDelegate(
|
||||||
@@ -478,56 +573,6 @@ class _FilesViewState extends State<FilesView> {
|
|||||||
child: controlsRow,
|
child: controlsRow,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
if (_isSelecting)
|
|
||||||
SliverAppBar(
|
|
||||||
pinned: true,
|
|
||||||
// This isn't the scroll view's topmost sliver - the Synced
|
|
||||||
// header above it already reserves status-bar space, so leaving
|
|
||||||
// this at its default `primary: true` double-reserves it too,
|
|
||||||
// showing up as a big empty gap above the toolbar.
|
|
||||||
primary: false,
|
|
||||||
automaticallyImplyLeading: false,
|
|
||||||
toolbarHeight: 48,
|
|
||||||
// No leading/actions slots - everything lives in `title`, wrapped
|
|
||||||
// in the exact same 16px horizontal Padding as the controls row
|
|
||||||
// above it, so the two rows' content lines up edge-to-edge
|
|
||||||
// instead of relying on SliverAppBar's own leadingWidth/actions
|
|
||||||
// insets (which don't match the controls row's).
|
|
||||||
titleSpacing: 0,
|
|
||||||
title: Padding(
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
IconButton(
|
|
||||||
icon: const Icon(Icons.close_rounded, size: 20),
|
|
||||||
tooltip: 'Cancel selection',
|
|
||||||
onPressed: _clearSelection,
|
|
||||||
visualDensity: VisualDensity.compact,
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Expanded(
|
|
||||||
child: Text(
|
|
||||||
'${selectedItems.length} selected',
|
|
||||||
style: theme.textTheme.titleSmall?.copyWith(
|
|
||||||
fontWeight: FontWeight.w700,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
for (final action in _buildSelectionActions(
|
|
||||||
provider,
|
|
||||||
selectedItems,
|
|
||||||
))
|
|
||||||
IconButton(
|
|
||||||
icon: Icon(action.icon, size: 20, color: action.color),
|
|
||||||
tooltip: action.label,
|
|
||||||
onPressed: action.onTap,
|
|
||||||
visualDensity: VisualDensity.compact,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
|
|
||||||
// Files List / Grid
|
// Files List / Grid
|
||||||
if (provider.isLoading)
|
if (provider.isLoading)
|
||||||
const SliverFillRemaining(
|
const SliverFillRemaining(
|
||||||
@@ -669,11 +714,81 @@ class _FilesViewState extends State<FilesView> {
|
|||||||
const MoreTabsButton(),
|
const MoreTabsButton(),
|
||||||
const ProfileAvatarButton(),
|
const ProfileAvatarButton(),
|
||||||
],
|
],
|
||||||
|
selectionBar: _isSelecting
|
||||||
|
? _buildSelectionBar(context, theme, provider, selectedItems)
|
||||||
|
: null,
|
||||||
contentSlivers: contentSlivers,
|
contentSlivers: contentSlivers,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Replaces the top bar entirely while selecting (see
|
||||||
|
/// `SyncedHeaderScaffold.selectionBar`) - a close button, the "N
|
||||||
|
/// selected" count, and the horizontally-scrollable bulk actions.
|
||||||
|
Widget _buildSelectionBar(
|
||||||
|
BuildContext context,
|
||||||
|
ThemeData theme,
|
||||||
|
ServerProvider provider,
|
||||||
|
List<NextcloudItem> selectedItems,
|
||||||
|
) {
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
width: MediaQuery.of(context).size.width * 0.5,
|
||||||
|
child: Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.close_rounded, size: 20),
|
||||||
|
tooltip: 'Cancel selection',
|
||||||
|
onPressed: _clearSelection,
|
||||||
|
visualDensity: VisualDensity.compact,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Text(
|
||||||
|
'${selectedItems.length} selected',
|
||||||
|
style: theme.textTheme.titleSmall?.copyWith(
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Expanded(
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
controller: _selectionActionsScrollController,
|
||||||
|
scrollDirection: Axis.horizontal,
|
||||||
|
// Left-aligned (not anchored to the trailing edge) so the
|
||||||
|
// first action's left edge sits at a fixed spot - lining up
|
||||||
|
// with the controls row's own first icon directly below it -
|
||||||
|
// regardless of how many actions there are.
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
for (final action in _buildSelectionActions(
|
||||||
|
provider,
|
||||||
|
selectedItems,
|
||||||
|
))
|
||||||
|
IconButton(
|
||||||
|
icon: Icon(action.icon, size: 20),
|
||||||
|
tooltip: action.label,
|
||||||
|
onPressed: action.onTap,
|
||||||
|
visualDensity: VisualDensity.compact,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _favoriteSelected(
|
Future<void> _favoriteSelected(
|
||||||
ServerProvider provider,
|
ServerProvider provider,
|
||||||
List<NextcloudItem> items,
|
List<NextcloudItem> items,
|
||||||
@@ -687,46 +802,82 @@ class _FilesViewState extends State<FilesView> {
|
|||||||
_clearSelection();
|
_clearSelection();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Hands the whole batch off to `DownloadService.kt` (see its doc
|
||||||
|
/// comment) rather than downloading each item in Dart then prompting
|
||||||
|
/// `file_saver` per file - same reasoning as `UploadService`/
|
||||||
|
/// `ShareUploadService.kt` on the upload side: a real Android Service
|
||||||
|
/// survives the app being closed mid-download, with one cancellable
|
||||||
|
/// notification for the whole selection instead of blocking here.
|
||||||
Future<void> _downloadSelected(
|
Future<void> _downloadSelected(
|
||||||
BuildContext context,
|
BuildContext context,
|
||||||
ServerProvider provider,
|
ServerProvider provider,
|
||||||
List<NextcloudItem> items,
|
List<NextcloudItem> items,
|
||||||
) async {
|
) async {
|
||||||
final messenger = ScaffoldMessenger.of(context);
|
final files = items.where((i) => !i.isFolder).toList();
|
||||||
messenger.showSnackBar(
|
_clearSelection();
|
||||||
SnackBar(
|
if (files.isEmpty) return;
|
||||||
content: Text('Downloading ${items.length} item(s)...'),
|
|
||||||
behavior: SnackBarBehavior.floating,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
var succeeded = 0;
|
final messenger = ScaffoldMessenger.of(context);
|
||||||
for (final item in items) {
|
|
||||||
if (item.isFolder) continue;
|
// Already mirrored locally by device sync (every selected file, not
|
||||||
|
// just some)? Save straight from the local copy instead of a fresh
|
||||||
|
// network fetch through DownloadService - see
|
||||||
|
// ServerProvider.localSyncedFilePath.
|
||||||
|
final localPaths = await Future.wait(
|
||||||
|
files.map(provider.localSyncedFilePath),
|
||||||
|
);
|
||||||
|
if (localPaths.every((path) => path != null)) {
|
||||||
try {
|
try {
|
||||||
final tempDir = await getTemporaryDirectory();
|
for (var i = 0; i < files.length; i++) {
|
||||||
final tempPath = p.join(tempDir.path, item.name);
|
final ext = p.extension(files[i].name).replaceFirst('.', '');
|
||||||
await provider.service!.downloadToFile(item.path, tempPath);
|
final baseName = p.basenameWithoutExtension(files[i].name);
|
||||||
final ext = p.extension(item.name).replaceFirst('.', '');
|
|
||||||
final baseName = p.basenameWithoutExtension(item.name);
|
|
||||||
await FileSaver.instance.saveFile(
|
await FileSaver.instance.saveFile(
|
||||||
name: baseName,
|
name: baseName,
|
||||||
filePath: tempPath,
|
filePath: localPaths[i]!,
|
||||||
ext: ext,
|
ext: ext,
|
||||||
);
|
);
|
||||||
succeeded++;
|
|
||||||
} catch (_) {
|
|
||||||
// Reported in the summary snackbar below.
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
_clearSelection();
|
|
||||||
messenger.showSnackBar(
|
messenger.showSnackBar(
|
||||||
SnackBar(
|
SnackBar(
|
||||||
content: Text('Downloaded $succeeded of ${items.length} item(s)'),
|
content: Text(
|
||||||
|
files.length == 1
|
||||||
|
? 'Downloaded ${files.first.name}'
|
||||||
|
: 'Downloaded ${files.length} files',
|
||||||
|
),
|
||||||
behavior: SnackBarBehavior.floating,
|
behavior: SnackBarBehavior.floating,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
} catch (e) {
|
||||||
|
messenger.showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text('Could not save file(s): $e'),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await DownloadService.startDownload(provider, files);
|
||||||
|
messenger.showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text(
|
||||||
|
files.length == 1
|
||||||
|
? 'Downloading ${files.first.name} - see the notification for progress'
|
||||||
|
: 'Downloading ${files.length} files - see the notification for progress',
|
||||||
|
),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
messenger.showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text('Could not start download: $e'),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _confirmDeleteSelected(
|
Future<void> _confirmDeleteSelected(
|
||||||
@@ -776,6 +927,28 @@ class _FilesViewState extends State<FilesView> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _moveOrCopySelected(
|
||||||
|
ServerProvider provider,
|
||||||
|
List<NextcloudItem> items, {
|
||||||
|
required bool copy,
|
||||||
|
}) async {
|
||||||
|
final result = await MoveCopyDestinationPicker.show(
|
||||||
|
context,
|
||||||
|
items,
|
||||||
|
copy: copy,
|
||||||
|
);
|
||||||
|
if (!mounted || result == null) return;
|
||||||
|
_clearSelection();
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text(
|
||||||
|
'${copy ? 'Copied' : 'Moved'} ${result.succeeded} of ${items.length} item(s)',
|
||||||
|
),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
Widget _buildListTile(
|
Widget _buildListTile(
|
||||||
BuildContext context,
|
BuildContext context,
|
||||||
NextcloudItem item,
|
NextcloudItem item,
|
||||||
@@ -795,7 +968,9 @@ class _FilesViewState extends State<FilesView> {
|
|||||||
: colorScheme.surfaceContainerLow,
|
: colorScheme.surfaceContainerLow,
|
||||||
child: InkWell(
|
child: InkWell(
|
||||||
onTap: () {
|
onTap: () {
|
||||||
if (_isSelecting) {
|
if (provider.isPicking) {
|
||||||
|
_handlePickTap(context, provider, item);
|
||||||
|
} else if (_isSelecting) {
|
||||||
_toggleSelection(item);
|
_toggleSelection(item);
|
||||||
} else if (item.isFolder) {
|
} else if (item.isFolder) {
|
||||||
provider.navigateToFolder(item.path);
|
provider.navigateToFolder(item.path);
|
||||||
@@ -803,10 +978,15 @@ class _FilesViewState extends State<FilesView> {
|
|||||||
_openFile(context, item, provider);
|
_openFile(context, item, provider);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onLongPress: () => _toggleSelection(item),
|
onLongPress: provider.isPicking && !provider.pickRequest!.allowMultiple
|
||||||
|
? null
|
||||||
|
: () => _toggleSelection(item),
|
||||||
child: Padding(
|
child: Padding(
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||||
child: Row(
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Stack(
|
||||||
|
clipBehavior: Clip.none,
|
||||||
children: [
|
children: [
|
||||||
SelectableThumbnail(
|
SelectableThumbnail(
|
||||||
isSelected: isSelected,
|
isSelected: isSelected,
|
||||||
@@ -820,6 +1000,15 @@ class _FilesViewState extends State<FilesView> {
|
|||||||
iconSize: 22,
|
iconSize: 22,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
Positioned(
|
||||||
|
right: -2,
|
||||||
|
bottom: -2,
|
||||||
|
child: SyncStatusBadge(
|
||||||
|
status: provider.syncStatusFor(item),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
const SizedBox(width: 14),
|
const SizedBox(width: 14),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Column(
|
child: Column(
|
||||||
@@ -850,7 +1039,7 @@ class _FilesViewState extends State<FilesView> {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
final content = _isSelecting
|
final content = _isSelecting || provider.isPicking
|
||||||
? card
|
? card
|
||||||
: SwipeableItem(
|
: SwipeableItem(
|
||||||
itemKey: ValueKey('file-${item.id}'),
|
itemKey: ValueKey('file-${item.id}'),
|
||||||
@@ -901,7 +1090,9 @@ class _FilesViewState extends State<FilesView> {
|
|||||||
clipBehavior: Clip.antiAlias,
|
clipBehavior: Clip.antiAlias,
|
||||||
child: InkWell(
|
child: InkWell(
|
||||||
onTap: () {
|
onTap: () {
|
||||||
if (_isSelecting) {
|
if (provider.isPicking) {
|
||||||
|
_handlePickTap(context, provider, item);
|
||||||
|
} else if (_isSelecting) {
|
||||||
_toggleSelection(item);
|
_toggleSelection(item);
|
||||||
} else if (item.isFolder) {
|
} else if (item.isFolder) {
|
||||||
provider.navigateToFolder(item.path);
|
provider.navigateToFolder(item.path);
|
||||||
@@ -909,14 +1100,25 @@ class _FilesViewState extends State<FilesView> {
|
|||||||
_openFile(context, item, provider);
|
_openFile(context, item, provider);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onLongPress: () => _toggleSelection(item),
|
onLongPress: provider.isPicking && !provider.pickRequest!.allowMultiple
|
||||||
child: SelectableThumbnail(
|
? null
|
||||||
|
: () => _toggleSelection(item),
|
||||||
|
child: Stack(
|
||||||
|
children: [
|
||||||
|
SelectableThumbnail(
|
||||||
isSelected: isSelected,
|
isSelected: isSelected,
|
||||||
checkmarkSize: 32,
|
checkmarkSize: 32,
|
||||||
child: isMedia
|
child: isMedia
|
||||||
? _buildMediaGridContent(context, item, provider)
|
? _buildMediaGridContent(context, item, provider)
|
||||||
: _buildPlainGridContent(context, item),
|
: _buildPlainGridContent(context, item),
|
||||||
),
|
),
|
||||||
|
Positioned(
|
||||||
|
right: 6,
|
||||||
|
bottom: 6,
|
||||||
|
child: SyncStatusBadge(status: provider.syncStatusFor(item)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1083,7 +1285,7 @@ class _FilesViewState extends State<FilesView> {
|
|||||||
title: const Text('Upload File'),
|
title: const Text('Upload File'),
|
||||||
onTap: () {
|
onTap: () {
|
||||||
Navigator.pop(sheetContext);
|
Navigator.pop(sheetContext);
|
||||||
_pickAndUploadFile(context, provider);
|
_pickAndUploadFile(context);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
ListTile(
|
ListTile(
|
||||||
@@ -1150,58 +1352,27 @@ class _FilesViewState extends State<FilesView> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _pickAndUploadFile(
|
// Mirrors `main.dart`'s `_handleSharedFiles` exactly, so picking a file
|
||||||
BuildContext context,
|
// via "+" lands on the same destination-picker screen and background
|
||||||
ServerProvider provider,
|
// foreground-service upload as receiving one via Android's "Share
|
||||||
) async {
|
// to..." sheet does, rather than a separate in-app-only upload path.
|
||||||
final result = await FilePicker.pickFiles();
|
Future<void> _pickAndUploadFile(BuildContext context) async {
|
||||||
if (result.isEmpty) return;
|
final picked = await FilePicker.pickFiles();
|
||||||
final picked = result.first;
|
if (picked.isEmpty) return;
|
||||||
if (picked.path == null) return;
|
final files = picked
|
||||||
|
.where((f) => f.path != null)
|
||||||
final progress = ValueNotifier<double?>(0);
|
.map(
|
||||||
if (!context.mounted) return;
|
(f) => SharedFileRef(
|
||||||
|
uri: Uri.file(f.path!).toString(),
|
||||||
showDialog(
|
name: f.name,
|
||||||
context: context,
|
size: f.lengthSync(),
|
||||||
barrierDismissible: false,
|
|
||||||
builder: (dialogContext) {
|
|
||||||
return AlertDialog(
|
|
||||||
title: Text('Uploading ${picked.name}'),
|
|
||||||
content: ValueListenableBuilder<double?>(
|
|
||||||
valueListenable: progress,
|
|
||||||
builder: (context, value, _) =>
|
|
||||||
LinearProgressIndicator(value: value),
|
|
||||||
),
|
),
|
||||||
);
|
)
|
||||||
},
|
.toList();
|
||||||
);
|
if (files.isEmpty || !context.mounted) return;
|
||||||
|
|
||||||
bool success = false;
|
Navigator.of(
|
||||||
try {
|
context,
|
||||||
success = await provider.uploadFileFromPath(
|
).push(MaterialPageRoute(builder: (_) => ShareUploadView(files: files)));
|
||||||
picked.name,
|
|
||||||
picked.path!,
|
|
||||||
onProgress: (sent, total) {
|
|
||||||
if (total > 0) progress.value = sent / total;
|
|
||||||
},
|
|
||||||
);
|
|
||||||
} catch (_) {
|
|
||||||
success = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (context.mounted) {
|
|
||||||
Navigator.pop(context); // close progress dialog
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(
|
|
||||||
content: Text(
|
|
||||||
success
|
|
||||||
? 'Uploaded ${picked.name} to Nextcloud'
|
|
||||||
: 'Failed to upload ${picked.name}',
|
|
||||||
),
|
|
||||||
behavior: SnackBarBehavior.floating,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -47,6 +47,60 @@ class _LoginViewState extends State<LoginView> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Resumes a saved account with one tap (see [ServerProvider.switchAccount]).
|
||||||
|
/// That can fail silently from the account's own perspective - most often
|
||||||
|
/// a stored app password that no longer works (revoked server-side, or
|
||||||
|
/// left over from before a since-fixed bug that deleted it too eagerly on
|
||||||
|
/// a plain network hiccup) - so this surfaces that as a SnackBar with a
|
||||||
|
/// silently failing every time - a delete button on the row itself (see
|
||||||
|
/// [_SavedAccountRow]) is the way out.
|
||||||
|
Future<void> _continueAsAccount(SavedAccount account) async {
|
||||||
|
final provider = context.read<ServerProvider>();
|
||||||
|
final success = await provider.switchAccount(account.id);
|
||||||
|
if (success || !mounted) return;
|
||||||
|
ScaffoldMessenger.of(context)
|
||||||
|
..hideCurrentSnackBar()
|
||||||
|
..showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text("Couldn't sign in as ${account.username}"),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mirrors AccountView's `_AccountsCard._confirmRemove` - same
|
||||||
|
/// destructive-action gate, just reached from the login screen instead of
|
||||||
|
/// Settings.
|
||||||
|
Future<void> _confirmRemoveAccount(SavedAccount account) async {
|
||||||
|
final host = Uri.tryParse(account.serverUrl)?.host ?? account.serverUrl;
|
||||||
|
final confirmed = await showDialog<bool>(
|
||||||
|
context: context,
|
||||||
|
builder: (dialogContext) {
|
||||||
|
return AlertDialog(
|
||||||
|
title: const Text('Remove Account'),
|
||||||
|
content: Text(
|
||||||
|
'Remove ${account.username} ($host)? You can add it again later.',
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.pop(dialogContext, false),
|
||||||
|
child: const Text('Cancel'),
|
||||||
|
),
|
||||||
|
FilledButton(
|
||||||
|
style: FilledButton.styleFrom(
|
||||||
|
backgroundColor: Theme.of(dialogContext).colorScheme.error,
|
||||||
|
),
|
||||||
|
onPressed: () => Navigator.pop(dialogContext, true),
|
||||||
|
child: const Text('Remove'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if (confirmed != true || !mounted) return;
|
||||||
|
await context.read<ServerProvider>().removeAccount(account.id);
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
@@ -81,9 +135,21 @@ class _LoginViewState extends State<LoginView> {
|
|||||||
final url = provider.pendingLoginUrl!;
|
final url = provider.pendingLoginUrl!;
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) async {
|
WidgetsBinding.instance.addPostFrameCallback((_) async {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
await Navigator.of(
|
// A plain MaterialPageRoute's animated slide/fade transition can
|
||||||
context,
|
// leave this screen fully black after popping back off of it - a
|
||||||
).push(MaterialPageRoute(builder: (_) => LoginWebViewView(url: url)));
|
// known Android WebView-as-PlatformView compositing issue with the
|
||||||
|
// Impeller renderer (the platform view's surface isn't always torn
|
||||||
|
// down in sync with an animated route transition). An instant,
|
||||||
|
// non-animated route sidesteps it entirely; the close (X) button
|
||||||
|
// already reads like a immediate action, not something that needs
|
||||||
|
// a slide, so no UX is lost.
|
||||||
|
await Navigator.of(context).push(
|
||||||
|
PageRouteBuilder(
|
||||||
|
pageBuilder: (_, _, _) => LoginWebViewView(url: url),
|
||||||
|
transitionDuration: Duration.zero,
|
||||||
|
reverseTransitionDuration: Duration.zero,
|
||||||
|
),
|
||||||
|
);
|
||||||
_webViewPushed = false;
|
_webViewPushed = false;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -110,7 +176,8 @@ class _LoginViewState extends State<LoginView> {
|
|||||||
provider.accounts.isNotEmpty) ...[
|
provider.accounts.isNotEmpty) ...[
|
||||||
_SavedAccountsSection(
|
_SavedAccountsSection(
|
||||||
accounts: provider.accounts,
|
accounts: provider.accounts,
|
||||||
onSelect: (account) => provider.switchAccount(account.id),
|
onSelect: (account) => _continueAsAccount(account),
|
||||||
|
onRemove: (account) => _confirmRemoveAccount(account),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 28),
|
const SizedBox(height: 28),
|
||||||
Row(
|
Row(
|
||||||
@@ -329,8 +396,13 @@ class _ServerForm extends StatelessWidget {
|
|||||||
class _SavedAccountsSection extends StatelessWidget {
|
class _SavedAccountsSection extends StatelessWidget {
|
||||||
final List<SavedAccount> accounts;
|
final List<SavedAccount> accounts;
|
||||||
final ValueChanged<SavedAccount> onSelect;
|
final ValueChanged<SavedAccount> onSelect;
|
||||||
|
final ValueChanged<SavedAccount> onRemove;
|
||||||
|
|
||||||
const _SavedAccountsSection({required this.accounts, required this.onSelect});
|
const _SavedAccountsSection({
|
||||||
|
required this.accounts,
|
||||||
|
required this.onSelect,
|
||||||
|
required this.onRemove,
|
||||||
|
});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
@@ -358,6 +430,7 @@ class _SavedAccountsSection extends StatelessWidget {
|
|||||||
_SavedAccountRow(
|
_SavedAccountRow(
|
||||||
account: account,
|
account: account,
|
||||||
onTap: () => onSelect(account),
|
onTap: () => onSelect(account),
|
||||||
|
onRemove: () => onRemove(account),
|
||||||
),
|
),
|
||||||
if (account != accounts.last)
|
if (account != accounts.last)
|
||||||
const Divider(height: 1, indent: 16, endIndent: 16),
|
const Divider(height: 1, indent: 16, endIndent: 16),
|
||||||
@@ -373,8 +446,13 @@ class _SavedAccountsSection extends StatelessWidget {
|
|||||||
class _SavedAccountRow extends StatelessWidget {
|
class _SavedAccountRow extends StatelessWidget {
|
||||||
final SavedAccount account;
|
final SavedAccount account;
|
||||||
final VoidCallback onTap;
|
final VoidCallback onTap;
|
||||||
|
final VoidCallback onRemove;
|
||||||
|
|
||||||
const _SavedAccountRow({required this.account, required this.onTap});
|
const _SavedAccountRow({
|
||||||
|
required this.account,
|
||||||
|
required this.onTap,
|
||||||
|
required this.onRemove,
|
||||||
|
});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
@@ -397,7 +475,12 @@ class _SavedAccountRow extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
title: Text(account.username),
|
title: Text(account.username),
|
||||||
subtitle: Text(host),
|
subtitle: Text(host),
|
||||||
trailing: const Icon(Icons.chevron_right_rounded),
|
trailing: IconButton(
|
||||||
|
icon: const Icon(Icons.close_rounded),
|
||||||
|
tooltip: 'Remove account',
|
||||||
|
visualDensity: VisualDensity.compact,
|
||||||
|
onPressed: onRemove,
|
||||||
|
),
|
||||||
onTap: onTap,
|
onTap: onTap,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,8 +42,17 @@ class _LoginWebViewViewState extends State<LoginWebViewView> {
|
|||||||
if (mounted) setState(() => _pageLoading = false);
|
if (mounted) setState(() => _pageLoading = false);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
)
|
);
|
||||||
..loadRequest(widget.url);
|
// Android's WebView CookieManager is a single store shared/persisted
|
||||||
|
// across every WebView instance in the app, not scoped to this
|
||||||
|
// controller - without clearing it first, "Add Account" (or logging
|
||||||
|
// back in as a different user on the same server) would silently land
|
||||||
|
// on whichever account's Nextcloud session cookie is already there
|
||||||
|
// instead of prompting for credentials, defeating the point of
|
||||||
|
// starting a fresh Login Flow v2 at all.
|
||||||
|
WebViewCookieManager().clearCookies().then((_) {
|
||||||
|
if (mounted) _controller.loadRequest(widget.url);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
void _cancel() {
|
void _cancel() {
|
||||||
|
|||||||
@@ -0,0 +1,528 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:intl/intl.dart';
|
||||||
|
import 'package:material_symbols_icons/symbols.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
import '../models/move_copy_result.dart';
|
||||||
|
import '../models/nextcloud_item.dart';
|
||||||
|
import '../providers/server_provider.dart';
|
||||||
|
import '../widgets/breadcrumbs.dart';
|
||||||
|
import '../widgets/item_icon.dart';
|
||||||
|
import '../widgets/more_tabs_button.dart';
|
||||||
|
import '../widgets/move_copy_conflict_sheet.dart';
|
||||||
|
import '../widgets/profile_avatar_button.dart';
|
||||||
|
import '../widgets/segmented_icon_toggle.dart';
|
||||||
|
import '../widgets/sort_menu_button.dart';
|
||||||
|
import '../widgets/sticky_header_delegate.dart';
|
||||||
|
import '../widgets/synced_header_scaffold.dart';
|
||||||
|
|
||||||
|
/// Destination-folder browser for moving/copying [items] (a multi-select
|
||||||
|
/// batch from Files or Photos). Visually mirrors `ShareUploadView`'s
|
||||||
|
/// browser (same chrome/controls/listing), but deliberately does **not**
|
||||||
|
/// reuse `ServerProvider`'s shared `currentFolderPath`/`pathStack`/`items`
|
||||||
|
/// navigation state the way that screen does - this is pushed mid-browsing
|
||||||
|
/// session (the user was already looking at a specific Files-tab folder
|
||||||
|
/// when they selected items and tapped Move/Copy), so clobbering that
|
||||||
|
/// shared state here would strand the Files tab in whatever folder this
|
||||||
|
/// picker last visited. Instead it owns its own local navigation state and
|
||||||
|
/// fetches through `ServerProvider.fetchFolderListing`, a stateless
|
||||||
|
/// pass-through that never touches shared fields - `ShareUploadView` gets
|
||||||
|
/// away with the shared state precisely because it always resets to root
|
||||||
|
/// and pops all the way to the app root afterward (a cold share-intent
|
||||||
|
/// launch has no prior browsing session to preserve); that doesn't hold
|
||||||
|
/// here.
|
||||||
|
class MoveCopyDestinationPicker extends StatefulWidget {
|
||||||
|
final List<NextcloudItem> items;
|
||||||
|
final bool copy;
|
||||||
|
|
||||||
|
const MoveCopyDestinationPicker({
|
||||||
|
super.key,
|
||||||
|
required this.items,
|
||||||
|
required this.copy,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Pushes the picker and returns the final [MoveCopyResult] (already
|
||||||
|
/// including any conflict resolution), or null if the user backed out
|
||||||
|
/// without confirming.
|
||||||
|
static Future<MoveCopyResult?> show(
|
||||||
|
BuildContext context,
|
||||||
|
List<NextcloudItem> items, {
|
||||||
|
required bool copy,
|
||||||
|
}) {
|
||||||
|
return Navigator.of(context).push<MoveCopyResult>(
|
||||||
|
MaterialPageRoute(
|
||||||
|
builder: (_) => MoveCopyDestinationPicker(items: items, copy: copy),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<MoveCopyDestinationPicker> createState() =>
|
||||||
|
_MoveCopyDestinationPickerState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _MoveCopyDestinationPickerState extends State<MoveCopyDestinationPicker> {
|
||||||
|
final ScrollController _scrollController = ScrollController();
|
||||||
|
List<String> _pathStack = const ['/'];
|
||||||
|
List<NextcloudItem> _rawItems = [];
|
||||||
|
bool _isLoading = true;
|
||||||
|
bool _isSubmitting = false;
|
||||||
|
|
||||||
|
String get _currentPath => _pathStack.last;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) => _fetch(_currentPath));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_scrollController.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _fetch(String path) async {
|
||||||
|
setState(() => _isLoading = true);
|
||||||
|
final raw = await context.read<ServerProvider>().fetchFolderListing(path);
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_rawItems = raw;
|
||||||
|
_isLoading = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void _navigateToFolder(String path) {
|
||||||
|
setState(() => _pathStack = [..._pathStack, path]);
|
||||||
|
_fetch(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _navigateToPathIndex(int index) {
|
||||||
|
if (index < 0 || index >= _pathStack.length - 1) return;
|
||||||
|
setState(() => _pathStack = _pathStack.sublist(0, index + 1));
|
||||||
|
_fetch(_currentPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _navigateUp() {
|
||||||
|
if (_pathStack.length <= 1) return false;
|
||||||
|
setState(() => _pathStack = _pathStack.sublist(0, _pathStack.length - 1));
|
||||||
|
_fetch(_currentPath);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Client-side mirror of `ServerProvider`'s own authoritative check (see
|
||||||
|
/// `_isSelfOrDescendant`) - just for disabling the confirm button with an
|
||||||
|
/// explanation up front instead of letting the request round-trip and
|
||||||
|
/// fail.
|
||||||
|
bool _destinationIsInvalid() {
|
||||||
|
final dest = _currentPath.endsWith('/') ? _currentPath : '$_currentPath/';
|
||||||
|
for (final item in widget.items) {
|
||||||
|
if (!item.isFolder) continue;
|
||||||
|
final folder = item.path.endsWith('/') ? item.path : '${item.path}/';
|
||||||
|
if (dest == folder || dest.startsWith(folder)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _confirm(ServerProvider provider) async {
|
||||||
|
setState(() => _isSubmitting = true);
|
||||||
|
final result = widget.copy
|
||||||
|
? await provider.copyItems(widget.items, _currentPath)
|
||||||
|
: await provider.moveItems(widget.items, _currentPath);
|
||||||
|
if (!mounted) return;
|
||||||
|
|
||||||
|
if (result.blockedReason != null) {
|
||||||
|
setState(() => _isSubmitting = false);
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text(result.blockedReason!),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var succeeded = result.succeeded;
|
||||||
|
var failed = result.failed;
|
||||||
|
|
||||||
|
if (result.conflicts.isNotEmpty) {
|
||||||
|
final choices = await MoveCopyConflictSheet.show(
|
||||||
|
context,
|
||||||
|
result.conflicts,
|
||||||
|
);
|
||||||
|
if (!mounted) return;
|
||||||
|
if (choices != null) {
|
||||||
|
final resolved = await provider.resolveConflicts(
|
||||||
|
result.conflicts,
|
||||||
|
_currentPath,
|
||||||
|
copy: widget.copy,
|
||||||
|
choices: choices,
|
||||||
|
);
|
||||||
|
succeeded += resolved.succeeded;
|
||||||
|
failed += resolved.failed;
|
||||||
|
}
|
||||||
|
// A dismissed sheet (choices == null) leaves those conflicts
|
||||||
|
// untouched at the source - same outcome as explicitly skipping
|
||||||
|
// every one, just without a network round-trip to get there.
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mounted) return;
|
||||||
|
Navigator.of(
|
||||||
|
context,
|
||||||
|
).pop(MoveCopyResult(succeeded: succeeded, failed: failed));
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildControlsRow(ServerProvider provider) {
|
||||||
|
return SizedBox(
|
||||||
|
height: 44,
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
scrollDirection: Axis.horizontal,
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
IconButton(
|
||||||
|
icon: Icon(
|
||||||
|
provider.filesSortAscending
|
||||||
|
? Icons.arrow_upward_rounded
|
||||||
|
: Icons.arrow_downward_rounded,
|
||||||
|
size: 20,
|
||||||
|
),
|
||||||
|
visualDensity: VisualDensity.compact,
|
||||||
|
tooltip: provider.filesSortAscending ? 'Ascending' : 'Descending',
|
||||||
|
onPressed: provider.toggleFilesSortOrder,
|
||||||
|
),
|
||||||
|
SizedBox(
|
||||||
|
width: 130,
|
||||||
|
child: SortMenuButton(
|
||||||
|
field: provider.filesSortField,
|
||||||
|
onChanged: provider.setFilesSortField,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
ToggleIconButton(
|
||||||
|
icon: provider.showHiddenFiles
|
||||||
|
? Icons.visibility_rounded
|
||||||
|
: Icons.visibility_off_rounded,
|
||||||
|
isSelected: provider.showHiddenFiles,
|
||||||
|
onTap: () => provider.toggleShowHiddenFiles(),
|
||||||
|
tooltip: 'Show hidden files',
|
||||||
|
),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
SegmentedIconGroup(
|
||||||
|
children: [
|
||||||
|
ToggleIconButton(
|
||||||
|
icon: Symbols.circles_rounded,
|
||||||
|
isSelected: provider.storageScope == StorageScope.cloud,
|
||||||
|
onTap: () => provider.setStorageScope(StorageScope.cloud),
|
||||||
|
tooltip: 'Cloud storage',
|
||||||
|
),
|
||||||
|
ToggleIconButton(
|
||||||
|
icon: Symbols.hard_drive_rounded,
|
||||||
|
isSelected: provider.storageScope == StorageScope.external,
|
||||||
|
onTap: () => provider.setStorageScope(StorageScope.external),
|
||||||
|
tooltip: 'External storage',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
SegmentedIconGroup(
|
||||||
|
children: [
|
||||||
|
ToggleIconButton(
|
||||||
|
icon: Icons.view_list_rounded,
|
||||||
|
isSelected: !provider.isGridView,
|
||||||
|
onTap: () => provider.setGridView(false),
|
||||||
|
tooltip: 'List view',
|
||||||
|
),
|
||||||
|
ToggleIconButton(
|
||||||
|
icon: Icons.grid_view_rounded,
|
||||||
|
isSelected: provider.isGridView,
|
||||||
|
onTap: () => provider.setGridView(true),
|
||||||
|
tooltip: 'Grid view',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only folders are valid Move/Copy destinations - files still show (so
|
||||||
|
// the listing matches what the Files tab itself would show for this
|
||||||
|
// folder) but are visually dimmed and inert, same treatment as
|
||||||
|
// ShareUploadView's own destination browser.
|
||||||
|
Widget _buildListTile(NextcloudItem item, ServerProvider provider) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final colorScheme = theme.colorScheme;
|
||||||
|
final isFolder = item.isFolder;
|
||||||
|
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 8),
|
||||||
|
child: ClipRRect(
|
||||||
|
borderRadius: BorderRadius.circular(16),
|
||||||
|
child: Opacity(
|
||||||
|
opacity: isFolder ? 1 : 0.5,
|
||||||
|
child: Material(
|
||||||
|
color: colorScheme.surfaceContainerLow,
|
||||||
|
child: InkWell(
|
||||||
|
onTap: isFolder ? () => _navigateToFolder(item.path) : null,
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: 16,
|
||||||
|
vertical: 12,
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
ItemThumbnail(
|
||||||
|
item: item,
|
||||||
|
provider: provider,
|
||||||
|
size: 44,
|
||||||
|
borderRadius: 12,
|
||||||
|
iconSize: 22,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 14),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
item.name,
|
||||||
|
style: theme.textTheme.titleMedium?.copyWith(
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
fontSize: 14,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
Text(
|
||||||
|
isFolder
|
||||||
|
? 'Folder'
|
||||||
|
: '${formatBytes(item.size)} • ${DateFormat.yMMMd().format(item.lastModified)}',
|
||||||
|
style: theme.textTheme.bodySmall?.copyWith(
|
||||||
|
color: colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (isFolder) const Icon(Icons.chevron_right_rounded),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildGridCard(NextcloudItem item, ServerProvider provider) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final colorScheme = theme.colorScheme;
|
||||||
|
final isFolder = item.isFolder;
|
||||||
|
final iconColor = getIconColor(context, item.type);
|
||||||
|
|
||||||
|
return Opacity(
|
||||||
|
opacity: isFolder ? 1 : 0.5,
|
||||||
|
child: Material(
|
||||||
|
color: colorScheme.surfaceContainerLow,
|
||||||
|
borderRadius: BorderRadius.circular(20),
|
||||||
|
clipBehavior: Clip.antiAlias,
|
||||||
|
child: InkWell(
|
||||||
|
onTap: isFolder ? () => _navigateToFolder(item.path) : null,
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(14),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||||
|
children: [
|
||||||
|
Container(
|
||||||
|
width: 40,
|
||||||
|
height: 40,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: iconColor.withValues(alpha: 0.12),
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
),
|
||||||
|
child: Icon(
|
||||||
|
getItemIcon(item.type),
|
||||||
|
color: iconColor,
|
||||||
|
size: 24,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
item.name,
|
||||||
|
maxLines: 2,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: theme.textTheme.titleMedium?.copyWith(
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
fontSize: 13,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
Text(
|
||||||
|
isFolder ? 'Folder' : formatBytes(item.size),
|
||||||
|
style: theme.textTheme.bodySmall?.copyWith(
|
||||||
|
color: colorScheme.onSurfaceVariant,
|
||||||
|
fontSize: 11,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final colorScheme = theme.colorScheme;
|
||||||
|
final provider = context.watch<ServerProvider>();
|
||||||
|
final hasBreadcrumbs = _pathStack.length > 1;
|
||||||
|
final currentLabel = _currentPath == '/'
|
||||||
|
? 'Home'
|
||||||
|
: _currentPath.split('/').where((s) => s.isNotEmpty).last;
|
||||||
|
final items = provider.applyFilesDisplayPrefs(_rawItems);
|
||||||
|
final invalidDestination = _destinationIsInvalid();
|
||||||
|
|
||||||
|
final controlsColumn = Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 16, 16, 12),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
_buildControlsRow(provider),
|
||||||
|
if (hasBreadcrumbs) ...[
|
||||||
|
const SizedBox(height: 10),
|
||||||
|
SizedBox(
|
||||||
|
height: 32,
|
||||||
|
child: Breadcrumbs(
|
||||||
|
pathStack: _pathStack,
|
||||||
|
onTap: _navigateToPathIndex,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
final contentSlivers = <Widget>[
|
||||||
|
SliverPersistentHeader(
|
||||||
|
pinned: true,
|
||||||
|
delegate: StickyHeaderDelegate(
|
||||||
|
height: hasBreadcrumbs ? 114 : 72,
|
||||||
|
child: controlsColumn,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (_isLoading)
|
||||||
|
const SliverFillRemaining(
|
||||||
|
hasScrollBody: false,
|
||||||
|
child: Center(child: CircularProgressIndicator()),
|
||||||
|
)
|
||||||
|
else if (items.isEmpty)
|
||||||
|
SliverFillRemaining(
|
||||||
|
hasScrollBody: false,
|
||||||
|
child: Center(
|
||||||
|
child: Text(
|
||||||
|
'Folder is empty',
|
||||||
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (provider.isGridView)
|
||||||
|
SliverPadding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
|
||||||
|
sliver: SliverGrid(
|
||||||
|
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
|
||||||
|
crossAxisCount: 2,
|
||||||
|
childAspectRatio: 1.1,
|
||||||
|
crossAxisSpacing: 12,
|
||||||
|
mainAxisSpacing: 12,
|
||||||
|
),
|
||||||
|
delegate: SliverChildBuilderDelegate((context, index) {
|
||||||
|
return _buildGridCard(items[index], provider);
|
||||||
|
}, childCount: items.length),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
SliverPadding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
|
||||||
|
sliver: SliverList(
|
||||||
|
delegate: SliverChildBuilderDelegate((context, index) {
|
||||||
|
return _buildListTile(items[index], provider);
|
||||||
|
}, childCount: items.length),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SliverToBoxAdapter(child: SizedBox(height: 24)),
|
||||||
|
];
|
||||||
|
|
||||||
|
return PopScope(
|
||||||
|
canPop: _pathStack.length <= 1,
|
||||||
|
onPopInvokedWithResult: (didPop, result) {
|
||||||
|
if (!didPop) _navigateUp();
|
||||||
|
},
|
||||||
|
child: Scaffold(
|
||||||
|
body: SyncedHeaderScaffold(
|
||||||
|
scrollController: _scrollController,
|
||||||
|
provider: provider,
|
||||||
|
actions: const [MoreTabsButton(), ProfileAvatarButton()],
|
||||||
|
contentSlivers: contentSlivers,
|
||||||
|
),
|
||||||
|
bottomNavigationBar: Material(
|
||||||
|
color: colorScheme.surfaceContainerHigh,
|
||||||
|
elevation: 8,
|
||||||
|
shape: const RoundedRectangleBorder(
|
||||||
|
borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
|
||||||
|
),
|
||||||
|
clipBehavior: Clip.antiAlias,
|
||||||
|
child: SafeArea(
|
||||||
|
top: false,
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(20, 16, 20, 16),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
if (invalidDestination) ...[
|
||||||
|
Text(
|
||||||
|
"Can't ${widget.copy ? 'copy' : 'move'} a folder into "
|
||||||
|
"itself or one of its own subfolders",
|
||||||
|
style: theme.textTheme.bodySmall?.copyWith(
|
||||||
|
color: colorScheme.error,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
],
|
||||||
|
SizedBox(
|
||||||
|
width: double.infinity,
|
||||||
|
child: FilledButton.icon(
|
||||||
|
onPressed: invalidDestination || _isSubmitting
|
||||||
|
? null
|
||||||
|
: () => _confirm(provider),
|
||||||
|
icon: _isSubmitting
|
||||||
|
? const SizedBox(
|
||||||
|
width: 18,
|
||||||
|
height: 18,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
)
|
||||||
|
: Icon(
|
||||||
|
widget.copy
|
||||||
|
? Icons.copy_rounded
|
||||||
|
: Icons.drive_file_move_rounded,
|
||||||
|
),
|
||||||
|
label: Text(
|
||||||
|
'${widget.copy ? 'Copy' : 'Move'} ${widget.items.length} '
|
||||||
|
'item(s) to $currentLabel',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+226
-87
@@ -1,14 +1,12 @@
|
|||||||
import 'package:file_saver/file_saver.dart';
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
import 'package:material_symbols_icons/symbols.dart';
|
import 'package:material_symbols_icons/symbols.dart';
|
||||||
import 'package:path/path.dart' as p;
|
|
||||||
import 'package:path_provider/path_provider.dart';
|
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
import 'package:share_plus/share_plus.dart';
|
import 'package:share_plus/share_plus.dart';
|
||||||
import '../models/nextcloud_item.dart';
|
import '../models/nextcloud_item.dart';
|
||||||
import '../models/selection_action.dart';
|
import '../models/selection_action.dart';
|
||||||
import '../providers/server_provider.dart';
|
import '../providers/server_provider.dart';
|
||||||
|
import '../services/download_service.dart';
|
||||||
import '../widgets/details/details_sheet.dart';
|
import '../widgets/details/details_sheet.dart';
|
||||||
import '../widgets/more_tabs_button.dart';
|
import '../widgets/more_tabs_button.dart';
|
||||||
import '../widgets/profile_avatar_button.dart';
|
import '../widgets/profile_avatar_button.dart';
|
||||||
@@ -19,6 +17,7 @@ import '../widgets/sort_menu_button.dart';
|
|||||||
import '../widgets/sticky_header_delegate.dart';
|
import '../widgets/sticky_header_delegate.dart';
|
||||||
import '../widgets/synced_header_scaffold.dart';
|
import '../widgets/synced_header_scaffold.dart';
|
||||||
import 'file_viewer_screen.dart';
|
import 'file_viewer_screen.dart';
|
||||||
|
import 'move_copy_destination_picker.dart';
|
||||||
|
|
||||||
class PhotosView extends StatefulWidget {
|
class PhotosView extends StatefulWidget {
|
||||||
final ScrollController scrollController;
|
final ScrollController scrollController;
|
||||||
@@ -29,29 +28,123 @@ class PhotosView extends StatefulWidget {
|
|||||||
State<PhotosView> createState() => _PhotosViewState();
|
State<PhotosView> createState() => _PhotosViewState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _PhotosViewState extends State<PhotosView> {
|
class _PhotosViewState extends State<PhotosView>
|
||||||
|
with SingleTickerProviderStateMixin {
|
||||||
bool _requested = false;
|
bool _requested = false;
|
||||||
final Set<String> _selectedIds = {};
|
final Set<String> _selectedIds = {};
|
||||||
|
final ScrollController _selectionActionsScrollController = ScrollController();
|
||||||
|
final List<AnimationController> _scrollHintControllers = [];
|
||||||
|
|
||||||
bool get _isSelecting => _selectedIds.isNotEmpty;
|
bool get _isSelecting => _selectedIds.isNotEmpty;
|
||||||
|
|
||||||
void _toggleSelection(NextcloudItem item) {
|
void _toggleSelection(NextcloudItem item) {
|
||||||
HapticFeedback.selectionClick();
|
HapticFeedback.selectionClick();
|
||||||
|
final enteringSelection = _selectedIds.isEmpty;
|
||||||
setState(() {
|
setState(() {
|
||||||
if (!_selectedIds.remove(item.id)) _selectedIds.add(item.id);
|
if (!_selectedIds.remove(item.id)) _selectedIds.add(item.id);
|
||||||
});
|
});
|
||||||
|
if (enteringSelection && _isSelecting) {
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback(
|
||||||
|
(_) => _playScrollHint(_selectionActionsScrollController),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void _clearSelection() {
|
void _clearSelection() {
|
||||||
setState(_selectedIds.clear);
|
setState(_selectedIds.clear);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A one-shot hint that the selection actions row actually scrolls -
|
||||||
|
/// mirrors `FilesView`'s identical controls-row hint (see its doc
|
||||||
|
/// comment): nudges it right and back, once, the first time a selection
|
||||||
|
/// starts. No-ops if there's nothing to scroll (row already fits).
|
||||||
|
Future<void> _playScrollHint(ScrollController scrollController) async {
|
||||||
|
await Future.delayed(const Duration(milliseconds: 500));
|
||||||
|
if (!mounted || !scrollController.hasClients) return;
|
||||||
|
final maxExtent = scrollController.position.maxScrollExtent;
|
||||||
|
if (maxExtent <= 0) return;
|
||||||
|
final double peak = maxExtent < 36 ? maxExtent : 36;
|
||||||
|
final controller = AnimationController(
|
||||||
|
vsync: this,
|
||||||
|
duration: const Duration(milliseconds: 900),
|
||||||
|
);
|
||||||
|
_scrollHintControllers.add(controller);
|
||||||
|
final hint = TweenSequence<double>([
|
||||||
|
TweenSequenceItem(
|
||||||
|
tween: Tween(
|
||||||
|
begin: 0.0,
|
||||||
|
end: peak,
|
||||||
|
).chain(CurveTween(curve: Curves.easeInOutSine)),
|
||||||
|
weight: 50,
|
||||||
|
),
|
||||||
|
TweenSequenceItem(
|
||||||
|
tween: Tween(
|
||||||
|
begin: peak,
|
||||||
|
end: 0.0,
|
||||||
|
).chain(CurveTween(curve: Curves.easeInOutSine)),
|
||||||
|
weight: 50,
|
||||||
|
),
|
||||||
|
]).animate(controller);
|
||||||
|
void onTick() {
|
||||||
|
if (scrollController.hasClients) {
|
||||||
|
scrollController.jumpTo(hint.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
hint.addListener(onTick);
|
||||||
|
await controller.forward();
|
||||||
|
hint.removeListener(onTick);
|
||||||
|
_scrollHintControllers.remove(controller);
|
||||||
|
controller.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
for (final controller in _scrollHintControllers) {
|
||||||
|
controller.dispose();
|
||||||
|
}
|
||||||
|
_selectionActionsScrollController.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mirrors `FilesView._handlePickTap` - Photos has no folders, so this is
|
||||||
|
/// just the matching/toggle/immediate-confirm branch.
|
||||||
|
void _handlePickTap(
|
||||||
|
BuildContext context,
|
||||||
|
ServerProvider provider,
|
||||||
|
NextcloudItem item,
|
||||||
|
) {
|
||||||
|
if (!provider.itemMatchesPickFilter(item)) {
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
const SnackBar(
|
||||||
|
content: Text("This app can't accept this file type"),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (provider.pickRequest!.allowMultiple) {
|
||||||
|
_toggleSelection(item);
|
||||||
|
} else {
|
||||||
|
provider.confirmPick([item]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The bulk actions shown in the sticky selection toolbar for the
|
/// The bulk actions shown in the sticky selection toolbar for the
|
||||||
/// currently-selected items.
|
/// currently-selected items.
|
||||||
List<SelectionAction> _buildSelectionActions(
|
List<SelectionAction> _buildSelectionActions(
|
||||||
ServerProvider provider,
|
ServerProvider provider,
|
||||||
List<NextcloudItem> selected,
|
List<NextcloudItem> selected,
|
||||||
) {
|
) {
|
||||||
|
if (provider.isPicking) {
|
||||||
|
return [
|
||||||
|
SelectionAction(
|
||||||
|
icon: Icons.check_rounded,
|
||||||
|
label: 'Use ${selected.length} item(s)',
|
||||||
|
onTap: () => provider.confirmPick(selected),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
}
|
||||||
return [
|
return [
|
||||||
SelectionAction(
|
SelectionAction(
|
||||||
icon: selected.every((i) => i.isFavorite)
|
icon: selected.every((i) => i.isFavorite)
|
||||||
@@ -60,7 +153,6 @@ class _PhotosViewState extends State<PhotosView> {
|
|||||||
label: selected.every((i) => i.isFavorite)
|
label: selected.every((i) => i.isFavorite)
|
||||||
? 'Remove from favorites'
|
? 'Remove from favorites'
|
||||||
: 'Favorite',
|
: 'Favorite',
|
||||||
color: Colors.red.shade400,
|
|
||||||
onTap: () => _favoriteSelected(provider, selected),
|
onTap: () => _favoriteSelected(provider, selected),
|
||||||
),
|
),
|
||||||
SelectionAction(
|
SelectionAction(
|
||||||
@@ -78,9 +170,18 @@ class _PhotosViewState extends State<PhotosView> {
|
|||||||
SelectionAction(
|
SelectionAction(
|
||||||
icon: Icons.delete_outline_rounded,
|
icon: Icons.delete_outline_rounded,
|
||||||
label: 'Delete',
|
label: 'Delete',
|
||||||
color: Theme.of(context).colorScheme.error,
|
|
||||||
onTap: () => _confirmDeleteSelected(context, provider, selected),
|
onTap: () => _confirmDeleteSelected(context, provider, selected),
|
||||||
),
|
),
|
||||||
|
SelectionAction(
|
||||||
|
icon: Icons.copy_rounded,
|
||||||
|
label: 'Copy',
|
||||||
|
onTap: () => _moveOrCopySelected(provider, selected, copy: true),
|
||||||
|
),
|
||||||
|
SelectionAction(
|
||||||
|
icon: Icons.drive_file_move_rounded,
|
||||||
|
label: 'Move',
|
||||||
|
onTap: () => _moveOrCopySelected(provider, selected, copy: false),
|
||||||
|
),
|
||||||
if (selected.length == 1)
|
if (selected.length == 1)
|
||||||
SelectionAction(
|
SelectionAction(
|
||||||
icon: Icons.info_outline_rounded,
|
icon: Icons.info_outline_rounded,
|
||||||
@@ -173,61 +274,13 @@ class _PhotosViewState extends State<PhotosView> {
|
|||||||
);
|
);
|
||||||
|
|
||||||
final List<Widget> contentSlivers = [
|
final List<Widget> contentSlivers = [
|
||||||
// Sticky while browsing; once selecting, the toolbar below takes over
|
// Sticky while browsing; once selecting, the selection bar takes over
|
||||||
// the pinned slot and this is free to scroll away.
|
// the very top of the screen instead (see `selectionBar` below), so
|
||||||
|
// this is free to scroll away rather than staying pinned under it.
|
||||||
SliverPersistentHeader(
|
SliverPersistentHeader(
|
||||||
pinned: !_isSelecting,
|
pinned: !_isSelecting,
|
||||||
delegate: StickyHeaderDelegate(height: 60, child: controlsRow),
|
delegate: StickyHeaderDelegate(height: 60, child: controlsRow),
|
||||||
),
|
),
|
||||||
if (_isSelecting)
|
|
||||||
SliverAppBar(
|
|
||||||
pinned: true,
|
|
||||||
// This isn't the scroll view's topmost sliver - the Synced
|
|
||||||
// header above it already reserves status-bar space, so leaving
|
|
||||||
// this at its default `primary: true` double-reserves it too,
|
|
||||||
// showing up as a big empty gap above the toolbar.
|
|
||||||
primary: false,
|
|
||||||
automaticallyImplyLeading: false,
|
|
||||||
toolbarHeight: 48,
|
|
||||||
// No leading/actions slots - everything lives in `title`, wrapped
|
|
||||||
// in the exact same 16px horizontal Padding as the controls row
|
|
||||||
// above it, so the two rows' content lines up edge-to-edge
|
|
||||||
// instead of relying on SliverAppBar's own leadingWidth/actions
|
|
||||||
// insets (which don't match the controls row's).
|
|
||||||
titleSpacing: 0,
|
|
||||||
title: Padding(
|
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
|
||||||
child: Row(
|
|
||||||
children: [
|
|
||||||
IconButton(
|
|
||||||
icon: const Icon(Icons.close_rounded, size: 20),
|
|
||||||
tooltip: 'Cancel selection',
|
|
||||||
onPressed: _clearSelection,
|
|
||||||
visualDensity: VisualDensity.compact,
|
|
||||||
),
|
|
||||||
const SizedBox(width: 8),
|
|
||||||
Expanded(
|
|
||||||
child: Text(
|
|
||||||
'${selectedItems.length} selected',
|
|
||||||
style: theme.textTheme.titleSmall?.copyWith(
|
|
||||||
fontWeight: FontWeight.w700,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
for (final action in _buildSelectionActions(
|
|
||||||
provider,
|
|
||||||
selectedItems,
|
|
||||||
))
|
|
||||||
IconButton(
|
|
||||||
icon: Icon(action.icon, size: 20, color: action.color),
|
|
||||||
tooltip: action.label,
|
|
||||||
onPressed: action.onTap,
|
|
||||||
visualDensity: VisualDensity.compact,
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SliverToBoxAdapter(child: SizedBox(height: 8)),
|
const SliverToBoxAdapter(child: SizedBox(height: 8)),
|
||||||
|
|
||||||
if (provider.isMediaLoading && photos.isEmpty)
|
if (provider.isMediaLoading && photos.isEmpty)
|
||||||
@@ -335,11 +388,81 @@ class _PhotosViewState extends State<PhotosView> {
|
|||||||
provider: provider,
|
provider: provider,
|
||||||
actions: const [MoreTabsButton(), ProfileAvatarButton()],
|
actions: const [MoreTabsButton(), ProfileAvatarButton()],
|
||||||
onRefresh: provider.fetchAllMedia,
|
onRefresh: provider.fetchAllMedia,
|
||||||
|
selectionBar: _isSelecting
|
||||||
|
? _buildSelectionBar(context, theme, provider, selectedItems)
|
||||||
|
: null,
|
||||||
contentSlivers: contentSlivers,
|
contentSlivers: contentSlivers,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Replaces the top bar entirely while selecting (see
|
||||||
|
/// `SyncedHeaderScaffold.selectionBar`) - a close button, the "N
|
||||||
|
/// selected" count, and the horizontally-scrollable bulk actions.
|
||||||
|
Widget _buildSelectionBar(
|
||||||
|
BuildContext context,
|
||||||
|
ThemeData theme,
|
||||||
|
ServerProvider provider,
|
||||||
|
List<NextcloudItem> selectedItems,
|
||||||
|
) {
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
width: MediaQuery.of(context).size.width * 0.5,
|
||||||
|
child: Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.close_rounded, size: 20),
|
||||||
|
tooltip: 'Cancel selection',
|
||||||
|
onPressed: _clearSelection,
|
||||||
|
visualDensity: VisualDensity.compact,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Text(
|
||||||
|
'${selectedItems.length} selected',
|
||||||
|
style: theme.textTheme.titleSmall?.copyWith(
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Expanded(
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
controller: _selectionActionsScrollController,
|
||||||
|
scrollDirection: Axis.horizontal,
|
||||||
|
// Left-aligned (not anchored to the trailing edge) so the
|
||||||
|
// first action's left edge sits at a fixed spot - lining up
|
||||||
|
// with the controls row's own first icon directly below it -
|
||||||
|
// regardless of how many actions there are.
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
for (final action in _buildSelectionActions(
|
||||||
|
provider,
|
||||||
|
selectedItems,
|
||||||
|
))
|
||||||
|
IconButton(
|
||||||
|
icon: Icon(action.icon, size: 20),
|
||||||
|
tooltip: action.label,
|
||||||
|
onPressed: action.onTap,
|
||||||
|
visualDensity: VisualDensity.compact,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
Widget _buildPhotoTile(
|
Widget _buildPhotoTile(
|
||||||
BuildContext context,
|
BuildContext context,
|
||||||
NextcloudItem photo,
|
NextcloudItem photo,
|
||||||
@@ -353,13 +476,17 @@ class _PhotosViewState extends State<PhotosView> {
|
|||||||
// floating rounded corner mid-drag (see the same fix in files_view).
|
// floating rounded corner mid-drag (see the same fix in files_view).
|
||||||
final tile = GestureDetector(
|
final tile = GestureDetector(
|
||||||
onTap: () {
|
onTap: () {
|
||||||
if (_isSelecting) {
|
if (provider.isPicking) {
|
||||||
|
_handlePickTap(context, provider, photo);
|
||||||
|
} else if (_isSelecting) {
|
||||||
_toggleSelection(photo);
|
_toggleSelection(photo);
|
||||||
} else {
|
} else {
|
||||||
_openLightbox(context, photo, provider);
|
_openLightbox(context, photo, provider);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onLongPress: () => _toggleSelection(photo),
|
onLongPress: provider.isPicking && !provider.pickRequest!.allowMultiple
|
||||||
|
? null
|
||||||
|
: () => _toggleSelection(photo),
|
||||||
child: ColoredBox(
|
child: ColoredBox(
|
||||||
color: colorScheme.surfaceContainerHigh,
|
color: colorScheme.surfaceContainerHigh,
|
||||||
child: SelectableThumbnail(
|
child: SelectableThumbnail(
|
||||||
@@ -515,45 +642,35 @@ class _PhotosViewState extends State<PhotosView> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Hands the whole batch off to `DownloadService.kt` - see
|
||||||
|
/// `FilesView._downloadSelected`'s identical doc comment for why.
|
||||||
Future<void> _downloadSelected(
|
Future<void> _downloadSelected(
|
||||||
BuildContext context,
|
BuildContext context,
|
||||||
ServerProvider provider,
|
ServerProvider provider,
|
||||||
List<NextcloudItem> items,
|
List<NextcloudItem> items,
|
||||||
) async {
|
) async {
|
||||||
final messenger = ScaffoldMessenger.of(context);
|
|
||||||
messenger.showSnackBar(
|
|
||||||
SnackBar(
|
|
||||||
content: Text('Downloading ${items.length} item(s)...'),
|
|
||||||
behavior: SnackBarBehavior.floating,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
var succeeded = 0;
|
|
||||||
for (final item in items) {
|
|
||||||
try {
|
|
||||||
final tempDir = await getTemporaryDirectory();
|
|
||||||
final tempPath = p.join(tempDir.path, item.name);
|
|
||||||
await provider.service!.downloadToFile(item.path, tempPath);
|
|
||||||
final ext = p.extension(item.name).replaceFirst('.', '');
|
|
||||||
final baseName = p.basenameWithoutExtension(item.name);
|
|
||||||
await FileSaver.instance.saveFile(
|
|
||||||
name: baseName,
|
|
||||||
filePath: tempPath,
|
|
||||||
ext: ext,
|
|
||||||
);
|
|
||||||
succeeded++;
|
|
||||||
} catch (_) {
|
|
||||||
// Reported in the summary snackbar below.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_clearSelection();
|
_clearSelection();
|
||||||
|
final messenger = ScaffoldMessenger.of(context);
|
||||||
|
try {
|
||||||
|
await DownloadService.startDownload(provider, items);
|
||||||
messenger.showSnackBar(
|
messenger.showSnackBar(
|
||||||
SnackBar(
|
SnackBar(
|
||||||
content: Text('Downloaded $succeeded of ${items.length} item(s)'),
|
content: Text(
|
||||||
|
items.length == 1
|
||||||
|
? 'Downloading ${items.first.name} - see the notification for progress'
|
||||||
|
: 'Downloading ${items.length} files - see the notification for progress',
|
||||||
|
),
|
||||||
behavior: SnackBarBehavior.floating,
|
behavior: SnackBarBehavior.floating,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
} catch (e) {
|
||||||
|
messenger.showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text('Could not start download: $e'),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _confirmDeleteSelected(
|
Future<void> _confirmDeleteSelected(
|
||||||
@@ -602,4 +719,26 @@ class _PhotosViewState extends State<PhotosView> {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _moveOrCopySelected(
|
||||||
|
ServerProvider provider,
|
||||||
|
List<NextcloudItem> items, {
|
||||||
|
required bool copy,
|
||||||
|
}) async {
|
||||||
|
final result = await MoveCopyDestinationPicker.show(
|
||||||
|
context,
|
||||||
|
items,
|
||||||
|
copy: copy,
|
||||||
|
);
|
||||||
|
if (!mounted || result == null) return;
|
||||||
|
_clearSelection();
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
content: Text(
|
||||||
|
'${copy ? 'Copied' : 'Moved'} ${result.succeeded} of ${items.length} item(s)',
|
||||||
|
),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,9 +9,12 @@ import '../services/share_intent_service.dart';
|
|||||||
import '../services/upload_service.dart';
|
import '../services/upload_service.dart';
|
||||||
import '../widgets/breadcrumbs.dart';
|
import '../widgets/breadcrumbs.dart';
|
||||||
import '../widgets/item_icon.dart';
|
import '../widgets/item_icon.dart';
|
||||||
|
import '../widgets/marquee_title.dart';
|
||||||
|
import '../widgets/profile_avatar_button.dart';
|
||||||
import '../widgets/segmented_icon_toggle.dart';
|
import '../widgets/segmented_icon_toggle.dart';
|
||||||
import '../widgets/sort_menu_button.dart';
|
import '../widgets/sort_menu_button.dart';
|
||||||
import '../widgets/synced_header_scaffold.dart' show formatBytes;
|
import '../widgets/sticky_header_delegate.dart';
|
||||||
|
import '../widgets/synced_header_scaffold.dart';
|
||||||
|
|
||||||
/// Shown when another app shares one or more files to Noo (Android's
|
/// Shown when another app shares one or more files to Noo (Android's
|
||||||
/// "Share to..." sheet). Lets the user browse to a destination folder,
|
/// "Share to..." sheet). Lets the user browse to a destination folder,
|
||||||
@@ -32,6 +35,8 @@ class ShareUploadView extends StatefulWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _ShareUploadViewState extends State<ShareUploadView> {
|
class _ShareUploadViewState extends State<ShareUploadView> {
|
||||||
|
final ScrollController _scrollController = ScrollController();
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
@@ -42,6 +47,12 @@ class _ShareUploadViewState extends State<ShareUploadView> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_scrollController.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _uploadHere(ServerProvider provider) async {
|
Future<void> _uploadHere(ServerProvider provider) async {
|
||||||
final messenger = ScaffoldMessenger.of(context);
|
final messenger = ScaffoldMessenger.of(context);
|
||||||
final navigator = Navigator.of(context);
|
final navigator = Navigator.of(context);
|
||||||
@@ -96,15 +107,6 @@ class _ShareUploadViewState extends State<ShareUploadView> {
|
|||||||
onChanged: provider.setFilesSortField,
|
onChanged: provider.setFilesSortField,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
ToggleIconButton(
|
|
||||||
icon: provider.showFavoritesOnlyFiles
|
|
||||||
? Icons.favorite_rounded
|
|
||||||
: Icons.favorite_border_rounded,
|
|
||||||
isSelected: provider.showFavoritesOnlyFiles,
|
|
||||||
onTap: provider.toggleFavoritesFilterFiles,
|
|
||||||
tooltip: 'Favorites only',
|
|
||||||
),
|
|
||||||
const SizedBox(width: 4),
|
|
||||||
ToggleIconButton(
|
ToggleIconButton(
|
||||||
icon: provider.showHiddenFiles
|
icon: provider.showHiddenFiles
|
||||||
? Icons.visibility_rounded
|
? Icons.visibility_rounded
|
||||||
@@ -332,76 +334,175 @@ class _ShareUploadViewState extends State<ShareUploadView> {
|
|||||||
: currentPath.split('/').where((s) => s.isNotEmpty).last;
|
: currentPath.split('/').where((s) => s.isNotEmpty).last;
|
||||||
final items = provider.items;
|
final items = provider.items;
|
||||||
|
|
||||||
return Scaffold(
|
// Mirrors FilesView's own controls-row + breadcrumbs sticky header
|
||||||
appBar: AppBar(
|
// exactly (padding, heights) so this reads as the same browser, just
|
||||||
title: Text(
|
// reached from a share intent instead of the Files tab.
|
||||||
widget.files.length == 1
|
final controlsColumn = Padding(
|
||||||
? 'Upload ${widget.files.first.name}'
|
padding: const EdgeInsets.fromLTRB(16, 16, 16, 12),
|
||||||
: 'Upload ${widget.files.length} files',
|
child: Column(
|
||||||
),
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
),
|
|
||||||
body: Column(
|
|
||||||
children: [
|
children: [
|
||||||
Padding(
|
_buildControlsRow(provider),
|
||||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
|
if (hasBreadcrumbs) ...[
|
||||||
child: _buildControlsRow(provider),
|
const SizedBox(height: 10),
|
||||||
),
|
SizedBox(
|
||||||
if (hasBreadcrumbs)
|
height: 32,
|
||||||
Padding(
|
|
||||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 4),
|
|
||||||
child: Breadcrumbs(
|
child: Breadcrumbs(
|
||||||
pathStack: provider.pathStack,
|
pathStack: provider.pathStack,
|
||||||
onTap: (index) => provider.navigateToPathIndex(index),
|
onTap: (index) => provider.navigateToPathIndex(index),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
Expanded(
|
],
|
||||||
child: provider.isLoading
|
],
|
||||||
? const Center(child: CircularProgressIndicator())
|
),
|
||||||
: items.isEmpty
|
);
|
||||||
? Center(
|
|
||||||
|
final contentSlivers = <Widget>[
|
||||||
|
SliverPersistentHeader(
|
||||||
|
pinned: true,
|
||||||
|
delegate: StickyHeaderDelegate(
|
||||||
|
height: hasBreadcrumbs ? 114 : 72,
|
||||||
|
child: controlsColumn,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (provider.isLoading)
|
||||||
|
const SliverFillRemaining(
|
||||||
|
hasScrollBody: false,
|
||||||
|
child: Center(child: CircularProgressIndicator()),
|
||||||
|
)
|
||||||
|
else if (items.isEmpty)
|
||||||
|
SliverFillRemaining(
|
||||||
|
hasScrollBody: false,
|
||||||
|
child: Center(
|
||||||
child: Text(
|
child: Text(
|
||||||
'Folder is empty',
|
'Folder is empty',
|
||||||
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
style: TextStyle(color: colorScheme.onSurfaceVariant),
|
||||||
),
|
),
|
||||||
)
|
|
||||||
: provider.isGridView
|
|
||||||
? GridView.builder(
|
|
||||||
padding: const EdgeInsets.symmetric(
|
|
||||||
horizontal: 20,
|
|
||||||
vertical: 8,
|
|
||||||
),
|
),
|
||||||
gridDelegate:
|
)
|
||||||
const SliverGridDelegateWithFixedCrossAxisCount(
|
else if (provider.isGridView)
|
||||||
|
SliverPadding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
|
||||||
|
sliver: SliverGrid(
|
||||||
|
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
|
||||||
crossAxisCount: 2,
|
crossAxisCount: 2,
|
||||||
childAspectRatio: 1.1,
|
childAspectRatio: 1.1,
|
||||||
crossAxisSpacing: 12,
|
crossAxisSpacing: 12,
|
||||||
mainAxisSpacing: 12,
|
mainAxisSpacing: 12,
|
||||||
),
|
),
|
||||||
itemCount: items.length,
|
delegate: SliverChildBuilderDelegate((context, index) {
|
||||||
itemBuilder: (context, index) =>
|
return _buildGridCard(context, items[index], provider);
|
||||||
_buildGridCard(context, items[index], provider),
|
}, childCount: items.length),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
: ListView.builder(
|
else
|
||||||
|
SliverPadding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
|
||||||
|
sliver: SliverList(
|
||||||
|
delegate: SliverChildBuilderDelegate((context, index) {
|
||||||
|
return _buildListTile(context, items[index], provider);
|
||||||
|
}, childCount: items.length),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
// So the last row isn't hidden behind the bottom "Upload to..." bar.
|
||||||
|
const SliverToBoxAdapter(child: SizedBox(height: 24)),
|
||||||
|
];
|
||||||
|
|
||||||
|
return Scaffold(
|
||||||
|
body: SyncedHeaderScaffold(
|
||||||
|
scrollController: _scrollController,
|
||||||
|
provider: provider,
|
||||||
|
// Same trailing actions as every other tab except "More tabs" -
|
||||||
|
// there's nowhere useful for it to go while mid-upload (jumping to
|
||||||
|
// Trash/Shares/etc. would abandon this destination picker), so the
|
||||||
|
// top chrome is identical to every other tab minus that one entry.
|
||||||
|
// Backing out is still the system back gesture/button, same as any
|
||||||
|
// other pushed screen.
|
||||||
|
actions: const [ProfileAvatarButton()],
|
||||||
|
contentSlivers: contentSlivers,
|
||||||
|
),
|
||||||
|
// A rounded-top, elevated bar "peeking" up from the bottom edge - the
|
||||||
|
// uploading-file summary (marqueed if it doesn't fit on one line)
|
||||||
|
// sits directly above the destination button, both inside the one
|
||||||
|
// sheet, rather than the summary living up in the scrolling content
|
||||||
|
// far away from the action it describes.
|
||||||
|
bottomNavigationBar: Material(
|
||||||
|
color: colorScheme.surfaceContainerHigh,
|
||||||
|
elevation: 8,
|
||||||
|
shape: const RoundedRectangleBorder(
|
||||||
|
borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
|
||||||
|
),
|
||||||
|
clipBehavior: Clip.antiAlias,
|
||||||
|
child: SafeArea(
|
||||||
|
top: false,
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(20, 16, 20, 16),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
// Same pill/chip look and exact same duller background
|
||||||
|
// color as the filter toggles' shared background
|
||||||
|
// (SegmentedIconGroup's `surfaceContainerHigh`), so it reads
|
||||||
|
// as part of the same visual language rather than a new
|
||||||
|
// accent color. Sized to the text itself (like a real chip)
|
||||||
|
// up to the row's available width - MarqueeTitle needs a
|
||||||
|
// concrete (not just loose) width to know whether/how far
|
||||||
|
// to scroll, so this measures the text once up front rather
|
||||||
|
// than leaving the chip unconstrained.
|
||||||
|
LayoutBuilder(
|
||||||
|
builder: (context, constraints) {
|
||||||
|
final uploadingText = widget.files.length == 1
|
||||||
|
? 'Uploading ${widget.files.first.name}'
|
||||||
|
: 'Uploading ${widget.files.length} files';
|
||||||
|
final chipTextStyle = theme.textTheme.titleSmall?.copyWith(
|
||||||
|
color: colorScheme.onSurfaceVariant,
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
);
|
||||||
|
const horizontalPadding = 28.0;
|
||||||
|
final painter = TextPainter(
|
||||||
|
text: TextSpan(text: uploadingText, style: chipTextStyle),
|
||||||
|
maxLines: 1,
|
||||||
|
textDirection: Directionality.of(context),
|
||||||
|
)..layout(maxWidth: double.infinity);
|
||||||
|
final chipWidth = (painter.width + horizontalPadding).clamp(
|
||||||
|
0.0,
|
||||||
|
constraints.maxWidth,
|
||||||
|
);
|
||||||
|
|
||||||
|
return Container(
|
||||||
|
width: chipWidth,
|
||||||
padding: const EdgeInsets.symmetric(
|
padding: const EdgeInsets.symmetric(
|
||||||
horizontal: 20,
|
horizontal: 14,
|
||||||
vertical: 8,
|
vertical: 8,
|
||||||
),
|
),
|
||||||
itemCount: items.length,
|
decoration: BoxDecoration(
|
||||||
itemBuilder: (context, index) =>
|
color: colorScheme.surfaceContainerHigh,
|
||||||
_buildListTile(context, items[index], provider),
|
borderRadius: BorderRadius.circular(20),
|
||||||
|
),
|
||||||
|
child: SizedBox(
|
||||||
|
height: 20,
|
||||||
|
child: MarqueeTitle(
|
||||||
|
text: uploadingText,
|
||||||
|
style: chipTextStyle,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
);
|
||||||
|
},
|
||||||
),
|
),
|
||||||
bottomNavigationBar: SafeArea(
|
const SizedBox(height: 12),
|
||||||
child: Padding(
|
SizedBox(
|
||||||
padding: const EdgeInsets.all(16),
|
width: double.infinity,
|
||||||
child: FilledButton.icon(
|
child: FilledButton.icon(
|
||||||
onPressed: () => _uploadHere(provider),
|
onPressed: () => _uploadHere(provider),
|
||||||
icon: const Icon(Icons.upload_rounded),
|
icon: const Icon(Icons.upload_rounded),
|
||||||
label: Text('Upload to $currentLabel'),
|
label: Text('Upload to $currentLabel'),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import '../models/app_tab.dart';
|
import '../models/app_tab.dart';
|
||||||
import '../views/activity_view.dart';
|
import '../views/activity_view.dart';
|
||||||
|
import '../views/favorites_view.dart';
|
||||||
import '../views/files_view.dart';
|
import '../views/files_view.dart';
|
||||||
import '../views/photos_view.dart';
|
import '../views/photos_view.dart';
|
||||||
import '../views/recent_view.dart';
|
import '../views/recent_view.dart';
|
||||||
@@ -16,6 +17,8 @@ Widget buildAppTabView(AppTab tab, ScrollController controller) {
|
|||||||
return FilesView(scrollController: controller);
|
return FilesView(scrollController: controller);
|
||||||
case AppTab.photos:
|
case AppTab.photos:
|
||||||
return PhotosView(scrollController: controller);
|
return PhotosView(scrollController: controller);
|
||||||
|
case AppTab.favorites:
|
||||||
|
return FavoritesView(scrollController: controller);
|
||||||
case AppTab.activity:
|
case AppTab.activity:
|
||||||
return ActivityView(scrollController: controller);
|
return ActivityView(scrollController: controller);
|
||||||
case AppTab.trash:
|
case AppTab.trash:
|
||||||
|
|||||||
@@ -51,11 +51,24 @@ class DetailsSheet extends StatelessWidget {
|
|||||||
child: Column(
|
child: Column(
|
||||||
children: [
|
children: [
|
||||||
DetailsHeader(item: item),
|
DetailsHeader(item: item),
|
||||||
|
// Icon size matches the bottom nav bar's own tab icons
|
||||||
|
// (FloatingBottomNavBar) rather than TabBar's oversized default,
|
||||||
|
// so a "tabs" affordance reads the same size everywhere in the
|
||||||
|
// app.
|
||||||
const TabBar(
|
const TabBar(
|
||||||
tabs: [
|
tabs: [
|
||||||
Tab(icon: Icon(Icons.info_outline_rounded), text: 'Info'),
|
Tab(
|
||||||
Tab(icon: Icon(Icons.history_rounded), text: 'Versions'),
|
icon: Icon(Icons.info_outline_rounded, size: 22),
|
||||||
Tab(icon: Icon(Icons.electric_bolt_rounded), text: 'Activity'),
|
text: 'Info',
|
||||||
|
),
|
||||||
|
Tab(
|
||||||
|
icon: Icon(Icons.history_rounded, size: 22),
|
||||||
|
text: 'Versions',
|
||||||
|
),
|
||||||
|
Tab(
|
||||||
|
icon: Icon(Icons.electric_bolt_rounded, size: 22),
|
||||||
|
text: 'Activity',
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
Expanded(
|
Expanded(
|
||||||
@@ -73,13 +86,25 @@ class DetailsSheet extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Icon/name/size/date row shared by [DetailsSheet] and the media viewer's
|
/// Icon/name/size/date row shared by [DetailsSheet], the media viewer's
|
||||||
/// collapsed "peek" state (which shows just this, before the user drags the
|
/// collapsed "peek" state (which shows just this, before the user drags the
|
||||||
/// sheet open far enough to reveal the tabs).
|
/// sheet open far enough to reveal the tabs), and [ShareSheet]'s own title
|
||||||
|
/// (so every per-item bottom sheet opens on the same header instead of
|
||||||
|
/// [ShareSheet] alone using a bare title `Text`).
|
||||||
class DetailsHeader extends StatelessWidget {
|
class DetailsHeader extends StatelessWidget {
|
||||||
final NextcloudItem item;
|
final NextcloudItem item;
|
||||||
|
|
||||||
const DetailsHeader({super.key, required this.item});
|
/// Defaults to this widget's own standalone inset ([DetailsSheet]); a
|
||||||
|
/// caller whose surrounding scroll view already applies horizontal
|
||||||
|
/// padding (e.g. [ShareSheet]'s `ListView`) should pass a padding with
|
||||||
|
/// zero left/right to avoid doubling it up.
|
||||||
|
final EdgeInsetsGeometry padding;
|
||||||
|
|
||||||
|
const DetailsHeader({
|
||||||
|
super.key,
|
||||||
|
required this.item,
|
||||||
|
this.padding = const EdgeInsets.fromLTRB(20, 12, 20, 8),
|
||||||
|
});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
@@ -87,7 +112,7 @@ class DetailsHeader extends StatelessWidget {
|
|||||||
final colorScheme = theme.colorScheme;
|
final colorScheme = theme.colorScheme;
|
||||||
|
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.fromLTRB(20, 12, 20, 8),
|
padding: padding,
|
||||||
child: Row(
|
child: Row(
|
||||||
children: [
|
children: [
|
||||||
Container(
|
Container(
|
||||||
|
|||||||
@@ -61,6 +61,14 @@ class FloatingBottomNavBar extends StatelessWidget {
|
|||||||
blurSigma: blurSigma,
|
blurSigma: blurSigma,
|
||||||
child: Padding(
|
child: Padding(
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 6),
|
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 6),
|
||||||
|
// The selected item's label expands the pill, and with enough
|
||||||
|
// tabs visible that can outgrow the available width (the
|
||||||
|
// ConstrainedBox above caps it at 480, but the screen itself may
|
||||||
|
// be narrower) - wrapped in a scroll view rather than a plain Row
|
||||||
|
// so it degrades to a swipe instead of overflowing/clipping.
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
scrollDirection: Axis.horizontal,
|
||||||
|
physics: const BouncingScrollPhysics(),
|
||||||
child: Row(
|
child: Row(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: List.generate(items.length, (index) {
|
children: List.generate(items.length, (index) {
|
||||||
@@ -80,7 +88,9 @@ class FloatingBottomNavBar extends StatelessWidget {
|
|||||||
vertical: 12,
|
vertical: 12,
|
||||||
),
|
),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: isSelected ? colorScheme.primary : Colors.transparent,
|
color: isSelected
|
||||||
|
? colorScheme.primary
|
||||||
|
: Colors.transparent,
|
||||||
borderRadius: BorderRadius.circular(26),
|
borderRadius: BorderRadius.circular(26),
|
||||||
),
|
),
|
||||||
child: Row(
|
child: Row(
|
||||||
@@ -114,6 +124,7 @@ class FloatingBottomNavBar extends StatelessWidget {
|
|||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:marquee/marquee.dart';
|
||||||
|
|
||||||
|
/// A plain, single-line ellipsized [Text] for content that fits, or an
|
||||||
|
/// auto-scrolling [Marquee] for text too long for the available width -
|
||||||
|
/// measured once via [TextPainter] rather than always marqueeing, so short
|
||||||
|
/// text just sits still like normal.
|
||||||
|
class MarqueeTitle extends StatelessWidget {
|
||||||
|
final String text;
|
||||||
|
final TextStyle? style;
|
||||||
|
|
||||||
|
const MarqueeTitle({super.key, required this.text, required this.style});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return LayoutBuilder(
|
||||||
|
builder: (context, constraints) {
|
||||||
|
final painter = TextPainter(
|
||||||
|
text: TextSpan(text: text, style: style),
|
||||||
|
maxLines: 1,
|
||||||
|
textDirection: Directionality.of(context),
|
||||||
|
)..layout(maxWidth: double.infinity);
|
||||||
|
|
||||||
|
if (painter.width <= constraints.maxWidth) {
|
||||||
|
return Text(
|
||||||
|
text,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: style,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return SizedBox(
|
||||||
|
height: painter.height,
|
||||||
|
child: Marquee(
|
||||||
|
text: text,
|
||||||
|
style: style,
|
||||||
|
blankSpace: 48,
|
||||||
|
velocity: 30,
|
||||||
|
startPadding: 0,
|
||||||
|
pauseAfterRound: const Duration(seconds: 1),
|
||||||
|
fadingEdgeStartFraction: 0.1,
|
||||||
|
fadingEdgeEndFraction: 0.15,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,6 +15,13 @@ class MoreTabsButton extends StatelessWidget {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final provider = context.watch<ServerProvider>();
|
final provider = context.watch<ServerProvider>();
|
||||||
|
|
||||||
|
// While picking (another app's GET_CONTENT request), MainShellView
|
||||||
|
// already restricts the bottom nav to Files/Photos - this button would
|
||||||
|
// otherwise be the one remaining way to reach a tab that isn't a valid
|
||||||
|
// pick source (Trash, Shares, ...), so it hides entirely rather than
|
||||||
|
// just disabling.
|
||||||
|
if (provider.isPicking) return const SizedBox.shrink();
|
||||||
|
|
||||||
return PopupMenuButton<AppTab>(
|
return PopupMenuButton<AppTab>(
|
||||||
icon: const Icon(Icons.apps_rounded),
|
icon: const Icon(Icons.apps_rounded),
|
||||||
tooltip: 'More tabs',
|
tooltip: 'More tabs',
|
||||||
|
|||||||
@@ -0,0 +1,172 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import '../models/move_copy_result.dart';
|
||||||
|
import 'gradual_bottom_sheet.dart';
|
||||||
|
|
||||||
|
/// Shown after a Move/Copy batch comes back with `MoveCopyResult.conflicts`
|
||||||
|
/// non-empty (an item with the same name already exists at the
|
||||||
|
/// destination) - summarizes every conflict at once rather than prompting
|
||||||
|
/// per item as they're hit, and lets the user resolve them all the same
|
||||||
|
/// way (overwrite/keep both) or open a per-item breakdown. Returns the
|
||||||
|
/// `ConflictChoice` map `ServerProvider.resolveConflicts` expects, or null
|
||||||
|
/// if dismissed without choosing.
|
||||||
|
class MoveCopyConflictSheet extends StatefulWidget {
|
||||||
|
final List<MoveCopyConflict> conflicts;
|
||||||
|
final ScrollController? scrollController;
|
||||||
|
|
||||||
|
const MoveCopyConflictSheet({
|
||||||
|
super.key,
|
||||||
|
required this.conflicts,
|
||||||
|
this.scrollController,
|
||||||
|
});
|
||||||
|
|
||||||
|
static Future<Map<String, ConflictChoice>?> show(
|
||||||
|
BuildContext context,
|
||||||
|
List<MoveCopyConflict> conflicts,
|
||||||
|
) {
|
||||||
|
return showGradualBottomSheet<Map<String, ConflictChoice>>(
|
||||||
|
context,
|
||||||
|
builder: (context, scrollController) => MoveCopyConflictSheet(
|
||||||
|
conflicts: conflicts,
|
||||||
|
scrollController: scrollController,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<MoveCopyConflictSheet> createState() => _MoveCopyConflictSheetState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _MoveCopyConflictSheetState extends State<MoveCopyConflictSheet> {
|
||||||
|
bool _decidingPerItem = false;
|
||||||
|
late final Map<String, ConflictChoice> _perItemChoices = {
|
||||||
|
for (final conflict in widget.conflicts)
|
||||||
|
conflict.item.id: ConflictChoice.keepBoth,
|
||||||
|
};
|
||||||
|
|
||||||
|
void _resolveAll(ConflictChoice choice) {
|
||||||
|
Navigator.pop(context, {
|
||||||
|
for (final conflict in widget.conflicts) conflict.item.id: choice,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void _confirmPerItem() {
|
||||||
|
Navigator.pop(context, _perItemChoices);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final colorScheme = theme.colorScheme;
|
||||||
|
final count = widget.conflicts.length;
|
||||||
|
|
||||||
|
return ListView(
|
||||||
|
controller: widget.scrollController,
|
||||||
|
padding: const EdgeInsets.fromLTRB(20, 12, 20, 24),
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
count == 1
|
||||||
|
? '1 item already exists at the destination'
|
||||||
|
: '$count items already exist at the destination',
|
||||||
|
style: theme.textTheme.titleMedium?.copyWith(
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text(
|
||||||
|
'Choose how to handle the conflicts.',
|
||||||
|
style: theme.textTheme.bodySmall?.copyWith(
|
||||||
|
color: colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
if (!_decidingPerItem) ...[
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () => _resolveAll(ConflictChoice.overwrite),
|
||||||
|
child: const Text('Overwrite all'),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
FilledButton.tonal(
|
||||||
|
onPressed: () => _resolveAll(ConflictChoice.keepBoth),
|
||||||
|
child: const Text('Keep both (rename)'),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
OutlinedButton(
|
||||||
|
onPressed: () => setState(() => _decidingPerItem = true),
|
||||||
|
child: const Text('Decide per item'),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
const Divider(),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
],
|
||||||
|
for (final conflict in widget.conflicts)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
conflict.item.isFolder
|
||||||
|
? Icons.folder_rounded
|
||||||
|
: Icons.insert_drive_file_rounded,
|
||||||
|
color: colorScheme.onSurfaceVariant,
|
||||||
|
size: 20,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 10),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
conflict.item.name,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: theme.textTheme.bodyMedium?.copyWith(
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
if (_decidingPerItem) ...[
|
||||||
|
const SizedBox(height: 6),
|
||||||
|
SizedBox(
|
||||||
|
width: double.infinity,
|
||||||
|
child: SegmentedButton<ConflictChoice>(
|
||||||
|
segments: const [
|
||||||
|
ButtonSegment(
|
||||||
|
value: ConflictChoice.overwrite,
|
||||||
|
label: Text('Overwrite'),
|
||||||
|
),
|
||||||
|
ButtonSegment(
|
||||||
|
value: ConflictChoice.keepBoth,
|
||||||
|
label: Text('Keep both'),
|
||||||
|
),
|
||||||
|
ButtonSegment(
|
||||||
|
value: ConflictChoice.skip,
|
||||||
|
label: Text('Skip'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
selected: {_perItemChoices[conflict.item.id]!},
|
||||||
|
showSelectedIcon: false,
|
||||||
|
onSelectionChanged: (selection) => setState(() {
|
||||||
|
_perItemChoices[conflict.item.id] = selection.first;
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (_decidingPerItem) ...[
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
SizedBox(
|
||||||
|
width: double.infinity,
|
||||||
|
child: FilledButton(
|
||||||
|
onPressed: _confirmPerItem,
|
||||||
|
child: const Text('Confirm'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+108
-12
@@ -1,10 +1,14 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:path/path.dart' as p;
|
||||||
|
import 'package:path_provider/path_provider.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:share_plus/share_plus.dart';
|
||||||
import '../models/nextcloud_item.dart';
|
import '../models/nextcloud_item.dart';
|
||||||
import '../models/nextcloud_share.dart';
|
import '../models/nextcloud_share.dart';
|
||||||
import '../models/nextcloud_sharee.dart';
|
import '../models/nextcloud_sharee.dart';
|
||||||
import '../providers/server_provider.dart';
|
import '../providers/server_provider.dart';
|
||||||
|
import 'details/details_sheet.dart' show DetailsHeader;
|
||||||
import 'gradual_bottom_sheet.dart';
|
import 'gradual_bottom_sheet.dart';
|
||||||
|
|
||||||
IconData _shareTypeIcon(ShareType type) {
|
IconData _shareTypeIcon(ShareType type) {
|
||||||
@@ -66,6 +70,8 @@ class _ShareSheetState extends State<ShareSheet> {
|
|||||||
List<NextcloudShare> _inherited = [];
|
List<NextcloudShare> _inherited = [];
|
||||||
List<NextcloudSharee> _searchResults = [];
|
List<NextcloudSharee> _searchResults = [];
|
||||||
bool _isSearching = false;
|
bool _isSearching = false;
|
||||||
|
bool _isAddingEmail = false;
|
||||||
|
bool _isSharingFile = false;
|
||||||
final _searchController = TextEditingController();
|
final _searchController = TextEditingController();
|
||||||
final _emailController = TextEditingController();
|
final _emailController = TextEditingController();
|
||||||
|
|
||||||
@@ -140,6 +146,7 @@ class _ShareSheetState extends State<ShareSheet> {
|
|||||||
Future<void> _addEmailShare() async {
|
Future<void> _addEmailShare() async {
|
||||||
final email = _emailController.text.trim();
|
final email = _emailController.text.trim();
|
||||||
if (email.isEmpty) return;
|
if (email.isEmpty) return;
|
||||||
|
setState(() => _isAddingEmail = true);
|
||||||
final provider = context.read<ServerProvider>();
|
final provider = context.read<ServerProvider>();
|
||||||
final messenger = ScaffoldMessenger.of(context);
|
final messenger = ScaffoldMessenger.of(context);
|
||||||
final share = await provider.createShare(
|
final share = await provider.createShare(
|
||||||
@@ -149,6 +156,7 @@ class _ShareSheetState extends State<ShareSheet> {
|
|||||||
);
|
);
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
if (share == null) {
|
if (share == null) {
|
||||||
|
setState(() => _isAddingEmail = false);
|
||||||
messenger.showSnackBar(
|
messenger.showSnackBar(
|
||||||
const SnackBar(
|
const SnackBar(
|
||||||
content: Text('Could not create email share'),
|
content: Text('Could not create email share'),
|
||||||
@@ -160,6 +168,7 @@ class _ShareSheetState extends State<ShareSheet> {
|
|||||||
setState(() {
|
setState(() {
|
||||||
_shares = [..._shares, share];
|
_shares = [..._shares, share];
|
||||||
_emailController.clear();
|
_emailController.clear();
|
||||||
|
_isAddingEmail = false;
|
||||||
});
|
});
|
||||||
messenger.showSnackBar(
|
messenger.showSnackBar(
|
||||||
SnackBar(
|
SnackBar(
|
||||||
@@ -216,13 +225,59 @@ class _ShareSheetState extends State<ShareSheet> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Downloads the item to a scratch file and hands it to Android's native
|
||||||
|
/// "Share to..." sheet (`share_plus`) - a completely different action
|
||||||
|
/// from the rest of this sheet (which shares *within* Nextcloud, via
|
||||||
|
/// users/links) and the only one here that reads the file's actual
|
||||||
|
/// bytes.
|
||||||
|
Future<void> _shareFileDirectly() async {
|
||||||
|
final provider = context.read<ServerProvider>();
|
||||||
|
if (provider.service == null) return;
|
||||||
|
setState(() => _isSharingFile = true);
|
||||||
|
final messenger = ScaffoldMessenger.of(context);
|
||||||
|
try {
|
||||||
|
// Already mirrored locally by device sync? Share that copy straight
|
||||||
|
// away instead of a fresh WebDAV fetch - see
|
||||||
|
// ServerProvider.localSyncedFilePath.
|
||||||
|
final tempPath =
|
||||||
|
await provider.localSyncedFilePath(widget.item) ??
|
||||||
|
await () async {
|
||||||
|
final tempDir = await getTemporaryDirectory();
|
||||||
|
final path = p.join(tempDir.path, widget.item.name);
|
||||||
|
await provider.service!.downloadToFile(widget.item.path, path);
|
||||||
|
return path;
|
||||||
|
}();
|
||||||
|
if (!mounted) return;
|
||||||
|
await SharePlus.instance.share(
|
||||||
|
ShareParams(
|
||||||
|
files: [XFile(tempPath)],
|
||||||
|
fileNameOverrides: [widget.item.name],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} catch (_) {
|
||||||
|
if (mounted) {
|
||||||
|
messenger.showSnackBar(
|
||||||
|
const SnackBar(
|
||||||
|
content: Text('Could not share the file'),
|
||||||
|
behavior: SnackBarBehavior.floating,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (mounted) setState(() => _isSharingFile = false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Widget _sectionHeader(String label) {
|
Widget _sectionHeader(String label) {
|
||||||
final colorScheme = Theme.of(context).colorScheme;
|
final theme = Theme.of(context);
|
||||||
|
final colorScheme = theme.colorScheme;
|
||||||
return Row(
|
return Row(
|
||||||
children: [
|
children: [
|
||||||
Text(
|
Text(
|
||||||
label,
|
label,
|
||||||
style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 15),
|
style: theme.textTheme.titleSmall?.copyWith(
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(width: 6),
|
const SizedBox(width: 6),
|
||||||
Icon(
|
Icon(
|
||||||
@@ -301,27 +356,52 @@ class _ShareSheetState extends State<ShareSheet> {
|
|||||||
|
|
||||||
return ListView(
|
return ListView(
|
||||||
controller: widget.scrollController,
|
controller: widget.scrollController,
|
||||||
padding: const EdgeInsets.fromLTRB(20, 12, 20, 24),
|
padding: const EdgeInsets.fromLTRB(20, 0, 20, 24),
|
||||||
children: [
|
children: [
|
||||||
Text(
|
// Same icon/name/meta header as DetailsSheet, so this and its
|
||||||
widget.item.name,
|
// sibling per-item bottom sheet open on identical chrome - just a
|
||||||
maxLines: 1,
|
// bare title `Text` here read as under-designed by comparison.
|
||||||
overflow: TextOverflow.ellipsis,
|
DetailsHeader(
|
||||||
style: theme.textTheme.titleMedium?.copyWith(
|
item: widget.item,
|
||||||
fontWeight: FontWeight.w700,
|
padding: const EdgeInsets.only(top: 12, bottom: 8),
|
||||||
),
|
),
|
||||||
|
if (!widget.item.isFolder) ...[
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
ListTile(
|
||||||
|
contentPadding: EdgeInsets.zero,
|
||||||
|
leading: _isSharingFile
|
||||||
|
? const Padding(
|
||||||
|
padding: EdgeInsets.all(12),
|
||||||
|
child: SizedBox(
|
||||||
|
width: 20,
|
||||||
|
height: 20,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
)
|
||||||
|
: const Icon(Icons.ios_share_rounded),
|
||||||
|
title: const Text('Share file directly'),
|
||||||
|
subtitle: const Text('Send the file itself via another app'),
|
||||||
|
onTap: _isSharingFile ? null : _shareFileDirectly,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
const Divider(),
|
||||||
|
],
|
||||||
|
const SizedBox(height: 12),
|
||||||
_sectionHeader('Internal shares'),
|
_sectionHeader('Internal shares'),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
TextField(
|
TextField(
|
||||||
controller: _searchController,
|
controller: _searchController,
|
||||||
decoration: InputDecoration(
|
decoration: InputDecoration(
|
||||||
|
isDense: true,
|
||||||
|
contentPadding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: 16,
|
||||||
|
vertical: 12,
|
||||||
|
),
|
||||||
hintText: 'Type names or teams',
|
hintText: 'Type names or teams',
|
||||||
prefixIcon: const Icon(Icons.search_rounded),
|
prefixIcon: const Icon(Icons.search_rounded),
|
||||||
suffixIcon: _isSearching
|
suffixIcon: _isSearching
|
||||||
? const Padding(
|
? const Padding(
|
||||||
padding: EdgeInsets.all(14),
|
padding: EdgeInsets.all(12),
|
||||||
child: SizedBox(
|
child: SizedBox(
|
||||||
width: 16,
|
width: 16,
|
||||||
height: 16,
|
height: 16,
|
||||||
@@ -378,9 +458,25 @@ class _ShareSheetState extends State<ShareSheet> {
|
|||||||
TextField(
|
TextField(
|
||||||
controller: _emailController,
|
controller: _emailController,
|
||||||
keyboardType: TextInputType.emailAddress,
|
keyboardType: TextInputType.emailAddress,
|
||||||
|
enabled: !_isAddingEmail,
|
||||||
decoration: InputDecoration(
|
decoration: InputDecoration(
|
||||||
|
isDense: true,
|
||||||
|
contentPadding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: 16,
|
||||||
|
vertical: 12,
|
||||||
|
),
|
||||||
hintText: 'Type an email',
|
hintText: 'Type an email',
|
||||||
prefixIcon: const Icon(Icons.email_outlined),
|
prefixIcon: const Icon(Icons.email_rounded),
|
||||||
|
suffixIcon: _isAddingEmail
|
||||||
|
? const Padding(
|
||||||
|
padding: EdgeInsets.all(12),
|
||||||
|
child: SizedBox(
|
||||||
|
width: 16,
|
||||||
|
height: 16,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: null,
|
||||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)),
|
border: OutlineInputBorder(borderRadius: BorderRadius.circular(16)),
|
||||||
filled: true,
|
filled: true,
|
||||||
fillColor: colorScheme.surfaceContainerLow,
|
fillColor: colorScheme.surfaceContainerLow,
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import '../models/sync_status.dart';
|
||||||
|
|
||||||
|
/// A small corner badge over a thumbnail showing device-sync status - a
|
||||||
|
/// `cloud_done` badge once a file's mirrored locally, `sync` while it's
|
||||||
|
/// actively being transferred. Nothing is drawn for `none`/`conflict`
|
||||||
|
/// (conflicts surface in the sync header, not as per-tile noise).
|
||||||
|
class SyncStatusBadge extends StatelessWidget {
|
||||||
|
final SyncItemStatus status;
|
||||||
|
|
||||||
|
const SyncStatusBadge({super.key, required this.status});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
if (status != SyncItemStatus.syncing && status != SyncItemStatus.synced) {
|
||||||
|
return const SizedBox.shrink();
|
||||||
|
}
|
||||||
|
final colorScheme = Theme.of(context).colorScheme;
|
||||||
|
final icon = status == SyncItemStatus.syncing
|
||||||
|
? Icons.sync_rounded
|
||||||
|
: Icons.cloud_done_rounded;
|
||||||
|
|
||||||
|
return Container(
|
||||||
|
width: 18,
|
||||||
|
height: 18,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: colorScheme.surface,
|
||||||
|
shape: BoxShape.circle,
|
||||||
|
border: Border.all(color: colorScheme.surface, width: 1.5),
|
||||||
|
),
|
||||||
|
child: Icon(icon, size: 13, color: colorScheme.primary),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,23 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:material_symbols_icons/symbols.dart';
|
||||||
import '../models/nextcloud_item.dart';
|
import '../models/nextcloud_item.dart';
|
||||||
|
import '../models/sync_status.dart';
|
||||||
import '../providers/server_provider.dart';
|
import '../providers/server_provider.dart';
|
||||||
|
|
||||||
|
/// Icon/label for the persistent header chip/panel - reflects device-sync
|
||||||
|
/// status (see `ServerProvider.syncHeaderStatus`), not the WebDAV
|
||||||
|
/// directory-listing refresh the pull gesture itself triggers (that has
|
||||||
|
/// its own, separate floating spinner bubble - see
|
||||||
|
/// `_SyncedHeaderScaffoldState`'s `_isRefreshing`).
|
||||||
|
(IconData, String) _syncHeaderDisplay(SyncHeaderStatus status) {
|
||||||
|
return switch (status) {
|
||||||
|
SyncHeaderStatus.off => (Icons.cloud_off_rounded, 'Sync off'),
|
||||||
|
SyncHeaderStatus.syncing => (Icons.cloud_sync_rounded, 'Syncing…'),
|
||||||
|
SyncHeaderStatus.done => (Icons.cloud_done_rounded, 'Synced'),
|
||||||
|
SyncHeaderStatus.alert => (Symbols.cloud_alert_rounded, 'Sync issue'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
String formatBytes(int bytes) {
|
String formatBytes(int bytes) {
|
||||||
if (bytes <= 0) return '0 B';
|
if (bytes <= 0) return '0 B';
|
||||||
if (bytes < 1024) return '$bytes B';
|
if (bytes < 1024) return '$bytes B';
|
||||||
@@ -41,6 +57,15 @@ class SyncedHeaderScaffold extends StatefulWidget {
|
|||||||
/// `provider.fetchTrash` for a tab backed by different data.
|
/// `provider.fetchTrash` for a tab backed by different data.
|
||||||
final Future<void> Function()? onRefresh;
|
final Future<void> Function()? onRefresh;
|
||||||
|
|
||||||
|
/// When non-null (a tab is mid-selection), this takes over the pinned top
|
||||||
|
/// bar entirely - replacing the sync-status chip, [actions], and the
|
||||||
|
/// pull-to-reveal quota panel - instead of appearing as a second app bar
|
||||||
|
/// further down in [contentSlivers]. Selection is a modal-ish state (you
|
||||||
|
/// came here to act on specific items), so it reads better as the one
|
||||||
|
/// thing at the very top than as a strip sandwiched under the normal
|
||||||
|
/// chrome.
|
||||||
|
final Widget? selectionBar;
|
||||||
|
|
||||||
const SyncedHeaderScaffold({
|
const SyncedHeaderScaffold({
|
||||||
super.key,
|
super.key,
|
||||||
required this.scrollController,
|
required this.scrollController,
|
||||||
@@ -48,6 +73,7 @@ class SyncedHeaderScaffold extends StatefulWidget {
|
|||||||
required this.actions,
|
required this.actions,
|
||||||
required this.contentSlivers,
|
required this.contentSlivers,
|
||||||
this.onRefresh,
|
this.onRefresh,
|
||||||
|
this.selectionBar,
|
||||||
});
|
});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -175,17 +201,29 @@ class _SyncedHeaderScaffoldState extends State<SyncedHeaderScaffold> {
|
|||||||
slivers: [
|
slivers: [
|
||||||
SliverAppBar(
|
SliverAppBar(
|
||||||
pinned: true,
|
pinned: true,
|
||||||
stretch: true,
|
stretch: widget.selectionBar == null,
|
||||||
expandedHeight: _headerLocked ? 190 : kToolbarHeight,
|
expandedHeight: widget.selectionBar != null
|
||||||
|
? kToolbarHeight
|
||||||
|
: (_headerLocked
|
||||||
|
? 190.0 + provider.syncConflicts.length * 52.0
|
||||||
|
: kToolbarHeight),
|
||||||
collapsedHeight: kToolbarHeight,
|
collapsedHeight: kToolbarHeight,
|
||||||
backgroundColor: colorScheme.surfaceContainer,
|
backgroundColor: colorScheme.surfaceContainer,
|
||||||
surfaceTintColor: colorScheme.surfaceContainer,
|
surfaceTintColor: colorScheme.surfaceContainer,
|
||||||
scrolledUnderElevation: 0,
|
scrolledUnderElevation: 0,
|
||||||
automaticallyImplyLeading: false,
|
automaticallyImplyLeading: false,
|
||||||
leadingWidth: _headerLocked ? 56 : 160,
|
leadingWidth: widget.selectionBar != null
|
||||||
leading: leadingWidget,
|
? 0
|
||||||
actions: widget.actions,
|
: (_headerLocked ? 56 : 160),
|
||||||
flexibleSpace: FlexibleSpaceBar(
|
leading: widget.selectionBar != null ? null : leadingWidget,
|
||||||
|
titleSpacing: widget.selectionBar != null ? 0 : null,
|
||||||
|
title: widget.selectionBar,
|
||||||
|
actions: widget.selectionBar != null
|
||||||
|
? const []
|
||||||
|
: widget.actions,
|
||||||
|
flexibleSpace: widget.selectionBar != null
|
||||||
|
? null
|
||||||
|
: FlexibleSpaceBar(
|
||||||
background: _SyncedStretchPanel(
|
background: _SyncedStretchPanel(
|
||||||
provider: provider,
|
provider: provider,
|
||||||
forceVisible: _headerLocked,
|
forceVisible: _headerLocked,
|
||||||
@@ -258,7 +296,11 @@ class _SyncStatusChip extends StatelessWidget {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final theme = Theme.of(context);
|
final theme = Theme.of(context);
|
||||||
final colorScheme = theme.colorScheme;
|
final colorScheme = theme.colorScheme;
|
||||||
final quota = provider.quota;
|
final status = provider.syncHeaderStatus;
|
||||||
|
final (icon, label) = _syncHeaderDisplay(status);
|
||||||
|
final iconColor = status == SyncHeaderStatus.alert
|
||||||
|
? colorScheme.error
|
||||||
|
: colorScheme.primary;
|
||||||
|
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.only(left: 12),
|
padding: const EdgeInsets.only(left: 12),
|
||||||
@@ -273,16 +315,10 @@ class _SyncStatusChip extends StatelessWidget {
|
|||||||
child: Row(
|
child: Row(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: [
|
children: [
|
||||||
Icon(
|
Icon(icon, color: iconColor, size: 18),
|
||||||
provider.isLoading
|
|
||||||
? Icons.cloud_sync_rounded
|
|
||||||
: Icons.cloud_done_outlined,
|
|
||||||
color: colorScheme.primary,
|
|
||||||
size: 18,
|
|
||||||
),
|
|
||||||
const SizedBox(width: 6),
|
const SizedBox(width: 6),
|
||||||
Text(
|
Text(
|
||||||
quota != null ? formatQuota(quota) : 'Sync',
|
label,
|
||||||
style: theme.textTheme.labelMedium?.copyWith(
|
style: theme.textTheme.labelMedium?.copyWith(
|
||||||
fontWeight: FontWeight.w700,
|
fontWeight: FontWeight.w700,
|
||||||
),
|
),
|
||||||
@@ -328,6 +364,9 @@ class _SyncedStretchPanel extends StatelessWidget {
|
|||||||
// before the 100px lock threshold.
|
// before the 100px lock threshold.
|
||||||
final progress = forceVisible ? 1.0 : (stretch / 50).clamp(0.0, 1.0);
|
final progress = forceVisible ? 1.0 : (stretch / 50).clamp(0.0, 1.0);
|
||||||
final quota = provider.quota;
|
final quota = provider.quota;
|
||||||
|
final status = provider.syncHeaderStatus;
|
||||||
|
final (_, statusLabel) = _syncHeaderDisplay(status);
|
||||||
|
final conflicts = provider.syncConflicts;
|
||||||
|
|
||||||
return Stack(
|
return Stack(
|
||||||
children: [
|
children: [
|
||||||
@@ -345,7 +384,7 @@ class _SyncedStretchPanel extends StatelessWidget {
|
|||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
Text(
|
Text(
|
||||||
provider.isLoading ? 'Syncing…' : 'Synced',
|
statusLabel,
|
||||||
style: theme.textTheme.titleLarge?.copyWith(
|
style: theme.textTheme.titleLarge?.copyWith(
|
||||||
fontWeight: FontWeight.w700,
|
fontWeight: FontWeight.w700,
|
||||||
),
|
),
|
||||||
@@ -394,6 +433,17 @@ class _SyncedStretchPanel extends StatelessWidget {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
if (conflicts.isNotEmpty) ...[
|
||||||
|
const SizedBox(height: 10),
|
||||||
|
for (final conflict in conflicts)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 8),
|
||||||
|
child: _SyncConflictRow(
|
||||||
|
conflict: conflict,
|
||||||
|
provider: provider,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -404,3 +454,93 @@ class _SyncedStretchPanel extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One row in the locked-open panel's conflicts section - a file that
|
||||||
|
/// changed both locally and on the server since the last sync, with the
|
||||||
|
/// same two resolutions the sync-conflict notification offers (see
|
||||||
|
/// `SyncWorker.notifyConflicts`/`ConflictResolveWorker` on the native
|
||||||
|
/// side), just triggered in-app instead.
|
||||||
|
class _SyncConflictRow extends StatefulWidget {
|
||||||
|
final SyncConflictInfo conflict;
|
||||||
|
final ServerProvider provider;
|
||||||
|
|
||||||
|
const _SyncConflictRow({required this.conflict, required this.provider});
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_SyncConflictRow> createState() => _SyncConflictRowState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _SyncConflictRowState extends State<_SyncConflictRow> {
|
||||||
|
bool _resolving = false;
|
||||||
|
|
||||||
|
Future<void> _resolve(bool useLocal) async {
|
||||||
|
setState(() => _resolving = true);
|
||||||
|
try {
|
||||||
|
await widget.provider.resolveSyncConflict(
|
||||||
|
widget.conflict,
|
||||||
|
useLocal: useLocal,
|
||||||
|
);
|
||||||
|
} catch (_) {
|
||||||
|
if (mounted) setState(() => _resolving = false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final colorScheme = theme.colorScheme;
|
||||||
|
|
||||||
|
return Container(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: colorScheme.errorContainer.withValues(alpha: 0.4),
|
||||||
|
borderRadius: BorderRadius.circular(16),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: [
|
||||||
|
Icon(Symbols.cloud_alert_rounded, color: colorScheme.error, size: 18),
|
||||||
|
const SizedBox(width: 10),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
widget.conflict.name,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: theme.textTheme.bodyMedium?.copyWith(
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (_resolving)
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.symmetric(horizontal: 8),
|
||||||
|
child: SizedBox(
|
||||||
|
width: 16,
|
||||||
|
height: 16,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else ...[
|
||||||
|
TextButton(
|
||||||
|
style: TextButton.styleFrom(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||||
|
minimumSize: Size.zero,
|
||||||
|
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||||
|
),
|
||||||
|
onPressed: () => _resolve(true),
|
||||||
|
child: const Text('Keep local'),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
style: TextButton.styleFrom(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||||
|
minimumSize: Size.zero,
|
||||||
|
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||||
|
),
|
||||||
|
onPressed: () => _resolve(false),
|
||||||
|
child: const Text('Use server'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -712,6 +712,54 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.11.0"
|
version: "2.11.0"
|
||||||
|
permission_handler:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: permission_handler
|
||||||
|
sha256: "59adad729136f01ea9e35a48f5d1395e25cba6cea552249ddbe9cf950f5d7849"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "11.4.0"
|
||||||
|
permission_handler_android:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: permission_handler_android
|
||||||
|
sha256: d3971dcdd76182a0c198c096b5db2f0884b0d4196723d21a866fc4cdea057ebc
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "12.1.0"
|
||||||
|
permission_handler_apple:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: permission_handler_apple
|
||||||
|
sha256: f49cb15a064ea9d974fc7fbb302099353b7b170d07284e86e264561579e5bcf8
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "9.6.1"
|
||||||
|
permission_handler_html:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: permission_handler_html
|
||||||
|
sha256: "6ea98b3f17f60d3b527f2647ed2ab4dc0f6bfe25b22cb1c363f5d8f62252f6ac"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.1.4+1"
|
||||||
|
permission_handler_platform_interface:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: permission_handler_platform_interface
|
||||||
|
sha256: ed86a61c190258fdd65de395ea0632822e3415c1faec38eae0c31b479c28a531
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "4.4.1"
|
||||||
|
permission_handler_windows:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: permission_handler_windows
|
||||||
|
sha256: caeae01858a0a7d2df67a445ac98e1ad95e55a0e77c73044f4e9b1c8c2289cbd
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.2.2"
|
||||||
petitparser:
|
petitparser:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ dependencies:
|
|||||||
marquee: ^2.3.0
|
marquee: ^2.3.0
|
||||||
local_auth: ^2.3.0
|
local_auth: ^2.3.0
|
||||||
webview_flutter: ^4.14.1
|
webview_flutter: ^4.14.1
|
||||||
|
permission_handler: ^11.3.1
|
||||||
|
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
flutter_test:
|
||||||
|
|||||||
@@ -11,6 +11,7 @@
|
|||||||
#include <flutter_secure_storage_windows/flutter_secure_storage_windows_plugin.h>
|
#include <flutter_secure_storage_windows/flutter_secure_storage_windows_plugin.h>
|
||||||
#include <local_auth_windows/local_auth_plugin.h>
|
#include <local_auth_windows/local_auth_plugin.h>
|
||||||
#include <pdfx/pdfx_plugin.h>
|
#include <pdfx/pdfx_plugin.h>
|
||||||
|
#include <permission_handler_windows/permission_handler_windows_plugin.h>
|
||||||
#include <share_plus/share_plus_windows_plugin_c_api.h>
|
#include <share_plus/share_plus_windows_plugin_c_api.h>
|
||||||
#include <url_launcher_windows/url_launcher_windows.h>
|
#include <url_launcher_windows/url_launcher_windows.h>
|
||||||
|
|
||||||
@@ -25,6 +26,8 @@ void RegisterPlugins(flutter::PluginRegistry* registry) {
|
|||||||
registry->GetRegistrarForPlugin("LocalAuthPlugin"));
|
registry->GetRegistrarForPlugin("LocalAuthPlugin"));
|
||||||
PdfxPluginRegisterWithRegistrar(
|
PdfxPluginRegisterWithRegistrar(
|
||||||
registry->GetRegistrarForPlugin("PdfxPlugin"));
|
registry->GetRegistrarForPlugin("PdfxPlugin"));
|
||||||
|
PermissionHandlerWindowsPluginRegisterWithRegistrar(
|
||||||
|
registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin"));
|
||||||
SharePlusWindowsPluginCApiRegisterWithRegistrar(
|
SharePlusWindowsPluginCApiRegisterWithRegistrar(
|
||||||
registry->GetRegistrarForPlugin("SharePlusWindowsPluginCApi"));
|
registry->GetRegistrarForPlugin("SharePlusWindowsPluginCApi"));
|
||||||
UrlLauncherWindowsRegisterWithRegistrar(
|
UrlLauncherWindowsRegisterWithRegistrar(
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ list(APPEND FLUTTER_PLUGIN_LIST
|
|||||||
flutter_secure_storage_windows
|
flutter_secure_storage_windows
|
||||||
local_auth_windows
|
local_auth_windows
|
||||||
pdfx
|
pdfx
|
||||||
|
permission_handler_windows
|
||||||
share_plus
|
share_plus
|
||||||
url_launcher_windows
|
url_launcher_windows
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user