-
Notifications
You must be signed in to change notification settings - Fork 68
/
main.dart
659 lines (606 loc) · 18.4 KB
/
main.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
import 'dart:async';
import 'dart:typed_data';
import 'package:agora_rtm/agora_rtm.dart';
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
bool _isLogin = false;
bool _isInChannel = false;
LocalInvitation? _localInvitation;
RemoteInvitation? _remoteInvitation;
final _userNameController = TextEditingController();
final _peerUserIdController = TextEditingController();
final _peerMessageController = TextEditingController();
final _invitationController = TextEditingController();
final _channelNameController = TextEditingController();
final _channelMessageController = TextEditingController();
final _infoStrings = <String>[];
AgoraRtmClient? _client;
AgoraRtmChannel? _channel;
@override
void initState() {
super.initState();
_createClient();
}
@override
void dispose() {
_client?.release();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Agora Real Time Message'),
),
body: Container(
padding: const EdgeInsets.all(16),
child: Column(
children: [
_buildLogin(),
_buildQueryOnlineStatus(),
_buildSubscribeOnlineStatus(),
_buildSendPeerMessage(),
_buildLocalInvitation(),
_buildRemoteInvitation(),
_buildJoinChannel(),
_buildGetMembers(),
_buildSendChannelMessage(),
_buildInfoList(),
],
),
)),
);
}
void _createClient() async {
_client = await AgoraRtmClient.createInstance('YOUR_APP_ID');
_log(await AgoraRtmClient.getSdkVersion());
await _client?.setParameters('{"rtm.log_filter": 15}');
await _client?.setLogFile('');
await _client?.setLogFilter(RtmLogFilter.info);
await _client?.setLogFileSize(10240);
_client?.onError = (error) {
_log("Client error: $error");
};
_client?.onConnectionStateChanged2 =
(RtmConnectionState state, RtmConnectionChangeReason reason) {
_log('Connection state changed: $state, reason: $reason');
if (state == RtmConnectionState.aborted) {
_client?.logout();
_log('Logout');
setState(() {
_isLogin = false;
});
}
};
_client?.onMessageReceived = (RtmMessage message, String peerId) {
_log("Peer msg: $peerId, msg: ${message.messageType} ${message.text}");
};
_client?.onTokenExpired = () {
_log("Token expired");
};
_client?.onTokenPrivilegeWillExpire = () {
_log("Token privilege will expire");
};
_client?.onPeersOnlineStatusChanged =
(Map<String, RtmPeerOnlineState> peersStatus) {
_log("Peers online status changed ${peersStatus.toString()}");
};
var callManager = _client?.getRtmCallManager();
callManager?.onError = (error) {
_log('Call manager error: $error');
};
callManager?.onLocalInvitationReceivedByPeer =
(LocalInvitation localInvitation) {
_log(
'Local invitation received by peer: ${localInvitation.calleeId}, content: ${localInvitation.content}');
};
callManager?.onLocalInvitationAccepted =
(LocalInvitation localInvitation, String response) {
_log(
'Local invitation accepted by peer: ${localInvitation.calleeId}, response: $response');
setState(() {
_localInvitation = null;
});
};
callManager?.onLocalInvitationRefused =
(LocalInvitation localInvitation, String response) {
_log(
'Local invitation refused by peer: ${localInvitation.calleeId}, response: $response');
setState(() {
_localInvitation = null;
});
};
callManager?.onLocalInvitationCanceled = (LocalInvitation localInvitation) {
_log(
'Local invitation canceled: ${localInvitation.calleeId}, content: ${localInvitation.content}');
setState(() {
_localInvitation = null;
});
};
callManager?.onLocalInvitationFailure =
(LocalInvitation localInvitation, int errorCode) {
_log(
'Local invitation failure: ${localInvitation.calleeId}, errorCode: $errorCode');
setState(() {
_localInvitation = null;
});
};
callManager?.onRemoteInvitationReceived =
(RemoteInvitation remoteInvitation) {
_log(
'Remote invitation received by peer: ${remoteInvitation.callerId}, content: ${remoteInvitation.content}');
setState(() {
_remoteInvitation = remoteInvitation;
});
};
callManager?.onRemoteInvitationAccepted =
(RemoteInvitation remoteInvitation) {
_log(
'Remote invitation accepted by peer: ${remoteInvitation.callerId}, content: ${remoteInvitation.content}');
setState(() {
_remoteInvitation = null;
});
};
callManager?.onRemoteInvitationRefused =
(RemoteInvitation remoteInvitation) {
_log(
'Remote invitation refused by peer: ${remoteInvitation.callerId}, content: ${remoteInvitation.content}');
setState(() {
_remoteInvitation = null;
});
};
callManager?.onRemoteInvitationCanceled =
(RemoteInvitation remoteInvitation) {
_log(
'Remote invitation canceled: ${remoteInvitation.callerId}, content: ${remoteInvitation.content}');
setState(() {
_remoteInvitation = null;
});
};
callManager?.onRemoteInvitationFailure =
(RemoteInvitation remoteInvitation, int errorCode) {
_log(
'Remote invitation failure: ${remoteInvitation.callerId}, errorCode: $errorCode');
setState(() {
_remoteInvitation = null;
});
};
}
Future<AgoraRtmChannel?> _createChannel(String name) async {
AgoraRtmChannel? channel = await _client?.createChannel(name);
if (channel != null) {
channel.onError = (error) {
_log("Channel error: $error");
};
channel.onMemberCountUpdated = (int memberCount) {
_log("Member count updated: $memberCount");
};
channel.onAttributesUpdated = (List<RtmChannelAttribute> attributes) {
_log("Channel attributes updated: ${attributes.toString()}");
};
channel.onMessageReceived =
(RtmMessage message, RtmChannelMember member) {
_log(
"Channel msg: ${member.userId}, msg: ${message.messageType} ${message.text}");
};
channel.onMemberJoined = (RtmChannelMember member) {
_log('Member joined: ${member.userId}, channel: ${member.channelId}');
};
channel.onMemberLeft = (RtmChannelMember member) {
_log('Member left: ${member.userId}, channel: ${member.channelId}');
};
}
return channel;
}
static TextStyle textStyle =
const TextStyle(fontSize: 18, color: Colors.blue);
Widget _buildLogin() {
return Row(children: <Widget>[
_isLogin
? Expanded(
child: Text('User Id: ${_userNameController.text}',
style: textStyle))
: Expanded(
child: TextField(
controller: _userNameController,
decoration:
const InputDecoration(hintText: 'Input your user id'))),
OutlinedButton(
onPressed: _toggleLogin,
child: Text(_isLogin ? 'Logout' : 'Login', style: textStyle),
)
]);
}
Widget _buildQueryOnlineStatus() {
if (!_isLogin) {
return Container();
}
return Row(children: <Widget>[
Expanded(
child: TextField(
controller: _peerUserIdController,
decoration:
const InputDecoration(hintText: 'Input peer user id'))),
OutlinedButton(
onPressed: _toggleQueryPeersOnlineStatus,
child: Text('Query Online', style: textStyle),
)
]);
}
Widget _buildSubscribeOnlineStatus() {
if (!_isLogin) {
return Container();
}
return Row(children: <Widget>[
OutlinedButton(
onPressed: _subscribePeersOnlineStatus,
child: Text('Subscribe Online', style: textStyle),
),
OutlinedButton(
onPressed: _unsubscribePeersOnlineStatus,
child: Text('Unsubscribe Online', style: textStyle),
)
]);
}
Widget _buildSendPeerMessage() {
if (!_isLogin) {
return Container();
}
return Row(children: <Widget>[
Expanded(
child: TextField(
controller: _peerMessageController,
decoration:
const InputDecoration(hintText: 'Input peer message'))),
OutlinedButton(
onPressed: _sendPeerMessage,
child: Text('Send to Peer', style: textStyle),
)
]);
}
Widget _buildLocalInvitation() {
if (!_isLogin) {
return Container();
}
return Row(children: <Widget>[
Expanded(
child: TextField(
controller: _invitationController,
decoration:
const InputDecoration(hintText: 'Input invitation content'))),
OutlinedButton(
onPressed: _toggleLocalInvitation,
child: Text(
'${_localInvitation == null ? 'Send' : 'Cancel'} local invitation',
style: textStyle),
)
]);
}
Widget _buildRemoteInvitation() {
if (!_isLogin || _remoteInvitation == null) {
return Container();
}
return Row(children: <Widget>[
OutlinedButton(
onPressed: _acceptRemoteInvitation,
child: Text('accept remote invitation', style: textStyle),
),
OutlinedButton(
onPressed: _refuseRemoteInvitation,
child: Text('refuse remote invitation', style: textStyle),
)
]);
}
Widget _buildJoinChannel() {
if (!_isLogin) {
return Container();
}
return Row(children: <Widget>[
_isInChannel
? Expanded(
child: Text('Channel: ${_channelNameController.text}',
style: textStyle))
: Expanded(
child: TextField(
controller: _channelNameController,
decoration:
const InputDecoration(hintText: 'Input channel id'))),
OutlinedButton(
onPressed: _toggleJoinChannel,
child: Text(_isInChannel ? 'Leave Channel' : 'Join Channel',
style: textStyle),
)
]);
}
Widget _buildSendChannelMessage() {
if (!_isLogin || !_isInChannel) {
return Container();
}
return Row(children: <Widget>[
Expanded(
child: TextField(
controller: _channelMessageController,
decoration:
const InputDecoration(hintText: 'Input channel message'))),
OutlinedButton(
onPressed: _sendChannelMessage,
child: Text('Send to Channel', style: textStyle),
)
]);
}
Widget _buildGetMembers() {
if (!_isLogin || !_isInChannel) {
return Container();
}
return Row(children: <Widget>[
OutlinedButton(
onPressed: _getMembers,
child: Text('Get Members in Channel', style: textStyle),
),
OutlinedButton(
onPressed: _getMemberCount,
child: Text('Get Member count in Channel', style: textStyle),
)
]);
}
Widget _buildInfoList() {
return Expanded(
child: ListView.builder(
itemExtent: 24,
itemBuilder: (context, i) {
return ListTile(
contentPadding: const EdgeInsets.all(0.0),
title: Text(_infoStrings[i]),
);
},
itemCount: _infoStrings.length,
));
}
void _toggleLogin() async {
if (_isLogin) {
try {
await _client?.logout();
_log('Logout success');
setState(() {
_isLogin = false;
_isInChannel = false;
});
} catch (errorCode) {
_log('Logout error: $errorCode');
}
} else {
String userId = _userNameController.text;
if (userId.isEmpty) {
_log('Please input your user id to login');
return;
}
try {
await _client?.login(null, userId);
_log('Login success: $userId');
setState(() {
_isLogin = true;
});
} catch (errorCode) {
_log('Login error: $errorCode');
}
}
}
void _toggleQueryPeersOnlineStatus() async {
String peerUid = _peerUserIdController.text;
if (peerUid.isEmpty) {
try {
List<String>? result = await _client?.queryPeersBySubscriptionOption(
RtmPeerSubscriptionOption.onlineStatus);
_log('Query result: $result');
} catch (errorCode) {
_log('Query error: $errorCode');
}
} else {
try {
Map<dynamic, dynamic>? result =
await _client?.queryPeersOnlineStatus([peerUid]);
_log('Query result: $result');
} catch (errorCode) {
_log('Query error: $errorCode');
}
}
}
void _subscribePeersOnlineStatus() async {
String peerUid = _peerUserIdController.text;
if (peerUid.isEmpty) {
_log('Please input peer user id to subscribe');
return;
}
try {
await _client?.subscribePeersOnlineStatus([peerUid]);
_log('Subscribe success');
} catch (errorCode) {
_log('Subscribe error: $errorCode');
}
}
void _unsubscribePeersOnlineStatus() async {
String peerUid = _peerUserIdController.text;
if (peerUid.isEmpty) {
_log('Please input peer user id to unsubscribe');
return;
}
try {
await _client?.unsubscribePeersOnlineStatus([peerUid]);
_log('Unsubscribe success');
} catch (errorCode) {
_log('Unsubscribe error: $errorCode');
}
}
void _sendPeerMessage() async {
String peerUid = _peerUserIdController.text;
if (peerUid.isEmpty) {
_log('Please input peer user id to send message');
return;
}
String text = _peerMessageController.text;
if (text.isEmpty) {
_log('Please input text to send');
return;
}
try {
RtmMessage? message = _client?.createTextMessage(text);
if (message != null) {
_log(message.text);
await _client?.sendMessageToPeer2(peerUid, message);
_log('Send peer message success');
}
} catch (errorCode) {
_log('Send peer message error: $errorCode');
}
}
void _toggleLocalInvitation() async {
String peerUid = _peerUserIdController.text;
if (peerUid.isEmpty) {
_log('Please input peer user id to send invitation');
return;
}
String text = _invitationController.text;
if (text.isEmpty) {
_log('Please input content to send');
return;
}
if (_localInvitation == null) {
try {
LocalInvitation? invitation =
await _client?.getRtmCallManager().createLocalInvitation(peerUid);
if (invitation != null) {
invitation.content = text;
_log(invitation.content ?? '');
await _client?.getRtmCallManager().sendLocalInvitation(invitation);
setState(() {
_localInvitation = invitation;
});
_log('Send local invitation success');
}
} catch (errorCode) {
_log('Send local invitation error: $errorCode');
}
} else {
try {
await _client
?.getRtmCallManager()
.cancelLocalInvitation(_localInvitation!);
_log('Cancel local invitation success');
} catch (errorCode) {
_log('Cancel local invitation error: $errorCode');
}
}
}
void _acceptRemoteInvitation() async {
if (_remoteInvitation == null) {
_log('No remote invitation');
return;
}
try {
await _client
?.getRtmCallManager()
.acceptRemoteInvitation(_remoteInvitation!);
_log('Accept remote invitation success');
} catch (errorCode) {
_log('Accept remote invitation error: $errorCode');
}
}
void _refuseRemoteInvitation() async {
if (_remoteInvitation == null) {
_log('No remote invitation');
return;
}
try {
await _client
?.getRtmCallManager()
.refuseRemoteInvitation(_remoteInvitation!);
_log('Refuse remote invitation success');
} catch (errorCode) {
_log('Refuse remote invitation error: $errorCode');
}
}
void _toggleJoinChannel() async {
if (_isInChannel) {
try {
await _channel?.leave();
_log('Leave channel success');
await _channel?.release();
_channelMessageController.clear();
setState(() {
_isInChannel = false;
});
} catch (errorCode) {
_log('Leave channel error: $errorCode');
}
} else {
String channelId = _channelNameController.text;
if (channelId.isEmpty) {
_log('Please input channel id to join');
return;
}
try {
_channel = await _createChannel(channelId);
await _channel?.join();
_log('Join channel success');
setState(() {
_isInChannel = true;
});
} catch (errorCode) {
_log('Join channel error: $errorCode');
}
}
}
void _getMembers() async {
try {
List<RtmChannelMember>? members = await _channel?.getMembers();
_log('Members: ${members.toString()}');
} catch (errorCode) {
_log('GetMembers failed: $errorCode');
}
}
void _getMemberCount() async {
String channelId = _channelNameController.text;
if (channelId.isEmpty) {
_log('Please input channel id to get');
return;
}
try {
List<RtmChannelMemberCount>? members =
await _client?.getChannelMemberCount([channelId]);
_log('Members: ${members.toString()}');
} catch (errorCode) {
_log('GetMembers failed: $errorCode');
}
}
void _sendChannelMessage() async {
String text = _channelMessageController.text;
if (text.isEmpty) {
_log('Please input text to send');
return;
}
try {
RtmMessage? message =
_client?.createRawMessage(Uint8List.fromList([]), text);
if (message != null) {
_log(message.text);
await _channel?.sendMessage2(message);
_log('Send channel message success');
}
} catch (errorCode) {
_log('Send channel message error: $errorCode');
}
}
void _log(String info) {
debugPrint(info);
setState(() {
_infoStrings.insert(0, info);
});
}
}