2024-05-26 05:39:21 +00:00
|
|
|
import 'dart:async';
|
|
|
|
import 'dart:convert';
|
|
|
|
import 'dart:io';
|
|
|
|
|
|
|
|
import 'package:get/get.dart';
|
|
|
|
import 'package:solian/models/packet.dart';
|
|
|
|
import 'package:solian/providers/auth.dart';
|
|
|
|
import 'package:solian/services.dart';
|
2024-07-06 09:39:19 +00:00
|
|
|
import 'package:web_socket_channel/web_socket_channel.dart';
|
2024-05-26 05:39:21 +00:00
|
|
|
|
|
|
|
class ChatProvider extends GetxController {
|
|
|
|
RxBool isConnected = false.obs;
|
|
|
|
RxBool isConnecting = false.obs;
|
|
|
|
|
2024-07-06 09:39:19 +00:00
|
|
|
WebSocketChannel? websocket;
|
2024-05-26 05:39:21 +00:00
|
|
|
|
|
|
|
StreamController<NetworkPackage> stream = StreamController.broadcast();
|
|
|
|
|
|
|
|
void connect({noRetry = false}) async {
|
2024-06-03 15:36:46 +00:00
|
|
|
if (isConnected.value) {
|
|
|
|
return;
|
|
|
|
} else {
|
|
|
|
disconnect();
|
|
|
|
}
|
2024-06-02 15:20:34 +00:00
|
|
|
|
2024-05-26 05:39:21 +00:00
|
|
|
final AuthProvider auth = Get.find();
|
2024-06-09 15:00:11 +00:00
|
|
|
await auth.ensureCredentials();
|
2024-05-26 05:39:21 +00:00
|
|
|
|
2024-06-29 09:35:18 +00:00
|
|
|
if (globalCredentials == null) await auth.loadCredentials();
|
|
|
|
|
2024-05-26 05:39:21 +00:00
|
|
|
final uri = Uri.parse(
|
2024-06-29 09:35:18 +00:00
|
|
|
'${ServiceFinder.services['messaging']}/api/ws?tk=${globalCredentials!.accessToken}'
|
2024-05-26 05:39:21 +00:00
|
|
|
.replaceFirst('http', 'ws'),
|
|
|
|
);
|
|
|
|
|
|
|
|
isConnecting.value = true;
|
|
|
|
|
|
|
|
try {
|
2024-07-06 09:39:19 +00:00
|
|
|
websocket = WebSocketChannel.connect(uri);
|
2024-05-26 05:39:21 +00:00
|
|
|
await websocket?.ready;
|
|
|
|
} catch (e) {
|
|
|
|
if (!noRetry) {
|
|
|
|
await auth.refreshCredentials();
|
|
|
|
return connect(noRetry: true);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
listen();
|
|
|
|
|
|
|
|
isConnected.value = true;
|
|
|
|
isConnecting.value = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
void disconnect() {
|
|
|
|
websocket?.sink.close(WebSocketStatus.normalClosure);
|
2024-06-02 15:20:34 +00:00
|
|
|
websocket = null;
|
2024-05-26 05:39:21 +00:00
|
|
|
isConnected.value = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
void listen() {
|
|
|
|
websocket?.stream.listen(
|
|
|
|
(event) {
|
|
|
|
final packet = NetworkPackage.fromJson(jsonDecode(event));
|
|
|
|
stream.sink.add(packet);
|
|
|
|
},
|
|
|
|
onDone: () {
|
|
|
|
isConnected.value = false;
|
2024-06-08 13:35:50 +00:00
|
|
|
Future.delayed(const Duration(seconds: 1), () => connect());
|
2024-05-26 05:39:21 +00:00
|
|
|
},
|
|
|
|
onError: (err) {
|
|
|
|
isConnected.value = false;
|
2024-06-06 12:49:18 +00:00
|
|
|
Future.delayed(const Duration(seconds: 3), () => connect());
|
2024-05-26 05:39:21 +00:00
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|