Initial commit

This commit is contained in:
Christian Pauly 2020-01-01 19:10:13 +01:00
commit b5f2ecd56f
96 changed files with 4522 additions and 0 deletions

View file

@ -0,0 +1,50 @@
import 'package:flutter/material.dart';
enum FocusPage { FIRST, SECOND }
class AdaptivePageLayout extends StatelessWidget {
final Widget firstScaffold;
final Widget secondScaffold;
final FocusPage primaryPage;
final double minWidth;
static const double defaultMinWidth = 400;
static bool columnMode(BuildContext context) =>
MediaQuery.of(context).size.width > 2 * defaultMinWidth;
AdaptivePageLayout(
{this.firstScaffold,
this.secondScaffold,
this.primaryPage = FocusPage.FIRST,
this.minWidth = defaultMinWidth,
Key key})
: super(key: key);
@override
Widget build(BuildContext context) {
return OrientationBuilder(builder: (context, orientation) {
if (orientation == Orientation.portrait ||
columnMode(context)) if (primaryPage == FocusPage.FIRST)
return firstScaffold;
else
return secondScaffold;
return Row(
children: <Widget>[
Container(
width: minWidth,
child: firstScaffold,
),
Container(
width: 1,
color: Color(0xFFE8E8E8),
),
Expanded(
child: Container(
child: secondScaffold,
),
)
],
);
});
}
}

View file

@ -0,0 +1,39 @@
import 'package:cached_network_image/cached_network_image.dart';
import 'package:famedlysdk/famedlysdk.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'matrix.dart';
class Avatar extends StatelessWidget {
final MxContent mxContent;
final double size;
const Avatar(this.mxContent, {this.size = 40, Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
final String src = mxContent.getThumbnail(
Matrix.of(context).client,
width: size * MediaQuery.of(context).devicePixelRatio,
height: size * MediaQuery.of(context).devicePixelRatio,
method: ThumbnailMethod.scale,
);
return CircleAvatar(
radius: size / 2,
backgroundImage: mxContent.mxc?.isNotEmpty ?? false
? kIsWeb
? NetworkImage(
src,
)
: CachedNetworkImageProvider(
src,
)
: null,
backgroundColor: Color(0xFFF8F8F8),
child: mxContent.mxc.isEmpty
? Text("@", style: TextStyle(color: Colors.blueGrey))
: null,
);
}
}

View file

@ -0,0 +1,70 @@
import 'package:famedlysdk/famedlysdk.dart';
import 'package:fluffychat/utils/app_route.dart';
import 'package:fluffychat/views/chat_details.dart';
import 'package:fluffychat/views/chat_list.dart';
import 'package:flutter/material.dart';
import 'matrix.dart';
class ChatSettingsPopupMenu extends StatelessWidget {
final Room room;
final bool displayChatDetails;
const ChatSettingsPopupMenu(this.room, this.displayChatDetails, {Key key})
: super(key: key);
@override
Widget build(BuildContext context) {
List<PopupMenuEntry<String>> items = <PopupMenuEntry<String>>[
room.pushRuleState == PushRuleState.notify
? const PopupMenuItem<String>(
value: "mute",
child: Text('Mute chat'),
)
: const PopupMenuItem<String>(
value: "unmute",
child: Text('Unmute chat'),
),
const PopupMenuItem<String>(
value: "leave",
child: Text('Leave'),
),
];
if (displayChatDetails)
items.insert(
0,
const PopupMenuItem<String>(
value: "details",
child: Text('Chat details'),
),
);
return PopupMenuButton(
onSelected: (String choice) async {
switch (choice) {
case "leave":
await Matrix.of(context).tryRequestWithLoadingDialog(room.leave());
Navigator.of(context).pushAndRemoveUntil(
AppRoute.defaultRoute(context, ChatListView()),
(Route r) => false);
break;
case "mute":
await Matrix.of(context).tryRequestWithLoadingDialog(
room.setPushRuleState(PushRuleState.mentions_only));
break;
case "unmute":
await Matrix.of(context).tryRequestWithLoadingDialog(
room.setPushRuleState(PushRuleState.notify));
break;
case "details":
Navigator.of(context).push(
AppRoute.defaultRoute(
context,
ChatDetails(room),
),
);
break;
}
},
itemBuilder: (BuildContext context) => items,
);
}
}

View file

@ -0,0 +1,55 @@
import 'package:cached_network_image/cached_network_image.dart';
import 'package:famedlysdk/famedlysdk.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'matrix.dart';
class ContentBanner extends StatelessWidget {
final MxContent mxContent;
final double height;
final IconData defaultIcon;
final bool loading;
const ContentBanner(this.mxContent,
{this.height = 400,
this.defaultIcon = Icons.people_outline,
this.loading = false,
Key key})
: super(key: key);
@override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
final int bannerSize =
(mediaQuery.size.width * mediaQuery.devicePixelRatio).toInt();
final String src = mxContent.getThumbnail(
Matrix.of(context).client,
width: bannerSize,
height: bannerSize,
method: ThumbnailMethod.scale,
);
return Container(
height: 200,
color: Color(0xFFF8F8F8),
child: !loading
? mxContent.mxc?.isNotEmpty ?? false
? kIsWeb
? Image.network(
src,
height: 200,
fit: BoxFit.cover,
)
: CachedNetworkImage(
imageUrl: src,
height: 200,
fit: BoxFit.cover,
placeholder: (c, s) =>
Center(child: CircularProgressIndicator()),
errorWidget: (c, s, o) => Icon(Icons.error, size: 200),
)
: Icon(defaultIcon, size: 200)
: Icon(defaultIcon, size: 200),
);
}
}

View file

@ -0,0 +1,59 @@
import 'package:fluffychat/views/chat.dart';
import 'package:flutter/material.dart';
import '../matrix.dart';
class NewGroupDialog extends StatelessWidget {
final TextEditingController controller = TextEditingController();
void submitAction(BuildContext context) async {
final MatrixState matrix = Matrix.of(context);
Map<String, dynamic> params = {};
if (controller.text.isNotEmpty) params["name"] = controller.text;
final String roomID = await matrix.tryRequestWithLoadingDialog(
matrix.client.createRoom(params: params),
);
Navigator.of(context).pop();
if (roomID != null)
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Chat(roomID)),
);
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text("Create new group"),
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextField(
controller: controller,
autofocus: true,
autocorrect: false,
textInputAction: TextInputAction.go,
onSubmitted: (s) => submitAction(context),
decoration: InputDecoration(
labelText: "Group name",
icon: Icon(Icons.people),
hintText: "Enter a group name"),
),
],
),
actions: <Widget>[
FlatButton(
child: Text("Close".toUpperCase(),
style: TextStyle(color: Colors.blueGrey)),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
child: Text("Create".toUpperCase()),
onPressed: () => submitAction(context),
),
],
);
}
}

View file

@ -0,0 +1,72 @@
import 'package:famedlysdk/famedlysdk.dart';
import 'package:fluffychat/views/chat.dart';
import 'package:flutter/material.dart';
import '../matrix.dart';
class NewPrivateChatDialog extends StatelessWidget {
final TextEditingController controller = TextEditingController();
void submitAction(BuildContext context) async {
if (controller.text.isEmpty) return;
final MatrixState matrix = Matrix.of(context);
final User user = User(
"@" + controller.text,
room: Room(id: "", client: matrix.client),
);
final String roomID =
await matrix.tryRequestWithLoadingDialog(user.startDirectChat());
Navigator.of(context).pop();
if (roomID != null)
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Chat(roomID)),
);
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text("New private chat"),
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
TextField(
controller: controller,
autofocus: true,
autocorrect: false,
textInputAction: TextInputAction.go,
onSubmitted: (s) => submitAction(context),
decoration: InputDecoration(
labelText: "Enter a username",
icon: Icon(Icons.account_circle),
prefixText: "@",
hintText: "username:homeserver"),
),
SizedBox(height: 16),
Text(
"Your username is ${Matrix.of(context).client.userID}",
style: TextStyle(
color: Colors.blueGrey,
fontSize: 12,
),
),
],
),
actions: <Widget>[
FlatButton(
child: Text("Close".toUpperCase(),
style: TextStyle(color: Colors.blueGrey)),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
child: Text("Continue".toUpperCase()),
onPressed: () => submitAction(context),
),
],
);
}
}

View file

