From 97bd8eee323faec832061ae9d9485d7b6e5dffcf Mon Sep 17 00:00:00 2001 From: "Rohit R. Abbadi" Date: Wed, 20 May 2020 21:53:33 +0530 Subject: [PATCH 01/19] custom Codegen for CodecTypes and PlatformMethods - mustache template based codegen - generates codec types and platform methods - addresses https://github.com/ably/ably-flutter/pull/5#discussion_r419159258 --- bin/README.md | 62 ++++++++++++++++++++++++ bin/codegen.dart | 48 ++++++++++++++++++ bin/codegencontext.dart | 55 +++++++++++++++++++++ bin/templates/PlatformConstants.java.hbs | 17 +++++++ bin/templates/platformconstants.dart.hbs | 11 +++++ bin/templates/platformconstants.h.hbs | 14 ++++++ bin/templates/platformconstants.m.hbs | 9 ++++ 7 files changed, 216 insertions(+) create mode 100644 bin/README.md create mode 100644 bin/codegen.dart create mode 100644 bin/codegencontext.dart create mode 100644 bin/templates/PlatformConstants.java.hbs create mode 100644 bin/templates/platformconstants.dart.hbs create mode 100644 bin/templates/platformconstants.h.hbs create mode 100644 bin/templates/platformconstants.m.hbs diff --git a/bin/README.md b/bin/README.md new file mode 100644 index 000000000..0daed5e32 --- /dev/null +++ b/bin/README.md @@ -0,0 +1,62 @@ +## Code generation to keep platform constants in sync + +#### Generating files + +```bash +cd bin +dart codegen.dart +``` + +#### Template format + +This generation is based on a 2 simple Regular expressions which work as below: + +input template contents +```text +Hola {{variable}}! +``` + +input context +```dart +Map context = { + "variable": "World" +}; +``` + +output file content +```text +Hola World +``` + +input template contents +```text +{{#each list}} + String {{name}} = "{{value}}"; +{{/each}} +``` + +input context +```dart +Map context = { + "list": [ + {"var1": "title", "var2": "Lorem Ipsum"}, + {"var1": "description", "var2": "Lorem ipsum dolor sit amet, consectetur adipiscing elit"}, + ] +}; +``` + +output file content +```text + + String title = "Lorem Ipsum"; + + String description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit"; + +``` +_mind the linebreaks_ + + +#### Template and Context files + +source template files are available in `bin/templates` + and source context data in `bin/codegencontext.dart`. diff --git a/bin/codegen.dart b/bin/codegen.dart new file mode 100644 index 000000000..f34f45f30 --- /dev/null +++ b/bin/codegen.dart @@ -0,0 +1,48 @@ +import 'dart:io'; +import 'codegencontext.dart' show context; + +String projectRoot = "../"; +String templatesRoot = "./templates/"; + +Map toGenerate = { + //input template path vs output file path + "${templatesRoot}platformconstants.dart.hbs": "${projectRoot}lib/src/gen/platformconstants.dart", + "${templatesRoot}platformconstants.java.hbs": "${projectRoot}android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java", + "${templatesRoot}platformconstants.h.hbs": "${projectRoot}ios/Classes/codec/AblyPlatformConstants.h", + "${templatesRoot}platformconstants.m.hbs": "${projectRoot}ios/Classes/codec/AblyPlatformConstants.m", +}; + +void main() async { + for(MapEntry entry in toGenerate.entries){ + String source = getContent(File(entry.key).readAsStringSync(), context); + File(entry.value).writeAsStringSync( + "//\n// Generated code. Do not modify.\n// source: ${entry.key.replaceAll('./', 'bin/')} \n//\n\n${source}" + ); + print("File written: ${entry.value} ✔"); + } +} + +//{{hello}}, {{ hi_there }} +final variableRegExp = RegExp("{{\\s*([a-zA-Z\$_][a-zA-Z0-9\$_]*)\\s*}}"); + +//{{#each xyz}}{{name}}{{/each}} +final iteratorRegexp = RegExp("{{#each\\s+([a-zA-Z\$_][a-zA-Z0-9\$_]*)\\s*}}([.\\s\\S]*?){{\\\s*\\/each\\s*}}"); + +String getContent(String templateStr, Map context){ + //matching loops + Iterable matches = iteratorRegexp.allMatches(templateStr); + if(matches!=null){ + for(RegExpMatch match in matches){ + String fullMatch = match.group(0); + String iteratorContext = match.group(1); + String iterable = match.group(2); + List> iteratingContext = context[iteratorContext]; + templateStr = templateStr.replaceFirst(fullMatch, iteratingContext.map((Map _context)=>getContent(iterable, _context)).join("")); + } + } + + //replacing variables + return templateStr.replaceAllMapped(variableRegExp, (match){ + return context[match.group(1)].toString(); + }); +} diff --git a/bin/codegencontext.dart b/bin/codegencontext.dart new file mode 100644 index 000000000..4cae156e5 --- /dev/null +++ b/bin/codegencontext.dart @@ -0,0 +1,55 @@ +///Transmission protocol custom types. Will be used by codecs +List> _types = [ + // Custom type values must be over 127. At the time of writing the standard message + // codec encodes them as an unsigned byte which means the maximum type value is 255. + // If we get to the point of having more than that number of custom types (i.e. more + // than 128 [255 - 127]) then we can either roll our own codec from scratch or, + // perhaps easier, reserve custom type value 255 to indicate that it will be followed + // by a subtype value - perhaps of a wider type. + // + // https://api.flutter.dev/flutter/services/StandardMessageCodec/writeValue.html + + //Ably flutter plugin protocol message + {"name": "ablyMessage", "value": 128}, + + //Other ably objects + {"name": "clientOptions", "value": 129}, + {"name": "tokenDetails", "value": 130}, + {"name": "errorInfo", "value": 144}, + + // Events + {"name": "connectionEvent", "value": 201}, + {"name": "connectionState", "value": 202}, + {"name": "connectionStateChange", "value": 203}, + {"name": "channelEvent", "value": 204}, + {"name": "channelState", "value": 205}, + {"name": "channelStateChange", "value": 206} +]; + +///Platform method names +List> _platformMethods = [ + {"name": "getPlatformVersion", "value": "getPlatformVersion"}, + {"name": "getVersion", "value": "getVersion"}, + {"name": "registerAbly", "value": "registerAbly"}, + + // Rest + {"name": "createRestWithOptions", "value": "createRestWithOptions"}, + {"name": "publish", "value": "publish"}, + + // Realtime + {"name": "createRealtimeWithOptions", "value": "createRealtimeWithOptions"}, + {"name": "connectRealtime", "value": "connectRealtime"}, + {"name": "closeRealtime", "value": "closeRealtime"}, + + //Realtime events + {"name": "onRealtimeConnectionStateChanged", "value": "onRealtimeConnectionStateChanged"}, + {"name": "onRealtimeChannelStateChanged", "value": "onRealtimeChannelStateChanged"} +]; + + +//exporting all the constants as a single map +// which can be directly fed to template as context +Map context = { + "types": _types, + "methods": _platformMethods +}; diff --git a/bin/templates/PlatformConstants.java.hbs b/bin/templates/PlatformConstants.java.hbs new file mode 100644 index 000000000..a18b5e72b --- /dev/null +++ b/bin/templates/PlatformConstants.java.hbs @@ -0,0 +1,17 @@ +package io.ably.flutter.plugin.gen; + + +public class PlatformConstants{ + + public class CodecTypes { + {{#each types}}public static final byte {{name}} = (byte){{value}}; + {{/each}} + } + + public class PlatformMethod { + + {{#each methods}}public static final String {{name}} = "{{value}}"; + {{/each}} + } + +} diff --git a/bin/templates/platformconstants.dart.hbs b/bin/templates/platformconstants.dart.hbs new file mode 100644 index 000000000..669154605 --- /dev/null +++ b/bin/templates/platformconstants.dart.hbs @@ -0,0 +1,11 @@ +class CodecTypes{ + + {{#each types}}static const int {{name}} = {{value}}; + {{/each}} +} + +class PlatformMethod { + + {{#each methods}}static const String {{name}} = "{{value}}"; + {{/each}} +} diff --git a/bin/templates/platformconstants.h.hbs b/bin/templates/platformconstants.h.hbs new file mode 100644 index 000000000..0bc8ed301 --- /dev/null +++ b/bin/templates/platformconstants.h.hbs @@ -0,0 +1,14 @@ +#import + +typedef NS_ENUM(UInt8, _Value) { + + {{#each types}}codecTypes_{{name}} = {{value}}, + {{/each}} +}; + + +@interface PLATFORM_METHODS : NSObject + +{{#each methods}}@property (class, nonatomic, assign, readonly) NSString *{{name}}; +{{/each}} +@end diff --git a/bin/templates/platformconstants.m.hbs b/bin/templates/platformconstants.m.hbs new file mode 100644 index 000000000..207021813 --- /dev/null +++ b/bin/templates/platformconstants.m.hbs @@ -0,0 +1,9 @@ +#import +#import "AblyPlatformConstants.h" + + +@implementation PLATFORM_METHODS + +{{#each methods}}+ (NSString*) {{name}} { return @"{{value}}"; } +{{/each}} +@end From 7ad42630799297fe2def283fc876284b2c276c57 Mon Sep 17 00:00:00 2001 From: "Rohit R. Abbadi" Date: Wed, 20 May 2020 21:57:54 +0530 Subject: [PATCH 02/19] code generated using custom Codegen for CodecTypes and PlatformMethods - 4 generated files: - PlatformConstants.java - AblyPlatformConstants.h - AblyPlatformConstants.m - platformconstants.dart Changes related to the same in relevant files --- DeveloperNotes.md | 5 ++ .../ably/flutter/plugin/AblyMessageCodec.java | 69 ++++++++----------- .../flutter/plugin/gen/PlatformConstants.java | 40 +++++++++++ ios/Classes/codec/AblyFlutterReader.h | 19 ----- ios/Classes/codec/AblyFlutterReader.m | 10 +-- ios/Classes/codec/AblyFlutterWriter.m | 15 ++-- ios/Classes/codec/AblyPlatformConstants.h | 37 ++++++++++ ios/Classes/codec/AblyPlatformConstants.m | 23 +++++++ lib/ably.dart | 1 + lib/src/ably_implementation.dart | 20 ++---- lib/src/codec.dart | 54 ++++----------- lib/src/gen/platformconstants.dart | 34 +++++++++ lib/src/impl/platform_object.dart | 37 ++-------- lib/src/impl/realtime/channels.dart | 2 +- lib/src/impl/realtime/connection.dart | 2 +- test/ably_flutter_plugin_test.dart | 44 ++++++++---- 16 files changed, 237 insertions(+), 175 deletions(-) create mode 100644 android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java create mode 100644 ios/Classes/codec/AblyPlatformConstants.h create mode 100644 ios/Classes/codec/AblyPlatformConstants.m create mode 100644 lib/src/gen/platformconstants.dart diff --git a/DeveloperNotes.md b/DeveloperNotes.md index 5d2b38957..baaad5550 100644 --- a/DeveloperNotes.md +++ b/DeveloperNotes.md @@ -48,3 +48,8 @@ being a specialized package that includes platform-specific implementation code - Flutter [documentation](https://flutter.dev/docs), offering tutorials, samples, guidance on mobile development, and a full API reference. + + +## Generating platform constants + +[Read about generation of platform specific constant files](bin/README.md) diff --git a/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java b/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java index a6285fa12..277ef30f5 100644 --- a/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java +++ b/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java @@ -18,25 +18,10 @@ import io.ably.lib.types.ErrorInfo; import io.ably.lib.types.Param; import io.flutter.plugin.common.StandardMessageCodec; +import io.ably.flutter.plugin.gen.PlatformConstants; public class AblyMessageCodec extends StandardMessageCodec { - //Ably flutter plugin protocol message - private static final byte _valueAblyMessage = (byte)128; - - //Other ably objects - private static final byte _valueClientOptions = (byte)129; - private static final byte _valueTokenDetails = (byte)130; - private static final byte _errorInfo = (byte)144; - - // Events - private static final byte _connectionEvent = (byte)201; - private static final byte _connectionState = (byte)202; - private static final byte _connectionStateChange = (byte)203; - private static final byte _channelEvent = (byte)204; - private static final byte _channelState = (byte)205; - private static final byte _channelStateChange = (byte)206; - // @FunctionalInterface interface CodecEncoder{ void encode(ByteArrayOutputStream stream, T value); } // @FunctionalInterface @@ -73,18 +58,18 @@ T decode(ByteBuffer buffer){ AblyMessageCodec self = this; codecMap = new HashMap(){ { - put(_valueAblyMessage, new CodecPair<>(null, self::readAblyFlutterMessage)); - put(_valueClientOptions, new CodecPair<>(null, self::readClientOptions)); - put(_valueTokenDetails, new CodecPair<>(null, self::readTokenDetails)); - put(_errorInfo, new CodecPair<>(self::writeErrorInfo, null)); - - put(_connectionEvent, new CodecPair<>(self::writeConnectionEvent, null)); - put(_connectionState, new CodecPair<>(self::writeConnectionState, null)); - put(_connectionStateChange, new CodecPair<>(self::writeConnectionStateChange, null)); - - put(_channelEvent, new CodecPair<>(self::writeChannelEvent, null)); - put(_channelState, new CodecPair<>(self::writeChannelState, null)); - put(_channelStateChange, new CodecPair<>(self::writeChannelStateChange, null)); + put(PlatformConstants.CodecTypes.ablyMessage, new CodecPair<>(null, self::readAblyFlutterMessage)); + put(PlatformConstants.CodecTypes.clientOptions, new CodecPair<>(null, self::readClientOptions)); + put(PlatformConstants.CodecTypes.tokenDetails, new CodecPair<>(null, self::readTokenDetails)); + put(PlatformConstants.CodecTypes.errorInfo, new CodecPair<>(self::writeErrorInfo, null)); + + put(PlatformConstants.CodecTypes.connectionEvent, new CodecPair<>(self::writeConnectionEvent, null)); + put(PlatformConstants.CodecTypes.connectionState, new CodecPair<>(self::writeConnectionState, null)); + put(PlatformConstants.CodecTypes.connectionStateChange, new CodecPair<>(self::writeConnectionStateChange, null)); + + put(PlatformConstants.CodecTypes.channelEvent, new CodecPair<>(self::writeChannelEvent, null)); + put(PlatformConstants.CodecTypes.channelState, new CodecPair<>(self::writeChannelState, null)); + put(PlatformConstants.CodecTypes.channelStateChange, new CodecPair<>(self::writeChannelStateChange, null)); } }; } @@ -109,19 +94,19 @@ private void readValue(final ByteBuffer buffer, final Consumer consumer) protected void writeValue(ByteArrayOutputStream stream, Object value) { Byte type = null; if(value instanceof ErrorInfo){ - type = _errorInfo; + type = PlatformConstants.CodecTypes.errorInfo; }else if(value instanceof ConnectionEvent){ - type = _connectionEvent; + type = PlatformConstants.CodecTypes.connectionEvent; }else if(value instanceof ConnectionState){ - type = _connectionState; + type = PlatformConstants.CodecTypes.connectionState; }else if(value instanceof ConnectionStateListener.ConnectionStateChange){ - type = _connectionStateChange; + type = PlatformConstants.CodecTypes.connectionStateChange; }else if(value instanceof ChannelEvent){ - type = _channelEvent; + type = PlatformConstants.CodecTypes.channelEvent; }else if(value instanceof ChannelState){ - type = _channelState; + type = PlatformConstants.CodecTypes.channelState; }else if(value instanceof ChannelStateListener.ChannelStateChange){ - type = _channelStateChange; + type = PlatformConstants.CodecTypes.channelStateChange; } if(type!=null){ CodecPair pair = codecMap.get(type); @@ -211,7 +196,7 @@ private TokenDetails readTokenDetails(final ByteBuffer buffer) { //HANDLING WRITE private void writeErrorInfo(ByteArrayOutputStream stream, ErrorInfo e){ - stream.write(_errorInfo); + stream.write(PlatformConstants.CodecTypes.errorInfo); writeValue(stream, e.code); writeValue(stream, e.message); writeValue(stream, e.statusCode); @@ -220,10 +205,10 @@ private void writeErrorInfo(ByteArrayOutputStream stream, ErrorInfo e){ writeValue(stream, null); //cause - not available in ably-java } - private void writeConnectionEvent(ByteArrayOutputStream stream, ConnectionEvent e){ writeEnum(stream, _connectionEvent, e); } - private void writeConnectionState(ByteArrayOutputStream stream, ConnectionState e){ writeEnum(stream, _connectionState, e); } + private void writeConnectionEvent(ByteArrayOutputStream stream, ConnectionEvent e){ writeEnum(stream, PlatformConstants.CodecTypes.connectionEvent, e); } + private void writeConnectionState(ByteArrayOutputStream stream, ConnectionState e){ writeEnum(stream, PlatformConstants.CodecTypes.connectionState, e); } private void writeConnectionStateChange(ByteArrayOutputStream stream, ConnectionStateListener.ConnectionStateChange c){ - stream.write(_connectionStateChange); + stream.write(PlatformConstants.CodecTypes.connectionStateChange); writeValue(stream, c.current); writeValue(stream, c.previous); writeValue(stream, c.event); @@ -231,10 +216,10 @@ private void writeConnectionStateChange(ByteArrayOutputStream stream, Connection writeValue(stream, c.reason); } - private void writeChannelEvent(ByteArrayOutputStream stream, ChannelEvent e){ writeEnum(stream, _channelEvent, e); } - private void writeChannelState(ByteArrayOutputStream stream, ChannelState e){ writeEnum(stream, _channelState, e); } + private void writeChannelEvent(ByteArrayOutputStream stream, ChannelEvent e){ writeEnum(stream, PlatformConstants.CodecTypes.channelEvent, e); } + private void writeChannelState(ByteArrayOutputStream stream, ChannelState e){ writeEnum(stream, PlatformConstants.CodecTypes.channelState, e); } private void writeChannelStateChange(ByteArrayOutputStream stream, ChannelStateListener.ChannelStateChange c){ - stream.write(_channelStateChange); + stream.write(PlatformConstants.CodecTypes.channelStateChange); writeValue(stream, c.current); writeValue(stream, c.previous); writeValue(stream, c.event); diff --git a/android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java b/android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java new file mode 100644 index 000000000..ca5efd9e8 --- /dev/null +++ b/android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java @@ -0,0 +1,40 @@ +// +// Generated code. Do not modify. +// source: bin/templates/platformconstants.java.hbs +// + +package io.ably.flutter.plugin.gen; + + +public class PlatformConstants{ + + public class CodecTypes { + public static final byte ablyMessage = (byte)128; + public static final byte clientOptions = (byte)129; + public static final byte tokenDetails = (byte)130; + public static final byte errorInfo = (byte)144; + public static final byte connectionEvent = (byte)201; + public static final byte connectionState = (byte)202; + public static final byte connectionStateChange = (byte)203; + public static final byte channelEvent = (byte)204; + public static final byte channelState = (byte)205; + public static final byte channelStateChange = (byte)206; + + } + + public class PlatformMethod { + + public static final String getPlatformVersion = "getPlatformVersion"; + public static final String getVersion = "getVersion"; + public static final String registerAbly = "registerAbly"; + public static final String createRestWithOptions = "createRestWithOptions"; + public static final String publish = "publish"; + public static final String createRealtimeWithOptions = "createRealtimeWithOptions"; + public static final String connectRealtime = "connectRealtime"; + public static final String closeRealtime = "closeRealtime"; + public static final String onRealtimeConnectionStateChanged = "onRealtimeConnectionStateChanged"; + public static final String onRealtimeChannelStateChanged = "onRealtimeChannelStateChanged"; + + } + +} diff --git a/ios/Classes/codec/AblyFlutterReader.h b/ios/Classes/codec/AblyFlutterReader.h index 20c0e4676..a51bede1d 100644 --- a/ios/Classes/codec/AblyFlutterReader.h +++ b/ios/Classes/codec/AblyFlutterReader.h @@ -7,22 +7,3 @@ NS_ASSUME_NONNULL_BEGIN @end NS_ASSUME_NONNULL_END - - -typedef NS_ENUM(UInt8, _Value) { - //Ably flutter plugin protocol message - _valueAblyMessage = 128, - - //Other ably objects - _valueClientOptions = 129, - _valueTokenDetails = 130, - _ValueErrorInfo = 144, - - //Events - _connectionEvent = 201, - _connectionState = 202, - _connectionStateChange = 203, - _channelEvent = 204, - _channelState = 205, - _channelStateChange = 206, -}; diff --git a/ios/Classes/codec/AblyFlutterReader.m b/ios/Classes/codec/AblyFlutterReader.m index fe387b6ec..330862524 100644 --- a/ios/Classes/codec/AblyFlutterReader.m +++ b/ios/Classes/codec/AblyFlutterReader.m @@ -1,6 +1,8 @@ #import "AblyFlutterReader.h" #import "Ably.h" #import "AblyFlutterMessage.h" +#import "AblyPlatformConstants.h" + static ARTLogLevel _logLevel(NSNumber *const number) { switch (number.unsignedIntegerValue) { @@ -17,14 +19,14 @@ static ARTLogLevel _logLevel(NSNumber *const number) { @implementation AblyFlutterReader -(id)readValueOfType:(const UInt8)type { - switch ((_Value)type) { - case _valueClientOptions: + switch (type) { + case codecTypes_clientOptions: return [self readClientOptions]; - case _valueTokenDetails: + case codecTypes_tokenDetails: return [self readTokenDeatils]; - case _valueAblyMessage: + case codecTypes_ablyMessage: return [self readAblyFlutterMessage]; } diff --git a/ios/Classes/codec/AblyFlutterWriter.m b/ios/Classes/codec/AblyFlutterWriter.m index b0f1e502d..9bb3e9987 100644 --- a/ios/Classes/codec/AblyFlutterWriter.m +++ b/ios/Classes/codec/AblyFlutterWriter.m @@ -3,6 +3,7 @@ #import "ARTTypes.h" #import "AblyFlutterMessage.h" #import "AblyFlutterReader.h" +#import "AblyPlatformConstants.h" @implementation AblyFlutterWriter @@ -27,7 +28,7 @@ - (void) writeEnum:(UInt8) type enumValue: (int const) enumValue{ } - (void) writeErrorInfo:(ARTErrorInfo *const) e{ - [self writeByte:_ValueErrorInfo]; + [self writeByte:codecTypes_errorInfo]; [self writeValue: nil]; //code - not available in ably-cocoa [self writeValue: [e message]]; [self writeValue: @([e statusCode])]; @@ -36,10 +37,10 @@ - (void) writeErrorInfo:(ARTErrorInfo *const) e{ [self writeValue: nil]; //cause - not available in ably-java } -- (void) writeConnectState:(ARTRealtimeConnectionState const) state{ [self writeEnum:_connectionState enumValue:state]; } -- (void) writeConnectEvent:(ARTRealtimeConnectionEvent const) event{ [self writeEnum:_connectionEvent enumValue:event]; } +- (void) writeConnectState:(ARTRealtimeConnectionState const) state{ [self writeEnum:codecTypes_connectionState enumValue:state]; } +- (void) writeConnectEvent:(ARTRealtimeConnectionEvent const) event{ [self writeEnum:codecTypes_connectionEvent enumValue:event]; } - (void) writeConnectionStateChange:(ARTConnectionStateChange *const) stateChange{ - [self writeByte:_connectionStateChange]; + [self writeByte:codecTypes_connectionStateChange]; [self writeConnectState: [stateChange current]]; [self writeConnectState: [stateChange previous]]; [self writeConnectEvent: [stateChange event]]; @@ -47,10 +48,10 @@ - (void) writeConnectionStateChange:(ARTConnectionStateChange *const) stateChang [self writeValue: [stateChange reason]]; } -- (void) writeChannelState:(ARTRealtimeChannelState const) state{ [self writeEnum:_channelState enumValue:state]; } -- (void) writeChannelEvent:(ARTChannelEvent const) event{ [self writeEnum:_channelEvent enumValue:event]; } +- (void) writeChannelState:(ARTRealtimeChannelState const) state{ [self writeEnum:codecTypes_channelState enumValue:state]; } +- (void) writeChannelEvent:(ARTChannelEvent const) event{ [self writeEnum:codecTypes_channelEvent enumValue:event]; } - (void) writeChannelStateChange:(ARTChannelStateChange *const) stateChange{ - [self writeByte:_channelStateChange]; + [self writeByte:codecTypes_channelStateChange]; [self writeChannelState: [stateChange current]]; [self writeChannelState: [stateChange previous]]; [self writeChannelEvent: [stateChange event]]; diff --git a/ios/Classes/codec/AblyPlatformConstants.h b/ios/Classes/codec/AblyPlatformConstants.h new file mode 100644 index 000000000..263554ce1 --- /dev/null +++ b/ios/Classes/codec/AblyPlatformConstants.h @@ -0,0 +1,37 @@ +// +// Generated code. Do not modify. +// source: bin/templates/platformconstants.h.hbs +// + +#import + +typedef NS_ENUM(UInt8, _Value) { + + codecTypes_ablyMessage = 128, + codecTypes_clientOptions = 129, + codecTypes_tokenDetails = 130, + codecTypes_errorInfo = 144, + codecTypes_connectionEvent = 201, + codecTypes_connectionState = 202, + codecTypes_connectionStateChange = 203, + codecTypes_channelEvent = 204, + codecTypes_channelState = 205, + codecTypes_channelStateChange = 206, + +}; + + +@interface PLATFORM_METHODS : NSObject + +@property (class, nonatomic, assign, readonly) NSString *getPlatformVersion; +@property (class, nonatomic, assign, readonly) NSString *getVersion; +@property (class, nonatomic, assign, readonly) NSString *registerAbly; +@property (class, nonatomic, assign, readonly) NSString *createRestWithOptions; +@property (class, nonatomic, assign, readonly) NSString *publish; +@property (class, nonatomic, assign, readonly) NSString *createRealtimeWithOptions; +@property (class, nonatomic, assign, readonly) NSString *connectRealtime; +@property (class, nonatomic, assign, readonly) NSString *closeRealtime; +@property (class, nonatomic, assign, readonly) NSString *onRealtimeConnectionStateChanged; +@property (class, nonatomic, assign, readonly) NSString *onRealtimeChannelStateChanged; + +@end diff --git a/ios/Classes/codec/AblyPlatformConstants.m b/ios/Classes/codec/AblyPlatformConstants.m new file mode 100644 index 000000000..a12fae315 --- /dev/null +++ b/ios/Classes/codec/AblyPlatformConstants.m @@ -0,0 +1,23 @@ +// +// Generated code. Do not modify. +// source: bin/templates/platformconstants.m.hbs +// + +#import +#import "AblyPlatformConstants.h" + + +@implementation PLATFORM_METHODS + ++ (NSString*) getPlatformVersion { return @"getPlatformVersion"; } ++ (NSString*) getVersion { return @"getVersion"; } ++ (NSString*) registerAbly { return @"registerAbly"; } ++ (NSString*) createRestWithOptions { return @"createRestWithOptions"; } ++ (NSString*) publish { return @"publish"; } ++ (NSString*) createRealtimeWithOptions { return @"createRealtimeWithOptions"; } ++ (NSString*) connectRealtime { return @"connectRealtime"; } ++ (NSString*) closeRealtime { return @"closeRealtime"; } ++ (NSString*) onRealtimeConnectionStateChanged { return @"onRealtimeConnectionStateChanged"; } ++ (NSString*) onRealtimeChannelStateChanged { return @"onRealtimeChannelStateChanged"; } + +@end diff --git a/lib/ably.dart b/lib/ably.dart index 10a1145af..fa663c1db 100644 --- a/lib/ably.dart +++ b/lib/ably.dart @@ -1,3 +1,4 @@ export 'src/interface.dart'; export 'src/defaults.dart'; export 'src/spec/spec.dart'; +export 'src/gen/platformconstants.dart'; diff --git a/lib/src/ably_implementation.dart b/lib/src/ably_implementation.dart index fdf045860..f0a51d807 100644 --- a/lib/src/ably_implementation.dart +++ b/lib/src/ably_implementation.dart @@ -3,7 +3,7 @@ import 'dart:async'; import 'package:ably_flutter_plugin/src/impl/message.dart'; import 'package:ably_flutter_plugin/src/interface.dart'; import 'package:flutter/services.dart'; - +import 'package:ably_flutter_plugin/src/gen/platformconstants.dart' show PlatformMethod; import 'package:streams_channel/streams_channel.dart'; import '../ably.dart'; import 'codec.dart'; @@ -11,14 +11,6 @@ import 'impl/platform_object.dart'; import 'impl/realtime/realtime.dart'; import 'impl/rest/rest.dart'; -///Extension to extract string name from PlatformMethod -extension on PlatformMethod { - String toName() { - // https://stackoverflow.com/a/59308734/392847 - return this.toString().split('.').last; - } -} - /// Ably plugin implementation /// Single point of interaction that exposes all necessary APIs to ably objects class AblyImplementation implements Ably { @@ -52,7 +44,7 @@ class AblyImplementation implements Ably { /// Registering instance with ably. /// On registration, older ably instance id destroyed! /// TODO check if this is desired behavior in case if 2 different ably instances are created in app - Future _register() async => (null != _handle) ? _handle : _handle = await methodChannel.invokeMethod(PlatformMethod.register.toName()); + Future _register() async => (null != _handle) ? _handle : _handle = await methodChannel.invokeMethod(PlatformMethod.registerAbly); @override Future createRealtime({ @@ -67,7 +59,7 @@ class AblyImplementation implements Ably { handle, this, await methodChannel.invokeMethod( - PlatformMethod.createRealtimeWithOptions.toName(), + PlatformMethod.createRealtimeWithOptions, message ), options: options, @@ -90,7 +82,7 @@ class AblyImplementation implements Ably { handle, this, await methodChannel.invokeMethod( - PlatformMethod.createRestWithOptions.toName(), + PlatformMethod.createRestWithOptions, message ), options: options, @@ -102,9 +94,9 @@ class AblyImplementation implements Ably { @override Future get platformVersion async => - await methodChannel.invokeMethod(PlatformMethod.getPlatformVersion.toName()); + await methodChannel.invokeMethod(PlatformMethod.getPlatformVersion); @override Future get version async => - await methodChannel.invokeMethod(PlatformMethod.getVersion.toName()); + await methodChannel.invokeMethod(PlatformMethod.getVersion); } diff --git a/lib/src/codec.dart b/lib/src/codec.dart index 116eb5f0b..90e863cd1 100644 --- a/lib/src/codec.dart +++ b/lib/src/codec.dart @@ -1,4 +1,5 @@ import 'package:ably_flutter_plugin/src/impl/message.dart'; +import 'package:ably_flutter_plugin/src/gen/platformconstants.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; @@ -28,64 +29,39 @@ class CodecPair{ class Codec extends StandardMessageCodec { - // Custom type values must be over 127. At the time of writing the standard message - // codec encodes them as an unsigned byte which means the maximum type value is 255. - // If we get to the point of having more than that number of custom types (i.e. more - // than 128 [255 - 127]) then we can either roll our own codec from scratch or, - // perhaps easier, reserve custom type value 255 to indicate that it will be followed - // by a subtype value - perhaps of a wider type. - // - // https://api.flutter.dev/flutter/services/StandardMessageCodec/writeValue.html - - //Ably flutter plugin protocol message - static const _valueAblyMessage = 128; - - //Other ably objects - static const _valueClientOptions = 129; - static const _valueTokenDetails = 130; - static const _valueErrorInfo = 144; - - // Events - static const _connectionEvent = 201; - static const _connectionState = 202; - static const _connectionStateChange = 203; - static const _channelEvent = 204; - static const _channelState = 205; - static const _channelStateChange = 206; - Map codecMap; Codec():super(){ this.codecMap = { //Ably flutter plugin protocol message - _valueAblyMessage: CodecPair(encodeAblyMessage, decodeAblyMessage), + CodecTypes.ablyMessage: CodecPair(encodeAblyMessage, decodeAblyMessage), //Other ably objects - _valueClientOptions: CodecPair(encodeClientOptions, decodeClientOptions), - _valueTokenDetails: CodecPair(encodeTokenDetails, decodeTokenDetails), - _valueErrorInfo: CodecPair(null, decodeErrorInfo), + CodecTypes.clientOptions: CodecPair(encodeClientOptions, decodeClientOptions), + CodecTypes.tokenDetails: CodecPair(encodeTokenDetails, decodeTokenDetails), + CodecTypes.errorInfo: CodecPair(null, decodeErrorInfo), //Events - Connection - _connectionEvent: CodecPair(null, decodeConnectionEvent), - _connectionState: CodecPair(null, decodeConnectionState), - _connectionStateChange: CodecPair(null, decodeConnectionStateChange), + CodecTypes.connectionEvent: CodecPair(null, decodeConnectionEvent), + CodecTypes.connectionState: CodecPair(null, decodeConnectionState), + CodecTypes.connectionStateChange: CodecPair(null, decodeConnectionStateChange), //Events - Channel - _channelEvent: CodecPair(null, decodeChannelEvent), - _channelState: CodecPair(null, decodeChannelState), - _channelStateChange: CodecPair(null, decodeChannelStateChange), + CodecTypes.channelEvent: CodecPair(null, decodeChannelEvent), + CodecTypes.channelState: CodecPair(null, decodeChannelState), + CodecTypes.channelStateChange: CodecPair(null, decodeChannelStateChange), }; } getCodecType(final dynamic value){ if (value is ClientOptions) { - return _valueClientOptions; + return CodecTypes.clientOptions; } else if (value is TokenDetails) { - return _valueTokenDetails; + return CodecTypes.tokenDetails; } else if (value is ErrorInfo) { - return _valueErrorInfo; + return CodecTypes.errorInfo; } else if (value is AblyMessage) { - return _valueAblyMessage; + return CodecTypes.ablyMessage; } } diff --git a/lib/src/gen/platformconstants.dart b/lib/src/gen/platformconstants.dart new file mode 100644 index 000000000..db7073e80 --- /dev/null +++ b/lib/src/gen/platformconstants.dart @@ -0,0 +1,34 @@ +// +// Generated code. Do not modify. +// source: bin/templates/platformconstants.dart.hbs +// + +class CodecTypes{ + + static const int ablyMessage = 128; + static const int clientOptions = 129; + static const int tokenDetails = 130; + static const int errorInfo = 144; + static const int connectionEvent = 201; + static const int connectionState = 202; + static const int connectionStateChange = 203; + static const int channelEvent = 204; + static const int channelState = 205; + static const int channelStateChange = 206; + +} + +class PlatformMethod { + + static const String getPlatformVersion = "getPlatformVersion"; + static const String getVersion = "getVersion"; + static const String registerAbly = "registerAbly"; + static const String createRestWithOptions = "createRestWithOptions"; + static const String publish = "publish"; + static const String createRealtimeWithOptions = "createRealtimeWithOptions"; + static const String connectRealtime = "connectRealtime"; + static const String closeRealtime = "closeRealtime"; + static const String onRealtimeConnectionStateChanged = "onRealtimeConnectionStateChanged"; + static const String onRealtimeChannelStateChanged = "onRealtimeChannelStateChanged"; + +} diff --git a/lib/src/impl/platform_object.dart b/lib/src/impl/platform_object.dart index 4d855b96f..3b371980d 100644 --- a/lib/src/impl/platform_object.dart +++ b/lib/src/impl/platform_object.dart @@ -4,35 +4,6 @@ import 'package:flutter/services.dart'; import 'package:streams_channel/streams_channel.dart'; -/// A method with a corresponding handler in platform code. -enum PlatformMethod { - getPlatformVersion, - getVersion, - register, - - /// Rest - createRestWithOptions, - publish, - - /// Realtime - createRealtimeWithOptions, - connectRealtime, - closeRealtime, - - ///Realtime events - realtime_onConnectionStateChanged, - realtime_onChannelStateChanged, -} - -///Extension to extract string name from PlatformMethod -extension on PlatformMethod { - - /// ref: https://stackoverflow.com/a/59308734/392847 - String toName() => this.toString().split('.').last; - -} - - /// An object which has a live counterpart in the Platform client library SDK, /// where that live counterpart is held as a strong reference by the plugin /// implementation. @@ -58,15 +29,15 @@ abstract class PlatformObject { } /// Call a method. - Future invoke(final PlatformMethod method, [final dynamic argument]) async { + Future invoke(final String method, [final dynamic argument]) async { final message = (null != argument) ? AblyMessage(_ablyHandle, AblyMessage(_handle, argument)) : AblyMessage(_ablyHandle, _handle); - return await methodChannel.invokeMethod(method.toName(), message); + return await methodChannel.invokeMethod(method, message); } - Stream listen(final PlatformMethod method){ - return eventChannel.receiveBroadcastStream(AblyMessage(_ablyHandle, AblyMessage(_handle, method.toName()))); + Stream listen(final String method){ + return eventChannel.receiveBroadcastStream(AblyMessage(_ablyHandle, AblyMessage(_handle, method))); } } diff --git a/lib/src/impl/realtime/channels.dart b/lib/src/impl/realtime/channels.dart index 00b486819..2404ac00b 100644 --- a/lib/src/impl/realtime/channels.dart +++ b/lib/src/impl/realtime/channels.dart @@ -90,7 +90,7 @@ class RealtimePlatformChannel extends PlatformObject implements spec.RealtimeCha @override Stream on([ChannelEvent state]) { // TODO: implement on - Stream stream = listen(PlatformMethod.realtime_onChannelStateChanged); + Stream stream = listen(PlatformMethod.onRealtimeChannelStateChanged); if (state!=null) { return stream.takeWhile((ChannelStateChange _stateChange) => _stateChange.event==state); } diff --git a/lib/src/impl/realtime/connection.dart b/lib/src/impl/realtime/connection.dart index 1ba7b8747..2b52f05ce 100644 --- a/lib/src/impl/realtime/connection.dart +++ b/lib/src/impl/realtime/connection.dart @@ -31,7 +31,7 @@ class ConnectionPlatformObject extends PlatformObject implements Connection { @override Stream on([ConnectionEvent state]) { - Stream stream = listen(PlatformMethod.realtime_onConnectionStateChanged).transform( + Stream stream = listen(PlatformMethod.onRealtimeConnectionStateChanged).transform( StreamTransformer.fromHandlers( handleData: (dynamic value, EventSink sink){ sink.add(value as ConnectionStateChange); diff --git a/test/ably_flutter_plugin_test.dart b/test/ably_flutter_plugin_test.dart index 0bb55a445..70f1c6802 100644 --- a/test/ably_flutter_plugin_test.dart +++ b/test/ably_flutter_plugin_test.dart @@ -26,24 +26,28 @@ void main() { int ablyCounter = 0; int counter = 0; + //test constants + String platformVersion = '42'; + String nativeLibraryVersion = '1.1.0'; + setUp(() { channel.setMockMethodCallHandler((MethodCall methodCall) async { switch(methodCall.method){ - case "getPlatformVersion": - return '42'; - case "getVersion": - return '1.1.0'; + case PlatformMethod.getPlatformVersion: + return platformVersion; + case PlatformMethod.getVersion: + return nativeLibraryVersion; - case "register": + case PlatformMethod.registerAbly: return ++ablyCounter; case "createrestWithKey": - case "createRestWithOptions": - case "createRealtimeWithOptions": + case PlatformMethod.createRestWithOptions: + case PlatformMethod.createRealtimeWithOptions: return ++counter; - case "publish": - case "connectRealtime": + case PlatformMethod.publish: + case PlatformMethod.connectRealtime: default: return null; // eventsOff, @@ -57,15 +61,15 @@ void main() { channel.setMockMethodCallHandler(null); }); - test(PlatformMethod.getPlatformVersion.toName(), () async { - expect(await ably.platformVersion, '42'); + test(PlatformMethod.getPlatformVersion, () async { + expect(await ably.platformVersion, platformVersion); }); - test(PlatformMethod.getVersion.toName(), () async { - expect(await ably.version, '1.1.0'); + test(PlatformMethod.getVersion, () async { + expect(await ably.version, nativeLibraryVersion); }); - test(PlatformMethod.createRestWithOptions.toName(), () async { + test(PlatformMethod.createRestWithOptions, () async { ClientOptions o = ClientOptions(); String host = "http://rest.ably.io/"; o.restHost = host; @@ -75,10 +79,20 @@ void main() { expect(rest.options.restHost, host); }); + test("createRestWithToken", () async { + String key = 'TEST-KEY'; + RestPlatformObject rest = await ably.createRest(key: key); + expect(rest.ablyHandle, ablyCounter); + expect(rest.handle, counter); + expect(rest.options.tokenDetails.token, key); + }); + test("createRestWithKey", () async { - RestPlatformObject rest = await ably.createRest(key: 'TEST-KEY'); + String key = 'TEST:KEY'; + RestPlatformObject rest = await ably.createRest(key: key); expect(rest.ablyHandle, ablyCounter); expect(rest.handle, counter); + expect(rest.options.key, key); }); test("publishMessage", () async { From 0d1f80b3548f0af8283e75e5690a43c337fcb3b7 Mon Sep 17 00:00:00 2001 From: "Rohit R. Abbadi" Date: Thu, 21 May 2020 00:13:45 +0530 Subject: [PATCH 03/19] iOS | generated code usage in implementation files and DeveloperNotes update --- DeveloperNotes.md | 4 ++++ bin/templates/platformconstants.h.hbs | 4 ++-- bin/templates/platformconstants.m.hbs | 2 +- ios/Classes/AblyFlutterPlugin.m | 22 +++++++++------------- ios/Classes/AblyFlutterStreamHandler.m | 9 +++++---- ios/Classes/codec/AblyFlutterReader.m | 6 +++--- ios/Classes/codec/AblyFlutterWriter.m | 14 +++++++------- ios/Classes/codec/AblyPlatformConstants.h | 22 +++++++++++----------- ios/Classes/codec/AblyPlatformConstants.m | 2 +- 9 files changed, 43 insertions(+), 42 deletions(-) diff --git a/DeveloperNotes.md b/DeveloperNotes.md index baaad5550..17dcfe5b5 100644 --- a/DeveloperNotes.md +++ b/DeveloperNotes.md @@ -52,4 +52,8 @@ samples, guidance on mobile development, and a full API reference. ## Generating platform constants +Some files in the project are generated to maintain sync between + platform constants on both native and dart side. + Generated file paths are configured as values in `bin/codegen.dart` for `toGenerate` Map + [Read about generation of platform specific constant files](bin/README.md) diff --git a/bin/templates/platformconstants.h.hbs b/bin/templates/platformconstants.h.hbs index 0bc8ed301..e7686da11 100644 --- a/bin/templates/platformconstants.h.hbs +++ b/bin/templates/platformconstants.h.hbs @@ -2,12 +2,12 @@ typedef NS_ENUM(UInt8, _Value) { - {{#each types}}codecTypes_{{name}} = {{value}}, + {{#each types}}{{name}}CodecType = {{value}}, {{/each}} }; -@interface PLATFORM_METHODS : NSObject +@interface AblyPlatformMethod : NSObject {{#each methods}}@property (class, nonatomic, assign, readonly) NSString *{{name}}; {{/each}} diff --git a/bin/templates/platformconstants.m.hbs b/bin/templates/platformconstants.m.hbs index 207021813..0915c39bc 100644 --- a/bin/templates/platformconstants.m.hbs +++ b/bin/templates/platformconstants.m.hbs @@ -2,7 +2,7 @@ #import "AblyPlatformConstants.h" -@implementation PLATFORM_METHODS +@implementation AblyPlatformMethod {{#each methods}}+ (NSString*) {{name}} { return @"{{value}}"; } {{/each}} diff --git a/ios/Classes/AblyFlutterPlugin.m b/ios/Classes/AblyFlutterPlugin.m index 037cf235f..9a4027a4b 100644 --- a/ios/Classes/AblyFlutterPlugin.m +++ b/ios/Classes/AblyFlutterPlugin.m @@ -9,6 +9,7 @@ #import "AblyFlutter.h" #import "AblyFlutterStreamHandler.h" #import "FlutterStreamsChannel.h" +#import "codec/AblyPlatformConstants.h" #define LOG(fmt, ...) NSLog((@"%@:%d " fmt), [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, ##__VA_ARGS__) @@ -101,10 +102,6 @@ -(nullable AblyFlutter *)ablyWithHandle:(NSNumber *)handle; result(nil); }; -static FlutterHandler _dispose = ^void(AblyFlutterPlugin *const plugin, FlutterMethodCall *const call, const FlutterResult result) { - // TODO -}; - @implementation AblyFlutterPlugin { long long _nextRegistration; NSDictionary* _handlers; @@ -139,15 +136,14 @@ -(instancetype)initWithChannel:(FlutterMethodChannel *const)channel { } _handlers = @{ - @"getPlatformVersion": _getPlatformVersion, - @"getVersion": _getVersion, - @"register": _register, - @"createRestWithOptions": _createRestWithOptions, - @"publish": _publishRestMessage, - @"createRealtimeWithOptions": _createRealtimeWithOptions, - @"connectRealtime": _connectRealtime, - @"closeRealtime": _closeRealtime, - @"dispose": _dispose, + AblyPlatformMethod.getPlatformVersion: _getPlatformVersion, + AblyPlatformMethod.getVersion: _getVersion, + AblyPlatformMethod.registerAbly: _register, + AblyPlatformMethod.createRestWithOptions: _createRestWithOptions, + AblyPlatformMethod.publish: _publishRestMessage, + AblyPlatformMethod.createRealtimeWithOptions: _createRealtimeWithOptions, + AblyPlatformMethod.connectRealtime: _connectRealtime, + AblyPlatformMethod.closeRealtime: _closeRealtime }; _nextRegistration = 1; diff --git a/ios/Classes/AblyFlutterStreamHandler.m b/ios/Classes/AblyFlutterStreamHandler.m index bc1236de9..37b7a869c 100644 --- a/ios/Classes/AblyFlutterStreamHandler.m +++ b/ios/Classes/AblyFlutterStreamHandler.m @@ -2,6 +2,7 @@ #import "AblyFlutterPlugin.h" #import "AblyFlutterMessage.h" #import "ARTRealtime.h" +#import "codec/AblyPlatformConstants.h" @implementation AblyFlutterStreamHandler{ ARTEventListener *listener; @@ -30,11 +31,11 @@ - (void) startListening:(AblyFlutterMessage *const)message emitter:(FlutterEvent AblyFlutterMessage *const _message = message.message; NSString *const eventName = _message.message; - if([@"realtime_onConnectionStateChanged" isEqual: eventName]) { + if([AblyPlatformMethod.onRealtimeConnectionStateChanged isEqual: eventName]) { listener = [[ably realtimeWithHandle: message.handle].connection on: ^(ARTConnectionStateChange * const stateChange) { emitter(stateChange); }]; - } else if([@"realtime_onChannelStateChanged" isEqual: eventName]) { + } else if([AblyPlatformMethod.onRealtimeChannelStateChanged isEqual: eventName]) { } } @@ -44,9 +45,9 @@ - (void) cancelListening:(AblyFlutterMessage *const)message { AblyFlutterMessage *const _message = message.message; NSString *const eventName = _message.message; - if([@"realtime_onConnectionStateChanged" isEqual: eventName]) { + if([AblyPlatformMethod.onRealtimeConnectionStateChanged isEqual: eventName]) { [[ably realtimeWithHandle: message.handle].connection off: listener]; - } else if([@"realtime_onChannelStateChanged" isEqual: eventName]) { + } else if([AblyPlatformMethod.onRealtimeChannelStateChanged isEqual: eventName]) { } } diff --git a/ios/Classes/codec/AblyFlutterReader.m b/ios/Classes/codec/AblyFlutterReader.m index 330862524..f33698372 100644 --- a/ios/Classes/codec/AblyFlutterReader.m +++ b/ios/Classes/codec/AblyFlutterReader.m @@ -20,13 +20,13 @@ @implementation AblyFlutterReader -(id)readValueOfType:(const UInt8)type { switch (type) { - case codecTypes_clientOptions: + case clientOptionsCodecType: return [self readClientOptions]; - case codecTypes_tokenDetails: + case tokenDetailsCodecType: return [self readTokenDeatils]; - case codecTypes_ablyMessage: + case ablyMessageCodecType: return [self readAblyFlutterMessage]; } diff --git a/ios/Classes/codec/AblyFlutterWriter.m b/ios/Classes/codec/AblyFlutterWriter.m index 9bb3e9987..3e6ef8979 100644 --- a/ios/Classes/codec/AblyFlutterWriter.m +++ b/ios/Classes/codec/AblyFlutterWriter.m @@ -28,7 +28,7 @@ - (void) writeEnum:(UInt8) type enumValue: (int const) enumValue{ } - (void) writeErrorInfo:(ARTErrorInfo *const) e{ - [self writeByte:codecTypes_errorInfo]; + [self writeByte:errorInfoCodecType]; [self writeValue: nil]; //code - not available in ably-cocoa [self writeValue: [e message]]; [self writeValue: @([e statusCode])]; @@ -37,10 +37,10 @@ - (void) writeErrorInfo:(ARTErrorInfo *const) e{ [self writeValue: nil]; //cause - not available in ably-java } -- (void) writeConnectState:(ARTRealtimeConnectionState const) state{ [self writeEnum:codecTypes_connectionState enumValue:state]; } -- (void) writeConnectEvent:(ARTRealtimeConnectionEvent const) event{ [self writeEnum:codecTypes_connectionEvent enumValue:event]; } +- (void) writeConnectState:(ARTRealtimeConnectionState const) state{ [self writeEnum:connectionStateCodecType enumValue:state]; } +- (void) writeConnectEvent:(ARTRealtimeConnectionEvent const) event{ [self writeEnum:connectionEventCodecType enumValue:event]; } - (void) writeConnectionStateChange:(ARTConnectionStateChange *const) stateChange{ - [self writeByte:codecTypes_connectionStateChange]; + [self writeByte:connectionStateChangeCodecType]; [self writeConnectState: [stateChange current]]; [self writeConnectState: [stateChange previous]]; [self writeConnectEvent: [stateChange event]]; @@ -48,10 +48,10 @@ - (void) writeConnectionStateChange:(ARTConnectionStateChange *const) stateChang [self writeValue: [stateChange reason]]; } -- (void) writeChannelState:(ARTRealtimeChannelState const) state{ [self writeEnum:codecTypes_channelState enumValue:state]; } -- (void) writeChannelEvent:(ARTChannelEvent const) event{ [self writeEnum:codecTypes_channelEvent enumValue:event]; } +- (void) writeChannelState:(ARTRealtimeChannelState const) state{ [self writeEnum:channelStateCodecType enumValue:state]; } +- (void) writeChannelEvent:(ARTChannelEvent const) event{ [self writeEnum:channelEventCodecType enumValue:event]; } - (void) writeChannelStateChange:(ARTChannelStateChange *const) stateChange{ - [self writeByte:codecTypes_channelStateChange]; + [self writeByte:channelStateChangeCodecType]; [self writeChannelState: [stateChange current]]; [self writeChannelState: [stateChange previous]]; [self writeChannelEvent: [stateChange event]]; diff --git a/ios/Classes/codec/AblyPlatformConstants.h b/ios/Classes/codec/AblyPlatformConstants.h index 263554ce1..400a208df 100644 --- a/ios/Classes/codec/AblyPlatformConstants.h +++ b/ios/Classes/codec/AblyPlatformConstants.h @@ -7,21 +7,21 @@ typedef NS_ENUM(UInt8, _Value) { - codecTypes_ablyMessage = 128, - codecTypes_clientOptions = 129, - codecTypes_tokenDetails = 130, - codecTypes_errorInfo = 144, - codecTypes_connectionEvent = 201, - codecTypes_connectionState = 202, - codecTypes_connectionStateChange = 203, - codecTypes_channelEvent = 204, - codecTypes_channelState = 205, - codecTypes_channelStateChange = 206, + ablyMessageCodecType = 128, + clientOptionsCodecType = 129, + tokenDetailsCodecType = 130, + errorInfoCodecType = 144, + connectionEventCodecType = 201, + connectionStateCodecType = 202, + connectionStateChangeCodecType = 203, + channelEventCodecType = 204, + channelStateCodecType = 205, + channelStateChangeCodecType = 206, }; -@interface PLATFORM_METHODS : NSObject +@interface AblyPlatformMethod : NSObject @property (class, nonatomic, assign, readonly) NSString *getPlatformVersion; @property (class, nonatomic, assign, readonly) NSString *getVersion; diff --git a/ios/Classes/codec/AblyPlatformConstants.m b/ios/Classes/codec/AblyPlatformConstants.m index a12fae315..6c9948375 100644 --- a/ios/Classes/codec/AblyPlatformConstants.m +++ b/ios/Classes/codec/AblyPlatformConstants.m @@ -7,7 +7,7 @@ #import "AblyPlatformConstants.h" -@implementation PLATFORM_METHODS +@implementation AblyPlatformMethod + (NSString*) getPlatformVersion { return @"getPlatformVersion"; } + (NSString*) getVersion { return @"getVersion"; } From cc1b82bad52231bfae05c1aa47399e88c66d56d5 Mon Sep 17 00:00:00 2001 From: "Rohit R. Abbadi" Date: Thu, 21 May 2020 00:19:22 +0530 Subject: [PATCH 04/19] android | generated code usage in implementation files --- .../flutter/plugin/AblyEventStreamHandler.java | 9 +++++---- .../flutter/plugin/AblyMethodCallHandler.java | 17 +++++++++-------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/android/src/main/java/io/ably/flutter/plugin/AblyEventStreamHandler.java b/android/src/main/java/io/ably/flutter/plugin/AblyEventStreamHandler.java index 4139fb19b..a4dc0b812 100644 --- a/android/src/main/java/io/ably/flutter/plugin/AblyEventStreamHandler.java +++ b/android/src/main/java/io/ably/flutter/plugin/AblyEventStreamHandler.java @@ -3,6 +3,7 @@ import android.os.Handler; import android.os.Looper; +import io.ably.flutter.plugin.gen.PlatformConstants; import io.ably.lib.realtime.ChannelStateListener; import io.ably.lib.realtime.ConnectionStateListener; import io.flutter.plugin.common.EventChannel; @@ -83,11 +84,11 @@ public void onListen(Object object, EventChannel.EventSink uiThreadEventSink) { methodCallHandler.>ablyDo((AblyFlutterMessage)object, (ablyLibrary, message) -> { String eventName = message.message; switch(eventName) { - case "realtime_onConnectionStateChanged": + case PlatformConstants.PlatformMethod.onRealtimeConnectionStateChanged: connectionStateListener = new PluginConnectionStateListener(eventSink); ablyLibrary.getRealtime(message.handle).connection.on(connectionStateListener); return; - case "realtime_onChannelStateChanged": + case PlatformConstants.PlatformMethod.onRealtimeChannelStateChanged: // channelStateListener = new PluginChannelStateListener(eventSink); // ablyLibrary.getRealtime(message.handle).connection.on(channelStateListener); // return; @@ -106,9 +107,9 @@ public void onCancel(Object object) { methodCallHandler.>ablyDo((AblyFlutterMessage)object, (ablyLibrary, message) -> { String eventName = message.message; switch (eventName) { - case "realtime_onConnectionStateChanged": + case PlatformConstants.PlatformMethod.onRealtimeConnectionStateChanged: ablyLibrary.getRealtime(message.handle).connection.off(connectionStateListener); - case "realtime_onChannelStateChanged": + case PlatformConstants.PlatformMethod.onRealtimeChannelStateChanged: // ablyLibrary.getRealtime(handle).connection.off(connectionStateListener); } }); diff --git a/android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java b/android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java index 190c4c07d..2e15e6e0a 100644 --- a/android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java +++ b/android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java @@ -16,6 +16,7 @@ import io.ably.lib.types.ErrorInfo; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; +import io.ably.flutter.plugin.gen.PlatformConstants; public class AblyMethodCallHandler implements MethodChannel.MethodCallHandler { private static AblyMethodCallHandler _instance; @@ -35,18 +36,18 @@ static synchronized AblyMethodCallHandler getInstance() { private AblyMethodCallHandler() { _map = new HashMap<>(); - _map.put("getPlatformVersion", this::getPlatformVersion); - _map.put("getVersion", this::getVersion); - _map.put("register", this::register); + _map.put(PlatformConstants.PlatformMethod.getPlatformVersion, this::getPlatformVersion); + _map.put(PlatformConstants.PlatformMethod.getVersion, this::getVersion); + _map.put(PlatformConstants.PlatformMethod.registerAbly, this::register); // Rest - _map.put("createRestWithOptions", this::createRestWithOptions); - _map.put("publish", this::publishRestMessage); + _map.put(PlatformConstants.PlatformMethod.createRestWithOptions, this::createRestWithOptions); + _map.put(PlatformConstants.PlatformMethod.publish, this::publishRestMessage); //Realtime - _map.put("createRealtimeWithOptions", this::createRealtimeWithOptions); - _map.put("connectRealtime", this::connectRealtime); - _map.put("closeRealtime", this::closeRealtime); + _map.put(PlatformConstants.PlatformMethod.createRealtimeWithOptions, this::createRealtimeWithOptions); + _map.put(PlatformConstants.PlatformMethod.connectRealtime, this::connectRealtime); + _map.put(PlatformConstants.PlatformMethod.closeRealtime, this::closeRealtime); } From de7f6902ab162a75c611ac4465d310de0b3c0f46 Mon Sep 17 00:00:00 2001 From: "Rohit R. Abbadi" Date: Sat, 23 May 2020 13:30:01 +0530 Subject: [PATCH 05/19] Transmission using plain JSON. Coded refactored on dart, iOS and Android end --- .../ably/flutter/plugin/AblyMessageCodec.java | 220 ++++++------ ios/Classes/codec/AblyFlutterReader.h | 7 + ios/Classes/codec/AblyFlutterReader.m | 163 +++++---- ios/Classes/codec/AblyFlutterWriter.m | 73 ++-- lib/src/codec.dart | 322 +++++++++++------- lib/src/impl/message.dart | 3 +- lib/src/spec/common.dart | 2 +- 7 files changed, 463 insertions(+), 327 deletions(-) diff --git a/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java b/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java index 277ef30f5..49c844f88 100644 --- a/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java +++ b/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java @@ -22,10 +22,9 @@ public class AblyMessageCodec extends StandardMessageCodec { -// @FunctionalInterface - interface CodecEncoder{ void encode(ByteArrayOutputStream stream, T value); } -// @FunctionalInterface - interface CodecDecoder{ T decode(ByteBuffer buffer); } + interface CodecEncoder{ Map encode(T value); } + interface CodecDecoder{ T decode(Map jsonMap); } + class CodecPair{ final CodecEncoder encoder; @@ -35,20 +34,20 @@ class CodecPair{ this.decoder = decoder; } - void encode(final ByteArrayOutputStream stream, final Object value){ + Map encode(final Object value){ if(this.encoder==null){ System.out.println("Codec encoder not defined"); - return; + return null; } - this.encoder.encode(stream, (T)value); + return this.encoder.encode((T)value); } - T decode(ByteBuffer buffer){ + T decode(Map jsonMap){ if(this.decoder==null){ System.out.println("Codec decoder not defined"); return null; } - return this.decoder.decode(buffer); + return this.decoder.decode(jsonMap); } } @@ -60,15 +59,15 @@ T decode(ByteBuffer buffer){ { put(PlatformConstants.CodecTypes.ablyMessage, new CodecPair<>(null, self::readAblyFlutterMessage)); put(PlatformConstants.CodecTypes.clientOptions, new CodecPair<>(null, self::readClientOptions)); - put(PlatformConstants.CodecTypes.tokenDetails, new CodecPair<>(null, self::readTokenDetails)); - put(PlatformConstants.CodecTypes.errorInfo, new CodecPair<>(self::writeErrorInfo, null)); +// put(PlatformConstants.CodecTypes.tokenDetails, new CodecPair<>(null, self::readTokenDetails)); + put(PlatformConstants.CodecTypes.errorInfo, new CodecPair<>(self::encodeErrorInfo, null)); - put(PlatformConstants.CodecTypes.connectionEvent, new CodecPair<>(self::writeConnectionEvent, null)); - put(PlatformConstants.CodecTypes.connectionState, new CodecPair<>(self::writeConnectionState, null)); - put(PlatformConstants.CodecTypes.connectionStateChange, new CodecPair<>(self::writeConnectionStateChange, null)); +// put(PlatformConstants.CodecTypes.connectionEvent, new CodecPair<>(self::writeConnectionEvent, null)); +// put(PlatformConstants.CodecTypes.connectionState, new CodecPair<>(self::writeConnectionState, null)); + put(PlatformConstants.CodecTypes.connectionStateChange, new CodecPair<>(self::encodeConnectionStateChange, null)); - put(PlatformConstants.CodecTypes.channelEvent, new CodecPair<>(self::writeChannelEvent, null)); - put(PlatformConstants.CodecTypes.channelState, new CodecPair<>(self::writeChannelState, null)); +// put(PlatformConstants.CodecTypes.channelEvent, new CodecPair<>(self::writeChannelEvent, null)); +// put(PlatformConstants.CodecTypes.channelState, new CodecPair<>(self::writeChannelState, null)); put(PlatformConstants.CodecTypes.channelStateChange, new CodecPair<>(self::writeChannelStateChange, null)); } }; @@ -78,18 +77,31 @@ T decode(ByteBuffer buffer){ protected Object readValueOfType(final byte type, final ByteBuffer buffer) { CodecPair pair = codecMap.get(type); if(pair!=null){ - return pair.decode(buffer); + Map jsonMap = (Map)readValue(buffer); + return pair.decode(jsonMap); } return super.readValueOfType(type, buffer); } - private void readValue(final ByteBuffer buffer, final Consumer consumer) { - final Object object = readValue(buffer); + private void readValueFromJson(Map jsonMap, String key, final Consumer consumer) { + final Object object = jsonMap.get(key); if (null != object) { consumer.accept(object); } } + private void writeValueToJson(Map jsonMap, String key, Object value) { + if (null != value) { + jsonMap.put(key, value); + } + } + + private void writeEnumToJson(Map jsonMap, String key, Enum value) { + if (null != value) { + jsonMap.put(key, value.ordinal()); + } + } + @Override protected void writeValue(ByteArrayOutputStream stream, Object value) { Byte type = null; @@ -111,7 +123,9 @@ protected void writeValue(ByteArrayOutputStream stream, Object value) { if(type!=null){ CodecPair pair = codecMap.get(type); if(pair!=null) { - pair.encode(stream, value); + stream.write(type); + Map jsonMap = pair.encode(value); + writeValue(stream, jsonMap); return; } } @@ -123,8 +137,7 @@ protected void writeValue(ByteArrayOutputStream stream, Object value) { * they are delivered as Long. * See: https://flutter.dev/docs/development/platform-integration/platform-channels#codec */ - private Long readValueAsLong(final ByteBuffer buffer) { - final Object object = readValue(buffer); + private Long readValueAsLong(final Object object) { if (null == object) { return null; } @@ -134,102 +147,119 @@ private Long readValueAsLong(final ByteBuffer buffer) { return (Long)object; // will java.lang.ClassCastException if object is not a Long } - private AblyFlutterMessage readAblyFlutterMessage(final ByteBuffer buffer) { - final Long handle = readValueAsLong(buffer); - final Object message = readValue(buffer); + private AblyFlutterMessage readAblyFlutterMessage(Map jsonMap) { + if(jsonMap==null) return null; + final Long handle = readValueAsLong(jsonMap.get("registrationHandle")); + Object messageType = jsonMap.get("type"); + final Integer type = (messageType==null)?null:Integer.parseInt(messageType.toString()); + Object message = jsonMap.get("message"); + if(type!=null){ + message = codecMap.get((byte)(int)type).decode((Map)message); + } return new AblyFlutterMessage<>(handle, message); } - private ClientOptions readClientOptions(final ByteBuffer buffer) { + private ClientOptions readClientOptions(Map jsonMap) { + if(jsonMap==null) return null; final ClientOptions o = new ClientOptions(); // AuthOptions (super class of ClientOptions) - readValue(buffer, v -> o.authUrl = (String)v); - readValue(buffer, v -> o.authMethod = (String)v); - readValue(buffer, v -> o.key = (String)v); - readValue(buffer, v -> o.tokenDetails = (Auth.TokenDetails)v); - readValue(buffer, v -> o.authHeaders = (Param[])v); - readValue(buffer, v -> o.authParams = (Param[])v); - readValue(buffer, v -> o.queryTime = (Boolean)v); - readValue(buffer); // o.useAuthToken + readValueFromJson(jsonMap, "authUrl", v -> o.authUrl = (String)v); + readValueFromJson(jsonMap, "authMethod", v -> o.authMethod = (String)v); + readValueFromJson(jsonMap, "key", v -> o.key = (String)v); + readValueFromJson(jsonMap, "tokenDetails", v -> o.tokenDetails = readTokenDetails((Map)v)); + readValueFromJson(jsonMap, "authHeaders", v -> o.authHeaders = (Param[])v); + readValueFromJson(jsonMap, "authParams", v -> o.authParams = (Param[])v); + readValueFromJson(jsonMap, "queryTime", v -> o.queryTime = (Boolean)v); +// readValueFromJson(buffer); // o.useAuthToken // ClientOptions - readValue(buffer, v -> o.clientId = (String)v); - readValue(buffer, v -> o.logLevel = (Integer)v); - readValue(buffer, v -> o.tls = (Boolean)v); - readValue(buffer, v -> o.restHost = (String)v); - readValue(buffer, v -> o.realtimeHost = (String)v); - readValue(buffer, v -> o.port = (Integer)v); - readValue(buffer, v -> o.tlsPort = (Integer)v); - readValue(buffer, v -> o.autoConnect = (Boolean)v); - readValue(buffer, v -> o.useBinaryProtocol = (Boolean)v); - readValue(buffer, v -> o.queueMessages = (Boolean)v); - readValue(buffer, v -> o.echoMessages = (Boolean)v); - readValue(buffer, v -> o.recover = (String)v); - readValue(buffer, v -> o.environment = (String)v); - readValue(buffer, v -> o.idempotentRestPublishing = (Boolean)v); - readValue(buffer, v -> o.httpOpenTimeout = (Integer)v); - readValue(buffer, v -> o.httpRequestTimeout = (Integer)v); - readValue(buffer, v -> o.httpMaxRetryCount = (Integer)v); - readValue(buffer, v -> o.realtimeRequestTimeout = (Long)v); - readValue(buffer, v -> o.fallbackHosts = (String[])v); - readValue(buffer, v -> o.fallbackHostsUseDefault = (Boolean)v); - readValue(buffer, v -> o.fallbackRetryTimeout = (Long)v); - readValue(buffer, v -> o.defaultTokenParams = (Auth.TokenParams) v); - readValue(buffer, v -> o.channelRetryTimeout = (Integer)v); - readValue(buffer, v -> o.transportParams = (Param[])v); + readValueFromJson(jsonMap, "clientId", v -> o.clientId = (String)v); + readValueFromJson(jsonMap, "logLevel", v -> o.logLevel = (Integer)v); + readValueFromJson(jsonMap, "tls", v -> o.tls = (Boolean)v); + readValueFromJson(jsonMap, "restHost", v -> o.restHost = (String)v); + readValueFromJson(jsonMap, "realtimeHost", v -> o.realtimeHost = (String)v); + readValueFromJson(jsonMap, "port", v -> o.port = (Integer)v); + readValueFromJson(jsonMap, "tlsPort", v -> o.tlsPort = (Integer)v); + readValueFromJson(jsonMap, "autoConnect", v -> o.autoConnect = (Boolean)v); + readValueFromJson(jsonMap, "useBinaryProtocol", v -> o.useBinaryProtocol = (Boolean)v); + readValueFromJson(jsonMap, "queueMessages", v -> o.queueMessages = (Boolean)v); + readValueFromJson(jsonMap, "echoMessages", v -> o.echoMessages = (Boolean)v); + readValueFromJson(jsonMap, "recover", v -> o.recover = (String)v); + readValueFromJson(jsonMap, "environment", v -> o.environment = (String)v); + readValueFromJson(jsonMap, "idempotentRestPublishing", v -> o.idempotentRestPublishing = (Boolean)v); + readValueFromJson(jsonMap, "httpOpenTimeout", v -> o.httpOpenTimeout = (Integer)v); + readValueFromJson(jsonMap, "httpRequestTimeout", v -> o.httpRequestTimeout = (Integer)v); + readValueFromJson(jsonMap, "httpMaxRetryCount", v -> o.httpMaxRetryCount = (Integer)v); + readValueFromJson(jsonMap, "realtimeRequestTimeout", v -> o.realtimeRequestTimeout = (Long)v); + readValueFromJson(jsonMap, "fallbackHosts", v -> o.fallbackHosts = (String[])v); + readValueFromJson(jsonMap, "fallbackHostsUseDefault", v -> o.fallbackHostsUseDefault = (Boolean)v); + readValueFromJson(jsonMap, "fallbackRetryTimeout", v -> o.fallbackRetryTimeout = (Long)v); + readValueFromJson(jsonMap, "defaultTokenParams", v -> o.defaultTokenParams = readTokenParams((Map)v)); + readValueFromJson(jsonMap, "channelRetryTimeout", v -> o.channelRetryTimeout = (Integer)v); + readValueFromJson(jsonMap, "transportParams", v -> o.transportParams = (Param[])v); return o; } - private TokenDetails readTokenDetails(final ByteBuffer buffer) { + private TokenDetails readTokenDetails(Map jsonMap) { + if(jsonMap==null) return null; final TokenDetails o = new TokenDetails(); + readValueFromJson(jsonMap, "token", v -> o.token = (String)v); + readValueFromJson(jsonMap, "expires", v -> o.expires = (int)v); + readValueFromJson(jsonMap, "issued", v -> o.issued = (int)v); + readValueFromJson(jsonMap, "capability", v -> o.capability = (String)v); + readValueFromJson(jsonMap, "clientId", v -> o.clientId = (String)v); - readValue(buffer, v -> o.token = (String)v); - readValue(buffer, v -> o.expires = (int)v); - readValue(buffer, v -> o.issued = (int)v); - readValue(buffer, v -> o.capability = (String)v); - readValue(buffer, v -> o.clientId = (String)v); + return o; + } + private Auth.TokenParams readTokenParams(Map jsonMap) { + if(jsonMap==null) return null; + final Auth.TokenParams o = new Auth.TokenParams(); + readValueFromJson(jsonMap, "capability", v -> o.capability = (String)v); + readValueFromJson(jsonMap, "clientId", v -> o.clientId = (String)v); + readValueFromJson(jsonMap, "timestamp", v -> o.timestamp = (int)v); + readValueFromJson(jsonMap, "ttl", v -> o.ttl = (long)v); + //nonce is not supported in ably-java return o; } +//=============================================================== +//=====================HANDLING WRITE============================ +//=============================================================== - //HANDLING WRITE - private void writeErrorInfo(ByteArrayOutputStream stream, ErrorInfo e){ - stream.write(PlatformConstants.CodecTypes.errorInfo); - writeValue(stream, e.code); - writeValue(stream, e.message); - writeValue(stream, e.statusCode); - writeValue(stream, e.href); - writeValue(stream, null); //requestId - not available in ably-java - writeValue(stream, null); //cause - not available in ably-java + private Map encodeErrorInfo(ErrorInfo c){ + if(c==null) return null; + HashMap jsonMap = new HashMap<>(); + writeValueToJson(jsonMap, "code", c.code); + writeValueToJson(jsonMap, "message", c.message); + writeValueToJson(jsonMap, "statusCode", c.statusCode); + writeValueToJson(jsonMap, "href", c.href); + //requestId and cause - not available in ably-java + return jsonMap; } - private void writeConnectionEvent(ByteArrayOutputStream stream, ConnectionEvent e){ writeEnum(stream, PlatformConstants.CodecTypes.connectionEvent, e); } - private void writeConnectionState(ByteArrayOutputStream stream, ConnectionState e){ writeEnum(stream, PlatformConstants.CodecTypes.connectionState, e); } - private void writeConnectionStateChange(ByteArrayOutputStream stream, ConnectionStateListener.ConnectionStateChange c){ - stream.write(PlatformConstants.CodecTypes.connectionStateChange); - writeValue(stream, c.current); - writeValue(stream, c.previous); - writeValue(stream, c.event); - writeValue(stream, c.retryIn); - writeValue(stream, c.reason); + private Map encodeConnectionStateChange(ConnectionStateListener.ConnectionStateChange c){ + if(c==null) return null; + HashMap jsonMap = new HashMap<>(); + writeEnumToJson(jsonMap, "current", c.current); + writeEnumToJson(jsonMap, "previous", c.previous); + writeEnumToJson(jsonMap, "event", c.event); + writeValueToJson(jsonMap, "retryIn", c.retryIn); + writeValueToJson(jsonMap, "reason", encodeErrorInfo(c.reason)); + return jsonMap; } - private void writeChannelEvent(ByteArrayOutputStream stream, ChannelEvent e){ writeEnum(stream, PlatformConstants.CodecTypes.channelEvent, e); } - private void writeChannelState(ByteArrayOutputStream stream, ChannelState e){ writeEnum(stream, PlatformConstants.CodecTypes.channelState, e); } - private void writeChannelStateChange(ByteArrayOutputStream stream, ChannelStateListener.ChannelStateChange c){ - stream.write(PlatformConstants.CodecTypes.channelStateChange); - writeValue(stream, c.current); - writeValue(stream, c.previous); - writeValue(stream, c.event); - writeValue(stream, c.resumed); - writeValue(stream, c.reason); + private Map writeChannelStateChange(ChannelStateListener.ChannelStateChange c){ + if(c==null) return null; + HashMap jsonMap = new HashMap<>(); + writeEnumToJson(jsonMap, "current", c.current); + writeEnumToJson(jsonMap, "previous", c.previous); + writeEnumToJson(jsonMap, "event", c.event); + writeValueToJson(jsonMap, "resumed", c.resumed); + writeValueToJson(jsonMap, "reason", encodeErrorInfo(c.reason)); + return jsonMap; } - private void writeEnum(ByteArrayOutputStream stream, int eventCode, Enum e){ - stream.write(eventCode); - writeValue(stream, e.ordinal()); - } } diff --git a/ios/Classes/codec/AblyFlutterReader.h b/ios/Classes/codec/AblyFlutterReader.h index a51bede1d..9b26bb570 100644 --- a/ios/Classes/codec/AblyFlutterReader.h +++ b/ios/Classes/codec/AblyFlutterReader.h @@ -1,9 +1,16 @@ @import Foundation; @import Flutter; +#import "ARTTokenDetails.h" +#import "ARTTokenParams.h" + NS_ASSUME_NONNULL_BEGIN @interface AblyFlutterReader : FlutterStandardReader + ++(ARTTokenDetails *)readTokenDetails: (NSDictionary *) jsonDict; ++(ARTTokenParams *)readTokenParams: (NSDictionary *) jsonDict; + @end NS_ASSUME_NONNULL_END diff --git a/ios/Classes/codec/AblyFlutterReader.m b/ios/Classes/codec/AblyFlutterReader.m index f33698372..443c396e9 100644 --- a/ios/Classes/codec/AblyFlutterReader.m +++ b/ios/Classes/codec/AblyFlutterReader.m @@ -2,6 +2,8 @@ #import "Ably.h" #import "AblyFlutterMessage.h" #import "AblyPlatformConstants.h" +#import "ARTTokenDetails.h" +#import "ARTTokenParams.h" static ARTLogLevel _logLevel(NSNumber *const number) { @@ -16,28 +18,36 @@ static ARTLogLevel _logLevel(NSNumber *const number) { return ARTLogLevelWarn; } +typedef id (^AblyCodecDecoder)(NSDictionary * jsonDict); + @implementation AblyFlutterReader + ++ (AblyCodecDecoder) getDecoder:(const NSString*)type { + NSDictionary* _handlers = @{ + [NSString stringWithFormat:@"%d", ablyMessageCodecType]: readAblyFlutterMessage, + [NSString stringWithFormat:@"%d", clientOptionsCodecType]: readClientOptions, + }; + return [_handlers objectForKey:[NSString stringWithFormat:@"%@", type]]; +} + -(id)readValueOfType:(const UInt8)type { - switch (type) { - case clientOptionsCodecType: - return [self readClientOptions]; - - case tokenDetailsCodecType: - return [self readTokenDeatils]; - - case ablyMessageCodecType: - return [self readAblyFlutterMessage]; + AblyCodecDecoder decoder = [AblyFlutterReader getDecoder: [NSString stringWithFormat:@"%d", type]]; + if(decoder){ + return decoder([self readValue]); + }else{ + return [super readValueOfType:type]; } - - return [super readValueOfType:type]; } --(AblyFlutterMessage *)readAblyFlutterMessage { - NSNumber *const handle = [self readValue]; - const id message = [self readValue]; - return [[AblyFlutterMessage alloc] initWithHandle:handle message:message]; -} +static AblyCodecDecoder readAblyFlutterMessage = ^AblyFlutterMessage*(NSDictionary *const jsonDict) { + AblyCodecDecoder decoder = [AblyFlutterReader getDecoder: [NSString stringWithFormat:@"%@", [jsonDict objectForKey:@"type"]]]; + id message = [jsonDict objectForKey:@"message"]; + if(decoder){ + message = decoder(message); + } + return [[AblyFlutterMessage alloc] initWithHandle:[jsonDict objectForKey:@"registrationHandle"] message:message]; +}; /** A macro to reduce boilerplate code for each value read where the pattern is to @@ -56,87 +66,104 @@ use an explicitly received null from Dart (manifesting this side as a nil id) object (other than null) that indicates the Objective-C property value is to be set to an id value of nil. */ -#define ON_VALUE(BLOCK) { \ - const id value = [self readValue]; \ +#define ON_VALUE(BLOCK, JSON_DICT, JSON_KEY) { \ + const id value = [JSON_DICT objectForKey: JSON_KEY]; \ if (value) { \ BLOCK(value); \ } \ } -#define READ_VALUE(OBJECT, PROPERTY) { \ - ON_VALUE(^(const id value) { OBJECT.PROPERTY = value; }); \ +#define READ_VALUE(OBJECT, PROPERTY, JSON_DICT, JSON_KEY) { \ + ON_VALUE(^(const id value) { OBJECT.PROPERTY = value; }, JSON_DICT, JSON_KEY); \ } /** Where an NSNumber has been decoded and the property to be set is BOOL. */ -#define READ_BOOL(OBJECT, PROPERTY) { \ - ON_VALUE(^(const id number) { OBJECT.PROPERTY = [number boolValue]; }); \ +#define READ_BOOL(OBJECT, PROPERTY, JSON_DICT, JSON_KEY) { \ + ON_VALUE(^(const id number) { OBJECT.PROPERTY = [number boolValue]; }, JSON_DICT, JSON_KEY); \ } --(ARTClientOptions *)readClientOptions { +static AblyCodecDecoder readClientOptions = ^AblyFlutterMessage*(NSDictionary *const jsonDict) { ARTClientOptions *const o = [ARTClientOptions new]; - + + if([jsonDict objectForKey:@"message"]) o.authUrl = [jsonDict objectForKey:@"message"]; + // AuthOptions (super class of ClientOptions) - READ_VALUE(o, authUrl); - READ_VALUE(o, authMethod); - READ_VALUE(o, key); -// READ_VALUE(o, tokenDetails); - ON_VALUE(^(const id value) { o.tokenDetails = value; }); - READ_VALUE(o, authHeaders); - READ_VALUE(o, authParams); - READ_VALUE(o, queryTime); - [self readValue]; // TODO READ_VALUE(o, useAuthToken); // property not found + READ_VALUE(o, authUrl, jsonDict, @"authUrl"); + READ_VALUE(o, authMethod, jsonDict, @"authMethod"); + READ_VALUE(o, key, jsonDict, @"key"); + ON_VALUE(^(const id value) { o.tokenDetails = [AblyFlutterReader readTokenDetails: value]; }, jsonDict, @"tokenDetails"); + READ_VALUE(o, authHeaders, jsonDict, @"authHeaders"); + READ_VALUE(o, authParams, jsonDict, @"authParams"); + READ_VALUE(o, queryTime, jsonDict, @"queryTime"); // ClientOptions - READ_VALUE(o, clientId); - ON_VALUE(^(const id value) { o.logLevel = _logLevel(value); }); + READ_VALUE(o, clientId, jsonDict, @"clientId"); + ON_VALUE(^(const id value) { o.logLevel = _logLevel(value); }, jsonDict, @"logLevel"); //TODO log handler - READ_VALUE(o, tls); - READ_VALUE(o, restHost); - READ_VALUE(o, realtimeHost); - [self readValue]; // TODO READ_VALUE(o, port); // NSInteger - [self readValue]; // TODO READ_VALUE(o, tlsPort); // NSInteger - READ_BOOL(o, autoConnect); - READ_VALUE(o, useBinaryProtocol); - READ_VALUE(o, queueMessages); - READ_VALUE(o, echoMessages); - READ_VALUE(o, recover); - READ_VALUE(o, environment); - READ_VALUE(o, idempotentRestPublishing); - [self readValue]; // TODO READ_VALUE(o, httpOpenTimeout); // NSTimeInterval - [self readValue]; // TODO READ_VALUE(o, httpRequestTimeout); // NSTimeInterval - [self readValue]; // TODO READ_VALUE(o, httpMaxRetryCount); // NSUInteger - [self readValue]; // TODO READ_VALUE(o, realtimeRequestTimeout); // NSTimeInterval - READ_VALUE(o, fallbackHosts); - READ_VALUE(o, fallbackHostsUseDefault); - [self readValue]; // TODO READ_VALUE(o, fallbackRetryTimeout); // property not found - READ_VALUE(o, defaultTokenParams); - [self readValue]; // TODO READ_VALUE(o, channelRetryTimeout); // NSTimeInterval - [self readValue]; // TODO READ_VALUE(o, transportParams); // property not found - // [self readValue]; // TODO READ_VALUE(o, asyncHttpThreadpoolSize); // property not found - // READ_VALUE(o, pushFullWait); + READ_VALUE(o, tls, jsonDict, @"tls"); + READ_VALUE(o, restHost, jsonDict, @"restHost"); + READ_VALUE(o, realtimeHost, jsonDict, @"realtimeHost"); + READ_BOOL(o, autoConnect, jsonDict, @"autoConnect"); + READ_VALUE(o, useBinaryProtocol, jsonDict, @"useBinaryProtocol"); + READ_VALUE(o, queueMessages, jsonDict, @"queueMessages"); + READ_VALUE(o, echoMessages, jsonDict, @"echoMessages"); + READ_VALUE(o, recover, jsonDict, @"recover"); + READ_VALUE(o, environment, jsonDict, @"environment"); + READ_VALUE(o, idempotentRestPublishing, jsonDict, @"idempotentRestPublishing"); + READ_VALUE(o, fallbackHosts, jsonDict, @"fallbackHosts"); + READ_VALUE(o, fallbackHostsUseDefault, jsonDict, @"fallbackHostsUseDefault"); + ON_VALUE(^(const id value) { o.defaultTokenParams = [AblyFlutterReader readTokenParams: value]; }, jsonDict, @"defaultTokenParams"); + READ_VALUE(o, defaultTokenParams, jsonDict, @"defaultTokenParams"); + //Following properties not supported by Objective C library + // READ_VALUE(o, useAuthToken); // property not found + // READ_VALUE(o, port); // NSInteger + // READ_VALUE(o, tlsPort); // NSInteger + // READ_VALUE(o, httpOpenTimeout); // NSTimeInterval + // READ_VALUE(o, httpRequestTimeout); // NSTimeInterval + // READ_VALUE(o, httpMaxRetryCount); // NSUInteger + // READ_VALUE(o, realtimeRequestTimeout); // NSTimeInterval + // READ_VALUE(o, fallbackRetryTimeout); // property not found + // READ_VALUE(o, channelRetryTimeout); // NSTimeInterval + // READ_VALUE(o, transportParams); // property not found + // READ_VALUE(o, asyncHttpThreadpoolSize); // property not found + // READ_VALUE(o, pushFullWait); return o; -} - +}; --(ARTTokenDetails *)readTokenDeatils { ++(ARTTokenDetails *)readTokenDetails: (NSDictionary *) jsonDict { __block NSString *token = nil; __block NSDate *expires = nil; __block NSDate *issued = nil; __block NSString *capability = nil; __block NSString *clientId = nil; - ON_VALUE(^(const id value) { token = value; }) - ON_VALUE(^(const id value) { expires = value; }) - ON_VALUE(^(const id value) { issued = value; }) - ON_VALUE(^(const id value) { capability = value; }) - ON_VALUE(^(const id value) { clientId = value; }) - + ON_VALUE(^(const id value) { token = value; }, jsonDict, @"token"); + ON_VALUE(^(const id value) { expires = value; }, jsonDict, @"expires"); + ON_VALUE(^(const id value) { issued = value; }, jsonDict, @"issued"); + ON_VALUE(^(const id value) { capability = value; }, jsonDict, @"capability"); + ON_VALUE(^(const id value) { clientId = value; }, jsonDict, @"clientId"); + ARTTokenDetails *const o = [ARTTokenDetails new]; [o initWithToken:token expires:expires issued:issued capability:capability clientId:clientId]; return o; } ++(ARTTokenParams *)readTokenParams: (NSDictionary *) jsonDict { + __block NSString *clientId = nil; + __block NSString *nonce = nil; + + ON_VALUE(^(const id value) { clientId = value; }, jsonDict, @"clientId"); + ON_VALUE(^(const id value) { nonce = value; }, jsonDict, @"nonce"); + + ARTTokenParams *const o = [ARTTokenParams new]; + [o initWithClientId: clientId nonce: nonce]; + READ_VALUE(o, ttl, jsonDict, @"ttl"); + READ_VALUE(o, capability, jsonDict, @"capability"); + READ_VALUE(o, timestamp, jsonDict, @"timestamp"); + return o; +} + @end diff --git a/ios/Classes/codec/AblyFlutterWriter.m b/ios/Classes/codec/AblyFlutterWriter.m index 3e6ef8979..7a73428d3 100644 --- a/ios/Classes/codec/AblyFlutterWriter.m +++ b/ios/Classes/codec/AblyFlutterWriter.m @@ -10,53 +10,62 @@ @implementation AblyFlutterWriter - (void)writeValue:(id)value { if([value isKindOfClass:[ARTErrorInfo class]]){ - [self writeErrorInfo: value]; + [self writeByte:errorInfoCodecType]; + [self writeValue: [self encodeErrorInfo: value]]; return; }else if([value isKindOfClass:[ARTConnectionStateChange class]]){ - [self writeConnectionStateChange: value]; + [self writeByte:connectionStateChangeCodecType]; + [self writeValue: [self encodeConnectionStateChange: value]]; return; }else if([value isKindOfClass:[ARTChannelStateChange class]]){ - [self writeConnectionStateChange: value]; + [self writeByte:channelStateChangeCodecType]; + [self writeValue: [self encodeChannelStateChange: value]]; return; } [super writeValue:value]; } -- (void) writeEnum:(UInt8) type enumValue: (int const) enumValue{ - [self writeByte:type]; - [self writeValue: [NSNumber numberWithInt:enumValue]]; +#define WRITE_VALUE(JSON_DICT, JSON_KEY, VALUE) { \ + if (VALUE) { \ + [JSON_DICT setObject:VALUE forKey:JSON_KEY]; \ + } \ } -- (void) writeErrorInfo:(ARTErrorInfo *const) e{ - [self writeByte:errorInfoCodecType]; - [self writeValue: nil]; //code - not available in ably-cocoa - [self writeValue: [e message]]; - [self writeValue: @([e statusCode])]; - [self writeValue: nil]; //href - not available in ably-cocoa - [self writeValue: nil]; //requestId - not available in ably-java - [self writeValue: nil]; //cause - not available in ably-java +#define WRITE_ENUM(JSON_DICT, JSON_KEY, ENUM_VALUE){ \ + if (ENUM_VALUE) { \ + WRITE_VALUE(JSON_DICT, JSON_KEY, [NSNumber numberWithInt:ENUM_VALUE]); \ + } \ } -- (void) writeConnectState:(ARTRealtimeConnectionState const) state{ [self writeEnum:connectionStateCodecType enumValue:state]; } -- (void) writeConnectEvent:(ARTRealtimeConnectionEvent const) event{ [self writeEnum:connectionEventCodecType enumValue:event]; } -- (void) writeConnectionStateChange:(ARTConnectionStateChange *const) stateChange{ - [self writeByte:connectionStateChangeCodecType]; - [self writeConnectState: [stateChange current]]; - [self writeConnectState: [stateChange previous]]; - [self writeConnectEvent: [stateChange event]]; - [self writeValue: @((int)([stateChange retryIn] * 1000))]; - [self writeValue: [stateChange reason]]; +- (NSMutableDictionary *) encodeErrorInfo:(ARTErrorInfo *const) e{ + NSMutableDictionary *jsonDict; + WRITE_VALUE(jsonDict, @"message", [e message]); + WRITE_VALUE(jsonDict, @"statusCode", @([e statusCode])); + //code - not available in ably-cocoa + //href - not available in ably-cocoa + //requestId - not available in ably-cocoa + //cause - not available in ably-cocoa + return jsonDict; } -- (void) writeChannelState:(ARTRealtimeChannelState const) state{ [self writeEnum:channelStateCodecType enumValue:state]; } -- (void) writeChannelEvent:(ARTChannelEvent const) event{ [self writeEnum:channelEventCodecType enumValue:event]; } -- (void) writeChannelStateChange:(ARTChannelStateChange *const) stateChange{ - [self writeByte:channelStateChangeCodecType]; - [self writeChannelState: [stateChange current]]; - [self writeChannelState: [stateChange previous]]; - [self writeChannelEvent: [stateChange event]]; - [self writeValue: @([stateChange resumed])]; - [self writeValue: [stateChange reason]]; +- (NSDictionary *) encodeConnectionStateChange:(ARTConnectionStateChange *const) stateChange{ + NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init]; + WRITE_ENUM(jsonDict, @"current", [stateChange current]); + WRITE_ENUM(jsonDict, @"previous", [stateChange previous]); + WRITE_ENUM(jsonDict, @"event", [stateChange event]); + WRITE_VALUE(jsonDict, @"retryIn", @((int)([stateChange retryIn] * 1000))); + WRITE_VALUE(jsonDict, @"reason", [self encodeErrorInfo: [stateChange reason]]); + return jsonDict; +} + +- (NSDictionary *) encodeChannelStateChange:(ARTChannelStateChange *const) stateChange{ + NSMutableDictionary *jsonDict; + WRITE_ENUM(jsonDict, @"current", [stateChange current]); + WRITE_ENUM(jsonDict, @"previous", [stateChange previous]); + WRITE_ENUM(jsonDict, @"event", [stateChange event]); + WRITE_VALUE(jsonDict, @"resumed", @([stateChange resumed])); + WRITE_VALUE(jsonDict, @"reason", [self encodeErrorInfo: [stateChange reason]]); + return jsonDict; } diff --git a/lib/src/codec.dart b/lib/src/codec.dart index 90e863cd1..7c19b30b4 100644 --- a/lib/src/codec.dart +++ b/lib/src/codec.dart @@ -1,27 +1,29 @@ -import 'package:ably_flutter_plugin/src/impl/message.dart'; import 'package:ably_flutter_plugin/src/gen/platformconstants.dart'; +import 'package:ably_flutter_plugin/src/impl/message.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import '../ably.dart'; -typedef CodecEncoder(final WriteBuffer buffer, final T value); -typedef T CodecDecoder(ReadBuffer buffer); +typedef CodecEncoder(final T value); +typedef T CodecDecoder(Map jsonMap); class CodecPair{ final CodecEncoder encoder; final CodecDecoder decoder; CodecPair(this.encoder, this.decoder); - encode(final WriteBuffer buffer, final dynamic value){ + Map encode(final dynamic value){ if (this.encoder==null) throw AblyException("Codec encoder not defined"); - return this.encoder(buffer, value as T); + if(value==null) return null; + return this.encoder(value as T); } - T decode(ReadBuffer buffer){ + T decode(Map jsonMap){ if (this.decoder==null) throw AblyException("Codec decoder not defined"); - return this.decoder(buffer); + if(jsonMap==null) return null; + return this.decoder(jsonMap); } } @@ -38,22 +40,22 @@ class Codec extends StandardMessageCodec { //Other ably objects CodecTypes.clientOptions: CodecPair(encodeClientOptions, decodeClientOptions), - CodecTypes.tokenDetails: CodecPair(encodeTokenDetails, decodeTokenDetails), CodecTypes.errorInfo: CodecPair(null, decodeErrorInfo), //Events - Connection - CodecTypes.connectionEvent: CodecPair(null, decodeConnectionEvent), - CodecTypes.connectionState: CodecPair(null, decodeConnectionState), CodecTypes.connectionStateChange: CodecPair(null, decodeConnectionStateChange), //Events - Channel - CodecTypes.channelEvent: CodecPair(null, decodeChannelEvent), - CodecTypes.channelState: CodecPair(null, decodeChannelState), CodecTypes.channelStateChange: CodecPair(null, decodeChannelStateChange), }; } - getCodecType(final dynamic value){ + Map toJsonMap(Map value){ + if(value==null) return null; + return Map.castFrom(value); + } + + int getCodecType(final dynamic value){ if (value is ClientOptions) { return CodecTypes.clientOptions; } else if (value is TokenDetails) { @@ -63,6 +65,7 @@ class Codec extends StandardMessageCodec { } else if (value is AblyMessage) { return CodecTypes.ablyMessage; } + return null; } @override @@ -72,163 +75,222 @@ class Codec extends StandardMessageCodec { super.writeValue(buffer, value); } else { buffer.putUint8(type); - codecMap[type].encode(buffer, value); + writeValue(buffer, codecMap[type].encode(value)); } } dynamic readValueOfType(int type, ReadBuffer buffer) { CodecPair pair = codecMap[type]; if (pair==null) { - return super.readValueOfType(type, buffer); + var x = super.readValueOfType(type, buffer); + return x; } else { - return pair.decode(buffer); + Map map = toJsonMap(readValue(buffer)); + return pair.decode(map); } } // =========== ENCODERS =========== - encodeClientOptions(final WriteBuffer buffer, final ClientOptions v){ + writeToJson(Map map, key, value){ + if(value==null) return; + map[key] = value; + } + + Map encodeClientOptions(final ClientOptions v){ + if(v==null) return null; + Map jsonMap = {}; // AuthOptions (super class of ClientOptions) - writeValue(buffer, v.authUrl); - writeValue(buffer, v.authMethod); - writeValue(buffer, v.key); - writeValue(buffer, v.tokenDetails); - writeValue(buffer, v.authHeaders); - writeValue(buffer, v.authParams); - writeValue(buffer, v.queryTime); - writeValue(buffer, v.useTokenAuth); + writeToJson(jsonMap, "authUrl", v.authUrl); + writeToJson(jsonMap, "authMethod", v.authMethod); + writeToJson(jsonMap, "key", v.key); + writeToJson(jsonMap, "tokenDetails", encodeTokenDetails(v.tokenDetails)); + writeToJson(jsonMap, "authHeaders", v.authHeaders); + writeToJson(jsonMap, "authParams", v.authParams); + writeToJson(jsonMap, "queryTime", v.queryTime); + writeToJson(jsonMap, "useTokenAuth", v.useTokenAuth); // ClientOptions - writeValue(buffer, v.clientId); - writeValue(buffer, v.logLevel); + writeToJson(jsonMap, "clientId", v.clientId); + writeToJson(jsonMap, "logLevel", v.logLevel); //TODO handle logHandler - writeValue(buffer, v.tls); - writeValue(buffer, v.restHost); - writeValue(buffer, v.realtimeHost); - writeValue(buffer, v.port); - writeValue(buffer, v.tlsPort); - writeValue(buffer, v.autoConnect); - writeValue(buffer, v.useBinaryProtocol); - writeValue(buffer, v.queueMessages); - writeValue(buffer, v.echoMessages); - writeValue(buffer, v.recover); - writeValue(buffer, v.environment); - writeValue(buffer, v.idempotentRestPublishing); - writeValue(buffer, v.httpOpenTimeout); - writeValue(buffer, v.httpRequestTimeout); - writeValue(buffer, v.httpMaxRetryCount); - writeValue(buffer, v.realtimeRequestTimeout); - writeValue(buffer, v.fallbackHosts); - writeValue(buffer, v.fallbackHostsUseDefault); - writeValue(buffer, v.fallbackRetryTimeout); - writeValue(buffer, v.defaultTokenParams); - writeValue(buffer, v.channelRetryTimeout); - writeValue(buffer, v.transportParams); - } - - encodeTokenDetails(final WriteBuffer buffer, final TokenDetails v){ - writeValue(buffer, v.token); - writeValue(buffer, v.expires); - writeValue(buffer, v.issued); - writeValue(buffer, v.capability); - writeValue(buffer, v.clientId); - } - - encodeAblyMessage(final WriteBuffer buffer, final AblyMessage v){ - writeValue(buffer, v.registrationHandle); - writeValue(buffer, v.message); + writeToJson(jsonMap, "tls", v.tls); + writeToJson(jsonMap, "restHost", v.restHost); + writeToJson(jsonMap, "realtimeHost", v.realtimeHost); + writeToJson(jsonMap, "port", v.port); + writeToJson(jsonMap, "tlsPort", v.tlsPort); + writeToJson(jsonMap, "autoConnect", v.autoConnect); + writeToJson(jsonMap, "useBinaryProtocol", v.useBinaryProtocol); + writeToJson(jsonMap, "queueMessages", v.queueMessages); + writeToJson(jsonMap, "echoMessages", v.echoMessages); + writeToJson(jsonMap, "recover", v.recover); + writeToJson(jsonMap, "environment", v.environment); + writeToJson(jsonMap, "idempotentRestPublishing", v.idempotentRestPublishing); + writeToJson(jsonMap, "httpOpenTimeout", v.httpOpenTimeout); + writeToJson(jsonMap, "httpRequestTimeout", v.httpRequestTimeout); + writeToJson(jsonMap, "httpMaxRetryCount", v.httpMaxRetryCount); + writeToJson(jsonMap, "realtimeRequestTimeout", v.realtimeRequestTimeout); + writeToJson(jsonMap, "fallbackHosts", v.fallbackHosts); + writeToJson(jsonMap, "fallbackHostsUseDefault", v.fallbackHostsUseDefault); + writeToJson(jsonMap, "fallbackRetryTimeout", v.fallbackRetryTimeout); + writeToJson(jsonMap, "defaultTokenParams", encodeTokenParams(v.defaultTokenParams)); + writeToJson(jsonMap, "channelRetryTimeout", v.channelRetryTimeout); + writeToJson(jsonMap, "transportParams", v.transportParams); + return jsonMap; + } + + Map encodeTokenDetails(final TokenDetails v){ + if(v==null) return null; + return { + "token": v.token, + "expires": v.expires, + "issued": v.issued, + "capability": v.capability, + "clientId": v.clientId, + }; + } + + Map encodeTokenParams(final TokenParams v){ + if(v==null) return null; + Map jsonMap = {}; + writeToJson(jsonMap, "capability", v.capability); + writeToJson(jsonMap, "clientId", v.clientId); + writeToJson(jsonMap, "nonce", v.nonce); + writeToJson(jsonMap, "timestamp", v.timestamp); + writeToJson(jsonMap, "ttl", v.ttl); + return jsonMap; + } + + Map encodeAblyMessage(final AblyMessage v){ + if(v==null) return null; + int codecType = getCodecType(v.message); + dynamic message = (v.message==null)?null:(codecType == null)?v.message:codecMap[codecType].encode(v.message); + Map jsonMap = {}; + writeToJson(jsonMap, "registrationHandle", v.registrationHandle); + writeToJson(jsonMap, "type", codecType); + writeToJson(jsonMap, "message", message); + return jsonMap; } // =========== DECODERS =========== - ClientOptions decodeClientOptions(ReadBuffer buffer){ - final ClientOptions v = ClientOptions(); + T readFromJson(Map jsonMap, String key){ + dynamic value = jsonMap[key]; + if(value==null) return null; + return value as T; + } + + ClientOptions decodeClientOptions(Map jsonMap){ + if(jsonMap==null) return null; + final ClientOptions v = ClientOptions(); // AuthOptions (super class of ClientOptions) - v.authUrl = readValue(buffer) as String; - v.authMethod = readValue(buffer) as HTTPMethods; - v.key = readValue(buffer) as String; - v.tokenDetails = readValue(buffer) as TokenDetails; - v.authHeaders = readValue(buffer) as Map; - v.authParams = readValue(buffer) as Map; - v.queryTime = readValue(buffer) as bool; - v.useTokenAuth = readValue(buffer) as bool; + v.authUrl = readFromJson(jsonMap, "authUrl"); + v.authMethod = readFromJson(jsonMap, "authMethod"); + v.key = readFromJson(jsonMap, "key"); + v.tokenDetails = decodeTokenDetails(toJsonMap(jsonMap["tokenDetails"])); + v.authHeaders = readFromJson>(jsonMap, "authHeaders"); + v.authParams = readFromJson>(jsonMap, "authParams"); + v.queryTime = readFromJson(jsonMap, "queryTime"); + v.useTokenAuth = readFromJson(jsonMap, "useTokenAuth"); // ClientOptions - v.clientId = readValue(buffer) as String; - v.logLevel = readValue(buffer) as int; + v.clientId = readFromJson(jsonMap, "clientId"); + v.logLevel = readFromJson(jsonMap, "logLevel"); //TODO handle logHandler - v.tls = readValue(buffer) as bool; - v.restHost = readValue(buffer) as String; - v.realtimeHost = readValue(buffer) as String; - v.port = readValue(buffer) as int; - v.tlsPort = readValue(buffer) as int; - v.autoConnect = readValue(buffer) as bool; - v.useBinaryProtocol = readValue(buffer) as bool; - v.queueMessages = readValue(buffer) as bool; - v.echoMessages = readValue(buffer) as bool; - v.recover = readValue(buffer) as String; - v.environment = readValue(buffer) as String; - v.idempotentRestPublishing = readValue(buffer) as bool; - v.httpOpenTimeout = readValue(buffer) as int; - v.httpRequestTimeout = readValue(buffer) as int; - v.httpMaxRetryCount = readValue(buffer) as int; - v.realtimeRequestTimeout = readValue(buffer) as int; - v.fallbackHosts = readValue(buffer) as List; - v.fallbackHostsUseDefault = readValue(buffer) as bool; - v.fallbackRetryTimeout = readValue(buffer) as int; - v.defaultTokenParams = readValue(buffer) as TokenParams; - v.channelRetryTimeout = readValue(buffer) as int; - v.transportParams = readValue(buffer) as Map; + v.tls = readFromJson(jsonMap, "tls"); + v.restHost = readFromJson(jsonMap, "restHost"); + v.realtimeHost = readFromJson(jsonMap, "realtimeHost"); + v.port = readFromJson(jsonMap, "port"); + v.tlsPort = readFromJson(jsonMap, "tlsPort"); + v.autoConnect = readFromJson(jsonMap, "autoConnect"); + v.useBinaryProtocol = readFromJson(jsonMap, "useBinaryProtocol"); + v.queueMessages = readFromJson(jsonMap, "queueMessages"); + v.echoMessages = readFromJson(jsonMap, "echoMessages"); + v.recover = readFromJson(jsonMap, "recover"); + v.environment = readFromJson(jsonMap, "environment"); + v.idempotentRestPublishing = readFromJson(jsonMap, "idempotentRestPublishing"); + v.httpOpenTimeout = readFromJson(jsonMap, "httpOpenTimeout"); + v.httpRequestTimeout = readFromJson(jsonMap, "httpRequestTimeout"); + v.httpMaxRetryCount = readFromJson(jsonMap, "httpMaxRetryCount"); + v.realtimeRequestTimeout = readFromJson(jsonMap, "realtimeRequestTimeout"); + v.fallbackHosts = readFromJson>(jsonMap, "fallbackHosts"); + v.fallbackHostsUseDefault = readFromJson(jsonMap, "fallbackHostsUseDefault"); + v.fallbackRetryTimeout = readFromJson(jsonMap, "fallbackRetryTimeout"); + v.defaultTokenParams = decodeTokenParams(toJsonMap(jsonMap["defaultTokenParams"])); + v.channelRetryTimeout = readFromJson(jsonMap, "channelRetryTimeout"); + v.transportParams = readFromJson>(jsonMap, "transportParams"); return v; } - TokenDetails decodeTokenDetails(ReadBuffer buffer){ - TokenDetails t = TokenDetails(readValue(buffer)); - t.expires = readValue(buffer) as int; - t.issued = readValue(buffer) as int; - t.capability = readValue(buffer) as String; - t.clientId = readValue(buffer) as String; - return t; + TokenDetails decodeTokenDetails(Map jsonMap){ + if(jsonMap==null) return null; + TokenDetails v = TokenDetails(jsonMap["token"]); + v.expires = readFromJson(jsonMap, "expires"); + v.issued = readFromJson(jsonMap, "issued"); + v.capability = readFromJson(jsonMap, "capability"); + v.clientId = readFromJson(jsonMap, "clientId"); + return v; } - AblyMessage decodeAblyMessage(ReadBuffer buffer){ + TokenParams decodeTokenParams(Map jsonMap){ + if(jsonMap==null) return null; + TokenParams v = TokenParams(); + v.capability = readFromJson(jsonMap, "capability"); + v.clientId = readFromJson(jsonMap, "clientId"); + v.nonce = readFromJson(jsonMap, "nonce"); + v.timestamp = readFromJson(jsonMap, "timestamp"); + v.ttl = readFromJson(jsonMap, "ttl"); + return v; + } + + AblyMessage decodeAblyMessage(Map jsonMap){ + if(jsonMap==null) return null; + int type = readFromJson(jsonMap, "type"); + dynamic message = jsonMap["message"]; + if(type!=null){ + message = codecMap[type].decode(toJsonMap(jsonMap["message"])); + } return AblyMessage( - readValue(buffer) as int, - readValue(buffer), + jsonMap["registrationHandle"] as int, + message, + type: type ); } - ErrorInfo decodeErrorInfo(ReadBuffer buffer){ + ErrorInfo decodeErrorInfo(Map jsonMap){ + if(jsonMap==null) return null; return ErrorInfo( - code: readValue(buffer) as int, - message: readValue(buffer) as String, - statusCode: readValue(buffer) as int, - href: readValue(buffer) as String, - requestId: readValue(buffer) as String, - cause: readValue(buffer) as ErrorInfo + code: jsonMap["code"] as int, + message: jsonMap["message"] as String, + statusCode: jsonMap["statusCode"] as int, + href: jsonMap["href"] as String, + requestId: jsonMap["requestId"] as String, + cause: jsonMap["cause"] as ErrorInfo ); } - ConnectionEvent decodeConnectionEvent(ReadBuffer buffer) => ConnectionEvent.values[readValue(buffer) as int]; - ConnectionState decodeConnectionState(ReadBuffer buffer) => ConnectionState.values[readValue(buffer) as int]; - ChannelEvent decodeChannelEvent(ReadBuffer buffer) => ChannelEvent.values[readValue(buffer) as int]; - ChannelState decodeChannelState(ReadBuffer buffer) => ChannelState.values[readValue(buffer) as int]; - - ConnectionStateChange decodeConnectionStateChange(ReadBuffer buffer){ - ConnectionState current = readValue(buffer) as ConnectionState; - ConnectionState previous = readValue(buffer) as ConnectionState; - ConnectionEvent event = readValue(buffer) as ConnectionEvent; - int retryIn = readValue(buffer) as int; - ErrorInfo reason = readValue(buffer) as ErrorInfo; + ConnectionEvent decodeConnectionEvent(int index) => (index==null)?null:ConnectionEvent.values[index]; + ConnectionState decodeConnectionState(int index) => (index==null)?null:ConnectionState.values[index]; + ChannelEvent decodeChannelEvent(int index) => (index==null)?null:ChannelEvent.values[index]; + ChannelState decodeChannelState(int index) => (index==null)?null:ChannelState.values[index]; + + ConnectionStateChange decodeConnectionStateChange(Map jsonMap){ + if(jsonMap==null) return null; + ConnectionState current = decodeConnectionState(readFromJson(jsonMap, "current")); + ConnectionState previous = decodeConnectionState(readFromJson(jsonMap, "previous")); + ConnectionEvent event = decodeConnectionEvent(readFromJson(jsonMap, "event")); + int retryIn = readFromJson(jsonMap, "retryIn"); + ErrorInfo reason = decodeErrorInfo(toJsonMap(jsonMap["reason"])); return ConnectionStateChange(current, previous, event, retryIn: retryIn, reason: reason); } - ChannelStateChange decodeChannelStateChange(ReadBuffer buffer){ - ChannelState current = readValue(buffer) as ChannelState; - ChannelState previous = readValue(buffer) as ChannelState; - ChannelEvent event = readValue(buffer) as ChannelEvent; - bool resumed = readValue(buffer) as bool; - ErrorInfo reason = readValue(buffer) as ErrorInfo; + ChannelStateChange decodeChannelStateChange(Map jsonMap){ + if(jsonMap==null) return null; + ChannelState current = decodeChannelState(readFromJson(jsonMap, "current")); + ChannelState previous = decodeChannelState(readFromJson(jsonMap, "previous")); + ChannelEvent event = decodeChannelEvent(readFromJson(jsonMap, "event")); + bool resumed = readFromJson(jsonMap, "resumed"); + ErrorInfo reason = decodeErrorInfo(jsonMap["reason"]); return ChannelStateChange(current, previous, event, resumed: resumed, reason: reason); } diff --git a/lib/src/impl/message.dart b/lib/src/impl/message.dart index 574884d6e..ed1b40168 100644 --- a/lib/src/impl/message.dart +++ b/lib/src/impl/message.dart @@ -1,6 +1,7 @@ class AblyMessage { final int registrationHandle; + final int type; final dynamic message; - AblyMessage(this.registrationHandle, this.message); + AblyMessage(this.registrationHandle, this.message, {this.type}); } diff --git a/lib/src/spec/common.dart b/lib/src/spec/common.dart index 24c9ecef8..79ef4ebc9 100644 --- a/lib/src/spec/common.dart +++ b/lib/src/spec/common.dart @@ -75,7 +75,7 @@ abstract class StatsMessageTraffic { StatsMessageTypes webhook; } -abstract class TokenParams { +class TokenParams { String capability; String clientId; String nonce; From 53187a60c55e19b5397708fbe0db75b1e505becf Mon Sep 17 00:00:00 2001 From: "Rohit R. Abbadi" Date: Sat, 23 May 2020 13:39:47 +0530 Subject: [PATCH 06/19] cleanup unwanted codecTypes --- .../ably/flutter/plugin/AblyMessageCodec.java | 21 +------------------ .../flutter/plugin/gen/PlatformConstants.java | 9 ++------ bin/codegencontext.dart | 9 ++------ ios/Classes/codec/AblyPlatformConstants.h | 9 ++------ lib/src/codec.dart | 2 -- lib/src/gen/platformconstants.dart | 9 ++------ 6 files changed, 9 insertions(+), 50 deletions(-) diff --git a/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java b/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java index 49c844f88..3f804ee6b 100644 --- a/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java +++ b/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java @@ -6,11 +6,8 @@ import java.util.Map; import java.util.function.Consumer; -import io.ably.lib.realtime.ChannelEvent; -import io.ably.lib.realtime.ChannelState; +import io.ably.flutter.plugin.gen.PlatformConstants; import io.ably.lib.realtime.ChannelStateListener; -import io.ably.lib.realtime.ConnectionEvent; -import io.ably.lib.realtime.ConnectionState; import io.ably.lib.realtime.ConnectionStateListener; import io.ably.lib.rest.Auth; import io.ably.lib.rest.Auth.TokenDetails; @@ -18,7 +15,6 @@ import io.ably.lib.types.ErrorInfo; import io.ably.lib.types.Param; import io.flutter.plugin.common.StandardMessageCodec; -import io.ably.flutter.plugin.gen.PlatformConstants; public class AblyMessageCodec extends StandardMessageCodec { @@ -59,15 +55,8 @@ T decode(Map jsonMap){ { put(PlatformConstants.CodecTypes.ablyMessage, new CodecPair<>(null, self::readAblyFlutterMessage)); put(PlatformConstants.CodecTypes.clientOptions, new CodecPair<>(null, self::readClientOptions)); -// put(PlatformConstants.CodecTypes.tokenDetails, new CodecPair<>(null, self::readTokenDetails)); put(PlatformConstants.CodecTypes.errorInfo, new CodecPair<>(self::encodeErrorInfo, null)); - -// put(PlatformConstants.CodecTypes.connectionEvent, new CodecPair<>(self::writeConnectionEvent, null)); -// put(PlatformConstants.CodecTypes.connectionState, new CodecPair<>(self::writeConnectionState, null)); put(PlatformConstants.CodecTypes.connectionStateChange, new CodecPair<>(self::encodeConnectionStateChange, null)); - -// put(PlatformConstants.CodecTypes.channelEvent, new CodecPair<>(self::writeChannelEvent, null)); -// put(PlatformConstants.CodecTypes.channelState, new CodecPair<>(self::writeChannelState, null)); put(PlatformConstants.CodecTypes.channelStateChange, new CodecPair<>(self::writeChannelStateChange, null)); } }; @@ -107,16 +96,8 @@ protected void writeValue(ByteArrayOutputStream stream, Object value) { Byte type = null; if(value instanceof ErrorInfo){ type = PlatformConstants.CodecTypes.errorInfo; - }else if(value instanceof ConnectionEvent){ - type = PlatformConstants.CodecTypes.connectionEvent; - }else if(value instanceof ConnectionState){ - type = PlatformConstants.CodecTypes.connectionState; }else if(value instanceof ConnectionStateListener.ConnectionStateChange){ type = PlatformConstants.CodecTypes.connectionStateChange; - }else if(value instanceof ChannelEvent){ - type = PlatformConstants.CodecTypes.channelEvent; - }else if(value instanceof ChannelState){ - type = PlatformConstants.CodecTypes.channelState; }else if(value instanceof ChannelStateListener.ChannelStateChange){ type = PlatformConstants.CodecTypes.channelStateChange; } diff --git a/android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java b/android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java index ca5efd9e8..06d3a411a 100644 --- a/android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java +++ b/android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java @@ -11,14 +11,9 @@ public class PlatformConstants{ public class CodecTypes { public static final byte ablyMessage = (byte)128; public static final byte clientOptions = (byte)129; - public static final byte tokenDetails = (byte)130; public static final byte errorInfo = (byte)144; - public static final byte connectionEvent = (byte)201; - public static final byte connectionState = (byte)202; - public static final byte connectionStateChange = (byte)203; - public static final byte channelEvent = (byte)204; - public static final byte channelState = (byte)205; - public static final byte channelStateChange = (byte)206; + public static final byte connectionStateChange = (byte)201; + public static final byte channelStateChange = (byte)202; } diff --git a/bin/codegencontext.dart b/bin/codegencontext.dart index 4cae156e5..c8ea44c5c 100644 --- a/bin/codegencontext.dart +++ b/bin/codegencontext.dart @@ -14,16 +14,11 @@ List> _types = [ //Other ably objects {"name": "clientOptions", "value": 129}, - {"name": "tokenDetails", "value": 130}, {"name": "errorInfo", "value": 144}, // Events - {"name": "connectionEvent", "value": 201}, - {"name": "connectionState", "value": 202}, - {"name": "connectionStateChange", "value": 203}, - {"name": "channelEvent", "value": 204}, - {"name": "channelState", "value": 205}, - {"name": "channelStateChange", "value": 206} + {"name": "connectionStateChange", "value": 201}, + {"name": "channelStateChange", "value": 202} ]; ///Platform method names diff --git a/ios/Classes/codec/AblyPlatformConstants.h b/ios/Classes/codec/AblyPlatformConstants.h index 400a208df..41937d568 100644 --- a/ios/Classes/codec/AblyPlatformConstants.h +++ b/ios/Classes/codec/AblyPlatformConstants.h @@ -9,14 +9,9 @@ typedef NS_ENUM(UInt8, _Value) { ablyMessageCodecType = 128, clientOptionsCodecType = 129, - tokenDetailsCodecType = 130, errorInfoCodecType = 144, - connectionEventCodecType = 201, - connectionStateCodecType = 202, - connectionStateChangeCodecType = 203, - channelEventCodecType = 204, - channelStateCodecType = 205, - channelStateChangeCodecType = 206, + connectionStateChangeCodecType = 201, + channelStateChangeCodecType = 202, }; diff --git a/lib/src/codec.dart b/lib/src/codec.dart index 7c19b30b4..2fae850a5 100644 --- a/lib/src/codec.dart +++ b/lib/src/codec.dart @@ -58,8 +58,6 @@ class Codec extends StandardMessageCodec { int getCodecType(final dynamic value){ if (value is ClientOptions) { return CodecTypes.clientOptions; - } else if (value is TokenDetails) { - return CodecTypes.tokenDetails; } else if (value is ErrorInfo) { return CodecTypes.errorInfo; } else if (value is AblyMessage) { diff --git a/lib/src/gen/platformconstants.dart b/lib/src/gen/platformconstants.dart index db7073e80..eabbc0a62 100644 --- a/lib/src/gen/platformconstants.dart +++ b/lib/src/gen/platformconstants.dart @@ -7,14 +7,9 @@ class CodecTypes{ static const int ablyMessage = 128; static const int clientOptions = 129; - static const int tokenDetails = 130; static const int errorInfo = 144; - static const int connectionEvent = 201; - static const int connectionState = 202; - static const int connectionStateChange = 203; - static const int channelEvent = 204; - static const int channelState = 205; - static const int channelStateChange = 206; + static const int connectionStateChange = 201; + static const int channelStateChange = 202; } From 303d380e2319a67e037626cb647383b6bb93e600 Mon Sep 17 00:00:00 2001 From: "Rohit R. Abbadi" Date: Sat, 23 May 2020 16:47:12 +0530 Subject: [PATCH 07/19] generating channel transferable json keys to stay in sync 1. Generation format changed from mustache templates to straight forward dart string interpolation 2. generating JSON keys for encodable/decodable objects. Properties of each object are generated to `TxObjectName` 3. generated JSON keys used in encoding/decoding methods --- .../ably/flutter/plugin/AblyMessageCodec.java | 114 +++++----- .../flutter/plugin/gen/PlatformConstants.java | 108 +++++++-- bin/README.md | 47 +--- bin/codegen.dart | 56 ++--- bin/codegencontext.dart | 104 ++++++++- bin/templates/PlatformConstants.java.hbs | 17 -- bin/templates/platformconstants.dart.dart | 18 ++ bin/templates/platformconstants.dart.hbs | 11 - bin/templates/platformconstants.h.dart | 21 ++ bin/templates/platformconstants.h.hbs | 14 -- bin/templates/platformconstants.java.dart | 24 ++ bin/templates/platformconstants.m.dart | 18 ++ bin/templates/platformconstants.m.hbs | 9 - ios/Classes/codec/AblyFlutterReader.m | 74 +++--- ios/Classes/codec/AblyFlutterWriter.m | 24 +- ios/Classes/codec/AblyPlatformConstants.h | 86 ++++++- ios/Classes/codec/AblyPlatformConstants.m | 84 ++++++- lib/src/codec.dart | 214 +++++++++--------- lib/src/gen/platformconstants.dart | 115 ++++++++-- 19 files changed, 769 insertions(+), 389 deletions(-) delete mode 100644 bin/templates/PlatformConstants.java.hbs create mode 100644 bin/templates/platformconstants.dart.dart delete mode 100644 bin/templates/platformconstants.dart.hbs create mode 100644 bin/templates/platformconstants.h.dart delete mode 100644 bin/templates/platformconstants.h.hbs create mode 100644 bin/templates/platformconstants.java.dart create mode 100644 bin/templates/platformconstants.m.dart delete mode 100644 bin/templates/platformconstants.m.hbs diff --git a/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java b/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java index 3f804ee6b..7d1ca955e 100644 --- a/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java +++ b/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java @@ -130,10 +130,10 @@ private Long readValueAsLong(final Object object) { private AblyFlutterMessage readAblyFlutterMessage(Map jsonMap) { if(jsonMap==null) return null; - final Long handle = readValueAsLong(jsonMap.get("registrationHandle")); - Object messageType = jsonMap.get("type"); + final Long handle = readValueAsLong(jsonMap.get(PlatformConstants.TxAblyMessage.registrationHandle)); + Object messageType = jsonMap.get(PlatformConstants.TxAblyMessage.type); final Integer type = (messageType==null)?null:Integer.parseInt(messageType.toString()); - Object message = jsonMap.get("message"); + Object message = jsonMap.get(PlatformConstants.TxAblyMessage.message); if(type!=null){ message = codecMap.get((byte)(int)type).decode((Map)message); } @@ -145,51 +145,51 @@ private ClientOptions readClientOptions(Map jsonMap) { final ClientOptions o = new ClientOptions(); // AuthOptions (super class of ClientOptions) - readValueFromJson(jsonMap, "authUrl", v -> o.authUrl = (String)v); - readValueFromJson(jsonMap, "authMethod", v -> o.authMethod = (String)v); - readValueFromJson(jsonMap, "key", v -> o.key = (String)v); - readValueFromJson(jsonMap, "tokenDetails", v -> o.tokenDetails = readTokenDetails((Map)v)); - readValueFromJson(jsonMap, "authHeaders", v -> o.authHeaders = (Param[])v); - readValueFromJson(jsonMap, "authParams", v -> o.authParams = (Param[])v); - readValueFromJson(jsonMap, "queryTime", v -> o.queryTime = (Boolean)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.authUrl, v -> o.authUrl = (String)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.authMethod, v -> o.authMethod = (String)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.key, v -> o.key = (String)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.tokenDetails, v -> o.tokenDetails = readTokenDetails((Map)v)); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.authHeaders, v -> o.authHeaders = (Param[])v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.authParams, v -> o.authParams = (Param[])v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.queryTime, v -> o.queryTime = (Boolean)v); // readValueFromJson(buffer); // o.useAuthToken // ClientOptions - readValueFromJson(jsonMap, "clientId", v -> o.clientId = (String)v); - readValueFromJson(jsonMap, "logLevel", v -> o.logLevel = (Integer)v); - readValueFromJson(jsonMap, "tls", v -> o.tls = (Boolean)v); - readValueFromJson(jsonMap, "restHost", v -> o.restHost = (String)v); - readValueFromJson(jsonMap, "realtimeHost", v -> o.realtimeHost = (String)v); - readValueFromJson(jsonMap, "port", v -> o.port = (Integer)v); - readValueFromJson(jsonMap, "tlsPort", v -> o.tlsPort = (Integer)v); - readValueFromJson(jsonMap, "autoConnect", v -> o.autoConnect = (Boolean)v); - readValueFromJson(jsonMap, "useBinaryProtocol", v -> o.useBinaryProtocol = (Boolean)v); - readValueFromJson(jsonMap, "queueMessages", v -> o.queueMessages = (Boolean)v); - readValueFromJson(jsonMap, "echoMessages", v -> o.echoMessages = (Boolean)v); - readValueFromJson(jsonMap, "recover", v -> o.recover = (String)v); - readValueFromJson(jsonMap, "environment", v -> o.environment = (String)v); - readValueFromJson(jsonMap, "idempotentRestPublishing", v -> o.idempotentRestPublishing = (Boolean)v); - readValueFromJson(jsonMap, "httpOpenTimeout", v -> o.httpOpenTimeout = (Integer)v); - readValueFromJson(jsonMap, "httpRequestTimeout", v -> o.httpRequestTimeout = (Integer)v); - readValueFromJson(jsonMap, "httpMaxRetryCount", v -> o.httpMaxRetryCount = (Integer)v); - readValueFromJson(jsonMap, "realtimeRequestTimeout", v -> o.realtimeRequestTimeout = (Long)v); - readValueFromJson(jsonMap, "fallbackHosts", v -> o.fallbackHosts = (String[])v); - readValueFromJson(jsonMap, "fallbackHostsUseDefault", v -> o.fallbackHostsUseDefault = (Boolean)v); - readValueFromJson(jsonMap, "fallbackRetryTimeout", v -> o.fallbackRetryTimeout = (Long)v); - readValueFromJson(jsonMap, "defaultTokenParams", v -> o.defaultTokenParams = readTokenParams((Map)v)); - readValueFromJson(jsonMap, "channelRetryTimeout", v -> o.channelRetryTimeout = (Integer)v); - readValueFromJson(jsonMap, "transportParams", v -> o.transportParams = (Param[])v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.clientId, v -> o.clientId = (String)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.logLevel, v -> o.logLevel = (Integer)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.tls, v -> o.tls = (Boolean)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.restHost, v -> o.restHost = (String)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.realtimeHost, v -> o.realtimeHost = (String)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.port, v -> o.port = (Integer)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.tlsPort, v -> o.tlsPort = (Integer)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.autoConnect, v -> o.autoConnect = (Boolean)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.useBinaryProtocol, v -> o.useBinaryProtocol = (Boolean)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.queueMessages, v -> o.queueMessages = (Boolean)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.echoMessages, v -> o.echoMessages = (Boolean)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.recover, v -> o.recover = (String)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.environment, v -> o.environment = (String)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.idempotentRestPublishing, v -> o.idempotentRestPublishing = (Boolean)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.httpOpenTimeout, v -> o.httpOpenTimeout = (Integer)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.httpRequestTimeout, v -> o.httpRequestTimeout = (Integer)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.httpMaxRetryCount, v -> o.httpMaxRetryCount = (Integer)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.realtimeRequestTimeout, v -> o.realtimeRequestTimeout = (Long)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.fallbackHosts, v -> o.fallbackHosts = (String[])v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.fallbackHostsUseDefault, v -> o.fallbackHostsUseDefault = (Boolean)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.fallbackRetryTimeout, v -> o.fallbackRetryTimeout = (Long)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.defaultTokenParams, v -> o.defaultTokenParams = readTokenParams((Map)v)); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.channelRetryTimeout, v -> o.channelRetryTimeout = (Integer)v); + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.transportParams, v -> o.transportParams = (Param[])v); return o; } private TokenDetails readTokenDetails(Map jsonMap) { if(jsonMap==null) return null; final TokenDetails o = new TokenDetails(); - readValueFromJson(jsonMap, "token", v -> o.token = (String)v); - readValueFromJson(jsonMap, "expires", v -> o.expires = (int)v); - readValueFromJson(jsonMap, "issued", v -> o.issued = (int)v); - readValueFromJson(jsonMap, "capability", v -> o.capability = (String)v); - readValueFromJson(jsonMap, "clientId", v -> o.clientId = (String)v); + readValueFromJson(jsonMap, PlatformConstants.TxTokenDetails.token, v -> o.token = (String)v); + readValueFromJson(jsonMap, PlatformConstants.TxTokenDetails.expires, v -> o.expires = (int)v); + readValueFromJson(jsonMap, PlatformConstants.TxTokenDetails.issued, v -> o.issued = (int)v); + readValueFromJson(jsonMap, PlatformConstants.TxTokenDetails.capability, v -> o.capability = (String)v); + readValueFromJson(jsonMap, PlatformConstants.TxTokenDetails.clientId, v -> o.clientId = (String)v); return o; } @@ -197,10 +197,10 @@ private TokenDetails readTokenDetails(Map jsonMap) { private Auth.TokenParams readTokenParams(Map jsonMap) { if(jsonMap==null) return null; final Auth.TokenParams o = new Auth.TokenParams(); - readValueFromJson(jsonMap, "capability", v -> o.capability = (String)v); - readValueFromJson(jsonMap, "clientId", v -> o.clientId = (String)v); - readValueFromJson(jsonMap, "timestamp", v -> o.timestamp = (int)v); - readValueFromJson(jsonMap, "ttl", v -> o.ttl = (long)v); + readValueFromJson(jsonMap, PlatformConstants.TxTokenParams.capability, v -> o.capability = (String)v); + readValueFromJson(jsonMap, PlatformConstants.TxTokenParams.clientId, v -> o.clientId = (String)v); + readValueFromJson(jsonMap, PlatformConstants.TxTokenParams.timestamp, v -> o.timestamp = (int)v); + readValueFromJson(jsonMap, PlatformConstants.TxTokenParams.ttl, v -> o.ttl = (long)v); //nonce is not supported in ably-java return o; } @@ -212,10 +212,10 @@ private Auth.TokenParams readTokenParams(Map jsonMap) { private Map encodeErrorInfo(ErrorInfo c){ if(c==null) return null; HashMap jsonMap = new HashMap<>(); - writeValueToJson(jsonMap, "code", c.code); - writeValueToJson(jsonMap, "message", c.message); - writeValueToJson(jsonMap, "statusCode", c.statusCode); - writeValueToJson(jsonMap, "href", c.href); + writeValueToJson(jsonMap, PlatformConstants.TxErrorInfo.code, c.code); + writeValueToJson(jsonMap, PlatformConstants.TxErrorInfo.message, c.message); + writeValueToJson(jsonMap, PlatformConstants.TxErrorInfo.statusCode, c.statusCode); + writeValueToJson(jsonMap, PlatformConstants.TxErrorInfo.href, c.href); //requestId and cause - not available in ably-java return jsonMap; } @@ -223,22 +223,22 @@ private Map encodeErrorInfo(ErrorInfo c){ private Map encodeConnectionStateChange(ConnectionStateListener.ConnectionStateChange c){ if(c==null) return null; HashMap jsonMap = new HashMap<>(); - writeEnumToJson(jsonMap, "current", c.current); - writeEnumToJson(jsonMap, "previous", c.previous); - writeEnumToJson(jsonMap, "event", c.event); - writeValueToJson(jsonMap, "retryIn", c.retryIn); - writeValueToJson(jsonMap, "reason", encodeErrorInfo(c.reason)); + writeEnumToJson(jsonMap, PlatformConstants.TxConnectionStateChange.current, c.current); + writeEnumToJson(jsonMap, PlatformConstants.TxConnectionStateChange.previous, c.previous); + writeEnumToJson(jsonMap, PlatformConstants.TxConnectionStateChange.event, c.event); + writeValueToJson(jsonMap, PlatformConstants.TxConnectionStateChange.retryIn, c.retryIn); + writeValueToJson(jsonMap, PlatformConstants.TxConnectionStateChange.reason, encodeErrorInfo(c.reason)); return jsonMap; } private Map writeChannelStateChange(ChannelStateListener.ChannelStateChange c){ if(c==null) return null; HashMap jsonMap = new HashMap<>(); - writeEnumToJson(jsonMap, "current", c.current); - writeEnumToJson(jsonMap, "previous", c.previous); - writeEnumToJson(jsonMap, "event", c.event); - writeValueToJson(jsonMap, "resumed", c.resumed); - writeValueToJson(jsonMap, "reason", encodeErrorInfo(c.reason)); + writeEnumToJson(jsonMap, PlatformConstants.TxChannelStateChange.current, c.current); + writeEnumToJson(jsonMap, PlatformConstants.TxChannelStateChange.previous, c.previous); + writeEnumToJson(jsonMap, PlatformConstants.TxChannelStateChange.event, c.event); + writeValueToJson(jsonMap, PlatformConstants.TxChannelStateChange.resumed, c.resumed); + writeValueToJson(jsonMap, PlatformConstants.TxChannelStateChange.reason, encodeErrorInfo(c.reason)); return jsonMap; } diff --git a/android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java b/android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java index 06d3a411a..de8a5b3f9 100644 --- a/android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java +++ b/android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java @@ -1,6 +1,6 @@ // // Generated code. Do not modify. -// source: bin/templates/platformconstants.java.hbs +// source file can be found at bin/templates' // package io.ably.flutter.plugin.gen; @@ -10,26 +10,98 @@ public class PlatformConstants{ public class CodecTypes { public static final byte ablyMessage = (byte)128; - public static final byte clientOptions = (byte)129; - public static final byte errorInfo = (byte)144; - public static final byte connectionStateChange = (byte)201; - public static final byte channelStateChange = (byte)202; - + public static final byte clientOptions = (byte)129; + public static final byte errorInfo = (byte)144; + public static final byte connectionStateChange = (byte)201; + public static final byte channelStateChange = (byte)202; } public class PlatformMethod { - public static final String getPlatformVersion = "getPlatformVersion"; - public static final String getVersion = "getVersion"; - public static final String registerAbly = "registerAbly"; - public static final String createRestWithOptions = "createRestWithOptions"; - public static final String publish = "publish"; - public static final String createRealtimeWithOptions = "createRealtimeWithOptions"; - public static final String connectRealtime = "connectRealtime"; - public static final String closeRealtime = "closeRealtime"; - public static final String onRealtimeConnectionStateChanged = "onRealtimeConnectionStateChanged"; - public static final String onRealtimeChannelStateChanged = "onRealtimeChannelStateChanged"; - + public static final String getVersion = "getVersion"; + public static final String registerAbly = "registerAbly"; + public static final String createRestWithOptions = "createRestWithOptions"; + public static final String publish = "publish"; + public static final String createRealtimeWithOptions = "createRealtimeWithOptions"; + public static final String connectRealtime = "connectRealtime"; + public static final String closeRealtime = "closeRealtime"; + public static final String onRealtimeConnectionStateChanged = "onRealtimeConnectionStateChanged"; + public static final String onRealtimeChannelStateChanged = "onRealtimeChannelStateChanged"; + } + + public class TxAblyMessage{ + public static final String registrationHandle = "registrationHandle"; + public static final String type = "type"; + public static final String message = "message"; + } + public class TxErrorInfo{ + public static final String code = "code"; + public static final String message = "message"; + public static final String statusCode = "statusCode"; + public static final String href = "href"; + public static final String requestId = "requestId"; + public static final String cause = "cause"; + } + public class TxClientOptions{ + public static final String authUrl = "authUrl"; + public static final String authMethod = "authMethod"; + public static final String key = "key"; + public static final String tokenDetails = "tokenDetails"; + public static final String authHeaders = "authHeaders"; + public static final String authParams = "authParams"; + public static final String queryTime = "queryTime"; + public static final String useTokenAuth = "useTokenAuth"; + public static final String clientId = "clientId"; + public static final String logLevel = "logLevel"; + public static final String tls = "tls"; + public static final String restHost = "restHost"; + public static final String realtimeHost = "realtimeHost"; + public static final String port = "port"; + public static final String tlsPort = "tlsPort"; + public static final String autoConnect = "autoConnect"; + public static final String useBinaryProtocol = "useBinaryProtocol"; + public static final String queueMessages = "queueMessages"; + public static final String echoMessages = "echoMessages"; + public static final String recover = "recover"; + public static final String environment = "environment"; + public static final String idempotentRestPublishing = "idempotentRestPublishing"; + public static final String httpOpenTimeout = "httpOpenTimeout"; + public static final String httpRequestTimeout = "httpRequestTimeout"; + public static final String httpMaxRetryCount = "httpMaxRetryCount"; + public static final String realtimeRequestTimeout = "realtimeRequestTimeout"; + public static final String fallbackHosts = "fallbackHosts"; + public static final String fallbackHostsUseDefault = "fallbackHostsUseDefault"; + public static final String fallbackRetryTimeout = "fallbackRetryTimeout"; + public static final String defaultTokenParams = "defaultTokenParams"; + public static final String channelRetryTimeout = "channelRetryTimeout"; + public static final String transportParams = "transportParams"; + } + public class TxTokenDetails{ + public static final String token = "token"; + public static final String expires = "expires"; + public static final String issued = "issued"; + public static final String capability = "capability"; + public static final String clientId = "clientId"; + } + public class TxTokenParams{ + public static final String capability = "capability"; + public static final String clientId = "clientId"; + public static final String nonce = "nonce"; + public static final String timestamp = "timestamp"; + public static final String ttl = "ttl"; + } + public class TxConnectionStateChange{ + public static final String current = "current"; + public static final String previous = "previous"; + public static final String event = "event"; + public static final String retryIn = "retryIn"; + public static final String reason = "reason"; + } + public class TxChannelStateChange{ + public static final String current = "current"; + public static final String previous = "previous"; + public static final String event = "event"; + public static final String resumed = "resumed"; + public static final String reason = "reason"; } - } diff --git a/bin/README.md b/bin/README.md index 0daed5e32..7d6ff396a 100644 --- a/bin/README.md +++ b/bin/README.md @@ -9,52 +9,7 @@ dart codegen.dart #### Template format -This generation is based on a 2 simple Regular expressions which work as below: - -input template contents -```text -Hola {{variable}}! -``` - -input context -```dart -Map context = { - "variable": "World" -}; -``` - -output file content -```text -Hola World -``` - -input template contents -```text -{{#each list}} - String {{name}} = "{{value}}"; -{{/each}} -``` - -input context -```dart -Map context = { - "list": [ - {"var1": "title", "var2": "Lorem Ipsum"}, - {"var1": "description", "var2": "Lorem ipsum dolor sit amet, consectetur adipiscing elit"}, - ] -}; -``` - -output file content -```text - - String title = "Lorem Ipsum"; - - String description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit"; - -``` -_mind the linebreaks_ - +A straight forward templates creating using dart string interpolation: #### Template and Context files diff --git a/bin/codegen.dart b/bin/codegen.dart index f34f45f30..c66c305a3 100644 --- a/bin/codegen.dart +++ b/bin/codegen.dart @@ -1,48 +1,34 @@ import 'dart:io'; import 'codegencontext.dart' show context; +import 'templates/platformconstants.dart.dart' as dart_template; +import 'templates/platformconstants.java.dart' as java_template; +import 'templates/platformconstants.h.dart' as objc_header_template; +import 'templates/platformconstants.m.dart' as objc_impl_template; + + +typedef String Template(Map context); String projectRoot = "../"; -String templatesRoot = "./templates/"; -Map toGenerate = { - //input template path vs output file path - "${templatesRoot}platformconstants.dart.hbs": "${projectRoot}lib/src/gen/platformconstants.dart", - "${templatesRoot}platformconstants.java.hbs": "${projectRoot}android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java", - "${templatesRoot}platformconstants.h.hbs": "${projectRoot}ios/Classes/codec/AblyPlatformConstants.h", - "${templatesRoot}platformconstants.m.hbs": "${projectRoot}ios/Classes/codec/AblyPlatformConstants.m", +Map toGenerate = { + //input template method vs output file path + dart_template.$: "${projectRoot}lib/src/gen/platformconstants.dart", + java_template.$: "${projectRoot}android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java", + objc_header_template.$: "${projectRoot}ios/Classes/codec/AblyPlatformConstants.h", + objc_impl_template.$: "${projectRoot}ios/Classes/codec/AblyPlatformConstants.m", }; void main() async { - for(MapEntry entry in toGenerate.entries){ - String source = getContent(File(entry.key).readAsStringSync(), context); + for(MapEntry entry in toGenerate.entries){ + String source = entry.key(context); File(entry.value).writeAsStringSync( - "//\n// Generated code. Do not modify.\n// source: ${entry.key.replaceAll('./', 'bin/')} \n//\n\n${source}" + '''// +// Generated code. Do not modify. +// source file can be found at bin/templates' +// + +${source}''' ); print("File written: ${entry.value} ✔"); } } - -//{{hello}}, {{ hi_there }} -final variableRegExp = RegExp("{{\\s*([a-zA-Z\$_][a-zA-Z0-9\$_]*)\\s*}}"); - -//{{#each xyz}}{{name}}{{/each}} -final iteratorRegexp = RegExp("{{#each\\s+([a-zA-Z\$_][a-zA-Z0-9\$_]*)\\s*}}([.\\s\\S]*?){{\\\s*\\/each\\s*}}"); - -String getContent(String templateStr, Map context){ - //matching loops - Iterable matches = iteratorRegexp.allMatches(templateStr); - if(matches!=null){ - for(RegExpMatch match in matches){ - String fullMatch = match.group(0); - String iteratorContext = match.group(1); - String iterable = match.group(2); - List> iteratingContext = context[iteratorContext]; - templateStr = templateStr.replaceFirst(fullMatch, iteratingContext.map((Map _context)=>getContent(iterable, _context)).join("")); - } - } - - //replacing variables - return templateStr.replaceAllMapped(variableRegExp, (match){ - return context[match.group(1)].toString(); - }); -} diff --git a/bin/codegencontext.dart b/bin/codegencontext.dart index c8ea44c5c..c8c090057 100644 --- a/bin/codegencontext.dart +++ b/bin/codegencontext.dart @@ -41,10 +41,112 @@ List> _platformMethods = [ {"name": "onRealtimeChannelStateChanged", "value": "onRealtimeChannelStateChanged"} ]; +List> objects = [ + { + "name": "AblyMessage", + "properties": [ + "registrationHandle", + "type", + "message" + ] + }, + { + "name": "ErrorInfo", + "properties": [ + "code", + "message", + "statusCode", + "href", + "requestId", + "cause" + ] + }, + { + "name": "ClientOptions", + "properties": [ + //Auth options + "authUrl", + "authMethod", + "key", + "tokenDetails", + "authHeaders", + "authParams", + "queryTime", + "useTokenAuth", + // ClientOptions + "clientId", + "logLevel", + "tls", + "restHost", + "realtimeHost", + "port", + "tlsPort", + "autoConnect", + "useBinaryProtocol", + "queueMessages", + "echoMessages", + "recover", + "environment", + "idempotentRestPublishing", + "httpOpenTimeout", + "httpRequestTimeout", + "httpMaxRetryCount", + "realtimeRequestTimeout", + "fallbackHosts", + "fallbackHostsUseDefault", + "fallbackRetryTimeout", + "defaultTokenParams", + "channelRetryTimeout", + "transportParams", + ] + }, + { + "name": "TokenDetails", + "properties": [ + "token", + "expires", + "issued", + "capability", + "clientId" + ] + }, + { + "name": "TokenParams", + "properties": [ + "capability", + "clientId", + "nonce", + "timestamp", + "ttl" + ] + }, + { + "name": "ConnectionStateChange", + "properties": [ + "current", + "previous", + "event", + "retryIn", + "reason" + ] + }, + { + "name": "ChannelStateChange", + "properties": [ + "current", + "previous", + "event", + "resumed", + "reason" + ] + } +]; + //exporting all the constants as a single map // which can be directly fed to template as context Map context = { "types": _types, - "methods": _platformMethods + "methods": _platformMethods, + "objects": objects }; diff --git a/bin/templates/PlatformConstants.java.hbs b/bin/templates/PlatformConstants.java.hbs deleted file mode 100644 index a18b5e72b..000000000 --- a/bin/templates/PlatformConstants.java.hbs +++ /dev/null @@ -1,17 +0,0 @@ -package io.ably.flutter.plugin.gen; - - -public class PlatformConstants{ - - public class CodecTypes { - {{#each types}}public static final byte {{name}} = (byte){{value}}; - {{/each}} - } - - public class PlatformMethod { - - {{#each methods}}public static final String {{name}} = "{{value}}"; - {{/each}} - } - -} diff --git a/bin/templates/platformconstants.dart.dart b/bin/templates/platformconstants.dart.dart new file mode 100644 index 000000000..f6118e183 --- /dev/null +++ b/bin/templates/platformconstants.dart.dart @@ -0,0 +1,18 @@ +String $(c) { + return ''' +class CodecTypes{ + ${c['types'].map((_) => "static const int ${_['name']} = ${_['value']};").join('\n\t')} +} + +class PlatformMethod { + ${c['methods'].map((_) => "static const String ${_['name']} = '${_['value']}';").join('\n\t')} +} + +${c['objects'].map((_) { + return ''' +class Tx${_['name']}{ + ${_['properties'].map((_p) => 'static const String ${_p} = "${_p}";').join('\n\t')} +} +''';}).join('\n')} +'''; +} \ No newline at end of file diff --git a/bin/templates/platformconstants.dart.hbs b/bin/templates/platformconstants.dart.hbs deleted file mode 100644 index 669154605..000000000 --- a/bin/templates/platformconstants.dart.hbs +++ /dev/null @@ -1,11 +0,0 @@ -class CodecTypes{ - - {{#each types}}static const int {{name}} = {{value}}; - {{/each}} -} - -class PlatformMethod { - - {{#each methods}}static const String {{name}} = "{{value}}"; - {{/each}} -} diff --git a/bin/templates/platformconstants.h.dart b/bin/templates/platformconstants.h.dart new file mode 100644 index 000000000..52b2cfed4 --- /dev/null +++ b/bin/templates/platformconstants.h.dart @@ -0,0 +1,21 @@ +String $(c) { + return ''' +#import + +typedef NS_ENUM(UInt8, _Value) { + ${c['types'].map((_) => '${_['name']}CodecType = ${_['value']},').join('\n ')} +}; + + +@interface AblyPlatformMethod : NSObject +${c['methods'].map((_) => '@property (class, nonatomic, assign, readonly) NSString *${_['name']};').join('\n')} +@end + +${c['objects'].map((_) { + return ''' +@interface Tx${_['name']} : NSObject +${_['properties'].map((_) => '@property (class, nonatomic, assign, readonly) NSString *${_};').join('\n')} +@end +'''; + }).join('\n')}'''; +} \ No newline at end of file diff --git a/bin/templates/platformconstants.h.hbs b/bin/templates/platformconstants.h.hbs deleted file mode 100644 index e7686da11..000000000 --- a/bin/templates/platformconstants.h.hbs +++ /dev/null @@ -1,14 +0,0 @@ -#import - -typedef NS_ENUM(UInt8, _Value) { - - {{#each types}}{{name}}CodecType = {{value}}, - {{/each}} -}; - - -@interface AblyPlatformMethod : NSObject - -{{#each methods}}@property (class, nonatomic, assign, readonly) NSString *{{name}}; -{{/each}} -@end diff --git a/bin/templates/platformconstants.java.dart b/bin/templates/platformconstants.java.dart new file mode 100644 index 000000000..832946e67 --- /dev/null +++ b/bin/templates/platformconstants.java.dart @@ -0,0 +1,24 @@ +String $(c) { + return ''' +package io.ably.flutter.plugin.gen; + + +public class PlatformConstants{ + + public class CodecTypes { + ${c['types'].map((_) => 'public static final byte ${_['name']} = (byte)${_['value']};').join('\n\t')} + } + + public class PlatformMethod { + ${c['methods'].map((_) => 'public static final String ${_['name']} = "${_['value']}";').join('\n\t')} + } + +${c['objects'].map((_) { + return ''' + public class Tx${_['name']}{ + ${_['properties'].map((_p) => 'public static final String ${_p} = "${_p}";').join('\n\t')} + }'''; + }).join('\n')} +} +'''; +} diff --git a/bin/templates/platformconstants.m.dart b/bin/templates/platformconstants.m.dart new file mode 100644 index 000000000..5217b76e0 --- /dev/null +++ b/bin/templates/platformconstants.m.dart @@ -0,0 +1,18 @@ +String $(c) { + return ''' +#import +#import "AblyPlatformConstants.h" + + +@implementation AblyPlatformMethod +${c['methods'].map((_) => '+ (NSString*) ${_['name']} { return @"${_['value']}"; }').join('\n')} +@end + +${c['objects'].map((_) { + return ''' +@implementation Tx${_['name']} +${_['properties'].map((_) => '+ (NSString*) ${_} { return @"${_}"; }').join('\n')} +@end +'''; + }).join('\n')}'''; +} \ No newline at end of file diff --git a/bin/templates/platformconstants.m.hbs b/bin/templates/platformconstants.m.hbs deleted file mode 100644 index 0915c39bc..000000000 --- a/bin/templates/platformconstants.m.hbs +++ /dev/null @@ -1,9 +0,0 @@ -#import -#import "AblyPlatformConstants.h" - - -@implementation AblyPlatformMethod - -{{#each methods}}+ (NSString*) {{name}} { return @"{{value}}"; } -{{/each}} -@end diff --git a/ios/Classes/codec/AblyFlutterReader.m b/ios/Classes/codec/AblyFlutterReader.m index 443c396e9..0fe2f8f71 100644 --- a/ios/Classes/codec/AblyFlutterReader.m +++ b/ios/Classes/codec/AblyFlutterReader.m @@ -41,12 +41,12 @@ -(id)readValueOfType:(const UInt8)type { } static AblyCodecDecoder readAblyFlutterMessage = ^AblyFlutterMessage*(NSDictionary *const jsonDict) { - AblyCodecDecoder decoder = [AblyFlutterReader getDecoder: [NSString stringWithFormat:@"%@", [jsonDict objectForKey:@"type"]]]; - id message = [jsonDict objectForKey:@"message"]; + AblyCodecDecoder decoder = [AblyFlutterReader getDecoder: [NSString stringWithFormat:@"%@", [jsonDict objectForKey:TxAblyMessage.type]]]; + id message = [jsonDict objectForKey:TxAblyMessage.message]; if(decoder){ message = decoder(message); } - return [[AblyFlutterMessage alloc] initWithHandle:[jsonDict objectForKey:@"registrationHandle"] message:message]; + return [[AblyFlutterMessage alloc] initWithHandle:[jsonDict objectForKey:TxAblyMessage.registrationHandle] message:message]; }; /** @@ -87,35 +87,33 @@ use an explicitly received null from Dart (manifesting this side as a nil id) static AblyCodecDecoder readClientOptions = ^AblyFlutterMessage*(NSDictionary *const jsonDict) { ARTClientOptions *const o = [ARTClientOptions new]; - if([jsonDict objectForKey:@"message"]) o.authUrl = [jsonDict objectForKey:@"message"]; - // AuthOptions (super class of ClientOptions) - READ_VALUE(o, authUrl, jsonDict, @"authUrl"); - READ_VALUE(o, authMethod, jsonDict, @"authMethod"); - READ_VALUE(o, key, jsonDict, @"key"); - ON_VALUE(^(const id value) { o.tokenDetails = [AblyFlutterReader readTokenDetails: value]; }, jsonDict, @"tokenDetails"); - READ_VALUE(o, authHeaders, jsonDict, @"authHeaders"); - READ_VALUE(o, authParams, jsonDict, @"authParams"); - READ_VALUE(o, queryTime, jsonDict, @"queryTime"); + READ_VALUE(o, authUrl, jsonDict, TxClientOptions.authUrl); + READ_VALUE(o, authMethod, jsonDict, TxClientOptions.authMethod); + READ_VALUE(o, key, jsonDict, TxClientOptions.key); + ON_VALUE(^(const id value) { o.tokenDetails = [AblyFlutterReader readTokenDetails: value]; }, jsonDict, TxClientOptions.tokenDetails); + READ_VALUE(o, authHeaders, jsonDict, TxClientOptions.authHeaders); + READ_VALUE(o, authParams, jsonDict, TxClientOptions.authParams); + READ_VALUE(o, queryTime, jsonDict, TxClientOptions.queryTime); // ClientOptions - READ_VALUE(o, clientId, jsonDict, @"clientId"); - ON_VALUE(^(const id value) { o.logLevel = _logLevel(value); }, jsonDict, @"logLevel"); + READ_VALUE(o, clientId, jsonDict, TxClientOptions.clientId); + ON_VALUE(^(const id value) { o.logLevel = _logLevel(value); }, jsonDict, TxClientOptions.logLevel); //TODO log handler - READ_VALUE(o, tls, jsonDict, @"tls"); - READ_VALUE(o, restHost, jsonDict, @"restHost"); - READ_VALUE(o, realtimeHost, jsonDict, @"realtimeHost"); - READ_BOOL(o, autoConnect, jsonDict, @"autoConnect"); - READ_VALUE(o, useBinaryProtocol, jsonDict, @"useBinaryProtocol"); - READ_VALUE(o, queueMessages, jsonDict, @"queueMessages"); - READ_VALUE(o, echoMessages, jsonDict, @"echoMessages"); - READ_VALUE(o, recover, jsonDict, @"recover"); - READ_VALUE(o, environment, jsonDict, @"environment"); - READ_VALUE(o, idempotentRestPublishing, jsonDict, @"idempotentRestPublishing"); - READ_VALUE(o, fallbackHosts, jsonDict, @"fallbackHosts"); - READ_VALUE(o, fallbackHostsUseDefault, jsonDict, @"fallbackHostsUseDefault"); - ON_VALUE(^(const id value) { o.defaultTokenParams = [AblyFlutterReader readTokenParams: value]; }, jsonDict, @"defaultTokenParams"); - READ_VALUE(o, defaultTokenParams, jsonDict, @"defaultTokenParams"); + READ_VALUE(o, tls, jsonDict, TxClientOptions.tls); + READ_VALUE(o, restHost, jsonDict, TxClientOptions.restHost); + READ_VALUE(o, realtimeHost, jsonDict, TxClientOptions.realtimeHost); + READ_BOOL(o, autoConnect, jsonDict, TxClientOptions.autoConnect); + READ_VALUE(o, useBinaryProtocol, jsonDict, TxClientOptions.useBinaryProtocol); + READ_VALUE(o, queueMessages, jsonDict, TxClientOptions.queueMessages); + READ_VALUE(o, echoMessages, jsonDict, TxClientOptions.echoMessages); + READ_VALUE(o, recover, jsonDict, TxClientOptions.recover); + READ_VALUE(o, environment, jsonDict, TxClientOptions.environment); + READ_VALUE(o, idempotentRestPublishing, jsonDict, TxClientOptions.idempotentRestPublishing); + READ_VALUE(o, fallbackHosts, jsonDict, TxClientOptions.fallbackHosts); + READ_VALUE(o, fallbackHostsUseDefault, jsonDict, TxClientOptions.fallbackHostsUseDefault); + ON_VALUE(^(const id value) { o.defaultTokenParams = [AblyFlutterReader readTokenParams: value]; }, jsonDict, TxClientOptions.defaultTokenParams); + READ_VALUE(o, defaultTokenParams, jsonDict, TxClientOptions.defaultTokenParams); //Following properties not supported by Objective C library // READ_VALUE(o, useAuthToken); // property not found // READ_VALUE(o, port); // NSInteger @@ -140,11 +138,11 @@ +(ARTTokenDetails *)readTokenDetails: (NSDictionary *) jsonDict { __block NSString *capability = nil; __block NSString *clientId = nil; - ON_VALUE(^(const id value) { token = value; }, jsonDict, @"token"); - ON_VALUE(^(const id value) { expires = value; }, jsonDict, @"expires"); - ON_VALUE(^(const id value) { issued = value; }, jsonDict, @"issued"); - ON_VALUE(^(const id value) { capability = value; }, jsonDict, @"capability"); - ON_VALUE(^(const id value) { clientId = value; }, jsonDict, @"clientId"); + ON_VALUE(^(const id value) { token = value; }, jsonDict, TxTokenDetails.token); + ON_VALUE(^(const id value) { expires = value; }, jsonDict, TxTokenDetails.expires); + ON_VALUE(^(const id value) { issued = value; }, jsonDict, TxTokenDetails.issued); + ON_VALUE(^(const id value) { capability = value; }, jsonDict, TxTokenDetails.capability); + ON_VALUE(^(const id value) { clientId = value; }, jsonDict, TxTokenDetails.clientId); ARTTokenDetails *const o = [ARTTokenDetails new]; [o initWithToken:token expires:expires issued:issued capability:capability clientId:clientId]; @@ -155,14 +153,14 @@ +(ARTTokenParams *)readTokenParams: (NSDictionary *) jsonDict { __block NSString *clientId = nil; __block NSString *nonce = nil; - ON_VALUE(^(const id value) { clientId = value; }, jsonDict, @"clientId"); - ON_VALUE(^(const id value) { nonce = value; }, jsonDict, @"nonce"); + ON_VALUE(^(const id value) { clientId = value; }, jsonDict, TxTokenParams.clientId); + ON_VALUE(^(const id value) { nonce = value; }, jsonDict, TxTokenParams.nonce); ARTTokenParams *const o = [ARTTokenParams new]; [o initWithClientId: clientId nonce: nonce]; - READ_VALUE(o, ttl, jsonDict, @"ttl"); - READ_VALUE(o, capability, jsonDict, @"capability"); - READ_VALUE(o, timestamp, jsonDict, @"timestamp"); + READ_VALUE(o, ttl, jsonDict, TxTokenParams.ttl); + READ_VALUE(o, capability, jsonDict, TxTokenParams.capability); + READ_VALUE(o, timestamp, jsonDict, TxTokenParams.timestamp); return o; } diff --git a/ios/Classes/codec/AblyFlutterWriter.m b/ios/Classes/codec/AblyFlutterWriter.m index 7a73428d3..3c25e7d88 100644 --- a/ios/Classes/codec/AblyFlutterWriter.m +++ b/ios/Classes/codec/AblyFlutterWriter.m @@ -39,8 +39,8 @@ - (void)writeValue:(id)value { - (NSMutableDictionary *) encodeErrorInfo:(ARTErrorInfo *const) e{ NSMutableDictionary *jsonDict; - WRITE_VALUE(jsonDict, @"message", [e message]); - WRITE_VALUE(jsonDict, @"statusCode", @([e statusCode])); + WRITE_VALUE(jsonDict, TxErrorInfo.message, [e message]); + WRITE_VALUE(jsonDict, TxErrorInfo.statusCode, @([e statusCode])); //code - not available in ably-cocoa //href - not available in ably-cocoa //requestId - not available in ably-cocoa @@ -50,21 +50,21 @@ - (void)writeValue:(id)value { - (NSDictionary *) encodeConnectionStateChange:(ARTConnectionStateChange *const) stateChange{ NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init]; - WRITE_ENUM(jsonDict, @"current", [stateChange current]); - WRITE_ENUM(jsonDict, @"previous", [stateChange previous]); - WRITE_ENUM(jsonDict, @"event", [stateChange event]); - WRITE_VALUE(jsonDict, @"retryIn", @((int)([stateChange retryIn] * 1000))); - WRITE_VALUE(jsonDict, @"reason", [self encodeErrorInfo: [stateChange reason]]); + WRITE_ENUM(jsonDict, TxConnectionStateChange.current, [stateChange current]); + WRITE_ENUM(jsonDict, TxConnectionStateChange.previous, [stateChange previous]); + WRITE_ENUM(jsonDict, TxConnectionStateChange.event, [stateChange event]); + WRITE_VALUE(jsonDict, TxConnectionStateChange.retryIn, @((int)([stateChange retryIn] * 1000))); + WRITE_VALUE(jsonDict, TxConnectionStateChange.reason, [self encodeErrorInfo: [stateChange reason]]); return jsonDict; } - (NSDictionary *) encodeChannelStateChange:(ARTChannelStateChange *const) stateChange{ NSMutableDictionary *jsonDict; - WRITE_ENUM(jsonDict, @"current", [stateChange current]); - WRITE_ENUM(jsonDict, @"previous", [stateChange previous]); - WRITE_ENUM(jsonDict, @"event", [stateChange event]); - WRITE_VALUE(jsonDict, @"resumed", @([stateChange resumed])); - WRITE_VALUE(jsonDict, @"reason", [self encodeErrorInfo: [stateChange reason]]); + WRITE_ENUM(jsonDict, TxChannelStateChange.current, [stateChange current]); + WRITE_ENUM(jsonDict, TxChannelStateChange.previous, [stateChange previous]); + WRITE_ENUM(jsonDict, TxChannelStateChange.event, [stateChange event]); + WRITE_VALUE(jsonDict, TxChannelStateChange.resumed, @([stateChange resumed])); + WRITE_VALUE(jsonDict, TxChannelStateChange.reason, [self encodeErrorInfo: [stateChange reason]]); return jsonDict; } diff --git a/ios/Classes/codec/AblyPlatformConstants.h b/ios/Classes/codec/AblyPlatformConstants.h index 41937d568..c483e810c 100644 --- a/ios/Classes/codec/AblyPlatformConstants.h +++ b/ios/Classes/codec/AblyPlatformConstants.h @@ -1,23 +1,20 @@ // // Generated code. Do not modify. -// source: bin/templates/platformconstants.h.hbs +// source file can be found at bin/templates' // #import typedef NS_ENUM(UInt8, _Value) { - ablyMessageCodecType = 128, clientOptionsCodecType = 129, errorInfoCodecType = 144, connectionStateChangeCodecType = 201, channelStateChangeCodecType = 202, - }; @interface AblyPlatformMethod : NSObject - @property (class, nonatomic, assign, readonly) NSString *getPlatformVersion; @property (class, nonatomic, assign, readonly) NSString *getVersion; @property (class, nonatomic, assign, readonly) NSString *registerAbly; @@ -28,5 +25,86 @@ typedef NS_ENUM(UInt8, _Value) { @property (class, nonatomic, assign, readonly) NSString *closeRealtime; @property (class, nonatomic, assign, readonly) NSString *onRealtimeConnectionStateChanged; @property (class, nonatomic, assign, readonly) NSString *onRealtimeChannelStateChanged; +@end + +@interface TxAblyMessage : NSObject +@property (class, nonatomic, assign, readonly) NSString *registrationHandle; +@property (class, nonatomic, assign, readonly) NSString *type; +@property (class, nonatomic, assign, readonly) NSString *message; +@end + +@interface TxErrorInfo : NSObject +@property (class, nonatomic, assign, readonly) NSString *code; +@property (class, nonatomic, assign, readonly) NSString *message; +@property (class, nonatomic, assign, readonly) NSString *statusCode; +@property (class, nonatomic, assign, readonly) NSString *href; +@property (class, nonatomic, assign, readonly) NSString *requestId; +@property (class, nonatomic, assign, readonly) NSString *cause; +@end + +@interface TxClientOptions : NSObject +@property (class, nonatomic, assign, readonly) NSString *authUrl; +@property (class, nonatomic, assign, readonly) NSString *authMethod; +@property (class, nonatomic, assign, readonly) NSString *key; +@property (class, nonatomic, assign, readonly) NSString *tokenDetails; +@property (class, nonatomic, assign, readonly) NSString *authHeaders; +@property (class, nonatomic, assign, readonly) NSString *authParams; +@property (class, nonatomic, assign, readonly) NSString *queryTime; +@property (class, nonatomic, assign, readonly) NSString *useTokenAuth; +@property (class, nonatomic, assign, readonly) NSString *clientId; +@property (class, nonatomic, assign, readonly) NSString *logLevel; +@property (class, nonatomic, assign, readonly) NSString *tls; +@property (class, nonatomic, assign, readonly) NSString *restHost; +@property (class, nonatomic, assign, readonly) NSString *realtimeHost; +@property (class, nonatomic, assign, readonly) NSString *port; +@property (class, nonatomic, assign, readonly) NSString *tlsPort; +@property (class, nonatomic, assign, readonly) NSString *autoConnect; +@property (class, nonatomic, assign, readonly) NSString *useBinaryProtocol; +@property (class, nonatomic, assign, readonly) NSString *queueMessages; +@property (class, nonatomic, assign, readonly) NSString *echoMessages; +@property (class, nonatomic, assign, readonly) NSString *recover; +@property (class, nonatomic, assign, readonly) NSString *environment; +@property (class, nonatomic, assign, readonly) NSString *idempotentRestPublishing; +@property (class, nonatomic, assign, readonly) NSString *httpOpenTimeout; +@property (class, nonatomic, assign, readonly) NSString *httpRequestTimeout; +@property (class, nonatomic, assign, readonly) NSString *httpMaxRetryCount; +@property (class, nonatomic, assign, readonly) NSString *realtimeRequestTimeout; +@property (class, nonatomic, assign, readonly) NSString *fallbackHosts; +@property (class, nonatomic, assign, readonly) NSString *fallbackHostsUseDefault; +@property (class, nonatomic, assign, readonly) NSString *fallbackRetryTimeout; +@property (class, nonatomic, assign, readonly) NSString *defaultTokenParams; +@property (class, nonatomic, assign, readonly) NSString *channelRetryTimeout; +@property (class, nonatomic, assign, readonly) NSString *transportParams; +@end + +@interface TxTokenDetails : NSObject +@property (class, nonatomic, assign, readonly) NSString *token; +@property (class, nonatomic, assign, readonly) NSString *expires; +@property (class, nonatomic, assign, readonly) NSString *issued; +@property (class, nonatomic, assign, readonly) NSString *capability; +@property (class, nonatomic, assign, readonly) NSString *clientId; +@end + +@interface TxTokenParams : NSObject +@property (class, nonatomic, assign, readonly) NSString *capability; +@property (class, nonatomic, assign, readonly) NSString *clientId; +@property (class, nonatomic, assign, readonly) NSString *nonce; +@property (class, nonatomic, assign, readonly) NSString *timestamp; +@property (class, nonatomic, assign, readonly) NSString *ttl; +@end + +@interface TxConnectionStateChange : NSObject +@property (class, nonatomic, assign, readonly) NSString *current; +@property (class, nonatomic, assign, readonly) NSString *previous; +@property (class, nonatomic, assign, readonly) NSString *event; +@property (class, nonatomic, assign, readonly) NSString *retryIn; +@property (class, nonatomic, assign, readonly) NSString *reason; +@end +@interface TxChannelStateChange : NSObject +@property (class, nonatomic, assign, readonly) NSString *current; +@property (class, nonatomic, assign, readonly) NSString *previous; +@property (class, nonatomic, assign, readonly) NSString *event; +@property (class, nonatomic, assign, readonly) NSString *resumed; +@property (class, nonatomic, assign, readonly) NSString *reason; @end diff --git a/ios/Classes/codec/AblyPlatformConstants.m b/ios/Classes/codec/AblyPlatformConstants.m index 6c9948375..92fde5cc0 100644 --- a/ios/Classes/codec/AblyPlatformConstants.m +++ b/ios/Classes/codec/AblyPlatformConstants.m @@ -1,6 +1,6 @@ // // Generated code. Do not modify. -// source: bin/templates/platformconstants.m.hbs +// source file can be found at bin/templates' // #import @@ -8,7 +8,6 @@ @implementation AblyPlatformMethod - + (NSString*) getPlatformVersion { return @"getPlatformVersion"; } + (NSString*) getVersion { return @"getVersion"; } + (NSString*) registerAbly { return @"registerAbly"; } @@ -19,5 +18,86 @@ + (NSString*) connectRealtime { return @"connectRealtime"; } + (NSString*) closeRealtime { return @"closeRealtime"; } + (NSString*) onRealtimeConnectionStateChanged { return @"onRealtimeConnectionStateChanged"; } + (NSString*) onRealtimeChannelStateChanged { return @"onRealtimeChannelStateChanged"; } +@end + +@implementation TxAblyMessage ++ (NSString*) registrationHandle { return @"registrationHandle"; } ++ (NSString*) type { return @"type"; } ++ (NSString*) message { return @"message"; } +@end + +@implementation TxErrorInfo ++ (NSString*) code { return @"code"; } ++ (NSString*) message { return @"message"; } ++ (NSString*) statusCode { return @"statusCode"; } ++ (NSString*) href { return @"href"; } ++ (NSString*) requestId { return @"requestId"; } ++ (NSString*) cause { return @"cause"; } +@end + +@implementation TxClientOptions ++ (NSString*) authUrl { return @"authUrl"; } ++ (NSString*) authMethod { return @"authMethod"; } ++ (NSString*) key { return @"key"; } ++ (NSString*) tokenDetails { return @"tokenDetails"; } ++ (NSString*) authHeaders { return @"authHeaders"; } ++ (NSString*) authParams { return @"authParams"; } ++ (NSString*) queryTime { return @"queryTime"; } ++ (NSString*) useTokenAuth { return @"useTokenAuth"; } ++ (NSString*) clientId { return @"clientId"; } ++ (NSString*) logLevel { return @"logLevel"; } ++ (NSString*) tls { return @"tls"; } ++ (NSString*) restHost { return @"restHost"; } ++ (NSString*) realtimeHost { return @"realtimeHost"; } ++ (NSString*) port { return @"port"; } ++ (NSString*) tlsPort { return @"tlsPort"; } ++ (NSString*) autoConnect { return @"autoConnect"; } ++ (NSString*) useBinaryProtocol { return @"useBinaryProtocol"; } ++ (NSString*) queueMessages { return @"queueMessages"; } ++ (NSString*) echoMessages { return @"echoMessages"; } ++ (NSString*) recover { return @"recover"; } ++ (NSString*) environment { return @"environment"; } ++ (NSString*) idempotentRestPublishing { return @"idempotentRestPublishing"; } ++ (NSString*) httpOpenTimeout { return @"httpOpenTimeout"; } ++ (NSString*) httpRequestTimeout { return @"httpRequestTimeout"; } ++ (NSString*) httpMaxRetryCount { return @"httpMaxRetryCount"; } ++ (NSString*) realtimeRequestTimeout { return @"realtimeRequestTimeout"; } ++ (NSString*) fallbackHosts { return @"fallbackHosts"; } ++ (NSString*) fallbackHostsUseDefault { return @"fallbackHostsUseDefault"; } ++ (NSString*) fallbackRetryTimeout { return @"fallbackRetryTimeout"; } ++ (NSString*) defaultTokenParams { return @"defaultTokenParams"; } ++ (NSString*) channelRetryTimeout { return @"channelRetryTimeout"; } ++ (NSString*) transportParams { return @"transportParams"; } +@end + +@implementation TxTokenDetails ++ (NSString*) token { return @"token"; } ++ (NSString*) expires { return @"expires"; } ++ (NSString*) issued { return @"issued"; } ++ (NSString*) capability { return @"capability"; } ++ (NSString*) clientId { return @"clientId"; } +@end + +@implementation TxTokenParams ++ (NSString*) capability { return @"capability"; } ++ (NSString*) clientId { return @"clientId"; } ++ (NSString*) nonce { return @"nonce"; } ++ (NSString*) timestamp { return @"timestamp"; } ++ (NSString*) ttl { return @"ttl"; } +@end + +@implementation TxConnectionStateChange ++ (NSString*) current { return @"current"; } ++ (NSString*) previous { return @"previous"; } ++ (NSString*) event { return @"event"; } ++ (NSString*) retryIn { return @"retryIn"; } ++ (NSString*) reason { return @"reason"; } +@end +@implementation TxChannelStateChange ++ (NSString*) current { return @"current"; } ++ (NSString*) previous { return @"previous"; } ++ (NSString*) event { return @"event"; } ++ (NSString*) resumed { return @"resumed"; } ++ (NSString*) reason { return @"reason"; } @end diff --git a/lib/src/codec.dart b/lib/src/codec.dart index 2fae850a5..b422eb6e0 100644 --- a/lib/src/codec.dart +++ b/lib/src/codec.dart @@ -98,63 +98,63 @@ class Codec extends StandardMessageCodec { if(v==null) return null; Map jsonMap = {}; // AuthOptions (super class of ClientOptions) - writeToJson(jsonMap, "authUrl", v.authUrl); - writeToJson(jsonMap, "authMethod", v.authMethod); - writeToJson(jsonMap, "key", v.key); - writeToJson(jsonMap, "tokenDetails", encodeTokenDetails(v.tokenDetails)); - writeToJson(jsonMap, "authHeaders", v.authHeaders); - writeToJson(jsonMap, "authParams", v.authParams); - writeToJson(jsonMap, "queryTime", v.queryTime); - writeToJson(jsonMap, "useTokenAuth", v.useTokenAuth); + 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); // ClientOptions - writeToJson(jsonMap, "clientId", v.clientId); - writeToJson(jsonMap, "logLevel", v.logLevel); + writeToJson(jsonMap, TxClientOptions.clientId, v.clientId); + writeToJson(jsonMap, TxClientOptions.logLevel, v.logLevel); //TODO handle logHandler - writeToJson(jsonMap, "tls", v.tls); - writeToJson(jsonMap, "restHost", v.restHost); - writeToJson(jsonMap, "realtimeHost", v.realtimeHost); - writeToJson(jsonMap, "port", v.port); - writeToJson(jsonMap, "tlsPort", v.tlsPort); - writeToJson(jsonMap, "autoConnect", v.autoConnect); - writeToJson(jsonMap, "useBinaryProtocol", v.useBinaryProtocol); - writeToJson(jsonMap, "queueMessages", v.queueMessages); - writeToJson(jsonMap, "echoMessages", v.echoMessages); - writeToJson(jsonMap, "recover", v.recover); - writeToJson(jsonMap, "environment", v.environment); - writeToJson(jsonMap, "idempotentRestPublishing", v.idempotentRestPublishing); - writeToJson(jsonMap, "httpOpenTimeout", v.httpOpenTimeout); - writeToJson(jsonMap, "httpRequestTimeout", v.httpRequestTimeout); - writeToJson(jsonMap, "httpMaxRetryCount", v.httpMaxRetryCount); - writeToJson(jsonMap, "realtimeRequestTimeout", v.realtimeRequestTimeout); - writeToJson(jsonMap, "fallbackHosts", v.fallbackHosts); - writeToJson(jsonMap, "fallbackHostsUseDefault", v.fallbackHostsUseDefault); - writeToJson(jsonMap, "fallbackRetryTimeout", v.fallbackRetryTimeout); - writeToJson(jsonMap, "defaultTokenParams", encodeTokenParams(v.defaultTokenParams)); - writeToJson(jsonMap, "channelRetryTimeout", v.channelRetryTimeout); - writeToJson(jsonMap, "transportParams", v.transportParams); + 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; } Map encodeTokenDetails(final TokenDetails v){ if(v==null) return null; return { - "token": v.token, - "expires": v.expires, - "issued": v.issued, - "capability": v.capability, - "clientId": v.clientId, + TxTokenDetails.token: v.token, + TxTokenDetails.expires: v.expires, + TxTokenDetails.issued: v.issued, + TxTokenDetails.capability: v.capability, + TxTokenDetails.clientId: v.clientId, }; } Map encodeTokenParams(final TokenParams v){ if(v==null) return null; Map jsonMap = {}; - writeToJson(jsonMap, "capability", v.capability); - writeToJson(jsonMap, "clientId", v.clientId); - writeToJson(jsonMap, "nonce", v.nonce); - writeToJson(jsonMap, "timestamp", v.timestamp); - writeToJson(jsonMap, "ttl", v.ttl); + 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; } @@ -163,9 +163,9 @@ class Codec extends StandardMessageCodec { int codecType = getCodecType(v.message); dynamic message = (v.message==null)?null:(codecType == null)?v.message:codecMap[codecType].encode(v.message); Map jsonMap = {}; - writeToJson(jsonMap, "registrationHandle", v.registrationHandle); - writeToJson(jsonMap, "type", codecType); - writeToJson(jsonMap, "message", message); + writeToJson(jsonMap, TxAblyMessage.registrationHandle, v.registrationHandle); + writeToJson(jsonMap, TxAblyMessage.type, codecType); + writeToJson(jsonMap, TxAblyMessage.message, message); return jsonMap; } @@ -182,74 +182,74 @@ class Codec extends StandardMessageCodec { final ClientOptions v = ClientOptions(); // AuthOptions (super class of ClientOptions) - v.authUrl = readFromJson(jsonMap, "authUrl"); - v.authMethod = readFromJson(jsonMap, "authMethod"); - v.key = readFromJson(jsonMap, "key"); - v.tokenDetails = decodeTokenDetails(toJsonMap(jsonMap["tokenDetails"])); - v.authHeaders = readFromJson>(jsonMap, "authHeaders"); - v.authParams = readFromJson>(jsonMap, "authParams"); - v.queryTime = readFromJson(jsonMap, "queryTime"); - v.useTokenAuth = readFromJson(jsonMap, "useTokenAuth"); + v.authUrl = readFromJson(jsonMap, TxClientOptions.authUrl); + v.authMethod = readFromJson(jsonMap, TxClientOptions.authMethod); + v.key = readFromJson(jsonMap, TxClientOptions.key); + v.tokenDetails = decodeTokenDetails(toJsonMap(jsonMap[TxClientOptions.tokenDetails])); + v.authHeaders = readFromJson>(jsonMap, TxClientOptions.authHeaders); + v.authParams = readFromJson>(jsonMap, TxClientOptions.authParams); + v.queryTime = readFromJson(jsonMap, TxClientOptions.queryTime); + v.useTokenAuth = readFromJson(jsonMap, TxClientOptions.useTokenAuth); // ClientOptions - v.clientId = readFromJson(jsonMap, "clientId"); - v.logLevel = readFromJson(jsonMap, "logLevel"); + v.clientId = readFromJson(jsonMap, TxClientOptions.clientId); + v.logLevel = readFromJson(jsonMap, TxClientOptions.logLevel); //TODO handle logHandler - v.tls = readFromJson(jsonMap, "tls"); - v.restHost = readFromJson(jsonMap, "restHost"); - v.realtimeHost = readFromJson(jsonMap, "realtimeHost"); - v.port = readFromJson(jsonMap, "port"); - v.tlsPort = readFromJson(jsonMap, "tlsPort"); - v.autoConnect = readFromJson(jsonMap, "autoConnect"); - v.useBinaryProtocol = readFromJson(jsonMap, "useBinaryProtocol"); - v.queueMessages = readFromJson(jsonMap, "queueMessages"); - v.echoMessages = readFromJson(jsonMap, "echoMessages"); - v.recover = readFromJson(jsonMap, "recover"); - v.environment = readFromJson(jsonMap, "environment"); - v.idempotentRestPublishing = readFromJson(jsonMap, "idempotentRestPublishing"); - v.httpOpenTimeout = readFromJson(jsonMap, "httpOpenTimeout"); - v.httpRequestTimeout = readFromJson(jsonMap, "httpRequestTimeout"); - v.httpMaxRetryCount = readFromJson(jsonMap, "httpMaxRetryCount"); - v.realtimeRequestTimeout = readFromJson(jsonMap, "realtimeRequestTimeout"); - v.fallbackHosts = readFromJson>(jsonMap, "fallbackHosts"); - v.fallbackHostsUseDefault = readFromJson(jsonMap, "fallbackHostsUseDefault"); - v.fallbackRetryTimeout = readFromJson(jsonMap, "fallbackRetryTimeout"); - v.defaultTokenParams = decodeTokenParams(toJsonMap(jsonMap["defaultTokenParams"])); - v.channelRetryTimeout = readFromJson(jsonMap, "channelRetryTimeout"); - v.transportParams = readFromJson>(jsonMap, "transportParams"); + v.tls = readFromJson(jsonMap, TxClientOptions.tls); + v.restHost = readFromJson(jsonMap, TxClientOptions.restHost); + v.realtimeHost = readFromJson(jsonMap, TxClientOptions.realtimeHost); + v.port = readFromJson(jsonMap, TxClientOptions.port); + v.tlsPort = readFromJson(jsonMap, TxClientOptions.tlsPort); + v.autoConnect = readFromJson(jsonMap, TxClientOptions.autoConnect); + v.useBinaryProtocol = readFromJson(jsonMap, TxClientOptions.useBinaryProtocol); + v.queueMessages = readFromJson(jsonMap, TxClientOptions.queueMessages); + v.echoMessages = readFromJson(jsonMap, TxClientOptions.echoMessages); + v.recover = readFromJson(jsonMap, TxClientOptions.recover); + v.environment = readFromJson(jsonMap, TxClientOptions.environment); + v.idempotentRestPublishing = readFromJson(jsonMap, TxClientOptions.idempotentRestPublishing); + v.httpOpenTimeout = readFromJson(jsonMap, TxClientOptions.httpOpenTimeout); + v.httpRequestTimeout = readFromJson(jsonMap, TxClientOptions.httpRequestTimeout); + v.httpMaxRetryCount = readFromJson(jsonMap, TxClientOptions.httpMaxRetryCount); + v.realtimeRequestTimeout = readFromJson(jsonMap, TxClientOptions.realtimeRequestTimeout); + v.fallbackHosts = readFromJson>(jsonMap, TxClientOptions.fallbackHosts); + v.fallbackHostsUseDefault = readFromJson(jsonMap, TxClientOptions.fallbackHostsUseDefault); + v.fallbackRetryTimeout = readFromJson(jsonMap, TxClientOptions.fallbackRetryTimeout); + v.defaultTokenParams = decodeTokenParams(toJsonMap(jsonMap[TxClientOptions.defaultTokenParams])); + v.channelRetryTimeout = readFromJson(jsonMap, TxClientOptions.channelRetryTimeout); + v.transportParams = readFromJson>(jsonMap, TxClientOptions.transportParams); return v; } TokenDetails decodeTokenDetails(Map jsonMap){ if(jsonMap==null) return null; - TokenDetails v = TokenDetails(jsonMap["token"]); - v.expires = readFromJson(jsonMap, "expires"); - v.issued = readFromJson(jsonMap, "issued"); - v.capability = readFromJson(jsonMap, "capability"); - v.clientId = readFromJson(jsonMap, "clientId"); + TokenDetails v = TokenDetails(jsonMap[TxTokenDetails.token]); + v.expires = readFromJson(jsonMap, TxTokenDetails.expires); + v.issued = readFromJson(jsonMap, TxTokenDetails.issued); + v.capability = readFromJson(jsonMap, TxTokenDetails.capability); + v.clientId = readFromJson(jsonMap, TxTokenDetails.clientId); return v; } TokenParams decodeTokenParams(Map jsonMap){ if(jsonMap==null) return null; TokenParams v = TokenParams(); - v.capability = readFromJson(jsonMap, "capability"); - v.clientId = readFromJson(jsonMap, "clientId"); - v.nonce = readFromJson(jsonMap, "nonce"); - v.timestamp = readFromJson(jsonMap, "timestamp"); - v.ttl = readFromJson(jsonMap, "ttl"); + v.capability = readFromJson(jsonMap, TxTokenParams.capability); + v.clientId = readFromJson(jsonMap, TxTokenParams.clientId); + v.nonce = readFromJson(jsonMap, TxTokenParams.nonce); + v.timestamp = readFromJson(jsonMap, TxTokenParams.timestamp); + v.ttl = readFromJson(jsonMap, TxTokenParams.ttl); return v; } AblyMessage decodeAblyMessage(Map jsonMap){ if(jsonMap==null) return null; - int type = readFromJson(jsonMap, "type"); - dynamic message = jsonMap["message"]; + int type = readFromJson(jsonMap, TxAblyMessage.type); + dynamic message = jsonMap[TxAblyMessage.message]; if(type!=null){ - message = codecMap[type].decode(toJsonMap(jsonMap["message"])); + message = codecMap[type].decode(toJsonMap(jsonMap[TxAblyMessage.message])); } return AblyMessage( - jsonMap["registrationHandle"] as int, + jsonMap[TxAblyMessage.registrationHandle] as int, message, type: type ); @@ -258,12 +258,12 @@ class Codec extends StandardMessageCodec { ErrorInfo decodeErrorInfo(Map jsonMap){ if(jsonMap==null) return null; return ErrorInfo( - code: jsonMap["code"] as int, - message: jsonMap["message"] as String, - statusCode: jsonMap["statusCode"] as int, - href: jsonMap["href"] as String, - requestId: jsonMap["requestId"] as String, - cause: jsonMap["cause"] as 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 ); } @@ -274,21 +274,21 @@ class Codec extends StandardMessageCodec { ConnectionStateChange decodeConnectionStateChange(Map jsonMap){ if(jsonMap==null) return null; - ConnectionState current = decodeConnectionState(readFromJson(jsonMap, "current")); - ConnectionState previous = decodeConnectionState(readFromJson(jsonMap, "previous")); - ConnectionEvent event = decodeConnectionEvent(readFromJson(jsonMap, "event")); - int retryIn = readFromJson(jsonMap, "retryIn"); - ErrorInfo reason = decodeErrorInfo(toJsonMap(jsonMap["reason"])); + ConnectionState current = decodeConnectionState(readFromJson(jsonMap, TxConnectionStateChange.current)); + ConnectionState previous = decodeConnectionState(readFromJson(jsonMap, TxConnectionStateChange.previous)); + ConnectionEvent event = decodeConnectionEvent(readFromJson(jsonMap, TxConnectionStateChange.event)); + int retryIn = readFromJson(jsonMap, TxConnectionStateChange.retryIn); + ErrorInfo reason = decodeErrorInfo(toJsonMap(jsonMap[TxConnectionStateChange.reason])); return ConnectionStateChange(current, previous, event, retryIn: retryIn, reason: reason); } ChannelStateChange decodeChannelStateChange(Map jsonMap){ if(jsonMap==null) return null; - ChannelState current = decodeChannelState(readFromJson(jsonMap, "current")); - ChannelState previous = decodeChannelState(readFromJson(jsonMap, "previous")); - ChannelEvent event = decodeChannelEvent(readFromJson(jsonMap, "event")); - bool resumed = readFromJson(jsonMap, "resumed"); - ErrorInfo reason = decodeErrorInfo(jsonMap["reason"]); + ChannelState current = decodeChannelState(readFromJson(jsonMap, TxChannelStateChange.current)); + ChannelState previous = decodeChannelState(readFromJson(jsonMap, TxChannelStateChange.previous)); + ChannelEvent event = decodeChannelEvent(readFromJson(jsonMap, TxChannelStateChange.event)); + bool resumed = readFromJson(jsonMap, TxChannelStateChange.resumed); + ErrorInfo reason = decodeErrorInfo(jsonMap[TxChannelStateChange.reason]); return ChannelStateChange(current, previous, event, resumed: resumed, reason: reason); } diff --git a/lib/src/gen/platformconstants.dart b/lib/src/gen/platformconstants.dart index eabbc0a62..b29fcbf4b 100644 --- a/lib/src/gen/platformconstants.dart +++ b/lib/src/gen/platformconstants.dart @@ -1,29 +1,108 @@ // // Generated code. Do not modify. -// source: bin/templates/platformconstants.dart.hbs +// source file can be found at bin/templates' // class CodecTypes{ - static const int ablyMessage = 128; - static const int clientOptions = 129; - static const int errorInfo = 144; - static const int connectionStateChange = 201; - static const int channelStateChange = 202; - + static const int clientOptions = 129; + static const int errorInfo = 144; + static const int connectionStateChange = 201; + static const int channelStateChange = 202; } class PlatformMethod { + static const String getPlatformVersion = 'getPlatformVersion'; + static const String getVersion = 'getVersion'; + static const String registerAbly = 'registerAbly'; + static const String createRestWithOptions = 'createRestWithOptions'; + static const String publish = 'publish'; + static const String createRealtimeWithOptions = 'createRealtimeWithOptions'; + static const String connectRealtime = 'connectRealtime'; + static const String closeRealtime = 'closeRealtime'; + static const String onRealtimeConnectionStateChanged = 'onRealtimeConnectionStateChanged'; + static const String onRealtimeChannelStateChanged = 'onRealtimeChannelStateChanged'; +} + +class TxAblyMessage{ + static const String registrationHandle = "registrationHandle"; + static const String type = "type"; + static const String message = "message"; +} + +class TxErrorInfo{ + static const String code = "code"; + static const String message = "message"; + static const String statusCode = "statusCode"; + static const String href = "href"; + static const String requestId = "requestId"; + static const String cause = "cause"; +} + +class TxClientOptions{ + static const String authUrl = "authUrl"; + static const String authMethod = "authMethod"; + static const String key = "key"; + static const String tokenDetails = "tokenDetails"; + static const String authHeaders = "authHeaders"; + static const String authParams = "authParams"; + static const String queryTime = "queryTime"; + static const String useTokenAuth = "useTokenAuth"; + static const String clientId = "clientId"; + static const String logLevel = "logLevel"; + static const String tls = "tls"; + static const String restHost = "restHost"; + static const String realtimeHost = "realtimeHost"; + static const String port = "port"; + static const String tlsPort = "tlsPort"; + static const String autoConnect = "autoConnect"; + static const String useBinaryProtocol = "useBinaryProtocol"; + static const String queueMessages = "queueMessages"; + static const String echoMessages = "echoMessages"; + static const String recover = "recover"; + static const String environment = "environment"; + static const String idempotentRestPublishing = "idempotentRestPublishing"; + static const String httpOpenTimeout = "httpOpenTimeout"; + static const String httpRequestTimeout = "httpRequestTimeout"; + static const String httpMaxRetryCount = "httpMaxRetryCount"; + static const String realtimeRequestTimeout = "realtimeRequestTimeout"; + static const String fallbackHosts = "fallbackHosts"; + static const String fallbackHostsUseDefault = "fallbackHostsUseDefault"; + static const String fallbackRetryTimeout = "fallbackRetryTimeout"; + static const String defaultTokenParams = "defaultTokenParams"; + static const String channelRetryTimeout = "channelRetryTimeout"; + static const String transportParams = "transportParams"; +} - static const String getPlatformVersion = "getPlatformVersion"; - static const String getVersion = "getVersion"; - static const String registerAbly = "registerAbly"; - static const String createRestWithOptions = "createRestWithOptions"; - static const String publish = "publish"; - static const String createRealtimeWithOptions = "createRealtimeWithOptions"; - static const String connectRealtime = "connectRealtime"; - static const String closeRealtime = "closeRealtime"; - static const String onRealtimeConnectionStateChanged = "onRealtimeConnectionStateChanged"; - static const String onRealtimeChannelStateChanged = "onRealtimeChannelStateChanged"; - +class TxTokenDetails{ + static const String token = "token"; + static const String expires = "expires"; + static const String issued = "issued"; + static const String capability = "capability"; + static const String clientId = "clientId"; } + +class TxTokenParams{ + static const String capability = "capability"; + static const String clientId = "clientId"; + static const String nonce = "nonce"; + static const String timestamp = "timestamp"; + static const String ttl = "ttl"; +} + +class TxConnectionStateChange{ + static const String current = "current"; + static const String previous = "previous"; + static const String event = "event"; + static const String retryIn = "retryIn"; + static const String reason = "reason"; +} + +class TxChannelStateChange{ + static const String current = "current"; + static const String previous = "previous"; + static const String event = "event"; + static const String resumed = "resumed"; + static const String reason = "reason"; +} + From cd09506a967bd6816e3779a8f28012ec7c1818cd Mon Sep 17 00:00:00 2001 From: Rohit Reddy Abbadi Date: Thu, 4 Jun 2020 16:34:57 +0530 Subject: [PATCH 08/19] Update ios/Classes/codec/AblyFlutterWriter.m [code consistency] remove space for ObjC arguments https://github.com/ably/ably-flutter/pull/13#discussion_r434455458 Co-authored-by: Quintin --- ios/Classes/codec/AblyFlutterWriter.m | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ios/Classes/codec/AblyFlutterWriter.m b/ios/Classes/codec/AblyFlutterWriter.m index 3c25e7d88..d2f4a9d28 100644 --- a/ios/Classes/codec/AblyFlutterWriter.m +++ b/ios/Classes/codec/AblyFlutterWriter.m @@ -11,7 +11,7 @@ @implementation AblyFlutterWriter - (void)writeValue:(id)value { if([value isKindOfClass:[ARTErrorInfo class]]){ [self writeByte:errorInfoCodecType]; - [self writeValue: [self encodeErrorInfo: value]]; + [self writeValue:[self encodeErrorInfo: value]]; return; }else if([value isKindOfClass:[ARTConnectionStateChange class]]){ [self writeByte:connectionStateChangeCodecType]; From aee2ca298f4798ee10bc5df0b4dad706380b27b3 Mon Sep 17 00:00:00 2001 From: Rohit Reddy Abbadi Date: Thu, 4 Jun 2020 16:39:04 +0530 Subject: [PATCH 09/19] Update ios/Classes/codec/AblyFlutterReader.m [cleanup] Adding NS_ASSUME_NONNULL_BEGIN and END as per the comment https://github.com/ably/ably-flutter/pull/13#discussion_r434447029 Co-authored-by: Quintin --- ios/Classes/codec/AblyFlutterReader.m | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/ios/Classes/codec/AblyFlutterReader.m b/ios/Classes/codec/AblyFlutterReader.m index 0fe2f8f71..eaf582b1e 100644 --- a/ios/Classes/codec/AblyFlutterReader.m +++ b/ios/Classes/codec/AblyFlutterReader.m @@ -18,7 +18,11 @@ static ARTLogLevel _logLevel(NSNumber *const number) { return ARTLogLevelWarn; } -typedef id (^AblyCodecDecoder)(NSDictionary * jsonDict); +NS_ASSUME_NONNULL_BEGIN + +typedef id (^AblyCodecDecoder)(NSDictionary * dictionary); + +NS_ASSUME_NONNULL_END @implementation AblyFlutterReader From bc8172ccb3d6515ffcc821c4667a09ccb692b026 Mon Sep 17 00:00:00 2001 From: "Rohit R. Abbadi" Date: Thu, 4 Jun 2020 16:49:41 +0530 Subject: [PATCH 10/19] leading space consistency in commentary https://github.com/ably/ably-flutter/pull/13/files#r434375290 --- bin/codegen.dart | 2 +- bin/codegencontext.dart | 8 ++++---- lib/src/codec.dart | 8 ++++---- lib/src/spec/common.dart | 2 +- lib/src/spec/rest/options.dart | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/bin/codegen.dart b/bin/codegen.dart index c66c305a3..4725ab2e1 100644 --- a/bin/codegen.dart +++ b/bin/codegen.dart @@ -11,7 +11,7 @@ typedef String Template(Map context); String projectRoot = "../"; Map toGenerate = { - //input template method vs output file path + // input template method vs output file path dart_template.$: "${projectRoot}lib/src/gen/platformconstants.dart", java_template.$: "${projectRoot}android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java", objc_header_template.$: "${projectRoot}ios/Classes/codec/AblyPlatformConstants.h", diff --git a/bin/codegencontext.dart b/bin/codegencontext.dart index c8c090057..e923ba1db 100644 --- a/bin/codegencontext.dart +++ b/bin/codegencontext.dart @@ -9,7 +9,7 @@ List> _types = [ // // https://api.flutter.dev/flutter/services/StandardMessageCodec/writeValue.html - //Ably flutter plugin protocol message + // Ably flutter plugin protocol message {"name": "ablyMessage", "value": 128}, //Other ably objects @@ -36,7 +36,7 @@ List> _platformMethods = [ {"name": "connectRealtime", "value": "connectRealtime"}, {"name": "closeRealtime", "value": "closeRealtime"}, - //Realtime events + // Realtime events {"name": "onRealtimeConnectionStateChanged", "value": "onRealtimeConnectionStateChanged"}, {"name": "onRealtimeChannelStateChanged", "value": "onRealtimeChannelStateChanged"} ]; @@ -64,7 +64,7 @@ List> objects = [ { "name": "ClientOptions", "properties": [ - //Auth options + // Auth options "authUrl", "authMethod", "key", @@ -143,7 +143,7 @@ List> objects = [ ]; -//exporting all the constants as a single map +// exporting all the constants as a single map // which can be directly fed to template as context Map context = { "types": _types, diff --git a/lib/src/codec.dart b/lib/src/codec.dart index b422eb6e0..48841cb45 100644 --- a/lib/src/codec.dart +++ b/lib/src/codec.dart @@ -35,17 +35,17 @@ class Codec extends StandardMessageCodec { Codec():super(){ this.codecMap = { - //Ably flutter plugin protocol message + // Ably flutter plugin protocol message CodecTypes.ablyMessage: CodecPair(encodeAblyMessage, decodeAblyMessage), - //Other ably objects + // Other ably objects CodecTypes.clientOptions: CodecPair(encodeClientOptions, decodeClientOptions), CodecTypes.errorInfo: CodecPair(null, decodeErrorInfo), - //Events - Connection + // Events - Connection CodecTypes.connectionStateChange: CodecPair(null, decodeConnectionStateChange), - //Events - Channel + // Events - Channel CodecTypes.channelStateChange: CodecPair(null, decodeChannelStateChange), }; } diff --git a/lib/src/spec/common.dart b/lib/src/spec/common.dart index 79ef4ebc9..2e7883285 100644 --- a/lib/src/spec/common.dart +++ b/lib/src/spec/common.dart @@ -234,7 +234,7 @@ abstract class EventListener { abstract class EventEmitter { // Remove all listener registrations, irrespective of type. - //Future off(); + // Future off(); /// Create a listener, with which registrations may be made. Stream on([E event]); diff --git a/lib/src/spec/rest/options.dart b/lib/src/spec/rest/options.dart index bec37b63b..31524290a 100644 --- a/lib/src/spec/rest/options.dart +++ b/lib/src/spec/rest/options.dart @@ -101,7 +101,7 @@ class ClientOptions extends AuthOptions { ///Use this only if you have been provided a dedicated environment by Ably String environment; //optional - //Fallbacks + // Fallbacks List fallbackHosts; //optional bool fallbackHostsUseDefault; //optional From a811d5652850e7970be20e4aa4716ba17f69134b Mon Sep 17 00:00:00 2001 From: "Rohit R. Abbadi" Date: Thu, 4 Jun 2020 16:55:18 +0530 Subject: [PATCH 11/19] [consistency] new line at EOF https://github.com/ably/ably-flutter/pull/13/files#r434377705 --- bin/templates/platformconstants.dart.dart | 2 +- bin/templates/platformconstants.h.dart | 2 +- bin/templates/platformconstants.m.dart | 2 +- lib/src/impl/realtime/channels.dart | 2 +- lib/src/impl/realtime/connection.dart | 2 +- lib/src/impl/realtime/realtime.dart | 2 +- lib/src/impl/rest/channels.dart | 2 +- lib/src/impl/rest/rest.dart | 2 +- lib/src/spec/auth.dart | 3 +-- lib/src/spec/common.dart | 2 +- lib/src/spec/connection.dart | 2 +- lib/src/spec/enums.dart | 2 +- lib/src/spec/message.dart | 2 +- lib/src/spec/push/channels.dart | 2 +- lib/src/spec/realtime/channels.dart | 2 +- lib/src/spec/realtime/realtime.dart | 2 +- lib/src/spec/rest/ably_base.dart | 2 +- lib/src/spec/rest/channels.dart | 2 +- lib/src/spec/rest/options.dart | 2 +- 19 files changed, 19 insertions(+), 20 deletions(-) diff --git a/bin/templates/platformconstants.dart.dart b/bin/templates/platformconstants.dart.dart index f6118e183..4a4afced4 100644 --- a/bin/templates/platformconstants.dart.dart +++ b/bin/templates/platformconstants.dart.dart @@ -15,4 +15,4 @@ class Tx${_['name']}{ } ''';}).join('\n')} '''; -} \ No newline at end of file +} diff --git a/bin/templates/platformconstants.h.dart b/bin/templates/platformconstants.h.dart index 52b2cfed4..868cad5b3 100644 --- a/bin/templates/platformconstants.h.dart +++ b/bin/templates/platformconstants.h.dart @@ -18,4 +18,4 @@ ${_['properties'].map((_) => '@property (class, nonatomic, assign, readonly) NSS @end '''; }).join('\n')}'''; -} \ No newline at end of file +} diff --git a/bin/templates/platformconstants.m.dart b/bin/templates/platformconstants.m.dart index 5217b76e0..335d37ffe 100644 --- a/bin/templates/platformconstants.m.dart +++ b/bin/templates/platformconstants.m.dart @@ -15,4 +15,4 @@ ${_['properties'].map((_) => '+ (NSString*) ${_} { return @"${_}"; }').join('\n' @end '''; }).join('\n')}'''; -} \ No newline at end of file +} diff --git a/lib/src/impl/realtime/channels.dart b/lib/src/impl/realtime/channels.dart index 2404ac00b..fdab04c01 100644 --- a/lib/src/impl/realtime/channels.dart +++ b/lib/src/impl/realtime/channels.dart @@ -124,4 +124,4 @@ class RealtimePlatformChannels extends spec.RealtimeChannels{ return RestPlatformChannel(ablyHandle, ablyPlugin, restHandle, ably, name, options); } -} \ No newline at end of file +} diff --git a/lib/src/impl/rest/rest.dart b/lib/src/impl/rest/rest.dart index ff4c46eb9..e33da84db 100644 --- a/lib/src/impl/rest/rest.dart +++ b/lib/src/impl/rest/rest.dart @@ -47,4 +47,4 @@ class RestPlatformObject extends PlatformObject implements spec.Rest { // TODO: implement release } -} \ No newline at end of file +} diff --git a/lib/src/spec/connection.dart b/lib/src/spec/connection.dart index f60de6a98..71bc1a6b8 100644 --- a/lib/src/spec/connection.dart +++ b/lib/src/spec/connection.dart @@ -28,4 +28,4 @@ abstract class Connection implements EventEmitter ping(); -} \ No newline at end of file +} diff --git a/lib/src/spec/enums.dart b/lib/src/spec/enums.dart index f722a4db6..eb5fce972 100644 --- a/lib/src/spec/enums.dart +++ b/lib/src/spec/enums.dart @@ -97,4 +97,4 @@ enum FormFactor{ car, embedded, other -} \ No newline at end of file +} diff --git a/lib/src/spec/message.dart b/lib/src/spec/message.dart index d042c8d05..94c4d015d 100644 --- a/lib/src/spec/message.dart +++ b/lib/src/spec/message.dart @@ -36,4 +36,4 @@ abstract class PresenceMessage { abstract class PresenceMessageStatic { //TODO why is this class required? PresenceMessageStatic.fromEncoded(Map jsonObject, ChannelOptions channelOptions); PresenceMessageStatic.fromEncodedArray(List jsonArray, ChannelOptions channelOptions); -} \ No newline at end of file +} diff --git a/lib/src/spec/push/channels.dart b/lib/src/spec/push/channels.dart index d585f3eeb..63863f846 100644 --- a/lib/src/spec/push/channels.dart +++ b/lib/src/spec/push/channels.dart @@ -6,4 +6,4 @@ abstract class PushChannel{ Future unsubscribeDevice(); // RSH7c Future unsubscribeClient(); // RSH7d Future> listSubscriptions(); // RSH7e -} \ No newline at end of file +} diff --git a/lib/src/spec/realtime/channels.dart b/lib/src/spec/realtime/channels.dart index b8f4a255d..23a1f731c 100644 --- a/lib/src/spec/realtime/channels.dart +++ b/lib/src/spec/realtime/channels.dart @@ -52,4 +52,4 @@ abstract class RealtimeChannels extends Channels { RealtimeChannels(AblyBase ably): super(ably); -} \ No newline at end of file +} diff --git a/lib/src/spec/realtime/realtime.dart b/lib/src/spec/realtime/realtime.dart index 4861350a5..dee810e13 100644 --- a/lib/src/spec/realtime/realtime.dart +++ b/lib/src/spec/realtime/realtime.dart @@ -18,4 +18,4 @@ abstract class Realtime extends AblyBase { final Connection connection; RealtimeChannels channels; -} \ No newline at end of file +} diff --git a/lib/src/spec/rest/ably_base.dart b/lib/src/spec/rest/ably_base.dart index ca972bd56..1e3a4249d 100644 --- a/lib/src/spec/rest/ably_base.dart +++ b/lib/src/spec/rest/ably_base.dart @@ -36,4 +36,4 @@ abstract class AblyBase { Map headers }); Future time(); -} \ No newline at end of file +} diff --git a/lib/src/spec/rest/channels.dart b/lib/src/spec/rest/channels.dart index 21f945ece..bcbb7076a 100644 --- a/lib/src/spec/rest/channels.dart +++ b/lib/src/spec/rest/channels.dart @@ -29,4 +29,4 @@ abstract class RestChannels extends Channels { RestChannels(ably) : super(ably); -} \ No newline at end of file +} diff --git a/lib/src/spec/rest/options.dart b/lib/src/spec/rest/options.dart index 31524290a..5339fe713 100644 --- a/lib/src/spec/rest/options.dart +++ b/lib/src/spec/rest/options.dart @@ -119,4 +119,4 @@ class ClientOptions extends AuthOptions { int realtimeRequestTimeout; int fallbackRetryTimeout; int channelRetryTimeout; -} \ No newline at end of file +} From 106c66812935dc68f256a9fb256a926481c1f9e6 Mon Sep 17 00:00:00 2001 From: "Rohit R. Abbadi" Date: Fri, 5 Jun 2020 09:31:36 +0530 Subject: [PATCH 12/19] Cleanup - remove usage of abbreviations gen -> generated https://github.com/ably/ably-flutter/pull/13/files#r434369291 - remove commented code (will be re-implemented while working on channel events) https://github.com/ably/ably-flutter/pull/13/files#r434372985 - make Java static classes final https://github.com/ably/ably-flutter/pull/13/files#r434373812 --- .../plugin/AblyEventStreamHandler.java | 18 ++------------ .../ably/flutter/plugin/AblyMessageCodec.java | 2 +- .../flutter/plugin/AblyMethodCallHandler.java | 2 +- .../{gen => generated}/PlatformConstants.java | 24 +++++++++---------- bin/codegen.dart | 4 ++-- bin/templates/platformconstants.java.dart | 10 ++++---- lib/ably.dart | 2 +- lib/src/ably_implementation.dart | 2 +- lib/src/codec.dart | 2 +- .../{gen => generated}/platformconstants.dart | 0 10 files changed, 26 insertions(+), 40 deletions(-) rename android/src/main/java/io/ably/flutter/plugin/{gen => generated}/PlatformConstants.java (91%) rename lib/src/{gen => generated}/platformconstants.dart (100%) diff --git a/android/src/main/java/io/ably/flutter/plugin/AblyEventStreamHandler.java b/android/src/main/java/io/ably/flutter/plugin/AblyEventStreamHandler.java index a4dc0b812..b637e09a7 100644 --- a/android/src/main/java/io/ably/flutter/plugin/AblyEventStreamHandler.java +++ b/android/src/main/java/io/ably/flutter/plugin/AblyEventStreamHandler.java @@ -3,7 +3,7 @@ import android.os.Handler; import android.os.Looper; -import io.ably.flutter.plugin.gen.PlatformConstants; +import io.ably.flutter.plugin.generated.PlatformConstants; import io.ably.lib.realtime.ChannelStateListener; import io.ably.lib.realtime.ConnectionStateListener; import io.flutter.plugin.common.EventChannel; @@ -50,14 +50,11 @@ public void error(final String s, final String s1, final Object o) { } @Override - public void endOfStream() { - //TODO work on this if required, or remove this TODO once all features are covered - } + public void endOfStream() {} } // Listeners private PluginConnectionStateListener connectionStateListener; - private PluginChannelStateListener channelStateListener; private class Listener{ EventChannel.EventSink eventSink; @@ -71,13 +68,6 @@ public void onConnectionStateChanged(ConnectionStateChange stateChange){ } } - private class PluginChannelStateListener extends Listener implements ChannelStateListener { - PluginChannelStateListener(EventChannel.EventSink eventSink){super(eventSink);} - public void onChannelStateChanged(io.ably.lib.realtime.ChannelStateListener.ChannelStateChange stateChange){ - eventSink.success(stateChange); - } - } - @Override public void onListen(Object object, EventChannel.EventSink uiThreadEventSink) { MainThreadEventSink eventSink = new MainThreadEventSink(uiThreadEventSink); @@ -88,10 +78,6 @@ public void onListen(Object object, EventChannel.EventSink uiThreadEventSink) { connectionStateListener = new PluginConnectionStateListener(eventSink); ablyLibrary.getRealtime(message.handle).connection.on(connectionStateListener); return; - case PlatformConstants.PlatformMethod.onRealtimeChannelStateChanged: - // channelStateListener = new PluginChannelStateListener(eventSink); - // ablyLibrary.getRealtime(message.handle).connection.on(channelStateListener); - // return; default: eventSink.error("unhandled event", null, null); } diff --git a/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java b/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java index 7d1ca955e..23950bb00 100644 --- a/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java +++ b/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java @@ -6,7 +6,7 @@ import java.util.Map; import java.util.function.Consumer; -import io.ably.flutter.plugin.gen.PlatformConstants; +import io.ably.flutter.plugin.generated.PlatformConstants; import io.ably.lib.realtime.ChannelStateListener; import io.ably.lib.realtime.ConnectionStateListener; import io.ably.lib.rest.Auth; diff --git a/android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java b/android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java index 2e15e6e0a..eabeb5424 100644 --- a/android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java +++ b/android/src/main/java/io/ably/flutter/plugin/AblyMethodCallHandler.java @@ -16,7 +16,7 @@ import io.ably.lib.types.ErrorInfo; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; -import io.ably.flutter.plugin.gen.PlatformConstants; +import io.ably.flutter.plugin.generated.PlatformConstants; public class AblyMethodCallHandler implements MethodChannel.MethodCallHandler { private static AblyMethodCallHandler _instance; diff --git a/android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java b/android/src/main/java/io/ably/flutter/plugin/generated/PlatformConstants.java similarity index 91% rename from android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java rename to android/src/main/java/io/ably/flutter/plugin/generated/PlatformConstants.java index de8a5b3f9..5900bcfe9 100644 --- a/android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java +++ b/android/src/main/java/io/ably/flutter/plugin/generated/PlatformConstants.java @@ -3,12 +3,12 @@ // source file can be found at bin/templates' // -package io.ably.flutter.plugin.gen; +package io.ably.flutter.plugin.generated; -public class PlatformConstants{ +final public class PlatformConstants{ - public class CodecTypes { + final public class CodecTypes { public static final byte ablyMessage = (byte)128; public static final byte clientOptions = (byte)129; public static final byte errorInfo = (byte)144; @@ -16,7 +16,7 @@ public class CodecTypes { public static final byte channelStateChange = (byte)202; } - public class PlatformMethod { + final public class PlatformMethod { public static final String getPlatformVersion = "getPlatformVersion"; public static final String getVersion = "getVersion"; public static final String registerAbly = "registerAbly"; @@ -28,13 +28,13 @@ public class PlatformMethod { public static final String onRealtimeConnectionStateChanged = "onRealtimeConnectionStateChanged"; public static final String onRealtimeChannelStateChanged = "onRealtimeChannelStateChanged"; } - - public class TxAblyMessage{ + + final public class TxAblyMessage{ public static final String registrationHandle = "registrationHandle"; public static final String type = "type"; public static final String message = "message"; } - public class TxErrorInfo{ + final public class TxErrorInfo{ public static final String code = "code"; public static final String message = "message"; public static final String statusCode = "statusCode"; @@ -42,7 +42,7 @@ public class TxErrorInfo{ public static final String requestId = "requestId"; public static final String cause = "cause"; } - public class TxClientOptions{ + final public class TxClientOptions{ public static final String authUrl = "authUrl"; public static final String authMethod = "authMethod"; public static final String key = "key"; @@ -76,28 +76,28 @@ public class TxClientOptions{ public static final String channelRetryTimeout = "channelRetryTimeout"; public static final String transportParams = "transportParams"; } - public class TxTokenDetails{ + final public class TxTokenDetails{ public static final String token = "token"; public static final String expires = "expires"; public static final String issued = "issued"; public static final String capability = "capability"; public static final String clientId = "clientId"; } - public class TxTokenParams{ + final public class TxTokenParams{ public static final String capability = "capability"; public static final String clientId = "clientId"; public static final String nonce = "nonce"; public static final String timestamp = "timestamp"; public static final String ttl = "ttl"; } - public class TxConnectionStateChange{ + final public class TxConnectionStateChange{ public static final String current = "current"; public static final String previous = "previous"; public static final String event = "event"; public static final String retryIn = "retryIn"; public static final String reason = "reason"; } - public class TxChannelStateChange{ + final public class TxChannelStateChange{ public static final String current = "current"; public static final String previous = "previous"; public static final String event = "event"; diff --git a/bin/codegen.dart b/bin/codegen.dart index 4725ab2e1..6165037b2 100644 --- a/bin/codegen.dart +++ b/bin/codegen.dart @@ -12,8 +12,8 @@ String projectRoot = "../"; Map toGenerate = { // input template method vs output file path - dart_template.$: "${projectRoot}lib/src/gen/platformconstants.dart", - java_template.$: "${projectRoot}android/src/main/java/io/ably/flutter/plugin/gen/PlatformConstants.java", + dart_template.$: "${projectRoot}lib/src/generated/platformconstants.dart", + java_template.$: "${projectRoot}android/src/main/java/io/ably/flutter/plugin/generated/PlatformConstants.java", objc_header_template.$: "${projectRoot}ios/Classes/codec/AblyPlatformConstants.h", objc_impl_template.$: "${projectRoot}ios/Classes/codec/AblyPlatformConstants.m", }; diff --git a/bin/templates/platformconstants.java.dart b/bin/templates/platformconstants.java.dart index 832946e67..109f0f983 100644 --- a/bin/templates/platformconstants.java.dart +++ b/bin/templates/platformconstants.java.dart @@ -1,21 +1,21 @@ String $(c) { return ''' -package io.ably.flutter.plugin.gen; +package io.ably.flutter.plugin.generated; -public class PlatformConstants{ +final public class PlatformConstants{ - public class CodecTypes { + final public class CodecTypes { ${c['types'].map((_) => 'public static final byte ${_['name']} = (byte)${_['value']};').join('\n\t')} } - public class PlatformMethod { + final public class PlatformMethod { ${c['methods'].map((_) => 'public static final String ${_['name']} = "${_['value']}";').join('\n\t')} } ${c['objects'].map((_) { return ''' - public class Tx${_['name']}{ + final public class Tx${_['name']}{ ${_['properties'].map((_p) => 'public static final String ${_p} = "${_p}";').join('\n\t')} }'''; }).join('\n')} diff --git a/lib/ably.dart b/lib/ably.dart index fa663c1db..aae000b7b 100644 --- a/lib/ably.dart +++ b/lib/ably.dart @@ -1,4 +1,4 @@ export 'src/interface.dart'; export 'src/defaults.dart'; export 'src/spec/spec.dart'; -export 'src/gen/platformconstants.dart'; +export 'src/generated/platformconstants.dart'; diff --git a/lib/src/ably_implementation.dart b/lib/src/ably_implementation.dart index f0a51d807..6a4872e8b 100644 --- a/lib/src/ably_implementation.dart +++ b/lib/src/ably_implementation.dart @@ -3,7 +3,7 @@ import 'dart:async'; import 'package:ably_flutter_plugin/src/impl/message.dart'; import 'package:ably_flutter_plugin/src/interface.dart'; import 'package:flutter/services.dart'; -import 'package:ably_flutter_plugin/src/gen/platformconstants.dart' show PlatformMethod; +import 'package:ably_flutter_plugin/src/generated/platformconstants.dart' show PlatformMethod; import 'package:streams_channel/streams_channel.dart'; import '../ably.dart'; import 'codec.dart'; diff --git a/lib/src/codec.dart b/lib/src/codec.dart index 48841cb45..b0431fef7 100644 --- a/lib/src/codec.dart +++ b/lib/src/codec.dart @@ -1,4 +1,4 @@ -import 'package:ably_flutter_plugin/src/gen/platformconstants.dart'; +import 'package:ably_flutter_plugin/src/generated/platformconstants.dart'; import 'package:ably_flutter_plugin/src/impl/message.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; diff --git a/lib/src/gen/platformconstants.dart b/lib/src/generated/platformconstants.dart similarity index 100% rename from lib/src/gen/platformconstants.dart rename to lib/src/generated/platformconstants.dart From f9269cbee8da186ffc0945d62e2e1217211a5ff5 Mon Sep 17 00:00:00 2001 From: "Rohit R. Abbadi" Date: Fri, 5 Jun 2020 12:03:52 +0530 Subject: [PATCH 13/19] cleanup java genereated code --- .../ably/flutter/plugin/generated/PlatformConstants.java | 9 ++++++++- bin/templates/platformconstants.java.dart | 3 ++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/android/src/main/java/io/ably/flutter/plugin/generated/PlatformConstants.java b/android/src/main/java/io/ably/flutter/plugin/generated/PlatformConstants.java index 5900bcfe9..7178f10d9 100644 --- a/android/src/main/java/io/ably/flutter/plugin/generated/PlatformConstants.java +++ b/android/src/main/java/io/ably/flutter/plugin/generated/PlatformConstants.java @@ -28,12 +28,13 @@ final public class PlatformMethod { public static final String onRealtimeConnectionStateChanged = "onRealtimeConnectionStateChanged"; public static final String onRealtimeChannelStateChanged = "onRealtimeChannelStateChanged"; } - + final public class TxAblyMessage{ public static final String registrationHandle = "registrationHandle"; public static final String type = "type"; public static final String message = "message"; } + final public class TxErrorInfo{ public static final String code = "code"; public static final String message = "message"; @@ -42,6 +43,7 @@ final public class TxErrorInfo{ public static final String requestId = "requestId"; public static final String cause = "cause"; } + final public class TxClientOptions{ public static final String authUrl = "authUrl"; public static final String authMethod = "authMethod"; @@ -76,6 +78,7 @@ final public class TxClientOptions{ public static final String channelRetryTimeout = "channelRetryTimeout"; public static final String transportParams = "transportParams"; } + final public class TxTokenDetails{ public static final String token = "token"; public static final String expires = "expires"; @@ -83,6 +86,7 @@ final public class TxTokenDetails{ public static final String capability = "capability"; public static final String clientId = "clientId"; } + final public class TxTokenParams{ public static final String capability = "capability"; public static final String clientId = "clientId"; @@ -90,6 +94,7 @@ final public class TxTokenParams{ public static final String timestamp = "timestamp"; public static final String ttl = "ttl"; } + final public class TxConnectionStateChange{ public static final String current = "current"; public static final String previous = "previous"; @@ -97,6 +102,7 @@ final public class TxConnectionStateChange{ public static final String retryIn = "retryIn"; public static final String reason = "reason"; } + final public class TxChannelStateChange{ public static final String current = "current"; public static final String previous = "previous"; @@ -104,4 +110,5 @@ final public class TxChannelStateChange{ public static final String resumed = "resumed"; public static final String reason = "reason"; } + } diff --git a/bin/templates/platformconstants.java.dart b/bin/templates/platformconstants.java.dart index 109f0f983..1c7117a35 100644 --- a/bin/templates/platformconstants.java.dart +++ b/bin/templates/platformconstants.java.dart @@ -17,7 +17,8 @@ ${c['objects'].map((_) { return ''' final public class Tx${_['name']}{ ${_['properties'].map((_p) => 'public static final String ${_p} = "${_p}";').join('\n\t')} - }'''; + } + '''; }).join('\n')} } '''; From 7321c659c3a5b2bb7a66ad84c5de3b97d1265d5f Mon Sep 17 00:00:00 2001 From: "Rohit R. Abbadi" Date: Fri, 5 Jun 2020 12:53:06 +0530 Subject: [PATCH 14/19] PR Comments related to ObjC and cleanup: - `@import Foundation;` https://github.com/ably/ably-flutter/pull/13/files#r434376328 https://github.com/ably/ably-flutter/pull/13/files#r434376097 - static externs instead of assigned properties https://github.com/ably/ably-flutter/pull/13/files#r434381831 - missing properties in platform libraries added to issue #14 https://github.com/ably/ably-flutter/pull/13/files#r434454731 --- .../ably/flutter/plugin/AblyMessageCodec.java | 8 +- bin/templates/platformconstants.h.dart | 6 +- bin/templates/platformconstants.m.dart | 5 +- example/ios/Runner.xcodeproj/project.pbxproj | 14 +- example/pubspec.lock | 24 +-- ios/Classes/AblyFlutterPlugin.m | 16 +- ios/Classes/AblyFlutterStreamHandler.m | 8 +- ios/Classes/codec/AblyFlutterReader.m | 92 +++++------ ios/Classes/codec/AblyFlutterWriter.m | 30 ++-- ios/Classes/codec/AblyPlatformConstants.h | 144 +++++++++--------- ios/Classes/codec/AblyPlatformConstants.m | 143 +++++++++-------- 11 files changed, 234 insertions(+), 256 deletions(-) diff --git a/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java b/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java index 23950bb00..e8d53aa8b 100644 --- a/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java +++ b/android/src/main/java/io/ably/flutter/plugin/AblyMessageCodec.java @@ -152,7 +152,7 @@ private ClientOptions readClientOptions(Map jsonMap) { readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.authHeaders, v -> o.authHeaders = (Param[])v); readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.authParams, v -> o.authParams = (Param[])v); readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.queryTime, v -> o.queryTime = (Boolean)v); -// readValueFromJson(buffer); // o.useAuthToken + readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.useTokenAuth, v -> o.useTokenAuth = (Boolean)v); // ClientOptions readValueFromJson(jsonMap, PlatformConstants.TxClientOptions.clientId, v -> o.clientId = (String)v); @@ -201,7 +201,8 @@ private Auth.TokenParams readTokenParams(Map jsonMap) { readValueFromJson(jsonMap, PlatformConstants.TxTokenParams.clientId, v -> o.clientId = (String)v); readValueFromJson(jsonMap, PlatformConstants.TxTokenParams.timestamp, v -> o.timestamp = (int)v); readValueFromJson(jsonMap, PlatformConstants.TxTokenParams.ttl, v -> o.ttl = (long)v); - //nonce is not supported in ably-java + // nonce is not supported in ably-java + // Track @ https://github.com/ably/ably-flutter/issues/14 return o; } @@ -216,7 +217,8 @@ private Map encodeErrorInfo(ErrorInfo c){ writeValueToJson(jsonMap, PlatformConstants.TxErrorInfo.message, c.message); writeValueToJson(jsonMap, PlatformConstants.TxErrorInfo.statusCode, c.statusCode); writeValueToJson(jsonMap, PlatformConstants.TxErrorInfo.href, c.href); - //requestId and cause - not available in ably-java + // requestId and cause - not available in ably-java + // track @ https://github.com/ably/ably-flutter/issues/14 return jsonMap; } diff --git a/bin/templates/platformconstants.h.dart b/bin/templates/platformconstants.h.dart index 868cad5b3..b5eb16d89 100644 --- a/bin/templates/platformconstants.h.dart +++ b/bin/templates/platformconstants.h.dart @@ -1,6 +1,6 @@ String $(c) { return ''' -#import +@import Foundation; typedef NS_ENUM(UInt8, _Value) { ${c['types'].map((_) => '${_['name']}CodecType = ${_['value']},').join('\n ')} @@ -8,13 +8,13 @@ typedef NS_ENUM(UInt8, _Value) { @interface AblyPlatformMethod : NSObject -${c['methods'].map((_) => '@property (class, nonatomic, assign, readonly) NSString *${_['name']};').join('\n')} +${c['methods'].map((_) => 'extern NSString *const AblyPlatformMethod_${_['name']};').join('\n')} @end ${c['objects'].map((_) { return ''' @interface Tx${_['name']} : NSObject -${_['properties'].map((_) => '@property (class, nonatomic, assign, readonly) NSString *${_};').join('\n')} +${_['properties'].map((name) => 'extern NSString *const Tx${_['name']}_${name};').join('\n')} @end '''; }).join('\n')}'''; diff --git a/bin/templates/platformconstants.m.dart b/bin/templates/platformconstants.m.dart index 335d37ffe..cd8ffcf18 100644 --- a/bin/templates/platformconstants.m.dart +++ b/bin/templates/platformconstants.m.dart @@ -1,17 +1,16 @@ String $(c) { return ''' -#import #import "AblyPlatformConstants.h" @implementation AblyPlatformMethod -${c['methods'].map((_) => '+ (NSString*) ${_['name']} { return @"${_['value']}"; }').join('\n')} +${c['methods'].map((_) => 'NSString *const AblyPlatformMethod_${_['name']}= @"${_['value']}";').join('\n')} @end ${c['objects'].map((_) { return ''' @implementation Tx${_['name']} -${_['properties'].map((_) => '+ (NSString*) ${_} { return @"${_}"; }').join('\n')} +${_['properties'].map((name) => 'NSString *const Tx${_['name']}_${name} = @"${name}";').join('\n')} @end '''; }).join('\n')}'''; diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj index 494525f02..c1474d95d 100644 --- a/example/ios/Runner.xcodeproj/project.pbxproj +++ b/example/ios/Runner.xcodeproj/project.pbxproj @@ -9,11 +9,7 @@ /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; - 3B80C3941E831B6300D905FE /* App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3B80C3931E831B6300D905FE /* App.framework */; }; - 3B80C3951E831B6300D905FE /* App.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 3B80C3931E831B6300D905FE /* App.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 5B20C6AD3D6ADBABD1A628C0 /* libPods-Runner.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5EC6C0963CF731849FD763A5 /* libPods-Runner.a */; }; - 9705A1C61CF904A100538489 /* Flutter.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9740EEBA1CF902C7004384FC /* Flutter.framework */; }; - 9705A1C71CF904A300538489 /* Flutter.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 9740EEBA1CF902C7004384FC /* Flutter.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 978B8F6F1D3862AE00F588F7 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */; }; 97C146F31CF9000F007C117D /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 97C146F21CF9000F007C117D /* main.m */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; @@ -28,8 +24,6 @@ dstPath = ""; dstSubfolderSpec = 10; files = ( - 3B80C3951E831B6300D905FE /* App.framework in Embed Frameworks */, - 9705A1C71CF904A300538489 /* Flutter.framework in Embed Frameworks */, ); name = "Embed Frameworks"; runOnlyForDeploymentPostprocessing = 0; @@ -41,7 +35,6 @@ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 3B80C3931E831B6300D905FE /* App.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = App.framework; path = Flutter/App.framework; sourceTree = ""; }; 5EC6C0963CF731849FD763A5 /* libPods-Runner.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Runner.a"; sourceTree = BUILT_PRODUCTS_DIR; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; 7AFFD8ED1D35381100E5BB4D /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; @@ -49,7 +42,6 @@ 8A321662A1A1009EAC96DCFE /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; - 9740EEBA1CF902C7004384FC /* Flutter.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Flutter.framework; path = Flutter/Flutter.framework; sourceTree = ""; }; 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; 97C146F21CF9000F007C117D /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; @@ -64,8 +56,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 9705A1C61CF904A100538489 /* Flutter.framework in Frameworks */, - 3B80C3941E831B6300D905FE /* App.framework in Frameworks */, 5B20C6AD3D6ADBABD1A628C0 /* libPods-Runner.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -86,9 +76,7 @@ 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( - 3B80C3931E831B6300D905FE /* App.framework */, 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, - 9740EEBA1CF902C7004384FC /* Flutter.framework */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, 9740EEB31CF90195004384FC /* Generated.xcconfig */, @@ -233,7 +221,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" thin"; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; diff --git a/example/pubspec.lock b/example/pubspec.lock index 996de5cc9..8f4d9ecbe 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -14,42 +14,42 @@ packages: name: archive url: "https://pub.dartlang.org" source: hosted - version: "2.0.11" + version: "2.0.13" args: dependency: transitive description: name: args url: "https://pub.dartlang.org" source: hosted - version: "1.5.2" + version: "1.6.0" async: dependency: transitive description: name: async url: "https://pub.dartlang.org" source: hosted - version: "2.4.0" + version: "2.4.1" boolean_selector: dependency: transitive description: name: boolean_selector url: "https://pub.dartlang.org" source: hosted - version: "1.0.5" + version: "2.0.0" charcode: dependency: transitive description: name: charcode url: "https://pub.dartlang.org" source: hosted - version: "1.1.2" + version: "1.1.3" collection: dependency: transitive description: name: collection url: "https://pub.dartlang.org" source: hosted - version: "1.14.11" + version: "1.14.12" convert: dependency: transitive description: @@ -63,7 +63,7 @@ packages: name: crypto url: "https://pub.dartlang.org" source: hosted - version: "2.1.3" + version: "2.1.4" cupertino_icons: dependency: "direct main" description: @@ -101,7 +101,7 @@ packages: name: image url: "https://pub.dartlang.org" source: hosted - version: "2.1.4" + version: "2.1.12" matcher: dependency: transitive description: @@ -143,7 +143,7 @@ packages: name: quiver url: "https://pub.dartlang.org" source: hosted - version: "2.0.5" + version: "2.1.3" sky_engine: dependency: transitive description: flutter @@ -155,7 +155,7 @@ packages: name: source_span url: "https://pub.dartlang.org" source: hosted - version: "1.5.5" + version: "1.7.0" stack_trace: dependency: transitive description: @@ -197,7 +197,7 @@ packages: name: test_api url: "https://pub.dartlang.org" source: hosted - version: "0.2.11" + version: "0.2.15" typed_data: dependency: transitive description: @@ -218,6 +218,6 @@ packages: name: xml url: "https://pub.dartlang.org" source: hosted - version: "3.5.0" + version: "3.6.1" sdks: dart: ">=2.6.0 <3.0.0" diff --git a/ios/Classes/AblyFlutterPlugin.m b/ios/Classes/AblyFlutterPlugin.m index 9a4027a4b..ce296a9c9 100644 --- a/ios/Classes/AblyFlutterPlugin.m +++ b/ios/Classes/AblyFlutterPlugin.m @@ -136,14 +136,14 @@ -(instancetype)initWithChannel:(FlutterMethodChannel *const)channel { } _handlers = @{ - AblyPlatformMethod.getPlatformVersion: _getPlatformVersion, - AblyPlatformMethod.getVersion: _getVersion, - AblyPlatformMethod.registerAbly: _register, - AblyPlatformMethod.createRestWithOptions: _createRestWithOptions, - AblyPlatformMethod.publish: _publishRestMessage, - AblyPlatformMethod.createRealtimeWithOptions: _createRealtimeWithOptions, - AblyPlatformMethod.connectRealtime: _connectRealtime, - AblyPlatformMethod.closeRealtime: _closeRealtime + AblyPlatformMethod_getPlatformVersion: _getPlatformVersion, + AblyPlatformMethod_getVersion: _getVersion, + AblyPlatformMethod_registerAbly: _register, + AblyPlatformMethod_createRestWithOptions: _createRestWithOptions, + AblyPlatformMethod_publish: _publishRestMessage, + AblyPlatformMethod_createRealtimeWithOptions: _createRealtimeWithOptions, + AblyPlatformMethod_connectRealtime: _connectRealtime, + AblyPlatformMethod_closeRealtime: _closeRealtime }; _nextRegistration = 1; diff --git a/ios/Classes/AblyFlutterStreamHandler.m b/ios/Classes/AblyFlutterStreamHandler.m index 37b7a869c..3dbb6a60d 100644 --- a/ios/Classes/AblyFlutterStreamHandler.m +++ b/ios/Classes/AblyFlutterStreamHandler.m @@ -31,11 +31,11 @@ - (void) startListening:(AblyFlutterMessage *const)message emitter:(FlutterEvent AblyFlutterMessage *const _message = message.message; NSString *const eventName = _message.message; - if([AblyPlatformMethod.onRealtimeConnectionStateChanged isEqual: eventName]) { + if([AblyPlatformMethod_onRealtimeConnectionStateChanged isEqual: eventName]) { listener = [[ably realtimeWithHandle: message.handle].connection on: ^(ARTConnectionStateChange * const stateChange) { emitter(stateChange); }]; - } else if([AblyPlatformMethod.onRealtimeChannelStateChanged isEqual: eventName]) { + } else if([AblyPlatformMethod_onRealtimeChannelStateChanged isEqual: eventName]) { } } @@ -45,9 +45,9 @@ - (void) cancelListening:(AblyFlutterMessage *const)message { AblyFlutterMessage *const _message = message.message; NSString *const eventName = _message.message; - if([AblyPlatformMethod.onRealtimeConnectionStateChanged isEqual: eventName]) { + if([AblyPlatformMethod_onRealtimeConnectionStateChanged isEqual: eventName]) { [[ably realtimeWithHandle: message.handle].connection off: listener]; - } else if([AblyPlatformMethod.onRealtimeChannelStateChanged isEqual: eventName]) { + } else if([AblyPlatformMethod_onRealtimeChannelStateChanged isEqual: eventName]) { } } diff --git a/ios/Classes/codec/AblyFlutterReader.m b/ios/Classes/codec/AblyFlutterReader.m index eaf582b1e..1368e29d3 100644 --- a/ios/Classes/codec/AblyFlutterReader.m +++ b/ios/Classes/codec/AblyFlutterReader.m @@ -45,12 +45,12 @@ -(id)readValueOfType:(const UInt8)type { } static AblyCodecDecoder readAblyFlutterMessage = ^AblyFlutterMessage*(NSDictionary *const jsonDict) { - AblyCodecDecoder decoder = [AblyFlutterReader getDecoder: [NSString stringWithFormat:@"%@", [jsonDict objectForKey:TxAblyMessage.type]]]; - id message = [jsonDict objectForKey:TxAblyMessage.message]; + AblyCodecDecoder decoder = [AblyFlutterReader getDecoder: [NSString stringWithFormat:@"%@", [jsonDict objectForKey:TxAblyMessage_type]]]; + id message = [jsonDict objectForKey:TxAblyMessage_message]; if(decoder){ message = decoder(message); } - return [[AblyFlutterMessage alloc] initWithHandle:[jsonDict objectForKey:TxAblyMessage.registrationHandle] message:message]; + return [[AblyFlutterMessage alloc] initWithHandle:[jsonDict objectForKey:TxAblyMessage_registrationHandle] message:message]; }; /** @@ -92,45 +92,37 @@ use an explicitly received null from Dart (manifesting this side as a nil id) ARTClientOptions *const o = [ARTClientOptions new]; // AuthOptions (super class of ClientOptions) - READ_VALUE(o, authUrl, jsonDict, TxClientOptions.authUrl); - READ_VALUE(o, authMethod, jsonDict, TxClientOptions.authMethod); - READ_VALUE(o, key, jsonDict, TxClientOptions.key); - ON_VALUE(^(const id value) { o.tokenDetails = [AblyFlutterReader readTokenDetails: value]; }, jsonDict, TxClientOptions.tokenDetails); - READ_VALUE(o, authHeaders, jsonDict, TxClientOptions.authHeaders); - READ_VALUE(o, authParams, jsonDict, TxClientOptions.authParams); - READ_VALUE(o, queryTime, jsonDict, TxClientOptions.queryTime); + READ_VALUE(o, authUrl, jsonDict, TxClientOptions_authUrl); + READ_VALUE(o, authMethod, jsonDict, TxClientOptions_authMethod); + READ_VALUE(o, key, jsonDict, TxClientOptions_key); + ON_VALUE(^(const id value) { o.tokenDetails = [AblyFlutterReader readTokenDetails: value]; }, jsonDict, TxClientOptions_tokenDetails); + READ_VALUE(o, authHeaders, jsonDict, TxClientOptions_authHeaders); + READ_VALUE(o, authParams, jsonDict, TxClientOptions_authParams); + READ_VALUE(o, queryTime, jsonDict, TxClientOptions_queryTime); // ClientOptions - READ_VALUE(o, clientId, jsonDict, TxClientOptions.clientId); - ON_VALUE(^(const id value) { o.logLevel = _logLevel(value); }, jsonDict, TxClientOptions.logLevel); - //TODO log handler - READ_VALUE(o, tls, jsonDict, TxClientOptions.tls); - READ_VALUE(o, restHost, jsonDict, TxClientOptions.restHost); - READ_VALUE(o, realtimeHost, jsonDict, TxClientOptions.realtimeHost); - READ_BOOL(o, autoConnect, jsonDict, TxClientOptions.autoConnect); - READ_VALUE(o, useBinaryProtocol, jsonDict, TxClientOptions.useBinaryProtocol); - READ_VALUE(o, queueMessages, jsonDict, TxClientOptions.queueMessages); - READ_VALUE(o, echoMessages, jsonDict, TxClientOptions.echoMessages); - READ_VALUE(o, recover, jsonDict, TxClientOptions.recover); - READ_VALUE(o, environment, jsonDict, TxClientOptions.environment); - READ_VALUE(o, idempotentRestPublishing, jsonDict, TxClientOptions.idempotentRestPublishing); - READ_VALUE(o, fallbackHosts, jsonDict, TxClientOptions.fallbackHosts); - READ_VALUE(o, fallbackHostsUseDefault, jsonDict, TxClientOptions.fallbackHostsUseDefault); - ON_VALUE(^(const id value) { o.defaultTokenParams = [AblyFlutterReader readTokenParams: value]; }, jsonDict, TxClientOptions.defaultTokenParams); - READ_VALUE(o, defaultTokenParams, jsonDict, TxClientOptions.defaultTokenParams); - //Following properties not supported by Objective C library - // READ_VALUE(o, useAuthToken); // property not found - // READ_VALUE(o, port); // NSInteger - // READ_VALUE(o, tlsPort); // NSInteger - // READ_VALUE(o, httpOpenTimeout); // NSTimeInterval - // READ_VALUE(o, httpRequestTimeout); // NSTimeInterval - // READ_VALUE(o, httpMaxRetryCount); // NSUInteger - // READ_VALUE(o, realtimeRequestTimeout); // NSTimeInterval - // READ_VALUE(o, fallbackRetryTimeout); // property not found - // READ_VALUE(o, channelRetryTimeout); // NSTimeInterval - // READ_VALUE(o, transportParams); // property not found - // READ_VALUE(o, asyncHttpThreadpoolSize); // property not found - // READ_VALUE(o, pushFullWait); + READ_VALUE(o, clientId, jsonDict, TxClientOptions_clientId); + ON_VALUE(^(const id value) { o.logLevel = _logLevel(value); }, jsonDict, TxClientOptions_logLevel); + // TODO log handler + READ_VALUE(o, tls, jsonDict, TxClientOptions_tls); + READ_VALUE(o, restHost, jsonDict, TxClientOptions_restHost); + READ_VALUE(o, realtimeHost, jsonDict, TxClientOptions_realtimeHost); + READ_BOOL(o, autoConnect, jsonDict, TxClientOptions_autoConnect); + READ_VALUE(o, useBinaryProtocol, jsonDict, TxClientOptions_useBinaryProtocol); + READ_VALUE(o, queueMessages, jsonDict, TxClientOptions_queueMessages); + READ_VALUE(o, echoMessages, jsonDict, TxClientOptions_echoMessages); + READ_VALUE(o, recover, jsonDict, TxClientOptions_recover); + READ_VALUE(o, environment, jsonDict, TxClientOptions_environment); + READ_VALUE(o, idempotentRestPublishing, jsonDict, TxClientOptions_idempotentRestPublishing); + READ_VALUE(o, fallbackHosts, jsonDict, TxClientOptions_fallbackHosts); + READ_VALUE(o, fallbackHostsUseDefault, jsonDict, TxClientOptions_fallbackHostsUseDefault); + ON_VALUE(^(const id value) { o.defaultTokenParams = [AblyFlutterReader readTokenParams: value]; }, jsonDict, TxClientOptions_defaultTokenParams); + READ_VALUE(o, defaultTokenParams, jsonDict, TxClientOptions_defaultTokenParams); + // Following properties not supported by Objective C library + // useAuthToken, port, tlsPort, httpOpenTimeout, httpRequestTimeout, + // httpMaxRetryCount, realtimeRequestTimeout, fallbackRetryTimeout, + // channelRetryTimeout, transportParams, asyncHttpThreadpoolSize, pushFullWait + // track @ https://github.com/ably/ably-flutter/issues/14 return o; }; @@ -142,11 +134,11 @@ +(ARTTokenDetails *)readTokenDetails: (NSDictionary *) jsonDict { __block NSString *capability = nil; __block NSString *clientId = nil; - ON_VALUE(^(const id value) { token = value; }, jsonDict, TxTokenDetails.token); - ON_VALUE(^(const id value) { expires = value; }, jsonDict, TxTokenDetails.expires); - ON_VALUE(^(const id value) { issued = value; }, jsonDict, TxTokenDetails.issued); - ON_VALUE(^(const id value) { capability = value; }, jsonDict, TxTokenDetails.capability); - ON_VALUE(^(const id value) { clientId = value; }, jsonDict, TxTokenDetails.clientId); + ON_VALUE(^(const id value) { token = value; }, jsonDict, TxTokenDetails_token); + ON_VALUE(^(const id value) { expires = value; }, jsonDict, TxTokenDetails_expires); + ON_VALUE(^(const id value) { issued = value; }, jsonDict, TxTokenDetails_issued); + ON_VALUE(^(const id value) { capability = value; }, jsonDict, TxTokenDetails_capability); + ON_VALUE(^(const id value) { clientId = value; }, jsonDict, TxTokenDetails_clientId); ARTTokenDetails *const o = [ARTTokenDetails new]; [o initWithToken:token expires:expires issued:issued capability:capability clientId:clientId]; @@ -157,14 +149,14 @@ +(ARTTokenParams *)readTokenParams: (NSDictionary *) jsonDict { __block NSString *clientId = nil; __block NSString *nonce = nil; - ON_VALUE(^(const id value) { clientId = value; }, jsonDict, TxTokenParams.clientId); - ON_VALUE(^(const id value) { nonce = value; }, jsonDict, TxTokenParams.nonce); + ON_VALUE(^(const id value) { clientId = value; }, jsonDict, TxTokenParams_clientId); + ON_VALUE(^(const id value) { nonce = value; }, jsonDict, TxTokenParams_nonce); ARTTokenParams *const o = [ARTTokenParams new]; [o initWithClientId: clientId nonce: nonce]; - READ_VALUE(o, ttl, jsonDict, TxTokenParams.ttl); - READ_VALUE(o, capability, jsonDict, TxTokenParams.capability); - READ_VALUE(o, timestamp, jsonDict, TxTokenParams.timestamp); + READ_VALUE(o, ttl, jsonDict, TxTokenParams_ttl); + READ_VALUE(o, capability, jsonDict, TxTokenParams_capability); + READ_VALUE(o, timestamp, jsonDict, TxTokenParams_timestamp); return o; } diff --git a/ios/Classes/codec/AblyFlutterWriter.m b/ios/Classes/codec/AblyFlutterWriter.m index d2f4a9d28..6e07667cb 100644 --- a/ios/Classes/codec/AblyFlutterWriter.m +++ b/ios/Classes/codec/AblyFlutterWriter.m @@ -39,32 +39,30 @@ - (void)writeValue:(id)value { - (NSMutableDictionary *) encodeErrorInfo:(ARTErrorInfo *const) e{ NSMutableDictionary *jsonDict; - WRITE_VALUE(jsonDict, TxErrorInfo.message, [e message]); - WRITE_VALUE(jsonDict, TxErrorInfo.statusCode, @([e statusCode])); - //code - not available in ably-cocoa - //href - not available in ably-cocoa - //requestId - not available in ably-cocoa - //cause - not available in ably-cocoa + WRITE_VALUE(jsonDict, TxErrorInfo_message, [e message]); + WRITE_VALUE(jsonDict, TxErrorInfo_statusCode, @([e statusCode])); + // code, href, requestId and cause - not available in ably-cocoa + // track @ https://github.com/ably/ably-flutter/issues/14 return jsonDict; } - (NSDictionary *) encodeConnectionStateChange:(ARTConnectionStateChange *const) stateChange{ NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init]; - WRITE_ENUM(jsonDict, TxConnectionStateChange.current, [stateChange current]); - WRITE_ENUM(jsonDict, TxConnectionStateChange.previous, [stateChange previous]); - WRITE_ENUM(jsonDict, TxConnectionStateChange.event, [stateChange event]); - WRITE_VALUE(jsonDict, TxConnectionStateChange.retryIn, @((int)([stateChange retryIn] * 1000))); - WRITE_VALUE(jsonDict, TxConnectionStateChange.reason, [self encodeErrorInfo: [stateChange reason]]); + WRITE_ENUM(jsonDict, TxConnectionStateChange_current, [stateChange current]); + WRITE_ENUM(jsonDict, TxConnectionStateChange_previous, [stateChange previous]); + WRITE_ENUM(jsonDict, TxConnectionStateChange_event, [stateChange event]); + WRITE_VALUE(jsonDict, TxConnectionStateChange_retryIn, @((int)([stateChange retryIn] * 1000))); + WRITE_VALUE(jsonDict, TxConnectionStateChange_reason, [self encodeErrorInfo: [stateChange reason]]); return jsonDict; } - (NSDictionary *) encodeChannelStateChange:(ARTChannelStateChange *const) stateChange{ NSMutableDictionary *jsonDict; - WRITE_ENUM(jsonDict, TxChannelStateChange.current, [stateChange current]); - WRITE_ENUM(jsonDict, TxChannelStateChange.previous, [stateChange previous]); - WRITE_ENUM(jsonDict, TxChannelStateChange.event, [stateChange event]); - WRITE_VALUE(jsonDict, TxChannelStateChange.resumed, @([stateChange resumed])); - WRITE_VALUE(jsonDict, TxChannelStateChange.reason, [self encodeErrorInfo: [stateChange reason]]); + WRITE_ENUM(jsonDict, TxChannelStateChange_current, [stateChange current]); + WRITE_ENUM(jsonDict, TxChannelStateChange_previous, [stateChange previous]); + WRITE_ENUM(jsonDict, TxChannelStateChange_event, [stateChange event]); + WRITE_VALUE(jsonDict, TxChannelStateChange_resumed, @([stateChange resumed])); + WRITE_VALUE(jsonDict, TxChannelStateChange_reason, [self encodeErrorInfo: [stateChange reason]]); return jsonDict; } diff --git a/ios/Classes/codec/AblyPlatformConstants.h b/ios/Classes/codec/AblyPlatformConstants.h index c483e810c..4fb8df1b9 100644 --- a/ios/Classes/codec/AblyPlatformConstants.h +++ b/ios/Classes/codec/AblyPlatformConstants.h @@ -3,7 +3,7 @@ // source file can be found at bin/templates' // -#import +@import Foundation; typedef NS_ENUM(UInt8, _Value) { ablyMessageCodecType = 128, @@ -15,96 +15,96 @@ typedef NS_ENUM(UInt8, _Value) { @interface AblyPlatformMethod : NSObject -@property (class, nonatomic, assign, readonly) NSString *getPlatformVersion; -@property (class, nonatomic, assign, readonly) NSString *getVersion; -@property (class, nonatomic, assign, readonly) NSString *registerAbly; -@property (class, nonatomic, assign, readonly) NSString *createRestWithOptions; -@property (class, nonatomic, assign, readonly) NSString *publish; -@property (class, nonatomic, assign, readonly) NSString *createRealtimeWithOptions; -@property (class, nonatomic, assign, readonly) NSString *connectRealtime; -@property (class, nonatomic, assign, readonly) NSString *closeRealtime; -@property (class, nonatomic, assign, readonly) NSString *onRealtimeConnectionStateChanged; -@property (class, nonatomic, assign, readonly) NSString *onRealtimeChannelStateChanged; +extern NSString *const AblyPlatformMethod_getPlatformVersion; +extern NSString *const AblyPlatformMethod_getVersion; +extern NSString *const AblyPlatformMethod_registerAbly; +extern NSString *const AblyPlatformMethod_createRestWithOptions; +extern NSString *const AblyPlatformMethod_publish; +extern NSString *const AblyPlatformMethod_createRealtimeWithOptions; +extern NSString *const AblyPlatformMethod_connectRealtime; +extern NSString *const AblyPlatformMethod_closeRealtime; +extern NSString *const AblyPlatformMethod_onRealtimeConnectionStateChanged; +extern NSString *const AblyPlatformMethod_onRealtimeChannelStateChanged; @end @interface TxAblyMessage : NSObject -@property (class, nonatomic, assign, readonly) NSString *registrationHandle; -@property (class, nonatomic, assign, readonly) NSString *type; -@property (class, nonatomic, assign, readonly) NSString *message; +extern NSString *const TxAblyMessage_registrationHandle; +extern NSString *const TxAblyMessage_type; +extern NSString *const TxAblyMessage_message; @end @interface TxErrorInfo : NSObject -@property (class, nonatomic, assign, readonly) NSString *code; -@property (class, nonatomic, assign, readonly) NSString *message; -@property (class, nonatomic, assign, readonly) NSString *statusCode; -@property (class, nonatomic, assign, readonly) NSString *href; -@property (class, nonatomic, assign, readonly) NSString *requestId; -@property (class, nonatomic, assign, readonly) NSString *cause; +extern NSString *const TxErrorInfo_code; +extern NSString *const TxErrorInfo_message; +extern NSString *const TxErrorInfo_statusCode; +extern NSString *const TxErrorInfo_href; +extern NSString *const TxErrorInfo_requestId; +extern NSString *const TxErrorInfo_cause; @end @interface TxClientOptions : NSObject -@property (class, nonatomic, assign, readonly) NSString *authUrl; -@property (class, nonatomic, assign, readonly) NSString *authMethod; -@property (class, nonatomic, assign, readonly) NSString *key; -@property (class, nonatomic, assign, readonly) NSString *tokenDetails; -@property (class, nonatomic, assign, readonly) NSString *authHeaders; -@property (class, nonatomic, assign, readonly) NSString *authParams; -@property (class, nonatomic, assign, readonly) NSString *queryTime; -@property (class, nonatomic, assign, readonly) NSString *useTokenAuth; -@property (class, nonatomic, assign, readonly) NSString *clientId; -@property (class, nonatomic, assign, readonly) NSString *logLevel; -@property (class, nonatomic, assign, readonly) NSString *tls; -@property (class, nonatomic, assign, readonly) NSString *restHost; -@property (class, nonatomic, assign, readonly) NSString *realtimeHost; -@property (class, nonatomic, assign, readonly) NSString *port; -@property (class, nonatomic, assign, readonly) NSString *tlsPort; -@property (class, nonatomic, assign, readonly) NSString *autoConnect; -@property (class, nonatomic, assign, readonly) NSString *useBinaryProtocol; -@property (class, nonatomic, assign, readonly) NSString *queueMessages; -@property (class, nonatomic, assign, readonly) NSString *echoMessages; -@property (class, nonatomic, assign, readonly) NSString *recover; -@property (class, nonatomic, assign, readonly) NSString *environment; -@property (class, nonatomic, assign, readonly) NSString *idempotentRestPublishing; -@property (class, nonatomic, assign, readonly) NSString *httpOpenTimeout; -@property (class, nonatomic, assign, readonly) NSString *httpRequestTimeout; -@property (class, nonatomic, assign, readonly) NSString *httpMaxRetryCount; -@property (class, nonatomic, assign, readonly) NSString *realtimeRequestTimeout; -@property (class, nonatomic, assign, readonly) NSString *fallbackHosts; -@property (class, nonatomic, assign, readonly) NSString *fallbackHostsUseDefault; -@property (class, nonatomic, assign, readonly) NSString *fallbackRetryTimeout; -@property (class, nonatomic, assign, readonly) NSString *defaultTokenParams; -@property (class, nonatomic, assign, readonly) NSString *channelRetryTimeout; -@property (class, nonatomic, assign, readonly) NSString *transportParams; +extern NSString *const TxClientOptions_authUrl; +extern NSString *const TxClientOptions_authMethod; +extern NSString *const TxClientOptions_key; +extern NSString *const TxClientOptions_tokenDetails; +extern NSString *const TxClientOptions_authHeaders; +extern NSString *const TxClientOptions_authParams; +extern NSString *const TxClientOptions_queryTime; +extern NSString *const TxClientOptions_useTokenAuth; +extern NSString *const TxClientOptions_clientId; +extern NSString *const TxClientOptions_logLevel; +extern NSString *const TxClientOptions_tls; +extern NSString *const TxClientOptions_restHost; +extern NSString *const TxClientOptions_realtimeHost; +extern NSString *const TxClientOptions_port; +extern NSString *const TxClientOptions_tlsPort; +extern NSString *const TxClientOptions_autoConnect; +extern NSString *const TxClientOptions_useBinaryProtocol; +extern NSString *const TxClientOptions_queueMessages; +extern NSString *const TxClientOptions_echoMessages; +extern NSString *const TxClientOptions_recover; +extern NSString *const TxClientOptions_environment; +extern NSString *const TxClientOptions_idempotentRestPublishing; +extern NSString *const TxClientOptions_httpOpenTimeout; +extern NSString *const TxClientOptions_httpRequestTimeout; +extern NSString *const TxClientOptions_httpMaxRetryCount; +extern NSString *const TxClientOptions_realtimeRequestTimeout; +extern NSString *const TxClientOptions_fallbackHosts; +extern NSString *const TxClientOptions_fallbackHostsUseDefault; +extern NSString *const TxClientOptions_fallbackRetryTimeout; +extern NSString *const TxClientOptions_defaultTokenParams; +extern NSString *const TxClientOptions_channelRetryTimeout; +extern NSString *const TxClientOptions_transportParams; @end @interface TxTokenDetails : NSObject -@property (class, nonatomic, assign, readonly) NSString *token; -@property (class, nonatomic, assign, readonly) NSString *expires; -@property (class, nonatomic, assign, readonly) NSString *issued; -@property (class, nonatomic, assign, readonly) NSString *capability; -@property (class, nonatomic, assign, readonly) NSString *clientId; +extern NSString *const TxTokenDetails_token; +extern NSString *const TxTokenDetails_expires; +extern NSString *const TxTokenDetails_issued; +extern NSString *const TxTokenDetails_capability; +extern NSString *const TxTokenDetails_clientId; @end @interface TxTokenParams : NSObject -@property (class, nonatomic, assign, readonly) NSString *capability; -@property (class, nonatomic, assign, readonly) NSString *clientId; -@property (class, nonatomic, assign, readonly) NSString *nonce; -@property (class, nonatomic, assign, readonly) NSString *timestamp; -@property (class, nonatomic, assign, readonly) NSString *ttl; +extern NSString *const TxTokenParams_capability; +extern NSString *const TxTokenParams_clientId; +extern NSString *const TxTokenParams_nonce; +extern NSString *const TxTokenParams_timestamp; +extern NSString *const TxTokenParams_ttl; @end @interface TxConnectionStateChange : NSObject -@property (class, nonatomic, assign, readonly) NSString *current; -@property (class, nonatomic, assign, readonly) NSString *previous; -@property (class, nonatomic, assign, readonly) NSString *event; -@property (class, nonatomic, assign, readonly) NSString *retryIn; -@property (class, nonatomic, assign, readonly) NSString *reason; +extern NSString *const TxConnectionStateChange_current; +extern NSString *const TxConnectionStateChange_previous; +extern NSString *const TxConnectionStateChange_event; +extern NSString *const TxConnectionStateChange_retryIn; +extern NSString *const TxConnectionStateChange_reason; @end @interface TxChannelStateChange : NSObject -@property (class, nonatomic, assign, readonly) NSString *current; -@property (class, nonatomic, assign, readonly) NSString *previous; -@property (class, nonatomic, assign, readonly) NSString *event; -@property (class, nonatomic, assign, readonly) NSString *resumed; -@property (class, nonatomic, assign, readonly) NSString *reason; +extern NSString *const TxChannelStateChange_current; +extern NSString *const TxChannelStateChange_previous; +extern NSString *const TxChannelStateChange_event; +extern NSString *const TxChannelStateChange_resumed; +extern NSString *const TxChannelStateChange_reason; @end diff --git a/ios/Classes/codec/AblyPlatformConstants.m b/ios/Classes/codec/AblyPlatformConstants.m index 92fde5cc0..c6f60c31e 100644 --- a/ios/Classes/codec/AblyPlatformConstants.m +++ b/ios/Classes/codec/AblyPlatformConstants.m @@ -3,101 +3,100 @@ // source file can be found at bin/templates' // -#import #import "AblyPlatformConstants.h" @implementation AblyPlatformMethod -+ (NSString*) getPlatformVersion { return @"getPlatformVersion"; } -+ (NSString*) getVersion { return @"getVersion"; } -+ (NSString*) registerAbly { return @"registerAbly"; } -+ (NSString*) createRestWithOptions { return @"createRestWithOptions"; } -+ (NSString*) publish { return @"publish"; } -+ (NSString*) createRealtimeWithOptions { return @"createRealtimeWithOptions"; } -+ (NSString*) connectRealtime { return @"connectRealtime"; } -+ (NSString*) closeRealtime { return @"closeRealtime"; } -+ (NSString*) onRealtimeConnectionStateChanged { return @"onRealtimeConnectionStateChanged"; } -+ (NSString*) onRealtimeChannelStateChanged { return @"onRealtimeChannelStateChanged"; } +NSString *const AblyPlatformMethod_getPlatformVersion= @"getPlatformVersion"; +NSString *const AblyPlatformMethod_getVersion= @"getVersion"; +NSString *const AblyPlatformMethod_registerAbly= @"registerAbly"; +NSString *const AblyPlatformMethod_createRestWithOptions= @"createRestWithOptions"; +NSString *const AblyPlatformMethod_publish= @"publish"; +NSString *const AblyPlatformMethod_createRealtimeWithOptions= @"createRealtimeWithOptions"; +NSString *const AblyPlatformMethod_connectRealtime= @"connectRealtime"; +NSString *const AblyPlatformMethod_closeRealtime= @"closeRealtime"; +NSString *const AblyPlatformMethod_onRealtimeConnectionStateChanged= @"onRealtimeConnectionStateChanged"; +NSString *const AblyPlatformMethod_onRealtimeChannelStateChanged= @"onRealtimeChannelStateChanged"; @end @implementation TxAblyMessage -+ (NSString*) registrationHandle { return @"registrationHandle"; } -+ (NSString*) type { return @"type"; } -+ (NSString*) message { return @"message"; } +NSString *const TxAblyMessage_registrationHandle = @"registrationHandle"; +NSString *const TxAblyMessage_type = @"type"; +NSString *const TxAblyMessage_message = @"message"; @end @implementation TxErrorInfo -+ (NSString*) code { return @"code"; } -+ (NSString*) message { return @"message"; } -+ (NSString*) statusCode { return @"statusCode"; } -+ (NSString*) href { return @"href"; } -+ (NSString*) requestId { return @"requestId"; } -+ (NSString*) cause { return @"cause"; } +NSString *const TxErrorInfo_code = @"code"; +NSString *const TxErrorInfo_message = @"message"; +NSString *const TxErrorInfo_statusCode = @"statusCode"; +NSString *const TxErrorInfo_href = @"href"; +NSString *const TxErrorInfo_requestId = @"requestId"; +NSString *const TxErrorInfo_cause = @"cause"; @end @implementation TxClientOptions -+ (NSString*) authUrl { return @"authUrl"; } -+ (NSString*) authMethod { return @"authMethod"; } -+ (NSString*) key { return @"key"; } -+ (NSString*) tokenDetails { return @"tokenDetails"; } -+ (NSString*) authHeaders { return @"authHeaders"; } -+ (NSString*) authParams { return @"authParams"; } -+ (NSString*) queryTime { return @"queryTime"; } -+ (NSString*) useTokenAuth { return @"useTokenAuth"; } -+ (NSString*) clientId { return @"clientId"; } -+ (NSString*) logLevel { return @"logLevel"; } -+ (NSString*) tls { return @"tls"; } -+ (NSString*) restHost { return @"restHost"; } -+ (NSString*) realtimeHost { return @"realtimeHost"; } -+ (NSString*) port { return @"port"; } -+ (NSString*) tlsPort { return @"tlsPort"; } -+ (NSString*) autoConnect { return @"autoConnect"; } -+ (NSString*) useBinaryProtocol { return @"useBinaryProtocol"; } -+ (NSString*) queueMessages { return @"queueMessages"; } -+ (NSString*) echoMessages { return @"echoMessages"; } -+ (NSString*) recover { return @"recover"; } -+ (NSString*) environment { return @"environment"; } -+ (NSString*) idempotentRestPublishing { return @"idempotentRestPublishing"; } -+ (NSString*) httpOpenTimeout { return @"httpOpenTimeout"; } -+ (NSString*) httpRequestTimeout { return @"httpRequestTimeout"; } -+ (NSString*) httpMaxRetryCount { return @"httpMaxRetryCount"; } -+ (NSString*) realtimeRequestTimeout { return @"realtimeRequestTimeout"; } -+ (NSString*) fallbackHosts { return @"fallbackHosts"; } -+ (NSString*) fallbackHostsUseDefault { return @"fallbackHostsUseDefault"; } -+ (NSString*) fallbackRetryTimeout { return @"fallbackRetryTimeout"; } -+ (NSString*) defaultTokenParams { return @"defaultTokenParams"; } -+ (NSString*) channelRetryTimeout { return @"channelRetryTimeout"; } -+ (NSString*) transportParams { return @"transportParams"; } +NSString *const TxClientOptions_authUrl = @"authUrl"; +NSString *const TxClientOptions_authMethod = @"authMethod"; +NSString *const TxClientOptions_key = @"key"; +NSString *const TxClientOptions_tokenDetails = @"tokenDetails"; +NSString *const TxClientOptions_authHeaders = @"authHeaders"; +NSString *const TxClientOptions_authParams = @"authParams"; +NSString *const TxClientOptions_queryTime = @"queryTime"; +NSString *const TxClientOptions_useTokenAuth = @"useTokenAuth"; +NSString *const TxClientOptions_clientId = @"clientId"; +NSString *const TxClientOptions_logLevel = @"logLevel"; +NSString *const TxClientOptions_tls = @"tls"; +NSString *const TxClientOptions_restHost = @"restHost"; +NSString *const TxClientOptions_realtimeHost = @"realtimeHost"; +NSString *const TxClientOptions_port = @"port"; +NSString *const TxClientOptions_tlsPort = @"tlsPort"; +NSString *const TxClientOptions_autoConnect = @"autoConnect"; +NSString *const TxClientOptions_useBinaryProtocol = @"useBinaryProtocol"; +NSString *const TxClientOptions_queueMessages = @"queueMessages"; +NSString *const TxClientOptions_echoMessages = @"echoMessages"; +NSString *const TxClientOptions_recover = @"recover"; +NSString *const TxClientOptions_environment = @"environment"; +NSString *const TxClientOptions_idempotentRestPublishing = @"idempotentRestPublishing"; +NSString *const TxClientOptions_httpOpenTimeout = @"httpOpenTimeout"; +NSString *const TxClientOptions_httpRequestTimeout = @"httpRequestTimeout"; +NSString *const TxClientOptions_httpMaxRetryCount = @"httpMaxRetryCount"; +NSString *const TxClientOptions_realtimeRequestTimeout = @"realtimeRequestTimeout"; +NSString *const TxClientOptions_fallbackHosts = @"fallbackHosts"; +NSString *const TxClientOptions_fallbackHostsUseDefault = @"fallbackHostsUseDefault"; +NSString *const TxClientOptions_fallbackRetryTimeout = @"fallbackRetryTimeout"; +NSString *const TxClientOptions_defaultTokenParams = @"defaultTokenParams"; +NSString *const TxClientOptions_channelRetryTimeout = @"channelRetryTimeout"; +NSString *const TxClientOptions_transportParams = @"transportParams"; @end @implementation TxTokenDetails -+ (NSString*) token { return @"token"; } -+ (NSString*) expires { return @"expires"; } -+ (NSString*) issued { return @"issued"; } -+ (NSString*) capability { return @"capability"; } -+ (NSString*) clientId { return @"clientId"; } +NSString *const TxTokenDetails_token = @"token"; +NSString *const TxTokenDetails_expires = @"expires"; +NSString *const TxTokenDetails_issued = @"issued"; +NSString *const TxTokenDetails_capability = @"capability"; +NSString *const TxTokenDetails_clientId = @"clientId"; @end @implementation TxTokenParams -+ (NSString*) capability { return @"capability"; } -+ (NSString*) clientId { return @"clientId"; } -+ (NSString*) nonce { return @"nonce"; } -+ (NSString*) timestamp { return @"timestamp"; } -+ (NSString*) ttl { return @"ttl"; } +NSString *const TxTokenParams_capability = @"capability"; +NSString *const TxTokenParams_clientId = @"clientId"; +NSString *const TxTokenParams_nonce = @"nonce"; +NSString *const TxTokenParams_timestamp = @"timestamp"; +NSString *const TxTokenParams_ttl = @"ttl"; @end @implementation TxConnectionStateChange -+ (NSString*) current { return @"current"; } -+ (NSString*) previous { return @"previous"; } -+ (NSString*) event { return @"event"; } -+ (NSString*) retryIn { return @"retryIn"; } -+ (NSString*) reason { return @"reason"; } +NSString *const TxConnectionStateChange_current = @"current"; +NSString *const TxConnectionStateChange_previous = @"previous"; +NSString *const TxConnectionStateChange_event = @"event"; +NSString *const TxConnectionStateChange_retryIn = @"retryIn"; +NSString *const TxConnectionStateChange_reason = @"reason"; @end @implementation TxChannelStateChange -+ (NSString*) current { return @"current"; } -+ (NSString*) previous { return @"previous"; } -+ (NSString*) event { return @"event"; } -+ (NSString*) resumed { return @"resumed"; } -+ (NSString*) reason { return @"reason"; } +NSString *const TxChannelStateChange_current = @"current"; +NSString *const TxChannelStateChange_previous = @"previous"; +NSString *const TxChannelStateChange_event = @"event"; +NSString *const TxChannelStateChange_resumed = @"resumed"; +NSString *const TxChannelStateChange_reason = @"reason"; @end From 236bda287398595e6b4f3e2ebd2c6d4f370cffdb Mon Sep 17 00:00:00 2001 From: "Rohit R. Abbadi" Date: Fri, 5 Jun 2020 12:54:40 +0530 Subject: [PATCH 15/19] fixed improper indent in generated dart file --- bin/templates/platformconstants.dart.dart | 6 +++--- lib/src/generated/platformconstants.dart | 18 +++++++++--------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/bin/templates/platformconstants.dart.dart b/bin/templates/platformconstants.dart.dart index 4a4afced4..2747e5ba5 100644 --- a/bin/templates/platformconstants.dart.dart +++ b/bin/templates/platformconstants.dart.dart @@ -1,17 +1,17 @@ String $(c) { return ''' class CodecTypes{ - ${c['types'].map((_) => "static const int ${_['name']} = ${_['value']};").join('\n\t')} +\t${c['types'].map((_) => "static const int ${_['name']} = ${_['value']};").join('\n\t')} } class PlatformMethod { - ${c['methods'].map((_) => "static const String ${_['name']} = '${_['value']}';").join('\n\t')} +\t${c['methods'].map((_) => "static const String ${_['name']} = '${_['value']}';").join('\n\t')} } ${c['objects'].map((_) { return ''' class Tx${_['name']}{ - ${_['properties'].map((_p) => 'static const String ${_p} = "${_p}";').join('\n\t')} +\t${_['properties'].map((_p) => 'static const String ${_p} = "${_p}";').join('\n\t')} } ''';}).join('\n')} '''; diff --git a/lib/src/generated/platformconstants.dart b/lib/src/generated/platformconstants.dart index b29fcbf4b..24d801a7c 100644 --- a/lib/src/generated/platformconstants.dart +++ b/lib/src/generated/platformconstants.dart @@ -4,7 +4,7 @@ // class CodecTypes{ - static const int ablyMessage = 128; + static const int ablyMessage = 128; static const int clientOptions = 129; static const int errorInfo = 144; static const int connectionStateChange = 201; @@ -12,7 +12,7 @@ class CodecTypes{ } class PlatformMethod { - static const String getPlatformVersion = 'getPlatformVersion'; + static const String getPlatformVersion = 'getPlatformVersion'; static const String getVersion = 'getVersion'; static const String registerAbly = 'registerAbly'; static const String createRestWithOptions = 'createRestWithOptions'; @@ -25,13 +25,13 @@ class PlatformMethod { } class TxAblyMessage{ - static const String registrationHandle = "registrationHandle"; + static const String registrationHandle = "registrationHandle"; static const String type = "type"; static const String message = "message"; } class TxErrorInfo{ - static const String code = "code"; + static const String code = "code"; static const String message = "message"; static const String statusCode = "statusCode"; static const String href = "href"; @@ -40,7 +40,7 @@ class TxErrorInfo{ } class TxClientOptions{ - static const String authUrl = "authUrl"; + static const String authUrl = "authUrl"; static const String authMethod = "authMethod"; static const String key = "key"; static const String tokenDetails = "tokenDetails"; @@ -75,7 +75,7 @@ class TxClientOptions{ } class TxTokenDetails{ - static const String token = "token"; + static const String token = "token"; static const String expires = "expires"; static const String issued = "issued"; static const String capability = "capability"; @@ -83,7 +83,7 @@ class TxTokenDetails{ } class TxTokenParams{ - static const String capability = "capability"; + static const String capability = "capability"; static const String clientId = "clientId"; static const String nonce = "nonce"; static const String timestamp = "timestamp"; @@ -91,7 +91,7 @@ class TxTokenParams{ } class TxConnectionStateChange{ - static const String current = "current"; + static const String current = "current"; static const String previous = "previous"; static const String event = "event"; static const String retryIn = "retryIn"; @@ -99,7 +99,7 @@ class TxConnectionStateChange{ } class TxChannelStateChange{ - static const String current = "current"; + static const String current = "current"; static const String previous = "previous"; static const String event = "event"; static const String resumed = "resumed"; From b1c2b0ac235805f6c1dbea43ae53d107a9dc356e Mon Sep 17 00:00:00 2001 From: "Rohit R. Abbadi" Date: Fri, 5 Jun 2020 14:54:40 +0530 Subject: [PATCH 16/19] remove abbreviations `jsonDict -> dictionary` https://github.com/ably/ably-flutter/pull/13#discussion_r434382948 --- ios/Classes/codec/AblyFlutterReader.h | 4 +- ios/Classes/codec/AblyFlutterReader.m | 92 +++++++++++++-------------- ios/Classes/codec/AblyFlutterWriter.m | 44 ++++++------- 3 files changed, 70 insertions(+), 70 deletions(-) diff --git a/ios/Classes/codec/AblyFlutterReader.h b/ios/Classes/codec/AblyFlutterReader.h index 9b26bb570..0811630cb 100644 --- a/ios/Classes/codec/AblyFlutterReader.h +++ b/ios/Classes/codec/AblyFlutterReader.h @@ -8,8 +8,8 @@ NS_ASSUME_NONNULL_BEGIN @interface AblyFlutterReader : FlutterStandardReader -+(ARTTokenDetails *)readTokenDetails: (NSDictionary *) jsonDict; -+(ARTTokenParams *)readTokenParams: (NSDictionary *) jsonDict; ++(ARTTokenDetails *)tokenDetailsFromDictionary: (NSDictionary *) dictionary; ++(ARTTokenParams *)tokenParamsFromDictionary: (NSDictionary *) dictionary; @end diff --git a/ios/Classes/codec/AblyFlutterReader.m b/ios/Classes/codec/AblyFlutterReader.m index 1368e29d3..7f43fc7e9 100644 --- a/ios/Classes/codec/AblyFlutterReader.m +++ b/ios/Classes/codec/AblyFlutterReader.m @@ -44,13 +44,13 @@ -(id)readValueOfType:(const UInt8)type { } } -static AblyCodecDecoder readAblyFlutterMessage = ^AblyFlutterMessage*(NSDictionary *const jsonDict) { - AblyCodecDecoder decoder = [AblyFlutterReader getDecoder: [NSString stringWithFormat:@"%@", [jsonDict objectForKey:TxAblyMessage_type]]]; - id message = [jsonDict objectForKey:TxAblyMessage_message]; +static AblyCodecDecoder readAblyFlutterMessage = ^AblyFlutterMessage*(NSDictionary *const dictionary) { + AblyCodecDecoder decoder = [AblyFlutterReader getDecoder: [NSString stringWithFormat:@"%@", [dictionary objectForKey:TxAblyMessage_type]]]; + id message = [dictionary objectForKey:TxAblyMessage_message]; if(decoder){ message = decoder(message); } - return [[AblyFlutterMessage alloc] initWithHandle:[jsonDict objectForKey:TxAblyMessage_registrationHandle] message:message]; + return [[AblyFlutterMessage alloc] initWithHandle:[dictionary objectForKey:TxAblyMessage_registrationHandle] message:message]; }; /** @@ -70,54 +70,54 @@ use an explicitly received null from Dart (manifesting this side as a nil id) object (other than null) that indicates the Objective-C property value is to be set to an id value of nil. */ -#define ON_VALUE(BLOCK, JSON_DICT, JSON_KEY) { \ - const id value = [JSON_DICT objectForKey: JSON_KEY]; \ +#define ON_VALUE(BLOCK, DICTIONARY, JSON_KEY) { \ + const id value = [DICTIONARY objectForKey: JSON_KEY]; \ if (value) { \ BLOCK(value); \ } \ } -#define READ_VALUE(OBJECT, PROPERTY, JSON_DICT, JSON_KEY) { \ - ON_VALUE(^(const id value) { OBJECT.PROPERTY = value; }, JSON_DICT, JSON_KEY); \ +#define READ_VALUE(OBJECT, PROPERTY, DICTIONARY, JSON_KEY) { \ + ON_VALUE(^(const id value) { OBJECT.PROPERTY = value; }, DICTIONARY, JSON_KEY); \ } /** Where an NSNumber has been decoded and the property to be set is BOOL. */ -#define READ_BOOL(OBJECT, PROPERTY, JSON_DICT, JSON_KEY) { \ - ON_VALUE(^(const id number) { OBJECT.PROPERTY = [number boolValue]; }, JSON_DICT, JSON_KEY); \ +#define READ_BOOL(OBJECT, PROPERTY, DICTIONARY, JSON_KEY) { \ + ON_VALUE(^(const id number) { OBJECT.PROPERTY = [number boolValue]; }, DICTIONARY, JSON_KEY); \ } -static AblyCodecDecoder readClientOptions = ^AblyFlutterMessage*(NSDictionary *const jsonDict) { +static AblyCodecDecoder readClientOptions = ^AblyFlutterMessage*(NSDictionary *const dictionary) { ARTClientOptions *const o = [ARTClientOptions new]; // AuthOptions (super class of ClientOptions) - READ_VALUE(o, authUrl, jsonDict, TxClientOptions_authUrl); - READ_VALUE(o, authMethod, jsonDict, TxClientOptions_authMethod); - READ_VALUE(o, key, jsonDict, TxClientOptions_key); - ON_VALUE(^(const id value) { o.tokenDetails = [AblyFlutterReader readTokenDetails: value]; }, jsonDict, TxClientOptions_tokenDetails); - READ_VALUE(o, authHeaders, jsonDict, TxClientOptions_authHeaders); - READ_VALUE(o, authParams, jsonDict, TxClientOptions_authParams); - READ_VALUE(o, queryTime, jsonDict, TxClientOptions_queryTime); + READ_VALUE(o, authUrl, dictionary, TxClientOptions_authUrl); + READ_VALUE(o, authMethod, dictionary, TxClientOptions_authMethod); + READ_VALUE(o, key, dictionary, TxClientOptions_key); + ON_VALUE(^(const id value) { o.tokenDetails = [AblyFlutterReader tokenDetailsFromDictionary: value]; }, dictionary, TxClientOptions_tokenDetails); + READ_VALUE(o, authHeaders, dictionary, TxClientOptions_authHeaders); + READ_VALUE(o, authParams, dictionary, TxClientOptions_authParams); + READ_VALUE(o, queryTime, dictionary, TxClientOptions_queryTime); // ClientOptions - READ_VALUE(o, clientId, jsonDict, TxClientOptions_clientId); - ON_VALUE(^(const id value) { o.logLevel = _logLevel(value); }, jsonDict, TxClientOptions_logLevel); + READ_VALUE(o, clientId, dictionary, TxClientOptions_clientId); + ON_VALUE(^(const id value) { o.logLevel = _logLevel(value); }, dictionary, TxClientOptions_logLevel); // TODO log handler - READ_VALUE(o, tls, jsonDict, TxClientOptions_tls); - READ_VALUE(o, restHost, jsonDict, TxClientOptions_restHost); - READ_VALUE(o, realtimeHost, jsonDict, TxClientOptions_realtimeHost); - READ_BOOL(o, autoConnect, jsonDict, TxClientOptions_autoConnect); - READ_VALUE(o, useBinaryProtocol, jsonDict, TxClientOptions_useBinaryProtocol); - READ_VALUE(o, queueMessages, jsonDict, TxClientOptions_queueMessages); - READ_VALUE(o, echoMessages, jsonDict, TxClientOptions_echoMessages); - READ_VALUE(o, recover, jsonDict, TxClientOptions_recover); - READ_VALUE(o, environment, jsonDict, TxClientOptions_environment); - READ_VALUE(o, idempotentRestPublishing, jsonDict, TxClientOptions_idempotentRestPublishing); - READ_VALUE(o, fallbackHosts, jsonDict, TxClientOptions_fallbackHosts); - READ_VALUE(o, fallbackHostsUseDefault, jsonDict, TxClientOptions_fallbackHostsUseDefault); - ON_VALUE(^(const id value) { o.defaultTokenParams = [AblyFlutterReader readTokenParams: value]; }, jsonDict, TxClientOptions_defaultTokenParams); - READ_VALUE(o, defaultTokenParams, jsonDict, TxClientOptions_defaultTokenParams); + READ_VALUE(o, tls, dictionary, TxClientOptions_tls); + READ_VALUE(o, restHost, dictionary, TxClientOptions_restHost); + READ_VALUE(o, realtimeHost, dictionary, TxClientOptions_realtimeHost); + READ_BOOL(o, autoConnect, dictionary, TxClientOptions_autoConnect); + READ_VALUE(o, useBinaryProtocol, dictionary, TxClientOptions_useBinaryProtocol); + READ_VALUE(o, queueMessages, dictionary, TxClientOptions_queueMessages); + READ_VALUE(o, echoMessages, dictionary, TxClientOptions_echoMessages); + READ_VALUE(o, recover, dictionary, TxClientOptions_recover); + READ_VALUE(o, environment, dictionary, TxClientOptions_environment); + READ_VALUE(o, idempotentRestPublishing, dictionary, TxClientOptions_idempotentRestPublishing); + READ_VALUE(o, fallbackHosts, dictionary, TxClientOptions_fallbackHosts); + READ_VALUE(o, fallbackHostsUseDefault, dictionary, TxClientOptions_fallbackHostsUseDefault); + ON_VALUE(^(const id value) { o.defaultTokenParams = [AblyFlutterReader tokenParamsFromDictionary: value]; }, dictionary, TxClientOptions_defaultTokenParams); + READ_VALUE(o, defaultTokenParams, dictionary, TxClientOptions_defaultTokenParams); // Following properties not supported by Objective C library // useAuthToken, port, tlsPort, httpOpenTimeout, httpRequestTimeout, // httpMaxRetryCount, realtimeRequestTimeout, fallbackRetryTimeout, @@ -127,36 +127,36 @@ use an explicitly received null from Dart (manifesting this side as a nil id) return o; }; -+(ARTTokenDetails *)readTokenDetails: (NSDictionary *) jsonDict { ++(ARTTokenDetails *)tokenDetailsFromDictionary: (NSDictionary *) dictionary { __block NSString *token = nil; __block NSDate *expires = nil; __block NSDate *issued = nil; __block NSString *capability = nil; __block NSString *clientId = nil; - ON_VALUE(^(const id value) { token = value; }, jsonDict, TxTokenDetails_token); - ON_VALUE(^(const id value) { expires = value; }, jsonDict, TxTokenDetails_expires); - ON_VALUE(^(const id value) { issued = value; }, jsonDict, TxTokenDetails_issued); - ON_VALUE(^(const id value) { capability = value; }, jsonDict, TxTokenDetails_capability); - ON_VALUE(^(const id value) { clientId = value; }, jsonDict, TxTokenDetails_clientId); + ON_VALUE(^(const id value) { token = value; }, dictionary, TxTokenDetails_token); + ON_VALUE(^(const id value) { expires = value; }, dictionary, TxTokenDetails_expires); + ON_VALUE(^(const id value) { issued = value; }, dictionary, TxTokenDetails_issued); + ON_VALUE(^(const id value) { capability = value; }, dictionary, TxTokenDetails_capability); + ON_VALUE(^(const id value) { clientId = value; }, dictionary, TxTokenDetails_clientId); ARTTokenDetails *const o = [ARTTokenDetails new]; [o initWithToken:token expires:expires issued:issued capability:capability clientId:clientId]; return o; } -+(ARTTokenParams *)readTokenParams: (NSDictionary *) jsonDict { ++(ARTTokenParams *)tokenParamsFromDictionary: (NSDictionary *) dictionary { __block NSString *clientId = nil; __block NSString *nonce = nil; - ON_VALUE(^(const id value) { clientId = value; }, jsonDict, TxTokenParams_clientId); - ON_VALUE(^(const id value) { nonce = value; }, jsonDict, TxTokenParams_nonce); + ON_VALUE(^(const id value) { clientId = value; }, dictionary, TxTokenParams_clientId); + ON_VALUE(^(const id value) { nonce = value; }, dictionary, TxTokenParams_nonce); ARTTokenParams *const o = [ARTTokenParams new]; [o initWithClientId: clientId nonce: nonce]; - READ_VALUE(o, ttl, jsonDict, TxTokenParams_ttl); - READ_VALUE(o, capability, jsonDict, TxTokenParams_capability); - READ_VALUE(o, timestamp, jsonDict, TxTokenParams_timestamp); + READ_VALUE(o, ttl, dictionary, TxTokenParams_ttl); + READ_VALUE(o, capability, dictionary, TxTokenParams_capability); + READ_VALUE(o, timestamp, dictionary, TxTokenParams_timestamp); return o; } diff --git a/ios/Classes/codec/AblyFlutterWriter.m b/ios/Classes/codec/AblyFlutterWriter.m index 6e07667cb..abbf5e6a6 100644 --- a/ios/Classes/codec/AblyFlutterWriter.m +++ b/ios/Classes/codec/AblyFlutterWriter.m @@ -25,45 +25,45 @@ - (void)writeValue:(id)value { [super writeValue:value]; } -#define WRITE_VALUE(JSON_DICT, JSON_KEY, VALUE) { \ +#define WRITE_VALUE(DICTIONARY, JSON_KEY, VALUE) { \ if (VALUE) { \ - [JSON_DICT setObject:VALUE forKey:JSON_KEY]; \ + [DICTIONARY setObject:VALUE forKey:JSON_KEY]; \ } \ } -#define WRITE_ENUM(JSON_DICT, JSON_KEY, ENUM_VALUE){ \ +#define WRITE_ENUM(DICTIONARY, JSON_KEY, ENUM_VALUE){ \ if (ENUM_VALUE) { \ - WRITE_VALUE(JSON_DICT, JSON_KEY, [NSNumber numberWithInt:ENUM_VALUE]); \ + WRITE_VALUE(DICTIONARY, JSON_KEY, [NSNumber numberWithInt:ENUM_VALUE]); \ } \ } - (NSMutableDictionary *) encodeErrorInfo:(ARTErrorInfo *const) e{ - NSMutableDictionary *jsonDict; - WRITE_VALUE(jsonDict, TxErrorInfo_message, [e message]); - WRITE_VALUE(jsonDict, TxErrorInfo_statusCode, @([e statusCode])); + NSMutableDictionary *dictionary; + WRITE_VALUE(dictionary, TxErrorInfo_message, [e message]); + WRITE_VALUE(dictionary, TxErrorInfo_statusCode, @([e statusCode])); // code, href, requestId and cause - not available in ably-cocoa // track @ https://github.com/ably/ably-flutter/issues/14 - return jsonDict; + return dictionary; } - (NSDictionary *) encodeConnectionStateChange:(ARTConnectionStateChange *const) stateChange{ - NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init]; - WRITE_ENUM(jsonDict, TxConnectionStateChange_current, [stateChange current]); - WRITE_ENUM(jsonDict, TxConnectionStateChange_previous, [stateChange previous]); - WRITE_ENUM(jsonDict, TxConnectionStateChange_event, [stateChange event]); - WRITE_VALUE(jsonDict, TxConnectionStateChange_retryIn, @((int)([stateChange retryIn] * 1000))); - WRITE_VALUE(jsonDict, TxConnectionStateChange_reason, [self encodeErrorInfo: [stateChange reason]]); - return jsonDict; + NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init]; + WRITE_ENUM(dictionary, TxConnectionStateChange_current, [stateChange current]); + WRITE_ENUM(dictionary, TxConnectionStateChange_previous, [stateChange previous]); + WRITE_ENUM(dictionary, TxConnectionStateChange_event, [stateChange event]); + WRITE_VALUE(dictionary, TxConnectionStateChange_retryIn, @((int)([stateChange retryIn] * 1000))); + WRITE_VALUE(dictionary, TxConnectionStateChange_reason, [self encodeErrorInfo: [stateChange reason]]); + return dictionary; } - (NSDictionary *) encodeChannelStateChange:(ARTChannelStateChange *const) stateChange{ - NSMutableDictionary *jsonDict; - WRITE_ENUM(jsonDict, TxChannelStateChange_current, [stateChange current]); - WRITE_ENUM(jsonDict, TxChannelStateChange_previous, [stateChange previous]); - WRITE_ENUM(jsonDict, TxChannelStateChange_event, [stateChange event]); - WRITE_VALUE(jsonDict, TxChannelStateChange_resumed, @([stateChange resumed])); - WRITE_VALUE(jsonDict, TxChannelStateChange_reason, [self encodeErrorInfo: [stateChange reason]]); - return jsonDict; + NSMutableDictionary *dictionary; + WRITE_ENUM(dictionary, TxChannelStateChange_current, [stateChange current]); + WRITE_ENUM(dictionary, TxChannelStateChange_previous, [stateChange previous]); + WRITE_ENUM(dictionary, TxChannelStateChange_event, [stateChange event]); + WRITE_VALUE(dictionary, TxChannelStateChange_resumed, @([stateChange resumed])); + WRITE_VALUE(dictionary, TxChannelStateChange_reason, [self encodeErrorInfo: [stateChange reason]]); + return dictionary; } From 5fcbad813dadc67e518b1492fbe020c6e4f004d2 Mon Sep 17 00:00:00 2001 From: "Rohit R. Abbadi" Date: Fri, 5 Jun 2020 15:10:19 +0530 Subject: [PATCH 17/19] update README https://github.com/ably/ably-flutter/pull/13#discussion_r434368693 --- bin/README.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/bin/README.md b/bin/README.md index 7d6ff396a..0e8fcbe05 100644 --- a/bin/README.md +++ b/bin/README.md @@ -1,5 +1,11 @@ ## Code generation to keep platform constants in sync +There are many platform constants that need to be sync on dart side and platform side. +Following are the constants that are being generated: +1. codec types +2. platform method and event names +3. serializable property names for serialization and de-serialization + #### Generating files ```bash @@ -15,3 +21,27 @@ A straight forward templates creating using dart string interpolation: source template files are available in `bin/templates` and source context data in `bin/codegencontext.dart`. + + +#### Generated files + +These files are generated/modified upon code generation + +1. `lib/src/generated/platformconstants.dart` for use in Flutter/Dart +2. `android/src/main/java/io/ably/flutter/plugin/generated/PlatformConstants.java` for use in Android/Java +3. `ios/Classes/codec/AblyPlatformConstants.h` for use in iOS/Objective-C +4. `ios/Classes/codec/AblyPlatformConstants.m` for use in iOS/Objective-C + +#### When would I need to run code generation? + +When any of the below need to be added/updated +1. A new codec type - required when a new top level serializable object is required (ex: `ErrorInfo` and `ClientOptions`) +2. Platform and event names - when implementing a new method in `MethodChannel` or new event in `EventChannel` +3. A new object needs to be serialized (either top-level, or nested) + + +#### What should I do after running code generation? + +1. Test that everything still works +2. Commit changes to the template(s) +3. Commit changes to the generate files From 237315e9a5b5a65bdc7abe091f4611bd4ef32c77 Mon Sep 17 00:00:00 2001 From: "Rohit R. Abbadi" Date: Thu, 25 Jun 2020 12:58:10 +0530 Subject: [PATCH 18/19] documented codec.dart and make necessary declarations private --- lib/src/codec.dart | 608 +++++++++++++++++++++++++-------------------- 1 file changed, 333 insertions(+), 275 deletions(-) diff --git a/lib/src/codec.dart b/lib/src/codec.dart index b0431fef7..8550deb52 100644 --- a/lib/src/codec.dart +++ b/lib/src/codec.dart @@ -6,290 +6,348 @@ import 'package:flutter/services.dart'; import '../ably.dart'; -typedef CodecEncoder(final T value); -typedef T CodecDecoder(Map jsonMap); -class CodecPair{ - - final CodecEncoder encoder; - final CodecDecoder decoder; - CodecPair(this.encoder, this.decoder); - - Map encode(final dynamic value){ - if (this.encoder==null) throw AblyException("Codec encoder not defined"); - if(value==null) return null; - return this.encoder(value as T); - } - - T decode(Map jsonMap){ - if (this.decoder==null) throw AblyException("Codec decoder not defined"); - if(jsonMap==null) return null; - return this.decoder(jsonMap); - } +/// a [_CodecEncoder] encodes custom type and converts it to a Map which will +/// be passed on to platform side +typedef Map _CodecEncoder(final T value); + +/// a [_CodecDecoder] decodes Map received from platform side and converts to +/// to respective dart types +typedef T _CodecDecoder(Map jsonMap); + +/// A class to manage encoding/decoding by provided encoder/decoder functions. +class _CodecPair{ + + final _CodecEncoder _encoder; + final _CodecDecoder _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 encode(final dynamic value){ + if (this._encoder==null) throw AblyException("Codec encoder is null"); + if(value==null) return null; + return this._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 jsonMap){ + if (this._decoder==null) throw AblyException("Codec decoder is null"); + if(jsonMap==null) return null; + return this._decoder(jsonMap); + } } class Codec extends StandardMessageCodec { - Map codecMap; - - Codec():super(){ - this.codecMap = { - // Ably flutter plugin protocol message - CodecTypes.ablyMessage: CodecPair(encodeAblyMessage, decodeAblyMessage), - - // Other ably objects - CodecTypes.clientOptions: CodecPair(encodeClientOptions, decodeClientOptions), - CodecTypes.errorInfo: CodecPair(null, decodeErrorInfo), - - // Events - Connection - CodecTypes.connectionStateChange: CodecPair(null, decodeConnectionStateChange), - - // Events - Channel - CodecTypes.channelStateChange: CodecPair(null, decodeChannelStateChange), - }; - } - - Map toJsonMap(Map value){ - if(value==null) return null; - return Map.castFrom(value); - } - - int getCodecType(final dynamic value){ - if (value is ClientOptions) { - return CodecTypes.clientOptions; - } else if (value is ErrorInfo) { - return CodecTypes.errorInfo; - } else if (value is AblyMessage) { - return CodecTypes.ablyMessage; + /// 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. + Map codecMap; + + Codec():super(){ + this.codecMap = { + // Ably flutter plugin protocol message + CodecTypes.ablyMessage: _CodecPair(encodeAblyMessage, decodeAblyMessage), + + // Other ably objects + CodecTypes.clientOptions: _CodecPair(encodeClientOptions, decodeClientOptions), + CodecTypes.errorInfo: _CodecPair(null, decodeErrorInfo), + + // Events - Connection + CodecTypes.connectionStateChange: _CodecPair(null, decodeConnectionStateChange), + + // Events - Channel + CodecTypes.channelStateChange: _CodecPair(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 toJsonMap(Map value){ + if(value==null) return null; + return Map.castFrom(value); + } + + /// Returns a value from [CodecTypes] based of the [Type] of [value] + int getCodecType(final dynamic value){ + if (value is ClientOptions) { + return CodecTypes.clientOptions; + } else if (value is ErrorInfo) { + return CodecTypes.errorInfo; + } else if (value is AblyMessage) { + return CodecTypes.ablyMessage; + } + return null; } - return null; - } - - @override - void writeValue (final WriteBuffer buffer, final dynamic value) { - int type = getCodecType(value); - if (type==null) { - super.writeValue(buffer, value); - } else { - buffer.putUint8(type); - writeValue(buffer, codecMap[type].encode(value)); + + /// 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 dynamic value) { + int 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) { + _CodecPair pair = codecMap[type]; + if (pair==null) { + return super.readValueOfType(type, buffer); + } else { + Map map = toJsonMap(readValue(buffer)); + return pair.decode(map); + } } - } - - dynamic readValueOfType(int type, ReadBuffer buffer) { - CodecPair pair = codecMap[type]; - if (pair==null) { - var x = super.readValueOfType(type, buffer); - return x; - } else { - Map map = toJsonMap(readValue(buffer)); - return pair.decode(map); + + // =========== ENCODERS =========== + /// Writes [value] for [key] in [map] if [value] is not null + writeToJson(Map map, key, value){ + if(value==null) return; + map[key] = value; + } + + /// Encodes [ClientOptions] to a Map + /// returns null of passed value [v] is null + Map encodeClientOptions(final ClientOptions v){ + if(v==null) return null; + Map jsonMap = {}; + // 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); + + // 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; } - } - - // =========== ENCODERS =========== - writeToJson(Map map, key, value){ - if(value==null) return; - map[key] = value; - } - - Map encodeClientOptions(final ClientOptions v){ - if(v==null) return null; - Map jsonMap = {}; - // 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); - - // 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; - } - - Map 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, - }; - } - - Map encodeTokenParams(final TokenParams v){ - if(v==null) return null; - Map jsonMap = {}; - 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; - } - - Map encodeAblyMessage(final AblyMessage v){ - if(v==null) return null; - int codecType = getCodecType(v.message); - dynamic message = (v.message==null)?null:(codecType == null)?v.message:codecMap[codecType].encode(v.message); - Map jsonMap = {}; - writeToJson(jsonMap, TxAblyMessage.registrationHandle, v.registrationHandle); - writeToJson(jsonMap, TxAblyMessage.type, codecType); - writeToJson(jsonMap, TxAblyMessage.message, message); - return jsonMap; - } - - - // =========== DECODERS =========== - T readFromJson(Map jsonMap, String key){ - dynamic value = jsonMap[key]; - if(value==null) return null; - return value as T; - } - - ClientOptions decodeClientOptions(Map jsonMap){ - if(jsonMap==null) return null; - - final ClientOptions v = ClientOptions(); - // AuthOptions (super class of ClientOptions) - v.authUrl = readFromJson(jsonMap, TxClientOptions.authUrl); - v.authMethod = readFromJson(jsonMap, TxClientOptions.authMethod); - v.key = readFromJson(jsonMap, TxClientOptions.key); - v.tokenDetails = decodeTokenDetails(toJsonMap(jsonMap[TxClientOptions.tokenDetails])); - v.authHeaders = readFromJson>(jsonMap, TxClientOptions.authHeaders); - v.authParams = readFromJson>(jsonMap, TxClientOptions.authParams); - v.queryTime = readFromJson(jsonMap, TxClientOptions.queryTime); - v.useTokenAuth = readFromJson(jsonMap, TxClientOptions.useTokenAuth); - - // ClientOptions - v.clientId = readFromJson(jsonMap, TxClientOptions.clientId); - v.logLevel = readFromJson(jsonMap, TxClientOptions.logLevel); - //TODO handle logHandler - v.tls = readFromJson(jsonMap, TxClientOptions.tls); - v.restHost = readFromJson(jsonMap, TxClientOptions.restHost); - v.realtimeHost = readFromJson(jsonMap, TxClientOptions.realtimeHost); - v.port = readFromJson(jsonMap, TxClientOptions.port); - v.tlsPort = readFromJson(jsonMap, TxClientOptions.tlsPort); - v.autoConnect = readFromJson(jsonMap, TxClientOptions.autoConnect); - v.useBinaryProtocol = readFromJson(jsonMap, TxClientOptions.useBinaryProtocol); - v.queueMessages = readFromJson(jsonMap, TxClientOptions.queueMessages); - v.echoMessages = readFromJson(jsonMap, TxClientOptions.echoMessages); - v.recover = readFromJson(jsonMap, TxClientOptions.recover); - v.environment = readFromJson(jsonMap, TxClientOptions.environment); - v.idempotentRestPublishing = readFromJson(jsonMap, TxClientOptions.idempotentRestPublishing); - v.httpOpenTimeout = readFromJson(jsonMap, TxClientOptions.httpOpenTimeout); - v.httpRequestTimeout = readFromJson(jsonMap, TxClientOptions.httpRequestTimeout); - v.httpMaxRetryCount = readFromJson(jsonMap, TxClientOptions.httpMaxRetryCount); - v.realtimeRequestTimeout = readFromJson(jsonMap, TxClientOptions.realtimeRequestTimeout); - v.fallbackHosts = readFromJson>(jsonMap, TxClientOptions.fallbackHosts); - v.fallbackHostsUseDefault = readFromJson(jsonMap, TxClientOptions.fallbackHostsUseDefault); - v.fallbackRetryTimeout = readFromJson(jsonMap, TxClientOptions.fallbackRetryTimeout); - v.defaultTokenParams = decodeTokenParams(toJsonMap(jsonMap[TxClientOptions.defaultTokenParams])); - v.channelRetryTimeout = readFromJson(jsonMap, TxClientOptions.channelRetryTimeout); - v.transportParams = readFromJson>(jsonMap, TxClientOptions.transportParams); - return v; - } - - TokenDetails decodeTokenDetails(Map jsonMap){ - if(jsonMap==null) return null; - TokenDetails v = TokenDetails(jsonMap[TxTokenDetails.token]); - v.expires = readFromJson(jsonMap, TxTokenDetails.expires); - v.issued = readFromJson(jsonMap, TxTokenDetails.issued); - v.capability = readFromJson(jsonMap, TxTokenDetails.capability); - v.clientId = readFromJson(jsonMap, TxTokenDetails.clientId); - return v; - } - - TokenParams decodeTokenParams(Map jsonMap){ - if(jsonMap==null) return null; - TokenParams v = TokenParams(); - v.capability = readFromJson(jsonMap, TxTokenParams.capability); - v.clientId = readFromJson(jsonMap, TxTokenParams.clientId); - v.nonce = readFromJson(jsonMap, TxTokenParams.nonce); - v.timestamp = readFromJson(jsonMap, TxTokenParams.timestamp); - v.ttl = readFromJson(jsonMap, TxTokenParams.ttl); - return v; - } - - AblyMessage decodeAblyMessage(Map jsonMap){ - if(jsonMap==null) return null; - int type = readFromJson(jsonMap, TxAblyMessage.type); - dynamic message = jsonMap[TxAblyMessage.message]; - if(type!=null){ - message = codecMap[type].decode(toJsonMap(jsonMap[TxAblyMessage.message])); + + /// Encodes [TokenDetails] to a Map + /// returns null of passed value [v] is null + Map 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 of passed value [v] is null + Map encodeTokenParams(final TokenParams v){ + if(v==null) return null; + Map jsonMap = {}; + 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 [AblyMessage] to a Map + /// returns null of passed value [v] is null + Map encodeAblyMessage(final AblyMessage v){ + if(v==null) return null; + int codecType = getCodecType(v.message); + dynamic message = (v.message==null)?null:(codecType == null)?v.message:codecMap[codecType].encode(v.message); + Map jsonMap = {}; + writeToJson(jsonMap, TxAblyMessage.registrationHandle, v.registrationHandle); + writeToJson(jsonMap, TxAblyMessage.type, codecType); + writeToJson(jsonMap, TxAblyMessage.message, message); + return jsonMap; + } + + + // =========== DECODERS =========== + /// Reads [key] value from [jsonMap] + /// Casts it to [T] if the value is not null + T readFromJson(Map jsonMap, String key){ + dynamic 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 jsonMap){ + if(jsonMap==null) return null; + + final ClientOptions v = ClientOptions(); + // AuthOptions (super class of ClientOptions) + v.authUrl = readFromJson(jsonMap, TxClientOptions.authUrl); + v.authMethod = readFromJson(jsonMap, TxClientOptions.authMethod); + v.key = readFromJson(jsonMap, TxClientOptions.key); + v.tokenDetails = decodeTokenDetails(toJsonMap(jsonMap[TxClientOptions.tokenDetails])); + v.authHeaders = readFromJson>(jsonMap, TxClientOptions.authHeaders); + v.authParams = readFromJson>(jsonMap, TxClientOptions.authParams); + v.queryTime = readFromJson(jsonMap, TxClientOptions.queryTime); + v.useTokenAuth = readFromJson(jsonMap, TxClientOptions.useTokenAuth); + + // ClientOptions + v.clientId = readFromJson(jsonMap, TxClientOptions.clientId); + v.logLevel = readFromJson(jsonMap, TxClientOptions.logLevel); + //TODO handle logHandler + v.tls = readFromJson(jsonMap, TxClientOptions.tls); + v.restHost = readFromJson(jsonMap, TxClientOptions.restHost); + v.realtimeHost = readFromJson(jsonMap, TxClientOptions.realtimeHost); + v.port = readFromJson(jsonMap, TxClientOptions.port); + v.tlsPort = readFromJson(jsonMap, TxClientOptions.tlsPort); + v.autoConnect = readFromJson(jsonMap, TxClientOptions.autoConnect); + v.useBinaryProtocol = readFromJson(jsonMap, TxClientOptions.useBinaryProtocol); + v.queueMessages = readFromJson(jsonMap, TxClientOptions.queueMessages); + v.echoMessages = readFromJson(jsonMap, TxClientOptions.echoMessages); + v.recover = readFromJson(jsonMap, TxClientOptions.recover); + v.environment = readFromJson(jsonMap, TxClientOptions.environment); + v.idempotentRestPublishing = readFromJson(jsonMap, TxClientOptions.idempotentRestPublishing); + v.httpOpenTimeout = readFromJson(jsonMap, TxClientOptions.httpOpenTimeout); + v.httpRequestTimeout = readFromJson(jsonMap, TxClientOptions.httpRequestTimeout); + v.httpMaxRetryCount = readFromJson(jsonMap, TxClientOptions.httpMaxRetryCount); + v.realtimeRequestTimeout = readFromJson(jsonMap, TxClientOptions.realtimeRequestTimeout); + v.fallbackHosts = readFromJson>(jsonMap, TxClientOptions.fallbackHosts); + v.fallbackHostsUseDefault = readFromJson(jsonMap, TxClientOptions.fallbackHostsUseDefault); + v.fallbackRetryTimeout = readFromJson(jsonMap, TxClientOptions.fallbackRetryTimeout); + v.defaultTokenParams = decodeTokenParams(toJsonMap(jsonMap[TxClientOptions.defaultTokenParams])); + v.channelRetryTimeout = readFromJson(jsonMap, TxClientOptions.channelRetryTimeout); + v.transportParams = readFromJson>(jsonMap, TxClientOptions.transportParams); + return v; + } + + /// Decodes value [jsonMap] to [TokenDetails] + /// returns null if [jsonMap] is null + TokenDetails decodeTokenDetails(Map jsonMap){ + if(jsonMap==null) return null; + TokenDetails v = TokenDetails(jsonMap[TxTokenDetails.token]); + v.expires = readFromJson(jsonMap, TxTokenDetails.expires); + v.issued = readFromJson(jsonMap, TxTokenDetails.issued); + v.capability = readFromJson(jsonMap, TxTokenDetails.capability); + v.clientId = readFromJson(jsonMap, TxTokenDetails.clientId); + return v; + } + + /// Decodes value [jsonMap] to [TokenParams] + /// returns null if [jsonMap] is null + TokenParams decodeTokenParams(Map jsonMap){ + if(jsonMap==null) return null; + TokenParams v = TokenParams(); + v.capability = readFromJson(jsonMap, TxTokenParams.capability); + v.clientId = readFromJson(jsonMap, TxTokenParams.clientId); + v.nonce = readFromJson(jsonMap, TxTokenParams.nonce); + v.timestamp = readFromJson(jsonMap, TxTokenParams.timestamp); + v.ttl = readFromJson(jsonMap, TxTokenParams.ttl); + return v; + } + + /// Decodes value [jsonMap] to [AblyMessage] + /// returns null if [jsonMap] is null + AblyMessage decodeAblyMessage(Map jsonMap){ + if(jsonMap==null) return null; + int type = readFromJson(jsonMap, TxAblyMessage.type); + dynamic message = jsonMap[TxAblyMessage.message]; + if(type!=null){ + message = codecMap[type].decode(toJsonMap(jsonMap[TxAblyMessage.message])); + } + return AblyMessage( + jsonMap[TxAblyMessage.registrationHandle] as int, + message, + type: type + ); + } + + /// Decodes value [jsonMap] to [ErrorInfo] + /// returns null if [jsonMap] is null + ErrorInfo decodeErrorInfo(Map jsonMap){ + if(jsonMap==null) return null; + return 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 [index] value to [ConnectionEvent] enum if not null + ConnectionEvent decodeConnectionEvent(int index) => (index==null)?null:ConnectionEvent.values[index]; + + /// Decodes [index] value to [ConnectionState] enum if not null + ConnectionState decodeConnectionState(int index) => (index==null)?null:ConnectionState.values[index]; + + /// Decodes [index] value to [ChannelEvent] enum if not null + ChannelEvent decodeChannelEvent(int index) => (index==null)?null:ChannelEvent.values[index]; + + /// Decodes [index] value to [ChannelState] enum if not null + ChannelState decodeChannelState(int index) => (index==null)?null:ChannelState.values[index]; + + /// Decodes value [jsonMap] to [ConnectionStateChange] + /// returns null if [jsonMap] is null + ConnectionStateChange decodeConnectionStateChange(Map jsonMap){ + if(jsonMap==null) return null; + ConnectionState current = decodeConnectionState(readFromJson(jsonMap, TxConnectionStateChange.current)); + ConnectionState previous = decodeConnectionState(readFromJson(jsonMap, TxConnectionStateChange.previous)); + ConnectionEvent event = decodeConnectionEvent(readFromJson(jsonMap, TxConnectionStateChange.event)); + int retryIn = readFromJson(jsonMap, TxConnectionStateChange.retryIn); + ErrorInfo reason = decodeErrorInfo(toJsonMap(jsonMap[TxConnectionStateChange.reason])); + return ConnectionStateChange(current, previous, event, retryIn: retryIn, reason: reason); + } + + /// Decodes value [jsonMap] to [ChannelStateChange] + /// returns null if [jsonMap] is null + ChannelStateChange decodeChannelStateChange(Map jsonMap){ + if(jsonMap==null) return null; + ChannelState current = decodeChannelState(readFromJson(jsonMap, TxChannelStateChange.current)); + ChannelState previous = decodeChannelState(readFromJson(jsonMap, TxChannelStateChange.previous)); + ChannelEvent event = decodeChannelEvent(readFromJson(jsonMap, TxChannelStateChange.event)); + bool resumed = readFromJson(jsonMap, TxChannelStateChange.resumed); + ErrorInfo reason = decodeErrorInfo(jsonMap[TxChannelStateChange.reason]); + return ChannelStateChange(current, previous, event, resumed: resumed, reason: reason); } - return AblyMessage( - jsonMap[TxAblyMessage.registrationHandle] as int, - message, - type: type - ); - } - - ErrorInfo decodeErrorInfo(Map jsonMap){ - if(jsonMap==null) return null; - return 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 - ); - } - - ConnectionEvent decodeConnectionEvent(int index) => (index==null)?null:ConnectionEvent.values[index]; - ConnectionState decodeConnectionState(int index) => (index==null)?null:ConnectionState.values[index]; - ChannelEvent decodeChannelEvent(int index) => (index==null)?null:ChannelEvent.values[index]; - ChannelState decodeChannelState(int index) => (index==null)?null:ChannelState.values[index]; - - ConnectionStateChange decodeConnectionStateChange(Map jsonMap){ - if(jsonMap==null) return null; - ConnectionState current = decodeConnectionState(readFromJson(jsonMap, TxConnectionStateChange.current)); - ConnectionState previous = decodeConnectionState(readFromJson(jsonMap, TxConnectionStateChange.previous)); - ConnectionEvent event = decodeConnectionEvent(readFromJson(jsonMap, TxConnectionStateChange.event)); - int retryIn = readFromJson(jsonMap, TxConnectionStateChange.retryIn); - ErrorInfo reason = decodeErrorInfo(toJsonMap(jsonMap[TxConnectionStateChange.reason])); - return ConnectionStateChange(current, previous, event, retryIn: retryIn, reason: reason); - } - - ChannelStateChange decodeChannelStateChange(Map jsonMap){ - if(jsonMap==null) return null; - ChannelState current = decodeChannelState(readFromJson(jsonMap, TxChannelStateChange.current)); - ChannelState previous = decodeChannelState(readFromJson(jsonMap, TxChannelStateChange.previous)); - ChannelEvent event = decodeChannelEvent(readFromJson(jsonMap, TxChannelStateChange.event)); - bool resumed = readFromJson(jsonMap, TxChannelStateChange.resumed); - ErrorInfo reason = decodeErrorInfo(jsonMap[TxChannelStateChange.reason]); - return ChannelStateChange(current, previous, event, resumed: resumed, reason: reason); - } } From 2a49b9693e08ee53aa8602f213535a0b6bcbc169 Mon Sep 17 00:00:00 2001 From: Rohit Reddy Abbadi Date: Sat, 27 Jun 2020 10:47:12 +0530 Subject: [PATCH 19/19] Rename _CodecEncoder and _CodecDecoder adhering to https://github.com/ably/ably-flutter/pull/13#pullrequestreview-438274770 --- lib/src/codec.dart | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/src/codec.dart b/lib/src/codec.dart index 8550deb52..297d5eda6 100644 --- a/lib/src/codec.dart +++ b/lib/src/codec.dart @@ -6,19 +6,19 @@ import 'package:flutter/services.dart'; import '../ably.dart'; -/// a [_CodecEncoder] encodes custom type and converts it to a Map which will +/// a [_Encoder] encodes custom type and converts it to a Map which will /// be passed on to platform side -typedef Map _CodecEncoder(final T value); +typedef Map _Encoder(final T value); -/// a [_CodecDecoder] decodes Map received from platform side and converts to +/// a [_Decoder] decodes Map received from platform side and converts to /// to respective dart types -typedef T _CodecDecoder(Map jsonMap); +typedef T _Decoder(Map jsonMap); /// A class to manage encoding/decoding by provided encoder/decoder functions. class _CodecPair{ - final _CodecEncoder _encoder; - final _CodecDecoder _decoder; + final _Encoder _encoder; + final _Decoder _decoder; _CodecPair(this._encoder, this._decoder); /// Convert properties from an ably library object instance (dart) to Map.