7 Commits

Author SHA1 Message Date
5d264f7651 added notes for next tasks 2024-03-30 18:33:52 +01:00
a6f7c09671 wip 2024-03-29 21:58:51 +01:00
eaf6d9f547 updated new linter rules 2024-03-29 18:47:54 +01:00
5b34afd6cb Merge branch 'develop' into feature-highEduGraduationCalculator
# Conflicts:
#	lib/view/pages/overhang.dart
2024-03-29 18:32:59 +01:00
25d901d093 WIP lk select dialog 2024-03-29 17:29:31 +01:00
6237a2e9cf Merge branch 'develop' into feature-highEduGraduationCalculator
# Conflicts:
#	lib/view/pages/overhang.dart
2024-03-24 14:21:01 +01:00
c4f5be2205 WIP high education graduation calculator 2024-03-23 15:42:31 +01:00
296 changed files with 2758 additions and 5223 deletions

16
.gitignore vendored
View File

@ -48,14 +48,14 @@ lib/generated_plugin_registrant.dart
#pubspec.lock #pubspec.lock
# Android related # Android related
materials/screenshots/android/**/gradle-wrapper.jar **/android/**/gradle-wrapper.jar
materials/screenshots/android/.gradle **/android/.gradle
materials/screenshots/android/captures/ **/android/captures/
materials/screenshots/android/gradlew **/android/gradlew
materials/screenshots/android/gradlew.bat **/android/gradlew.bat
materials/screenshots/android/key.properties **/android/key.properties
materials/screenshots/android/local.properties **/android/local.properties
materials/screenshots/android/**/GeneratedPluginRegistrant.java **/android/**/GeneratedPluginRegistrant.java
# iOS/XCode related # iOS/XCode related
**/ios/**/*.mode1v3 **/ios/**/*.mode1v3

View File

@ -9,10 +9,6 @@
# packages, and plugins designed to encourage good coding practices. # packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml include: package:flutter_lints/flutter.yaml
analyzer:
errors:
invalid_annotation_target: ignore
linter: linter:
# The lint rules applied to this project can be customized in the # The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml` # section below to disable rules from the `package:flutter_lints/flutter.yaml`
@ -32,13 +28,6 @@ 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