@ -0,0 +1,32 @@
import 'package:famedlysdk/famedlysdk.dart';
import 'package:flutter/material.dart';
import '../matrix.dart';
class RedactMessageDialog extends StatelessWidget {
final Event event;
const RedactMessageDialog(this.event);
void removeAction(BuildContext context) {
Matrix.of(context).tryRequestWithLoadingDialog(event.redact());
Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text("Message will be removed for all participants"),
actions: <Widget>[
FlatButton(
child: Text("Close".toUpperCase(),
style: TextStyle(color: Colors.blueGrey)),
onPressed: () => Navigator.of(context).pop(),
),
FlatButton(
child: Text("Remove".toUpperCase()),
onPressed: () => removeAction(context),
),
],
);
}
}

View file

@ -0,0 +1,67 @@
import 'package:famedlysdk/famedlysdk.dart';
import 'package:fluffychat/components/message_content.dart';
import 'package:fluffychat/utils/app_route.dart';
import 'package:fluffychat/views/chat.dart';
import 'package:flutter/material.dart';
import '../avatar.dart';
class ChatListItem extends StatelessWidget {
final Room room;
final bool activeChat;
const ChatListItem(this.room, {this.activeChat = false});
@override
Widget build(BuildContext context) {
return Material(
color: activeChat ? Color(0xFFE8E8E8) : Colors.white,
child: ListTile(
leading: Avatar(room.avatar),
title: Text(room.displayname),
subtitle: MessageContent(room.lastEvent, textOnly: true),
onTap: () {
if (activeChat)
Navigator.pushReplacement(
context,
AppRoute.defaultRoute(context, Chat(room.id)),
);
else
Navigator.push(
context,
AppRoute.defaultRoute(context, Chat(room.id)),
);
},
onLongPress: () {},
trailing: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Text(room.timeCreated.toEventTimeString()),
room.notificationCount > 0
? Container(
width: 20,
height: 20,
margin: EdgeInsets.only(top: 3),
decoration: BoxDecoration(
color: room.highlightCount > 0
? Colors.red
: Color(0xFF5625BA),
borderRadius: BorderRadius.circular(20),
),
child: Center(
child: Text(
room.notificationCount.toString(),
style: TextStyle(color: Colors.white),
),
),
)
: Text(" "),
],
),
),
),
);
}
}

View file

@ -0,0 +1,128 @@
import 'package:bubble/bubble.dart';
import 'package:famedlysdk/famedlysdk.dart';
import 'package:fluffychat/components/dialogs/redact_message_dialog.dart';
import 'package:fluffychat/components/message_content.dart';
import 'package:flutter/material.dart';
import '../avatar.dart';
import '../matrix.dart';
import 'state_message.dart';
class Message extends StatelessWidget {
final Event event;
const Message(this.event);
@override
Widget build(BuildContext context) {
if (event.typeKey != "m.room.message") return StateMessage(event);
Client client = Matrix.of(context).client;
final bool ownMessage = event.senderId == client.userID;
Alignment alignment = ownMessage ? Alignment.topRight : Alignment.topLeft;
Color color = Color(0xFFF8F8F8);
BubbleNip nip = ownMessage ? BubbleNip.rightBottom : BubbleNip.leftBottom;
final Color textColor = ownMessage ? Colors.white : Colors.black;
MainAxisAlignment rowMainAxisAlignment =
ownMessage ? MainAxisAlignment.end : MainAxisAlignment.start;
if (ownMessage) {
color = event.status == -1 ? Colors.redAccent : Color(0xFF5625BA);
}
List<PopupMenuEntry<String>> popupMenuList = [];
if (event.canRedact && !event.redacted && event.status > 1)
popupMenuList.add(
const PopupMenuItem<String>(
value: "remove",
child: Text('Remove message'),
),
);
if (ownMessage && event.status == -1) {
popupMenuList.add(
const PopupMenuItem<String>(
value: "resend",
child: Text('Send again'),
),
);
popupMenuList.add(
const PopupMenuItem<String>(
value: "delete",
child: Text('Delete message'),
),
);
}
List<Widget> rowChildren = [
Expanded(
child: PopupMenuButton(
onSelected: (String choice) async {
switch (choice) {
case "remove":
showDialog(
context: context,
builder: (BuildContext context) => RedactMessageDialog(event),
);
break;
case "resend":
event.sendAgain();
break;
case "delete":
event.remove();
break;
}
},
itemBuilder: (BuildContext context) => popupMenuList,
child: Opacity(
opacity: event.status == 0 ? 0.5 : 1,
child: Bubble(
elevation: 0,
alignment: alignment,
margin: BubbleEdges.symmetric(horizontal: 4),
color: color,
nip: nip,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
ownMessage ? "You" : event.sender.calcDisplayname(),
style: TextStyle(
color: textColor,
fontWeight: FontWeight.bold,
),
),
SizedBox(width: 4),
Text(
event.time.toEventTimeString(),
style: TextStyle(color: textColor, fontSize: 12),
),
],
),
MessageContent(
event,
textColor: textColor,
),
],
),
),
),
),
),
];
if (ownMessage)
rowChildren.add(Avatar(event.sender.avatarUrl));
else
rowChildren.insert(0, Avatar(event.sender.avatarUrl));
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: rowMainAxisAlignment,
children: rowChildren,
),
);
}
}

View file

@ -0,0 +1,119 @@
import 'package:famedlysdk/famedlysdk.dart';
import 'package:fluffychat/utils/app_route.dart';
import 'package:fluffychat/views/chat.dart';
import 'package:flutter/material.dart';
import '../avatar.dart';
import '../matrix.dart';
class ParticipantListItem extends StatelessWidget {
final User user;
const ParticipantListItem(this.user);
participantAction(BuildContext context, String action) async {
final MatrixState matrix = Matrix.of(context);
switch (action) {
case "ban":
matrix.tryRequestWithLoadingDialog(user.ban());
break;
case "unban":
matrix.tryRequestWithLoadingDialog(user.unban());
break;
case "kick":
matrix.tryRequestWithLoadingDialog(user.kick());
break;
case "admin":
matrix.tryRequestWithLoadingDialog(user.setPower(100));
break;
case "user":
matrix.tryRequestWithLoadingDialog(user.setPower(100));
break;
case "message":
final String roomId = await user.startDirectChat();
Navigator.of(context).pushAndRemoveUntil(
AppRoute.defaultRoute(
context,
Chat(roomId),
),
(Route r) => r.isFirst);
break;
}
}
@override
Widget build(BuildContext context) {
const Map<Membership, String> membershipBatch = {
Membership.join: "",
Membership.ban: "Banned",
Membership.invite: "Invited",
Membership.leave: "Left",
};
final String permissionBatch = user.powerLevel == 100
? "Admin"
: user.powerLevel >= 50 ? "Moderator" : "";
List<PopupMenuEntry<String>> items = <PopupMenuEntry<String>>[];
if (user.canChangePowerLevel &&
user.room.ownPowerLevel == 100 &&
user.powerLevel != 100)
items.add(
PopupMenuItem(child: Text("Make an admin"), value: "admin"),
);
if (user.canChangePowerLevel && user.powerLevel != 0)
items.add(
PopupMenuItem(child: Text("Revoke all permissions"), value: "user"),
);
if (user.canKick)
items.add(
PopupMenuItem(child: Text("Kick from group"), value: "kick"),
);
if (user.canBan && user.membership != Membership.ban)
items.add(
PopupMenuItem(child: Text("Ban from group"), value: "ban"),
);
else if (user.canBan && user.membership == Membership.ban)
items.add(
PopupMenuItem(child: Text("Remove exile"), value: "unban"),
);
if (user.id != Matrix.of(context).client.userID)
items.add(
PopupMenuItem(child: Text("Send a message"), value: "message"),
);
return PopupMenuButton(
onSelected: (action) => participantAction(context, action),
itemBuilder: (c) => items,
child: ListTile(
title: Row(
children: <Widget>[
Text(user.calcDisplayname()),
permissionBatch.isEmpty
? Container()
: Container(
padding: EdgeInsets.all(4),
margin: EdgeInsets.symmetric(horizontal: 8),
decoration: BoxDecoration(
color: Color(0xFFF8F8F8),
borderRadius: BorderRadius.circular(8),
),
child: Center(child: Text(permissionBatch)),
),
membershipBatch[user.membership].isEmpty
? Container()
: Container(
padding: EdgeInsets.all(4),
margin: EdgeInsets.symmetric(horizontal: 8),
decoration: BoxDecoration(
color: Color(0xFFF8F8F8),
borderRadius: BorderRadius.circular(8),
),
child:
Center(child: Text(membershipBatch[user.membership])),
),
],
),
subtitle: Text(user.id),
leading: Avatar(user.avatarUrl),
),
);
}
}

