2020-04-18 11:48:21 +00:00
|
|
|
import 'package:comunic/helpers/events_helper.dart';
|
2020-04-17 14:04:47 +00:00
|
|
|
import 'package:comunic/models/api_request.dart';
|
|
|
|
import 'package:comunic/models/config.dart';
|
|
|
|
import 'package:web_socket_channel/web_socket_channel.dart';
|
|
|
|
|
2020-04-17 13:25:26 +00:00
|
|
|
/// User web socket helper
|
|
|
|
///
|
|
|
|
/// @author Pierre Hubert
|
|
|
|
|
|
|
|
class WebSocketHelper {
|
2020-04-17 14:04:47 +00:00
|
|
|
static WebSocketChannel _ws;
|
|
|
|
|
|
|
|
/// Check out whether we are currently connected to WebSocket or not
|
2020-04-17 13:25:26 +00:00
|
|
|
static bool isConnected() {
|
2020-04-17 14:04:47 +00:00
|
|
|
return _ws != null && _ws.closeCode == null;
|
2020-04-17 13:25:26 +00:00
|
|
|
}
|
|
|
|
|
2020-04-17 14:04:47 +00:00
|
|
|
/// Get WebSocket access token
|
|
|
|
//TODO : Handles the case user tokens were destroyed (auto sign-out user)
|
|
|
|
static Future<String> _getWsToken() async =>
|
|
|
|
(await APIRequest(uri: "ws/token", needLogin: true).exec())
|
|
|
|
.assertOk()
|
|
|
|
.getObject()["token"];
|
|
|
|
|
2020-04-17 13:25:26 +00:00
|
|
|
/// Connect to WebSocket
|
|
|
|
static connect() async {
|
|
|
|
if (isConnected()) return;
|
2020-04-17 14:04:47 +00:00
|
|
|
|
|
|
|
// First, get an access token
|
|
|
|
final token = await _getWsToken();
|
|
|
|
|
2020-04-18 11:48:21 +00:00
|
|
|
// Determine WebSocket URI
|
2020-04-17 14:04:47 +00:00
|
|
|
final wsURL =
|
|
|
|
"${(config().apiServerSecure ? "wss" : "ws")}://${config()
|
|
|
|
.apiServerName}${config().apiServerUri}ws?token=$token";
|
|
|
|
final wsURI = Uri.parse(wsURL);
|
|
|
|
|
|
|
|
// Connect
|
|
|
|
_ws = WebSocketChannel.connect(wsURI);
|
|
|
|
|
|
|
|
_ws.stream.listen(
|
|
|
|
// When we got data
|
|
|
|
(onData) => print("WS New data: $onData"),
|
|
|
|
|
|
|
|
// Print errors on console
|
|
|
|
onError: (e, stack) {
|
|
|
|
print("WS error! $e");
|
|
|
|
print(stack);
|
|
|
|
},
|
|
|
|
|
|
|
|
// Notify when the channel is closed
|
2020-04-18 11:48:21 +00:00
|
|
|
onDone: () {
|
|
|
|
print("WS Channel closed");
|
|
|
|
EventsHelper.emit(WSClosedEvent());
|
|
|
|
},
|
2020-04-17 14:04:47 +00:00
|
|
|
);
|
2020-04-17 13:25:26 +00:00
|
|
|
}
|
|
|
|
}
|