Message history

Update time: 2024/03/07 11:13:59

Message history

Users can store message history in the local database or in the cloud for later queries.

Local message history

Query local message history

  • API introduction

The SDK provides an interface for querying the local message history by account in a chat with the provided account (account) and session type (sessionType), and the limit of returned messages (limit). The result is displayed in descending order. The newest messages are displayed at the top.

  • API prototype
dart /// Query history messages in the local database.
 /// Note: The result is displayed in descending order. The newest messages are displayed at the top.
 /// [account] The user account to be queried (user account or group ID)
 /// [sessionType] Session type (P2P or group chat)
 /// [limit]     The limit of returned messages
Future<NIMResult<List<NIMMessage>>> queryMessageList(
      String account, NIMSessionType sessionType, int limit);
  • Parameters
Parameter
Type Description
account String The user account to be queried (user account or group ID).
sessionType NIMSessionType The session type P2P chats, group chats, and , NIMSessionType.p2p represents a P2P chat and NIMSessionType.team is used for a group chat. For other session types, see NIMSessionType
limit int The limit of messages per query
  • Example
dart// Query messages earlier than the anchor with 20 messages, and the results are sorted in descending order by time
final result = await NimCore.instance.messageService.queryMessageList(account,sessionType,limit);

Local message history

Query local message history

  • API introduction

The SDK can query messages in message history by anchor and the limit results can be earlier than (QUERY\_OLD) or later than (QUERY\_NEW) the anchor and the limit number of returned messages are sorted based on direction by time. The messages in the result are sorted in ascending order by time, the earliest message is displayed at the top.

  • API prototype
dart * Query history messages on the local database by the `anchor` and `direction`
 * Query messages earlier than (`QUERY\_OLD`) or later than (`QUERY\_NEW`) the anchor and the `limit` number of returned messages are sorted based on `direction` by time.
 /// The messages in the result are sorted by `time`..
 /// Note: The anchor message is not returned.
Future<NIMResult<List<NIMMessage>>> queryMessageListEx(
      NIMMessage anchor, QueryDirection direction, int limit);
  • Parameters
Parameter Type Description
anchor NIMMessage The anchor used in a query.
direction QueryDirection The direction of a query
limit int The limit of messages per query

The anchor parameter indicates the query anchor, the starting point of a query. The query result does not include the anchor. You cannot set the value to null.

You can use the MessageBuilder.createEmptyMessage(...) method to generate an empty message as an anchor when making the first query. If you want to query messages in the P2P chat with the account accid001, and use 2019-01-15 17:00:00 (the corresponding timestamp is 1547542800000) as the start time, you can configure the anchor as follows:

createEmptyMessage method

dartNIMMessage msg = MessageBuilder.createEmptyMessage("accid001", SessionTypeEnum.P2P, 1547542800000L);

The direction indicates the query direction. QueryDirectionEnum.QUERY_OLD indicates messages earlier than the anchor. QueryDirectionEnum.QUERY_NEW indicates messages later than the anchor. For example, take 2019-01-15 17:00:00 (the corresponding timestamp is 1547542800000) as the anchor:

  • To query messages from 16:59:00 to 17:00:00, set direction to QueryDirectionEnum.QUERY_OLD.

  • To query messages from 17:00:00 to 17:01:00, set direction to QueryDirectionEnum.QUERY_NEW.

  • Example

dart/// Query messages earlier than the anchor with 20 messages, and the results are sorted in descending order by time
final result = await NimCore.instance.messageService.queryMessageListEx(anchor,direction,limit);

Query the last message

Query the most recent message of a specified session.

dart///  [account] target account ID or group ID
///  [sessionType] Session type

Future<NIMResult<NIMMessage>> queryLastMessage(
      String account, NIMSessionType sessionType);

Query messages by uuid

  • API prototype
dart /// Get multiple messages based on message IDs. The first message in the list of messages is supported on Windows and macOS.
 ///  [uuids] The list of message IDs.
 ///  [sessionId] Session ID
 ///  [sessionType] Session type

Future<NIMResult<List<NIMMessage>>> queryMessageListByUuid(
      List<String> uuids,String sessionId,NIMSessionType sessionType);
  • Example
dart// Get multiple messages based on message IDs
List<String> uuids = [message.getUuid()];
final result = await NimCore.instance.messageService.queryMessageListByUuid(uuidsList,sessionId,sessionType);