View file

@ -0,0 +1,23 @@
import 'package:bubble/bubble.dart';
import 'package:famedlysdk/famedlysdk.dart';
import 'package:flutter/material.dart';
import '../message_content.dart';
class StateMessage extends StatelessWidget {
final Event event;
const StateMessage(this.event);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Bubble(
color: Color(0xFFF8F8F8),
elevation: 0,
alignment: Alignment.center,
child: MessageContent(event),
),
);
}
}

167
lib/components/matrix.dart Normal file
View file

@ -0,0 +1,167 @@
import 'dart:convert';
import 'package:famedlysdk/famedlysdk.dart';
import 'package:fluffychat/utils/sqflite_store.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:localstorage/localstorage.dart';
import 'package:toast/toast.dart';
class Matrix extends StatefulWidget {
final Widget child;
final String clientName;
final Client client;
Matrix({this.child, this.clientName, this.client, Key key}) : super(key: key);
@override
MatrixState createState() => MatrixState();
/// Returns the (nearest) Client instance of your application.
static MatrixState of(BuildContext context) {
MatrixState newState =
(context.dependOnInheritedWidgetOfExactType<_InheritedMatrix>()).data;
newState.context = context;
return newState;
}
}
class MatrixState extends State<Matrix> {
Client client;
BuildContext context;
/// Used to load the old account if there is no store available.
void loadAccount() async {
final LocalStorage storage = LocalStorage('LocalStorage');
await storage.ready;
final credentialsStr = storage.getItem(widget.clientName);
if (credentialsStr == null || credentialsStr.isEmpty) {
client.connection.onLoginStateChanged.add(LoginState.loggedOut);
return;
}
print("[Matrix] Restoring account credentials");
final Map<String, dynamic> credentials = json.decode(credentialsStr);
client.connection.connect(
newDeviceID: credentials["deviceID"],
newDeviceName: credentials["deviceName"],
newHomeserver: credentials["homeserver"],
newLazyLoadMembers: credentials["lazyLoadMembers"],
//newMatrixVersions: credentials["matrixVersions"], // FIXME: wrong List type
newToken: credentials["token"],
newUserID: credentials["userID"],
);
}
/// Used to save the current account persistently if there is no store available.
Future<void> saveAccount() async {
if (!kIsWeb) return;
print("[Matrix] Save account credentials in crypted preferences");
final Map<String, dynamic> credentials = {
"deviceID": client.deviceID,
"deviceName": client.deviceName,
"homeserver": client.homeserver,
"lazyLoadMembers": client.lazyLoadMembers,
"matrixVersions": client.matrixVersions,
"token": client.accessToken,
"userID": client.userID,
};
final LocalStorage storage = LocalStorage('LocalStorage');
await storage.ready;
await storage.setItem(widget.clientName, json.encode(credentials));
return;
}
void clean() async {
if (!kIsWeb) return;
print("Clear session...");
final LocalStorage storage = LocalStorage('LocalStorage');
await storage.ready;
storage.deleteItem(widget.clientName);
}
BuildContext _loadingDialogContext;
Future<dynamic> tryRequestWithLoadingDialog(Future<dynamic> request) async {
showLoadingDialog(context);
final dynamic = await tryRequestWithErrorToast(request);
hideLoadingDialog();
return dynamic;
}
Future<dynamic> tryRequestWithErrorToast(Future<dynamic> request) async {
try {
return await request;
} catch (exception) {
Toast.show(
exception.toString(),
context,
duration: Toast.LENGTH_LONG,
);
return false;
}
}
showLoadingDialog(BuildContext context) {
_loadingDialogContext = context;
showDialog(
context: _loadingDialogContext,
barrierDismissible: false,
builder: (BuildContext context) => AlertDialog(
content: Row(
children: <Widget>[
CircularProgressIndicator(),
SizedBox(width: 16),
Text("Loading... Please wait"),
],
),
),
);
}
hideLoadingDialog() => Navigator.of(_loadingDialogContext)?.pop();
@override
void initState() {
if (widget.client == null) {
client = Client(widget.clientName, debug: true);
if (!kIsWeb)
client.store = Store(client);
else
loadAccount();
} else {
client = widget.client;
}
super.initState();
}
@override
Widget build(BuildContext context) {
return _InheritedMatrix(
data: this,
child: widget.child,
);
}
}
class _InheritedMatrix extends InheritedWidget {
final MatrixState data;
_InheritedMatrix({Key key, this.data, Widget child})
: super(key: key, child: child);
@override
bool updateShouldNotify(_InheritedMatrix old) {
bool update = old.data.client.accessToken != this.data.client.accessToken ||
old.data.client.userID != this.data.client.userID ||
old.data.client.matrixVersions != this.data.client.matrixVersions ||
old.data.client.lazyLoadMembers != this.data.client.lazyLoadMembers ||
old.data.client.deviceID != this.data.client.deviceID ||
old.data.client.deviceName != this.data.client.deviceName ||
old.data.client.homeserver != this.data.client.homeserver;
return update;
}
}

View file

@ -0,0 +1,78 @@
import 'package:famedlysdk/famedlysdk.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'matrix.dart';
class MessageContent extends StatelessWidget {
final Event event;
final Color textColor;
final bool textOnly;
const MessageContent(this.event, {this.textColor, this.textOnly = false});
@override
Widget build(BuildContext context) {
final int maxLines = textOnly ? 1 : null;
if (textOnly)
return Text(
event.getBody(),
style: TextStyle(
color: textColor,
decoration: event.redacted ? TextDecoration.lineThrough : null,
),
maxLines: maxLines,
);
switch (event.type) {
case EventTypes.Audio:
case EventTypes.Image:
case EventTypes.File:
case EventTypes.Video:
return Container(
width: 200,
child: RaisedButton(
color: Colors.blueGrey,
child: Text(
"Download ${event.getBody()}",
overflow: TextOverflow.fade,
softWrap: false,
maxLines: 1,
),
onPressed: () => launch(
MxContent(event.content["url"])
.getDownloadLink(Matrix.of(context).client),
),
),
);
case EventTypes.Text:
case EventTypes.Reply:
case EventTypes.Notice:
return Text(
event.getBody(),
style: TextStyle(
color: textColor,
decoration: event.redacted ? TextDecoration.lineThrough : null,
),
);
case EventTypes.Emote:
return Text(
"* " + event.getBody(),
maxLines: maxLines,
style: TextStyle(
color: textColor,
fontStyle: FontStyle.italic,
decoration: event.redacted ? TextDecoration.lineThrough : null,
),
);
default:
return Text(
"${event.sender.calcDisplayname()} sent a ${event.typeKey} event",
maxLines: maxLines,
style: TextStyle(
color: textColor,
decoration: event.redacted ? TextDecoration.lineThrough : null,
),
);
}
}
}

59
lib/main.dart Normal file
View file

@ -0,0 +1,59 @@
import 'package:famedlysdk/famedlysdk.dart';
import 'package:flutter/material.dart';
import 'components/matrix.dart';
import 'views/chat_list.dart';
import 'views/login.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Matrix(
clientName: "FluffyWeb",
child: MaterialApp(
title: 'FluffyWeb',
theme: ThemeData(
primaryColor: Color(0xFF5625BA),
backgroundColor: Colors.white,
scaffoldBackgroundColor: Colors.white,
dialogTheme: DialogTheme(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
),
),
popupMenuTheme: PopupMenuThemeData(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
),
),
appBarTheme: AppBarTheme(
color: Colors.white,
elevation: 1,
textTheme: TextTheme(
title: TextStyle(color: Colors.black),
),
iconTheme: IconThemeData(color: Colors.black),
),
),
home: Builder(
builder: (BuildContext context) => StreamBuilder<LoginState>(
stream:
Matrix.of(context).client.connection.onLoginStateChanged.stream,
builder: (context, snapshot) {
if (!snapshot.hasData)
return Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
if (Matrix.of(context).client.isLogged()) return ChatListView();
return LoginPage();
},
),
),
),
);
}
}

34
lib/utils/app_route.dart Normal file
View file

@ -0,0 +1,34 @@
import 'package:fluffychat/components/adaptive_page_layout.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class AppRoute extends PageRouteBuilder {
static Route defaultRoute(BuildContext context, Widget page) {
return context != null && !AdaptivePageLayout.columnMode(context)
? CupertinoPageRoute(
builder: (BuildContext context) => page,
)
: AppRoute(page);
}
final Widget page;
AppRoute(this.page)
: super(
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) =>
page,
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) =>
FadeTransition(
opacity: animation,
child: child,
),
);
}

