nim_core 1.0.0-rc.8 nim_core: ^1.0.0-rc.8 copied to clipboard
A Flutter plugin for NetEase IM SDK on Android, iOS and Windows.
// Copyright (c) 2021 NetEase, Inc. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:nim_core/nim_core.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
static const appKey = '';
static const account = '';
static const token = '';
static const friendAccount = '';
static const chatroomId = '';
late StreamSubscription authStatusStreamSubscription;
late StreamSubscription messageStreamSubscription;
@override
void initState() {
super.initState();
authStatusStreamSubscription =
NimCore.instance.authService.authStatus.listen((event) {
print('AuthService##auth status event: ${event.status.name}');
});
messageStreamSubscription =
NimCore.instance.messageService.onMessage.listen((messages) {
messages.forEach((message) {
print(
'MessageService##receive message: ${message.fromNickname} says ${message.content}');
});
});
NimCore.instance
.initialize(
NIMAndroidSDKOptions(
appKey: appKey,
),
)
.then((value) async {
await NimCore.instance.authService.login(NIMLoginInfo(
account: account,
token: token,
));
MessageBuilder.createCustomMessage(
sessionId: friendAccount,
sessionType: NIMSessionType.p2p,
content: 'Nice to meet you!',
attachment: NIMCustomMessageAttachment(
data: {
'key': account,
'list': [1, 2, 3, 4],
}
)
).then<NIMResult>((result) {
if (result.isSuccess) {
return NimCore.instance.messageService
.sendMessage(message: result.data!);
} else {
return result;
}
}).then((result) {
print(
'MessageService##send message: ${result.code} ${result.errorDetails}');
});
setupChatroom();
NimCore.instance.messageService.querySessionList().then((value) => print("session call back"));
});
}
@override
void dispose() {
authStatusStreamSubscription.cancel();
messageStreamSubscription.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(),
),
);
}
void setupChatroom() {
var chatroomService = NimCore.instance.chatroomService;
chatroomService.onEventNotified.listen((event) {
print('ChatroomService##on event notified: $event');
});
chatroomService.onMessageStatusChanged.listen((event) {
print('ChatroomService##on message status changed: ${event.uuid} ${event.status}');
});
chatroomService.onMessageAttachmentProgressUpdate.listen((event) {
print('ChatroomService##on message attachment progress update: ${event.id} ${event.progress}');
});
chatroomService.onMessageReceived.listen((messages) {
messages.forEach((message) {
print(
'ChatroomService##on message received: ${message.fromAccount} ${message.fromNickname} '
'\'${message.content}\'');
final attachment = message.messageAttachment;
if (attachment is NIMChatroomNotificationAttachment) {
print('ChatroomService##on notification: ${attachment.operatorNick} '
'${NIMChatroomNotificationTypes.typeToString(attachment.type)}');
}
if (message.content == 'fetch room info') {
chatroomService.fetchChatroomInfo(chatroomId).then((value) {
print(
'ChatroomService##fetch updated chatroom info: ${value.data?.name} '
'${value.data?.announcement}');
});
}
final setAnnouncement = RegExp(r'^set announcement (.+)$')
.firstMatch(message.content ?? '');
if (setAnnouncement != null) {
chatroomService
.updateChatroomInfo(
roomId: chatroomId,
request: NIMChatroomUpdateRequest(
announcement: setAnnouncement.group(1),
),
needNotify: true,
)
.then((value) {
print(
'ChatroomService##set chatroom announcement: ${value.code} ${value.errorDetails}');
});
}
final pollMessage = RegExp(r'^poll message( [0-9]*)$')
.firstMatch(message.content ?? '');
if (pollMessage != null) {
chatroomService.fetchMessageHistory(
roomId: chatroomId,
startTime: DateTime.now().millisecondsSinceEpoch,
limit:
max(1, int.tryParse(pollMessage.group(1)?.trim() ?? '1') ?? 1),
direction: QueryDirection.QUERY_OLD,
messageTypeList: [NIMMessageType.text],
).then((messages) {
var index = 0;
messages.data?.forEach((message) {
print(
'ChatroomService##message history: ${index++} ${message.fromAccount} ${message.fromNickname} '
'\'${message.content}\'');
});
});
}
if (message.content == 'poll queue') {
chatroomService.fetchChatroomQueue(chatroomId).then((value) {
print(
'ChatroomService##poll queue: ${value.code} ${value.errorDetails} '
'${value.data?.map((e) => '${e.key}:${e.value}').toList()}');
});
}
if (message.content == 'clear queue') {
chatroomService.clearChatroomQueue(message.sessionId!).then((value) {
print(
'ChatroomService##clear queue: ${value.code} ${value.errorDetails}');
});
}
final pollQueueEntry = RegExp(r'^poll queue entry (.+)$')
.firstMatch(message.content ?? '');
if (pollQueueEntry != null) {
chatroomService
.pollChatroomQueueEntry(chatroomId, pollQueueEntry.group(1))
.then((value) {
print(
'ChatroomService##poll queue entry: ${value.code} ${value.errorDetails} ${value.data?.key} ${value.data?.value}');
});
}
final addQueueEntry = RegExp(r'^add queue entry (.+) (.+)$')
.firstMatch(message.content ?? '');
if (addQueueEntry != null) {
chatroomService
.updateChatroomQueueEntry(
roomId: chatroomId,
entry: NIMChatroomQueueEntry(
key: addQueueEntry.group(1) as String,
value: addQueueEntry.group(2) as String,
),
isTransient: true,
)
.then((value) {
print(
'ChatroomService##add queue entry: ${value.code} ${value.errorDetails}');
});
}
// if (message.content == 'exit') {
// chatroomService.exitChatroom(message.sessionId!).then((value) {
// print(
// 'ChatroomService##exit chatroom: ${value.code} ${value.errorDetails}');
// });
// }
final setNickname =
RegExp(r'^set nickname (.+)$').firstMatch(message.content ?? '');
if (setNickname != null) {
chatroomService
.updateChatroomMyMemberInfo(
roomId: chatroomId,
request: NIMChatroomUpdateMyMemberInfoRequest(
nickname: setNickname.group(1) as String,
needSave: true,
),
)
.then((value) {
print(
'ChatroomService##update chatroom my info: ${value.code} ${value.errorDetails}');
});
}
if (message.content == 'ping') {
ChatroomMessageBuilder.createChatroomTextMessage(
roomId: message.sessionId!,
text: 'pong',
).then<NIMResult>((result) {
if (result.isSuccess) {
return chatroomService.sendChatroomMessage(result.data!);
} else {
return result;
}
}).then((value) {
print(
'ChatroomService##send message: ${value.code} ${value.errorDetails}');
});
}
final fetchMembers = RegExp(r'^fetch members( [0-9]*)$')
.firstMatch(message.content ?? '');
if (fetchMembers != null) {
chatroomService
.fetchChatroomMembers(
roomId: chatroomId,
queryType: NIMChatroomMemberQueryType.values.firstWhere(
(element) =>
element.index ==
int.tryParse(fetchMembers.group(1)?.trim() ?? '0'),
orElse: () => NIMChatroomMemberQueryType.allNormalMember),
limit: 10,
)
.then((result) {
var index = 0;
result.data?.forEach((member) {
print(
'ChatroomService fetchChatroomMembers ##member_${index++}: ${member.account} ${member.nickname} ${member.memberType}');
});
});
}
final fetchMember =
RegExp(r'^fetch member (.+)$').firstMatch(message.content ?? '');
if (fetchMember != null) {
chatroomService.fetchChatroomMembersByAccount(
roomId: chatroomId,
accountList: [fetchMember.group(1) as String]).then((result) {
final member = result.data != null && result.data!.isNotEmpty
? result.data![0]
: null;
print(
'ChatroomService fetch member: ${member?.account} ${member?.nickname} ${member?.memberType}');
});
}
if (message.content == 'mute me') {
chatroomService
.markChatroomMemberTempMuted(
duration: 5000,
options: NIMChatroomMemberOptions(
roomId: chatroomId,
account: message.fromAccount!,
),
needNotify: true,
)
.then((result) {
print(
'ChatroomService temp mute member: ${result.code} ${result.errorDetails}');
});
}
});
});
chatroomService.enterChatroom(NIMChatRoomEnterRequest.fromMap({
'roomId': chatroomId,
})).then((value) {
print(
'ChatroomService##enter chatroom: ${value.code} ${value.errorDetails}');
});
}
}