updated project style guidelines

This commit is contained in:
Elias Müller 2024-04-03 19:18:17 +02:00
parent 27618f4404
commit 4c7f53e309
185 changed files with 505 additions and 873 deletions

View File

@ -28,6 +28,13 @@ linter:
prefer_relative_imports: true prefer_relative_imports: true
unnecessary_lambdas: true unnecessary_lambdas: true
prefer_single_quotes: true prefer_single_quotes: true
prefer_if_elements_to_conditional_expressions: true
prefer_expression_function_bodies: true
omit_local_variable_types: true
eol_at_end_of_file: true
cast_nullable_to_non_nullable: true
avoid_void_async: true
avoid_multiple_declarations_per_line: true
# Additional information about this file can be found at # Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options # https://dart.dev/guides/language/analysis-options

View File

@ -4,7 +4,5 @@ class ApiError {
ApiError(this.message); ApiError(this.message);
@override @override
String toString() { String toString() => 'ApiError: $message';
return 'ApiError: $message';
}
} }

View File

@ -6,7 +6,7 @@ import 'getHolidaysResponse.dart';
class GetHolidays { class GetHolidays {
Future<GetHolidaysResponse> query() async { Future<GetHolidaysResponse> query() async {
String response = (await http.get(Uri.parse('https://ferien-api.de/api/v1/holidays/HE'))).body; var response = (await http.get(Uri.parse('https://ferien-api.de/api/v1/holidays/HE'))).body;
return GetHolidaysResponse( return GetHolidaysResponse(
List<GetHolidaysResponseObject>.from( List<GetHolidaysResponseObject>.from(
jsonDecode(response).map<GetHolidaysResponseObject>( jsonDecode(response).map<GetHolidaysResponseObject>(

View File

@ -23,7 +23,5 @@ class GetHolidaysCache extends RequestCache<GetHolidaysResponse> {
} }
@override @override
Future<GetHolidaysResponse> onLoad() { Future<GetHolidaysResponse> onLoad() => GetHolidays().query();
return GetHolidays().query();
}
} }

View File

@ -2,7 +2,6 @@ import 'dart:convert';
import 'dart:io'; import 'dart:io';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import '../../../model/accountData.dart'; import '../../../model/accountData.dart';
import '../../../model/endpointData.dart'; import '../../../model/endpointData.dart';
@ -10,7 +9,7 @@ import 'autocompleteResponse.dart';
class AutocompleteApi { class AutocompleteApi {
Future<AutocompleteResponse> find(String query) async { Future<AutocompleteResponse> find(String query) async {
Map<String, dynamic> getParameters = { var getParameters = <String, dynamic>{
'search': query, 'search': query,
'itemType': ' ', 'itemType': ' ',
'itemId': ' ', 'itemId': ' ',
@ -18,15 +17,15 @@ class AutocompleteApi {
'limit': '10', 'limit': '10',
}; };
Map<String, String> headers = {}; var headers = <String, String>{};
headers.putIfAbsent('Accept', () => 'application/json'); headers.putIfAbsent('Accept', () => 'application/json');
headers.putIfAbsent('OCS-APIRequest', () => 'true'); headers.putIfAbsent('OCS-APIRequest', () => 'true');
Uri endpoint = Uri.https('${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().domain}', '${EndpointData().nextcloud().path}/ocs/v2.php/core/autocomplete/get', getParameters); var endpoint = Uri.https('${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().domain}', '${EndpointData().nextcloud().path}/ocs/v2.php/core/autocomplete/get', getParameters);
Response response = await http.get(endpoint, headers: headers); var response = await http.get(endpoint, headers: headers);
if(response.statusCode != HttpStatus.ok) throw Exception('Api call failed with ${response.statusCode}: ${response.body}'); if(response.statusCode != HttpStatus.ok) throw Exception('Api call failed with ${response.statusCode}: ${response.body}');
String result = response.body; var result = response.body;
return AutocompleteResponse.fromJson(jsonDecode(result)['ocs']); return AutocompleteResponse.fromJson(jsonDecode(result)['ocs']);
} }

View File

@ -1,7 +1,6 @@
import 'dart:io'; import 'dart:io';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import '../../../model/accountData.dart'; import '../../../model/accountData.dart';
import '../../../model/endpointData.dart'; import '../../../model/endpointData.dart';
@ -9,12 +8,12 @@ import 'fileSharingApiParams.dart';
class FileSharingApi { class FileSharingApi {
Future<void> share(FileSharingApiParams query) async { Future<void> share(FileSharingApiParams query) async {
Map<String, String> headers = {}; var headers = <String, String>{};
headers.putIfAbsent('Accept', () => 'application/json'); headers.putIfAbsent('Accept', () => 'application/json');
headers.putIfAbsent('OCS-APIRequest', () => 'true'); headers.putIfAbsent('OCS-APIRequest', () => 'true');
Uri endpoint = Uri.https('${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().domain}', '${EndpointData().nextcloud().path}/ocs/v2.php/apps/files_sharing/api/v1/shares', query.toJson().map((key, value) => MapEntry(key, value.toString()))); var endpoint = Uri.https('${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().domain}', '${EndpointData().nextcloud().path}/ocs/v2.php/apps/files_sharing/api/v1/shares', query.toJson().map((key, value) => MapEntry(key, value.toString())));
Response response = await http.post(endpoint, headers: headers); var response = await http.post(endpoint, headers: headers);
if(response.statusCode != HttpStatus.ok) { if(response.statusCode != HttpStatus.ok) {
throw Exception('Api call failed with ${response.statusCode}: ${response.body}'); throw Exception('Api call failed with ${response.statusCode}: ${response.body}');

View File

@ -14,13 +14,9 @@ class GetChat extends TalkApi<GetChatResponse> {
GetChat(this.chatToken, this.params) : super('v1/chat/$chatToken', null, getParameters: params.toJson()); GetChat(this.chatToken, this.params) : super('v1/chat/$chatToken', null, getParameters: params.toJson());
@override @override
assemble(String raw) { assemble(String raw) => GetChatResponse.fromJson(jsonDecode(raw)['ocs']);
return GetChatResponse.fromJson(jsonDecode(raw)['ocs']);
}
@override @override
Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) { Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) => http.get(uri, headers: headers);
return http.get(uri, headers: headers);
}
} }

View File

@ -13,8 +13,7 @@ class GetChatCache extends RequestCache<GetChatResponse> {
} }
@override @override
Future<GetChatResponse> onLoad() { Future<GetChatResponse> onLoad() => GetChat(
return GetChat(
chatToken, chatToken,
GetChatParams( GetChatParams(
lookIntoFuture: GetChatParamsSwitch.off, lookIntoFuture: GetChatParamsSwitch.off,
@ -22,11 +21,8 @@ class GetChatCache extends RequestCache<GetChatResponse> {
limit: 200, limit: 200,
) )
).run(); ).run();
}
@override @override
GetChatResponse onLocalData(String json) { GetChatResponse onLocalData(String json) => GetChatResponse.fromJson(jsonDecode(json));
return GetChatResponse.fromJson(jsonDecode(json));
}
} }

View File

@ -16,7 +16,7 @@ class GetChatResponse extends ApiResponse {
Map<String, dynamic> toJson() => _$GetChatResponseToJson(this); Map<String, dynamic> toJson() => _$GetChatResponseToJson(this);
List<GetChatResponseObject> sortByTimestamp() { List<GetChatResponseObject> sortByTimestamp() {
List<GetChatResponseObject> sorted = data.toList(); var sorted = data.toList();
sorted.sort((a, b) => a.timestamp.compareTo(b.timestamp)); sorted.sort((a, b) => a.timestamp.compareTo(b.timestamp));
return sorted; return sorted;
} }
@ -60,12 +60,11 @@ class GetChatResponseObject {
Map<String, dynamic> toJson() => _$GetChatResponseObjectToJson(this); Map<String, dynamic> toJson() => _$GetChatResponseObjectToJson(this);
static GetChatResponseObject getDateDummy(int timestamp) { static GetChatResponseObject getDateDummy(int timestamp) {
DateTime elementDate = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000); var elementDate = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
return getTextDummy(Jiffy.parseFromDateTime(elementDate).format(pattern: 'dd.MM.yyyy')); return getTextDummy(Jiffy.parseFromDateTime(elementDate).format(pattern: 'dd.MM.yyyy'));
} }
static GetChatResponseObject getTextDummy(String text) { static GetChatResponseObject getTextDummy(String text) => GetChatResponseObject(
return GetChatResponseObject(
0, 0,
'', '',
GetRoomResponseObjectMessageActorType.user, GetRoomResponseObjectMessageActorType.user,
@ -81,13 +80,12 @@ class GetChatResponseObject {
null, null,
null null
); );
}
} }
Map<String, RichObjectString>? _fromJson(json) { Map<String, RichObjectString>? _fromJson(json) {
if(json is Map<String, dynamic>) { if(json is Map<String, dynamic>) {
Map<String, RichObjectString> data = {}; var data = <String, RichObjectString>{};
for (var element in json.keys) { for (var element in json.keys) {
data.putIfAbsent(element, () => RichObjectString.fromJson(json[element])); data.putIfAbsent(element, () => RichObjectString.fromJson(json[element]));
} }

View File

@ -10,9 +10,7 @@ class CreateRoom extends TalkApi {
CreateRoom(this.params) : super('v4/room', params); CreateRoom(this.params) : super('v4/room', params);
@override @override
assemble(String raw) { assemble(String raw) => null;
return null;
}
@override @override
Future<Response>? request(Uri uri, Object? body, Map<String, String>? headers) { Future<Response>? request(Uri uri, Object? body, Map<String, String>? headers) {

View File

@ -10,13 +10,9 @@ class DeleteMessage extends TalkApi {
DeleteMessage(this.chatToken, this.messageId) : super('v1/chat/$chatToken/$messageId', null); DeleteMessage(this.chatToken, this.messageId) : super('v1/chat/$chatToken/$messageId', null);
@override @override
assemble(String raw) { assemble(String raw) => null;
return null;
}
@override @override
Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) { Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) => http.delete(uri, headers: headers);
return http.delete(uri, headers: headers);
}
} }

View File

@ -11,9 +11,7 @@ class DeleteReactMessage extends TalkApi {
DeleteReactMessage({required this.chatToken, required this.messageId, required DeleteReactMessageParams params}) : super('v1/reaction/$chatToken/$messageId', params); DeleteReactMessage({required this.chatToken, required this.messageId, required DeleteReactMessageParams params}) : super('v1/reaction/$chatToken/$messageId', params);
@override @override
assemble(String raw) { assemble(String raw) => null;
return null;
}
@override @override
Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) { Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) {

View File

@ -10,13 +10,9 @@ class GetParticipants extends TalkApi<GetParticipantsResponse> {
GetParticipants(this.token) : super('v4/room/$token/participants', null); GetParticipants(this.token) : super('v4/room/$token/participants', null);
@override @override
GetParticipantsResponse assemble(String raw) { GetParticipantsResponse assemble(String raw) => GetParticipantsResponse.fromJson(jsonDecode(raw)['ocs']);
return GetParticipantsResponse.fromJson(jsonDecode(raw)['ocs']);
}
@override @override
Future<http.Response> request(Uri uri, Object? body, Map<String, String>? headers) { Future<http.Response> request(Uri uri, Object? body, Map<String, String>? headers) => http.get(uri, headers: headers);
return http.get(uri, headers: headers);
}
} }

View File

@ -12,15 +12,11 @@ class GetParticipantsCache extends RequestCache<GetParticipantsResponse> {
} }
@override @override
Future<GetParticipantsResponse> onLoad() { Future<GetParticipantsResponse> onLoad() => GetParticipants(
return GetParticipants(
chatToken, chatToken,
).run(); ).run();
}
@override @override
GetParticipantsResponse onLocalData(String json) { GetParticipantsResponse onLocalData(String json) => GetParticipantsResponse.fromJson(jsonDecode(json));
return GetParticipantsResponse.fromJson(jsonDecode(json));
}
} }

View File

@ -13,13 +13,9 @@ class GetReactions extends TalkApi<GetReactionsResponse> {
GetReactions({required this.chatToken, required this.messageId}) : super('v1/reaction/$chatToken/$messageId', null); GetReactions({required this.chatToken, required this.messageId}) : super('v1/reaction/$chatToken/$messageId', null);
@override @override
assemble(String raw) { assemble(String raw) => GetReactionsResponse.fromJson(jsonDecode(raw)['ocs']);
return GetReactionsResponse.fromJson(jsonDecode(raw)['ocs']);
}
@override @override
Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) { Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) => http.get(uri, headers: headers);
return http.get(uri, headers: headers);
}
} }

View File

@ -9,12 +9,8 @@ class LeaveRoom extends TalkApi {
LeaveRoom(this.chatToken) : super('v4/room/$chatToken/participants/self', null); LeaveRoom(this.chatToken) : super('v4/room/$chatToken/participants/self', null);
@override @override
assemble(String raw) { assemble(String raw) => null;
return null;
}
@override @override
Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) { Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) => http.delete(uri, headers: headers);
return http.delete(uri, headers: headers);
}
} }

View File

@ -11,9 +11,7 @@ class ReactMessage extends TalkApi {
ReactMessage({required this.chatToken, required this.messageId, required ReactMessageParams params}) : super('v1/reaction/$chatToken/$messageId', params); ReactMessage({required this.chatToken, required this.messageId, required ReactMessageParams params}) : super('v1/reaction/$chatToken/$messageId', params);
@override @override
assemble(String raw) { assemble(String raw) => null;
return null;
}
@override @override
Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) { Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) {

View File

@ -14,13 +14,9 @@ class GetRoom extends TalkApi<GetRoomResponse> {
@override @override
GetRoomResponse assemble(String raw) { GetRoomResponse assemble(String raw) => GetRoomResponse.fromJson(jsonDecode(raw)['ocs']);
return GetRoomResponse.fromJson(jsonDecode(raw)['ocs']);
}
@override @override
Future<http.Response> request(Uri uri, Object? body, Map<String, String>? headers) { Future<http.Response> request(Uri uri, Object? body, Map<String, String>? headers) => http.get(uri, headers: headers);
return http.get(uri, headers: headers);
}
} }

View File

@ -12,16 +12,12 @@ class GetRoomCache extends RequestCache<GetRoomResponse> {
} }
@override @override
GetRoomResponse onLocalData(String json) { GetRoomResponse onLocalData(String json) => GetRoomResponse.fromJson(jsonDecode(json));
return GetRoomResponse.fromJson(jsonDecode(json));
}
@override @override
Future<GetRoomResponse> onLoad() { Future<GetRoomResponse> onLoad() => GetRoom(
return GetRoom(
GetRoomParams( GetRoomParams(
includeStatus: true, includeStatus: true,
) )
).run(); ).run();
}
} }

View File

@ -10,9 +10,7 @@ class SendMessage extends TalkApi {
SendMessage(this.chatToken, SendMessageParams params) : super('v1/chat/$chatToken', params); SendMessage(this.chatToken, SendMessageParams params) : super('v1/chat/$chatToken', params);
@override @override
assemble(String raw) { assemble(String raw) => null;
return null;
}
@override @override
Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) { Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) {

View File

@ -11,9 +11,7 @@ class SetFavorite extends TalkApi {
SetFavorite(this.chatToken, this.favoriteState) : super('v4/room/$chatToken/favorite', null); SetFavorite(this.chatToken, this.favoriteState) : super('v4/room/$chatToken/favorite', null);
@override @override
assemble(String raw) { assemble(String raw) => null;
return null;
}
@override @override
Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) { Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) {

View File

@ -15,9 +15,7 @@ class SetReadMarker extends TalkApi {
} }
@override @override
assemble(String raw) { assemble(String raw) => null;
return null;
}
@override @override
Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) { Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) {

View File

@ -34,7 +34,7 @@ abstract class TalkApi<T extends ApiResponse?> extends ApiRequest {
getParameters?.update(key, (value) => value.toString()); getParameters?.update(key, (value) => value.toString());
}); });
Uri endpoint = Uri.https('${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().domain}', '${EndpointData().nextcloud().path}/ocs/v2.php/apps/spreed/api/$path', getParameters); var endpoint = Uri.https('${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().domain}', '${EndpointData().nextcloud().path}/ocs/v2.php/apps/spreed/api/$path', getParameters);
headers ??= {}; headers ??= {};
headers?.putIfAbsent('Accept', () => 'application/json'); headers?.putIfAbsent('Accept', () => 'application/json');

View File

@ -6,7 +6,5 @@ class TalkError {
TalkError(this.status, this.code, this.message); TalkError(this.status, this.code, this.message);
@override @override
String toString() { String toString() => 'Talk - $status - ($code): $message';
return 'Talk - $status - ($code): $message';
}
} }