View file

@ -0,0 +1,588 @@
/*
* Copyright (c) 2019 Zender & Kurtz GbR.
*
* Authors:
* Christian Pauly <krille@famedly.com>
* Marcel Radzio <mtrnord@famedly.com>
*
* This file is part of famedlysdk_store_sqflite.
*
* famedlysdk_store_sqflite is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* famedlysdk_store_sqflite is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with famedlysdk_store_sqflite. If not, see <http://www.gnu.org/licenses/>.
*/
library famedlysdk_store_sqflite;
import 'dart:async';
import 'dart:convert';
import 'dart:core';
import 'package:famedlysdk/famedlysdk.dart';
import 'package:path/path.dart' as p;
import 'package:sqflite/sqflite.dart';
/// Responsible to store all data persistent and to query objects from the
/// database.
class Store extends StoreAPI {
final Client client;
Store(this.client) {
_init();
}
Database _db;
/// SQLite database for all persistent data. It is recommended to extend this
/// SDK instead of writing direct queries to the database.
//Database get db => _db;
_init() async {
var databasePath = await getDatabasesPath();
String path = p.join(databasePath, "FluffyMatrix.db");
_db = await openDatabase(path, version: 14,
onCreate: (Database db, int version) async {
await createTables(db);
}, onUpgrade: (Database db, int oldVersion, int newVersion) async {
if (client.debug)
print(
"[Store] Migrate databse from version $oldVersion to $newVersion");
if (oldVersion != newVersion) {
await schemes.forEach((String name, String scheme) async {
if (name != "Clients") await db.execute("DROP TABLE IF EXISTS $name");
});
await createTables(db);
await db.rawUpdate("UPDATE Clients SET prev_batch='' WHERE client=?",
[client.clientName]);
}
});
await _db.rawUpdate("UPDATE Events SET status=-1 WHERE status=0");
List<Map> list = await _db
.rawQuery("SELECT * FROM Clients WHERE client=?", [client.clientName]);
if (list.length == 1) {
var clientList = list[0];
client.connection.connect(
newToken: clientList["token"],
newHomeserver: clientList["homeserver"],
newUserID: clientList["matrix_id"],
newDeviceID: clientList["device_id"],
newDeviceName: clientList["device_name"],
newLazyLoadMembers: clientList["lazy_load_members"] == 1,
newMatrixVersions: clientList["matrix_versions"].toString().split(","),
newPrevBatch: clientList["prev_batch"].toString().isEmpty
? null
: clientList["prev_batch"],
);
if (client.debug)
print("[Store] Restore client credentials of ${client.userID}");
} else
client.connection.onLoginStateChanged.add(LoginState.loggedOut);
}
Future<void> createTables(Database db) async {
await schemes.forEach((String name, String scheme) async {
await db.execute(scheme);
});
}
Future<String> queryPrevBatch() async {
List<Map> list = await txn.rawQuery(
"SELECT prev_batch FROM Clients WHERE client=?", [client.clientName]);
return list[0]["prev_batch"];
}
/// Will be automatically called when the client is logged in successfully.
Future<void> storeClient() async {
await _db
.rawInsert('INSERT OR IGNORE INTO Clients VALUES(?,?,?,?,?,?,?,?,?)', [
client.clientName,
client.accessToken,
client.homeserver,
client.userID,
client.deviceID,
client.deviceName,
client.prevBatch,
client.matrixVersions.join(","),
client.lazyLoadMembers,
]);
return;
}
/// Clears all tables from the database.
Future<void> clear() async {
await _db
.rawDelete("DELETE FROM Clients WHERE client=?", [client.clientName]);
await schemes.forEach((String name, String scheme) async {
if (name != "Clients") await _db.rawDelete("DELETE FROM $name");
});
return;
}
Future<void> transaction(Future<void> queries()) async {
return _db.transaction((txnObj) async {
txn = txnObj;
await queries();
});
}
/// Will be automatically called on every synchronisation. Must be called inside of
// /// [transaction].
Future<void> storePrevBatch(dynamic sync) {
txn.rawUpdate("UPDATE Clients SET prev_batch=? WHERE client=?",
[client.prevBatch, client.clientName]);
return null;
}
Future<void> storeRoomPrevBatch(Room room) async {
await _db.rawUpdate("UPDATE Rooms SET prev_batch=? WHERE room_id=?",
[room.prev_batch, room.id]);
return null;
}
/// Stores a RoomUpdate object in the database. Must be called inside of
/// [transaction].
Future<void> storeRoomUpdate(RoomUpdate roomUpdate) {
if (txn == null) return null;
// Insert the chat into the database if not exists
if (roomUpdate.membership != Membership.leave)
txn.rawInsert(
"INSERT OR IGNORE INTO Rooms " + "VALUES(?, ?, 0, 0, '', 0, 0, '') ",
[roomUpdate.id, roomUpdate.membership.toString().split('.').last]);
else {
txn.rawDelete("DELETE FROM Rooms WHERE room_id=? ", [roomUpdate.id]);
return null;
}
// Update the notification counts and the limited timeline boolean and the summary
String updateQuery =
"UPDATE Rooms SET highlight_count=?, notification_count=?, membership=?";
List<dynamic> updateArgs = [
roomUpdate.highlight_count,
roomUpdate.notification_count,
roomUpdate.membership.toString().split('.').last
];
if (roomUpdate.summary?.mJoinedMemberCount != null) {
updateQuery += ", joined_member_count=?";
updateArgs.add(roomUpdate.summary.mJoinedMemberCount);
}
if (roomUpdate.summary?.mInvitedMemberCount != null) {
updateQuery += ", invited_member_count=?";
updateArgs.add(roomUpdate.summary.mInvitedMemberCount);
}
if (roomUpdate.summary?.mHeroes != null) {
updateQuery += ", heroes=?";
updateArgs.add(roomUpdate.summary.mHeroes.join(","));
}
updateQuery += " WHERE room_id=?";
updateArgs.add(roomUpdate.id);
txn.rawUpdate(updateQuery, updateArgs);
// Is the timeline limited? Then all previous messages should be
// removed from the database!
if (roomUpdate.limitedTimeline) {
txn.rawDelete("DELETE FROM Events WHERE room_id=?", [roomUpdate.id]);
txn.rawUpdate("UPDATE Rooms SET prev_batch=? WHERE room_id=?",
[roomUpdate.prev_batch, roomUpdate.id]);
}
return null;
}
/// Stores an UserUpdate object in the database. Must be called inside of
/// [transaction].
Future<void> storeUserEventUpdate(UserUpdate userUpdate) {
if (txn == null) return null;
if (userUpdate.type == "account_data")
txn.rawInsert("INSERT OR REPLACE INTO AccountData VALUES(?, ?)", [
userUpdate.eventType,
json.encode(userUpdate.content["content"]),
]);
else if (userUpdate.type == "presence")
txn.rawInsert("INSERT OR REPLACE INTO Presences VALUES(?, ?, ?)", [
userUpdate.eventType,
userUpdate.content["sender"],
json.encode(userUpdate.content["content"]),
]);
return null;
}
Future<dynamic> redactMessage(EventUpdate eventUpdate) async {
List<Map<String, dynamic>> res = await _db.rawQuery(
"SELECT * FROM Events WHERE event_id=?",
[eventUpdate.content["redacts"]]);
if (res.length == 1) {
Event event = Event.fromJson(res[0], null);
event.setRedactionEvent(Event.fromJson(eventUpdate.content, null));
final int changes1 = await _db.rawUpdate(
"UPDATE Events SET unsigned=?, content=?, prev_content=? WHERE event_id=?",
[
json.encode(event.unsigned ?? ""),
json.encode(event.content ?? ""),
json.encode(event.prevContent ?? ""),
event.eventId,
],
);
final int changes2 = await _db.rawUpdate(
"UPDATE RoomStates SET unsigned=?, content=?, prev_content=? WHERE event_id=?",
[
json.encode(event.unsigned ?? ""),
json.encode(event.content ?? ""),
json.encode(event.prevContent ?? ""),
event.eventId,
],
);
if (changes1 == 1 && changes2 == 1) return true;
}
return false;
}
/// Stores an EventUpdate object in the database. Must be called inside of
/// [transaction].
Future<void> storeEventUpdate(EventUpdate eventUpdate) {
if (txn == null) return null;
Map<String, dynamic> eventContent = eventUpdate.content;
String type = eventUpdate.type;
String chat_id = eventUpdate.roomID;
// Get the state_key for m.room.member events
String state_key = "";
if (eventContent["state_key"] is String) {
state_key = eventContent["state_key"];
}
if (eventUpdate.eventType == "m.room.redaction") {
redactMessage(eventUpdate);
}
if (type == "timeline" || type == "history") {
// calculate the status
num status = 2;
if (eventContent["status"] is num) status = eventContent["status"];
// Save the event in the database
if ((status == 1 || status == -1) &&
eventContent["unsigned"] is Map<String, dynamic> &&
eventContent["unsigned"]["transaction_id"] is String)
txn.rawUpdate(
"UPDATE Events SET status=?, event_id=? WHERE event_id=?", [
status,
eventContent["event_id"],
eventContent["unsigned"]["transaction_id"]
]);
else
txn.rawInsert(
"INSERT OR REPLACE INTO Events VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
[
eventContent["event_id"],
chat_id,
eventContent["origin_server_ts"],
eventContent["sender"],
eventContent["type"],
json.encode(eventContent["unsigned"] ?? ""),
json.encode(eventContent["content"]),
json.encode(eventContent["prevContent"]),
eventContent["state_key"],
status
]);
// Is there a transaction id? Then delete the event with this id.
if (status != -1 &&
eventUpdate.content.containsKey("unsigned") &&
eventUpdate.content["unsigned"]["transaction_id"] is String)
txn.rawDelete("DELETE FROM Events WHERE event_id=?",
[eventUpdate.content["unsigned"]["transaction_id"]]);
}
if (type == "history") return null;
if (eventUpdate.content["event_id"] != null ||
eventUpdate.content["state_key"] != null) {
final String now = DateTime.now().millisecondsSinceEpoch.toString();
txn.rawInsert(
"INSERT OR REPLACE INTO RoomStates VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
[
eventContent["event_id"] ?? now,
chat_id,
eventContent["origin_server_ts"] ?? now,
eventContent["sender"],
state_key,
json.encode(eventContent["unsigned"] ?? ""),
json.encode(eventContent["prev_content"] ?? ""),
eventContent["type"],
json.encode(eventContent["content"]),
]);
} else
txn.rawInsert("INSERT OR REPLACE INTO RoomAccountData VALUES(?, ?, ?)", [
eventContent["type"],
chat_id,
json.encode(eventContent["content"]),
]);
return null;
}
/// Returns a User object by a given Matrix ID and a Room.
Future<User> getUser({String matrixID, Room room}) async {
List<Map<String, dynamic>> res = await _db.rawQuery(
"SELECT * FROM RoomStates WHERE state_key=? AND room_id=?",
[matrixID, room.id]);
if (res.length != 1) return null;
return RoomState.fromJson(res[0], room).asUser;
}
/// Loads all Users in the database to provide a contact list
/// except users who are in the Room with the ID [exceptRoomID].
Future<List<User>> loadContacts({String exceptRoomID = ""}) async {
List<Map<String, dynamic>> res = await _db.rawQuery(
"SELECT * FROM RoomStates WHERE state_key LIKE '@%:%' AND state_key!=? AND room_id!=? GROUP BY state_key ORDER BY state_key",
[client.userID, exceptRoomID]);
List<User> userList = [];
for (int i = 0; i < res.length; i++)
userList
.add(RoomState.fromJson(res[i], Room(id: "", client: client)).asUser);
return userList;
}
/// Returns all users of a room by a given [roomID].
Future<List<User>> loadParticipants(Room room) async {
List<Map<String, dynamic>> res = await _db.rawQuery(
"SELECT * " +
" FROM RoomStates " +
" WHERE room_id=? " +
" AND type='m.room.member'",
[room.id]);
List<User> participants = [];
for (num i = 0; i < res.length; i++) {
participants.add(RoomState.fromJson(res[i], room).asUser);
}
return participants;
}
/// Returns a list of events for the given room and sets all participants.
Future<List<Event>> getEventList(Room room) async {
List<Map<String, dynamic>> eventRes = await _db.rawQuery(
"SELECT * " +
" FROM Events " +
" WHERE room_id=?" +
" GROUP BY event_id " +
" ORDER BY origin_server_ts DESC",
[room.id]);
List<Event> eventList = [];
for (num i = 0; i < eventRes.length; i++)
eventList.add(Event.fromJson(eventRes[i], room));
return eventList;
}
/// Returns all rooms, the client is participating. Excludes left rooms.
Future<List<Room>> getRoomList({bool onlyLeft = false}) async {
List<Map<String, dynamic>> res = await _db.rawQuery("SELECT * " +
" FROM Rooms" +
" WHERE membership" +
(onlyLeft ? "=" : "!=") +
"'leave' " +
" GROUP BY room_id ");
List<Room> roomList = [];
for (num i = 0; i < res.length; i++) {
Room room = await Room.getRoomFromTableRow(
res[i],
client,
states: getStatesFromRoomId(res[i]["room_id"]),
);
roomList.add(room);
}
return roomList;
}
/// Returns a room without events and participants.
@deprecated
Future<Room> getRoomById(String id) async {
List<Map<String, dynamic>> res =
await _db.rawQuery("SELECT * FROM Rooms WHERE room_id=?", [id]);
if (res.length != 1) return null;
return Room.getRoomFromTableRow(res[0], client,
roomAccountData: getAccountDataFromRoomId(id),
states: getStatesFromRoomId(id));
}
Future<List<Map<String, dynamic>>> getStatesFromRoomId(String id) async {
return _db.rawQuery("SELECT * FROM RoomStates WHERE room_id=?", [id]);
}
Future<List<Map<String, dynamic>>> getAccountDataFromRoomId(String id) async {
return _db.rawQuery("SELECT * FROM RoomAccountData WHERE room_id=?", [id]);
}
Future<void> resetNotificationCount(String roomID) async {
await _db.rawDelete(
"UPDATE Rooms SET notification_count=0, highlight_count=0 WHERE room_id=?",
[roomID]);
return;
}
Future<void> forgetRoom(String roomID) async {
await _db.rawDelete("DELETE FROM Rooms WHERE room_id=?", [roomID]);
return;
}
/// Searches for the event in the store.
Future<Event> getEventById(String eventID, Room room) async {
List<Map<String, dynamic>> res = await _db.rawQuery(
"SELECT * FROM Events WHERE event_id=? AND room_id=?",
[eventID, room.id]);
if (res.length == 0) return null;
return Event.fromJson(res[0], room);
}
Future<Map<String, AccountData>> getAccountData() async {
Map<String, AccountData> newAccountData = {};
List<Map<String, dynamic>> rawAccountData =
await _db.rawQuery("SELECT * FROM AccountData");
for (int i = 0; i < rawAccountData.length; i++)
newAccountData[rawAccountData[i]["type"]] =
AccountData.fromJson(rawAccountData[i]);
return newAccountData;
}
Future<Map<String, Presence>> getPresences() async {
Map<String, Presence> newPresences = {};
// TODO: Fix the json parsing of presences
/*List<Map<String, dynamic>> rawPresences =
await _db.rawQuery("SELECT * FROM Presences");
for (int i = 0; i < rawPresences.length; i++)
newPresences[rawPresences[i]["type"]] =
Presence.fromJson(rawPresences[i]);*/
return newPresences;
}
Future removeEvent(String eventId) async {
assert(eventId != "");
await _db.rawDelete("DELETE FROM Events WHERE event_id=?", [eventId]);
return;
}
Future forgetNotification(String roomID) async {
assert(roomID != "");
await _db
.rawDelete("DELETE FROM NotificationsCache WHERE chat_id=?", [roomID]);
return;
}
Future addNotification(String roomID, String event_id, int uniqueID) async {
assert(roomID != "");
assert(event_id != "");
assert(uniqueID != "");
await _db.rawInsert(
"INSERT OR REPLACE INTO NotificationsCache(id, chat_id, event_id) VALUES (?, ?, ?)",
[uniqueID, roomID, event_id]);
// Make sure we got the same unique ID everywhere
await _db.rawUpdate("UPDATE NotificationsCache SET id=? WHERE chat_id=?",
[uniqueID, roomID]);
return;
}
Future<List<Map<String, dynamic>>> getNotificationByRoom(
String room_id) async {
assert(room_id != "");
List<Map<String, dynamic>> res = await _db.rawQuery(
"SELECT * FROM NotificationsCache WHERE chat_id=?", [room_id]);
if (res.length == 0) return null;
return res;
}
static final Map<String, String> schemes = {
/// The database scheme for the Client class.
"Clients": 'CREATE TABLE IF NOT EXISTS Clients(' +
'client TEXT PRIMARY KEY, ' +
'token TEXT, ' +
'homeserver TEXT, ' +
'matrix_id TEXT, ' +
'device_id TEXT, ' +
'device_name TEXT, ' +
'prev_batch TEXT, ' +
'matrix_versions TEXT, ' +
'lazy_load_members INTEGER, ' +
'UNIQUE(client))',
/// The database scheme for the Room class.
'Rooms': 'CREATE TABLE IF NOT EXISTS Rooms(' +
'room_id TEXT PRIMARY KEY, ' +
'membership TEXT, ' +
'highlight_count INTEGER, ' +
'notification_count INTEGER, ' +
'prev_batch TEXT, ' +
'joined_member_count INTEGER, ' +
'invited_member_count INTEGER, ' +
'heroes TEXT, ' +
'UNIQUE(room_id))',
/// The database scheme for the TimelineEvent class.
'Events': 'CREATE TABLE IF NOT EXISTS Events(' +
'event_id TEXT PRIMARY KEY, ' +
'room_id TEXT, ' +
'origin_server_ts INTEGER, ' +
'sender TEXT, ' +
'type TEXT, ' +
'unsigned TEXT, ' +
'content TEXT, ' +
'prev_content TEXT, ' +
'state_key TEXT, ' +
"status INTEGER, " +
'UNIQUE(event_id))',
/// The database scheme for room states.
'RoomStates': 'CREATE TABLE IF NOT EXISTS RoomStates(' +
'event_id TEXT PRIMARY KEY, ' +
'room_id TEXT, ' +
'origin_server_ts INTEGER, ' +
'sender TEXT, ' +
'state_key TEXT, ' +
'unsigned TEXT, ' +
'prev_content TEXT, ' +
'type TEXT, ' +
'content TEXT, ' +
'UNIQUE(room_id,state_key,type))',
/// The database scheme for room states.
'AccountData': 'CREATE TABLE IF NOT EXISTS AccountData(' +
'type TEXT PRIMARY KEY, ' +
'content TEXT, ' +
'UNIQUE(type))',
/// The database scheme for room states.
'RoomAccountData': 'CREATE TABLE IF NOT EXISTS RoomAccountData(' +
'type TEXT PRIMARY KEY, ' +
'room_id TEXT, ' +
'content TEXT, ' +
'UNIQUE(type,room_id))',
/// The database scheme for room states.
'Presences': 'CREATE TABLE IF NOT EXISTS Presences(' +
'type TEXT PRIMARY KEY, ' +
'sender TEXT, ' +
'content TEXT, ' +
'UNIQUE(sender))',
/// The database scheme for the NotificationsCache class.
"NotificationsCache": 'CREATE TABLE IF NOT EXISTS NotificationsCache(' +
'id int, ' +
'chat_id TEXT, ' + // The chat id
'event_id TEXT, ' + // The matrix id of the Event
'UNIQUE(event_id))',
};
}

