跳到主要内容

自定义消息和 provider

1. 自定义消息

1.1 编写自定义普通消息的代码

import { MessageTag, MessageContent, MessageFlag, JsonConverter } from '@rongcloud/imkit';

/**
* 消息标识
* @version 1.0.0
*/
export const CustomTextMessageObjectName = "RCD:TstMsg";

/**
* 自定义文本消息
*
*/

@MessageTag(CustomTextMessageObjectName, MessageFlag.Count)
export class CustomTextMessage extends MessageContent {
// 文本内容
content: string = '';

constructor() {
super();
}

encode(): string {
let map = super.encodeBaseData();
// 将文本内容放到字典
map.set('content', this.content)

return JsonConverter.stringifyFromHashMap(map);
}

decode(contentString: string): void {
let hashMap = JsonConverter.parseToHashMap(contentString);
super.decodeBaseData(hashMap);
// 将文本内容从字典中解出
if (hashMap.get("content")) {
this.content = hashMap.get("content") as string;
}
}

getClassName(): string {
return CustomTextMessage.name
}
}

1.2 编写自定义小灰条消息的代码

/**
* @date 2024/12/16
* @author 融云
*/
import { JsonConverter, MessageContent, MessageFlag, MessageTag, StringChecker } from '@rongcloud/imlib';

export const CustomInfoMessageObjectName = "RCD:InfoMsg";

/**
* 自定义小灰条消息
*/
@MessageTag(CustomInfoMessageObjectName, MessageFlag.Save)
export class CustomInfoMessage extends MessageContent {
/**
* 小灰条内容
*/
message: string = "";

constructor() {
super();
}

encode(): string {
let map = super.encodeBaseData();
if (StringChecker.isValid(this.message)) {
map.set("message", this.message);
}
return JsonConverter.stringifyFromHashMap(map);
}

decode(contentString: string): void {
let map = JsonConverter.parseToHashMap(contentString);
super.decodeBaseData(map);

if (map.get("message")) {
this.message = map.get("message") as string;
}
}

getClassName(): string {
return CustomInfoMessage.name;
}
}

1.3 将消息注册给 IMLib

消息注册给 IMLib,保证消息能够正常的收发

let clazzList : List<MessageContentConstructor> = new List();
clazzList.add(CustomTextMessage);
clazzList.add(CustomInfoMessage);
IMEngine.getInstance().registerMessageType(clazzList);

2. 自定义消息 provider

只有需要 UI 展示的消息需要写 provider

2.1 编写普通消息 provider

普通消息是指带头像的消息,例如常见的文本图片等

/**
* Created on 2024/07/09
* @author 融云
*/
import { BaseMessageItemProvider, MessageBubbleView, UiMessage } from '@rongcloud/imkit';
import { CustomTextMessage } from '../message/CustomTextMessaget';

export class CustomTextMessageItemProvider extends BaseMessageItemProvider<CustomTextMessage> {
public getMessageWrapBuilder(): WrappedBuilder<[Context, UiMessage, number]> {
return wrapBuilder(bindTextMessageData);
}

public isShowSummaryName(context: Context, messageContent: CustomTextMessage): boolean {
return true;
}

public getSummaryTextByMessageContent(context: Context,
messageContent: CustomTextMessage): Promise<MutableStyledString> {
return new Promise((resolve) => {
let content = messageContent.content;
if (content.concat("\n")) {
content = content.replaceAll("\n", " ");
}
resolve(new MutableStyledString(content));
});
}
}

@Builder
export function bindTextMessageData(context: Context, uiMessage: UiMessage, position: number) {
CustomTextMessageView({ uiMessage: uiMessage })
}