View File

@ -13,8 +13,8 @@ class ListFiles extends WebdavApi<ListFilesParams> {
@override @override
Future<ListFilesResponse> run() async { Future<ListFilesResponse> run() async {
List<WebDavFile> davFiles = (await (await WebdavApi.webdav).propfind(PathUri.parse(params.path))).toWebDavFiles(); var davFiles = (await (await WebdavApi.webdav).propfind(PathUri.parse(params.path))).toWebDavFiles();
Set<CacheableFile> files = davFiles.map(CacheableFile.fromDavFile).toSet(); var files = davFiles.map(CacheableFile.fromDavFile).toSet();
// webdav handles subdirectories wrong, this is a fix // webdav handles subdirectories wrong, this is a fix
// currently this fix is not needed anymore // currently this fix is not needed anymore

View File

@ -11,19 +11,17 @@ class ListFilesCache extends RequestCache<ListFilesResponse> {
ListFilesCache({required onUpdate, required this.path}) : super(RequestCache.cacheNothing, onUpdate) { ListFilesCache({required onUpdate, required this.path}) : super(RequestCache.cacheNothing, onUpdate) {
var bytes = utf8.encode('MarianumMobile-$path'); var bytes = utf8.encode('MarianumMobile-$path');
String cacheName = md5.convert(bytes).toString(); var cacheName = md5.convert(bytes).toString();
start('MarianumMobile', 'wd-folder-$cacheName'); start('MarianumMobile', 'wd-folder-$cacheName');
} }
@override @override
Future<ListFilesResponse> onLoad() async { Future<ListFilesResponse> onLoad() async {
ListFilesResponse data = await ListFiles(ListFilesParams(path)).run(); var data = await ListFiles(ListFilesParams(path)).run();
return data; return data;
} }
@override @override
ListFilesResponse onLocalData(String json) { ListFilesResponse onLocalData(String json) => ListFilesResponse.fromJson(jsonDecode(json));
return ListFilesResponse.fromJson(jsonDecode(json));
}
} }

View File

@ -17,11 +17,7 @@ abstract class WebdavApi<T> extends ApiRequest {
static Future<WebDavClient> webdav = establishWebdavConnection(); static Future<WebDavClient> webdav = establishWebdavConnection();
static Future<String> webdavConnectString = buildWebdavConnectString(); static Future<String> webdavConnectString = buildWebdavConnectString();
static Future<WebDavClient> establishWebdavConnection() async { static Future<WebDavClient> establishWebdavConnection() async => NextcloudClient(Uri.parse('https://${EndpointData().nextcloud().full()}'), password: AccountData().getPassword(), loginName: AccountData().getUsername()).webdav;
return NextcloudClient(Uri.parse('https://${EndpointData().nextcloud().full()}'), password: AccountData().getPassword(), loginName: AccountData().getUsername()).webdav;
}
static Future<String> buildWebdavConnectString() async { static Future<String> buildWebdavConnectString() async => 'https://${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().full()}/remote.php/dav/files/${AccountData().getUsername()}/';
return 'https://${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().full()}/remote.php/dav/files/${AccountData().getUsername()}/';
}
} }

View File

@ -9,13 +9,9 @@ class GetBreakers extends MhslApi<GetBreakersResponse> {
GetBreakers() : super('breaker/'); GetBreakers() : super('breaker/');
@override @override
GetBreakersResponse assemble(String raw) { GetBreakersResponse assemble(String raw) => GetBreakersResponse.fromJson(jsonDecode(raw));
return GetBreakersResponse.fromJson(jsonDecode(raw));
}
@override @override
Future<Response>? request(Uri uri) { Future<Response>? request(Uri uri) => http.get(uri);
return http.get(uri);
}
} }

View File

@ -10,12 +10,8 @@ class GetBreakersCache extends RequestCache<GetBreakersResponse> {
} }
@override @override
GetBreakersResponse onLocalData(String json) { GetBreakersResponse onLocalData(String json) => GetBreakersResponse.fromJson(jsonDecode(json));
return GetBreakersResponse.fromJson(jsonDecode(json));
}
@override @override
Future<GetBreakersResponse> onLoad() { Future<GetBreakersResponse> onLoad() => GetBreakers().run();
return GetBreakers().run();
}
} }

View File

@ -16,7 +16,7 @@ class AddCustomTimetableEvent extends MhslApi<void> {
@override @override
Future<Response>? request(Uri uri) { Future<Response>? request(Uri uri) {
String body = jsonEncode(params.toJson()); var body = jsonEncode(params.toJson());
return http.post(uri, body: body); return http.post(uri, body: body);
} }
} }

View File

@ -12,12 +12,8 @@ class GetCustomTimetableEvent extends MhslApi<GetCustomTimetableEventResponse> {
GetCustomTimetableEvent(this.params) : super('server/timetable/customEvents?user=${params.user}'); GetCustomTimetableEvent(this.params) : super('server/timetable/customEvents?user=${params.user}');
@override @override
GetCustomTimetableEventResponse assemble(String raw) { GetCustomTimetableEventResponse assemble(String raw) => GetCustomTimetableEventResponse.fromJson({'events': jsonDecode(raw)});
return GetCustomTimetableEventResponse.fromJson({'events': jsonDecode(raw)});
}
@override @override
Future<Response>? request(Uri uri) { Future<Response>? request(Uri uri) => http.get(uri);
return http.get(uri);
}
} }

View File

@ -13,12 +13,8 @@ class GetCustomTimetableEventCache extends RequestCache<GetCustomTimetableEventR
} }
@override @override
Future<GetCustomTimetableEventResponse> onLoad() { Future<GetCustomTimetableEventResponse> onLoad() => GetCustomTimetableEvent(params).run();
return GetCustomTimetableEvent(params).run();
}
@override @override
GetCustomTimetableEventResponse onLocalData(String json) { GetCustomTimetableEventResponse onLocalData(String json) => GetCustomTimetableEventResponse.fromJson(jsonDecode(json));
return GetCustomTimetableEventResponse.fromJson(jsonDecode(json));
}
} }

View File

@ -15,7 +15,5 @@ class RemoveCustomTimetableEvent extends MhslApi<void> {
void assemble(String raw) {} void assemble(String raw) {}
@override @override
Future<Response>? request(Uri uri) { Future<Response>? request(Uri uri) => http.delete(uri, body: jsonEncode(params.toJson()));
return http.delete(uri, body: jsonEncode(params.toJson()));
}
} }

View File

@ -15,7 +15,5 @@ class UpdateCustomTimetableEvent extends MhslApi<void> {
void assemble(String raw) {} void assemble(String raw) {}
@override @override
Future<Response>? request(Uri uri) { Future<Response>? request(Uri uri) => http.patch(uri, body: jsonEncode(params.toJson()));
return http.patch(uri, body: jsonEncode(params.toJson()));
}
} }

View File

@ -10,12 +10,8 @@ class GetMessages extends MhslApi<GetMessagesResponse> {
@override @override
GetMessagesResponse assemble(String raw) { GetMessagesResponse assemble(String raw) => GetMessagesResponse.fromJson(jsonDecode(raw));
return GetMessagesResponse.fromJson(jsonDecode(raw));
}
@override @override
Future<http.Response> request(Uri uri) { Future<http.Response> request(Uri uri) => http.get(uri);
return http.get(uri);
}
} }

View File

@ -10,12 +10,8 @@ class GetMessagesCache extends RequestCache<GetMessagesResponse> {
} }
@override @override
GetMessagesResponse onLocalData(String json) { GetMessagesResponse onLocalData(String json) => GetMessagesResponse.fromJson(jsonDecode(json));
return GetMessagesResponse.fromJson(jsonDecode(json));
}
@override @override
Future<GetMessagesResponse> onLoad() { Future<GetMessagesResponse> onLoad() => GetMessages().run();
return GetMessages().run();
}
} }

View File