237
lib/views/chat.dart Normal file
View file

@ -0,0 +1,237 @@
import 'dart:io';
import 'package:famedlysdk/famedlysdk.dart';
import 'package:file_picker/file_picker.dart';
import 'package:fluffychat/components/adaptive_page_layout.dart';
import 'package:fluffychat/components/chat_settings_popup_menu.dart';
import 'package:fluffychat/components/list_items/message.dart';
import 'package:fluffychat/components/matrix.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:toast/toast.dart';
import 'chat_list.dart';
class Chat extends StatefulWidget {
final String id;
const Chat(this.id, {Key key}) : super(key: key);
@override
_ChatState createState() => _ChatState();
}
class _ChatState extends State<Chat> {
Room room;
Timeline timeline;
final ScrollController _scrollController = new ScrollController();
@override
void initState() {
_scrollController.addListener(() async {
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
if (timeline.events.length > 0 &&
timeline.events[timeline.events.length - 1].type !=
EventTypes.RoomCreate) {
await timeline.requestHistory(historyCount: 100);
}
}
});
super.initState();
}
Future<bool> getTimeline() async {
timeline ??= await room.getTimeline(onUpdate: () {
setState(() {});
});
return true;
}
@override
void dispose() {
timeline?.sub?.cancel();
super.dispose();
}
final TextEditingController sendController = TextEditingController();
void send() {
if (sendController.text.isEmpty) return;
room.sendTextEvent(sendController.text);
sendController.text = "";
}
void sendFileAction(BuildContext context) async {
if (kIsWeb) {
return Toast.show("Not supported in web", context);
}
File file = await FilePicker.getFile();
if (file == null) return;
Matrix.of(context).tryRequestWithLoadingDialog(
room.sendFileEvent(
MatrixFile(bytes: await file.readAsBytes(), path: file.path),
),
);
}
void sendImageAction(BuildContext context) async {
if (kIsWeb) {
return Toast.show("Not supported in web", context);
}
File file = await ImagePicker.pickImage(
source: ImageSource.gallery,
imageQuality: 50,
maxWidth: 1600,
maxHeight: 1600);
if (file == null) return;
Matrix.of(context).tryRequestWithLoadingDialog(
room.sendImageEvent(
MatrixFile(bytes: await file.readAsBytes(), path: file.path),
),
);
}
void openCameraAction(BuildContext context) async {
if (kIsWeb) {
return Toast.show("Not supported in web", context);
}
File file = await ImagePicker.pickImage(
source: ImageSource.camera,
imageQuality: 50,
maxWidth: 1600,
maxHeight: 1600);
if (file == null) return;
Matrix.of(context).tryRequestWithLoadingDialog(
room.sendImageEvent(
MatrixFile(bytes: await file.readAsBytes(), path: file.path),
),
);
}
@override
Widget build(BuildContext context) {
Client client = Matrix.of(context).client;
room ??= client.getRoomById(widget.id);
if (room.membership == Membership.invite) room.join();
return AdaptivePageLayout(
primaryPage: FocusPage.SECOND,
firstScaffold: ChatList(
activeChat: widget.id,
),
secondScaffold: Scaffold(
appBar: AppBar(
title: Text(room.displayname),
actions: <Widget>[ChatSettingsPopupMenu(room, !room.isDirectChat)],
),
body: SafeArea(
child: Column(
children: <Widget>[
Expanded(
child: FutureBuilder<bool>(
future: getTimeline(),
builder: (BuildContext context, snapshot) {
if (!snapshot.hasData)
return Center(
child: CircularProgressIndicator(),
);
if (room.notificationCount != null &&
room.notificationCount > 0 &&
timeline != null &&
timeline.events.length > 0)
room.sendReadReceipt(timeline.events[0].eventId);
return ListView.builder(
reverse: true,
itemCount: timeline.events.length,
controller: _scrollController,
itemBuilder: (BuildContext context, int i) =>
Message(timeline.events[i]),
);
},
),
),
Container(
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.2),
spreadRadius: 1,
blurRadius: 2,
offset: Offset(0, -1), // changes position of shadow
),
],
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
kIsWeb
? Container()
: PopupMenuButton<String>(
icon: Icon(Icons.add),
onSelected: (String choice) async {
if (choice == "file")
sendFileAction(context);
else if (choice == "image")
sendImageAction(context);
if (choice == "camera") openCameraAction(context);
},
itemBuilder: (BuildContext context) =>
<PopupMenuEntry<String>>[
const PopupMenuItem<String>(
value: "file",
child: ListTile(
leading: Icon(Icons.attach_file),
title: Text('Send file'),
contentPadding: EdgeInsets.all(0),
),
),
const PopupMenuItem<String>(
value: "image",
child: ListTile(
leading: Icon(Icons.image),
title: Text('Send image'),
contentPadding: EdgeInsets.all(0),
),
),
const PopupMenuItem<String>(
value: "camera",
child: ListTile(
leading: Icon(Icons.camera),
title: Text('Open camera'),
contentPadding: EdgeInsets.all(0),
),
),
],
),
SizedBox(width: 8),
Expanded(
child: TextField(
onSubmitted: (t) => send(),
controller: sendController,
decoration: InputDecoration(
labelText: "Write a message...",
hintText: "You're message",
border: InputBorder.none,
),
)),
SizedBox(width: 8),
IconButton(
icon: Icon(Icons.send),
onPressed: () => send(),
),
],
),
),
],
),
),
),
);
}
}

