fix: Improve receiving shares

This commit is contained in:
Anton Stubenbord
2023-10-03 17:49:38 +02:00
parent 37ed8bbb04
commit ad23df4f89
29 changed files with 529 additions and 348 deletions

View File

@@ -1,20 +1,24 @@
import 'dart:async';
import 'dart:io';
import 'package:bloc/bloc.dart';
import 'package:flutter/foundation.dart';
import 'package:paperless_mobile/core/service/file_service.dart';
import 'package:path/path.dart' as p;
import 'package:provider/provider.dart';
part 'receive_share_state.dart';
class ConsumptionChangeNotifier extends ChangeNotifier {
List<File> pendingFiles = [];
ConsumptionChangeNotifier();
final Completer _restored = Completer();
Future<void> get isInitialized => _restored.future;
Future<void> loadFromConsumptionDirectory({required String userId}) async {
pendingFiles = await _getCurrentFiles(userId);
if (!_restored.isCompleted) {
_restored.complete();
}
notifyListeners();
}

View File

@@ -1,8 +1,4 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:paperless_mobile/core/database/tables/local_user_account.dart';
import 'package:paperless_mobile/extensions/flutter_extensions.dart';
import 'package:paperless_mobile/features/sharing/cubit/receive_share_cubit.dart';
@@ -20,13 +16,13 @@ class ConsumptionQueueView extends StatelessWidget {
final currentUser = context.watch<LocalUserAccount>();
return Scaffold(
appBar: AppBar(
title: Text("Upload Queue"), //TODO: INTL
title: Text("Pending Files"), //TODO: INTL
),
body: Consumer<ConsumptionChangeNotifier>(
builder: (context, value, child) {
if (value.pendingFiles.isEmpty) {
return Center(
child: Text("No pending files."),
child: Text("There are no pending files."), //TODO: INTL
);
}
return ListView.builder(
@@ -34,7 +30,37 @@ class ConsumptionQueueView extends StatelessWidget {
final file = value.pendingFiles.elementAt(index);
final filename = p.basename(file.path);
return ListTile(
title: Text(filename),
title: Text(
filename,
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
subtitle: Row(
children: [
ActionChip(
label: Text(S.of(context)!.upload),
avatar: const Icon(Icons.file_upload_outlined),
onPressed: () {
consumeLocalFile(
context,
file: file,
userId: currentUser.id,
);
},
),
const SizedBox(width: 8),
ActionChip(
label: Text(S.of(context)!.discard),
avatar: const Icon(Icons.delete),
onPressed: () {
context.read<ConsumptionChangeNotifier>().discardFile(
file,
userId: currentUser.id,
);
},
),
],
),
leading: Padding(
padding: const EdgeInsets.all(4),
child: ClipRRect(
@@ -46,60 +72,7 @@ class ConsumptionQueueView extends StatelessWidget {
),
),
),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () {
context
.read<ConsumptionChangeNotifier>()
.discardFile(file, userId: currentUser.id);
},
),
);
return Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: Column(
children: [
Text(filename, maxLines: 1),
SizedBox(
height: 56,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
ActionChip(
label: Text(S.of(context)!.upload),
avatar: Icon(Icons.file_upload_outlined),
onPressed: () {
consumeLocalFile(
context,
file: file,
userId: currentUser.id,
);
},
),
SizedBox(width: 8),
ActionChip(
label: Text(S.of(context)!.discard),
avatar: Icon(Icons.delete),
onPressed: () {
context
.read<ConsumptionChangeNotifier>()
.discardFile(
file,
userId: currentUser.id,
);
},
),
],
),
),
],
).padded(),
),
],
).padded();
},
itemCount: value.pendingFiles.length,
);

View File

