Revert "Merge branch 'matrix-chat' into 'gsoc-2021'"

This reverts merge request !11
This commit is contained in:
Thuvarakan Tharmarajasingam
2021-08-23 14:03:46 +00:00
parent d5637fd6a6
commit d41a572888
7 changed files with 109 additions and 298 deletions

View File

@ -1,26 +1,27 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'pages/Profile.dart';
import 'p2p/MatrixServerModel.dart';
import 'package:flutter/material.dart';
import 'pages/Profile.dart';
void main() {
runApp(MyApp());
}
Route<dynamic> generateRoute(RouteSettings settings) {
return MaterialPageRoute(builder: (_) => Profile());
return MaterialPageRoute(
builder: (_) => Profile());
}
class MyApp extends StatelessWidget {
void initState() {}
void initState(){
}
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [ChangeNotifierProvider(create: (_) => MatrixServer())],
child: const MaterialApp(
return MaterialApp(
onGenerateRoute: generateRoute,
initialRoute: '/',
),
);
}
}

View File

@ -1,61 +0,0 @@
import 'package:flutter/foundation.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:p2p_client_dart/p2p_client_dart.dart';
class Contact {
String displayName;
String? roomId;
String? userId;
Contact(this.displayName);
@override
String toString() {
return displayName;
}
Contact.fromJson(Map<String, String> json)
: displayName = json['displayName']!,
roomId = json['roomId'],
userId = json['userId'];
}
class MatrixServer extends ChangeNotifier {
Server _server = Server();
Server get server => _server;
@override
String toString() {
return 'Matrix Server - ${server.toString()}';
}
set server(Server newServer) {
this._server = newServer;
notifyListeners();
}
Future<void> setServerConfig(
String url, String name, String? username, String? password) async {
this._server = server = Server.init(url, name);
if (username != null && password != null) {
await this._server.login(username, password);
print(this._server.isAuthenticated);
}
}
Future<List<Contact>> getContactsList() async {
var roomData = await server.getJoinedRooms();
List<Contact> contacts = roomData.map((e) {
Map<String, String> contact = {};
e.retainWhere((e) => e.senderId != server.userId);
if (e.length == 0) return Contact("None");
contact["roomId"] = e[0].roomId;
contact["userId"] = e[0].senderId;
contact["displayName"] = e[0].content['displayname'];
return Contact.fromJson(contact);
}).toList();
contacts.retainWhere((element) => element.displayName != "None");
return contacts;
}
}

View File

