feat: просмотрщик видео. Крутой.

This commit is contained in:
Jganenokk
2026-07-27 16:33:41 +07:00
parent 8602755a8c
commit 92c0a90367
17 changed files with 1161 additions and 475 deletions
+1 -1
View File
@@ -625,7 +625,7 @@ class ChatsModule {
ContactInfoFetch.clear();
PresenceFetch.clear();
ChatInfoFetch.clear();
SharedContentModule.clearPhotoIndex();
SharedContentModule.clearMediaIndex();
}
void _enqueueGlobalPush(Packet packet) {
+36 -31
View File
@@ -95,19 +95,19 @@ class CommonChatEntry {
}
}
class ChatPhotoFeed {
class ChatMediaFeed {
final List<SharedMediaItem> items;
final int total;
final bool reachedEnd;
const ChatPhotoFeed({
const ChatMediaFeed({
required this.items,
required this.total,
required this.reachedEnd,
});
}
class _ChatPhotoIndex {
class _ChatMediaIndex {
final List<SharedMediaItem> items = [];
final Set<String> seen = {};
int total = 0;
@@ -116,62 +116,69 @@ class _ChatPhotoIndex {
Future<void>? inFlight;
}
String photoDedupKey(String messageId, PhotoAttachment photo) =>
'$messageId:p${photo.photoId ?? photo.baseUrl}';
String mediaDedupKey(String messageId, MessageAttachment attachment) {
if (attachment is PhotoAttachment) {
return '$messageId:p${attachment.photoId ?? attachment.baseUrl}';
}
if (attachment is VideoAttachment) {
return '$messageId:v${attachment.videoId ?? attachment.baseUrl}';
}
return '$messageId:${attachment.hashCode}';
}
class SharedContentModule {
static const int _photoIndexPageSize = 60;
static const int _photoIndexMaxPages = 40;
static const int _mediaIndexPageSize = 60;
static const int _mediaIndexMaxPages = 40;
static final Map<int, _ChatPhotoIndex> _photoIndexes = {};
static final Map<int, _ChatMediaIndex> _mediaIndexes = {};
final Api _api;
SharedContentModule(this._api);
static void clearPhotoIndex() => _photoIndexes.clear();
static void clearMediaIndex() => _mediaIndexes.clear();
Future<ChatPhotoFeed?> photoFeedFor({
Future<ChatMediaFeed?> mediaFeedFor({
required int chatId,
required String photoKey,
required String mediaKey,
required Future<String?> Function() resolveAnchor,
}) async {
final index = _photoIndexes.putIfAbsent(chatId, _ChatPhotoIndex.new);
final index = _mediaIndexes.putIfAbsent(chatId, _ChatMediaIndex.new);
for (var page = 0; page < _photoIndexMaxPages; page++) {
if (index.seen.contains(photoKey)) return _snapshot(index);
for (var page = 0; page < _mediaIndexMaxPages; page++) {
if (index.seen.contains(mediaKey)) return _snapshot(index);
if (index.reachedEnd) return null;
await _nextPhotoPage(chatId, index, resolveAnchor);
await _nextMediaPage(chatId, index, resolveAnchor);
}
return null;
}
Future<ChatPhotoFeed> loadMorePhotos({
Future<ChatMediaFeed> loadMoreMedia({
required int chatId,
required Future<String?> Function() resolveAnchor,
}) async {
final index = _photoIndexes.putIfAbsent(chatId, _ChatPhotoIndex.new);
final index = _mediaIndexes.putIfAbsent(chatId, _ChatMediaIndex.new);
if (!index.reachedEnd) {
await _nextPhotoPage(chatId, index, resolveAnchor);
await _nextMediaPage(chatId, index, resolveAnchor);
}
return _snapshot(index);
}
ChatPhotoFeed _snapshot(_ChatPhotoIndex index) {
ChatMediaFeed _snapshot(_ChatMediaIndex index) {
final counted = index.items.length;
final total = index.reachedEnd
? counted
: (index.total > counted ? index.total : counted);
return ChatPhotoFeed(
return ChatMediaFeed(
items: List.unmodifiable(index.items),
total: total,
reachedEnd: index.reachedEnd,
);
}
Future<void> _nextPhotoPage(
Future<void> _nextMediaPage(
int chatId,
_ChatPhotoIndex index,
_ChatMediaIndex index,
Future<String?> Function() resolveAnchor,
) async {
final pending = index.inFlight;
@@ -179,7 +186,7 @@ class SharedContentModule {
await pending;
return;
}
final task = _loadPhotoPage(chatId, index, resolveAnchor);
final task = _loadMediaPage(chatId, index, resolveAnchor);
index.inFlight = task;
try {
await task;
@@ -188,15 +195,13 @@ class SharedContentModule {
}
}
Future<void> _loadPhotoPage(
Future<void> _loadMediaPage(
int chatId,
_ChatPhotoIndex index,
_ChatMediaIndex index,
Future<String?> Function() resolveAnchor,
) async {
final initial = !index.started;
final anchor = initial
? await resolveAnchor()
: index.items.last.messageId;
final anchor = initial ? await resolveAnchor() : index.items.last.messageId;
if (anchor == null || anchor.isEmpty) {
index.reachedEnd = true;
return;
@@ -205,9 +210,9 @@ class SharedContentModule {
final page = await fetchMedia(
chatId: chatId,
anchorMessageId: anchor,
attachTypes: const ['PHOTO'],
forward: initial ? _photoIndexPageSize : 0,
backward: _photoIndexPageSize,
attachTypes: const ['PHOTO', 'VIDEO'],
forward: initial ? _mediaIndexPageSize : 0,
backward: _mediaIndexPageSize,
);
index.started = true;
if (page.total > index.total) index.total = page.total;
@@ -1120,6 +1120,7 @@ class _ChatInfoScreenState extends State<ChatInfoScreen>
chatId: _mediaChatId,
anchorMessageId: anchor,
myId: _myId,
sourceName: widget.name,
kind: kind,
emptyLabel: emptyLabel,
emptyIcon: emptyIcon,
+1 -1
View File
@@ -1078,7 +1078,7 @@ class _ChatScreenState extends State<ChatScreen>
forward: _forwardMessageById,
delete: (messageId, senderId) =>
_confirmDeleteMessage(messageId, senderId == _myId),
viewAllPhotos: () => _openChatInfo(initialTab: ChatInfoTab.media),
viewAllMedia: () => _openChatInfo(initialTab: ChatInfoTab.media),
);
void _forwardMessageById(String messageId) {
@@ -67,6 +67,7 @@ class BubbleContext {
final int myId;
final String chatType;
final int? chatId;
final String? chatName;
final PhotoViewerActions? photoActions;
final String? overrideStatus;
final ValueListenable<int>? otherReadTime;
@@ -87,6 +88,7 @@ class BubbleContext {
required this.myId,
required this.chatType,
this.chatId,
this.chatName,
this.photoActions,
this.overrideStatus,
this.otherReadTime,
@@ -535,6 +535,7 @@ class PhotoBubble extends StatelessWidget {
message: ctx.message,
actions: ctx.photoActions,
hero: hero,
sourceName: ctx.chatName,
),
),
);
@@ -7,7 +7,7 @@ import '../../../../core/utils/format.dart';
import '../../../../core/utils/haptics.dart';
import '../../../../models/attachment.dart';
import '../../custom_notification.dart';
import '../../video_player_screen.dart';
import '../../photo_viewer.dart';
import 'bubble_context.dart';
import 'video_note_bubble.dart';
@@ -185,7 +185,14 @@ class VideoBubble extends StatelessWidget {
Navigator.of(context).push(
MaterialPageRoute(
fullscreenDialog: true,
builder: (_) => VideoPlayerScreen(sources: sources),
builder: (_) => PhotoViewerScreen.video(
attachment: video,
initialVideoSources: sources,
chatId: ctx.message.chatId,
message: ctx.message,
actions: ctx.photoActions,
sourceName: ctx.chatName,
),
),
);
}
@@ -26,7 +26,6 @@ import '../photo_viewer.dart';
import '../reload_on_reconnect.dart';
import '../small_spinner.dart';
import '../swipe_route.dart';
import '../video_player_screen.dart';
enum SharedContentKind { media, files, voice, links }
@@ -457,6 +456,7 @@ class SharedMediaTab extends StatefulWidget {
final int chatId;
final String anchorMessageId;
final int myId;
final String sourceName;
final SharedContentKind kind;
final String emptyLabel;
final IconData emptyIcon;
@@ -468,6 +468,7 @@ class SharedMediaTab extends StatefulWidget {
required this.chatId,
required this.anchorMessageId,
required this.myId,
required this.sourceName,
required this.kind,
required this.emptyLabel,
required this.emptyIcon,
@@ -649,6 +650,7 @@ class _SharedMediaTabState extends State<SharedMediaTab>
item: items[index],
onGoTo: () => _goTo(items[index]),
onGoToMessage: widget.onGoToMessage,
sourceName: widget.sourceName,
),
);
}
@@ -658,11 +660,13 @@ class _MediaTile extends StatelessWidget {
final SharedMediaItem item;
final VoidCallback onGoTo;
final void Function(String messageId, int time) onGoToMessage;
final String sourceName;
const _MediaTile({
required this.item,
required this.onGoTo,
required this.onGoToMessage,
required this.sourceName,
});
void _menu(BuildContext context) {
@@ -758,7 +762,24 @@ class _MediaTile extends StatelessWidget {
showCustomNotification(context, 'Не удалось загрузить видео');
return;
}
pushSwipeable(context, (_) => VideoPlayerScreen(sources: sources));
pushSwipeable(
context,
(_) => PhotoViewerScreen.video(
attachment: att,
initialVideoSources: sources,
chatId: item.chatId,
message: CachedMessage(
id: item.messageId,
accountId: 0,
chatId: item.chatId,
senderId: item.senderId,
text: item.text,
time: item.time,
),
actions: PhotoViewerActions(goToMessage: onGoToMessage),
sourceName: sourceName,
),
);
return;
}
final url = att.baseUrl ?? att.previewData ?? '';
@@ -777,9 +798,11 @@ class _MediaTile extends StatelessWidget {
accountId: 0,
chatId: item.chatId,
senderId: item.senderId,
text: item.text,
time: item.time,
),
actions: PhotoViewerActions(goToMessage: onGoToMessage),
sourceName: sourceName,
),
);
}
+1
View File
@@ -802,6 +802,7 @@ class MessageBubble extends StatelessWidget {
myId: myId,
chatType: chatType,
chatId: chatId,
chatName: peerName,
photoActions: photoActions,
overrideStatus: overrideStatus,
otherReadTime: otherReadTime,
File diff suppressed because it is too large Load Diff
@@ -1,326 +0,0 @@
import 'package:flutter/material.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:video_player/video_player.dart';
import '../../core/utils/format.dart';
import 'small_spinner.dart';
class VideoPlayerScreen extends StatefulWidget {
final Map<String, String> sources;
final String? initialQuality;
const VideoPlayerScreen({
super.key,
required this.sources,
this.initialQuality,
});
@override
State<VideoPlayerScreen> createState() => _VideoPlayerScreenState();
}
class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
VideoPlayerController? _controller;
bool _error = false;
bool _controlsVisible = true;
double? _dragValue;
late String _quality;
int _loadGeneration = 0;
@override
void initState() {
super.initState();
_quality =
widget.initialQuality != null &&
widget.sources.containsKey(widget.initialQuality)
? widget.initialQuality!
: widget.sources.keys.first;
_load(_quality);
}
Future<void> _load(
String quality, {
Duration? position,
bool wasPlaying = true,
}) async {
final url = widget.sources[quality];
if (url == null) {
setState(() => _error = true);
return;
}
final generation = ++_loadGeneration;
final old = _controller;
final controller = VideoPlayerController.networkUrl(Uri.parse(url));
_controller = controller;
setState(() {
_quality = quality;
_error = false;
});
try {
await controller.initialize();
old?.removeListener(_onTick);
await old?.dispose();
if (!mounted) {
await controller.dispose();
return;
}
if (generation != _loadGeneration) {
return;
}
if (position != null) await controller.seekTo(position);
if (generation != _loadGeneration) {
return;
}
controller.addListener(_onTick);
if (wasPlaying) controller.play();
setState(() {});
} catch (_) {
if (generation == _loadGeneration && mounted) {
setState(() => _error = true);
}
}
}
void _onTick() {
if (mounted) setState(() {});
}
Future<void> _switchQuality(String quality) async {
if (quality == _quality) return;
final c = _controller;
final position = c?.value.position;
final wasPlaying = c?.value.isPlaying ?? true;
await _load(quality, position: position, wasPlaying: wasPlaying);
}
@override
void dispose() {
_controller?.removeListener(_onTick);
_controller?.dispose();
super.dispose();
}
void _togglePlay() {
final c = _controller;
if (c == null || !c.value.isInitialized) return;
setState(() => c.value.isPlaying ? c.pause() : c.play());
}
void _toggleControls() {
setState(() => _controlsVisible = !_controlsVisible);
}
@override
Widget build(BuildContext context) {
final c = _controller;
final ready = c != null && c.value.isInitialized;
final buffering = ready && c.value.isBuffering;
final value = ready ? c.value : null;
return Scaffold(
backgroundColor: Colors.black,
body: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: _toggleControls,
child: Stack(
children: [
Center(
child: _error
? const Icon(Symbols.error, color: Colors.white54, size: 64)
: ready
? AspectRatio(
aspectRatio: c.value.aspectRatio,
child: VideoPlayer(c),
)
: const SmallSpinner(size: 36, color: Colors.white),
),
if (buffering)
const Center(
child: SmallSpinner(size: 36, color: Colors.white),
),
if (!_error)
AnimatedOpacity(
opacity: _controlsVisible ? 1 : 0,
duration: const Duration(milliseconds: 150),
child: IgnorePointer(
ignoring: !_controlsVisible,
child: _buildControls(context, value, buffering),
),
),
],
),
),
);
}
Widget _buildControls(
BuildContext context,
VideoPlayerValue? value,
bool buffering,
) {
final topPad = MediaQuery.of(context).padding.top;
final bottomPad = MediaQuery.of(context).padding.bottom;
final duration = value?.duration ?? Duration.zero;
final position = value?.position ?? Duration.zero;
final maxMs = duration.inMilliseconds.toDouble();
final posMs = position.inMilliseconds.toDouble().clamp(0, maxMs);
final sliderValue = _dragValue ?? posMs.toDouble();
final isPlaying = value?.isPlaying ?? false;
return Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.black54, Colors.transparent, Colors.black54],
stops: [0, 0.5, 1],
),
),
child: Column(
children: [
Padding(
padding: EdgeInsets.only(top: topPad + 4, left: 4, right: 8),
child: Row(
children: [
IconButton(
icon: const Icon(Symbols.close, color: Colors.white),
onPressed: () => Navigator.of(context).pop(),
),
const Spacer(),
if (widget.sources.length > 1)
PopupMenuButton<String>(
color: Colors.black87,
initialValue: _quality,
onSelected: _switchQuality,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 6,
),
decoration: BoxDecoration(
color: Colors.white24,
borderRadius: BorderRadius.circular(8),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Symbols.tune,
color: Colors.white,
size: 18,
),
const SizedBox(width: 6),
Text(
_quality,
style: const TextStyle(
color: Colors.white,
fontSize: 14,
),
),
],
),
),
itemBuilder: (_) => widget.sources.keys
.map(
(q) => PopupMenuItem<String>(
value: q,
child: Row(
children: [
Icon(
q == _quality
? Symbols.check
: Symbols.check_box_outline_blank,
color: q == _quality
? Colors.white
: Colors.transparent,
size: 18,
),
const SizedBox(width: 8),
Text(
q,
style: const TextStyle(color: Colors.white),
),
],
),
),
)
.toList(),
),
],
),
),
Expanded(
child: Center(
child: buffering
? const SizedBox.shrink()
: IconButton(
iconSize: 64,
icon: Icon(
isPlaying ? Symbols.pause : Symbols.play_arrow,
color: Colors.white,
fill: 1,
),
onPressed: _togglePlay,
),
),
),
Padding(
padding: EdgeInsets.only(
left: 12,
right: 12,
bottom: bottomPad + 8,
),
child: Row(
children: [
Text(
formatDurationClock(position),
style: const TextStyle(color: Colors.white, fontSize: 12),
),
Expanded(
child: SliderTheme(
data: SliderTheme.of(context).copyWith(
trackHeight: 2,
thumbShape: const RoundSliderThumbShape(
enabledThumbRadius: 6,
),
overlayShape: const RoundSliderOverlayShape(
overlayRadius: 14,
),
activeTrackColor: Colors.white,
inactiveTrackColor: Colors.white30,
thumbColor: Colors.white,
),
child: Slider(
min: 0,
max: maxMs <= 0 ? 1 : maxMs,
value: maxMs <= 0
? 0
: sliderValue.clamp(0, maxMs).toDouble(),
onChanged: maxMs <= 0
? null
: (v) => setState(() => _dragValue = v),
onChangeEnd: maxMs <= 0
? null
: (v) {
_controller?.seekTo(
Duration(milliseconds: v.round()),
);
setState(() => _dragValue = null);
},
),
),
),
Text(
formatDurationClock(duration),
style: const TextStyle(color: Colors.white, fontSize: 12),
),
],
),
),
],
),
);
}
}
+15
View File
@@ -581,6 +581,21 @@
"photoViewerSaveAs": "Save as…",
"photoViewerViewAll": "View all photos",
"photoViewerRotate": "Rotate",
"mediaViewerCounter": "{index} of {total}",
"@mediaViewerCounter": {
"placeholders": {
"index": {
"type": "int"
},
"total": {
"type": "int"
}
}
},
"mediaViewerViewAll": "View all media",
"videoViewerSettings": "Settings",
"videoViewerSpeed": "Speed",
"videoViewerQuality": "Quality",
"sharedCopyLink": "Copy link",
"sharedLinkCopied": "Link copied",
"chatInfoActionLeave": "Leave",
+30
View File
@@ -2642,6 +2642,36 @@ abstract class AppLocalizations {
/// **'Rotate'**
String get photoViewerRotate;
/// No description provided for @mediaViewerCounter.
///
/// In en, this message translates to:
/// **'{index} of {total}'**
String mediaViewerCounter(int index, int total);
/// No description provided for @mediaViewerViewAll.
///
/// In en, this message translates to:
/// **'View all media'**
String get mediaViewerViewAll;
/// No description provided for @videoViewerSettings.
///
/// In en, this message translates to:
/// **'Settings'**
String get videoViewerSettings;
/// No description provided for @videoViewerSpeed.
///
/// In en, this message translates to:
/// **'Speed'**
String get videoViewerSpeed;
/// No description provided for @videoViewerQuality.
///
/// In en, this message translates to:
/// **'Quality'**
String get videoViewerQuality;
/// No description provided for @sharedCopyLink.
///
/// In en, this message translates to:
+17
View File
@@ -1360,6 +1360,23 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get photoViewerRotate => 'Rotate';
@override
String mediaViewerCounter(int index, int total) {
return '$index of $total';
}
@override
String get mediaViewerViewAll => 'View all media';
@override
String get videoViewerSettings => 'Settings';
@override
String get videoViewerSpeed => 'Speed';
@override
String get videoViewerQuality => 'Quality';
@override
String get sharedCopyLink => 'Copy link';
+17
View File
@@ -1368,6 +1368,23 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get photoViewerRotate => 'Повернуть';
@override
String mediaViewerCounter(int index, int total) {
return '$index из $total';
}
@override
String get mediaViewerViewAll => 'Все медиа чата';
@override
String get videoViewerSettings => 'Настройки';
@override
String get videoViewerSpeed => 'Скорость';
@override
String get videoViewerQuality => 'Качество';
@override
String get sharedCopyLink => 'Копировать ссылку';
+5
View File
@@ -447,6 +447,11 @@
"photoViewerSaveAs": "Сохранить как…",
"photoViewerViewAll": "Все фото чата",
"photoViewerRotate": "Повернуть",
"mediaViewerCounter": "{index} из {total}",
"mediaViewerViewAll": "Все медиа чата",
"videoViewerSettings": "Настройки",
"videoViewerSpeed": "Скорость",
"videoViewerQuality": "Качество",
"sharedCopyLink": "Копировать ссылку",
"sharedLinkCopied": "Ссылка скопирована",
"chatInfoActionLeave": "Покинуть",