Browse Source

fix chat service

pull/18/head
Sun 3 years ago
parent
commit
35c9cfcd05
  1. 6
      lib/account.dart
  2. 64
      lib/apps/chat/add.dart
  3. 11
      lib/apps/chat/detail.dart
  4. 52
      lib/apps/chat/models.dart
  5. 15
      lib/apps/device/page.dart
  6. 3
      lib/apps/group/detail.dart
  7. 2
      lib/apps/group/models.dart
  8. 2
      lib/apps/jarvis/detail.dart
  9. 14
      lib/apps/primitives.dart
  10. 8
      lib/apps/wallet/page.dart
  11. 31
      lib/global.dart
  12. 19
      lib/pages/account_quick.dart
  13. 2
      lib/pages/account_restore.dart
  14. 26
      lib/pages/home.dart
  15. 2
      lib/pages/setting/network.dart
  16. 15
      lib/pages/setting/profile.dart
  17. 76
      lib/provider.dart
  18. 24
      lib/security.dart
  19. 16
      lib/session.dart
  20. 20
      lib/utils/better_print.dart
  21. 36
      lib/utils/logined_cache.dart
  22. 18
      lib/widgets/chat_message.dart
  23. 4
      lib/widgets/show_contact.dart
  24. 6
      lib/widgets/show_pin.dart
  25. 4
      lib/widgets/transfer.dart
  26. 44
      lib/widgets/user_info.dart
  27. 3
      src/apps.rs
  28. 1
      src/apps/chat/models/friend.rs
  29. 3
      src/apps/chat/models/request.rs
  30. 5
      src/apps/chat/rpc.rs
  31. 21
      src/layer.rs
  32. 3
      src/migrate/session.rs
  33. 9
      src/rpc.rs
  34. 16
      src/server.rs
  35. 42
      src/session.rs
  36. 20
      src/storage.rs

6
lib/account.dart

