Reformat code with latest Flutter 3 linting

This commit is contained in:
Varakh 2022-06-23 00:44:08 +02:00
parent 7ef179906d
commit 011113d72b
35 changed files with 107 additions and 233 deletions

View file

@ -30,8 +30,7 @@ class _DialogManagerState extends State<DialogManager> {
void _showDialog(DialogRequest request) { void _showDialog(DialogRequest request) {
List<Widget> actions = <Widget>[]; List<Widget> actions = <Widget>[];
if (request.buttonTitleDeny != null && if (request.buttonTitleDeny != null && request.buttonTitleDeny!.isNotEmpty) {
request.buttonTitleDeny!.isNotEmpty) {
Widget denyBtn = TextButton( Widget denyBtn = TextButton(
child: Text(request.buttonTitleDeny!), child: Text(request.buttonTitleDeny!),
onPressed: () { onPressed: () {

View file

@ -15,11 +15,7 @@ class ApiKey {
final String? comment; final String? comment;
ApiKey( ApiKey({required this.key, required this.created, required this.accessLevel, this.comment});
{required this.key,
required this.created,
required this.accessLevel,
this.comment});
// JSON Init // JSON Init
factory ApiKey.fromJson(Map<String, dynamic> json) => _$ApiKeyFromJson(json); factory ApiKey.fromJson(Map<String, dynamic> json) => _$ApiKeyFromJson(json);

View file

@ -12,8 +12,7 @@ class ApiKeys {
ApiKeys({required this.apikeys}); ApiKeys({required this.apikeys});
// JSON Init // JSON Init
factory ApiKeys.fromJson(Map<String, dynamic> json) => factory ApiKeys.fromJson(Map<String, dynamic> json) => _$ApiKeysFromJson(json);
_$ApiKeysFromJson(json);
// JSON Export // JSON Export
Map<String, dynamic> toJson() => _$ApiKeysToJson(this); Map<String, dynamic> toJson() => _$ApiKeysToJson(this);

View file

@ -15,8 +15,7 @@ class ApiKeysResponse {
ApiKeysResponse({required this.status, required this.data}); ApiKeysResponse({required this.status, required this.data});
// JSON Init // JSON Init
factory ApiKeysResponse.fromJson(Map<String, dynamic> json) => factory ApiKeysResponse.fromJson(Map<String, dynamic> json) => _$ApiKeysResponseFromJson(json);
_$ApiKeysResponseFromJson(json);
// JSON Export // JSON Export
Map<String, dynamic> toJson() => _$ApiKeysResponseToJson(this); Map<String, dynamic> toJson() => _$ApiKeysResponseToJson(this);

View file

@ -15,8 +15,7 @@ class ConfigResponse {
ConfigResponse({required this.status, required this.data}); ConfigResponse({required this.status, required this.data});
// JSON Init // JSON Init
factory ConfigResponse.fromJson(Map<String, dynamic> json) => factory ConfigResponse.fromJson(Map<String, dynamic> json) => _$ConfigResponseFromJson(json);
_$ConfigResponseFromJson(json);
// JSON Export // JSON Export
Map<String, dynamic> toJson() => _$ConfigResponseToJson(this); Map<String, dynamic> toJson() => _$ConfigResponseToJson(this);

View file

@ -13,8 +13,7 @@ class CreateApiKeyResponse {
CreateApiKeyResponse({required this.status, required this.data}); CreateApiKeyResponse({required this.status, required this.data});
// JSON Init // JSON Init
factory CreateApiKeyResponse.fromJson(Map<String, dynamic> json) => factory CreateApiKeyResponse.fromJson(Map<String, dynamic> json) => _$CreateApiKeyResponseFromJson(json);
_$CreateApiKeyResponseFromJson(json);
// JSON Export // JSON Export
Map<String, dynamic> toJson() => _$CreateApiKeyResponseToJson(this); Map<String, dynamic> toJson() => _$CreateApiKeyResponseToJson(this);

View file

@ -19,8 +19,7 @@ class History {
History({required this.items, required this.multipasteItems, this.totalSize}); History({required this.items, required this.multipasteItems, this.totalSize});
// JSON Init // JSON Init
factory History.fromJson(Map<String, dynamic> json) => factory History.fromJson(Map<String, dynamic> json) => _$HistoryFromJson(json);
_$HistoryFromJson(json);
// JSON Export // JSON Export
Map<String, dynamic> toJson() => _$HistoryToJson(this); Map<String, dynamic> toJson() => _$HistoryToJson(this);

View file

@ -23,8 +23,7 @@ class HistoryItem {
this.thumbnail}); this.thumbnail});
// JSON Init // JSON Init
factory HistoryItem.fromJson(Map<String, dynamic> json) => factory HistoryItem.fromJson(Map<String, dynamic> json) => _$HistoryItemFromJson(json);
_$HistoryItemFromJson(json);
// JSON Export // JSON Export
Map<String, dynamic> toJson() => _$HistoryItemToJson(this); Map<String, dynamic> toJson() => _$HistoryItemToJson(this);

View file

@ -15,8 +15,7 @@ class HistoryMultipasteItem {
HistoryMultipasteItem(this.items, {required this.date, required this.urlId}); HistoryMultipasteItem(this.items, {required this.date, required this.urlId});
// JSON Init // JSON Init
factory HistoryMultipasteItem.fromJson(Map<String, dynamic> json) => factory HistoryMultipasteItem.fromJson(Map<String, dynamic> json) => _$HistoryMultipasteItemFromJson(json);
_$HistoryMultipasteItemFromJson(json);
// JSON Export // JSON Export
Map<String, dynamic> toJson() => _$HistoryMultipasteItemToJson(this); Map<String, dynamic> toJson() => _$HistoryMultipasteItemToJson(this);

View file

@ -9,8 +9,7 @@ class HistoryMultipasteItemEntry {
HistoryMultipasteItemEntry({required this.id}); HistoryMultipasteItemEntry({required this.id});
// JSON Init // JSON Init
factory HistoryMultipasteItemEntry.fromJson(Map<String, dynamic> json) => factory HistoryMultipasteItemEntry.fromJson(Map<String, dynamic> json) => _$HistoryMultipasteItemEntryFromJson(json);
_$HistoryMultipasteItemEntryFromJson(json);
// JSON Export // JSON Export
Map<String, dynamic> toJson() => _$HistoryMultipasteItemEntryToJson(this); Map<String, dynamic> toJson() => _$HistoryMultipasteItemEntryToJson(this);

View file

@ -15,8 +15,7 @@ class HistoryResponse {
HistoryResponse({required this.status, required this.data}); HistoryResponse({required this.status, required this.data});
// JSON Init // JSON Init
factory HistoryResponse.fromJson(Map<String, dynamic> json) => factory HistoryResponse.fromJson(Map<String, dynamic> json) => _$HistoryResponseFromJson(json);
_$HistoryResponseFromJson(json);
// JSON Export // JSON Export
Map<String, dynamic> toJson() => _$HistoryResponseToJson(this); Map<String, dynamic> toJson() => _$HistoryResponseToJson(this);

View file

@ -15,8 +15,7 @@ class RestError {
required this.errorId, required this.errorId,
}); // JSON Init }); // JSON Init
factory RestError.fromJson(Map<String, dynamic> json) => factory RestError.fromJson(Map<String, dynamic> json) => _$RestErrorFromJson(json);
_$RestErrorFromJson(json);
// JSON Export // JSON Export
Map<String, dynamic> toJson() => _$RestErrorToJson(this); Map<String, dynamic> toJson() => _$RestErrorToJson(this);

View file

@ -13,8 +13,7 @@ class Uploaded {
Uploaded({required this.ids, required this.urls}); Uploaded({required this.ids, required this.urls});
// JSON Init // JSON Init
factory Uploaded.fromJson(Map<String, dynamic> json) => factory Uploaded.fromJson(Map<String, dynamic> json) => _$UploadedFromJson(json);
_$UploadedFromJson(json);
// JSON Export // JSON Export
Map<String, dynamic> toJson() => _$UploadedToJson(this); Map<String, dynamic> toJson() => _$UploadedToJson(this);

View file

@ -13,8 +13,7 @@ class UploadedMulti {
UploadedMulti({required this.url, required this.urlId}); UploadedMulti({required this.url, required this.urlId});
// JSON Init // JSON Init
factory UploadedMulti.fromJson(Map<String, dynamic> json) => factory UploadedMulti.fromJson(Map<String, dynamic> json) => _$UploadedMultiFromJson(json);
_$UploadedMultiFromJson(json);
// JSON Export // JSON Export
Map<String, dynamic> toJson() => _$UploadedMultiToJson(this); Map<String, dynamic> toJson() => _$UploadedMultiToJson(this);

View file

@ -15,8 +15,7 @@ class UploadedMultiResponse {
UploadedMultiResponse({required this.status, required this.data}); UploadedMultiResponse({required this.status, required this.data});
// JSON Init // JSON Init
factory UploadedMultiResponse.fromJson(Map<String, dynamic> json) => factory UploadedMultiResponse.fromJson(Map<String, dynamic> json) => _$UploadedMultiResponseFromJson(json);
_$UploadedMultiResponseFromJson(json);
// JSON Export // JSON Export
Map<String, dynamic> toJson() => _$UploadedMultiResponseToJson(this); Map<String, dynamic> toJson() => _$UploadedMultiResponseToJson(this);

View file

@ -15,8 +15,7 @@ class UploadedResponse {
UploadedResponse({required this.status, required this.data}); UploadedResponse({required this.status, required this.data});
// JSON Init // JSON Init
factory UploadedResponse.fromJson(Map<String, dynamic> json) => factory UploadedResponse.fromJson(Map<String, dynamic> json) => _$UploadedResponseFromJson(json);
_$UploadedResponseFromJson(json);
// JSON Export // JSON Export
Map<String, dynamic> toJson() => _$UploadedResponseToJson(this); Map<String, dynamic> toJson() => _$UploadedResponseToJson(this);

View file

@ -13,8 +13,7 @@ class Session {
: url = '', : url = '',
apiKey = ''; apiKey = '';
factory Session.fromJson(Map<String, dynamic> json) => factory Session.fromJson(Map<String, dynamic> json) => _$SessionFromJson(json);
_$SessionFromJson(json);
Map<String, dynamic> toJson() => _$SessionToJson(this); Map<String, dynamic> toJson() => _$SessionToJson(this);
} }

View file

@ -26,8 +26,7 @@ class UploadedPaste {
this.items}); this.items});
// JSON Init // JSON Init
factory UploadedPaste.fromJson(Map<String, dynamic> json) => factory UploadedPaste.fromJson(Map<String, dynamic> json) => _$UploadedPasteFromJson(json);
_$UploadedPasteFromJson(json);
// JSON Export // JSON Export
Map<String, dynamic> toJson() => _$UploadedPasteToJson(this); Map<String, dynamic> toJson() => _$UploadedPasteToJson(this);

View file

@ -33,10 +33,8 @@ class FileRepository {
return response; return response;
} }
Future<UploadedResponse> postUpload( Future<UploadedResponse> postUpload(List<File>? files, Map<String, String>? additionalFiles) async {
List<File>? files, Map<String, String>? additionalFiles) async { var response = await _api.post('/file/upload', files: files, additionalFiles: additionalFiles);
var response = await _api.post('/file/upload',
files: files, additionalFiles: additionalFiles);
return UploadedResponse.fromJson(json.decode(response.body)); return UploadedResponse.fromJson(json.decode(response.body));
} }
@ -44,12 +42,10 @@ class FileRepository {
Map<String, String> multiPasteIds = Map(); Map<String, String> multiPasteIds = Map();
ids.forEach((element) { ids.forEach((element) {
multiPasteIds.putIfAbsent( multiPasteIds.putIfAbsent("ids[${ids.indexOf(element) + 1}]", () => element);
"ids[${ids.indexOf(element) + 1}]", () => element);
}); });
var response = var response = await _api.post('/file/create_multipaste', fields: multiPasteIds);
await _api.post('/file/create_multipaste', fields: multiPasteIds);
return UploadedMultiResponse.fromJson(json.decode(response.body)); return UploadedMultiResponse.fromJson(json.decode(response.body));
} }
} }

View file

@ -8,8 +8,8 @@ import '../services/api.dart';
class UserRepository { class UserRepository {
Api _api = locator<Api>(); Api _api = locator<Api>();
Future<CreateApiKeyResponse> postApiKey(String url, String username, Future<CreateApiKeyResponse> postApiKey(
String password, String accessLevel, String comment) async { String url, String username, String password, String accessLevel, String comment) async {
_api.setUrl(url); _api.setUrl(url);
var fields = Map.fromEntries([ var fields = Map.fromEntries([

View file

@ -24,34 +24,25 @@ class Api implements ApiErrorConverter {
String _url = ""; String _url = "";
String _apiKey = ""; String _apiKey = "";
Map<String, String> _headers = { Map<String, String> _headers = {"Content-Type": _applicationJson, "Accept": _applicationJson};
"Content-Type": _applicationJson,
"Accept": _applicationJson
};
Duration _timeout = Duration(seconds: Constants.apiRequestTimeoutLimit); Duration _timeout = Duration(seconds: Constants.apiRequestTimeoutLimit);
Future<http.Response> fetch<T>(String route) async { Future<http.Response> fetch<T>(String route) async {
try { try {
_logger.d( _logger
"Requesting GET API endpoint '${_url + route}' with headers '$_headers' and maximum timeout '$_timeout'"); .d("Requesting GET API endpoint '${_url + route}' with headers '$_headers' and maximum timeout '$_timeout'");
var response = await http var response = await http.get(Uri.parse(_url + route), headers: _headers).timeout(_timeout);
.get(Uri.parse(_url + route), headers: _headers)
.timeout(_timeout);
handleRestErrors(response); handleRestErrors(response);
return response; return response;
} on TimeoutException { } on TimeoutException {
throw ServiceException( throw ServiceException(code: ErrorCode.SOCKET_TIMEOUT, message: _errorTimeout);
code: ErrorCode.SOCKET_TIMEOUT, message: _errorTimeout);
} on SocketException { } on SocketException {
throw ServiceException( throw ServiceException(code: ErrorCode.SOCKET_ERROR, message: _errorNoConnection);
code: ErrorCode.SOCKET_ERROR, message: _errorNoConnection);
} }
} }
Future<http.Response> post<T>(String route, Future<http.Response> post<T>(String route,
{Map<String, String?>? fields, {Map<String, String?>? fields, List<File>? files, Map<String, String>? additionalFiles}) async {
List<File>? files,
Map<String, String>? additionalFiles}) async {
try { try {
var uri = Uri.parse(_url + route); var uri = Uri.parse(_url + route);
var request = http.MultipartRequest('POST', uri) var request = http.MultipartRequest('POST', uri)
@ -68,34 +59,27 @@ class Api implements ApiErrorConverter {
if (files != null && files.isNotEmpty) { if (files != null && files.isNotEmpty) {
files.forEach((element) async { files.forEach((element) async {
request.files.add(await http.MultipartFile.fromPath( request.files.add(await http.MultipartFile.fromPath('file[${files.indexOf(element) + 1}]', element.path));
'file[${files.indexOf(element) + 1}]', element.path));
}); });
} }
if (additionalFiles != null && additionalFiles.length > 0) { if (additionalFiles != null && additionalFiles.length > 0) {
List<String> keys = additionalFiles.keys.toList(); List<String> keys = additionalFiles.keys.toList();
additionalFiles.forEach((key, value) { additionalFiles.forEach((key, value) {
var index = files != null var index = files != null ? files.length + keys.indexOf(key) + 1 : keys.indexOf(key) + 1;
? files.length + keys.indexOf(key) + 1 request.files.add(http.MultipartFile.fromString('file[$index]', value, filename: key));
: keys.indexOf(key) + 1;
request.files.add(http.MultipartFile.fromString('file[$index]', value,
filename: key));
}); });
} }
_logger.d( _logger.d("Requesting POST API endpoint '${uri.toString()}' and ${request.files.length} files");
"Requesting POST API endpoint '${uri.toString()}' and ${request.files.length} files");
var multiResponse = await request.send(); var multiResponse = await request.send();
var response = await http.Response.fromStream(multiResponse); var response = await http.Response.fromStream(multiResponse);
handleRestErrors(response); handleRestErrors(response);
return response; return response;
} on TimeoutException { } on TimeoutException {
throw ServiceException( throw ServiceException(code: ErrorCode.SOCKET_TIMEOUT, message: _errorTimeout);
code: ErrorCode.SOCKET_TIMEOUT, message: _errorTimeout);
} on SocketException { } on SocketException {
throw ServiceException( throw ServiceException(code: ErrorCode.SOCKET_ERROR, message: _errorNoConnection);
code: ErrorCode.SOCKET_ERROR, message: _errorNoConnection);
} }
} }
@ -123,17 +107,14 @@ class Api implements ApiErrorConverter {
/// have a json decoded object. Replace this with a custom /// have a json decoded object. Replace this with a custom
/// conversion method by overwriting the interface if needed /// conversion method by overwriting the interface if needed
void handleRestErrors(http.Response response) { void handleRestErrors(http.Response response) {
if (response.statusCode != HttpStatus.ok && if (response.statusCode != HttpStatus.ok && response.statusCode != HttpStatus.noContent) {
response.statusCode != HttpStatus.noContent) {
if (response.headers.containsKey(HttpHeaders.contentTypeHeader)) { if (response.headers.containsKey(HttpHeaders.contentTypeHeader)) {
ContentType responseContentType = ContentType responseContentType = ContentType.parse(response.headers[HttpHeaders.contentTypeHeader]!);
ContentType.parse(response.headers[HttpHeaders.contentTypeHeader]!);
if (ContentType.json.primaryType == responseContentType.primaryType && if (ContentType.json.primaryType == responseContentType.primaryType &&
ContentType.json.subType == responseContentType.subType) { ContentType.json.subType == responseContentType.subType) {
var parsedBody = convert(response); var parsedBody = convert(response);
throw new RestServiceException(response.statusCode, throw new RestServiceException(response.statusCode, responseBody: parsedBody);
responseBody: parsedBody);
} }
} }

View file

@ -27,28 +27,20 @@ class DialogService {
title: title, title: title,
description: description, description: description,
buttonTitleAccept: buttonTitleAccept:
buttonTitleAccept == null || buttonTitleAccept.isEmpty buttonTitleAccept == null || buttonTitleAccept.isEmpty ? translate('dialog.confirm') : buttonTitleAccept));
? translate('dialog.confirm')
: buttonTitleAccept));
return _dialogCompleter!.future; return _dialogCompleter!.future;
} }
Future<DialogResponse> showConfirmationDialog( Future<DialogResponse> showConfirmationDialog(
{String? title, {String? title, String? description, String? buttonTitleAccept, String? buttonTitleDeny}) {
String? description,
String? buttonTitleAccept,
String? buttonTitleDeny}) {
_dialogCompleter = Completer<DialogResponse>(); _dialogCompleter = Completer<DialogResponse>();
_showDialogListener(DialogRequest( _showDialogListener(DialogRequest(
title: title, title: title,
description: description, description: description,
buttonTitleAccept: buttonTitleAccept:
buttonTitleAccept == null || buttonTitleAccept.isEmpty buttonTitleAccept == null || buttonTitleAccept.isEmpty ? translate('dialog.confirm') : buttonTitleAccept,
? translate('dialog.confirm') buttonTitleDeny:
: buttonTitleAccept, buttonTitleDeny == null || buttonTitleDeny.isEmpty ? translate('dialog.cancel') : buttonTitleDeny));
buttonTitleDeny: buttonTitleDeny == null || buttonTitleDeny.isEmpty
? translate('dialog.cancel')
: buttonTitleDeny));
return _dialogCompleter!.future; return _dialogCompleter!.future;
} }

View file

@ -23,8 +23,7 @@ class FileService {
return await _fileRepository.postDelete(id); return await _fileRepository.postDelete(id);
} }
Future<UploadedResponse> uploadPaste( Future<UploadedResponse> uploadPaste(List<File>? files, Map<String, String>? additionalFiles) async {
List<File>? files, Map<String, String>? additionalFiles) async {
return await _fileRepository.postUpload(files, additionalFiles); return await _fileRepository.postUpload(files, additionalFiles);
} }

View file

@ -57,8 +57,7 @@ class PermissionService extends StoppableService {
return; return;
} }
var ignoredDialog = var ignoredDialog = await _storageService.hasStoragePermissionDialogIgnored();
await _storageService.hasStoragePermissionDialogIgnored();
if (ignoredDialog) { if (ignoredDialog) {
_logger.d('Permanently ignored permission request, skipping'); _logger.d('Permanently ignored permission request, skipping');
@ -105,9 +104,8 @@ class PermissionService extends StoppableService {
super.start(); super.start();
await checkEnabledAndPermission(); await checkEnabledAndPermission();
_serviceCheckTimer = Timer.periodic( _serviceCheckTimer =
Duration(milliseconds: Constants.mediaPermissionCheckInterval), Timer.periodic(Duration(milliseconds: Constants.mediaPermissionCheckInterval), (_serviceTimer) async {
(_serviceTimer) async {
if (!super.serviceStopped) { if (!super.serviceStopped) {
await checkEnabledAndPermission(); await checkEnabledAndPermission();
} else { } else {

View file

@ -12,10 +12,9 @@ class UserService {
final FileService _fileService = locator<FileService>(); final FileService _fileService = locator<FileService>();
final UserRepository _userRepository = locator<UserRepository>(); final UserRepository _userRepository = locator<UserRepository>();
Future<CreateApiKeyResponse> createApiKey(String url, String username, Future<CreateApiKeyResponse> createApiKey(
String password, String accessLevel, String comment) async { String url, String username, String password, String accessLevel, String comment) async {
return await _userRepository.postApiKey( return await _userRepository.postApiKey(url, username, password, accessLevel, comment);
url, username, password, accessLevel, comment);
} }
Future<ApiKeysResponse> getApiKeys() async { Future<ApiKeysResponse> getApiKeys() async {
@ -27,8 +26,7 @@ class UserService {
try { try {
await _fileService.getHistory(); await _fileService.getHistory();
} on ServiceException catch (e) { } on ServiceException catch (e) {
throw new ServiceException( throw new ServiceException(code: ErrorCode.INVALID_API_KEY, message: e.message);
code: ErrorCode.INVALID_API_KEY, message: e.message);
} }
} }
} }

View file

@ -34,8 +34,7 @@ class HistoryModel extends BaseModel {
String? errorMessage; String? errorMessage;
void init() { void init() {
_refreshTriggerSubscription = _refreshTriggerSubscription = _refreshService.refreshEventController.stream.listen((event) {
_refreshService.refreshEventController.stream.listen((event) {
if (event == RefreshEvent.RefreshHistory) { if (event == RefreshEvent.RefreshHistory) {
_logger.d('History needs a refresh'); _logger.d('History needs a refresh');
getHistory(); getHistory();
@ -55,8 +54,7 @@ class HistoryModel extends BaseModel {
pastes.add( pastes.add(
UploadedPaste( UploadedPaste(
id: key, id: key,
date: date: DateTime.fromMillisecondsSinceEpoch(millisecondsSinceEpoch),
DateTime.fromMillisecondsSinceEpoch(millisecondsSinceEpoch),
filename: value.filename, filename: value.filename,
filesize: int.parse(value.filesize), filesize: int.parse(value.filesize),
hash: value.hash, hash: value.hash,
@ -92,11 +90,9 @@ class HistoryModel extends BaseModel {
e.responseBody is RestError && e.responseBody is RestError &&
e.responseBody.message != null) { e.responseBody.message != null) {
if (e.statusCode == HttpStatus.badRequest) { if (e.statusCode == HttpStatus.badRequest) {
errorMessage = translate('api.bad_request', errorMessage = translate('api.bad_request', args: {'reason': e.responseBody.message});
args: {'reason': e.responseBody.message});
} else { } else {
errorMessage = translate('api.general_rest_error_payload', errorMessage = translate('api.general_rest_error_payload', args: {'message': e.responseBody.message});
args: {'message': e.responseBody.message});
} }
} else { } else {
errorMessage = translate('api.general_rest_error'); errorMessage = translate('api.general_rest_error');
@ -119,8 +115,7 @@ class HistoryModel extends BaseModel {
Future deletePaste(String id) async { Future deletePaste(String id) async {
DialogResponse res = await _dialogService.showConfirmationDialog( DialogResponse res = await _dialogService.showConfirmationDialog(
title: translate('history.delete_dialog.title'), title: translate('history.delete_dialog.title'),
description: description: translate('history.delete_dialog.description', args: {'id': id}),
translate('history.delete_dialog.description', args: {'id': id}),
buttonTitleAccept: translate('history.delete_dialog.accept'), buttonTitleAccept: translate('history.delete_dialog.accept'),
buttonTitleDeny: translate('history.delete_dialog.deny')); buttonTitleDeny: translate('history.delete_dialog.deny'));
@ -144,8 +139,7 @@ class HistoryModel extends BaseModel {
e.statusCode != HttpStatus.forbidden && e.statusCode != HttpStatus.forbidden &&
e.responseBody is RestError && e.responseBody is RestError &&
e.responseBody.message != null) { e.responseBody.message != null) {
errorMessage = translate('api.general_rest_error_payload', errorMessage = translate('api.general_rest_error_payload', args: {'message': e.responseBody.message});
args: {'message': e.responseBody.message});
} else { } else {
errorMessage = translate('api.general_rest_error'); errorMessage = translate('api.general_rest_error');
} }

View file

@ -117,19 +117,14 @@ class LoginModel extends BaseModel {
try { try {
if (useCredentialsLogin) { if (useCredentialsLogin) {
CreateApiKeyResponse apiKeyResponse = await _userService.createApiKey( CreateApiKeyResponse apiKeyResponse = await _userService.createApiKey(
url, url, username, password, 'apikey', 'fbmobile-${new DateTime.now().millisecondsSinceEpoch}');
username,
password,
'apikey',
'fbmobile-${new DateTime.now().millisecondsSinceEpoch}');
var newKey = apiKeyResponse.data['new_key']; var newKey = apiKeyResponse.data['new_key'];
if (newKey != null) { if (newKey != null) {
success = await _sessionService.login(url, newKey); success = await _sessionService.login(url, newKey);
} else { } else {
throw new ServiceException( throw new ServiceException(
code: ErrorCode.INVALID_API_KEY, code: ErrorCode.INVALID_API_KEY, message: translate('login.errors.invalid_api_key'));
message: translate('login.errors.invalid_api_key'));
} }
} else { } else {
_sessionService.setApiConfig(url, apiKey); _sessionService.setApiConfig(url, apiKey);
@ -141,15 +136,13 @@ class LoginModel extends BaseModel {
if (e is RestServiceException) { if (e is RestServiceException) {
if (e.statusCode == HttpStatus.unauthorized) { if (e.statusCode == HttpStatus.unauthorized) {
errorMessage = translate('login.errors.wrong_credentials'); errorMessage = translate('login.errors.wrong_credentials');
} else if (e.statusCode != HttpStatus.unauthorized && } else if (e.statusCode != HttpStatus.unauthorized && e.statusCode == HttpStatus.forbidden) {
e.statusCode == HttpStatus.forbidden) {
errorMessage = translate('login.errors.forbidden'); errorMessage = translate('login.errors.forbidden');
} else if (e.statusCode == HttpStatus.notFound) { } else if (e.statusCode == HttpStatus.notFound) {
errorMessage = translate('api.incompatible_error_not_found'); errorMessage = translate('api.incompatible_error_not_found');
} }
if (e.statusCode == HttpStatus.badRequest) { if (e.statusCode == HttpStatus.badRequest) {
errorMessage = translate('api.bad_request', errorMessage = translate('api.bad_request', args: {'reason': e.responseBody.message});
args: {'reason': e.responseBody.message});
} else { } else {
errorMessage = translate('api.general_rest_error'); errorMessage = translate('api.general_rest_error');
} }

View file

@ -27,8 +27,7 @@ class AppRouter {
return MaterialPageRoute( return MaterialPageRoute(
builder: (_) => Scaffold( builder: (_) => Scaffold(
body: Center( body: Center(
child: Text(translate('dev.no_route', child: Text(translate('dev.no_route', args: {'route': settings.name})),
args: {'route': settings.name})),
), ),
)); ));
} }

View file

@ -31,9 +31,7 @@ class _BaseViewState<T extends BaseModel> extends State<BaseView<T>> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ChangeNotifierProvider<T?>( return ChangeNotifierProvider<T?>(create: (context) => model, child: Consumer<T>(builder: widget.builder!));
create: (context) => model,
child: Consumer<T>(builder: widget.builder!));
} }
@override @override

View file

@ -42,8 +42,7 @@ class HistoryView extends StatelessWidget {
? Container( ? Container(
padding: EdgeInsets.all(0), padding: EdgeInsets.all(0),
child: RefreshIndicator( child: RefreshIndicator(
onRefresh: () async => await model.getHistory(), onRefresh: () async => await model.getHistory(), child: _renderItems(model, url, context)))
child: _renderItems(model, url, context)))
: Container( : Container(
padding: EdgeInsets.all(25), padding: EdgeInsets.all(25),
child: CenteredErrorRow( child: CenteredErrorRow(
@ -63,8 +62,7 @@ class HistoryView extends StatelessWidget {
var openInBrowserButton = _renderOpenInBrowser(model, fullPasteUrl); var openInBrowserButton = _renderOpenInBrowser(model, fullPasteUrl);
var dateWidget = ListTile( var dateWidget = ListTile(
title: Text( title: Text(FormatterUtil.formatEpoch(paste.date!.millisecondsSinceEpoch)),
FormatterUtil.formatEpoch(paste.date!.millisecondsSinceEpoch)),
subtitle: Text(translate('history.date')), subtitle: Text(translate('history.date')),
); );
@ -76,8 +74,7 @@ class HistoryView extends StatelessWidget {
var copyWidget = ListTile( var copyWidget = ListTile(
title: Text(translate('history.copy_link.description')), title: Text(translate('history.copy_link.description')),
trailing: IconButton( trailing: IconButton(
icon: Icon(Icons.copy, icon: Icon(Icons.copy, color: blueColor, textDirection: TextDirection.ltr),
color: blueColor, textDirection: TextDirection.ltr),
onPressed: () { onPressed: () {
FlutterClipboard.copy(fullPasteUrl).then((value) { FlutterClipboard.copy(fullPasteUrl).then((value) {
final snackBar = SnackBar( final snackBar = SnackBar(
@ -168,14 +165,12 @@ class HistoryView extends StatelessWidget {
trailing: Wrap(children: [ trailing: Wrap(children: [
openInBrowserButton, openInBrowserButton,
IconButton( IconButton(
icon: Icon(Icons.share, icon: Icon(Icons.share, color: blueColor, textDirection: TextDirection.ltr),
color: blueColor, textDirection: TextDirection.ltr),
onPressed: () async { onPressed: () async {
await Share.share(fullPasteUrl); await Share.share(fullPasteUrl);
}) })
]), ]),
subtitle: Text(!paste.isMulti! ? paste.filename! : '', subtitle: Text(!paste.isMulti! ? paste.filename! : '', style: TextStyle(fontStyle: FontStyle.italic)),
style: TextStyle(fontStyle: FontStyle.italic)),
), ),
)); ));
}); });
@ -196,8 +191,7 @@ class HistoryView extends StatelessWidget {
Widget _renderOpenInBrowser(HistoryModel model, String url) { Widget _renderOpenInBrowser(HistoryModel model, String url) {
return IconButton( return IconButton(
icon: Icon(Icons.open_in_new, icon: Icon(Icons.open_in_new, color: blueColor, textDirection: TextDirection.ltr),
color: blueColor, textDirection: TextDirection.ltr),
onPressed: () { onPressed: () {
return model.openLink(url); return model.openLink(url);
}); });

View file

@ -59,18 +59,13 @@ class LoginView extends StatelessWidget {
child: Icon(Icons.help, color: buttonBackgroundColor), child: Icon(Icons.help, color: buttonBackgroundColor),
onTap: () { onTap: () {
_dialogService.showDialog( _dialogService.showDialog(
title: translate( title: translate('login.compatibility_dialog.title'),
'login.compatibility_dialog.title'), description: translate('login.compatibility_dialog.body'));
description: translate(
'login.compatibility_dialog.body'));
}, },
), ),
InkWell( InkWell(
child: Icon( child:
model.useCredentialsLogin Icon(model.useCredentialsLogin ? Icons.person_outline : Icons.vpn_key, color: blueColor),
? Icons.person_outline
: Icons.vpn_key,
color: blueColor),
onTap: () { onTap: () {
model.toggleLoginMethod(); model.toggleLoginMethod();
}, },
@ -90,13 +85,11 @@ class LoginView extends StatelessWidget {
apiKeyController: model.apiKeyController), apiKeyController: model.apiKeyController),
UIHelper.verticalSpaceMedium(), UIHelper.verticalSpaceMedium(),
ElevatedButton( ElevatedButton(
child: Text(translate('login.button'), child: Text(translate('login.button'), style: TextStyle(color: buttonForegroundColor)),
style: TextStyle(color: buttonForegroundColor)),
onPressed: () async { onPressed: () async {
var loginSuccess = await model.login(); var loginSuccess = await model.login();
if (loginSuccess) { if (loginSuccess) {
_navigationService _navigationService.navigateAndReplaceTo(HomeView.routeName);
.navigateAndReplaceTo(HomeView.routeName);
} }
}, },
) )

View file

@ -9,8 +9,7 @@ class AnonymousTabBarView extends StatefulWidget {
AnonymousTabBarState createState() => AnonymousTabBarState(); AnonymousTabBarState createState() => AnonymousTabBarState();
} }
class AnonymousTabBarState extends State<AnonymousTabBarView> class AnonymousTabBarState extends State<AnonymousTabBarView> with SingleTickerProviderStateMixin {
with SingleTickerProviderStateMixin {
TabController? _tabController; TabController? _tabController;
int _currentTabIndex = 0; int _currentTabIndex = 0;

View file

@ -9,8 +9,7 @@ class TabBarContainerView extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
Session? currentSession = Provider.of<Session?>(context); Session? currentSession = Provider.of<Session?>(context);
bool isAuthenticated = bool isAuthenticated = currentSession != null ? currentSession.apiKey.isNotEmpty : false;
currentSession != null ? currentSession.apiKey.isNotEmpty : false;
if (isAuthenticated) { if (isAuthenticated) {
return AuthenticatedTabBarView(); return AuthenticatedTabBarView();

View file

@ -26,8 +26,7 @@ class UploadView extends StatelessWidget {
} }
bool _isUploadButtonEnabled(UploadModel model) { bool _isUploadButtonEnabled(UploadModel model) {
return model.pasteTextTouched || return model.pasteTextTouched || (model.paths != null && model.paths!.length > 0);
(model.paths != null && model.paths!.length > 0);
} }
Widget _render(UploadModel model, BuildContext context) { Widget _render(UploadModel model, BuildContext context) {
@ -40,9 +39,7 @@ class UploadView extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
children: [ children: [
CircularProgressIndicator(), CircularProgressIndicator(),
(model.stateMessage != null && model.stateMessage!.isNotEmpty (model.stateMessage != null && model.stateMessage!.isNotEmpty ? Text(model.stateMessage!) : Container())
? Text(model.stateMessage!)
: Container())
])) ]))
: ListView(children: <Widget>[ : ListView(children: <Widget>[
Padding( Padding(
@ -61,15 +58,12 @@ class UploadView extends StatelessWidget {
color: buttonBackgroundColor, color: buttonBackgroundColor,
), ),
suffixIcon: IconButton( suffixIcon: IconButton(
onPressed: () => onPressed: () => model.pasteTextController.clear(),
model.pasteTextController.clear(),
icon: Icon(Icons.clear), icon: Icon(Icons.clear),
), ),
hintText: translate('upload.text_to_be_pasted'), hintText: translate('upload.text_to_be_pasted'),
contentPadding: contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0), border: OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(32.0)),
), ),
controller: model.pasteTextController)), controller: model.pasteTextController)),
Padding( Padding(
@ -85,24 +79,20 @@ class UploadView extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end,
children: [ children: [
ElevatedButton.icon( ElevatedButton.icon(
icon: Icon(Icons.file_copy_sharp, icon: Icon(Icons.file_copy_sharp, color: blueColor),
color: blueColor),
onPressed: () => model.openFileExplorer(), onPressed: () => model.openFileExplorer(),
label: Text( label: Text(
translate('upload.open_file_explorer'), translate('upload.open_file_explorer'),
style: style: TextStyle(color: buttonForegroundColor),
TextStyle(color: buttonForegroundColor),
)), )),
ElevatedButton.icon( ElevatedButton.icon(
icon: Icon(Icons.cancel, color: orangeColor), icon: Icon(Icons.cancel, color: orangeColor),
onPressed: model.paths != null && onPressed: model.paths != null && model.paths!.length > 0
model.paths!.length > 0
? () => model.clearCachedFiles() ? () => model.clearCachedFiles()
: null, : null,
label: Text( label: Text(
translate('upload.clear_temporary_files'), translate('upload.clear_temporary_files'),
style: style: TextStyle(color: buttonForegroundColor),
TextStyle(color: buttonForegroundColor),
)), )),
], ],
)), )),
@ -128,48 +118,35 @@ class UploadView extends StatelessWidget {
onPressed: !_isUploadButtonEnabled(model) onPressed: !_isUploadButtonEnabled(model)
? null ? null
: () async { : () async {
Map<String, bool>? items = Map<String, bool>? items = await model.upload();
await model.upload(); String? clipboardContent = model.generatePasteLinks(items, url);
String? clipboardContent = model
.generatePasteLinks(items, url);
if (clipboardContent != null && if (clipboardContent != null && clipboardContent.isNotEmpty) {
clipboardContent.isNotEmpty) { FlutterClipboard.copy(clipboardContent).then((value) {
FlutterClipboard.copy(
clipboardContent)
.then((value) {
final snackBar = SnackBar( final snackBar = SnackBar(
action: SnackBarAction( action: SnackBarAction(
label: translate( label: translate('upload.dismiss'),
'upload.dismiss'),
textColor: blueColor, textColor: blueColor,
onPressed: () { onPressed: () {
ScaffoldMessenger.of( ScaffoldMessenger.of(context).hideCurrentSnackBar();
context)
.hideCurrentSnackBar();
}, },
), ),
content: Text(translate( content: Text(translate('upload.uploaded')),
'upload.uploaded')),
duration: Duration(seconds: 10), duration: Duration(seconds: 10),
); );
ScaffoldMessenger.of(context) ScaffoldMessenger.of(context).showSnackBar(snackBar);
.showSnackBar(snackBar);
}); });
} }
}, },
icon: Icon(Icons.upload_rounded, icon: Icon(Icons.upload_rounded, color: greenColor),
color: greenColor),
label: Text( label: Text(
translate('upload.upload'), translate('upload.upload'),
style: style: TextStyle(color: buttonForegroundColor),
TextStyle(color: buttonForegroundColor),
)), )),
])), ])),
model.errorMessage != null && model.errorMessage!.isNotEmpty model.errorMessage != null && model.errorMessage!.isNotEmpty
? (Padding( ? (Padding(
padding: padding: const EdgeInsets.only(top: 10.0, bottom: 10.0),
const EdgeInsets.only(top: 10.0, bottom: 10.0),
child: CenteredErrorRow(model.errorMessage))) child: CenteredErrorRow(model.errorMessage)))
: Container(), : Container(),
Builder( Builder(
@ -181,28 +158,16 @@ class UploadView extends StatelessWidget {
: model.paths != null : model.paths != null
? Container( ? Container(
padding: const EdgeInsets.only(bottom: 30.0), padding: const EdgeInsets.only(bottom: 30.0),
height: height: MediaQuery.of(context).size.height * 0.50,
MediaQuery.of(context).size.height * 0.50,
child: ListView.separated( child: ListView.separated(
itemCount: model.paths != null && itemCount: model.paths != null && model.paths!.isNotEmpty ? model.paths!.length : 1,
model.paths!.isNotEmpty itemBuilder: (BuildContext context, int index) {
? model.paths!.length final bool isMultiPath = model.paths != null && model.paths!.isNotEmpty;
: 1,
itemBuilder:
(BuildContext context, int index) {
final bool isMultiPath =
model.paths != null &&
model.paths!.isNotEmpty;
final String name = (isMultiPath final String name = (isMultiPath
? model.paths! ? model.paths!.map((e) => e.name).toList()[index]
.map((e) => e.name)
.toList()[index]
: model.fileName ?? '...'); : model.fileName ?? '...');
final path = model.paths!.length > 0 final path = model.paths!.length > 0
? model.paths! ? model.paths!.map((e) => e.path).toList()[index].toString()
.map((e) => e.path)
.toList()[index]
.toString()
: ''; : '';
return Card( return Card(
@ -213,9 +178,7 @@ class UploadView extends StatelessWidget {
subtitle: Text(path), subtitle: Text(path),
)); ));
}, },
separatorBuilder: separatorBuilder: (BuildContext context, int index) => const Divider(),
(BuildContext context, int index) =>
const Divider(),
), ),
) )
: Container(), : Container(),

View file

@ -32,7 +32,6 @@ class _SwipeNavigationState extends State<SwipeNavigation> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return SimpleGestureDetector( return SimpleGestureDetector(onHorizontalSwipe: _onHorizontalSwipe, child: widget.child!);
onHorizontalSwipe: _onHorizontalSwipe, child: widget.child!);
} }
} }