@ -25,7 +25,7 @@ if (flutterVersionName == null) {
android { android {
namespace "eu.mhsl.marianum.mobile.client" namespace "eu.mhsl.marianum.mobile.client"
compileSdk flutter.compileSdkVersion compileSdk flutter.compileSdkVersion
ndkVersion "27.0.12077973" ndkVersion flutter.ndkVersion
compileOptions { compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8 sourceCompatibility JavaVersion.VERSION_1_8
@ -41,8 +41,11 @@ android {
} }
defaultConfig { defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "eu.mhsl.marianum.mobile.client" applicationId "eu.mhsl.marianum.mobile.client"
minSdkVersion 26 // You can update the following values to match your application needs.
// For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
minSdkVersion 19
targetSdkVersion flutter.targetSdkVersion targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger() versionCode flutterVersionCode.toInteger()
versionName flutterVersionName versionName flutterVersionName
@ -63,6 +66,5 @@ flutter {
} }
dependencies { dependencies {
implementation 'com.android.support:multidex:2.0.1' implementation 'com.android.support:multidex:1.0.3'
implementation 'com.android.tools:desugar_jdk_libs:2.0.3'
} }

View File

@ -1,6 +1,3 @@
org.gradle.jvmargs=-Xmx4G org.gradle.jvmargs=-Xmx4G
android.useAndroidX=true android.useAndroidX=true
android.enableJetifier=true android.enableJetifier=true
android.defaults.buildfeatures.buildconfig=true
android.nonTransitiveRClass=false
android.nonFinalResIds=false

View File

@ -1,7 +1,6 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

View File

@ -19,8 +19,8 @@ pluginManagement {
plugins { plugins {
id "dev.flutter.flutter-plugin-loader" version "1.0.0" id "dev.flutter.flutter-plugin-loader" version "1.0.0"
id "com.android.application" version '8.1.4' apply false id "com.android.application" version "7.3.0" apply false
id "org.jetbrains.kotlin.android" version "1.8.10" apply false id "org.jetbrains.kotlin.android" version "1.7.10" apply false
} }
include ":app" include ":app"

View File

@ -1,29 +0,0 @@
-----BEGIN CERTIFICATE-----
MIIFBTCCAu2gAwIBAgIQS6hSk/eaL6JzBkuoBI110DANBgkqhkiG9w0BAQsFADBP
MQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFy
Y2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTAeFw0yNDAzMTMwMDAwMDBa
Fw0yNzAzMTIyMzU5NTlaMDMxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBF
bmNyeXB0MQwwCgYDVQQDEwNSMTAwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
AoIBAQDPV+XmxFQS7bRH/sknWHZGUCiMHT6I3wWd1bUYKb3dtVq/+vbOo76vACFL
YlpaPAEvxVgD9on/jhFD68G14BQHlo9vH9fnuoE5CXVlt8KvGFs3Jijno/QHK20a
/6tYvJWuQP/py1fEtVt/eA0YYbwX51TGu0mRzW4Y0YCF7qZlNrx06rxQTOr8IfM4
FpOUurDTazgGzRYSespSdcitdrLCnF2YRVxvYXvGLe48E1KGAdlX5jgc3421H5KR
mudKHMxFqHJV8LDmowfs/acbZp4/SItxhHFYyTr6717yW0QrPHTnj7JHwQdqzZq3
DZb3EoEmUVQK7GH29/Xi8orIlQ2NAgMBAAGjgfgwgfUwDgYDVR0PAQH/BAQDAgGG
MB0GA1UdJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATASBgNVHRMBAf8ECDAGAQH/
AgEAMB0GA1UdDgQWBBS7vMNHpeS8qcbDpHIMEI2iNeHI6DAfBgNVHSMEGDAWgBR5
tFnme7bl5AFzgAiIyBpY9umbbjAyBggrBgEFBQcBAQQmMCQwIgYIKwYBBQUHMAKG
Fmh0dHA6Ly94MS5pLmxlbmNyLm9yZy8wEwYDVR0gBAwwCjAIBgZngQwBAgEwJwYD
VR0fBCAwHjAcoBqgGIYWaHR0cDovL3gxLmMubGVuY3Iub3JnLzANBgkqhkiG9w0B
AQsFAAOCAgEAkrHnQTfreZ2B5s3iJeE6IOmQRJWjgVzPw139vaBw1bGWKCIL0vIo
zwzn1OZDjCQiHcFCktEJr59L9MhwTyAWsVrdAfYf+B9haxQnsHKNY67u4s5Lzzfd
u6PUzeetUK29v+PsPmI2cJkxp+iN3epi4hKu9ZzUPSwMqtCceb7qPVxEbpYxY1p9
1n5PJKBLBX9eb9LU6l8zSxPWV7bK3lG4XaMJgnT9x3ies7msFtpKK5bDtotij/l0
GaKeA97pb5uwD9KgWvaFXMIEt8jVTjLEvwRdvCn294GPDF08U8lAkIv7tghluaQh
1QnlE4SEN4LOECj8dsIGJXpGUk3aU3KkJz9icKy+aUgA+2cP21uh6NcDIS3XyfaZ
QjmDQ993ChII8SXWupQZVBiIpcWO4RqZk3lr7Bz5MUCwzDIA359e57SSq5CCkY0N
4B6Vulk7LktfwrdGNVI5BsC9qqxSwSKgRJeZ9wygIaehbHFHFhcBaMDKpiZlBHyz
rsnnlFXCb5s8HKn5LsUgGvB24L7sGNZP2CX7dhHov+YhD+jozLW2p9W4959Bz2Ei
RmqDtmiXLnzqTpXbI+suyCsohKRg6Un0RC47+cpiVwHiXZAW+cn8eiNIjqbVgXLx
KPpdzvvtTnOPlC7SQZSYmdunr3Bf9b77AiC/ZidstK36dRILKz7OA54=
-----END CERTIFICATE-----

View File

@ -1,7 +0,0 @@
targets:
$default:
builders:
json_serializable:
options:
explicit_to_json: false
generic_argument_factories: true

View File

Before

Width:  |  Height:  |  Size: 94 KiB

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 KiB

View File

Before

Width:  |  Height:  |  Size: 100 KiB

After

Width:  |  Height:  |  Size: 100 KiB

View File

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

View File

@ -1,15 +1,17 @@
import 'dart:convert'; import 'dart:convert';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'getHolidaysResponse.dart'; import 'getHolidaysResponse.dart';
class GetHolidays { class GetHolidays {
Future<GetHolidaysResponse> query() async { Future<GetHolidaysResponse> query() async {
var response = (await http.get(Uri.parse('https://ferien-api.de/api/v1/holidays/HE'))).body; String response = (await http.get(Uri.parse('https://ferien-api.de/api/v1/holidays/HE'))).body;
var data = jsonDecode(response) as List<dynamic>;
return GetHolidaysResponse( return GetHolidaysResponse(
List<GetHolidaysResponseObject>.from( List<GetHolidaysResponseObject>.from(
data.map<GetHolidaysResponseObject>((e) => GetHolidaysResponseObject.fromJson(e as Map<String, dynamic>)) jsonDecode(response).map<GetHolidaysResponseObject>(
GetHolidaysResponseObject.fromJson
)
) )
); );
} }

View File

@ -6,21 +6,24 @@ import 'getHolidaysResponse.dart';
class GetHolidaysCache extends RequestCache<GetHolidaysResponse> { class GetHolidaysCache extends RequestCache<GetHolidaysResponse> {
GetHolidaysCache({onUpdate, renew}) : super(RequestCache.cacheDay, onUpdate, renew: renew) { GetHolidaysCache({onUpdate, renew}) : super(RequestCache.cacheDay, onUpdate, renew: renew) {
start('state-holidays'); start('MarianumMobile', 'state-holidays');
} }
@override @override
GetHolidaysResponse onLocalData(String json) { GetHolidaysResponse onLocalData(String json) {
List<dynamic> parsedListJson = jsonDecode(json)['data']; List<dynamic> parsedListJson = jsonDecode(json)['data'];
return GetHolidaysResponse( return GetHolidaysResponse(
List<GetHolidaysResponseObject>.from( List<GetHolidaysResponseObject>.from(
parsedListJson.map<GetHolidaysResponseObject>( parsedListJson.map<GetHolidaysResponseObject>(
(i) => GetHolidaysResponseObject.fromJson(i as Map<String, dynamic>) // ignore: unnecessary_lambdas
(dynamic i) => GetHolidaysResponseObject.fromJson(i)
)
) )
)
); );
} }
@override @override
Future<GetHolidaysResponse> onLoad() => GetHolidays().query(); Future<GetHolidaysResponse> onLoad() {
return GetHolidays().query();
}
} }

View File

@ -2,6 +2,7 @@ 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';
@ -9,7 +10,7 @@ import 'autocompleteResponse.dart';
class AutocompleteApi { class AutocompleteApi {
Future<AutocompleteResponse> find(String query) async { Future<AutocompleteResponse> find(String query) async {
var getParameters = <String, dynamic>{ Map<String, dynamic> getParameters = {
'search': query, 'search': query,
'itemType': ' ', 'itemType': ' ',
'itemId': ' ', 'itemId': ' ',
@ -17,15 +18,15 @@ class AutocompleteApi {
'limit': '10', 'limit': '10',
}; };
var headers = <String, String>{}; Map<String, String> headers = {};
headers.putIfAbsent('Accept', () => 'application/json'); headers.putIfAbsent('Accept', () => 'application/json');
headers.putIfAbsent('OCS-APIRequest', () => 'true'); headers.putIfAbsent('OCS-APIRequest', () => 'true');
var endpoint = Uri.https('${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().domain}', '${EndpointData().nextcloud().path}/ocs/v2.php/core/autocomplete/get', getParameters); Uri endpoint = Uri.https('${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().domain}', '${EndpointData().nextcloud().path}/ocs/v2.php/core/autocomplete/get', getParameters);
var response = await http.get(endpoint, headers: headers); Response 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}');
var result = response.body; String result = response.body;
return AutocompleteResponse.fromJson(jsonDecode(result)['ocs']); return AutocompleteResponse.fromJson(jsonDecode(result)['ocs']);
} }

View File

@ -1,6 +1,7 @@
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';
@ -8,12 +9,12 @@ import 'fileSharingApiParams.dart';
class FileSharingApi { class FileSharingApi {
Future<void> share(FileSharingApiParams query) async { Future<void> share(FileSharingApiParams query) async {
var headers = <String, String>{}; Map<String, String> headers = {};
headers.putIfAbsent('Accept', () => 'application/json'); headers.putIfAbsent('Accept', () => 'application/json');
headers.putIfAbsent('OCS-APIRequest', () => 'true'); headers.putIfAbsent('OCS-APIRequest', () => 'true');
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()))); 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 response = await http.post(endpoint, headers: headers); Response 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,9 +14,13 @@ 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) => GetChatResponse.fromJson(jsonDecode(raw)['ocs']); assemble(String raw) {
return GetChatResponse.fromJson(jsonDecode(raw)['ocs']);
}
@override @override
Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) => http.get(uri, headers: headers); Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) {
return http.get(uri, headers: headers);
}
} }

View File

@ -9,11 +9,12 @@ class GetChatCache extends RequestCache<GetChatResponse> {
String chatToken; String chatToken;
GetChatCache({required onUpdate, required this.chatToken}) : super(RequestCache.cacheNothing, onUpdate) { GetChatCache({required onUpdate, required this.chatToken}) : super(RequestCache.cacheNothing, onUpdate) {
start('nc-chat-$chatToken'); start('MarianumMobile', 'nc-chat-$chatToken');
} }
@override @override
Future<GetChatResponse> onLoad() => GetChat( Future<GetChatResponse> onLoad() {
return GetChat(
chatToken, chatToken,
GetChatParams( GetChatParams(
lookIntoFuture: GetChatParamsSwitch.off, lookIntoFuture: GetChatParamsSwitch.off,
@ -21,8 +22,11 @@ class GetChatCache extends RequestCache<GetChatResponse> {
limit: 200, limit: 200,
) )
).run(); ).run();
}
@override @override
GetChatResponse onLocalData(String json) => GetChatResponse.fromJson(jsonDecode(json)); GetChatResponse onLocalData(String 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() {
var sorted = data.toList(); List<GetChatResponseObject> 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;
} }
@ -38,7 +38,6 @@ class GetChatResponseObject {
Map<String, int>? reactions; Map<String, int>? reactions;
List<String>? reactionsSelf; List<String>? reactionsSelf;
@JsonKey(fromJson: _fromJson) Map<String, RichObjectString>? messageParameters; @JsonKey(fromJson: _fromJson) Map<String, RichObjectString>? messageParameters;
GetChatResponseObject? parent;
GetChatResponseObject( GetChatResponseObject(
this.id, this.id,
@ -54,19 +53,19 @@ class GetChatResponseObject {
this.message, this.message,
this.messageParameters, this.messageParameters,
this.reactions, this.reactions,
this.reactionsSelf, this.reactionsSelf
this.parent,
); );
factory GetChatResponseObject.fromJson(Map<String, dynamic> json) => _$GetChatResponseObjectFromJson(json); factory GetChatResponseObject.fromJson(Map<String, dynamic> json) => _$GetChatResponseObjectFromJson(json);
Map<String, dynamic> toJson() => _$GetChatResponseObjectToJson(this); Map<String, dynamic> toJson() => _$GetChatResponseObjectToJson(this);
static GetChatResponseObject getDateDummy(int timestamp) { static GetChatResponseObject getDateDummy(int timestamp) {
var elementDate = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000); DateTime 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) => GetChatResponseObject( static GetChatResponseObject getTextDummy(String text) {
return GetChatResponseObject(
0, 0,
'', '',
GetRoomResponseObjectMessageActorType.user, GetRoomResponseObjectMessageActorType.user,
@ -80,15 +79,15 @@ class GetChatResponseObject {
text, text,
null, null,
null, 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>) {
var data = <String, RichObjectString>{}; Map<String, RichObjectString> data = {};
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

@ -52,10 +52,6 @@ GetChatResponseObject _$GetChatResponseObjectFromJson(
(json['reactionsSelf'] as List<dynamic>?) (json['reactionsSelf'] as List<dynamic>?)
?.map((e) => e as String) ?.map((e) => e as String)
.toList(), .toList(),
json['parent'] == null
? null
: GetChatResponseObject.fromJson(
json['parent'] as Map<String, dynamic>),
); );
Map<String, dynamic> _$GetChatResponseObjectToJson( Map<String, dynamic> _$GetChatResponseObjectToJson(
@ -78,7 +74,6 @@ Map<String, dynamic> _$GetChatResponseObjectToJson(
'reactionsSelf': instance.reactionsSelf, 'reactionsSelf': instance.reactionsSelf,
'messageParameters': 'messageParameters':
instance.messageParameters?.map((k, e) => MapEntry(k, e.toJson())), instance.messageParameters?.map((k, e) => MapEntry(k, e.toJson())),
'parent': instance.parent?.toJson(),
}; };
const _$GetRoomResponseObjectMessageActorTypeEnumMap = { const _$GetRoomResponseObjectMessageActorTypeEnumMap = {

View File

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

View File

@ -11,7 +11,9 @@ 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) => null; assemble(String raw) {
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,9 +10,13 @@ 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.fromJson(jsonDecode(raw)['ocs']); GetParticipantsResponse assemble(String raw) {
return GetParticipantsResponse.fromJson(jsonDecode(raw)['ocs']);
}
@override @override
Future<http.Response> request(Uri uri, Object? body, Map<String, String>? headers) => http.get(uri, headers: headers); Future<http.Response> request(Uri uri, Object? body, Map<String, String>? headers) {
return http.get(uri, headers: headers);
}
} }

View File

@ -8,15 +8,19 @@ class GetParticipantsCache extends RequestCache<GetParticipantsResponse> {
String chatToken; String chatToken;
GetParticipantsCache({required onUpdate, required this.chatToken}) : super(RequestCache.cacheNothing, onUpdate) { GetParticipantsCache({required onUpdate, required this.chatToken}) : super(RequestCache.cacheNothing, onUpdate) {
start('nc-chat-participants-$chatToken'); start('MarianumMobile', 'nc-chat-participants-$chatToken');
} }
@override @override
Future<GetParticipantsResponse> onLoad() => GetParticipants( Future<GetParticipantsResponse> onLoad() {
return GetParticipants(
chatToken, chatToken,
).run(); ).run();
}
@override @override
GetParticipantsResponse onLocalData(String json) => GetParticipantsResponse.fromJson(jsonDecode(json)); GetParticipantsResponse onLocalData(String json) {
return GetParticipantsResponse.fromJson(jsonDecode(json));
}
} }

View File

@ -13,9 +13,13 @@ 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) => GetReactionsResponse.fromJson(jsonDecode(raw)['ocs']); assemble(String raw) {
return GetReactionsResponse.fromJson(jsonDecode(raw)['ocs']);
}
@override @override
Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) => http.get(uri, headers: headers); Future<Response>? request(Uri uri, ApiParams? body, Map<String, String>? headers) {
return http.get(uri, headers: headers);
}
} }

View File

@ -9,8 +9,12 @@ 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) => null; assemble(String raw) {
return null;
}
@override @override
Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) => http.delete(uri, headers: headers); Future<Response> request(Uri uri, Object? body, Map<String, String>? headers) {
return http.delete(uri, headers: headers);
}
} }

View File

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

View File

@ -8,16 +8,20 @@ import 'getRoomResponse.dart';
class GetRoomCache extends RequestCache<GetRoomResponse> { class GetRoomCache extends RequestCache<GetRoomResponse> {
GetRoomCache({onUpdate, renew}) : super(RequestCache.cacheMinute, onUpdate, renew: renew) { GetRoomCache({onUpdate, renew}) : super(RequestCache.cacheMinute, onUpdate, renew: renew) {
start('nc-rooms'); start('MarianumMobile', 'nc-rooms');
} }
@override @override
GetRoomResponse onLocalData(String json) => GetRoomResponse.fromJson(jsonDecode(json)); GetRoomResponse onLocalData(String json) {
return GetRoomResponse.fromJson(jsonDecode(json));
}
@override @override
Future<GetRoomResponse> onLoad() => GetRoom( Future<GetRoomResponse> onLoad() {
return GetRoom(
GetRoomParams( GetRoomParams(
includeStatus: true, includeStatus: true,
) )
).run(); ).run();
}
} }

View File

@ -10,7 +10,9 @@ 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) => null; assemble(String raw) {
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

@ -7,7 +7,7 @@ part 'sendMessageParams.g.dart';
@JsonSerializable(explicitToJson: true, includeIfNull: false) @JsonSerializable(explicitToJson: true, includeIfNull: false)
class SendMessageParams extends ApiParams { class SendMessageParams extends ApiParams {
String message; String message;
String? replyTo; int? replyTo;
SendMessageParams(this.message, {this.replyTo}); SendMessageParams(this.message, {this.replyTo});

View File

@ -9,7 +9,7 @@ part of 'sendMessageParams.dart';
SendMessageParams _$SendMessageParamsFromJson(Map<String, dynamic> json) => SendMessageParams _$SendMessageParamsFromJson(Map<String, dynamic> json) =>
SendMessageParams( SendMessageParams(
json['message'] as String, json['message'] as String,
replyTo: json['replyTo'] as String?, replyTo: json['replyTo'] as int?,
); );
Map<String, dynamic> _$SendMessageParamsToJson(SendMessageParams instance) { Map<String, dynamic> _$SendMessageParamsToJson(SendMessageParams instance) {

View File

@ -11,7 +11,9 @@ 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) => null; assemble(String raw) {
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,7 +15,9 @@ class SetReadMarker extends TalkApi {
} }
@override @override
assemble(String raw) => null; assemble(String raw) {
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());
}); });
var endpoint = Uri.https('${AccountData().buildHttpAuthString()}@${EndpointData().nextcloud().domain}', '${EndpointData().nextcloud().path}/ocs/v2.php/apps/spreed/api/$path', getParameters); Uri 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,5 +6,7 @@ class TalkError {
TalkError(this.status, this.code, this.message); TalkError(this.status, this.code, this.message);
@override @override
String toString() => 'Talk - $status - ($code): $message'; String toString() {
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 {
var davFiles = (await (await WebdavApi.webdav).propfind(PathUri.parse(params.path))).toWebDavFiles(); List<WebDavFile> davFiles = (await (await WebdavApi.webdav).propfind(PathUri.parse(params.path))).toWebDavFiles();
var files = davFiles.map(CacheableFile.fromDavFile).toSet(); Set<CacheableFile> 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,17 +11,19 @@ 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');
var cacheName = md5.convert(bytes).toString(); String cacheName = md5.convert(bytes).toString();
start('wd-folder-$cacheName'); start('MarianumMobile', 'wd-folder-$cacheName');
} }
@override @override
Future<ListFilesResponse> onLoad() async { Future<ListFilesResponse> onLoad() async {
var data = await ListFiles(ListFilesParams(path)).run(); ListFilesResponse data = await ListFiles(ListFilesParams(path)).run();
return data; return data;
} }
@override @override
ListFilesResponse onLocalData(String json) => ListFilesResponse.fromJson(jsonDecode(json)); ListFilesResponse onLocalData(String json) {
return ListFilesResponse.fromJson(jsonDecode(json));
}
} }

View File

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

View File

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

View File

@ -6,12 +6,16 @@ import 'getBreakersResponse.dart';
class GetBreakersCache extends RequestCache<GetBreakersResponse> { class GetBreakersCache extends RequestCache<GetBreakersResponse> {
GetBreakersCache({onUpdate, renew}) : super(RequestCache.cacheMinute, onUpdate, renew: renew) { GetBreakersCache({onUpdate, renew}) : super(RequestCache.cacheMinute, onUpdate, renew: renew) {
start('breakers'); start('MarianumMobile', 'breakers');
} }
@override @override
GetBreakersResponse onLocalData(String json) => GetBreakersResponse.fromJson(jsonDecode(json)); GetBreakersResponse onLocalData(String json) {
return GetBreakersResponse.fromJson(jsonDecode(json));
}
@override @override
Future<GetBreakersResponse> onLoad() => GetBreakers().run(); Future<GetBreakersResponse> onLoad() {
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) {
var body = jsonEncode(params.toJson()); String body = jsonEncode(params.toJson());
return http.post(uri, body: body); return http.post(uri, body: body);
} }
} }

