feat: Stories
This commit is contained in:
parent
a695a4a001
commit
231a2e26f9
13 changed files with 1065 additions and 4 deletions
178
lib/pages/story/story_page.dart
Normal file
178
lib/pages/story/story_page.dart
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
//@dart=2.12
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
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';
|
||||
import 'package:fluffychat/utils/matrix_sdk_extensions.dart/client_stories_extension.dart';
|
||||
import 'package:fluffychat/utils/platform_infos.dart';
|
||||
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;
|
||||
|
||||
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, (_) {
|
||||
if (!mounted) {
|
||||
_progressTimer?.cancel();
|
||||
return;
|
||||
}
|
||||
if (loadingMode) return;
|
||||
setState(() {
|
||||
progress = progress += _step;
|
||||
});
|
||||
if (progress > maxProgress) {
|
||||
skip();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
String get roomId => VRouter.of(context).pathParameters['roomid'] ?? '';
|
||||
|
||||
Future<VideoPlayerController> loadVideoController(Event event) async {
|
||||
final matrixFile = await event.downloadAndDecryptAttachment();
|
||||
final tmpDirectory = await getTemporaryDirectory();
|
||||
final file = File(tmpDirectory.path + matrixFile.name);
|
||||
final videoPlayerController = VideoPlayerController.file(file)
|
||||
..setLooping(true);
|
||||
await videoPlayerController.initialize();
|
||||
videoPlayerController.play();
|
||||
return videoPlayerController;
|
||||
}
|
||||
|
||||
void skip() {
|
||||
if (index + 1 >= max) {
|
||||
VRouter.of(context).pop();
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
index++;
|
||||
});
|
||||
_restartTimer();
|
||||
}
|
||||
|
||||
DateTime _holdedAt = DateTime.fromMicrosecondsSinceEpoch(0);
|
||||
|
||||
void hold(_) {
|
||||
_holdedAt = DateTime.now();
|
||||
if (loadingMode) return;
|
||||
_progressTimer?.cancel();
|
||||
}
|
||||
|
||||
void unhold([_]) {
|
||||
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 = {};
|
||||
|
||||
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;
|
||||
|
||||
String get title =>
|
||||
Matrix.of(context)
|
||||
.client
|
||||
.getRoomById(roomId)
|
||||
?.getState(EventTypes.RoomCreate)
|
||||
?.sender
|
||||
.calcDisplayname() ??
|
||||
'Story not found';
|
||||
|
||||
Future<List<Event>>? loadStory;
|
||||
|
||||
Future<List<Event>> _loadStory() async {
|
||||
final room = Matrix.of(context).client.getRoomById(roomId);
|
||||
if (room == null) return [];
|
||||
final timeline = await room.getTimeline();
|
||||
var events =
|
||||
timeline.events.where((e) => e.type == EventTypes.Message).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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
max = events.length;
|
||||
if (events.isNotEmpty) {
|
||||
_restartTimer();
|
||||
}
|
||||
events
|
||||
.where((event) => {MessageTypes.Image, MessageTypes.Video}
|
||||
.contains(event.messageType))
|
||||
.forEach((event) => downloadAndDecryptAttachment(event,
|
||||
event.messageType == MessageTypes.Video && PlatformInfos.isMobile));
|
||||
return events;
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
}
|
||||
187
lib/pages/story/story_view.dart
Normal file
187
lib/pages/story/story_view.dart
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
//@dart=2.12
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:flutter_blurhash/flutter_blurhash.dart';
|
||||
import 'package:flutter_gen/gen_l10n/l10n.dart';
|
||||
import 'package:matrix/matrix.dart';
|
||||
import 'package:video_player/video_player.dart';
|
||||
|
||||
import 'package:fluffychat/pages/story/story_page.dart';
|
||||
import 'package:fluffychat/utils/localized_exception_extension.dart';
|
||||
import 'package:fluffychat/utils/platform_infos.dart';
|
||||
import 'package:fluffychat/utils/string_color.dart';
|
||||
|
||||
class StoryView extends StatelessWidget {
|
||||
final StoryPageController controller;
|
||||
const StoryView(this.controller, {Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(controller.title),
|
||||
backgroundColor:
|
||||
Theme.of(context).appBarTheme.backgroundColor?.withOpacity(0.5),
|
||||
),
|
||||
extendBodyBehindAppBar: true,
|
||||
body: FutureBuilder<List<Event>>(
|
||||
future: controller.loadStory,
|
||||
builder: (context, snapshot) {
|
||||
final error = snapshot.error;
|
||||
if (error != null) {
|
||||
return Center(child: Text(error.toLocalizedString(context)));
|
||||
}
|
||||
final events = snapshot.data;
|
||||
if (events == null) {
|
||||
return const Center(
|
||||
child: CircularProgressIndicator.adaptive(
|
||||
strokeWidth: 2,
|
||||
));
|
||||
}
|
||||
if (events.isEmpty) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Center(
|
||||
child: Text(
|
||||
L10n.of(context)!.thisUserHasNotPostedAnythingYet,
|
||||
textAlign: TextAlign.center,
|
||||
)),
|
||||
);
|
||||
}
|
||||
final event = events[controller.index];
|
||||
final backgroundColor = event.content.tryGet<String>('body')?.color ??
|
||||
Theme.of(context).primaryColor;
|
||||
final backgroundColorDark =
|
||||
event.content.tryGet<String>('body')?.darkColor ??
|
||||
Theme.of(context).primaryColorDark;
|
||||
if (event.messageType == MessageTypes.Text) {
|
||||
controller.loadingModeOff();
|
||||
}
|
||||
return GestureDetector(
|
||||
onTapDown: controller.hold,
|
||||
onTapUp: controller.unhold,
|
||||
child: Stack(
|
||||
children: [
|
||||
if (event.messageType == MessageTypes.Video &&
|
||||
PlatformInfos.isMobile)
|
||||
FutureBuilder<VideoPlayerController>(
|
||||
future: controller.loadVideoController(event),
|
||||
builder: (context, snapshot) {
|
||||
final videoPlayerController = snapshot.data;
|
||||
if (videoPlayerController == null) {
|
||||
controller.loadingModeOn();
|
||||
return Container();
|
||||
}
|
||||
controller.loadingModeOff();
|
||||
return Center(child: VideoPlayer(videoPlayerController));
|
||||
},
|
||||
),
|
||||
if (event.messageType == MessageTypes.Image ||
|
||||
(event.messageType == MessageTypes.Video &&
|
||||
!PlatformInfos.isMobile))
|
||||
Positioned(
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: FutureBuilder<MatrixFile>(
|
||||
future: controller.downloadAndDecryptAttachment(
|
||||
event, event.messageType == MessageTypes.Video),
|
||||
builder: (context, snapshot) {
|
||||
final matrixFile = snapshot.data;
|
||||
if (matrixFile == null) {
|
||||
controller.loadingModeOn();
|
||||
final hash = event.infoMap['xyz.amorgan.blurhash'];
|
||||
return hash is String
|
||||
? BlurHash(
|
||||
hash: hash,
|
||||
imageFit: BoxFit.cover,
|
||||
)
|
||||
: Container();
|
||||
}
|
||||
controller.loadingModeOff();
|
||||
return Image.memory(
|
||||
matrixFile.bytes,
|
||||
fit: BoxFit.cover,
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 200),
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
decoration: BoxDecoration(
|
||||
gradient: event.messageType == MessageTypes.Text
|
||||
? LinearGradient(
|
||||
colors: [
|
||||
backgroundColor,
|
||||
backgroundColorDark,
|
||||
backgroundColor,
|
||||
],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
controller.loadingMode
|
||||
? L10n.of(context)!.loadingPleaseWait
|
||||
: event.content.tryGet<String>('body') ?? '',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 24,
|
||||
color: Colors.white,
|
||||
backgroundColor: event.messageType == MessageTypes.Text
|
||||
? null
|
||||
: Colors.black,
|
||||
),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
bottom: 8,
|
||||
left: 8,
|
||||
right: 8,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
for (var i = 0; i < events.length; i++)
|
||||
Container(
|
||||
margin: const EdgeInsets.all(4),
|
||||
width: 8,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: Colors.black, width: 1),
|
||||
color: i == controller.index
|
||||
? Colors.white
|
||||
: Colors.grey.shade400,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: SafeArea(
|
||||
child: LinearProgressIndicator(
|
||||
color: Theme.of(context).primaryColor,
|
||||
backgroundColor: Theme.of(context).colorScheme.surface,
|
||||
value: controller.loadingMode
|
||||
? null
|
||||
: controller.progress.inMilliseconds /
|
||||
StoryPageController.maxProgress.inMilliseconds,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue