rustdesk/flutter/lib/mobile/pages/settings_page.dart

483 lines
14 KiB
Dart
Raw Normal View History

import 'dart:async';
2022-03-28 15:44:45 +08:00
import 'dart:convert';
import 'package:flutter/material.dart';
2022-03-28 15:44:45 +08:00
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';
import 'package:settings_ui/settings_ui.dart';
import 'package:url_launcher/url_launcher.dart';
2022-05-24 23:33:00 +08:00
import '../../common.dart';
import '../../models/model.dart';
2022-08-05 20:29:43 +08:00
import '../../models/platform_model.dart';
import '../widgets/dialog.dart';
import 'home_page.dart';
2022-04-15 17:50:15 +08:00
import 'scan_page.dart';
2022-03-28 15:44:45 +08:00
class SettingsPage extends StatefulWidget implements PageShape {
@override
2022-03-23 15:28:21 +08:00
final title = translate("Settings");
@override
final icon = Icon(Icons.settings);
@override
2022-04-15 17:50:15 +08:00
final appBarActions = [ScanButton()];
2022-03-28 15:44:45 +08:00
@override
_SettingsState createState() => _SettingsState();
}
2022-08-04 17:24:02 +08:00
const url = 'https://rustdesk.com/';
final _hasIgnoreBattery = androidVersion >= 26;
var _ignoreBatteryOpt = false;
2022-08-04 17:24:02 +08:00
class _SettingsState extends State<SettingsPage> with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
if (_hasIgnoreBattery) {
updateIgnoreBatteryStatus();
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
updateIgnoreBatteryStatus();
}
}
Future<bool> updateIgnoreBatteryStatus() async {
final res = await PermissionManager.check("ignore_battery_optimizations");
if (_ignoreBatteryOpt != res) {
setState(() {
_ignoreBatteryOpt = res;
});
return true;
} else {
return false;
}
}
@override
Widget build(BuildContext context) {
2022-03-28 15:44:45 +08:00
Provider.of<FfiModel>(context);
final username = getUsername();
2022-08-01 14:33:08 +08:00
final enableAbr = gFFI.getByName("option", "enable-abr") != 'N';
2022-07-14 18:33:41 +08:00
final enhancementsTiles = [
SettingsTile.switchTile(
title: Text(translate('Adaptive Bitrate') + '(beta)'),
initialValue: enableAbr,
onToggle: (v) {
final msg = Map()
..["name"] = "enable-abr"
..["value"] = "";
if (!v) {
msg["value"] = "N";
}
2022-08-01 14:33:08 +08:00
gFFI.setByName("option", json.encode(msg));
2022-07-14 18:33:41 +08:00
setState(() {});
},
2022-07-14 18:33:41 +08:00
)
];
if (_hasIgnoreBattery) {
2022-07-14 18:33:41 +08:00
enhancementsTiles.insert(
0,
SettingsTile.switchTile(
initialValue: _ignoreBatteryOpt,
2022-07-14 18:33:41 +08:00
title: Text(translate('Keep RustDesk background service')),
description:
Text('* ${translate('Ignore Battery Optimizations')}'),
onToggle: (v) async {
if (v) {
PermissionManager.request("ignore_battery_optimizations");
} else {
final res = await DialogManager.show<bool>(
(setState, close) => CustomAlertDialog(
title: Text(translate("Open System Setting")),
content: Text(translate(
"android_open_battery_optimizations_tip")),
actions: [
TextButton(
onPressed: () => close(),
child: Text(translate("Cancel"))),
ElevatedButton(
onPressed: () => close(true),
child:
Text(translate("Open System Setting"))),
],
));
if (res == true) {
PermissionManager.request("application_details_settings");
2022-07-14 18:33:41 +08:00
}
}
2022-07-14 18:33:41 +08:00
}));
}
return SettingsList(
sections: [
SettingsSection(
2022-04-05 00:51:47 +08:00
title: Text(translate("Account")),
2022-03-28 15:44:45 +08:00
tiles: [
SettingsTile.navigation(
title: Text(username == null
? translate("Login")
: translate("Logout") + ' ($username)'),
leading: Icon(Icons.person),
onPressed: (context) {
if (username == null) {
showLogin();
} else {
logout();
}
},
),
],
),
2022-07-14 18:33:41 +08:00
SettingsSection(title: Text(translate("Settings")), tiles: [
SettingsTile.navigation(
2022-03-24 21:31:47 +08:00
title: Text(translate('ID/Relay Server')),
leading: Icon(Icons.cloud),
onPressed: (context) {
2022-04-15 17:50:15 +08:00
showServerSettings();
2022-08-04 17:24:02 +08:00
}),
SettingsTile.navigation(
title: Text(translate('Language')),
leading: Icon(Icons.translate),
onPressed: (context) {
showLanguageSettings();
2022-07-17 16:47:19 +08:00
})
2022-07-14 18:33:41 +08:00
]),
2022-03-28 15:44:45 +08:00
SettingsSection(
2022-07-14 18:33:41 +08:00
title: Text(translate("Enhancements")),
tiles: enhancementsTiles,
),
SettingsSection(
2022-03-28 15:44:45 +08:00
title: Text(translate("About")),
tiles: [
SettingsTile.navigation(
2022-04-15 17:50:15 +08:00
onPressed: (context) async {
if (await canLaunchUrl(Uri.parse(url))) {
await launchUrl(Uri.parse(url));
2022-04-15 17:50:15 +08:00
}
},
2022-03-28 15:44:45 +08:00
title: Text(translate("Version: ") + version),
2022-04-15 17:50:15 +08:00
value: Padding(
padding: EdgeInsets.symmetric(vertical: 8),
child: Text('rustdesk.com',
style: TextStyle(
decoration: TextDecoration.underline,
)),
),
leading: Icon(Icons.info)),
],
),
],
);
}
}
2022-04-15 17:50:15 +08:00
void showServerSettings() {
final id = gFFI.getByName('option', 'custom-rendezvous-server');
final relay = gFFI.getByName('option', 'relay-server');
final api = gFFI.getByName('option', 'api-server');
final key = gFFI.getByName('option', 'key');
2022-04-15 17:50:15 +08:00
showServerSettingsWithValue(id, relay, key, api);
}
2022-03-24 20:57:30 +08:00
2022-08-05 20:29:43 +08:00
void showLanguageSettings() async {
2022-08-04 17:24:02 +08:00
try {
final langs = json.decode(gFFI.getByName('langs')) as List<dynamic>;
2022-08-05 20:29:43 +08:00
var lang = await bind.mainGetLocalOption(key: "lang");
2022-08-04 17:24:02 +08:00
DialogManager.show((setState, close) {
final setLang = (v) {
if (lang != v) {
setState(() {
lang = v;
});
2022-08-05 20:29:43 +08:00
bind.mainSetLocalOption(key: "lang", value: v);
HomePage.homeKey.currentState?.refreshPages();
2022-08-04 17:24:02 +08:00
Future.delayed(Duration(milliseconds: 200), close);
}
};
return CustomAlertDialog(
title: SizedBox.shrink(),
content: Column(
children: [
getRadio('Default', '', lang, setLang),
Divider(color: MyTheme.border),
] +
langs.map((e) {
final key = e[0] as String;
final name = e[1] as String;
return getRadio(name, key, lang, setLang);
}).toList(),
),
actions: []);
}, backDismiss: true, clickMaskDismiss: true);
} catch (_e) {}
}
2022-03-24 20:57:30 +08:00
void showAbout() {
DialogManager.show((setState, close) {
return CustomAlertDialog(
title: Text(translate('About') + ' RustDesk'),
content: Wrap(direction: Axis.vertical, spacing: 12, children: [
Text('Version: $version'),
InkWell(
onTap: () async {
const url = 'https://rustdesk.com/';
if (await canLaunchUrl(Uri.parse(url))) {
await launchUrl(Uri.parse(url));
2022-03-24 20:57:30 +08:00
}
},
child: Padding(
padding: EdgeInsets.symmetric(vertical: 8),
2022-03-28 15:44:45 +08:00
child: Text('rustdesk.com',
2022-03-24 20:57:30 +08:00
style: TextStyle(
decoration: TextDecoration.underline,
)),
)),
]),
2022-03-24 21:23:22 +08:00
actions: [],
2022-03-24 20:57:30 +08:00
);
2022-04-21 10:02:47 +08:00
}, clickMaskDismiss: true, backDismiss: true);
2022-03-24 20:57:30 +08:00
}
2022-03-28 15:44:45 +08:00
Future<String> login(String name, String pass) async {
/* js test CORS
const data = { username: 'example', password: 'xx' };
fetch('http://localhost:21114/api/login', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
*/
final url = getUrl();
final body = {
'username': name,
'password': pass,
2022-08-05 20:29:43 +08:00
'id': bind.mainGetMyId(),
'uuid': bind.mainGetUuid()
2022-03-28 15:44:45 +08:00
};
try {
final response = await http.post(Uri.parse('$url/api/login'),
2022-03-28 15:44:45 +08:00
headers: {"Content-Type": "application/json"}, body: json.encode(body));
return parseResp(response.body);
} catch (e) {
print(e);
return 'Failed to access $url';
}
}
String parseResp(String body) {
final data = json.decode(body);
final error = data['error'];
if (error != null) {
return error!;
}
final token = data['access_token'];
if (token != null) {
gFFI.setByName('option', '{"name": "access_token", "value": "$token"}');
2022-03-28 15:44:45 +08:00
}
final info = data['user'];
if (info != null) {
final value = json.encode(info);
gFFI.setByName(
'option', json.encode({"name": "user_info", "value": value}));
gFFI.ffiModel.updateUser();
2022-03-28 15:44:45 +08:00
}
return '';
}
void refreshCurrentUser() async {
final token = gFFI.getByName("option", "access_token");
2022-03-28 15:44:45 +08:00
if (token == '') return;
final url = getUrl();
2022-08-05 20:29:43 +08:00
final body = {'id': bind.mainGetMyId(), 'uuid': bind.mainGetUuid()};
2022-03-28 15:44:45 +08:00
try {
final response = await http.post(Uri.parse('$url/api/currentUser'),
2022-03-28 15:44:45 +08:00
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer $token"
},
body: json.encode(body));
final status = response.statusCode;
if (status == 401 || status == 400) {
resetToken();
return;
}
parseResp(response.body);
} catch (e) {
print('$e');
}
}
void logout() async {
final token = gFFI.getByName("option", "access_token");
2022-03-28 15:44:45 +08:00
if (token == '') return;
final url = getUrl();
2022-08-05 20:29:43 +08:00
final body = {'id': bind.mainGetMyId(), 'uuid': bind.mainGetUuid()};
2022-03-28 15:44:45 +08:00
try {
await http.post(Uri.parse('$url/api/logout'),
2022-03-28 15:44:45 +08:00
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer $token"
},
body: json.encode(body));
} catch (e) {
2022-04-19 13:07:45 +08:00
showToast('Failed to access $url');
2022-03-28 15:44:45 +08:00
}
resetToken();
}
void resetToken() {
gFFI.setByName('option', '{"name": "access_token", "value": ""}');
gFFI.setByName('option', '{"name": "user_info", "value": ""}');
gFFI.ffiModel.updateUser();
2022-03-28 15:44:45 +08:00
}
String getUrl() {
var url = gFFI.getByName('option', 'api-server');
2022-03-28 15:44:45 +08:00
if (url == '') {
url = gFFI.getByName('option', 'custom-rendezvous-server');
2022-03-28 15:44:45 +08:00
if (url != '') {
if (url.contains(':')) {
final tmp = url.split(':');
if (tmp.length == 2) {
var port = int.parse(tmp[1]) - 2;
url = 'http://${tmp[0]}:$port';
}
} else {
url = 'http://$url:21114';
2022-03-28 15:44:45 +08:00
}
}
}
if (url == '') {
url = 'https://admin.rustdesk.com';
}
return url;
}
void showLogin() {
final passwordController = TextEditingController();
final nameController = TextEditingController();
var loading = false;
var error = '';
DialogManager.show((setState, close) {
return CustomAlertDialog(
title: Text(translate('Login')),
content: Column(mainAxisSize: MainAxisSize.min, children: [
TextField(
autofocus: true,
autocorrect: false,
enableSuggestions: false,
keyboardType: TextInputType.visiblePassword,
decoration: InputDecoration(
labelText: translate('Username'),
),
controller: nameController,
),
PasswordWidget(controller: passwordController),
]),
actions: (loading
? <Widget>[CircularProgressIndicator()]
: (error != ""
? <Widget>[
Text(translate(error),
style: TextStyle(color: Colors.red))
]
: <Widget>[])) +
<Widget>[
TextButton(
style: flatButtonStyle,
onPressed: loading
? null
: () {
close();
setState(() {
loading = false;
});
},
child: Text(translate('Cancel')),
),
TextButton(
style: flatButtonStyle,
onPressed: loading
? null
: () async {
final name = nameController.text.trim();
final pass = passwordController.text.trim();
if (name != "" && pass != "") {
setState(() {
loading = true;
});
final e = await login(name, pass);
setState(() {
loading = false;
error = e;
});
if (e == "") {
close();
}
}
},
child: Text(translate('OK')),
),
],
);
});
}
String? getUsername() {
final token = gFFI.getByName("option", "access_token");
2022-03-28 15:44:45 +08:00
String? username;
if (token != "") {
final info = gFFI.getByName("option", "user_info");
2022-03-28 15:44:45 +08:00
if (info != "") {
try {
Map<String, dynamic> tmp = json.decode(info);
username = tmp["name"];
} catch (e) {
print('$e');
}
}
}
return username;
}
2022-04-15 17:50:15 +08:00
class ScanButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
return IconButton(
icon: Icon(Icons.qr_code_scanner),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => ScanPage(),
),
);
},
);
}
}