-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathnexusphp_adapter.dart
More file actions
574 lines (510 loc) · 17.6 KB
/
nexusphp_adapter.dart
File metadata and controls
574 lines (510 loc) · 17.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:logger/logger.dart';
import '../../models/app_models.dart';
import 'site_adapter.dart';
import 'api_exceptions.dart';
import 'package:pt_mate/services/site_config_service.dart';
import '../../utils/format.dart';
import 'nexusphp_helper.dart';
/// NexusPHP 站点适配器
/// 实现 NexusPHP (1.9+) 站点的 API 调用
class NexusPHPAdapter with NexusPHPHelper implements SiteAdapter {
// ⚡ Bolt: Cache RegExp to avoid recompiling on every match during loops
static final RegExp _invisibleCharsRegExp = RegExp(r'[\s\u200B-\u200D\uFEFF]');
late SiteConfig _siteConfig;
late Dio _dio;
Map<String, String>? _discountMapping;
Map<String, String>? _tagMapping;
static final Logger _logger = Logger();
@override
Map<String, String>? get discountMapping => _discountMapping;
@override
Map<String, String>? get tagMapping => _tagMapping;
@override
SiteConfig get siteConfig => _siteConfig;
@override
Future<void> init(SiteConfig config) async {
final swTotal = Stopwatch()..start();
_siteConfig = config;
// 加载优惠类型映射配置
final swDiscount = Stopwatch()..start();
await _loadDiscountMapping();
// 加载标签映射配置
await _loadTagMapping();
swDiscount.stop();
if (kDebugMode) {
_logger.d('NexusPHPAdapter.init: 加载优惠映射耗时=${swDiscount.elapsedMilliseconds}ms');
}
_dio = Dio(
BaseOptions(
connectTimeout: const Duration(seconds: 5),
receiveTimeout: const Duration(seconds: 10),
sendTimeout: const Duration(seconds: 30),
headers: {
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36',
},
),
);
final swInterceptors = Stopwatch()..start();
_dio.interceptors.clear();
_dio.interceptors.add(
InterceptorsWrapper(
onRequest: (options, handler) async {
// 设置baseUrl
if (options.baseUrl.isEmpty || options.baseUrl == '/') {
var base = _siteConfig.baseUrl.trim();
if (base.endsWith('/')) base = base.substring(0, base.length - 1);
options.baseUrl = base;
}
// 动态构建请求头
options.headers.addAll(_buildHeaders(_siteConfig.apiKey));
return handler.next(options);
},
),
);
swInterceptors.stop();
if (kDebugMode) {
_logger.d('NexusPHPAdapter.init: 配置Dio与拦截器耗时=${swInterceptors.elapsedMilliseconds}ms');
}
swTotal.stop();
if (kDebugMode) {
_logger.d('NexusPHPAdapter.init: 总耗时=${swTotal.elapsedMilliseconds}ms');
}
}
/// 加载优惠类型映射配置
Future<void> _loadDiscountMapping() async {
try {
final template = await SiteConfigService.getTemplateById(
'',
SiteType.nexusphp,
);
if (template?.discountMapping != null) {
_discountMapping = Map<String, String>.from(
template!.discountMapping,
);
}
final specialMapping = await SiteConfigService.getDiscountMapping(
_siteConfig.baseUrl,
);
if (specialMapping.isNotEmpty) {
_discountMapping?.addAll(specialMapping);
}
} catch (e) {
// 使用默认映射
_discountMapping = {};
}
}
/// 加载标签映射配置
Future<void> _loadTagMapping() async {
try {
final template = await SiteConfigService.getTemplateById(
'',
SiteType.nexusphp,
);
if (template?.tagMapping != null) {
_tagMapping = Map<String, String>.from(template!.tagMapping);
}
} catch (e) {
_tagMapping = {};
}
}
/// 构建请求头,包含Bearer Token认证
Map<String, String> _buildHeaders(String? token) {
final headers = <String, String>{
'Content-Type': 'application/json',
'Accept': 'application/json',
};
if (token != null && token.isNotEmpty) {
headers['Authorization'] = 'Bearer $token';
}
return headers;
}
@override
Future<MemberProfile> fetchMemberProfile({String? apiKey}) async {
try {
final response = await _dio.get(
'/api/v1/profile',
queryParameters: {'include_fields[user]': 'seeding_leeching_data'},
);
final data = response.data;
if (data['ret'] == 0 && data['data'] != null) {
return _parseMemberProfile(data['data']['data']);
} else {
throw SiteApiException(
message: '获取用户资料失败: ${data['msg'] ?? '未知错误'}',
responseData: data,
);
}
} catch (e) {
throw ApiExceptionAdapter.wrapError(e, '获取用户资料');
}
}
/// 解析用户资料数据
MemberProfile _parseMemberProfile(Map<String, dynamic> data) {
final uploadedBytes = (data['uploaded'] ?? 0).toInt();
final downloadedBytes = (data['downloaded'] ?? 0).toInt();
return MemberProfile(
username: data['username'] ?? '',
bonus: (data['bonus'] ?? 0).toDouble(),
shareRate: double.tryParse(data['share_ratio']?.toString() ?? '0') ?? 0.0,
uploadedBytes: uploadedBytes,
downloadedBytes: downloadedBytes,
uploadedBytesString: Formatters.dataFromBytes(uploadedBytes),
downloadedBytesString: Formatters.dataFromBytes(downloadedBytes),
userId: data['id']?.toString(), // 从data.data.id获取用户ID
passKey: null, // NexusPHP API类型不提供passKey
lastAccess: Formatters.parseDateTimeCustom(
data['last_access']?.toString(),
),
bonusPerHour: data['seed_bonus_per_hour']?.toDouble(),
seedingSizeBytes: data['seeding_leeching_data']?['seeding_size']?.toInt(),
);
}
@override
Future<TorrentSearchResult> searchTorrents({
String? keyword,
int pageNumber = 1,
int pageSize = 30,
int? onlyFav,
Map<String, dynamic>? additionalParams,
}) async {
final Map<String, dynamic> params = {
'page': pageNumber.toString(),
'per_page': pageSize.toString(),
'include_fields[torrent]': 'download_url,has_bookmarked,active_status',
};
if (keyword != null && keyword.isNotEmpty) {
params['filter[title]'] = keyword;
}
if (onlyFav != null && onlyFav > 0) {
params['filter[bookmark]'] = onlyFav;
}
var url = '/api/v1/torrents';
// 添加额外参数
if (additionalParams != null && additionalParams.isNotEmpty) {
//
for (var add in additionalParams.entries) {
if (add.key == 'category') {
var category = add.value.toString().split('#');
if (category.length == 2) {
url += '/${category[0]}';
params['filter[category]'] = category[1];
}
} else {
params[add.key] = add.value;
}
}
}
try {
final response = await _dio.get(url, queryParameters: params);
if (kDebugMode) {
_logger.d(
'NexusPHPAdapter.searchTorrents raw response: ${response.data}',
);
}
final data = response.data;
if (data['ret'] == 0) {
return _parseTorrentSearchResult(data['data']);
} else {
throw SiteApiException(
message: '搜索失败: ${data['msg'] ?? '未知错误'}',
responseData: data,
);
}
} catch (e) {
throw ApiExceptionAdapter.wrapError(e, '搜索种子');
}
}
TorrentSearchResult _parseTorrentSearchResult(Map<String, dynamic> data) {
final meta = data['meta'] as Map<String, dynamic>;
final items = (data['data'] as List)
.map((item) => _parseTorrentItem(item as Map<String, dynamic>))
.toList();
return TorrentSearchResult(
pageNumber: meta['current_page'] as int,
pageSize: meta['per_page'] as int,
total: meta['total'] as int,
totalPages: meta['last_page'] as int,
items: items,
);
}
TorrentItem _parseTorrentItem(Map<String, dynamic> item) {
// 解析促销信息
String discountText = 'Normal';
final promotionInfo = item['promotion_info'] as Map<String, dynamic>?;
if (promotionInfo != null) {
final originalText = promotionInfo['text'] as String? ?? 'Normal';
// 映射促销信息以兼容现有的显示逻辑
if (originalText.toLowerCase().contains('2x') &&
originalText.toLowerCase().contains('free')) {
discountText = 'Free*2';
} else {
discountText = originalText;
}
}
// 解析下载状态
DownloadStatus status = DownloadStatus.none;
final activeStatus = item['active_status'];
if (activeStatus is Map<String, dynamic>) {
final s = activeStatus['active_status']?.toString().toLowerCase();
if (s == 'leeching') {
status = DownloadStatus.downloading;
} else if (s == 'seeding' || s == 'inactivity') {
status = DownloadStatus.completed;
}
}
final name = item['name'] as String;
final smallDescr = item['small_descr'] as String? ?? '';
// 计算标签并清理描述
final tags = TagType.matchTags(name + smallDescr);
// NexusPHP api tags parsing
if (item['tags'] != null && item['tags'] is List) {
final tagsList = item['tags'] as List;
for (var tagMap in tagsList) {
if (tagMap is Map) {
final tagName = tagMap['name']?.toString();
if (tagName != null && tagName.isNotEmpty) {
// 1. matchTags (in case the tag name itself is a known tag keyword)
// tags.addAll(TagType.matchTags(tagName));
// 2. parseTagType (using the mapping config)
final mappedTag = parseTagType(tagName);
if (mappedTag != null && !tags.contains(mappedTag)) {
tags.add(mappedTag);
}
}
}
}
}
return TorrentItem(
id: (item['id'] as int).toString(),
name: name,
smallDescr: smallDescr,
discount: parseDiscountType(discountText),
discountEndTime: null, // 暂时没有
downloadUrl: item['download_url'] as String?,
seeders: item['seeders'] as int,
leechers: item['leechers'] as int,
sizeBytes: item['size'] as int,
downloadStatus: status,
collection: item['has_bookmarked'] as bool? ?? false,
imageList: const [], // 暂时没有图片列表
cover: item['cover'] as String? ?? '',
createdDate: Formatters.parseDateTimeCustom(
item['added'] != null ? item['added'] + ':00' : null,
),
isTop: item['pos_state'] != 'normal',
tags: tags,
comments: item['comments'] as int? ?? 0,
);
}
@override
Future<TorrentDetail> fetchTorrentDetail(
String id, {
String? description,
}) async {
try {
if (description != null && description.isNotEmpty) {
return TorrentDetail(descr: description, descrHtml: description);
}
final response = await _dio.get(
'/api/v1/detail/$id',
queryParameters: {'includes': 'extra'},
);
final data = response.data;
if (data == null ||
data['data'] == null ||
data['data']['data'] == null) {
throw SiteApiException(message: '响应数据格式错误', responseData: data);
}
final torrentData = data['data']['data'];
final extra = torrentData['extra'] as Map<String, dynamic>?;
final descr = extra?['descr']?.toString() ?? '';
return TorrentDetail(descr: descr);
} catch (e) {
throw ApiExceptionAdapter.wrapError(e, '获取种子详情');
}
}
@override
Future<TorrentCommentList> fetchComments(String id, {int pageNumber = 1, int pageSize = 20}) async {
try {
final response = await _dio.get(
'/api/v1/comments',
queryParameters: {
'torrent_id': id,
'page': pageNumber,
'per_page': pageSize,
},
);
final data = response.data as Map<String, dynamic>;
if (data['ret'] != 0) {
throw DioException(
requestOptions: response.requestOptions,
response: response,
error: data['msg'] ?? '获取评论失败',
);
}
final responseData = data['data'] as Map<String, dynamic>;
final meta = responseData['meta'] as Map<String, dynamic>?;
final commentsList = responseData['data'] as List? ?? [];
// 解析评论列表
final comments = commentsList.map((item) {
final commentData = item as Map<String, dynamic>;
final createUser = commentData['create_user'] as Map<String, dynamic>?;
return TorrentComment(
id: (commentData['id'] ?? '').toString(),
createdDate: Formatters.parseDateTimeCustom(
commentData['created_at']?.toString(),
),
lastModifiedDate: Formatters.parseDateTimeCustom(
commentData['created_at']?.toString(),
),
torrentId: id,
author: createUser?['username']?.toString() ?? '',
text: (commentData['text'] ?? '').toString(),
editedBy: '',
subject: '',
);
}).toList();
return TorrentCommentList(
pageNumber: meta?['current_page'] ?? pageNumber,
pageSize: meta?['per_page'] ?? pageSize,
total: meta?['total'] ?? comments.length,
totalPages: meta?['last_page'] ?? 1,
comments: comments,
);
} catch (e) {
// 当评论API不可用时,优雅降级返回空列表
return TorrentCommentList(
pageNumber: pageNumber,
pageSize: pageSize,
total: 0,
totalPages: 0,
comments: [],
);
}
}
//实际上调用不到了
@override
Future<String> genDlToken({required String id, String? url}) async {
// 检查必要的配置参数
if (_siteConfig.passKey == null || _siteConfig.passKey!.isEmpty) {
throw Exception('站点配置缺少passKey,无法生成下载链接');
}
if (_siteConfig.userId == null || _siteConfig.userId!.isEmpty) {
throw Exception('站点配置缺少userId,无法生成下载链接');
}
// https://www.ptskit.org/download.php?downhash={userId}.{jwt}
final jwt = getDownLoadHash(_siteConfig.passKey!, id, _siteConfig.userId!);
return '${_siteConfig.baseUrl}download.php?downhash=${_siteConfig.userId!}.$jwt';
}
@override
Future<Map<String, dynamic>> queryHistory({
required List<String> tids,
}) async {
// TODO: 实现NexusPHP下载历史查询
// 临时返回空历史
return {'data': <String, dynamic>{}};
}
@override
Future<void> toggleCollection({
required String torrentId,
required bool make,
}) async {
try {
final String endpoint;
if (make) {
endpoint = '/api/v1/bookmarks';
} else {
endpoint = '/api/v1/bookmarks/delete';
}
final formData = FormData.fromMap({'torrent_id': torrentId});
final response = await _dio.post(
endpoint,
data: formData,
options: Options(headers: {'Accept': 'application/json'}),
);
final data = response.data;
if (data != null && data['ret'] != null && data['ret'] != 0) {
throw SiteApiException(
message: '收藏操作失败: ${data['msg'] ?? '未知错误'}',
responseData: data,
);
}
} catch (e) {
throw ApiExceptionAdapter.wrapError(e, '收藏操作');
}
}
@override
Future<bool> testConnection() async {
try {
// TODO: 实现NexusPHP连接测试
// 临时返回true
return true;
} catch (e) {
return false;
}
}
@override
Future<List<SearchCategoryConfig>> getSearchCategories() async {
// 通过baseUrl匹配预设配置
final defaultCategories =
await SiteConfigService.getDefaultSearchCategories(
_siteConfig.baseUrl,
);
// 如果获取到默认分类配置,则直接返回
if (defaultCategories.isNotEmpty) {
return defaultCategories;
}
final List<SearchCategoryConfig> categories = [];
// 默认塞个综合进来
categories.add(
SearchCategoryConfig(id: 'all', displayName: '综合', parameters: '{}'),
);
try {
final response = await _dio.get('/api/v1/sections');
if (response.statusCode == 200) {
final data = response.data;
if (data['ret'] == 0 && data['data'] != null) {
// 双循环遍历sections和categories
final sectionsData = data['data']['data'] is List
? data['data']['data']
: data['data']['sections'] as List;
var onlyOne = false;
if (sectionsData.length == 1) {
onlyOne = true;
}
for (final section in sectionsData) {
final sectionName = section['name'] as String;
final sectionDisplayName = (section['display_name'] as String)
.replaceAll(_invisibleCharsRegExp, '');
final categoriesData = section['categories'] as List;
for (final category in categoriesData) {
final categoryId = category['id'];
final categoryName = (category['name'] as String).replaceAll(
_invisibleCharsRegExp,
'',
);
categories.add(
SearchCategoryConfig(
id: '${sectionName}_$categoryId',
displayName: onlyOne
? categoryName
: '$sectionDisplayName.$categoryName',
parameters: '{"category":"$sectionName#$categoryId"}',
),
);
}
}
return categories;
}
}
// 如果获取失败,返回空列表
return categories;
} catch (e) {
// 发生异常时,返回空列表
return categories;
}
}
}