mirror of
https://gitlab.com/comunic/comunicmobile
synced 2024-12-26 04:48:51 +00:00
Connect to WebSocket
This commit is contained in:
parent
9021ca7168
commit
de3cd9c7b7
@ -1,15 +1,54 @@
|
||||
import 'package:comunic/models/api_request.dart';
|
||||
import 'package:comunic/models/config.dart';
|
||||
import 'package:web_socket_channel/web_socket_channel.dart';
|
||||
|
||||
/// User web socket helper
|
||||
///
|
||||
/// @author Pierre Hubert
|
||||
|
||||
class WebSocketHelper {
|
||||
/// Check out whether we are currently connected to websocket or not
|
||||
static WebSocketChannel _ws;
|
||||
|
||||
/// Check out whether we are currently connected to WebSocket or not
|
||||
static bool isConnected() {
|
||||
return true;
|
||||
return _ws != null && _ws.closeCode == null;
|
||||
}
|
||||
|
||||
/// 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"];
|
||||
|
||||
/// Connect to WebSocket
|
||||
static connect() async {
|
||||
if (isConnected()) return;
|
||||
|
||||
// First, get an access token
|
||||
final token = await _getWsToken();
|
||||
|
||||
// Determine websocket URI
|
||||
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
|
||||
onDone: () => print("WS Channel closed"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -49,7 +49,9 @@ class _InitializeWidgetState extends State<InitializeWidget> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return WebSocketHelper.isConnected() ? MainRoute() : _buildNonReadyWidget();
|
||||
return !_error && WebSocketHelper.isConnected()
|
||||
? MainRoute()
|
||||
: _buildNonReadyWidget();
|
||||
}
|
||||
|
||||
/// Build loading widget
|
||||
|
Loading…
Reference in New Issue
Block a user