Skip to content

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

feat: bangumi interest (#2062)

LiggMax96bfa38f4912
diff --git a/lib/bean/card/bangumi_info_card.dart b/lib/bean/card/bangumi_info_card.dart
index a740b6f8..22d3dda8 100644
--- a/lib/bean/card/bangumi_info_card.dart
+++ b/lib/bean/card/bangumi_info_card.dart
@@ -200,36 +200,36 @@ class _BangumiInfoCardVState extends State<BangumiInfoCardV> {
),
),
if (!widget.isLoading)
- Row(
- children: [
- Text(
- widget.showRating
- ? '${widget.bangumiItem.ratingScore}'
- : '***',
- style: TextStyle(
- fontSize: 20,
- fontWeight: FontWeight.bold,
- color:
- Theme.of(context).colorScheme.primary,
+ Row(
+ children: [
+ Text(
+ widget.showRating
+ ? '${widget.bangumiItem.ratingScore}'
+ : '***',
+ style: TextStyle(
+ fontSize: 16,
+ fontWeight: FontWeight.bold,
+ color:
+ Theme.of(context).colorScheme.primary,
+ ),
),
- ),
- const SizedBox(width: 8),
- RatingBarIndicator(
- itemCount: 5,
- rating: widget.showRating
- ? widget.bangumiItem.ratingScore
- .toDouble() /
- 2
- : 0,
- itemBuilder: (context, index) => Icon(
- Icons.star_rounded,
- color:
- Theme.of(context).colorScheme.primary,
+ const SizedBox(width: 8),
+ RatingBarIndicator(
+ itemCount: 5,
+ rating: widget.showRating
+ ? widget.bangumiItem.ratingScore
+ .toDouble() /
+ 2
+ : 0,
+ itemBuilder: (context, index) => Icon(
+ Icons.star_rounded,
+ color:
+ Theme.of(context).colorScheme.primary,
+ ),
+ itemSize: 20.0,
),
- itemSize: 20.0,
- ),
- ],
- ),
+ ],
+ ),
SizedBox(height: 8),
Text(
'Bangumi Ranked:',
diff --git a/lib/bean/card/comments_card.dart b/lib/bean/card/comments_card.dart
index c3499014..81f308a0 100644
--- a/lib/bean/card/comments_card.dart
+++ b/lib/bean/card/comments_card.dart
@@ -10,6 +10,7 @@ class CommentsCard extends StatelessWidget {
required this.commentItem,
}) {
isBone = false;
+ isOwn = false;
}
CommentsCard.bone({
@@ -17,10 +18,20 @@ class CommentsCard extends StatelessWidget {
}) {
isBone = true;
commentItem = null;
+ isOwn = false;
+ }
+
+ CommentsCard.own({
+ super.key,
+ required this.commentItem,
+ }) {
+ isBone = false;
+ isOwn = true;
}
late final CommentItem? commentItem;
late final bool isBone;
+ late final bool isOwn;
@override
Widget build(BuildContext context) {
@@ -68,7 +79,22 @@ class CommentsCard extends StatelessWidget {
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Text(commentItem!.user.nickname),
+ Row(
+ spacing: 5,
+ children: [
+ Text(commentItem!.user.nickname),
+ if(isOwn)
+ Container(
+ padding: const EdgeInsets.symmetric(horizontal: 2),
+ decoration: BoxDecoration(
+ color: Theme.of(context).colorScheme.primary,
+ borderRadius: BorderRadius.circular(4),
+ ),
+ child: Text('我的吐槽',
+ style: TextStyle(fontSize: 12,color: Theme.of(context).colorScheme.primaryContainer),
+ ))
+ ],
+ ),
Text(dateFormat(commentItem!.comment.updatedAt)),
],
),
diff --git a/lib/modules/bangumi/bangumi_interest.dart b/lib/modules/bangumi/bangumi_interest.dart
new file mode 100644
index 00000000..fcc439d4
--- /dev/null
+++ b/lib/modules/bangumi/bangumi_interest.dart
@@ -0,0 +1,99 @@
+import 'package:kazumi/modules/comments/comment_item.dart';
+
+class BangumiInterest {
+ final int id;
+
+ final int rate;
+
+ final int type;
+
+ final String comment;
+
+ final List<String> tags;
+
+ final int epStatus;
+
+ final int volStatus;
+
+ final int updatedAt;
+
+ final User? user;
+
+ BangumiInterest({
+ required this.id,
+ required this.rate,
+ required this.type,
+ required this.comment,
+ required this.tags,
+ required this.epStatus,
+ required this.volStatus,
+ required this.updatedAt,
+ this.user,
+ });
+
+ bool get hasUserProfile => user != null;
+
+ bool get hasReviewContent => rate > 0 || comment.trim().isNotEmpty;
+
+ BangumiInterest copyWithUser({User? user}) {
+ return BangumiInterest(
+ id: id,
+ rate: rate,
+ type: type,
+ comment: comment,
+ tags: tags,
+ epStatus: epStatus,
+ volStatus: volStatus,
+ updatedAt: updatedAt,
+ user: user ?? this.user,
+ );
+ }
+
+ factory BangumiInterest.fromJson(Map<String, dynamic> json) {
+ final tagsRaw = json['tags'];
+ final List<String> tagList = [];
+ if (tagsRaw is List) {
+ for (final e in tagsRaw) {
+ if (e is String) {
+ tagList.add(e);
+ } else if (e is Map && e['name'] != null) {
+ tagList.add(e['name'].toString());
+ }
+ }
+ }
+ return BangumiInterest(
+ id: (json['id'] as num).toInt(),
+ rate: (json['rate'] as num?)?.toInt() ?? 0,
+ type: (json['type'] as num?)?.toInt() ?? 0,
+ comment: json['comment'] as String? ?? '',
+ tags: tagList,
+ epStatus: (json['epStatus'] as num?)?.toInt() ?? 0,
+ volStatus: (json['volStatus'] as num?)?.toInt() ?? 0,
+ updatedAt: (json['updatedAt'] as num?)?.toInt() ?? 0,
+ );
+ }
+
+ factory BangumiInterest.mergeLocalSubmission({
+ BangumiInterest? previous,
+ required int rate,
+ required String comment,
+ required List<String> tags,
+ }) {
+ return BangumiInterest(
+ id: previous?.id ?? 0,
+ rate: rate,
+ type: previous?.type ?? 0,
+ comment: comment,
+ tags: List<String>.from(tags),
+ epStatus: previous?.epStatus ?? 0,
+ volStatus: previous?.volStatus ?? 0,
+ updatedAt: DateTime.now().millisecondsSinceEpoch ~/ 1000,
+ user: previous?.user,
+ );
+ }
+
+ @override
+ String toString() {
+ return 'BangumiInterest{id: $id, rate: $rate, type: $type, comment: $comment, tags: $tags, epStatus: $epStatus, volStatus: $volStatus, updatedAt: $updatedAt, user: $user}';
+ }
+}
diff --git a/lib/modules/bangumi/bangumi_item.dart b/lib/modules/bangumi/bangumi_item.dart
index 31d0f4a5..53aa3f67 100644
--- a/lib/modules/bangumi/bangumi_item.dart
+++ b/lib/modules/bangumi/bangumi_item.dart
@@ -1,6 +1,7 @@
import 'package:hive_ce/hive.dart';
import 'package:kazumi/modules/bangumi/bangumi_tag.dart';
import 'package:kazumi/utils/date_time.dart';
+import 'bangumi_interest.dart';
part 'bangumi_item.g.dart';
@@ -36,6 +37,7 @@ class BangumiItem {
List<int> votesCount;
@HiveField(14, defaultValue: '')
String info;
+ BangumiInterest? interest;
BangumiItem({
required this.id,
@@ -53,6 +55,7 @@ class BangumiItem {
required this.votes,
required this.votesCount,
required this.info,
+ this.interest,
});
factory BangumiItem.fromJson(Map<String, dynamic> json) {
@@ -60,20 +63,25 @@ class BangumiItem {
if (jsonData.containsKey('infobox') && jsonData['infobox'] is List) {
final List<dynamic> infobox = jsonData['infobox'];
for (var item in infobox) {
- if (item is Map<String, dynamic> && item['key'] == '别名') {
- final dynamic value = item['value'];
- if (value is List) {
- return value
+ if (item is Map && item['key'] == '别名') {
+ // api.bgm.tv /v0 uses `value`; next.bgm.tv /p1 uses `values`
+ final dynamic raw = item['values'] ?? item['value'];
+ if (raw == null) {
+ return [];
+ }
+ if (raw is List) {
+ return raw
.map<String>((element) {
- if (element is Map<String, dynamic> &&
- element.containsKey('v')) {
+ if (element is Map && element.containsKey('v')) {
return element['v'].toString();
}
- return '';
+ return element.toString().trim();
})
.where((alias) => alias.isNotEmpty)
.toList();
}
+ final text = raw.toString().trim();
+ return text.isEmpty ? [] : [text];
}
}
}
@@ -96,10 +104,37 @@ class BangumiItem {
return [];
}
+ String resolveAirDateString(Map<String, dynamic> jsonData) {
+ String? nonEmpty(dynamic v) {
+ if (v == null) return null;
+ final s = v.toString().trim();
+ return s.isEmpty ? null : s;
+ }
+ // For api.bgm.tv date
+ final fromTop = nonEmpty(jsonData['date']);
+ if (fromTop != null) return fromTop;
+ // For next.bgm.tv date
+ final airtime = jsonData['airtime'];
+ if (airtime is Map) {
+ final fromAir = nonEmpty(airtime['date']);
+ if (fromAir != null) return fromAir;
+ }
+ return '';
+ }
+
+ final String airDateStr = resolveAirDateString(json);
+
List list = json['tags'] ?? [];
List<String> bangumiAlias = parseBangumiAliases(json);
List<BangumiTag> tagList = list.map((i) => BangumiTag.fromJson(i)).toList();
List<int> voteList = parseBangumiVoteCount(json);
+ BangumiInterest? interest;
+ final interestRaw = json['interest'];
+ if (interestRaw is Map<String, dynamic>) {
+ interest = BangumiInterest.fromJson(json['interest']);
+ } else if (interestRaw is Map) {
+ interest = BangumiInterest.fromJson(Map<String, dynamic>.from(interestRaw));
+ }
return BangumiItem(
id: json['id'],
type: json['type'] ?? 2,
@@ -108,8 +143,8 @@ class BangumiItem {
? (((json['nameCN'] ?? '') == '') ? json['name'] : json['nameCN'])
: json['name_cn'],
summary: json['summary'] ?? '',
- airDate: json['date'] ?? '',
- airWeekday: dateStringToWeekday(json['date'] ?? '2000-11-11'),
+ airDate: airDateStr,
+ airWeekday: dateStringToWeekday(airDateStr.isEmpty ? '2000-11-11' : airDateStr),
rank: json['rating']['rank'] ?? 0,
images: Map<String, String>.from(
json['images'] ??
@@ -128,6 +163,7 @@ class BangumiItem {
votes: json['rating']['total'] ?? 0,
votesCount: voteList,
info: json['info'] ?? '',
+ interest: interest,
);
}
}
diff --git a/lib/pages/collect/collect_controller.dart b/lib/pages/collect/collect_controller.dart
index 5fd73e64..c6a16e35 100644
--- a/lib/pages/collect/collect_controller.dart
+++ b/lib/pages/collect/collect_controller.dart
@@ -46,6 +46,10 @@ abstract class _CollectController with Store {
return _collectCrudRepository.getCollectType(bangumiItem.id);
}
+ BangumiItem? getCollectibleBangumiItem(int id) {
+ return _collectCrudRepository.getCollectible(id)?.bangumiItem;
+ }
+
@action
Future<void> addCollect(BangumiItem bangumiItem, {type = 1}) async {
if (type == 0) {
diff --git a/lib/pages/info/info_controller.dart b/lib/pages/info/info_controller.dart
index b61875c5..b99f8b5b 100644
--- a/lib/pages/info/info_controller.dart
+++ b/lib/pages/info/info_controller.dart
@@ -1,8 +1,10 @@
import 'package:kazumi/bean/dialog/dialog_helper.dart';
+import 'package:kazumi/modules/bangumi/bangumi_interest.dart';
import 'package:kazumi/modules/bangumi/bangumi_item.dart';
import 'package:kazumi/pages/collect/collect_controller.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:kazumi/modules/search/plugin_search_module.dart';
+import 'package:kazumi/pages/info/rating_review_dialog.dart';
import 'package:kazumi/request/apis/bangumi_api.dart';
import 'package:mobx/mobx.dart';
import 'package:kazumi/services/logging/logger.dart';
@@ -36,40 +38,136 @@ abstract class _InfoController with Store {
@observable
var staffList = ObservableList<StaffFullItem>();
+ bool _isFillingInterestUserProfile = false;
+
+ int _commentsOffset = 0;
+
+ void clearComments() {
+ commentsList.clear();
+ _commentsOffset = 0;
+ }
+
+ Future<bool> fillInterestUserProfileIfNeeded() async {
+ final interest = bangumiItem.interest;
+ if (interest == null || interest.hasUserProfile) {
+ return false;
+ }
+ if (_isFillingInterestUserProfile) {
+ return false;
+ }
+ _isFillingInterestUserProfile = true;
+ try {
+ final user = await BangumiApi.getCurrentUser();
+ if (user == null) {
+ return false;
+ }
+ bangumiItem.interest = interest.copyWithUser(user: user);
+ await collectController.updateLocalCollect(bangumiItem);
+ return true;
+ } catch (e) {
+ KazumiLogger()
+ .e('InfoController: failed to fill interest user profile', error: e);
+ return false;
+ } finally {
+ _isFillingInterestUserProfile = false;
+ }
+ }
+
+ void _removeCurrentUserFromPublicComments() {
+ final interest = bangumiItem.interest;
+ if (interest == null) return;
+ final userId = interest.user?.id;
+ if (userId == null) return;
+ commentsList.removeWhere((item) => item.user.id == userId);
+ }
+
Future<void> queryBangumiInfoByID(int id, {String type = "init"}) async {
isLoading = true;
try {
- final value = await BangumiApi.getBangumiInfoByID(id);
- if (value != null) {
- if (type == "init") {
- bangumiItem = value;
- } else {
- bangumiItem.summary = value.summary;
- bangumiItem.tags = value.tags;
- bangumiItem.rank = value.rank;
- bangumiItem.airDate = value.airDate;
- bangumiItem.airWeekday = value.airWeekday;
- bangumiItem.alias = value.alias;
- bangumiItem.ratingScore = value.ratingScore;
- bangumiItem.votes = value.votes;
- bangumiItem.votesCount = value.votesCount;
- }
- collectController.updateLocalCollect(bangumiItem);
- }
+ await _updateBangumiInfoByID(id, type: type);
} finally {
isLoading = false;
}
}
- Future<void> queryBangumiCommentsByID(int id, {int offset = 0}) async {
- if (offset == 0) {
- commentsList.clear();
+ Future<void> refreshBangumiInfoByID(int id) async {
+ await _updateBangumiInfoByID(id, type: "update");
+ }
+
+ Future<void> _updateBangumiInfoByID(int id, {required String type}) async {
+ final value = await BangumiApi.getBangumiInfoByID(id);
+ if (value == null) {
+ return;
+ }
+ if (type == "init") {
+ bangumiItem = value;
+ } else {
+ bangumiItem.summary = value.summary;
+ bangumiItem.tags = value.tags;
+ bangumiItem.rank = value.rank;
+ bangumiItem.airDate = value.airDate;
+ bangumiItem.airWeekday = value.airWeekday;
+ bangumiItem.alias = value.alias;
+ bangumiItem.ratingScore = value.ratingScore;
+ bangumiItem.votes = value.votes;
+ bangumiItem.votesCount = value.votesCount;
+ final incomingInterest = value.interest;
+ final previousInterest = bangumiItem.interest;
+ if (incomingInterest == null) {
+ bangumiItem.interest = null;
+ } else if (previousInterest == null || !previousInterest.hasUserProfile) {
+ bangumiItem.interest = incomingInterest;
+ } else {
+ bangumiItem.interest =
+ incomingInterest.copyWithUser(user: previousInterest.user);
+ }
+ }
+ await collectController.updateLocalCollect(bangumiItem);
+ }
+
+ Future<void> queryBangumiCommentsByID(int id, {bool refresh = true}) async {
+ await _updateBangumiCommentsByID(
+ id,
+ refresh: refresh,
+ clearBeforeFetch: true,
+ );
+ }
+
+ Future<void> _updateBangumiCommentsByID(
+ int id, {
+ required bool refresh,
+ required bool clearBeforeFetch,
+ }) async {
+ if (refresh) {
+ if (clearBeforeFetch) {
+ clearComments();
+ }
}
+ final offset = refresh ? 0 : _commentsOffset;
await BangumiApi.getBangumiCommentsByID(id, offset: offset).then((value) {
- commentsList.addAll(value.commentList);
+ if (refresh && !clearBeforeFetch) {
+ commentsList = ObservableList<CommentItem>.of(value.commentList);
+ } else {
+ commentsList.addAll(value.commentList);
+ }
+ _commentsOffset = refresh
+ ? value.commentList.length
+ : _commentsOffset + value.commentList.length;
+ _removeCurrentUserFromPublicComments();
});
KazumiLogger().i(
- 'InfoController: loaded comments list length ${commentsList.length}');
+ 'InfoController: loaded comments list length ${commentsList.length}, offset $_commentsOffset');
+ }
+
+ Future<void> refreshBangumiCommentsSilently(int id) async {
+ if (commentsList.isEmpty) {
+ return;
+ }
+ await _updateBangumiCommentsByID(
+ id,
+ refresh: true,
+ clearBeforeFetch: false,
+ );
}
Future<void> queryBangumiCharactersByID(int id) async {
@@ -104,4 +202,30 @@ abstract class _InfoController with Store {
KazumiLogger()
.i('InfoController: loaded staff list length ${staffList.length}');
}
+
+ Future<bool> rateBangumi(RatingReviewResult data,
+ {required int localType}) async {
+ final trimmedComment = data.comment.trim();
+ if (await BangumiApi.addOrUpdateBangumiEvaluationBySubjectID(
+ bangumiItem.id,
+ localType,
+ comment: trimmedComment.isNotEmpty ? trimmedComment : null,
+ rate: data.score > 0 ? data.score : 0,
+ tags: data.tags.isNotEmpty ? data.tags : null,
+ )) {
+ bangumiItem.interest = BangumiInterest.mergeLocalSubmission(
+ previous: bangumiItem.interest,
+ rate: data.score,
+ comment: trimmedComment,
+ tags: data.tags,
+ );
+ await collectController.updateLocalCollect(bangumiItem);
+ await fillInterestUserProfileIfNeeded();
+ _removeCurrentUserFromPublicComments();
+ await refreshBangumiCommentsSilently(bangumiItem.id);
+ await refreshBangumiInfoByID(bangumiItem.id);
+ return true;
+ }
+ return false;
+ }
}
diff --git a/lib/pages/info/info_page.dart b/lib/pages/info/info_page.dart
index a9de0428..ba0b1159 100644
--- a/lib/pages/info/info_page.dart
+++ b/lib/pages/info/info_page.dart
@@ -1,5 +1,7 @@
import 'dart:io';
import 'dart:ui';
+import 'package:kazumi/bean/dialog/dialog_helper.dart';
+import 'package:kazumi/pages/info/rating_review_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:kazumi/bean/widget/collect_button.dart';
@@ -123,7 +125,7 @@ class _InfoPageState extends State<InfoPage> with TickerProviderStateMixin {
}
}
- Future<void> loadMoreComments({int offset = 0}) async {
+ Future<void> loadMoreComments({bool loadMore = false}) async {
if (commentsIsLoading) return;
setState(() {
commentsIsLoading = true;
@@ -133,11 +135,13 @@ class _InfoPageState extends State<InfoPage> with TickerProviderStateMixin {
try {
await infoController.queryBangumiCommentsByID(
infoController.bangumiItem.id,
- offset: offset);
+ refresh: !loadMore);
if (mounted) {
setState(() {
commentsIsLoading = false;
- if (infoController.commentsList.isEmpty) {
+ if (infoController.commentsList.isEmpty &&
+ !(infoController.bangumiItem.interest?.hasReviewContent ??
+ false)) {
commentsIsEmpty = true;
}
});
@@ -153,18 +157,47 @@ class _InfoPageState extends State<InfoPage> with TickerProviderStateMixin {
}
}
+ void onBangumiRatingTap() {
+ final token = GStorage.setting
+ .get(SettingBoxKey.bangumiAccessToken, defaultValue: '')
+ .toString()
+ .trim();
+ if (token.isEmpty) {
+ KazumiDialog.showToast(message: '请先在同步设置中绑定你的 Bangumi 配置以发表吐槽');
+ return;
+ }
+ final localType = infoController.collectController
+ .getCollectType(infoController.bangumiItem);
+ if (localType == 0) {
+ KazumiDialog.showToast(message: '请先追番后再发表评价');
+ return;
+ }
+ KazumiDialog.show(
+ builder: (context) => RatingReviewDialog(
+ bangumiItem: infoController.bangumiItem,
+ onSubmit: (data) async {
+ final updated =
+ await infoController.rateBangumi(data, localType: localType);
+ if (updated && mounted) {
+ setState(() {});
+ }
+ return updated;
+ },
+ ),
+ );
+ }
+
@override
void initState() {
super.initState();
infoController.bangumiItem = inputBangumiIten;
infoController.characterList.clear();
- infoController.commentsList.clear();
+ infoController.clearComments();
infoController.staffList.clear();
infoController.pluginSearchResponseList.clear();
videoPageController.resetEpisodeState();
- // Because the gap between different bangumi API response is too large, sometimes we need to query the bangumi info again
- // We need the type parameter to determine whether to attach the new data to the old data
- // We can't generally replace the old data with the new data, because the old data contains images url, update them will cause the image to reload and flicker
+ // Search results can miss rating distribution or summaries, so fill those
+ // fields without replacing image URLs that are already rendered.
if (_needsBangumiInfoRefresh(infoController.bangumiItem)) {
_showBangumiInfoSkeleton = true;
queryBangumiInfoByID(
@@ -178,36 +211,52 @@ class _InfoPageState extends State<InfoPage> with TickerProviderStateMixin {
infoTabController = TabController(length: 5, vsync: this);
showRating =
GStorage.setting.get(SettingBoxKey.showRating, defaultValue: true);
- infoTabController.addListener(() {
- int index = infoTabController.index;
- if (index == 1 &&
- infoController.commentsList.isEmpty &&
- !commentsIsLoading &&
- !commentsIsEmpty &&
- !commentsQueryTimeout) {
- loadMoreComments();
- }
- if (index == 2 &&
- infoController.characterList.isEmpty &&
- !charactersIsLoading &&
- !charactersIsEmpty &&
- !charactersQueryTimeout) {
- loadCharacters();
- }
- if (index == 4 &&
- infoController.staffList.isEmpty &&
- !staffIsLoading &&
- !staffIsEmpty &&
- !staffQueryTimeout) {
- loadStaff();
+ infoTabController.addListener(onInfoTabChanged);
+ }
+
+ void onInfoTabChanged() {
+ final index = infoTabController.index;
+ if (index == 2 &&
+ infoController.characterList.isEmpty &&
+ !charactersIsLoading &&
+ !charactersIsEmpty &&
+ !charactersQueryTimeout) {
+ loadCharacters();
+ }
+ if (index == 4 &&
+ infoController.staffList.isEmpty &&
+ !staffIsLoading &&
+ !staffIsEmpty &&
+ !staffQueryTimeout) {
+ loadStaff();
+ }
+ }
+
+ Future<void> onCommentsTabSelected() async {
+ final interest = infoController.bangumiItem.interest;
+ final token = GStorage.setting
+ .get(SettingBoxKey.bangumiAccessToken, defaultValue: '')
+ .toString()
+ .trim();
+ if (interest != null && token.isNotEmpty) {
+ final updated = await infoController.fillInterestUserProfileIfNeeded();
+ if (updated && mounted) {
+ setState(() {});
}
- });
+ }
+ if (infoController.commentsList.isEmpty &&
+ !commentsIsLoading &&
+ !commentsIsEmpty &&
+ !commentsQueryTimeout) {
+ loadMoreComments();
+ }
}
@override
void dispose() {
+ infoTabController.removeListener(onInfoTabChanged);
infoController.characterList.clear();
- infoController.commentsList.clear();
+ infoController.clearComments();
infoController.staffList.clear();
infoController.pluginSearchResponseList.clear();
videoPageController.resetEpisodeState();
@@ -226,7 +275,7 @@ class _InfoPageState extends State<InfoPage> with TickerProviderStateMixin {
await infoController.queryBangumiInfoByID(id, type: type);
} catch (e) {
KazumiLogger()
- .e('InfoController: failed to query bangumi info by ID', error: e);
+ .e('InfoPage: failed to query bangumi info by ID', error: e);
} finally {
if (enforceMinimumLoadingDuration && mounted) {
await _waitForMinimumBangumiInfoLoadingDuration(loadingStartedAt);
@@ -397,38 +446,55 @@ class _InfoPageState extends State<InfoPage> with TickerProviderStateMixin {
loadCharacters: loadCharacters,
loadStaff: loadStaff,
commentsList: infoController.commentsList,
+ commentsIsLoading: commentsIsLoading,
+ onCommentsTabSelected: onCommentsTabSelected,
characterList: infoController.characterList,
staffList: infoController.staffList,
isLoading: showBangumiInfoSkeleton,
);
}),
),
- floatingActionButton: FloatingActionButton.extended(
- icon: const Icon(Icons.play_arrow_rounded),
- label: Text('开始观看'),
- onPressed: () async {
- showModalBottomSheet(
- isScrollControlled: true,
- constraints: BoxConstraints(
- maxHeight: (MediaQuery.sizeOf(context).height >=
- LayoutBreakpoint.compact['height']!)
- ? MediaQuery.of(context).size.height * 3 / 4
- : MediaQuery.of(context).size.height,
- maxWidth: (MediaQuery.sizeOf(context).width >=
- LayoutBreakpoint.medium['width']!)
- ? MediaQuery.of(context).size.width * 9 / 16
- : MediaQuery.of(context).size.width,
- ),
- clipBehavior: Clip.antiAlias,
- backgroundColor: Theme.of(context).scaffoldBackgroundColor,
- showDragHandle: true,
- context: context,
- builder: (context) {
- return SourceSheet(
- tabController: sourceTabController,
- infoController: infoController);
- },
- );
+ floatingActionButton: AnimatedBuilder(
+ animation: infoTabController,
+ builder: (context, child) {
+ final showRatingFab = infoTabController.index == 1;
+ return showRatingFab
+ ? FloatingActionButton.extended(
+ tooltip: '吐槽',
+ onPressed: onBangumiRatingTap,
+ label: const Text('发表吐槽'),
+ icon: const Icon(Icons.rate_review_rounded),
+ )
+ : FloatingActionButton.extended(
+ tooltip: '开始观看',
+ onPressed: () async {
+ showModalBottomSheet(
+ isScrollControlled: true,
+ constraints: BoxConstraints(
+ maxHeight: (MediaQuery.sizeOf(context).height >=
+ LayoutBreakpoint.compact['height']!)
+ ? MediaQuery.of(context).size.height * 3 / 4
+ : MediaQuery.of(context).size.height,
+ maxWidth: (MediaQuery.sizeOf(context).width >=
+ LayoutBreakpoint.medium['width']!)
+ ? MediaQuery.of(context).size.width * 9 / 16
+ : MediaQuery.of(context).size.width,
+ ),
+ clipBehavior: Clip.antiAlias,
+ backgroundColor:
+ Theme.of(context).scaffoldBackgroundColor,
+ showDragHandle: true,
+ context: context,
+ builder: (context) {
+ return SourceSheet(
+ tabController: sourceTabController,
+ infoController: infoController);
+ },
+ );
+ },
+ label: const Text('开始观看'),
+ icon: const Icon(Icons.play_arrow_rounded),
+ );
},
),
),
diff --git a/lib/pages/info/info_tabview.dart b/lib/pages/info/info_tabview.dart
index c27382a5..57e849f3 100644
--- a/lib/pages/info/info_tabview.dart
+++ b/lib/pages/info/info_tabview.dart
@@ -27,6 +27,8 @@ class InfoTabView extends StatefulWidget {
required this.loadStaff,
required this.bangumiItem,
required this.commentsList,
+ required this.commentsIsLoading,
+ this.onCommentsTabSelected,
required this.characterList,
required this.staffList,
required this.isLoading,
@@ -34,12 +36,14 @@ class InfoTabView extends StatefulWidget {
final bool commentsQueryTimeout;
final bool commentsIsEmpty;
+ final bool commentsIsLoading;
+ final VoidCallback? onCommentsTabSelected;
final bool charactersQueryTimeout;
final bool charactersIsEmpty;
final bool staffQueryTimeout;
final bool staffIsEmpty;
final TabController tabController;
- final Future<void> Function({int offset}) loadMoreComments;
+ final Future<void> Function({bool loadMore}) loadMoreComments;
final Future<void> Function() loadCharacters;
final Future<void> Function() loadStaff;
final BangumiItem bangumiItem;
@@ -58,6 +62,27 @@ class _InfoTabViewState extends State<InfoTabView>
bool fullIntro = false;
bool fullTag = false;
+ @override
+ void initState() {
+ super.initState();
+ widget.tabController.addListener(_onTabChanged);
+ if (widget.tabController.index == 1) {
+ widget.onCommentsTabSelected?.call();
+ }
+ }
+
+ @override
+ void dispose() {
+ widget.tabController.removeListener(_onTabChanged);
+ super.dispose();
+ }
+
+ void _onTabChanged() {
+ if (widget.tabController.index == 1) {
+ widget.onCommentsTabSelected?.call();
+ }
+ }
+
Widget get infoBody {
return Center(
child: Padding(
@@ -211,7 +236,7 @@ class _InfoTabViewState extends State<InfoTabView>
onNotification: (scrollEnd) {
final metrics = scrollEnd.metrics;
if (metrics.pixels >= metrics.maxScrollExtent - 200) {
- widget.loadMoreComments(offset: widget.commentsList.length);
+ widget.loadMoreComments(loadMore: widget.commentsList.isNotEmpty);
}
return true;
},
@@ -226,11 +251,35 @@ class _InfoTabViewState extends State<InfoTabView>
NestedScrollView.sliverOverlapAbsorberHandleFor(context),
),
SliverLayoutBuilder(builder: (context, _) {
- if (widget.commentsList.isNotEmpty) {
+ final myInterest = widget.bangumiItem.interest;
+ final showMyReview = !widget.commentsIsLoading &&
+ myInterest != null &&
+ myInterest.hasUserProfile &&
+ myInterest.hasReviewContent;
+ final listItemCount =
+ widget.commentsList.length + (showMyReview ? 1 : 0);
+
+ if (listItemCount > 0) {
return SliverList.separated(
addAutomaticKeepAlives: false,
- itemCount: widget.commentsList.length,
+ itemCount: listItemCount,
itemBuilder: (context, index) {
+ final commentIndex = showMyReview ? index - 1 : index;
+ final myUser = myInterest?.user;
+ final card = showMyReview && index == 0 && myUser != null
+ ? CommentsCard.own(
+ commentItem: CommentItem(
+ user: myUser,
+ comment: Comment(
+ rate: myInterest.rate,
+ comment: myInterest.comment,
+ updatedAt: myInterest.updatedAt,
+ ),
+ ),
+ )
+ : CommentsCard(
+ commentItem: widget.commentsList[commentIndex],
+ );
return SafeArea(
top: false,
bottom: false,
@@ -242,9 +291,7 @@ class _InfoTabViewState extends State<InfoTabView>
width: MediaQuery.sizeOf(context).width > maxWidth
? maxWidth
: MediaQuery.sizeOf(context).width - 32,
- child: CommentsCard(
- commentItem: widget.commentsList[index],
- ),
+ child: card,
),
),
),
@@ -279,7 +326,7 @@ class _InfoTabViewState extends State<InfoTabView>
GeneralErrorButton(
onPressed: () {
widget.loadMoreComments(
- offset: widget.commentsList.length);
+ loadMore: widget.commentsList.isNotEmpty);
},
text: '重试',
),
diff --git a/lib/pages/info/rating_review_dialog.dart b/lib/pages/info/rating_review_dialog.dart
new file mode 100644
index 00000000..709dd8dd
--- /dev/null
+++ b/lib/pages/info/rating_review_dialog.dart
@@ -0,0 +1,669 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_rating_bar/flutter_rating_bar.dart';
+import 'package:kazumi/modules/bangumi/bangumi_item.dart';
+import 'package:kazumi/modules/bangumi/bangumi_tag.dart';
+import 'package:kazumi/services/logging/logger.dart';
+
+class RatingReviewResult {
+ const RatingReviewResult({
+ required this.score,
+ required this.tags,
+ required this.comment,
+ });
+
+ final int score;
+
+ final List<String> tags;
+
+ final String comment;
+}
+
+typedef RatingReviewSubmitCallback = Future<bool> Function(
+ RatingReviewResult result,
+);
+
+class RatingReviewDialog extends StatefulWidget {
+ const RatingReviewDialog({
+ super.key,
+ required this.bangumiItem,
+ this.onSubmit,
+ });
+
+ final BangumiItem bangumiItem;
+
+ final RatingReviewSubmitCallback? onSubmit;
+
+ @override
+ State<RatingReviewDialog> createState() => _RatingReviewDialogState();
+}
+
+class _RatingReviewDialogState extends State<RatingReviewDialog> {
+ static const List<String> scoreLabels = <String>[
+ '未评分',
+ '不忍直视',
+ '很差',
+ '差',
+ '较差',
+ '不过不失',
+ '还行',
+ '推荐',
+ '力荐',
+ '神作',
+ '超神作',
+ ];
+
+ /// 用户最多可选 / 输入的标签数量
+ static const int _maxSelectedTags = 10;
+
+ /// 单个自定义标签最大字符数
+ static const int _maxTagLength = 10;
+
+ /// 吐槽内容最大字符数
+ static const int _maxCommentLength = 380;
+
+ List<BangumiTag> tabs = [];
+ late int score;
+ final TextEditingController commentController = TextEditingController();
+ final tagInputController = TextEditingController();
+ late List<String> selectedTags;
+
+ bool _isOnTagPage = false;
+ bool _isSubmitting = false;
+
+ @override
+ void initState() {
+ super.initState();
+ final interest = widget.bangumiItem.interest;
+ tabs = List<BangumiTag>.from(widget.bangumiItem.tags);
+ selectedTags = List<String>.from(interest?.tags ?? const <String>[]);
+ score = (interest?.rate ?? 0).clamp(0, 10);
+ commentController.text = interest?.comment ?? '';
+ }
+
+ @override
+ void dispose() {
+ commentController.dispose();
+ tagInputController.dispose();
+ super.dispose();
+ }
+
+ String get displayName {
+ final cn = widget.bangumiItem.nameCn.trim();
+ if (cn.isNotEmpty) return cn;
+ return widget.bangumiItem.name;
+ }
+
+ String get scoreLabel => scoreLabels[score.clamp(0, 10)];
+
+ void _toggleTag(String rawTag) {
+ if (_isSubmitting) return;
+ final tag = rawTag.trim();
+ if (tag.isEmpty) return;
+ setState(() {
+ if (selectedTags.contains(tag)) {
+ selectedTags.remove(tag);
+ return;
+ }
+ if (selectedTags.length >= _maxSelectedTags) {
+ return;
+ }
+ selectedTags.add(tag);
+ });
+ }
+
+ void _addCustomTag() {
+ if (_isSubmitting) return;
+ final text = tagInputController.text.trim();
+ if (text.isEmpty) return;
+ if (text.length > _maxTagLength) {
+ return;
+ }
+ if (selectedTags.length >= _maxSelectedTags) {
+ return;
+ }
+ if (selectedTags.contains(text)) {
+ tagInputController.clear();
+ return;
+ }
+ setState(() {
+ tabs.insert(0, BangumiTag(name: text, count: 1, totalCount: 1));
+ selectedTags.add(text);
+ tagInputController.clear();
+ });
+ }
+
+ Future<void> _submit() async {
+ if (_isSubmitting) return;
+ final result = RatingReviewResult(
+ score: score,
+ tags: List<String>.unmodifiable(selectedTags),
+ comment: commentController.text,
+ );
+ setState(() => _isSubmitting = true);
+ try {
+ final submitted = await widget.onSubmit?.call(result) ?? true;
+ if (submitted && mounted) {
+ Navigator.of(context).pop();
+ return;
+ }
+ } catch (e, stackTrace) {
+ KazumiLogger().e(
+ 'RatingReviewDialog: failed to submit rating review',
+ error: e,
+ stackTrace: stackTrace,
+ );
+ }
+ if (mounted) {
+ setState(() => _isSubmitting = false);
+ }
+ }
+
+ void _openTagSelection() {
+ if (_isSubmitting) return;
+ setState(() => _isOnTagPage = true);
+ }
+
+ void _closeTagSelection() {
+ if (_isSubmitting) return;
+ setState(() => _isOnTagPage = false);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+
+ final mediaQuery = MediaQuery.of(context);
+ final maxHeight =
+ mediaQuery.size.height - mediaQuery.viewInsets.bottom - 80;
+
+ return PopScope(
+ canPop: !_isSubmitting && !_isOnTagPage,
+ onPopInvokedWithResult: (didPop, _) {
+ if (!didPop && _isOnTagPage && !_isSubmitting) {
+ _closeTagSelection();
+ }
+ },
+ child: Dialog(
+ clipBehavior: Clip.antiAlias,
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxWidth: 600,
+ maxHeight: maxHeight > 320 ? maxHeight : double.infinity,
+ ),
+ child: AnimatedSize(
+ duration: const Duration(milliseconds: 300),
+ curve: Curves.easeInOut,
+ alignment: Alignment.topCenter,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ AnimatedSwitcher(
+ duration: const Duration(milliseconds: 200),
+ child: _isOnTagPage
+ ? _buildTagPageHeader(theme)
+ : _buildMainHeader(theme),
+ ),
+ const Divider(height: 1),
+ Flexible(
+ child: AnimatedSwitcher(
+ duration: const Duration(milliseconds: 220),
+ transitionBuilder: (child, animation) {
+ return FadeTransition(opacity: animation, child: child);
+ },
+ child: _isOnTagPage
+ ? _buildTagPageContent(theme)
+ : _buildMainScrollContent(theme),
+ ),
+ ),
+ AnimatedSwitcher(
+ duration: const Duration(milliseconds: 200),
+ child: _isOnTagPage
+ ? const SizedBox.shrink(key: ValueKey('no-actions'))
+ : Column(
+ key: const ValueKey('main-actions'),
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const Divider(height: 1),
+ _buildActions(theme),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _buildMainHeader(ThemeData theme) {
+ final colorScheme = theme.colorScheme;
+ return Padding(
+ key: const ValueKey('main-header'),
+ padding: const EdgeInsets.fromLTRB(24, 20, 24, 16),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text('评价 · 吐槽', style: theme.textTheme.titleLarge),
+ InkWell(
+ onTap: _isSubmitting ? null : () => Navigator.of(context).pop(),
+ child: Icon(
+ Icons.close,
+ color: _isSubmitting
+ ? colorScheme.onSurface.withValues(alpha: 0.38)
+ : null,
+ ),
+ ),
+ ],
+ ),
+ Text(
+ displayName,
+ style: theme.textTheme.bodyMedium?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ ),
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _buildTagPageHeader(ThemeData theme) {
+ final colorScheme = theme.colorScheme;
+ return Padding(
+ key: const ValueKey('tag-header'),
+ padding: const EdgeInsets.fromLTRB(4, 8, 16, 8),
+ child: Row(
+ children: [
+ IconButton(
+ icon: const Icon(Icons.arrow_back),
+ onPressed: _isSubmitting ? null : _closeTagSelection,
+ ),
+ const SizedBox(width: 4),
+ Expanded(
+ child: Text('选择标签', style: theme.textTheme.titleMedium),
+ ),
+ Text(
+ '${selectedTags.length} / $_maxSelectedTags',
+ style: theme.textTheme.bodySmall?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _buildMainScrollContent(ThemeData theme) {
+ return SingleChildScrollView(
+ key: const ValueKey('main-content'),
+ padding: const EdgeInsets.fromLTRB(24, 16, 24, 16),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ _buildBangumiRatingSummary(theme),
+ const SizedBox(height: 20),
+ _buildScoreSection(theme),
+ _buildTagSummaryRow(theme),
+ const SizedBox(height: 20),
+ _buildCommentSection(theme),
+ ],
+ ),
+ );
+ }
+
+ Widget _buildTagSummaryRow(ThemeData theme) {
+ final colorScheme = theme.colorScheme;
+ final count = selectedTags.length;
+
+ return InkWell(
+ onTap: _openTagSelection,
+ borderRadius: BorderRadius.circular(12),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
+ decoration: BoxDecoration(
+ border: Border.all(color: colorScheme.outlineVariant),
+ borderRadius: BorderRadius.circular(12),
+ ),
+ child: Row(
+ children: [
+ Icon(
+ Icons.new_label_outlined,
+ color: colorScheme.onSurfaceVariant,
+ ),
+ const SizedBox(width: 8),
+ Text(
+ '标签',
+ style: theme.textTheme.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w500,
+ ),
+ ),
+ const SizedBox(width: 8),
+ Expanded(
+ child: count > 0
+ ? Text(
+ '已选 $count 个',
+ style: theme.textTheme.bodyMedium?.copyWith(
+ color: colorScheme.primary,
+ ),
+ )
+ : Text(
+ '点击选择标签',
+ style: theme.textTheme.bodySmall?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ ),
+ ),
+ ),
+ Icon(
+ Icons.chevron_right_rounded,
+ size: 20,
+ color: colorScheme.onSurfaceVariant,
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _buildTagPageContent(ThemeData theme) {
+ final colorScheme = theme.colorScheme;
+
+ return SingleChildScrollView(
+ key: const ValueKey('tag-content'),
+ padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ Expanded(
+ child: TextField(
+ controller: tagInputController,
+ maxLength: _maxTagLength,
+ textInputAction: TextInputAction.done,
+ onSubmitted: (_) => _addCustomTag(),
+ enabled: !_isSubmitting,
+ scrollPadding: const EdgeInsets.symmetric(vertical: 10),
+ decoration: InputDecoration(
+ hintText: '输入自定义标签',
+ hintStyle: const TextStyle(fontSize: 12),
+ isDense: true,
+ counterText: '',
+ contentPadding:
+ const EdgeInsets.symmetric(vertical: 8, horizontal: 10),
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(10),
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(width: 8),
+ FilledButton.tonal(
+ style: FilledButton.styleFrom(
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(8),
+ ),
+ ),
+ onPressed: _isSubmitting ? null : _addCustomTag,
+ child: const Text('添加'),
+ ),
+ ],
+ ),
+ if (tabs.isNotEmpty) ...[
+ const SizedBox(height: 16),
+ Text(
+ '热门标签',
+ style: theme.textTheme.bodySmall?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ ),
+ ),
+ const SizedBox(height: 8),
+ Wrap(
+ spacing: 8,
+ runSpacing: 6,
+ children: tabs.map((tag) {
+ final selected = selectedTags.contains(tag.name);
+ return InkWell(
+ onTap: _isSubmitting ? null : () => _toggleTag(tag.name),
+ borderRadius: BorderRadius.circular(6),
+ child: Container(
+ padding:
+ const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
+ decoration: BoxDecoration(
+ color: selected
+ ? colorScheme.primaryContainer
+ : colorScheme.surfaceContainerLow,
+ borderRadius: BorderRadius.circular(6),
+ border: Border.all(
+ color: selected
+ ? colorScheme.primary.withValues(alpha: 0.4)
+ : colorScheme.outlineVariant,
+ ),
+ ),
+ child: Text(
+ '${tag.name} (${tag.count})',
+ style: theme.textTheme.bodySmall?.copyWith(
+ color: selected
+ ? colorScheme.onPrimaryContainer
+ : colorScheme.onSurface,
+ ),
+ ),
+ ),
+ );
+ }).toList(),
+ ),
+ ],
+ ],
+ ),
+ );
+ }
+
+ Widget _buildBangumiRatingSummary(ThemeData theme) {
+ final colorScheme = theme.colorScheme;
+ final votes = widget.bangumiItem.votes;
+ final score = widget.bangumiItem.ratingScore;
+ final rank = widget.bangumiItem.rank;
+
+ return Row(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ Text(
+ score.toStringAsFixed(1),
+ style: theme.textTheme.headlineMedium?.copyWith(
+ fontWeight: FontWeight.bold,
+ color: colorScheme.primary,
+ height: 1.1,
+ ),
+ ),
+ const SizedBox(height: 2),
+ Text(
+ '$votes 人评分',
+ style: theme.textTheme.bodySmall?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(width: 16),
+ Container(
+ width: 1,
+ height: 40,
+ color: colorScheme.outlineVariant,
+ ),
+ const SizedBox(width: 16),
+ Expanded(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ '番剧评分',
+ style: theme.textTheme.bodySmall?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ ),
+ ),
+ const SizedBox(height: 4),
+ RatingBarIndicator(
+ itemCount: 5,
+ rating: (score / 2).clamp(0, 5).toDouble(),
+ itemBuilder: (context, _) => Icon(
+ Icons.star_rounded,
+ color: colorScheme.primary,
+ ),
+ itemSize: 18,
+ ),
+ if (rank > 0)
+ Padding(
+ padding: const EdgeInsets.only(top: 4),
+ child: Text(
+ 'Bangumi #$rank',
+ style: theme.textTheme.bodySmall?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ );
+ }
+
+ Widget _buildScoreSection(ThemeData theme) {
+ final colorScheme = theme.colorScheme;
+ final hasScore = score > 0;
+
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ Text('我的评分', style: theme.textTheme.titleSmall),
+ const Spacer(),
+ if (hasScore)
+ Text(
+ '$score / 10 $scoreLabel',
+ style: theme.textTheme.bodyMedium?.copyWith(
+ color: colorScheme.primary,
+ fontWeight: FontWeight.bold,
+ ),
+ )
+ else
+ Text(
+ scoreLabel,
+ style: theme.textTheme.bodyMedium?.copyWith(
+ color: colorScheme.onSurfaceVariant,
+ ),
+ ),
+ ],
+ ),
+ Center(
+ child: RatingBar(
+ initialRating: score / 2,
+ minRating: 0,
+ maxRating: 5,
+ allowHalfRating: true,
+ itemCount: 5,
+ itemSize: 36,
+ glow: false,
+ ratingWidget: RatingWidget(
+ full: Icon(Icons.star_rounded, color: colorScheme.primary),
+ half: Icon(Icons.star_half_rounded, color: colorScheme.primary),
+ empty: Icon(
+ Icons.star_outline_rounded,
+ color: colorScheme.outline,
+ ),
+ ),
+ onRatingUpdate: (value) {
+ if (_isSubmitting) return;
+ final newScore = (value * 2).round().clamp(0, 10);
+ if (newScore != score) {
+ setState(() => score = newScore);
+ }
+ },
+ ),
+ ),
+ const SizedBox(height: 5),
+ if (hasScore)
+ Center(
+ child: TextButton(
+ onPressed: _isSubmitting ? null : () => setState(() => score = 0),
+ child: Text(
+ '清除评分',
+ style: TextStyle(color: colorScheme.outline),
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+
+ Widget _buildCommentSection(ThemeData theme) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text('吐槽', style: theme.textTheme.titleSmall),
+ const SizedBox(height: 8),
+ TextField(
+ controller: commentController,
+ enabled: !_isSubmitting,
+ minLines: 3,
+ maxLines: 6,
+ decoration: InputDecoration(
+ hintText: '写下你对这部番剧的看法…',
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(10),
+ ),
+ ),
+ maxLength: _maxCommentLength,
+ textInputAction: TextInputAction.newline,
+ ),
+ ],
+ );
+ }
+
+ Widget _buildActions(ThemeData theme) {
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.end,
+ children: [
+ FilledButton(
+ onPressed: _isSubmitting ? null : _submit,
+ style: FilledButton.styleFrom(
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(10),
+ ),
+ ),
+ child: SizedBox(
+ width: 36,
+ height: 20,
+ child: Center(
+ child: _isSubmitting
+ ? SizedBox(
+ width: 16,
+ height: 16,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ color: theme.colorScheme.primary,
+ ),
+ )
+ : const Text('提交'),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/lib/request/apis/bangumi_api.dart b/lib/request/apis/bangumi_api.dart
index 6925e11f..43306e3b 100644
--- a/lib/request/apis/bangumi_api.dart
+++ b/lib/request/apis/bangumi_api.dart
@@ -12,6 +12,7 @@ import 'package:kazumi/modules/bangumi/bangumi_collection.dart';
import 'package:kazumi/modules/collect/collect_type.dart';
import 'package:kazumi/modules/collect/collect_type_mapper.dart';
import 'package:kazumi/modules/bangumi/bangumi_collection_type.dart';
+import 'package:kazumi/modules/comments/comment_item.dart';
class BangumiApi {
static final BangumiClient _client = BangumiClient.instance;
@@ -211,7 +212,7 @@ class BangumiApi {
try {
final jsonData = await _client.get(
ApiEndpoints.formatUrl(
- ApiEndpoints.bangumiAPIDomain + ApiEndpoints.bangumiInfoByID, [id]),
+ ApiEndpoints.bangumiAPINextDomain + ApiEndpoints.bangumiInfoByIDNext, [id]),
);
return BangumiItem.fromJson(jsonData);
} catch (e) {
@@ -340,6 +341,11 @@ class BangumiApi {
}
static Future<String?> getUsername() async {
+ final user = await getCurrentUser();
+ return user?.username;
+ }
+
+ static Future<User?> getCurrentUser() async {
try {
final jsonData = await _client.get(
ApiEndpoints.formatUrl(
@@ -348,7 +354,7 @@ class BangumiApi {
requiresAuth: true,
);
if (jsonData['id'] != null) {
- return jsonData['username'] ?? 'Unknown';
+ return User.fromJson(Map<String, dynamic>.from(jsonData));
}
} on NetworkException catch (e) {
if (e.statusCode == 401) {
@@ -357,7 +363,7 @@ class BangumiApi {
}
rethrow;
} catch (e) {
- KazumiLogger().e('Network: get username failed', error: e);
+ KazumiLogger().e('Network: get current user failed', error: e);
}
return null;
}
@@ -509,4 +515,23 @@ class BangumiApi {
}
return await updateBangumiById(id, {'type': type.value});
}
+
+ /// update or add Bangumi evaluation by subjectID
+ static Future<bool> addOrUpdateBangumiEvaluationBySubjectID(
+ int subjectID,
+ int localType, {
+ String? comment,
+ int? rate,
+ List<String>? tags,
+ }) async {
+ final bangumiType = CollectType.fromValue(localType).toBangumiCollectionType();
+ if (bangumiType == null) {
+ return false;
+ }
+ final data = <String, dynamic>{'type': bangumiType.value};
+ if (comment != null) data['comment'] = comment;
+ if (rate != null) data['rate'] = rate;
+ if (tags != null) data['tags'] = tags;
+ return updateBangumiById(subjectID, data);
+ }
}