Files

942 lines
28 KiB
Dart
Raw Permalink Normal View History

import 'dart:async';
2022-03-19 23:28:29 +08:00
import 'dart:convert';
2022-03-19 23:28:29 +08:00
import 'package:flutter/material.dart';
2023-02-28 00:41:09 +09:00
import 'package:flutter_hbb/consts.dart';
2022-11-23 09:41:05 +08:00
import 'package:flutter_hbb/main.dart';
2024-06-13 18:30:29 +08:00
import 'package:flutter_hbb/mobile/pages/settings_page.dart';
2023-07-10 09:40:41 +08:00
import 'package:flutter_hbb/models/chat_model.dart';
2022-08-08 17:53:51 +08:00
import 'package:flutter_hbb/models/platform_model.dart';
import 'package:get/get.dart';
2022-10-26 21:39:28 +09:00
import 'package:window_manager/window_manager.dart';
2022-03-19 23:28:29 +08:00
import '../common.dart';
2022-09-02 17:19:44 +08:00
import '../common/formatter/id_formatter.dart';
2022-11-03 21:58:25 +08:00
import '../desktop/pages/server_page.dart' as desktop;
2022-08-22 20:18:31 +08:00
import '../desktop/widgets/tabbar_widget.dart';
2022-05-24 23:33:00 +08:00
import '../mobile/pages/server_page.dart';
2023-06-23 18:25:42 +08:00
import 'model.dart';
2022-03-19 23:28:29 +08:00
2022-09-29 13:07:20 +08:00
const kLoginDialogTag = "LOGIN";
2022-07-29 18:34:25 +08:00
const kUseTemporaryPassword = "use-temporary-password";
const kUsePermanentPassword = "use-permanent-password";
const kUseBothPasswords = "use-both-passwords";
2022-03-19 23:28:29 +08:00
class ServerModel with ChangeNotifier {
2022-04-17 11:34:46 +08:00
bool _isStart = false; // Android MainService status
2022-03-19 23:28:29 +08:00
bool _mediaOk = false;
bool _inputOk = false;
2022-03-28 17:24:52 +08:00
bool _audioOk = false;
bool _fileOk = false;
2024-12-07 22:34:54 +08:00
bool _clipboardOk = false;
2023-01-28 16:41:47 +08:00
bool _showElevation = false;
2023-08-30 11:48:42 +08:00
bool hideCm = false;
2023-06-23 18:25:42 +08:00
int _connectStatus = 0; // Rendezvous Server status
2022-07-29 18:34:25 +08:00
String _verificationMethod = "";
2022-08-01 20:42:30 +08:00
String _temporaryPasswordLength = "";
2025-05-23 17:10:47 +08:00
bool _allowNumericOneTimePassword = false;
2022-11-20 15:53:08 +08:00
String _approveMode = "";
int _zeroClientLengthCounter = 0;
2022-04-17 11:34:46 +08:00
late String _emptyIdShow;
2022-09-02 17:19:44 +08:00
late final IDTextEditingController _serverId;
2023-09-04 12:11:35 +08:00
final _serverPasswd =
TextEditingController(text: translate("Generating ..."));
2022-09-01 21:18:53 +08:00
final tabController = DesktopTabController(tabType: DesktopTabType.cm);
2022-08-22 20:18:31 +08:00
2022-09-06 21:20:53 -07:00
final List<Client> _clients = [];
2022-03-19 23:28:29 +08:00
2022-10-26 21:39:28 +09:00
Timer? cmHiddenTimer;
final _wakelockKey = UniqueKey();
bool get isStart => _isStart;
2022-03-19 23:28:29 +08:00
bool get mediaOk => _mediaOk;
bool get inputOk => _inputOk;
2022-03-22 21:47:42 +08:00
bool get audioOk => _audioOk;
bool get fileOk => _fileOk;
2024-12-07 22:34:54 +08:00
bool get clipboardOk => _clipboardOk;
2022-11-10 10:27:13 +08:00
bool get showElevation => _showElevation;
2023-06-23 18:25:42 +08:00
int get connectStatus => _connectStatus;
2022-08-01 20:42:30 +08:00
String get verificationMethod {
final index = [
kUseTemporaryPassword,
kUsePermanentPassword,
kUseBothPasswords
].indexOf(_verificationMethod);
if (index < 0) {
2022-08-13 12:43:35 +08:00
return kUseBothPasswords;
2022-08-01 20:42:30 +08:00
}
return _verificationMethod;
}
2022-11-20 15:53:08 +08:00
String get approveMode => _approveMode;
2022-09-06 21:20:53 -07:00
setVerificationMethod(String method) async {
2024-05-17 14:19:11 +08:00
await bind.mainSetOption(key: kOptionVerificationMethod, value: method);
2023-11-08 11:28:59 +08:00
/*
2022-11-23 09:41:05 +08:00
if (method != kUsePermanentPassword) {
await bind.mainSetOption(
key: 'allow-hide-cm', value: bool2option('allow-hide-cm', false));
}
2023-11-08 11:28:59 +08:00
*/
2022-08-01 20:42:30 +08:00
}
String get temporaryPasswordLength {
final lengthIndex = ["6", "8", "10"].indexOf(_temporaryPasswordLength);
if (lengthIndex < 0) {
2022-08-13 12:43:35 +08:00
return "6";
2022-08-01 20:42:30 +08:00
}
return _temporaryPasswordLength;
}
2022-09-06 21:20:53 -07:00
setTemporaryPasswordLength(String length) async {
await bind.mainSetOption(key: "temporary-password-length", value: length);
2022-08-01 20:42:30 +08:00
}
2022-07-29 18:34:25 +08:00
2022-11-20 15:53:08 +08:00
setApproveMode(String mode) async {
2024-05-17 14:19:11 +08:00
await bind.mainSetOption(key: kOptionApproveMode, value: mode);
2023-11-08 11:28:59 +08:00
/*
2022-11-23 09:41:05 +08:00
if (mode != 'password') {
await bind.mainSetOption(
key: 'allow-hide-cm', value: bool2option('allow-hide-cm', false));
}
2023-11-08 11:28:59 +08:00
*/
2022-11-20 15:53:08 +08:00
}
2025-05-23 17:10:47 +08:00
bool get allowNumericOneTimePassword => _allowNumericOneTimePassword;
switchAllowNumericOneTimePassword() async {
await mainSetBoolOption(
kOptionAllowNumericOneTimePassword, !_allowNumericOneTimePassword);
}
TextEditingController get serverId => _serverId;
TextEditingController get serverPasswd => _serverPasswd;
2022-08-22 20:18:31 +08:00
List<Client> get clients => _clients;
2022-03-19 23:28:29 +08:00
final controller = ScrollController();
WeakReference<FFI> parent;
ServerModel(this.parent) {
_emptyIdShow = translate("Generating ...");
2022-09-02 17:19:44 +08:00
_serverId = IDTextEditingController(text: _emptyIdShow);
2022-04-17 11:34:46 +08:00
2023-08-30 11:48:42 +08:00
/*
// initital _hideCm at startup
final verificationMethod =
bind.mainGetOptionSync(key: kOptionVerificationMethod);
final approveMode = bind.mainGetOptionSync(key: kOptionApproveMode);
_hideCm = option2bool(
'allow-hide-cm', bind.mainGetOptionSync(key: 'allow-hide-cm'));
if (!(approveMode == 'password' &&
verificationMethod == kUsePermanentPassword)) {
_hideCm = false;
}
2023-08-30 11:48:42 +08:00
*/
2022-11-20 15:53:08 +08:00
timerCallback() async {
2023-06-24 21:09:45 +08:00
final connectionStatus =
jsonDecode(await bind.mainGetConnectStatus()) as Map<String, dynamic>;
final statusNum = connectionStatus['status_num'] as int;
if (statusNum != _connectStatus) {
_connectStatus = statusNum;
2023-06-23 18:25:42 +08:00
notifyListeners();
}
2023-03-13 13:46:44 +08:00
if (desktopType == DesktopType.cm) {
final res = await bind.cmCheckClientsLength(length: _clients.length);
if (res != null) {
debugPrint("clients not match!");
updateClientState(res);
} else {
if (_clients.isEmpty) {
hideCmWindow();
if (_zeroClientLengthCounter++ == 12) {
// 6 second
windowManager.close();
}
} else {
_zeroClientLengthCounter = 0;
2023-08-30 11:48:42 +08:00
if (!hideCm) showCmWindow();
}
2023-03-13 13:46:44 +08:00
}
}
2022-07-29 18:34:25 +08:00
2022-07-29 22:07:45 +08:00
updatePasswordModel();
2022-11-20 15:53:08 +08:00
}
if (!isTest) {
2022-11-23 09:41:05 +08:00
Future.delayed(Duration.zero, () async {
if (await bind.optionSynced()) {
await timerCallback();
}
});
2022-11-20 15:53:08 +08:00
Timer.periodic(Duration(milliseconds: 500), (timer) async {
await timerCallback();
});
}
// Initial keyboard status is off on mobile
if (isMobile) {
bind.mainSetOption(key: kOptionEnableKeyboard, value: 'N');
}
2022-03-22 21:47:42 +08:00
}
/// 1. check android permission
/// 2. check config
/// audio true by default (if permission on) (false default < Android 10)
/// file true by default (if permission on)
checkAndroidPermission() async {
// audio
2023-02-28 00:41:09 +09:00
if (androidVersion < 30 ||
!await AndroidPermissionManager.check(kRecordAudio)) {
_audioOk = false;
bind.mainSetOption(key: kOptionEnableAudio, value: "N");
} else {
final audioOption = await bind.mainGetOption(key: kOptionEnableAudio);
2024-07-24 17:20:58 +08:00
_audioOk = audioOption != 'N';
}
// Android file transfer is confined to app-specific storage. Files enter
// and leave the workspace through Android's system document picker.
final fileOption = await bind.mainGetOption(key: kOptionEnableFileTransfer);
_fileOk = fileOption != 'N';
2024-12-07 22:34:54 +08:00
// clipboard
final clipOption = await bind.mainGetOption(key: kOptionEnableClipboard);
_clipboardOk = clipOption != 'N';
notifyListeners();
}
2022-08-08 17:53:51 +08:00
updatePasswordModel() async {
2022-07-29 22:07:45 +08:00
var update = false;
final temporaryPassword = await bind.mainGetTemporaryPassword();
2022-08-08 17:53:51 +08:00
final verificationMethod =
await bind.mainGetOption(key: kOptionVerificationMethod);
2022-08-08 17:53:51 +08:00
final temporaryPasswordLength =
await bind.mainGetOption(key: "temporary-password-length");
final approveMode = await bind.mainGetOption(key: kOptionApproveMode);
2025-05-23 17:10:47 +08:00
final numericOneTimePassword =
await mainGetBoolOption(kOptionAllowNumericOneTimePassword);
2023-08-30 11:48:42 +08:00
/*
2022-11-23 09:41:05 +08:00
var hideCm = option2bool(
'allow-hide-cm', await bind.mainGetOption(key: 'allow-hide-cm'));
if (!(approveMode == 'password' &&
verificationMethod == kUsePermanentPassword)) {
hideCm = false;
}
2023-08-30 11:48:42 +08:00
*/
2022-11-20 15:53:08 +08:00
if (_approveMode != approveMode) {
_approveMode = approveMode;
update = true;
}
2024-06-10 11:01:39 +08:00
var stopped = await mainGetBoolOption(kOptionStopService);
final oldPwdText = _serverPasswd.text;
if (stopped ||
verificationMethod == kUsePermanentPassword ||
2022-11-20 15:53:08 +08:00
_approveMode == 'click') {
2022-08-01 20:42:30 +08:00
_serverPasswd.text = '-';
} else {
if (_serverPasswd.text != temporaryPassword &&
temporaryPassword.isNotEmpty) {
_serverPasswd.text = temporaryPassword;
}
2022-08-01 20:42:30 +08:00
}
if (oldPwdText != _serverPasswd.text) {
2022-07-29 22:07:45 +08:00
update = true;
}
if (_verificationMethod != verificationMethod) {
_verificationMethod = verificationMethod;
update = true;
}
2022-08-01 20:42:30 +08:00
if (_temporaryPasswordLength != temporaryPasswordLength) {
if (_temporaryPasswordLength.isNotEmpty) {
bind.mainUpdateTemporaryPassword();
}
2022-08-01 20:42:30 +08:00
_temporaryPasswordLength = temporaryPasswordLength;
update = true;
}
2025-05-23 17:10:47 +08:00
if (_allowNumericOneTimePassword != numericOneTimePassword) {
_allowNumericOneTimePassword = numericOneTimePassword;
update = true;
}
2023-08-30 11:48:42 +08:00
/*
2022-11-23 09:41:05 +08:00
if (_hideCm != hideCm) {
_hideCm = hideCm;
if (desktopType == DesktopType.cm) {
if (hideCm) {
await hideCmWindow();
2022-11-23 09:41:05 +08:00
} else {
await showCmWindow();
2022-11-23 09:41:05 +08:00
}
}
update = true;
}
2023-08-30 11:48:42 +08:00
*/
2022-07-29 22:07:45 +08:00
if (update) {
notifyListeners();
}
}
toggleAudio() async {
if (clients.any((c) => !c.disconnected)) {
await showClientsMayNotBeChangedAlert(parent.target);
}
2023-02-28 00:41:09 +09:00
if (!_audioOk && !await AndroidPermissionManager.check(kRecordAudio)) {
final res = await AndroidPermissionManager.request(kRecordAudio);
2022-04-13 15:33:23 +08:00
if (!res) {
showToast(translate('Failed'));
return;
}
}
2022-03-22 21:47:42 +08:00
_audioOk = !_audioOk;
bind.mainSetOption(
key: kOptionEnableAudio, value: _audioOk ? defaultOptionYes : 'N');
2022-03-22 21:47:42 +08:00
notifyListeners();
}
toggleFile() async {
if (clients.any((c) => !c.disconnected)) {
await showClientsMayNotBeChangedAlert(parent.target);
}
_fileOk = !_fileOk;
bind.mainSetOption(
key: kOptionEnableFileTransfer,
value: _fileOk ? defaultOptionYes : 'N');
notifyListeners();
}
2024-12-07 22:34:54 +08:00
toggleClipboard() async {
_clipboardOk = !clipboardOk;
bind.mainSetOption(
key: kOptionEnableClipboard,
value: clipboardOk ? defaultOptionYes : 'N');
notifyListeners();
}
toggleInput() async {
if (clients.any((c) => !c.disconnected)) {
await showClientsMayNotBeChangedAlert(parent.target);
}
2022-04-13 15:33:23 +08:00
if (_inputOk) {
parent.target?.invokeMethod("stop_input");
2024-05-17 14:19:11 +08:00
bind.mainSetOption(key: kOptionEnableKeyboard, value: 'N');
2022-04-13 15:33:23 +08:00
} else {
if (parent.target != null) {
2023-03-07 11:21:23 +09:00
/// the result of toggle-on depends on user actions in the settings page.
/// handle result, see [ServerModel.changeStatue]
showInputWarnAlert(parent.target!);
}
2022-03-22 21:47:42 +08:00
}
}
Future<bool> checkRequestNotificationPermission() async {
debugPrint("androidVersion $androidVersion");
if (androidVersion < 33) {
return true;
}
if (await AndroidPermissionManager.check(kAndroid13Notification)) {
debugPrint("notification permission already granted");
return true;
}
var res = await AndroidPermissionManager.request(kAndroid13Notification);
debugPrint("notification permission request result: $res");
return res;
}
2024-06-05 23:11:44 +08:00
Future<bool> checkFloatingWindowPermission() async {
debugPrint("androidVersion $androidVersion");
if (androidVersion < 23) {
return false;
}
if (await AndroidPermissionManager.check(kSystemAlertWindow)) {
debugPrint("alert window permission already granted");
return true;
}
var res = await AndroidPermissionManager.request(kSystemAlertWindow);
debugPrint("alert window permission request result: $res");
return res;
}
2022-05-29 04:39:12 +08:00
/// Toggle the screen sharing service.
2022-03-22 21:47:42 +08:00
toggleService() async {
2022-04-13 15:33:23 +08:00
if (_isStart) {
2023-05-20 15:12:52 +02:00
final res = await parent.target?.dialogManager
.show<bool>((setState, close, context) {
2022-09-03 18:19:50 +08:00
submit() => close(true);
return CustomAlertDialog(
title: Row(children: [
const Icon(Icons.warning_amber_sharp,
color: Colors.redAccent, size: 28),
const SizedBox(width: 10),
Text(translate("Warning")),
]),
content: Text(translate("android_stop_service_tip")),
actions: [
TextButton(onPressed: close, child: Text(translate("Cancel"))),
2023-03-02 03:50:04 +01:00
TextButton(onPressed: submit, child: Text(translate("OK"))),
2022-09-03 18:19:50 +08:00
],
onSubmit: submit,
onCancel: close,
);
});
2022-04-13 15:33:23 +08:00
if (res == true) {
2022-03-22 21:47:42 +08:00
stopService();
}
2022-04-13 15:33:23 +08:00
} else {
await checkRequestNotificationPermission();
2024-06-05 23:11:44 +08:00
if (bind.mainGetLocalOption(key: kOptionDisableFloatingWindow) != 'Y') {
await checkFloatingWindowPermission();
}
2023-05-20 15:12:52 +02:00
final res = await parent.target?.dialogManager
.show<bool>((setState, close, context) {
2022-09-03 18:19:50 +08:00
submit() => close(true);
return CustomAlertDialog(
title: Row(children: [
const Icon(Icons.warning_amber_sharp,
color: Colors.redAccent, size: 28),
const SizedBox(width: 10),
Text(translate("Warning")),
]),
content: Text(translate("android_service_will_start_tip")),
actions: [
2023-01-15 19:46:16 +08:00
dialogButton("Cancel", onPressed: close, isOutline: true),
dialogButton("OK", onPressed: submit),
2022-09-03 18:19:50 +08:00
],
onSubmit: submit,
onCancel: close,
);
});
2022-04-13 15:33:23 +08:00
if (res == true) {
2022-03-22 21:47:42 +08:00
startService();
}
}
}
2022-05-29 04:39:12 +08:00
/// Start the screen sharing service.
2022-11-03 21:58:25 +08:00
Future<void> startService() async {
_isStart = true;
notifyListeners();
2023-06-06 07:39:44 +08:00
parent.target?.ffiModel.updateEventListener(parent.target!.sessionId, "");
await parent.target?.invokeMethod("init_service");
2023-01-26 11:05:23 +08:00
// ugly is here, because for desktop, below is useless
await bind.mainStartService();
2022-04-15 17:45:48 +08:00
updateClientState();
2024-03-24 11:23:06 +08:00
if (isAndroid) {
2024-06-13 18:30:29 +08:00
androidUpdatekeepScreenOn();
}
}
2022-05-29 04:39:12 +08:00
/// Stop the screen sharing service.
2022-11-03 21:58:25 +08:00
Future<void> stopService() async {
_isStart = false;
2022-08-12 18:42:02 +08:00
closeAll();
await parent.target?.invokeMethod("stop_service");
await bind.mainStopService();
notifyListeners();
// for androidUpdatekeepScreenOn only
WakelockManager.disable(_wakelockKey);
}
2022-11-29 22:36:35 +08:00
fetchID() async {
final id = await bind.mainGetMyId();
if (id != _serverId.id) {
_serverId.id = id;
notifyListeners();
}
}
2022-03-19 23:28:29 +08:00
changeStatue(String name, bool value) {
debugPrint("changeStatue value $value");
2022-03-19 23:28:29 +08:00
switch (name) {
case "media":
_mediaOk = value;
2022-04-13 15:33:23 +08:00
if (value && !_isStart) {
startService();
}
2022-03-19 23:28:29 +08:00
break;
case "input":
2022-04-13 15:33:23 +08:00
if (_inputOk != value) {
bind.mainSetOption(
key: kOptionEnableKeyboard,
value: value ? defaultOptionYes : 'N');
2022-03-22 21:47:42 +08:00
}
2022-03-19 23:28:29 +08:00
_inputOk = value;
break;
default:
return;
}
notifyListeners();
}
2022-08-22 20:18:31 +08:00
// force
updateClientState([String? json]) async {
2022-10-20 23:05:34 +09:00
if (isTest) return;
var res = await bind.cmGetClientsState();
2023-07-31 20:02:01 +08:00
List<dynamic> clientsJson;
2022-03-19 23:28:29 +08:00
try {
2023-07-31 20:02:01 +08:00
clientsJson = jsonDecode(res);
} catch (e) {
debugPrint("Failed to decode clientsJson: '$res', error $e");
return;
}
final oldClientLenght = _clients.length;
2023-07-31 20:02:01 +08:00
_clients.clear();
tabController.state.value.tabs.clear();
for (var clientJson in clientsJson) {
try {
2022-04-15 17:45:48 +08:00
final client = Client.fromJson(clientJson);
2022-08-22 20:18:31 +08:00
_clients.add(client);
2022-10-26 21:39:28 +09:00
_addTab(client);
2023-07-31 20:02:01 +08:00
} catch (e) {
debugPrint("Failed to decode clientJson '$clientJson', error $e");
2022-03-25 16:34:27 +08:00
}
2022-04-15 17:45:48 +08:00
}
if (desktopType == DesktopType.cm) {
if (_clients.isEmpty) {
hideCmWindow();
2023-08-30 11:48:42 +08:00
} else if (!hideCm) {
showCmWindow();
}
}
if (_clients.length != oldClientLenght) {
notifyListeners();
2024-06-13 18:30:29 +08:00
if (isAndroid) androidUpdatekeepScreenOn();
}
2022-03-19 23:28:29 +08:00
}
void addConnection(Map<String, dynamic> evt) {
try {
2022-03-19 23:28:29 +08:00
final client = Client.fromJson(jsonDecode(evt["client"]));
if (client.authorized) {
parent.target?.dialogManager.dismissByTag(getLoginDialogTag(client.id));
final index = _clients.indexWhere((c) => c.id == client.id);
if (index < 0) {
_clients.add(client);
} else {
if (_clients[index].authorized) {
_clients[index].privacyMode = client.privacyMode;
notifyListeners();
return;
}
_clients[index].authorized = true;
_clients[index].privacyMode = client.privacyMode;
}
} else {
final index = _clients.indexWhere((c) => c.id == client.id);
if (index >= 0) {
_clients[index].privacyMode = client.privacyMode;
notifyListeners();
return;
}
_clients.add(client);
2022-04-19 13:07:45 +08:00
}
2022-10-26 21:39:28 +09:00
_addTab(client);
2022-10-08 20:15:02 +08:00
// remove disconnected
final index_disconnected = _clients
.indexWhere((c) => c.disconnected && c.peerId == client.peerId);
if (index_disconnected >= 0) {
_clients.removeAt(index_disconnected);
tabController.remove(index_disconnected);
}
2023-08-30 11:48:42 +08:00
if (desktopType == DesktopType.cm && !hideCm) {
showCmWindow();
}
2022-10-08 20:15:02 +08:00
scrollToBottom();
notifyListeners();
if (isAndroid && !client.authorized) showLoginDialog(client);
2024-06-13 18:30:29 +08:00
if (isAndroid) androidUpdatekeepScreenOn();
} catch (e) {
2022-04-19 13:07:45 +08:00
debugPrint("Failed to call loginRequest,error:$e");
}
}
2022-10-26 21:39:28 +09:00
void _addTab(Client client) {
tabController.add(TabInfo(
key: client.id.toString(),
label: client.name,
closable: false,
2023-07-08 11:09:50 +08:00
onTap: () {},
2022-11-03 21:58:25 +08:00
page: desktop.buildConnectionCard(client)));
2022-10-26 21:39:28 +09:00
Future.delayed(Duration.zero, () async {
if (!hideCm) windowOnTop(null);
2022-10-26 21:39:28 +09:00
});
2023-03-07 10:56:35 +08:00
// Only do the hidden task when on Desktop.
if (client.authorized && isDesktop) {
2022-10-26 21:39:28 +09:00
cmHiddenTimer = Timer(const Duration(seconds: 3), () {
2022-11-23 09:41:05 +08:00
if (!hideCm) windowManager.minimize();
2022-10-26 21:39:28 +09:00
cmHiddenTimer = null;
});
}
2023-07-10 09:40:41 +08:00
parent.target?.chatModel
.updateConnIdOfKey(MessageKey(client.peerId, client.id));
2022-10-26 21:39:28 +09:00
}
2022-04-19 13:07:45 +08:00
void showLoginDialog(Client client) {
showClientDialog(
client,
client.isFileTransfer
? "Transfer file"
2025-07-01 13:12:55 +08:00
: client.isViewCamera
? "View camera"
: client.isTerminal
? "Terminal"
2025-07-01 13:12:55 +08:00
: "Share screen",
'Do you accept?',
'android_new_connection_tip',
() => sendLoginResponse(client, false),
() => sendLoginResponse(client, true),
);
}
handleVoiceCall(Client client, bool accept) {
parent.target?.invokeMethod("cancel_notification", client.id);
bind.cmHandleIncomingVoiceCall(id: client.id, accept: accept);
}
showVoiceCallDialog(Client client) {
showClientDialog(
client,
'Voice call',
'Do you accept?',
'android_new_voice_call_tip',
() => handleVoiceCall(client, false),
() => handleVoiceCall(client, true),
);
}
showClientDialog(Client client, String title, String contentTitle,
String content, VoidCallback onCancel, VoidCallback onSubmit) {
2023-05-08 12:34:19 +08:00
parent.target?.dialogManager.show((setState, close, context) {
2022-09-03 18:19:50 +08:00
cancel() {
onCancel();
2022-09-03 18:19:50 +08:00
close();
}
submit() {
onSubmit();
2022-09-03 18:19:50 +08:00
close();
}
return CustomAlertDialog(
title:
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
Text(translate(title)),
IconButton(onPressed: close, icon: const Icon(Icons.close))
2022-09-03 18:19:50 +08:00
]),
content: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(translate(contentTitle)),
2022-09-29 21:53:50 +08:00
ClientInfo(client),
2022-09-03 18:19:50 +08:00
Text(
translate(content),
style: Theme.of(globalKey.currentContext!).textTheme.bodyMedium,
2022-04-19 13:07:45 +08:00
),
2022-09-03 18:19:50 +08:00
],
),
actions: [
2023-01-15 19:46:16 +08:00
dialogButton("Dismiss", onPressed: cancel, isOutline: true),
2023-06-28 20:22:57 +08:00
if (approveMode != 'password')
dialogButton("Accept", onPressed: submit),
2022-09-03 18:19:50 +08:00
],
onSubmit: submit,
onCancel: cancel,
);
}, tag: getLoginDialogTag(client.id));
2022-04-19 13:07:45 +08:00
}
scrollToBottom() {
2022-08-22 20:18:31 +08:00
if (isDesktop) return;
Future.delayed(Duration(milliseconds: 200), () {
controller.animateTo(controller.position.maxScrollExtent,
duration: Duration(milliseconds: 200),
curve: Curves.fastLinearToSlowEaseIn);
});
}
void sendLoginResponse(Client client, bool res) async {
2022-04-19 13:07:45 +08:00
if (res) {
2022-08-17 17:23:55 +08:00
bind.cmLoginRes(connId: client.id, res: res);
2025-07-01 13:12:55 +08:00
if (!client.isFileTransfer && !client.isTerminal) {
parent.target?.invokeMethod("start_capture");
2022-04-19 13:07:45 +08:00
}
parent.target?.invokeMethod("cancel_notification", client.id);
2022-08-22 20:18:31 +08:00
client.authorized = true;
2022-04-19 13:07:45 +08:00
notifyListeners();
} else {
2022-08-17 17:23:55 +08:00
bind.cmLoginRes(connId: client.id, res: res);
parent.target?.invokeMethod("cancel_notification", client.id);
2022-08-22 20:18:31 +08:00
final index = _clients.indexOf(client);
2022-08-24 21:52:21 +08:00
tabController.remove(index);
2022-08-22 20:18:31 +08:00
_clients.remove(client);
2024-06-13 18:30:29 +08:00
if (isAndroid) androidUpdatekeepScreenOn();
2022-03-19 23:28:29 +08:00
}
}
void onClientRemove(Map<String, dynamic> evt) {
try {
2022-03-19 23:28:29 +08:00
final id = int.parse(evt['id'] as String);
2022-10-08 20:15:02 +08:00
final close = (evt['close'] as String) == 'true';
2022-08-22 20:18:31 +08:00
if (_clients.any((c) => c.id == id)) {
final index = _clients.indexWhere((client) => client.id == id);
2022-09-01 21:18:53 +08:00
if (index >= 0) {
2022-10-08 20:15:02 +08:00
if (close) {
_clients.removeAt(index);
tabController.remove(index);
} else {
_clients[index].disconnected = true;
}
2022-09-01 21:18:53 +08:00
}
2022-08-12 18:42:02 +08:00
parent.target?.dialogManager.dismissByTag(getLoginDialogTag(id));
parent.target?.invokeMethod("cancel_notification", id);
2022-03-29 23:10:43 +08:00
}
if (desktopType == DesktopType.cm && _clients.isEmpty) {
hideCmWindow();
}
2024-06-13 18:30:29 +08:00
if (isAndroid) androidUpdatekeepScreenOn();
2022-03-19 23:28:29 +08:00
notifyListeners();
} catch (e) {
2022-03-19 23:28:29 +08:00
debugPrint("onClientRemove failed,error:$e");
}
}
/// `byOperator` false means the CM's window went away rather than a person asking for the
/// peers to go. The sessions end either way; only the close reason differs, and with it
/// whether the peer is allowed to reconnect. See `ipc::Data::CmWindowClosed`.
Future<void> closeAll({bool byOperator = true}) async {
await Future.wait(_clients.map((client) => byOperator
? bind.cmCloseConnection(connId: client.id)
: bind.cmCloseConnectionWindow(connId: client.id)));
2022-03-25 16:34:27 +08:00
_clients.clear();
2022-08-24 21:52:21 +08:00
tabController.state.value.tabs.clear();
2024-06-13 18:30:29 +08:00
if (isAndroid) androidUpdatekeepScreenOn();
2022-08-24 21:52:21 +08:00
}
void jumpTo(int id) {
final index = _clients.indexWhere((client) => client.id == id);
tabController.jumpTo(index);
2022-03-19 23:28:29 +08:00
}
2022-11-10 10:27:13 +08:00
void setShowElevation(bool show) {
if (_showElevation != show) {
_showElevation = show;
notifyListeners();
}
}
2023-02-07 16:11:55 +08:00
void updateVoiceCallState(Map<String, dynamic> evt) {
try {
final client = Client.fromJson(jsonDecode(evt["client"]));
final index = _clients.indexWhere((element) => element.id == client.id);
if (index != -1) {
2023-02-07 16:47:19 +08:00
_clients[index].inVoiceCall = client.inVoiceCall;
_clients[index].incomingVoiceCall = client.incomingVoiceCall;
2023-02-07 17:09:36 +08:00
if (client.incomingVoiceCall) {
if (isAndroid) {
showVoiceCallDialog(client);
} else {
// Has incoming phone call, let's set the window on top.
Future.delayed(Duration.zero, () {
windowOnTop(null);
});
}
2023-02-07 17:09:36 +08:00
}
2023-02-07 16:11:55 +08:00
notifyListeners();
}
} catch (e) {
debugPrint("updateVoiceCallState failed: $e");
}
}
2024-06-13 18:30:29 +08:00
void androidUpdatekeepScreenOn() async {
if (!isAndroid) return;
var floatingWindowDisabled =
bind.mainGetLocalOption(key: kOptionDisableFloatingWindow) == "Y" ||
!await AndroidPermissionManager.check(kSystemAlertWindow);
final keepScreenOn = floatingWindowDisabled
? KeepScreenOn.never
: optionToKeepScreenOn(
bind.mainGetLocalOption(key: kOptionKeepScreenOn));
final on = ((keepScreenOn == KeepScreenOn.serviceOn) && _isStart) ||
(keepScreenOn == KeepScreenOn.duringControlled &&
_clients.map((e) => !e.disconnected).isNotEmpty);
if (on) {
WakelockManager.enable(_wakelockKey, isServer: true);
} else {
WakelockManager.disable(_wakelockKey);
2024-06-13 18:30:29 +08:00
}
}
2022-03-19 23:28:29 +08:00
}
enum ClientType {
remote,
file,
2025-03-10 21:06:53 +08:00
camera,
portForward,
2025-07-01 13:12:55 +08:00
terminal,
}
2022-03-19 23:28:29 +08:00
class Client {
2022-03-22 21:47:42 +08:00
int id = 0; // client connections inner count id
2022-03-19 23:28:29 +08:00
bool authorized = false;
bool isFileTransfer = false;
2025-03-10 21:06:53 +08:00
bool isViewCamera = false;
2025-07-01 13:12:55 +08:00
bool isTerminal = false;
String portForward = "";
2022-03-19 23:28:29 +08:00
String name = "";
2026-03-04 21:43:19 +08:00
String avatar = "";
2022-03-22 21:47:42 +08:00
String peerId = ""; // peer user's id,show at app
bool keyboard = false;
bool clipboard = false;
bool audio = false;
2022-08-18 19:49:41 +08:00
bool file = false;
bool restart = false;
2022-09-22 09:55:34 +08:00
bool recording = false;
2023-11-05 21:53:21 +08:00
bool blockInput = false;
bool privacyMode = false;
2022-10-08 20:15:02 +08:00
bool disconnected = false;
2023-01-17 13:28:33 +08:00
bool fromSwitch = false;
2023-02-07 16:11:55 +08:00
bool inVoiceCall = false;
bool incomingVoiceCall = false;
2022-03-19 23:28:29 +08:00
2023-07-05 17:01:33 +08:00
RxInt unreadChatMessageCount = 0.obs;
2025-05-23 17:10:47 +08:00
Client(this.id, this.authorized, this.isFileTransfer, this.isViewCamera,
this.name, this.peerId, this.keyboard, this.clipboard, this.audio);
2022-03-19 23:28:29 +08:00
Client.fromJson(Map<String, dynamic> json) {
id = json['id'];
authorized = json['authorized'];
isFileTransfer = json['is_file_transfer'];
2025-03-10 21:06:53 +08:00
// TODO: no entry then default.
isViewCamera = json['is_view_camera'];
2025-07-01 13:12:55 +08:00
isTerminal = json['is_terminal'] ?? false;
portForward = json['port_forward'];
2022-03-19 23:28:29 +08:00
name = json['name'];
2026-03-04 21:43:19 +08:00
avatar = json['avatar'] ?? '';
2022-03-19 23:28:29 +08:00
peerId = json['peer_id'];
2022-04-13 15:33:23 +08:00
keyboard = json['keyboard'];
clipboard = json['clipboard'];
audio = json['audio'];
2022-08-18 19:49:41 +08:00
file = json['file'];
restart = json['restart'];
2022-09-22 09:55:34 +08:00
recording = json['recording'];
2023-11-05 21:53:21 +08:00
blockInput = json['block_input'];
privacyMode = json['privacy_mode'] ?? privacyMode;
2022-10-08 20:15:02 +08:00
disconnected = json['disconnected'];
2023-01-17 13:28:33 +08:00
fromSwitch = json['from_switch'];
2023-02-07 16:11:55 +08:00
inVoiceCall = json['in_voice_call'];
incomingVoiceCall = json['incoming_voice_call'];
2022-03-19 23:28:29 +08:00
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
2022-10-08 20:15:02 +08:00
data['id'] = id;
data['authorized'] = authorized;
2022-10-08 20:15:02 +08:00
data['is_file_transfer'] = isFileTransfer;
2025-03-10 21:06:53 +08:00
data['is_view_camera'] = isViewCamera;
2025-07-01 13:12:55 +08:00
data['is_terminal'] = isTerminal;
data['port_forward'] = portForward;
2022-10-08 20:15:02 +08:00
data['name'] = name;
2026-03-04 21:43:19 +08:00
data['avatar'] = avatar;
2022-10-08 20:15:02 +08:00
data['peer_id'] = peerId;
data['keyboard'] = keyboard;
data['clipboard'] = clipboard;
data['audio'] = audio;
2022-10-16 12:32:52 +08:00
data['file'] = file;
data['restart'] = restart;
data['recording'] = recording;
2023-11-05 21:53:21 +08:00
data['block_input'] = blockInput;
data['privacy_mode'] = privacyMode;
2022-10-08 20:15:02 +08:00
data['disconnected'] = disconnected;
2023-01-17 13:28:33 +08:00
data['from_switch'] = fromSwitch;
data['in_voice_call'] = inVoiceCall;
data['incoming_voice_call'] = incomingVoiceCall;
2022-03-19 23:28:29 +08:00
return data;
}
ClientType type_() {
if (isFileTransfer) {
return ClientType.file;
2025-03-10 21:06:53 +08:00
} else if (isViewCamera) {
return ClientType.camera;
2025-07-01 13:12:55 +08:00
} else if (isTerminal) {
return ClientType.terminal;
} else if (portForward.isNotEmpty) {
return ClientType.portForward;
} else {
return ClientType.remote;
}
}
2022-03-19 23:28:29 +08:00
}
2022-03-22 21:47:42 +08:00
2022-04-19 13:07:45 +08:00
String getLoginDialogTag(int id) {
2022-09-29 13:07:20 +08:00
return kLoginDialogTag + id.toString();
2022-04-19 13:07:45 +08:00
}
showInputWarnAlert(FFI ffi) {
2023-05-08 12:34:19 +08:00
ffi.dialogManager.show((setState, close, context) {
2022-09-03 18:19:50 +08:00
submit() {
AndroidPermissionManager.startAction(kActionAccessibilitySettings);
2022-09-03 18:19:50 +08:00
close();
}
return CustomAlertDialog(
title: Text(translate("How to get Android input permission?")),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(translate("android_input_permission_tip1")),
const SizedBox(height: 10),
Text(translate("android_input_permission_tip2")),
2022-04-19 13:07:45 +08:00
],
2022-09-03 18:19:50 +08:00
),
actions: [
2023-01-15 19:46:16 +08:00
dialogButton("Cancel", onPressed: close, isOutline: true),
dialogButton("Open System Setting", onPressed: submit),
2022-09-03 18:19:50 +08:00
],
onSubmit: submit,
onCancel: close,
);
});
2022-03-22 21:47:42 +08:00
}
Future<void> showClientsMayNotBeChangedAlert(FFI? ffi) async {
2023-05-08 12:34:19 +08:00
await ffi?.dialogManager.show((setState, close, context) {
return CustomAlertDialog(
title: Text(translate("Permissions")),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(translate("android_permission_may_not_change_tip")),
],
),
actions: [
dialogButton("OK", onPressed: close),
],
onSubmit: close,
onCancel: close,
);
});
}