АААААА СУКО ПЛЕИР МУЗЫКО

This commit is contained in:
needle10
2025-11-22 17:29:31 +03:00
parent 51168a6481
commit bf995d8358
6 changed files with 1632 additions and 40 deletions

View File

@@ -0,0 +1,511 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../services/music_player_service.dart';
class BottomSheetMusicPlayer extends StatefulWidget {
const BottomSheetMusicPlayer({super.key});
static final ValueNotifier<bool> isExpandedNotifier = ValueNotifier<bool>(
false,
);
@override
State<BottomSheetMusicPlayer> createState() => _BottomSheetMusicPlayerState();
}
class _BottomSheetMusicPlayerState extends State<BottomSheetMusicPlayer>
with SingleTickerProviderStateMixin {
late AnimationController _animationController;
bool _isExpanded = false;
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 200),
);
BottomSheetMusicPlayer.isExpandedNotifier.addListener(_onExpandedChanged);
}
void _onExpandedChanged() {
final shouldBeExpanded = BottomSheetMusicPlayer.isExpandedNotifier.value;
if (shouldBeExpanded != _isExpanded) {
setState(() {
_isExpanded = shouldBeExpanded;
if (_isExpanded) {
_animationController.forward();
} else {
_animationController.reverse();
}
});
}
}
@override
void dispose() {
BottomSheetMusicPlayer.isExpandedNotifier.removeListener(
_onExpandedChanged,
);
_animationController.dispose();
super.dispose();
}
void _toggleExpand() {
setState(() {
_isExpanded = !_isExpanded;
BottomSheetMusicPlayer.isExpandedNotifier.value = _isExpanded;
if (_isExpanded) {
_animationController.forward();
} else {
_animationController.reverse();
}
});
}
String _formatDuration(Duration duration) {
String twoDigits(int n) => n.toString().padLeft(2, '0');
final hours = duration.inHours;
final minutes = duration.inMinutes.remainder(60);
final seconds = duration.inSeconds.remainder(60);
if (hours > 0) {
return '${twoDigits(hours)}:${twoDigits(minutes)}:${twoDigits(seconds)}';
}
return '${twoDigits(minutes)}:${twoDigits(seconds)}';
}
@override
Widget build(BuildContext context) {
final musicPlayer = context.watch<MusicPlayerService>();
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final track = musicPlayer.currentTrack;
if (track == null) {
return const SizedBox.shrink();
}
return AnimatedBuilder(
animation: _animationController,
builder: (context, child) {
final screenHeight = MediaQuery.of(context).size.height;
final collapsedHeight = 100.0;
final expandedHeight = screenHeight * 0.75;
final animationValue = Curves.easeInOut.transform(
_animationController.value,
);
final currentHeight =
collapsedHeight +
(expandedHeight - collapsedHeight) * animationValue;
return Material(
color: Colors.transparent,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
curve: Curves.easeInOut,
height: currentHeight,
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.only(
topLeft: const Radius.circular(24),
topRight: const Radius.circular(24),
bottomLeft: Radius.circular(24 * (1 - animationValue)),
bottomRight: Radius.circular(24 * (1 - animationValue)),
),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.2),
blurRadius: 12,
offset: const Offset(0, -4),
),
],
),
child: _buildAnimatedContent(
context,
musicPlayer,
track,
colorScheme,
),
),
);
},
);
}
Widget _buildAnimatedContent(
BuildContext context,
MusicPlayerService musicPlayer,
MusicTrack track,
ColorScheme colorScheme,
) {
return AnimatedSwitcher(
duration: const Duration(milliseconds: 300),
switchInCurve: Curves.easeInOut,
switchOutCurve: Curves.easeInOut,
transitionBuilder: (Widget child, Animation<double> animation) {
return FadeTransition(
opacity: animation,
child: SlideTransition(
position:
Tween<Offset>(
begin: const Offset(0.0, 0.1),
end: Offset.zero,
).animate(
CurvedAnimation(parent: animation, curve: Curves.easeInOut),
),
child: child,
),
);
},
child: _isExpanded
? _buildExpandedView(context, musicPlayer, track, colorScheme)
: _buildCollapsedView(context, musicPlayer, track, colorScheme),
);
}
Widget _buildCollapsedView(
BuildContext context,
MusicPlayerService musicPlayer,
MusicTrack track,
ColorScheme colorScheme,
) {
return SafeArea(
key: const ValueKey('collapsed'),
top: false,
child: GestureDetector(
onTap: _toggleExpand,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
child: Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Container(
width: 48,
height: 48,
color: colorScheme.primaryContainer,
child: track.albumArtUrl != null
? Image.network(
track.albumArtUrl!,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) =>
_buildAlbumArtPlaceholder(colorScheme),
)
: _buildAlbumArtPlaceholder(colorScheme),
),
),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Text(
track.title,
style: Theme.of(context).textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w600,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
Text(
track.artist,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: colorScheme.onSurface.withOpacity(0.7),
fontSize: 12,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
const SizedBox(width: 8),
GestureDetector(
onTap: () {
if (musicPlayer.isPlaying) {
musicPlayer.pause();
} else {
musicPlayer.resume();
}
},
child: Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: colorScheme.primary,
shape: BoxShape.circle,
),
child: Icon(
musicPlayer.isPlaying ? Icons.pause : Icons.play_arrow,
size: 24,
color: colorScheme.onPrimary,
),
),
),
],
),
),
),
);
}
Widget _buildExpandedView(
BuildContext context,
MusicPlayerService musicPlayer,
MusicTrack track,
ColorScheme colorScheme,
) {
return SafeArea(
key: const ValueKey('expanded'),
top: false,
child: Column(
children: [
GestureDetector(
onTap: _toggleExpand,
onVerticalDragEnd: (details) {
if (details.primaryVelocity != null &&
details.primaryVelocity! > 200) {
_toggleExpand();
}
},
child: Container(
margin: const EdgeInsets.only(top: 12),
padding: const EdgeInsets.symmetric(vertical: 12),
width: double.infinity,
child: Center(
child: Container(
width: 40,
height: 4,
decoration: BoxDecoration(
color: colorScheme.onSurface.withOpacity(0.3),
borderRadius: BorderRadius.circular(2),
),
),
),
),
),
Expanded(
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
LayoutBuilder(
builder: (context, constraints) {
final maxWidth = constraints.maxWidth;
final albumSize = maxWidth < 400 ? maxWidth : 400.0;
return Container(
width: albumSize,
height: albumSize,
margin: EdgeInsets.symmetric(
horizontal: (maxWidth - albumSize) / 2,
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.3),
blurRadius: 20,
offset: const Offset(0, 10),
),
],
),
child: ClipRRect(
borderRadius: BorderRadius.circular(24),
child: track.albumArtUrl != null
? Image.network(
track.albumArtUrl!,
fit: BoxFit.cover,
errorBuilder:
(context, error, stackTrace) =>
_buildLargeAlbumArtPlaceholder(
context,
colorScheme,
),
)
: _buildLargeAlbumArtPlaceholder(
context,
colorScheme,
),
),
);
},
),
const SizedBox(height: 16),
Text(
track.title,
style: Theme.of(context).textTheme.headlineSmall
?.copyWith(fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
Text(
track.artist,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
color: colorScheme.onSurface.withOpacity(0.7),
),
textAlign: TextAlign.center,
),
if (track.album != null) ...[
const SizedBox(height: 4),
Text(
track.album!,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurface.withOpacity(0.6),
),
textAlign: TextAlign.center,
),
],
const SizedBox(height: 32),
Column(
children: [
Slider(
value: musicPlayer.duration.inMilliseconds > 0
? musicPlayer.position.inMilliseconds /
musicPlayer.duration.inMilliseconds
: 0.0,
onChanged: (value) {
final newPosition = Duration(
milliseconds:
(value * musicPlayer.duration.inMilliseconds)
.round(),
);
musicPlayer.seek(newPosition);
},
activeColor: colorScheme.primary,
inactiveColor: colorScheme.surfaceContainerHigh,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
_formatDuration(musicPlayer.position),
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: colorScheme.onSurface.withOpacity(
0.7,
),
),
),
Text(
_formatDuration(musicPlayer.duration),
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: colorScheme.onSurface.withOpacity(
0.7,
),
),
),
],
),
),
],
),
const SizedBox(height: 24),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
onPressed: musicPlayer.previous,
icon: const Icon(Icons.skip_previous),
iconSize: 32,
style: IconButton.styleFrom(
backgroundColor: colorScheme.surfaceContainerHigh,
foregroundColor: colorScheme.onSurface,
padding: const EdgeInsets.all(16),
),
),
const SizedBox(width: 16),
FilledButton(
onPressed: () {
if (musicPlayer.isPlaying) {
musicPlayer.pause();
} else {
musicPlayer.resume();
}
},
style: FilledButton.styleFrom(
backgroundColor: colorScheme.primary,
foregroundColor: colorScheme.onPrimary,
padding: const EdgeInsets.all(20),
shape: const CircleBorder(),
minimumSize: const Size(72, 72),
),
child: musicPlayer.isLoading
? SizedBox(
width: 32,
height: 32,
child: CircularProgressIndicator(
strokeWidth: 3,
valueColor: AlwaysStoppedAnimation<Color>(
colorScheme.onPrimary,
),
),
)
: Icon(
musicPlayer.isPlaying
? Icons.pause
: Icons.play_arrow,
size: 36,
),
),
const SizedBox(width: 16),
IconButton(
onPressed: musicPlayer.next,
icon: const Icon(Icons.skip_next),
iconSize: 32,
style: IconButton.styleFrom(
backgroundColor: colorScheme.surfaceContainerHigh,
foregroundColor: colorScheme.onSurface,
padding: const EdgeInsets.all(16),
),
),
],
),
const SizedBox(height: 24),
],
),
),
),
),
],
),
);
}
Widget _buildAlbumArtPlaceholder(ColorScheme colorScheme) {
return Container(
color: colorScheme.primaryContainer,
child: Icon(
Icons.music_note,
color: colorScheme.onPrimaryContainer,
size: 28,
),
);
}
Widget _buildLargeAlbumArtPlaceholder(
BuildContext context,
ColorScheme colorScheme,
) {
return Container(
width: double.infinity,
height: double.infinity,
color: colorScheme.primaryContainer,
child: Icon(
Icons.music_note,
color: colorScheme.onPrimaryContainer,
size: 80,
),
);
}
}

