1
0
mirror of https://gitlab.com/comunic/comunicmobile synced 2025-02-18 14:42:39 +00:00
comunicmobile/lib/helpers/websocket_helper.dart

92 lines
2.4 KiB
Dart
Raw Normal View History

import 'dart:convert';
2020-04-18 13:48:21 +02:00
import 'package:comunic/helpers/events_helper.dart';
2020-04-17 16:04:47 +02:00
import 'package:comunic/models/api_request.dart';
import 'package:comunic/models/config.dart';
import 'package:comunic/models/ws_message.dart';
2020-04-17 16:04:47 +02:00
import 'package:web_socket_channel/web_socket_channel.dart';
2020-04-17 15:25:26 +02:00
/// User web socket helper
///
/// @author Pierre Hubert
class WebSocketHelper {
2020-04-17 16:04:47 +02:00
static WebSocketChannel _ws;
/// Check out whether we are currently connected to WebSocket or not
2020-04-17 15:25:26 +02:00
static bool isConnected() {
2020-04-17 16:04:47 +02:00
return _ws != null && _ws.closeCode == null;
2020-04-17 15:25:26 +02:00
}
2020-04-17 16:04:47 +02: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 15:25:26 +02:00
/// Connect to WebSocket
static connect() async {
if (isConnected()) return;
2020-04-17 16:04:47 +02:00
// First, get an access token
final token = await _getWsToken();
2020-04-18 13:48:21 +02:00
// Determine WebSocket URI
2020-04-17 16:04:47 +02: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
(data) {
print("WS New data: $data");
_processMessage(data.toString());
},
2020-04-17 16:04:47 +02:00
// Print errors on console
onError: (e, stack) {
print("WS error! $e");
print(stack);
},
// Notify when the channel is closed
2020-04-18 13:48:21 +02:00
onDone: () {
print("WS Channel closed");
EventsHelper.emit(WSClosedEvent());
},
2020-04-17 16:04:47 +02:00
);
2020-04-17 15:25:26 +02:00
}
/// Process incoming message
static _processMessage(String msgStr) {
try {
final msg = WsMessage.fromJSON(jsonDecode(msgStr));
if (!msg.hasId)
_processUnattendedMessage(msg);
else
throw Exception("Do not know how to process attended message!");
} catch (e, stack) {
print("WS could not process message: $e");
print(stack);
}
}
/// Process an unattended message
static _processUnattendedMessage(WsMessage msg) {
switch (msg.title) {
case "number_notifs":
EventsHelper.emit(NewNumberNotifsEvent(msg.data));
break;
default:
throw Exception("Unknown message type: ${msg.title}");
}
}
2020-04-17 15:25:26 +02:00
}