@ -124,15 +124,15 @@ extension LanguageExtension on Language {
} }
class Account { class Account {
String gid = ''; String pid = '';
String name = ''; String name = '';
Uint8List? avatar; Uint8List? avatar;
bool online = false; bool online = false;
bool hasNew = false; bool hasNew = false;
String pin = ''; String pin = '';
Account(String gid, String name, [String avatar = "", bool online = false]) { Account(String pid, String name, [String avatar = "", bool online = false]) {
this.gid = gid; this.pid = pid;
this.name = name; this.name = name;
this.updateAvatar(avatar); this.updateAvatar(avatar);
this.online = online; this.online = online;

64
lib/apps/chat/add.dart

@ -26,9 +26,8 @@ import 'package:esse/apps/domain/models.dart';
class ChatAdd extends StatefulWidget { class ChatAdd extends StatefulWidget {
final String id; final String id;
final String addr;
final String name; final String name;
ChatAdd({Key? key, this.id = '', this.addr = '', this.name = ''}) : super(key: key); ChatAdd({Key? key, this.id = '', this.name = ''}) : super(key: key);
@override @override
_ChatAddState createState() => _ChatAddState(); _ChatAddState createState() => _ChatAddState();
@ -42,18 +41,16 @@ class _ChatAddState extends State<ChatAdd> {
void _scanCallback(bool isOk, String app, List params) { void _scanCallback(bool isOk, String app, List params) {
Navigator.of(context).pop(); Navigator.of(context).pop();
if (isOk && app == 'add-friend' && params.length == 3) { if (isOk && app == 'add-friend' && params.length == 2) {
setState(() { setState(() {
this._showHome = false; this._showHome = false;
final avatar = Avatar(name: params[2], width: 100.0, colorSurface: false); final avatar = Avatar(name: params[1], width: 100.0, colorSurface: false);
String id = gidParse(params[0].trim()); String id = pidParse(params[0].trim());
String addr = addrParse(params[1]);
this._coreScreen = _InfoScreen( this._coreScreen = _InfoScreen(
callback: this._sendCallback, callback: this._sendCallback,
id: id, id: id,
addr: addr, name: params[1],
name: params[2],
bio: '', bio: '',
avatar: avatar, avatar: avatar,
); );
@ -61,13 +58,12 @@ class _ChatAddState extends State<ChatAdd> {
} }
} }
void _searchCallBack(String id, String addr, String name, String bio, Avatar avatar) { void _searchCallBack(String id, String name, String bio, Avatar avatar) {
setState(() { setState(() {
this._showHome = false; this._showHome = false;
this._coreScreen = _InfoScreen( this._coreScreen = _InfoScreen(
callback: this._sendCallback, callback: this._sendCallback,
id: id, id: id,
addr: addr,
name: name, name: name,
bio: bio, bio: bio,
avatar: avatar, avatar: avatar,
@ -151,7 +147,6 @@ class _ChatAddState extends State<ChatAdd> {
callback: this._sendCallback, callback: this._sendCallback,
name: widget.name, name: widget.name,
id: widget.id, id: widget.id,
addr: widget.addr,
bio: '', bio: '',
avatar: avatar, avatar: avatar,
); );
@ -196,9 +191,7 @@ class _ChatAddState extends State<ChatAdd> {
final res = await httpPost('chat-request-list', []); final res = await httpPost('chat-request-list', []);
if (res.isOk) { if (res.isOk) {
res.params.forEach((param) { res.params.forEach((param) {
if (param.length == 10) { this._requests[param[0]] = Request.fromList(param);
this._requests[param[0]] = Request.fromList(param);
}
}); });
setState(() {}); setState(() {});
} else { } else {
@ -235,8 +228,7 @@ class _ChatAddState extends State<ChatAdd> {
context, context,
Icons.info, Icons.info,
lang.info, lang.info,
UserInfo(app: 'add-friend', UserInfo(app: 'add-friend', id: account.pid, name: account.name)
id: account.gid, name: account.name, addr: Global.addr)
), ),
child: Padding( child: Padding(
padding: const EdgeInsets.only(right: 10.0), padding: const EdgeInsets.only(right: 10.0),
@ -320,8 +312,7 @@ class _ChatAddState extends State<ChatAdd> {
const SizedBox(height: 10.0), const SizedBox(height: 10.0),
const Divider(height: 1.0, color: Color(0x40ADB0BB)), const Divider(height: 1.0, color: Color(0x40ADB0BB)),
const SizedBox(height: 10.0), const SizedBox(height: 10.0),
_infoListTooltip(Icons.person, color.primary, gidText(request.gid), gidPrint(request.gid)), _infoListTooltip(Icons.person, color.primary, pidText(request.pid), pidPrint(request.pid)),
_infoListTooltip(Icons.location_on, color.primary, addrText(request.addr), addrPrint(request.addr)),
_infoList(Icons.turned_in, color.primary, request.remark), _infoList(Icons.turned_in, color.primary, request.remark),
_infoList(Icons.access_time_rounded, color.primary, request.time.toString()), _infoList(Icons.access_time_rounded, color.primary, request.time.toString()),
const SizedBox(height: 10.0), const SizedBox(height: 10.0),
@ -415,9 +406,7 @@ class _ChatAddState extends State<ChatAdd> {
InkWell( InkWell(
onTap: () { onTap: () {
Navigator.pop(context); Navigator.pop(context);
rpc.send('chat-request-create', [ rpc.send('chat-request-create', [request.pid, request.name, request.remark]);
request.gid, request.addr, request.name, request.remark
]);
setState(() { setState(() {
this._requests.remove(request.id); this._requests.remove(request.id);
}); });
@ -672,27 +661,23 @@ class _InputScreen extends StatefulWidget {
class _InputScreenState extends State<_InputScreen> { class _InputScreenState extends State<_InputScreen> {
TextEditingController userIdEditingController = TextEditingController(); TextEditingController userIdEditingController = TextEditingController();
TextEditingController addrEditingController = TextEditingController();
TextEditingController remarkEditingController = TextEditingController(); TextEditingController remarkEditingController = TextEditingController();
TextEditingController nameEditingController = TextEditingController(); TextEditingController nameEditingController = TextEditingController();
FocusNode userIdFocus = FocusNode(); FocusNode userIdFocus = FocusNode();
FocusNode addrFocus = FocusNode();
FocusNode remarkFocus = FocusNode(); FocusNode remarkFocus = FocusNode();
send() { send() {
final id = gidParse(userIdEditingController.text.trim()); final id = pidParse(userIdEditingController.text.trim());
final addr = addrParse(addrEditingController.text.trim()); if (id == '') {
if (id == '' || addr == '') {
return; return;
} }
final name = nameEditingController.text.trim(); final name = nameEditingController.text.trim();
final remark = remarkEditingController.text.trim(); final remark = remarkEditingController.text.trim();
rpc.send('chat-request-create', [id, addr, name, remark]); rpc.send('chat-request-create', [id, name, remark]);
setState(() { setState(() {
userIdEditingController.text = ''; userIdEditingController.text = '';
addrEditingController.text = '';
nameEditingController.text = ''; nameEditingController.text = '';
remarkEditingController.text = ''; remarkEditingController.text = '';
}); });
@ -714,12 +699,6 @@ class _InputScreenState extends State<_InputScreen> {
controller: userIdEditingController, controller: userIdEditingController,
focus: userIdFocus), focus: userIdFocus),
const SizedBox(height: 20.0), const SizedBox(height: 20.0),
InputText(
icon: Icons.location_on,
text: lang.address + ' (0x00..00)',
controller: addrEditingController,
focus: addrFocus),
const SizedBox(height: 20.0),
InputText( InputText(
icon: Icons.turned_in, icon: Icons.turned_in,
text: lang.remark, text: lang.remark,
@ -735,7 +714,6 @@ class _InputScreenState extends State<_InputScreen> {
class _InfoScreen extends StatelessWidget { class _InfoScreen extends StatelessWidget {
final Function callback; final Function callback;
final String id; final String id;
final String addr;
final String name; final String name;
final String bio; final String bio;
final Avatar avatar; final Avatar avatar;
@ -744,7 +722,6 @@ class _InfoScreen extends StatelessWidget {
Key? key, Key? key,
required this.callback, required this.callback,
required this.id, required this.id,
required this.addr,
required this.name, required this.name,
required this.bio, required this.bio,
required this.avatar, required this.avatar,
@ -773,19 +750,10 @@ class _InfoScreen extends StatelessWidget {
ListTile( ListTile(
contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 2.0), contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 2.0),
leading: Icon(Icons.person, color: color.primary), leading: Icon(Icons.person, color: color.primary),
title: Text(gidPrint(this.id), style: TextStyle(fontSize: 16.0)), title: Text(pidPrint(this.id), style: TextStyle(fontSize: 16.0)),
trailing: TextButton(
child: Icon(Icons.copy, size: 20.0),
onPressed: () => Clipboard.setData(ClipboardData(text: gidText(this.id))),
)
),
ListTile(
contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 2.0),
leading: Icon(Icons.location_on, color: color.primary),
title: Text(addrPrint(this.addr), style: TextStyle(fontSize: 16.0)),
trailing: TextButton( trailing: TextButton(
child: Icon(Icons.copy, size: 20.0), child: Icon(Icons.copy, size: 20.0),
onPressed: () => Clipboard.setData(ClipboardData(text: addrText(this.addr))), onPressed: () => Clipboard.setData(ClipboardData(text: pidText(this.id))),
) )
), ),
ListTile( ListTile(
@ -797,7 +765,7 @@ class _InfoScreen extends StatelessWidget {
TextButton( TextButton(
child: Text(lang.addFriend, style: TextStyle(fontSize: 20.0)), child: Text(lang.addFriend, style: TextStyle(fontSize: 20.0)),
onPressed: () { onPressed: () {
rpc.send('chat-request-create', [this.id, this.addr, this.name, '']); rpc.send('chat-request-create', [this.id, this.name, '']);
this.callback(); this.callback();
} }
), ),

11
lib/apps/chat/detail.dart

@ -26,7 +26,7 @@ class ChatDetail extends StatefulWidget {
class _ChatDetailState extends State<ChatDetail> { class _ChatDetailState extends State<ChatDetail> {
bool _loading = false; bool _loading = false;
Friend _friend = Friend('', '', ''); Friend _friend = Friend('', '');
Map<int, Message> _messages = {}; Map<int, Message> _messages = {};
@override @override
@ -83,7 +83,7 @@ class _ChatDetailState extends State<ChatDetail> {
} }
_send(MessageType mtype, String raw) { _send(MessageType mtype, String raw) {
rpc.send('chat-message-create', [_friend.id, _friend.gid, mtype.toInt(), raw]); rpc.send('chat-message-create', [_friend.id, _friend.pid, mtype.toInt(), raw]);
} }
@override @override
@ -165,9 +165,8 @@ class _ChatDetailState extends State<ChatDetail> {
lang.friendInfo, lang.friendInfo,
UserInfo( UserInfo(
app: 'add-friend', app: 'add-friend',
id: _friend.gid, id: _friend.pid,
name: _friend.name, name: _friend.name,
addr: _friend.addr,
title: lang.qrFriend, title: lang.qrFriend,
remark: _friend.remark, remark: _friend.remark,
), ),
@ -207,7 +206,7 @@ class _ChatDetailState extends State<ChatDetail> {
); );
} else if (value == 4) { } else if (value == 4) {
rpc.send('chat-request-create', [ rpc.send('chat-request-create', [
_friend.gid, _friend.addr, _friend.name, lang.fromContactCard(meName) _friend.pid, _friend.name, lang.fromContactCard(meName)
]); ]);
} else if (value == 5) { } else if (value == 5) {
showDialog( showDialog(
@ -264,7 +263,7 @@ class _ChatDetailState extends State<ChatDetail> {
itemCount: recentMessageKeys.length, itemCount: recentMessageKeys.length,
reverse: true, reverse: true,
itemBuilder: (BuildContext context, index) => ChatMessage( itemBuilder: (BuildContext context, index) => ChatMessage(
fgid: _friend.gid, fpid: _friend.pid,
name: _friend.name, name: _friend.name,
message: this._messages[recentMessageKeys[index]]!, message: this._messages[recentMessageKeys[index]]!,
) )

52
lib/apps/chat/models.dart

@ -8,9 +8,8 @@ import 'package:esse/apps/primitives.dart';
class Friend { class Friend {
int id = 0; int id = 0;
String gid = ''; String pid = '';
String name = ''; String name = '';
String addr = '';
String wallet = ''; String wallet = '';
String remark = ''; String remark = '';
bool isClosed = false; bool isClosed = false;
@ -18,10 +17,10 @@ class Friend {
bool online = false; bool online = false;
// new friend from network // new friend from network
Friend(this.gid, this.name, this.addr); Friend(this.pid, this.name);
Avatar showAvatar({bool needOnline = false, double width = 45.0}) { Avatar showAvatar({bool needOnline = false, double width = 45.0}) {
final avatar = Global.avatarPath + this.gid + '.png'; final avatar = Global.avatarPath + this.pid + '.png';
if (needOnline) { if (needOnline) {
return Avatar(width: width, name: this.name, avatarPath: avatar, return Avatar(width: width, name: this.name, avatarPath: avatar,
online: this.online, online: this.online,
@ -34,23 +33,21 @@ class Friend {
Friend.fromList(List params) { Friend.fromList(List params) {
this.id = params[0]; this.id = params[0];
this.gid = params[1]; this.pid = params[1];
this.addr = params[2]; this.name = params[2];
this.name = params[3]; this.wallet = params[3];
this.wallet = params[4]; this.remark = params[4];
this.remark = params[5]; this.isClosed = params[5];
this.isClosed = params[6]; this.time = RelativeTime.fromInt(params[6]);
this.time = RelativeTime.fromInt(params[7]); if (params.length == 8) {
if (params.length == 9) { this.online = params[7];
this.online = params[8];
} }
} }
} }
class Request { class Request {
int id = 0; int id = 0;
String gid = ''; String pid = '';
String addr = '';
String name = ''; String name = '';
String remark = ''; String remark = '';
bool isMe = true; bool isMe = true;
@ -59,33 +56,32 @@ class Request {
bool isDelivery = false; bool isDelivery = false;
RelativeTime time = RelativeTime(); RelativeTime time = RelativeTime();
Request(this.gid, this.addr, this.name, this.remark); Request(this.pid, this.name, this.remark);
overIt(bool isOk) { overIt(bool isOk) {
this.over = true; this.over = true;
this.ok = isOk; this.ok = isOk;
} }
Friend toFriend(String gid) { Friend toFriend(String pid) {
return Friend(gid, this.name, this.addr); return Friend(pid, this.name);
} }
Avatar showAvatar([double width = 45.0]) { Avatar showAvatar([double width = 45.0]) {
final avatar = Global.avatarPath + this.gid + '.png'; final avatar = Global.avatarPath + this.pid + '.png';
return Avatar(width: width, name: this.name, avatarPath: avatar); return Avatar(width: width, name: this.name, avatarPath: avatar);
} }
Request.fromList(List params) { Request.fromList(List params) {
this.id = params[0]; this.id = params[0];
this.gid = params[1]; this.pid = params[1];
this.addr = params[2]; this.name = params[2];
this.name = params[3]; this.remark = params[3];
this.remark = params[4]; this.isMe = params[4];
this.isMe = params[5]; this.ok = params[5];
this.ok = params[6]; this.over = params[6];
this.over = params[7]; this.isDelivery = params[7];
this.isDelivery = params[8]; this.time = RelativeTime.fromInt(params[8]);
this.time = RelativeTime.fromInt(params[9]);
} }
} }

15
lib/apps/device/page.dart

@ -48,11 +48,11 @@ class _DevicesPageState extends State<DevicesPage> {
)); ));
} }
_showQrCode(String name, String id, String addr, String lock, ColorScheme color, lang) async { _showQrCode(String name, String id, String lock, ColorScheme color, lang) async {
final res = await httpPost('account-mnemonic', [lock]); final res = await httpPost('account-mnemonic', [lock]);
if (res.isOk) { if (res.isOk) {
final words = res.params[0]; final words = res.params[0];
final info = json.encode({'app': 'distribute', 'params': [name, gidText(id), addrText(addr), words]}); final info = json.encode({'app': 'distribute', 'params': [name, pidText(id), words]});
showShadowDialog(context, Icons.qr_code_rounded, lang.deviceQrcode, showShadowDialog(context, Icons.qr_code_rounded, lang.deviceQrcode,
Column( Column(
children: [ children: [
@ -109,7 +109,7 @@ class _DevicesPageState extends State<DevicesPage> {
} }
Widget deviceWidget(ColorScheme color, Device device, bool isDesktop, double widgetWidth, lang) { Widget deviceWidget(ColorScheme color, Device device, bool isDesktop, double widgetWidth, lang) {
final bool isLocal = device.addr == Global.addr; final bool isLocal = true; // TODO
final String name = isLocal ? (device.name + " (${lang.deviceLocal})") : device.name; final String name = isLocal ? (device.name + " (${lang.deviceLocal})") : device.name;
return Container( return Container(
@ -126,10 +126,6 @@ class _DevicesPageState extends State<DevicesPage> {
? Icon(Icons.cloud_done_rounded, size: 38.0, color: Color(0xFF6174FF)) ? Icon(Icons.cloud_done_rounded, size: 38.0, color: Color(0xFF6174FF))
: Icon(Icons.cloud_off_rounded, size: 38.0, color: Colors.grey), : Icon(Icons.cloud_off_rounded, size: 38.0, color: Colors.grey),
title: Text(name), title: Text(name),
subtitle: Container(
padding: const EdgeInsets.only(top: 8.0),
child: Text(addrPrint(device.addr))
),
), ),
Row( Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisAlignment: MainAxisAlignment.spaceEvenly,
@ -207,13 +203,12 @@ class _DevicesPageState extends State<DevicesPage> {
Icons.security_rounded, Icons.security_rounded,
lang.verifyPin, lang.verifyPin,
PinWords( PinWords(
gid: account.gid, pid: account.pid,
callback: (key) async { callback: (key) async {
Navigator.of(context).pop(); Navigator.of(context).pop();
_showQrCode( _showQrCode(
account.name, account.name,
account.gid, account.pid,
Global.addr,
key, key,
color, color,
lang, lang,

3
lib/apps/group/detail.dart

@ -289,7 +289,7 @@ class _GroupChatDetailState extends State<GroupChatDetail> {
final msg = this._messages[recentMessageKeys[index]]!; final msg = this._messages[recentMessageKeys[index]]!;
return ChatMessage( return ChatMessage(
avatar: this._members[msg.mid]!.showAvatar(isOnline: false), avatar: this._members[msg.mid]!.showAvatar(isOnline: false),
fgid: this._members[msg.mid]!.mid, fpid: this._members[msg.mid]!.mid,
name: this._members[msg.mid]!.name, name: this._members[msg.mid]!.name,
message: msg, message: msg,
); );
@ -336,7 +336,6 @@ class _MemberScreenState extends State<_MemberScreen> {
app: 'add-friend', app: 'add-friend',
id: member.mid, id: member.mid,
name: member.name, name: member.name,
addr: member.addr,
title: lang.qrFriend, title: lang.qrFriend,
), ),
0.0, 0.0,

2
lib/apps/group/models.dart

@ -47,7 +47,7 @@ class Member {
this.addr = params[3]; this.addr = params[3];
this.name = params[4]; this.name = params[4];
this.leave = params[5]; this.leave = params[5];
if (this.addr == Global.addr) { if (this.mid == Global.pid) {
this.online = true; this.online = true;
} }
} }

2
lib/apps/jarvis/detail.dart

@ -120,7 +120,7 @@ class _JarvisDetailState extends State<JarvisDetail> {
itemCount: recentMessageKeys.length, itemCount: recentMessageKeys.length,
reverse: true, reverse: true,
itemBuilder: (BuildContext context, index) => ChatMessage( itemBuilder: (BuildContext context, index) => ChatMessage(
fgid: '', fpid: '',
name: lang.jarvis, name: lang.jarvis,
message: this._messages[recentMessageKeys[index]]!, message: this._messages[recentMessageKeys[index]]!,
) )

14
lib/apps/primitives.dart

@ -154,7 +154,7 @@ class BaseMessage {
List showInvite() { List showInvite() {
var type = GroupType.Tmp; var type = GroupType.Tmp;
var gid = ''; var pid = '';
var addr = ''; var addr = '';
var name = ''; var name = '';
var proof = ''; var proof = '';
@ -166,12 +166,12 @@ class BaseMessage {
} }
final raw_0 = this.content.substring(iType + 2); final raw_0 = this.content.substring(iType + 2);
final iGid = raw_0.indexOf(';;'); final iPid = raw_0.indexOf(';;');
if (iGid > 0) { if (iPid > 0) {
gid = raw_0.substring(0, iGid); pid = raw_0.substring(0, iPid);
} }
final raw_1 = raw_0.substring(iGid + 2); final raw_1 = raw_0.substring(iPid + 2);
final iAddr = raw_1.indexOf(';;'); final iAddr = raw_1.indexOf(';;');
if (iAddr > 0) { if (iAddr > 0) {
addr = raw_1.substring(0, iAddr); addr = raw_1.substring(0, iAddr);
@ -183,7 +183,7 @@ class BaseMessage {
name = raw_2.substring(0, iName).replaceAll('-;', ';'); name = raw_2.substring(0, iName).replaceAll('-;', ';');
} else { } else {
name = raw_2.replaceAll('-;', ';'); name = raw_2.replaceAll('-;', ';');
return [type, gid, addr, name, proof, key]; return [type, pid, addr, name, proof, key];
} }
final raw_3 = raw_2.substring(iName + 2); final raw_3 = raw_2.substring(iName + 2);
@ -195,7 +195,7 @@ class BaseMessage {
proof = raw_3; proof = raw_3;
} }
return [type, gid, addr, name, proof, key]; return [type, pid, addr, name, proof, key];
} }
// [hash, to, amount, name, network] // [hash, to, amount, name, network]

8
lib/apps/wallet/page.dart

@ -1025,7 +1025,7 @@ class _TransferTokenState extends State<_TransferToken> {
items: this._nft.map((value) { items: this._nft.map((value) {
return DropdownMenuItem<String>( return DropdownMenuItem<String>(
value: value, value: value,
child: Text(gidPrint(value, '', 6)), child: Text(pidPrint(value, '', 6)),
); );
}).toList(), }).toList(),
), ),
@ -1090,13 +1090,13 @@ class _TransferTokenState extends State<_TransferToken> {
return; return;
} }
final amount = restoreBalance(a, widget.token.decimal); final amount = restoreBalance(a, widget.token.decimal);
final gid = context.read<AccountProvider>().activedAccount.gid; final pid = context.read<AccountProvider>().activedAccount.pid;
showShadowDialog( showShadowDialog(
context, context,
Icons.security_rounded, Icons.security_rounded,
lang.verifyPin, lang.verifyPin,
PinWords( PinWords(
gid: gid, pid: pid,
callback: (key) async { callback: (key) async {
Navigator.of(context).pop(); Navigator.of(context).pop();
rpc.send('wallet-transfer', [ rpc.send('wallet-transfer', [
@ -1248,7 +1248,7 @@ class _ImportNftState extends State<_ImportNft> {
itemBuilder: (BuildContext context, int index) { itemBuilder: (BuildContext context, int index) {
final hash = this._nft[index]; final hash = this._nft[index];
return ListTile( return ListTile(
title: Text('TokenID: ' + gidPrint(hash, '', 6)), title: Text('TokenID: ' + pidPrint(hash, '', 6)),
trailing: IconButton(icon: Icon(Icons.link, color: color.primary), trailing: IconButton(icon: Icon(Icons.link, color: color.primary),
onPressed: () { onPressed: () {
launch(widget.token.nftUrl(hash)); launch(widget.token.nftUrl(hash));

31
lib/global.dart

@ -1,6 +1,6 @@
class Global { class Global {
static String version = 'v0.5.0'; static String version = 'v0.5.0';
static String gid = '0000000000000000000000000000000000000000000000000000000000000000'; static String pid = '0000000000000000000000000000000000000000000000000000000000000000';
static String httpRpc = '127.0.0.1:7365'; static String httpRpc = '127.0.0.1:7365';
static String wsRpc = '127.0.0.1:7366'; static String wsRpc = '127.0.0.1:7366';
//static String httpRpc = '192.168.2.148:8001'; // test code //static String httpRpc = '192.168.2.148:8001'; // test code
@ -8,24 +8,23 @@ class Global {
//static String httpRpc = '192.168.50.250:8001'; // test code //static String httpRpc = '192.168.50.250:8001'; // test code
//static String wsRpc = '192.168.50.250:8081'; // test code //static String wsRpc = '192.168.50.250:8081'; // test code
static String optionCache = 'option'; static String optionCache = 'option';
static String addr = '0x';
static String home = '.tdn'; static String home = '.tdn';
static String filePath = home + '/' + gid + '/files/'; static String filePath = home + '/' + pid + '/files/';
static String imagePath = home + '/' + gid + '/images/'; static String imagePath = home + '/' + pid + '/images/';
static String thumbPath = home + '/' + gid + '/thumbs/'; static String thumbPath = home + '/' + pid + '/thumbs/';
static String emojiPath = home + '/' + gid + '/emojis/'; static String emojiPath = home + '/' + pid + '/emojis/';
static String recordPath = home + '/' + gid + '/records/'; static String recordPath = home + '/' + pid + '/records/';
static String avatarPath = home + '/' + gid + '/avatars/'; static String avatarPath = home + '/' + pid + '/avatars/';
static changeGid(String gid) { static changePid(String pid) {
Global.gid = gid; Global.pid = pid;
Global.filePath = home + '/' + gid + '/files/'; Global.filePath = home + '/' + pid + '/files/';
Global.imagePath = home + '/' + gid + '/images/'; Global.imagePath = home + '/' + pid + '/images/';
Global.thumbPath = home + '/' + gid + '/thumbs/'; Global.thumbPath = home + '/' + pid + '/thumbs/';
Global.emojiPath = home + '/' + gid + '/emojis/'; Global.emojiPath = home + '/' + pid + '/emojis/';
Global.recordPath = home + '/' + gid + '/records/'; Global.recordPath = home + '/' + pid + '/records/';
Global.avatarPath = home + '/' + gid + '/avatars/'; Global.avatarPath = home + '/' + pid + '/avatars/';
} }
static changeWs(String newWs) { static changeWs(String newWs) {

19
lib/pages/account_quick.dart

@ -140,15 +140,20 @@ class _AccountQuickPageState extends State<AccountQuickPage> {
]); ]);
if (res.isOk) { if (res.isOk) {
// save this User final pid = res.params[0];
final account = Account(res.params[0], name, avatar); final login = await httpPost('account-login', [pid, lock]);
Provider.of<AccountProvider>(context, listen: false).addAccount(account, lock); if (login.isOk) {
Provider.of<DeviceProvider>(context, listen: false).updateActived(); // save this User
final account = Account(pid, name, avatar);
Navigator.push(context, MaterialPageRoute(builder: (_) => AccountDomainScreen( Provider.of<AccountProvider>(context, listen: false).addAccount(account, lock);
name: name, Provider.of<DeviceProvider>(context, listen: false).updateActived();
)));
Navigator.push(context, MaterialPageRoute(builder: (_) => AccountDomainScreen(
name: name,
)));
}
} else { } else {
// TODO tostor error // TODO tostor error
print(res.error); print(res.error);

2
lib/pages/account_restore.dart

@ -324,7 +324,7 @@ class _AccountRestorePageState extends State<AccountRestorePage> {
Navigator.of(context).pop(); Navigator.of(context).pop();
if (app == 'distribute' && params.length == 4) { if (app == 'distribute' && params.length == 4) {
final name = params[0]; final name = params[0];
//final id = gidParse(params[1]); //final id = pidParse(params[1]);
final addr = addrParse(params[2]); final addr = addrParse(params[2]);
final mnemonicWords = params[3]; final mnemonicWords = params[3];
setState(() { setState(() {

26
lib/pages/home.dart

@ -98,11 +98,10 @@ class _HomeListState extends State<HomeList> {
MaterialPageRoute( MaterialPageRoute(
builder: (context) => QRScan(callback: (isOk, app, params) { builder: (context) => QRScan(callback: (isOk, app, params) {
Navigator.of(context).pop(); Navigator.of(context).pop();
if (app == 'add-friend' && params.length == 3) { if (app == 'add-friend' && params.length == 2) {
final id = gidParse(params[0]); final id = pidParse(params[0]);
final addr = addrParse(params[1]); final name = params[1].trim();
final name = params[2].trim(); final widget = ChatAdd(id: id, name: name);
final widget = ChatAdd(id: id, addr: addr, name: name);
Provider.of<AccountProvider>(context, listen: false).systemAppFriendAddNew = false; Provider.of<AccountProvider>(context, listen: false).systemAppFriendAddNew = false;
if (isDesktop) { if (isDesktop) {
Provider.of<AccountProvider>(context, listen: false).updateActivedWidget(widget); Provider.of<AccountProvider>(context, listen: false).updateActivedWidget(widget);
@ -111,7 +110,7 @@ class _HomeListState extends State<HomeList> {
} }
} else if (app == 'distribute' && params.length == 4) { } else if (app == 'distribute' && params.length == 4) {
//final _name = params[0].trim(); //final _name = params[0].trim();
//final id = gidParse(params[1]); //final id = pidParse(params[1]);
final addr = addrParse(params[2]); final addr = addrParse(params[2]);
//final _mnemonicWords = params[3]; //final _mnemonicWords = params[3];
Provider.of<DeviceProvider>(context, listen: false).connect(addr); Provider.of<DeviceProvider>(context, listen: false).connect(addr);
@ -174,8 +173,7 @@ class _HomeListState extends State<HomeList> {
UserInfo( UserInfo(
app: 'add-friend', app: 'add-friend',
id: provider.id, id: provider.id,
name: provider.activedAccount.name, name: provider.activedAccount.name));
addr: Global.addr));
} }
}, },
itemBuilder: (context) { itemBuilder: (context) {
@ -312,7 +310,7 @@ class DrawerWidget extends StatelessWidget {
? () { ? () {
Navigator.of(context).pop(); Navigator.of(context).pop();
Provider.of<AccountProvider>(context, listen: false) Provider.of<AccountProvider>(context, listen: false)
.updateActivedAccount(account.gid, account.pin); .updateActivedAccount(account.pid, account.pin);
Provider.of<DeviceProvider>(context, listen: false) Provider.of<DeviceProvider>(context, listen: false)
.updateActived(); .updateActived();
} }
@ -340,18 +338,18 @@ class DrawerWidget extends StatelessWidget {
Icons.security_rounded, Icons.security_rounded,
lang.verifyPin, lang.verifyPin,
PinWords( PinWords(
gid: account.gid, pid: account.pid,
callback: (key) async { callback: (key) async {
Navigator.of(context).pop(); Navigator.of(context).pop();
Provider.of<AccountProvider>(context, Provider.of<AccountProvider>(context,
listen: false) listen: false)
.onlineAccount(account.gid, key); .onlineAccount(account.pid, key);
}), }),
0.0, 0.0,
); );
} else { } else {
Provider.of<AccountProvider>(context, listen: false) Provider.of<AccountProvider>(context, listen: false)
.offlineAccount(account.gid); .offlineAccount(account.pid);
} }
}, },
), ),
@ -380,8 +378,8 @@ class DrawerWidget extends StatelessWidget {
final accounts = provider.accounts; final accounts = provider.accounts;
List<Widget> accountsWidget = []; List<Widget> accountsWidget = [];
accounts.forEach((gid, account) { accounts.forEach((pid, account) {
if (gid != me.gid) { if (pid != me.pid) {
accountsWidget.add(_listAccount(context, account, color.primary, lang)); accountsWidget.add(_listAccount(context, account, color.primary, lang));
} }
}); });

2
lib/pages/setting/network.dart

@ -26,7 +26,6 @@ class _NetworkDetailState extends State<NetworkDetail> {
changeWs() async { changeWs() async {
Global.changeWs(wsController.text); Global.changeWs(wsController.text);
await rpc.init(wsController.text); await rpc.init(wsController.text);
rpc.send('system-info', []);
setState(() {}); setState(() {});
} }
@ -42,6 +41,7 @@ class _NetworkDetailState extends State<NetworkDetail> {
void loadNetworkDht() async { void loadNetworkDht() async {
final res = await httpPost('network-dht', []); final res = await httpPost('network-dht', []);
print(res);
if (res.isOk) { if (res.isOk) {
this.networkDht.clear(); this.networkDht.clear();
res.params.forEach((p) { res.params.forEach((p) {

15
lib/pages/setting/profile.dart

@ -167,8 +167,7 @@ class _ProfileDetailState extends State<ProfileDetail> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max, mainAxisSize: MainAxisSize.max,
children: [ children: [
_infoListTooltip(Icons.person, color.primary, gidText(account.gid), gidPrint(account.gid)), _infoListTooltip(Icons.person, color.primary, pidText(account.pid), pidPrint(account.pid)),
_infoListTooltip(Icons.location_on, color.primary, addrText(Global.addr), addrPrint(Global.addr)),
SizedBox( SizedBox(
height: 40.0, height: 40.0,
child: Row( child: Row(
@ -177,8 +176,8 @@ class _ProfileDetailState extends State<ProfileDetail> {
size: 20.0, color: color.primary), size: 20.0, color: color.primary),
const SizedBox(width: 20.0), const SizedBox(width: 20.0),
TextButton( TextButton(
onPressed: () => _pinCheck(account.gid, onPressed: () => _pinCheck(account.pid,
(key) => _changePin(context, account.gid, key, lang.setPin), (key) => _changePin(context, account.pid, key, lang.setPin),
lang.verifyPin, color lang.verifyPin, color
), ),
child: Text(lang.change + ' PIN'), child: Text(lang.change + ' PIN'),
@ -200,8 +199,8 @@ class _ProfileDetailState extends State<ProfileDetail> {
child: Text(lang.hide + ' ' + lang.mnemonic), child: Text(lang.hide + ' ' + lang.mnemonic),
) )
: TextButton( : TextButton(
onPressed: () => _pinCheck(account.gid, onPressed: () => _pinCheck(account.pid,
(key) => _showMnemonic(account.gid, key), lang.verifyPin, color), (key) => _showMnemonic(account.pid, key), lang.verifyPin, color),
child: Text(lang.show + ' ' + lang.mnemonic), child: Text(lang.show + ' ' + lang.mnemonic),
), ),
]), ]),
@ -278,13 +277,13 @@ class _ProfileDetailState extends State<ProfileDetail> {
} }
} }
_pinCheck(String gid, Function callback, String title, color) { _pinCheck(String pid, Function callback, String title, color) {
showShadowDialog( showShadowDialog(
context, context,
Icons.security_rounded, Icons.security_rounded,
title, title,
PinWords( PinWords(
gid: gid, pid: pid,
callback: (key) async { callback: (key) async {
Navigator.of(context).pop(); Navigator.of(context).pop();
callback(key); callback(key);

76
lib/provider.dart

@ -14,12 +14,12 @@ const DEFAULT_ONLINE_INIT = 8;
const DEFAULT_ONLINE_DELAY = 5; const DEFAULT_ONLINE_DELAY = 5;
class AccountProvider extends ChangeNotifier { class AccountProvider extends ChangeNotifier {
Map<String, Account> accounts = {}; // account's gid and account. Map<String, Account> accounts = {}; // account's pid and account.
String activedAccountId = ''; // actived account gid. String activedAccountId = ''; // actived account pid.
Account get activedAccount => this.accounts[activedAccountId]!; Account get activedAccount => this.accounts[activedAccountId]!;
/// current user's did. /// current user's did.
String get id => this.activedAccount.gid; String get id => this.activedAccount.pid;
bool systemAppFriendAddNew = false; bool systemAppFriendAddNew = false;
@ -48,7 +48,6 @@ class AccountProvider extends ChangeNotifier {
rpc.addNotice(_accountNotice); rpc.addNotice(_accountNotice);
// rpc // rpc
rpc.addListener('account-system-info', _systemInfo);
rpc.addListener('account-update', _accountUpdate); rpc.addListener('account-update', _accountUpdate);
rpc.addListener('account-login', _accountLogin); rpc.addListener('account-login', _accountLogin);
@ -65,28 +64,26 @@ class AccountProvider extends ChangeNotifier {
} }
/// when security load accounts from cache. /// when security load accounts from cache.
autoAccounts(String gid, String pin, Map<String, Account> accounts) { autoAccounts(String pid, String pin, Map<String, Account> accounts) {
Global.changeGid(gid); Global.changePid(pid);
this.accounts = accounts; this.accounts = accounts;
this.activedAccountId = gid; this.activedAccountId = pid;
this.activedAccount.online = true; this.activedAccount.online = true;
this.activedAccount.pin = pin; this.activedAccount.pin = pin;
rpc.send('session-list', []); rpc.send('session-list', []);
new Future.delayed(Duration(seconds: DEFAULT_ONLINE_INIT),
() => rpc.send('account-online', [gid]));
initLogined(gid, this.accounts.values.toList()); initLogined(pid, this.accounts.values.toList());
this.coreShowWidget = DefaultCoreShow(); this.coreShowWidget = DefaultCoreShow();
} }
/// when security add account. /// when security add account.
addAccount(Account account, String pin) { addAccount(Account account, String pin) {
Global.changeGid(account.gid); Global.changePid(account.pid);
this.accounts[account.gid] = account; this.accounts[account.pid] = account;
this.activedAccountId = account.gid; this.activedAccountId = account.pid;
this.activedAccount.online = true; this.activedAccount.online = true;
this.activedAccount.pin = pin; this.activedAccount.pin = pin;
@ -94,11 +91,11 @@ class AccountProvider extends ChangeNotifier {
updateLogined(account); updateLogined(account);
} }
updateActivedAccount(String gid, String pin) { updateActivedAccount(String pid, String pin) {
Global.changeGid(gid); Global.changePid(pid);
this.clearActivedAccount(); this.clearActivedAccount();
this.activedAccountId = gid; this.activedAccountId = pid;
this.activedAccount.online = true; this.activedAccount.online = true;
this.activedAccount.pin = pin; this.activedAccount.pin = pin;
this.activedAccount.hasNew = false; this.activedAccount.hasNew = false;
@ -113,11 +110,9 @@ class AccountProvider extends ChangeNotifier {
if (!this.activedAccount.online) { if (!this.activedAccount.online) {
this.activedAccount.online = true; this.activedAccount.online = true;
new Future.delayed(Duration(seconds: DEFAULT_ONLINE_DELAY),
() => rpc.send('account-online', [gid]));
} }
mainLogined(gid); mainLogined(pid);
notifyListeners(); notifyListeners();
} }
@ -133,25 +128,22 @@ class AccountProvider extends ChangeNotifier {
clearLogined(); clearLogined();
} }
onlineAccount(String gid, String pin) { onlineAccount(String pid, String pin) {
this.accounts[gid]!.online = true; this.accounts[pid]!.online = true;
this.accounts[gid]!.pin = pin; this.accounts[pid]!.pin = pin;
rpc.send('account-login', [gid, pin]); rpc.send('account-login', [pid, pin]);
new Future.delayed(Duration(seconds: DEFAULT_ONLINE_DELAY),
() => rpc.send('account-online', [gid]));
notifyListeners(); notifyListeners();
} }
offlineAccount(String gid) { offlineAccount(String pid) {
this.accounts[gid]!.online = false; this.accounts[pid]!.online = false;
this.accounts[gid]!.pin = ''; this.accounts[pid]!.pin = '';
if (gid == this.activedAccountId) { if (pid == this.activedAccountId) {
this.clearActivedAccount(); this.clearActivedAccount();
} }
rpc.send('account-offline', [gid]); rpc.send('account-offline', [pid]);
notifyListeners(); notifyListeners();
} }
@ -181,7 +173,7 @@ class AccountProvider extends ChangeNotifier {
clearActivedSession(SessionType type) { clearActivedSession(SessionType type) {
if (this.actived > 0 && this.activedSession.type == type) { if (this.actived > 0 && this.activedSession.type == type) {
rpc.send('session-suspend', [this.actived, this.activedSession.gid, rpc.send('session-suspend', [this.actived, this.activedSession.pid,
this.activedSession.type == SessionType.Group] this.activedSession.type == SessionType.Group]
); );
this.actived = 0; this.actived = 0;
@ -202,7 +194,7 @@ class AccountProvider extends ChangeNotifier {
if (id > 0) { if (id > 0) {
if (this.actived != id && this.actived > 0) { if (this.actived != id && this.actived > 0) {
rpc.send('session-suspend', [this.actived, this.activedSession.gid, rpc.send('session-suspend', [this.actived, this.activedSession.pid,
this.activedSession.type == SessionType.Group] this.activedSession.type == SessionType.Group]
); );
} }
@ -219,7 +211,7 @@ class AccountProvider extends ChangeNotifier {
} }
}); });
} }
rpc.send('session-connect', [id, this.activedSession.gid]); rpc.send('session-connect', [id, this.activedSession.pid]);
notifyListeners(); notifyListeners();
} }
} }
@ -237,17 +229,13 @@ class AccountProvider extends ChangeNotifier {
} }
// -- callback when receive rpc info. -- // // -- callback when receive rpc info. -- //
_systemInfo(List params) {
Global.addr = params[0];
}
_accountLogin(List _params) { _accountLogin(List _params) {
// nothing. // nothing.
} }
_accountNotice(String gid) { _accountNotice(String pid) {
if (this.accounts.containsKey(gid)) { if (this.accounts.containsKey(pid)) {
this.accounts[gid]!.hasNew = true; this.accounts[pid]!.hasNew = true;
notifyListeners(); notifyListeners();
} }
} }
@ -261,10 +249,10 @@ class AccountProvider extends ChangeNotifier {
} }
_accountUpdate(List params) { _accountUpdate(List params) {
final gid = params[0]; final pid = params[0];
this.accounts[gid]!.name = params[1]; this.accounts[pid]!.name = params[1];
if (params[2].length > 1) { if (params[2].length > 1) {
this.accounts[gid]!.updateAvatar(params[2]); this.accounts[pid]!.updateAvatar(params[2]);
} }
notifyListeners(); notifyListeners();
} }

24
lib/security.dart

@ -182,11 +182,11 @@ class _SecurityPageState extends State<SecurityPage> {
final mainAccount = loginedAccounts[0]; final mainAccount = loginedAccounts[0];
Map<String, Account> accounts = {}; Map<String, Account> accounts = {};
loginedAccounts.forEach((account) { loginedAccounts.forEach((account) {
accounts[account.gid] = account; accounts[account.pid] = account;
}); });
final res = await httpPost('account-login', [mainAccount.gid, ""]); final res = await httpPost('account-login', [mainAccount.pid, ""]);
if (res.isOk) { if (res.isOk) {
_handleLogined(mainAccount.gid, "", accounts); _handleLogined(mainAccount.pid, "", accounts);
return; return;
} else { } else {
showShadowDialog( showShadowDialog(
@ -194,10 +194,10 @@ class _SecurityPageState extends State<SecurityPage> {
Icons.security_rounded, Icons.security_rounded,
"PIN", "PIN",
PinWords( PinWords(
gid: mainAccount.gid, pid: mainAccount.pid,
callback: (key) async { callback: (key) async {
Navigator.of(context).pop(); Navigator.of(context).pop();
_handleLogined(mainAccount.gid, key, accounts); _handleLogined(mainAccount.pid, key, accounts);
return; return;
}), }),
0.0 0.0
@ -215,7 +215,7 @@ class _SecurityPageState extends State<SecurityPage> {
if (this._accounts.length > 0) { if (this._accounts.length > 0) {
final accountId = this._accounts.keys.first; final accountId = this._accounts.keys.first;
this._selectedUserId = this._accounts[accountId]!.gid; this._selectedUserId = this._accounts[accountId]!.pid;
this._accountsLoaded = true; this._accountsLoaded = true;
} }
} else { } else {
@ -242,7 +242,7 @@ class _SecurityPageState extends State<SecurityPage> {
Icons.security_rounded, Icons.security_rounded,
title, title,
PinWords( PinWords(
gid: this._selectedUserId, pid: this._selectedUserId,
callback: (pinWords) async { callback: (pinWords) async {
Navigator.of(context).pop(); Navigator.of(context).pop();
_verifyAfter(pinWords); _verifyAfter(pinWords);
@ -268,16 +268,16 @@ class _SecurityPageState extends State<SecurityPage> {
iconEnabledColor: Color(0xFFADB0BB), iconEnabledColor: Color(0xFFADB0BB),
isExpanded: true, isExpanded: true,
value: this._selectedUserId, value: this._selectedUserId,
onChanged: (String? gid) { onChanged: (String? pid) {
if (gid != null) { if (pid != null) {
setState(() { setState(() {
this._selectedUserId = gid; this._selectedUserId = pid;
}); });
} }
}, },
items: this._accounts.values.map((Account account) { items: this._accounts.values.map((Account account) {
return DropdownMenuItem<String>( return DropdownMenuItem<String>(
value: account.gid, value: account.pid,
child: Row( child: Row(
children: [ children: [
Expanded( Expanded(
@ -287,7 +287,7 @@ class _SecurityPageState extends State<SecurityPage> {
style: TextStyle(fontSize: 16) style: TextStyle(fontSize: 16)
), ),
), ),
Text(" (${gidPrint(account.gid)})", style: TextStyle(fontSize: 16)), Text(" (${pidPrint(account.pid)})", style: TextStyle(fontSize: 16)),
] ]
), ),
); );

16
lib/session.dart

@ -41,7 +41,7 @@ enum OnlineType {
class Session { class Session {
int id; int id;
int fid; int fid;
String gid; String pid;
String addr; String addr;
SessionType type; SessionType type;
String name; String name;
@ -147,7 +147,17 @@ class Session {
} }
Avatar showAvatar({double width = 45.0}) { Avatar showAvatar({double width = 45.0}) {
final avatar = Global.avatarPath + this.gid + '.png'; String avatar = Global.avatarPath;
switch (this.type) {
case SessionType.Chat:
avatar + this.pid + '.png';
break;
case SessionType.Group:
avatar + 'group_' + this.pid + '.png';
break;
default:
break;
}
Color color; Color color;
switch (this.online) { switch (this.online) {
@ -194,7 +204,7 @@ class Session {
Session.fromList(List params) Session.fromList(List params)
: this.id = params[0], : this.id = params[0],
this.fid = params[1], this.fid = params[1],
this.gid = params[2], this.pid = params[2],
this.addr = params[3], this.addr = params[3],
this.type = SessionTypeExtension.fromInt(params[4]), this.type = SessionTypeExtension.fromInt(params[4]),
this.name = params[5], this.name = params[5],

20
lib/utils/better_print.dart

@ -1,16 +1,16 @@
String gidText(String? gid, [String pre='EH']) { String pidText(String? pid, [String pre='EH']) {
if (gid == null) { if (pid == null) {
return ''; return '';
} }
return pre + gid.toUpperCase(); return pre + pid.toUpperCase();
} }
String gidPrint(String? gid, [String pre='EH', int n = 4]) { String pidPrint(String? pid, [String pre='EH', int n = 6]) {
if (gid == null) { if (pid == null) {
return ''; return '';
} }
final info = gid.toUpperCase(); final info = pid.toUpperCase();
final len = info.length; final len = info.length;
if (len > n+n) { if (len > n+n) {
return pre + info.substring(0, n) + '...' + info.substring(len - n, len); return pre + info.substring(0, n) + '...' + info.substring(len - n, len);
@ -19,11 +19,11 @@ String gidPrint(String? gid, [String pre='EH', int n = 4]) {
} }
} }
String gidParse(String gid, [String pre='EH']) { String pidParse(String pid, [String pre='EH']) {
if (gid.length > 2 && gid.substring(0, 2) == pre) { if (pid.length > 2 && pid.substring(0, 2) == pre) {
return gid.substring(2); return pid.substring(2);
} else { } else {
return gid; return pid;
} }
} }

36
lib/utils/logined_cache.dart

@ -14,7 +14,7 @@ Future<List<Account>> getLogined() async {
final fields = prefs.getStringList(id); final fields = prefs.getStringList(id);
if (fields != null && fields.length == 5) { if (fields != null && fields.length == 5) {
accounts.add(Account( accounts.add(Account(
fields[0], // gid fields[0], // pid
fields[1], // name fields[1], // name
fields[2], // avatar fields[2], // avatar
false, false,
@ -28,7 +28,7 @@ Future<List<Account>> getLogined() async {
return accounts; return accounts;
} }
initLogined(String gid, List<Account> accounts) async { initLogined(String pid, List<Account> accounts) async {
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedPreferences prefs = await SharedPreferences.getInstance();
final ids = prefs.getStringList(LOGINED_CACHE_NAME); final ids = prefs.getStringList(LOGINED_CACHE_NAME);
if (ids != null) { if (ids != null) {
@ -37,19 +37,19 @@ initLogined(String gid, List<Account> accounts) async {
}); });
} }
List<String> newIds = [gid]; List<String> newIds = [pid];
accounts.forEach((account) { accounts.forEach((account) {
final List<String> fields = [ final List<String> fields = [
account.gid, account.pid,
account.name, account.name,
account.encodeAvatar(), account.encodeAvatar(),
]; ];
if (account.gid != gid) { if (account.pid != pid) {
newIds.add(account.gid); newIds.add(account.pid);
} }
prefs.setStringList(account.gid, fields); prefs.setStringList(account.pid, fields);
}); });
prefs.setStringList(LOGINED_CACHE_NAME, newIds); prefs.setStringList(LOGINED_CACHE_NAME, newIds);
@ -64,44 +64,44 @@ updateLogined(Account account) async {
} }
if (!ids.contains(account.gid)) { if (!ids.contains(account.pid)) {
ids.add(account.gid); ids.add(account.pid);
prefs.setStringList(LOGINED_CACHE_NAME, ids); prefs.setStringList(LOGINED_CACHE_NAME, ids);
} }
final List<String> fields = [ final List<String> fields = [
account.gid, account.pid,
account.name, account.name,
account.encodeAvatar(), account.encodeAvatar(),
]; ];
prefs.setStringList(account.gid, fields); prefs.setStringList(account.pid, fields);
} }
/// change main logined account. /// change main logined account.
mainLogined(String gid) async { mainLogined(String pid) async {
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedPreferences prefs = await SharedPreferences.getInstance();
List<String>? ids = prefs.getStringList(LOGINED_CACHE_NAME); List<String>? ids = prefs.getStringList(LOGINED_CACHE_NAME);
if (ids == null) { if (ids == null) {
ids = []; ids = [];
} }
ids.remove(gid); ids.remove(pid);
ids.insert(0, gid); ids.insert(0, pid);
prefs.setStringList(LOGINED_CACHE_NAME, ids); prefs.setStringList(LOGINED_CACHE_NAME, ids);
} }
/// remove auto-login accounts. /// remove auto-login accounts.
removeLogined(String gid) async { removeLogined(String pid) async {
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove(gid); prefs.remove(pid);
List<String>? ids = prefs.getStringList(LOGINED_CACHE_NAME); List<String>? ids = prefs.getStringList(LOGINED_CACHE_NAME);
if (ids == null) { if (ids == null) {
ids = []; ids = [];
} }
if (ids.contains(gid)) { if (ids.contains(pid)) {
ids.remove(gid); ids.remove(pid);
prefs.setStringList(LOGINED_CACHE_NAME, ids); prefs.setStringList(LOGINED_CACHE_NAME, ids);
} }
} }

18
lib/widgets/chat_message.dart

@ -22,13 +22,13 @@ import 'package:esse/apps/wallet/models.dart' show NetworkExtension, Network, To
class ChatMessage extends StatelessWidget { class ChatMessage extends StatelessWidget {
final Widget? avatar; final Widget? avatar;
final String fgid; final String fpid;
final String name; final String name;
final BaseMessage message; final BaseMessage message;
const ChatMessage({Key? key, required this.fgid, required this.name, required this.message, this.avatar}): super(key: key); const ChatMessage({Key? key, required this.fpid, required this.name, required this.message, this.avatar}): super(key: key);
Widget _showContactCard(Widget avatar, String gid, String name, String title, ColorScheme color, [String pre='EH']) { Widget _showContactCard(Widget avatar, String pid, String name, String title, ColorScheme color, [String pre='EH']) {
return Container( return Container(
padding: const EdgeInsets.only(top: 10, bottom: 6.0, left: 10.0, right: 10.0), padding: const EdgeInsets.only(top: 10, bottom: 6.0, left: 10.0, right: 10.0),
width: 200.0, width: 200.0,
@ -41,7 +41,7 @@ class ChatMessage extends StatelessWidget {
child: Column(children: [ child: Column(children: [
Text(name, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: color.onPrimary, fontSize: 16.0)), Text(name, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: color.onPrimary, fontSize: 16.0)),
const SizedBox(height: 4.0), const SizedBox(height: 4.0),
Text(gidPrint(gid, pre), style: TextStyle(color: Colors.grey, fontSize: 12.0)), Text(pidPrint(pid, pre), style: TextStyle(color: Colors.grey, fontSize: 12.0)),
]))]), ]))]),
const SizedBox(height: 5.0), const SizedBox(height: 5.0),
const Divider(height: 1.0, color: Color(0x40ADB0BB)), const Divider(height: 1.0, color: Color(0x40ADB0BB)),
@ -220,7 +220,7 @@ class ChatMessage extends StatelessWidget {
} }
Widget _showContact(context, lang, color, maxWidth) { Widget _showContact(context, lang, color, maxWidth) {
// contact [name, gid, addr, avatar] // contact [name, pid, avatar]
final infos = message.showContact(); final infos = message.showContact();
if (infos[1].length > 0) { if (infos[1].length > 0) {
return GestureDetector( return GestureDetector(
@ -229,7 +229,7 @@ class ChatMessage extends StatelessWidget {
Icons.person_rounded, Icons.person_rounded,
lang.contactCard, lang.contactCard,
UserInfo( UserInfo(
showQr: false, id: infos[1], addr: infos[2], name: infos[0], showQr: false, id: infos[1], name: infos[0],
remark: lang.fromContactCard(name), remark: lang.fromContactCard(name),
avatar: Avatar(width: 100.0, name: infos[0], avatarPath: infos[3]), avatar: Avatar(width: 100.0, name: infos[0], avatarPath: infos[3]),
callback: () { callback: () {
@ -251,7 +251,7 @@ class ChatMessage extends StatelessWidget {
} }
Widget _showInvite(context, lang, color, maxWidth) { Widget _showInvite(context, lang, color, maxWidth) {
// contact [type, gid, addr, name, proof, key] // contact [type, pid, addr, name, proof, key]
final infos = message.showInvite(); final infos = message.showInvite();
if (infos[1].length > 0) { if (infos[1].length > 0) {
final GroupType gtype = infos[0]; final GroupType gtype = infos[0];
@ -260,7 +260,7 @@ class ChatMessage extends StatelessWidget {
context, context,
Icons.groups_rounded, Icons.groups_rounded,
lang.groupChat, lang.groupChat,
UserInfo(showQr: false, id: infos[1], addr: infos[2], name: infos[3], pre: 'EG', UserInfo(showQr: false, id: infos[1], name: infos[3], pre: 'EG',
title: gtype.lang(lang), title: gtype.lang(lang),
avatar: Container(width: 100.0, height: 100.0, avatar: Container(width: 100.0, height: 100.0,
padding: const EdgeInsets.all(8.0), padding: const EdgeInsets.all(8.0),
@ -271,7 +271,7 @@ class ChatMessage extends StatelessWidget {
Navigator.pop(context); Navigator.pop(context);
// TOOD join invite. // TOOD join invite.
// Provider.of<GroupChatProvider>(context, listen: false).join( // Provider.of<GroupChatProvider>(context, listen: false).join(
// gtype, infos[1], infos[2], infos[3], fgid, infos[4], infos[5] // gtype, infos[1], infos[2], infos[3], fpid, infos[4], infos[5]
// ); // );
}, },
), ),

4
lib/widgets/show_contact.dart

@ -40,7 +40,7 @@ class _ContactListState extends State<ContactList> {
List<Friend> offlines = []; List<Friend> offlines = [];
res.params.forEach((params) { res.params.forEach((params) {
final friend = Friend.fromList(params); final friend = Friend.fromList(params);
if (!widget.filters.contains(friend.gid)) { if (!widget.filters.contains(friend.pid)) {
if (friend.online) { if (friend.online) {
onlines.add(friend); onlines.add(friend);
} else { } else {
@ -52,7 +52,7 @@ class _ContactListState extends State<ContactList> {
} else { } else {
res.params.forEach((params) { res.params.forEach((params) {
final friend = Friend.fromList(params); final friend = Friend.fromList(params);
if (!widget.filters.contains(friend.gid)) { if (!widget.filters.contains(friend.pid)) {
this._friends.add(friend); this._friends.add(friend);
} }
}); });

6
lib/widgets/show_pin.dart

@ -56,9 +56,9 @@ Widget _keyboradInput(Color color, Color bg, String text, Function callback) {
class PinWords extends StatefulWidget { class PinWords extends StatefulWidget {
final Function callback; final Function callback;
final String gid; final String pid;
PinWords({Key? key, required this.gid, required this.callback}) : super(key: key); PinWords({Key? key, required this.pid, required this.callback}) : super(key: key);
@override @override
_PinWordsState createState() => _PinWordsState(); _PinWordsState createState() => _PinWordsState();
@ -71,7 +71,7 @@ class _PinWordsState extends State<PinWords> {
_checkPin() async { _checkPin() async {
bool check = false; bool check = false;
final res = await httpPost('account-pin-check', [widget.gid, _pinWords]); final res = await httpPost('account-pin-check', [widget.pid, _pinWords]);
if (res.isOk) { if (res.isOk) {
check = res.params[0]; check = res.params[0];
} else { } else {

4
lib/widgets/transfer.dart

@ -353,13 +353,13 @@ class _TransferState extends State<Transfer> {
return; return;
} }
final amount = restoreBalance(a, this._selectedToken.decimal); final amount = restoreBalance(a, this._selectedToken.decimal);
final gid = context.read<AccountProvider>().activedAccount.gid; final pid = context.read<AccountProvider>().activedAccount.pid;
showShadowDialog( showShadowDialog(
context, context,
Icons.security_rounded, Icons.security_rounded,
lang.verifyPin, lang.verifyPin,
PinWords( PinWords(
gid: gid, pid: pid,
callback: (key) async { callback: (key) async {
if (this._main.length < 2) { if (this._main.length < 2) {
return; return;

44
lib/widgets/user_info.dart

@ -11,7 +11,6 @@ class UserInfo extends StatefulWidget {
final String? app; final String? app;
final String id; final String id;
final String name; final String name;
final String addr;
final String? title; final String? title;
final String? remark; final String? remark;
final String? bio; final String? bio;
@ -23,7 +22,6 @@ class UserInfo extends StatefulWidget {
UserInfo({Key? key, UserInfo({Key? key,
required this.id, required this.id,
required this.addr,
required this.name, required this.name,
this.app, this.app,
this.remark, this.remark,
@ -37,7 +35,7 @@ class UserInfo extends StatefulWidget {
if (this.showQr) { if (this.showQr) {
this.qrInfo = { this.qrInfo = {
"app": this.app, "app": this.app,
"params": [gidText(this.id, this.pre), addrText(this.addr), this.name], "params": [pidText(this.id, this.pre), this.name],
}; };
} }
} }
@ -48,7 +46,6 @@ class UserInfo extends StatefulWidget {
class _UserInfoState extends State<UserInfo> { class _UserInfoState extends State<UserInfo> {
bool idCopy = false; bool idCopy = false;
bool addrCopy = false;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -57,7 +54,7 @@ class _UserInfoState extends State<UserInfo> {
Color idColor = idCopy ? color.primary : color.onPrimary; Color idColor = idCopy ? color.primary : color.onPrimary;
Color addrColor = addrCopy ? color.primary : color.onPrimary; print(pidText(widget.id));
return Column( return Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
@ -114,47 +111,28 @@ class _UserInfoState extends State<UserInfo> {
const SizedBox(height: 20), const SizedBox(height: 20),
InkWell( InkWell(
onTap: () { onTap: () {
Clipboard.setData(ClipboardData(text: gidText(widget.id))); Clipboard.setData(ClipboardData(text: pidText(widget.id)));
setState(() { setState(() {
idCopy = true; idCopy = true;
addrCopy = false;
}); });
}, },
child: Container( child: Container(
width: 250.0, width: 250.0,
child: Row( child: Row(
children: [ children: [
Icon(Icons.person, size: 20.0, color: color.primary), Expanded(
Spacer(), child: Text(pidText(widget.id, widget.pre),
Text(gidPrint(widget.id, widget.pre), style: TextStyle(fontSize: 14, color: idColor)), style: TextStyle(fontSize: 14, color: idColor))),
Spacer(), Padding(
Icon(idCopy ? Icons.file_copy : Icons.copy, size: 20.0, color: color.primary), padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: Icon(idCopy ? Icons.file_copy : Icons.copy,
size: 20.0, color: color.primary),
),
] ]
), ),
) )
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
InkWell(
onTap: () {
Clipboard.setData(ClipboardData(text: addrText(widget.addr)));
setState(() {
idCopy = false;
addrCopy = true;
});
},
child: Container(
width: 250.0,
child: Row(
children: [
Icon(Icons.location_on, size: 20.0, color: color.primary),
Spacer(),
Text(addrPrint(widget.addr), style: TextStyle(fontSize: 14, color: addrColor)),
Spacer(),
Icon(addrCopy ? Icons.file_copy : Icons.copy, size: 20.0, color: color.primary),
]
),
)
),
if (widget.remark != null) if (widget.remark != null)
Container( Container(
width: 250.0, width: 250.0,

3
src/apps.rs

@ -31,6 +31,7 @@ pub(crate) fn app_rpc_inject(handler: &mut RpcHandler<Global>) {
//cloud::new_rpc_handler(handler); //cloud::new_rpc_handler(handler);
} }
#[allow(non_snake_case)]
pub(crate) async fn app_layer_handle( pub(crate) async fn app_layer_handle(
fgid: GroupId, fgid: GroupId,
msg: RecvType, msg: RecvType,
@ -55,7 +56,7 @@ pub(crate) async fn app_layer_handle(
let mut delete = vec![]; let mut delete = vec![];
for (gid, session) in &layer.groups { for (gid, session) in &layer.groups {
if session.pid == peer.id { if session.addr == peer.id {
delete.push(*gid); delete.push(*gid);
results.rpcs.push(session_lost(&session.s_id)); results.rpcs.push(session_lost(&session.s_id));
} }

1
src/apps/chat/models/friend.rs

@ -72,6 +72,7 @@ impl Friend {
pub fn to_session(&self) -> Session { pub fn to_session(&self) -> Session {
Session::new( Session::new(
self.id, self.id,
id_to_str(&self.pid),
self.pid, self.pid,
SessionType::Chat, SessionType::Chat,
self.name.clone(), self.name.clone(),

3
src/apps/chat/models/request.rs

@ -65,7 +65,6 @@ impl Request {
json!([ json!([
self.id, self.id,
id_to_str(&self.pid), id_to_str(&self.pid),
self.pid.to_hex(),
self.name, self.name,
self.remark, self.remark,
self.is_me, self.is_me,
@ -77,7 +76,7 @@ impl Request {
} }
pub fn get_id(db: &DStorage, pid: &PeerId) -> Result<Request> { pub fn get_id(db: &DStorage, pid: &PeerId) -> Result<Request> {
let sql = format!("SELECT id, pid, name, remark, is_me, is_ok, is_over, is_delivery, datetime FROM requests WHERE pid = '{}'", pid.to_hex()); let sql = format!("SELECT id, pid, name, remark, is_me, is_ok, is_over, is_delivery, datetime FROM requests WHERE pid = '{}'", id_to_str(pid));
let mut matrix = db.query(&sql)?; let mut matrix = db.query(&sql)?;
if matrix.len() > 0 { if matrix.len() > 0 {
Ok(Request::from_values(matrix.pop().unwrap())) // safe unwrap() Ok(Request::from_values(matrix.pop().unwrap())) // safe unwrap()

5
src/apps/chat/rpc.rs

@ -258,9 +258,8 @@ pub(crate) fn new_rpc_handler(handler: &mut RpcHandler<Global>) {
"chat-request-create", "chat-request-create",
|params: Vec<RpcParam>, state: Arc<Global>| async move { |params: Vec<RpcParam>, state: Arc<Global>| async move {
let remote_pid = id_from_str(params[0].as_str().ok_or(RpcError::ParseError)?)?; let remote_pid = id_from_str(params[0].as_str().ok_or(RpcError::ParseError)?)?;
let remote_addr = PeerId::from_hex(params[1].as_str().ok_or(RpcError::ParseError)?)?; let remote_name = params[1].as_str().ok_or(RpcError::ParseError)?.to_string();
let remote_name = params[2].as_str().ok_or(RpcError::ParseError)?.to_string(); let remark = params[2].as_str().ok_or(RpcError::ParseError)?.to_string();
let remark = params[3].as_str().ok_or(RpcError::ParseError)?.to_string();
let pid = state.pid().await; let pid = state.pid().await;
let db_key = state.group.read().await.db_key(&pid)?; let db_key = state.group.read().await.db_key(&pid)?;

21
src/layer.rs

@ -1,3 +1,4 @@
use esse_primitives::id_to_str;
use group_types::GroupChatId; use group_types::GroupChatId;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
@ -66,7 +67,7 @@ impl Layer {
return true; return true;
} else { } else {
for (_, session) in &self.groups { for (_, session) in &self.groups {
if session.pid == *addr { if session.addr == *addr {
return true; return true;
} }
} }
@ -111,12 +112,13 @@ impl Layer {
} }
pub fn chat_rm_online(&mut self, pid: &PeerId) -> Option<PeerId> { pub fn chat_rm_online(&mut self, pid: &PeerId) -> Option<PeerId> {
self.chats.remove(pid).map(|session| session.pid) self.chats.remove(pid).map(|session| session.addr)
} }
pub fn chat_add(&mut self, pid: PeerId, sid: i64, fid: i64) { pub fn chat_add(&mut self, pid: PeerId, sid: i64, fid: i64) {
if !self.chats.contains_key(&pid) { if !self.chats.contains_key(&pid) {
self.chats.insert(pid, LayerSession::new(pid, sid, fid)); self.chats
.insert(pid, LayerSession::new(id_to_str(&pid), pid, sid, fid));
} }
} }
@ -270,8 +272,10 @@ impl Layer {
/// online connected layer session. /// online connected layer session.
pub(crate) struct LayerSession { pub(crate) struct LayerSession {
/// session network id. /// session refs symbol id (Chat is friend's pid, Group is GroupChatId)
pub pid: PeerId, pub pid: String,
/// session network addr.
pub addr: PeerId,
/// session database id. /// session database id.
pub s_id: i64, pub s_id: i64,
/// layer service database id. /// layer service database id.
@ -285,9 +289,10 @@ pub(crate) struct LayerSession {
} }
impl LayerSession { impl LayerSession {
fn new(pid: PeerId, s_id: i64, db_id: i64) -> Self { fn new(pid: String, addr: PeerId, s_id: i64, db_id: i64) -> Self {
Self { Self {
pid, pid,
addr,
s_id, s_id,
db_id, db_id,
suspend_me: false, suspend_me: false,
@ -303,7 +308,7 @@ impl LayerSession {
self.suspend_remote = false; self.suspend_remote = false;
} }
self.remain = 0; self.remain = 0;
self.pid self.addr
} }
pub fn suspend(&mut self, is_me: bool, must: bool) -> Option<PeerId> { pub fn suspend(&mut self, is_me: bool, must: bool) -> Option<PeerId> {
@ -320,7 +325,7 @@ impl LayerSession {
if self.suspend_remote && self.suspend_me { if self.suspend_remote && self.suspend_me {
self.remain = 6; // keep-alive 10~11 minutes 120s/time self.remain = 6; // keep-alive 10~11 minutes 120s/time
Some(self.pid) Some(self.addr)
} else { } else {
None None
} }

3
src/migrate/session.rs

@ -4,6 +4,7 @@ pub(super) const SESSION_VERSIONS: [&str; 2] = [
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
fid INTEGER NOT NULL, fid INTEGER NOT NULL,
pid TEXT NOT NULL, pid TEXT NOT NULL,
addr TEXT NOT NULL,
s_type INTEGER NOT NULL, s_type INTEGER NOT NULL,
name TEXT NOT NULL, name TEXT NOT NULL,
is_top INTEGER NOT NULL, is_top INTEGER NOT NULL,
@ -11,5 +12,5 @@ pub(super) const SESSION_VERSIONS: [&str; 2] = [
last_datetime INTEGER, last_datetime INTEGER,
last_content TEXT, last_content TEXT,
last_readed INTEGER);", last_readed INTEGER);",
"INSERT INTO sessions (fid, pid, s_type, name, is_top, is_close, last_datetime, last_content, last_readed) VALUES (0, '', 3, '', 0, 0, 0, '', 1);", // Jarvis. "INSERT INTO sessions (fid, pid, addr, s_type, name, is_top, is_close, last_datetime, last_content, last_readed) VALUES (0, '', '', 3, '', 0, 0, 0, '', 1);", // Jarvis.
]; ];

9
src/rpc.rs

@ -7,7 +7,9 @@ use tdn::{
prelude::{new_send_channel, start_main}, prelude::{new_send_channel, start_main},
types::{ types::{
group::GroupId, group::GroupId,
message::{NetworkType, SendMessage, SendType, StateRequest, StateResponse}, message::{
NetworkType, RpcSendMessage, SendMessage, SendType, StateRequest, StateResponse,
},
primitives::{HandleResult, Peer, PeerId, Result}, primitives::{HandleResult, Peer, PeerId, Result},
rpc::{json, rpc_response, RpcError, RpcHandler, RpcParam}, rpc::{json, rpc_response, RpcError, RpcHandler, RpcParam},
}, },
@ -170,7 +172,10 @@ pub(crate) async fn inner_rpc(uid: u64, method: &str, global: &Arc<Global>) -> R
} }
}; };
global.send(SendMessage::Rpc(uid, param, false)).await?; global
.rpc_send
.send(RpcSendMessage(uid, param, false))
.await?;
return Ok(()); return Ok(());
} }

16
src/server.rs

@ -18,9 +18,9 @@ use tokio::{
use tdn_storage::local::DStorage; use tdn_storage::local::DStorage;
use crate::account::Account; use crate::account::Account;
//use crate::apps::app_layer_handle; use crate::apps::app_layer_handle;
use crate::global::Global; use crate::global::Global;
use crate::group::Group; use crate::group::{handle as group_handle, Group};
use crate::layer::Layer; use crate::layer::Layer;
use crate::migrate::{main_migrate, ACCOUNT_DB}; use crate::migrate::{main_migrate, ACCOUNT_DB};
use crate::primitives::network_seeds; use crate::primitives::network_seeds;
@ -93,14 +93,14 @@ pub async fn start(db_path: String) -> Result<()> {
while let Some(message) = self_recv.recv().await { while let Some(message) = self_recv.recv().await {
match message { match message {
ReceiveMessage::Group(g_msg) => { ReceiveMessage::Group(g_msg) => {
//if let Ok(handle_result) = group.write().await.handle(g_msg, now_rpc_uid).await { if let Ok(handle_result) = group_handle(g_msg, &global).await {
//handle(handle_result, now_rpc_uid, true, &sender).await; handle(handle_result, now_rpc_uid, true, &global).await;
//} }
} }
ReceiveMessage::Layer(fgid, l_msg) => { ReceiveMessage::Layer(fgid, l_msg) => {
// if let Ok(handle_result) = app_layer_handle(&layer, fgid, tgid, l_msg).await { if let Ok(handle_result) = app_layer_handle(fgid, l_msg, &global).await {
// handle(handle_result, now_rpc_uid, true, &sender).await; handle(handle_result, now_rpc_uid, true, &global).await;
// } }
} }
ReceiveMessage::Rpc(uid, params, is_ws) => { ReceiveMessage::Rpc(uid, params, is_ws) => {
if !is_ws { if !is_ws {

42
src/session.rs

@ -1,4 +1,3 @@
use esse_primitives::{id_from_str, id_to_str};
use tdn::types::{ use tdn::types::{
primitives::{PeerId, Result}, primitives::{PeerId, Result},
rpc::{json, RpcParam}, rpc::{json, RpcParam},
@ -36,7 +35,8 @@ impl SessionType {
pub(crate) struct Session { pub(crate) struct Session {
pub id: i64, pub id: i64,
fid: i64, fid: i64,
pub pid: PeerId, pub pid: String,
pub addr: PeerId,
pub s_type: SessionType, pub s_type: SessionType,
name: String, name: String,
is_top: bool, is_top: bool,
@ -47,10 +47,18 @@ pub(crate) struct Session {
} }
impl Session { impl Session {
pub fn new(fid: i64, pid: PeerId, s_type: SessionType, name: String, datetime: i64) -> Self { pub fn new(
fid: i64,
pid: String,
addr: PeerId,
s_type: SessionType,
name: String,
datetime: i64,
) -> Self {
Self { Self {
fid, fid,
pid, pid,
addr,
s_type, s_type,
name, name,
id: 0, id: 0,
@ -66,7 +74,8 @@ impl Session {
json!([ json!([
self.id, self.id,
self.fid, self.fid,
id_to_str(&self.pid), self.pid,
self.addr.to_hex(),
self.s_type.to_int(), self.s_type.to_int(),
self.name, self.name,
self.is_top, self.is_top,
@ -86,7 +95,8 @@ impl Session {
is_top: v.pop().unwrap().as_bool(), is_top: v.pop().unwrap().as_bool(),
name: v.pop().unwrap().as_string(), name: v.pop().unwrap().as_string(),
s_type: SessionType::from_int(v.pop().unwrap().as_i64()), s_type: SessionType::from_int(v.pop().unwrap().as_i64()),
pid: id_from_str(v.pop().unwrap().as_str()).unwrap_or(PeerId::default()), addr: PeerId::from_hex(v.pop().unwrap().as_str()).unwrap_or(PeerId::default()),
pid: v.pop().unwrap().as_string(),
fid: v.pop().unwrap().as_i64(), fid: v.pop().unwrap().as_i64(),
id: v.pop().unwrap().as_i64(), id: v.pop().unwrap().as_i64(),
} }
@ -102,17 +112,19 @@ impl Session {
let id = unique_check.pop().unwrap().pop().unwrap().as_i64(); let id = unique_check.pop().unwrap().pop().unwrap().as_i64();
self.id = id; self.id = id;
let sql = format!("UPDATE sessions SET pid='{}', name = '{}', is_top = '{}', is_close = false WHERE id = {}", let sql = format!("UPDATE sessions SET pid='{}', addr='{}', name = '{}', is_top = '{}', is_close = false WHERE id = {}",
id_to_str(&self.pid), self.pid,
self.addr.to_hex(),
self.name, self.name,
self.is_top, self.is_top,
self.id, self.id,
); );
db.update(&sql)?; db.update(&sql)?;
} else { } else {
let sql = format!("INSERT INTO sessions (fid, pid, s_type, name, is_top, is_close, last_datetime, last_content, last_readed) VALUES ({}, '{}', {}, '{}', {}, {}, {}, '{}', {})", let sql = format!("INSERT INTO sessions (fid, pid, addr, s_type, name, is_top, is_close, last_datetime, last_content, last_readed) VALUES ({}, '{}', '{}', {}, '{}', {}, {}, {}, '{}', {})",
self.fid, self.fid,
id_to_str(&self.pid), self.pid,
self.addr.to_hex(),
self.s_type.to_int(), self.s_type.to_int(),
self.name, self.name,
self.is_top, self.is_top,
@ -129,7 +141,7 @@ impl Session {
} }
pub fn get(db: &DStorage, id: &i64) -> Result<Session> { pub fn get(db: &DStorage, id: &i64) -> Result<Session> {
let sql = format!("SELECT id, fid, pid, s_type, name, is_top, is_close, last_datetime, last_content, last_readed FROM sessions WHERE id = {}", id); let sql = format!("SELECT id, fid, pid, addr, s_type, name, is_top, is_close, last_datetime, last_content, last_readed FROM sessions WHERE id = {}", id);
let mut matrix = db.query(&sql)?; let mut matrix = db.query(&sql)?;
if matrix.len() > 0 { if matrix.len() > 0 {
Ok(Session::from_values(matrix.pop().unwrap())) // safe unwrap() Ok(Session::from_values(matrix.pop().unwrap())) // safe unwrap()
@ -139,7 +151,7 @@ impl Session {
} }
pub fn list(db: &DStorage) -> Result<Vec<Session>> { pub fn list(db: &DStorage) -> Result<Vec<Session>> {
let matrix = db.query("SELECT id, fid, pid, s_type, name, is_top, is_close, last_datetime, last_content, last_readed FROM sessions ORDER BY last_datetime DESC")?; let matrix = db.query("SELECT id, fid, pid, addr, s_type, name, is_top, is_close, last_datetime, last_content, last_readed FROM sessions ORDER BY last_datetime DESC")?;
let mut sessions = vec![]; let mut sessions = vec![];
for values in matrix { for values in matrix {
sessions.push(Session::from_values(values)); sessions.push(Session::from_values(values));
@ -253,17 +265,17 @@ pub(crate) fn connect_session(
db: &DStorage, db: &DStorage,
s_type: &SessionType, s_type: &SessionType,
fid: &i64, fid: &i64,
pid: &PeerId, addr: &PeerId,
) -> Result<Option<Session>> { ) -> Result<Option<Session>> {
let sql = format!("SELECT id, fid, pid, s_type, name, is_top, is_close, last_datetime, last_content, last_readed FROM sessions WHERE s_type = {} AND fid = {}", s_type.to_int(), fid); let sql = format!("SELECT id, fid, pid, addr, s_type, name, is_top, is_close, last_datetime, last_content, last_readed FROM sessions WHERE s_type = {} AND fid = {}", s_type.to_int(), fid);
let mut matrix = db.query(&sql)?; let mut matrix = db.query(&sql)?;
if matrix.len() > 0 { if matrix.len() > 0 {
let session = Session::from_values(matrix.pop().unwrap()); // safe unwrap() let session = Session::from_values(matrix.pop().unwrap()); // safe unwrap()
let _ = db.update(&format!( let _ = db.update(&format!(
"UPDATE sessions SET pid = '{}' WHERE id = {}", "UPDATE sessions SET addr = '{}' WHERE id = {}",
pid.to_hex(), addr.to_hex(),
session.id, session.id,
)); ));

20
src/storage.rs

@ -350,70 +350,70 @@ pub(crate) fn consensus_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result
pub(crate) fn session_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> { pub(crate) fn session_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> {
let mut db_path = base.clone(); let mut db_path = base.clone();
db_path.push(pid.to_hex()); db_path.push(id_to_str(pid));
db_path.push(SESSION_DB); db_path.push(SESSION_DB);
DStorage::open(db_path, db_key) DStorage::open(db_path, db_key)
} }
pub(crate) fn chat_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> { pub(crate) fn chat_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> {
let mut db_path = base.clone(); let mut db_path = base.clone();
db_path.push(pid.to_hex()); db_path.push(id_to_str(pid));
db_path.push(CHAT_DB); db_path.push(CHAT_DB);
DStorage::open(db_path, db_key) DStorage::open(db_path, db_key)
} }
pub(crate) fn file_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> { pub(crate) fn file_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> {
let mut db_path = base.clone(); let mut db_path = base.clone();
db_path.push(pid.to_hex()); db_path.push(id_to_str(pid));
db_path.push(FILE_DB); db_path.push(FILE_DB);
DStorage::open(db_path, db_key) DStorage::open(db_path, db_key)
} }
pub(crate) fn _service_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> { pub(crate) fn _service_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> {
let mut db_path = base.clone(); let mut db_path = base.clone();
db_path.push(pid.to_hex()); db_path.push(id_to_str(pid));
db_path.push(SERVICE_DB); db_path.push(SERVICE_DB);
DStorage::open(db_path, db_key) DStorage::open(db_path, db_key)
} }
pub(crate) fn jarvis_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> { pub(crate) fn jarvis_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> {
let mut db_path = base.clone(); let mut db_path = base.clone();
db_path.push(pid.to_hex()); db_path.push(id_to_str(pid));
db_path.push(JARVIS_DB); db_path.push(JARVIS_DB);
DStorage::open(db_path, db_key) DStorage::open(db_path, db_key)
} }
pub(crate) fn group_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> { pub(crate) fn group_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> {
let mut db_path = base.clone(); let mut db_path = base.clone();
db_path.push(pid.to_hex()); db_path.push(id_to_str(pid));
db_path.push(GROUP_DB); db_path.push(GROUP_DB);
DStorage::open(db_path, db_key) DStorage::open(db_path, db_key)
} }
pub(crate) fn _dao_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> { pub(crate) fn _dao_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> {
let mut db_path = base.clone(); let mut db_path = base.clone();
db_path.push(pid.to_hex()); db_path.push(id_to_str(pid));
db_path.push(DAO_DB); db_path.push(DAO_DB);
DStorage::open(db_path, db_key) DStorage::open(db_path, db_key)
} }
pub(crate) fn domain_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> { pub(crate) fn domain_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> {
let mut db_path = base.clone(); let mut db_path = base.clone();
db_path.push(pid.to_hex()); db_path.push(id_to_str(pid));
db_path.push(DOMAIN_DB); db_path.push(DOMAIN_DB);
DStorage::open(db_path, db_key) DStorage::open(db_path, db_key)
} }
pub(crate) fn wallet_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> { pub(crate) fn wallet_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> {
let mut db_path = base.clone(); let mut db_path = base.clone();
db_path.push(pid.to_hex()); db_path.push(id_to_str(pid));
db_path.push(WALLET_DB); db_path.push(WALLET_DB);
DStorage::open(db_path, db_key) DStorage::open(db_path, db_key)
} }
pub(crate) fn _cloud_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> { pub(crate) fn _cloud_db(base: &PathBuf, pid: &PeerId, db_key: &str) -> Result<DStorage> {
let mut db_path = base.clone(); let mut db_path = base.clone();
db_path.push(pid.to_hex()); db_path.push(id_to_str(pid));
db_path.push(CLOUD_DB); db_path.push(CLOUD_DB);
DStorage::open(db_path, db_key) DStorage::open(db_path, db_key)
} }

Loading…
Cancel
Save