mirror of
https://github.com/GopeedLab/gopeed.git
synced 2026-11-19 06:43:42 +00:00
feat: new ui (#1455)
This commit is contained in:
742 files changed
+59951
-5934
No files matched your search
+164
-187
@@ -3,11 +3,7 @@ import 'dart:io';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:dio/io.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:get/get.dart' as getx;
|
||||
|
||||
import '../app/routes/app_pages.dart';
|
||||
import '../database/database.dart';
|
||||
import '../util/util.dart';
|
||||
import 'model/create_task.dart';
|
||||
import 'model/create_task_batch.dart';
|
||||
import 'model/downloader_config.dart';
|
||||
@@ -22,286 +18,267 @@ import 'model/task.dart';
|
||||
import 'model/update_check_extension_resp.dart';
|
||||
import 'model/update_extension_settings.dart';
|
||||
|
||||
class ApiTimeoutException implements Exception {
|
||||
const ApiTimeoutException(this.message);
|
||||
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
class _Client {
|
||||
static _Client? _instance;
|
||||
_Client._();
|
||||
|
||||
static final _Client instance = _Client._();
|
||||
|
||||
late Dio dio;
|
||||
bool initialized = false;
|
||||
|
||||
_Client._internal();
|
||||
|
||||
factory _Client(String network, String address, String apiToken) {
|
||||
if (_instance == null) {
|
||||
_instance = _Client._internal();
|
||||
var dio = Dio();
|
||||
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.options.contentType = Headers.jsonContentType;
|
||||
dio.options.sendTimeout = const Duration(seconds: 5);
|
||||
dio.options.connectTimeout = const Duration(seconds: 5);
|
||||
dio.options.receiveTimeout = const Duration(seconds: 120);
|
||||
dio.interceptors.add(InterceptorsWrapper(
|
||||
void init(String network, String address, String apiToken, {VoidCallback? onUnauthorized}) {
|
||||
final isUnixSocket = network == 'unix';
|
||||
final baseUrl = isUnixSocket
|
||||
? 'http://127.0.0.1/'
|
||||
: kIsWeb
|
||||
? kDebugMode
|
||||
? 'http://127.0.0.1:9999/'
|
||||
: ''
|
||||
: 'http://$address/';
|
||||
dio = Dio(
|
||||
BaseOptions(
|
||||
baseUrl: baseUrl,
|
||||
contentType: Headers.jsonContentType,
|
||||
sendTimeout: const Duration(seconds: 5),
|
||||
connectTimeout: const Duration(seconds: 5),
|
||||
receiveTimeout: const Duration(seconds: 120),
|
||||
),
|
||||
);
|
||||
dio.interceptors.add(
|
||||
InterceptorsWrapper(
|
||||
onRequest: (options, handler) {
|
||||
if (apiToken.isNotEmpty) {
|
||||
options.headers['X-Api-Token'] = apiToken;
|
||||
}
|
||||
if (Util.isWeb()) {
|
||||
final token = Database.instance.getWebToken();
|
||||
if (token != null) {
|
||||
options.headers['Authorization'] = 'Bearer $token';
|
||||
}
|
||||
}
|
||||
handler.next(options);
|
||||
},
|
||||
onError: (error, handler) {
|
||||
// Only web version has a login page
|
||||
if (Util.isWeb() && error.response?.statusCode == 401) {
|
||||
getx.Get.rootDelegate.offAndToNamed(Routes.LOGIN);
|
||||
if (kIsWeb && error.response?.statusCode == 401) {
|
||||
onUnauthorized?.call();
|
||||
}
|
||||
handler.next(error);
|
||||
},
|
||||
));
|
||||
|
||||
_instance!.dio = dio;
|
||||
if (isUnixSocket) {
|
||||
(_instance!.dio.httpClientAdapter as IOHttpClientAdapter)
|
||||
.createHttpClient = () {
|
||||
final client = HttpClient();
|
||||
client.connectionFactory =
|
||||
(Uri uri, String? proxyHost, int? proxyPort) {
|
||||
return Socket.startConnect(
|
||||
InternetAddress(address, type: InternetAddressType.unix), 0);
|
||||
};
|
||||
return client;
|
||||
),
|
||||
);
|
||||
if (isUnixSocket) {
|
||||
(dio.httpClientAdapter as IOHttpClientAdapter).createHttpClient = () {
|
||||
final client = HttpClient();
|
||||
client.connectionFactory = (Uri uri, String? proxyHost, int? proxyPort) {
|
||||
return Socket.startConnect(InternetAddress(address, type: InternetAddressType.unix), 0);
|
||||
};
|
||||
}
|
||||
return client;
|
||||
};
|
||||
}
|
||||
return _instance!;
|
||||
initialized = true;
|
||||
}
|
||||
}
|
||||
|
||||
class TimeoutException implements Exception {
|
||||
final String message;
|
||||
|
||||
TimeoutException(this.message);
|
||||
void init(String network, String address, String apiToken, {VoidCallback? onUnauthorized}) {
|
||||
_Client.instance.init(network, address, apiToken, onUnauthorized: onUnauthorized);
|
||||
}
|
||||
|
||||
late _Client _client;
|
||||
|
||||
void init(String network, String address, String apiToken) {
|
||||
_client = _Client(network, address, apiToken);
|
||||
void initDefault({String address = '127.0.0.1:9999', String apiToken = ''}) {
|
||||
if (!_Client.instance.initialized) {
|
||||
init('tcp', address, apiToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// Used by LocationKeepAliveCoordinator to reconcile keep-alive
|
||||
void Function()? _onTaskChanged;
|
||||
|
||||
void setTaskChangedListener(void Function() listener) {
|
||||
_onTaskChanged = listener;
|
||||
}
|
||||
|
||||
void _notifyTaskChanged() {
|
||||
_onTaskChanged?.call();
|
||||
}
|
||||
|
||||
Future<T> _parse<T>(
|
||||
Future<Response> Function() fetch,
|
||||
T Function(dynamic json)? fromJsonT,
|
||||
) async {
|
||||
Future<T> _parse<T>(Future<Response<dynamic>> Function() fetch, T Function(dynamic json)? fromJsonT) async {
|
||||
initDefault();
|
||||
try {
|
||||
var resp = await fetch();
|
||||
final resp = await fetch();
|
||||
fromJsonT ??= (json) => null as T;
|
||||
final result = Result<T>.fromJson(resp.data, fromJsonT);
|
||||
if (result.code == 0) {
|
||||
return result.data as T;
|
||||
} else {
|
||||
throw Exception(result);
|
||||
}
|
||||
final message = result.msg;
|
||||
throw Exception(message == null || message.isEmpty ? 'API error ${result.code}' : message);
|
||||
} on DioException catch (e) {
|
||||
if (e.type == DioExceptionType.sendTimeout ||
|
||||
e.type == DioExceptionType.receiveTimeout ||
|
||||
e.type == DioExceptionType.connectionTimeout ||
|
||||
e.type == DioExceptionType.connectionError) {
|
||||
throw TimeoutException("request timeout");
|
||||
throw const ApiTimeoutException('request timeout');
|
||||
}
|
||||
throw Exception(Result(code: 1000, msg: e.message));
|
||||
throw Exception(e.message ?? 'request failed');
|
||||
}
|
||||
}
|
||||
|
||||
Future<ResolveResult> resolve(ResolveTask resolveTask) async {
|
||||
Future<ResolveResult> resolve(ResolveTask resolveTask) {
|
||||
if (resolveTask.req == null) {
|
||||
throw ArgumentError('resolve request is required');
|
||||
}
|
||||
return _parse<ResolveResult>(
|
||||
() => _client.dio.post("api/v1/resolve", data: resolveTask),
|
||||
(data) => ResolveResult.fromJson(data));
|
||||
() => _Client.instance.dio.post('api/v1/resolve', data: resolveTask),
|
||||
(data) => ResolveResult.fromJson(data as Map<String, dynamic>),
|
||||
);
|
||||
}
|
||||
|
||||
Future<String> createTask(CreateTask createTask) async {
|
||||
final result = await _parse<String>(
|
||||
() => _client.dio.post("api/v1/tasks", data: createTask),
|
||||
(data) => data as String);
|
||||
_notifyTaskChanged();
|
||||
return result;
|
||||
Future<String> createTask(CreateTask createTask) {
|
||||
return _parse<String>(() => _Client.instance.dio.post('api/v1/tasks', data: createTask), (data) => data as String);
|
||||
}
|
||||
|
||||
Future<List<String>> createTaskBatch(CreateTaskBatch createTaskBatch) async {
|
||||
final result = await _parse<List<String>>(
|
||||
() => _client.dio.post("api/v1/tasks/batch", data: createTaskBatch),
|
||||
(data) => (data as List).map((e) => e as String).toList());
|
||||
_notifyTaskChanged();
|
||||
return result;
|
||||
Future<List<String>> createTaskBatch(CreateTaskBatch createTaskBatch) {
|
||||
return _parse<List<String>>(
|
||||
() => _Client.instance.dio.post('api/v1/tasks/batch', data: createTaskBatch),
|
||||
(data) => (data as List<dynamic>).map((e) => e as String).toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> patchTask(String id, ResolveTask patchTask) async {
|
||||
return _parse(
|
||||
() => _client.dio.patch("api/v1/tasks/$id", data: patchTask), null);
|
||||
Future<void> patchTask(String id, ResolveTask patchTask) {
|
||||
return _parse<void>(() => _Client.instance.dio.patch('api/v1/tasks/$id', data: patchTask), null);
|
||||
}
|
||||
|
||||
Future<List<Task>> getTasks(List<Status> statuses) async {
|
||||
Future<List<Task>> getTasks(List<Status> statuses) {
|
||||
final query = statuses.map((e) => 'status=${e.name}').join('&');
|
||||
return _parse<List<Task>>(
|
||||
() => _client.dio.get(
|
||||
"/api/v1/tasks?${statuses.map((e) => "status=${e.name}").join("&")}"),
|
||||
(data) => (data as List).map((e) => Task.fromJson(e)).toList());
|
||||
() => _Client.instance.dio.get('/api/v1/tasks?$query'),
|
||||
(data) => (data as List<dynamic>).map((e) => Task.fromJson(e as Map<String, dynamic>)).toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> pauseTask(String id) async {
|
||||
await _parse(() => _client.dio.put("api/v1/tasks/$id/pause"), null);
|
||||
_notifyTaskChanged();
|
||||
Future<TaskRuntimeStatus> getTaskStatus(String id) {
|
||||
return _parse<TaskRuntimeStatus>(
|
||||
() => _Client.instance.dio.get('/api/v1/tasks/$id/status'),
|
||||
(data) => TaskRuntimeStatus.fromJson(data as Map<String, dynamic>),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> continueTask(String id) async {
|
||||
await _parse(() => _client.dio.put("api/v1/tasks/$id/continue"), null);
|
||||
_notifyTaskChanged();
|
||||
Future<Map<String, dynamic>> getTaskStats(String id) {
|
||||
return _parse<Map<String, dynamic>>(
|
||||
() => _Client.instance.dio.get('/api/v1/tasks/$id/stats'),
|
||||
(data) =>
|
||||
data is Map ? {for (final entry in data.entries) entry.key.toString(): entry.value} : const <String, dynamic>{},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> pauseAllTasks(List<String>? ids) async {
|
||||
await _parse(
|
||||
() => _client.dio.put("api/v1/tasks/pause", queryParameters: {
|
||||
"id": ids,
|
||||
}),
|
||||
null);
|
||||
_notifyTaskChanged();
|
||||
Future<void> pauseTask(String id) {
|
||||
return _parse<void>(() => _Client.instance.dio.put('api/v1/tasks/$id/pause'), null);
|
||||
}
|
||||
|
||||
Future<void> continueAllTasks(List<String>? ids) async {
|
||||
await _parse(
|
||||
() => _client.dio.put("api/v1/tasks/continue", queryParameters: {
|
||||
"id": ids,
|
||||
}),
|
||||
null);
|
||||
_notifyTaskChanged();
|
||||
Future<void> continueTask(String id) {
|
||||
return _parse<void>(() => _Client.instance.dio.put('api/v1/tasks/$id/continue'), null);
|
||||
}
|
||||
|
||||
Future<void> deleteTask(String id, bool force) async {
|
||||
await _parse(
|
||||
() => _client.dio.delete("api/v1/tasks/$id?force=$force"), null);
|
||||
_notifyTaskChanged();
|
||||
Future<void> pauseAllTasks(List<String>? ids) {
|
||||
return _parse<void>(() => _Client.instance.dio.put('api/v1/tasks/pause', queryParameters: {'id': ids}), null);
|
||||
}
|
||||
|
||||
Future<void> deleteTasks(List<String>? ids, bool force) async {
|
||||
await _parse(
|
||||
() => _client.dio.delete("api/v1/tasks", queryParameters: {
|
||||
"id": ids,
|
||||
"force": force,
|
||||
}),
|
||||
null);
|
||||
_notifyTaskChanged();
|
||||
Future<void> continueAllTasks(List<String>? ids) {
|
||||
return _parse<void>(() => _Client.instance.dio.put('api/v1/tasks/continue', queryParameters: {'id': ids}), null);
|
||||
}
|
||||
|
||||
Future<DownloaderConfig> getConfig() async {
|
||||
return _parse(() => _client.dio.get("api/v1/config"),
|
||||
(data) => DownloaderConfig.fromJson(data));
|
||||
Future<void> deleteTask(String id, bool force) {
|
||||
return _parse<void>(() => _Client.instance.dio.delete('api/v1/tasks/$id?force=$force'), null);
|
||||
}
|
||||
|
||||
Future<void> putConfig(DownloaderConfig config) async {
|
||||
return _parse(() => _client.dio.put("api/v1/config", data: config), null);
|
||||
Future<void> deleteTasks(List<String>? ids, bool force) {
|
||||
return _parse<void>(
|
||||
() => _Client.instance.dio.delete('api/v1/tasks', queryParameters: {'id': ids, 'force': force}),
|
||||
null,
|
||||
);
|
||||
}
|
||||
|
||||
Future<String> installExtension(InstallExtension installExtension) async {
|
||||
Future<DownloaderConfig> getConfig() {
|
||||
return _parse<DownloaderConfig>(
|
||||
() => _Client.instance.dio.get('api/v1/config'),
|
||||
(data) => DownloaderConfig.fromJson(data as Map<String, dynamic>),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> putConfig(DownloaderConfig config) {
|
||||
return _parse<void>(() => _Client.instance.dio.put('api/v1/config', data: config.toJson()), null);
|
||||
}
|
||||
|
||||
Future<String> installExtension(InstallExtension installExtension) {
|
||||
return _parse<String>(
|
||||
() => _client.dio.post("api/v1/extensions", data: installExtension),
|
||||
(data) => data as String);
|
||||
() => _Client.instance.dio.post('api/v1/extensions', data: installExtension.toJson()),
|
||||
(data) => data as String,
|
||||
);
|
||||
}
|
||||
|
||||
Future<List<Extension>> getExtensions() async {
|
||||
return _parse<List<Extension>>(() => _client.dio.get("api/v1/extensions"),
|
||||
(data) => (data as List).map((e) => Extension.fromJson(e)).toList());
|
||||
Future<List<Extension>> getExtensions() {
|
||||
return _parse<List<Extension>>(
|
||||
() => _Client.instance.dio.get('api/v1/extensions'),
|
||||
(data) => (data as List<dynamic>).map((e) => Extension.fromJson(e as Map<String, dynamic>)).toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> updateExtensionSettings(
|
||||
String identity, UpdateExtensionSettings updateExtensionSettings) async {
|
||||
return _parse(
|
||||
() => _client.dio.put("api/v1/extensions/$identity/settings",
|
||||
data: updateExtensionSettings),
|
||||
null);
|
||||
Future<void> updateExtensionSettings(String identity, UpdateExtensionSettings updateExtensionSettings) {
|
||||
return _parse<void>(
|
||||
() => _Client.instance.dio.put('api/v1/extensions/$identity/settings', data: updateExtensionSettings.toJson()),
|
||||
null,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> switchExtension(
|
||||
String identity, SwitchExtension switchExtension) async {
|
||||
return _parse(
|
||||
() => _client.dio
|
||||
.put("api/v1/extensions/$identity/switch", data: switchExtension),
|
||||
null);
|
||||
Future<void> switchExtension(String identity, SwitchExtension switchExtension) {
|
||||
return _parse<void>(
|
||||
() => _Client.instance.dio.put('api/v1/extensions/$identity/switch', data: switchExtension.toJson()),
|
||||
null,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> deleteExtension(String identity) async {
|
||||
return _parse(() => _client.dio.delete("api/v1/extensions/$identity"), null);
|
||||
Future<void> deleteExtension(String identity) {
|
||||
return _parse<void>(() => _Client.instance.dio.delete('api/v1/extensions/$identity'), null);
|
||||
}
|
||||
|
||||
Future<UpdateCheckExtensionResp> upgradeCheckExtension(String identity) async {
|
||||
return _parse(() => _client.dio.get("api/v1/extensions/$identity/update"),
|
||||
(data) => UpdateCheckExtensionResp.fromJson(data));
|
||||
Future<UpdateCheckExtensionResp> upgradeCheckExtension(String identity) {
|
||||
return _parse<UpdateCheckExtensionResp>(
|
||||
() => _Client.instance.dio.get('api/v1/extensions/$identity/update'),
|
||||
(data) => UpdateCheckExtensionResp.fromJson(data as Map<String, dynamic>),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> updateExtension(String identity) async {
|
||||
return _parse(
|
||||
() => _client.dio.post("api/v1/extensions/$identity/update"), null);
|
||||
Future<void> updateExtension(String identity) {
|
||||
return _parse<void>(() => _Client.instance.dio.post('api/v1/extensions/$identity/update'), null);
|
||||
}
|
||||
|
||||
Future<void> testWebhook(String url) async {
|
||||
return _parse(
|
||||
() => _client.dio.post("api/v1/webhook/test", data: {"url": url}), null);
|
||||
Future<void> testWebhook(String url) {
|
||||
return _parse<void>(() => _Client.instance.dio.post('api/v1/webhook/test', data: {'url': url}), null);
|
||||
}
|
||||
|
||||
Future<String> login(LoginReq loginReq) async {
|
||||
return _parse(() => _client.dio.post("api/web/login", data: loginReq),
|
||||
(data) => data as String);
|
||||
Future<void> login(LoginReq loginReq) {
|
||||
return _parse<void>(() => _Client.instance.dio.post('api/web/login', data: loginReq.toJson()), null);
|
||||
}
|
||||
|
||||
Future<Response<String>> proxyRequest<T>(String uri,
|
||||
{data, Options? options}) async {
|
||||
Future<Response<String>> proxyRequest<T>(String uri, {dynamic data, Options? options}) async {
|
||||
initDefault();
|
||||
options ??= Options();
|
||||
options.headers ??= {};
|
||||
options.headers!["X-Target-Uri"] = uri;
|
||||
|
||||
// add timestamp to avoid cache
|
||||
return _client.dio.request(
|
||||
"/api/v1/proxy?t=${DateTime.now().millisecondsSinceEpoch}",
|
||||
data: data,
|
||||
options: options);
|
||||
options.headers!['X-Target-Uri'] = uri;
|
||||
return _Client.instance.dio.request<String>(
|
||||
'/api/v1/proxy?t=${DateTime.now().millisecondsSinceEpoch}',
|
||||
data: data,
|
||||
options: options,
|
||||
);
|
||||
}
|
||||
|
||||
String join(String path) {
|
||||
final baseUrl = _client.dio.options.baseUrl;
|
||||
final cleanBaseUrl = baseUrl.endsWith('/')
|
||||
? baseUrl.substring(0, baseUrl.length - 1)
|
||||
: baseUrl;
|
||||
return "$cleanBaseUrl/${Util.cleanPath(path)}";
|
||||
initDefault();
|
||||
final baseUrl = _Client.instance.dio.options.baseUrl;
|
||||
final cleanBaseUrl = baseUrl.endsWith('/') ? baseUrl.substring(0, baseUrl.length - 1) : baseUrl;
|
||||
final cleanPath = path.startsWith('/') ? path.substring(1) : path;
|
||||
return '$cleanBaseUrl/$cleanPath';
|
||||
}
|
||||
|
||||
/// Generic request method for API proxy
|
||||
/// Directly forwards requests to gopeed REST API
|
||||
Future<Response> forward(
|
||||
Future<Response<dynamic>> forward(
|
||||
String path, {
|
||||
String method = 'GET',
|
||||
dynamic data,
|
||||
Map<String, dynamic>? queryParameters,
|
||||
}) async {
|
||||
return _client.dio.request(
|
||||
initDefault();
|
||||
return _Client.instance.dio.request<dynamic>(
|
||||
path,
|
||||
data: data,
|
||||
queryParameters: queryParameters,
|
||||
|
||||
@@ -12,9 +12,12 @@ class GopeedSiteApi {
|
||||
|
||||
static const _host = 'gopeed.com';
|
||||
|
||||
Future<Map<String, dynamic>> getRelease() async {
|
||||
final json = await _getJson('/api/release');
|
||||
return json as Map<String, dynamic>;
|
||||
Future<List<dynamic>> getReleases({int perPage = 10}) async {
|
||||
final json = await _getJson('/api/releases', queryParameters: {'per_page': perPage.clamp(1, 100).toString()});
|
||||
if (json is! List<dynamic>) {
|
||||
throw const FormatException('Invalid releases response');
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
Future<StoreExtensionPage> getExtensions({
|
||||
@@ -24,13 +27,16 @@ class GopeedSiteApi {
|
||||
StoreSortOrder order = StoreSortOrder.desc,
|
||||
String? query,
|
||||
}) async {
|
||||
final json = await _getJson('/api/extensions', queryParameters: {
|
||||
'page': page.toString(),
|
||||
'limit': limit.clamp(1, 100).toString(),
|
||||
'sort': sort.name,
|
||||
'order': order.name,
|
||||
if (query != null && query.trim().isNotEmpty) 'q': query.trim(),
|
||||
});
|
||||
final json = await _getJson(
|
||||
'/api/extensions',
|
||||
queryParameters: {
|
||||
'page': page.toString(),
|
||||
'limit': limit.clamp(1, 100).toString(),
|
||||
'sort': sort.name,
|
||||
'order': order.name,
|
||||
if (query != null && query.trim().isNotEmpty) 'q': query.trim(),
|
||||
},
|
||||
);
|
||||
return StoreExtensionPage.fromJson(json as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
@@ -43,8 +49,7 @@ class GopeedSiteApi {
|
||||
);
|
||||
}
|
||||
|
||||
Future<dynamic> _getJson(String path,
|
||||
{Map<String, String>? queryParameters}) async {
|
||||
Future<dynamic> _getJson(String path, {Map<String, String>? queryParameters}) async {
|
||||
final uri = Uri.https(_host, path, queryParameters);
|
||||
final Response<String> response = await proxyRequest(uri.toString());
|
||||
if (response.data == null || response.data!.isEmpty) {
|
||||
|
||||
@@ -11,16 +11,9 @@ class CreateTask {
|
||||
Request? req;
|
||||
Options? opts;
|
||||
|
||||
CreateTask({
|
||||
this.rid,
|
||||
this.req,
|
||||
this.opts,
|
||||
});
|
||||
CreateTask({this.rid, this.req, this.opts});
|
||||
|
||||
factory CreateTask.fromJson(
|
||||
Map<String, dynamic> json,
|
||||
) =>
|
||||
_$CreateTaskFromJson(json);
|
||||
factory CreateTask.fromJson(Map<String, dynamic> json) => _$CreateTaskFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$CreateTaskToJson(this);
|
||||
}
|
||||
@@ -7,26 +7,13 @@ part of 'create_task.dart';
|
||||
// **************************************************************************
|
||||
|
||||
CreateTask _$CreateTaskFromJson(Map<String, dynamic> json) => CreateTask(
|
||||
rid: json['rid'] as String?,
|
||||
req: json['req'] == null
|
||||
? null
|
||||
: Request.fromJson(json['req'] as Map<String, dynamic>),
|
||||
opts: json['opts'] == null
|
||||
? null
|
||||
: Options.fromJson(json['opts'] as Map<String, dynamic>),
|
||||
);
|
||||
rid: json['rid'] as String?,
|
||||
req: json['req'] == null ? null : Request.fromJson(json['req'] 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>{};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
writeNotNull('rid', instance.rid);
|
||||
writeNotNull('req', instance.req?.toJson());
|
||||
writeNotNull('opts', instance.opts?.toJson());
|
||||
return val;
|
||||
}
|
||||
Map<String, dynamic> _$CreateTaskToJson(CreateTask instance) => <String, dynamic>{
|
||||
'rid': ?instance.rid,
|
||||
'req': ?instance.req?.toJson(),
|
||||
'opts': ?instance.opts?.toJson(),
|
||||
};
|
||||
@@ -10,15 +10,9 @@ class CreateTaskBatch {
|
||||
List<CreateTaskBatchItem>? reqs;
|
||||
Options? opts;
|
||||
|
||||
CreateTaskBatch({
|
||||
this.reqs,
|
||||
this.opts,
|
||||
});
|
||||
CreateTaskBatch({this.reqs, this.opts});
|
||||
|
||||
factory CreateTaskBatch.fromJson(
|
||||
Map<String, dynamic> json,
|
||||
) =>
|
||||
_$CreateTaskBatchFromJson(json);
|
||||
factory CreateTaskBatch.fromJson(Map<String, dynamic> json) => _$CreateTaskBatchFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$CreateTaskBatchToJson(this);
|
||||
}
|
||||
@@ -28,12 +22,8 @@ class CreateTaskBatchItem {
|
||||
Request? req;
|
||||
Options? opts;
|
||||
|
||||
CreateTaskBatchItem({
|
||||
this.req,
|
||||
this.opts,
|
||||
});
|
||||
CreateTaskBatchItem({this.req, this.opts});
|
||||
|
||||
factory CreateTaskBatchItem.fromJson(Map<String, dynamic> json) =>
|
||||
_$CreateTaskBatchItemFromJson(json);
|
||||
factory CreateTaskBatchItem.fromJson(Map<String, dynamic> json) => _$CreateTaskBatchItemFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$CreateTaskBatchItemToJson(this);
|
||||
}
|
||||
@@ -6,50 +6,22 @@ part of 'create_task_batch.dart';
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
CreateTaskBatch _$CreateTaskBatchFromJson(Map<String, dynamic> json) =>
|
||||
CreateTaskBatch(
|
||||
reqs: (json['reqs'] as List<dynamic>?)
|
||||
?.map((e) => CreateTaskBatchItem.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
opts: json['opts'] == null
|
||||
? null
|
||||
: Options.fromJson(json['opts'] as Map<String, dynamic>),
|
||||
);
|
||||
CreateTaskBatch _$CreateTaskBatchFromJson(Map<String, dynamic> json) => CreateTaskBatch(
|
||||
reqs: (json['reqs'] as List<dynamic>?)?.map((e) => CreateTaskBatchItem.fromJson(e as Map<String, dynamic>)).toList(),
|
||||
opts: json['opts'] == null ? null : Options.fromJson(json['opts'] as Map<String, dynamic>),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$CreateTaskBatchToJson(CreateTaskBatch instance) {
|
||||
final val = <String, dynamic>{};
|
||||
Map<String, dynamic> _$CreateTaskBatchToJson(CreateTaskBatch instance) => <String, dynamic>{
|
||||
'reqs': ?instance.reqs?.map((e) => e.toJson()).toList(),
|
||||
'opts': ?instance.opts?.toJson(),
|
||||
};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
CreateTaskBatchItem _$CreateTaskBatchItemFromJson(Map<String, dynamic> json) => CreateTaskBatchItem(
|
||||
req: json['req'] == null ? null : Request.fromJson(json['req'] as Map<String, dynamic>),
|
||||
opts: json['opts'] == null ? null : Options.fromJson(json['opts'] as Map<String, dynamic>),
|
||||
);
|
||||
|
||||
writeNotNull('reqs', instance.reqs?.map((e) => e.toJson()).toList());
|
||||
writeNotNull('opts', instance.opts?.toJson());
|
||||
return val;
|
||||
}
|
||||
|
||||
CreateTaskBatchItem _$CreateTaskBatchItemFromJson(Map<String, dynamic> json) =>
|
||||
CreateTaskBatchItem(
|
||||
req: json['req'] == null
|
||||
? null
|
||||
: Request.fromJson(json['req'] as Map<String, dynamic>),
|
||||
opts: json['opts'] == null
|
||||
? null
|
||||
: Options.fromJson(json['opts'] as Map<String, dynamic>),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$CreateTaskBatchItemToJson(CreateTaskBatchItem instance) {
|
||||
final val = <String, dynamic>{};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
writeNotNull('req', instance.req?.toJson());
|
||||
writeNotNull('opts', instance.opts?.toJson());
|
||||
return val;
|
||||
}
|
||||
Map<String, dynamic> _$CreateTaskBatchItemToJson(CreateTaskBatchItem instance) => <String, dynamic>{
|
||||
'req': ?instance.req,
|
||||
'opts': ?instance.opts,
|
||||
};
|
||||
@@ -13,16 +13,17 @@ class DownloaderConfig {
|
||||
ScriptConfig script = ScriptConfig();
|
||||
AutoTorrentConfig autoTorrent = AutoTorrentConfig();
|
||||
ArchiveConfig archive = ArchiveConfig();
|
||||
bool autoStartTasks;
|
||||
bool autoDeleteMissingFileTasks;
|
||||
|
||||
DownloaderConfig({
|
||||
this.downloadDir = '',
|
||||
this.maxRunning = 0,
|
||||
this.autoStartTasks = false,
|
||||
this.autoDeleteMissingFileTasks = false,
|
||||
});
|
||||
|
||||
factory DownloaderConfig.fromJson(Map<String, dynamic> json) =>
|
||||
_$DownloaderConfigFromJson(json);
|
||||
factory DownloaderConfig.fromJson(Map<String, dynamic> json) => _$DownloaderConfigFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$DownloaderConfigToJson(this);
|
||||
}
|
||||
@@ -47,14 +48,9 @@ class HttpConfig {
|
||||
int connections;
|
||||
bool useServerCtime;
|
||||
|
||||
HttpConfig({
|
||||
this.userAgent = '',
|
||||
this.connections = 0,
|
||||
this.useServerCtime = false,
|
||||
});
|
||||
HttpConfig({this.userAgent = '', this.connections = 0, this.useServerCtime = false});
|
||||
|
||||
factory HttpConfig.fromJson(Map<String, dynamic> json) =>
|
||||
_$HttpConfigFromJson(json);
|
||||
factory HttpConfig.fromJson(Map<String, dynamic> json) => _$HttpConfigFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$HttpConfigToJson(this);
|
||||
}
|
||||
@@ -75,8 +71,7 @@ class BtConfig {
|
||||
this.seedTime = 0,
|
||||
});
|
||||
|
||||
factory BtConfig.fromJson(Map<String, dynamic> json) =>
|
||||
_$BtConfigFromJson(json);
|
||||
factory BtConfig.fromJson(Map<String, dynamic> json) => _$BtConfigFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$BtConfigToJson(this);
|
||||
}
|
||||
@@ -89,16 +84,9 @@ class Ed2kConfig {
|
||||
String serverMet;
|
||||
String nodesDat;
|
||||
|
||||
Ed2kConfig({
|
||||
this.listenPort = 0,
|
||||
this.udpPort = 0,
|
||||
this.serverAddr = '',
|
||||
this.serverMet = '',
|
||||
this.nodesDat = '',
|
||||
});
|
||||
Ed2kConfig({this.listenPort = 0, this.udpPort = 0, this.serverAddr = '', this.serverMet = '', this.nodesDat = ''});
|
||||
|
||||
factory Ed2kConfig.fromJson(Map<String, dynamic> json) =>
|
||||
_$Ed2kConfigFromJson(json);
|
||||
factory Ed2kConfig.fromJson(Map<String, dynamic> json) => _$Ed2kConfigFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$Ed2kConfigToJson(this);
|
||||
}
|
||||
@@ -106,12 +94,12 @@ class Ed2kConfig {
|
||||
@JsonSerializable(explicitToJson: true)
|
||||
class ExtraConfig {
|
||||
String themeMode;
|
||||
String themeColor;
|
||||
String locale;
|
||||
bool lastDeleteTaskKeep;
|
||||
bool defaultDirectDownload;
|
||||
bool defaultBtClient;
|
||||
bool notifyWhenNewVersion;
|
||||
bool autoStartTasks;
|
||||
bool desktopNotification;
|
||||
bool backgroundLocationKeepAlive;
|
||||
List<DownloadCategory> downloadCategories;
|
||||
@@ -121,12 +109,12 @@ class ExtraConfig {
|
||||
|
||||
ExtraConfig({
|
||||
this.themeMode = '',
|
||||
this.themeColor = 'green',
|
||||
this.locale = '',
|
||||
this.lastDeleteTaskKeep = false,
|
||||
this.defaultDirectDownload = false,
|
||||
this.defaultBtClient = true,
|
||||
this.notifyWhenNewVersion = true,
|
||||
this.autoStartTasks = false,
|
||||
this.desktopNotification = true,
|
||||
this.backgroundLocationKeepAlive = false,
|
||||
this.downloadCategories = const [],
|
||||
@@ -144,8 +132,7 @@ class DownloadCategory {
|
||||
String path;
|
||||
bool isBuiltIn;
|
||||
String? nameKey; // i18n key for built-in categories (e.g., 'categoryMusic')
|
||||
bool
|
||||
isDeleted; // Mark built-in categories as deleted instead of removing them
|
||||
bool isDeleted; // Mark built-in categories as deleted instead of removing them
|
||||
|
||||
DownloadCategory({
|
||||
required this.name,
|
||||
@@ -155,8 +142,7 @@ class DownloadCategory {
|
||||
this.isDeleted = false,
|
||||
});
|
||||
|
||||
factory DownloadCategory.fromJson(Map<String, dynamic> json) =>
|
||||
_$DownloadCategoryFromJson(json);
|
||||
factory DownloadCategory.fromJson(Map<String, dynamic> json) => _$DownloadCategoryFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$DownloadCategoryToJson(this);
|
||||
}
|
||||
@@ -166,10 +152,7 @@ class WebhookConfig {
|
||||
bool enable;
|
||||
List<String> urls;
|
||||
|
||||
WebhookConfig({
|
||||
this.enable = false,
|
||||
this.urls = const [],
|
||||
});
|
||||
WebhookConfig({this.enable = false, this.urls = const []});
|
||||
|
||||
factory WebhookConfig.fromJson(Map<String, dynamic>? json) =>
|
||||
json == null ? WebhookConfig() : _$WebhookConfigFromJson(json);
|
||||
@@ -182,10 +165,7 @@ class ScriptConfig {
|
||||
bool enable;
|
||||
List<String> paths;
|
||||
|
||||
ScriptConfig({
|
||||
this.enable = false,
|
||||
this.paths = const [],
|
||||
});
|
||||
ScriptConfig({this.enable = false, this.paths = const []});
|
||||
|
||||
factory ScriptConfig.fromJson(Map<String, dynamic>? json) =>
|
||||
json == null ? ScriptConfig() : _$ScriptConfigFromJson(json);
|
||||
@@ -211,8 +191,7 @@ class ProxyConfig {
|
||||
this.pwd = '',
|
||||
});
|
||||
|
||||
factory ProxyConfig.fromJson(Map<String, dynamic> json) =>
|
||||
_$ProxyConfigFromJson(json);
|
||||
factory ProxyConfig.fromJson(Map<String, dynamic> json) => _$ProxyConfigFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$ProxyConfigToJson(this);
|
||||
}
|
||||
@@ -228,16 +207,12 @@ class ExtraConfigBt {
|
||||
|
||||
ExtraConfigBt();
|
||||
|
||||
factory ExtraConfigBt.fromJson(Map<String, dynamic> json) =>
|
||||
_$ExtraConfigBtFromJson(json);
|
||||
factory ExtraConfigBt.fromJson(Map<String, dynamic> json) => _$ExtraConfigBtFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$ExtraConfigBtToJson(this);
|
||||
}
|
||||
|
||||
enum GithubMirrorType {
|
||||
jsdelivr,
|
||||
ghProxy,
|
||||
}
|
||||
enum GithubMirrorType { jsdelivr, ghProxy }
|
||||
|
||||
@JsonSerializable()
|
||||
class GithubMirror {
|
||||
@@ -246,15 +221,9 @@ class GithubMirror {
|
||||
bool isBuiltIn;
|
||||
bool isDeleted;
|
||||
|
||||
GithubMirror({
|
||||
required this.type,
|
||||
required this.url,
|
||||
this.isBuiltIn = false,
|
||||
this.isDeleted = false,
|
||||
});
|
||||
GithubMirror({required this.type, required this.url, this.isBuiltIn = false, this.isDeleted = false});
|
||||
|
||||
factory GithubMirror.fromJson(Map<String, dynamic> json) =>
|
||||
_$GithubMirrorFromJson(json);
|
||||
factory GithubMirror.fromJson(Map<String, dynamic> json) => _$GithubMirrorFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$GithubMirrorToJson(this);
|
||||
}
|
||||
@@ -264,15 +233,10 @@ class ExtraConfigGithubMirror {
|
||||
bool enabled;
|
||||
List<GithubMirror> mirrors;
|
||||
|
||||
ExtraConfigGithubMirror({
|
||||
this.enabled = true,
|
||||
this.mirrors = const [],
|
||||
});
|
||||
ExtraConfigGithubMirror({this.enabled = true, this.mirrors = const []});
|
||||
|
||||
factory ExtraConfigGithubMirror.fromJson(Map<String, dynamic>? json) =>
|
||||
json == null
|
||||
? ExtraConfigGithubMirror()
|
||||
: _$ExtraConfigGithubMirrorFromJson(json);
|
||||
json == null ? ExtraConfigGithubMirror() : _$ExtraConfigGithubMirrorFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$ExtraConfigGithubMirrorToJson(this);
|
||||
}
|
||||
@@ -282,10 +246,7 @@ class AutoTorrentConfig {
|
||||
bool enable;
|
||||
bool deleteAfterDownload;
|
||||
|
||||
AutoTorrentConfig({
|
||||
this.enable = false,
|
||||
this.deleteAfterDownload = false,
|
||||
});
|
||||
AutoTorrentConfig({this.enable = false, this.deleteAfterDownload = false});
|
||||
|
||||
factory AutoTorrentConfig.fromJson(Map<String, dynamic>? json) =>
|
||||
json == null ? AutoTorrentConfig() : _$AutoTorrentConfigFromJson(json);
|
||||
@@ -298,10 +259,7 @@ class ArchiveConfig {
|
||||
bool autoExtract;
|
||||
bool deleteAfterExtract;
|
||||
|
||||
ArchiveConfig({
|
||||
this.autoExtract = true,
|
||||
this.deleteAfterExtract = true,
|
||||
});
|
||||
ArchiveConfig({this.autoExtract = true, this.deleteAfterExtract = true});
|
||||
|
||||
factory ArchiveConfig.fromJson(Map<String, dynamic>? json) =>
|
||||
json == null ? ArchiveConfig() : _$ArchiveConfigFromJson(json);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -33,8 +33,7 @@ class Extension {
|
||||
required this.devPath,
|
||||
});
|
||||
|
||||
factory Extension.fromJson(Map<String, dynamic> json) =>
|
||||
_$ExtensionFromJson(json);
|
||||
factory Extension.fromJson(Map<String, dynamic> json) => _$ExtensionFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$ExtensionToJson(this);
|
||||
}
|
||||
|
||||
@@ -43,13 +42,9 @@ class Repository {
|
||||
String url;
|
||||
String directory;
|
||||
|
||||
Repository({
|
||||
required this.url,
|
||||
required this.directory,
|
||||
});
|
||||
Repository({required this.url, required this.directory});
|
||||
|
||||
factory Repository.fromJson(Map<String, dynamic> json) =>
|
||||
_$RepositoryFromJson(json);
|
||||
factory Repository.fromJson(Map<String, dynamic> json) => _$RepositoryFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$RepositoryToJson(this);
|
||||
}
|
||||
|
||||
@@ -71,8 +66,7 @@ class Setting {
|
||||
required this.type,
|
||||
});
|
||||
|
||||
factory Setting.fromJson(Map<String, dynamic> json) =>
|
||||
_$SettingFromJson(json);
|
||||
factory Setting.fromJson(Map<String, dynamic> json) => _$SettingFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$SettingToJson(this);
|
||||
}
|
||||
|
||||
@@ -81,17 +75,10 @@ class Option {
|
||||
String label;
|
||||
Object value;
|
||||
|
||||
Option({
|
||||
required this.label,
|
||||
required this.value,
|
||||
});
|
||||
Option({required this.label, required this.value});
|
||||
|
||||
factory Option.fromJson(Map<String, dynamic> json) => _$OptionFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$OptionToJson(this);
|
||||
}
|
||||
|
||||
enum SettingType {
|
||||
string,
|
||||
number,
|
||||
boolean,
|
||||
}
|
||||
enum SettingType { string, number, boolean }
|
||||
@@ -7,92 +7,64 @@ part of 'extension.dart';
|
||||
// **************************************************************************
|
||||
|
||||
Extension _$ExtensionFromJson(Map<String, dynamic> json) => Extension(
|
||||
identity: json['identity'] as String,
|
||||
name: json['name'] as String,
|
||||
author: json['author'] as String,
|
||||
title: json['title'] as String,
|
||||
description: json['description'] as String,
|
||||
icon: json['icon'] as String,
|
||||
version: json['version'] as String,
|
||||
homepage: json['homepage'] as String,
|
||||
repository: json['repository'] == null
|
||||
? null
|
||||
: Repository.fromJson(json['repository'] as Map<String, dynamic>),
|
||||
disabled: json['disabled'] as bool,
|
||||
devMode: json['devMode'] as bool,
|
||||
devPath: json['devPath'] as String,
|
||||
)..settings = (json['settings'] as List<dynamic>?)
|
||||
?.map((e) => Setting.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
identity: json['identity'] as String,
|
||||
name: json['name'] as String,
|
||||
author: json['author'] as String,
|
||||
title: json['title'] as String,
|
||||
description: json['description'] as String,
|
||||
icon: json['icon'] as String,
|
||||
version: json['version'] as String,
|
||||
homepage: json['homepage'] as String,
|
||||
repository: json['repository'] == null ? null : Repository.fromJson(json['repository'] as Map<String, dynamic>),
|
||||
disabled: json['disabled'] as bool,
|
||||
devMode: json['devMode'] as bool,
|
||||
devPath: json['devPath'] as String,
|
||||
)..settings = (json['settings'] as List<dynamic>?)?.map((e) => Setting.fromJson(e as Map<String, dynamic>)).toList();
|
||||
|
||||
Map<String, dynamic> _$ExtensionToJson(Extension instance) {
|
||||
final val = <String, dynamic>{
|
||||
'identity': instance.identity,
|
||||
'name': instance.name,
|
||||
'author': instance.author,
|
||||
'title': instance.title,
|
||||
'description': instance.description,
|
||||
'icon': instance.icon,
|
||||
'version': instance.version,
|
||||
'homepage': instance.homepage,
|
||||
};
|
||||
Map<String, dynamic> _$ExtensionToJson(Extension instance) => <String, dynamic>{
|
||||
'identity': instance.identity,
|
||||
'name': instance.name,
|
||||
'author': instance.author,
|
||||
'title': instance.title,
|
||||
'description': instance.description,
|
||||
'icon': instance.icon,
|
||||
'version': instance.version,
|
||||
'homepage': instance.homepage,
|
||||
'repository': ?instance.repository?.toJson(),
|
||||
'settings': ?instance.settings?.map((e) => e.toJson()).toList(),
|
||||
'disabled': instance.disabled,
|
||||
'devMode': instance.devMode,
|
||||
'devPath': instance.devPath,
|
||||
};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
Repository _$RepositoryFromJson(Map<String, dynamic> json) =>
|
||||
Repository(url: json['url'] as String, directory: json['directory'] as String);
|
||||
|
||||
writeNotNull('repository', instance.repository?.toJson());
|
||||
writeNotNull('settings', instance.settings?.map((e) => e.toJson()).toList());
|
||||
val['disabled'] = instance.disabled;
|
||||
val['devMode'] = instance.devMode;
|
||||
val['devPath'] = instance.devPath;
|
||||
return val;
|
||||
}
|
||||
Map<String, dynamic> _$RepositoryToJson(Repository instance) => <String, dynamic>{
|
||||
'url': instance.url,
|
||||
'directory': instance.directory,
|
||||
};
|
||||
|
||||
Repository _$RepositoryFromJson(Map<String, dynamic> json) => Repository(
|
||||
url: json['url'] as String,
|
||||
directory: json['directory'] as String,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$RepositoryToJson(Repository instance) =>
|
||||
<String, dynamic>{
|
||||
'url': instance.url,
|
||||
'directory': instance.directory,
|
||||
};
|
||||
|
||||
Setting _$SettingFromJson(Map<String, dynamic> json) => Setting(
|
||||
name: json['name'] as String,
|
||||
title: json['title'] as String,
|
||||
description: json['description'] as String,
|
||||
required: json['required'] as bool,
|
||||
type: $enumDecode(_$SettingTypeEnumMap, json['type']),
|
||||
)
|
||||
Setting _$SettingFromJson(Map<String, dynamic> json) =>
|
||||
Setting(
|
||||
name: json['name'] as String,
|
||||
title: json['title'] as String,
|
||||
description: json['description'] as String,
|
||||
required: json['required'] as bool,
|
||||
type: $enumDecode(_$SettingTypeEnumMap, json['type']),
|
||||
)
|
||||
..value = json['value']
|
||||
..options = (json['options'] as List<dynamic>?)
|
||||
?.map((e) => Option.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
..options = (json['options'] as List<dynamic>?)?.map((e) => Option.fromJson(e as Map<String, dynamic>)).toList();
|
||||
|
||||
Map<String, dynamic> _$SettingToJson(Setting instance) {
|
||||
final val = <String, dynamic>{
|
||||
'name': instance.name,
|
||||
'title': instance.title,
|
||||
'description': instance.description,
|
||||
'required': instance.required,
|
||||
'type': _$SettingTypeEnumMap[instance.type]!,
|
||||
};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
writeNotNull('value', instance.value);
|
||||
writeNotNull('options', instance.options);
|
||||
return val;
|
||||
}
|
||||
Map<String, dynamic> _$SettingToJson(Setting instance) => <String, dynamic>{
|
||||
'name': instance.name,
|
||||
'title': instance.title,
|
||||
'description': instance.description,
|
||||
'required': instance.required,
|
||||
'type': _$SettingTypeEnumMap[instance.type]!,
|
||||
'value': ?instance.value,
|
||||
'options': ?instance.options,
|
||||
};
|
||||
|
||||
const _$SettingTypeEnumMap = {
|
||||
SettingType.string: 'string',
|
||||
@@ -100,12 +72,10 @@ const _$SettingTypeEnumMap = {
|
||||
SettingType.boolean: 'boolean',
|
||||
};
|
||||
|
||||
Option _$OptionFromJson(Map<String, dynamic> json) => Option(
|
||||
label: json['label'] as String,
|
||||
value: json['value'] as Object,
|
||||
);
|
||||
Option _$OptionFromJson(Map<String, dynamic> json) =>
|
||||
Option(label: json['label'] as String, value: json['value'] as Object);
|
||||
|
||||
Map<String, dynamic> _$OptionToJson(Option instance) => <String, dynamic>{
|
||||
'label': instance.label,
|
||||
'value': instance.value,
|
||||
};
|
||||
'label': instance.label,
|
||||
'value': instance.value,
|
||||
};
|
||||
@@ -7,12 +7,8 @@ class InstallExtension {
|
||||
bool devMode;
|
||||
String url;
|
||||
|
||||
InstallExtension({
|
||||
this.devMode = false,
|
||||
required this.url,
|
||||
});
|
||||
InstallExtension({this.devMode = false, required this.url});
|
||||
|
||||
factory InstallExtension.fromJson(Map<String, dynamic> json) =>
|
||||
_$InstallExtensionFromJson(json);
|
||||
factory InstallExtension.fromJson(Map<String, dynamic> json) => _$InstallExtensionFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$InstallExtensionToJson(this);
|
||||
}
|
||||
@@ -7,13 +7,9 @@ part of 'install_extension.dart';
|
||||
// **************************************************************************
|
||||
|
||||
InstallExtension _$InstallExtensionFromJson(Map<String, dynamic> json) =>
|
||||
InstallExtension(
|
||||
devMode: json['devMode'] as bool? ?? false,
|
||||
url: json['url'] as String,
|
||||
);
|
||||
InstallExtension(devMode: json['devMode'] as bool? ?? false, url: json['url'] as String);
|
||||
|
||||
Map<String, dynamic> _$InstallExtensionToJson(InstallExtension instance) =>
|
||||
<String, dynamic>{
|
||||
'devMode': instance.devMode,
|
||||
'url': instance.url,
|
||||
};
|
||||
Map<String, dynamic> _$InstallExtensionToJson(InstallExtension instance) => <String, dynamic>{
|
||||
'devMode': instance.devMode,
|
||||
'url': instance.url,
|
||||
};
|
||||
@@ -7,12 +7,8 @@ class LoginReq {
|
||||
String username;
|
||||
String password;
|
||||
|
||||
LoginReq({
|
||||
required this.username,
|
||||
required this.password,
|
||||
});
|
||||
LoginReq({required this.username, required this.password});
|
||||
|
||||
factory LoginReq.fromJson(Map<String, dynamic> json) =>
|
||||
_$LoginReqFromJson(json);
|
||||
factory LoginReq.fromJson(Map<String, dynamic> json) => _$LoginReqFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$LoginReqToJson(this);
|
||||
}
|
||||
@@ -6,12 +6,10 @@ part of 'login.dart';
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
LoginReq _$LoginReqFromJson(Map<String, dynamic> json) => LoginReq(
|
||||
username: json['username'] as String,
|
||||
password: json['password'] as String,
|
||||
);
|
||||
LoginReq _$LoginReqFromJson(Map<String, dynamic> json) =>
|
||||
LoginReq(username: json['username'] as String, password: json['password'] as String);
|
||||
|
||||
Map<String, dynamic> _$LoginReqToJson(LoginReq instance) => <String, dynamic>{
|
||||
'username': instance.username,
|
||||
'password': instance.password,
|
||||
};
|
||||
'username': instance.username,
|
||||
'password': instance.password,
|
||||
};
|
||||
@@ -11,10 +11,7 @@ class Meta {
|
||||
Resource? res;
|
||||
Options opts;
|
||||
|
||||
Meta({
|
||||
required this.req,
|
||||
required this.opts,
|
||||
});
|
||||
Meta({required this.req, required this.opts});
|
||||
|
||||
factory Meta.fromJson(Map<String, dynamic> json) => _$MetaFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$MetaToJson(this);
|
||||
|
||||
@@ -7,24 +7,12 @@ part of 'meta.dart';
|
||||
// **************************************************************************
|
||||
|
||||
Meta _$MetaFromJson(Map<String, dynamic> json) => Meta(
|
||||
req: Request.fromJson(json['req'] as Map<String, dynamic>),
|
||||
opts: Options.fromJson(json['opts'] as Map<String, dynamic>),
|
||||
)..res = json['res'] == null
|
||||
? null
|
||||
: Resource.fromJson(json['res'] as Map<String, dynamic>);
|
||||
req: Request.fromJson(json['req'] as Map<String, dynamic>),
|
||||
opts: Options.fromJson(json['opts'] as Map<String, dynamic>),
|
||||
)..res = json['res'] == null ? null : Resource.fromJson(json['res'] as Map<String, dynamic>);
|
||||
|
||||
Map<String, dynamic> _$MetaToJson(Meta instance) {
|
||||
final val = <String, dynamic>{
|
||||
'req': instance.req.toJson(),
|
||||
};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
writeNotNull('res', instance.res?.toJson());
|
||||
val['opts'] = instance.opts.toJson();
|
||||
return val;
|
||||
}
|
||||
Map<String, dynamic> _$MetaToJson(Meta instance) => <String, dynamic>{
|
||||
'req': instance.req.toJson(),
|
||||
'res': ?instance.res?.toJson(),
|
||||
'opts': instance.opts.toJson(),
|
||||
};
|
||||
@@ -6,18 +6,13 @@ part 'options.g.dart';
|
||||
class Options {
|
||||
String name;
|
||||
String path;
|
||||
bool asDefaultPath;
|
||||
List<int> selectFiles;
|
||||
Object? extra;
|
||||
|
||||
Options({
|
||||
this.name = '',
|
||||
this.path = '',
|
||||
this.selectFiles = const [],
|
||||
this.extra,
|
||||
});
|
||||
Options({this.name = '', this.path = '', this.asDefaultPath = false, this.selectFiles = const [], this.extra});
|
||||
|
||||
factory Options.fromJson(Map<String, dynamic> json) =>
|
||||
_$OptionsFromJson(json);
|
||||
factory Options.fromJson(Map<String, dynamic> json) => _$OptionsFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$OptionsToJson(this);
|
||||
}
|
||||
@@ -40,8 +35,7 @@ class OptsExtraHttp {
|
||||
this.deleteAfterExtract = false,
|
||||
});
|
||||
|
||||
factory OptsExtraHttp.fromJson(Map<String, dynamic> json) =>
|
||||
_$OptsExtraHttpFromJson(json);
|
||||
factory OptsExtraHttp.fromJson(Map<String, dynamic> json) => _$OptsExtraHttpFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$OptsExtraHttpToJson(this);
|
||||
}
|
||||
@@ -7,58 +7,35 @@ part of 'options.dart';
|
||||
// **************************************************************************
|
||||
|
||||
Options _$OptionsFromJson(Map<String, dynamic> json) => Options(
|
||||
name: json['name'] as String? ?? '',
|
||||
path: json['path'] as String? ?? '',
|
||||
selectFiles: (json['selectFiles'] as List<dynamic>?)
|
||||
?.map((e) => (e as num).toInt())
|
||||
.toList() ??
|
||||
const [],
|
||||
extra: json['extra'],
|
||||
);
|
||||
name: json['name'] as String? ?? '',
|
||||
path: json['path'] as String? ?? '',
|
||||
asDefaultPath: json['asDefaultPath'] as bool? ?? false,
|
||||
selectFiles: (json['selectFiles'] as List<dynamic>?)?.map((e) => (e as num).toInt()).toList() ?? const [],
|
||||
extra: json['extra'],
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$OptionsToJson(Options instance) {
|
||||
final val = <String, dynamic>{
|
||||
'name': instance.name,
|
||||
'path': instance.path,
|
||||
'selectFiles': instance.selectFiles,
|
||||
};
|
||||
Map<String, dynamic> _$OptionsToJson(Options instance) => <String, dynamic>{
|
||||
'name': instance.name,
|
||||
'path': instance.path,
|
||||
'asDefaultPath': instance.asDefaultPath,
|
||||
'selectFiles': instance.selectFiles,
|
||||
'extra': ?instance.extra,
|
||||
};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
OptsExtraHttp _$OptsExtraHttpFromJson(Map<String, dynamic> json) => OptsExtraHttp(
|
||||
connections: (json['connections'] as num?)?.toInt() ?? 0,
|
||||
autoTorrent: json['autoTorrent'] as bool?,
|
||||
deleteTorrentAfterDownload: json['deleteTorrentAfterDownload'] as bool?,
|
||||
autoExtract: json['autoExtract'] as bool?,
|
||||
archivePassword: json['archivePassword'] as String? ?? '',
|
||||
deleteAfterExtract: json['deleteAfterExtract'] as bool? ?? false,
|
||||
);
|
||||
|
||||
writeNotNull('extra', instance.extra);
|
||||
return val;
|
||||
}
|
||||
|
||||
OptsExtraHttp _$OptsExtraHttpFromJson(Map<String, dynamic> json) =>
|
||||
OptsExtraHttp(
|
||||
connections: (json['connections'] as num?)?.toInt() ?? 0,
|
||||
autoTorrent: json['autoTorrent'] as bool?,
|
||||
deleteTorrentAfterDownload: json['deleteTorrentAfterDownload'] as bool?,
|
||||
autoExtract: json['autoExtract'] as bool?,
|
||||
archivePassword: json['archivePassword'] as String? ?? '',
|
||||
deleteAfterExtract: json['deleteAfterExtract'] as bool? ?? false,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$OptsExtraHttpToJson(OptsExtraHttp instance) {
|
||||
final val = <String, dynamic>{
|
||||
'connections': instance.connections,
|
||||
};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
writeNotNull('autoTorrent', instance.autoTorrent);
|
||||
writeNotNull(
|
||||
'deleteTorrentAfterDownload', instance.deleteTorrentAfterDownload);
|
||||
writeNotNull('autoExtract', instance.autoExtract);
|
||||
val['archivePassword'] = instance.archivePassword;
|
||||
val['deleteAfterExtract'] = instance.deleteAfterExtract;
|
||||
return val;
|
||||
}
|
||||
Map<String, dynamic> _$OptsExtraHttpToJson(OptsExtraHttp instance) => <String, dynamic>{
|
||||
'connections': instance.connections,
|
||||
'autoTorrent': ?instance.autoTorrent,
|
||||
'deleteTorrentAfterDownload': ?instance.deleteTorrentAfterDownload,
|
||||
'autoExtract': ?instance.autoExtract,
|
||||
'archivePassword': instance.archivePassword,
|
||||
'deleteAfterExtract': instance.deleteAfterExtract,
|
||||
};
|
||||
@@ -0,0 +1,110 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
enum TaskPieceState { pending, completed }
|
||||
|
||||
/// Decoded view of Gopeed's ordered `bitset-v1` piece map.
|
||||
///
|
||||
/// A set bit means the piece is complete and verified. The decoder keeps the
|
||||
/// compact bytes instead of expanding large torrents into per-piece objects;
|
||||
/// [stateAt] reads any piece in O(1).
|
||||
class TaskPieceMap {
|
||||
const TaskPieceMap._({
|
||||
required this.encoding,
|
||||
required this.pieceCount,
|
||||
required this.pieceSize,
|
||||
required this.completedPieces,
|
||||
required Uint8List data,
|
||||
}) : _data = data;
|
||||
|
||||
static const supportedEncoding = 'bitset-v1';
|
||||
|
||||
final String encoding;
|
||||
final int pieceCount;
|
||||
final int pieceSize;
|
||||
final int completedPieces;
|
||||
final Uint8List _data;
|
||||
|
||||
static TaskPieceMap empty() =>
|
||||
TaskPieceMap._(encoding: supportedEncoding, pieceCount: 0, pieceSize: 0, completedPieces: 0, data: Uint8List(0));
|
||||
|
||||
/// Decodes the Base64 bitset returned by Go. Piece N uses bit `N % 8` of
|
||||
/// byte `N ~/ 8`, from least-significant to most-significant bit.
|
||||
static TaskPieceMap? fromJson(Object? value) {
|
||||
if (value is! Map) return null;
|
||||
final json = {for (final entry in value.entries) entry.key.toString(): entry.value};
|
||||
final encoding = json['encoding'];
|
||||
final pieceCount = json['pieceCount'];
|
||||
final pieceSize = json['pieceSize'];
|
||||
final completedPieces = json['completedPieces'];
|
||||
final encodedData = json['data'];
|
||||
if (encoding != supportedEncoding ||
|
||||
pieceCount is! int ||
|
||||
pieceCount < 0 ||
|
||||
pieceSize is! int ||
|
||||
pieceSize < 0 ||
|
||||
completedPieces is! int ||
|
||||
completedPieces < 0 ||
|
||||
completedPieces > pieceCount ||
|
||||
encodedData is! String) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
final data = base64Decode(encodedData);
|
||||
final expectedLength = (pieceCount + 7) ~/ 8;
|
||||
if (data.length != expectedLength) return null;
|
||||
|
||||
var actualCompleted = 0;
|
||||
for (var index = 0; index < pieceCount; index++) {
|
||||
if ((data[index ~/ 8] & (1 << (index % 8))) != 0) actualCompleted++;
|
||||
}
|
||||
if (actualCompleted != completedPieces) return null;
|
||||
|
||||
return TaskPieceMap._(
|
||||
encoding: encoding,
|
||||
pieceCount: pieceCount,
|
||||
pieceSize: pieceSize,
|
||||
completedPieces: completedPieces,
|
||||
data: data,
|
||||
);
|
||||
} on FormatException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Packs local states with the same bit order. Used for widget construction
|
||||
/// and tests; API responses are decoded through [fromJson].
|
||||
factory TaskPieceMap.fromStates(List<TaskPieceState> states, {int pieceSize = 0}) {
|
||||
final data = Uint8List((states.length + 7) ~/ 8);
|
||||
var completedPieces = 0;
|
||||
for (var index = 0; index < states.length; index++) {
|
||||
if (states[index] != TaskPieceState.completed) continue;
|
||||
data[index ~/ 8] |= 1 << (index % 8);
|
||||
completedPieces++;
|
||||
}
|
||||
return TaskPieceMap._(
|
||||
encoding: supportedEncoding,
|
||||
pieceCount: states.length,
|
||||
pieceSize: pieceSize,
|
||||
completedPieces: completedPieces,
|
||||
data: data,
|
||||
);
|
||||
}
|
||||
|
||||
bool get isEmpty => pieceCount == 0;
|
||||
bool get isNotEmpty => !isEmpty;
|
||||
|
||||
TaskPieceState stateAt(int index) {
|
||||
RangeError.checkValidIndex(index, this, 'index', pieceCount);
|
||||
final completed = (_data[index ~/ 8] & (1 << (index % 8))) != 0;
|
||||
return completed ? TaskPieceState.completed : TaskPieceState.pending;
|
||||
}
|
||||
|
||||
bool contains(TaskPieceState state) => switch (state) {
|
||||
TaskPieceState.completed => completedPieces > 0,
|
||||
TaskPieceState.pending => completedPieces < pieceCount,
|
||||
};
|
||||
|
||||
List<TaskPieceState> toStates() => List.generate(pieceCount, stateAt, growable: false);
|
||||
}
|
||||
@@ -11,17 +11,9 @@ class Request {
|
||||
RequestProxy? proxy;
|
||||
bool skipVerifyCert;
|
||||
|
||||
Request({
|
||||
this.rawUrl,
|
||||
required this.url,
|
||||
this.extra,
|
||||
this.labels,
|
||||
this.proxy,
|
||||
this.skipVerifyCert = false,
|
||||
});
|
||||
Request({this.rawUrl, required this.url, this.extra, this.labels, this.proxy, this.skipVerifyCert = false});
|
||||
|
||||
factory Request.fromJson(Map<String, dynamic> json) =>
|
||||
_$RequestFromJson(json);
|
||||
factory Request.fromJson(Map<String, dynamic> json) => _$RequestFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$RequestToJson(this);
|
||||
}
|
||||
@@ -32,14 +24,9 @@ class ReqExtraHttp {
|
||||
Map<String, String> header;
|
||||
String body;
|
||||
|
||||
ReqExtraHttp({
|
||||
this.method = 'GET',
|
||||
this.header = const {},
|
||||
this.body = '',
|
||||
});
|
||||
ReqExtraHttp({this.method = 'GET', this.header = const {}, this.body = ''});
|
||||
|
||||
factory ReqExtraHttp.fromJson(Map<String, dynamic> json) =>
|
||||
_$ReqExtraHttpFromJson(json);
|
||||
factory ReqExtraHttp.fromJson(Map<String, dynamic> json) => _$ReqExtraHttpFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$ReqExtraHttpToJson(this);
|
||||
}
|
||||
@@ -48,21 +35,14 @@ class ReqExtraHttp {
|
||||
class ReqExtraBt {
|
||||
List<String> trackers;
|
||||
|
||||
ReqExtraBt({
|
||||
this.trackers = const [],
|
||||
});
|
||||
ReqExtraBt({this.trackers = const []});
|
||||
|
||||
factory ReqExtraBt.fromJson(Map<String, dynamic> json) =>
|
||||
_$ReqExtraBtFromJson(json);
|
||||
factory ReqExtraBt.fromJson(Map<String, dynamic> json) => _$ReqExtraBtFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$ReqExtraBtToJson(this);
|
||||
}
|
||||
|
||||
enum RequestProxyMode {
|
||||
follow,
|
||||
none,
|
||||
custom,
|
||||
}
|
||||
enum RequestProxyMode { follow, none, custom }
|
||||
|
||||
@JsonSerializable()
|
||||
class RequestProxy {
|
||||
@@ -80,8 +60,7 @@ class RequestProxy {
|
||||
this.pwd = '',
|
||||
});
|
||||
|
||||
factory RequestProxy.fromJson(Map<String, dynamic> json) =>
|
||||
_$RequestProxyFromJson(json);
|
||||
factory RequestProxy.fromJson(Map<String, dynamic> json) => _$RequestProxyFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$RequestProxyToJson(this);
|
||||
}
|
||||
@@ -7,82 +7,55 @@ part of 'request.dart';
|
||||
// **************************************************************************
|
||||
|
||||
Request _$RequestFromJson(Map<String, dynamic> json) => Request(
|
||||
rawUrl: json['rawUrl'] as String?,
|
||||
url: json['url'] as String,
|
||||
extra: json['extra'],
|
||||
labels: (json['labels'] as Map<String, dynamic>?)?.map(
|
||||
(k, e) => MapEntry(k, e as String),
|
||||
),
|
||||
proxy: json['proxy'] == null
|
||||
? null
|
||||
: RequestProxy.fromJson(json['proxy'] as Map<String, dynamic>),
|
||||
skipVerifyCert: json['skipVerifyCert'] as bool? ?? false,
|
||||
);
|
||||
rawUrl: json['rawUrl'] as String?,
|
||||
url: json['url'] as String,
|
||||
extra: json['extra'],
|
||||
labels: (json['labels'] as Map<String, dynamic>?)?.map((k, e) => MapEntry(k, e as String)),
|
||||
proxy: json['proxy'] == null ? null : RequestProxy.fromJson(json['proxy'] as Map<String, dynamic>),
|
||||
skipVerifyCert: json['skipVerifyCert'] as bool? ?? false,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$RequestToJson(Request instance) {
|
||||
final val = <String, dynamic>{
|
||||
'rawUrl': instance.rawUrl,
|
||||
'url': instance.url,
|
||||
};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
writeNotNull('extra', instance.extra);
|
||||
writeNotNull('labels', instance.labels);
|
||||
writeNotNull('proxy', instance.proxy?.toJson());
|
||||
val['skipVerifyCert'] = instance.skipVerifyCert;
|
||||
return val;
|
||||
}
|
||||
Map<String, dynamic> _$RequestToJson(Request instance) => <String, dynamic>{
|
||||
'rawUrl': ?instance.rawUrl,
|
||||
'url': instance.url,
|
||||
'extra': ?instance.extra,
|
||||
'labels': ?instance.labels,
|
||||
'proxy': ?instance.proxy?.toJson(),
|
||||
'skipVerifyCert': instance.skipVerifyCert,
|
||||
};
|
||||
|
||||
ReqExtraHttp _$ReqExtraHttpFromJson(Map<String, dynamic> json) => ReqExtraHttp(
|
||||
method: json['method'] as String? ?? 'GET',
|
||||
header: (json['header'] as Map<String, dynamic>?)?.map(
|
||||
(k, e) => MapEntry(k, e as String),
|
||||
) ??
|
||||
const {},
|
||||
body: json['body'] as String? ?? '',
|
||||
);
|
||||
method: json['method'] as String? ?? 'GET',
|
||||
header: (json['header'] as Map<String, dynamic>?)?.map((k, e) => MapEntry(k, e as String)) ?? const {},
|
||||
body: json['body'] as String? ?? '',
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$ReqExtraHttpToJson(ReqExtraHttp instance) =>
|
||||
<String, dynamic>{
|
||||
'method': instance.method,
|
||||
'header': instance.header,
|
||||
'body': instance.body,
|
||||
};
|
||||
Map<String, dynamic> _$ReqExtraHttpToJson(ReqExtraHttp instance) => <String, dynamic>{
|
||||
'method': instance.method,
|
||||
'header': instance.header,
|
||||
'body': instance.body,
|
||||
};
|
||||
|
||||
ReqExtraBt _$ReqExtraBtFromJson(Map<String, dynamic> json) => ReqExtraBt(
|
||||
trackers: (json['trackers'] as List<dynamic>?)
|
||||
?.map((e) => e as String)
|
||||
.toList() ??
|
||||
const [],
|
||||
);
|
||||
ReqExtraBt _$ReqExtraBtFromJson(Map<String, dynamic> json) =>
|
||||
ReqExtraBt(trackers: (json['trackers'] as List<dynamic>?)?.map((e) => e as String).toList() ?? const []);
|
||||
|
||||
Map<String, dynamic> _$ReqExtraBtToJson(ReqExtraBt instance) =>
|
||||
<String, dynamic>{
|
||||
'trackers': instance.trackers,
|
||||
};
|
||||
Map<String, dynamic> _$ReqExtraBtToJson(ReqExtraBt instance) => <String, dynamic>{'trackers': instance.trackers};
|
||||
|
||||
RequestProxy _$RequestProxyFromJson(Map<String, dynamic> json) => RequestProxy(
|
||||
mode: $enumDecodeNullable(_$RequestProxyModeEnumMap, json['mode']) ??
|
||||
RequestProxyMode.follow,
|
||||
scheme: json['scheme'] as String? ?? 'http',
|
||||
host: json['host'] as String? ?? '',
|
||||
usr: json['usr'] as String? ?? '',
|
||||
pwd: json['pwd'] as String? ?? '',
|
||||
);
|
||||
mode: $enumDecodeNullable(_$RequestProxyModeEnumMap, json['mode']) ?? RequestProxyMode.follow,
|
||||
scheme: json['scheme'] as String? ?? 'http',
|
||||
host: json['host'] as String? ?? '',
|
||||
usr: json['usr'] as String? ?? '',
|
||||
pwd: json['pwd'] as String? ?? '',
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$RequestProxyToJson(RequestProxy instance) =>
|
||||
<String, dynamic>{
|
||||
'mode': _$RequestProxyModeEnumMap[instance.mode]!,
|
||||
'scheme': instance.scheme,
|
||||
'host': instance.host,
|
||||
'usr': instance.usr,
|
||||
'pwd': instance.pwd,
|
||||
};
|
||||
Map<String, dynamic> _$RequestProxyToJson(RequestProxy instance) => <String, dynamic>{
|
||||
'mode': _$RequestProxyModeEnumMap[instance.mode]!,
|
||||
'scheme': instance.scheme,
|
||||
'host': instance.host,
|
||||
'usr': instance.usr,
|
||||
'pwd': instance.pwd,
|
||||
};
|
||||
|
||||
const _$RequestProxyModeEnumMap = {
|
||||
RequestProxyMode.follow: 'follow',
|
||||
|
||||
@@ -9,12 +9,8 @@ class ResolveResult {
|
||||
String id;
|
||||
Resource res;
|
||||
|
||||
ResolveResult({
|
||||
this.id = "",
|
||||
required this.res,
|
||||
});
|
||||
ResolveResult({this.id = "", required this.res});
|
||||
|
||||
factory ResolveResult.fromJson(Map<String, dynamic> json) =>
|
||||
_$ResolveResultFromJson(json);
|
||||
factory ResolveResult.fromJson(Map<String, dynamic> json) => _$ResolveResultFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$ResolveResultToJson(this);
|
||||
}
|
||||
@@ -7,13 +7,9 @@ part of 'resolve_result.dart';
|
||||
// **************************************************************************
|
||||
|
||||
ResolveResult _$ResolveResultFromJson(Map<String, dynamic> json) =>
|
||||
ResolveResult(
|
||||
id: json['id'] as String? ?? "",
|
||||
res: Resource.fromJson(json['res'] as Map<String, dynamic>),
|
||||
);
|
||||
ResolveResult(id: json['id'] as String? ?? "", res: Resource.fromJson(json['res'] as Map<String, dynamic>));
|
||||
|
||||
Map<String, dynamic> _$ResolveResultToJson(ResolveResult instance) =>
|
||||
<String, dynamic>{
|
||||
'id': instance.id,
|
||||
'res': instance.res.toJson(),
|
||||
};
|
||||
Map<String, dynamic> _$ResolveResultToJson(ResolveResult instance) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'res': instance.res.toJson(),
|
||||
};
|
||||
@@ -10,12 +10,8 @@ class ResolveTask {
|
||||
Request? req;
|
||||
Options? opts;
|
||||
|
||||
ResolveTask({
|
||||
this.req,
|
||||
this.opts,
|
||||
});
|
||||
ResolveTask({this.req, this.opts});
|
||||
|
||||
factory ResolveTask.fromJson(Map<String, dynamic> json) =>
|
||||
_$ResolveTaskFromJson(json);
|
||||
factory ResolveTask.fromJson(Map<String, dynamic> json) => _$ResolveTaskFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$ResolveTaskToJson(this);
|
||||
}
|
||||
@@ -7,24 +7,11 @@ part of 'resolve_task.dart';
|
||||
// **************************************************************************
|
||||
|
||||
ResolveTask _$ResolveTaskFromJson(Map<String, dynamic> json) => ResolveTask(
|
||||
req: json['req'] == null
|
||||
? null
|
||||
: Request.fromJson(json['req'] as Map<String, dynamic>),
|
||||
opts: json['opts'] == null
|
||||
? null
|
||||
: Options.fromJson(json['opts'] as Map<String, dynamic>),
|
||||
);
|
||||
req: json['req'] == null ? null : Request.fromJson(json['req'] as Map<String, dynamic>),
|
||||
opts: json['opts'] == null ? null : Options.fromJson(json['opts'] as Map<String, dynamic>),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$ResolveTaskToJson(ResolveTask instance) {
|
||||
final val = <String, dynamic>{};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
writeNotNull('req', instance.req);
|
||||
writeNotNull('opts', instance.opts);
|
||||
return val;
|
||||
}
|
||||
Map<String, dynamic> _$ResolveTaskToJson(ResolveTask instance) => <String, dynamic>{
|
||||
'req': ?instance.req,
|
||||
'opts': ?instance.opts,
|
||||
};
|
||||
@@ -11,15 +11,9 @@ class Resource {
|
||||
List<FileInfo> files;
|
||||
String hash;
|
||||
|
||||
Resource(
|
||||
{this.name = "",
|
||||
this.size = 0,
|
||||
this.range = false,
|
||||
required this.files,
|
||||
this.hash = ""});
|
||||
Resource({this.name = "", this.size = 0, this.range = false, required this.files, this.hash = ""});
|
||||
|
||||
factory Resource.fromJson(Map<String, dynamic> json) =>
|
||||
_$ResourceFromJson(json);
|
||||
factory Resource.fromJson(Map<String, dynamic> json) => _$ResourceFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$ResourceToJson(this);
|
||||
}
|
||||
@@ -31,15 +25,9 @@ class FileInfo {
|
||||
int size;
|
||||
Request? req;
|
||||
|
||||
FileInfo({
|
||||
this.path = "",
|
||||
required this.name,
|
||||
this.size = 0,
|
||||
this.req,
|
||||
});
|
||||
FileInfo({this.path = "", required this.name, this.size = 0, this.req});
|
||||
|
||||
factory FileInfo.fromJson(Map<String, dynamic> json) =>
|
||||
_$FileInfoFromJson(json);
|
||||
factory FileInfo.fromJson(Map<String, dynamic> json) => _$FileInfoFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$FileInfoToJson(this);
|
||||
}
|
||||
@@ -7,45 +7,31 @@ part of 'resource.dart';
|
||||
// **************************************************************************
|
||||
|
||||
Resource _$ResourceFromJson(Map<String, dynamic> json) => Resource(
|
||||
name: json['name'] as String? ?? "",
|
||||
size: (json['size'] as num?)?.toInt() ?? 0,
|
||||
range: json['range'] as bool? ?? false,
|
||||
files: (json['files'] as List<dynamic>)
|
||||
.map((e) => FileInfo.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
hash: json['hash'] as String? ?? "",
|
||||
);
|
||||
name: json['name'] as String? ?? "",
|
||||
size: (json['size'] as num?)?.toInt() ?? 0,
|
||||
range: json['range'] as bool? ?? false,
|
||||
files: (json['files'] as List<dynamic>).map((e) => FileInfo.fromJson(e as Map<String, dynamic>)).toList(),
|
||||
hash: json['hash'] as String? ?? "",
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$ResourceToJson(Resource instance) => <String, dynamic>{
|
||||
'name': instance.name,
|
||||
'size': instance.size,
|
||||
'range': instance.range,
|
||||
'files': instance.files.map((e) => e.toJson()).toList(),
|
||||
'hash': instance.hash,
|
||||
};
|
||||
'name': instance.name,
|
||||
'size': instance.size,
|
||||
'range': instance.range,
|
||||
'files': instance.files.map((e) => e.toJson()).toList(),
|
||||
'hash': instance.hash,
|
||||
};
|
||||
|
||||
FileInfo _$FileInfoFromJson(Map<String, dynamic> json) => FileInfo(
|
||||
path: json['path'] as String? ?? "",
|
||||
name: json['name'] as String,
|
||||
size: (json['size'] as num?)?.toInt() ?? 0,
|
||||
req: json['req'] == null
|
||||
? null
|
||||
: Request.fromJson(json['req'] as Map<String, dynamic>),
|
||||
);
|
||||
path: json['path'] as String? ?? "",
|
||||
name: json['name'] as String,
|
||||
size: (json['size'] as num?)?.toInt() ?? 0,
|
||||
req: json['req'] == null ? null : Request.fromJson(json['req'] as Map<String, dynamic>),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$FileInfoToJson(FileInfo instance) {
|
||||
final val = <String, dynamic>{
|
||||
'path': instance.path,
|
||||
'name': instance.name,
|
||||
'size': instance.size,
|
||||
};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
writeNotNull('req', instance.req?.toJson());
|
||||
return val;
|
||||
}
|
||||
Map<String, dynamic> _$FileInfoToJson(FileInfo instance) => <String, dynamic>{
|
||||
'path': instance.path,
|
||||
'name': instance.name,
|
||||
'size': instance.size,
|
||||
'req': ?instance.req?.toJson(),
|
||||
};
|
||||
@@ -2,28 +2,19 @@ import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
part 'result.g.dart';
|
||||
|
||||
@JsonSerializable(genericArgumentFactories: true)
|
||||
@JsonSerializable(genericArgumentFactories: true, createToJson: false)
|
||||
class Result<T> {
|
||||
int code;
|
||||
String? msg;
|
||||
T? data;
|
||||
|
||||
Result({
|
||||
required this.code,
|
||||
this.msg,
|
||||
this.data,
|
||||
});
|
||||
Result({required this.code, this.msg, this.data});
|
||||
|
||||
factory Result.fromJson(
|
||||
Map<String, dynamic> json,
|
||||
T Function(dynamic json) fromJsonT,
|
||||
) =>
|
||||
factory Result.fromJson(Map<String, dynamic> json, T Function(dynamic json) fromJsonT) =>
|
||||
_$ResultFromJson(json, fromJsonT);
|
||||
Map<String, dynamic> toJson() => {
|
||||
'code': code,
|
||||
'msg': msg,
|
||||
'data': data is List
|
||||
? (data as dynamic)?.map((e) => e.toJson()).toList()
|
||||
: (data as dynamic)?.toJson(),
|
||||
};
|
||||
'code': code,
|
||||
'msg': msg,
|
||||
'data': data is List ? (data as dynamic)?.map((e) => e.toJson()).toList() : (data as dynamic)?.toJson(),
|
||||
};
|
||||
}
|
||||
@@ -6,43 +6,11 @@ part of 'result.dart';
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
Result<T> _$ResultFromJson<T>(
|
||||
Map<String, dynamic> json,
|
||||
T Function(Object? json) fromJsonT,
|
||||
) =>
|
||||
Result<T>(
|
||||
code: (json['code'] as num).toInt(),
|
||||
msg: json['msg'] as String?,
|
||||
data: _$nullableGenericFromJson(json['data'], fromJsonT),
|
||||
);
|
||||
Result<T> _$ResultFromJson<T>(Map<String, dynamic> json, T Function(Object? json) fromJsonT) => Result<T>(
|
||||
code: (json['code'] as num).toInt(),
|
||||
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>{
|
||||
'code': instance.code,
|
||||
};
|
||||
|
||||
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,
|
||||
) =>
|
||||
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);
|
||||
@@ -11,8 +11,7 @@ class StoreExtensionPage {
|
||||
data: (json['data'] as List<dynamic>? ?? [])
|
||||
.map((e) => StoreExtension.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
pagination: StorePagination.fromJson(
|
||||
json['pagination'] as Map<String, dynamic>? ?? {}),
|
||||
pagination: StorePagination.fromJson(json['pagination'] as Map<String, dynamic>? ?? {}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -137,13 +136,6 @@ class StoreExtension {
|
||||
}
|
||||
}
|
||||
|
||||
enum StoreExtensionSort {
|
||||
stars,
|
||||
installs,
|
||||
updated,
|
||||
}
|
||||
enum StoreExtensionSort { stars, installs, updated }
|
||||
|
||||
enum StoreSortOrder {
|
||||
asc,
|
||||
desc,
|
||||
}
|
||||
enum StoreSortOrder { asc, desc }
|
||||
@@ -6,11 +6,8 @@ part 'switch_extension.g.dart';
|
||||
class SwitchExtension {
|
||||
bool status;
|
||||
|
||||
SwitchExtension({
|
||||
required this.status,
|
||||
});
|
||||
SwitchExtension({required this.status});
|
||||
|
||||
factory SwitchExtension.fromJson(Map<String, dynamic> json) =>
|
||||
_$SwitchExtensionFromJson(json);
|
||||
factory SwitchExtension.fromJson(Map<String, dynamic> json) => _$SwitchExtensionFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$SwitchExtensionToJson(this);
|
||||
}
|
||||
@@ -6,12 +6,6 @@ part of 'switch_extension.dart';
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
SwitchExtension _$SwitchExtensionFromJson(Map<String, dynamic> json) =>
|
||||
SwitchExtension(
|
||||
status: json['status'] as bool,
|
||||
);
|
||||
SwitchExtension _$SwitchExtensionFromJson(Map<String, dynamic> json) => SwitchExtension(status: json['status'] as bool);
|
||||
|
||||
Map<String, dynamic> _$SwitchExtensionToJson(SwitchExtension instance) =>
|
||||
<String, dynamic>{
|
||||
'status': instance.status,
|
||||
};
|
||||
Map<String, dynamic> _$SwitchExtensionToJson(SwitchExtension instance) => <String, dynamic>{'status': instance.status};
|
||||
@@ -12,6 +12,8 @@ enum Protocol { http, bt, ed2k }
|
||||
enum ExtractStatus {
|
||||
@JsonValue('')
|
||||
none,
|
||||
@JsonValue('queued')
|
||||
queued,
|
||||
@JsonValue('extracting')
|
||||
extracting,
|
||||
@JsonValue('done')
|
||||
@@ -19,7 +21,7 @@ enum ExtractStatus {
|
||||
@JsonValue('error')
|
||||
error,
|
||||
@JsonValue('waitingParts')
|
||||
waitingParts
|
||||
waitingParts,
|
||||
}
|
||||
|
||||
@JsonSerializable(explicitToJson: true)
|
||||
@@ -70,8 +72,51 @@ class Progress {
|
||||
this.extractProgress = 0,
|
||||
});
|
||||
|
||||
factory Progress.fromJson(Map<String, dynamic> json) =>
|
||||
_$ProgressFromJson(json);
|
||||
factory Progress.fromJson(Map<String, dynamic> json) => _$ProgressFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$ProgressToJson(this);
|
||||
}
|
||||
|
||||
@JsonSerializable()
|
||||
class FileRuntimeStatus {
|
||||
int index;
|
||||
int size;
|
||||
int downloaded;
|
||||
|
||||
FileRuntimeStatus({required this.index, required this.size, required this.downloaded});
|
||||
|
||||
factory FileRuntimeStatus.fromJson(Map<String, dynamic> json) => _$FileRuntimeStatusFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$FileRuntimeStatusToJson(this);
|
||||
}
|
||||
|
||||
@JsonSerializable(explicitToJson: true)
|
||||
class TaskRuntimeStatus {
|
||||
Status status;
|
||||
int used;
|
||||
int speed;
|
||||
int downloaded;
|
||||
int total;
|
||||
int uploadSpeed;
|
||||
int uploaded;
|
||||
ExtractStatus extractStatus;
|
||||
int extractProgress;
|
||||
List<FileRuntimeStatus> files;
|
||||
|
||||
TaskRuntimeStatus({
|
||||
required this.status,
|
||||
required this.used,
|
||||
required this.speed,
|
||||
required this.downloaded,
|
||||
required this.total,
|
||||
required this.uploadSpeed,
|
||||
required this.uploaded,
|
||||
this.extractStatus = ExtractStatus.none,
|
||||
this.extractProgress = 0,
|
||||
required this.files,
|
||||
});
|
||||
|
||||
factory TaskRuntimeStatus.fromJson(Map<String, dynamic> json) => _$TaskRuntimeStatusFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$TaskRuntimeStatusToJson(this);
|
||||
}
|
||||
@@ -7,37 +7,27 @@ part of 'task.dart';
|
||||
// **************************************************************************
|
||||
|
||||
Task _$TaskFromJson(Map<String, dynamic> json) => Task(
|
||||
id: json['id'] as String,
|
||||
name: json['name'] as String,
|
||||
meta: Meta.fromJson(json['meta'] as Map<String, dynamic>),
|
||||
status: $enumDecode(_$StatusEnumMap, json['status']),
|
||||
uploading: json['uploading'] as bool,
|
||||
progress: Progress.fromJson(json['progress'] as Map<String, dynamic>),
|
||||
createdAt: DateTime.parse(json['createdAt'] as String),
|
||||
updatedAt: DateTime.parse(json['updatedAt'] as String),
|
||||
)..protocol = $enumDecodeNullable(_$ProtocolEnumMap, json['protocol']);
|
||||
id: json['id'] as String,
|
||||
name: json['name'] as String,
|
||||
meta: Meta.fromJson(json['meta'] as Map<String, dynamic>),
|
||||
status: $enumDecode(_$StatusEnumMap, json['status']),
|
||||
uploading: json['uploading'] as bool,
|
||||
progress: Progress.fromJson(json['progress'] as Map<String, dynamic>),
|
||||
createdAt: DateTime.parse(json['createdAt'] as String),
|
||||
updatedAt: DateTime.parse(json['updatedAt'] as String),
|
||||
)..protocol = $enumDecodeNullable(_$ProtocolEnumMap, json['protocol']);
|
||||
|
||||
Map<String, dynamic> _$TaskToJson(Task instance) {
|
||||
final val = <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'name': instance.name,
|
||||
};
|
||||
|
||||
void writeNotNull(String key, dynamic value) {
|
||||
if (value != null) {
|
||||
val[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
writeNotNull('protocol', _$ProtocolEnumMap[instance.protocol]);
|
||||
val['meta'] = instance.meta.toJson();
|
||||
val['status'] = _$StatusEnumMap[instance.status]!;
|
||||
val['uploading'] = instance.uploading;
|
||||
val['progress'] = instance.progress.toJson();
|
||||
val['createdAt'] = instance.createdAt.toIso8601String();
|
||||
val['updatedAt'] = instance.updatedAt.toIso8601String();
|
||||
return val;
|
||||
}
|
||||
Map<String, dynamic> _$TaskToJson(Task instance) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'name': instance.name,
|
||||
'protocol': ?_$ProtocolEnumMap[instance.protocol],
|
||||
'meta': instance.meta.toJson(),
|
||||
'status': _$StatusEnumMap[instance.status]!,
|
||||
'uploading': instance.uploading,
|
||||
'progress': instance.progress.toJson(),
|
||||
'createdAt': instance.createdAt.toIso8601String(),
|
||||
'updatedAt': instance.updatedAt.toIso8601String(),
|
||||
};
|
||||
|
||||
const _$StatusEnumMap = {
|
||||
Status.ready: 'ready',
|
||||
@@ -48,38 +38,71 @@ const _$StatusEnumMap = {
|
||||
Status.done: 'done',
|
||||
};
|
||||
|
||||
const _$ProtocolEnumMap = {
|
||||
Protocol.http: 'http',
|
||||
Protocol.bt: 'bt',
|
||||
Protocol.ed2k: 'ed2k',
|
||||
};
|
||||
const _$ProtocolEnumMap = {Protocol.http: 'http', Protocol.bt: 'bt', Protocol.ed2k: 'ed2k'};
|
||||
|
||||
Progress _$ProgressFromJson(Map<String, dynamic> json) => Progress(
|
||||
used: (json['used'] as num).toInt(),
|
||||
speed: (json['speed'] as num).toInt(),
|
||||
downloaded: (json['downloaded'] as num).toInt(),
|
||||
uploadSpeed: (json['uploadSpeed'] as num).toInt(),
|
||||
uploaded: (json['uploaded'] as num).toInt(),
|
||||
extractStatus:
|
||||
$enumDecodeNullable(_$ExtractStatusEnumMap, json['extractStatus']) ??
|
||||
ExtractStatus.none,
|
||||
extractProgress: (json['extractProgress'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
used: (json['used'] as num).toInt(),
|
||||
speed: (json['speed'] as num).toInt(),
|
||||
downloaded: (json['downloaded'] as num).toInt(),
|
||||
uploadSpeed: (json['uploadSpeed'] as num).toInt(),
|
||||
uploaded: (json['uploaded'] as num).toInt(),
|
||||
extractStatus: $enumDecodeNullable(_$ExtractStatusEnumMap, json['extractStatus']) ?? ExtractStatus.none,
|
||||
extractProgress: (json['extractProgress'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$ProgressToJson(Progress instance) => <String, dynamic>{
|
||||
'used': instance.used,
|
||||
'speed': instance.speed,
|
||||
'downloaded': instance.downloaded,
|
||||
'uploadSpeed': instance.uploadSpeed,
|
||||
'uploaded': instance.uploaded,
|
||||
'extractStatus': _$ExtractStatusEnumMap[instance.extractStatus]!,
|
||||
'extractProgress': instance.extractProgress,
|
||||
};
|
||||
'used': instance.used,
|
||||
'speed': instance.speed,
|
||||
'downloaded': instance.downloaded,
|
||||
'uploadSpeed': instance.uploadSpeed,
|
||||
'uploaded': instance.uploaded,
|
||||
'extractStatus': _$ExtractStatusEnumMap[instance.extractStatus]!,
|
||||
'extractProgress': instance.extractProgress,
|
||||
};
|
||||
|
||||
const _$ExtractStatusEnumMap = {
|
||||
ExtractStatus.none: '',
|
||||
ExtractStatus.queued: 'queued',
|
||||
ExtractStatus.extracting: 'extracting',
|
||||
ExtractStatus.done: 'done',
|
||||
ExtractStatus.error: 'error',
|
||||
ExtractStatus.waitingParts: 'waitingParts',
|
||||
};
|
||||
|
||||
FileRuntimeStatus _$FileRuntimeStatusFromJson(Map<String, dynamic> json) => FileRuntimeStatus(
|
||||
index: (json['index'] as num).toInt(),
|
||||
size: (json['size'] as num).toInt(),
|
||||
downloaded: (json['downloaded'] as num).toInt(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$FileRuntimeStatusToJson(FileRuntimeStatus instance) => <String, dynamic>{
|
||||
'index': instance.index,
|
||||
'size': instance.size,
|
||||
'downloaded': instance.downloaded,
|
||||
};
|
||||
|
||||
TaskRuntimeStatus _$TaskRuntimeStatusFromJson(Map<String, dynamic> json) => TaskRuntimeStatus(
|
||||
status: $enumDecode(_$StatusEnumMap, json['status']),
|
||||
used: (json['used'] as num).toInt(),
|
||||
speed: (json['speed'] as num).toInt(),
|
||||
downloaded: (json['downloaded'] as num).toInt(),
|
||||
total: (json['total'] as num).toInt(),
|
||||
uploadSpeed: (json['uploadSpeed'] as num).toInt(),
|
||||
uploaded: (json['uploaded'] as num).toInt(),
|
||||
extractStatus: $enumDecodeNullable(_$ExtractStatusEnumMap, json['extractStatus']) ?? ExtractStatus.none,
|
||||
extractProgress: (json['extractProgress'] as num?)?.toInt() ?? 0,
|
||||
files: (json['files'] as List<dynamic>).map((e) => FileRuntimeStatus.fromJson(e as Map<String, dynamic>)).toList(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$TaskRuntimeStatusToJson(TaskRuntimeStatus instance) => <String, dynamic>{
|
||||
'status': _$StatusEnumMap[instance.status]!,
|
||||
'used': instance.used,
|
||||
'speed': instance.speed,
|
||||
'downloaded': instance.downloaded,
|
||||
'total': instance.total,
|
||||
'uploadSpeed': instance.uploadSpeed,
|
||||
'uploaded': instance.uploaded,
|
||||
'extractStatus': _$ExtractStatusEnumMap[instance.extractStatus]!,
|
||||
'extractProgress': instance.extractProgress,
|
||||
'files': instance.files.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
@@ -0,0 +1,207 @@
|
||||
export 'piece_map_codec.dart' show TaskPieceMap, TaskPieceState;
|
||||
|
||||
import 'piece_map_codec.dart';
|
||||
import 'task.dart';
|
||||
|
||||
class TaskPeerStats {
|
||||
const TaskPeerStats({
|
||||
required this.address,
|
||||
required this.client,
|
||||
required this.downloadSpeed,
|
||||
required this.uploadSpeed,
|
||||
required this.pieceCount,
|
||||
required this.completion,
|
||||
required this.relevance,
|
||||
required this.source,
|
||||
required this.transport,
|
||||
});
|
||||
|
||||
final String address;
|
||||
final String client;
|
||||
final int downloadSpeed;
|
||||
final int uploadSpeed;
|
||||
final int pieceCount;
|
||||
final double? completion;
|
||||
final double? relevance;
|
||||
final String source;
|
||||
final String transport;
|
||||
|
||||
factory TaskPeerStats.fromJson(Map<String, dynamic> json) {
|
||||
return TaskPeerStats(
|
||||
address: _string(json, 'address'),
|
||||
client: _string(json, 'client'),
|
||||
downloadSpeed: _integer(json, 'downloadSpeed'),
|
||||
uploadSpeed: _integer(json, 'uploadSpeed'),
|
||||
pieceCount: _integer(json, 'pieceCount'),
|
||||
completion: _optionalDecimal(json, 'completion'),
|
||||
relevance: _optionalDecimal(json, 'relevance'),
|
||||
source: _string(json, 'source'),
|
||||
transport: _string(json, 'transport'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
sealed class TaskStats {
|
||||
const TaskStats({required this.peers, required this.pieceMap});
|
||||
|
||||
final List<TaskPeerStats> peers;
|
||||
final TaskPieceMap pieceMap;
|
||||
|
||||
static TaskStats? fromJson(Protocol? protocol, Map<String, dynamic> json) {
|
||||
final snapshot = _map(json['snapshot']);
|
||||
final runtime = _map(json['runtime']);
|
||||
if (snapshot.isEmpty && runtime.isEmpty) return null;
|
||||
return switch (protocol) {
|
||||
Protocol.http => HttpTaskStats.fromJson(snapshot),
|
||||
Protocol.bt => BtTaskStats.fromJson(snapshot: snapshot, runtime: runtime),
|
||||
Protocol.ed2k => Ed2kTaskStats.fromJson(snapshot: snapshot, runtime: runtime),
|
||||
null => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class HttpConnectionStats {
|
||||
const HttpConnectionStats({
|
||||
required this.downloaded,
|
||||
required this.total,
|
||||
required this.completed,
|
||||
required this.failed,
|
||||
required this.retryTimes,
|
||||
});
|
||||
|
||||
final int downloaded;
|
||||
final int total;
|
||||
final bool completed;
|
||||
final bool failed;
|
||||
final int retryTimes;
|
||||
|
||||
factory HttpConnectionStats.fromJson(Map<String, dynamic> json) {
|
||||
return HttpConnectionStats(
|
||||
downloaded: _integer(json, 'downloaded'),
|
||||
total: _integer(json, 'total'),
|
||||
completed: json['completed'] == true,
|
||||
failed: json['failed'] == true,
|
||||
retryTimes: _integer(json, 'retryTimes'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class HttpTaskStats extends TaskStats {
|
||||
HttpTaskStats({required this.connections}) : super(peers: const [], pieceMap: TaskPieceMap.empty());
|
||||
|
||||
final List<HttpConnectionStats> connections;
|
||||
|
||||
factory HttpTaskStats.fromJson(Map<String, dynamic> json) {
|
||||
return HttpTaskStats(
|
||||
connections: _maps(json['connections']).map(HttpConnectionStats.fromJson).toList(growable: false),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class BtTaskStats extends TaskStats {
|
||||
const BtTaskStats({
|
||||
required this.totalPeers,
|
||||
required this.activePeers,
|
||||
required this.connectedSeeders,
|
||||
required this.connectedLeechers,
|
||||
required this.seedBytes,
|
||||
required this.seedRatio,
|
||||
required this.seedTime,
|
||||
required super.peers,
|
||||
required super.pieceMap,
|
||||
});
|
||||
|
||||
final int totalPeers;
|
||||
final int activePeers;
|
||||
final int connectedSeeders;
|
||||
final int connectedLeechers;
|
||||
final int seedBytes;
|
||||
final double seedRatio;
|
||||
final int seedTime;
|
||||
|
||||
factory BtTaskStats.fromJson({required Map<String, dynamic> snapshot, required Map<String, dynamic> runtime}) {
|
||||
return BtTaskStats(
|
||||
totalPeers: _integer(runtime, 'totalPeers'),
|
||||
activePeers: _integer(runtime, 'activePeers'),
|
||||
connectedSeeders: _integer(runtime, 'connectedSeeders'),
|
||||
connectedLeechers: _integer(runtime, 'connectedLeechers'),
|
||||
seedBytes: _integer(snapshot, 'seedBytes'),
|
||||
seedRatio: _decimal(snapshot, 'seedRatio'),
|
||||
seedTime: _integer(snapshot, 'seedTime'),
|
||||
peers: _peerList(runtime['peers']),
|
||||
pieceMap: TaskPieceMap.fromJson(snapshot['pieceMap']) ?? TaskPieceMap.empty(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class Ed2kTaskStats extends TaskStats {
|
||||
const Ed2kTaskStats({
|
||||
required this.activePeers,
|
||||
required this.totalPeers,
|
||||
required this.downloadRate,
|
||||
required this.upload,
|
||||
required this.uploadRate,
|
||||
required this.totalDone,
|
||||
required this.totalWanted,
|
||||
required super.peers,
|
||||
required super.pieceMap,
|
||||
});
|
||||
|
||||
final int activePeers;
|
||||
final int totalPeers;
|
||||
final int downloadRate;
|
||||
final int upload;
|
||||
final int uploadRate;
|
||||
final int totalDone;
|
||||
final int totalWanted;
|
||||
int get completedPieces => pieceMap.completedPieces;
|
||||
|
||||
factory Ed2kTaskStats.fromJson({required Map<String, dynamic> snapshot, required Map<String, dynamic> runtime}) {
|
||||
return Ed2kTaskStats(
|
||||
activePeers: _integer(runtime, 'activePeers'),
|
||||
totalPeers: _integer(runtime, 'totalPeers'),
|
||||
downloadRate: _integer(runtime, 'downloadRate'),
|
||||
upload: _integer(snapshot, 'upload'),
|
||||
uploadRate: _integer(runtime, 'uploadRate'),
|
||||
totalDone: _integer(snapshot, 'totalDone'),
|
||||
totalWanted: _integer(snapshot, 'totalWanted'),
|
||||
peers: _peerList(runtime['peers']),
|
||||
pieceMap: TaskPieceMap.fromJson(snapshot['pieceMap']) ?? TaskPieceMap.empty(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
List<Map<String, dynamic>> _maps(Object? value) {
|
||||
if (value is! List) return const [];
|
||||
return value
|
||||
.whereType<Map>()
|
||||
.map((item) => {for (final entry in item.entries) entry.key.toString(): entry.value})
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
Map<String, dynamic> _map(Object? value) {
|
||||
if (value is! Map) return const {};
|
||||
return {for (final entry in value.entries) entry.key.toString(): entry.value};
|
||||
}
|
||||
|
||||
List<TaskPeerStats> _peerList(Object? value) => _maps(value).map(TaskPeerStats.fromJson).toList(growable: false);
|
||||
|
||||
int _integer(Map<String, dynamic> json, String key) => switch (json[key]) {
|
||||
final int value => value,
|
||||
_ => 0,
|
||||
};
|
||||
|
||||
double _decimal(Map<String, dynamic> json, String key) => switch (json[key]) {
|
||||
final num value => value.toDouble(),
|
||||
_ => 0,
|
||||
};
|
||||
|
||||
double? _optionalDecimal(Map<String, dynamic> json, String key) => switch (json[key]) {
|
||||
final num value => value.toDouble(),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
String _string(Map<String, dynamic> json, String key) => switch (json[key]) {
|
||||
final String value when value.isNotEmpty => value,
|
||||
_ => '—',
|
||||
};
|
||||
@@ -6,11 +6,8 @@ part 'update_check_extension_resp.g.dart';
|
||||
class UpdateCheckExtensionResp {
|
||||
String newVersion;
|
||||
|
||||
UpdateCheckExtensionResp({
|
||||
required this.newVersion,
|
||||
});
|
||||
UpdateCheckExtensionResp({required this.newVersion});
|
||||
|
||||
factory UpdateCheckExtensionResp.fromJson(Map<String, dynamic> json) =>
|
||||
_$UpdateCheckExtensionRespFromJson(json);
|
||||
factory UpdateCheckExtensionResp.fromJson(Map<String, dynamic> json) => _$UpdateCheckExtensionRespFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$UpdateCheckExtensionRespToJson(this);
|
||||
}
|
||||
@@ -6,14 +6,9 @@ part of 'update_check_extension_resp.dart';
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
UpdateCheckExtensionResp _$UpdateCheckExtensionRespFromJson(
|
||||
Map<String, dynamic> json) =>
|
||||
UpdateCheckExtensionResp(
|
||||
newVersion: json['newVersion'] as String,
|
||||
);
|
||||
UpdateCheckExtensionResp _$UpdateCheckExtensionRespFromJson(Map<String, dynamic> json) =>
|
||||
UpdateCheckExtensionResp(newVersion: json['newVersion'] as String);
|
||||
|
||||
Map<String, dynamic> _$UpdateCheckExtensionRespToJson(
|
||||
UpdateCheckExtensionResp instance) =>
|
||||
<String, dynamic>{
|
||||
'newVersion': instance.newVersion,
|
||||
};
|
||||
Map<String, dynamic> _$UpdateCheckExtensionRespToJson(UpdateCheckExtensionResp instance) => <String, dynamic>{
|
||||
'newVersion': instance.newVersion,
|
||||
};
|
||||
@@ -6,11 +6,8 @@ part 'update_extension_settings.g.dart';
|
||||
class UpdateExtensionSettings {
|
||||
Map<String, dynamic> settings;
|
||||
|
||||
UpdateExtensionSettings({
|
||||
required this.settings,
|
||||
});
|
||||
UpdateExtensionSettings({required this.settings});
|
||||
|
||||
factory UpdateExtensionSettings.fromJson(Map<String, dynamic> json) =>
|
||||
_$UpdateExtensionSettingsFromJson(json);
|
||||
factory UpdateExtensionSettings.fromJson(Map<String, dynamic> json) => _$UpdateExtensionSettingsFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$UpdateExtensionSettingsToJson(this);
|
||||
}
|
||||
@@ -6,14 +6,9 @@ part of 'update_extension_settings.dart';
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
UpdateExtensionSettings _$UpdateExtensionSettingsFromJson(
|
||||
Map<String, dynamic> json) =>
|
||||
UpdateExtensionSettings(
|
||||
settings: json['settings'] as Map<String, dynamic>,
|
||||
);
|
||||
UpdateExtensionSettings _$UpdateExtensionSettingsFromJson(Map<String, dynamic> json) =>
|
||||
UpdateExtensionSettings(settings: json['settings'] as Map<String, dynamic>);
|
||||
|
||||
Map<String, dynamic> _$UpdateExtensionSettingsToJson(
|
||||
UpdateExtensionSettings instance) =>
|
||||
<String, dynamic>{
|
||||
'settings': instance.settings,
|
||||
};
|
||||
Map<String, dynamic> _$UpdateExtensionSettingsToJson(UpdateExtensionSettings instance) => <String, dynamic>{
|
||||
'settings': instance.settings,
|
||||
};
|
||||
@@ -0,0 +1,104 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
|
||||
|
||||
import '../core/window/app_window_frame.dart';
|
||||
import '../core/window/app_window_appearance.dart';
|
||||
import '../core/window/window_capability_transport.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../shared/theme/app_component_themes.dart';
|
||||
import '../shared/theme/app_theme.dart';
|
||||
import '../features/auth/application/web_auth_controller.dart';
|
||||
import 'application/app_appearance_controller.dart';
|
||||
import 'application/app_runtime_controller.dart';
|
||||
import 'rpc/webview_rpc_overlay.dart';
|
||||
import 'rpc/webview_rpc_service.dart';
|
||||
import 'router/app_router.dart';
|
||||
|
||||
class GopeedApp extends ConsumerStatefulWidget {
|
||||
const GopeedApp({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<GopeedApp> createState() => _GopeedAppState();
|
||||
}
|
||||
|
||||
class _GopeedAppState extends ConsumerState<GopeedApp> with WidgetsBindingObserver {
|
||||
late final GoRouter _router;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_router = AppRouter.build(ref.read(webAuthControllerProvider));
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_router.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangePlatformBrightness() {
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
ref.listen(appRuntimeControllerProvider, (_, next) {
|
||||
final runtime = next.value;
|
||||
if (runtime != null) {
|
||||
ref.read(appAppearanceControllerProvider.notifier).initialize(runtime.downloaderConfig.extra);
|
||||
}
|
||||
});
|
||||
final runtime = ref.watch(appRuntimeControllerProvider).value;
|
||||
if (runtime != null) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
ref.read(appAppearanceControllerProvider.notifier).initialize(runtime.downloaderConfig.extra);
|
||||
});
|
||||
}
|
||||
|
||||
final appearance = ref.watch(appAppearanceControllerProvider);
|
||||
final themeColor = appearance.themeColor;
|
||||
final isLightTheme = appearance.resolveIsLight(WidgetsBinding.instance.platformDispatcher.platformBrightness);
|
||||
final themeMode = switch (appearance.themeMode) {
|
||||
AppThemeMode.system => shad.ThemeMode.system,
|
||||
AppThemeMode.light => shad.ThemeMode.light,
|
||||
AppThemeMode.dark => shad.ThemeMode.dark,
|
||||
};
|
||||
AppWindowCapabilityHost.instance.updateAppearance(
|
||||
AppWindowAppearance(
|
||||
themeMode: appearance.themeMode.key,
|
||||
themeColor: appearance.themeColor.key,
|
||||
locale: runtime?.downloaderConfig.extra.locale ?? '',
|
||||
),
|
||||
);
|
||||
|
||||
return shad.ShadcnApp.router(
|
||||
debugShowCheckedModeBanner: false,
|
||||
onGenerateTitle: (context) => context.l10n.appTitle,
|
||||
theme: AppTheme.light(themeColor),
|
||||
darkTheme: AppTheme.dark(themeColor),
|
||||
materialTheme: isLightTheme ? AppTheme.materialLight(themeColor) : AppTheme.materialDark(themeColor),
|
||||
themeMode: themeMode,
|
||||
locale: supportedLocaleFromConfig(runtime?.downloaderConfig.extra.locale ?? ''),
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
builder: (context, child) {
|
||||
final content = AppComponentThemes(child: AppWindowFrame(child: child ?? const SizedBox.shrink()));
|
||||
if (!WebViewRpcService.instance.supported) {
|
||||
return content;
|
||||
}
|
||||
return Overlay(
|
||||
initialEntries: [
|
||||
OverlayEntry(builder: (_) => content),
|
||||
OverlayEntry(builder: (_) => const WebViewRpcOverlay()),
|
||||
],
|
||||
);
|
||||
},
|
||||
routerConfig: _router,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
|
||||
/// Keeps the Android process alive while Gopeed is available for downloads.
|
||||
class AndroidForegroundService {
|
||||
const AndroidForegroundService._();
|
||||
|
||||
static Future<void> ensureRunning(AppLocalizations l10n) async {
|
||||
if (!Platform.isAndroid) return;
|
||||
|
||||
FlutterForegroundTask.init(
|
||||
androidNotificationOptions: AndroidNotificationOptions(
|
||||
channelId: 'gopeed_service',
|
||||
channelName: l10n.androidForegroundServiceChannel,
|
||||
channelImportance: NotificationChannelImportance.LOW,
|
||||
showWhen: true,
|
||||
priority: NotificationPriority.LOW,
|
||||
),
|
||||
iosNotificationOptions: const IOSNotificationOptions(showNotification: false, playSound: false),
|
||||
foregroundTaskOptions: ForegroundTaskOptions(
|
||||
eventAction: ForegroundTaskEventAction.nothing(),
|
||||
autoRunOnBoot: true,
|
||||
allowWakeLock: true,
|
||||
allowWifiLock: true,
|
||||
),
|
||||
);
|
||||
|
||||
if (await FlutterForegroundTask.isRunningService) {
|
||||
_throwOnFailure(await FlutterForegroundTask.restartService());
|
||||
return;
|
||||
}
|
||||
|
||||
_throwOnFailure(
|
||||
await FlutterForegroundTask.startService(
|
||||
notificationTitle: l10n.androidForegroundNotificationTitle,
|
||||
notificationText: l10n.androidForegroundNotificationText,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
static void _throwOnFailure(ServiceRequestResult result) {
|
||||
if (result case ServiceRequestFailure(:final error)) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../api/model/downloader_config.dart';
|
||||
import '../../shared/theme/app_theme_color.dart';
|
||||
|
||||
enum AppThemeMode {
|
||||
system('system'),
|
||||
light('light'),
|
||||
dark('dark');
|
||||
|
||||
const AppThemeMode(this.key);
|
||||
|
||||
final String key;
|
||||
|
||||
static AppThemeMode fromKey(String? key) {
|
||||
return values.where((mode) => mode.key == key).firstOrNull ?? AppThemeMode.system;
|
||||
}
|
||||
}
|
||||
|
||||
class AppAppearanceState {
|
||||
const AppAppearanceState({this.themeMode = AppThemeMode.system, this.themeColor = AppThemeColor.green});
|
||||
|
||||
final AppThemeMode themeMode;
|
||||
final AppThemeColor themeColor;
|
||||
|
||||
bool resolveIsLight(Brightness systemBrightness) {
|
||||
return switch (themeMode) {
|
||||
AppThemeMode.system => systemBrightness == Brightness.light,
|
||||
AppThemeMode.light => true,
|
||||
AppThemeMode.dark => false,
|
||||
};
|
||||
}
|
||||
|
||||
AppAppearanceState copyWith({AppThemeMode? themeMode, AppThemeColor? themeColor}) {
|
||||
return AppAppearanceState(themeMode: themeMode ?? this.themeMode, themeColor: themeColor ?? this.themeColor);
|
||||
}
|
||||
}
|
||||
|
||||
final appAppearanceControllerProvider = NotifierProvider<AppAppearanceController, AppAppearanceState>(
|
||||
AppAppearanceController.new,
|
||||
);
|
||||
|
||||
class AppAppearanceController extends Notifier<AppAppearanceState> {
|
||||
bool _initialized = false;
|
||||
|
||||
@override
|
||||
AppAppearanceState build() => const AppAppearanceState();
|
||||
|
||||
void initialize(ExtraConfig config) {
|
||||
if (_initialized) return;
|
||||
_initialized = true;
|
||||
state = AppAppearanceState(
|
||||
themeMode: AppThemeMode.fromKey(config.themeMode),
|
||||
themeColor: AppThemeColor.fromKey(config.themeColor),
|
||||
);
|
||||
}
|
||||
|
||||
void setThemeMode(AppThemeMode mode) {
|
||||
_initialized = true;
|
||||
state = state.copyWith(themeMode: mode);
|
||||
}
|
||||
|
||||
void setThemeColor(AppThemeColor color) {
|
||||
_initialized = true;
|
||||
state = state.copyWith(themeColor: color);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:app_links/app_links.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:share_handler/share_handler.dart';
|
||||
import 'package:window_manager/window_manager.dart';
|
||||
|
||||
import '../../api/model/create_task.dart';
|
||||
import '../../api/model/install_extension.dart';
|
||||
import '../../api/model/request.dart';
|
||||
import '../../core/entry/app_startup_options.dart';
|
||||
import '../../core/utils/content_uri_resolver.dart';
|
||||
import '../../core/window/app_window_launcher.dart';
|
||||
import '../../features/extensions/application/pending_extension_install.dart';
|
||||
import '../../features/tasks/application/pending_create_task.dart';
|
||||
import '../../util/util.dart';
|
||||
import '../router/app_router.dart';
|
||||
import 'app_runtime_controller.dart';
|
||||
|
||||
final appDeepLinkControllerProvider = AsyncNotifierProvider<AppDeepLinkController, AppDeepLinkState>(
|
||||
AppDeepLinkController.new,
|
||||
);
|
||||
|
||||
class AppDeepLinkState {
|
||||
const AppDeepLinkState({this.started = false});
|
||||
|
||||
final bool started;
|
||||
}
|
||||
|
||||
class AppDeepLinkController extends AsyncNotifier<AppDeepLinkState> {
|
||||
StreamSubscription<Uri>? _subscription;
|
||||
StreamSubscription<SharedMedia>? _sharedMediaSubscription;
|
||||
bool _started = false;
|
||||
|
||||
@override
|
||||
Future<AppDeepLinkState> build() async {
|
||||
final runtime = ref.watch(appRuntimeControllerProvider).value;
|
||||
if (runtime == null || _started || kIsWeb) {
|
||||
return AppDeepLinkState(started: _started);
|
||||
}
|
||||
_started = true;
|
||||
final appLinks = AppLinks();
|
||||
_subscription = appLinks.uriLinkStream.listen((uri) {
|
||||
unawaited(_handleUri(uri));
|
||||
});
|
||||
if (Util.isMobile()) {
|
||||
final shareHandler = ShareHandlerPlatform.instance;
|
||||
_sharedMediaSubscription = shareHandler.sharedMediaStream.listen((media) {
|
||||
unawaited(_handleSharedMedia(media, ignoreContentUri: true));
|
||||
});
|
||||
try {
|
||||
final media = await shareHandler.getInitialSharedMedia();
|
||||
if (media != null) {
|
||||
await _handleSharedMedia(media);
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
ref.onDispose(() {
|
||||
_subscription?.cancel();
|
||||
_sharedMediaSubscription?.cancel();
|
||||
});
|
||||
try {
|
||||
final initial = await appLinks.getInitialLink();
|
||||
if (initial != null) {
|
||||
await _handleUri(initial);
|
||||
}
|
||||
} catch (_) {}
|
||||
return const AppDeepLinkState(started: true);
|
||||
}
|
||||
|
||||
Future<void> _handleSharedMedia(SharedMedia media, {bool ignoreContentUri = false}) async {
|
||||
final uri = sharedMediaUri(media);
|
||||
if (uri == null || (ignoreContentUri && uri.scheme == 'content')) return;
|
||||
await _handleUri(uri);
|
||||
}
|
||||
|
||||
Future<void> _handleUri(Uri uri) async {
|
||||
if (uri.scheme == 'gopeed') {
|
||||
await _handleGopeedUri(uri);
|
||||
return;
|
||||
}
|
||||
final createTask = CreateTask(req: Request(url: await _uriToTaskUrl(uri)));
|
||||
await _openCreate(createTask);
|
||||
}
|
||||
|
||||
Future<void> _handleGopeedUri(Uri uri) async {
|
||||
if (isSilentGopeedWakeUri(uri)) {
|
||||
return;
|
||||
}
|
||||
final route = gopeedDeepLinkRoute(uri);
|
||||
if (route == '/create') {
|
||||
final params = uri.queryParameters['params'];
|
||||
if (params?.isNotEmpty == true) {
|
||||
await _openCreate(CreateTask.fromJson(_decodeParams(params!)));
|
||||
return;
|
||||
}
|
||||
await _openCreate(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (route == '/extension') {
|
||||
final params = uri.queryParameters['params'];
|
||||
if (params?.isNotEmpty == true) {
|
||||
ref.read(pendingExtensionInstallProvider.notifier).set(InstallExtension.fromJson(_decodeParams(params!)));
|
||||
}
|
||||
await _go('/extensions');
|
||||
return;
|
||||
}
|
||||
|
||||
await _go('/');
|
||||
}
|
||||
|
||||
Future<void> _openCreate(CreateTask? createTask) async {
|
||||
if (Util.isDesktop()) {
|
||||
final opened = await AppWindowLauncher.openCreateTaskWindow(createTask: createTask);
|
||||
if (!opened) {
|
||||
ref.read(pendingCreateTaskProvider.notifier).set(createTask);
|
||||
await _go('/create');
|
||||
}
|
||||
return;
|
||||
}
|
||||
ref.read(pendingCreateTaskProvider.notifier).set(createTask);
|
||||
await _go('/create');
|
||||
}
|
||||
|
||||
Future<void> _go(String route) async {
|
||||
if (Util.isDesktop()) {
|
||||
await windowManager.show();
|
||||
await windowManager.focus();
|
||||
}
|
||||
final context = AppRouter.rootNavigatorKey.currentContext;
|
||||
if (context != null && context.mounted) {
|
||||
context.go(route);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> _decodeParams(String params) {
|
||||
final safeParams = params.replaceAll('"', '').replaceAll(' ', '+');
|
||||
final paramsJson = String.fromCharCodes(base64Decode(base64.normalize(safeParams)));
|
||||
return jsonDecode(paramsJson) as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
Future<String> _uriToTaskUrl(Uri uri) async {
|
||||
if (uri.scheme == 'magnet' || uri.scheme == 'http' || uri.scheme == 'https') {
|
||||
return uri.toString();
|
||||
}
|
||||
if (uri.scheme == 'file') {
|
||||
return Util.isWindows() ? Uri.decodeFull(uri.path.substring(1)) : uri.path;
|
||||
}
|
||||
if (uri.scheme == 'content' && Util.isAndroid()) {
|
||||
return ContentUriResolver.copyToCache(uri);
|
||||
}
|
||||
throw ArgumentError.value(uri, 'uri', 'Unsupported task URI scheme');
|
||||
}
|
||||
}
|
||||
|
||||
/// Picks the actionable URI from content received through the platform share UI.
|
||||
///
|
||||
/// File attachments take precedence over an optional text caption. Both the
|
||||
/// Android and iOS share-handler implementations expose attachments as local
|
||||
/// paths that are ready for the app to read.
|
||||
Uri? sharedMediaUri(SharedMedia media) {
|
||||
final attachments = media.attachments;
|
||||
if (attachments != null) {
|
||||
for (final attachment in attachments) {
|
||||
final path = attachment?.path.trim();
|
||||
if (path != null && path.isNotEmpty) return Uri.file(path);
|
||||
}
|
||||
}
|
||||
|
||||
final content = media.content?.trim();
|
||||
if (content == null || content.isEmpty) return null;
|
||||
return Uri.tryParse(content);
|
||||
}
|
||||
|
||||
/// Gopeed's established links use `gopeed:///create`, where the action is the
|
||||
/// URI path. Do not interpret the URI host as an action: the host-style
|
||||
/// `gopeed://create` form is intentionally unsupported.
|
||||
String gopeedDeepLinkRoute(Uri uri) {
|
||||
return uri.path;
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import '../../api/model/task.dart';
|
||||
import '../../core/capabilities/app_capabilities.dart';
|
||||
import '../../l10n/l10n.dart';
|
||||
import '../../util/util.dart';
|
||||
import 'app_runtime_controller.dart';
|
||||
|
||||
final appNotificationControllerProvider = AsyncNotifierProvider<AppNotificationController, AppNotificationState>(
|
||||
AppNotificationController.new,
|
||||
);
|
||||
|
||||
class AppNotificationState {
|
||||
const AppNotificationState({this.started = false});
|
||||
|
||||
final bool started;
|
||||
}
|
||||
|
||||
class AppNotificationController extends AsyncNotifier<AppNotificationState> {
|
||||
final FlutterLocalNotificationsPlugin _plugin = FlutterLocalNotificationsPlugin();
|
||||
final Map<String, Status> _previousStatus = {};
|
||||
Timer? _timer;
|
||||
var _notificationId = 0;
|
||||
|
||||
@override
|
||||
Future<AppNotificationState> build() async {
|
||||
final runtime = ref.watch(appRuntimeControllerProvider).value;
|
||||
if (runtime == null || kIsWeb || !Util.isDesktop()) {
|
||||
return const AppNotificationState();
|
||||
}
|
||||
await _initNotifications(appLocalizationsFor(runtime.downloaderConfig.extra.locale));
|
||||
_startPolling();
|
||||
ref.onDispose(() {
|
||||
_timer?.cancel();
|
||||
});
|
||||
return const AppNotificationState(started: true);
|
||||
}
|
||||
|
||||
Future<void> _initNotifications(AppLocalizations locale) async {
|
||||
const darwin = DarwinInitializationSettings(
|
||||
requestAlertPermission: false,
|
||||
requestBadgePermission: false,
|
||||
requestSoundPermission: false,
|
||||
);
|
||||
final linux = LinuxInitializationSettings(
|
||||
defaultActionName: locale.open,
|
||||
defaultIcon: AssetsLinuxIcon('assets/icon/icon.png'),
|
||||
);
|
||||
|
||||
String? windowsIconPath;
|
||||
try {
|
||||
if (Util.isWindows()) {
|
||||
final byteData = await rootBundle.load('assets/icon/icon.ico');
|
||||
final tempDir = await getTemporaryDirectory();
|
||||
final file = File('${tempDir.path}/notification_icon.ico');
|
||||
await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
|
||||
windowsIconPath = file.path;
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
final windows = WindowsInitializationSettings(
|
||||
appName: 'Gopeed',
|
||||
appUserModelId: 'com.gopeed.gopeed',
|
||||
guid: '3c1bf3f4-3d91-4eaa-a33f-8705e71cf1ce',
|
||||
iconPath: windowsIconPath,
|
||||
);
|
||||
|
||||
await _plugin.initialize(
|
||||
settings: InitializationSettings(macOS: darwin, linux: linux, windows: windows),
|
||||
);
|
||||
}
|
||||
|
||||
void _startPolling() {
|
||||
_timer?.cancel();
|
||||
_timer = Timer.periodic(const Duration(seconds: 2), (_) async {
|
||||
try {
|
||||
final runtime = ref.read(appRuntimeControllerProvider).value;
|
||||
if (runtime?.downloaderConfig.extra.desktopNotification == false) {
|
||||
return;
|
||||
}
|
||||
final tasks = await ref.read(gopeedServiceProvider).getTasks(Status.values);
|
||||
final locale = appLocalizationsFor(runtime?.downloaderConfig.extra.locale ?? '');
|
||||
for (final task in tasks) {
|
||||
final previous = _previousStatus[task.id];
|
||||
if (previous != null && previous != task.status) {
|
||||
if (task.status == Status.done) {
|
||||
await _showNotification(title: locale.notificationTaskDone, body: task.name);
|
||||
} else if (task.status == Status.error) {
|
||||
await _showNotification(title: locale.notificationTaskError, body: task.name);
|
||||
}
|
||||
}
|
||||
_previousStatus[task.id] = task.status;
|
||||
}
|
||||
final currentIds = tasks.map((task) => task.id).toSet();
|
||||
_previousStatus.removeWhere((id, _) => !currentIds.contains(id));
|
||||
} catch (_) {}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _showNotification({required String title, required String body}) async {
|
||||
const details = NotificationDetails(
|
||||
macOS: DarwinNotificationDetails(),
|
||||
linux: LinuxNotificationDetails(),
|
||||
windows: WindowsNotificationDetails(),
|
||||
);
|
||||
await _plugin.show(id: _notificationId++, title: title, body: body, notificationDetails: details);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:launch_at_startup/launch_at_startup.dart';
|
||||
import 'package:tray_manager/tray_manager.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import 'package:window_manager/window_manager.dart';
|
||||
|
||||
import '../../api/api.dart' as api;
|
||||
import '../../api/model/downloader_config.dart';
|
||||
import '../../core/libgopeed_boot.dart';
|
||||
import '../../core/capabilities/app_capabilities.dart';
|
||||
import '../../core/window/app_window_launcher.dart';
|
||||
import '../../core/window/window_capability_transport.dart';
|
||||
import '../../database/database.dart';
|
||||
import '../../database/entity.dart';
|
||||
import '../../features/tasks/application/pending_create_task.dart';
|
||||
import '../../features/tasks/application/pending_update_task.dart';
|
||||
import '../../l10n/l10n.dart';
|
||||
import '../../util/package_info.dart';
|
||||
import '../../util/updater.dart';
|
||||
import '../../util/util.dart';
|
||||
import '../../util/browser_extension_host/browser_extension_host.dart';
|
||||
import '../../util/log_util.dart';
|
||||
import '../../util/scheme_register/scheme_register.dart';
|
||||
import '../rpc/host_rpc_service.dart';
|
||||
import '../router/app_router.dart';
|
||||
import 'app_runtime_controller.dart';
|
||||
|
||||
final appPlatformControllerProvider = AsyncNotifierProvider<AppPlatformController, AppPlatformState>(
|
||||
AppPlatformController.new,
|
||||
);
|
||||
|
||||
class AppPlatformState {
|
||||
const AppPlatformState({
|
||||
this.started = false,
|
||||
this.launchAtStartup = false,
|
||||
this.runAsMenubarApp = false,
|
||||
this.updateStatus = AppUpdateStatus.idle,
|
||||
this.latestVersion,
|
||||
this.updateError,
|
||||
});
|
||||
|
||||
final bool started;
|
||||
final bool launchAtStartup;
|
||||
final bool runAsMenubarApp;
|
||||
final AppUpdateStatus updateStatus;
|
||||
final VersionInfo? latestVersion;
|
||||
final String? updateError;
|
||||
}
|
||||
|
||||
enum AppUpdateStatus { idle, checking, upToDate, available, failed }
|
||||
|
||||
class AppPlatformController extends AsyncNotifier<AppPlatformState> with WindowListener, TrayListener {
|
||||
bool _started = false;
|
||||
String? _trayLocaleConfig;
|
||||
bool _updateInitialized = false;
|
||||
bool _launchAtStartup = false;
|
||||
bool _runAsMenubarApp = false;
|
||||
AppUpdateStatus _updateStatus = AppUpdateStatus.idle;
|
||||
VersionInfo? _latestVersion;
|
||||
String? _updateError;
|
||||
Future<VersionInfo?>? _checkUpdateFuture;
|
||||
final _windowsResizeSave = Util.debounce(() async {
|
||||
final size = await windowManager.getSize();
|
||||
Database.instance.saveWindowState(WindowStateEntity(width: size.width, height: size.height));
|
||||
}, 500);
|
||||
|
||||
@override
|
||||
Future<AppPlatformState> build() async {
|
||||
final runtime = ref.watch(appRuntimeControllerProvider).value;
|
||||
if (runtime == null || kIsWeb) {
|
||||
return _snapshot();
|
||||
}
|
||||
if (!Util.isDesktop()) {
|
||||
_scheduleInitialUpdateCheck();
|
||||
return _snapshot();
|
||||
}
|
||||
if (_started) {
|
||||
final localeConfig = runtime.downloaderConfig.extra.locale;
|
||||
if (_trayLocaleConfig != localeConfig) await _initTray();
|
||||
return _snapshot();
|
||||
}
|
||||
await _start();
|
||||
_scheduleInitialUpdateCheck();
|
||||
ref.onDispose(() {
|
||||
windowManager.removeListener(this);
|
||||
trayManager.removeListener(this);
|
||||
unawaited(HostRpcService.instance.stop());
|
||||
unawaited(AppWindowCapabilityHost.instance.stop());
|
||||
});
|
||||
return _snapshot();
|
||||
}
|
||||
|
||||
void _scheduleInitialUpdateCheck() {
|
||||
if (_updateInitialized) return;
|
||||
_updateInitialized = true;
|
||||
Timer.run(() => unawaited(_initCheckUpdate()));
|
||||
}
|
||||
|
||||
Future<void> _start() async {
|
||||
_started = true;
|
||||
await AppWindowCapabilityHost.instance.start(LocalAppCapabilities.instance.registry);
|
||||
windowManager.addListener(this);
|
||||
await windowManager.setPreventClose(true);
|
||||
if (Util.isMacos()) {
|
||||
_runAsMenubarApp = Database.instance.getRunAsMenubarApp();
|
||||
await windowManager.setSkipTaskbar(_runAsMenubarApp);
|
||||
}
|
||||
await _initTray();
|
||||
await _initHostRpc();
|
||||
unawaited(_initDesktopIntegrations());
|
||||
await _initLaunchAtStartup();
|
||||
}
|
||||
|
||||
Future<void> _initTray() async {
|
||||
final localeConfig = ref.read(appRuntimeControllerProvider).value?.downloaderConfig.extra.locale ?? '';
|
||||
final locale = appLocalizationsFor(localeConfig);
|
||||
if (Util.isWindows()) {
|
||||
await trayManager.setIcon('assets/tray_icon/icon.ico');
|
||||
} else if (Util.isMacos()) {
|
||||
await trayManager.setIcon('assets/tray_icon/icon_mac.png', isTemplate: true);
|
||||
} else if (Platform.environment.containsKey('FLATPAK_ID') || Platform.environment.containsKey('SNAP')) {
|
||||
await trayManager.setIcon('com.gopeed.Gopeed');
|
||||
} else {
|
||||
await trayManager.setIcon('assets/tray_icon/icon.png');
|
||||
}
|
||||
|
||||
final version = _safeVersionLabel(locale.version);
|
||||
final menu = Menu(
|
||||
items: [
|
||||
MenuItem(label: locale.show, onClick: (_) => _showMainWindow()),
|
||||
MenuItem.separator(),
|
||||
MenuItem(label: locale.create, onClick: (_) => _openCreateTask()),
|
||||
MenuItem(
|
||||
label: locale.startAll,
|
||||
onClick: (_) => unawaited(ref.read(gopeedServiceProvider).continueAllTasks(null)),
|
||||
),
|
||||
MenuItem(
|
||||
label: locale.pauseAll,
|
||||
onClick: (_) => unawaited(ref.read(gopeedServiceProvider).pauseAllTasks(null)),
|
||||
),
|
||||
MenuItem(label: locale.setting, onClick: (_) => _go('/settings')),
|
||||
MenuItem.separator(),
|
||||
MenuItem(
|
||||
label: locale.donate,
|
||||
onClick: (_) => unawaited(launchUrl(Uri.parse('https://gopeed.com/docs/donate'))),
|
||||
),
|
||||
MenuItem(label: version),
|
||||
MenuItem.separator(),
|
||||
MenuItem(label: locale.exit, onClick: (_) => _exit()),
|
||||
],
|
||||
);
|
||||
|
||||
if (!Util.isLinux()) {
|
||||
await trayManager.setToolTip('Gopeed');
|
||||
}
|
||||
await trayManager.setContextMenu(menu);
|
||||
trayManager.removeListener(this);
|
||||
trayManager.addListener(this);
|
||||
_trayLocaleConfig = localeConfig;
|
||||
}
|
||||
|
||||
Future<void> _initHostRpc() async {
|
||||
await HostRpcService.instance.start(
|
||||
onCreate: (createTask, silent) async {
|
||||
final pendingUpdate = ref.read(pendingUpdateTaskProvider);
|
||||
if (pendingUpdate != null && createTask.req != null) {
|
||||
ref
|
||||
.read(pendingUpdateRequestProvider.notifier)
|
||||
.set(PendingUpdateRequest(task: pendingUpdate, createTask: createTask));
|
||||
await _showMainWindow();
|
||||
return;
|
||||
}
|
||||
if (silent) {
|
||||
await ref.read(gopeedServiceProvider).createTask(createTask);
|
||||
return;
|
||||
}
|
||||
final opened = await AppWindowLauncher.openCreateTaskWindow(createTask: createTask);
|
||||
if (!opened) {
|
||||
ref.read(pendingCreateTaskProvider.notifier).set(createTask);
|
||||
await _go('/create');
|
||||
}
|
||||
},
|
||||
onForward: ({required path, required method, data, query}) {
|
||||
return api.forward(path, method: method, data: data, queryParameters: query);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _initDesktopIntegrations() async {
|
||||
try {
|
||||
registerUrlScheme('gopeed');
|
||||
final runtime = ref.read(appRuntimeControllerProvider).value;
|
||||
if (runtime?.downloaderConfig.extra.defaultBtClient == true) {
|
||||
registerDefaultTorrentClient();
|
||||
}
|
||||
} catch (error, stackTrace) {
|
||||
logger.w('register scheme failed', error, stackTrace);
|
||||
}
|
||||
|
||||
try {
|
||||
await installHost();
|
||||
for (final browser in Browser.values) {
|
||||
await installManifest(browser);
|
||||
}
|
||||
} catch (error, stackTrace) {
|
||||
logger.w('browser extension host integration failed', error, stackTrace);
|
||||
}
|
||||
|
||||
try {
|
||||
await installUpdater();
|
||||
} catch (error, stackTrace) {
|
||||
// Native helper assets are generated by release builds, so their absence
|
||||
// in a source/debug bundle must not prevent the app from starting.
|
||||
logger.w('updater integration failed', error, stackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _initLaunchAtStartup() async {
|
||||
if (!Util.isWindows() && !Util.isLinux()) {
|
||||
return;
|
||||
}
|
||||
launchAtStartup.setup(appName: packageInfo.appName, appPath: Platform.resolvedExecutable, args: const ['--hidden']);
|
||||
_launchAtStartup = await launchAtStartup.isEnabled();
|
||||
}
|
||||
|
||||
Future<void> setLaunchAtStartup(bool enabled) async {
|
||||
if (!Util.isWindows() && !Util.isLinux()) {
|
||||
return;
|
||||
}
|
||||
if (enabled) {
|
||||
await launchAtStartup.enable();
|
||||
} else {
|
||||
await launchAtStartup.disable();
|
||||
}
|
||||
_launchAtStartup = enabled;
|
||||
_emit();
|
||||
}
|
||||
|
||||
Future<void> setRunAsMenubarApp(bool enabled) async {
|
||||
if (!Util.isMacos()) {
|
||||
return;
|
||||
}
|
||||
Database.instance.saveRunAsMenubarApp(enabled);
|
||||
_runAsMenubarApp = enabled;
|
||||
await windowManager.setSkipTaskbar(enabled);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||||
await _showMainWindow();
|
||||
_emit();
|
||||
}
|
||||
|
||||
Future<void> _initCheckUpdate() async {
|
||||
final runtime = ref.read(appRuntimeControllerProvider).value;
|
||||
if (runtime?.downloaderConfig.extra.notifyWhenNewVersion == false) return;
|
||||
await checkForUpdate();
|
||||
}
|
||||
|
||||
Future<VersionInfo?> checkForUpdate() {
|
||||
return _checkUpdateFuture ??= _performUpdateCheck().whenComplete(() => _checkUpdateFuture = null);
|
||||
}
|
||||
|
||||
Future<VersionInfo?> _performUpdateCheck() async {
|
||||
_updateStatus = AppUpdateStatus.checking;
|
||||
_updateError = null;
|
||||
_emit();
|
||||
try {
|
||||
_latestVersion = await checkUpdate();
|
||||
_updateStatus = _latestVersion == null ? AppUpdateStatus.upToDate : AppUpdateStatus.available;
|
||||
_emit();
|
||||
return _latestVersion;
|
||||
} catch (error, stackTrace) {
|
||||
_latestVersion = null;
|
||||
_updateStatus = AppUpdateStatus.failed;
|
||||
_updateError = error.toString();
|
||||
_emit();
|
||||
logger.w('check update failed', error, stackTrace);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> startUpdate(VersionInfo versionInfo, UpdateProgressCallback onProgress) async {
|
||||
final runtime = ref.read(appRuntimeControllerProvider).value;
|
||||
await updateApp(
|
||||
versionInfo,
|
||||
githubMirror: runtime?.downloaderConfig.extra.githubMirror ?? ExtraConfigGithubMirror(enabled: false),
|
||||
onProgress: onProgress,
|
||||
);
|
||||
}
|
||||
|
||||
AppPlatformState _snapshot() => AppPlatformState(
|
||||
started: _started,
|
||||
launchAtStartup: _launchAtStartup,
|
||||
runAsMenubarApp: _runAsMenubarApp,
|
||||
updateStatus: _updateStatus,
|
||||
latestVersion: _latestVersion,
|
||||
updateError: _updateError,
|
||||
);
|
||||
|
||||
void _emit() {
|
||||
state = AsyncValue.data(_snapshot());
|
||||
}
|
||||
|
||||
String _safeVersionLabel(String label) {
|
||||
try {
|
||||
return '$label($appVersion)';
|
||||
} catch (_) {
|
||||
return label;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showMainWindow() async {
|
||||
await windowManager.show();
|
||||
await windowManager.focus();
|
||||
}
|
||||
|
||||
Future<void> _openCreateTask() async {
|
||||
await _showMainWindow();
|
||||
final opened = await AppWindowLauncher.openCreateTaskWindow();
|
||||
if (!opened) {
|
||||
_go('/create');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _go(String route) async {
|
||||
final context = AppRouter.rootNavigatorKey.currentContext;
|
||||
await _showMainWindow();
|
||||
if (context != null && context.mounted) {
|
||||
context.go(route);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _exit() async {
|
||||
try {
|
||||
await HostRpcService.instance.stop();
|
||||
await AppWindowCapabilityHost.instance.stop();
|
||||
await LibgopeedBoot.instance.stop();
|
||||
} catch (_) {}
|
||||
await windowManager.destroy();
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowClose() async {
|
||||
final isPreventClose = await windowManager.isPreventClose();
|
||||
if (isPreventClose) {
|
||||
await windowManager.hide();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowFocus() {
|
||||
if (Util.isMacos() && _runAsMenubarApp) {
|
||||
unawaited(windowManager.setSkipTaskbar(true));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onTrayIconMouseDown() {
|
||||
unawaited(_showMainWindow());
|
||||
}
|
||||
|
||||
@override
|
||||
void onTrayIconRightMouseDown() {
|
||||
trayManager.popUpContextMenu();
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowMaximize() {
|
||||
Database.instance.saveWindowState(WindowStateEntity(isMaximized: true));
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowUnmaximize() {
|
||||
Database.instance.saveWindowState(WindowStateEntity(isMaximized: false));
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowResize() {
|
||||
_windowsResizeSave();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import '../../api/api.dart' as api;
|
||||
import '../../api/model/downloader_config.dart';
|
||||
import '../../core/capabilities/app_capabilities.dart';
|
||||
import '../../core/common/start_config.dart';
|
||||
import '../../core/entry/app_initializer.dart';
|
||||
import '../../core/libgopeed_boot.dart';
|
||||
import '../../database/database.dart';
|
||||
import '../../database/entity.dart';
|
||||
import '../../features/auth/application/web_auth_controller.dart';
|
||||
import '../../l10n/l10n.dart';
|
||||
import '../../util/log_util.dart';
|
||||
import '../../util/package_info.dart';
|
||||
import '../../util/util.dart';
|
||||
import '../rpc/webview_rpc_service.dart';
|
||||
import 'android_foreground_service.dart';
|
||||
import 'location_keep_alive.dart';
|
||||
|
||||
const unixSocketPath = 'gopeed.sock';
|
||||
|
||||
final appRuntimeControllerProvider = AsyncNotifierProvider<AppRuntimeController, AppRuntimeState>(
|
||||
AppRuntimeController.new,
|
||||
);
|
||||
|
||||
class AppRuntimeState {
|
||||
const AppRuntimeState({
|
||||
required this.startConfig,
|
||||
required this.runningPort,
|
||||
required this.downloaderConfig,
|
||||
this.localBackendStarted = false,
|
||||
this.startupError,
|
||||
});
|
||||
|
||||
final StartConfig startConfig;
|
||||
final int runningPort;
|
||||
final DownloaderConfig downloaderConfig;
|
||||
final bool localBackendStarted;
|
||||
final Object? startupError;
|
||||
|
||||
String runningAddress() {
|
||||
if (startConfig.network == 'unix') {
|
||||
return startConfig.address;
|
||||
}
|
||||
return '${startConfig.address.split(':').first}:$runningPort';
|
||||
}
|
||||
}
|
||||
|
||||
class AppRuntimeController extends AsyncNotifier<AppRuntimeState> {
|
||||
static StartConfig? _defaultStartConfig;
|
||||
|
||||
@override
|
||||
Future<AppRuntimeState> build() async {
|
||||
ref.onDispose(() => unawaited(WebViewRpcService.instance.stop()));
|
||||
return _init();
|
||||
}
|
||||
|
||||
Future<void> reloadConfig() async {
|
||||
final current = state.value;
|
||||
if (current == null) return;
|
||||
state = AsyncValue.data(
|
||||
AppRuntimeState(
|
||||
startConfig: current.startConfig,
|
||||
runningPort: current.runningPort,
|
||||
downloaderConfig: await ref.read(gopeedServiceProvider).getConfig(),
|
||||
localBackendStarted: current.localBackendStarted,
|
||||
startupError: current.startupError,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void replaceDownloaderConfig(DownloaderConfig config) {
|
||||
final current = state.value;
|
||||
if (current == null) return;
|
||||
state = AsyncValue.data(
|
||||
AppRuntimeState(
|
||||
startConfig: current.startConfig,
|
||||
runningPort: current.runningPort,
|
||||
downloaderConfig: DownloaderConfig.fromJson(config.toJson()),
|
||||
localBackendStarted: current.localBackendStarted,
|
||||
startupError: current.startupError,
|
||||
),
|
||||
);
|
||||
unawaited(LocationKeepAliveCoordinator.instance.reconcile(enabled: config.extra.backgroundLocationKeepAlive));
|
||||
}
|
||||
|
||||
Future<AppRuntimeState> _init() async {
|
||||
await AppInitializer.ensureDatabaseInitialized();
|
||||
try {
|
||||
await initPackageInfo();
|
||||
} catch (_) {}
|
||||
initLogger();
|
||||
|
||||
final startConfig = await _loadStartConfig();
|
||||
try {
|
||||
startConfig.webViewRpcConfig = await WebViewRpcService.instance.start();
|
||||
} catch (error, stackTrace) {
|
||||
logger.w('webview RPC initialization failed', error, stackTrace);
|
||||
}
|
||||
Object? startupError;
|
||||
var runningPort = 0;
|
||||
var localBackendStarted = false;
|
||||
try {
|
||||
// Go's rest.Start is already idempotent: when its server is running it
|
||||
// returns the existing port before rebuilding or touching the Unix
|
||||
// socket. This is also what keeps Riverpod hot reload safe.
|
||||
runningPort = await LibgopeedBoot.instance.start(startConfig);
|
||||
localBackendStarted = true;
|
||||
} catch (error, stackTrace) {
|
||||
startupError = error;
|
||||
logger.w('libgopeed init failed, falling back to external API', error, stackTrace);
|
||||
if (startConfig.network == 'unix') {
|
||||
startConfig.network = 'tcp';
|
||||
startConfig.address = '127.0.0.1:9999';
|
||||
}
|
||||
runningPort = int.tryParse(startConfig.address.split(':').last) ?? 9999;
|
||||
}
|
||||
|
||||
api.init(
|
||||
startConfig.network,
|
||||
_runningAddress(startConfig, runningPort),
|
||||
startConfig.apiToken,
|
||||
onUnauthorized: ref.read(webAuthControllerProvider).requireLogin,
|
||||
);
|
||||
|
||||
final config = await _loadDownloaderConfig();
|
||||
unawaited(_initTrackerUpdate(config));
|
||||
unawaited(_initAndroidForegroundService(appLocalizationsFor(config.extra.locale)));
|
||||
|
||||
final result = AppRuntimeState(
|
||||
startConfig: startConfig,
|
||||
runningPort: runningPort,
|
||||
downloaderConfig: config,
|
||||
localBackendStarted: localBackendStarted,
|
||||
startupError: startupError,
|
||||
);
|
||||
if (Util.isIOS()) {
|
||||
LocationKeepAliveCoordinator.instance.start(
|
||||
() =>
|
||||
state.value?.downloaderConfig.extra.backgroundLocationKeepAlive ?? config.extra.backgroundLocationKeepAlive,
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<void> _initAndroidForegroundService(AppLocalizations l10n) async {
|
||||
try {
|
||||
await AndroidForegroundService.ensureRunning(l10n);
|
||||
} catch (error, stackTrace) {
|
||||
logger.w('Android foreground service initialization failed', error, stackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
Future<StartConfig> _loadStartConfig() async {
|
||||
final defaultCfg = await _initDefaultStartConfig();
|
||||
final saved = Database.instance.getStartConfig();
|
||||
final cfg = StartConfig()
|
||||
..network = saved?.network ?? defaultCfg.network
|
||||
..address = saved?.address ?? defaultCfg.address
|
||||
..apiToken = saved?.apiToken ?? defaultCfg.apiToken
|
||||
..storage = defaultCfg.storage
|
||||
..storageDir = defaultCfg.storageDir
|
||||
..refreshInterval = defaultCfg.refreshInterval;
|
||||
return cfg;
|
||||
}
|
||||
|
||||
Future<StartConfig> _initDefaultStartConfig() async {
|
||||
if (_defaultStartConfig != null) {
|
||||
return _defaultStartConfig!;
|
||||
}
|
||||
final cfg = StartConfig()
|
||||
..storage = 'bolt'
|
||||
..storageDir = Util.getStorageDir()
|
||||
..refreshInterval = 0
|
||||
..apiToken = '';
|
||||
if (!Util.supportUnixSocket()) {
|
||||
cfg
|
||||
..network = 'tcp'
|
||||
..address = '127.0.0.1:0';
|
||||
} else {
|
||||
cfg
|
||||
..network = 'unix'
|
||||
..address = '${(await getTemporaryDirectory()).path}/$unixSocketPath';
|
||||
}
|
||||
_defaultStartConfig = cfg;
|
||||
return cfg;
|
||||
}
|
||||
|
||||
Future<DownloaderConfig> _loadDownloaderConfig() async {
|
||||
DownloaderConfig config;
|
||||
try {
|
||||
config = await ref.read(gopeedServiceProvider).getConfig();
|
||||
} catch (error, stackTrace) {
|
||||
logger.w('load downloader config failed', error, stackTrace);
|
||||
config = DownloaderConfig();
|
||||
}
|
||||
await _initDownloaderConfig(config);
|
||||
return config;
|
||||
}
|
||||
|
||||
Future<void> _initDownloaderConfig(DownloaderConfig config) async {
|
||||
final extra = config.extra;
|
||||
if (extra.themeMode.isEmpty) {
|
||||
extra.themeMode = 'system';
|
||||
}
|
||||
if (extra.themeColor.isEmpty) {
|
||||
extra.themeColor = 'green';
|
||||
}
|
||||
if (extra.bt.trackerSubscribeUrls.isEmpty) {
|
||||
extra.bt.trackerSubscribeUrls.addAll(allTrackerSubscribeUrls);
|
||||
}
|
||||
if (config.proxy.scheme.isEmpty) {
|
||||
config.proxy.scheme = 'http';
|
||||
}
|
||||
if (config.downloadDir.isEmpty) {
|
||||
config.downloadDir = await _defaultDownloadDir();
|
||||
}
|
||||
if (extra.downloadCategories.isEmpty) {
|
||||
extra.downloadCategories = [
|
||||
DownloadCategory(
|
||||
name: '',
|
||||
path: path.join(config.downloadDir, 'Music'),
|
||||
isBuiltIn: true,
|
||||
nameKey: 'categoryMusic',
|
||||
),
|
||||
DownloadCategory(
|
||||
name: '',
|
||||
path: path.join(config.downloadDir, 'Video'),
|
||||
isBuiltIn: true,
|
||||
nameKey: 'categoryVideo',
|
||||
),
|
||||
DownloadCategory(
|
||||
name: '',
|
||||
path: path.join(config.downloadDir, 'Document'),
|
||||
isBuiltIn: true,
|
||||
nameKey: 'categoryDocument',
|
||||
),
|
||||
DownloadCategory(
|
||||
name: '',
|
||||
path: path.join(config.downloadDir, 'Program'),
|
||||
isBuiltIn: true,
|
||||
nameKey: 'categoryProgram',
|
||||
),
|
||||
];
|
||||
}
|
||||
if (extra.githubMirror.mirrors.isEmpty) {
|
||||
extra.githubMirror.mirrors = [
|
||||
GithubMirror(type: GithubMirrorType.jsdelivr, url: 'https://fastly.jsdelivr.net/gh', isBuiltIn: true),
|
||||
GithubMirror(type: GithubMirrorType.ghProxy, url: 'https://fastgit.cc', isBuiltIn: true),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _initTrackerUpdate(DownloaderConfig config) async {
|
||||
final btExtra = config.extra.bt;
|
||||
final lastUpdateTime = btExtra.lastTrackerUpdateTime;
|
||||
if (!btExtra.autoUpdateTrackers ||
|
||||
(lastUpdateTime != null && !lastUpdateTime.isBefore(DateTime.now().subtract(const Duration(days: 1))))) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await updateTrackers(config);
|
||||
} catch (error, stackTrace) {
|
||||
logger.w('tracker update failed', error, stackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateTrackers(DownloaderConfig config) async {
|
||||
final btExtra = config.extra.bt;
|
||||
final trackers = <String>[];
|
||||
for (final url in btExtra.trackerSubscribeUrls) {
|
||||
final resp = await api.proxyRequest(url);
|
||||
final data = resp.data;
|
||||
if (resp.statusCode == 200 && data != null && data.isNotEmpty) {
|
||||
trackers.addAll(const LineSplitter().convert(data).where((line) => line.trim().isNotEmpty));
|
||||
}
|
||||
}
|
||||
btExtra.subscribeTrackers = trackers;
|
||||
btExtra.lastTrackerUpdateTime = DateTime.now();
|
||||
config.protocolConfig.bt.trackers = {...btExtra.subscribeTrackers, ...btExtra.customTrackers}.toList();
|
||||
await ref.read(gopeedServiceProvider).putConfig(config);
|
||||
|
||||
final current = state.value;
|
||||
if (current != null) {
|
||||
state = AsyncValue.data(
|
||||
AppRuntimeState(
|
||||
startConfig: current.startConfig,
|
||||
runningPort: current.runningPort,
|
||||
downloaderConfig: config,
|
||||
localBackendStarted: current.localBackendStarted,
|
||||
startupError: current.startupError,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> _defaultDownloadDir() async {
|
||||
if (kIsWeb) {
|
||||
return './';
|
||||
}
|
||||
if (Util.isDesktop()) {
|
||||
return (await getDownloadsDirectory())?.path ?? './';
|
||||
}
|
||||
if (Util.isAndroid()) {
|
||||
return (await getExternalStorageDirectory())?.path ?? (await getApplicationDocumentsDirectory()).path;
|
||||
}
|
||||
if (Util.isIOS()) {
|
||||
return (await getApplicationDocumentsDirectory()).path;
|
||||
}
|
||||
return './';
|
||||
}
|
||||
|
||||
String _runningAddress(StartConfig config, int runningPort) {
|
||||
if (config.network == 'unix') {
|
||||
return config.address;
|
||||
}
|
||||
return '${config.address.split(':').first}:$runningPort';
|
||||
}
|
||||
|
||||
Future<void> saveStartConfig(StartConfig config) async {
|
||||
Database.instance.saveStartConfig(
|
||||
StartConfigEntity(network: config.network, address: config.address, apiToken: config.apiToken),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const allTrackerSubscribeUrls = [
|
||||
'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_all.txt',
|
||||
'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_all_http.txt',
|
||||
'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_all_https.txt',
|
||||
'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_all_ip.txt',
|
||||
'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_all_udp.txt',
|
||||
'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_all_ws.txt',
|
||||
'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_best.txt',
|
||||
'https://raw.githubusercontent.com/ngosang/trackerslist/master/trackers_best_ip.txt',
|
||||
'https://raw.githubusercontent.com/XIU2/TrackersListCollection/master/all.txt',
|
||||
'https://raw.githubusercontent.com/XIU2/TrackersListCollection/master/best.txt',
|
||||
'https://raw.githubusercontent.com/XIU2/TrackersListCollection/master/http.txt',
|
||||
];
|
||||
@@ -0,0 +1,13 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
class LocaleController extends ChangeNotifier {
|
||||
Locale _locale = const Locale('en');
|
||||
|
||||
Locale get locale => _locale;
|
||||
|
||||
void setLocale(Locale locale) {
|
||||
if (_locale == locale) return;
|
||||
_locale = locale;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../api/api.dart' as api;
|
||||
import '../../api/model/task.dart';
|
||||
|
||||
class LocationKeepAlive {
|
||||
const LocationKeepAlive._();
|
||||
|
||||
static const _channel = MethodChannel('gopeed/location_keep_alive');
|
||||
|
||||
static Future<bool> requestPermission() async {
|
||||
if (!Platform.isIOS) return false;
|
||||
try {
|
||||
return await _channel.invokeMethod<bool>('requestPermission') ?? false;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> start() async {
|
||||
if (Platform.isIOS) await _channel.invokeMethod<void>('start');
|
||||
}
|
||||
|
||||
static Future<void> stop() async {
|
||||
if (Platform.isIOS) await _channel.invokeMethod<void>('stop');
|
||||
}
|
||||
}
|
||||
|
||||
class LocationKeepAliveCoordinator {
|
||||
LocationKeepAliveCoordinator._();
|
||||
|
||||
static final instance = LocationKeepAliveCoordinator._();
|
||||
|
||||
Timer? _timer;
|
||||
bool Function()? _enabled;
|
||||
bool _reconciling = false;
|
||||
|
||||
void start(bool Function() enabled) {
|
||||
if (!Platform.isIOS) return;
|
||||
_enabled = enabled;
|
||||
_timer?.cancel();
|
||||
_timer = Timer.periodic(const Duration(seconds: 10), (_) => unawaited(reconcile()));
|
||||
unawaited(reconcile());
|
||||
}
|
||||
|
||||
Future<void> reconcile({bool? enabled}) async {
|
||||
if (!Platform.isIOS || _reconciling) return;
|
||||
_reconciling = true;
|
||||
try {
|
||||
if (!(enabled ?? _enabled?.call() ?? false)) {
|
||||
await LocationKeepAlive.stop();
|
||||
return;
|
||||
}
|
||||
final running = await api.getTasks([Status.running]);
|
||||
running.isEmpty ? await LocationKeepAlive.stop() : await LocationKeepAlive.start();
|
||||
} catch (_) {
|
||||
// Keep the current native state when task status cannot be queried.
|
||||
} finally {
|
||||
_reconciling = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:shadcn_flutter/shadcn_flutter.dart' as shad;
|
||||
|
||||
import '../api/model/create_task.dart';
|
||||
import '../app/application/app_appearance_controller.dart';
|
||||
import '../core/window/app_window_bootstrap.dart';
|
||||
import '../core/window/app_window_frame.dart';
|
||||
import '../core/window/app_window_payload.dart';
|
||||
import '../core/window/window_capability_transport.dart';
|
||||
import '../features/tasks/presentation/pages/create_task_window_page.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import '../shared/theme/app_component_themes.dart';
|
||||
import '../shared/theme/app_theme.dart';
|
||||
import '../shared/theme/app_theme_color.dart';
|
||||
|
||||
class ChildWindowApp extends StatefulWidget {
|
||||
const ChildWindowApp({super.key, required this.payload, required this.session});
|
||||
|
||||
final AppWindowPayload payload;
|
||||
final ChildWindowSession session;
|
||||
|
||||
@override
|
||||
State<ChildWindowApp> createState() => _ChildWindowAppState();
|
||||
}
|
||||
|
||||
class _ChildWindowAppState extends State<ChildWindowApp> with WidgetsBindingObserver {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
widget.session.appearance.addListener(_appearanceChanged);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
widget.session.appearance.removeListener(_appearanceChanged);
|
||||
widget.session.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangePlatformBrightness() {
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
void _appearanceChanged() {
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final appearance = widget.session.appearance.value;
|
||||
final themeColor = AppThemeColor.fromKey(appearance.themeColor);
|
||||
final themeMode = AppThemeMode.fromKey(appearance.themeMode);
|
||||
final isLightTheme = switch (themeMode) {
|
||||
AppThemeMode.system => WidgetsBinding.instance.platformDispatcher.platformBrightness == Brightness.light,
|
||||
AppThemeMode.light => true,
|
||||
AppThemeMode.dark => false,
|
||||
};
|
||||
final shadThemeMode = switch (themeMode) {
|
||||
AppThemeMode.system => shad.ThemeMode.system,
|
||||
AppThemeMode.light => shad.ThemeMode.light,
|
||||
AppThemeMode.dark => shad.ThemeMode.dark,
|
||||
};
|
||||
final locale = supportedLocaleFromConfig(appearance.locale);
|
||||
|
||||
return shad.ShadcnApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
onGenerateTitle: (context) => AppWindowBootstrap.subWindowTitle(widget.payload.type, context.l10n),
|
||||
theme: AppTheme.light(themeColor),
|
||||
darkTheme: AppTheme.dark(themeColor),
|
||||
materialTheme: isLightTheme ? AppTheme.materialLight(themeColor) : AppTheme.materialDark(themeColor),
|
||||
themeMode: shadThemeMode,
|
||||
locale: locale,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
builder: (context, child) => AppComponentThemes(child: child ?? const SizedBox.shrink()),
|
||||
home: AppWindowFrame(child: Builder(builder: _buildPage)),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPage(BuildContext context) {
|
||||
return switch (widget.payload.type) {
|
||||
AppWindowType.createTask => CreateTaskWindowPage(
|
||||
windowController: widget.session.controller,
|
||||
initialTask: widget.payload.createTask == null ? null : CreateTask.fromJson(widget.payload.createTask!),
|
||||
),
|
||||
_ => shad.Scaffold(child: Center(child: Text(context.l10n.unsupportedWindowPayload))),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import 'package:get/get.dart';
|
||||
|
||||
import '../controllers/app_controller.dart';
|
||||
|
||||
class AppBinding extends Bindings {
|
||||
@override
|
||||
void dependencies() {
|
||||
Get.lazyPut<AppController>(
|
||||
() => AppController(),
|
||||
);
|
||||
}
|
||||
}
|
||||
Loaded 50 of 742 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user