View File

@ -12,8 +12,12 @@ 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.fromJson({'events': jsonDecode(raw)}); GetCustomTimetableEventResponse assemble(String raw) {
return GetCustomTimetableEventResponse.fromJson({'events': jsonDecode(raw)});
}
@override @override
Future<Response>? request(Uri uri) => http.get(uri); Future<Response>? request(Uri uri) {
return http.get(uri);
}
} }

View File

@ -9,12 +9,16 @@ class GetCustomTimetableEventCache extends RequestCache<GetCustomTimetableEventR
GetCustomTimetableEventParams params; GetCustomTimetableEventParams params;
GetCustomTimetableEventCache(this.params, {onUpdate, renew}) : super(RequestCache.cacheMinute, onUpdate, renew: renew) { GetCustomTimetableEventCache(this.params, {onUpdate, renew}) : super(RequestCache.cacheMinute, onUpdate, renew: renew) {
start('customTimetableEvents'); start('MarianumMobile', 'customTimetableEvents');
} }
@override @override
Future<GetCustomTimetableEventResponse> onLoad() => GetCustomTimetableEvent(params).run(); Future<GetCustomTimetableEventResponse> onLoad() {
return GetCustomTimetableEvent(params).run();
}
@override @override
GetCustomTimetableEventResponse onLocalData(String json) => GetCustomTimetableEventResponse.fromJson(jsonDecode(json)); GetCustomTimetableEventResponse onLocalData(String json) {
return GetCustomTimetableEventResponse.fromJson(jsonDecode(json));
}
} }

View File

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

View File

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

View File

@ -0,0 +1,21 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../../mhslApi.dart';
import 'getMessagesResponse.dart';
class GetMessages extends MhslApi<GetMessagesResponse> {
GetMessages() : super('message/messages.json');
@override
GetMessagesResponse assemble(String raw) {
return GetMessagesResponse.fromJson(jsonDecode(raw));
}
@override
Future<http.Response> request(Uri uri) {
return http.get(uri);
}
}

View File

@ -0,0 +1,21 @@
import 'dart:convert';
import '../../../requestCache.dart';
import 'getMessages.dart';
import 'getMessagesResponse.dart';
class GetMessagesCache extends RequestCache<GetMessagesResponse> {
GetMessagesCache({onUpdate, renew}) : super(RequestCache.cacheMinute, onUpdate, renew: renew) {
start('MarianumMobile', 'message');
}
@override
GetMessagesResponse onLocalData(String json) {
return GetMessagesResponse.fromJson(jsonDecode(json));
}
@override
Future<GetMessagesResponse> onLoad() {
return GetMessages().run();
}
}

View File

@ -0,0 +1,28 @@
import 'package:json_annotation/json_annotation.dart';
import '../../../apiResponse.dart';
part 'getMessagesResponse.g.dart';
@JsonSerializable(explicitToJson: true)
class GetMessagesResponse extends ApiResponse {
String base;
Set<GetMessagesResponseObject> messages;
GetMessagesResponse(this.base, this.messages);
factory GetMessagesResponse.fromJson(Map<String, dynamic> json) => _$GetMessagesResponseFromJson(json);
Map<String, dynamic> toJson() => _$GetMessagesResponseToJson(this);
}
@JsonSerializable(explicitToJson: true)
class GetMessagesResponseObject {
String name;
String date;
String url;
GetMessagesResponseObject(this.name, this.date, this.url);
factory GetMessagesResponseObject.fromJson(Map<String, dynamic> json) => _$GetMessagesResponseObjectFromJson(json);
Map<String, dynamic> toJson() => _$GetMessagesResponseObjectToJson(this);
}

View File

@ -0,0 +1,49 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'getMessagesResponse.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
GetMessagesResponse _$GetMessagesResponseFromJson(Map<String, dynamic> json) =>
GetMessagesResponse(
json['base'] as String,
(json['messages'] as List<dynamic>)
.map((e) =>
GetMessagesResponseObject.fromJson(e as Map<String, dynamic>))
.toSet(),
)..headers = (json['headers'] as Map<String, dynamic>?)?.map(
(k, e) => MapEntry(k, e as String),
);
Map<String, dynamic> _$GetMessagesResponseToJson(GetMessagesResponse instance) {
final val = <String, dynamic>{};
void writeNotNull(String key, dynamic value) {
if (value != null) {
val[key] = value;
}
}
writeNotNull('headers', instance.headers);
val['base'] = instance.base;
val['messages'] = instance.messages.map((e) => e.toJson()).toList();
return val;
}
GetMessagesResponseObject _$GetMessagesResponseObjectFromJson(
Map<String, dynamic> json) =>
GetMessagesResponseObject(
json['name'] as String,
json['date'] as String,
json['url'] as String,
);
Map<String, dynamic> _$GetMessagesResponseObjectToJson(
GetMessagesResponseObject instance) =>
<String, dynamic>{
'name': instance.name,
'date': instance.date,
'url': instance.url,
};

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 {
var endpoint = Uri.parse('https://mhsl.eu/marianum/marianummobile/$subpath'); Uri endpoint = Uri.parse('https://mhsl.eu/marianum/marianummobile/$subpath');
var data = await request(endpoint); http.Response? 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,4 +31,5 @@ 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,8 +19,8 @@ class NotifyRegister extends MhslApi<void> {
@override @override
Future<http.Response> request(Uri uri) { Future<http.Response> request(Uri uri) {
var requestString = jsonEncode(params.toJson()); String requestString = jsonEncode(params.toJson());
log('register at push proxy with username ${params.username}'); log(requestString);
return http.post(uri, body: requestString); return http.post(uri, body: requestString);
} }
} }

View File

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

View File