Delete local messages

Delete a local message

  • API introduction

Delete a specified message

  • API prototype
dart /// Delete a message.
 ///  [message] The message to be deleted
 ///  [ignore] The interface is not supported for Windows and macOS. true: The delete operation is not recorded locally; false: Record the delete operation locally
 /// If you retrieve messages from the IM server and the returned messages contain a message that is deleted from the local database will not be added to the local database.
 /// The delete tag will be overwriten by the clear tag

Future<void> deleteChattingHistory(NIMMessage message, bool ignore);
  • Parameters
Parameter Type Description
message NIMMessage The message to be deleted.
Ignore bool true: The delete operation is not recorded locally; false: The clear operation is recorded locally.
When messages are retrieved from the server, the messages that are deleted locally will not be added in the database.
The deleted tag is overwriten by the cleared tag.
  • Example
dart// Delete a message
await NimCore.instance.messageService.deleteChattingHistory(message,ignore);

Delete multiple messages at a time

  • API introduction

Delete multiple specified messages.

  • API prototype
dart /// Delete multiple messages. The interface is not supported on Windows and macOS.
 ///
 ///  [msgList] Messages to be deleted.
 ///  [ignore] true: The delete operation is not recorded locally; false: Record the delete operation locally
 /// If you retrieve messages from the IM server and the returned messages contain a message that is deleted from the local database will not be added to the local database.
 /// The delete tag will be overwriten by the clear tag

  Future<void> deleteChattingHistoryList(
      List<NIMMessage> msgList, bool ignore);
  • Parameters
Parameter Type Description
msgList List<NIMMessage> Messages to be deleted.
Ignore bool true: The delete operation is not recorded locally; false: The clear operation is recorded locally.
When messages are retrieved from the server, the messages that are deleted locally will not be added in the database.
The deleted tag is overwriten by the cleared tag.
  • Example
dart//  Delete multiple messages
await NimCore.instance.messageService.deleteChattingHistoryList(msgList,ignore);

Delete messages in a specified session

  • API introduction

Delete all messages of a session from the local database, and specify whether to record this clear operation into the database. If the clear operation is recorded, the messages retrieved from the server will not be synchronized to the local database.

dart /// Clear all local messages of a specified user.
 ///
 /// [account]  IM account of the peer in a chat, (`accid`).
 ///  [sessionType] Session type

Future<void> clearChattingHistory(
      String account, NIMSessionType sessionType);
  • Parameters
Parameter Type Description
account String IM account of the peer in a chat, (accid).
sessionType NIMSessionType The ID of a session. If it is a P2P chat, use a user account. For group chats, use a group ID.
  • Example
dart// Record the clear operation.
await NimCore.instance.messageService.clearChattingHistory(account,sessionType);

Delete all messages

The SDK can delete all messages in the database.

dart/// Clear all messages in the database.
/// You can also specify whether the recent sessions are deleted.
/// If the recent contacts is cleared, MsgServiceObserve.observeRecentContactDeleted(Observer, boolean) will be triggered for a notification.
/// [ clearRecent ] Whether the recent sessions are deleted.

Future<void> clearMsgDatabase(bool clearRecent);

Message history in the server

Query message history in the server

The SDK provides interfaces to retrieve messages in the server. The query starts from the anchor (excluded) to toTime based on the direction parameter. The result of messages in a limit number is returned. The query scope is determined by toTime and limit. The parameter that applies first is prioritized. For example, if the messages sent or received between the anchor and toTime is greater than the limit number, the limit number of messages are returned. If less than the limit number, the actual number of messages are returned. The returned result may have a number smaller than the limit..

You can use the MessageBuilder.createEmptyMessage(...) method to generate an empty message as an anchor when making the first query. Messages at the anchor are not returned. The last parameter of this interface can determine whether the retrieved messages are saved to the local database. If you choose to save them locally, you can also get these messages when using the interface for retrieving local messages.

  • API prototype
dart /// Get messages of a specified type in the message history from the IM server. The returned messages in the result is not stored in the local database.
 /// <p>
 * The query starts from the `anchor` (excluded) to `toTime` based on the direction parameter. The result of messages in a limit number is returned. <br>
 /// The query scope is determined by toTime and limit. The parameter that applies first is prioritized. For example, if the messages sent or received between the anchor and toTime is greater than the limit number, the limit number of messages are returned. If less than the limit number, the actual number of messages are returned.
 /// The number of returned messages may be smaller than the limit.
 ///
 /// [anchor] start time. A value of null is not allowed. <br>
 ///                  Set a custom anchor. Create an empty object using {@link MessageBuilder#createEmptyMessage(String, SessionTypeEnum, long)}.<br>
 /// [toTime] The end time of a time range for a query in milliseconds
 /// [limit] The limit of messages returned from a query. A maximum of 100 messages are allowed.
 /// [direction] The query direction. QUERY_OLD: query messages earlier than the `anchor` and sort the result in descending order by time; QUERY_NEW: query messages later than the `anchor` and sort the result in ascending order by time.|
 ///  [msgTypes]  Message types in an array. Message types, 0: text; 1: image; 2: audio; 3: video; 4: location; 5: notification; 6: file; 10: Tip; 100: custom. Other types are invalid.
 /// [persist] Whether roaming messages returned are persisted in the local database.

  Future<NIMResult<List<NIMMessage>>> pullMessageHistoryExType(
      NIMMessage anchor,
      int toTime,
      int limit,
      QueryDirection direction,
      List<NIMMessageType> messageTypeList,
      bool persist);
  • Parameters
Parameter Type Description
anchor NIMMessage The message sent at the start time. A value of null is not allowed.
Set a custom anchor and create an empty message using MessageBuilder#createEmptyMessage.
toTime int The end time of a time range in milliseconds
limit int limit of messages returned from a query. A maximum of 100 messages are allowed.
direction QueryDirection QUERY_OLD: query messages earlier than the anchor and sort the result in descending order by time; QUERY_NEW: query messages later than the anchor and sort the result in ascending order by time.
messageTypeList List<NIMMessageType> Types of messages to be queried.
persist bool Whether roaming messages returned are persisted in the local database.

The anchor parameter indicates the query anchor, the starting point of a query. The query result does not include the anchor. You cannot set the value to null.

You can use the MessageBuilder.createEmptyMessage(...) method to generate an empty message as an anchor when making the first query. If you want to query messages in the P2P chat with the account accid001, and use 2019-01-15 17:00:00 (the corresponding timestamp is 1547542800000) as the start time, you can configure the anchor as follows:

dartNIMMessage msg = MessageBuilder.createEmptyMessage("accid001", SessionTypeEnum.P2P, 1547542800000L);

The direction indicates the query direction. QueryDirectionEnum.QUERY_OLD indicates messages earlier than the anchor. QueryDirectionEnum.QUERY_NEW indicates messages later than the anchor. For example, take 2019-01-15 17:00:00 (the corresponding timestamp is 1547542800000) as the anchor:

  • To query messages from 16:59:00 to 17:00:00, set direction to QueryDirectionEnum.QUERY_OLD.

  • To query messages from 17:00:00 to 17:01:00, set direction to QueryDirectionEnum.QUERY_NEW.

  • Example

dart// Retrieve 100 messages from the server.
long newTime = System.currentTimeMillis();
long oldTime = newTime - 1000 * 60 * 60; // one hour earlier
NIMMessage anchor = MessageBuilder.createEmptyMessage("testAccount", SessionTypeEnum.P2P, newTime);
        var result = await NimCore.instance.messageService.pullMessageHistoryExType(anchor,toTime,limit,direction,mList,persist);

In addition, the following simplified interface is provided:

Get history messages from the server. The returned result is displayed in ascending order. Query a limited number of messages earlier than the anchor. The returned result may have a number smaller than the limit..

dart///
///  [anchor] The anchor for a query.
/// [limit] The limit of messages returned from a query. A maximum of 100 messages are allowed.
/// [persist] Whether messages in chat history returned are persisted in the local database.
///
Future<NIMResult<List<NIMMessage>>> pullMessageHistory(
      NIMMessage anchor, int limit, bool persist);

Query messages by type

You can specify a message type when retrieving messages from the server.

  • API prototype