@ -1,8 +1,6 @@
import 'package:flutter_nearby_connections_example/database/DatabaseHelper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nearby_connections_example/p2p/MatrixServerModel.dart';
import 'package:provider/provider.dart';
import '../classes/Global.dart';
@ -15,15 +13,15 @@ class ChatListScreen extends StatefulWidget {
class _ChatListScreenState extends State<ChatListScreen> {
bool isLoading = false;
List<Contact> conversers = [];
List<String> conversers = [];
@override
void initState() {
super.initState();
refreshMessages();
// Global.conversations.forEach((key, value) {
// conversers.add(key);
// });
Global.conversations.forEach((key, value) {
conversers.add(key);
});
print(" 37 reloaded:" + Global.cache.toString());
}
@ -38,15 +36,6 @@ class _ChatListScreenState extends State<ChatListScreen> {
@override
Widget build(BuildContext context) {
var server = context.watch<MatrixServer>();
Future<void> getContacts() async {
var contacts = await server.getContactsList();
setState(() {
conversers = contacts;
});
}
getContacts();
return Scaffold(
appBar: AppBar(
title: Text("Chats"),
@ -119,7 +108,7 @@ class _ChatListScreenState extends State<ChatListScreen> {
},
child: Column(
children: [
Text(conversers[index].displayName),
Text(conversers[index]),
],
crossAxisAlignment: CrossAxisAlignment.start,
),

View File

@ -1,13 +1,10 @@
import 'package:bubble/bubble.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_nearby_connections/flutter_nearby_connections.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_nearby_connections_example/classes/Payload.dart';
import 'package:nanoid/nanoid.dart';
import 'package:intl/intl.dart';
import 'package:flutter_nearby_connections_example/p2p/MatrixServerModel.dart';
import '../database/DatabaseHelper.dart';
import '../classes/Msg.dart';
@ -16,7 +13,7 @@ import '../classes/Global.dart';
class ChatPage extends StatefulWidget {
ChatPage(this.converser);
final Contact converser;
final String converser;
@override
_ChatPageState createState() => _ChatPageState();
@ -36,37 +33,11 @@ class _ChatPageState extends State<ChatPage> {
ScrollController _scrollController = new ScrollController();
Widget build(BuildContext context) {
var server = context.watch<MatrixServer>();
server.server.onEvent((data) {
print('data: ${data.content['type']}');
if (data.content['type'] == 'm.room.message') {
print('data: ${data.content['sender']}');
print(
'bool: ${(data.content['sender'] as String).contains(widget.converser.userId!)}');
// assuming only text will be send for now
if ((data.content['sender'] as String)
.contains(widget.converser.userId!)) {
// save to db
String msg = data.content['content']['body'];
String sender = widget.converser.userId!;
String timestamp = DateTime.now().toUtc().toString();
print('data: ${msg}');
var msgId = nanoid(21);
setState(() {
Global.conversations[widget.converser]!
.add({msgId: Msg(msg, "received", timestamp, msgId)});
insertIntoConversationsTable(Msg(msg, "received", timestamp, msgId),
widget.converser.userId!);
});
}
}
});
final myController = TextEditingController();
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
title: Text('Chat with ' + widget.converser.displayName),
title: Text('Chat with ' + widget.converser),
),
body: SingleChildScrollView(
reverse: true,
@ -77,16 +48,13 @@ class _ChatPageState extends State<ChatPage> {
children: [
Container(
height: MediaQuery.of(context).size.height * .8,
child: Global.conversations[widget.converser] == null
? Text("no messages")
: ListView.builder(
child:Global.conversations[widget.converser]==null? Text("no messages"): ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
// reverse: true,
controller: _scrollController,
padding: const EdgeInsets.all(8),
itemCount:
messageList == null ? 0 : messageList.length,
itemCount: messageList == null ? 0 : messageList.length,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 55,
@ -124,15 +92,10 @@ class _ChatPageState extends State<ChatPage> {
),
),
ElevatedButton(
onPressed: () async {
var message = await server.server.sendMessage(
widget.converser.userId!, myController.text,
roomId: widget.converser.roomId!);
print("message send to ${widget.converser.roomId!}");
print("message: $message");
onPressed: () {
var msgId = nanoid(21);
var data = {
"sender": "${Global.myName}",
"sender": "$Global.myName",
"receiver": "$widget.device.deviceName",
"message": "$myController.text",
"id": "$msgId",
@ -140,17 +103,16 @@ class _ChatPageState extends State<ChatPage> {
"type": "Payload"
};
var Mesagedata = data.toString();
try {
Global.cache[msgId] = Payload(
msgId,
Global.myName,
widget.converser.displayName,
widget.converser,
myController.text,
DateTime.now().toUtc().toString());
insertIntoMessageTable(Payload(
msgId,
Global.myName,
widget.converser.displayName,
widget.converser,
myController.text,
DateTime.now().toUtc().toString()));
// Global.devices.forEach((element) {
@ -159,21 +121,19 @@ class _ChatPageState extends State<ChatPage> {
// });
// Global.nearbyService!
// .sendMessage(widget.device.deviceId, myController.text);
} finally {
setState(() {
// Global
// .conversations[widget.device.deviceName][msgId](new Msg(widget.device.deviceId,
// myController.text, "sent"));
Msg msg = Msg(myController.text, "sent",
data["Timestamp"]!, msgId);
Global.conversations[widget.converser]!
.add({msgId: msg});
messageList.add(msg);
insertIntoConversationsTable(
msg, widget.converser.displayName);
Global.conversations[widget.converser]!.add({
msgId: Msg(myController.text, "sent",
data["Timestamp"]!, msgId)
});
insertIntoConversationsTable(
Msg(myController.text, "sent", data["Timestamp"]!,
msgId),
widget.converser);
});
}
},
child: Text("send")),
],

View File

@ -7,7 +7,6 @@ import 'package:flutter_nearby_connections_example/classes/Payload.dart';
import 'package:flutter_styled_toast/flutter_styled_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nearby_connections/flutter_nearby_connections.dart';
import 'package:flutter_nearby_connections_example/p2p/MatrixServerModel.dart';
import '../classes/Global.dart';
import '../classes/Msg.dart';
@ -37,7 +36,6 @@ class _DevicesListScreenState extends State<DevicesListScreen> {
refreshMessages();
print(" 37 reloaded:"+ Global.cache.toString());
}
Future refreshMessages() async {
setState(() => isLoading = true);
@ -54,7 +52,6 @@ class _DevicesListScreenState extends State<DevicesListScreen> {
Global.nearbyService!.stopAdvertisingPeer();
super.dispose();
}
var _selectedIndex = 0;
Widget getBody(BuildContext context) {
switch (_selectedIndex) {
@ -68,13 +65,11 @@ class _DevicesListScreenState extends State<DevicesListScreen> {
throw UnimplementedError();
}
}
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
@ -96,6 +91,7 @@ class _DevicesListScreenState extends State<DevicesListScreen> {
BottomNavigationBarItem(
icon: Icon(Icons.group_work),
title: Text("Available"),
),
BottomNavigationBarItem(
icon: Icon(Icons.account_box),
@ -145,7 +141,7 @@ class _DevicesListScreenState extends State<DevicesListScreen> {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) {
return ChatPage(Contact(device.deviceName));
return ChatPage(device.deviceName);
},
),
);
@ -301,14 +297,8 @@ class _DevicesListScreenState extends State<DevicesListScreen> {
if (Global.conversations[ temp2['sender']]== null) {
Global.conversations[ temp2['sender']]= [];
}
Global.conversations[temp2['sender']]!.add({
temp2["id"]: Msg(
temp2['message'], "received", temp2['Timestamp'], temp2["id"])
});
insertIntoConversationsTable(
Msg(temp2['message'], "received", temp2['Timestamp'],
temp2["id"]),
temp2['sender']);
Global.conversations[ temp2['sender']]!.add({temp2["id"]:Msg(temp2['message'],"received",temp2['Timestamp'],temp2["id"])});
insertIntoConversationsTable(Msg(temp2['message'],"received",temp2['Timestamp'],temp2["id"]), temp2['sender']);
if (Global.cache[temp2["id"]] == null) {
Global.cache[temp2["id"]] = Ack(temp2["id"]);
print("280 test");

View File

@ -1,20 +1,13 @@
import 'package:flutter/material.dart';
import 'package:flutter_nearby_connections_example/pages/ChatListScreen.dart';
import 'package:provider/provider.dart';
import 'package:flutter_nearby_connections_example/p2p/MatrixServerModel.dart';
import 'package:flutter_nearby_connections_example/pages/DeviceListScreen.dart';
import 'package:nanoid/nanoid.dart';
import '../classes/Global.dart';
import 'DeviceListScreen.dart';
class Profile extends StatelessWidget {
TextEditingController myName = TextEditingController();
TextEditingController serverUrl = TextEditingController();
TextEditingController userName = TextEditingController();
TextEditingController password = TextEditingController();
var custom_length_id = nanoid(6);
@override
Widget build(BuildContext context) {
var server = context.watch<MatrixServer>();
print('server ${server.toString()}');
return Scaffold(
body: Center(
child: Column(
@ -40,76 +33,17 @@ class Profile extends StatelessWidget {
: null;
},
),
TextFormField(
controller: serverUrl,
decoration: const InputDecoration(
icon: Icon(Icons.circle_rounded),
hintText: 'Server you wish to connect to',
labelText: 'Server Url *',
),
onSaved: (String? value) {
// This optional block of code can be used to run
// code when the user saves the form.
},
// validator: (String? value) {
// return (value != null && value.contains('@'))
// ? 'Do not use the @ char.'
// : null;
// },
),
TextFormField(
controller: userName,
decoration: const InputDecoration(
icon: Icon(Icons.person_add),
hintText: 'Enter you matrix username?',
labelText: 'Username *',
),
onSaved: (String? value) {
// This optional block of code can be used to run
// code when the user saves the form.
},
// validator: (String? value) {
// return (value != null && value.contains('@'))
// ? 'Do not use the @ char.'
// : null;
// },
),
TextFormField(
controller: password,
obscureText: true,
decoration: const InputDecoration(
icon: Icon(Icons.password),
hintText: 'Enter you matrix password?',
labelText: 'Password *',
),
onSaved: (String? value) {
// This optional block of code can be used to run
// code when the user saves the form.
},
// validator: (String? value) {
// return (value != null && value.contains('@'))
// ? 'Do not use the @ char.'
// : null;
// },
),
SizedBox(
height: 20,
),
ElevatedButton(
onPressed: () async {
ElevatedButton(onPressed: () {
// Global.myName = myName.text+custom_length_id;
await server.setServerConfig(
serverUrl.text, myName.text, userName.text, password.text);
Global.myName = myName.text;
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => ChatListScreen(),
// DevicesListScreen(deviceType: DeviceType.browser),
),
);
},
child: Text("Save"),
)
builder: (_) => DevicesListScreen(deviceType: DeviceType.browser)));
}, child: Text("Save"))
],
),
),

View File

@ -3,10 +3,10 @@ description: Demonstrates how to use the flutter_nearby_connections plugin.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: "none" # Remove this line if you wish to publish to pub.dev
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
environment:
sdk: ">=2.12.0 <3.0.0"
sdk: '>=2.12.0 <3.0.0'
dependencies:
flutter:
@ -19,9 +19,7 @@ dependencies:
nanoid: ^1.0.0
sqflite: ^2.0.0+3
intl: ^0.17.0
p2p_client_dart:
path: ../p2p-client/p2p-client-dart
provider: ^5.0.0
dev_dependencies:
flutter_test: