mirror of
https://github.com/lollipopkit/flutter_server_box.git
synced 2026-01-31 13:25:10 +01:00
opt. for docker & apt
This commit is contained in:
35
lib/core/extension/ssh_client.dart
Normal file
35
lib/core/extension/ssh_client.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:dartssh2/dartssh2.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:toolbox/core/extension/uint8list.dart';
|
||||
|
||||
typedef OnStd = void Function(String data, StreamSink<Uint8List> sink);
|
||||
typedef OnStdin = void Function(StreamSink<Uint8List> sink);
|
||||
|
||||
typedef PwdRequestFunc = Future<String> Function();
|
||||
final pwdRequestWithUserReg = RegExp(r'\[sudo\] password for (.+):');
|
||||
|
||||
extension SSHClientX on SSHClient {
|
||||
Future<int?> exec(String cmd,
|
||||
{OnStd? onStderr, OnStd? onStdout, OnStdin? stdin}) async {
|
||||
final session = await execute(cmd);
|
||||
|
||||
if (onStderr != null) {
|
||||
await for (final data in session.stderr) {
|
||||
onStderr(data.string, session.stdin);
|
||||
}
|
||||
}
|
||||
if (onStdout != null) {
|
||||
await for (final data in session.stdout) {
|
||||
onStdout(data.string, session.stdin);
|
||||
}
|
||||
}
|
||||
if (stdin != null) {
|
||||
stdin(session.stdin);
|
||||
}
|
||||
|
||||
session.close();
|
||||
return session.exitCode;
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:toolbox/data/model/distribution.dart';
|
||||
|
||||
@@ -60,4 +63,6 @@ extension StringX on String {
|
||||
}
|
||||
|
||||
String get withLangExport => 'export LANG=en_US.UTF-8 && $this';
|
||||
|
||||
Uint8List get uint8List => Uint8List.fromList(utf8.encode(this));
|
||||
}
|
||||
|
||||
@@ -1,19 +1,15 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:dartssh2/dartssh2.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:toolbox/core/extension/ssh_client.dart';
|
||||
import 'package:toolbox/core/extension/stringx.dart';
|
||||
import 'package:toolbox/core/extension/uint8list.dart';
|
||||
import 'package:toolbox/core/provider_base.dart';
|
||||
import 'package:toolbox/data/model/apt/upgrade_pkg_info.dart';
|
||||
import 'package:toolbox/data/model/distribution.dart';
|
||||
|
||||
typedef PwdRequestFunc = Future<String> Function(
|
||||
int triedTimes, String? userName);
|
||||
final pwdRequestWithUserReg = RegExp(r'\[sudo\] password for (.+):');
|
||||
|
||||
class AptProvider extends BusyProvider {
|
||||
final logger = Logger('AptProvider');
|
||||
|
||||
@@ -29,45 +25,37 @@ class AptProvider extends BusyProvider {
|
||||
String? upgradeLog;
|
||||
String? updateLog;
|
||||
String lastLog = '';
|
||||
int triedTimes = 0;
|
||||
bool isRequestingPwd = false;
|
||||
|
||||
AptProvider();
|
||||
|
||||
Future<void> init(SSHClient client, Distribution dist, Function() onUpgrade,
|
||||
Function() onUpdate, PwdRequestFunc onPasswordRequest) async {
|
||||
Future<void> init(
|
||||
SSHClient client,
|
||||
Distribution dist,
|
||||
Function() onUpgrade,
|
||||
Function() onUpdate,
|
||||
PwdRequestFunc onPasswordRequest,
|
||||
String user) async {
|
||||
this.client = client;
|
||||
this.dist = dist;
|
||||
this.onUpgrade = onUpgrade;
|
||||
this.onPasswordRequest = onPasswordRequest;
|
||||
whoami = (await client.run('whoami').string).trim();
|
||||
whoami = user;
|
||||
}
|
||||
|
||||
bool get isSU => whoami == 'root';
|
||||
|
||||
void clear() {
|
||||
client = null;
|
||||
dist = null;
|
||||
upgradeable = null;
|
||||
error = null;
|
||||
upgradeLog = null;
|
||||
updateLog = whoami = null;
|
||||
onUpgrade = null;
|
||||
onUpdate = null;
|
||||
onPasswordRequest = null;
|
||||
triedTimes = 0;
|
||||
client = dist = updateLog = upgradeLog = upgradeable =
|
||||
error = whoami = onUpdate = onUpgrade = onPasswordRequest = null;
|
||||
isRequestingPwd = false;
|
||||
}
|
||||
|
||||
Future<void> refreshInstalled() async {
|
||||
if (client == null) {
|
||||
error = 'No client';
|
||||
return;
|
||||
}
|
||||
|
||||
final result = await _update();
|
||||
getUpgradeableList(result);
|
||||
try {} catch (e) {
|
||||
try {
|
||||
getUpgradeableList(result);
|
||||
} catch (e) {
|
||||
error = '[Server Raw]:\n$result\n[App Error]:\n$e';
|
||||
} finally {
|
||||
notifyListeners();
|
||||
@@ -100,32 +88,27 @@ class AptProvider extends BusyProvider {
|
||||
upgradeable = list.map((e) => UpgradePkgInfo(e, dist!)).toList();
|
||||
}
|
||||
|
||||
Future<String> _update() async {
|
||||
Future<String?> _update() async {
|
||||
switch (dist) {
|
||||
case Distribution.rehl:
|
||||
return await client?.run(_wrap('yum check-update')).string ?? '';
|
||||
return await client?.run(_wrap('yum check-update')).string;
|
||||
default:
|
||||
final session = await client!.execute(_wrap('apt update'));
|
||||
session.stderr.listen((event) => _onPwd(event, session.stdin));
|
||||
session.stdout.listen((event) {
|
||||
updateLog = (updateLog ?? '') + event.string;
|
||||
notifyListeners();
|
||||
onUpdate ?? () {}();
|
||||
});
|
||||
await session.done;
|
||||
await client!.exec(
|
||||
_wrap('apt update'),
|
||||
onStderr: _onPwd,
|
||||
onStdout: (data, sink) {
|
||||
updateLog = (updateLog ?? '') + data;
|
||||
notifyListeners();
|
||||
onUpdate!();
|
||||
},
|
||||
);
|
||||
return await client
|
||||
?.run('apt list --upgradeable'.withLangExport)
|
||||
.string ??
|
||||
'';
|
||||
?.run('apt list --upgradeable'.withLangExport)
|
||||
.string;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> upgrade() async {
|
||||
if (client == null) {
|
||||
error = 'No client';
|
||||
return;
|
||||
}
|
||||
|
||||
final upgradeCmd = () {
|
||||
switch (dist) {
|
||||
case Distribution.rehl:
|
||||
@@ -135,38 +118,34 @@ class AptProvider extends BusyProvider {
|
||||
}
|
||||
}();
|
||||
|
||||
final session = await client!.execute(_wrap(upgradeCmd));
|
||||
session.stderr.listen((e) => _onPwd(e, session.stdin));
|
||||
|
||||
session.stdout.listen((data) async {
|
||||
final log = data.string;
|
||||
if (lastLog == log.trim()) return;
|
||||
upgradeLog = (upgradeLog ?? '') + log;
|
||||
lastLog = log.trim();
|
||||
notifyListeners();
|
||||
onUpgrade!();
|
||||
});
|
||||
await client!.exec(
|
||||
_wrap(upgradeCmd),
|
||||
onStderr: (data, sink) => _onPwd(data, sink),
|
||||
onStdout: (log, sink) {
|
||||
if (lastLog == log.trim()) return;
|
||||
upgradeLog = (upgradeLog ?? '') + log;
|
||||
lastLog = log.trim();
|
||||
notifyListeners();
|
||||
onUpgrade!();
|
||||
},
|
||||
);
|
||||
|
||||
upgradeLog = null;
|
||||
await session.done;
|
||||
refreshInstalled();
|
||||
}
|
||||
|
||||
Future<void> _onPwd(Uint8List e, StreamSink<Uint8List> stdin) async {
|
||||
Future<void> _onPwd(String event, StreamSink<Uint8List> stdin) async {
|
||||
if (isRequestingPwd) return;
|
||||
isRequestingPwd = true;
|
||||
final event = e.string;
|
||||
if (event.contains('[sudo] password for ')) {
|
||||
final user = pwdRequestWithUserReg.firstMatch(event)?.group(1);
|
||||
logger.info('sudo password request for $user');
|
||||
triedTimes++;
|
||||
final pwd =
|
||||
await (onPasswordRequest ?? (_, __) async => '')(triedTimes, user);
|
||||
final pwd = await onPasswordRequest!();
|
||||
if (pwd.isEmpty) {
|
||||
logger.info('sudo password request cancelled');
|
||||
return;
|
||||
}
|
||||
stdin.add(Uint8List.fromList(utf8.encode('$pwd\n')));
|
||||
stdin.add('$pwd\n'.uint8List);
|
||||
}
|
||||
isRequestingPwd = false;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,24 @@
|
||||
import 'dart:async';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:dartssh2/dartssh2.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:toolbox/core/extension/ssh_client.dart';
|
||||
import 'package:toolbox/core/extension/stringx.dart';
|
||||
import 'package:toolbox/core/extension/uint8list.dart';
|
||||
import 'package:toolbox/core/provider_base.dart';
|
||||
import 'package:toolbox/data/model/docker/ps.dart';
|
||||
import 'package:toolbox/data/res/error.dart';
|
||||
import 'package:toolbox/data/store/docker.dart';
|
||||
import 'package:toolbox/locator.dart';
|
||||
|
||||
final _dockerNotFound = RegExp(r'command not found|Unknown command');
|
||||
final _versionReg = RegExp(r'(Version:)\s+([0-9]+\.[0-9]+\.[0-9]+)');
|
||||
final _editionReg = RegExp(r'(Client:)\s+(.+-.+)');
|
||||
final _userIdReg = RegExp(r'.+:(\d+:\d+):.+');
|
||||
|
||||
const _dockerPS = 'docker ps -a';
|
||||
|
||||
final _logger = Logger('DockerProvider');
|
||||
|
||||
class DockerProvider extends BusyProvider {
|
||||
SSHClient? client;
|
||||
@@ -15,82 +26,125 @@ class DockerProvider extends BusyProvider {
|
||||
List<DockerPsItem>? items;
|
||||
String? version;
|
||||
String? edition;
|
||||
String? error;
|
||||
DockerErr? error;
|
||||
PwdRequestFunc? onPwdReq;
|
||||
String? hostId;
|
||||
String? runLog;
|
||||
bool isRequestingPwd = false;
|
||||
|
||||
void init(SSHClient client, String userName) {
|
||||
void init(SSHClient client, String userName, PwdRequestFunc onPwdReq,
|
||||
String hostId) {
|
||||
this.client = client;
|
||||
this.userName = userName;
|
||||
this.onPwdReq = onPwdReq;
|
||||
this.hostId = hostId;
|
||||
}
|
||||
|
||||
void clear() {
|
||||
client = null;
|
||||
userName = null;
|
||||
error = null;
|
||||
items = null;
|
||||
version = null;
|
||||
edition = null;
|
||||
client = userName = error = items = version = edition = onPwdReq = null;
|
||||
isRequestingPwd = false;
|
||||
hostId = runLog = null;
|
||||
}
|
||||
|
||||
Future<void> refresh() async {
|
||||
if (client == null) {
|
||||
error = 'no client';
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
|
||||
final verRaw = await client!.run('docker version'.withLangExport).string;
|
||||
if (verRaw.contains(_dockerNotFound)) {
|
||||
error = 'docker not found';
|
||||
error = DockerErr(type: DockerErrType.notInstalled);
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
|
||||
version = _versionReg.firstMatch(verRaw)?.group(2);
|
||||
edition = _editionReg.firstMatch(verRaw)?.group(2);
|
||||
|
||||
final passwd = await client!.run('cat /etc/passwd | grep $userName').string;
|
||||
final userId = _userIdReg.firstMatch(passwd)?.group(1)?.split(':').first;
|
||||
try {
|
||||
version = _versionReg.firstMatch(verRaw)?.group(2);
|
||||
edition = _editionReg.firstMatch(verRaw)?.group(2);
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
}
|
||||
|
||||
try {
|
||||
final cmd = 'docker ps -a'.withLangExport;
|
||||
final raw = await () async {
|
||||
final raw = await client!.run(cmd).string;
|
||||
if (raw.contains('permission denied')) {
|
||||
return await client!
|
||||
.run(
|
||||
'export DOCKER_HOST=unix:///run/user/${userId ?? 1000}/docker.sock && $cmd')
|
||||
.string;
|
||||
// judge whether to use DOCKER_HOST / sudo
|
||||
final dockerHost = locator<DockerStore>().getDockerHost(hostId!);
|
||||
final cmd = () {
|
||||
if (dockerHost == null || dockerHost.isEmpty) {
|
||||
return 'sudo -S $_dockerPS'.withLangExport;
|
||||
}
|
||||
return raw;
|
||||
return 'export DOCKER_HOST=$dockerHost && $_dockerPS'.withLangExport;
|
||||
}();
|
||||
|
||||
// run docker ps
|
||||
var raw = '';
|
||||
await client!.exec(
|
||||
cmd,
|
||||
onStderr: _onPwd,
|
||||
onStdout: (data, _) => raw = '$raw$data',
|
||||
);
|
||||
|
||||
// parse result
|
||||
final lines = raw.split('\n');
|
||||
lines.removeAt(0);
|
||||
lines.removeWhere((element) => element.isEmpty);
|
||||
items = lines.map((e) => DockerPsItem.fromRawString(e)).toList();
|
||||
} catch (e) {
|
||||
error = e.toString();
|
||||
error = DockerErr(type: DockerErrType.unknown, message: e.toString());
|
||||
rethrow;
|
||||
} finally {
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _onPwd(String event, StreamSink<Uint8List> stdin) async {
|
||||
if (isRequestingPwd) return;
|
||||
isRequestingPwd = true;
|
||||
if (event.contains('[sudo] password for ')) {
|
||||
_logger.info('sudo password request for $userName');
|
||||
final pwd = await onPwdReq!();
|
||||
if (pwd.isEmpty) {
|
||||
_logger.info('sudo password request cancelled');
|
||||
return;
|
||||
}
|
||||
stdin.add('$pwd\n'.uint8List);
|
||||
}
|
||||
isRequestingPwd = false;
|
||||
}
|
||||
|
||||
Future<bool> _do(String id, String cmd) async {
|
||||
setBusyState();
|
||||
if (client == null) {
|
||||
error = 'no client';
|
||||
setBusyState(false);
|
||||
return false;
|
||||
}
|
||||
final result = await client!.run(cmd).string;
|
||||
final result = await client!.run('$cmd $id').string;
|
||||
await refresh();
|
||||
setBusyState(false);
|
||||
return result.contains(id);
|
||||
}
|
||||
|
||||
Future<bool> stop(String id) async => await _do(id, 'docker stop $id');
|
||||
Future<bool> stop(String id) async => await _do(id, 'docker stop');
|
||||
|
||||
Future<bool> start(String id) async => await _do(id, 'docker start $id');
|
||||
Future<bool> start(String id) async => await _do(id, 'docker start');
|
||||
|
||||
Future<bool> delete(String id) async => await _do(id, 'docker rm $id');
|
||||
Future<bool> delete(String id) async => await _do(id, 'docker rm');
|
||||
|
||||
Future<DockerErr?> run(String cmd) async {
|
||||
if (!cmd.startsWith('docker ')) {
|
||||
return DockerErr(type: DockerErrType.cmdNoPrefix);
|
||||
}
|
||||
setBusyState();
|
||||
|
||||
final errs = <String>[];
|
||||
final code = await client!.exec(
|
||||
cmd,
|
||||
onStderr: (data, _) => errs.add(data),
|
||||
onStdout: (data, _) {
|
||||
runLog = '$runLog$data';
|
||||
notifyListeners();
|
||||
},
|
||||
);
|
||||
|
||||
runLog = null;
|
||||
|
||||
if (errs.isNotEmpty || code != 0) {
|
||||
setBusyState(false);
|
||||
return DockerErr(type: DockerErrType.unknown, message: errs.join('\n'));
|
||||
}
|
||||
await refresh();
|
||||
setBusyState(false);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
class BuildData {
|
||||
static const String name = "ServerBox";
|
||||
static const int build = 165;
|
||||
static const int build = 166;
|
||||
static const String engine =
|
||||
"Flutter 3.3.9 • channel stable • https://github.com/flutter/flutter.git\nFramework • revision b8f7f1f986 (12 days ago) • 2022-11-23 06:43:51 +0900\nEngine • revision 8f2221fbef\nTools • Dart 2.18.5 • DevTools 2.15.0\n";
|
||||
static const String buildAt = "2022-12-04 21:41:26.055331";
|
||||
static const int modifications = 1;
|
||||
static const String buildAt = "2022-12-04 21:57:10.591121";
|
||||
static const int modifications = 2;
|
||||
}
|
||||
|
||||
28
lib/data/res/error.dart
Normal file
28
lib/data/res/error.dart
Normal file
@@ -0,0 +1,28 @@
|
||||
enum ErrFrom {
|
||||
unknown,
|
||||
apt,
|
||||
docker,
|
||||
sftp,
|
||||
ssh,
|
||||
}
|
||||
|
||||
abstract class Err<T> {
|
||||
final ErrFrom from;
|
||||
final T type;
|
||||
final String? message;
|
||||
|
||||
Err({required this.from, required this.type, this.message});
|
||||
}
|
||||
|
||||
enum DockerErrType {
|
||||
unknown,
|
||||
noClient,
|
||||
notInstalled,
|
||||
invalidVersion,
|
||||
cmdNoPrefix
|
||||
}
|
||||
|
||||
class DockerErr extends Err<DockerErrType> {
|
||||
DockerErr({required DockerErrType type, String? message})
|
||||
: super(from: ErrFrom.docker, type: type, message: message);
|
||||
}
|
||||
11
lib/data/store/docker.dart
Normal file
11
lib/data/store/docker.dart
Normal file
@@ -0,0 +1,11 @@
|
||||
import 'package:toolbox/core/persistant_store.dart';
|
||||
|
||||
class DockerStore extends PersistentStore {
|
||||
String? getDockerHost(String id) {
|
||||
return box.get(id);
|
||||
}
|
||||
|
||||
void setDockerHost(String id, String host) {
|
||||
box.put(id, host);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ class SettingStore extends PersistentStore {
|
||||
StoreProperty<int> get primaryColor =>
|
||||
property('primaryColor', defaultValue: Colors.deepPurpleAccent.value);
|
||||
StoreProperty<int> get serverStatusUpdateInterval =>
|
||||
property('serverStatusUpdateInterval', defaultValue: 2);
|
||||
property('serverStatusUpdateInterval', defaultValue: 5);
|
||||
StoreProperty<int> get launchPage => property('launchPage', defaultValue: 0);
|
||||
|
||||
StoreProperty<int> get storeVersion =>
|
||||
|
||||
@@ -81,6 +81,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"clear": MessageLookupByLibrary.simpleMessage("Clear"),
|
||||
"clickSee": MessageLookupByLibrary.simpleMessage("Click here"),
|
||||
"close": MessageLookupByLibrary.simpleMessage("Close"),
|
||||
"cmd": MessageLookupByLibrary.simpleMessage("Command"),
|
||||
"containerStatus":
|
||||
MessageLookupByLibrary.simpleMessage("Container status"),
|
||||
"convert": MessageLookupByLibrary.simpleMessage("Convert"),
|
||||
@@ -94,6 +95,14 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"delete": MessageLookupByLibrary.simpleMessage("Delete"),
|
||||
"disconnected": MessageLookupByLibrary.simpleMessage("Disconnected"),
|
||||
"dl2Local": m0,
|
||||
"dockerCmdPrefixErr": MessageLookupByLibrary.simpleMessage(
|
||||
"Please make sure that the docker command prefix is correct."),
|
||||
"dockerEditHost":
|
||||
MessageLookupByLibrary.simpleMessage("Edit DOCKER_HOST"),
|
||||
"dockerEmptyRunningItems": MessageLookupByLibrary.simpleMessage(
|
||||
"No running container. \nIt may be that the env DOCKER_HOST is not read correctly. You can found it by running `echo \$DOCKER_HOST` in terminal."),
|
||||
"dockerNotInstalled":
|
||||
MessageLookupByLibrary.simpleMessage("Docker not installed"),
|
||||
"dockerStatusRunningAndStoppedFmt": m1,
|
||||
"dockerStatusRunningFmt": m2,
|
||||
"download": MessageLookupByLibrary.simpleMessage("Download"),
|
||||
@@ -128,6 +137,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"installDockerWithUrl": MessageLookupByLibrary.simpleMessage(
|
||||
"Please https://docs.docker.com/engine/install docker first."),
|
||||
"invalidJson": MessageLookupByLibrary.simpleMessage("Invalid JSON"),
|
||||
"invalidVersion":
|
||||
MessageLookupByLibrary.simpleMessage("Invalid version"),
|
||||
"invalidVersionHelp": m6,
|
||||
"keepForeground":
|
||||
MessageLookupByLibrary.simpleMessage("Keep app foreground!"),
|
||||
|
||||
@@ -76,6 +76,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"clear": MessageLookupByLibrary.simpleMessage("清除"),
|
||||
"clickSee": MessageLookupByLibrary.simpleMessage("点击查看"),
|
||||
"close": MessageLookupByLibrary.simpleMessage("关闭"),
|
||||
"cmd": MessageLookupByLibrary.simpleMessage("命令"),
|
||||
"containerStatus": MessageLookupByLibrary.simpleMessage("容器状态"),
|
||||
"convert": MessageLookupByLibrary.simpleMessage("转换"),
|
||||
"copy": MessageLookupByLibrary.simpleMessage("复制到剪切板"),
|
||||
@@ -88,6 +89,13 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"delete": MessageLookupByLibrary.simpleMessage("删除"),
|
||||
"disconnected": MessageLookupByLibrary.simpleMessage("连接断开"),
|
||||
"dl2Local": m0,
|
||||
"dockerCmdPrefixErr":
|
||||
MessageLookupByLibrary.simpleMessage("命令前缀错误,没有以 `docker` 开头"),
|
||||
"dockerEditHost":
|
||||
MessageLookupByLibrary.simpleMessage("编辑 DOCKER_HOST"),
|
||||
"dockerEmptyRunningItems": MessageLookupByLibrary.simpleMessage(
|
||||
"没有正在运行的容器。\n这可能是因为环境变量 DOCKER_HOST 没有被正确读取。你可以通过在终端内运行 `echo \$DOCKER_HOST` 来获取。"),
|
||||
"dockerNotInstalled": MessageLookupByLibrary.simpleMessage("Docker未安装"),
|
||||
"dockerStatusRunningAndStoppedFmt": m1,
|
||||
"dockerStatusRunningFmt": m2,
|
||||
"download": MessageLookupByLibrary.simpleMessage("下载"),
|
||||
@@ -116,6 +124,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"installDockerWithUrl": MessageLookupByLibrary.simpleMessage(
|
||||
"请先 https://docs.docker.com/engine/install docker"),
|
||||
"invalidJson": MessageLookupByLibrary.simpleMessage("无效的json,存在格式问题"),
|
||||
"invalidVersion": MessageLookupByLibrary.simpleMessage("不支持的版本"),
|
||||
"invalidVersionHelp": m6,
|
||||
"keepForeground": MessageLookupByLibrary.simpleMessage("请保持应用处于前台!"),
|
||||
"keyAuth": MessageLookupByLibrary.simpleMessage("公钥认证"),
|
||||
|
||||
@@ -1350,6 +1350,66 @@ class S {
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Docker not installed`
|
||||
String get dockerNotInstalled {
|
||||
return Intl.message(
|
||||
'Docker not installed',
|
||||
name: 'dockerNotInstalled',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Invalid version`
|
||||
String get invalidVersion {
|
||||
return Intl.message(
|
||||
'Invalid version',
|
||||
name: 'invalidVersion',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Command`
|
||||
String get cmd {
|
||||
return Intl.message(
|
||||
'Command',
|
||||
name: 'cmd',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `No running container. \nIt may be that the env DOCKER_HOST is not read correctly. You can found it by running 'echo $DOCKER_HOST' in terminal.`
|
||||
String get dockerEmptyRunningItems {
|
||||
return Intl.message(
|
||||
'No running container. \nIt may be that the env DOCKER_HOST is not read correctly. You can found it by running `echo \$DOCKER_HOST` in terminal.',
|
||||
name: 'dockerEmptyRunningItems',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Edit DOCKER_HOST`
|
||||
String get dockerEditHost {
|
||||
return Intl.message(
|
||||
'Edit DOCKER_HOST',
|
||||
name: 'dockerEditHost',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Please make sure that the docker command prefix is correct.`
|
||||
String get dockerCmdPrefixErr {
|
||||
return Intl.message(
|
||||
'Please make sure that the docker command prefix is correct.',
|
||||
name: 'dockerCmdPrefixErr',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class AppLocalizationDelegate extends LocalizationsDelegate<S> {
|
||||
|
||||
@@ -128,5 +128,11 @@
|
||||
"feedback": "Feedback",
|
||||
"feedbackOnGithub": "If you have any questions, please feedback on Github.",
|
||||
"update": "Update",
|
||||
"inputDomainHere": "Input Domain here"
|
||||
"inputDomainHere": "Input Domain here",
|
||||
"dockerNotInstalled": "Docker not installed",
|
||||
"invalidVersion": "Invalid version",
|
||||
"cmd": "Command",
|
||||
"dockerEmptyRunningItems": "No running container. \nIt may be that the env DOCKER_HOST is not read correctly. You can found it by running `echo $DOCKER_HOST` in terminal.",
|
||||
"dockerEditHost": "Edit DOCKER_HOST",
|
||||
"dockerCmdPrefixErr": "Please make sure that the docker command prefix is correct."
|
||||
}
|
||||
@@ -128,5 +128,11 @@
|
||||
"feedback": "反馈",
|
||||
"feedbackOnGithub": "如果你有任何问题,请在GitHub反馈",
|
||||
"update": "更新",
|
||||
"inputDomainHere": "在这里输入域名"
|
||||
"inputDomainHere": "在这里输入域名",
|
||||
"dockerNotInstalled": "Docker未安装",
|
||||
"invalidVersion": "不支持的版本",
|
||||
"cmd": "命令",
|
||||
"dockerEmptyRunningItems": "没有正在运行的容器。\n这可能是因为环境变量 DOCKER_HOST 没有被正确读取。你可以通过在终端内运行 `echo $DOCKER_HOST` 来获取。",
|
||||
"dockerEditHost": "编辑 DOCKER_HOST",
|
||||
"dockerCmdPrefixErr": "命令前缀错误,没有以 `docker` 开头"
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import 'package:toolbox/data/provider/server.dart';
|
||||
import 'package:toolbox/data/provider/sftp_download.dart';
|
||||
import 'package:toolbox/data/provider/snippet.dart';
|
||||
import 'package:toolbox/data/service/app.dart';
|
||||
import 'package:toolbox/data/store/docker.dart';
|
||||
import 'package:toolbox/data/store/private_key.dart';
|
||||
import 'package:toolbox/data/store/server.dart';
|
||||
import 'package:toolbox/data/store/setting.dart';
|
||||
@@ -46,6 +47,10 @@ Future<void> setupLocatorForStores() async {
|
||||
final snippet = SnippetStore();
|
||||
await snippet.init(boxName: 'snippet');
|
||||
locator.registerSingleton(snippet);
|
||||
|
||||
final docker = DockerStore();
|
||||
await docker.init(boxName: 'docker');
|
||||
locator.registerSingleton(docker);
|
||||
}
|
||||
|
||||
Future<void> setupLocator() async {
|
||||
|
||||
@@ -58,61 +58,60 @@ class _AptManagePageState extends State<AptManagePage>
|
||||
return;
|
||||
}
|
||||
|
||||
// ignore: prefer_function_declarations_over_variables
|
||||
Function onSubmitted = () {
|
||||
if (textController.text == '') {
|
||||
showRoundDialog(context, s.attention, Text(s.fieldMustNotEmpty), [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(), child: Text(s.ok)),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
Navigator.of(context).pop();
|
||||
};
|
||||
|
||||
// ignore: prefer_function_declarations_over_variables
|
||||
PwdRequestFunc onPwdRequest = (triedTimes, user) async {
|
||||
if (!mounted) return '';
|
||||
await showRoundDialog(
|
||||
context,
|
||||
triedTimes == 3 ? s.lastTry : (user ?? s.unknown),
|
||||
TextField(
|
||||
controller: textController,
|
||||
keyboardType: TextInputType.visiblePassword,
|
||||
obscureText: true,
|
||||
onSubmitted: (_) => onSubmitted(),
|
||||
decoration: InputDecoration(
|
||||
labelText: s.pwd,
|
||||
),
|
||||
),
|
||||
[
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop();
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
child: Text(s.cancel)),
|
||||
TextButton(
|
||||
onPressed: () => onSubmitted(),
|
||||
child: Text(
|
||||
s.ok,
|
||||
style: const TextStyle(color: Colors.red),
|
||||
)),
|
||||
]);
|
||||
return textController.text.trim();
|
||||
};
|
||||
|
||||
_aptProvider.init(
|
||||
si.client!,
|
||||
si.status.sysVer.dist,
|
||||
() =>
|
||||
scrollController.jumpTo(scrollController.position.maxScrollExtent),
|
||||
() => scrollControllerUpdate
|
||||
.jumpTo(scrollControllerUpdate.positions.last.maxScrollExtent),
|
||||
onPwdRequest);
|
||||
.jumpTo(scrollController.position.maxScrollExtent),
|
||||
onPwdRequest,
|
||||
widget.spi.user);
|
||||
_aptProvider.refreshInstalled();
|
||||
}
|
||||
|
||||
void onSubmitted() {
|
||||
if (textController.text == '') {
|
||||
showRoundDialog(context, s.attention, Text(s.fieldMustNotEmpty), [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(), child: Text(s.ok)),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
|
||||
Future<String> onPwdRequest() async {
|
||||
if (!mounted) return '';
|
||||
await showRoundDialog(
|
||||
context,
|
||||
widget.spi.user,
|
||||
TextField(
|
||||
controller: textController,
|
||||
keyboardType: TextInputType.visiblePassword,
|
||||
obscureText: true,
|
||||
onSubmitted: (_) => onSubmitted(),
|
||||
decoration: InputDecoration(
|
||||
labelText: s.pwd,
|
||||
),
|
||||
),
|
||||
[
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop();
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
child: Text(s.cancel)),
|
||||
TextButton(
|
||||
onPressed: () => onSubmitted(),
|
||||
child: Text(
|
||||
s.ok,
|
||||
style: const TextStyle(color: Colors.red),
|
||||
)),
|
||||
]);
|
||||
return textController.text.trim();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
|
||||
@@ -6,7 +6,9 @@ import 'package:toolbox/data/model/docker/ps.dart';
|
||||
import 'package:toolbox/data/model/server/server_private_info.dart';
|
||||
import 'package:toolbox/data/provider/docker.dart';
|
||||
import 'package:toolbox/data/provider/server.dart';
|
||||
import 'package:toolbox/data/res/error.dart';
|
||||
import 'package:toolbox/data/res/url.dart';
|
||||
import 'package:toolbox/data/store/docker.dart';
|
||||
import 'package:toolbox/generated/l10n.dart';
|
||||
import 'package:toolbox/locator.dart';
|
||||
import 'package:toolbox/view/widget/center_loading.dart';
|
||||
@@ -25,6 +27,7 @@ class DockerManagePage extends StatefulWidget {
|
||||
class _DockerManagePageState extends State<DockerManagePage> {
|
||||
final _docker = locator<DockerProvider>();
|
||||
final greyTextStyle = const TextStyle(color: Colors.grey);
|
||||
final textController = TextEditingController();
|
||||
late S s;
|
||||
|
||||
@override
|
||||
@@ -51,69 +54,233 @@ class _DockerManagePageState extends State<DockerManagePage> {
|
||||
Navigator.of(context).pop();
|
||||
return;
|
||||
}
|
||||
_docker.init(client, widget.spi.user);
|
||||
_docker.init(client, widget.spi.user, onPwdRequest, widget.spi.id);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
centerTitle: true,
|
||||
title: TwoLineText(up: 'Docker', down: widget.spi.name),
|
||||
),
|
||||
body: _buildMain(),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMain() {
|
||||
return Consumer<DockerProvider>(builder: (_, docker, __) {
|
||||
final running = docker.items;
|
||||
if (docker.error != null && running == null) {
|
||||
return SizedBox.expand(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.error,
|
||||
size: 37,
|
||||
),
|
||||
const SizedBox(height: 27),
|
||||
Text(docker.error!),
|
||||
const SizedBox(height: 27),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(17),
|
||||
child: _buildSolution(docker.error!),
|
||||
)
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
if (running == null) {
|
||||
_docker.refresh();
|
||||
return centerLoading;
|
||||
}
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(7),
|
||||
children: [
|
||||
_buildVersion(
|
||||
docker.edition ?? s.unknown, docker.version ?? s.unknown),
|
||||
_buildPsItems(running, docker)
|
||||
].map((e) => RoundRectCard(e)).toList(),
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
centerTitle: true,
|
||||
title: TwoLineText(up: 'Docker', down: widget.spi.name),
|
||||
actions: [
|
||||
IconButton(
|
||||
onPressed: () => docker.refresh(),
|
||||
icon: const Icon(Icons.refresh))
|
||||
],
|
||||
),
|
||||
body: _buildMain(docker),
|
||||
floatingActionButton: _buildFAB(docker),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Widget _buildSolution(String err) {
|
||||
switch (err) {
|
||||
case 'docker not found':
|
||||
Widget _buildFAB(DockerProvider docker) {
|
||||
final c = TextEditingController();
|
||||
return FloatingActionButton(
|
||||
onPressed: () {
|
||||
showRoundDialog(
|
||||
context,
|
||||
s.cmd,
|
||||
TextField(
|
||||
keyboardType: TextInputType.multiline,
|
||||
maxLines: 7,
|
||||
controller: c,
|
||||
autocorrect: false,
|
||||
),
|
||||
[
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(s.cancel),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
Navigator.of(context).pop();
|
||||
final result = await docker.run(c.text.trim());
|
||||
if (result != null) {
|
||||
showSnackBar(
|
||||
context, Text(getErrMsg(result) ?? s.unknownError));
|
||||
}
|
||||
},
|
||||
child: Text(s.run),
|
||||
)
|
||||
],
|
||||
);
|
||||
},
|
||||
child: const Icon(Icons.code),
|
||||
);
|
||||
}
|
||||
|
||||
String? getErrMsg(DockerErr err) {
|
||||
switch (err.type) {
|
||||
case DockerErrType.cmdNoPrefix:
|
||||
return s.dockerCmdPrefixErr;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
void onSubmitted() {
|
||||
if (textController.text == '') {
|
||||
showRoundDialog(context, s.attention, Text(s.fieldMustNotEmpty), [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(), child: Text(s.ok)),
|
||||
]);
|
||||
return;
|
||||
}
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
|
||||
Future<String> onPwdRequest() async {
|
||||
if (!mounted) return '';
|
||||
await showRoundDialog(
|
||||
context,
|
||||
widget.spi.user,
|
||||
TextField(
|
||||
controller: textController,
|
||||
keyboardType: TextInputType.visiblePassword,
|
||||
obscureText: true,
|
||||
onSubmitted: (_) => onSubmitted(),
|
||||
decoration: InputDecoration(
|
||||
labelText: s.pwd,
|
||||
),
|
||||
),
|
||||
[
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop();
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
child: Text(s.cancel)),
|
||||
TextButton(
|
||||
onPressed: () => onSubmitted(),
|
||||
child: Text(
|
||||
s.ok,
|
||||
style: const TextStyle(color: Colors.red),
|
||||
)),
|
||||
]);
|
||||
return textController.text.trim();
|
||||
}
|
||||
|
||||
Widget _buildMain(DockerProvider docker) {
|
||||
final running = docker.items;
|
||||
if (docker.error != null && running == null) {
|
||||
return SizedBox.expand(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.error,
|
||||
size: 37,
|
||||
),
|
||||
const SizedBox(height: 27),
|
||||
_buildErr(docker.error!),
|
||||
const SizedBox(height: 27),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(17),
|
||||
child: _buildSolution(docker.error!),
|
||||
)
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
if (running == null) {
|
||||
_docker.refresh();
|
||||
return centerLoading;
|
||||
}
|
||||
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(7),
|
||||
children: [
|
||||
_buildVersion(docker.edition ?? s.unknown, docker.version ?? s.unknown),
|
||||
_buildPsItems(running, docker),
|
||||
_buildEditHost(running, docker),
|
||||
_buildRunLog(docker),
|
||||
].map((e) => RoundRectCard(e)).toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildRunLog(DockerProvider docker) {
|
||||
if (docker.runLog == null) return const SizedBox();
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(17),
|
||||
child: Text(docker.runLog!, maxLines: 1,),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildEditHost(List<DockerPsItem> running, DockerProvider docker) {
|
||||
if (running.isEmpty) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(17, 17, 17, 0),
|
||||
child: Column(
|
||||
children: [
|
||||
Text(
|
||||
s.dockerEmptyRunningItems,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => _showEditHostDialog(docker),
|
||||
child: Text(s.dockerEditHost))
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
return const SizedBox();
|
||||
}
|
||||
|
||||
Future<void> _showEditHostDialog(DockerProvider docker) async {
|
||||
await showRoundDialog(
|
||||
context,
|
||||
s.dockerEditHost,
|
||||
TextField(
|
||||
maxLines: 1,
|
||||
autocorrect: false,
|
||||
controller:
|
||||
TextEditingController(text: 'unix:///run/user/1000/docker.sock'),
|
||||
onSubmitted: (value) {
|
||||
locator<DockerStore>().setDockerHost(widget.spi.id, value.trim());
|
||||
docker.refresh();
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
),
|
||||
[
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(s.cancel)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildErr(DockerErr err) {
|
||||
var errStr = '';
|
||||
switch (err.type) {
|
||||
case DockerErrType.noClient:
|
||||
errStr = s.noClient;
|
||||
break;
|
||||
case DockerErrType.notInstalled:
|
||||
errStr = s.dockerNotInstalled;
|
||||
break;
|
||||
case DockerErrType.invalidVersion:
|
||||
errStr = s.invalidVersion;
|
||||
break;
|
||||
default:
|
||||
errStr = err.message ?? s.unknown;
|
||||
}
|
||||
return Text(errStr);
|
||||
}
|
||||
|
||||
Widget _buildSolution(DockerErr err) {
|
||||
switch (err.type) {
|
||||
case DockerErrType.notInstalled:
|
||||
return UrlText(
|
||||
text: s.installDockerWithUrl,
|
||||
replace: s.install,
|
||||
);
|
||||
case 'no client':
|
||||
case DockerErrType.noClient:
|
||||
return Text(s.waitConnection);
|
||||
case 'invalid version':
|
||||
case DockerErrType.invalidVersion:
|
||||
return UrlText(
|
||||
text: s.invalidVersionHelp(issueUrl),
|
||||
replace: 'Github',
|
||||
|
||||
@@ -51,7 +51,7 @@ class _ServerDetailPageState extends State<ServerDetailPage>
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.all(13),
|
||||
children: [
|
||||
SizedBox(height: _media.size.height * 0.03),
|
||||
SizedBox(height: _media.size.height * 0.01),
|
||||
_buildLinuxIcon(si.status.sysVer),
|
||||
SizedBox(height: _media.size.height * 0.03),
|
||||
_buildUpTimeAndSys(si.status),
|
||||
|
||||
Reference in New Issue
Block a user