@Component
export struct CustomTextMessageView {
@ObjectLink uiMessage: UiMessage
private textMessage: CustomTextMessage = new CustomTextMessage()
controller: TextController = new TextController();
@State isClickLook: boolean = false // 是否点击了查看
private styledString: MutableStyledString = new MutableStyledString('')

aboutToAppear(): void {
this.textMessage = this.uiMessage.message.content as CustomTextMessage
}

build() {
MessageBubbleView({
uiMessage: this.uiMessage,
userInfo: this.uiMessage.senderInfo
}) {
// 普通模式
Text(undefined, { controller: this.controller }).
fontSize(17).
fontColor($r('app.color.rc_color_111F2C')).
lineHeight(21).
margin(10).
onAttach(() => {
//先让其显示内容
this.styledString = new MutableStyledString(this.textMessage.content);
this.controller.setStyledString(this.styledString);
})
}
}
}

2.2 编写小灰条消息 provider

小灰条消息一般居中显示,无头像,常见的比如撤回消息

import { BaseNotificationMessageItemProvider, UiMessage } from "@rongcloud/imkit";
import { CustomInfoMessage } from "../message/CustomInfoMessage";

/**
* 自定义小灰条消息 provider
*/
export class CustomInfoMessageProvider extends BaseNotificationMessageItemProvider<CustomInfoMessage> {
public getMessageWrapBuilder(): WrappedBuilder<[Context, UiMessage, number]> {
return wrapBuilder(bindMessageData);
}

public getSummaryTextByMessageContent(context: Context,
messageContent: CustomInfoMessage): Promise<MutableStyledString> {
return new Promise((resolve, reject) => {
resolve(new MutableStyledString(messageContent.message));
});
}
}

@Builder
export function bindMessageData(context: Context, messageModel: UiMessage, position: number) {
InfoMessageView({ context: context, messageModel: messageModel})
}


@Component
struct InfoMessageView {
@Require @Prop context: Context;
@ObjectLink messageModel: UiMessage
private messageContent: CustomInfoMessage = new CustomInfoMessage();

aboutToAppear(): void {
this.messageContent = this.messageModel.message.content as CustomInfoMessage;
}
build() {
Row() {
Text(this.messageContent.message).
backgroundColor($r('app.color.rc_color_EDEDED')).
borderRadius(8).
fontSize(14).
fontColor($r('app.color.rc_color_85909C')).
padding(10)
}.margin({ top: 10, bottom: 10 }).justifyContent(FlexAlign.Center).alignItems(VerticalAlign.Center).width('100%')
}
}

2.3 将消息和 provider 进行绑定

将消息和 provider 进行绑定,保证该消息能在 UI 上正常展示

// 获取会话服务
let conversationService = RongIM.getInstance().conversationService()

// 注册自定义文本消息和 provider 给 IMKit,方便聊天页面 UI 展示
conversationService.addMessageItemProvider(CustomTextMessageObjectName, new CustomTextMessageItemProvider())

// 注册自定义小灰条消息和 provider 给 IMKit,方便聊天页面 UI 展示
conversationService.addMessageItemProvider(CustomInfoMessageObjectName, new CustomInfoMessageProvider());

3. 使用自定义消息

3.1 自定义普通消息

let conId = new ConversationIdentifier();
conId.conversationType = ConversationType.Private;
conId.targetId = "会话 Id";

let textMsg = new CustomTextMessage();
textMsg.content = '自定义文本消息'

let msg = new Message(conId, textMsg);

RongIM.getInstance().messageService().sendMessage(msg).then((result: IAsyncResult<Message>) => {
if (result.code === EngineError.Success) {
promptAction.showToast({
message: "发送自定义文本消息成功",
bottom: 400,
})
}
})

3.2 自定义小灰条消息

let conId = new ConversationIdentifier();
conId.conversationType = ConversationType.Private;
conId.targetId = "会话 Id";

let infoMsg = new CustomInfoMessage();
infoMsg.message = "自定义小灰条消息";
let msg = new Message(conId, infoMsg);

RongIM.getInstance().messageService().sendMessage(msg).then((result: IAsyncResult<Message>) => {
if (result.code === EngineError.Success) {
promptAction.showToast({
message: "发送自定义小灰条消息成功",
bottom: 400,
})
}
})