Rebuild Noo as a full Nextcloud client: auth, media, and Material You UI

Replaces the starter template with Login Flow v2 auth, WebDAV-backed
Files/Photos/Activity tabs, a swipeable media viewer with PDF/text/video
preview, Material You dynamic theming, a frosted-glass floating nav bar,
and a rebranded app icon/identity (com.example -> family.nasa).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-15 16:07:02 -04:00
co-authored by Claude Sonnet 5
parent 54f80a65e7
commit f62d912ef7
47 changed files with 5083 additions and 1571 deletions
+58 -52
View File
@@ -1,13 +1,13 @@
import 'package:dynamic_color/dynamic_color.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:provider/provider.dart';
import 'providers/server_provider.dart';
import 'theme/app_theme.dart';
import 'views/account_view.dart';
import 'views/activity_view.dart';
import 'views/files_view.dart';
import 'views/login_view.dart';
import 'views/photos_view.dart';
import 'views/search_view.dart';
import 'widgets/floating_bottom_bar.dart';
void main() {
@@ -27,13 +27,50 @@ class NextcloudApp extends StatelessWidget {
Widget build(BuildContext context) {
final provider = context.watch<ServerProvider>();
return MaterialApp(
title: 'Nextcloud Material',
debugShowCheckedModeBanner: false,
theme: AppTheme.light(provider.seedColor),
darkTheme: AppTheme.dark(provider.seedColor),
themeMode: provider.themeMode,
home: provider.isLoggedIn ? const MainShellView() : const LoginView(),
return DynamicColorBuilder(
builder: (lightDynamic, darkDynamic) {
return MaterialApp(
title: 'Noo',
debugShowCheckedModeBanner: false,
theme: AppTheme.light(
provider.seedColor,
dynamicScheme: lightDynamic,
useDynamicColor: provider.useDynamicColor,
),
darkTheme: AppTheme.dark(
provider.seedColor,
dynamicScheme: darkDynamic,
useDynamicColor: provider.useDynamicColor,
),
themeMode: provider.themeMode,
home: provider.isRestoringSession
? const _SplashView()
: (provider.isLoggedIn
? const MainShellView()
: const LoginView()),
);
},
);
}
}
class _SplashView extends StatelessWidget {
const _SplashView();
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.cloud_outlined, size: 48, color: colorScheme.primary),
const SizedBox(height: 20),
CircularProgressIndicator(color: colorScheme.primary),
],
),
),
);
}
}
@@ -47,32 +84,13 @@ class MainShellView extends StatefulWidget {
class _MainShellViewState extends State<MainShellView> {
int _currentIndex = 0;
bool _isNavVisible = true;
late final List<ScrollController> _scrollControllers;
@override
void initState() {
super.initState();
_scrollControllers = List.generate(4, (index) {
final controller = ScrollController();
controller.addListener(() {
if (controller.position.userScrollDirection == ScrollDirection.reverse) {
if (_isNavVisible) {
setState(() {
_isNavVisible = false;
});
}
} else if (controller.position.userScrollDirection == ScrollDirection.forward) {
if (!_isNavVisible) {
setState(() {
_isNavVisible = true;
});
}
}
});
return controller;
});
_scrollControllers = List.generate(3, (index) => ScrollController());
}
@override
@@ -85,27 +103,11 @@ class _MainShellViewState extends State<MainShellView> {
@override
Widget build(BuildContext context) {
final provider = context.watch<ServerProvider>();
final navItems = const [
FloatingNavItem(
label: 'Files',
icon: Icons.folder_outlined,
selectedIcon: Icons.folder_rounded,
),
FloatingNavItem(
label: 'Photos',
icon: Icons.photo_library_outlined,
selectedIcon: Icons.photo_library_rounded,
),
FloatingNavItem(
label: 'Activity',
icon: Icons.history_rounded,
selectedIcon: Icons.history_toggle_off_rounded,
),
FloatingNavItem(
label: 'Account',
icon: Icons.account_circle_outlined,
selectedIcon: Icons.account_circle_rounded,
),
FloatingNavItem(label: 'Files', icon: Icons.folder_rounded),
FloatingNavItem(label: 'Photos', icon: Icons.photo_library_rounded),
FloatingNavItem(label: 'Activity', icon: Icons.history_rounded),
];
return Scaffold(
@@ -117,19 +119,23 @@ class _MainShellViewState extends State<MainShellView> {
FilesView(scrollController: _scrollControllers[0]),
PhotosView(scrollController: _scrollControllers[1]),
ActivityView(scrollController: _scrollControllers[2]),
AccountView(scrollController: _scrollControllers[3]),
],
),
FloatingBottomNavBar(
selectedIndex: _currentIndex,
items: navItems,
isVisible: _isNavVisible,
opacity: provider.bottomBarOpacity,
blurSigma: provider.bottomBarBlur,
onDestinationSelected: (index) {
setState(() {
_currentIndex = index;
_isNavVisible = true;
});
},
onSearchTap: () {
Navigator.of(
context,
).push(MaterialPageRoute(builder: (_) => const SearchView()));
},
),
],
),
+43 -8
View File
@@ -9,12 +9,14 @@ class NextcloudItem {
final NextcloudItemType type;
final int size; // in bytes
final DateTime lastModified;
final DateTime dateCreated;
final bool isFavorite;
final String? mimeType;
final String? etag;
final String? previewUrl;
final int? imageWidth;
final int? imageHeight;
final String? mountType;
const NextcloudItem({
required this.id,
@@ -23,16 +25,20 @@ class NextcloudItem {
required this.type,
required this.size,
required this.lastModified,
DateTime? dateCreated,
this.isFavorite = false,
this.mimeType,
this.etag,
this.previewUrl,
this.imageWidth,
this.imageHeight,
});
this.mountType,
}) : dateCreated = dateCreated ?? lastModified;
bool get isFolder => type == NextcloudItemType.folder;
bool get isMedia => type == NextcloudItemType.image || type == NextcloudItemType.video;
bool get isMedia =>
type == NextcloudItemType.image || type == NextcloudItemType.video;
bool get isExternalStorage => mountType == 'external';
NextcloudItem copyWith({
String? id,
@@ -41,12 +47,14 @@ class NextcloudItem {
NextcloudItemType? type,
int? size,
DateTime? lastModified,
DateTime? dateCreated,
bool? isFavorite,
String? mimeType,
String? etag,
String? previewUrl,
int? imageWidth,
int? imageHeight,
String? mountType,
}) {
return NextcloudItem(
id: id ?? this.id,
@@ -55,31 +63,58 @@ class NextcloudItem {
type: type ?? this.type,
size: size ?? this.size,
lastModified: lastModified ?? this.lastModified,
dateCreated: dateCreated ?? this.dateCreated,
isFavorite: isFavorite ?? this.isFavorite,
mimeType: mimeType ?? this.mimeType,
etag: etag ?? this.etag,
previewUrl: previewUrl ?? this.previewUrl,
imageWidth: imageWidth ?? this.imageWidth,
imageHeight: imageHeight ?? this.imageHeight,
mountType: mountType ?? this.mountType,
);
}
static NextcloudItemType deduceType(String path, bool isCollection, String? mime) {
static NextcloudItemType deduceType(
String path,
bool isCollection,
String? mime,
) {
if (isCollection) return NextcloudItemType.folder;
final lower = path.toLowerCase();
if (mime?.startsWith('image/') == true || lower.endsWith('.jpg') || lower.endsWith('.jpeg') || lower.endsWith('.png') || lower.endsWith('.webp') || lower.endsWith('.gif') || lower.endsWith('.heic')) {
if (mime?.startsWith('image/') == true ||
lower.endsWith('.jpg') ||
lower.endsWith('.jpeg') ||
lower.endsWith('.png') ||
lower.endsWith('.webp') ||
lower.endsWith('.gif') ||
lower.endsWith('.heic')) {
return NextcloudItemType.image;
}
if (mime?.startsWith('video/') == true || lower.endsWith('.mp4') || lower.endsWith('.mov') || lower.endsWith('.mkv') || lower.endsWith('.webm')) {
if (mime?.startsWith('video/') == true ||
lower.endsWith('.mp4') ||
lower.endsWith('.mov') ||
lower.endsWith('.mkv') ||
lower.endsWith('.webm')) {
return NextcloudItemType.video;
}
if (mime?.startsWith('audio/') == true || lower.endsWith('.mp3') || lower.endsWith('.flac') || lower.endsWith('.wav') || lower.endsWith('.ogg')) {
if (mime?.startsWith('audio/') == true ||
lower.endsWith('.mp3') ||
lower.endsWith('.flac') ||
lower.endsWith('.wav') ||
lower.endsWith('.ogg')) {
return NextcloudItemType.audio;
}
if (lower.endsWith('.pdf') || lower.endsWith('.txt') || lower.endsWith('.md') || lower.endsWith('.docx') || lower.endsWith('.xlsx')) {
if (lower.endsWith('.pdf') ||
lower.endsWith('.txt') ||
lower.endsWith('.md') ||
lower.endsWith('.docx') ||
lower.endsWith('.xlsx')) {
return NextcloudItemType.document;
}
if (lower.endsWith('.zip') || lower.endsWith('.tar') || lower.endsWith('.gz') || lower.endsWith('.7z')) {
if (lower.endsWith('.zip') ||
lower.endsWith('.tar') ||
lower.endsWith('.gz') ||
lower.endsWith('.7z')) {
return NextcloudItemType.archive;
}
return NextcloudItemType.file;
+355 -69
View File
@@ -1,29 +1,71 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import '../models/nextcloud_item.dart';
import '../services/login_flow_service.dart';
import '../services/nextcloud_service.dart';
import '../theme/app_theme.dart';
enum LoginFlowStatus { idle, initiating, awaitingBrowser, error }
enum FileSortField { name, dateCreated, dateModified, size }
class ServerProvider extends ChangeNotifier {
static const _storage = FlutterSecureStorage();
static const _keyServerUrl = 'nc_server_url';
static const _keyLoginName = 'nc_login_name';
static const _keyAppPassword = 'nc_app_password';
// Cached UI settings/toggles (SharedPreferences keys)
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 _prefGridView = 'ui_grid_view';
static const _prefShowFavoritesOnly = 'ui_show_favorites_only';
static const _prefShowExternalOnly = 'ui_show_external_only';
static const _prefShowHidden = 'ui_show_hidden';
static const _prefSortField = 'ui_sort_field';
static const _prefSortAscending = 'ui_sort_ascending';
final Future<SharedPreferences> _prefsFuture =
SharedPreferences.getInstance();
String _serverUrl = '';
String _username = '';
String _password = '';
bool _isLoggedIn = false;
bool _isLoading = false;
bool _isRestoringSession = true;
String? _errorMessage;
// Login flow v2 state
LoginFlowStatus _loginFlowStatus = LoginFlowStatus.idle;
Uri? _pendingLoginUrl;
Timer? _pollTimer;
Timer? _pollTimeoutTimer;
// Theme state
Color _seedColor = AppTheme.defaultNextcloudBlue;
ThemeMode _themeMode = ThemeMode.system;
bool _useDynamicColor = true;
// UI settings
double _bottomBarOpacity = 0.55;
double _bottomBarBlur = 28;
// Navigation state
String _currentFolderPath = '/';
List<String> _pathStack = ['/'];
bool _isGridView = false;
String _searchQuery = '';
bool _showFavoritesOnly = false;
bool _showExternalOnly = false;
bool _showHidden = false;
FileSortField _sortField = FileSortField.name;
bool _sortAscending = true;
// Data state
List<NextcloudItem> _items = [];
@@ -33,95 +75,158 @@ class ServerProvider extends ChangeNotifier {
NextcloudService? _service;
ServerProvider() {
_loadSavedSession();
_restoreSession();
_loadPreferences();
}
// Getters
String get serverUrl => _serverUrl;
String get username => _username;
String get password => _password;
bool get isLoggedIn => _isLoggedIn;
bool get isLoading => _isLoading;
bool get isRestoringSession => _isRestoringSession;
String? get errorMessage => _errorMessage;
LoginFlowStatus get loginFlowStatus => _loginFlowStatus;
Uri? get pendingLoginUrl => _pendingLoginUrl;
Color get seedColor => _seedColor;
ThemeMode get themeMode => _themeMode;
bool get useDynamicColor => _useDynamicColor;
double get bottomBarOpacity => _bottomBarOpacity;
double get bottomBarBlur => _bottomBarBlur;
String get currentFolderPath => _currentFolderPath;
List<String> get pathStack => _pathStack;
bool get isGridView => _isGridView;
String get searchQuery => _searchQuery;
bool get showFavoritesOnly => _showFavoritesOnly;
bool get showExternalOnly => _showExternalOnly;
bool get showHidden => _showHidden;
FileSortField get sortField => _sortField;
bool get sortAscending => _sortAscending;
/// Exposes the active service so views can build file URLs, auth headers,
/// and trigger downloads/previews directly.
NextcloudService? get service => _service;
List<NextcloudItem> get items {
var filtered = _items;
if (_showFavoritesOnly) {
filtered = filtered.where((item) => item.isFavorite).toList();
}
if (_searchQuery.trim().isNotEmpty) {
final query = _searchQuery.toLowerCase();
filtered = filtered.where((item) => item.name.toLowerCase().contains(query)).toList();
if (_showExternalOnly) {
filtered = filtered.where((item) => item.isExternalStorage).toList();
}
return filtered;
if (!_showHidden) {
filtered = filtered.where((item) => !item.name.startsWith('.')).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);
}
}
final folders = filtered.where((i) => i.isFolder).toList()..sort(compare);
final files = filtered.where((i) => !i.isFolder).toList()..sort(compare);
return _sortAscending
? [...folders, ...files]
: [...folders.reversed, ...files.reversed];
}
List<NextcloudItem> get photoItems {
final allMedia = _items.where((i) => i.isMedia || i.type == NextcloudItemType.image).toList();
if (_searchQuery.trim().isNotEmpty) {
final query = _searchQuery.toLowerCase();
return allMedia.where((i) => i.name.toLowerCase().contains(query)).toList();
}
return allMedia;
return _items
.where((i) => i.isMedia || i.type == NextcloudItemType.image)
.toList();
}
NextcloudUserQuota? get quota => _quota;
List<NextcloudActivity> get activities => _activities;
Future<void> _loadSavedSession() async {
Future<void> _restoreSession() async {
try {
final file = File('.nextcloud_session.json');
if (await file.exists()) {
final content = await file.readAsString();
final data = jsonDecode(content);
if (data['serverUrl'] != null && data['username'] != null && data['password'] != null) {
final sUrl = data['serverUrl'].toString();
final uName = data['username'].toString();
final pWord = data['password'].toString();
final server = await _storage.read(key: _keyServerUrl);
final loginName = await _storage.read(key: _keyLoginName);
final appPassword = await _storage.read(key: _keyAppPassword);
if (sUrl.isNotEmpty && uName.isNotEmpty && pWord.isNotEmpty) {
await login(serverUrl: sUrl, username: uName, password: pWord, saveSession: false);
}
}
if (server != null && loginName != null && appPassword != null) {
await _applyCredentials(server, loginName, appPassword, persist: false);
}
} catch (_) {}
} catch (e) {
debugPrint('[ServerProvider] Session restore failed: $e');
} finally {
_isRestoringSession = false;
notifyListeners();
}
}
Future<void> _saveSession() async {
Future<void> _loadPreferences() async {
try {
final file = File('.nextcloud_session.json');
final data = {
'serverUrl': _serverUrl,
'username': _username,
'password': _password,
};
await file.writeAsString(jsonEncode(data));
} catch (_) {}
}
final prefs = await _prefsFuture;
Future<void> _clearSavedSession() async {
try {
final file = File('.nextcloud_session.json');
if (await file.exists()) {
await file.delete();
final themeModeName = prefs.getString(_prefThemeMode);
if (themeModeName != null) {
_themeMode = ThemeMode.values.firstWhere(
(m) => m.name == themeModeName,
orElse: () => ThemeMode.system,
);
}
} catch (_) {}
_useDynamicColor =
prefs.getBool(_prefUseDynamicColor) ?? _useDynamicColor;
final seedColorValue = prefs.getInt(_prefSeedColor);
if (seedColorValue != null) _seedColor = Color(seedColorValue);
_bottomBarOpacity =
prefs.getDouble(_prefBottomBarOpacity) ?? _bottomBarOpacity;
_bottomBarBlur = prefs.getDouble(_prefBottomBarBlur) ?? _bottomBarBlur;
_isGridView = prefs.getBool(_prefGridView) ?? _isGridView;
_showFavoritesOnly =
prefs.getBool(_prefShowFavoritesOnly) ?? _showFavoritesOnly;
_showExternalOnly =
prefs.getBool(_prefShowExternalOnly) ?? _showExternalOnly;
_showHidden = prefs.getBool(_prefShowHidden) ?? _showHidden;
final sortFieldName = prefs.getString(_prefSortField);
if (sortFieldName != null) {
_sortField = FileSortField.values.firstWhere(
(f) => f.name == sortFieldName,
orElse: () => FileSortField.name,
);
}
_sortAscending = prefs.getBool(_prefSortAscending) ?? _sortAscending;
notifyListeners();
} catch (e) {
debugPrint('[ServerProvider] Preference restore failed: $e');
}
}
Future<bool> login({
required String serverUrl,
required String username,
required String password,
bool saveSession = true,
Future<void> _persistCredentials(
String server,
String loginName,
String appPassword,
) async {
await _storage.write(key: _keyServerUrl, value: server);
await _storage.write(key: _keyLoginName, value: loginName);
await _storage.write(key: _keyAppPassword, value: appPassword);
}
Future<void> _clearPersistedCredentials() async {
await _storage.delete(key: _keyServerUrl);
await _storage.delete(key: _keyLoginName);
await _storage.delete(key: _keyAppPassword);
}
Future<bool> _applyCredentials(
String serverUrl,
String username,
String appPassword, {
bool persist = true,
}) async {
_isLoading = true;
_errorMessage = null;
@@ -129,7 +234,7 @@ class ServerProvider extends ChangeNotifier {
_serverUrl = serverUrl;
_username = username;
_password = password;
_password = appPassword;
_service = NextcloudService(
serverUrl: _serverUrl,
@@ -143,8 +248,8 @@ class ServerProvider extends ChangeNotifier {
_isLoggedIn = true;
_currentFolderPath = '/';
_pathStack = ['/'];
if (saveSession) {
await _saveSession();
if (persist) {
await _persistCredentials(_serverUrl, _username, _password);
}
await refreshData();
_isLoading = false;
@@ -153,14 +258,101 @@ class ServerProvider extends ChangeNotifier {
}
} catch (e) {
_errorMessage = e.toString().replaceAll('Exception: ', '');
if (!persist) {
// A previously-saved app password no longer works; drop it.
await _clearPersistedCredentials();
}
}
_isLoggedIn = false;
_service = null;
_isLoading = false;
notifyListeners();
return false;
}
/// Starts Nextcloud Login Flow v2: asks the server for a one-time login
/// URL, opens it in the system browser, then polls until the user
/// authorizes and the server hands back a scoped app password. The app
/// never sees the user's real password.
Future<void> startLoginFlow(String serverUrl) async {
_loginFlowStatus = LoginFlowStatus.initiating;
_errorMessage = null;
notifyListeners();
try {
final init = await LoginFlowService.initiate(serverUrl);
_pendingLoginUrl = init.loginUrl;
final opened = await launchUrl(
init.loginUrl,
mode: LaunchMode.externalApplication,
);
if (!opened) {
throw Exception('Could not open the browser for login.');
}
_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 _applyCredentials(
result.serverUrl,
result.loginName,
result.appPassword,
);
}
} catch (e) {
timer.cancel();
_pollTimeoutTimer?.cancel();
cancelLoginFlow(
errorMessage: e.toString().replaceAll('Exception: ', ''),
);
}
});
} catch (e) {
_loginFlowStatus = LoginFlowStatus.error;
_errorMessage = e.toString().replaceAll('Exception: ', '');
notifyListeners();
}
}
Future<void> reopenLoginBrowser() async {
if (_pendingLoginUrl != null) {
await launchUrl(_pendingLoginUrl!, mode: LaunchMode.externalApplication);
}
}
void cancelLoginFlow({String? errorMessage}) {
_pollTimer?.cancel();
_pollTimeoutTimer?.cancel();
_pendingLoginUrl = null;
_loginFlowStatus = errorMessage != null
? LoginFlowStatus.error
: LoginFlowStatus.idle;
_errorMessage = errorMessage;
notifyListeners();
}
Future<void> logout() async {
_isLoggedIn = false;
_serverUrl = '';
@@ -170,13 +362,15 @@ class ServerProvider extends ChangeNotifier {
_quota = null;
_activities = [];
_service = null;
await _clearSavedSession();
await _clearPersistedCredentials();
notifyListeners();
}
Future<void> refreshData() async {
if (!_isLoggedIn || _service == null) {
debugPrint('[ServerProvider] refreshData skipped: isLoggedIn=$_isLoggedIn, service=${_service != null}');
debugPrint(
'[ServerProvider] refreshData skipped: isLoggedIn=$_isLoggedIn, service=${_service != null}',
);
return;
}
@@ -184,20 +378,28 @@ class ServerProvider extends ChangeNotifier {
_errorMessage = null;
notifyListeners();
debugPrint('[ServerProvider] Refreshing data for path: $_currentFolderPath');
debugPrint(
'[ServerProvider] Refreshing data for path: $_currentFolderPath',
);
try {
_items = await _service!.fetchDirectory(_currentFolderPath);
debugPrint('[ServerProvider] Loaded ${_items.length} items for $_currentFolderPath');
debugPrint(
'[ServerProvider] Loaded ${_items.length} items for $_currentFolderPath',
);
try {
_quota = await _service!.fetchUserQuota();
debugPrint('[ServerProvider] Loaded quota: used=${_quota?.usedBytes}, total=${_quota?.totalBytes}');
debugPrint(
'[ServerProvider] Loaded quota: used=${_quota?.usedBytes}, total=${_quota?.totalBytes}',
);
} catch (e) {
debugPrint('[ServerProvider] Quota fetch warning: $e');
}
try {
_activities = await _service!.fetchActivities();
debugPrint('[ServerProvider] Loaded ${_activities.length} activity items');
debugPrint(
'[ServerProvider] Loaded ${_activities.length} activity items',
);
} catch (e) {
debugPrint('[ServerProvider] Activity fetch warning: $e');
}
@@ -210,6 +412,11 @@ class ServerProvider extends ChangeNotifier {
}
}
Future<List<NextcloudItem>> searchFiles(String query) async {
if (_service == null) return [];
return _service!.searchFiles(query);
}
Future<void> navigateToFolder(String path) async {
_currentFolderPath = path;
_pathStack.add(path);
@@ -224,24 +431,69 @@ class ServerProvider extends ChangeNotifier {
}
}
void toggleViewMode() {
_isGridView = !_isGridView;
notifyListeners();
/// 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);
_currentFolderPath = _pathStack.last;
await refreshData();
}
void setSearchQuery(String query) {
_searchQuery = query;
void setGridView(bool value) {
if (_isGridView == value) return;
_isGridView = value;
notifyListeners();
_prefsFuture.then((p) => p.setBool(_prefGridView, value));
}
void toggleFavoritesFilter() {
_showFavoritesOnly = !_showFavoritesOnly;
notifyListeners();
_prefsFuture.then(
(p) => p.setBool(_prefShowFavoritesOnly, _showFavoritesOnly),
);
}
Future<bool> uploadFile(String name, Uint8List bytes) async {
void toggleExternalStorageFilter() {
_showExternalOnly = !_showExternalOnly;
notifyListeners();
_prefsFuture.then(
(p) => p.setBool(_prefShowExternalOnly, _showExternalOnly),
);
}
void toggleShowHidden() {
_showHidden = !_showHidden;
notifyListeners();
_prefsFuture.then((p) => p.setBool(_prefShowHidden, _showHidden));
}
void setSortField(FileSortField field) {
if (_sortField == field) return;
_sortField = field;
notifyListeners();
_prefsFuture.then((p) => p.setString(_prefSortField, field.name));
}
void toggleSortOrder() {
_sortAscending = !_sortAscending;
notifyListeners();
_prefsFuture.then((p) => p.setBool(_prefSortAscending, _sortAscending));
}
Future<bool> uploadFileFromPath(
String name,
String localFilePath, {
void Function(int sent, int total)? onProgress,
}) async {
if (_service == null) return false;
final success = await _service!.uploadFile(_currentFolderPath, name, bytes);
final success = await _service!.uploadFileFromPath(
_currentFolderPath,
name,
localFilePath,
onProgress: onProgress,
);
if (success) {
await refreshData();
}
@@ -259,7 +511,10 @@ class ServerProvider extends ChangeNotifier {
Future<bool> createFolder(String folderName) async {
if (_service == null) return false;
final success = await _service!.createFolder(_currentFolderPath, folderName);
final success = await _service!.createFolder(
_currentFolderPath,
folderName,
);
if (success) {
await refreshData();
}
@@ -280,11 +535,42 @@ class ServerProvider extends ChangeNotifier {
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 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 setThemeMode(ThemeMode mode) {
_themeMode = mode;
notifyListeners();
_prefsFuture.then((p) => p.setString(_prefThemeMode, mode.name));
}
@override
void dispose() {
_pollTimer?.cancel();
_pollTimeoutTimer?.cancel();
super.dispose();
}
}
+117
View File
@@ -0,0 +1,117 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
class LoginFlowInit {
final Uri loginUrl;
final Uri pollEndpoint;
final String pollToken;
const LoginFlowInit({
required this.loginUrl,
required this.pollEndpoint,
required this.pollToken,
});
}
class LoginFlowResult {
final String serverUrl;
final String loginName;
final String appPassword;
const LoginFlowResult({
required this.serverUrl,
required this.loginName,
required this.appPassword,
});
}
/// Implements Nextcloud's "Login Flow v2": the app never sees the user's
/// real password. It asks the server for a one-time login URL, the user
/// authorizes in their browser, and the app polls until the server hands
/// back a scoped app password.
/// https://docs.nextcloud.com/server/latest/developer_manual/client_apis/LoginFlow/index.html#login-flow-v2
class LoginFlowService {
static const _userAgent = 'Nextcloud-Flutter-Client/1.0';
static String normalizeServerUrl(String input) {
var url = input.trim();
if (!url.startsWith('http://') && !url.startsWith('https://')) {
url = 'https://$url';
}
if (url.endsWith('/')) {
url = url.substring(0, url.length - 1);
}
return url;
}
static Future<LoginFlowInit> initiate(String serverUrl) async {
final cleanUrl = normalizeServerUrl(serverUrl);
final endpoint = Uri.parse('$cleanUrl/index.php/login/v2');
debugPrint('[LoginFlow] Initiating login flow at $endpoint');
final response = await http.post(
endpoint,
headers: {'User-Agent': _userAgent, 'OCS-APIRequest': 'true'},
);
if (response.statusCode != 200) {
throw Exception(
'Could not start login flow (HTTP ${response.statusCode}). '
'Check the server address and that it is a reachable Nextcloud instance.',
);
}
final data = jsonDecode(response.body);
final loginUrl = data['login'] as String?;
final poll = data['poll'] as Map?;
final pollToken = poll?['token'] as String?;
final pollEndpoint = poll?['endpoint'] as String?;
if (loginUrl == null || pollToken == null || pollEndpoint == null) {
throw Exception('Server response did not include login flow details.');
}
return LoginFlowInit(
loginUrl: Uri.parse(loginUrl),
pollEndpoint: Uri.parse(pollEndpoint),
pollToken: pollToken,
);
}
/// Performs a single poll attempt. Returns null while the user has not
/// finished authorizing yet (server responds 404 during that window).
static Future<LoginFlowResult?> poll(Uri pollEndpoint, String token) async {
final response = await http.post(
pollEndpoint,
headers: {
'User-Agent': _userAgent,
'OCS-APIRequest': 'true',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {'token': token},
);
if (response.statusCode == 404) {
return null;
}
if (response.statusCode != 200) {
throw Exception('Login poll failed (HTTP ${response.statusCode}).');
}
final data = jsonDecode(response.body);
final server = data['server'] as String?;
final loginName = data['loginName'] as String?;
final appPassword = data['appPassword'] as String?;
if (server == null || loginName == null || appPassword == null) {
throw Exception('Server response did not include app credentials.');
}
return LoginFlowResult(
serverUrl: server,
loginName: loginName,
appPassword: appPassword,
);
}
}
+383 -87
View File
@@ -1,5 +1,6 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:xml/xml.dart' as xml;
@@ -8,24 +9,49 @@ import '../models/nextcloud_item.dart';
extension XmlElementHelper on xml.XmlNode {
Iterable<xml.XmlElement> findLocalChildren(String localName) {
return children.whereType<xml.XmlElement>().where(
(e) => e.name.local.toLowerCase() == localName.toLowerCase(),
);
(e) => e.name.local.toLowerCase() == localName.toLowerCase(),
);
}
Iterable<xml.XmlElement> findLocalDescendants(String localName) {
if (this is xml.XmlDocument) {
return (this as xml.XmlDocument).descendants.whereType<xml.XmlElement>().where(
(e) => e.name.local.toLowerCase() == localName.toLowerCase(),
);
return (this as xml.XmlDocument).descendants
.whereType<xml.XmlElement>()
.where((e) => e.name.local.toLowerCase() == localName.toLowerCase());
} else if (this is xml.XmlElement) {
return (this as xml.XmlElement).descendants.whereType<xml.XmlElement>().where(
(e) => e.name.local.toLowerCase() == localName.toLowerCase(),
);
return (this as xml.XmlElement).descendants
.whereType<xml.XmlElement>()
.where((e) => e.name.local.toLowerCase() == localName.toLowerCase());
}
return [];
}
}
/// WebDAV date props (`getlastmodified`, `creationdate`) come back as RFC 1123
/// dates (e.g. "Mon, 01 Jan 2024 00:00:00 GMT"), which [DateTime.tryParse]
/// can't read since it only understands ISO 8601. Fall back to [HttpDate].
DateTime? _parseDavDate(String? raw) {
if (raw == null || raw.isEmpty) return null;
final iso = DateTime.tryParse(raw);
if (iso != null) return iso;
try {
return HttpDate.parse(raw);
} catch (_) {
return null;
}
}
/// Normalizes a WebDAV `href` (which servers may return as either a bare
/// path or a full absolute URL) down to just its path, trailing slash
/// stripped, so hrefs from either form can be compared directly.
String _davPath(String value) {
var path = Uri.parse(value.trim()).path;
if (path.endsWith('/') && path.length > 1) {
path = path.substring(0, path.length - 1);
}
return path;
}
class NextcloudService {
final String serverUrl;
final String username;
@@ -58,6 +84,44 @@ class NextcloudService {
};
}
/// Auth headers usable directly by widgets that fetch content themselves
/// (e.g. `Image.network(url, headers: service.authHeaders)`).
Map<String, String> get authHeaders => _headers;
/// The direct WebDAV download URL for a file at [itemPath].
String fileUrl(String itemPath) {
var cleanPath = itemPath.trim();
if (!cleanPath.startsWith('/')) cleanPath = '/$cleanPath';
return '$_cleanServerUrl/remote.php/dav/files/$username$cleanPath';
}
/// Downloads the file at [itemPath] to [savePath], reporting progress.
Future<void> downloadToFile(
String itemPath,
String savePath, {
void Function(int received, int total)? onProgress,
}) async {
final dio = Dio();
await dio.download(
fileUrl(itemPath),
savePath,
options: Options(headers: _headers),
onReceiveProgress: onProgress,
);
}
/// Fetches the raw bytes of a file (used for in-app text/PDF previews).
Future<List<int>> fetchBytes(String itemPath) async {
final response = await http.get(
Uri.parse(fileUrl(itemPath)),
headers: _headers,
);
if (response.statusCode != 200) {
throw Exception('Failed to download file. HTTP ${response.statusCode}');
}
return response.bodyBytes;
}
Future<bool> testConnection() async {
try {
final davPath = '$_cleanServerUrl/remote.php/dav/files/$username/';
@@ -75,7 +139,9 @@ class NextcloudService {
</d:prop>
</d:propfind>''';
final streamed = await http.Client().send(request);
debugPrint('[Nextcloud Test] Connection response HTTP status: ${streamed.statusCode}');
debugPrint(
'[Nextcloud Test] Connection response HTTP status: ${streamed.statusCode}',
);
if (streamed.statusCode == 207 || streamed.statusCode == 200) {
return true;
@@ -83,7 +149,9 @@ class NextcloudService {
// Try fallback endpoint /remote.php/webdav/
final legacyPath = '$_cleanServerUrl/remote.php/webdav/';
debugPrint('[Nextcloud Test] Testing legacy WebDAV endpoint: $legacyPath');
debugPrint(
'[Nextcloud Test] Testing legacy WebDAV endpoint: $legacyPath',
);
final req2 = http.Request('PROPFIND', Uri.parse(legacyPath))
..headers.addAll({
..._headers,
@@ -91,7 +159,9 @@ class NextcloudService {
'Content-Type': 'application/xml',
});
final st2 = await http.Client().send(req2);
debugPrint('[Nextcloud Test] Legacy WebDAV response HTTP status: ${st2.statusCode}');
debugPrint(
'[Nextcloud Test] Legacy WebDAV response HTTP status: ${st2.statusCode}',
);
if (st2.statusCode == 207 || st2.statusCode == 200) {
return true;
}
@@ -106,7 +176,9 @@ class NextcloudService {
} catch (e) {
debugPrint('[Nextcloud Test] Error: $e');
final str = e.toString();
if (str.contains('XMLHttpRequest') || str.contains('ClientException') || str.contains('Failed to fetch')) {
if (str.contains('XMLHttpRequest') ||
str.contains('ClientException') ||
str.contains('Failed to fetch')) {
throw Exception(
'Browser CORS Policy Blocked: The web browser blocked the connection preflight request to $_cleanServerUrl. '
'To bypass browser CORS, run the application as a native Windows app (flutter run -d windows) '
@@ -134,15 +206,17 @@ class NextcloudService {
});
const body = '''<?xml version="1.0" encoding="utf-8" ?>
<d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
<d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns" xmlns:nc="http://nextcloud.org/ns">
<d:prop>
<d:getlastmodified/>
<d:creationdate/>
<d:getcontentlength/>
<d:getcontenttype/>
<d:resourcetype/>
<oc:favorite/>
<oc:fileid/>
<oc:size/>
<nc:mount-type/>
</d:prop>
</d:propfind>''';
@@ -151,11 +225,16 @@ class NextcloudService {
var streamedResponse = await http.Client().send(request);
var responseBody = await streamedResponse.stream.bytesToString();
debugPrint('[Nextcloud DAV] PROPFIND primary URL status: ${streamedResponse.statusCode}, bytes: ${responseBody.length}');
debugPrint(
'[Nextcloud DAV] PROPFIND primary URL status: ${streamedResponse.statusCode}, bytes: ${responseBody.length}',
);
if (streamedResponse.statusCode != 207 && streamedResponse.statusCode != 200) {
if (streamedResponse.statusCode != 207 &&
streamedResponse.statusCode != 200) {
final fallbackUrl = '$_cleanServerUrl/remote.php/webdav$cleanPath';
debugPrint('[Nextcloud DAV] Primary URL failed (${streamedResponse.statusCode}). Trying fallback: $fallbackUrl');
debugPrint(
'[Nextcloud DAV] Primary URL failed (${streamedResponse.statusCode}). Trying fallback: $fallbackUrl',
);
final req2 = http.Request('PROPFIND', Uri.parse(fallbackUrl))
..headers.addAll({
..._headers,
@@ -165,51 +244,207 @@ class NextcloudService {
..body = body;
final res2 = await http.Client().send(req2);
final body2 = await res2.stream.bytesToString();
debugPrint('[Nextcloud DAV] Fallback URL response status: ${res2.statusCode}, bytes: ${body2.length}');
debugPrint(
'[Nextcloud DAV] Fallback URL response status: ${res2.statusCode}, bytes: ${body2.length}',
);
if (res2.statusCode == 207 || res2.statusCode == 200) {
streamedResponse = res2;
responseBody = body2;
} else {
throw Exception('Failed to load directory $cleanPath. HTTP ${streamedResponse.statusCode}');
throw Exception(
'Failed to load directory $cleanPath. HTTP ${streamedResponse.statusCode}',
);
}
}
final document = xml.XmlDocument.parse(responseBody);
final responses = document.findLocalDescendants('response');
debugPrint('[Nextcloud DAV] Found ${responses.length} response nodes in XML');
debugPrint(
'[Nextcloud DAV] Found ${responses.length} response nodes in XML',
);
List<NextcloudItem> items = [];
for (var res in responses) {
final hrefNode = res.findLocalChildren('href').firstOrNull ?? res.findLocalDescendants('href').firstOrNull;
final hrefNode =
res.findLocalChildren('href').firstOrNull ??
res.findLocalDescendants('href').firstOrNull;
final href = hrefNode?.innerText ?? '';
var normalizedHref = Uri.decodeFull(href).trim();
if (normalizedHref.endsWith('/') && normalizedHref.length > 1) {
normalizedHref = normalizedHref.substring(0, normalizedHref.length - 1);
}
var targetDav = '$_cleanServerUrl/remote.php/dav/files/$username$cleanPath'.trim();
if (targetDav.endsWith('/') && targetDav.length > 1) {
targetDav = targetDav.substring(0, targetDav.length - 1);
}
var targetLegacy = '$_cleanServerUrl/remote.php/webdav$cleanPath'.trim();
if (targetLegacy.endsWith('/') && targetLegacy.length > 1) {
targetLegacy = targetLegacy.substring(0, targetLegacy.length - 1);
}
// Servers may return `href` as either a server-relative path or a full
// absolute URL; compare on path only so both forms line up.
final hrefPath = _davPath(Uri.decodeFull(href));
final targetDavPath = _davPath(
'$_cleanServerUrl/remote.php/dav/files/$username$cleanPath',
);
final targetLegacyPath = _davPath(
'$_cleanServerUrl/remote.php/webdav$cleanPath',
);
// Skip current root directory entry itself
if (normalizedHref == targetDav ||
normalizedHref == targetLegacy ||
normalizedHref.endsWith('/remote.php/dav/files/$username') ||
normalizedHref.endsWith('/remote.php/webdav')) {
if (hrefPath == targetDavPath ||
hrefPath == targetLegacyPath ||
hrefPath.endsWith('/remote.php/dav/files/$username') ||
hrefPath.endsWith('/remote.php/webdav')) {
continue;
}
final props = res.findLocalDescendants('prop');
if (props.isEmpty) continue;
bool isCollection = false;
String? sizeStr;
String? lastModStr;
String? createdStr;
String? mimeType;
bool isFav = false;
String? fileId;
String? mountType;
for (var prop in props) {
if (!isCollection) {
final resTypeNode = prop
.findLocalChildren('resourcetype')
.firstOrNull;
if (resTypeNode != null &&
resTypeNode.findLocalChildren('collection').isNotEmpty) {
isCollection = true;
}
}
sizeStr ??=
prop.findLocalChildren('size').firstOrNull?.innerText ??
prop.findLocalChildren('getcontentlength').firstOrNull?.innerText;
lastModStr ??= prop
.findLocalChildren('getlastmodified')
.firstOrNull
?.innerText;
createdStr ??= prop
.findLocalChildren('creationdate')
.firstOrNull
?.innerText;
mimeType ??= prop
.findLocalChildren('getcontenttype')
.firstOrNull
?.innerText;
if (!isFav) {
isFav =
prop.findLocalChildren('favorite').firstOrNull?.innerText == '1';
}
fileId ??= prop.findLocalChildren('fileid').firstOrNull?.innerText;
mountType ??= prop
.findLocalChildren('mount-type')
.firstOrNull
?.innerText;
}
final name = Uri.decodeFull(
href.split('/').where((s) => s.isNotEmpty).last,
);
if (name.isEmpty) continue;
final size = int.tryParse(sizeStr ?? '0') ?? 0;
final lastMod = _parseDavDate(lastModStr) ?? DateTime.now();
final created = _parseDavDate(createdStr);
final itemType = NextcloudItem.deduceType(name, isCollection, mimeType);
final validId = (fileId != null && fileId.isNotEmpty) ? fileId : name;
items.add(
NextcloudItem(
id: validId,
name: name,
path: '$cleanPath$name',
type: itemType,
size: size,
lastModified: lastMod,
dateCreated: created,
isFavorite: isFav,
mimeType: mimeType,
previewUrl:
'$_cleanServerUrl/core/preview?fileId=$validId&x=500&y=500',
mountType: mountType,
),
);
}
debugPrint(
'[Nextcloud DAV] Successfully parsed ${items.length} items from directory $cleanPath',
);
return items;
}
/// Searches the whole file tree by name using the WebDAV SEARCH-REPORT
/// extension (supported by Nextcloud/ownCloud), rather than just the
/// currently open folder.
Future<List<NextcloudItem>> searchFiles(String query) async {
final term = query.trim();
if (term.isEmpty) return [];
final url = '$_cleanServerUrl/remote.php/dav/';
debugPrint('[Nextcloud DAV] SEARCH "$term" from $url');
final escaped = term
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;');
final body =
'''<?xml version="1.0" encoding="utf-8" ?>
<d:searchrequest xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
<d:basicsearch>
<d:select>
<d:prop>
<d:displayname/>
<d:getcontentlength/>
<d:getlastmodified/>
<d:getcontenttype/>
<d:resourcetype/>
<oc:favorite/>
<oc:fileid/>
</d:prop>
</d:select>
<d:from>
<d:scope>
<d:href>/files/$username</d:href>
<d:depth>infinity</d:depth>
</d:scope>
</d:from>
<d:where>
<d:like>
<d:prop><d:displayname/></d:prop>
<d:literal>%$escaped%</d:literal>
</d:like>
</d:where>
<d:orderby/>
</d:basicsearch>
</d:searchrequest>''';
final request = http.Request('SEARCH', Uri.parse(url))
..headers.addAll({..._headers, 'Content-Type': 'text/xml'})
..body = body;
final streamed = await http.Client().send(request);
final responseBody = await streamed.stream.bytesToString();
debugPrint(
'[Nextcloud DAV] SEARCH status: ${streamed.statusCode}, bytes: ${responseBody.length}',
);
if (streamed.statusCode != 207 && streamed.statusCode != 200) {
throw Exception('Search failed. HTTP ${streamed.statusCode}');
}
final document = xml.XmlDocument.parse(responseBody);
final responses = document.findLocalDescendants('response');
final results = <NextcloudItem>[];
for (var res in responses) {
final hrefNode =
res.findLocalChildren('href').firstOrNull ??
res.findLocalDescendants('href').firstOrNull;
final href = hrefNode?.innerText ?? '';
if (href.isEmpty) continue;
final props = res.findLocalDescendants('prop');
if (props.isEmpty) continue;
bool isCollection = false;
String? sizeStr;
String? lastModStr;
@@ -219,44 +454,73 @@ class NextcloudService {
for (var prop in props) {
if (!isCollection) {
final resTypeNode = prop.findLocalChildren('resourcetype').firstOrNull;
if (resTypeNode != null && resTypeNode.findLocalChildren('collection').isNotEmpty) {
final resTypeNode = prop
.findLocalChildren('resourcetype')
.firstOrNull;
if (resTypeNode != null &&
resTypeNode.findLocalChildren('collection').isNotEmpty) {
isCollection = true;
}
}
sizeStr ??= prop.findLocalChildren('size').firstOrNull?.innerText ??
prop.findLocalChildren('getcontentlength').firstOrNull?.innerText;
lastModStr ??= prop.findLocalChildren('getlastmodified').firstOrNull?.innerText;
mimeType ??= prop.findLocalChildren('getcontenttype').firstOrNull?.innerText;
sizeStr ??= prop
.findLocalChildren('getcontentlength')
.firstOrNull
?.innerText;
lastModStr ??= prop
.findLocalChildren('getlastmodified')
.firstOrNull
?.innerText;
mimeType ??= prop
.findLocalChildren('getcontenttype')
.firstOrNull
?.innerText;
if (!isFav) {
isFav = prop.findLocalChildren('favorite').firstOrNull?.innerText == '1';
isFav =
prop.findLocalChildren('favorite').firstOrNull?.innerText == '1';
}
fileId ??= prop.findLocalChildren('fileid').firstOrNull?.innerText;
}
final name = Uri.decodeFull(href.split('/').where((s) => s.isNotEmpty).last);
var decodedHref = Uri.decodeFull(href);
if (decodedHref.endsWith('/') && decodedHref.length > 1) {
decodedHref = decodedHref.substring(0, decodedHref.length - 1);
}
final name = decodedHref.split('/').where((s) => s.isNotEmpty).last;
if (name.isEmpty) continue;
// Strip the DAV root prefix so `path` matches what fetchDirectory produces.
final marker = '/files/$username';
final markerIndex = decodedHref.indexOf(marker);
final itemPath = markerIndex >= 0
? decodedHref.substring(markerIndex + marker.length)
: decodedHref;
if (itemPath.isEmpty) continue;
final size = int.tryParse(sizeStr ?? '0') ?? 0;
final lastMod = lastModStr != null ? DateTime.tryParse(lastModStr) ?? DateTime.now() : DateTime.now();
final lastMod = _parseDavDate(lastModStr) ?? DateTime.now();
final itemType = NextcloudItem.deduceType(name, isCollection, mimeType);
final validId = (fileId != null && fileId.isNotEmpty) ? fileId : name;
items.add(NextcloudItem(
id: validId,
name: name,
path: '$cleanPath$name',
type: itemType,
size: size,
lastModified: lastMod,
isFavorite: isFav,
mimeType: mimeType,
previewUrl: '$_cleanServerUrl/core/preview?fileId=$validId&x=500&y=500',
));
results.add(
NextcloudItem(
id: validId,
name: name,
path: itemPath,
type: itemType,
size: size,
lastModified: lastMod,
isFavorite: isFav,
mimeType: mimeType,
previewUrl:
'$_cleanServerUrl/core/preview?fileId=$validId&x=500&y=500',
),
);
}
debugPrint('[Nextcloud DAV] Successfully parsed ${items.length} items from directory $cleanPath');
return items;
debugPrint(
'[Nextcloud DAV] Search returned ${results.length} results for "$term"',
);
return results;
}
Future<NextcloudUserQuota> fetchUserQuota() async {
@@ -264,7 +528,9 @@ class NextcloudService {
debugPrint('[Nextcloud OCS] Fetching user quota from $url');
final response = await http.get(Uri.parse(url), headers: _headers);
debugPrint('[Nextcloud OCS] User quota response status: ${response.statusCode}');
debugPrint(
'[Nextcloud OCS] User quota response status: ${response.statusCode}',
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
@@ -287,17 +553,22 @@ class NextcloudService {
serverVersion: 'Nextcloud Server',
);
} else {
throw Exception('Failed to fetch user quota. HTTP ${response.statusCode}');
throw Exception(
'Failed to fetch user quota. HTTP ${response.statusCode}',
);
}
}
Future<List<NextcloudActivity>> fetchActivities() async {
try {
final url = '$_cleanServerUrl/ocs/v2.php/apps/activity/api/v2/activity?format=json';
final url =
'$_cleanServerUrl/ocs/v2.php/apps/activity/api/v2/activity?format=json';
debugPrint('[Nextcloud OCS] Fetching activity feed from $url');
final response = await http.get(Uri.parse(url), headers: _headers);
debugPrint('[Nextcloud OCS] Activity response status: ${response.statusCode}');
debugPrint(
'[Nextcloud OCS] Activity response status: ${response.statusCode}',
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
@@ -314,7 +585,9 @@ class NextcloudService {
id: (a['activity_id'] ?? '').toString(),
title: a['subject'] ?? 'Server Activity',
subject: a['message'] ?? (a['subject'] ?? ''),
timestamp: DateTime.fromMillisecondsSinceEpoch((a['timestamp'] as int? ?? 0) * 1000),
timestamp: DateTime.fromMillisecondsSinceEpoch(
(a['timestamp'] as int? ?? 0) * 1000,
),
icon: Icons.cloud_outlined,
author: a['user'] ?? username,
);
@@ -326,24 +599,42 @@ class NextcloudService {
return [];
}
Future<bool> uploadFile(String folderPath, String fileName, Uint8List fileBytes) async {
/// Uploads a file from disk, streaming it so large files don't need to be
/// buffered fully in memory, with progress reporting.
Future<bool> uploadFileFromPath(
String folderPath,
String fileName,
String localFilePath, {
void Function(int sent, int total)? onProgress,
}) async {
var cleanPath = folderPath.trim();
if (!cleanPath.startsWith('/')) cleanPath = '/$cleanPath';
if (!cleanPath.endsWith('/')) cleanPath = '$cleanPath/';
final url = '$_cleanServerUrl/remote.php/dav/files/$username$cleanPath$fileName';
debugPrint('[Nextcloud DAV] Uploading file to $url');
final url =
'$_cleanServerUrl/remote.php/dav/files/$username$cleanPath$fileName';
debugPrint('[Nextcloud DAV] Streaming upload to $url');
final response = await http.put(
Uri.parse(url),
headers: {
..._headers,
'Content-Type': 'application/octet-stream',
},
body: fileBytes,
final file = File(localFilePath);
final length = await file.length();
final dio = Dio();
final response = await dio.put<void>(
url,
data: file.openRead(),
options: Options(
headers: {..._headers, Headers.contentLengthHeader: length},
contentType: 'application/octet-stream',
),
onSendProgress: onProgress,
);
debugPrint('[Nextcloud DAV] Upload status: ${response.statusCode}');
return response.statusCode == 201 || response.statusCode == 204 || response.statusCode == 200;
debugPrint(
'[Nextcloud DAV] Streaming upload status: ${response.statusCode}',
);
return response.statusCode == 201 ||
response.statusCode == 204 ||
response.statusCode == 200;
}
Future<bool> deleteItem(String itemPath) async {
@@ -363,16 +654,21 @@ class NextcloudService {
if (!cleanPath.startsWith('/')) cleanPath = '/$cleanPath';
if (!cleanPath.endsWith('/')) cleanPath = '$cleanPath/';
final url = '$_cleanServerUrl/remote.php/dav/files/$username$cleanPath$folderName';
final url =
'$_cleanServerUrl/remote.php/dav/files/$username$cleanPath$folderName';
debugPrint('[Nextcloud DAV] Creating folder at $url');
final request = http.Request('MKCOL', Uri.parse(url))..headers.addAll(_headers);
final request = http.Request('MKCOL', Uri.parse(url))
..headers.addAll(_headers);
final response = await http.Client().send(request);
debugPrint('[Nextcloud DAV] Create folder status: ${response.statusCode}');
return response.statusCode == 201;
}
Future<bool> toggleFavorite(String itemPath, bool currentFavoriteState) async {
Future<bool> toggleFavorite(
String itemPath,
bool currentFavoriteState,
) async {
var cleanPath = itemPath.trim();
if (!cleanPath.startsWith('/')) cleanPath = '/$cleanPath';
@@ -380,7 +676,8 @@ class NextcloudService {
final newFavVal = currentFavoriteState ? '0' : '1';
debugPrint('[Nextcloud DAV] Toggling favorite ($newFavVal) for $url');
final body = '''<?xml version="1.0" encoding="utf-8" ?>
final body =
'''<?xml version="1.0" encoding="utf-8" ?>
<d:propertyupdate xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
<d:set>
<d:prop>
@@ -390,14 +687,13 @@ class NextcloudService {
</d:propertyupdate>''';
final request = http.Request('PROPPATCH', Uri.parse(url))
..headers.addAll({
..._headers,
'Content-Type': 'application/xml',
})
..headers.addAll({..._headers, 'Content-Type': 'application/xml'})
..body = body;
final response = await http.Client().send(request);
debugPrint('[Nextcloud DAV] Toggle favorite status: ${response.statusCode}');
debugPrint(
'[Nextcloud DAV] Toggle favorite status: ${response.statusCode}',
);
return response.statusCode == 207 || response.statusCode == 200;
}
}
+48 -42
View File
@@ -12,35 +12,38 @@ class AppTheme {
Color(0xFF2E7D32), // Emerald Green
];
static ThemeData light(Color seedColor) {
final colorScheme = ColorScheme.fromSeed(
seedColor: seedColor,
brightness: Brightness.light,
);
static ThemeData light(
Color seedColor, {
ColorScheme? dynamicScheme,
bool useDynamicColor = true,
}) {
final colorScheme = (useDynamicColor && dynamicScheme != null)
? dynamicScheme
: ColorScheme.fromSeed(
seedColor: seedColor,
brightness: Brightness.light,
);
return ThemeData(
useMaterial3: true,
brightness: Brightness.light,
colorScheme: colorScheme,
scaffoldBackgroundColor: colorScheme.surface,
textTheme: GoogleFonts.interTextTheme(ThemeData.light().textTheme).copyWith(
headlineMedium: GoogleFonts.inter(
fontWeight: FontWeight.w600,
letterSpacing: -0.5,
),
titleLarge: GoogleFonts.inter(
fontWeight: FontWeight.w600,
letterSpacing: -0.2,
),
titleMedium: GoogleFonts.inter(
fontWeight: FontWeight.w500,
),
),
textTheme: GoogleFonts.interTextTheme(ThemeData.light().textTheme)
.copyWith(
headlineMedium: GoogleFonts.inter(
fontWeight: FontWeight.w600,
letterSpacing: -0.5,
),
titleLarge: GoogleFonts.inter(
fontWeight: FontWeight.w600,
letterSpacing: -0.2,
),
titleMedium: GoogleFonts.inter(fontWeight: FontWeight.w500),
),
cardTheme: CardThemeData(
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
color: colorScheme.surfaceContainerLow,
),
appBarTheme: AppBarTheme(
@@ -57,35 +60,38 @@ class AppTheme {
);
}
static ThemeData dark(Color seedColor) {
final colorScheme = ColorScheme.fromSeed(
seedColor: seedColor,
brightness: Brightness.dark,
);
static ThemeData dark(
Color seedColor, {
ColorScheme? dynamicScheme,
bool useDynamicColor = true,
}) {
final colorScheme = (useDynamicColor && dynamicScheme != null)
? dynamicScheme
: ColorScheme.fromSeed(
seedColor: seedColor,
brightness: Brightness.dark,
);
return ThemeData(
useMaterial3: true,
brightness: Brightness.dark,
colorScheme: colorScheme,
scaffoldBackgroundColor: colorScheme.surface,
textTheme: GoogleFonts.interTextTheme(ThemeData.dark().textTheme).copyWith(
headlineMedium: GoogleFonts.inter(
fontWeight: FontWeight.w600,
letterSpacing: -0.5,
),
titleLarge: GoogleFonts.inter(
fontWeight: FontWeight.w600,
letterSpacing: -0.2,
),
titleMedium: GoogleFonts.inter(
fontWeight: FontWeight.w500,
),
),
textTheme: GoogleFonts.interTextTheme(ThemeData.dark().textTheme)
.copyWith(
headlineMedium: GoogleFonts.inter(
fontWeight: FontWeight.w600,
letterSpacing: -0.5,
),
titleLarge: GoogleFonts.inter(
fontWeight: FontWeight.w600,
letterSpacing: -0.2,
),
titleMedium: GoogleFonts.inter(fontWeight: FontWeight.w500),
),
cardTheme: CardThemeData(
elevation: 0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
color: colorScheme.surfaceContainerLow,
),
appBarTheme: AppBarTheme(
+519 -288
View File
@@ -2,11 +2,10 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/server_provider.dart';
import '../theme/app_theme.dart';
import '../widgets/frosted_glass_container.dart';
class AccountView extends StatelessWidget {
final ScrollController scrollController;
const AccountView({super.key, required this.scrollController});
const AccountView({super.key});
String _formatBytes(int bytes) {
if (bytes <= 0) return '0 GB';
@@ -21,298 +20,320 @@ class AccountView extends StatelessWidget {
final provider = context.watch<ServerProvider>();
final quota = provider.quota;
return CustomScrollView(
controller: scrollController,
physics: const BouncingScrollPhysics(),
slivers: [
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 16, 20, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Account & Storage',
style: theme.textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.w700,
return Scaffold(
appBar: AppBar(
title: const Text('Account & Storage'),
actions: [
IconButton(
onPressed: () => _showLogoutConfirmation(context, provider),
icon: const Icon(Icons.logout_rounded),
tooltip: 'Log Out',
color: colorScheme.error,
),
],
),
body: SafeArea(
child: ListView(
padding: const EdgeInsets.fromLTRB(20, 8, 20, 32),
physics: const BouncingScrollPhysics(),
children: [
Text(
'Connected to ${provider.serverUrl}',
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 20),
// User Profile & Storage Card
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: colorScheme.primaryContainer.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(28),
border: Border.all(
color: colorScheme.primary.withValues(alpha: 0.2),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
CircleAvatar(
radius: 28,
backgroundColor: colorScheme.primary,
child: Text(
(quota?.userName ?? provider.username)
.substring(0, 1)
.toUpperCase(),
style: theme.textTheme.headlineSmall?.copyWith(
color: colorScheme.onPrimary,
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
quota?.userName ?? provider.username,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 2),
Text(
quota?.email ?? provider.username,
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 10,
vertical: 4,
),
decoration: BoxDecoration(
color: provider.isLoggedIn
? Colors.green.withValues(alpha: 0.2)
: Colors.red.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(12),
),
child: Text(
provider.isLoggedIn ? 'ONLINE' : 'OFFLINE',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: provider.isLoggedIn
? Colors.green.shade800
: Colors.red.shade800,
),
),
),
],
),
const SizedBox(height: 20),
const Divider(height: 1),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Storage Quota',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w600,
),
),
Text(
quota != null
? (quota.totalBytes > 0
? '${_formatBytes(quota.usedBytes)} of ${_formatBytes(quota.totalBytes)}'
: '${_formatBytes(quota.usedBytes)} (Unlimited)')
: 'Live Server Storage',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
fontWeight: FontWeight.w500,
),
),
],
),
const SizedBox(height: 10),
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: LinearProgressIndicator(
value: quota != null && quota.totalBytes > 0
? quota.usagePercentage
: 0.1,
minHeight: 10,
backgroundColor: colorScheme.surfaceContainerHighest,
valueColor: AlwaysStoppedAnimation<Color>(
colorScheme.primary,
),
),
IconButton.filledTonal(
onPressed: () {
_showLogoutConfirmation(context, provider);
},
icon: const Icon(Icons.logout_rounded),
tooltip: 'Log Out',
style: IconButton.styleFrom(
foregroundColor: colorScheme.error,
backgroundColor: colorScheme.errorContainer.withValues(alpha: 0.5),
),
const SizedBox(height: 8),
Text(
quota != null
? (quota.totalBytes > 0
? '${(quota.usagePercentage * 100).toStringAsFixed(1)}% used'
: 'Unlimited Storage Plan')
: 'WebDAV connection active',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
fontSize: 11,
),
),
],
),
),
const SizedBox(height: 24),
// Server Credentials Section
Text(
'Server Connection Info',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 10),
Card(
child: Column(
children: [
ListTile(
leading: const Icon(Icons.dns_rounded),
title: const Text('Nextcloud Host'),
subtitle: Text(provider.serverUrl),
),
const Divider(height: 1, indent: 16, endIndent: 16),
ListTile(
leading: const Icon(Icons.person_rounded),
title: const Text('Logged In User'),
subtitle: Text(provider.username),
),
const Divider(height: 1, indent: 16, endIndent: 16),
ListTile(
leading: const Icon(Icons.refresh_rounded),
title: const Text('Refresh WebDAV Cache'),
onTap: () async {
await provider.refreshData();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Refreshed WebDAV directory data'),
behavior: SnackBarBehavior.floating,
),
);
}
},
),
],
),
),
const SizedBox(height: 24),
// Material You Design Settings
Text(
'Material You Aesthetics',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 10),
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Accent Color',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 4),
Text(
provider.useDynamicColor
? 'Matching your wallpaper'
: 'Custom color',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_AccentSwatch(
isSelected: provider.useDynamicColor,
onTap: () => provider.setUseDynamicColor(true),
borderColor: colorScheme.onSurface,
background: colorScheme.surfaceContainerHighest,
child: Icon(
Icons.wallpaper_rounded,
color: colorScheme.onSurfaceVariant,
size: 20,
),
),
...AppTheme.seedColors.map((color) {
final isSelected =
!provider.useDynamicColor &&
provider.seedColor == color;
return _AccentSwatch(
isSelected: isSelected,
onTap: () => provider.setSeedColor(color),
borderColor: colorScheme.onSurface,
background: color,
child: isSelected
? const Icon(
Icons.check_rounded,
color: Colors.white,
size: 20,
)
: null,
);
}),
],
),
const SizedBox(height: 20),
const Divider(height: 1),
const SizedBox(height: 16),
Text(
'Theme Mode',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 12),
SizedBox(
width: double.infinity,
child: SegmentedButton<ThemeMode>(
segments: const [
ButtonSegment(
value: ThemeMode.system,
icon: Icon(Icons.brightness_auto_rounded),
label: Text('System'),
),
ButtonSegment(
value: ThemeMode.light,
icon: Icon(Icons.light_mode_rounded),
label: Text('Light'),
),
ButtonSegment(
value: ThemeMode.dark,
icon: Icon(Icons.dark_mode_rounded),
label: Text('Dark'),
),
],
selected: {provider.themeMode},
onSelectionChanged: (set) =>
provider.setThemeMode(set.first),
),
),
],
),
const SizedBox(height: 4),
Text(
'Connected to ${provider.serverUrl}',
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 20),
// User Profile & Storage Card
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: colorScheme.primaryContainer.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(28),
border: Border.all(
color: colorScheme.primary.withValues(alpha: 0.2),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
CircleAvatar(
radius: 28,
backgroundColor: colorScheme.primary,
child: Text(
(quota?.userName ?? provider.username).substring(0, 1).toUpperCase(),
style: theme.textTheme.headlineSmall?.copyWith(
color: colorScheme.onPrimary,
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
quota?.userName ?? provider.username,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 2),
Text(
quota?.email ?? provider.username,
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: provider.isLoggedIn ? Colors.green.withValues(alpha: 0.2) : Colors.red.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(12),
),
child: Text(
provider.isLoggedIn ? 'ONLINE' : 'OFFLINE',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: provider.isLoggedIn ? Colors.green.shade800 : Colors.red.shade800,
),
),
),
],
),
const SizedBox(height: 20),
const Divider(height: 1),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Storage Quota',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w600,
),
),
Text(
quota != null
? (quota.totalBytes > 0
? '${_formatBytes(quota.usedBytes)} of ${_formatBytes(quota.totalBytes)}'
: '${_formatBytes(quota.usedBytes)} (Unlimited)')
: 'Live Server Storage',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
fontWeight: FontWeight.w500,
),
),
],
),
const SizedBox(height: 10),
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: LinearProgressIndicator(
value: quota != null && quota.totalBytes > 0 ? quota.usagePercentage : 0.1,
minHeight: 10,
backgroundColor: colorScheme.surfaceContainerHighest,
valueColor: AlwaysStoppedAnimation<Color>(colorScheme.primary),
),
),
const SizedBox(height: 8),
Text(
quota != null
? (quota.totalBytes > 0
? '${(quota.usagePercentage * 100).toStringAsFixed(1)}% used'
: 'Unlimited Storage Plan')
: 'WebDAV connection active',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
fontSize: 11,
),
),
],
),
),
const SizedBox(height: 24),
// Server Credentials Section
Text(
'Server Connection Info',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 10),
Card(
child: Column(
children: [
ListTile(
leading: const Icon(Icons.dns_rounded),
title: const Text('Nextcloud Host'),
subtitle: Text(provider.serverUrl),
),
const Divider(height: 1, indent: 16, endIndent: 16),
ListTile(
leading: const Icon(Icons.person_rounded),
title: const Text('Logged In User'),
subtitle: Text(provider.username),
),
const Divider(height: 1, indent: 16, endIndent: 16),
ListTile(
leading: const Icon(Icons.refresh_rounded),
title: const Text('Refresh WebDAV Cache'),
onTap: () async {
await provider.refreshData();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Refreshed WebDAV directory data'),
behavior: SnackBarBehavior.floating,
),
);
}
},
),
],
),
),
const SizedBox(height: 24),
// Material You Design Settings
Text(
'Material You Aesthetics',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 10),
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Dynamic Accent Color Seed',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: AppTheme.seedColors.map((color) {
final isSelected = provider.seedColor == color;
return GestureDetector(
onTap: () => provider.setSeedColor(color),
child: Container(
width: 44,
height: 44,
decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
border: isSelected
? Border.all(color: colorScheme.onSurface, width: 3)
: null,
),
child: isSelected
? const Icon(Icons.check_rounded, color: Colors.white, size: 20)
: null,
),
);
}).toList(),
),
const SizedBox(height: 20),
const Divider(height: 1),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Theme Mode',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w600,
),
),
SegmentedButton<ThemeMode>(
segments: const [
ButtonSegment(
value: ThemeMode.system,
icon: Icon(Icons.brightness_auto_rounded),
label: Text('System'),
),
ButtonSegment(
value: ThemeMode.light,
icon: Icon(Icons.light_mode_rounded),
label: Text('Light'),
),
ButtonSegment(
value: ThemeMode.dark,
icon: Icon(Icons.dark_mode_rounded),
label: Text('Dark'),
),
],
selected: {provider.themeMode},
onSelectionChanged: (set) => provider.setThemeMode(set.first),
),
],
),
],
),
),
),
],
),
),
),
),
const SizedBox(height: 24),
const SliverToBoxAdapter(
child: SizedBox(height: 100),
// UI Settings
Text(
'UI',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 10),
const _BottomBarAppearanceCard(),
],
),
],
),
);
}
@@ -322,7 +343,9 @@ class AccountView extends StatelessWidget {
builder: (context) {
return AlertDialog(
title: const Text('Log Out'),
content: Text('Are you sure you want to disconnect from ${provider.serverUrl}?'),
content: Text(
'Are you sure you want to disconnect from ${provider.serverUrl}?',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
@@ -333,7 +356,7 @@ class AccountView extends StatelessWidget {
backgroundColor: Theme.of(context).colorScheme.error,
),
onPressed: () {
Navigator.pop(context);
Navigator.of(context).popUntil((route) => route.isFirst);
provider.logout();
},
child: const Text('Log Out'),
@@ -344,3 +367,211 @@ class AccountView extends StatelessWidget {
);
}
}
class _BottomBarAppearanceCard extends StatefulWidget {
const _BottomBarAppearanceCard();
@override
State<_BottomBarAppearanceCard> createState() =>
_BottomBarAppearanceCardState();
}
class _BottomBarAppearanceCardState extends State<_BottomBarAppearanceCard> {
// Mirrors the provider values locally so the slider thumb and the live
// preview track the drag gesture on every frame. Driving them straight off
// `provider.bottomBar*` instead would tie the slider's own responsiveness
// to a full Provider-wide rebuild — including the expensive BackdropFilter
// blur in the preview — which can't keep up with fast drag ticks and makes
// the thumb appear stuck until the next unrelated rebuild.
double? _opacity;
double? _blur;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final provider = context.watch<ServerProvider>();
final opacity = _opacity ?? provider.bottomBarOpacity;
final blur = _blur ?? provider.bottomBarBlur;
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Bottom Bar Appearance',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 4),
Text(
'Adjust the glass effect of the floating bottom bar',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 16),
// Live preview
Container(
height: 140,
width: double.infinity,
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
colorScheme.primary,
colorScheme.tertiary,
colorScheme.secondary,
],
),
),
child: Stack(
children: [
Positioned.fill(
child: CustomPaint(painter: _PreviewPatternPainter()),
),
Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.only(bottom: 16),
child: FrostedGlassContainer(
opacity: opacity,
blurSigma: blur,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 18,
vertical: 12,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.folder_rounded,
color: colorScheme.onSurfaceVariant,
),
const SizedBox(width: 16),
Icon(
Icons.photo_library_rounded,
color: colorScheme.onSurfaceVariant,
),
const SizedBox(width: 16),
Icon(
Icons.history_rounded,
color: colorScheme.onSurfaceVariant,
),
],
),
),
),
),
),
],
),
),
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Opacity', style: theme.textTheme.bodyMedium),
Text(
'${(opacity * 100).round()}%',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
Slider(
value: opacity,
min: 0.1,
max: 1.0,
onChanged: (value) => setState(() => _opacity = value),
onChangeEnd: provider.setBottomBarOpacity,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Blur', style: theme.textTheme.bodyMedium),
Text(
blur.round().toString(),
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
Slider(
value: blur,
min: 0,
max: 40,
onChanged: (value) => setState(() => _blur = value),
onChangeEnd: provider.setBottomBarBlur,
),
],
),
),
);
}
}
class _PreviewPatternPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.white.withValues(alpha: 0.25)
..style = PaintingStyle.stroke
..strokeWidth = 10;
for (var x = -size.height; x < size.width; x += 24) {
canvas.drawLine(
Offset(x, size.height),
Offset(x + size.height, 0),
paint,
);
}
}
@override
bool shouldRepaint(covariant _PreviewPatternPainter oldDelegate) => false;
}
class _AccentSwatch extends StatelessWidget {
final bool isSelected;
final VoidCallback onTap;
final Color borderColor;
final Color background;
final Widget? child;
const _AccentSwatch({
required this.isSelected,
required this.onTap,
required this.borderColor,
required this.background,
this.child,
});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: Container(
width: 44,
height: 44,
decoration: BoxDecoration(
color: background,
shape: BoxShape.circle,
border: isSelected ? Border.all(color: borderColor, width: 3) : null,
),
child: child,
),
);
}
}
+89 -102
View File
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../providers/server_provider.dart';
import '../widgets/profile_avatar_button.dart';
class ActivityView extends StatelessWidget {
final ScrollController scrollController;
@@ -19,29 +20,16 @@ class ActivityView extends StatelessWidget {
controller: scrollController,
physics: const BouncingScrollPhysics(),
slivers: [
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 16, 20, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Activity Log',
style: theme.textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 4),
Text(
'Real-time server sync & file events',
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
SliverAppBar(
pinned: true,
expandedHeight: kToolbarHeight,
collapsedHeight: kToolbarHeight,
backgroundColor: colorScheme.surface,
surfaceTintColor: colorScheme.surface,
scrolledUnderElevation: 0,
actions: const [ProfileAvatarButton()],
),
const SliverToBoxAdapter(child: SizedBox(height: 8)),
if (activities.isEmpty)
SliverFillRemaining(
@@ -58,93 +46,92 @@ class ActivityView extends StatelessWidget {
SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: 20),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final act = activities[index];
delegate: SliverChildBuilderDelegate((context, index) {
final act = activities[index];
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: colorScheme.outlineVariant.withValues(alpha: 0.2),
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: colorScheme.outlineVariant.withValues(
alpha: 0.2,
),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: colorScheme.primaryContainer,
shape: BoxShape.circle,
),
child: Icon(
act.icon,
color: colorScheme.onPrimaryContainer,
size: 20,
),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
act.title,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
fontSize: 14,
),
),
Text(
DateFormat.jm().format(act.timestamp),
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
fontSize: 11,
),
),
],
),
const SizedBox(height: 4),
Text(
act.subject,
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
fontSize: 13,
),
),
const SizedBox(height: 6),
Text(
'By ${act.author} • ${DateFormat.MMMd().format(act.timestamp)}',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.primary,
fontWeight: FontWeight.w500,
fontSize: 11,
),
),
],
),
),
],
),
),
);
},
childCount: activities.length,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: colorScheme.primaryContainer,
shape: BoxShape.circle,
),
child: Icon(
act.icon,
color: colorScheme.onPrimaryContainer,
size: 20,
),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
act.title,
style: theme.textTheme.titleMedium
?.copyWith(
fontWeight: FontWeight.w600,
fontSize: 14,
),
),
Text(
DateFormat.jm().format(act.timestamp),
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
fontSize: 11,
),
),
],
),
const SizedBox(height: 4),
Text(
act.subject,
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
fontSize: 13,
),
),
const SizedBox(height: 6),
Text(
'By ${act.author} • ${DateFormat.MMMd().format(act.timestamp)}',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.primary,
fontWeight: FontWeight.w500,
fontSize: 11,
),
),
],
),
),
],
),
),
);
}, childCount: activities.length),
),
),
const SliverToBoxAdapter(
child: SizedBox(height: 100),
),
const SliverToBoxAdapter(child: SizedBox(height: 100)),
],
);
}
File diff suppressed because it is too large Load Diff
+944 -338
View File
File diff suppressed because it is too large Load Diff
+223 -211
View File
@@ -11,40 +11,18 @@ class LoginView extends StatefulWidget {
class _LoginViewState extends State<LoginView> {
final _formKey = GlobalKey<FormState>();
final _urlController = TextEditingController(text: 'https://');
final _userController = TextEditingController();
final _passController = TextEditingController();
bool _obscurePassword = true;
final _urlController = TextEditingController();
@override
void dispose() {
_urlController.dispose();
_userController.dispose();
_passController.dispose();
super.dispose();
}
void _handleLogin() async {
void _handleContinue() {
if (!_formKey.currentState!.validate()) return;
FocusScope.of(context).unfocus();
final provider = context.read<ServerProvider>();
final success = await provider.login(
serverUrl: _urlController.text.trim(),
username: _userController.text.trim(),
password: _passController.text,
);
if (!success && mounted) {
final error = provider.errorMessage ?? 'Failed to connect to Nextcloud server.';
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(error),
backgroundColor: Theme.of(context).colorScheme.error,
behavior: SnackBarBehavior.floating,
),
);
}
context.read<ServerProvider>().startLoginFlow(_urlController.text.trim());
}
@override
@@ -53,6 +31,10 @@ class _LoginViewState extends State<LoginView> {
final colorScheme = theme.colorScheme;
final provider = context.watch<ServerProvider>();
final isAwaitingBrowser =
provider.loginFlowStatus == LoginFlowStatus.awaitingBrowser;
final isInitiating = provider.loginFlowStatus == LoginFlowStatus.initiating;
return Scaffold(
body: SafeArea(
child: Center(
@@ -61,193 +43,23 @@ class _LoginViewState extends State<LoginView> {
padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 24),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 440),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Header Logo & Branding
Center(
child: Container(
width: 80,
height: 80,
decoration: BoxDecoration(
color: colorScheme.primaryContainer,
shape: BoxShape.circle,
),
child: Icon(
Icons.cloud_outlined,
size: 44,
color: colorScheme.onPrimaryContainer,
),
),
child: isAwaitingBrowser
? _WaitingForBrowser(
onCancel: () => provider.cancelLoginFlow(),
onReopenBrowser: provider.reopenLoginBrowser,
)
: _ServerForm(
formKey: _formKey,
urlController: _urlController,
isLoading: isInitiating || provider.isLoading,
errorMessage:
provider.loginFlowStatus == LoginFlowStatus.error
? provider.errorMessage
: null,
onContinue: _handleContinue,
theme: theme,
colorScheme: colorScheme,
),
const SizedBox(height: 24),
Text(
'Nextcloud Client',
textAlign: TextAlign.center,
style: theme.textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.w800,
letterSpacing: -0.5,
),
),
const SizedBox(height: 6),
Text(
'Log in to your selfhosted Nextcloud server',
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 36),
// Error Box if any
if (provider.errorMessage != null)
Container(
margin: const EdgeInsets.only(bottom: 20),
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: colorScheme.errorContainer,
borderRadius: BorderRadius.circular(16),
),
child: Row(
children: [
Icon(
Icons.error_outline_rounded,
color: colorScheme.onErrorContainer,
size: 20,
),
const SizedBox(width: 12),
Expanded(
child: Text(
provider.errorMessage!,
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onErrorContainer,
fontWeight: FontWeight.w500,
),
),
),
],
),
),
// Server URL Input
TextFormField(
controller: _urlController,
keyboardType: TextInputType.url,
decoration: InputDecoration(
labelText: 'Server Address',
hintText: 'https://cloud.example.com',
prefixIcon: const Icon(Icons.dns_outlined),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
),
filled: true,
fillColor: colorScheme.surfaceContainerLow,
),
validator: (val) {
if (val == null || val.trim().isEmpty || val == 'https://') {
return 'Please enter your Nextcloud server URL';
}
return null;
},
),
const SizedBox(height: 16),
// Username Input
TextFormField(
controller: _userController,
decoration: InputDecoration(
labelText: 'Username',
prefixIcon: const Icon(Icons.person_outline_rounded),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
),
filled: true,
fillColor: colorScheme.surfaceContainerLow,
),
validator: (val) {
if (val == null || val.trim().isEmpty) {
return 'Please enter your username';
}
return null;
},
),
const SizedBox(height: 16),
// Password / App Password Input
TextFormField(
controller: _passController,
obscureText: _obscurePassword,
decoration: InputDecoration(
labelText: 'Password or App Password',
prefixIcon: const Icon(Icons.lock_outline_rounded),
suffixIcon: IconButton(
icon: Icon(
_obscurePassword ? Icons.visibility_off_outlined : Icons.visibility_outlined,
),
onPressed: () {
setState(() {
_obscurePassword = !_obscurePassword;
});
},
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
),
filled: true,
fillColor: colorScheme.surfaceContainerLow,
),
validator: (val) {
if (val == null || val.isEmpty) {
return 'Please enter your password or app password';
}
return null;
},
),
const SizedBox(height: 28),
// Login Button
SizedBox(
height: 54,
child: FilledButton(
onPressed: provider.isLoading ? null : _handleLogin,
style: FilledButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(27),
),
),
child: provider.isLoading
? SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(
strokeWidth: 2.5,
color: colorScheme.onPrimary,
),
)
: const Text(
'Log In',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
),
const SizedBox(height: 24),
Text(
'Supports standard WebDAV and OCS APIs for all self-hosted Nextcloud Hub installations.',
textAlign: TextAlign.center,
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
fontSize: 11,
),
),
],
),
),
),
),
),
@@ -255,3 +67,203 @@ class _LoginViewState extends State<LoginView> {
);
}
}
class _ServerForm extends StatelessWidget {
final GlobalKey<FormState> formKey;
final TextEditingController urlController;
final bool isLoading;
final String? errorMessage;
final VoidCallback onContinue;
final ThemeData theme;
final ColorScheme colorScheme;
const _ServerForm({
required this.formKey,
required this.urlController,
required this.isLoading,
required this.errorMessage,
required this.onContinue,
required this.theme,
required this.colorScheme,
});
@override
Widget build(BuildContext context) {
return Form(
key: formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Center(
child: Container(
width: 80,
height: 80,
decoration: BoxDecoration(
color: colorScheme.primaryContainer,
shape: BoxShape.circle,
),
child: Icon(
Icons.cloud_outlined,
size: 44,
color: colorScheme.onPrimaryContainer,
),
),
),
const SizedBox(height: 24),
Text(
'Noo',
textAlign: TextAlign.center,
style: theme.textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.w800,
letterSpacing: -0.5,
),
),
const SizedBox(height: 6),
Text(
'Connect to your self-hosted server',
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 36),
if (errorMessage != null)
Container(
margin: const EdgeInsets.only(bottom: 20),
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: colorScheme.errorContainer,
borderRadius: BorderRadius.circular(16),
),
child: Row(
children: [
Icon(
Icons.error_outline_rounded,
color: colorScheme.onErrorContainer,
size: 20,
),
const SizedBox(width: 12),
Expanded(
child: Text(
errorMessage!,
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onErrorContainer,
fontWeight: FontWeight.w500,
),
),
),
],
),
),
TextFormField(
controller: urlController,
keyboardType: TextInputType.url,
autofillHints: const [AutofillHints.url],
decoration: InputDecoration(
labelText: 'Server Address',
hintText: 'cloud.example.com',
prefixIcon: const Icon(Icons.dns_outlined),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
),
filled: true,
fillColor: colorScheme.surfaceContainerLow,
),
validator: (val) {
if (val == null || val.trim().isEmpty) {
return 'Please enter your Nextcloud server address';
}
return null;
},
onFieldSubmitted: (_) => onContinue(),
),
const SizedBox(height: 28),
SizedBox(
height: 54,
child: FilledButton(
onPressed: isLoading ? null : onContinue,
style: FilledButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(27),
),
),
child: isLoading
? SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(
strokeWidth: 2.5,
color: colorScheme.onPrimary,
),
)
: const Text(
'Continue',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
),
const SizedBox(height: 24),
Text(
"You'll finish signing in through your browser. This app never sees your password.",
textAlign: TextAlign.center,
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
fontSize: 11,
),
),
],
),
);
}
}
class _WaitingForBrowser extends StatelessWidget {
final VoidCallback onCancel;
final VoidCallback onReopenBrowser;
const _WaitingForBrowser({
required this.onCancel,
required this.onReopenBrowser,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
return Column(
mainAxisSize: MainAxisSize.min,
children: [
CircularProgressIndicator(color: colorScheme.primary),
const SizedBox(height: 28),
Text(
'Waiting for you to sign in',
textAlign: TextAlign.center,
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
Text(
'Complete the login in the browser window that just opened, then come back here.',
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 32),
OutlinedButton.icon(
onPressed: onReopenBrowser,
icon: const Icon(Icons.open_in_browser_rounded),
label: const Text('Reopen browser'),
),
const SizedBox(height: 12),
TextButton(onPressed: onCancel, child: const Text('Cancel')),
],
);
}
}
+51 -160
View File
@@ -1,8 +1,9 @@
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../models/nextcloud_item.dart';
import '../providers/server_provider.dart';
import '../widgets/profile_avatar_button.dart';
import 'file_viewer_screen.dart';
class PhotosView extends StatelessWidget {
final ScrollController scrollController;
@@ -20,29 +21,16 @@ class PhotosView extends StatelessWidget {
controller: scrollController,
physics: const BouncingScrollPhysics(),
slivers: [
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 16, 20, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Photos & Media',
style: theme.textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 4),
Text(
'${photos.length} cloud photos & video streams',
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
SliverAppBar(
pinned: true,
expandedHeight: kToolbarHeight,
collapsedHeight: kToolbarHeight,
backgroundColor: colorScheme.surface,
surfaceTintColor: colorScheme.surface,
scrolledUnderElevation: 0,
actions: const [ProfileAvatarButton()],
),
const SliverToBoxAdapter(child: SizedBox(height: 8)),
if (photos.isEmpty)
SliverFillRemaining(
@@ -76,24 +64,23 @@ class PhotosView extends StatelessWidget {
mainAxisSpacing: 8,
childAspectRatio: 1.0,
),
delegate: SliverChildBuilderDelegate(
(context, index) {
final photo = photos[index];
return _buildPhotoTile(context, photo, provider);
},
childCount: photos.length,
),
delegate: SliverChildBuilderDelegate((context, index) {
final photo = photos[index];
return _buildPhotoTile(context, photo, provider);
}, childCount: photos.length),
),
),
const SliverToBoxAdapter(
child: SizedBox(height: 100),
),
const SliverToBoxAdapter(child: SizedBox(height: 100)),
],
);
}
Widget _buildPhotoTile(BuildContext context, NextcloudItem photo, ServerProvider provider) {
Widget _buildPhotoTile(
BuildContext context,
NextcloudItem photo,
ServerProvider provider,
) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
@@ -109,10 +96,27 @@ class PhotosView extends StatelessWidget {
fit: StackFit.expand,
children: [
photo.previewUrl != null
? Image.network(
photo.previewUrl!,
fit: BoxFit.cover,
errorBuilder: (ctx, err, stack) => _buildFallbackTile(context, photo),
? LayoutBuilder(
builder: (context, constraints) {
// Decode at the tile's actual rendered size rather
// than the full 500x500 preview the server returns —
// cheaper to decode/cache while scrolling a grid.
final cachePixels =
(constraints.maxWidth *
MediaQuery.of(context).devicePixelRatio)
.round();
return Image.network(
photo.previewUrl!,
headers: provider.service?.authHeaders,
fit: BoxFit.cover,
cacheWidth: cachePixels,
cacheHeight: cachePixels,
filterQuality: FilterQuality.low,
gaplessPlayback: true,
errorBuilder: (ctx, err, stack) =>
_buildFallbackTile(context, photo),
);
},
)
: _buildFallbackTile(context, photo),
if (photo.type == NextcloudItemType.video)
@@ -136,11 +140,7 @@ class PhotosView extends StatelessWidget {
const Positioned(
top: 8,
right: 8,
child: Icon(
Icons.star_rounded,
color: Colors.amber,
size: 18,
),
child: Icon(Icons.star_rounded, color: Colors.amber, size: 18),
),
],
),
@@ -164,123 +164,14 @@ class PhotosView extends StatelessWidget {
);
}
void _openLightbox(BuildContext context, NextcloudItem photo, ServerProvider provider) {
showDialog(
context: context,
barrierColor: Colors.black.withValues(alpha: 0.92),
builder: (context) {
return Dialog.fullscreen(
backgroundColor: Colors.transparent,
child: Stack(
children: [
InteractiveViewer(
minScale: 0.8,
maxScale: 4.0,
child: Center(
child: photo.previewUrl != null
? Image.network(
photo.previewUrl!,
fit: BoxFit.contain,
)
: Icon(
photo.type == NextcloudItemType.video
? Icons.movie_rounded
: Icons.image_rounded,
size: 120,
color: Colors.white70,
),
),
),
Positioned(
top: 24,
left: 16,
right: 16,
child: SafeArea(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton.filledTonal(
onPressed: () => Navigator.pop(context),
icon: const Icon(Icons.close_rounded, color: Colors.white),
style: IconButton.styleFrom(
backgroundColor: Colors.black.withValues(alpha: 0.5),
),
),
Row(
children: [
IconButton.filledTonal(
onPressed: () {
provider.toggleItemFavorite(photo);
},
icon: Icon(
photo.isFavorite ? Icons.star_rounded : Icons.star_outline_rounded,
color: photo.isFavorite ? Colors.amber : Colors.white,
),
style: IconButton.styleFrom(
backgroundColor: Colors.black.withValues(alpha: 0.5),
),
),
const SizedBox(width: 8),
IconButton.filledTonal(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Downloading full resolution ${photo.name}...'),
behavior: SnackBarBehavior.floating,
),
);
},
icon: const Icon(Icons.download_rounded, color: Colors.white),
style: IconButton.styleFrom(
backgroundColor: Colors.black.withValues(alpha: 0.5),
),
),
],
),
],
),
),
),
Positioned(
bottom: 32,
left: 24,
right: 24,
child: SafeArea(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 14),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.65),
borderRadius: BorderRadius.circular(24),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
photo.name,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600,
fontSize: 15,
),
),
const SizedBox(height: 4),
Text(
'${DateFormat.yMMMMd().format(photo.lastModified)} • Nextcloud Photos',
style: const TextStyle(
color: Colors.white70,
fontSize: 12,
),
),
],
),
),
),
),
],
),
);
},
void _openLightbox(
BuildContext context,
NextcloudItem photo,
ServerProvider provider,
) {
Navigator.push(
context,
FileViewerScreen.route(item: photo, siblings: provider.photoItems),
);
}
}
+201
View File
@@ -0,0 +1,201 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../models/nextcloud_item.dart';
import '../providers/server_provider.dart';
import 'file_viewer_screen.dart';
class SearchView extends StatefulWidget {
const SearchView({super.key});
@override
State<SearchView> createState() => _SearchViewState();
}
class _SearchViewState extends State<SearchView> {
final _controller = TextEditingController();
final _focusNode = FocusNode();
Timer? _debounce;
List<NextcloudItem> _results = [];
bool _isSearching = false;
String? _error;
bool _hasSearched = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback(
(_) => _focusNode.requestFocus(),
);
}
@override
void dispose() {
_debounce?.cancel();
_controller.dispose();
_focusNode.dispose();
super.dispose();
}
void _onChanged(String query) {
_debounce?.cancel();
if (query.trim().isEmpty) {
setState(() {
_results = [];
_hasSearched = false;
_error = null;
});
return;
}
_debounce = Timer(
const Duration(milliseconds: 500),
() => _runSearch(query),
);
}
Future<void> _runSearch(String query) async {
final provider = context.read<ServerProvider>();
setState(() {
_isSearching = true;
_error = null;
});
try {
final results = await provider.searchFiles(query);
if (!mounted) return;
setState(() {
_results = results;
_hasSearched = true;
_isSearching = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_error = e.toString().replaceAll('Exception: ', '');
_isSearching = false;
_hasSearched = true;
});
}
}
IconData _iconFor(NextcloudItemType type) {
switch (type) {
case NextcloudItemType.folder:
return Icons.folder_rounded;
case NextcloudItemType.image:
return Icons.image_rounded;
case NextcloudItemType.video:
return Icons.movie_rounded;
case NextcloudItemType.audio:
return Icons.audiotrack_rounded;
case NextcloudItemType.document:
return Icons.description_rounded;
case NextcloudItemType.archive:
return Icons.folder_zip_rounded;
case NextcloudItemType.file:
return Icons.insert_drive_file_rounded;
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
return Scaffold(
appBar: AppBar(
titleSpacing: 0,
title: TextField(
controller: _controller,
focusNode: _focusNode,
onChanged: _onChanged,
decoration: const InputDecoration(
hintText: 'Search your files...',
border: InputBorder.none,
),
style: theme.textTheme.titleMedium,
),
actions: [
if (_controller.text.isNotEmpty)
IconButton(
icon: const Icon(Icons.close_rounded),
onPressed: () {
_controller.clear();
_onChanged('');
},
),
],
),
body: _buildBody(context, colorScheme, theme),
);
}
Widget _buildBody(
BuildContext context,
ColorScheme colorScheme,
ThemeData theme,
) {
if (_isSearching) {
return const Center(child: CircularProgressIndicator());
}
if (_error != null) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Text(
_error!,
textAlign: TextAlign.center,
style: TextStyle(color: colorScheme.error),
),
),
);
}
if (!_hasSearched) {
return Center(
child: Text(
'Search across your whole Nextcloud',
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
);
}
if (_results.isEmpty) {
return Center(
child: Text(
'No results found',
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
);
}
return ListView.builder(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
itemCount: _results.length,
itemBuilder: (context, index) {
final item = _results[index];
return ListTile(
leading: Icon(_iconFor(item.type), color: colorScheme.primary),
title: Text(item.name, maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(
item.isFolder
? item.path
: DateFormat.yMMMd().format(item.lastModified),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
onTap: () {
if (item.isFolder) {
context.read<ServerProvider>().navigateToFolder(item.path);
Navigator.pop(context);
} else {
Navigator.push(context, FileViewerScreen.route(item: item));
}
},
);
},
);
}
}
+110 -115
View File
@@ -1,145 +1,140 @@
import 'dart:ui';
import 'package:flutter/material.dart';
import 'frosted_glass_container.dart';
class FloatingNavItem {
final String label;
final IconData icon;
final IconData selectedIcon;
final String? badge;
const FloatingNavItem({
required this.label,
required this.icon,
required this.selectedIcon,
this.badge,
});
const FloatingNavItem({required this.label, required this.icon});
}
/// A floating pill-shaped bottom navigation bar in the style of Google
/// Photos' 2026 redesign: unselected destinations collapse to just their
/// icon, the selected destination expands into an icon+label capsule, and
/// a detached circular action (search) sits just outside the pill.
class FloatingBottomNavBar extends StatelessWidget {
final int selectedIndex;
final ValueChanged<int> onDestinationSelected;
final List<FloatingNavItem> items;
final bool isVisible;
final VoidCallback? onSearchTap;
final double opacity;
final double blurSigma;
const FloatingBottomNavBar({
super.key,
required this.selectedIndex,
required this.onDestinationSelected,
required this.items,
this.isVisible = true,
this.onSearchTap,
this.opacity = 0.55,
this.blurSigma = 28,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final colorScheme = Theme.of(context).colorScheme;
return AnimatedSlide(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOutCubic,
offset: isVisible ? Offset.zero : const Offset(0, 1.5),
child: AnimatedOpacity(
duration: const Duration(milliseconds: 250),
opacity: isVisible ? 1.0 : 0.0,
child: SafeArea(
child: Align(
alignment: Alignment.bottomCenter,
child: Container(
margin: const EdgeInsets.only(bottom: 20, left: 24, right: 24),
constraints: const BoxConstraints(maxWidth: 460),
height: 68,
child: ClipRRect(
borderRadius: BorderRadius.circular(34),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 20, sigmaY: 20),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.82),
borderRadius: BorderRadius.circular(34),
border: Border.all(
color: colorScheme.outlineVariant.withValues(alpha: 0.3),
width: 1,
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.12),
blurRadius: 24,
offset: const Offset(0, 8),
),
],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: List.generate(items.length, (index) {
final item = items[index];
final isSelected = selectedIndex == index;
return Expanded(
child: InkWell(
onTap: () => onDestinationSelected(index),
borderRadius: BorderRadius.circular(28),
splashColor: colorScheme.primary.withValues(alpha: 0.12),
highlightColor: Colors.transparent,
child: AnimatedContainer(
duration: const Duration(milliseconds: 250),
curve: Curves.easeInOutCubic,
margin: const EdgeInsets.symmetric(horizontal: 4),
padding: const EdgeInsets.symmetric(vertical: 6),
decoration: BoxDecoration(
color: isSelected
? colorScheme.primaryContainer
: Colors.transparent,
borderRadius: BorderRadius.circular(24),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
AnimatedScale(
duration: const Duration(milliseconds: 200),
scale: isSelected ? 1.12 : 1.0,
child: Icon(
isSelected ? item.selectedIcon : item.icon,
size: 22,
color: isSelected
? colorScheme.onPrimaryContainer
: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 3),
AnimatedDefaultTextStyle(
duration: const Duration(milliseconds: 200),
style: TextStyle(
fontSize: 11,
fontWeight: isSelected
? FontWeight.w700
: FontWeight.w500,
color: isSelected
? colorScheme.onPrimaryContainer
: colorScheme.onSurfaceVariant,
letterSpacing: 0.1,
),
child: Text(
item.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
),
);
}),
),
),
),
),
return SafeArea(
child: Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.only(bottom: 20, left: 20, right: 20),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 480),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
_buildPill(context, colorScheme),
const SizedBox(width: 10),
_buildSearchButton(context, colorScheme),
],
),
),
),
),
);
}
Widget _buildPill(BuildContext context, ColorScheme colorScheme) {
return FrostedGlassContainer(
opacity: opacity,
blurSigma: blurSigma,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 6),
child: Row(
mainAxisSize: MainAxisSize.min,
children: List.generate(items.length, (index) {
final item = items[index];
final isSelected = selectedIndex == index;
return InkWell(
onTap: () => onDestinationSelected(index),
borderRadius: BorderRadius.circular(26),
splashColor: colorScheme.primary.withValues(alpha: 0.12),
highlightColor: Colors.transparent,
child: AnimatedContainer(
duration: const Duration(milliseconds: 250),
curve: Curves.easeInOutCubic,
padding: EdgeInsets.symmetric(
horizontal: isSelected ? 16 : 12,
vertical: 12,
),
decoration: BoxDecoration(
color: isSelected ? colorScheme.primary : Colors.transparent,
borderRadius: BorderRadius.circular(26),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
item.icon,
size: 22,
color: isSelected
? colorScheme.onPrimary
: colorScheme.onSurfaceVariant,
),
if (isSelected) ...[
const SizedBox(width: 8),
Text(
item.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w700,
color: colorScheme.onPrimary,
letterSpacing: 0.1,
),
),
],
],
),
),
);
}),
),
),
);
}
Widget _buildSearchButton(BuildContext context, ColorScheme colorScheme) {
return FrostedGlassContainer(
opacity: opacity,
blurSigma: blurSigma,
child: SizedBox(
width: 52,
height: 52,
child: InkWell(
onTap: onSearchTap,
borderRadius: BorderRadius.circular(32),
splashColor: colorScheme.primary.withValues(alpha: 0.12),
child: Icon(
Icons.search_rounded,
color: colorScheme.onSurfaceVariant,
size: 24,
),
),
),
);
}
}
+59
View File
@@ -0,0 +1,59 @@
import 'dart:ui';
import 'package:flutter/material.dart';
/// The frosted-glass pill background shared by all floating chrome in the
/// app (bottom nav bar, media viewer action bar): blurred backdrop, a
/// translucent tonal fill, a faint outline, and a soft drop shadow.
class FrostedGlassContainer extends StatelessWidget {
final Widget child;
final double borderRadius;
/// Blur sigma for the backdrop filter. Defaults to a fixed value; pass an
/// explicit value (e.g. from user settings) to make it adjustable.
final double blurSigma;
/// Opacity (0-1) of the tonal fill behind the blur. Defaults to a fixed
/// value; pass an explicit value (e.g. from user settings) to make it
/// adjustable.
final double opacity;
const FrostedGlassContainer({
super.key,
required this.child,
this.borderRadius = 32,
this.blurSigma = 28,
this.opacity = 0.55,
});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return ClipRRect(
borderRadius: BorderRadius.circular(borderRadius),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: blurSigma, sigmaY: blurSigma),
child: Container(
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHighest.withValues(
alpha: opacity,
),
borderRadius: BorderRadius.circular(borderRadius),
border: Border.all(
color: colorScheme.outlineVariant.withValues(alpha: 0.35),
width: 1,
),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.14),
blurRadius: 24,
offset: const Offset(0, 8),
),
],
),
child: child,
),
),
);
}
}
+45
View File
@@ -0,0 +1,45 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/server_provider.dart';
import '../views/account_view.dart';
/// Top-bar avatar button that opens the account screen. Replaces the old
/// "Account" bottom-nav destination, matching how Google Drive surfaces
/// account access from a profile picture in the app bar.
class ProfileAvatarButton extends StatelessWidget {
const ProfileAvatarButton({super.key});
@override
Widget build(BuildContext context) {
final provider = context.watch<ServerProvider>();
final colorScheme = Theme.of(context).colorScheme;
final initial = provider.username.isNotEmpty
? provider.username[0].toUpperCase()
: '?';
return Padding(
padding: const EdgeInsets.only(right: 8),
child: IconButton(
tooltip: 'Account',
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (_) => const AccountView()),
);
},
icon: CircleAvatar(
radius: 17,
backgroundColor: colorScheme.primary,
child: Text(
initial,
style: TextStyle(
color: colorScheme.onPrimary,
fontWeight: FontWeight.bold,
fontSize: 14,
),
),
),
),
);
}
}
+65
View File
@@ -0,0 +1,65 @@
import 'package:flutter/material.dart';
/// A single icon button that fills with a solid circle when active —
/// the building block for Drive-style toggle controls.
class ToggleIconButton extends StatelessWidget {
final IconData icon;
final bool isSelected;
final VoidCallback onTap;
final String? tooltip;
const ToggleIconButton({
super.key,
required this.icon,
required this.isSelected,
required this.onTap,
this.tooltip,
});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final button = Material(
color: isSelected ? colorScheme.primaryContainer : Colors.transparent,
shape: const CircleBorder(),
child: InkWell(
onTap: onTap,
customBorder: const CircleBorder(),
child: Padding(
padding: const EdgeInsets.all(8),
child: Icon(
icon,
size: 20,
color: isSelected
? colorScheme.onPrimaryContainer
: colorScheme.onSurfaceVariant,
),
),
),
);
return tooltip != null ? Tooltip(message: tooltip!, child: button) : button;
}
}
/// A pill-shaped row of [ToggleIconButton]s sharing one background, matching
/// the list/grid view switch seen in Google Drive's toolbar.
class SegmentedIconGroup extends StatelessWidget {
final List<Widget> children;
const SegmentedIconGroup({super.key, required this.children});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Container(
padding: const EdgeInsets.all(2),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(20),
),
child: Row(mainAxisSize: MainAxisSize.min, children: children),
);
}
}