platform/lib/server.dart

220 lines
6.4 KiB
Dart
Raw Normal View History

2016-04-29 01:19:09 +00:00
library angel_websocket.server;
2016-06-27 00:42:21 +00:00
import 'dart:async';
2016-07-06 13:33:40 +00:00
import 'dart:convert';
2016-04-29 01:19:09 +00:00
import 'dart:io';
import 'package:angel_framework/angel_framework.dart';
2016-06-27 00:42:21 +00:00
import 'package:json_god/json_god.dart' as god;
import 'package:merge_map/merge_map.dart';
2016-06-27 00:42:21 +00:00
import 'angel_websocket.dart';
2016-09-03 12:34:01 +00:00
export 'angel_websocket.dart';
2016-04-29 01:19:09 +00:00
part 'websocket_context.dart';
2016-05-03 23:42:06 +00:00
class Realtime {
const Realtime();
2016-06-27 00:42:21 +00:00
}
2016-04-29 01:19:09 +00:00
2016-09-17 20:00:17 +00:00
class AngelWebSocket extends AngelPlugin {
Angel _app;
List<WebSocket> _clients = [];
2016-09-18 01:35:16 +00:00
StreamController<WebSocketContext> _onConnection =
new StreamController<WebSocketContext>.broadcast();
2016-09-17 20:00:17 +00:00
List<WebSocket> get clients => new List.from(_clients, growable: false);
List<String> servicesAlreadyWired = [];
String endpoint;
2016-09-18 01:35:16 +00:00
Stream<WebSocketContext> get onConnection => _onConnection.stream;
2016-04-29 01:19:09 +00:00
AngelWebSocket(String this.endpoint);
_batchEvent(String path) {
return (HookedServiceEvent e) async {
var event = await transformEvent(e);
event.eventName = "$path::${event.eventName}";
await batchEvent(event);
};
}
Future batchEvent(WebSocketEvent event) async {
// Default implementation will just immediately fire events
_clients.forEach((client) {
client.add(god.serialize(event));
});
}
Future<List<WebSocketEvent>> getBatchedEvents() async => [];
2016-06-27 00:42:21 +00:00
Future handleAction(WebSocketAction action, WebSocketContext socket) async {
var split = action.eventName.split("::");
2016-06-27 00:42:21 +00:00
if (split.length < 2)
return socket.sendError(new AngelHttpException.BadRequest());
2016-06-27 00:42:21 +00:00
var service = _app.service(split[0]);
2016-04-29 01:19:09 +00:00
if (service == null)
return socket.sendError(new AngelHttpException.NotFound(
message: "No service \"${split[0]}\" exists."));
var eventName = split[1];
var params = mergeMap([
god.deserializeDatum(action.params),
{"provider": Providers.WEBSOCKET}
]);
2016-07-06 13:33:40 +00:00
try {
if (eventName == "index") {
return socket.send("${split[0]}::" + HookedServiceEvent.INDEXED,
await service.index(params));
} else if (eventName == "read") {
return socket.send("${split[0]}::" + HookedServiceEvent.READ,
await service.read(action.id, params));
} else if (eventName == "create") {
return new WebSocketEvent(
eventName: "${split[0]}::" + HookedServiceEvent.CREATED,
data: await service.create(action.data, params));
} else if (eventName == "modify") {
return new WebSocketEvent(
eventName: "${split[0]}::" + HookedServiceEvent.MODIFIED,
data: await service.modify(action.id, action.data, params));
} else if (eventName == "update") {
return new WebSocketEvent(
eventName: "${split[0]}::" + HookedServiceEvent.UPDATED,
data: await service.update(action.id, action.data, params));
} else if (eventName == "remove") {
return new WebSocketEvent(
eventName: "${split[0]}::" + HookedServiceEvent.REMOVED,
data: await service.remove(action.id, params));
} else {
return socket.sendError(new AngelHttpException.MethodNotAllowed(
message: "Method Not Allowed: \"$eventName\""));
2016-04-29 01:19:09 +00:00
}
} catch (e) {
if (e is AngelHttpException) return socket.sendError(e);
2016-06-27 00:42:21 +00:00
return socket.sendError(new AngelHttpException(e));
2016-04-29 01:19:09 +00:00
}
}
2016-04-29 01:19:09 +00:00
hookupService(Pattern _path, HookedService service) {
String path = _path.toString();
var batch = _batchEvent(path);
2016-05-03 23:42:06 +00:00
service
..afterCreated.listen(batch)
..afterModified.listen(batch)
..afterUpdated.listen(batch)
..afterRemoved.listen(batch);
servicesAlreadyWired.add(path);
}
2016-07-06 13:33:40 +00:00
Future onConnect(WebSocketContext socket) async {}
onData(WebSocketContext socket, data) async {
try {
2016-09-18 01:35:16 +00:00
socket._onData.add(data);
2016-07-06 13:33:40 +00:00
var fromJson = JSON.decode(data);
var action = new WebSocketAction(
id: fromJson['id'],
eventName: fromJson['eventName'],
data: fromJson['data'],
params: fromJson['params']);
if (action.eventName == null ||
action.eventName is! String ||
2016-07-06 13:33:40 +00:00
action.eventName.isEmpty) {
throw new AngelHttpException.BadRequest();
}
2016-05-03 23:42:06 +00:00
2016-09-18 01:35:16 +00:00
if (fromJson is Map && fromJson.containsKey("eventName")) {
socket._onAll.add(fromJson);
socket.on._getStreamForEvent(fromJson["eventName"].toString()).add(fromJson);
}
2016-07-06 13:33:40 +00:00
2016-09-18 01:35:16 +00:00
if (action.eventName.contains("::")) {
var split = action.eventName.split("::");
if (split.length >= 2) {
if ([
"index",
"read",
"create",
"modify",
"update",
"remove"
].contains(split[1])) {
var event = handleAction(action, socket);
if (event is Future) event = await event;
if (event is WebSocketEvent) {
batchEvent(event);
}
}
}
2016-04-29 01:19:09 +00:00
}
} catch (e) {
// Send an error
2016-07-06 13:33:40 +00:00
if (e is AngelHttpException)
socket.sendError(e);
else
socket.sendError(new AngelHttpException(e));
}
}
Future<WebSocketEvent> transformEvent(HookedServiceEvent event) async {
return new WebSocketEvent(eventName: event.eventName, data: event.result);
}
wireAllServices(Angel app) {
for (Pattern key in app.services.keys.where((x) {
return !servicesAlreadyWired.contains(x) &&
app.services[x] is HookedService;
})) {
hookupService(key, app.services[key]);
}
2016-06-27 00:42:21 +00:00
}
2016-09-17 20:00:17 +00:00
@override
Future call(Angel app) async {
2016-09-17 20:00:17 +00:00
this._app = app..container.singleton(this);
if (runtimeType != AngelWebSocket)
app.container.singleton(this, as: AngelWebSocket);
// Set up services
wireAllServices(app);
app.onService.listen((_) {
wireAllServices(app);
});
app.get(endpoint, (RequestContext req, ResponseContext res) async {
if (!WebSocketTransformer.isUpgradeRequest(req.underlyingRequest))
throw new AngelHttpException.BadRequest();
2016-09-03 12:43:34 +00:00
res
..willCloseItself = true
..end();
var ws = await WebSocketTransformer.upgrade(req.underlyingRequest);
2016-07-06 13:33:40 +00:00
_clients.add(ws);
var socket = new WebSocketContext(ws, req, res);
2016-07-06 13:33:40 +00:00
await onConnect(socket);
2016-09-18 01:35:16 +00:00
_onConnection.add(socket);
2016-09-17 20:00:17 +00:00
req.params['socket'] = socket;
ws.listen((data) {
onData(socket, data);
}, onDone: () {
_clients.remove(ws);
}, onError: (e) {
_clients.remove(ws);
}, cancelOnError: true);
});
}
}