mirror of
https://github.com/GopeedLab/gopeed.git
synced 2026-11-09 18:10:29 +00:00
feat: support custom tracker url (#59)
This commit is contained in:
1 parent
9ef3405e43
commit
691c2f496e
71 files changed
+2209
-891
No files matched your search
+42
-22
@@ -1,17 +1,16 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:dio/adapter.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:gopeed/util/util.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../util/util.dart';
|
||||
import 'model/create_task.dart';
|
||||
import 'model/request.dart';
|
||||
import 'model/resource.dart';
|
||||
import 'model/result.dart';
|
||||
import 'model/task.dart';
|
||||
|
||||
import '../core/libgopeed_boot.dart';
|
||||
import 'model/server_config.dart';
|
||||
import 'model/downloader_config.dart';
|
||||
|
||||
class _Client {
|
||||
static _Client? _instance;
|
||||
@@ -20,25 +19,35 @@ class _Client {
|
||||
|
||||
_Client._internal();
|
||||
|
||||
factory _Client() {
|
||||
factory _Client(String network, String address, String apiToken) {
|
||||
if (_instance == null) {
|
||||
_instance = _Client._internal();
|
||||
var dio = Dio();
|
||||
final isUnixSocket = LibgopeedBoot.instance.config.network == 'unix';
|
||||
dio.options.baseUrl = isUnixSocket
|
||||
? 'http://127.0.0.1'
|
||||
: (Util.isWeb()
|
||||
? ""
|
||||
: 'http://${LibgopeedBoot.instance.config.address}');
|
||||
final isUnixSocket = network == 'unix';
|
||||
var baseUrl = 'http://127.0.0.1';
|
||||
if (!isUnixSocket) {
|
||||
if (Util.isWeb()) {
|
||||
baseUrl = kDebugMode ? 'http://127.0.0.1:9999' : '';
|
||||
} else {
|
||||
baseUrl = 'http://$address';
|
||||
}
|
||||
}
|
||||
dio.options.baseUrl = baseUrl;
|
||||
dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {
|
||||
if (apiToken.isNotEmpty) {
|
||||
options.headers['X-Api-Token'] = apiToken;
|
||||
}
|
||||
handler.next(options);
|
||||
}));
|
||||
|
||||
_instance!.dio = dio;
|
||||
if (isUnixSocket) {
|
||||
(_instance!.dio.httpClientAdapter as DefaultHttpClientAdapter)
|
||||
.onHttpClientCreate = (client) {
|
||||
client.connectionFactory =
|
||||
(Uri uri, String? proxyHost, int? proxyPort) {
|
||||
var address = InternetAddress(LibgopeedBoot.instance.config.address,
|
||||
type: InternetAddressType.unix);
|
||||
return Socket.startConnect(address, 0);
|
||||
return Socket.startConnect(
|
||||
InternetAddress(address, type: InternetAddressType.unix), 0);
|
||||
};
|
||||
return client;
|
||||
};
|
||||
@@ -48,7 +57,11 @@ class _Client {
|
||||
}
|
||||
}
|
||||
|
||||
var _client = _Client();
|
||||
late _Client _client;
|
||||
|
||||
void init(String network, String address, String apiToken) {
|
||||
_client = _Client(network, address, apiToken);
|
||||
}
|
||||
|
||||
Future<T> _parse<T>(
|
||||
Future<Response> Function() fetch,
|
||||
@@ -57,7 +70,7 @@ Future<T> _parse<T>(
|
||||
try {
|
||||
var resp = await fetch();
|
||||
if (fromJsonT != null) {
|
||||
return Result<T>.fromJson(jsonDecode(resp.data), fromJsonT).data as T;
|
||||
return Result<T>.fromJson(resp.data, fromJsonT).data as T;
|
||||
} else {
|
||||
return null as T;
|
||||
}
|
||||
@@ -65,8 +78,7 @@ Future<T> _parse<T>(
|
||||
if (e.response == null) {
|
||||
throw Exception("Server error");
|
||||
}
|
||||
throw Exception(
|
||||
Result.fromJson(jsonDecode(e.response?.data), (_) => null).msg);
|
||||
throw Exception(Result.fromJson(e.response?.data, (_) => null).msg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,7 +89,6 @@ Future<Resource> resolve(Request request) async {
|
||||
}
|
||||
|
||||
Future<String> createTask(CreateTask createTask) async {
|
||||
print(jsonEncode(createTask));
|
||||
return _parse<String>(
|
||||
() => _client.dio.post("/api/v1/tasks", data: createTask),
|
||||
(data) => data as String);
|
||||
@@ -103,11 +114,20 @@ Future<void> deleteTask(String id, bool force) async {
|
||||
() => _client.dio.delete("/api/v1/tasks/$id?force=$force"), null);
|
||||
}
|
||||
|
||||
Future<ServerConfig> getConfig() async {
|
||||
Future<DownloaderConfig> getConfig() async {
|
||||
return _parse(() => _client.dio.get("/api/v1/config"),
|
||||
(data) => ServerConfig.fromJson(data));
|
||||
(data) => DownloaderConfig.fromJson(data));
|
||||
}
|
||||
|
||||
Future<void> putConfig(ServerConfig config) async {
|
||||
Future<void> putConfig(DownloaderConfig config) async {
|
||||
return _parse(() => _client.dio.put("/api/v1/config", data: config), null);
|
||||
}
|
||||
|
||||
Future<Response<T>> proxyRequest<T>(String uri,
|
||||
{data, Options? options}) async {
|
||||
options ??= Options();
|
||||
options.headers ??= {};
|
||||
options.headers!["X-Target-Uri"] = uri;
|
||||
|
||||
return _client.dio.request("/api/v1/proxy", data: data, options: options);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
part 'downloader_config.g.dart';
|
||||
|
||||
@JsonSerializable(explicitToJson: true)
|
||||
class DownloaderConfig {
|
||||
String downloadDir = '';
|
||||
ProtocolConfig protocolConfig = ProtocolConfig();
|
||||
ExtraConfig extra = ExtraConfig();
|
||||
|
||||
DownloaderConfig();
|
||||
|
||||
factory DownloaderConfig.fromJson(Map<String, dynamic> json) =>
|
||||
_$DownloaderConfigFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$DownloaderConfigToJson(this);
|
||||
}
|
||||
|
||||
@JsonSerializable(explicitToJson: true)
|
||||
class ProtocolConfig {
|
||||
HttpConfig http = HttpConfig();
|
||||
BtConfig bt = BtConfig();
|
||||
|
||||
ProtocolConfig();
|
||||
|
||||
factory ProtocolConfig.fromJson(Map<String, dynamic> json) =>
|
||||
_$ProtocolConfigFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$ProtocolConfigToJson(this);
|
||||
}
|
||||
|
||||
@JsonSerializable()
|
||||
class HttpConfig {
|
||||
int connections = 0;
|
||||
|
||||
HttpConfig();
|
||||
|
||||
factory HttpConfig.fromJson(Map<String, dynamic> json) =>
|
||||
_$HttpConfigFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$HttpConfigToJson(this);
|
||||
}
|
||||
|
||||
@JsonSerializable()
|
||||
class BtConfig {
|
||||
List<String> trackers = [];
|
||||
|
||||
BtConfig();
|
||||
|
||||
factory BtConfig.fromJson(Map<String, dynamic> json) =>
|
||||
_$BtConfigFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$BtConfigToJson(this);
|
||||
}
|
||||
|
||||
@JsonSerializable(explicitToJson: true)
|
||||
class ExtraConfig {
|
||||
String themeMode = '';
|
||||
String locale = '';
|
||||
ExtraConfigBt bt = ExtraConfigBt();
|
||||
|
||||
ExtraConfig();
|
||||
|
||||
factory ExtraConfig.fromJson(Map<String, dynamic> json) =>
|
||||
_$ExtraConfigFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$ExtraConfigToJson(this);
|
||||
}
|
||||
|
||||
@JsonSerializable()
|
||||
class ExtraConfigBt {
|
||||
List<String> trackerSubscribeUrls = [];
|
||||
List<String> subscribeTrackers = [];
|
||||
DateTime? lastTrackerUpdateTime;
|
||||
|
||||
List<String> customTrackers = [];
|
||||
|
||||
ExtraConfigBt();
|
||||
|
||||
factory ExtraConfigBt.fromJson(Map<String, dynamic> json) =>
|
||||
_$ExtraConfigBtFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$ExtraConfigBtToJson(this);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'downloader_config.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
DownloaderConfig _$DownloaderConfigFromJson(Map<String, dynamic> json) =>
|
||||
DownloaderConfig()
|
||||
..downloadDir = json['downloadDir'] as String
|
||||
..protocolConfig = ProtocolConfig.fromJson(
|
||||
json['protocolConfig'] as Map<String, dynamic>)
|
||||
..extra = ExtraConfig.fromJson(json['extra'] as Map<String, dynamic>);
|
||||
|
||||
Map<String, dynamic> _$DownloaderConfigToJson(DownloaderConfig instance) =>
|
||||
<String, dynamic>{
|
||||
'downloadDir': instance.downloadDir,
|
||||
'protocolConfig': instance.protocolConfig.toJson(),
|
||||
'extra': instance.extra.toJson(),
|
||||
};
|
||||
|
||||
ProtocolConfig _$ProtocolConfigFromJson(Map<String, dynamic> json) =>
|
||||
ProtocolConfig()
|
||||
..http = HttpConfig.fromJson(json['http'] as Map<String, dynamic>)
|
||||
..bt = BtConfig.fromJson(json['bt'] as Map<String, dynamic>);
|
||||
|
||||
Map<String, dynamic> _$ProtocolConfigToJson(ProtocolConfig instance) =>
|
||||
<String, dynamic>{
|
||||
'http': instance.http.toJson(),
|
||||
'bt': instance.bt.toJson(),
|
||||
};
|
||||
|
||||
HttpConfig _$HttpConfigFromJson(Map<String, dynamic> json) =>
|
||||
HttpConfig()..connections = json['connections'] as int;
|
||||
|
||||
Map<String, dynamic> _$HttpConfigToJson(HttpConfig instance) =>
|
||||
<String, dynamic>{
|
||||
'connections': instance.connections,
|
||||
};
|
||||
|
||||
BtConfig _$BtConfigFromJson(Map<String, dynamic> json) => BtConfig()
|
||||
..trackers =
|
||||
(json['trackers'] as List<dynamic>).map((e) => e as String).toList();
|
||||
|
||||
Map<String, dynamic> _$BtConfigToJson(BtConfig instance) => <String, dynamic>{
|
||||
'trackers': instance.trackers,
|
||||
};
|
||||
|
||||
ExtraConfig _$ExtraConfigFromJson(Map<String, dynamic> json) => ExtraConfig()
|
||||
..themeMode = json['themeMode'] as String
|
||||
..locale = json['locale'] as String
|
||||
..bt = ExtraConfigBt.fromJson(json['bt'] as Map<String, dynamic>);
|
||||
|
||||
Map<String, dynamic> _$ExtraConfigToJson(ExtraConfig instance) =>
|
||||
<String, dynamic>{
|
||||
'themeMode': instance.themeMode,
|
||||
'locale': instance.locale,
|
||||
'bt': instance.bt.toJson(),
|
||||
};
|
||||
|
||||
ExtraConfigBt _$ExtraConfigBtFromJson(Map<String, dynamic> json) =>
|
||||
ExtraConfigBt()
|
||||
..trackerSubscribeUrls = (json['trackerSubscribeUrls'] as List<dynamic>)
|
||||
.map((e) => e as String)
|
||||
.toList()
|
||||
..lastTrackerUpdateTime = json['lastTrackerUpdateTime'] == null
|
||||
? null
|
||||
: DateTime.parse(json['lastTrackerUpdateTime'] as String)
|
||||
..subscribeTrackers = (json['subscribeTrackers'] as List<dynamic>)
|
||||
.map((e) => e as String)
|
||||
.toList()
|
||||
..customTrackers = (json['customTrackers'] as List<dynamic>)
|
||||
.map((e) => e as String)
|
||||
.toList();
|
||||
|
||||
Map<String, dynamic> _$ExtraConfigBtToJson(ExtraConfigBt instance) {
|
||||
final val = <String, dynamic>{
|
||||
'trackerSubscribeUrls': instance.trackerSubscribeUrls,
|
||||
};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
writeNotNull('lastTrackerUpdateTime',
|
||||
instance.lastTrackerUpdateTime?.toIso8601String());
|
||||
val['subscribeTrackers'] = instance.subscribeTrackers;
|
||||
val['customTrackers'] = instance.customTrackers;
|
||||
return val;
|
||||
}
|
||||
@@ -6,13 +6,11 @@ part 'options.g.dart';
|
||||
class Options {
|
||||
String name;
|
||||
String path;
|
||||
int connections;
|
||||
List<int> selectFiles;
|
||||
|
||||
Options({
|
||||
required this.name,
|
||||
required this.path,
|
||||
required this.connections,
|
||||
required this.selectFiles,
|
||||
});
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ part of 'options.dart';
|
||||
Options _$OptionsFromJson(Map<String, dynamic> json) => Options(
|
||||
name: json['name'] as String,
|
||||
path: json['path'] as String,
|
||||
connections: json['connections'] as int,
|
||||
selectFiles:
|
||||
(json['selectFiles'] as List<dynamic>).map((e) => e as int).toList(),
|
||||
);
|
||||
@@ -17,6 +16,5 @@ Options _$OptionsFromJson(Map<String, dynamic> json) => Options(
|
||||
Map<String, dynamic> _$OptionsToJson(Options instance) => <String, dynamic>{
|
||||
'name': instance.name,
|
||||
'path': instance.path,
|
||||
'connections': instance.connections,
|
||||
'selectFiles': instance.selectFiles,
|
||||
};
|
||||
@@ -1,24 +0,0 @@
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
part 'server_config.g.dart';
|
||||
|
||||
@JsonSerializable()
|
||||
class ServerConfig {
|
||||
late String host;
|
||||
late int port;
|
||||
late int connections;
|
||||
late String downloadDir;
|
||||
Map<String, dynamic>? extra;
|
||||
|
||||
ServerConfig({
|
||||
required this.host,
|
||||
required this.port,
|
||||
required this.connections,
|
||||
required this.downloadDir,
|
||||
this.extra,
|
||||
});
|
||||
|
||||
factory ServerConfig.fromJson(Map<String, dynamic> json) =>
|
||||
_$ServerConfigFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$ServerConfigToJson(this);
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'server_config.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
ServerConfig _$ServerConfigFromJson(Map<String, dynamic> json) => ServerConfig(
|
||||
host: json['host'] as String,
|
||||
port: json['port'] as int,
|
||||
connections: json['connections'] as int,
|
||||
downloadDir: json['downloadDir'] as String,
|
||||
extra: json['extra'] as Map<String, dynamic>?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$ServerConfigToJson(ServerConfig instance) {
|
||||
final val = <String, dynamic>{
|
||||
'host': instance.host,
|
||||
'port': instance.port,
|
||||
'connections': instance.connections,
|
||||
'downloadDir': instance.downloadDir,
|
||||
};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
writeNotNull('extra', instance.extra);
|
||||
return val;
|
||||
}
|
||||
@@ -7,7 +7,7 @@ part 'task.g.dart';
|
||||
|
||||
enum Status { ready, running, pause, error, done }
|
||||
|
||||
@JsonSerializable()
|
||||
@JsonSerializable(explicitToJson: true)
|
||||
class Task {
|
||||
String id;
|
||||
Resource res;
|
||||
|
||||
@@ -18,10 +18,10 @@ Task _$TaskFromJson(Map<String, dynamic> json) => Task(
|
||||
|
||||
Map<String, dynamic> _$TaskToJson(Task instance) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'res': instance.res,
|
||||
'opts': instance.opts,
|
||||
'res': instance.res.toJson(),
|
||||
'opts': instance.opts.toJson(),
|
||||
'status': _$StatusEnumMap[instance.status]!,
|
||||
'progress': instance.progress,
|
||||
'progress': instance.progress.toJson(),
|
||||
'size': instance.size,
|
||||
'createdAt': instance.createdAt.toIso8601String(),
|
||||
};
|
||||
|
||||
@@ -20,7 +20,7 @@ class LibgopeedFFi implements LibgopeedInterface {
|
||||
var completer = Completer<int>();
|
||||
var result = _libgopeed.Start(jsonEncode(cfg).toNativeUtf8().cast());
|
||||
if (result.r1 != nullptr) {
|
||||
completer.completeError(result.r1.cast<Utf8>().toDartString());
|
||||
completer.completeError(Exception(result.r1.cast<Utf8>().toDartString()));
|
||||
} else {
|
||||
completer.complete(result.r0);
|
||||
}
|
||||
|
||||
@@ -4,19 +4,14 @@ part 'start_config.g.dart';
|
||||
|
||||
@JsonSerializable()
|
||||
class StartConfig {
|
||||
String network;
|
||||
String address;
|
||||
String storage;
|
||||
String storageDir;
|
||||
int refreshInterval;
|
||||
late String network;
|
||||
late String address;
|
||||
late String storage;
|
||||
late String storageDir;
|
||||
late int refreshInterval;
|
||||
late String apiToken;
|
||||
|
||||
StartConfig({
|
||||
required this.network,
|
||||
required this.address,
|
||||
required this.storage,
|
||||
required this.storageDir,
|
||||
required this.refreshInterval,
|
||||
});
|
||||
StartConfig();
|
||||
|
||||
factory StartConfig.fromJson(Map<String, dynamic> json) =>
|
||||
_$StartConfigFromJson(json);
|
||||
|
||||
@@ -6,13 +6,13 @@ part of 'start_config.dart';
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
StartConfig _$StartConfigFromJson(Map<String, dynamic> json) => StartConfig(
|
||||
network: json['network'] as String,
|
||||
address: json['address'] as String,
|
||||
storage: json['storage'] as String,
|
||||
storageDir: json['storageDir'] as String,
|
||||
refreshInterval: json['refreshInterval'] as int,
|
||||
);
|
||||
StartConfig _$StartConfigFromJson(Map<String, dynamic> json) => StartConfig()
|
||||
..network = json['network'] as String
|
||||
..address = json['address'] as String
|
||||
..storage = json['storage'] as String
|
||||
..storageDir = json['storageDir'] as String
|
||||
..refreshInterval = json['refreshInterval'] as int
|
||||
..apiToken = json['apiToken'] as String;
|
||||
|
||||
Map<String, dynamic> _$StartConfigToJson(StartConfig instance) =>
|
||||
<String, dynamic>{
|
||||
@@ -21,4 +21,5 @@ Map<String, dynamic> _$StartConfigToJson(StartConfig instance) =>
|
||||
'storage': instance.storage,
|
||||
'storageDir': instance.storageDir,
|
||||
'refreshInterval': instance.refreshInterval,
|
||||
'apiToken': instance.apiToken,
|
||||
};
|
||||
@@ -1,22 +1,18 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:gopeed/core/common/start_config.dart';
|
||||
|
||||
import '../libgopeed_boot.dart';
|
||||
|
||||
LibgopeedBoot create() => LibgopeedBootBrowser();
|
||||
|
||||
class LibgopeedBootBrowser implements LibgopeedBoot {
|
||||
late LibgopeedConfig _config;
|
||||
|
||||
LibgopeedBootBrowser() {
|
||||
_config = LibgopeedConfig();
|
||||
// do nothing
|
||||
@override
|
||||
Future<int> start(StartConfig cfg) async {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@override
|
||||
LibgopeedConfig get config => _config;
|
||||
|
||||
@override
|
||||
Future<void> start() async {}
|
||||
|
||||
@override
|
||||
Future<void> stop() async {}
|
||||
}
|
||||
@@ -16,48 +16,30 @@ import '../libgopeed_boot.dart';
|
||||
LibgopeedBoot create() => LibgopeedBootNative();
|
||||
|
||||
class LibgopeedBootNative implements LibgopeedBoot {
|
||||
late LibgopeedConfig _config;
|
||||
late LibgopeedInterface _libgopeed;
|
||||
late SendPort _childSendPort;
|
||||
|
||||
LibgopeedBootNative() {
|
||||
_config = LibgopeedConfig();
|
||||
if (!Util.isDesktop()) {
|
||||
_libgopeed = LibgopeedChannel();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
LibgopeedConfig get config => _config;
|
||||
|
||||
@override
|
||||
Future<void> start() async {
|
||||
Future<int> start(StartConfig cfg) async {
|
||||
var storageDir = "./";
|
||||
if (!Util.isUnix()) {
|
||||
// not support unix socket, use tcp
|
||||
_config.network = "tcp";
|
||||
_config.address = "127.0.0.1:0";
|
||||
} else {
|
||||
_config.network = "unix";
|
||||
if (Util.isDesktop()) {
|
||||
_config.address = LibgopeedBoot.unixSocketPath;
|
||||
} else if (Platform.isAndroid) {
|
||||
_config.address =
|
||||
"${(await getTemporaryDirectory()).path}/${LibgopeedBoot.unixSocketPath}";
|
||||
storageDir = (await getExternalStorageDirectory())?.path ?? "";
|
||||
}
|
||||
if (Platform.isAndroid) {
|
||||
storageDir = (await getExternalStorageDirectory())?.path ?? storageDir;
|
||||
}
|
||||
final cfg = StartConfig(
|
||||
network: _config.network,
|
||||
address: _config.address,
|
||||
storage: 'bolt',
|
||||
storageDir: storageDir,
|
||||
refreshInterval: _config.refreshInterval);
|
||||
if (Platform.isIOS) {
|
||||
storageDir = (await getLibraryDirectory()).path;
|
||||
}
|
||||
cfg.storage = 'bolt';
|
||||
cfg.storageDir = storageDir;
|
||||
cfg.refreshInterval = 0;
|
||||
var port =
|
||||
Util.isDesktop() ? await _ffiStart(cfg) : await _libgopeed.start(cfg);
|
||||
if (_config.network == "tcp") {
|
||||
_config.address = "${_config.address.split(":")[0]}:$port";
|
||||
}
|
||||
return port;
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -1,19 +1,8 @@
|
||||
import 'common/start_config.dart';
|
||||
import "libgopeed_boot_stub.dart"
|
||||
if (dart.library.html) 'entry/libgopeed_boot_browser.dart'
|
||||
if (dart.library.io) 'entry/libgopeed_boot_native.dart';
|
||||
|
||||
class LibgopeedConfig {
|
||||
late String network;
|
||||
late String address;
|
||||
late int refreshInterval;
|
||||
|
||||
LibgopeedConfig({
|
||||
this.network = "tcp",
|
||||
this.address = "127.0.0.1:0",
|
||||
this.refreshInterval = 500,
|
||||
});
|
||||
}
|
||||
|
||||
abstract class LibgopeedBoot {
|
||||
static const unixSocketPath = 'gopeed.sock';
|
||||
|
||||
@@ -26,9 +15,7 @@ abstract class LibgopeedBoot {
|
||||
|
||||
factory LibgopeedBoot() => create();
|
||||
|
||||
Future<void> start();
|
||||
Future<int> start(StartConfig cfg);
|
||||
|
||||
Future<void> stop();
|
||||
|
||||
LibgopeedConfig get config;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
const enUS = {
|
||||
'en_US': {
|
||||
'label': 'English',
|
||||
'error': 'Error',
|
||||
'tip': 'Tip',
|
||||
'confirm': 'Confirm',
|
||||
'cancel': 'Cancel',
|
||||
'selectAll': 'Select All',
|
||||
'home.task': 'Task',
|
||||
'home.setting': 'Setting',
|
||||
'create.title': 'Create Task',
|
||||
'create.downloadLink': 'Download Link',
|
||||
'create.downloadLinkValid': 'Please enter the download link',
|
||||
'create.downloadLinkHit':
|
||||
'Please enter the download link, HTTP/HTTPS/MAGNET supported@append',
|
||||
'create.downloadLinkHitDesktop': ', or drag the torrent file here directly',
|
||||
'create.download': 'Download',
|
||||
'create.error.noStoragePermission': 'Storage permission required',
|
||||
'create.selectFile': 'Select File',
|
||||
'setting.title': 'Setting',
|
||||
'setting.basic': 'Basic',
|
||||
'setting.advanced': 'Advanced',
|
||||
'setting.general': 'General',
|
||||
'setting.downloadDir': 'Download Directory',
|
||||
'setting.downloadDirValid': 'Please select the download directory',
|
||||
'setting.connections': 'Connections',
|
||||
'setting.items': '@count items',
|
||||
'setting.subscribeTracker': 'Subscribe Tracker',
|
||||
'setting.subscribeFail':
|
||||
'Subscribe failed, please check network or try again later',
|
||||
'setting.update': 'Update',
|
||||
'setting.updateDaily': 'Update daily',
|
||||
'setting.lastUpdate': 'Last update: @time',
|
||||
'setting.addTracker': 'Add Tracker',
|
||||
'setting.addTrackerHit':
|
||||
'Please enter the tracker server url, one per line',
|
||||
'setting.ui': 'UI',
|
||||
'setting.theme': 'Theme',
|
||||
'setting.themeSystem': 'System',
|
||||
'setting.themeLight': 'Light',
|
||||
'setting.themeDark': 'Dark',
|
||||
'setting.locale': 'Language',
|
||||
'setting.about': 'About',
|
||||
'setting.homepage': 'Homepage',
|
||||
'setting.version': 'Version',
|
||||
'setting.protocol': 'Protocol',
|
||||
'setting.port': 'Port',
|
||||
'setting.apiToken': 'API Token',
|
||||
'setting.notSet': 'NS',
|
||||
'setting.set': 'SET',
|
||||
'setting.effectAfterRestart': 'Effect after restart',
|
||||
'task.deleteTask': 'Delete Task',
|
||||
'task.deleteTaskTip': 'Keep downloaded files',
|
||||
'task.delete': 'Delete',
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
const ruRU = {
|
||||
'ru_RU': {
|
||||
'label': 'Русский(Россия)',
|
||||
'error': 'Ошибка',
|
||||
'confirm': 'Подтвердить',
|
||||
'cancel': 'Отмена',
|
||||
'home.task': 'Задачи',
|
||||
'home.setting': 'Настройки',
|
||||
'create.title': 'Создать задачу',
|
||||
'create.downloadLink': 'Ссылка для скачивание',
|
||||
'create.downloadLinkValid': 'Пожалуйста, введите ссылку для скачивания',
|
||||
'create.downloadLinkHit':
|
||||
'Пожалуйста, введите ссылку для скачивания, HTTP/HTTPS/MAGNET supported@append',
|
||||
'create.downloadLinkHitDesktop': ', или перетащите сюда торрент-файл',
|
||||
'create.download': 'Скачать',
|
||||
'create.error.noStoragePermission': 'Требуется доступ к хранилищу',
|
||||
'create.selectDir': 'Выберите папку',
|
||||
'setting.title': 'Настройки',
|
||||
'setting.basic': 'Основные параметры',
|
||||
'setting.theme': 'Тема',
|
||||
'setting.themeSystem': 'Системная',
|
||||
'setting.themeLight': 'Светлая',
|
||||
'setting.themeDark': 'Тёмная',
|
||||
'setting.downloadDir': 'Папка загрузки',
|
||||
'setting.downloadDirValid': 'Пожалуйста, выберите папку загрузки',
|
||||
'setting.connections': 'Количество подключений',
|
||||
'setting.locale': 'Язык',
|
||||
'task.deleteTask': 'Удалить задачу',
|
||||
'task.deleteTaskTip': 'Сохранить загруженные файлы',
|
||||
'task.delete': 'Удалить',
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
const zhCN = {
|
||||
'zh_CN': {
|
||||
'label': '中文(简体)',
|
||||
'error': '错误',
|
||||
'tip': '提示',
|
||||
'confirm': '确认',
|
||||
'cancel': '取消',
|
||||
'selectAll': '全选',
|
||||
'home.task': '任务',
|
||||
'home.setting': '设置',
|
||||
'create.title': '创建任务',
|
||||
'create.downloadLink': '下载链接',
|
||||
'create.downloadLinkValid': '请输入下载链接',
|
||||
'create.downloadLinkHit': '请输入下载链接,支持 HTTP/HTTPS/MAGNET@append',
|
||||
'create.downloadLinkHitDesktop': ',也可以直接拖拽种子文件到此处',
|
||||
'create.download': '下载',
|
||||
'create.error.noStoragePermission': '需要开启存储权限',
|
||||
'create.selectFile': '选择文件',
|
||||
'setting.title': '设置',
|
||||
'setting.basic': '基础',
|
||||
'setting.advanced': '高级',
|
||||
'setting.general': '通用',
|
||||
'setting.downloadDir': '下载目录',
|
||||
'setting.downloadDirValid': '请选择下载目录',
|
||||
'setting.connections': '连接数',
|
||||
'setting.items': '@count 条',
|
||||
'setting.subscribeTracker': '订阅 Tracker',
|
||||
'setting.subscribeFail': '订阅失败,请检查网络或稍后重试',
|
||||
'setting.update': '更新',
|
||||
'setting.updateDaily': '每天自动更新',
|
||||
'setting.lastUpdate': '上次更新:@time',
|
||||
'setting.addTracker': '添加 Tracker',
|
||||
'setting.addTrackerHit': '请输入 tracker 服务器地址,每行一条',
|
||||
'setting.ui': '界面',
|
||||
'setting.theme': '主题',
|
||||
'setting.themeSystem': '跟随系统',
|
||||
'setting.themeLight': '明亮主题',
|
||||
'setting.themeDark': '暗黑主题',
|
||||
'setting.locale': '语言',
|
||||
'setting.about': '关于',
|
||||
'setting.homepage': '主页',
|
||||
'setting.version': '版本',
|
||||
'setting.protocol': '通讯协议',
|
||||
'setting.port': '端口',
|
||||
'setting.apiToken': '接口令牌',
|
||||
'setting.notSet': '未设置',
|
||||
'setting.set': '已设置',
|
||||
'setting.effectAfterRestart': '此配置项将在重启应用后生效',
|
||||
'task.deleteTask': '删除任务',
|
||||
'task.deleteTaskTip': '保留已下载的文件',
|
||||
'task.delete': '删除',
|
||||
}
|
||||
};
|
||||
@@ -1,6 +1,9 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import 'langs/en_us.dart';
|
||||
import 'langs/zh_cn.dart';
|
||||
|
||||
Locale toLocale(String key) {
|
||||
final arr = key.split('_');
|
||||
return Locale(arr[0], arr[1]);
|
||||
@@ -11,107 +14,11 @@ String getLocaleKey(Locale locale) {
|
||||
}
|
||||
|
||||
final messages = _Messages();
|
||||
const mainLocale = Locale('zh', 'CN');
|
||||
const fallbackLocale = Locale('en', 'US');
|
||||
|
||||
class _Messages extends Translations {
|
||||
// just include available locales here
|
||||
@override
|
||||
Map<String, Map<String, String>> get keys => {
|
||||
'zh_CN': {
|
||||
'error': '错误',
|
||||
'confirm': '确认',
|
||||
'cancel': '取消',
|
||||
'home.task': '任务',
|
||||
'home.setting': '设置',
|
||||
'create.title': '创建任务',
|
||||
'create.downloadLink': '下载链接',
|
||||
'create.downloadLinkValid': '请输入下载链接',
|
||||
'create.downloadLinkHit': '请输入下载链接,支持 HTTP/HTTPS/MAGNET@append',
|
||||
'create.downloadLinkHitDesktop': ',也可以直接拖拽种子文件到此处',
|
||||
'create.download': '下载',
|
||||
'create.error.noStoragePermission': '需要开启存储权限',
|
||||
'create.selectDir': '选择目录',
|
||||
'setting.title': '设置',
|
||||
'setting.basic': '基础设置',
|
||||
'setting.theme': '主题',
|
||||
'setting.themeSystem': '跟随系统',
|
||||
'setting.themeLight': '明亮主题',
|
||||
'setting.themeDark': '暗黑主题',
|
||||
'setting.downloadDir': '下载目录',
|
||||
'setting.downloadDirValid': '请选择下载目录',
|
||||
'setting.connections': '连接数',
|
||||
'setting.locale': '语言',
|
||||
'setting.locale.zh_CN': '中文(简体)',
|
||||
'setting.locale.en_US': '英文(美国)',
|
||||
'setting.locale.ru_RU': '俄语 (俄罗斯) ',
|
||||
'task.deleteTask': '删除任务',
|
||||
'task.deleteTaskTip': '保留已下载的文件',
|
||||
'task.delete': '删除',
|
||||
},
|
||||
'en_US': {
|
||||
'error': 'Error',
|
||||
'confirm': 'Confirm',
|
||||
'cancel': 'Cancel',
|
||||
'home.task': 'Task',
|
||||
'home.setting': 'Setting',
|
||||
'create.title': 'Create Task',
|
||||
'create.downloadLink': 'Download Link',
|
||||
'create.downloadLinkValid': 'Please enter the download link',
|
||||
'create.downloadLinkHit':
|
||||
'Please enter the download link, HTTP/HTTPS/MAGNET supported@append',
|
||||
'create.downloadLinkHitDesktop':
|
||||
', or drag the torrent file here directly',
|
||||
'create.download': 'Download',
|
||||
'create.error.noStoragePermission': 'Storage permission required',
|
||||
'create.selectDir': 'Select Directory',
|
||||
'setting.title': 'Setting',
|
||||
'setting.basic': 'Basic',
|
||||
'setting.theme': 'Theme',
|
||||
'setting.themeSystem': 'System',
|
||||
'setting.themeLight': 'Light',
|
||||
'setting.themeDark': 'Dark',
|
||||
'setting.downloadDir': 'Download Directory',
|
||||
'setting.downloadDirValid': 'Please select the download directory',
|
||||
'setting.connections': 'Connections',
|
||||
'setting.locale': 'Language',
|
||||
'setting.locale.zh_CN': 'Chinese(Simplified)',
|
||||
'setting.locale.en_US': 'English(US)',
|
||||
'setting.locale.ru_RU': 'Russian(Russia)',
|
||||
'task.deleteTask': 'Delete Task',
|
||||
'task.deleteTaskTip': 'Keep downloaded files',
|
||||
'task.delete': 'Delete',
|
||||
},
|
||||
'ru_RU': {
|
||||
'error': 'Ошибка',
|
||||
'confirm': 'Подтвердить',
|
||||
'cancel': 'Отмена',
|
||||
'home.task': 'Задачи',
|
||||
'home.setting': 'Настройки',
|
||||
'create.title': 'Создать задачу',
|
||||
'create.downloadLink': 'Ссылка для скачивание',
|
||||
'create.downloadLinkValid': 'Пожалуйста, введите ссылку для скачивания',
|
||||
'create.downloadLinkHit':
|
||||
'Пожалуйста, введите ссылку для скачивания, HTTP/HTTPS/MAGNET supported@append',
|
||||
'create.downloadLinkHitDesktop':
|
||||
', или перетащите сюда торрент-файл',
|
||||
'create.download': 'Скачать',
|
||||
'create.error.noStoragePermission': 'Требуется доступ к хранилищу',
|
||||
'create.selectDir': 'Выберите папку',
|
||||
'setting.title': 'Настройки',
|
||||
'setting.basic': 'Основные параметры',
|
||||
'setting.theme': 'Тема',
|
||||
'setting.themeSystem': 'Системная',
|
||||
'setting.themeLight': 'Светлая',
|
||||
'setting.themeDark': 'Тёмная',
|
||||
'setting.downloadDir': 'Папка загрузки',
|
||||
'setting.downloadDirValid': 'Пожалуйста, выберите папку загрузки',
|
||||
'setting.connections': 'Количество подключений',
|
||||
'setting.locale': 'Язык',
|
||||
'setting.locale.zh_CN': 'Китайский(Упрощенный)',
|
||||
'setting.locale.en_US': 'Английский(США)',
|
||||
'setting.locale.ru_RU': 'Русский(Россия)',
|
||||
'task.deleteTask': 'Удалить задачу',
|
||||
'task.deleteTaskTip': 'Сохранить загруженные файлы',
|
||||
'task.delete': 'Удалить',
|
||||
},
|
||||
};
|
||||
Map<String, Map<String, String>> get keys => {...zhCN, ...enUS};
|
||||
}
|
||||
+54
-18
@@ -1,33 +1,69 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:gopeed/api/api.dart' as api;
|
||||
import 'package:gopeed/i18n/messages.dart';
|
||||
|
||||
import 'core/libgopeed_boot.dart';
|
||||
import 'i18n/messages.dart';
|
||||
import 'routes/router.dart';
|
||||
import 'setting/setting.dart';
|
||||
import 'theme/theme.dart';
|
||||
import 'pages/app/app_controller.dart';
|
||||
import 'pages/app/app_view.dart';
|
||||
import 'util/log_util.dart';
|
||||
import 'util/mac_secure_util.dart';
|
||||
import 'util/package_info.dart';
|
||||
|
||||
void main() async {
|
||||
await init();
|
||||
onStart();
|
||||
|
||||
runApp(const AppView());
|
||||
}
|
||||
|
||||
Future<void> init() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
final controller = Get.put(AppController());
|
||||
try {
|
||||
await LibgopeedBoot.instance.start();
|
||||
await Setting.instance.load();
|
||||
await controller.loadStartConfig();
|
||||
final startCfg = controller.startConfig.value;
|
||||
controller.runningPort.value = await LibgopeedBoot.instance.start(startCfg);
|
||||
api.init(startCfg.network, controller.runningAddress(), startCfg.apiToken);
|
||||
} catch (e) {
|
||||
logger.e("init fail", e);
|
||||
logger.e("libgopeed init fail", e);
|
||||
}
|
||||
MacSecureUtil.loadBookmark();
|
||||
|
||||
runApp(GetMaterialApp.router(
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: GopeedTheme.light,
|
||||
darkTheme: GopeedTheme.dark,
|
||||
themeMode: Setting.instance.themeMode,
|
||||
translations: messages,
|
||||
locale: toLocale(Setting.instance.locale),
|
||||
fallbackLocale: fallbackLocale,
|
||||
getPages: Routes.routes,
|
||||
));
|
||||
try {
|
||||
await controller.loadDownloaderConfig();
|
||||
MacSecureUtil.loadBookmark();
|
||||
} catch (e) {
|
||||
logger.e("load config fail", e);
|
||||
}
|
||||
|
||||
try {
|
||||
await initPackageInfo();
|
||||
} catch (e) {
|
||||
logger.e("init package info fail", e);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> onStart() async {
|
||||
final appController = Get.find<AppController>();
|
||||
await appController.trackerUpdateOnStart();
|
||||
|
||||
// if is debug mode, check language message is complete
|
||||
if (kDebugMode) {
|
||||
final mainLang = getLocaleKey(mainLocale);
|
||||
final fullMessages = messages.keys[mainLang];
|
||||
messages.keys.keys.where((e) => e != mainLang).forEach((lang) {
|
||||
final langMessages = messages.keys[lang];
|
||||
if (langMessages == null) {
|
||||
logger.w("missing language: $lang");
|
||||
return;
|
||||
}
|
||||
final missingKeys =
|
||||
fullMessages!.keys.where((key) => langMessages[key] == null);
|
||||
if (missingKeys.isNotEmpty) {
|
||||
logger.w("missing language: $lang, keys: $missingKeys");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:external_path/external_path.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../api/api.dart';
|
||||
import '../../api/model/downloader_config.dart';
|
||||
import '../../core/common/start_config.dart';
|
||||
import '../../i18n/messages.dart';
|
||||
import '../../util/log_util.dart';
|
||||
import '../../util/util.dart';
|
||||
|
||||
const _startConfigNetwork = "start.network";
|
||||
const _startConfigAddress = "start.address";
|
||||
const _startConfigApiToken = "start.apiToken";
|
||||
|
||||
const unixSocketPath = 'gopeed.sock';
|
||||
|
||||
const allTrackerSubscribeUrls = [
|
||||
'https://github.com/ngosang/trackerslist/raw/master/trackers_all.txt',
|
||||
'https://github.com/ngosang/trackerslist/raw/master/trackers_all_http.txt',
|
||||
'https://github.com/ngosang/trackerslist/raw/master/trackers_all_https.txt',
|
||||
'https://github.com/ngosang/trackerslist/raw/master/trackers_all_ip.txt',
|
||||
'https://github.com/ngosang/trackerslist/raw/master/trackers_all_udp.txt',
|
||||
'https://github.com/ngosang/trackerslist/raw/master/trackers_all_ws.txt',
|
||||
'https://github.com/ngosang/trackerslist/raw/master/trackers_best.txt',
|
||||
'https://github.com/ngosang/trackerslist/raw/master/trackers_best_ip.txt',
|
||||
'https://github.com/XIU2/TrackersListCollection/raw/master/all.txt',
|
||||
'https://github.com/XIU2/TrackersListCollection/raw/master/best.txt',
|
||||
'https://github.com/XIU2/TrackersListCollection/raw/master/http.txt',
|
||||
];
|
||||
|
||||
class AppController extends GetxController {
|
||||
static StartConfig? _defaultStartConfig;
|
||||
|
||||
final startConfig = StartConfig().obs;
|
||||
final runningPort = 0.obs;
|
||||
final downloaderConfig = DownloaderConfig().obs;
|
||||
|
||||
String runningAddress() {
|
||||
if (startConfig.value.network == 'unix') {
|
||||
return startConfig.value.address;
|
||||
}
|
||||
return '${startConfig.value.address.split(':').first}:$runningPort';
|
||||
}
|
||||
|
||||
Future<StartConfig> _initDefaultStartConfig() async {
|
||||
if (_defaultStartConfig != null) {
|
||||
return _defaultStartConfig!;
|
||||
}
|
||||
_defaultStartConfig = StartConfig();
|
||||
if (!Util.isUnix()) {
|
||||
// not support unix socket, use tcp
|
||||
_defaultStartConfig!.network = "tcp";
|
||||
_defaultStartConfig!.address = "127.0.0.1:0";
|
||||
} else {
|
||||
_defaultStartConfig!.network = "unix";
|
||||
if (Util.isDesktop()) {
|
||||
_defaultStartConfig!.address = unixSocketPath;
|
||||
}
|
||||
if (Util.isMobile()) {
|
||||
_defaultStartConfig!.address =
|
||||
"${(await getTemporaryDirectory()).path}/$unixSocketPath";
|
||||
}
|
||||
}
|
||||
_defaultStartConfig!.apiToken = '';
|
||||
return _defaultStartConfig!;
|
||||
}
|
||||
|
||||
Future<void> loadStartConfig() async {
|
||||
final defaultCfg = await _initDefaultStartConfig();
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
startConfig.value.network =
|
||||
prefs.getString(_startConfigNetwork) ?? defaultCfg.network;
|
||||
startConfig.value.address =
|
||||
prefs.getString(_startConfigAddress) ?? defaultCfg.address;
|
||||
startConfig.value.apiToken =
|
||||
prefs.getString(_startConfigApiToken) ?? defaultCfg.apiToken;
|
||||
}
|
||||
|
||||
Future<void> loadDownloaderConfig() async {
|
||||
try {
|
||||
downloaderConfig.value = await getConfig();
|
||||
} catch (e) {
|
||||
logger.w("load downloader config fail", e);
|
||||
downloaderConfig.value = DownloaderConfig();
|
||||
}
|
||||
await _initDownloaderConfig();
|
||||
}
|
||||
|
||||
Future<void> trackerUpdate() async {
|
||||
final btExtConfig = downloaderConfig.value.extra.bt;
|
||||
final result = <String>[];
|
||||
for (var u in btExtConfig.trackerSubscribeUrls) {
|
||||
result.addAll(await _fetchTrackers(u));
|
||||
}
|
||||
btExtConfig.subscribeTrackers.clear();
|
||||
btExtConfig.subscribeTrackers.addAll(result);
|
||||
downloaderConfig.update((val) {
|
||||
val!.extra.bt.lastTrackerUpdateTime = DateTime.now();
|
||||
});
|
||||
refreshTrackers();
|
||||
|
||||
await saveConfig();
|
||||
}
|
||||
|
||||
refreshTrackers() {
|
||||
final btConfig = downloaderConfig.value.protocolConfig.bt;
|
||||
final btExtConfig = downloaderConfig.value.extra.bt;
|
||||
btConfig.trackers.clear();
|
||||
btConfig.trackers.addAll(btExtConfig.subscribeTrackers);
|
||||
btConfig.trackers.addAll(btExtConfig.customTrackers);
|
||||
// remove duplicate
|
||||
btConfig.trackers.toSet().toList();
|
||||
}
|
||||
|
||||
Future<void> trackerUpdateOnStart() async {
|
||||
final btExtConfig = downloaderConfig.value.extra.bt;
|
||||
final lastUpdateTime = btExtConfig.lastTrackerUpdateTime;
|
||||
// if last update time is null or more than 1 day, update trackers
|
||||
if (lastUpdateTime == null ||
|
||||
lastUpdateTime.difference(DateTime.now()).inDays < 0) {
|
||||
await trackerUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<String>> _fetchTrackers(String subscribeUrl) async {
|
||||
final resp = await proxyRequest(subscribeUrl);
|
||||
if (resp.statusCode != 200) {
|
||||
throw Exception('Failed to get trackers');
|
||||
}
|
||||
const ls = LineSplitter();
|
||||
return ls.convert(resp.data).where((e) => e.isNotEmpty).toList();
|
||||
}
|
||||
|
||||
_initDownloaderConfig() async {
|
||||
final config = downloaderConfig.value;
|
||||
if (config.protocolConfig.http.connections == 0) {
|
||||
config.protocolConfig.http.connections = 16;
|
||||
}
|
||||
final extra = config.extra;
|
||||
if (extra.themeMode.isEmpty) {
|
||||
extra.themeMode = ThemeMode.system.name;
|
||||
}
|
||||
if (extra.locale.isEmpty) {
|
||||
extra.locale = getLocaleKey(ui.window.locale);
|
||||
}
|
||||
if (extra.bt.trackerSubscribeUrls.isEmpty) {
|
||||
// default select all tracker subscribe urls
|
||||
extra.bt.trackerSubscribeUrls.addAll(allTrackerSubscribeUrls);
|
||||
}
|
||||
|
||||
if (Util.isAndroid()) {
|
||||
config.downloadDir =
|
||||
'${await ExternalPath.getExternalStoragePublicDirectory(ExternalPath.DIRECTORY_DOWNLOADS)}/com.gopeed';
|
||||
return;
|
||||
}
|
||||
|
||||
if (config.downloadDir.isEmpty) {
|
||||
if (Util.isWeb()) {
|
||||
config.downloadDir = './';
|
||||
}
|
||||
if (Util.isDesktop()) {
|
||||
config.downloadDir = (await getDownloadsDirectory())?.path ?? "./";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> saveConfig() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_startConfigNetwork, startConfig.value.network);
|
||||
await prefs.setString(_startConfigAddress, startConfig.value.address);
|
||||
await putConfig(downloaderConfig.value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../i18n/messages.dart';
|
||||
import '../../routes/router.dart';
|
||||
import '../../theme/theme.dart';
|
||||
import 'app_controller.dart';
|
||||
|
||||
class AppView extends GetView<AppController> {
|
||||
const AppView({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final config = controller.downloaderConfig.value;
|
||||
return GetMaterialApp.router(
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: GopeedTheme.light,
|
||||
darkTheme: GopeedTheme.dark,
|
||||
themeMode: ThemeMode.values.byName(config.extra.themeMode),
|
||||
translations: messages,
|
||||
locale: toLocale(config.extra.locale),
|
||||
fallbackLocale: fallbackLocale,
|
||||
getPages: Routes.routes,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,27 @@
|
||||
import 'package:desktop_drop/desktop_drop.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:permission_handler/permission_handler.dart';
|
||||
import 'package:rounded_loading_button/rounded_loading_button.dart';
|
||||
|
||||
import '../../api/api.dart';
|
||||
import '../../api/model/create_task.dart';
|
||||
import '../../api/model/options.dart';
|
||||
import '../../api/model/request.dart';
|
||||
import '../../api/model/resource.dart';
|
||||
import 'create_controller.dart';
|
||||
import '../../setting/setting.dart';
|
||||
import '../../widget/file_list_view.dart';
|
||||
import 'package:permission_handler/permission_handler.dart';
|
||||
import 'package:rounded_loading_button/rounded_loading_button.dart';
|
||||
|
||||
import '../../routes/router.dart';
|
||||
import '../../util/util.dart';
|
||||
import '../../widget/directory_selector.dart';
|
||||
import '../../widget/file_list_view.dart';
|
||||
import '../app/app_controller.dart';
|
||||
import 'create_controller.dart';
|
||||
|
||||
class CreateView extends GetView<CreateController> {
|
||||
CreateView({Key? key}) : super(key: key);
|
||||
|
||||
final _resolveFormKey = GlobalKey<FormState>();
|
||||
|
||||
final _urlController = TextEditingController();
|
||||
final _confirmController = RoundedLoadingButtonController();
|
||||
CreateView({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -103,9 +103,11 @@ class CreateView extends GetView<CreateController> {
|
||||
}
|
||||
|
||||
Future<void> _showResolveDialog(Resource res) async {
|
||||
final appController = Get.find<AppController>();
|
||||
final setting = appController.downloaderConfig.value;
|
||||
|
||||
final createFormKey = GlobalKey<FormState>();
|
||||
final pathController =
|
||||
TextEditingController(text: Setting.instance.downloadDir);
|
||||
final pathController = TextEditingController(text: setting.downloadDir);
|
||||
final downloadController = RoundedLoadingButtonController();
|
||||
var fileValues = List.filled(res.files.length, true);
|
||||
|
||||
@@ -181,7 +183,6 @@ class CreateView extends GetView<CreateController> {
|
||||
opts: Options(
|
||||
name: '',
|
||||
path: pathController.text,
|
||||
connections: Setting.instance.connections,
|
||||
selectFiles: fileValues
|
||||
.asMap()
|
||||
.entries
|
||||
|
||||
@@ -1,20 +1,4 @@
|
||||
import 'package:get/get.dart';
|
||||
import '../../api/api.dart';
|
||||
|
||||
class RootController extends GetxController {
|
||||
//TODO: Implement RootController
|
||||
|
||||
final count = 0.obs;
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
}
|
||||
|
||||
@override
|
||||
void onReady() {
|
||||
super.onReady();
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {}
|
||||
void increment() => count.value++;
|
||||
}
|
||||
class RootController extends GetxController {}
|
||||
@@ -1,12 +1,16 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../setting/setting.dart';
|
||||
|
||||
class SettingController extends GetxController {
|
||||
final setting = Setting.instance.obs;
|
||||
final tapStatues = <int, bool>{}.obs;
|
||||
final tapStatues = <String, bool>{}.obs;
|
||||
|
||||
void clearTapStatus() {
|
||||
tapStatues.clear();
|
||||
// set all tap status to false
|
||||
void clearTap() {
|
||||
tapStatues.updateAll((key, value) => false);
|
||||
}
|
||||
|
||||
// set one tap status to true
|
||||
void onTap(String key) {
|
||||
clearTap();
|
||||
tapStatues[key] = true;
|
||||
}
|
||||
}
|
||||
@@ -1,207 +1,548 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:gopeed/i18n/messages.dart';
|
||||
import 'package:gopeed/util/util.dart';
|
||||
import '../../setting/setting.dart';
|
||||
import '../../widget/directory_selector.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../../i18n/messages.dart';
|
||||
import '../../util/package_info.dart';
|
||||
import '../../util/util.dart';
|
||||
import '../../widget/check_list_view.dart';
|
||||
import '../../widget/directory_selector.dart';
|
||||
import '../../widget/outlined_button_loading.dart';
|
||||
import '../app/app_controller.dart';
|
||||
import 'setting_controller.dart';
|
||||
|
||||
const _padding = SizedBox(height: 10);
|
||||
final _divider = const Divider().paddingOnly(left: 10, right: 10);
|
||||
|
||||
class SettingView extends GetView<SettingController> {
|
||||
const SettingView({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final appController = Get.find<AppController>();
|
||||
final downloaderCfg = appController.downloaderConfig;
|
||||
final startCfg = appController.startConfig;
|
||||
|
||||
Timer? timer;
|
||||
debounceSave() {
|
||||
debounceSave({bool needRestart = false}) {
|
||||
var completer = Completer<void>();
|
||||
timer?.cancel();
|
||||
timer = Timer(const Duration(milliseconds: 500), () {
|
||||
Setting.instance
|
||||
.save()
|
||||
appController
|
||||
.saveConfig()
|
||||
.then(completer.complete)
|
||||
.onError(completer.completeError);
|
||||
if (needRestart) {
|
||||
Get.snackbar('tip'.tr, 'setting.effectAfterRestart'.tr);
|
||||
}
|
||||
});
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text('setting.title'.tr),
|
||||
centerTitle: true,
|
||||
),
|
||||
body: Column(
|
||||
// download basic config items start
|
||||
final buildDownloadDir = _buildConfigItem(
|
||||
'setting.downloadDir', () => downloaderCfg.value.downloadDir,
|
||||
(Key key) {
|
||||
final downloadDirController =
|
||||
TextEditingController(text: downloaderCfg.value.downloadDir);
|
||||
downloadDirController.addListener(() async {
|
||||
if (downloadDirController.text != downloaderCfg.value.downloadDir) {
|
||||
downloaderCfg.value.downloadDir = downloadDirController.text;
|
||||
if (Util.isDesktop()) {
|
||||
controller.clearTap();
|
||||
}
|
||||
|
||||
await debounceSave();
|
||||
}
|
||||
});
|
||||
return DirectorySelector(
|
||||
controller: downloadDirController,
|
||||
showLabel: false,
|
||||
);
|
||||
});
|
||||
|
||||
// http config items start
|
||||
final httpConfig = downloaderCfg.value.protocolConfig.http;
|
||||
final buildHttpConnections = _buildConfigItem(
|
||||
'setting.connections'.tr, () => httpConfig.connections.toString(),
|
||||
(Key key) {
|
||||
final connectionsController =
|
||||
TextEditingController(text: httpConfig.connections.toString());
|
||||
connectionsController.addListener(() async {
|
||||
if (connectionsController.text.isNotEmpty &&
|
||||
connectionsController.text != httpConfig.connections.toString()) {
|
||||
httpConfig.connections = int.parse(connectionsController.text);
|
||||
|
||||
await debounceSave();
|
||||
}
|
||||
});
|
||||
|
||||
return TextField(
|
||||
key: key,
|
||||
focusNode: FocusNode(),
|
||||
controller: connectionsController,
|
||||
keyboardType: TextInputType.number,
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.digitsOnly,
|
||||
_NumericalRangeFormatter(min: 1, max: 256),
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
// bt config items start
|
||||
final btExtConfig = downloaderCfg.value.extra.bt;
|
||||
|
||||
final buildBtTrackerSubscribeUrls = _buildConfigItem(
|
||||
'setting.subscribeTracker'.tr,
|
||||
() => 'setting.items'.trParams(
|
||||
{'count': btExtConfig.trackerSubscribeUrls.length.toString()}),
|
||||
(Key key) {
|
||||
final trackerUpdateController = OutlinedButtonLoadingController();
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('setting.basic'.tr, style: Get.textTheme.titleLarge),
|
||||
const SizedBox(height: 10),
|
||||
Obx(() => Card(
|
||||
child: Column(
|
||||
children: _buildConfigItems([
|
||||
_ConfigItem(
|
||||
'setting.theme'.tr,
|
||||
() => _getThemeName(controller.setting.value.themeMode),
|
||||
() => DropdownButton<ThemeMode>(
|
||||
value: controller.setting.value.themeMode,
|
||||
isDense: true,
|
||||
onChanged: (value) async {
|
||||
controller.setting.value.themeMode = value!;
|
||||
controller.clearTapStatus();
|
||||
Get.changeThemeMode(value);
|
||||
SizedBox(
|
||||
height: 200,
|
||||
child: CheckListView(
|
||||
items: allTrackerSubscribeUrls,
|
||||
checked: btExtConfig.trackerSubscribeUrls,
|
||||
onChanged: (value) {
|
||||
btExtConfig.trackerSubscribeUrls = value;
|
||||
|
||||
await debounceSave();
|
||||
},
|
||||
items: ThemeMode.values
|
||||
.map((e) => DropdownMenuItem<ThemeMode>(
|
||||
value: e,
|
||||
child: Text(_getThemeName(e)),
|
||||
))
|
||||
.toList(),
|
||||
)),
|
||||
_ConfigItem('setting.downloadDir'.tr,
|
||||
() => controller.setting.value.downloadDir, () {
|
||||
final downloadDirController = TextEditingController(
|
||||
text: controller.setting.value.downloadDir);
|
||||
downloadDirController.addListener(() async {
|
||||
if (downloadDirController.text !=
|
||||
controller.setting.value.downloadDir) {
|
||||
controller.setting.value.downloadDir =
|
||||
downloadDirController.text;
|
||||
if (Util.isDesktop()) {
|
||||
controller.clearTapStatus();
|
||||
}
|
||||
|
||||
await debounceSave();
|
||||
}
|
||||
});
|
||||
return DirectorySelector(
|
||||
controller: downloadDirController,
|
||||
showLabel: false,
|
||||
);
|
||||
}),
|
||||
_ConfigItem('setting.connections'.tr,
|
||||
() => controller.setting.value.connections.toString(),
|
||||
() {
|
||||
final connectionsController = TextEditingController(
|
||||
text: controller.setting.value.connections.toString());
|
||||
connectionsController.addListener(() async {
|
||||
if (connectionsController.text.isNotEmpty &&
|
||||
connectionsController.text !=
|
||||
controller.setting.value.connections.toString()) {
|
||||
controller.setting.value.connections =
|
||||
int.parse(connectionsController.text);
|
||||
|
||||
await debounceSave();
|
||||
}
|
||||
});
|
||||
|
||||
return TextField(
|
||||
controller: connectionsController,
|
||||
keyboardType: TextInputType.number,
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.digitsOnly,
|
||||
NumericalRangeFormatter(min: 1, max: 256),
|
||||
],
|
||||
);
|
||||
}),
|
||||
_ConfigItem(
|
||||
'setting.locale'.tr,
|
||||
() => _getLocaleName(controller.setting.value.locale),
|
||||
() => DropdownButton<String>(
|
||||
value: controller.setting.value.locale,
|
||||
isDense: true,
|
||||
onChanged: (value) async {
|
||||
controller.setting.value.locale = value!;
|
||||
controller.clearTapStatus();
|
||||
Get.updateLocale(toLocale(value));
|
||||
|
||||
await debounceSave();
|
||||
},
|
||||
items: _getLocales()
|
||||
.map((e) => DropdownMenuItem<String>(
|
||||
value:
|
||||
e.substring(_settingLocaleKey.length),
|
||||
child: Text(e.tr),
|
||||
))
|
||||
.toList(),
|
||||
)),
|
||||
]),
|
||||
))),
|
||||
debounceSave();
|
||||
},
|
||||
),
|
||||
),
|
||||
_padding,
|
||||
Row(
|
||||
children: [
|
||||
OutlinedButtonLoading(
|
||||
onPressed: () async {
|
||||
trackerUpdateController.start();
|
||||
try {
|
||||
await appController.trackerUpdate();
|
||||
} catch (e) {
|
||||
Get.snackbar('error'.tr, 'setting.subscribeFail'.tr);
|
||||
} finally {
|
||||
trackerUpdateController.stop();
|
||||
}
|
||||
},
|
||||
controller: trackerUpdateController,
|
||||
child: Text('setting.update'.tr),
|
||||
),
|
||||
Flexible(
|
||||
child: SizedBox(
|
||||
width: 200,
|
||||
child: SwitchListTile(
|
||||
controlAffinity: ListTileControlAffinity.leading,
|
||||
value: true,
|
||||
onChanged: (bool value) {},
|
||||
title: Text('setting.updateDaily'.tr)),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
Text('setting.lastUpdate'.trParams({
|
||||
'time': btExtConfig.lastTrackerUpdateTime != null
|
||||
? DateFormat('yyyy-MM-dd HH:mm:ss')
|
||||
.format(btExtConfig.lastTrackerUpdateTime!)
|
||||
: ''
|
||||
})),
|
||||
],
|
||||
).paddingAll(16),
|
||||
);
|
||||
});
|
||||
final buildBtTrackers = _buildConfigItem(
|
||||
'setting.addTracker'.tr,
|
||||
() => 'setting.items'
|
||||
.trParams({'count': btExtConfig.customTrackers.length.toString()}),
|
||||
(Key key) {
|
||||
final trackersController = TextEditingController(
|
||||
text: btExtConfig.customTrackers.join('\r\n').toString());
|
||||
const ls = LineSplitter();
|
||||
return TextField(
|
||||
key: key,
|
||||
focusNode: FocusNode(),
|
||||
controller: trackersController,
|
||||
keyboardType: TextInputType.multiline,
|
||||
maxLines: 5,
|
||||
decoration: InputDecoration(
|
||||
hintText: 'setting.addTrackerHit'.tr,
|
||||
),
|
||||
onChanged: (value) async {
|
||||
btExtConfig.customTrackers = ls.convert(value);
|
||||
appController.refreshTrackers();
|
||||
|
||||
await debounceSave();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
// ui config items start
|
||||
final buildTheme = _buildConfigItem(
|
||||
'setting.theme',
|
||||
() => _getThemeName(downloaderCfg.value.extra.themeMode),
|
||||
(Key key) => DropdownButton<String>(
|
||||
key: key,
|
||||
value: downloaderCfg.value.extra.themeMode,
|
||||
onChanged: (value) async {
|
||||
downloaderCfg.update((val) {
|
||||
val?.extra.themeMode = value!;
|
||||
});
|
||||
Get.changeThemeMode(ThemeMode.values.byName(value!));
|
||||
controller.clearTap();
|
||||
|
||||
await debounceSave();
|
||||
},
|
||||
items: ThemeMode.values
|
||||
.map((e) => DropdownMenuItem<String>(
|
||||
value: e.name,
|
||||
child: Text(_getThemeName(e.name)),
|
||||
))
|
||||
.toList(),
|
||||
));
|
||||
final buildLocale = _buildConfigItem(
|
||||
'setting.locale',
|
||||
() => messages.keys[downloaderCfg.value.extra.locale]!['label']!,
|
||||
(Key key) => DropdownButton<String>(
|
||||
key: key,
|
||||
value: downloaderCfg.value.extra.locale,
|
||||
isDense: true,
|
||||
onChanged: (value) async {
|
||||
downloaderCfg.update((val) {
|
||||
val!.extra.locale = value!;
|
||||
});
|
||||
Get.updateLocale(toLocale(value!));
|
||||
controller.clearTap();
|
||||
|
||||
await debounceSave();
|
||||
},
|
||||
items: messages.keys.keys
|
||||
.map((e) => DropdownMenuItem<String>(
|
||||
value: e,
|
||||
child: Text(messages.keys[e]!['label']!),
|
||||
))
|
||||
.toList(),
|
||||
));
|
||||
|
||||
// about config items start
|
||||
buildHomepage() => ListTile(
|
||||
title: Text('主页'.tr),
|
||||
subtitle: const Text('https://github.com/monkeyWie/gopeed'),
|
||||
onTap: () {
|
||||
launchUrl(Uri.parse('https://github.com/monkeyWie/gopeed'));
|
||||
},
|
||||
);
|
||||
buildVersion() => ListTile(
|
||||
title: Text('版本'.tr),
|
||||
subtitle: Text(packageInfo.version),
|
||||
);
|
||||
|
||||
// advanced config items start
|
||||
final buildApiProtocol = _buildConfigItem(
|
||||
'setting.protocol'.tr,
|
||||
() => startCfg.value.network == 'tcp'
|
||||
? 'TCP ${startCfg.value.address}'
|
||||
: 'Unix',
|
||||
(Key key) {
|
||||
final items = <Widget>[
|
||||
SizedBox(
|
||||
width: 150,
|
||||
child: DropdownButtonFormField<String>(
|
||||
value: startCfg.value.network,
|
||||
onChanged: (value) async {
|
||||
startCfg.update((val) {
|
||||
val!.network = value!;
|
||||
});
|
||||
|
||||
await debounceSave(needRestart: true);
|
||||
},
|
||||
items: [
|
||||
!Util.isMobile()
|
||||
? const DropdownMenuItem<String>(
|
||||
value: 'tcp',
|
||||
child: Text('TCP'),
|
||||
)
|
||||
: null,
|
||||
Util.isUnix()
|
||||
? const DropdownMenuItem<String>(
|
||||
value: 'unix',
|
||||
child: Text('Unix'),
|
||||
)
|
||||
: null,
|
||||
].where((e) => e != null).map((e) => e!).toList(),
|
||||
),
|
||||
)
|
||||
];
|
||||
if (Util.isDesktop() && startCfg.value.network == 'tcp') {
|
||||
final arr = startCfg.value.address.split(':');
|
||||
var ip = '127.0.0.1';
|
||||
var port = '0';
|
||||
if (arr.length > 1) {
|
||||
ip = arr[0];
|
||||
port = arr[1];
|
||||
}
|
||||
|
||||
final ipController = TextEditingController(text: ip);
|
||||
final portController = TextEditingController(text: port);
|
||||
updateAddress() async {
|
||||
final newAddress = '${ipController.text}:${portController.text}';
|
||||
if (newAddress != startCfg.value.address) {
|
||||
startCfg.value.address = newAddress;
|
||||
|
||||
await debounceSave(needRestart: true);
|
||||
}
|
||||
}
|
||||
|
||||
ipController.addListener(updateAddress);
|
||||
portController.addListener(updateAddress);
|
||||
items.addAll([
|
||||
const Padding(padding: EdgeInsets.only(left: 20)),
|
||||
SizedBox(
|
||||
width: 200,
|
||||
child: TextFormField(
|
||||
controller: ipController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'IP',
|
||||
contentPadding: EdgeInsets.all(0.0),
|
||||
),
|
||||
keyboardType: TextInputType.number,
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.allow(RegExp('[0-9.]')),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Padding(padding: EdgeInsets.only(left: 10)),
|
||||
SizedBox(
|
||||
width: 200,
|
||||
child: TextFormField(
|
||||
controller: portController,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'setting.port'.tr,
|
||||
contentPadding: const EdgeInsets.all(0.0),
|
||||
),
|
||||
keyboardType: TextInputType.number,
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.digitsOnly,
|
||||
_NumericalRangeFormatter(min: 0, max: 65535),
|
||||
],
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
return Form(
|
||||
child: Row(
|
||||
children: items,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
final buildApiToken = _buildConfigItem(
|
||||
'setting.apiToken'.tr,
|
||||
() => startCfg.value.apiToken.isEmpty
|
||||
? 'setting.notSet'.tr
|
||||
: 'setting.seted'.tr, (Key key) {
|
||||
final apiTokenController =
|
||||
TextEditingController(text: startCfg.value.apiToken);
|
||||
apiTokenController.addListener(() async {
|
||||
if (apiTokenController.text != startCfg.value.apiToken) {
|
||||
startCfg.value.apiToken = apiTokenController.text;
|
||||
|
||||
await debounceSave(needRestart: true);
|
||||
}
|
||||
});
|
||||
apiTokenController.addListener(() async {});
|
||||
return TextField(
|
||||
key: key,
|
||||
obscureText: true,
|
||||
controller: apiTokenController,
|
||||
focusNode: FocusNode(),
|
||||
);
|
||||
});
|
||||
|
||||
return Obx(() {
|
||||
return GestureDetector(
|
||||
onTap: () {
|
||||
controller.clearTap();
|
||||
},
|
||||
child: DefaultTabController(
|
||||
length: 2,
|
||||
child: Scaffold(
|
||||
appBar: PreferredSize(
|
||||
preferredSize: Size.fromHeight(56),
|
||||
child: AppBar(
|
||||
bottom: TabBar(
|
||||
tabs: [
|
||||
Tab(
|
||||
text: 'setting.basic'.tr,
|
||||
),
|
||||
Tab(
|
||||
text: 'setting.advanced'.tr,
|
||||
),
|
||||
],
|
||||
),
|
||||
)),
|
||||
body: TabBarView(
|
||||
children: [
|
||||
SingleChildScrollView(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: _addPadding([
|
||||
Text('setting.general'.tr),
|
||||
Card(
|
||||
child: Column(
|
||||
children: _addDivider([
|
||||
buildDownloadDir(),
|
||||
]),
|
||||
)),
|
||||
const Text('HTTP'),
|
||||
Card(
|
||||
child: Column(
|
||||
children: _addDivider([
|
||||
buildHttpConnections(),
|
||||
]),
|
||||
)),
|
||||
const Text('BitTorrent'),
|
||||
Card(
|
||||
child: Column(
|
||||
children: _addDivider([
|
||||
buildBtTrackerSubscribeUrls(),
|
||||
buildBtTrackers(),
|
||||
]),
|
||||
)),
|
||||
Text('setting.ui'.tr),
|
||||
Card(
|
||||
child: Column(
|
||||
children: _addDivider([
|
||||
buildTheme(),
|
||||
buildLocale(),
|
||||
]),
|
||||
)),
|
||||
Text('setting.about'.tr),
|
||||
Card(
|
||||
child: Column(
|
||||
children: _addDivider([
|
||||
buildHomepage(),
|
||||
buildVersion(),
|
||||
]),
|
||||
)),
|
||||
]),
|
||||
),
|
||||
),
|
||||
Column(
|
||||
children: [
|
||||
Card(
|
||||
child: Column(
|
||||
children: [
|
||||
..._addDivider([
|
||||
buildApiProtocol(),
|
||||
Util.isDesktop() && startCfg.value.network == 'tcp'
|
||||
? buildApiToken()
|
||||
: null,
|
||||
]),
|
||||
],
|
||||
)),
|
||||
],
|
||||
),
|
||||
],
|
||||
).paddingOnly(left: 16, right: 16, top: 16, bottom: 64)),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
List<Widget> _buildConfigItems(List<_ConfigItem> buildItems) {
|
||||
void _tapInputWidget(GlobalKey key) {
|
||||
if (key.currentContext == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (key.currentContext?.widget is TextField) {
|
||||
final textField = key.currentContext?.widget as TextField;
|
||||
textField.focusNode?.requestFocus();
|
||||
return;
|
||||
}
|
||||
|
||||
/* GestureDetector? detector;
|
||||
void searchForGestureDetector(BuildContext? element) {
|
||||
element?.visitChildElements((element) {
|
||||
if (element.widget is GestureDetector) {
|
||||
detector = element.widget as GestureDetector?;
|
||||
} else {
|
||||
searchForGestureDetector(element);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
searchForGestureDetector(key.currentContext);
|
||||
detector?.onTap?.call(); */
|
||||
}
|
||||
|
||||
Widget Function() _buildConfigItem(
|
||||
String label, String Function() text, Widget Function(Key key) input) {
|
||||
final tapStatues = controller.tapStatues;
|
||||
final inputKey = GlobalKey();
|
||||
return () => ListTile(
|
||||
title: Text(label.tr),
|
||||
subtitle: tapStatues[label] ?? false ? input(inputKey) : Text(text()),
|
||||
onTap: () {
|
||||
controller.onTap(label);
|
||||
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
|
||||
_tapInputWidget(inputKey);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
List<Widget> _addPadding(List<Widget> widgets) {
|
||||
final result = <Widget>[];
|
||||
for (var i = 0; i < buildItems.length; i++) {
|
||||
final buildItem = buildItems[i];
|
||||
result.add(ListTile(
|
||||
title: Text(buildItem.label),
|
||||
subtitle: controller.tapStatues[i] ?? false
|
||||
? buildItem.inputItem()
|
||||
: Text(buildItem.text()),
|
||||
onTap: () {
|
||||
controller.tapStatues[i] = true;
|
||||
// set other false
|
||||
for (var j = 0; j < controller.tapStatues.length; j++) {
|
||||
if (j != i) {
|
||||
controller.tapStatues[j] = false;
|
||||
}
|
||||
}
|
||||
}));
|
||||
if (i != buildItems.length - 1) {
|
||||
result.add(const Divider());
|
||||
for (var i = 0; i < widgets.length; i++) {
|
||||
result.add(widgets[i]);
|
||||
result.add(_padding);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
List<Widget> _addDivider(List<Widget?> widgets) {
|
||||
final result = <Widget>[];
|
||||
final newArr = widgets.where((e) => e != null).map((e) => e!).toList();
|
||||
for (var i = 0; i < newArr.length; i++) {
|
||||
result.add(newArr[i]);
|
||||
if (i != newArr.length - 1) {
|
||||
result.add(_divider);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
String _getThemeName(ThemeMode themeMode) {
|
||||
switch (themeMode) {
|
||||
case ThemeMode.system:
|
||||
return 'setting.themeSystem'.tr;
|
||||
String _getThemeName(String? themeMode) {
|
||||
switch (ThemeMode.values.byName(themeMode ?? ThemeMode.system.name)) {
|
||||
case ThemeMode.light:
|
||||
return 'setting.themeLight'.tr;
|
||||
case ThemeMode.dark:
|
||||
return 'setting.themeDark'.tr;
|
||||
default:
|
||||
return 'setting.themeSystem'.tr;
|
||||
}
|
||||
}
|
||||
|
||||
final _settingLocaleKey = 'setting.locale.';
|
||||
|
||||
List<String> _getLocales() {
|
||||
return messages.keys[getLocaleKey(fallbackLocale)]!.entries
|
||||
.where((e) => e.key.startsWith(_settingLocaleKey))
|
||||
.map((e) => e.key)
|
||||
.toList();
|
||||
}
|
||||
|
||||
String _getLocaleName(String locale) {
|
||||
final localeKey = '$_settingLocaleKey${locale.toString()}';
|
||||
if (messages.keys[locale]?.containsKey(localeKey) ?? false) {
|
||||
return localeKey.tr;
|
||||
}
|
||||
return '$_settingLocaleKey$locale'.tr;
|
||||
}
|
||||
}
|
||||
|
||||
class _ConfigItem {
|
||||
late String label;
|
||||
late String Function() text;
|
||||
late Widget Function() inputItem;
|
||||
late Widget Function(Key key) inputItem;
|
||||
|
||||
_ConfigItem(this.label, this.text, this.inputItem);
|
||||
}
|
||||
|
||||
class NumericalRangeFormatter extends TextInputFormatter {
|
||||
class _NumericalRangeFormatter extends TextInputFormatter {
|
||||
final int min;
|
||||
final int max;
|
||||
|
||||
NumericalRangeFormatter({required this.min, required this.max});
|
||||
_NumericalRangeFormatter({required this.min, required this.max});
|
||||
|
||||
@override
|
||||
TextEditingValue formatEditUpdate(
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
import '../../api/model/task.dart';
|
||||
import '../../core/libgopeed_boot.dart';
|
||||
|
||||
import '../../api/api.dart';
|
||||
import '../../api/model/task.dart';
|
||||
|
||||
class TaskController extends GetxController {
|
||||
final tabIndex = 0.obs;
|
||||
@@ -16,27 +15,6 @@ class TaskController extends GetxController {
|
||||
|
||||
late final Timer _timer;
|
||||
|
||||
_loadUnDone() async {
|
||||
unDoneTasks.value = await getTasks(
|
||||
[Status.ready, Status.running, Status.pause, Status.error]);
|
||||
final lastLastSize = _lastUnDoneSize;
|
||||
if (lastLastSize != unDoneTasks.length) {
|
||||
_lastUnDoneSize = unDoneTasks.length;
|
||||
}
|
||||
// when unDoneTasks.length reduce, it means some task is done, refresh doneTasks
|
||||
return lastLastSize > _lastUnDoneSize;
|
||||
}
|
||||
|
||||
_loadDone() async {
|
||||
doneTasks.value = await getTasks([Status.done]);
|
||||
final lastLastSize = _lastDoneSize;
|
||||
if (lastLastSize != doneTasks.length) {
|
||||
_lastDoneSize = doneTasks.length;
|
||||
}
|
||||
// when doneTasks.length increase, it means some task is done, refresh unDoneTasks
|
||||
return lastLastSize < _lastDoneSize;
|
||||
}
|
||||
|
||||
loadTab() async {
|
||||
if (tabIndex.value == 0) {
|
||||
if (await _loadUnDone()) {
|
||||
@@ -49,22 +27,41 @@ class TaskController extends GetxController {
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
|
||||
loadTab();
|
||||
_timer = Timer.periodic(
|
||||
Duration(milliseconds: LibgopeedBoot.instance.config.refreshInterval),
|
||||
(timer) async {
|
||||
loadTab();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
super.onClose();
|
||||
|
||||
_timer.cancel();
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
|
||||
loadTab();
|
||||
_timer = Timer.periodic(const Duration(milliseconds: 1000), (timer) async {
|
||||
loadTab();
|
||||
});
|
||||
}
|
||||
|
||||
_loadDone() async {
|
||||
doneTasks.value = await getTasks([Status.done]);
|
||||
final lastLastSize = _lastDoneSize;
|
||||
if (lastLastSize != doneTasks.length) {
|
||||
_lastDoneSize = doneTasks.length;
|
||||
}
|
||||
// when doneTasks.length increase, it means some task is done, refresh unDoneTasks
|
||||
return lastLastSize < _lastDoneSize;
|
||||
}
|
||||
|
||||
_loadUnDone() async {
|
||||
unDoneTasks.value = await getTasks(
|
||||
[Status.ready, Status.running, Status.pause, Status.error]);
|
||||
final lastLastSize = _lastUnDoneSize;
|
||||
if (lastLastSize != unDoneTasks.length) {
|
||||
_lastUnDoneSize = unDoneTasks.length;
|
||||
}
|
||||
// when unDoneTasks.length reduce, it means some task is done, refresh doneTasks
|
||||
return lastLastSize > _lastUnDoneSize;
|
||||
}
|
||||
}
|
||||
@@ -2,62 +2,14 @@ import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import '../../api/api.dart';
|
||||
import '../../api/model/task.dart';
|
||||
import 'package:styled_widget/styled_widget.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../../api/api.dart';
|
||||
import '../../api/model/task.dart';
|
||||
import '../../util/util.dart';
|
||||
import 'task_controller.dart';
|
||||
|
||||
class TaskView extends GetView<TaskController> {
|
||||
const TaskView({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DefaultTabController(
|
||||
length: 2,
|
||||
child: Scaffold(
|
||||
appBar: PreferredSize(
|
||||
preferredSize: const Size.fromHeight(56),
|
||||
child: AppBar(
|
||||
bottom: TabBar(
|
||||
tabs: const [
|
||||
Tab(
|
||||
icon: Icon(Icons.file_download),
|
||||
),
|
||||
Tab(
|
||||
icon: Icon(Icons.done),
|
||||
),
|
||||
],
|
||||
onTap: (index) {
|
||||
controller.tabIndex.value = index;
|
||||
if (index == 1) {
|
||||
controller.loadTab();
|
||||
}
|
||||
},
|
||||
),
|
||||
)),
|
||||
body: TabBarView(
|
||||
children: [
|
||||
Obx(() => buildTaskList(controller.unDoneTasks)),
|
||||
Obx(() => buildTaskList(controller.doneTasks)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget buildTaskList(List<Task> tasks) {
|
||||
return ListView.builder(
|
||||
itemCount: tasks.length,
|
||||
itemBuilder: (context, index) {
|
||||
return Item(task: tasks[index]);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class Item extends StatelessWidget {
|
||||
final Task task;
|
||||
|
||||
@@ -79,22 +31,20 @@ class Item extends StatelessWidget {
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
flex: 1,
|
||||
child: Text(
|
||||
"${isDone() ? "" : "${Util.fmtByte(task.progress.downloaded)} / "}${Util.fmtByte(task.size)}",
|
||||
style: Get.textTheme.bodyText1
|
||||
?.copyWith(color: Get.theme.disabledColor),
|
||||
).padding(left: 18)),
|
||||
"${isDone() ? "" : "${Util.fmtByte(task.progress.downloaded)} / "}${Util.fmtByte(task.size)}",
|
||||
style: context.textTheme.bodyText1
|
||||
?.copyWith(color: Get.theme.disabledColor),
|
||||
).padding(left: 18)),
|
||||
Expanded(
|
||||
flex: 1,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
Text("${Util.fmtByte(task.progress.speed)} / s",
|
||||
style: Get.textTheme.subtitle2),
|
||||
...buildActions()
|
||||
],
|
||||
)),
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
Text("${Util.fmtByte(task.progress.speed)} / s",
|
||||
style: context.textTheme.subtitle2),
|
||||
...buildActions()
|
||||
],
|
||||
)),
|
||||
],
|
||||
),
|
||||
LinearProgressIndicator(
|
||||
@@ -144,18 +94,32 @@ class Item extends StatelessWidget {
|
||||
return list;
|
||||
}
|
||||
|
||||
double getProgress() {
|
||||
return task.size <= 0 ? 1 : task.progress.downloaded / task.size;
|
||||
}
|
||||
|
||||
bool isDone() {
|
||||
return task.status == Status.done;
|
||||
}
|
||||
|
||||
bool isRunning() {
|
||||
return task.status == Status.running;
|
||||
}
|
||||
|
||||
Future<void> _showDeleteDialog(String id) {
|
||||
final keep = true.obs;
|
||||
|
||||
final context = Get.context!;
|
||||
|
||||
return showDialog<void>(
|
||||
context: Get.context!,
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => AlertDialog(
|
||||
title: Text('task.deleteTask'.tr),
|
||||
content: Obx(() => CheckboxListTile(
|
||||
value: keep.value,
|
||||
title: Text('task.deleteTaskTip'.tr,
|
||||
style: Get.textTheme.bodyText1),
|
||||
style: context.textTheme.bodyText1),
|
||||
onChanged: (v) {
|
||||
keep.value = v!;
|
||||
})),
|
||||
@@ -182,16 +146,52 @@ class Item extends StatelessWidget {
|
||||
],
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
double getProgress() {
|
||||
return task.size <= 0 ? 1 : task.progress.downloaded / task.size;
|
||||
class TaskView extends GetView<TaskController> {
|
||||
const TaskView({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DefaultTabController(
|
||||
length: 2,
|
||||
child: Scaffold(
|
||||
appBar: PreferredSize(
|
||||
preferredSize: const Size.fromHeight(56),
|
||||
child: AppBar(
|
||||
bottom: TabBar(
|
||||
tabs: const [
|
||||
Tab(
|
||||
icon: Icon(Icons.file_download),
|
||||
),
|
||||
Tab(
|
||||
icon: Icon(Icons.done),
|
||||
),
|
||||
],
|
||||
onTap: (index) {
|
||||
if (controller.tabIndex.value != index) {
|
||||
controller.tabIndex.value = index;
|
||||
controller.loadTab();
|
||||
}
|
||||
},
|
||||
),
|
||||
)),
|
||||
body: TabBarView(
|
||||
children: [
|
||||
Obx(() => buildTaskList(controller.unDoneTasks)),
|
||||
Obx(() => buildTaskList(controller.doneTasks)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
bool isRunning() {
|
||||
return task.status == Status.running;
|
||||
}
|
||||
|
||||
bool isDone() {
|
||||
return task.status == Status.done;
|
||||
Widget buildTaskList(List<Task> tasks) {
|
||||
return ListView.builder(
|
||||
itemCount: tasks.length,
|
||||
itemBuilder: (context, index) {
|
||||
return Item(task: tasks[index]);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
import 'package:get/get.dart';
|
||||
import '../pages/create/create_controller.dart';
|
||||
import '../pages/setting/setting_view.dart';
|
||||
|
||||
import '../pages/create/create_controller.dart';
|
||||
import '../pages/create/create_view.dart';
|
||||
import '../pages/home/home_controller.dart';
|
||||
import '../pages/home/home_view.dart';
|
||||
import '../pages/root/root_controller.dart';
|
||||
import '../pages/root/root_view.dart';
|
||||
import '../pages/setting/setting_controller.dart';
|
||||
import '../pages/setting/setting_view.dart';
|
||||
import '../pages/task/task_controller.dart';
|
||||
import '../pages/task/task_view.dart';
|
||||
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
import 'package:external_path/external_path.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gopeed/i18n/messages.dart';
|
||||
import '../api/api.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import '../api/model/server_config.dart';
|
||||
import '../util/util.dart';
|
||||
|
||||
class Setting {
|
||||
String host = "127.0.0.1";
|
||||
int port = 0;
|
||||
int connections = 0;
|
||||
late String downloadDir;
|
||||
late ThemeMode themeMode;
|
||||
late String locale;
|
||||
|
||||
// singleton pattern
|
||||
static Setting? _instance;
|
||||
|
||||
static Setting get instance {
|
||||
_instance ??= Setting._internal();
|
||||
_instance!.themeMode = ThemeMode.system;
|
||||
_instance!.locale = getLocaleKey(ui.window.locale);
|
||||
return _instance!;
|
||||
}
|
||||
|
||||
Setting._internal();
|
||||
|
||||
Future<void> load() async {
|
||||
final config = await getConfig();
|
||||
host = config.host;
|
||||
port = config.port;
|
||||
connections = config.connections;
|
||||
downloadDir = config.downloadDir;
|
||||
final themeMode = config.extra?['themeMode'];
|
||||
if (themeMode != null) {
|
||||
this.themeMode = ThemeMode.values.byName(themeMode);
|
||||
}
|
||||
final locale = config.extra?['locale'];
|
||||
if (locale != null) {
|
||||
this.locale = locale;
|
||||
}
|
||||
|
||||
if (Util.isAndroid()) {
|
||||
downloadDir =
|
||||
'${await ExternalPath.getExternalStoragePublicDirectory(ExternalPath.DIRECTORY_DOWNLOADS)}/com.gopeed';
|
||||
return;
|
||||
}
|
||||
|
||||
if (downloadDir.isEmpty) {
|
||||
if (Util.isWeb()) {
|
||||
downloadDir = './';
|
||||
}
|
||||
if (Util.isDesktop()) {
|
||||
downloadDir = (await getDownloadsDirectory())!.path;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> save() async {
|
||||
final config = ServerConfig(
|
||||
host: host,
|
||||
port: port,
|
||||
connections: connections,
|
||||
downloadDir: downloadDir,
|
||||
extra: {
|
||||
'themeMode': themeMode.name,
|
||||
'locale': locale,
|
||||
},
|
||||
);
|
||||
await putConfig(config);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:logger/logger.dart';
|
||||
import 'package:logger/src/outputs/file_output.dart';
|
||||
|
||||
@@ -7,5 +8,13 @@ import 'util.dart';
|
||||
|
||||
final logger = Logger(
|
||||
printer: PrettyPrinter(),
|
||||
output: Util.isDesktop() ? FileOutput(file: File('log.txt')) : null,
|
||||
output: buildOutput(),
|
||||
);
|
||||
|
||||
buildOutput() {
|
||||
// if is debug mode, output to console
|
||||
if (!kDebugMode && Util.isDesktop()) {
|
||||
return FileOutput(file: File('log.txt'));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
|
||||
late PackageInfo packageInfo;
|
||||
|
||||
Future<void> initPackageInfo() async {
|
||||
packageInfo = await PackageInfo.fromPlatform();
|
||||
}
|
||||
@@ -3,6 +3,14 @@ import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
class Util {
|
||||
static String buildAbsPath(String dir, String path, String name) {
|
||||
return (dir == "" ? "" : "$dir/") + buildPath(path, name);
|
||||
}
|
||||
|
||||
static String buildPath(String path, String name) {
|
||||
return (path == "" ? "" : "$path/") + name;
|
||||
}
|
||||
|
||||
static String fmtByte(int byte) {
|
||||
if (byte < 1024) {
|
||||
return "$byte B";
|
||||
@@ -15,24 +23,16 @@ class Util {
|
||||
}
|
||||
}
|
||||
|
||||
static String buildPath(String path, String name) {
|
||||
return (path == "" ? "" : "$path/") + name;
|
||||
}
|
||||
|
||||
static String buildAbsPath(String dir, String path, String name) {
|
||||
return (dir == "" ? "" : "$dir/") + buildPath(path, name);
|
||||
}
|
||||
|
||||
static isWeb() {
|
||||
return kIsWeb;
|
||||
}
|
||||
|
||||
static isAndroid() {
|
||||
return !kIsWeb && Platform.isAndroid;
|
||||
}
|
||||
|
||||
static isMacos() {
|
||||
return !kIsWeb && Platform.isMacOS;
|
||||
static isIOS() {
|
||||
return !kIsWeb && Platform.isIOS;
|
||||
}
|
||||
|
||||
static isMobile() {
|
||||
return !kIsWeb && (Platform.isAndroid || Platform.isIOS);
|
||||
}
|
||||
|
||||
static isDesktop() {
|
||||
@@ -42,10 +42,18 @@ class Util {
|
||||
return Platform.isWindows || Platform.isLinux || Platform.isMacOS;
|
||||
}
|
||||
|
||||
static isMacos() {
|
||||
return !kIsWeb && Platform.isMacOS;
|
||||
}
|
||||
|
||||
static isUnix() {
|
||||
if (kIsWeb) {
|
||||
return false;
|
||||
}
|
||||
return !Platform.isWindows;
|
||||
}
|
||||
|
||||
static isWeb() {
|
||||
return kIsWeb;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
class CheckListView extends StatefulWidget {
|
||||
final List<String> items;
|
||||
final List<String> checked;
|
||||
final void Function(List<String> value) onChanged;
|
||||
|
||||
const CheckListView({
|
||||
Key? key,
|
||||
required this.items,
|
||||
required this.checked,
|
||||
required this.onChanged,
|
||||
}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<CheckListView> createState() => _CheckListView();
|
||||
}
|
||||
|
||||
class _CheckListView extends State<CheckListView> {
|
||||
bool get _allChecked => _checked.length == _items.length;
|
||||
|
||||
List<String> get _checked => widget.checked;
|
||||
|
||||
List<String> get _items => widget.items;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(top: 10),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: Colors.grey, width: 1),
|
||||
borderRadius: BorderRadius.circular(5)),
|
||||
child: Column(
|
||||
children: [
|
||||
CheckboxListTile(
|
||||
value: _allChecked,
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
_checked.clear();
|
||||
if (value!) {
|
||||
_checked.addAll(_items);
|
||||
}
|
||||
widget.onChanged(_checked);
|
||||
});
|
||||
},
|
||||
title: Text('selectAll'.tr),
|
||||
),
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
itemCount: _items.length,
|
||||
itemBuilder: (context, index) {
|
||||
var item = _items[index];
|
||||
return CheckboxListTile(
|
||||
value: _checked.contains(item),
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
_checked.contains(item)
|
||||
? _checked.remove(item)
|
||||
: _checked.add(item);
|
||||
widget.onChanged(_checked);
|
||||
});
|
||||
},
|
||||
title: Text(item),
|
||||
);
|
||||
}),
|
||||
),
|
||||
],
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import 'package:file_selector/file_selector.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:gopeed/util/util.dart';
|
||||
|
||||
import '../util/mac_secure_util.dart';
|
||||
import '../util/util.dart';
|
||||
|
||||
class DirectorySelector extends StatefulWidget {
|
||||
final TextEditingController controller;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import '../util/util.dart';
|
||||
|
||||
import '../api/model/resource.dart';
|
||||
import '../util/util.dart';
|
||||
|
||||
class FileListView extends StatefulWidget {
|
||||
final List<FileInfo> files;
|
||||
@@ -30,7 +30,7 @@ class _FileListViewState extends State<FileListView> {
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Padding(padding: EdgeInsets.only(top: 10)),
|
||||
Text('create.selectDir'.tr,
|
||||
Text('create.selectFile'.tr,
|
||||
style: TextStyle(color: themeData.hintColor)),
|
||||
Expanded(
|
||||
child: Container(
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class OutlinedButtonLoading extends StatefulWidget {
|
||||
final Widget child;
|
||||
final VoidCallback onPressed;
|
||||
final OutlinedButtonLoadingController controller;
|
||||
|
||||
const OutlinedButtonLoading(
|
||||
{super.key,
|
||||
required this.child,
|
||||
required this.onPressed,
|
||||
required this.controller});
|
||||
|
||||
@override
|
||||
State<OutlinedButtonLoading> createState() => _OutlinedButtonLoadingState();
|
||||
}
|
||||
|
||||
class _OutlinedButtonLoadingState extends State<OutlinedButtonLoading> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ValueListenableBuilder<bool>(
|
||||
valueListenable: widget.controller,
|
||||
builder: (context, value, child) {
|
||||
return OutlinedButton(
|
||||
key: widget.key,
|
||||
onPressed: value ? null : widget.onPressed,
|
||||
child: value
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
),
|
||||
)
|
||||
: widget.child,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class OutlinedButtonLoadingController extends ValueNotifier<bool> {
|
||||
OutlinedButtonLoadingController() : super(false);
|
||||
|
||||
void start() {
|
||||
value = true;
|
||||
}
|
||||
|
||||
void stop() {
|
||||
value = false;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ PODS:
|
||||
- FlutterMacOS (1.0.0)
|
||||
- macos_secure_bookmarks (0.0.3):
|
||||
- FlutterMacOS
|
||||
- package_info_plus (0.0.1):
|
||||
- FlutterMacOS
|
||||
- path_provider_macos (0.0.1):
|
||||
- FlutterMacOS
|
||||
- shared_preferences_macos (0.0.1):
|
||||
@@ -18,6 +20,7 @@ DEPENDENCIES:
|
||||
- file_selector_macos (from `Flutter/ephemeral/.symlinks/plugins/file_selector_macos/macos`)
|
||||
- FlutterMacOS (from `Flutter/ephemeral`)
|
||||
- macos_secure_bookmarks (from `Flutter/ephemeral/.symlinks/plugins/macos_secure_bookmarks/macos`)
|
||||
- package_info_plus (from `Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos`)
|
||||
- path_provider_macos (from `Flutter/ephemeral/.symlinks/plugins/path_provider_macos/macos`)
|
||||
- shared_preferences_macos (from `Flutter/ephemeral/.symlinks/plugins/shared_preferences_macos/macos`)
|
||||
- url_launcher_macos (from `Flutter/ephemeral/.symlinks/plugins/url_launcher_macos/macos`)
|
||||
@@ -31,6 +34,8 @@ EXTERNAL SOURCES:
|
||||
:path: Flutter/ephemeral
|
||||
macos_secure_bookmarks:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/macos_secure_bookmarks/macos
|
||||
package_info_plus:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos
|
||||
path_provider_macos:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/path_provider_macos/macos
|
||||
shared_preferences_macos:
|
||||
@@ -43,6 +48,7 @@ SPEC CHECKSUMS:
|
||||
file_selector_macos: f1b08a781e66103e3ba279fd5d4024a2478b3af6
|
||||
FlutterMacOS: ae6af50a8ea7d6103d888583d46bd8328a7e9811
|
||||
macos_secure_bookmarks: cff041c4b377fa00941bb901aaec4d27fac5edf2
|
||||
package_info_plus: 02d7a575e80f194102bef286361c6c326e4c29ce
|
||||
path_provider_macos: 3c0c3b4b0d4a76d2bf989a913c2de869c5641a19
|
||||
shared_preferences_macos: a64dc611287ed6cbe28fd1297898db1336975727
|
||||
url_launcher_macos: 597e05b8e514239626bcf4a850fcf9ef5c856ec3
|
||||
|
||||
+15
-1
@@ -376,7 +376,7 @@ packages:
|
||||
source: hosted
|
||||
version: "3.2.2"
|
||||
intl:
|
||||
dependency: transitive
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: intl
|
||||
url: "https://pub.flutter-io.cn"
|
||||
@@ -494,6 +494,20 @@ packages:
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.1.0"
|
||||
package_info_plus:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: package_info_plus
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "3.0.2"
|
||||
package_info_plus_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: package_info_plus_platform_interface
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.0.1"
|
||||
path:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -15,7 +15,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev
|
||||
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
|
||||
# Read more about iOS versioning at
|
||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||
version: 1.0.0+1
|
||||
version: 1.2.0+1
|
||||
|
||||
environment:
|
||||
sdk: ">=2.17.6 <3.0.0"
|
||||
@@ -50,6 +50,8 @@ dependencies:
|
||||
external_path: ^1.0.3
|
||||
logger: ^1.1.0
|
||||
desktop_drop: ^0.3.3
|
||||
intl: ^0.17.0
|
||||
package_info_plus: ^3.0.2
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
Reference in new issue
Block a user