feat: bugfixes, finished go_router migration, implemented better visibility of states

This commit is contained in:
Anton Stubenbord
2023-10-06 01:17:08 +02:00
parent ad23df4f89
commit a2c5ced3b7
102 changed files with 1512 additions and 3090 deletions

View File

@@ -1,104 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:paperless_api/paperless_api.dart';
import 'package:paperless_mobile/core/widgets/dialog_utils/dialog_cancel_button.dart';
import 'package:paperless_mobile/extensions/flutter_extensions.dart';
import 'package:paperless_mobile/features/document_bulk_action/cubit/document_bulk_action_cubit.dart';
import 'package:paperless_mobile/features/labels/view/widgets/label_form_field.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
typedef LabelOptionsSelector<T extends Label> = Map<int, T> Function(
DocumentBulkActionState state);
class BulkEditLabelBottomSheet<T extends Label> extends StatefulWidget {
final String title;
final String formFieldLabel;
final Widget formFieldPrefixIcon;
final LabelOptionsSelector<T> availableOptionsSelector;
final void Function(int? selectedId) onSubmit;
final int? initialValue;
final bool canCreateNewLabel;
const BulkEditLabelBottomSheet({
super.key,
required this.title,
required this.formFieldLabel,
required this.formFieldPrefixIcon,
required this.availableOptionsSelector,
required this.onSubmit,
this.initialValue,
required this.canCreateNewLabel,
});
@override
State<BulkEditLabelBottomSheet<T>> createState() =>
_BulkEditLabelBottomSheetState<T>();
}
class _BulkEditLabelBottomSheetState<T extends Label>
extends State<BulkEditLabelBottomSheet<T>> {
final _formKey = GlobalKey<FormBuilderState>();
@override
Widget build(BuildContext context) {
return Padding(
padding:
EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
child: BlocBuilder<DocumentBulkActionCubit, DocumentBulkActionState>(
builder: (context, state) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
widget.title,
style: Theme.of(context).textTheme.titleLarge,
).paddedOnly(bottom: 24),
FormBuilder(
key: _formKey,
child: LabelFormField<T>(
initialValue: widget.initialValue != null
? IdQueryParameter.fromId(widget.initialValue!)
: const IdQueryParameter.unset(),
canCreateNewLabel: widget.canCreateNewLabel,
name: "labelFormField",
options: widget.availableOptionsSelector(state),
labelText: widget.formFieldLabel,
prefixIcon: widget.formFieldPrefixIcon,
allowSelectUnassigned: true,
),
),
const SizedBox(height: 8),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
const DialogCancelButton(),
const SizedBox(width: 16),
FilledButton(
onPressed: () {
if (_formKey.currentState?.saveAndValidate() ??
false) {
final value = _formKey.currentState
?.getRawValue('labelFormField')
as IdQueryParameter?;
widget.onSubmit(value?.maybeWhen(
fromId: (id) => id, orElse: () => null));
}
},
child: Text(S.of(context)!.apply),
),
],
).padded(8),
],
),
),
);
},
),
);
}
}

View File

@@ -1,30 +0,0 @@
// import 'package:flutter/material.dart';
// import 'package:flutter/src/widgets/framework.dart';
// import 'package:flutter/src/widgets/placeholder.dart';
// class LabelBulkSelectionWidget extends StatelessWidget {
// final int labelId;
// final String title;
// final bool selected;
// final bool excluded;
// final Widget Function(int id) leadingWidgetBuilder;
// final void Function(int id) onSelected;
// final void Function(int id) onUnselected;
// final void Function(int id) onRemoved;
// const LabelBulkSelectionWidget({
// super.key,
// required this.labelId,
// required this.title,
// required this.leadingWidgetBuilder,
// required this.onSelected,
// required this.onUnselected,
// required this.onRemoved,
// });
// @override
// Widget build(BuildContext context) {
// return ListTile(
// title: Text(title),
// );
// }
// }

View File