@ -15,9 +15,9 @@ abstract class MhslApi<T> extends ApiRequest {
T assemble(String raw); T assemble(String raw);
Future<T> run() async { Future<T> run() async {
Uri endpoint = Uri.parse('https://mhsl.eu/marianum/marianummobile/$subpath'); var endpoint = Uri.parse('https://mhsl.eu/marianum/marianummobile/$subpath');
http.Response? data = await request(endpoint); var data = await request(endpoint);
if(data == null) { if(data == null) {
throw ApiError('Request could not be dispatched!'); throw ApiError('Request could not be dispatched!');
} }
@ -31,5 +31,4 @@ abstract class MhslApi<T> extends ApiRequest {
static String dateTimeToJson(DateTime time) => Jiffy.parseFromDateTime(time).format(pattern: 'yyyy-MM-dd HH:mm:ss'); static String dateTimeToJson(DateTime time) => Jiffy.parseFromDateTime(time).format(pattern: 'yyyy-MM-dd HH:mm:ss');
static DateTime dateTimeFromJson(String time) => DateTime.parse(time); static DateTime dateTimeFromJson(String time) => DateTime.parse(time);
} }

View File

@ -19,7 +19,7 @@ class NotifyRegister extends MhslApi<void> {
@override @override
Future<http.Response> request(Uri uri) { Future<http.Response> request(Uri uri) {
String requestString = jsonEncode(params.toJson()); var requestString = jsonEncode(params.toJson());
log(requestString); log(requestString);
return http.post(uri, body: requestString); return http.post(uri, body: requestString);
} }

View File

@ -15,7 +15,5 @@ class AddFeedback extends MhslApi<void> {
void assemble(String raw) {} void assemble(String raw) {}
@override @override
Future<Response>? request(Uri uri) { Future<Response>? request(Uri uri) => http.post(uri, body: jsonEncode(params.toJson()));
return http.post(uri, body: jsonEncode(params.toJson()));
}
} }

View File

@ -19,12 +19,12 @@ class UpdateUserIndex extends MhslApi<void> {
@override @override
Future<http.Response> request(Uri uri) { Future<http.Response> request(Uri uri) {
String data = jsonEncode(params.toJson()); var data = jsonEncode(params.toJson());
log('Updating userindex:\n $data'); log('Updating userindex:\n $data');
return http.post(uri, body: data); return http.post(uri, body: data);
} }
static void index() async { static Future<void> index() async {
UpdateUserIndex( UpdateUserIndex(
UpdateUserIndexParams( UpdateUserIndexParams(
username: AccountData().getUsername(), username: AccountData().getUsername(),

View File

@ -20,8 +20,8 @@ abstract class RequestCache<T extends ApiResponse?> {
static void ignore(Exception e) {} static void ignore(Exception e) {}
void start(String file, String document) async { Future<void> start(String file, String document) async {
Map<String, dynamic>? tableData = await Localstore.instance.collection(file).doc(document).get(); var tableData = await Localstore.instance.collection(file).doc(document).get();
if(tableData != null) { if(tableData != null) {
onUpdate(onLocalData(tableData['json'])); onUpdate(onLocalData(tableData['json']));
} }
@ -31,7 +31,7 @@ abstract class RequestCache<T extends ApiResponse?> {
} }
try { try {
T newValue = await onLoad(); var newValue = await onLoad();
onUpdate(newValue); onUpdate(newValue);
Localstore.instance.collection(file).doc(document).set({ Localstore.instance.collection(file).doc(document).set({

View File

@ -14,7 +14,7 @@ class Authenticate extends WebuntisApi {
@override @override
Future<AuthenticateResponse> run() async { Future<AuthenticateResponse> run() async {
awaitingResponse = true; awaitingResponse = true;
String rawAnswer = await query(this); var rawAnswer = await query(this);
AuthenticateResponse response = finalize(AuthenticateResponse.fromJson(jsonDecode(rawAnswer)['result'])); AuthenticateResponse response = finalize(AuthenticateResponse.fromJson(jsonDecode(rawAnswer)['result']));
_lastResponse = response; _lastResponse = response;
if(!awaitedResponse.isCompleted) awaitedResponse.complete(); if(!awaitedResponse.isCompleted) awaitedResponse.complete();

View File

@ -8,7 +8,7 @@ class GetHolidays extends WebuntisApi {
@override @override
Future<GetHolidaysResponse> run() async { Future<GetHolidaysResponse> run() async {
String rawAnswer = await query(this); var rawAnswer = await query(this);
return finalize(GetHolidaysResponse.fromJson(jsonDecode(rawAnswer))); return finalize(GetHolidaysResponse.fromJson(jsonDecode(rawAnswer)));
} }
@ -17,8 +17,8 @@ class GetHolidays extends WebuntisApi {
time = DateTime(time.year, time.month, time.day, 0, 0, 0, 0, 0); time = DateTime(time.year, time.month, time.day, 0, 0, 0, 0, 0);
for (var element in holidaysResponse.result) { for (var element in holidaysResponse.result) {
DateTime start = DateTime.parse(element.startDate.toString()); var start = DateTime.parse(element.startDate.toString());
DateTime end = DateTime.parse(element.endDate.toString()); var end = DateTime.parse(element.endDate.toString());
if(!start.isAfter(time) && !end.isBefore(time)) return element; if(!start.isAfter(time) && !end.isBefore(time)) return element;
} }

View File

@ -10,12 +10,8 @@ class GetHolidaysCache extends RequestCache<GetHolidaysResponse> {
} }
@override @override
Future<GetHolidaysResponse> onLoad() { Future<GetHolidaysResponse> onLoad() => GetHolidays().run();
return GetHolidays().run();
}
@override @override
GetHolidaysResponse onLocalData(String json) { GetHolidaysResponse onLocalData(String json) => GetHolidaysResponse.fromJson(jsonDecode(json));
return GetHolidaysResponse.fromJson(jsonDecode(json));
}
} }

View File

@ -9,7 +9,7 @@ class GetRooms extends WebuntisApi {
@override @override
Future<GetRoomsResponse> run() async { Future<GetRoomsResponse> run() async {
String rawAnswer = await query(this); var rawAnswer = await query(this);
try { try {
return finalize(GetRoomsResponse.fromJson(jsonDecode(rawAnswer))); return finalize(GetRoomsResponse.fromJson(jsonDecode(rawAnswer)));
} catch(e, trace) { } catch(e, trace) {

View File

@ -10,13 +10,9 @@ class GetRoomsCache extends RequestCache<GetRoomsResponse> {
} }
@override @override
Future<GetRoomsResponse> onLoad() { Future<GetRoomsResponse> onLoad() => GetRooms().run();
return GetRooms().run();
}
@override @override
GetRoomsResponse onLocalData(String json) { GetRoomsResponse onLocalData(String json) => GetRoomsResponse.fromJson(jsonDecode(json));
return GetRoomsResponse.fromJson(jsonDecode(json));
}
} }

View File

@ -8,7 +8,7 @@ class GetSubjects extends WebuntisApi {
@override @override
Future<GetSubjectsResponse> run() async { Future<GetSubjectsResponse> run() async {
String rawAnswer = await query(this); var rawAnswer = await query(this);
return finalize(GetSubjectsResponse.fromJson(jsonDecode(rawAnswer))); return finalize(GetSubjectsResponse.fromJson(jsonDecode(rawAnswer)));
} }
} }

View File

@ -10,13 +10,9 @@ class GetSubjectsCache extends RequestCache<GetSubjectsResponse> {
} }
@override @override
Future<GetSubjectsResponse> onLoad() { Future<GetSubjectsResponse> onLoad() => GetSubjects().run();
return GetSubjects().run();
}
@override @override
onLocalData(String json) { onLocalData(String json) => GetSubjectsResponse.fromJson(jsonDecode(json));
return GetSubjectsResponse.fromJson(jsonDecode(json));
}
} }

View File

@ -11,7 +11,7 @@ class GetTimetable extends WebuntisApi {
@override @override
Future<GetTimetableResponse> run() async { Future<GetTimetableResponse> run() async {
String rawAnswer = await query(this); var rawAnswer = await query(this);
return finalize(GetTimetableResponse.fromJson(jsonDecode(rawAnswer))); return finalize(GetTimetableResponse.fromJson(jsonDecode(rawAnswer)));
} }

View File

@ -15,13 +15,10 @@ class GetTimetableCache extends RequestCache<GetTimetableResponse> {
} }
@override @override
GetTimetableResponse onLocalData(String json) { GetTimetableResponse onLocalData(String json) => GetTimetableResponse.fromJson(jsonDecode(json));
return GetTimetableResponse.fromJson(jsonDecode(json));
}
@override @override
Future<GetTimetableResponse> onLoad() async { Future<GetTimetableResponse> onLoad() async => GetTimetable(
return GetTimetable(
GetTimetableParams( GetTimetableParams(
options: GetTimetableParamsOptions( options: GetTimetableParamsOptions(
element: GetTimetableParamsOptionsElement( element: GetTimetableParamsOptionsElement(
@ -38,5 +35,4 @@ class GetTimetableCache extends RequestCache<GetTimetableResponse> {
) )
) )
).run(); ).run();
}
} }

View File

@ -20,13 +20,13 @@ abstract class WebuntisApi extends ApiRequest {
Future<String> query(WebuntisApi untis) async { Future<String> query(WebuntisApi untis) async {
String query = '{"id":"ID","method":"$method","params":${untis._body()},"jsonrpc":"2.0"}'; var query = '{"id":"ID","method":"$method","params":${untis._body()},"jsonrpc":"2.0"}';
String sessionId = '0'; var sessionId = '0';
if(authenticatedResponse) { if(authenticatedResponse) {
sessionId = (await Authenticate.getSession()).sessionId; sessionId = (await Authenticate.getSession()).sessionId;
} }
http.Response data = await post(query, {'Cookie': 'JSESSIONID=$sessionId'}); var data = await post(query, {'Cookie': 'JSESSIONID=$sessionId'});
response = data; response = data;
dynamic jsonData = jsonDecode(data.body); dynamic jsonData = jsonDecode(data.body);
@ -48,16 +48,12 @@ abstract class WebuntisApi extends ApiRequest {
Future<ApiResponse> run(); Future<ApiResponse> run();
String _body() { String _body() => genericParam == null ? '{}' : jsonEncode(genericParam);
return genericParam == null ? '{}' : jsonEncode(genericParam);
}
Future<http.Response> post(String data, Map<String, String>? headers) async { Future<http.Response> post(String data, Map<String, String>? headers) async => await http
return await http
.post(endpoint, body: data, headers: headers) .post(endpoint, body: data, headers: headers)
.timeout( .timeout(
const Duration(seconds: 10), const Duration(seconds: 10),
onTimeout: () => throw WebuntisError('Timeout', 1) onTimeout: () => throw WebuntisError('Timeout', 1)
); );
}
} }

View File

@ -5,7 +5,5 @@ class WebuntisError implements Exception {
WebuntisError(this.message, this.code); WebuntisError(this.message, this.code);
@override @override
String toString() { String toString() => 'WebUntis ($code): $message';
return 'WebUntis ($code): $message';
}
} }

View File

@ -94,8 +94,7 @@ class _AppState extends State<App> with WidgetsBindingObserver {
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => PersistentTabView(
return PersistentTabView(
controller: App.bottomNavigator, controller: App.bottomNavigator,
navBarOverlap: const NavBarOverlap.none(), navBarOverlap: const NavBarOverlap.none(),
backgroundColor: Theme.of(context).colorScheme.primary, backgroundColor: Theme.of(context).colorScheme.primary,
@ -119,7 +118,7 @@ class _AppState extends State<App> with WidgetsBindingObserver {
icon: Consumer<ChatListProps>( icon: Consumer<ChatListProps>(
builder: (context, value, child) { builder: (context, value, child) {
if(value.primaryLoading()) return const Icon(Icons.chat); if(value.primaryLoading()) return const Icon(Icons.chat);
int messages = value.getRoomsResponse.data.map((e) => e.unreadMessages).reduce((a, b) => a+b); var messages = value.getRoomsResponse.data.map((e) => e.unreadMessages).reduce((a, b) => a+b);
return badges.Badge( return badges.Badge(
showBadge: messages > 0, showBadge: messages > 0,
position: badges.BadgePosition.topEnd(top: -3, end: -3), position: badges.BadgePosition.topEnd(top: -3, end: -3),
@ -164,7 +163,6 @@ class _AppState extends State<App> with WidgetsBindingObserver {
), ),
), ),
); );
}
@override @override
void dispose() { void dispose() {

View File

@ -1,30 +1,20 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
extension IsSameDay on DateTime { extension IsSameDay on DateTime {
bool isSameDay(DateTime other) { bool isSameDay(DateTime other) => year == other.year && month == other.month && day == other.day;
return year == other.year && month == other.month && day == other.day;
}
DateTime nextWeekday(int day) { DateTime nextWeekday(int day) => add(Duration(days: (day - weekday) % DateTime.daysPerWeek));
return add(Duration(days: (day - weekday) % DateTime.daysPerWeek));
}
DateTime withTime(TimeOfDay time) { DateTime withTime(TimeOfDay time) => copyWith(hour: time.hour, minute: time.minute);
return copyWith(hour: time.hour, minute: time.minute);
}
TimeOfDay toTimeOfDay() { TimeOfDay toTimeOfDay() => TimeOfDay(hour: hour, minute: minute);
return TimeOfDay(hour: hour, minute: minute);
}
bool isSameDateTime(DateTime other) { bool isSameDateTime(DateTime other) {
bool isSameDay = this.isSameDay(other); var isSameDay = this.isSameDay(other);
bool isSameTimeOfDay = (toTimeOfDay() == other.toTimeOfDay()); var isSameTimeOfDay = (toTimeOfDay() == other.toTimeOfDay());
return isSameDay && isSameTimeOfDay; return isSameDay && isSameTimeOfDay;
} }
bool isSameOrAfter(DateTime other) { bool isSameOrAfter(DateTime other) => isSameDateTime(other) || isAfter(other);
return isSameDateTime(other) || isAfter(other);
}
} }

View File

@ -1,5 +1,3 @@
extension RenderNotNullExt<T> on T? { extension RenderNotNullExt<T> on T? {
R? wrapNullable<R>(R Function(T data) defaultValueCallback) { R? wrapNullable<R>(R Function(T data) defaultValueCallback) => this != null ? defaultValueCallback(this as T) : null;
return this != null ? defaultValueCallback(this as T) : null;
}
} }

View File

@ -2,7 +2,7 @@ import 'package:flutter/material.dart';
extension TextExt on Text { extension TextExt on Text {
Size get size { Size get size {
final TextPainter textPainter = TextPainter( final textPainter = TextPainter(
text: TextSpan(text: data, style: style), text: TextSpan(text: data, style: style),
maxLines: 1, maxLines: 1,
textDirection: TextDirection.ltr textDirection: TextDirection.ltr

View File

@ -1,15 +1,9 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
extension TimeOfDayExt on TimeOfDay { extension TimeOfDayExt on TimeOfDay {
bool isBefore(TimeOfDay other) { bool isBefore(TimeOfDay other) => hour < other.hour && minute < other.minute;
return hour < other.hour && minute < other.minute;
}
bool isAfter(TimeOfDay other) { bool isAfter(TimeOfDay other) => hour > other.hour && minute > other.minute;
return hour > other.hour && minute > other.minute;
}
TimeOfDay add({int hours = 0, int minutes = 0}) { TimeOfDay add({int hours = 0, int minutes = 0}) => replacing(hour: hour + hours, minute: minute + minutes);
return replacing(hour: hour + hours, minute: minute + minutes);
}
} }

View File

@ -41,16 +41,14 @@ Future<void> main() async {
log('Error initializing Firebase app!'); log('Error initializing Firebase app!');
} }
ByteData data = await PlatformAssetBundle().load('assets/ca/lets-encrypt-r3.pem'); var data = await PlatformAssetBundle().load('assets/ca/lets-encrypt-r3.pem');
SecurityContext.defaultContext.setTrustedCertificatesBytes(data.buffer.asUint8List()); SecurityContext.defaultContext.setTrustedCertificatesBytes(data.buffer.asUint8List());
if(kReleaseMode) { if(kReleaseMode) {
ErrorWidget.builder = (error) { ErrorWidget.builder = (error) => PlaceholderView(
return PlaceholderView(
icon: Icons.phonelink_erase_rounded, icon: Icons.phonelink_erase_rounded,
text: error.toStringShort(), text: error.toStringShort(),
); );
};
} }
runApp( runApp(
@ -101,8 +99,7 @@ class _MainState extends State<Main> {
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => Directionality(
return Directionality(
textDirection: TextDirection.ltr, textDirection: TextDirection.ltr,
child: Consumer<SettingsProvider>( child: Consumer<SettingsProvider>(
builder: (context, settings, child) { builder: (context, settings, child) {
@ -146,7 +143,6 @@ class _MainState extends State<Main> {
}, },
), ),
); );
}
@override @override
void dispose() { void dispose() {

View File

@ -17,9 +17,7 @@ class AccountData {
final Future<SharedPreferences> _storage = SharedPreferences.getInstance(); final Future<SharedPreferences> _storage = SharedPreferences.getInstance();
Completer<void> _populated = Completer(); Completer<void> _populated = Completer();
factory AccountData() { factory AccountData() => _instance;
return _instance;
}
AccountData._construct() { AccountData._construct() {
_updateFromStorage(); _updateFromStorage();
@ -38,16 +36,12 @@ class AccountData {
return _password!; return _password!;
} }
String getUserSecret() { String getUserSecret() => sha512.convert(utf8.encode('${AccountData().getUsername()}:${AccountData().getPassword()}')).toString();
return sha512.convert(utf8.encode('${AccountData().getUsername()}:${AccountData().getPassword()}')).toString();
}
Future<String> getDeviceId() async { Future<String> getDeviceId() async => sha512.convert(utf8.encode('${getUserSecret()}@${await FirebaseMessaging.instance.getToken()}')).toString();
return sha512.convert(utf8.encode('${getUserSecret()}@${await FirebaseMessaging.instance.getToken()}')).toString();
}
Future<void> setData(String username, String password) async { Future<void> setData(String username, String password) async {
SharedPreferences storage = await _storage; var storage = await _storage;
storage.setString(_usernameField, username); storage.setString(_usernameField, username);
storage.setString(_passwordField, password); storage.setString(_passwordField, password);
@ -59,13 +53,13 @@ class AccountData {
if(context != null) Provider.of<AccountModel>(context, listen: false).setState(AccountModelState.loggedOut); if(context != null) Provider.of<AccountModel>(context, listen: false).setState(AccountModelState.loggedOut);
SharedPreferences storage = await _storage; var storage = await _storage;
await storage.remove(_usernameField); await storage.remove(_usernameField);
await storage.remove(_passwordField); await storage.remove(_passwordField);
} }
Future<void> _updateFromStorage() async { Future<void> _updateFromStorage() async {
SharedPreferences storage = await _storage; var storage = await _storage;
//await storage.reload(); // This line was the cause of the first rejected google play upload :( //await storage.reload(); // This line was the cause of the first rejected google play upload :(
if(storage.containsKey(_usernameField) && storage.containsKey(_passwordField)) { if(storage.containsKey(_usernameField) && storage.containsKey(_passwordField)) {
_username = storage.getString(_usernameField); _username = storage.getString(_usernameField);
@ -79,9 +73,7 @@ class AccountData {
return isPopulated(); return isPopulated();
} }
bool isPopulated() { bool isPopulated() => _username != null && _password != null;
return _username != null && _password != null;
}
String buildHttpAuthString() { String buildHttpAuthString() {
if(!isPopulated()) throw Exception('AccountData (e.g. username or password) is not initialized!'); if(!isPopulated()) throw Exception('AccountData (e.g. username or password) is not initialized!');

View File

@ -19,10 +19,9 @@ class Breaker extends StatefulWidget {
class _BreakerState extends State<Breaker> { class _BreakerState extends State<Breaker> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => Consumer<BreakerProps>(
return Consumer<BreakerProps>(
builder: (context, value, child) { builder: (context, value, child) {
String? blocked = value.isBlocked(widget.breaker); var blocked = value.isBlocked(widget.breaker);
if(blocked != null) { if(blocked != null) {
return PlaceholderView(icon: Icons.security_outlined, text: "Die App/ Dieser Bereich wurde als Schutzmaßnahme deaktiviert!\n\n${blocked.isEmpty ? "Es wurde vom Server kein Grund übermittelt." : blocked}"); return PlaceholderView(icon: Icons.security_outlined, text: "Die App/ Dieser Bereich wurde als Schutzmaßnahme deaktiviert!\n\n${blocked.isEmpty ? "Es wurde vom Server kein Grund übermittelt." : blocked}");
} }
@ -30,5 +29,4 @@ class _BreakerState extends State<Breaker> {
return widget.child; return widget.child;
}, },
); );
}
} }

View File

@ -18,13 +18,13 @@ class BreakerProps extends DataHolder {
} }
if(primaryLoading()) return null; if(primaryLoading()) return null;
GetBreakersResponse breakers = _getBreakersResponse!; var breakers = _getBreakersResponse!;
if(breakers.global.areas.contains(type)) return breakers.global.message; if(breakers.global.areas.contains(type)) return breakers.global.message;
int selfVersion = int.parse(packageInfo!.buildNumber); var selfVersion = int.parse(packageInfo!.buildNumber);
for(var key in breakers.regional.keys) { for(var key in breakers.regional.keys) {
GetBreakersReponseObject value = breakers.regional[key]!; var value = breakers.regional[key]!;
if(int.parse(key.split('b')[1]) >= selfVersion) { if(int.parse(key.split('b')[1]) >= selfVersion) {
if(value.areas.contains(type)) return value.message; if(value.areas.contains(type)) return value.message;
@ -35,9 +35,7 @@ class BreakerProps extends DataHolder {
} }
@override @override
List<ApiResponse?> properties() { List<ApiResponse?> properties() => [_getBreakersResponse];
return [_getBreakersResponse];
}
@override @override
void run() { void run() {

View File

@ -11,9 +11,7 @@ class ChatListProps extends DataHolder {
GetRoomResponse get getRoomsResponse => _getRoomResponse!; GetRoomResponse get getRoomsResponse => _getRoomResponse!;
@override @override
List<ApiResponse?> properties() { List<ApiResponse?> properties() => [_getRoomResponse];
return [_getRoomResponse];
}
@override @override
void run({renew}) { void run({renew}) {

View File

@ -11,15 +11,13 @@ class ChatProps extends DataHolder {
GetChatResponse get getChatResponse => _getChatResponse!; GetChatResponse get getChatResponse => _getChatResponse!;
@override @override
List<ApiResponse?> properties() { List<ApiResponse?> properties() => [_getChatResponse];
return [_getChatResponse];
}
@override @override
void run() { void run() {
notifyListeners(); notifyListeners();
if(_queryToken.isEmpty) return; if(_queryToken.isEmpty) return;
DateTime requestStart = DateTime.now(); var requestStart = DateTime.now();
GetChatCache( GetChatCache(
chatToken: _queryToken, chatToken: _queryToken,
@ -39,7 +37,5 @@ class ChatProps extends DataHolder {
run(); run();
} }
String currentToken() { String currentToken() => _queryToken;
return _queryToken;
}
} }

View File

@ -3,10 +3,10 @@ import 'package:localstore/localstore.dart';
import '../widget/debug/cacheView.dart'; import '../widget/debug/cacheView.dart';
class DataCleaner { class DataCleaner {
static void cleanOldCache() async { static Future<void> cleanOldCache() async {
var cacheData = await Localstore.instance.collection(CacheView.collection).get(); var cacheData = await Localstore.instance.collection(CacheView.collection).get();
cacheData?.forEach((key, value) async { cacheData?.forEach((key, value) async {
DateTime lastUpdate = DateTime.fromMillisecondsSinceEpoch(value['lastupdate']); var lastUpdate = DateTime.fromMillisecondsSinceEpoch(value['lastupdate']);
if(DateTime.now().subtract(const Duration(days: 200)).isAfter(lastUpdate)) { if(DateTime.now().subtract(const Duration(days: 200)).isAfter(lastUpdate)) {
await Localstore.instance.collection(CacheView.collection).doc(key.split('/').last).delete(); await Localstore.instance.collection(CacheView.collection).doc(key.split('/').last).delete();
} }

View File

@ -6,16 +6,14 @@ import '../api/apiResponse.dart';
abstract class DataHolder extends ChangeNotifier { abstract class DataHolder extends ChangeNotifier {
CollectionRef storage(String path) { CollectionRef storage(String path) => Localstore.instance.collection(path);
return Localstore.instance.collection(path);
}
void run(); void run();
List<ApiResponse?> properties(); List<ApiResponse?> properties();
bool primaryLoading() { bool primaryLoading() {
// log("${toString()} ${properties().map((e) => e != null ? "1" : "0").join(", ")}"); // log("${toString()} ${properties().map((e) => e != null ? "1" : "0").join(", ")}");
for(ApiResponse? element in properties()) { for(var element in properties()) {
if(element == null) return true; if(element == null) return true;
} }
return false; return false;

View File

@ -23,17 +23,13 @@ class Endpoint {
Endpoint({required this.domain, this.path = ''}); Endpoint({required this.domain, this.path = ''});
String full() { String full() => domain + path;
return domain + path;
}
} }
class EndpointData { class EndpointData {
static final EndpointData _instance = EndpointData._construct(); static final EndpointData _instance = EndpointData._construct();
factory EndpointData() { factory EndpointData() => _instance;
return _instance;
}
EndpointData._construct(); EndpointData._construct();
@ -43,8 +39,7 @@ class EndpointData {
return existingName.startsWith('google') ? EndpointMode.stage : EndpointMode.live; return existingName.startsWith('google') ? EndpointMode.stage : EndpointMode.live;
} }
Endpoint webuntis() { Endpoint webuntis() => EndpointOptions(
return EndpointOptions(
live: Endpoint( live: Endpoint(
domain: 'peleus.webuntis.com', domain: 'peleus.webuntis.com',
), ),
@ -53,10 +48,8 @@ class EndpointData {
path: '/marianum/marianummobile/webuntis/public/index.php/api' path: '/marianum/marianummobile/webuntis/public/index.php/api'
), ),
).get(getEndpointMode()); ).get(getEndpointMode());
}
Endpoint nextcloud() { Endpoint nextcloud() => EndpointOptions(
return EndpointOptions(
live: Endpoint( live: Endpoint(
domain: 'cloud.marianum-fulda.de', domain: 'cloud.marianum-fulda.de',
), ),
@ -65,6 +58,5 @@ class EndpointData {
path: '/marianum/marianummobile/cloud', path: '/marianum/marianummobile/cloud',
) )
).get(getEndpointMode()); ).get(getEndpointMode());
}
} }

View File

@ -23,9 +23,7 @@ class FilesProps extends DataHolder {
} }
@override @override
List<ApiResponse?> properties() { List<ApiResponse?> properties() => [_listFilesResponse];
return [_listFilesResponse];
}
@override @override
void run() { void run() {

View File

@ -10,9 +10,7 @@ class HolidaysProps extends DataHolder {
GetHolidaysResponse get getHolidaysResponse => _getHolidaysResponse!; GetHolidaysResponse get getHolidaysResponse => _getHolidaysResponse!;
@override @override
List<ApiResponse?> properties() { List<ApiResponse?> properties() => [_getHolidaysResponse];
return [_getHolidaysResponse];
}
@override @override
void run() { void run() {

View File

@ -9,9 +9,7 @@ class MessageProps extends DataHolder {
GetMessagesResponse get getMessagesResponse => _getMessagesResponse!; GetMessagesResponse get getMessagesResponse => _getMessagesResponse!;
@override @override
List<ApiResponse?> properties() { List<ApiResponse?> properties() => [_getMessagesResponse];
return [_getMessagesResponse];
}
@override @override
void run({renew}) { void run({renew}) {

View File

@ -42,9 +42,7 @@ class TimetableProps extends DataHolder {
bool get hasError => error != null; bool get hasError => error != null;
@override @override
List<ApiResponse?> properties() { List<ApiResponse?> properties() => [_getTimetableResponse, _getRoomsResponse, _getSubjectsResponse, _getHolidaysResponse, _getCustomTimetableEventResponse];
return [_getTimetableResponse, _getRoomsResponse, _getSubjectsResponse, _getHolidaysResponse, _getCustomTimetableEventResponse];
}
@override @override
void run({renew}) { void run({renew}) {
@ -101,9 +99,7 @@ class TimetableProps extends DataHolder {
DateTime getDate(DateTime d) => DateTime(d.year, d.month, d.day); DateTime getDate(DateTime d) => DateTime(d.year, d.month, d.day);
bool isWeekend(DateTime queryDate) { bool isWeekend(DateTime queryDate) => queryDate.weekday == DateTime.saturday || queryDate.weekday == DateTime.sunday;
return queryDate.weekday == DateTime.saturday || queryDate.weekday == DateTime.sunday;
}
void updateWeek(DateTime start, DateTime end) { void updateWeek(DateTime start, DateTime end) {
properties().forEach((element) => element = null); properties().forEach((element) => element = null);
@ -123,7 +119,7 @@ class TimetableProps extends DataHolder {
error = null; error = null;
notifyListeners(); notifyListeners();
DateTime queryWeek = DateTime.now().add(const Duration(days: 2)); var queryWeek = DateTime.now().add(const Duration(days: 2));
startDate = getDate(queryWeek.subtract(Duration(days: queryWeek.weekday - 1))); startDate = getDate(queryWeek.subtract(Duration(days: queryWeek.weekday - 1)));
endDate = getDate(queryWeek.add(Duration(days: DateTime.daysPerWeek - queryWeek.weekday))); endDate = getDate(queryWeek.add(Duration(days: DateTime.daysPerWeek - queryWeek.weekday)));

View File

@ -3,27 +3,25 @@ import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class NotificationService { class NotificationService {
static final NotificationService _instance = NotificationService._internal(); static final NotificationService _instance = NotificationService._internal();
factory NotificationService() { factory NotificationService() => _instance;
return _instance;
}
NotificationService._internal(); NotificationService._internal();
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
Future<void> initializeNotifications() async { Future<void> initializeNotifications() async {
const AndroidInitializationSettings androidSettings = AndroidInitializationSettings( const androidSettings = AndroidInitializationSettings(
'@mipmap/ic_launcher' '@mipmap/ic_launcher'
); );
final DarwinInitializationSettings iosSettings = DarwinInitializationSettings( final iosSettings = DarwinInitializationSettings(
onDidReceiveLocalNotification: (id, title, body, payload) { onDidReceiveLocalNotification: (id, title, body, payload) {
// TODO Navigate to Talk section (This runs when an Notification is tapped) // TODO Navigate to Talk section (This runs when an Notification is tapped)
}, },
); );
final InitializationSettings initializationSettings = InitializationSettings( final initializationSettings = InitializationSettings(
android: androidSettings, android: androidSettings,
iOS: iosSettings, iOS: iosSettings,
); );
@ -34,7 +32,7 @@ class NotificationService {
} }
Future<void> showNotification({required String title, required String body, required int badgeCount}) async { Future<void> showNotification({required String title, required String body, required int badgeCount}) async {
const AndroidNotificationDetails androidPlatformChannelSpecifics = const androidPlatformChannelSpecifics =
AndroidNotificationDetails( AndroidNotificationDetails(
'marmobile', 'marmobile',
'Marianum Fulda', 'Marianum Fulda',
@ -43,9 +41,9 @@ class NotificationService {
ticker: 'Marianum Fulda', ticker: 'Marianum Fulda',
); );
const DarwinNotificationDetails iosPlatformChannelSpecifics = DarwinNotificationDetails(); const iosPlatformChannelSpecifics = DarwinNotificationDetails();
const NotificationDetails platformChannelSpecifics = NotificationDetails( const platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics, android: androidPlatformChannelSpecifics,
iOS: iosPlatformChannelSpecifics iOS: iosPlatformChannelSpecifics
); );

View File

@ -8,8 +8,7 @@ import '../storage/base/settingsProvider.dart';
import '../widget/confirmDialog.dart'; import '../widget/confirmDialog.dart';
class NotifyUpdater { class NotifyUpdater {
static ConfirmDialog enableAfterDisclaimer(SettingsProvider settings) { static ConfirmDialog enableAfterDisclaimer(SettingsProvider settings) => ConfirmDialog(
return ConfirmDialog(
title: 'Warnung', title: 'Warnung',
icon: Icons.warning_amber, icon: Icons.warning_amber,
content: '' content: ''
@ -25,9 +24,8 @@ class NotifyUpdater {
NotifyUpdater.registerToServer(); NotifyUpdater.registerToServer();
}, },
); );
} static Future<void> registerToServer() async {
static void registerToServer() async { var fcmToken = await FirebaseMessaging.instance.getToken();
String? fcmToken = await FirebaseMessaging.instance.getToken();
if(fcmToken == null) throw Exception('Failed to register push notification because there is no FBC token!'); if(fcmToken == null) throw Exception('Failed to register push notification because there is no FBC token!');

View File

@ -29,7 +29,7 @@ class SettingsProvider extends ChangeNotifier {
_readFromStorage(); _readFromStorage();
} }
void reset() async { Future<void> reset() async {
_storage = await SharedPreferences.getInstance(); _storage = await SharedPreferences.getInstance();
_storage.remove(_fieldName); _storage.remove(_fieldName);
_settings = DefaultSettings.get(); _settings = DefaultSettings.get();
@ -38,7 +38,7 @@ class SettingsProvider extends ChangeNotifier {
notifyListeners(); notifyListeners();
} }
void _readFromStorage() async { Future<void> _readFromStorage() async {
_storage = await SharedPreferences.getInstance(); _storage = await SharedPreferences.getInstance();
try { try {
@ -63,7 +63,7 @@ class SettingsProvider extends ChangeNotifier {
} }
Map<String, dynamic> _mergeSettings(Map<String, dynamic> oldMap, Map<String, dynamic> newMap) { Map<String, dynamic> _mergeSettings(Map<String, dynamic> oldMap, Map<String, dynamic> newMap) {
Map<String, dynamic> mergedMap = Map.from(newMap); var mergedMap = Map<String, dynamic>.from(newMap);
oldMap.forEach((key, value) { oldMap.forEach((key, value) {
if (mergedMap.containsKey(key)) { if (mergedMap.containsKey(key)) {

View File

@ -15,9 +15,7 @@ class AppTheme {
} }
} }
static bool isDarkMode(BuildContext context) { static bool isDarkMode(BuildContext context) => Theme.of(context).brightness == Brightness.dark;
return Theme.of(context).brightness == Brightness.dark;
}
} }
class ThemeModeDisplay { class ThemeModeDisplay {

View File

@ -20,9 +20,7 @@ class Login extends StatefulWidget {
class _LoginState extends State<Login> { class _LoginState extends State<Login> {
bool displayDisclaimerText = true; bool displayDisclaimerText = true;
String? _checkInput(value){ String? _checkInput(value)=> (value ?? '').length == 0 ? 'Eingabe erforderlich' : null;
return (value ?? '').length == 0 ? 'Eingabe erforderlich' : null;
}
Future<String?> _login(LoginData data) async { Future<String?> _login(LoginData data) async {
await AccountData().removeData(); await AccountData().removeData();
@ -49,15 +47,10 @@ class _LoginState extends State<Login> {
return null; return null;
} }
Future<String> _resetPassword(String name) { Future<String> _resetPassword(String name) => Future.delayed(Duration.zero).then((_) => 'Diese Funktion steht nicht zur Verfügung!');
return Future.delayed(Duration.zero).then((_) {
return 'Diese Funktion steht nicht zur Verfügung!';
});
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => FlutterLogin(
return FlutterLogin(
logo: Image.asset('assets/logo/icon.png').image, logo: Image.asset('assets/logo/icon.png').image,
userValidator: _checkInput, userValidator: _checkInput,
@ -109,5 +102,4 @@ class _LoginState extends State<Login> {
userType: LoginUserType.name, userType: LoginUserType.name,
); );
}
} }

View File

@ -26,14 +26,14 @@ class FileElement extends StatefulWidget {
const FileElement(this.file, this.path, this.refetch, {super.key}); const FileElement(this.file, this.path, this.refetch, {super.key});
static Future<DownloaderCore> download(BuildContext context, String remotePath, String name, Function(double) onProgress, Function(OpenResult) onDone) async { static Future<DownloaderCore> download(BuildContext context, String remotePath, String name, Function(double) onProgress, Function(OpenResult) onDone) async {
Directory paths = await getTemporaryDirectory(); var paths = await getTemporaryDirectory();
var encodedPath = Uri.encodeComponent(remotePath); var encodedPath = Uri.encodeComponent(remotePath);
encodedPath = encodedPath.replaceAll('%2F', '/'); encodedPath = encodedPath.replaceAll('%2F', '/');
String local = paths.path + Platform.pathSeparator + name; var local = paths.path + Platform.pathSeparator + name;
DownloaderUtils options = DownloaderUtils( var options = DownloaderUtils(
progressCallback: (current, total) { progressCallback: (current, total) {
final progress = (current / total) * 100; final progress = (current / total) * 100;
onProgress(progress); onProgress(progress);
@ -52,7 +52,7 @@ class FileElement extends StatefulWidget {
); );
return await Flowder.download( return await Flowder.download(
"${await WebdavApi.webdavConnectString}$encodedPath", '${await WebdavApi.webdavConnectString}$encodedPath',
options, options,
); );
} }
@ -89,8 +89,7 @@ class _FileElementState extends State<FileElement> {
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => ListTile(
return ListTile(
leading: CenteredLeading( leading: CenteredLeading(
Icon(widget.file.isDirectory ? Icons.folder : Icons.description_outlined) Icon(widget.file.isDirectory ? Icons.folder : Icons.description_outlined)
), ),
@ -100,9 +99,7 @@ class _FileElementState extends State<FileElement> {
onTap: () { onTap: () {
if(widget.file.isDirectory) { if(widget.file.isDirectory) {
Navigator.of(context).push(MaterialPageRoute( Navigator.of(context).push(MaterialPageRoute(
builder: (context) { builder: (context) => Files(widget.path.toList()..add(widget.file.name)),
return Files(widget.path.toList()..add(widget.file.name));
},
)); ));
} else { } else {
if(EndpointData().getEndpointMode() == EndpointMode.stage) { if(EndpointData().getEndpointMode() == EndpointMode.stage) {
@ -141,12 +138,10 @@ class _FileElementState extends State<FileElement> {
setState(() => percent = progress); setState(() => percent = progress);
}, (result) { }, (result) {
if(result.type != ResultType.done) { if(result.type != ResultType.done) {
showDialog(context: context, builder: (context) { showDialog(context: context, builder: (context) => AlertDialog(
return AlertDialog(
title: const Text('Download'), title: const Text('Download'),
content: Text(result.message), content: Text(result.message),
); ));
});
} }
setState(() { setState(() {
@ -158,8 +153,7 @@ class _FileElementState extends State<FileElement> {
} }
}, },
onLongPress: () { onLongPress: () {
showDialog(context: context, builder: (context) { showDialog(context: context, builder: (context) => SimpleDialog(
return SimpleDialog(
children: [ children: [
ListTile( ListTile(
leading: const Icon(Icons.delete_outline), leading: const Icon(Icons.delete_outline),
@ -189,9 +183,7 @@ class _FileElementState extends State<FileElement> {
), ),
), ),
], ],
); ));
});
}, },
); );
}
} }

View File

@ -32,18 +32,18 @@ class _FileUploadDialogState extends State<FileUploadDialog> {
TextEditingController fileNameController = TextEditingController(); TextEditingController fileNameController = TextEditingController();
void upload({bool override = false}) async { Future<void> upload({bool override = false}) async {
setState(() { setState(() {
state = FileUploadState.upload; state = FileUploadState.upload;
}); });
WebDavClient webdavClient = await WebdavApi.webdav; var webdavClient = await WebdavApi.webdav;
if(!override) { if(!override) {
setState(() { setState(() {
state = FileUploadState.checkConflict; state = FileUploadState.checkConflict;
}); });
List<WebDavResponse> result = (await webdavClient.propfind(PathUri.parse(widget.remotePath.join('/')))).responses; var result = (await webdavClient.propfind(PathUri.parse(widget.remotePath.join('/')))).responses;
if(result.any((element) => element.href!.endsWith('/$targetFileName'))) { if(result.any((element) => element.href!.endsWith('/$targetFileName'))) {
setState(() { setState(() {
state = FileUploadState.conflict; state = FileUploadState.conflict;
@ -56,7 +56,7 @@ class _FileUploadDialogState extends State<FileUploadDialog> {
} }
} }
Future<HttpClientResponse> uploadTask = webdavClient.putFile(File(widget.localPath), FileStat.statSync(widget.localPath), PathUri.parse(fullRemotePath)); // TODO use onProgress from putFile var uploadTask = webdavClient.putFile(File(widget.localPath), FileStat.statSync(widget.localPath), PathUri.parse(fullRemotePath)); // TODO use onProgress from putFile
uploadTask.then(Future<HttpClientResponse?>.value).catchError((e) { uploadTask.then(Future<HttpClientResponse?>.value).catchError((e) {
setState(() { setState(() {
state = FileUploadState.error; state = FileUploadState.error;

View File

@ -64,9 +64,7 @@ class SortOptions {
) )
}; };
static BetterSortOption getOption(SortOption option) { static BetterSortOption getOption(SortOption option) => options[option]!;
return options[option]!;
}
} }
class _FilesState extends State<Files> { class _FilesState extends State<Files> {
@ -101,7 +99,7 @@ class _FilesState extends State<Files> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
List<CacheableFile> files = data?.sortBy( var files = data?.sortBy(
sortOption: currentSort, sortOption: currentSort,
foldersToTop: Provider.of<SettingsProvider>(context).val().fileSettings.sortFoldersToTop, foldersToTop: Provider.of<SettingsProvider>(context).val().fileSettings.sortFoldersToTop,
reversed: currentSortDirection reversed: currentSortDirection
@ -119,8 +117,7 @@ class _FilesState extends State<Files> {
// ), // ),
PopupMenuButton<bool>( PopupMenuButton<bool>(
icon: Icon(currentSortDirection ? Icons.text_rotate_up : Icons.text_rotation_down), icon: Icon(currentSortDirection ? Icons.text_rotate_up : Icons.text_rotation_down),
itemBuilder: (context) { itemBuilder: (context) => [true, false].map((e) => PopupMenuItem<bool>(
return [true, false].map((e) => PopupMenuItem<bool>(
value: e, value: e,
enabled: e != currentSortDirection, enabled: e != currentSortDirection,
child: Row( child: Row(
@ -130,8 +127,7 @@ class _FilesState extends State<Files> {
Text(e ? 'Aufsteigend' : 'Absteigend') Text(e ? 'Aufsteigend' : 'Absteigend')
], ],
) )
)).toList(); )).toList(),
},
onSelected: (e) { onSelected: (e) {
setState(() { setState(() {
currentSortDirection = e; currentSortDirection = e;
@ -141,8 +137,7 @@ class _FilesState extends State<Files> {
), ),
PopupMenuButton<SortOption>( PopupMenuButton<SortOption>(
icon: const Icon(Icons.sort), icon: const Icon(Icons.sort),
itemBuilder: (context) { itemBuilder: (context) => SortOptions.options.keys.map((key) => PopupMenuItem<SortOption>(
return SortOptions.options.keys.map((key) => PopupMenuItem<SortOption>(
value: key, value: key,
enabled: key != currentSort, enabled: key != currentSort,
child: Row( child: Row(
@ -152,8 +147,7 @@ class _FilesState extends State<Files> {
Text(SortOptions.getOption(key).displayName) Text(SortOptions.getOption(key).displayName)
], ],
) )
)).toList(); )).toList(),
},
onSelected: (e) { onSelected: (e) {
setState(() { setState(() {
currentSort = e; currentSort = e;
@ -167,8 +161,7 @@ class _FilesState extends State<Files> {
heroTag: 'uploadFile', heroTag: 'uploadFile',
backgroundColor: Theme.of(context).primaryColor, backgroundColor: Theme.of(context).primaryColor,
onPressed: () { onPressed: () {
showDialog(context: context, builder: (context) { showDialog(context: context, builder: (context) => SimpleDialog(
return SimpleDialog(
children: [ children: [
ListTile( ListTile(
leading: const Icon(Icons.create_new_folder_outlined), leading: const Icon(Icons.create_new_folder_outlined),
@ -224,8 +217,7 @@ class _FilesState extends State<Files> {
), ),
), ),
], ],
); ));
});
}, },
child: const Icon(Icons.add), child: const Icon(Icons.add),
), ),
@ -239,7 +231,7 @@ class _FilesState extends State<Files> {
padding: EdgeInsets.zero, padding: EdgeInsets.zero,
itemCount: files.length, itemCount: files.length,
itemBuilder: (context, index) { itemBuilder: (context, index) {
CacheableFile file = files.toList()[index]; var file = files.toList()[index];
return FileElement(file, widget.path, _query); return FileElement(file, widget.path, _query);
}, },
), ),
@ -248,7 +240,7 @@ class _FilesState extends State<Files> {
); );
} }
void mediaUpload(String? path) async { Future<void> mediaUpload(String? path) async {
context.loaderOverlay.hide(); context.loaderOverlay.hide();
if(path == null) { if(path == null) {

View File

@ -44,8 +44,7 @@ class _FeedbackDialogState extends State<FeedbackDialog> {
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => Scaffold(
return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Feedback'), title: const Text('Feedback'),
), ),
@ -125,7 +124,7 @@ class _FeedbackDialogState extends State<FeedbackDialog> {
onPressed: () async { onPressed: () async {
context.loaderOverlay.show(); context.loaderOverlay.show();
var imageData = await (await FilePick.galleryPick())?.readAsBytes(); var imageData = await (await FilePick.galleryPick())?.readAsBytes();
context.loaderOverlay.hide(); if(context.mounted) context.loaderOverlay.hide();
setState(() { setState(() {
_image = imageData; _image = imageData;
}); });
@ -170,6 +169,4 @@ class _FeedbackDialogState extends State<FeedbackDialog> {
], ],
), ),
); );
}
} }

View File

@ -4,7 +4,6 @@ import 'package:flutter/material.dart';
import 'package:jiffy/jiffy.dart'; import 'package:jiffy/jiffy.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import '../../../../api/holidays/getHolidaysResponse.dart';
import '../../../../model/holidays/holidaysProps.dart'; import '../../../../model/holidays/holidaysProps.dart';
import '../../../../storage/base/settingsProvider.dart'; import '../../../../storage/base/settingsProvider.dart';
import '../../../../widget/centeredLeading.dart'; import '../../../../widget/centeredLeading.dart';
@ -22,9 +21,7 @@ class Holidays extends StatefulWidget {
} }
extension StringExtension on String { extension StringExtension on String {
String capitalize() { String capitalize() => '${this[0].toUpperCase()}${substring(1).toLowerCase()}';
return "${this[0].toUpperCase()}${substring(1).toLowerCase()}";
}
} }
class _HolidaysState extends State<Holidays> { class _HolidaysState extends State<Holidays> {
@ -41,13 +38,10 @@ class _HolidaysState extends State<Holidays> {
super.initState(); super.initState();
} }
String parseString(String enDate) { String parseString(String enDate) => Jiffy.parse(enDate).format(pattern: 'dd.MM.yyyy');
return Jiffy.parse(enDate).format(pattern: 'dd.MM.yyyy');
}
void showDisclaimer() { void showDisclaimer() {
showDialog(context: context, builder: (context) { showDialog(context: context, builder: (context) => AlertDialog(
return AlertDialog(
title: const Text('Richtigkeit und Bereitstellung der Daten'), title: const Text('Richtigkeit und Bereitstellung der Daten'),
content: Column( content: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
@ -70,13 +64,11 @@ class _HolidaysState extends State<Holidays> {
TextButton(child: const Text('ferien-api.de besuchen'), onPressed: () => ConfirmDialog.openBrowser(context, 'https://ferien-api.de/')), TextButton(child: const Text('ferien-api.de besuchen'), onPressed: () => ConfirmDialog.openBrowser(context, 'https://ferien-api.de/')),
TextButton(child: const Text('Okay'), onPressed: () => Navigator.of(context).pop()), TextButton(child: const Text('Okay'), onPressed: () => Navigator.of(context).pop()),
], ],
); ));
});
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => Scaffold(
return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Schulferien in Hessen'), title: const Text('Schulferien in Hessen'),
actions: [ actions: [
@ -87,8 +79,7 @@ class _HolidaysState extends State<Holidays> {
PopupMenuButton<bool>( PopupMenuButton<bool>(
initialValue: settings.val().holidaysSettings.showPastEvents, initialValue: settings.val().holidaysSettings.showPastEvents,
icon: const Icon(Icons.manage_history_outlined), icon: const Icon(Icons.manage_history_outlined),
itemBuilder: (context) { itemBuilder: (context) => [true, false].map((e) => PopupMenuItem<bool>(
return [true, false].map((e) => PopupMenuItem<bool>(
value: e, value: e,
enabled: e != showPastEvents, enabled: e != showPastEvents,
child: Row( child: Row(
@ -98,8 +89,7 @@ class _HolidaysState extends State<Holidays> {
Text(e ? 'Alle anzeigen' : 'Nur zukünftige anzeigen') Text(e ? 'Alle anzeigen' : 'Nur zukünftige anzeigen')
], ],
) )
)).toList(); )).toList(),
},
onSelected: (e) { onSelected: (e) {
setState(() { setState(() {
showPastEvents = e; showPastEvents = e;
@ -112,7 +102,7 @@ class _HolidaysState extends State<Holidays> {
body: Consumer<HolidaysProps>(builder: (context, value, child) { body: Consumer<HolidaysProps>(builder: (context, value, child) {
if(value.primaryLoading()) return const LoadingSpinner(); if(value.primaryLoading()) return const LoadingSpinner();
List<GetHolidaysResponseObject> holidays = value.getHolidaysResponse.data; var holidays = value.getHolidaysResponse.data;
if(!showPastEvents) holidays = holidays.where((element) => DateTime.parse(element.end).isAfter(DateTime.now())).toList(); if(!showPastEvents) holidays = holidays.where((element) => DateTime.parse(element.end).isAfter(DateTime.now())).toList();
if(holidays.isEmpty) return const PlaceholderView(icon: Icons.search_off, text: 'Es wurden keine Ferieneinträge gefunden!'); if(holidays.isEmpty) return const PlaceholderView(icon: Icons.search_off, text: 'Es wurden keine Ferieneinträge gefunden!');
@ -120,8 +110,8 @@ class _HolidaysState extends State<Holidays> {
return ListView.builder( return ListView.builder(
itemCount: holidays.length, itemCount: holidays.length,
itemBuilder: (context, index) { itemBuilder: (context, index) {
GetHolidaysResponseObject holiday = holidays[index]; var holiday = holidays[index];
String holidayType = holiday.name.split(' ').first.capitalize(); var holidayType = holiday.name.split(' ').first.capitalize();
return ListTile( return ListTile(
leading: const CenteredLeading(Icon(Icons.calendar_month)), leading: const CenteredLeading(Icon(Icons.calendar_month)),
title: Text('$holidayType ab ${parseString(holiday.start)}'), title: Text('$holidayType ab ${parseString(holiday.start)}'),
@ -164,5 +154,4 @@ class _HolidaysState extends State<Holidays> {
}, },
) )
); );
}
} }

View File

@ -1,7 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import '../../../../api/mhsl/message/getMessages/getMessagesResponse.dart';
import '../../../../model/message/messageProps.dart'; import '../../../../model/message/messageProps.dart';
import '../../../../widget/loadingSpinner.dart'; import '../../../../widget/loadingSpinner.dart';
import 'messageView.dart'; import 'messageView.dart';
@ -24,8 +23,7 @@ class _MessageState extends State<Message> {
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => Scaffold(
return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Marianum Message'), title: const Text('Marianum Message'),
), ),
@ -36,7 +34,7 @@ class _MessageState extends State<Message> {
child: ListView.builder( child: ListView.builder(
itemCount: value.getMessagesResponse.messages.length, itemCount: value.getMessagesResponse.messages.length,
itemBuilder: (context, index) { itemBuilder: (context, index) {
GetMessagesResponseObject message = value.getMessagesResponse.messages.toList()[index]; var message = value.getMessagesResponse.messages.toList()[index];
return ListTile( return ListTile(
leading: const Column( leading: const Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
@ -58,5 +56,4 @@ class _MessageState extends State<Message> {
); );
}), }),
); );
}
} }

View File

@ -17,8 +17,7 @@ class MessageView extends StatefulWidget {
class _MessageViewState extends State<MessageView> { class _MessageViewState extends State<MessageView> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => Scaffold(
return Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text(widget.message.name), title: Text(widget.message.name),
), ),
@ -27,8 +26,7 @@ class _MessageViewState extends State<MessageView> {
enableHyperlinkNavigation: true, enableHyperlinkNavigation: true,
onDocumentLoadFailed: (PdfDocumentLoadFailedDetails e) { onDocumentLoadFailed: (PdfDocumentLoadFailedDetails e) {
Navigator.of(context).pop(); Navigator.of(context).pop();
showDialog(context: context, builder: (context) { showDialog(context: context, builder: (context) => AlertDialog(
return AlertDialog(
title: const Text('Fehler beim öffnen'), title: const Text('Fehler beim öffnen'),
content: Text("Dokument '${widget.message.name}' konnte nicht geladen werden:\n${e.description}"), content: Text("Dokument '${widget.message.name}' konnte nicht geladen werden:\n${e.description}"),
actions: [ actions: [
@ -36,8 +34,7 @@ class _MessageViewState extends State<MessageView> {
Navigator.of(context).pop(); Navigator.of(context).pop();
}, child: const Text('Ok')) }, child: const Text('Ok'))
], ],
); ));
});
}, },
onHyperlinkClicked: (PdfHyperlinkClickedDetails e) { onHyperlinkClicked: (PdfHyperlinkClickedDetails e) {
showDialog( showDialog(
@ -52,5 +49,4 @@ class _MessageViewState extends State<MessageView> {
}, },
), ),
); );
}
} }

View File

@ -5,8 +5,7 @@ class Roomplan extends StatelessWidget {
const Roomplan({super.key}); const Roomplan({super.key});
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => Scaffold(
return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Raumplan'), title: const Text('Raumplan'),
), ),
@ -17,5 +16,4 @@ class Roomplan extends StatelessWidget {
backgroundDecoration: BoxDecoration(color: Theme.of(context).colorScheme.background), backgroundDecoration: BoxDecoration(color: Theme.of(context).colorScheme.background),
), ),
); );
}
} }

View File

@ -8,7 +8,7 @@ class AppSharePlatformView extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
Color foregroundColor = Theme.of(context).colorScheme.onBackground; var foregroundColor = Theme.of(context).colorScheme.onBackground;
return Column( return Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,

View File

@ -11,8 +11,7 @@ class QrShareView extends StatefulWidget {
class _QrShareViewState extends State<QrShareView> { class _QrShareViewState extends State<QrShareView> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => DefaultTabController(
return DefaultTabController(
length: 2, length: 2,
child: Scaffold( child: Scaffold(
appBar: AppBar( appBar: AppBar(
@ -32,5 +31,4 @@ class _QrShareViewState extends State<QrShareView> {
), ),
), ),
); );
}
} }

View File

@ -8,8 +8,7 @@ class SelectShareTypeDialog extends StatelessWidget {
const SelectShareTypeDialog({super.key}); const SelectShareTypeDialog({super.key});
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => SimpleDialog(
return SimpleDialog(
children: [ children: [
ListTile( ListTile(
leading: const Icon(Icons.qr_code_2_outlined), leading: const Icon(Icons.qr_code_2_outlined),
@ -36,5 +35,4 @@ class SelectShareTypeDialog extends StatelessWidget {
) )
], ],
); );
}
} }

View File

@ -21,9 +21,7 @@ class Overhang extends StatelessWidget {
const Overhang({super.key}); const Overhang({super.key});
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => Scaffold(
return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Mehr'), title: const Text('Mehr'),
actions: [ actions: [
@ -79,5 +77,4 @@ class Overhang extends StatelessWidget {
], ],
), ),
); );
}
} }

View File

@ -35,7 +35,7 @@ class _ChatInfoState extends State<ChatInfo> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
bool isGroup = widget.room.type != GetRoomResponseObjectConversationType.oneToOne; var isGroup = widget.room.type != GetRoomResponseObjectConversationType.oneToOne;
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text(widget.room.displayName), title: Text(widget.room.displayName),

View File

@ -13,20 +13,16 @@ class ParticipantsListView extends StatefulWidget {
class _ParticipantsListViewState extends State<ParticipantsListView> { class _ParticipantsListViewState extends State<ParticipantsListView> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => Scaffold(
return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Teilnehmende'), title: const Text('Teilnehmende'),
), ),
body: ListView( body: ListView(
children: widget.participantsResponse.data.map((participant) { children: widget.participantsResponse.data.map((participant) => ListTile(
return ListTile(
leading: UserAvatar(id: participant.actorId), leading: UserAvatar(id: participant.actorId),
title: Text(participant.displayName), title: Text(participant.displayName),
subtitle: participant.statusMessage != null ? Text(participant.statusMessage!) : null, subtitle: participant.statusMessage != null ? Text(participant.statusMessage!) : null,
); )).toList(),
}).toList(),
), ),
); );
}
} }

View File

@ -119,14 +119,14 @@ class _ChatListState extends State<ChatList> {
if(data.primaryLoading()) return const LoadingSpinner(); if(data.primaryLoading()) return const LoadingSpinner();
latestData = data; latestData = data;
List<ChatTile> chats = []; var chats = <ChatTile>[];
for (var chatRoom in data.getRoomsResponse.sortBy( for (var chatRoom in data.getRoomsResponse.sortBy(
lastActivity: true, lastActivity: true,
favoritesToTop: Provider.of<SettingsProvider>(context).val().talkSettings.sortFavoritesToTop, favoritesToTop: Provider.of<SettingsProvider>(context).val().talkSettings.sortFavoritesToTop,
unreadToTop: Provider.of<SettingsProvider>(context).val().talkSettings.sortUnreadToTop, unreadToTop: Provider.of<SettingsProvider>(context).val().talkSettings.sortUnreadToTop,
) )
) { ) {
bool hasDraft = settings.val().talkSettings.drafts.containsKey(chatRoom.token); var hasDraft = settings.val().talkSettings.drafts.containsKey(chatRoom.token);
chats.add(ChatTile(data: chatRoom, query: _query, hasDraft: hasDraft)); chats.add(ChatTile(data: chatRoom, query: _query, hasDraft: hasDraft));
} }

View File

@ -40,19 +40,18 @@ class _ChatViewState extends State<ChatView> {
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => Consumer<ChatProps>(
return Consumer<ChatProps>(
builder: (context, data, child) { builder: (context, data, child) {
List<Widget> messages = List<Widget>.empty(growable: true); var messages = List<Widget>.empty(growable: true);
if(!data.primaryLoading()) { if(!data.primaryLoading()) {
DateTime lastDate = DateTime.now(); var lastDate = DateTime.now();
data.getChatResponse.sortByTimestamp().forEach((element) { data.getChatResponse.sortByTimestamp().forEach((element) {
DateTime elementDate = DateTime.fromMillisecondsSinceEpoch(element.timestamp * 1000); var elementDate = DateTime.fromMillisecondsSinceEpoch(element.timestamp * 1000);
if(element.systemMessage.contains('reaction')) return; if(element.systemMessage.contains('reaction')) return;
int commonRead = int.parse(data.getChatResponse.headers?['x-chat-last-common-read'] ?? '0'); var commonRead = int.parse(data.getChatResponse.headers?['x-chat-last-common-read'] ?? '0');
if(!elementDate.isSameDay(lastDate)) { if(!elementDate.isSameDay(lastDate)) {
lastDate = elementDate; lastDate = elementDate;
@ -140,5 +139,4 @@ class _ChatViewState extends State<ChatView> {
); );
}, },
); );
}
} }

View File

@ -51,15 +51,13 @@ class ChatBubble extends StatefulWidget {
class _ChatBubbleState extends State<ChatBubble> { class _ChatBubbleState extends State<ChatBubble> {
BubbleStyle getSystemStyle() { BubbleStyle getSystemStyle() => BubbleStyle(
return BubbleStyle(
color: AppTheme.isDarkMode(context) ? const Color(0xff182229) : Colors.white, color: AppTheme.isDarkMode(context) ? const Color(0xff182229) : Colors.white,
borderWidth: 1, borderWidth: 1,
elevation: 2, elevation: 2,
margin: const BubbleEdges.only(bottom: 20, top: 10), margin: const BubbleEdges.only(bottom: 20, top: 10),
alignment: Alignment.center, alignment: Alignment.center,
); );
}
BubbleStyle getRemoteStyle(bool seamless) { BubbleStyle getRemoteStyle(bool seamless) {
var color = AppTheme.isDarkMode(context) ? const Color(0xff202c33) : Colors.white; var color = AppTheme.isDarkMode(context) ? const Color(0xff202c33) : Colors.white;
@ -105,17 +103,17 @@ class _ChatBubbleState extends State<ChatBubble> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
message = ChatMessage(originalMessage: widget.bubbleData.message, originalData: widget.bubbleData.messageParameters); message = ChatMessage(originalMessage: widget.bubbleData.message, originalData: widget.bubbleData.messageParameters);
bool showActorDisplayName = widget.bubbleData.messageType == GetRoomResponseObjectMessageType.comment && widget.chatData.type != GetRoomResponseObjectConversationType.oneToOne; var showActorDisplayName = widget.bubbleData.messageType == GetRoomResponseObjectMessageType.comment && widget.chatData.type != GetRoomResponseObjectConversationType.oneToOne;
bool showBubbleTime = widget.bubbleData.messageType != GetRoomResponseObjectMessageType.system; var showBubbleTime = widget.bubbleData.messageType != GetRoomResponseObjectMessageType.system;
Text actorText = Text( var actorText = Text(
widget.bubbleData.actorDisplayName, widget.bubbleData.actorDisplayName,
textAlign: TextAlign.start, textAlign: TextAlign.start,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
style: TextStyle(color: Theme.of(context).primaryColor, fontWeight: FontWeight.bold), style: TextStyle(color: Theme.of(context).primaryColor, fontWeight: FontWeight.bold),
); );
Text timeText = Text( var timeText = Text(
Jiffy.parseFromMillisecondsSinceEpoch(widget.bubbleData.timestamp * 1000).format(pattern: 'HH:mm'), Jiffy.parseFromMillisecondsSinceEpoch(widget.bubbleData.timestamp * 1000).format(pattern: 'HH:mm'),
textAlign: TextAlign.end, textAlign: TextAlign.end,
style: TextStyle(color: widget.timeIconColor, fontSize: widget.timeIconSize), style: TextStyle(color: widget.timeIconColor, fontSize: widget.timeIconSize),
@ -186,8 +184,8 @@ class _ChatBubbleState extends State<ChatBubble> {
), ),
onLongPress: () { onLongPress: () {
showDialog(context: context, builder: (context) { showDialog(context: context, builder: (context) {
List<String> commonReactions = ['👍', '👎', '😆', '❤️', '👀']; var commonReactions = <String>['👍', '👎', '😆', '❤️', '👀'];
bool canReact = widget.bubbleData.messageType == GetRoomResponseObjectMessageType.comment; var canReact = widget.bubbleData.messageType == GetRoomResponseObjectMessageType.comment;
return SimpleDialog( return SimpleDialog(
children: [ children: [
Visibility( Visibility(
@ -217,8 +215,7 @@ class _ChatBubbleState extends State<ChatBubble> {
), ),
IconButton( IconButton(
onPressed: () { onPressed: () {
showDialog(context: context, builder: (context) { showDialog(context: context, builder: (context) => AlertDialog(
return AlertDialog(
contentPadding: const EdgeInsets.all(15), contentPadding: const EdgeInsets.all(15),
titlePadding: const EdgeInsets.only(left: 6, top: 15), titlePadding: const EdgeInsets.only(left: 6, top: 15),
title: Row( title: Row(
@ -278,8 +275,7 @@ class _ChatBubbleState extends State<ChatBubble> {
], ],
), ),
), ),
); ));
});
}, },
style: IconButton.styleFrom( style: IconButton.styleFrom(
padding: EdgeInsets.zero, padding: EdgeInsets.zero,
@ -350,8 +346,7 @@ class _ChatBubbleState extends State<ChatBubble> {
if(message.file == null) return; if(message.file == null) return;
if(downloadProgress > 0) { if(downloadProgress > 0) {
showDialog(context: context, builder: (context) { showDialog(context: context, builder: (context) => AlertDialog(
return AlertDialog(
title: const Text('Download abbrechen?'), title: const Text('Download abbrechen?'),
content: const Text('Möchtest du den Download abbrechen?'), content: const Text('Möchtest du den Download abbrechen?'),
actions: [ actions: [
@ -369,8 +364,7 @@ class _ChatBubbleState extends State<ChatBubble> {
}); });
}, child: const Text('Ja, Abbrechen')) }, child: const Text('Ja, Abbrechen'))
], ],
); ));
});
return; return;
} }
@ -388,11 +382,9 @@ class _ChatBubbleState extends State<ChatBubble> {
}); });
if(result.type != ResultType.done) { if(result.type != ResultType.done) {
showDialog(context: context, builder: (context) { showDialog(context: context, builder: (context) => AlertDialog(
return AlertDialog(
content: Text(result.message), content: Text(result.message),
); ));
});
} }
}); });
}, },
@ -408,7 +400,7 @@ class _ChatBubbleState extends State<ChatBubble> {
alignment: widget.isSender ? WrapAlignment.end : WrapAlignment.start, alignment: widget.isSender ? WrapAlignment.end : WrapAlignment.start,
crossAxisAlignment: WrapCrossAlignment.start, crossAxisAlignment: WrapCrossAlignment.start,
children: widget.bubbleData.reactions?.entries.map<Widget>((e) { children: widget.bubbleData.reactions?.entries.map<Widget>((e) {
bool hasSelfReacted = widget.bubbleData.reactionsSelf?.contains(e.key) ?? false; var hasSelfReacted = widget.bubbleData.reactionsSelf?.contains(e.key) ?? false;
return Container( return Container(
margin: const EdgeInsets.only(right: 2.5, left: 2.5), margin: const EdgeInsets.only(right: 2.5, left: 2.5),
child: ActionChip( child: ActionChip(

View File

@ -37,8 +37,7 @@ class ChatMessage {
} }
return CachedNetworkImage( return CachedNetworkImage(
errorWidget: (context, url, error) { errorWidget: (context, url, error) => Padding(padding: const EdgeInsets.only(top: 10), child: Row(
return Padding(padding: const EdgeInsets.only(top: 10), child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
children: [ children: [
@ -47,12 +46,9 @@ class ChatMessage {
Flexible(child: Text(file!.name, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(fontWeight: FontWeight.bold))), Flexible(child: Text(file!.name, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(fontWeight: FontWeight.bold))),
const SizedBox(width: 10), const SizedBox(width: 10),
], ],
)); )),
},
alignment: Alignment.center, alignment: Alignment.center,
placeholder: (context, url) { placeholder: (context, url) => const Padding(padding: EdgeInsets.all(10), child: CircularProgressIndicator()),
return const Padding(padding: EdgeInsets.all(10), child: CircularProgressIndicator());
},
fadeInDuration: Duration.zero, fadeInDuration: Duration.zero,
fadeOutDuration: Duration.zero, fadeOutDuration: Duration.zero,
errorListener: (value) {}, errorListener: (value) {},
@ -60,7 +56,7 @@ class ChatMessage {
); );
} }
void onOpen(LinkableElement link) async { Future<void> onOpen(LinkableElement link) async {
if(await canLaunchUrlString(link.url)) { if(await canLaunchUrlString(link.url)) {
await launchUrlString(link.url); await launchUrlString(link.url);
} }

View File

@ -34,15 +34,15 @@ class _ChatTextfieldState extends State<ChatTextfield> {
Provider.of<ChatProps>(context, listen: false).run(); Provider.of<ChatProps>(context, listen: false).run();
} }
void mediaUpload(String? path) async { Future<void> mediaUpload(String? path) async {
context.loaderOverlay.hide(); context.loaderOverlay.hide();
if(path == null) { if(path == null) {
return; return;
} }
String filename = "${path.split("/").last.split(".").first}-${const Uuid().v4()}.${path.split(".").last}"; var filename = "${path.split("/").last.split(".").first}-${const Uuid().v4()}.${path.split(".").last}";
String shareFolder = 'MarianumMobile'; var shareFolder = 'MarianumMobile';
WebdavApi.webdav.then((webdav) { WebdavApi.webdav.then((webdav) {
webdav.mkcol(PathUri.parse('/$shareFolder')); webdav.mkcol(PathUri.parse('/$shareFolder'));
}); });
@ -91,8 +91,7 @@ class _ChatTextfieldState extends State<ChatTextfield> {
children: <Widget>[ children: <Widget>[
GestureDetector( GestureDetector(
onTap: (){ onTap: (){
showDialog(context: context, builder: (context) { showDialog(context: context, builder: (context) => SimpleDialog(
return SimpleDialog(
children: [ children: [
ListTile( ListTile(
leading: const Icon(Icons.file_open), leading: const Icon(Icons.file_open),
@ -118,8 +117,7 @@ class _ChatTextfieldState extends State<ChatTextfield> {
), ),
), ),
], ],
); ));
});
}, },
child: Material( child: Material(
elevation: 5, elevation: 5,

View File

@ -40,7 +40,7 @@ class _ChatTileState extends State<ChatTile> {
username = value.getString('username')! username = value.getString('username')!
}); });
bool isGroup = widget.data.type != GetRoomResponseObjectConversationType.oneToOne; var isGroup = widget.data.type != GetRoomResponseObjectConversationType.oneToOne;
circleAvatar = UserAvatar(id: isGroup ? widget.data.token : widget.data.name, isGroup: isGroup); circleAvatar = UserAvatar(id: isGroup ? widget.data.token : widget.data.name, isGroup: isGroup);
} }
@ -56,10 +56,7 @@ class _ChatTileState extends State<ChatTile> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => Consumer<ChatProps>(builder: (context, chatData, child) => ListTile(
return Consumer<ChatProps>(builder: (context, chatData, child) {
return ListTile(
style: ListTileStyle.list, style: ListTileStyle.list,
tileColor: chatData.currentToken() == widget.data.token && TalkNavigator.isSecondaryVisible(context) tileColor: chatData.currentToken() == widget.data.token && TalkNavigator.isSecondaryVisible(context)
? Theme.of(context).primaryColor.withAlpha(100) ? Theme.of(context).primaryColor.withAlpha(100)
@ -120,7 +117,7 @@ class _ChatTileState extends State<ChatTile> {
), ),
onTap: () async { onTap: () async {
setCurrentAsRead(); setCurrentAsRead();
ChatView view = ChatView(room: widget.data, selfId: username, avatar: circleAvatar); var view = ChatView(room: widget.data, selfId: username, avatar: circleAvatar);
TalkNavigator.pushSplitView(context, view, overrideToSingleSubScreen: true); TalkNavigator.pushSplitView(context, view, overrideToSingleSubScreen: true);
Provider.of<ChatProps>(context, listen: false).setQueryToken(widget.data.token); Provider.of<ChatProps>(context, listen: false).setQueryToken(widget.data.token);
}, },
@ -185,7 +182,5 @@ class _ChatTileState extends State<ChatTile> {
], ],
)); ));
}, },
); ));
});
}
} }

View File

@ -6,8 +6,7 @@ class SplitViewPlaceholder extends StatelessWidget {
const SplitViewPlaceholder({super.key}); const SplitViewPlaceholder({super.key});
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => Scaffold(
return Scaffold(
appBar: AppBar(), appBar: AppBar(),
body: Center( body: Center(
child: Column( child: Column(
@ -25,5 +24,4 @@ class SplitViewPlaceholder extends StatelessWidget {
), ),
) )
); );
}
} }

View File

@ -11,8 +11,7 @@ class JoinChat extends SearchDelegate<String> {
CancelableOperation<AutocompleteResponse>? future; CancelableOperation<AutocompleteResponse>? future;
@override @override
List<Widget>? buildActions(BuildContext context) { List<Widget>? buildActions(BuildContext context) => [
return [
if(future != null && query.isNotEmpty) FutureBuilder( if(future != null && query.isNotEmpty) FutureBuilder(
future: future!.value, future: future!.value,
builder: (context, snapshot) { builder: (context, snapshot) {
@ -35,12 +34,9 @@ class JoinChat extends SearchDelegate<String> {
), ),
if(query.isNotEmpty) IconButton(onPressed: () => query = '', icon: const Icon(Icons.delete)), if(query.isNotEmpty) IconButton(onPressed: () => query = '', icon: const Icon(Icons.delete)),
]; ];
}
@override @override
Widget? buildLeading(BuildContext context) { Widget? buildLeading(BuildContext context) => null;
return null;
}
@override @override
Widget buildResults(BuildContext context) { Widget buildResults(BuildContext context) {
@ -61,8 +57,8 @@ class JoinChat extends SearchDelegate<String> {
return ListView.builder( return ListView.builder(
itemCount: snapshot.data!.data.length, itemCount: snapshot.data!.data.length,
itemBuilder: (context, index) { itemBuilder: (context, index) {
AutocompleteResponseObject object = snapshot.data!.data[index]; var object = snapshot.data!.data[index];
CircleAvatar circleAvatar = CircleAvatar( var circleAvatar = CircleAvatar(
foregroundImage: Image.network('https://${EndpointData().nextcloud().full()}/avatar/${object.id}/128').image, foregroundImage: Image.network('https://${EndpointData().nextcloud().full()}/avatar/${object.id}/128').image,
backgroundColor: Theme.of(context).primaryColor, backgroundColor: Theme.of(context).primaryColor,
foregroundColor: Colors.white, foregroundColor: Colors.white,
@ -89,8 +85,6 @@ class JoinChat extends SearchDelegate<String> {
} }
@override @override
Widget buildSuggestions(BuildContext context) { Widget buildSuggestions(BuildContext context) => buildResults(context);
return buildResults(context);
}
} }

View File

@ -30,8 +30,7 @@ class _MessageReactionsState extends State<MessageReactions> {
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => Scaffold(
return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Reaktionen'), title: const Text('Reaktionen'),
), ),
@ -42,8 +41,7 @@ class _MessageReactionsState extends State<MessageReactions> {
if(snapshot.data == null) return const PlaceholderView(icon: Icons.search_off_outlined, text: 'Keine Reaktionen gefunden!'); if(snapshot.data == null) return const PlaceholderView(icon: Icons.search_off_outlined, text: 'Keine Reaktionen gefunden!');
return ListView( return ListView(
children: [ children: [
...snapshot.data!.data.entries.map<Widget>((entry) { ...snapshot.data!.data.entries.map<Widget>((entry) => ExpansionTile(
return ExpansionTile(
textColor: Theme.of(context).colorScheme.onSurface, textColor: Theme.of(context).colorScheme.onSurface,
collapsedTextColor: Theme.of(context).colorScheme.onSurface, collapsedTextColor: Theme.of(context).colorScheme.onSurface,
iconColor: Theme.of(context).colorScheme.onSurface, iconColor: Theme.of(context).colorScheme.onSurface,
@ -53,7 +51,7 @@ class _MessageReactionsState extends State<MessageReactions> {
leading: CenteredLeading(Text(entry.key)), leading: CenteredLeading(Text(entry.key)),
title: Text('${entry.value.length} mal reagiert'), title: Text('${entry.value.length} mal reagiert'),
children: entry.value.map((e) { children: entry.value.map((e) {
bool isSelf = AccountData().getUsername() == e.actorId; var isSelf = AccountData().getUsername() == e.actorId;
return ListTile( return ListTile(
leading: UserAvatar(id: e.actorId, isGroup: false), leading: UserAvatar(id: e.actorId, isGroup: false),
title: Text(e.actorDisplayName), title: Text(e.actorDisplayName),
@ -71,12 +69,10 @@ class _MessageReactionsState extends State<MessageReactions> {
), ),
); );
}).toList(), }).toList(),
); ))
})
], ],
); );
}, },
), ),
); );
}
} }

View File

@ -9,16 +9,12 @@ class SearchChat extends SearchDelegate {
SearchChat(this.chats); SearchChat(this.chats);
@override @override
List<Widget>? buildActions(BuildContext context) { List<Widget>? buildActions(BuildContext context) => [
return [
if(query.isNotEmpty) IconButton(onPressed: () => query = '', icon: const Icon(Icons.delete)), if(query.isNotEmpty) IconButton(onPressed: () => query = '', icon: const Icon(Icons.delete)),
]; ];
}
@override @override
Widget? buildLeading(BuildContext context) { Widget? buildLeading(BuildContext context) => null;
return null;
}
@override @override
Widget buildResults(BuildContext context) { Widget buildResults(BuildContext context) {
@ -35,7 +31,5 @@ class SearchChat extends SearchDelegate {
} }
@override @override
Widget buildSuggestions(BuildContext context) { Widget buildSuggestions(BuildContext context) => buildResults(context);
return buildResults(context);
}
} }

View File

@ -9,7 +9,7 @@ class TalkNavigator {
static void pushSplitView(BuildContext context, Widget view, {bool overrideToSingleSubScreen = false}) { static void pushSplitView(BuildContext context, Widget view, {bool overrideToSingleSubScreen = false}) {
if(isSecondaryVisible(context)) { if(isSecondaryVisible(context)) {
SplitViewState splitView = SplitView.of(context); var splitView = SplitView.of(context);
overrideToSingleSubScreen ? splitView.setSecondary(view) : splitView.push(view); overrideToSingleSubScreen ? splitView.setSecondary(view) : splitView.push(view);
} else { } else {
pushScreen(context, screen: view, withNavBar: false); pushScreen(context, screen: view, withNavBar: false);

Some files were not shown because too many files have changed in this diff Show More