webdav存在自引用问题,现版本修复完成

This commit is contained in:
2026-08-17 22:24:56 +08:00
parent 457a9bf1e5
commit a6056c7f1a
5 changed files with 874 additions and 622 deletions
+537 -467
View File
File diff suppressed because it is too large Load Diff
+81 -100
View File
@@ -1,9 +1,4 @@
// ============================================================
// 文件名: webdav_file_list_page.dart
// 功能: WebDAV 文件浏览页面,支持文件夹导航和音乐播放
// 调用方式: Navigator.push(context, MaterialPageRoute(builder: (_) => WebDAVFileListPage()))
// ============================================================
// lib/pages/webdav_file_list_page.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../services/webdav_service.dart';
@@ -11,7 +6,6 @@ import '../services/playback_service.dart';
import '../services/audio_service.dart';
class WebDAVFileListPage extends StatefulWidget {
/// 当前浏览路径,默认为根目录 '/'
final String currentPath;
const WebDAVFileListPage({super.key, this.currentPath = '/'});
@@ -26,6 +20,15 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
String _errorMessage = '';
String _currentPath = '/';
// 安全解码
String _safeDecode(String input) {
try {
return Uri.decodeComponent(input);
} catch (_) {
return input; // 解码失败时返回原始字符串
}
}
@override
void initState() {
super.initState();
@@ -33,9 +36,6 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
_loadDirectory();
}
// -------------------------------------------------------------
// 加载当前目录内容
// -------------------------------------------------------------
Future<void> _loadDirectory() async {
setState(() {
_isLoading = true;
@@ -57,9 +57,6 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
}
}
// -------------------------------------------------------------
// 进入子目录
// -------------------------------------------------------------
void _enterDirectory(WebDAVItem dir) {
Navigator.push(
context,
@@ -69,9 +66,6 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
);
}
// -------------------------------------------------------------
// 播放音乐文件
// -------------------------------------------------------------
void _playSong(WebDAVItem file) async {
try {
final url = WebDAVService.instance.getFileUrl(file.path);
@@ -79,13 +73,11 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
final song = Song(
id: file.path,
title: file.name.replaceAll(RegExp(r'\.[^.]*$'), ''),
title: _safeDecode(file.name).replaceAll(RegExp(r'\.[^.]*$'), ''),
artist: '未知艺术家',
url: url,
);
context.read<AudioService>().playSong(song);
// ✅ 移除 SnackBar,直接显示 MiniPlayer
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
@@ -98,12 +90,13 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
}
}
// -------------------------------------------------------------
// 构建面包屑路径显示(只显示最后两级,避免过长)
// -------------------------------------------------------------
String _getDisplayPath() {
if (_currentPath == '/') return '根目录';
final parts = _currentPath.split('/').where((s) => s.isNotEmpty).toList();
if (_currentPath == '/' || _currentPath.isEmpty) return '根目录';
final decoded = _safeDecode(_currentPath);
final parts = decoded.split('/').where((s) => s.isNotEmpty).toList();
if (parts.isEmpty) return '根目录';
if (parts.length <= 2) return parts.join(' / ');
return '... / ${parts.sublist(parts.length - 2).join(' / ')}';
}
@@ -132,85 +125,74 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
),
],
),
body: _buildBody(),
);
}
// -------------------------------------------------------------
// 构建主体内容
// -------------------------------------------------------------
Widget _buildBody() {
if (_isLoading) {
return const Center(
child: CircularProgressIndicator(
color: Color(0xFFB8D4D0),
),
);
}
if (_errorMessage.isNotEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.error_outline, size: 48, color: Colors.grey[600]),
const SizedBox(height: 16),
Text(
_errorMessage,
style: TextStyle(color: Colors.grey[400]),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadDirectory,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFFB8D4D0),
foregroundColor: Colors.black87,
body: _isLoading
? const Center(
child: CircularProgressIndicator(
color: Color(0xFFB8D4D0),
),
child: const Text('重试'),
),
],
),
);
}
if (_items.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.folder_open, size: 48, color: Colors.grey[600]),
const SizedBox(height: 16),
Text(
'此目录为空',
style: TextStyle(color: Colors.grey[400]),
),
const SizedBox(height: 8),
Text(
'支持格式: MP3, FLAC, M4A, APE, WAV, OPUS',
style: TextStyle(color: Colors.grey[600], fontSize: 12),
),
],
),
);
}
return ListView.builder(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
itemCount: _items.length,
itemBuilder: (context, index) {
final item = _items[index];
return _buildListItem(item);
},
)
: _errorMessage.isNotEmpty
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.error_outline,
size: 48, color: Colors.grey[600]),
const SizedBox(height: 16),
Text(
_errorMessage,
style: TextStyle(color: Colors.grey[400]),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadDirectory,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFFB8D4D0),
foregroundColor: Colors.black87,
),
child: const Text('重试'),
),
],
),
)
: _items.isEmpty
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.folder_open,
size: 48, color: Colors.grey[600]),
const SizedBox(height: 16),
Text(
'此目录为空',
style: TextStyle(color: Colors.grey[400]),
),
const SizedBox(height: 8),
Text(
'支持格式: MP3, FLAC, M4A, APE, WAV, OPUS',
style: TextStyle(
color: Colors.grey[600], fontSize: 12),
),
],
),
)
: ListView.builder(
padding: const EdgeInsets.symmetric(
horizontal: 16, vertical: 8),
itemCount: _items.length,
itemBuilder: (context, index) {
final item = _items[index];
return _buildListItem(item);
},
),
);
}
// -------------------------------------------------------------
// 构建单个列表项(区分目录和文件)
// -------------------------------------------------------------
Widget _buildListItem(WebDAVItem item) {
final displayName = _safeDecode(item.name);
if (item.isDirectory) {
// ---------- 目录项 ----------
return ListTile(
contentPadding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
leading: const Icon(
@@ -219,7 +201,7 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
size: 32,
),
title: Text(
item.name,
displayName,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
@@ -242,7 +224,6 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
onTap: () => _enterDirectory(item),
);
} else {
// ---------- 音乐文件项 ----------
final sizeStr = item.size != null
? '${(item.size! / 1024 / 1024).toStringAsFixed(1)} MB'
: '';
@@ -254,7 +235,7 @@ class _WebDAVFileListPageState extends State<WebDAVFileListPage> {
size: 28,
),
title: Text(
item.name,
displayName,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w400,
+32 -55
View File
@@ -1,16 +1,9 @@
// ============================================================
// 文件名: webdav_service.dart
// 功能: WebDAV 协议通信服务,支持文件夹浏览和音乐文件读取
// ============================================================
// lib/services/webdav_service.dart
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:xml/xml.dart';
// -----------------------------------------------------------------
// WebDAV 服务单例
// -----------------------------------------------------------------
class WebDAVService {
static const String _keyBaseUrl = 'webdav_base_url';
static const String _keyUsername = 'webdav_username';
@@ -25,16 +18,11 @@ class WebDAVService {
String? _baseUrl;
String? _username;
// -------------------------------------------------------------
// 公开 Getter
// -------------------------------------------------------------
bool get isConnected => _dio != null;
String? get baseUrl => _baseUrl;
String? get username => _username;
// -------------------------------------------------------------
// 凭据管理
// -------------------------------------------------------------
// 保存凭据
Future<void> saveCredentials(
String baseUrl, String username, String password) async {
final prefs = await SharedPreferences.getInstance();
@@ -53,6 +41,7 @@ class WebDAVService {
));
}
// 加载已保存的凭据
Future<bool> loadCredentials() async {
final prefs = await SharedPreferences.getInstance();
final baseUrl = prefs.getString(_keyBaseUrl);
@@ -74,6 +63,7 @@ class WebDAVService {
return false;
}
// 清除凭据
Future<void> clearCredentials() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_keyBaseUrl);
@@ -84,15 +74,22 @@ class WebDAVService {
_username = null;
}
// -------------------------------------------------------------
// 核心:列出目录内容(文件夹 + 音乐文件)
// 这是浏览模式的核心方法,支持进入子目录
// -------------------------------------------------------------
// 获取音乐文件列表(PROPFIND
Future<List<WebDAVItem>> listDirectory({String path = '/'}) async {
if (_dio == null) throw Exception('WebDAV 未连接');
final requestPath = path.startsWith('/') ? path : '/$path';
// 路径规范化:去掉首尾斜杠,用于比较
String _normalize(String p) {
var s = p;
if (s.startsWith('/')) s = s.substring(1);
if (s.endsWith('/')) s = s.substring(0, s.length - 1);
return s;
}
final normalizedRequest = _normalize(requestPath);
final body = '''
<?xml version="1.0" encoding="utf-8"?>
<propfind xmlns="DAV:">
@@ -124,14 +121,13 @@ class WebDAVService {
final items = <WebDAVItem>[];
final musicExtensions = ['.mp3', '.flac', '.m4a', '.ape', '.wav', '.opus'];
final responseNodes = xml.findAllElements('D:response');
for (final responseNode in responseNodes) {
for (final responseNode in xml.findAllElements('D:response')) {
final hrefNode = responseNode.findElements('D:href').firstOrNull;
if (hrefNode == null) continue;
String fullPath = Uri.decodeComponent(hrefNode.text.trim());
// 去掉 baseUrl 前缀
// 去掉 baseUrl 前缀,得到相对路径
String relativePath = fullPath;
if (_baseUrl != null) {
try {
@@ -149,10 +145,10 @@ class WebDAVService {
}
}
// 跳过根目录自身
if (relativePath.isEmpty ||
relativePath == '/' ||
relativePath == requestPath) {
// 使用规范化路径比较,跳过当前目录自身
final normalizedRelative = _normalize(relativePath);
if (normalizedRelative.isEmpty ||
normalizedRelative == normalizedRequest) {
continue;
}
@@ -160,7 +156,6 @@ class WebDAVService {
? relativePath.substring(0, relativePath.length - 1)
: relativePath;
// ✅ 解码文件名
String fileName = cleanPath.split('/').last;
fileName = Uri.decodeComponent(fileName);
if (fileName.isEmpty) continue;
@@ -219,26 +214,28 @@ class WebDAVService {
));
}
// 排序
// 排序:目录在前,文件在后
items.sort((a, b) {
if (a.isDirectory && !b.isDirectory) return -1;
if (!a.isDirectory && b.isDirectory) return 1;
return a.name.toLowerCase().compareTo(b.name.toLowerCase());
});
// 只保留一条日志,避免刷屏
print('WebDAV listDirectory: 找到 ${items.length} 项,路径: $requestPath');
return items;
}
// -------------------------------------------------------------
// 兼容旧接口:获取所有音乐文件(递归扫描)
// 用于主页的"我的收藏"列表(后续可改为读取用户收藏)
// -------------------------------------------------------------
// 获取文件完整 URL
String getFileUrl(String path) {
if (_baseUrl == null) throw Exception('WebDAV 未配置');
final base = _baseUrl!.endsWith('/') ? _baseUrl! : '$_baseUrl/';
final cleanPath = path.startsWith('/') ? path.substring(1) : path;
return '$base$cleanPath';
}
// 递归获取所有音乐文件(用于收藏列表)
Future<List<WebDAVFileItem>> getMusicFiles({String path = '/'}) async {
if (_dio == null) throw Exception('WebDAV 未连接');
// 递归获取所有文件(先获取当前目录,再递归子目录)
final allItems = await _listAllRecursive(path);
final musicExtensions = ['.mp3', '.flac', '.m4a', '.ape', '.wav', '.opus'];
@@ -255,7 +252,6 @@ class WebDAVService {
.toList();
}
// 递归获取所有目录和文件(内部使用)
Future<List<WebDAVItem>> _listAllRecursive(String path) async {
final items = await listDirectory(path: path);
final result = <WebDAVItem>[];
@@ -263,32 +259,16 @@ class WebDAVService {
for (final item in items) {
result.add(item);
if (item.isDirectory) {
// 递归获取子目录内容
try {
final subItems = await _listAllRecursive(item.path);
result.addAll(subItems);
} catch (_) {
// 忽略无法读取的子目录
}
} catch (_) {}
}
}
return result;
}
// -------------------------------------------------------------
// 获取文件的完整下载 URL
// -------------------------------------------------------------
String getFileUrl(String path) {
if (_baseUrl == null) throw Exception('WebDAV 未配置');
final base = _baseUrl!.endsWith('/') ? _baseUrl! : '$_baseUrl/';
final cleanPath = path.startsWith('/') ? path.substring(1) : path;
return '$base$cleanPath';
}
}
// -----------------------------------------------------------------
// 数据模型:WebDAV 目录项(用于浏览模式)
// -----------------------------------------------------------------
class WebDAVItem {
final String path;
final String name;
@@ -305,9 +285,6 @@ class WebDAVItem {
});
}
// -----------------------------------------------------------------
// 数据模型:WebDAV 文件项(用于播放列表)
// -----------------------------------------------------------------
class WebDAVFileItem {
final String path;
final String name;
+150
View File
@@ -0,0 +1,150 @@
import 'package:flutter/material.dart';
/// 磁吸进度状态
class MagneticSnapState {
/// 吸附进度 0.0 ~ 1.0
final double progress;
/// 媒体库透明度
double get mediaOpacity {
// 0% ~ 70%: 1.0 → 0.45
// 70% ~ 100%: 0.45 → 0
if (progress <= 0.7) {
return 1.0 - (progress / 0.7) * 0.55;
} else {
final t = (progress - 0.7) / 0.3;
return 0.45 * (1 - t);
}
}
/// 收藏标题位移(从 +12px → 0)
double get favoriteTranslateY {
return (1 - progress) * 12;
}
/// 收藏列表展开程度 0.0 ~ 1.0
double get listReveal {
if (progress <= 0.7) return 0.0;
return (progress - 0.7) / 0.3;
}
/// 是否完全吸附
bool get isSnapped => progress >= 1.0;
/// 是否在磁吸区(进度 > 70%)
bool get isInMagneticZone => progress > 0.7;
const MagneticSnapState(this.progress);
factory MagneticSnapState.initial() => const MagneticSnapState(0.0);
MagneticSnapState copyWith({double? progress}) {
return MagneticSnapState(progress ?? this.progress);
}
}
/// 磁吸控制器
class MagneticScrollController extends ChangeNotifier {
/// 吸附进度
double _progress = 0.0;
double get progress => _progress;
/// 是否已吸附
bool _isSnapped = false;
bool get isSnapped => _isSnapped;
/// 动画控制器(用于吸附动画)
AnimationController? _animationController;
TickerProvider? _tickerProvider;
/// 状态
MagneticSnapState get state => MagneticSnapState(_progress);
void init(TickerProvider vsync) {
_animationController = AnimationController(
vsync: vsync,
duration: const Duration(milliseconds: 300),
);
}
@override
void dispose() {
_animationController?.dispose();
super.dispose();
}
/// 更新滚动进度(在滚动时调用)
void updateProgress(double newProgress) {
if (_isSnapped) return;
_progress = newProgress.clamp(0.0, 1.0);
notifyListeners();
}
/// 处理松手事件
void onDragEnd(double velocity) {
if (_isSnapped) return;
final threshold = 0.45; // 45% 触发吸附
final shouldSnap = _progress > threshold || velocity > 800;
if (shouldSnap) {
snapOpen();
} else {
snapBack();
}
}
/// 吸附展开
void snapOpen() {
if (_isSnapped) return;
_isSnapped = true;
_animationController?.reset();
_animationController
?.animateTo(
1.0,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOutBack,
)
.then((_) {
_progress = 1.0;
notifyListeners();
});
// 实时更新进度
_animationController?.addListener(() {
_progress = _animationController!.value;
notifyListeners();
});
}
/// 回弹
void snapBack() {
if (_isSnapped) return;
_animationController?.reset();
_animationController
?.animateTo(
0.0,
duration: const Duration(milliseconds: 250),
curve: Curves.easeOut,
)
.then((_) {
_progress = 0.0;
notifyListeners();
});
_animationController?.addListener(() {
_progress = _animationController!.value;
notifyListeners();
});
}
/// 重置状态(退出页面时)
void reset() {
_isSnapped = false;
_progress = 0.0;
_animationController?.reset();
notifyListeners();
}
}
+74
View File
@@ -0,0 +1,74 @@
// lib/widgets/magnetic_scroll_physics.dart
import 'package:flutter/material.dart';
class MagneticScrollPhysics extends ClampingScrollPhysics {
final double snapPoint;
final double magneticZoneStart;
const MagneticScrollPhysics({
required this.snapPoint,
this.magneticZoneStart = 0.20,
super.parent,
});
@override
MagneticScrollPhysics applyTo(ScrollPhysics? ancestor) {
return MagneticScrollPhysics(
snapPoint: snapPoint,
magneticZoneStart: magneticZoneStart,
parent: buildParent(ancestor),
);
}
@override
Simulation? createBallisticSimulation(
ScrollMetrics position,
double velocity,
) {
final offset = position.pixels;
if (offset <= 0 || offset >= snapPoint) {
return super.createBallisticSimulation(position, velocity);
}
final shouldSnap = _shouldSnap(offset, velocity);
final target = shouldSnap ? snapPoint : 0.0;
if ((offset - target).abs() < 1.0) {
return null;
}
return ScrollSpringSimulation(
SpringDescription(
mass: 1.0,
stiffness: 320.0,
damping: 26.0,
),
offset,
target,
velocity,
tolerance: const Tolerance(
velocity: 0.01,
distance: 0.5,
),
);
}
bool _shouldSnap(double offset, double velocity) {
final zoneStart = snapPoint * magneticZoneStart;
// 向上滑 → 吸附展开
if (velocity > 20) {
return true;
}
// 向下滑 → 回去
if (velocity < -20) {
return false;
}
// 松手速度很小,用当前位置决定
return offset >= zoneStart;
}
}