View File

@@ -1,6 +1,6 @@
import 'package:flutter/material.dart';
import 'dart:io' show File;
import 'dart:convert' show base64Decode;
import 'dart:convert' show base64Decode, jsonDecode, jsonEncode;
import 'package:http/http.dart' as http;
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
@@ -25,6 +25,7 @@ import 'package:gwid/full_screen_video_player.dart';
import 'package:just_audio/just_audio.dart';
import 'package:gwid/services/cache_service.dart';
import 'package:video_player/video_player.dart';
import 'package:gwid/services/music_player_service.dart';
bool _currentIsDark = false;
@@ -2117,17 +2118,34 @@ class ChatMessageBubble extends StatelessWidget {
final fileName = file['name'] ?? 'Файл';
final fileSize = file['size'] as int? ?? 0;
widgets.add(
_buildFileWidget(
context,
fileName,
fileSize,
file,
textColor,
isUltraOptimized,
chatId,
),
);
final preview = file['preview'] as Map<String, dynamic>?;
final isMusic = preview != null && preview['_type'] == 'MUSIC';
if (isMusic) {
widgets.add(
_buildMusicFileWidget(
context,
fileName,
fileSize,
file,
textColor,
isUltraOptimized,
chatId,
),
);
} else {
widgets.add(
_buildFileWidget(
context,
fileName,
fileSize,
file,
textColor,
isUltraOptimized,
chatId,
),
);
}
widgets.add(const SizedBox(height: 6));
}
@@ -2302,6 +2320,406 @@ class ChatMessageBubble extends StatelessWidget {
);
}
Widget _buildMusicFileWidget(
BuildContext context,
String fileName,
int fileSize,
Map<String, dynamic> fileData,
Color textColor,
bool isUltraOptimized,
int? chatId,
) {
final borderRadius = BorderRadius.circular(isUltraOptimized ? 8 : 12);
final preview = fileData['preview'] as Map<String, dynamic>?;
final fileId = fileData['fileId'] as int?;
final token = fileData['token'] as String?;
final title = preview?['title'] as String? ?? fileName;
final artist = preview?['artistName'] as String? ?? 'Unknown Artist';
final album = preview?['albumName'] as String?;
final albumArtUrl = preview?['baseUrl'] as String?;
final duration = preview?['duration'] as int?;
String durationText = '';
if (duration != null) {
final durationSeconds = (duration / 1000).round();
final minutes = durationSeconds ~/ 60;
final seconds = durationSeconds % 60;
durationText = '$minutes:${seconds.toString().padLeft(2, '0')}';
}
final sizeStr = _formatFileSize(fileSize);
return GestureDetector(
onTap: () async {
final prefs = await SharedPreferences.getInstance();
final fileIdMap = prefs.getStringList('file_id_to_path_map') ?? [];
final fileIdString = fileId?.toString();
bool isDownloaded = false;
String? filePath;
if (fileIdString != null) {
for (final mapping in fileIdMap) {
if (mapping.startsWith('$fileIdString:')) {
filePath = mapping.substring(fileIdString.length + 1);
final file = io.File(filePath);
if (await file.exists()) {
isDownloaded = true;
break;
}
}
}
}
if (!isDownloaded) {
await _handleFileDownload(context, fileId, token, fileName, chatId);
await Future.delayed(const Duration(seconds: 1));
if (fileIdString != null) {
final updatedFileIdMap =
prefs.getStringList('file_id_to_path_map') ?? [];
for (final mapping in updatedFileIdMap) {
if (mapping.startsWith('$fileIdString:')) {
filePath = mapping.substring(fileIdString.length + 1);
final file = io.File(filePath);
if (await file.exists()) {
isDownloaded = true;
break;
}
}
}
}
}
if (isDownloaded && filePath != null) {
final track = MusicTrack(
id:
fileId?.toString() ??
DateTime.now().millisecondsSinceEpoch.toString(),
title: title,
artist: artist,
album: album,
albumArtUrl: albumArtUrl,
duration: duration,
filePath: filePath,
fileId: fileId,
token: token,
chatId: chatId,
);
final musicMetadataJson = prefs.getString('music_metadata') ?? '{}';
final musicMetadata =
jsonDecode(musicMetadataJson) as Map<String, dynamic>;
musicMetadata[fileIdString ?? ''] = track.toJson();
await prefs.setString('music_metadata', jsonEncode(musicMetadata));
final musicPlayer = MusicPlayerService();
await musicPlayer.playTrack(track);
}
},
child: Container(
decoration: BoxDecoration(
color: textColor.withOpacity(0.05),
borderRadius: borderRadius,
border: Border.all(color: textColor.withOpacity(0.1), width: 1),
),
child: Padding(
padding: const EdgeInsets.all(12),
child: Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Container(
width: 56,
height: 56,
color: textColor.withOpacity(0.1),
child: albumArtUrl != null
? Image.network(
albumArtUrl,
fit: BoxFit.cover,
errorBuilder: (context, error, stackTrace) => Icon(
Icons.music_note,
color: textColor.withOpacity(0.8),
size: 24,
),
)
: Icon(
Icons.music_note,
color: textColor.withOpacity(0.8),
size: 24,
),
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
title,
style: TextStyle(
color: textColor,
fontSize: 14,
fontWeight: FontWeight.w600,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
Text(
artist,
style: TextStyle(
color: textColor.withOpacity(0.7),
fontSize: 12,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
if (album != null) ...[
const SizedBox(height: 2),
Text(
album,
style: TextStyle(
color: textColor.withOpacity(0.6),
fontSize: 11,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
const SizedBox(height: 4),
if (fileId != null)
ValueListenableBuilder<double>(
valueListenable: FileDownloadProgressService()
.getProgress(fileId.toString()),
builder: (context, progress, child) {
if (progress < 0) {
return Row(
children: [
if (durationText.isNotEmpty) ...[
Text(
durationText,
style: TextStyle(
color: textColor.withOpacity(0.6),
fontSize: 11,
),
),
const SizedBox(width: 8),
Text(
'',
style: TextStyle(
color: textColor.withOpacity(0.6),
fontSize: 11,
),
),
const SizedBox(width: 8),
],
Text(
sizeStr,
style: TextStyle(
color: textColor.withOpacity(0.6),
fontSize: 11,
),
),
],
);
} else if (progress < 1.0) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
LinearProgressIndicator(
value: progress,
minHeight: 3,
backgroundColor: textColor.withOpacity(0.1),
),
const SizedBox(height: 4),
Text(
'${(progress * 100).toStringAsFixed(0)}%',
style: TextStyle(
color: textColor.withOpacity(0.6),
fontSize: 11,
),
),
],
);
} else {
return Row(
children: [
Icon(
Icons.check_circle,
size: 12,
color: Colors.green.withOpacity(0.8),
),
const SizedBox(width: 4),
Text(
'Загружено',
style: TextStyle(
color: Colors.green.withOpacity(0.8),
fontSize: 11,
),
),
],
);
}
},
)
else
Row(
children: [
if (durationText.isNotEmpty) ...[
Text(
durationText,
style: TextStyle(
color: textColor.withOpacity(0.6),
fontSize: 11,
),
),
const SizedBox(width: 8),
Text(
'',
style: TextStyle(
color: textColor.withOpacity(0.6),
fontSize: 11,
),
),
const SizedBox(width: 8),
],
Text(
sizeStr,
style: TextStyle(
color: textColor.withOpacity(0.6),
fontSize: 11,
),
),
],
),
],
),
),
if (fileId != null)
ValueListenableBuilder<double>(
valueListenable: FileDownloadProgressService().getProgress(
fileId.toString(),
),
builder: (context, progress, child) {
if (progress >= 0 && progress < 1.0) {
return const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
);
}
return IconButton(
onPressed: () async {
final prefs = await SharedPreferences.getInstance();
final fileIdMap =
prefs.getStringList('file_id_to_path_map') ?? [];
final fileIdString = fileId.toString();
bool isDownloaded = false;
String? filePath;
for (final mapping in fileIdMap) {
if (mapping.startsWith('$fileIdString:')) {
filePath = mapping.substring(
fileIdString.length + 1,
);
final file = io.File(filePath);
if (await file.exists()) {
isDownloaded = true;
break;
}
}
}
if (!isDownloaded) {
await _handleFileDownload(
context,
fileId,
token,
fileName,
chatId,
);
await Future.delayed(const Duration(seconds: 1));
final updatedFileIdMap =
prefs.getStringList('file_id_to_path_map') ?? [];
for (final mapping in updatedFileIdMap) {
if (mapping.startsWith('$fileIdString:')) {
filePath = mapping.substring(
fileIdString.length + 1,
);
final file = io.File(filePath);
if (await file.exists()) {
isDownloaded = true;
break;
}
}
}
}
if (isDownloaded && filePath != null) {
final track = MusicTrack(
id: fileId.toString(),
title: title,
artist: artist,
album: album,
albumArtUrl: albumArtUrl,
duration: duration,
filePath: filePath,
fileId: fileId,
token: token,
chatId: chatId,
);
final musicMetadataJson =
prefs.getString('music_metadata') ?? '{}';
final musicMetadata =
jsonDecode(musicMetadataJson)
as Map<String, dynamic>;
musicMetadata[fileIdString] = track.toJson();
await prefs.setString(
'music_metadata',
jsonEncode(musicMetadata),
);
final musicPlayer = MusicPlayerService();
await musicPlayer.playTrack(track);
}
},
icon: const Icon(Icons.play_arrow),
style: IconButton.styleFrom(
backgroundColor: textColor.withOpacity(0.1),
foregroundColor: textColor,
),
);
},
)
else
IconButton(
onPressed: () async {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Не удалось загрузить файл'),
backgroundColor: Colors.red,
),
);
}
},
icon: const Icon(Icons.play_arrow),
style: IconButton.styleFrom(
backgroundColor: textColor.withOpacity(0.1),
foregroundColor: textColor,
),
),
],
),
),
),
);
}
String _getFileExtension(String fileName) {
final parts = fileName.split('.');
if (parts.length > 1) {