OpenContacts/lib/widgets/messages.dart

609 lines
22 KiB
Dart
Raw Normal View History

2023-05-01 16:00:56 -04:00
import 'package:cached_network_image/cached_network_image.dart';
2023-05-01 13:13:40 -04:00
import 'package:contacts_plus_plus/api_client.dart';
import 'package:contacts_plus_plus/apis/message_api.dart';
2023-05-01 16:00:56 -04:00
import 'package:contacts_plus_plus/auxiliary.dart';
2023-05-01 13:13:40 -04:00
import 'package:contacts_plus_plus/models/friend.dart';
import 'package:contacts_plus_plus/models/message.dart';
2023-05-01 16:00:56 -04:00
import 'package:contacts_plus_plus/models/session.dart';
2023-05-01 13:13:40 -04:00
import 'package:contacts_plus_plus/neos_hub.dart';
import 'package:contacts_plus_plus/widgets/generic_avatar.dart';
2023-04-29 15:26:12 -04:00
import 'package:flutter/material.dart';
2023-04-30 03:01:59 -04:00
import 'package:intl/intl.dart';
2023-04-29 15:26:12 -04:00
class Messages extends StatefulWidget {
const Messages({required this.friend, super.key});
final Friend friend;
@override
State<StatefulWidget> createState() => _MessagesState();
}
class _MessagesState extends State<Messages> {
Future<Iterable<Message>>? _messagesFuture;
2023-04-30 03:01:59 -04:00
final TextEditingController _messageTextController = TextEditingController();
2023-05-01 16:00:56 -04:00
final ScrollController _sessionListScrollController = ScrollController();
2023-04-30 07:39:09 -04:00
ClientHolder? _clientHolder;
HubHolder? _cacheHolder;
2023-04-30 03:01:59 -04:00
bool _isSendable = false;
2023-05-01 16:00:56 -04:00
bool _showSessionListChevron = false;
double get _shevronOpacity => _showSessionListChevron ? 1.0 : 0.0;
2023-04-30 17:14:29 -04:00
void _loadMessages() {
final cache = _cacheHolder?.hub.getCache(widget.friend.id);
if (cache != null) {
_messagesFuture = Future(() => cache.messages);
2023-04-30 17:14:29 -04:00
} else {
2023-05-01 16:00:56 -04:00
_messagesFuture = MessageApi.getUserMessages(
_clientHolder!.client, userId: widget.friend.id)
2023-04-30 17:14:29 -04:00
..then((value) {
final list = value.toList();
list.sort();
_cacheHolder?.hub.setCache(widget.friend.id, list);
2023-05-01 16:00:56 -04:00
_cacheHolder?.hub.registerListener(
widget.friend.id, () => setState(() {}));
2023-04-30 17:14:29 -04:00
return list;
});
}
2023-04-29 15:26:12 -04:00
}
@override
2023-04-30 07:39:09 -04:00
void didChangeDependencies() {
super.didChangeDependencies();
final clientHolder = ClientHolder.of(context);
2023-04-30 17:14:29 -04:00
bool dirty = false;
2023-04-30 07:39:09 -04:00
if (_clientHolder != clientHolder) {
_clientHolder = clientHolder;
2023-04-30 17:14:29 -04:00
dirty = true;
2023-04-30 07:39:09 -04:00
}
final cacheHolder = HubHolder.of(context);
2023-04-30 17:14:29 -04:00
if (_cacheHolder != cacheHolder) {
_cacheHolder = cacheHolder;
dirty = true;
}
if (dirty) _loadMessages();
}
@override
void dispose() {
_cacheHolder?.hub.unregisterListener(widget.friend.id);
2023-05-01 16:00:56 -04:00
_messageTextController.dispose();
_sessionListScrollController.dispose();
super.dispose();
2023-04-29 15:26:12 -04:00
}
2023-05-01 16:00:56 -04:00
@override
void initState() {
super.initState();
_sessionListScrollController.addListener(() {
if (_sessionListScrollController.position.maxScrollExtent > 0 && !_showSessionListChevron) {
setState(() {
_showSessionListChevron = true;
});
}
if (_sessionListScrollController.position.atEdge && _sessionListScrollController.position.pixels > 0
&& _showSessionListChevron) {
setState(() {
_showSessionListChevron = false;
});
}
});
}
2023-04-29 15:26:12 -04:00
@override
Widget build(BuildContext context) {
2023-05-01 16:00:56 -04:00
final apiClient = ClientHolder
.of(context)
.client;
2023-04-30 17:14:29 -04:00
var sessions = widget.friend.userStatus.activeSessions;
2023-05-01 16:00:56 -04:00
final appBarColor = Theme
.of(context)
.colorScheme
.surfaceVariant;
2023-04-29 15:26:12 -04:00
return Scaffold(
appBar: AppBar(
title: Text(widget.friend.username),
2023-04-30 17:14:29 -04:00
scrolledUnderElevation: 0.0,
2023-05-01 16:00:56 -04:00
backgroundColor: appBarColor,
/*bottom: sessions.isEmpty ? null : PreferredSize(
2023-04-30 17:14:29 -04:00
preferredSize: Size.fromHeight(_headerHeight),
child: Column(
children: sessions.getRange(0, _headerExpanded ? sessions.length : 1).map((e) => Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: GenericAvatar(imageUri: Aux.neosDbToHttp(e.thumbnail),),
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(e.name),
Text("${e.sessionUsers.length} users active"),
],
2023-04-30 17:14:29 -04:00
),
),
const Spacer(),
if (sessions.length > 1) TextButton(onPressed: (){
setState(() {
_headerExpanded = !_headerExpanded;
});
}, child: Text("+${sessions.length-1}"),)
],
)).toList(),
2023-04-30 17:14:29 -04:00
),
),*/
2023-04-29 15:26:12 -04:00
),
2023-05-01 16:00:56 -04:00
body: Stack(
children: [
FutureBuilder(
future: _messagesFuture,
builder: (context, snapshot) {
if (snapshot.hasData) {
final data = _cacheHolder?.hub
.getCache(widget.friend.id)
?.messages ?? [];
return ListView.builder(
reverse: true,
itemCount: data.length,
itemBuilder: (context, index) {
final entry = data.elementAt(index);
return entry.senderId == apiClient.userId
? MyMessageBubble(message: entry)
: OtherMessageBubble(message: entry);
2023-05-01 16:00:56 -04:00
},
);
} else if (snapshot.hasError) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 64, vertical: 128,),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text("Failed to load messages:", style: Theme
.of(context)
.textTheme
.titleMedium,),
const SizedBox(height: 16,),
Text("${snapshot.error}"),
const Spacer(),
TextButton.icon(
onPressed: () {
setState(() {
_loadMessages();
});
},
style: TextButton.styleFrom(
backgroundColor: Theme
.of(context)
.colorScheme
.secondaryContainer,
padding: const EdgeInsets.symmetric(
vertical: 16, horizontal: 16),
),
icon: const Icon(Icons.refresh),
label: const Text("Retry"),
),
],
),
),
);
} else {
return Column(
2023-04-30 17:14:29 -04:00
mainAxisSize: MainAxisSize.max,
2023-05-01 16:00:56 -04:00
mainAxisAlignment: MainAxisAlignment.end,
children: const [
LinearProgressIndicator(),
],
);
}
},
),
if (sessions.isNotEmpty) Positioned(
top: 0.0,
left: 0.0,
right: 0.0,
child: Container(
constraints: const BoxConstraints(maxHeight: 64),
decoration: BoxDecoration(
color: appBarColor,
border: const Border(top: BorderSide(width: 1, color: Colors.black26), )
),
child: Stack(
children: [
ListView.builder(
controller: _sessionListScrollController,
scrollDirection: Axis.horizontal,
itemCount: sessions.length,
itemBuilder: (context, index) => SessionTile(session: sessions[index]),
),
AnimatedOpacity(
opacity: _shevronOpacity,
curve: Curves.easeOut,
duration: const Duration(milliseconds: 200),
child: Align(
alignment: Alignment.centerRight,
child: Container(
padding: const EdgeInsets.only(left: 16, right: 4, top: 1, bottom: 1),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [
appBarColor.withOpacity(0),
appBarColor,
appBarColor,
],
),
),
height: double.infinity,
child: const Icon(Icons.chevron_right),
),
),
)
],
),
),
),
],
),
bottomNavigationBar: Padding(
padding: MediaQuery
.of(context)
.viewInsets,
child: BottomAppBar(
padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 6),
child: Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(8),
child: TextField(
controller: _messageTextController,
maxLines: 4,
minLines: 1,
onChanged: (text) {
if (text.isNotEmpty && !_isSendable) {
2023-04-30 17:14:29 -04:00
setState(() {
2023-05-01 16:00:56 -04:00
_isSendable = true;
2023-04-30 17:14:29 -04:00
});
2023-05-01 16:00:56 -04:00
} else if (text.isEmpty && _isSendable) {
setState(() {
_isSendable = false;
});
}
},
decoration: InputDecoration(
isDense: true,
hintText: "Send a message to ${widget.friend
.username}...",
contentPadding: const EdgeInsets.all(16),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(24)
)
2023-04-30 17:14:29 -04:00
),
2023-05-01 16:00:56 -04:00
),
2023-04-29 15:26:12 -04:00
),
2023-04-30 17:14:29 -04:00
),
2023-05-01 16:00:56 -04:00
Padding(
padding: const EdgeInsets.only(left: 8, right: 4.0),
child: IconButton(
splashRadius: 24,
onPressed: _isSendable ? () async {
setState(() {
_isSendable = false;
});
final message = Message(
id: Message.generateId(),
recipientId: widget.friend.id,
senderId: apiClient.userId,
type: MessageType.text,
content: _messageTextController.text,
sendTime: DateTime.now().toUtc(),
);
try {
if (_cacheHolder == null) {
throw "Hub not connected.";
}
_cacheHolder!.hub.sendMessage(message);
_messageTextController.clear();
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("Failed to send message\n$e",
maxLines: null,
),
),
);
2023-04-30 03:01:59 -04:00
setState(() {
_isSendable = true;
});
}
2023-05-01 16:00:56 -04:00
} : null,
iconSize: 28,
icon: const Icon(Icons.send),
2023-04-30 03:01:59 -04:00
),
2023-05-01 16:00:56 -04:00
)
],
),
2023-04-30 03:01:59 -04:00
),
),
2023-04-29 15:26:12 -04:00
);
}
}
class MyMessageBubble extends StatelessWidget {
2023-04-30 03:01:59 -04:00
MyMessageBubble({required this.message, super.key});
2023-04-29 15:26:12 -04:00
final Message message;
2023-04-30 03:01:59 -04:00
final DateFormat _dateFormat = DateFormat.Hm();
2023-04-29 15:26:12 -04:00
@override
Widget build(BuildContext context) {
2023-04-29 16:21:00 -04:00
var content = message.content;
if (message.type == MessageType.sessionInvite) {
content = "<Session Invite>";
} else if (message.type == MessageType.sound) {
content = "<Voice Message>";
} else if (message.type == MessageType.object) {
content = "<Asset>";
}
2023-04-29 15:26:12 -04:00
return Row(
mainAxisAlignment: MainAxisAlignment.end,
2023-04-29 16:21:00 -04:00
mainAxisSize: MainAxisSize.min,
2023-04-29 15:26:12 -04:00
children: [
2023-04-29 16:21:00 -04:00
Flexible(
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
color: Theme.of(context).colorScheme.primaryContainer,
margin: const EdgeInsets.only(left: 32, bottom: 16, right: 12),
2023-04-29 16:21:00 -04:00
child: Padding(
2023-04-30 03:01:59 -04:00
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
content,
softWrap: true,
maxLines: null,
style: Theme.of(context).textTheme.bodyLarge,
),
const SizedBox(height: 6,),
Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
_dateFormat.format(message.sendTime),
style: Theme.of(context).textTheme.labelMedium?.copyWith(color: Colors.white54),
),
const SizedBox(width: 4,),
MessageStateIndicator(messageState: message.state),
],
2023-04-30 03:01:59 -04:00
),
],
2023-04-29 16:21:00 -04:00
),
),
),
2023-04-29 15:26:12 -04:00
),
],
);
}
}
class OtherMessageBubble extends StatelessWidget {
2023-04-30 03:01:59 -04:00
OtherMessageBubble({required this.message, super.key});
2023-04-29 15:26:12 -04:00
final Message message;
2023-04-30 03:01:59 -04:00
final DateFormat _dateFormat = DateFormat.Hm();
2023-04-29 15:26:12 -04:00
@override
Widget build(BuildContext context) {
2023-04-29 16:21:00 -04:00
var content = message.content;
if (message.type == MessageType.sessionInvite) {
content = "<Session Invite>";
} else if (message.type == MessageType.sound) {
content = "<Voice Message>";
} else if (message.type == MessageType.object) {
content = "<Asset>";
}
2023-04-29 15:26:12 -04:00
return Row(
2023-04-29 16:21:00 -04:00
mainAxisSize: MainAxisSize.min,
2023-04-29 15:26:12 -04:00
mainAxisAlignment: MainAxisAlignment.start,
children: [
2023-04-29 16:21:00 -04:00
Flexible(
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
color: Theme
.of(context)
.colorScheme
.secondaryContainer,
margin: const EdgeInsets.only(right: 32, bottom: 16, left: 12),
2023-04-29 16:21:00 -04:00
child: Padding(
2023-04-30 03:01:59 -04:00
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
content,
softWrap: true,
maxLines: null,
style: Theme.of(context).textTheme.bodyLarge,
),
const SizedBox(height: 6,),
Text(
_dateFormat.format(message.sendTime),
style: Theme.of(context).textTheme.labelMedium?.copyWith(color: Colors.white54),
),
],
2023-04-29 16:21:00 -04:00
),
),
),
2023-04-29 15:26:12 -04:00
),
],
);
}
2023-04-30 03:01:59 -04:00
}
class MessageStateIndicator extends StatelessWidget {
const MessageStateIndicator({required this.messageState, super.key});
final MessageState messageState;
2023-04-30 03:01:59 -04:00
@override
Widget build(BuildContext context) {
late final IconData icon;
switch (messageState) {
case MessageState.local:
icon = Icons.alarm;
break;
case MessageState.sent:
icon = Icons.done;
break;
case MessageState.read:
icon = Icons.done_all;
break;
}
return Icon(
icon,
size: 12,
color: messageState == MessageState.read ? Theme.of(context).colorScheme.primary : null,
);
2023-04-30 03:01:59 -04:00
}
2023-05-01 16:00:56 -04:00
}
2023-04-30 03:01:59 -04:00
2023-05-01 16:00:56 -04:00
class SessionTile extends StatelessWidget {
const SessionTile({required this.session, super.key});
final Session session;
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: () {
showDialog(context: context, builder: (context) {
final ScrollController userListScrollController = ScrollController();
final thumbnailUri = Aux.neosDbToHttp(session.thumbnail);
return Dialog(
insetPadding: const EdgeInsets.all(32),
child: Container(
constraints: const BoxConstraints(maxHeight: 400),
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: ListView(
children: [
Text(session.name, style: Theme.of(context).textTheme.titleMedium),
Text(session.description.isEmpty ? "No description." : session.description, style: Theme.of(context).textTheme.labelMedium),
Text("Tags: ${session.tags.isEmpty ? "None" : session.tags.join(", ")}",
style: Theme.of(context).textTheme.labelMedium,
softWrap: true,
),
Text("Users: ${session.sessionUsers.length}", style: Theme.of(context).textTheme.labelMedium),
Text("Maximum users: ${session.maxUsers}", style: Theme.of(context).textTheme.labelMedium),
Text("Headless: ${session.headlessHost ? "Yes" : "No"}", style: Theme.of(context).textTheme.labelMedium),
],
),
),
if (session.sessionUsers.isNotEmpty) Expanded(
child: Scrollbar(
trackVisibility: true,
controller: userListScrollController,
thumbVisibility: true,
child: ListView.builder(
controller: userListScrollController,
shrinkWrap: true,
itemCount: session.sessionUsers.length,
itemBuilder: (context, index) {
final user = session.sessionUsers[index];
return ListTile(
dense: true,
title: Text(user.username, textAlign: TextAlign.end,),
subtitle: Text(user.isPresent ? "Active" : "Inactive", textAlign: TextAlign.end,),
);
},
),
),
) else Expanded(
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: const [
Icon(Icons.person_remove_alt_1_rounded),
Padding(
padding: EdgeInsets.all(16.0),
child: Text("No one is currently playing.", textAlign: TextAlign.center,),
)
],
),
),
),
],
),
),
Expanded(
child: Center(
child: thumbnailUri.isEmpty ? const Text("No Image") : CachedNetworkImage(
imageUrl: thumbnailUri,
placeholder: (context, url) {
return const CircularProgressIndicator();
},
errorWidget: (context, error, what) => Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Icon(Icons.no_photography),
Padding(
padding: EdgeInsets.all(16.0),
child: Text("Failed to load Image"),
)
],
),
),
),
)
],
),
),
);
});
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GenericAvatar(imageUri: Aux.neosDbToHttp(session.thumbnail), placeholderIcon: Icons.no_photography),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(session.name),
Text("${session.sessionUsers.length}/${session.maxUsers} active users")
],
),
)
],
),
);
}
2023-04-29 15:26:12 -04:00
}