fluffychat/lib/pages/story/story_page.dart

518 lines
15 KiB
Dart
Raw Normal View History

2021-12-24 14:18:09 +01:00
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
2021-12-26 13:17:30 +01:00
import 'package:adaptive_dialog/adaptive_dialog.dart';
2021-12-26 11:30:44 +01:00
import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
2021-12-26 09:59:34 +01:00
import 'package:flutter_gen/gen_l10n/l10n.dart';
2021-12-26 12:46:18 +01:00
import 'package:future_loading_dialog/future_loading_dialog.dart';
2021-12-24 14:18:09 +01:00
import 'package:matrix/matrix.dart';
import 'package:path_provider/path_provider.dart';
import 'package:video_player/video_player.dart';
import 'package:vrouter/vrouter.dart';
import 'package:fluffychat/pages/story/story_view.dart';
2021-12-27 17:13:54 +01:00
import 'package:fluffychat/utils/date_time_extension.dart';
2021-12-26 11:38:16 +01:00
import 'package:fluffychat/utils/localized_exception_extension.dart';
2021-12-24 14:18:09 +01:00
import 'package:fluffychat/utils/matrix_sdk_extensions.dart/client_stories_extension.dart';
2022-01-24 15:35:59 +01:00
import 'package:fluffychat/utils/matrix_sdk_extensions.dart/ios_badge_client_extension.dart';
2021-12-24 14:18:09 +01:00
import 'package:fluffychat/utils/platform_infos.dart';
2021-12-26 09:59:34 +01:00
import 'package:fluffychat/utils/room_status_extension.dart';
2022-03-06 11:39:31 +01:00
import 'package:fluffychat/utils/story_theme_data.dart';
2021-12-26 09:59:34 +01:00
import 'package:fluffychat/widgets/avatar.dart';
2021-12-24 14:18:09 +01:00
import 'package:fluffychat/widgets/matrix.dart';
class StoryPage extends StatefulWidget {
const StoryPage({Key? key}) : super(key: key);
@override
StoryPageController createState() => StoryPageController();
}
class StoryPageController extends State<StoryPage> {
int index = 0;
int max = 0;
Duration progress = Duration.zero;
Timer? _progressTimer;
bool loadingMode = false;
2021-12-26 11:30:44 +01:00
final TextEditingController replyController = TextEditingController();
final FocusNode replyFocus = FocusNode();
2021-12-25 14:07:48 +01:00
final List<Event> events = [];
2021-12-26 09:59:34 +01:00
Timeline? timeline;
2021-12-25 14:07:48 +01:00
Event? get currentEvent => index < events.length ? events[index] : null;
2022-02-20 10:24:23 +01:00
StoryThemeData get storyThemeData =>
StoryThemeData.fromJson(currentEvent?.content
.tryGetMap<String, dynamic>(StoryThemeData.contentKey) ??
{});
2021-12-25 14:07:48 +01:00
2021-12-26 11:30:44 +01:00
bool replyLoading = false;
2021-12-26 11:40:18 +01:00
bool _modalOpened = false;
2021-12-26 11:30:44 +01:00
2021-12-27 13:07:15 +01:00
VideoPlayerController? _videoPlayerController;
2021-12-26 11:30:44 +01:00
void replyEmojiAction() async {
if (replyLoading) return;
2021-12-26 11:40:18 +01:00
_modalOpened = true;
2021-12-26 11:30:44 +01:00
await showModalBottomSheet(
context: context,
builder: (context) => EmojiPicker(
onEmojiSelected: (c, e) {
Navigator.of(context).pop();
replyAction(e.emoji);
},
),
);
2021-12-26 11:40:18 +01:00
_modalOpened = false;
2021-12-26 11:30:44 +01:00
}
void replyAction([String? message]) async {
message ??= replyController.text;
if (message.isEmpty) return;
2021-12-27 17:13:54 +01:00
final currentEvent = this.currentEvent;
if (currentEvent == null) return;
2021-12-26 11:30:44 +01:00
setState(() {
replyLoading = true;
});
try {
final client = Matrix.of(context).client;
2021-12-27 17:13:54 +01:00
final roomId = await client.startDirectChat(currentEvent.senderId);
var replyText = L10n.of(context)!.storyFrom(
currentEvent.originServerTs.localizedTime(context),
currentEvent.content.tryGet<String>('body') ?? '');
replyText = replyText.split('\n').map((line) => '> $line').join('\n');
message = '$replyText\n\n$message';
await client.getRoomById(roomId)!.sendTextEvent(message);
2021-12-26 11:30:44 +01:00
replyController.clear();
replyFocus.unfocus();
ScaffoldMessenger.of(context).showSnackBar(
2021-12-26 11:37:24 +01:00
SnackBar(content: Text(L10n.of(context)!.replyHasBeenSent)),
2021-12-26 11:30:44 +01:00
);
} catch (e, s) {
Logs().w('Unable to reply to story', e, s);
2021-12-26 11:37:24 +01:00
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(e.toLocalizedString(context))),
);
2021-12-26 11:30:44 +01:00
} finally {
setState(() {
replyLoading = false;
});
}
}
2021-12-26 09:59:34 +01:00
List<User> get currentSeenByUsers {
final timeline = this.timeline;
final currentEvent = this.currentEvent;
if (timeline == null || currentEvent == null) return [];
return Matrix.of(context).client.getRoomById(roomId)?.getSeenByUsers(
timeline,
events,
{},
eventId: currentEvent.eventId,
) ??
[];
}
2021-12-28 19:30:19 +01:00
void share() async {
Matrix.of(context).shareContent = currentEvent?.content;
hold();
VRouter.of(context).to('share');
}
2021-12-26 11:40:18 +01:00
void displaySeenByUsers() async {
_modalOpened = true;
await showModalBottomSheet(
context: context,
builder: (context) => Scaffold(
appBar: AppBar(
title: Text(seenByUsersTitle),
),
body: ListView.builder(
itemCount: currentSeenByUsers.length,
itemBuilder: (context, i) => ListTile(
leading: Avatar(
mxContent: currentSeenByUsers[i].avatarUrl,
name: currentSeenByUsers[i].calcDisplayname(),
2021-12-26 09:59:34 +01:00
),
2021-12-26 11:40:18 +01:00
title: Text(currentSeenByUsers[i].calcDisplayname()),
2021-12-26 09:59:34 +01:00
),
),
2021-12-26 11:40:18 +01:00
),
);
_modalOpened = false;
}
2021-12-26 09:59:34 +01:00
String get seenByUsersTitle {
final seenByUsers = currentSeenByUsers;
if (seenByUsers.isEmpty) return '';
if (seenByUsers.length == 1) {
return L10n.of(context)!.seenByUser(seenByUsers.single.calcDisplayname());
}
if (seenByUsers.length == 2) {
return L10n.of(context)!.seenByUserAndUser(
seenByUsers.first.calcDisplayname(),
seenByUsers.last.calcDisplayname(),
);
}
return L10n.of(context)!.seenByUserAndCountOthers(
2021-12-26 11:49:15 +01:00
seenByUsers.first.calcDisplayname(),
2021-12-26 09:59:34 +01:00
seenByUsers.length - 1,
);
}
2021-12-24 14:18:09 +01:00
static const Duration _step = Duration(milliseconds: 50);
static const Duration maxProgress = Duration(seconds: 5);
void _restartTimer([bool reset = true]) {
_progressTimer?.cancel();
if (reset) progress = Duration.zero;
_progressTimer = Timer.periodic(_step, (_) {
2021-12-26 11:40:18 +01:00
if (replyFocus.hasFocus || _modalOpened) return;
2021-12-24 14:18:09 +01:00
if (!mounted) {
_progressTimer?.cancel();
return;
}
if (loadingMode) return;
setState(() {
2021-12-27 13:07:15 +01:00
final video = _videoPlayerController;
if (video == null) {
progress += _step;
} else {
progress = video.value.position;
}
2021-12-24 14:18:09 +01:00
});
2021-12-27 13:07:15 +01:00
final max = _videoPlayerController?.value.duration ?? maxProgress;
2021-12-28 20:04:26 +01:00
if (progress >= max) {
2021-12-24 14:18:09 +01:00
skip();
}
});
}
2021-12-26 09:59:34 +01:00
bool get isOwnStory {
final client = Matrix.of(context).client;
final room = client.getRoomById(roomId);
if (room == null) return false;
return room.ownPowerLevel >= 100;
}
2021-12-24 14:18:09 +01:00
String get roomId => VRouter.of(context).pathParameters['roomid'] ?? '';
2021-12-28 23:08:27 +01:00
Future<VideoPlayerController?>? loadVideoControllerFuture;
2021-12-28 20:04:26 +01:00
2021-12-28 23:08:27 +01:00
Future<VideoPlayerController?> loadVideoController(Event event) async {
2021-12-28 20:04:26 +01:00
try {
final matrixFile = await event.downloadAndDecryptAttachment();
2021-12-28 23:08:27 +01:00
if (!mounted) return null;
2021-12-28 20:04:26 +01:00
final tmpDirectory = await getTemporaryDirectory();
final fileName =
event.content.tryGet<String>('filename') ?? 'unknown_story_video.mp4';
final file = File(tmpDirectory.path + '/' + fileName);
await file.writeAsBytes(matrixFile.bytes);
2021-12-28 23:08:27 +01:00
if (!mounted) return null;
2021-12-28 20:04:26 +01:00
final videoPlayerController =
_videoPlayerController = VideoPlayerController.file(file);
await videoPlayerController.initialize();
await videoPlayerController.play();
return videoPlayerController;
} catch (e, s) {
Logs().w('Unable to load video story. Try again...', e, s);
await Future.delayed(const Duration(seconds: 3));
return loadVideoController(event);
}
2021-12-24 14:18:09 +01:00
}
void skip() {
if (index + 1 >= max) {
if (isOwnStory) {
VRouter.of(context).to('/stories/create');
} else {
VRouter.of(context).to('/rooms');
}
2021-12-24 14:18:09 +01:00
return;
}
setState(() {
2021-12-28 20:04:26 +01:00
_videoPlayerController?.dispose();
_videoPlayerController = null;
loadVideoControllerFuture = null;
2021-12-24 14:18:09 +01:00
index++;
});
_restartTimer();
maybeSetReadMarker();
2021-12-24 14:18:09 +01:00
}
DateTime _holdedAt = DateTime.fromMicrosecondsSinceEpoch(0);
2021-12-26 11:30:44 +01:00
bool isHold = false;
2021-12-28 20:04:26 +01:00
@override
void dispose() {
_videoPlayerController?.dispose();
super.dispose();
}
2021-12-26 11:30:44 +01:00
void hold([_]) {
2021-12-24 14:18:09 +01:00
_holdedAt = DateTime.now();
if (loadingMode) return;
_progressTimer?.cancel();
2021-12-26 11:30:44 +01:00
setState(() {
isHold = true;
});
2021-12-24 14:18:09 +01:00
}
void unhold([_]) {
2021-12-26 11:30:44 +01:00
isHold = false;
2021-12-24 14:18:09 +01:00
if (DateTime.now().millisecondsSinceEpoch -
_holdedAt.millisecondsSinceEpoch <
200) {
skip();
return;
}
_restartTimer(false);
}
void loadingModeOn() => _setLoadingMode(true);
void loadingModeOff() => _setLoadingMode(false);
final Map<String, Future<MatrixFile>> _fileCache = {};
2021-12-28 19:30:19 +01:00
void _delete() async {
final event = currentEvent;
if (event == null) return;
_modalOpened = true;
if (await showOkCancelAlertDialog(
context: context,
title: L10n.of(context)!.deleteMessage,
message: L10n.of(context)!.areYouSure,
okLabel: L10n.of(context)!.yes,
cancelLabel: L10n.of(context)!.cancel,
) !=
OkCancelResult.ok) {
return;
}
await showFutureLoadingDialog(
context: context,
future: event.redactEvent,
);
setState(() {
2022-03-13 10:58:39 +01:00
events.remove(event);
2021-12-28 19:30:19 +01:00
_modalOpened = false;
});
}
void _report() async {
2021-12-26 12:46:18 +01:00
_modalOpened = true;
final event = currentEvent;
if (event == null) return;
final score = await showConfirmationDialog<int>(
context: context,
title: L10n.of(context)!.reportMessage,
message: L10n.of(context)!.howOffensiveIsThisContent,
cancelLabel: L10n.of(context)!.cancel,
okLabel: L10n.of(context)!.ok,
actions: [
AlertDialogAction(
key: -100,
label: L10n.of(context)!.extremeOffensive,
),
AlertDialogAction(
key: -50,
label: L10n.of(context)!.offensive,
),
AlertDialogAction(
key: 0,
label: L10n.of(context)!.inoffensive,
),
]);
if (score == null) return;
final reason = await showTextInputDialog(
useRootNavigator: false,
context: context,
title: L10n.of(context)!.whyDoYouWantToReportThis,
okLabel: L10n.of(context)!.ok,
cancelLabel: L10n.of(context)!.cancel,
textFields: [DialogTextField(hintText: L10n.of(context)!.reason)]);
if (reason == null || reason.single.isEmpty) return;
final result = await showFutureLoadingDialog(
context: context,
future: () => Matrix.of(context).client.reportContent(
roomId,
event.eventId,
reason: reason.single,
score: score,
),
);
_modalOpened = false;
if (result.error != null) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(L10n.of(context)!.contentHasBeenReported)),
);
}
2021-12-24 14:18:09 +01:00
Future<MatrixFile> downloadAndDecryptAttachment(
Event event, bool getThumbnail) async {
return _fileCache[event.eventId] ??=
event.downloadAndDecryptAttachment(getThumbnail: getThumbnail);
}
void _setLoadingMode(bool mode) => loadingMode != mode
? WidgetsBinding.instance?.addPostFrameCallback((_) {
setState(() {
loadingMode = mode;
});
})
: null;
2021-12-25 08:56:35 +01:00
Uri? get avatar => Matrix.of(context)
.client
.getRoomById(roomId)
?.getState(EventTypes.RoomCreate)
?.sender
.avatarUrl;
2021-12-24 14:18:09 +01:00
String get title =>
Matrix.of(context)
.client
.getRoomById(roomId)
?.getState(EventTypes.RoomCreate)
?.sender
.calcDisplayname() ??
'Story not found';
2021-12-25 14:07:48 +01:00
Future<void>? loadStory;
2021-12-24 14:18:09 +01:00
2021-12-25 14:07:48 +01:00
Future<void> _loadStory() async {
try {
final client = Matrix.of(context).client;
await client.roomsLoading;
await client.accountDataLoading;
final room = client.getRoomById(roomId);
if (room == null) return;
if (room.membership != Membership.join) {
final joinedFuture = room.client.onSync.stream
.where((u) => u.rooms?.join?.containsKey(room.id) ?? false)
.first;
await room.join();
await joinedFuture;
}
final timeline = this.timeline = await room.getTimeline();
timeline.requestKeys();
2022-03-13 10:58:39 +01:00
var events = timeline.events
.where((e) => e.type == EventTypes.Message && !e.redacted)
.toList();
final hasOutdatedEvents = events.removeOutdatedEvents();
// Request history if possible
if (!hasOutdatedEvents &&
timeline.events.first.type != EventTypes.RoomCreate &&
events.length < 30) {
try {
await timeline
.requestHistory(historyCount: 100)
.timeout(const Duration(seconds: 5));
events = timeline.events
.where((e) => e.type == EventTypes.Message)
.toList();
events.removeOutdatedEvents();
} catch (e, s) {
Logs().d('Unable to request history in stories', e, s);
}
2021-12-24 14:18:09 +01:00
}
max = events.length;
if (events.isNotEmpty) {
_restartTimer();
}
2021-12-25 08:56:35 +01:00
// Preload images and videos
events
.where((event) => {MessageTypes.Image, MessageTypes.Video}
.contains(event.messageType))
.forEach((event) => downloadAndDecryptAttachment(
event,
event.messageType == MessageTypes.Video &&
PlatformInfos.isMobile));
// Reverse list
this.events.clear();
this.events.addAll(events.reversed.toList());
// Set start position
if (this.events.isNotEmpty) {
final receiptId = room.roomAccountData['m.receipt']?.content
.tryGetMap<String, dynamic>(room.client.userID!)
?.tryGet<String>('event_id');
index = this.events.indexWhere((event) => event.eventId == receiptId);
index++;
if (index >= this.events.length) index = 0;
2021-12-25 14:07:48 +01:00
}
maybeSetReadMarker();
} catch (e, s) {
Logs().e('Unable to load story', e, s);
2021-12-25 14:07:48 +01:00
}
return;
2021-12-24 14:18:09 +01:00
}
void maybeSetReadMarker() {
final currentEvent = this.currentEvent;
if (currentEvent == null) return;
final room = currentEvent.room;
room.client.updateIosBadge();
if (index == events.length - 1) {
timeline!.setReadMarker();
return;
}
if (!currentSeenByUsers.any((u) => u.id == u.room.client.userID)) {
timeline!.setReadMarker(currentEvent.eventId);
}
}
2021-12-28 19:30:19 +01:00
void onPopupStoryAction(PopupStoryAction action) async {
switch (action) {
case PopupStoryAction.report:
_report();
break;
case PopupStoryAction.delete:
_delete();
break;
2022-02-20 10:24:23 +01:00
case PopupStoryAction.message:
final roomIdResult = await showFutureLoadingDialog(
context: context,
future: () => currentEvent!.sender.startDirectChat(),
);
if (roomIdResult.error != null) return;
VRouter.of(context).toSegments(['rooms', roomIdResult.result!]);
break;
2021-12-28 19:30:19 +01:00
}
}
2021-12-24 14:18:09 +01:00
@override
Widget build(BuildContext context) {
loadStory ??= _loadStory();
return StoryView(this);
}
}
extension on List<Event> {
bool removeOutdatedEvents() {
final outdatedIndex = indexWhere((event) =>
DateTime.now().difference(event.originServerTs).inHours >
ClientStoriesExtension.lifeTimeInHours);
if (outdatedIndex != -1) {
removeRange(outdatedIndex, length);
return true;
}
return false;
}
}
2021-12-26 12:46:18 +01:00
enum PopupStoryAction {
report,
2021-12-28 19:30:19 +01:00
delete,
2022-02-20 10:24:23 +01:00
message,
2021-12-26 12:46:18 +01:00
}