Offline tab as Files view, automatic background sync, sync notifications
Build APK / build (push) Successful in 5m27s

- Offline tab is now FilesView(offline: true) over a FolderBrowser interface
  (FilesController / OfflineController) sharing controls, tiles, thumbnails
- Synced files follow the Files Cache rule (default: refresh every 15 min):
  per-account WorkManager jobs, in-app timer, resume and pull triggers;
  root-etag shortcut skips full walks when nothing changed
- Single sync at a time (shared lock); logging out stops that account's sync
- Sync safety: PROPFIND failures skip the path instead of deleting local files
- Mirror empty folders and remove deleted ones; drop synced paths deleted on
  the server; missing local files are re-downloaded
- Notifications: silent per-account sync notifications, "Background sync
  notifications" setting, audible upload/download completion
- Files refresh in place (no spinner flash); retry after network returns
- Fix sync badges not updating (shared native status stream), "Sync off" on
  launch (eager providers), Files Cache section moved under Device Sync

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-21 18:06:55 -04:00
co-authored by Claude Sonnet 5
parent 49ae712f5e
commit f2bba2914e
38 changed files with 3133 additions and 741 deletions
+31 -4
View File
@@ -6,9 +6,11 @@ import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'models/app_tab.dart';
import 'models/pick_request.dart';
import 'providers/connectivity_controller.dart';
import 'providers/favorites_controller.dart';
import 'providers/files_controller.dart';
import 'providers/item_operations.dart';
import 'providers/offline_controller.dart';
import 'providers/photos_controller.dart';
import 'providers/pick_controller.dart';
import 'providers/recent_controller.dart';
@@ -38,14 +40,26 @@ void main() {
// replaced/recreated for the app's lifetime (account switching is
// internal state on SessionController, not a new provider instance).
providers: [
ChangeNotifierProvider(create: (_) => SessionController()),
ChangeNotifierProvider(create: (_) => SettingsController()),
ChangeNotifierProvider(create: (_) => ConnectivityController()),
ChangeNotifierProvider(
create: (context) => SyncStatusController(context.read()),
create: (context) => SessionController(context.read()),
),
ChangeNotifierProvider(create: (_) => SettingsController()),
// Before SyncStatusController, which follows its Files Cache rule
// for how often synced files refresh.
ChangeNotifierProvider(
create: (context) => FilesController(context.read()),
),
ChangeNotifierProvider(
// Eager (`lazy: false`) - this controller only loads its persisted
// state when SessionController fires the account-ready event, and
// that fires once at startup, before any widget has read this
// provider. Lazily created, it would register its listener too
// late and stay empty ("Sync off") until an account switch.
lazy: false,
create: (context) =>
SyncStatusController(context.read(), context.read()),
),
ChangeNotifierProvider(
create: (context) =>
PhotosController(context.read(), context.read()),
@@ -66,6 +80,12 @@ void main() {
ChangeNotifierProvider(
create: (context) => PickController(context.read()),
),
ChangeNotifierProvider(
// Eager for the same reason as SyncStatusController above.
lazy: false,
create: (context) =>
OfflineController(context.read(), context.read()),
),
Provider(
create: (context) => ItemOperations(
session: context.read(),
@@ -276,6 +296,7 @@ class _MainShellViewState extends State<MainShellView> {
Widget build(BuildContext context) {
final settings = context.watch<SettingsController>();
final pick = context.watch<PickController>();
final connectivity = context.watch<ConnectivityController>();
// A one-shot request (e.g. tapping a search result) to switch tabs -
// consumed here so it only fires once, then cleared after this frame
@@ -294,9 +315,15 @@ class _MainShellViewState extends State<MainShellView> {
// 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.
// them, since picking is a separate mode from normal browsing. With
// no network at all, every other tab would just show its own loading
// spinner forever/an error state, so the bottom nav collapses to just
// Offline - the one tab that works without a connection (see
// `FilesView(offline: true)`/`ConnectivityController`).
final visible = pickRequest != null
? [AppTab.files, AppTab.photos]
: connectivity.isOffline
? [AppTab.offline]
: settings.visibleTabs;
final selectedTab = visible.contains(_currentTab)
? _currentTab
+14 -1
View File
@@ -4,7 +4,16 @@ import 'package:material_symbols_icons/symbols.dart';
/// Every destination the bottom nav bar can show. Order here is only the
/// fallback default — actual order/visibility/default-tab are user
/// configurable and persisted in `SettingsController`.
enum AppTab { files, photos, favorites, activity, trash, shares, recent }
enum AppTab {
files,
photos,
favorites,
activity,
trash,
shares,
recent,
offline,
}
/// At most this many tabs may be visible in the bottom nav bar at once —
/// the rest are reachable through the "more" dropdown instead.
@@ -27,6 +36,8 @@ extension AppTabInfo on AppTab {
return 'Shares';
case AppTab.recent:
return 'Recent';
case AppTab.offline:
return 'Offline';
}
}
@@ -46,6 +57,8 @@ extension AppTabInfo on AppTab {
return Icons.groups_rounded;
case AppTab.recent:
return Symbols.search_activity_rounded;
case AppTab.offline:
return Icons.offline_pin_rounded;
}
}
}
@@ -0,0 +1,53 @@
import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/foundation.dart';
/// Whether the device currently has *any* network route (Wi-Fi, mobile
/// data, ethernet - not a guarantee the Nextcloud server itself is
/// reachable, just OS-level connectivity). The single source of truth
/// other controllers/views consult before attempting a network request or
/// deciding whether to fall back to offline-only behavior - see
/// `SessionController` (skips its login-restore HTTP call entirely while
/// offline) and `MainShellView` (restricts the bottom nav to just the
/// Offline tab while offline).
class ConnectivityController extends ChangeNotifier {
bool _isOffline = false;
StreamSubscription<List<ConnectivityResult>>? _sub;
Timer? _recheckTimer;
bool get isOffline => _isOffline;
ConnectivityController() {
Connectivity().checkConnectivity().then(_apply);
_sub = Connectivity().onConnectivityChanged.listen(_apply);
// The very first check can spuriously report "no network" while the
// OS's connectivity stack is still attaching callbacks to this
// just-started process - a real Android cold-start quirk, not a
// genuine transition. That matters here specifically because
// onConnectivityChanged only fires on actual transitions, so a false
// initial "offline" read would otherwise stick for the rest of the
// session (SessionController would keep treating every login as
// provisional, and every network-fetching controller would never get
// its real activation signal - see addAccountReadyListener's doc
// comment) even though the device was online the whole time. Re-
// verify once, shortly after, to correct it.
_recheckTimer = Timer(const Duration(seconds: 2), () {
Connectivity().checkConnectivity().then(_apply);
});
}
void _apply(List<ConnectivityResult> results) {
final offline =
results.isEmpty || results.every((r) => r == ConnectivityResult.none);
if (offline == _isOffline) return;
_isOffline = offline;
notifyListeners();
}
@override
void dispose() {
_sub?.cancel();
_recheckTimer?.cancel();
super.dispose();
}
}
+212 -72
View File
@@ -3,6 +3,7 @@ import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/nextcloud_item.dart';
import 'folder_browser.dart';
import 'session_controller.dart';
enum FileSortField { name, dateCreated, dateModified, size }
@@ -20,7 +21,8 @@ enum FilesTypeFilter { all, filesOnly, foldersOnly }
/// content - just the list of names/sizes/dates) are reused across
/// navigation instead of refetched from the server every time.
enum CachePolicy {
/// Every navigation refetches - today's behavior.
/// Every navigation refetches. Synced files are checked each time the app
/// opens (and on pull-to-refresh), but not on a background schedule.
never,
/// A listing is reused until it's older than [FilesController.
@@ -29,9 +31,17 @@ enum CachePolicy {
interval,
/// A listing is reused indefinitely until the user pulls to refresh.
/// Synced files likewise only update on pull-to-refresh / "Sync now".
manual,
}
/// New accounts (and anyone who's never touched the setting) refresh
/// periodically - the Files Cache rule also drives how often synced
/// folders/files are brought in line with the server, see
/// `SyncStatusController`.
const defaultCachePolicy = CachePolicy.interval;
const defaultCacheIntervalMinutes = 15;
/// One cached folder listing and when it was fetched.
class _CachedDirectory {
final List<NextcloudItem> items;
@@ -52,7 +62,9 @@ class _CachedDirectory {
/// comments for why they depend on this one.
///
/// Split out of the former single `ServerProvider` god object.
class FilesController extends ChangeNotifier with WidgetsBindingObserver {
class FilesController extends ChangeNotifier
with WidgetsBindingObserver
implements FolderBrowser {
final SessionController session;
static const _prefGridView = 'ui_grid_view';
@@ -60,8 +72,8 @@ class FilesController extends ChangeNotifier with WidgetsBindingObserver {
static const _prefFilesTypeFilter = 'ui_files_type_filter';
static const _prefShowHiddenFiles = 'ui_show_hidden';
static const _prefFolderSort = 'ui_folder_sort';
static const _prefCachePolicy = 'ui_cache_policy';
static const _prefCacheIntervalMinutes = 'ui_cache_interval_minutes';
static const prefCachePolicy = 'ui_cache_policy';
static const prefCacheIntervalMinutes = 'ui_cache_interval_minutes';
String _currentFolderPath = '/';
List<String> _pathStack = ['/'];
@@ -74,11 +86,16 @@ class FilesController extends ChangeNotifier with WidgetsBindingObserver {
final Map<String, FileSortField> _folderSortField = {};
final Map<String, bool> _folderSortAscending = {};
CachePolicy _cachePolicy = CachePolicy.never;
int _cacheIntervalMinutes = 5;
CachePolicy _cachePolicy = defaultCachePolicy;
int _cacheIntervalMinutes = defaultCacheIntervalMinutes;
final Map<String, _CachedDirectory> _directoryCache = {};
Timer? _cacheRefreshTimer;
// Auto-retry of a failed (not in-place) load that looks like a network
// hiccup - see [_scheduleNetworkRetry].
Timer? _retryTimer;
int _retryAttempt = 0;
List<NextcloudItem> _items = [];
NextcloudUserQuota? _quota;
List<NextcloudActivity> _activities = [];
@@ -89,26 +106,37 @@ class FilesController extends ChangeNotifier with WidgetsBindingObserver {
WidgetsBinding.instance.addObserver(this);
session.addAccountClearedListener(_onAccountCleared);
session.addAccountActivatedListener(_onAccountActivated);
session.addAccountReadyListener(_restoreDisplayPrefs);
}
// Getters
@override
String get currentFolderPath => _currentFolderPath;
@override
List<String> get pathStack => _pathStack;
bool get isGridView => _isGridView;
StorageScope get storageScope => _storageScope;
FilesTypeFilter get filesTypeFilter => _filesTypeFilter;
bool get showHiddenFiles => _showHiddenFiles;
FileSortField get filesSortField =>
_folderSortField[_currentFolderPath] ?? FileSortField.name;
bool get filesSortAscending =>
_folderSortAscending[_currentFolderPath] ?? true;
FileSortField get filesSortField => sortFieldFor(_currentFolderPath);
bool get filesSortAscending => sortAscendingFor(_currentFolderPath);
/// Per-folder sort prefs keyed by remote path - also what the Offline tab
/// reads for the same path in the local mirror, so a folder sorts the
/// same in both places.
FileSortField sortFieldFor(String path) =>
_folderSortField[path] ?? FileSortField.name;
bool sortAscendingFor(String path) => _folderSortAscending[path] ?? true;
CachePolicy get cachePolicy => _cachePolicy;
int get cacheIntervalMinutes => _cacheIntervalMinutes;
@override
bool get isLoading => _isLoading;
@override
String? get errorMessage => _errorMessage;
NextcloudUserQuota? get quota => _quota;
List<NextcloudActivity> get activities => _activities;
@override
List<NextcloudItem> get items => applyFilesDisplayPrefs(_items);
int _compareItems(NextcloudItem a, NextcloudItem b, FileSortField field) {
@@ -140,6 +168,7 @@ class FilesController extends ChangeNotifier with WidgetsBindingObserver {
List<NextcloudItem> source, {
required bool showFavoritesOnly,
required bool showHidden,
bool applyStorageScope = true,
}) {
var filtered = source;
if (showFavoritesOnly) {
@@ -148,13 +177,15 @@ class FilesController extends ChangeNotifier with WidgetsBindingObserver {
if (!showHidden) {
filtered = filtered.where((item) => !_isHiddenItem(item)).toList();
}
filtered = filtered
.where(
(item) => _storageScope == StorageScope.external
? item.isExternalStorage
: !item.isExternalStorage,
)
.toList();
if (applyStorageScope) {
filtered = filtered
.where(
(item) => _storageScope == StorageScope.external
? item.isExternalStorage
: !item.isExternalStorage,
)
.toList();
}
return filtered;
}
@@ -165,13 +196,22 @@ class FilesController extends ChangeNotifier with WidgetsBindingObserver {
/// listings via [fetchFolderListing] rather than reading [items] itself)
/// can render with the exact same controls/behavior as the Files tab
/// without duplicating this logic.
List<NextcloudItem> applyFilesDisplayPrefs(List<NextcloudItem> rawItems) {
///
/// [folderPath] picks which folder's sort prefs apply (default: the
/// Files tab's current folder). [applyStorageScope] is off for the
/// Offline tab, whose local mirror has no cloud/external distinction.
List<NextcloudItem> applyFilesDisplayPrefs(
List<NextcloudItem> rawItems, {
String? folderPath,
bool applyStorageScope = true,
}) {
var filtered = applyCommonFilters(
rawItems,
// Files itself doesn't filter by favorite - that's the dedicated
// Favorites tab's job.
showFavoritesOnly: false,
showHidden: _showHiddenFiles,
applyStorageScope: applyStorageScope,
);
switch (_filesTypeFilter) {
case FilesTypeFilter.all:
@@ -182,17 +222,21 @@ class FilesController extends ChangeNotifier with WidgetsBindingObserver {
filtered = filtered.where((i) => i.isFolder).toList();
}
final field = filesSortField;
final path = folderPath ?? _currentFolderPath;
final field = sortFieldFor(path);
final folders = filtered.where((i) => i.isFolder).toList()
..sort((a, b) => _compareItems(a, b, field));
final files = filtered.where((i) => !i.isFolder).toList()
..sort((a, b) => _compareItems(a, b, field));
return filesSortAscending
return sortAscendingFor(path)
? [...folders, ...files]
: [...folders.reversed, ...files.reversed];
}
void _onAccountCleared() {
_prefsRestore = null;
_retryTimer?.cancel();
_retryAttempt = 0;
_cacheRefreshTimer?.cancel();
_directoryCache.clear();
_folderSortField.clear();
@@ -206,61 +250,97 @@ class FilesController extends ChangeNotifier with WidgetsBindingObserver {
_storageScope = StorageScope.cloud;
_filesTypeFilter = FilesTypeFilter.all;
_showHiddenFiles = false;
_cachePolicy = CachePolicy.never;
_cacheIntervalMinutes = 5;
_cachePolicy = defaultCachePolicy;
_cacheIntervalMinutes = defaultCacheIntervalMinutes;
_isLoading = false;
_errorMessage = null;
notifyListeners();
}
Future<void> _onAccountActivated() async {
// Memoized per account (reset in _onAccountCleared) so the ready-event
// and activated-event paths below share one restore instead of racing
// two reads of the same prefs.
Future<void>? _prefsRestore;
/// Loads this account's display prefs (grid/list, hidden, type filter,
/// sort, cache policy) - hooked to `addAccountReadyListener` as well as
/// activation so the Offline tab, which reads these same prefs, respects
/// them even on a provisional/offline login where activation never fires.
Future<void> _restoreDisplayPrefs() => _prefsRestore ??= _doRestoreDisplayPrefs();
/// Completes once this account's cache policy/display prefs have been
/// loaded from storage - lets `SyncStatusController` schedule background
/// sync from the user's real policy instead of the defaults.
Future<void> get displayPrefsLoaded => _restoreDisplayPrefs();
Future<void> _doRestoreDisplayPrefs() async {
final id = session.activeAccountId;
if (id != null) {
final prefs = await session.prefsFuture;
String k(String base) => session.accountStore.accountPrefKey(id, base);
// The whole prefs-restore block is wrapped, not just the JSON
// decode below - a single bad/mistyped stored value here (an
// unguarded `prefs.getBool`/`getString`/`getInt` throws if the
// key holds a different runtime type than requested) would
// otherwise propagate uncaught out of this method entirely,
// silently skipping `refreshData()` below and leaving the Files
// tab permanently empty on this activation with no error surfaced
// anywhere - exactly what happened before this was guarded.
try {
final prefs = await session.prefsFuture;
String k(String base) => session.accountStore.accountPrefKey(id, base);
_isGridView = prefs.getBool(k(_prefGridView)) ?? false;
final storageScopeName = prefs.getString(k(_prefStorageScope));
_storageScope = StorageScope.values.firstWhere(
(s) => s.name == storageScopeName,
orElse: () => StorageScope.cloud,
);
final filesTypeFilterName = prefs.getString(k(_prefFilesTypeFilter));
_filesTypeFilter = FilesTypeFilter.values.firstWhere(
(f) => f.name == filesTypeFilterName,
orElse: () => FilesTypeFilter.all,
);
_showHiddenFiles = prefs.getBool(k(_prefShowHiddenFiles)) ?? false;
_isGridView = prefs.getBool(k(_prefGridView)) ?? false;
final storageScopeName = prefs.getString(k(_prefStorageScope));
_storageScope = StorageScope.values.firstWhere(
(s) => s.name == storageScopeName,
orElse: () => StorageScope.cloud,
);
final filesTypeFilterName = prefs.getString(k(_prefFilesTypeFilter));
_filesTypeFilter = FilesTypeFilter.values.firstWhere(
(f) => f.name == filesTypeFilterName,
orElse: () => FilesTypeFilter.all,
);
_showHiddenFiles = prefs.getBool(k(_prefShowHiddenFiles)) ?? false;
final folderSortJson = prefs.getString(k(_prefFolderSort));
if (folderSortJson != null) {
try {
final decoded = jsonDecode(folderSortJson) as Map<String, dynamic>;
for (final entry in decoded.entries) {
final value = entry.value as Map<String, dynamic>;
final fieldName = value['field'] as String?;
if (fieldName != null) {
_folderSortField[entry.key] = FileSortField.values.firstWhere(
(f) => f.name == fieldName,
orElse: () => FileSortField.name,
);
final folderSortJson = prefs.getString(k(_prefFolderSort));
if (folderSortJson != null) {
try {
final decoded = jsonDecode(folderSortJson) as Map<String, dynamic>;
for (final entry in decoded.entries) {
final value = entry.value as Map<String, dynamic>;
final fieldName = value['field'] as String?;
if (fieldName != null) {
_folderSortField[entry.key] = FileSortField.values.firstWhere(
(f) => f.name == fieldName,
orElse: () => FileSortField.name,
);
}
final ascending = value['ascending'] as bool?;
if (ascending != null) {
_folderSortAscending[entry.key] = ascending;
}
}
final ascending = value['ascending'] as bool?;
if (ascending != null) _folderSortAscending[entry.key] = ascending;
} catch (e) {
debugPrint('[FilesController] Folder sort restore failed: $e');
}
} catch (e) {
debugPrint('[FilesController] Folder sort restore failed: $e');
}
}
final cachePolicyName = prefs.getString(k(_prefCachePolicy));
_cachePolicy = CachePolicy.values.firstWhere(
(c) => c.name == cachePolicyName,
orElse: () => CachePolicy.never,
);
_cacheIntervalMinutes = prefs.getInt(k(_prefCacheIntervalMinutes)) ?? 5;
notifyListeners();
final cachePolicyName = prefs.getString(k(prefCachePolicy));
_cachePolicy = CachePolicy.values.firstWhere(
(c) => c.name == cachePolicyName,
orElse: () => defaultCachePolicy,
);
_cacheIntervalMinutes =
prefs.getInt(k(prefCacheIntervalMinutes)) ??
defaultCacheIntervalMinutes;
notifyListeners();
} catch (e) {
debugPrint('[FilesController] Account-activation prefs restore failed: $e');
}
}
}
Future<void> _onAccountActivated() async {
await _restoreDisplayPrefs();
_startCacheRefreshTimerIfNeeded();
await refreshData();
}
@@ -305,10 +385,21 @@ class FilesController extends ChangeNotifier with WidgetsBindingObserver {
// can recognize it's for an account the user has already left and
// discard itself instead of overwriting the new account's content.
final gen = session.sessionGeneration;
_retryTimer?.cancel();
_isLoading = true;
_errorMessage = null;
notifyListeners();
// Refreshing a folder that's already on screen (pull-to-refresh, the
// periodic cache refresh) swaps the listing in place once the server
// answers - blanking the list to a spinner first made every refresh
// look like the files vanished and reappeared. The spinner is only for
// when there's nothing to show yet (first load, just navigated into a
// new folder - see [_navigateTo], which clears the outgoing folder's
// items - or retrying after an error).
final inPlace = _items.isNotEmpty && _errorMessage == null;
if (!inPlace) {
_isLoading = true;
_errorMessage = null;
notifyListeners();
}
debugPrint('[FilesController] Refreshing data for path: $_currentFolderPath');
@@ -320,6 +411,11 @@ class FilesController extends ChangeNotifier with WidgetsBindingObserver {
_items,
DateTime.now(),
);
// Show the new listing now rather than after the quota/activity
// fetches below - they're unrelated to what the list displays.
_isLoading = false;
_retryAttempt = 0;
notifyListeners();
debugPrint(
'[FilesController] Loaded ${_items.length} items for $_currentFolderPath',
);
@@ -336,7 +432,12 @@ class FilesController extends ChangeNotifier with WidgetsBindingObserver {
} catch (e) {
if (gen != session.sessionGeneration) return;
debugPrint('[FilesController] Error fetching directory: $e');
_errorMessage = e.toString().replaceAll('Exception: ', '');
// A failed in-place refresh keeps the (slightly stale) listing on
// screen instead of replacing it with an error page.
if (!inPlace) {
_errorMessage = e.toString().replaceAll('Exception: ', '');
_scheduleNetworkRetry(e);
}
} finally {
if (gen == session.sessionGeneration) {
_isLoading = false;
@@ -345,17 +446,46 @@ class FilesController extends ChangeNotifier with WidgetsBindingObserver {
}
}
/// The OS reports "connected" a moment before the route actually works,
/// so the first request after regaining Wi-Fi/data can fail with "Network
/// is unreachable" - leaving the Files tab on an error page until the
/// user taps Retry. Quietly retry a few times (2s, 4s, 8s, 15s) when the
/// failure is network-level and the device is online; a real server error
/// (auth, 5xx) isn't retried.
void _scheduleNetworkRetry(Object error) {
final text = error.toString();
final isNetworkError =
text.contains('SocketException') ||
text.contains('ClientException') ||
text.contains('TimeoutException') ||
text.contains('Network is unreachable');
if (!isNetworkError ||
_retryAttempt >= 4 ||
session.connectivity.isOffline) {
return;
}
final delays = [2, 4, 8, 15];
final delay = Duration(seconds: delays[_retryAttempt]);
_retryAttempt++;
_retryTimer = Timer(delay, () => unawaited(refreshData()));
}
Future<List<NextcloudItem>> searchFiles(String query) async {
final service = session.service;
if (service == null) return [];
return service.searchFiles(query);
}
@override
Future<void> reload() => refreshData();
@override
Future<void> navigateToFolder(String path) async {
_pathStack.add(path);
await _navigateTo(path);
}
@override
Future<void> navigateUp() async {
if (_pathStack.length > 1) {
_pathStack.removeLast();
@@ -365,6 +495,7 @@ class FilesController extends ChangeNotifier with WidgetsBindingObserver {
/// Jumps directly to an ancestor folder by its position in [pathStack]
/// (as tapped from a breadcrumb), trimming everything below it.
@override
Future<void> navigateToPathIndex(int index) async {
if (index < 0 || index >= _pathStack.length - 1) return;
_pathStack = _pathStack.sublist(0, index + 1);
@@ -402,6 +533,10 @@ class FilesController extends ChangeNotifier with WidgetsBindingObserver {
notifyListeners();
return;
}
// Don't leave the folder just left on screen under the new breadcrumb
// while this one loads - clearing it is what makes [refreshData] show
// its spinner (rather than refreshing in place) for a navigation.
_items = [];
await refreshData();
}
@@ -493,15 +628,20 @@ class FilesController extends ChangeNotifier with WidgetsBindingObserver {
);
}
void setFilesSortField(FileSortField field) {
if (filesSortField == field) return;
_folderSortField[_currentFolderPath] = field;
void setFilesSortField(FileSortField field) =>
setSortFieldFor(_currentFolderPath, field);
void toggleFilesSortOrder() => toggleSortOrderFor(_currentFolderPath);
void setSortFieldFor(String path, FileSortField field) {
if (sortFieldFor(path) == field) return;
_folderSortField[path] = field;
notifyListeners();
_persistFolderSort();
}
void toggleFilesSortOrder() {
_folderSortAscending[_currentFolderPath] = !filesSortAscending;
void toggleSortOrderFor(String path) {
_folderSortAscending[path] = !sortAscendingFor(path);
notifyListeners();
_persistFolderSort();
}
@@ -511,7 +651,7 @@ class FilesController extends ChangeNotifier with WidgetsBindingObserver {
_cachePolicy = policy;
notifyListeners();
_persistAccountPref(
_prefCachePolicy,
prefCachePolicy,
(p, key) => p.setString(key, policy.name),
);
_startCacheRefreshTimerIfNeeded();
@@ -523,7 +663,7 @@ class FilesController extends ChangeNotifier with WidgetsBindingObserver {
_cacheIntervalMinutes = clamped;
notifyListeners();
_persistAccountPref(
_prefCacheIntervalMinutes,
prefCacheIntervalMinutes,
(p, key) => p.setInt(key, clamped),
);
_startCacheRefreshTimerIfNeeded();
+31
View File
@@ -0,0 +1,31 @@
import '../models/nextcloud_item.dart';
/// What `FilesView` needs from whatever is supplying the folder it's
/// showing: the breadcrumb trail, the (already display-pref-filtered and
/// sorted) items, loading/error state, and navigation. Implemented by
/// [FilesController] (the server's folders) and [OfflineController] (the
/// device-sync mirror of those same folders) so the Files tab and the
/// Offline tab are literally the same view over two data sources.
///
/// Deliberately not a `Listenable` - `context.watch` subscribes to the
/// concrete provider registered in `main()`, not to this interface, so the
/// view picks the concrete controller and then treats it as a
/// [FolderBrowser].
abstract interface class FolderBrowser {
List<String> get pathStack;
String get currentFolderPath;
/// Items in [currentFolderPath] with the shared Files display prefs
/// (hidden files, type filter, sort) already applied.
List<NextcloudItem> get items;
bool get isLoading;
String? get errorMessage;
Future<void> navigateToFolder(String path);
Future<void> navigateToPathIndex(int index);
Future<void> navigateUp();
/// Re-reads the current folder (pull-to-refresh / retry).
Future<void> reload();
}
+246
View File
@@ -0,0 +1,246 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import '../models/nextcloud_item.dart';
import '../services/sync_service.dart';
import 'files_controller.dart';
import 'folder_browser.dart';
import 'session_controller.dart';
/// The Offline tab's data source: `FilesView` (the same view as the Files
/// tab) over whatever device-sync has actually mirrored to local storage,
/// i.e. the Files tab's folders filtered down to what's available offline -
/// read straight off
/// disk, no server round-trip, since the whole point is browsing what's
/// available without a connection. Walks
/// `<externalFilesDir>/sync/<accountId>/...` directly (mirrors
/// `SyncEngine.kt#syncRoot`'s layout exactly, same technique
/// `SyncStatusController.localSyncedFilePath` already relies on) rather
/// than round-tripping through a MethodChannel. Listens for
/// [SessionController.addAccountReadyListener] rather than
/// `addAccountActivatedListener` - this controller's own work is entirely
/// local, so it's safe to run even on a provisional/offline login (see
/// that method's doc comment).
///
/// Display controls (grid/list, sort, hidden files, files/folders filter)
/// aren't kept here - [items] runs the listing through the Files tab's own
/// [FilesController] prefs so the two tabs always agree.
class OfflineController extends ChangeNotifier
with WidgetsBindingObserver
implements FolderBrowser {
final SessionController session;
final FilesController files;
List<String> _pathStack = const ['/'];
List<NextcloudItem> _items = [];
bool _isLoading = false;
String? _errorMessage;
bool _wasSyncing = false;
// Resolved once in _load - lets [localFileFor] stay synchronous so it can
// be called straight from a widget's build.
String? _syncBasePath;
StreamSubscription<SyncStatusSnapshot>? _statusSub;
OfflineController(this.session, this.files) {
WidgetsBinding.instance.addObserver(this);
session.addAccountClearedListener(_onAccountCleared);
session.addAccountReadyListener(_onAccountActivated);
// Refreshes automatically once a sync pass finishes, so newly
// downloaded files show up here without a manual pull-to-refresh.
_statusSub = SyncService.statusStream.listen(_onStatusSnapshot);
}
@override
List<String> get pathStack => _pathStack;
@override
String get currentFolderPath => _pathStack.last;
@override
List<NextcloudItem> get items => files.applyFilesDisplayPrefs(
_items,
folderPath: currentFolderPath,
// The local mirror has no cloud/external distinction to filter on.
applyStorageScope: false,
);
// Only "loading" while there's nothing to show yet - a reload over an
// already-listed folder (e.g. the automatic one after a sync pass
// finishes) swaps the list in place instead of flashing a spinner.
@override
bool get isLoading => _isLoading && _items.isEmpty;
@override
String? get errorMessage => _errorMessage;
void _onAccountCleared() {
_pathStack = const ['/'];
_items = [];
_isLoading = false;
_errorMessage = null;
notifyListeners();
}
void _onAccountActivated() {
unawaited(_load());
}
/// A background sync (which can run while the app is closed or paused)
/// may have added or removed files since this list was last read - re-read
/// the folder whenever the app comes back to the foreground.
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) unawaited(_load());
}
void _onStatusSnapshot(SyncStatusSnapshot snapshot) {
if (_wasSyncing && !snapshot.syncing) {
unawaited(_load());
}
_wasSyncing = snapshot.syncing;
}
/// Reloads the currently browsed folder - used by pull-to-refresh and as
/// the account-activation entry point.
@override
Future<void> reload() => _load();
@override
Future<void> navigateToFolder(String path) async {
_pathStack = [..._pathStack, path];
await _load();
}
@override
Future<void> navigateToPathIndex(int index) async {
if (index < 0 || index >= _pathStack.length - 1) return;
_pathStack = _pathStack.sublist(0, index + 1);
await _load();
}
@override
Future<void> navigateUp() async {
if (_pathStack.length <= 1) return;
_pathStack = _pathStack.sublist(0, _pathStack.length - 1);
await _load();
}
Future<void> _load() async {
final accountId = session.activeAccountId;
if (accountId == null) return;
_isLoading = true;
_errorMessage = null;
notifyListeners();
try {
_syncBasePath ??= (await getExternalStorageDirectory())?.path;
// A sync can delete the very folder being browsed (deleted on the
// server) - step out to the nearest ancestor that still exists rather
// than showing a phantom empty folder.
final base = _syncBasePath;
if (base != null) {
while (_pathStack.length > 1 &&
!Directory(
p.join(
base,
'sync',
accountId,
currentFolderPath.replaceFirst('/', ''),
),
).existsSync()) {
_pathStack = _pathStack.sublist(0, _pathStack.length - 1);
}
}
_items = await _listFolder(accountId, currentFolderPath);
} catch (e) {
debugPrint('[OfflineController] Error listing local files: $e');
_errorMessage = e.toString().replaceAll('Exception: ', '');
} finally {
_isLoading = false;
notifyListeners();
}
}
/// The absolute local path for [item] - a pure function of its remote-
/// style `path` (same `<accountId>/<relPath>` layout `SyncEngine.kt#
/// syncRoot` uses). Deliberately doesn't re-verify [item] is "in sync
/// scope" the way `SyncStatusController.localSyncedFilePath` does for
/// arbitrary items from elsewhere in the app - every item this
/// controller ever hands out already came from listing this exact
/// directory tree, so it's definitionally already local; re-checking
/// scope here was the actual bug behind a file the Offline tab had just
/// listed reporting itself as "no longer available".
/// Synchronous counterpart to [localPathFor] for building thumbnails -
/// null until the first [_load] has resolved the storage directory. Doesn't
/// check the file exists; the image widget's own error fallback covers a
/// missing one.
File? localFileFor(NextcloudItem item) {
final accountId = session.activeAccountId;
final base = _syncBasePath;
if (accountId == null || base == null) return null;
final relPath = item.path.startsWith('/')
? item.path.substring(1)
: item.path;
return File(p.join(base, 'sync', accountId, relPath));
}
Future<String?> localPathFor(NextcloudItem item) async {
final accountId = session.activeAccountId;
if (accountId == null) 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', accountId, relPath));
return file.existsSync() ? file.path : null;
}
static Future<List<NextcloudItem>> _listFolder(
String accountId,
String folderPath,
) async {
final base = await getExternalStorageDirectory();
if (base == null) return [];
final relFolder = folderPath == '/' ? '' : folderPath.replaceFirst('/', '');
final dir = Directory(p.join(base.path, 'sync', accountId, relFolder));
if (!dir.existsSync()) return [];
final items = <NextcloudItem>[];
await for (final entity in dir.list(followLinks: false)) {
final name = p.basename(entity.path);
final remotePath = folderPath == '/' ? '/$name' : '$folderPath/$name';
if (entity is Directory) {
items.add(
NextcloudItem(
id: remotePath,
name: name,
path: remotePath,
type: NextcloudItemType.folder,
size: 0,
lastModified: (await entity.stat()).modified,
),
);
} else if (entity is File) {
final stat = await entity.stat();
items.add(
NextcloudItem(
id: remotePath,
name: name,
path: remotePath,
type: NextcloudItem.deduceType(remotePath, false, null),
size: stat.size,
lastModified: stat.modified,
),
);
}
}
return items;
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_statusSub?.cancel();
super.dispose();
}
}
+21 -12
View File
@@ -76,18 +76,27 @@ class PhotosController extends ChangeNotifier {
Future<void> _onAccountActivated() async {
final id = session.activeAccountId;
if (id != null) {
final prefs = await session.prefsFuture;
String k(String base) => session.accountStore.accountPrefKey(id, base);
_showFavoritesOnly =
prefs.getBool(k(_prefShowFavoritesOnlyPhotos)) ?? false;
_showHidden = prefs.getBool(k(_prefShowHiddenPhotos)) ?? false;
final sortFieldName = prefs.getString(k(_prefSortField));
_sortField = FileSortField.values.firstWhere(
(f) => f.name == sortFieldName,
orElse: () => FileSortField.name,
);
_sortAscending = prefs.getBool(k(_prefSortAscending)) ?? true;
notifyListeners();
// Wrapped so a single bad/mistyped stored pref value can't
// silently skip fetchAllMedia() below and leave Photos permanently
// empty on this activation with no error surfaced anywhere - see
// FilesController._onAccountActivated's identical guard for the
// real incident this mirrors.
try {
final prefs = await session.prefsFuture;
String k(String base) => session.accountStore.accountPrefKey(id, base);
_showFavoritesOnly =
prefs.getBool(k(_prefShowFavoritesOnlyPhotos)) ?? false;
_showHidden = prefs.getBool(k(_prefShowHiddenPhotos)) ?? false;
final sortFieldName = prefs.getString(k(_prefSortField));
_sortField = FileSortField.values.firstWhere(
(f) => f.name == sortFieldName,
orElse: () => FileSortField.name,
);
_sortAscending = prefs.getBool(k(_prefSortAscending)) ?? true;
notifyListeners();
} catch (e) {
debugPrint('[PhotosController] Account-activation prefs restore failed: $e');
}
}
unawaited(fetchAllMedia());
}
+135 -17
View File
@@ -8,6 +8,7 @@ import '../services/app_lock_service.dart';
import '../services/login_flow_service.dart';
import '../services/nextcloud_service.dart';
import '../services/sync_service.dart';
import 'connectivity_controller.dart';
enum LoginFlowStatus { idle, initiating, awaitingBrowser, error }
@@ -25,10 +26,21 @@ enum LoginFlowStatus { idle, initiating, awaitingBrowser, error }
/// `.claude/context/architecture.md`'s "State management" section for the
/// full rationale.
class SessionController extends ChangeNotifier with WidgetsBindingObserver {
final ConnectivityController connectivity;
final Future<SharedPreferences> prefsFuture =
SharedPreferences.getInstance();
final AccountStore accountStore = AccountStore();
// True from the moment a saved session is restored (or a network
// failure keeps it alive - see `_applyCredentialsForAccount`) without
// ever having actually reached the server, until a real
// `testConnection()` succeeds. Network-fetching controllers have no
// reason to check this themselves - they only ever hear about account
// activation via [addAccountActivatedListener], which simply doesn't
// fire while this is true (see [addAccountReadyListener] for the
// signal that *does* fire either way).
bool _isProvisionalLogin = false;
String _serverUrl = '';
String _username = '';
String _password = '';
@@ -71,13 +83,23 @@ class SessionController extends ChangeNotifier with WidgetsBindingObserver {
// them - it's constructed first, they depend on it. `cleared` fires
// wherever `_clearActiveContent()` used to run (about to switch/log out -
// reset your own state); `activated` fires only once credentials are
// actually verified (fetch your own data now).
// actually verified against the server, so it's safe to make network
// requests (fetch your own data now) - it deliberately does *not* fire
// for a provisional/offline login (see `_isProvisionalLogin`), so a
// network-fetching controller never has to check connectivity itself.
// `ready` fires in *both* cases - verified or provisional - for the
// handful of controllers (SyncStatusController/OfflineController) whose
// own activation work is local-only (prefs, on-disk files) and safe to
// run with no connection at all.
final List<VoidCallback> _accountClearedListeners = [];
final List<VoidCallback> _accountActivatedListeners = [];
final List<VoidCallback> _accountReadyListeners = [];
void addAccountClearedListener(VoidCallback cb) =>
_accountClearedListeners.add(cb);
void addAccountActivatedListener(VoidCallback cb) =>
_accountActivatedListeners.add(cb);
void addAccountReadyListener(VoidCallback cb) =>
_accountReadyListeners.add(cb);
void _notifyAccountCleared() {
for (final cb in _accountClearedListeners) {
cb();
@@ -88,10 +110,20 @@ class SessionController extends ChangeNotifier with WidgetsBindingObserver {
for (final cb in _accountActivatedListeners) {
cb();
}
for (final cb in _accountReadyListeners) {
cb();
}
}
SessionController() {
void _notifyAccountProvisionallyReady() {
for (final cb in _accountReadyListeners) {
cb();
}
}
SessionController(this.connectivity) {
WidgetsBinding.instance.addObserver(this);
connectivity.addListener(_onConnectivityChanged);
_init();
}
@@ -175,11 +207,16 @@ class SessionController extends ChangeNotifier with WidgetsBindingObserver {
/// Verifies [appPassword] for [account] and, on success, makes it the
/// live session, firing [_notifyAccountActivated] so every other
/// controller fetches its own data. The password is expected to already
/// be durably saved by the caller (either freshly, via
/// [_completeLoginFlow], or previously, since this is also how a saved
/// session is restored/switched to) - this method only writes to
/// [AccountStore] to drop a password that turns out to no longer work.
/// controller fetches its own data. With no network route at all, or on
/// a network-level (not auth) failure, skips/gives up on verification
/// but still logs in *provisionally* - see [_isProvisionalLogin] - so
/// the app still opens into `MainShellView` (restricted to the Offline
/// tab while offline) instead of bouncing to `LoginView`. The password
/// is expected to already be durably saved by the caller (either
/// freshly, via [_completeLoginFlow], or previously, since this is also
/// how a saved session is restored/switched to) - this method only
/// writes to [AccountStore] to drop a password that turns out to no
/// longer work (an actual 401, never a network failure).
Future<bool> _applyCredentialsForAccount(
SavedAccount account,
String appPassword,
@@ -199,10 +236,25 @@ class SessionController extends ChangeNotifier with WidgetsBindingObserver {
password: _password,
);
// No point even attempting the request with no network route at all -
// treat this exactly like the network-failure branch below (stay
// logged in provisionally, `service` already assigned) without paying
// for a doomed HTTP call first.
if (connectivity.isOffline) {
if (gen != _sessionGeneration) return false;
_isProvisionalLogin = true;
_isLoggedIn = true;
_isLoading = false;
notifyListeners();
_notifyAccountProvisionallyReady();
return true;
}
try {
final success = await _service!.testConnection();
if (gen != _sessionGeneration) return false;
if (success) {
_isProvisionalLogin = false;
_isLoggedIn = true;
_isLoading = false;
notifyListeners();
@@ -212,20 +264,35 @@ class SessionController extends ChangeNotifier with WidgetsBindingObserver {
} catch (e) {
if (gen != _sessionGeneration) return false;
_errorMessage = e.toString().replaceAll('Exception: ', '');
// Only drop the stored password on an actual auth rejection (401) -
// 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.
// Only drop the stored password - and only actually log out - on an
// actual auth rejection (401). Every other failure (DNS, timeout,
// unreachable host, a transient 5xx) is provisional: staying
// "logged in" with the cached account/service lets the app still
// land on MainShellView instead of bouncing to LoginView, which
// would strand a genuinely offline user with no way back in short
// of Login Flow v2 again (activeAccountId is never cleared and
// switchAccount() no-ops when asked to "switch" to the account
// that's already nominally active). `_service` is already assigned
// above and needs no re-creation once connectivity returns.
if (_errorMessage?.contains('401') == true) {
await accountStore.deletePassword(account.id);
_isProvisionalLogin = false;
_isLoggedIn = false;
_service = null;
_isLoading = false;
notifyListeners();
return false;
}
_isProvisionalLogin = true;
_isLoggedIn = true;
_isLoading = false;
notifyListeners();
_notifyAccountProvisionallyReady();
return true;
}
if (gen != _sessionGeneration) return false;
_isProvisionalLogin = false;
_isLoggedIn = false;
_service = null;
_isLoading = false;
@@ -233,6 +300,41 @@ class SessionController extends ChangeNotifier with WidgetsBindingObserver {
return false;
}
/// Once connectivity actually returns, re-verifies a provisional/offline
/// login for real - this is what finally fires [_notifyAccountActivated]
/// (not just [_notifyAccountProvisionallyReady]) so network-fetching
/// controllers get their first real fetch without requiring an app
/// restart.
void _onConnectivityChanged() {
_reverifyTimer?.cancel();
if (!_isProvisionalLogin || connectivity.isOffline) return;
unawaited(_reverify(0));
}
Timer? _reverifyTimer;
/// One re-verification attempt, retried with a growing delay if the
/// server still can't be reached. The OS reports "connected" a moment
/// before the route actually works (the first request right after
/// regaining Wi-Fi/data fails with "Network is unreachable"), and
/// `onConnectivityChanged` won't fire again to give a second chance - so
/// without retrying, the login stayed provisional and the Files tab showed
/// a connection error until the user tapped Retry.
Future<void> _reverify(int attempt) async {
if (!_isProvisionalLogin || connectivity.isOffline) return;
final id = _activeAccountId;
if (id == null) return;
final account = _accounts.where((a) => a.id == id).firstOrNull;
if (account == null) return;
await _applyCredentialsForAccount(account, _password);
if (_isProvisionalLogin && !connectivity.isOffline && attempt < 5) {
_reverifyTimer = Timer(
Duration(seconds: 2 * (attempt + 1)),
() => unawaited(_reverify(attempt + 1)),
);
}
}
/// Starts Nextcloud Login Flow v2: asks the server for a one-time login
/// URL, then polls until the user authorizes (in LoginWebViewView, pushed
/// by LoginView once loginFlowStatus flips to awaitingBrowser below) and
@@ -370,6 +472,8 @@ class SessionController extends ChangeNotifier with WidgetsBindingObserver {
_activeAccountId = accountId;
final prefs = await prefsFuture;
await accountStore.saveActiveAccountId(prefs, accountId);
// Signed back in (or switched to) - it syncs in the background again.
await accountStore.setSignedOut(prefs, accountId, false);
notifyListeners();
final account = _accounts.where((a) => a.id == accountId).firstOrNull;
@@ -377,6 +481,7 @@ class SessionController extends ChangeNotifier with WidgetsBindingObserver {
? null
: await accountStore.readPassword(accountId);
if (account == null || password == null) {
_isProvisionalLogin = false;
_isLoading = false;
_isLoggedIn = false;
notifyListeners();
@@ -443,6 +548,9 @@ class SessionController extends ChangeNotifier with WidgetsBindingObserver {
for (final key in AccountStore.perAccountPrefKeys) {
await prefs.remove(accountStore.accountPrefKey(accountId, key));
}
await accountStore.setSignedOut(prefs, accountId, false);
// Its background sync job holds that account's credentials - stop it.
unawaited(SyncService.cancelAccount(accountId));
if (!wasActive) {
notifyListeners();
@@ -466,6 +574,7 @@ class SessionController extends ChangeNotifier with WidgetsBindingObserver {
Future<void> _deactivateSession() async {
_sessionGeneration++;
_notifyAccountCleared();
_isProvisionalLogin = false;
_isLoggedIn = false;
_serverUrl = '';
_username = '';
@@ -474,7 +583,6 @@ class SessionController extends ChangeNotifier with WidgetsBindingObserver {
final prefs = await prefsFuture;
await accountStore.saveActiveAccountId(prefs, null);
notifyListeners();
unawaited(SyncService.cancel());
}
/// Ends the active session but keeps this account saved - unlike
@@ -484,8 +592,16 @@ class SessionController extends ChangeNotifier with WidgetsBindingObserver {
/// Always lands on the login screen even if other accounts are saved -
/// deliberately not the same as switching to one of them.
Future<void> logout() async {
if (_activeAccountId == null) return;
final id = _activeAccountId;
if (id == null) return;
// Logging out stops that account's background sync (the other saved
// accounts keep syncing - each has its own job). It's remembered as
// signed out so a later reschedule for some other account doesn't
// bring its job back; signing in again re-enables it.
final prefs = await prefsFuture;
await accountStore.setSignedOut(prefs, id, true);
await _deactivateSession();
unawaited(SyncService.cancelAccount(id));
}
/// Confirms the device can do local auth and prompts once to enable login
@@ -564,6 +680,8 @@ class SessionController extends ChangeNotifier with WidgetsBindingObserver {
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
connectivity.removeListener(_onConnectivityChanged);
_reverifyTimer?.cancel();
_pollTimer?.cancel();
_pollTimeoutTimer?.cancel();
super.dispose();
+337 -47
View File
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import '../models/nextcloud_item.dart';
import '../models/sync_status.dart';
import '../services/sync_service.dart';
import 'files_controller.dart';
import 'session_controller.dart';
/// Device-sync state and settings: which remote paths (files or folders,
@@ -16,13 +17,37 @@ import 'session_controller.dart';
/// (`syncStatusFor`) despite living in an unrelated domain; now it's a
/// second, focused provider those views read alongside their own tab
/// controller.
class SyncStatusController extends ChangeNotifier {
///
/// **Keeping synced files current.** Synced folders/files follow the same
/// Files Cache rule (Settings) as folder listings, so nothing needs the
/// "Sync now" button:
///
/// - *Refresh periodically (N min)*: a WorkManager periodic job runs in the
/// background at that interval (Android's floor is 15 min, so shorter
/// values only apply in the foreground), and while the app's open an
/// in-app timer runs a pass every N minutes plus one on resume if it's
/// been longer than that.
/// - *Never cache*: no background schedule; a pass runs each time the app
/// is opened/resumed.
/// - *Refresh manually only*: only pull-to-refresh (any tab's sync header)
/// and "Sync now".
///
/// Every automatic pass is cheap when nothing changed - the native worker
/// checks each synced root's etag (Nextcloud propagates any descendant
/// change up to every ancestor's etag) and skips the full walk if it's
/// unchanged and the local copy is intact. There's no server push: Nextcloud's
/// only push channels (the `notify_push` server app, or FCM via Nextcloud's
/// push proxy) need server-side setup and a persistent connection/registered
/// app identity, so this polls instead.
class SyncStatusController extends ChangeNotifier with WidgetsBindingObserver {
final SessionController session;
final FilesController files;
static const _prefSyncedPaths = 'ui_synced_folders';
static const prefSyncedPaths = 'ui_synced_folders';
static const _prefSyncedPathTypes = 'ui_synced_folder_types';
static const _prefSyncEverything = 'ui_sync_everything';
static const prefSyncEverything = 'ui_sync_everything';
static const _prefSyncOnCellular = 'ui_sync_on_cellular';
static const _prefSyncNotifications = 'ui_sync_notifications';
List<String> _syncedPaths = [];
// path -> isFolder, keyed the same as [_syncedPaths] - missing entries
@@ -31,6 +56,7 @@ class SyncStatusController extends ChangeNotifier {
Map<String, bool> _syncedPathTypes = {};
bool _syncEverything = false;
bool _syncOnCellular = false;
bool _syncNotifications = true;
bool _isSyncingNow = false;
Set<String> _syncingFileIds = {};
@@ -38,9 +64,45 @@ class SyncStatusController extends ChangeNotifier {
List<SyncConflictInfo> _syncConflicts = [];
StreamSubscription<SyncStatusSnapshot>? _statusSub;
SyncStatusController(this.session) {
// Gates addSyncedPaths/removeSyncedPaths (anything that persists
// _syncedPaths) against running before _onAccountActivated's async
// prefs load has actually finished - without this, syncing a folder
// right after opening the app could race the load, overwrite the
// persisted list with just the one path being added/removed, and
// silently destroy every previously-synced folder. Deliberately starts
// *incomplete*, not pre-completed - a mutation is only ever reachable
// from Files/Offline UI, which requires a completed activation already
// (Files' own item list depends on the same login event), so there's no
// real deadlock risk, and starting complete would leave the very first
// cold-start load completely unprotected (only account *switches*
// re-arm it, via _onAccountCleared - the bug that actually caused
// repeated data loss here).
Completer<void> _accountLoadedGate = Completer<void>();
// True once _syncedPaths/_syncedPathTypes/_syncEverything have been
// loaded from prefs for the *current* account - _onAccountActivated can
// fire more than once per account (e.g. SessionController re-verifying
// a provisional/offline login once connectivity returns), and a second
// pass re-reading from storage could clobber an in-memory mutation made
// between the first load and the second one if its own persist hadn't
// landed yet. Reset in _onAccountCleared.
bool _hasLoadedSyncedPathsForAccount = false;
Timer? _autoSyncTimer;
bool _foreground = true;
DateTime? _lastAutoSyncAt;
CachePolicy? _lastPolicy;
int? _lastInterval;
SyncStatusController(this.session, this.files) {
WidgetsBinding.instance.addObserver(this);
files.addListener(_onFilesChanged);
session.addAccountClearedListener(_onAccountCleared);
session.addAccountActivatedListener(_onAccountActivated);
// `ready`, not `activated` - this controller's own activation work
// (loading prefs, calling the native sync channel) is local/native
// only, so it's safe to run even on a provisional/offline login (see
// `SessionController.addAccountReadyListener`'s doc comment).
session.addAccountReadyListener(_onAccountActivated);
_statusSub = SyncService.statusStream.listen(_applySnapshot);
_loadGlobalPrefs();
}
@@ -49,7 +111,21 @@ class SyncStatusController extends ChangeNotifier {
bool get syncEverything => _syncEverything;
bool get syncOnCellular => _syncOnCellular;
/// Whether background (automatic) sync runs may post progress/summary
/// notifications. Conflicts and user-initiated "Sync now" always notify.
bool get syncNotifications => _syncNotifications;
bool get isSyncingNow => _isSyncingNow;
bool get _hasSyncScope => _syncEverything || _syncedPaths.isNotEmpty;
/// How often the background WorkManager job should run, or null for no
/// background sync at all - only the "refresh periodically" Files Cache
/// policy schedules one (see the class doc comment).
int? get backgroundSyncIntervalMinutes =>
files.cachePolicy == CachePolicy.interval
? files.cacheIntervalMinutes
: null;
List<SyncConflictInfo> get syncConflicts => List.unmodifiable(_syncConflicts);
/// How many of [syncedPaths] are folders (as opposed to individual
@@ -57,11 +133,6 @@ class SyncStatusController extends ChangeNotifier {
int get syncedFolderCount =>
_syncedPaths.where((p) => _syncedPathTypes[p] ?? true).length;
/// How many individual files have actually been mirrored locally so far
/// - distinct from [syncedFolderCount]/[syncedPaths], which are just the
/// configured *targets*, not what's actually landed on disk yet.
int get syncedItemCount => _syncedFileIds.length;
SyncHeaderStatus get syncHeaderStatus {
if (_syncConflicts.isNotEmpty) return SyncHeaderStatus.alert;
if (_isSyncingNow) return SyncHeaderStatus.syncing;
@@ -121,10 +192,21 @@ class SyncStatusController extends ChangeNotifier {
Future<void> _loadGlobalPrefs() async {
final prefs = await session.prefsFuture;
_syncOnCellular = prefs.getBool(_prefSyncOnCellular) ?? _syncOnCellular;
_syncNotifications =
prefs.getBool(_prefSyncNotifications) ?? _syncNotifications;
notifyListeners();
}
void _onAccountCleared() {
// Re-armed (not completed) here, not just at construction - an
// account switch means the *next* activation's load has to finish
// before any mutation touching _syncedPaths is safe again. Only
// replace the Completer if nothing's still awaiting the old one -
// swapping it out from under a pending awaiter would orphan that
// await forever, since nothing would ever complete the discarded
// instance.
if (_accountLoadedGate.isCompleted) _accountLoadedGate = Completer<void>();
_hasLoadedSyncedPathsForAccount = false;
_syncedPaths = [];
_syncedPathTypes = {};
_syncEverything = false;
@@ -132,47 +214,175 @@ class SyncStatusController extends ChangeNotifier {
_syncingFileIds = {};
_syncedFileIds = {};
_syncConflicts = [];
_autoSyncTimer?.cancel();
_lastAutoSyncAt = null;
_lastPolicy = null;
_lastInterval = null;
notifyListeners();
}
Future<void> _onAccountActivated() async {
final id = session.activeAccountId;
if (id != null) {
final prefs = await session.prefsFuture;
String k(String base) => session.accountStore.accountPrefKey(id, base);
final pathsJson = prefs.getString(k(_prefSyncedPaths));
if (pathsJson != null) {
try {
_syncedPaths = (jsonDecode(pathsJson) as List).cast<String>();
} catch (e) {
debugPrint('[SyncStatusController] Synced paths restore failed: $e');
// Only load _syncedPaths/_syncedPathTypes/_syncEverything once per
// account, not on every activation - this can fire more than once
// for the same account (e.g. SessionController re-verifying a
// provisional/offline login once connectivity returns), and a second
// read from storage could clobber an in-memory mutation made between
// the first load and this one if its own persist hadn't landed yet.
// See _hasLoadedSyncedPathsForAccount's doc comment.
if (id != null && !_hasLoadedSyncedPathsForAccount) {
_hasLoadedSyncedPathsForAccount = true;
// Wrapped so a single bad/mistyped stored pref value can't
// propagate uncaught out of this method and skip the gate
// completion below - that would leave every future
// addSyncedPaths/removeSyncedPaths call awaiting a gate that never
// completes, hanging forever. See FilesController.
// _onAccountActivated's identical guard for the real incident this
// mirrors.
try {
final prefs = await session.prefsFuture;
String k(String base) => session.accountStore.accountPrefKey(id, base);
final pathsJson = prefs.getString(k(prefSyncedPaths));
if (pathsJson != null) {
try {
_syncedPaths = (jsonDecode(pathsJson) as List).cast<String>();
} catch (e) {
debugPrint('[SyncStatusController] Synced paths restore failed: $e');
_syncedPaths = [];
}
} else {
_syncedPaths = [];
}
} else {
_syncedPaths = [];
}
final typesJson = prefs.getString(k(_prefSyncedPathTypes));
if (typesJson != null) {
try {
_syncedPathTypes = (jsonDecode(typesJson) as Map).map(
(k, v) => MapEntry(k as String, v as bool),
);
} catch (e) {
debugPrint('[SyncStatusController] Synced path types restore failed: $e');
final typesJson = prefs.getString(k(_prefSyncedPathTypes));
if (typesJson != null) {
try {
_syncedPathTypes = (jsonDecode(typesJson) as Map).map(
(k, v) => MapEntry(k as String, v as bool),
);
} catch (e) {
debugPrint('[SyncStatusController] Synced path types restore failed: $e');
_syncedPathTypes = {};
}
} else {
_syncedPathTypes = {};
}
} else {
_syncedPathTypes = {};
_syncEverything = prefs.getBool(k(prefSyncEverything)) ?? false;
notifyListeners();
} catch (e) {
debugPrint('[SyncStatusController] Account-activation prefs restore failed: $e');
}
_syncEverything = prefs.getBool(k(_prefSyncEverything)) ?? false;
notifyListeners();
}
// Only now is it safe for addSyncedPaths/removeSyncedPaths to mutate
// and persist _syncedPaths - see _accountLoadedGate's doc comment.
if (!_accountLoadedGate.isCompleted) _accountLoadedGate.complete();
unawaited(SyncService.getStatus(id).then(_applySnapshot));
// Scheduling depends on the Files Cache policy, so wait for it to load
// rather than scheduling from the defaults and correcting a moment later.
await files.displayPrefsLoaded;
_lastPolicy = files.cachePolicy;
_lastInterval = files.cacheIntervalMinutes;
unawaited(SyncService.reschedule(session, this));
unawaited(SyncService.getStatus().then(_applySnapshot));
_restartAutoSyncTimer();
if (_dueForAutoSync) unawaited(_autoSync());
}
// ---- Automatic sync (see the class doc comment) ----
void _onFilesChanged() {
// FilesController notifies on every navigation - only the cache rule
// itself matters here.
if (_lastPolicy == null) return; // account not activated yet
final policy = files.cachePolicy;
final interval = files.cacheIntervalMinutes;
if (policy == _lastPolicy && interval == _lastInterval) return;
_lastPolicy = policy;
_lastInterval = interval;
unawaited(SyncService.reschedule(session, this));
_restartAutoSyncTimer();
}
/// Whether an app-open/resume should kick off a pass under the current
/// cache rule.
bool get _dueForAutoSync {
switch (files.cachePolicy) {
case CachePolicy.never:
return true;
case CachePolicy.manual:
return false;
case CachePolicy.interval:
final last = _lastAutoSyncAt;
return last == null ||
DateTime.now().difference(last) >=
Duration(minutes: files.cacheIntervalMinutes);
}
}
void _restartAutoSyncTimer() {
_autoSyncTimer?.cancel();
if (!_foreground ||
!_hasSyncScope ||
files.cachePolicy != CachePolicy.interval) {
return;
}
_autoSyncTimer = Timer.periodic(
Duration(minutes: files.cacheIntervalMinutes),
(_) => unawaited(_autoSync()),
);
}
/// A quiet, network-setting-respecting pass - see [SyncService.syncNow].
Future<void> _autoSync() async {
if (!_canSyncQuietly) return;
_lastAutoSyncAt = DateTime.now();
try {
await SyncService.syncNow(
session,
this,
force: false,
respectNetworkSetting: true,
);
} catch (e) {
debugPrint('[SyncStatusController] Automatic sync failed: $e');
}
}
/// A deliberate pull-to-refresh (any tab's sync header): check for server
/// changes now, regardless of the cache rule or the Wi-Fi-only setting.
Future<void> syncOnPull() async {
if (!_canSyncQuietly) return;
try {
await SyncService.syncNow(session, this, force: false);
} catch (e) {
debugPrint('[SyncStatusController] Pull-triggered sync failed: $e');
}
}
bool get _canSyncQuietly =>
_hasSyncScope &&
!_isSyncingNow &&
session.isLoggedIn &&
!session.connectivity.isOffline;
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
_foreground = true;
_restartAutoSyncTimer();
if (_dueForAutoSync) unawaited(_autoSync());
} else if (state == AppLifecycleState.paused) {
// The in-app timer only runs while foregrounded; WorkManager owns the
// background schedule.
_foreground = false;
_autoSyncTimer?.cancel();
}
}
void _applySnapshot(SyncStatusSnapshot snapshot) {
if (snapshot.accountId != null &&
// A null accountId is the bus's initial "nothing has synced in this
// process yet" emission on subscribe - applying it would wipe the
// synced-file ids seeded by getStatus(accountId).
if (snapshot.accountId == null ||
snapshot.accountId != session.activeAccountId) {
return;
}
@@ -181,6 +391,11 @@ class SyncStatusController extends ChangeNotifier {
_syncedFileIds = snapshot.syncedFileIds;
_syncConflicts = snapshot.conflicts;
notifyListeners();
// A synced file/folder deleted on the server has nothing left to sync -
// drop it from the synced list rather than leaving a dead entry.
final gone = snapshot.missingRoots.where(_syncedPaths.contains).toList();
if (gone.isNotEmpty) unawaited(removeSyncedPaths(gone));
}
void _persistSyncedPaths() {
@@ -188,7 +403,7 @@ class SyncStatusController extends ChangeNotifier {
if (id == null) return;
session.prefsFuture.then((p) {
p.setString(
session.accountStore.accountPrefKey(id, _prefSyncedPaths),
session.accountStore.accountPrefKey(id, prefSyncedPaths),
jsonEncode(_syncedPaths),
);
p.setString(
@@ -200,26 +415,74 @@ class SyncStatusController extends ChangeNotifier {
bool isPathSynced(String path) => _syncedPaths.contains(path);
void addSyncedPath(String path, {required bool isFolder}) {
if (_syncedPaths.contains(path)) return;
_syncedPaths = [..._syncedPaths, path];
_syncedPathTypes = {..._syncedPathTypes, path: isFolder};
Future<void> addSyncedPath(String path, {required bool isFolder}) {
return addSyncedPaths({path: isFolder});
}
/// Adds every path in [entries] (path -> isFolder) to sync in one go -
/// unlike calling [addSyncedPath] once per item in a loop, this touches
/// `_syncedPaths`/persists/reschedules/triggers an immediate sync
/// exactly once no matter how many paths are being added. Looping
/// `addSyncedPath` from a multi-select "Sync to device" was the actual
/// bug behind only the first selected item ever actually syncing: each
/// call fired its own `SyncService.syncNow`, and WorkManager's
/// `enqueueUniqueWork(..., ExistingWorkPolicy.REPLACE, ...)` policy
/// meant each later call cancelled the previous item's still-in-flight
/// sync pass (and could stomp on its `SyncEngine.saveState`, which
/// overwrites the whole state map rather than merging) instead of
/// letting it finish.
Future<void> addSyncedPaths(Map<String, bool> entries) async {
// Must not mutate/persist _syncedPaths before the per-account load
// has actually populated it - see _accountLoadedGate's doc comment.
await _accountLoadedGate.future;
var changed = false;
entries.forEach((path, isFolder) {
if (_syncedPaths.contains(path)) return;
_syncedPaths = [..._syncedPaths, path];
_syncedPathTypes = {..._syncedPathTypes, path: isFolder};
changed = true;
});
if (!changed) return;
notifyListeners();
_persistSyncedPaths();
unawaited(SyncService.reschedule(session, this));
_restartAutoSyncTimer();
// `reschedule` alone only lines up the *periodic* job, which can be up
// to an hour away from its first run - without an immediate one-off
// sync here too, newly-added items would just sit unsynced until the
// user thought to trigger one manually (e.g. pulling to refresh on
// the Offline tab).
unawaited(_syncNowSilently());
}
/// Unsyncs [path] and deletes its already-downloaded local mirror (see
/// `SyncService.removeLocalSync`) - stopping sync alone would leave
/// whatever had already been downloaded sitting on disk indefinitely.
void removeSyncedPath(String path) {
if (!_syncedPaths.contains(path)) return;
_syncedPaths = _syncedPaths.where((f) => f != path).toList();
_syncedPathTypes = {..._syncedPathTypes}..remove(path);
Future<void> removeSyncedPath(String path) {
return removeSyncedPaths([path]);
}
/// Batched counterpart to [removeSyncedPath] - see [addSyncedPaths]'s
/// doc comment for why a multi-item loop of individual calls is unsafe
/// for `reschedule`/native side effects, even though removal itself
/// (unlike adding) doesn't trigger a one-off sync to race.
Future<void> removeSyncedPaths(List<String> paths) async {
await _accountLoadedGate.future;
var changed = false;
for (final path in paths) {
if (!_syncedPaths.contains(path)) continue;
_syncedPaths = _syncedPaths.where((f) => f != path).toList();
_syncedPathTypes = {..._syncedPathTypes}..remove(path);
changed = true;
}
if (!changed) return;
notifyListeners();
_persistSyncedPaths();
unawaited(SyncService.reschedule(session, this));
unawaited(SyncService.removeLocalSync(session, path));
_restartAutoSyncTimer();
for (final path in paths) {
unawaited(SyncService.removeLocalSync(session, path));
}
}
void setSyncEverything(bool value) {
@@ -230,12 +493,24 @@ class SyncStatusController extends ChangeNotifier {
if (id != null) {
session.prefsFuture.then(
(p) => p.setBool(
session.accountStore.accountPrefKey(id, _prefSyncEverything),
session.accountStore.accountPrefKey(id, prefSyncEverything),
value,
),
);
}
unawaited(SyncService.reschedule(session, this));
_restartAutoSyncTimer();
if (value) unawaited(_syncNowSilently());
}
void setSyncNotifications(bool value) {
if (_syncNotifications == value) return;
_syncNotifications = value;
notifyListeners();
session.prefsFuture.then((p) => p.setBool(_prefSyncNotifications, value));
// Baked into each periodic job's input, so the jobs have to be
// re-enqueued for the change to reach background runs.
unawaited(SyncService.reschedule(session, this));
}
void setSyncOnCellular(bool value) {
@@ -246,6 +521,18 @@ class SyncStatusController extends ChangeNotifier {
unawaited(SyncService.reschedule(session, this));
}
/// Fire-and-forget immediate sync, swallowing errors - called right
/// after turning sync on for something (see [addSyncedPath]/
/// [setSyncEverything]) so it actually starts syncing now instead of
/// only ever running on the next periodic pass or a manual "Sync now".
Future<void> _syncNowSilently() async {
try {
await SyncService.syncNow(session, this);
} catch (e) {
debugPrint('[SyncStatusController] Immediate sync failed: $e');
}
}
/// 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
@@ -277,6 +564,9 @@ class SyncStatusController extends ChangeNotifier {
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
files.removeListener(_onFilesChanged);
_autoSyncTimer?.cancel();
_statusSub?.cancel();
super.dispose();
}
+20
View File
@@ -20,6 +20,7 @@ class AccountStore {
static const _prefAccountsList = 'accounts_list';
static const _prefActiveAccountId = 'active_account_id';
static const _prefMigrationDone = 'account_migration_v1_done';
static const _prefSignedOutAccounts = 'signed_out_account_ids';
/// The per-account browsing prefs that get namespaced under
/// `acct_<id>_<key>` on migration/save - everything else (theme, tab
@@ -38,6 +39,7 @@ class AccountStore {
'ui_cache_policy',
'ui_cache_interval_minutes',
'ui_synced_folders',
'ui_synced_folder_types',
'ui_sync_everything',
];
@@ -129,6 +131,24 @@ class AccountStore {
}
}
/// Accounts the user explicitly logged out of. They stay saved (password
/// and prefs intact, resumable from the login screen) but are treated as
/// signed out - notably, they don't sync in the background. Cleared again
/// the moment the account is activated.
Set<String> loadSignedOut(SharedPreferences prefs) =>
(prefs.getStringList(_prefSignedOutAccounts) ?? const []).toSet();
Future<void> setSignedOut(
SharedPreferences prefs,
String accountId,
bool signedOut,
) async {
final current = loadSignedOut(prefs);
final changed = signedOut ? current.add(accountId) : current.remove(accountId);
if (!changed) return;
await prefs.setStringList(_prefSignedOutAccounts, current.toList());
}
Future<String?> readPassword(String accountId) =>
_storage.read(key: '$_passwordKeyPrefix$accountId');
+170 -31
View File
@@ -1,9 +1,13 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as p;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:path_provider/path_provider.dart';
import '../models/sync_status.dart';
import '../models/saved_account.dart';
import '../providers/files_controller.dart';
import '../providers/session_controller.dart';
import '../providers/sync_status_controller.dart';
@@ -16,12 +20,17 @@ class SyncStatusSnapshot {
final Set<String> syncedFileIds;
final List<SyncConflictInfo> conflicts;
/// Configured sync paths the server says no longer exist (deleted on the
/// web) - the app drops them from its synced list.
final Set<String> missingRoots;
const SyncStatusSnapshot({
required this.accountId,
required this.syncing,
required this.syncingFileIds,
required this.syncedFileIds,
required this.conflicts,
this.missingRoots = const {},
});
factory SyncStatusSnapshot.fromMap(Map<dynamic, dynamic> map) {
@@ -38,6 +47,9 @@ class SyncStatusSnapshot {
.cast<Map<dynamic, dynamic>>()
.map(SyncConflictInfo.fromMap)
.toList(),
missingRoots: ((map['missingRoots'] as List?) ?? const [])
.cast<String>()
.toSet(),
);
}
}
@@ -56,42 +68,89 @@ class SyncService {
'dev.ayushya.noo/sync_service/status',
);
/// Cancels (if [SyncStatusController.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.
/// Brings the background periodic sync jobs in line with every saved
/// account's current settings - one job per account with sync enabled
/// (paths or "sync everything", and the Files Cache policy set to refresh
/// periodically), cancelled for accounts without and for accounts the
/// user logged out of. Background sync is deliberately not limited to the
/// active account: each account's job carries that account's own
/// credentials, paths and interval, so switching accounts doesn't stop the
/// others.
///
/// Call whenever any of that changes - a periodic `WorkRequest`'s input is
/// fixed at enqueue time and can only be updated by re-enqueueing. The
/// active account's settings come from [sync]/its live state (they may not
/// have been persisted yet); every other account's are read from storage.
static Future<void> reschedule(
SessionController session,
SyncStatusController sync,
) async {
final accountId = session.activeAccountId;
final authHeader = session.service?.authHeaders['Authorization'];
if (accountId == null || authHeader == null) {
return cancel();
final prefs = await session.prefsFuture;
final store = session.accountStore;
final wifiOnly = !sync.syncOnCellular;
final signedOut = store.loadSignedOut(prefs);
for (final account in session.accounts) {
try {
if (signedOut.contains(account.id)) {
await cancelAccount(account.id);
continue;
}
final isActive = account.id == session.activeAccountId;
final config = isActive
? _SyncConfig(
paths: sync.syncEverything ? ['/'] : sync.syncedPaths,
intervalMinutes: sync.backgroundSyncIntervalMinutes,
)
: _SyncConfig.fromPrefs(prefs, store.accountPrefKey, account.id);
final password = await store.readPassword(account.id);
if (password == null ||
config.paths.isEmpty ||
config.intervalMinutes == null) {
await cancelAccount(account.id);
continue;
}
await _channel.invokeMethod('reschedule', {
'accountId': account.id,
'serverUrl': account.serverUrl,
'username': account.username,
'authHeader': _basicAuth(account, password),
'folders': jsonEncode(config.paths),
'wifiOnly': wifiOnly,
'intervalMinutes': config.intervalMinutes,
'notify': sync.syncNotifications,
});
} catch (e) {
debugPrint('[SyncService] Could not schedule ${account.id}: $e');
}
}
final paths = sync.syncEverything ? ['/'] : sync.syncedPaths;
await _channel.invokeMethod('reschedule', {
'accountId': accountId,
'serverUrl': session.serverUrl,
'username': session.username,
'authHeader': authHeader,
'folders': jsonEncode(paths),
'wifiOnly': !sync.syncOnCellular,
});
}
static Future<void> cancel() async {
await _channel.invokeMethod('cancel');
static String _basicAuth(SavedAccount account, String password) =>
'Basic ${base64Encode(utf8.encode('${account.username}:$password'))}';
/// Stops [accountId]'s periodic job (the account was removed, or has
/// nothing left to sync).
static Future<void> cancelAccount(String accountId) async {
await _channel.invokeMethod('cancel', {'accountId': accountId});
}
/// Runs a one-off sync pass immediately (Settings' "Sync now"),
/// independent of the periodic schedule.
/// Runs a one-off sync pass immediately, independent of the periodic
/// schedule.
///
/// [force] (Settings' "Sync now", a newly-added path): full walk of every
/// synced root, visible progress notification, supersedes any run already
/// in flight. Without it (pull-to-refresh, foreground timer, app resume)
/// the pass is a quiet check that uses the cheap root-etag shortcut and
/// never interrupts a run already in progress. [respectNetworkSetting]
/// makes such a pass wait for Wi-Fi when "Sync on cellular" is off (the
/// automatic triggers do; a deliberate pull doesn't).
static Future<void> syncNow(
SessionController session,
SyncStatusController sync,
) async {
SyncStatusController sync, {
bool force = true,
bool respectNetworkSetting = false,
}) async {
final accountId = session.activeAccountId;
final authHeader = session.service?.authHeaders['Authorization'];
if (accountId == null || authHeader == null) {
@@ -105,26 +164,43 @@ class SyncService {
'username': session.username,
'authHeader': authHeader,
'folders': jsonEncode(paths),
'force': force,
'notify': sync.syncNotifications,
if (respectNetworkSetting) 'wifiOnly': !sync.syncOnCellular,
});
}
/// One-shot status snapshot - used to seed [SyncStatusController]'s state
/// right after login/account-switch, before the first [statusStream]
/// event arrives.
static Future<SyncStatusSnapshot> getStatus() async {
///
/// [accountId] is required for `syncedFileIds` to be populated on a fresh
/// app start - the native bus only knows an account once a sync pass has
/// run in this process.
static Future<SyncStatusSnapshot> getStatus(String? accountId) async {
final result = await _channel.invokeMethod<Map<dynamic, dynamic>>(
'getSyncStatus',
{'accountId': accountId},
);
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>),
);
}
///
/// One shared stream, deliberately: every call to
/// `EventChannel.receiveBroadcastStream()` opens its *own* native
/// subscription, and the native side only keeps one listener - a second
/// subscriber (the Offline tab's controller, once it became eagerly
/// created) silently took the events away from the first
/// (`SyncStatusController`), so sync badges stopped updating until the app
/// was restarted. This is a broadcast stream, so any number of Dart
/// listeners share the one native subscription.
static final Stream<SyncStatusSnapshot> statusStream = _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`
@@ -184,3 +260,66 @@ class SyncService {
return file.existsSync() ? file.path : null;
}
}
/// One account's background-sync settings, as far as scheduling is
/// concerned.
class _SyncConfig {
final List<String> paths;
/// Null = background sync off for this account.
final int? intervalMinutes;
const _SyncConfig({required this.paths, required this.intervalMinutes});
/// Reads a *non-active* account's persisted settings - the same per-account
/// keys `SyncStatusController`/`FilesController` write. Malformed values
/// fall back to "nothing to sync" rather than throwing.
factory _SyncConfig.fromPrefs(
SharedPreferences prefs,
String Function(String accountId, String baseKey) key,
String accountId,
) {
var paths = <String>[];
try {
final everything =
prefs.getBool(
key(accountId, SyncStatusController.prefSyncEverything),
) ??
false;
final json = prefs.getString(
key(accountId, SyncStatusController.prefSyncedPaths),
);
if (everything) {
paths = ['/'];
} else if (json != null) {
paths = (jsonDecode(json) as List).cast<String>();
}
} catch (e) {
debugPrint('[SyncService] Unreadable sync paths for $accountId: $e');
}
var policy = defaultCachePolicy;
var minutes = defaultCacheIntervalMinutes;
try {
final policyName = prefs.getString(
key(accountId, FilesController.prefCachePolicy),
);
policy = CachePolicy.values.firstWhere(
(c) => c.name == policyName,
orElse: () => defaultCachePolicy,
);
minutes =
prefs.getInt(
key(accountId, FilesController.prefCacheIntervalMinutes),
) ??
defaultCacheIntervalMinutes;
} catch (e) {
debugPrint('[SyncService] Unreadable cache rule for $accountId: $e');
}
return _SyncConfig(
paths: paths,
intervalMinutes: policy == CachePolicy.interval ? minutes : null,
);
}
}
+64 -65
View File
@@ -8,6 +8,7 @@ import '../providers/settings_controller.dart';
import '../providers/sync_status_controller.dart';
import '../services/sync_service.dart';
import '../theme/app_theme.dart';
import '../widgets/app_tab_view_builder.dart';
import '../widgets/frosted_glass_container.dart';
import '../widgets/seek_bar_painter.dart';
import '../widgets/synced_header_scaffold.dart' show formatQuota;
@@ -254,6 +255,25 @@ class AccountView extends StatelessWidget {
const _DeviceSyncCard(),
const SizedBox(height: 24),
// Files Cache
Text(
'Files Cache',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 4),
Text(
'How often folder listings and synced files refresh from the server',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 10),
const _CacheSettingsCard(),
const SizedBox(height: 24),
// Material You Design Settings
Text(
'Material You Aesthetics',
@@ -443,24 +463,6 @@ class AccountView extends StatelessWidget {
),
const SizedBox(height: 10),
const _MediaPlayerCard(),
const SizedBox(height: 24),
// Files Cache
Text(
'Files Cache',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 4),
Text(
'Reuse a folder\'s listing instead of refetching it on every visit',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 10),
const _CacheSettingsCard(),
],
),
),
@@ -772,8 +774,6 @@ class _DeviceSyncCardState extends State<_DeviceSyncCard> {
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final session = context.watch<SessionController>();
final sync = context.watch<SyncStatusController>();
final folders = sync.syncedPaths;
@@ -793,49 +793,37 @@ class _DeviceSyncCardState extends State<_DeviceSyncCard> {
onChanged: sync.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,
),
ListTile(
leading: const Icon(Icons.offline_pin_rounded),
title: const Text('View offline files'),
subtitle: Text(
everything
? 'Every folder in this account is synced'
: folders.isEmpty
? 'Nothing synced yet'
: '${folders.length} synced folder${folders.length == 1 ? '' : 's'}/file${folders.length == 1 ? '' : 's'}',
),
trailing: const Icon(Icons.chevron_right_rounded),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (_) =>
Scaffold(body: buildAppTabView(AppTab.offline, ScrollController())),
),
)
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: () {
sync.removeSyncedPath(folder);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Removed from device sync'),
behavior: SnackBarBehavior.floating,
),
);
},
),
),
const Divider(height: 1, indent: 16, endIndent: 16),
],
),
),
const Divider(height: 1, indent: 16, endIndent: 16),
SwitchListTile(
secondary: const Icon(Icons.notifications_outlined),
title: const Text('Background sync notifications'),
subtitle: const Text(
'Show a notification when a background sync updates files. '
'Conflicts and "Sync now" always notify.',
),
value: sync.syncNotifications,
onChanged: sync.setSyncNotifications,
),
const Divider(height: 1, indent: 16, endIndent: 16),
SwitchListTile(
secondary: const Icon(Icons.signal_cellular_alt_rounded),
title: const Text('Sync on cellular'),
@@ -1359,11 +1347,14 @@ class _CacheSettingsCard extends StatelessWidget {
String _description(CachePolicy policy) {
switch (policy) {
case CachePolicy.never:
return 'Every visit to a folder fetches it fresh';
return 'Every visit to a folder fetches it fresh; synced files are '
'checked each time you open the app';
case CachePolicy.interval:
return 'Reuse a folder\'s listing until it\'s a few minutes old';
return 'Reuse a folder\'s listing until it\'s a few minutes old; '
'synced files update in the background on the same schedule';
case CachePolicy.manual:
return 'Reuse a folder\'s listing until you pull to refresh';
return 'Reuse a folder\'s listing until you pull to refresh; synced '
'files only update when you pull down or tap Sync now';
}
}
@@ -1425,6 +1416,14 @@ class _CacheSettingsCard extends StatelessWidget {
onChanged: (value) =>
files.setCacheIntervalMinutes(value.round()),
),
if (files.cacheIntervalMinutes < 15)
Text(
'While the app is closed, synced files refresh at most '
'every 15 min (an Android limit).',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
+235 -65
View File
@@ -1,4 +1,5 @@
import 'dart:convert';
import 'dart:io';
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:flutter/material.dart';
@@ -53,10 +54,30 @@ class FileViewerScreen extends StatefulWidget {
/// The other items in the same folder/album, so images and videos can be
/// swiped through without leaving the viewer. Non-media items in this list
/// are ignored. If omitted (or the item isn't an image/video), the viewer
/// just shows [item] on its own.
/// just shows [item] on its own. Works the same way whether or not
/// [localPathResolver] is set - swiping through offline media resolves
/// each sibling's local path on demand, exactly like Files/Photos.
final List<NextcloudItem>? siblings;
const FileViewerScreen({super.key, required this.item, this.siblings});
/// When set, every preview (and "open externally") resolves its file
/// from local disk through this instead of fetching from the server -
/// used by the Offline tab, whose whole point is browsing already-
/// downloaded files with no connection. Called once per item actually
/// shown (the initial item and each swiped-to sibling), not just up
/// front. Actions that need a live server (favorite/delete/download-to-
/// device) hide themselves in this mode; Share/Open-externally/Details
/// still work (Share already prefers the local copy when one exists -
/// see `ShareSheet._shareFileDirectly` - and Details' shares/activity/
/// versions tabs degrade the same way any other offline server call
/// does).
final Future<String?> Function(NextcloudItem item)? localPathResolver;
const FileViewerScreen({
super.key,
required this.item,
this.siblings,
this.localPathResolver,
});
/// Opens the viewer with no page transition — media should appear
/// instantly, not fade/zoom in the way MaterialPageRoute normally would.
@@ -65,10 +86,14 @@ class FileViewerScreen extends StatefulWidget {
static Route<void> route({
required NextcloudItem item,
List<NextcloudItem>? siblings,
Future<String?> Function(NextcloudItem item)? localPathResolver,
}) {
return _InstantOpenPageRoute<void>(
pageBuilder: (context) =>
FileViewerScreen(item: item, siblings: siblings),
pageBuilder: (context) => FileViewerScreen(
item: item,
siblings: siblings,
localPathResolver: localPathResolver,
),
);
}
@@ -112,6 +137,8 @@ class _FileViewerScreenState extends State<FileViewerScreen> {
NextcloudItem get _currentItem => _mediaItems[_currentIndex];
bool get _isOffline => widget.localPathResolver != null;
bool get _isPdf => _currentItem.name.toLowerCase().endsWith('.pdf');
bool get _isText => _textPreviewExtensions.contains(
p.extension(_currentItem.name).toLowerCase(),
@@ -173,7 +200,19 @@ class _FileViewerScreenState extends State<FileViewerScreen> {
final item = _currentItem;
setState(() => _isBusy = true);
try {
final path = await _downloadToTemp(session, item);
final path = _isOffline
? await widget.localPathResolver!(item)
: await _downloadToTemp(session, item);
if (path == null) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('This file is no longer available offline'),
),
);
}
return;
}
final result = await OpenFile.open(path);
if (mounted && result.type != ResultType.done) {
ScaffoldMessenger.of(context).showSnackBar(
@@ -371,6 +410,10 @@ class _FileViewerScreenState extends State<FileViewerScreen> {
child: _MediaActionBar(
isFavorite: _currentItem.isFavorite,
isBusy: _isBusy,
// Favorite/delete/download-to-device all need a live
// server - hidden rather than shown-and-failing while
// browsing an already-local file from the Offline tab.
showServerActions: !_isOffline,
opacity: settings.bottomBarOpacity,
blurSigma: settings.bottomBarBlur,
onShare: () => ShareSheet.show(context, _currentItem),
@@ -401,21 +444,59 @@ class _FileViewerScreenState extends State<FileViewerScreen> {
onPageChanged: (index) => setState(() => _currentIndex = index),
itemBuilder: (context, index) {
final mediaItem = _mediaItems[index];
if (mediaItem.type == NextcloudItemType.image) {
return _ImagePreview(
if (!_isOffline) {
if (mediaItem.type == NextcloudItemType.image) {
return _ImagePreview(
key: ValueKey(mediaItem.id),
url: session.service!.fileUrl(mediaItem.path),
headers: session.service!.authHeaders,
);
}
return _VideoPreview(
key: ValueKey(mediaItem.id),
url: session.service!.fileUrl(mediaItem.path),
headers: session.service!.authHeaders,
isActive: index == _currentIndex,
controlsBottomOffset: _controlsVisible ? 108 : 24,
opacity: settings.bottomBarOpacity,
blurSigma: settings.bottomBarBlur,
);
}
return _VideoPreview(
// Offline: each swiped-to item resolves its own local path on
// demand (see FileViewerScreen.localPathResolver's doc comment) -
// this is what makes swiping through offline media behave exactly
// like Files/Photos instead of only ever showing the one item the
// viewer was opened on.
return FutureBuilder<String?>(
key: ValueKey(mediaItem.id),
url: session.service!.fileUrl(mediaItem.path),
headers: session.service!.authHeaders,
isActive: index == _currentIndex,
controlsBottomOffset: _controlsVisible ? 108 : 24,
opacity: settings.bottomBarOpacity,
blurSigma: settings.bottomBarBlur,
future: widget.localPathResolver!(mediaItem),
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
final localPath = snapshot.data;
if (localPath == null) {
return Center(
child: Icon(
Icons.cloud_off_rounded,
color: Theme.of(context).colorScheme.onSurfaceVariant,
size: 64,
),
);
}
if (mediaItem.type == NextcloudItemType.image) {
return _ImagePreview(url: null, headers: const {}, localPath: localPath);
}
return _VideoPreview(
url: null,
headers: const {},
localPath: localPath,
isActive: index == _currentIndex,
controlsBottomOffset: _controlsVisible ? 108 : 24,
opacity: settings.bottomBarOpacity,
blurSigma: settings.bottomBarBlur,
);
},
);
},
);
@@ -429,10 +510,18 @@ class _FileViewerScreenState extends State<FileViewerScreen> {
return const SizedBox.shrink();
default:
if (_isPdf) {
return _PdfPreview(item: widget.item, session: session);
return _PdfPreview(
item: widget.item,
session: session,
localPathResolver: widget.localPathResolver,
);
}
if (_isText) {
return _TextPreview(item: widget.item, session: session);
return _TextPreview(
item: widget.item,
session: session,
localPathResolver: widget.localPathResolver,
);
}
return _UnsupportedPreview(
item: widget.item,
@@ -449,6 +538,7 @@ class _FileViewerScreenState extends State<FileViewerScreen> {
class _MediaActionBar extends StatelessWidget {
final bool isFavorite;
final bool isBusy;
final bool showServerActions;
final double opacity;
final double blurSigma;
final VoidCallback onShare;
@@ -461,6 +551,7 @@ class _MediaActionBar extends StatelessWidget {
const _MediaActionBar({
required this.isFavorite,
required this.isBusy,
required this.showServerActions,
required this.opacity,
required this.blurSigma,
required this.onShare,
@@ -493,30 +584,33 @@ class _MediaActionBar extends StatelessWidget {
tooltip: 'Share',
onTap: isBusy ? null : onShare,
),
_ActionIconButton(
icon: isFavorite
? Icons.favorite_rounded
: Icons.favorite_border_rounded,
tooltip: 'Favorite',
color: isFavorite ? Colors.red : null,
onTap: onFavorite,
),
if (showServerActions)
_ActionIconButton(
icon: isFavorite
? Icons.favorite_rounded
: Icons.favorite_border_rounded,
tooltip: 'Favorite',
color: isFavorite ? Colors.red : null,
onTap: onFavorite,
),
_ActionIconButton(
icon: Icons.open_in_new_rounded,
tooltip: 'Open externally',
onTap: isBusy ? null : onOpenExternally,
),
_ActionIconButton(
icon: Icons.download_rounded,
tooltip: 'Download',
onTap: isBusy ? null : onDownload,
),
_ActionIconButton(
icon: Icons.delete_outline_rounded,
tooltip: 'Delete',
color: colorScheme.error,
onTap: isBusy ? null : onDelete,
),
if (showServerActions)
_ActionIconButton(
icon: Icons.download_rounded,
tooltip: 'Download',
onTap: isBusy ? null : onDownload,
),
if (showServerActions)
_ActionIconButton(
icon: Icons.delete_outline_rounded,
tooltip: 'Delete',
color: colorScheme.error,
onTap: isBusy ? null : onDelete,
),
_ActionIconButton(
icon: Icons.info_outline_rounded,
tooltip: 'Details',
@@ -567,10 +661,20 @@ class _ActionIconButton extends StatelessWidget {
}
class _ImagePreview extends StatefulWidget {
final String url;
final String? url;
final Map<String, String> headers;
const _ImagePreview({super.key, required this.url, required this.headers});
/// When set, read the image from this on-disk path instead of [url] -
/// already-resolved by the caller (see
/// `FileViewerScreen.localPathResolver`'s doc comment).
final String? localPath;
const _ImagePreview({
super.key,
required this.url,
required this.headers,
this.localPath,
});
@override
State<_ImagePreview> createState() => _ImagePreviewState();
@@ -646,24 +750,38 @@ class _ImagePreviewState extends State<_ImagePreview>
minScale: 0.8,
maxScale: 5.0,
child: Center(
child: Image.network(
widget.url,
headers: widget.headers,
fit: BoxFit.contain,
loadingBuilder: (context, child, progress) {
if (progress == null) return child;
return Center(
child: CircularProgressIndicator(color: colorScheme.primary),
);
},
errorBuilder: (context, error, stack) => Center(
child: Icon(
Icons.broken_image_outlined,
color: colorScheme.onSurfaceVariant,
size: 64,
),
),
),
child: widget.localPath != null
? Image.file(
File(widget.localPath!),
fit: BoxFit.contain,
errorBuilder: (context, error, stack) => Center(
child: Icon(
Icons.broken_image_outlined,
color: colorScheme.onSurfaceVariant,
size: 64,
),
),
)
: Image.network(
widget.url!,
headers: widget.headers,
fit: BoxFit.contain,
loadingBuilder: (context, child, progress) {
if (progress == null) return child;
return Center(
child: CircularProgressIndicator(
color: colorScheme.primary,
),
);
},
errorBuilder: (context, error, stack) => Center(
child: Icon(
Icons.broken_image_outlined,
color: colorScheme.onSurfaceVariant,
size: 64,
),
),
),
),
),
),
@@ -672,10 +790,15 @@ class _ImagePreviewState extends State<_ImagePreview>
}
class _VideoPreview extends StatefulWidget {
final String url;
final String? url;
final Map<String, String> headers;
final bool isActive;
/// When set, read the video from this on-disk path instead of [url] -
/// already-resolved by the caller (see
/// `FileViewerScreen.localPathResolver`'s doc comment).
final String? localPath;
/// Distance from the bottom of the screen the transport controls should
/// sit at. Passed in by the parent so the controls can track the floating
/// action bar: resting just above it when visible, sliding down to hug
@@ -691,6 +814,7 @@ class _VideoPreview extends StatefulWidget {
super.key,
required this.url,
required this.headers,
this.localPath,
this.isActive = true,
this.controlsBottomOffset = 24,
this.opacity = 0.55,
@@ -713,10 +837,12 @@ class _VideoPreviewState extends State<_VideoPreview> {
Future<void> _init() async {
try {
final controller = VideoPlayerController.networkUrl(
Uri.parse(widget.url),
httpHeaders: widget.headers,
);
final controller = widget.localPath != null
? VideoPlayerController.file(File(widget.localPath!))
: VideoPlayerController.networkUrl(
Uri.parse(widget.url!),
httpHeaders: widget.headers,
);
await controller.initialize();
if (!mounted) {
controller.dispose();
@@ -973,7 +1099,16 @@ class _PdfPreview extends StatefulWidget {
final NextcloudItem item;
final SessionController session;
const _PdfPreview({required this.item, required this.session});
/// When set, read bytes from the local path it resolves to instead of
/// fetching from the server - see
/// `FileViewerScreen.localPathResolver`'s doc comment.
final Future<String?> Function(NextcloudItem item)? localPathResolver;
const _PdfPreview({
required this.item,
required this.session,
this.localPathResolver,
});
@override
State<_PdfPreview> createState() => _PdfPreviewState();
@@ -991,11 +1126,25 @@ class _PdfPreviewState extends State<_PdfPreview> {
Future<void> _load() async {
try {
final bytes = await widget.session.service!.fetchBytes(widget.item.path);
final Uint8List bytes;
if (widget.localPathResolver != null) {
final localPath = await widget.localPathResolver!(widget.item);
if (localPath == null) {
if (mounted) {
setState(() => _error = 'No longer available offline');
}
return;
}
bytes = await File(localPath).readAsBytes();
} else {
bytes = Uint8List.fromList(
await widget.session.service!.fetchBytes(widget.item.path),
);
}
if (!mounted) return;
setState(() {
_controller = PdfControllerPinch(
document: PdfDocument.openData(Uint8List.fromList(bytes)),
document: PdfDocument.openData(bytes),
);
});
} catch (e) {
@@ -1040,7 +1189,16 @@ class _TextPreview extends StatefulWidget {
final NextcloudItem item;
final SessionController session;
const _TextPreview({required this.item, required this.session});
/// When set, read bytes from the local path it resolves to instead of
/// fetching from the server - see
/// `FileViewerScreen.localPathResolver`'s doc comment.
final Future<String?> Function(NextcloudItem item)? localPathResolver;
const _TextPreview({
required this.item,
required this.session,
this.localPathResolver,
});
@override
State<_TextPreview> createState() => _TextPreviewState();
@@ -1058,7 +1216,19 @@ class _TextPreviewState extends State<_TextPreview> {
Future<void> _load() async {
try {
final bytes = await widget.session.service!.fetchBytes(widget.item.path);
final List<int> bytes;
if (widget.localPathResolver != null) {
final localPath = await widget.localPathResolver!(widget.item);
if (localPath == null) {
if (mounted) {
setState(() => _error = 'No longer available offline');
}
return;
}
bytes = await File(localPath).readAsBytes();
} else {
bytes = await widget.session.service!.fetchBytes(widget.item.path);
}
if (mounted) {
setState(() => _content = utf8.decode(bytes, allowMalformed: true));
}
+180 -254
View File
@@ -1,16 +1,18 @@
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:file_saver/file_saver.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:path/path.dart' as p;
import 'package:provider/provider.dart';
import 'package:share_plus/share_plus.dart';
import '../models/nextcloud_item.dart';
import '../models/selection_action.dart';
import '../providers/files_controller.dart';
import '../providers/folder_browser.dart';
import '../providers/item_operations.dart';
import '../providers/offline_controller.dart';
import '../providers/pick_controller.dart';
import '../providers/session_controller.dart';
import '../providers/settings_controller.dart';
@@ -19,13 +21,14 @@ import '../services/download_service.dart';
import '../services/share_intent_service.dart';
import '../widgets/breadcrumbs.dart';
import '../widgets/details/details_sheet.dart';
import '../widgets/files_controls_row.dart';
import '../widgets/item_icon.dart';
import '../widgets/manage_synced_folders_sheet.dart';
import '../widgets/media_grid_tile.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/swipeable_item.dart';
import '../widgets/sync_status_badge.dart';
@@ -34,10 +37,23 @@ import 'file_viewer_screen.dart';
import 'move_copy_destination_picker.dart';
import 'share_upload_view.dart';
/// The Files tab - and, with [offline] set, the Offline tab, which is the
/// same view over the device-sync mirror instead of the server: the Files
/// tab's folders filtered down to what's available offline. The two share
/// every display pref/control, the header, breadcrumbs, list/grid tiles and
/// thumbnails; [offline] only swaps the data source (`FolderBrowser`),
/// reads images from the local file instead of a server preview, and turns
/// off everything that needs the server (selection and its bulk actions,
/// swipe actions, sync badges, the "+" menu, pick mode).
class FilesView extends StatefulWidget {
final ScrollController scrollController;
final bool offline;
const FilesView({super.key, required this.scrollController});
const FilesView({
super.key,
required this.scrollController,
this.offline = false,
});
@override
State<FilesView> createState() => _FilesViewState();
@@ -116,6 +132,35 @@ class _FilesViewState extends State<FilesView>
bool get _isSelecting => _selectedIds.isNotEmpty;
bool get _offline => widget.offline;
/// The folder data source for this tab. Watches the concrete controller
/// (that's what's registered as a provider), then hands it back as the
/// [FolderBrowser] the rest of the view actually needs.
FolderBrowser _browserOf(BuildContext context) => _offline
? context.watch<OfflineController>()
: context.watch<FilesController>();
/// The on-device copy of [item] for the Offline tab; null online, where
/// thumbnails come from server previews instead.
File? _localFileFor(BuildContext context, NextcloudItem item) => _offline
? context.read<OfflineController>().localFileFor(item)
: null;
// (Online only - the Offline tab always reloads on first build, since a
// local listing has no cheap "already loaded" signal.)
// Normally FilesController's own account-activation listener fetches the
// first listing (see FilesController._onAccountActivated) - but the
// bottom nav collapses to just the Offline tab while
// ConnectivityController briefly (mis)reports offline right after a cold
// start, which stops this view (and therefore FilesController, a lazily-
// constructed provider) from ever being built during the window that
// listener fires in. Photos/Favorites already guard against exactly this
// with their own one-shot self-fetch on first build; Files needs the same
// fallback so a folder that's genuinely empty is distinguishable from one
// that just never got its initial fetch.
bool _requestedInitialLoad = false;
@override
void initState() {
super.initState();
@@ -411,14 +456,26 @@ class _FilesViewState extends State<FilesView>
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
// Display prefs (grid/list, filters, sort) live on FilesController for
// both tabs; `browser` is the tab's own folder listing.
final files = context.watch<FilesController>();
final browser = _browserOf(context);
final pathDepth = files.pathStack.length;
if (!_requestedInitialLoad) {
_requestedInitialLoad = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_offline || (browser.items.isEmpty && !browser.isLoading)) {
browser.reload();
}
});
}
final pathDepth = browser.pathStack.length;
final navigatingDeeper = pathDepth > _lastPathDepth;
_lastPathDepth = pathDepth;
final hasBreadcrumbs = files.pathStack.length > 1;
final selectedItems = files.items
final hasBreadcrumbs = browser.pathStack.length > 1;
final selectedItems = browser.items
.where((i) => _selectedIds.contains(i.id))
.toList();
@@ -430,134 +487,20 @@ class _FilesViewState extends State<FilesView>
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 44,
// No persistent hint widget here - instead, a one-shot nudge
// (see _playControlsScrollHint, triggered from initState) just
// scrolls this row a little to the right and back, once, right
// after it first appears. Two static attempts before this -
// fading the controls' own opacity via ShaderMask, then a
// chevron badge overlaid on the edge - both add a
// permanent element competing with the actual controls; a
// motion cue that plays once and gets out of the way reads
// just as clearly without that cost.
child: SingleChildScrollView(
controller: _controlsScrollController,
scrollDirection: Axis.horizontal,
child: Row(
children: [
IconButton(
icon: Icon(
files.filesSortAscending
? Icons.arrow_upward_rounded
: Icons.arrow_downward_rounded,
size: 20,
),
visualDensity: VisualDensity.compact,
tooltip: files.filesSortAscending
? 'Ascending'
: 'Descending',
onPressed: files.toggleFilesSortOrder,
),
// A plain width, not Expanded - this row scrolls
// horizontally now, which gives every control unbounded
// width to lay out in, so a flex child would throw.
SizedBox(
width: 130,
child: SortMenuButton(
field: files.filesSortField,
onChanged: files.setFilesSortField,
),
),
ToggleIconButton(
icon: files.showHiddenFiles
? Icons.visibility_rounded
: Icons.visibility_off_rounded,
isSelected: files.showHiddenFiles,
onTap: () => files.toggleShowHiddenFiles(),
tooltip: 'Show hidden files',
),
const SizedBox(width: 4),
SegmentedIconGroup(
children: [
ToggleIconButton(
icon: Symbols.circles_rounded,
isSelected: files.storageScope == StorageScope.cloud,
onTap: () =>
files.setStorageScope(StorageScope.cloud),
tooltip: 'Cloud storage',
),
ToggleIconButton(
icon: Symbols.hard_drive_rounded,
isSelected:
files.storageScope == StorageScope.external,
onTap: () =>
files.setStorageScope(StorageScope.external),
tooltip: 'External storage',
),
],
),
const SizedBox(width: 8),
SegmentedIconGroup(
children: [
ToggleIconButton(
icon: Icons.select_all_rounded,
isSelected:
files.filesTypeFilter == FilesTypeFilter.all,
onTap: () =>
files.setFilesTypeFilter(FilesTypeFilter.all),
tooltip: 'Files & folders',
),
ToggleIconButton(
icon: Icons.insert_drive_file_outlined,
isSelected:
files.filesTypeFilter ==
FilesTypeFilter.filesOnly,
onTap: () => files.setFilesTypeFilter(
FilesTypeFilter.filesOnly,
),
tooltip: 'Files only',
),
ToggleIconButton(
icon: Icons.folder_outlined,
isSelected:
files.filesTypeFilter ==
FilesTypeFilter.foldersOnly,
onTap: () => files.setFilesTypeFilter(
FilesTypeFilter.foldersOnly,
),
tooltip: 'Folders only',
),
],
),
const SizedBox(width: 8),
SegmentedIconGroup(
children: [
ToggleIconButton(
icon: Icons.view_list_rounded,
isSelected: !files.isGridView,
onTap: () => files.setGridView(false),
tooltip: 'List view',
),
ToggleIconButton(
icon: Icons.grid_view_rounded,
isSelected: files.isGridView,
onTap: () => files.setGridView(true),
tooltip: 'Grid view',
),
],
),
],
),
),
// The scroll-hint nudge (see _playScrollHint) plays on this row
// once, right after it first appears.
FilesControlsRow(
folderPath: browser.currentFolderPath,
showStorageScope: !_offline,
scrollController: _controlsScrollController,
),
if (hasBreadcrumbs) ...[
const SizedBox(height: 10),
SizedBox(
height: 32,
child: Breadcrumbs(
pathStack: files.pathStack,
onTap: (index) => files.navigateToPathIndex(index),
pathStack: browser.pathStack,
onTap: (index) => browser.navigateToPathIndex(index),
),
),
],
@@ -577,12 +520,12 @@ class _FilesViewState extends State<FilesView>
),
),
// Files List / Grid
if (files.isLoading)
if (browser.isLoading)
const SliverFillRemaining(
hasScrollBody: false,
child: Center(child: CircularProgressIndicator()),
)
else if (files.errorMessage != null)
else if (browser.errorMessage != null)
SliverFillRemaining(
hasScrollBody: false,
child: Center(
@@ -598,7 +541,7 @@ class _FilesViewState extends State<FilesView>
),
const SizedBox(height: 16),
Text(
'WebDAV Sync Error',
_offline ? 'Could not read local files' : 'WebDAV Sync Error',
style: theme.textTheme.titleLarge?.copyWith(
color: colorScheme.error,
fontWeight: FontWeight.bold,
@@ -606,7 +549,7 @@ class _FilesViewState extends State<FilesView>
),
const SizedBox(height: 8),
Text(
files.errorMessage!,
browser.errorMessage!,
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
@@ -614,16 +557,16 @@ class _FilesViewState extends State<FilesView>
),
const SizedBox(height: 20),
FilledButton.icon(
onPressed: files.refreshData,
onPressed: browser.reload,
icon: const Icon(Icons.refresh_rounded),
label: const Text('Retry Connection'),
label: Text(_offline ? 'Retry' : 'Retry Connection'),
),
],
),
),
),
)
else if (files.items.isEmpty)
else if (browser.items.isEmpty)
SliverFillRemaining(
hasScrollBody: false,
child: Center(
@@ -631,13 +574,17 @@ class _FilesViewState extends State<FilesView>
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.folder_open_rounded,
_offline
? Icons.offline_pin_outlined
: Icons.folder_open_rounded,
size: 64,
color: colorScheme.outlineVariant,
),
const SizedBox(height: 12),
Text(
'Folder is empty',
_offline && !hasBreadcrumbs
? 'Nothing downloaded yet'
: 'Folder is empty',
style: theme.textTheme.titleMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
@@ -658,14 +605,14 @@ class _FilesViewState extends State<FilesView>
mainAxisSpacing: 12,
),
delegate: SliverChildBuilderDelegate((context, index) {
final item = files.items[index];
final item = browser.items[index];
return _FolderEnterAnimation(
key: ValueKey('${files.currentFolderPath}::${item.id}'),
key: ValueKey('${browser.currentFolderPath}::${item.id}'),
index: index,
fromRight: navigatingDeeper,
child: _buildGridCard(context, item),
);
}, childCount: files.items.length),
}, childCount: browser.items.length),
),
)
else
@@ -674,14 +621,14 @@ class _FilesViewState extends State<FilesView>
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
sliver: SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final item = files.items[index];
final item = browser.items[index];
return _FolderEnterAnimation(
key: ValueKey('${files.currentFolderPath}::${item.id}'),
key: ValueKey('${browser.currentFolderPath}::${item.id}'),
index: index,
fromRight: navigatingDeeper,
child: _buildListTile(context, item),
);
}, childCount: files.items.length),
}, childCount: browser.items.length),
),
),
@@ -696,23 +643,31 @@ class _FilesViewState extends State<FilesView>
];
return PopScope(
canPop: !_isSelecting && files.pathStack.length <= 1,
canPop: !_isSelecting && browser.pathStack.length <= 1,
onPopInvokedWithResult: (didPop, result) {
if (didPop) return;
if (_isSelecting) {
_clearSelection();
} else {
files.navigateUp();
browser.navigateUp();
}
},
child: SyncedHeaderScaffold(
scrollController: widget.scrollController,
onRefresh: browser.reload,
actions: [
IconButton(
icon: const Icon(Icons.add_rounded),
tooltip: 'New',
onPressed: () => _showCreateMenu(context),
),
if (_offline)
IconButton(
icon: const Icon(Icons.sync_rounded),
tooltip: 'Manage synced folders',
onPressed: () => ManageSyncedFoldersSheet.show(context),
)
else
IconButton(
icon: const Icon(Icons.add_rounded),
tooltip: 'New',
onPressed: () => _showCreateMenu(context),
),
const MoreTabsButton(),
const ProfileAvatarButton(),
],
@@ -815,15 +770,17 @@ class _FilesViewState extends State<FilesView>
) {
final allSynced = items.every((i) => sync.isPathSynced(i.path));
if (allSynced) {
for (final item in items) {
sync.removeSyncedPath(item.path);
}
// Batched (not one removeSyncedPath call per item) so the
// reschedule/native side effects fire once for the whole selection
// instead of racing each other - see addSyncedPaths' doc comment
// for why a per-item loop caused only the first item to actually
// sync.
sync.removeSyncedPaths(items.map((i) => i.path).toList());
} else {
for (final item in items) {
if (!sync.isPathSynced(item.path)) {
sync.addSyncedPath(item.path, isFolder: item.isFolder);
}
}
sync.addSyncedPaths({
for (final item in items)
if (!sync.isPathSynced(item.path)) item.path: item.isFolder,
});
}
_clearSelection();
ScaffoldMessenger.of(context).showSnackBar(
@@ -989,13 +946,15 @@ class _FilesViewState extends State<FilesView>
Widget _buildListTile(BuildContext context, NextcloudItem item) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final files = context.watch<FilesController>();
final browser = _browserOf(context);
final pick = context.watch<PickController>();
final sync = context.watch<SyncStatusController>();
final session = context.watch<SessionController>();
final settings = context.watch<SettingsController>();
final ops = context.read<ItemOperations>();
final isSelected = _selectedIds.contains(item.id);
// Pick mode and selection are server-side features - never on Offline.
final picking = !_offline && pick.isPicking;
// No border radius here — the outer ClipRRect below is the only place
// that rounds this tile's corners. Rounding it here too would give the
@@ -1007,17 +966,17 @@ class _FilesViewState extends State<FilesView>
: colorScheme.surfaceContainerLow,
child: InkWell(
onTap: () {
if (pick.isPicking) {
if (picking) {
_handlePickTap(context, item);
} else if (_isSelecting) {
_toggleSelection(item);
} else if (item.isFolder) {
files.navigateToFolder(item.path);
browser.navigateToFolder(item.path);
} else {
_openFile(context, item);
}
},
onLongPress: pick.isPicking && !pick.pickRequest!.allowMultiple
onLongPress: _offline || (picking && !pick.pickRequest!.allowMultiple)
? null
: () => _toggleSelection(item),
child: Padding(
@@ -1034,18 +993,21 @@ class _FilesViewState extends State<FilesView>
child: ItemThumbnail(
item: item,
service: session.service,
localFile: _localFileFor(context, item),
size: 44,
borderRadius: 12,
iconSize: 22,
),
),
Positioned(
right: -2,
bottom: -2,
child: SyncStatusBadge(
status: sync.syncStatusFor(item),
// Everything on the Offline tab is synced by definition.
if (!_offline)
Positioned(
right: -2,
bottom: -2,
child: SyncStatusBadge(
status: sync.syncStatusFor(item),
),
),
),
],
),
const SizedBox(width: 14),
@@ -1078,7 +1040,7 @@ class _FilesViewState extends State<FilesView>
),
);
final content = _isSelecting || pick.isPicking
final content = _isSelecting || picking || _offline
? card
: SwipeableItem(
itemKey: ValueKey('file-${item.id}'),
@@ -1111,14 +1073,19 @@ class _FilesViewState extends State<FilesView>
}
Widget _buildGridCard(BuildContext context, NextcloudItem item) {
final files = context.watch<FilesController>();
final browser = _browserOf(context);
final pick = context.watch<PickController>();
final sync = context.watch<SyncStatusController>();
final isSelected = _selectedIds.contains(item.id);
final isMedia =
(item.type == NextcloudItemType.image ||
item.type == NextcloudItemType.video) &&
item.previewUrl != null;
final picking = !_offline && pick.isPicking;
// Offline reads the image straight from the local mirror; videos have
// no local thumbnail (that would need a frame-extraction plugin), so
// they fall through to the plain icon card there.
final isMedia = _offline
? item.type == NextcloudItemType.image
: (item.type == NextcloudItemType.image ||
item.type == NextcloudItemType.video) &&
item.previewUrl != null;
return Material(
color: Theme.of(context).colorScheme.surfaceContainerLow,
@@ -1126,17 +1093,17 @@ class _FilesViewState extends State<FilesView>
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () {
if (pick.isPicking) {
if (picking) {
_handlePickTap(context, item);
} else if (_isSelecting) {
_toggleSelection(item);
} else if (item.isFolder) {
files.navigateToFolder(item.path);
browser.navigateToFolder(item.path);
} else {
_openFile(context, item);
}
},
onLongPress: pick.isPicking && !pick.pickRequest!.allowMultiple
onLongPress: _offline || (picking && !pick.pickRequest!.allowMultiple)
? null
: () => _toggleSelection(item),
child: Stack(
@@ -1148,92 +1115,36 @@ class _FilesViewState extends State<FilesView>
? _buildMediaGridContent(context, item)
: _buildPlainGridContent(context, item),
),
Positioned(
right: 6,
bottom: 6,
child: SyncStatusBadge(status: sync.syncStatusFor(item)),
),
if (!_offline)
Positioned(
right: 6,
bottom: 6,
child: SyncStatusBadge(status: sync.syncStatusFor(item)),
),
],
),
),
);
}
/// Grid content for images/videos: the actual preview fills the whole
/// card as a background, with the name/size legible over a bottom scrim
/// — matching a Google Photos-style grid instead of a small icon badge.
/// Grid content for images/videos - see [MediaGridTile].
Widget _buildMediaGridContent(BuildContext context, NextcloudItem item) {
final session = context.watch<SessionController>();
final theme = Theme.of(context);
final localFile = _localFileFor(context, item);
return LayoutBuilder(
builder: (context, constraints) {
final cachePixels =
(constraints.maxWidth * MediaQuery.of(context).devicePixelRatio)
.round();
return Stack(
fit: StackFit.expand,
children: [
Image.network(
item.previewUrl!,
headers: session.service?.authHeaders,
fit: BoxFit.cover,
cacheWidth: cachePixels,
cacheHeight: cachePixels,
filterQuality: FilterQuality.low,
gaplessPlayback: true,
errorBuilder: (ctx, err, stack) =>
_buildPlainGridContent(context, item),
),
if (item.type == NextcloudItemType.video)
const Center(
child: Icon(
Icons.play_circle_fill_rounded,
color: Colors.white,
size: 36,
),
return MediaGridTile(
item: item,
imageBuilder: (cachePixels) => ResizeImage(
localFile != null
? FileImage(localFile)
: NetworkImage(
item.previewUrl!,
headers: session.service?.authHeaders,
),
Positioned(
left: 0,
right: 0,
bottom: 0,
child: Container(
padding: const EdgeInsets.fromLTRB(10, 20, 10, 8),
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.transparent, Colors.black87],
),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.titleSmall?.copyWith(
color: Colors.white,
fontWeight: FontWeight.w600,
fontSize: 12,
),
),
Text(
formatBytes(item.size),
style: theme.textTheme.bodySmall?.copyWith(
color: Colors.white70,
fontSize: 10,
),
),
],
),
),
),
],
);
},
width: cachePixels,
height: cachePixels,
),
fallbackBuilder: (ctx) => _buildPlainGridContent(ctx, item),
);
}
@@ -1287,6 +1198,21 @@ class _FilesViewState extends State<FilesView>
}
void _openFile(BuildContext context, NextcloudItem item) {
if (_offline) {
// Same in-app viewer (including swiping between the folder's media),
// just reading from disk instead of the server - see
// `FileViewerScreen.localPathResolver`'s doc comment.
final offline = context.read<OfflineController>();
Navigator.push(
context,
FileViewerScreen.route(
item: item,
siblings: offline.items,
localPathResolver: offline.localPathFor,
),
);
return;
}
final files = context.read<FilesController>();
Navigator.push(
context,
+12 -1
View File
@@ -14,7 +14,12 @@ import '../views/trash_view.dart';
Widget buildAppTabView(AppTab tab, ScrollController controller) {
switch (tab) {
case AppTab.files:
return FilesView(scrollController: controller);
// Keyed so the Files and Offline tabs (same widget type) never share
// State when the visible-tab list shifts positions in the IndexedStack.
return FilesView(
key: const ValueKey('files'),
scrollController: controller,
);
case AppTab.photos:
return PhotosView(scrollController: controller);
case AppTab.favorites:
@@ -27,5 +32,11 @@ Widget buildAppTabView(AppTab tab, ScrollController controller) {
return SharesView(scrollController: controller);
case AppTab.recent:
return RecentView(scrollController: controller);
case AppTab.offline:
return FilesView(
key: const ValueKey('offline'),
scrollController: controller,
offline: true,
);
}
}
+136
View File
@@ -0,0 +1,136 @@
import 'package:flutter/material.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:provider/provider.dart';
import '../providers/files_controller.dart';
import 'segmented_icon_toggle.dart';
import 'sort_menu_button.dart';
/// The Files tab's sort/hidden/scope/type-filter/view-mode controls row,
/// shared with the Offline tab so both read and write the exact same
/// [FilesController] prefs. [folderPath] picks which folder's sort applies
/// (the Files tab's current folder, or the folder being browsed offline).
/// [showStorageScope] is off for Offline - a local mirror has no
/// cloud/external distinction.
class FilesControlsRow extends StatelessWidget {
final String folderPath;
final bool showStorageScope;
final ScrollController? scrollController;
const FilesControlsRow({
super.key,
required this.folderPath,
this.showStorageScope = true,
this.scrollController,
});
@override
Widget build(BuildContext context) {
final files = context.watch<FilesController>();
return SizedBox(
height: 44,
child: SingleChildScrollView(
controller: scrollController,
scrollDirection: Axis.horizontal,
child: Row(
children: [
IconButton(
icon: Icon(
files.sortAscendingFor(folderPath)
? Icons.arrow_upward_rounded
: Icons.arrow_downward_rounded,
size: 20,
),
visualDensity: VisualDensity.compact,
tooltip: files.sortAscendingFor(folderPath)
? 'Ascending'
: 'Descending',
onPressed: () => files.toggleSortOrderFor(folderPath),
),
// A plain width, not Expanded - this row scrolls horizontally,
// which gives every control unbounded width to lay out in, so a
// flex child would throw.
SizedBox(
width: 130,
child: SortMenuButton(
field: files.sortFieldFor(folderPath),
onChanged: (field) => files.setSortFieldFor(folderPath, field),
),
),
ToggleIconButton(
icon: files.showHiddenFiles
? Icons.visibility_rounded
: Icons.visibility_off_rounded,
isSelected: files.showHiddenFiles,
onTap: () => files.toggleShowHiddenFiles(),
tooltip: 'Show hidden files',
),
const SizedBox(width: 4),
if (showStorageScope) ...[
SegmentedIconGroup(
children: [
ToggleIconButton(
icon: Symbols.circles_rounded,
isSelected: files.storageScope == StorageScope.cloud,
onTap: () => files.setStorageScope(StorageScope.cloud),
tooltip: 'Cloud storage',
),
ToggleIconButton(
icon: Symbols.hard_drive_rounded,
isSelected: files.storageScope == StorageScope.external,
onTap: () => files.setStorageScope(StorageScope.external),
tooltip: 'External storage',
),
],
),
const SizedBox(width: 8),
],
SegmentedIconGroup(
children: [
ToggleIconButton(
icon: Icons.select_all_rounded,
isSelected: files.filesTypeFilter == FilesTypeFilter.all,
onTap: () => files.setFilesTypeFilter(FilesTypeFilter.all),
tooltip: 'Files & folders',
),
ToggleIconButton(
icon: Icons.insert_drive_file_outlined,
isSelected:
files.filesTypeFilter == FilesTypeFilter.filesOnly,
onTap: () =>
files.setFilesTypeFilter(FilesTypeFilter.filesOnly),
tooltip: 'Files only',
),
ToggleIconButton(
icon: Icons.folder_outlined,
isSelected:
files.filesTypeFilter == FilesTypeFilter.foldersOnly,
onTap: () =>
files.setFilesTypeFilter(FilesTypeFilter.foldersOnly),
tooltip: 'Folders only',
),
],
),
const SizedBox(width: 8),
SegmentedIconGroup(
children: [
ToggleIconButton(
icon: Icons.view_list_rounded,
isSelected: !files.isGridView,
onTap: () => files.setGridView(false),
tooltip: 'List view',
),
ToggleIconButton(
icon: Icons.grid_view_rounded,
isSelected: files.isGridView,
onTap: () => files.setGridView(true),
tooltip: 'Grid view',
),
],
),
],
),
),
);
}
}
+20 -6
View File
@@ -1,3 +1,4 @@
import 'dart:io';
import 'package:flutter/material.dart';
import '../models/nextcloud_item.dart';
import '../services/nextcloud_service.dart';
@@ -56,10 +57,16 @@ class ItemThumbnail extends StatelessWidget {
final double borderRadius;
final double iconSize;
/// The on-device copy of [item] (the Offline tab's synced mirror) - when
/// set, images render from this file instead of a server preview, so
/// thumbnails work with no connection.
final File? localFile;
const ItemThumbnail({
super.key,
required this.item,
required this.service,
this.localFile,
required this.size,
required this.borderRadius,
required this.iconSize,
@@ -71,6 +78,7 @@ class ItemThumbnail extends StatelessWidget {
final isMedia =
item.type == NextcloudItemType.image ||
item.type == NextcloudItemType.video;
final useLocal = item.type == NextcloudItemType.image && localFile != null;
// Decode straight to the size this thumbnail is actually painted at —
// the server hands back a 500x500 preview regardless, and decoding that
// in full for a ~40dp tile (times however many are on screen while
@@ -86,16 +94,22 @@ class ItemThumbnail extends StatelessWidget {
color: iconColor.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(borderRadius),
),
child: isMedia && item.previewUrl != null
child: useLocal || (isMedia && item.previewUrl != null)
? Stack(
fit: StackFit.expand,
children: [
Image.network(
item.previewUrl!,
headers: service?.authHeaders,
Image(
image: ResizeImage(
useLocal
? FileImage(localFile!) as ImageProvider
: NetworkImage(
item.previewUrl!,
headers: service?.authHeaders,
),
width: cachePixels,
height: cachePixels,
),
fit: BoxFit.cover,
cacheWidth: cachePixels,
cacheHeight: cachePixels,
filterQuality: FilterQuality.low,
gaplessPlayback: true,
loadingBuilder: (context, child, progress) {
@@ -0,0 +1,108 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/sync_status_controller.dart';
/// The configured sync targets (folders/files) with a "stop syncing"
/// action per target - what used to be Settings' Device Sync card's own
/// inline list, moved into a sheet here so the main Offline view can look
/// like a plain Files-style browser instead of always showing this
/// management UI up top.
class ManageSyncedFoldersSheet extends StatelessWidget {
final SyncStatusController sync;
const ManageSyncedFoldersSheet({super.key, required this.sync});
static void show(BuildContext context) {
final sync = context.read<SyncStatusController>();
showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Theme.of(context).colorScheme.surfaceContainerHigh,
showDragHandle: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(28)),
),
builder: (sheetContext) => ManageSyncedFoldersSheet(sync: sync),
);
}
void _remove(BuildContext context, String path) {
sync.removeSyncedPath(path);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Removed from device sync'),
behavior: SnackBarBehavior.floating,
),
);
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: sync,
builder: (context, _) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final everything = sync.syncEverything;
final targets = sync.syncedPaths;
return SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 4, 20, 20),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Synced to this device',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 12),
if (everything)
Text(
'Every folder in this account is being synced to this '
'device.',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
)
else if (targets.isEmpty)
Text(
'Nothing synced yet - select a folder or file in Files '
'and use "Sync to device" to mirror it here for offline '
'access.',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
)
else
Flexible(
child: ListView.separated(
shrinkWrap: true,
itemCount: targets.length,
separatorBuilder: (_, _) => const Divider(height: 1),
itemBuilder: (context, index) {
final target = targets[index];
return ListTile(
contentPadding: EdgeInsets.zero,
leading: const Icon(Icons.sync_rounded),
title: Text(target),
trailing: IconButton(
icon: const Icon(Icons.close_rounded),
tooltip: 'Stop syncing',
onPressed: () => _remove(context, target),
),
);
},
),
),
],
),
),
);
},
);
}
}
+98
View File
@@ -0,0 +1,98 @@
import 'package:flutter/material.dart';
import '../models/nextcloud_item.dart';
import 'synced_header_scaffold.dart' show formatBytes;
/// Grid content for an image/video: the actual preview fills the whole card
/// as a background, with the name/size legible over a bottom scrim -
/// matching a Google Photos-style grid instead of a small icon badge.
/// Shared by the Files and Offline tabs; they differ only in where the
/// pixels come from ([imageBuilder] - a server preview vs. the local
/// mirror file) and what to show if that fails ([fallbackBuilder]).
class MediaGridTile extends StatelessWidget {
final NextcloudItem item;
/// Given the pixel width to decode at, returns the image to paint.
/// Decoding straight to the painted size (rather than the full 500x500
/// server preview / full-resolution local file) avoids a real source of
/// scrolling jank.
final ImageProvider Function(int cachePixels) imageBuilder;
final WidgetBuilder fallbackBuilder;
const MediaGridTile({
super.key,
required this.item,
required this.imageBuilder,
required this.fallbackBuilder,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return LayoutBuilder(
builder: (context, constraints) {
final cachePixels =
(constraints.maxWidth * MediaQuery.of(context).devicePixelRatio)
.round();
return Stack(
fit: StackFit.expand,
children: [
Image(
image: imageBuilder(cachePixels),
fit: BoxFit.cover,
filterQuality: FilterQuality.low,
gaplessPlayback: true,
errorBuilder: (ctx, err, stack) => fallbackBuilder(ctx),
),
if (item.type == NextcloudItemType.video)
const Center(
child: Icon(
Icons.play_circle_fill_rounded,
color: Colors.white,
size: 36,
),
),
Positioned(
left: 0,
right: 0,
bottom: 0,
child: Container(
padding: const EdgeInsets.fromLTRB(10, 20, 10, 8),
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.transparent, Colors.black87],
),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
item.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.titleSmall?.copyWith(
color: Colors.white,
fontWeight: FontWeight.w600,
fontSize: 12,
),
),
Text(
formatBytes(item.size),
style: theme.textTheme.bodySmall?.copyWith(
color: Colors.white70,
fontSize: 10,
),
),
],
),
),
),
],
);
},
);
}
}
+6 -2
View File
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/app_tab.dart';
import '../providers/connectivity_controller.dart';
import '../providers/pick_controller.dart';
import '../providers/settings_controller.dart';
import 'app_tab_view_builder.dart';
@@ -16,13 +17,16 @@ class MoreTabsButton extends StatelessWidget {
Widget build(BuildContext context) {
final pick = context.watch<PickController>();
final settings = context.watch<SettingsController>();
final connectivity = context.watch<ConnectivityController>();
// 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 (pick.isPicking) return const SizedBox.shrink();
// just disabling. Same idea while offline: every hidden tab needs a
// network request to show anything useful, so there's nothing this
// button could usefully open.
if (pick.isPicking || connectivity.isOffline) return const SizedBox.shrink();
return PopupMenuButton<AppTab>(
icon: const Icon(Icons.apps_rounded),
+31 -20
View File
@@ -1,8 +1,10 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:provider/provider.dart';
import '../models/nextcloud_item.dart';
import '../models/sync_status.dart';
import '../providers/connectivity_controller.dart';
import '../providers/files_controller.dart';
import '../providers/session_controller.dart';
import '../providers/sync_status_controller.dart';
@@ -11,8 +13,12 @@ import '../providers/sync_status_controller.dart';
/// status (see `SyncStatusController.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) {
/// `_SyncedHeaderScaffoldState`'s `_isRefreshing`). [isOffline] takes
/// priority over everything else - with no connection at all, "nothing
/// configured to sync" and "can't sync right now" are different facts,
/// and the latter is the one actually worth surfacing.
(IconData, String) _syncHeaderDisplay(SyncHeaderStatus status, bool isOffline) {
if (isOffline) return (Icons.cloud_off_rounded, 'Offline');
return switch (status) {
SyncHeaderStatus.off => (Icons.cloud_off_rounded, 'Sync off'),
SyncHeaderStatus.syncing => (Icons.cloud_sync_rounded, 'Syncing…'),
@@ -21,25 +27,25 @@ import '../providers/sync_status_controller.dart';
};
}
/// The expanded sync panel's headline - actual folder/item counts instead
/// of just repeating the compact chip's generic "Synced" label, which reads
/// as true even when nothing has actually finished syncing yet (e.g. right
/// after adding a folder, before the first pass completes).
String _syncSummary(SyncStatusController sync) {
/// The expanded sync panel's headline - counts of what's actually
/// *configured* to sync (folders/files) instead of just repeating the
/// compact chip's generic "Synced" label. Deliberately doesn't add up the
/// individual files inside a synced folder ("1 folder synced", not "1
/// folder & 4 items synced") - once a folder's synced, its file count is
/// an implementation detail, not something the user picked.
String _syncSummary(SyncStatusController sync, bool isOffline) {
if (isOffline) return 'Offline';
if (sync.syncConflicts.isNotEmpty) return 'Sync issue';
if (sync.isSyncingNow) return 'Syncing…';
final items = sync.syncedItemCount;
if (sync.syncEverything) {
return items > 0 ? '$items item${items == 1 ? '' : 's'} synced' : 'Sync off';
}
if (sync.syncEverything) return 'Whole account synced';
final folders = sync.syncedFolderCount;
if (folders == 0) return 'Sync off';
final folderWord = folders == 1 ? 'folder' : 'folders';
if (items == 0) {
return '$folders $folderWord selected — nothing synced yet';
}
final itemWord = items == 1 ? 'item' : 'items';
return '$folders $folderWord & $items $itemWord synced';
final files = sync.syncedPaths.length - folders;
if (folders == 0 && files == 0) return 'Sync off';
final parts = <String>[
if (folders > 0) '$folders folder${folders == 1 ? '' : 's'}',
if (files > 0) '$files file${files == 1 ? '' : 's'}',
];
return '${parts.join(' & ')} synced';
}
String formatBytes(int bytes) {
@@ -143,6 +149,9 @@ class _SyncedHeaderScaffoldState extends State<SyncedHeaderScaffold> {
final refresh =
widget.onRefresh ?? context.read<FilesController>().refreshData;
setState(() => _isRefreshing = true);
// A deliberate pull also checks synced folders/files for server changes
// - the "sync" header is exactly where you'd expect that to happen.
unawaited(context.read<SyncStatusController>().syncOnPull());
refresh().whenComplete(() {
if (mounted) setState(() => _isRefreshing = false);
});
@@ -318,7 +327,8 @@ class _SyncStatusChip extends StatelessWidget {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final status = context.watch<SyncStatusController>().syncHeaderStatus;
final (icon, label) = _syncHeaderDisplay(status);
final isOffline = context.watch<ConnectivityController>().isOffline;
final (icon, label) = _syncHeaderDisplay(status, isOffline);
final iconColor = status == SyncHeaderStatus.alert
? colorScheme.error
: colorScheme.primary;
@@ -372,6 +382,7 @@ class _SyncedStretchPanel extends StatelessWidget {
final quota = context.watch<FilesController>().quota;
final serverUrl = context.watch<SessionController>().serverUrl;
final syncStatus = context.watch<SyncStatusController>();
final isOffline = context.watch<ConnectivityController>().isOffline;
return LayoutBuilder(
builder: (context, constraints) {
@@ -382,7 +393,7 @@ class _SyncedStretchPanel extends StatelessWidget {
// Reaches 1.0 (title fully hidden) at 50px of pull — comfortably
// before the 100px lock threshold.
final progress = forceVisible ? 1.0 : (stretch / 50).clamp(0.0, 1.0);
final statusLabel = _syncSummary(syncStatus);
final statusLabel = _syncSummary(syncStatus, isOffline);
final conflicts = syncStatus.syncConflicts;
return Stack(