forked from deriv-com/flutter-deriv-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection_cubit.dart
192 lines (153 loc) · 5.58 KB
/
connection_cubit.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import 'dart:async';
import 'dart:developer' as dev;
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_deriv_api/api/api_initializer.dart';
import 'package:flutter_deriv_api/api/response/ping_response_result.dart';
import 'package:flutter_deriv_api/services/connection/api_manager/base_api.dart';
import 'package:flutter_deriv_api/services/connection/api_manager/binary_api.dart';
import 'package:flutter_deriv_api/services/connection/api_manager/connection_information.dart';
import 'package:deriv_dependency_injector/dependency_injector.dart';
part 'connection_state.dart';
/// Bringing [ConnectionCubit] to flutter-deriv-api to simplify the usage of api.
class ConnectionCubit extends Cubit<ConnectionState> {
/// Initializes [ConnectionCubit].
ConnectionCubit(
ConnectionInformation connectionInformation, {
BaseAPI? api,
this.enableDebug = false,
// TODO(NA): Refactor to only get BinaryAPI instance. and printResponse and proxyAwareConnection can be part of BinaryAPI only.
this.printResponse = false,
this.proxyAwareConnection = false,
}) : super(const ConnectionInitialState()) {
APIInitializer().initialize(
api: api ??
BinaryAPI(
key: _key,
proxyAwareConnection: proxyAwareConnection,
enableDebug: enableDebug,
),
);
_api = Injector()<BaseAPI>();
_connectionInformation = connectionInformation;
_connect(_connectionInformation);
_startKeepAliveTimer();
}
final String _key = '${UniqueKey()}';
late final BaseAPI _api;
/// Enables debug mode.
///
/// Default value is `false`.
final bool enableDebug;
/// Prints API response to console, only works if [enableDebug] is `true`.
///
/// Default value is `false`.
final bool printResponse;
/// A flag to indicate if the connection is proxy aware.
final bool proxyAwareConnection;
// In some devices like Samsung J6 or Huawei Y7, the call manager doesn't response to the ping call less than 5 sec.
final Duration _pingTimeout = const Duration(seconds: 5);
final Duration _connectivityCheckInterval = const Duration(seconds: 5);
Timer? _connectivityTimer;
static late ConnectionInformation _connectionInformation;
/// Gets connection information of WebSocket (endpoint, brand, appId).
static ConnectionInformation get connectionInformation =>
_connectionInformation;
/// Gets endpoint of websocket.
static String get endpoint => _connectionInformation.endpoint;
/// Gets auth endpoint of websocket.
static String get authEndpoint => _connectionInformation.authEndpoint;
/// Gets app id of websocket.
static String get appId => _connectionInformation.appId;
/// Stream subscription for connectivity.
StreamSubscription<ConnectivityResult>? connectivitySubscription;
/// Getter for [BaseAPI] implementation class. By default, it will be [BinaryAPI].
BaseAPI get api => _api;
/// Reconnect to Websocket.
Future<void> reconnect({
ConnectionInformation? connectionInformation,
bool isChangingLanguage = false,
}) async {
emit(ConnectionDisconnectedState(isChangingLanguage: isChangingLanguage));
if (connectionInformation != null) {
_connectionInformation = connectionInformation;
}
await _connect(_connectionInformation);
}
/// Connects to the web socket.
Future<void> _connect(ConnectionInformation connectionInformation) async {
if (state is ConnectionConnectingState) {
return;
}
emit(const ConnectionConnectingState());
try {
await _api.disconnect().timeout(_pingTimeout);
} on Exception catch (e) {
dev.log('$runtimeType disconnect exception: $e', error: e);
unawaited(reconnect());
return;
}
await _api.connect(
_connectionInformation,
printResponse: enableDebug && printResponse,
onOpen: (String key) {
if (_key == key) {
emit(const ConnectionConnectedState());
}
},
onDone: (String key) {
if (_key == key) {
unawaited(reconnect());
}
},
onError: (String key) {
if (_key == key) {
emit(const ConnectionDisconnectedState());
}
},
);
if (_api is BinaryAPI) {
_setupConnectivityListener();
}
}
void _setupConnectivityListener() {
connectivitySubscription ??= Connectivity().onConnectivityChanged.listen(
(ConnectivityResult status) async {
final bool isConnectedToNetwork = status == ConnectivityResult.mobile ||
status == ConnectivityResult.wifi;
if (isConnectedToNetwork) {
final bool isConnected = await _ping();
if (!isConnected) {
await reconnect();
}
} else if (status == ConnectivityResult.none) {
emit(const ConnectionDisconnectedState());
}
},
);
}
void _startKeepAliveTimer() {
if (_connectivityTimer == null || !_connectivityTimer!.isActive) {
_connectivityTimer =
Timer.periodic(_connectivityCheckInterval, (Timer timer) => _ping());
}
}
Future<bool> _ping() async {
try {
final PingResponse response =
await PingResponse.pingMethod().timeout(_pingTimeout);
return response.ping == PingEnum.pong;
} on Exception catch (_) {
return false;
}
}
@override
Future<void> close() {
_connectivityTimer?.cancel();
connectivitySubscription?.cancel();
connectivitySubscription = null;
return super.close();
}
}