2022-04-01 18:59:18 +02:00
|
|
|
import 'dart:async';
|
|
|
|
import 'dart:convert';
|
|
|
|
|
|
|
|
import 'package:logging/logging.dart';
|
2022-05-03 19:37:10 +02:00
|
|
|
import 'package:nc_photos/stream_extension.dart';
|
2022-04-01 18:59:18 +02:00
|
|
|
import 'package:nc_photos_plugin/nc_photos_plugin.dart';
|
|
|
|
|
|
|
|
class NativeEventListener<T> {
|
|
|
|
NativeEventListener(this.listener);
|
|
|
|
|
|
|
|
void begin() {
|
|
|
|
if (_subscription != null) {
|
|
|
|
_log.warning("[begin] Already listening");
|
|
|
|
return;
|
|
|
|
}
|
2022-05-03 19:37:10 +02:00
|
|
|
_subscription = _mappedStream.whereType<T>().listen(listener);
|
2022-04-01 18:59:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
void end() {
|
|
|
|
if (_subscription == null) {
|
|
|
|
_log.warning("[end] Already not listening");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
_subscription?.cancel();
|
|
|
|
_subscription = null;
|
|
|
|
}
|
|
|
|
|
2022-07-08 16:52:18 +02:00
|
|
|
static final _mappedStream =
|
2022-05-03 19:37:10 +02:00
|
|
|
NativeEvent.stream.whereType<NativeEventObject>().map((ev) {
|
2022-04-01 18:59:18 +02:00
|
|
|
switch (ev.event) {
|
|
|
|
case FileExifUpdatedEvent._id:
|
|
|
|
return FileExifUpdatedEvent.fromEvent(ev);
|
|
|
|
|
2022-09-10 06:03:49 +02:00
|
|
|
case ImageProcessorUploadSuccessEvent._id:
|
|
|
|
return ImageProcessorUploadSuccessEvent.fromEvent(ev);
|
|
|
|
|
2022-04-01 18:59:18 +02:00
|
|
|
default:
|
|
|
|
throw ArgumentError("Invalid event: ${ev.event}");
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
final void Function(T) listener;
|
|
|
|
StreamSubscription<T>? _subscription;
|
|
|
|
|
2022-12-16 16:01:04 +01:00
|
|
|
final _log = Logger("event.native_event.NativeEventListener<${T.runtimeType}>");
|
2022-04-01 18:59:18 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
class FileExifUpdatedEvent {
|
|
|
|
const FileExifUpdatedEvent(this.fileIds);
|
|
|
|
|
|
|
|
factory FileExifUpdatedEvent.fromEvent(NativeEventObject ev) {
|
|
|
|
assert(ev.event == _id);
|
|
|
|
assert(ev.data != null);
|
|
|
|
final dataJson = jsonDecode(ev.data!) as Map;
|
|
|
|
return FileExifUpdatedEvent((dataJson["fileIds"] as List).cast<int>());
|
|
|
|
}
|
|
|
|
|
|
|
|
NativeEventObject toEvent() => NativeEventObject(
|
|
|
|
_id,
|
|
|
|
jsonEncode({
|
|
|
|
"fileIds": fileIds,
|
|
|
|
}),
|
|
|
|
);
|
|
|
|
|
|
|
|
static const _id = "FileExifUpdatedEvent";
|
|
|
|
|
|
|
|
final List<int> fileIds;
|
|
|
|
}
|
2022-09-10 06:03:49 +02:00
|
|
|
|
|
|
|
class ImageProcessorUploadSuccessEvent {
|
|
|
|
const ImageProcessorUploadSuccessEvent();
|
|
|
|
|
|
|
|
factory ImageProcessorUploadSuccessEvent.fromEvent(NativeEventObject ev) {
|
|
|
|
assert(ev.event == _id);
|
|
|
|
assert(ev.data == null);
|
|
|
|
return const ImageProcessorUploadSuccessEvent();
|
|
|
|
}
|
|
|
|
|
|
|
|
static const _id = "ImageProcessorUploadSuccessEvent";
|
|
|
|
}
|