65 lines
1.7 KiB
Dart
65 lines
1.7 KiB
Dart
// lib/metadata/file_provider.dart
|
|
import 'dart:io';
|
|
import 'package:flutter/foundation.dart'; // ⭐ 添加
|
|
import 'package:path_provider/path_provider.dart';
|
|
import 'package:dio/dio.dart';
|
|
import '../services/webdav_service.dart';
|
|
|
|
abstract class FileProvider {
|
|
Future<File?> getFile(String url);
|
|
}
|
|
|
|
class WebDAVFileProvider implements FileProvider {
|
|
final Dio _dio = Dio();
|
|
|
|
@override
|
|
Future<File?> getFile(String url) async {
|
|
try {
|
|
// 1. 获取缓存目录
|
|
final cacheDir = await getTemporaryDirectory();
|
|
final cachePath = '${cacheDir.path}/metadata_${url.hashCode}.tmp';
|
|
final cacheFile = File(cachePath);
|
|
|
|
// 2. 如果缓存存在且未过期,直接返回
|
|
if (await cacheFile.exists()) {
|
|
final stat = await cacheFile.stat();
|
|
// 缓存 1 小时内有效(86400 秒)
|
|
if (DateTime.now().difference(stat.modified).inSeconds < 86400) {
|
|
return cacheFile;
|
|
}
|
|
}
|
|
|
|
// 3. 获取认证头
|
|
final headers = await WebDAVService.instance.getAuthHeaders();
|
|
if (headers.isEmpty) return null;
|
|
|
|
// 4. 只下载前 1MB
|
|
await _dio.download(
|
|
url,
|
|
cachePath,
|
|
options: Options(
|
|
headers: headers,
|
|
receiveTimeout: const Duration(seconds: 10),
|
|
sendTimeout: const Duration(seconds: 10),
|
|
),
|
|
);
|
|
|
|
return cacheFile;
|
|
} catch (e) {
|
|
debugPrint('⚠️ [WebDAVFileProvider] download failed: $e');
|
|
return null;
|
|
}
|
|
}
|
|
}
|
|
|
|
class LocalFileProvider implements FileProvider {
|
|
@override
|
|
Future<File?> getFile(String url) async {
|
|
final file = File(url);
|
|
if (await file.exists()) {
|
|
return file;
|
|
}
|
|
return null;
|
|
}
|
|
}
|