164
lib/views/chat_details.dart Normal file
View file

@ -0,0 +1,164 @@
import 'dart:io';
import 'package:famedlysdk/famedlysdk.dart';
import 'package:fluffychat/components/adaptive_page_layout.dart';
import 'package:fluffychat/components/chat_settings_popup_menu.dart';
import 'package:fluffychat/components/content_banner.dart';
import 'package:fluffychat/components/list_items/participant_list_item.dart';
import 'package:fluffychat/components/matrix.dart';
import 'package:fluffychat/utils/app_route.dart';
import 'package:fluffychat/views/chat_list.dart';
import 'package:fluffychat/views/invitation_selection.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:toast/toast.dart';
class ChatDetails extends StatefulWidget {
final Room room;
const ChatDetails(this.room);
@override
_ChatDetailsState createState() => _ChatDetailsState();
}
class _ChatDetailsState extends State<ChatDetails> {
List<User> members;
void setDisplaynameAction(BuildContext context, String displayname) async {
final MatrixState matrix = Matrix.of(context);
final Map<String, dynamic> success =
await matrix.tryRequestWithLoadingDialog(
widget.room.setName(displayname),
);
if (success != null && success.length == 0) {
Toast.show(
"Displayname has been changed",
context,
duration: Toast.LENGTH_LONG,
);
}
}
void setAvatarAction(BuildContext context) async {
final File tempFile = await ImagePicker.pickImage(
source: ImageSource.gallery,
imageQuality: 50,
maxWidth: 1600,
maxHeight: 1600);
if (tempFile == null) return;
final MatrixState matrix = Matrix.of(context);
final Map<String, dynamic> success =
await matrix.tryRequestWithLoadingDialog(
widget.room.setAvatar(
MatrixFile(
bytes: await tempFile.readAsBytes(),
path: tempFile.path,
),
),
);
if (success != null && success.length == 0) {
Toast.show(
"Avatar has been changed",
context,
duration: Toast.LENGTH_LONG,
);
}
}
void requestMoreMembersAction(BuildContext context) async {
final List<User> participants = await Matrix.of(context)
.tryRequestWithLoadingDialog(widget.room.requestParticipants());
if (participants != null) setState(() => members = participants);
}
@override
Widget build(BuildContext context) {
members ??= widget.room.getParticipants();
final int actualMembersCount =
widget.room.mInvitedMemberCount + widget.room.mJoinedMemberCount;
final bool canRequestMoreMembers = members.length < actualMembersCount;
widget.room.onUpdate = () => setState(() => members = null);
return AdaptivePageLayout(
primaryPage: FocusPage.SECOND,
firstScaffold: ChatList(
activeChat: widget.room.id,
),
secondScaffold: Scaffold(
appBar: AppBar(
title: Text(widget.room.displayname),
actions: <Widget>[ChatSettingsPopupMenu(widget.room, false)],
),
body: ListView.builder(
itemCount: members.length + 1 + (canRequestMoreMembers ? 1 : 0),
itemBuilder: (BuildContext context, int i) => i == 0
? Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
ContentBanner(widget.room.avatar),
widget.room.canSendEvent("m.room.avatar") && !kIsWeb
? ListTile(
title: Text("Edit group avatar"),
trailing: Icon(Icons.file_upload),
onTap: () => setAvatarAction(context),
)
: Container(),
widget.room.canSendEvent("m.room.name")
? ListTile(
trailing: Icon(Icons.edit),
title: TextField(
textInputAction: TextInputAction.done,
onSubmitted: (s) =>
setDisplaynameAction(context, s),
decoration: InputDecoration(
border: InputBorder.none,
labelText: "Edit group name",
labelStyle: TextStyle(color: Colors.black),
hintText: (widget.room.displayname),
),
),
)
: Container(),
Row(
children: <Widget>[
Expanded(
child: Container(height: 8, color: Color(0xFFF8F8F8)),
),
SizedBox(width: 8),
Text(
"$actualMembersCount participant(s)",
style: TextStyle(
fontSize: 15,
),
),
SizedBox(width: 8),
Expanded(
child: Container(height: 8, color: Color(0xFFF8F8F8)),
),
],
),
ListTile(
title: Text("Invite contact"),
leading: Icon(Icons.add),
onTap: () => Navigator.of(context).push(
AppRoute.defaultRoute(
context,
InvitationSelection(widget.room),
),
),
),
],
)
: i < members.length + 1
? ParticipantListItem(members[i - 1])
: ListTile(
title: Text(
"Load more ${actualMembersCount - members.length} participants"),
leading: Icon(Icons.refresh),
onTap: () => requestMoreMembersAction(context),
),
),
),
);
}
}

