-
Notifications
You must be signed in to change notification settings - Fork 17
/
codec.dart
1109 lines (1036 loc) · 41.6 KB
/
codec.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import '../../authentication/authentication.dart';
import '../../error/error.dart';
import '../../generated/platform_constants.dart';
import '../../message/message.dart';
import '../../push_notifications/push_notifications.dart';
import '../../push_notifications/src/local_device.dart';
import '../../realtime/realtime.dart';
import '../../realtime/src/realtime_channel_options.dart';
import '../../rest/rest.dart';
import '../platform.dart';
/// a [_Encoder] encodes custom type and converts it to a Map which will
/// be passed on to platform side
typedef _Encoder<T> = Map<String, dynamic>? Function(T value);
/// a [_Decoder] decodes Map received from platform side and converts to
/// to respective dart types
typedef _Decoder<T> = T Function(Map<String, dynamic> jsonMap);
/// A class to manage encoding/decoding by provided encoder/decoder functions.
class _CodecPair<T> {
final _Encoder<T>? _encoder;
final _Decoder<T>? _decoder;
_CodecPair(this._encoder, this._decoder);
/// Convert properties from an ably library object instance (dart) to Map.
/// if passed [value] is null, encoder will not be called.
/// This method will throw an [AblyException] if encoder is null.
Map<String, dynamic>? encode(final Object? value) {
if (_encoder == null) throw AblyException('Codec encoder is null');
if (value == null) return null;
return _encoder!(value as T);
}
/// Convert Map entries to an ably library object instance (dart).
/// if passed [jsonMap] is null, decoder will not be called.
/// This method will throw an [AblyException] if decoder is null.
T? decode(Map<String, dynamic>? jsonMap) {
if (_decoder == null) throw AblyException('Codec decoder is null');
if (jsonMap == null) return null;
return _decoder!(jsonMap);
}
}
/// Custom message codec for encoding objects to send to platform
/// or decoding objects received from platform.
class Codec extends StandardMessageCodec {
/// Map of codec type (a value from [CodecTypes]) vs encoder/decoder pair.
/// Encoder/decoder can be null.
/// For example, [ErrorInfo] only needs a decoder but not an encoder.
late Map<int, _CodecPair> codecMap;
/// initializes codec with codec map linking codec type to codec pair
Codec() : super() {
codecMap = {
// Ably flutter plugin protocol message
CodecTypes.ablyMessage:
_CodecPair<AblyMessage>(_encodeAblyMessage, _decodeAblyMessage),
CodecTypes.ablyEventMessage:
_CodecPair<AblyEventMessage>(_encodeAblyEventMessage, null),
// Other ably objects
CodecTypes.clientOptions:
_CodecPair<ClientOptions>(_encodeClientOptions, _decodeClientOptions),
CodecTypes.tokenParams:
_CodecPair<TokenParams>(_encodeTokenParams, _decodeTokenParams),
CodecTypes.tokenDetails:
_CodecPair<TokenDetails>(_encodeTokenDetails, _decodeTokenDetails),
CodecTypes.tokenRequest:
_CodecPair<TokenRequest>(_encodeTokenRequest, null),
CodecTypes.restChannelOptions:
_CodecPair<RestChannelOptions>(_encodeRestChannelOptions, null),
CodecTypes.realtimeChannelOptions: _CodecPair<RealtimeChannelOptions>(
_encodeRealtimeChannelOptions,
null,
),
CodecTypes.paginatedResult:
_CodecPair<PaginatedResult>(null, _decodePaginatedResult),
CodecTypes.realtimeHistoryParams:
_CodecPair<RealtimeHistoryParams>(_encodeRealtimeHistoryParams, null),
CodecTypes.restHistoryParams:
_CodecPair<RestHistoryParams>(_encodeRestHistoryParams, null),
CodecTypes.restPresenceParams:
_CodecPair<RestPresenceParams>(_encodeRestPresenceParams, null),
CodecTypes.realtimePresenceParams: _CodecPair<RealtimePresenceParams>(
_encodeRealtimePresenceParams,
null,
),
// Push Notifications
CodecTypes.deviceDetails:
_CodecPair<DeviceDetails>(null, _decodeDeviceDetails),
CodecTypes.localDevice: _CodecPair<LocalDevice>(null, _decodeLocalDevice),
CodecTypes.pushChannelSubscription: _CodecPair<PushChannelSubscription>(
null, _decodePushChannelSubscription),
CodecTypes.unNotificationSettings: _CodecPair<UNNotificationSettings>(
null, _decodeUNNotificationSettings),
CodecTypes.remoteMessage:
_CodecPair<RemoteMessage>(null, _decodeRemoteMessage),
CodecTypes.errorInfo:
_CodecPair<ErrorInfo>(_encodeErrorInfo, _decodeErrorInfo),
CodecTypes.messageData: _CodecPair<MessageData?>(
_encodeChannelMessageData,
_decodeChannelMessageData,
),
CodecTypes.messageExtras: _CodecPair<MessageExtras?>(
_encodeChannelMessageExtras,
_decodeChannelMessageExtras,
),
CodecTypes.message:
_CodecPair<Message>(_encodeChannelMessage, _decodeChannelMessage),
CodecTypes.presenceMessage:
_CodecPair<PresenceMessage>(null, _decodePresenceMessage),
// Events - Connection
CodecTypes.connectionStateChange:
_CodecPair<ConnectionStateChange>(null, _decodeConnectionStateChange),
// Events - Channel
CodecTypes.channelStateChange:
_CodecPair<ChannelStateChange>(null, _decodeChannelStateChange),
};
}
/// Converts a Map with dynamic keys and values to
/// a Map with String keys and dynamic values.
/// Returns null of [value] is null.
Map<String, dynamic>? toJsonMap(Map<dynamic, dynamic>? value) {
if (value == null) return null;
return Map.castFrom<dynamic, dynamic, String, dynamic>(value);
}
/// Converts a Map with dynamic keys and values to
/// a Map with String keys and dynamic values.
/// Returns null of [value] is null.
Map<String, T> toTypedJsonMap<T>(Map<dynamic, dynamic>? value) {
if (value == null) return <String, T>{};
return Map.castFrom<dynamic, dynamic, String, T>(value);
}
/// Returns a value from [CodecTypes] based of the [Type] of [value]
int? getCodecType(final Object? value) {
if (value is ClientOptions) {
return CodecTypes.clientOptions;
} else if (value is TokenDetails) {
return CodecTypes.tokenDetails;
} else if (value is TokenParams) {
return CodecTypes.tokenParams;
} else if (value is TokenRequest) {
return CodecTypes.tokenRequest;
} else if (value is MessageData) {
return CodecTypes.messageData;
} else if (value is MessageExtras) {
return CodecTypes.messageExtras;
} else if (value is Message) {
return CodecTypes.message;
} else if (value is RealtimeHistoryParams) {
return CodecTypes.realtimeHistoryParams;
} else if (value is RestHistoryParams) {
return CodecTypes.restHistoryParams;
} else if (value is RestPresenceParams) {
return CodecTypes.restPresenceParams;
} else if (value is RealtimePresenceParams) {
return CodecTypes.realtimePresenceParams;
} else if (value is ErrorInfo) {
return CodecTypes.errorInfo;
} else if (value is AblyMessage) {
return CodecTypes.ablyMessage;
} else if (value is AblyEventMessage) {
return CodecTypes.ablyEventMessage;
}
// ignore: avoid_returning_null
return null;
}
/// Encodes values from [_CodecPair._encoder] available in [_CodecPair]
/// obtained from [codecMap] against codecType obtained from [value].
/// If decoder is not found, [StandardMessageCodec] is used to read value
@override
void writeValue(final WriteBuffer buffer, final Object? value) {
final type = getCodecType(value);
if (type == null) {
super.writeValue(buffer, value);
} else {
buffer.putUint8(type);
writeValue(buffer, codecMap[type]!.encode(value));
}
}
/// Decodes values from [_CodecPair._decoder] available in codec pair,
/// obtained from [codecMap] against [type].
/// If decoder is not found, [StandardMessageCodec] is used to read value
@override
dynamic readValueOfType(int type, ReadBuffer buffer) {
final pair = codecMap[type];
if (pair == null) {
return super.readValueOfType(type, buffer);
} else {
final map = toJsonMap(readValue(buffer) as Map?);
return pair.decode(map);
}
}
// =========== ENCODERS ===========
/// Writes [value] for [key] in [map] if [value] is not null
void _writeToJson(Map<String, dynamic> map, String key, Object? value) {
assert(value is! DateTime, '`DateTime` objects cannot be encoded');
if (value == null) return;
map[key] = value;
}
/// Encodes [ClientOptions] to a Map
/// returns null of [v] is null
Map<String, dynamic> _encodeClientOptions(final ClientOptions v) {
final jsonMap = <String, dynamic>{};
// AuthOptions (super class of ClientOptions)
_writeToJson(jsonMap, TxClientOptions.authUrl, v.authUrl);
_writeToJson(jsonMap, TxClientOptions.authMethod, v.authMethod);
_writeToJson(jsonMap, TxClientOptions.key, v.key);
_writeToJson(jsonMap, TxClientOptions.tokenDetails,
_encodeTokenDetails(v.tokenDetails));
_writeToJson(jsonMap, TxClientOptions.authHeaders, v.authHeaders);
_writeToJson(jsonMap, TxClientOptions.authParams, v.authParams);
_writeToJson(jsonMap, TxClientOptions.queryTime, v.queryTime);
_writeToJson(jsonMap, TxClientOptions.useTokenAuth, v.useTokenAuth);
_writeToJson(
jsonMap, TxClientOptions.hasAuthCallback, v.authCallback != null);
// ClientOptions
_writeToJson(jsonMap, TxClientOptions.clientId, v.clientId);
_writeToJson(jsonMap, TxClientOptions.logLevel, v.logLevel);
//TODO handle logHandler
_writeToJson(jsonMap, TxClientOptions.tls, v.tls);
_writeToJson(jsonMap, TxClientOptions.restHost, v.restHost);
_writeToJson(jsonMap, TxClientOptions.realtimeHost, v.realtimeHost);
_writeToJson(jsonMap, TxClientOptions.port, v.port);
_writeToJson(jsonMap, TxClientOptions.tlsPort, v.tlsPort);
_writeToJson(jsonMap, TxClientOptions.autoConnect, v.autoConnect);
_writeToJson(
jsonMap, TxClientOptions.useBinaryProtocol, v.useBinaryProtocol);
_writeToJson(jsonMap, TxClientOptions.queueMessages, v.queueMessages);
_writeToJson(jsonMap, TxClientOptions.echoMessages, v.echoMessages);
_writeToJson(jsonMap, TxClientOptions.recover, v.recover);
_writeToJson(jsonMap, TxClientOptions.environment, v.environment);
_writeToJson(jsonMap, TxClientOptions.idempotentRestPublishing,
v.idempotentRestPublishing);
_writeToJson(jsonMap, TxClientOptions.httpOpenTimeout, v.httpOpenTimeout);
_writeToJson(
jsonMap, TxClientOptions.httpRequestTimeout, v.httpRequestTimeout);
_writeToJson(
jsonMap, TxClientOptions.httpMaxRetryCount, v.httpMaxRetryCount);
_writeToJson(jsonMap, TxClientOptions.realtimeRequestTimeout,
v.realtimeRequestTimeout);
_writeToJson(jsonMap, TxClientOptions.fallbackHosts, v.fallbackHosts);
_writeToJson(jsonMap, TxClientOptions.fallbackHostsUseDefault,
v.fallbackHostsUseDefault);
_writeToJson(
jsonMap, TxClientOptions.fallbackRetryTimeout, v.fallbackRetryTimeout);
_writeToJson(jsonMap, TxClientOptions.defaultTokenParams,
_encodeTokenParams(v.defaultTokenParams));
_writeToJson(
jsonMap, TxClientOptions.channelRetryTimeout, v.channelRetryTimeout);
_writeToJson(jsonMap, TxClientOptions.transportParams, v.transportParams);
return jsonMap;
}
/// Encodes [TokenDetails] to a Map
/// returns null if [v] is null
Map<String, dynamic>? _encodeTokenDetails(final TokenDetails? v) {
if (v == null) return null;
return {
TxTokenDetails.token: v.token,
TxTokenDetails.expires: v.expires,
TxTokenDetails.issued: v.issued,
TxTokenDetails.capability: v.capability,
TxTokenDetails.clientId: v.clientId,
};
}
/// Encodes [TokenParams] to a Map
/// returns null if [v] is null
Map<String, dynamic>? _encodeTokenParams(final TokenParams? v) {
if (v == null) return null;
final jsonMap = <String, dynamic>{};
_writeToJson(jsonMap, TxTokenParams.capability, v.capability);
_writeToJson(jsonMap, TxTokenParams.clientId, v.clientId);
_writeToJson(jsonMap, TxTokenParams.nonce, v.nonce);
_writeToJson(jsonMap, TxTokenParams.timestamp, v.timestamp);
_writeToJson(jsonMap, TxTokenParams.ttl, v.ttl);
return jsonMap;
}
/// Encodes [TokenRequest] to a Map
/// returns null if [v] is null
Map<String, dynamic> _encodeTokenRequest(final TokenRequest v) {
final jsonMap = <String, dynamic>{};
_writeToJson(jsonMap, TxTokenRequest.capability, v.capability);
_writeToJson(jsonMap, TxTokenRequest.clientId, v.clientId);
_writeToJson(jsonMap, TxTokenRequest.keyName, v.keyName);
_writeToJson(jsonMap, TxTokenRequest.mac, v.mac);
_writeToJson(jsonMap, TxTokenRequest.nonce, v.nonce);
_writeToJson(
jsonMap, TxTokenRequest.timestamp, v.timestamp?.millisecondsSinceEpoch);
_writeToJson(jsonMap, TxTokenRequest.ttl, v.ttl);
return jsonMap;
}
/// Encodes [RestChannelOptions] to a Map
/// returns null if [v] is null
Map<String, dynamic> _encodeRestChannelOptions(final RestChannelOptions v) {
final jsonMap = <String, dynamic>{};
_writeToJson(jsonMap, TxRestChannelOptions.cipher, v.cipher);
return jsonMap;
}
/// Encodes [ChannelMode] to a string constant
String _encodeChannelMode(ChannelMode mode) {
switch (mode) {
case ChannelMode.presence:
return TxEnumConstants.presence;
case ChannelMode.publish:
return TxEnumConstants.publish;
case ChannelMode.subscribe:
return TxEnumConstants.subscribe;
case ChannelMode.presenceSubscribe:
return TxEnumConstants.presenceSubscribe;
}
}
/// Encodes [RealtimeChannelOptions] to a Map
/// returns null if [v] is null
Map<String, dynamic> _encodeRealtimeChannelOptions(
final RealtimeChannelOptions v) {
final jsonMap = <String, dynamic>{};
_writeToJson(jsonMap, TxRealtimeChannelOptions.cipher, v.cipher);
_writeToJson(jsonMap, TxRealtimeChannelOptions.params, v.params);
_writeToJson(
jsonMap,
TxRealtimeChannelOptions.modes,
v.modes?.map(_encodeChannelMode).toList(),
);
return jsonMap;
}
/// Encodes [RestHistoryParams] to a Map
/// returns null if [v] is null
Map<String, dynamic> _encodeRestHistoryParams(final RestHistoryParams v) {
final jsonMap = <String, dynamic>{};
_writeToJson(
jsonMap, TxRestHistoryParams.start, v.start.millisecondsSinceEpoch);
_writeToJson(
jsonMap, TxRestHistoryParams.end, v.end.millisecondsSinceEpoch);
_writeToJson(jsonMap, TxRestHistoryParams.direction, v.direction);
_writeToJson(jsonMap, TxRestHistoryParams.limit, v.limit);
return jsonMap;
}
/// Encodes [RestPresenceParams] to a Map
/// returns null if [v] is null
Map<String, dynamic> _encodeRestPresenceParams(final RestPresenceParams v) {
final jsonMap = <String, dynamic>{};
_writeToJson(jsonMap, TxRestPresenceParams.limit, v.limit);
_writeToJson(jsonMap, TxRestPresenceParams.clientId, v.clientId);
_writeToJson(jsonMap, TxRestPresenceParams.connectionId, v.connectionId);
return jsonMap;
}
Map<String, dynamic> _encodeRealtimePresenceParams(
final RealtimePresenceParams v) {
final jsonMap = <String, dynamic>{};
_writeToJson(jsonMap, TxRealtimePresenceParams.waitForSync, v.waitForSync);
_writeToJson(jsonMap, TxRealtimePresenceParams.clientId, v.clientId);
_writeToJson(
jsonMap, TxRealtimePresenceParams.connectionId, v.connectionId);
return jsonMap;
}
/// Encodes [RealtimeHistoryParams] to a Map
/// returns null of [v] is null
Map<String, dynamic> _encodeRealtimeHistoryParams(
final RealtimeHistoryParams v,
) {
final jsonMap = <String, dynamic>{};
_writeToJson(
jsonMap,
TxRealtimeHistoryParams.start,
v.start.millisecondsSinceEpoch,
);
_writeToJson(
jsonMap,
TxRealtimeHistoryParams.end,
v.end.millisecondsSinceEpoch,
);
_writeToJson(jsonMap, TxRealtimeHistoryParams.direction, v.direction);
_writeToJson(jsonMap, TxRealtimeHistoryParams.limit, v.limit);
_writeToJson(jsonMap, TxRealtimeHistoryParams.untilAttach, v.untilAttach);
return jsonMap;
}
/// Encodes [AblyMessage] to a Map
/// returns null of [v] is null
Map<String, dynamic> _encodeAblyMessage(final AblyMessage v) {
final codecType = getCodecType(v.message);
final message = (codecType == null)
? v.message
: codecMap[codecType]!.encode(v.message);
final jsonMap = <String, dynamic>{};
_writeToJson(jsonMap, TxAblyMessage.registrationHandle, v.handle);
_writeToJson(jsonMap, TxAblyMessage.type, codecType);
_writeToJson(jsonMap, TxAblyMessage.message, message);
return jsonMap;
}
/// Encodes [AblyEventMessage] to a Map
/// returns null of [v] is null
Map<String, dynamic> _encodeAblyEventMessage(final AblyEventMessage v) {
final codecType = getCodecType(v.message);
final message = (v.message == null)
? null
: (codecType == null)
? v.message
: codecMap[codecType]!.encode(v.message);
final jsonMap = <String, dynamic>{};
_writeToJson(jsonMap, TxAblyEventMessage.eventName, v.eventName);
_writeToJson(jsonMap, TxAblyEventMessage.type, codecType);
_writeToJson(jsonMap, TxAblyEventMessage.message, message);
return jsonMap;
}
/// Encodes [ErrorInfo] to a Map
/// returns null of [v] is null
Map<String, dynamic>? _encodeErrorInfo(final ErrorInfo? v) {
if (v == null) return null;
final jsonMap = <String, dynamic>{};
_writeToJson(jsonMap, TxErrorInfo.code, v.code);
_writeToJson(jsonMap, TxErrorInfo.message, v.message);
_writeToJson(jsonMap, TxErrorInfo.statusCode, v.statusCode);
_writeToJson(jsonMap, TxErrorInfo.href, v.href);
_writeToJson(jsonMap, TxErrorInfo.requestId, v.requestId);
_writeToJson(jsonMap, TxErrorInfo.cause, v.cause);
return jsonMap;
}
/// Encodes [MessageData] to a Map
/// returns null of [v] is null
Map<String, dynamic>? _encodeChannelMessageData(final MessageData? v) {
if (v == null) return null;
final jsonMap = <String, dynamic>{};
_writeToJson(jsonMap, TxMessageData.data, v.data);
return jsonMap;
}
/// Encodes [MessageExtras] to a Map
/// returns null of [v] is null
Map<String, dynamic>? _encodeChannelMessageExtras(final MessageExtras? v) {
if (v == null) return null;
final jsonMap = <String, dynamic>{};
// Not encoding `delta`, as it is a readonly extension
_writeToJson(jsonMap, TxMessageExtras.extras, v.map);
return jsonMap;
}
/// Encodes [Message] to a Map
/// returns null of [v] is null
Map<String, dynamic> _encodeChannelMessage(final Message v) {
final jsonMap = <String, dynamic>{};
// Note: connectionId and timestamp are automatically set by platform
// So they are suppressed on dart side
_writeToJson(jsonMap, TxMessage.name, v.name);
_writeToJson(jsonMap, TxMessage.clientId, v.clientId);
_writeToJson(jsonMap, TxMessage.data, v.data);
_writeToJson(jsonMap, TxMessage.id, v.id);
_writeToJson(jsonMap, TxMessage.encoding, v.encoding);
_writeToJson(jsonMap, TxMessage.extras, v.extras);
return jsonMap;
}
// =========== DECODERS ===========
/// Reads [key] value from [jsonMap]
/// Casts it to [T] if the value is not null
T? _readFromJson<T>(Map<String, dynamic> jsonMap, String key) {
final value = jsonMap[key];
if (value == null) return null;
return value as T;
}
/// Decodes value [jsonMap] to [ClientOptions]
/// returns null if [jsonMap] is null
ClientOptions _decodeClientOptions(Map<String, dynamic> jsonMap) {
final tokenDetails = toJsonMap(_readFromJson<Map>(
jsonMap,
TxClientOptions.tokenDetails,
));
final tokenParams = toJsonMap(_readFromJson<Map>(
jsonMap,
TxClientOptions.defaultTokenParams,
));
return ClientOptions()
// AuthOptions (super class of ClientOptions)
..authUrl = _readFromJson<String>(
jsonMap,
TxClientOptions.authUrl,
)
..authMethod = _readFromJson<String>(
jsonMap,
TxClientOptions.authMethod,
)
..key = _readFromJson<String>(
jsonMap,
TxClientOptions.key,
)
..tokenDetails =
(tokenDetails == null) ? null : _decodeTokenDetails(tokenDetails)
..authHeaders = _readFromJson<Map<String, String>>(
jsonMap,
TxClientOptions.authHeaders,
)
..authParams = _readFromJson<Map<String, String>>(
jsonMap,
TxClientOptions.authParams,
)
..queryTime = _readFromJson<bool>(
jsonMap,
TxClientOptions.queryTime,
)
..useTokenAuth = _readFromJson<bool>(
jsonMap,
TxClientOptions.useTokenAuth,
)
// ClientOptions
..clientId = _readFromJson<String>(
jsonMap,
TxClientOptions.clientId,
)
..logLevel = _readFromJson<int>(
jsonMap,
TxClientOptions.logLevel,
)
//TODO handle logHandler
..tls = _readFromJson<bool>(
jsonMap,
TxClientOptions.tls,
)
..restHost = _readFromJson<String>(
jsonMap,
TxClientOptions.restHost,
)
..realtimeHost = _readFromJson<String>(
jsonMap,
TxClientOptions.realtimeHost,
)
..port = _readFromJson<int>(
jsonMap,
TxClientOptions.port,
)
..tlsPort = _readFromJson<int>(
jsonMap,
TxClientOptions.tlsPort,
)
..autoConnect = _readFromJson<bool>(
jsonMap,
TxClientOptions.autoConnect,
)
..useBinaryProtocol = _readFromJson<bool>(
jsonMap,
TxClientOptions.useBinaryProtocol,
)
..queueMessages = _readFromJson<bool>(
jsonMap,
TxClientOptions.queueMessages,
)
..echoMessages = _readFromJson<bool>(
jsonMap,
TxClientOptions.echoMessages,
)
..recover = _readFromJson<String>(
jsonMap,
TxClientOptions.recover,
)
..environment = _readFromJson<String>(
jsonMap,
TxClientOptions.environment,
)
..idempotentRestPublishing = _readFromJson<bool>(
jsonMap,
TxClientOptions.idempotentRestPublishing,
)
..httpOpenTimeout = _readFromJson<int>(
jsonMap,
TxClientOptions.httpOpenTimeout,
)
..httpRequestTimeout = _readFromJson<int>(
jsonMap,
TxClientOptions.httpRequestTimeout,
)
..httpMaxRetryCount = _readFromJson<int>(
jsonMap,
TxClientOptions.httpMaxRetryCount,
)
..realtimeRequestTimeout = _readFromJson<int>(
jsonMap,
TxClientOptions.realtimeRequestTimeout,
)
..fallbackHosts = _readFromJson<List<String>>(
jsonMap,
TxClientOptions.fallbackHosts,
)
..fallbackHostsUseDefault = _readFromJson<bool>(
jsonMap,
TxClientOptions.fallbackHostsUseDefault,
)
..fallbackRetryTimeout = _readFromJson<int>(
jsonMap,
TxClientOptions.fallbackRetryTimeout,
)
..defaultTokenParams =
(tokenParams == null) ? null : _decodeTokenParams(tokenParams)
..channelRetryTimeout = _readFromJson<int>(
jsonMap,
TxClientOptions.channelRetryTimeout,
)
..transportParams = _readFromJson<Map<String, String>>(
jsonMap,
TxClientOptions.transportParams,
);
}
/// Decodes value [jsonMap] to [TokenDetails]
/// returns null if [jsonMap] is null
TokenDetails _decodeTokenDetails(Map<String, dynamic> jsonMap) =>
TokenDetails(_readFromJson<String>(jsonMap, TxTokenDetails.token))
..expires = _readFromJson<int>(jsonMap, TxTokenDetails.expires)
..issued = _readFromJson<int>(jsonMap, TxTokenDetails.issued)
..capability = _readFromJson<String>(jsonMap, TxTokenDetails.capability)
..clientId = _readFromJson<String>(jsonMap, TxTokenDetails.clientId);
/// Decodes value [jsonMap] to [TokenParams]
/// returns null if [jsonMap] is null
TokenParams _decodeTokenParams(Map<String, dynamic> jsonMap) {
final timestamp = _readFromJson<int>(jsonMap, TxTokenParams.timestamp);
final params = TokenParams()
..capability = _readFromJson<String>(jsonMap, TxTokenParams.capability)
..clientId = _readFromJson<String>(jsonMap, TxTokenParams.clientId)
..nonce = _readFromJson<String>(jsonMap, TxTokenParams.nonce)
..timestamp = (timestamp != null)
? DateTime.fromMillisecondsSinceEpoch(timestamp)
: null
..ttl = _readFromJson<int>(jsonMap, TxTokenParams.ttl);
return params;
}
/// Decodes value [jsonMap] to [AblyMessage]
/// returns null if [jsonMap] is null
AblyMessage _decodeAblyMessage(Map<String, dynamic> jsonMap) {
final type = _readFromJson<int>(jsonMap, TxAblyMessage.type);
var message = jsonMap[TxAblyMessage.message] as Object;
if (type != null) {
message = codecMap[type]!.decode(
toJsonMap(_readFromJson<Map>(jsonMap, TxAblyMessage.message)),
) as Object;
}
return AblyMessage(
message,
handle: jsonMap[TxAblyMessage.registrationHandle] as int?,
type: type,
);
}
DeviceDetails _decodeDeviceDetails(Map<String, dynamic> jsonMap) {
FormFactor formFactor = _decodeFormFactor(
_readFromJson<String>(jsonMap, TxDeviceDetails.formFactor));
return DeviceDetails(
jsonMap[TxDeviceDetails.id] as String?,
jsonMap[TxDeviceDetails.clientId] as String?,
_decodeDevicePlatform(jsonMap[TxDeviceDetails.platform] as String),
formFactor,
toTypedJsonMap<String>(
jsonMap[TxDeviceDetails.metadata] as Map<Object?, Object?>?),
_decodeDevicePushDetails(
Map<String, dynamic>.from(jsonMap[TxDeviceDetails.devicePushDetails]
as Map<Object?, Object?>),
),
);
}
DevicePushDetails _decodeDevicePushDetails(Map<String, dynamic> jsonMap) {
final jsonMapErrorReason =
jsonMap[TxDevicePushDetails.errorReason] as Map<Object?, Object?>?;
final recipient =
jsonMap[TxDevicePushDetails.recipient] as Map<Object?, Object?>?;
return DevicePushDetails(
recipient != null ? Map<String, String>.from(recipient) : null,
_decodeDevicePushState(jsonMap[TxDevicePushDetails.state] as String?),
(jsonMapErrorReason != null)
? _decodeErrorInfo(Map<String, dynamic>.from(jsonMapErrorReason))
: null);
}
LocalDevice _decodeLocalDevice(Map<String, dynamic> jsonMap) => LocalDevice(
_decodeDeviceDetails(jsonMap),
jsonMap[TxLocalDevice.deviceSecret] as String?,
jsonMap[TxLocalDevice.deviceIdentityToken] as String?);
FormFactor _decodeFormFactor(String? enumValue) {
switch (enumValue) {
case TxFormFactorEnum.phone:
return FormFactor.phone;
case TxFormFactorEnum.tablet:
return FormFactor.tablet;
case TxFormFactorEnum.desktop:
return FormFactor.desktop;
case TxFormFactorEnum.tv:
return FormFactor.tv;
case TxFormFactorEnum.watch:
return FormFactor.watch;
case TxFormFactorEnum.car:
return FormFactor.car;
case TxFormFactorEnum.embedded:
return FormFactor.embedded;
case TxFormFactorEnum.other:
return FormFactor.other;
}
throw AblyException(
'Platform communication error. FormFactor is invalid: $enumValue',
);
}
DevicePushState? _decodeDevicePushState(String? enumValue) {
switch (enumValue) {
case TxDevicePushStateEnum.active:
return DevicePushState.active;
case TxDevicePushStateEnum.failing:
return DevicePushState.failing;
case TxDevicePushStateEnum.failed:
return DevicePushState.failed;
default:
return null;
}
}
DevicePlatform _decodeDevicePlatform(String? enumValue) {
switch (enumValue) {
case TxDevicePlatformEnum.android:
return DevicePlatform.android;
case TxDevicePlatformEnum.ios:
return DevicePlatform.ios;
case TxDevicePlatformEnum.browser:
return DevicePlatform.browser;
}
throw AblyException(
'Platform communication error. DevicePlatform is invalid: $enumValue',
);
}
PushChannelSubscription _decodePushChannelSubscription(
Map<String, dynamic> jsonMap) =>
PushChannelSubscription(
channel: jsonMap[TxPushChannelSubscription.channel] as String,
clientId: jsonMap[TxPushChannelSubscription.clientId] as String?,
deviceId: jsonMap[TxPushChannelSubscription.deviceId] as String?,
);
UNNotificationSettings _decodeUNNotificationSettings(
Map<String, dynamic> jsonMap) =>
UNNotificationSettings(
authorizationStatus: _decodeUNAuthorizationStatus(
jsonMap[TxUNNotificationSettings.authorizationStatus] as String),
soundSetting: _decodeUNNotificationSetting(
jsonMap[TxUNNotificationSettings.soundSetting] as String),
badgeSetting: _decodeUNNotificationSetting(
jsonMap[TxUNNotificationSettings.badgeSetting] as String),
alertSetting: _decodeUNNotificationSetting(
jsonMap[TxUNNotificationSettings.alertSetting] as String),
notificationCenterSetting: _decodeUNNotificationSetting(
jsonMap[TxUNNotificationSettings.notificationCenterSetting]
as String),
lockScreenSetting: _decodeUNNotificationSetting(
jsonMap[TxUNNotificationSettings.lockScreenSetting] as String),
carPlaySetting: _decodeUNNotificationSetting(
jsonMap[TxUNNotificationSettings.carPlaySetting] as String),
alertStyle: _decodeUNAlertStyle(
jsonMap[TxUNNotificationSettings.alertStyle] as String),
showPreviewsSetting: _decodeUNShowPreviewsSetting(
jsonMap[TxUNNotificationSettings.showPreviewsSetting] as String),
criticalAlertSetting: _decodeUNNotificationSetting(
jsonMap[TxUNNotificationSettings.criticalAlertSetting] as String),
providesAppNotificationSettings:
jsonMap[TxUNNotificationSettings.providesAppNotificationSettings]
as bool,
announcementSetting: _decodeUNNotificationSetting(
jsonMap[TxUNNotificationSettings.announcementSetting] as String),
);
UNShowPreviewsSetting _decodeUNShowPreviewsSetting(String setting) {
switch (setting) {
case TxUNShowPreviewsSettingEnum.always:
return UNShowPreviewsSetting.always;
case TxUNShowPreviewsSettingEnum.whenAuthenticated:
return UNShowPreviewsSetting.whenAuthenticated;
case TxUNShowPreviewsSettingEnum.never:
return UNShowPreviewsSetting.never;
}
throw AblyException(
'Platform communication error. UNShowPreviewsSetting is invalid: $setting',
);
}
UNAlertStyle _decodeUNAlertStyle(String style) {
switch (style) {
case TxUNAlertStyleEnum.alert:
return UNAlertStyle.alert;
case TxUNAlertStyleEnum.banner:
return UNAlertStyle.banner;
case TxUNAlertStyleEnum.none:
return UNAlertStyle.none;
}
throw AblyException(
'Platform communication error. UNAlertStyle is invalid: $style',
);
}
UNAuthorizationStatus _decodeUNAuthorizationStatus(String status) {
switch (status) {
case TxUNAuthorizationStatusEnum.notDetermined:
return UNAuthorizationStatus.notDetermined;
case TxUNAuthorizationStatusEnum.denied:
return UNAuthorizationStatus.denied;
case TxUNAuthorizationStatusEnum.authorized:
return UNAuthorizationStatus.authorized;
case TxUNAuthorizationStatusEnum.provisional:
return UNAuthorizationStatus.provisional;
case TxUNAuthorizationStatusEnum.ephemeral:
return UNAuthorizationStatus.ephemeral;
}
throw AblyException(
'Platform communication error. UNAuthorizationStatus is invalid: $status',
);
}
UNNotificationSetting _decodeUNNotificationSetting(String setting) {
switch (setting) {
case TxUNNotificationSettingEnum.disabled:
return UNNotificationSetting.disabled;
case TxUNNotificationSettingEnum.enabled:
return UNNotificationSetting.enabled;
case TxUNNotificationSettingEnum.notSupported:
return UNNotificationSetting.notSupported;
}
throw AblyException(
'Platform communication error. UNNotificationSetting is invalid: $setting',
);
}
RemoteMessage _decodeRemoteMessage(Map<String, dynamic> jsonMap) =>
RemoteMessage.fromMap(jsonMap);
/// Decodes value [jsonMap] to [ErrorInfo]
/// returns null if [jsonMap] is null
ErrorInfo _decodeErrorInfo(Map<String, dynamic> jsonMap) => ErrorInfo(
code: jsonMap[TxErrorInfo.code] as int?,
message: jsonMap[TxErrorInfo.message] as String?,
statusCode: jsonMap[TxErrorInfo.statusCode] as int?,
href: jsonMap[TxErrorInfo.href] as String?,
requestId: jsonMap[TxErrorInfo.requestId] as String?,
cause: jsonMap[TxErrorInfo.cause] as ErrorInfo?,
);
/// Decodes [eventName] to [ConnectionEvent] enum if not null
ConnectionEvent _decodeConnectionEvent(String? eventName) {
switch (eventName) {
case TxEnumConstants.initialized:
return ConnectionEvent.initialized;
case TxEnumConstants.connecting:
return ConnectionEvent.connecting;
case TxEnumConstants.connected:
return ConnectionEvent.connected;
case TxEnumConstants.disconnected:
return ConnectionEvent.disconnected;
case TxEnumConstants.suspended:
return ConnectionEvent.suspended;
case TxEnumConstants.closing:
return ConnectionEvent.closing;
case TxEnumConstants.closed:
return ConnectionEvent.closed;
case TxEnumConstants.failed:
return ConnectionEvent.failed;
case TxEnumConstants.update:
return ConnectionEvent.update;
}
throw AblyException(
'Platform communication error. Connection event is invalid: $eventName',
);
}
/// Decodes [state] to [ConnectionState] enum if not null
ConnectionState _decodeConnectionState(String? state) {
switch (state) {
case TxEnumConstants.initialized:
return ConnectionState.initialized;
case TxEnumConstants.connecting:
return ConnectionState.connecting;
case TxEnumConstants.connected:
return ConnectionState.connected;
case TxEnumConstants.disconnected:
return ConnectionState.disconnected;
case TxEnumConstants.suspended:
return ConnectionState.suspended;
case TxEnumConstants.closing:
return ConnectionState.closing;
case TxEnumConstants.closed:
return ConnectionState.closed;
case TxEnumConstants.failed:
return ConnectionState.failed;
}
throw AblyException(
'Platform communication error. Connection state is invalid: $state',
);
}
/// Decodes [eventName] to [ChannelEvent] enum if not null
ChannelEvent _decodeChannelEvent(String? eventName) {
switch (eventName) {
case TxEnumConstants.initialized:
return ChannelEvent.initialized;
case TxEnumConstants.attaching:
return ChannelEvent.attaching;
case TxEnumConstants.attached:
return ChannelEvent.attached;
case TxEnumConstants.detaching:
return ChannelEvent.detaching;
case TxEnumConstants.detached:
return ChannelEvent.detached;
case TxEnumConstants.suspended:
return ChannelEvent.suspended;
case TxEnumConstants.failed:
return ChannelEvent.failed;
case TxEnumConstants.update:
return ChannelEvent.update;
}
throw AblyException(
'Platform communication error. Channel event is invalid: $eventName',
);
}
/// Decodes [state] to [ChannelState] enum if not null
ChannelState _decodeChannelState(String? state) {
switch (state) {
case TxEnumConstants.initialized:
return ChannelState.initialized;
case TxEnumConstants.attaching:
return ChannelState.attaching;
case TxEnumConstants.attached:
return ChannelState.attached;
case TxEnumConstants.detaching:
return ChannelState.detaching;
case TxEnumConstants.detached:
return ChannelState.detached;
case TxEnumConstants.suspended:
return ChannelState.suspended;
case TxEnumConstants.failed:
return ChannelState.failed;
}
throw AblyException(
'Platform communication error. Channel state is invalid: $state',
);
}
/// Decodes value [jsonMap] to [ConnectionStateChange]
/// returns null if [jsonMap] is null
ConnectionStateChange _decodeConnectionStateChange(
Map<String, dynamic> jsonMap,
) {
final current = _decodeConnectionState(
_readFromJson<String>(jsonMap, TxConnectionStateChange.current));
final previous = _decodeConnectionState(
_readFromJson<String>(jsonMap, TxConnectionStateChange.previous));
final event = _decodeConnectionEvent(
_readFromJson<String>(jsonMap, TxConnectionStateChange.event));
final retryIn =
_readFromJson<int>(jsonMap, TxConnectionStateChange.retryIn);
final errorInfo =
toJsonMap(_readFromJson<Map>(jsonMap, TxConnectionStateChange.reason));
final reason = (errorInfo == null) ? null : _decodeErrorInfo(errorInfo);
return ConnectionStateChange(
current,
previous,
event,
retryIn: retryIn,
reason: reason,
);
}