dart /// [anchor] start time. A value of null is not allowed.
 /// [toTime] The end time of a time range for a query in milliseconds.
 /// [limit] The limit of messages returned from a query. A maximum of 100 messages are allowed.
 /// [direction] The query direction. QUERY_OLD: query messages earlier than the `anchor` and sort the result in descending order by time; QUERY_NEW: query messages later than the `anchor` and sort the result in ascending order by time.|
 ///  [messageTypeList]  Types of messages in array Message types, 0: text; 1: image; 2: audio; 3: video; 4: location; 5: notification; 6: file; 10: Tip; 100: custom. Other types are invalid.
 /// [persist] Whether messages in chat history returned are persisted in the local database.
Future<NIMResult<List<NIMMessage>>> pullMessageHistoryExType(
      NIMMessage anchor,
      int toTime,
      int limit,
      QueryDirection direction,
      List<NIMMessageType> messageTypeList,
      bool persist);

Delete messages from the server

Delete messages in a session from the server

  • API prototype
dart /// Clear history messages.
 ///
 ///  [sessionId]    user account
 ///  [sessionType] Session type
 ///[ sync] Whether data are synced with other devices
Future<void> clearServerHistory(String sessionId, NIMSessionType sessionType,
      bool sync);
  • Parameters
Parameter Type Description
sessionId String User account
sessionType NIMSessionType Session type
sync bool Whether data is synced with other devices
  • Example
dartawait NimCore.instance.messageService.clearServerHistory(sessionId,sessionType,sync);

Delete a message from the server for the current user

After a user deletes a message in the cloud, the account can no longer fetch the message from the server. Other devices that log in to this account cannot load the deleted message. Message history of other accounts is not affected by this operation. After a message is deleted by this operation, the MsgServiceObserve#observeDeleteMsgSelf callback will be triggered.

  • API prototype
dart///
 * Delete a local message and the message stored in the server and roaming message for the current user.
 /// [msg]  The message to be deleted for the current user
 /// [ext] extension field

Future<NIMResult<int>> deleteMsgSelf(NIMMessage msg, String ext);
  • Parameters
Parameter Type Description
msg NIMMessage The message to be deleted for the current user.
ext String The extension field, optional
  • Example
dartvar result = await NimCore.instance.messageService.deleteMsgSelf(message,ext);

Delete multiple messages from the server for the current user

  • API prototype
dart///
 /// Delete multiple messages in a session from the server for the current user
 ///
 /// [msgList] The messages to be deleted for the current user.
 /// [ext] The extension field

Future<NIMResult<int>> deleteMsgListSelf(List<NIMMessage> msgList, String ext);
  • Parameters
Parameter Type Description
msgList List<NIMMessage> Messages to be deleted for the current user.
ext String The extension field
  • Example
dartvar result = await NimCore.instance.messageService.deleteMsgListSelf(mList,ext);

Search for messages

The SDK supports keyword search using the lucene plug-in or the search function that comes with the SDK.

Search for messages in a session (new)

  • API introduction

The SDK allows you to search for messages in a P2P chats. The matched result contains messages of a specified type between startTime and endTime. The messages in the fromAccount list are also added to the result.

  • API prototype
dart    /// Query history messages in the local database.
    /// The matched result contains messages of a specified type between startTime and endTime. The messages in the fromAccount list are also added to the result.
    ///
    ///  [sessionType] Session type
    ///  [sessionId] Session ID
    ///  [option] Options for search
Future<NIMResult<List<NIMMessage>>> searchMessage(NIMSessionType sessionType,
      String sessionId, MessageSearchOption searchOption);

The searchOption parameter contains the following fields:

Parameter Type Description
startTime int The start time. The default value is 0
endTime int The end time. The default value 0 indicates the maximum timestamp. Make sure that endTime must be later than startTime.
limit int The maximum number of returned messages. The default value is 100. A value of 0 indicates that then unlimited number of messages are returned.
order SearchOrderEnum Query direction, the default value SearchOrderEnum.DESC indicates searching from newest message to the earliest messages, and SearchOrderEnum.ASC from the earliest messages to the newest messages. Regardless of the query direction, query results are displayed in ascending order by time.
messageTypes List<NIMMessageType> Message types. Only text messages are available for search by default and allMessageTypes is set to false. The first type in the list is supported on Windows and macOS.
messageSubTypes List<int> Subtypes of messages to be queried.
allMessageTypes bool All types of messages for search. The default value is false. If true, messageType is ignored and messages of all types are returned.
searchContent String Search text. if the type of message is text, the content will be matched.
fromIds List<String> List of message senders.
enableContentTransfer bool Escape the special characters for regular expression to text. The default value is true. The parameter is not supported for Windows and macOS.
  • Example