135
lib/views/chat_list.dart Normal file
View file

@ -0,0 +1,135 @@
import 'package:famedlysdk/famedlysdk.dart';
import 'package:fluffychat/components/adaptive_page_layout.dart';
import 'package:fluffychat/components/dialogs/new_group_dialog.dart';
import 'package:fluffychat/components/dialogs/new_private_chat_dialog.dart';
import 'package:fluffychat/components/list_items/chat_list_item.dart';
import 'package:fluffychat/components/matrix.dart';
import 'package:fluffychat/utils/app_route.dart';
import 'package:fluffychat/views/settings.dart';
import 'package:flutter/material.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';
class ChatListView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return AdaptivePageLayout(
primaryPage: FocusPage.FIRST,
firstScaffold: ChatList(),
secondScaffold: Scaffold(
body: Center(
child: Icon(Icons.chat, size: 100, color: Color(0xFF5625BA)),
),
),
);
}
}
class ChatList extends StatefulWidget {
final String activeChat;
const ChatList({this.activeChat, Key key}) : super(key: key);
@override
_ChatListState createState() => _ChatListState();
}
class _ChatListState extends State<ChatList> {
RoomList roomList;
Future<List<Room>> getRooms(BuildContext context) async {
Client client = Matrix.of(context).client;
if (roomList != null) return roomList.rooms;
if (client.prevBatch?.isEmpty ?? true)
await client.connection.onFirstSync.stream.first;
roomList = client.getRoomList(onUpdate: () {
setState(() {});
});
return roomList.rooms;
}
@override
void dispose() {
roomList?.eventSub?.cancel();
roomList?.firstSyncSub?.cancel();
roomList?.roomSub?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
"Conversations",
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
onPressed: () {},
),
PopupMenuButton(
onSelected: (String choice) {
switch (choice) {
case "settings":
Navigator.of(context).push(
AppRoute.defaultRoute(
context,
SettingsView(),
),
);
}
},
itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
value: "settings",
child: Text('Settings'),
),
],
),
],
),
floatingActionButton: SpeedDial(
child: Icon(Icons.add),
backgroundColor: Color(0xFF5625BA),
children: [
SpeedDialChild(
child: Icon(Icons.people_outline),
backgroundColor: Colors.blue,
label: 'Create new group',
labelStyle: TextStyle(fontSize: 18.0),
onTap: () => showDialog(
context: context,
builder: (BuildContext innerContext) => NewGroupDialog(),
),
),
SpeedDialChild(
child: Icon(Icons.chat_bubble_outline),
backgroundColor: Colors.green,
label: 'New private chat',
labelStyle: TextStyle(fontSize: 18.0),
onTap: () => showDialog(
context: context,
builder: (BuildContext innerContext) => NewPrivateChatDialog()),
),
],
),
body: FutureBuilder<List<Room>>(
future: getRooms(context),
builder: (BuildContext context, snapshot) {
if (snapshot.hasData) {
List<Room> rooms = snapshot.data;
return ListView.builder(
itemCount: rooms.length,
itemBuilder: (BuildContext context, int i) => ChatListItem(
rooms[i],
activeChat: widget.activeChat == rooms[i].id,
),
);
} else
return Center(
child: CircularProgressIndicator(),
);
},
),
);
}
}

View file