@@ -6,16 +6,14 @@ import 'package:flutter/material.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:open_filex/open_filex.dart';
import 'package:paperless_api/paperless_api.dart';
import 'package:paperless_mobile/core/database/tables/local_user_account.dart';
import 'package:paperless_mobile/core/notifier/document_changed_notifier.dart';
import 'package:paperless_mobile/core/repository/label_repository.dart';
import 'package:paperless_mobile/core/service/file_description.dart';
import 'package:paperless_mobile/core/service/file_service.dart';
import 'package:paperless_mobile/features/notifications/services/local_notification_service.dart';
import 'package:printing/printing.dart';
import 'package:share_plus/share_plus.dart';
import 'package:cross_file/cross_file.dart';
import 'package:path/path.dart' as p;
part 'document_details_cubit.freezed.dart';
part 'document_details_state.dart';
@@ -94,11 +92,9 @@ class DocumentDetailsCubit extends Cubit<DocumentDetailsState> {
if (state.metaData == null) {
await loadMetaData();
}
final desc = FileDescription.fromPath(
state.metaData!.mediaFilename.replaceAll("/", " "),
);
final filePath = state.metaData!.mediaFilename.replaceAll("/", " ");
final fileName = "${desc.filename}.pdf";
final fileName = "${p.basenameWithoutExtension(filePath)}.pdf";
final file = File("${cacheDir.path}/$fileName");
if (!file.existsSync()) {
@@ -126,50 +122,58 @@ class DocumentDetailsCubit extends Cubit<DocumentDetailsState> {
if (state.metaData == null) {
await loadMetaData();
}
String filePath = _buildDownloadFilePath(
String targetPath = _buildDownloadFilePath(
downloadOriginal,
await FileService.downloadsDirectory,
);
final desc = FileDescription.fromPath(
state.metaData!.mediaFilename
.replaceAll("/", " "), // Flatten directory structure
);
if (!File(filePath).existsSync()) {
File(filePath).createSync();
if (!await File(targetPath).exists()) {
await File(targetPath).create();
} else {
return _notificationService.notifyFileDownload(
await _notificationService.notifyFileDownload(
document: state.document,
filename: "${desc.filename}.${desc.extension}",
filePath: filePath,
filename: p.basename(targetPath),
filePath: targetPath,
finished: true,
locale: locale,
userId: userId,
);
}
await _notificationService.notifyFileDownload(
document: state.document,
filename: "${desc.filename}.${desc.extension}",
filePath: filePath,
finished: false,
locale: locale,
userId: userId,
);
// await _notificationService.notifyFileDownload(
// document: state.document,
// filename: p.basename(targetPath),
// filePath: targetPath,
// finished: false,
// locale: locale,
// userId: userId,
// );
await _api.downloadToFile(
state.document,
filePath,
targetPath,
original: downloadOriginal,
onProgressChanged: (progress) {
_notificationService.notifyFileDownload(
document: state.document,
filename: p.basename(targetPath),
filePath: targetPath,
finished: true,
locale: locale,
userId: userId,
progress: progress,
);
},
);
await _notificationService.notifyFileDownload(
document: state.document,
filename: "${desc.filename}.${desc.extension}",
filePath: filePath,
filename: p.basename(targetPath),
filePath: targetPath,
finished: true,
locale: locale,
userId: userId,
);
debugPrint("Downloaded file to $filePath");
debugPrint("Downloaded file to $targetPath");
}
Future<void> shareDocument({bool shareOriginal = false}) async {
@@ -220,12 +224,9 @@ class DocumentDetailsCubit extends Cubit<DocumentDetailsState> {
}
String _buildDownloadFilePath(bool original, Directory dir) {
final description = FileDescription.fromPath(
state.metaData!.mediaFilename
.replaceAll("/", " "), // Flatten directory structure
);
final extension = original ? description.extension : 'pdf';
return "${dir.path}/${description.filename}.$extension";
final normalizedPath = state.metaData!.mediaFilename.replaceAll("/", " ");
final extension = original ? p.extension(normalizedPath) : '.pdf';
return "${dir.path}/${p.basenameWithoutExtension(normalizedPath)}$extension";
}
@override

View File

@@ -1,4 +1,3 @@
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
@@ -48,7 +47,7 @@ class _DocumentDetailsPageState extends State<DocumentDetailsPage> {
Widget build(BuildContext context) {
final hasMultiUserSupport =
context.watch<LocalUserAccount>().hasMultiUserSupport;
final tabLength = 4 + (hasMultiUserSupport ? 1 : 0);
final tabLength = 4 + (hasMultiUserSupport && false ? 1 : 0);
return WillPopScope(
onWillPop: () async {
Navigator.of(context)
@@ -86,51 +85,52 @@ class _DocumentDetailsPageState extends State<DocumentDetailsPage> {
collapsedHeight: kToolbarHeight,
expandedHeight: 250.0,
flexibleSpace: FlexibleSpaceBar(
background: Stack(
alignment: Alignment.topCenter,
children: [
BlocBuilder<DocumentDetailsCubit,
DocumentDetailsState>(
builder: (context, state) {
return Positioned.fill(
child: GestureDetector(
onTap: () {
DocumentPreviewRoute($extra: state.document)
.push(context);
},
child: DocumentPreview(
document: state.document,
fit: BoxFit.cover,
background: BlocBuilder<DocumentDetailsCubit,
DocumentDetailsState>(
builder: (context, state) {
return Hero(
tag: "thumb_${state.document.id}",
child: GestureDetector(
onTap: () {
DocumentPreviewRoute($extra: state.document)
.push(context);
},
child: Stack(
alignment: Alignment.topCenter,
children: [
Positioned.fill(
child: DocumentPreview(
enableHero: false,
document: state.document,
fit: BoxFit.cover,
),
),
),
);
},
),
// Positioned.fill(
// top: -kToolbarHeight,
// child: DecoratedBox(
// decoration: BoxDecoration(
// gradient: LinearGradient(
// colors: [
// Theme.of(context)
// .colorScheme
// .background
// .withOpacity(0.8),
// Theme.of(context)
// .colorScheme
// .background
// .withOpacity(0.5),
// Colors.transparent,
// Colors.transparent,
// Colors.transparent,
// ],
// begin: Alignment.topCenter,
// end: Alignment.bottomCenter,
// ),
// ),
// ),
// ),
],
Positioned.fill(
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
stops: [0.2, 0.4],
colors: [
Theme.of(context)
.colorScheme
.background
.withOpacity(0.6),
Theme.of(context)
.colorScheme
.background
.withOpacity(0.3),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
),
),
],
),
),
);
},
),
),
bottom: ColoredTabBar(
@@ -177,7 +177,7 @@ class _DocumentDetailsPageState extends State<DocumentDetailsPage> {
),
),
),
if (hasMultiUserSupport)
if (hasMultiUserSupport && false)
Tab(
child: Text(
"Permissions",
@@ -266,7 +266,7 @@ class _DocumentDetailsPageState extends State<DocumentDetailsPage> {
),
],
),
if (hasMultiUserSupport)
if (hasMultiUserSupport && false)
CustomScrollView(
controller: _pagingScrollController,
slivers: [
@@ -406,7 +406,7 @@ class _DocumentDetailsPageState extends State<DocumentDetailsPage> {
if (delete) {
try {
await context.read<DocumentDetailsCubit>().delete(document);
showSnackBar(context, S.of(context)!.documentSuccessfullyDeleted);
// showSnackBar(context, S.of(context)!.documentSuccessfullyDeleted);
} on PaperlessApiException catch (error, stackTrace) {
showErrorMessage(context, error, stackTrace);
} finally {

View File

@@ -40,7 +40,6 @@ class _DocumentEditPageState extends State<DocumentEditPage> {
static const fkContent = 'content';
final GlobalKey<FormBuilderState> _formKey = GlobalKey();
bool _isSubmitLoading = false;
@override
Widget build(BuildContext context) {
@@ -314,18 +313,13 @@ class _DocumentEditPageState extends State<DocumentEditPage> {
tags: (values[fkTags] as IdsTagsQuery?)?.include,
content: values[fkContent],
);
setState(() {
_isSubmitLoading = true;
});
try {
await context.read<DocumentEditCubit>().updateDocument(mergedDocument);
showSnackBar(context, S.of(context)!.documentSuccessfullyUpdated);
} on PaperlessApiException catch (error, stackTrace) {
showErrorMessage(context, error, stackTrace);
} finally {
setState(() {
_isSubmitLoading = false;
});
context.pop();
}
}

View File

@@ -1,44 +0,0 @@
import 'dart:io';
import 'dart:isolate';
import 'package:image/image.dart' as im;
typedef ImageOperationCallback = im.Image Function(im.Image);
class DecodeParam {
final File file;
final SendPort sendPort;
final im.Image Function(im.Image) imageOperation;
DecodeParam(this.file, this.sendPort, this.imageOperation);
}
void decodeIsolate(DecodeParam param) {
// Read an image from file (webp in this case).
// decodeImage will identify the format of the image and use the appropriate
// decoder.
var image = im.decodeImage(param.file.readAsBytesSync())!;
// Resize the image to a 120x? thumbnail (maintaining the aspect ratio).
var processed = param.imageOperation(image);
param.sendPort.send(processed);
}
// Decode and process an image file in a separate thread (isolate) to avoid
// stalling the main UI thread.
Future<File> processImage(
File file,
ImageOperationCallback imageOperation,
) async {
var receivePort = ReceivePort();
await Isolate.spawn(
decodeIsolate,
DecodeParam(
file,
receivePort.sendPort,
imageOperation,
));
var image = await receivePort.first as im.Image;
return file.writeAsBytes(im.encodePng(image));
}

View File

@@ -13,7 +13,6 @@ import 'package:paperless_mobile/constants.dart';
import 'package:paperless_mobile/core/config/hive/hive_config.dart';
import 'package:paperless_mobile/core/database/tables/global_settings.dart';
import 'package:paperless_mobile/core/global/constants.dart';
import 'package:paperless_mobile/core/service/file_description.dart';
import 'package:paperless_mobile/core/service/file_service.dart';
import 'package:paperless_mobile/features/app_drawer/view/app_drawer.dart';
import 'package:paperless_mobile/features/document_scan/cubit/document_scanner_cubit.dart';
@@ -22,7 +21,6 @@ import 'package:paperless_mobile/features/document_scan/view/widgets/scanned_ima
import 'package:paperless_mobile/features/document_search/view/sliver_search_bar.dart';
import 'package:paperless_mobile/features/document_upload/view/document_upload_preparation_page.dart';
import 'package:paperless_mobile/features/documents/view/pages/document_view.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/connectivity_aware_action_wrapper.dart';
import 'package:paperless_mobile/helpers/message_helpers.dart';
@@ -261,12 +259,12 @@ class _ScannerPageState extends State<ScannerPage>
$extra: file.bytes,
fileExtension: file.extension,
).push<DocumentUploadResult>(context);
if ((uploadResult?.success ?? false) && uploadResult?.taskId != null) {
if (uploadResult?.success ?? false) {
// For paperless version older than 1.11.3, task id will always be null!
context.read<DocumentScannerCubit>().reset();
context
.read<PendingTasksNotifier>()
.listenToTaskChanges(uploadResult!.taskId!);
// context
// .read<PendingTasksNotifier>()
// .listenToTaskChanges(uploadResult!.taskId!);
}
}
@@ -350,17 +348,17 @@ class _ScannerPageState extends State<ScannerPage>
void _onUploadFromFilesystem() async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: supportedFileExtensions,
allowedExtensions:
supportedFileExtensions.map((e) => e.replaceAll(".", "")).toList(),
withData: true,
allowMultiple: false,
);
if (result?.files.single.path != null) {
final path = result!.files.single.path!;
final fileDescription = FileDescription.fromPath(path);
final extension = p.extension(path);
final filename = p.basenameWithoutExtension(path);
File file = File(path);
if (!supportedFileExtensions.contains(
fileDescription.extension.toLowerCase(),
)) {
if (!supportedFileExtensions.contains(extension.toLowerCase())) {
showErrorMessage(
context,
const PaperlessApiException(ErrorCode.unsupportedFileFormat),
@@ -369,10 +367,15 @@ class _ScannerPageState extends State<ScannerPage>
}
DocumentUploadRoute(
$extra: file.readAsBytesSync(),
filename: fileDescription.filename,
title: fileDescription.filename,
fileExtension: fileDescription.extension,
).push(context);
filename: filename,
title: filename,
fileExtension: extension,
).push<DocumentUploadResult>(context);
// if (uploadResult.success && uploadResult.taskId != null) {
// context
// .read<PendingTasksNotifier>()
// .listenToTaskChanges(uploadResult.taskId!);
// }
}
}

View File

@@ -16,6 +16,8 @@ class DocumentSearchCubit extends Cubit<DocumentSearchState>
with DocumentPagingBlocMixin {
@override
final PaperlessDocumentsApi api;
@override
final ConnectivityStatusService connectivityStatusService;
@override
final DocumentChangedNotifier notifier;
@@ -25,6 +27,7 @@ class DocumentSearchCubit extends Cubit<DocumentSearchState>
this.api,
this.notifier,
this._userAppState,
this.connectivityStatusService,
) : super(
DocumentSearchState(
searchHistory: _userAppState.documentSearchHistory),
@@ -120,9 +123,4 @@ class DocumentSearchCubit extends Cubit<DocumentSearchState>
@override
Future<void> onFilterUpdated(DocumentFilter filter) async {}
@override
// TODO: implement connectivityStatusService
ConnectivityStatusService get connectivityStatusService =>
throw UnimplementedError();
}

View File

@@ -8,6 +8,8 @@ import 'package:paperless_mobile/features/document_search/cubit/document_search_
import 'package:paperless_mobile/features/document_search/view/document_search_page.dart';
import 'package:paperless_mobile/features/settings/view/manage_accounts_page.dart';
import 'package:paperless_mobile/features/settings/view/widgets/user_avatar.dart';
import 'package:paperless_mobile/features/sharing/cubit/receive_share_cubit.dart';
import 'package:paperless_mobile/features/tasks/model/pending_tasks_notifier.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
import 'package:provider/provider.dart';
@@ -51,7 +53,21 @@ class _DocumentSearchBarState extends State<DocumentSearchBar> {
crossAxisAlignment: CrossAxisAlignment.center,
children: [
IconButton(
icon: const Icon(Icons.menu),
icon: ListenableBuilder(
listenable:
context.read<ConsumptionChangeNotifier>(),
builder: (context, child) {
return Badge(
isLabelVisible: context
.read<ConsumptionChangeNotifier>()
.pendingFiles
.isNotEmpty,
child: const Icon(Icons.menu),
backgroundColor: Colors.red,
smallSize: 8,
);
},
),
onPressed: Scaffold.of(context).openDrawer,
),
Flexible(
@@ -81,6 +97,7 @@ class _DocumentSearchBarState extends State<DocumentSearchBar> {
context.read(),
Hive.box<LocalUserAppState>(HiveBoxes.localUserAppState)
.get(context.read<LocalUserAccount>().id)!,
context.read(),
),
child: const DocumentSearchPage(),
);
@@ -95,10 +112,7 @@ class _DocumentSearchBarState extends State<DocumentSearchBar> {
onPressed: () {
showDialog(
context: context,
builder: (_) => Provider.value(
value: context.read<LocalUserAccount>(),
child: const ManageAccountsPage(),
),
builder: (_) => const ManageAccountsPage(),
);
},
);

View File

@@ -1,5 +1,4 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hive_flutter/adapters.dart';
import 'package:paperless_api/paperless_api.dart';
import 'package:paperless_mobile/core/config/hive/hive_config.dart';
@@ -9,7 +8,6 @@ import 'package:paperless_mobile/features/settings/view/manage_accounts_page.dar
import 'package:paperless_mobile/features/settings/view/widgets/global_settings_builder.dart';
import 'package:paperless_mobile/features/settings/view/widgets/user_avatar.dart';
import 'package:provider/provider.dart';
import 'package:sliver_tools/sliver_tools.dart';
class SliverSearchBar extends StatelessWidget {
final bool floating;
@@ -24,10 +22,8 @@ class SliverSearchBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
if (context.watch<LocalUserAccount>().paperlessUser.canViewDocuments) {
return SliverAppBar(
return const SliverAppBar(
titleSpacing: 8,
automaticallyImplyLeading: false,
title: DocumentSearchBar(),

View File

@@ -6,12 +6,13 @@ import 'package:flutter/foundation.dart';
import 'package:paperless_api/paperless_api.dart';
import 'package:paperless_mobile/core/repository/label_repository.dart';
import 'package:paperless_mobile/core/service/connectivity_status_service.dart';
import 'package:paperless_mobile/features/tasks/model/pending_tasks_notifier.dart';
part 'document_upload_state.dart';
class DocumentUploadCubit extends Cubit<DocumentUploadState> {
final PaperlessDocumentsApi _documentApi;
final PendingTasksNotifier _tasksNotifier;
final LabelRepository _labelRepository;
final ConnectivityStatusService _connectivityStatusService;
@@ -19,6 +20,7 @@ class DocumentUploadCubit extends Cubit<DocumentUploadState> {
this._labelRepository,
this._documentApi,
this._connectivityStatusService,
this._tasksNotifier,
) : super(const DocumentUploadState()) {
_labelRepository.addListener(
this,
@@ -43,7 +45,7 @@ class DocumentUploadCubit extends Cubit<DocumentUploadState> {
DateTime? createdAt,
int? asn,
}) async {
return await _documentApi.create(
final taskId = await _documentApi.create(
bytes,
filename: filename,
title: title,
@@ -53,6 +55,10 @@ class DocumentUploadCubit extends Cubit<DocumentUploadState> {
createdAt: createdAt,
asn: asn,
);
if (taskId != null) {
_tasksNotifier.listenToTaskChanges(taskId);
}
return taskId;
}
@override

View File

@@ -6,7 +6,6 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:go_router/go_router.dart';
import 'package:hive/hive.dart';
import 'package:image/image.dart' as img;
import 'package:intl/date_symbol_data_local.dart';
import 'package:intl/intl.dart';
import 'package:paperless_api/paperless_api.dart';
@@ -24,7 +23,6 @@ import 'package:paperless_mobile/features/labels/tags/view/widgets/tags_form_fie
import 'package:paperless_mobile/features/labels/view/widgets/label_form_field.dart';
import 'package:paperless_mobile/features/sharing/view/widgets/file_thumbnail.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
import 'package:paperless_mobile/helpers/message_helpers.dart';
import 'package:provider/provider.dart';

View File

@@ -247,8 +247,13 @@ class _DocumentsPageState extends State<DocumentsPage> {
resizeToAvoidBottomInset: true,
body: WillPopScope(
onWillPop: () async {
if (context.read<DocumentsCubit>().state.selection.isNotEmpty) {
context.read<DocumentsCubit>().resetSelection();
final cubit = context.read<DocumentsCubit>();
if (cubit.state.selection.isNotEmpty) {
cubit.resetSelection();
return false;
}
if (cubit.state.filter.appliedFiltersCount > 0 || cubit.state.filter.selectedView != null) {
await _onResetFilter();
return false;
}
return true;

View File

@@ -31,16 +31,19 @@ class DocumentPreview extends StatelessWidget {
Widget build(BuildContext context) {
return ConnectivityAwareActionWrapper(
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: isClickable
? () => DocumentPreviewRoute($extra: document).push(context)
: null,
child: HeroMode(
enabled: enableHero,
child: Hero(
tag: "thumb_${document.id}",
child: _buildPreview(context),
),
),
child: Builder(builder: (context) {
if (enableHero) {
return Hero(
tag: "thumb_${document.id}",
child: _buildPreview(context),
);
}
return _buildPreview(context);
}),
),
);
}

View File

@@ -1,11 +0,0 @@
import 'package:flutter/material.dart';
import 'package:paperless_mobile/extensions/flutter_extensions.dart';
class NewItemsLoadingWidget extends StatelessWidget {
const NewItemsLoadingWidget({super.key});
@override
Widget build(BuildContext context) {
return Center(child: const CircularProgressIndicator().padded());
}
}

View File

@@ -6,7 +6,6 @@ import 'package:paperless_api/paperless_api.dart';
import 'package:paperless_mobile/features/documents/view/pages/documents_page.dart';
import 'package:paperless_mobile/features/documents/view/widgets/search/document_filter_form.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
import 'package:paperless_mobile/helpers/connectivity_aware_action_wrapper.dart';
enum DateRangeSelection { before, after }

View File

@@ -1,10 +1,9 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:hive_flutter/adapters.dart';
import 'package:paperless_api/paperless_api.dart';
import 'package:paperless_mobile/core/config/hive/hive_config.dart';
import 'package:paperless_mobile/core/database/tables/local_user_account.dart';
import 'package:paperless_mobile/core/config/hive/hive_extensions.dart';
import 'package:paperless_mobile/core/database/tables/local_user_app_state.dart';
import 'package:paperless_mobile/core/factory/paperless_api_factory.dart';
import 'package:paperless_mobile/core/repository/label_repository.dart';
@@ -17,14 +16,9 @@ import 'package:paperless_mobile/features/documents/cubit/documents_cubit.dart';
import 'package:paperless_mobile/features/home/view/model/api_version.dart';
import 'package:paperless_mobile/features/inbox/cubit/inbox_cubit.dart';
import 'package:paperless_mobile/features/labels/cubit/label_cubit.dart';
import 'package:paperless_mobile/features/login/cubit/authentication_cubit.dart';
import 'package:paperless_mobile/features/saved_view/cubit/saved_view_cubit.dart';
import 'package:paperless_mobile/features/settings/view/widgets/global_settings_builder.dart';
import 'package:paperless_mobile/features/tasks/model/pending_tasks_notifier.dart';
import 'package:paperless_mobile/routes/typed/branches/landing_route.dart';
import 'package:paperless_mobile/routes/typed/top_level/login_route.dart';
import 'package:paperless_mobile/routes/typed/top_level/switching_accounts_route.dart';
import 'package:paperless_mobile/routes/typed/top_level/verify_identity_route.dart';
import 'package:provider/provider.dart';
class HomeShellWidget extends StatelessWidget {
@@ -52,16 +46,16 @@ class HomeShellWidget extends StatelessWidget {
return GlobalSettingsBuilder(
builder: (context, settings) {
final currentUserId = settings.loggedInUserId;
if (currentUserId == null) {
// This is currently the case (only for a few ms) when the current user logs out of the app.
return const SizedBox.shrink();
}
final apiVersion = ApiVersion(paperlessApiVersion);
return ValueListenableBuilder(
valueListenable:
Hive.box<LocalUserAccount>(HiveBoxes.localUserAccount)
.listenable(keys: [currentUserId]),
Hive.localUserAccountBox.listenable(keys: [currentUserId]),
builder: (context, box, _) {
if (currentUserId == null) {
//This only happens during logout...
//TODO: Find way so this does not occur anymore
return SizedBox.shrink();
}
final currentLocalUser = box.get(currentUserId)!;
return MultiProvider(
key: ValueKey(currentUserId),
@@ -181,9 +175,7 @@ class HomeShellWidget extends StatelessWidget {
context.read(),
context.read(),
);
if (currentLocalUser
.paperlessUser.canViewDocuments &&
currentLocalUser.paperlessUser.canViewTags) {
if (currentLocalUser.paperlessUser.canViewInbox) {
inboxCubit.initialize();
}
return inboxCubit;

View File

@@ -1,41 +0,0 @@
import 'package:flutter/material.dart';
class RouteDescription {
final String label;
final Icon icon;
final Icon selectedIcon;
final Widget Function(Widget icon)? badgeBuilder;
final bool enabled;
RouteDescription({
required this.label,
required this.icon,
required this.selectedIcon,
this.badgeBuilder,
this.enabled = true,
});
NavigationDestination toNavigationDestination() {
return NavigationDestination(
label: label,
icon: badgeBuilder?.call(icon) ?? icon,
selectedIcon: badgeBuilder?.call(selectedIcon) ?? selectedIcon,
);
}
NavigationRailDestination toNavigationRailDestination() {
return NavigationRailDestination(
label: Text(label),
icon: icon,
selectedIcon: selectedIcon,
);
}
BottomNavigationBarItem toBottomNavigationBarItem() {
return BottomNavigationBarItem(
label: label,
icon: badgeBuilder?.call(icon) ?? icon,
activeIcon: badgeBuilder?.call(selectedIcon) ?? selectedIcon,
);
}
}

View File

@@ -8,12 +8,6 @@ import 'package:paperless_mobile/features/inbox/cubit/inbox_cubit.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
import 'package:paperless_mobile/theme.dart';
const _landingPage = 0;
const _documentsIndex = 1;
const _scannerIndex = 2;
const _labelsIndex = 3;
const _inboxIndex = 4;
class ScaffoldWithNavigationBar extends StatefulWidget {
final UserModel authenticatedUser;
final StatefulNavigationShell navigationShell;
@@ -29,11 +23,6 @@ class ScaffoldWithNavigationBar extends StatefulWidget {
}
class ScaffoldWithNavigationBarState extends State<ScaffoldWithNavigationBar> {
@override
void didChangeDependencies() {
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
@@ -58,7 +47,7 @@ class ScaffoldWithNavigationBarState extends State<ScaffoldWithNavigationBar> {
Icons.home,
color: theme.colorScheme.primary,
),
label: S.of(context)!.home,
label: S.of(context)!.home,
),
_toggleDestination(
NavigationDestination(

View File

@@ -1,78 +0,0 @@
import 'package:flutter/material.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:paperless_mobile/core/repository/label_repository.dart';
import 'package:paperless_mobile/core/repository/saved_view_repository.dart';
import 'package:paperless_mobile/extensions/flutter_extensions.dart';
import 'package:paperless_mobile/features/login/cubit/authentication_cubit.dart';
import 'package:paperless_mobile/features/settings/view/widgets/user_settings_builder.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
import 'package:provider/provider.dart';
class VerifyIdentityPage extends StatelessWidget {
const VerifyIdentityPage({super.key});
@override
Widget build(BuildContext context) {
return Material(
child: Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: Theme.of(context).colorScheme.background,
title: Text(S.of(context)!.verifyYourIdentity),
),
body: UserAccountBuilder(
builder: (context, settings) {
if (settings == null) {
return const SizedBox.shrink();
}
return Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(S
.of(context)!
.useTheConfiguredBiometricFactorToAuthenticate)
.paddedSymmetrically(horizontal: 16),
const Icon(
Icons.fingerprint,
size: 96,
),
Wrap(
alignment: WrapAlignment.spaceBetween,
runAlignment: WrapAlignment.spaceBetween,
runSpacing: 8,
spacing: 8,
children: [
TextButton(
onPressed: () => _logout(context),
child: Text(
S.of(context)!.disconnect,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
),
),
),
ElevatedButton(
onPressed: () => context
.read<AuthenticationCubit>()
.restoreSessionState(),
child: Text(S.of(context)!.verifyIdentity),
),
],
).padded(16),
],
);
},
),
),
);
}
void _logout(BuildContext context) {
context.read<AuthenticationCubit>().logout();
context.read<LabelRepository>().clear();
context.read<SavedViewRepository>().clear();
HydratedBloc.storage.clear();
}
}

View File

@@ -19,8 +19,10 @@ class InboxCubit extends HydratedCubit<InboxState>
final LabelRepository _labelRepository;
final PaperlessDocumentsApi _documentsApi;
@override
final ConnectivityStatusService connectivityStatusService;
@override
final DocumentChangedNotifier notifier;
@@ -35,21 +37,34 @@ class InboxCubit extends HydratedCubit<InboxState>
this._labelRepository,
this.notifier,
this.connectivityStatusService,
) : super(InboxState(
labels: _labelRepository.state,
)) {
) : super(InboxState(labels: _labelRepository.state)) {
notifier.addListener(
this,
onDeleted: remove,
onUpdated: (document) {
if (document.tags
final hasInboxTag = document.tags
.toSet()
.intersection(state.inboxTags.toSet())
.isEmpty) {
.isNotEmpty;
final wasInInboxBeforeUpdate =
state.documents.map((e) => e.id).contains(document.id);
if (!hasInboxTag && wasInInboxBeforeUpdate) {
print(
"INBOX: Removing document: has: $hasInboxTag, had: $wasInInboxBeforeUpdate");
remove(document);
emit(state.copyWith(itemsInInboxCount: state.itemsInInboxCount - 1));
} else {
replace(document);
} else if (hasInboxTag) {
if (wasInInboxBeforeUpdate) {
print(
"INBOX: Replacing document: has: $hasInboxTag, had: $wasInInboxBeforeUpdate");
replace(document);
} else {
print(
"INBOX: Adding document: has: $hasInboxTag, had: $wasInInboxBeforeUpdate");
_addDocument(document);
emit(
state.copyWith(itemsInInboxCount: state.itemsInInboxCount + 1));
}
}
},
);
@@ -61,22 +76,20 @@ class InboxCubit extends HydratedCubit<InboxState>
);
}
@override
Future<void> initialize() async {
await refreshItemsInInboxCount(false);
await loadInbox();
}
Future<void> refreshItemsInInboxCount([bool shouldLoadInbox = true]) async {
debugPrint("Checking for new items in inbox...");
final stats = await _statsApi.getServerStatistics();
if (stats.documentsInInbox != state.itemsInInboxCount && shouldLoadInbox) {
await loadInbox();
}
emit(
state.copyWith(
itemsInInboxCount: stats.documentsInInbox,
),
);
emit(state.copyWith(itemsInInboxCount: stats.documentsInInbox));
}
///
@@ -85,7 +98,6 @@ class InboxCubit extends HydratedCubit<InboxState>
Future<void> loadInbox() async {
if (!isClosed) {
debugPrint("Initializing inbox...");
final inboxTags = await _labelRepository.findAllTags().then(
(tags) => tags.where((t) => t.isInboxTag).map((t) => t.id!),
);
@@ -113,11 +125,22 @@ class InboxCubit extends HydratedCubit<InboxState>
}
}
Future<void> _addDocument(DocumentModel document) async {
emit(state.copyWith(
value: [
...state.value,
PagedSearchResult(
count: 1,
results: [document],
),
],
));
}
///
/// Fetches inbox tag ids and loads the inbox items (documents).
///
Future<void> reloadInbox() async {
emit(state.copyWith(hasLoaded: false, isLoading: true));
final inboxTags = await _labelRepository.findAllTags().then(
(tags) => tags.where((t) => t.isInboxTag).map((t) => t.id!),
);
@@ -134,6 +157,7 @@ class InboxCubit extends HydratedCubit<InboxState>
}
emit(state.copyWith(inboxTags: inboxTags));
updateFilter(
emitLoading: false,
filter: DocumentFilter(
sortField: SortField.added,
tags: TagsQuery.ids(include: inboxTags.toList()),
@@ -154,7 +178,7 @@ class InboxCubit extends HydratedCubit<InboxState>
document.copyWith(tags: updatedTags),
);
// Remove first so document is not replaced first.
remove(document);
// remove(document);
notifier.notifyUpdated(updatedDocument);
return tagsToRemove;
}

View File

@@ -42,6 +42,7 @@ class _InboxPageState extends State<InboxPage>
@override
void initState() {
super.initState();
context.read<InboxCubit>().reloadInbox();
WidgetsBinding.instance.addPostFrameCallback((_) {
_nestedScrollViewKey.currentState!.innerController
.addListener(_scrollExtentChangedListener);

View File

@@ -1,35 +0,0 @@
import 'package:flutter/material.dart';
import 'package:paperless_api/paperless_api.dart';
class StoragePathWidget extends StatelessWidget {
final StoragePath? storagePath;
final Color? textColor;
final bool isClickable;
final void Function(int? id)? onSelected;
const StoragePathWidget({
Key? key,
this.storagePath,
this.textColor,
this.isClickable = true,
this.onSelected,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return AbsorbPointer(
absorbing: !isClickable,
child: GestureDetector(
onTap: () => onSelected?.call(storagePath?.id),
child: Text(
storagePath?.name ?? "-",
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: textColor ?? Theme.of(context).colorScheme.primary,
),
),
),
);
}
}

View File

@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import 'package:paperless_api/paperless_api.dart';
import 'package:paperless_mobile/extensions/flutter_extensions.dart';
import 'package:paperless_mobile/features/edit_label/view/impl/add_tag_page.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
@@ -68,9 +69,10 @@ class _FullscreenTagsFormState extends State<FullscreenTagsForm> {
@override
Widget build(BuildContext context) {
final showFab = MediaQuery.viewInsetsOf(context).bottom == 0;
final theme = Theme.of(context);
return Scaffold(
floatingActionButton: widget.allowCreation
floatingActionButton: widget.allowCreation && showFab
? FloatingActionButton(
heroTag: "fab_tags_form",
onPressed: _onAddTag,
@@ -238,10 +240,16 @@ class _FullscreenTagsFormState extends State<FullscreenTagsForm> {
var matches = _options
.where((e) => e.name.trim().toLowerCase().contains(normalizedQuery));
if (matches.isEmpty && widget.allowCreation) {
yield Text(S.of(context)!.noItemsFound);
yield TextButton(
child: Text(S.of(context)!.addTag),
onPressed: _onAddTag,
yield Center(
child: Column(
children: [
Text(S.of(context)!.noItemsFound).padded(),
TextButton(
child: Text(S.of(context)!.addTag),
onPressed: _onAddTag,
),
],
),
);
}
for (final tag in matches) {

View File

@@ -69,6 +69,7 @@ class _FullscreenLabelFormState<T extends Label>
@override
Widget build(BuildContext context) {
final showFab = MediaQuery.viewInsetsOf(context).bottom == 0;
final theme = Theme.of(context);
final options = _filterOptionsByQuery(_textEditingController.text);
return Scaffold(
@@ -124,6 +125,13 @@ class _FullscreenLabelFormState<T extends Label>
),
),
),
floatingActionButton: showFab && widget.onCreateNewLabel != null
? FloatingActionButton(
heroTag: "fab_label_form",
onPressed: _onCreateNewLabel,
child: const Icon(Icons.add),
)
: null,
body: Builder(
builder: (context) {
return Column(

View File

@@ -2,7 +2,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:paperless_api/paperless_api.dart';
import 'package:paperless_mobile/core/database/tables/local_user_account.dart';
import 'package:paperless_mobile/core/navigation/push_routes.dart';
import 'package:paperless_mobile/helpers/format_helpers.dart';
import 'package:paperless_mobile/routes/typed/branches/labels_route.dart';

View File

@@ -76,9 +76,7 @@ class LabelTabView<T extends Label> extends StatelessWidget {
Text(
translateMatchingAlgorithmName(
context, l.matchingAlgorithm) +
((l.match?.isNotEmpty ?? false)
? ": ${l.match}"
: ""),
(l.match.isNotEmpty ? ": ${l.match}" : ""),
maxLines: 2,
),
onOpenEditPage: canEdit ? onEdit : null,

View File

@@ -146,7 +146,7 @@ class _LandingPageState extends State<LandingPage> {
shape: Theme.of(context).cardTheme.shape,
titleTextStyle: Theme.of(context).textTheme.labelLarge,
title: Text(S.of(context)!.documentsInInbox),
onTap: currentUser.canViewTags && currentUser.canViewDocuments
onTap: currentUser.canViewInbox
? () => InboxRoute().go(context)
: null,
trailing: Text(
@@ -161,9 +161,11 @@ class _LandingPageState extends State<LandingPage> {
shape: Theme.of(context).cardTheme.shape,
titleTextStyle: Theme.of(context).textTheme.labelLarge,
title: Text(S.of(context)!.totalDocuments),
onTap: () {
DocumentsRoute().go(context);
},
onTap: currentUser.canViewDocuments
? () {
DocumentsRoute().go(context);
}
: null,
trailing: Text(
stats.documentsTotal.toString(),
style: Theme.of(context).textTheme.labelLarge,

View File

@@ -1,5 +1,3 @@
import 'dart:math';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:paperless_api/paperless_api.dart';

View File

@@ -1,8 +1,6 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:paperless_mobile/core/bloc/connectivity_cubit.dart';
import 'package:paperless_mobile/core/navigation/push_routes.dart';
import 'package:paperless_mobile/features/documents/view/widgets/adaptive_documents_view.dart';
import 'package:paperless_mobile/features/documents/view/widgets/selection/view_type_selection_widget.dart';
import 'package:paperless_mobile/features/linked_documents/cubit/linked_documents_cubit.dart';

View File

@@ -1,11 +1,9 @@
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/widgets.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:hive_flutter/adapters.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:paperless_api/paperless_api.dart';
import 'package:paperless_mobile/core/bloc/connectivity_cubit.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/global_settings.dart';
@@ -14,6 +12,7 @@ import 'package:paperless_mobile/core/database/tables/local_user_app_state.dart'
import 'package:paperless_mobile/core/database/tables/local_user_settings.dart';
import 'package:paperless_mobile/core/database/tables/user_credentials.dart';
import 'package:paperless_mobile/core/factory/paperless_api_factory.dart';
import 'package:paperless_mobile/core/interceptor/language_header.interceptor.dart';
import 'package:paperless_mobile/core/model/info_message_exception.dart';
import 'package:paperless_mobile/core/security/session_manager.dart';
import 'package:paperless_mobile/core/service/connectivity_status_service.dart';
@@ -22,21 +21,26 @@ import 'package:paperless_mobile/features/login/model/client_certificate.dart';
import 'package:paperless_mobile/features/login/model/login_form_credentials.dart';
import 'package:paperless_mobile/features/login/model/reachability_status.dart';
import 'package:paperless_mobile/features/login/services/authentication_service.dart';
import 'package:paperless_mobile/features/notifications/services/local_notification_service.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
part 'authentication_state.dart';
typedef _FutureVoidCallback = Future<void> Function();
class AuthenticationCubit extends Cubit<AuthenticationState> {
final LocalAuthenticationService _localAuthService;
final PaperlessApiFactory _apiFactory;
final SessionManager _sessionManager;
final ConnectivityStatusService _connectivityService;
final LocalNotificationService _notificationService;
AuthenticationCubit(
this._localAuthService,
this._apiFactory,
this._sessionManager,
this._connectivityService,
this._notificationService,
) : super(const UnauthenticatedState());
Future<void> login({
@@ -45,7 +49,11 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
ClientCertificate? clientCertificate,
}) async {
assert(credentials.username != null && credentials.password != null);
emit(const CheckingLoginState());
if (state is AuthenticatingState) {
// Cancel duplicate login requests
return;
}
emit(const AuthenticatingState(AuthenticatingStage.authenticating));
final localUserId = "${credentials.username}@$serverUrl";
_debugPrintMessage(
"login",
@@ -58,35 +66,63 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
credentials,
clientCertificate,
_sessionManager,
onFetchUserInformation: () async {
emit(const AuthenticatingState(
AuthenticatingStage.fetchingUserInformation));
},
onPerformLogin: () async {
emit(const AuthenticatingState(AuthenticatingStage.authenticating));
},
onPersistLocalUserData: () async {
emit(const AuthenticatingState(
AuthenticatingStage.persistingLocalUserData));
},
);
// Mark logged in user as currently active user.
final globalSettings =
Hive.box<GlobalSettings>(HiveBoxes.globalSettings).getValue()!;
globalSettings.loggedInUserId = localUserId;
await globalSettings.save();
emit(AuthenticatedState(localUserId: localUserId));
_debugPrintMessage(
"login",
"User successfully logged in.",
} catch (e) {
emit(
AuthenticationErrorState(
serverUrl: serverUrl,
username: credentials.username!,
password: credentials.password!,
clientCertificate: clientCertificate,
),
);
} catch (error) {
emit(const UnauthenticatedState());
rethrow;
}
// Mark logged in user as currently active user.
final globalSettings =
Hive.box<GlobalSettings>(HiveBoxes.globalSettings).getValue()!;
globalSettings.loggedInUserId = localUserId;
await globalSettings.save();
emit(AuthenticatedState(localUserId: localUserId));
_debugPrintMessage(
"login",
"User successfully logged in.",
);
}
/// Switches to another account if it exists.
Future<void> switchAccount(String localUserId) async {
emit(const SwitchingAccountsState());
_debugPrintMessage(
"switchAccount",
"Trying to switch to user $localUserId...",
);
final globalSettings =
Hive.box<GlobalSettings>(HiveBoxes.globalSettings).getValue()!;
if (globalSettings.loggedInUserId == localUserId) {
emit(AuthenticatedState(localUserId: localUserId));
return;
}
final userAccountBox =
Hive.box<LocalUserAccount>(HiveBoxes.localUserAccount);
// if (globalSettings.loggedInUserId == localUserId) {
// _debugPrintMessage(
// "switchAccount",
// "User $localUserId is already logged in.",
// );
// emit(AuthenticatedState(localUserId: localUserId));
// return;
// }
final userAccountBox = Hive.localUserAccountBox;
if (!userAccountBox.containsKey(localUserId)) {
debugPrint("User $localUserId not yet registered.");
@@ -99,10 +135,18 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
final authenticated = await _localAuthService
.authenticateLocalUser("Authenticate to switch your account.");
if (!authenticated) {
debugPrint("User not authenticated.");
_debugPrintMessage(
"switchAccount",
"User could not be authenticated.",
);
emit(VerifyIdentityState(userId: localUserId));
return;
}
}
final currentlyLoggedInUser = globalSettings.loggedInUserId;
if (currentlyLoggedInUser != localUserId) {
await _notificationService.cancelUserNotifications(localUserId);
}
await withEncryptedBox<UserCredentials, void>(
HiveBoxes.localUserCredentials, (credentialsBox) async {
if (!credentialsBox.containsKey(localUserId)) {
@@ -131,9 +175,7 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
apiVersion,
);
emit(AuthenticatedState(
localUserId: localUserId,
));
emit(AuthenticatedState(localUserId: localUserId));
});
}
@@ -142,19 +184,33 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
required String serverUrl,
ClientCertificate? clientCertificate,
required bool enableBiometricAuthentication,
required String locale,
}) async {
assert(credentials.password != null && credentials.username != null);
final localUserId = "${credentials.username}@$serverUrl";
final sessionManager = SessionManager();
await _addUser(
localUserId,
serverUrl,
credentials,
clientCertificate,
sessionManager,
);
return localUserId;
final sessionManager = SessionManager([
LanguageHeaderInterceptor(locale),
]);
try {
await _addUser(
localUserId,
serverUrl,
credentials,
clientCertificate,
sessionManager,
// onPerformLogin: () async {
// emit(AuthenticatingState(AuthenticatingStage.authenticating));
// await Future.delayed(const Duration(milliseconds: 500));
// },
);
return localUserId;
} catch (error, stackTrace) {
print(error);
debugPrintStack(stackTrace: stackTrace);
rethrow;
}
}
Future<void> removeAccount(String userId) async {
@@ -170,28 +226,33 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
}
///
/// Performs a conditional hydration based on the local authentication success.
/// Restores the previous session if exists.
///
Future<void> restoreSessionState() async {
Future<void> restoreSession([String? userId]) async {
emit(const RestoringSessionState());
_debugPrintMessage(
"restoreSessionState",
"Trying to restore previous session...",
);
final globalSettings =
Hive.box<GlobalSettings>(HiveBoxes.globalSettings).getValue()!;
final localUserId = globalSettings.loggedInUserId;
if (localUserId == null) {
final restoreSessionForUser = userId ?? globalSettings.loggedInUserId;
// final localUserId = globalSettings.loggedInUserId;
if (restoreSessionForUser == null) {
_debugPrintMessage(
"restoreSessionState",
"There is nothing to restore.",
);
final otherAccountsExist = Hive.localUserAccountBox.isNotEmpty;
// If there is nothing to restore, we can quit here.
emit(const UnauthenticatedState());
emit(
UnauthenticatedState(redirectToAccountSelection: otherAccountsExist),
);
return;
}
final localUserAccountBox =
Hive.box<LocalUserAccount>(HiveBoxes.localUserAccount);
final localUserAccount = localUserAccountBox.get(localUserId)!;
final localUserAccount = localUserAccountBox.get(restoreSessionForUser)!;
_debugPrintMessage(
"restoreSessionState",
"Checking if biometric authentication is required...",
@@ -207,7 +268,7 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
final localAuthSuccess =
await _localAuthService.authenticateLocalUser(authenticationMesage);
if (!localAuthSuccess) {
emit(const RequiresLocalAuthenticationState());
emit(VerifyIdentityState(userId: restoreSessionForUser));
_debugPrintMessage(
"restoreSessionState",
"User could not be authenticated.",
@@ -231,7 +292,7 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
final authentication =
await withEncryptedBox<UserCredentials, UserCredentials>(
HiveBoxes.localUserCredentials, (box) {
return box.get(globalSettings.loggedInUserId!);
return box.get(restoreSessionForUser);
});
if (authentication == null) {
@@ -290,8 +351,9 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
"Skipping update of server user (server could not be reached).",
);
}
emit(AuthenticatedState(localUserId: localUserId));
globalSettings.loggedInUserId = restoreSessionForUser;
await globalSettings.save();
emit(AuthenticatedState(localUserId: restoreSessionForUser));
_debugPrintMessage(
"restoreSessionState",
@@ -300,7 +362,7 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
}
Future<void> logout([bool removeAccount = false]) async {
emit(const LogginOutState());
emit(const LoggingOutState());
_debugPrintMessage(
"logout",
"Trying to log out current user...",
@@ -308,13 +370,16 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
await _resetExternalState();
final globalSettings = Hive.globalSettingsBox.getValue()!;
final userId = globalSettings.loggedInUserId!;
await _notificationService.cancelUserNotifications(userId);
final otherAccountsExist = Hive.localUserAccountBox.length > 1;
emit(UnauthenticatedState(redirectToAccountSelection: otherAccountsExist));
if (removeAccount) {
this.removeAccount(userId);
await this.removeAccount(userId);
}
globalSettings.loggedInUserId = null;
await globalSettings.save();
emit(const UnauthenticatedState());
_debugPrintMessage(
"logout",
"User successfully logged out.",
@@ -322,16 +387,8 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
}
Future<void> _resetExternalState() async {
_debugPrintMessage(
"_resetExternalState",
"Resetting session manager and clearing storage...",
);
_sessionManager.resetSettings();
await HydratedBloc.storage.clear();
_debugPrintMessage(
"_resetExternalState",
"Session manager successfully reset and storage cleared.",
);
}
Future<int> _addUser(
@@ -339,8 +396,11 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
String serverUrl,
LoginFormCredentials credentials,
ClientCertificate? clientCert,
SessionManager sessionManager,
) async {
SessionManager sessionManager, {
_FutureVoidCallback? onPerformLogin,
_FutureVoidCallback? onPersistLocalUserData,
_FutureVoidCallback? onFetchUserInformation,
}) async {
assert(credentials.username != null && credentials.password != null);
_debugPrintMessage("_addUser", "Adding new user $localUserId...");
@@ -356,6 +416,8 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
"Trying to login user ${credentials.username} on $serverUrl...",
);
await onPerformLogin?.call();
final token = await authApi.login(
username: credentials.username!,
password: credentials.password!,
@@ -384,6 +446,7 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
);
throw InfoMessageException(code: ErrorCode.userAlreadyExists);
}
await onFetchUserInformation?.call();
final apiVersion = await _getApiVersion(sessionManager.client);
_debugPrintMessage(
"_addUser",
@@ -413,6 +476,7 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
"_addUser",
"Persisting local user account...",
);
await onPersistLocalUserData?.call();
// Create user account
await userAccountBox.put(
localUserId,
@@ -490,7 +554,7 @@ class AuthenticationCubit extends Cubit<AuthenticationState> {
"API version ($apiVersion) successfully retrieved.",
);
return apiVersion;
} on DioException catch (e) {
} on DioException catch (_) {
return defaultValue;
}
}

View File

@@ -7,34 +7,76 @@ sealed class AuthenticationState {
switch (this) { AuthenticatedState() => true, _ => false };
}
class UnauthenticatedState extends AuthenticationState {
const UnauthenticatedState();
class UnauthenticatedState extends AuthenticationState with EquatableMixin {
final bool redirectToAccountSelection;
const UnauthenticatedState({this.redirectToAccountSelection = false});
@override
List<Object?> get props => [redirectToAccountSelection];
}
class RequiresLocalAuthenticationState extends AuthenticationState {
const RequiresLocalAuthenticationState();
class RestoringSessionState extends AuthenticationState {
const RestoringSessionState();
}
class CheckingLoginState extends AuthenticationState {
const CheckingLoginState();
class VerifyIdentityState extends AuthenticationState {
final String userId;
const VerifyIdentityState({required this.userId});
}
class LogginOutState extends AuthenticationState {
const LogginOutState();
class AuthenticatingState extends AuthenticationState with EquatableMixin {
final AuthenticatingStage currentStage;
const AuthenticatingState(this.currentStage);
@override
List<Object?> get props => [currentStage];
}
class AuthenticatedState extends AuthenticationState {
class LoggingOutState extends AuthenticationState {
const LoggingOutState();
}
class AuthenticatedState extends AuthenticationState with EquatableMixin {
final String localUserId;
const AuthenticatedState({
required this.localUserId,
});
const AuthenticatedState({required this.localUserId});
@override
List<Object?> get props => [localUserId];
}
class SwitchingAccountsState extends AuthenticationState {
const SwitchingAccountsState();
}
class AuthenticationErrorState extends AuthenticationState {
const AuthenticationErrorState();
class AuthenticationErrorState extends AuthenticationState with EquatableMixin {
final ErrorCode? errorCode;
final String serverUrl;
final ClientCertificate? clientCertificate;
final String username;
final String password;
const AuthenticationErrorState({
this.errorCode,
required this.serverUrl,
this.clientCertificate,
required this.username,
required this.password,
});
@override
List<Object?> get props => [
errorCode,
serverUrl,
clientCertificate,
username,
password,
];
}
enum AuthenticatingStage {
authenticating,
persistingLocalUserData,
fetchingUserInformation,
}

View File

@@ -1,48 +0,0 @@
import 'package:equatable/equatable.dart';
class OldAuthenticationState with EquatableMixin {
final bool showBiometricAuthenticationScreen;
final bool isAuthenticated;
final String? username;
final String? fullName;
final String? localUserId;
final int? apiVersion;
const OldAuthenticationState({
this.isAuthenticated = false,
this.showBiometricAuthenticationScreen = false,
this.username,
this.fullName,
this.localUserId,
this.apiVersion,
});
OldAuthenticationState copyWith({
bool? isAuthenticated,
bool? showBiometricAuthenticationScreen,
String? username,
String? fullName,
String? localUserId,
int? apiVersion,
}) {
return OldAuthenticationState(
isAuthenticated: isAuthenticated ?? this.isAuthenticated,
showBiometricAuthenticationScreen: showBiometricAuthenticationScreen ??
this.showBiometricAuthenticationScreen,
username: username ?? this.username,
fullName: fullName ?? this.fullName,
localUserId: localUserId ?? this.localUserId,
apiVersion: apiVersion ?? this.apiVersion,
);
}
@override
List<Object?> get props => [
localUserId,
username,
fullName,
isAuthenticated,
showBiometricAuthenticationScreen,
apiVersion,
];
}

View File

@@ -12,5 +12,9 @@ class ClientCertificate {
@HiveField(1)
String? passphrase;
ClientCertificate({required this.bytes, this.passphrase});
ClientCertificate({
required this.bytes,
this.passphrase,
});
}

View File

@@ -7,9 +7,16 @@ class ClientCertificateFormModel {
final Uint8List bytes;
final String? passphrase;
ClientCertificateFormModel({required this.bytes, this.passphrase});
ClientCertificateFormModel({
required this.bytes,
this.passphrase,
});
ClientCertificateFormModel copyWith({Uint8List? bytes, String? passphrase}) {
ClientCertificateFormModel copyWith({
Uint8List? bytes,
String? passphrase,
String? filePath,
}) {
return ClientCertificateFormModel(
bytes: bytes ?? this.bytes,
passphrase: passphrase ?? this.passphrase,

View File

@@ -3,27 +3,21 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:hive_flutter/adapters.dart';
import 'package:paperless_api/paperless_api.dart';
import 'package:paperless_mobile/core/config/hive/hive_config.dart';
import 'package:paperless_mobile/core/database/tables/local_user_account.dart';
import 'package:paperless_mobile/core/exception/server_message_exception.dart';
import 'package:paperless_mobile/core/model/info_message_exception.dart';
import 'package:paperless_mobile/features/login/cubit/authentication_cubit.dart';
import 'package:paperless_mobile/core/service/connectivity_status_service.dart';
import 'package:paperless_mobile/extensions/flutter_extensions.dart';
import 'package:paperless_mobile/features/login/model/client_certificate.dart';
import 'package:paperless_mobile/features/login/model/client_certificate_form_model.dart';
import 'package:paperless_mobile/features/login/model/login_form_credentials.dart';
import 'package:paperless_mobile/features/login/model/reachability_status.dart';
import 'package:paperless_mobile/features/login/view/widgets/form_fields/client_certificate_form_field.dart';
import 'package:paperless_mobile/features/login/view/widgets/form_fields/server_address_form_field.dart';
import 'package:paperless_mobile/features/login/view/widgets/form_fields/user_credentials_form_field.dart';
import 'package:paperless_mobile/features/login/view/widgets/login_pages/server_connection_page.dart';
import 'package:paperless_mobile/features/users/view/widgets/user_account_list_tile.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
import 'package:paperless_mobile/helpers/message_helpers.dart';
import 'widgets/login_pages/server_login_page.dart';
import 'widgets/never_scrollable_scroll_behavior.dart';
class AddAccountPage extends StatefulWidget {
final FutureOr<void> Function(
BuildContext context,
@@ -33,17 +27,27 @@ class AddAccountPage extends StatefulWidget {
ClientCertificate? clientCertificate,
) onSubmit;
final String submitText;
final String titleString;
final String? initialServerUrl;
final String? initialUsername;
final String? initialPassword;
final ClientCertificate? initialClientCertificate;
final String submitText;
final String titleText;
final bool showLocalAccounts;
final Widget? bottomLeftButton;
const AddAccountPage({
Key? key,
required this.onSubmit,
required this.submitText,
required this.titleString,
required this.titleText,
this.showLocalAccounts = false,
this.initialServerUrl,
this.initialUsername,
this.initialPassword,
this.initialClientCertificate,
this.bottomLeftButton,
}) : super(key: key);
@override
@@ -52,86 +56,170 @@ class AddAccountPage extends StatefulWidget {
class _AddAccountPageState extends State<AddAccountPage> {
final _formKey = GlobalKey<FormBuilderState>();
bool _isCheckingConnection = false;
ReachabilityStatus _reachabilityStatus = ReachabilityStatus.unknown;
final PageController _pageController = PageController();
bool _isFormSubmitted = false;
@override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable:
Hive.box<LocalUserAccount>(HiveBoxes.localUserAccount).listenable(),
builder: (context, localAccounts, child) {
return Scaffold(
resizeToAvoidBottomInset: false,
body: FormBuilder(
key: _formKey,
child: PageView(
controller: _pageController,
scrollBehavior: NeverScrollableScrollBehavior(),
children: [
if (widget.showLocalAccounts && localAccounts.isNotEmpty)
Scaffold(
appBar: AppBar(
title: Text(S.of(context)!.logInToExistingAccount),
),
bottomNavigationBar: BottomAppBar(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FilledButton(
child: Text(S.of(context)!.goToLogin),
onPressed: () {
_pageController.nextPage(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
},
),
],
),
),
body: ListView.builder(
itemBuilder: (context, index) {
final account = localAccounts.values.elementAt(index);
return Card(
child: UserAccountListTile(
account: account,
onTap: () {
context
.read<AuthenticationCubit>()
.switchAccount(account.id);
},
),
);
},
itemCount: localAccounts.length,
),
),
ServerConnectionPage(
titleText: widget.titleString,
formBuilderKey: _formKey,
onContinue: () {
_pageController.nextPage(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
},
),
ServerLoginPage(
formBuilderKey: _formKey,
submitText: widget.submitText,
onSubmit: _login,
),
],
return Scaffold(
appBar: AppBar(
title: Text(widget.titleText),
),
bottomNavigationBar: BottomAppBar(
child: Row(
mainAxisAlignment: widget.bottomLeftButton != null
? MainAxisAlignment.spaceBetween
: MainAxisAlignment.end,
children: [
if (widget.bottomLeftButton != null) widget.bottomLeftButton!,
FilledButton(
child: Text(S.of(context)!.loginPageSignInTitle),
onPressed: _reachabilityStatus == ReachabilityStatus.reachable &&
!_isFormSubmitted
? _onSubmit
: null,
),
),
);
},
],
),
),
resizeToAvoidBottomInset: true,
body: FormBuilder(
key: _formKey,
child: ListView(
children: [
ServerAddressFormField(
initialValue: widget.initialServerUrl,
onSubmit: (address) {
_updateReachability(address);
},
).padded(),
ClientCertificateFormField(
initialBytes: widget.initialClientCertificate?.bytes,
initialPassphrase: widget.initialClientCertificate?.passphrase,
onChanged: (_) => _updateReachability(),
).padded(),
_buildStatusIndicator(),
if (_reachabilityStatus == ReachabilityStatus.reachable) ...[
UserCredentialsFormField(
formKey: _formKey,
initialUsername: widget.initialUsername,
initialPassword: widget.initialPassword,
onFieldsSubmitted: _onSubmit,
),
Text(
S.of(context)!.loginRequiredPermissionsHint,
style: Theme.of(context).textTheme.bodySmall?.apply(
color: Theme.of(context)
.colorScheme
.onBackground
.withOpacity(0.6),
),
).padded(16),
]
],
),
),
);
}
Future<void> _login() async {
Future<void> _updateReachability([String? address]) async {
setState(() {
_isCheckingConnection = true;
});
final certForm =
_formKey.currentState?.getRawValue<ClientCertificateFormModel>(
ClientCertificateFormField.fkClientCertificate,
);
final status = await context
.read<ConnectivityStatusService>()
.isPaperlessServerReachable(
address ??
_formKey.currentState!
.getRawValue(ServerAddressFormField.fkServerAddress),
certForm != null
? ClientCertificate(
bytes: certForm.bytes,
passphrase: certForm.passphrase,
)
: null,
);
setState(() {
_isCheckingConnection = false;
_reachabilityStatus = status;
});
}
Widget _buildStatusIndicator() {
if (_isCheckingConnection) {
return const ListTile();
}
Widget _buildIconText(
IconData icon,
String text, [
Color? color,
]) {
return ListTile(
title: Text(
text,
style: Theme.of(context).textTheme.bodySmall?.copyWith(color: color),
),
leading: Icon(
icon,
color: color,
),
);
}
Color errorColor = Theme.of(context).colorScheme.error;
switch (_reachabilityStatus) {
case ReachabilityStatus.unknown:
return Container();
case ReachabilityStatus.reachable:
return _buildIconText(
Icons.done,
S.of(context)!.connectionSuccessfulylEstablished,
Colors.green,
);
case ReachabilityStatus.notReachable:
return _buildIconText(
Icons.close,
S.of(context)!.couldNotEstablishConnectionToTheServer,
errorColor,
);
case ReachabilityStatus.unknownHost:
return _buildIconText(
Icons.close,
S.of(context)!.hostCouldNotBeResolved,
errorColor,
);
case ReachabilityStatus.missingClientCertificate:
return _buildIconText(
Icons.close,
S.of(context)!.loginPageReachabilityMissingClientCertificateText,
errorColor,
);
case ReachabilityStatus.invalidClientCertificateConfiguration:
return _buildIconText(
Icons.close,
S.of(context)!.incorrectOrMissingCertificatePassphrase,
errorColor,
);
case ReachabilityStatus.connectionTimeout:
return _buildIconText(
Icons.close,
S.of(context)!.connectionTimedOut,
errorColor,
);
}
}
Future<void> _onSubmit() async {
FocusScope.of(context).unfocus();
setState(() {
_isFormSubmitted = true;
});
if (_formKey.currentState?.saveAndValidate() ?? false) {
final form = _formKey.currentState!.value;
ClientCertificate? clientCert;
@@ -162,6 +250,10 @@ class _AddAccountPageState extends State<AddAccountPage> {
showInfoMessage(context, error);
} catch (error) {
showGenericError(context, error);
} finally {
setState(() {
_isFormSubmitted = false;
});
}
}
}

View File

@@ -1,9 +1,9 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:hive_flutter/adapters.dart';
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/global_settings.dart';
import 'package:paperless_mobile/core/model/info_message_exception.dart';
import 'package:paperless_mobile/features/app_intro/application_intro_slideshow.dart';
@@ -13,18 +13,41 @@ import 'package:paperless_mobile/features/login/model/login_form_credentials.dar
import 'package:paperless_mobile/features/login/view/add_account_page.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/documents_route.dart';
import 'package:paperless_mobile/routes/typed/top_level/login_route.dart';
class LoginPage extends StatelessWidget {
const LoginPage({super.key});
final String? initialServerUrl;
final String? initialUsername;
final String? initialPassword;
final ClientCertificate? initialClientCertificate;
const LoginPage({
super.key,
this.initialServerUrl,
this.initialUsername,
this.initialPassword,
this.initialClientCertificate,
});
@override
Widget build(BuildContext context) {
return AddAccountPage(
titleString: S.of(context)!.connectToPaperless,
titleText: S.of(context)!.connectToPaperless,
submitText: S.of(context)!.signIn,
onSubmit: _onLogin,
showLocalAccounts: true,
initialServerUrl: initialServerUrl,
initialUsername: initialUsername,
initialPassword: initialPassword,
initialClientCertificate: initialClientCertificate,
bottomLeftButton: Hive.localUserAccountBox.isNotEmpty
? TextButton(
child: Text(S.of(context)!.logInToExistingAccount),
onPressed: () {
const LoginToExistingAccountRoute().go(context);
},
)
: null,
);
}

View File

@@ -0,0 +1,66 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hive_flutter/adapters.dart';
import 'package:paperless_mobile/core/config/hive/hive_extensions.dart';
import 'package:paperless_mobile/features/login/cubit/authentication_cubit.dart';
import 'package:paperless_mobile/features/users/view/widgets/user_account_list_tile.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
import 'package:paperless_mobile/routes/typed/top_level/login_route.dart';
class LoginToExistingAccountPage extends StatelessWidget {
const LoginToExistingAccountPage({super.key});
@override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: Hive.localUserAccountBox.listenable(),
builder: (context, value, _) {
final localAccounts = value.values;
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text(S.of(context)!.logInToExistingAccount),
),
bottomNavigationBar: BottomAppBar(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
child: Text(S.of(context)!.addAnotherAccount),
onPressed: () {
const LoginRoute().go(context);
},
),
],
),
),
body: ListView.builder(
itemBuilder: (context, index) {
final account = localAccounts.elementAt(index);
return Card(
child: UserAccountListTile(
account: account,
onTap: () {
context
.read<AuthenticationCubit>()
.switchAccount(account.id);
},
trailing: IconButton(
tooltip: S.of(context)!.remove,
icon: Icon(Icons.close),
onPressed: () {
context
.read<AuthenticationCubit>()
.removeAccount(account.id);
},
),
),
);
},
itemCount: localAccounts.length,
),
);
},
);
}
}

View File

@@ -0,0 +1,64 @@
import 'package:flutter/material.dart';
import 'package:paperless_mobile/extensions/flutter_extensions.dart';
import 'package:paperless_mobile/features/login/cubit/authentication_cubit.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
import 'package:paperless_mobile/routes/typed/top_level/login_route.dart';
import 'package:provider/provider.dart';
class VerifyIdentityPage extends StatelessWidget {
final String userId;
const VerifyIdentityPage({super.key, required this.userId});
@override
Widget build(BuildContext context) {
return Material(
child: Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: Theme.of(context).colorScheme.background,
title: Text(S.of(context)!.verifyYourIdentity),
),
bottomNavigationBar: BottomAppBar(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TextButton(
onPressed: () {
const LoginToExistingAccountRoute().go(context);
},
child: Text(S.of(context)!.goToLogin),
),
FilledButton(
onPressed: () =>
context.read<AuthenticationCubit>().restoreSession(userId),
child: Text(S.of(context)!.verifyIdentity),
),
],
),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(
S.of(context)!.useTheConfiguredBiometricFactorToAuthenticate,
textAlign: TextAlign.center,
).paddedSymmetrically(horizontal: 16),
const Icon(
Icons.fingerprint,
size: 96,
),
// Wrap(
// alignment: WrapAlignment.spaceBetween,
// runAlignment: WrapAlignment.spaceBetween,
// runSpacing: 8,
// spacing: 8,
// children: [
// ],
// ).padded(16),
],
),
),
);
}
}

View File

@@ -1,4 +1,5 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
@@ -12,11 +13,16 @@ import 'obscured_input_text_form_field.dart';
class ClientCertificateFormField extends StatefulWidget {
static const fkClientCertificate = 'clientCertificate';
final String? initialPassphrase;
final Uint8List? initialBytes;
final void Function(ClientCertificateFormModel? cert) onChanged;
const ClientCertificateFormField({
Key? key,
super.key,
required this.onChanged,
}) : super(key: key);
this.initialPassphrase,
this.initialBytes,
});
@override
State<ClientCertificateFormField> createState() =>
@@ -31,7 +37,12 @@ class _ClientCertificateFormFieldState
return FormBuilderField<ClientCertificateFormModel?>(
key: const ValueKey('login-client-cert'),
onChanged: widget.onChanged,
initialValue: null,
initialValue: widget.initialBytes != null
? ClientCertificateFormModel(
bytes: widget.initialBytes!,
passphrase: widget.initialPassphrase,
)
: null,
validator: (value) {
if (value == null) {
return null;
@@ -108,8 +119,7 @@ class _ClientCertificateFormFieldState
),
label: S.of(context)!.passphrase,
).padded(),
] else
...[]
]
],
),
),
@@ -122,20 +132,23 @@ class _ClientCertificateFormFieldState
}
Future<void> _onSelectFile(
FormFieldState<ClientCertificateFormModel?> field) async {
FilePickerResult? result = await FilePicker.platform.pickFiles(
FormFieldState<ClientCertificateFormModel?> field,
) async {
final result = await FilePicker.platform.pickFiles(
allowMultiple: false,
);
if (result != null && result.files.single.path != null) {
File file = File(result.files.single.path!);
setState(() {
_selectedFile = file;
});
final changedValue =
field.value?.copyWith(bytes: file.readAsBytesSync()) ??
ClientCertificateFormModel(bytes: file.readAsBytesSync());
field.didChange(changedValue);
if (result == null || result.files.single.path == null) {
return;
}
File file = File(result.files.single.path!);
setState(() {
_selectedFile = file;
});
final bytes = await file.readAsBytes();
final changedValue = field.value?.copyWith(bytes: bytes) ??
ClientCertificateFormModel(bytes: bytes);
field.didChange(changedValue);
}
Widget _buildSelectedFileText(

View File

@@ -8,11 +8,12 @@ import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
class ServerAddressFormField extends StatefulWidget {
static const String fkServerAddress = "serverAddress";
final String? initialValue;
final void Function(String? address) onSubmit;
const ServerAddressFormField({
Key? key,
required this.onSubmit,
this.initialValue,
}) : super(key: key);
@override
@@ -38,6 +39,7 @@ class _ServerAddressFormFieldState extends State<ServerAddressFormField> {
@override
Widget build(BuildContext context) {
return FormBuilderField<String>(
initialValue: widget.initialValue,
name: ServerAddressFormField.fkServerAddress,
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (value) {
@@ -90,7 +92,7 @@ class _ServerAddressFormFieldState extends State<ServerAddressFormField> {
)
: null,
),
autofocus: true,
autofocus: false,
onSubmitted: (_) {
onFieldSubmitted();
_formatInput();

View File

@@ -1,19 +1,27 @@
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:hive_flutter/adapters.dart';
import 'package:paperless_mobile/core/config/hive/hive_extensions.dart';
import 'package:paperless_mobile/extensions/flutter_extensions.dart';
import 'package:paperless_mobile/features/login/model/login_form_credentials.dart';
import 'package:paperless_mobile/features/login/view/widgets/form_fields/obscured_input_text_form_field.dart';
import 'package:paperless_mobile/features/login/view/widgets/form_fields/server_address_form_field.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
class UserCredentialsFormField extends StatefulWidget {
static const fkCredentials = 'credentials';
final void Function() onFieldsSubmitted;
final String? initialUsername;
final String? initialPassword;
final GlobalKey<FormBuilderState> formKey;
const UserCredentialsFormField({
Key? key,
required this.onFieldsSubmitted,
this.initialUsername,
this.initialPassword,
required this.formKey,
}) : super(key: key);
@override
@@ -28,6 +36,10 @@ class _UserCredentialsFormFieldState extends State<UserCredentialsFormField> {
@override
Widget build(BuildContext context) {
return FormBuilderField<LoginFormCredentials?>(
initialValue: LoginFormCredentials(
password: widget.initialPassword,
username: widget.initialUsername,
),
name: UserCredentialsFormField.fkCredentials,
builder: (field) => AutofillGroup(
child: Column(
@@ -50,6 +62,17 @@ class _UserCredentialsFormFieldState extends State<UserCredentialsFormField> {
if (value?.trim().isEmpty ?? true) {
return S.of(context)!.usernameMustNotBeEmpty;
}
final serverAddress = widget.formKey.currentState!
.getRawValue<String>(
ServerAddressFormField.fkServerAddress);
if (serverAddress != null) {
final userExists = Hive.localUserAccountBox.values
.map((e) => e.id)
.contains('$value@$serverAddress');
if (userExists) {
return S.of(context)!.userAlreadyExists;
}
}
return null;
},
autofillHints: const [AutofillHints.username],

View File

@@ -1,170 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:paperless_mobile/core/service/connectivity_status_service.dart';
import 'package:paperless_mobile/extensions/flutter_extensions.dart';
import 'package:paperless_mobile/features/login/model/client_certificate.dart';
import 'package:paperless_mobile/features/login/model/client_certificate_form_model.dart';
import 'package:paperless_mobile/features/login/model/reachability_status.dart';
import 'package:paperless_mobile/features/login/view/widgets/form_fields/client_certificate_form_field.dart';
import 'package:paperless_mobile/features/login/view/widgets/form_fields/server_address_form_field.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
import 'package:provider/provider.dart';
class ServerConnectionPage extends StatefulWidget {
final GlobalKey<FormBuilderState> formBuilderKey;
final VoidCallback onContinue;
final String titleText;
const ServerConnectionPage({
super.key,
required this.formBuilderKey,
required this.onContinue,
required this.titleText,
});
@override
State<ServerConnectionPage> createState() => _ServerConnectionPageState();
}
class _ServerConnectionPageState extends State<ServerConnectionPage> {
bool _isCheckingConnection = false;
ReachabilityStatus _reachabilityStatus = ReachabilityStatus.unknown;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
toolbarHeight: kToolbarHeight - 4,
title: Text(widget.titleText),
bottom: PreferredSize(
child: _isCheckingConnection
? const LinearProgressIndicator()
: const SizedBox(height: 4.0),
preferredSize: const Size.fromHeight(4.0),
),
),
resizeToAvoidBottomInset: true,
body: SingleChildScrollView(
child: Column(
children: [
ServerAddressFormField(
onSubmit: (address) {
_updateReachability(address);
},
).padded(),
ClientCertificateFormField(
onChanged: (_) => _updateReachability(),
).padded(),
_buildStatusIndicator(),
],
).padded(),
),
bottomNavigationBar: BottomAppBar(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TextButton(
child: Text(S.of(context)!.testConnection),
onPressed: _updateReachability,
),
FilledButton(
child: Text(S.of(context)!.continueLabel),
onPressed: _reachabilityStatus == ReachabilityStatus.reachable
? widget.onContinue
: null,
),
],
),
),
);
}
Future<void> _updateReachability([String? address]) async {
setState(() {
_isCheckingConnection = true;
});
final certForm = widget.formBuilderKey.currentState
?.getRawValue(ClientCertificateFormField.fkClientCertificate)
as ClientCertificateFormModel?;
final status = await context
.read<ConnectivityStatusService>()
.isPaperlessServerReachable(
address ??
widget.formBuilderKey.currentState!
.getRawValue(ServerAddressFormField.fkServerAddress),
certForm != null
? ClientCertificate(
bytes: certForm.bytes, passphrase: certForm.passphrase)
: null,
);
setState(() {
_isCheckingConnection = false;
_reachabilityStatus = status;
});
}
Widget _buildStatusIndicator() {
if (_isCheckingConnection) {
return const ListTile();
}
Color errorColor = Theme.of(context).colorScheme.error;
switch (_reachabilityStatus) {
case ReachabilityStatus.unknown:
return Container();
case ReachabilityStatus.reachable:
return _buildIconText(
Icons.done,
S.of(context)!.connectionSuccessfulylEstablished,
Colors.green,
);
case ReachabilityStatus.notReachable:
return _buildIconText(
Icons.close,
S.of(context)!.couldNotEstablishConnectionToTheServer,
errorColor,
);
case ReachabilityStatus.unknownHost:
return _buildIconText(
Icons.close,
S.of(context)!.hostCouldNotBeResolved,
errorColor,
);
case ReachabilityStatus.missingClientCertificate:
return _buildIconText(
Icons.close,
S.of(context)!.loginPageReachabilityMissingClientCertificateText,
errorColor,
);
case ReachabilityStatus.invalidClientCertificateConfiguration:
return _buildIconText(
Icons.close,
S.of(context)!.incorrectOrMissingCertificatePassphrase,
errorColor,
);
case ReachabilityStatus.connectionTimeout:
return _buildIconText(
Icons.close,
S.of(context)!.connectionTimedOut,
errorColor,
);
}
}
Widget _buildIconText(
IconData icon,
String text, [
Color? color,
]) {
return ListTile(
title: Text(
text,
style: Theme.of(context).textTheme.bodySmall?.copyWith(color: color),
),
leading: Icon(
icon,
color: color,
),
);
}
}

View File

@@ -1,85 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:paperless_mobile/extensions/flutter_extensions.dart';
import 'package:paperless_mobile/features/login/view/widgets/form_fields/server_address_form_field.dart';
import 'package:paperless_mobile/features/login/view/widgets/form_fields/user_credentials_form_field.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
class ServerLoginPage extends StatefulWidget {
final String submitText;
final Future<void> Function() onSubmit;
final GlobalKey<FormBuilderState> formBuilderKey;
const ServerLoginPage({
super.key,
required this.onSubmit,
required this.formBuilderKey,
required this.submitText,
});
@override
State<ServerLoginPage> createState() => _ServerLoginPageState();
}
class _ServerLoginPageState extends State<ServerLoginPage> {
bool _isLoginLoading = false;
@override
Widget build(BuildContext context) {
final serverAddress = (widget.formBuilderKey.currentState
?.getRawValue(ServerAddressFormField.fkServerAddress)
as String?)
?.replaceAll(RegExp(r'https?://'), '') ??
'';
return Scaffold(
appBar: AppBar(
title: Text(S.of(context)!.loginPageSignInTitle),
bottom: _isLoginLoading
? const PreferredSize(
preferredSize: Size.fromHeight(4.0),
child: LinearProgressIndicator(),
)
: null,
),
body: ListView(
children: [
Text(
S.of(context)!.signInToServer(serverAddress) + ":",
style: Theme.of(context).textTheme.labelLarge,
).padded(16),
UserCredentialsFormField(
onFieldsSubmitted: widget.onSubmit,
),
Text(
S.of(context)!.loginRequiredPermissionsHint,
style: Theme.of(context).textTheme.bodySmall?.apply(
color: Theme.of(context)
.colorScheme
.onBackground
.withOpacity(0.6),
),
).padded(16),
],
),
bottomNavigationBar: BottomAppBar(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FilledButton(
onPressed: !_isLoginLoading
? () async {
setState(() => _isLoginLoading = true);
try {
await widget.onSubmit();
} finally {
setState(() => _isLoginLoading = false);
}
}
: null,
child: Text(S.of(context)!.signIn),
)
],
),
),
);
}
}

View File

@@ -0,0 +1,34 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:paperless_mobile/extensions/flutter_extensions.dart';
import 'package:paperless_mobile/theme.dart';
class LoginTransitionPage extends StatelessWidget {
final String text;
const LoginTransitionPage({super.key, required this.text});
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => false,
child: AnnotatedRegion<SystemUiOverlayStyle>(
value: buildOverlayStyle(
Theme.of(context),
systemNavigationBarColor: Theme.of(context).colorScheme.background,
),
child: Scaffold(
body: Stack(
alignment: Alignment.center,
children: [
const CircularProgressIndicator(),
Align(
alignment: Alignment.bottomCenter,
child: Text(text).paddedOnly(bottom: 24),
),
],
).padded(16),
),
),
);
}
}

View File

@@ -1,8 +0,0 @@
import 'package:flutter/widgets.dart';
class NeverScrollableScrollBehavior extends ScrollBehavior {
@override
ScrollPhysics getScrollPhysics(BuildContext context) {
return const NeverScrollableScrollPhysics();
}
}

View File

@@ -54,6 +54,7 @@ class LocalNotificationService {
required bool finished,
required String locale,
required String userId,
double? progress,
}) async {
final tr = await S.delegate.load(Locale(locale));
@@ -68,8 +69,10 @@ class LocalNotificationService {
android: AndroidNotificationDetails(
NotificationChannel.documentDownload.id + "_${document.id}",
NotificationChannel.documentDownload.name,
progress: ((progress ?? 0) * 100).toInt(),
maxProgress: 100,
indeterminate: progress == null && !finished,
ongoing: !finished,
indeterminate: true,
importance: Importance.max,
priority: Priority.high,
showProgress: !finished,

View File

@@ -3,7 +3,6 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:paperless_api/paperless_api.dart';
import 'package:paperless_mobile/core/notifier/document_changed_notifier.dart';
import 'package:paperless_mobile/core/service/connectivity_status_service.dart';
import 'package:rxdart/streams.dart';
import 'paged_documents_state.dart';
@@ -51,6 +50,7 @@ mixin DocumentPagingBlocMixin<State extends DocumentPagingState>
/// Use [loadMore] to load more data.
Future<void> updateFilter({
final DocumentFilter filter = const DocumentFilter(),
bool emitLoading = true,
}) async {
final hasConnection =
await connectivityStatusService.isConnectedToInternet();
@@ -60,7 +60,9 @@ mixin DocumentPagingBlocMixin<State extends DocumentPagingState>
.expand((page) => page.results)
.where((doc) => filter.matches(doc))
.toList();
emit(state.copyWithPaged(isLoading: true));
if (emitLoading) {
emit(state.copyWithPaged(isLoading: true));
}
emit(
state.copyWithPaged(
@@ -79,7 +81,9 @@ mixin DocumentPagingBlocMixin<State extends DocumentPagingState>
return;
}
try {
emit(state.copyWithPaged(isLoading: true));
if (emitLoading) {
emit(state.copyWithPaged(isLoading: true));
}
final result = await api.findAll(filter.copyWith(page: 1));
emit(
@@ -146,7 +150,7 @@ mixin DocumentPagingBlocMixin<State extends DocumentPagingState>
/// Deletes a document and removes it from the currently loaded state.
///
Future<void> delete(DocumentModel document) async {
emit(state.copyWithPaged(isLoading: true));
// emit(state.copyWithPaged(isLoading: true));
try {
await api.delete(document);
notifier.notifyDeleted(document);
@@ -213,6 +217,7 @@ mixin DocumentPagingBlocMixin<State extends DocumentPagingState>
}
}
@override
Future<void> close() {
notifier.removeListener(this);

View File

@@ -1,62 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:paperless_mobile/core/bloc/connectivity_cubit.dart';
import 'package:paperless_mobile/core/navigation/push_routes.dart';
import 'package:paperless_mobile/core/widgets/hint_card.dart';
import 'package:paperless_mobile/features/saved_view/cubit/saved_view_cubit.dart';
import 'package:paperless_mobile/features/saved_view/view/saved_view_loading_sliver_list.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
class SavedViewList extends StatelessWidget {
const SavedViewList({super.key});
@override
Widget build(BuildContext context) {
return BlocBuilder<ConnectivityCubit, ConnectivityState>(
builder: (context, connectivity) {
return BlocBuilder<SavedViewCubit, SavedViewState>(
builder: (context, state) {
return state.when(
initial: () => const SavedViewLoadingSliverList(),
loading: () => const SavedViewLoadingSliverList(),
loaded: (savedViews) {
if (savedViews.isEmpty) {
return SliverToBoxAdapter(
child: HintCard(
hintText: S
.of(context)!
.createViewsToQuicklyFilterYourDocuments,
),
);
}
return SliverList.builder(
itemBuilder: (context, index) {
final view = savedViews.values.elementAt(index);
return ListTile(
enabled: connectivity.isConnected,
title: Text(view.name),
subtitle: Text(
S.of(context)!.nFiltersSet(view.filterRules.length),
),
onTap: () {
pushSavedViewDetailsRoute(context, savedView: view);
},
);
},
itemCount: savedViews.length,
);
},
error: () => const SliverToBoxAdapter(
child: Center(
child: Text(
"An error occurred while trying to load the saved views.",
),
),
),
);
},
);
},
);
}
}

View File

@@ -1,32 +0,0 @@
import 'package:flutter/material.dart';
import 'package:paperless_mobile/core/widgets/shimmer_placeholder.dart';
class SavedViewLoadingSliverList extends StatelessWidget {
const SavedViewLoadingSliverList({super.key});
@override
Widget build(BuildContext context) {
return SliverList.builder(
itemBuilder: (context, index) => ShimmerPlaceholder(
child: ListTile(
title: Align(
alignment: Alignment.centerLeft,
child: Container(
width: 300,
height: 14,
color: Colors.white,
),
),
subtitle: Align(
alignment: Alignment.centerLeft,
child: Container(
width: 150,
height: 12,
color: Colors.white,
),
),
),
),
);
}
}

View File

@@ -1,102 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:paperless_api/paperless_api.dart';
import 'package:paperless_mobile/core/bloc/connectivity_cubit.dart';
import 'package:paperless_mobile/core/navigation/push_routes.dart';
import 'package:paperless_mobile/features/documents/view/widgets/adaptive_documents_view.dart';
import 'package:paperless_mobile/features/documents/view/widgets/documents_empty_state.dart';
import 'package:paperless_mobile/features/documents/view/widgets/selection/confirm_delete_saved_view_dialog.dart';
import 'package:paperless_mobile/features/documents/view/widgets/selection/view_type_selection_widget.dart';
import 'package:paperless_mobile/features/paged_document_view/view/document_paging_view_mixin.dart';
import 'package:paperless_mobile/features/saved_view_details/cubit/saved_view_details_cubit.dart';
import 'package:paperless_mobile/routes/typed/branches/documents_route.dart';
class SavedViewDetailsPage extends StatefulWidget {
final Future<void> Function(SavedView savedView) onDelete;
const SavedViewDetailsPage({
super.key,
required this.onDelete,
});
@override
State<SavedViewDetailsPage> createState() => _SavedViewDetailsPageState();
}
class _SavedViewDetailsPageState extends State<SavedViewDetailsPage>
with DocumentPagingViewMixin<SavedViewDetailsPage, SavedViewDetailsCubit> {
@override
final pagingScrollController = ScrollController();
@override
Widget build(BuildContext context) {
final cubit = context.watch<SavedViewDetailsCubit>();
return Scaffold(
appBar: AppBar(
title: Text(cubit.savedView.name),
actions: [
IconButton(
icon: const Icon(Icons.delete),
onPressed: () async {
final shouldDelete = await showDialog<bool>(
context: context,
builder: (context) => ConfirmDeleteSavedViewDialog(
view: cubit.savedView,
),
) ??
false;
if (shouldDelete) {
await widget.onDelete(cubit.savedView);
context.pop(context);
}
},
),
BlocBuilder<SavedViewDetailsCubit, SavedViewDetailsState>(
builder: (context, state) {
return ViewTypeSelectionWidget(
viewType: state.viewType,
onChanged: cubit.setViewType,
);
},
),
],
),
body: BlocBuilder<SavedViewDetailsCubit, SavedViewDetailsState>(
builder: (context, state) {
if (state.hasLoaded && state.documents.isEmpty) {
return DocumentsEmptyState(state: state);
}
return BlocBuilder<ConnectivityCubit, ConnectivityState>(
builder: (context, connectivity) {
return CustomScrollView(
controller: pagingScrollController,
slivers: [
SliverAdaptiveDocumentsView(
documents: state.documents,
hasInternetConnection: connectivity.isConnected,
isLabelClickable: false,
isLoading: state.isLoading,
hasLoaded: state.hasLoaded,
onTap: (document) {
DocumentDetailsRoute(
$extra: document,
isLabelClickable: false,
).push(context);
},
viewType: state.viewType,
),
if (state.hasLoaded && state.isLoading)
const SliverToBoxAdapter(
child: Center(
child: CircularProgressIndicator(),
),
)
],
);
},
);
},
),
);
}
}

View File

@@ -1,5 +1,3 @@
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:paperless_api/paperless_api.dart';

View File

@@ -1,16 +1,13 @@
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:hive_flutter/adapters.dart';
import 'package:paperless_mobile/core/config/hive/hive_config.dart';
import 'package:paperless_mobile/core/database/tables/local_user_account.dart';
import 'package:paperless_mobile/features/home/view/model/api_version.dart';
import 'package:paperless_mobile/core/config/hive/hive_extensions.dart';
import 'package:paperless_mobile/features/login/cubit/authentication_cubit.dart';
import 'package:paperless_mobile/features/login/model/login_form_credentials.dart';
import 'package:paperless_mobile/features/login/view/add_account_page.dart';
import 'package:paperless_mobile/features/settings/view/dialogs/switch_account_dialog.dart';
import 'package:paperless_mobile/features/settings/view/widgets/global_settings_builder.dart';
import 'package:paperless_mobile/features/users/view/widgets/user_account_list_tile.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
import 'package:paperless_mobile/routes/typed/top_level/add_account_route.dart';
import 'package:provider/provider.dart';
class ManageAccountsPage extends StatelessWidget {
@@ -20,16 +17,15 @@ class ManageAccountsPage extends StatelessWidget {
Widget build(BuildContext context) {
return GlobalSettingsBuilder(
builder: (context, globalSettings) {
// This is one of the few places where the currentLoggedInUser can be null
// (exactly after loggin out as the current user to be precise).
if (globalSettings.loggedInUserId == null) {
return const SizedBox.shrink();
}
// // This is one of the few places where the currentLoggedInUser can be null
// // (exactly after loggin out as the current user to be precise).
return ValueListenableBuilder(
valueListenable:
Hive.box<LocalUserAccount>(HiveBoxes.localUserAccount)
.listenable(),
valueListenable: Hive.localUserAccountBox.listenable(),
builder: (context, box, _) {
if (globalSettings.loggedInUserId == null) {
return const SizedBox.shrink();
}
final userIds = box.keys.toList().cast<String>();
final otherAccounts = userIds
.whereNot((element) => element == globalSettings.loggedInUserId)
@@ -70,6 +66,7 @@ class ManageAccountsPage extends StatelessWidget {
],
onSelected: (value) async {
if (value == 0) {
Navigator.of(context).pop();
await context
.read<AuthenticationCubit>()
.logout(true);
@@ -133,11 +130,12 @@ class ManageAccountsPage extends StatelessWidget {
_onAddAccount(context, globalSettings.loggedInUserId!);
},
),
if (context.watch<LocalUserAccount>().hasMultiUserSupport)
ListTile(
leading: const Icon(Icons.admin_panel_settings),
title: Text(S.of(context)!.managePermissions),
),
//TODO: Implement permission/user settings at some point...
// if (context.watch<LocalUserAccount>().hasMultiUserSupport)
// ListTile(
// leading: const Icon(Icons.admin_panel_settings),
// title: Text(S.of(context)!.managePermissions),
// ),
],
);
},
@@ -147,43 +145,43 @@ class ManageAccountsPage extends StatelessWidget {
}
Future<void> _onAddAccount(BuildContext context, String currentUser) async {
final userId = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AddAccountPage(
titleString: S.of(context)!.addAccount,
onSubmit: (context, username, password, serverUrl,
clientCertificate) async {
final userId = await context.read<AuthenticationCubit>().addAccount(
credentials: LoginFormCredentials(
username: username,
password: password,
),
clientCertificate: clientCertificate,
serverUrl: serverUrl,
//TODO: Ask user whether to enable biometric authentication
enableBiometricAuthentication: false,
);
Navigator.of(context).pop<String?>(userId);
},
submitText: S.of(context)!.addAccount,
),
),
);
if (userId != null) {
final shoudSwitch = await showDialog<bool>(
context: context,
builder: (context) => const SwitchAccountDialog(),
) ??
false;
if (shoudSwitch) {
_onSwitchAccount(context, currentUser, userId);
}
}
Navigator.of(context).pop();
AddAccountRoute().push<String>(context);
// final userId = await Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => AddAccountPage(
// titleText: S.of(context)!.addAccount,
// onSubmit: (context, username, password, serverUrl,
// clientCertificate) async {
// try {
// final userId =
// await context.read<AuthenticationCubit>().addAccount(
// credentials: LoginFormCredentials(
// username: username,
// password: password,
// ),
// clientCertificate: clientCertificate,
// serverUrl: serverUrl,
// //TODO: Ask user whether to enable biometric authentication
// enableBiometricAuthentication: false,
// );
// Navigator.of(context).pop<String?>(userId);
// } on PaperlessFormValidationException catch (error) {}
// },
// submitText: S.of(context)!.addAccount,
// ),
// ),
// );
}
void _onSwitchAccount(
BuildContext context, String currentUser, String newUser) async {
BuildContext context,
String currentUser,
String newUser,
) async {
if (currentUser == newUser) return;
Navigator.of(context).pop();

View File

@@ -1,29 +0,0 @@
import 'package:flutter/material.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
class SwitchingAccountsPage extends StatelessWidget {
const SwitchingAccountsPage({super.key});
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => false,
child: Material(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 16),
Text(
S.of(context)!.switchingAccountsPleaseWait,
style: Theme.of(context).textTheme.labelLarge,
),
],
),
),
),
);
}
}

View File

@@ -21,6 +21,7 @@ class _LanguageSelectionSettingState extends State<LanguageSelectionSetting> {
'tr': LanguageOption('Türkçe', true),
'pl': LanguageOption('Polska', true),
'ca': LanguageOption('Catalan', true),
'ru': LanguageOption('Русский', true),
};
@override
@@ -34,9 +35,9 @@ class _LanguageSelectionSettingState extends State<LanguageSelectionSetting> {
onTap: () => showDialog<String>(
context: context,
builder: (_) => RadioSettingsDialog<String>(
footer: const Text(
"* Not fully translated yet. Some words may be displayed in English!",
),
// footer: const Text(
// "* Not fully translated yet. Some words may be displayed in English!",
// ),
titleText: S.of(context)!.language,
options: [
for (var language in _languageOptions.entries)

View File

@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import 'package:paperless_mobile/features/settings/view/widgets/global_settings_builder.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
class SkipDocumentPreprationOnShareSetting extends StatelessWidget {
const SkipDocumentPreprationOnShareSetting({super.key});
@@ -9,9 +10,8 @@ class SkipDocumentPreprationOnShareSetting extends StatelessWidget {
return GlobalSettingsBuilder(
builder: (context, settings) {
return SwitchListTile(
title: Text("Direct share"),
subtitle:
Text("Always directly upload when sharing files with the app."),
title: Text(S.of(context)!.skipEditingReceivedFiles),
subtitle: Text(S.of(context)!.uploadWithoutPromptingUploadForm),
value: settings.skipDocumentPreprarationOnUpload,
onChanged: (value) {
settings.skipDocumentPreprarationOnUpload = value;

View File

@@ -1,73 +0,0 @@
import 'dart:io';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:paperless_api/paperless_api.dart';
import 'package:paperless_mobile/core/database/tables/local_user_account.dart';
import 'package:paperless_mobile/core/global/constants.dart';
import 'package:paperless_mobile/core/translation/error_code_localization_mapper.dart';
import 'package:paperless_mobile/features/document_upload/view/document_upload_preparation_page.dart';
import 'package:paperless_mobile/features/sharing/model/share_intent_queue.dart';
import 'package:paperless_mobile/features/sharing/view/dialog/discard_shared_file_dialog.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
import 'package:paperless_mobile/routes/typed/branches/scanner_route.dart';
import 'package:receive_sharing_intent/receive_sharing_intent.dart';
import 'package:path/path.dart' as p;
class UploadQueueProcessor {
final ShareIntentQueue queue;
UploadQueueProcessor({required this.queue});
bool _isFileTypeSupported(File file) {
final isSupported =
supportedFileExtensions.contains(p.extension(file.path));
return isSupported;
}
void processIncomingFiles(
BuildContext context, {
required List<SharedMediaFile> sharedFiles,
}) async {
if (sharedFiles.isEmpty) {
return;
}
Iterable<File> files = sharedFiles.map((file) => File(file.path));
if (Platform.isIOS) {
files = files
.map((file) => File(file.path.replaceAll('file://', '')))
.toList();
}
final supportedFiles = files.where(_isFileTypeSupported);
final unsupportedFiles = files.whereNot(_isFileTypeSupported);
debugPrint(
"Received ${files.length} files, out of which ${supportedFiles.length} are supported.}");
if (supportedFiles.isEmpty) {
Fluttertoast.showToast(
msg: translateError(
context,
ErrorCode.unsupportedFileFormat,
),
);
if (Platform.isAndroid) {
// As stated in the docs, SystemNavigator.pop() is ignored on IOS to comply with HCI guidelines.
await SystemNavigator.pop();
}
return;
}
if (unsupportedFiles.isNotEmpty) {
//TODO: INTL
Fluttertoast.showToast(
msg:
"${unsupportedFiles.length}/${files.length} files could not be processed.");
}
await ShareIntentQueue.instance.addAll(
supportedFiles,
userId: context.read<LocalUserAccount>().id,
);
}
}

View File

@@ -1,105 +0,0 @@
import 'dart:collection';
import 'dart:io';
import 'package:flutter/widgets.dart';
import 'package:hive/hive.dart';
import 'package:paperless_mobile/core/config/hive/hive_extensions.dart';
import 'package:paperless_mobile/core/service/file_service.dart';
import 'package:receive_sharing_intent/receive_sharing_intent.dart';
import 'package:path/path.dart' as p;
class ShareIntentQueue extends ChangeNotifier {
final Map<String, Queue<File>> _queues = {};
ShareIntentQueue._();
static final instance = ShareIntentQueue._();
Future<void> initialize() async {
final users = Hive.localUserAccountBox.values;
for (final user in users) {
final userId = user.id;
debugPrint("Locating remaining files to be uploaded for $userId...");
final consumptionDir =
await FileService.getConsumptionDirectory(userId: userId);
final files = await FileService.getAllFiles(consumptionDir);
debugPrint(
"Found ${files.length} files to be uploaded for $userId. Adding to queue...");
getQueue(userId).addAll(files);
}
}
void add(
File file, {
required String userId,
}) =>
addAll([file], userId: userId);
Future<void> addAll(
Iterable<File> files, {
required String userId,
}) async {
if (files.isEmpty) {
return;
}
final consumptionDirectory =
await FileService.getConsumptionDirectory(userId: userId);
final copiedFiles = await Future.wait([
for (var file in files)
file.copy('${consumptionDirectory.path}/${p.basename(file.path)}')
]);
debugPrint(
"Adding received files to queue: ${files.map((e) => e.path).join(",")}",
);
getQueue(userId).addAll(copiedFiles);
notifyListeners();
}
/// Removes and returns the first item in the requested user's queue if it exists.
File? pop(String userId) {
if (hasUnhandledFiles(userId: userId)) {
final file = getQueue(userId).removeFirst();
notifyListeners();
return file;
// Don't notify listeners, only when new item is added.
}
return null;
}
Future<void> onConsumed(File file) {
debugPrint(
"File ${file.path} successfully consumed. Delelting local copy.");
return file.delete();
}
Future<void> discard(File file) {
debugPrint("Discarding file ${file.path}.");
return file.delete();
}
/// Returns whether the queue of the requested user contains files waiting for processing.
bool hasUnhandledFiles({
required String userId,
}) =>
getQueue(userId).isNotEmpty;
int unhandledFileCount({
required String userId,
}) =>
getQueue(userId).length;
Queue<File> getQueue(String userId) {
if (!_queues.containsKey(userId)) {
_queues[userId] = Queue<File>();
}
return _queues[userId]!;
}
}
class UserAwareShareMediaFile {
final String userId;
final SharedMediaFile sharedFile;
UserAwareShareMediaFile(this.userId, this.sharedFile);
}

View File

@@ -1,9 +1,8 @@
import 'package:flutter/material.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';
import 'package:paperless_mobile/features/sharing/view/widgets/file_thumbnail.dart';
import 'package:paperless_mobile/features/sharing/view/widgets/upload_queue_shell.dart';
import 'package:paperless_mobile/features/sharing/view/widgets/event_listener_shell.dart';
import 'package:paperless_mobile/generated/l10n/app_localizations.dart';
import 'package:path/path.dart' as p;
import 'package:provider/provider.dart';

View File

@@ -3,19 +3,22 @@ import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hive/hive.dart';
import 'package:paperless_api/paperless_api.dart';
import 'package:paperless_mobile/core/bloc/connectivity_cubit.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/notifier/document_changed_notifier.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/inbox/cubit/inbox_cubit.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/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';
@@ -23,25 +26,33 @@ import 'package:paperless_mobile/routes/typed/branches/scanner_route.dart';
import 'package:path/path.dart' as p;
import 'package:receive_sharing_intent/receive_sharing_intent.dart';
class UploadQueueShell extends StatefulWidget {
class EventListenerShell extends StatefulWidget {
final Widget child;
const UploadQueueShell({super.key, required this.child});
const EventListenerShell({super.key, required this.child});
@override
State<UploadQueueShell> createState() => _UploadQueueShellState();
State<EventListenerShell> createState() => _EventListenerShellState();
}
class _UploadQueueShellState extends State<UploadQueueShell> {
class _EventListenerShellState extends State<EventListenerShell>
with WidgetsBindingObserver {
StreamSubscription? _subscription;
StreamSubscription? _documentDeletedSubscription;
Timer? _inboxTimer;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
ReceiveSharingIntent.getInitialMedia().then(_onReceiveSharedFiles);
_subscription =
ReceiveSharingIntent.getMediaStream().listen(_onReceiveSharedFiles);
context.read<PendingTasksNotifier>().addListener(_onTasksChanged);
_documentDeletedSubscription =
context.read<DocumentChangedNotifier>().$deleted.listen((event) {
showSnackBar(context, S.of(context)!.documentSuccessfullyDeleted);
});
_listenToInboxChanges();
// WidgetsBinding.instance.addPostFrameCallback((_) async {
// final notifier = context.read<ConsumptionChangeNotifier>();
// await notifier.isInitialized;
@@ -67,6 +78,52 @@ class _UploadQueueShellState extends State<UploadQueueShell> {
// });
}
void _listenToInboxChanges() {
final cubit = context.read<InboxCubit>();
final currentUser = context.read<LocalUserAccount>();
if (!currentUser.paperlessUser.canViewInbox || _inboxTimer != null) {
return;
}
cubit.refreshItemsInInboxCount(false);
_inboxTimer = Timer.periodic(30.seconds, (_) {
cubit.refreshItemsInInboxCount(false);
});
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_subscription?.cancel();
_documentDeletedSubscription?.cancel();
_inboxTimer?.cancel();
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
switch (state) {
case AppLifecycleState.resumed:
debugPrint(
"App resumed, reloading connectivity and "
"restarting periodic query for inbox changes...",
);
context.read<ConnectivityCubit>().reload();
_listenToInboxChanges();
break;
case AppLifecycleState.inactive:
case AppLifecycleState.paused:
case AppLifecycleState.detached:
default:
_inboxTimer?.cancel();
_inboxTimer = null;
debugPrint(
"App either paused or hidden, stopping "
"periodic query for inbox changes.",
);
break;
}
}
void _onTasksChanged() {
final taskNotifier = context.read<PendingTasksNotifier>();
final userId = context.read<LocalUserAccount>().id;
@@ -96,12 +153,6 @@ class _UploadQueueShellState extends State<UploadQueueShell> {
}
}
@override
void dispose() {
_subscription?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return widget.child;
@@ -167,9 +218,9 @@ Future<void> consumeLocalFile(
);
await consumptionNotifier.discardFile(file, userId: userId);
if (result.taskId != null) {
taskNotifier.listenToTaskChanges(result.taskId!);
}
// if (result.taskId != null) {
// taskNotifier.listenToTaskChanges(result.taskId!);
// }
if (exitAppAfterConsumed) {
SystemNavigator.pop();
}

View File

@@ -52,10 +52,10 @@ class PendingTasksNotifier extends ValueNotifier<Map<String, Task>> {
_subscriptions[taskId]?.cancel();
_subscriptions.remove(taskId);
} else {
_subscriptions.forEach((key, value) {
value.cancel();
_subscriptions.remove(key);
});
for (var sub in _subscriptions.values) {
sub.cancel();
}
_subscriptions.clear();
}
}