kopia lustrzana https://gitlab.com/mysocialportal/relatica
87 wiersze
2.2 KiB
Dart
87 wiersze
2.2 KiB
Dart
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import 'package:logging/logging.dart';
|
|
import 'package:path/path.dart' as p;
|
|
import 'package:result_monad/result_monad.dart';
|
|
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
|
import 'package:stack_trace/stack_trace.dart';
|
|
|
|
import '../models/auth/profile.dart';
|
|
import 'globals_services.dart';
|
|
|
|
part 'persistent_info_services.g.dart';
|
|
|
|
final _logger = Logger('PersistentInfoProvider');
|
|
|
|
@Riverpod(keepAlive: true)
|
|
class PersistentInfo extends _$PersistentInfo {
|
|
@override
|
|
DateTime build(Profile profile) {
|
|
load();
|
|
return DateTime(1970, 1, 1);
|
|
}
|
|
|
|
Future<void> updateLastMyConnectionUpdate(DateTime value) async {
|
|
state = value;
|
|
await save();
|
|
}
|
|
|
|
void load() {
|
|
final file = File(filePath);
|
|
if (!file.existsSync()) {
|
|
return;
|
|
}
|
|
|
|
Result.ok('')
|
|
.transform((_) => File(filePath).readAsStringSync())
|
|
.transform((str) => jsonDecode(str))
|
|
.transform((json) => _PersistentInfo.fromJson(json))
|
|
.match(onSuccess: (info) {
|
|
state = info.lastMyConnectionsUpdate;
|
|
}, onError: (error) {
|
|
_logger.severe('Error reading Persistence: $error', Trace.current());
|
|
});
|
|
}
|
|
|
|
Future<void> save() async {
|
|
Result.ok(
|
|
_PersistentInfo(
|
|
lastMyConnectionsUpdate: state,
|
|
).toJson(),
|
|
)
|
|
.transform((json) => jsonEncode(json))
|
|
.withResultAsync((json) async => File(filePath).writeAsString(json))
|
|
.withError(
|
|
(error) => _logger.severe(
|
|
'Error reading Persistence: $error',
|
|
Trace.current(),
|
|
),
|
|
);
|
|
}
|
|
|
|
String get filePath {
|
|
final appSupportDir = ref.watch(applicationSupportDirectoryProvider);
|
|
return p.join(appSupportDir.path, '${profile.id}.json');
|
|
}
|
|
}
|
|
|
|
class _PersistentInfo {
|
|
final DateTime lastMyConnectionsUpdate;
|
|
|
|
const _PersistentInfo({
|
|
required this.lastMyConnectionsUpdate,
|
|
});
|
|
|
|
Map<String, dynamic> toJson() => {
|
|
'lastMyConnectionsUpdate': lastMyConnectionsUpdate.toIso8601String(),
|
|
};
|
|
|
|
factory _PersistentInfo.fromJson(Map<String, dynamic> json) =>
|
|
_PersistentInfo(
|
|
lastMyConnectionsUpdate:
|
|
DateTime.tryParse(json['lastMyConnectionsUpdate']) ??
|
|
DateTime(1970),
|
|
);
|
|
}
|