api修改和更新检查器修改

modrinth_api.dart:拦截器改为只替换 options.baseUrl,path 保持相对 /v2/search、query 留在 queryParameters,避免"整串写回 path"导致的 host 缺失 + query 重复拼接。mirror_service.dart:新增 apiBase getter,返回当前镜像的 API base(official→api.modrinth.com、mcim→modrinth-api.mcimirror.top、custom→自定义 base)

Signed-off-by: driftinblock <3480428251@qq.com>
This commit is contained in:
Ventiの酒 committed 2026-11-04 17:43:57 +08:00
1 parent ddd72c43fb
commit e32125aa8e
35 files changed
+4171 -1325

No files matched your search

+210
View File
@@ -0,0 +1,210 @@
/// 一条更新日志条目。
class ReleaseNoteItem {
final String text;
/// 是否为列表项(发布说明里以 `*`、`-` 或数字开头)。
final bool bullet;
const ReleaseNoteItem({required this.text, required this.bullet});
}
/// 一个更新日志分组,例如「更新」「修复」或发布者自定义的小标题。
class ReleaseNoteSection {
final String title;
final List<ReleaseNoteItem> items;
const ReleaseNoteSection({required this.title, required this.items});
}
/// 发布说明里提取出的链接。
class ReleaseNoteLink {
final String label;
final String url;
const ReleaseNoteLink({required this.label, required this.url});
}
/// Gitee 发布说明的轻量解析结果。
///
/// 不引入 Markdown 依赖,只处理发布说明里常见的标题、列表、粗体和链接。
class ReleaseNotes {
final List<ReleaseNoteSection> sections;
final List<ReleaseNoteLink> links;
const ReleaseNotes({required this.sections, required this.links});
/// 没有任何可展示的正文条目。
bool get isEmpty => sections.isEmpty;
factory ReleaseNotes.parse(String markdown) {
final sections = <String, ReleaseNoteSection>{};
final links = <ReleaseNoteLink>[];
final seenUrls = <String>{};
var activeTitle = '更新';
ReleaseNoteSection sectionFor(String title) {
return sections.putIfAbsent(
title,
() => ReleaseNoteSection(title: title, items: <ReleaseNoteItem>[]),
);
}
void addLink(String label, String url) {
final cleanedUrl =
url.trim().replaceFirst(RegExp(r'[.,;:!?,。;:!?*_`]+$'), '');
if (cleanedUrl.isEmpty || !seenUrls.add(cleanedUrl)) return;
final cleanedLabel =
_cleanInline(label).replaceFirst(RegExp(r'[::\s]+$'), '').trim();
links.add(
ReleaseNoteLink(
label: cleanedLabel.isEmpty ? '相关链接' : cleanedLabel,
url: cleanedUrl,
),
);
}
final normalized = markdown.replaceAll('\r\n', '\n').replaceAll('\r', '\n');
for (var rawLine in normalized.split('\n')) {
var line = rawLine.trim();
if (line.isEmpty) continue;
if (line.startsWith('```')) continue;
if (RegExp(r'^[-*_]{3,}$').hasMatch(line)) continue;
line = line.replaceFirst(RegExp(r'^>\s?'), '');
final heading = RegExp(r'^#{1,6}\s+(.*)$').firstMatch(line);
if (heading != null) {
final title = _cleanInline(heading.group(1) ?? '');
if (title.isEmpty) continue;
final lower = title.toLowerCase();
if (title.contains('更新') ||
title.contains('新增') ||
lower.contains('feature') ||
lower.contains('change')) {
activeTitle = '更新';
} else if (title.contains('修复') ||
lower.contains('fix') ||
lower.contains('bug')) {
activeTitle = '修复';
} else {
activeTitle = title;
sectionFor(title);
}
continue;
}
final bulletMatch = RegExp(r'^[*+-]\s+(.*)$').firstMatch(line) ??
RegExp(r'^\d+[.)]\s+(.*)$').firstMatch(line);
final isBullet = bulletMatch != null;
var content = bulletMatch?.group(1)?.trim() ?? line;
// 先提取 Markdown 链接,避免 URL 里的字符干扰后面的列表解析。
content = content.replaceAllMapped(
RegExp(r'\[([^\]]+)\]\((https?://[^)\s]+)\)'),
(match) {
addLink(match.group(1) ?? '', match.group(2) ?? '');
return '';
},
);
// 提取裸链接,并从正文中移除,避免日志里出现很长的 URL。
content = content.replaceAllMapped(
RegExp(r'https?://[^\s)<>]+'),
(match) {
final rawUrl = match.group(0) ?? '';
final rest = content.replaceRange(match.start, match.end, '');
addLink(_linkLabel(rest), rawUrl);
return '';
},
);
content = _cleanInline(content);
content = content.replaceFirst(RegExp(r'[\s::]+$'), '').trim();
if (content.isEmpty || _isChangelogLabel(content)) continue;
final prefixMatch = RegExp(
r'^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(?:\([^)]*\))?!?:\s*',
caseSensitive: false,
).firstMatch(content);
String? prefix;
if (prefixMatch != null) {
prefix = (prefixMatch.group(1) ?? '').toLowerCase();
content = content.substring(prefixMatch.end).trim();
}
if (content.isEmpty) continue;
final hasPrefix = prefix != null;
final isFix = prefix == 'fix' ||
prefix == 'revert' ||
(!hasPrefix && content.startsWith('修复'));
final String title;
if (hasPrefix) {
title = isFix ? '修复' : '更新';
} else if (activeTitle == '修复') {
title = '修复';
} else if (activeTitle == '更新') {
title = isFix ? '修复' : '更新';
} else {
title = activeTitle;
}
sectionFor(title).items.add(
ReleaseNoteItem(text: content, bullet: isBullet),
);
}
// 固定先展示「更新」和「修复」,再展示发布者自定义的小标题。
final ordered = <ReleaseNoteSection>[];
for (final title in const ['更新', '修复']) {
final section = sections[title];
if (section != null && section.items.isNotEmpty) ordered.add(section);
}
for (final section in sections.values) {
if (section.title != '更新' &&
section.title != '修复' &&
section.items.isNotEmpty) {
ordered.add(section);
}
}
return ReleaseNotes(sections: ordered, links: links);
}
}
String _cleanInline(String text) {
var value = text;
value = value.replaceAllMapped(
RegExp(r'!\[([^\]]*)\]\([^)]*\)'),
(match) => match.group(1) ?? '',
);
value = value.replaceAllMapped(
RegExp(r'\[([^\]]+)\]\([^)]*\)'),
(match) => match.group(1) ?? '',
);
value = value.replaceAll(RegExp(r'<[^>]*>'), '');
value = value.replaceAll('**', '').replaceAll('__', '').replaceAll('`', '');
value = value.replaceFirst(RegExp(r'^\s*>\s?'), '');
return value.trim();
}
String _linkLabel(String text) {
final label = _cleanInline(text).replaceFirst(RegExp(r'[::\s]+$'), '').trim();
if (label.isEmpty) return '相关链接';
if (label.contains('更新日志') ||
label.contains('完整的更新') ||
label.toLowerCase().contains('changelog')) {
return '完整的更新日志';
}
return label.length > 32 ? '${label.substring(0, 32)}…' : label;
}
bool _isChangelogLabel(String text) {
final label = text.replaceAll(RegExp(r'[::\s]+'), '').toLowerCase();
return label == '完整的更新日志' ||
label == '完整更新日志' ||
label == '更新日志' ||
label == 'changelog' ||
label == 'releasenotes' ||
label == 'fullchangelog';
}
+24
View File
@@ -0,0 +1,24 @@
/// 软件更新信息,由 Gitee 发布接口解析而来。
class UpdateInfo {
final String latestVersion;
final String downloadUrl;
final String apkName;
/// Gitee 发布说明(Markdown 原文)。
final String releaseNotes;
/// Gitee 发布接口返回的发布时间。
final DateTime? releasedAt;
/// Gitee 发布页地址。
final String releasePageUrl;
const UpdateInfo({
required this.latestVersion,
required this.downloadUrl,
required this.apkName,
this.releaseNotes = '',
this.releasedAt,
this.releasePageUrl = '',
});
}
+96 -36
View File
@@ -1,26 +1,23 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../core/l10n/strings.dart';
/// 软件更新信息,由 Gitee 发布接口的 tag_name 与 assets 解析而来
class UpdateInfo {
final String latestVersion;
final String downloadUrl;
final String apkName;
const UpdateInfo({
required this.latestVersion,
required this.downloadUrl,
required this.apkName,
});
}
import '../l10n/strings.dart';
import '../widgets/update_dialog.dart';
import 'update_info.dart';
export 'update_info.dart';
/// 更新检查与安装服务:负责从 Gitee 拉取发布信息、下载并调起系统安装器。
class UpdateService {
const UpdateService._();
/// Gitee 仓库地址
static const _repoUrl = 'https://gitee.com/driftinblock/zvmanager';
/// Gitee 仓库最新发布信息地址
static const _updateInfoUrl =
'https://gitee.com/api/v5/repos/driftinblock/zvmanager/releases/latest';
@@ -59,33 +56,89 @@ class UpdateService {
final json = jsonDecode(body) as Map<String, dynamic>;
// Gitee 发布接口的 tag_name 形如 "v1.3.0",去掉开头的 "v" 用于版本号对比
final tag = json['tag_name'] as String? ?? '';
final latestVersion = tag.startsWith('v') ? tag.substring(1) : tag;
final latestVersion =
tag.startsWith('v') || tag.startsWith('V') ? tag.substring(1) : tag;
if (latestVersion.isEmpty) return null;
// 从 assets 中筛选 APK 安装包,取其直链与文件名
String downloadUrl = '';
String apkName = '';
final assets = json['assets'] as List<dynamic>? ?? [];
for (final item in assets) {
final name = (item as Map<String, dynamic>)['name'] as String? ?? '';
final asset = item as Map<String, dynamic>;
final name = asset['name'] as String? ?? '';
if (name.endsWith('.apk')) {
downloadUrl = (item['browser_download_url'] as String? ??
item['download_url'] as String? ??
downloadUrl = (asset['browser_download_url'] as String? ??
asset['download_url'] as String? ??
'');
apkName = name;
break;
}
}
final htmlUrl = json['html_url'] as String? ?? '';
final releasePageUrl = htmlUrl.isNotEmpty
? htmlUrl
: (tag.isEmpty
? '$_repoUrl/releases'
: '$_repoUrl/releases/tag/${Uri.encodeComponent(tag)}');
return UpdateInfo(
latestVersion: latestVersion,
downloadUrl: downloadUrl,
apkName: apkName,
releaseNotes: json['body'] as String? ?? '',
releasedAt: DateTime.tryParse(json['created_at'] as String? ?? ''),
releasePageUrl: releasePageUrl,
);
} finally {
client.close();
}
}
/// 判断 [latest] 是否比 [current] 新。只有新版本更高时才返回 true,
/// 避免当前版本高于 Gitee 发布版本时误提示更新并引导降级。
static bool isNewerVersion(String latest, String current) {
if (latest.trim().isEmpty) return false;
final latestParts = _parseVersion(latest);
final currentParts = _parseVersion(current);
if (latestParts == null || currentParts == null) {
return latest.trim() != current.trim();
}
final length = latestParts.length > currentParts.length
? latestParts.length
: currentParts.length;
for (var i = 0; i < length; i++) {
final latestPart = i < latestParts.length ? latestParts[i] : 0;
final currentPart = i < currentParts.length ? currentParts[i] : 0;
if (latestPart != currentPart) return latestPart > currentPart;
}
return false;
}
/// 把 "v2.0.3+16" 解析成 [2, 0, 3],忽略 v 前缀、后缀和构建号。
static List<int>? _parseVersion(String version) {
var value = version.trim();
if (value.isEmpty) return null;
if (value.startsWith('v') || value.startsWith('V')) {
value = value.substring(1);
}
final suffixIndex = value.indexOf(RegExp(r'[-+]'));
if (suffixIndex >= 0) value = value.substring(0, suffixIndex);
final parts = value.split('.');
final numbers = <int>[];
for (final part in parts) {
final match = RegExp(r'^\d+').firstMatch(part);
if (match == null) return null;
numbers.add(int.parse(match.group(0)!));
}
return numbers.isEmpty ? null : numbers;
}
/// 展示版本对比结果弹窗;`hasUpdate` 为 false 时若无更新且 `silentOnNoUpdate` 为 true 则直接静默返回。
static void showUpdateDialog(
BuildContext context,
@@ -93,28 +146,33 @@ class UpdateService {
String currentVersion, {
bool silentOnNoUpdate = false,
}) {
final hasUpdate = info.latestVersion != currentVersion;
final hasUpdate = isNewerVersion(info.latestVersion, currentVersion);
if (!hasUpdate && silentOnNoUpdate) return;
showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(hasUpdate ? S.t('发现新版本') : S.t('已是最新')),
content: Text(hasUpdate
? '最新版本: ${info.latestVersion}\n当前版本: $currentVersion'
: S.f('当前版本 {0} 已是最新', [currentVersion])),
actions: [
TextButton(
onPressed: () => Navigator.pop(context), child: T('关闭')),
if (hasUpdate)
FilledButton(
onPressed: () {
Navigator.pop(context);
downloadAndInstall(context, info);
},
child: T('立即更新'),
if (!hasUpdate) {
showDialog<void>(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(S.t('已是最新')),
content: Text(S.f('当前版本 {0} 已是最新', [currentVersion])),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(),
child: T('关闭'),
),
],
],
),
);
return;
}
showDialog<void>(
context: context,
builder: (_) => UpdateDialog(
info: info,
currentVersion: currentVersion,
onUpdate: () => downloadAndInstall(context, info),
onOpenUrl: openUrl,
),
);
}
@@ -171,7 +229,9 @@ class UpdateService {
CircularProgressIndicator(value: value),
const SizedBox(height: 16),
Text(
percent == null ? S.t('正在下载安装包…') : S.f('下载中:{0}%', [percent]),
percent == null
? S.t('正在下载安装包…')
: S.f('下载中:{0}%', [percent]),
style: Theme.of(context).textTheme.bodyMedium,
),
],