platform/lib/io.dart

76 lines
2.1 KiB
Dart
Raw Normal View History

2016-12-23 10:47:21 +00:00
/// Command-line WebSocket client library for the Angel framework.
2016-12-23 20:57:46 +00:00
library angel_websocket.io;
2016-12-23 10:47:21 +00:00
import 'dart:async';
2016-12-23 20:57:46 +00:00
import 'dart:io';
2016-12-23 10:47:21 +00:00
import 'package:angel_client/angel_client.dart';
import 'package:http/http.dart' as http;
import 'package:json_god/json_god.dart' as god;
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:web_socket_channel/io.dart';
2016-12-23 20:57:46 +00:00
import 'angel_websocket.dart';
2016-12-23 10:47:21 +00:00
import 'base_websocket_client.dart';
export 'package:angel_client/angel_client.dart';
export 'angel_websocket.dart';
final RegExp _straySlashes = new RegExp(r"(^/)|(/+$)");
/// Queries an Angel server via WebSockets.
class WebSockets extends BaseWebSocketClient {
2017-06-30 23:09:03 +00:00
final List<IoWebSocketsService> _services = [];
2017-03-02 03:54:58 +00:00
2016-12-23 10:47:21 +00:00
WebSockets(String path) : super(new http.Client(), path);
2017-03-02 03:54:58 +00:00
@override
Stream<String> authenticateViaPopup(String url, {String eventName: 'token'}) {
throw new UnimplementedError(
'Opening popup windows is not supported in the `dart:io` client.');
}
@override
Future close() {
for (var service in _services) {
service.close();
}
return super.close();
}
2016-12-23 10:47:21 +00:00
@override
2016-12-23 20:57:46 +00:00
Future<WebSocketChannel> getConnectedWebSocket() async {
2017-04-10 01:45:45 +00:00
var socket = await WebSocket.connect(basePath,
headers: authToken?.isNotEmpty == true
? {'Authorization': 'Bearer $authToken'}
: {});
2016-12-23 20:57:46 +00:00
return new IOWebSocketChannel(socket);
2016-12-23 10:47:21 +00:00
}
@override
2017-09-24 04:37:58 +00:00
IoWebSocketsService service(String path,
2016-12-23 10:47:21 +00:00
{Type type, AngelDeserializer deserializer}) {
2016-12-23 20:57:46 +00:00
String uri = path.replaceAll(_straySlashes, '');
2017-09-24 04:37:58 +00:00
return new IoWebSocketsService(socket, this, uri, type);
2016-12-23 10:47:21 +00:00
}
2016-12-23 20:57:46 +00:00
@override
serialize(x) => god.serialize(x);
2016-12-23 10:47:21 +00:00
}
2017-06-30 23:09:03 +00:00
class IoWebSocketsService extends WebSocketsService {
2016-12-23 10:47:21 +00:00
final Type type;
2017-06-30 23:09:03 +00:00
IoWebSocketsService(WebSocketChannel socket, Angel app, String uri, this.type)
2016-12-23 10:47:21 +00:00
: super(socket, app, uri);
2016-12-23 20:57:46 +00:00
@override
serialize(WebSocketAction action) => god.serialize(action);
@override
deserialize(x) {
if (type != null && type != dynamic) {
return god.deserializeDatum(x, outputType: type);
} else
return super.deserialize(x);
}
2016-12-23 10:47:21 +00:00
}