mirror of
https://github.com/GopeedLab/gopeed.git
synced 2026-11-14 12:23:43 +00:00
feat: flutter ui integration
This commit is contained in:
1 parent
0fc133e46d
commit
c4a30dc4c2
170 files changed
+7783
-1
No files matched your search
@@ -0,0 +1,107 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:dio/adapter.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:gopeed/api/model/create_task.dart';
|
||||
import 'package:gopeed/api/model/request.dart';
|
||||
import 'package:gopeed/api/model/resource.dart';
|
||||
import 'package:gopeed/api/model/result.dart';
|
||||
import 'package:gopeed/api/model/task.dart';
|
||||
|
||||
import '../core/libgopeed_boot.dart';
|
||||
import 'model/server_config.dart';
|
||||
|
||||
class _Client {
|
||||
static _Client? _instance;
|
||||
|
||||
late Dio dio;
|
||||
|
||||
_Client._internal();
|
||||
|
||||
factory _Client() {
|
||||
if (_instance == null) {
|
||||
_instance = _Client._internal();
|
||||
var dio = Dio();
|
||||
dio.options.baseUrl = "http://127.0.0.1:${LibgopeedBoot.instance.port}";
|
||||
_instance!.dio = dio;
|
||||
(_instance!.dio.httpClientAdapter as DefaultHttpClientAdapter)
|
||||
.onHttpClientCreate = (client) {
|
||||
if (LibgopeedBoot.instance.network == "unix") {
|
||||
client.connectionFactory =
|
||||
(Uri uri, String? proxyHost, int? proxyPort) {
|
||||
var address = InternetAddress(LibgopeedBoot.instance.address,
|
||||
type: InternetAddressType.unix);
|
||||
return Socket.startConnect(address, 0);
|
||||
};
|
||||
}
|
||||
return client;
|
||||
};
|
||||
}
|
||||
return _instance!;
|
||||
}
|
||||
}
|
||||
|
||||
var _client = _Client();
|
||||
|
||||
Future<T> _parse<T>(
|
||||
Future<Response> Function() fetch,
|
||||
T Function(dynamic json)? fromJsonT,
|
||||
) async {
|
||||
try {
|
||||
var resp = await fetch();
|
||||
if (fromJsonT != null) {
|
||||
return Result<T>.fromJson(jsonDecode(resp.data), fromJsonT).data as T;
|
||||
} else {
|
||||
return null as T;
|
||||
}
|
||||
} on DioError catch (e) {
|
||||
if (e.response == null) {
|
||||
throw Exception("Server error");
|
||||
}
|
||||
throw Exception(
|
||||
Result.fromJson(jsonDecode(e.response?.data), (_) => null).msg);
|
||||
}
|
||||
}
|
||||
|
||||
Future<Resource> resolve(Request request) async {
|
||||
return _parse<Resource>(
|
||||
() => _client.dio.post("/api/v1/resolve", data: request),
|
||||
(data) => Resource.fromJson(data));
|
||||
}
|
||||
|
||||
Future<String> createTask(CreateTask createTask) async {
|
||||
print(jsonEncode(createTask));
|
||||
return _parse<String>(
|
||||
() => _client.dio.post("/api/v1/tasks", data: createTask),
|
||||
(data) => data as String);
|
||||
}
|
||||
|
||||
Future<List<Task>> getTasks(List<Status> statuses) async {
|
||||
return _parse<List<Task>>(
|
||||
() => _client.dio
|
||||
.get("/api/v1/tasks?status=${statuses.map((e) => e.name).join(",")}"),
|
||||
(data) => (data as List).map((e) => Task.fromJson(e)).toList());
|
||||
}
|
||||
|
||||
Future<void> pauseTask(String id) async {
|
||||
return _parse(() => _client.dio.put("/api/v1/tasks/$id/pause"), null);
|
||||
}
|
||||
|
||||
Future<void> continueTask(String id) async {
|
||||
return _parse(() => _client.dio.put("/api/v1/tasks/$id/continue"), null);
|
||||
}
|
||||
|
||||
Future<void> deleteTask(String id, bool force) async {
|
||||
return _parse(
|
||||
() => _client.dio.delete("/api/v1/tasks/$id?force=$force"), null);
|
||||
}
|
||||
|
||||
Future<ServerConfig> getConfig() async {
|
||||
return _parse(() => _client.dio.get("/api/v1/config"),
|
||||
(data) => ServerConfig.fromJson(data));
|
||||
}
|
||||
|
||||
Future<void> putConfig(ServerConfig config) async {
|
||||
return _parse(() => _client.dio.put("/api/v1/config", data: config), null);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
import 'options.dart';
|
||||
import 'resource.dart';
|
||||
|
||||
part 'create_task.g.dart';
|
||||
|
||||
@JsonSerializable(explicitToJson: true)
|
||||
class CreateTask {
|
||||
Resource res;
|
||||
Options? opts;
|
||||
|
||||
CreateTask({
|
||||
required this.res,
|
||||
this.opts,
|
||||
});
|
||||
|
||||
factory CreateTask.fromJson(Map<String, dynamic> json) =>
|
||||
_$CreateTaskFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$CreateTaskToJson(this);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'create_task.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
CreateTask _$CreateTaskFromJson(Map<String, dynamic> json) => CreateTask(
|
||||
res: Resource.fromJson(json['res'] as Map<String, dynamic>),
|
||||
opts: json['opts'] == null
|
||||
? null
|
||||
: Options.fromJson(json['opts'] as Map<String, dynamic>),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$CreateTaskToJson(CreateTask instance) {
|
||||
final val = <String, dynamic>{
|
||||
'res': instance.res.toJson(),
|
||||
};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
writeNotNull('opts', instance.opts?.toJson());
|
||||
return val;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
part 'options.g.dart';
|
||||
|
||||
@JsonSerializable()
|
||||
class Options {
|
||||
String name;
|
||||
String path;
|
||||
int connections;
|
||||
List<int> selectFiles;
|
||||
|
||||
Options({
|
||||
required this.name,
|
||||
required this.path,
|
||||
required this.connections,
|
||||
required this.selectFiles,
|
||||
});
|
||||
|
||||
factory Options.fromJson(Map<String, dynamic> json) =>
|
||||
_$OptionsFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$OptionsToJson(this);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'options.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
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(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$OptionsToJson(Options instance) => <String, dynamic>{
|
||||
'name': instance.name,
|
||||
'path': instance.path,
|
||||
'connections': instance.connections,
|
||||
'selectFiles': instance.selectFiles,
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
part 'request.g.dart';
|
||||
|
||||
@JsonSerializable()
|
||||
class Request {
|
||||
String url;
|
||||
Map<String, dynamic>? extra;
|
||||
|
||||
Request({
|
||||
required this.url,
|
||||
this.extra,
|
||||
});
|
||||
|
||||
factory Request.fromJson(Map<String, dynamic> json) =>
|
||||
_$RequestFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$RequestToJson(this);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'request.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
Request _$RequestFromJson(Map<String, dynamic> json) => Request(
|
||||
url: json['url'] as String,
|
||||
extra: json['extra'] as Map<String, dynamic>?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$RequestToJson(Request instance) {
|
||||
final val = <String, dynamic>{
|
||||
'url': instance.url,
|
||||
};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
writeNotNull('extra', instance.extra);
|
||||
return val;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import 'request.dart';
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
part 'resource.g.dart';
|
||||
|
||||
@JsonSerializable(explicitToJson: true)
|
||||
class Resource {
|
||||
Request req;
|
||||
String name;
|
||||
int size;
|
||||
bool range;
|
||||
List<FileInfo> files;
|
||||
Map<String, dynamic>? extra;
|
||||
|
||||
Resource({
|
||||
required this.req,
|
||||
required this.name,
|
||||
required this.size,
|
||||
required this.range,
|
||||
required this.files,
|
||||
this.extra,
|
||||
});
|
||||
|
||||
factory Resource.fromJson(Map<String, dynamic> json) =>
|
||||
_$ResourceFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$ResourceToJson(this);
|
||||
}
|
||||
|
||||
@JsonSerializable()
|
||||
class FileInfo {
|
||||
String name;
|
||||
String path;
|
||||
int size;
|
||||
|
||||
FileInfo({
|
||||
required this.name,
|
||||
required this.path,
|
||||
required this.size,
|
||||
});
|
||||
|
||||
factory FileInfo.fromJson(Map<String, dynamic> json) =>
|
||||
_$FileInfoFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$FileInfoToJson(this);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'resource.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
Resource _$ResourceFromJson(Map<String, dynamic> json) => Resource(
|
||||
req: Request.fromJson(json['req'] as Map<String, dynamic>),
|
||||
name: json['name'] as String,
|
||||
size: json['size'] as int,
|
||||
range: json['range'] as bool,
|
||||
files: (json['files'] as List<dynamic>)
|
||||
.map((e) => FileInfo.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
extra: json['extra'] as Map<String, dynamic>?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$ResourceToJson(Resource instance) {
|
||||
final val = <String, dynamic>{
|
||||
'req': instance.req.toJson(),
|
||||
'name': instance.name,
|
||||
'size': instance.size,
|
||||
'range': instance.range,
|
||||
'files': instance.files.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
writeNotNull('extra', instance.extra);
|
||||
return val;
|
||||
}
|
||||
|
||||
FileInfo _$FileInfoFromJson(Map<String, dynamic> json) => FileInfo(
|
||||
name: json['name'] as String,
|
||||
path: json['path'] as String,
|
||||
size: json['size'] as int,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$FileInfoToJson(FileInfo instance) => <String, dynamic>{
|
||||
'name': instance.name,
|
||||
'path': instance.path,
|
||||
'size': instance.size,
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
part 'result.g.dart';
|
||||
|
||||
@JsonSerializable(genericArgumentFactories: true)
|
||||
class Result<T> {
|
||||
String? msg;
|
||||
T? data;
|
||||
|
||||
Result({
|
||||
this.msg,
|
||||
this.data,
|
||||
});
|
||||
|
||||
factory Result.fromJson(
|
||||
Map<String, dynamic> json,
|
||||
T Function(dynamic json) fromJsonT,
|
||||
) =>
|
||||
_$ResultFromJson(json, fromJsonT);
|
||||
Map<String, dynamic> toJson() => {
|
||||
'msg': msg,
|
||||
'data': data is List
|
||||
? (data as dynamic)?.map((e) => e.toJson()).toList()
|
||||
: (data as dynamic)?.toJson(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'result.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
Result<T> _$ResultFromJson<T>(
|
||||
Map<String, dynamic> json,
|
||||
T Function(Object? json) fromJsonT,
|
||||
) =>
|
||||
Result<T>(
|
||||
msg: json['msg'] as String?,
|
||||
data: _$nullableGenericFromJson(json['data'], fromJsonT),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$ResultToJson<T>(
|
||||
Result<T> instance,
|
||||
Object? Function(T value) toJsonT,
|
||||
) {
|
||||
final val = <String, dynamic>{};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
writeNotNull('msg', instance.msg);
|
||||
writeNotNull('data', _$nullableGenericToJson(instance.data, toJsonT));
|
||||
return val;
|
||||
}
|
||||
|
||||
T? _$nullableGenericFromJson<T>(
|
||||
Object? input,
|
||||
T Function(Object? json) fromJson,
|
||||
) =>
|
||||
input == null ? null : fromJson(input);
|
||||
|
||||
Object? _$nullableGenericToJson<T>(
|
||||
T? input,
|
||||
Object? Function(T value) toJson,
|
||||
) =>
|
||||
input == null ? null : toJson(input);
|
||||
@@ -0,0 +1,24 @@
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import 'options.dart';
|
||||
import 'resource.dart';
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
part 'task.g.dart';
|
||||
|
||||
enum Status { ready, running, pause, error, done }
|
||||
|
||||
@JsonSerializable()
|
||||
class Task {
|
||||
String id;
|
||||
Resource res;
|
||||
Options opts;
|
||||
Status status;
|
||||
Progress progress;
|
||||
int size;
|
||||
DateTime createdAt;
|
||||
|
||||
Task({
|
||||
required this.id,
|
||||
required this.res,
|
||||
required this.opts,
|
||||
required this.status,
|
||||
required this.progress,
|
||||
required this.size,
|
||||
required this.createdAt,
|
||||
});
|
||||
|
||||
factory Task.fromJson(Map<String, dynamic> json) => _$TaskFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$TaskToJson(this);
|
||||
}
|
||||
|
||||
@JsonSerializable()
|
||||
class Progress {
|
||||
int used;
|
||||
int speed;
|
||||
int downloaded;
|
||||
|
||||
Progress({
|
||||
required this.used,
|
||||
required this.speed,
|
||||
required this.downloaded,
|
||||
});
|
||||
|
||||
factory Progress.fromJson(Map<String, dynamic> json) =>
|
||||
_$ProgressFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$ProgressToJson(this);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'task.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
Task _$TaskFromJson(Map<String, dynamic> json) => Task(
|
||||
id: json['id'] as String,
|
||||
res: Resource.fromJson(json['res'] as Map<String, dynamic>),
|
||||
opts: Options.fromJson(json['opts'] as Map<String, dynamic>),
|
||||
status: $enumDecode(_$StatusEnumMap, json['status']),
|
||||
progress: Progress.fromJson(json['progress'] as Map<String, dynamic>),
|
||||
size: json['size'] as int,
|
||||
createdAt: DateTime.parse(json['createdAt'] as String),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$TaskToJson(Task instance) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'res': instance.res,
|
||||
'opts': instance.opts,
|
||||
'status': _$StatusEnumMap[instance.status]!,
|
||||
'progress': instance.progress,
|
||||
'size': instance.size,
|
||||
'createdAt': instance.createdAt.toIso8601String(),
|
||||
};
|
||||
|
||||
const _$StatusEnumMap = {
|
||||
Status.ready: 'ready',
|
||||
Status.running: 'running',
|
||||
Status.pause: 'pause',
|
||||
Status.error: 'error',
|
||||
Status.done: 'done',
|
||||
};
|
||||
|
||||
Progress _$ProgressFromJson(Map<String, dynamic> json) => Progress(
|
||||
used: json['used'] as int,
|
||||
speed: json['speed'] as int,
|
||||
downloaded: json['downloaded'] as int,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$ProgressToJson(Progress instance) => <String, dynamic>{
|
||||
'used': instance.used,
|
||||
'speed': instance.speed,
|
||||
'downloaded': instance.downloaded,
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:gopeed/core/common/libgopeed_interface.dart';
|
||||
import 'package:gopeed/core/common/start_config.dart';
|
||||
|
||||
class LibgopeedChannel implements LibgopeedInterface {
|
||||
static const _channel = MethodChannel('gopeed.com/libgopeed');
|
||||
|
||||
@override
|
||||
Future<int> start(StartConfig cfg) async {
|
||||
final port = await _channel.invokeMethod('start', {
|
||||
'cfg': jsonEncode(cfg),
|
||||
});
|
||||
return port as int;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> stop() async {
|
||||
return await _channel.invokeMethod('stop');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:ffi';
|
||||
|
||||
import 'package:ffi/ffi.dart';
|
||||
import 'package:gopeed/core/ffi/libgopeed_bind.dart';
|
||||
|
||||
import 'libgopeed_interface.dart';
|
||||
import 'start_config.dart';
|
||||
|
||||
class LibgopeedFFi implements LibgopeedInterface {
|
||||
late LibgopeedBind _libgopeed;
|
||||
|
||||
LibgopeedFFi(LibgopeedBind libgopeed) {
|
||||
_libgopeed = libgopeed;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<int> start(StartConfig cfg) {
|
||||
var completer = Completer<int>();
|
||||
var result = _libgopeed.Start(jsonEncode(cfg).toNativeUtf8().cast());
|
||||
if (result.r1 != nullptr) {
|
||||
completer.completeError(result.r1.cast<Utf8>().toDartString());
|
||||
} else {
|
||||
completer.complete(result.r0);
|
||||
}
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> stop() {
|
||||
var completer = Completer<void>();
|
||||
_libgopeed.Stop();
|
||||
completer.complete();
|
||||
return completer.future;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import 'package:gopeed/core/common/start_config.dart';
|
||||
|
||||
abstract class LibgopeedInterface {
|
||||
Future<int> start(StartConfig cfg);
|
||||
|
||||
Future<void> stop();
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
part 'start_config.g.dart';
|
||||
|
||||
@JsonSerializable()
|
||||
class StartConfig {
|
||||
String network;
|
||||
String address;
|
||||
String storage;
|
||||
String storageDir;
|
||||
int refreshInterval;
|
||||
|
||||
StartConfig({
|
||||
required this.network,
|
||||
required this.address,
|
||||
required this.storage,
|
||||
required this.storageDir,
|
||||
required this.refreshInterval,
|
||||
});
|
||||
|
||||
factory StartConfig.fromJson(Map<String, dynamic> json) =>
|
||||
_$StartConfigFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$StartConfigToJson(this);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
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,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$StartConfigToJson(StartConfig instance) =>
|
||||
<String, dynamic>{
|
||||
'network': instance.network,
|
||||
'address': instance.address,
|
||||
'storage': instance.storage,
|
||||
'storageDir': instance.storageDir,
|
||||
'refreshInterval': instance.refreshInterval,
|
||||
};
|
||||
@@ -0,0 +1,241 @@
|
||||
// AUTO GENERATED FILE, DO NOT EDIT.
|
||||
//
|
||||
// Generated by `package:ffigen`.
|
||||
import 'dart:ffi' as ffi;
|
||||
|
||||
/// Bindings to gopeed core.
|
||||
class LibgopeedBind {
|
||||
/// Holds the symbol lookup function.
|
||||
final ffi.Pointer<T> Function<T extends ffi.NativeType>(String symbolName)
|
||||
_lookup;
|
||||
|
||||
/// The symbols are looked up in [dynamicLibrary].
|
||||
LibgopeedBind(ffi.DynamicLibrary dynamicLibrary)
|
||||
: _lookup = dynamicLibrary.lookup;
|
||||
|
||||
/// The symbols are looked up with [lookup].
|
||||
LibgopeedBind.fromLookup(
|
||||
ffi.Pointer<T> Function<T extends ffi.NativeType>(String symbolName)
|
||||
lookup)
|
||||
: _lookup = lookup;
|
||||
|
||||
Start_return Start(
|
||||
ffi.Pointer<ffi.Char> cfg,
|
||||
) {
|
||||
return _Start(
|
||||
cfg,
|
||||
);
|
||||
}
|
||||
|
||||
late final _StartPtr =
|
||||
_lookup<ffi.NativeFunction<Start_return Function(ffi.Pointer<ffi.Char>)>>(
|
||||
'Start');
|
||||
late final _Start =
|
||||
_StartPtr.asFunction<Start_return Function(ffi.Pointer<ffi.Char>)>();
|
||||
|
||||
void Stop() {
|
||||
return _Stop();
|
||||
}
|
||||
|
||||
late final _StopPtr =
|
||||
_lookup<ffi.NativeFunction<ffi.Void Function()>>('Stop');
|
||||
late final _Stop = _StopPtr.asFunction<void Function()>();
|
||||
}
|
||||
|
||||
class __mbstate_t extends ffi.Union {
|
||||
@ffi.Array.multi([128])
|
||||
external ffi.Array<ffi.Char> __mbstate8;
|
||||
|
||||
@ffi.LongLong()
|
||||
external int _mbstateL;
|
||||
}
|
||||
|
||||
class __darwin_pthread_handler_rec extends ffi.Struct {
|
||||
external ffi
|
||||
.Pointer<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<ffi.Void>)>>
|
||||
__routine;
|
||||
|
||||
external ffi.Pointer<ffi.Void> __arg;
|
||||
|
||||
external ffi.Pointer<__darwin_pthread_handler_rec> __next;
|
||||
}
|
||||
|
||||
class _opaque_pthread_attr_t extends ffi.Struct {
|
||||
@ffi.Long()
|
||||
external int __sig;
|
||||
|
||||
@ffi.Array.multi([56])
|
||||
external ffi.Array<ffi.Char> __opaque;
|
||||
}
|
||||
|
||||
class _opaque_pthread_cond_t extends ffi.Struct {
|
||||
@ffi.Long()
|
||||
external int __sig;
|
||||
|
||||
@ffi.Array.multi([40])
|
||||
external ffi.Array<ffi.Char> __opaque;
|
||||
}
|
||||
|
||||
class _opaque_pthread_condattr_t extends ffi.Struct {
|
||||
@ffi.Long()
|
||||
external int __sig;
|
||||
|
||||
@ffi.Array.multi([8])
|
||||
external ffi.Array<ffi.Char> __opaque;
|
||||
}
|
||||
|
||||
class _opaque_pthread_mutex_t extends ffi.Struct {
|
||||
@ffi.Long()
|
||||
external int __sig;
|
||||
|
||||
@ffi.Array.multi([56])
|
||||
external ffi.Array<ffi.Char> __opaque;
|
||||
}
|
||||
|
||||
class _opaque_pthread_mutexattr_t extends ffi.Struct {
|
||||
@ffi.Long()
|
||||
external int __sig;
|
||||
|
||||
@ffi.Array.multi([8])
|
||||
external ffi.Array<ffi.Char> __opaque;
|
||||
}
|
||||
|
||||
class _opaque_pthread_once_t extends ffi.Struct {
|
||||
@ffi.Long()
|
||||
external int __sig;
|
||||
|
||||
@ffi.Array.multi([8])
|
||||
external ffi.Array<ffi.Char> __opaque;
|
||||
}
|
||||
|
||||
class _opaque_pthread_rwlock_t extends ffi.Struct {
|
||||
@ffi.Long()
|
||||
external int __sig;
|
||||
|
||||
@ffi.Array.multi([192])
|
||||
external ffi.Array<ffi.Char> __opaque;
|
||||
}
|
||||
|
||||
class _opaque_pthread_rwlockattr_t extends ffi.Struct {
|
||||
@ffi.Long()
|
||||
external int __sig;
|
||||
|
||||
@ffi.Array.multi([16])
|
||||
external ffi.Array<ffi.Char> __opaque;
|
||||
}
|
||||
|
||||
class _opaque_pthread_t extends ffi.Struct {
|
||||
@ffi.Long()
|
||||
external int __sig;
|
||||
|
||||
external ffi.Pointer<__darwin_pthread_handler_rec> __cleanup_stack;
|
||||
|
||||
@ffi.Array.multi([8176])
|
||||
external ffi.Array<ffi.Char> __opaque;
|
||||
}
|
||||
|
||||
class _GoString_ extends ffi.Struct {
|
||||
external ffi.Pointer<ffi.Char> p;
|
||||
|
||||
@ptrdiff_t()
|
||||
external int n;
|
||||
}
|
||||
|
||||
typedef ptrdiff_t = __darwin_ptrdiff_t;
|
||||
typedef __darwin_ptrdiff_t = ffi.Long;
|
||||
|
||||
class GoInterface extends ffi.Struct {
|
||||
external ffi.Pointer<ffi.Void> t;
|
||||
|
||||
external ffi.Pointer<ffi.Void> v;
|
||||
}
|
||||
|
||||
class GoSlice extends ffi.Struct {
|
||||
external ffi.Pointer<ffi.Void> data;
|
||||
|
||||
@GoInt()
|
||||
external int len;
|
||||
|
||||
@GoInt()
|
||||
external int cap;
|
||||
}
|
||||
|
||||
typedef GoInt = GoInt64;
|
||||
typedef GoInt64 = ffi.LongLong;
|
||||
|
||||
class Start_return extends ffi.Struct {
|
||||
@GoInt()
|
||||
external int r0;
|
||||
|
||||
external ffi.Pointer<ffi.Char> r1;
|
||||
}
|
||||
|
||||
const int __DARWIN_ONLY_64_BIT_INO_T = 1;
|
||||
|
||||
const int __DARWIN_ONLY_UNIX_CONFORMANCE = 1;
|
||||
|
||||
const int __DARWIN_ONLY_VERS_1050 = 1;
|
||||
|
||||
const int __DARWIN_UNIX03 = 1;
|
||||
|
||||
const int __DARWIN_64_BIT_INO_T = 1;
|
||||
|
||||
const int __DARWIN_VERS_1050 = 1;
|
||||
|
||||
const int __DARWIN_NON_CANCELABLE = 0;
|
||||
|
||||
const String __DARWIN_SUF_EXTSN = '\$DARWIN_EXTSN';
|
||||
|
||||
const int __DARWIN_C_ANSI = 4096;
|
||||
|
||||
const int __DARWIN_C_FULL = 900000;
|
||||
|
||||
const int __DARWIN_C_LEVEL = 900000;
|
||||
|
||||
const int __STDC_WANT_LIB_EXT1__ = 1;
|
||||
|
||||
const int __DARWIN_NO_LONG_LONG = 0;
|
||||
|
||||
const int _DARWIN_FEATURE_64_BIT_INODE = 1;
|
||||
|
||||
const int _DARWIN_FEATURE_ONLY_64_BIT_INODE = 1;
|
||||
|
||||
const int _DARWIN_FEATURE_ONLY_VERS_1050 = 1;
|
||||
|
||||
const int _DARWIN_FEATURE_ONLY_UNIX_CONFORMANCE = 1;
|
||||
|
||||
const int _DARWIN_FEATURE_UNIX_CONFORMANCE = 3;
|
||||
|
||||
const int __has_ptrcheck = 0;
|
||||
|
||||
const int __DARWIN_NULL = 0;
|
||||
|
||||
const int __PTHREAD_SIZE__ = 8176;
|
||||
|
||||
const int __PTHREAD_ATTR_SIZE__ = 56;
|
||||
|
||||
const int __PTHREAD_MUTEXATTR_SIZE__ = 8;
|
||||
|
||||
const int __PTHREAD_MUTEX_SIZE__ = 56;
|
||||
|
||||
const int __PTHREAD_CONDATTR_SIZE__ = 8;
|
||||
|
||||
const int __PTHREAD_COND_SIZE__ = 40;
|
||||
|
||||
const int __PTHREAD_ONCE_SIZE__ = 8;
|
||||
|
||||
const int __PTHREAD_RWLOCK_SIZE__ = 192;
|
||||
|
||||
const int __PTHREAD_RWLOCKATTR_SIZE__ = 16;
|
||||
|
||||
const int __DARWIN_WCHAR_MAX = 2147483647;
|
||||
|
||||
const int __DARWIN_WCHAR_MIN = -2147483648;
|
||||
|
||||
const int __DARWIN_WEOF = -1;
|
||||
|
||||
const int _FORTIFY_SOURCE = 2;
|
||||
|
||||
const int NULL = 0;
|
||||
|
||||
const int USER_ADDR_NULL = 0;
|
||||
@@ -0,0 +1,171 @@
|
||||
import 'dart:async';
|
||||
import 'dart:ffi';
|
||||
import 'dart:io';
|
||||
import 'dart:isolate';
|
||||
|
||||
import 'package:gopeed/core/common/libgopeed_channel.dart';
|
||||
import 'package:gopeed/core/common/libgopeed_ffi.dart';
|
||||
import 'package:gopeed/core/common/start_config.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import '../util/util.dart';
|
||||
import 'common/libgopeed_interface.dart';
|
||||
import 'ffi/libgopeed_bind.dart';
|
||||
|
||||
const unixSocketPath = 'gopeed.sock';
|
||||
|
||||
class LibgopeedBoot {
|
||||
String network = "";
|
||||
String address = "";
|
||||
int port = 0;
|
||||
int refreshInterval = 250;
|
||||
|
||||
late LibgopeedInterface _libgopeed;
|
||||
late SendPort _childSendPort;
|
||||
|
||||
static LibgopeedBoot? _instance;
|
||||
|
||||
static LibgopeedBoot get instance {
|
||||
if (_instance == null) {
|
||||
_instance = LibgopeedBoot._internal();
|
||||
if (!Util.isDesktop()) {
|
||||
_instance!._libgopeed = LibgopeedChannel();
|
||||
}
|
||||
}
|
||||
return _instance!;
|
||||
}
|
||||
|
||||
LibgopeedBoot._internal();
|
||||
|
||||
Future<void> start() async {
|
||||
var storageDir = "./";
|
||||
if (!Util.isUnix()) {
|
||||
// not support unix socket, use tcp
|
||||
network = "tcp";
|
||||
address = "127.0.0.1:0";
|
||||
} else {
|
||||
network = "unix";
|
||||
if (Util.isDesktop()) {
|
||||
address = unixSocketPath;
|
||||
} else if (Platform.isAndroid) {
|
||||
address = "${(await getTemporaryDirectory()).path}/$unixSocketPath";
|
||||
storageDir = (await getExternalStorageDirectory())?.path ?? "";
|
||||
}
|
||||
}
|
||||
final cfg = StartConfig(
|
||||
network: network,
|
||||
address: address,
|
||||
storage: 'bolt',
|
||||
storageDir: storageDir,
|
||||
refreshInterval: refreshInterval);
|
||||
if (Util.isDesktop()) {
|
||||
port = await _ffiStart(cfg);
|
||||
} else {
|
||||
port = await _libgopeed.start(cfg);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> stop() async {
|
||||
if (Util.isDesktop()) {
|
||||
await _ffiStop();
|
||||
} else {
|
||||
await _libgopeed.stop();
|
||||
}
|
||||
}
|
||||
|
||||
_ffiInit() {
|
||||
if (Platform.isMacOS) {
|
||||
_libgopeed =
|
||||
LibgopeedFFi(LibgopeedBind(DynamicLibrary.open('libgopeed.dylib')));
|
||||
}
|
||||
}
|
||||
|
||||
// FFI run in isolate
|
||||
Future<int> _ffiStart(StartConfig cfg) async {
|
||||
var startCompleter = Completer<int>();
|
||||
|
||||
var mainReceive = ReceivePort();
|
||||
var isolate = await Isolate.spawn((SendPort sendPort) {
|
||||
_ffiInit();
|
||||
var childReceive = ReceivePort();
|
||||
sendPort.send(childReceive.sendPort);
|
||||
|
||||
childReceive.listen((message) async {
|
||||
late _Result result;
|
||||
try {
|
||||
if (message is _StartParam) {
|
||||
result = _StartResult();
|
||||
(result as _StartResult).port = await _libgopeed.start(message.cfg);
|
||||
}
|
||||
if (message is _StopParam) {
|
||||
result = _StopResult();
|
||||
await _libgopeed.stop();
|
||||
childReceive.close();
|
||||
Isolate.exit(sendPort);
|
||||
}
|
||||
} on Exception catch (e) {
|
||||
result.exception = e;
|
||||
}
|
||||
sendPort.send(result);
|
||||
});
|
||||
}, mainReceive.sendPort);
|
||||
|
||||
var childCompleter = Completer<void>();
|
||||
mainReceive.listen((message) {
|
||||
if (message is SendPort) {
|
||||
_childSendPort = message;
|
||||
childCompleter.complete();
|
||||
}
|
||||
if (message is _StartResult) {
|
||||
if (message.exception != null) {
|
||||
startCompleter.completeError(message.exception!);
|
||||
} else {
|
||||
startCompleter.complete(message.port!);
|
||||
}
|
||||
}
|
||||
if (message is _StopResult) {
|
||||
isolate.kill();
|
||||
if (message.exception != null) {
|
||||
_stopCompleter.completeError(message.exception!);
|
||||
} else {
|
||||
_stopCompleter.complete();
|
||||
}
|
||||
}
|
||||
});
|
||||
await childCompleter.future;
|
||||
_childSendPort.send(_StartParam(cfg: cfg));
|
||||
return startCompleter.future;
|
||||
}
|
||||
|
||||
late Completer<void> _stopCompleter;
|
||||
|
||||
Future<void> _ffiStop() async {
|
||||
_stopCompleter = Completer<void>();
|
||||
_childSendPort.send(_StopParam());
|
||||
return _stopCompleter.future;
|
||||
}
|
||||
}
|
||||
|
||||
class _Result {
|
||||
Exception? exception;
|
||||
|
||||
_Result();
|
||||
}
|
||||
|
||||
class _StartParam {
|
||||
final StartConfig cfg;
|
||||
|
||||
_StartParam({required this.cfg});
|
||||
}
|
||||
|
||||
class _StartResult extends _Result {
|
||||
int? port;
|
||||
|
||||
_StartResult();
|
||||
}
|
||||
|
||||
class _StopParam {}
|
||||
|
||||
class _StopResult extends _Result {
|
||||
_StopResult();
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import 'core/libgopeed_boot.dart';
|
||||
import 'routes/router.dart';
|
||||
import 'setting/setting.dart';
|
||||
import 'theme/theme.dart';
|
||||
import 'util/mac_secure_util.dart';
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
await LibgopeedBoot.instance.start();
|
||||
await Setting.instance.load();
|
||||
MacSecureUtil.loadBookmark();
|
||||
|
||||
runApp(GetMaterialApp.router(
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: GopeedTheme.light,
|
||||
darkTheme: GopeedTheme.dark,
|
||||
themeMode: Setting.instance.themeMode,
|
||||
getPages: Routes.routes,
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
class CreateController extends GetxController {
|
||||
var currentIndex = 0.obs;
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import 'dart:developer' as developer;
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:gopeed/api/api.dart';
|
||||
import 'package:gopeed/api/model/create_task.dart';
|
||||
import 'package:gopeed/api/model/options.dart';
|
||||
import 'package:gopeed/api/model/request.dart';
|
||||
import 'package:gopeed/api/model/resource.dart';
|
||||
import 'package:gopeed/pages/create/create_controller.dart';
|
||||
import 'package:gopeed/setting/setting.dart';
|
||||
import 'package:gopeed/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 '../../widget/directory_selector.dart';
|
||||
|
||||
class CreateView extends GetView<CreateController> {
|
||||
CreateView({Key? key}) : super(key: key);
|
||||
|
||||
final _resolveFormKey = GlobalKey<FormState>();
|
||||
final _urlController = TextEditingController(
|
||||
text: "https://dldir1.qq.com/weixin/Windows/WeChatSetup.exe");
|
||||
final _confirmController = RoundedLoadingButtonController();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
onPressed: () => Get.rootDelegate.offNamed(Routes.task)),
|
||||
actions: [Container()],
|
||||
title: const Text("创建任务"),
|
||||
),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24.0),
|
||||
child: Form(
|
||||
key: _resolveFormKey,
|
||||
autovalidateMode: AutovalidateMode.always, //开启自动校验
|
||||
child: Column(
|
||||
children: [
|
||||
TextFormField(
|
||||
autofocus: true,
|
||||
controller: _urlController,
|
||||
minLines: 1,
|
||||
maxLines: 15,
|
||||
decoration: const InputDecoration(
|
||||
hintText: "请输入下载链接,支持 HTTP/HTTPS/MAGNET",
|
||||
labelText: "下载链接",
|
||||
icon: Icon(Icons.link)),
|
||||
validator: (v) {
|
||||
return v!.trim().isNotEmpty ? null : "请输入下载链接";
|
||||
}),
|
||||
// 登录按钮
|
||||
Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(15.0),
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints.tightFor(
|
||||
width: 150,
|
||||
height: 40,
|
||||
),
|
||||
child: RoundedLoadingButton(
|
||||
color: Get.theme.colorScheme.secondary,
|
||||
onPressed: () async {
|
||||
if (_resolveFormKey.currentState!.validate()) {
|
||||
_confirmController.start();
|
||||
try {
|
||||
final res = await resolve(Request(
|
||||
url: _urlController.text,
|
||||
));
|
||||
await _showResolveDialog(res);
|
||||
} catch (e) {
|
||||
Get.snackbar("错误", e.toString());
|
||||
} finally {
|
||||
_confirmController.reset();
|
||||
}
|
||||
}
|
||||
},
|
||||
controller: _confirmController,
|
||||
child: const Text("确认"),
|
||||
),
|
||||
)),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _showResolveDialog(Resource res) async {
|
||||
final createFormKey = GlobalKey<FormState>();
|
||||
final pathController =
|
||||
TextEditingController(text: Setting.instance.downloadDir);
|
||||
final downloadController = RoundedLoadingButtonController();
|
||||
var fileValues = List.filled(res.files.length, true);
|
||||
|
||||
return await showDialog<void>(
|
||||
context: Get.context!,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => AlertDialog(
|
||||
content: Builder(
|
||||
builder: (context) {
|
||||
// Get available height and width of the build area of this widget. Make a choice depending on the size.
|
||||
var height = MediaQuery.of(context).size.height;
|
||||
var width = MediaQuery.of(context).size.width;
|
||||
|
||||
return SizedBox(
|
||||
height: height * 0.5,
|
||||
width: width,
|
||||
child: Form(
|
||||
key: createFormKey,
|
||||
autovalidateMode: AutovalidateMode.always, //开启自动校验
|
||||
child: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: FileListView(
|
||||
files: res.files,
|
||||
values: fileValues,
|
||||
)),
|
||||
DirectorySelector(
|
||||
controller: pathController,
|
||||
),
|
||||
],
|
||||
)),
|
||||
);
|
||||
},
|
||||
),
|
||||
actions: [
|
||||
ConstrainedBox(
|
||||
constraints: BoxConstraints.tightFor(
|
||||
width: Get.theme.buttonTheme.minWidth,
|
||||
height: Get.theme.buttonTheme.height,
|
||||
),
|
||||
child: ElevatedButton(
|
||||
style:
|
||||
ElevatedButton.styleFrom(shape: const StadiumBorder())
|
||||
.copyWith(
|
||||
backgroundColor: MaterialStateProperty.all(
|
||||
Get.theme.backgroundColor)),
|
||||
onPressed: () {
|
||||
Get.back();
|
||||
},
|
||||
child: const Text("取消"),
|
||||
),
|
||||
),
|
||||
ConstrainedBox(
|
||||
constraints: BoxConstraints.tightFor(
|
||||
width: Get.theme.buttonTheme.minWidth,
|
||||
height: Get.theme.buttonTheme.height,
|
||||
),
|
||||
child: RoundedLoadingButton(
|
||||
color: Get.theme.colorScheme.secondary,
|
||||
onPressed: () async {
|
||||
try {
|
||||
if (createFormKey.currentState!.validate()) {
|
||||
downloadController.start();
|
||||
if (Platform.isAndroid) {
|
||||
if (!await Permission.storage.request().isGranted) {
|
||||
Get.snackbar("错误", "需要开启存储权限");
|
||||
return;
|
||||
}
|
||||
}
|
||||
await createTask(CreateTask(
|
||||
res: res,
|
||||
opts: Options(
|
||||
name: '',
|
||||
path: pathController.text,
|
||||
connections: Setting.instance.connections,
|
||||
selectFiles: fileValues
|
||||
.asMap()
|
||||
.entries
|
||||
.where((e) => e.value)
|
||||
.map((e) => e.key)
|
||||
.toList(),
|
||||
)));
|
||||
Get.back();
|
||||
Get.rootDelegate.offNamed(Routes.task);
|
||||
}
|
||||
} catch (e) {
|
||||
Get.snackbar("错误", e.toString());
|
||||
developer.log(e.toString(), name: 'flutter');
|
||||
} finally {
|
||||
downloadController.reset();
|
||||
}
|
||||
},
|
||||
controller: downloadController,
|
||||
child: const Text("下载"),
|
||||
),
|
||||
),
|
||||
],
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
class HomeController extends GetxController {
|
||||
var currentIndex = 0.obs;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:stylish_bottom_bar/stylish_bottom_bar.dart';
|
||||
|
||||
import '../../routes/router.dart';
|
||||
import 'home_controller.dart';
|
||||
|
||||
class HomeView extends GetView<HomeController> {
|
||||
const HomeView({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GetRouterOutlet.builder(
|
||||
builder: (context, delegate, currentRoute) {
|
||||
//This router outlet handles the appbar and the bottom navigation bar
|
||||
final currentLocation = currentRoute?.location;
|
||||
var currentIndex = 0;
|
||||
if (currentLocation?.startsWith(Routes.setting) == true) {
|
||||
currentIndex = 1;
|
||||
}
|
||||
return Scaffold(
|
||||
extendBody: true, //to make floating action button notch transparent
|
||||
|
||||
//to avoid the floating action button overlapping behavior,
|
||||
// when a soft keyboard is displayed
|
||||
// resizeToAvoidBottomInset: false,
|
||||
body: GetRouterOutlet(
|
||||
initialRoute: Routes.task,
|
||||
|
||||
//delegate: Get.nestedKey(Routes.HOME),
|
||||
// key: Get.nestedKey(Routes.HOME),
|
||||
// key: Get.nestedKey(Routes.home),
|
||||
),
|
||||
|
||||
bottomNavigationBar: StylishBottomBar(
|
||||
items: [
|
||||
AnimatedBarItems(
|
||||
icon: const Icon(Icons.list),
|
||||
selectedColor: Get.theme.primaryColor,
|
||||
title: const Text('任务')),
|
||||
AnimatedBarItems(
|
||||
icon: const Icon(Icons.settings),
|
||||
selectedColor: Get.theme.primaryColor,
|
||||
title: const Text('设置')),
|
||||
],
|
||||
iconSize: 32,
|
||||
barAnimation: BarAnimation.fade,
|
||||
iconStyle: IconStyle.Default,
|
||||
hasNotch: true,
|
||||
opacity: 0.3,
|
||||
currentIndex: currentIndex,
|
||||
onTap: (index) {
|
||||
switch (index) {
|
||||
case 0:
|
||||
delegate.toNamed(Routes.task);
|
||||
break;
|
||||
case 1:
|
||||
delegate.toNamed(Routes.setting);
|
||||
break;
|
||||
}
|
||||
},
|
||||
),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
onPressed: () {
|
||||
/* Get.isDarkMode
|
||||
? {
|
||||
Get.changeTheme(GopeedTheme.light),
|
||||
Get.changeThemeMode(ThemeMode.light)
|
||||
}
|
||||
: {
|
||||
Get.changeTheme(GopeedTheme.dark),
|
||||
Get.changeThemeMode(ThemeMode.dark)
|
||||
}; */
|
||||
Get.rootDelegate.toNamed(Routes.create);
|
||||
},
|
||||
child: const Icon(
|
||||
Icons.add,
|
||||
)),
|
||||
floatingActionButtonLocation:
|
||||
FloatingActionButtonLocation.centerDocked,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import 'package:get/get.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++;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../../routes/router.dart';
|
||||
import 'root_controller.dart';
|
||||
|
||||
class RootView extends GetView<RootController> {
|
||||
const RootView({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GetRouterOutlet.builder(
|
||||
builder: (context, delegate, current) {
|
||||
return Scaffold(
|
||||
body: GetRouterOutlet(
|
||||
initialRoute: Routes.home,
|
||||
// anchorRoute: '/',
|
||||
// filterPages: (afterAnchor) {
|
||||
// return afterAnchor.take(1);
|
||||
// },
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:gopeed/api/api.dart';
|
||||
import 'package:gopeed/api/model/server_config.dart';
|
||||
|
||||
import '../../setting/setting.dart';
|
||||
|
||||
class SettingController extends GetxController {
|
||||
final setting = Setting.instance.obs;
|
||||
final tapStatues = <int, bool>{}.obs;
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:gopeed/setting/setting.dart';
|
||||
import 'package:gopeed/widget/directory_selector.dart';
|
||||
|
||||
import 'setting_controller.dart';
|
||||
|
||||
class SettingView extends GetView<SettingController> {
|
||||
const SettingView({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
Timer? timer;
|
||||
debounceSave() {
|
||||
timer?.cancel();
|
||||
timer = Timer(const Duration(milliseconds: 500), Setting.instance.save);
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('设置'),
|
||||
centerTitle: true,
|
||||
),
|
||||
body: Column(
|
||||
// 左对齐
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text("基本设置", style: Get.textTheme.titleLarge),
|
||||
const SizedBox(height: 10),
|
||||
Obx(() => Card(
|
||||
child: Column(
|
||||
children: _buildConfigItems([
|
||||
_ConfigItem(
|
||||
"主题",
|
||||
() => _getThemeName(controller.setting.value.themeMode),
|
||||
() => DropdownButton<ThemeMode>(
|
||||
value: controller.setting.value.themeMode,
|
||||
isDense: true,
|
||||
onChanged: (value) {
|
||||
controller.setting.value.themeMode = value!;
|
||||
Get.changeThemeMode(value);
|
||||
|
||||
debounceSave();
|
||||
},
|
||||
items: ThemeMode.values
|
||||
.map((e) => DropdownMenuItem<ThemeMode>(
|
||||
value: e,
|
||||
child: Text(_getThemeName(e)),
|
||||
))
|
||||
.toList(),
|
||||
)),
|
||||
_ConfigItem(
|
||||
"下载目录", () => controller.setting.value.downloadDir, () {
|
||||
final downloadDirController = TextEditingController(
|
||||
text: controller.setting.value.downloadDir);
|
||||
downloadDirController.addListener(() {
|
||||
if (downloadDirController.text !=
|
||||
controller.setting.value.downloadDir) {
|
||||
controller.setting.value.downloadDir =
|
||||
downloadDirController.text;
|
||||
|
||||
debounceSave();
|
||||
}
|
||||
});
|
||||
return DirectorySelector(
|
||||
controller: downloadDirController,
|
||||
showLabel: false,
|
||||
);
|
||||
}),
|
||||
_ConfigItem("连接数",
|
||||
() => controller.setting.value.connections.toString(),
|
||||
() {
|
||||
final connectionsController = TextEditingController(
|
||||
text: controller.setting.value.connections.toString());
|
||||
connectionsController.addListener(() {
|
||||
if (connectionsController.text.isNotEmpty &&
|
||||
connectionsController.text !=
|
||||
controller.setting.value.connections.toString()) {
|
||||
controller.setting.value.connections =
|
||||
int.parse(connectionsController.text);
|
||||
|
||||
debounceSave();
|
||||
}
|
||||
});
|
||||
|
||||
return TextField(
|
||||
controller: connectionsController,
|
||||
keyboardType: TextInputType.number,
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.digitsOnly,
|
||||
NumericalRangeFormatter(min: 1, max: 256),
|
||||
],
|
||||
);
|
||||
}),
|
||||
]),
|
||||
))),
|
||||
],
|
||||
).paddingAll(16),
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> _buildConfigItems(List<_ConfigItem> buildItems) {
|
||||
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());
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
String _getThemeName(ThemeMode themeMode) {
|
||||
switch (themeMode) {
|
||||
case ThemeMode.system:
|
||||
return "跟随系统";
|
||||
case ThemeMode.light:
|
||||
return "明亮主题";
|
||||
case ThemeMode.dark:
|
||||
return "暗黑主题";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _ConfigItem {
|
||||
late String label;
|
||||
late String Function() text;
|
||||
late Widget Function() inputItem;
|
||||
|
||||
_ConfigItem(this.label, this.text, this.inputItem);
|
||||
}
|
||||
|
||||
class NumericalRangeFormatter extends TextInputFormatter {
|
||||
final int min;
|
||||
final int max;
|
||||
|
||||
NumericalRangeFormatter({required this.min, required this.max});
|
||||
|
||||
@override
|
||||
TextEditingValue formatEditUpdate(
|
||||
TextEditingValue oldValue,
|
||||
TextEditingValue newValue,
|
||||
) {
|
||||
if (newValue.text.isEmpty) {
|
||||
return newValue;
|
||||
}
|
||||
var intVal = int.tryParse(newValue.text);
|
||||
if (intVal == null) {
|
||||
return oldValue;
|
||||
}
|
||||
if (intVal < min) {
|
||||
return newValue.copyWith(text: min.toString());
|
||||
} else if (intVal > max) {
|
||||
return oldValue.copyWith(text: max.toString());
|
||||
} else {
|
||||
return newValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:get/get.dart';
|
||||
import 'package:gopeed/api/model/task.dart';
|
||||
import 'package:gopeed/core/libgopeed_boot.dart';
|
||||
|
||||
import '../../api/api.dart';
|
||||
|
||||
class TaskController extends GetxController {
|
||||
final tabIndex = 0.obs;
|
||||
final unDoneTasks = <Task>[].obs;
|
||||
final doneTasks = <Task>[].obs;
|
||||
|
||||
var _lastUnDoneSize = 0;
|
||||
var _lastDoneSize = 0;
|
||||
|
||||
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()) {
|
||||
await _loadDone();
|
||||
}
|
||||
} else {
|
||||
if (await _loadDone()) {
|
||||
await _loadUnDone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onInit() {
|
||||
super.onInit();
|
||||
|
||||
loadTab();
|
||||
_timer = Timer.periodic(
|
||||
Duration(milliseconds: LibgopeedBoot.instance.refreshInterval),
|
||||
(timer) async {
|
||||
loadTab();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void onClose() {
|
||||
super.onClose();
|
||||
|
||||
_timer.cancel();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:gopeed/api/api.dart';
|
||||
import 'package:gopeed/api/model/task.dart';
|
||||
import 'package:styled_widget/styled_widget.dart';
|
||||
import 'package:url_launcher/url_launcher.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;
|
||||
|
||||
const Item({Key? key, required this.task}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
var controller = Get.find<TaskController>();
|
||||
|
||||
return Card(
|
||||
elevation: 4.0,
|
||||
child: InkWell(
|
||||
onTap: () {},
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
ListTile(
|
||||
title: Text(task.res.name),
|
||||
leading: const Icon(Icons.insert_drive_file),
|
||||
),
|
||||
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)),
|
||||
Expanded(
|
||||
flex: 1,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
Text("${Util.fmtByte(task.progress.speed)} / s",
|
||||
style: Get.textTheme.subtitle2),
|
||||
...buildActions()
|
||||
],
|
||||
)),
|
||||
],
|
||||
),
|
||||
LinearProgressIndicator(
|
||||
value: getProgress(),
|
||||
),
|
||||
],
|
||||
),
|
||||
)).padding(horizontal: 8, top: 8);
|
||||
}
|
||||
|
||||
List<Widget> buildActions() {
|
||||
final list = <Widget>[];
|
||||
if (isDone()) {
|
||||
if (Util.isDesktop()) {
|
||||
list.add(IconButton(
|
||||
icon: const Icon(Icons.folder_open),
|
||||
onPressed: () async {
|
||||
print(Util.buildAbsPath(task.opts.path, task.res.files[0].path,
|
||||
task.res.files[0].name));
|
||||
final file = File(Util.buildAbsPath(task.opts.path,
|
||||
task.res.files[0].path, task.res.files[0].name));
|
||||
await launchUrl(file.parent.uri);
|
||||
},
|
||||
));
|
||||
}
|
||||
} else {
|
||||
if (isRunning()) {
|
||||
list.add(IconButton(
|
||||
icon: const Icon(Icons.pause),
|
||||
onPressed: () async {
|
||||
await pauseTask(task.id);
|
||||
},
|
||||
));
|
||||
} else {
|
||||
list.add(IconButton(
|
||||
icon: const Icon(Icons.play_arrow),
|
||||
onPressed: () async {
|
||||
await continueTask(task.id);
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
list.add(IconButton(
|
||||
icon: const Icon(Icons.delete),
|
||||
onPressed: () {
|
||||
_showDeleteDialog(task.id);
|
||||
},
|
||||
));
|
||||
return list;
|
||||
}
|
||||
|
||||
Future<void> _showDeleteDialog(String id) {
|
||||
final keep = true.obs;
|
||||
|
||||
return showDialog<void>(
|
||||
context: Get.context!,
|
||||
barrierDismissible: false,
|
||||
builder: (_) => AlertDialog(
|
||||
title: const Text("删除任务"),
|
||||
content: Obx(() => CheckboxListTile(
|
||||
value: keep.value,
|
||||
title: Text("保留已下载的文件", style: Get.textTheme.bodyText1),
|
||||
onChanged: (v) {
|
||||
keep.value = v!;
|
||||
})),
|
||||
actions: [
|
||||
TextButton(
|
||||
child: const Text("取消"),
|
||||
onPressed: () => Get.back(), //关闭对话框
|
||||
),
|
||||
TextButton(
|
||||
child: const Text(
|
||||
"删除",
|
||||
style: TextStyle(color: Colors.redAccent),
|
||||
),
|
||||
onPressed: () async {
|
||||
try {
|
||||
await deleteTask(id, !keep.value);
|
||||
Get.find<TaskController>().loadTab();
|
||||
Get.back();
|
||||
} catch (e) {
|
||||
Get.snackbar("错误", e.toString());
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
));
|
||||
}
|
||||
|
||||
double getProgress() {
|
||||
return task.size <= 0 ? 1 : task.progress.downloaded / task.size;
|
||||
}
|
||||
|
||||
bool isRunning() {
|
||||
return task.status == Status.running;
|
||||
}
|
||||
|
||||
bool isDone() {
|
||||
return task.status == Status.done;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import 'package:get/get.dart';
|
||||
import 'package:gopeed/pages/create/create_controller.dart';
|
||||
import 'package:gopeed/pages/setting/setting_view.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/task/task_controller.dart';
|
||||
import '../pages/task/task_view.dart';
|
||||
|
||||
abstract class _Paths {
|
||||
static const root = '/';
|
||||
|
||||
static const create = '/create';
|
||||
|
||||
static const home = '/home';
|
||||
static const task = '/task';
|
||||
static const setting = '/setting';
|
||||
}
|
||||
|
||||
class Routes {
|
||||
static const root = _Paths.root;
|
||||
|
||||
static const create = _Paths.create;
|
||||
|
||||
static const home = _Paths.home;
|
||||
static const task = _Paths.home + _Paths.task;
|
||||
static const setting = _Paths.home + _Paths.setting;
|
||||
|
||||
static final routes = [
|
||||
GetPage(
|
||||
name: _Paths.root,
|
||||
participatesInRootNavigator: true,
|
||||
// preventDuplicates: true,
|
||||
page: () => const RootView(),
|
||||
binding: BindingsBuilder(() {
|
||||
Get.lazyPut<RootController>(() => RootController(), fenix: true);
|
||||
}),
|
||||
children: [
|
||||
GetPage(
|
||||
name: _Paths.create,
|
||||
transition: Transition.downToUp,
|
||||
// preventDuplicates: true,
|
||||
page: () => CreateView(),
|
||||
binding: BindingsBuilder(() {
|
||||
Get.lazyPut<CreateController>(() => CreateController(),
|
||||
fenix: true);
|
||||
}),
|
||||
),
|
||||
GetPage(
|
||||
name: _Paths.home,
|
||||
// preventDuplicates: true,
|
||||
page: () => const HomeView(),
|
||||
binding: BindingsBuilder(() {
|
||||
Get.lazyPut<HomeController>(() => HomeController(),
|
||||
fenix: true);
|
||||
}),
|
||||
children: [
|
||||
GetPage(
|
||||
name: _Paths.task,
|
||||
page: () => const TaskView(),
|
||||
binding: BindingsBuilder(() {
|
||||
Get.lazyPut<TaskController>(() => TaskController());
|
||||
}),
|
||||
),
|
||||
GetPage(
|
||||
name: _Paths.setting,
|
||||
page: () => const SettingView(),
|
||||
binding: BindingsBuilder(() {
|
||||
Get.lazyPut<SettingController>(() => SettingController());
|
||||
}),
|
||||
)
|
||||
]),
|
||||
]),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:external_path/external_path.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
import 'package:gopeed/api/api.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import '../api/model/server_config.dart';
|
||||
import '../util/util.dart';
|
||||
|
||||
class Setting {
|
||||
late String host;
|
||||
late int port;
|
||||
late int connections;
|
||||
late String downloadDir;
|
||||
late ThemeMode themeMode;
|
||||
|
||||
Setting({
|
||||
required this.host,
|
||||
required this.port,
|
||||
required this.connections,
|
||||
required this.downloadDir,
|
||||
required this.themeMode,
|
||||
});
|
||||
|
||||
// singleton pattern
|
||||
static Setting? _instance;
|
||||
|
||||
static Setting get instance {
|
||||
_instance ??= Setting._internal();
|
||||
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.system;
|
||||
} else {
|
||||
this.themeMode = ThemeMode.values.byName(themeMode);
|
||||
}
|
||||
|
||||
if (Platform.isAndroid) {
|
||||
downloadDir =
|
||||
'${await ExternalPath.getExternalStoragePublicDirectory(ExternalPath.DIRECTORY_DOWNLOADS)}/com.gopeed';
|
||||
return;
|
||||
}
|
||||
|
||||
if (downloadDir.isEmpty) {
|
||||
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,
|
||||
},
|
||||
);
|
||||
await putConfig(config);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class GopeedTheme {
|
||||
static const _gopeedreenPrimaryValue = 0xFF79C476;
|
||||
static const _gopeedreen =
|
||||
MaterialColor(_gopeedreenPrimaryValue, <int, Color>{
|
||||
50: Color(0xFFEFF8EF),
|
||||
100: Color(0xFFD7EDD6),
|
||||
200: Color(0xFFBCE2BB),
|
||||
300: Color(0xFFA1D69F),
|
||||
400: Color(0xFF8DCD8B),
|
||||
500: Color(_gopeedreenPrimaryValue),
|
||||
600: Color(0xFF71BE6E),
|
||||
700: Color(0xFF66B663),
|
||||
800: Color(0xFF5CAF59),
|
||||
900: Color(0xFF49A246),
|
||||
});
|
||||
|
||||
static const _gopeedreenAccentValue = 0xFFC9FFC7;
|
||||
static const _gopeedreenAccent =
|
||||
MaterialColor(_gopeedreenAccentValue, <int, Color>{
|
||||
100: Color(0xFFFAFFFA),
|
||||
200: Color(_gopeedreenAccentValue),
|
||||
400: Color(0xFF97FF94),
|
||||
700: Color(0xFF7FFF7A),
|
||||
});
|
||||
|
||||
static final _light =
|
||||
ThemeData(brightness: Brightness.light, primarySwatch: _gopeedreen);
|
||||
static final light = _light.copyWith(
|
||||
colorScheme: _light.colorScheme.copyWith(secondary: _gopeedreenAccent));
|
||||
|
||||
static final _dark =
|
||||
ThemeData(brightness: Brightness.dark, primarySwatch: _gopeedreen);
|
||||
static final dark = _dark.copyWith(
|
||||
colorScheme: _dark.colorScheme.copyWith(secondary: _gopeedreenAccent));
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:macos_secure_bookmarks/macos_secure_bookmarks.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class MacSecureUtil {
|
||||
static const _bookmarkKey = "bookmark:";
|
||||
|
||||
static Future<void> saveBookmark(String dir) async {
|
||||
if (!Platform.isMacOS) {
|
||||
return;
|
||||
}
|
||||
final secureBookmarks = SecureBookmarks();
|
||||
final bookmark = await secureBookmarks.bookmark(Directory(dir));
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_bookmarkKey + dir, bookmark);
|
||||
}
|
||||
|
||||
static Future<void> loadBookmark() async {
|
||||
if (!Platform.isMacOS) {
|
||||
return;
|
||||
}
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final keys = prefs.getKeys();
|
||||
final secureBookmarks = SecureBookmarks();
|
||||
keys.where((k) => k.startsWith(_bookmarkKey)).forEach((k) async {
|
||||
final resolvedFile = await secureBookmarks
|
||||
.resolveBookmark(prefs.getString(k)!, isDirectory: true);
|
||||
await secureBookmarks.startAccessingSecurityScopedResource(resolvedFile);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import 'dart:io';
|
||||
|
||||
class Util {
|
||||
static String fmtByte(int byte) {
|
||||
if (byte < 1024) {
|
||||
return "$byte B";
|
||||
} else if (byte < 1024 * 1024) {
|
||||
return "${(byte / 1024).toStringAsFixed(2)} KB";
|
||||
} else if (byte < 1024 * 1024 * 1024) {
|
||||
return "${(byte / 1024 / 1024).toStringAsFixed(2)} MB";
|
||||
} else {
|
||||
return "${(byte / 1024 / 1024 / 1024).toStringAsFixed(2)} GB";
|
||||
}
|
||||
}
|
||||
|
||||
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 isDesktop() {
|
||||
return Platform.isWindows || Platform.isLinux || Platform.isMacOS;
|
||||
}
|
||||
|
||||
static isUnix() {
|
||||
return !Platform.isWindows;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import 'package:file_selector/file_selector.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../util/mac_secure_util.dart';
|
||||
|
||||
class DirectorySelector extends StatefulWidget {
|
||||
final TextEditingController controller;
|
||||
final bool showLabel;
|
||||
|
||||
const DirectorySelector(
|
||||
{Key? key, required this.controller, this.showLabel = true})
|
||||
: super(key: key);
|
||||
|
||||
@override
|
||||
State<DirectorySelector> createState() => _DirectorySelectorState();
|
||||
}
|
||||
|
||||
class _DirectorySelectorState extends State<DirectorySelector> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
readOnly: true,
|
||||
controller: widget.controller,
|
||||
decoration: widget.showLabel
|
||||
? const InputDecoration(
|
||||
labelText: "下载目录",
|
||||
)
|
||||
: null,
|
||||
validator: (v) {
|
||||
return v!.trim().isNotEmpty ? null : "请选择下载目录";
|
||||
},
|
||||
)),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.folder_open),
|
||||
onPressed: () async {
|
||||
if (GetPlatform.isDesktop) {
|
||||
var dir = await getDirectoryPath();
|
||||
if (dir != null) {
|
||||
widget.controller.text = dir;
|
||||
MacSecureUtil.saveBookmark(dir);
|
||||
}
|
||||
}
|
||||
})
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gopeed/util/util.dart';
|
||||
|
||||
import '../api/model/resource.dart';
|
||||
|
||||
class FileListView extends StatefulWidget {
|
||||
final List<FileInfo> files;
|
||||
final List<bool> values;
|
||||
|
||||
const FileListView({
|
||||
Key? key,
|
||||
required this.files,
|
||||
required this.values,
|
||||
}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<FileListView> createState() => _FileListViewState();
|
||||
}
|
||||
|
||||
class _FileListViewState extends State<FileListView> {
|
||||
List<FileInfo> get _files => widget.files;
|
||||
|
||||
List<bool> get _values => widget.values;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final themeData = Theme.of(context);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Padding(padding: EdgeInsets.only(top: 10)),
|
||||
Text("选择文件", style: TextStyle(color: themeData.hintColor)),
|
||||
Expanded(
|
||||
child: Container(
|
||||
margin: const EdgeInsets.only(top: 10),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: Colors.grey, width: 1),
|
||||
borderRadius: BorderRadius.circular(5)),
|
||||
child: ListView.builder(
|
||||
itemCount: _files.length,
|
||||
itemBuilder: (context, index) {
|
||||
var file = _files[index];
|
||||
return CheckboxListTile(
|
||||
value: _values[index],
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
_values[index] = value!;
|
||||
});
|
||||
},
|
||||
title: Text(Util.buildPath(file.path, file.name)),
|
||||
subtitle: Text(Util.fmtByte(file.size)),
|
||||
secondary: const Icon(Icons.description),
|
||||
);
|
||||
}))),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user