Dedupe native transfer/notification code and split ServerProvider into focused controllers
Build APK / build (push) Successful in 5m20s

Consolidates duplicated GET/PUT/notification-channel logic across
DownloadService/ShareUploadService/SyncEngine into shared Kotlin helpers,
gives upload/download real batch queueing instead of dropping a second
concurrent batch, and dedupes repeated Dart channel-argument boilerplate.

Replaces the 2300+ line ServerProvider god object with ten focused
ChangeNotifiers (SessionController, SettingsController, FilesController,
PhotosController, FavoritesController, TrashController, SharesController,
RecentController, SyncStatusController, PickController) plus ItemOperations,
a plain coordinator for cross-domain item mutations - fixing the coupling
where device-sync status, per-tab data, and global UI prefs all lived in
one object. Updates every view/widget call site accordingly and refreshes
the architecture/server/standards/styling docs to match.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-20 10:04:12 -04:00
co-authored by Claude Sonnet 5
parent faaec5365f
commit ff5f04e9a1
58 changed files with 4158 additions and 3594 deletions
+110
View File
@@ -0,0 +1,110 @@
import 'package:flutter/material.dart';
import '../models/nextcloud_item.dart';
import 'files_controller.dart';
import 'session_controller.dart';
/// The Favorites tab: every favorited item across the whole account (not
/// scoped to any one folder - a favorited item several folders deep still
/// shows up regardless of whether its parent folders are themselves
/// favorited, which is exactly why this is its own account-wide fetch
/// rather than a filter toggle over whatever folder Files happens to be
/// browsing - see `server.md`'s Favorites section for the full history of
/// why a filter-toggle approach was tried and reverted). Depends on
/// [FilesController] to reuse its exact
/// display prefs (hidden/type-filter/sort/storage-scope) via
/// [FilesController.applyFilesDisplayPrefs] - deliberately shared rather
/// than a second parallel settings dimension.
class FavoritesController extends ChangeNotifier {
final SessionController session;
final FilesController files;
List<NextcloudItem> _allFavorites = [];
bool _isLoading = false;
String? _errorMessage;
// True once fetchAll has run at least once (i.e. the Favorites tab has
// been visited) - delete/rename/move/copy re-sync afterward, but only
// when it's actually been loaded, so those actions don't pay for an
// extra network round-trip on every Files/Photos edit for an account
// that's never opened the Favorites tab this session.
bool _everFetched = false;
FavoritesController(this.session, this.files) {
session.addAccountClearedListener(_onAccountCleared);
}
bool get isLoading => _isLoading;
String? get errorMessage => _errorMessage;
/// The Favorites tab's content, run through the exact same hidden/type-
/// filter/sort/storage-scope display prefs as the Files tab. No
/// favorites filter needed here - the source list is already
/// all-favorites.
List<NextcloudItem> get items => files.applyFilesDisplayPrefs(_allFavorites);
void _onAccountCleared() {
_allFavorites = [];
_isLoading = false;
_errorMessage = null;
_everFetched = false;
notifyListeners();
}
/// Loads every favorited item across the whole account for the Favorites
/// tab.
Future<void> fetchAll() async {
final service = session.service;
if (!session.isLoggedIn || service == null) return;
final gen = session.sessionGeneration;
_everFetched = true;
_isLoading = true;
_errorMessage = null;
notifyListeners();
try {
final favorites = await service.fetchFavorites();
if (gen != session.sessionGeneration) return;
_allFavorites = favorites;
debugPrint('[FavoritesController] Loaded ${_allFavorites.length} favorites');
} catch (e) {
if (gen != session.sessionGeneration) return;
debugPrint('[FavoritesController] Error fetching favorites: $e');
_errorMessage = e.toString().replaceAll('Exception: ', '');
} finally {
if (gen == session.sessionGeneration) {
_isLoading = false;
notifyListeners();
}
}
}
/// Re-syncs [_allFavorites] after a delete/rename/move/copy elsewhere in
/// the app - those operations don't know how to patch this list in place
/// (a move changes an item's path; WebDAV COPY's handling of custom
/// properties like `oc:favorite` isn't reliable enough to assume the
/// copy is still favorited), so this just refetches - but only if
/// Favorites has actually been loaded this session. Called by
/// `ItemOperations` after delete/rename/move/copy.
Future<void> syncIfLoaded() {
return _everFetched ? fetchAll() : Future.value();
}
/// Patches a favorite-toggle result into [_allFavorites] in place (added
/// if newly favorited, removed if un-favorited, updated otherwise) -
/// called by `ItemOperations.toggleItemFavorite` after a successful
/// server call. Cheap enough not to need a full refetch, unlike
/// [syncIfLoaded].
void applyFavoriteToggle(NextcloudItem updated) {
final index = _allFavorites.indexWhere((i) => i.id == updated.id);
if (updated.isFavorite) {
if (index != -1) {
_allFavorites[index] = updated;
} else {
_allFavorites = [..._allFavorites, updated];
}
} else if (index != -1) {
_allFavorites = [..._allFavorites]..removeAt(index);
}
notifyListeners();
}
}
+557
View File
@@ -0,0 +1,557 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/nextcloud_item.dart';
import 'session_controller.dart';
enum FileSortField { name, dateCreated, dateModified, size }
/// Which storage a listing shows — always exactly one, like the list/grid
/// view toggle, not an optional filter. Shared across Files/Photos/
/// Favorites (see [applyCommonFilters]'s doc comment).
enum StorageScope { cloud, external }
/// The Files tab's files/folders/both filter — independent of and applied
/// after [StorageScope]/favorites/hidden filtering.
enum FilesTypeFilter { all, filesOnly, foldersOnly }
/// How aggressively the Files tab's folder listings (not thumbnails/file
/// 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.
never,
/// A listing is reused until it's older than [FilesController.
/// cacheIntervalMinutes]; a timer also proactively refreshes the current
/// folder on that same interval while the app is in the foreground.
interval,
/// A listing is reused indefinitely until the user pulls to refresh.
manual,
}
/// One cached folder listing and when it was fetched.
class _CachedDirectory {
final List<NextcloudItem> items;
final DateTime fetchedAt;
const _CachedDirectory(this.items, this.fetchedAt);
}
/// The Files tab: current folder/browsing state, display prefs (grid/list,
/// hidden, type filter, storage scope, sort), the directory-listing cache,
/// and - piggybacked onto the same fetch cycle as the original single
/// provider did - account quota and the Activity tab's feed (neither is
/// really "Files" data, but both were always fetched alongside the current
/// folder's listing, not independently; preserved here as-is rather than
/// invented a home for them, since untangling that wasn't asked for). Also
/// the shared [storageScope]/[applyCommonFilters]/[applyFilesDisplayPrefs]
/// logic Photos/Favorites both reuse - see their own controllers' doc
/// comments for why they depend on this one.
///
/// Split out of the former single `ServerProvider` god object.
class FilesController extends ChangeNotifier with WidgetsBindingObserver {
final SessionController session;
static const _prefGridView = 'ui_grid_view';
static const _prefStorageScope = 'ui_storage_scope';
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';
String _currentFolderPath = '/';
List<String> _pathStack = ['/'];
bool _isGridView = false;
StorageScope _storageScope = StorageScope.cloud;
FilesTypeFilter _filesTypeFilter = FilesTypeFilter.all;
bool _showHiddenFiles = false;
final Map<String, FileSortField> _folderSortField = {};
final Map<String, bool> _folderSortAscending = {};
CachePolicy _cachePolicy = CachePolicy.never;
int _cacheIntervalMinutes = 5;
final Map<String, _CachedDirectory> _directoryCache = {};
Timer? _cacheRefreshTimer;
List<NextcloudItem> _items = [];
NextcloudUserQuota? _quota;
List<NextcloudActivity> _activities = [];
bool _isLoading = false;
String? _errorMessage;
FilesController(this.session) {
WidgetsBinding.instance.addObserver(this);
session.addAccountClearedListener(_onAccountCleared);
session.addAccountActivatedListener(_onAccountActivated);
}
// Getters
String get currentFolderPath => _currentFolderPath;
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;
CachePolicy get cachePolicy => _cachePolicy;
int get cacheIntervalMinutes => _cacheIntervalMinutes;
bool get isLoading => _isLoading;
String? get errorMessage => _errorMessage;
NextcloudUserQuota? get quota => _quota;
List<NextcloudActivity> get activities => _activities;
List<NextcloudItem> get items => applyFilesDisplayPrefs(_items);
int _compareItems(NextcloudItem a, NextcloudItem b, FileSortField field) {
switch (field) {
case FileSortField.name:
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
case FileSortField.dateCreated:
return a.dateCreated.compareTo(b.dateCreated);
case FileSortField.dateModified:
return a.lastModified.compareTo(b.lastModified);
case FileSortField.size:
return a.size.compareTo(b.size);
}
}
/// True if [item] or any ancestor folder in its path is a dotfile/dotfolder.
bool _isHiddenItem(NextcloudItem item) {
return item.path
.split('/')
.where((segment) => segment.isNotEmpty)
.any((segment) => segment.startsWith('.'));
}
/// Applies the shared favorites-only/hidden-files/storage-scope toggles -
/// shared by Files' own [items], Photos' `photoItems` (its own favorites-
/// only/hidden toggles, but [storageScope] here), and Favorites'
/// `favoriteItems` (via [applyFilesDisplayPrefs]).
List<NextcloudItem> applyCommonFilters(
List<NextcloudItem> source, {
required bool showFavoritesOnly,
required bool showHidden,
}) {
var filtered = source;
if (showFavoritesOnly) {
filtered = filtered.where((item) => item.isFavorite).toList();
}
if (!showHidden) {
filtered = filtered.where((item) => !_isHiddenItem(item)).toList();
}
filtered = filtered
.where(
(item) => _storageScope == StorageScope.external
? item.isExternalStorage
: !item.isExternalStorage,
)
.toList();
return filtered;
}
/// Applies the Files tab's current sort/filter display prefs (hidden,
/// type filter, storage scope, sort field/direction) to an arbitrary raw
/// item list - factored out of the [items] getter so both the Favorites
/// tab and the Move/Copy destination picker (which fetches its own
/// 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) {
var filtered = applyCommonFilters(
rawItems,
// Files itself doesn't filter by favorite - that's the dedicated
// Favorites tab's job.
showFavoritesOnly: false,
showHidden: _showHiddenFiles,
);
switch (_filesTypeFilter) {
case FilesTypeFilter.all:
break;
case FilesTypeFilter.filesOnly:
filtered = filtered.where((i) => !i.isFolder).toList();
case FilesTypeFilter.foldersOnly:
filtered = filtered.where((i) => i.isFolder).toList();
}
final field = filesSortField;
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
? [...folders, ...files]
: [...folders.reversed, ...files.reversed];
}
void _onAccountCleared() {
_cacheRefreshTimer?.cancel();
_directoryCache.clear();
_folderSortField.clear();
_folderSortAscending.clear();
_items = [];
_quota = null;
_activities = [];
_currentFolderPath = '/';
_pathStack = ['/'];
_isGridView = false;
_storageScope = StorageScope.cloud;
_filesTypeFilter = FilesTypeFilter.all;
_showHiddenFiles = false;
_cachePolicy = CachePolicy.never;
_cacheIntervalMinutes = 5;
_isLoading = false;
_errorMessage = 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);
_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 ascending = value['ascending'] as bool?;
if (ascending != null) _folderSortAscending[entry.key] = ascending;
}
} 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();
}
_startCacheRefreshTimerIfNeeded();
await refreshData();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// Only relevant under CachePolicy.interval.
if (state == AppLifecycleState.resumed) {
_startCacheRefreshTimerIfNeeded();
} else if (state == AppLifecycleState.paused) {
_cacheRefreshTimer?.cancel();
}
}
void _startCacheRefreshTimerIfNeeded() {
_cacheRefreshTimer?.cancel();
if (_cachePolicy != CachePolicy.interval || !session.isLoggedIn) return;
_cacheRefreshTimer = Timer.periodic(
Duration(minutes: _cacheIntervalMinutes),
(_) => refreshData(),
);
}
bool _isCacheFresh(String path) {
if (_cachePolicy == CachePolicy.never) return false;
final cached = _directoryCache[path];
if (cached == null) return false;
if (_cachePolicy == CachePolicy.manual) return true;
return DateTime.now().difference(cached.fetchedAt) <
Duration(minutes: _cacheIntervalMinutes);
}
Future<void> refreshData() async {
final service = session.service;
if (!session.isLoggedIn || service == null) {
debugPrint(
'[FilesController] refreshData skipped: isLoggedIn=${session.isLoggedIn}, service=${service != null}',
);
return;
}
// Captured so a response landing after an account switch mid-flight
// 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;
_isLoading = true;
_errorMessage = null;
notifyListeners();
debugPrint('[FilesController] Refreshing data for path: $_currentFolderPath');
try {
final items = await service.fetchDirectory(_currentFolderPath);
if (gen != session.sessionGeneration) return;
_items = items;
_directoryCache[_currentFolderPath] = _CachedDirectory(
_items,
DateTime.now(),
);
debugPrint(
'[FilesController] Loaded ${_items.length} items for $_currentFolderPath',
);
try {
_quota = await service.fetchUserQuota();
} catch (e) {
debugPrint('[FilesController] Quota fetch warning: $e');
}
try {
_activities = await service.fetchActivities();
} catch (e) {
debugPrint('[FilesController] Activity fetch warning: $e');
}
} catch (e) {
if (gen != session.sessionGeneration) return;
debugPrint('[FilesController] Error fetching directory: $e');
_errorMessage = e.toString().replaceAll('Exception: ', '');
} finally {
if (gen == session.sessionGeneration) {
_isLoading = false;
notifyListeners();
}
}
}
Future<List<NextcloudItem>> searchFiles(String query) async {
final service = session.service;
if (service == null) return [];
return service.searchFiles(query);
}
Future<void> navigateToFolder(String path) async {
_pathStack.add(path);
await _navigateTo(path);
}
Future<void> navigateUp() async {
if (_pathStack.length > 1) {
_pathStack.removeLast();
await _navigateTo(_pathStack.last);
}
}
/// Jumps directly to an ancestor folder by its position in [pathStack]
/// (as tapped from a breadcrumb), trimming everything below it.
Future<void> navigateToPathIndex(int index) async {
if (index < 0 || index >= _pathStack.length - 1) return;
_pathStack = _pathStack.sublist(0, index + 1);
await _navigateTo(_pathStack.last);
}
/// Navigates directly to an arbitrary absolute folder path (e.g. from a
/// search result) - unlike [navigateToFolder], which assumes [path] is a
/// child of wherever the user is currently browsing and just appends it,
/// this rebuilds the whole breadcrumb trail from root so it's correct
/// regardless of where the user was before.
Future<void> navigateToAbsoluteFolder(String path) async {
final normalized = path.trim().replaceAll(RegExp(r'/+$'), '');
final segments = normalized.split('/').where((s) => s.isNotEmpty).toList();
final stack = <String>['/'];
var current = '';
for (final segment in segments) {
current = '$current/$segment';
stack.add(current);
}
_pathStack = stack;
await _navigateTo(stack.last);
}
/// Switches the current folder to [path], serving its listing straight
/// from the cache when that's still fresh (instant, no network call at
/// all) and only falling back to [refreshData] otherwise.
Future<void> _navigateTo(String path) async {
_currentFolderPath = path;
final cached = _directoryCache[path];
if (cached != null && _isCacheFresh(path)) {
debugPrint('[FilesController] Serving cached listing for $path');
_items = cached.items;
_errorMessage = null;
notifyListeners();
return;
}
await refreshData();
}
/// A destination-picker-only fetch: the current folder listing state
/// (`items`/`currentFolderPath`/`pathStack`/the directory cache) belongs
/// to whichever tab is actively browsing (Files), so the Move/Copy
/// destination picker deliberately doesn't touch any of it - it fetches
/// listings for its own local navigation state through this instead.
Future<List<NextcloudItem>> fetchFolderListing(String path) {
return session.service?.fetchDirectory(path) ?? Future.value([]);
}
void invalidateCache() => _directoryCache.clear();
/// Persists a per-account browsing pref under its `acct_<id>_`-namespaced
/// key. No-op if there's no active account (shouldn't normally happen -
/// these setters are only reachable from screens that require one).
void _persistAccountPref(
String baseKey,
void Function(SharedPreferences prefs, String key) write,
) {
final id = session.activeAccountId;
if (id == null) return;
session.prefsFuture.then(
(p) => write(p, session.accountStore.accountPrefKey(id, baseKey)),
);
}
void setGridView(bool value) {
if (_isGridView == value) return;
_isGridView = value;
notifyListeners();
_persistAccountPref(_prefGridView, (p, key) => p.setBool(key, value));
}
void setStorageScope(StorageScope scope) {
if (_storageScope == scope) return;
_storageScope = scope;
notifyListeners();
_persistAccountPref(
_prefStorageScope,
(p, key) => p.setString(key, scope.name),
);
}
void setFilesTypeFilter(FilesTypeFilter filter) {
if (_filesTypeFilter == filter) return;
_filesTypeFilter = filter;
notifyListeners();
_persistAccountPref(
_prefFilesTypeFilter,
(p, key) => p.setString(key, filter.name),
);
}
/// Only *enabling* hidden-files visibility is gated - hiding them again
/// never exposes anything, so that direction is always allowed instantly.
Future<void> toggleShowHiddenFiles() async {
if (!_showHiddenFiles) {
if (!await session.passGate(
session.lockHiddenFiles,
'Unlock to show hidden files',
)) {
return;
}
}
_showHiddenFiles = !_showHiddenFiles;
notifyListeners();
_persistAccountPref(
_prefShowHiddenFiles,
(p, key) => p.setBool(key, _showHiddenFiles),
);
}
void _persistFolderSort() {
final combined = <String, dynamic>{};
for (final path in {
..._folderSortField.keys,
..._folderSortAscending.keys,
}) {
combined[path] = {
'field': _folderSortField[path]?.name,
'ascending': _folderSortAscending[path],
};
}
_persistAccountPref(
_prefFolderSort,
(p, key) => p.setString(key, jsonEncode(combined)),
);
}
void setFilesSortField(FileSortField field) {
if (filesSortField == field) return;
_folderSortField[_currentFolderPath] = field;
notifyListeners();
_persistFolderSort();
}
void toggleFilesSortOrder() {
_folderSortAscending[_currentFolderPath] = !filesSortAscending;
notifyListeners();
_persistFolderSort();
}
void setCachePolicy(CachePolicy policy) {
if (_cachePolicy == policy) return;
_cachePolicy = policy;
notifyListeners();
_persistAccountPref(
_prefCachePolicy,
(p, key) => p.setString(key, policy.name),
);
_startCacheRefreshTimerIfNeeded();
}
void setCacheIntervalMinutes(int minutes) {
final clamped = minutes.clamp(1, 60);
if (_cacheIntervalMinutes == clamped) return;
_cacheIntervalMinutes = clamped;
notifyListeners();
_persistAccountPref(
_prefCacheIntervalMinutes,
(p, key) => p.setInt(key, clamped),
);
_startCacheRefreshTimerIfNeeded();
}
Future<bool> createFolder(String folderName) async {
final service = session.service;
if (service == null) return false;
final success = await service.createFolder(_currentFolderPath, folderName);
if (success) {
await refreshData();
}
return success;
}
/// Patches a favorite-toggle result into [items] in place (no refetch) -
/// called by `ItemOperations.toggleItemFavorite` after a successful
/// server call.
void applyFavoriteToggle(NextcloudItem updated) {
final index = _items.indexWhere((i) => i.id == updated.id);
if (index != -1) _items[index] = updated;
notifyListeners();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_cacheRefreshTimer?.cancel();
super.dispose();
}
}
+358
View File
@@ -0,0 +1,358 @@
import 'package:flutter/foundation.dart';
import '../models/move_copy_result.dart';
import '../models/nextcloud_file_version.dart';
import '../models/nextcloud_item.dart';
import '../models/nextcloud_share.dart';
import '../models/nextcloud_sharee.dart';
import 'favorites_controller.dart';
import 'files_controller.dart';
import 'photos_controller.dart';
import 'session_controller.dart';
/// The one place that knows how an item mutation (delete/rename/move/copy/
/// favorite-toggle/create-folder) ripples across Files/Photos/Favorites -
/// those three each own their own item list, but a mutation triggered from
/// *any* of them (see each call site in the views) needs to reconcile all
/// three, since e.g. a delete removes an item Photos might also be
/// showing. Deliberately holds direct references to the sibling
/// controllers (constructed once in `main.dart`, after they already exist)
/// rather than a generic event bus, so callers can still `await` a
/// mutation and know every affected list has already been reconciled by
/// the time it returns - exactly the same guarantee the single
/// `ServerProvider` god object gave for free before this was split out.
///
/// Also home to the file-details sheet's per-item pass-throughs (shares/
/// activity/versions) - stateless, no stored data, so they don't need a
/// controller of their own.
class ItemOperations {
final SessionController session;
final FilesController files;
final PhotosController photos;
final FavoritesController favorites;
const ItemOperations({
required this.session,
required this.files,
required this.photos,
required this.favorites,
});
Future<bool> deleteItem(String itemPath) async {
final service = session.service;
if (service == null) return false;
final success = await service.deleteItem(itemPath);
if (success) {
photos.applyDelete(itemPath);
await files.refreshData();
await favorites.syncIfLoaded();
}
return success;
}
Future<bool> renameItem(NextcloudItem item, String newName) async {
final service = session.service;
if (service == null) return false;
final success = await service.renameItem(item.path, newName);
if (success) {
await files.refreshData();
await favorites.syncIfLoaded();
}
return success;
}
/// True if [destFolderPath] is [folderPath] itself or one of its own
/// descendants - moving/copying a folder into itself (or a subfolder of
/// itself) is nonsensical and rejected client-side rather than left to
/// the server to (maybe) reject.
bool _isSelfOrDescendant(String destFolderPath, String folderPath) {
final dest = destFolderPath.endsWith('/')
? destFolderPath
: '$destFolderPath/';
final folder = folderPath.endsWith('/') ? folderPath : '$folderPath/';
return dest == folder || dest.startsWith(folder);
}
Future<MoveCopyResult> _moveOrCopyItems(
List<NextcloudItem> items,
String destFolderPath, {
required bool copy,
}) async {
final service = session.service;
if (service == null || items.isEmpty) return const MoveCopyResult();
for (final item in items) {
if (item.isFolder && _isSelfOrDescendant(destFolderPath, item.path)) {
return const MoveCopyResult(
blockedReason:
"Can't move a folder into itself or one of its own subfolders",
);
}
}
var succeeded = 0;
var failed = 0;
final conflicts = <MoveCopyConflict>[];
for (final item in items) {
final status = copy
? await service.copyItem(item.path, destFolderPath)
: await service.moveItem(item.path, destFolderPath);
if (status == 201 || status == 204) {
succeeded++;
} else if (status == 412) {
conflicts.add(MoveCopyConflict(item));
} else {
failed++;
}
}
if (succeeded > 0) {
files.invalidateCache();
await files.refreshData();
await favorites.syncIfLoaded();
}
return MoveCopyResult(
succeeded: succeeded,
conflicts: conflicts,
failed: failed,
);
}
/// Moves every item in [items] into [destFolderPath], keeping each
/// item's own filename. Items that would collide with something already
/// there come back in [MoveCopyResult.conflicts] rather than failing
/// outright - resolve those with [resolveConflicts].
Future<MoveCopyResult> moveItems(
List<NextcloudItem> items,
String destFolderPath,
) {
return _moveOrCopyItems(items, destFolderPath, copy: false);
}
/// Same as [moveItems] but duplicates rather than relocates.
Future<MoveCopyResult> copyItems(
List<NextcloudItem> items,
String destFolderPath,
) {
return _moveOrCopyItems(items, destFolderPath, copy: true);
}
/// Finds the first `name (n).ext` not already in [existing] - `existing`
/// is mutated as names are claimed, so a batch of "keep both" resolutions
/// never picks the same generated name twice.
String _nextAvailableName(String name, Set<String> existing) {
if (!existing.contains(name)) return name;
final dotIndex = name.lastIndexOf('.');
final hasExtension = dotIndex > 0 && dotIndex < name.length - 1;
final base = hasExtension ? name.substring(0, dotIndex) : name;
final ext = hasExtension ? name.substring(dotIndex) : '';
var n = 2;
while (existing.contains('$base ($n)$ext')) {
n++;
}
return '$base ($n)$ext';
}
/// Resolves a previous [moveItems]/[copyItems] call's conflicts per
/// [choices] (keyed by `item.id`): overwrite the existing item, keep
/// both (renamed against a fresh listing of [destFolderPath] so two
/// "keep both" picks in the same batch can't collide with each other),
/// or skip (left untouched at the source).
Future<MoveCopyResult> resolveConflicts(
List<MoveCopyConflict> conflicts,
String destFolderPath, {
required bool copy,
required Map<String, ConflictChoice> choices,
}) async {
final service = session.service;
if (service == null || conflicts.isEmpty) return const MoveCopyResult();
final needsKeepBoth = conflicts.any(
(c) => choices[c.item.id] == ConflictChoice.keepBoth,
);
final existingNames = needsKeepBoth
? (await files.fetchFolderListing(destFolderPath))
.map((i) => i.name)
.toSet()
: <String>{};
var succeeded = 0;
var failed = 0;
for (final conflict in conflicts) {
final choice = choices[conflict.item.id] ?? ConflictChoice.skip;
if (choice == ConflictChoice.skip) continue;
final int status;
if (choice == ConflictChoice.overwrite) {
status = copy
? await service.copyItem(
conflict.item.path,
destFolderPath,
overwrite: true,
)
: await service.moveItem(
conflict.item.path,
destFolderPath,
overwrite: true,
);
} else {
final newName = _nextAvailableName(conflict.item.name, existingNames);
existingNames.add(newName);
status = copy
? await service.copyItem(
conflict.item.path,
destFolderPath,
newName: newName,
)
: await service.moveItem(
conflict.item.path,
destFolderPath,
newName: newName,
);
}
if (status == 201 || status == 204) {
succeeded++;
} else {
failed++;
}
}
if (succeeded > 0) {
files.invalidateCache();
await files.refreshData();
await favorites.syncIfLoaded();
}
return MoveCopyResult(succeeded: succeeded, failed: failed);
}
Future<void> toggleItemFavorite(NextcloudItem item) async {
final service = session.service;
if (service == null) return;
final success = await service.toggleFavorite(item.path, item.isFavorite);
if (success) {
final updated = item.copyWith(isFavorite: !item.isFavorite);
files.applyFavoriteToggle(updated);
photos.applyFavoriteToggle(updated);
favorites.applyFavoriteToggle(updated);
}
}
/// Creates a public link share for [item] and returns its URL, or null on
/// failure (server error, unsupported item, etc).
Future<String?> createShareLink(NextcloudItem item) async {
final service = session.service;
if (service == null) return null;
try {
return await service.createPublicShareLink(item.path);
} catch (e) {
debugPrint('[ItemOperations] createShareLink failed: $e');
return null;
}
}
// --- Details sheet: per-item sharing/activity/versions ---
//
// Thin pass-throughs (no stored state) - the data here is transient and
// scoped to whichever item's Details sheet happens to be open, so it
// lives in that sheet's own local widget state rather than a controller.
Future<List<NextcloudShare>> fetchItemShares(NextcloudItem item) async {
final service = session.service;
if (service == null) return [];
try {
return await service.fetchSharesForPath(item.path);
} catch (e) {
debugPrint('[ItemOperations] fetchItemShares failed: $e');
return [];
}
}
Future<List<NextcloudShare>> fetchInheritedShares(NextcloudItem item) async {
final service = session.service;
if (service == null) return [];
return service.fetchInheritedShares(item.path);
}
Future<List<NextcloudSharee>> searchSharees(String query) async {
final service = session.service;
if (service == null) return [];
try {
return await service.searchSharees(query);
} catch (e) {
debugPrint('[ItemOperations] searchSharees failed: $e');
return [];
}
}
Future<NextcloudShare?> createShare({
required String path,
required int shareType,
String? shareWith,
String? password,
DateTime? expireDate,
}) async {
final service = session.service;
if (service == null) return null;
try {
return await service.createShare(
path: path,
shareType: shareType,
shareWith: shareWith,
password: password,
expireDate: expireDate,
);
} catch (e) {
debugPrint('[ItemOperations] createShare failed: $e');
return null;
}
}
/// Deletes a share (from the file-details/Share sheet, not the Shares
/// tab itself - see `SharesController.deleteShare` for that one, which
/// additionally patches the tab's own list).
Future<bool> deleteShare(NextcloudShare share) async {
final service = session.service;
if (service == null) return false;
return service.deleteShare(share.id);
}
Future<List<NextcloudActivity>> fetchFileActivity(NextcloudItem item) async {
final service = session.service;
if (service == null) return [];
return service.fetchFileActivity(item.id);
}
Future<List<NextcloudFileVersion>> fetchFileVersions(
NextcloudItem item,
) async {
final service = session.service;
if (service == null) return [];
return service.fetchFileVersions(item.id);
}
Future<bool> restoreFileVersion(
NextcloudItem item,
String versionLabel,
) async {
final service = session.service;
if (service == null) return false;
try {
return await service.restoreFileVersion(item.id, versionLabel);
} catch (e) {
debugPrint('[ItemOperations] restoreFileVersion failed: $e');
return false;
}
}
Future<bool> downloadVersion(
NextcloudItem item,
String versionLabel,
String savePath,
) async {
final service = session.service;
if (service == null) return false;
try {
await service.downloadVersionToFile(item.id, versionLabel, savePath);
return true;
} catch (e) {
debugPrint('[ItemOperations] downloadVersion failed: $e');
return false;
}
}
}
+190
View File
@@ -0,0 +1,190 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/nextcloud_item.dart';
import 'files_controller.dart';
import 'session_controller.dart';
/// The Photos tab: every image/video across the whole account (not just
/// the currently browsed folder - see [fetchAllMedia]). Depends on
/// [FilesController] only for the shared [StorageScope] toggle and
/// [FilesController.applyCommonFilters] - Photos' own favorites-only/
/// hidden toggles are independent of Files', but the storage-scope split
/// (cloud vs external) is one shared setting across every tab.
class PhotosController extends ChangeNotifier {
final SessionController session;
final FilesController files;
static const _prefShowFavoritesOnlyPhotos = 'ui_show_favorites_only_photos';
static const _prefShowHiddenPhotos = 'ui_show_hidden_photos';
static const _prefSortField = 'ui_sort_field';
static const _prefSortAscending = 'ui_sort_ascending';
List<NextcloudItem> _allMedia = [];
bool _isLoading = false;
String? _errorMessage;
bool _showFavoritesOnly = false;
bool _showHidden = false;
FileSortField _sortField = FileSortField.name;
bool _sortAscending = true;
PhotosController(this.session, this.files) {
session.addAccountClearedListener(_onAccountCleared);
session.addAccountActivatedListener(_onAccountActivated);
}
bool get isLoading => _isLoading;
String? get errorMessage => _errorMessage;
bool get showFavoritesOnly => _showFavoritesOnly;
bool get showHidden => _showHidden;
FileSortField get sortField => _sortField;
bool get sortAscending => _sortAscending;
/// All images/videos across the whole account (not just the currently
/// browsed folder) — see [fetchAllMedia].
List<NextcloudItem> get items {
final media = _allMedia.where((i) => i.isMedia).toList();
final filtered = files.applyCommonFilters(
media,
showFavoritesOnly: _showFavoritesOnly,
showHidden: _showHidden,
)..sort((a, b) => _compare(a, b));
return _sortAscending ? filtered : filtered.reversed.toList();
}
int _compare(NextcloudItem a, NextcloudItem b) {
switch (_sortField) {
case FileSortField.name:
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
case FileSortField.dateCreated:
return a.dateCreated.compareTo(b.dateCreated);
case FileSortField.dateModified:
return a.lastModified.compareTo(b.lastModified);
case FileSortField.size:
return a.size.compareTo(b.size);
}
}
void _onAccountCleared() {
_allMedia = [];
_isLoading = false;
_errorMessage = 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);
_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();
}
unawaited(fetchAllMedia());
}
/// Loads every image/video across the whole account for the Photos tab.
Future<void> fetchAllMedia() async {
final service = session.service;
if (!session.isLoggedIn || service == null) return;
final gen = session.sessionGeneration;
_isLoading = true;
_errorMessage = null;
notifyListeners();
try {
final media = await service.fetchAllMedia();
if (gen != session.sessionGeneration) return;
_allMedia = media;
debugPrint('[PhotosController] Loaded ${_allMedia.length} media items');
} catch (e) {
if (gen != session.sessionGeneration) return;
debugPrint('[PhotosController] Error fetching all media: $e');
_errorMessage = e.toString().replaceAll('Exception: ', '');
} finally {
if (gen == session.sessionGeneration) {
_isLoading = false;
notifyListeners();
}
}
}
void _persistAccountPref(
String baseKey,
void Function(SharedPreferences prefs, String key) write,
) {
final id = session.activeAccountId;
if (id == null) return;
session.prefsFuture.then(
(p) => write(p, session.accountStore.accountPrefKey(id, baseKey)),
);
}
void toggleFavoritesFilter() {
_showFavoritesOnly = !_showFavoritesOnly;
notifyListeners();
_persistAccountPref(
_prefShowFavoritesOnlyPhotos,
(p, key) => p.setBool(key, _showFavoritesOnly),
);
}
Future<void> toggleShowHidden() async {
if (!_showHidden) {
if (!await session.passGate(
session.lockHiddenFiles,
'Unlock to show hidden files',
)) {
return;
}
}
_showHidden = !_showHidden;
notifyListeners();
_persistAccountPref(
_prefShowHiddenPhotos,
(p, key) => p.setBool(key, _showHidden),
);
}
void setSortField(FileSortField field) {
if (_sortField == field) return;
_sortField = field;
notifyListeners();
_persistAccountPref(_prefSortField, (p, key) => p.setString(key, field.name));
}
void toggleSortOrder() {
_sortAscending = !_sortAscending;
notifyListeners();
_persistAccountPref(
_prefSortAscending,
(p, key) => p.setBool(key, _sortAscending),
);
}
/// Removes an item by path (a delete elsewhere in the app) - called by
/// `ItemOperations.deleteItem` after a successful server call.
void applyDelete(String path) {
_allMedia = _allMedia.where((i) => i.path != path).toList();
notifyListeners();
}
/// Patches a favorite-toggle result into [items]' source list in place -
/// called by `ItemOperations.toggleItemFavorite` after a successful
/// server call.
void applyFavoriteToggle(NextcloudItem updated) {
final index = _allMedia.indexWhere((i) => i.id == updated.id);
if (index != -1) _allMedia[index] = updated;
notifyListeners();
}
}
+95
View File
@@ -0,0 +1,95 @@
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 '../models/pick_request.dart';
import '../services/pick_intent_service.dart';
import 'session_controller.dart';
/// State for Noo acting as *another* app's GET_CONTENT picker (see
/// `PickIntentService`/`MainActivity.kt`) - non-null [pickRequest] while
/// active, set at startup/onNewPickRequest in `MainShellView`, cleared
/// once the pick is confirmed or cancelled. Cross-cutting (both Files and
/// Photos need to know when picking mode is active and route taps through
/// [confirmPick] instead of their normal open/select behavior), so this is
/// its own small controller rather than living on any one tab's.
class PickController extends ChangeNotifier {
final SessionController session;
PickController(this.session);
PickRequest? _pickRequest;
bool _isDownloadingForPick = false;
PickRequest? get pickRequest => _pickRequest;
bool get isPicking => _pickRequest != null;
bool get isDownloadingForPick => _isDownloadingForPick;
/// Whether [item] can be handed back to the app that's currently picking
/// - always true for folders (still browsable), mime-filtered for files.
bool itemMatchesPickFilter(NextcloudItem item) {
if (item.isFolder) return true;
final request = _pickRequest;
return request == null || request.matches(item.mimeType);
}
/// Called once (from MainShellView) as soon as a pick request is known -
/// either the cold-start request or one that arrived via onNewPickRequest
/// while already running.
void setPickRequest(PickRequest request) {
_pickRequest = request;
notifyListeners();
}
/// Downloads each selected item to a scratch cache folder, then hands the
/// local paths back to the caller through PickIntentService, which closes
/// the picker Activity on success. Left in [pickRequest] (i.e. picking
/// mode stays visually active) if the download fails partway, so the user
/// can see the error and retry rather than the screen finishing under
/// them with nothing returned to the caller.
Future<bool> confirmPick(List<NextcloudItem> items) async {
final service = session.service;
if (_pickRequest == null || service == null || items.isEmpty) {
return false;
}
_isDownloadingForPick = true;
notifyListeners();
try {
final tempDir = await getTemporaryDirectory();
final pickDir = Directory(p.join(tempDir.path, 'picker'));
final localPaths = <String>[];
final mimeTypes = <String>[];
for (final item in items) {
// Each item gets its own subfolder (keyed by id, not smashed into
// the filename) so two different items can share a plain file
// name without colliding, while the file on disk - and therefore
// the display name the caller sees via the content:// Uri
// MainActivity.kt hands back - stays exactly `item.name`.
final itemDir = Directory(p.join(pickDir.path, item.id));
await itemDir.create(recursive: true);
final localPath = p.join(itemDir.path, item.name);
await service.downloadToFile(item.path, localPath);
localPaths.add(localPath);
mimeTypes.add(item.mimeType ?? 'application/octet-stream');
}
await PickIntentService.finishPick(localPaths, mimeTypes);
_pickRequest = null;
return true;
} catch (_) {
return false;
} finally {
_isDownloadingForPick = false;
notifyListeners();
}
}
/// Backs out of picking mode entirely, telling the caller nothing was
/// picked and closing the picker Activity.
Future<void> cancelPick() async {
if (_pickRequest == null) return;
_pickRequest = null;
notifyListeners();
await PickIntentService.cancelPick();
}
}
+59
View File
@@ -0,0 +1,59 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../models/nextcloud_item.dart';
import 'session_controller.dart';
/// The Recent Files tab. Kept separate from Files' own loading/error
/// state, likewise.
class RecentController extends ChangeNotifier {
final SessionController session;
List<NextcloudItem> _items = [];
bool _isLoading = false;
String? _errorMessage;
RecentController(this.session) {
session.addAccountClearedListener(_onAccountCleared);
session.addAccountActivatedListener(_onAccountActivated);
}
List<NextcloudItem> get items => _items;
bool get isLoading => _isLoading;
String? get errorMessage => _errorMessage;
void _onAccountCleared() {
_items = [];
_isLoading = false;
_errorMessage = null;
notifyListeners();
}
void _onAccountActivated() {
unawaited(fetchAll());
}
Future<void> fetchAll() async {
final service = session.service;
if (!session.isLoggedIn || service == null) return;
final gen = session.sessionGeneration;
_isLoading = true;
_errorMessage = null;
notifyListeners();
try {
final recent = await service.fetchRecentFiles();
if (gen != session.sessionGeneration) return;
_items = recent;
} catch (e) {
if (gen != session.sessionGeneration) return;
debugPrint('[RecentController] Error fetching recent files: $e');
_errorMessage = e.toString().replaceAll('Exception: ', '');
} finally {
if (gen == session.sessionGeneration) {
_isLoading = false;
notifyListeners();
}
}
}
}
File diff suppressed because it is too large Load Diff
+571
View File
@@ -0,0 +1,571 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import '../models/saved_account.dart';
import '../services/account_store.dart';
import '../services/app_lock_service.dart';
import '../services/login_flow_service.dart';
import '../services/nextcloud_service.dart';
import '../services/sync_service.dart';
enum LoginFlowStatus { idle, initiating, awaitingBrowser, error }
/// Owns everything about *which* account is live and whether it's actually
/// authenticated: the saved-accounts list, the active account, Login Flow
/// v2, the live [NextcloudService] instance, the session-generation guard
/// every other controller's fetches check against, and app lock. Doesn't
/// hold a single byte of any tab's *content* - that's what
/// [FilesController]/`PhotosController`/etc. own, each reacting to this
/// controller's account-activated/cleared signals (below) rather than this
/// controller reaching into them directly, since this is constructed
/// before them (they depend on it, not the other way around).
///
/// Split out of the former single `ServerProvider` god object - see
/// `.claude/context/architecture.md`'s "State management" section for the
/// full rationale.
class SessionController extends ChangeNotifier with WidgetsBindingObserver {
final Future<SharedPreferences> prefsFuture =
SharedPreferences.getInstance();
final AccountStore accountStore = AccountStore();
String _serverUrl = '';
String _username = '';
String _password = '';
bool _isLoggedIn = false;
bool _isLoading = false;
bool _isRestoringSession = true;
String? _errorMessage;
LoginFlowStatus _loginFlowStatus = LoginFlowStatus.idle;
Uri? _pendingLoginUrl;
Timer? _pollTimer;
Timer? _pollTimeoutTimer;
bool _addAccountFlowActive = false;
NextcloudService? _service;
List<SavedAccount> _accounts = [];
String? _activeAccountId;
// Bumped at the start of every account switch/removal/activation so an
// in-flight fetch from the account being left can recognize it's stale
// (by comparing against the generation it captured at its own start) and
// discard its result instead of writing it into the now-active account's
// state. Every other controller's fetch methods check this too.
int _sessionGeneration = 0;
bool _loginLockEnabled = false;
bool _lockAccountSwitching = false;
bool _lockHiddenFiles = false;
// Transient (never persisted) - starts locked whenever the app process
// starts, and re-locks on every backgrounding if a lock is configured;
// see didChangeAppLifecycleState.
bool _isUnlocked = false;
static const _prefLoginLockEnabled = 'ui_login_lock_enabled';
static const _prefLockAccountSwitching = 'ui_lock_account_switching';
static const _prefLockHiddenFiles = 'ui_lock_hidden_files';
// Sibling controllers (Files/Photos/Favorites/Trash/Shares/Recent/Sync)
// register here instead of this controller holding forward references to
// 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).
final List<VoidCallback> _accountClearedListeners = [];
final List<VoidCallback> _accountActivatedListeners = [];
void addAccountClearedListener(VoidCallback cb) =>
_accountClearedListeners.add(cb);
void addAccountActivatedListener(VoidCallback cb) =>
_accountActivatedListeners.add(cb);
void _notifyAccountCleared() {
for (final cb in _accountClearedListeners) {
cb();
}
}
void _notifyAccountActivated() {
for (final cb in _accountActivatedListeners) {
cb();
}
}
SessionController() {
WidgetsBinding.instance.addObserver(this);
_init();
}
Future<void> _init() async {
final prefs = await prefsFuture;
await accountStore.migrateLegacyIfNeeded(prefs);
_accounts = accountStore.loadAccounts(prefs);
_activeAccountId = accountStore.loadActiveAccountId(prefs);
await Future.wait([_loadPreferences(), _restoreSession()]);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// Re-locks the app on backgrounding when login lock is set up - a
// one-time unlock at cold start would give the feature no real
// security value, since the realistic threat is someone else picking
// up an already-running, unlocked phone.
if (state == AppLifecycleState.paused &&
_loginLockEnabled &&
_isUnlocked) {
_isUnlocked = false;
notifyListeners();
}
}
// Getters
String get serverUrl => _serverUrl;
String get username => _username;
bool get isLoggedIn => _isLoggedIn;
bool get isLoading => _isLoading;
bool get isRestoringSession => _isRestoringSession;
String? get errorMessage => _errorMessage;
int get sessionGeneration => _sessionGeneration;
NextcloudService? get service => _service;
LoginFlowStatus get loginFlowStatus => _loginFlowStatus;
Uri? get pendingLoginUrl => _pendingLoginUrl;
List<SavedAccount> get accounts => List.unmodifiable(_accounts);
String? get activeAccountId => _activeAccountId;
SavedAccount? get activeAccount =>
_accounts.where((a) => a.id == _activeAccountId).firstOrNull;
bool get isAddAccountFlow => _addAccountFlowActive;
bool get loginLockEnabled => _loginLockEnabled;
bool get lockAccountSwitching => _lockAccountSwitching;
bool get lockHiddenFiles => _lockHiddenFiles;
bool get needsUnlock => _loginLockEnabled && !_isUnlocked;
Future<void> _restoreSession() async {
try {
final id = _activeAccountId;
if (id == null) return;
final account = _accounts.where((a) => a.id == id).firstOrNull;
if (account == null) return;
final password = await accountStore.readPassword(id);
if (password == null) return;
await _applyCredentialsForAccount(account, password);
} catch (e) {
debugPrint('[SessionController] Session restore failed: $e');
} finally {
_isRestoringSession = false;
notifyListeners();
}
}
Future<void> _loadPreferences() async {
try {
final prefs = await prefsFuture;
_loginLockEnabled =
prefs.getBool(_prefLoginLockEnabled) ?? _loginLockEnabled;
_lockAccountSwitching =
prefs.getBool(_prefLockAccountSwitching) ?? _lockAccountSwitching;
_lockHiddenFiles =
prefs.getBool(_prefLockHiddenFiles) ?? _lockHiddenFiles;
notifyListeners();
} catch (e) {
debugPrint('[SessionController] Preference restore failed: $e');
}
}
/// 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.
Future<bool> _applyCredentialsForAccount(
SavedAccount account,
String appPassword,
) async {
final gen = _sessionGeneration;
_isLoading = true;
_errorMessage = null;
notifyListeners();
_serverUrl = account.serverUrl;
_username = account.username;
_password = appPassword;
_service = NextcloudService(
serverUrl: _serverUrl,
username: _username,
password: _password,
);
try {
final success = await _service!.testConnection();
if (gen != _sessionGeneration) return false;
if (success) {
_isLoggedIn = true;
_isLoading = false;
notifyListeners();
_notifyAccountActivated();
return true;
}
} 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.
if (_errorMessage?.contains('401') == true) {
await accountStore.deletePassword(account.id);
}
}
if (gen != _sessionGeneration) return false;
_isLoggedIn = false;
_service = null;
_isLoading = false;
notifyListeners();
return false;
}
/// 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
/// the server hands back a scoped app password. The app never sees the
/// user's real password. [addAccount] only marks the flow as "add
/// another account" for [isAddAccountFlow] - the pushed Add Account
/// screen reads that to decide when to pop itself; this method's own
/// persistence behavior on success ([_completeLoginFlow]) is the same
/// either way (create-or-refresh the resulting account, then activate
/// it).
Future<void> startLoginFlow(
String serverUrl, {
bool addAccount = false,
}) async {
_addAccountFlowActive = addAccount;
_loginFlowStatus = LoginFlowStatus.initiating;
_errorMessage = null;
notifyListeners();
try {
final init = await LoginFlowService.initiate(serverUrl);
_pendingLoginUrl = init.loginUrl;
_loginFlowStatus = LoginFlowStatus.awaitingBrowser;
notifyListeners();
_pollTimer?.cancel();
_pollTimeoutTimer?.cancel();
_pollTimeoutTimer = Timer(const Duration(minutes: 10), () {
if (_loginFlowStatus == LoginFlowStatus.awaitingBrowser) {
cancelLoginFlow(errorMessage: 'Login timed out. Please try again.');
}
});
_pollTimer = Timer.periodic(const Duration(seconds: 2), (timer) async {
try {
final result = await LoginFlowService.poll(
init.pollEndpoint,
init.pollToken,
);
if (result != null) {
timer.cancel();
_pollTimeoutTimer?.cancel();
_loginFlowStatus = LoginFlowStatus.idle;
_pendingLoginUrl = null;
await _completeLoginFlow(result);
_addAccountFlowActive = false;
}
} on http.ClientException catch (e) {
// A single dropped connection (e.g. the network briefly
// reconfiguring right as the login browser opens) used to abort
// the whole flow, forcing the user to start over even though
// they'd already granted access - just skip this tick and let
// the next scheduled poll (2s later) try again. The 10-minute
// timeout above is still the real ceiling.
debugPrint('[SessionController] Poll network hiccup, retrying: $e');
} catch (e) {
timer.cancel();
_pollTimeoutTimer?.cancel();
cancelLoginFlow(
errorMessage: e.toString().replaceAll('Exception: ', ''),
);
}
});
} catch (e) {
_loginFlowStatus = LoginFlowStatus.error;
_errorMessage = e.toString().replaceAll('Exception: ', '');
notifyListeners();
}
}
void cancelLoginFlow({String? errorMessage}) {
_pollTimer?.cancel();
_pollTimeoutTimer?.cancel();
_pendingLoginUrl = null;
_addAccountFlowActive = false;
_loginFlowStatus = errorMessage != null
? LoginFlowStatus.error
: LoginFlowStatus.idle;
_errorMessage = errorMessage;
notifyListeners();
}
/// Turns a completed Login Flow v2 result into a saved account (creating
/// it, or refreshing its password if it already existed - e.g. an
/// expired app password re-authenticated) and makes it the active
/// session. Used for both the first/only login and "add account".
Future<void> _completeLoginFlow(LoginFlowResult result) async {
final serverUrl = LoginFlowService.normalizeServerUrl(result.serverUrl);
final id = SavedAccount.makeId(serverUrl, result.loginName);
final account = SavedAccount(
id: id,
serverUrl: serverUrl,
username: result.loginName,
);
_accounts = [
for (final a in _accounts)
if (a.id != id) a,
account,
];
final prefs = await prefsFuture;
await accountStore.saveAccounts(prefs, _accounts);
await accountStore.writePassword(id, result.appPassword);
await _activateAccount(id);
}
/// The shared engine behind switching accounts, falling back to another
/// account after removing the active one, and landing on the newly
/// created/refreshed account after a login flow completes: tears down
/// the outgoing account's live content (without ever setting
/// [isLoggedIn] false - see below), then loads the target account's
/// credentials.
///
/// Non-goal, by design: no simultaneous multi-account state. This is a
/// full teardown-and-reload of the active session every time, exactly
/// like [logout] already did - just without touching any *other* saved
/// account's stored credentials/prefs.
Future<void> _activateAccount(String accountId) async {
// Invalidates any fetch still in flight for the account being left, so
// a slow response can't land in the new account's state.
_sessionGeneration++;
// A pending "add account" flow can't stay pending through a manual
// switch/cycle - simplicity over blocking the gesture.
if (_loginFlowStatus != LoginFlowStatus.idle) cancelLoginFlow();
_notifyAccountCleared();
// Not `_isLoggedIn = false` - that would bounce main.dart's root
// routing through LoginView mid-switch. Each tab already shows its own
// spinner from its own loading state, so this alone is enough to
// avoid flashing the outgoing account's stale content.
_isLoading = true;
notifyListeners();
_activeAccountId = accountId;
final prefs = await prefsFuture;
await accountStore.saveActiveAccountId(prefs, accountId);
notifyListeners();
final account = _accounts.where((a) => a.id == accountId).firstOrNull;
final password = account == null
? null
: await accountStore.readPassword(accountId);
if (account == null || password == null) {
_isLoading = false;
_isLoggedIn = false;
notifyListeners();
return;
}
await _applyCredentialsForAccount(account, password);
}
/// Switches to an already-saved account. No-op (returns true) if it's
/// already active and logged in; no-op (returns false) if unknown - but
/// if [accountId] is nominally "active" while [isLoggedIn] is false (a
/// session-restore that failed, e.g. transient network trouble at cold
/// start), this still retries rather than no-op, since that's exactly the
/// case LoginView's "Continue as" tile exists to recover from. Gated
/// behind login lock when [lockAccountSwitching] is on. Returns whether
/// the account ended up logged in, so callers (LoginView's saved-account
/// tile) can surface a failure - e.g. a stored app password that no
/// longer works and needs the account removed/re-added.
Future<bool> switchAccount(String accountId) async {
if (accountId == _activeAccountId && _isLoggedIn) return true;
if (!_accounts.any((a) => a.id == accountId)) return false;
if (!await passGate(_lockAccountSwitching, 'Unlock to switch accounts')) {
return false;
}
await _activateAccount(accountId);
return _isLoggedIn;
}
Future<SavedAccount?> _cycleAccount(int direction) async {
if (_accounts.length < 2) return null;
if (!await passGate(_lockAccountSwitching, 'Unlock to switch accounts')) {
return null;
}
final currentIndex = _accounts.indexWhere((a) => a.id == _activeAccountId);
final targetIndex = currentIndex == -1
? 0
: (currentIndex + direction) % _accounts.length;
final target =
_accounts[(targetIndex + _accounts.length) % _accounts.length];
unawaited(_activateAccount(target.id));
return target;
}
/// Cycles to the next/previous saved account (by the order they were
/// added) - used by the avatar's swipe-up/down quick-switch gesture.
Future<SavedAccount?> cycleToNextAccount() => _cycleAccount(1);
Future<SavedAccount?> cycleToPreviousAccount() => _cycleAccount(-1);
/// Removes a saved account entirely: its stored password, its
/// namespaced prefs, and its entry in the saved-accounts list. If it was
/// the active account, falls back to another saved account, or - if none
/// remain - deactivates the session (the only path here that sets
/// [isLoggedIn] false; unlike [logout], there's nothing left to keep).
Future<void> removeAccount(String accountId) async {
final index = _accounts.indexWhere((a) => a.id == accountId);
if (index == -1) return;
final wasActive = accountId == _activeAccountId;
_accounts = [..._accounts]..removeAt(index);
final prefs = await prefsFuture;
await accountStore.saveAccounts(prefs, _accounts);
await accountStore.deletePassword(accountId);
for (final key in AccountStore.perAccountPrefKeys) {
await prefs.remove(accountStore.accountPrefKey(accountId, key));
}
if (!wasActive) {
notifyListeners();
return;
}
if (_accounts.isEmpty) {
await _deactivateSession();
return;
}
await _activateAccount(_accounts.first.id);
}
/// Clears the active session pointer and tears down its content, without
/// touching any saved account's own data - shared by [logout] (which
/// deliberately keeps the account around to resume later, no
/// re-authentication needed) and [removeAccount]'s "nothing left to fall
/// back to" branch (where the account's data has already been deleted by
/// the time this runs).
Future<void> _deactivateSession() async {
_sessionGeneration++;
_notifyAccountCleared();
_isLoggedIn = false;
_serverUrl = '';
_username = '';
_password = '';
_activeAccountId = null;
final prefs = await prefsFuture;
await accountStore.saveActiveAccountId(prefs, null);
notifyListeners();
unawaited(SyncService.cancel());
}
/// Ends the active session but keeps this account saved - unlike
/// [removeAccount], nothing is deleted (password, prefs, its entry in
/// [accounts] all remain), so it's available to resume with a single tap
/// from the login screen's saved-accounts list, no Login Flow v2 needed.
/// 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;
await _deactivateSession();
}
/// Confirms the device can do local auth and prompts once to enable login
/// lock. Returns false (leaving lock disabled) if the device has no
/// biometric/PIN capability or the user cancels/fails the confirmation.
Future<bool> setupLoginLock() async {
if (!await AppLockService.isDeviceSupported()) return false;
final confirmed = await AppLockService.authenticate(
'Confirm to turn on login lock',
);
if (!confirmed) return false;
_loginLockEnabled = true;
// Already just authenticated - don't immediately re-prompt behind it.
_isUnlocked = true;
notifyListeners();
prefsFuture.then((p) => p.setBool(_prefLoginLockEnabled, true));
return true;
}
/// Turns login lock off, along with both of its sub-toggles (meaningless
/// once the base lock is gone). Requires a successful auth first, same as
/// turning it on - otherwise anyone with momentary access to an unlocked
/// phone could just switch it off.
Future<bool> disableLoginLock() async {
if (!_loginLockEnabled) return true;
final confirmed = await AppLockService.authenticate(
'Confirm to turn off login lock',
);
if (!confirmed) return false;
_loginLockEnabled = false;
_lockAccountSwitching = false;
_lockHiddenFiles = false;
_isUnlocked = false;
notifyListeners();
prefsFuture.then((p) {
p.setBool(_prefLoginLockEnabled, false);
p.setBool(_prefLockAccountSwitching, false);
p.setBool(_prefLockHiddenFiles, false);
});
return true;
}
void setLockAccountSwitching(bool value) {
if (!_loginLockEnabled) return;
_lockAccountSwitching = value;
notifyListeners();
prefsFuture.then((p) => p.setBool(_prefLockAccountSwitching, value));
}
void setLockHiddenFiles(bool value) {
if (!_loginLockEnabled) return;
_lockHiddenFiles = value;
notifyListeners();
prefsFuture.then((p) => p.setBool(_prefLockHiddenFiles, value));
}
/// Called by the lock screen. Returns whether it actually unlocked.
Future<bool> attemptUnlock() async {
final success = await AppLockService.authenticate('Unlock Noo');
if (success) {
_isUnlocked = true;
notifyListeners();
}
return success;
}
/// Prompts for auth if [gate] is on and login lock is configured;
/// returns true immediately (no prompt) otherwise. Shared by the
/// account-switching gate above and [FilesController]'s/`PhotosController`'s
/// hidden-files gates.
Future<bool> passGate(bool gate, String reason) async {
if (!_loginLockEnabled || !gate) return true;
return AppLockService.authenticate(reason);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_pollTimer?.cancel();
_pollTimeoutTimer?.cancel();
super.dispose();
}
}
+327
View File
@@ -0,0 +1,327 @@
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/app_tab.dart';
import '../theme/app_theme.dart';
/// What swiping a Files list-view item left/right does, user-configurable
/// in Settings.
enum SwipeAction { none, favorite, delete, share }
/// Thumb/track presets for the video player's seek bar, matching the four
/// combinations offered by other Material You media players: a Material 3
/// slider-style thumb ([classic]), an animated travelling wave with a round
/// thumb ([wavy]), a thin flat bar with no distinct thumb ([slim]), and an
/// animated wave with a tick-mark thumb ([squiggly]).
enum MediaProgressBarStyle { classic, wavy, slim, squiggly }
/// Global (not per-account) UI settings: theme, bottom-nav appearance, tab
/// configuration, swipe actions. Independent of login state - these mean
/// the same thing whether any account is signed in or not, unlike
/// [FilesController]'s/etc. per-account display prefs. Split out of the
/// former single `ServerProvider` god object.
class SettingsController extends ChangeNotifier {
static const _prefThemeMode = 'ui_theme_mode';
static const _prefUseDynamicColor = 'ui_use_dynamic_color';
static const _prefSeedColor = 'ui_seed_color';
static const _prefBottomBarOpacity = 'ui_bottom_bar_opacity';
static const _prefBottomBarBlur = 'ui_bottom_bar_blur';
static const _prefTabOrder = 'ui_tab_order';
static const _prefHiddenTabs = 'ui_hidden_tabs';
static const _prefDefaultTab = 'ui_default_tab';
static const _prefSwipeLeftAction = 'ui_swipe_left_action';
static const _prefSwipeRightAction = 'ui_swipe_right_action';
static const _prefAmoledDark = 'ui_amoled_dark';
static const _prefMediaProgressBarStyle = 'ui_media_progress_bar_style';
static const _prefTapTabToScrollTop = 'ui_tap_tab_to_scroll_top';
final Future<SharedPreferences> _prefsFuture =
SharedPreferences.getInstance();
Color _seedColor = AppTheme.defaultNextcloudBlue;
ThemeMode _themeMode = ThemeMode.system;
bool _useDynamicColor = true;
bool _amoledDark = false;
MediaProgressBarStyle _mediaProgressBarStyle = MediaProgressBarStyle.wavy;
double _bottomBarOpacity = 0.55;
double _bottomBarBlur = 28;
bool _tapTabToScrollTop = true;
List<AppTab> _tabOrder = AppTab.values.toList();
Set<AppTab> _hiddenTabs = {};
AppTab _defaultTab = AppTab.files;
SwipeAction _swipeLeftAction = SwipeAction.delete;
SwipeAction _swipeRightAction = SwipeAction.favorite;
// A one-shot request for the shell to switch its active bottom-nav tab
// (e.g. a search result landing on Files) - consumed and cleared by
// MainShellView the next time it builds, not a persisted preference.
AppTab? _requestedTab;
AppTab? get requestedTab => _requestedTab;
/// Asks the shell to switch its active bottom-nav tab to [tab] - e.g. so
/// tapping a search result lands the user on the Files tab even if they
/// opened search from somewhere else.
void requestTab(AppTab tab) {
_requestedTab = tab;
notifyListeners();
}
/// Called by the shell once it's consumed [requestedTab].
void consumeRequestedTab() {
_requestedTab = null;
}
SettingsController() {
_load();
}
Color get seedColor => _seedColor;
ThemeMode get themeMode => _themeMode;
bool get useDynamicColor => _useDynamicColor;
bool get amoledDark => _amoledDark;
MediaProgressBarStyle get mediaProgressBarStyle => _mediaProgressBarStyle;
double get bottomBarOpacity => _bottomBarOpacity;
double get bottomBarBlur => _bottomBarBlur;
bool get tapTabToScrollTop => _tapTabToScrollTop;
/// Every tab in the user's configured order, including hidden ones — used
/// by the reorder/visibility settings UI.
List<AppTab> get tabOrder => _tabOrder;
Set<AppTab> get hiddenTabs => _hiddenTabs;
AppTab get defaultTab => _defaultTab;
/// The tabs the bottom nav bar should actually show, in order.
List<AppTab> get visibleTabs =>
_tabOrder.where((t) => !_hiddenTabs.contains(t)).toList();
SwipeAction get swipeLeftAction => _swipeLeftAction;
SwipeAction get swipeRightAction => _swipeRightAction;
Future<void> _load() async {
try {
final prefs = await _prefsFuture;
final themeModeName = prefs.getString(_prefThemeMode);
if (themeModeName != null) {
_themeMode = ThemeMode.values.firstWhere(
(m) => m.name == themeModeName,
orElse: () => ThemeMode.system,
);
}
_useDynamicColor =
prefs.getBool(_prefUseDynamicColor) ?? _useDynamicColor;
_amoledDark = prefs.getBool(_prefAmoledDark) ?? _amoledDark;
final progressBarStyleName = prefs.getString(_prefMediaProgressBarStyle);
if (progressBarStyleName != null) {
_mediaProgressBarStyle = MediaProgressBarStyle.values.firstWhere(
(s) => s.name == progressBarStyleName,
orElse: () => _mediaProgressBarStyle,
);
}
final seedColorValue = prefs.getInt(_prefSeedColor);
if (seedColorValue != null) _seedColor = Color(seedColorValue);
_bottomBarOpacity =
prefs.getDouble(_prefBottomBarOpacity) ?? _bottomBarOpacity;
_bottomBarBlur = prefs.getDouble(_prefBottomBarBlur) ?? _bottomBarBlur;
_tapTabToScrollTop =
prefs.getBool(_prefTapTabToScrollTop) ?? _tapTabToScrollTop;
final savedOrderNames = prefs.getStringList(_prefTabOrder);
if (savedOrderNames != null) {
final order = <AppTab>[];
for (final name in savedOrderNames) {
final match = AppTab.values.where((t) => t.name == name).firstOrNull;
if (match != null) order.add(match);
}
// Forward-compat: a tab added in a later app update won't be in an
// older saved order yet, so append anything missing.
for (final tab in AppTab.values) {
if (!order.contains(tab)) order.add(tab);
}
_tabOrder = order;
}
final savedHiddenNames = prefs.getStringList(_prefHiddenTabs);
if (savedHiddenNames != null) {
_hiddenTabs = savedHiddenNames
.map(
(name) => AppTab.values.where((t) => t.name == name).firstOrNull,
)
.whereType<AppTab>()
.toSet();
// Never let every tab end up hidden.
if (_hiddenTabs.length >= AppTab.values.length) {
_hiddenTabs = {};
}
}
final savedDefaultName = prefs.getString(_prefDefaultTab);
if (savedDefaultName != null) {
final match = AppTab.values
.where((t) => t.name == savedDefaultName)
.firstOrNull;
if (match != null) _defaultTab = match;
}
if (_hiddenTabs.contains(_defaultTab)) {
_defaultTab = _tabOrder.firstWhere(
(t) => !_hiddenTabs.contains(t),
orElse: () => _tabOrder.first,
);
}
_enforceMaxVisibleTabs();
final swipeLeftName = prefs.getString(_prefSwipeLeftAction);
if (swipeLeftName != null) {
_swipeLeftAction = SwipeAction.values.firstWhere(
(a) => a.name == swipeLeftName,
orElse: () => _swipeLeftAction,
);
}
final swipeRightName = prefs.getString(_prefSwipeRightAction);
if (swipeRightName != null) {
_swipeRightAction = SwipeAction.values.firstWhere(
(a) => a.name == swipeRightName,
orElse: () => _swipeRightAction,
);
}
notifyListeners();
} catch (e) {
debugPrint('[SettingsController] Preference restore failed: $e');
}
}
void setSeedColor(Color color) {
_seedColor = color;
_useDynamicColor = false;
notifyListeners();
_prefsFuture.then((p) {
p.setInt(_prefSeedColor, color.toARGB32());
p.setBool(_prefUseDynamicColor, false);
});
}
void setUseDynamicColor(bool value) {
_useDynamicColor = value;
notifyListeners();
_prefsFuture.then((p) => p.setBool(_prefUseDynamicColor, value));
}
void setAmoledDark(bool value) {
_amoledDark = value;
notifyListeners();
_prefsFuture.then((p) => p.setBool(_prefAmoledDark, value));
}
void setMediaProgressBarStyle(MediaProgressBarStyle style) {
_mediaProgressBarStyle = style;
notifyListeners();
_prefsFuture.then(
(p) => p.setString(_prefMediaProgressBarStyle, style.name),
);
}
void setBottomBarOpacity(double value) {
_bottomBarOpacity = value;
notifyListeners();
_prefsFuture.then((p) => p.setDouble(_prefBottomBarOpacity, value));
}
void setBottomBarBlur(double value) {
_bottomBarBlur = value;
notifyListeners();
_prefsFuture.then((p) => p.setDouble(_prefBottomBarBlur, value));
}
void setTapTabToScrollTop(bool value) {
_tapTabToScrollTop = value;
notifyListeners();
_prefsFuture.then((p) => p.setBool(_prefTapTabToScrollTop, value));
}
void setThemeMode(ThemeMode mode) {
_themeMode = mode;
notifyListeners();
_prefsFuture.then((p) => p.setString(_prefThemeMode, mode.name));
}
void setTabOrder(List<AppTab> order) {
_tabOrder = order;
notifyListeners();
_prefsFuture.then(
(p) => p.setStringList(_prefTabOrder, order.map((t) => t.name).toList()),
);
}
/// Shows or hides a tab in the bottom nav bar. Refuses to hide the last
/// remaining visible tab. If the tab being hidden is the current default,
/// the default falls back to the next visible tab.
/// Returns null on success, or a user-facing reason the change was
/// refused (hiding the last visible tab, or showing a 6th).
String? setTabHidden(AppTab tab, bool hidden) {
if (hidden) {
final remaining = _tabOrder
.where((t) => t != tab && !_hiddenTabs.contains(t))
.length;
if (remaining == 0) return 'At least one tab must stay visible';
_hiddenTabs = {..._hiddenTabs, tab};
if (_defaultTab == tab) {
_defaultTab = _tabOrder.firstWhere((t) => !_hiddenTabs.contains(t));
_prefsFuture.then(
(p) => p.setString(_prefDefaultTab, _defaultTab.name),
);
}
} else {
final currentlyVisible = _tabOrder
.where((t) => !_hiddenTabs.contains(t))
.length;
if (currentlyVisible >= maxVisibleTabs) {
return 'You can only show up to $maxVisibleTabs tabs at once';
}
_hiddenTabs = {..._hiddenTabs}..remove(tab);
}
notifyListeners();
_prefsFuture.then(
(p) => p.setStringList(
_prefHiddenTabs,
_hiddenTabs.map((t) => t.name).toList(),
),
);
return null;
}
/// If more than [maxVisibleTabs] end up visible (e.g. a fresh install, or
/// an existing saved config from before a new tab was added to the app),
/// hide the overflow automatically rather than exceeding the cap.
void _enforceMaxVisibleTabs() {
final visible = _tabOrder.where((t) => !_hiddenTabs.contains(t)).toList();
if (visible.length <= maxVisibleTabs) return;
_hiddenTabs = {..._hiddenTabs, ...visible.sublist(maxVisibleTabs)};
if (_hiddenTabs.contains(_defaultTab)) {
_defaultTab = _tabOrder.firstWhere((t) => !_hiddenTabs.contains(t));
}
}
void setDefaultTab(AppTab tab) {
if (_hiddenTabs.contains(tab) || _defaultTab == tab) return;
_defaultTab = tab;
notifyListeners();
_prefsFuture.then((p) => p.setString(_prefDefaultTab, tab.name));
}
void setSwipeLeftAction(SwipeAction action) {
if (_swipeLeftAction == action) return;
_swipeLeftAction = action;
notifyListeners();
_prefsFuture.then((p) => p.setString(_prefSwipeLeftAction, action.name));
}
void setSwipeRightAction(SwipeAction action) {
if (_swipeRightAction == action) return;
_swipeRightAction = action;
notifyListeners();
_prefsFuture.then((p) => p.setString(_prefSwipeRightAction, action.name));
}
}
+81
View File
@@ -0,0 +1,81 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../models/nextcloud_share.dart';
import 'session_controller.dart';
/// The Shares tab. Kept separate from Files' own loading/error state,
/// likewise.
class SharesController extends ChangeNotifier {
final SessionController session;
List<NextcloudShare> _shares = [];
bool _isLoading = false;
String? _errorMessage;
bool _sharedWithMe = false;
SharesController(this.session) {
session.addAccountClearedListener(_onAccountCleared);
session.addAccountActivatedListener(_onAccountActivated);
}
List<NextcloudShare> get shares => _shares;
bool get isLoading => _isLoading;
String? get errorMessage => _errorMessage;
bool get sharedWithMe => _sharedWithMe;
void _onAccountCleared() {
_shares = [];
_isLoading = false;
_errorMessage = null;
_sharedWithMe = false;
notifyListeners();
}
void _onAccountActivated() {
unawaited(fetchAll());
}
Future<void> fetchAll() async {
final service = session.service;
if (!session.isLoggedIn || service == null) return;
final gen = session.sessionGeneration;
_isLoading = true;
_errorMessage = null;
notifyListeners();
try {
final shares = await service.fetchShares(sharedWithMe: _sharedWithMe);
if (gen != session.sessionGeneration) return;
_shares = shares;
} catch (e) {
if (gen != session.sessionGeneration) return;
debugPrint('[SharesController] Error fetching shares: $e');
_errorMessage = e.toString().replaceAll('Exception: ', '');
} finally {
if (gen == session.sessionGeneration) {
_isLoading = false;
notifyListeners();
}
}
}
/// Switches between "shared by me" and "shared with me" and refetches.
void setSharedWithMe(bool value) {
if (_sharedWithMe == value) return;
_sharedWithMe = value;
notifyListeners();
fetchAll();
}
Future<bool> deleteShare(NextcloudShare share) async {
final service = session.service;
if (service == null) return false;
final success = await service.deleteShare(share.id);
if (success) {
_shares = _shares.where((s) => s.id != share.id).toList();
notifyListeners();
}
return success;
}
}
+215
View File
@@ -0,0 +1,215 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import '../models/nextcloud_item.dart';
import '../models/sync_status.dart';
import '../services/sync_service.dart';
import 'session_controller.dart';
/// Device-sync state and settings: which remote paths (files or folders,
/// per account) get mirrored locally by the native `SyncWorker`, whether
/// its periodic background runs are allowed on cellular, and live status
/// pushed from `SyncStatusBus.kt` (syncing-now/per-file-syncing/synced/
/// conflicts) - see `server.md`'s "Device sync" section. Split out of the
/// former single `ServerProvider` god object specifically because this
/// state used to reach directly into Files/Photos/Favorites item lists
/// (`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 {
final SessionController session;
static const _prefSyncedPaths = 'ui_synced_folders';
static const _prefSyncEverything = 'ui_sync_everything';
static const _prefSyncOnCellular = 'ui_sync_on_cellular';
List<String> _syncedPaths = [];
bool _syncEverything = false;
bool _syncOnCellular = false;
bool _isSyncingNow = false;
Set<String> _syncingFileIds = {};
Set<String> _syncedFileIds = {};
List<SyncConflictInfo> _syncConflicts = [];
StreamSubscription<SyncStatusSnapshot>? _statusSub;
SyncStatusController(this.session) {
session.addAccountClearedListener(_onAccountCleared);
session.addAccountActivatedListener(_onAccountActivated);
_statusSub = SyncService.statusStream.listen(_applySnapshot);
_loadGlobalPrefs();
}
List<String> get syncedPaths => List.unmodifiable(_syncedPaths);
bool get syncEverything => _syncEverything;
bool get syncOnCellular => _syncOnCellular;
bool get isSyncingNow => _isSyncingNow;
List<SyncConflictInfo> get syncConflicts => List.unmodifiable(_syncConflicts);
SyncHeaderStatus get syncHeaderStatus {
if (_syncConflicts.isNotEmpty) return SyncHeaderStatus.alert;
if (_isSyncingNow) return SyncHeaderStatus.syncing;
if (!_syncEverything && _syncedPaths.isEmpty) return SyncHeaderStatus.off;
return SyncHeaderStatus.done;
}
SyncItemStatus syncStatusFor(NextcloudItem item) {
if (_syncingFileIds.contains(item.id)) return SyncItemStatus.syncing;
if (_syncConflicts.any((c) => c.fileId == item.id)) {
return SyncItemStatus.conflict;
}
if (_syncedFileIds.contains(item.id)) return SyncItemStatus.synced;
return SyncItemStatus.none;
}
Future<void> _loadGlobalPrefs() async {
final prefs = await session.prefsFuture;
_syncOnCellular = prefs.getBool(_prefSyncOnCellular) ?? _syncOnCellular;
notifyListeners();
}
void _onAccountCleared() {
_syncedPaths = [];
_syncEverything = false;
_isSyncingNow = false;
_syncingFileIds = {};
_syncedFileIds = {};
_syncConflicts = [];
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');
_syncedPaths = [];
}
} else {
_syncedPaths = [];
}
_syncEverything = prefs.getBool(k(_prefSyncEverything)) ?? false;
notifyListeners();
}
unawaited(SyncService.reschedule(session, this));
unawaited(SyncService.getStatus().then(_applySnapshot));
}
void _applySnapshot(SyncStatusSnapshot snapshot) {
if (snapshot.accountId != null &&
snapshot.accountId != session.activeAccountId) {
return;
}
_isSyncingNow = snapshot.syncing;
_syncingFileIds = snapshot.syncingFileIds;
_syncedFileIds = snapshot.syncedFileIds;
_syncConflicts = snapshot.conflicts;
notifyListeners();
}
void _persistSyncedPaths() {
final id = session.activeAccountId;
if (id == null) return;
session.prefsFuture.then(
(p) => p.setString(
session.accountStore.accountPrefKey(id, _prefSyncedPaths),
jsonEncode(_syncedPaths),
),
);
}
bool isPathSynced(String path) => _syncedPaths.contains(path);
void addSyncedPath(String path) {
if (_syncedPaths.contains(path)) return;
_syncedPaths = [..._syncedPaths, path];
notifyListeners();
_persistSyncedPaths();
unawaited(SyncService.reschedule(session, this));
}
void removeSyncedPath(String path) {
if (!_syncedPaths.contains(path)) return;
_syncedPaths = _syncedPaths.where((f) => f != path).toList();
notifyListeners();
_persistSyncedPaths();
unawaited(SyncService.reschedule(session, this));
}
void setSyncEverything(bool value) {
if (_syncEverything == value) return;
_syncEverything = value;
notifyListeners();
final id = session.activeAccountId;
if (id != null) {
session.prefsFuture.then(
(p) => p.setBool(
session.accountStore.accountPrefKey(id, _prefSyncEverything),
value,
),
);
}
unawaited(SyncService.reschedule(session, this));
}
void setSyncOnCellular(bool value) {
if (_syncOnCellular == value) return;
_syncOnCellular = value;
notifyListeners();
session.prefsFuture.then((p) => p.setBool(_prefSyncOnCellular, value));
unawaited(SyncService.reschedule(session, this));
}
/// In-app conflict resolution (the sync header's "Keep local"/"Use
/// server" buttons) - see `SyncService.resolveConflict`'s doc comment
/// for why this shares the exact same native path the notification
/// actions use.
Future<void> resolveSyncConflict(
SyncConflictInfo conflict, {
required bool useLocal,
}) {
return SyncService.resolveConflict(
session,
conflict,
useLocal ? 'local' : 'server',
);
}
/// The local mirror path for [item] if it falls under a synced folder
/// *and* has actually been synced down already - a pure function of the
/// remote path once a folder's marked synced (mirrors
/// `SyncEngine.kt#syncRoot`'s `<externalFilesDir>/sync/<accountId>/...`
/// layout exactly), so this never needs to read the native sync-state
/// SharedPreferences from Dart. Callers (Share/Download) use this to
/// skip a fresh WebDAV fetch when a local copy already exists.
Future<String?> localSyncedFilePath(NextcloudItem item) async {
final id = session.activeAccountId;
if (id == null) return null;
final itemPath = item.path.endsWith('/')
? item.path.substring(0, item.path.length - 1)
: item.path;
final isSynced =
_syncEverything ||
_syncedPaths.any((folder) {
final f = folder.endsWith('/')
? folder.substring(0, folder.length - 1)
: folder;
return itemPath == f || itemPath.startsWith('$f/');
});
if (!isSynced) return null;
return SyncService.localSyncedFilePath(id, item.path);
}
@override
void dispose() {
_statusSub?.cancel();
super.dispose();
}
}
+84
View File
@@ -0,0 +1,84 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../models/nextcloud_item.dart';
import 'session_controller.dart';
/// The Trash tab. Kept separate from Files' own loading/error state so a
/// trash-fetch failure can't bleed a stale error into Files.
class TrashController extends ChangeNotifier {
final SessionController session;
List<NextcloudItem> _items = [];
bool _isLoading = false;
String? _errorMessage;
TrashController(this.session) {
session.addAccountClearedListener(_onAccountCleared);
session.addAccountActivatedListener(_onAccountActivated);
}
List<NextcloudItem> get items => _items;
bool get isLoading => _isLoading;
String? get errorMessage => _errorMessage;
void _onAccountCleared() {
_items = [];
_isLoading = false;
_errorMessage = null;
notifyListeners();
}
void _onAccountActivated() {
unawaited(fetchAll());
}
Future<void> fetchAll() async {
final service = session.service;
if (!session.isLoggedIn || service == null) return;
final gen = session.sessionGeneration;
_isLoading = true;
_errorMessage = null;
notifyListeners();
try {
final trash = await service.fetchTrash();
if (gen != session.sessionGeneration) return;
_items = trash;
} catch (e) {
if (gen != session.sessionGeneration) return;
debugPrint('[TrashController] Error fetching trash: $e');
_errorMessage = e.toString().replaceAll('Exception: ', '');
} finally {
if (gen == session.sessionGeneration) {
_isLoading = false;
notifyListeners();
}
}
}
/// Restores a trashed item (identified by [NextcloudItem.path], the
/// trash-relative name) back to where it was deleted from.
Future<bool> restore(NextcloudItem item) async {
final service = session.service;
if (service == null) return false;
final success = await service.restoreTrashItem(item.path);
if (success) {
_items = _items.where((i) => i.id != item.id).toList();
notifyListeners();
}
return success;
}
/// Permanently deletes a trashed item. Cannot be undone.
Future<bool> deleteForever(NextcloudItem item) async {
final service = session.service;
if (service == null) return false;
final success = await service.deleteTrashItemForever(item.path);
if (success) {
_items = _items.where((i) => i.id != item.id).toList();
notifyListeners();
}
return success;
}
}