dart// Search for messages using a keyword, return the latest 100 messages.
MessageSearchOption option = MessageSearchOption( limit: 100,searchContent: 'test')

 var result = await NimCore.instance.messageService.searchMessage(SessionTypeEnum.P2P,"testAccount",option);

Global search (new)

  • API introduction

The SDK allows you to global search for messages. The matched result contains messages of a specified type between startTime and endTime. The messages in the fromAccount list are also added to the result.

  • API prototype
dart  /// Global search for all history messages in the local database.
  /// The matched result contains messages of a specified type between startTime and endTime. The messages in the fromAccount list are also added to the result.
  ///
  ///  [option] Options for search
 Future<NIMResult<List<NIMMessage>>> searchAllMessage(
      MessageSearchOption option);

The option is used for the search. For MessageSearchOption, see the API for search P2P chats

  • Example
dart// Search for messages using a `test` keyword, return the latest 100 messages.
MessageSearchOption option = MessageSearchOption( limit: 100,searchContent: 'test')

var result = await NimCore.instance.messageService.searchAllMessage(searchOption);

Search for P2P messages on the server

  • API prototype
dart /// Search chat history using keywords
 ///
 ///  [otherAccid] Peer account.
 ///  [fromTime] The start time in milliseconds.
 ///  [endTime] The end time in milliseconds.
 ///  [keyword] Keyword for search
 /// [limit] The limit of messages returned from a query. A maximum of 100 messages are allowed.
 /// [reverse] Optional. If the parameter is not specified, false is used by default. A value of true implements a reverse search that starts from the earliest to date and displays the result in descending order. The default value is false, which indicates that the search starts from the current date to the earliest time and displays the result in ascending order.
 Future<NIMResult<List<NIMMessage>>> searchRoamingMsg(
      String otherAccid,
      int fromTime,
      int endTime,
      String keyword,
      int limit,
      bool reverse);
  • Parameters
Parameter Type Description
otherAccid String peer account
fromTime int The start time in milliseconds.
endTime int The end time in milliseconds
keyword String Keyword for search
limit int limit of messages returned from a query. A maximum of 100 messages are allowed.
reverse bool Optional. If the parameter is not specified, false is used by default. A value of true implements a reverse search that starts from the earliest to date and displays the result in descending order. The default value is false, which indicates that the search starts from the current date to the earliest time and displays the result in ascending order.

Global search for message history on the server

  • API prototype
dart /// Global search for history messages in the cloud
 ///
 ///  [config] Configuration for search

  Future<NIMResult<List<NIMMessage>>> searchCloudMessageHistory(
      MessageKeywordSearchConfig config);
  • Parameters

MessageKeywordSearchConfig class

Parameter Type Description
keyword String Keyword used for search.
fromTime int The start time
toTime int The end time
sessionLimit int Limit of sessions
msgLimit int Limit of messages
asc boolean The rule used to sort messages. The default value is false.
p2pList List<String> P2P chats for search. The search scope is specified with this parameter and {@link MsgFullKeywordSearchConfig#teamList} combined
teamList List<String> Groups for search. To query messages in a specified group, use the group ID.
otherAccid String The parameter is required for web apps. IM account of the peer in a P2P chat, (accid).
  • Example
dartMessageKeywordSearchConfig config =MessageKeywordSearchConfig(keyword:'test', startTime:'The start time', endTime:'the end time');

var result = await NimCore.instance.messageService.searchCloudMessageHistory(messageKeywordSearchConfig);
Was this page helpful?
Yes
No
  • Local message history
  • Query local message history
  • Local message history
  • Query local message history
  • createEmptyMessage method
  • Query the last message
  • Query messages by uuid
  • Delete local messages
  • Delete a local message
  • Delete multiple messages at a time
  • Delete messages in a specified session
  • Delete all messages
  • Message history in the server
  • Query message history in the server
  • Query messages by type
  • Delete messages from the server
  • Delete messages in a session from the server
  • Delete a message from the server for the current user
  • Delete multiple messages from the server for the current user
  • Search for messages
  • Local message search
  • Search for messages in a session (new)
  • Global search (new)
  • Search for P2P messages on the server
  • Global search for message history on the server