loris/lib/business_logic/websocket.dart

62 lines
1.7 KiB
Dart

import 'dart:async';
import 'package:loris/business_logic/settings.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import '../global.dart' as global;
bool connected = false;
Map<String, Map<String, StreamController>> map = {};
Future<void> reloadWebsockets() async {
for (int i = 0; i < global.settings!.identities.length; i++) {
final idName = global.settings!.identities.keys.toList()[i];
final id = global.settings!.identities[idName]!;
Map<String, StreamController> idMap = {
"home": getStreamController(id, StreamType.user),
"local": getStreamController(id, StreamType.publicLocal),
"public": getStreamController(id, StreamType.publicLocal),
};
map.addAll(
{idName: idMap},
);
}
}
enum StreamType {
user,
public,
publicLocal,
}
extension StreamTypeExtension on StreamType {
String get name {
switch (this) {
case StreamType.user:
return "user";
case StreamType.public:
return "public";
case StreamType.publicLocal:
return "public:local";
}
}
}
StreamController getStreamController(AccountSettings id, StreamType type) {
var query = {
"stream": type.name,
"access_token": id.token,
};
var host = id.webSocketUrl;
host = host.replaceFirstMapped("wss://", (match) => "");
host = host.replaceFirstMapped("ws://", (match) => "");
const scheme = "wss";
const path = "/api/v1/streaming";
final uri =
Uri(scheme: scheme, host: host, path: path, queryParameters: query);
final controller = StreamController.broadcast();
final socket = WebSocketChannel.connect(uri);
controller.addStream(socket.stream);
return controller;
}