@@ -6,7 +6,7 @@ import 'package:paperless_mobile/core/widgets/dialog_utils/dialog_cancel_button.
import 'package:paperless_mobile/core/widgets/dialog_utils/dialog_confirm_button.dart';
import 'package:paperless_mobile/core/widgets/future_or_builder.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
import 'package:transparent_image/transparent_image.dart';
import 'package:paperless_mobile/features/sharing/view/widgets/file_thumbnail.dart';
class DiscardSharedFileDialog extends StatelessWidget {
final FutureOr<Uint8List> bytes;
@@ -24,13 +24,13 @@ class DiscardSharedFileDialog extends StatelessWidget {
if (!snapshot.hasData) {
return const CircularProgressIndicator();
}
return LimitedBox(
maxHeight: 200,
maxWidth: 200,
child: FadeInImage(
fit: BoxFit.contain,
placeholder: MemoryImage(kTransparentImage),
image: MemoryImage(snapshot.data!),
return ClipRRect(
borderRadius: BorderRadius.circular(12),
child: FileThumbnail(
bytes: snapshot.data!,
width: 150,
height: 100,
fit: BoxFit.cover,
),
);
},

View File

@@ -0,0 +1,29 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:paperless_mobile/core/widgets/dialog_utils/dialog_cancel_button.dart';
import 'package:paperless_mobile/core/widgets/dialog_utils/dialog_confirm_button.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
class PendingFilesInfoDialog extends StatelessWidget {
final List<File> pendingFiles;
const PendingFilesInfoDialog({super.key, required this.pendingFiles});
@override
Widget build(BuildContext context) {
final fileCount = pendingFiles.length;
return AlertDialog(
title: Text("Pending Files"),
content: Text(
"$fileCount files are waiting to be uploaded. Do you want to upload them now?",
),
actions: [
DialogCancelButton(),
DialogConfirmButton(
label: S.of(context)!.upload,
),
],
);
}
}

View File

@@ -28,13 +28,15 @@ class FileThumbnail extends StatefulWidget {
class _FileThumbnailState extends State<FileThumbnail> {
late String? mimeType;
late final Future<Uint8List?> _fileBytes;
@override
void initState() {
super.initState();
mimeType = widget.file != null
? mime.lookupMimeType(widget.file!.path)
: mime.lookupMimeType('', headerBytes: widget.bytes);
_fileBytes = widget.file?.readAsBytes().then(_convertPdfToPng) ??
_convertPdfToPng(widget.bytes!);
}
@override
@@ -45,8 +47,7 @@ class _FileThumbnailState extends State<FileThumbnail> {
height: widget.height,
child: Center(
child: FutureBuilder<Uint8List?>(
future: widget.file?.readAsBytes().then(_convertPdfToPng) ??
_convertPdfToPng(widget.bytes!),
future: _fileBytes,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const SizedBox.shrink();

View File

@@ -10,15 +10,16 @@ import 'package:paperless_api/paperless_api.dart';
import 'package:paperless_mobile/core/config/hive/hive_config.dart';
import 'package:paperless_mobile/core/config/hive/hive_extensions.dart';
import 'package:paperless_mobile/core/database/tables/local_user_account.dart';
import 'package:paperless_mobile/core/service/connectivity_status_service.dart';
import 'package:paperless_mobile/features/document_upload/view/document_upload_preparation_page.dart';
import 'package:paperless_mobile/features/notifications/services/local_notification_service.dart';
import 'package:paperless_mobile/features/sharing/cubit/receive_share_cubit.dart';
import 'package:paperless_mobile/features/sharing/view/dialog/discard_shared_file_dialog.dart';
import 'package:paperless_mobile/features/tasks/cubit/task_status_cubit.dart';
import 'package:paperless_mobile/features/sharing/view/dialog/pending_files_info_dialog.dart';
import 'package:paperless_mobile/features/tasks/model/pending_tasks_notifier.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
import 'package:paperless_mobile/helpers/message_helpers.dart';
import 'package:paperless_mobile/routes/typed/branches/scanner_route.dart';
import 'package:paperless_mobile/routes/typed/branches/upload_queue_route.dart';
import 'package:path/path.dart' as p;
import 'package:receive_sharing_intent/receive_sharing_intent.dart';
@@ -39,57 +40,40 @@ class _UploadQueueShellState extends State<UploadQueueShell> {
ReceiveSharingIntent.getInitialMedia().then(_onReceiveSharedFiles);
_subscription =
ReceiveSharingIntent.getMediaStream().listen(_onReceiveSharedFiles);
context.read<PendingTasksNotifier>().addListener(_onTasksChanged);
// WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
// context.read<ReceiveShareCubit>().loadFromConsumptionDirectory(
// userId: context.read<LocalUserAccount>().id,
// );
// final state = context.read<ReceiveShareCubit>().state;
// print("Current state is " + state.toString());
// final files = state.files;
// if (files.isNotEmpty) {
// showSnackBar(
// WidgetsBinding.instance.addPostFrameCallback((_) async {
// final notifier = context.read<ConsumptionChangeNotifier>();
// await notifier.isInitialized;
// final pendingFiles = notifier.pendingFiles;
// if (pendingFiles.isEmpty) {
// return;
// }
// final shouldProcess = await showDialog<bool>(
// context: context,
// builder: (context) =>
// PendingFilesInfoDialog(pendingFiles: pendingFiles),
// ) ??
// false;
// if (shouldProcess) {
// final userId = context.read<LocalUserAccount>().id;
// await consumeLocalFiles(
// context,
// "You have ${files.length} shared files waiting to be uploaded.",
// action: SnackBarActionConfig(
// label: "Show me",
// onPressed: () {
// UploadQueueRoute().push(context);
// },
// ),
// files: pendingFiles,
// userId: userId,
// );
// // showDialog(
// // context: context,
// // builder: (context) => AlertDialog(
// // title: Text("Pending files"),
// // content: Text(
// // "You have ${files.length} files waiting to be uploaded.",
// // ),
// // actions: [
// // TextButton(
// // child: Text(S.of(context)!.gotIt),
// // onPressed: () {
// // Navigator.pop(context);
// // UploadQueueRoute().push(context);
// // },
// // ),
// // ],
// // ),
// // );
// }
// });
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
context.read<PendingTasksNotifier>().addListener(_onTasksChanged);
}
void _onTasksChanged() {
final taskNotifier = context.read<PendingTasksNotifier>();
final userId = context.read<LocalUserAccount>().id;
for (var task in taskNotifier.value.values) {
context.read<LocalNotificationService>().notifyTaskChanged(task);
context
.read<LocalNotificationService>()
.notifyTaskChanged(task, userId: userId);
}
}
@@ -103,23 +87,18 @@ class _UploadQueueShellState extends State<UploadQueueShell> {
files: files,
userId: userId,
);
final localFiles = notifier.pendingFiles;
for (int i = 0; i < localFiles.length; i++) {
final file = localFiles[i];
await consumeLocalFile(
context,
file: file,
userId: userId,
exitAppAfterConsumed: i == localFiles.length - 1,
);
}
consumeLocalFiles(
context,
files: files,
userId: userId,
exitAppAfterConsumed: true,
);
}
}
@override
void dispose() {
_subscription?.cancel();
context.read<PendingTasksNotifier>().removeListener(_onTasksChanged);
super.dispose();
}
@@ -135,28 +114,43 @@ Future<void> consumeLocalFile(
required String userId,
bool exitAppAfterConsumed = false,
}) async {
final filename = p.basename(file.path);
final hasInternetConnection =
await context.read<ConnectivityStatusService>().isConnectedToInternet();
if (!hasInternetConnection) {
showSnackBar(
context,
"Could not consume $filename", //TODO: INTL
details: S.of(context)!.youreOffline,
);
return;
}
final consumptionNotifier = context.read<ConsumptionChangeNotifier>();
final taskNotifier = context.read<PendingTasksNotifier>();
final ioFile = File(file.path);
// if (!await ioFile.exists()) {
// Fluttertoast.showToast(
// msg: S.of(context)!.couldNotAccessReceivedFile,
// toastLength: Toast.LENGTH_LONG,
// );
// }
final bytes = ioFile.readAsBytes();
final bytes = file.readAsBytes();
final shouldDirectlyUpload =
Hive.globalSettingsBox.getValue()!.skipDocumentPreprarationOnUpload;
if (shouldDirectlyUpload) {
final taskId = await context.read<PaperlessDocumentsApi>().create(
await bytes,
filename: p.basename(file.path),
title: p.basenameWithoutExtension(file.path),
);
consumptionNotifier.discardFile(file, userId: userId);
if (taskId != null) {
taskNotifier.listenToTaskChanges(taskId);
try {
final taskId = await context.read<PaperlessDocumentsApi>().create(
await bytes,
filename: filename,
title: p.basenameWithoutExtension(file.path),
);
consumptionNotifier.discardFile(file, userId: userId);
if (taskId != null) {
taskNotifier.listenToTaskChanges(taskId);
}
} catch (error) {
await Fluttertoast.showToast(
msg: S.of(context)!.couldNotUploadDocument,
);
return;
} finally {
if (exitAppAfterConsumed) {
SystemNavigator.pop();
}
}
} else {
final result = await DocumentUploadRoute(
@@ -193,3 +187,20 @@ Future<void> consumeLocalFile(
}
}
}
Future<void> consumeLocalFiles(
BuildContext context, {
required List<File> files,
required String userId,
bool exitAppAfterConsumed = false,
}) async {
for (int i = 0; i < files.length; i++) {
final file = files[i];
await consumeLocalFile(
context,
file: file,
userId: userId,
exitAppAfterConsumed: exitAppAfterConsumed && (i == files.length - 1),
);
}
}