@ -6,14 +6,12 @@ part 'addFeedbackParams.g.dart';
class AddFeedbackParams { class AddFeedbackParams {
String user; String user;
String feedback; String feedback;
String? screenshot;
int appVersion; int appVersion;
AddFeedbackParams({ AddFeedbackParams({
required this.user, required this.user,
required this.feedback, required this.feedback,
this.screenshot,
required this.appVersion, required this.appVersion,
}); });

View File

@ -10,7 +10,6 @@ AddFeedbackParams _$AddFeedbackParamsFromJson(Map<String, dynamic> json) =>
AddFeedbackParams( AddFeedbackParams(
user: json['user'] as String, user: json['user'] as String,
feedback: json['feedback'] as String, feedback: json['feedback'] as String,
screenshot: json['screenshot'] as String?,
appVersion: json['appVersion'] as int, appVersion: json['appVersion'] as int,
); );
@ -18,6 +17,5 @@ Map<String, dynamic> _$AddFeedbackParamsToJson(AddFeedbackParams instance) =>
<String, dynamic>{ <String, dynamic>{
'user': instance.user, 'user': instance.user,
'feedback': instance.feedback, 'feedback': instance.feedback,
'screenshot': instance.screenshot,
'appVersion': instance.appVersion, 'appVersion': instance.appVersion,
}; };

View File

@ -4,7 +4,7 @@ import 'dart:developer';
import 'package:device_info_plus/device_info_plus.dart'; import 'package:device_info_plus/device_info_plus.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'package:package_info_plus/package_info_plus.dart'; import 'package:package_info/package_info.dart';
import '../../../../../model/accountData.dart'; import '../../../../../model/accountData.dart';
import '../../../mhslApi.dart'; import '../../../mhslApi.dart';
@ -19,12 +19,12 @@ class UpdateUserIndex extends MhslApi<void> {
@override @override
Future<http.Response> request(Uri uri) { Future<http.Response> request(Uri uri) {
var data = jsonEncode(params.toJson()); String data = jsonEncode(params.toJson());
log('Updating userindex: ${data.length}'); log('Updating userindex:\n $data');
return http.post(uri, body: data); return http.post(uri, body: data);
} }
static Future<void> index() async { static void index() async {
UpdateUserIndex( UpdateUserIndex(
UpdateUserIndexParams( UpdateUserIndexParams(
username: AccountData().getUsername(), username: AccountData().getUsername(),

View File

@ -1,9 +1,9 @@
import 'dart:convert'; import 'dart:convert';
import 'dart:developer';
import 'package:localstore/localstore.dart'; import 'package:localstore/localstore.dart';
import 'apiResponse.dart'; import 'apiResponse.dart';
import 'webuntis/webuntisError.dart';
abstract class RequestCache<T extends ApiResponse?> { abstract class RequestCache<T extends ApiResponse?> {
static const int cacheNothing = 0; static const int cacheNothing = 0;
@ -11,8 +11,6 @@ abstract class RequestCache<T extends ApiResponse?> {
static const int cacheHour = 60 * 60; static const int cacheHour = 60 * 60;
static const int cacheDay = 60 * 60 * 24; static const int cacheDay = 60 * 60 * 24;
static String collection = 'MarianumMobile';
int maxCacheTime; int maxCacheTime;
Function(T) onUpdate; Function(T) onUpdate;
Function(Exception) onError; Function(Exception) onError;
@ -22,8 +20,8 @@ abstract class RequestCache<T extends ApiResponse?> {
static void ignore(Exception e) {} static void ignore(Exception e) {}
Future<void> start(String document) async { void start(String file, String document) async {
var tableData = await Localstore.instance.collection(collection).doc(document).get(); Map<String, dynamic>? tableData = await Localstore.instance.collection(file).doc(document).get();
if(tableData != null) { if(tableData != null) {
onUpdate(onLocalData(tableData['json'])); onUpdate(onLocalData(tableData['json']));
} }
@ -32,16 +30,18 @@ abstract class RequestCache<T extends ApiResponse?> {
if(renew == null || !renew!) return; if(renew == null || !renew!) return;
} }
T? newValue;
try { try {
var newValue = await onLoad(); newValue = await onLoad();
onUpdate(newValue); onUpdate(newValue as T);
Localstore.instance.collection(collection).doc(document).set({ Localstore.instance.collection(file).doc(document).set({
'json': jsonEncode(newValue), 'json': jsonEncode(newValue),
'lastupdate': DateTime.now().millisecondsSinceEpoch 'lastupdate': DateTime.now().millisecondsSinceEpoch
}); });
} on WebuntisError catch(e) { } catch(e) {
onError(e); log("Error while fetching/ parsing. Raw server response: ${newValue?.rawResponse.body ?? "no response"}");
onError(Exception(e.toString()));
} }
} }

View File

@ -14,7 +14,7 @@ class Authenticate extends WebuntisApi {
@override @override
Future<AuthenticateResponse> run() async { Future<AuthenticateResponse> run() async {
awaitingResponse = true; awaitingResponse = true;
var rawAnswer = await query(this); String 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 {
var rawAnswer = await query(this); String 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) {
var start = DateTime.parse(element.startDate.toString()); DateTime start = DateTime.parse(element.startDate.toString());
var end = DateTime.parse(element.endDate.toString()); DateTime 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

@ -6,12 +6,16 @@ import 'getHolidaysResponse.dart';
class GetHolidaysCache extends RequestCache<GetHolidaysResponse> { class GetHolidaysCache extends RequestCache<GetHolidaysResponse> {
GetHolidaysCache({onUpdate}) : super(RequestCache.cacheDay, onUpdate) { GetHolidaysCache({onUpdate}) : super(RequestCache.cacheDay, onUpdate) {
start('wu-holidays'); start('MarianumMobile', 'wu-holidays');
} }
@override @override
Future<GetHolidaysResponse> onLoad() => GetHolidays().run(); Future<GetHolidaysResponse> onLoad() {
return GetHolidays().run();
}
@override @override
GetHolidaysResponse onLocalData(String json) => GetHolidaysResponse.fromJson(jsonDecode(json)); GetHolidaysResponse onLocalData(String 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 {
var rawAnswer = await query(this); String 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

@ -6,13 +6,17 @@ import 'getRoomsResponse.dart';
class GetRoomsCache extends RequestCache<GetRoomsResponse> { class GetRoomsCache extends RequestCache<GetRoomsResponse> {
GetRoomsCache({onUpdate}) : super(RequestCache.cacheHour, onUpdate) { GetRoomsCache({onUpdate}) : super(RequestCache.cacheHour, onUpdate) {
start('wu-rooms'); start('MarianumMobile', 'wu-rooms');
} }
@override @override
Future<GetRoomsResponse> onLoad() => GetRooms().run(); Future<GetRoomsResponse> onLoad() {
return GetRooms().run();
}
@override @override
GetRoomsResponse onLocalData(String json) => GetRoomsResponse.fromJson(jsonDecode(json)); GetRoomsResponse onLocalData(String 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 {
var rawAnswer = await query(this); String rawAnswer = await query(this);
return finalize(GetSubjectsResponse.fromJson(jsonDecode(rawAnswer))); return finalize(GetSubjectsResponse.fromJson(jsonDecode(rawAnswer)));
} }
} }

View File

@ -6,13 +6,17 @@ import 'getSubjectsResponse.dart';
class GetSubjectsCache extends RequestCache<GetSubjectsResponse> { class GetSubjectsCache extends RequestCache<GetSubjectsResponse> {
GetSubjectsCache({onUpdate}) : super(RequestCache.cacheHour, onUpdate) { GetSubjectsCache({onUpdate}) : super(RequestCache.cacheHour, onUpdate) {
start('wu-subjects'); start('MarianumMobile', 'wu-subjects');
} }
@override @override
Future<GetSubjectsResponse> onLoad() => GetSubjects().run(); Future<GetSubjectsResponse> onLoad() {
return GetSubjects().run();
}
@override @override
onLocalData(String json) => GetSubjectsResponse.fromJson(jsonDecode(json)); onLocalData(String 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 {
var rawAnswer = await query(this); String rawAnswer = await query(this);
return finalize(GetTimetableResponse.fromJson(jsonDecode(rawAnswer))); return finalize(GetTimetableResponse.fromJson(jsonDecode(rawAnswer)));
} }

View File

@ -11,14 +11,17 @@ class GetTimetableCache extends RequestCache<GetTimetableResponse> {
int enddate; int enddate;
GetTimetableCache({required onUpdate, onError, required this.startdate, required this.enddate}) : super(RequestCache.cacheMinute, onUpdate, onError: onError) { GetTimetableCache({required onUpdate, onError, required this.startdate, required this.enddate}) : super(RequestCache.cacheMinute, onUpdate, onError: onError) {
start('wu-timetable-$startdate-$enddate'); start('MarianumMobile', 'wu-timetable-$startdate-$enddate');
} }
@override @override
GetTimetableResponse onLocalData(String json) => GetTimetableResponse.fromJson(jsonDecode(json)); GetTimetableResponse onLocalData(String json) {
return GetTimetableResponse.fromJson(jsonDecode(json));
}
@override @override
Future<GetTimetableResponse> onLoad() async => GetTimetable( Future<GetTimetableResponse> onLoad() async {
return GetTimetable(
GetTimetableParams( GetTimetableParams(
options: GetTimetableParamsOptions( options: GetTimetableParamsOptions(
element: GetTimetableParamsOptionsElement( element: GetTimetableParamsOptionsElement(
@ -35,4 +38,5 @@ 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 {
var query = '{"id":"ID","method":"$method","params":${untis._body()},"jsonrpc":"2.0"}'; String query = '{"id":"ID","method":"$method","params":${untis._body()},"jsonrpc":"2.0"}';
var sessionId = '0'; String sessionId = '0';
if(authenticatedResponse) { if(authenticatedResponse) {
sessionId = (await Authenticate.getSession()).sessionId; sessionId = (await Authenticate.getSession()).sessionId;
} }
var data = await post(query, {'Cookie': 'JSESSIONID=$sessionId'}); http.Response data = await post(query, {'Cookie': 'JSESSIONID=$sessionId'});
response = data; response = data;
dynamic jsonData = jsonDecode(data.body); dynamic jsonData = jsonDecode(data.body);
@ -48,12 +48,16 @@ abstract class WebuntisApi extends ApiRequest {
Future<ApiResponse> run(); Future<ApiResponse> run();
String _body() => genericParam == null ? '{}' : jsonEncode(genericParam); String _body() {
return genericParam == null ? '{}' : jsonEncode(genericParam);
}
Future<http.Response> post(String data, Map<String, String>? headers) async => await http Future<http.Response> post(String data, Map<String, String>? headers) async {
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,5 +5,7 @@ class WebuntisError implements Exception {
WebuntisError(this.message, this.code); WebuntisError(this.message, this.code);
@override @override
String toString() => 'WebUntis ($code): $message'; String toString() {
return 'WebUntis ($code): $message';
}
} }

View File

@ -5,34 +5,35 @@ import 'dart:developer';
import 'package:easy_debounce/easy_throttle.dart'; import 'package:easy_debounce/easy_throttle.dart';
import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'state/app/modules/app_modules.dart';
import 'package:persistent_bottom_nav_bar_v2/persistent_bottom_nav_bar_v2.dart'; import 'package:persistent_bottom_nav_bar_v2/persistent_bottom_nav_bar_v2.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:badges/badges.dart' as badges; import 'package:badges/badges.dart' as badges;
import 'api/mhsl/breaker/getBreakers/getBreakersResponse.dart'; import 'api/mhsl/breaker/getBreakers/getBreakersResponse.dart';
import 'api/mhsl/server/userIndex/update/updateUserindex.dart'; import 'api/mhsl/server/userIndex/update/updateUserindex.dart';
import 'main.dart';
import 'model/breakers/Breaker.dart'; import 'model/breakers/Breaker.dart';
import 'model/breakers/BreakerProps.dart'; import 'model/breakers/BreakerProps.dart';
import 'model/chatList/chatListProps.dart'; import 'model/chatList/chatListProps.dart';
import 'model/dataCleaner.dart';
import 'model/timetable/timetableProps.dart'; import 'model/timetable/timetableProps.dart';
import 'notification/notificationController.dart'; import 'notification/notificationController.dart';
import 'notification/notificationTasks.dart'; import 'notification/notificationTasks.dart';
import 'notification/notifyUpdater.dart'; import 'notification/notifyUpdater.dart';
import 'storage/base/settingsProvider.dart'; import 'storage/base/settingsProvider.dart';
import 'view/pages/files/files.dart';
import 'view/pages/overhang.dart'; import 'view/pages/overhang.dart';
import 'view/pages/talk/chatList.dart';
import 'view/pages/timetable/timetable.dart';
class App extends StatefulWidget { class App extends StatefulWidget {
const App({super.key}); const App({super.key});
static PersistentTabController bottomNavigator = PersistentTabController(initialIndex: 0);
@override @override
State<App> createState() => _AppState(); State<App> createState() => _AppState();
} }
class _AppState extends State<App> with WidgetsBindingObserver { class _AppState extends State<App> with WidgetsBindingObserver {
late Timer refetchChats; late Timer refetchChats;
late Timer updateTimings; late Timer updateTimings;
@ -56,7 +57,6 @@ class _AppState extends State<App> with WidgetsBindingObserver {
@override @override
void initState() { void initState() {
Main.bottomNavigator = PersistentTabController(initialIndex: 0);
WidgetsBinding.instance.addObserver(this); WidgetsBinding.instance.addObserver(this);
WidgetsBinding.instance.addPostFrameCallback((timeStamp) { WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
Provider.of<BreakerProps>(context, listen: false).run(); Provider.of<BreakerProps>(context, listen: false).run();
@ -87,44 +87,63 @@ class _AppState extends State<App> with WidgetsBindingObserver {
FirebaseMessaging.onMessageOpenedApp.listen((message) => NotificationController.onAppOpenedByNotification(message, context)); FirebaseMessaging.onMessageOpenedApp.listen((message) => NotificationController.onAppOpenedByNotification(message, context));
FirebaseMessaging.instance.getInitialMessage().then((message) => message == null ? null : NotificationController.onAppOpenedByNotification(message, context)); FirebaseMessaging.instance.getInitialMessage().then((message) => message == null ? null : NotificationController.onAppOpenedByNotification(message, context));
DataCleaner.cleanOldCache();
super.initState(); super.initState();
} }
@override @override
Widget build(BuildContext context) => PersistentTabView( Widget build(BuildContext context) {
controller: Main.bottomNavigator, return PersistentTabView(
controller: App.bottomNavigator,
gestureNavigationEnabled: true,
navBarOverlap: const NavBarOverlap.none(), navBarOverlap: const NavBarOverlap.none(),
backgroundColor: Theme.of(context).colorScheme.primary, backgroundColor: Theme.of(context).colorScheme.primary,
handleAndroidBackButtonPress: false,
screenTransitionAnimation: const ScreenTransitionAnimation(curve: Curves.easeOutQuad, duration: Duration(milliseconds: 200)), screenTransitionAnimation: const ScreenTransitionAnimation(curve: Curves.easeOutQuad, duration: Duration(milliseconds: 200)),
tabs: [ tabs: [
AppModule.getModule(Modules.timetable).toBottomTab(context), PersistentTabConfig(
AppModule.getModule(Modules.talk).toBottomTab( screen: const Breaker(breaker: BreakerArea.timetable, child: Timetable()),
context, item: ItemConfig(
itemBuilder: (icon) => Consumer<ChatListProps>( activeForegroundColor: Theme.of(context).primaryColor,
builder: (context, value, child) { inactiveForegroundColor: Theme.of(context).colorScheme.secondary,
if(value.primaryLoading()) return Icon(icon); icon: const Icon(Icons.calendar_month),
var messages = value.getRoomsResponse.data.map((e) => e.unreadMessages).reduce((a, b) => a+b); title: 'Vertretung'
return badges.Badge( ),
showBadge: messages > 0, ),
position: badges.BadgePosition.topEnd(top: -3, end: -3), PersistentTabConfig(
stackFit: StackFit.loose, screen: const Breaker(breaker: BreakerArea.talk, child: ChatList()),
badgeStyle: badges.BadgeStyle( item: ItemConfig(
padding: const EdgeInsets.all(3), activeForegroundColor: Theme.of(context).primaryColor,
badgeColor: Theme.of(context).primaryColor, inactiveForegroundColor: Theme.of(context).colorScheme.secondary,
elevation: 1, icon: Consumer<ChatListProps>(
), builder: (context, value, child) {
badgeContent: Text('$messages', style: const TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.bold)), if(value.primaryLoading()) return const Icon(Icons.chat);
child: Icon(icon), int messages = value.getRoomsResponse.data.map((e) => e.unreadMessages).reduce((a, b) => a+b);
); return badges.Badge(
}, showBadge: messages > 0,
position: badges.BadgePosition.topEnd(top: -3, end: -3),
stackFit: StackFit.loose,
badgeStyle: badges.BadgeStyle(
padding: const EdgeInsets.all(3),
badgeColor: Theme.of(context).primaryColor,
elevation: 1,
),
badgeContent: Text('$messages', style: const TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.bold)),
child: const Icon(Icons.chat),
);
},
),
title: 'Talk',
),
),
PersistentTabConfig(
screen: const Breaker(breaker: BreakerArea.files, child: Files([])),
item: ItemConfig(
activeForegroundColor: Theme.of(context).primaryColor,
inactiveForegroundColor: Theme.of(context).colorScheme.secondary,
icon: const Icon(Icons.folder),
title: 'Dateien'
), ),
), ),
AppModule.getModule(Modules.files).toBottomTab(context),
PersistentTabConfig( PersistentTabConfig(
screen: const Breaker(breaker: BreakerArea.more, child: Overhang()), screen: const Breaker(breaker: BreakerArea.more, child: Overhang()),
item: ItemConfig( item: ItemConfig(
@ -143,6 +162,7 @@ class _AppState extends State<App> with WidgetsBindingObserver {
), ),
), ),
); );
}
@override @override
void dispose() { void dispose() {

View File

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

View File

@ -1,3 +1,5 @@
extension RenderNotNullExt<T> on T? { extension RenderNotNullExt<T> on T? {
R? wrapNullable<R>(R Function(T data) defaultValueCallback) => this != null ? defaultValueCallback(this as T) : null; R? wrapNullable<R>(R Function(T data) defaultValueCallback) {
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( final TextPainter 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,9 +1,15 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
extension TimeOfDayExt on TimeOfDay { extension TimeOfDayExt on TimeOfDay {
bool isBefore(TimeOfDay other) => hour < other.hour && minute < other.minute; bool isBefore(TimeOfDay other) {
return hour < other.hour && minute < other.minute;
}
bool isAfter(TimeOfDay other) => hour > other.hour && minute > other.minute; bool isAfter(TimeOfDay other) {
return hour > other.hour && minute > other.minute;
}
TimeOfDay add({int hours = 0, int minutes = 0}) => replacing(hour: hour + hours, minute: minute + minutes); TimeOfDay add({int hours = 0, int minutes = 0}) {
return replacing(hour: hour + hours, minute: minute + minutes);
}
} }

View File

@ -7,13 +7,10 @@ import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:jiffy/jiffy.dart'; import 'package:jiffy/jiffy.dart';
import 'package:loader_overlay/loader_overlay.dart'; import 'package:loader_overlay/loader_overlay.dart';
import 'package:path_provider/path_provider.dart';
import 'package:persistent_bottom_nav_bar_v2/persistent_bottom_nav_bar_v2.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'api/mhsl/breaker/getBreakers/getBreakersResponse.dart'; import 'api/mhsl/breaker/getBreakers/getBreakersResponse.dart';
import 'app.dart'; import 'app.dart';
@ -26,46 +23,37 @@ import 'model/chatList/chatListProps.dart';
import 'model/chatList/chatProps.dart'; import 'model/chatList/chatProps.dart';
import 'model/files/filesProps.dart'; import 'model/files/filesProps.dart';
import 'model/holidays/holidaysProps.dart'; import 'model/holidays/holidaysProps.dart';
import 'model/message/messageProps.dart';
import 'model/timetable/timetableProps.dart'; import 'model/timetable/timetableProps.dart';
import 'storage/base/settingsProvider.dart'; import 'storage/base/settingsProvider.dart';
import 'theming/darkAppTheme.dart'; import 'theming/darkAppTheme.dart';
import 'theming/lightAppTheme.dart'; import 'theming/lightAppTheme.dart';
import 'view/login/login.dart'; import 'view/login/login.dart';
import 'view/pages/more/abiturCalculator/models/abiturCalculatorModel.dart';
import 'widget/placeholderView.dart'; import 'widget/placeholderView.dart';
Future<void> main() async { Future<void> main() async {
log('MarianumMobile started');
WidgetsFlutterBinding.ensureInitialized(); WidgetsFlutterBinding.ensureInitialized();
addCertificateAsTrusted(ByteData certificate) => SecurityContext.defaultContext.setTrustedCertificatesBytes(certificate.buffer.asUint8List()); try {
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
var initialisationTasks = [ log("Firebase token: ${await FirebaseMessaging.instance.getToken() ?? "Error: no Firebase token!"}");
Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform) } catch (e) {
.then((value) async => log("Firebase token: ${await FirebaseMessaging.instance.getToken() ?? "Error: no Firebase token!"}")) log('Error initializing Firebase app!');
.onError((error, stackTrace) => log('Error initializing Firebase: $error')), }
PlatformAssetBundle().load('assets/ca/lets-encrypt-r3.pem').then(addCertificateAsTrusted), ByteData data = await PlatformAssetBundle().load('assets/ca/lets-encrypt-r3.pem');
PlatformAssetBundle().load('assets/ca/lets-encrypt-r10.pem').then(addCertificateAsTrusted), SecurityContext.defaultContext.setTrustedCertificatesBytes(data.buffer.asUint8List());
Future(() async { if(kReleaseMode) {
await HydratedStorage.build( ErrorWidget.builder = (error) {
storageDirectory: HydratedStorageDirectory((await getTemporaryDirectory()).path) return PlaceholderView(
).then((storage) => HydratedBloc.storage = storage); icon: Icons.phonelink_erase_rounded,
}) text: error.toStringShort(),
]; );
};
log('starting app initialisation...');
await Future.wait(initialisationTasks);
log('app initialisation done!');
if(kReleaseMode) {
ErrorWidget.builder = (error) => PlaceholderView(
icon: Icons.phonelink_erase_rounded,
text: error.toStringShort(),
);
} }
log('running app...');
runApp( runApp(
MultiProvider( MultiProvider(
providers: [ providers: [
@ -79,7 +67,10 @@ Future<void> main() async {
ChangeNotifierProvider(create: (context) => ChatProps()), ChangeNotifierProvider(create: (context) => ChatProps()),
ChangeNotifierProvider(create: (context) => FilesProps()), ChangeNotifierProvider(create: (context) => FilesProps()),
ChangeNotifierProvider(create: (context) => MessageProps()),
ChangeNotifierProvider(create: (context) => HolidaysProps()), ChangeNotifierProvider(create: (context) => HolidaysProps()),
ChangeNotifierProvider(create: (context) => AbiturCalculatorModel()),
], ],
child: const Main(), child: const Main(),
) )
@ -88,8 +79,6 @@ Future<void> main() async {
class Main extends StatefulWidget { class Main extends StatefulWidget {
const Main({super.key}); const Main({super.key});
static PersistentTabController bottomNavigator = PersistentTabController(initialIndex: 0);
@override @override
State<Main> createState() => _MainState(); State<Main> createState() => _MainState();
@ -115,7 +104,8 @@ class _MainState extends State<Main> {
} }
@override @override
Widget build(BuildContext context) => Directionality( Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr, textDirection: TextDirection.ltr,
child: Consumer<SettingsProvider>( child: Consumer<SettingsProvider>(
builder: (context, settings, child) { builder: (context, settings, child) {
@ -159,6 +149,7 @@ class _MainState extends State<Main> {
}, },
), ),
); );
}
@override @override
void dispose() { void dispose() {

View File

@ -17,7 +17,9 @@ class AccountData {
final Future<SharedPreferences> _storage = SharedPreferences.getInstance(); final Future<SharedPreferences> _storage = SharedPreferences.getInstance();
Completer<void> _populated = Completer(); Completer<void> _populated = Completer();
factory AccountData() => _instance; factory AccountData() {
return _instance;
}
AccountData._construct() { AccountData._construct() {
_updateFromStorage(); _updateFromStorage();
@ -36,12 +38,16 @@ class AccountData {
return _password!; return _password!;
} }
String getUserSecret() => sha512.convert(utf8.encode('${AccountData().getUsername()}:${AccountData().getPassword()}')).toString(); String getUserSecret() {
return sha512.convert(utf8.encode('${AccountData().getUsername()}:${AccountData().getPassword()}')).toString();
}
Future<String> getDeviceId() async => sha512.convert(utf8.encode('${getUserSecret()}@${await FirebaseMessaging.instance.getToken()}')).toString(); Future<String> getDeviceId() async {
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 {
var storage = await _storage; SharedPreferences storage = await _storage;
storage.setString(_usernameField, username); storage.setString(_usernameField, username);
storage.setString(_passwordField, password); storage.setString(_passwordField, password);
@ -53,13 +59,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);
var storage = await _storage; SharedPreferences 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 {
var storage = await _storage; SharedPreferences 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);
@ -73,7 +79,9 @@ class AccountData {
return isPopulated(); return isPopulated();
} }
bool isPopulated() => _username != null && _password != null; bool isPopulated() {
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,9 +19,10 @@ class Breaker extends StatefulWidget {
class _BreakerState extends State<Breaker> { class _BreakerState extends State<Breaker> {
@override @override
Widget build(BuildContext context) => Consumer<BreakerProps>( Widget build(BuildContext context) {
return Consumer<BreakerProps>(
builder: (context, value, child) { builder: (context, value, child) {
var blocked = value.isBlocked(widget.breaker); String? 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}");
} }
@ -29,4 +30,5 @@ class _BreakerState extends State<Breaker> {
return widget.child; return widget.child;
}, },
); );
}
} }

View File

@ -1,4 +1,4 @@
import 'package:package_info_plus/package_info_plus.dart'; import 'package:package_info/package_info.dart';
import '../../api/apiResponse.dart'; import '../../api/apiResponse.dart';
import '../../api/mhsl/breaker/getBreakers/getBreakersCache.dart'; import '../../api/mhsl/breaker/getBreakers/getBreakersCache.dart';
@ -18,13 +18,13 @@ class BreakerProps extends DataHolder {
} }
if(primaryLoading()) return null; if(primaryLoading()) return null;
var breakers = _getBreakersResponse!; GetBreakersResponse breakers = _getBreakersResponse!;
if(breakers.global.areas.contains(type)) return breakers.global.message; if(breakers.global.areas.contains(type)) return breakers.global.message;
var selfVersion = int.parse(packageInfo!.buildNumber); int selfVersion = int.parse(packageInfo!.buildNumber);
for(var key in breakers.regional.keys) { for(var key in breakers.regional.keys) {
var value = breakers.regional[key]!; GetBreakersReponseObject 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,7 +35,9 @@ class BreakerProps extends DataHolder {
} }
@override @override
List<ApiResponse?> properties() => [_getBreakersResponse]; List<ApiResponse?> properties() {
return [_getBreakersResponse];
}
@override @override
void run() { void run() {

View File

@ -1,5 +1,5 @@
import 'package:flutter_app_badge/flutter_app_badge.dart'; import 'package:flutter_app_badger/flutter_app_badger.dart';
import '../../api/apiResponse.dart'; import '../../api/apiResponse.dart';
import '../../api/marianumcloud/talk/room/getRoomCache.dart'; import '../../api/marianumcloud/talk/room/getRoomCache.dart';
@ -11,7 +11,9 @@ class ChatListProps extends DataHolder {
GetRoomResponse get getRoomsResponse => _getRoomResponse!; GetRoomResponse get getRoomsResponse => _getRoomResponse!;
@override @override
List<ApiResponse?> properties() => [_getRoomResponse]; List<ApiResponse?> properties() {
return [_getRoomResponse];
}
@override @override
void run({renew}) { void run({renew}) {
@ -20,7 +22,7 @@ class ChatListProps extends DataHolder {
onUpdate: (GetRoomResponse data) => { onUpdate: (GetRoomResponse data) => {
_getRoomResponse = data, _getRoomResponse = data,
notifyListeners(), notifyListeners(),
FlutterAppBadge.count(data.data.map((e) => e.unreadMessages).reduce((a, b) => a+b)) FlutterAppBadger.updateBadgeCount(data.data.map((e) => e.unreadMessages).reduce((a, b) => a+b))
} }
); );
} }

View File

@ -1,31 +1,25 @@
import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';
import '../../api/apiResponse.dart'; import '../../api/apiResponse.dart';
import '../../api/marianumcloud/talk/chat/getChatCache.dart'; import '../../api/marianumcloud/talk/chat/getChatCache.dart';
import '../../api/marianumcloud/talk/chat/getChatResponse.dart'; import '../../api/marianumcloud/talk/chat/getChatResponse.dart';
import '../../storage/base/settingsProvider.dart';
import '../dataHolder.dart'; import '../dataHolder.dart';
class ChatProps extends DataHolder { class ChatProps extends DataHolder {
String _queryToken = ''; String _queryToken = '';
DateTime _lastTokenSet = DateTime.now(); DateTime _lastTokenSet = DateTime.now();
int? _referenceMessageId;
GetChatResponse? _getChatResponse; GetChatResponse? _getChatResponse;
GetChatResponse get getChatResponse => _getChatResponse!; GetChatResponse get getChatResponse => _getChatResponse!;
int? get getReferenceMessageId => _referenceMessageId;
set unsafeInternalSetReferenceMessageId(int? reference) => _referenceMessageId = reference;
@override @override
List<ApiResponse?> properties() => [_getChatResponse]; List<ApiResponse?> properties() {
return [_getChatResponse];
}
@override @override
void run() { void run() {
notifyListeners(); notifyListeners();
if(_queryToken.isEmpty) return; if(_queryToken.isEmpty) return;
var requestStart = DateTime.now(); DateTime requestStart = DateTime.now();
GetChatCache( GetChatCache(
chatToken: _queryToken, chatToken: _queryToken,
@ -38,20 +32,6 @@ class ChatProps extends DataHolder {
); );
} }
void setReferenceMessageId(int? messageId, BuildContext context, String sendToToken) {
Future.microtask(() {
_referenceMessageId = messageId;
notifyListeners();
var settings = Provider.of<SettingsProvider>(context, listen: false);
if(messageId != null) {
settings.val(write: true).talkSettings.draftReplies[sendToToken] = messageId;
} else {
settings.val(write: true).talkSettings.draftReplies.removeWhere((key, value) => key == sendToToken);
}
});
}
void setQueryToken(String token) { void setQueryToken(String token) {
_queryToken = token; _queryToken = token;
_getChatResponse = null; _getChatResponse = null;
@ -59,5 +39,7 @@ class ChatProps extends DataHolder {
run(); run();
} }
String currentToken() => _queryToken; String currentToken() {
return _queryToken;
}
} }

View File

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

View File

@ -6,14 +6,16 @@ import '../api/apiResponse.dart';
abstract class DataHolder extends ChangeNotifier { abstract class DataHolder extends ChangeNotifier {
CollectionRef storage(String path) => Localstore.instance.collection(path); CollectionRef storage(String 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(var element in properties()) { for(ApiResponse? element in properties()) {
if(element == null) return true; if(element == null) return true;
} }
return false; return false;

View File

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

View File

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

View File

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

View File

@ -0,0 +1,27 @@
import '../../api/apiResponse.dart';
import '../../api/mhsl/message/getMessages/getMessagesCache.dart';
import '../../api/mhsl/message/getMessages/getMessagesResponse.dart';
import '../dataHolder.dart';
class MessageProps extends DataHolder {
GetMessagesResponse? _getMessagesResponse;
GetMessagesResponse get getMessagesResponse => _getMessagesResponse!;
@override
List<ApiResponse?> properties() {
return [_getMessagesResponse];
}
@override
void run({renew}) {
GetMessagesCache(
renew: renew,
onUpdate: (GetMessagesResponse data) => {
_getMessagesResponse = data,
notifyListeners(),
}
);
}
}

View File

@ -42,7 +42,9 @@ class TimetableProps extends DataHolder {
bool get hasError => error != null; bool get hasError => error != null;
@override @override
List<ApiResponse?> properties() => [_getTimetableResponse, _getRoomsResponse, _getSubjectsResponse, _getHolidaysResponse, _getCustomTimetableEventResponse]; List<ApiResponse?> properties() {
return [_getTimetableResponse, _getRoomsResponse, _getSubjectsResponse, _getHolidaysResponse, _getCustomTimetableEventResponse];
}
@override @override
void run({renew}) { void run({renew}) {
@ -99,7 +101,9 @@ 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) => queryDate.weekday == DateTime.saturday || queryDate.weekday == DateTime.sunday; bool isWeekend(DateTime queryDate) {
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);
@ -119,7 +123,7 @@ class TimetableProps extends DataHolder {
error = null; error = null;
notifyListeners(); notifyListeners();
var queryWeek = DateTime.now().add(const Duration(days: 2)); DateTime 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,22 +3,27 @@ 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() => _instance; factory NotificationService() {
return _instance;
}
NotificationService._internal(); NotificationService._internal();
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
Future<void> initializeNotifications() async { Future<void> initializeNotifications() async {
const androidSettings = AndroidInitializationSettings( const AndroidInitializationSettings androidSettings = AndroidInitializationSettings(
'@mipmap/ic_launcher' '@mipmap/ic_launcher'
); );
final iosSettings = DarwinInitializationSettings( final DarwinInitializationSettings iosSettings = DarwinInitializationSettings(
onDidReceiveLocalNotification: (id, title, body, payload) {
// TODO Navigate to Talk section (This runs when an Notification is tapped)
},
); );
final initializationSettings = InitializationSettings( final InitializationSettings initializationSettings = InitializationSettings(
android: androidSettings, android: androidSettings,
iOS: iosSettings, iOS: iosSettings,
); );
@ -29,7 +34,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 androidPlatformChannelSpecifics = const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails( AndroidNotificationDetails(
'marmobile', 'marmobile',
'Marianum Fulda', 'Marianum Fulda',
@ -38,9 +43,9 @@ class NotificationService {
ticker: 'Marianum Fulda', ticker: 'Marianum Fulda',
); );
const iosPlatformChannelSpecifics = DarwinNotificationDetails(); const DarwinNotificationDetails iosPlatformChannelSpecifics = DarwinNotificationDetails();
const platformChannelSpecifics = NotificationDetails( const NotificationDetails platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics, android: androidPlatformChannelSpecifics,
iOS: iosPlatformChannelSpecifics iOS: iosPlatformChannelSpecifics
); );

View File

@ -1,15 +1,15 @@
import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter_app_badge/flutter_app_badge.dart'; import 'package:flutter_app_badger/flutter_app_badger.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import '../main.dart'; import '../app.dart';
import '../model/chatList/chatListProps.dart'; import '../model/chatList/chatListProps.dart';
import '../model/chatList/chatProps.dart'; import '../model/chatList/chatProps.dart';
class NotificationTasks { class NotificationTasks {
static void updateBadgeCount(RemoteMessage notification) { static void updateBadgeCount(RemoteMessage notification) {
FlutterAppBadge.count(int.parse(notification.data['unreadCount'] ?? 0)); FlutterAppBadger.updateBadgeCount(int.parse(notification.data['unreadCount'] ?? 0));
} }
static void updateProviders(BuildContext context) { static void updateProviders(BuildContext context) {
@ -18,6 +18,6 @@ class NotificationTasks {
} }
static void navigateToTalk() { static void navigateToTalk() {
Main.bottomNavigator.jumpToTab(1); App.bottomNavigator.jumpToTab(1);
} }
} }

View File

@ -8,7 +8,8 @@ import '../storage/base/settingsProvider.dart';
import '../widget/confirmDialog.dart'; import '../widget/confirmDialog.dart';
class NotifyUpdater { class NotifyUpdater {
static ConfirmDialog enableAfterDisclaimer(SettingsProvider settings) => ConfirmDialog( static ConfirmDialog enableAfterDisclaimer(SettingsProvider settings) {
return ConfirmDialog(
title: 'Warnung', title: 'Warnung',
icon: Icons.warning_amber, icon: Icons.warning_amber,
content: '' content: ''
@ -24,9 +25,9 @@ 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

@ -1,9 +0,0 @@
import 'package:dio/dio.dart';
import '../../infrastructure/dataLoader/data_loader.dart';
abstract class HolidayDataLoader<TResult> extends DataLoader<TResult> {
HolidayDataLoader() : super(Dio(BaseOptions(
baseUrl: 'https://ferien-api.de/api/v1/',
)));
}

View File

@ -1,9 +0,0 @@
import 'package:dio/dio.dart';
import '../../infrastructure/dataLoader/data_loader.dart';
abstract class MhslDataLoader<TResult> extends DataLoader<TResult> {
MhslDataLoader() : super(Dio(BaseOptions(
baseUrl: 'https://mhsl.eu/marianum/marianummobile/'
)));
}

View File

@ -1,46 +0,0 @@
import 'dart:convert';
import 'dart:developer';
import 'package:dio/dio.dart';
abstract class DataLoader<TResult> {
final Dio dio;
DataLoader(this.dio) {
dio.options.connectTimeout = const Duration(seconds: 10).inMilliseconds;
dio.options.sendTimeout = const Duration(seconds: 30).inMilliseconds;
dio.options.receiveTimeout = const Duration(seconds: 30).inMilliseconds;
}
Future<TResult> run() async {
var fetcher = fetch();
await Future.wait([
fetcher,
Future.delayed(const Duration(milliseconds: 500)) // TODO tune or remove
]);
var response = await fetcher;
try {
return assemble(DataLoaderResult(
json: jsonDecode(response.data!),
headers: response.headers.map.map((key, value) => MapEntry(key, value.join(';'))),
));
} catch(trace, e) {
log(trace.toString());
throw(e);
}
}
Future<Response<String>> fetch();
TResult assemble(DataLoaderResult data);
}
class DataLoaderResult {
final dynamic json;
final Map<String, String> headers;
Map<String, dynamic> asMap() => json as Map<String, dynamic>;
List<dynamic> asList() => json as List<dynamic>;
List<Map<String, dynamic>> asListOfMaps() => asList().map((e) => e as Map<String, dynamic>).toList();
DataLoaderResult({required this.json, required this.headers});
}

View File

@ -1,55 +0,0 @@
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:jiffy/jiffy.dart';
import 'loadable_state_event.dart';
import 'loadable_state_state.dart';
class LoadableStateBloc extends Bloc<LoadableStateEvent, LoadableStateState> {
late StreamSubscription<List<ConnectivityResult>> _updateStream;
void Function()? reFetch;
LoadableStateBloc() : super(const LoadableStateState(connections: null)) {
on<ConnectivityChanged>((event, emit) {
emit(event.state);
if(connectivityStatusKnown() && isConnected()) {
if(reFetch == null) return;
reFetch!();
}
});
emitConnectivity(List<ConnectivityResult> result) => add(ConnectivityChanged(LoadableStateState(connections: result)));
Connectivity().checkConnectivity().then(emitConnectivity);
_updateStream = Connectivity().onConnectivityChanged.listen(emitConnectivity);
}
bool connectivityStatusKnown() => state.connections != null;
bool isConnected() => !(state.connections?.contains(ConnectivityResult.none) ?? true);
bool allowRetry() => reFetch != null;
IconData connectionIcon() => connectivityStatusKnown()
? isConnected()
? Icons.nearby_error
: Icons.signal_wifi_connected_no_internet_4
: Icons.device_unknown;
Color connectionColor(BuildContext context) => connectivityStatusKnown() && !isConnected()
? Colors.grey.shade600
: Theme.of(context).primaryColor;
String connectionText({int? lastUpdated}) => connectivityStatusKnown()
? isConnected()
? 'Verbindung fehlgeschlagen'
: 'Offline${lastUpdated == null ? '' : ' - Stand von ${Jiffy.parseFromMillisecondsSinceEpoch(lastUpdated).fromNow()}'}'
: 'Unbekannte Fehlerursache';
@override
Future<void> close() {
_updateStream.cancel();
return super.close();
}
}

View File

@ -1,7 +0,0 @@
import 'loadable_state_state.dart';
sealed class LoadableStateEvent {}
final class ConnectivityChanged extends LoadableStateEvent {
final LoadableStateState state;
ConnectivityChanged(this.state);
}

View File

@ -1,11 +0,0 @@
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'loadable_state_state.freezed.dart';
@freezed
class LoadableStateState with _$LoadableStateState {
const factory LoadableStateState({
required List<ConnectivityResult>? connections,
}) = _LoadableStateState;
}

View File

@ -1,147 +0,0 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'loadable_state_state.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
T _$identity<T>(T value) => value;
final _privateConstructorUsedError = UnsupportedError(
'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models');
/// @nodoc
mixin _$LoadableStateState {
List<ConnectivityResult>? get connections =>
throw _privateConstructorUsedError;
@JsonKey(ignore: true)
$LoadableStateStateCopyWith<LoadableStateState> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $LoadableStateStateCopyWith<$Res> {
factory $LoadableStateStateCopyWith(
LoadableStateState value, $Res Function(LoadableStateState) then) =
_$LoadableStateStateCopyWithImpl<$Res, LoadableStateState>;
@useResult
$Res call({List<ConnectivityResult>? connections});
}
/// @nodoc
class _$LoadableStateStateCopyWithImpl<$Res, $Val extends LoadableStateState>
implements $LoadableStateStateCopyWith<$Res> {
_$LoadableStateStateCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
@pragma('vm:prefer-inline')
@override
$Res call({
Object? connections = freezed,
}) {
return _then(_value.copyWith(
connections: freezed == connections
? _value.connections
: connections // ignore: cast_nullable_to_non_nullable
as List<ConnectivityResult>?,
) as $Val);
}
}
/// @nodoc
abstract class _$$LoadableStateStateImplCopyWith<$Res>
implements $LoadableStateStateCopyWith<$Res> {
factory _$$LoadableStateStateImplCopyWith(_$LoadableStateStateImpl value,
$Res Function(_$LoadableStateStateImpl) then) =
__$$LoadableStateStateImplCopyWithImpl<$Res>;
@override
@useResult
$Res call({List<ConnectivityResult>? connections});
}
/// @nodoc
class __$$LoadableStateStateImplCopyWithImpl<$Res>
extends _$LoadableStateStateCopyWithImpl<$Res, _$LoadableStateStateImpl>
implements _$$LoadableStateStateImplCopyWith<$Res> {
__$$LoadableStateStateImplCopyWithImpl(_$LoadableStateStateImpl _value,
$Res Function(_$LoadableStateStateImpl) _then)
: super(_value, _then);
@pragma('vm:prefer-inline')
@override
$Res call({
Object? connections = freezed,
}) {
return _then(_$LoadableStateStateImpl(
connections: freezed == connections
? _value._connections
: connections // ignore: cast_nullable_to_non_nullable
as List<ConnectivityResult>?,
));
}
}
/// @nodoc
class _$LoadableStateStateImpl implements _LoadableStateState {
const _$LoadableStateStateImpl(
{required final List<ConnectivityResult>? connections})
: _connections = connections;
final List<ConnectivityResult>? _connections;
@override
List<ConnectivityResult>? get connections {
final value = _connections;
if (value == null) return null;
if (_connections is EqualUnmodifiableListView) return _connections;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(value);
}
@override
String toString() {
return 'LoadableStateState(connections: $connections)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$LoadableStateStateImpl &&
const DeepCollectionEquality()
.equals(other._connections, _connections));
}
@override
int get hashCode => Object.hash(
runtimeType, const DeepCollectionEquality().hash(_connections));
@JsonKey(ignore: true)
@override
@pragma('vm:prefer-inline')
_$$LoadableStateStateImplCopyWith<_$LoadableStateStateImpl> get copyWith =>
__$$LoadableStateStateImplCopyWithImpl<_$LoadableStateStateImpl>(
this, _$identity);
}
abstract class _LoadableStateState implements LoadableStateState {
const factory _LoadableStateState(
{required final List<ConnectivityResult>? connections}) =
_$LoadableStateStateImpl;
@override
List<ConnectivityResult>? get connections;
@override
@JsonKey(ignore: true)
_$$LoadableStateStateImplCopyWith<_$LoadableStateStateImpl> get copyWith =>
throw _privateConstructorUsedError;
}

View File

@ -1,27 +0,0 @@
import 'package:freezed_annotation/freezed_annotation.dart';
import 'loading_error.dart';
part 'loadable_state.freezed.dart';
@freezed
class LoadableState<TState> with _$LoadableState {
const LoadableState._();
const factory LoadableState({
required bool isLoading,
required TState? data,
required int? lastFetch,
required void Function()? reFetch,
required LoadingError? error,
}) = _LoadableState;
bool _hasError() => error != null;
bool _hasData() => data != null;
bool showPrimaryLoading() => isLoading && !_hasData();
bool showBackgroundLoading() => isLoading && _hasData();
bool showErrorBar() => _hasError() && _hasData();
bool showError() => _hasError() && !_hasData();
bool showContent() => _hasData();
}

View File

@ -1,246 +0,0 @@
// coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'loadable_state.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
T _$identity<T>(T value) => value;
final _privateConstructorUsedError = UnsupportedError(
'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models');
/// @nodoc
mixin _$LoadableState<TState> {
bool get isLoading => throw _privateConstructorUsedError;
TState? get data => throw _privateConstructorUsedError;
int? get lastFetch => throw _privateConstructorUsedError;
void Function()? get reFetch => throw _privateConstructorUsedError;
LoadingError? get error => throw _privateConstructorUsedError;
@JsonKey(ignore: true)
$LoadableStateCopyWith<TState, LoadableState<TState>> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $LoadableStateCopyWith<TState, $Res> {
factory $LoadableStateCopyWith(LoadableState<TState> value,
$Res Function(LoadableState<TState>) then) =
_$LoadableStateCopyWithImpl<TState, $Res, LoadableState<TState>>;
@useResult
$Res call(
{bool isLoading,
TState? data,
int? lastFetch,
void Function()? reFetch,
LoadingError? error});
$LoadingErrorCopyWith<$Res>? get error;
}
/// @nodoc
class _$LoadableStateCopyWithImpl<TState, $Res,
$Val extends LoadableState<TState>>
implements $LoadableStateCopyWith<TState, $Res> {
_$LoadableStateCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
@pragma('vm:prefer-inline')
@override
$Res call({
Object? isLoading = null,
Object? data = freezed,
Object? lastFetch = freezed,
Object? reFetch = freezed,
Object? error = freezed,
}) {
return _then(_value.copyWith(
isLoading: null == isLoading
? _value.isLoading
: isLoading // ignore: cast_nullable_to_non_nullable
as bool,
data: freezed == data
? _value.data
: data // ignore: cast_nullable_to_non_nullable
as TState?,
lastFetch: freezed == lastFetch
? _value.lastFetch
: lastFetch // ignore: cast_nullable_to_non_nullable
as int?,
reFetch: freezed == reFetch
? _value.reFetch
: reFetch // ignore: cast_nullable_to_non_nullable
as void Function()?,
error: freezed == error
? _value.error
: error // ignore: cast_nullable_to_non_nullable
as LoadingError?,
) as $Val);
}
@override
@pragma('vm:prefer-inline')
$LoadingErrorCopyWith<$Res>? get error {
if (_value.error == null) {
return null;
}
return $LoadingErrorCopyWith<$Res>(_value.error!, (value) {
return _then(_value.copyWith(error: value) as $Val);
});
}
}
/// @nodoc
abstract class _$$LoadableStateImplCopyWith<TState, $Res>
implements $LoadableStateCopyWith<TState, $Res> {
factory _$$LoadableStateImplCopyWith(_$LoadableStateImpl<TState> value,
$Res Function(_$LoadableStateImpl<TState>) then) =
__$$LoadableStateImplCopyWithImpl<TState, $Res>;
@override
@useResult
$Res call(
{bool isLoading,
TState? data,
int? lastFetch,
void Function()? reFetch,
LoadingError? error});
@override
$LoadingErrorCopyWith<$Res>? get error;
}
/// @nodoc
class __$$LoadableStateImplCopyWithImpl<TState, $Res>
extends _$LoadableStateCopyWithImpl<TState, $Res,
_$LoadableStateImpl<TState>>
implements _$$LoadableStateImplCopyWith<TState, $Res> {
__$$LoadableStateImplCopyWithImpl(_$LoadableStateImpl<TState> _value,
$Res Function(_$LoadableStateImpl<TState>) _then)
: super(_value, _then);
@pragma('vm:prefer-inline')
@override
$Res call({
Object? isLoading = null,
Object? data = freezed,
Object? lastFetch = freezed,
Object? reFetch = freezed,
Object? error = freezed,
}) {
return _then(_$LoadableStateImpl<TState>(
isLoading: null == isLoading
? _value.isLoading
: isLoading // ignore: cast_nullable_to_non_nullable
as bool,
data: freezed == data
? _value.data
: data // ignore: cast_nullable_to_non_nullable
as TState?,
lastFetch: freezed == lastFetch
? _value.lastFetch
: lastFetch // ignore: cast_nullable_to_non_nullable
as int?,
reFetch: freezed == reFetch
? _value.reFetch
: reFetch // ignore: cast_nullable_to_non_nullable
as void Function()?,
error: freezed == error
? _value.error
: error // ignore: cast_nullable_to_non_nullable
as LoadingError?,
));
}
}
/// @nodoc
class _$LoadableStateImpl<TState> extends _LoadableState<TState> {
const _$LoadableStateImpl(
{this.isLoading = true,
this.data = null,
this.lastFetch = null,
this.reFetch = null,
this.error = null})
: super._();
@override
@JsonKey()
final bool isLoading;
@override
@JsonKey()
final TState? data;
@override
@JsonKey()
final int? lastFetch;
@override
@JsonKey()
final void Function()? reFetch;
@override
@JsonKey()
final LoadingError? error;
@override
String toString() {
return 'LoadableState<$TState>(isLoading: $isLoading, data: $data, lastFetch: $lastFetch, reFetch: $reFetch, error: $error)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$LoadableStateImpl<TState> &&
(identical(other.isLoading, isLoading) ||
other.isLoading == isLoading) &&
const DeepCollectionEquality().equals(other.data, data) &&
(identical(other.lastFetch, lastFetch) ||
other.lastFetch == lastFetch) &&
(identical(other.reFetch, reFetch) || other.reFetch == reFetch) &&
(identical(other.error, error) || other.error == error));
}
@override
int get hashCode => Object.hash(runtimeType, isLoading,
const DeepCollectionEquality().hash(data), lastFetch, reFetch, error);
@JsonKey(ignore: true)
@override
@pragma('vm:prefer-inline')
_$$LoadableStateImplCopyWith<TState, _$LoadableStateImpl<TState>>
get copyWith => __$$LoadableStateImplCopyWithImpl<TState,
_$LoadableStateImpl<TState>>(this, _$identity);
}
abstract class _LoadableState<TState> extends LoadableState<TState> {
const factory _LoadableState(
{final bool isLoading,
final TState? data,
final int? lastFetch,
final void Function()? reFetch,
final LoadingError? error}) = _$LoadableStateImpl<TState>;
const _LoadableState._() : super._();
@override
bool get isLoading;
@override
TState? get data;
@override
int? get lastFetch;
@override
void Function()? get reFetch;
@override
LoadingError? get error;
@override
@JsonKey(ignore: true)
_$$LoadableStateImplCopyWith<TState, _$LoadableStateImpl<TState>>
get copyWith => throw _privateConstructorUsedError;
}

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