diff --git a/lib/main.dart b/lib/main.dart index eff95aa..ac86b4b 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -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 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( - onGenerateRoute: generateRoute, - initialRoute: '/', - ), + return MaterialApp( + onGenerateRoute: generateRoute, + initialRoute: '/', ); } } + + diff --git a/lib/p2p/MatrixServerModel.dart b/lib/p2p/MatrixServerModel.dart deleted file mode 100644 index cef1387..0000000 --- a/lib/p2p/MatrixServerModel.dart +++ /dev/null @@ -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 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 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> getContactsList() async { - var roomData = await server.getJoinedRooms(); - List contacts = roomData.map((e) { - Map 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; - } -} diff --git a/lib/pages/ChatListScreen.dart b/lib/pages/ChatListScreen.dart index f8c7708..b97effd 100644 --- a/lib/pages/ChatListScreen.dart +++ b/lib/pages/ChatListScreen.dart @@ -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 { bool isLoading = false; - List conversers = []; + List 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 { @override Widget build(BuildContext context) { - var server = context.watch(); - Future 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 { }, child: Column( children: [ - Text(conversers[index].displayName), + Text(conversers[index]), ], crossAxisAlignment: CrossAxisAlignment.start, ), diff --git a/lib/pages/ChatPage.dart b/lib/pages/ChatPage.dart index 7ae1ef1..a21e6ed 100644 --- a/lib/pages/ChatPage.dart +++ b/lib/pages/ChatPage.dart @@ -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 { ScrollController _scrollController = new ScrollController(); Widget build(BuildContext context) { - var server = context.watch(); - 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,43 +48,40 @@ class _ChatPageState extends State { children: [ Container( height: MediaQuery.of(context).size.height * .8, - 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, - itemBuilder: (BuildContext context, int index) { - return Container( - height: 55, - child: messageList[index].msgtype == 'sent' - ? Bubble( - margin: BubbleEdges.only(top: 10), - nip: BubbleNip.rightTop, - color: Color(0xffd1c4e9), - child: Text( - messageList[index].msgtype + - ": " + - messageList[index].message, - textAlign: TextAlign.right), - ) - : Bubble( - nip: BubbleNip.leftTop, - color: Color(0xff80DEEA), - margin: BubbleEdges.only(top: 10), - child: Text( - messageList[index].msgtype + - ": " + - messageList[index].message, - ), - ), - ); - }, - ), + 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, + itemBuilder: (BuildContext context, int index) { + return Container( + height: 55, + child: messageList[index].msgtype == 'sent' + ? Bubble( + margin: BubbleEdges.only(top: 10), + nip: BubbleNip.rightTop, + color: Color(0xffd1c4e9), + child: Text( + messageList[index].msgtype + + ": " + + messageList[index].message, + textAlign: TextAlign.right), + ) + : Bubble( + nip: BubbleNip.leftTop, + color: Color(0xff80DEEA), + margin: BubbleEdges.only(top: 10), + child: Text( + messageList[index].msgtype + + ": " + + messageList[index].message, + ), + ), + ); + }, + ), ), TextFormField( controller: myController, @@ -124,15 +92,10 @@ class _ChatPageState extends State { ), ), 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,40 +103,37 @@ class _ChatPageState extends State { "type": "Payload" }; var Mesagedata = data.toString(); - try { - Global.cache[msgId] = Payload( - msgId, - Global.myName, - widget.converser.displayName, - myController.text, - DateTime.now().toUtc().toString()); - insertIntoMessageTable(Payload( - msgId, - Global.myName, - widget.converser.displayName, - myController.text, - DateTime.now().toUtc().toString())); - // Global.devices.forEach((element) { - // Global.nearbyService! - // .sendMessage(element.deviceId, Mesagedata); - // }); - // 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.cache[msgId] = Payload( + msgId, + Global.myName, + widget.converser, + myController.text, + DateTime.now().toUtc().toString()); + insertIntoMessageTable(Payload( + msgId, + Global.myName, + widget.converser, + myController.text, + DateTime.now().toUtc().toString())); + // Global.devices.forEach((element) { + // Global.nearbyService! + // .sendMessage(element.deviceId, Mesagedata); + // }); + // Global.nearbyService! + // .sendMessage(widget.device.deviceId, myController.text); + setState(() { + // Global + // .conversations[widget.device.deviceName][msgId](new Msg(widget.device.deviceId, + // myController.text, "sent")); + 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")), ], diff --git a/lib/pages/DeviceListScreen.dart b/lib/pages/DeviceListScreen.dart index bd2daa5..681f3ab 100644 --- a/lib/pages/DeviceListScreen.dart +++ b/lib/pages/DeviceListScreen.dart @@ -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'; @@ -35,9 +34,8 @@ class _DevicesListScreenState extends State { super.initState(); init(); refreshMessages(); - print(" 37 reloaded:" + Global.cache.toString()); + print(" 37 reloaded:"+ Global.cache.toString()); } - Future refreshMessages() async { setState(() => isLoading = true); @@ -54,27 +52,24 @@ class _DevicesListScreenState extends State { Global.nearbyService!.stopAdvertisingPeer(); super.dispose(); } - var _selectedIndex = 0; Widget getBody(BuildContext context) { switch (_selectedIndex) { case 0: - // return showTrips(context); + // return showTrips(context); case 1: - // return search(widget.account); + // return search(widget.account); case 2: return Text('Not yet implemented!'); default: throw UnimplementedError(); } } - void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); } - @override Widget build(BuildContext context) { return Scaffold( @@ -96,6 +91,7 @@ class _DevicesListScreenState extends State { BottomNavigationBarItem( icon: Icon(Icons.group_work), title: Text("Available"), + ), BottomNavigationBarItem( icon: Icon(Icons.account_box), @@ -145,7 +141,7 @@ class _DevicesListScreenState extends State { Navigator.of(context).push( MaterialPageRoute( builder: (context) { - return ChatPage(Contact(device.deviceName)); + return ChatPage(device.deviceName); }, ), ); @@ -298,17 +294,11 @@ class _DevicesListScreenState extends State { Global.myName.toString()); if (temp2['type'] == "Payload" && temp2['receiver'] == Global.myName) { // Global.cache[temp2["id"]]!.broadcast = false; - 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']); + 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']); if (Global.cache[temp2["id"]] == null) { Global.cache[temp2["id"]] = Ack(temp2["id"]); print("280 test"); diff --git a/lib/pages/Profile.dart b/lib/pages/Profile.dart index 757d777..6b4348d 100644 --- a/lib/pages/Profile.dart +++ b/lib/pages/Profile.dart @@ -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(); - 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 { - // 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( + ElevatedButton(onPressed: () { + // Global.myName = myName.text+custom_length_id; + 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")) ], ), ), diff --git a/pubspec.yaml b/pubspec.yaml index cadd15e..bb050b7 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -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,13 +19,11 @@ 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: sdk: flutter flutter: - uses-material-design: true + uses-material-design: true \ No newline at end of file