diff --git a/lib/core/di/cubit_registrations.dart b/lib/core/di/cubit_registrations.dart index acbffda9..92ba8925 100644 --- a/lib/core/di/cubit_registrations.dart +++ b/lib/core/di/cubit_registrations.dart @@ -55,6 +55,7 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/features/user_details/presentation/cubit/user_details_cubit.dart'; import 'package:eatvio_app/features/video_calls/managers/video_call_manager.dart'; import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit.dart'; import 'package:eatvio_app/core/comments/comments_cubit/comments_cubit.dart'; import 'package:get_it/get_it.dart'; @@ -319,5 +320,8 @@ class CubitRegistrations { personalDietSuggestionService: sl(), ), ); + sl.registerFactory( + () => VideoCallRecordingsCubit(repository: sl()), + ); } } diff --git a/lib/core/di/repository_registrations.dart b/lib/core/di/repository_registrations.dart index bb260432..61e561fb 100644 --- a/lib/core/di/repository_registrations.dart +++ b/lib/core/di/repository_registrations.dart @@ -35,6 +35,7 @@ import 'package:eatvio_app/features/recipe/repositories/my_recipes_repository.da import 'package:eatvio_app/features/registration/repositories/registration_repository.dart'; import 'package:eatvio_app/features/registration_v2/repositories/registration_repository_v2.dart'; import 'package:eatvio_app/features/settings/repositories/service_repository.dart'; +import 'package:eatvio_app/features/video_calls/recordings/repositories/video_call_recordings_repository.dart'; import 'package:eatvio_app/features/video_calls/repositories/video_call_repository.dart'; import 'package:get_it/get_it.dart'; @@ -53,6 +54,9 @@ class RepositoryRegistrations { // Core repositories sl.registerLazySingleton(() => ChatRepository(chatService: sl())); sl.registerLazySingleton(() => VideoCallRepository(videoCallService: sl())); + sl.registerLazySingleton( + () => VideoCallRecordingsRepository(videoCallService: sl(), dio: sl()), + ); sl.registerLazySingleton(() => FeedRepository(feedService: sl())); sl.registerLazySingleton(() => ProfileRepository(profileService: sl())); sl.registerLazySingleton(() => CalendarRepository(calendarService: sl())); diff --git a/lib/core/routing/other_routes.dart b/lib/core/routing/other_routes.dart index 266ecece..6a3ae191 100644 --- a/lib/core/routing/other_routes.dart +++ b/lib/core/routing/other_routes.dart @@ -16,6 +16,9 @@ import 'package:eatvio_app/features/chat/presentation/pages/payment_screen.dart' import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart'; import 'package:eatvio_app/features/video_calls/presentation/pages/video_call_screen.dart'; import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_state.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/pages/video_call_recording_player_screen.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/become_consultant_screen.dart'; import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/stepper_become_consultant_screen.dart'; import 'package:eatvio_app/features/consultant_rating/presentation/consultant_rating_screen.dart'; @@ -140,6 +143,19 @@ class OtherRoutes { GoRoute(path: ConsultationsArchiveScreen.path, name: ConsultationsArchiveScreen.name, builder: (context, state) => const ConsultationsArchiveScreen()), GoRoute(path: ConsultantFinancesScreen.path, name: ConsultantFinancesScreen.name, builder: (context, state) => const ConsultantFinancesScreen()), GoRoute(path: UserPurchasesScreen.path, name: UserPurchasesScreen.name, builder: (context, state) => const UserPurchasesScreen()), + GoRoute( + path: VideoCallRecordingsScreen.path, + name: VideoCallRecordingsScreen.name, + builder: (context, state) => const VideoCallRecordingsScreen(), + ), + GoRoute( + path: VideoCallRecordingPlayerScreen.path, + name: VideoCallRecordingPlayerScreen.name, + builder: (context, state) { + final recording = state.extra as VideoCallRecordingModel; + return VideoCallRecordingPlayerScreen(recording: recording); + }, + ), // Finance routes GoRoute(path: RouteConstants.userFinanceScreen, name: 'userFinanceScreen', builder: (context, state) => const UserFinanceScreen()), diff --git a/lib/features/menu/presentation/pages/menu_screen.dart b/lib/features/menu/presentation/pages/menu_screen.dart index ba53911f..29f7ed28 100644 --- a/lib/features/menu/presentation/pages/menu_screen.dart +++ b/lib/features/menu/presentation/pages/menu_screen.dart @@ -14,6 +14,7 @@ import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_state import 'package:eatvio_app/features/my_diets/presentation/my_diets_screen.dart'; import 'package:eatvio_app/features/my_plans/presentation/my_plans_screen.dart'; import 'package:eatvio_app/features/recipe/presentation/pages/my_recipes_screen.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; @@ -49,6 +50,12 @@ class MenuScreen extends StatelessWidget { if (profileModel.roles.contains('consultant')) _divider(context), if (profileModel.roles.contains('consultant')) _tile(leading: ImageConstant.icnPlans, title: 'Мои планы', onTap: () => GoRouter.of(context).push(MyPlansScreen.path)), + _divider(context), + _tile( + leading: ImageConstant.icnConsultation, + title: 'Мои консультации', + onTap: () => GoRouter.of(context).push(VideoCallRecordingsScreen.path), + ), if (!hidePlans) ...[ _divider(context), _tile( diff --git a/lib/features/video_calls/recordings/models/recording_duration_formatter.dart b/lib/features/video_calls/recordings/models/recording_duration_formatter.dart new file mode 100644 index 00000000..91b4e9c5 --- /dev/null +++ b/lib/features/video_calls/recordings/models/recording_duration_formatter.dart @@ -0,0 +1,18 @@ +String formatRecordingDuration(int? durationSeconds) { + if (durationSeconds == null || durationSeconds < 0) { + return ''; + } + + final hours = durationSeconds ~/ 3600; + final minutes = (durationSeconds % 3600) ~/ 60; + final seconds = durationSeconds % 60; + + final mm = minutes.toString().padLeft(2, '0'); + final ss = seconds.toString().padLeft(2, '0'); + + if (hours > 0) { + return '$hours:$mm:$ss'; + } + + return '$mm:$ss'; +} diff --git a/lib/features/video_calls/recordings/models/recording_not_ready_exception.dart b/lib/features/video_calls/recordings/models/recording_not_ready_exception.dart new file mode 100644 index 00000000..c690e4ec --- /dev/null +++ b/lib/features/video_calls/recordings/models/recording_not_ready_exception.dart @@ -0,0 +1,10 @@ +class RecordingNotReadyException implements Exception { + const RecordingNotReadyException({this.message}); + + final String? message; + + static const code = 'recording_not_ready'; + + @override + String toString() => message ?? 'Recording is not ready'; +} diff --git a/lib/features/video_calls/recordings/models/recording_period.dart b/lib/features/video_calls/recordings/models/recording_period.dart new file mode 100644 index 00000000..6ac5d6b4 --- /dev/null +++ b/lib/features/video_calls/recordings/models/recording_period.dart @@ -0,0 +1,13 @@ +/// Период фильтра списка записей. +/// Значение совпадает с `filters[created_at][$date_range]`. +enum RecordingPeriod { + today('today'), + week('week'), + currentMonth('current_month'), + prevMonth('prev_month'), + all('all'); + + const RecordingPeriod(this.apiValue); + + final String apiValue; +} diff --git a/lib/features/video_calls/recordings/models/video_call_recording_model.dart b/lib/features/video_calls/recordings/models/video_call_recording_model.dart new file mode 100644 index 00000000..69918629 --- /dev/null +++ b/lib/features/video_calls/recordings/models/video_call_recording_model.dart @@ -0,0 +1,52 @@ +import 'package:eatvio_app/core/models/pagination_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'video_call_recording_model.freezed.dart'; +part 'video_call_recording_model.g.dart'; + +@freezed +abstract class VideoCallRecordingsPagination with _$VideoCallRecordingsPagination { + const factory VideoCallRecordingsPagination({ + @JsonKey(name: 'data') required List data, + @JsonKey(name: 'links') required Links links, + @JsonKey(name: 'meta') required Meta meta, + }) = _VideoCallRecordingsPagination; + + factory VideoCallRecordingsPagination.fromJson(Map json) => + _$VideoCallRecordingsPaginationFromJson(json); +} + +@freezed +abstract class VideoCallRecordingModel with _$VideoCallRecordingModel { + const VideoCallRecordingModel._(); + + const factory VideoCallRecordingModel({ + @JsonKey(name: 'id') required int id, + @JsonKey(name: 'status') required String status, + @JsonKey(name: 'duration_seconds') int? durationSeconds, + @JsonKey(name: 'size_bytes') int? sizeBytes, + @JsonKey(name: 'created_at') required DateTime createdAt, + @JsonKey(name: 'preview_url') required String previewUrl, + @JsonKey(name: 'file_url') String? fileUrl, + @JsonKey(name: 'counterpart') VideoCallRecordingCounterpartModel? counterpart, + }) = _VideoCallRecordingModel; + + factory VideoCallRecordingModel.fromJson(Map json) => + _$VideoCallRecordingModelFromJson(json); + + bool get isReady => status == 'ready'; + + bool get isInProgress => status == 'in_progress'; +} + +@freezed +abstract class VideoCallRecordingCounterpartModel with _$VideoCallRecordingCounterpartModel { + const factory VideoCallRecordingCounterpartModel({ + @JsonKey(name: 'name') required String name, + @JsonKey(name: 'slug') required String slug, + @JsonKey(name: 'profile_photo_url') String? profilePhotoUrl, + }) = _VideoCallRecordingCounterpartModel; + + factory VideoCallRecordingCounterpartModel.fromJson(Map json) => + _$VideoCallRecordingCounterpartModelFromJson(json); +} diff --git a/lib/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit.dart b/lib/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit.dart new file mode 100644 index 00000000..79a3c179 --- /dev/null +++ b/lib/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit.dart @@ -0,0 +1,124 @@ +import 'dart:developer'; +import 'dart:io'; + +import 'package:eatvio_app/core/error_reporting/report_from.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/recording_period.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/cubit/video_call_recordings_state.dart'; +import 'package:eatvio_app/features/video_calls/recordings/repositories/video_call_recordings_repository.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; + +class VideoCallRecordingsCubit extends Cubit { + VideoCallRecordingsCubit({required this.repository}) + : super(const VideoCallRecordingsState()); + + final VideoCallRecordingsRepository repository; + + Future load({bool refresh = false}) async { + if (state.isLoading && !refresh && state.recordings.isNotEmpty) { + return; + } + + emit( + state.copyWith( + isLoading: true, + error: null, + currentPage: 1, + ), + ); + + try { + final page = await repository.getRecordings( + page: 1, + period: state.period == RecordingPeriod.all ? null : state.period, + ); + + emit( + state.copyWith( + isLoading: false, + recordings: page.data, + currentPage: page.meta.currentPage, + lastPage: page.meta.lastPage, + error: null, + ), + ); + } catch (error, stackTrace) { + await reportFrom(error, stackTrace, this); + log(error.toString(), stackTrace: stackTrace); + emit( + state.copyWith( + isLoading: false, + error: error.toString(), + ), + ); + } + } + + Future setPeriod(RecordingPeriod period) async { + if (state.period == period) { + return; + } + + emit(state.copyWith(period: period)); + await load(refresh: true); + } + + Future loadNextPage() async { + if (state.isLoading || state.isLoadingMore || state.currentPage >= state.lastPage) { + return; + } + + final nextPage = state.currentPage + 1; + emit(state.copyWith(isLoadingMore: true, error: null)); + + try { + final page = await repository.getRecordings( + page: nextPage, + period: state.period == RecordingPeriod.all ? null : state.period, + ); + + emit( + state.copyWith( + isLoadingMore: false, + recordings: [...state.recordings, ...page.data], + currentPage: page.meta.currentPage, + lastPage: page.meta.lastPage, + ), + ); + } catch (error, stackTrace) { + await reportFrom(error, stackTrace, this); + log(error.toString(), stackTrace: stackTrace); + emit( + state.copyWith( + isLoadingMore: false, + error: error.toString(), + ), + ); + } + } + + Future downloadRecording({ + required int recordingId, + required String fileUrl, + }) async { + emit(state.copyWith(isDownloading: true, downloadError: null)); + + try { + final file = await repository.downloadRecordingFile( + fileUrl: fileUrl, + recordingId: recordingId, + ); + emit(state.copyWith(isDownloading: false)); + return file; + } catch (error, stackTrace) { + await reportFrom(error, stackTrace, this); + log(error.toString(), stackTrace: stackTrace); + emit( + state.copyWith( + isDownloading: false, + downloadError: error.toString(), + ), + ); + return null; + } + } +} diff --git a/lib/features/video_calls/recordings/presentation/cubit/video_call_recordings_state.dart b/lib/features/video_calls/recordings/presentation/cubit/video_call_recordings_state.dart new file mode 100644 index 00000000..b6644b25 --- /dev/null +++ b/lib/features/video_calls/recordings/presentation/cubit/video_call_recordings_state.dart @@ -0,0 +1,20 @@ +import 'package:eatvio_app/features/video_calls/recordings/models/recording_period.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'video_call_recordings_state.freezed.dart'; + +@freezed +abstract class VideoCallRecordingsState with _$VideoCallRecordingsState { + const factory VideoCallRecordingsState({ + @Default(true) bool isLoading, + @Default(false) bool isLoadingMore, + @Default(false) bool isDownloading, + @Default([]) List recordings, + @Default(RecordingPeriod.all) RecordingPeriod period, + @Default(1) int currentPage, + @Default(1) int lastPage, + String? error, + String? downloadError, + }) = _VideoCallRecordingsState; +} diff --git a/lib/features/video_calls/recordings/presentation/pages/video_call_recording_player_screen.dart b/lib/features/video_calls/recordings/presentation/pages/video_call_recording_player_screen.dart new file mode 100644 index 00000000..2c41fbf4 --- /dev/null +++ b/lib/features/video_calls/recordings/presentation/pages/video_call_recording_player_screen.dart @@ -0,0 +1,239 @@ +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/theme/custom_text_style.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/token_storage.dart'; +import 'package:eatvio_app/core/widgets/loader.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:eatvio_app/features/video_calls/recordings/repositories/video_call_recordings_repository.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:flutter/material.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:share_plus/share_plus.dart'; +import 'package:video_player/video_player.dart'; + +class VideoCallRecordingPlayerScreen extends StatefulWidget { + const VideoCallRecordingPlayerScreen({super.key, required this.recording}); + + static const name = 'videoCallRecordingPlayerScreen'; + static const path = '/video-call-recording-player-screen'; + + final VideoCallRecordingModel recording; + + @override + State createState() => _VideoCallRecordingPlayerScreenState(); +} + +class _VideoCallRecordingPlayerScreenState extends State { + VideoPlayerController? _controller; + bool _isInitializing = true; + bool _hasError = false; + bool _isDownloading = false; + + @override + void initState() { + super.initState(); + _initPlayer(); + } + + Future _initPlayer() async { + final fileUrl = widget.recording.fileUrl; + if (fileUrl == null || fileUrl.isEmpty) { + setState(() { + _isInitializing = false; + _hasError = true; + }); + return; + } + + try { + final token = await TokenStorage.getTokenFromStorage(); + final controller = VideoPlayerController.networkUrl( + Uri.parse(fileUrl), + httpHeaders: { + if (token != null && token.isNotEmpty) 'Authorization': 'Bearer $token', + }, + ); + await controller.initialize(); + await controller.play(); + if (!mounted) { + await controller.dispose(); + return; + } + setState(() { + _controller = controller; + _isInitializing = false; + }); + } catch (_) { + if (!mounted) { + return; + } + setState(() { + _isInitializing = false; + _hasError = true; + }); + } + } + + Future _download() async { + final fileUrl = widget.recording.fileUrl; + if (fileUrl == null) { + return; + } + + setState(() => _isDownloading = true); + try { + final file = await sl().downloadRecordingFile( + fileUrl: fileUrl, + recordingId: widget.recording.id, + ); + if (!mounted) { + return; + } + await SharePlus.instance.share( + ShareParams( + files: [XFile(file.path)], + text: S.of(context).video_call_recordings_card_title, + ), + ); + } catch (_) { + if (mounted) { + await Fluttertoast.showToast(msg: S.of(context).video_call_recordings_download_error); + } + } finally { + if (mounted) { + setState(() => _isDownloading = false); + } + } + } + + @override + void dispose() { + _controller?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final s = S.of(context); + final title = widget.recording.counterpart?.name ?? s.video_call_recordings_title; + final controller = _controller; + + return Scaffold( + backgroundColor: appTheme.whiteA700, + appBar: AppBar( + centerTitle: true, + title: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black), + ), + ), + body: Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 24), + child: Column( + children: [ + Expanded( + child: Center( + child: _isInitializing + ? const Loader() + : _hasError || controller == null + ? Text( + s.video_call_recordings_player_error, + textAlign: TextAlign.center, + style: TextStyles.textMMedium.copyWith(color: appTheme.blueGray400), + ) + : AspectRatio( + aspectRatio: controller.value.aspectRatio == 0 + ? 16 / 9 + : controller.value.aspectRatio, + child: Stack( + alignment: Alignment.bottomCenter, + children: [ + VideoPlayer(controller), + _PlayerControls(controller: controller), + ], + ), + ), + ), + ), + const SizedBox(height: 16), + SizedBox( + width: double.infinity, + height: 44, + child: ElevatedButton( + onPressed: _isDownloading || widget.recording.fileUrl == null ? null : _download, + style: ElevatedButton.styleFrom( + backgroundColor: appTheme.blueA400, + foregroundColor: Colors.white, + elevation: 0, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + ), + child: _isDownloading + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white), + ) + : Text( + s.video_call_recordings_download, + style: TextStyles.textSMedium.copyWith( + color: Colors.white, + fontWeight: FontWeight.w700, + ), + ), + ), + ), + ], + ), + ), + ); + } +} + +class _PlayerControls extends StatelessWidget { + const _PlayerControls({required this.controller}); + + final VideoPlayerController controller; + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: controller, + builder: (context, _) { + return ColoredBox( + color: Colors.black.withValues(alpha: 0.35), + child: Row( + children: [ + IconButton( + onPressed: () { + if (controller.value.isPlaying) { + controller.pause(); + } else { + controller.play(); + } + }, + icon: Icon( + controller.value.isPlaying ? Icons.pause : Icons.play_arrow, + color: Colors.white, + ), + ), + Expanded( + child: VideoProgressIndicator( + controller, + allowScrubbing: true, + colors: VideoProgressColors( + playedColor: appTheme.blueA400, + bufferedColor: Colors.white38, + backgroundColor: Colors.white24, + ), + ), + ), + const SizedBox(width: 8), + ], + ), + ); + }, + ); + } +} diff --git a/lib/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart b/lib/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart new file mode 100644 index 00000000..e1ee1b07 --- /dev/null +++ b/lib/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart @@ -0,0 +1,211 @@ +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/theme/custom_text_style.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/widgets/data_error_widget.dart'; +import 'package:eatvio_app/core/widgets/loader.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/cubit/video_call_recordings_state.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/pages/video_call_recording_player_screen.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/widgets/recording_card.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/widgets/recording_period_dropdown.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:fluttertoast/fluttertoast.dart'; +import 'package:go_router/go_router.dart'; +import 'package:share_plus/share_plus.dart'; + +class VideoCallRecordingsScreen extends StatelessWidget { + const VideoCallRecordingsScreen({super.key}); + + static const name = 'videoCallRecordingsScreen'; + static const path = '/video-call-recordings-screen'; + + @override + Widget build(BuildContext context) { + return BlocProvider( + create: (_) => sl()..load(), + child: const _VideoCallRecordingsView(), + ); + } +} + +class _VideoCallRecordingsView extends StatefulWidget { + const _VideoCallRecordingsView(); + + @override + State<_VideoCallRecordingsView> createState() => _VideoCallRecordingsViewState(); +} + +class _VideoCallRecordingsViewState extends State<_VideoCallRecordingsView> { + final _scrollController = ScrollController(); + int? _downloadingId; + + @override + void initState() { + super.initState(); + _scrollController.addListener(_onScroll); + } + + @override + void dispose() { + _scrollController + ..removeListener(_onScroll) + ..dispose(); + super.dispose(); + } + + void _onScroll() { + if (!_scrollController.hasClients) { + return; + } + final position = _scrollController.position; + if (position.pixels >= position.maxScrollExtent - 200) { + context.read().loadNextPage(); + } + } + + Future _download(VideoCallRecordingModel recording) async { + final fileUrl = recording.fileUrl; + if (fileUrl == null) { + return; + } + + setState(() => _downloadingId = recording.id); + final file = await context.read().downloadRecording( + recordingId: recording.id, + fileUrl: fileUrl, + ); + if (!mounted) { + return; + } + setState(() => _downloadingId = null); + + if (file == null) { + final error = context.read().state.downloadError; + await Fluttertoast.showToast( + msg: error ?? S.of(context).video_call_recordings_download_error, + ); + return; + } + + await SharePlus.instance.share( + ShareParams(files: [XFile(file.path)], text: S.of(context).video_call_recordings_card_title), + ); + } + + void _openPlayer(VideoCallRecordingModel recording) { + final fileUrl = recording.fileUrl; + if (fileUrl == null) { + return; + } + GoRouter.of(context).push( + VideoCallRecordingPlayerScreen.path, + extra: recording, + ); + } + + @override + Widget build(BuildContext context) { + final s = S.of(context); + + return Scaffold( + backgroundColor: appTheme.whiteA700, + appBar: AppBar( + centerTitle: true, + title: Text( + s.video_call_recordings_title, + style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black), + ), + actions: [ + IconButton( + tooltip: s.video_call_recordings_retention_tooltip, + onPressed: () { + showDialog( + context: context, + builder: (context) => AlertDialog( + content: Text(s.video_call_recordings_retention_tooltip), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('OK'), + ), + ], + ), + ); + }, + icon: Icon(Icons.help_outline, color: appTheme.blueA400), + ), + ], + ), + body: BlocBuilder( + builder: (context, state) { + return Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 12), + child: RecordingPeriodDropdown( + value: state.period, + onChanged: (period) => context.read().setPeriod(period), + ), + ), + Expanded(child: _buildBody(context, state, s)), + ], + ); + }, + ), + ); + } + + Widget _buildBody(BuildContext context, VideoCallRecordingsState state, S s) { + if (state.isLoading && state.recordings.isEmpty) { + return const Loader(); + } + + if (state.error != null && state.recordings.isEmpty) { + return DataErrorWidget( + onReload: () => context.read().load(refresh: true), + ); + } + + if (state.recordings.isEmpty) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + s.video_call_recordings_empty, + textAlign: TextAlign.center, + style: TextStyles.textMMedium.copyWith(color: appTheme.blueGray400), + ), + ), + ); + } + + return RefreshIndicator( + onRefresh: () => context.read().load(refresh: true), + child: ListView.separated( + controller: _scrollController, + padding: const EdgeInsets.fromLTRB(16, 0, 16, 24), + itemCount: state.recordings.length + (state.isLoadingMore ? 1 : 0), + separatorBuilder: (_, _) => const SizedBox(height: 16), + itemBuilder: (context, index) { + if (index >= state.recordings.length) { + return const Padding( + padding: EdgeInsets.symmetric(vertical: 16), + child: Center(child: CircularProgressIndicator()), + ); + } + + final recording = state.recordings[index]; + return RecordingCard( + recording: recording, + isDownloading: _downloadingId == recording.id, + onPlay: () => _openPlayer(recording), + onDownload: () => _download(recording), + ); + }, + ), + ); + } +} diff --git a/lib/features/video_calls/recordings/presentation/widgets/recording_card.dart b/lib/features/video_calls/recordings/presentation/widgets/recording_card.dart new file mode 100644 index 00000000..0de07b24 --- /dev/null +++ b/lib/features/video_calls/recordings/presentation/widgets/recording_card.dart @@ -0,0 +1,251 @@ +import 'package:cached_network_image/cached_network_image.dart'; +import 'package:eatvio_app/core/theme/custom_text_style.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/utils/date_time_utils.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/recording_duration_formatter.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:flutter/material.dart'; + +class RecordingCard extends StatelessWidget { + const RecordingCard({ + super.key, + required this.recording, + required this.onPlay, + required this.onDownload, + this.isDownloading = false, + }); + + final VideoCallRecordingModel recording; + final VoidCallback onPlay; + final VoidCallback onDownload; + final bool isDownloading; + + @override + Widget build(BuildContext context) { + final s = S.of(context); + final isReady = recording.isReady; + + return Container( + decoration: BoxDecoration( + color: appTheme.whiteA700, + borderRadius: BorderRadius.circular(12), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.15), + blurRadius: 10, + offset: const Offset(0, 4), + ), + ], + ), + clipBehavior: Clip.antiAlias, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + AspectRatio( + aspectRatio: 1.775, + child: Stack( + fit: StackFit.expand, + children: [ + ColoredBox( + color: appTheme.dividerColor, + child: CachedNetworkImage( + imageUrl: recording.previewUrl, + fit: BoxFit.cover, + errorWidget: (_, _, _) => ColoredBox(color: appTheme.dividerColor), + ), + ), + if (isReady) ...[ + Center( + child: Material( + color: Colors.transparent, + child: InkWell( + onTap: onPlay, + customBorder: const CircleBorder(), + child: Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: appTheme.blueA400, + shape: BoxShape.circle, + ), + child: const Icon(Icons.play_arrow, color: Colors.white, size: 28), + ), + ), + ), + ), + if (recording.durationSeconds != null) + Positioned( + right: 8, + bottom: 8, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.7), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + formatRecordingDuration(recording.durationSeconds), + style: TextStyles.textSMedium.copyWith( + color: Colors.white, + fontSize: 10, + ), + ), + ), + ), + ] else + ColoredBox( + color: Colors.white.withValues(alpha: 0.72), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + SizedBox( + width: 28, + height: 28, + child: CircularProgressIndicator( + strokeWidth: 2.5, + color: appTheme.blueA400, + ), + ), + const SizedBox(height: 10), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + s.video_call_recordings_processing, + textAlign: TextAlign.center, + style: TextStyles.textSMedium.copyWith(color: appTheme.black), + ), + ), + ], + ), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(12, 12, 12, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + s.video_call_recordings_card_title, + style: TextStyles.textMMedium.copyWith( + color: appTheme.black900, + fontSize: 18, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 8), + Row( + children: [ + _CounterpartAvatar(counterpart: recording.counterpart), + const SizedBox(width: 8), + Expanded( + child: Text( + recording.counterpart?.name ?? s.video_call_counterpart_default, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyles.textSMedium.copyWith( + color: const Color(0xFF666666), + fontSize: 12, + ), + ), + ), + Container( + width: 3, + height: 3, + margin: const EdgeInsets.symmetric(horizontal: 6), + decoration: const BoxDecoration( + color: Color(0xFF666666), + shape: BoxShape.circle, + ), + ), + Text( + recording.createdAt.format('d MMMM yyyy, HH:mm', 'ru'), + style: TextStyles.textSMedium.copyWith( + color: const Color(0xFF666666), + fontSize: 12, + ), + ), + ], + ), + if (isReady) ...[ + const SizedBox(height: 12), + SizedBox( + width: double.infinity, + height: 40, + child: ElevatedButton( + onPressed: isDownloading ? null : onDownload, + style: ElevatedButton.styleFrom( + backgroundColor: appTheme.blueA400, + foregroundColor: Colors.white, + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + ), + ), + child: isDownloading + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.white, + ), + ) + : Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + s.video_call_recordings_download, + style: TextStyles.textSMedium.copyWith( + color: Colors.white, + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(width: 8), + const Icon(Icons.download, size: 20), + ], + ), + ), + ), + ], + ], + ), + ), + ], + ), + ); + } +} + +class _CounterpartAvatar extends StatelessWidget { + const _CounterpartAvatar({required this.counterpart}); + + final VideoCallRecordingCounterpartModel? counterpart; + + @override + Widget build(BuildContext context) { + final url = counterpart?.profilePhotoUrl; + return ClipOval( + child: SizedBox( + width: 24, + height: 24, + child: url != null && url.isNotEmpty + ? CachedNetworkImage( + imageUrl: url, + fit: BoxFit.cover, + errorWidget: (_, _, _) => _placeholder(), + ) + : _placeholder(), + ), + ); + } + + Widget _placeholder() { + return ColoredBox( + color: appTheme.backgroundAvatar, + child: Icon(Icons.person, size: 16, color: appTheme.blueGray400), + ); + } +} diff --git a/lib/features/video_calls/recordings/presentation/widgets/recording_period_dropdown.dart b/lib/features/video_calls/recordings/presentation/widgets/recording_period_dropdown.dart new file mode 100644 index 00000000..e18f8530 --- /dev/null +++ b/lib/features/video_calls/recordings/presentation/widgets/recording_period_dropdown.dart @@ -0,0 +1,52 @@ +import 'package:eatvio_app/core/theme/custom_text_style.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/widgets/custom_drop_down_button.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/recording_period.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:flutter/material.dart'; + +class RecordingPeriodDropdown extends StatelessWidget { + const RecordingPeriodDropdown({ + super.key, + required this.value, + required this.onChanged, + }); + + final RecordingPeriod value; + final ValueChanged onChanged; + + @override + Widget build(BuildContext context) { + final s = S.of(context); + + String label(RecordingPeriod period) => switch (period) { + RecordingPeriod.today => s.video_call_recordings_period_today, + RecordingPeriod.week => s.video_call_recordings_period_week, + RecordingPeriod.currentMonth => s.video_call_recordings_period_current_month, + RecordingPeriod.prevMonth => s.video_call_recordings_period_prev_month, + RecordingPeriod.all => s.video_call_recordings_period_all, + }; + + return CustomDropDownButton( + key: ValueKey(value), + isExpanded: true, + value: value, + onChanged: (period) { + if (period != null) { + onChanged(period); + } + }, + items: RecordingPeriod.values + .map( + (period) => DropdownMenuItem( + value: period, + child: Text( + label(period), + style: TextStyles.textMMedium.copyWith(color: appTheme.black), + ), + ), + ) + .toList(), + ); + } +} diff --git a/lib/features/video_calls/recordings/repositories/video_call_recordings_repository.dart b/lib/features/video_calls/recordings/repositories/video_call_recordings_repository.dart new file mode 100644 index 00000000..fb1abf2b --- /dev/null +++ b/lib/features/video_calls/recordings/repositories/video_call_recordings_repository.dart @@ -0,0 +1,81 @@ +import 'dart:io'; + +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/recording_not_ready_exception.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/recording_period.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:eatvio_app/features/video_calls/services/video_call_service.dart'; +import 'package:path_provider/path_provider.dart'; + +class VideoCallRecordingsRepository { + VideoCallRecordingsRepository({ + required this.videoCallService, + required this.dio, + }); + + final VideoCallService videoCallService; + final Dio dio; + + Future getRecordings({ + required int page, + RecordingPeriod? period, + }) { + return videoCallService.getRecordings( + page: page, + dateRange: period?.apiValue, + ); + } + + /// Скачивает файл записи во временную директорию. + /// + /// [fileUrl] — абсолютный URL из `file_url` ответа списка. + Future downloadRecordingFile({ + required String fileUrl, + required int recordingId, + }) async { + try { + final uri = Uri.parse(fileUrl).replace( + queryParameters: { + ...Uri.parse(fileUrl).queryParameters, + 'download': '1', + }, + ); + + final directory = await getTemporaryDirectory(); + final targetPath = '${directory.path}/recording_$recordingId.mp4'; + + await dio.download( + uri.toString(), + targetPath, + options: Options( + responseType: ResponseType.bytes, + validateStatus: (status) => status != null && status < 400, + ), + ); + + return File(targetPath); + } on DioException catch (error) { + _throwIfNotReady(error); + rethrow; + } + } + + void _throwIfNotReady(DioException error) { + if (error.response?.statusCode != 409) { + return; + } + + final data = error.response?.data; + String? message; + String? code; + + if (data is Map) { + message = data['message']?.toString(); + code = data['code']?.toString(); + } + + if (code == RecordingNotReadyException.code || code == null) { + throw RecordingNotReadyException(message: message); + } + } +} diff --git a/lib/features/video_calls/services/video_call_service.dart b/lib/features/video_calls/services/video_call_service.dart index b87fc03a..88768381 100644 --- a/lib/features/video_calls/services/video_call_service.dart +++ b/lib/features/video_calls/services/video_call_service.dart @@ -1,5 +1,6 @@ import 'package:dio/dio.dart'; import 'package:eatvio_app/features/video_calls/models/video_call_models.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; import 'package:retrofit/retrofit.dart'; part 'video_call_service.g.dart'; @@ -36,4 +37,10 @@ abstract class VideoCallService { @Path('conversation') required String conversationUuid, @Body() required Map body, }); + + @GET('/api/video-call/recordings') + Future getRecordings({ + @Query('page') required int page, + @Query(r'filters[created_at][$date_range]') String? dateRange, + }); } diff --git a/lib/generated/intl/messages_en.dart b/lib/generated/intl/messages_en.dart index 99a1c3c0..b5e0c9b1 100644 --- a/lib/generated/intl/messages_en.dart +++ b/lib/generated/intl/messages_en.dart @@ -1037,6 +1037,45 @@ class MessageLookup extends MessageLookupByLibrary { "video_call_recording_notice": MessageLookupByLibrary.simpleMessage( "The video call will be recorded.\nThe consultation may be reviewed by Eatvio staff for quality assurance.", ), + "video_call_recordings_card_title": MessageLookupByLibrary.simpleMessage( + "Video consultation with a nutrition specialist", + ), + "video_call_recordings_download": MessageLookupByLibrary.simpleMessage( + "Download", + ), + "video_call_recordings_download_error": + MessageLookupByLibrary.simpleMessage( + "Could not download the recording. Please try again later.", + ), + "video_call_recordings_empty": MessageLookupByLibrary.simpleMessage( + "No video consultations yet", + ), + "video_call_recordings_period_all": MessageLookupByLibrary.simpleMessage( + "All time", + ), + "video_call_recordings_period_current_month": + MessageLookupByLibrary.simpleMessage("Current month"), + "video_call_recordings_period_prev_month": + MessageLookupByLibrary.simpleMessage("Previous month"), + "video_call_recordings_period_today": MessageLookupByLibrary.simpleMessage( + "Today", + ), + "video_call_recordings_period_week": MessageLookupByLibrary.simpleMessage( + "7 days", + ), + "video_call_recordings_player_error": MessageLookupByLibrary.simpleMessage( + "Could not play the recording", + ), + "video_call_recordings_processing": MessageLookupByLibrary.simpleMessage( + "Recording is being processed…", + ), + "video_call_recordings_retention_tooltip": + MessageLookupByLibrary.simpleMessage( + "Video consultation recordings are stored on Eatvio servers for 1 year.", + ), + "video_call_recordings_title": MessageLookupByLibrary.simpleMessage( + "My consultations", + ), "video_call_role_consultant": MessageLookupByLibrary.simpleMessage( "Eatvio consultant", ), diff --git a/lib/generated/intl/messages_ru.dart b/lib/generated/intl/messages_ru.dart index 5f6457d6..f9675eb0 100644 --- a/lib/generated/intl/messages_ru.dart +++ b/lib/generated/intl/messages_ru.dart @@ -534,6 +534,45 @@ class MessageLookup extends MessageLookupByLibrary { "video_call_recording_notice": MessageLookupByLibrary.simpleMessage( "Видеозвонок будет записан.\nКонсультация может быть проверена сотрудниками Итвио, на предмет качества оказания услуг.", ), + "video_call_recordings_card_title": MessageLookupByLibrary.simpleMessage( + "Видеоконсультация со специалистом по питанию", + ), + "video_call_recordings_download": MessageLookupByLibrary.simpleMessage( + "Скачать", + ), + "video_call_recordings_download_error": + MessageLookupByLibrary.simpleMessage( + "Не удалось скачать запись. Попробуйте позже.", + ), + "video_call_recordings_empty": MessageLookupByLibrary.simpleMessage( + "Пока нет видеоконсультаций", + ), + "video_call_recordings_period_all": MessageLookupByLibrary.simpleMessage( + "Всё время", + ), + "video_call_recordings_period_current_month": + MessageLookupByLibrary.simpleMessage("Текущий месяц"), + "video_call_recordings_period_prev_month": + MessageLookupByLibrary.simpleMessage("Прошлый месяц"), + "video_call_recordings_period_today": MessageLookupByLibrary.simpleMessage( + "Сегодня", + ), + "video_call_recordings_period_week": MessageLookupByLibrary.simpleMessage( + "7 дней", + ), + "video_call_recordings_player_error": MessageLookupByLibrary.simpleMessage( + "Не удалось воспроизвести запись", + ), + "video_call_recordings_processing": MessageLookupByLibrary.simpleMessage( + "Запись обрабатывается…", + ), + "video_call_recordings_retention_tooltip": + MessageLookupByLibrary.simpleMessage( + "Записи видеоконсультаций хранятся на серверах Итвио в течение 1 года.", + ), + "video_call_recordings_title": MessageLookupByLibrary.simpleMessage( + "Мои консультации", + ), "video_call_role_consultant": MessageLookupByLibrary.simpleMessage( "Консультант Итвио", ), diff --git a/lib/generated/l10n.dart b/lib/generated/l10n.dart index fc12f142..e3842212 100644 --- a/lib/generated/l10n.dart +++ b/lib/generated/l10n.dart @@ -4696,6 +4696,136 @@ class S { args: [], ); } + + /// `My consultations` + String get video_call_recordings_title { + return Intl.message( + 'My consultations', + name: 'video_call_recordings_title', + desc: '', + args: [], + ); + } + + /// `Video consultation recordings are stored on Eatvio servers for 1 year.` + String get video_call_recordings_retention_tooltip { + return Intl.message( + 'Video consultation recordings are stored on Eatvio servers for 1 year.', + name: 'video_call_recordings_retention_tooltip', + desc: '', + args: [], + ); + } + + /// `No video consultations yet` + String get video_call_recordings_empty { + return Intl.message( + 'No video consultations yet', + name: 'video_call_recordings_empty', + desc: '', + args: [], + ); + } + + /// `Recording is being processed…` + String get video_call_recordings_processing { + return Intl.message( + 'Recording is being processed…', + name: 'video_call_recordings_processing', + desc: '', + args: [], + ); + } + + /// `Download` + String get video_call_recordings_download { + return Intl.message( + 'Download', + name: 'video_call_recordings_download', + desc: '', + args: [], + ); + } + + /// `Could not download the recording. Please try again later.` + String get video_call_recordings_download_error { + return Intl.message( + 'Could not download the recording. Please try again later.', + name: 'video_call_recordings_download_error', + desc: '', + args: [], + ); + } + + /// `Could not play the recording` + String get video_call_recordings_player_error { + return Intl.message( + 'Could not play the recording', + name: 'video_call_recordings_player_error', + desc: '', + args: [], + ); + } + + /// `Video consultation with a nutrition specialist` + String get video_call_recordings_card_title { + return Intl.message( + 'Video consultation with a nutrition specialist', + name: 'video_call_recordings_card_title', + desc: '', + args: [], + ); + } + + /// `Today` + String get video_call_recordings_period_today { + return Intl.message( + 'Today', + name: 'video_call_recordings_period_today', + desc: '', + args: [], + ); + } + + /// `7 days` + String get video_call_recordings_period_week { + return Intl.message( + '7 days', + name: 'video_call_recordings_period_week', + desc: '', + args: [], + ); + } + + /// `Current month` + String get video_call_recordings_period_current_month { + return Intl.message( + 'Current month', + name: 'video_call_recordings_period_current_month', + desc: '', + args: [], + ); + } + + /// `Previous month` + String get video_call_recordings_period_prev_month { + return Intl.message( + 'Previous month', + name: 'video_call_recordings_period_prev_month', + desc: '', + args: [], + ); + } + + /// `All time` + String get video_call_recordings_period_all { + return Intl.message( + 'All time', + name: 'video_call_recordings_period_all', + desc: '', + args: [], + ); + } } class AppLocalizationDelegate extends LocalizationsDelegate { diff --git a/lib/l10n/intl_en.arb b/lib/l10n/intl_en.arb index becf3334..9d15bdb7 100644 --- a/lib/l10n/intl_en.arb +++ b/lib/l10n/intl_en.arb @@ -592,6 +592,19 @@ "dayWord": {"type": "String"} } }, - "no_active_personal_diet_consultations": "No active consultations with a personal diet" + "no_active_personal_diet_consultations": "No active consultations with a personal diet", + "video_call_recordings_title": "My consultations", + "video_call_recordings_retention_tooltip": "Video consultation recordings are stored on Eatvio servers for 1 year.", + "video_call_recordings_empty": "No video consultations yet", + "video_call_recordings_processing": "Recording is being processed…", + "video_call_recordings_download": "Download", + "video_call_recordings_download_error": "Could not download the recording. Please try again later.", + "video_call_recordings_player_error": "Could not play the recording", + "video_call_recordings_card_title": "Video consultation with a nutrition specialist", + "video_call_recordings_period_today": "Today", + "video_call_recordings_period_week": "7 days", + "video_call_recordings_period_current_month": "Current month", + "video_call_recordings_period_prev_month": "Previous month", + "video_call_recordings_period_all": "All time" } diff --git a/lib/l10n/intl_ru.arb b/lib/l10n/intl_ru.arb index 298a587a..fa0c8f6b 100644 --- a/lib/l10n/intl_ru.arb +++ b/lib/l10n/intl_ru.arb @@ -347,5 +347,18 @@ "dayWord": {"type": "String"} } }, - "no_active_personal_diet_consultations": "Нет активных консультаций с персональной диетой" + "no_active_personal_diet_consultations": "Нет активных консультаций с персональной диетой", + "video_call_recordings_title": "Мои консультации", + "video_call_recordings_retention_tooltip": "Записи видеоконсультаций хранятся на серверах Итвио в течение 1 года.", + "video_call_recordings_empty": "Пока нет видеоконсультаций", + "video_call_recordings_processing": "Запись обрабатывается…", + "video_call_recordings_download": "Скачать", + "video_call_recordings_download_error": "Не удалось скачать запись. Попробуйте позже.", + "video_call_recordings_player_error": "Не удалось воспроизвести запись", + "video_call_recordings_card_title": "Видеоконсультация со специалистом по питанию", + "video_call_recordings_period_today": "Сегодня", + "video_call_recordings_period_week": "7 дней", + "video_call_recordings_period_current_month": "Текущий месяц", + "video_call_recordings_period_prev_month": "Прошлый месяц", + "video_call_recordings_period_all": "Всё время" } diff --git a/pubspec.yaml b/pubspec.yaml index b8218101..a2d657f9 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -86,6 +86,7 @@ dependencies: intl_utils: ^2.8.13 sentry_dio: ^9.10.0 livekit_client: ^2.6.1 + video_player: ^2.10.0 audio_session: ^0.1.25 flutter_foreground_task: ^9.2.1 flutter_callkit_incoming: ^3.1.1 diff --git a/test/features/menu/presentation/pages/menu_screen_smoke_test.dart b/test/features/menu/presentation/pages/menu_screen_smoke_test.dart index cfc1ddf8..9dc01bfc 100644 --- a/test/features/menu/presentation/pages/menu_screen_smoke_test.dart +++ b/test/features/menu/presentation/pages/menu_screen_smoke_test.dart @@ -107,6 +107,11 @@ void main() { name: 'myPlansScreen', builder: (context, state) => const Scaffold(body: Text('My Plans')), ), + GoRoute( + path: '/video-call-recordings-screen', + name: 'videoCallRecordingsScreen', + builder: (context, state) => const Scaffold(body: Text('My Consultations')), + ), GoRoute( path: '/consultant-finances-screen', name: 'consultantFinancesScreen', @@ -152,6 +157,7 @@ void main() { expect(find.text('Меню'), findsOneWidget); expect(find.text('Настройки профиля'), findsOneWidget); + expect(find.text('Мои консультации'), findsOneWidget); }); testWidgets('renders menu screen for consultant', (tester) async { @@ -171,6 +177,7 @@ void main() { expect(find.text('Мои рецепты'), findsOneWidget); expect(find.text('Мои диеты'), findsOneWidget); expect(find.text('Мои планы'), findsOneWidget); + expect(find.text('Мои консультации'), findsOneWidget); }); }); } diff --git a/test/features/video_calls/recordings/models/video_call_recording_model_test.dart b/test/features/video_calls/recordings/models/video_call_recording_model_test.dart new file mode 100644 index 00000000..03f7892d --- /dev/null +++ b/test/features/video_calls/recordings/models/video_call_recording_model_test.dart @@ -0,0 +1,47 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:eatvio_app/features/video_calls/recordings/models/recording_duration_formatter.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('VideoCallRecordingsPagination', () { + test('parses fixture with ready and in_progress items', () { + final json = jsonDecode( + File('test/fixtures/video_call_recordings/recordings_page.json').readAsStringSync(), + ) as Map; + + final page = VideoCallRecordingsPagination.fromJson(json); + + expect(page.data, hasLength(2)); + expect(page.meta.currentPage, 1); + expect(page.meta.lastPage, 1); + expect(page.meta.perPage, 20); + + final ready = page.data.first; + expect(ready.id, 123); + expect(ready.isReady, isTrue); + expect(ready.durationSeconds, 187); + expect(ready.fileUrl, isNotNull); + expect(ready.counterpart?.name, 'Иван Петров'); + expect(ready.counterpart?.slug, 'ivan-petrov'); + + final processing = page.data.last; + expect(processing.isInProgress, isTrue); + expect(processing.durationSeconds, isNull); + expect(processing.fileUrl, isNull); + expect(processing.counterpart, isNull); + expect(processing.previewUrl, contains('placeholder')); + }); + }); + + group('formatRecordingDuration', () { + test('formats seconds and hours', () { + expect(formatRecordingDuration(null), ''); + expect(formatRecordingDuration(5), '00:05'); + expect(formatRecordingDuration(187), '03:07'); + expect(formatRecordingDuration(3661), '1:01:01'); + }); + }); +} diff --git a/test/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit_test.dart b/test/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit_test.dart new file mode 100644 index 00000000..aa570806 --- /dev/null +++ b/test/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit_test.dart @@ -0,0 +1,112 @@ +import 'package:eatvio_app/core/models/pagination_model.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/recording_period.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit.dart'; +import 'package:eatvio_app/features/video_calls/recordings/repositories/video_call_recordings_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockRecordingsRepository extends Mock implements VideoCallRecordingsRepository {} + +void main() { + late _MockRecordingsRepository repository; + late VideoCallRecordingsCubit cubit; + + VideoCallRecordingsPagination page({ + required int currentPage, + required int lastPage, + required List data, + }) { + return VideoCallRecordingsPagination( + data: data, + links: const Links( + first: 'https://example.com?page=1', + last: 'https://example.com?page=2', + prev: null, + next: null, + ), + meta: Meta( + currentPage: currentPage, + from: 1, + lastPage: lastPage, + links: const [], + perPage: 20, + to: data.length, + total: data.length, + ), + ); + } + + VideoCallRecordingModel recording(int id) { + return VideoCallRecordingModel( + id: id, + status: 'ready', + createdAt: DateTime.utc(2026, 9, 21, 10), + previewUrl: 'https://example.com/preview.jpg', + fileUrl: 'https://example.com/api/video-call/recordings/$id/file', + ); + } + + setUp(() { + repository = _MockRecordingsRepository(); + cubit = VideoCallRecordingsCubit(repository: repository); + }); + + tearDown(() async { + await cubit.close(); + }); + + test('load fills recordings', () async { + when( + () => repository.getRecordings(page: 1, period: null), + ).thenAnswer( + (_) async => page(currentPage: 1, lastPage: 1, data: [recording(1)]), + ); + + await cubit.load(); + + expect(cubit.state.isLoading, isFalse); + expect(cubit.state.recordings, hasLength(1)); + expect(cubit.state.error, isNull); + }); + + test('setPeriod resets to page 1 and reloads', () async { + when( + () => repository.getRecordings(page: 1, period: null), + ).thenAnswer( + (_) async => page(currentPage: 1, lastPage: 2, data: [recording(1)]), + ); + when( + () => repository.getRecordings(page: 1, period: RecordingPeriod.week), + ).thenAnswer( + (_) async => page(currentPage: 1, lastPage: 1, data: [recording(2)]), + ); + + await cubit.load(); + await cubit.setPeriod(RecordingPeriod.week); + + expect(cubit.state.period, RecordingPeriod.week); + expect(cubit.state.currentPage, 1); + expect(cubit.state.recordings.single.id, 2); + verify(() => repository.getRecordings(page: 1, period: RecordingPeriod.week)).called(1); + }); + + test('loadNextPage appends recordings', () async { + when( + () => repository.getRecordings(page: 1, period: null), + ).thenAnswer( + (_) async => page(currentPage: 1, lastPage: 2, data: [recording(1)]), + ); + when( + () => repository.getRecordings(page: 2, period: null), + ).thenAnswer( + (_) async => page(currentPage: 2, lastPage: 2, data: [recording(2)]), + ); + + await cubit.load(); + await cubit.loadNextPage(); + + expect(cubit.state.recordings.map((e) => e.id), [1, 2]); + expect(cubit.state.currentPage, 2); + }); +} diff --git a/test/features/video_calls/recordings/presentation/widgets/recording_card_test.dart b/test/features/video_calls/recordings/presentation/widgets/recording_card_test.dart new file mode 100644 index 00000000..8e94581d --- /dev/null +++ b/test/features/video_calls/recordings/presentation/widgets/recording_card_test.dart @@ -0,0 +1,91 @@ +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart'; +import 'package:eatvio_app/features/video_calls/recordings/presentation/widgets/recording_card.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:network_image_mock/network_image_mock.dart'; + +void main() { + Widget wrap(Widget child) { + return MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [ + S.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: const [Locale('ru')], + home: Scaffold(body: child), + ); + } + + testWidgets('ready card shows download and play', (tester) async { + await mockNetworkImagesFor(() async { + final recording = VideoCallRecordingModel( + id: 1, + status: 'ready', + durationSeconds: 125, + createdAt: DateTime.utc(2026, 5, 12, 14), + previewUrl: 'https://example.com/preview.jpg', + fileUrl: 'https://example.com/file', + counterpart: const VideoCallRecordingCounterpartModel( + name: 'Сидни', + slug: 'sydney', + profilePhotoUrl: 'https://example.com/a.jpg', + ), + ); + + var played = false; + var downloaded = false; + + await tester.pumpWidget( + wrap( + RecordingCard( + recording: recording, + onPlay: () => played = true, + onDownload: () => downloaded = true, + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('Скачать'), findsOneWidget); + expect(find.text('02:05'), findsOneWidget); + expect(find.textContaining('обрабатывается'), findsNothing); + + await tester.tap(find.byIcon(Icons.play_arrow)); + await tester.tap(find.text('Скачать')); + expect(played, isTrue); + expect(downloaded, isTrue); + }); + }); + + testWidgets('in_progress card hides download and play', (tester) async { + await mockNetworkImagesFor(() async { + final recording = VideoCallRecordingModel( + id: 2, + status: 'in_progress', + createdAt: DateTime.utc(2026, 5, 12, 14), + previewUrl: 'https://example.com/placeholder.png', + ); + + await tester.pumpWidget( + wrap( + RecordingCard( + recording: recording, + onPlay: () {}, + onDownload: () {}, + ), + ), + ); + await tester.pump(); + + expect(find.textContaining('обрабатывается'), findsOneWidget); + expect(find.text('Скачать'), findsNothing); + expect(find.byIcon(Icons.play_arrow), findsNothing); + }); + }); +} diff --git a/test/features/video_calls/recordings/repositories/video_call_recordings_repository_test.dart b/test/features/video_calls/recordings/repositories/video_call_recordings_repository_test.dart new file mode 100644 index 00000000..1c2bbdfa --- /dev/null +++ b/test/features/video_calls/recordings/repositories/video_call_recordings_repository_test.dart @@ -0,0 +1,74 @@ +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/video_calls/recordings/models/recording_not_ready_exception.dart'; +import 'package:eatvio_app/features/video_calls/recordings/repositories/video_call_recordings_repository.dart'; +import 'package:eatvio_app/features/video_calls/services/video_call_service.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; + +class _MockVideoCallService extends Mock implements VideoCallService {} + +class _MockDio extends Mock implements Dio {} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUpAll(() { + registerFallbackValue(''); + registerFallbackValue(Options()); + + const MethodChannel pathProviderChannel = + MethodChannel('plugins.flutter.io/path_provider'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(pathProviderChannel, (call) async { + if (call.method == 'getTemporaryDirectory') { + return '/tmp'; + } + return null; + }); + }); + + late _MockVideoCallService service; + late _MockDio dio; + late VideoCallRecordingsRepository repository; + + setUp(() { + service = _MockVideoCallService(); + dio = _MockDio(); + repository = VideoCallRecordingsRepository( + videoCallService: service, + dio: dio, + ); + }); + + test('downloadRecordingFile maps 409 to RecordingNotReadyException', () async { + when( + () => dio.download( + any(), + any(), + options: any(named: 'options'), + ), + ).thenThrow( + DioException( + requestOptions: RequestOptions(path: '/file'), + response: Response( + requestOptions: RequestOptions(path: '/file'), + statusCode: 409, + data: { + 'message': 'Not ready', + 'code': RecordingNotReadyException.code, + }, + ), + type: DioExceptionType.badResponse, + ), + ); + + await expectLater( + repository.downloadRecordingFile( + fileUrl: 'https://example.com/api/video-call/recordings/1/file', + recordingId: 1, + ), + throwsA(isA()), + ); + }); +} diff --git a/test/fixtures/video_call_recordings/recordings_page.json b/test/fixtures/video_call_recordings/recordings_page.json new file mode 100644 index 00000000..b2ed19e2 --- /dev/null +++ b/test/fixtures/video_call_recordings/recordings_page.json @@ -0,0 +1,44 @@ +{ + "data": [ + { + "id": 123, + "status": "ready", + "duration_seconds": 187, + "size_bytes": 15728640, + "created_at": "2026-09-21T10:00:00.000000Z", + "preview_url": "https://example.com/storage/recordings/123/preview.jpg", + "file_url": "https://example.com/api/video-call/recordings/123/file", + "counterpart": { + "name": "Иван Петров", + "slug": "ivan-petrov", + "profile_photo_url": "https://example.com/storage/users/ivan.jpg" + } + }, + { + "id": 122, + "status": "in_progress", + "duration_seconds": null, + "size_bytes": null, + "created_at": "2026-09-21T09:00:00.000000Z", + "preview_url": "https://example.com/images/element-image-placeholder.png", + "file_url": null, + "counterpart": null + } + ], + "links": { + "first": "https://example.com/api/video-call/recordings?page=1", + "last": "https://example.com/api/video-call/recordings?page=1", + "prev": null, + "next": null + }, + "meta": { + "current_page": 1, + "from": 1, + "last_page": 1, + "links": [], + "path": "https://example.com/api/video-call/recordings", + "per_page": 20, + "to": 2, + "total": 2 + } +}