-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathnexusphp_web_adapter.dart
More file actions
1647 lines (1452 loc) · 53.5 KB
/
nexusphp_web_adapter.dart
File metadata and controls
1647 lines (1452 loc) · 53.5 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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'package:flutter/foundation.dart';
import 'package:logger/logger.dart';
import '../../models/app_models.dart';
import '../../utils/format.dart';
import 'site_adapter.dart';
import 'api_exceptions.dart';
import '../site_config_service.dart';
import 'base_web_adapter.dart';
import 'package:dio/dio.dart';
import 'package:beautiful_soup_dart/beautiful_soup.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'dart:convert';
import '../logging/log_file_service.dart';
import 'nexusphp_helper.dart';
/// 参数对象,用于 Isolate 搜索解析
class ParseSearchParams {
final String html;
final Map<String, dynamic> searchConfig;
final Map<String, dynamic> totalPagesConfig;
final Map<String, String> discountMapping;
final Map<String, String> tagMapping;
final String baseUrl;
final String passKey;
final String userId;
final int pageNumber;
final int pageSize;
ParseSearchParams({
required this.html,
required this.searchConfig,
required this.totalPagesConfig,
required this.discountMapping,
required this.tagMapping,
required this.baseUrl,
required this.passKey,
required this.userId,
required this.pageNumber,
required this.pageSize,
});
}
/// 解析结果对象
class ParsedTorrentResult {
final List<TorrentItem> items;
final int totalPages;
final List<String> logs;
ParsedTorrentResult({
required this.items,
required this.totalPages,
this.logs = const [],
});
}
/// Helper class for Isolate usage
class _AdapterHelper with BaseWebAdapterMixin {}
// ⚡ Bolt: Caching RegExp instances to prevent recompilation during isolate parsing loops.
final _sizeRegExp = RegExp(r'([\d.]+)\s*(\w+)');
final _htmlUrlRegExp = RegExp(
r'(src|href)="((?!https?://|//|data:|javascript:|#)[^"]+)"',
caseSensitive: false,
);
/// Isolate entry point for parsing search results
Future<ParsedTorrentResult> _parseSearchResponseInIsolate(
ParseSearchParams params,
) async {
final soup = BeautifulSoup(params.html);
final logs = <String>[];
final torrents = await NexusPHPWebAdapter._staticParseTorrentList(
soup,
params.searchConfig,
params.discountMapping,
params.tagMapping,
params.baseUrl,
params.passKey,
params.userId,
logs,
);
final totalPages = await NexusPHPWebAdapter._staticParseTotalPages(
soup,
params.totalPagesConfig,
logs,
);
return ParsedTorrentResult(
items: torrents,
totalPages: totalPages,
logs: logs,
);
}
/// NexusPHP Web站点适配器
/// 用于处理基于Web接口的NexusPHP站点
class NexusPHPWebAdapter extends SiteAdapter
with BaseWebAdapterMixin, NexusPHPHelper {
late SiteConfig _siteConfig;
late Dio _dio;
Map<String, String>? _discountMapping;
Map<String, String>? _tagMapping;
@override
Map<String, String>? get tagMapping => _tagMapping;
@override
Map<String, String>? get discountMapping => _discountMapping;
SiteConfigTemplate? _customTemplate;
static final Logger _logger = Logger();
static const int _maxHtmlDumpLength = 200 * 1024; // 200KB 截断
void _logRuleAndSoup(String tag, Map<String, dynamic>? rule, dynamic soup) {
try {
final ruleJson = rule != null ? jsonEncode(rule) : '{}';
String html = '';
try {
html = soup?.toString() ?? '';
} catch (_) {}
if (html.length > _maxHtmlDumpLength) {
html = '${html.substring(0, _maxHtmlDumpLength)}\n... (truncated)';
}
// todo简单脱敏
_logger.e('[$tag] rule=$ruleJson');
// 使用 debugPrint 输出 HTML,避免 Logger 的格式化(边框等)导致难以复制
debugPrint('HTML=$html');
LogFileService.instance.append('[$tag] rule=$ruleJson');
LogFileService.instance.append('HTML=$html');
} catch (_) {
// 忽略日志失败
}
}
@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(
'NexusPHPWebAdapter.init: 加载优惠映射耗时=${swDiscount.elapsedMilliseconds}ms',
);
}
final swDio = Stopwatch()..start();
_dio = Dio(
BaseOptions(
connectTimeout: const Duration(seconds: 5),
receiveTimeout: const Duration(seconds: 10),
sendTimeout: const Duration(seconds: 30),
),
);
_dio.options.baseUrl = _siteConfig.baseUrl;
_dio.options.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';
_dio.options.responseType = ResponseType.plain; // 设置为plain避免JSON解析警告
swDio.stop();
if (kDebugMode) {
_logger.d(
'NexusPHPWebAdapter.init: 创建Dio与基本配置耗时=${swDio.elapsedMilliseconds}ms',
);
}
// 添加响应拦截器处理302重定向
final swInterceptors = Stopwatch()..start();
_dio.interceptors.add(
InterceptorsWrapper(
onRequest: (options, handler) {
// 动态添加Cookie
if (_siteConfig.cookie != null && _siteConfig.cookie!.isNotEmpty) {
options.headers['Cookie'] = _siteConfig.cookie;
}
handler.next(options);
},
onResponse: (response, handler) {
// 检查是否是302重定向到登录页面
// Dio默认会自动跟随重定向,因此最终状态码可能是200。
// 我们需要检查最终的URI或重定向记录来判断是否跳转到了登录页。
final isLoginRedirect =
response.realUri.toString().contains('login') ||
response.redirects.any(
(r) => r.location.toString().contains('login'),
);
if (isLoginRedirect) {
throw SiteAuthenticationException(
message: 'Cookie已过期,请重新登录更新Cookie',
);
}
if (response.statusCode == 302) {
final location = response.headers.value('location');
if (location != null && location.contains('login')) {
throw SiteAuthenticationException(
message: 'Cookie已过期,请重新登录更新Cookie',
);
}
}
handler.next(response);
},
onError: (error, handler) {
// 检查DioException中的响应状态码
if (error.response?.statusCode == 302) {
final location = error.response?.headers.value('location');
if (location != null && location.contains('login')) {
throw SiteAuthenticationException(
message: 'Cookie已过期,请重新登录更新Cookie',
);
}
}
handler.next(error);
},
),
);
swInterceptors.stop();
if (kDebugMode) {
_logger.d(
'NexusPHPWebAdapter.init: 添加拦截器耗时=${swInterceptors.elapsedMilliseconds}ms',
);
}
swTotal.stop();
if (kDebugMode) {
_logger.d(
'NexusPHPWebAdapter.init: 总耗时=${swTotal.elapsedMilliseconds}ms',
);
}
}
void setCustomTemplate(SiteConfigTemplate template) {
_customTemplate = template;
}
/// 加载优惠类型映射配置
Future<void> _loadDiscountMapping() async {
try {
if (_customTemplate != null) {
_discountMapping = Map<String, String>.from(
_customTemplate!.discountMapping,
);
return;
}
final template = await SiteConfigService.getTemplateById(
_siteConfig.templateId,
_siteConfig.siteType,
);
if (template?.discountMapping != null) {
_discountMapping = Map<String, String>.from(template!.discountMapping);
}
} catch (e) {
// 使用默认映射
_discountMapping = {};
}
}
/// 加载标签映射配置
Future<void> _loadTagMapping() async {
try {
if (_customTemplate != null) {
_tagMapping = Map<String, String>.from(_customTemplate!.tagMapping);
return;
}
final template = await SiteConfigService.getTemplateById(
_siteConfig.templateId,
_siteConfig.siteType,
);
if (template?.tagMapping != null) {
_tagMapping = Map<String, String>.from(template!.tagMapping);
}
} catch (e) {
_tagMapping = {};
}
}
/// 从字符串解析标签类型(静态方法)
static TagType? _staticParseTagType(
String? str,
Map<String, String> mapping,
) {
if (str == null || str.isEmpty) return null;
final enumName = mapping[str];
if (enumName != null) {
for (final type in TagType.values) {
if (type.name.toLowerCase() == enumName.toLowerCase()) {
return type;
}
// 也可以尝试匹配 content
if (type.content == enumName) {
return type;
}
}
}
return null;
}
/// 从字符串解析优惠类型(静态方法)
static DiscountType _staticParseDiscountType(
String? str,
Map<String, String> mapping,
) {
if (str == null || str.isEmpty) return DiscountType.normal;
final enumValue = mapping[str];
if (enumValue != null) {
for (final type in DiscountType.values) {
if (type.value == enumValue) {
return type;
}
}
}
return DiscountType.normal;
}
@override
Future<MemberProfile> fetchMemberProfile({String? apiKey}) async {
try {
// 获取配置信息
final config = await _getUserInfoConfig();
final path = config['path'] as String? ?? 'usercp.php';
final response = await _dio.get('/$path');
final soup = BeautifulSoup(response.data);
// 根据配置提取用户信息
final userInfo = await _extractUserInfoByConfig(soup, config);
// 提取PassKey(如果配置了)
String? passKey = await _extractPassKeyByConfig();
// 提取每小时魔力(如果配置了)
double? bonusPerHour = await _extractBonusPerHourByConfig();
// 将字符串格式的数据转换为数字
double shareRate =
double.tryParse(userInfo['ratio']?.replaceAll(',', '') ?? '0') ?? 0.0;
double bonusPoints =
double.tryParse((userInfo['bonus'] ?? '0').replaceAll(',', '')) ??
0.0;
// 对于bytes,由于web版本直接提供格式化字符串,这里设置为0
// 实际使用时应该使用uploadedBytesString和downloadedBytesString
int uploadedBytes = 0;
int downloadedBytes = 0;
// 更新站点配置中的临时 passKey 和 userId,便于后续下载链接生成等逻辑使用
try {
final uidStr = (userInfo['userId'] ?? '').toString();
if ((passKey != null && passKey.isNotEmpty) &&
(_siteConfig.passKey == null || _siteConfig.passKey!.isEmpty)) {
_siteConfig = _siteConfig.copyWith(passKey: passKey);
}
if (uidStr.isNotEmpty &&
(_siteConfig.userId == null || _siteConfig.userId!.isEmpty)) {
_siteConfig = _siteConfig.copyWith(userId: uidStr);
}
} catch (_) {}
return MemberProfile(
username: userInfo['userName'] ?? '',
bonus: bonusPoints,
shareRate: shareRate,
uploadedBytes: uploadedBytes,
downloadedBytes: downloadedBytes,
uploadedBytesString: userInfo['upload'] ?? '0 B',
downloadedBytesString: userInfo['download'] ?? '0 B',
userId: userInfo['userId'],
passKey: passKey,
bonusPerHour: bonusPerHour,
lastAccess: null, // Web版本暂不提供该字段
);
} catch (e) {
throw ApiExceptionAdapter.wrapError(e, '获取用户资料');
}
}
/// 获取指定类型的配置
/// [configType] 配置类型,如 'userInfo', 'passKey', 'search', 'categories' 等
Future<Map<String, dynamic>> _getFinderConfig(String configType) async {
if (_customTemplate != null && _customTemplate!.infoFinder != null) {
final infoFinder = _customTemplate!.infoFinder!;
if (infoFinder[configType] != null) {
return infoFinder[configType] as Map<String, dynamic>;
}
}
// 优先读取 SiteConfig.templateId 对应的配置
if (_siteConfig.templateId != '-1') {
try {
final template = await SiteConfigService.getTemplateById(
_siteConfig.templateId,
_siteConfig.siteType,
);
if (template != null && template.infoFinder != null) {
final infoFinder = template.infoFinder!;
if (infoFinder[configType] != null) {
return infoFinder[configType] as Map<String, dynamic>;
}
}
} catch (e) {
// 如果获取模板配置失败,继续使用默认配置
if (kDebugMode) {
if (kDebugMode) {
_logger.e('获取模板配置失败: $e');
}
}
}
}
// 没有找到模板配置或模板ID为-1,使用默认的 NexusPHPWeb 配置
final template = await SiteConfigService.getTemplateById(
'',
SiteType.nexusphpweb,
);
if (template != null && template.infoFinder != null) {
final infoFinder = template.infoFinder!;
if (infoFinder[configType] != null) {
return infoFinder[configType] as Map<String, dynamic>;
}
}
return {};
}
/// 获取指定类型的请求配置
/// [action] 请求动作,如 'loginPage', 'collect', 'unCollect' 或 'search.normal' 等
Future<Map<String, dynamic>?> _getRequestConfig(String action) async {
final templatesToTry = <SiteConfigTemplate?>[];
// 1. 尝试自定义模板
if (_customTemplate != null) {
templatesToTry.add(_customTemplate);
}
// 2. 尝试指定的模板 ID
if (_siteConfig.templateId != '-1' && _siteConfig.templateId.isNotEmpty) {
try {
final template = await SiteConfigService.getTemplateById(
_siteConfig.templateId,
_siteConfig.siteType,
);
if (template != null) {
templatesToTry.add(template);
}
} catch (e) {
if (kDebugMode) {
_logger.e('获取模板失败: $e');
}
}
}
// 3. 始终最后尝试默认的 NexusPHPWeb 模板
try {
final defaultTemplate = await SiteConfigService.getTemplateById(
'',
SiteType.nexusphpweb,
);
if (defaultTemplate != null) {
templatesToTry.add(defaultTemplate);
}
} catch (_) {}
// 对每个模板尝试解析动作路径
final parts = action.split('.');
for (final template in templatesToTry) {
if (template == null || template.request == null) continue;
dynamic current = template.request;
bool found = true;
for (final part in parts) {
if (current is Map && current.containsKey(part)) {
current = current[part];
} else {
found = false;
break;
}
}
if (found && current is Map<String, dynamic>) {
return current;
}
}
return null;
}
/// 获取用户信息配置(保持向前兼容)
Future<Map<String, dynamic>> _getUserInfoConfig() async {
return _getFinderConfig('userInfo');
}
/// 根据配置提取用户信息
Future<Map<String, String?>> _extractUserInfoByConfig(
BeautifulSoup soup,
Map<String, dynamic> config,
) async {
final result = <String, String?>{};
// 获取行选择器配置
final rowsConfig = config['rows'] as Map<String, dynamic>?;
final fieldsConfig = config['fields'] as Map<String, dynamic>?;
if (rowsConfig == null || fieldsConfig == null) {
throw Exception('配置格式错误:缺少 rows 或 fields 配置');
}
// 根据行选择器找到目标元素
final rowSelector = rowsConfig['selector'] as String?;
if (rowSelector == null || rowSelector.isEmpty) {
throw Exception('配置错误:缺少行选择器');
}
final targetElement = findFirstElementBySelector(soup, rowSelector);
if (targetElement == null) {
_logRuleAndSoup('userInfo.rows.notFound', rowsConfig, soup);
throw Exception('未找到目标元素:$rowSelector');
}
// 遍历字段配置,提取每个字段的值
for (final fieldEntry in fieldsConfig.entries) {
final fieldName = fieldEntry.key;
final fieldConfig = fieldEntry.value as Map<String, dynamic>;
try {
final value = await extractFirstFieldValue(targetElement, fieldConfig);
result[fieldName] = value;
} catch (e) {
// 如果某个字段提取失败,记录但继续处理其他字段
_logRuleAndSoup(
'userInfo.field.extractFailed.$fieldName',
fieldConfig,
targetElement,
);
result[fieldName] = null;
}
}
return result;
}
/// 根据配置提取每小时魔力(bonusPerHour)
Future<double?> _extractBonusPerHourByConfig() async {
try {
final bonusConfig = await _getFinderConfig('bonusPerHour');
final path = bonusConfig['path'] as String? ?? 'mybonus.php';
final response = await _dio.get('/$path');
final soup = BeautifulSoup(response.data);
final rowsConfig = bonusConfig['rows'] as Map<String, dynamic>?;
final fieldsConfig = bonusConfig['fields'] as Map<String, dynamic>?;
if (rowsConfig == null || fieldsConfig == null) {
throw Exception('配置格式错误:缺少 rows 或 fields 配置');
}
final rowSelector = rowsConfig['selector'] as String?;
if (rowSelector == null || rowSelector.isEmpty) {
throw Exception('配置错误:缺少行选择器');
}
final targetElement = findFirstElementBySelector(soup, rowSelector);
if (targetElement == null) {
_logRuleAndSoup('bonus.rows.notFound', rowsConfig, soup);
throw Exception('未找到目标元素:$rowSelector');
}
final field = fieldsConfig['bonusPerHour'] as Map<String, dynamic>?;
if (field == null) {
_logRuleAndSoup('bonus.field.missing', fieldsConfig, soup);
throw Exception('配置错误:缺少 bonusPerHour 字段');
}
final value = await extractFirstFieldValue(targetElement, field);
if (value == null || value.isEmpty) return null;
final parsed = double.tryParse(value.replaceAll(',', ''));
return parsed;
} catch (e) {
_logRuleAndSoup('bonus.extract.failed', null, BeautifulSoup(''));
return null;
}
}
/// 根据配置提取PassKey
Future<String?> _extractPassKeyByConfig() async {
try {
// 获取PassKey配置
final passKeyConfig = await _getFinderConfig('passKey');
// 获取PassKey页面路径
final path = passKeyConfig['path'] as String?;
if (path == null || path.isEmpty) {
throw Exception('PassKey配置中缺少path字段');
}
final response = await _dio.get('/$path');
final soup = BeautifulSoup(response.data);
// 获取行选择器配置
final rowsConfig = passKeyConfig['rows'] as Map<String, dynamic>?;
if (rowsConfig == null) {
_logRuleAndSoup('passKey.rows.missing', passKeyConfig, soup);
throw Exception('配置格式错误:缺少 rows 配置');
}
// 根据行选择器找到目标元素
final rowSelector = rowsConfig['selector'] as String?;
if (rowSelector == null || rowSelector.isEmpty) {
throw Exception('配置错误:缺少行选择器');
}
final targetElement = findFirstElementBySelector(soup, rowSelector);
if (targetElement == null) {
_logRuleAndSoup('passKey.rows.notFound', rowsConfig, soup);
throw Exception('未找到目标元素:$rowSelector');
}
// 根据配置提取PassKey
final fields = passKeyConfig['fields'] as Map<String, dynamic>?;
final passKeyField = fields?['passKey'] as Map<String, dynamic>?;
if (passKeyField != null) {
final value = await extractFirstFieldValue(targetElement, passKeyField);
if (value != null && value.isNotEmpty) {
return value.trim();
} else {
_logRuleAndSoup(
'passKey.field.extractFailed',
passKeyField,
targetElement,
);
_logRuleAndSoup('passKey.rows.info', rowsConfig, soup);
throw Exception('提取PassKey失败:未匹配到目标元素$rowSelector');
}
}
_logRuleAndSoup('passKey.field.undefined', passKeyConfig, soup);
throw Exception('无法从配置中提取PassKey');
} catch (e) {
_logRuleAndSoup('passKey.extract.failed', null, BeautifulSoup(''));
throw Exception('提取PassKey失败: $e');
}
}
@override
Future<TorrentSearchResult> searchTorrents({
String? keyword,
int pageNumber = 0,
int pageSize = 100,
int? onlyFav,
Map<String, dynamic>? additionalParams,
}) async {
try {
// 确定搜索动作类型
String searchAction = 'search.normal';
// 提取分类前缀信息(如果存在)
String? categoryParam;
if (additionalParams != null &&
additionalParams.containsKey('category')) {
categoryParam = additionalParams['category'] as String?;
if (categoryParam != null && categoryParam.startsWith('special')) {
searchAction = 'search.special';
}
}
// 获取搜索请求配置
final requestConfig = await _getRequestConfig(searchAction);
if (requestConfig == null) {
throw Exception('未找到搜索配置: $searchAction');
}
final path = requestConfig['path'] as String? ?? '/torrents.php';
final method = requestConfig['method'] as String? ?? 'GET';
final configParams = Map<String, dynamic>.from(
requestConfig['params'] as Map<String, dynamic>? ?? {},
);
// 提取分类 ID(格式: "prefix#categoryId")
String categoryId = '';
if (categoryParam != null) {
final parts = categoryParam.split('#');
if (parts.length == 2 && parts[1].isNotEmpty) {
categoryId = parts[1];
}
}
// 构建最终查询参数
final queryParams = <String, dynamic>{};
// 替换占位符并填充参数
configParams.forEach((key, value) {
if (value is String) {
String val = value;
val = val.replaceAll('{keyword}', keyword ?? '');
val = val.replaceAll('{page}', (pageNumber - 1).toString());
val = val.replaceAll('{pageSize}', pageSize.toString());
// 处理 {categoryId} 占位符:无分类时移除该参数
if (val.contains('{categoryId}')) {
if (categoryId.isNotEmpty) {
val = val.replaceAll('{categoryId}', categoryId);
} else {
return; // 没有分类 ID,不加入 queryParams
}
}
// 处理 {onlyFav} 占位符
if (val.contains('{onlyFav}')) {
if (onlyFav == 1) {
val = val.replaceAll('{onlyFav}', '1');
queryParams[key] = val;
}
// 如果不是 1,则不加入 queryParams (即移除该参数)
} else {
queryParams[key] = val;
}
} else {
queryParams[key] = value;
}
});
// 添加其他额外参数
if (additionalParams != null) {
additionalParams.forEach((key, value) {
if (key != 'category') {
queryParams[key] = value;
}
});
}
// 发送请求
final response = await _dio.request(
path,
queryParameters: method.toUpperCase() == 'GET' ? queryParams : null,
data: method.toUpperCase() == 'POST' ? queryParams : null,
options: Options(method: method.toUpperCase()),
);
// 准备在 Isolate 中进行解析的参数
final searchConfig = await _getFinderConfig('search');
final totalPagesConfig = await _getFinderConfig('totalPages');
// 如果搜索配置为空,直接返回空结果,不启动 Isolate
if (searchConfig.isEmpty) {
return TorrentSearchResult(
pageNumber: pageNumber,
pageSize: pageSize,
total: 0,
totalPages: 0,
items: [],
);
}
final parseParams = ParseSearchParams(
html: response.data.toString(),
searchConfig: searchConfig,
totalPagesConfig: totalPagesConfig,
discountMapping: _discountMapping ?? {},
tagMapping: _tagMapping ?? {},
baseUrl: _siteConfig.baseUrl,
passKey: _siteConfig.passKey ?? '',
userId: _siteConfig.userId ?? '',
pageNumber: pageNumber,
pageSize: pageSize,
);
// 在 Isolate 中执行解析
final result = await compute(_parseSearchResponseInIsolate, parseParams);
return TorrentSearchResult(
pageNumber: pageNumber,
pageSize: pageSize,
total: result.items.length * result.totalPages, // 估算值
totalPages: result.totalPages,
items: result.items,
);
} catch (e) {
throw ApiExceptionAdapter.wrapError(e, '搜索种子');
}
}
/// 下载种子文件
///
/// [url] 种子文件的下载链接(相对路径或绝对路径)
/// 返回种子文件的字节数据
Future<List<int>> downloadTorrent(String url) async {
try {
// 确保URL是相对路径或完整的BaseURL路径
String downloadUrl = url;
if (url.startsWith('http')) {
// 如果是完整URL,检查是否属于当前站点
if (!url.startsWith(_siteConfig.baseUrl)) {
// 如果不属于当前站点,直接使用Dio下载(带Cookie可能会有问题,但尝试一下)
// 或者这里应该抛出异常?通常下载链接应该是站内的
}
}
_logger.i('NexusPHPWebAdapter: Downloading torrent from $downloadUrl');
final response = await _dio.get<List<int>>(
downloadUrl,
options: Options(
responseType: ResponseType.bytes,
followRedirects: true,
maxRedirects: 5,
validateStatus: (status) => status != null && status < 400,
),
);
_logger.i(
'NexusPHPWebAdapter: Download finished. Status: ${response.statusCode}',
);
_logger.d('NexusPHPWebAdapter: Response headers: ${response.headers}');
_logger.d('NexusPHPWebAdapter: Final URI: ${response.realUri}');
if (response.realUri.toString().contains('login') ||
response.realUri.toString().contains('verify')) {
throw Exception(
'Download redirected to login/verify page. Check cookies.',
);
}
final contentType = response.headers.value('content-type');
if (contentType != null &&
!contentType.contains('bittorrent') &&
!contentType.contains('octet-stream')) {
_logger.w(
'NexusPHPWebAdapter: Warning - Content-Type is $contentType, might not be a torrent file.',
);
}
if (response.data != null) {
return response.data!;
} else {
throw Exception('下载种子文件失败: 响应为空');
}
} catch (e) {
_logger.e('下载种子文件失败: $e');
rethrow;
}
}
Future<int> parseTotalPages(BeautifulSoup soup) async {
final config = await _getFinderConfig('totalPages');
if (config.isEmpty) {
return 1;
}
return _staticParseTotalPages(soup, config);
}
static Future<int> _staticParseTotalPages(
BeautifulSoup soup,
Map<String, dynamic> config, [
List<String>? logs,
]) async {
final helper = _AdapterHelper();
int totalPages = 1;
try {
final rowsConfig = config['rows'] as Map<String, dynamic>?;
final fieldsConfig = config['fields'] as Map<String, dynamic>?;
if (rowsConfig == null || fieldsConfig == null) {
return 1;
}
// 获取行选择器配置
final rowSelector = rowsConfig['selector'] as String?;
if (rowSelector == null || rowSelector.isEmpty) {
return 1;
}
// 找到目标行
final rows = helper.findElementBySelector(soup, rowSelector);
if (rows.isEmpty) {
return 1;
}
final fieldConfig = fieldsConfig['totalPages'] as Map<String, dynamic>?;
if (fieldConfig == null) {
return 1;
}
List<int> pageValues = [];
for (final row in rows) {
final values = await helper.extractFieldValue(row, fieldConfig);
for (final val in values) {
final parsed = FormatUtil.parseInt(val);
if (parsed != null) {
pageValues.add(parsed);
}
}
}
if (pageValues.isNotEmpty) {
totalPages = pageValues.reduce((a, b) => a > b ? a : b);
}
} catch (e) {
logs?.add('解析总页数失败: $e');
if (logs == null) {
// 在静态上下文中直接调用 _logger 是安全的,因为它是 static final
_logger.e('解析总页数失败: $e');
}
}
return totalPages;
}
Future<List<TorrentItem>> parseTorrentList(BeautifulSoup soup) async {
// 获取搜索配置
final searchConfig = await _getFinderConfig('search');
// 如果没有配置,返回空列表
if (searchConfig.isEmpty) return [];
return _staticParseTorrentList(
soup,
searchConfig,
_discountMapping ?? {},
_tagMapping ?? {},
_siteConfig.baseUrl,
_siteConfig.passKey ?? '',
_siteConfig.userId ?? '',
);
}
static Future<List<TorrentItem>> _staticParseTorrentList(
BeautifulSoup soup,
Map<String, dynamic> searchConfig,
Map<String, String> discountMapping,
Map<String, String> tagMapping,
String baseUrl,
String passKey,
String userId, [
List<String>? logs,
]) async {
final helper = _AdapterHelper();
final torrents = <TorrentItem>[];
try {
final rowsConfig = searchConfig['rows'] as Map<String, dynamic>?;
final fieldsConfig = searchConfig['fields'] as Map<String, dynamic>?;
if (rowsConfig == null || fieldsConfig == null) {
logs?.add('search.config.missing: $searchConfig');
return torrents;
}
final rowSelector = rowsConfig['selector'] as String?;
if (rowSelector == null) {
logs?.add('search.rowSelector.missing: $rowsConfig');
return torrents;
}
// 使用配置的选择器查找行
final rows = helper.findElementBySelector(soup, rowSelector);
for (final rowElement in rows) {
final row = rowElement as Bs4Element;
try {
// 提取种子ID - 如果提取失败则跳过当前行
final torrentIdConfig =
fieldsConfig['torrentId'] as Map<String, dynamic>?;
if (torrentIdConfig == null) {
continue;
}
final torrentIdList = await helper.extractFieldValue(
row,
torrentIdConfig,
);
final torrentId = torrentIdList.isNotEmpty ? torrentIdList.first : '';
if (torrentId.isEmpty) {
continue; // 种子ID提取失败,跳过当前行
}
// 提取其他字段
final torrentNameList = await helper.extractFieldValue(
row,
fieldsConfig['torrentName'] as Map<String, dynamic>? ?? {},
);
final torrentName = torrentNameList.isNotEmpty
? torrentNameList.first