Message Persistence API for Dart SDK
Message Persistence gives you real-time access to the history of messages published to PubNub. Each message is timestamped to the nearest 10 nanoseconds and stored across multiple availability zones in several geographic locations. You can encrypt stored messages with AES-256 so they are not readable on PubNub’s network. For details, see Message Persistence.
You control how long messages are stored through your account’s retention policy. Options include: 1 day, 7 days, 30 days, 3 months, 6 months, 1 year, or Unlimited.
You can retrieve the following:
- Messages
- Message reactions
- Files (using the File Sharing API)
Batch history
Requires Message Persistence
This method requires that Message Persistence is enabled for your key in the Admin Portal.
This function fetches historical messages from multiple channels. The includeMessageActions or includeActions flag also allows you to fetch message actions along with the messages.
It's possible to control how messages are returned and in what order. For example, you can:
- Search for messages starting on the newest end of the timeline.
- Search for messages from the oldest end of the timeline.
- Page through results by providing a
startORendtimetoken. - Retrieve a slice of the time line by providing both a
startANDendtimetoken. - Retrieve a specific (maximum) number of messages using the
countparameter.
Batch history returns up to 100 messages on a single channel, or 25 per channel on a maximum of 500 channels. Use the start and end timestamps to page through the next batch of messages.
Start & End parameter usage clarity
If you specify only the start parameter (without end), you will receive messages that are older than the start timetoken.
If you specify only the end parameter (without start), you will receive messages from that end timetoken and newer.
Specify values for both start and end parameters to retrieve messages between those timetokens (inclusive of the end value).
Keep in mind that you will still receive a maximum of 100 messages (or 25, for multiple channels) even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the start timetoken are necessary to page through the full set of results if more messages meet the timetoken values.
Method(s)
To run fetchMessages() you can use the following method(s) in the Dart SDK:
1pubnub.batch.fetchMessages(
2 Set<String> channels,
3 {Keyset? keyset,
4 String? using,
5 int? count,
6 Timetoken? start,
7 Timetoken? end,
8 bool? reverse,
9 bool? includeMeta,
10 bool includeMessageActions = false,
11 bool includeMessageType = true,
12 bool includeCustomMessageType,
13 bool includeUUID = true}
14)
| Parameter | Description |
|---|---|
channels *Type: Set<String>Default: n/a | Specifies channels to return history messages from. |
keysetType: KeysetDefault: n/a | Override for the PubNub default keyset configuration. |
usingType: StringDefault: n/a | Keyset name from the keysetStore to be used for this method call. |
countType: intDefault: n/a | The paging object used for pagination. Set count to specify the number of historical messages to return per channel.If includeMessageActions is false, then 100 is the default (and maximum) value. Otherwise it's 25.Set start to delimit the start of time slice (exclusive) to pull messages from.Set end to delimit the end of time slice (inclusive) to pull messages from. |
startType: Timetoken Default: n/a | timetoken denoting the start of the range requested (return values will be less than start). |
endType: Timetoken Default: n/a | timetoken denoting the end of the range requested (return values will be greater than or equal to end). |
reverseType: boolDefault: false | Setting to true traverses the time line in reverse, starting with the oldest message first. |
includeMetaType: boolDefault: false | Whether to include message metadata within response or not. |
includeMessageActionsType: boolDefault: false | The flag denoting to retrieve history messages with message actions. If true, the method is limited to one channel only. |
includeMessageTypeType: boolDefault: true | The flag denoting to retrieve history messages with message type. |
includeCustomMessageTypeType: boolDefault: false | Indicates whether to retrieve messages with the custom message type. For more information, refer to Retrieving Messages. |
includeUUIDType: boolDefault: n/a | The flag denoting to include message sender's UUID. |
Sample code
Reference code
Retrieve the last 25 messages on a channel:
1import 'package:pubnub/pubnub.dart';
2
3void main() async {
4 // Create a PubNub instance with the default keyset.
5 var pubnub = PubNub(
6 defaultKeyset: Keyset(
7 subscribeKey: 'demo',
8 publishKey: 'demo',
9 userId: UserId('myUniqueUserId'),
10 ),
11 );
12
13 // Channels to fetch history from
14 Set<String> channels = {'my_channel'};
15
show all 30 linesReturns
The fetchMessages() operation returns a map of channels and a List<BatchHistoryResultEntry>:
| Property | Description |
|---|---|
channelsType: Map<String, List<BatchHistoryResultEntry>> | Map of channels and their respective lists of BatchHistoryResultEntry. See BatchHistoryResultEntry for more details. |
BatchHistoryResultEntry
| Method | Description |
|---|---|
messageType: dynamic | The message content. |
timetokenType: Timetoken | Timetoken of the message. Always returned by default. |
uuidType: String | UUID of the sender. |
actionsType: Map<String, dynamic>? | If includeMessageActions was true, this contains message actions. Otherwise, it's null. |
messageTypeType: MessageType | Internal type of the message. |
customMessageTypeType: String? | Custom type of the message. null if empty. |
metaType: Map<String, dynamic> | If includeMeta was true, this contains message metadata. Otherwise, it's null. |
errorType: PubNubException? | The exception thrown if message decryption failed for a given message. |
Other examples
Paging history Responses
1 var messages = <BatchHistoryResultEntry>[];
2 var channel = 'my_channel';
3 var loopResult, start, count;
4 do {
5 loopResult =
6 await pubnub.batch.fetchMessages({channel}, start: start, count: count);
7
8 messages.addAll((loopResult as BatchHistoryResult).channels[channel]!);
9
10 if ((loopResult).more != null) {
11 var more = loopResult.more as MoreHistory;
12 start = Timetoken(BigInt.parse(more.start));
13 count = more.count;
14 }
15 } while (loopResult.more != null);
Delete messages from history
Requires Message Persistence
This method requires that Message Persistence is enabled for your key in the Admin Portal.
Removes the messages from the history of a specific channel.
Required setting
There is a setting to accept delete from history requests for a key, which you must enable by checking the Enable Delete-From-History checkbox in the key settings for your key in the Admin Portal.
Requires Initialization with secret key.
Method(s)
To deleteMessages() you can use the following method(s) in the Dart SDK.
1pubnub.delete()
| Parameter | Description |
|---|---|
channels *Type: List<String> | Specifies channels to delete messages from. |
startType: Long | Timetoken delimiting the start of time slice (inclusive) to delete messages from. |
endType: Long | Timetoken delimiting the end of time slice (exclusive) to delete messages from. |
Sample code
1await pubnub
2 .channel('channel-name')
3 .messages(
4 from: Timetoken(BigInt.parse('123345')),
5 to: Timetoken(BigInt.parse('123538293')),
6 )
7 .delete();
Other examples
Delete specific message from history
To delete a specific message, pass the publish timetoken (received from a successful publish) in the End parameter and timetoken +/- 1 in the Start parameter. For example, if 15526611838554310 is the publish timetoken, pass 15526611838554309 in Start and 15526611838554310 in End parameters respectively as shown in the following code snippet.
1await pubnub
2 .channel('channel-name')
3 .messages(
4 from: Timetoken(BigInt.parse('15526611838554309')),
5 to: Timetoken(BigInt.parse('15526611838554310')),
6 )
7 .delete();
Message counts
Requires Message Persistence
This method requires that Message Persistence is enabled for your key in the Admin Portal.
Returns the number of messages published on one or more channels since a given time. The count returned is the number of messages in history with a timetoken value greater than or equal to than the passed value in the channelsTimetokenparameter.
Unlimited message retention
For keys with unlimited message retention enabled, this method considers only messages published in the last 7 days.
Method(s)
To run messageCounts() you can use the following method(s) in the Dart SDK:
1pubnub.batch.countMessages(
2 dynamic channels,
3 {Keyset? keyset,
4 String? using,
5 Timetoken? timetoken}
6)
| Parameter | Description |
|---|---|
channels *Type: Map<String, Timetoken> or Set<String> | Specifies channels set. Or Map of channel names and timetoken for message count. |
keysetType: Keyset | Override for the PubNub default keyset configuration. |
usingType: String | Keyset name from the keysetStore to be used for this method call. |
timetokenType: Timetoken | timetoken is required when channels is a Set of channel names. |
Sample code
1var result = await pubnub.batch.countMessages({'my_channel'},
2 timetoken: Timetoken(BigInt.from(13406746780720711)));
Returns
This operation returns a CountMessagesResult which contains the following property:
| Property Name | Type | Description |
|---|---|---|
channels | Map<String, int> | Channel names with message count. |
History (deprecated)
Requires Message Persistence
This method requires that Message Persistence is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
This function fetches historical messages of a channel.
It's possible to control how messages are returned and in what order, for example you can:
- Search for messages starting on the newest end of the timeline (default behavior -
reverse=false) - Search for messages from the oldest end of the timeline by setting
reversetotrue. - Page through results by providing a
startORendtimetoken. - Retrieve a slice of the time line by providing both a
startANDendtimetoken. - Limit the number of messages to a specific quantity using the
countparameter.
Start & End parameter usage clarity
If only the start parameter is specified (without end), you will receive messages that are older than and up to that start timetoken value. If only the end parameter is specified (without start) you will receive messages that match that end timetoken value and newer. Specifying values for both start and end parameters will return messages between those timetoken values (inclusive on the end value). Keep in mind that you will still receive a maximum of 100 messages even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the start timetoken is necessary to page through the full set of results if more than 100 messages meet the timetoken values.
Method(s)
To run history() you can use the following method(s) in the Dart SDK:
1pubnub.channel(String).history(
2 {ChannelHistoryOrder order = ChannelHistoryOrder.descending,
3 int chunkSize = 100}
4)
5
6// OR
7
8pubnub.channel(String).messages()
| Parameter | Description |
|---|---|
order *Type: ChannelHistoryOrderDefault: ChannelHistoryOrder.descending | Order of messages based on timetoken. Refer to Channel History Order for more details. |
chunkSizeType: intDefault: false | Number of returned messages. |
Channel history order
| Parameter | Description |
|---|---|
ascendingType: const ChannelHistoryOrder | Ascending order of messages, based on timetokens. |
descendingType: const ChannelHistoryOrder | Descending order of messages, based on timetokens. |
valuesType: const List<ChannelHistoryOrder> | A constant list of the values in this enum, in order of their declaration. |
Sample code
Retrieve the last 100 messages on a channel:
1var history = pubnub.channel('my_channel').history(chunkSize: 100);
Returns
The history() operation returns a PaginatedChannelHistory which contains the following properties:
| Property | Description |
|---|---|
chunkSizeType: int | Maximum number of fetched messages when calling more(). |
endTimetokenType: Timetoken | Upper boundary of fetched messages timetokens. |
hasMoreType: bool | Returns true if there are more messages to be fetched. Keep in mind, that before the first more call, it will always be true. |
messagesType: List<BaseMessage> | Readonly list of messages. It will be empty before first more call. Refer to the method description below for more details on the more call. |
orderType: ChannelHistoryOrder | Order of messages based on timetoken. Refer to Channel History Order for more details. |
startTimetokenType: Long | Lower boundary of fetched messages timetokens. |
PaginatedChannelHistory has the following methods:
| Method | Returns | Description |
|---|---|---|
more | Future<FetchHistoryResult> | Fetches more messages and stores them in the messages property of PaginatedChannelHistory. |
reset | void | Resets the history to the beginning. |
Base message
| Parameter | Description |
|---|---|
contentType: dynamic | The message content. |
messageType: dynamic | Alias for content. |
originalMessageType: dynamic | Original JSON message received from the server. |
publishedAtType: Timetoken | Timetoken at which the server accepted the message. |
timetokenType: Timetoken | Alias for timetoken. |
Other examples
Use history() to retrieve the three oldest messages by retrieving from the time line in reverse
1var history = pubnub
2 .channel('my_channel')
3 .history(order: ChannelHistoryOrder.ascending, chunkSize: 3)
Response
1{
2 "messages":[
3 {
4 "Timetoken": 0,
5 "message": "Pub1"
6 },
7 {
8 "Timetoken": 0,
9 "message": "Pub2"
10 },
11 {
12 "Timetoken": 0,
13 "message": "Pub3"
14 }
15 ],
show all 18 linesHistory paging example
1var history = pubnub.channel('asdf').history(chunkSize: 100, order: ChannelHistoryOrder.descending);
2// To fetch next page:
3await history.more();
4// To access messages:
5print(history.messages);