Skip to content

基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。

basic bangumi list support done

Predidit53cc6829b1d0
diff --git a/assets/images/loading.png b/assets/images/loading.png
new file mode 100644
index 00000000..357ae73f
Binary files /dev/null and b/assets/images/loading.png differ
diff --git a/assets/images/noface.jpeg b/assets/images/noface.jpeg
new file mode 100644
index 00000000..16639025
Binary files /dev/null and b/assets/images/noface.jpeg differ
diff --git a/lib/bean/card/bangumi_card.dart b/lib/bean/card/bangumi_card.dart
new file mode 100644
index 00000000..11b09223
--- /dev/null
+++ b/lib/bean/card/bangumi_card.dart
@@ -0,0 +1,111 @@
+import 'package:flutter/material.dart';
+import 'package:kazumi/utils/constans.dart';
+import 'package:kazumi/utils/utils.dart';
+import 'package:kazumi/modules/bangumi/calendar_module.dart';
+import 'package:kazumi/bean/card/network_img_layer.dart';
+import 'package:kazumi/pages/menu/menu.dart';
+import 'package:provider/provider.dart';
+
+// 视频卡片 - 垂直布局
+class BangumiCardV extends StatelessWidget {
+ const BangumiCardV({
+ super.key,
+ required this.bangumiItem,
+ this.longPress,
+ this.longPressEnd,
+ });
+
+ final BangumiItem bangumiItem;
+ final Function()? longPress;
+ final Function()? longPressEnd;
+
+ @override
+ Widget build(BuildContext context) {
+ String heroTag = Utils.makeHeroTag(bangumiItem.id);
+ // final PlayerController playerController = Modular.get<PlayerController>();
+ final navigationBarState = Provider.of<NavigationBarState>(context);
+ return Card(
+ elevation: 0,
+ clipBehavior: Clip.hardEdge,
+ margin: EdgeInsets.zero,
+ child: GestureDetector(
+ child: InkWell(
+ onTap: () async {
+
+ },
+ child: Column(
+ children: [
+ ClipRRect(
+ borderRadius: const BorderRadius.only(
+ topLeft: StyleString.imgRadius,
+ topRight: StyleString.imgRadius,
+ bottomLeft: StyleString.imgRadius,
+ bottomRight: StyleString.imgRadius,
+ ),
+ child: AspectRatio(
+ aspectRatio: 0.65,
+ child: LayoutBuilder(builder: (context, boxConstraints) {
+ final double maxWidth = boxConstraints.maxWidth;
+ final double maxHeight = boxConstraints.maxHeight;
+ return Stack(
+ children: [
+ Hero(
+ tag: heroTag,
+ child: NetworkImgLayer(
+ src: bangumiItem.images?['large'] ?? '',
+ width: maxWidth,
+ height: maxHeight,
+ ),
+ ),
+ ],
+ );
+ }),
+ ),
+ ),
+ BangumiContent(bangumiItem: bangumiItem)
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+class BangumiContent extends StatelessWidget {
+ const BangumiContent({super.key, required this.bangumiItem});
+ // ignore: prefer_typing_uninitialized_variables
+ final BangumiItem bangumiItem;
+ @override
+ Widget build(BuildContext context) {
+ return Expanded(
+ child: Padding(
+ // 多列
+ padding: const EdgeInsets.fromLTRB(4, 5, 0, 3),
+ // 单列
+ // padding: const EdgeInsets.fromLTRB(14, 10, 4, 8),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ // mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ bangumiItem.nameCn ?? '',
+ textAlign: TextAlign.start,
+ style: const TextStyle(
+ fontWeight: FontWeight.w500,
+ letterSpacing: 0.3,
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ )),
+ ],
+ ),
+ const SizedBox(height: 1),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/bean/card/network_img_layer.dart b/lib/bean/card/network_img_layer.dart
new file mode 100644
index 00000000..0d126197
--- /dev/null
+++ b/lib/bean/card/network_img_layer.dart
@@ -0,0 +1,117 @@
+import 'package:cached_network_image/cached_network_image.dart';
+import 'package:flutter/material.dart';
+import 'package:kazumi/utils/constans.dart';
+import 'package:kazumi/utils/extension.dart';
+
+class NetworkImgLayer extends StatelessWidget {
+ const NetworkImgLayer({
+ super.key,
+ this.src,
+ required this.width,
+ required this.height,
+ this.type,
+ this.fadeOutDuration,
+ this.fadeInDuration,
+ // 图片质量 默认1%
+ this.quality,
+ this.origAspectRatio,
+ });
+
+ final String? src;
+ final double width;
+ final double height;
+ final String? type;
+ final Duration? fadeOutDuration;
+ final Duration? fadeInDuration;
+ final int? quality;
+ final double? origAspectRatio;
+
+ @override
+ Widget build(BuildContext context) {
+ final String imageUrl = src ?? '';
+ int? memCacheWidth, memCacheHeight;
+ double aspectRatio = (width / height).toDouble();
+
+ void setMemCacheSizes() {
+ if (aspectRatio > 1) {
+ memCacheHeight = height.cacheSize(context);
+ } else if (aspectRatio < 1) {
+ memCacheWidth = width.cacheSize(context);
+ } else {
+ if (origAspectRatio != null && origAspectRatio! > 1) {
+ memCacheWidth = width.cacheSize(context);
+ } else if (origAspectRatio != null && origAspectRatio! < 1) {
+ memCacheHeight = height.cacheSize(context);
+ } else {
+ memCacheWidth = width.cacheSize(context);
+ memCacheHeight = height.cacheSize(context);
+ }
+ }
+ }
+
+ setMemCacheSizes();
+
+ if (memCacheWidth == null && memCacheHeight == null) {
+ memCacheWidth = width.toInt();
+ }
+
+ return src != '' && src != null
+ ? ClipRRect(
+ clipBehavior: Clip.antiAlias,
+ borderRadius: BorderRadius.circular(
+ type == 'avatar'
+ ? 50
+ : type == 'emote'
+ ? 0
+ : StyleString.imgRadius.x,
+ ),
+ child: CachedNetworkImage(
+ imageUrl: imageUrl,
+ width: width,
+ height: height,
+ memCacheWidth: memCacheWidth,
+ memCacheHeight: memCacheHeight,
+ fit: BoxFit.cover,
+ fadeOutDuration:
+ fadeOutDuration ?? const Duration(milliseconds: 120),
+ fadeInDuration:
+ fadeInDuration ?? const Duration(milliseconds: 120),
+ filterQuality: FilterQuality.high,
+ errorWidget: (BuildContext context, String url, Object error) =>
+ placeholder(context),
+ placeholder: (BuildContext context, String url) =>
+ placeholder(context),
+ ),
+ )
+ : placeholder(context);
+ }
+
+ Widget placeholder(BuildContext context) {
+ return Container(
+ width: width,
+ height: height,
+ clipBehavior: Clip.antiAlias,
+ decoration: BoxDecoration(
+ color: Theme.of(context).colorScheme.onInverseSurface.withOpacity(0.4),
+ borderRadius: BorderRadius.circular(type == 'avatar'
+ ? 50
+ : type == 'emote'
+ ? 0
+ : StyleString.imgRadius.x),
+ ),
+ child: type == 'bg'
+ ? const SizedBox()
+ : Center(
+ child: Image.asset(
+ type == 'avatar'
+ ? 'assets/images/noface.jpeg'
+ : 'assets/images/loading.png',
+ width: width,
+ height: height,
+ cacheWidth: width.cacheSize(context),
+ cacheHeight: height.cacheSize(context),
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/modules/bangumi/calendar_module.dart b/lib/modules/bangumi/calendar_module.dart
new file mode 100644
index 00000000..2c433d15
--- /dev/null
+++ b/lib/modules/bangumi/calendar_module.dart
@@ -0,0 +1,122 @@
+class Weekday {
+ String? en;
+ String? cn;
+ String? ja;
+ int? id;
+
+ Weekday({this.en, this.cn, this.ja, this.id});
+
+ factory Weekday.fromJson(Map<String, dynamic> json) {
+ return Weekday(
+ en: json['en'],
+ cn: json['cn'],
+ ja: json['ja'],
+ id: json['id'],
+ );
+ }
+}
+
+class RatingCount {
+ int? count1;
+ int? count2;
+ int? count3;
+ int? count4;
+ int? count5;
+ int? count6;
+ int? count7;
+ int? count8;
+ int? count9;
+ int? count10;
+
+ RatingCount({
+ this.count1,
+ this.count2,
+ this.count3,
+ this.count4,
+ this.count5,
+ this.count6,
+ this.count7,
+ this.count8,
+ this.count9,
+ this.count10,
+ });
+
+ factory RatingCount.fromJson(Map<String, dynamic> json) {
+ return RatingCount(
+ count1: json['1'],
+ count2: json['2'],
+ count3: json['3'],
+ count4: json['4'],
+ count5: json['5'],
+ count6: json['6'],
+ count7: json['7'],
+ count8: json['8'],
+ count9: json['9'],
+ count10: json['10'],
+ );
+ }
+}
+
+class Rating {
+ int total;
+ RatingCount count;
+ double score;
+
+ Rating({required this.total, required this.count, required this.score});
+
+ factory Rating.fromJson(Map<String, dynamic> json) {
+ return Rating(
+ total: json['total'],
+ count: RatingCount.fromJson(json['count']),
+ score: json['score'].toDouble(),
+ );
+ }
+}
+
+class BangumiItem {
+ int? id;
+ String? url;
+ int? type;
+ String? name;
+ String? nameCn;
+ String? summary;
+ String? airDate;
+ int? airWeekday;
+ Rating? rating;
+ int? rank;
+ Map<String, String>? images;
+ Map<String, int>? collection;
+
+ BangumiItem({
+ this.id,
+ this.url,
+ this.type,
+ this.name,
+ this.nameCn,
+ this.summary,
+ this.airDate,
+ this.airWeekday,
+ this.rating,
+ this.rank,
+ this.images,
+ this.collection,
+ });
+
+ factory BangumiItem.fromJson(Map<String, dynamic> json) {
+ return BangumiItem(
+ id: json['id'],
+ url: json['url'],
+ type: json['type'],
+ name: json['name'],
+ nameCn: json['name_cn'] == '' ? json['name'] : json['name_cn'],
+ summary: json['summary'],
+ airDate: json['air_date'],
+ airWeekday: json['air_weekday'],
+ rating: Rating.fromJson(json['rating']),
+ rank: json['rank'],
+ images: Map<String, String>.from(json['images']),
+ collection: Map<String, int>.from(json['collection']),
+ );
+ }
+}
+
diff --git a/lib/pages/error/http_error.dart b/lib/pages/error/http_error.dart
new file mode 100644
index 00000000..616e9d7a
--- /dev/null
+++ b/lib/pages/error/http_error.dart
@@ -0,0 +1,46 @@
+import 'package:flutter/material.dart';
+
+class HttpError extends StatelessWidget {
+ const HttpError(
+ {required this.errMsg, required this.fn, this.btnText, super.key});
+
+ final String? errMsg;
+ final Function()? fn;
+ final String? btnText;
+
+ @override
+ Widget build(BuildContext context) {
+ return SliverToBoxAdapter(
+ child: SizedBox(
+ height: 400,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ const SizedBox(height: 30),
+ Text(
+ errMsg ?? '请求异常',
+ textAlign: TextAlign.center,
+ style: Theme.of(context).textTheme.titleSmall,
+ ),
+ const SizedBox(height: 20),
+ FilledButton.tonal(
+ onPressed: () {
+ fn!();
+ },
+ style: ButtonStyle(
+ backgroundColor: MaterialStateProperty.resolveWith((states) {
+ return Theme.of(context).colorScheme.primary.withAlpha(20);
+ }),
+ ),
+ child: Text(
+ btnText ?? '点击重试',
+ style: TextStyle(color: Theme.of(context).colorScheme.primary),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/pages/index_module.dart b/lib/pages/index_module.dart
index b32160c0..8e4924db 100644
--- a/lib/pages/index_module.dart
+++ b/lib/pages/index_module.dart
@@ -3,6 +3,7 @@ import 'package:flutter_modular/flutter_modular.dart';
import 'package:kazumi/pages/router.dart';
import 'package:kazumi/pages/init_page.dart';
import 'package:flutter/material.dart';
+import 'package:kazumi/pages/popular/popular_controller.dart';
class IndexModule extends Module {
@@ -11,7 +12,7 @@ class IndexModule extends Module {
@override
void binds(i) {
- // i.addSingleton(PopularController.new);
+ i.addSingleton(PopularController.new);
}
@override
@@ -22,7 +23,7 @@ class IndexModule extends Module {
ChildRoute(
"/error",
child: (_) => Scaffold(
- appBar: AppBar (title: const Text("BiliNeo")),
+ appBar: AppBar (title: const Text("Kazumi")),
body: const Center(child: Text("初始化失败")),
),
),
diff --git a/lib/pages/popular/popular_controller.dart b/lib/pages/popular/popular_controller.dart
new file mode 100644
index 00000000..d1920dfa
--- /dev/null
+++ b/lib/pages/popular/popular_controller.dart
@@ -0,0 +1,30 @@
+import 'package:flutter/material.dart';
+import 'package:kazumi/request/bangumi.dart';
+import 'package:kazumi/modules/bangumi/calendar_module.dart';
+import 'package:mobx/mobx.dart';
+
+part 'popular_controller.g.dart';
+
+class PopularController = _PopularController with _$PopularController;
+
+abstract class _PopularController with Store {
+ final ScrollController scrollController = ScrollController();
+
+ @observable
+ ObservableList<BangumiItem> bangumiList = ObservableList.of([BangumiItem()]);
+
+ List<String> _items = [];
+ List<String> get items => _items;
+ List<BangumiItem> get listValue => bangumiList.toList();
+
+ double scrollOffset = 0.0;
+ bool isLoadingMore = true;
+
+ @action
+ Future queryBangumiListFeed() async {
+ var result = await BangumiHTTP.getBangumiList();
+ bangumiList.addAll(result);
+ isLoadingMore = false;
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/lib/pages/popular/popular_controller.g.dart b/lib/pages/popular/popular_controller.g.dart
new file mode 100644
index 00000000..60092a11
--- /dev/null
+++ b/lib/pages/popular/popular_controller.g.dart
@@ -0,0 +1,43 @@
+// GENERATED CODE - DO NOT MODIFY BY HAND
+
+part of 'popular_controller.dart';
+
+// **************************************************************************
+// StoreGenerator
+// **************************************************************************
+
+// ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic, no_leading_underscores_for_local_identifiers
+
+mixin _$PopularController on _PopularController, Store {
+ late final _$bangumiListAtom =
+ Atom(name: '_PopularController.bangumiList', context: context);
+
+ @override
+ ObservableList<BangumiItem> get bangumiList {
+ _$bangumiListAtom.reportRead();
+ return super.bangumiList;
+ }
+
+ @override
+ set bangumiList(ObservableList<BangumiItem> value) {
+ _$bangumiListAtom.reportWrite(value, super.bangumiList, () {
+ super.bangumiList = value;
+ });
+ }
+
+ late final _$queryBangumiListFeedAsyncAction =
+ AsyncAction('_PopularController.queryBangumiListFeed', context: context);
+
+ @override
+ Future<dynamic> queryBangumiListFeed() {
+ return _$queryBangumiListFeedAsyncAction
+ .run(() => super.queryBangumiListFeed());
+ }
+
+ @override
+ String toString() {
+ return '''
+bangumiList: ${bangumiList}
+ ''';
+ }
+}
diff --git a/lib/pages/popular/popular_page.dart b/lib/pages/popular/popular_page.dart
index d0994229..2a69e5a4 100644
--- a/lib/pages/popular/popular_page.dart
+++ b/lib/pages/popular/popular_page.dart
@@ -1,18 +1,172 @@
+import 'dart:io';
+import 'dart:async';
+
import 'package:flutter/material.dart';
+import 'package:flutter_modular/flutter_modular.dart';
+import 'package:kazumi/pages/popular/popular_controller.dart';
+import 'package:kazumi/utils/constans.dart';
+import 'package:kazumi/pages/error/http_error.dart';
+import 'package:flutter_mobx/flutter_mobx.dart';
+import 'package:kazumi/bean/card/bangumi_card.dart';
+import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
+import 'package:flutter/services.dart';
class PopularPage extends StatefulWidget {
- const PopularPage({
- super.key
- });
+ const PopularPage({super.key});
@override
State<PopularPage> createState() => _PopularPageState();
}
-class _PopularPageState extends State<PopularPage> {
+class _PopularPageState extends State<PopularPage>
+ with AutomaticKeepAliveClientMixin {
+ DateTime? _lastPressedAt;
+ bool timeout = false;
+ final ScrollController scrollController = ScrollController();
+ final PopularController popularController = Modular.get<PopularController>();
+
+ @override
+ bool get wantKeepAlive => true;
+
+ @override
+ void initState() {
+ super.initState();
+ debugPrint('Popular初始化成功');
+ timeout = false;
+ if (popularController.bangumiList.length < 5) {
+ debugPrint('Popular缓存列表为空, 尝试重加载');
+ Timer(const Duration(seconds: 3), () {
+ timeout = true;
+ });
+ popularController.scrollOffset = 0.0;
+ popularController.queryBangumiListFeed();
+ }
+ }
+
+ @override
+ void dispose() {
+ // popularController.scrollOffset = scrollController.offset;
+ scrollController.removeListener(() {});
+ debugPrint('popular 模块已卸载, 监听器移除');
+ super.dispose();
+ }
+
+ void onBackPressed(BuildContext context) {
+ if (_lastPressedAt == null ||
+ DateTime.now().difference(_lastPressedAt!) >
+ const Duration(seconds: 2)) {
+ // 两次点击时间间隔超过2秒,重新记录时间戳
+ _lastPressedAt = DateTime.now();
+ SmartDialog.showToast("再按一次退出应用");
+ return;
+ }
+ SystemNavigator.pop(); // 退出应用
+ }
+
@override
Widget build(BuildContext context) {
- return const Placeholder();
+ super.build(context);
+ var themedata = Theme.of(context);
+ WidgetsBinding.instance?.addPostFrameCallback((_) {
+ debugPrint('尝试恢复状态');
+ scrollController.jumpTo(popularController.scrollOffset);
+ debugPrint('Popular加载完成');
+ });
+ return PopScope(
+ canPop: false,
+ onPopInvoked: (bool didPop) async {
+ onBackPressed(context);
+ },
+ child: SafeArea(
+ child: RefreshIndicator(
+ onRefresh: () async {
+ await popularController.queryBangumiListFeed();
+ },
+ child: Scaffold(
+ body: CustomScrollView(
+ controller: scrollController,
+ slivers: [
+ SliverToBoxAdapter(
+ child: Padding(
+ padding:
+ const EdgeInsets.only(top: 10, bottom: 10, left: 16),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(
+ '每日放送',
+ style: Theme.of(context).textTheme.titleMedium,
+ ),
+ ],
+ ),
+ ),
+ ),
+ SliverPadding(
+ padding: const EdgeInsets.fromLTRB(
+ StyleString.safeSpace, 0, StyleString.safeSpace, 0),
+ sliver: Observer(builder: (context) {
+ if (popularController.bangumiList.length < 5 &&
+ timeout == true) {
+ return HttpError(
+ errMsg: '加载推荐流错误',
+ fn: () {
+ popularController.queryBangumiListFeed();
+ },
+ );
+ }
+ if (popularController.bangumiList.length < 5 &&
+ timeout == false) {
+ return const SliverToBoxAdapter(
+ child: SizedBox(
+ height: 600,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ CircularProgressIndicator(),
+ ],
+ )),
+ );
+ }
+ return contentGrid(popularController.bangumiList);
+ })),
+ ],
+ ),
+ floatingActionButton: FloatingActionButton(
+ onPressed: () {
+ scrollController.jumpTo(0.0);
+ popularController.scrollOffset = 0.0;
+ },
+ child: const Icon(Icons.arrow_upward),
+ ),
+ backgroundColor: themedata.colorScheme.primaryContainer,
+ ),
+ ),
+ ),
+ );
}
-}
+ Widget contentGrid(bangumiList) {
+ int crossCount = Platform.isWindows || Platform.isLinux ? 6 : 3;
+ return SliverGrid(
+ gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
+ // 行间距
+ mainAxisSpacing: StyleString.cardSpace - 2,
+ // 列间距
+ crossAxisSpacing: StyleString.cardSpace,
+ // 列数
+ crossAxisCount: crossCount,
+ mainAxisExtent: MediaQuery.of(context).size.width / crossCount / 0.65 +
+ MediaQuery.textScalerOf(context).scale(32.0),
+ ),
+ delegate: SliverChildBuilderDelegate(
+ (BuildContext context, int index) {
+ return bangumiList!.isNotEmpty
+ ? BangumiCardV(bangumiItem: bangumiList[index])
+ : null;
+ },
+ childCount: bangumiList!.isNotEmpty ? bangumiList!.length : 10,
+ ),
+ );
+ }
+}
diff --git a/lib/request/api.dart b/lib/request/api.dart
new file mode 100644
index 00000000..c47a08a8
--- /dev/null
+++ b/lib/request/api.dart
@@ -0,0 +1,4 @@
+class Api {
+ // 每日放送
+ static const String bangumiCalendar = 'https://api.bgm.tv/calendar';
+}
\ No newline at end of file
diff --git a/lib/request/bangumi.dart b/lib/request/bangumi.dart
new file mode 100644
index 00000000..4b68cea0
--- /dev/null
+++ b/lib/request/bangumi.dart
@@ -0,0 +1,24 @@
+import 'package:flutter/material.dart';
+import 'package:kazumi/request/api.dart';
+import 'package:kazumi/request/request.dart';
+import 'package:kazumi/modules/bangumi/calendar_module.dart';
+
+class BangumiHTTP {
+ static Future getBangumiList({int? page}) async {
+ List<BangumiItem> bangumiList = [];
+ try {
+ var res = await Request().get(Api.bangumiCalendar);
+ final jsonData = res.data;
+ final jsonList = jsonData[0]['items'];
+ for (dynamic jsonItem in jsonList) {
+ if (jsonItem is Map<String, dynamic>) {
+ bangumiList.add(BangumiItem.fromJson(jsonItem));
+ }
+ }
+ } catch (e) {
+ debugPrint('解析推荐列表错误 ${e.toString()}');
+ debugPrint('当前列表长度 ${bangumiList.length}');
+ }
+ return bangumiList;
+ }
+}
diff --git a/lib/request/interceptor.dart b/lib/request/interceptor.dart
new file mode 100644
index 00000000..7ecd804f
--- /dev/null
+++ b/lib/request/interceptor.dart
@@ -0,0 +1,72 @@
+import 'package:dio/dio.dart';
+import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
+import 'package:connectivity_plus/connectivity_plus.dart';
+
+class ApiInterceptor extends Interceptor {
+ // static Box setting = GStorage.setting;
+ @override
+ void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
+ handler.next(options);
+ }
+
+ @override
+ void onResponse(Response response, ResponseInterceptorHandler handler) {
+ handler.next(response);
+ }
+
+ @override
+ void onError(DioException err, ErrorInterceptorHandler handler) async {
+ String url = err.requestOptions.uri.toString();
+ if (!url.contains('heartBeat')) {
+ SmartDialog.showToast(
+ await dioError(err),
+ displayType: SmartToastType.onlyRefresh,
+ );
+ }
+ super.onError(err, handler);
+ // super.onError(err, handler);
+ }
+
+ static Future<String> dioError(DioException error) async {
+ switch (error.type) {
+ case DioExceptionType.badCertificate:
+ return '证书有误!';
+ case DioExceptionType.badResponse:
+ return '服务器异常,请稍后重试!';
+ case DioExceptionType.cancel:
+ return '请求已被取消,请重新请求';
+ case DioExceptionType.connectionError:
+ return '连接错误,请检查网络设置';
+ case DioExceptionType.connectionTimeout:
+ return '网络连接超时,请检查网络设置';
+ case DioExceptionType.receiveTimeout:
+ return '响应超时,请稍后重试!';
+ case DioExceptionType.sendTimeout:
+ return '发送请求超时,请检查网络设置';
+ case DioExceptionType.unknown:
+ final String res = await checkConnect();
+ return '$res 网络异常';
+ }
+ }
+
+ static Future<String> checkConnect() async {
+ final ConnectivityResult connectivityResult =
+ await Connectivity().checkConnectivity();
+ switch (connectivityResult) {
+ case ConnectivityResult.mobile:
+ return '正在使用移动流量';
+ case ConnectivityResult.wifi:
+ return '正在使用wifi';
+ case ConnectivityResult.ethernet:
+ return '正在使用局域网';
+ case ConnectivityResult.vpn:
+ return '正在使用代理网络';
+ case ConnectivityResult.other:
+ return '正在使用其他网络';
+ case ConnectivityResult.none:
+ return '未连接到任何网络';
+ default:
+ return '';
+ }
+ }
+}
diff --git a/lib/request/request.dart b/lib/request/request.dart
index e69de29b..a6daa852 100644
--- a/lib/request/request.dart
+++ b/lib/request/request.dart
@@ -0,0 +1,174 @@
+import 'dart:io';
+
+import 'package:dio/dio.dart';
+import 'package:dio/io.dart';
+import 'package:flutter/material.dart';
+// import 'package:hive/hive.dart';
+// import 'package:kazumi/utils/storage.dart';
+import 'package:kazumi/request/interceptor.dart';
+
+class Request {
+ static final Request _instance = Request._internal();
+ static late final Dio dio;
+ // Box setting = GStorage.setting;
+ // static Box localCache = GStorage.localCache;
+ // late bool enableSystemProxy;
+ factory Request() => _instance;
+
+ // 初始化 (一般只在应用启动时调用)
+ static setCookie() {
+ setOptionsHeaders();
+ }
+
+ // 设置请求头
+ static setOptionsHeaders() {
+ dio.options.headers['referer'] = '';
+ }
+
+ // 设置代理
+ static setProxy() {
+ // var systemProxyHost =
+ // localCache.get(LocalCacheKey.systemProxyHost, defaultValue: '');
+ // var systemProxyPort =
+ // localCache.get(LocalCacheKey.systemProxyPort, defaultValue: '');
+ // dio.httpClientAdapter = IOHttpClientAdapter(
+ // createHttpClient: () {
+ // final HttpClient client = HttpClient();
+ // // Config the client.
+ // client.findProxy = (Uri uri) {
+ // // return 'PROXY host:port';
+ // return 'PROXY $systemProxyHost:$systemProxyPort';
+ // };
+ // client.badCertificateCallback =
+ // (X509Certificate cert, String host, int port) => true;
+ // return client;
+ // },
+ // );
+ // debugPrint('代理设置更新成功');
+ }
+
+ // 禁用代理
+ static disableProxy() {
+ dio.httpClientAdapter = IOHttpClientAdapter(
+ createHttpClient: () {
+ final HttpClient client = HttpClient();
+ return client;
+ },
+ );
+ debugPrint('代理禁用');
+ }
+
+ Request._internal() {
+ //BaseOptions、Options、RequestOptions 都可以配置参数,优先级别依次递增,且可以根据优先级别覆盖参数
+ BaseOptions options = BaseOptions(
+ //请求基地址,可以包含子路径
+ baseUrl: '',
+ //连接服务器超时时间,单位是毫秒.
+ connectTimeout: const Duration(milliseconds: 12000),
+ //响应流上前后两次接受到数据的间隔,单位为毫秒。
+ receiveTimeout: const Duration(milliseconds: 12000),
+ //Http请求头.
+ headers: {},
+ );
+
+ // enableSystemProxy = setting.get(SettingBoxKey.enableSystemProxy,
+ // defaultValue: false) as bool;
+
+ dio = Dio(options);
+ debugPrint('Dio 初始化完成');
+
+ // if (enableSystemProxy) {
+ // setProxy();
+ // debugPrint('系统代理启用');
+ // }
+
+ // 拦截器
+ dio.interceptors.add(ApiInterceptor());
+
+ // 日志拦截器 输出请求、响应内容
+ dio.interceptors.add(LogInterceptor(
+ request: false,
+ requestHeader: false,
+ responseHeader: false,
+ ));
+
+ dio.transformer = BackgroundTransformer();
+ dio.options.validateStatus = (int? status) {
+ return status! >= 200 && status < 300;
+ };
+ }
+
+ get(url, {data, options, cancelToken, extra}) async {
+ Response response;
+ final Options options = Options();
+ ResponseType resType = ResponseType.json;
+ if (extra != null) {
+ resType = extra!['resType'] ?? ResponseType.json;
+ if (extra['ua'] != null) {
+ options.headers = {'user-agent': headerUa(type: extra['ua'])};
+ }
+ }
+ options.responseType = resType;
+
+ try {
+ response = await dio.get(
+ url,
+ queryParameters: data,
+ options: options,
+ cancelToken: cancelToken,
+ );
+ return response;
+ } on DioException catch (e) {
+ Response errResponse = Response(
+ data: {
+ 'message': await ApiInterceptor.dioError(e)
+ }, // 将自定义 Map 数据赋值给 Response 的 data 属性
+ statusCode: 200,
+ requestOptions: RequestOptions(),
+ );
+ return errResponse;
+ }
+ }
+
+ post(url, {data, queryParameters, options, cancelToken, extra}) async {
+ // print('post-data: $data');
+ Response response;
+ try {
+ response = await dio.post(
+ url,
+ data: data,
+ queryParameters: queryParameters,
+ options: options,
+ cancelToken: cancelToken,
+ );
+ // print('post success: ${response.data}');
+ return response;
+ } on DioException catch (e) {
+ Response errResponse = Response(
+ data: {
+ 'message': await ApiInterceptor.dioError(e)
+ }, // 将自定义 Map 数据赋值给 Response 的 data 属性
+ statusCode: 200,
+ requestOptions: RequestOptions(),
+ );
+ return errResponse;
+ }
+ }
+
+ String headerUa({type = 'mob'}) {
+ String headerUa = '';
+ if (type == 'mob') {
+ if (Platform.isIOS) {
+ headerUa =
+ 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1 Mobile/15E148 Safari/604.1';
+ } else {
+ headerUa =
+ 'Mozilla/5.0 (Linux; Android 10; SM-G975F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Mobile Safari/537.36';
+ }
+ } else {
+ headerUa =
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.2 Safari/605.1.15';
+ }
+ return headerUa;
+ }
+}
\ No newline at end of file
diff --git a/lib/utils/constans.dart b/lib/utils/constans.dart
new file mode 100644
index 00000000..b7c444e0
--- /dev/null
+++ b/lib/utils/constans.dart
@@ -0,0 +1,9 @@
+import 'package:flutter/material.dart';
+
+class StyleString {
+ static const double cardSpace = 8;
+ static const double safeSpace = 12;
+ static BorderRadius mdRadius = BorderRadius.circular(10);
+ static const Radius imgRadius = Radius.circular(10);
+ static const double aspectRatio = 16 / 10;
+}
\ No newline at end of file
diff --git a/lib/utils/extension.dart b/lib/utils/extension.dart
new file mode 100644
index 00000000..2f0b8e76
--- /dev/null
+++ b/lib/utils/extension.dart
@@ -0,0 +1,8 @@
+import 'package:flutter/material.dart';
+
+extension ImageExtension on num {
+ int cacheSize(BuildContext context) {
+ return (this * MediaQuery.of(context).devicePixelRatio).round();
+ }
+}
+
diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart
new file mode 100644
index 00000000..a53d04d8
--- /dev/null
+++ b/lib/utils/utils.dart
@@ -0,0 +1,287 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'dart:math';
+import 'package:crypto/crypto.dart';
+import 'package:path_provider/path_provider.dart';
+
+class Utils {
+ static final Random random = Random();
+
+ static Future<String> getCookiePath() async {
+ final Directory tempDir = await getApplicationSupportDirectory();
+ final String tempPath = "${tempDir.path}/.plpl/";
+ final Directory dir = Directory(tempPath);
+ final bool b = await dir.exists();
+ if (!b) {
+ dir.createSync(recursive: true);
+ }
+ return tempPath;
+ }
+
+ static String numFormat(dynamic number) {
+ if (number == null) {
+ return '0';
+ }
+ if (number is String) {
+ return number;
+ }
+ final String res = (number / 10000).toString();
+ if (int.parse(res.split('.')[0]) >= 1) {
+ return '${(number / 10000).toStringAsFixed(1)}万';
+ } else {
+ return number.toString();
+ }
+ }
+
+ static String timeFormat(dynamic time) {
+ // 1小时内
+ if (time is String && time.contains(':')) {
+ return time;
+ }
+ if (time < 3600) {
+ final int minute = time ~/ 60;
+ final double res = time / 60;
+ if (minute != res) {
+ return '${minute < 10 ? '0$minute' : minute}:${(time - minute * 60) < 10 ? '0${(time - minute * 60)}' : (time - minute * 60)}';
+ } else {
+ return '$minute:00';
+ }
+ } else {
+ final int hour = time ~/ 3600;
+ final String hourStr = hour < 10 ? '0$hour' : hour.toString();
+ var a = timeFormat(time - hour * 3600);
+ return '$hourStr:$a';
+ }
+ }
+
+ // 完全相对时间显示
+ static String formatTimestampToRelativeTime(timeStamp) {
+ var difference = DateTime.now()
+ .difference(DateTime.fromMillisecondsSinceEpoch(timeStamp * 1000));
+
+ if (difference.inDays > 365) {
+ return '${difference.inDays ~/ 365}年前';
+ } else if (difference.inDays > 30) {
+ return '${difference.inDays ~/ 30}个月前';
+ } else if (difference.inDays > 0) {
+ return '${difference.inDays}天前';
+ } else if (difference.inHours > 0) {
+ return '${difference.inHours}小时前';
+ } else if (difference.inMinutes > 0) {
+ return '${difference.inMinutes}分钟前';
+ } else {
+ return '刚刚';
+ }
+ }
+
+ // 时间显示,刚刚,x分钟前
+ static String dateFormat(timeStamp, {formatType = 'list'}) {
+ // 当前时间
+ int time = (DateTime.now().millisecondsSinceEpoch / 1000).round();
+ // 对比
+ int distance = (time - timeStamp).toInt();
+ // 当前年日期
+ String currentYearStr = 'MM月DD日 hh:mm';
+ String lastYearStr = 'YY年MM月DD日 hh:mm';
+ if (formatType == 'detail') {
+ currentYearStr = 'MM-DD hh:mm';
+ lastYearStr = 'YY-MM-DD hh:mm';
+ return CustomStamp_str(
+ timestamp: timeStamp,
+ date: lastYearStr,
+ toInt: false,
+ formatType: formatType);
+ }
+ if (distance <= 60) {
+ return '刚刚';
+ } else if (distance <= 3600) {
+ return '${(distance / 60).floor()}分钟前';
+ } else if (distance <= 43200) {
+ return '${(distance / 60 / 60).floor()}小时前';
+ } else if (DateTime.fromMillisecondsSinceEpoch(time * 1000).year ==
+ DateTime.fromMillisecondsSinceEpoch(timeStamp * 1000).year) {
+ return CustomStamp_str(
+ timestamp: timeStamp,
+ date: currentYearStr,
+ toInt: false,
+ formatType: formatType);
+ } else {
+ return CustomStamp_str(
+ timestamp: timeStamp,
+ date: lastYearStr,
+ toInt: false,
+ formatType: formatType);
+ }
+ }
+
+ // 时间戳转时间
+ static String CustomStamp_str(
+ {int? timestamp, // 为空则显示当前时间
+ String? date, // 显示格式,比如:'YY年MM月DD日 hh:mm:ss'
+ bool toInt = true, // 去除0开头
+ String? formatType}) {
+ timestamp ??= (DateTime.now().millisecondsSinceEpoch / 1000).round();
+ String timeStr =
+ (DateTime.fromMillisecondsSinceEpoch(timestamp * 1000)).toString();
+
+ dynamic dateArr = timeStr.split(' ')[0];
+ dynamic timeArr = timeStr.split(' ')[1];
+
+ String YY = dateArr.split('-')[0];
+ String MM = dateArr.split('-')[1];
+ String DD = dateArr.split('-')[2];
+
+ String hh = timeArr.split(':')[0];
+ String mm = timeArr.split(':')[1];
+ String ss = timeArr.split(':')[2];
+
+ ss = ss.split('.')[0];
+
+ // 去除0开头
+ if (toInt) {
+ MM = (int.parse(MM)).toString();
+ DD = (int.parse(DD)).toString();
+ hh = (int.parse(hh)).toString();
+ mm = (int.parse(mm)).toString();
+ }
+
+ if (date == null) {
+ return timeStr;
+ }
+
+ // if (formatType == 'list' && int.parse(DD) > DateTime.now().day - 2) {
+ // return '昨天';
+ // }
+
+ date = date
+ .replaceAll('YY', YY)
+ .replaceAll('MM', MM)
+ .replaceAll('DD', DD)
+ .replaceAll('hh', hh)
+ .replaceAll('mm', mm)
+ .replaceAll('ss', ss);
+ if (int.parse(YY) == DateTime.now().year &&
+ int.parse(MM) == DateTime.now().month) {
+ // 当天
+ if (int.parse(DD) == DateTime.now().day) {
+ return '今天';
+ }
+ }
+ return date;
+ }
+
+ static String makeHeroTag(v) {
+ return v.toString() + random.nextInt(9999).toString();
+ }
+
+ static int duration(String duration) {
+ List timeList = duration.split(':');
+ int len = timeList.length;
+ if (len == 2) {
+ return int.parse(timeList[0]) * 60 + int.parse(timeList[1]);
+ }
+ if (len == 3) {
+ return int.parse(timeList[0]) * 3600 +
+ int.parse(timeList[1]) * 60 +
+ int.parse(timeList[2]);
+ }
+ return 0;
+ }
+
+ static int findClosestNumber(int target, List<int> numbers) {
+ int minDiff = 127;
+ late int closestNumber;
+ try {
+ for (int number in numbers) {
+ int diff = (number - target).abs();
+
+ if (diff < minDiff) {
+ minDiff = diff;
+ closestNumber = number;
+ }
+ }
+ } catch (_) {}
+ return closestNumber;
+ }
+
+ // 版本对比
+ static bool needUpdate(localVersion, remoteVersion) {
+ List<String> localVersionList = localVersion.split('.');
+ List<String> remoteVersionList = remoteVersion.split('v')[1].split('.');
+ for (int i = 0; i < localVersionList.length; i++) {
+ int localVersion = int.parse(localVersionList[i]);
+ int remoteVersion = int.parse(remoteVersionList[i]);
+ if (remoteVersion > localVersion) {
+ return true;
+ } else if (remoteVersion < localVersion) {
+ return false;
+ }
+ }
+ return false;
+ }
+
+ // 检查更新
+ static Future<bool> checkUpdata() async {
+ return true;
+ }
+
+ // 下载适用于当前系统的安装包
+ static Future matchVersion(data) async {}
+
+ // 时间戳转时间
+ static tampToSeektime(number) {
+ int hours = number ~/ 60;
+ int minutes = number % 60;
+
+ String formattedHours = hours.toString().padLeft(2, '0');
+ String formattedMinutes = minutes.toString().padLeft(2, '0');
+
+ return '$formattedHours:$formattedMinutes';
+ }
+
+ static String appSign(
+ Map<String, dynamic> params, String appkey, String appsec) {
+ params['appkey'] = appkey;
+ var searchParams = Uri(queryParameters: params).query;
+ var sortedParams = searchParams.split('&')..sort();
+ var sortedQueryString = sortedParams.join('&');
+
+ var appsecString = sortedQueryString + appsec;
+ var md5Digest = md5.convert(utf8.encode(appsecString));
+ var md5String = md5Digest.toString(); // 获取MD5哈希值
+
+ return md5String;
+ }
+
+ static List<int> generateRandomBytes(int minLength, int maxLength) {
+ return List<int>.generate(random.nextInt(maxLength - minLength + 1),
+ (_) => random.nextInt(0x60) + 0x20);
+ }
+
+ static String base64EncodeRandomString(int minLength, int maxLength) {
+ List<int> randomBytes = generateRandomBytes(minLength, maxLength);
+ return base64.encode(randomBytes);
+ }
+
+ static String jsonToWebVTT(Map<String, dynamic> json) {
+ var webvttContent = 'WEBVTT FILE\n\n';
+ int i = 1;
+ for (var entry in json['body']) {
+ final startTime = formatTime(entry['from']);
+ final endTime = formatTime(entry['to']);
+ final content = entry['content'];
+ webvttContent +=
+ '${i.toString()}\n$startTime --> $endTime\n$content\n\n';
+ i = i + 1;
+ }
+ return webvttContent;
+ }
+
+ static String formatTime(double seconds) {
+ final hours = seconds ~/ 3600;
+ final minutes = (seconds % 3600) ~/ 60;
+ final secs = seconds % 60;
+ return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${secs.toStringAsFixed(3).replaceAll('.', '.')}';
+ }
+}
diff --git a/pubspec.lock b/pubspec.lock
index 5a61ac1a..242d3b90 100644
--- a/pubspec.lock
+++ b/pubspec.lock
@@ -1387,15 +1387,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.13.0"
- webview_windows:
- dependency: "direct main"
- description:
- path: "."
- ref: main
- resolved-ref: "571e96e93de6df4a9f8bc1ddbcdb75d0cfc8d5b1"
- url: "https://github.com/Predidit/flutter-webview-windows.git"
- source: git
- version: "0.4.0"
win32:
dependency: transitive
description:
diff --git a/pubspec.yaml b/pubspec.yaml
index 7e8ad461..d871626c 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -75,10 +75,10 @@ dependencies:
git:
url: https://github.com/xiaoyaocz/flutter_ns_danmaku.git
ref: master
- webview_windows:
- git:
- url: https://github.com/Predidit/flutter-webview-windows.git
- ref: main
+ # webview_windows:
+ # git:
+ # url: https://github.com/Predidit/flutter-webview-windows.git
+ # ref: main
dev_dependencies:
flutter_test:
@@ -110,6 +110,8 @@ flutter:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
+ assets:
+ - assets/images/
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc
index 60de1648..4ac0d029 100644
--- a/windows/flutter/generated_plugin_registrant.cc
+++ b/windows/flutter/generated_plugin_registrant.cc
@@ -13,7 +13,6 @@
#include <screen_brightness_windows/screen_brightness_windows_plugin.h>
#include <screen_retriever/screen_retriever_plugin.h>
#include <url_launcher_windows/url_launcher_windows.h>
-#include <webview_windows/webview_windows_plugin.h>
#include <window_manager/window_manager_plugin.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
@@ -31,8 +30,6 @@ void RegisterPlugins(flutter::PluginRegistry* registry) {
registry->GetRegistrarForPlugin("ScreenRetrieverPlugin"));
UrlLauncherWindowsRegisterWithRegistrar(
registry->GetRegistrarForPlugin("UrlLauncherWindows"));
- WebviewWindowsPluginRegisterWithRegistrar(
- registry->GetRegistrarForPlugin("WebviewWindowsPlugin"));
WindowManagerPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("WindowManagerPlugin"));
}
diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake
index 618c5f41..84bea540 100644
--- a/windows/flutter/generated_plugins.cmake
+++ b/windows/flutter/generated_plugins.cmake
@@ -10,7 +10,6 @@ list(APPEND FLUTTER_PLUGIN_LIST
screen_brightness_windows
screen_retriever
url_launcher_windows
- webview_windows
window_manager
)