feat: add local file management and incoming share support
This commit is contained in:
1 parent
731a83fcbc
commit
ed875ef2e1
43 files changed
+2674
-36
No files matched your search
@@ -0,0 +1,100 @@
|
||||
import 'package:cupertino_ui/cupertino_ui.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:material_ui/material_ui.dart' show SelectableText;
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'share_thumbnail.dart';
|
||||
import '../../../core/widgets/app_page_scaffold.dart';
|
||||
import '../../../l10n/app_localizations.dart';
|
||||
import 'sharing_controller.dart';
|
||||
|
||||
class ReceivedSharePage extends ConsumerWidget {
|
||||
const ReceivedSharePage({super.key});
|
||||
Future<void> _open(BuildContext context, WidgetRef ref, String path) async {
|
||||
final opened = await ref
|
||||
.read(sharingControllerProvider.notifier)
|
||||
.open(path);
|
||||
if (!opened && context.mounted) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
await showCupertinoDialog<void>(
|
||||
context: context,
|
||||
builder: (context) => CupertinoAlertDialog(
|
||||
content: Text(l10n.filesOpenFailed),
|
||||
actions: [
|
||||
CupertinoDialogAction(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: Text(l10n.commonConfirm),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final inbox = ref.watch(sharingControllerProvider);
|
||||
final l10n = AppLocalizations.of(context);
|
||||
return AppPageScaffold(
|
||||
navigationBar: CupertinoNavigationBar(
|
||||
middle: Text(l10n.shareReceivedTitle),
|
||||
),
|
||||
child: SafeArea(
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
Text(l10n.shareSavedHint),
|
||||
if (inbox.importing)
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(16),
|
||||
child: CupertinoActivityIndicator(),
|
||||
),
|
||||
if (inbox.failed)
|
||||
Text(
|
||||
l10n.shareReceiveFailed,
|
||||
style: const TextStyle(color: CupertinoColors.systemRed),
|
||||
),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
for (final item in inbox.items.reversed)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (item.type == 'image') shareThumbnail(item.path),
|
||||
if (item.type == 'file' ||
|
||||
item.type == 'video' ||
|
||||
item.type == 'image')
|
||||
Text(
|
||||
Uri.file(item.path).pathSegments.last,
|
||||
style: const TextStyle(fontWeight: FontWeight.w600),
|
||||
),
|
||||
if (item.type == 'text' || item.type == 'url')
|
||||
SelectableText(item.path),
|
||||
if (item.type != 'text' && item.type != 'url')
|
||||
CupertinoButton(
|
||||
onPressed: () => _open(context, ref, item.path),
|
||||
child: Text(l10n.shareOpen),
|
||||
),
|
||||
if (item.message?.isNotEmpty == true)
|
||||
SelectableText(item.message!),
|
||||
if (item.type == 'text' || item.type == 'url')
|
||||
CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: () => Clipboard.setData(
|
||||
ClipboardData(text: item.path),
|
||||
),
|
||||
child: Text(l10n.shareCopy),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import 'package:cupertino_ui/cupertino_ui.dart';
|
||||
import '../../../l10n/app_localizations.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'sharing_controller.dart';
|
||||
|
||||
class ShareReceiver extends StatefulWidget {
|
||||
const ShareReceiver({super.key, required this.router, required this.child});
|
||||
final GoRouter router;
|
||||
final Widget child;
|
||||
@override
|
||||
State<ShareReceiver> createState() => _ShareReceiverState();
|
||||
}
|
||||
|
||||
class _ShareReceiverState extends State<ShareReceiver>
|
||||
with WidgetsBindingObserver {
|
||||
String get _currentPath =>
|
||||
widget.router.routerDelegate.currentConfiguration.isEmpty
|
||||
? widget.router.routeInformationProvider.value.uri.path
|
||||
: widget.router.state.uri.path;
|
||||
bool _navigatePending = false;
|
||||
bool _clipboardCheckPending = true;
|
||||
bool _clipboardFrameScheduled = false;
|
||||
bool _clipboardDialogOpen = false;
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
sharingContainer.listen(
|
||||
sharingControllerProvider.select((value) => value.delivery),
|
||||
(previous, next) {
|
||||
_navigatePending = true;
|
||||
_navigate();
|
||||
},
|
||||
);
|
||||
sharingContainer.listen(
|
||||
sharingControllerProvider.select((value) => value.clipboardUrl),
|
||||
(previous, next) {
|
||||
if (next != null) _scheduleClipboard();
|
||||
},
|
||||
);
|
||||
widget.router.routerDelegate.addListener(_routeChanged);
|
||||
_scheduleClipboard();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (state == AppLifecycleState.resumed) {
|
||||
_clipboardCheckPending = true;
|
||||
_scheduleClipboard();
|
||||
}
|
||||
}
|
||||
|
||||
void _routeChanged() {
|
||||
_navigate();
|
||||
_scheduleClipboard();
|
||||
}
|
||||
|
||||
void _scheduleClipboard() {
|
||||
if (_clipboardFrameScheduled || !mounted) return;
|
||||
_clipboardFrameScheduled = true;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) async {
|
||||
_clipboardFrameScheduled = false;
|
||||
if (!mounted ||
|
||||
WidgetsBinding.instance.lifecycleState != AppLifecycleState.resumed ||
|
||||
_currentPath == '/splash') {
|
||||
return;
|
||||
}
|
||||
if (_clipboardCheckPending) {
|
||||
_clipboardCheckPending = false;
|
||||
await sharingContainer
|
||||
.read(sharingControllerProvider.notifier)
|
||||
.checkClipboard();
|
||||
}
|
||||
if (mounted) _showClipboardPrompt();
|
||||
});
|
||||
WidgetsBinding.instance.ensureVisualUpdate();
|
||||
}
|
||||
|
||||
Future<void> _showClipboardPrompt() async {
|
||||
if (_clipboardDialogOpen ||
|
||||
!mounted ||
|
||||
WidgetsBinding.instance.lifecycleState != AppLifecycleState.resumed) {
|
||||
return;
|
||||
}
|
||||
final state = sharingContainer.read(sharingControllerProvider);
|
||||
final url = state.clipboardUrl;
|
||||
final text = state.clipboardText;
|
||||
final context = widget.router.routerDelegate.navigatorKey.currentContext;
|
||||
if (url == null || text == null || context == null) return;
|
||||
_clipboardDialogOpen = true;
|
||||
final l10n = AppLocalizations.of(context);
|
||||
try {
|
||||
final accepted = await showCupertinoDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => CupertinoAlertDialog(
|
||||
title: Text(l10n.shareClipboardTitle),
|
||||
content: Column(
|
||||
children: [
|
||||
Text(l10n.shareClipboardQuestion),
|
||||
const SizedBox(height: 12),
|
||||
Text(text, maxLines: 5, overflow: TextOverflow.ellipsis),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
CupertinoDialogAction(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: Text(l10n.commonCancel),
|
||||
),
|
||||
CupertinoDialogAction(
|
||||
isDefaultAction: true,
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: Text(l10n.shareClipboardConfirm),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (mounted &&
|
||||
sharingContainer.read(sharingControllerProvider).clipboardUrl ==
|
||||
url) {
|
||||
sharingContainer
|
||||
.read(sharingControllerProvider.notifier)
|
||||
.resolveClipboard(share: accepted == true);
|
||||
}
|
||||
} finally {
|
||||
_clipboardDialogOpen = false;
|
||||
}
|
||||
}
|
||||
|
||||
void _navigate() {
|
||||
if (!_navigatePending || !mounted || _currentPath == '/splash') {
|
||||
return;
|
||||
}
|
||||
_navigatePending = false;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted && _currentPath != '/received-share') {
|
||||
widget.router.push('/received-share');
|
||||
}
|
||||
});
|
||||
WidgetsBinding.instance.ensureVisualUpdate();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
disposeSharingContainer();
|
||||
widget.router.routerDelegate.removeListener(_routeChanged);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => widget.child;
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export 'share_thumbnail_stub.dart'
|
||||
if (dart.library.io) 'share_thumbnail_io.dart';
|
||||
@@ -0,0 +1,10 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
Widget shareThumbnail(String path) => Image.file(
|
||||
File(path),
|
||||
height: 180,
|
||||
fit: BoxFit.contain,
|
||||
cacheWidth: 720,
|
||||
errorBuilder: (_, _, _) => const SizedBox.shrink(),
|
||||
);
|
||||
@@ -0,0 +1,3 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
Widget shareThumbnail(String path) => const SizedBox.shrink();
|
||||
@@ -0,0 +1,190 @@
|
||||
import 'package:crypto/crypto.dart';
|
||||
import '../data/clipboard_repository.dart';
|
||||
import '../domain/douyin_share.dart';
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:receive_sharing_intent/receive_sharing_intent.dart';
|
||||
import '../data/share_storage.dart';
|
||||
import '../domain/shared_inbox.dart';
|
||||
|
||||
ProviderContainer? _sharingContainer;
|
||||
|
||||
/// Local-phone inbox is independent of account caches.
|
||||
ProviderContainer get sharingContainer =>
|
||||
_sharingContainer ??= ProviderContainer();
|
||||
void disposeSharingContainer() {
|
||||
_sharingContainer?.dispose();
|
||||
_sharingContainer = null;
|
||||
}
|
||||
|
||||
final clipboardRepositoryProvider = Provider((ref) => ClipboardRepository());
|
||||
|
||||
final sharingControllerProvider =
|
||||
NotifierProvider.autoDispose<SharingController, SharedInbox>(
|
||||
SharingController.new,
|
||||
);
|
||||
|
||||
/// Kept alive by ShareReceiver, independent of account-scoped business providers.
|
||||
class SharingController extends AutoDisposeNotifier<SharedInbox> {
|
||||
Future<void> _pending = Future.value();
|
||||
Future<void> _initialShareReady = Future.value();
|
||||
String? _lastBatch;
|
||||
DateTime? _lastReceived;
|
||||
bool _disposed = false;
|
||||
bool _opening = false;
|
||||
bool _checkingClipboard = false;
|
||||
bool _mobile = false;
|
||||
final Set<String> _handledClipboard = {};
|
||||
|
||||
Future<void> checkClipboard() async {
|
||||
if (!_mobile ||
|
||||
_disposed ||
|
||||
_checkingClipboard ||
|
||||
state.clipboardUrl != null ||
|
||||
state.importing) {
|
||||
return;
|
||||
}
|
||||
_checkingClipboard = true;
|
||||
try {
|
||||
// Finish loading saved shares before checking for an already imported URL.
|
||||
await _initialShareReady;
|
||||
await _pending;
|
||||
if (_disposed || state.importing) return;
|
||||
final text = await ref.read(clipboardRepositoryProvider).readText();
|
||||
if (_disposed || text == null || text.length > 20000) return;
|
||||
final url = findDouyinShareUrl(text);
|
||||
if (url == null || state.importing || state.clipboardUrl != null) return;
|
||||
final fingerprint = sha256.convert(utf8.encode(url)).toString();
|
||||
final repository = ref.read(clipboardRepositoryProvider);
|
||||
if (_handledClipboard.contains(fingerprint) ||
|
||||
repository.lastHandledFingerprint == fingerprint ||
|
||||
state.items.any(
|
||||
(item) =>
|
||||
(item.type == 'url' || item.type == 'text') &&
|
||||
findDouyinShareUrl(item.path) == url,
|
||||
)) {
|
||||
return;
|
||||
}
|
||||
state = state.copyWith(clipboardText: text.trim(), clipboardUrl: url);
|
||||
} catch (_) {
|
||||
// Clipboard denial/unavailability must not interrupt returning to the app.
|
||||
} finally {
|
||||
_checkingClipboard = false;
|
||||
}
|
||||
}
|
||||
|
||||
void resolveClipboard({required bool share}) {
|
||||
final url = state.clipboardUrl;
|
||||
final text = state.clipboardText;
|
||||
if (url == null || text == null) return;
|
||||
final fingerprint = sha256.convert(utf8.encode(url)).toString();
|
||||
_handledClipboard.add(fingerprint);
|
||||
// Keep only hashes, never persist unrelated clipboard content.
|
||||
if (_handledClipboard.length > 64) {
|
||||
_handledClipboard.remove(_handledClipboard.first);
|
||||
}
|
||||
ref.read(clipboardRepositoryProvider).markHandled(fingerprint);
|
||||
state = state.copyWith(clipboardText: null, clipboardUrl: null);
|
||||
if (share) {
|
||||
receive([
|
||||
SharedMediaFile(path: url, type: SharedMediaType.url, message: text),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> open(String path) async {
|
||||
if (_opening) return true;
|
||||
_opening = true;
|
||||
try {
|
||||
return await openSharedItem(path);
|
||||
} finally {
|
||||
_opening = false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
SharedInbox build() {
|
||||
if (kIsWeb ||
|
||||
(defaultTargetPlatform != TargetPlatform.android &&
|
||||
defaultTargetPlatform != TargetPlatform.iOS)) {
|
||||
return const SharedInbox();
|
||||
}
|
||||
_mobile = true;
|
||||
_pending = loadSharedItems().then(
|
||||
(items) {
|
||||
if (!_disposed) {
|
||||
state = state.copyWith(
|
||||
items: items
|
||||
.map((item) => SharedItem.fromJson(item.toMap()))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
},
|
||||
onError: (Object error) {
|
||||
if (!_disposed) state = state.copyWith(failed: true);
|
||||
},
|
||||
);
|
||||
final subscription = ReceiveSharingIntent.instance.getMediaStream().listen(
|
||||
receive,
|
||||
onError: (Object error) => _error(),
|
||||
);
|
||||
_initialShareReady = ReceiveSharingIntent.instance.getInitialMedia().then(
|
||||
receive,
|
||||
onError: (Object error) => _error(),
|
||||
);
|
||||
ref.onDispose(() {
|
||||
_disposed = true;
|
||||
subscription.cancel();
|
||||
});
|
||||
return const SharedInbox();
|
||||
}
|
||||
|
||||
void _error() {
|
||||
if (!_disposed) {
|
||||
state = state.copyWith(failed: true, delivery: state.delivery + 1);
|
||||
}
|
||||
}
|
||||
|
||||
void receive(List<SharedMediaFile> items) {
|
||||
if (_disposed || items.isEmpty) return;
|
||||
final signature = jsonEncode(items.map((item) => item.toMap()).toList());
|
||||
final now = DateTime.now();
|
||||
if (_lastBatch == signature &&
|
||||
_lastReceived != null &&
|
||||
now.difference(_lastReceived!).inSeconds < 2) {
|
||||
return;
|
||||
}
|
||||
_lastBatch = signature;
|
||||
_lastReceived = now;
|
||||
_pending = _pending.then((_) async {
|
||||
if (_disposed) return;
|
||||
state = state.copyWith(
|
||||
importing: true,
|
||||
failed: false,
|
||||
delivery: state.delivery + 1,
|
||||
);
|
||||
try {
|
||||
final saved = await saveSharedItems(items);
|
||||
if (!_disposed) {
|
||||
state = state.copyWith(
|
||||
items: [
|
||||
...state.items,
|
||||
...saved.map((item) => SharedItem.fromJson(item.toMap())),
|
||||
],
|
||||
);
|
||||
}
|
||||
} catch (_) {
|
||||
if (!_disposed) state = state.copyWith(failed: true);
|
||||
} finally {
|
||||
if (!_disposed) state = state.copyWith(importing: false);
|
||||
try {
|
||||
await ReceiveSharingIntent.instance.reset();
|
||||
} catch (_) {
|
||||
/* Do not block subsequent batches. */
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user