@ -0,0 +1,74 @@
import 'package:famedlysdk/famedlysdk.dart';
import 'package:fluffychat/components/adaptive_page_layout.dart';
import 'package:fluffychat/components/avatar.dart';
import 'package:fluffychat/components/matrix.dart';
import 'package:flutter/material.dart';
import 'package:toast/toast.dart';
import 'chat_list.dart';
class InvitationSelection extends StatelessWidget {
final Room room;
const InvitationSelection(this.room, {Key key}) : super(key: key);
Future<List<User>> getContacts(BuildContext context) async {
final Client client = Matrix.of(context).client;
List<User> participants = await room.requestParticipants();
List<User> contacts = [];
Map<String, bool> userMap = {};
for (int i = 0; i < client.roomList.rooms.length; i++) {
List<User> roomUsers = client.roomList.rooms[i].getParticipants();
for (int j = 0; j < roomUsers.length; j++) {
if (userMap[roomUsers[j].id] != true &&
participants.indexWhere((u) => u.id == roomUsers[j].id) == -1)
contacts.add(roomUsers[j]);
userMap[roomUsers[j].id] = true;
}
}
return contacts;
}
void inviteAction(BuildContext context, String id) async {
final success = await Matrix.of(context).tryRequestWithLoadingDialog(
room.invite(id),
);
if (success != false)
Toast.show(
"Contact has been invited to the group.",
context,
duration: Toast.LENGTH_LONG,
);
}
@override
Widget build(BuildContext context) {
final String groupName = room.name?.isEmpty ?? false ? "group" : room.name;
return AdaptivePageLayout(
primaryPage: FocusPage.SECOND,
firstScaffold: ChatList(activeChat: room.id),
secondScaffold: Scaffold(
appBar: AppBar(
title: Text("Invite contact to $groupName"),
),
body: FutureBuilder<List<User>>(
future: getContacts(context),
builder: (BuildContext context, snapshot) {
if (!snapshot.hasData)
return Center(
child: CircularProgressIndicator(),
);
List<User> contacts = snapshot.data;
return ListView.builder(
itemCount: contacts.length,
itemBuilder: (BuildContext context, int i) => ListTile(
leading: Avatar(contacts[i].avatarUrl),
title: Text(contacts[i].calcDisplayname()),
subtitle: Text(contacts[i].id),
onTap: () => inviteAction(context, contacts[i].id),
),
);
},
)),
);
}
}

144
lib/views/login.dart Normal file
View file

@ -0,0 +1,144 @@
import 'dart:math';
import 'package:famedlysdk/famedlysdk.dart';
import 'package:fluffychat/components/matrix.dart';
import 'package:flutter/material.dart';
const String defaultHomeserver = "https://matrix.org";
class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final TextEditingController usernameController = TextEditingController();
final TextEditingController passwordController = TextEditingController();
final TextEditingController serverController =
TextEditingController(text: "matrix.org");
String usernameError;
String passwordError;
String serverError;
void login(BuildContext context) async {
MatrixState matrix = Matrix.of(context);
if (usernameController.text.isEmpty) {
setState(() => usernameError = "Please enter your username.");
print("Please enter your username.");
} else {
setState(() => usernameError = null);
}
if (passwordController.text.isEmpty) {
setState(() => passwordError = "Please enter your password.");
} else {
setState(() => passwordError = null);
}
serverError = null;
if (usernameController.text.isEmpty || passwordController.text.isEmpty)
return;
String homeserver = serverController.text;
if (homeserver.isEmpty) homeserver = defaultHomeserver;
if (!homeserver.startsWith("https://"))
homeserver = "https://" + homeserver;
try {
matrix.showLoadingDialog(context);
if (!await matrix.client.checkServer(homeserver)) {
setState(() => serverError = "Homeserver is not compatible.");
return matrix.hideLoadingDialog();
}
} catch (exception) {
setState(() => serverError = "Connection attempt failed!");
return matrix.hideLoadingDialog();
}
try {
await matrix.client
.login(usernameController.text, passwordController.text);
} on MatrixException catch (exception) {
setState(() => passwordError = exception.errorMessage);
return matrix.hideLoadingDialog();
} catch (exception) {
setState(() => passwordError = exception.toString());
return matrix.hideLoadingDialog();
}
Matrix.of(context).saveAccount();
matrix.hideLoadingDialog();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: TextField(
controller: serverController,
decoration: InputDecoration(
icon: Icon(Icons.domain),
hintText: "matrix.org",
errorText: serverError,
errorMaxLines: 1,
prefixText: "https://",
labelText: serverError == null ? "Homeserver" : serverError),
),
),
body: ListView(
padding: EdgeInsets.symmetric(
vertical: 16,
horizontal: max((MediaQuery.of(context).size.width - 600) / 2, 16)),
children: <Widget>[
Image.asset("assets/fluffychat-banner.png"),
TextField(
controller: usernameController,
decoration: InputDecoration(
hintText: "@username:domain",
icon: Icon(Icons.account_box),
errorText: usernameError,
labelText: "Username"),
),
TextField(
controller: passwordController,
obscureText: true,
onSubmitted: (t) => login(context),
decoration: InputDecoration(
icon: Icon(Icons.vpn_key),
hintText: "****",
errorText: passwordError,
labelText: "Password"),
),
SizedBox(height: 20),
Card(
elevation: 7,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50),
),
child: Container(
width: 120.0,
height: 50.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
gradient: LinearGradient(
begin: Alignment.bottomLeft,
end: Alignment.topRight,
colors: <Color>[
Colors.blue,
Color(0xFF5625BA),
],
),
),
child: RawMaterialButton(
onPressed: () => login(context),
splashColor: Colors.grey,
child: Text(
"Login",
style: TextStyle(color: Colors.white, fontSize: 20.0),
),
),
),
),
],
),
);
}
}

141
lib/views/settings.dart Normal file
View file

@ -0,0 +1,141 @@
import 'dart:io';
import 'package:famedlysdk/famedlysdk.dart';
import 'package:fluffychat/components/adaptive_page_layout.dart';
import 'package:fluffychat/components/content_banner.dart';
import 'package:fluffychat/components/matrix.dart';
import 'package:fluffychat/utils/app_route.dart';
import 'package:fluffychat/views/chat_list.dart';
import 'package:fluffychat/views/login.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:toast/toast.dart';
class SettingsView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return AdaptivePageLayout(
primaryPage: FocusPage.SECOND,
firstScaffold: ChatList(),
secondScaffold: Settings(),
);
}
}
class Settings extends StatefulWidget {
@override
_SettingsState createState() => _SettingsState();
}
class _SettingsState extends State<Settings> {
Future<dynamic> profileFuture;
dynamic profile;
void logoutAction(BuildContext context) async {
MatrixState matrix = Matrix.of(context);
Navigator.of(context).pushAndRemoveUntil(
AppRoute.defaultRoute(context, LoginPage()), (r) => false);
await matrix.tryRequestWithLoadingDialog(matrix.client.logout());
matrix.clean();
}
void setDisplaynameAction(BuildContext context, String displayname) async {
final MatrixState matrix = Matrix.of(context);
final Map<String, dynamic> success =
await matrix.tryRequestWithLoadingDialog(
matrix.client.connection.jsonRequest(
type: HTTPType.PUT,
action: "/client/r0/profile/${matrix.client.userID}/displayname",
data: {"displayname": displayname},
),
);
if (success != null && success.length == 0) {
Toast.show(
"Displayname has been changed",
context,
duration: Toast.LENGTH_LONG,
);
setState(() {
profileFuture = null;
profile = null;
});
}
}
void setAvatarAction(BuildContext context) async {
final File tempFile = await ImagePicker.pickImage(
source: ImageSource.gallery,
imageQuality: 50,
maxWidth: 1600,
maxHeight: 1600);
if (tempFile == null) return;
final MatrixState matrix = Matrix.of(context);
final Map<String, dynamic> success =
await matrix.tryRequestWithLoadingDialog(
matrix.client.setAvatar(
MatrixFile(
bytes: await tempFile.readAsBytes(),
path: tempFile.path,
),
),
);
if (success != null && success.length == 0) {
Toast.show(
"Avatar has been changed",
context,
duration: Toast.LENGTH_LONG,
);
setState(() {
profileFuture = null;
profile = null;
});
}
}
@override
Widget build(BuildContext context) {
final Client client = Matrix.of(context).client;
profileFuture ??= client.getProfileFromUserId(client.userID);
profileFuture.then((p) => setState(() => profile = p));
return Scaffold(
appBar: AppBar(
title: Text("Settings"),
),
body: ListView(
children: <Widget>[
ContentBanner(
profile?.avatarUrl ?? MxContent(""),
defaultIcon: Icons.account_circle,
loading: profile == null,
),
kIsWeb
? Container()
: ListTile(
title: Text("Upload avatar"),
trailing: Icon(Icons.file_upload),
onTap: () => setAvatarAction(context),
),
ListTile(
trailing: Icon(Icons.edit),
title: TextField(
readOnly: profile == null,
textInputAction: TextInputAction.done,
onSubmitted: (s) => setDisplaynameAction(context, s),
decoration: InputDecoration(
border: InputBorder.none,
labelText: "Edit displayname",
labelStyle: TextStyle(color: Colors.black),
hintText: (profile?.displayname ?? ""),
),
),
),
ListTile(
trailing: Icon(Icons.exit_to_app),
title: Text("Logout"),
onTap: () => logoutAction(context),
),
],
),
);
}
}