diff --git a/.gitignore b/.gitignore index 19e558c..f1fc372 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ # Created by .ignore support plugin (hsz.mobi) npm-debug.log +.idea diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..5563665 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,4 @@ +README.md +CHANGELOG.md +LICENSE.md +*.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 4154ba7..43e660b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,107 +1,1173 @@ -Changelog -========= +# Changelog +## v3.1.33 (Aug 24, 2023) +> **Thank you everyone for using our SDK v3. This is our final release as we transition to our latest SDK v4 (first released in Apr 2022). Please reach out to our support if you have any questions.** +### Improvements +- Fixed a bug where called `ChangeLogAPI` infinitely +## v3.1.32 (JAN 31, 2023) +### Improvements +- Fixed a bug where `sb.connect()` fails in React Native due to unexpected `localStorage` access + +## v3.1.31 (JAN 25, 2023) +### Improvements +- Fixed a bug where `pendingMessage.data` is set to 'null' string when `sendUserMessage()` is called with a message text as an argument +- Fixed a bug where `MessageCollection` calls `onMessagesUpdated()` with old messages on connect and reconnect when `localCacheEnabled` is set to false + +## v3.1.30 (JAN 10, 2023) +### Improvements +- Fixed a bug where MessageCollection is logging quota exceeded errors when local storage is full +- Improved stability + +## v3.1.29 (NOV 04, 2022) +### Improvements +- Changed ackStateMap cleanup time when disconnect is called +- Fixed Message Filter in LocalCache not working with customTypes + +## v3.1.28 (OCT 27, 2022) +- Fixed a bug where `channel.sendFileMessage()` fails when it is called in a web worker, `Worker` + +## v3.1.27 (SEP 23, 2022) +- Fixed onMessageUpdate being called for the same message in View after checking HugeGap when connecting or reconnecting +- Fixed a bug in group channel changelogs + +## v3.1.26 (SEP 7, 2022) +- Fixed wrong includeMetaArray property happening during changelog sync + +## v3.1.25 (AUG 31, 2022) +- Implemented channel membership history where clients can retrieve whether users have joined or left the channel +- Improved stability + +## v3.1.24 (AUG 119, 2022) +- Fixed Promise polyfill for browsers that do not support 'Promise.finally()' +- Improved stability + +## v3.1.23 (AUG 03, 2022) +- Fixed a bug where `message.mentionedUsers` is not updated when `updateUserMessage()` is called with `messageParams.mentionedUserIds` set to an empty array +- Improved stability + +## v3.1.22 (JUL 25, 2022) +- Added `sb.setOnlineListener()` and `sb.setOfflineListener()` interfaces for non-browser environments +- Improved stability + +## v3.1.21 (JUL 20, 2022) +- File upload failed messages are now resendable through `channel.resendFileMessage()`. +- Fixed a bug where `groupChannelCollection.onChannelsUpdated()` is not called when `groupChannel.lastMessage` is updated. +- When local cache is enabled, conversion of pending messages that are not registered for auto-resend to failed messages is now being processed only when `sb.connect()` is called by customer. +- `channel.resendFileMessage()` now considers `fileMessage.messageParams.file` if blob is not given as an argument. +- Improved stability. + +## v3.1.20 (JUN 30, 2022) +- Fixed File upload error with PUT requests in RN. + +## v3.1.19 (JUN 24, 2022) +- Fixed a bug in `BaseChannel.resendFileMessage()` such that `reqId` of resent message is the same as `reqId` of the original failed message. + +## v3.1.18 (JUN 22, 2022) +- Fixed incorrect failedMessage validation in resendFileMessage() +- Fixed issue in loading messages from cache using default limit +- Fixed incorrect type definition of CustomTypesFilterProperty in PreviousMessageListQuery +- Added nickname startswith/nickname exact match filter in groupChannelListQuery +- Fixed error occurs after deleteReaction in RN +## v3.1.17 (JUN 10, 2022) +- Fixed bug that enables custom typed messages being filtered out of message collection + +## v3.1.16 (MAY 31, 2022) +- Fixed bug TypingStatusUpdate event does not work in GroupChannelCollection. +- Fixed Wrong Type definition in SendBird.d.ts +- Fixed bug Android file upload is not working(RN) +## v3.1.14 (MAY 20, 2022) +- Fixed bug SessionHandlers Broken. + +## v3.1.13 (MAY 11, 2022) +- Fixed incorrect type in User.lastSeenAt. +- Fixed bug when createChannelWithUserIds without callback. +- Fixed bug "operators is not defined" on `CHANNEL_OPERATOR_UPDATE` event. +- Added `HiddenChannelFilter.ALL`. +- Update `axios` library. + +## v3.1.11 (APR 29, 2022) +- Fixed bug when reading unsent file message from local cache in React Native. +- Fixed bug storing cached metadata into local cache in `BaseChannel`. + +## v3.1.10 (APR 04, 2022) +- Fixed issue of MessageCollection changelog partially not updating/deleting cached messages. +- Fixed type error of `isUserMessage()` being undefined. + +## v3.1.9 (MAR 16, 2022) +- Deprecated `ConnectionManager` in `SendBird`. +- Fixed wrong channel list order in `GroupChannelCollection`. +- Added GroupChannelTotalUnreadChannelCountParams. +- Added `getTotalUnreadChannelCount(params)` in `SendBird`. + +## v3.1.8 (FEB 11, 2022) +- Fixed duplicate file messages being sent by `sendFileMessage()` in React Native. +- Fixed new messages not being fetched on websocket connect/reconnect in `MessageCollection`. + +## v3.1.7 (JAN 07, 2022) +- Applied type narrowing to `BaseMessage`, `BaseChannel` and `messageCallback`. +- Replaced all `File` type with the new `FileType` for React Native support. +- Fixed create channel with cover image error in React Native. +- Fixed child message's `parentMessage` update on parent message update when local cache is enabled. +- Added `applyParentMessage` in `BaseMessage`. +- Improved stability. + +## v3.1.6 (DEC 29, 2021) +- Bug-fix in retrying reconnect with application settings. +- Fixed type definitions to `enum`. + +## v3.1.5 (DEC 24, 2021) +- Fixed pending message not being added to a message collection issue when local cache enabled in React Native. +- All properties of `MessageSearchQueryOptions` are now made optional. +- Added type definitions `PUSH_TEMPLATE_DEFAULT` and `PUSH_TEMPLATE_ALTERNATIVE` in `SendBird`. +- Added `clearCachedData()` interface in `SendBird` for local caching. + +## v3.1.4 (DEC 14, 2021) +- Improved stability. + +## v3.1.3 (DEC 10, 2021) +- Added `useAsyncStorageAsDatabase` in `SendBird` for React Native. +- Fixed type signatures: + - Fixed `setOrder` in `GroupChannelCollection`. + - Fixed `next` in `OpenChannelListQuery`. + - Fixed `load` in `PreviousMessageListQuery`. +- Improved stability. + +## v3.1.2 (DEC 1, 2021) +- Fixed TypeScript interface in `PreviousMessageListQuery`. +- Deprecated `includeReplies` and `includeParentMessageText`. +- Added `replyType` and `includeParentMessageInfo`. + +## v3.1.1 (NOV 24, 2021) +- `dns` dependency removed. + +## v3.1.0 (NOV 23, 2021) +- Added local caching support (see the [details](https://sendbird.com/docs/chat/v3/javascript/guides/local-caching)): + - Added `GroupChannelCollection`. + - Added `GroupChannelCollectionHandler`. + - Added `GroupChannelContext`. + - Added `MessageCollectionInitPolicy`. + - Added `MessageCollection`. + - Added `MessageCollectionHandler`. + - Added `MessageContext`. + - Added `CollectionEventSource`. + - Added new parameter `localCacheEnabled` in `SendBird` constructor. + - Added `GroupChannelFilter` in `SendBird`. + - Added `MessageFilter` enum in `SendBird`. + - Added `messageParams` in `UserMessage`. + - Added `messageParams` in `FileMessage`. + - Added `clearCachedMessages()` in `SendBird`. +- Added reply to channel feature: + - Added `includeParentMessageInfo` in `MessageRetrievalParams`. + - Added `includeParentMessageInfo` in `MessageListParams`. + - Added `includeParentMessageInfo` in `PreviousMessageListQuery`. + - Added `includeParentMessageInfo` in `ThreadedMessageListParams`. + - Added `includeParentMessageInfo` in `MessageChangeLogsParams`. + - Added `parentMessage` in `BaseMessage`. + - Deprecated `includeParentMessageText` in `MessageRetrievalParams`. + - Deprecated `includeParentMessageText` in `MessageListParams`. + - Deprecated `includeParentMessageText` in `PreviousMessageListQuery`. + - Deprecated `includeParentMessageText` in `ThreadedMessageListParams`. + - Deprecated `includeParentMessageText` in `MessageChangeLogsParams`. + - Added `isReplyToChannel` in `UserMessageParams`. + - Added `isReplyToChannel` in `FileMessageParams`. + - Added `isReplyToChannel` in `BaseMessage`. + - Added `replyType` in `MessageListParams`. + - Added `replyType` in `PreviousMessageListQuery`. + - Added `replyType` in `MessageChangeLogsParams`. + - Added `ReplyType` enum in `BaseMessage`. + - Deprecated `includeReplies` in `MessageListParams`. + - Deprecated `includeReplies` in `PreviousMessageListQuery`. + - Deprecated `includeReplies` in `MessageChangeLogsParams`. +- Added `belongsTo()` in `MessageListParams`. + +## v3.0.160(OCT 29, 2021) +- Improved stability. + +## v3.0.159(OCT 26, 2021) +- Changed `User` to `RestrictedUser` when `MutedUserListQuery` and `BannedUserListQuery` fetch users. +- Changed `User` to `RestrictedUser` in `onUserMuted` and `onUserBanned` in `ChannelHandler`. +- Added `restrictionInfo` in `Member`. + +## v3.0.158(OCT 06, 2021) +- Improved stability. + +## v3.0.157(OCT 01, 2021) +- Downgraded ws version from 8.2.0 to 7.5.5 due to Webpack 5 build error. + +## v3.0.156(SEP 24, 2021) +- Added `markAsRead(callback)` in `GroupChannel`. +- Deprecated `markAsRead()` in `GroupChannel`. + +## v3.0.155(SEP 1, 2021) +- Added `includeReactions` in `MessageRetrievalParams`. +- Resolved security advisory on `ws` dependency with version upgrade. + +## v3.0.154(AUG 6, 2021) +- Added `metadataKey`, `metadataValues` and `metadataValueStartsWith` in `GroupChannelListQuery` and `PublicGroupChannelListQuery`. +- Optimized Supergroup protocol handling to improve performance for specific use cases. +- Improved stability. + +## v3.0.153(JUN 11, 2021) +- Improved stability. + +## v3.0.152(JUN 10, 2021) +- Added `getMessage()` in `BaseMessage`. + +## v3.0.151(MAY 28, 2021) +- Added `MessageTypeFilter` in `BaseChannel`. +- Improved stability. + +## v3.0.150(MAY 26, 2021) +- Added `joinedAt` in `GroupChannel`. +- Improved stability. + +## v3.0.149(APR 20, 2021) +- Added `NONE` log level in `LogLevel`. +- Improved stability. + +## v3.0.148(MAR 31, 2021) + +- Added `AppleCriticalAlertOptions` interface. +- Added `appleCriticalAlertOptions` in `BaseMessage`, `UserMessageParams`, `FileMessageParams`, `ScheduledUserMessage`, and `ScheduledUserMessageParams`. +- Downgraded log level from `ERROR` to `DEBUG` for all internal API calls. + +## v3.0.147(MAR 24, 2021) + +- Added `onChannelMemberCountChanged` and `onChannelParticipantCountChanged` in `ChannelHandler`. +- Changed `markAsDelivered` policy to remove rate limit timer. +- Improved stability. + +## v3.0.145(MAR 05, 2021) + +- Added `getCachedMetaData()` in BaseChannel. +- Corrected type signatures in `getMessagesByTimestamp()` and `getMessagesByMessageId()`. +- Corrected attribute name to `reverse` in `MessageListParams`. + +## v3.0.144(FEB 19, 2021) + +- Add & Delete reaction API bug-fix to support emoji code and URI encoding. +- React native bug fix: Group channel static `buildFromSerializedData()`. + +## v3.0.143(FEB 04, 2021) + +- IE11 compatibility fix for `getPreviousMessagesByID()`. +- Deprecated `markAsDelivered()` in `GroupChannel`. +- Improved stability. + +## v3.0.142(JAN 11, 2021) + +- Added `sendingStatus` to `AdminMessage`. +- Updated TypeScript DefinitelyTyped file for Promise feature support. +- Resolved security advisory on `axios` dependency. +- Improved stability. + +## v3.0.141(DEC 21, 2020) + +- Added a setter for `operators` in `OpenChannelParams`. +- Added `getLogLevel()` and `setLogLevel()` in `SendBird`. +- Improved stability. + +## v3.0.140(NOV 25, 2020) + +- Bug-fix in connection management. +- Minor bug fixed. + +## v3.0.139(NOV 25, 2020) (DEPRECATED) + +- Removed `addOperator()`, `addOperators()`, `addOperatorUserId()`, `addOperatorUserIds()` from `OpenChannelParams`. +- Improved stability. + +## v3.0.138(OCT 30, 2020) + +- Added `getAllowFriendDiscovery()` and `setAllowFriendDiscovery()` in `SendBird`. + - If it's set to `false`, `uploadFriendDiscoveries()` called by others does not add the user as a friend. +- Set `size` in `FileMessage` automatically. +- Improved stability. + +## v3.0.137(OCT 21, 2020) + +- Bug-fix in `profileUrl`. + +## v3.0.136(OCT 16, 2020) (DEPRECATED) + +- Added `showSubchannelMessagesOnly` in `MessageListParams` and `PreviousMessageListQuery`. +- Bug-fix in `profileUrl` not showing in `Sender`. +- Improved stability. + +## v3.0.135(OCT 8, 2020) + +- Bug-fix in outdated `isMuted` in `Member`. +- Bug-fix in error handling. + +## v3.0.134(SEP 17, 2020) + +- Added `getTypingUsers()` in `GroupChannel`. + - It returns the users even if the user is not in `members`. + - Deprecated `getTypingMembers()` in `GroupChanenl`. +- Set `url` as visible in `FileMessage` object. +- Set `profileUrl` as visible in `User` object. +- Bug-fix in error handling +- Improved stability. + +## v3.0.133(SEP 4, 2020) + +- Added `nicknameStartsWithFilter` in `ApplicationUserListQuery`. + +## v3.0.132(AUG 21, 2020) + +- Added `creator` in `BaseChannel`. +- Added `isOperatorMessage` in `BaseMessage`. +- Added `copyUserMessage()` and `copyFileMessage()` in `BaseChannel`. +- Change the type of all `messageId`s to `number`. +- Bug-fix in wrong channel info in `onChannelFrozen` callback. +- Bug-fix in unread member count and unread delivery count. + +## v3.0.131(AUG 7, 2020) + +- Fixed duplicated `appInfo` in `SendBird.d.ts`. + +## v3.0.130(AUG 7, 2020) (DEPRECATED) + +- Added `order` in `GroupChannelMemberListQuery`. The value could be `member_nickname_alphabetical` (default) or `operator_then_member_alphabetical`. +- Added `isMuted` in `Member`. +- Removed value type check in `channel.createMetaData()` and `channel.updateMetaData()`. +- Bug-fix on `profileUrl` setter. + +## v3.0.129(JUL 24, 2020) + +- Renamed `includeReaction` to `includeReactions` in `channel.getMessageChangeLogs()` (`includeReaction` is deprecated). +- Added `ogMetaData` in `BaseMessage`. + - `ogMetaData` holds open graph properties including `title`, `url`, `description`, and `defaultImage`. + - `ogMetaData.defaultImage` has the image-related properties including `url`, `secureUrl`, `type`, `width`, `height`, `alt` as defined in the target website. + - `ogMetaData` may not be set at the moment of sending. Once the message is sent, Sendbird service would fetch and analyze the open graph property and give the result as a form of message update event. + +## v3.0.128(JUL 10, 2020) + +- Added `addOperators()` and `removeOperators()` in `GroupChannel` and `OpenChannel`. +- Bug-fix in missing `data` field of file message. + +## v3.0.127(JUN 26, 2020) + +- Added a dependency for `axios` and `form-data`. + - Please add [axios](https://github.com/axios/axios) to the `script` tag if you're using SendBird by copy-and-paste the `SendBird.min.js` file. +- Added `getUnreadMemberCount()` and `getUndeliveredMemberCount()` in `GroupChannel`. + - Deprecated `getReadReceipt()` and `getDeliveryReceipt()` in `GroupChannel`. +- Bug-fix in updating operators in `GroupChannel`. + +## v3.0.126(JUN 16, 2020) + +- Bug-fixes in message threading. +- Improved stability. + +## v3.0.125(JUN 1, 2020) + +- Added `includeFrozen` property in `GroupChannelListQuery`, `PublicGroupChannelListQuery`, `OpenChannelListQuery` and `GroupChannelChangeLogsParams`. +- Added `GroupChannelChangeLogsParams`. +- Added `getMyGroupChannelChangeLogsByToken()` and `getMyGroupChannelChangeLogsByTimestamp()` with `GroupChannelChangeLogsParams` in `SendBird`. +- Deprecated some `getMyGroupChannelChangeLogsByToken()` and `getMyGroupChannelChangeLogsByTimestamp()` in `SendBird`. +- Bug-fix: Failure in applying reactions. +- Bug-fix: Invalid `channelUrl` on `getMessage()`. + +## v3.0.124(MAY 23, 2020) + +- Bug-fix: Failure in `getMessageList()`. + +## v3.0.123(MAY 22, 2020) + +- Added message thread feature support + - Added `parentMessageId`, `parentMessageText`, `threadInfo` in `UserMessage` and `FileMessage`. + - Added `onThreadInfoUpdated()` in `ChannelHandler`. + - Added `getThreadedMessagesByTimestamp()`, `applyThreadInfoUpdateEvent()` in `UserMessage` and `FileMessage`. + - Added thread-related parameters in `GroupChannelListQuery`. +- Added emoji feature support + - Added `getAllEmoji()`, `getEmojiCategory()`, and `getEmoji()` in `SendBird`. +- Added parameter classes for message retrieval. +- Bug-fix: Crash on IE strict mode. + +## v3.0.122(APR 29, 2020) + +- Added `metaArrays` in `UserMessageParams` and `FileMessageParams`. + - Message could be sent with predefined `metaArrays`. + +## v3.0.121(APR 10, 2020) + +- Improved stability. + +## v3.0.120(APR 7, 2020) + +- `webpack` build failure fix. +- Improved stability. + +## v3.0.119(MAR 11, 2020) + +- Added `sendingStatus` in `UserMessage` and `FileMessage`. +- Added `role` in `Member`. +- Added `onOperatorUpdated` in `ChannelHandler`. +- Deprecated `requestState` in `UserMessage` and `FileMessage`. +- Improved stability. + +## v3.0.118(MAR 5, 2020) + +- Added version control over the final state of `reactions`. +- Improved stability. + +## v3.0.117(JAN 15, 2020) + +- Added `createMessageSearchQuery()` in `SendBird`. + - `MessageSearchQuery` searches messages with the keyword. + - Options like `exactMatch`, `channelUrl`, `channelCustomType`, `messageTimestampFrom`, `messageTimestampTo`, `order` are available for fine-tuned search. +- Improved stability. + +## v3.0.116(JAN 10, 2020) + +- Improved stability. + +## v3.0.115(DEC 24, 2019) + +- Added `reactions` in `BaseMessage`. + - Added `addReaction()`, `deleteReaction()` in `BaseChannel`. + - Added `onReactionUpdated()` in `ChannelHandler`. + - Added `applyReactionEvent()` in `BaseMessage`. + - Added `includeReaction` parameter to `get**MessagesByID()`, `get**MessagesByTimestamp()` in `BaseChannel`. + - Added `includeReaction` parameter to `getMessageChangeLogsByID()`, `getMessageChangeLogsByTimestamp()` in `BaseChannel`. +- Added `markAsDelivered()`, `getDeliveryReceipt()` in `GroupChannel`. + - Added `onDeliveryReceiptUpdated` in `ChannelHandler`. +- Improved stability. + +## v3.0.114(DEC 18, 2019) + +- Bug-fix in file uploading. +- Improved stability. + +## v3.0.113(DEC 4, 2019) + +- Added `errorCode` and `isResendable()` in `UserMessage` and `FileMessage`. + - `resendUserMessage()` and `resendFileMessage()` work only when `isResendable()` is `true`. +- Improved stability. + +## v3.0.112(NOV 8, 2019) + +- Added `updateCurrentUserInfoWithPreferredLanguages()` in `SendBird`. + - When `preferredLanguages` is set, push notification message would get translated with target languages. +- Added `preferredLanguages` in `User`. +- Added `messageOffsetTimestamp` in `GroupChannel`. +- Added `reqId` for the `BaseMessage`s which are fetched from API call. +- Improved stability. + +## v3.0.111(OCT 25, 2019) + +- Compatibility fix for React Native and Internet Explorer 10. +- Improved stability. + +## v3.0.110(OCT 23, 2019) + +- Improved stability. + +## v3.0.109(OCT 22, 2019) + +- Added support for Promise pattern (BETA) + - except `sendUserMessage()`, `sendFileMessage()`, `cancelUploadingFileMessage()` +- Added `report()`, `reportUser()` and `reportMessage()` in `BaseChannel`. +- Added `onTotalUnreadMessageCountUpdated` in `UserEventHandler`. + - `onTotalUnreadMessageCountUpdated` is called when total unread message count is updated. +- Improved stability. + +## v3.0.108(SEP 9, 2019) + +- Improved stability. + +## v3.0.106(AUG 23, 2019) + +- Improved stability. + +## v3.0.105(AUG 16, 2019) + +- Added `translateUserMessage()` in `BaseChannel` to support on-demand translation. +- Added `resendFileMessage()` in `BaseChannel` to support resend file message with `Blob` object. +- Added `metaArrays` property in `BaseMessage` and deprecated `metaArray`. + - `metaArrays` is an array which contains `MessageMetaArray` instances. + - `MessageMetaArray` is a pair of key and a value array. + - `metaArrays` keeps the inserted order. +- Added `isStrict()` and `setStrict()` in `GroupChannelParams` to set strict channel creation mode. + - When the strict mode is `true`, creating channel with a invalid user will fail. +- Improved stability. + +## v3.0.104(JUL 22, 2019) + +- Improved stability. + +## v3.0.103(JUN 14, 2019) + +- Improved stability. + +## v3.0.102(JUN 11, 2019) + +- Fixed a bug about TypeScript. + +## v3.0.101(JUN 11, 2019) + +- Improved stability. +- Added `resendUserMessage()` in `BaseChannel` to retry to send a `UserMessage` which has `requestID`. +- Added `requestState` and enum `MessageRequestState` which has NONE, PENDING, FAILED, and SUCCEEDED in `SendBird`. +- Added `myLastRead` in `GroupChannel` to detect last read timestamp of current connected user. + +## v3.0.100(MAY 17, 2019) + +- Improved stability. +- Added `delete()` in `GroupChannel` to delete the `GroupChannel`. Only operators can do this action. + +## v3.0.99(MAY 3, 2019) + +- Added `isDiscoverable` property to `GroupChannel` and `GroupChannelParams`. + - if `isDiscoverable` of a public group channel is set to false, then the channel will not appear during querying with `PublicGroupChannelListQuery`. (default: true) + +## v3.0.98(APR 5, 2019) + +- Improved stability. + +## v3.0.97(MAR 14, 2019) + +- Improved stability. + +## v3.0.96(FEB 21, 2019) + +- Minor bug fixed. + +## v3.0.95(FEB 21, 2019) + +- Minor bug fixed. + +## v3.0.94(FEB 14, 2019) + +- Improved stability. +- Minor bug fixed. +- Updated `SendBird.d.ts` file for TypeScript. + +## v3.0.93(JAN 17, 2019) + +- Add push trigger option to enable/disable remote push notification. + - Added `setPushTriggerOption(option, callback)` to `SendBird`. It determines whether the current user receives remote push notification in all group channels. + - Added `getPushTriggerOption(callback)` to `SendBird`. It returns the current push trigger option setting for all group channels. + - Added `setMyPushTriggerOption(option, callback)` to `GroupChannel`. It determines whether the current user receives remote push notification in the group channel. + - Added `getMyPushTriggerOption(callback)` to `GroupChannel`. It returns the current push trigger option setting for the group channel. +- Snooze or stop snooze remote push notification in specific duration. + - Added `setSnoozePeriod(snoozeOn, startTs, endTs, callback)` into `SendBird`. It enables or disables snooze in the period. + - Added `getSnoozePeriod(callback)` into `SendBird`. It returns the current snooze setting for the current user. + +## v3.0.92(DEC 13, 2018) + +- Minor bug fixed. + +## v3.0.91(NOV 30, 2018) + +- Minor bug fixed. + +## v3.0.90(NOV 23, 2018) + +- Minor bug fixed. + +## v3.0.89(NOV 22, 2018) + +- Added `createDistinctChannelIfNotExist()` in `GroupChannel`. + - It creates distinct channel and gets the channel with `isCreated` flag which represents whether the channel is actually created or not. +- Added `getMessageChangeLogsByTimestamp()` in `SendBird`. + - It retrieves message change logs since the given timestamp. +- Added `hiddenState` property in `GroupChannel` to get channel's hidden state. + - `unhidden`: It's not hidden channel. + - `hidden-allow-auto-unhide`: It's hidden channel which is automatically unhidden when new message comes in. + - `hidden-prevent-auto-unhide`: It's hidden channel which is not unhidden when new message comes in. +- Added `allowAutoUnhide` as the second parameter into `hide()` to allow automatic unhide on new message. +- Added `unhide()` in `GroupChannel` to manually unhide the channel. +- Added `hiddenChannelFilter` in `GroupChannelListQuery` to filter by `hiddenState`. + - `unhidden_only`: Get all unhidden channels. (default) + - `hidden_only`: Get all hidden channels which `hiddenState` is `hidden_allow_auto_unhide` or `hidden_prevent_auto_unhide`. + - `hidden_allow_auto_unhide`: Get channels which `hiddenState` is `hidden_allow_auto_unhide`. + - `hidden_prevent_auto_unhide`: Get channels which `hiddenState` is `hidden_prevent_auto_unhide`. + +## v3.0.88(NOV 15, 2018) + +- Changed type of `sender` property in `UserMessage` and `FileMessage` from `User` to a new class `Sender` which extends `User`. + - `Sender` has `isBlockedByMe` property which indicates that the message sender is blocked by the current user (default: false). + - `isBlockedByMe` is valid in `GroupChannel` only. + - Message from blocked user is delivered only when `block_mode` in `Application` is set to `explicit` mode. Otherwise, it's not visible nor delivered. +- Minor bug fixed. + +## v3.0.87(NOV 8, 2018) + +- Added `ApplicationUserListQuery`. + - It is used to get users created in the application. + - It could be derived by `createApplicationUserListQuery()` in `SendBird`. + - `userIdsFilter`: use to filter through userIds to get users. + - `metaDataKeyFilter`: use to filter by user's metaData to get users. If you set this value, you should set `metaDataValuesFilter` too. + - `metaDataValuesFilter`: use to filter by user's metaData to get users. If you set this value, you should set `metaDataKeyFilter` too. +- Added `userIdsFilter` in `BlockedUserListQuery` to get filtered by userIds among users blocked by currentUser. +- Deprecated `createUserListQuery()` in `SendBird`. We recommend that you use `createApplicationUserListQuery()`. + +## v3.0.85(OCT 31, 2018) + +- Added `ScheduledUserMessage` feature to send `UserMessage` at the time specified by a user. + - Added `ScheduledUserMessage` that is a scheduled `UserMessage`. + - Added `ScheduledUserMessageParams` in `SendBird` to be delivered as a parameter to register scheduled `UserMessage`. + - Added `registerScheduledUserMessage` in `GroupChannel` to register scheduled `UserMessage`. +- Improved stability. +- Minor bug fixed. + +## v3.0.84(OCT 26, 2018) + +- Added `getMyMutedInfo()` in `BaseChannel` +- Added `muteUser(user, seconds, description, callback)` and `muteUserWithUserId(userId, seconds, description, callback)` in `BaseChannel` +- Added `metadata_value_alphabetical` order in `GroupChannelListQuery` and `PublicGroupChannelListQuery` +- Added `metadataOrderKeyFilter` in `GroupChannelListQuery` and `PublicGroupChannelListQuery` +- Minor bug fixed + +## v3.0.83(OCT 18, 2018) + +- Added `getLastConnectedAt()` in `SendBird` to get currentUser's last connection timestamp. +- Improved `sendFileMessage()` in `BaseChannel`. From now, message's order is guaranteed regardless of the file size uploaded. +- Improved stability. +- Minor bug fixed. + +## v3.0.82(OCT 11, 2018) + +- Improved stability. +- Minor bug fixed. + +## v3.0.81(SEP 21, 2018) + +- Added readStatus of currentUser by passing `true` as first argument to `getReadStatus()` in `GroupChannel`. Passing `false` or nothing to `getReadStatus()` returns the read status without currentUser. +- Added `getReadMembers()` in `GroupChannel` to return a list of members who read the message. +- Added `getUnreadMember()` in `GroupChannel` to return a list of members who did not read the message. +- Added `isEqual()` in `GroupChannel` and `BaseMessage` to deep-equal with other instance. +- Added `isIdentical()` in `GroupChannel` and `BaseMessage` to check if the instance is identical to another. +- Fixed to call `connect()` callback function with an error when connection is lost while connecting to SendBird. +- Minor bug fixed. +- Deprecated some feature. + + - Deprecated `getCurrentUserId()` in `SendBird`. + - Deprecated `CLOSING` in ConnectionState in `SendBird`. + - Deprecated some `createChannel()`, `createChannelWithUserIds()` in `GroupChannel` and `OpenChannel`. + - Deprecated some `updateChannel()` in `GroupChannel` and `OpenChannel`. + - Deprecated some `sendUserMessage()` and `sendFileMessage()`. + - Deprecated `getChannelCount()` in `GroupChannel`. Use newly added `SendBird.getGroupChannelCount()` instead. + - Deprecated `getTotalUnreadMessageCount()` in `GroupChannel`. Use newly added `SendBird.getTotalUnreadMessageCount()` instead. + - Deprecated `getTotalUnreadChannelCount()` in `GroupChannel`. Use newly added `SendBird.getTotalUnreadChannelCount()` instead. + - Deprecated `getUnreadItemCount()` in `GroupChannel`. Use newly added `SendBird.getUnreadItemCount()` instead. + +## v3.0.79(SEP 14, 2018) + +- From now, `useMemberAsMessageSender` option is true by default. +- Fixed a bug previous messages not showing the senders' latest user metadata. +- Minor bug fixed. + +## v3.0.78(SEP 11, 2018) + +- Improved stability. +- Minor bug fixed. + +## v3.0.77(SEP 5, 2018) + +- Fixed a bug to support NodeJS below 10. + +## v3.0.75(SEP 4, 2018) + +- Improved connection state check when reconnected. + +## v3.0.74(SEP 4, 2018) + +- Minor bug fixed. +- Improved reconnection mechanism to detect network recovered on browsers only. +- Support NodeJS version 10. + +## v3.0.73(SEP 3, 2018) + +- Minor bug fixed. + +## v3.0.72(Aug 24, 2018) + +- Added `updateUserMessage()` with `UserMessageParams` in BaseChannel. +- Added `updateFileMessage()` with `FileMessageParams` in BaseChannel. +- Minor bug fixed. + +## v3.0.71(Aug 16, 2018) + +- Improved connection management. + +## v3.0.70(Aug 3, 2018) + +- Added `invitedAt` in GroupChannel. + +## v3.0.69(Jul 13, 2018) + +- Added properties as `limit`, `reverse`, `messageTypeFilter`, `customTypeFilter`, and `senderUserIdsFilter` in PreviousMessageListQuery. +- Added `getNextMessagesByTimestamp`, `getPreviousMessagesByTimestamp`, `getPreviousAndNextMessagesByTimestamp`, `getNextMessagesByID`, `getPreviousMessagesByID`, and `getPreviousAndNextMessagesByID` with `sendUserIds` parameter in BaseChannel. + +## v3.0.68(Jul 6, 2018) + +- Disabled to put the current user into mentionedUsers, mentionedUserIds in UserMessageParams and FileMessageParams. +- Changed not to increase unreadMentionCount and not to call onMentionReceived for CHANNEL mention by the current user (i.e. the message sender is the current user). + +## v3.0.67(Jun 29, 2018) + +- Added `unreadMentionCount` in `GroupChannel` to check the mention count of the current user. +- Added `unread_mention_count_only` in CountPreference to receive only updated `unreadMentionCount`. +- Added `mentionType` with `users` and `channel` in `BaseMessage` to check the type of mention. +- Added `mentionType` with `users` and `channel` in `BaseMessageParams` to set type of mention. + +## v3.0.66(Jun 22, 2018) + +- Added `nicknameStartsWithFilter` in `MemberListQuery` to search Group Channel members by nickname. +- Added `CountPreference` in `GroupChannel` which represents an enum of count preferences - 'all', 'unread_message_count_only', 'off'. +- Added `myCountPreference` in `GroupChannel` to get my count preference of a Group Channel. +- Added `setMyCountPreference` in `GroupChannel` to set my Group Channel count preference to a value in GroupChannel.CountPreference. +- Minor bug-fix. + +## v3.0.65(Jun 13, 2018) + +- Added `memberStateFilter` in `MemberListQuery` to search members based on the state of the member in a Group Channel. +- Added `myMutedState` in `GroupChannel` to show the state of the connected user in a Group Channel. +- Added `joinedMemberCount` in `GroupChannel` to show the total count of joined users in a Group Channel. +- Added `getUnreadItemCount` that receives an array argument having at least one among 'non_super_group_channel_unread_message_count', 'non_super_group_channel_invitation_count', 'super_group_channel_unread_message_count', and 'super_group_channel_invitation_count' in `GroupChannel`. +- Changed the type of `invitees` from `Member` to `User` on `onUserReceivedInvitation`. + +## v3.0.64(Jun 1, 2018) + +- Added a typing indicator throttle option in SendBird.Options. +- Fixed a minor bug for `GroupChannelParams`, `UserMessageParams` and `FileMessageParams`. +- Fixed a minor bug for `includeEmpty` to accept only a boolean argument. + +## v3.0.63 + +- Fixed an occasional member count mismatch in a super group channel. + +## v3.0.62 + +- Added a property named `myRole` in the `GroupChannel` which is a role of current user in the group channel. +- Added `GroupChannelTotalUnreadMessageCountParams` class that is used to get total unread message count. + +## v3.0.61 + +- Ordered member list by nickname alphabetically. +- Fixed a bug that a file upload. + +## v3.0.60 + +- Bugfix about RequireJS. + +## v3.0.59 + +- Bugfix about myMemberState when user decline invitation. + +## v3.0.58 + +- Deprecated `operatorFilter` in `GroupChannelMemberListQuery`. +- Added `createOperatorListQuery` in `BaseChannel` to search users that are operators in channel. +- Minor bugfix. + +## v3.0.57 + +- Added `pushNotificationDeliveryOption` in `UserMessageParams` and `FileMessageParams` to determine whether it’d deliver the push notification for a user/file message. +- Added `channelCustomTypes` in `getTotalUnreadMessageCount()` to get an unread message count of `GroupChannel` with specific custom types. + +## v3.0.56 + +- Changed an ephemeral `GroupChannel` to maintain fields of `lastMessage` and `unreadMessageCount` after connected. +- Update `SendBird.d.ts` file. + +## v3.0.55 + +- Added `UserMessageParams` feature. + - This is used in `sendUserMessage()` of channel. + - message: set text message to send. This value is required. + - data: set message data to send. + - customType: set message customType to send. + - targetLanguages: set message translation target language list. + - mentionedUserIds: set mentioned userId. + - mentionedUsers: set mentioned User. +- Added `FileMessageParams` feature. + - This is used in `sendFileMessage()` of channel. + - `file` or `fileUrl` is required. + - file: set file to send. + - fileUrl: set file's url to send. + - fileName: set file's name to send. When you set a file and do not specify this value, it is specified by name of the file. When you set a fileUrl and do not specify this value, it is set as empty string. + - fileSize: set file's size to send. When you set a file and do not specify this value, it is specified by size of the file. When you set a fileUrl and do not specify this value, it is set as 0. + - mimeType: set file's type to send. When you set a file and do not specify this value, it is specified by type of the file. When you set a fileUrl and do not specify this value, it is specified by inferring from fileUrl. + - data: set message data to send. + - customType: set message customType to send. + - thumbnailSizes: set size of the thumbnail to be created. This value only works when you use file not fileUrl. + - mentionedUserIds: set mentioned userId. + - mentionedUsers: set mentioned User. +- Added `sendUserMessage(UserMessageParams, CallBackFunction)` in channel. +- Added `sendFileMessage(FileMessageParams, CallBackFunction)` in channel. +- Added `mentionedUsers` in UserMessage and FileMessage to check mentioned user. +- Added `isEphemeral` in GroupChannel to indicate whether the channel supports message retention. +- Added `myMemberState` in GroupChannel to check my joined state on GroupChannel. +- Added `operator` feature in GroupChannel. + - Added `operators` in `GroupChannelParams` to set operator. + - Added `operatorUserIds` in `GroupChannelParams` to set operator. +- Added `banUser` in `GroupChannel` to ban User. +- Added `banUserWithUserId` in `GroupChannel` to ban User using userId. +- Added `unbanUser` in `GroupChannel` to remove banned User using User object. +- Added `unbanUserWithUserId` in `GroupChannel` to remove banned User using userId. +- Added `muteUser` in `GroupChannel` to mute User using User object. +- Added `muteUserWithUserId` in `GroupChannel` to mute User using userId. +- Added `unmuteUser` in `GroupChannel` to unmute User using User object. +- Added `unmuteUserWithUserId` in `GroupChannel` to unmute User using userId. +- Added `freeze` in `GroupChannel` not to allow messages from members from the channel. +- Added `unfreeze` in `GroupChannel` to allow messages from members from the channel. +- Added `isFrozen` in `GroupChannel` to check if the channel is frozen or not. +- From now, channel param in callbacks of the ChannelHandler below can come in either GroupChannel or OpenChannel. + - onUserMuted(channel, user) + - onUserUnmuted(channel, user) + - onUserBanned(channel, user) + - onUserUnbanned(channel, user) + - onChannelFrozen(channel) + - onChannelUnfrozen(channel) +- Added `createMemberListQuery()` in `GroupChannel` to search members. + +## v3.0.54 + +- Minor bugfix for `UserMessage` and `FileMessage`. + +## v3.0.53 + +- Deprecated `userIdsFilter` in `GroupChannelListQuery`. +- Deprecated `userIdsFilterExactMatch` in `GroupChannelListQuery`. +- Deprecated `queryType` in `GroupChannelListQuery`. +- Added `userIdsExactFilter` in `GroupChannelListQuery` to replace `userIdsFilter` and `userIdsFilterExactMatch`. +- Added `userIdsIncludeFilter` in `GroupChannelListQuery` to replace `userIdsFilter` and `userIdsFilterExactMatch`. +- Added `userIdsIncludeFilterQueryType` in `GroupChannelListQuery` to replace `queryType`. +- Added `customTypeStartsWithFilter` in `GroupChannelListQuery` to search channels based on `customType`. +- Added `superChannelFilter` in `GroupChannelListQuery` to search channels that `isSuper` is true. +- Added `publicChannelFilter` in `GroupChannelListQuery` to search channels that `isPublic` is true. +- Added `GroupChannelParams` feature. + - This is used in `createChannel()` and `updateChannel()` of GroupChannel. + - isDistinct: set isDistinct on creation or update. + - isSuper: set isSuper on creation. + - isPublic: set isPublic on creation or update. + - channelUrl: set url of channel on creation. + - name: set name on creation or update. + - data: set data on creation or update. + - customType: set customType on creation or update. + - coverUrl: set coverUrl on creation or update. + - coverImage: set coverUrl using file on creation or update. + - addUser(): add user to be invited using user instance. + - addUsers(): add user to be invited using user instance array. + - addUserId(): add user to be invited using userId. + - addUserIds(): add user to be invited using userId array. +- Added `PublicGroupChannelListQuery` in `SendBird` to search channels that `isPublic` is true. + - limit: set list count for result. + - includeEmpty: set whether to get channel that conversation is empty. + - order: set order of result. + - channelNameContainsFilter: set channelName to get channels based on. + - channelUrlsFilter: set channelUrls to get channels based on. + - customTypesFilter: set customTypes to get channels based on. + - customTypeStartsWithFilter: set to get channels starting with the passed customType. + - superChannelFilter: set whether to fetch all channels, super channels only, or non-super channels only. + - membershipFilter: set whether to fetch according to the current user state of join. + - next(): get channel list. + +## v3.0.52 + +- Added `channelUrlsFilter` in `GroupChannelListQuery`. + +## v3.0.51 + +- Minor bugfix for `markAsReadWithChannelUrls()`. + +## v3.0.50 + +- Added `markAsReadWithChannelUrls()` in `SendBird` to simultaneously mark as read multiple channels the logged in user has joined. +- Added `markAsReadAll()` in `SendBird` to mark as read all channels the logged in user has joined. +- Deprecated `markAsReadAll()` in `GroupChannel`. +- From now, if you pass param as `true` when you call `hide()`, the channel's unreadMessageCount set to 0. + +## v3.0.49 + +- Added `customTypesFilter` in `GroupChannelListQuery` to search groupChannel. +- Added `getOriginalProfileUrl()` in `User` for getting original profile image. +- Added `Friend` feature. + - uploadFriendDiscoveries(): add friend using discovery key. + - deleteFriendDiscovery() / deleteFriendDiscoveries(): delete friend's discovery key. + - addFriends(): add friend using friend's userID. + - deleteFriend() / deleteFriends(): delete friend using friend's userID. + - createFriendListQuery(): create object for getting friend list. + - getFriendChangeLogsByToken(): get friend relation changed log. + - addUserEventHandler(): add handler for receiving user event. + - removeUserEventHandler() / removeAllUserEventHandler(): remove user event handler. + - UserEventHandler: user event handler object. +- From now, even when you call `connect()` before the previous `connect()` finishes, all of them get called back for the connection establishment result at the same time. + +## v3.0.48 + +- Added `isActive` in `User`. + +## v3.0.47 + +- Update TypeScript Definition file(SendBird.d.ts). + +## v3.0.46 + +- Minor bug fixes. + +## v3.0.45 + +- Minor bug fixes. + +## v3.0.44 + +- Added `customTypeFilter` in `createMyGroupChannelListQuery`. +- Added `onChannelHidden` in `ChannelHandler`. + +## v3.0.43 + +- Added `isHidden` in `GroupChannel`. + +## v3.0.42 + +- Added `getMessageChangeLogsByToken()` in `Channel`. + +## v3.0.41 + +- Updated TypeScript Definition file(SendBird.d.ts). + > **NOTE** + > Install via NPM and import like below in your TypeScript file: + +```javascript +import * as SendBird from "SendBird"; +var sb = new SendBird({ appId: "USER_APP_ID" }); +// do something... +``` + +If you have trouble importing `SendBird`, please check your `tsconfig.json` file and change the value of `"allowSyntheticDefaultImports"` to `true` in `compilerOptions`. + +## v3.0.40 + +- Added `serialize()` and `buildFromSerializedData()` in `User`, `Message` and `Channel`. +- Added `getChannelCount()` and `resetMyHistory()` in `GroupChannel`. + +## v3.0.39 + +- Added `isBlockedByMe` and `isBlockingMe` in `Member`. + +## v3.0.38 + +- Added `createMetaData`, `updateMetaData`, `deleteMetaData` and `deleteAllMetaData` in `User`. +- Added `metaDataKey` and `metaDataValues` filter in `UserListQuery`. +- Added `isFrozen` in `OpenChannel`. +- Added `hidePreviousMessages` option in `hide` function. + +## v3.0.37 + +- Added `channelNameContainsFilter` in myGroupChannelListQuery object. +- Added `onMetaDataCreated`, `onMetaDataUpdated`, `onMetaDataDeleted`, `onMetaCountersCreated`, `onMetaCountersUpdated` and `onMetaCountersDeleted` handlers in `ChannelHandler`. + +## v3.0.36 + +- Updated login status check. +- minor bugfix for NodeJS. + +## v3.0.35 + +- Updated dependent libs for NodeJS. + +## v3.0.34 + +- Updated the TypeScript file. +- Fixed the WebSocket disconnect. + +## v3.0.33 + +- Fixed version check. + +## v3.0.32 + +- Added `delete()` in OpenChannel. +- Added `updateChannel()` in GroupChannel and OpenChannel. + +## v3.0.31 + +- Fixed a compatibility issue with React Native. + +## v3.0.30 + +- Added `getPushTemplate()` and `setPushTemplate()`. +- Added checking SDK's version using `SendBird.version`. +- Now support connecting to custom host. +- Added return value when call `cancelUploadingFileMessage()`. + +## v3.0.29 + +- Fix the bug that drops message events when sb.setErrorFirstCallback was set to True. + +## v3.0.28 + +- `SendBirdException` now inherits from the JavaScript Error object. +- You can now decide the error parameter order in callback functions using `sb.setErrorFirstCallback(True|False)`. + +## v3.0.27 + +- Added `updateUserMessage()` and `updateFileMessage()`. +- Added `onMessageUpdated()` in ChannelHandler. +- You now can confirm file upload progress by passing a progressHandler as a parameter when calling `sendFileMessage()`. +- Added `cancelUploadingFileMessage()`. + +## v3.0.26 + +- Added getTotalUnreadChannelCount +- Now markAsRead doesn't have any delays + +## v3.0.25 + +- Now GroupChannelList returns correct readstatus as well. +- Member nickname/profile get updated when new messages arrived. +- Return more consistent errors when connection() is not made before calling methods. +- Now we don't count senders in readreceipt. + +## v3.0.24 + +- Now it supports IE8/9 with some Flash libraries +- Fixed a bug regarding disableStateChange/enableStateChange + ## v3.0.23 + ### update - * Fixed a file uploading bug in React Native. - * Fixed minor bugs related to null check. + +- Fixed a file uploading bug in React Native. +- Fixed minor bugs related to null check. ## v3.0.22 + ### update - * Fixed a bug in calling markAsRead(). - * Added supports for video/image thumbnail generations and file encryption/access control. + +- Fixed a bug in calling markAsRead(). +- Added supports for video/image thumbnail generations and file encryption/access control. ## v3.0.19 + ### update - * connect()/disconnect() doesn't clear out connection/channel handlers anymore. - Instead you should use removeAllConnectionHandlers() and removeAllChannelHandlers(). - * Fixed a bug in removing ios push tokens. - * Now reconnect() method has been added which you can use when you want to manually trigger reconnect logic when network condition gets better. + +- connect()/disconnect() doesn't clear out connection/channel handlers anymore. + Instead you should use removeAllConnectionHandlers() and removeAllChannelHandlers(). +- Fixed a bug in removing ios push tokens. +- Now reconnect() method has been added which you can use when you want to manually trigger reconnect logic when network condition gets better. ## v3.0.18 + ### update - * Added "getMessages" series of methods with timestamp and messageId filter. - * Fixed a callback handling bug. + +- Added "getMessages" series of methods with timestamp and messageId filter. +- Fixed a callback handling bug. ## v3.0.17 + ### update - * Finally push notifications feature is officially supported in V3 JS SDK. - * Added "setBackgroundState()" and "setForegroundState()". - * Added "messageType" filter to PreviousMessageQueryList. + +- Finally push notifications feature is officially supported in V3 JS SDK. +- Added "setBackgroundState()" and "setForegroundState()". +- Added "messageType" filter to PreviousMessageQueryList. ## v3.0.16 + ### update - * InItial connection speed has been improved a lot!. - * Auto-Reconnection is now more robust. - * Auto-Translation support has been added. + +- InItial connection speed has been improved a lot!. +- Auto-Reconnection is now more robust. +- Auto-Translation support has been added. ## v3.0.15 + ### update - * Fixed a bug that created non-integer file size field. + +- Fixed a bug that created non-integer file size field. ## v3.0.14 + ### update - * Fixed a reconnection bug happening after calling disconnect() and connect() in serial. - * Added "custom_type" field to message/file object. - * Added "user_id"/"nickanme" filters to GroupChannelList. + +- Fixed a reconnection bug happening after calling disconnect() and connect() in serial. +- Added "custom_type" field to message/file object. +- Added "user_id"/"nickanme" filters to GroupChannelList. ## v3.0.12 + ### update - * Fixed wrong message_id, data field of FileMessage object. + +- Fixed wrong message_id, data field of FileMessage object. ## v3.0.11 + ### update - * Fixed a Keep-Alive bug now and it should be much faster in React Native/NodeJS. - * Now calling "connect()" multiple times in a row triggers "disconnect()" internally to avoid having multiple websocket connections - * New License File + +- Fixed a Keep-Alive bug now and it should be much faster in React Native/NodeJS. +- Now calling "connect()" multiple times in a row triggers "disconnect()" internally to avoid having multiple websocket connections +- New License File ## v3.0.10 + ### update - * Fixed a bug that increases unread message count when a user gets its own messages - * Cleared out old ws object's event handlers after disconnect to prevent a user from getting messages from another user who logged in on the same device. + +- Fixed a bug that increases unread message count when a user gets its own messages +- Cleared out old ws object's event handlers after disconnect to prevent a user from getting messages from another user who logged in on the same device. ## v3.0.9 + ### update - * minor bugfix for IE, Safari, Opera. + +- minor bugfix for IE, Safari, Opera. ## v3.0.8 + ### update - * `sendFileMessage` bugfix. + +- `sendFileMessage` bugfix. ## v3.0.7 + ### update - * Added features like filtered user list, open channel keyword search, push preference setting, etc. - * `messageListQuery` bugfix. + +- Added features like filtered user list, open channel keyword search, push preference setting, etc. +- `messageListQuery` bugfix. ## v3.0.6 + ### update - * add dependencies + +- add dependencies ## v3.0.5 + ### update - * NodeJS Keepalive bugfix. - * React Native android bugfix. + +- NodeJS Keepalive bugfix. +- React Native android bugfix. ## v3.0.4 + ### update - * `createPreviousMessageListQuery` bugfix. - * npm bundle bugfix. + +- `createPreviousMessageListQuery` bugfix. +- npm bundle bugfix. ## v3.0.3 + ### update - * npm publish. +- npm publish. ## v3.0.2 + ### update - * Reconnect bugfix. - * `getMetaCounters`, `getMetaData` bugfix. +- Reconnect bugfix. +- `getMetaCounters`, `getMetaData` bugfix. ## v3.0.1 + ### update - * `blockUserWithUserId` bugfix. +- `blockUserWithUserId` bugfix. ## v3.0.0 + ### update - * v3.0.0 release. + +- v3.0.0 release. diff --git a/DEPRECATED.md b/DEPRECATED.md new file mode 100644 index 0000000..f5f88e6 --- /dev/null +++ b/DEPRECATED.md @@ -0,0 +1,288 @@ +# Deprecated classes, methods, properties + + +## v3.1.9 + +### Classes + +| Old class | New Class | +| --------- | --------- | +| ConnectionManager | N/A | + + +## v3.0.159 + +### Methods + +| Old class | Old property | New class | New property | +| --------- | ------------ | --------- | ------------ | +| MessageRetrievalParams | includeParentMessageText: boolean | MessageRetrievalParams | includeParentMessageInfo: boolean | +| PreviousMessageListQuery | includeParentMessageText: boolean | PreviousMessageListQuery | includeParentMessageInfo: boolean | +| PreviousMessageListQuery | includeReplies: boolean | PreviousMessageListQuery | replyType: ReplyType | +| MessageListParams | includeParentMessageText: boolean | MessageListParams | includeParentMessageInfo: boolean | +| MessageListParams | includeReplies: boolean | MessageListParams | replyType: ReplyType | +| ThreadedMessageListParams | includeParentMessageText: boolean | ThreadedMessageListParams | includeParentMessageInfo: boolean | +| MessageChangeLogsParams | includeParentMessageText: boolean | MessageChangeLogsParams | includeParentMessageInfo: boolean | +| MessageChangeLogsParams | includeReplies: boolean | MessageChangeLogsParams | replyType: ReplyType | + + +## v3.0.156 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| GroupChannel | markAsRead(): void | GroupChannel | markAsRead(callback: VoidCallback): Promise<void> | + + +## v3.0.143 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| GroupChannel | markAsDelivered(): void | SendBird | markAsDelivered(channelUrl: String): void | + + +## v3.0.142 + +### Properties + +| Old class | Old property | New class | New property | +| --------- | ------------ | --------- | ------------ | +| UserMessage | sendingStatus: string | BaseMessage | sendingStatus: string | +| FileMessage | sendingStatus: string | BaseMessage | sendingStatus: string | +| AdminMessage | N/A | BaseMessage | sendingStatus: string | +| PreviousMessageListQuery | customTypeFilter: string | PreviousMessageListQuery | customTypesFilter: string[] | +| MessageListParams | customType: string | MessageListParams | customTypes: string[] | +| ThreadedMessageListParams | customType: string | ThreadedMessageListParams | customTypes: string[] | + + +## v3.0.134 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| GroupChannel | getTypingMembers(): Member[] | GroupChannel | getTypingUsers(): Member[] | + + +## v3.0.129 + +### Properties + +| Old class | Old property | New class | New property | +| --------- | ------------ | --------- | ------------ | +| PreviousMessageListQuery | includeReaction: boolean | PreviousMessageListQuery | includeReactions: boolean | +| MessageChangeLogsParams | includeReaction: boolean | MessageChangeLogsParams | includeReactions: boolean | +| MessageListParams | includeReaction: boolean | MessageListParams | includeReactions: boolean | +| ThreadedMessageListParams | includeReaction: boolean | ThreadedMessageListParams | includeReactions: boolean | + + +## v3.0.127 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| GroupChannel | getReadReceipt(message: UserMessage | FileMessage): number | GroupChannel | getUnreadMemberCount(message: UserMessage | FileMessage): number | +| GroupChannel | getDeliveryReceipt(message: UserMessage | FileMessage): number | GroupChannel | getUndeliveredMemberCount(message: UserMessage | FileMessage): number | + + +## v3.0.125 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| SendBird | getMyGroupChannelChangeLogsByToken(token: string, customTypes: string[]): object | SendBird | getMyGroupChannelChangeLogsByToken(token: string, params: GroupChannelChangeLogsParams): object | +| SendBird | getMyGroupChannelChangeLogsByToken(token: string, customTypes: string[], includeEmpty: boolean): object | SendBird | getMyGroupChannelChangeLogsByToken(token: string, params: GroupChannelChangeLogsParams): object | +| SendBird | getMyGroupChannelChangeLogsByTimestamp(timestamp: number, customTypes: string[]): object | SendBird | getMyGroupChannelChangeLogsByTimestamp(timestmap: number, params: GroupChannelChangeLogsParams): object | +| SendBird | getMyGroupChannelChangeLogsByTimestamp(timestamp: number, customTypes: string[], includeEmpty: boolean): object | SendBird | getMyGroupChannelChangeLogsByTimestamp(timestmap: number, params: GroupChannelChangeLogsParams): object | + + +## v3.0.123 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| BaseChannel | getMessageChangeLogsByTimestamp(timestamp: number): object | BaseChannel | getMessageChangeLogsSinceTimestamp(timestamp: number, params: MessageChangeLogsParams): object | +| BaseChannel | getMessageChangeLogsByTimestamp(timestamp: number, includeMetaArray: boolean): object | BaseChannel | getMessageChangeLogsSinceTimestamp(timestamp: number, params: MessageChangeLogsParams): object | +| BaseChannel | getMessageChangeLogsByTimestamp(timestamp: number, includeMetaArray: boolean, includeReactions: boolean): object | BaseChannel | getMessageChangeLogsSinceTimestamp(timestamp: number, params: MessageChangeLogsParams): object | +| BaseChannel | getMessageChangeLogsByToken(): object | BaseChannel | getMessageChangeLogsSinceToken(token: string, params: MessageChangeLogsParams): object | +| BaseChannel | getMessageChangeLogsByToken(token: string): object | BaseChannel | getMessageChangeLogsSinceToken(token: string, params: MessageChangeLogsParams): object | +| BaseChannel | getMessageChangeLogsByToken(token: string, includeMetaArray: boolean): object | BaseChannel | getMessageChangeLogsSinceToken(token: string, params: MessageChangeLogsParams): object | +| BaseChannel | getMessageChangeLogsByToken(token: string, includeMetaArray: boolean, includeReactions: boolean): object | BaseChannel | getMessageChangeLogsSinceToken(token: string, params: MessageChangeLogsParams): object | +| BaseChannel | getPreviousMessagesByTimestamp(timestamp: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByTimestamp(timestamp: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByTimestamp(timestamp: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByTimestamp(timestamp: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByTimestamp(timestamp: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByTimestamp(timestamp: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByTimestamp(timestamp: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByTimestamp(timestamp: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByTimestamp(timestamp: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByTimestamp(timestamp: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByTimestamp(timestamp: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByTimestamp(timestamp: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByID(messageId: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByID(messageId: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByID(messageId: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByID(messageId: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByID(messageId: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByID(messageId: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByID(messageId: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByID(messageId: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | + + +## v3.0.122 + +### Properties + +| Old class | Old property | New class | New property | +| --------- | ------------ | --------- | ------------ | +| BaseMessageParams | metaArrayKeys: string[] | BaseMessageParams | metaArrays: MessageMetaArray[] | + + +## v3.0.119 + +### Properties + +| Old class | Old property | New class | New property | +| --------- | ------------ | --------- | ------------ | +| UserMessage | requestState: string | UserMessage | sendingStatus: string | +| FileMessage | requestState: string | FileMessage | sendingStatus: string | + + +### Classes + +| Old class | New class | +| --------- | --------- | +| MessageRequestState | MessageSendingStatus | + + +## v3.0.109 + +### Methods + +| Old class | Old method | New class | New method/property | +| --------- | ---------- | --------- | ------------------- | +| SendBird | getCurrentUserId(): string | SendBird | currentUser: User | + + +## v3.0.105 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| BaseChannel | addMessageMetaArrayValues(message: BaseMessage, metaArrays: object): BaseMessage | BaseChannel | addMessageMetaArrayValues(message: BaseMessage, metaArrays: MessageMetaArray[]): BaseMessage | +| BaseChannel | removeMessageMetaArrayValues(message: BaseMessage, metaArrays: object): BaseMessage | BaseChannel | removeMessageMetaArrayValues(message: BaseMessage, metaArrays: MessageMetaArray[]): BaseMessage | + + +## v3.0.93 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| GroupChannel | getPushPreference(): boolean | GroupChannel | getMyPushTriggerOption(): boolean | +| GroupChannel | setPushPreference(enable: boolean): object | GroupChannel | setMyPushTriggerOption(pushTriggerOption: boolean): boolean | + +### Properties + +| Old class | Old property | New class | New property | +| --------- | ------------ | --------- | ------------ | +| GroupChannel | isPushEnabled: boolean | GroupChannel | myPushTriggerOption: string | + + +## v3.0.86 + +### Classes + +| Old class | New class | +| --------- | --------- | +| UserListQuery | ApplicationUserListQuery | + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| SendBird | createUserListQuery(): UserListQuery | SendBird | createApplicationUserListQuery(): ApplicationUserListQuery | +| SendBird | createUserListQuery(userIds: string[]): UserListQuery | SendBird | createApplicationUserListQuery(): ApplicationUserListQuery | + + +## v3.0.84 + +### Properties + +| Old class | Old property | New class | New property | +| --------- | ------------ | --------- | ------------ | +| UserMessageParams | targetLanguages: string[] | UserMessageParams | translationTargetLanguages: string[] | + + +## v3.0.80 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| GroupChannel | getChannelCount(memberStateFilter: string): number | SendBird | getGroupChannelCount(memberStateFilter: string): number | +| GroupChannel | getUnreadItemCount(keys: string[]): number | SendBird | getUnreadItemCount(keys: string[]): number | +| GroupChannel | getTotalUnreadMessageCount(): number | SendBird | getTotalUnreadMessageCount(): number | +| GroupChannel | getTotalUnreadMessageCount(channelCustomTypes: string[]): number | SendBird | getTotalUnreadMessageCount(channelCustomTypesFilter: string[]): number | +| GroupChannel | getTotalUnreadMessageCount(params: GroupChannelTotalUnreadMessageCountParams): number | SendBird | getTotalUnreadMessageCount(params: GroupChannelTotalUnreadMessageCountParams): number | +| GroupChannel | getTotalUnreadChannelCount(): number | SendBird | getTotalUnreadChannelCount(): number | + + +## v3.0.50 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| GroupChannel | markAsReadAll(): void | SendBird | markAsReadAll(): void | + + +## v3.0.49 + +### Properties + +| Old class | Old property | New class | New property | +| --------- | ------------ | --------- | ------------ | +| GroupChannelListQuery | customTypeFilter: string | GroupChannelListQuery | customTypesFilter: string[] | + + +## v3.0.36 + +### Classes + +| Old class | New class | +| --------- | --------- | +| MessageListQuery | PreviousMessageListQuery | + + +## v3.0.27 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| N/A | N/A | SendBird | setErrorFirstCallback(errorFirstInCallback: boolean) | diff --git a/LICENSE.md b/LICENSE.md index 2e405c9..2f6f2ec 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ -#SendBird SDK LICENSE +# SendBird SDK LICENSE -This is an agreement between You ("You") and SendBird DBA (Smile Family, Inc.), the developer of SendBird, located at 541 Jefferson Ave. Suite 100 Redwood City, CA 94063, ("SendBird") regarding Your use of the SendBird SDK and any associated documentation or other materials made available by SendBird (collectively the "SDK"). This agreement applies to any updates or supplements for the SDK, unless other terms accompany those items. If so, those other terms apply. +This is an agreement between You ("You") and SendBird, Inc., the developer of SendBird, located at 400 1st Ave, San Mateo, CA 94401, ("SendBird") regarding Your use of the SendBird SDK and any associated documentation or other materials made available by SendBird (collectively the "SDK"). This agreement applies to any updates or supplements for the SDK, unless other terms accompany those items. If so, those other terms apply. By installing, accessing or otherwise using the SDK, You accept the terms of this agreement. If You do not agree to the terms of this agreement, do not install, access or use the SDK. diff --git a/README.md b/README.md index 1802aa9..0bf358e 100644 --- a/README.md +++ b/README.md @@ -1,44 +1,356 @@ -SendBird-SDK-JavaScript -=========== +# [Sendbird](https://sendbird.com) Chat SDK v3 for JavaScript -[SendBird](https://sendbird.com) provides the chat API and SDK for your app enabling real-time communication among your users. +![Platform](https://img.shields.io/badge/platform-JAVASCRIPT-orange.svg) +![Languages](https://img.shields.io/badge/language-JAVASCRIPT-orange.svg) +[![npm](https://img.shields.io/npm/v/sendbird.svg?style=popout&colorB=red)](https://www.npmjs.com/package/sendbird) +## Deprecation Note (v3) +:warning: Please note that Sendbird’s SDK v3 will be deprecated by **July 2023**. You may still use the older SDKs at your choice, but no new updates or bug fixes will be made to SDK v3. -# Getting Started +**We recommend clients to plan their migration to SDK v4 as early as possible as there are breaking changes.** We also provide prioritized support for migration and any issues related to v4. SDK v4 provides far richer and robust features in Websocket, Local caching, Polls, Scheduled Messages, Pinned Message, and many more. So try it out now! ([Chat SDK v4](https://github.com/sendbird/sendbird-chat-sdk-javascript/)) -[Bower](http://bower.io) package for [SendBird.com](https://sendbird.com) JavaScript SDK +
- bower install sendbird +## Table of contents + 1. [Introduction](#introduction) + 1. [Before getting started](#before-getting-started) + 1. [Getting started](#getting-started) + 1. [Sending your first message](#sending-your-first-message) + 1. [Appendix](#appendix) + 2. [Notice](#notice) + 3. [Changelogs](#changelogs) -[npm](https://www.npmjs.com/package/sendbird) module for [SendBird.com](https://sendbird.com) JavaScript SDK +
- npm install sendbird +## Introduction +Through Sendbird Chat SDK for Javascript, you can efficiently integrate real-time chat into your client app. On the client-side implementation, you can initialize, configure and build the chat with minimal effort. On the server-side, Sendbird ensures reliable infra-management services for your chat within the app. This **read.me** provides the Chat SDK’s structure, supplementary features, and the installation steps. -[download](https://github.com/smilefam/SendBird-SDK-JavaScript) for [SendBird.com](https://sendbird.com) JavaScript SDK +### How it works +It is simple to implement chat in your client app with the Chat SDK: a user logs in, sees a list of channels, selects or creates an [open channel](https://sendbird.com/docs/chat/v3/javascript/guides/open-channel#2-create-a-channel) or a [group channel](https://sendbird.com/docs/chat/v3/javascript/guides/group-channel#2-create-a-channel), and, through the use of the [channel event handlers](https://sendbird.com/docs/chat/v3/javascript/guides/event-handler), sends messages to the channel, while also receiving them from other users within the channel. -# [Sample](https://github.com/smilefam/SendBird-JavaScript) +### More about Sendbird Chat SDK for JavaScript - * [Basic Sample](https://sample.sendbird.com) using [Sendbird SDK](https://github.com/smilefam/SendBird-SDK-JavaScript). [download](https://github.com/smilefam/SendBird-JavaScript/tree/master/basic-sample) - +Find out more about Sendbird Chat for JavaScript on [Chat SDK for JavaScript doc](https://sendbird.com/docs/chat/v3/javascript/getting-started/about-chat-sdk). -# [Documentation](https://docs.sendbird.com/javascript) +
+## Before getting started -## Upgrading to v3.0.23 - If you want to check the record of other version, go to [Change Log](https://github.com/smilefam/SendBird-SDK-JavaScript/blob/master/CHANGELOG.md). -n/access control. - * Fixed a file uploading bug in React Native. - * Fixed minor bugs related to null check. +This section shows you the prerequisites you need to check for using Sendbird Chat SDK for JavaScript. If you have any comments or questions regarding bugs and feature requests, visit [Sendbird community](https://community.sendbird.com). +### Supported browsers - -## [Change Log](https://github.com/smilefam/SendBird-SDK-JavaScript/blob/master/CHANGELOG.md) +| Browser | Supported versions | +| :---: | :--- | +| Internet Explorer | 10 or higher | +| Edge | 13 or higher | +| Chrome | 16 or higher | +| Firefox | 11 or higher | +| Safari | 7 or higher | +| Opera | 12.1 or higher | +| iOS Safari | 7 or higher | +| Android Browswer | 4.4 (Kitkat) or higher | +### More about additional features of Sendbird the the Chat SDK -## License -[SendBird License](https://github.com/smilefam/SendBird-SDK-JavaScript/blob/master/LICENSE.md) +Try building your Sendbird application with these two add-ons: +- [Sendbird UIKit for JavaScript](https://sendbird.com/docs/uikit/v1/javascript/getting-started/about-uikit): a development kit with a user interface that enables an easy and fast integration of standard chat features into new or existing client apps. +- [Sendbird SyncManager for JavaScript](https://sendbird.com/docs/syncmanager/v1/javascript/getting-started/about-syncmanager): the Chat SDK add-on that optimizes the user caching experience by interlinking the synchronization of the local data storage with the chat data in Sendbird server through an event-driven structure. +
+ +## Getting started + +This section gives you information you need to get started with Sendbird Chat SDK for JavaScript. + +### Try the sample app + +The fastest way to test the Chat SDK is to build your chat app on top of our sample app. To create a project for the sample app, download the app from our GitHub repository. The link is down below. + +- https://github.com/sendbird/Sendbird-JavaScript + +You can also download the sample using a git command: + +```bash +$ git clone https://github.com/sendbird/SendBird-JavaScript +``` + +> **Note**: Find out more about Sendbird SDK for JavaScript samples on https://sample.sendbird.com + +### Different sample projects + +For JavaScript, Sendbird supports a variety of sample projects. Their installation procedures are detailed as below: + +#### Run the web sample projects + +There are three web sample projects: [basic sample](https://github.com/sendbird/sendbird-javascript-samples/tree/master/javascript/javascript-basic), [live chat sample](https://github.com/sendbird/sendbird-javascript-samples/tree/master/javascript/javascript-live-chat), and [widget sample](https://github.com/sendbird/sendbird-javascript-samples/tree/master/javascript/javascript-widget). To run the sample projects, do the following to use `NodeJS` for your local server: + +1. Download and install `NodeJS` if your system doesn't have it yet. +2. Open a terminal and move to the project path. +```bash +$ cd web-basic-sample +``` +3. Install packages that are used in the sample project. +```bash +$ npm install +``` +4. Run the sample project. +```bash +$ npm start +``` + +#### Run the React Native sample project + +Our [React Native sample project](https://github.com/sendbird/SendBird-JavaScript/tree/master/react-native-redux-sample) is built on the [Redux](https://redux.js.org/) pattern of [React Native](https://reactnative.dev/). To run the sample, do the following: + +1. Download and install [`NodeJS`](https://nodejs.org/en/) if your system doesn't have it yet. +2. Setup the [React Native environment](https://reactnative.dev/docs/environment-setup) in your system. +3. Open a terminal and enter the commands below in your project path. +```bash +$ cd react-native-redux-sample/ReactNativeWithSendBird +$ npm install +``` +4. Run the sample app by entering the commands below. +```bash +$ react-native run-ios +$ react-native run-android +``` + +Before entering the two commands above, you should run the simulator from the [Android Studio](https://developer.android.com/studio/) in advance. The command for iOS works without further action. + +### Here are the steps to install Chat SDK + +Follow the simple steps below to build the Chat SDK into your client app. + +#### Step 1: Create a Sendbird application from your dashboard + +A Sendbird application comprises everything required in a chat service including users, message, and channels. To create an application: + +1. Go to the [Sendbird Dashboard](https://dashboard.sendbird.com/auth/signup) and enter your email and password, and create a new account. You can also sign up with a Google account. +2. When prompted by the setup wizard, enter your organization information to manage Sendbird applications. +3. Lastly, when your dashboard home appears after completing setup, click **Create +** at the top-right corner. + +Regardless of the platform, only one Sendbird application can be integrated per app; however, the application supports communication across allSendbird’s provided platforms without any additional setup. Sendbird currently supports iOS, Android, web, .NET, and Unity client apps. + +> Note: All the data is limited to the scope of a single application, thus the users in different Sendbird applications are unable to chat with each other. + +#### Step 2: Install the Chat SDK + +If you’re familiar with using external libraries or SDKs, installing the Chat SDK is simple.You can install the Chat SDK with package manager `npm` or `yarn` by entering the command below on the command line. + +- **Npm** + +> Note: To use npm to install the Chat SDK, Node.js must be first installed on your system. + +```bash +$ npm install sendbird (request to npm server) +``` + +Install via `Npm` and import like below in your `TypeScript` file. + +```bash +import * as SendBird from "sendbird"; +var sb = new SendBird({ appId: "APP_ID" }); +// do something... +``` + +If you have trouble importing Sendbird, please check your `tsconfig.json` file and change the value of `allowSyntheticDefaultImports` to true in `compilerOptions`. + +- **Yarn** + +```bash +$ yarn add sendbird +``` + +Or download the latest Chat SDK for JavaScript from the following link if you do not want to use package manager + +- https://github.com/sendbird/Sendbird-SDK-JavaScript + +> **Note**: You should also add `axios` library into the ` + +``` + +
+ +## Sending your first message + +Follow the step-by-step instructions below to authenticate and send your first message. + +### Authentication + +To use the features of the Chat SDK in your client app, a `sb` instance must be initiated in each client app before user authentication with Sendbird server. These instances communicate and interact with the server based on an authenticated user account, allowing for the client app to use the Chat SDK features. + +### Step 1: Initialize the Chat SDK + +You need to initialize a `sb` instance before authentication. Initialization binds the Chat SDK to Javascript’s context which allows the Chat SDK to respond to connection and state changes and also enables client apps to use the Chat SDK features. + +To initialize a `Sendbird` instance, pass the `App_ID` of your Sendbird application in the dashboard as an argument to a parameter in the `new Sendbird()` method. As the `new SendBird()` can only be a single instance, call it only a single time across your Javascript client app. Typically, initialization is implemented in the user login screen. + +> **Note**: It is recommended to initialize the Chat SDK at the top of your Javascript file. + +```javascript +var sb = new SendBird({appId: APP_ID}); +``` + +### Step 2: Connect to Sendbird server + +After initialization by use of `new SendBird()`, your client app must always be connected to Sendbird server before calling any methods. If you attempt to call a method without connecting, an [`ERR_CONNECTION_REQUIRED (800101)`](https://sendbird.com/docs/chat/v3/android/guides/error-codes) error would return. + +Connect a user to Sendbird server either through a unique user ID or in combination with an access token. Sendbird prefers the latter method, as it ensures privacy with the user. The former is useful during the developmental phase or if your service doesn't require additional security. + +#### A. User ID + +Connect a user to Sendbird server using their unique **user ID**. By default, Sendbird server can authenticate a user by a unique user ID. Upon request for a connection, the server queries the database to check for a match. Any untaken user ID is automatically registered as a new user to the Sendbird system, while an existing ID is allowed to log indirectly. The ID must be unique within a Sendbird application, such as a hashed email address or phone number in your service. + +```javascript +sb.connect(USER_ID, function(user, error) { + if (error) { + return; + } +}); +``` + +#### B. A combination of user ID and access token ID + +Sendbird prefers that you pass the APP ID through the use of a token, as it ensures privacy for the users. Create a user along with their access token, or issue an access token for an existing user. Once an access token is issued, a user is required to provide the access token in the `sb.connect()` method which is used for logging in. + +1. Using the Chat Platform API, create a Sendbird user account with the information submitted when a user signs up your service. +2. Save the user ID along with the issued access token to your persistent storage which is securely managed. +3. When the user attempts to log in to the Sendbird application, load the user ID and access token from the storage, and then pass them to the `sb.connect()` method. +4. Periodically replacing the user's access token is recommended to protect the account. + +```javascript +sb.connect(USER_ID, ACCESS_TOKEN, function(user, error) {}); +``` + +#### - Tips for user account security + +From **Settings** > **Application** > **Security** > **Access token permission** setting in your dashboard, you can prevent users without an access token from logging in to your Sendbird application or restrict their access to **read** and **write** messages. + +For security reasons, you can also use a session token when a user logs in to Sendbird server instead of an access token. Go to the [Access token vs. Session token](https://sendbird.com/docs/chat/v3/platform-api/guides/user#2-create-a-user-3-access-token-vs-session-token) section from the [Chat Platform API](https://sendbird.com/docs/chat/v3/platform-api/getting-started/prepare-to-use-api) guide to learn more. + +### Step 3: Create a new open channel + +Create an [open channel](https://sendbird.com/docs/chat/v3/javascript/guides/open-channel#2-create-a-channel). Once created, all users in your Sendbird application can easily participate in the channel. You also can create a [group channel](https://sendbird.com/docs/chat/v3/javascript/guides/group-channel#2-create-a-channel) by [inviting users](https://sendbird.com/docs/chat/v3/javascript/guides/group-channel#2-invite-users-as-members) as new members to the channel. + +> Note: All the methods in the following steps are asynchronous, excluding the `new SendBird()`. As a result, your client app must receive success callbacks from Sendbird server to proceed to the next step. A good way to do this is the nesting of methods: Go to [Step 4: Enter the channel](#step-4-enter-the-channel) to learn more about how you can nest the `openChannel.enter()` in the `OpenChannel.getChannel()` method. + +```javascript +sb.OpenChannel.createChannel(function(openChannel, error) { + if (error) { + return; + } +}); +``` + +### Step 4: Enter the channel + +Enter the channel to send and receive messages. + +```javascript +sb.OpenChannel.getChannel(CHANNEL_URL, function(openChannel, error) { + if (error) { + return; + } + + openChannel.enter(function(response, error) { + if (error) { + return; + } + }) +}); +``` + +### Step 5: Send a message to the channel + +Finally, send a message to the channel. There are [three types](https://sendbird.com/docs/chat/v3/platform-api/guides/messages#-3-resource-representation): a user message, which is a plain text, a file message, which is a binary file, such as an image or PDF, and an admin message, which is a plain text sent through the [dashboard](https://dashboard.sendbird.com/auth/signin) or [Chat Platform API](https://sendbird.com/docs/chat/v3/platform-api/guides/messages#2-send-a-message). + +```javascript +openChannel.sendUserMessage(MESSAGE, DATA, CUSTOM_TYPE, function(message, error) { + if (error) { + return; + } +}); +``` + +
+ +## Appendix + +Sendbird wants customers to be confident that Chat SDK will be useful, work well, and fit within their needs. Thus, we have compiled a couple of optional guidelines. Take a few minutes to read and apply them at your convenience. + +### XSS prevention + +XSS (Cross-site scripting) is a type of computer security vulnerability. XSS helps attackers inject client-side scripts into web pages viewed by other users. Users can send any type of string data without restriction through Chat SDKs. Make sure that you check the safety of received data from other users before rendering it into your DOM. + +> **Note**: For more about the XSS prevention, visit the [OWASP's XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html) page. + +### Use functions of Sendbird objects with Immutable-js + +If you are using the [Immutable-js](https://immutable-js.github.io/immutable-js/) in your web app, instead of the `Immutable.Map()`, call the `Immutable.fromJS()` which converts deeply nested objects to an `Immutable Map`. +So you can call the functions of Sendbird objects because the `fromJS()` method returns internal objects. But if you use a `Map` function, you can't call any functions of a Sendbird object. + +```javascript +var userIds = ['John', 'Harry']; + +sb.GroupChannel.createChannelWithUserIds(userIds, false, NAME, COVER_URL, DATA, function(groupChannel, error) { + if (error) { + return; + } + + var immutableObject = Immutable.fromJS(groupChannel); + console.log(immutableObject); +}); +``` + +### Parameter ordering in callbacks + +In a callback, the `error` parameter is passed last in order by default. For example, the `connect()` method below returns parameters in **(user, error)** order. + +```javascript +sb.connect(USER_ID, function(user, error) {}); +``` + +You can configure your Sendbird application to change the order by calling the `sb.setErrorFirstCallback(true)`. Once **true** is set, all callbacks pass the error as the first parameter. + +```javascript +sb.setErrorFirstCallback(true); +sb.connect(USER_ID, function(error, user) {}); +``` + +The `sb.setErrorFirstCallback(false)` returns callbacks to their original parameter ordering, with errors last. + +> **Note**: Go to the [Event handler](https://sendbird.com/docs/chat/v3/javascript/guides/event-handler) page to learn more about the usages of the Chat SDK's handlers and callbacks. + +
+ +## Notice + +### v.3.1.0 Release (Local Caching) + +Local caching has been introduced to the Chat SDK in this v3.1.0 release. The newly embedded local caching functionalities can be enabled through an optional parameter `localCacheEnabled` in the `Sendbird` constructor, whose default is **false**. When local caching is turned off, the SDK is backward compatible with v3.0. This means it will work exactly the same as v3.0 and therefore is compatible with SyncManager. However, we strongly recommend you to use the Chat SDK with local caching instead of SyncManager for the following reasons: + +- Sendbird Chat SDK with local caching supports new functionalities such as group channel collection, message collection, and message auto-resend. +- SyncManager will be deprecated eventually as the embedded local caching serves as the new and better version of it. + +For further information, please see our [Docs](https://sendbird.com/docs/chat/v3/javascript/guides/local-caching). + +Additionally, migration guide for clients currently using SyncManager will be available soon. + +
+ +## Changelogs + +## v3.1.33 (Aug 24, 2023) +> **Thank you everyone for using our SDK v3. This is our final release as we transition to our latest SDK v4 (first released in Apr 2022). Please reach out to our support if you have any questions.** +### Improvements +- Fixed a bug where called `ChangeLogAPI` infinitely + +If you want to check the record of other versions, go to [Change Log](https://github.com/sendbird/Sendbird-SDK-JavaScript/blob/master/CHANGELOG.md). diff --git a/SendBird.d.ts b/SendBird.d.ts index df4bad1..402b7a2 100644 --- a/SendBird.d.ts +++ b/SendBird.d.ts @@ -1,361 +1,2628 @@ -// Type definitions for SendBird 3.0.x -// Project: https://sendbird.com/ - -interface SendBirdFactory { - new(option: Object): SendBird_Instance; -} - - -/** - * Interface for the SendBird Main - */ -interface SendBird_Instance { - connect(userId: string, callback?: Function): void; - connect(userId: string, accessToken: string, callback?: Function): void; - disconnect(callback?: Function): void; - // You can reinitate auto-reconnect manually. - reconnect(): boolean; - - getConnectionState(): string; - getApplicationId(): string; - - updateCurrentUserInfo(nickname: string, profileImage: string, callback?: Function): void; - - // Push token - registerGCMPushTokenForCurrentUser(gcmRegToken: string, callback?: Function): void; - unregisterGCMPushTokenForCurrentUser(gcmRegToken: string, callback?: Function): void; - unregisterGCMPushTokenAllForCurrentUser(callback?: Function): void; - - registerAPNSPushTokenForCurrentUser(apnsRegToken: string, callback?: Function): void; - unregisterAPNSPushTokenForCurrentUser(apnsRegToken: string, callback?: Function): void; - unregisterAPNSPushTokenAllForCurrentUser(callback: Function): void; - - unregisterPushTokenAllForCurrentUser(callback: Function): void; // This removes both All APNS/GCM tokens - - getPendingGCMToken(): string; - getPendingAPNSToken(): string; - - setDoNotDisturb(doNotDisturbOn: boolean, startHour: number, startMin: number, endHour: number, endMin: number, timezone: string, callback?: Function): void; - getDoNotDisturb(callback: Function): void; - - // Block / Unblock - blockUser(userToBlock: User, callback?: Function): void; - blockUserWithUserId(userToBlock: string, callback?: Function): void; - - unblockUser(blockedUser: User, callback?: Function): void; - unblockUserWithUserId(blockedUserId: string, callback?: Function): void; - - // Channel Handler - ChannelHandler: ChannelHandlerFactory; - - addChannelHandler(id: string, handler: ChannelHandler_Instance): void; - removeChannelHandler(id: string): void; - removeAllChannelHandlers(): void; - - // Connection Handler - ConnectionHandler(): void; - - addConnectionHandler(id: string, handler: ConnectionHandler): void; - removeConnectionHandler(id: string): void; - removeAllConnectionHandlers(): void; - - createUserListQuery(): UserListQuery; - createBlockedUserListQuery(): UserListQuery; - - // Background/Foreground Appstate for push notifications in React Native / Ionic - setBackgroundState(): void; - setForegroundState(): void; - - // State change should be disabled when image picker is loaded in Android. - disableStateChange(): void; - enableStateChange(): void; - - currentUser: User; - GroupChannel: GroupChannel; - OpenChannel: OpenChannel; - UserMessage: UserMessage; -} - -interface ConnectionHandler { - onReconnectStarted(): void; - onReconnectSucceeded(): void; - onReconnectFailed(): void; -} - - /** - * User + * Type Definitions for Sendbird SDK v3.1.33 + * homepage: https://sendbird.com/ + * git: https://github.com/sendbird/Sendbird-SDK-JavaScript */ -interface User { - nickname: string; - profileUrl: string; - userId: string; - connectionStatus: string; - lastSeenAt: string; -} - -interface UserListQuery { - hasNext: boolean; - limit: number; - isLoading: boolean; - - next(callback: Function): void; -} +export = SendBird; +export as namespace SendBird; -/** - * Message - */ -interface BaseMessage { - isGroupChannel(): boolean; - isOpenChannel(): boolean; - - isUserMessage(): boolean; - isAdminMessage(): boolean; - isFileMessage(): boolean; - - channelUrl: string; - messageId: number; - createdAt: number; - channelType: string; - messageType: string; - customType: string; -} +declare const SendBird: SendBirdStatic; -interface AdminMessage extends BaseMessage { - message: string; - data: string; +declare interface SendBirdParams { + appId: string; + localCacheEnabled?: boolean; } -interface UserMessage extends BaseMessage { - message: string; - data: string; - sender: User; -} +interface SendBirdStatic { + version: number; + new(sendBirdParams: SendBirdParams): SendBird.SendBirdInstance; + getInstance(): SendBird.SendBirdInstance; -interface FileMessage extends BaseMessage { - message: string; - sender: User; + LogLevel: SendBird.LogLevel; - url: string; - name: string; - size: number; - type: string; - data: string; - thumbnails : [Object]; + getLogLevel(): typeof SendBird.LogLevel[keyof typeof SendBird.LogLevel]; + setLogLevel(logLevel: typeof SendBird.LogLevel[keyof typeof SendBird.LogLevel]): void; + getAppVersion(): string; + setAppVersion(appVersion: string): void; } -interface ThumbnailSize { - maxWidth: number; - maxHeight: number; +declare enum CollectionEventSource { + // Real-time event types (0 <= code < 1000) + EVENT_CHANNEL_CHANGED, + EVENT_USER_RECEIVED_INVITATION, + EVENT_USER_DECLINED_INVITATION, + EVENT_USER_JOINED, + EVENT_USER_LEFT, + EVENT_CHANNEL_ENTER, + EVENT_CHANNEL_EXIT, + EVENT_CHANNEL_FROZEN, + EVENT_CHANNEL_UNFROZEN, + EVENT_CHANNEL_HIDDEN, + EVENT_CHANNEL_UNHIDDEN, + EVENT_TYPING_STATUS_UPDATED, + EVENT_OPERATOR_UPDATED, + EVENT_CHANNEL_METADATA_UPDATED, + EVENT_CHANNEL_METADATA_DELETED, + EVENT_CHANNEL_METACOUNTER_UPDATED, + EVENT_CHANNEL_METACOUNTER_DELETED, + EVENT_CHANNEL_DELETED, + EVENT_USER_MUTED, + EVENT_USER_UNMUTED, + EVENT_USER_BANNED, + EVENT_USER_UNBANNED, + EVENT_MESSAGE_RECEIVED, + EVENT_MESSAGE_SENT, + EVENT_MESSAGE_UPDATED, + EVENT_MESSAGE_DELETED, + EVENT_READ_RECEIPT_UPDATED, + EVENT_DELIVERY_RECEIPT_UPDATED, + EVENT_MENTION, + EVENT_REACTION_UPDATED, + EVENT_THREAD_INFO_UPDATED, + + // Api request event types (code >= 1000) + CHANNEL_BACKGROUND = 1000, + CHANNEL_CHANGELOG, + MESSAGE_BACKGROUND, + MESSAGE_FILL, + MESSAGE_CHANGELOG, + + LOCAL_MESSAGE_PENDING_CREATED = 2000, + LOCAL_MESSAGE_FAILED, + LOCAL_MESSAGE_CANCELED, + LOCAL_MESSAGE_RESEND_STARTED, + MESSAGE_COLLECTION_FILTER_MISMATCH, } -interface MessageListQuery { - next(messageTimestamp: number, limit: number, reverse: boolean, callback: Function): void; - prev(messageTimestamp: number, limit: number, reverse: boolean, callback: Function): void; - load(messageTimestamp: number, prevLimit: number, nextLimit: number, reverse: boolean, callback: Function): void; +declare enum GroupChannelOrder { + LATEST_LAST_MESSAGE = 'latest_last_message', + CHRONOLOGICAL = 'chronological', + CHANNEL_NAME_ALPHABETICAL = 'channel_name_alphabetical', } -interface PreviousMessageListQuery { - hasMore: boolean; - load(limit: number, reverse: boolean, callback: Function): void; - load(limit: number, reverse: boolean, messageType: string, callback: Function): void; +declare enum MessageCollectionInitPolicy { + CACHE_AND_REPLACE_BY_API = 'cache_and_replace_by_api', } - -/** - * Channel - */ -interface BaseChannel { - isGroupChannel: boolean; - isOpenChannel: boolean; - - url: string; - name: string; - coverUrl: string; - createdAt: number; - data: string; - customType: string; - - createPreviousMessageListQuery() : PreviousMessageListQuery; - createMessageListQuery(): MessageListQuery; - - /* SendMessage */ - sendFileMessage(file: any, callback: Function): void; - sendFileMessage(file: any, data: string, callback: Function): void; - sendFileMessage(file: any, data: string, customType: string, callback: Function): void; - sendFileMessage(file: any, data: string, customType: string, thumbnailSizes: [ThumbnailSize], callback: Function): void; - sendFileMessage(file: any, name: string, type: string, size: number, data: string, callback: Function): void; - sendFileMessage(file: any, name: string, type: string, size: number, data: string, customType: string, callback: Function): void; - sendFileMessage(file: any, name: string, type: string, size: number, data: string, customType: string, thumbnailSizes: [ThumbnailSize], callback: Function): void; - - sendUserMessage(message: string, callback: Function): void; - sendUserMessage(message: string, data: string, callback: Function): void; - sendUserMessage(message: string, data: string, customType: string, callback: Function): void; - sendUserMessage(message: string, data: string, customType: string, targetLanguages: [string], callback: Function): void; - - /* MetaCounter */ - createMetaCounters(metaCounterMap: Object, callback: Function): void; - updateMetaCounters(metaCounterMap: Object, upsert: boolean, callback: Function): void; - increaseMetaCounters(metaCounterMap: Object, callback: Function): void; - decreaseMetaCounters(metaCounterMap: Object, callback: Function): void; - getMetaCounters(keys: Object, callback: Function): void; - getAllMetaCounters(callback: Function): void; - deleteMetaCounter(key: string, callback: Function): void; - deleteAllMetaCounters(callback: Function): void; - - /* MetaData */ - createMetaData(metaDataMap: Object, callback: Function): void; - updateMetaData(metaDataMap: Object, upsert: boolean, callback: Function): void; - getMetaData(keys: Object, callback: Function): void; - getAllMetaData(callback: Function): void; - deleteMetaData(key: string, callback: Function): void; - deleteAllMetaData(callback: Function): void; - - deleteMessage(message: FileMessage|UserMessage, callback: Function): void; - - /* GetMessages */ - getNextMessagesByTimestamp(ts: number, isInclusive: boolean, nextResultSize: number, shouldReverse:boolean, messageType: string, customType: string, callback: Function): void; - getPreviousMessagesByTimestamp(ts: number, isInclusive: boolean, prevtResultSize: number, shouldReverse:boolean, messageType: string, customType: string, callback: Function): void; - getPreviousAndNextMessagesByTimestamp(ts: number, prevtResultSize: number, nextResultSize: number, shouldReverse:boolean, messageType: string, customType: string, callback: Function): void; - getNextMessagesByID(messageId: number, isInclusive: boolean, nextResultSize: number, shouldReverse:boolean, messageType: string, customType: string, callback: Function): void; - getPreviousMessagesByID(messageId: number, isInclusive: boolean, prevtResultSize: number, shouldReverse:boolean, messageType: string, customType: string, callback: Function): void; - getPreviousAndNextMessagesByID(messageId: number, prevtResultSize: number, nextResultSize: number, shouldReverse:boolean, messageType: string, customType: string, callback: Function): void; - +declare enum QueryType { + AND = 'AND', + OR = 'OR', } - -interface ChannelHandlerFactory { - new(): ChannelHandler_Instance; +declare enum SearchField { + MEMBER_NICKNAME = 'member_nickname', + CHANNEL_NAME = 'channel_name', } - -interface ChannelHandler_Instance { - onMessageReceived(channel: GroupChannel|OpenChannel, message: AdminMessage|UserMessage): void; - onMessageDeleted(channel: GroupChannel, messageId: number): void; - onReadReceiptUpdated(channel: GroupChannel): void; - onTypingStatusUpdated(channel: GroupChannel): void; - onTypingStatusUpdated(channel: GroupChannel): void; - onUserJoined(channel: GroupChannel, user: User): void; - onUserLeft(channel: GroupChannel, user: User): void; - onUserEntered(channel: OpenChannel, user: User): void; - onUserExited(channel: OpenChannel, user: User): void; - onUserMuted(channel: OpenChannel, user: User): void; - onUserUnmuted(channel: OpenChannel, user: User): void; - onUserBanned(channel: OpenChannel, user: User): void; - onUserUnbanned(channel: OpenChannel, user: User): void; - onChannelFrozen(channel: OpenChannel): void; - onChannelUnfrozen(channel: OpenChannel): void; - onChannelChanged(channel: OpenChannel|GroupChannel): void; - onChannelDeleted(channelUrl: string): void; +declare enum MemberStateFilter { + ALL = 'all', + JOINED = 'joined_only', + INVITED = 'invited_only', + INVITED_BY_FRIEND = 'invited_by_friend', + INVITED_BY_NON_FRIEND = 'invited_by_non_friend', } - - -/** - * Open Channel - */ -interface OpenChannel extends BaseChannel { - - createChannel(callback: Function): void; - createChannel(name: string, coverUrl: string, data: any, callback: Function): void; - createChannel(name: string, coverUrl: string, data: any, operatorUserIds: any, callback: Function): void; - createChannel(name: string, coverUrl: string, data: any, operatorUserIds: any, customType: Function, callback: Function): void; - - enter(callback: Function): void; - exit(callback: Function): void; - - getChannel(channelUrl: string, callback: Function): void; - - refresh(): void; - - createParticipantListQuery(): UserListQuery; - createMutedUserListQuery(): UserListQuery; - createBannedUserListQuery(): UserListQuery; - - banUser(user: User, seconds: number, callback: Function): void; - banUserWithUserId(userId: string, seconds: number, callback: Function): void; - - unbanUser(user: User, callback: Function): void; - unbanUserWithUserId(userId: string, callback: Function): void; - - muteUser(user: User, callback: Function): void; - muteUserWithUserId(userId: string, callback: Function): void; - - unmuteUser(user: User, callback: Function): void; - unmuteUserWithUserId(userId: string, callback: Function): void; - - isOperator(user: User): boolean; - isOperatorWithUserId(userId: string): boolean; - - createOpenChannelListQuery(): OpenChannelListQuery; +declare enum SuperChannelFilter { + ALL = 'all', + SUPER = 'super', + NON_SUPER = 'nonsuper', } - -interface OpenChannelListQuery { - limit: number; - hasNext: boolean; - next(callback: Function): void; +declare enum PublicChannelFilter { + ALL = 'all', + PUBLIC = 'public', + PRIVATE = 'private', } - -interface OpenChannelParticipantListQuery { - limit: number; - hasNext: boolean; - mutedOnly: boolean; - next(callback: Function): void; +declare enum UnreadChannelFilter { + ALL = 'all', + UNREAD_MESSAGE = 'unread_message', } - - -/** - * Group Channel - */ -interface GroupChannelListQuery { - limit: number; - includeEmpty: boolean; - order: string; - hasNext: boolean; - next(callback: Function): void; +declare enum HiddenChannelFilter { + ALL = 'all', + UNHIDDEN = 'unhidden_only', + HIDDEN = 'hidden_only', + HIDDEN_ALLOW_AUTO_UNHIDE = 'hidden_allow_auto_unhide', + HIDDEN_PREVENT_AUTO_UNHIDE = 'hidden_prevent_auto_unhide', } -interface GroupChannel extends BaseChannel { - createChannel(users: [User], isDistinct: boolean, callback: Function): void; - createChannel(users: [User], isDistinct: boolean, callback: Function): void; - createChannelWithUserIds(userIds: [string], isDistinct: boolean, name: string, coverUrl: string, data: any, callback: Function): void; - createChannelWithUserIds(userIds: [string], isDistinct: boolean, name: string, coverUrl: string, data: any, customType: string, callback: Function): void; - createChannelWithUserIds(userIds: [string], isDistinct: boolean, name: string, coverImageFile: Object, data: any, callback: Function): void; - createChannelWithUserIds(userIds: [string], isDistinct: boolean, name: string, coverImageFile: Object, data: any, customType: string, callback: Function): void; - - getChannel(channelUrl: string, callback: Function): void; - - markAsRead(): void; - markAsReadAll(callback: Function): void; - - refresh(callback: Function): void; - - invite(users: [User], callback: Function): void; - inviteWithUserIds(userIds: [string], callback: Function): void; - - hide(callback: Function): void; - leave(callback: Function): void; - markAsRead(): void; - - getReadReceipt(message: UserMessage): number; - updateReadReceipt(userId: string, timestamp: number): void; - - startTyping(): void; - endTyping(): void; - isTyping(): boolean; - getTypingMembers(): [number, User]; - getTotalUnreadMessageCount(callback: Function): void; - - isDistinct: boolean; - unreadMessageCount: number; - members: [number, User]; - lastMessage: BaseMessage; - memberCount: number; - - createMyGroupChannelListQuery(): GroupChannelListQuery; - - setPushPreference(pushOn: boolean, callback: Function): void; - getPushPreference(callback: Function): void; - - getReadStatus(): Object; +declare namespace SendBird { + interface SendBirdError extends Error { + code: number; + message: string; + } + + /** + * @deprecated + */ + type voidErrorLastCallback = (result: null, error: SendBirdError) => void; + type voidErrorFirstCallback = (error: SendBirdError) => void; + type voidCallback = voidErrorFirstCallback | voidErrorLastCallback; + + type ListenerCallback = () => void; + type Unsubscribe = () => void; + + type userCallback = (user: User, error: SendBirdError) => void; + type pushSettingCallback = (response: string, error: SendBirdError) => void; + + type getFriendChangeLogs = { + updatedUsers: Array; + deletedUserIds: Array; + hasMore: boolean; + token: string; + }; + type getFriendChangeLogsByTokenHandler = (data: getFriendChangeLogs, error: SendBirdError) => void; + + type groupChannelChangeLogs = { + updatedChannels: Array; + deletedChannelUrls: Array; + hasMore: boolean; + token: string; + }; + type getGroupChannelChangeLogsHandler = (data: groupChannelChangeLogs, error: SendBirdError) => void; + + type getEmojiContainerHandler = (data: EmojiContainer, error: SendBirdError) => void; + + type getEmojiCategoryHandler = (data: EmojiCategory, error: SendBirdError) => void; + + type getEmojiHandler = (data: Emoji, error: SendBirdError) => void; + + type pushTokens = { + deviceTokens: Array; + type: 'gcm' | 'apns' | 'apns_voip'; + hasMore: boolean; + token: string; + }; + type getMyPushTokensHandler = (data: pushTokens, error: SendBirdError) => void; + + type LogLevel = { + VERBOSE: 'verbose', + DEBUG: 'debug', + INFO: 'info', + WARN: 'warn', + ERROR: 'error', + NONE: 'none', + }; + + type MessageTypeFilter = { + ALL: '', + USER: 'MESG', + FILE: 'FILE', + ADMIN: 'ADMM' + }; + + type ReplyType = { + ALL: 'all', + NONE: 'none', + ONLY_REPLY_TO_CHANNEL: 'only_reply_to_channel' + } + + type RestrictionType = { + MUTED: 'muted', + BANNED: 'banned' + }; + + type MessageSendingStatus = { + NONE: 'none', + PENDING: 'pending', + FAILED: 'failed', + CANCELED: 'canceled', + SUCCEEDED: 'succeeded' + }; + + interface DiscoveryObject { + friendDiscoveryKey: string; + friendName?: string; + } + interface SendBirdInstance { + PUSH_TEMPLATE_DEFAULT: string; + PUSH_TEMPLATE_ALTERNATIVE: string; + + User: UserStatic; + Member: MemberStatic; + RestrictedUser: RestrictedUserStatic; + BaseChannel: { + MessageTypeFilter: MessageTypeFilter; + }; + OpenChannel: OpenChannelStatic; + GroupChannel: GroupChannelStatic; + + GroupChannelCollection: GroupChannelCollectionStatic; + GroupChannelFilter: GroupChannelFilterStatic; + + MessageCollection: MessageCollectionStatic; + MessageFilter: MessageFilterStatic; + + BaseMessage: { + ReplyType: ReplyType; + getMessage(params: MessageRetrievalParams, callback?: messageCallback): Promise; + }; + UserMessage: UserMessageStatic; + FileMessage: FileMessageStatic; + AdminMessage: AdminMessageStatic; + + MessageMetaArray: MessageMetaArray; + Options: Options; + + SessionHandler: SessionHandlerStatic; + UserEventHandler: UserEventHandlerStatic; + ChannelHandler: ChannelHandlerStatic; + ConnectionHandler: ConnectionHandlerStatic; + + GroupChannelParams: GroupChannelParams; + OpenChannelParams: OpenChannelParams; + GroupChannelListQuery: GroupChannelListQueryStatic; + UserMessageParams: UserMessageParams; + FileMessageParams: FileMessageParams; + GroupChannelTotalUnreadMessageCountParams: GroupChannelTotalUnreadMessageCountParams; + GroupChannelTotalUnreadChannelCountParams: GroupChannelTotalUnreadChannelCountParams; + ScheduledUserMessageParams: ScheduledUserMessageParams; + GroupChannelChangeLogsParams: GroupChannelChangeLogsParams; + MessageRetrievalParams: MessageRetrievalParams; + MessageListParams: MessageListParams; + ThreadedMessageListParams: ThreadedMessageListParams; + MessageChangeLogsParams: MessageChangeLogsParams; + + CollectionEventSource: typeof CollectionEventSource; + + currentUser: User; + appInfo: AppInfo; + ekey: string; + isCacheEnabled: boolean; + + setErrorFirstCallback(errorFirstCallback: boolean): void; + + connect(userId: string, callback?: userCallback): Promise; + connect(userId: string, accessToken: string, callback?: userCallback): Promise; + connect(userId: string, apiHost: string, wsHost: string, callback?: userCallback): Promise; + connect(userId: string, accessToken: string, apiHost: string, wsHost: string, callback?: userCallback): Promise; + + disconnect(callback?: commonCallback): Promise; + + reconnect(): boolean; // You can initiate auto-reconnect manually. + + updateCurrentUserInfo(nickname: string, profileUrl: string, callback?: userCallback): Promise; + updateCurrentUserInfoWithProfileImage(nickname: string, profileImageFile: FileType, callback?: userCallback): Promise; + updateCurrentUserInfoWithPreferredLanguages(preferredLanguages: Array, callback?: userCallback): Promise; + + /** + * @deprecated since version v3.0.109, please use {@link currentUser} instead + */ + getCurrentUserId(): string; + getApplicationId(): string; + getConnectionState(): string; + getLastConnectedAt(): number; + + setSessionHandler(handler: SessionHandler): void; + + addChannelHandler(id: string, handler: ChannelHandler): void; + removeChannelHandler(id: string): void; + removeAllChannelHandlers(): void; + + addConnectionHandler(id: string, handler: ConnectionHandler): void; + removeConnectionHandler(id: string): void; + removeAllConnectionHandlers(): void; + + addUserEventHandler(id: string, handler: UserEventHandler): void; + removeUserEventHandler(id: string): void; + removeAllUserEventHandler(): void; + + /** + * @deprecated since version v3.0.86, please use {@link createApplicationUserListQuery()} instead + */ + createUserListQuery(): UserListQuery; + /** + * @deprecated since version v3.0.86, please use {@link createApplicationUserListQuery()} instead + */ + createUserListQuery(userIds: Array): UserListQuery; + createApplicationUserListQuery(): ApplicationUserListQuery; + createBlockedUserListQuery(): BlockedUserListQuery; + createMessageSearchQuery(keyword: String, options?: MessageSearchQueryOptions): MessageSearchQuery; + + blockUser(userToBlock: User, callback?: userCallback): Promise; + blockUserWithUserId(userToBlock: string, callback?: userCallback): Promise; + + unblockUser(blockedUser: User, callback?: commonCallback): Promise; + unblockUserWithUserId(blockedUserId: string, callback?: commonCallback): Promise; + + setChannelInvitationPreference(isAutoAccept: boolean, callback?: commonCallback): Promise; + getChannelInvitationPreference(callback?: commonCallback): Promise; + + getPendingGCMToken(): string; + getPendingAPNSToken(): string; + + registerGCMPushTokenForCurrentUser(gcmRegToken: string, callback?: pushSettingCallback): string; + unregisterGCMPushTokenForCurrentUser(gcmRegToken: string, callback?: commonCallback): void; + unregisterGCMPushTokenAllForCurrentUser(callback?: commonCallback): void; + + registerAPNSPushTokenForCurrentUser(apnsRegToken: string, callback?: pushSettingCallback): string; + unregisterAPNSPushTokenForCurrentUser(apnsRegToken: string, callback?: commonCallback): void; + unregisterAPNSPushTokenAllForCurrentUser(callback?: commonCallback): void; + + unregisterPushTokenAllForCurrentUser(callback?: commonCallback): void; // This removes all push tokens including APNS/GCM + getMyPushTokensByToken(token: string, type: 'gcm' | 'apns' | 'apns_voip', callback?: getMyPushTokensHandler): Promise; + + setPushTemplate(templateName: string, callback?: pushSettingCallback): string | void; + getPushTemplate(callback?: pushSettingCallback): string | void; + + setPushTriggerOption(pushTriggerOption: 'all' | 'mention_only' | 'off', callback?: commonCallback): Promise; + getPushTriggerOption(callback?: getPushTriggerOptionCallback): Promise; + + setDoNotDisturb( + doNotDisturbOn: boolean, + startHour: number, + startMin: number, + endHour: number, + endMin: number, + timezone: string, + callback?: commonCallback + ): Promise; + getDoNotDisturb(callback?: commonCallback): Promise; + + setSnoozePeriod(snoozeOn: boolean, startTs: number, endTs: number, callback?: commonCallback): Promise; + getSnoozePeriod(callback?: commonCallback): Promise; + + // Background/Foreground Appstate for push notifications in React Native / Ionic + setBackgroundState(): void; + setForegroundState(): void; + + // State change should be disabled when image picker is loaded in Android. + disableStateChange(): void; + enableStateChange(): void; + + uploadFriendDiscoveries(discoveries: Array, callback?: commonCallback): Promise; + deleteFriendDiscovery(discoveryKey: string, callback?: commonCallback): Promise; + deleteFriendDiscoveries(discoveryKeys: Array, callback?: commonCallback): Promise; + + getFriendChangeLogsByToken(callback?: getFriendChangeLogsByTokenHandler): Promise; + getFriendChangeLogsByToken(token: string, callback?: getFriendChangeLogsByTokenHandler): Promise; + + addFriends(userIds: Array, callback?: userListQueryCallback): Promise>; + deleteFriend(userId: string, callback?: commonCallback): Promise; + deleteFriends(userIds: Array, callback?: commonCallback): Promise; + + createFriendListQuery(): FriendListQuery; + + markAsReadAll(callback?: commonCallback): Promise; + markAsReadWithChannelUrls(channelUrls: Array, callback?: commonCallback): Promise; + + markAsDelivered(channelUrl: String): void; + + getGroupChannelCount(memberStateFilter: string, callback?: commonCallback): Promise; + + getUnreadItemCount(keys: Array, callback?: commonCallback): Promise; + getTotalUnreadMessageCount( + groupChannelTotalUnreadMessageCountParams: GroupChannelTotalUnreadMessageCountParams, + callback?: groupChannelCountCallback + ): Promise; + getTotalUnreadMessageCount(channelCustomTypes: Array, callback?: groupChannelCountCallback): Promise; + /** + * @deprecated since version v3.0.80, please use {@link getTotalUnreadMessageCount()} instead + */ + getTotalUnreadMessageCount(callback?: groupChannelCountCallback): Promise; + getTotalUnreadChannelCount(callback?: groupChannelCountCallback): Promise; + getTotalUnreadChannelCount( + groupChannelTotalUnreadChannelCountParams: GroupChannelTotalUnreadChannelCountParams, + callback?: groupChannelCountCallback + ): Promise; + + getSubscribedTotalUnreadMessageCount(): number; + getSubscribedCustomTypeTotalUnreadMessageCount(): number; + getSubscribedCustomTypeUnreadMessageCount(customType: string): number; + + getMyGroupChannelChangeLogsByToken( + token: string, + params: GroupChannelChangeLogsParams, + callback?: getGroupChannelChangeLogsHandler + ): Promise; + /** + * @deprecated since version v3.0.125 + */ + getMyGroupChannelChangeLogsByToken( + token: string, + customTypes: Array, + includeEmpty?: boolean, + callback?: getGroupChannelChangeLogsHandler + ): Promise; + getMyGroupChannelChangeLogsByTimestamp( + ts: number, + params: GroupChannelChangeLogsParams, + callback?: getGroupChannelChangeLogsHandler + ): Promise; + /** + * @deprecated since version v3.0.125 + */ + getMyGroupChannelChangeLogsByTimestamp( + ts: number, + customTypes: Array, + includeEmpty?: boolean, + callback?: getGroupChannelChangeLogsHandler + ): Promise; + + getAllEmoji(callback?: getEmojiContainerHandler): Promise; + getEmojiCategory(categoryId: number, callback?: getEmojiCategoryHandler): Promise; + getEmoji(emojiKey: string, callback?: getEmojiHandler): Promise; + + getAllowFriendDiscovery(callback?: commonCallback): Promise; + setAllowFriendDiscovery(allowFriendDiscovery: boolean, callback?: commonCallback): Promise; + + clearCachedMessages(channelUrls: string[]): Promise; + clearCachedData(): Promise; + + useAsyncStorageAsDatabase(AsyncStorage: object): void; + useMMKVAsDatabase(MMKV: object): void; + + /** + * Set online listener to onlineDetector for mobile environment + * */ + setOnlineListener(onlineListener: (onOnline: ListenerCallback) => Unsubscribe): void; + /** + * Set offline listener to onlineDetector for mobile environment + * */ + setOfflineListener(offlineListener: (onOffline: ListenerCallback) => Unsubscribe): void; + } + interface Options { + useMemberAsMessageSender: boolean; + typingIndicatorThrottle: number; + websocketResponseTimeout: number; + } + interface AppInfo { + uploadSizeLimit: number; + emojiHash: string; + premiumFeatureList: Array; + applicationAttributes: Array; + isUsingReaction: boolean; + } + + interface FriendListQuery { + hasMore: boolean; + isLoading: boolean; + limit: number; + next(callback?: userListQueryCallback): Promise>; + } + interface MessageSearchQuery { + hasNext: boolean; + isLoading: boolean; + next(callback?: messageListCallback): Promise>; + } + interface MessageSearchQueryOptions { + limit?: number; + reverse?: boolean; + exactMatch?: boolean; + channelUrl?: string; + channelCustomType?: string; + messageTimestampFrom?: number; + messageTimestampTo?: number; + order?: 'score' | 'ts'; + advancedQuery?: boolean; + targetFields?: Array; + } + + interface SessionHandlerStatic { + new(): SessionHandler; + } + interface SessionHandler { + /** + * @deprecated since v3.0.160 + */ + onSessionExpired(): void; + onSessionTokenRequired(onSuccess: (accessToken: string) => void, onFail: () => void): void; + onSessionRefreshed(): void; + onSessionError(err: SendBirdError): void; + onSessionClosed(): void; + } + + interface UserEventHandlerStatic { + new(): UserEventHandler; + } + interface UserEventHandler { + onFriendsDiscovered(users: Array): void; + onTotalUnreadMessageCountUpdated(totalCount: Number, countByCustomTypes: Object): void; + } + + interface ChannelHandlerStatic { + new(): ChannelHandler; + } + interface ChannelHandler { + onMessageReceived(channel: OpenChannel | GroupChannel, message: AdminMessage | UserMessage | FileMessage): void; + onMessageUpdated(channel: OpenChannel | GroupChannel, message: AdminMessage | UserMessage | FileMessage): void; + onMessageDeleted(channel: OpenChannel | GroupChannel, messageId: number): void; + onReadReceiptUpdated(channel: GroupChannel): void; + onTypingStatusUpdated(channel: GroupChannel): void; + onUserJoined(channel: GroupChannel, user: User): void; + onUserLeft(channel: GroupChannel, user: User): void; + onOperatorUpdated(channel: BaseChannel, operators: Array): void; + onUserEntered(channel: OpenChannel, user: User): void; + onUserExited(channel: OpenChannel, user: User): void; + onUserMuted(channel: OpenChannel | GroupChannel, user: User): void; + onUserUnmuted(channel: OpenChannel | GroupChannel, user: User): void; + onUserBanned(channel: OpenChannel | GroupChannel, user: User): void; + onUserUnbanned(channel: OpenChannel | GroupChannel, user: User): void; + onChannelFrozen(channel: OpenChannel | GroupChannel): void; + onChannelUnfrozen(channel: OpenChannel | GroupChannel): void; + onChannelChanged(channel: OpenChannel | GroupChannel): void; + onChannelDeleted(channelUrl: string, channelType: string): void; + onUserReceivedInvitation(channel: GroupChannel, inviter: User, invitees: Array): void; + onUserDeclinedInvitation(channel: GroupChannel, inviter: User, invitee: Member): void; + onMetaDataCreated(channel: OpenChannel | GroupChannel, metaData: Object): void; + onMetaDataUpdated(channel: OpenChannel | GroupChannel, metaData: Object): void; + onMetaDataDeleted(channel: OpenChannel | GroupChannel, metaDataKeys: Array): void; + onMetaCountersCreated(channel: OpenChannel | GroupChannel, metaCounter: Object): void; + onMetaCountersUpdated(channel: OpenChannel | GroupChannel, metaCounter: Object): void; + onMetaCountersDeleted(channel: OpenChannel | GroupChannel, metaCounterKeys: Array): void; + onChannelHidden(channel: GroupChannel): void; + onReactionUpdated(channel: OpenChannel | GroupChannel, event: ReactionEvent): void; + onDeliveryReceiptUpdated(channel: OpenChannel | GroupChannel): void; + onMentionReceived(channel: OpenChannel | GroupChannel, message: AdminMessage | UserMessage | FileMessage): void; + onThreadInfoUpdated(channel: OpenChannel | GroupChannel, event: ThreadInfoUpdateEvent): void; + onChannelMemberCountChanged(channels: Array): void; + onChannelParticipantCountChanged(channels: Array): void; + } + + interface ConnectionHandlerStatic { + new(): ConnectionHandler; + } + interface ConnectionHandler { + onReconnectStarted(): void; + onReconnectSucceeded(): void; + onReconnectFailed(): void; + } + + interface MessageFilter { + messageType: string; + customTypes: string[]; + senderUserIds: string[]; + sendingStatus: string; + + clone(): MessageFilter; + match(message: BaseMessageInstance): boolean; + } + + interface MessageFilterStatic { + new(): MessageFilter; + } + + /** + * Message + */ + interface BaseMessageInstance { + channelUrl: string; + channelType: string | null; + messageId: number; + messageType: 'base' | 'user' | 'file' | 'admin'; + data: string | null; + customType: string | null; + metaArrays: Array; + reactions: Array; + mentionType: string | null; + mentionedMessageTemplate: string | null; + mentionedUsers: Array; + sendingStatus: MessageSendingStatus[keyof MessageSendingStatus] | null; + silent: boolean; + createdAt: number; + updatedAt: number; + parentMessageId: number; + parentMessageText: string | null; + threadInfo: ThreadInfo | null; + ogMetaData: OGMetaData | null; + appleCriticalAlertOptions: AppleCriticalAlertOptions | null; + isReplyToChannel: boolean; + parentMessage: UserMessage | FileMessage | AdminMessage | null; + + isEqual(target: BaseMessageInstance): boolean; + isIdentical(target: BaseMessageInstance): boolean; + isOpenChannel(): boolean; + isGroupChannel(): boolean; + isUserMessage(): this is UserMessage; + isFileMessage(): this is FileMessage; + isAdminMessage(): this is AdminMessage; + serialize(): Object; + getMetaArraysByKeys(keys: Array): Array; + applyReactionEvent(event: ReactionEvent): void; + getThreadedMessagesByTimestamp( + timestamp: number, + params: ThreadedMessageListParams, + callback?: threadedMessageCallback + ): Promise; + applyThreadInfoUpdateEvent(event: ThreadInfoUpdateEvent): boolean; + + /** + * @deprecated + */ + metaArray: Object; + /** + * @deprecated + */ + getMetaArrayByKeys(keys: Array): Object; + applyParentMessage(updatedParentMessage: UserMessage | FileMessage | AdminMessage): boolean; + } + + interface AdminMessage extends BaseMessageInstance { + messageType: 'admin'; + message: string; + translations: Object; + } + interface AdminMessageStatic { + buildFromSerializedData(serializedObject: Object): AdminMessage; + getMessage(params: MessageRetrievalParams, callback?: messageCallback): Promise; + } + + interface GroupChannelTotalUnreadMessageCountParams { + new(): GroupChannelTotalUnreadMessageCountParams; + channelCustomTypesFilter: Array; + superChannelFilter: 'all' | 'super' | 'nonsuper' | 'broadcast_only'; + } + + interface GroupChannelTotalUnreadChannelCountParams { + new(): GroupChannelTotalUnreadChannelCountParams; + channelCustomTypesFilter: Array; + superChannelFilter: 'all' | 'super' | 'nonsuper' | 'broadcast_only'; + } + + interface Emoji { + key: string; + url: string; + } + + interface EmojiCategory { + id: number; + name: string; + url: string; + emojis: Array; + } + + interface EmojiContainer { + emojiHash: string; + emojiCategories: Array; + } + + interface BaseMessageParams { + mentionType: 'users' | 'channel'; + mentionedUserIds: Array; + mentionedUsers: Array; + mentionedMessageTemplate: string | null; + metaArrays: Array; + /** + * @deprecated since version v3.0.122, please use {@link metaArrays} instead + */ + metaArrayKeys: Array; + data: string; + customType: string; + pushNotificationDeliveryOption: 'default' | 'suppress'; + parentMessageId: number; + appleCriticalAlertOptions: AppleCriticalAlertOptions; + isReplyToChannel: boolean; + + serialize(): Object; + } + + interface UserMessageParams extends BaseMessageParams { + new(): UserMessageParams; + message: string; + /** + * @deprecated since version v3.0.84, please use {@link translationTargetLanguages} instead + */ + targetLanguages: Array; + translationTargetLanguages: Array; + } + interface UserMessage extends BaseMessageInstance { + messageType: 'user'; + message: string | null; + sender: Sender | null; + reqId: string; + translations: Object; + /** + * @deprecated since version v3.0.119, please use {@link BaseMessageInstance.sendingStatus} instead + */ + requestState: 'none' | 'pending' | 'failed' | 'succeeded' | null; + requestedMentionUserIds: Array; + errorCode: number; + messageSurvivalSeconds: number; + plugins: Array; + + readonly messageParams: UserMessageParams | null; + + isResendable(): boolean; + serialize(): Object; + } + interface UserMessageStatic { + buildFromSerializedData(serializedObject: Object): UserMessage; + getMessage(params: MessageRetrievalParams, callback?: messageCallback): Promise; + } + + interface FileMessageParams extends BaseMessageParams { + new(): FileMessageParams; + file: FileType; + fileUrl: string; + fileName: string; + fileSize: number; + mimeType: string; + thumbnailSizes: Array; + } + interface FileMessage extends BaseMessageInstance { + messageType: 'file'; + sender: Sender | null; + reqId: string; + plainUrl: string | null; + url: string; + name: string; + size: number; + type: string | null; + thumbnails: Array; + /** + * @deprecated since version v3.0.119, please use {@link BaseMessageInstance.sendingStatus} instead + */ + requestState: 'none' | 'pending' | 'failed' | 'succeeded' | null; + requestedMentionUserIds: Array; + errorCode: number; + messageSurvivalSeconds: number; + + readonly messageParams: FileMessageParams | null; + + isResendable(): boolean; + serialize(): Object; + } + interface FileMessageStatic { + buildFromSerializedData(serializedObject: Object): FileMessage; + getMessage(params: MessageRetrievalParams, callback?: messageCallback): Promise; + } + + interface MessageRetrievalParams { + new(): MessageRetrievalParams; + channelUrl: string; + channelType: string; + messageId: number; + includeMetaArray: boolean; + includeReactions: boolean; + /** + * @deprecated since version v3.0.159, please use {@link includeParentMessageInfo} instead + */ + includeParentMessageText: boolean; + includeThreadInfo: boolean; + includeParentMessageInfo: boolean; + } + interface MessageListParams { + new(): MessageListParams; + prevResultSize: number; + nextResultSize: number; + isInclusive: boolean; + reverse: boolean; + messageType: string; + /** + * @deprecated since version v3.0.142, please use {@link customTypes} instead + */ + customType: string; + customTypes: Array; + senderUserIds: Array; + includeMetaArray: boolean; + /** + * @deprecated since version v3.0.125, please use {@link includeReactions} instead + */ + includeReaction: boolean; + includeReactions: boolean; + /** + * @deprecated since version v3.0.159, please use {@link replyType} instead + */ + includeReplies: boolean; + /** + * @deprecated since version v3.0.159, please use {@link includeParentMessageInfo} instead + */ + includeParentMessageText: boolean; + includeThreadInfo: boolean; + showSubchannelMessagesOnly: boolean; + replyType: ReplyType[keyof ReplyType]; + includeParentMessageInfo: boolean; + + belongsTo(messageParams: UserMessageParams | FileMessageParams): boolean; + } + interface ThreadedMessageListParams { + new(): ThreadedMessageListParams; + prevResultSize: number; + nextResultSize: number; + isInclusive: boolean; + reverse: boolean; + messageType: string; + /** + * @deprecated since version v3.0.142, please use {@link customTypes} instead + */ + customType: string; + customTypes: Array; + senderUserIds: Array; + includeMetaArray: boolean; + /** + * @deprecated since version v3.0.125, please use {@link includeReactions} instead + */ + includeReaction: boolean; + includeReactions: boolean; + /** + * @deprecated since version v3.0.159, please use {@link includeParentMessageInfo} instead + */ + includeParentMessageText: boolean; + includeParentMessageInfo: boolean; + } + interface MessageChangeLogsParams { + new(): MessageChangeLogsParams; + includeMetaArray: boolean; + /** + * @deprecated since version v3.0.125, please use {@link includeReactions} instead + */ + includeReaction: boolean; + includeReactions: boolean; + /** + * @deprecated since version v3.0.159, please use {@link replyType} instead + */ + includeReplies: boolean; + /** + * @deprecated since version v3.0.159, please use {@link includeParentMessageInfo} instead + */ + includeParentMessageText: boolean; + includeThreadInfo: boolean; + replyType: ReplyType[keyof ReplyType]; + includeParentMessageInfo: boolean; + } + + interface ThumbnailObject { + url: string; + plainUrl: string; + height: number; + width: number; + real_height: number; + real_width: number; + } + interface ThumbnailSize { + maxWidth: number; + maxHeight: number; + } + + /** + * File interface for React Native + * @see {@link https://github.com/facebook/react-native/blob/main/Libraries/Network/FormData.js#L73-L85} for further information about interface. + * For the reason that the name and type properties are not optional, refer {@link module:utils/FileConverter#isFileLikeObject} + */ + interface ReactNativeFileLikeObject { + uri: string; + name: string; + type: string + size?: number; + } + + type FileType = File | Blob | ReactNativeFileLikeObject; + + /** + * User + */ + interface User { + userId: string; + nickname: string; + profileUrl: string; + plainProfileUrl: string; + metaData: Object; + connectionStatus: string; + lastSeenAt: number; + isActive: boolean; + requireAuth: boolean; + friendDiscoveryKey: string | null; + friendName: string | null; + preferredLanguages: Array; + + getOriginalProfileUrl(): string; + createMetaData(metaDataMap: Object, callback?: commonCallback): Promise; + updateMetaData(metaDataMap: Object, upsert?: boolean, callback?: commonCallback): void; + deleteMetaData(metaDataKey: string, callback?: commonCallback): Promise; + deleteAllMetaData(callback?: commonCallback): Promise; + + serialize(): Object; + } + interface UserStatic { + buildFromSerializedData(serializedObject: Object): User; + } + + interface Sender extends User { + isBlockedByMe: boolean; + } + + interface Member extends User { + state: 'invited' | 'joined'; + role: 'none' | 'operator'; + isMuted: boolean; + isBlockedByMe: boolean; + isBlockingMe: boolean; + restrictionInfo: RestrictionInfo; + } + interface MemberStatic { + buildFromSerializedData(serializedObject: Object): Member; + } + + interface RestrictionInfo { + restrictionType: RestrictionType[keyof RestrictionType]; + description: string; + endAt: number; + } + interface RestrictedUser extends User { + restrictionInfo: RestrictionInfo; + } + interface RestrictedUserStatic { + RestrictionType: RestrictionType; + } + + /** + * Channel + */ + type fileMessagesCallbackObject = { + progress: (event: ProgressEvent, messageRequestId: string) => void; + sent: (message: FileMessage, error: SendBirdError) => void; + complete: (error: SendBirdError) => void; + }; + type messageCallback = (message: T, error: SendBirdError) => void; + type reactionEventCallback = (event: ReactionEvent, error: SendBirdError) => void; + type cancelUploadingFileMessageCallback = (isSuccess: boolean, error: SendBirdError) => void; + type fileUploadprogressHandler = (event: ProgressEvent) => void; + type messageChangeLogs = { + updatedMessages: Array; + deletedMessageIds: Array; + hasMore: boolean; + token: string; + }; + type getMessageChangeLogsHandler = (data: messageChangeLogs, error: SendBirdError) => void; + type mutedInfo = { + isMuted: boolean; + startAt: number; + endAt: number; + remainingDuration: number; + description: string; + }; + type getMyMutedInfoHandler = (info: mutedInfo, error: SendBirdError) => void; + + interface BaseChannel { + url: string; + name: string; + coverUrl: string; + data: string | null; + customType: string | null; + isFrozen: boolean; + isEphemeral: boolean; + creator: User | null; + createdAt: number; + + isGroupChannel(): this is GroupChannel; + isOpenChannel(): this is OpenChannel; + serialize(): Object; + + /** + * @deprecated since version v3.0.123, please use {@link getMessageChangeLogsSinceToken()} instead + */ + getMessageChangeLogsByToken(token: string, callback?: getMessageChangeLogsHandler): Promise; + /** + * @deprecated since version v3.0.123, please use {@link getMessageChangeLogsSinceToken()} instead + */ + getMessageChangeLogsByToken(token: string, includeMetaArray: boolean, callback?: getMessageChangeLogsHandler): Promise; + /** + * @deprecated since version v3.0.123, please use {@link getMessageChangeLogsSinceToken()} instead + */ + getMessageChangeLogsByToken( + token: string, + includeMetaArray: boolean, + includeReactions: boolean, + callback?: getMessageChangeLogsHandler + ): Promise; + + /** + * @deprecated since version v3.0.123, please use {@link getMessageChangeLogsSinceTimestamp()} instead + */ + getMessageChangeLogsByTimestamp(ts: number, callback?: getMessageChangeLogsHandler): Promise; + /** + * @deprecated since version v3.0.123, please use {@link getMessageChangeLogsSinceTimestamp()} instead + */ + getMessageChangeLogsByTimestamp(ts: number, includeMetaArray: boolean, callback?: getMessageChangeLogsHandler): Promise; + /** + * @deprecated since version v3.0.123, please use {@link getMessageChangeLogsSinceTimestamp()} instead + */ + getMessageChangeLogsByTimestamp( + ts: number, + includeMetaArray: boolean, + includeReactions: boolean, + callback?: getMessageChangeLogsHandler + ): Promise; + + getMessageChangeLogsSinceToken( + token: string, + params: MessageChangeLogsParams, + callback?: getMessageChangeLogsHandler + ): Promise; + getMessageChangeLogsSinceTimestamp( + timestamp: number, + params: MessageChangeLogsParams, + callback?: getMessageChangeLogsHandler + ): Promise; + + getMyMutedInfo(callback?: getMyMutedInfoHandler): void; + createOperatorListQuery(): OperatorListQuery; + + /** Message */ + /** + * @deprecated since version v3.0.36, please use {@link createPreviousMessageListQuery()} instead + */ + createMessageListQuery(): MessageListQuery; + createPreviousMessageListQuery(): PreviousMessageListQuery; + + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByTimestamp()} instead + */ + getNextMessagesByTimestamp( + ts: number, + isInclusive: boolean, + nextResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByTimestamp()} instead + */ + getNextMessagesByTimestamp( + ts: number, + isInclusive: boolean, + nextResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByTimestamp()} instead + */ + getNextMessagesByTimestamp( + ts: number, + isInclusive: boolean, + nextResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + includeMetaArray: boolean, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByTimestamp()} instead + */ + getNextMessagesByTimestamp( + ts: number, + isInclusive: boolean, + nextResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + includeMetaArray: boolean, + includeReactions: boolean, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByTimestamp()} instead + */ + getPreviousMessagesByTimestamp( + ts: number, + isInclusive: boolean, + prevResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByTimestamp()} instead + */ + getPreviousMessagesByTimestamp( + ts: number, + isInclusive: boolean, + prevResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByTimestamp()} instead + */ + getPreviousMessagesByTimestamp( + ts: number, + isInclusive: boolean, + prevResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + includeMetaArray: boolean, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByTimestamp()} instead + */ + getPreviousMessagesByTimestamp( + ts: number, + isInclusive: boolean, + prevResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + includeMetaArray: boolean, + includeReactions: boolean, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByTimestamp()} instead + */ + getPreviousAndNextMessagesByTimestamp( + ts: number, + prevResultSize: number, + nextResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByTimestamp()} instead + */ + getPreviousAndNextMessagesByTimestamp( + ts: number, + prevResultSize: number, + nextResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByTimestamp()} instead + */ + getPreviousAndNextMessagesByTimestamp( + ts: number, + prevResultSize: number, + nextResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + includeMetaArray: boolean, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByTimestamp()} instead + */ + getPreviousAndNextMessagesByTimestamp( + ts: number, + prevResultSize: number, + nextResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + includeMetaArray: boolean, + includeReactions: boolean, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByMessageId()} instead + */ + getNextMessagesByID( + messageId: number, + isInclusive: boolean, + nextResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByMessageId()} instead + */ + getNextMessagesByID( + messageId: number, + isInclusive: boolean, + nextResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByMessageId()} instead + */ + getNextMessagesByID( + messageId: number, + isInclusive: boolean, + nextResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + includeMetaArray: boolean, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByMessageId()} instead + */ + getNextMessagesByID( + messageId: number, + isInclusive: boolean, + nextResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + includeMetaArray: boolean, + includeReactions: boolean, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByMessageId()} instead + */ + getPreviousMessagesByID( + messageId: number, + isInclusive: boolean, + prevResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByMessageId()} instead + */ + getPreviousMessagesByID( + messageId: number, + isInclusive: boolean, + prevResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByMessageId()} instead + */ + getPreviousMessagesByID( + messageId: number, + isInclusive: boolean, + prevResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + includeMetaArray: boolean, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByMessageId()} instead + */ + getPreviousMessagesByID( + messageId: number, + isInclusive: boolean, + prevResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + includeMetaArray: boolean, + includeReactions: boolean, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByMessageId()} instead + */ + getPreviousAndNextMessagesByID( + messageId: number, + prevResultSize: number, + nextResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByMessageId()} instead + */ + getPreviousAndNextMessagesByID( + messageId: number, + prevResultSize: number, + nextResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByMessageId()} instead + */ + getPreviousAndNextMessagesByID( + messageId: number, + prevResultSize: number, + nextResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + includeMetaArray: boolean, + callback?: messageListCallback + ): Promise>; + /** + * @deprecated since version v3.0.123, please use {@link getMessagesByMessageId()} instead + */ + getPreviousAndNextMessagesByID( + messageId: number, + prevResultSize: number, + nextResultSize: number, + shouldReverse: boolean, + messageType: string, + customType: string, + senderUserIds: Array, + includeMetaArray: boolean, + includeReactions: boolean, + callback?: messageListCallback + ): Promise>; + + getMessagesByTimestamp(timestamp: number, params: MessageListParams, callback?: messageListCallback): Promise>; + getMessagesByMessageId(messageId: number, params: MessageListParams, callback?: messageListCallback): Promise>; + + /** FileMessage */ + sendFileMessage(fileMessageParams: FileMessageParams, callback: messageCallback): FileMessage; + sendFileMessage(file: FileType, callback: messageCallback): FileMessage; + /** + * @deprecated + */ + sendFileMessage(file: FileType, data: string, callback: messageCallback): FileMessage; + /** + * @deprecated + */ + sendFileMessage(file: FileType, data: string, customType: string, callback: messageCallback): FileMessage; + /** + * @deprecated + */ + sendFileMessage( + file: FileType, + data: string, + customType: string, + thumbnailSizes: Array, + callback: messageCallback + ): FileMessage; + /** + * @deprecated + */ + sendFileMessage( + file: FileType, + name: string, + type: string, + size: number, + data: string, + callback: messageCallback + ): FileMessage; + /** + * @deprecated + */ + sendFileMessage( + file: FileType, + name: string, + type: string, + size: number, + data: string, + customType: string, + callback: messageCallback + ): FileMessage; + sendFileMessage( + file: FileType, + name: string, + type: string, + size: number, + data: string, + customType: string, + thumbnailSizes: Array, + callback: messageCallback + ): FileMessage; + + sendFileMessage( + fileMessageParams: FileMessageParams, + progressHandler: fileUploadprogressHandler, + callback: messageCallback + ): FileMessage; + sendFileMessage(file: FileType, progressHandler: fileUploadprogressHandler, callback: messageCallback): FileMessage; + /** + * @deprecated + */ + sendFileMessage( + file: FileType, + data: string, + progressHandler: fileUploadprogressHandler, + callback: messageCallback + ): FileMessage; + /** + * @deprecated + */ + sendFileMessage( + file: FileType, + data: string, + customType: string, + progressHandler: fileUploadprogressHandler, + callback: messageCallback + ): FileMessage; + /** + * @deprecated + */ + sendFileMessage( + file: FileType, + data: string, + customType: string, + thumbnailSizes: Array, + progressHandler: fileUploadprogressHandler, + callback: messageCallback + ): FileMessage; + /** + * @deprecated + */ + sendFileMessage( + file: FileType, + name: string, + type: string, + size: number, + data: string, + progressHandler: fileUploadprogressHandler, + callback: messageCallback + ): FileMessage; + /** + * @deprecated + */ + sendFileMessage( + file: FileType, + name: string, + type: string, + size: number, + data: string, + customType: string, + progressHandler: fileUploadprogressHandler, + callback: messageCallback + ): FileMessage; + sendFileMessage( + file: FileType, + name: string, + type: string, + size: number, + data: string, + customType: string, + thumbnailSizes: Array, + progressHandler: fileUploadprogressHandler, + callback: messageCallback + ): FileMessage; + + sendFileMessage(file: string, callback: messageCallback): FileMessage; + /** + * @deprecated + */ + sendFileMessage(file: string, data: string, callback: messageCallback): FileMessage; + /** + * @deprecated + */ + sendFileMessage(file: string, data: string, customType: string, callback: messageCallback): FileMessage; + /** + * @deprecated + */ + sendFileMessage( + file: string, + name: string, + type: string, + size: number, + data: string, + callback: messageCallback + ): FileMessage; + sendFileMessage( + file: string, + name: string, + type: string, + size: number, + data: string, + customType: string, + callback: messageCallback + ): FileMessage; + + /** + * @deprecated + */ + sendFileMessage(file: string, progressHandler: fileUploadprogressHandler, callback: messageCallback): FileMessage; + /** + * @deprecated + */ + sendFileMessage( + file: string, + data: string, + progressHandler: fileUploadprogressHandler, + callback: messageCallback + ): FileMessage; + /** + * @deprecated + */ + sendFileMessage( + file: string, + data: string, + customType: string, + progressHandler: fileUploadprogressHandler, + callback: messageCallback + ): FileMessage; + /** + * @deprecated + */ + sendFileMessage( + file: string, + name: string, + type: string, + size: number, + data: string, + progressHandler: fileUploadprogressHandler, + callback: messageCallback + ): FileMessage; + /** + * @deprecated + */ + sendFileMessage( + file: string, + name: string, + type: string, + size: number, + data: string, + customType: string, + progressHandler: fileUploadprogressHandler, + callback: messageCallback + ): FileMessage; + + sendFileMessages( + fileMessageParamsList: Array, + callbackObject: fileMessagesCallbackObject + ): Array; + + /** UserMessage */ + sendUserMessage(userMessageParams: UserMessageParams, callback: messageCallback): UserMessage; + sendUserMessage(message: string, callback: messageCallback): UserMessage; + /** + * @deprecated + */ + sendUserMessage(message: string, data: string, callback: messageCallback): UserMessage; + /** + * @deprecated + */ + sendUserMessage(message: string, data: string, customType: string, callback: messageCallback): UserMessage; + sendUserMessage( + message: string, + data: string, + customType: string, + translationTargetLanguages: Array, + callback: messageCallback + ): UserMessage; + + resendUserMessage(userMessage: UserMessage, callback?: messageCallback): Promise; + resendFileMessage(fileMessage: FileMessage, callback?: messageCallback): Promise; + resendFileMessage(fileMessage: FileMessage, file: FileType, callback?: messageCallback): Promise; + + translateUserMessage( + message: UserMessage, + translationTargetLanguages: Array, + callback?: messageCallback + ): Promise; + + /** Edit Message */ + updateFileMessage(messageId: number, data: string, customType: string, callback?: messageCallback): Promise; + updateFileMessage(messageId: number, fileMessageParams: FileMessageParams, callback?: messageCallback): Promise; + updateUserMessage( + messageId: number, + message: string, + data: string, + customType: string, + callback?: messageCallback + ): Promise; + updateUserMessage(messageId: number, userMessageParams: UserMessageParams, callback?: messageCallback): Promise; + deleteMessage(message: FileMessage, callback?: commonCallback): Promise; + deleteMessage(message: UserMessage, callback?: commonCallback): Promise; + cancelUploadingFileMessage(messageReqId: string, callback: cancelUploadingFileMessageCallback): boolean; + + /** Copy Message */ + copyUserMessage(channel: BaseChannel, message: UserMessage, callback: messageCallback): UserMessage; + copyFileMessage(channel: BaseChannel, message: FileMessage, callback: messageCallback): FileMessage; + + /** Operators */ + addOperators(operatorUserIds: Array, callback?: commonCallback): Promise; + removeOperators(operatorUserIds: Array, callback?: commonCallback): Promise; + + /** Reaction */ + addReaction(message: UserMessage | FileMessage | AdminMessage, key: string, callback?: reactionEventCallback): Promise; + deleteReaction( + message: UserMessage | FileMessage | AdminMessage, + key: string, + callback?: reactionEventCallback + ): Promise; + + /** MetaData */ + createMetaData(metaDataMap: Object, callback?: commonCallback): Promise; + updateMetaData(metaDataMap: Object, upsert?: boolean, callback?: commonCallback): Promise; + getMetaData(keys: Array, callback?: commonCallback): Promise; + getAllMetaData(callback?: commonCallback): Promise; + deleteMetaData(key: string, callback?: commonCallback): Promise; + deleteAllMetaData(callback?: commonCallback): Promise; + getCachedMetaData(): object; + + /** MetaCounter */ + createMetaCounters(metaCounterMap: Object, callback?: commonCallback): Promise; + updateMetaCounters(metaCounterMap: Object, upsert?: boolean, callback?: commonCallback): Promise; + increaseMetaCounters(metaCounterMap: Object, callback?: commonCallback): Promise; + decreaseMetaCounters(metaCounterMap: Object, callback?: commonCallback): Promise; + getMetaCounters(keys: Array, callback?: commonCallback): Promise; + getAllMetaCounters(callback?: commonCallback): Promise; + deleteMetaCounter(key: string, callback?: commonCallback): Promise; + deleteAllMetaCounters(callback?: commonCallback): Promise; + + /** MessageMetaArray */ + createMessageMetaArrayKeys( + message: UserMessage | FileMessage | AdminMessage, + keys: Array, + callback?: commonCallback + ): Promise; + deleteMessageMetaArrayKeys( + message: UserMessage | FileMessage | AdminMessage, + keys: Array, + callback?: commonCallback + ): Promise; + addMessageMetaArrayValues( + message: UserMessage | FileMessage | AdminMessage, + data: Array, + callback?: commonCallback + ): Promise; + /** + * @deprecated since version v3.0.105 + */ + addMessageMetaArrayValues( + message: UserMessage | FileMessage | AdminMessage, + data: Object, + callback?: commonCallback + ): Promise; + removeMessageMetaArrayValues( + message: UserMessage | FileMessage | AdminMessage, + data: Array, + callback?: commonCallback + ): Promise; + /** + * @deprecated since version v3.0.105 + */ + removeMessageMetaArrayValues( + message: UserMessage | FileMessage | AdminMessage, + data: Object, + callback?: commonCallback + ): Promise; + + /** Report */ + report(category: string, description: string, callback?: commonCallback): Promise; + reportUser(user: User, category: string, description: string, callback?: commonCallback): Promise; + reportMessage( + message: UserMessage | FileMessage | AdminMessage, + category: string, + description: string, + callback?: commonCallback + ): Promise; + } + + type messageListCallback = ( + messageList: Array, + error: SendBirdError + ) => void; + + /** + * @deprecated since version v3.0.36, please use {@link PreviousMessageListQuery} instead + */ + interface MessageListQuery { + next(messageTimestamp: number, limit: number, reverse: boolean, callback?: messageListCallback): void; + prev(messageTimestamp: number, limit: number, reverse: boolean, callback?: messageListCallback): void; + load( + messageTimestamp: number, + prevLimit: number, + nextLimit: number, + reverse: boolean, + callback?: messageListCallback + ): void; + } + + type ThreadedMessageListInfo = { + parentMessage: UserMessage | FileMessage | AdminMessage; + threadedReplies: Array; + }; + /** + * @deprecated since version v3.0.27, please use {@link SendBirdInstance.setErrorFirstCallback} + */ + type threadedMessageErrorLastCallback = (threadedMessageListInfo: ThreadedMessageListInfo, error: SendBirdError) => void; + type threadedMessageErrorFirstCallback = (error: SendBirdError, threadedMessageListInfo: ThreadedMessageListInfo) => void; + type threadedMessageCallback = threadedMessageErrorFirstCallback | threadedMessageErrorLastCallback; + + interface PreviousMessageListQuery { + hasMore: boolean; + isLoading: boolean; + limit: number; + reverse: boolean; + messageTypeFilter: 0 | 1 | 2 | 3 | '' | 'MESG' | 'FILE' | 'ADMM'; + /** + * @deprecated since version v3.0.142, please use {@link customTypesFilter} instead + */ + customTypeFilter: string; + customTypesFilter: Array; + senderUserIdsFilter: Array; + includeMetaArray: boolean; + /** + * @deprecated since version v3.0.129, please use {@link includeReactions} instead + */ + includeReaction: boolean; + includeReactions: boolean; + /** + * @deprecated since version v3.0.159, please use {@link replyType} instead + */ + includeReplies: boolean; + /** + * @deprecated since version v3.0.159, please use {@link includeParentMessageInfo} instead + */ + includeParentMessageText: boolean; + includeThreadInfo: boolean; + showSubchannelMessagesOnly: boolean; + replyType: ReplyType[keyof ReplyType]; + includeParentMessageInfo: boolean; + + load(limit: number, reverse: boolean, messageType?: number | string, callback?: messageListCallback): Promise>; + load(callback?: messageListCallback): Promise>; + } + + /** + * OpenChannel + */ + type commonCallback = (response: Object, error: SendBirdError) => void; + type openChannelCallback = (openChannel: OpenChannel, error: SendBirdError) => void; + + interface OpenChannelParams { + new(): OpenChannelParams; + channelUrl: string; + name: string; + coverUrlOrImage: string | FileType; + data: string; + customType: string; + operatorUserIds: Array; + } + + interface OpenChannel extends BaseChannel { + participantCount: number; + operators: Array; + + refresh(callback?: openChannelCallback): Promise; + delete(callback?: commonCallback): Promise; + enter(callback?: openChannelCallback): Promise; + exit(callback?: openChannelCallback): Promise; + + createParticipantListQuery(): ParticipantListQuery; + createMutedUserListQuery(): MutedUserListQuery; + createBannedUserListQuery(): BannedUserListQuery; + + updateChannel(params: OpenChannelParams, callback?: openChannelCallback): Promise; + updateChannel(name: string, coverUrlOrImageFile: string | FileType, data: string, callback?: openChannelCallback): Promise; + /** + * @deprecated + */ + updateChannel( + name: string, + coverUrlOrImageFile: string | FileType, + data: string, + operatorUserIds: Array | string, + callback?: openChannelCallback + ): Promise; + updateChannel( + name: string, + coverUrlOrImageFile: string | FileType, + data: string, + operatorUserIds: Array | string, + customType: string, + callback?: openChannelCallback + ): Promise; + + updateChannelWithOperatorUserIds( + name: string, + coverUrlOrImageFile: string | FileType, + data: string, + operatorUserIds: Array | string, + callback?: openChannelCallback + ): Promise; + updateChannelWithOperatorUserIds( + name: string, + coverUrlOrImageFile: string | FileType, + data: string, + operatorUserIds: Array | string, + customType: string, + callback?: openChannelCallback + ): Promise; + + banUser(user: User, seconds?: number, callback?: commonCallback): Promise; + banUserWithUserId(userId: string, seconds?: number, callback?: commonCallback): Promise; + unbanUser(user: User, callback?: commonCallback): Promise; + unbanUserWithUserId(userId: string, callback?: commonCallback): Promise; + + muteUser(user: User, callback?: commonCallback): Promise; + muteUser(user: User, seconds: number, description: string, callback?: commonCallback): Promise; + muteUserWithUserId(userId: string, callback?: commonCallback): Promise; + muteUserWithUserId(userId: string, seconds: number, description: string, callback?: commonCallback): Promise; + unmuteUser(user: User, callback?: commonCallback): Promise; + unmuteUserWithUserId(userId: string, callback?: commonCallback): Promise; + + isOperator(user: User): boolean; + isOperatorWithUserId(userId: string): boolean; + } + + type userListQueryCallback = (userList: Array, error: SendBirdError) => void; + /** + * @deprecated since version v3.0.86, please use {@link ApplicationUserListQuery} instead + */ + interface UserListQuery { + limit: number; + hasNext: boolean; + isLoading: boolean; + metaDataKey: string; + metaDataValues: Array; + + next(callback?: userListQueryCallback): Promise>; + } + + interface ApplicationUserListQuery { + limit: number; + hasNext: boolean; + isLoading: boolean; + userIdsFilter: Array; + metaDataKeyFilter: string; + metaDataValuesFilter: Array; + nicknameStartsWithFilter: string; + + next(callback?: userListQueryCallback): Promise>; + } + + interface BlockedUserListQuery { + limit: number; + hasNext: boolean; + isLoading: boolean; + userIdsFilter: Array; + + next(callback?: userListQueryCallback): Promise>; + } + + interface ParticipantListQuery { + limit: number; + hasNext: boolean; + isLoading: boolean; + + next(callback?: userListQueryCallback): Promise>; + } + + interface MutedUserListQuery { + limit: number; + hasNext: boolean; + isLoading: boolean; + + next(callback?: userListQueryCallback): Promise>; + } + + interface BannedUserListQuery { + limit: number; + hasNext: boolean; + isLoading: boolean; + + next(callback?: userListQueryCallback): Promise>; + } + + interface OperatorListQuery { + limit: number; + hasNext: boolean; + isLoading: boolean; + next(callback?: userListQueryCallback): Promise>; + } + + interface OpenChannelStatic { + buildFromSerializedData(serializedObject: Object): OpenChannel; + + getChannel(channelUrl: string, callback?: openChannelCallback): Promise; + getChannelWithoutCache(channelUrl: string, callback?: openChannelCallback): Promise; + + createChannel(callback?: openChannelCallback): Promise; + createChannel(params: OpenChannelParams, callback?: openChannelCallback): Promise; + + /** + * @deprecated + */ + createChannel(name: string, coverUrlOrImageFile: string | FileType, data: string, callback?: openChannelCallback): Promise; + + /** + * @deprecated + */ + createChannel( + name: string, + coverUrlOrImageFile: string | FileType, + data: string, + operatorUserIds: Array | string, + callback?: openChannelCallback + ): Promise; + createChannel( + name: string, + coverUrlOrImageFile: string | FileType, + data: string, + operatorUserIds: Array | string, + customType: string, + callback?: openChannelCallback + ): Promise; + + createChannelWithOperatorUserIds( + name: string, + coverUrlOrImageFile: string | FileType, + data: string, + operatorUserIds: Array | string, + callback?: openChannelCallback + ): Promise; + createChannelWithOperatorUserIds( + name: string, + coverUrlOrImageFile: string | FileType, + data: string, + operatorUserIds: Array | string, + customType: string, + callback?: openChannelCallback + ): Promise; + + createOpenChannelListQuery(): OpenChannelListQuery; + } + + type openChannelListQueryCallback = (openChannelList: Array, error: SendBirdError) => void; + interface OpenChannelListQuery { + limit: number; + hasNext: boolean; + nameKeyword: string; + urlKeyword: string; + customTypes: Array; + includeFrozen: boolean; + + next(callback?: openChannelListQueryCallback): Promise>; + } + + /** + * ScheduledUserMessage + */ + interface ScheduledUserMessage { + scheduledId: number; + scheduledDateTimeString: string; + scheduledTimezone: string; + status: 'scheduled' | 'sent' | 'canceled' | 'failed'; + createdAt: number; + updatedAt: number; + channelUrl: string; + sender: User; + message: string; + customType: string; + data: string; + /** + * @deprecated + */ + metaArray: Object; + metaArrays: Array; + mentionType: 'users' | 'channel'; + mentionedUsers: Array; + pushNotificationDeliveryOption: 'default' | 'suppress'; + translationTargetLanguages: Array; + errorMessage: string; + errorCode: number; + appleCriticalAlertOptions: AppleCriticalAlertOptions; + + isGroupChannel(): boolean; + isOpenChannel(): boolean; + } + + type scheduledUserMessageCallback = (scheduledUserMessage: ScheduledUserMessage, error: SendBirdError) => void; + + /** + * GroupChannel + */ + interface GroupChannelParams { + new(): GroupChannelParams; + isDistinct: boolean; + isSuper: boolean; + isBroadcast: boolean; + isPublic: boolean; + isDiscoverable: boolean; + isStrict: boolean; + isEphemeral: boolean; + channelUrl: string; + name: string; + data: string; + customType: string; + coverUrl: string; + coverImage: FileType; + operators: Array; + operatorUserIds: Array; + accessCode: string; + messageSurvivalSeconds: number; + + addUser(user: User): void; + addUsers(user: Array): void; + addUserId(userId: string): void; + addUserIds(userId: Array): void; + } + + interface ScheduledUserMessageParams { + new(): ScheduledUserMessageParams; + message: string; + data: string; + customType: string; + translationTargetLanguages: Array; + metaArrayKeys: Array; + mentionType: 'users' | 'channel'; + mentionedUserIds: Array; + mentionedUsers: Array; + pushNotificationDeliveryOption: 'default' | 'suppress'; + year: number; + month: number; + day: number; + hour: number; + min: number; + timezone: string; + scheduledDateTimeString: string; + appleCriticalAlertOptions: AppleCriticalAlertOptions; + + setSchedule(year: number, month: number, day: number, hour: number, min: number, timezone: string): void; + } + + interface GroupChannelChangeLogsParams { + new(): GroupChannelChangeLogsParams; + customTypes: Array; + includeEmpty: boolean; + includeFrozen: boolean; + } + + interface DistinctGroupChannelResponse { + channel: GroupChannel; + isCreated: boolean; + } + + interface MessageMetaArray { + new(key: string, value: Array): MessageMetaArray; + key: string; + value: Array; + } + interface Reaction { + key: string; + userIds: Array; + updatedAt: number; + } + interface ReactionEvent { + messageId: number; + userId: string; + key: string; + operation: 'add' | 'delete'; + updatedAt: number; + } + + interface ThreadInfo { + replyCount: number; + mostRepliedUsers: Array; + lastRepliedAt: number; + updatedAt: number; + } + interface ThreadInfoUpdateEvent { + threadInfo: ThreadInfo; + targetMessageId: number; + channelUrl: string; + channelType: string; + } + + interface OGMetaData { + title: string; + url: string; + description: string; + defaultImage: OGImage; + } + interface OGImage { + url: string; + secureUrl: string; + type: string; + width: number; + height: number; + alt: string; + } + + interface Plugin { + type: string; + vendor: string; + detail: {}; + } + + interface AppleCriticalAlertOptions { + name: string; + volume: number; + + serialize(): Object; + } + + type groupChannelCallback = (groupChannel: GroupChannel, error: SendBirdError) => void; + type distinctGroupChannelCallback = (response: DistinctGroupChannelResponse, error: SendBirdError) => void; + type getPushPreferenceCallback = (isPushOn: boolean, error: SendBirdError) => void; + type getPushTriggerOptionCallback = ( + pushTriggerOption: 'all' | 'mention_only' | 'off' | 'default', + error: SendBirdError + ) => void; + interface GroupChannel extends BaseChannel { + isHidden: boolean; + isDistinct: boolean; + isSuper: boolean; + isBroadcast: boolean; + isPublic: boolean; + /** + * @deprecated since version v3.0.93, please use {@link myPushTriggerOption} instead + */ + isPushEnabled: boolean; + myPushTriggerOption: 'default' | 'all' | 'mention_only' | 'off'; + myCountPreference: string; + lastMessage: UserMessage | FileMessage | AdminMessage | null; + unreadMessageCount: number; + unreadMentionCount: number; + members: Array; + memberCount: number; + joinedMemberCount: number; + myMemberState: 'none' | 'joined' | 'invited'; + myRole: 'operator' | 'none'; + myMutedState: 'muted' | 'unmuted'; + inviter: User | null; + invitedAt: number; + joinedAt: number; + isAccessCodeRequired: boolean; + hiddenState: 'unhidden' | 'hidden_allow_auto_unhide' | 'hidden_prevent_auto_unhide'; + isDiscoverable: boolean; + myLastRead: number; + messageOffsetTimestamp: number; + messageSurvivalSeconds: number; + + isEqual(target: GroupChannel): boolean; + isIdentical(target: GroupChannel): boolean; + refresh(callback?: groupChannelCallback): Promise; + delete(callback?: commonCallback): Promise; + + updateChannel(groupChannelParams: GroupChannelParams, callback?: groupChannelCallback): Promise; + updateChannel(name: string, coverUrlOrImageFile: string | FileType, data: string, callback?: groupChannelCallback): Promise; + /** + * @deprecated + */ + updateChannel( + isDistinct: boolean, + name: string, + coverUrlOrImageFile: string | FileType, + data: string, + callback?: groupChannelCallback + ): Promise; + updateChannel( + isDistinct: boolean, + name: string, + coverUrlOrImageFile: string | FileType, + data: string, + customType: string, + callback?: groupChannelCallback + ): Promise; + + resetMyHistory(callback?: commonCallback): Promise; + + invite(users: Array, callback?: groupChannelCallback): Promise; + inviteWithUserIds(userIds: Array, callback?: groupChannelCallback): Promise; + acceptInvitation(accessCode?: string, callback?: groupChannelCallback): Promise; + declineInvitation(callback?: commonCallback): Promise; + + join(accessCode?: string, callback?: groupChannelCallback): Promise; + leave(callback?: commonCallback): Promise; + + hide(hidePreviousMessages?: boolean, callback?: commonCallback): Promise; + hide(hidePreviousMessages: boolean, allowAutoUnhide: boolean, callback?: commonCallback): Promise; + unhide(callback?: commonCallback): Promise; + + markAsRead(callback?: voidCallback): Promise; + /** + * @deprecated since version v3.0.156 + */ + markAsRead(): void; + /** + * @deprecated since version v3.0.127, please use {@link getUnreadMemberCount()} instead + */ + getReadReceipt(message: UserMessage | FileMessage | AdminMessage): number; + getReadStatus(includeAllMembers?: boolean): Object; + getUnreadMembers(message: UserMessage | FileMessage, includeAllMembers?: boolean): Array; + getReadMembers(message: UserMessage | FileMessage, includeAllMembers?: boolean): Array; + getUnreadMemberCount(message: UserMessage | FileMessage | AdminMessage): number; + + /** + * @deprecated since version v3.0.143, please use {@link SendBirdInstance.markAsDelivered()} instead + */ + markAsDelivered(): void; + /** + * @deprecated since version v3.0.127, please use {@link getUndeliveredMemberCount()} instead + */ + getDeliveryReceipt(message: UserMessage | FileMessage | AdminMessage): number; + getUndeliveredMemberCount(message: UserMessage | FileMessage | AdminMessage): number; + + startTyping(): void; + endTyping(): void; + isTyping(): boolean; + getTypingMembers(): Array; // DEPRECATE + getTypingUsers(): Array; + + /** + * @deprecated since version v3.0.93, please use {@link getMyPushTriggerOption()} instead + */ + setPushPreference(pushOn: boolean, callback?: commonCallback): Promise; + /** + * @deprecated since version v3.0.93, please use {@link getMyPushTriggerOption()} instead + */ + getPushPreference(callback?: getPushPreferenceCallback): Promise; + setMyPushTriggerOption( + pushTriggerOption: 'all' | 'mention_only' | 'off' | 'default', + callback?: getPushTriggerOptionCallback + ): Promise; + getMyPushTriggerOption(callback?: getPushTriggerOptionCallback): Promise; + setMyCountPreference( + preference: 'all' | 'unread_message_count_only' | 'unread_mention_count_only' | 'off', + callback?: commonCallback + ): Promise; + + createMemberListQuery(): GroupChannelMemberListQuery; + createBannedUserListQuery(): BannedUserListQuery; + + banUser(user: User, seconds: number, description: string, callback?: commonCallback): Promise; + banUserWithUserId(userId: string, seconds: number, description: string, callback?: commonCallback): Promise; + unbanUser(User: User, callback?: commonCallback): Promise; + unbanUserWithUserId(userId: string, callback?: commonCallback): Promise; + + muteUser(user: User, callback?: commonCallback): Promise; + muteUser(user: User, seconds: number, description: string, callback?: commonCallback): Promise; + muteUserWithUserId(userId: string, callback?: commonCallback): Promise; + muteUserWithUserId(userId: string, seconds: number, description: string, callback?: commonCallback): Promise; + unmuteUser(user: User, callback?: commonCallback): Promise; + unmuteUserWithUserId(userId: string, callback?: commonCallback): Promise; + + freeze(callback?: commonCallback): Promise; + unfreeze(callback?: commonCallback): Promise; + + createMessageCollection(): MessageCollectionBuilder; + + registerScheduledUserMessage( + scheduledUserMessageParams: ScheduledUserMessageParams, + callback?: scheduledUserMessageCallback + ): Promise; + } + + type groupChannelCountCallback = (count: number, error: SendBirdError) => void; + + type SearchFilterParams = { + searchQuery: string, + searchFields: SearchField[] + }; + + type UserIdsFilterParams = { + userIds: string[], + includeMode: boolean, + queryType: QueryType + }; + + interface GroupChannelFilter { + includeEmpty: boolean; + nicknameContainsFilter: string; + nicknameStartsWithFilter: string; + nicknameExactMatchFilter: string; + channelNameContainsFilter: string; + memberStateFilter: MemberStateFilter; + customTypesFilter: string[]; + channelUrlsFilter: string[]; + superChannelFilter: SuperChannelFilter; + publicChannelFilter: PublicChannelFilter; + customTypeStartsWithFilter: string; + unreadChannelFilter: UnreadChannelFilter; + hiddenChannelFilter: HiddenChannelFilter; + includeFrozen: boolean; + includeMetaData: boolean; + + searchFilter: SearchFilterParams; + userIdsFilter: UserIdsFilterParams; + + setSearchFilter(fields: SearchField[], query: string): void; + setUserIdsFilter(userIds: string[], includeMode: boolean, queryType: QueryType): void; + + match(channel: GroupChannel): boolean; + } + + interface GroupChannelFilterStatic { + new(): GroupChannelFilter; + + QueryType: typeof QueryType; + SearchField: typeof SearchField; + MemberStateFilter: typeof MemberStateFilter; + SuperChannelFilter: typeof SuperChannelFilter; + PublicChannelFilter: typeof PublicChannelFilter; + UnreadChannelFilter: typeof UnreadChannelFilter; + HiddenChannelFilter: typeof HiddenChannelFilter; + } + + type MessageCollectionInitResultHandler = (err: Error, messages: BaseMessageInstance[]) => void; + + interface MessageCollectionInitHandler { + onCacheResult(handler: MessageCollectionInitResultHandler): MessageCollectionInitHandler; + onApiResult(handler: MessageCollectionInitResultHandler): MessageCollectionInitHandler; + } + + interface GroupChannelContext { + readonly source: CollectionEventSource; + readonly isFromEvent: boolean; + } + + interface GroupChannelCollectionHandler { + onChannelsAdded: (context: GroupChannelContext, channels: BaseChannel[]) => void; + onChannelsUpdated: (context: GroupChannelContext, channels: BaseChannel[]) => void; + onChannelsDeleted: (context: GroupChannelContext, channelUrls: string[]) => void; + } + + interface GroupChannelCollection { + readonly hasMore: boolean; + readonly channelList: GroupChannel[]; + + loadMore(): Promise; + dispose(): void; + setGroupChannelCollectionHandler(handler: GroupChannelCollectionHandler): void; + } + + interface GroupChannelCollectionStatic { + GroupChannelOrder: typeof GroupChannelOrder; + } + + interface GroupChannelCollectionBuilder { + setFilter(filter: GroupChannelFilter): GroupChannelCollectionBuilder; + setOrder(order: GroupChannelOrder): GroupChannelCollectionBuilder; + setLimit(limit: number): GroupChannelCollectionBuilder; + build(): GroupChannelCollection; + } + + interface MessageContext { + readonly source: CollectionEventSource; + readonly isFromEvent: boolean; + readonly sendingStatus: MessageSendingStatus[keyof MessageSendingStatus]; + } + + interface MessageCollectionHandler { + onMessagesAdded: (context: MessageContext, channel: BaseChannel, messages: BaseMessageInstance[]) => void; + onMessagesUpdated: (context: MessageContext, channel: BaseChannel, messages: BaseMessageInstance[]) => void; + onMessagesDeleted: (context: MessageContext, channel: BaseChannel, messages: BaseMessageInstance[]) => void; + onChannelUpdated: (context: GroupChannelContext, channel: BaseChannel) => void; + onChannelDeleted: (context: GroupChannelContext, channelUrl: string) => void; + onHugeGapDetected: () => void; + } + + interface MessageCollection { + readonly channel: BaseChannel; + readonly succeededMessages: BaseMessageInstance[]; + readonly pendingMessages: BaseMessageInstance[]; + readonly failedMessages: BaseMessageInstance[]; + readonly startingPoint: number; + readonly hasPrevious: boolean; + readonly hasNext: boolean; + + initialize(initPolicy: MessageCollectionInitPolicy): MessageCollectionInitHandler; + loadPrevious(): Promise; + loadNext(): Promise; + removeFailedMessages(messages: BaseMessageInstance[]): Promise; + removeAllFailedMessages(): Promise; + dispose(): void; + setMessageCollectionHandler(handler: MessageCollectionHandler): void; + } + + interface MessageCollectionStatic { + MessageCollectionInitPolicy: typeof MessageCollectionInitPolicy; + } + + interface MessageCollectionBuilder { + setFilter(filter: MessageFilter): MessageCollectionBuilder; + setStartingPoint(startingPoint: number): MessageCollectionBuilder; + setLimit(limit: number): MessageCollectionBuilder; + build(): MessageCollection; + } + + interface GroupChannelStatic { + buildFromSerializedData(serializedObject: Object): GroupChannel; + + createMyGroupChannelListQuery(): GroupChannelListQuery; + createPublicGroupChannelListQuery(): PublicGroupChannelListQuery; + + /** + * @deprecated since version v3.0.80, please use {@link SendBirdInstance.getUnreadItemCount()} instead + */ + getUnreadItemCount(keys: Array, callback?: commonCallback): Promise; + /** + * @deprecated since version v3.0.80, please use {@link SendBirdInstance.getTotalUnreadMessageCount()} instead + */ + getTotalUnreadMessageCount( + groupChannelTotalUnreadMessageCountParams?: GroupChannelTotalUnreadMessageCountParams, + callback?: groupChannelCountCallback + ): Promise; + /** + * @deprecated since version v3.0.80, please use {@link SendBirdInstance.getTotalUnreadMessageCount()} instead + */ + getTotalUnreadMessageCount(channelCustomTypes: Array, callback?: groupChannelCountCallback): Promise; + /** + * @deprecated since version v3.0.80, please use {@link SendBirdInstance.getTotalUnreadChannelCount()} instead + */ + getTotalUnreadChannelCount(callback?: groupChannelCountCallback): Promise; + + createChannel(groupChannelParams: GroupChannelParams, callback?: groupChannelCallback): Promise; + createChannel(users: Array, callback?: groupChannelCallback): Promise; + /** + * @deprecated + */ + createChannel(users: Array, isDistinct: boolean, callback?: groupChannelCallback): Promise; + /** + * @deprecated + */ + createChannel(users: Array, isDistinct: boolean, customType: string, callback?: groupChannelCallback): Promise; + /** + * @deprecated + */ + createChannel( + users: Array, + isDistinct: boolean, + name: string, + coverUrlOrImageFile: string | FileType, + data: string, + callback?: groupChannelCallback + ): Promise; + createChannel( + users: Array, + isDistinct: boolean, + name: string, + coverUrlOrImageFile: string | FileType, + data: string, + customType: string, + callback?: groupChannelCallback + ): Promise; + createDistinctChannelIfNotExist( + groupChannelParams: GroupChannelParams, + callback?: distinctGroupChannelCallback + ): Promise; + + createChannelWithUserIds(userIds: Array, callback?: groupChannelCallback): Promise; + /** + * @deprecated + */ + createChannelWithUserIds(userIds: Array, isDistinct: boolean, callback?: groupChannelCallback): Promise; + /** + * @deprecated + */ + createChannelWithUserIds( + userIds: Array, + isDistinct: boolean, + customType: string, + callback?: groupChannelCallback + ): Promise; + /** + * @deprecated + */ + createChannelWithUserIds( + userIds: Array, + isDistinct: boolean, + name: string, + coverUrlOrImageFile: string | FileType, + data: string, + callback?: groupChannelCallback + ): Promise; + createChannelWithUserIds( + userIds: Array, + isDistinct: boolean, + name: string, + coverUrlOrImageFile: string | FileType, + data: string, + customType: string, + callback?: groupChannelCallback + ): Promise; + + getChannel(channelUrl: string, callback?: groupChannelCallback): Promise; + getChannelWithoutCache(channelUrl: string, callback?: groupChannelCallback): Promise; + + /** + * @deprecated since version v3.0.50, please use {@link SendBirdInstance.markAsReadAll()} instead + */ + markAsReadAll(callback?: commonCallback): Promise; + + createGroupChannelCollection(): GroupChannelCollectionBuilder; + } + + type groupChannelMemberListQueryCallback = (groupChannelList: Array, error: SendBirdError) => void; + interface GroupChannelMemberListQuery { + limit: number; + hasNext: boolean; + isLoading: boolean; + order: 'member_nickname_alphabetical' | 'operator_then_member_alphabetical'; + mutedMemberFilter: 'all' | 'muted' | 'unmuted'; + /** + * @deprecated + */ + operatorFilter: 'all' | 'operator' | 'nonoperator'; + memberStateFilter: 'all' | 'joined_only' | 'invited_only' | 'invited_by_friend' | 'invited_by_non_friend'; + nicknameStartsWithFilter: string; + + next(callback?: groupChannelMemberListQueryCallback): Promise>; + } + + type groupChannelListQueryCallback = (groupChannelList: Array, error: SendBirdError) => void; + interface GroupChannelListQueryStatic { + buildFromSerializedData(serializedObject: object): GroupChannelListQuery; + } + interface GroupChannelListQuery { + limit: number; + hasNext: boolean; + isLoading: boolean; + includeEmpty: boolean; + order: 'latest_last_message' | 'chronological' | 'channel_name_alphabetical' | 'metadata_value_alphabetical'; + /** + * @deprecated + */ + userIdsFilter: Array; + /** + * @deprecated + */ + userIdsFilterExactMatch: boolean; + /** + * @deprecated + */ + queryType: 'AND' | 'OR'; + userIdsExactFilter: Array; + userIdsIncludeFilter: Array; + userIdsIncludeFilterQueryType: 'AND' | 'OR'; + nicknameContainsFilter: string; + nicknameStartWithFilter: string; + nicknameExactMatchFilter: string; + channelNameContainsFilter: string; + /** + * @deprecated since version v3.0.49, please use {@link customTypesFilter} instead + */ + customTypeFilter: string; + customTypesFilter: Array; + customTypeStartsWithFilter: string; + channelUrlsFilter: Array; + superChannelFilter: 'all' | 'super' | 'nonsuper' | 'broadcast_only'; + publicChannelFilter: 'all' | 'public' | 'private'; + metadataOrderKeyFilter: string; + metadataKey: string; + metadataValues: Array; + metadataValueStartsWith: string; + memberStateFilter: 'all' | 'joined_only' | 'invited_only' | 'invited_by_friend' | 'invited_by_non_friend'; + hiddenChannelFilter: 'all' | 'unhidden_only' | 'hidden_only' | 'hidden_allow_auto_unhide' | 'hidden_prevent_auto_unhide'; + unreadChannelFilter: 'all' | 'unread_message'; + includeFrozen: boolean; + + setSearchFilter(fields: Array, queryString: string): void; + serialize(): object; + next(callback?: groupChannelListQueryCallback): Promise>; + } + + interface PublicGroupChannelListQuery { + limit: number; + hasNext: boolean; + isLoading: boolean; + includeEmpty: boolean; + order: 'chronological' | 'channel_name_alphabetical' | 'metadata_value_alphabetical'; + channelNameContainsFilter: string; + channelUrlsFilter: Array; + customTypesFilter: Array; + customTypeStartsWithFilter: string; + superChannelFilter: 'all' | 'super' | 'nonsuper' | 'broadcast_only'; + membershipFilter: 'all' | 'joined'; + metadataOrderKeyFilter: string; + metadataKey: string; + metadataValues: Array; + metadataValueStartsWith: string; + includeFrozen: boolean; + + next(callback?: groupChannelListQueryCallback): Promise>; + } } - -declare var SendBird: SendBirdFactory; diff --git a/SendBird.min.js b/SendBird.min.js index 4bcb7ff..766ad73 100644 --- a/SendBird.min.js +++ b/SendBird.min.js @@ -1,8 +1,6 @@ /** - * Copyright (c) 2016 SendBird DBA (Smile Family, Inc.) - * SendBird JavaScript SDK v3.0.23 + * Copyright (c) 2016 Sendbird DBA (Smile Family, Inc.) + * Sendbird JavaScript SDK v3.1.33 */ -!function(root,factory){"object"==typeof exports&&"object"==typeof module?module.exports=factory():"function"==typeof define&&define.amd?define([],factory()):"object"==typeof exports?exports.SendBird=factory():(root.SendBird=factory(),root.SendBird2=factory())}(this,function(){var DEBUG=!1,DEBUG_HOST=!1,WS_HOST="wss://ws.sendbird.com",API_HOST="https://api.sendbird.com",DEBUG_WS_HOST="ws://localtest.me:9000",DEBUG_API_HOST="http://localtest.me:8000/api";DEBUG_HOST&&(WS_HOST=DEBUG_WS_HOST,API_HOST=DEBUG_API_HOST);try{var console=window.console||{log:function(){}}}catch(e){var console={log:function(){}}}var OS_VERSION="undefined";try{OS_VERSION=navigator.userAgent.replace(/,/g,".")}catch(e){OS_VERSION="undefined"}var _Xhr,SDK_VERSION="3.0.23",API_HEADER_PARAM="JS,"+OS_VERSION+","+SDK_VERSION+",",MIME_JSON="application/json; charset=utf-8";try{_Xhr="undefined"==typeof window?require("xhr2"):null}catch(err){_Xhr=null}if(_Xhr){var Agent=require("agentkeepalive"),HttpsAgent=require("agentkeepalive").HttpsAgent;try{var options={},nodejsHttpAgent=new Agent({keepAlive:!0,timeout:6e4,keepAliveTimeout:6e4});options.httpAgent=nodejsHttpAgent;var nodejsHttpsAgent=new HttpsAgent({keepAlive:!0,timeout:6e4,keepAliveTimeout:6e4});options.httpsAgent=nodejsHttpsAgent,_Xhr.nodejsSet(options)}catch(e){}}var _cb_wrapper=function(error,result,cb){cb&&"function"==typeof cb&&cb(result,error)},_ajaxCall=function(url,data,method,header,cb){function _isIE(){try{if("undefined"==typeof navigator||"undefined"==typeof navigator.userAgent)return!1;var myNav=navigator.userAgent.toLowerCase();return myNav.indexOf("msie")!=-1&&parseInt(myNav.split("msie")[1])}catch(err){return!1}}var _AJAX_SUCCESS_CODE=200,_AJAX_ERROR_CODE=400,request=_Xhr?new _Xhr:new XMLHttpRequest,_IE_version=_isIE();if(!("withCredentials"in request)&&_IE_version&&_IE_version<10){request=new XDomainRequest,request.withCredentials=!0,request.open(method,url);for(var i in header)data[i]=header[i];request.onload=function(){request.status>=_AJAX_SUCCESS_CODE&&request.status<_AJAX_ERROR_CODE?_cb_wrapper(null,JSON.parse(request.responseText),cb):_cb_wrapper({status:request.status,statusText:request.statusText,response:request.responseText},null,cb)},request.onerror=function(){_cb_wrapper({status:404,statusText:"There was a connection error"},null,cb)}}else{try{request=_Xhr?new _Xhr:new XMLHttpRequest,request.open(method,url),request.onload=function(){request.status>=_AJAX_SUCCESS_CODE&&request.status<_AJAX_ERROR_CODE?_cb_wrapper(null,JSON.parse(request.responseText),cb):_cb_wrapper({status:request.status,statusText:request.statusText,response:request.responseText},null,cb)},request.onerror=function(){_cb_wrapper({status:404,statusText:"There was a connection error"},null,cb)}}catch(err){request=new ActiveXObject("Microsoft.XMLHTTP"),request.open(method,url),request.onreadystatechange=function(){4==request.readyState&&(request.status>=_AJAX_SUCCESS_CODE&&request.status<_AJAX_ERROR_CODE?_cb_wrapper(null,JSON.parse(request.responseText),cb):_cb_wrapper({status:request.status,statusText:request.statusText,response:request.responseText},null,cb))}}try{for(var i in header)request.setRequestHeader(i,header[i]?header[i]:"sendbird")}catch(e){}}try{switch(method){case"get":case"GET":request.send();break;default:data instanceof FormData?request.send(data):(request.setRequestHeader("Content-Type",MIME_JSON),request.send(JSON.stringify(data)))}}catch(e){}},_inherit=function(){var F=function(){};return function(Parent,Child){F.prototype=new Parent,Child.prototype=new F,Child.super=Parent.prototype,Child.prototype.constructor=Child}}(),SendBirdObject=function(){var appId="",reconnectFactor=3e3,reconnectCount=0,reconnectDelay=0,BaseMessage=function(jsonObject){this.isOpenChannel=function(){return this.channelType==BaseChannel.CHANNEL_TYPE_OPEN},this.isGroupChannel=function(){return this.channelType==BaseChannel.CHANNEL_TYPE_GROUP},this.isUserMessage=function(){return this.messageType==BaseMessage.MESSAGE_TYPE_USER},this.isAdminMessage=function(){return this.messageType==BaseMessage.MESSAGE_TYPE_ADMIN},this.isFileMessage=function(){return this.messageType==BaseMessage.MESSAGE_TYPE_FILE},this._update=function(jsonObject){this.messageId=jsonObject.hasOwnProperty("msg_id")?parseInt(jsonObject.msg_id):0,this.channelUrl=jsonObject.hasOwnProperty("channel_url")?String(jsonObject.channel_url):"",this.createdAt=jsonObject.hasOwnProperty("ts")?parseInt(jsonObject.ts):0,this.channelType=jsonObject.hasOwnProperty("channel_type")?String(jsonObject.channel_type):BaseChannel.CHANNEL_TYPE_GROUP},this.messageType=BaseMessage.MESSAGE_TYPE_BASE,jsonObject&&this._update(jsonObject)};BaseMessage.build=function(jsonObject,channel){if(!jsonObject)return null;var user,msgId,message,data,createdAt,customType,translations;switch(jsonObject.type){case"MESG":return user=new User(jsonObject.user),msgId=parseInt(jsonObject.message_id),message=String(jsonObject.message),data=String(jsonObject.data),createdAt=parseInt(jsonObject.created_at),customType=jsonObject.hasOwnProperty("custom_type")?String(jsonObject.custom_type):"",translations=jsonObject.hasOwnProperty("translations")?jsonObject.translations:{},new UserMessage(UserMessage.build("",msgId,user,channel,message,data,customType,translations,createdAt));case"FILE":user=new User(jsonObject.user),msgId=parseInt(jsonObject.message_id),message=String(jsonObject.message),createdAt=parseInt(jsonObject.created_at),customType=jsonObject.hasOwnProperty("custom_type")?String(jsonObject.custom_type):"";var file=jsonObject.file,url=String(file.url),name=String(file.name),fileType=String(file.type),size=parseInt(file.size)||0;data=String(file.data),console.log(jsonObject);var thumbnails=jsonObject.hasOwnProperty("thumbnails")?jsonObject.thumbnails:[],requireAuth=!!jsonObject.hasOwnProperty("require_auth")&&jsonObject.require_auth;return new FileMessage(FileMessage.build("",msgId,user,channel,url,name,fileType,size,data,customType,createdAt,thumbnails,requireAuth));case"BRDM":case"ADMM":return msgId=parseInt(jsonObject.message_id),message=String(jsonObject.message),data=String(jsonObject.data),createdAt=parseInt(jsonObject.created_at),customType=jsonObject.hasOwnProperty("custom_type")?String(jsonObject.custom_type):"",translations=jsonObject.hasOwnProperty("translations")?jsonObject.translations:{},new AdminMessage(AdminMessage.build(msgId,channel,message,data,customType,translations,createdAt))}return null},BaseMessage.MESSAGE_TYPE_BASE="base",BaseMessage.MESSAGE_TYPE_ADMIN="admin",BaseMessage.MESSAGE_TYPE_USER="user",BaseMessage.MESSAGE_TYPE_FILE="file";var AdminMessage=function(jsonObject){this.messageType=BaseMessage.MESSAGE_TYPE_ADMIN,jsonObject&&(this._update(jsonObject),this.message=String(jsonObject.message),this.data=jsonObject.hasOwnProperty("data")?String(jsonObject.data):"",this.customType=jsonObject.hasOwnProperty("custom_type")?String(jsonObject.custom_type):"",this.translations=jsonObject.hasOwnProperty("translations")?jsonObject.translations:{})};_inherit(BaseMessage,AdminMessage),AdminMessage.build=function(msgId,channel,message,data,customType,translations,createdAt){var obj={msg_id:msgId,channel_url:channel.url,channel_type:channel.isOpenChannel()?BaseChannel.CHANNEL_TYPE_OPEN:BaseChannel.CHANNEL_TYPE_GROUP,ts:createdAt,message:message,data:data};return customType&&(obj.custom_type=customType),translations&&(obj.translations=translations),obj};var UserMessage=function(jsonObject){this.messageType=BaseMessage.MESSAGE_TYPE_USER,jsonObject&&(this._update(jsonObject),this.message=String(jsonObject.message),this.data=jsonObject.hasOwnProperty("data")?String(jsonObject.data):"",this.sender=new User(jsonObject.user),this.reqId=jsonObject.hasOwnProperty("req_id")?String(jsonObject.req_id):"",this.customType=jsonObject.hasOwnProperty("custom_type")?String(jsonObject.custom_type):"",this.translations=jsonObject.hasOwnProperty("translations")?jsonObject.translations:{})};_inherit(BaseMessage,UserMessage),UserMessage.build=function(requestId,msgId,user,channel,message,data,customType,translations,createdAt){var obj={};obj.req_id=requestId,obj.msg_id=msgId,obj.channel_url=channel.url,obj.channel_type=channel.channelType==BaseChannel.CHANNEL_TYPE_OPEN?BaseChannel.CHANNEL_TYPE_OPEN:BaseChannel.CHANNEL_TYPE_GROUP,obj.ts=createdAt,obj.message=message,data&&(obj.data=data),customType&&(obj.custom_type=customType),translations&&(obj.translations=translations);var userObj={};return userObj.user_id=user.userId,userObj.nickname=user.nickname,userObj.profile_url=user.profileUrl,obj.user=userObj,obj};var FileMessage=function(jsonObject){if(this.messageType=BaseMessage.MESSAGE_TYPE_FILE,jsonObject&&(this._update(jsonObject),this.sender=new User(jsonObject.user),this.requireAuth=!!jsonObject.hasOwnProperty("require_auth")&&jsonObject.require_auth,this.url=this.requireAuth?String(jsonObject.url)+"?auth="+APIClient.getInstance().ekey:String(jsonObject.url),this.name=jsonObject.hasOwnProperty("name")?jsonObject.name:"File",this.size=parseInt(jsonObject.size)||0,this.type=String(jsonObject.type),this.data=jsonObject.hasOwnProperty("custom")?String(jsonObject.custom):"",this.reqId=jsonObject.hasOwnProperty("req_id")?String(jsonObject.req_id):"",this.customType=jsonObject.hasOwnProperty("custom_type")?String(jsonObject.custom_type):"",this.thumbnails=jsonObject.hasOwnProperty("thumbnails")?jsonObject.thumbnails:[],this.requireAuth))for(var i in this.thumbnails)this.thumbnails[i].url+="?auth="+APIClient.getInstance().ekey};_inherit(BaseMessage,FileMessage),FileMessage.build=function(requestId,msgId,user,channel,url,name,type,size,data,customType,createdAt,thumbnails,requireAuth){var obj={};obj.req_id=requestId,obj.msg_id=msgId,obj.channel_url=channel.url,obj.channel_type=channel.channelType==BaseChannel.CHANNEL_TYPE_OPEN?BaseChannel.CHANNEL_TYPE_OPEN:BaseChannel.CHANNEL_TYPE_GROUP,obj.ts=createdAt,obj.url=url,obj.name=name,obj.type=type,obj.size=size,obj.custom=data;var userObj={};return userObj.user_id=user.userId,userObj.nickname=user.nickname,userObj.profile_url=user.profileUrl,obj.user=userObj,customType&&(obj.custom_type=customType),requireAuth&&(obj.require_auth=requireAuth),thumbnails&&(obj.thumbnails=thumbnails),obj};var BaseChannel=function(jsonObject){this._update=function(jsonObject){this.url=String(jsonObject.channel_url),this.name=String(jsonObject.name),this.coverUrl=String(jsonObject.cover_url),this.createdAt=jsonObject.hasOwnProperty("created_at")?1e3*jsonObject.created_at:0,this.data=String(jsonObject.data),this.customType=jsonObject.hasOwnProperty("custom_type")?jsonObject.custom_type:""},this.isGroupChannel=function(){return this.channelType==BaseChannel.CHANNEL_TYPE_GROUP},this.isOpenChannel=function(){return this.channelType==BaseChannel.CHANNEL_TYPE_OPEN},this.createPreviousMessageListQuery=function(){return new PreviousMessageListQuery(this)},this.createMessageListQuery=function(){return new MessageListQuery(this)};var _getMessagesByTimestamp=function(channel,ts,isInclusive,prevResultSize,nextResultSize,shouldReverse,messageType,customType,cb){APIClient.getInstance().messageList(channel.isOpenChannel(),channel.url,ts,prevResultSize,nextResultSize,isInclusive,shouldReverse,messageType,customType,function(response,error){if(error)return void(cb&&cb(null,error));var objs=response.messages,messages=[];for(var i in objs){var msg=BaseMessage.build(objs[i],channel);msg&&messages.push(msg)}cb&&cb(messages)})},_getMessagesByID=function(channel,msgID,isInclusive,prevResultSize,nextResultSize,shouldReverse,messageType,customType,cb){APIClient.getInstance().messageListByID(channel.isOpenChannel(),channel.url,msgID,prevResultSize,nextResultSize,isInclusive,shouldReverse,messageType,customType,function(response,error){if(error)return void(cb&&cb(null,error));var objs=response.messages,messages=[];for(var i in objs){var msg=BaseMessage.build(objs[i],channel);msg&&messages.push(msg)}cb&&cb(messages)})};this.getNextMessagesByTimestamp=function(ts,isInclusive,nextResultSize,shouldReverse,messageType,customType,cb){return _SELF=this,_getMessagesByTimestamp(_SELF,ts,isInclusive,0,nextResultSize,shouldReverse,messageType,customType,cb)},this.getPreviousMessagesByTimestamp=function(ts,isInclusive,prevResultSize,shouldReverse,messageType,customType,cb){return _SELF=this,_getMessagesByTimestamp(_SELF,ts,isInclusive,prevResultSize,0,shouldReverse,messageType,customType,cb)},this.getPreviousAndNextMessagesByTimestamp=function(ts,prevResultSize,nextResultSize,shouldReverse,messageType,customType,cb){return _SELF=this,_getMessagesByTimestamp(_SELF,ts,!0,prevResultSize,nextResultSize,shouldReverse,messageType,customType,cb)},this.getNextMessagesByID=function(msgId,isInclusive,nextResultSize,shouldReverse,messageType,customType,cb){return _SELF=this,_getMessagesByID(_SELF,msgId,isInclusive,0,nextResultSize,shouldReverse,messageType,customType,cb)},this.getPreviousMessagesByID=function(msgId,isInclusive,prevResultSize,shouldReverse,messageType,customType,cb){return _SELF=this,_getMessagesByID(_SELF,msgId,isInclusive,prevResultSize,0,shouldReverse,messageType,customType,cb)},this.getPreviousAndNextMessagesByID=function(msgId,prevResultSize,nextResultSize,shouldReverse,messageType,customType,cb){return _SELF=this,_getMessagesByID(_SELF,msgId,!0,prevResultSize,nextResultSize,shouldReverse,messageType,customType,cb)},this._sendFileCommand=function(channelUrl,fileUrl,name,type,size,data,customType,thumbnails,requireAuth,callback){var requestId=Command.generateRequestId(),command=Command.bFile(requestId,channelUrl,fileUrl,name,type,size,data,customType,thumbnails,requireAuth);SendBird.getInstance().sendCommand(command,function(ackedCommand,error){if(error)return void(callback&&callback(null,error));var fileMessage=new FileMessage(ackedCommand.getJsonElement());callback&&callback(fileMessage)})},this.sendFileMessage=function(){var _SELF=this,file="",callback="",name="",type="",size="",data="",customType="",thumbnailSizes=[];switch(arguments.length){case 2:file=arguments[0],callback=arguments[1],"string"==typeof file?(name="",type="",size=0):(name=file.name,type=file.type,size=file.size);break;case 3:file=arguments[0],data=arguments[1],callback=arguments[2],"string"==typeof file?(name="",type="",size=0):(name=file.name,type=file.type,size=file.size);break;case 4:file=arguments[0],data=arguments[1],customType=arguments[2],callback=arguments[3],"string"==typeof file?(name="",type="",size=0):(name=file.name,type=file.type,size=file.size);break;case 5:file=arguments[0],data=arguments[1],customType=arguments[2],thumbnailSizes=arguments[3],callback=arguments[4],"string"==typeof file?(name="",type="",size=0):(name=file.name,type=file.type,size=file.size);break;case 6:file=arguments[0],name=arguments[1],type=arguments[2],size=arguments[3],data=arguments[4],callback=arguments[5];break;case 7:file=arguments[0],name=arguments[1],type=arguments[2],size=arguments[3],data=arguments[4],customType=arguments[5],callback=arguments[6];break;case 8:file=arguments[0],name=arguments[1],type=arguments[2],size=arguments[3],data=arguments[4],customType=arguments[5],thumbnailSizes=arguments[6],callback=arguments[7]}var channelUrl=_SELF.url;"string"==typeof file?_SELF._sendFileCommand(channelUrl,file,name,type,size,data,customType,[],!1,callback):APIClient.getInstance().uploadFile(file,type,thumbnailSizes,channelUrl,function(response,error){if(error)return void(callback&&callback(null,error));var result=JSON.parse(response),fileUrl=result.url,thumbnails=result.hasOwnProperty("thumbnails")?result.thumbnails:[],requireAuth=!!result.hasOwnProperty("require_auth")&&result.require_auth;_SELF._sendFileCommand(channelUrl,fileUrl,name,type,size,data,customType,thumbnails,requireAuth,callback)})},this.sendUserMessage=function(message,data,customType,targetLanguages,cb){"function"==typeof data&&(cb=data,data="",customType="",targetLanguages=[]),"function"==typeof customType&&(cb=customType,customType="",targetLanguages=[]),"function"==typeof targetLanguages&&(cb=targetLanguages,targetLanguages=[]),targetLanguages||(targetLanguages=[]),"string"==typeof targetLanguages&&(targetLanguages=[targetLanguages]);var cmd=Command.bMessage(this.url,message,data,customType,[],targetLanguages),msgObj=UserMessage.build(cmd.requestId,0,SendBird.getInstance().currentUser,this,message,data,(new Date).getTime()),msg=new UserMessage(msgObj);return SendBird.getInstance().sendCommand(cmd,function(ackedCommand,error){if(error)return void(cb&&cb(null,error));var userMessage=new UserMessage(ackedCommand.getJsonElement());cb&&cb(userMessage)}),msg},this.createMetaCounters=function(metaCounterMap,cb){APIClient.getInstance().createMetaCounters(this.isOpenChannel(),this.url,metaCounterMap,function(response,error){return error?void cb(null,error):void(cb&&cb(response))})},this.updateMetaCounters=function(metaCounterMap,upsert,cb){APIClient.getInstance().updateMetaCounters(this.isOpenChannel(),this.url,metaCounterMap,upsert,APIClient.UPDATE_META_COUNTER_MODE_SET,function(response,error){return error?void cb(null,error):void(cb&&cb(response))})},this.increaseMetaCounters=function(metaCounterMap,cb){APIClient.getInstance().updateMetaCounters(this.isOpenChannel(),this.url,metaCounterMap,!1,APIClient.UPDATE_META_COUNTER_MODE_INC,function(response,error){return error?void cb(null,error):void(cb&&cb(response))})},this.decreaseMetaCounters=function(metaCounterMap,cb){APIClient.getInstance().updateMetaCounters(this.isOpenChannel(),this.url,metaCounterMap,!1,APIClient.UPDATE_META_COUNTER_MODE_DEC,function(response,error){if(error)return void cb(null,error);var jsonObject=response,metas={};for(var i in jsonObject){var item=jsonObject[i];metas[i]=item}"function"==typeof cb&&cb(metas,null)})},this.getMetaCounters=function(keys,cb){APIClient.getInstance().getMetaCounters(this.isOpenChannel(),this.url,keys,function(response,error){return error?void cb(null,error):void("function"==typeof cb&&cb(response,null))})},this.getAllMetaCounters=function(cb){APIClient.getInstance().getAllMetaCounters(this.isOpenChannel(),this.url,function(response,error){return error?void cb(null,error):void("function"==typeof cb&&cb(response,null))})},this.deleteMetaCounter=function(key,cb){APIClient.getInstance().deleteMetaCounter(this.isOpenChannel(),this.url,key,function(response,error){return error?void cb(null,error):void(cb&&cb(response,null))})},this.deleteAllMetaCounters=function(cb){APIClient.getInstance().deleteAllMetaCounters(this.isOpenChannel(),this.url,function(response,error){return error?void(cb&&cb(null,error)):void(cb&&cb(response,null))})},this.createMetaData=function(metaDataMap,cb){APIClient.getInstance().createMetaData(this.isOpenChannel(),this.url,metaDataMap,function(response,error){return error?void cb(null,error):void(cb&&cb(response,null))})},this.updateMetaData=function(metaDataMap,upsert,cb){APIClient.getInstance().updateMetaData(this.isOpenChannel(),this.url,metaDataMap,upsert,function(response,error){return error?void cb(null,error):void(cb&&cb(response,null))})},this.getMetaData=function(keys,cb){APIClient.getInstance().getMetaData(this.isOpenChannel(),this.url,keys,function(response,error){return error?void cb(null,error):void(cb&&cb(response,null))})},this.getAllMetaData=function(cb){APIClient.getInstance().getAllMetaData(this.isOpenChannel(),this.url,function(response,error){return error?void cb(null,error):void(cb&&cb(response,null))})},this.deleteMetaData=function(key,cb){APIClient.getInstance().deleteMetaData(this.isOpenChannel(),this.url,key,function(response,error){return error?void cb(null,error):void(cb&&cb(response,null))})},this.deleteAllMetaData=function(cb){APIClient.getInstance().deleteAllMetaData(this.isOpenChannel(),this.url,function(response,error){return error?void(cb&&cb(null,error)):void(cb&&cb(response,null))})},this.deleteMessage=function(message,cb){var _SELF=this;return message?void APIClient.getInstance().deleteMessage(_SELF.isOpenChannel(),_SELF.url,message.messageId,function(response,error){return error?void(cb&&cb(null,error)):void(cb&&cb())}):void(cb&&cb(null,new SendBirdException("Invalid arguments.",SendBirdError.INVALID_PARAMETER)))},this.channelType=BaseChannel.CHANNEL_TYPE_BASE,jsonObject&&this._update(jsonObject)};BaseChannel.CHANNEL_TYPE_OPEN="open",BaseChannel.CHANNEL_TYPE_GROUP="group",BaseChannel.CHANNEL_TYPE_BASE="base";var OpenChannel=function(jsonObject){this.parse=function(jsonObject){if(jsonObject.hasOwnProperty("participant_count")&&(this.participantCount=parseInt(jsonObject.participant_count)),jsonObject.hasOwnProperty("operators")&&jsonObject.operators){this.operators=[];for(var i in jsonObject.operators){var operator=new User(jsonObject.operators[i]);this.operators.push(operator)}}},this.refresh=function(cb){OpenChannel.getChannelWithoutCache(this.url,function(channel,error){return error?void(cb&&cb(null,error)):void(cb&&cb())})},this.update=function(jsonObject){this._update(jsonObject),this.parse(jsonObject)},this.enter=function(cb){var _SELF=this,cmd=Command.bEnter(_SELF.url);SendBird.getInstance().sendCommand(cmd,function(response,error){return error?void(cb&&cb(null,error)):(OpenChannel.enteredChannels[_SELF.url]=_SELF,void(cb&&cb(null)))})},this.exit=function(cb){var _SELF=this,cmd=Command.bExit(_SELF.url);SendBird.getInstance().sendCommand(cmd,function(response,error){return error?void(cb&&cb(null,error)):(delete OpenChannel.enteredChannels[_SELF.url],void(cb&&cb(null)))})},this.createParticipantListQuery=function(){return new UserListQuery(UserListQuery.PARTICIPANT,this)},this.createMutedUserListQuery=function(){return new UserListQuery(UserListQuery.MUTED_USER,this)},this.createBannedUserListQuery=function(){return new UserListQuery(UserListQuery.BANNED_USER,this)},this.banUser=function(user,seconds,cb){return!user||parseInt(seconds)<0?void(cb&&cb(null,new SendBirdException("Invalid parameter.",SendBirdError.INVALID_PARAMETER))):void this.banUserWithUserId(user.userId,seconds,cb)},this.banUserWithUserId=function(userId,seconds,cb){return!userId||parseInt(seconds)<0?void(cb&&cb(null,new SendBirdException("Invalid parameter.",SendBirdError.INVALID_PARAMETER))):void APIClient.getInstance().banUser(this.url,userId,null,seconds,function(response,error){return error?void(cb&&cb(null,error)):void(cb&&cb())})},this.unbanUser=function(user,cb){return user?void this.unbanUserWithUserId(user.userId,cb):void(cb&&cb(null,new SendBirdException("Invalid parameter.",SendBirdError.INVALID_PARAMETER)))},this.unbanUserWithUserId=function(userId,cb){return userId?void APIClient.getInstance().unbanUser(this.url,userId,function(response,error){return error?void(cb&&cb(null,error)):void(cb&&cb())}):void(cb&&cb(null,new SendBirdException("Invalid parameter.",SendBirdError.INVALID_PARAMETER)))},this.muteUser=function(user,cb){return user?void this.muteUserWithUserId(user.userId,cb):void(cb&&cb(null,new SendBirdException("Invalid parameter.",SendBirdError.INVALID_PARAMETER)))},this.muteUserWithUserId=function(userId,cb){return userId?void APIClient.getInstance().muteUser(this.url,userId,function(response,error){return error?void(cb&&cb(null,error)):void(cb&&cb())}):void(cb&&cb(null,new SendBirdException("Invalid parameter.",SendBirdError.INVALID_PARAMETER)))},this.unmuteUser=function(user,cb){return user?void this.unmuteUserWithUserId(user.userId,cb):void(cb&&cb(null,new SendBirdException("Invalid parameter.",SendBirdError.INVALID_PARAMETER)))},this.unmuteUserWithUserId=function(userId,cb){return userId?void APIClient.getInstance().unmuteUser(this.url,userId,function(response,error){return error?void(cb&&cb(null,error)):void(cb&&cb())}):void(cb&&cb(null,new SendBirdException("Invalid parameter.",SendBirdError.INVALID_PARAMETER)))},this.isOperator=function(user){return!!user&&this.isOperatorWithUserId(user.userId)},this.isOperatorWithUserId=function(userId){for(var i in this.operators)if(this.operators[i].userId==userId)return!0;return!1},this.channelType=BaseChannel.CHANNEL_TYPE_OPEN,this.participantCount=0,this.operators=[],jsonObject&&(this._update(jsonObject),this.parse(jsonObject))};_inherit(BaseChannel,OpenChannel),OpenChannel.enteredChannels={},OpenChannel.clearEnteredChannels=function(){OpenChannel.enteredChannels={}},OpenChannel.createOpenChannelListQuery=function(){return new OpenChannelListQuery},OpenChannel.createChannel=function(){var name,coverUrl,data,operatorUserIds,customType,cb;switch(arguments.length){case 1:cb=arguments[0];break;case 4:name=arguments[0],coverUrl=arguments[1],data=arguments[2],cb=arguments[3];break;case 5:name=arguments[0],coverUrl=arguments[1],data=arguments[2],operatorUserIds=arguments[3],cb=arguments[4];break;case 6:name=arguments[0],coverUrl=arguments[1],data=arguments[2],operatorUserIds=arguments[3],customType=arguments[4],cb=arguments[5]}OpenChannel.createChannelWithOperatorUserIds(name,coverUrl,data,operatorUserIds,customType,cb)},OpenChannel.upsert=function(jsonObject){var newChannel=new OpenChannel(jsonObject);return OpenChannel.cachedChannels.hasOwnProperty(newChannel.url)?OpenChannel.cachedChannels[newChannel.url].update(jsonObject):OpenChannel.cachedChannels[newChannel.url]=newChannel,OpenChannel.cachedChannels[newChannel.url]},OpenChannel.createChannelWithOperatorUserIds=function(name,coverUrl,data,operatorUserIds,customType,cb){"function"==typeof customType&&(cb=customType,customType=""),APIClient.getInstance().createOpenChannel(name,coverUrl,data,operatorUserIds,customType,function(response,error){if(error)return void(cb&&cb(null,error));var channel=OpenChannel.upsert(response);cb&&cb(channel)})},OpenChannel.cachedChannels={},OpenChannel.clearCache=function(){OpenChannel.cachedChannels={}},OpenChannel.removeCachedChannel=function(channelUrl){delete OpenChannel.cachedChannels[channelUrl]},OpenChannel.getChannel=function(channelUrl,cb){OpenChannel.cachedChannels.hasOwnProperty(channelUrl)?cb&&cb(OpenChannel.cachedChannels[channelUrl]):OpenChannel.getChannelWithoutCache(channelUrl,cb)},OpenChannel.getChannelWithoutCache=function(channelUrl,cb){APIClient.getInstance().getOpenChannel(channelUrl,function(response,error){return error?void(cb&&cb(null,error)):(OpenChannel.upsert(response),void(cb&&cb(OpenChannel.cachedChannels[channelUrl],null)))})};var GroupChannel=function(jsonObject){var startTypingLastSentAt,endTypingLastSentAt,cachedTypingStatus={},markAsReadScheduled=!1;this.parse=function(jsonObject){var _SELF=this;if(_SELF.isDistinct=!!jsonObject.is_distinct,_SELF.unreadMessageCount=parseInt(jsonObject.unread_message_count),jsonObject.hasOwnProperty("read_receipt")){_SELF.cachedReadReceiptStatus={};for(var key in jsonObject.read_receipt){var value=jsonObject.read_receipt[key];_SELF.updateReadReceipt(key,parseInt(value))}}if(jsonObject.hasOwnProperty("members")){_SELF.members=[],_SELF.memberMap={};var objMembers=jsonObject.members;objMembers.forEach(function(member){var user=new User(member);_SELF.members.push(user),_SELF.memberMap[user.userId]=user}),_SELF.memberCount=_SELF.members.length}jsonObject.hasOwnProperty("member_count")&&(_SELF.memberCount=parseInt(jsonObject.member_count)),jsonObject.hasOwnProperty("last_message")&&"object"==typeof jsonObject.last_message&&jsonObject.last_message?_SELF.lastMessage=BaseMessage.build(jsonObject.last_message,_SELF):_SELF.lastMessage=null},this.refresh=function(cb){GroupChannel.getChannelWithoutCache(this.url,function(channel,error){return error?void(cb&&cb(null,error)):void(cb&&cb())})},this.update=function(jsonObject){this._update(jsonObject),this.parse(jsonObject)};var userToIds=function(userId){var userIds=[];return userId instanceof User?(userIds=[],userIds.push(userId.userId),userIds):Array.isArray(userId)?(userIds=[],userId.forEach(function(user){user instanceof User&&userIds.push(user.userId),parseInt(user)>0&&userIds.push(user)}),userIds):parseInt(userId)>0?(userIds=[],userIds.push(userId),userIds):void 0};this.invite=function(_users,cb){var userIds=userToIds(_users);this.inviteWithUserIds(userIds,cb)},this.inviteWithUserIds=function(userIds,cb){APIClient.getInstance().groupChannelInvite(this.url,userIds,function(response,error){return error?void(cb&&cb(null,error)):(GroupChannel.upsert(response),void(cb&&cb(null)))})},this.hide=function(cb){APIClient.getInstance().groupChannelHide(this.url,SendBird.getInstance().currentUser.userId,function(response,error){return error?void(cb&&cb(null,error)):void(cb&&cb(response))})},this.leave=function(cb){APIClient.getInstance().groupChannelLeave(this.url,SendBird.getInstance().currentUser.userId,function(response,error){return error?void(cb&&cb(null,error)):void(cb&&cb())})},this.markAsRead=function(){markAsReadScheduled=!0},this.fireMarkAsRead=function(){markAsReadScheduled&&(markAsReadScheduled=!1,this.sendMarkAsRead(function(response,error){}))},this.sendMarkAsRead=function(cb){var _SELF=this;if(!SendBird.getInstance().currentUser)return void(cb&&cb(null,new SendBirdException("Connection must be made before you mark as read.",SendBirdError.CONNECTION_REQUIRED)));var cmd=Command.bRead(_SELF.url);if(SendBird.getInstance().sendCommand(cmd,null),_SELF.unreadMessageCount>0){_SELF.unreadMessageCount=0;for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onChannelChanged(_SELF)}}cb&&cb()},this.getReadReceipt=function(message){if(message instanceof BaseMessage||console.log("message is not BaseMessage instance"),message.messageType==message.MESSAGE_TYPE_ADMIN)return 0;var me=SendBird.getInstance().currentUser,unreadMemberCount=0,createdAt=message.createdAt,members=this.members;for(var i in members){var member=members[i],key=member.userId;if(me.userId!=key){var value=this.cachedReadReceiptStatus[key];value=1e4&&(delete cachedTypingStatus[i],removed=!0)}return removed},this.updateTypingStatus=function(user,start){start?cachedTypingStatus[user.userId]=(new Date).getTime():delete cachedTypingStatus[user.userId]},this.isTyping=function(){return 0!=Object.keys(cachedTypingStatus).length},this.getTypingMembers=function(){var result=[];for(var userId in cachedTypingStatus){var user=this.memberMap[userId];this.memberMap[userId]&&result.push(user)}return result},this.addMember=function(user){this.removeMember(user),this.memberMap[user.userId]=user,this.members.push(user),this.memberCount++,this.updateReadReceipt(user.userId,0)},this.removeMember=function(user){var targetUserId=user.userId;if(this.memberMap.hasOwnProperty(user.userId)){delete this.memberMap[user.userId];for(var i in this.members){var member=this.members[i];if(member.userId==targetUserId){this.members.splice(i,1);break}}this.memberCount--}},this.setPushPreference=function(pushOn,cb){return SendBird.getInstance().currentUser?void APIClient.getInstance().setPushPreference(SendBird.getInstance().currentUser.userId,this.url,pushOn,function(response,error){ -return error?void(cb&&cb(null,error)):void(cb&&cb(response))}):void(cb&&cb(null,new SendBirdException("Connection must be made before you set push preference setting for this channel.",SendBirdError.CONNECTION_REQUIRED)))},this.getPushPreference=function(cb){return SendBird.getInstance().currentUser?void APIClient.getInstance().getPushPreference(SendBird.getInstance().currentUser.userId,this.url,function(response,error){if(error)return void(cb&&cb(null,error));if(cb){var pushOn;try{pushOn=response.enable}catch(e){pushOn=!1}cb(pushOn)}}):void(cb&&cb(null,new SendBirdException("Connection must be made before you get push preference setting for this channel.",SendBirdError.CONNECTION_REQUIRED)))},this.channelType=BaseChannel.CHANNEL_TYPE_GROUP,this.isDistinct=!1,this.unreadMessageCount=0,this.members=[],this.memberMap={},this.lastMessage={},this.memberCount=0,this.cachedReadReceiptStatus={},jsonObject&&(this._update(jsonObject),this.parse(jsonObject))};_inherit(BaseChannel,GroupChannel),GroupChannel.createMyGroupChannelListQuery=function(){return new GroupChannelListQuery(SendBird.getInstance().currentUser)},GroupChannel.getTotalUnreadMessageCount=function(cb){return SendBird.getInstance().currentUser?void APIClient.getInstance().getTotalUnreadMessageCount(SendBird.getInstance().currentUser.userId,function(response,error){if(error)return void(cb&&cb(null,error));var unreadCount=parseInt(response.unread_count);cb&&cb(unreadCount)}):void(cb&&cb(null,new SendBirdException("Connection must be made before you get total unread message count.",SendBirdError.CONNECTION_REQUIRED)))},GroupChannel.createChannel=function(){var users=null,isDistinct=null,name=null,coverUrl=null,data=null,callback=null,customType=null;switch(arguments.length){case 3:users=arguments[0],isDistinct=arguments[1],callback=arguments[2];break;case 4:users=arguments[0],isDistinct=arguments[1],customType=arguments[2],callback=arguments[3];break;case 6:users=arguments[0],isDistinct=arguments[1],name=arguments[2],coverUrl=arguments[3],data=arguments[4],callback=arguments[5];break;case 7:users=arguments[0],isDistinct=arguments[1],name=arguments[2],coverUrl=arguments[3],data=arguments[4],customType=arguments[5],callback=arguments[6]}var userIds=[];users.forEach(function(user){userIds.push(user.userId)}),GroupChannel.createChannelWithUserIds(userIds,isDistinct,name,coverUrl,data,customType,callback)},GroupChannel.createChannelWithUserIds=function(_userIds,isDistinct,name,coverUrl,data,customType,cb){"function"==typeof customType&&(cb=customType,customType="");var userIdSet=_userIds.filter(function(elem,index,self){return index==self.indexOf(elem)}),me=SendBird.getInstance().currentUser;userIdSet.push(me.userId),APIClient.getInstance().createGroupChannel(userIdSet,isDistinct,name,coverUrl,data,customType,function(response,error){if(error)return void(cb&&cb(null,error));var channel=new GroupChannel(response);GroupChannel.cachedChannels[channel.url]=channel,cb&&cb(channel,null)})},GroupChannel.cachedChannels={},GroupChannel.clearCache=function(){GroupChannel.cachedChannels={}},GroupChannel.removeCachedChannel=function(channelUrl){delete GroupChannel.cachedChannels[channelUrl]},GroupChannel.upsert=function(jsonObject){var newChannel=new GroupChannel(jsonObject);return GroupChannel.cachedChannels.hasOwnProperty(newChannel.url)?GroupChannel.cachedChannels[newChannel.url].update(jsonObject):GroupChannel.cachedChannels[newChannel.url]=newChannel,GroupChannel.cachedChannels[newChannel.url]},GroupChannel.getChannelWithoutCache=function(channelUrl,cb){APIClient.getInstance().getGroupChannel(channelUrl,!0,!0,function(response,error){return error?void(cb&&cb(null,error)):(GroupChannel.upsert(response),void(cb&&cb(GroupChannel.cachedChannels[channelUrl],null)))})},GroupChannel.getChannel=function(channelUrl,cb){if(GroupChannel.cachedChannels.hasOwnProperty(channelUrl)){if(cb)return void cb(GroupChannel.cachedChannels[channelUrl],null)}else GroupChannel.getChannelWithoutCache(channelUrl,cb)},GroupChannel.markAsReadAllLastSentAt,GroupChannel.markAsReadAll=function(cb){var now=(new Date).getTime();return now-GroupChannel.markAsReadAllLastSentAt<1e3?void(cb&&cb(new SendBirdException("MarkAsRead rate limit exceeded.",SendBirdError.MARK_AS_READ_RATE_LIMIT_EXCEEDED))):(GroupChannel.markAsReadAllLastSentAt=now,void APIClient.getInstance().groupChannelMarkAsReadAll(SendBird.getInstance().currentUser.userId,function(response,error){if(error)return void(cb&&cb(error));for(var i in GroupChannel.cachedChannels)GroupChannel.cachedChannels[i].unreadMessageCount=0;cb&&cb(null)}))};var ChannelEvent=function(jsonObject){jsonObject&&(this.category=jsonObject.hasOwnProperty("cat")?parseInt(jsonObject.cat):0,this.data=jsonObject.hasOwnProperty("data")?jsonObject.data:null,this.channelUrl=jsonObject.hasOwnProperty("channel_url")?String(jsonObject.channel_url):"",this.channelType=jsonObject.hasOwnProperty("channel_type")?String(jsonObject.channel_type):BaseChannel.CHANNEL_TYPE_GROUP),this.isGroupChannel=function(){return this.channelType==BaseChannel.CHANNEL_TYPE_GROUP},this.isOpenChannel=function(){return this.channelType==BaseChannel.CHANNEL_TYPE_OPEN}};ChannelEvent.CATEGORY_NONE=0,ChannelEvent.CATEGORY_CHANNEL_ENTER=10102,ChannelEvent.CATEGORY_CHANNEL_EXIT=10103,ChannelEvent.CATEGORY_USER_CHANNEL_MUTE=10201,ChannelEvent.CATEGORY_USER_CHANNEL_UNMUTE=10200,ChannelEvent.CATEGORY_USER_CHANNEL_BAN=10601,ChannelEvent.CATEGORY_USER_CHANNEL_UNBAN=10600,ChannelEvent.CATEGORY_CHANNEL_FREEZE=10701,ChannelEvent.CATEGORY_CHANNEL_UNFREEZE=10700,ChannelEvent.CATEGORY_TYPING_START=10900,ChannelEvent.CATEGORY_TYPING_END=10901,ChannelEvent.CATEGORY_CHANNEL_JOIN=1e4,ChannelEvent.CATEGORY_CHANNEL_LEAVE=10001,ChannelEvent.CATEGORY_CHANNEL_PROP_CHANGED=11e3,ChannelEvent.CATEGORY_CHANNEL_DELETED=12e3;var ReadStatus=function(jsonObject){jsonObject&&(this.reader=new User(jsonObject.user),this.timestamp=parseInt(jsonObject.ts),this.channelUrl=jsonObject.hasOwnProperty("channel_url")?String(jsonObject.channel_url):"",this.channelType=jsonObject.hasOwnProperty("channel_type")?String(jsonObject.channel_type):BaseChannel.CHANNEL_TYPE_GROUP)},User=function(jsonObject){this.nickname="",this.profileUrl="",this.userId="",this.connectionStatus,this.lastSeenAt=null;var _SELF=this;if(jsonObject)try{jsonObject.hasOwnProperty("guest_id")&&(_SELF.userId=String(jsonObject.guest_id)),jsonObject.hasOwnProperty("user_id")&&(_SELF.userId=String(jsonObject.user_id)),jsonObject.hasOwnProperty("name")&&(_SELF.nickname=String(jsonObject.name)),jsonObject.hasOwnProperty("nickname")&&(_SELF.nickname=String(jsonObject.nickname)),jsonObject.hasOwnProperty("image")&&(_SELF.profileUrl=String(jsonObject.image)),jsonObject.hasOwnProperty("profile_url")&&(_SELF.profileUrl=String(jsonObject.profile_url)),jsonObject.hasOwnProperty("is_online")?_SELF.connectionStatus=jsonObject.is_online?User.ONLINE:User.OFFLINE:_SELF.connectionStatus=User.NON_AVAILABLE,jsonObject.hasOwnProperty("last_seen_at")?_SELF.lastSeenAt=parseInt(jsonObject.last_seen_at):_SELF.lastSeenAt=0}catch(e){console.log(e)}};User.NON_AVAILABLE="nonavailable",User.ONLINE="online",User.OFFLINE="offline",User.build=function(userId,nickname,profileUrl,isOnline,lastSeenAt){return{user_id:userId,nickname:nickname,profile_url:profileUrl,is_online:isOnline,last_seen_at:lastSeenAt}};var Command=function(_command,_payload,_requestId){this.isAckRequired=function(){return"MESG"==this.command||"FILE"==this.command||"ENTR"==this.command||"EXIT"==this.command},this.encode=function(){return this.command+this.payload+"\n"},this.decode=function(cmd){cmd=cmd.trim(),this.command=cmd.substring(0,4),this.payload=cmd.substring(4)},this.getJsonElement=function(){return JSON.parse(this.payload)},this.isRequestIdCommand=function(){return this.isAckRequired()||"EROR"==this.command},this.command,this.payload,this.requestId;var _SELF=this;if(0!=arguments.length){var reqId;switch(arguments.length){case 1:var data=arguments[0];if(!data||data.length<=4)return _SELF.command="NOOP",void(_SELF.payload="{}");if(data=data.trim(),_SELF.command=data.substring(0,4),_SELF.payload=data.substring(4),_SELF.isRequestIdCommand()){var obj=_SELF.getJsonElement();obj&&(_SELF.requestId=obj.hasOwnProperty("req_id")?obj.req_id:"")}break;case 3:reqId=arguments[2];case 2:var command=arguments[0],payload=arguments[1];reqId=reqId?reqId:"",_SELF.command=command,_SELF.requestId=reqId,_SELF.requestId||_SELF.isRequestIdCommand()&&(_SELF.requestId=Command.generateRequestId()),payload.req_id=_SELF.requestId,_SELF.payload=JSON.stringify(payload)}}};Command.bMessage=function(channelUrl,message,data,customType,mentionedUserIds,targetLanguages){var obj={};obj.channel_url=channelUrl,obj.message=message,obj.data=data,obj.mentioned=[];for(var i in mentionedUserIds){var item=mentionedUserIds[i];obj.mentioned.push(String(item))}return customType&&(obj.custom_type=customType),targetLanguages.length>0&&(obj.target_langs=targetLanguages),new Command("MESG",obj)},Command.bRead=function(channelUrl){var obj={};return obj.channel_url=channelUrl,new Command("READ",obj)},Command.bTypeStart=function(channelUrl,time){var obj={};return obj.channel_url=channelUrl,obj.time=time,new Command("TPST",obj)},Command.bTypeEnd=function(channelUrl,time){var obj={};return obj.channel_url=channelUrl,obj.time=time,new Command("TPEN",obj)},Command.bFile=function(requestId,channelUrl,url,name,type,size,data,customType,thumbnails,requireAuth){var obj={};return obj.channel_url=channelUrl,obj.url=url,obj.name=name,obj.type=type,obj.size=size,obj.custom=data,customType&&(obj.custom_type=customType),thumbnails&&(obj.thumbnails=thumbnails),requireAuth&&(obj.require_auth=requireAuth),new Command("FILE",obj,requestId)},Command.bPing=function(){var obj={};return obj.id=(new Date).getTime(),new Command("PING",obj)},Command.bEnter=function(channelUrl){var obj={};return obj.channel_url=channelUrl,new Command("ENTR",obj)},Command.bExit=function(channelUrl){var obj={};return obj.channel_url=channelUrl,new Command("EXIT",obj)},Command.requestIdSeed=(new Date).getTime(),Command.generateRequestId=function(){return Command.requestIdSeed++,String(Command.requestIdSeed)};var GroupChannelListQuery=function(_user){this.isLoading=!1,this.limit=20,this.includeEmpty=!1,this.order=GroupChannelListQuery.ORDER_LATEST_LAST_MESSAGE,this.hasNext=!0,this.userIdsFilter=[],this.userIdsFilterExactMatch=!1,this.nicknameContainsFilter="",this.queryType="AND";var user=_user,token="",sInstance=this;this.next=function(cb){return sInstance.hasNext?(sInstance.isLoading&&cb(null,new SendBirdException("Query in progress.",SendBirdError.QUERY_IN_PROGRESS)),sInstance.isLoading=!0,void APIClient.getInstance().loadUserGroupChannelList(user.userId,token,sInstance.limit,sInstance.includeEmpty,sInstance.order,sInstance.userIdsFilter,sInstance.userIdsFilterExactMatch,sInstance.nicknameContainsFilter,sInstance.queryType,function(response,error){if(error)return sInstance.isLoading=!1,void(cb&&cb(null,error));var result=response;token=String(result.next),(!token||token.length<=0)&&(sInstance.hasNext=!1);var channelObjs=result.channels,channels=[];for(var i in channelObjs){var channel=GroupChannel.upsert(channelObjs[i]);channels.push(channel)}sInstance.isLoading=!1,cb&&cb(channels,null)})):void cb([],null)}};GroupChannelListQuery.ORDER_LATEST_LAST_MESSAGE="latest_last_message",GroupChannelListQuery.ORDER_CHRONOLOGICAL="chronological";var MessageListQuery=function(_channel){this.isLoading=!1;var channel=_channel,sInstance=this;this.next=function(messageTimestamp,limit,reverse,cb){return sInstance.isLoading?void cb(null,new SendBirdException("Query in progress.",SendBirdError.QUERY_IN_PROGRESS)):(sInstance.isLoading=!0,void APIClient.getInstance().messageList(channel.isOpenChannel(),channel.url,messageTimestamp,0,limit,!1,reverse,"","",function(response,error){if(error)return sInstance.isLoading=!1,void(cb&&cb(null,error));var objs=response.messages,messages=[];for(var i in objs){var msg=BaseMessage.build(objs[i],channel);msg&&messages.push(msg)}sInstance.isLoading=!1,cb&&cb(messages)}))},this.prev=function(messageTimestamp,limit,reverse,cb){return sInstance.isLoading?void cb(null,new SendBirdException("Query in progress.",SendBirdError.QUERY_IN_PROGRESS)):(sInstance.isLoading=!0,void APIClient.getInstance().messageList(channel.isOpenChannel(),channel.url,messageTimestamp,limit,0,!1,reverse,"","",function(response,error){if(error)return sInstance.isLoading=!1,void(cb&&cb(null,error));var objs=response.messages,messages=[];for(var i in objs){var msg=BaseMessage.build(objs[i],channel);msg&&messages.push(msg)}sInstance.isLoading=!1,cb&&cb(messages)}))},this.load=function(messageTimestamp,prevLimit,nextLimit,reverse,cb){return sInstance.isLoading?void cb(null,new SendBirdException("Query in progress.",SendBirdError.QUERY_IN_PROGRESS)):(sInstance.isLoading=!0,void APIClient.getInstance().messageList(channel.isOpenChannel(),channel.url,messageTimestamp,prevLimit,nextLimit,!0,reverse,"","",function(response,error){if(error)return sInstance.isLoading=!1,void(cb&&cb(null,error));var objs=response.messages,messages=[];for(var i in objs){var msg=BaseMessage.build(objs[i],channel);msg&&messages.push(msg)}sInstance.isLoading=!1,cb&&cb(messages)}))}},OpenChannelListQuery=function(){var token="";this.limit=20,this.isLoading=!1,this.hasNext=!0,this.nameKeyword="",this.urlKeyword="";var sInstance=this;this.next=function(cb){return this.hasNext?this.isLoading?void cb(null,new SendBirdException("WS connection closed.",SendBirdError.QUERY_IN_PROGRESS)):(sInstance.isLoading=!0,void APIClient.getInstance().loadOpenChannelList(token,sInstance.limit,sInstance.nameKeyword,sInstance.urlKeyword,function(response,error){if(error)return sInstance.isLoading=!1,void(cb&&cb(null,error));var result=response;try{token=String(result.next)}catch(e){token=""}token||(sInstance.hasNext=!1);var channelObjs=result.channels,channels=[];channelObjs.forEach(function(item){var channel=OpenChannel.upsert(item);channels.push(channel)}),sInstance.isLoading=!1,cb(channels,null)})):void cb([],null)}},PreviousMessageListQuery=function(_channel){var channel=_channel,messageTimestamp=0x8000000000000000;this.hasMore=!0,this.isLoading=!1;var sInstance=this;this.load=function(limit,reverse,messageType,cb){if("function"==typeof messageType&&(cb=messageType,messageType=""),messageType==BaseMessage.MESSAGE_TYPE_ADMIN?messageType="ADMM":messageType==BaseMessage.MESSAGE_TYPE_USER&&(messageType="MESG"),messageType=messageType==BaseMessage.MESSAGE_TYPE_FILE?"FILE":"",sInstance.hasMore){if(sInstance.isLoading)return void cb(null,new SendBirdException("WS connection closed.",SendBirdError.QUERY_IN_PROGRESS));sInstance.isLoading=!0,APIClient.getInstance().messageList(channel.isOpenChannel(),channel.url,messageTimestamp,limit,0,!1,reverse,messageType,"",function(response,error){if(error)return sInstance.isLoading=!1,void(cb&&cb(null,error));var objs=response.messages,messages=[];for(var i in objs){var msg=BaseMessage.build(objs[i],channel);msg&&(messages.push(msg),msg.createdAt<=messageTimestamp&&(messageTimestamp=msg.createdAt))}(messages.length<=0||messages.length300?_ajaxCall(APIClient.API_ROUTING_URL.replace("%s",appId),{},"GET",{SendBird:API_HEADER_PARAM+appId},function(result,error){return error?void cb(null,new SendBirdException("Server is unreachable.",SendBirdError.NETWORK_ROUTING_ERROR)):(WS_HOST=result.ws_server,API_HOST=result.api_server,sbRouterTimer=now,void("function"==typeof cb&&cb({API_HOST:API_HOST,WS_HOST:WS_HOST})))},function(errCode,errTxt){cb(null,new SendBirdException(errTxt,errCode))}):cb(null,null)}};var requestFILE=function(url,form,file,fileType,thumbnailSizes,channelUrl,cb){APIClient.getInstance().checkRouting(function(result,error){if(error)cb(null,new SendBirdException("Request failed.",SendBirdError.REQUEST_FAILED));else{var request=new XMLHttpRequest;request.open("POST",API_HOST+url,!0),request.setRequestHeader("SendBird",API_HEADER_PARAM+appId),request.setRequestHeader("Session-Key",APIClient.getInstance().sessionKey);var formData=new FormData;fileType&&"undefined"!=typeof Blob?formData.append("file",new Blob([file],{type:fileType}),file.name):formData.append("file",file,file.name),channelUrl&&formData.append("channel_url",channelUrl);for(var i in thumbnailSizes){var i2=parseInt(i)+1;formData.append("thumbnail"+i2,thumbnailSizes[i].maxWidth+","+thumbnailSizes[i].maxHeight)}request.onload=function(){cb(request.response)},request.onerror=function(e){cb(null,new SendBirdException(request.statusText,SendBirdError.REQUEST_FAILED))},request.send(formData)}})},requestDELETE=function(url,params,cb){"function"==typeof params&&(cb=params,params={}),APIClient.getInstance().checkRouting(function(result,error){error?cb(null,new SendBirdException("Request failed.",SendBirdError.REQUEST_FAILED)):_ajaxCall(API_HOST+url,params,"DELETE",{"Session-Key":APIClient.getInstance().sessionKey,SendBird:API_HEADER_PARAM+appId},cb)})},encodeParams=function(params){var encodedParams="";for(var i in params){var tmp=encodeURIComponent(params[i]);encodedParams+=tmp+","}return encodedParams.length>1&&(encodedParams=encodedParams.substring(0,encodedParams.length-1)),encodedParams},requestGET=function(url,params,cb){"function"==typeof params&&(cb=params,params={});var fullUrl,urlParams="";if(params){for(var key in params)""!=urlParams&&(urlParams+="&"),urlParams+=key+"="+params[key];fullUrl=API_HOST+url+"?"+urlParams}else fullUrl=API_HOST+url;APIClient.getInstance().checkRouting(function(result,error){error?cb(null,new SendBirdException("Request failed.",SendBirdError.REQUEST_FAILED)):_ajaxCall(fullUrl,params,"GET",{"Session-Key":APIClient.getInstance().sessionKey,SendBird:API_HEADER_PARAM+appId},cb)})},requestPOST=function(url,params,cb){"function"==typeof params&&(cb=params,params={}),APIClient.getInstance().checkRouting(function(result,error){error||_ajaxCall(API_HOST+url,params,"POST",{"Session-Key":APIClient.getInstance().sessionKey,SendBird:API_HEADER_PARAM+appId},cb)})},requestPUT=function(url,params,cb){"function"==typeof params&&(cb=params,params={}),APIClient.getInstance().checkRouting(function(result,error){error||_ajaxCall(API_HOST+url,params,"PUT",{"Session-Key":APIClient.getInstance().sessionKey,SendBird:API_HEADER_PARAM+appId},cb)})};this.groupChannelInvite=function(channelUrl,_userIds,cb){var url=APIClient.API_GROUPCHANNELS_CHANNELURL_INVITE.replace("%s",encodeURIComponent(channelUrl)),form={},userIds=[];try{Array.isArray(_userIds)?userIds=_userIds:userIds.push(_userIds)}catch(e){console.log(e),cb(null,new SendBirdException("Invalid parameter.",SendBirdError.INVALID_PARAMETER))}form.user_ids=userIds,requestPOST(url,form,cb)},this.groupChannelHide=function(channelUrl,userId,cb){var url=APIClient.API_GROUPCHANNELS_CHANNELURL_HIDE.replace("%s",encodeURIComponent(channelUrl)),form={};form.user_id=userId,requestPUT(url,form,cb)},this.groupChannelLeave=function(channelUrl,userId,cb){var url=APIClient.API_GROUPCHANNELS_CHANNELURL_LEAVE.replace("%s",encodeURIComponent(channelUrl)),form={};form.user_id=userId,requestPUT(url,form,cb)},this.groupChannelMarkAsRead=function(channelUrl,userId,cb){var url=APIClient.API_GROUPCHANNELS_CHANNELURL_MESSAGES_MARKASREAD.replace("%s",encodeURIComponent(channelUrl)),form={};form.user_id=userId,requestPUT(url,form,cb)},this.groupChannelMarkAsReadAll=function(userId,cb){var url=APIClient.API_USERS_USERID_MARKASREADALL.replace("%s",encodeURIComponent(userId)),form={};requestPUT(url,form,cb)},this.messageList=function(isOpenChannel,channelUrl,messageTimestamp,prevLimit,nextLimit,include,reverse,messageType,customType,cb){var url;url=isOpenChannel?String(APIClient.API_OPENCHANNELS_CHANNELURL_MESSAGES.replace("%s",channelUrl)):String(APIClient.API_GROUPCHANNELS_CHANNELURL_MESSAGES.replace("%s",channelUrl));var params={};params.is_sdk=String(!0),params.message_ts=String(messageTimestamp),params.prev_limit=String(prevLimit),params.next_limit=String(nextLimit),params.include=String(include),params.reverse=String(reverse),messageType&&(params.message_type=String(messageType)),customType&&(params.custom_type=String(customType)),requestGET(url,params,cb)},this.messageListByID=function(isOpenChannel,channelUrl,messageID,prevLimit,nextLimit,include,reverse,messageType,customType,cb){var url;url=isOpenChannel?String(APIClient.API_OPENCHANNELS_CHANNELURL_MESSAGES.replace("%s",channelUrl)):String(APIClient.API_GROUPCHANNELS_CHANNELURL_MESSAGES.replace("%s",channelUrl));var params={};params.is_sdk=String(!0),params.message_id=messageID,params.prev_limit=String(prevLimit),params.next_limit=String(nextLimit),params.include=String(include),params.reverse=String(reverse),messageType&&(params.message_type=String(messageType)),customType&&(params.custom_type=String(customType)),requestGET(url,params,cb)},this.login=function(userId,accessToken,cb){var url=APIClient.API_USERS_USERID_LOGIN.replace("%s",encodeURIComponent(userId)),form={};form.app_id=appId,accessToken&&(form.access_token=accessToken),requestPOST(url,form,function(response,error){error?cb(null,error):(APIClient.getInstance().sessionKey=response.key,APIClient.getInstance().ekey=response.ekey,cb(response,error))})},this.updateUserInfo=function(userId,nickname,profileUrl,cb){var form={};nickname&&(form.nickname=nickname),profileUrl&&(form.profile_url=profileUrl);var url=String(APIClient.API_USERS_USERID).replace("%s",encodeURIComponent(userId));requestPUT(url,form,cb)},this.getGroupChannel=function(channelUrl,member,readReceipt,cb){var url=APIClient.API_GROUPCHANNELS_CHANNELURL.replace("%s",encodeURIComponent(channelUrl)),params={member:String(member),read_receipt:String(readReceipt)};requestGET(url,params,cb)},this.getOpenChannel=function(channelUrl,cb){var url=APIClient.API_OPENCHANNELS_CHANNELURL.replace("%s",encodeURIComponent(channelUrl));requestGET(url,cb)},this.createGroupChannel=function(_userIds,isDistinct,name,coverUrlOrFile,data,customType,cb){var url=APIClient.API_GROUPCHANNELS,userIds=[];"string"==typeof _userIds?userIds.push(_userIds):_userIds.forEach(function(userId){userIds.push(userId)});var form;coverUrlOrFile&&"string"!=typeof coverUrlOrFile?(form=new FormData,coverUrlOrFile&&form.append("cover_file",coverUrlOrFile,coverUrlOrFile.name),form.append("user_ids",userIds),form.append("is_distinct",isDistinct),name&&form.append("name",name),data&&form.append("data",data),customType&&form.append("custom_type",customType)):(form={},coverUrlOrFile&&(form.cover_url=coverUrlOrFile),form.user_ids=userIds,form.is_distinct=isDistinct,name&&(form.name=name),data&&(form.data=data),customType&&(form.custom_type=customType)),requestPOST(url,form,cb)},this.createOpenChannel=function(name,coverUrlOrFile,data,operatorIds,customType,cb){var form,url=String(APIClient.API_OPENCHANNELS);coverUrlOrFile&&"string"!=typeof coverUrlOrFile?(form=new FormData,coverUrlOrFile&&form.append("cover_file",coverUrlOrFile,coverUrlOrFile.name),name&&form.append("name",name),data&&form.append("data",data),operatorIds&&(Array.isArray(operatorIds)?form.append("operators",operatorIds):form.append("operators",[operatorIds])),customType&&form.append("custom_type",customType)):(form={},coverUrlOrFile&&(form.cover_url=coverUrlOrFile),name&&(form.name=name),data&&(form.data=data),operatorIds&&(Array.isArray(operatorIds)?form.operators=operatorIds:form.operators=[operatorIds]),customType&&(form.custom_type=customType)),requestPOST(url,form,cb)},this.createMetaCounters=function(isOpenChannel,channelUrl,metaCounterMap,cb){var url;url=isOpenChannel?APIClient.API_OPENCHANNELS_CHANNELURL_METACOUNTER.replace("%s",encodeURIComponent(channelUrl)):APIClient.API_GROUPCHANNELS_CHANNELURL_METACOUNTER.replace("%s",encodeURIComponent(channelUrl));var form={};form.metacounter=metaCounterMap,requestPOST(url,form,cb)},this.updateMetaCounters=function(isOpenChannel,channelUrl,metaCounterMap,upsert,mode,cb){var url;url=isOpenChannel?APIClient.API_OPENCHANNELS_CHANNELURL_METACOUNTER.replace("%s",encodeURIComponent(channelUrl)):APIClient.API_GROUPCHANNELS_CHANNELURL_METACOUNTER.replace("%s",encodeURIComponent(channelUrl));var form={};switch(form.metacounter=metaCounterMap,form.upsert=upsert,mode){case APIClient.UPDATE_META_COUNTER_MODE_SET:form.mode="set";break;case APIClient.UPDATE_META_COUNTER_MODE_INC:form.mode="increase";break;case APIClient.UPDATE_META_COUNTER_MODE_DEC:form.mode="decrease"}requestPUT(url,form,cb)},this.getAllMetaCounters=function(isOpenChannel,channelUrl,cb){this.getMetaCounters(isOpenChannel,channelUrl,{},cb)},this.getMetaCounters=function(isOpenChannel,channelUrl,keys,cb){var url;url=isOpenChannel?APIClient.API_OPENCHANNELS_CHANNELURL_METACOUNTER.replace("%s",encodeURIComponent(channelUrl)):APIClient.API_GROUPCHANNELS_CHANNELURL_METACOUNTER.replace("%s",encodeURIComponent(channelUrl));var joinedKeys=encodeParams(keys),params={keys:joinedKeys};requestGET(url,params,cb)},this.deleteMetaCounter=function(isOpenChannel,channelUrl,key,cb){ -var url="";url=isOpenChannel?APIClient.API_OPENCHANNELS_CHANNELURL_METACOUNTER_KEY.replace("%s",encodeURIComponent(channelUrl)).replace("%s",key):APIClient.API_GROUPCHANNELS_CHANNELURL_METACOUNTER_KEY.replace("%s",encodeURIComponent(channelUrl)).replace("%s",key);var form={};requestDELETE(url,form,cb)},this.deleteAllMetaCounters=function(isOpenChannel,channelUrl,cb){var url="";url=isOpenChannel?APIClient.API_OPENCHANNELS_CHANNELURL_METACOUNTER.replace("%s",encodeURIComponent(channelUrl)):APIClient.API_GROUPCHANNELS_CHANNELURL_METACOUNTER.replace("%s",encodeURIComponent(channelUrl));var form={};requestDELETE(url,form,cb)},this.createMetaData=function(isOpenChannel,channelUrl,metaDataMap,cb){var url="";url=isOpenChannel?APIClient.API_OPENCHANNELS_CHANNELURL_METADATA.replace("%s",encodeURIComponent(channelUrl)):APIClient.API_GROUPCHANNELS_CHANNELURL_METADATA.replace("%s",encodeURIComponent(channelUrl));var form={},metas={};for(var i in metaDataMap){var item=metaDataMap[i];metas[i]=item}form.metadata=metas,requestPOST(url,form,cb)},this.updateMetaData=function(isOpenChannel,channelUrl,metaDataMap,upsert,cb){var url="";url=isOpenChannel?APIClient.API_OPENCHANNELS_CHANNELURL_METADATA.replace("%s",encodeURIComponent(channelUrl)):APIClient.API_GROUPCHANNELS_CHANNELURL_METADATA.replace("%s",encodeURIComponent(channelUrl));var form={},metas={};for(var i in metaDataMap){var item=metaDataMap[i];metas[i]=item}form.metadata=metas,form.upsert=upsert,requestPUT(url,form,cb)},this.getAllMetaData=function(isOpenChannel,channelUrl,cb){this.getMetaData(isOpenChannel,channelUrl,{},cb)},this.getMetaData=function(isOpenChannel,channelUrl,keys,cb){var url="";url=isOpenChannel?APIClient.API_OPENCHANNELS_CHANNELURL_METADATA.replace("%s",encodeURIComponent(channelUrl)):APIClient.API_GROUPCHANNELS_CHANNELURL_METADATA.replace("%s",encodeURIComponent(channelUrl));var joinedKeys=encodeParams(keys),params={keys:joinedKeys};requestGET(url,params,cb)},this.deleteMetaData=function(isOpenChannel,channelUrl,key,cb){var url="";url=isOpenChannel?APIClient.API_OPENCHANNELS_CHANNELURL_METADATA_KEY.replace("%s",encodeURIComponent(channelUrl)).replace("%s",key):APIClient.API_GROUPCHANNELS_CHANNELURL_METADATA_KEY.replace("%s",encodeURIComponent(channelUrl)).replace("%s",key),requestDELETE(url,{},cb)},this.deleteAllMetaData=function(isOpenChannel,channelUrl,cb){var url="";url=isOpenChannel?APIClient.API_OPENCHANNELS_CHANNELURL_METADATA.replace("%s",encodeURIComponent(channelUrl)):APIClient.API_GROUPCHANNELS_CHANNELURL_METADATA.replace("%s",encodeURIComponent(channelUrl)),requestDELETE(url,{},cb)},this.loadUserList=function(token,limit,userIds,cb){var url=APIClient.API_USERS,params={token:encodeURIComponent(token),limit:String(limit)};if("function"==typeof userIds)cb=userIds;else try{var serializedUserIds="";for(var i in userIds){var userId=userIds[i];serializedUserIds+=userId+","}serializedUserIds.length>1&&(serializedUserIds=serializedUserIds.substring(0,serializedUserIds.length-1)),params.user_ids=serializedUserIds}catch(e){}requestGET(url,params,cb)},this.loadBlockedUserList=function(blockerUserId,token,limit,cb){var url=APIClient.API_USERS_USERID_BLOCK.replace("%s",encodeURIComponent(blockerUserId)),params={token:encodeURIComponent(token),limit:String(limit)};requestGET(url,params,cb)},this.loadOpenChannelList=function(token,limit,nameKeyword,urlKeyword,cb){var url=APIClient.API_OPENCHANNELS,params={token:encodeURIComponent(token),limit:String(limit)};nameKeyword&&(params.name_contains=encodeURIComponent(nameKeyword)),urlKeyword&&(params.url_contains=encodeURIComponent(urlKeyword)),requestGET(url,params,cb)},this.uploadFile=function(file,fileType,thumbnailSizes,channelUrl,cb){requestFILE(APIClient.API_STORAGE_FILE,{},file,fileType,thumbnailSizes,channelUrl,cb)},this.uploadProfileImage=function(file,cb){requestFILE(APIClient.API_STORAGE_PROFILE,{},file,"",[],"",cb)},this.loadUserGroupChannelList=function(userId,token,limit,includeEmpty,order,userIds,userIdsExactMatch,nicknameContainsFilter,queryType,cb){var url=APIClient.API_MYGROUPCHANNELS.replace("%s",encodeURIComponent(userId)),params={token:encodeURIComponent(token),limit:String(limit),show_member:!0,show_empty:String(includeEmpty),order:order};if(nicknameContainsFilter)try{params.members_nickname_contains=encodeURIComponent(nicknameContainsFilter)}catch(e){}if(userIds.length>0)try{userIdsExactMatch?params.members_exactly_in=encodeParams(userIds):(params.members_include_in=encodeParams(userIds),params.query_type=queryType)}catch(e){}requestGET(url,params,cb)},this.loadOpenChannelParticipantList=function(channelUrl,token,limit,cb){var url=APIClient.API_OPENCHANNELS_CHANNELURL_PARTICIPANTS.replace("%s",channelUrl),params={token:encodeURIComponent(token),limit:String(limit)};requestGET(url,params,cb)},this.loadOpenChannelMutedList=function(channelUrl,token,limit,cb){var url=APIClient.API_OPENCHANNELS_CHANNELURL_MUTE.replace("%s",channelUrl),params={token:encodeURIComponent(token),limit:String(limit)};requestGET(url,params,cb)},this.loadOpenChannelBanList=function(channelUrl,token,limit,cb){var url=APIClient.API_OPENCHANNELS_CHANNELURL_BAN.replace("%s",channelUrl),params={token:encodeURIComponent(token),limit:String(limit)};requestGET(url,params,cb)},this.setDoNotDisturb=function(userId,doNotDisturbOn,startHour,startMin,endHour,endMin,timezone,cb){var url=APIClient.API_USERS_USERID_PUSHPREFERENCE.replace("%s",encodeURIComponent(userId)),params={do_not_disturb:doNotDisturbOn,start_hour:startHour,start_min:startMin,end_hour:endHour,end_min:endMin,timezone:timezone};requestPUT(url,params,cb)},this.getDoNotDisturb=function(userId,cb){var url=APIClient.API_USERS_USERID_PUSHPREFERENCE.replace("%s",encodeURIComponent(userId));requestGET(url,cb)},this.setPushPreference=function(userId,channelUrl,value,cb){var url=APIClient.API_USERS_USERID_PUSHPREFERENCE_CHANNELURL.replace("%s",encodeURIComponent(userId)).replace("%s",encodeURIComponent(channelUrl)),params={};params.enable=value,requestPUT(url,params,cb)},this.getPushPreference=function(userId,channelUrl,cb){var url=APIClient.API_USERS_USERID_PUSHPREFERENCE_CHANNELURL.replace("%s",encodeURIComponent(userId)).replace("%s",encodeURIComponent(channelUrl));requestGET(url,cb)},this.registerGCMPushToken=function(userId,token,cb){var url=APIClient.API_USERS_USERID_PUSH_GCM.replace("%s",encodeURIComponent(userId)),params={gcm_reg_token:token};requestPOST(url,params,cb)},this.unregisterGCMPushToken=function(userId,token,cb){var url=APIClient.API_USERS_USERID_PUSH_GCM_TOKEN.replace("%s",encodeURIComponent(userId)).replace("%s",encodeURIComponent(token));requestDELETE(url,cb)},this.unregisterGCMPushTokenAll=function(userId,cb){var url=APIClient.API_USERS_USERID_PUSH_GCM.replace("%s",encodeURIComponent(userId));requestDELETE(url,cb)},this.registerAPNSPushToken=function(userId,token,cb){var url=APIClient.API_USERS_USERID_PUSH_APNS.replace("%s",encodeURIComponent(userId)),form={apns_device_token:token};requestPOST(url,form,cb)},this.unregisterAPNSPushToken=function(userId,token,cb){var url=APIClient.API_USERS_USERID_PUSH_APNS_TOKEN.replace("%s",encodeURIComponent(userId)).replace("%s",encodeURIComponent(token));requestDELETE(url,cb)},this.unregisterAPNSPushTokenAll=function(userId,cb){var url=APIClient.API_USERS_USERID_PUSH_APNS.replace("%s",encodeURIComponent(userId));requestDELETE(url,cb)},this.unregisterPushTokenAll=function(userId,cb){var url=APIClient.API_USERS_USERID_PUSH.replace("%s",encodeURIComponent(userId));requestDELETE(url,cb)},this.blockUser=function(blockerUserId,blockeeUserId,cb){var url=APIClient.API_USERS_USERID_BLOCK.replace("%s",encodeURIComponent(blockerUserId)),params={target_id:blockeeUserId};requestPOST(url,params,cb)},this.unblockUser=function(blockerUserId,blockeeUserId,cb){var url=APIClient.API_USERS_USERID_BLOCK_TARGETID.replace("%s",encodeURIComponent(blockerUserId)).replace("%s",encodeURIComponent(blockeeUserId));requestDELETE(url,{},cb)},this.banUser=function(channelUrl,userId,description,seconds,cb){var url=APIClient.API_OPENCHANNELS_CHANNELURL_BAN.replace("%s",encodeURIComponent(channelUrl)),params={user_id:userId};description&&(params.description=description),params.seconds=String(seconds),requestPOST(url,params,cb)},this.unbanUser=function(channelUrl,userId,cb){var url=APIClient.API_OPENCHANNELS_CHANNELURL_BAN_USERID.replace("%s",encodeURIComponent(channelUrl)).replace("%s",encodeURIComponent(userId));requestDELETE(url,{},cb)},this.muteUser=function(channelUrl,userId,cb){var url=APIClient.API_OPENCHANNELS_CHANNELURL_MUTE.replace("%s",encodeURIComponent(channelUrl)),params={user_id:userId};requestPOST(url,params,cb)},this.unmuteUser=function(channelUrl,userId,cb){var url=APIClient.API_OPENCHANNELS_CHANNELURL_MUTE_USERID.replace("%s",encodeURIComponent(channelUrl)).replace("%s",encodeURIComponent(userId));requestDELETE(url,{},cb)},this.deleteMessage=function(isOpenChannel,channelUrl,messageId,cb){var url="";url=isOpenChannel?APIClient.API_OPENCHANNELS_CHANNELURL_MESSAGES_MESSAGEID.replace("%s",encodeURIComponent(channelUrl)).replace("%s",encodeURIComponent(messageId)):APIClient.API_GROUPCHANNELS_CHANNELURL_MESSAGES_MESSAGEID.replace("%s",encodeURIComponent(channelUrl)).replace("%s",encodeURIComponent(messageId)),requestDELETE(url,{},cb)}},apiClientInstance=null;APIClient.getInstance=function(){return null===apiClientInstance?null:apiClientInstance},APIClient.API_VERSION="v3",APIClient.API_ROUTING_URL="https://api-p.sendbird.com/routing/%s",APIClient.API_USERS="/%v/users".replace("%v",APIClient.API_VERSION),APIClient.API_USERS_USERID_LOGIN="/%v/users/%s/login".replace("%v",APIClient.API_VERSION),APIClient.API_USERS_USERID="/%v/users/%s".replace("%v",APIClient.API_VERSION),APIClient.API_USERS_USERID_UNREADCOUNT="/%v/users/%s/unread_count".replace("%v",APIClient.API_VERSION),APIClient.API_USERS_USERID_MARKASREADALL="/%v/users/%s/mark_as_read_all".replace("%v",APIClient.API_VERSION),APIClient.API_USERS_USERID_PUSH_GCM_TOKEN="/%v/users/%s/push/gcm/%s".replace("%v",APIClient.API_VERSION),APIClient.API_USERS_USERID_PUSH_GCM="/%v/users/%s/push/gcm".replace("%v",APIClient.API_VERSION),APIClient.API_USERS_USERID_PUSHPREFERENCE_CHANNELURL="/%v/users/%s/push_preference/%s".replace("%v",APIClient.API_VERSION),APIClient.API_USERS_USERID_PUSHPREFERENCE="/%v/users/%s/push_preference/".replace("%v",APIClient.API_VERSION),APIClient.API_USERS_USERID_BLOCK="/%v/users/%s/block".replace("%v",APIClient.API_VERSION),APIClient.API_USERS_USERID_BLOCK_TARGETID="/%v/users/%s/block/%s".replace("%v",APIClient.API_VERSION),APIClient.API_USERS_USERID_PUSH_APNS_TOKEN="/%v/users/%s/push/apns/%s".replace("%v",APIClient.API_VERSION),APIClient.API_USERS_USERID_PUSH_APNS="/%v/users/%s/push/apns".replace("%v",APIClient.API_VERSION),APIClient.API_USERS_USERID_PUSH="/%v/users/%s/push".replace("%v",APIClient.API_VERSION),APIClient.API_OPENCHANNELS="/%v/open_channels".replace("%v",APIClient.API_VERSION),APIClient.API_OPENCHANNELS_CHANNELURL="/%v/open_channels/%s".replace("%v",APIClient.API_VERSION),APIClient.API_OPENCHANNELS_CHANNELURL_MESSAGES="/%v/open_channels/%s/messages".replace("%v",APIClient.API_VERSION),APIClient.API_OPENCHANNELS_CHANNELURL_MESSAGES_MESSAGEID="/%v/open_channels/%s/messages/%s".replace("%v",APIClient.API_VERSION),APIClient.API_OPENCHANNELS_CHANNELURL_PARTICIPANTS="/%v/open_channels/%s/participants".replace("%v",APIClient.API_VERSION),APIClient.API_OPENCHANNELS_CHANNELURL_METADATA="/%v/open_channels/%s/metadata".replace("%v",APIClient.API_VERSION),APIClient.API_OPENCHANNELS_CHANNELURL_METADATA_KEY="/%v/open_channels/%s/metadata/%s".replace("%v",APIClient.API_VERSION),APIClient.API_OPENCHANNELS_CHANNELURL_METACOUNTER="/%v/open_channels/%s/metacounter".replace("%v",APIClient.API_VERSION),APIClient.API_OPENCHANNELS_CHANNELURL_METACOUNTER_KEY="/%v/open_channels/%s/metacounter/%s".replace("%v",APIClient.API_VERSION),APIClient.API_OPENCHANNELS_CHANNELURL_BAN="/%v/open_channels/%s/ban".replace("%v",APIClient.API_VERSION),APIClient.API_OPENCHANNELS_CHANNELURL_BAN_USERID="/%v/open_channels/%s/ban/%s".replace("%v",APIClient.API_VERSION),APIClient.API_OPENCHANNELS_CHANNELURL_MUTE="/%v/open_channels/%s/mute".replace("%v",APIClient.API_VERSION),APIClient.API_OPENCHANNELS_CHANNELURL_MUTE_USERID="/%v/open_channels/%s/mute/%s".replace("%v",APIClient.API_VERSION),APIClient.API_GROUPCHANNELS="/%v/group_channels".replace("%v",APIClient.API_VERSION),APIClient.API_MYGROUPCHANNELS="/%v/users/%s/my_group_channels".replace("%v",APIClient.API_VERSION),APIClient.API_GROUPCHANNELS_CHANNELURL="/%v/group_channels/%s".replace("%v",APIClient.API_VERSION),APIClient.API_GROUPCHANNELS_CHANNELURL_INVITE="/%v/group_channels/%s/invite".replace("%v",APIClient.API_VERSION),APIClient.API_GROUPCHANNELS_CHANNELURL_HIDE="/%v/group_channels/%s/hide".replace("%v",APIClient.API_VERSION),APIClient.API_GROUPCHANNELS_CHANNELURL_LEAVE="/%v/group_channels/%s/leave".replace("%v",APIClient.API_VERSION),APIClient.API_GROUPCHANNELS_CHANNELURL_MESSAGES="/%v/group_channels/%s/messages".replace("%v",APIClient.API_VERSION),APIClient.API_GROUPCHANNELS_CHANNELURL_MESSAGES_MARKASREAD="/%v/group_channels/%s/messages/mark_as_read".replace("%v",APIClient.API_VERSION),APIClient.API_GROUPCHANNELS_CHANNELURL_MESSAGES_TOTALCOUNT="/%v/group_channels/%s/messages/total_count".replace("%v",APIClient.API_VERSION),APIClient.API_GROUPCHANNELS_CHANNELURL_MESSAGES_UNREADCOUNT="/%v/group_channels/%s/messages/unread_count".replace("%v",APIClient.API_VERSION),APIClient.API_GROUPCHANNELS_CHANNELURL_MESSAGES_MESSAGEID="/%v/group_channels/%s/messages/%s".replace("%v",APIClient.API_VERSION),APIClient.API_GROUPCHANNELS_CHANNELURL_MEMBERS="/%v/group_channels/%s/members".replace("%v",APIClient.API_VERSION),APIClient.API_GROUPCHANNELS_CHANNELURL_METADATA="/%v/group_channels/%s/metadata".replace("%v",APIClient.API_VERSION),APIClient.API_GROUPCHANNELS_CHANNELURL_METADATA_KEY="/%v/group_channels/%s/metadata/%s".replace("%v",APIClient.API_VERSION),APIClient.API_GROUPCHANNELS_CHANNELURL_METACOUNTER="/%v/group_channels/%s/metacounter".replace("%v",APIClient.API_VERSION),APIClient.API_GROUPCHANNELS_CHANNELURL_METACOUNTER_KEY="/%v/group_channels/%s/metacounter/%s".replace("%v",APIClient.API_VERSION),APIClient.API_STORAGE_FILE="/%v/storage/file".replace("%v",APIClient.API_VERSION),APIClient.API_STORAGE_PROFILE="/%v/storage/profile".replace("%v",APIClient.API_VERSION),APIClient.UPDATE_META_COUNTER_MODE_SET=0,APIClient.UPDATE_META_COUNTER_MODE_INC=1,APIClient.UPDATE_META_COUNTER_MODE_DEC=2;var SendBird=function(_initParams){var _singleton=SendBird.getInstance();if(_singleton)return _singleton;try{if(!_initParams.hasOwnProperty("appId"))return console.log("Must be set appId"),{}}catch(e){return console.log("Must be set appId"),{}}this.GCMPushToken="",this.APNSPushToken="",this.pushTokenRegistrationState={SUCCESS:"success",PENDING:"pending",ERROR:"error"},this.loginTimer,this.onLoginTimerCancel,this.globalTimer,this.reconnectTimer,this.onReconnectTimerCancel,this.currentUser=null,this.wsClient,this.connectionState={CONNECTING:"CONNECTING",OPEN:"OPEN",CLOSING:"CLOSING",CLOSED:"CLOSED"},this.ConnectionState=this.connectionState,this.OpenChannel=OpenChannel,this.GroupChannel=GroupChannel,this.UserMessage=UserMessage,this.channelHandlers={},this.connectionHandlers={};var ackStateMap={},CMD_ACK_TIMEOUT=1e4;appId=_initParams.appId,sendbirdInstance=this,apiClientInstance=APIClient.getInstance(),apiClientInstance||(apiClientInstance=new APIClient),this.ChannelHandler=function(){this.onMessageReceived=function(channel,message){},this.onMessageDeleted=function(channel,msgId){},this.onReadReceiptUpdated=function(channel){},this.onTypingStatusUpdated=function(channel){},this.onUserJoined=function(channel,user){},this.onUserLeft=function(channel,user){},this.onUserEntered=function(channel,user){},this.onUserExited=function(channel,user){},this.onUserMuted=function(channel,user){},this.onUserUnmuted=function(channel,user){},this.onUserBanned=function(channel,user){},this.onUserUnbanned=function(channel,user){},this.onChannelFrozen=function(channel){},this.onChannelUnfrozen=function(channel){},this.onChannelChanged=function(channel){},this.onChannelDeleted=function(channel){}},this.addChannelHandler=function(id,handler){SendBird.getInstance().channelHandlers[id]=handler},this.removeChannelHandler=function(id){delete SendBird.getInstance().channelHandlers[id]},this.removeAllChannelHandlers=function(){SendBird.getInstance().channelHandlers={}},this.ConnectionHandler=function(){this.onReconnectStarted=function(){},this.onReconnectSucceeded=function(){},this.onReconnectFailed=function(){}},this.addConnectionHandler=function(id,cb){SendBird.getInstance().connectionHandlers[id]=cb},this.removeConnectionHandler=function(id){delete SendBird.getInstance().connectionHandlers[id]},this.removeAllConnectionHandlers=function(){SendBird.getInstance().connectionHandlers={}},this.createUserListQuery=function(userIds){return userIds?new UserListQuery(UserListQuery.FILTERED_USER,userIds):new UserListQuery(UserListQuery.ALL_USER)},this.createBlockedUserListQuery=function(){return new UserListQuery(UserListQuery.BLOCKED_USER)},this.getApplicationId=function(){return appId},this.getDebugMode=function(){return DEBUG},this.setDebugMode=function(isDebug){DEBUG=isDebug},this.setDebugHostMode=function(isDebug){DEBUG_HOST=isDebug},this.setAPIHost=function(host){API_HOST=host},this.setWSHost=function(host){WS_HOST=host},this.getConnectionState=function(){if(!SendBird.getInstance())return this.connectionState.CLOSED;try{return SendBird.getInstance().wsClient?SendBird.getInstance().wsClient.getConnectionState():SendBird.getInstance().connectionState.CLOSED}catch(e){return SendBird.getInstance().connectionState.CLOSED}};var getAckInfo=function(requestId){return ackStateMap.hasOwnProperty(requestId)?ackStateMap[requestId]:null},messageReceived=function(message){var cmd=new Command(message);if(cmd.requestId){var ackInfo=getAckInfo(cmd.requestId);if(null==ackInfo)return;clearTimeout(ackInfo.timer);var cb=ackInfo.handler;if(cb)if("EROR"==cmd.command){var error=cmd.getJsonElement(),errCode=error.code,errMessage=error.message;cb(cmd,new SendBirdException(errMessage,errCode))}else cb(cmd,null)}else switch(cmd.command){case"LOGI":if(SendBird.getInstance().loginTimer)if(clearTimeout(SendBird.getInstance().loginTimer),SendBird.getInstance().loginTimer=null,SendBird.getInstance().onLoginTimerCancel=null,logiPayload=cmd.getJsonElement(),logiPayload.hasOwnProperty("error")){var errCode=logiPayload.code,errMessage=logiPayload.message;SendBird.getInstance().loginHandler(null,new SendBirdException(errMessage,errCode))}else logiPayload.hasOwnProperty("key")&&(APIClient.getInstance().sessionKey=logiPayload.key),logiPayload.hasOwnProperty("ekey")&&(APIClient.getInstance().ekey=logiPayload.ekey),logiPayload.hasOwnProperty("user_id")&&(SendBird.getInstance().currentUser=new User(logiPayload)),SendBird.getInstance().loginHandler(SendBird.getInstance().currentUser,null);break;case"MESG":case"FILE":case"BRDM":case"ADMM":var msg="",is_silent=!1;if("MESG"==cmd.command?msg=new UserMessage(cmd.getJsonElement()):"FILE"==cmd.command?msg=new FileMessage(cmd.getJsonElement()):(msg=new AdminMessage(cmd.getJsonElement()),cmd.getJsonElement().hasOwnProperty("silent")&&(is_silent=cmd.getJsonElement().silent)),!msg)return;msg.isGroupChannel()?GroupChannel.getChannel(msg.channelUrl,function(channel,error){if(error)return void(cb&&cb(null,error));if(!is_silent){channel.lastMessage=msg,msg.sender&&msg.sender.userId==SendBird.getInstance().currentUser.userId||channel.unreadMessageCount++;for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onChannelChanged(channel)}}for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onMessageReceived(channel,msg)}}):OpenChannel.getChannel(msg.channelUrl,function(channel,error){if(error)return void(cb&&cb(null,error));for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onMessageReceived(channel,msg)}});break;case"READ":var rst=new ReadStatus(cmd.getJsonElement());GroupChannel.getChannel(rst.channelUrl,function(channel,error){if(error)return void(cb&&cb(null,error));if(rst.reader.userId==SendBird.getInstance().currentUser.userId){if(channel.unreadMessageCount>0){channel.unreadMessageCount=0;for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onChannelChanged(channel)}}}else{channel.updateReadReceipt(rst.reader.userId,rst.timestamp);for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onReadReceiptUpdated(channel)}}});break;case"TPST":case"TPEN":break;case"MTIO":break;case"SYEV":processChannelEvent(cmd);break;case"DELM":var obj=cmd.getJsonElement(),channelType=String(obj.channel_type),channelUrl=String(obj.channel_url),msgId=String(obj.msg_id);switch(channelType){case BaseChannel.CHANNEL_TYPE_OPEN:OpenChannel.getChannel(channelUrl,function(channel,error){if(error)return void console.log("Discard a command.");for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onMessageDeleted(channel,msgId)}});break;case BaseChannel.CHANNEL_TYPE_GROUP:GroupChannel.getChannel(channelUrl,function(channel,error){if(error)return void console.log("Discard a command.");for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onMessageDeleted(channel,msgId)}})}break;case"LEAV":break;case"JOIN":break;case"PONG":}},processChannelEvent=function(cmd){var event=new ChannelEvent(cmd.getJsonElement());switch(event.category){case ChannelEvent.CATEGORY_CHANNEL_JOIN:case ChannelEvent.CATEGORY_CHANNEL_LEAVE:GroupChannel.getChannel(event.channelUrl,function(channel,error){if(error)return void console.log("Discard a command: "+cmd.command+":"+event.category);var user=new User(event.data);if(event.category==ChannelEvent.CATEGORY_CHANNEL_JOIN){channel.addMember(user);for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onUserJoined(channel,user)}}else{channel.removeMember(user);for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onUserLeft(channel,user)}}});break;case ChannelEvent.CATEGORY_TYPING_START:case ChannelEvent.CATEGORY_TYPING_END:GroupChannel.getChannel(event.channelUrl,function(channel,error){if(error)return void console.log("Discard a command: "+cmd.command+":"+event.category);var user=new User(event.data);event.category==ChannelEvent.CATEGORY_TYPING_START?channel.updateTypingStatus(user,!0):channel.updateTypingStatus(user,!1);for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onTypingStatusUpdated(channel)}});break;case ChannelEvent.CATEGORY_CHANNEL_ENTER:case ChannelEvent.CATEGORY_CHANNEL_EXIT:OpenChannel.getChannel(event.channelUrl,function(channel,error){if(error)return void console.log("Discard a command: "+cmd.command+":"+event.category);event.data.hasOwnProperty("participant_count")&&(channel.participantCount=event.data.participant_count);var user=new User(event.data);if(event.category==ChannelEvent.CATEGORY_CHANNEL_ENTER)for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onUserEntered(channel,user)}else for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onUserExited(channel,user)}});break;case ChannelEvent.CATEGORY_USER_CHANNEL_MUTE:case ChannelEvent.CATEGORY_USER_CHANNEL_UNMUTE:OpenChannel.getChannel(event.channelUrl,function(channel,error){if(error)return void console.log("Discard a command: "+cmd.command+":"+event.category);var user=new User(event.data);if(event.category==ChannelEvent.CATEGORY_USER_CHANNEL_MUTE)for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onUserMuted(channel,user)}else for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onUserUnmuted(channel,user)}});break;case ChannelEvent.CATEGORY_USER_CHANNEL_BAN:case ChannelEvent.CATEGORY_USER_CHANNEL_UNBAN:OpenChannel.getChannel(event.channelUrl,function(channel,error){if(error)return void console.log("Discard a command: "+cmd.command+":"+event.category);var user=new User(event.data);if(event.category==ChannelEvent.CATEGORY_USER_CHANNEL_BAN)for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onUserBanned(channel,user)}else for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onUserUnbanned(channel,user)}});break;case ChannelEvent.CATEGORY_CHANNEL_FREEZE:case ChannelEvent.CATEGORY_CHANNEL_UNFREEZE:OpenChannel.getChannel(event.channelUrl,function(channel,error){if(error)return void console.log("Discard a command: "+cmd.command+":"+event.category);if(event.category==ChannelEvent.CATEGORY_CHANNEL_FREEZE)for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onChannelFrozen(channel)}else for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onChannelUnfrozen(channel)}});break;case ChannelEvent.CATEGORY_CHANNEL_DELETED:if(event.isGroupChannel()){GroupChannel.removeCachedChannel(event.channelUrl);for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onChannelDeleted(event.channelUrl,"group")}}else{OpenChannel.removeCachedChannel(event.channelUrl);for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onChannelDeleted(event.channelUrl,"open")}}break;case ChannelEvent.CATEGORY_CHANNEL_PROP_CHANGED:event.isOpenChannel()?OpenChannel.getChannelWithoutCache(event.channelUrl,function(channel,error){if(error)return void console.log("Discard a command: "+cmd.command+":"+event.category);for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onChannelChanged(channel)}}):GroupChannel.getChannelWithoutCache(event.channelUrl,function(channel,error){if(error)return void console.log("Discard a command: "+cmd.command+":"+event.category);for(var i in SendBird.getInstance().channelHandlers){var handler=SendBird.getInstance().channelHandlers[i];handler.onChannelChanged(channel)}})}};this.connect=function(userId,accessToken,cb){"function"==typeof accessToken&&(cb=accessToken,accessToken=null),disconnectWithLogout(!0,null),connectWS(userId,accessToken,cb)};var isBackgroundMode=!1,notClosed=!1,enableStateChange=!0;this.setBackgroundState=function(){isBackgroundMode||(isBackgroundMode=!0,this.getConnectionState()!=this.connectionState.CLOSED?(notClosed=!0,disconnectWithLogout(!1,null)):notClosed=!1)},this.setForegroundState=function(){isBackgroundMode&&(isBackgroundMode=!1,notClosed&&this.currentUser&&(reconnectCount=0,reconnectWS(this.currentUser.userId,!0)))},this.disableStateChange=function(){enableStateChange=!1},this.enableStateChange=function(){enableStateChange=!0},this.disconnect=function(cb){disconnectWithLogout(!0,cb)},this.reconnect=function(){return!(!APIClient.getInstance().sessionKey||!this.currentUser)&&(shouldCallStarted=!0,reconnectCount>0&&(shouldCallStarted=!1),disconnectWithLogout(!1,null),reconnectCount=0,reconnectWS(this.currentUser.userId,shouldCallStarted),!0)};var disconnectWithLogout=function(isLogout,cb){if(SendBird.getInstance().loginTimer&&(clearTimeout(SendBird.getInstance().loginTimer),SendBird.getInstance().onLoginTimerCancel&&(SendBird.getInstance().onLoginTimerCancel(),SendBird.getInstance().onLoginTimerCancel=null),SendBird.getInstance().loginTimer=null),SendBird.getInstance().reconnectTimer&&(clearTimeout(SendBird.getInstance().reconnectTimer),SendBird.getInstance().onReconnectTimerCancel&&(SendBird.getInstance().onReconnectTimerCancel(),SendBird.getInstance().onReconnectTimerCancel=null),SendBird.getInstance().reconnectTimer=null),SendBird.getInstance().wsClient&&(reconnectCount=0,SendBird.getInstance().wsClient.disconnect(!0),SendBird.getInstance().wsClient=null),isLogout){OpenChannel.clearEnteredChannels(),OpenChannel.clearCache(),GroupChannel.clearCache(),SendBird.getInstance().globalTimer&&(clearTimeout(this.globalTimer),SendBird.getInstance().globalTimer=null);for(var reqId in SendBird.getInstance().ackStateMap)clearTimeout(SendBird.getInstance().ackStateMap[reqId].timer);SendBird.getInstance().ackStateMap={},SendBird.getInstance().currentUser=null,APIClient.getInstance().sessionKey=null,APIClient.getInstance().ekey=null}cb&&cb()},reconnectWS=function(userId,shouldCallStarted){if(SendBird.getInstance().reconnectTimer)DEBUG&&console.log("still reconnecting");else{if(reconnectCount+=1,reconnectCount<=1){if(shouldCallStarted)for(var i in SendBird.getInstance().connectionHandlers){var handler=SendBird.getInstance().connectionHandlers[i];handler.onReconnectStarted(i)}reconnectDelay=0}else reconnectDelay=reconnectFactor*Math.pow(2,reconnectCount-2);if(!userId||!APIClient.getInstance().sessionKey||reconnectCount>=6){disconnectWithLogout(!1,null),reconnectCount=0;for(var i in SendBird.getInstance().connectionHandlers){var handler=SendBird.getInstance().connectionHandlers[i];handler.onReconnectFailed(i)}return}SendBird.getInstance().onReconnectTimerCancel=function(){reconnectCount=0},SendBird.getInstance().reconnectTimer=setTimeout(function(){SendBird.getInstance().reconnectTimer=null,SendBird.getInstance().onReconnectTimerCancel=null,SendBird.getInstance().wsClient&&SendBird.getInstance().wsClient.disconnect(!0);var WSClientHandler=new WSClient.WSClientHandler;SendBird.getInstance().wsClient=new WSClient(WSClientHandler),SendBird.getInstance().loginHandler=function(user){reconnectCount=0;for(var i in OpenChannel.enteredChannels){var channel=OpenChannel.enteredChannels[i];channel.enter()}for(var i in SendBird.getInstance().connectionHandlers){var handler=SendBird.getInstance().connectionHandlers[i];handler.onReconnectSucceeded(i)}},WSClientHandler.onOpen=function(e){DEBUG&&console.log("reconnectWS onOpen"),SendBird.getInstance().loginTimer=setTimeout(function(){DEBUG&&console.log("reconnectWS loginTimer timedout"),SendBird.getInstance().loginTimer=null,reconnectWS(userId,!0)},CMD_ACK_TIMEOUT),SendBird.getInstance().onLoginTimerCancel=null},WSClientHandler.onMessage=function(message){messageReceived(message)},WSClientHandler.onError=function(message){DEBUG&&console.log("reconnectWS onError"),reconnectWS(userId,!0)},WSClientHandler.onClose=function(message){DEBUG&&console.log("reconnectWS onClose")};var API_HOST_OLD=API_HOST;APIClient.getInstance().checkRouting(function(result,error){return error?void reconnectWS(userId,!0):(API_HOST_OLD!=API_HOST&&_ajaxCall(API_HOST,{},"GET",{},function(){}),void SendBird.getInstance().wsClient.connect(userId,null,WS_HOST))})},reconnectDelay)}},connectWS=function(userId,accessToken,cb){var WSClientHandler=new WSClient.WSClientHandler;SendBird.getInstance().wsClient=new WSClient(WSClientHandler),WSClientHandler.onMessage=function(message){messageReceived(message)},SendBird.getInstance().loginHandler=function(user,sendbirdException){if(sendbirdException)SendBird.getInstance().disconnect(null),cb&&cb(null,sendbirdException);else{clearTimeout(SendBird.getInstance().globalTimer);var globalTimerLoop=function(){if(GroupChannel.cachedChannels)for(var i in GroupChannel.cachedChannels){var channel=GroupChannel.cachedChannels[i];if(channel.fireMarkAsRead(),channel.invalidateTypingStatus())for(var i2 in SendBird.getInstance().channelHandlers){ -var channelHandler=SendBird.getInstance().channelHandlers[i2];channelHandler.onTypingStatusUpdated(channel)}}SendBird.getInstance().globalTimer=setTimeout(function(){globalTimerLoop()},1e3)};globalTimerLoop(),cb&&cb(user,null)}},WSClientHandler.onOpen=function(e){SendBird.getInstance().loginTimer=setTimeout(function(){SendBird.getInstance().loginTimer=null,SendBird.getInstance().onLoginTimerCancel=null,SendBird.getInstance().disconnect(null),cb&&cb(null,new SendBirdException("Connection timeout.",SendBirdError.LOGIN_TIMEOUT))},CMD_ACK_TIMEOUT),SendBird.getInstance().onLoginTimerCancel=function(){cb&&cb(null,new SendBirdException("Connection Cancelled.",SendBirdError.REQUEST_FAILED))}},WSClientHandler.onError=function(error){DEBUG&&console.log("WSClientHandler.onError",error),APIClient.getInstance().sessionKey?reconnectWS(userId,!0):cb&&cb(null,new SendBirdException("Websocket connection failed.",SendBirdError.WEBSOCKET_CONNECTION_FAILED))},WSClientHandler.onClose=function(message){DEBUG&&console.log("WSClientHandler.onClose")},APIClient.getInstance().checkRouting(function(result,error){return error?void(cb&&cb(null,new SendBirdException("Connection routing failed.",SendBirdError.REQUEST_FAILED))):(_ajaxCall(API_HOST,{},"GET",{},function(){}),void SendBird.getInstance().wsClient.connect(userId,accessToken,WS_HOST))})};this.sendCommand=function(cmd,cb){if(null==SendBird.getInstance().wsClient||SendBird.getInstance().wsClient.getConnectionState()!=SendBird.getInstance().connectionState.OPEN)return void(cb&&cb(null,new SendBirdException("WS connection closed.",SendBirdError.WEBSOCKET_CONNECTION_CLOSED)));if(cmd.isAckRequired()){var reqId=cmd.requestId,obj={handler:cb,timer:setTimeout(function(){cb(null,new SendBirdException("Command received no ack.",SendBirdError.ACK_TIMEOUT)),delete ackStateMap[reqId]},CMD_ACK_TIMEOUT)};ackStateMap[reqId]=obj,SendBird.getInstance().wsClient.send(cmd,function(response,error){if(error)return clearTimeout(obj.timer),void cb(null,error)})}else SendBird.getInstance().wsClient.send(cmd,cb)},this.updateCurrentUserInfoWithProfileImage=function(nickname,profileImage,cb){var _SELF=this;return _SELF.currentUser?void(profileImage?APIClient.getInstance().uploadProfileImage(profileImage,function(response,error){if(error)return void(cb&&cb(error));var fileUrl=response.url;_SELF.updateCurrentUserInfo(nickname,fileUrl,cb)}):_SELF.updateCurrentUserInfo(nickname,null,cb)):void(cb&&cb(null,new SendBirdException("Connection must be made before you update user information.",SendBirdError.INVALID_INITIALIZATION)))},this.updateCurrentUserInfo=function(nickname,profileUrl,cb){var _SELF=this;return _SELF.currentUser?void APIClient.getInstance().updateUserInfo(_SELF.currentUser.userId,nickname,profileUrl,function(response,error){return error?void(cb&&cb(null,error)):(_SELF.currentUser&&(nickname&&(_SELF.currentUser.nickname=nickname),profileUrl&&(_SELF.currentUser.profileUrl=profileUrl)),void(cb&&cb()))}):void(cb&&cb(null,new SendBirdException("Connection must be made before you update user information.",SendBirdError.INVALID_INITIALIZATION)))},this.getPendingGCMToken=function(){return this.GCMPushToken},this.getPendingAPNSToken=function(){return this.APNSPushToken},this.registerGCMPushTokenForCurrentUser=function(gcmRegToken,cb){var _SELF=this;return gcmRegToken?this.currentUser?void APIClient.getInstance().registerGCMPushToken(this.currentUser.userId,gcmRegToken,function(response,error){return error?void(cb&&cb(_SELF.pushTokenRegistrationState.ERROR,error)):(_SELF.GCMPushToken="",void(cb&&cb(_SELF.pushTokenRegistrationState.SUCCESS)))}):(_SELF.GCMPushToken=gcmRegToken,void cb(_SELF.pushTokenRegistrationState.PENDING)):void cb(_SELF.pushTokenRegistrationState.ERROR,new SendBirdException("Invalid token",SendBirdError.INVALID_PARAMETER))},this.unregisterGCMPushTokenForCurrentUser=function(gcmRegToken,cb){return this.currentUser?gcmRegToken?void APIClient.getInstance().unregisterGCMPushToken(this.currentUser.userId,gcmRegToken,function(response,error){return error?void(cb&&cb(null,error)):void(cb&&cb())}):void cb(null,new SendBirdException("Invalid token",SendBirdError.INVALID_PARAMETER)):void cb(null,new SendBirdException("Connection must be made before you unregister push token.",SendBirdError.INVALID_INITIALIZATION))},this.unregisterGCMPushTokenAllForCurrentUser=function(cb){return this.currentUser?void APIClient.getInstance().unregisterGCMPushTokenAll(this.currentUser.userId,function(response,error){return error?void(cb&&cb(null,error)):void(cb&&cb())}):void cb(null,new SendBirdException("Connection must be made before you unregister push token.",SendBirdError.INVALID_INITIALIZATION))},this.registerAPNSPushTokenForCurrentUser=function(apnsRegToken,cb){var _SELF=this;return apnsRegToken?this.currentUser?void APIClient.getInstance().registerAPNSPushToken(this.currentUser.userId,apnsRegToken,function(response,error){return error?void(cb&&cb(_SELF.pushTokenRegistrationState.ERROR,error)):(_SELF.APNSPushToken="",void(cb&&cb(_SELF.pushTokenRegistrationState.SUCCESS)))}):(_SELF.APNSPushToken=apnsRegToken,void cb(_SELF.pushTokenRegistrationState.PENDING)):void cb(_SELF.pushTokenRegistrationState.ERROR,new SendBirdException("Invalid token",SendBirdError.INVALID_PARAMETER))},this.unregisterAPNSPushTokenForCurrentUser=function(apnsRegToken,cb){return this.currentUser?void APIClient.getInstance().unregisterAPNSPushToken(this.currentUser.userId,apnsRegToken,function(response,error){return error?void(cb&&cb(null,error)):void(cb&&cb())}):void cb(null,new SendBirdException("Connection must be made before you unregister push token.",SendBirdError.INVALID_INITIALIZATION))},this.unregisterAPNSPushTokenAllForCurrentUser=function(cb){return this.currentUser?void APIClient.getInstance().unregisterAPNSPushTokenAll(this.currentUser.userId,function(response,error){return error?void(cb&&cb(null,error)):void(cb&&cb())}):void cb(null,new SendBirdException("Connection must be made before you unregister push token.",SendBirdError.INVALID_INITIALIZATION))},this.unregisterPushTokenAllForCurrentUser=function(cb){return this.currentUser?void APIClient.getInstance().unregisterAPNSPushTokenAll(this.currentUser.userId,function(response,error){return error?void(cb&&cb(null,error)):void(cb&&cb())}):void cb(null,new SendBirdException("Connection must be made before you unregister push token.",SendBirdError.INVALID_INITIALIZATION))},this.setDoNotDisturb=function(doNotDisturbOn,startHour,startMin,endHour,endMin,timezone,cb){var _SELF=this;return this.currentUser?startHour<0||startHour>23||startMin<0||startMin>59||endHour<0||endHour>23||endMin<0||endMin>59?void(cb&&cb(null,new SendBirdException("Invalid arguments.",SendBirdError.INVALID_PARAMETER))):void APIClient.getInstance().setDoNotDisturb(_SELF.currentUser.userId,doNotDisturbOn,startHour,startMin,endHour,endMin,timezone,function(response,error){return error?void(cb&&cb(null,error)):void(cb&&cb())}):void(cb&&cb(null,new SendBirdException("Connection must be made before you set do-not-disturb.",SendBirdError.INVALID_INITIALIZATION)))},this.getDoNotDisturb=function(cb){var _SELF=this;return _SELF.currentUser?void APIClient.getInstance().getDoNotDisturb(_SELF.currentUser.userId,function(response,error){if(error)return void(cb&&cb(null,error));var data={doNotDisturbOn:response.do_not_disturb,startHour:response.start_hour,startMin:response.start_min,endHour:response.end_hour,endMin:response.end_min,timezone:response.timezone};cb&&cb(data)}):void(cb&&cb(null,new SendBirdException("Connection must be made before you get do-not-disturb setting.",SendBirdError.INVALID_INITIALIZATION)))},this.blockUser=function(userToBlock,cb){return this.currentUser&&this.currentUser.userId!=userToBlock.userId?void this.blockUserWithUserId(userToBlock.userId,cb):void(cb&&cb(null,new SendBirdException("Invalid operation.",SendBirdError.INVALID_INITIALIZATION)))},this.blockUserWithUserId=function(userIdToBlock,cb){return this.currentUser&&this.currentUser.userId!=userIdToBlock?void APIClient.getInstance().blockUser(this.currentUser.userId,userIdToBlock,function(response,error){return error?void(cb&&cb(null,error)):void(cb&&cb(new User(response)))}):void(cb&&cb(null,new SendBirdException("Invalid operation.",SendBirdError.INVALID_INITIALIZATION)))},this.unblockUser=function(blockedUser,cb){return this.currentUser?void this.unblockUserWithUserId(blockedUser.userId,cb):void(cb&&cb(null,new SendBirdException("Connection must be made before you unblock users.",SendBirdError.INVALID_INITIALIZATION)))},this.unblockUserWithUserId=function(blockedUserId,cb){return this.currentUser?void APIClient.getInstance().unblockUser(this.currentUser.userId,blockedUserId,function(response,error){return error?void(cb&&cb(null,error)):void(cb&&cb())}):void(cb&&cb(null,new SendBirdException("Connection must be made before you unblock users.",SendBirdError.INVALID_INITIALIZATION)))}},sendbirdInstance=null;return SendBird.getInstance=function(){return null===sendbirdInstance?null:sendbirdInstance},{SendBird:SendBird}}();return SendBirdObject.SendBird}); \ No newline at end of file + +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("axios"),require("form-data"),require("ws")):"function"==typeof define&&define.amd?define(["axios","form-data","ws"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).SendBird=t(e.axios,e.FormData,e.WebSocket)}(this,(function(e,t,n){"use strict";function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=r(e),s=r(t),a=r(n);function o(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function l(e){for(var t=1;te.length)&&(t=e.length);for(var n=0,r=new Array(t);n=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,a=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return a=e.done,e},e:function(e){o=!0,s=e},f:function(){try{a||null==n.return||n.return()}finally{if(o)throw s}}}}var T=function(){function e(){}return Object.defineProperty(e,"OS_VERSION",{get:function(){return"undefined"!=typeof navigator&&navigator.userAgent?navigator.userAgent.replace(/,/g,"."):"noAgent"},enumerable:!1,configurable:!0}),Object.defineProperty(e,"SDK_VERSION",{get:function(){return"3.1.33"},enumerable:!1,configurable:!0}),Object.defineProperty(e,"SDK_MAJOR_VERSION",{get:function(){return e.SDK_VERSION.split(".")[0]},enumerable:!1,configurable:!0}),Object.defineProperty(e,"DEFAULT_MAX_UNREAD_COUNT_OF_SUPER_GROUP_CHANNEL",{get:function(){return 100},enumerable:!1,configurable:!0}),Object.defineProperty(e,"INTERNAL_CALL",{get:function(){return"ic"},enumerable:!1,configurable:!0}),e}(),U={},O=function(){function e(e){this._container=e}return e.create=function(t,n){return U[t]=new e(n),U[t]},e.get=function(e){return e||(e=wi.getInstance()._iid),U[e]},Object.defineProperty(e.prototype,"container",{get:function(){return this._container},enumerable:!1,configurable:!0}),e.prototype.get=function(e){return this._container[e]},e.prototype.set=function(e,t){this._container[e]=t},e.prototype.remove=function(e){this._container.hasOwnProperty(e)&&delete this._container[e]},e}(),M=function(e,t){return M=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},M(e,t)};function k(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}M(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var R=function(){return R=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0&&i[i.length-1])||6!==s[0]&&2!==s[0])){a=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]1?o-1:0),u=1;u-1&&(q=t)}},{key:"supportedLogLevels",get:function(){return K}},{key:"logLevel",get:function(){return z[Q]},set:function(e){z.includes(e)||(e=Y),Q=z.indexOf(e)}},{key:"defaultLogLevel",get:function(){return Y}},{key:"isDisplayableLogLevel",value:function(e){var t=z.indexOf(e);return 0<=t&&t<=Q}},{key:"log",value:function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i0){var e=this._queue.shift();this.lock(e)}}}]),e}(),Z=function(){function e(t){c(this,e),this.sb=t,this.mutex=new X,this.pingTimer=null,this.pingTimeoutTimer=null}return h(e,[{key:"ping",value:function(){var e=this,t=x.get(this.sb._iid).Command.bPing(),n=O.get(this.sb._iid).container,r=n.wsAdapter,i=n.pongTimeout;r.client.send(t),J.debug("`PING`"),this.pingTimeoutTimer=setTimeout((function(){J.debug("`PING` timeout."),e.stop(),r.client.handler&&r.client.handler.onError()}),i)}},{key:"pong",value:function(){this.pingTimeoutTimer&&(clearTimeout(this.pingTimeoutTimer),this.pingTimeoutTimer=null)}},{key:"refreshTimer",value:function(){var e=this,t=O.get(this.sb._iid).container.pingInterval;this.mutex.lock((function(n){e.stop(),e.pingTimer=setInterval((function(){e.ping()}),t),n()}))}},{key:"start",value:function(){this.refreshTimer(),this.ping()}},{key:"stop",value:function(){this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=null),this.pingTimeoutTimer&&(clearTimeout(this.pingTimeoutTimer),this.pingTimeoutTimer=null)}}]),e}(),$=function(){return"undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"==navigator.product},ee=function(){return"undefined"==typeof window&&"undefined"!=typeof process&&("node"===process.title||void 0!==process.versions&&process.versions.node||"[object process]"===String(process))};!function(e){e.FILE="file",e.BLOB="blob",e.BLOB_LIKE_OBJECT="blobLikeObject",e.URL="url"}(D||(D={}));var te=function(){function e(){}var t;return e.isFileLikeObject=function(e){return"object"==typeof e&&null!==e&&e.hasOwnProperty("name")&&"string"==typeof e.name&&e.hasOwnProperty("uri")&&"string"==typeof e.uri&&e.hasOwnProperty("type")&&"string"==typeof e.type},t=e,e.convertFileToDataUrl=function(e){return new Promise((function(t,n){var r=new FileReader;r.onload=function(e){return t(r.result)},r.onerror=function(e){return n(r.error)},r.readAsDataURL(e)}))},e.convertFileToArrayBuffer=function(e){return new Promise((function(t,n){var r=new FileReader;r.onload=function(e){return t(r.result)},r.onerror=function(e){return n(r.error)},r.readAsArrayBuffer(e)}))},e.convertDataUrlToByteArray=function(e){for(var t=e.split(","),n=t[0].match(/:(.*?);/)[1],r=atob(t[1]),i=r.length,s=new Uint8Array(i);i--;)s[i]=r.charCodeAt(i);return[s,n]},e.convertDataURLtoFile=function(e,n){var r=t.convertDataUrlToByteArray(e),i=r[0],s=r[1];return new File([i],n,{type:s})},e.convertDataURLtoBlob=function(e){var n=t.convertDataUrlToByteArray(e),r=n[0],i=n[1];return new Blob([r],{type:i})},e.convertArrayBufferToFile=function(e,t){return new File([e],t)},e.isFile=function(e){return"undefined"!=typeof window&&"File"in window&&"undefined"!=typeof File&&e instanceof File},e.isBlob=function(e){return"undefined"!=typeof window&&"Blob"in window&&"undefined"!=typeof Blob&&e instanceof Blob},e.isFileTypeBlob=function(e){return e===D.BLOB||e===D.FILE},e.convertBlobToBuffer=function(n){return L(void 0,void 0,void 0,(function(){var r;return w(t,(function(t){switch(t.label){case 0:return[4,e.convertFileToArrayBuffer(n)];case 1:return r=t.sent(),[2,Buffer.from(r)]}}))}))},e}(),ne=[H.CONNECTION_REQUIRED,H.NETWORK_ERROR,H.ACK_TIMEOUT,H.WEBSOCKET_CONNECTION_CLOSED,H.WEBSOCKET_CONNECTION_FAILED,H.FILE_UPLOAD_CANCEL_FAILED,H.REQUEST_CANCELED,500901,500910,900200],re=[H.SESSION_TOKEN_EXPIRED,H.SESSION_TOKEN_REVOKED,H.USER_DEACTIVATED,H.NON_EXISTING_USER],ie=[H.WEBSOCKET_CONNECTION_CLOSED,H.WEBSOCKET_CONNECTION_FAILED],se=function(){function e(){}return e.deepEqual=function(e,t){if(e!==t){var n=R({},e),r=R({},t);return(!n.hasOwnProperty("messageId")||!r.hasOwnProperty("messageId")||n.messageId===r.messageId)&&((!n.hasOwnProperty("reqId")||!r.hasOwnProperty("reqId")||n.reqId===r.reqId)&&(n.hasOwnProperty("messageId")&&delete n.messageId,n.hasOwnProperty("reqId")&&delete n.reqId,r.hasOwnProperty("messageId")&&delete r.messageId,r.hasOwnProperty("reqId")&&delete r.reqId,JSON.stringify(n)===JSON.stringify(r)))}return!0},e.isResendableError=function(e){return e>0&&ne.indexOf(e)>=0},e.isAutoResendableError=function(e){return e>0&&ie.indexOf(e)>=0},e.isNonAutoReconnectableError=function(e){return e>0&&re.indexOf(e)>=0},e.isFile=function(e){var t=te.isFileLikeObject(e);return t||(ee()?"undefined"!=typeof Buffer&&e instanceof Buffer:"undefined"!=typeof Blob?e instanceof Blob:"undefined"!=typeof File&&e instanceof File)},e}(),ae=function(){function e(e){var t=this;this.fields={},e&&Object.keys(e).forEach((function(n){t.fields[n]={value:e[n]},se.isFile(e[n])&&(t.fields[n].filename=e[n].name)})),this.options={},this.internal=!1,this.upload={reqId:null,deleteRequest:null,progressHandler:null}}return e.prototype.add=function(e,t,n){void 0===n&&(n=null),this.fields[e]={value:t,filename:n}},e.prototype.remove=function(e){this.fields.hasOwnProperty(e)&&delete this.fields[e]},e.prototype.yield=function(){return L(this,void 0,void 0,(function(){var e,t,n,r,i,a,o,l,u,c,d,h,p=this;return w(this,(function(f){switch(f.label){case 0:for(e=!1,t=Object.keys(this.fields),n=0,r=t;n0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.noSessionKey,r=void 0!==n&&n,i=t.accessToken,a=void 0===i?null:i,o=e instanceof s.default&&"function"==typeof e.getHeaders?e.getHeaders():{},l=O.get(this.sb._iid),u=l.container,c=u.appId,d=u.auth,h=u.extensions,p=u.getUserAgentWithExtensions,f=wi.getAppVersion(),_="JS,".concat(T.OS_VERSION,",").concat(T.SDK_VERSION,",").concat(c);return f&&(_+=",".concat(f)),o.SendBird=_,o["SB-User-Agent"]=encodeURIComponent(p(h)),!r&&d.sessionKey&&(o["Session-Key"]=d.sessionKey),a&&(o["App-Id"]=c,o["Access-Token"]=a),o["Request-Sent-Timestamp"]=(new Date).getTime().toString(),e instanceof s.default&&$()&&(o["Content-Type"]="multipart/form-data"),o}},{key:"_createQuery",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};try{var n=[];return Object.keys(t).forEach((function(e){var r=t[e];if(null!=r){var i="";i="object"===u(r)?Array.isArray(r)?r.map((function(e){return encodeURIComponent("string"==typeof e?e.trim():e)})).join(","):encodeURIComponent(JSON.stringify(r)):encodeURIComponent(r),n.push("".concat(e,"=").concat(i))}})),n.length>0?"".concat(e,"?").concat(n.join("&")):e}catch(t){return J.debug("createWithEncodedGetParams is failed. - ",t),e}}},{key:"_request",value:function(e,t,n,r){var a=this;this.checkRouting((function(o,l){if(o)r(new H("Request failed.",H.REQUEST_FAILED),null);else{var u=a._buildUrl({apiHost:l.apiHost,url:t,params:n});(n?n.yield():Promise.resolve({})).then((function(o){var l=a._createHeader(o,n?n.options:{}),c=[{level:J.supportedLogLevels.DEBUG,messages:["url:",t]},{level:J.supportedLogLevels.DEBUG,messages:["data:",o]}],d=null;switch(e){case"GET":case"DELETE":d=a._createQuery(u,o);break;case"POST":case"PUT":d=u}var h=null;if(("undefined"==typeof ServiceWorker||"undefined"==typeof ServiceWorkerRegistration||"undefined"!=typeof ServiceWorkerContainer)&&"undefined"==typeof Worker||ee()||"function"!=typeof fetch)switch(e){case"GET":h=i.default.get(d,{headers:l,validateStatus:a._validateStatus});break;case"POST":var p={headers:l,validateStatus:a._validateStatus,onUploadProgress:function(e){n.upload.progressHandler&&n.upload.progressHandler(e,n.upload.reqId)}};if(o instanceof s.default){var f=null;"function"==typeof AbortController?(f=new AbortController,p.signal=f.signal):(f=i.default.CancelToken.source(),p.cancelToken=f.token);var _=a.cls.FileMessageQueue,g=n.upload.reqId;g&&(c.push({level:J.supportedLogLevels.DEBUG,messages:["request id:",g]}),_.uploadRequest[g]=f)}h=i.default.post(d,"function"==typeof o.getBuffer?o.getBuffer():o,p);break;case"PUT":h=i.default.put(d,o,{headers:l,validateStatus:a._validateStatus});break;case"DELETE":h=i.default.delete(d,{headers:l,validateStatus:a._validateStatus})}else{var y={method:e,headers:l};switch(e){case"GET":break;case"POST":if(o instanceof s.default){if("function"==typeof AbortController){var m=new AbortController,E=m.signal;y.signal=E;var v=a.cls.FileMessageQueue,b=n.upload.reqId;b&&(c.push({level:J.supportedLogLevels.DEBUG,messages:["request id:",b]}),v.uploadRequest[b]=m)}y.body="function"==typeof o.getBuffer?o.getBuffer():o}else l["Content-Type"]="application/json; charset=utf-8",y.body=JSON.stringify(o);break;case"PUT":o instanceof s.default?y.body="function"==typeof o.getBuffer?o.getBuffer():o:(l["Content-Type"]="application/json; charset=utf-8",y.body=JSON.stringify(o))}h=fetch(d,y).then((function(e){return e.json().then((function(t){if(!a._validateStatus(e.status))throw{request:{isAbort:!1},response:{data:t}};return Promise.resolve({data:t})}))}))}J.group("".concat(e," request"),c),c=[],h.then((function(t){try{var i=t.data;"POST"===e&&"function"==typeof n.upload.deleteRequest&&n.upload.deleteRequest(),c.push({level:J.supportedLogLevels.DEBUG,messages:["data:",i]}),r(null,i)}catch(e){throw{code:le,rawError:e}}})).catch((function(i){if(i.code===le)throw i.rawError;"POST"===e&&"function"==typeof n.upload.deleteRequest&&n.upload.deleteRequest();var s=a._handleError(i);if(c.push({level:J.supportedLogLevels.DEBUG,messages:["error:",s]}),t&&n)if(n.options&&n.options.isSessionRefresh)r(s,null);else{var o=O.get(a.sb._iid).container.sessionManager;o.isSessionError(s)?o.refreshSessionIfExpiredError(s).then((function(){return r(new H("Session is refreshed successfully.",H.SESSION_REFRESH_SUCCESS),null)})).catch((function(e){return r(new H("Session refresh failed.",H.SESSION_REFRESH_FAILED),null)})):r(s,null)}else r(s,null)})).finally((function(){return J.group("".concat(e," response"),c)}))}))}}))}},{key:"_validateStatus",value:function(e){return e>=200&&e<400}},{key:"_handleError",value:function(e){var t=e.request,n=e.response;if(t){if(t.isAbort||t.aborted)return new H("Request has been canceled.",H.REQUEST_CANCELED);if(n){var r=n.data,i=r?r.message:"Request failed.",s=r?r.code:H.REQUEST_FAILED;return new H(i,s)}return new H("Request failed.",H.REQUEST_FAILED)}return new H("There was a network error.",H.NETWORK_ERROR)}},{key:"get",value:function(e,t,n){this._request("GET",e,t,n)}},{key:"dummyCall",value:function(e){this._request("GET",null,null,e)}},{key:"post",value:function(e,t,n){this._request("POST",e,t,n)}},{key:"put",value:function(e,t,n){this._request("PUT",e,t,n)}},{key:"delete",value:function(e,t,n){this._request("DELETE",e,t,n)}},{key:"refreshSessionKey",value:function(t,n){var r=this,i=t.accessToken;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.USERS_USERID_SESSION_KEY.replace("%s",encodeURIComponent(s.userId)),o=new ae;o.add("expiring_session",!0),o.options.isSessionRefresh=!0,o.options.noSessionKey=!0,o.options.accessToken=i,r.post(a,o,n)}}))}},{key:"updateCurrentUserInfo",value:function(t,n){var r=this,i=t.nickname,s=t.profileUrl,a=t.profileImage,o=t.preferredLanguages;this.sb.ConnectionManager.ready((function(t,l){if(t)n(t,null);else{var u=e.Path.USERS_USERID.replace("%s",encodeURIComponent(l.userId)),c=new ae;i&&c.add("nickname",i),s&&c.add("profile_url",s),a&&c.add("profile_file",a,a.name),o&&c.add("preferred_languages",o),r.put(u,c,n)}}))}},{key:"getMyGroupChannelChangeLogs",value:function(t,n){var r=this;return oe(this.sb._iid,(function(n){var i=t.ts,s=t.token,a=t.customTypes,o=t.includeEmpty,l=t.includeFrozen;r.sb.ConnectionManager.ready((function(t,u){if(t)n(t,null);else{var c=e.Path.USERS_USERID_MY_GROUP_CHANNEL_CHANGELOGS.replace("%s",encodeURIComponent(u.userId)),d=new ae({show_read_receipt:!0,show_delivery_receipt:!0,show_member:!0});s&&d.add("token",s),i&&d.add("change_ts",i),a&&a.length>0&&d.add("custom_types",a),"boolean"==typeof o&&d.add("show_empty",o),"boolean"==typeof l&&d.add("show_frozen",l),r.get(c,d,n)}}))}),n)}},{key:"getChannelInvitationPreference",value:function(t,n){var r=this;this.sb.ConnectionManager.ready((function(t,i){if(t)n(t,null);else{var s=e.Path.USERS_USERID_GROUP_CHANNEL_INVITATION_PREFERENCE.replace("%s",encodeURIComponent(i.userId));r.get(s,null,n)}}))}},{key:"getGroupChannelCount",value:function(t,n){var r=this,i=t.memberStateFilter;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=r.cls.GroupChannel,o=e.Path.USERS_USERID_GROUP_CHANNEL_COUNT.replace("%s",encodeURIComponent(s.userId)),l="";switch(i){case a.MemberStateFilter.JOINED:l="joined";break;case a.MemberStateFilter.INVITED:l="invited";break;case a.MemberStateFilter.INVITED_BY_FRIEND:l="invited_by_friend";break;case a.MemberStateFilter.INVITED_BY_NON_FRIEND:l="invited_by_non_friend";break;case a.MemberStateFilter.LEFT:l="left";default:l="all"}var u=new ae({state:l});r.get(o,u,n)}}))}},{key:"getUnreadItemCount",value:function(t,n){var r=this,i=t.keys;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.USERS_USERID_UNREAD_ITEM_COUNT.replace("%s",encodeURIComponent(s.userId)),o=new ae({item_keys:i});r.get(a,o,n)}}))}},{key:"getTotalUnreadMessageCount",value:function(t,n){var r=this,i=t.customTypesFilter,s=t.superChannelFilter;this.sb.ConnectionManager.ready((function(t,a){if(t)n(t,null);else{var o=e.Path.USERS_USERID_UNREAD_MESSAGE_COUNT.replace("%s",encodeURIComponent(a.userId)),l=new ae({super_mode:s});null!==i&&i.length>0&&l.add("custom_types",i),r.get(o,l,n)}}))}},{key:"getTotalUnreadChannelCount",value:function(t,n){var r=this,i=t.customTypesFilter,s=t.superChannelFilter;this.sb.ConnectionManager.ready((function(t,a){if(t)n(t,null);else{var o=e.Path.USERS_USERID_UNREAD_CHANNEL_COUNT.replace("%s",encodeURIComponent(a.userId)),l=new ae({super_mode:s});null!==i&&i.length>0&&l.add("custom_types",i),r.get(o,l,n)}}))}},{key:"searchMessages",value:function(t,n){var r=this,i=t.keyword,s=t.limit,a=t.reverse,o=t.exactMatch,l=t.channelUrl,u=t.channelCustomType,c=t.messageTimestampFrom,d=t.messageTimestampTo,h=t.order,p=t.nextToken,f=t.advancedQuery,_=t.targetFields;this.sb.ConnectionManager.ready((function(t,g){if(t)n(t,null);else{var y=e.Path.SEARCH_MESSAGE,m=new ae({limit:s,reverse:a,query:i,custom_type:u});c&&m.add("message_ts_from",c),d&&m.add("message_ts_to",d),l&&m.add("channel_url",l),h&&m.add("sort_field",h),"boolean"==typeof o&&m.add("exact_match",o),null!==p&&p.length>0&&m.add("after",p),"boolean"==typeof f&&m.add("advanced_query",f),_&&Array.isArray(_)&&m.add("target_fields",_),r.get(y,m,n)}}))}},{key:"markAsReadAll",value:function(t,n){var r=this,i=t.channelUrls;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.USERS_USERID_MARKASREADALL.replace("%s",encodeURIComponent(s.userId)),o=new ae;i&&o.add("channel_urls",i),r.put(a,o,n)}}))}},{key:"markAsDelivered",value:function(t,n){var r=this,i=t.channelUrl,s=t.userId;this.sb.ConnectionManager.ready((function(t,a){if(t)n(t,null);else{var o=e.Path.GROUPCHANNELS_CHANNELURL_MESSAGES_MARKASDELIVERED.replace("%s",encodeURIComponent(i)),l=new ae;s&&l.add("user_id",s),r.put(o,l,n)}}))}},{key:"setChannelInvitationPreference",value:function(t,n){var r=this,i=t.isAutoAccept;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.USERS_USERID_GROUP_CHANNEL_INVITATION_PREFERENCE.replace("%s",encodeURIComponent(s.userId)),o=new ae({auto_accept:i});r.put(a,o,n)}}))}},{key:"blockUser",value:function(t,n){var r=this,i=t.blockedUserId;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.USERS_USERID_BLOCK.replace("%s",encodeURIComponent(s.userId)),o=new ae({target_id:i});r.post(a,o,n)}}))}},{key:"unblockUser",value:function(t,n){var r=this,i=t.unblockedUserId;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.USERS_USERID_BLOCK_TARGETID.replace("%s",encodeURIComponent(s.userId)).replace("%s",encodeURIComponent(i));r.delete(a,null,n)}}))}},{key:"getPushTriggerOption",value:function(t,n){var r=this;this.sb.ConnectionManager.ready((function(t,i){if(t)n(t,null);else{var s=e.Path.USERS_USERID_PUSHPREFERENCE.replace("%s",encodeURIComponent(i.userId));r.get(s,null,n)}}))}},{key:"setPushTriggerOption",value:function(t,n){var r=this,i=t.pushTriggerOption;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.USERS_USERID_PUSHPREFERENCE.replace("%s",encodeURIComponent(s.userId)),o=new ae({push_trigger_option:i});r.put(a,o,n)}}))}},{key:"getPushTokens",value:function(t,n){var r=this,i=t.ts,s=t.token,a=t.type;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=e.Path.USERS_USERID_PUSH_DEVICE_TOKENS.replace("%s",encodeURIComponent(o.userId)).replace("%s",encodeURIComponent(a)),u=new ae;s&&u.add("token",s),i&&u.add("created_ts",i),r.get(l,u,n)}}))}},{key:"getPushTemplate",value:function(t,n){var r=this;this.sb.ConnectionManager.ready((function(t,i){if(t)n(t,null);else{var s=e.Path.USERS_USERID_PUSH_TEMPLATE.replace("%s",encodeURIComponent(i.userId));r.get(s,null,n)}}))}},{key:"setPushTemplate",value:function(t,n){var r=this,i=t.templateName;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.USERS_USERID_PUSH_TEMPLATE.replace("%s",encodeURIComponent(s.userId)),o=new ae({name:i});r.put(a,o,n)}}))}},{key:"getDoNotDisturb",value:function(t,n){var r=this;this.sb.ConnectionManager.ready((function(t,i){if(t)n(t,null);else{var s=e.Path.USERS_USERID_PUSHPREFERENCE.replace("%s",encodeURIComponent(i.userId));r.get(s,null,n)}}))}},{key:"setDoNotDisturb",value:function(t,n){var r=this,i=t.doNotDisturbOn,s=t.startHour,a=t.startMin,o=t.endHour,l=t.endMin,u=t.timezone;this.sb.ConnectionManager.ready((function(t,c){if(t)n(t,null);else{var d=e.Path.USERS_USERID_PUSHPREFERENCE.replace("%s",encodeURIComponent(c.userId)),h=new ae({do_not_disturb:i,start_hour:s,start_min:a,end_hour:o,end_min:l,timezone:u});r.put(d,h,n)}}))}},{key:"getSnoozePeriod",value:function(t,n){var r=this;this.sb.ConnectionManager.ready((function(t,i){if(t)n(t,null);else{var s=e.Path.USERS_USERID_PUSHPREFERENCE.replace("%s",encodeURIComponent(i.userId));r.get(s,null,n)}}))}},{key:"setSnoozePeriod",value:function(t,n){var r=this,i=t.snoozeOn,s=t.startTs,a=t.endTs;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=e.Path.USERS_USERID_PUSHPREFERENCE.replace("%s",encodeURIComponent(o.userId)),u=new ae({snooze_enabled:i,snooze_start_ts:s,snooze_end_ts:a});r.put(l,u,n)}}))}},{key:"registerGCMPushToken",value:function(t,n){var r=this,i=t.token;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.USERS_USERID_PUSH_GCM.replace("%s",encodeURIComponent(s.userId)),o=new ae({gcm_reg_token:i,always_push:!0});r.post(a,o,n)}}))}},{key:"unregisterGCMPushToken",value:function(t,n){var r=this,i=t.token;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.USERS_USERID_PUSH_GCM_TOKEN.replace("%s",encodeURIComponent(s.userId)).replace("%s",encodeURIComponent(i));r.delete(a,null,n)}}))}},{key:"unregisterAllGCMPushTokens",value:function(t,n){var r=this;this.sb.ConnectionManager.ready((function(t,i){if(t)n(t,null);else{var s=e.Path.USERS_USERID_PUSH_GCM.replace("%s",encodeURIComponent(i.userId));r.delete(s,null,n)}}))}},{key:"registerAPNSPushToken",value:function(t,n){var r=this,i=t.token;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.USERS_USERID_PUSH_APNS.replace("%s",encodeURIComponent(s.userId)),o=new ae({apns_device_token:i,always_push:!0});r.post(a,o,n)}}))}},{key:"unregisterAPNSPushToken",value:function(t,n){var r=this,i=t.token;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.USERS_USERID_PUSH_APNS_TOKEN.replace("%s",encodeURIComponent(s.userId)).replace("%s",encodeURIComponent(i));r.delete(a,null,n)}}))}},{key:"unregisterAllAPNSPushTokens",value:function(t,n){var r=this;this.sb.ConnectionManager.ready((function(t,i){if(t)n(t,null);else{var s=e.Path.USERS_USERID_PUSH_APNS.replace("%s",encodeURIComponent(i.userId));r.delete(s,null,n)}}))}},{key:"unregisterAllPushTokens",value:function(t,n){var r=this;this.sb.ConnectionManager.ready((function(t,i){if(t)n(t,null);else{var s=e.Path.USERS_USERID_PUSH.replace("%s",encodeURIComponent(i.userId));r.delete(s,null,n)}}))}},{key:"loadFriendList",value:function(t,n){var r=this,i=t.token,s=t.limit;this.sb.ConnectionManager.ready((function(t,a){if(t)n(t,null);else{var o=e.Path.FRIENDS.replace("%s",encodeURIComponent(a.userId)),l=new ae({limit:s,token:i});r.get(o,l,n)}}))}},{key:"getFriendChangeLogsByToken",value:function(t,n){var r=this,i=t.token;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.FRIENDS_CHANGE_LOGS.replace("%s",encodeURIComponent(s.userId)),o=new ae;i&&o.add("token",i),r.get(a,o,n)}}))}},{key:"addFriends",value:function(t,n){var r=this,i=t.userIds;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.FRIENDS.replace("%s",encodeURIComponent(s.userId)),o=new ae({user_ids:i});r.post(a,o,n)}}))}},{key:"deleteFriends",value:function(t,n){var r=this,i=t.userIds;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.FRIENDS.replace("%s",encodeURIComponent(s.userId)),o=new ae({user_ids:i});r.delete(a,o,n)}}))}},{key:"uploadFriendDiscoveries",value:function(t,n){var r=this,i=t.discoveries;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.FRIENDS_DISCOVERIES.replace("%s",encodeURIComponent(s.userId)),o=[];i.forEach((function(e){o.push({friend_discovery_key:e.friendDiscoveryKey,friend_name:"string"==typeof e.friendName||e.friendName?e.friendName:null})}));var l=new ae({friend_discoveries:o});r.put(a,l,n)}}))}},{key:"deleteFriendDiscoveries",value:function(t,n){var r=this,i=t.discoveryKeys;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.FRIENDS_DISCOVERIES.replace("%s",encodeURIComponent(s.userId)),o=new ae({friend_discovery_keys:i});r.delete(a,o,n)}}))}},{key:"loadUserList",value:function(t,n){var r=this,i=t.token,s=t.limit,a=t.userIdsFilter,o=t.metaDataKeyFilter,l=t.metaDataValuesFilter,u=t.nicknameStartsWithFilter;this.sb.ConnectionManager.ready((function(t,c){if(t)n(t,null);else{var d=e.Path.USERS,h=new ae({token:i,limit:s});a&&a.length>0&&h.add("user_ids",a),o&&l&&l.length>0&&(h.add("metadatakey",o),h.add("metadatavalues_in",l)),u&&h.add("nickname_startswith",u),r.get(d,h,n)}}))}},{key:"loadBlockedUserList",value:function(t,n){var r=this,i=t.token,s=t.limit,a=t.userIdsFilter;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=e.Path.USERS_USERID_BLOCK.replace("%s",encodeURIComponent(o.userId)),u=new ae({token:i,limit:s});a&&a.length>0&&u.add("user_ids",a),r.get(l,u,n)}}))}},{key:"createUserMetaData",value:function(t,n){var r=this,i=t.metaData;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.USERS_USERID_METADATA.replace("%s",encodeURIComponent(s.userId)),o=new ae({metadata:i});r.post(a,o,n)}}))}},{key:"updateUserMetaData",value:function(t,n){var r=this,i=t.metaData,s=t.upsert;this.sb.ConnectionManager.ready((function(t,a){if(t)n(t,null);else{var o=e.Path.USERS_USERID_METADATA.replace("%s",encodeURIComponent(a.userId)),l=new ae({metadata:i,upsert:s});r.put(o,l,n)}}))}},{key:"deleteUserMetaData",value:function(t,n){var r=this,i=t.metaDataKey;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.USERS_USERID_METADATA_KEY.replace("%s",encodeURIComponent(s.userId)).replace("%s",encodeURIComponent(i));r.delete(a,null,n)}}))}},{key:"deleteAllUserMetaData",value:function(t,n){var r=this;this.sb.ConnectionManager.ready((function(t,i){if(t)n(t,null);else{var s=e.Path.USERS_USERID_METADATA.replace("%s",encodeURIComponent(i.userId));r.delete(s,null,n)}}))}},{key:"getMessageChangeLogs",value:function(t,n){var r=this;return oe(this.sb._iid,(function(n){var i=t.channelUrl,s=t.ts,a=t.timestamp,o=t.token,l=t.isOpenChannel,u=t.includeMetaArray,c=t.includeReaction,d=t.includeReactions,h=t.includeReplies,p=t.includeParentMessageText,f=t.includeThreadInfo,_=t.replyType,g=t.includeParentMessageInfo;r.sb.ConnectionManager.ready((function(t,y){if(t)n(t,null);else{var m=l?e.Path.OPENCHANNELS_CHANNELURL_MESSAGES_CHANGELOGS.replace("%s",encodeURIComponent(i)):e.Path.GROUPCHANNELS_CHANNELURL_MESSAGES_CHANGELOGS.replace("%s",encodeURIComponent(i)),E=new ae;o&&E.add("token",o),s&&E.add("change_ts",s),a&&E.add("change_ts",a),"boolean"==typeof u&&E.add("with_sorted_meta_array",u),"boolean"==typeof d?E.add("include_reactions",d):E.add("include_reactions","boolean"==typeof c&&c),"boolean"==typeof f&&E.add("include_thread_info",f),"string"==typeof _?E.add("include_reply_type",_):E.add("include_reply_type","boolean"==typeof h&&h?r.cls.BaseMessage.ReplyType.ALL:r.cls.BaseMessage.ReplyType.NONE),"boolean"==typeof g?E.add("include_parent_message_info",g):E.add("include_parent_message_info","boolean"==typeof p&&p),r.get(m,E,n)}}))}),n)}},{key:"getMyMutedInfo",value:function(t,n){var r=this,i=t.channelUrl,s=t.userId,a=t.isGroupChannel;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=a?e.Path.GROUPCHANNELS_CHANNELURL_MUTE_USERID.replace("%s",encodeURIComponent(i)).replace("%s",encodeURIComponent(s)):e.Path.OPENCHANNELS_CHANNELURL_MUTE_USERID.replace("%s",encodeURIComponent(i)).replace("%s",encodeURIComponent(s));r.get(l,null,n)}}))}},{key:"loadBannedUserList",value:function(t,n){var r=this,i=t.token,s=t.limit,a=t.channelUrl,o=t.isOpenChannel;this.sb.ConnectionManager.ready((function(t,l){if(t)n(t,null);else{var u=o?e.Path.OPENCHANNELS_CHANNELURL_BAN.replace("%s",encodeURIComponent(a)):e.Path.GROUPCHANNELS_CHANNELURL_BAN.replace("%s",encodeURIComponent(a)),c=new ae({token:i,limit:s});r.get(u,c,n)}}))}},{key:"loadMutedUserList",value:function(t,n){var r=this,i=t.token,s=t.limit,a=t.channelUrl,o=t.isOpenChannel;this.sb.ConnectionManager.ready((function(t,l){if(t)n(t,null);else{var u=o?e.Path.OPENCHANNELS_CHANNELURL_MUTE.replace("%s",encodeURIComponent(a)):e.Path.GROUPCHANNELS_CHANNELURL_MUTE.replace("%s",encodeURIComponent(a)),c=new ae({token:i,limit:s});r.get(u,c,n)}}))}},{key:"getMessageList",value:function(t,n){var r=this;return oe(this.sb._iid,(function(n){var i=t.channel,s=t.token,a=t.tokenType,o=t.isInclusive,l=t.prevResultSize,u=void 0===l?0:l,c=t.nextResultSize,d=void 0===c?0:c,h=t.shouldReverse,p=t.messageType,f=t.customType,_=t.customTypes,g=t.senderUserIds,y=t.includeMetaArray,m=t.includeReaction,E=t.includeReactions,v=t.includeReplies,b=t.includeParentMessageText,C=t.includeThreadInfo,A=t.replyType,N=t.includeParentMessageInfo,S=t.showSubchannelMessagesOnly,I=t.rootMessageId,T=t.parentMessageId;r.sb.ConnectionManager.ready((function(t,l){if(t)n(t,null);else{var c=i.isOpenChannel()?e.Path.OPENCHANNELS_CHANNELURL_MESSAGES.replace("%s",i.url):e.Path.GROUPCHANNELS_CHANNELURL_MESSAGES.replace("%s",i.url),U=new ae({is_sdk:String(!0),prev_limit:String(u),next_limit:String(d),include:String(o),reverse:String(h)});"timestamp"===a?U.add("message_ts",s):"messageId"===a&&U.add("message_id",String(s)),p&&U.add("message_type",String(p)),Array.isArray(_)&&(0===_.length&&("string"==typeof f?_.push(f):_.push("*")),U.add("custom_types",_)),Array.isArray(g)&&g.length>0&&U.add("sender_ids",g),"boolean"==typeof y&&U.add("with_sorted_meta_array",y),"boolean"==typeof E?U.add("include_reactions",E):U.add("include_reactions","boolean"==typeof m&&m),"boolean"==typeof C&&U.add("include_thread_info",C),"string"==typeof A?U.add("include_reply_type",A):U.add("include_reply_type","boolean"==typeof v&&v?r.cls.BaseMessage.ReplyType.ALL:r.cls.BaseMessage.ReplyType.NONE),"boolean"==typeof N?U.add("include_parent_message_info",N):U.add("include_parent_message_info","boolean"==typeof b&&b),"boolean"==typeof S&&i.isOpenChannel()&&U.add("show_subchannel_messages_only",S),I&&U.add("root_message_id",I),T&&U.add("parent_message_id",T),r.get(c,U,n)}}))}),n)}},{key:"checkMessageHugeGap",value:function(t,n){var r=this;return oe(this.sb._iid,(function(n){var i=t.channelUrl;t.channelType;var s=t.messageType,a=void 0===s?"":s,o=t.customTypes,l=void 0===o?["*"]:o,u=t.senderUserIds,c=void 0===u?[]:u,d=t.includeReactions,h=void 0===d||d,p=t.includeMetaArray,f=void 0!==p&&p,_=t.showSubchannelMessagesOnly,g=void 0!==_&&_,y=t.threshold,m=t.previous,E=t.next,v="".concat(e.Path.GROUPCHANNELS_CHANNELURL_MESSAGES_GAP.replace("%s",encodeURIComponent(i))),b=new ae({huge_gap_threshold:y,prev_start_ts:m.from,prev_end_ts:m.to,prev_cache_count:m.cachedCount,next_start_ts:E.from,next_end_ts:E.to,next_cache_count:E.cachedCount,reverse:!0,custom_types:l,message_type:a,include_reactions:h,with_sorted_meta_array:f,show_subchannel_messages_only:g});Array.isArray(c)&&c.length>0&&b.add("sender_ids",c),r.get(v,b,n)}),n)}},{key:"translateUserMessage",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel,a=t.messageId,o=t.translationTargetLanguages;this.sb.ConnectionManager.ready((function(t,l){if(t)n(t,null);else{var u=s?e.Path.OPENCHANNELS_CHANNELURL_MESSAGES_MESSAGEID_TRANSLATION.replace("%s",encodeURIComponent(i)).replace("%s",a):e.Path.GROUPCHANNELS_CHANNELURL_MESSAGES_MESSAGEID_TRANSLATION.replace("%s",encodeURIComponent(i)).replace("%s",a),c=new ae({target_langs:o});r.post(u,c,n)}}))}},{key:"getMessage",value:function(t,n){var r=this,i=t.channel,s=t.messageId,a=t.includeMetaArray,o=t.includeReactions,l=t.includeParentMessageText,u=t.includeThreadInfo,c=t.includeParentMessageInfo;this.sb.ConnectionManager.ready((function(t,d){if(t)n(t,null);else{var h=i.isOpenChannel()?e.Path.OPENCHANNELS_CHANNELURL_MESSAGES_MESSAGEID.replace("%s",encodeURIComponent(i.url)).replace("%s",encodeURIComponent(s)):e.Path.GROUPCHANNELS_CHANNELURL_MESSAGES_MESSAGEID.replace("%s",encodeURIComponent(i.url)).replace("%s",encodeURIComponent(s)),p=new ae({is_sdk:String(!0)});"boolean"==typeof a&&p.add("with_sorted_meta_array",a),"boolean"==typeof o&&p.add("include_reactions",o),"boolean"==typeof u&&p.add("include_thread_info",u),"boolean"==typeof c?p.add("include_parent_message_info",c):p.add("include_parent_message_info","boolean"==typeof l&&l),r.get(h,p,n)}}))}},{key:"deleteMessage",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel,a=t.messageId;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=s?e.Path.OPENCHANNELS_CHANNELURL_MESSAGES_MESSAGEID.replace("%s",encodeURIComponent(i)).replace("%s",encodeURIComponent(a)):e.Path.GROUPCHANNELS_CHANNELURL_MESSAGES_MESSAGEID.replace("%s",encodeURIComponent(i)).replace("%s",encodeURIComponent(a));r.delete(l,null,n)}}))}},{key:"muteUser",value:function(t,n){var r=this,i=t.channelUrl,s=t.userId,a=t.description,o=t.seconds,l=t.isGroupChannel;this.sb.ConnectionManager.ready((function(t,u){if(t)n(t,null);else{var c=l?e.Path.GROUPCHANNELS_CHANNELURL_MUTE.replace("%s",encodeURIComponent(i)):e.Path.OPENCHANNELS_CHANNELURL_MUTE.replace("%s",encodeURIComponent(i)),d=new ae({user_id:s});o&&(o>0||-1!==o)&&d.add("seconds",o),a&&d.add("description",a),r.post(c,d,n)}}))}},{key:"unmuteUser",value:function(t,n){var r=this,i=t.channelUrl,s=t.userId,a=t.isGroupChannel;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=a?e.Path.GROUPCHANNELS_CHANNELURL_MUTE_USERID.replace("%s",encodeURIComponent(i)).replace("%s",encodeURIComponent(s)):e.Path.OPENCHANNELS_CHANNELURL_MUTE_USERID.replace("%s",encodeURIComponent(i)).replace("%s",encodeURIComponent(s));r.delete(l,null,n)}}))}},{key:"banUser",value:function(t,n){var r=this,i=t.channelUrl,s=t.userId,a=t.description,o=t.seconds,l=t.isGroupChannel;this.sb.ConnectionManager.ready((function(t,u){if(t)n(t,null);else{var c=l?e.Path.GROUPCHANNELS_CHANNELURL_BAN.replace("%s",encodeURIComponent(i)):e.Path.OPENCHANNELS_CHANNELURL_BAN.replace("%s",encodeURIComponent(i)),d=new ae({user_id:s});a&&d.add("description",a),d.add("seconds",String(o)),r.post(c,d,n)}}))}},{key:"unbanUser",value:function(t,n){var r=this,i=t.channelUrl,s=t.userId,a=t.isGroupChannel;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=a?e.Path.GROUPCHANNELS_CHANNELURL_BAN_USERID.replace("%s",encodeURIComponent(i)).replace("%s",encodeURIComponent(s)):e.Path.OPENCHANNELS_CHANNELURL_BAN_USERID.replace("%s",encodeURIComponent(i)).replace("%s",encodeURIComponent(s));r.delete(l,null,n)}}))}},{key:"getMetaCounters",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel,a=t.keys;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=s?e.Path.OPENCHANNELS_CHANNELURL_METACOUNTER.replace("%s",encodeURIComponent(i)):e.Path.GROUPCHANNELS_CHANNELURL_METACOUNTER.replace("%s",encodeURIComponent(i)),u=new ae({keys:a});r.get(l,u,n)}}))}},{key:"createMetaCounters",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel,a=t.metaCounter;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=s?e.Path.OPENCHANNELS_CHANNELURL_METACOUNTER.replace("%s",encodeURIComponent(i)):e.Path.GROUPCHANNELS_CHANNELURL_METACOUNTER.replace("%s",encodeURIComponent(i)),u=new ae({metacounter:a});r.post(l,u,n)}}))}},{key:"updateMetaCounters",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel,a=t.metaCounter,o=t.upsert,l=t.mode;this.sb.ConnectionManager.ready((function(t,u){if(t)n(t,null);else{var c=s?e.Path.OPENCHANNELS_CHANNELURL_METACOUNTER.replace("%s",encodeURIComponent(i)):e.Path.GROUPCHANNELS_CHANNELURL_METACOUNTER.replace("%s",encodeURIComponent(i)),d=new ae({metacounter:a,upsert:o,mode:l});r.put(c,d,n)}}))}},{key:"deleteMetaCounter",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel,a=t.key;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=s?e.Path.OPENCHANNELS_CHANNELURL_METACOUNTER_KEY.replace("%s",encodeURIComponent(i)).replace("%s",a):e.Path.GROUPCHANNELS_CHANNELURL_METACOUNTER_KEY.replace("%s",encodeURIComponent(i)).replace("%s",a);r.delete(l,null,n)}}))}},{key:"deleteAllMetaCounters",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel;this.sb.ConnectionManager.ready((function(t,a){if(t)n(t,null);else{var o=s?e.Path.OPENCHANNELS_CHANNELURL_METACOUNTER.replace("%s",encodeURIComponent(i)):e.Path.GROUPCHANNELS_CHANNELURL_METACOUNTER.replace("%s",encodeURIComponent(i));r.delete(o,null,n)}}))}},{key:"getMetaData",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel,a=t.keys;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=s?e.Path.OPENCHANNELS_CHANNELURL_METADATA.replace("%s",encodeURIComponent(i)):e.Path.GROUPCHANNELS_CHANNELURL_METADATA.replace("%s",encodeURIComponent(i)),u=new ae({keys:a,include_ts:!0});r.get(l,u,n)}}))}},{key:"createMetaData",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel,a=t.metaData;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=s?e.Path.OPENCHANNELS_CHANNELURL_METADATA.replace("%s",encodeURIComponent(i)):e.Path.GROUPCHANNELS_CHANNELURL_METADATA.replace("%s",encodeURIComponent(i)),u=new ae({metadata:a,include_ts:!0});r.post(l,u,n)}}))}},{key:"updateMetaData",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel,a=t.metaData,o=t.upsert;this.sb.ConnectionManager.ready((function(t,l){if(t)n(t,null);else{var u=s?e.Path.OPENCHANNELS_CHANNELURL_METADATA.replace("%s",encodeURIComponent(i)):e.Path.GROUPCHANNELS_CHANNELURL_METADATA.replace("%s",encodeURIComponent(i)),c=new ae({metadata:a,upsert:o,include_ts:!0});r.put(u,c,n)}}))}},{key:"deleteMetaData",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel,a=t.key;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=s?e.Path.OPENCHANNELS_CHANNELURL_METADATA_KEY.replace("%s",encodeURIComponent(i)).replace("%s",a):e.Path.GROUPCHANNELS_CHANNELURL_METADATA_KEY.replace("%s",encodeURIComponent(i)).replace("%s",a),u=new ae({include_ts:!0});r.delete(l,u,n)}}))}},{key:"deleteAllMetaData",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel;this.sb.ConnectionManager.ready((function(t,a){if(t)n(t,null);else{var o=s?e.Path.OPENCHANNELS_CHANNELURL_METADATA.replace("%s",encodeURIComponent(i)):e.Path.GROUPCHANNELS_CHANNELURL_METADATA.replace("%s",encodeURIComponent(i)),l=new ae({include_ts:!0});r.delete(o,l,n)}}))}},{key:"loadOperatorList",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel,a=t.token,o=t.limit;this.sb.ConnectionManager.ready((function(t,l){if(t)n(t,null);else{var u=s?e.Path.OPENCHANNELS_OPERATORS.replace("%s",encodeURIComponent(i)):e.Path.GROUPCHANNELS_OPERATORS.replace("%s",encodeURIComponent(i)),c=new ae({token:a,limit:o});r.get(u,c,n)}}))}},{key:"getOpenChannel",value:function(t,n){var r=this,i=t.channelUrl,s=t.internalCall;this.sb.ConnectionManager.ready((function(t,a){if(t)n(t,null);else{var o=e.Path.OPENCHANNELS_CHANNELURL.replace("%s",encodeURIComponent(i)),l=new ae({});l.internal=s===T.INTERNAL_CALL,r.get(o,l,n)}}))}},{key:"loadOpenChannelList",value:function(t,n){var r=this,i=t.token,s=t.limit,a=t.nameKeyword,o=t.urlKeyword,l=t.customTypes,u=t.includeFrozen,c=t.includeMetaData;this.sb.ConnectionManager.ready((function(t,d){if(t)n(t,null);else{var h=e.Path.OPENCHANNELS,p=new ae({token:i,limit:s});a&&p.add("name_contains",a),o&&p.add("url_contains",o),l&&l.length>0&&p.add("custom_types",l),"boolean"==typeof u&&p.add("show_frozen",u),"boolean"==typeof c&&p.add("show_metadata",c),r.get(h,p,n)}}))}},{key:"loadParticipantList",value:function(t,n){var r=this,i=t.token,s=t.limit,a=t.channelUrl;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=e.Path.OPENCHANNELS_CHANNELURL_PARTICIPANTS.replace("%s",encodeURIComponent(a)),u=new ae({token:i,limit:s});r.get(l,u,n)}}))}},{key:"createOpenChannel",value:function(t,n){var r=this,i=t.name,s=t.coverUrlOrImage,a=t.data,o=t.operatorUserIds,l=t.customType,u=t.channelUrl;this.sb.ConnectionManager.ready((function(t,c){if(t)n(t,null);else{var d=e.Path.OPENCHANNELS,h=new ae;"string"==typeof s&&h.add("cover_url",s),se.isFile(s)&&h.add("cover_file",s),null!==u&&"string"==typeof u&&h.add("channel_url",u),null!==i&&"string"==typeof i&&h.add("name",i),a&&h.add("data",a),o&&(Array.isArray(o)?h.add("operators",o):h.add("operators",[o])),l&&h.add("custom_type",l),r.post(d,h,n)}}))}},{key:"updateOpenChannel",value:function(t,n){var r=this,i=t.channelUrl,s=t.name,a=t.coverUrlOrImage,o=t.data,l=t.operatorUserIds,u=t.customType;this.sb.ConnectionManager.ready((function(t,c){if(t)n(t,null);else{var d=e.Path.OPENCHANNELS_CHANNELURL.replace("%s",encodeURIComponent(i)),h=new ae;"string"==typeof a&&h.add("cover_url",a),se.isFile(a)&&h.add("cover_file",a,a.name),null!==s&&"string"==typeof s&&h.add("name",s),null!==o&&"string"==typeof o&&h.add("data",o),null!==l&&(Array.isArray(l)?h.add("operator_ids",l):h.add("operator_ids",[l])),null!==u&&"string"==typeof u&&h.add("custom_type",u),r.put(d,h,n)}}))}},{key:"deleteOpenChannel",value:function(t,n){var r=this,i=t.channelUrl;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.OPENCHANNELS_CHANNELURL.replace("%s",encodeURIComponent(i));r.delete(a,null,n)}}))}},{key:"getGroupChannel",value:function(t,n){var r=this,i=t.channelUrl,s=t.showMember,a=t.internalCall;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=e.Path.GROUPCHANNELS_CHANNELURL.replace("%s",encodeURIComponent(i)),u=new ae({show_member:s,show_read_receipt:!0,show_delivery_receipt:!0});u.internal=a===T.INTERNAL_CALL,r.get(l,u,n)}}))}},{key:"loadGroupChannelList",value:function(t,n){var r=this,i=t.token,s=t.limit,a=t.includeEmpty,o=t.order,l=t.userIdsFilter,u=t.nicknameContainsFilter,c=t.nicknameStartsWithFilter,d=t.nicknameExactMatchFilter,h=t.channelNameContainsFilter,p=t.channelUrlsFilter,f=t.customTypesFilter,_=t.customTypeStartsWithFilter,g=t.memberStateFilter,y=t.superChannelFilter,m=t.publicChannelFilter,E=t.unreadChannelFilter,v=t.metadataOrderKeyFilter,b=t.metadataKey,C=t.metadataValues,A=t.metadataValueStartsWith,N=t.hiddenChannelFilter,S=t.searchFilter,I=t.includeFrozen,T=t.includeMetaData;return oe(this.sb._iid,(function(t){r.sb.ConnectionManager.ready((function(n,U){if(n)t(n,null);else{var O=e.Path.MYGROUPCHANNELS.replace("%s",encodeURIComponent(U.userId)),M=new ae({token:i,limit:s,order:o,show_member:!0,show_read_receipt:!0,show_delivery_receipt:!0,show_empty:String(a),member_state_filter:g});f&&f.length>0&&M.add("custom_types",f),u&&M.add("members_nickname_contains",u),c&&M.add("members_nickname_startswith",c),d&&M.add("members_nickname",d),h&&M.add("name_contains",h),S&&S.hasOwnProperty("search_query")&&S.hasOwnProperty("search_fields")&&(M.add("search_query",S.search_query),M.add("search_fields",S.search_fields)),l&&l.userIds&&l.userIds.length>0&&(l.includeMode?(M.add("members_include_in",l.userIds),M.add("query_type",l.queryType.toUpperCase())):M.add("members_exactly_in",l.userIds)),p&&p.length>0&&M.add("channel_urls",p),M.add("super_mode",y),M.add("public_mode",m),M.add("unread_filter",E),v&&M.add("metadata_order_key",v),b&&M.add("metadata_key",b),C&&C.length>0&&M.add("metadata_values",C),A&&M.add("metadata_value_startswith",A),_&&M.add("custom_type_startswith",_),N&&M.add("hidden_mode",N),"boolean"==typeof I&&M.add("show_frozen",I),"boolean"==typeof T&&M.add("show_metadata",T),r.get(O,M,t)}}))}),n)}},{key:"loadPublicGroupChannelList",value:function(t,n){var r=this,i=t.token,s=t.limit,a=t.includeEmpty,o=t.order,l=t.channelNameContainsFilter,u=t.channelUrlsFilter,c=t.customTypesFilter,d=t.customTypeStartsWithFilter,h=t.superChannelFilter,p=t.membershipFilter,f=t.metadataOrderKeyFilter,_=t.metadataKey,g=t.metadataValues,y=t.metadataValueStartsWith,m=t.includeFrozen,E=t.includeMetaData;this.sb.ConnectionManager.ready((function(t,v){if(t)n(t,null);else{var b=r.cls.GroupChannel,C=e.Path.GROUPCHANNELS,A=new ae({token:i,limit:s,order:o,show_member:!0,show_read_receipt:!0,show_delivery_receipt:!0,show_empty:String(a),public_mode:b.PublicChannelFilter.PUBLIC,public_membership_mode:p});c&&c.length>0&&A.add("custom_types",c),l&&A.add("name_contains",l),u&&u.length>0&&A.add("channel_urls",u),A.add("super_mode",h),f&&A.add("metadata_order_key",f),_&&A.add("metadata_key",_),g&&g.length>0&&A.add("metadata_values",g),y&&A.add("metadata_value_startswith",y),d&&A.add("custom_type_startswith",d),"boolean"==typeof m&&A.add("show_frozen",m),"boolean"==typeof E&&A.add("show_metadata",E),r.get(C,A,n)}}))}},{key:"createGroupChannel",value:function(t,n){var r=this,i=t.isDistinct,s=t.isSuper,a=t.isBroadcast,o=t.isPublic,l=t.channelUrl,u=t.isDiscoverable,c=t.isStrict,d=t.name,h=t.data,p=t.customType,f=t.coverUrl,_=t.coverImage,g=t.accessCode,y=t.isEphemeral,m=t._invitedUserIds,E=void 0===m?[]:m,v=t.operatorUserIds,b=t.messageSurvivalSeconds;this.sb.ConnectionManager.ready((function(t,m){if(t)n(t,null);else{var C=e.Path.GROUPCHANNELS,N=new ae({user_ids:[m.userId].concat(A(E)).filter((function(e,t,n){return t===n.indexOf(e)}))});null!==f&&"string"==typeof f&&N.add("cover_url",f),se.isFile(_)&&N.add("cover_file",_,_.name),null!==l&&N.add("channel_url",l),null!==i&&N.add("is_distinct",i),null!==s&&N.add("is_super",s),null!==a&&N.add("is_broadcast",a),null!==o&&N.add("is_public",o),null!==u&&N.add("is_discoverable",u),null!==c&&N.add("strict",c),null!==y&&N.add("is_ephemeral",y),g&&N.add("access_code",g),null!==d&&"string"==typeof d&&N.add("name",d),h&&N.add("data",h),p&&N.add("custom_type",p),Array.isArray(v)&&v.length>0&&N.add("operator_ids",v),null!==b&&b>-1&&N.add("message_survival_seconds",b),r.post(C,N,n)}}))}},{key:"updateGroupChannel",value:function(t,n){var r=this,i=t.isDistinct,s=t.isPublic,a=t.channelUrl,o=t.isDiscoverable,l=t.name,u=t.data,c=t.customType,d=t.coverUrl,h=t.coverImage,p=t.accessCode,f=t.operatorUserIds,_=t.messageSurvivalSeconds;this.sb.ConnectionManager.ready((function(t,g){if(t)n(t,null);else{var y=e.Path.GROUPCHANNELS_CHANNELURL.replace("%s",encodeURIComponent(a)),m=new ae;null!==i&&m.add("is_distinct",i),null!==s&&m.add("is_public",s),null!==o&&m.add("is_discoverable",o),null!==p&&m.add("access_code",p),null!==d&&"string"==typeof d&&m.add("cover_url",d),se.isFile(h)&&m.add("cover_file",h,h.name),null!==l&&"string"==typeof l&&m.add("name",l),null!==u&&"string"==typeof u&&m.add("data",u),null!==c&&"string"==typeof c&&m.add("custom_type",c),null!==f&&(Array.isArray(f)?m.add("operator_ids",f):f&&m.add("operator_ids",[f])),null!==_&&_>-1&&m.add("message_survival_seconds",_),r.put(y,m,n)}}))}},{key:"addOperators",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel,a=void 0!==s&&s,o=t.operatorUserIds;this.sb.ConnectionManager.ready((function(t,s){if(!t){var l=(a?e.Path.OPENCHANNELS_CHANNELURL_OPERATORS:e.Path.GROUPCHANNELS_CHANNELURL_OPERATORS).replace("%s",encodeURIComponent(i)),u=new ae({operator_ids:o});r.post(l,u,n)}}))}},{key:"removeOperators",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel,a=void 0!==s&&s,o=t.operatorUserIds;this.sb.ConnectionManager.ready((function(t,s){if(!t){var l=(a?e.Path.OPENCHANNELS_CHANNELURL_OPERATORS:e.Path.GROUPCHANNELS_CHANNELURL_OPERATORS).replace("%s",encodeURIComponent(i)),u=new ae({operator_ids:o});r.delete(l,u,n)}}))}},{key:"inviteToGroupChannel",value:function(t,n){var r=this,i=t.channelUrl,s=t.userIds;this.sb.ConnectionManager.ready((function(t,a){if(t)n(t,null);else{var o=e.Path.GROUPCHANNELS_CHANNELURL_INVITE.replace("%s",encodeURIComponent(i)),l=new ae({user_ids:s});r.post(o,l,n)}}))}},{key:"acceptInvitation",value:function(t,n){var r=this,i=t.channelUrl,s=t.accessCode;this.sb.ConnectionManager.ready((function(t,a){if(t)n(t,null);else{var o=e.Path.GROUPCHANNELS_CHANNELURL_ACCEPT_INVITATION.replace("%s",encodeURIComponent(i)),l=new ae({user_id:a.userId});s&&l.add("access_code",s),r.put(o,l,n)}}))}},{key:"declineInvitation",value:function(t,n){var r=this,i=t.channelUrl;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.GROUPCHANNELS_CHANNELURL_DECLINE_INVITATION.replace("%s",encodeURIComponent(i)),o=new ae({user_id:s.userId});r.put(a,o,n)}}))}},{key:"joinGroupChannel",value:function(t,n){var r=this,i=t.channelUrl,s=t.accessCode;this.sb.ConnectionManager.ready((function(t,a){if(t)n(t,null);else{var o=e.Path.GROUPCHANNELS_CHANNELURL_JOIN.replace("%s",encodeURIComponent(i)),l=new ae({user_id:a.userId});s&&l.add("access_code",s),r.put(o,l,n)}}))}},{key:"leaveGroupChannel",value:function(t,n){var r=this,i=t.channelUrl;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.GROUPCHANNELS_CHANNELURL_LEAVE.replace("%s",encodeURIComponent(i)),o=new ae({user_id:s.userId});r.put(a,o,n)}}))}},{key:"hideGroupChannel",value:function(t,n){var r=this,i=t.channelUrl,s=t.hidePreviousMessages,a=t.allowAutoUnhide;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=e.Path.GROUPCHANNELS_CHANNELURL_HIDE.replace("%s",encodeURIComponent(i)),u=new ae({user_id:o.userId,hide_previous_messages:s,allow_auto_unhide:a});r.put(l,u,n)}}))}},{key:"unhideGroupChannel",value:function(t,n){var r=this,i=t.channelUrl;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.GROUPCHANNELS_CHANNELURL_HIDE.replace("%s",encodeURIComponent(i));r.delete(a,null,n)}}))}},{key:"freeze",value:function(t,n){var r=this,i=t.channelUrl,s=t.isGroupChannel,a=t.freezing;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=s?e.Path.GROUPCHANNELS_CHANNELURL_FREEZE.replace("%s",encodeURIComponent(i)):e.Path.OPENCHANNELS_CHANNELURL_FREEZE.replace("%s",encodeURIComponent(i)),u=new ae({freeze:a});r.put(l,u,n)}}))}},{key:"deleteGroupChannel",value:function(t,n){var r=this,i=t.channelUrl;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.GROUPCHANNELS_CHANNELURL.replace("%s",encodeURIComponent(i));r.delete(a,null,n)}}))}},{key:"loadMemberList",value:function(t,n){var r=this,i=t.channelUrl,s=t.token,a=t.limit,o=t.mutedMemberFilter,l=t.order,u=t.memberStateFilter,c=t.nicknameStartsWithFilter;this.sb.ConnectionManager.ready((function(t,d){if(t)n(t,null);else{var h=e.Path.GROUPCHANNELS_MEMBERS.replace("%s",encodeURIComponent(i)),p=new ae({token:s,limit:a,order:l.toLowerCase(),muted_member_filter:o.toLowerCase(),member_state_filter:u,show_member_is_muted:!0,show_read_receipt:!0,show_delivery_receipt:!0});c&&p.add("nickname_startswith",c),r.get(h,p,n)}}))}},{key:"report",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel,a=t.reportCategory,o=t.reportingUserId,l=t.reportDescription;this.sb.ConnectionManager.ready((function(t,u){if(t)n(t,null);else{var c=e.Path.REPORT_CHANNELS.replace("%s",encodeURIComponent(s?"open_channels":"group_channels")).replace("%s",encodeURIComponent(i)),d=new ae({report_category:a});null!=o&&d.add("reporting_user_id",o),null!=l&&d.add("report_description",l),r.post(c,d,n)}}))}},{key:"reportUser",value:function(t,n){var r=this,i=t.offendingUserId,s=t.channelUrl,a=t.isOpenChannel,o=t.reportCategory,l=t.reportingUserId,u=t.reportDescription;this.sb.ConnectionManager.ready((function(t,c){if(t)n(t,null);else{var d=e.Path.REPORT_USERS.replace("%s",encodeURIComponent(i)),h=new ae({channel_url:s,channel_type:a?"open_channels":"group_channels",report_category:o});null!=l&&h.add("reporting_user_id",l),null!=u&&h.add("report_description",u),r.post(d,h,n)}}))}},{key:"reportMessage",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel,a=t.messageId,o=t.reportCategory,l=t.reportingUserId,u=t.reportDescription,c=t.offendingUserId;this.sb.ConnectionManager.ready((function(t,d){if(t)n(t,null);else{var h=e.Path.REPORT_MESSAGES.replace("%s",encodeURIComponent(s?"open_channels":"group_channels")).replace("%s",encodeURIComponent(i)).replace("%s",encodeURIComponent(a)),p=new ae({report_category:o,offending_user_id:c});null!=l&&p.add("reporting_user_id",l),null!=u&&p.add("report_description",u),r.post(h,p,n)}}))}},{key:"sendUserMessage",value:function(t,n){var r=this,i=t.channelUrl,s=t.isOpenChannel,a=t.message,o=t.data,l=t.customType,u=t.translationTargetLanguages,c=t.metaArrays,d=t.mentionType,h=t.mentionedUserIds,p=t.mentionedMessageTemplate,f=t.pushNotificationDeliveryOption,_=t.rootMessageId,g=t.parentMessageId,y=t.appleCriticalAlertOptions,m=t.isReplyToChannel;this.sb.ConnectionManager.ready((function(t,E){if(t)n(t,null);else{var v=r.cls.FileMessageParams,b=s?e.Path.OPENCHANNELS_CHANNELURL_MESSAGES.replace("%s",encodeURIComponent(i)):e.Path.GROUPCHANNELS_CHANNELURL_MESSAGES.replace("%s",encodeURIComponent(i)),C=new ae({message_type:"MESG",user_id:E.userId,message:a,mention_type:d,mentioned_user_ids:[]});null!=o&&C.add("data",o),null!=l&&C.add("custom_type",l),u&&C.add("translation_target_langs",u),c&&c.length>0&&C.add("sorted_metaarray",c.map((function(e){return e.encode()}))),d===r.cls.BaseMessageParams.MentionType.CHANNEL?C.add("mentioned_user_ids",[]):Array.isArray(h)&&h.length>0&&C.add("mentioned_user_ids",h),p&&C.add("mentioned_message_template",p),f&&f!==v.PushNotificationDeliveryOption.DEFAULT&&C.add("push_option",f),_&&C.add("root_message_id",_),g&&C.add("parent_message_id",g),y&&C.add("apple_critical_alert_options",y.serialize()),m&&C.add("reply_to_channel",m),r.post(b,C,n)}}))}},{key:"sendFileMessage",value:function(t,n){var r=this,i=t.reqId,s=t.channelUrl,a=t.isOpenChannel,o=t.fileUrl,l=t.fileName,u=t.fileSize,c=t.fileType,d=t.data,h=t.customType,p=t.thumbnailSizes,f=t.requireAuth,_=t.metaArrays,g=t.mentionType,y=t.mentionedUserIds,m=t.pushNotificationDeliveryOption,E=t.rootMessageId,v=t.parentMessageId,b=t.appleCriticalAlertOptions,C=t.isReplyToChannel;this.sb.ConnectionManager.ready((function(t,A){if(t)n(t,null);else{var N=r.cls.FileMessageParams,S=a?e.Path.OPENCHANNELS_CHANNELURL_MESSAGES.replace("%s",encodeURIComponent(s)):e.Path.GROUPCHANNELS_CHANNELURL_MESSAGES.replace("%s",encodeURIComponent(s)),I=new ae({message_type:"FILE",user_id:A.userId,url:o,mention_type:g,mentioned_user_ids:[],req_id:i});null!=l&&I.add("file_name",l),null!=u&&I.add("file_size",u),null!=c&&I.add("file_type",c),null!=d&&I.add("custom_field",d),null!=h&&I.add("custom_type",h),p&&I.add("thumbnails",p),f&&I.add("require_auth",f),_&&_.length>0&&I.add("sorted_metaarray",_.map((function(e){return e.encode()}))),g===r.cls.BaseMessageParams.MentionType.CHANNEL?I.add("mentioned_user_ids",[]):Array.isArray(y)&&y.length>0&&I.add("mentioned_user_ids",y),m&&m!==N.PushNotificationDeliveryOption.DEFAULT&&I.add("push_option",m),E&&I.add("root_message_id",E),v&&I.add("parent_message_id",v),b&&I.add("apple_critical_alert_options",b.serialize()),C&&I.add("reply_to_channel",C),r.post(S,I,n)}}))}},{key:"uploadFile",value:function(t,n){var r=this,i=t.file,s=t.thumbnailSizes,a=t.channelUrl,o=t.progressHandler,l=t.reqId;this.sb.ConnectionManager.ready((function(t,u){if(t)n(t,null);else{var c=O.get(r.sb._iid).container.appInfo;if(c)if("number"==typeof i.size||i.size||(i.size=0),"number"==typeof i.size)if(i.size<=c.uploadSizeLimit){var d=e.Path.STORAGE_FILE,h=new ae;if(h.add("file",i,i.name),a&&"string"==typeof a&&h.add("channel_url",a),s)for(var p=0;p0&&u.add("metaarray",i.metaArrayKeys),i.mentionType&&u.add("mention_type",i._mentionType),i._mentionType===r.cls.BaseMessageParams.MentionType.CHANNEL?u.add("mentioned_user_ids",[]):Array.isArray(i._mentionedUserIds)&&i._mentionedUserIds.length>0&&u.add("mentioned_user_ids",i._mentionedUserIds),i.translationTargetLanguages&&i.translationTargetLanguages.length>0&&u.add("translation_target_langs",i.translationTargetLanguages),i.pushNotificationDeliveryOption&&i.pushNotificationDeliveryOption!==r.cls.BaseMessageParams.PushNotificationDeliveryOption.DEFAULT&&u.add("push_option",i.pushNotificationDeliveryOption),i.appleCriticalAlertOptions&&u.add("apple_critical_alert_options",i.appleCriticalAlertOptions.serialize()),r.post(l,u,n)}}))}},{key:"getMyPushTriggerOption",value:function(t,n){var r=this,i=t.channelUrl;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.USERS_USERID_PUSHPREFERENCE_CHANNELURL.replace("%s",encodeURIComponent(s.userId)).replace("%s",encodeURIComponent(i));r.get(a,null,n)}}))}},{key:"setMyPushTriggerOption",value:function(t,n){var r=this,i=t.channelUrl,s=t.pushTriggerOption,a=t.enable;this.sb.ConnectionManager.ready((function(t,o){if(t)n(t,null);else{var l=e.Path.USERS_USERID_PUSHPREFERENCE_CHANNELURL.replace("%s",encodeURIComponent(o.userId)).replace("%s",encodeURIComponent(i)),u=new ae;s&&u.add("push_trigger_option",s),"boolean"==typeof a&&u.add("enable",a),r.put(l,u,n)}}))}},{key:"setMyCountPreference",value:function(t,n){var r=this,i=t.channelUrl,s=t.countPreference;this.sb.ConnectionManager.ready((function(t,a){if(t)n(t,null);else{var o=e.Path.USERS_COUNT_PREFERENCE.replace("%s",encodeURIComponent(a.userId)).replace("%s",encodeURIComponent(i)),l=new ae({count_preference:s});r.put(o,l,n)}}))}},{key:"resetMyHistory",value:function(t,n){var r=this,i=t.channelUrl;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.GROUPCHANNELS_RESET_USER_HISTORY.replace("%s",encodeURIComponent(i));r.put(a,null,n)}}))}},{key:"addReaction",value:function(t,n){var r=this,i=t.isGroupChannel,s=t.channelUrl,a=t.messageId,o=t.key;this.sb.ConnectionManager.ready((function(t,l){if(t)n(t,null);else{var u=i?e.Path.GROUPCHANNELS_CHANNELURL_MESSAGES_MESSAGEID_REACTION.replace("%s",encodeURIComponent(s)).replace("%s",encodeURIComponent(a)):e.Path.OPENCHANNELS_CHANNELURL_MESSAGES_MESSAGEID_REACTION.replace("%s",encodeURIComponent(s)).replace("%s",encodeURIComponent(a)),c=new ae({reaction:o});r.post(u,c,n)}}))}},{key:"deleteReaction",value:function(t,n){var r=this,i=t.isGroupChannel,s=t.channelUrl,a=t.messageId,o=t.key;this.sb.ConnectionManager.ready((function(t,l){if(t)n(t,null);else{var u=i?e.Path.GROUPCHANNELS_CHANNELURL_MESSAGES_MESSAGEID_REACTION.replace("%s",encodeURIComponent(s)).replace("%s",encodeURIComponent(a)):e.Path.OPENCHANNELS_CHANNELURL_MESSAGES_MESSAGEID_REACTION.replace("%s",encodeURIComponent(s)).replace("%s",encodeURIComponent(a)),c=new ae({reaction:o});r.delete(u,c,n)}}))}},{key:"getAllEmoji",value:function(t){var n=this;this.sb.ConnectionManager.ready((function(r,i){r?t(r,null):n.get(e.Path.EMOJI_CATEGORIES,null,t)}))}},{key:"getEmojiCategory",value:function(t,n){var r=this,i=t.categoryId;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.EMOJI_CATEGORIES_CATEGORYID.replace("%s",i);r.get(a,null,n)}}))}},{key:"getEmoji",value:function(t,n){var r=this,i=t.emojiKey;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.EMOJIS_EMOJIKEY.replace("%s",i);r.get(a,null,n)}}))}},{key:"getAllowFriendDiscovery",value:function(t){var n=this;this.sb.ConnectionManager.ready((function(r,i){if(r)t(r,null);else{var s=e.Path.USERS_USERID_ALLOW_FRIEND_DISCOVERY.replace("%s",encodeURIComponent(i.userId));n.get(s,null,t)}}))}},{key:"setAllowFriendDiscovery",value:function(t,n){var r=this,i=t.allowFriendDiscovery;this.sb.ConnectionManager.ready((function(t,s){if(t)n(t,null);else{var a=e.Path.USERS_USERID_ALLOW_FRIEND_DISCOVERY.replace("%s",encodeURIComponent(s.userId)),o=new ae;"boolean"==typeof i&&o.add("allow_friend_discovery",i),r.put(a,o,n)}}))}}],[{key:"Path",get:function(){return{USERS:"/users",USERS_USERID:"/users/%s",USERS_USERID_LOGIN:"/users/%s/login",USERS_USERID_SESSION_KEY:"/users/%s/session_key",USERS_USERID_METADATA:"/users/%s/metadata",USERS_USERID_METADATA_KEY:"/users/%s/metadata/%s",USERS_USERID_MARKASREADALL:"/users/%s/mark_as_read_all",USERS_USERID_MY_GROUP_CHANNEL_CHANGELOGS:"/users/%s/my_group_channels/changelogs",USERS_USERID_UNREAD_ITEM_COUNT:"/users/%s/unread_item_count",USERS_USERID_UNREAD_MESSAGE_COUNT:"/users/%s/unread_message_count",USERS_USERID_UNREAD_CHANNEL_COUNT:"/users/%s/unread_channel_count",USERS_USERID_PUSH_GCM_TOKEN:"/users/%s/push/gcm/%s",USERS_USERID_PUSH_GCM:"/users/%s/push/gcm",USERS_USERID_PUSH_DEVICE_TOKENS:"/users/%s/push/%s/device_tokens",USERS_USERID_PUSHPREFERENCE_CHANNELURL:"/users/%s/push_preference/%s",USERS_USERID_PUSHPREFERENCE:"/users/%s/push_preference/",USERS_USERID_PUSH_TEMPLATE:"/users/%s/push/template",USERS_USERID_BLOCK:"/users/%s/block",USERS_USERID_BLOCK_TARGETID:"/users/%s/block/%s",USERS_USERID_PUSH_APNS_TOKEN:"/users/%s/push/apns/%s",USERS_USERID_PUSH_APNS:"/users/%s/push/apns",USERS_USERID_PUSH:"/users/%s/push",USERS_USERID_GROUP_CHANNEL_INVITATION_PREFERENCE:"/users/%s/channel_invitation_preference",USERS_USERID_GROUP_CHANNEL_COUNT:"/users/%s/group_channel_count",USERS_COUNT_PREFERENCE:"/users/%s/count_preference/%s",USERS_USERID_ALLOW_FRIEND_DISCOVERY:"/users/%s/allow_friend_discovery",OPENCHANNELS:"/open_channels",OPENCHANNELS_CHANNELURL:"/open_channels/%s",OPENCHANNELS_CHANNELURL_MESSAGES:"/open_channels/%s/messages",OPENCHANNELS_CHANNELURL_MESSAGES_MESSAGEID:"/open_channels/%s/messages/%s",OPENCHANNELS_CHANNELURL_MESSAGES_MESSAGEID_TRANSLATION:"/open_channels/%s/messages/%s/translation",OPENCHANNELS_CHANNELURL_MESSAGES_CHANGELOGS:"/open_channels/%s/messages/changelogs",OPENCHANNELS_CHANNELURL_SCHEDULED_MESSAGES:"/open_channels/%s/scheduled_messages",OPENCHANNELS_CHANNELURL_PARTICIPANTS:"/open_channels/%s/participants",OPENCHANNELS_CHANNELURL_OPERATORS:"/open_channels/%s/operators",OPENCHANNELS_CHANNELURL_METADATA:"/open_channels/%s/metadata",OPENCHANNELS_CHANNELURL_METADATA_KEY:"/open_channels/%s/metadata/%s",OPENCHANNELS_CHANNELURL_METACOUNTER:"/open_channels/%s/metacounter",OPENCHANNELS_CHANNELURL_METACOUNTER_KEY:"/open_channels/%s/metacounter/%s",OPENCHANNELS_CHANNELURL_BAN:"/open_channels/%s/ban",OPENCHANNELS_CHANNELURL_BAN_USERID:"/open_channels/%s/ban/%s",OPENCHANNELS_CHANNELURL_MUTE:"/open_channels/%s/mute",OPENCHANNELS_CHANNELURL_MUTE_USERID:"/open_channels/%s/mute/%s",OPENCHANNELS_CHANNELURL_FREEZE:"/open_channels/%s/freeze",OPENCHANNELS_OPERATORS:"/open_channels/%s/operators",OPENCHANNELS_CHANNELURL_MESSAGES_MESSAGEID_REACTION:"/open_channels/%s/messages/%s/reactions",GROUPCHANNELS:"/group_channels",MYGROUPCHANNELS:"/users/%s/my_group_channels",GROUPCHANNELS_CHANNELURL:"/group_channels/%s",GROUPCHANNELS_CHANNELURL_INVITE:"/group_channels/%s/invite",GROUPCHANNELS_CHANNELURL_ACCEPT_INVITATION:"/group_channels/%s/accept",GROUPCHANNELS_CHANNELURL_DECLINE_INVITATION:"/group_channels/%s/decline",GROUPCHANNELS_CHANNELURL_HIDE:"/group_channels/%s/hide",GROUPCHANNELS_CHANNELURL_LEAVE:"/group_channels/%s/leave",GROUPCHANNELS_CHANNELURL_JOIN:"/group_channels/%s/join",GROUPCHANNELS_CHANNELURL_OPERATORS:"/group_channels/%s/operators",GROUPCHANNELS_CHANNELURL_MESSAGES:"/group_channels/%s/messages",GROUPCHANNELS_CHANNELURL_MESSAGES_MARKASREAD:"/group_channels/%s/messages/mark_as_read",GROUPCHANNELS_CHANNELURL_MESSAGES_MARKASDELIVERED:"/group_channels/%s/messages/mark_as_delivered",GROUPCHANNELS_CHANNELURL_MESSAGES_TOTALCOUNT:"/group_channels/%s/messages/total_count",GROUPCHANNELS_CHANNELURL_MESSAGES_UNREADCOUNT:"/group_channels/%s/messages/unread_count",GROUPCHANNELS_CHANNELURL_MESSAGES_MESSAGEID:"/group_channels/%s/messages/%s",GROUPCHANNELS_CHANNELURL_MESSAGES_MESSAGEID_TRANSLATION:"/group_channels/%s/messages/%s/translation",GROUPCHANNELS_CHANNELURL_MESSAGES_CHANGELOGS:"/group_channels/%s/messages/changelogs",GROUPCHANNELS_CHANNELURL_MESSAGES_GAP:"/group_channels/%s/messages_gap",GROUPCHANNELS_CHANNELURL_SCHEDULED_MESSAGES:"/group_channels/%s/scheduled_messages",GROUPCHANNELS_CHANNELURL_MEMBERS:"/group_channels/%s/members",GROUPCHANNELS_CHANNELURL_METADATA:"/group_channels/%s/metadata",GROUPCHANNELS_CHANNELURL_METADATA_KEY:"/group_channels/%s/metadata/%s",GROUPCHANNELS_CHANNELURL_METACOUNTER:"/group_channels/%s/metacounter",GROUPCHANNELS_CHANNELURL_METACOUNTER_KEY:"/group_channels/%s/metacounter/%s",GROUPCHANNELS_RESET_USER_HISTORY:"/group_channels/%s/reset_user_history",GROUPCHANNELS_OPERATORS:"/group_channels/%s/operators",GROUPCHANNELS_MEMBERS:"/group_channels/%s/members",GROUPCHANNELS_CHANNELURL_BAN:"/group_channels/%s/ban",GROUPCHANNELS_CHANNELURL_BAN_USERID:"/group_channels/%s/ban/%s",GROUPCHANNELS_CHANNELURL_MUTE:"/group_channels/%s/mute",GROUPCHANNELS_CHANNELURL_MUTE_USERID:"/group_channels/%s/mute/%s",GROUPCHANNELS_CHANNELURL_FREEZE:"/group_channels/%s/freeze",GROUPCHANNELS_CHANNELURL_MESSAGES_MESSAGEID_REACTION:"/group_channels/%s/messages/%s/reactions",STORAGE_FILE:"/storage/file",STORAGE_PROFILE:"/storage/profile_image",FRIENDS:"/users/%s/friends",FRIENDS_CHANGE_LOGS:"/users/%s/friends/changelogs",FRIENDS_DISCOVERIES:"/users/%s/friend_discoveries",SEARCH_MESSAGE:"/search/messages",REPORT_USERS:"/report/users/%s",REPORT_CHANNELS:"/report/%s/%s",REPORT_MESSAGES:"/report/%s/%s/messages/%s",EMOJIS_EMOJIKEY:"/emojis/%s",EMOJI_CATEGORIES:"/emoji_categories",EMOJI_CATEGORIES_CATEGORYID:"/emoji_categories/%s"}}}]),e}(),ce=function(){function e(t,n){c(this,e),this.sb=t,this.ws=null,this.wsHost=null,this.WebSocket=null,this.handler=n||new e.ConnectionHandler,this.explicitDisconnect=!1,this.lastActiveMillis=0;try{this.WebSocket="undefined"==typeof WebSocket?a.default:WebSocket}catch(e){this.WebSocket=WebSocket}}return h(e,[{key:"connect",value:function(e,t,n){var r=this;J.debug("`WebSocketClient.connect` called.");var i=O.get(this.sb._iid).container,s=i.pinger,a=i.auth,o=i.extensions,l=i.getUserAgentWithExtensions,u=i.sessionManager,c=wi.getAppVersion();this.wsHost=n;try{var d="/?p=JS"+"&pv=".concat(encodeURIComponent(T.OS_VERSION))+"&sv=".concat(encodeURIComponent(T.SDK_VERSION))+"&ai=".concat(encodeURIComponent(this.sb.getApplicationId()));if(c&&(d+="&av=".concat(encodeURIComponent(c))),a.sessionKey?d+="&key=".concat(encodeURIComponent(a.sessionKey)):d+="&user_id=".concat(encodeURIComponent(e),"&access_token=").concat(encodeURIComponent(t)),d+="&active=1",d+="&SB-User-Agent=".concat(encodeURIComponent(l(o))),d+="&Request-Sent-Timestamp=".concat((new Date).getTime().toString()),d+="&include_extra_data=".concat(encodeURIComponent(["premium_feature_list","file_upload_size_limit","application_attributes","emoji_hash"].join(","))),u.handler&&(d+="&expiring_session=1"),d+="&use_local_cache=1",this.ws=new this.WebSocket(this.wsHost+d),!this.ws)return this.sb.isReconnectingOnError=!0,void this.handler.onError({message:"ws does not exist."})}catch(e){return this.sb.isReconnectingOnError=!0,void this.handler.onError(e)}try{this.sb.getDebugMode()&&"undefined"!=typeof window&&(window.ws=this.ws)}catch(e){J.debug("`window` object does not exist.")}var h=!1;this.ws.onopen=function(e){J.debug("`WebSocket.onopen` called."),r.handler.onOpen(e)},this.ws.onmessage=function(e){r.active();for(var t=e.data.split("\n"),n=0;n-1&&this._observers.splice(t,1)},e}();!function(e){e[e.EVENT_CHANNEL_CHANGED=0]="EVENT_CHANNEL_CHANGED",e[e.EVENT_USER_RECEIVED_INVITATION=1]="EVENT_USER_RECEIVED_INVITATION",e[e.EVENT_USER_DECLINED_INVITATION=2]="EVENT_USER_DECLINED_INVITATION",e[e.EVENT_USER_JOINED=3]="EVENT_USER_JOINED",e[e.EVENT_USER_LEFT=4]="EVENT_USER_LEFT",e[e.EVENT_CHANNEL_ENTER=5]="EVENT_CHANNEL_ENTER",e[e.EVENT_CHANNEL_EXIT=6]="EVENT_CHANNEL_EXIT",e[e.EVENT_CHANNEL_FROZEN=7]="EVENT_CHANNEL_FROZEN",e[e.EVENT_CHANNEL_UNFROZEN=8]="EVENT_CHANNEL_UNFROZEN",e[e.EVENT_CHANNEL_HIDDEN=9]="EVENT_CHANNEL_HIDDEN",e[e.EVENT_CHANNEL_UNHIDDEN=10]="EVENT_CHANNEL_UNHIDDEN",e[e.EVENT_TYPING_STATUS_UPDATED=11]="EVENT_TYPING_STATUS_UPDATED",e[e.EVENT_OPERATOR_UPDATED=12]="EVENT_OPERATOR_UPDATED",e[e.EVENT_CHANNEL_METADATA_UPDATED=13]="EVENT_CHANNEL_METADATA_UPDATED",e[e.EVENT_CHANNEL_METADATA_DELETED=14]="EVENT_CHANNEL_METADATA_DELETED",e[e.EVENT_CHANNEL_METACOUNTER_UPDATED=15]="EVENT_CHANNEL_METACOUNTER_UPDATED",e[e.EVENT_CHANNEL_METACOUNTER_DELETED=16]="EVENT_CHANNEL_METACOUNTER_DELETED",e[e.EVENT_CHANNEL_DELETED=17]="EVENT_CHANNEL_DELETED",e[e.EVENT_USER_MUTED=18]="EVENT_USER_MUTED",e[e.EVENT_USER_UNMUTED=19]="EVENT_USER_UNMUTED",e[e.EVENT_USER_BANNED=20]="EVENT_USER_BANNED",e[e.EVENT_USER_UNBANNED=21]="EVENT_USER_UNBANNED",e[e.EVENT_MESSAGE_RECEIVED=22]="EVENT_MESSAGE_RECEIVED",e[e.EVENT_MESSAGE_SENT=23]="EVENT_MESSAGE_SENT",e[e.EVENT_MESSAGE_UPDATED=24]="EVENT_MESSAGE_UPDATED",e[e.EVENT_MESSAGE_DELETED=25]="EVENT_MESSAGE_DELETED",e[e.EVENT_READ_RECEIPT_UPDATED=26]="EVENT_READ_RECEIPT_UPDATED",e[e.EVENT_DELIVERY_RECEIPT_UPDATED=27]="EVENT_DELIVERY_RECEIPT_UPDATED",e[e.EVENT_MENTION=28]="EVENT_MENTION",e[e.EVENT_REACTION_UPDATED=29]="EVENT_REACTION_UPDATED",e[e.EVENT_THREAD_INFO_UPDATED=30]="EVENT_THREAD_INFO_UPDATED",e[e.CHANNEL_BACKGROUND=1e3]="CHANNEL_BACKGROUND",e[e.CHANNEL_CHANGELOG=1001]="CHANNEL_CHANGELOG",e[e.MESSAGE_BACKGROUND=1002]="MESSAGE_BACKGROUND",e[e.MESSAGE_FILL=1003]="MESSAGE_FILL",e[e.MESSAGE_CHANGELOG=1004]="MESSAGE_CHANGELOG",e[e.LOCAL_MESSAGE_PENDING_CREATED=2e3]="LOCAL_MESSAGE_PENDING_CREATED",e[e.LOCAL_MESSAGE_FAILED=2001]="LOCAL_MESSAGE_FAILED",e[e.LOCAL_MESSAGE_CANCELED=2002]="LOCAL_MESSAGE_CANCELED",e[e.LOCAL_MESSAGE_RESEND_STARTED=2003]="LOCAL_MESSAGE_RESEND_STARTED",e[e.MESSAGE_COLLECTION_FILTER_MISMATCH=2004]="MESSAGE_COLLECTION_FILTER_MISMATCH"}(de||(de={}));var fe,_e={},ge=function(){function e(){this._observers=[]}return e.of=function(t){return _e[t]||(_e[t]=new e),_e[t]},e.prototype.addObserver=function(e){this._observers.push(e)},e.prototype.removeObserver=function(e){var t=this._observers.indexOf(e);t>=0&&this._observers.splice(t,1)},e.prototype.send=function(e){for(var t=0,n=this._observers;t1&&void 0!==arguments[1])||arguments[1],r=O.get(this.sb._iid),i=r.container,s=i.auth,a=i.apiClient,o=i.commandHandler,l=i.ackStateMap,u=i.sessionManager,c=this.cls.OpenChannel;if(this.sb.connecting=!1,this.sb.reconnecting=!0,this.sb.reconnectTimer)J.debug("Reconnect: still reconnecting.");else{if(this.reconnectCount+=1,this.reconnectCount<=1){if(n){Object.keys(l).forEach((function(e){var t=l[e];t&&(clearTimeout(t.timer),(0,t.handler)(new H("Command received no ack.",H.ACK_TIMEOUT),null));delete l[e]}));var d=pe.of(this.sb._iid);d.invokeDisconnect(),Object.keys(this.sb.connectionHandlers).forEach((function(e){t.sb.connectionHandlers[e].onReconnectStarted()}))}this.reconnectDelay=0}else this.reconnectDelay=Math.min(1e3*this.reconnectParams.interval*Math.pow(this.reconnectParams.multiplier,this.reconnectCount-2),this.reconnectParams.maxInterval>0?1e3*this.reconnectParams.maxInterval:Number.MAX_SAFE_INTEGER);if(!e||!s.sessionKey||this.reconnectParams.retryCount>0&&this.reconnectCount>this.reconnectParams.retryCount)return this.disconnect({clearSession:!1,err:new H("Websocket connection failed with a number of retries.",H.WEBSOCKET_CONNECTION_FAILED)},null),this.reconnectCount=0,Object.keys(this.sb.connectionHandlers).forEach((function(e){t.sb.connectionHandlers[e].onReconnectFailed()})),this.sb.connecting=!1,this.sb.reconnecting=!1,this.sb.isReconnectingOnError=!1,void this.sb.ConnectionManager.errorAllReadyHandler();this.sb.onReconnectTimerCancel=function(){t.reconnectCount=0},this.sb.reconnectTimer=setTimeout((function(){t.sb.reconnectTimer=null,t.sb.onReconnectTimerCancel=null,t.client&&t.client.disconnect(!0);var n=new ce.ConnectionHandler;t.client=new ce(t.sb,n),t.sb.loginHandler=function(n,r){n?u.isSessionError(n)?u.refreshSessionIfExpiredError(n).then((function(){clearTimeout(t.sb.reconnectTimer),t.sb.reconnectTimer=null,t.reconnectCount=0,t.reconnect(e,!1)})).catch((function(){})):(clearTimeout(t.sb.reconnectTimer),t.sb.reconnectTimer=null,t.reconnect(e,!1)):(t.reconnectCount=0,t.sb.connecting=!1,t.sb.reconnecting=!1,t.sb.isReconnectingOnError=!1,pe.of(t.sb._iid).invokeConnect(),Object.keys(t.sb.connectionHandlers).forEach((function(e){t.sb.connectionHandlers[e].onReconnectSucceeded()})),t.sb.ConnectionManager.processAllReadyHandler(null),t.sb.isReconnectingOnError&&Object.keys(t.sb.ConnectionManager.networkHandlers).forEach((function(e){t.sb.ConnectionManager.networkHandlers[e].onReconnected()})),Object.keys(c.enteredChannels).forEach((function(e){c.enteredChannels[e].enter((function(n,r){if(n){var i=t.cls.FileMessageQueue;delete c.enteredChannels[e],i.delete(e)}}))})))},n.onOpen=function(){J.debug("Reconnect: `WebSocketClient.ConnectionHandler.onOpen` called."),t.sb.loginTimer=setTimeout((function(){J.debug("Reconnect: `loginTimer` timeout."),t.sb.loginTimer=null,t.reconnect(e,!0)}),t.sb.Options.websocketResponseTimeout),t.sb.onLoginTimerCancel=null},n.onMessage=function(e){o.onRawCommandReceived(e)},n.onError=function(n){J.debug("Reconnect: `WebSocketClient.ConnectionHandler.onError` called.",n),t.sb.isReconnectingOnError=!0,t.sb.ConnectionManager.errorAllReadyHandler(),t.reconnect(e,!0)},n.onClose=function(){J.debug("Reconnect: `WebSocketClient.ConnectionHandler.onClose` called."),t.sb.reconnecting=!1},a.checkRouting((function(n,r){n?t.reconnect(e,!0):(t.sb.getCurrentApiHost()!==r.apiHost&&a.get("/",null,(function(){})),t.client.connect(e,null,r.wsHost))}))}),this.reconnectDelay)}}},{key:"disconnect",value:function(e,t){var n=O.get(this.sb._iid),r=n.container.ackStateMap,i=this.cls,s=i.GroupChannel,a=i.OpenChannel,o=e.clearSession,l=e.err;this.sb.loginTimer&&(clearTimeout(this.sb.loginTimer),this.sb.onLoginTimerCancel&&(this.sb.onLoginTimerCancel(),this.sb.onLoginTimerCancel=null),this.sb.loginTimer=null),this.sb.reconnectTimer&&(clearTimeout(this.sb.reconnectTimer),this.sb.onReconnectTimerCancel&&(this.sb.onReconnectTimerCancel(),this.sb.onReconnectTimerCancel=null),this.sb.reconnectTimer=null),this.client&&(this.reconnectCount=0,this.client.disconnect(!0),this.client=null),Object.keys(r).forEach((function(e){var t=r[e];t&&(clearTimeout(t.timer),(0,t.handler)(new H("WebSocket connection must be made first.",H.WEBSOCKET_CONNECTION_CLOSED),null))})),n.set("ackStateMap",{}),o&&(a.clearEnteredChannels(),a.clearCache(),s.clearCache(),this.sb.globalTimer&&(clearInterval(this.sb.globalTimer),this.sb.globalTimer=null),this.sb.currentUser=null,n.set("subscribedUnreadMessageCount",{all:0,custom_types:{},ts:0}),n.set("auth",new F)),l&&(this.flushConnectionCallbacks(l,null),this.sb.connecting=!1,this.sb.reconnecting=!1,this.sb.isReconnectingOnError=!1),t&&t(null,null)}},{key:"flushConnectionCallbacks",value:function(e,t){var n=this,r=O.get(this.sb._iid).container,i=r.store,s=r.localCacheEnabled,a=this.sb.connectionCallbacks;if(this.sb.connectionCallbacks=[],e)if(s){var o=this.sb._getCurrentUserDataKey();se.isNonAutoReconnectableError(e.code)?i.remove(o).catch((function(e){return J.debug("Sendbird connect store remove error: ",e)})).finally((function(){return a.forEach((function(t){return t(e,null)}))})):i.get(o).then((function(e){n.sb._populateVaultFromCurrentUserData(e)})).catch((function(e){J.debug("Sendbird connect store fetch error: ",e)})).finally((function(){n.sb.currentUser?a.forEach((function(t){return t(e,n.sb.currentUser)})):a.forEach((function(t){return t(e,null)}))}))}else a.forEach((function(t){return t(e,null)}));else pe.of(this.sb._iid).invokeConnect(),s?i.set({key:this.sb._getCurrentUserDataKey(),value:this._createCurrentUserData(t),generation:1}).catch((function(e){return J.debug("Sendbird connect store write error: ",e)})).finally((function(){return a.forEach((function(e){return e(null,n.sb.currentUser)}))})):a.forEach((function(e){return e(null,t)}))}},{key:"_createCurrentUserData",value:function(e){var t=O.get(this.sb._iid).container,n=t.auth,r=t.maxUnreadCountOfSuperGroupChannel,i=t.profileImageEncryption,s=t.appInfo,a=t.connectedAt,o=t.firstConnectedAt,l=t.concurrentCallLimit,u=t.backOffDelay,c={currentUser:(e||this.sb.currentUser).serialize(),maxUnreadCountOfSuperGroupChannel:T.DEFAULT_MAX_UNREAD_COUNT_OF_SUPER_GROUP_CHANNEL,profileImageEncryption:!1};return n.sessionKey&&(c.sessionKey=n.sessionKey),n.eKey&&(c.eKey=n.eKey),r&&(c.maxUnreadCountOfSuperGroupChannel=r),i&&(c.profileImageEncryption=i),s&&(c.appInfo=s._objectify()),a&&o&&(c.connectedAt=a,c.firstConnectedAt=o),l&&u&&(c.concurrentCallLimit=l,c.backOffDelay=u),c}}]),e}(),me=function(){function e(t){var n=t.type,r=t.nullable,i=void 0!==r&&r,s=t.optional,a=void 0!==s&&s,o=t.optionalIf,l=void 0===o?null:o,u=t.ignoreIf,d=void 0===u?null:u,h=t.defaultValue,p=void 0===h?null:h,f=t.constraint,_=void 0===f?null:f;c(this,e),this.type=n,this.nullable=i,this.optional=a,this.optionalIf=l,this.ignoreIf=d,this.defaultValue=p,this.constraint=_}return h(e,[{key:"isMatchingType",value:function(e){var t=function(t,n){return"string"==typeof n?u(t)===n||"array"===n&&Array.isArray(t)||"file"===n&&se.isFile(t)||"null"===n&&null===t||"date"===n&&t instanceof Date:"function"==typeof n?t instanceof n:"object"===u(n)&&Object.keys(n).map((function(e){return n[e]})).indexOf(e)>-1};return t(e,this.type)||Array.isArray(this.type)&&this.type.some((function(n){return t(e,n)}))||this.nullable&&null===e}}],[{key:"parse",value:function(t,n){for(t=e.toArray(t);t.length>0&&void 0===t[t.length-1];)t.pop();var r=!1,i=null;"callback"===n[n.length-1].type&&("function"==typeof t[t.length-1]&&(i=t.pop()),n.pop(),r=!0);var s=[],a=null,o=0;return n.forEach((function(n){"function"==typeof n.ignoreIf&&n.ignoreIf(t)?s.push(n.hasOwnProperty("defaultValue")?n.defaultValue:null):n.isMatchingType(t[o])?(n.nullable&&null===t[o]||!n.constraint||n.constraint(t[o])||(a=e.error),s.push(t[o]),o++):n.optional||"function"==typeof n.optionalIf&&n.optionalIf(t)?s.push(n.hasOwnProperty("defaultValue")?n.defaultValue:null):(a=e.error,s.push(t[o]),o++)})),r&&i&&s.push(i),t.length!==o&&(a=e.error),[a].concat(s)}},{key:"error",get:function(){return new H("Invalid parameter.",H.INVALID_PARAMETER)}},{key:"toArray",value:function(e){for(var t=[],n=0;n1&&void 0!==arguments[1])||arguments[1],n=O.get(this.sb._iid),r=n.container,i=r.auth,s=r.isInBackground;t&&i.hasSession()?e&&(this.sb.currentUser?e(null,this.sb.currentUser):(this.addReadyHandler(e),this.errorAllReadyHandler()),this.sb.getConnectionState()!==this.sb.ConnectionState.CLOSED||s||this.sb.reconnect()):(this.addReadyHandler(e),this.sb.isReconnectingOnError?this.errorAllReadyHandler():this.sb.getConnectionState()===this.sb.ConnectionState.OPEN?this.processAllReadyHandler(null):this.sb.getConnectionState()===this.sb.ConnectionState.CONNECTING||this.errorAllReadyHandler())}},{key:"processAllReadyHandler",value:function(e){if(this.readyHandlers.length>0){var t=this.sb.currentUser,n=this.readyHandlers;this.readyHandlers=[],n.forEach((function(n){n&&"function"==typeof n&&n(e,t)}))}}},{key:"errorAllReadyHandler",value:function(){var e=O.get(this.sb._iid).container.auth;this.processAllReadyHandler(e&&e.hasSession()?new H("WebSocket connection must be made first.",H.WEBSOCKET_CONNECTION_CLOSED):new H("Connection should be made first.",H.CONNECTION_REQUIRED))}},{key:"NetworkHandler",value:function(){this.onReconnected=function(){}}},{key:"addNetworkHandler",value:function(e,t){J.warn("`ConnectionManager` will be deprecated."),this.networkHandlers[e]=t}},{key:"removeNetworkHandler",value:function(e){J.warn("`ConnectionManager` will be deprecated."),delete this.networkHandlers[e]}},{key:"removeAllNetworkHandler",value:function(){J.warn("`ConnectionManager` will be deprecated."),this.networkHandlers={}}},{key:"authenticate",value:function(e){var t=this;if(J.warn("`ConnectionManager` will be deprecated."),this.sb.getConnectionState()===this.sb.ConnectionState.OPEN||this.sb.reconnecting)this.sb.connecting=!1,e(null,this.sb.currentUser);else if(this.authInfoRequester&&"function"==typeof this.authInfoRequester){this.sb.connecting=!0,this.authCount++;var n=setTimeout((function(){n=null,t.authCount--,0===t.authCount&&0===t.sb.connectionCallbacks.length&&(t.sb.connecting=!1),t.errorAllReadyHandler(),e(new H("Connection should be made first.",H.CONNECTION_REQUIRED),null)}),this.authenticateTimer);this.authInfoRequester((function(r){if(n){clearTimeout(n),n=null,t.authCount--;var i=function(n,r){t.sb.connecting=!1,e(n,null)};r&&r.hasOwnProperty("userId")?r.accessToken?r.apiHost&&r.wsHost?t.sb.connect(r.userId,r.accessToken,r.apiHost,r.wsHost,i):t.sb.connect(r.userId,r.accessToken,i):r.apiHost&&r.wsHost?t.sb.connect(r.userId,r.apiHost,r.wsHost,i):t.sb.connect(r.userId,i):e(me.error,null)}}))}else e(me.error,null)}}]),e}(),ve=function(){this.onSessionExpired=function(){},this.onSessionTokenRequired=function(e,t){return e(null)},this.onSessionError=function(e){},this.onSessionRefreshed=function(){},this.onSessionClosed=function(){}},be=function(){function e(){c(this,e),this.handler=null,this.resolvers=[]}return h(e,[{key:"_refreshSessionToken",value:function(){var t=this;return new Promise((function(n,r){var i=null,s=function(){i&&(clearTimeout(i),i=null)},a=function(){i&&(s(),r(e.sessionTokenRequestFailedError))};i=setTimeout((function(){return a()}),3e4),t.handler.onSessionTokenRequired((function(e){i&&(s(),n(e))}),a)}))}},{key:"_refreshSessionKey",value:function(){var t=this;return new Promise((function(n,r){var i=O.get(t._iid).container,s=i.auth,a=i.wsAdapter;s.sessionToken?a.isConnected?t._refreshSessionKeyByCommand().then((function(){return n()})).catch((function(e){e.isSessionTokenExpiredError?r(e):t._refreshSessionKeyByApi().then((function(){return n()})).catch((function(e){return r(e)}))})):t._refreshSessionKeyByApi().then((function(){return n()})).catch((function(e){return r(e)})):r(e.sessionTokenNotFoundError)}))}},{key:"_refreshSessionKeyByCommand",value:function(){var t=this;return new Promise((function(n,r){var i=wi.getInstance(t._iid),s=O.get(t._iid).container.auth,a=x.get(t._iid).Command,o=a.bSessionRefresh({token:s.sessionToken,requestId:a.generateRequestId()});i.sendCommand(o,(function(t,a){if(!i.getErrorFirstCallback()){var o=[t,a];a=o[0],t=o[1]}t?r(t):a?a.hasOwnProperty("error")?r(e.sessionKeyRefreshFailedError):(a.hasOwnProperty("new_key")&&(s.sessionKey=a.new_key),n()):r(e.sessionKeyRefreshFailedError)}))}))}},{key:"_refreshSessionKeyByApi",value:function(){var t=this;return new Promise((function(n,r){!function i(s){if(s<3){var a=O.get(t._iid).container,o=a.auth,l=a.apiClient,u={};o.sessionToken&&(u.accessToken=o.sessionToken),l.refreshSessionKey(u,(function(e,t){if(e)e.isSessionTokenExpiredError||e.isSessionTokenRevokedError?r(e):i(s+1);else{var a=t.key;o.sessionKey=a,n()}}))}else r(e.sessionKeyRefreshFailedError)}(0)}))}},{key:"_handleSessionToken",value:function(t){var n=this;t?(O.get(this._iid).container.auth.sessionToken=t,this._refreshSessionKey().then((function(){return n._handleSessionRefreshSuccess()})).catch((function(){return n._handleSessionRefreshError(e.sessionTokenRequestFailedError)}))):this._handleSessionClosed(e.sessionTokenRequestFailedError)}},{key:"_handleSessionRefreshSuccess",value:function(){this.handler.onSessionRefreshed(),this._flushResolvers(null)}},{key:"_handleSessionRefreshError",value:function(e){this._cancelConnection(),this.handler.onSessionError(e),this._flushResolvers(e)}},{key:"_handleSessionClosed",value:function(e){this._cancelConnection(),this.handler.onSessionClosed(),this._flushResolvers(e)}},{key:"_cancelConnection",value:function(){var e=wi.getInstance(this._iid);e.reconnecting&&(Object.keys(e.connectionHandlers).forEach((function(t){e.connectionHandlers[t].onReconnectFailed()})),e.reconnecting=!1),e.disconnect()}},{key:"_flushResolvers",value:function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=0;n2&&void 0!==arguments[2]?arguments[2]:null;switch(c(this,e),this.command=t,this.requestId=r,arguments.length){case 1:if(!t||t.length<=4)this.command="NOOP",this.payload="{}";else if(this.decode(t),this.isRequestIdCommand){var i=this.getJsonElement();i&&(this.requestId=i.req_id||"")}break;case 2:case 3:!this.requestId&&this.isRequestIdCommand&&(this.requestId=e.generateRequestId()),n.req_id=this.requestId||"",this.payload=JSON.stringify(n)}}return h(e,[{key:"isRequestIdCommand",get:function(){return this.isAckRequired||"EROR"===this.command}},{key:"isAckRequired",get:function(){return"LOGI"===this.command||"MESG"===this.command||"FILE"===this.command||"ENTR"===this.command||"EXIT"===this.command||"READ"===this.command||"MEDI"===this.command||"FEDI"===this.command}},{key:"encode",value:function(){return this.command+this.payload+"\n"}},{key:"decode",value:function(e){e=e.trim(),this.command=e.substring(0,4),this.payload=e.substring(4)}},{key:"getJsonElement",value:function(){return JSON.parse(this.payload)}}],[{key:"bSessionRefresh",value:function(e){return new this("LOGI",{token:e.token,expiring_session:1},e.requestId)}},{key:"bPing",value:function(){return new this("PING",{id:(new Date).getTime(),active:1})}},{key:"bMessage",value:function(e){var t=e.channelUrl,n=e.message,r=e.data,i=e.customType,s=e.metaArrays,a=e.mentionType,o=e.mentionedUserIds,l=e.mentionedMessageTemplate,u=e.translationTargetLanguages,c=e.pushNotificationDeliveryOption,d=e.appleCriticalAlertOptions,h=e.requestId,p=void 0===h?null:h,f=e.silent,_=void 0!==f&&f,g=e.rootMessageId,y=void 0===g?null:g,m=e.parentMessageId,E=void 0===m?null:m,v=e.isReplyToChannel,b=void 0!==v&&v,C=x.get(this._iid),A=C.UserMessageParams,N=C.BaseMessageParams,S={};return S.channel_url=t,S.message=n,S.data=r,s&&s.length>0&&(S.metaarray=s.map((function(e){return e.encode()}))),a&&(S.mention_type=a),S.mentioned_user_ids=[],a===N.MentionType.CHANNEL?S.mentioned_user_ids=[]:Array.isArray(o)&&o.length>0&&(S.mentioned_user_ids=o),l&&(S.mentioned_message_template=l),i&&(S.custom_type=i),u&&u.length>0&&(S.target_langs=u),c&&c!==A.PushNotificationDeliveryOption.DEFAULT&&(S.push_option=c),d&&(S.apple_critical_alert_options=d.serialize()),_&&(S.silent=_),y&&(S.root_message_id=y),E&&(S.parent_message_id=E),b&&(S.reply_to_channel=b),new this("MESG",S,p)}},{key:"bFile",value:function(e){var t=e.channelUrl,n=e.url,r=e.name,i=e.type,s=e.size,a=e.data,o=e.customType,l=e.thumbnailSizes,u=e.requireAuth,c=e.metaArrays,d=e.mentionType,h=e.mentionedUserIds,p=e.pushNotificationDeliveryOption,f=e.appleCriticalAlertOptions,_=e.requestId,g=void 0===_?null:_,y=e.silent,m=void 0!==y&&y,E=e.rootMessageId,v=void 0===E?null:E,b=e.parentMessageId,C=void 0===b?null:b,A=e.isReplyToChannel,N=void 0!==A&&A,S=x.get(this._iid),I=S.BaseMessageParams,T=S.FileMessageParams,U={};return U.channel_url=t,U.url=n,U.name=r||"",U.type=i||"",U.size=s||0,U.custom=a,o&&(U.custom_type=o),l&&(U.thumbnails=l),u&&(U.require_auth=u),c&&c.length>0&&(U.metaarray=c.map((function(e){return e.encode()}))),d&&(U.mention_type=d),U.mentioned_user_ids=[],d===I.MentionType.CHANNEL?U.mentioned_user_ids=[]:Array.isArray(h)&&h.length>0&&(U.mentioned_user_ids=h),p&&p!==T.PushNotificationDeliveryOption.DEFAULT&&(U.push_option=p),f&&(U.apple_critical_alert_options=f.serialize()),m&&(U.silent=m),v&&(U.root_message_id=v),C&&(U.parent_message_id=C),N&&(U.reply_to_channel=N),new this("FILE",U,g)}},{key:"bUpdateUserMessage",value:function(e){var t=e.channelUrl,n=e.messageId,r=e.appleCriticalAlertOptions,i=e.message,s=void 0===i?null:i,a=e.data,o=void 0===a?null:a,l=e.customType,u=void 0===l?null:l,c=e.mentionType,d=void 0===c?null:c,h=e.mentionedUserIds,p=void 0===h?null:h,f=e.mentionedMessageTemplate,_=void 0===f?null:f,g=e.metaArrayParams,y=void 0===g?null:g,m=x.get(this._iid).BaseMessageParams,E={};return E.channel_url=t,E.msg_id=n,null!=s&&void 0!==s&&(E.message=s),null!=o&&void 0!==o&&(E.data=o),null!=u&&void 0!==u&&(E.custom_type=u),d&&(E.mention_type=d),d===m.MentionType.CHANNEL?E.mentioned_user_ids=[]:Array.isArray(p)&&p.length>=0&&(E.mentioned_user_ids=p),_&&(E.mentioned_message_template=_),y&&(E.metaarray=y),r&&(E.apple_critical_alert_options=r.serialize()),new this("MEDI",E)}},{key:"bUpdateFileMessage",value:function(e){var t=e.channelUrl,n=e.messageId,r=e.appleCriticalAlertOptions,i=e.data,s=void 0===i?null:i,a=e.customType,o=void 0===a?null:a,l=e.mentionType,u=void 0===l?null:l,c=e.mentionedUserIds,d=void 0===c?null:c,h=e.metaArrayParams,p=void 0===h?null:h,f=x.get(this._iid).BaseMessageParams,_={};return _.channel_url=t,_.msg_id=n,null!=s&&void 0!==s&&(_.data=s),null!=o&&void 0!==o&&(_.custom_type=o),u&&(_.mention_type=u),u===f.MentionType.CHANNEL?_.mentioned_user_ids=[]:Array.isArray(d)&&d.length>=0&&(_.mentioned_user_ids=d),p&&(_.metaarray=p),r&&(_.apple_critical_alert_options=r.serialize()),new this("FEDI",_)}},{key:"bRead",value:function(e){var t=e.channelUrl,n={};return n.channel_url=t,new this("READ",n)}},{key:"bMessageAck",value:function(e){var t=e.channelUrl,n=e.messageId,r={};return r.channel_url=t,r.msg_id=n,new this("MACK",r)}},{key:"bTypeStart",value:function(e){var t=e.channelUrl,n=e.time,r={};return r.channel_url=t,r.time=n,new this("TPST",r)}},{key:"bTypeEnd",value:function(e){var t=e.channelUrl,n=e.time,r={};return r.channel_url=t,r.time=n,new this("TPEN",r)}},{key:"bEnter",value:function(e){var t=e.channelUrl,n={};return n.channel_url=t,new this("ENTR",n)}},{key:"bExit",value:function(e){var t=e.channelUrl,n={};return n.channel_url=t,new this("EXIT",n)}},{key:"generateRequestId",value:function(){return Ae++,String(Ae)}}]),e}(),Se=1048576,Ie=function(){function e(e){void 0===e&&(e={}),this._emojiHash=e.emoji_hash||"",this._uploadSizeLimit=e.file_upload_size_limit?e.file_upload_size_limit*Se:Number.MAX_VALUE,this._useReaction=!!e.use_reaction,this._applicationAttributes=e.application_attributes||[],this._premiumFeatureList=e.premium_feature_list||[],this._disableSupergroupMack=e.disable_supergroup_mack||!1}return Object.defineProperty(e.prototype,"emojiHash",{get:function(){return this._emojiHash},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"uploadSizeLimit",{get:function(){return this._uploadSizeLimit},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isUsingReaction",{get:function(){return this._useReaction},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"applicationAttributes",{get:function(){return this._applicationAttributes},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"premiumFeatureList",{get:function(){return this._premiumFeatureList},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isSupergroupMackDisabled",{get:function(){return this._disableSupergroupMack},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"enabledChannelMemberShipHistory",{get:function(){return this._applicationAttributes.includes("channel_membership_history")},enumerable:!1,configurable:!0}),e.prototype._objectify=function(){var e={};return e.emoji_hash=this._emojiHash,this._uploadSizeLimit!==Number.MAX_VALUE&&(e.file_upload_size_limit=this._uploadSizeLimit/Se),e.use_reaction=this._useReaction,e.application_attributes=this._applicationAttributes,e.premium_feature_list=this._premiumFeatureList,e.disable_supergroup_mack=this._disableSupergroupMack,e},e}(),Te=function(){function e(e){this._source=e}return Object.defineProperty(e.prototype,"source",{get:function(){return this._source},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isFromEvent",{get:function(){return this._source>=2e3},enumerable:!1,configurable:!0}),e}(),Ue=function(e){return L(void 0,void 0,void 0,(function(){return w(this,(function(t){return[2,new Promise((function(t){return setTimeout(t,e)}))]}))}))},Oe=function(){var e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){var n=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"===t?n:3&n|8).toString(16)}))},Me=new Map,ke=new Map,Re=function(){function e(t){var n=t.key,r=t.concurrentCallLimit,i=void 0===r?2:r,s=t.backOffDelay,a=void 0===s?0:s;this._holdersKey=e.createSemaphoreHoldersKey(n),this._resolversKey=e.createSemaphoreResolversKey(n),this._numLocks=i,this._backOffDelay=a,this.holders||(this.holders=[]),this.resolvers||(this.resolvers=[])}return e.createSemaphoreHoldersKey=function(e){return"collection@semaphore_holders_for:"+e},e.createSemaphoreResolversKey=function(e){return"collection@semaphore_resolvers_for:"+e},e.createChainProcessStateKey=function(e){return"collection@semaphore_chain_process_state_for:"+e},Object.defineProperty(e.prototype,"numLocksAvailable",{get:function(){return this._numLocks-this.holders.length},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"resolvers",{get:function(){return ke[this._resolversKey]},set:function(e){ke[this._resolversKey]=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"holders",{get:function(){return Me[this._holdersKey]},set:function(e){Me[this._holdersKey]=e},enumerable:!1,configurable:!0}),e.prototype.tryObtainLock=function(){this.numLocksAvailable>0&&this.resolvers.length>0&&this.giveLockToFirstResolver()},e.prototype.giveLockToFirstResolver=function(){var e=this.resolvers.shift();this.holders=P(P([],this.holders,!0),[e.key],!1),e.resolver(e.key)},e.prototype.queueForLock=function(){return L(this,void 0,void 0,(function(){var e=this;return w(this,(function(t){return[2,new Promise((function(t){var n={key:Oe(),resolver:function(e){return t(e)}};e.resolvers.push(n),e.tryObtainLock()}))]}))}))},e.prototype.releaseLock=function(e){return L(this,void 0,void 0,(function(){var t;return w(this,(function(n){switch(n.label){case 0:return(t=this.holders.indexOf(e))>=0?(this.holders.splice(t,1),[4,Ue(this._backOffDelay)]):[3,2];case 1:n.sent(),this.tryObtainLock(),n.label=2;case 2:return[2]}}))}))},e}();!function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.END=2]="END"}(fe||(fe={}));var Le,we=function(){},Pe=function(){function e(e,t,n,r){void 0===n&&(n=2),void 0===r&&(r=10),this._worker=null,this._state=fe.IDLE,this._retryCount=0,this._retryLimit=3,this._isPaused=!1,this.onProgress=we,this.onStop=we,this.onError=we,this.onEnd=we,this._key=e,this._worker=t,this._semaphore=new Re({key:e,concurrentCallLimit:n,backOffDelay:r})}return Object.defineProperty(e.prototype,"isIdle",{get:function(){return this._state===fe.IDLE},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isRunning",{get:function(){return this._state===fe.RUNNING},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isDone",{get:function(){return this._state===fe.END},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isPaused",{get:function(){return this._isPaused},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"retryCount",{get:function(){return this._retryCount},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"retryLimit",{get:function(){return this._retryLimit},enumerable:!1,configurable:!0}),e.prototype.resume=function(e,t){return void 0===t&&(t=!1),this._isPaused=!1,this.isDone&&t&&(this._state=fe.IDLE),this.run(e)},e.prototype.run=function(e){return L(this,void 0,void 0,(function(){var t,n,r;return w(this,(function(i){switch(i.label){case 0:return this._isPaused||!this.isIdle?[3,5]:(t=this,[4,this._semaphore.queueForLock()]);case 1:t._key=i.sent(),this._state=fe.RUNNING,i.label=2;case 2:return i.trys.push([2,4,,5]),[4,this._worker(e)];case 3:return n=i.sent(),this._retryCount=0,this.onProgress(n),n.hasNext?(this._state=fe.IDLE,this._isPaused?(this._semaphore.releaseLock(this._key),this.onStop()):(this.run(n.nextParams),this._semaphore.releaseLock(this._key))):(this._state=fe.END,this._semaphore.releaseLock(this._key),this.onEnd(),this._isPaused&&this.onStop()),[3,5];case 4:return r=i.sent(),J.warn("Collection sync run error: ",r),this._state=fe.IDLE,this._semaphore.releaseLock(this._key),this.onError(r),this._retryCount=this._limit,e.nextParams=this._token=r.next,this._token||(e.hasNext=!1),this._completed=!e.hasNext,J.debug("Group channel collection background sync fetched channels count: ",i.length),[4,c.upsert(i)];case 4:return p.sent(),[4,u.set({key:h,value:{token:this._token,range:this._syncRange,completed:this._completed,primaryKeyIndex:this._pkIndex},generation:1})];case 5:return p.sent(),a={source:de.CHANNEL_BACKGROUND,payload:{channels:i}},d.send(a),[3,9];case 6:return p.sent().isInvalidTokenError?[4,u.remove(h)]:[3,8];case 7:p.sent(),p.label=8;case 8:return[3,9];case 9:return[3,11];case 10:J.debug("Group channel collection background sync has finished."),e.hasNext=!1,p.label=11;case 11:return[2,e]}}))}))}))}return e.of=function(t,n){return void 0===n&&(n=We),He[t]||(He[t]=new e({iid:t,limit:n})),He[t]},Object.defineProperty(e.prototype,"range",{get:function(){return this._syncRange},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"completed",{get:function(){return this._completed},enumerable:!1,configurable:!0}),e.prototype.resume=function(){J.debug("Group channel collection background sync has resumed."),this._sync.resume("")},e.prototype.pause=function(){J.debug("Group channel collection background sync has paused."),this._sync.stop()},e}(),Ge={},xe=function(){function e(e){var t=e.iid,n=this;this._token=0,this._sync=null,this._pkIndex=Date.now(),this._iid=t;var r=x.get(this._iid).GroupChannel,i=O.get(this._iid);this._token=i.get("firstConnectedAt")/1e3;var s=i.get("currentUserId"),a=i.get("store"),o=i.get("apiClient"),l=i.container.localCacheEnabled,u=$e.of(this._iid),c=ge.of(this._iid),d="sendbird:".concat(s,"@groupchannel/changelogs");this._sync=new Pe(d,(function(e){return L(n,void 0,void 0,(function(){var e,t,n,i,s,h,p,f,_=this;return w(this,(function(g){switch(g.label){case 0:return e={hasNext:!0,nextParams:""},l?[4,a.get(d)]:[3,2];case 1:return n=g.sent(),[3,3];case 2:n=null,g.label=3;case 3:(t=n)&&(this._token=t.token,this._pkIndex=t.primaryKeyIndex),i={},"number"==typeof this._token?i.ts=this._token:i.token=this._token,g.label=4;case 4:return g.trys.push([4,10,,13]),[4,o.getMyGroupChannelChangeLogs(i)];case 5:return s=g.sent(),h={updatedChannels:s.updated.map((function(e){return e.cached_primary_key=_._pkIndex--,r.upsert(e)})),deletedChannelUrls:s.deleted},e.hasNext=s.has_more,(h.updatedChannels.length>0||h.deletedChannelUrls.length>0)&&(e.nextParams=this._token=s.next),J.debug("Group channel collection changelog sync update channels count: ",h.updatedChannels.length),J.debug("Group channel collection changelog sync deleted channel urls count: ",h.deletedChannelUrls.length),l?[4,u.upsert(h.updatedChannels)]:[3,9];case 6:return g.sent(),[4,u.remove(h.deletedChannelUrls)];case 7:return g.sent(),[4,a.set({key:d,value:{token:this._token,primaryKeyIndex:this._pkIndex},generation:1})];case 8:g.sent(),g.label=9;case 9:return p={source:de.CHANNEL_CHANGELOG,payload:h},c.send(p),[2,e];case 10:return(f=g.sent()).isInvalidTokenError?[4,a.remove(d)]:[3,12];case 11:g.sent(),g.label=12;case 12:throw f;case 13:return[2]}}))}))}))}return e.of=function(t){return Ge[t]||(Ge[t]=new e({iid:t})),Ge[t]},e.prototype.resume=function(){J.debug("Group channel collection changelog sync has resumed."),this._sync.resume(0,!0)},e.prototype.pause=function(){J.debug("Group channel collection changelog sync has paused."),this._sync.stop()},e}(),je=function(e,t){for(var n=0;n0){for(var r=0,i=e.length-1,s=Math.floor((r+i)/2);r0)i=s,s=Math.floor((r+i)/2);else{if(!(a<0))return s;r=s+1,s=Math.floor((r+i)/2)}}return qe(e[s],t,n)>0?s:s+1}return e.length},Ve=function(e,t){return t-e},qe=function(e,t,n){switch(n){case Le.LATEST_LAST_MESSAGE:if(e.lastMessage&&!t.lastMessage)return-1;if(!e.lastMessage&&t.lastMessage)return 1;if(e.lastMessage&&t.lastMessage){var r=e.lastMessage.createdAt;if(0===(s=t.lastMessage.createdAt-r)){var i=e.createdAt;0===(s=t.createdAt-i)&&(s=Ve(e.cachedPrimaryKey,t.cachedPrimaryKey))}return s}r=e.createdAt;return 0===(s=t.createdAt-r)&&(s=Ve(e.cachedPrimaryKey,t.cachedPrimaryKey)),s;case Le.CHRONOLOGICAL:return 0===(s=t.createdAt-e.createdAt)&&(s=Ve(e.cachedPrimaryKey,t.cachedPrimaryKey)),s;case Le.CHANNEL_NAME_ALPHABETICAL:var s;return 0===(s=e.name.localeCompare(t.name))&&(s=Ve(e.cachedPrimaryKey,t.cachedPrimaryKey)),s}},Ke=function(){},ze={NAME_ALPHABETICAL:["name","-pk"],CHRONOLOGICAL:["-createdAt","-pk"],LATEST_LAST_MESSAGE:["-lastMessageCreatedAt","-createdAt","-pk"]},Ye={LATEST:["channelUrl","-createdAt","-messageId"],LATEST_UNSENT:["channelUrl","sendingStatus","createdAt"],CHILD_MESSAGE_FIRST:["channelUrl","-parentMessageId","-createdAt"]},Qe=function(){function e(){}return e.prototype.isNetworkConnected=function(){return!("undefined"==typeof navigator||!navigator.onLine)},e.ready=function(){return L(this,void 0,void 0,(function(){return w(this,(function(e){return"undefined"!=typeof navigator&&navigator&&"boolean"==typeof navigator.onLine?[2,navigator.onLine]:[2,new Promise((function(e,t){i.default.get("https://www.google.com").then((function(){return e(!0)})).catch((function(){return e(!1)}))}))]}))}))},e}(),We=40;!function(e){e.LATEST_LAST_MESSAGE="latest_last_message",e.CHRONOLOGICAL="chronological",e.CHANNEL_NAME_ALPHABETICAL="channel_name_alphabetical"}(Le||(Le={}));var Je,Xe=function(){function e(e){var t=e.iid,n=e.filter,r=e.order,i=e.limit,s=void 0===i?20:i,a=this;this._channels=[],this._token=null,this._hasMore=!0,this._iid=t,this._filter=n,this._order=r,this._limit=s,this._syncLimit=Math.max(s,We),this._eventObserver={onevent:function(e){return L(a,void 0,void 0,(function(){return w(this,(function(t){return[2,this._handleEvent(e)]}))}))}},this._eventHandler={onChannelsAdded:Ke,onChannelsUpdated:Ke,onChannelsDeleted:Ke};var o=O.get(this._iid);this._localCacheEnabled=o.container.localCacheEnabled,this._localCacheEnabled&&(this._backgroundSync=Fe.of(this._iid,this._syncLimit),this._backgroundSync.resume()),this._changelogSync=xe.of(this._iid),this._changelogSync.resume(),ge.of(this._iid).addObserver(this._eventObserver),this._connectionStateObserver={onConnect:function(){a._localCacheEnabled&&a._backgroundSync.resume(),a._changelogSync.resume()},onDisconnect:function(){return L(a,void 0,void 0,(function(){return w(this,(function(e){switch(e.label){case 0:return[4,Qe.ready()];case 1:return e.sent()||(this._localCacheEnabled&&this._backgroundSync.pause(),this._changelogSync.pause()),[2]}}))}))}},pe.of(this._iid).addObserver(this._connectionStateObserver)}return e.prototype._handleEvent=function(e){var t=this,n=e.source,r=e.payload,i=O.get(this._iid),s=new Te(n);switch(n){case de.CHANNEL_BACKGROUND:break;case de.CHANNEL_CHANGELOG:var a=r,o=a.updatedChannels,l=a.deletedChannelUrls,u=o.filter((function(e){return t._filter.match(e)}));this._addChannelsToView(u,{context:s}),this._removeChannelsFromView(l,{context:s});break;case de.EVENT_USER_DECLINED_INVITATION:var c=i.get("currentUserId"),d=r,h=d.channel;d.invitee.userId===c?this._removeChannelsFromView([h.url],{context:s}):this._filter.match(h)?this._addChannelsToView([h],{context:s}):this._removeChannelsFromView([h.url],{context:s});break;case de.EVENT_USER_LEFT:c=i.get("currentUserId");var p=r;h=p.channel;p.user.userId===c?this._removeChannelsFromView([h.url],{context:s}):this._filter.match(h)?this._addChannelsToView([h],{context:s}):this._removeChannelsFromView([h.url],{context:s});break;case de.EVENT_USER_BANNED:case de.EVENT_USER_UNBANNED:break;case de.EVENT_USER_MUTED:case de.EVENT_USER_UNMUTED:case de.EVENT_TYPING_STATUS_UPDATED:case de.EVENT_OPERATOR_UPDATED:case de.EVENT_CHANNEL_METADATA_UPDATED:case de.EVENT_CHANNEL_METADATA_DELETED:case de.EVENT_CHANNEL_METACOUNTER_UPDATED:case de.EVENT_CHANNEL_METACOUNTER_DELETED:h=r.channel;this._filter.match(h)?this._addChannelsToView([h],{context:s}):this._removeChannelsFromView([h.url],{context:s});break;case de.EVENT_READ_RECEIPT_UPDATED:case de.EVENT_USER_RECEIVED_INVITATION:case de.EVENT_USER_JOINED:case de.EVENT_CHANNEL_FROZEN:case de.EVENT_CHANNEL_UNFROZEN:case de.EVENT_CHANNEL_HIDDEN:case de.EVENT_CHANNEL_UNHIDDEN:case de.EVENT_CHANNEL_CHANGED:h=r.channel;this._filter.match(h)?this._addChannelsToView([h],{context:s}):this._removeChannelsFromView([h.url],{context:s});break;case de.EVENT_CHANNEL_DELETED:var f=r.channelUrl;this._removeChannelsFromView([f],{context:s})}},e.prototype._getRemoteChannels=function(){return L(this,void 0,void 0,(function(){var e,t,n,r;return w(this,(function(i){switch(i.label){case 0:return e=x.get(this._iid).GroupChannel,t=O.get(this._iid),[4,t.get("apiClient").loadGroupChannelList(R(R({},this._filter),{order:this._order,token:this._token,limit:this._limit,userIdsFilter:this._filter.userIdsFilter,searchFilter:(s=this._filter.searchFilter,s.searchQuery&&s.searchFields?{search_query:s.searchQuery,search_fields:s.searchFields.join(",").toLocaleLowerCase()}:{})}))];case 1:return n=i.sent(),r=n.channels.map((function(t){return"number"==typeof n.ts&&(t.ts=n.ts),e.upsert(t)})),[4,$e.of(this._iid).upsert(r)];case 2:return i.sent(),[2,[r,n.next]]}var s}))}))},e.prototype._addChannelsToView=function(e,t){void 0===t&&(t={});for(var n=t.context,r=void 0===n?null:n,i=[],s=[],a=0,o=e;a0&&this._eventHandler.onChannelsAdded(r,i),s.length>0&&this._eventHandler.onChannelsUpdated(r,s))},e.prototype._removeChannelsFromView=function(e,t){void 0===t&&(t={});for(var n=t.context,r=void 0===n?null:n,i=[],s=0,a=e;s=0&&(i.push(this._channels[l].url),this._channels.splice(l,1))}return r&&i.length>0&&this._eventHandler.onChannelsDeleted(r,i),i},Object.defineProperty(e.prototype,"channelList",{get:function(){return this._channels},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hasMore",{get:function(){return this._hasMore},enumerable:!1,configurable:!0}),e.prototype.loadMore=function(){return L(this,void 0,void 0,(function(){var e,t,n,r,i;return w(this,(function(s){switch(s.label){case 0:return this._hasMore?[4,Qe.ready()]:[3,5];case 1:return s.sent()?[3,3]:(J.debug("Group channel collection loadMore() from the cache."),e=$e.of(this._iid),t=e.getNextContainerToken(this._order,this._channels),[4,e.getNextChannels(this._filter,this._order,t,this._limit)]);case 2:return r=s.sent(),this._addChannelsToView(r),[2,r];case 3:return J.debug("Group channel collection loadMore() from the server."),[4,this._getRemoteChannels()];case 4:return n=s.sent(),r=n[0],i=n[1],this._token=i,this._token||(this._hasMore=!1),this._addChannelsToView(r),[2,r];case 5:return[2,[]]}}))}))},e.prototype.dispose=function(){pe.of(this._iid).removeObserver(this._connectionStateObserver),this._localCacheEnabled&&this._backgroundSync.pause(),this._changelogSync.pause(),ge.of(this._iid).removeObserver(this._eventObserver)},e.prototype.setGroupChannelCollectionHandler=function(e){this._eventHandler=e},e.GroupChannelOrder=Le,e}(),Ze={},$e=function(){function e(e){var t=e.iid,n=e.collection,r=void 0===n?null:n;this._collection=null,this._pkIndex=Date.now(),this._lastFetchedPrimaryKey=Date.now(),this._iid=t,this._collection=r,Ze[t]=this}return e.of=function(e){return Ze[e]},e.prototype._serialize=function(e){var t=this._createPk();return e.cachedPrimaryKey=t,R(R({},e.serialize()),{lastMessageCreatedAt:e.lastMessage?e.lastMessage.createdAt:-1,pk:t})},e.prototype._deserialize=function(e){return e?x.get(this._iid).GroupChannel.buildFromSerializedData(e):null},Object.defineProperty(e.prototype,"_localCacheEnabled",{get:function(){return O.get(this._iid).get("localCacheEnabled")},enumerable:!1,configurable:!0}),e.prototype._createPk=function(){return this._pkIndex++},e.prototype._fetch=function(e,t,n){return L(this,void 0,void 0,(function(){var r,i,s,a,o,l,u,c=this;return w(this,(function(d){switch(d.label){case 0:if(!this._localCacheEnabled)return[3,2];switch(r=ze.LATEST_LAST_MESSAGE,t){case Le.CHANNEL_NAME_ALPHABETICAL:r=ze.NAME_ALPHABETICAL;break;case Le.CHRONOLOGICAL:r=ze.CHRONOLOGICAL;break;case Le.LATEST_LAST_MESSAGE:r=ze.LATEST_LAST_MESSAGE}return i=n.containerToken,s=i.lastMessageCreatedAt,a=i.createdAt,o=i.name,l=i.lastFetchedPrimaryKey,u={where:function(n){switch(t){case Le.LATEST_LAST_MESSAGE:if(n.lastMessageCreatedAt>s)return!1;if(n.lastMessageCreatedAt===s&&Ve(l,n.pk)>=0)return!1;if(n.lastMessageCreatedAt<0){if(n.createdAt>a)return!1;if(n.createdAt===a&&Ve(l,n.pk)>=0)return!1}break;case Le.CHANNEL_NAME_ALPHABETICAL:var r=n.name.localeCompare(o);if(r<0)return!1;if(0===r&&Ve(l,n.pk)>=0)return!1;break;case Le.CHRONOLOGICAL:if(n.createdAt>a)return!1;if(n.createdAt===a&&Ve(l,n.pk)>=0)return!1}return e.match(c._deserialize(n))},index:r},[4,this._collection.query(u).fetch({limit:n.limit})];case 1:return[2,d.sent().map((function(e){return c._deserialize(e)}))];case 2:return[2,[]]}}))}))},e.prototype.getNextContainerToken=function(e,t){switch(e){case Le.LATEST_LAST_MESSAGE:return t.length>0?{lastMessageCreatedAt:(n=t[t.length-1]).lastMessage?n.lastMessage.createdAt:-1,createdAt:n.createdAt,lastFetchedPrimaryKey:n.cachedPrimaryKey}:{lastMessageCreatedAt:Number.MAX_SAFE_INTEGER,createdAt:Number.MAX_SAFE_INTEGER,lastFetchedPrimaryKey:this._lastFetchedPrimaryKey};case Le.CHRONOLOGICAL:return t.length>0?{createdAt:(n=t[t.length-1]).createdAt,lastFetchedPrimaryKey:n.cachedPrimaryKey}:{createdAt:Number.MAX_SAFE_INTEGER,lastFetchedPrimaryKey:this._lastFetchedPrimaryKey};case Le.CHANNEL_NAME_ALPHABETICAL:var n;return t.length>0?{name:(n=t[t.length-1]).name,lastFetchedPrimaryKey:n.cachedPrimaryKey}:{name:"",lastFetchedPrimaryKey:this._lastFetchedPrimaryKey}}},e.prototype.get=function(e){return L(this,void 0,void 0,(function(){var t;return w(this,(function(n){switch(n.label){case 0:return this._localCacheEnabled?(t=this._deserialize,[4,this._collection.getByKey(e)]):[3,2];case 1:return[2,t.apply(this,[n.sent()])];case 2:return[2,null]}}))}))},e.prototype.getNextChannels=function(e,t,n,r){return void 0===r&&(r=100),L(this,void 0,void 0,(function(){return w(this,(function(i){switch(i.label){case 0:return[4,this._fetch(e,t,{containerToken:n,limit:r})];case 1:return[2,i.sent()]}}))}))},e.prototype.upsert=function(e){return L(this,void 0,void 0,(function(){var t,n=this;return w(this,(function(r){switch(r.label){case 0:return this._localCacheEnabled?(t=e.map((function(e){return n._serialize(e)})),[4,this._collection.upsertMany(t)]):[3,2];case 1:r.sent(),r.label=2;case 2:return[2]}}))}))},e.prototype.remove=function(e){return L(this,void 0,void 0,(function(){return w(this,(function(t){switch(t.label){case 0:return this._localCacheEnabled?[4,this._collection.removeIf({where:{url:{"/in":e}}})]:[3,3];case 1:return t.sent(),[4,wi.getInstance(this._iid).clearCachedMessages(e)];case 2:t.sent(),t.label=3;case 3:return[2]}}))}))},e.prototype.clear=function(){return L(this,void 0,void 0,(function(){return w(this,(function(e){switch(e.label){case 0:return this._localCacheEnabled?[4,this._collection.clear()]:[3,2];case 1:e.sent(),e.label=2;case 2:return[2]}}))}))},e}(),et=function(){function e(){this.messageType="",this.customTypes=["*"],this.senderUserIds=[],this.sendingStatus=null}return e.prototype.clone=function(){var t=new e,n=JSON.parse(JSON.stringify(this));return Object.keys(n).forEach((function(e){t[e]=n[e]})),t},e.prototype.match=function(e){if(this.messageType&&this.messageType!==e.messageType)return!1;if(!this.customTypes.includes("*")&&!this.customTypes.includes(e.customType))return!1;if(this.senderUserIds.length>0){if(!e.isUserMessage()&&!e.isFileMessage())return!1;if(!this.senderUserIds.includes(e.sender.userId))return!1}return!this.sendingStatus||this.sendingStatus===e.sendingStatus},e}(),tt=function(e,t){if(e.length>0){for(var n=0,r=e.length-1,i=Math.floor((n+r)/2);n0)r=i,i=Math.floor((n+r)/2);else{if(!(s<0))return i;n=i+1,i=Math.floor((n+r)/2)}}return e[i].createdAt>t.createdAt?i:i+1}return e.length},nt=function(e){var t=e.channel,n=e.ts,r=e.prevLimit,i=void 0===r?0:r,s=e.nextLimit,a=void 0===s?0:s,o=e.filter,l={channel:t,token:n,tokenType:"timestamp",isInclusive:!0,prevResultSize:i,nextResultSize:a,shouldReverse:!1,includeMetaArray:!0,includeReactions:!0,includeThreadInfo:!0,includeReplies:!0,includeParentMessageText:!0,showSubchannelMessagesOnly:!0};if(o){var u=o.messageType,c=o.customTypes,d=o.senderUserIds;u&&(l.messageType=u),c.length>0&&(l.customTypes=c),d.length>0&&(l.senderUserIds=d)}return l},rt=function(e,t,n){if(n.length>0){var r=n.map((function(e){return e.createdAt}));t.includes("prev")&&(e.top=Math.min.apply(Math,P([e.top],r,!1))),t.includes("next")&&(e.bottom=Math.max.apply(Math,P([e.bottom],r,!1)))}},it=function(e){return new Promise((function(t,n){setTimeout((function(){return t()}),e)}))},st={};!function(e){e.SUCCEEDED="succeeded",e.UNSENT="unsent"}(Je||(Je={}));var at,ot=function(){function e(e){var t=e.iid,n=e.collections;this._iid=t,this._collections=n,st[t]=this}return e.of=function(e){return st[e]},e.prototype._serialize=function(e){return e.serialize()},e.prototype._deserialize=function(e){if(e){var t=R(R({},e),{messageId:parseInt(e.messageId)}),n=x.get(this._iid),r=n.UserMessage,i=n.FileMessage,s=n.AdminMessage;if("user"===t.messageType)return r.buildFromSerializedData(t);if("file"===t.messageType)return i.buildFromSerializedData(t);if("admin"===t.messageType)return s.buildFromSerializedData(t)}return null},e.deserialize=function(e,t){if(t){var n=R(R({},t),{messageId:parseInt(t.messageId)}),r=x.get(e),i=r.UserMessage,s=r.FileMessage,a=r.AdminMessage;if("user"===n.messageType)return i.buildFromSerializedData(n);if("file"===n.messageType)return s.buildFromSerializedData(n);if("admin"===n.messageType)return a.buildFromSerializedData(n)}return null},Object.defineProperty(e.prototype,"_localCacheEnabled",{get:function(){return O.get(this._iid).get("localCacheEnabled")},enumerable:!1,configurable:!0}),e.prototype._getMessageCollectionByType=function(e){return e?this._collections[e]:this._collections.succeeded},e.prototype._getIndexByCollection=function(e){return"UnsentMessage"===e.name?Ye.LATEST_UNSENT:Ye.LATEST},e.prototype._fetch=function(e,t,n){return L(this,void 0,void 0,(function(){var r,i,s=this;return w(this,(function(a){switch(a.label){case 0:return this._localCacheEnabled?(r={where:function(r){if(!r)return!1;if(e&&r.channelUrl!==e)return!1;if(n.parentMessageId&&r.parentMessageId!==n.parentMessageId)return!1;if(n.backward){if(r.createdAt<=n.token)return!1}else if(r.createdAt>=n.token)return!1;return!!t.match(s._deserialize(r))},index:n.index,backward:n.backward},[4,n.collection.query(r)]):[3,3];case 1:return[4,a.sent().fetch({limit:n.limit})];case 2:return i=a.sent(),[2,Promise.all(i.map((function(e){return L(s,void 0,void 0,(function(){var t,r,i;return w(this,(function(s){switch(s.label){case 0:return t=this._deserialize(e),(r=e.messageParams)&&r.file&&te.isFileTypeBlob(r.fileType)&&"string"==typeof t._messageParams.file?(i=t._messageParams,[4,n.collection.getBlob(r.file)]):[3,2];case 1:i._file=s.sent(),s.label=2;case 2:return[2,t]}}))}))})))];case 3:return[2,[]]}}))}))},e.fetch=function(t,n,r){return L(this,void 0,void 0,(function(){var i,s,a=this;return w(this,(function(o){switch(o.label){case 0:return i={where:function(i){if(!i)return!1;if(r.backward){if(i.createdAt<=r.token)return!1}else if(i.createdAt>=r.token)return!1;return!!n.match(e.deserialize(t,i))},index:r.index,backward:r.backward},[4,r.collection.query(i)];case 1:return[4,o.sent().fetch({limit:r.limit})];case 2:return s=o.sent(),[2,Promise.all(s.map((function(n){return L(a,void 0,void 0,(function(){var i,s,a;return w(this,(function(o){switch(o.label){case 0:return i=e.deserialize(t,n),(s=n.messageParams)&&s.file&&te.isFileTypeBlob(s.fileType)&&"string"==typeof i._messageParams.file?(a=i._messageParams,[4,r.collection.getBlob(s.file)]):[3,2];case 1:a.file=o.sent(),o.label=2;case 2:return[2,i]}}))}))})))]}}))}))},e.prototype.get=function(e,t){return L(this,void 0,void 0,(function(){var n,r;return w(this,(function(i){switch(i.label){case 0:return this._localCacheEnabled?(n=this._getMessageCollectionByType(t),r=this._deserialize,[4,n.getByKey(e)]):[3,2];case 1:return[2,r.apply(this,[i.sent()])];case 2:return[2,null]}}))}))},e.prototype.getPreviousAndNextMessages=function(e,t,n,r,i){return void 0===r&&(r=30),L(this,void 0,void 0,(function(){var s,a;return w(this,(function(o){switch(o.label){case 0:return[4,this.getPreviousMessages(e,t,n,r,i)];case 1:return s=o.sent(),[4,this.getNextMessages(e,t,n,r,i)];case 2:return a=o.sent(),[2,function(e){for(var t=[],n={},r=0,i=e;ri.createdAt||i.createdAt>r)&&t.match(a._deserialize(i)))},index:Ye.LATEST},[4,this._getMessageCollectionByType(i).query(s)]):[3,3];case 1:return[4,o.sent().count()];case 2:return[2,o.sent()];case 3:return[2,0]}}))}))},e.prototype._serializeMessages=function(e,t){return L(this,void 0,void 0,(function(){var n,r,i=this;return w(this,(function(s){switch(s.label){case 0:return n=this._getMessageCollectionByType(t),r=[],[4,Promise.all(e.map((function(e){return L(i,void 0,void 0,(function(){var t,i;return w(this,(function(s){switch(s.label){case 0:return(t=e.serialize())?((t=R({},t)).messageParams&&(t.messageParams=R({},t.messageParams)),e.sendingStatus&&"succeeded"!==e.sendingStatus?t.messageId="unsent-".concat(e.reqId):t.messageId="".concat(e.messageId),e.isFileMessage()&&e._messageParams&&e._messageParams.file&&te.isBlob(e._messageParams.file)&&te.isFileTypeBlob(e._messageParams.fileType)?[4,n.saveBlob(e._messageParams.file,e.reqId)]:[3,2]):[3,3];case 1:i=s.sent(),t.messageParams.file=i,s.label=2;case 2:r.push(t),s.label=3;case 3:return[2]}}))}))})))];case 1:return s.sent(),[2,r]}}))}))},e.prototype.upsert=function(e,t){return L(this,void 0,void 0,(function(){var n,r,i,s,a,o,l,u,c,d,h,p,f,_,g;return w(this,(function(y){switch(y.label){case 0:return this._localCacheEnabled?(n=wi.getInstance(this._iid),r=this._getMessageCollectionByType(t),[4,this._serializeMessages(e,t)]):[3,13];case 1:return i=y.sent(),[4,r.upsertMany(i)];case 2:if(y.sent(),t&&t!==Je.SUCCEEDED)return[3,13];s=[],a=[],o=0,y.label=3;case 3:return o0?(c=(u=s).concat,[4,this._locallyUpdateChildMessages(l,Je.SUCCEEDED)]):[3,6]:[3,7];case 4:return s=c.apply(u,[y.sent()]),h=(d=a).concat,[4,this._locallyUpdateChildMessages(l,Je.UNSENT)];case 5:a=h.apply(d,[y.sent()]),y.label=6;case 6:return o++,[3,3];case 7:return s.length>0?(p=this._getMessageCollectionByType(Je.SUCCEEDED),[4,this._serializeMessages(s,Je.SUCCEEDED)]):[3,10];case 8:return f=y.sent(),[4,p.upsertMany(f)];case 9:y.sent(),y.label=10;case 10:return a.length>0?(_=this._getMessageCollectionByType(Je.UNSENT),[4,this._serializeMessages(a,Je.UNSENT)]):[3,13];case 11:return g=y.sent(),[4,_.upsertMany(g)];case 12:y.sent(),y.label=13;case 13:return[2]}}))}))},e.prototype._locallyUpdateChildMessages=function(e,t){return L(this,void 0,void 0,(function(){var n,r,i;return w(this,(function(s){switch(s.label){case 0:return n=new et,r=[],i=this._getMessageCollectionByType(t),[4,this.getAllChildMessages(e,n,i)];case 1:return s.sent().forEach((function(t){t.applyParentMessage(e)&&r.push(t)})),[2,r]}}))}))},e.prototype.remove=function(e,t){return L(this,void 0,void 0,(function(){var n,r;return w(this,(function(i){switch(i.label){case 0:return this._localCacheEnabled?[4,it(500)]:[3,3];case 1:return i.sent(),n=this._getMessageCollectionByType(t),r={messageId:{"/in":e.map((function(e){return"".concat(e)}))}},[4,n.removeIf({where:r})];case 2:i.sent(),i.label=3;case 3:return[2]}}))}))},e.prototype.removeUnsentMessages=function(e){return L(this,void 0,void 0,(function(){var t,n,r,i,s,a;return w(this,(function(o){switch(o.label){case 0:return t=e.channelUrl,n=e.sendingStatus,r=e.reqIds,i=[],this._localCacheEnabled?[4,it(500)]:[3,3];case 1:return o.sent(),s=this._getMessageCollectionByType(Je.UNSENT),a={channelUrl:{"=":t}},n&&(a.sendingStatus={"=":n}),r&&r.length>0&&(a.reqId={"/in":r}),[4,s.removeIf({where:a})];case 2:i=o.sent(),o.label=3;case 3:return[2,i]}}))}))},e.prototype.removeFailedMessages=function(e,t){return L(this,void 0,void 0,(function(){var n,r,i,s;return w(this,(function(a){switch(a.label){case 0:return n=[],this._localCacheEnabled?[4,it(500)]:[3,3];case 1:return a.sent(),r=this._getMessageCollectionByType(Je.UNSENT),i=wi.getInstance(this._iid),s={channelUrl:{"=":e},sendingStatus:{"=":i.MessageSendingStatus.FAILED}},t&&t.length>0&&(s.reqId={"/in":t}),[4,r.removeIf({where:s})];case 2:n=a.sent(),a.label=3;case 3:return[2,n]}}))}))},e.prototype.clearByChannelUrl=function(e){return L(this,void 0,void 0,(function(){var t=this;return w(this,(function(n){switch(n.label){case 0:return[4,Promise.all(Object.keys(Je).map((function(n){var r=t._getMessageCollectionByType(Je[n]),i={channelUrl:{"=":e}};return r.removeIf({where:i})})))];case 1:return n.sent(),[2]}}))}))},e.prototype.clear=function(e){return L(this,void 0,void 0,(function(){return w(this,(function(t){switch(t.label){case 0:return this._localCacheEnabled?[4,this._getMessageCollectionByType(e).clear()]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))}))},e.prototype.clearAll=function(){return L(this,void 0,void 0,(function(){var e=this;return w(this,(function(t){switch(t.label){case 0:return this._localCacheEnabled?[4,Promise.all(Object.keys(Je).map((function(t){return e.clear(Je[t])})))]:[3,2];case 1:t.sent(),t.label=2;case 2:return[2]}}))}))},e.prototype.clearAbove=function(e,t){return L(this,void 0,void 0,(function(){var n,r;return w(this,(function(i){switch(i.label){case 0:return this._localCacheEnabled?(n=this._getMessageCollectionByType(t),r={createdAt:{"<":e}},[4,n.removeIf({where:r})]):[3,2];case 1:i.sent(),i.label=2;case 2:return[2]}}))}))},e}(),lt=function(){function e(){this.messageId=null,this.userId=null,this.key=null,this.operation="",this.updatedAt=null}return e.createFromJson=function(e){var t=parseInt(e.msg_id),n=e.user_id,r=e.operation,i=e.reaction,s=e.updated_at;if(t&&"string"==typeof n&&"string"==typeof r&&["add","delete"].indexOf(r.toLowerCase())>=0&&"string"==typeof i&&i&&"number"==typeof s){var a=new this;return a.messageId=t,a.userId=n,a.key=i,a.operation=r.toLowerCase(),a.updatedAt=s,a}return null},e}(),ut=function(e){return Object.keys(e).forEach((function(t){e[t]&&"object"==typeof e[t]&&ut(e[t])})),Object.freeze(e)},ct=function(){function e(){}return e.serialize=function(e,t){void 0===t&&(t=null);var n=JSON.parse(JSON.stringify(e));return t&&t(n),ut(n)},e.serializeWithoutFreeze=function(e,t){void 0===t&&(t=null);var n=JSON.parse(JSON.stringify(e));return t&&t(n),n},e.deserialize=function(e,t){void 0===t&&(t=null);var n=JSON.parse(JSON.stringify(e));return t&&t(n),n},e}(),dt={TIMESTAMP:"timestamp",MESSAGE_ID:"messageId"},ht=new WeakMap,pt=function(){function e(t){c(this,e),this.messageId=0,this.messageType=e.MESSAGE_TYPE_BASE,this.channelUrl="",this.data=null,this.customType=null,this.silent=!1,this.createdAt=0,this.updatedAt=0,this.channelType=null,this.metaArrays=[],this.reactions=[],this.mentionType=null,this.mentionedUsers=[],this.mentionedUserIds=[],this.mentionedMessageTemplate=null,this.sendingStatus=null,ht.set(this,0),this.parentMessageId=0,this.parentMessageText=null,this.threadInfo=null,this.isReplyToChannel=!1,this.parentMessage=null,this.ogMetaData=null,this.isOperatorMessage=!1,this.appleCriticalAlertOptions=null,this.reqId="",this._isAutoResendRegistered=!1,t&&this.__update(t)}return h(e,[{key:"serialize",value:function(e){var t=this;return ct.serialize(this,(function(n){n.hasOwnProperty("_sender")&&(n.sender=n._sender,delete n._sender),n.hasOwnProperty("_isAutoResendRegistered")&&(n.isAutoResendRegistered=n._isAutoResendRegistered,delete n._isAutoResendRegistered),t.appleCriticalAlertOptions&&(n.appleCriticalAlertOptions=t.appleCriticalAlertOptions.serialize()),e&&e(n)}))}},{key:"isIdentical",value:function(e){return!("object"!==u(e)||!e.hasOwnProperty("messageId"))&&(0!==this.messageId&&0!==e.messageId?this.messageId===e.messageId:this.reqId===e.reqId)}},{key:"isEqual",value:function(e){return se.deepEqual(this,e)}},{key:"isOpenChannel",value:function(){var e=x.get(this._iid).BaseChannel;return this.channelType===e.CHANNEL_TYPE_OPEN}},{key:"isGroupChannel",value:function(){var e=x.get(this._iid).BaseChannel;return this.channelType===e.CHANNEL_TYPE_GROUP}},{key:"isUserMessage",value:function(){return this.messageType===e.MESSAGE_TYPE_USER}},{key:"isAdminMessage",value:function(){return this.messageType===e.MESSAGE_TYPE_ADMIN}},{key:"isFileMessage",value:function(){return this.messageType===e.MESSAGE_TYPE_FILE}},{key:"__update",value:function(e){var t=this,n=wi.getInstance(this._iid),r=x.get(this._iid),i=r.User,s=r.BaseChannel,a=r.BaseMessageParams,o=r.BaseMessage,u=r.Reaction,c=r.MessageMetaArray,d=r.ThreadInfo,h=r.OGMetaData,p=r.AppleCriticalAlertOptions;if(e.hasOwnProperty("msg_id")&&e.msg_id&&(this.messageId=parseInt(e.msg_id)),e.hasOwnProperty("type"))switch(e.type){case"MESG":this.messageType=o.MESSAGE_TYPE_USER;break;case"FILE":this.messageType=o.MESSAGE_TYPE_FILE;break;case"BRDM":case"ADMM":this.messageType=o.MESSAGE_TYPE_ADMIN}e.hasOwnProperty("message_id")&&e.message_id&&(this.messageId=parseInt(e.message_id)),this.channelUrl=e.hasOwnProperty("channel_url")?String(e.channel_url):"",this.data=e.hasOwnProperty("data")?String(e.data):"",this.customType=e.hasOwnProperty("custom_type")?String(e.custom_type):"",e.hasOwnProperty("silent")&&(this.silent=e.silent),this.createdAt=e.hasOwnProperty("ts")?parseInt(e.ts):0,e.hasOwnProperty("created_at")&&(this.createdAt=parseInt(e.created_at)),this.updatedAt=e.hasOwnProperty("updated_at")?parseInt(e.updated_at):0,this.channelType=e.hasOwnProperty("channel_type")?String(e.channel_type):s.CHANNEL_TYPE_GROUP;var f=e.hasOwnProperty("metaarray")?e.metaarray:{},_=e.hasOwnProperty("metaarray_key_order")?e.metaarray_key_order:Object.keys(f).sort((function(e,t){return e.localeCompare(t)}));this.metaArrays=[];for(var g=0;g<_.length;g++){var y=_[g];this.metaArrays.push(new c(y,f[y]||[]))}if(e.hasOwnProperty("sorted_metaarray")){var m=e.sorted_metaarray;Array.isArray(m)&&(this.metaArrays=m.map((function(e){return new c(e.key,e.value)})))}if(this.reactions=[],e.hasOwnProperty("reactions")&&Array.isArray(e.reactions))for(var E=0;E0?n.MessageSendingStatus.SUCCEEDED:n.MessageSendingStatus.FAILED,e.hasOwnProperty("sending_status")&&(this.sendingStatus=e.sending_status),e.hasOwnProperty("root_message_id")&&e.root_message_id&&ht.set(this,parseInt(e.root_message_id)),e.hasOwnProperty("parent_message_id")&&e.parent_message_id&&(this.parentMessageId=parseInt(e.parent_message_id)),this.threadInfo=new d(e.thread_info),this.isReplyToChannel=!!e.hasOwnProperty("is_reply_to_channel")&&e.is_reply_to_channel,e.hasOwnProperty("parent_message_info")){var b=l({},e.parent_message_info);e.parent_message_info.hasOwnProperty("file")&&(b.require_auth=!!e.parent_message_info.file.require_auth);var C={channelType:this.channelType,channelUrl:this.channelUrl};switch(this.parentMessage=s.buildMessage(b,C),this.parentMessage.messageType){case o.MESSAGE_TYPE_USER:this.parentMessageText=this.parentMessage.message;break;case o.MESSAGE_TYPE_FILE:this.parentMessageText=this.parentMessage.name}}e.hasOwnProperty("og_tag")&&(this.ogMetaData=new h(e.og_tag)),e.hasOwnProperty("is_op_msg")&&(this.isOperatorMessage=e.is_op_msg),e.hasOwnProperty("apple_critical_alert_options")&&(this.appleCriticalAlertOptions=new p(e.apple_critical_alert_options)),e.hasOwnProperty("is_auto_resend_registered")&&(this._isAutoResendRegistered=e.is_auto_resend_registered),this.reqId=e.hasOwnProperty("req_id")?e.req_id:""}},{key:"getMetaArraysByKeys",value:function(e){return Array.isArray(e)?this.metaArrays.filter((function(t){return e.indexOf(t.key)>-1})):[]}},{key:"metaArray",get:function(){var e={};return this.metaArrays.forEach((function(t){e[t.key]=t.value})),e},set:function(e){if("object"===u(e)&&e){var t=x.get(this._iid).MessageMetaArray,n=[];Object.keys(e).forEach((function(r){n.push(new t(r,e[r]))})),this.metaArrays=n}}},{key:"getMetaArrayByKeys",value:function(e){var t={};return this.getMetaArraysByKeys(e).forEach((function(e){t[e.key]=e.value})),t}},{key:"applyReactionEvent",value:function(e){var t=this,n=x.get(this._iid),r=n.Reaction,i=null,s=me.parse(arguments,[new me({type:lt,constraint:function(e){return parseInt(e.messageId)===parseInt(t.messageId)}})]),a=C(s,2);if(i=a[0],e=a[1],!i){for(var o=!1,l=0;l=t)return this.parentMessage=e,!0}return!1}},{key:"_setRootMessageId",value:function(e){ht.set(this,e)}}],[{key:"MESSAGE_TYPE_BASE",get:function(){return"base"}},{key:"MESSAGE_TYPE_ADMIN",get:function(){return"admin"}},{key:"MESSAGE_TYPE_USER",get:function(){return"user"}},{key:"MESSAGE_TYPE_FILE",get:function(){return"file"}},{key:"SendingStatus",get:function(){return{NONE:"none",PENDING:"pending",FAILED:"failed",CANCELED:"canceled",SUCCEEDED:"succeeded"}}},{key:"ReplyType",get:function(){return{ALL:"all",NONE:"none",ONLY_REPLY_TO_CHANNEL:"only_reply_to_channel"}}},{key:"getMessage",value:function(e,t){var n=this,r=x.get(this._iid),i=r.BaseChannel,s=r.MessageRetrievalParams,a=null,o=me.parse(arguments,[new me({type:s,constraint:function(e){return e._validate()}}),new me({type:"callback"})]),u=C(o,3);return a=u[0],e=u[1],t=u[2],oe(this._iid,(function(t){if(a)t(a,null);else{var r=x.get(n._iid),s=r.GroupChannel,o=r.OpenChannel;switch(e.channelType){case i.CHANNEL_TYPE_GROUP:s.getChannel(e.channelUrl,T.INTERNAL_CALL,(function(r,s){if(wi.getInstance(n._iid).getErrorFirstCallback()){var a=[r,s];s=a[0],r=a[1]}s?t(s,null):O.get(n._iid).container.apiClient.getMessage(l({channel:r},e),(function(e,n){if(e)t(e,null);else{var s=i.buildMessage(n,r);t(null,s)}}))}));break;case i.CHANNEL_TYPE_OPEN:o.getChannel(e.channelUrl,T.INTERNAL_CALL,(function(r,s){if(wi.getInstance(n._iid).getErrorFirstCallback()){var a=[r,s];s=a[0],r=a[1]}s?t(s,null):O.get(n._iid).container.apiClient.getMessage(l({channel:r},e),(function(e,n){if(e)t(e,null);else{var s=i.buildMessage(n,r);t(null,s)}}))}))}}}),t)}}]),e}(),ft=function(){function e(e){this.nickname="",this.plainProfileUrl="",this.userId="",this.connectionStatus="",this.lastSeenAt=null,this.metaData={},this.isActive=!0,this.friendDiscoveryKey=null,this.friendName=null,this._preferredLanguages=null,this.requireAuth=null,e&&this.__update(e)}return e.objectify=function(e){var t=e.userId,n=void 0===t?null:t,r=e.nickname,i=void 0===r?"":r,s=e.plainProfileUrl,a=void 0===s?"":s,o=e.connectionStatus,l=void 0===o?"":o,u=e.lastSeenAt,c=void 0===u?0:u,d=e.metaData,h=void 0===d?{}:d,p=e.isActive,f=void 0===p||p,_=e.friendDiscoveryKey,g=void 0===_?null:_,y=e.friendName,m=void 0===y?null:y,E=e.preferredLanguages,v=void 0===E?null:E,b=e.requireAuth;return{user_id:n,nickname:i,profile_url:a,is_online:l,last_seen_at:c,metadata:h,is_active:f,friend_discovery_key:g,friend_name:m,preferred_languages:v,require_auth_for_profile_image:void 0!==b&&b}},e.buildFromSerializedData=function(e){var t=x.get(this._iid).User,n=ct.deserialize(e);return new t(t.objectify(n))},Object.defineProperty(e.prototype,"preferredLanguages",{get:function(){return this._preferredLanguages},enumerable:!1,configurable:!0}),e.prototype.__update=function(t){var n=O.get(this._iid).container.auth;t.hasOwnProperty("guest_id")&&(this.userId=t.guest_id),t.hasOwnProperty("user_id")&&(this.userId=t.user_id),t.hasOwnProperty("name")&&(this.nickname=t.name),t.hasOwnProperty("nickname")&&(this.nickname=t.nickname),t.hasOwnProperty("require_auth_for_profile_image")?this.requireAuth=t.require_auth_for_profile_image:this.requireAuth=null,(t.hasOwnProperty("image")||t.hasOwnProperty("profile_url"))&&(this.plainProfileUrl=t.image||t.profile_url||"",Object.defineProperty(this,"profileUrl",{value:this.requireAuth?"".concat(this.plainProfileUrl,"?auth=").concat(n.eKey):this.plainProfileUrl,configurable:!0,writable:!1})),t.hasOwnProperty("is_online")?t.is_online===e.NON_AVAILABLE?this.connectionStatus=e.NON_AVAILABLE:this.connectionStatus=t.is_online?e.ONLINE:e.OFFLINE:this.connectionStatus=e.NON_AVAILABLE,t.hasOwnProperty("last_seen_at")?this.lastSeenAt=parseInt(t.last_seen_at):this.lastSeenAt=0,t.hasOwnProperty("metadata")?this.metaData=t.metadata:this.metaData={},t.hasOwnProperty("is_active")?this.isActive=void 0===t.is_active||t.is_active:this.isActive=!0,t.hasOwnProperty("friend_discovery_key")?this.friendDiscoveryKey=t.friend_discovery_key:this.friendDiscoveryKey=null,t.hasOwnProperty("friend_name")?this.friendName=t.friend_name:this.friendName=null,t.hasOwnProperty("preferred_languages")?this._preferredLanguages=t.preferred_languages||null:this._preferredLanguages=null},e.prototype._updateMetaData=function(e,t){var n=this;void 0===t&&(t=!1);var r=x.get(this._iid).GroupChannel;Object.keys(e).forEach((function(r){t?delete n.metaData[r]:n.metaData[r]=e[r]})),Object.keys(r.cachedChannels).forEach((function(e){if(r.cachedChannels.hasOwnProperty(e)){var t=r.cachedChannels[e];if(t.memberMap.hasOwnProperty(n.userId))t.memberMap[n.userId].metaData=n.metaData}}))},e.prototype.serialize=function(){return ct.serialize(this,(function(e){e.hasOwnProperty("_preferredLanguages")&&(e.preferredLanguages=e._preferredLanguages,delete e._preferredLanguages)}))},e.prototype.getOriginalProfileUrl=function(){var e="";if(((e=(e=this.plainProfileUrl.indexOf("://")>-1?this.plainProfileUrl.split("/")[2]:this.plainProfileUrl.split("/")[0]).split("?")[0]).indexOf("sendbird.com")>-1||e.indexOf("sendbirdtest.com")>-1||e.indexOf("intoz.com")>-1||e.indexOf("file-local")>-1)&&this.plainProfileUrl.indexOf(e+"/profile_images/")>-1){var t=this.plainProfileUrl.replace("profile_images/","");return t===this.plainProfileUrl?"":t}return""},e.prototype.createMetaData=function(e,t){var n,r=this,i=null;return n=me.parse(arguments,[new me({type:"object",constraint:function(e){return Object.keys(e).length>0&&!Array.isArray(e)}}),new me({type:"callback"})]),i=n[0],e=n[1],t=n[2],oe(this._iid,(function(t){i?t(i,null):O.get(r._iid).container.apiClient.createUserMetaData({metaData:e},(function(e,n){e||r._updateMetaData(n),t(e,n)}))}),t)},e.prototype.updateMetaData=function(e,t,n){var r,i=this,s=null;return r=me.parse(arguments,[new me({type:"object",constraint:function(e){return!Array.isArray(e)&&Object.keys(e).length>0&&Object.keys(e).map((function(t){return e[t]})).every((function(e){return"string"==typeof e}))}}),new me({type:"boolean",optional:!0,defaultValue:!1}),new me({type:"callback"})]),s=r[0],e=r[1],t=r[2],n=r[3],oe(this._iid,(function(n){s?n(s,null):O.get(i._iid).container.apiClient.updateUserMetaData({metaData:e,upsert:t},(function(e,t){e||i._updateMetaData(t),n(e,t)}))}),n)},e.prototype.deleteMetaData=function(e,t){var n,r=this,i=null;return n=me.parse(arguments,[new me({type:"string",constraint:function(e){return e.length>0}}),new me({type:"callback"})]),i=n[0],e=n[1],t=n[2],oe(this._iid,(function(t){if(i)t(i,null);else{var n={};n[e]="",O.get(r._iid).container.apiClient.deleteUserMetaData({metaDataKey:e},(function(e,i){e||r._updateMetaData(n,!0),t(e,i)}))}}),t)},e.prototype.deleteAllMetaData=function(e){var t=this;return oe(this._iid,(function(e){var n=t.metaData;O.get(t._iid).container.apiClient.deleteAllUserMetaData({},(function(r,i){r||t._updateMetaData(n,!0),e(r,i)}))}),e)},Object.defineProperty(e,"NON_AVAILABLE",{get:function(){return"nonavailable"},enumerable:!1,configurable:!0}),Object.defineProperty(e,"ONLINE",{get:function(){return"online"},enumerable:!1,configurable:!0}),Object.defineProperty(e,"OFFLINE",{get:function(){return"offline"},enumerable:!1,configurable:!0}),e}(),_t=function(){function e(e,t){this._source=e,this._sendingStatus=t}return Object.defineProperty(e.prototype,"source",{get:function(){return this._source},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isFromEvent",{get:function(){return this._source>=2e3},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sendingStatus",{get:function(){return this._sendingStatus},enumerable:!1,configurable:!0}),e}(),gt={},yt=function(e,t){return"sendbird:".concat(e,"@channel/").concat(t,"/message/sync")},mt=function(){function e(e){var t=e.iid,n=e.channel,r=e.limit,i=void 0===r?Nt:r,s=this;this._prevSync=null,this._nextSync=null,this._syncRange=new De({top:Number.MAX_SAFE_INTEGER,bottom:-1}),this._isPrevSyncComplete=!1,this._isNextSyncComplete=!1,this._iid=t,this._channel=n,this._limit=i;var a=x.get(this._iid).BaseChannel,o=O.get(this._iid),l=o.get("currentUserId"),u=o.get("store"),c=o.get("apiClient"),d=ot.of(this._iid),h=ge.of(this._iid),p=yt(l,this._channel.url),f=o.container.concurrentCallLimit,_=o.container.backOffDelay;this._prevSync=new Pe(p,(function(e){return L(s,void 0,void 0,(function(){var e,t,r,i,s,o,l,f,_,g=this;return w(this,(function(y){switch(y.label){case 0:return e={hasNext:!0,nextParams:null},[4,u.get(p)];case 1:return(t=y.sent())&&t.isPrevSyncComplete?[3,7]:(t&&(this._syncRange=t.range,this._isPrevSyncComplete=t.isPrevSyncComplete),r=nt({channel:this._channel,ts:this._syncRange.top,prevLimit:this._limit}),[4,c.getMessageList(r)]);case 2:return i=y.sent(),s=[],o=i.messages.map((function(e){var t=a.buildMessage(e,g._channel);return(t.isUserMessage()||t.isFileMessage())&&t._isSentByMe()&&s.push(t.reqId),t})),l=this.getMinCreatedAt(o),this._syncRange.top=Math.min(this._syncRange.top,l),this._syncRange.bottom<0&&(this._syncRange.bottom=this.getMaxCreatedAt(o)),this._isPrevSyncComplete=o.length0?[4,d.removeUnsentMessages({channelUrl:this._channel.url,reqIds:s})]:[3,5];case 4:y.sent(),y.label=5;case 5:return f={range:this._syncRange,isPrevSyncComplete:this._isPrevSyncComplete,isNextSyncComplete:t?t.isNextSyncComplete:this._isNextSyncComplete},[4,u.set({key:p,value:f,generation:1})];case 6:return y.sent(),_={source:de.MESSAGE_BACKGROUND,payload:{channel:n,messages:o}},h.send(_),e.hasNext=!this._isPrevSyncComplete,[3,8];case 7:J.debug("Message collection background sync has finished."),e.hasNext=!1,y.label=8;case 8:return[2,e]}}))}))}),f,_),this._nextSync=new Pe(p,(function(e){return L(s,void 0,void 0,(function(){var e,t,r,i,s,o,l,f,_,g=this;return w(this,(function(y){switch(y.label){case 0:return e={hasNext:!0,nextParams:null},[4,u.get(p)];case 1:return(t=y.sent())?(this._syncRange=t.range,r=nt({channel:this._channel,ts:this._syncRange.bottom,nextLimit:this._limit}),[4,c.getMessageList(r)]):[3,7];case 2:return i=y.sent(),s=[],o=i.messages.map((function(e){var t=a.buildMessage(e,g._channel);return(t.isUserMessage()||t.isFileMessage())&&t._isSentByMe()&&s.push(t.reqId),t})),l=this.getMaxCreatedAt(o),this._syncRange.bottom=Math.max(this._syncRange.bottom,l),this._isNextSyncComplete=o.length0?[4,d.removeUnsentMessages({channelUrl:this._channel.url,reqIds:s})]:[3,5];case 4:y.sent(),y.label=5;case 5:return f={range:this._syncRange,isPrevSyncComplete:t?t.isPrevSyncComplete:this._isPrevSyncComplete,isNextSyncComplete:this._isNextSyncComplete},[4,u.set({key:p,value:f,generation:1})];case 6:y.sent(),_={source:de.MESSAGE_BACKGROUND,payload:{channel:n,messages:o}},h.send(_),e.hasNext=!this._isNextSyncComplete,y.label=7;case 7:return[2,e]}}))}))}),f,_)}return e.of=function(t,n,r){return void 0===r&&(r=Nt),gt[t]||(gt[t]={}),gt[t][n.url]||(gt[t][n.url]=new e({iid:t,channel:n,limit:r})),gt[t][n.url]},Object.defineProperty(e.prototype,"range",{get:function(){return this._syncRange},enumerable:!1,configurable:!0}),e.prototype.resume=function(){J.debug("Message collection background sync has resumed."),this._isPrevSyncComplete||this._prevSync.resume(null),this._isNextSyncComplete||this._nextSync.resume(null)},e.prototype.pause=function(){J.debug("Message collection background sync has paused."),this._prevSync.stop(),this._nextSync.stop()},e.prototype.getMinCreatedAt=function(e){var t=Number.MAX_SAFE_INTEGER;return e.forEach((function(e){var n=e.createdAt;nt&&(t=n)})),t},e}(),Et={},vt=function(e,t){return"sendbird:".concat(e,"@channel/").concat(t,"/message/changelogs")},bt=function(){function e(e){var t=e.iid,n=e.channel,r=this;this._token=0,this._sync=null,this._iid=t,this._channel=n;var i=x.get(this._iid).BaseChannel,s=O.get(this._iid),a=s.get("currentUserId"),o=s.get("store"),l=s.get("apiClient"),u=s.container.localCacheEnabled,c=ot.of(this._iid),d=ge.of(this._iid),h=vt(a,this._channel.url);this._sync=new Pe(h,(function(e){return L(r,void 0,void 0,(function(){var e,t,r,a,p,f,_,g,y,m,E=this;return w(this,(function(v){switch(v.label){case 0:return e={hasNext:!0,nextParams:""},u?[4,o.get(h)]:[3,2];case 1:return r=v.sent(),[3,3];case 2:r=null,v.label=3;case 3:t=r,this._token=t?t.token:s.get("firstConnectedAt")/1e3,a={channelUrl:this._channel.url,isOpenChannel:this._channel.isOpenChannel(),includeMetaArray:!0,includeReactions:!0,includeReplies:!0,includeParentMessageText:!0,includeThreadInfo:!0},"number"==typeof this._token?a.timestamp=this._token:a.token=this._token,v.label=4;case 4:return v.trys.push([4,12,,15]),[4,l.getMessageChangeLogs(a)];case 5:return p=v.sent(),f=p.updated.map((function(e){return i.buildMessage(e,E._channel)})),_={updatedMessages:f,deletedMessageIds:p.deleted.map((function(e){return parseInt(e.message_id)}))},e.hasNext=p.has_more,(_.updatedMessages.length>0||_.deletedMessageIds.length>0)&&(e.nextParams=this._token=p.next),u?(g=[],f.forEach((function(e){(e.isUserMessage()||e.isFileMessage())&&e._isSentByMe()&&g.push(e.reqId)})),g.length>0?[4,c.removeUnsentMessages({channelUrl:this._channel.url,reqIds:g})]:[3,7]):[3,11];case 6:v.sent(),v.label=7;case 7:return[4,c.upsert(f)];case 8:return v.sent(),[4,c.remove(_.deletedMessageIds)];case 9:return v.sent(),[4,o.set({key:h,value:{token:this._token},generation:1})];case 10:v.sent(),v.label=11;case 11:return J.debug("Message collection changelog sync update messages count: ",_.updatedMessages.length),J.debug("Message collection changelog sync deleted message ids count: ",_.deletedMessageIds.length),y={source:de.MESSAGE_CHANGELOG,payload:R({channel:n},_)},d.send(y),[2,e];case 12:return(m=v.sent()).isInvalidTokenError?[4,o.remove(h)]:[3,14];case 13:v.sent(),v.label=14;case 14:throw m;case 15:return[2]}}))}))}))}return e.of=function(t,n){return Et[t]||(Et[t]={}),Et[t][n.url]||(Et[t][n.url]=new e({iid:t,channel:n})),Et[t][n.url]},e.prototype.resume=function(){J.debug("Message collection changelog sync has resumed."),this._sync.resume(null,!0)},e.prototype.pause=function(){J.debug("Message collection changelog sync has paused."),this._sync.stop()},e}();!function(e){e.CACHE_AND_REPLACE_BY_API="cache_and_replace_by_api",e.CACHE_ONLY="cache_only"}(at||(at={}));var Ct,At=function(){function e(){this._onCacheResult=null,this._onApiResult=null}return e.prototype.invokeCacheResult=function(e,t){this._onCacheResult(e,t)},e.prototype.invokeApiResult=function(e,t){this._onApiResult(e,t)},e.prototype.onCacheResult=function(e){return this._onCacheResult=e,this},e.prototype.onApiResult=function(e){return this._onApiResult=e,this},e}();!function(e){e[e.BACKGROUND_SYNC_CLOSE=0]="BACKGROUND_SYNC_CLOSE",e[e.BACKGROUND_SYNC_OPEN=1]="BACKGROUND_SYNC_OPEN",e[e.FILL=2]="FILL",e[e.USER_CALL=3]="USER_CALL"}(Ct||(Ct={}));var Nt=100,St=new De({top:Number.MAX_SAFE_INTEGER,bottom:0}),It=new Map,Tt=function(e){return"sendbird@message/fill/".concat(e,"/").concat(Oe())},Ut=function(){function e(e){var t=e.iid,n=e.channel,r=e.startingPoint,i=e.filter,s=e.limit,a=void 0===s?100:s,o=this;this._hugeGapCheckTimer=null,this._messages=[],this._syncRange=new De(R({},St)),this._hasPrevious=!0,this._hasNext=!0,this._unsentMessages=[],this._iid=t,this._channel=n,this._startingPoint=r,this._filter=i,this._limit=a,this._syncLimit=Math.max(a,Nt),this._eventObserver={onevent:function(e){return L(o,void 0,void 0,(function(){return w(this,(function(t){switch(t.label){case 0:return[4,this._handleEvent(e)];case 1:return t.sent(),[2]}}))}))}},this._eventHandler={onMessagesAdded:Ke,onMessagesUpdated:Ke,onMessagesDeleted:Ke,onChannelUpdated:Ke,onChannelDeleted:Ke,onHugeGapDetected:Ke};var l=O.get(this._iid);this._localCacheEnabled=l.container.localCacheEnabled,this._localCacheEnabled&&(this._backgroundSync=mt.of(this._iid,this._channel,this._syncLimit),this._backgroundSync.resume()),this._changelogSync=bt.of(this._iid,this._channel),this._changelogSync.resume(),this._connectionObserver={onConnect:function(){o._checkHugeGap(),o._localCacheEnabled&&o._backgroundSync.resume(),o._changelogSync.resume()},onDisconnect:function(){return L(o,void 0,void 0,(function(){return w(this,(function(e){switch(e.label){case 0:return[4,Qe.ready()];case 1:return e.sent()||(this._previousFillSync.stop(),this._nextFillSync.stop(),this._localCacheEnabled&&this._backgroundSync.pause(),this._changelogSync.pause()),[2]}}))}))}},this._previousFillSync=new Pe(Tt("prev"),(function(e){return L(o,void 0,void 0,(function(){var t,n,r;return w(this,(function(i){switch(i.label){case 0:return[4,this._getRemoteMessages({ts:e,prevLimit:this._syncLimit})];case 1:return(t=i.sent()).length>0?(n=Math.min.apply(Math,t.map((function(e){return e.createdAt}))),this._syncRange.top=Math.min(this._syncRange.top,n),r=new _t(de.MESSAGE_FILL,t[0].sendingStatus),this._addOnlyMessageToView(t,{context:r}),[2,{hasNext:t.length=n,nextParams:this._syncRange.top}]):[2,{hasNext:!1,nextParams:0}]}}))}))})),this._nextFillSync=new Pe(Tt("next"),(function(e){return L(o,void 0,void 0,(function(){var t,n,r;return w(this,(function(i){switch(i.label){case 0:return[4,this._getRemoteMessages({ts:e,nextLimit:this._syncLimit})];case 1:return(t=i.sent()).length>0?(n=Math.max.apply(Math,t.map((function(e){return e.createdAt}))),this._syncRange.bottom=Math.max(this._syncRange.bottom,n),r=new _t(de.MESSAGE_FILL,t[0].sendingStatus),this._addOnlyMessageToView(t,{context:r}),[2,{hasNext:t.length0){this._removeMatchingUnsentMessagesFromView(o);var u=new _t(t,o[0].sendingStatus);this._addMessagesToView(o,{context:u})}if(l&&l.length>0)if((p=this._removeMessagesFromView(l,{})).length>0){u=new _t(t,p[0].sendingStatus);this._eventHandler.onMessagesDeleted(u,this._channel,p)}}break;case de.LOCAL_MESSAGE_PENDING_CREATED:case de.LOCAL_MESSAGE_RESEND_STARTED:case de.LOCAL_MESSAGE_CANCELED:var c=r,d=(a=c.channel,c.message);u=new _t(t,d.sendingStatus);a.url===this._channel.url&&this._upsertUnsentMessagesToView([d],{context:u});break;case de.EVENT_MESSAGE_SENT:var h=r;a=h.channel,d=h.message;if(a.url===this._channel.url){var p=this._removeMatchingUnsentMessagesFromView([d]);if(this._hasNext){if(p.length>0){u=new _t(t,p[0].sendingStatus);this._eventHandler.onMessagesDeleted(u,a,p)}}else{this._addMessagesToView([d],{});var u=new _t(t,d.sendingStatus);p.length>0?this._eventHandler.onMessagesUpdated(u,a,[d]):this._eventHandler.onMessagesAdded(u,a,[d])}}break;case de.EVENT_MESSAGE_RECEIVED:var f=r;a=f.channel,d=f.message;if(a.url===this._channel.url&&!this._hasNext){u=new _t(t,d.sendingStatus);this._addMessagesToView([d],{context:u})}break;case de.LOCAL_MESSAGE_FAILED:var _=r;a=_.channel,d=_.message;if(a.url===this._channel.url&&d.sendingStatus===i.MessageSendingStatus.FAILED){u=new _t(t,d.sendingStatus);this._upsertUnsentMessagesToView([d],{context:u})}break;case de.EVENT_MESSAGE_UPDATED:var g=r;a=g.channel,d=g.message;if(a.url===this._channel.url){u=new _t(t,d.sendingStatus);this._addMessagesToView([d],{context:u,isUpdateOnly:!0})}break;case de.EVENT_MESSAGE_DELETED:var y=r,m=(a=y.channel,y.messageId);if(a.url===this._channel.url)if(It.delete(m),(p=this._removeMessagesFromView([m],{})).length>0){u=new _t(t,p[0].sendingStatus);this._eventHandler.onMessagesDeleted(u,this._channel,p)}break;case de.EVENT_DELIVERY_RECEIPT_UPDATED:case de.EVENT_READ_RECEIPT_UPDATED:if((a=r.channel).isGroupChannel()){o=[];for(var E=0,v=this._messages;E0?It.set(d.messageId,T):It.delete(d.messageId))}if(o.length>0){u=new _t(t,o[0].sendingStatus);this._eventHandler.onMessagesUpdated(u,a,o)}}break;case de.EVENT_USER_LEFT:var b=O.get(this._iid),C=r,A=(a=C.channel,C.user),N=b.get("currentUserId");if(A.userId!==N){o=[];for(var S=0,I=this._messages;S0?It.set(d.messageId,T):It.delete(d.messageId))}if(o.length>0){u=new _t(t,o[0].sendingStatus);this._eventHandler.onMessagesUpdated(u,a,o)}}else{u=new Te(t);this._eventHandler.onChannelDeleted(u,a.url)}break;case de.EVENT_CHANNEL_CHANGED:case de.EVENT_USER_RECEIVED_INVITATION:case de.EVENT_USER_JOINED:case de.EVENT_CHANNEL_FROZEN:case de.EVENT_CHANNEL_UNFROZEN:case de.EVENT_CHANNEL_HIDDEN:case de.EVENT_CHANNEL_UNHIDDEN:case de.EVENT_USER_MUTED:case de.EVENT_USER_UNMUTED:case de.EVENT_TYPING_STATUS_UPDATED:case de.EVENT_OPERATOR_UPDATED:case de.EVENT_CHANNEL_METADATA_UPDATED:case de.EVENT_CHANNEL_METADATA_DELETED:case de.EVENT_CHANNEL_METACOUNTER_UPDATED:case de.EVENT_CHANNEL_METACOUNTER_DELETED:a=r.channel,u=new Te(t);this._eventHandler.onChannelUpdated(u,a);break;case de.EVENT_CHANNEL_DELETED:a=r.channel,u=new Te(t);this._eventHandler.onChannelDeleted(u,a.url)}},e.prototype._createRemoteMessageParams=function(e){var t=e.prevLimit,n=void 0===t?0:t,r=e.nextLimit,i=void 0===r?0:r,s=new(0,x.get(this._iid).MessageListParams);return s.isInclusive=!0,s.prevResultSize=n,s.nextResultSize=i,s.includeMetaArray=!0,s.includeReactions=!0,s.includeThreadInfo=!0,s.includeReplies=!0,s.includeParentMessageText=!0,this._filter.messageType&&(s.messageType=this._filter.messageType),this._filter.customTypes.length>0&&(s.customTypes=this._filter.customTypes),this._filter.senderUserIds.length>0&&(s.senderUserIds=this._filter.senderUserIds),s},e.prototype._getRemoteMessages=function(e){var t=e.ts,n=e.prevLimit,r=void 0===n?0:n,i=e.nextLimit,s=void 0===i?0:i;return L(this,void 0,void 0,(function(){var e,n,i,a;return w(this,(function(o){switch(o.label){case 0:return e=[],r>0?(i=this._createRemoteMessageParams({prevLimit:r,nextLimit:0}),[4,this._channel.getMessagesByTimestamp(t,i)]):[3,2];case 1:n=o.sent(),e=e.concat(n),this._hasPrevious=n.length>=r,o.label=2;case 2:return s>0?(i=this._createRemoteMessageParams({prevLimit:0,nextLimit:s}),[4,this._channel.getMessagesByTimestamp(t,i)]):[3,4];case 3:a=o.sent(),e=e.concat(a),this._hasNext=a.length>=s,o.label=4;case 4:return e.length>0?[4,this._upsertRemotelyFetchedMessages(e)]:[3,6];case 5:o.sent(),o.label=6;case 6:return[2,e]}}))}))},e.prototype._upsertRemotelyFetchedMessages=function(e,t){return void 0===t&&(t={}),L(this,void 0,void 0,(function(){var n,r,i,s;return w(this,(function(a){switch(a.label){case 0:return n=t.context,r=void 0===n?null:n,i=ot.of(this._iid),s=e.map((function(e){return e.reqId})),[4,i.removeUnsentMessages({channelUrl:this.channel.url,reqIds:s})];case 1:return a.sent(),this._removeMatchingUnsentMessagesFromView(e,{context:r}),[4,i.upsert(e,Je.SUCCEEDED)];case 2:return a.sent(),[2]}}))}))},e.prototype._checkHugeGap=function(){return L(this,void 0,void 0,(function(){var e,t,n,r,i,s,a,o,l,u,c,d,h,p,f,_=this;return w(this,(function(g){switch(g.label){case 0:return g.trys.push([0,12,,13]),e=x.get(this._iid).BaseChannel,t=O.get(this._iid),n=t.get("apiClient"),this._messages.length>0?(r=ot.of(this._iid),i={from:this._messages[0].createdAt,to:Math.min(this._syncRange.top,this._messages[this._messages.length-1].createdAt),cachedCount:0},s=i,[4,r.countBetween(this._channel.url,this._filter,i.from,i.to)]):[3,8];case 1:return s.cachedCount=g.sent(),a={from:Math.max(this._syncRange.bottom,this._messages[0].createdAt),to:this.hasNext?this._messages[this._messages.length-1].createdAt:Number.MAX_SAFE_INTEGER,cachedCount:0},o=a,[4,r.countBetween(this._channel.url,this._filter,a.from,a.to)];case 2:return o.cachedCount=g.sent(),l={iid:this._iid,channelUrl:this._channel.url,channelType:this._channel.channelType,filter:this._filter,previous:i,next:a},[4,n.checkMessageHugeGap(R(R({},l),l.filter))];case 3:return u=g.sent(),(c={isHugeGap:!!u.is_huge_gap,previousMessages:u.prev_messages.map((function(t){return e.buildMessage(t,_._channel)}))||[],previousHasMore:!!u.prev_hasmore,nextMessages:u.next_messages.map((function(t){return e.buildMessage(t,_._channel)}))||[],nextHasMore:!!u.next_hasmore}).isHugeGap?[3,6]:(h=P(P([],c.previousMessages,!0),c.nextMessages,!0),J.debug("Message collection non-huge gap message fill count: ",h.length),h.length>0?(p=new _t(de.MESSAGE_FILL,h[0].sendingStatus),[4,this._upsertRemotelyFetchedMessages(h,{context:p})]):[3,5]);case 4:g.sent(),this._addOnlyMessageToView(h,{context:p}),this._extendSyncRange(["prev"],c.previousMessages),this._extendSyncRange(["next"],c.nextMessages),c.previousHasMore&&this._previousFillSync.run(this._syncRange.top),c.nextHasMore&&this._nextFillSync.run(this._syncRange.bottom),g.label=5;case 5:return[3,7];case 6:setTimeout((function(){return _._eventHandler.onHugeGapDetected()}),10),g.label=7;case 7:return[3,11];case 8:return d=Math.floor(this._syncLimit/2),[4,this._getRemoteMessages({ts:this._startingPoint,prevLimit:d,nextLimit:d})];case 9:return(h=g.sent()).length>0?(p=new _t(de.MESSAGE_FILL,h[0].sendingStatus),[4,this._upsertRemotelyFetchedMessages(h,{context:p})]):[3,11];case 10:g.sent(),this._addOnlyMessageToView(h,{context:p}),this._extendSyncRange(["prev","next"],this._messages),g.label=11;case 11:return[3,13];case 12:return f=g.sent(),J.warn("Message collection huge gap checker error: ",f),this._hugeGapCheckTimer=setTimeout((function(){_._hugeGapCheckTimer=null,_._checkHugeGap()}),3e3),[3,13];case 13:return[2]}}))}))},e.prototype._extendSyncRange=function(e,t){if(t.length>0){var n=t.map((function(e){return e.createdAt}));e.includes("prev")&&(this._syncRange.top=Math.min.apply(Math,P([this._syncRange.top],n,!1))),e.includes("next")&&(this._syncRange.bottom=Math.max.apply(Math,P([this._syncRange.bottom],n,!1)))}},e.prototype._updateChildMessagesInView=function(e){var t=[];return this._messages.forEach((function(n){n.applyParentMessage(e)&&t.push(n)})),t},e.prototype._addOnlyMessageToView=function(e,t){void 0===t&&(t={});var n=t.context,r=void 0===n?null:n;t.isUpdateOnly;for(var i=wi.getInstance(this._iid),s=[],a=0,o=e;a0&&this._eventHandler.onMessagesAdded(r,this._channel,s)},e.prototype._addMessagesToView=function(e,t){void 0===t&&(t={});for(var n=t.context,r=void 0===n?null:n,i=t.isUpdateOnly,s=void 0!==i&&i,a=wi.getInstance(this._iid),o=[],l=[],u=[],c=0,d=e;c=0){if(l.push(h),this._messages[p]=h,h.updatedAt>0){var _=this._updateChildMessagesInView(h);l=l.concat(_)}}else if(!s){var g=tt(this._messages,h);o.push(h),this._messages.splice(g,0,h)}}else p>=0&&(u.push(h),this._messages.splice(p,1))}}r&&(o.length>0&&this._eventHandler.onMessagesAdded(r,this._channel,o),l.length>0&&this._eventHandler.onMessagesUpdated(r,this._channel,l),u.length>0&&this._eventHandler.onMessagesDeleted(r,this._channel,u))},e.prototype._removeMessagesFromView=function(e,t){void 0===t&&(t={});for(var n=t.context,r=void 0===n?null:n,i=[],s=0,a=e;s=0){var u=this._messages[l];i.push(u),this._messages.splice(l,1)}}return r&&i.length>0&&this._eventHandler.onMessagesDeleted(r,this._channel,i),i},e.prototype._upsertUnsentMessagesToView=function(e,t){void 0===t&&(t={});for(var n=t.context,r=void 0===n?null:n,i=[],s=[],a=[],o=0,l=e;o=0)s.push(u),this._unsentMessages[c]=u;else{var d=tt(this._unsentMessages,u);i.push(u),this._unsentMessages.splice(d,0,u)}else c>=0&&(this._unsentMessages.splice(c,1),a.push(u))}r&&(i.length>0&&this._eventHandler.onMessagesAdded(r,this._channel,i),s.length>0&&this._eventHandler.onMessagesUpdated(r,this._channel,s),a.length>0&&this._eventHandler.onMessagesDeleted(r,this._channel,a))},e.prototype._removeMatchingUnsentMessagesFromView=function(e,t){void 0===t&&(t={});for(var n=t.context,r=void 0===n?null:n,i=[],s=0,a=e;s=0){var u=this._unsentMessages[l];i.push(u),this._unsentMessages.splice(l,1)}}}return r&&i.length>0&&this._eventHandler.onMessagesDeleted(r,this._channel,i),i},e.prototype._removeFailedMessagesFromView=function(e){var t=wi.getInstance(this._iid),n=[],r=[],i=this._unsentMessages.map((function(e){return e.reqId}));if(e)for(var s=0,a=e;s=0&&this._unsentMessages[l].sendingStatus===t.MessageSendingStatus.FAILED?n.push(this._unsentMessages[l]):r.push(this._unsentMessages[l])}else for(var u=0,c=this._unsentMessages;u0){e.getIsProcessingAutoResend()||(J.debug("Auto-resend queue started."),e.setIsProcessingAutoResend(!0));var n=t[0];J.debug("Processing auto-resend for message request id: ",n.reqId),x.get(e._iid).GroupChannel.getChannel(n.channelUrl,T.INTERNAL_CALL,(function(t,r){var i;if(e.getErrorFirstCallback()&&(r=(i=[t,r])[0],t=i[1]),r)throw r;n.isUserMessage()?t._autoResendUserMessage(n):n.isFileMessage()&&t._autoResendFileMessage(n)}))}else J.debug("Auto-resend queue finished."),e.setIsProcessingAutoResend(!1)}catch(t){J.warn("Process auto-resend error: ",t),e.setIsProcessingAutoResend(!1)}},e._completeCurrentAndProcessNextAutoResend=function(e,t){if(e.isCacheEnabled&&t._isAutoResendRegistered){var n=e.getAutoResendQueue();if(t.sendingStatus===e.MessageSendingStatus.SUCCEEDED||t.sendingStatus===e.MessageSendingStatus.FAILED&&!se.isAutoResendableError(t.errorCode))n.length>0&&t.reqId===n[0].reqId&&(n.shift(),this._processNextAutoResend(e));else if(t.sendingStatus===e.MessageSendingStatus.PENDING){if(n.length>0&&n.map((function(e){return e.reqId})).indexOf(t.reqId)>-1)return;n.push(t),!e.getIsProcessingAutoResend()&&n.length>0&&this._processNextAutoResend(e)}}},e._processAutoResendRegisteredPendingMessages=function(e){return L(this,void 0,void 0,(function(){var t,n,r,i,s,a,o,l,u,c,d,h;return w(this,(function(p){switch(p.label){case 0:return t=ot.of(e._iid),n=ge.of(e._iid),(r=new et).sendingStatus=e.MessageSendingStatus.PENDING,[4,t.getAllUnsentMessages(r)];case 1:i=p.sent(),s=0,a=i,p.label=2;case 2:return s0?Math.min.apply(Math,this._messages.map((function(e){return e.createdAt}))):Number.MAX_SAFE_INTEGER,[4,Qe.ready()]):[3,5];case 1:return n.sent()?[3,3]:(J.debug("Message collection loadPrevious() from the cache."),[4,ot.of(this._iid).getPreviousMessages(this._channel.url,this._filter,e,this._limit)]);case 2:return t=n.sent(),this._addMessagesToView(t),[2,t];case 3:return J.debug("Message collection loadPrevious() from the server."),[4,this._getRemoteMessages({ts:e,prevLimit:this._limit})];case 4:return t=n.sent(),this._addMessagesToView(t),rt(this._syncRange,["prev"],this._messages),[2,t];case 5:return[2,[]]}}))}))},e.prototype.loadNext=function(){return L(this,void 0,void 0,(function(){var e,t;return w(this,(function(n){switch(n.label){case 0:return this._hasNext?(e=this._messages.length>0?Math.max.apply(Math,this._messages.map((function(e){return e.createdAt}))):0,[4,Qe.ready()]):[3,5];case 1:return n.sent()?[3,3]:(J.debug("Message collection loadNext() from the cache."),[4,ot.of(this._iid).getNextMessages(this._channel.url,this._filter,e,this._limit)]);case 2:return t=n.sent(),this._addMessagesToView(t),[2,t];case 3:return J.debug("Message collection loadNext() from the server."),[4,this._getRemoteMessages({ts:e,nextLimit:this._limit})];case 4:return t=n.sent(),this._addMessagesToView(t),rt(this._syncRange,["next"],this._messages),[2,t];case 5:return[2,[]]}}))}))},e.prototype.removeFailedMessages=function(e){return L(this,void 0,void 0,(function(){var t,n,r,i;return w(this,(function(s){switch(s.label){case 0:return t=wi.getInstance(this._iid),n=ot.of(this._iid),r=e.map((function(e){return e.reqId})),[4,n.removeUnsentMessages({channelUrl:this.channel.url,sendingStatus:t.MessageSendingStatus.FAILED,reqIds:r})];case 1:return i=s.sent(),this._removeFailedMessagesFromView(e),[2,i]}}))}))},e.prototype.removeAllFailedMessages=function(){return L(this,void 0,void 0,(function(){var e;return w(this,(function(t){switch(t.label){case 0:return e=wi.getInstance(this._iid),[4,ot.of(this._iid).removeUnsentMessages({channelUrl:this.channel.url,sendingStatus:e.MessageSendingStatus.FAILED})];case 1:return t.sent(),this._removeFailedMessagesFromView(),[2]}}))}))},e.prototype.dispose=function(){this._localCacheEnabled&&(this._previousFillSync.stop(),this._nextFillSync.stop(),this._backgroundSync.pause()),this._changelogSync.pause(),pe.of(this._iid).removeObserver(this._connectionObserver),this._hugeGapCheckTimer&&(clearTimeout(this._hugeGapCheckTimer),this._hugeGapCheckTimer=null),ge.of(this._iid).removeObserver(this._eventObserver)},e.prototype.setMessageCollectionHandler=function(e){this._eventHandler=e},e}(),Ot={TIMESTAMP:"timestamp",MESSAGE_ID:"messageId"},Mt=new WeakMap,kt=new WeakMap,Rt=function(){function e(t){c(this,e),this.url="",this.channelType=e.CHANNEL_TYPE_BASE,this.name="",this.coverUrl="",this.creator=null,this.createdAt=0,this.data=null,this.customType=null,this.isFrozen=!1,this.isEphemeral=!1,Mt.set(this,{}),kt.set(this,""),t&&this.__update(t)}return h(e,[{key:"__update",value:function(e){this.url=e.hasOwnProperty("channel_url")?String(e.channel_url):"",this.name=e.hasOwnProperty("name")?String(e.name):"",this.coverUrl=e.hasOwnProperty("cover_url")?String(e.cover_url):"",this.createdAt=e.hasOwnProperty("created_at")?1e3*e.created_at:0,this.data=e.hasOwnProperty("data")?String(e.data):"",this.customType=e.hasOwnProperty("custom_type")?e.custom_type:"",this.isFrozen=!!e.hasOwnProperty("freeze")&&e.freeze,this.isEphemeral=!!e.hasOwnProperty("is_ephemeral")&&e.is_ephemeral,e.hasOwnProperty("created_by")&&null!==e.created_by&&"object"===u(e.created_by)&&Object.keys(e.created_by).length>0?this.creator=new ft(e.created_by):this.creator=null,e.hasOwnProperty("metadata")&&null!==e.metadata&&(e.hasOwnProperty("ts")&&"number"==typeof e.ts?this._refreshMetaData(e.metadata,e.ts):this._refreshMetaData(e.metadata,-1)),e.hasOwnProperty("cached_primary_key")&&(this.cachedPrimaryKey=e.cached_primary_key)}},{key:"_addOrUpdateCachedMetaData",value:function(e,t){var n=this,r=Mt.get(this);Object.keys(e).forEach((function(i){var s=r[i],a=e[i];s?t>s.updatedAt&&(s.value=a,s.updatedAt=t,s.isRemoved=!1):r[i]={value:a,updatedAt:t,isRemoved:!1},$e.of(n._iid).upsert([n]).then((function(){})).catch((function(e){J.error(e)}))}))}},{key:"_markAsDeletedCachedMetaData",value:function(e,t){var n=this,r=Mt.get(this);e.forEach((function(e){var i=r[e];i?t>i.updatedAt&&(i.isRemoved=!0,i.updatedAt=t):r[e]={value:null,updatedAt:t,isRemoved:!0},$e.of(n._iid).upsert([n]).then((function(){})).catch((function(e){J.error(e)}))}))}},{key:"_refreshMetaData",value:function(e,t){var n={};Object.keys(e).forEach((function(r){n[r]={value:e[r],updatedAt:t,isRemoved:!1}})),Mt.set(this,n)}},{key:"_clearCachedMetaData",value:function(){Mt.set(this,{})}},{key:"cachedPrimaryKey",get:function(){return kt.get(this)},set:function(e){kt.set(this,e)}},{key:"isGroupChannel",value:function(){var e=x.get(this._iid).BaseChannel;return this.channelType===e.CHANNEL_TYPE_GROUP}},{key:"isOpenChannel",value:function(){var e=x.get(this._iid).BaseChannel;return this.channelType===e.CHANNEL_TYPE_OPEN}},{key:"createOperatorListQuery",value:function(){return new(0,x.get(this._iid).OperatorListQuery)(this)}},{key:"createMessageListQuery",value:function(){return new(0,x.get(this._iid).MessageListQuery)(this)}},{key:"createPreviousMessageListQuery",value:function(){return new(0,x.get(this._iid).PreviousMessageListQuery)(this)}},{key:"serialize",value:function(){var e=this;return ct.serialize(this,(function(t){if(null!==t.lastMessage&&"object"===u(t.lastMessage)){var n=t.lastMessage;n.hasOwnProperty("_sender")&&(n.sender=n._sender,delete n._sender,t.lastMessage=n)}t.hasOwnProperty("_messageOffsetTimestamp")&&(t.messageOffsetTimestamp=t._messageOffsetTimestamp,delete t._messageOffsetTimestamp),t.metadata=e.getCachedMetaData(),e.cachedPrimaryKey&&(t.cachedPrimaryKey=e.cachedPrimaryKey)}))}},{key:"getMessageChangeLogsByTimestamp",value:function(e,t,n,r){var i=this,s=null,a=me.parse(arguments,[new me({type:"number",constraint:function(e){return e>=0}}),new me({type:"boolean",optional:!0,defaultValue:!1}),new me({type:"boolean",optional:!0,defaultValue:!1}),new me({type:"callback"})]),o=C(a,5);return s=o[0],e=o[1],t=o[2],n=o[3],r=o[4],oe(this._iid,(function(r){s?r(s,null):O.get(i._iid).container.apiClient.getMessageChangeLogs({channelUrl:i.url,ts:e,token:null,isOpenChannel:i.isOpenChannel(),includeMetaArray:t,includeReactions:n}).then((function(e){var t=x.get(i._iid).BaseChannel,n={updatedMessages:e.updated.map((function(e){return t.buildMessage(e,i)})),deletedMessageIds:e.deleted.map((function(e){return parseInt(e.message_id)})),hasMore:e.has_more,token:e.next};r(null,n)})).catch((function(e){r(e,null)}))}),r)}},{key:"getMessageChangeLogsByToken",value:function(e,t,n,r){var i=this,s=null,a=me.parse(arguments,[new me({type:"string",nullable:!0}),new me({type:"boolean",optional:!0,defaultValue:!1}),new me({type:"boolean",optional:!0,defaultValue:!1}),new me({type:"callback"})]),o=C(a,5);return s=o[0],e=o[1],t=o[2],n=o[3],r=o[4],oe(this._iid,(function(r){s?r(s,null):O.get(i._iid).container.apiClient.getMessageChangeLogs({channelUrl:i.url,ts:null,token:e,isOpenChannel:i.isOpenChannel(),includeMetaArray:t,includeReactions:n}).then((function(e){var t=x.get(i._iid).BaseChannel,n={updatedMessages:e.updated.map((function(e){return t.buildMessage(e,i)})),deletedMessageIds:e.deleted.map((function(e){return parseInt(e.message_id)})),hasMore:e.has_more,token:e.next};r(null,n)})).catch((function(e){r(e,null)}))}),r)}},{key:"getMessageChangeLogsSinceToken",value:function(e,t,n){var r=this,i=x.get(this._iid),s=i.BaseChannel,a=i.MessageChangeLogsParams,o=null,u=me.parse(arguments,[new me({type:"string",nullable:!0}),new me({type:a,constraint:function(e){return e._validate()}}),new me({type:"callback"})]),c=C(u,4);return o=c[0],e=c[1],t=c[2],n=c[3],oe(this._iid,(function(n){o?n(o,null):O.get(r._iid).container.apiClient.getMessageChangeLogs(l({channelUrl:r.url,ts:null,token:e,isOpenChannel:r.isOpenChannel()},t)).then((function(e){var t={updatedMessages:e.updated.map((function(e){return s.buildMessage(e,r)})),deletedMessageIds:e.deleted.map((function(e){return parseInt(e.message_id)})),hasMore:e.has_more,token:e.next};n(null,t)})).catch((function(e){n(e,null)}))}),n)}},{key:"getMessageChangeLogsSinceTimestamp",value:function(e,t,n){var r=this,i=x.get(this._iid),s=i.BaseChannel,a=i.MessageChangeLogsParams,o=null,u=me.parse(arguments,[new me({type:"number",constraint:function(e){return e>=0}}),new me({type:a,constraint:function(e){return e._validate()}}),new me({type:"callback"})]),c=C(u,4);return o=c[0],e=c[1],t=c[2],n=c[3],oe(this._iid,(function(n){o?n(o,null):O.get(r._iid).container.apiClient.getMessageChangeLogs(l({channelUrl:r.url,timestamp:e,token:null,isOpenChannel:r.isOpenChannel()},t)).then((function(e){var t={updatedMessages:e.updated.map((function(e){return s.buildMessage(e,r)})),deletedMessageIds:e.deleted.map((function(e){return parseInt(e.message_id)})),hasMore:e.has_more,token:e.next};n(null,t)})).catch((function(e){n(e,null)}))}),n)}},{key:"getMyMutedInfo",value:function(e){var t=this;return oe(this._iid,(function(e){var n=wi.getInstance(t._iid);O.get(t._iid).container.apiClient.getMyMutedInfo({channelUrl:t.url,userId:n.currentUser?n.currentUser.userId:null,isGroupChannel:t.isGroupChannel()},(function(t,n){var r=null;t||(r={isMuted:n.is_muted,startAt:n.start_at,endAt:n.end_at,remainingDuration:n.remaining_duration,description:n.description}),e(t,r)}))}),e)}},{key:"_parseMessageListParams",value:function(e){for(var t=x.get(this._iid),n=t.MessageListParams,r=new n,i=null,s=!1,a=0,o=0,l=!1,u="",c="",d=null,h=!1,p=!1,f=null,_=arguments.length,g=new Array(_>1?_-1:0),y=1;y<_;y++)g[y-1]=arguments[y];switch(e){case"prev":var m=me.parse(g,[new me({type:"number"}),new me({type:"boolean"}),new me({type:"number"}),new me({type:"boolean"}),new me({type:"string"}),new me({type:"string"}),new me({type:"array",optional:!0}),new me({type:"boolean",optional:!0,defaultValue:!1}),new me({type:"boolean",optional:!0,defaultValue:!1}),new me({type:"callback"})]),E=C(m,11);i=E[0],s=E[2],a=E[3],l=E[4],u=E[5],c=E[6],d=E[7],h=E[8],p=E[9],f=E[10];break;case"next":var v=me.parse(g,[new me({type:"number"}),new me({type:"boolean"}),new me({type:"number"}),new me({type:"boolean"}),new me({type:"string"}),new me({type:"string"}),new me({type:"array",optional:!0}),new me({type:"boolean",optional:!0,defaultValue:!1}),new me({type:"boolean",optional:!0,defaultValue:!1}),new me({type:"callback"})]),b=C(v,11);i=b[0],s=b[2],o=b[3],l=b[4],u=b[5],c=b[6],d=b[7],h=b[8],p=b[9],f=b[10];break;case"prevnext":var A=me.parse(g,[new me({type:"number"}),new me({type:"number"}),new me({type:"number"}),new me({type:"boolean"}),new me({type:"string"}),new me({type:"string"}),new me({type:"array",optional:!0}),new me({type:"boolean",optional:!0,defaultValue:!1}),new me({type:"boolean",optional:!0,defaultValue:!1}),new me({type:"callback"})]),N=C(A,11);i=N[0],a=N[2],o=N[3],l=N[4],u=N[5],c=N[6],d=N[7],h=N[8],p=N[9],f=N[10],s=!0}return i?[null,f]:(r.isInclusive=s,r.prevResultSize=a,r.nextResultSize=o,r.reverse=l,r.messageType=u,r.customType=c,""===r.customType&&(r.customType="*"),r.senderUserIds=d,r.includeMetaArray=h,r.includeReactions=p,[r,f])}},{key:"_getMessageList",value:function(e,t,n,r){var i=this,s=x.get(this._iid),a=s.MessageListParams,o=null,u=me.parse(arguments,[new me({type:"number"}),new me({type:"string",constraint:function(e){return Object.values(Ot).includes(e)}}),new me({type:a,constraint:function(e){return e._validate()}}),new me({type:"callback"})]),c=C(u,5);return o=c[0],e=c[1],t=c[2],n=c[3],r=c[4],oe(this._iid,(function(r){o?r(o,null):O.get(i._iid).container.apiClient.getMessageList(l(l({channel:i,token:e,tokenType:t},n),{},{shouldReverse:n.reverse})).then((function(e){var t=x.get(i._iid).BaseChannel,n=e.messages.map((function(e){return t.buildMessage(e,i)})).filter((function(e){return null!==e}));r(null,n)})).catch((function(e){r(e,null)}))}),r)}},{key:"getPreviousMessagesByTimestamp",value:function(e){var t=this._parseMessageListParams.apply(this,["prev"].concat(A(me.toArray(arguments)))),n=C(t,2),r=n[0],i=n[1];return this._getMessageList(e,Ot.TIMESTAMP,r,i)}},{key:"getNextMessagesByTimestamp",value:function(e){var t=this._parseMessageListParams.apply(this,["next"].concat(A(me.toArray(arguments)))),n=C(t,2),r=n[0],i=n[1];return this._getMessageList(e,Ot.TIMESTAMP,r,i)}},{key:"getPreviousAndNextMessagesByTimestamp",value:function(e){var t=this._parseMessageListParams.apply(this,["prevnext"].concat(A(me.toArray(arguments)))),n=C(t,2),r=n[0],i=n[1];return this._getMessageList(e,Ot.TIMESTAMP,r,i)}},{key:"getPreviousMessagesByID",value:function(e){var t=this._parseMessageListParams.apply(this,["prev"].concat(A(me.toArray(arguments)))),n=C(t,2),r=n[0],i=n[1];return this._getMessageList(e,Ot.MESSAGE_ID,r,i)}},{key:"getNextMessagesByID",value:function(e){var t=this._parseMessageListParams.apply(this,["next"].concat(A(me.toArray(arguments)))),n=C(t,2),r=n[0],i=n[1];return this._getMessageList(e,Ot.MESSAGE_ID,r,i)}},{key:"getPreviousAndNextMessagesByID",value:function(e){var t=this._parseMessageListParams.apply(this,["prevnext"].concat(A(me.toArray(arguments)))),n=C(t,2),r=n[0],i=n[1];return this._getMessageList(e,Ot.MESSAGE_ID,r,i)}},{key:"getMessagesByTimestamp",value:function(e,t,n){return this._getMessageList(e,Ot.TIMESTAMP,t,n)}},{key:"getMessagesByMessageId",value:function(e,t,n){return this._getMessageList(e,Ot.MESSAGE_ID,t,n)}},{key:"_sendUserMessage",value:function(e){var t=this,n=e.reqId,r=e.message,i=e.data,s=e.customType,a=e.metaArrays,o=e.mentionType,u=e.mentionedUserIds,c=e.mentionedUsers,d=e.mentionedMessageTemplate,h=e.pushNotificationDeliveryOption,p=e.rootMessageId,f=e.parentMessageId,_=e.translationTargetLanguages,g=e.appleCriticalAlertOptions,y=e.silent,m=void 0!==y&&y,E=e.isReplyToChannel,v=e.messageParams,b=e.oldMessage,C=void 0===b?null:b,A=e.isManualResend,N=void 0!==A&&A,S=e.callback,I=x.get(this._iid),T=I.Command,U=I.UserMessage,M=wi.getInstance(this._iid),k=ot.of(this._iid),R=$e.of(this._iid),L=ge.of(this._iid),w=O.get(this._iid).container.localCacheEnabled;n||(n=T.generateRequestId());var P={};Array.isArray(_)&&_.forEach((function(e){return P[e]=""}));var D=U.objectify({messageId:0,reqId:n,user:M.currentUser||{},channel:this,message:r,data:i,customType:s,metaArrays:a,mentionType:o,mentionedUserIds:u,mentionedUsers:c,mentionedMessageTemplate:d,rootMessageId:p,parentMessageId:f,translations:P,silent:m,appleCriticalAlertOptions:g,isReplyToChannel:E,messageParams:v,createdAt:(new Date).getTime()}),F=new U(D);if(F.requestState=M.MessageRequestState.PENDING,F.sendingStatus=M.MessageSendingStatus.PENDING,F.requestedMentionUserIds=u,F._messageParams=v,!M.currentUser){var G=new H("Connection should be made first.",H.CONNECTION_REQUIRED),j=new U(D);return j.requestState=M.MessageRequestState.FAILED,j.sendingStatus=M.MessageSendingStatus.FAILED,j.requestedMentionUserIds=u,j.errorCode=G.code,S(G,j),F}return(!t.isGroupChannel()||C&&C._isAutoResendRegistered?Promise.resolve():k.upsert([F],Je.UNSENT).then((function(){L.send({source:N?de.LOCAL_MESSAGE_RESEND_STARTED:de.LOCAL_MESSAGE_PENDING_CREATED,payload:{channel:t,message:F}})}))).then((function(){var e=T.bMessage({channelUrl:t.url,message:r,data:i,customType:s,metaArrays:a,mentionType:o,mentionedUserIds:u,mentionedMessageTemplate:d,requestId:n,rootMessageId:p,parentMessageId:f,silent:m,translationTargetLanguages:_,pushNotificationDeliveryOption:h,appleCriticalAlertOptions:g,isReplyToChannel:E});(F.reqId=e.requestId,t.isGroupChannel()&&M.getConnectionState()!==M.ConnectionState.OPEN&&M.currentUser&&!M.connecting&&!M.reconnecting&&"string"==typeof s&&0===s.indexOf("SB_VIDEOCHAT"))?O.get(M._iid).container.apiClient.sendUserMessage({channelUrl:t.url,isOpenChannel:t.isOpenChannel(),message:r,data:i,customType:s,translationTargetLanguages:_,metaArrays:a,mentionType:o,mentionedUserIds:u,mentionedMessageTemplate:d,pushNotificationDeliveryOption:h,rootMessageId:p,parentMessageId:f,appleCriticalAlertOptions:g,isReplyToChannel:E},(function(e,r){var i=null;if(e){if(F._isAutoResendRegistered&&se.isAutoResendableError(e.code))return;(i=new U(D)).requestState=M.MessageRequestState.FAILED,i.requestedMentionUserIds=u,C&&(i._isAutoResendRegistered=C._isAutoResendRegistered),e.code===H.REQUEST_CANCELED?(i.sendingStatus=M.MessageSendingStatus.CANCELED,k.removeUnsentMessages({channelUrl:t.url,sendingStatus:M.MessageSendingStatus.PENDING,reqIds:[n]}).then((function(){L.send({source:de.LOCAL_MESSAGE_CANCELED,payload:{channel:t,message:i}})})).catch((function(e){return J.error(e)})).finally((function(){S&&S(new H(e.message,e.code),i)}))):(i.errorCode=e.code,i.sendingStatus=M.MessageSendingStatus.FAILED,w&&se.isAutoResendableError(e.code)&&(i.sendingStatus=M.MessageSendingStatus.PENDING,i.errorCode=0,i._isAutoResendRegistered=!0),k.upsert([i],Je.UNSENT).then((function(){Ut._completeCurrentAndProcessNextAutoResend(M,i),L.send({source:de.LOCAL_MESSAGE_FAILED,payload:{channel:t,message:i}})})).catch((function(e){return J.error(e)})).finally((function(){var t=i._clone();t.sendingStatus=M.MessageSendingStatus.FAILED,t.errorCode=e.code,t._isAutoResendRegistered=!1,S&&S(new H(e.message,e.code),t)})))}else{for(var s in(i=new U(r)).reqId=n,i.requestState=M.MessageRequestState.SUCCEEDED,i.sendingStatus=M.MessageSendingStatus.SUCCEEDED,C&&(i._isAutoResendRegistered=C._isAutoResendRegistered),t.lastMessage=i,M.channelHandlers){M.channelHandlers[s].onChannelChanged(t)}R.upsert([t]).then((function(){L.send({source:de.EVENT_CHANNEL_CHANGED,payload:{channel:t}})})).then((function(){return k.removeUnsentMessages({channelUrl:t.url,sendingStatus:M.MessageSendingStatus.PENDING,reqIds:[n]})})).then((function(){return k.upsert([i],Je.SUCCEEDED)})).then((function(){Ut._completeCurrentAndProcessNextAutoResend(M,i),L.send({source:de.EVENT_MESSAGE_SENT,payload:{channel:t,message:i}})})).catch((function(e){return J.error(e)})).finally((function(){S&&S(null,i)}))}})):M.sendCommand(e,(function(r,i){if(M.getErrorFirstCallback()){var s=[r,i];i=s[0],r=s[1]}if(i){if(F._isAutoResendRegistered&&se.isAutoResendableError(i.code))return;var a=new U(D);a.reqId=e.requestId,a.requestState=M.MessageRequestState.FAILED,i.code===H.REQUEST_CANCELED?(a.sendingStatus=M.MessageSendingStatus.CANCELED,t.isGroupChannel()&&k.removeUnsentMessages({channelUrl:t.url,sendingStatus:M.MessageSendingStatus.PENDING,reqIds:[n]}).then((function(){L.send({source:de.LOCAL_MESSAGE_CANCELED,payload:{channel:t,message:a}})})).catch((function(e){return J.error(e)})).finally((function(){S&&S(new H(i.message,i.code),a)}))):(a.sendingStatus=M.MessageSendingStatus.FAILED,a.errorCode=i.code,a.requestedMentionUserIds=u,t.isGroupChannel()?(w&&se.isAutoResendableError(i.code)&&(a.sendingStatus=M.MessageSendingStatus.PENDING,a.errorCode=0,a._isAutoResendRegistered=!0),k.upsert([a],Je.UNSENT).then((function(){return Ut._completeCurrentAndProcessNextAutoResend(M,a),L.send({source:de.LOCAL_MESSAGE_FAILED,payload:{channel:t,message:a}})})).catch((function(e){return J.error(e)})).finally((function(){var e=a._clone();e.sendingStatus=M.MessageSendingStatus.FAILED,e.errorCode=i.code,e._isAutoResendRegistered=!1,S&&S(new H(i.message,i.code),e)}))):S&&S(new H(i.message,i.code),a))}else{var o=new U(l(l({},r.getJsonElement()),{},{messageParams:v}));o.reqId=n,o.requestState=M.MessageRequestState.SUCCEEDED,o.sendingStatus=M.MessageSendingStatus.SUCCEEDED,C&&(o._isAutoResendRegistered=C._isAutoResendRegistered);var c=M.currentUser;if(c&&o._sender&&c.userId===o._sender.userId&&(c.nickname!==o._sender.nickname&&(c.nickname=o._sender.nickname),c.plainProfileUrl!==o._sender.plainProfileUrl&&(c.plainProfileUrl=o._sender.plainProfileUrl),se.deepEqual(c.metaData,o._sender.metaData)||(c.metaData=o._sender.metaData)),t.isGroupChannel()){t.lastMessage=o,Object.keys(M.channelHandlers).forEach((function(e){M.channelHandlers[e].onChannelChanged(t)}));var d=ge.of(t._iid);$e.of(t._iid).upsert([t]).then((function(){d.send({source:de.EVENT_CHANNEL_CHANGED,payload:{channel:t}})})).then((function(){return k.removeUnsentMessages({channelUrl:t.url,sendingStatus:M.MessageSendingStatus.PENDING,reqIds:[n]})})).then((function(){return k.upsert([o],Je.SUCCEEDED)})).then((function(){Ut._completeCurrentAndProcessNextAutoResend(M,o),d.send({source:de.EVENT_MESSAGE_SENT,payload:{channel:t,message:o}})})).catch((function(e){return J.error(e)})).finally((function(){S&&S(null,o)}))}else S&&S(null,o)}}))})),F}},{key:"sendUserMessage",value:function(){var e=me.toArray(arguments),t=e.pop(),n=null,r=null,i=x.get(this._iid),s=i.UserMessageParams;if("function"==typeof t)if(e[0]instanceof s)null===(r=e[0]).data&&(r.data=""),null===r.customType&&(r.customType="");else if("string"==typeof e[0])switch((r=new s).data="",r.customType="",r.message=e[0],e.length){case 1:break;case 2:r.data=e[1]||"";break;case 3:r.data=e[1]||"",r.customType=e[2]||"";break;case 4:r.data=e[1]||"",r.customType=e[2]||"",r.translationTargetLanguages=Array.isArray(e[3])?e[3]:[e[3]];break;default:n=me.error}else n=me.error;else n=me.error;var a=O.get(this._iid),o=a.container.isErrorFirstInCallback;return!n&&r._validate()&&r.message?this._sendUserMessage(l(l({},r),{},{metaArrays:r.metaArrays,mentionType:r.mentionType,mentionedUserIds:r._mentionedUserIds,mentionedUsers:r.mentionedUsers,mentionedMessageTemplate:r.mentionedMessageTemplate,rootMessageId:r.rootMessageId,parentMessageId:r.parentMessageId,translationTargetLanguages:r._translationTargetLanguages,messageParams:r,callback:function(e,n){o?t(e,n):t(n,e)}})):(o?t(me.error,null):t(null,me.error),null)}},{key:"_autoResendUserMessage",value:function(e){var t=this,n=wi.getInstance(this._iid);if(n&&n.currentUser){var r=e._messageParams;return new Promise((function(n,i){return t._sendUserMessage(l(l({},r),{},{reqId:e.reqId,metaArrays:r.metaArrays,mentionType:r.mentionType,mentionedUserIds:r._mentionedUserIds,rootMessageId:r.rootMessageId,parentMessageId:r.parentMessageId,translationTargetLanguages:r._translationTargetLanguages,pushNotificationDeliveryOption:r.pushNotificationDeliveryOption,messageParams:r,oldMessage:e,callback:function(e,t){e?i(e):n(t)}}))}))}}},{key:"_autoResendFileMessage",value:function(e){var t=wi.getInstance(this._iid);if(t&&t.currentUser){var n=this._parsePendingFileMessage(e),r=x.get(this._iid).FileMessageQueue;r.create(this).addJob(new r.Job({fileInfo:n,pendingMessage:e._clone(),requestId:e.reqId,error:n.error,response:null}))}}},{key:"resendUserMessage",value:function(e,t){var n=this,r=x.get(this._iid),i=r.UserMessage,s=r.UserMessageParams,a=null,o=me.parse(arguments,[new me({type:i,constraint:function(e){return 0===e.messageId&&e.isResendable()&&e.reqId&&e.channelUrl===n.url&&"string"==typeof e.message&&"string"==typeof e.data&&"string"==typeof e.customType&&"object"===u(e.translations)&&!Array.isArray(e.translations)}}),new me({type:"callback"})]),c=C(o,3);return a=c[0],e=c[1],t=c[2],oe(this._iid,(function(t){if(a)a.message+=" Please check if the failed message is resend-able with `message.isResendable().`",t(a,null);else{var r=Object.keys(e.translations),i=s.PushNotificationDeliveryOption.DEFAULT;n._sendUserMessage(l(l({},e),{},{mentionedUserIds:e.requestedMentionUserIds,translationTargetLanguages:r,pushNotificationDeliveryOption:i,reqId:e.reqId,messageParams:e._messageParams,isManualResend:!0,callback:t}))}}),t)}},{key:"updateUserMessage",value:function(e,t,n,r,i){var s=this,a=x.get(this._iid),o=a.Command,u=a.UserMessage,c=a.UserMessageParams,d=arguments,h=null,p=null;if("number"==typeof e)switch(d.length){case 3:var f=me.parse(d,[new me({type:"number"}),new me({type:c}),new me({type:"callback"})]),_=C(f,4);h=_[0],e=_[1],p=_[2],i=_[3];break;case 5:p=new c;var g=me.parse(d,[new me({type:"number"}),new me({type:"string",nullable:!0}),new me({type:"string",nullable:!0}),new me({type:"string",nullable:!0}),new me({type:"callback"})]),y=C(g,6);h=y[0],e=y[1],t=y[2],n=y[3],r=y[4],i=y[5],p.message=t,p.data=n,p.customType=r}return oe(this._iid,(function(t){if(!h&&p&&p._validate()){var n=o.bUpdateUserMessage(l(l({channelUrl:s.url,messageId:e},p),{},{mentionType:p._mentionType,mentionedUserIds:p._mentionedUserIds,mentionedMessageTemplate:p.mentionedMessageTemplate})),r=wi.getInstance(s._iid);r.sendCommand(n,(function(e,n){if(r.getErrorFirstCallback()){var i=[e,n];n=i[0],e=i[1]}var a=null;if(!n&&(a=new u(l(l({},e.getJsonElement()),{},{messageParams:p})),s.isGroupChannel())){var o=!1;s.lastMessage?(s.lastMessage.createdAt=0}}),new me({type:"string",nullable:!0}),new me({type:"string",nullable:!0}),new me({type:"array"})]),8);i.error=s[0],i.file=s[1],i.name=s[2],i.type=s[3],i.size=s[4],i.data=s[5],i.customType=s[6],i.thumbnailSizes=s[7];var a=se.isFile(i.file);a&&(i.name=i.name||i.file.name,i.type=i.type||i.file.type,i.size=i.size||i.file.size),i.messageParams={mentionType:n.MentionType.USERS,mentionedUserIds:i.mentionedUserIds,cachedMentionedUsers:[],cachedMentionedUserIds:[],metaArrays:i.metaArrays,parentMessageId:i.parentMessageId,pushNotificationDeliveryOption:i.pushNotificationDeliveryOption,appleCriticalAlertOptions:i.appleCriticalAlertOptions,fileName:i.name,mimeType:i.type,fileSize:i.size,data:i.data,customType:i.customType,isUpdate:!1,file:a?i.file:null,fileUrl:a?null:i.file,thumbnailSizes:i.thumbnailSizes}}else i.error=me.error;return se.isFile(i.file)&&(i.name=i.name||i.file.name,i.type=i.type||i.file.type,i.size=i.size||i.file.size),i}},{key:"_createTempFileMessage",value:function(e){try{var t,n=wi.getInstance(this._iid),r=x.get(this._iid),i=r.Command,s=r.FileMessage,a=l(l({},e),{},{messageId:0,reqId:null!==(t=e.reqId)&&void 0!==t?t:i.generateRequestId(),user:n.currentUser||{},channel:this,plainUrl:"string"==typeof e.file?e.file:"",thumbnails:e.thumbnailSizes.map((function(e){return{url:"",plainUrl:"",width:e.maxWidth,height:e.maxHeight,real_width:0,real_height:0}})),sendingStatus:n.MessageSendingStatus.PENDING,createdAt:(new Date).getTime()}),o=s.objectify(a);return new s(o)}catch(e){return null}}},{key:"sendFileMessage",value:function(){var e=this,t=me.toArray(arguments),n=this._parseFileMessageArguments(t),r=x.get(this._iid),i=r.Command,s=null,a=i.generateRequestId();n.error||((s=this._createTempFileMessage(n)).requestedMentionUserIds=n.mentionedUserIds,a=s.reqId);var o=wi.getInstance(this._iid);if(o&&o.currentUser||(n.error=new H("Connection should be made first.",H.CONNECTION_REQUIRED)),this.isGroupChannel()){var l=ot.of(this._iid),u=ge.of(this._iid);l.upsert([s],Je.UNSENT).then((function(){u.send({source:de.LOCAL_MESSAGE_PENDING_CREATED,payload:{channel:e,message:s}})}))}var c=x.get(this._iid),d=c.FileMessageQueue,h=d.create(this);return h.addJob(new d.Job({fileInfo:n,pendingMessage:s,requestId:a,error:n.error,response:null})),s}},{key:"sendFileMessages",value:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=n.progress?n.progress:function(){},i=n.sent?n.sent:function(){},s=n.complete?n.complete:function(){};if(Array.isArray(e)&&e.length>0&&e.length<=20){var a=[];return e.forEach((function(n,o){a.push(t.sendFileMessage(n,r,(function(t,n){i(t,n),o===e.length-1&&s(null)})))})),a}return s(me.error),null}},{key:"resendFileMessage",value:function(e,t,n){var r=this,i=x.get(this._iid),s=i.FileMessage,a=i.FileMessageParams,o=null,l=me.parse(arguments,[new me({type:s,constraint:function(e){return 0===e.messageId&&e.isResendable()&&e.reqId&&e.channelUrl===r.url&&Array.isArray(e.thumbnails)}}),new me({type:"file",optionalIf:function(e){var t,n,r=!!e[0].plainUrl,i=se.isFile(null===(t=e[0])||void 0===t||null===(n=t.messageParams)||void 0===n?void 0:n.file);return r||i},defaultValue:null}),new me({type:"callback"})]),u=C(l,4);return o=u[0],e=u[1],t=u[2],n=u[3],oe(this._iid,(function(n){if(o)o.message+=" Please check if the failed message is resend-able with `message.isResendable().`",n(o,null);else{var i,s=new a;s._reqId=e.reqId,e.plainUrl?s.fileUrl=e.plainUrl:t?s.file=t:se.isFile(null===(i=e.messageParams)||void 0===i?void 0:i.file)&&(s.file=e.messageParams.file),s.fileName=e.name,s.fileSize=e.size,s.mimeType=e.type,s.data=e.data,s.customType=e.customType,s.mentionType=e.mentionType,s.mentionedUserIds=e.requestedMentionUserIds,s.metaArrays=e.metaArrays,s.thumbnailSizes=e.thumbnails.map((function(e){return{maxWidth:e.width,maxHeight:e.height}})),s.appleCriticalAlertOptions=e.appleCriticalAlertOptions,r.sendFileMessage(s,n)}}),n)}},{key:"updateFileMessage",value:function(e,t,n,r){var i=this,s=x.get(this._iid),a=s.Command,o=s.FileMessage,u=s.FileMessageParams,c=arguments,d=null,h=null;if("number"==typeof e)switch(c.length){case 3:var p=me.parse(c,[new me({type:"number"}),new me({type:u}),new me({type:"callback"})]),f=C(p,4);d=f[0],e=f[1],h=f[2],r=f[3],h&&(h._isUpdate=!0);break;case 4:h=new u;var _=me.parse(c,[new me({type:"number"}),new me({type:"string",nullable:!0}),new me({type:"string",nullable:!0}),new me({type:"callback"})]),g=C(_,5);d=g[0],e=g[1],t=g[2],n=g[3],r=g[4],h.data=t,h.customType=n,h._isUpdate=!0}return oe(this._iid,(function(t){if(!d&&h&&h._validate()){var n=a.bUpdateFileMessage(l(l({channelUrl:i.url,messageId:e},h),{},{mentionType:h._mentionType,mentionedUserIds:h._mentionedUserIds})),r=wi.getInstance(i._iid);r.sendCommand(n,(function(e,n){if(r.getErrorFirstCallback()){var s=[e,n];n=s[0],e=s[1]}var a=null;if(!n&&(a=new o(l(l({},e.getJsonElement()),{},{messageParams:h})),i.isGroupChannel())){var u=!1;i.lastMessage?(i.lastMessage.createdAt0}}),new me({type:"callback"})]),c=C(u,4);return o=c[0],e=c[1],t=c[2],n=c[3],oe(this._iid,(function(n){o?n(o,null):e.sendingStatus===i.MessageSendingStatus.SUCCEEDED?O.get(r._iid).container.apiClient.addReaction({isGroupChannel:e.isGroupChannel(),channelUrl:e.channelUrl,messageId:e.messageId,key:t},(function(t,r){var i=null;t||(i=a.createFromJson(l(l({},r),{},{msg_id:e.messageId}))),n(t,i)})):n(new H("Cannot add reaction to a non-succeeded message.",H.REQUEST_FAILED),null)}),n)}},{key:"deleteReaction",value:function(e,t,n){var r=this,i=wi.getInstance(this._iid),s=x.get(this._iid),a=s.ReactionEvent,o=null,u=me.parse(arguments,[new me({type:pt}),new me({type:"string",constraint:function(e){return e.length>0}}),new me({type:"callback"})]),c=C(u,4);return o=c[0],e=c[1],t=c[2],n=c[3],oe(this._iid,(function(n){o?n(o,null):e.sendingStatus===i.MessageSendingStatus.SUCCEEDED?O.get(r._iid).container.apiClient.deleteReaction({isGroupChannel:e.isGroupChannel(),channelUrl:e.channelUrl,messageId:e.messageId,key:t},(function(t,r){var i=null;t||(i=a.createFromJson(l(l({},r),{},{msg_id:e.messageId}))),n(t,i)})):n(new H("Cannot remove reaction to a non-succeeded message.",H.REQUEST_FAILED),null)}),n)}},{key:"deleteMessage",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"object",constraint:function(e){return!Array.isArray(e)&&null!==e&&e.hasOwnProperty("messageId")}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.deleteMessage({channelUrl:n.url,isOpenChannel:n.isOpenChannel(),messageId:e.messageId},(function(r,i){if(!r&&n.isGroupChannel()){var s=ot.of(n._iid),a=ge.of(n._iid);s.remove([e.messageId],Je.SUCCEEDED).then((function(){a.send({source:de.EVENT_MESSAGE_DELETED,payload:{channel:n,message:e}})})).catch((function(e){return J.error(e)}))}t(r,null)}))}),t)}},{key:"copyUserMessage",value:function(t,n,r){var i=x.get(this._iid);i.Command;var s=i.UserMessage,a=i.BaseMessageParams,o=null,u=me.parse(arguments,[new me({type:e}),new me({type:s}),new me({type:"callback"})]),c=C(u,4);o=c[0],t=c[1],n=c[2],r=c[3];var d=O.get(this._iid),h=d.container.isErrorFirstInCallback;if(o)return h?r(me.error,null):r(null,me.error),null;if(this.url!==n.channelUrl){var p=new H("The message does not belong to this channel",H.INVALID_PARAMETER);return h?r(p,null):r(null,p),null}var f=Object.keys(n.translations);f.forEach((function(e){return""}));var _=a.PushNotificationDeliveryOption.DEFAULT;return t._sendUserMessage(l(l({},n),{},{reqId:null,pushNotificationDeliveryOption:_,translationTargetLanguages:f,rootMessageId:null,parentMessageId:null,parentMessageText:null,messageParams:n._messageParams,callback:r}))}},{key:"copyFileMessage",value:function(t,n,r){var i=this,s=x.get(this._iid),a=s.Command;s.GroupChannel;var o=s.FileMessage,l=s.BaseMessageParams;s.FileMessageParams;var u=s.User,c=null,d=me.parse(arguments,[new me({type:e}),new me({type:o}),new me({type:"callback"})]),h=C(d,4);c=h[0],t=h[1],n=h[2],r=h[3];var p=O.get(this._iid),f=p.container.isErrorFirstInCallback;if(c)return f?r(me.error,null):r(null,me.error),null;if(this.url!==n.channelUrl){var _=new H("The message does not belong to this channel");return f?r(_,null):r(null,_),null}var g=wi.getInstance(this._iid),y=n,m=y.url,E=y.name,v=y.type,b=y.size,A=y.data,N=y.customType,S=y.mentionType,I=y.mentionedUserIds,T=y.mentionedUsers,U=y.metaArrays,M=y.thumbnails,k=y.requireAuth,R=y.messageSurvivalSeconds,L=y.silent,w=y.appleCriticalAlertOptions,P=a.generateRequestId(),D=g.currentUser||{},F=t.url,G=t.isOpenChannel(),j=T.filter((function(e){return new u(u.objectify(e))})),B=l.PushNotificationDeliveryOption.DEFAULT,V=o.objectify({messageId:0,reqId:P,user:D,channel:t,plainUrl:m,name:E,type:v,size:b,data:A,customType:N,mentionType:S,mentionedUserIds:I,mentionedUsers:j,requestedMentionUserIds:I,metaArrays:U,thumbnails:M,requireAuth:k,messageSurvivalSeconds:R,silent:L,createdAt:(new Date).getTime(),appleCriticalAlertOptions:w}),q=new o(V);if(q.requestState=g.MessageRequestState.PENDING,q.sendingStatus=g.MessageSendingStatus.PENDING,!g.currentUser){var K=new H("Connection should be made first.",H.CONNECTION_REQUIRED),z=new o(V);return z.requestState=g.MessageRequestState.FAILED,z.sendingStatus=g.MessageSendingStatus.FAILED,z.errorCode=K.code,f?r(K,z):r(z,K),q}var Y=a.bFile({requestId:P,channelUrl:F,url:m,name:E,type:v,size:b,data:A,customType:N,metaArrays:U,mentionType:S,mentionedUserIds:I,thumbnailSizes:M,requireAuth:k,pushNotificationDeliveryOption:B,silent:L,appleCriticalAlertOptions:w});return g.getConnectionState()===g.ConnectionState.OPEN||g.connecting||g.reconnecting?g.sendCommand(Y,(function(e,n){if(g.getErrorFirstCallback()){var s=[e,n];n=s[0],e=s[1]}if(n)if(n.code!==H.INVALID_PARAMETER){var a=new o(V);a.requestState=g.MessageRequestState.FAILED,a.sendingStatus=g.MessageSendingStatus.FAILED,n.code!==H.FILE_UPLOAD_CANCEL_FAILED&&n.code!==H.REQUEST_CANCELED||(a.sendingStatus=g.MessageSendingStatus.CANCELED),a.errorCode=n.code,f?r(n,a):r(a,n)}else f?r(n,null):r(null,n);else{var l=new o(e.getJsonElement()),u=l._sender;if(D&&u&&D.userId===u.userId&&(D.nickname!==u.nickname&&(D.nickname=u.nickname),D.plainProfileUrl!==u.plainProfileUrl&&(D.plainProfileUrl=u.plainProfileUrl)),t.isGroupChannel()){t.lastMessage=l,Object.keys(g.channelHandlers).forEach((function(e){g.channelHandlers[e].onChannelChanged(t)}));var c=ge.of(i._iid);$e.of(i._iid).upsert([t]).then((function(){c.send({source:de.EVENT_CHANNEL_CHANGED,payload:{channel:t}})})).catch((function(e){return J.error(e)})),ot.of(i._iid).upsert([l]).then((function(){c.send({source:de.EVENT_MESSAGE_SENT,payload:{channel:i,message:l}})})).catch((function(e){return J.error(e)}))}f?r(null,l):r(l,null)}})):p.container.apiClient.sendFileMessage({channelUrl:F,isOpenChannel:G,fileUrl:m,fileName:E,fileType:v,fileSize:b,data:A,customType:N,metaArrays:U,mentionType:S,mentionedUserIds:I,thumbnailSizes:M,requireAuth:k,pushNotificationDeliveryOption:B,appleCriticalAlertOptions:w},(function(e,n){if(e)if(e.code!==H.INVALID_PARAMETER){var i=new o(commnad.getJsonElement());i.requestState=g.MessageRequestState.FAILED,i.sendingStatus=g.MessageSendingStatus.FAILED,e.code!==H.FILE_UPLOAD_CANCEL_FAILED&&e.code!==H.REQUEST_CANCELED||(i.sendingStatus=g.MessageSendingStatus.CANCELED),i.errorCode=e.code,f?r(e,i):r(i,e)}else f?r(e,null):r(null,e);else{var s=new o(n),a=s._sender;D&&a&&D.userId===a.userId&&(D.nickname!==a.nickname&&(D.nickname=a.nickname),D.plainProfileUrl!==a.plainProfileUrl&&(D.plainProfileUrl=a.plainProfileUrl)),t.isGroupChannel()&&(t.lastMessage=s,Object.keys(g.channelHandlers).forEach((function(e){g.channelHandlers[e].onChannelChanged(t)}))),f?r(null,s):r(s,null)}})),q}},{key:"addOperators",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"array",constraint:function(e){return Object.keys(e).map((function(t){return e[t]})).every((function(e){return"string"==typeof e}))}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.addOperators({channelUrl:n.url,isOpenChannel:n.isOpenChannel(),operatorUserIds:e},(function(e,n){return t(e,n)}))}),t)}},{key:"removeOperators",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"array",constraint:function(e){return Object.keys(e).map((function(t){return e[t]})).every((function(e){return"string"==typeof e}))}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.removeOperators({channelUrl:n.url,isOpenChannel:n.isOpenChannel(),operatorUserIds:e},(function(e,n){return t(e,n)}))}),t)}},{key:"getMetaCounters",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"array",constraint:function(e){return Object.keys(e).map((function(t){return e[t]})).every((function(e){return"string"==typeof e}))}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.getMetaCounters({channelUrl:n.url,isOpenChannel:n.isOpenChannel(),keys:e},(function(e,n){return t(e,n)}))}),t)}},{key:"getAllMetaCounters",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.getMetaCounters({channelUrl:t.url,isOpenChannel:t.isOpenChannel(),keys:[]},(function(t,n){return e(t,n)}))}),e)}},{key:"createMetaCounters",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"object",constraint:function(e){return e&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.keys(e).map((function(t){return e[t]})).every((function(e){return"number"==typeof e}))}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.createMetaCounters({channelUrl:n.url,isOpenChannel:n.isOpenChannel(),metaCounter:e},(function(e,n){return t(e,n)}))}),t)}},{key:"updateMetaCounters",value:function(e,t,n){var r=this,i=null,s=me.parse(arguments,[new me({type:"object",constraint:function(e){return e&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.keys(e).map((function(t){return e[t]})).every((function(e){return"number"==typeof e}))}}),new me({type:"boolean",optional:!0,defaultValue:!1}),new me({type:"callback"})]),a=C(s,4);return i=a[0],e=a[1],t=a[2],n=a[3],oe(this._iid,(function(n){i?n(i,null):O.get(r._iid).container.apiClient.updateMetaCounters({channelUrl:r.url,isOpenChannel:r.isOpenChannel(),metaCounter:e,upsert:t,mode:"set"},(function(e,t){return n(e,t)}))}),n)}},{key:"increaseMetaCounters",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"object",constraint:function(e){return e&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.keys(e).map((function(t){return e[t]})).every((function(e){return"number"==typeof e}))}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.updateMetaCounters({channelUrl:n.url,isOpenChannel:n.isOpenChannel(),metaCounter:e,upsert:!1,mode:"increase"},(function(e,n){return t(e,n)}))}),t)}},{key:"decreaseMetaCounters",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"object",constraint:function(e){return e&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.keys(e).map((function(t){return e[t]})).every((function(e){return"number"==typeof e}))}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.updateMetaCounters({channelUrl:n.url,isOpenChannel:n.isOpenChannel(),metaCounter:e,upsert:!1,mode:"decrease"},(function(e,n){var r=null;e||(r={},Object.keys(n).forEach((function(e){r[e]=n[e]}))),t(e,r)}))}),t)}},{key:"deleteMetaCounter",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"string"}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.deleteMetaCounter({channelUrl:n.url,isOpenChannel:n.isOpenChannel(),key:e},(function(e,n){return t(e,n)}))}),t)}},{key:"deleteAllMetaCounters",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.deleteAllMetaCounters({channelUrl:t.url,isOpenChannel:t.isOpenChannel()},(function(t,n){return e(t,n)}))}),e)}},{key:"getCachedMetaData",value:function(){var e=Mt.get(this),t={};return Object.keys(e).forEach((function(n){var r=e[n];r.isRemoved||(t[n]=r.value)})),t}},{key:"getMetaData",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"array",constraint:function(e){return Object.keys(e).map((function(t){return e[t]})).every((function(e){return"string"==typeof e}))}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.getMetaData({channelUrl:n.url,isOpenChannel:n.isOpenChannel(),keys:e},(function(e,r){if(r&&r.ts){var i=r.metadata;n._addOrUpdateCachedMetaData(i,r.ts),t(e,i)}else t(e,r)}))}),t)}},{key:"getAllMetaData",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.getMetaData({channelUrl:t.url,isOpenChannel:t.isOpenChannel(),keys:[]},(function(n,r){if(r&&r.ts){var i=r.metadata;t._refreshMetaData(i,r.ts),e(n,i)}else e(n,r)}))}),e)}},{key:"createMetaData",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"object",constraint:function(e){return e&&!Array.isArray(e)&&Object.keys(e).length>0}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.createMetaData({channelUrl:n.url,isOpenChannel:n.isOpenChannel(),metaData:e},(function(e,n){t(e,n&&n.ts?n.metadata:n)}))}),t)}},{key:"updateMetaData",value:function(e,t,n){var r=this,i=null,s=me.parse(arguments,[new me({type:"object",constraint:function(e){return e&&!Array.isArray(e)&&Object.keys(e).length>0}}),new me({type:"boolean",optional:!0,defaultValue:!1}),new me({type:"callback"})]),a=C(s,4);return i=a[0],e=a[1],t=a[2],n=a[3],oe(this._iid,(function(n){i?n(i,null):O.get(r._iid).container.apiClient.updateMetaData({channelUrl:r.url,isOpenChannel:r.isOpenChannel(),metaData:e,upsert:t},(function(e,t){n(e,t&&t.ts?t.metadata:t)}))}),n)}},{key:"deleteMetaData",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"string"}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.deleteMetaData({channelUrl:n.url,isOpenChannel:n.isOpenChannel(),key:e},(function(e,n){t(e,n&&n.ts?{}:n)}))}),t)}},{key:"deleteAllMetaData",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.deleteAllMetaData({channelUrl:t.url,isOpenChannel:t.isOpenChannel()},(function(t,n){return e(t,n&&n.ts?{}:n)}))}),e)}},{key:"_updateMessageMetaArray",value:function(e,t,n,r){var i=this;return oe(this._iid,(function(r){var s=x.get(i._iid),a=s.Command,o=s.UserMessage,l=s.FileMessage,u=s.AdminMessage,c=null;if(t.isUserMessage()?c=a.bUpdateUserMessage({channelUrl:e,messageId:t.messageId,metaArrayParams:n}):t.isFileMessage()&&(c=a.bUpdateFileMessage({channelUrl:e,messageId:t.messageId,metaArrayParams:n})),c){var d=wi.getInstance(i._iid);d.sendCommand(c,(function(e,n){if(d.getErrorFirstCallback()){var i=[e,n];n=i[0],e=i[1]}var s=null;n||(t.isUserMessage()?s=new o(e.getJsonElement()):t.isFileMessage()?s=new l(e.getJsonElement()):t.isAdminMessage()&&(s=new u(e.getJsonElement()))),r(n,s)}))}else r(me.error,null)}),r)}},{key:"createMessageMetaArrayKeys",value:function(e,t,n){var r=x.get(this._iid),i=r.MessageMetaArray,s=null,a=me.parse(arguments,[new me({type:pt}),new me({type:"array",constraint:function(e){return e.every((function(e){return"string"==typeof e&&""!==e}))}}),new me({type:"callback"})]),o=C(a,4);if(s=o[0],e=o[1],t=o[2],n=o[3],s)return oe(this._iid,(function(e){e(s,null)}),n);var l=[];if(Array.isArray(t))for(var u=0;u0&&e.every((function(e){return e instanceof i}))||Object.keys(e).length>0&&Object.keys(e).every((function(t){return Array.isArray(e[t])&&e[t].length>0&&e[t].every((function(e){return"string"==typeof e&&e.length>0}))})))}}),new me({type:"callback"})]),o=C(a,4);if(s=o[0],e=o[1],t=o[2],n=o[3],s)return oe(this._iid,(function(e){e(s,null)}),n);var l=Array.isArray(t)?t.map((function(e){return e.encode()})):Object.keys(t).map((function(e){return{key:e,value:t[e]}}));return this._updateMessageMetaArray(this.url,e,{array:l,mode:"add",upsert:!0},n)}},{key:"removeMessageMetaArrayValues",value:function(e,t,n){var r=x.get(this._iid),i=r.MessageMetaArray,s=null,a=me.parse(arguments,[new me({type:pt}),new me({type:"object",constraint:function(e){return e&&(Array.isArray(e)&&e.length>0&&e.every((function(e){return e instanceof i}))||Object.keys(e).length>0&&Object.keys(e).every((function(t){return Array.isArray(e[t])&&e[t].length>0&&e[t].every((function(e){return"string"==typeof e&&e.length>0}))})))}}),new me({type:"callback"})]),o=C(a,4);if(s=o[0],e=o[1],t=o[2],n=o[3],s)return oe(this._iid,(function(e){e(s,null)}),n);var l=Array.isArray(t)?t.map((function(e){return e.encode()})):Object.keys(t).map((function(e){return{key:e,value:t[e]}}));return this._updateMessageMetaArray(this.url,e,{array:l,mode:"remove",upsert:!0},n)}},{key:"report",value:function(e,t,n){var r=this,i=x.get(this._iid),s=i.BaseChannel,a=null,o=me.parse(arguments,[new me({type:s.ReportCategory}),new me({type:"string"}),new me({type:"callback"})]),l=C(o,4);return a=l[0],e=l[1],t=l[2],n=l[3],oe(this._iid,(function(n){if(a)n(a,null);else{var i=wi.getInstance(r._iid);O.get(r._iid).container.apiClient.report({channelUrl:r.url,isOpenChannel:r.isOpenChannel(),reportCategory:e,reportingUserId:i.currentUser?i.currentUser.userId:null,reportDescription:t},(function(e,t){n(e,null)}))}}),n)}},{key:"reportUser",value:function(e,t,n,r){var i=this,s=x.get(this._iid),a=s.BaseChannel,o=null,l=me.parse(arguments,[new me({type:ft}),new me({type:a.ReportCategory}),new me({type:"string"}),new me({type:"callback"})]),u=C(l,5);return o=u[0],e=u[1],t=u[2],n=u[3],r=u[4],oe(this._iid,(function(r){if(o)r(o,null);else{var s=wi.getInstance(i._iid);O.get(i._iid).container.apiClient.reportUser({channelUrl:i.url,isOpenChannel:i.isOpenChannel(),reportCategory:t,offendingUserId:e.userId,reportingUserId:s.currentUser?s.currentUser.userId:null,reportDescription:n},(function(e,t){r(e,null)}))}}),r)}},{key:"reportMessage",value:function(e,t,n,r){var i=this,s=x.get(this._iid),a=s.BaseChannel,o=null,l=me.parse(arguments,[new me({type:pt}),new me({type:a.ReportCategory}),new me({type:"string"}),new me({type:"callback"})]),u=C(l,5);return o=u[0],e=u[1],t=u[2],n=u[3],r=u[4],oe(this._iid,(function(r){if(o)r(o,null);else{var s=wi.getInstance(i._iid);O.get(i._iid).container.apiClient.reportMessage({messageId:e.messageId,channelUrl:i.url,isOpenChannel:i.isOpenChannel(),reportCategory:t,offendingUserId:e.sender.userId,reportingUserId:s.currentUser?s.currentUser.userId:null,reportDescription:n},(function(e,t){r(e,null)}))}}),r)}}],[{key:"CHANNEL_TYPE_OPEN",get:function(){return"open"}},{key:"CHANNEL_TYPE_GROUP",get:function(){return"group"}},{key:"CHANNEL_TYPE_BASE",get:function(){return"base"}},{key:"MessageTypeFilter",get:function(){return{ALL:"",USER:"MESG",FILE:"FILE",ADMIN:"ADMM"}}},{key:"ReportCategory",get:function(){return{SPAM:"spam",HARASSING:"harassing",SUSPICIOUS:"suspicious",INAPPROPRIATE:"inappropriate"}}},{key:"buildMessage",value:function(e,t){var n=x.get(this._iid),r=n.UserMessage,i=n.FileMessage,s=n.AdminMessage;if(e)switch(e.hasOwnProperty("channel_type")||(e.channel_type=t.channelType),e.type){case"MESG":return new r(e);case"FILE":var a=e.file;return new i(l(l({},e),{},{url:String(a.url),name:String(a.name),type:String(a.type),size:parseInt(a.size),data:String(a.data)}));case"BRDM":case"ADMM":return new s(e)}return null}}]),e}(),Lt=function(){function e(t){c(this,e),t&&(this.category=t.hasOwnProperty("cat")?parseInt(t.cat):0,this.data=t.hasOwnProperty("data")?t.data:null,this.channelUrl=t.hasOwnProperty("channel_url")?String(t.channel_url):"",this.channelType=t.hasOwnProperty("channel_type")?String(t.channel_type):Rt.CHANNEL_TYPE_GROUP,this.channel=t.hasOwnProperty("channel")?t.channel:null)}return h(e,[{key:"isGroupChannel",value:function(){return this.channelType===Rt.CHANNEL_TYPE_GROUP}},{key:"isOpenChannel",value:function(){return this.channelType===Rt.CHANNEL_TYPE_OPEN}}]),e}();Lt.CATEGORY_NONE=0,Lt.CATEGORY_CHANNEL_ENTER=10102,Lt.CATEGORY_CHANNEL_EXIT=10103,Lt.CATEGORY_USER_CHANNEL_MUTE=10201,Lt.CATEGORY_USER_CHANNEL_UNMUTE=10200,Lt.CATEGORY_USER_CHANNEL_BAN=10601,Lt.CATEGORY_USER_CHANNEL_UNBAN=10600,Lt.CATEGORY_CHANNEL_FREEZE=10701,Lt.CATEGORY_CHANNEL_UNFREEZE=10700,Lt.CATEGORY_TYPING_START=10900,Lt.CATEGORY_TYPING_END=10901,Lt.CATEGORY_CHANNEL_JOIN=1e4,Lt.CATEGORY_CHANNEL_LEAVE=10001,Lt.CATEGORY_CHANNEL_OPERATOR_UPDATE=10002,Lt.CATEGORY_CHANNEL_INVITE=10020,Lt.CATEGORY_CHANNEL_DECLINE_INVITE=10022,Lt.CATEGORY_CHANNEL_PROP_CHANGED=11e3,Lt.CATEGORY_CHANNEL_DELETED=12e3,Lt.CATEGORY_CHANNEL_META_DATA_CHANGED=11100,Lt.CATEGORY_CHANNEL_META_COUNTERS_CHANGED=11200,Lt.CATEGORY_CHANNEL_HIDE=13e3,Lt.CATEGORY_CHANNEL_UNHIDE=13001;var wt=h((function e(t){c(this,e),t&&(this.category=t.hasOwnProperty("cat")?parseInt(t.cat):0)}));wt.CATEGORY_USER_BLOCK=20001,wt.CATEGORY_USER_UNBLOCK=2e4,wt.CATEGORY_FRIEND_DISCOVERED=20900;var Pt=function(){function e(t){c(this,e),this.sb=t,this.cls=x.get(this.sb._iid)}return h(e,[{key:"onRawCommandReceived",value:function(e){var t=this,n=this.cls,r=n.Command,i=n.User,s=n.Member,a=n.RestrictedUser,o=n.BaseChannel,c=n.GroupChannel,d=n.OpenChannel,h=n.UserMessage,p=n.FileMessage,f=n.AdminMessage,_=n.BaseMessageParams,g=n.ReactionEvent,y=n.ReadStatus,m=n.ThreadInfoUpdateEvent,E=n.RestrictionInfo,v=O.get(this.sb._iid),b=v.container,C=b.pinger,A=b.auth,N=b.subscribedUnreadMessageCount,S=b.sessionManager,U=b.ackStateMap,M=new r(e),k=M.getJsonElement();if(k.hasOwnProperty("unread_cnt")&&"object"===u(k.unread_cnt)){var R=!1,L=k.unread_cnt.ts;"number"==typeof L&&L>N.ts&&(N.all!==k.unread_cnt.all&&(R=!0),N.all=k.unread_cnt.all>=0?k.unread_cnt.all:0,k.unread_cnt.custom_types&&Object.keys(k.unread_cnt.custom_types).forEach((function(e){N.custom_types[e]!==k.unread_cnt.custom_types[e]&&(R=!0),N.custom_types[e]=k.unread_cnt.custom_types[e]})),R=R&&N.ts>0,N.ts=L),R&&Object.keys(this.sb.userEventHandlers).forEach((function(e){t.sb.userEventHandlers[e].onTotalUnreadMessageCountUpdated(N.all,N.custom_types)}))}var w=M.requestId;if(w){var P=U[w];if(P){clearTimeout(P.timer);var D=P.handler;U.hasOwnProperty(w)&&delete U[w],D&&("EROR"===M.command?D(new H(k.message,k.code),null):D(null,M))}}else{C&&"LOGI"!==M.command&&C.refreshTimer();var F,G=$e.of(this.sb._iid),x=ot.of(this.sb._iid),j=ge.of(this.sb._iid);switch(M.command){case"LOGI":if(this.sb.loginTimer)if(clearTimeout(this.sb.loginTimer),this.sb.loginTimer=null,this.sb.onLoginTimerCancel=null,k.hasOwnProperty("error"))this.sb.isSessionOpened=!1,this.sb.loginHandler(new H(k.message,k.code),null);else{if(this.sb.isSessionOpened=!0,k.hasOwnProperty("key")&&(A.sessionKey=k.key),k.hasOwnProperty("ekey")&&(A.eKey=k.ekey),k.hasOwnProperty("user_id")&&(this.sb.currentUser=new i(k)),"number"==typeof k.ping_interval&&k.ping_interval>0&&v.set("pingInterval",1e3*k.ping_interval),"number"==typeof k.pong_timeout&&k.pong_timeout>0&&v.set("pongTimeout",1e3*k.pong_timeout),"number"==typeof k.login_ts){var B=1e3*k.login_ts;v.set("connectedAt",B);var V=v.container,q=V.firstConnectedAt,K=V.localCacheEnabled,z=V.store;if(!q){var Y=B;if(K){var Q=(F=this.sb.currentUser.userId,"sendbird:".concat(F,"@firstConnectedAt"));z.get(Q).then((function(e){e&&(Y=e.ts)})).catch((function(e){t.handleCacheError(e)})).finally((function(){v.set("firstConnectedAt",Y)}))}else v.set("firstConnectedAt",Y)}}if(k.hasOwnProperty("reconnect")&&"object"===u(k.reconnect)){var W=k.reconnect,X=v.container.wsAdapter;W.hasOwnProperty("interval")&&"number"==typeof W.interval&&(X.reconnectParams.interval=W.interval),W.hasOwnProperty("max_interval")&&"number"==typeof W.max_interval&&(X.reconnectParams.maxInterval=W.max_interval),W.hasOwnProperty("mul")&&"number"==typeof W.mul&&(X.reconnectParams.multiplier=W.mul),W.hasOwnProperty("retry_cnt")&&"number"==typeof W.retry_cnt&&(X.reconnectParams.retryCount=W.retry_cnt)}"number"==typeof k.max_unread_cnt_on_super_group?v.set("maxUnreadCountOfSuperGroupChannel",k.max_unread_cnt_on_super_group):v.set("maxUnreadCountOfSuperGroupChannel",T.DEFAULT_MAX_UNREAD_COUNT_OF_SUPER_GROUP_CHANNEL),k.profile_image_encryption&&v.set("profileImageEncryption",!0),C&&C.start(),k.hasOwnProperty("file_upload_size_limit")&&k.hasOwnProperty("premium_feature_list")&&k.hasOwnProperty("emoji_hash")&&v.set("appInfo",new Ie(k)),k.hasOwnProperty("concurrent_call_limit")&&k.hasOwnProperty("back_off_delay")&&(v.set("concurrentCallLimit",k.concurrent_call_limit),v.set("backOffDelay",k.back_off_delay)),this.sb.loginHandler(null,this.sb.currentUser)}break;case"EXPR":var Z=new H("The session would be expired.",k.reason||H.SESSION_KEY_EXPIRED);S.refreshSessionIfExpiredError(Z).then((function(){})).catch((function(){}));break;case"MESG":case"FILE":case"BRDM":case"ADMM":var $=null;if("MESG"===M.command?$=new h(k):"FILE"===M.command?$=new p(k):"BRDM"!==M.command&&"ADMM"!==M.command||($=new f(k)),$){var ee=this.sb.currentUser?this.sb.currentUser.userId:null,te=$.silent,ne=!!k.force_update_last_message,re=$._sender&&$._sender.userId===ee;if($.isGroupChannel()){var ie=c.cachedChannels.hasOwnProperty($.channelUrl);c.getChannel($.channelUrl,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var i=[e,n];n=i[0],e=i[1]}if(!n){if(!v.container.appInfo.isSupergroupMackDisabled||!e.isSuper||e.isBroadcast){var s=r.bMessageAck({channelUrl:$.channelUrl,messageId:$.messageId});t.sb.sendCommand(s)}if(e.isHidden=!1,e.hiddenState=c.HiddenState.UNHIDDEN,c.cachedChannels[e.url]=e,$._sender&&e.memberMap.hasOwnProperty($._sender.userId)){var a=e.memberMap[$._sender.userId];a.nickname!==$._sender.nickname&&(a.nickname=$._sender.nickname),a.plainProfileUrl!==$._sender.plainProfileUrl&&(a.plainProfileUrl=$._sender.plainProfileUrl),se.deepEqual(a.metaData,$._sender.metaData)||(a.metaData=$._sender.metaData),a.isBlockedByMe!==$._sender.isBlockedByMe&&(a.isBlockedByMe=$._sender.isBlockedByMe)}var o=t.sb.currentUser;o&&re&&(o.nickname!==$._sender.nickname&&(o.nickname=$._sender.nickname),o.plainProfileUrl!==$._sender.plainProfileUrl&&(o.plainProfileUrl=$._sender.plainProfileUrl),se.deepEqual(o.metaData,$._sender.metaData)||(o.metaData=$._sender.metaData));var l=!1;if($.mentionType===_.MentionType.CHANNEL)re||(l=!0);else if($.mentionType===_.MentionType.USERS)for(var u=0;u<$.mentionedUsers.length;u++)if(!re&&$.mentionedUsers[u].userId===ee){l=!0;break}te&&!re||(e.isEphemeral||ie)&&((!e.lastMessage||e.lastMessage.createdAt<$.createdAt)&&(e.lastMessage=$),re||e._setGroupChannelUnreadCount(e.unreadMessageCount+1,e.unreadMentionCount+(l?1:0))),ne&&(!e.lastMessage||e.lastMessage.createdAt<$.createdAt)&&(e.lastMessage=$),te&&!re||(G.upsert([e]).then((function(){j.send({source:de.EVENT_CHANNEL_CHANGED,payload:{channel:e}})})).catch((function(e){t.handleCacheError(e)})),Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onChannelChanged(e)}))),Object.keys(t.sb.channelHandlers).forEach((function(n){var r=t.sb.channelHandlers[n];r.onMessageReceived(e,$),l&&r.onMentionReceived(e,$)})),x.upsert([$]).then((function(){j.send({source:de.EVENT_MESSAGE_RECEIVED,payload:{channel:e,message:$}})})).catch((function(e){t.handleCacheError(e)}))}}))}else $.isOpenChannel()&&d.getChannel($.channelUrl,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}if(!n){var i=!1;if($.mentionType===_.MentionType.CHANNEL)i=!0;else if($.mentionType===_.MentionType.USERS)for(var s=0;s<$.mentionedUsers.length;s++)if($.mentionedUsers[s].userId===ee){i=!0;break}Object.keys(t.sb.channelHandlers).forEach((function(n){var r=t.sb.channelHandlers[n];d.enteredChannels[e.url]&&r.onMessageReceived(e,$),i&&r.onMentionReceived(e,$)})),d.enteredChannels[e.url]&&j.send({source:de.EVENT_MESSAGE_RECEIVED,payload:{channel:e,message:$}})}}))}break;case"MEDI":case"FEDI":case"AEDI":var ae=null;if("MEDI"===M.command?ae=new h(k):"FEDI"===M.command?ae=new p(k):"AEDI"===M.command&&(ae=new f(k)),ae){var oe=this.sb.currentUser?this.sb.currentUser.userId:null,le=ae.silent,ue=ae.sender&&ae.sender.userId===oe;if(ae.isGroupChannel()){var ce=c.cachedChannels.hasOwnProperty(ae.channelUrl);c.getChannel(ae.channelUrl,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}if(!n){var i=e.cachedReadReceiptStatus[oe],s=i&&i>=ae.createAt,a=t.sb.currentUser;a&&ue&&(a.nickname!==ae._sender.nickname&&(a.nickname=ae._sender.nickname),a.plainProfileUrl!==ae._sender.plainProfileUrl&&(a.plainProfileUrl=ae._sender.plainProfileUrl),se.deepEqual(a.metaData,ae._sender.metaData)||(a.metaData=ae._sender.metaData));var o=!1,l=!1;if(!ue&&!s&&k&&k.hasOwnProperty("old_values")){var u=k.old_values.mention_type||ae.mentionType,c=k.old_values.mentioned_user_ids||ae.mentionedUsers.map((function(e){return e.userId}));if(u===_.MentionType.USERS&&ae.mentionType===_.MentionType.USERS){for(var d=!1,h=!1,p=0;p0||e.unreadMentionCount>0)&&(e._setGroupChannelUnreadCount(0,0),Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onChannelChanged(e)})),G.upsert([e]).then((function(){j.send({source:de.EVENT_CHANNEL_CHANGED,payload:{channel:e}})})).catch((function(e){t.handleCacheError(e)}))):0!==e.unreadMessageCount&&0!==e.unreadMentionCount||(Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onChannelChanged(e)})),G.upsert([e]).then((function(){j.send({source:de.EVENT_CHANNEL_CHANGED,payload:{channel:e}})})).catch((function(e){t.handleCacheError(e)}))):Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onReadReceiptUpdated(e)})),j.send({source:de.EVENT_READ_RECEIPT_UPDATED,payload:{channel:e,user:_e.reader}})))}));break;case"MRCT":var me=String(k.channel_type),Ee=String(k.channel_url),ve=g.createFromJson(k);switch(me){case o.CHANNEL_TYPE_GROUP:c.getChannel(Ee,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}n?J.debug("Discard command:","`".concat(M.command,"`")):(Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onReactionUpdated(e,ve)})),x.get("".concat(ve.messageId)).then((function(n){n&&(n.applyReactionEvent(ve),x.upsert([n]).then((function(){j.send({source:de.EVENT_REACTION_UPDATED,payload:{channel:e,reactionEvent:ve}})})).catch((function(e){t.handleCacheError(e)})))})).catch((function(e){t.handleCacheError(e)})))}));break;case o.CHANNEL_TYPE_OPEN:d.getChannel(Ee,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}n?J.debug("Discard command:","`".concat(M.command,"`")):(Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onReactionUpdated(e,ve)})),j.send({source:de.EVENT_REACTION_UPDATED,payload:{channel:e,reactionEvent:ve}}))}))}break;case"DLVR":var be=String(k.channel_url),Ce=k.hasOwnProperty("updated")?k.updated:null,Ae=c.cachedChannels.hasOwnProperty(be);c.getChannel(be,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}if(!n){var i=!1;Object.keys(Ce).forEach((function(n){t.sb.currentUser&&n===t.sb.currentUser.userId&&(i=!0),Ae&&e.updateDeliveryReceipt(n,parseInt(Ce[n]))})),c.cachedChannels[e.url]=e,i&&1===Object.keys(Ce).length||(Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onDeliveryReceiptUpdated(e)})),j.send({source:de.EVENT_DELIVERY_RECEIPT_UPDATED,payload:{channel:e}}))}}));break;case"MTHD":var Ne=String(k.channel_url),Se=String(k.channel_type),Te=m.createFromJson(k);switch(Se){case o.CHANNEL_TYPE_GROUP:c.getChannel(Ne,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}n||(Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onThreadInfoUpdated(e,Te)})),x.get("".concat(Te.targetMessageId)).then((function(n){n&&(n.applyThreadInfoUpdateEvent(Te),x.upsert([n]).then((function(){j.send({source:de.EVENT_THREAD_INFO_UPDATED,payload:{channel:e,threadInfoUpdateEvent:Te}})})).catch((function(e){t.handleCacheError(e)})))})).catch((function(e){t.handleCacheError(e)})))}));break;case o.CHANNEL_TYPE_OPEN:d.getChannel(Ne,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}n||(Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onThreadInfoUpdated(e,Te)})),j.send({source:de.EVENT_THREAD_INFO_UPDATED,payload:{channel:e,threadInfoUpdateEvent:Te}}))}))}break;case"MCNT":if(k.hasOwnProperty("group_channels")&&Array.isArray(k.group_channels)){var Ue,Oe=[],Me=I(k.group_channels);try{for(Me.s();!(Ue=Me.n()).done;){var ke=Ue.value;if(ke){var Re=c.cachedChannels[ke.channel_url];if(Re&&Re.isBroadcast)Re.setLatestMemberCount(ke.member_count,ke.joined_member_count,ke.ts)&&Oe.push(Re)}}}catch(e){Me.e(e)}finally{Me.f()}Oe.length>0&&(Object.keys(this.sb.channelHandlers).forEach((function(e){t.sb.channelHandlers[e].onChannelMemberCountChanged(Oe)})),G.upsert(Oe).then((function(){var e,t=I(Oe);try{for(t.s();!(e=t.n()).done;){var n=e.value;j.send({source:de.EVENT_CHANNEL_CHANGED,payload:{channel:n}})}}catch(e){t.e(e)}finally{t.f()}})).catch((function(e){t.handleCacheError(e)})))}if(k.hasOwnProperty("open_channels")&&Array.isArray(k.open_channels)){var Le,we=[],Pe=I(k.open_channels);try{for(Pe.s();!(Le=Pe.n()).done;){var De=Le.value;if(De){var He=d.cachedChannels[De.channel_url];if(He)He.setLatestParticipantCount(De.participant_count,De.ts)&&we.push(He)}}}catch(e){Pe.e(e)}finally{Pe.f()}if(we.length>0){Object.keys(this.sb.channelHandlers).forEach((function(e){t.sb.channelHandlers[e].onChannelParticipantCountChanged(we)}));var Fe,Ge=I(we);try{for(Ge.s();!(Fe=Ge.n()).done;){var xe=Fe.value;j.send({source:de.EVENT_CHANNEL_CHANGED,payload:{channel:xe}})}}catch(e){Ge.e(e)}finally{Ge.f()}}}break;case"SYEV":var je=new Lt(k),Be=k.ts;switch(je.category){case Lt.CATEGORY_CHANNEL_JOIN:case Lt.CATEGORY_CHANNEL_LEAVE:c.getChannel(je.channelUrl,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}if(n)J.debug("Discard command:","`".concat(M.command,"`"),je.category);else{var a=je.data.hasOwnProperty("member_count")?je.data.member_count:null,o=je.data.hasOwnProperty("joined_member_count")?je.data.joined_member_count:null,l=!1;if(je.category===Lt.CATEGORY_CHANNEL_JOIN){(je.data.hasOwnProperty("users")?je.data.users:[je.data]).forEach((function(n){e.isSuper||e.isBroadcast?l=e.setLatestMemberCount(a,o,k.ts):(n.state=s.JOINED,e.addMember(new s(n),Be),e.updateJoinedMemberCount());var r=new i(n);t.sb.currentUser&&r.userId===t.sb.currentUser.userId&&(e.myMemberState="joined",c.cachedChannels[e.url]=e),Object.keys(t.sb.channelHandlers).forEach((function(n){var i=t.sb.channelHandlers[n];i.onUserJoined(e,r),e.isBroadcast&&l&&i.onChannelMemberCountChanged([e])})),G.upsert([e]).then((function(){j.send({source:de.EVENT_USER_JOINED,payload:{channel:e,user:r}})})).catch((function(e){t.handleCacheError(e)}))}))}else{var u=new i(je.data);if(t.sb.currentUser&&u.userId===t.sb.currentUser.userId?(e.isPublic||c.removeCachedChannel(je.channelUrl),e.myMemberState="none",e.invitedAt=0,e.joinedAt=0,e._setGroupChannelUnreadCount(0,0)):c.cachedChannels[e.url]=e,e.isSuper||e.isBroadcast)l=e.setLatestMemberCount(a,o,k.ts);else v.container.appInfo.enabledChannelMemberShipHistory?(e.memberMap[u.userId].state=c.MemberStateFilter.LEFT,e.memberCount=je.data.member_count):e.removeMember(u),e.updateJoinedMemberCount();Object.keys(t.sb.channelHandlers).forEach((function(n){var r=t.sb.channelHandlers[n];r.onUserLeft(e,u),e.isBroadcast&&l&&r.onChannelMemberCountChanged([e])})),G.upsert([e]).then((function(){j.send({source:de.EVENT_USER_LEFT,payload:{channel:e,user:u}})})).catch((function(e){t.handleCacheError(e)}))}}}));break;case Lt.CATEGORY_CHANNEL_OPERATOR_UPDATE:je.isGroupChannel()?c.getChannel(je.channelUrl,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}if(n)J.debug("Discard command:","`".concat(M.command,"`"),je.category);else{for(var s=je.data.operators.map((function(e){return new i(e)})),a=s.map((function(e){return e.userId})),o=0;o=0?c.Role.OPERATOR:c.Role.NONE;e.myRole=t.sb.currentUser&&a.indexOf(t.sb.currentUser.userId)>=0?c.Role.OPERATOR:c.Role.NONE,Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onOperatorUpdated(e,s)})),G.upsert([e]).then((function(){j.send({source:de.EVENT_OPERATOR_UPDATED,payload:{channel:e,operators:s}})})).catch((function(e){t.handleCacheError(e)}))}})):je.isOpenChannel()&&d.getChannel(je.channelUrl,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}n?J.debug("Discard command:","`".concat(M.command,"`"),je.category):(e.operators=je.data.operators.map((function(e){return new i(e)})),Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onOperatorUpdated(e,e.operators)})))}));break;case Lt.CATEGORY_CHANNEL_INVITE:c.getChannel(je.channelUrl,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}if(n)J.debug("Discard command:","`".concat(M.command,"`"),je.category);else{var a=null;je.data&&je.data.inviter&&Object.keys(je.data.inviter).length>0&&(a=new i(je.data.inviter));for(var o=[],l=0;l0&&(s=new i(je.data.inviter));var a=new i(je.data.invitee);if(t.sb.currentUser&&a.userId===t.sb.currentUser.userId&&(e.invitedAt=0,e.myMemberState="none",e.isPublic||c.removeCachedChannel(je.channelUrl)),e.isSuper||e.isBroadcast){var o=je.data.hasOwnProperty("member_count")?je.data.member_count:null,l=je.data.hasOwnProperty("joined_member_count")?je.data.joined_member_count:null;e.setLatestMemberCount(o,l,k.ts)}else e.removeMember(a);t.sb.currentUser&&a.userId!==t.sb.currentUser.userId&&(c.cachedChannels[e.url]=e),Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onUserDeclinedInvitation(e,s,a)})),G.upsert([e]).then((function(){j.send({source:de.EVENT_USER_DECLINED_INVITATION,payload:{channel:e,inviter:s,invitee:a}})})).catch((function(e){t.handleCacheError(e)}))}}));break;case Lt.CATEGORY_TYPING_START:case Lt.CATEGORY_TYPING_END:c.getChannel(je.channelUrl,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}if(n)J.debug("Discard command:","`".concat(M.command,"`"),je.category);else{var s=new i(je.data);je.category===Lt.CATEGORY_TYPING_START?e.updateTypingStatus(s,!0):e.updateTypingStatus(s,!1),Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onTypingStatusUpdated(e)})),G.upsert([e]).then((function(){j.send({source:de.EVENT_TYPING_STATUS_UPDATED,payload:{channel:e}})})).catch((function(e){t.handleCacheError(e)}))}}));break;case Lt.CATEGORY_CHANNEL_ENTER:case Lt.CATEGORY_CHANNEL_EXIT:d.getChannel(je.channelUrl,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}if(n)J.debug("Discard command:","`".concat(M.command,"`"),je.category);else{var s=je.data.hasOwnProperty("participant_count")?je.data.participant_count:null,a=e.setLatestParticipantCount(s,k.ts),o=new i(je.data);je.category===Lt.CATEGORY_CHANNEL_ENTER?(Object.keys(t.sb.channelHandlers).forEach((function(n){var r=t.sb.channelHandlers[n];r.onUserEntered(e,o),a&&r.onChannelParticipantCountChanged([e])})),j.send({source:de.EVENT_CHANNEL_ENTER,payload:{channel:e,user:o}})):(Object.keys(t.sb.channelHandlers).forEach((function(n){var r=t.sb.channelHandlers[n];r.onUserExited(e,o),a&&r.onChannelParticipantCountChanged([e])})),j.send({source:de.EVENT_CHANNEL_EXIT,payload:{channel:e,user:o}}))}}));break;case Lt.CATEGORY_USER_CHANNEL_MUTE:case Lt.CATEGORY_USER_CHANNEL_UNMUTE:var Ve=je.category===Lt.CATEGORY_USER_CHANNEL_MUTE,qe=l({},je.data);Ve&&(qe.restriction_type=a.RestrictionType.MUTED);var Ke=Ve?new a(qe):new i(je.data),ze=Ve?"muted":"unmuted";je.isOpenChannel()?d.getChannel(je.channelUrl,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}n?J.debug("Discard command:","`".concat(M.command,"`"),je.category):Ve?(Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onUserMuted(e,Ke)})),j.send({source:de.EVENT_USER_MUTED,payload:{channel:e,user:Ke}})):(Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onUserUnmuted(e,Ke)})),j.send({source:de.EVENT_USER_UNMUTED,payload:{channel:e,user:Ke}}))})):c.getChannel(je.channelUrl,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}n?J.debug("Discard command:","`".concat(M.command,"`"),je.category):(t.sb.currentUser&&Ke.userId===t.sb.currentUser.userId&&(e.myMutedState=ze),Array.isArray(e.members)&&e.members.filter((function(e){return e&&e.userId===Ke.userId})).forEach((function(e){e.isMuted=Ve,e.restrictionInfo=new E(qe)})),Ve?(Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onUserMuted(e,Ke)})),G.upsert([e]).then((function(){j.send({source:de.EVENT_USER_MUTED,payload:{channel:e,user:Ke}})})).catch((function(e){t.handleCacheError(e)}))):(Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onUserUnmuted(e,Ke)})),G.upsert([e]).then((function(){j.send({source:de.EVENT_USER_UNMUTED,payload:{channel:e,user:Ke}})})).catch((function(e){t.handleCacheError(e)}))))}));break;case Lt.CATEGORY_USER_CHANNEL_BAN:case Lt.CATEGORY_USER_CHANNEL_UNBAN:var Ye=je.category===Lt.CATEGORY_USER_CHANNEL_BAN,Qe=l({},je.data);Ye&&(Qe.restriction_type=a.RestrictionType.BANNED);var We=Ye?new a(Qe):new i(je.data);je.isOpenChannel()?d.getChannel(je.channelUrl,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}if(n)J.debug("Discard command:","`".concat(M.command,"`"),je.category);else if(Ye){if(t.sb.currentUser&&We.userId===t.sb.currentUser.userId)delete d.enteredChannels[je.channelUrl],t.cls.FileMessageQueue.delete(je.channelUrl);Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onUserBanned(e,We)})),j.send({source:de.EVENT_USER_BANNED,payload:{channel:e,user:We}})}else Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onUserUnbanned(e,We)})),j.send({source:de.EVENT_USER_UNBANNED,payload:{channel:e,user:We}})})):c.getChannel(je.channelUrl,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}if(n)J.debug("Discard command:","`".concat(M.command,"`"),je.category);else if(Ye){if(t.sb.currentUser&&We.userId===t.sb.currentUser.userId&&(e.isPublic||c.removeCachedChannel(je.channelUrl),e.myMemberState="none",e.invitedAt=0,e.joinedAt=0,e._setGroupChannelUnreadCount(0,0)),e.isSuper||e.isBroadcast){var i=je.data.hasOwnProperty("member_count")?je.data.member_count:null,s=je.data.hasOwnProperty("joined_member_count")?je.data.joined_member_count:null;e.setLatestMemberCount(i,s,k.ts)}else e.removeMember(We),e.updateJoinedMemberCount();Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onUserBanned(e,We)})),j.send({source:de.EVENT_USER_BANNED,payload:{channel:e,user:We}})}else Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onUserUnbanned(e,We)})),j.send({source:de.EVENT_USER_UNBANNED,payload:{channel:e,user:We}})}));break;case Lt.CATEGORY_CHANNEL_FREEZE:case Lt.CATEGORY_CHANNEL_UNFREEZE:je.isOpenChannel()?d.getChannel(je.channelUrl,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}n?J.debug("Discard command:","`".concat(M.command,"`"),je.category):(e.isFrozen=je.data.freeze,d.cachedChannels[e.url]=e,je.category===Lt.CATEGORY_CHANNEL_FREEZE?(Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onChannelFrozen(e)})),j.send({source:de.EVENT_CHANNEL_FROZEN,payload:{channel:e}})):(Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onChannelUnfrozen(e)})),j.send({source:de.EVENT_CHANNEL_UNFROZEN,payload:{channel:e}})))})):c.getChannel(je.channelUrl,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}n?J.debug("Discard command:","`".concat(M.command,"`"),je.category):(e.isFrozen=je.data.freeze,c.cachedChannels[e.url]=e,je.category===Lt.CATEGORY_CHANNEL_FREEZE?(Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onChannelFrozen(e)})),G.upsert([e]).then((function(){j.send({source:de.EVENT_CHANNEL_FROZEN,payload:{channel:e}})})).catch((function(e){t.handleCacheError(e)}))):(Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onChannelUnfrozen(e)})),G.upsert([e]).then((function(){j.send({source:de.EVENT_CHANNEL_UNFROZEN,payload:{channel:e}})})).catch((function(e){t.handleCacheError(e)}))))}));break;case Lt.CATEGORY_CHANNEL_DELETED:je.isGroupChannel()?c.removeCachedChannel(je.channelUrl):d.removeCachedChannel(je.channelUrl);var Je=je.channelUrl,Xe=je.isGroupChannel()?"group":"open";Object.keys(this.sb.channelHandlers).forEach((function(e){t.sb.channelHandlers[e].onChannelDeleted(Je,Xe)})),G.remove([Je]).then((function(){j.send({source:de.EVENT_CHANNEL_DELETED,payload:{channelUrl:Je,channelType:Xe}})})).catch((function(e){t.handleCacheError(e)}));break;case Lt.CATEGORY_CHANNEL_PROP_CHANGED:je.isOpenChannel()?d.getChannelWithoutCache(je.channelUrl,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}n?J.debug("Discard command:","`".concat(M.command,"`"),je.category):(Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onChannelChanged(e)})),j.send({source:de.EVENT_CHANNEL_CHANGED,payload:{channel:e}}))})):c.getChannelWithoutCache(je.channelUrl,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}if(n)J.debug("Discard command:","`".concat(M.command,"`"),je.category);else{var i=e.unreadMessageCount,s=e.unreadMentionCount;e.myCountPreference!==c.CountPreference.ALL&&(e.myCountPreference===c.CountPreference.UNREAD_MESSAGE_COUNT_ONLY?s=0:e.myCountPreference===c.CountPreference.UNREAD_MENTION_COUNT_ONLY?i=0:(i=0,s=0)),e._setGroupChannelUnreadCount(i,s),Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onChannelChanged(e)})),G.upsert([e]).then((function(){j.send({source:de.EVENT_CHANNEL_CHANGED,payload:{channel:e}})})).catch((function(e){t.handleCacheError(e)}))}}));break;case Lt.CATEGORY_CHANNEL_META_DATA_CHANGED:case Lt.CATEGORY_CHANNEL_META_COUNTERS_CHANGED:var Ze=je.data.hasOwnProperty("created"),et=je.data.hasOwnProperty("updated"),tt=je.data.hasOwnProperty("deleted");(je.isOpenChannel()?d.getChannel(je.channelUrl,T.INTERNAL_CALL):c.getChannel(je.channelUrl,T.INTERNAL_CALL)).then((function(e){var n=je.data.created,r=je.data.updated,i=je.data.deleted;Object.keys(t.sb.channelHandlers).forEach((function(s){var a=t.sb.channelHandlers[s];if(je.category===Lt.CATEGORY_CHANNEL_META_DATA_CHANGED){var o=k.ts;Ze&&e._addOrUpdateCachedMetaData(n,o),et&&e._addOrUpdateCachedMetaData(r,o),tt&&e._markAsDeletedCachedMetaData(i,o),Ze&&a.onMetaDataCreated(e,n),et&&a.onMetaDataUpdated(e,r),tt&&a.onMetaDataDeleted(e,i),(Ze||et)&&j.send({source:de.EVENT_CHANNEL_METADATA_UPDATED,payload:{channel:e,metaData:l(l({},n),r)}}),tt&&j.send({source:de.EVENT_CHANNEL_METADATA_DELETED,payload:{channel:e,metaData:l({},i)}})}else Ze&&a.onMetaCountersCreated(e,n),et&&a.onMetaCountersUpdated(e,r),tt&&a.onMetaCountersDeleted(e,i),(Ze||et)&&j.send({source:de.EVENT_CHANNEL_METACOUNTER_UPDATED,payload:{channel:e,metaData:l(l({},n),r)}}),tt&&j.send({source:de.EVENT_CHANNEL_METACOUNTER_DELETED,payload:{channel:e,metaData:l({},i)}})}))})).catch((function(e){return J.debug("Discard command:","`".concat(M.command,"`"),je.category)}));break;case Lt.CATEGORY_CHANNEL_HIDE:case Lt.CATEGORY_CHANNEL_UNHIDE:c.getChannel(je.channelUrl,T.INTERNAL_CALL,(function(e,n){if(t.sb.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}n?J.debug("Discard command:","`".concat(M.command,"`"),je.category):je.category===Lt.CATEGORY_CHANNEL_HIDE?(e.isHidden=!0,je.data&&(je.data.hasOwnProperty("allow_auto_unhide")&&(e.hiddenState=je.data.allow_auto_unhide?c.HiddenState.HIDDEN_ALLOW_AUTO_UNHIDE:c.HiddenState.HIDDEN_PREVENT_AUTO_UNHIDE),je.data.hasOwnProperty("hide_previous_messages")&&je.data.hide_previous_messages&&e._setGroupChannelUnreadCount(0,0)),k.hasOwnProperty("ts_message_offset")&&(e._messageOffsetTimestamp=k.ts_message_offset),c.cachedChannels[e.url]=e,Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onChannelHidden(e)})),G.upsert([e]).then((function(){j.send({source:de.EVENT_CHANNEL_HIDDEN,payload:{channel:e}})})).catch((function(e){t.handleCacheError(e)}))):(e.isHidden=!1,e.hiddenState=c.HiddenState.UNHIDDEN,c.cachedChannels[e.url]=e,Object.keys(t.sb.channelHandlers).forEach((function(n){t.sb.channelHandlers[n].onChannelChanged(e)})),G.upsert([e]).then((function(){j.send({source:de.EVENT_CHANNEL_UNHIDDEN,payload:{channel:e}})})).catch((function(e){t.handleCacheError(e)})))}))}break;case"USEV":var nt=new Lt(k);switch(nt.category){case wt.CATEGORY_USER_BLOCK:case wt.CATEGORY_USER_UNBLOCK:var rt=nt.data.blocker.user_id,it=nt.data.blockee.user_id;Object.keys(c.cachedChannels).forEach((function(e){var n=c.cachedChannels[e];try{t.sb.currentUser&&(t.sb.currentUser.userId===rt?n.memberMap[it].isBlockedByMe=nt.category===wt.CATEGORY_USER_BLOCK:t.sb.currentUser.userId===it&&(n.memberMap[rt].isBlockingMe=nt.category===wt.CATEGORY_USER_BLOCK))}catch(e){}}));break;case wt.CATEGORY_FRIEND_DISCOVERED:var st=nt.data.friend_discoveries.map((function(e){return new i(e)}));Object.keys(this.sb.userEventHandlers).forEach((function(e){t.sb.userEventHandlers[e].onFriendsDiscovered(st)}))}break;case"LEAV":case"JOIN":case"PONG":case"MTIO":case"TPST":case"TPEN":break;default:J.debug("Discard command:","`".concat(M.command,"`"))}}}},{key:"handleCacheError",value:function(e){J.error(e)}}]),e}(),Dt=200,Ht={},Ft={},Gt=function(){function e(t){c(this,e),this.channel=t,this.uploadQueue=[],this.messageQueue=[],this.latestTimestampToSendMessage=0,x.get(this._iid).FileMessageQueue.queueMap[t.url]=this}return h(e,[{key:"_handleMessageQueueUpdated",value:function(e){var t=this;switch(J.debug("`fileMessageQueue` message queue updated:",this.messageQueue),e){case"add":this.uploadQueue.length<6&&this._moveFirstPendingMessageToUploadQueue();break;case"update":case"remove":if(this.messageQueue.length>0){var n=x.get(this._iid).FileMessageQueue,r=this.messageQueue[0];if(r)if(r.state===n.State.UPLOADED)if(r.state=n.State.SENDING,navigator&&"boolean"==typeof navigator.onLine)if(navigator.onLine){for(0===this.latestTimestampToSendMessage&&(this.latestTimestampToSendMessage=(new Date).getTime()-Dt);(new Date).getTime()-this.latestTimestampToSendMessage-1&&(t.state=r.State.SENT,this._handleMessageQueueUpdated("update")),this._finalizeUpload(t.requestId)}else navigator&&"boolean"==typeof navigator.onLine?navigator.onLine?this._uploadFile(t,(function(e){t.error&&t.error.code===H.REQUEST_FAILED&&(t.error=new H("Failed to upload a file.",H.NETWORK_ERROR)),t.error&&t.state===r.State.SENT||(t.state=r.State.UPLOADED),t.fileInfo=e,n._handleMessageQueueUpdated("update"),n._finalizeUpload(t.requestId)})):(t.state=r.State.SENT,t.error=new H("Connection is not valid. Please reconnect.",H.WEBSOCKET_CONNECTION_CLOSED),t.response=null,this._handleMessageQueueUpdated("update"),this._finalizeUpload(t.requestId)):Qe.ready().then((function(e){e?n._uploadFile(t,(function(e){t.error&&t.error.code===H.REQUEST_FAILED&&(t.error=new H("Failed to upload a file.",H.NETWORK_ERROR)),t.error&&t.state===r.State.SENT||(t.state=r.State.UPLOADED),t.fileInfo=e,n._handleMessageQueueUpdated("update"),n._finalizeUpload(t.requestId)})):(t.state=r.State.SENT,t.error=new H("Connection is not valid. Please reconnect.",H.WEBSOCKET_CONNECTION_CLOSED),t.response=null,n._handleMessageQueueUpdated("update"),n._finalizeUpload(t.requestId))}));break;case"update":break;case"remove":this.uploadQueue.length<6&&this._moveFirstPendingMessageToUploadQueue()}}},{key:"_moveFirstPendingMessageToUploadQueue",value:function(){var e=x.get(this._iid).FileMessageQueue,t=this.messageQueue.filter((function(t){return t.state===e.State.PENDING}));if(t.length>0){var n=t[0];this.uploadQueue.push(n),this._handleUploadQueueUpdated("add",n)}}},{key:"_sendUploadedMessage",value:function(e,t){var n=x.get(this._iid),r=n.Command,i=n.FileMessage,s=e.fileInfo,a=r.bFile(l(l({},s),{},{requestId:e.requestId,channelUrl:this.channel.url,url:s.file,metaArrays:s.metaArrays})),o=wi.getInstance(this._iid),u=O.get(this._iid);o.getConnectionState()===o.ConnectionState.OPEN||!o.currentUser||o.connecting||o.reconnecting?o.sendCommand(a,(function(e,n){if(o.getErrorFirstCallback()){var r=[e,n];n=r[0],e=r[1]}if(n){var l=new i(a.getJsonElement());l.requestedMentionUserIds=s.mentionedUserIds,t(n,l)}else{var u=new i(e.getJsonElement());t(null,u)}})):u.container.apiClient.sendFileMessage(l(l({reqId:e.requestId,channelUrl:this.channel.url,isOpenChannel:this.channel.isOpenChannel()},s),{},{fileUrl:s.file,fileName:s.name,fileSize:s.size,fileType:s.type,metaArrays:s.metaArrays}),(function(e,n){var r=new i(e?a.getJsonElement():n);e&&(r.requestedMentionUserIds=s.mentionedUserIds),t(e,r)}))}},{key:"_uploadFile",value:function(e,t){var n=e.fileInfo,r=e.pendingMessage;if("string"!=typeof n.file&&n.file){var i=x.get(this._iid).FileMessageQueue;O.get(this._iid).container.apiClient.uploadFile(l(l({},n),{},{fileType:n.type,channelUrl:this.channel.url,reqId:r?r.reqId:null}),(function(r,s){if(r)e.state=i.State.SENT,e.error=r,e.response=null,t(n);else{var a="object"===u(s)?s:JSON.parse(s);n.file=a.url,n.thumbnailSizes=a.hasOwnProperty("thumbnails")?a.thumbnails:[],n.requireAuth=!!a.hasOwnProperty("require_auth")&&a.require_auth,n.size=a.hasOwnProperty("file_size")?a.file_size:n.size,t(n)}}))}else n.thumbnailSizes=[],n.requireAuth=!1,t(n)}},{key:"_finalizeUpload",value:function(e){var t=this.uploadQueue.map((function(e){return e.requestId})).indexOf(e);if(t>-1){var n=this.uploadQueue.splice(t,1);n.length>0&&this._handleUploadQueueUpdated("remove",n[0])}}},{key:"_finalizeMessage",value:function(){var e=this,t=O.get(this._iid),n=t.container.localCacheEnabled,r=t.container.isErrorFirstInCallback,i=wi.getInstance(this._iid),s=$e.of(this._iid),a=ot.of(this._iid),o=ge.of(this._iid),l=x.get(this._iid).FileMessageQueue,u=this.messageQueue[0],c=u.pendingMessage;if(u&&u.state===l.State.SENT){u.state=l.State.DONE;var d=u.response;d&&c&&(d._isAutoResendRegistered=c._isAutoResendRegistered);var h=u.error,p=h?new H(h.message,h.code):null,f=u.fileInfo.callback;if(d&&!h){d.reqId=c.reqId,d.requestState=i.MessageRequestState.SUCCEEDED,d.sendingStatus=i.MessageSendingStatus.SUCCEEDED;var _=i.currentUser;if(_&&d._sender&&_.userId===d._sender.userId&&(_.nickname!==d._sender.nickname&&(_.nickname=d._sender.nickname),_.plainProfileUrl!==d._sender.plainProfileUrl&&(_.plainProfileUrl=d._sender.plainProfileUrl)),this.channel.isGroupChannel())return this.channel.lastMessage=d,Object.keys(i.channelHandlers).forEach((function(t){i.channelHandlers[t].onChannelChanged(e.channel)})),void s.upsert([this.channel]).then((function(){o.send({source:de.EVENT_CHANNEL_CHANGED,payload:{channel:e.channel}})})).then((function(){return a.removeUnsentMessages({channelUrl:e.channel.url,sendingStatus:i.MessageSendingStatus.PENDING,reqIds:[d.reqId]})})).then((function(){return a.upsert([d],Je.SUCCEEDED)})).then((function(){Ut._completeCurrentAndProcessNextAutoResend(i,d),o.send({source:de.EVENT_MESSAGE_SENT,payload:{channel:e.channel,message:d}})})).catch((function(e){return J.error(e)})).finally((function(){f&&(f.isPromisifyCallback||r?f(null,d):f(d,null)),e.messageQueue.shift(),e._handleMessageQueueUpdated("remove")}))}if(h){if(d&&d._isAutoResendRegistered&&se.isAutoResendableError(h.code))return this.messageQueue.shift(),void this._handleMessageQueueUpdated("remove");if(u.pendingMessage&&(d=u.pendingMessage._clone()),d&&h.code!==H.INVALID_PARAMETER)if(d.requestState=i.MessageRequestState.FAILED,h.code===H.FILE_UPLOAD_CANCEL_FAILED||h.code===H.REQUEST_CANCELED){if(d.sendingStatus=i.MessageSendingStatus.CANCELED,this.channel.isGroupChannel())return void a.removeUnsentMessages({channelUrl:this.channel.url,sendingStatus:i.MessageSendingStatus.PENDING,reqIds:[d.reqId]}).then((function(){o.send({source:de.LOCAL_MESSAGE_CANCELED,payload:{channel:e.channel,message:d}})})).catch((function(e){return J.error(e)})).finally((function(){f&&(f.isPromisifyCallback||r?f(p,d):f(d,p)),e.messageQueue.shift(),e._handleMessageQueueUpdated("remove")}))}else if(d.sendingStatus=i.MessageSendingStatus.FAILED,d.errorCode=h.code,d.requestedMentionUserIds=u.fileInfo.mentionedUserIds,h.code===H.FILE_SIZE_LIMIT_EXCEEDED&&d._messageParams&&d._messageParams.file&&(d._messageParams.file=null),this.channel.isGroupChannel())return void(h.code===H.USER_NOT_MEMBER||h.code===H.CHANNEL_NOT_FOUND?s.remove([this.channel.url]).then((function(){return a.removeUnsentMessages({channelUrl:e.channel.url,sendingStatus:i.MessageSendingStatus.PENDING,reqIds:[d.reqId]})})).then((function(){o.send({source:de.LOCAL_MESSAGE_FAILED,payload:{channel:e.channel,message:d}})})).catch((function(e){return J.error(e)})).finally((function(){f&&(f.isPromisifyCallback||r?f(p,d):f(d,p)),e.messageQueue.shift(),e._handleMessageQueueUpdated("remove")})):(n&&se.isAutoResendableError(h.code)&&(d.sendingStatus=i.MessageSendingStatus.PENDING,d.errorCode=0,d._isAutoResendRegistered=!0),a.upsert([d],Je.UNSENT).then((function(){Ut._completeCurrentAndProcessNextAutoResend(i,d),o.send({source:de.LOCAL_MESSAGE_FAILED,payload:{channel:e.channel,message:d}})})).catch((function(e){return J.error(e)})).finally((function(){var t=d._clone();t.sendingStatus=i.MessageSendingStatus.FAILED,t.errorCode=h.code,t._isAutoResendRegistered=!1,f&&(f.isPromisifyCallback||r?f(p,t):f(t,p)),e.messageQueue.shift(),e._handleMessageQueueUpdated("remove")}))))}f&&(f.isPromisifyCallback||r?f(p,d):f(d,p)),this.messageQueue.shift(),this._handleMessageQueueUpdated("remove")}}},{key:"addJob",value:function(e){this.messageQueue.push(e),this._handleMessageQueueUpdated("add")}},{key:"cancelUploadItemByRequestId",value:function(e,t){this._finalizeUpload(e);var n=this.messageQueue.map((function(e){return e.requestId})).indexOf(e);if(n>-1){var r=x.get(this._iid).FileMessageQueue,i=this.messageQueue[n];!i||i.state!==r.State.UPLOADING&&i.state!==r.State.PENDING||(i.state=r.State.SENT,i.response=null,i.error=new H("Uploading has been completed or canceled.",H.FILE_UPLOAD_CANCEL_FAILED),this._handleMessageQueueUpdated("update"));var s=r.uploadRequest[e];if(s)return"function"==typeof s.abort?s.abort():"function"==typeof s.cancel&&s.cancel("Upload has been canceled."),t(null,!0),!0;t(new H("Uploading has been completed or canceled.",H.FILE_UPLOAD_CANCEL_FAILED),!1)}else t(new H("Uploading has been completed or canceled.",H.FILE_UPLOAD_CANCEL_FAILED),!1);return!1}}],[{key:"State",get:function(){return{PENDING:"pending",UPLOADING:"uploading",UPLOADED:"uploaded",SENDING:"sending",SENT:"sent",DONE:"done"}}},{key:"getByChannelUrl",value:function(e){return x.get(this._iid).FileMessageQueue.queueMap[e]}},{key:"create",value:function(e){var t=x.get(this._iid).FileMessageQueue;return t.queueMap.hasOwnProperty(e.url)||(t.queueMap[e.url]=new t(e)),t.queueMap[e.url]}},{key:"delete",value:function(e){var t=x.get(this._iid).FileMessageQueue;t.queueMap.hasOwnProperty(e)&&delete t.queueMap[e]}},{key:"clear",value:function(){Ft[this._iid]={}}},{key:"queueMap",get:function(){return Ft[this._iid]||(Ft[this._iid]={}),Ft[this._iid]}},{key:"uploadRequest",get:function(){return Ht[this._iid]||(Ht[this._iid]={}),Ht[this._iid]}}]),e}();Gt.Job=function(){return h((function e(t){var n=t.fileInfo,r=t.requestId,i=t.pendingMessage,s=t.state,a=t.error,o=void 0===a?null:a,l=t.response,u=void 0===l?null:l;c(this,e),this.fileInfo=n,this.requestId=r,this.pendingMessage=i,this.state=s||Gt.State.PENDING,this.error=o,this.response=u}))}();var xt,jt={},Bt=function(){function e(e){var t=e.dbname,n=e.itemSizeLimit,r=void 0===n?1048576:n,i=e.cacheLimit,s=void 0===i?256:i,a=e.blockHashBase,o=void 0===a?2:a,l=e.blockHashMultiplier,u=void 0===l?10:l,c=e.blockHashConstant,d=void 0===c?11:c,h=e.transactionApplyDelay,p=void 0===h?200:h,f=e.disableLogger,_=void 0!==f&&f;return jt[t]||(this.itemSizeLimit=r,this.cacheLimit=s,this.blockHashBase=o,this.blockHashMultiplier=u,this.blockHashConstant=d,this.transactionApplyDelay=p,this.disableLogger=_,jt[t]=this),jt[t]}return e.get=function(e){return jt[e]},e}();!function(e){e[e.UNKNOWN_ERROR=6e7]="UNKNOWN_ERROR",e[e.STORE_NOT_DEFINED=61001e3]="STORE_NOT_DEFINED",e[e.STORE_NOT_AVAILABLE=61001001]="STORE_NOT_AVAILABLE",e[e.STORE_NOT_AVAILABLE_IN_PRIVATE_BROWSING=61001002]="STORE_NOT_AVAILABLE_IN_PRIVATE_BROWSING",e[e.STORE_IS_FULL=61001003]="STORE_IS_FULL",e[e.STORE_INVALID_KEY_TYPE=61002e3]="STORE_INVALID_KEY_TYPE",e[e.STORE_BROKEN_INTEGRITY=61002001]="STORE_BROKEN_INTEGRITY",e[e.STORE_BROKEN_BLOB=61002002]="STORE_BROKEN_BLOB",e[e.STORE_ENCRYPTION_INVALID=61002003]="STORE_ENCRYPTION_INVALID",e[e.STORE_ITEM_SIZE_LIMIT_EXCEEDED=61017e3]="STORE_ITEM_SIZE_LIMIT_EXCEEDED",e[e.STORE_READ_FAILED=61017001]="STORE_READ_FAILED",e[e.STORE_WRITE_FAILED=61017002]="STORE_WRITE_FAILED",e[e.DATABASE_SCHEMA_NOT_ON_UPGRADE=62002e3]="DATABASE_SCHEMA_NOT_ON_UPGRADE",e[e.COLLECTION_NOT_READY=63001e3]="COLLECTION_NOT_READY",e[e.COLLECTION_KEY_NOT_MATCH=63002e3]="COLLECTION_KEY_NOT_MATCH",e[e.COLLECTION_QUERY_NOT_VALID=63002001]="COLLECTION_QUERY_NOT_VALID",e[e.COLLECTION_KEY_NOT_FOUND=63004e3]="COLLECTION_KEY_NOT_FOUND",e[e.COLLECTION_KEY_NOT_GIVEN=63004001]="COLLECTION_KEY_NOT_GIVEN",e[e.COLLECTION_INSERT_DUPLICATE=63009e3]="COLLECTION_INSERT_DUPLICATE",e[e.COLLECTION_WRITE_FAILED=63017e3]="COLLECTION_WRITE_FAILED",e[e.COLLECTION_ITEM_SIZE_LIMIT_EXCEEDED=63017001]="COLLECTION_ITEM_SIZE_LIMIT_EXCEEDED",e[e.INDEX_TABLE_IS_REQUIRED=65001e3]="INDEX_TABLE_IS_REQUIRED",e[e.INDEX_TYPE_NOT_MATCH=65002e3]="INDEX_TYPE_NOT_MATCH",e[e.COMPARE_TYPE_NOT_MATCH=69002001]="COMPARE_TYPE_NOT_MATCH",e[e.CIRCULAR_REFERENCE_FOUND=69002002]="CIRCULAR_REFERENCE_FOUND"}(xt||(xt={}));var Vt,qt=function(e){function t(n){var r=n.code,i=void 0===r?xt.UNKNOWN_ERROR:r,s=n.message,a=void 0===s?"Unknown error occurred.":s,o=e.call(this,a)||this;return o.code=i,Object.setPrototypeOf(o,t.prototype),o}return k(t,e),Object.defineProperty(t,"storeNotDefined",{get:function(){return new t({code:xt.STORE_NOT_DEFINED,message:"Store is not defined. Specify the store on NestDB()"})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"storeNotAvailable",{get:function(){return new t({code:xt.STORE_NOT_AVAILABLE,message:"Store is not available. Check your environment settings."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"storeNotAvailableInPrivateBrowsing",{get:function(){return new t({code:xt.STORE_NOT_AVAILABLE_IN_PRIVATE_BROWSING,message:"Store is not available because it is in private browsing."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"storeIsFull",{get:function(){return new t({code:xt.STORE_IS_FULL,message:"Store is full."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"storeKeyTypeIsInvalid",{get:function(){return new t({code:xt.STORE_INVALID_KEY_TYPE,message:"Store key should be string type."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"storeBrokenIntegrity",{get:function(){return new t({code:xt.STORE_BROKEN_INTEGRITY,message:"Data should be in a store but it does not. Integrity is broken."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"storeBrokenBlob",{get:function(){return new t({code:xt.STORE_BROKEN_BLOB,message:"Data should be in a store but it does not. Blob data is broken."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"storeEncryptionInvalid",{get:function(){return new t({code:xt.STORE_ENCRYPTION_INVALID,message:"Encryption algorithm has changed. All the store should reset."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"storeItemSizeExceeded",{get:function(){return new t({code:xt.STORE_ITEM_SIZE_LIMIT_EXCEEDED,message:"The size of the item exceeds the limit that the store allows."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"storeReadFailed",{get:function(){return new t({code:xt.STORE_READ_FAILED,message:"Failed to read from store."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"storeWriteFailed",{get:function(){return new t({code:xt.STORE_WRITE_FAILED,message:"Failed to write to store."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"databaseSchemaNotOnUpgrade",{get:function(){return new t({code:xt.DATABASE_SCHEMA_NOT_ON_UPGRADE,message:"Committing schema is not allowed when upgrade is not running."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"collectionNotReady",{get:function(){return new t({code:xt.COLLECTION_NOT_READY,message:"Collection is not ready due to an error during initialization."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"collectionKeyNotMatch",{get:function(){return new t({code:xt.COLLECTION_KEY_NOT_MATCH,message:"keyName of collection could not change."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"collectionQueryNotValid",{get:function(){return new t({code:xt.COLLECTION_QUERY_NOT_VALID,message:"Query parameter is not a valid format."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"collectionInsertDuplicate",{get:function(){return new t({code:xt.COLLECTION_INSERT_DUPLICATE,message:"The key already exists."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"collectionKeyNotFound",{get:function(){return new t({code:xt.COLLECTION_KEY_NOT_FOUND,message:"The key is not found."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"collectionKeyNotGiven",{get:function(){return new t({code:xt.COLLECTION_KEY_NOT_GIVEN,message:"The item should contain [keyName] property."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"collectionWriteFailed",{get:function(){return new t({code:xt.COLLECTION_WRITE_FAILED,message:"Failed to write an item."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"collectionItemSizeExceeded",{get:function(){return new t({code:xt.COLLECTION_ITEM_SIZE_LIMIT_EXCEEDED,message:"The size of the item exceeds the limit that a collection allows."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"indexTableIsRequired",{get:function(){return new t({code:xt.INDEX_TABLE_IS_REQUIRED,message:"Index table is required."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"indexTypesNotMatch",{get:function(){return new t({code:xt.INDEX_TYPE_NOT_MATCH,message:"Indexed column should have primitive type."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"compareTypesNotMatch",{get:function(){return new t({code:xt.COMPARE_TYPE_NOT_MATCH,message:"Values to compare have different types."})},enumerable:!1,configurable:!0}),Object.defineProperty(t,"circularReferenceFound",{get:function(){return new t({code:xt.CIRCULAR_REFERENCE_FOUND,message:"Cannot handle circular referenced object."})},enumerable:!1,configurable:!0}),t}(Error);!function(e){e.INIT="init",e.READY="ready",e.CLOSED="closed"}(Vt||(Vt={}));var Kt,zt=function(e,t){if(void 0===t&&(t=new WeakMap),"object"==typeof e&&null!==e){if(t.has(e))throw qt.circularReferenceFound;t.set(e,!0);var n=null;if(Array.isArray(e))n=e.map((function(e){return zt(e,t)}));else if(e instanceof RegExp)n=e;else if(e instanceof Date)n=e;else for(var r in n={},e)n[r]=zt(e[r],t);return t.delete(e),n}return e},Yt=function(e,t){if(null==t)return 1;if(null==e)return-1;if(typeof e!=typeof t)throw qt.compareTypesNotMatch;var n=0;switch(typeof e){case"boolean":case"number":n=e-t;break;case"string":n=e.localeCompare(t)}return n},Qt=function(e,t){for(var n=0,r=0;r>>0)%t},Wt=function(e){return new Promise((function(t){setTimeout((function(){return t()}),e)}))},Jt=function(e,t){if(!t)return!1;if("function"!=typeof e){for(var n in e){if(["/and","&&"].includes(n)){if(e[n].some((function(e){return!Jt(e,t)})))return!1}else if(["/or","||"].includes(n)){if(e[n].every((function(e){return!Jt(e,t)})))return!1}else if("/where"===n){if(!(0,e[n])(t))return!1}else{var r=n;if("object"==typeof e[r]){var i=e[r];for(var s in i)switch(s){case"/eq":case"=":if((a=t[r])!==(o=i[s]))return!1;break;case"/neq":case"!=":if((a=t[r])===(o=i[s]))return!1;break;case"/gt":case">":var a=t[r],o=i[s];if(!(Yt(a,o)>0))return!1;break;case"/gte":case">=":a=t[r],o=i[s];if(!(Yt(a,o)>=0))return!1;break;case"/lt":case"<":a=t[r],o=i[s];if(!(Yt(a,o)<0))return!1;break;case"/lte":case"<=":a=t[r],o=i[s];if(!(Yt(a,o)<=0))return!1;break;case"/in":a=t[r];if(!(o=i[s]).includes(a))return!1;break;case"/nin":a=t[r];if((o=i[s]).includes(a))return!1;break;case"/contain":a=t[r],o=i[s];if(!a.includes(o))return!1;break;case"/regex":a=t[r];if(!(o=i[s]).test(a))return!1;break;case"/where":a=t[r];if(!(0,i[s])(a))return!1}}else if("function"==typeof e[r]){if(!e[r](t[r]))return!1}else if(e[r]!==t[r])return!1}}return!0}return e(t)},Xt=function(){},Zt=function(){return Promise.resolve()},$t=function(e){return e},en=function(e,t){t(null)};!function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(Kt||(Kt={}));var tn,nn,rn,sn=function(){function e(e){var t=e.initialPrevValue,n=void 0===t?null:t,r=e.initialNextValue,i=void 0===r?null:r,s=e.iterator,a=e.map,o=void 0===a?$t:a,l=e.backward,u=void 0===l?Zt:l,c=e.forward,d=void 0===c?Zt:c,h=e.complete,p=void 0===h?Xt:h;this._prevValue=n,this._nextValue=i,this._error=null,this._map=o,this._backward=u,this._forward=d,this._iterator=s,this._complete=p}return Object.defineProperty(e.prototype,"prevValue",{get:function(){return this._map(this._prevValue)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"nextValue",{get:function(){return this._map(this._nextValue)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"error",{get:function(){return this._error},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hasPrevious",{get:function(){return!!this._prevValue},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hasNext",{get:function(){return!!this._nextValue},enumerable:!1,configurable:!0}),e.prototype.prev=function(){return L(this,void 0,void 0,(function(){var e,t,n;return w(this,(function(r){switch(r.label){case 0:if(!this.hasPrevious)return[3,6];r.label=1;case 1:return r.trys.push([1,3,,4]),e=this._prevValue,t=this,[4,this._backward()];case 2:return t._prevValue=r.sent()||null,this._nextValue=e,[3,4];case 3:return n=r.sent(),this._error=n,[3,4];case 4:return[4,this._iterator(this)];case 5:return[2,r.sent()];case 6:this._complete(),r.label=7;case 7:return[2]}}))}))},e.prototype.next=function(){return L(this,void 0,void 0,(function(){var e,t,n;return w(this,(function(r){switch(r.label){case 0:if(!this.hasNext)return[3,6];r.label=1;case 1:return r.trys.push([1,3,,4]),e=this._nextValue,t=this,[4,this._forward()];case 2:return t._nextValue=r.sent()||null,this._prevValue=e,[3,4];case 3:return n=r.sent(),this._error=n,[3,4];case 4:return[4,this._iterator(this)];case 5:return[2,r.sent()];case 6:this._complete(),r.label=7;case 7:return[2]}}))}))},e.prototype.stop=function(){this._prevValue=null,this._nextValue=null,this._complete()},e}(),an=function(){function e(e){var t=e.condition,n=void 0===t?{}:t,r=e.backward,i=void 0!==r&&r,s=e.blockManager,a=e.indexer;this.condition=n,this.backward=i,this._blockManager=s,this._indexer=a}return e.prototype.findOptimizedStartPosition=function(){var e=this,t=["=","/eq",">",">=","/gt","/gte"],n=["=","/eq","<","<=","/lt","/lte"];if(this.backward){var r=this._indexer.origin.length-1;if("function"!=typeof this.condition)for(var i in this._indexer.fields){var s=this._indexer.fields[i],a=1;if("-"===s[0]&&(s=s.slice(1),a=-1),this.condition[s])if("object"==typeof this.condition[s]){var o=a>0?n:t;for(var l in this.condition[s])if(o.includes(l))for(var u=r;u>=0;u--)if(a*Yt(this._indexer.origin[u].columnValues[i],this.condition[s][l])<=0){r=u;break}}else for(u=r;u>=0;u--)if(a*Yt(this._indexer.origin[u].columnValues[i],this.condition[s])<=0){r=u;break}}return Math.min(r+1,this._indexer.origin.length-1)}var c=0;if("function"!=typeof this.condition)for(var d=function(r){var i=h._indexer.fields[r],s=1;if("-"===i[0]&&(i=i.slice(1),s=-1),h.condition[i])if("object"==typeof h.condition[i])Object.keys(h.condition[i]).forEach((function(a){if((s>0?t:n).includes(a))for(var o=c;o=0){c=o;break}}));else for(var a=c;a=0){c=a;break}},h=this,i=0;i0){for(var r=Math.ceil(e.data.length/n),i="".concat(r,".").concat(e.type,".").concat(t),s=[],a=0;a0))return[3,6];a=0,u.label=1;case 1:return a0))return[3,2];for(i=0;i-1){var r=this._items[n];return t===rn.PERSISTENT&&(r.state=nn.PERSISTENT),t!==rn.NO_CACHE&&this.put(r),r}return null},e.prototype.put=function(e){if(this._limit>0){var t=this._items.map((function(e){return e.key})).indexOf(e.key);if(t>-1)_n.includes(this._items[t].state)&&_n.includes(e.state)?(this._items.splice(t,1),this._items.push(e)):(this._items[t].state=e.state,this._items[t].generation=e.generation,this._items[t].value=e.value);else{this._items.push(e);var n=this._items.filter((function(e){return e.state===nn.VOLATILE})),r=n.length-this._limit;if(r>0){for(var i=[],s=0,a=this._items;s0?r--:i.push(o)}this._items=i}}}},e.prototype.remove=function(e){var t=this._items.map((function(e){return e.key})).indexOf(e);t>-1&&this._items.splice(t,1)},e.prototype.clearByCondition=function(e){this._items=this._items.filter((function(t){return!e(t)}))},e.prototype.clear=function(e){void 0===e&&(e=!1),this._items=e?[]:this._items.filter((function(e){return e.state!==nn.VOLATILE}))},e}(),mn=function(){function e(e){var t=e.dbname,n=e.collectionName,r=e.store;this._metadata=null,this._requests=[],this._onCommit=new Map,this._onWrite=new Map,this._onError=new Map,this.dbname=t,this.collectionName=n,this.metadataKey=function(e,t){return"".concat(un(e,t),"/trans.metadata")}(t,n),this.recordsetKey=function(e,t){return"".concat(un(e,t),"/trans.recordset")}(t,n),this._store=r}return Object.defineProperty(e.prototype,"generation",{get:function(){return this._metadata?this._metadata.generation:0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"requestCount",{get:function(){return this._requests.length},enumerable:!1,configurable:!0}),e.prototype._getReducedRecordset=function(e){return void 0===e&&(e=[]),L(this,void 0,void 0,(function(){var t;return w(this,(function(n){switch(n.label){case 0:return[4,this._store.get(this.recordsetKey)];case 1:return(t=n.sent()||[]).push.apply(t,e),[2,this._reduceRecordSet(t)]}}))}))},e.prototype._reduceRecordSet=function(e){for(var t=[],n={},r=e.length-1;r>=0;r--){for(var i=e[r],s=[],a=i.requests.length-1;a>=0;a--){var o=i.requests[a],l=o.data;n[l.key]||(s.unshift(o),n[l.key]=!0)}s.length>0&&(i.requests=s,t.unshift(i))}return t},e.prototype._applyRecord=function(e,t){return L(this,void 0,void 0,(function(){var n,r,i,s,a,o,l,u,c;return w(this,(function(d){switch(d.label){case 0:n=yn.get(this.dbname),r=t.generation,i=t.requests,s=null,d.label=1;case 1:return d.trys.push([1,3,,4]),[4,this._store.setMany(i.map((function(e){return R(R({},e.data),{generation:r})})))];case 2:for(a=d.sent(),o=0;o0))return[3,4];for(t=[],n={},o=e.length-1;o>=0;o--)r=e[o],u=r.data,n[u.key]||(n[u.key]=!0,t.unshift(r));return i={generation:this.generation,requests:t},[4,this._getReducedRecordset([i])];case 1:return s=p.sent(),[4,this._store.set({key:this.recordsetKey,value:s,generation:this.generation})];case 2:return p.sent(),this._metadata.generation++,[4,this._store.set({key:this.metadataKey,value:this._metadata,generation:1})];case 3:for(p.sent(),a=yn.get(this.dbname),o=0;o0?(r=this.createBlockId(e,n),[4,t.find(this._store,r)]):[3,4];case 2:if((i=a.sent())&&(s=En.createFromCacheItem(i),s.getItemByKey(e)))return[2,s];a.label=3;case 3:return n--,[3,1];case 4:return[2,null]}}))}))},e.prototype.getFromBlock=function(e){return L(this,void 0,void 0,(function(){var t;return w(this,(function(n){switch(n.label){case 0:return[4,this._findBlock(e)];case 1:return[2,(t=n.sent())?t.getItemByKey(e):null]}}))}))},e.prototype.putToBlock=function(e,t){return L(this,void 0,void 0,(function(){var n,r,i,s,a;return w(this,(function(o){switch(o.label){case 0:return n=Bt.get(this.dbname),r=this.createBlockId(e),i=Math.floor(this._store.itemSizeLimit/n.itemSizeLimit),[4,yn.get(this.dbname).find(this._store,r)];case 1:return s=o.sent(),(a=s?En.createFromCacheItem(s):new En({blockId:r,keyName:this.keyName,items:[],limit:i})).add(t)?(this._transaction.requestWrite({key:a.blockId,value:a.serialize()}),[2,!0]):[2,!1]}}))}))},e.prototype.removeFromBlock=function(e){return L(this,void 0,void 0,(function(){var t;return w(this,(function(n){switch(n.label){case 0:return[4,this._findBlock(e)];case 1:return(t=n.sent())&&t.remove(e)?(this._transaction.requestWrite({key:t.blockId,value:t.serialize()}),[2,!0]):[2,!1]}}))}))},e.prototype.clearAllBlocks=function(){return L(this,void 0,void 0,(function(){var e,t,n,r,i,s,a;return w(this,(function(o){switch(o.label){case 0:return e=dn(this.dbname,this.collectionName),[4,this._store.getAllKeys()];case 1:return t=o.sent(),n=t.filter((function(t){return t.startsWith(e)})),[4,this._store.removeMany(n)];case 2:for(o.sent(),r=yn.get(this.dbname),i=0,s=n;i")),this._transaction=s,this._store=a,this._transaction.on(tn.COMMIT,this.indexerKey,(function(){return o.commit()})),this._transaction.on(tn.ERROR,this.indexerKey,(function(){return o.abort()}))}return e.createKey=function(e){return e.join(">")},e.parseKey=function(e){return e.split(">")},e.prototype._addItem=function(e){var t=e[this.keyName],n=this.getColumnValues(e),r=this.indexOf(n),i=r[0];return r[1]?!this._table[i].keys.includes(t)&&(this._table[i].keys.push(t),!0):(this._table.splice(i,0,{columnValues:n,keys:[t]}),!0)},e.prototype._removeItem=function(e){var t=e[this.keyName],n=this.getColumnValues(e),r=this.indexOf(n),i=r[0];if(r[1]){var s=this._table[i].keys.indexOf(t);if(s>-1)return this._table[i].keys.splice(s,1),0===this._table[i].keys.length&&this._table.splice(i,1),!0}return!1},Object.defineProperty(e.prototype,"origin",{get:function(){return this._origin},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"table",{get:function(){return this._table},enumerable:!1,configurable:!0}),e.prototype.getColumnValues=function(e){for(var t,n,r=[],i=0,s=this.fields;i0){for(var t=0,n=this._table.length-1;t<=n;){var r=Math.floor((t+n)/2),i=this.diff(e,this._table[r].columnValues);if(i>0)t=r+1;else{if(!(i<0))return[r,!0];n=r-1}}return[t,!1]}return[0,!1]},e.prototype.ensure=function(){return L(this,void 0,void 0,(function(){var e,t,n,r,i,s,a,o,l,u,c,d;return w(this,(function(h){switch(h.label){case 0:return[4,(e=yn.get(this.dbname)).find(this._store,this.indexerKey,rn.PERSISTENT)];case 1:return(t=h.sent())?[3,7]:(n=dn(this.dbname,this.collectionName),[4,this._store.getAllKeys()]);case 2:r=h.sent(),i=0,s=r,h.label=3;case 3:return i-1&&this._queue.splice(n,1),t.onReleased(e)}},e.prototype._requestLock=function(e){var t=this;return new Promise((function(n){var r={nodeId:e.nodeId,requestId:e.requestId,ts:e.ts,onAcquired:function(e){t.isHost&&t._send(Sn.ACQUIRE_LOCK,{requestId:e}),n()},onReleased:function(){t._acquire(t._queue[0])}},i=!1;for(var s in t._queue)if(t._queue[s].ts>r.ts){t._queue.splice(parseInt(s),0,r),i=!0;break}i||t._queue.push(r),t._currentItem||t._acquire(t._queue[0])}))},e.prototype._sendSync=function(){var e;this.isHost&&this._send(Sn.SYNC_HOST,{data:{currentItemRequestId:null===(e=this._currentItem)||void 0===e?void 0:e.requestId,queue:this._queue.map((function(e){return{nodeId:e.nodeId,requestId:e.requestId,ts:e.ts}}))}})},e.prototype._waitUntilSyncCompleted=function(){return L(this,void 0,void 0,(function(){var e=this;return w(this,(function(t){return this.isHost&&!this.isInSync?[2,new Promise((function(t){e._activationQueue.push(t)}))]:[2]}))}))},e.prototype._waitSync=function(){var e=this;this.isInSync||(this._activationTimeout=setTimeout((function(){e._completeSync()}),8))},e.prototype._completeSync=function(){this.isInSync||(this._state=Nn.DONE,this._activationQueue.forEach((function(e){return e()})),this._activationQueue=[])},e.prototype.registerNode=function(){this._send(Sn.NEWNODE),this._waitSync()},e.prototype.claimHost=function(){this._hostId=this.nodeId,this._send(Sn.CLAIM_HOST),this._waitSync()},e.prototype.lock=function(){return L(this,void 0,void 0,(function(){var e;return w(this,(function(t){switch(t.label){case 0:return[4,this._waitUntilSyncCompleted()];case 1:return t.sent(),e=this._send(Sn.REQUEST_LOCK),[4,this._requestLock(e)];case 2:return t.sent(),[2]}}))}))},e.prototype.unlock=function(){var e;this._release(null===(e=this._currentItem)||void 0===e?void 0:e.requestId)},e}(),kn=function(){function e(e){var t=e.dbname,n=e.collectionName,r=e.keyName,i=e.keyHash,s=e.indexes,a=e.store,o=this;this._state=Vt.INIT,this._metadata=null,this._indexers=[],this.dbname=t,this.name=n,this.keyName=r,this.indexes=P([[r]],s.filter((function(e){return bn.createKey(e)!==o.keyName})),!0),this._keyHash=i,this._store=a,this._mutex=new Mn(function(e,t){return"".concat(un(e,t),".lock")}(t,n)),this._blobContainer=new fn({dbname:t,collectionName:n,store:a}),this._transaction=new mn({dbname:t,collectionName:n,store:a})}return e.metadataOf=function(e,t,n){return L(this,void 0,void 0,(function(){var r;return w(this,(function(i){switch(i.label){case 0:return r=cn(e,t),[4,n.get(r)];case 1:return[2,i.sent()]}}))}))},Object.defineProperty(e.prototype,"state",{get:function(){return this._state},enumerable:!1,configurable:!0}),e.prototype.init=function(){return L(this,void 0,void 0,(function(){var t,n,r,i,s,a,o,l,u,c,d,h,p=this;return w(this,(function(f){switch(f.label){case 0:return[4,this._mutex.lock()];case 1:f.sent(),f.label=2;case 2:return f.trys.push([2,9,,10]),t=Bt.get(this.dbname),[4,e.metadataOf(this.dbname,this.name,this._store)];case 3:return n=f.sent(),this._metadata=n||{keyName:this.keyName,blockLevel:1,blockHashBase:t.blockHashBase,blockHashMultiplier:t.blockHashMultiplier,blockHashConstant:t.blockHashConstant,indexes:this.indexes},[4,this._transaction.init()];case 4:for(f.sent(),this._blockManager=new vn({dbname:this.dbname,collectionName:this.name,hashFunction:this._keyHash,metadata:this._metadata,transaction:this._transaction,store:this._store}),r=P([],this.indexes,!0),i=[],s=r.map((function(e){return bn.createKey(e)})),a=n?n.indexes.map((function(e){return bn.createKey(e)})):[],o=0,l=a;o0&&!r.some((function(t){switch(t){case qn.CHANNEL_NAME:return e.name.toLowerCase().includes(n.toLowerCase());case qn.MEMBER_NICKNAME:return e.members.some((function(e){return e.nickname.toLowerCase().includes(n.toLowerCase())}));default:return!0}})))return!1;var i=this._userIdsFilter,s=i.includeMode,a=i.queryType,o=i.userIds,l=O.get(this._iid).get("currentUserId"),u=e.members.map((function(e){return e.userId}));if(s){if(o.length>0)switch(a){case Vn.AND:if(o.some((function(e){return!u.includes(e)})))return!1;break;case Vn.OR:if(o.every((function(e){return!u.includes(e)})))return!1}}else{if(o.includes(l)||o.push(l),e.members.length>o.length)return!1;if(!function(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(var n=P([],e,!0).sort(),r=P([],t,!0).sort(),i=0;i0&&!this.customTypesFilter.includes(e.customType))return!1;if(this.customTypeStartsWithFilter&&!new RegExp("^".concat(this.customTypeStartsWithFilter)).test(e.customType))return!1;if(this.channelNameContainsFilter&&!e.name.toLowerCase().includes(this.channelNameContainsFilter.toLowerCase()))return!1;if(this.nicknameContainsFilter){var c=this.nicknameContainsFilter.toLowerCase();if(!e.members.some((function(e){return e.userId!==l&&e.nickname.toLowerCase().includes(c)})))return!1}if(this.nicknameStartsWithFilter){var d=this.nicknameStartsWithFilter.toLowerCase();if(!e.members.some((function(e){return e.userId!==l&&e.nickname.toLowerCase().startsWith(d)})))return!1}if(this.nicknameExactMatchFilter){var h=this.nicknameExactMatchFilter.toLowerCase();if(!e.members.some((function(e){return e.userId!==l&&e.nickname.toLowerCase()!==h})))return!1}if(this.channelUrlsFilter.length>0&&!this.channelUrlsFilter.includes(e.url))return!1;if(this.memberStateFilter)switch(this.memberStateFilter){case Kn.JOINED:if("joined"!==e.myMemberState)return!1;break;case Kn.INVITED:if("invited"!==e.myMemberState)return!1;break;case Kn.INVITED_BY_FRIEND:if("invited"!==e.myMemberState||!this._isFriend(e.inviter))return!1;break;case Kn.INVITED_BY_NON_FRIEND:if("invited"!==e.myMemberState||this._isFriend(e.inviter))return!1}if(this.hiddenChannelFilter)switch(this.hiddenChannelFilter){case Wn.UNHIDDEN:if(e.isHidden||"unhidden"!==e.hiddenState)return!1;break;case Wn.HIDDEN:if(!e.isHidden)return!1;break;case Wn.HIDDEN_ALLOW_AUTO_UNHIDE:if(!e.isHidden||"hidden_allow_auto_unhide"!==e.hiddenState)return!1;break;case Wn.HIDDEN_PREVENT_AUTO_UNHIDE:if(!e.isHidden||"hidden_prevent_auto_unhide"!==e.hiddenState)return!1}if(this.unreadChannelFilter&&this.unreadChannelFilter===Qn.UNREAD_MESSAGE)if(0===e.unreadMessageCount)return!1;if(this.publicChannelFilter)switch(this.publicChannelFilter){case Yn.PUBLIC:if(!e.isPublic||"none"===e.myMemberState)return!1;break;case Yn.PRIVATE:if(e.isPublic)return!1}if(this.superChannelFilter)switch(this.superChannelFilter){case zn.SUPER:if(!e.isSuper)return!1;break;case zn.NON_SUPER:if(e.isSuper)return!1}return!0},e.QueryType=Vn,e.SearchField=qn,e.MemberStateFilter=Kn,e.SuperChannelFilter=zn,e.PublicChannelFilter=Yn,e.UnreadChannelFilter=Qn,e.HiddenChannelFilter=Wn,e}(),$n=function(){function e(e){var t=e.iid;this._iid=t,this._filter=new Zn,this._filter.iid=this._iid,this._order=Le.LATEST_LAST_MESSAGE,this._limit=20}return e.prototype.setFilter=function(e){return this._filter=e.clone(),this._filter.iid=this._iid,this},e.prototype.setOrder=function(e){return this._order=e,this},e.prototype.setLimit=function(e){return this._limit=e,this},e.prototype.build=function(){return new Xe({iid:this._iid,filter:this._filter,order:this._order,limit:this._limit})},e}(),er=function(){function e(e){var t=e.iid,n=e.channel;this._iid=t,this._channel=n,this._startingPoint=Date.now(),this._filter=new et,this._limit=100}return e.prototype.setFilter=function(e){return this._filter=e.clone(),this},e.prototype.setStartingPoint=function(e){return this._startingPoint=e,this},e.prototype.setLimit=function(e){return this._limit=e,this},e.prototype.build=function(){return new Ut({iid:this._iid,channel:this._channel,startingPoint:this._startingPoint,filter:this._filter,limit:this._limit})},e}(),tr={},nr={},rr=new WeakMap,ir=new WeakMap,sr=new WeakMap,ar=function(e){f(n,e);var t=E(n);function n(e){var r;return c(this,n),(r=t.call(this,e)).channelType=Rt.CHANNEL_TYPE_GROUP,r.isDistinct=!1,r.isSuper=!1,r.isBroadcast=!1,r.isPublic=!1,r.unreadMessageCount=0,r.inviter=null,r.members=[],r.memberMap={},r.lastMessage=null,r.memberCount=0,r.joinedMemberCount=0,r.cachedReadReceiptStatus={},r.cachedDeliveryReceiptStatus=null,r.myPushTriggerOption=n.PushTriggerOption.DEFAULT,r.isPushEnabled,r.isHidden=!1,r.hiddenState=n.HiddenState.UNHIDDEN,r.isDiscoverable=!0,r.myLastRead=0,r.messageSurvivalSeconds=-1,r.invitedAt=0,r.joinedAt=0,r._messageOffsetTimestamp=0,r._cachedLastDeliveredReceipt={sentAt:0,timeout:null},rr.set(y(r),{}),ir.set(y(r),{start:0,end:0}),sr.set(y(r),0),e&&r._update(e),r}return h(n,[{key:"messageOffsetTimestamp",get:function(){return this._messageOffsetTimestamp}},{key:"createMessageCollection",value:function(){return new er({iid:this._iid,channel:this})}},{key:"_setGroupChannelUnreadCount",value:function(e,t){try{if("number"==typeof e&&e>=0)if("all"===this.myCountPreference||"unread_message_count_only"===this.myCountPreference)if(this.isSuper||this.isBroadcast){var n=O.get(this._iid).container.maxUnreadCountOfSuperGroupChannel;this.unreadMessageCount=e>=n?n:e}else this.unreadMessageCount=e;else this.unreadMessageCount=0;"number"==typeof t&&t>=0&&("all"===this.myCountPreference||"unread_mention_count_only"===this.myCountPreference?this.unreadMentionCount=t:this.unreadMentionCount=0)}catch(e){}}},{key:"_update",value:function(e){var t=this,n=x.get(this._iid),r=n.BaseChannel,i=n.GroupChannel,s=n.User,a=n.Member;if(this.isAccessCodeRequired=!!e.is_access_code_required&&e.is_access_code_required,this.isDistinct=!!e.is_distinct&&e.is_distinct,this.isPushEnabled=!!e.is_push_enabled&&e.is_push_enabled,this.isHidden=!!e.hasOwnProperty("is_hidden")&&e.is_hidden,this.myPushTriggerOption=e.push_trigger_option?e.push_trigger_option:i.PushTriggerOption.DEFAULT,this.myCountPreference=e.hasOwnProperty("count_preference")?e.count_preference:i.CountPreference.ALL,this.unreadMessageCount=0,this.unreadMentionCount=0,this._setGroupChannelUnreadCount(parseInt(e.unread_message_count),parseInt(e.unread_mention_count)),e.hasOwnProperty("read_receipt")&&(this.cachedReadReceiptStatus={},Object.keys(e.read_receipt).forEach((function(n){var r=e.read_receipt[n];t.updateReadReceipt(n,parseInt(r))}))),e.hasOwnProperty("delivery_receipt")&&"object"===u(e.delivery_receipt)&&null!==e.delivery_receipt&&(this.cachedDeliveryReceiptStatus||(this.cachedDeliveryReceiptStatus={}),Object.keys(e.delivery_receipt).forEach((function(n){var r=e.delivery_receipt[n];t.updateDeliveryReceipt(n,parseInt(r))}))),e.hasOwnProperty("user_last_read")&&"number"==typeof e.user_last_read?this.myLastRead=e.user_last_read:this.myLastRead=0,e.hasOwnProperty("members")){this.members=[],this.memberMap={};for(var o=0;o0?this.inviter=new s(e.inviter):this.inviter=null,this.invitedAt=e.invited_at||0,this.joinedAt=e.joined_ts||0,e.hasOwnProperty("is_super")&&"boolean"==typeof e.is_super?this.isSuper=e.is_super:this.isSuper=!1,e.hasOwnProperty("is_broadcast")&&"boolean"==typeof e.is_broadcast?this.isBroadcast=e.is_broadcast:this.isBroadcast=!1,e.hasOwnProperty("is_public")&&"boolean"==typeof e.is_public?this.isPublic=e.is_public:this.isPublic=!1,e.hasOwnProperty("hidden_state")?this.hiddenState=e.hidden_state:this.hiddenState=i.HiddenState.UNHIDDEN,e.hasOwnProperty("is_discoverable")&&"boolean"==typeof e.is_discoverable?this.isDiscoverable=e.is_discoverable:this.isDiscoverable=this.isPublic,e.hasOwnProperty("ts_message_offset")&&(this._messageOffsetTimestamp=e.ts_message_offset),e.hasOwnProperty("message_survival_seconds")&&"number"==typeof e.message_survival_seconds&&(this.messageSurvivalSeconds=e.message_survival_seconds)}},{key:"addMember",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!this.isSuper&&!this.isBroadcast){var n=x.get(this._iid),r=n.Member,i=this.removeMember(e);i&&i.state===r.JOINED&&(e.state=r.JOINED),this.memberMap[e.userId]=e,this.members.push(e),this.memberCount++,this.updateReadReceipt(e.userId,t),this.updateDeliveryReceipt(e.userId,t)}}},{key:"removeMember",value:function(e){var t=null;if(!this.isSuper&&!this.isBroadcast&&this.memberMap.hasOwnProperty(e.userId)){delete this.memberMap[e.userId];for(var n=0;n0&&e.every((function(e){return!!e.userId&&"string"==typeof e.userId}))}}),new me({type:"callback"})]),i=C(r,3);return n=i[0],e=i[1],t=i[2],n?oe(this._iid,(function(e){return e(me.error,null)}),t):this.inviteWithUserIds(e.map((function(e){return e.userId})),t)}},{key:"inviteWithUserIds",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"array",constraint:function(e){return e.every((function(e){return"string"==typeof e}))}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.inviteToGroupChannel({channelUrl:n.url,userIds:e},(function(e,r){var i=null;e||(i=x.get(n._iid).GroupChannel.upsert(r));t(e,i)}))}),t)}},{key:"acceptInvitation",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"string",optional:!0,defaultValue:null}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.acceptInvitation({channelUrl:n.url,accessCode:e},(function(e,r){var i=null;e||((i=x.get(n._iid).GroupChannel.upsert(r)).myMemberState="joined");t(e,i)}))}),t)}},{key:"declineInvitation",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.declineInvitation({channelUrl:t.url},(function(n,r){var i=null;if(!n){var s=x.get(t._iid).GroupChannel;(i=s.upsert(r)).myMemberState="none",t.isPublic||s.removeCachedChannel(t.url)}e(n,i)}))}),e)}},{key:"join",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"string",optional:!0,defaultValue:null}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.joinGroupChannel({channelUrl:n.url,accessCode:e},(function(e,r){var i=null;e||((i=x.get(n._iid).GroupChannel.upsert(r)).myMemberState="joined");t(e,i)}))}),t)}},{key:"leave",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.leaveGroupChannel({channelUrl:t.url},(function(t,n){return e(t,null)}))}),e)}},{key:"muteUser",value:function(e,t,n,r){return this.muteUserWithUserId(e?e.userId:null,t,n,r)}},{key:"muteUserWithUserId",value:function(e,t,n,r){var i=this,s=null,a=me.parse(arguments,[new me({type:"string"}),new me({type:"number",optional:!0,defaultValue:-1,constraint:function(e){return e>=-1}}),new me({type:"string",optional:!0,defaultValue:""}),new me({type:"callback"})]),o=C(a,5);return s=o[0],e=o[1],t=o[2],n=o[3],r=o[4],oe(this._iid,(function(r){s?r(s,null):O.get(i._iid).container.apiClient.muteUser({channelUrl:i.url,userId:e,description:n,seconds:t,isGroupChannel:!0},(function(e,t){r(e,null)}))}),r)}},{key:"unmuteUser",value:function(e,t){return this.unmuteUserWithUserId(e?e.userId:null,t)}},{key:"unmuteUserWithUserId",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"string"}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.unmuteUser({channelUrl:n.url,userId:e,isGroupChannel:!0},(function(e,n){t(e,null)}))}),t)}},{key:"banUser",value:function(e,t,n,r){return this.banUserWithUserId(e?e.userId:null,t,n,r)}},{key:"banUserWithUserId",value:function(e,t,n,r){var i=this,s=null,a=me.parse(arguments,[new me({type:"string"}),new me({type:"number",optional:!0,defaultValue:-1,constraint:function(e){return e>=-1}}),new me({type:"string"}),new me({type:"callback"})]),o=C(a,5);return s=o[0],e=o[1],t=o[2],n=o[3],r=o[4],oe(this._iid,(function(r){s?r(s,null):O.get(i._iid).container.apiClient.banUser({channelUrl:i.url,userId:e,description:n,seconds:t,isGroupChannel:!0},(function(e,t){r(e,null)}))}),r)}},{key:"unbanUser",value:function(e,t){return this.unbanUserWithUserId(e?e.userId:null,t)}},{key:"unbanUserWithUserId",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"string"}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.unbanUser({channelUrl:n.url,userId:e,isGroupChannel:!0},(function(e,n){t(e,null)}))}),t)}},{key:"updateJoinedMemberCount",value:function(){if(!this.isSuper&&!this.isBroadcast){var e=x.get(this._iid).Member;this.joinedMemberCount=this.members.filter((function(t){return t.state===e.JOINED})).length}}},{key:"setLatestMemberCount",value:function(e,t,n){var r=!1;return"number"==typeof e&&"number"==typeof t&&"number"==typeof n&&n>=sr.get(this)&&(sr.set(this,n),r=t!==this.joinedMemberCount||e!==this.memberCount,this.memberCount=e,this.joinedMemberCount=t),r}},{key:"hide",value:function(e,t,n){var r=this,i=null,s=me.parse(arguments,[new me({type:"boolean",optional:!0,defaultValue:!1}),new me({type:"boolean",optional:!0,defaultValue:!0}),new me({type:"callback"})]),a=C(s,4);return i=a[0],e=a[1],t=a[2],n=a[3],oe(this._iid,(function(n){i?n(i,null):O.get(r._iid).container.apiClient.hideGroupChannel({channelUrl:r.url,hidePreviousMessages:e,allowAutoUnhide:t},(function(i,s){if(!i){var a=x.get(r._iid).GroupChannel;r.isHidden=!0,r.hiddenState=t?a.HiddenState.HIDDEN_ALLOW_AUTO_UNHIDE:a.HiddenState.HIDDEN_PREVENT_AUTO_UNHIDE,e&&r._setGroupChannelUnreadCount(0,0),s.hasOwnProperty("ts_message_offset")&&(r._messageOffsetTimestamp=s.ts_message_offset),a.cachedChannels[r.url]=r}n(i,s)}))}),n)}},{key:"unhide",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.unhideGroupChannel({channelUrl:t.url},(function(n,r){if(!n){var i=x.get(t._iid).GroupChannel;t.isHidden=!1,t.hiddenState=i.HiddenState.UNHIDDEN,i.cachedChannels[t.url]=t}e(n,r)}))}),e)}},{key:"freeze",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.freeze({channelUrl:t.url,isGroupChannel:!0,freezing:!0},(function(n,r){if(!n){var i=x.get(t._iid).GroupChannel;t.isFrozen=!0,i.cachedChannels[t.url]=t}e(n,null)}))}),e)}},{key:"unfreeze",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.freeze({channelUrl:t.url,isGroupChannel:!0,freezing:!1},(function(n,r){if(!n){var i=x.get(t._iid).GroupChannel;t.isFrozen=!1,i.cachedChannels[t.url]=t}e(n,null)}))}),e)}},{key:"delete",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.deleteGroupChannel({channelUrl:t.url},(function(n,r){n||x.get(t._iid).GroupChannel.removeCachedChannel(t.url);e(n,r)}))}),e)}},{key:"markAsRead",value:function(e){var t=this;return oe(this._iid,(function(e){var n=x.get(t._iid).Command,r=wi.getInstance(t._iid),i=n.bRead({channelUrl:t.url});r.sendCommand(i,(function(n,i){if(r.getErrorFirstCallback()){var s=[n,i];i=s[0],n=s[1]}if(i)e(i,null);else if(r.currentUser){var a=$e.of(t._iid),o=ge.of(t._iid);t.updateReadReceipt(r.currentUser.userId,n.getJsonElement().ts);var l=!1;(t.unreadMessageCount>0||t.unreadMentionCount>0)&&(t._setGroupChannelUnreadCount(0,0),Object.keys(r.channelHandlers).forEach((function(e){r.channelHandlers[e].onChannelChanged(t)})),l=!0),e(null,null),a.upsert([t]).then((function(){l&&o.send({source:de.EVENT_CHANNEL_CHANGED,payload:{channel:t}}),o.send({source:de.EVENT_READ_RECEIPT_UPDATED,payload:{channel:t}})})).catch((function(e){return J.error(e)}))}else{var u=new SendBirdException("Connection should be made first.",SendBirdException.CONNECTION_REQUIRED);e(u,null)}}))}),e)}},{key:"getUnreadMemberCount",value:function(e){var t=O.get(this._iid),n=x.get(this._iid).Member,r=t.container.currentUserId;if(e instanceof pt&&!e.isAdminMessage()&&r&&!this.isSuper&&!this.isBroadcast){for(var i=0,s=e.createdAt,a=this.members,o=0;o1&&void 0!==arguments[1]&&arguments[1],n=wi.getInstance(this._iid);if(n.currentUser&&!this.isSuper&&!this.isBroadcast&&e instanceof pt&&!e.isAdminMessage()){for(var r=[],i=0;i=e.createdAt&&r.push(s)}}return r}return[]}},{key:"getUnreadMembers",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=wi.getInstance(this._iid);if(n.currentUser&&!this.isSuper&&!this.isBroadcast&&e instanceof pt&&!e.isAdminMessage()){for(var r=[],i=0;i0&&void 0!==arguments[0]&&arguments[0],n=wi.getInstance(this._iid);if(n.currentUser&&!this.isSuper&&!this.isBroadcast){for(var r={},i=Object.keys(this.cachedReadReceiptStatus),s=function(s){var a=i[s];if(!t&&a===n.currentUser.userId)return"continue";var o=e.cachedReadReceiptStatus[a],l=e.members.filter((function(e){return e.userId===a}));r[a]={user:l.length>0?l[0]:null,last_seen_at:parseInt(o)}},a=0;a9e3)&&(n=1e3);var r=ir.get(this);if(t-r.start>=n){r.end=0,r.start=t;var i=x.get(this._iid).Command.bTypeStart({channelUrl:this.url,time:r.start});e.sendCommand(i,null)}}},{key:"endTyping",value:function(){var e=wi.getInstance(this._iid),t=(new Date).getTime(),n=e.Options.typingIndicatorThrottle;("number"!=typeof n||n<1e3||n>9e3)&&(n=1e3);var r=ir.get(this);if(t-r.end>=n){r.start=0,r.end=t;var i=x.get(this._iid).Command.bTypeEnd({channelUrl:this.url,time:r.end});e.sendCommand(i,null)}}},{key:"invalidateTypingStatus",value:function(){var e=rr.get(this),t=(new Date).getTime(),n=!1;return Object.keys(e).forEach((function(r){var i=e[r].ts;t-i>=1e4&&(delete e[r],n=!0)})),n}},{key:"getTypingMembers",value:function(){var e=this,t=rr.get(this),n=[];return Object.keys(t).forEach((function(t){var r=e.memberMap[t];r&&n.push(r)})),n}},{key:"getTypingUsers",value:function(){var e=rr.get(this),t=[];return Object.keys(e).forEach((function(n){var r=e[n].user;t.push(r)})),t}},{key:"updateTypingStatus",value:function(e,t){var n=rr.get(this);t?n[e.userId]={user:e,ts:(new Date).getTime()}:delete n[e.userId]}},{key:"isTyping",value:function(){var e=rr.get(this);return 0!==Object.keys(e).length}},{key:"registerScheduledUserMessage",value:function(e,t){var n=this,r=x.get(this._iid),i=r.ScheduledUserMessage,s=r.ScheduledUserMessageParams,a=null,o=me.parse(arguments,[new me({type:s,constraint:function(e){return"string"==typeof e.message&&"string"==typeof e._getScheduleString()}}),new me({type:"callback"})]),l=C(o,3);return a=l[0],e=l[1],t=l[2],oe(this._iid,(function(t){a?t(a,null):O.get(n._iid).container.apiClient.registerScheduledUserMessage({groupChannelParams:e,channelUrl:n.url,isOpenChannel:!1},(function(e,r){var s=null;if(!e){s=new i(r);var a=wi.getInstance(n._iid).currentUser;a&&s._sender&&a.userId===s._sender.userId&&(a.nickname=s._sender.nickname,a.plainProfileUrl=s._sender.plainProfileUrl,a.metaData=s._sender.metaData)}t(e,s)}))}),t)}},{key:"getPushPreference",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.getMyPushTriggerOption({channelUrl:t.url},(function(n,r){var i=null;if(!n){try{i=r.enable}catch(e){i=!1}t.isPushEnabled=i}e&&e(n,i)}))}),e)}},{key:"setPushPreference",value:function(e,t){var n=this;return oe(this._iid,(function(t){var r=x.get(n._iid).GroupChannel;O.get(n._iid).container.apiClient.setMyPushTriggerOption({channelUrl:n.url,enable:e},(function(e,i){e||(n.isPushEnabled=i.enable,n.isPushEnabled||(n.myPushTriggerOption=r.PushTriggerOption.OFF)),t(e,i)}))}),t)}},{key:"getMyPushTriggerOption",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.getMyPushTriggerOption({channelUrl:t.url},(function(r,i){var s=null;if(!r){try{s=i.push_trigger_option||n.PushTriggerOption.DEFAULT}catch(e){J.debug(e)}t.myPushTriggerOption=s}e(r,s)}))}),e)}},{key:"setMyPushTriggerOption",value:function(e,t){var n=this,r=x.get(this._iid),i=r.GroupChannel,s=null,a=me.parse(arguments,[new me({type:i.PushTriggerOption}),new me({type:"callback"})]),o=C(a,3);return s=o[0],e=o[1],t=o[2],oe(this._iid,(function(t){s?t(s,null):O.get(n._iid).container.apiClient.setMyPushTriggerOption({channelUrl:n.url,pushTriggerOption:e},(function(e,r){var i=null;if(!e){try{i=r.push_trigger_option}catch(e){J.debug(e)}n.myPushTriggerOption=i}t(e,i)}))}),t)}},{key:"setMyCountPreference",value:function(e,t){var n=this,r=x.get(this._iid),i=r.GroupChannel,s=null,a=me.parse(arguments,[new me({type:i.CountPreference}),new me({type:"callback"})]),o=C(a,3);return s=o[0],e=o[1],t=o[2],oe(this._iid,(function(t){s?t(s,null):O.get(n._iid).container.apiClient.setMyCountPreference({channelUrl:n.url,countPreference:e},(function(e,r){var s=null;e||(s=n.myCountPreference=r.count_preference,n._setGroupChannelUnreadCount(n.unreadMessageCount,n.unreadMentionCount),i.cachedChannels[n.url]=n),t(e,s)}))}),t)}},{key:"resetMyHistory",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.resetMyHistory({channelUrl:t.url},(function(n,r){if(!n&&r.hasOwnProperty("ts_message_offset")){var i=x.get(t._iid).GroupChannel;t._messageOffsetTimestamp=r.ts_message_offset,i.cachedChannels[t.url]=t}e(n,r)}))}),e)}}],[{key:"MemberStateFilter",get:function(){return{ALL:"all",JOINED:"joined_only",INVITED:"invited_only",INVITED_BY_FRIEND:"invited_by_friend",INVITED_BY_NON_FRIEND:"invited_by_non_friend",LEFT:"left"}}},{key:"PushTriggerOption",get:function(){return{DEFAULT:"default",ALL:"all",MENTION_ONLY:"mention_only",OFF:"off"}}},{key:"CountPreference",get:function(){return{ALL:"all",UNREAD_MESSAGE_COUNT_ONLY:"unread_message_count_only",UNREAD_MENTION_COUNT_ONLY:"unread_mention_count_only",OFF:"off"}}},{key:"HiddenState",get:function(){return{UNHIDDEN:"unhidden",HIDDEN_ALLOW_AUTO_UNHIDE:"hidden_allow_auto_unhide",HIDDEN_PREVENT_AUTO_UNHIDE:"hidden_prevent_auto_unhide"}}},{key:"PublicChannelFilter",get:function(){return{ALL:"all",PUBLIC:"public",PRIVATE:"private"}}},{key:"SuperChannelFilter",get:function(){return{ALL:"all",SUPER:"super",NON_SUPER:"nonsuper",BROADCAST_ONLY:"broadcast_only"}}},{key:"UnreadChannelFilter",get:function(){return{ALL:"all",UNREAD_MESSAGE:"unread_message"}}},{key:"HiddenChannelFilter",get:function(){return{ALL:"all",UNHIDDEN:"unhidden_only",HIDDEN:"hidden_only",HIDDEN_ALLOW_AUTO_UNHIDE:"hidden_allow_auto_unhide",HIDDEN_PREVENT_AUTO_UNHIDE:"hidden_prevent_auto_unhide"}}},{key:"Role",get:function(){return{OPERATOR:"operator",NONE:"none"}}},{key:"UnreadItemKey",get:function(){return{GROUP_CHANNEL_UNREAD_MENTION_COUNT:"group_channel_unread_mention_count",NONSUPER_UNREAD_MENTION_COUNT:"non_super_group_channel_unread_mention_count",SUPER_UNREAD_MENTION_COUNT:"super_group_channel_unread_mention_count",GROUP_CHANNEL_UNREAD_MESSAGE_COUNT:"group_channel_unread_message_count",NONSUPER_UNREAD_MESSAGE_COUNT:"non_super_group_channel_unread_message_count",SUPER_UNREAD_MESSAGE_COUNT:"super_group_channel_unread_message_count",GROUP_CHANNEL_INVITATION_COUNT:"group_channel_invitation_count",NONSUPER_INVITATION_COUNT:"non_super_group_channel_invitation_count",SUPER_INVITATION_COUNT:"super_group_channel_invitation_count"}}},{key:"cachedChannels",get:function(){return tr[this._iid]||(tr[this._iid]={}),tr[this._iid]}},{key:"createGroupChannelCollection",value:function(){return new $n({iid:this._iid})}},{key:"buildFromSerializedData",value:function(e){var t=x.get(this._iid),n=t.User,r=t.Member,i=t.GroupChannel,s=t.BaseMessage,a=t.UserMessage,o=t.FileMessage,c=t.AdminMessage,d=ct.deserialize(e),h=function(e){return null!=e&&"object"===u(e)?e.messageType===s.MESSAGE_TYPE_USER?new a(a.objectify(l(l({},e),{},{channel:{url:e.channelUrl,channelType:e.channelType},user:e.sender,mentionedUsers:e.mentionedUsers}))):e.messageType===s.MESSAGE_TYPE_FILE?new o(o.objectify(l(l({},e),{},{channel:{url:e.channelUrl,channelType:e.channelType},user:e.sender,mentionedUsers:e.mentionedUsers}))):new c(c.objectify(l(l({},e),{},{channel:{url:e.channelUrl,channelType:e.channelType},mentionedUsers:e.mentionedUsers}))):null}(d.lastMessage);return new i({channel_url:d.url,name:d.name,cover_url:d.coverUrl,data:d.data,custom_type:d.customType,invited_at:d.invitedAt,created_at:d.createdAt/1e3,joined_ts:d.joinedAt,is_access_code_required:d.isAccessCodeRequired,is_distinct:d.isDistinct,is_super:d.isSuper,is_broadcast:d.isBroadcast,is_public:d.isPublic,is_discoverable:d.isDiscoverable,is_hidden:d.isHidden,is_ephemeral:d.isEphemeral,is_muted:d.myMutedState,is_push_enabled:d.isPushEnabled,freeze:d.isFrozen,unread_message_count:d.unreadMessageCount,unread_mention_count:d.unreadMentionCount,push_trigger_option:d.myPushTriggerOption,count_preference:d.myCountPreference,hidden_state:d.hiddenState,member_count:d.memberCount,joined_member_count:d.joinedMemberCount,member_state:d.myMemberState,my_role:d.myRole,user_last_read:d.myLastRead,ts_message_offset:d.messageOffsetTimestamp,message_survival_seconds:d.messageSurvivalSeconds,read_receipt:d.cachedReadReceiptStatus,delivery_receipt:d.cachedDeliveryReceiptStatus,members:d.members.map((function(e){return r.objectify(l({},e))})),last_message:h,created_by:null!==d.creator&&void 0!==d.creator&&"object"===u(d.creator)?n.objectify(d.creator):null,inviter:null!==d.inviter&&void 0!==d.inviter&&"object"===u(d.inviter)?n.objectify(d.inviter):null,metadata:d.metadata,cached_primary_key:d.cachedPrimaryKey})}},{key:"upsert",value:function(e){var t=x.get(this._iid).GroupChannel,n=new t(e);if(t.cachedChannels.hasOwnProperty(n.url)){if(n.isEphemeral){var r=t.cachedChannels[n.url];e.last_message=r.lastMessage,e.unread_message_count=r.unreadMessageCount}t.cachedChannels[n.url].update(e)}else t.cachedChannels[n.url]=n;return t.cachedChannels[n.url]}},{key:"removeCachedChannel",value:function(e){var t=x.get(this._iid),n=t.GroupChannel,r=t.FileMessageQueue;n.cachedChannels[e]&&delete n.cachedChannels[e],r.delete(e)}},{key:"clearCache",value:function(){tr[this._iid]={},x.get(this._iid).FileMessageQueue.clear()}},{key:"getChannel",value:function(e,t){var n=null,r=null,i=me.parse(arguments,[new me({type:"string",constraint:function(e){return e.length>0}}),new me({type:"string",optional:!0,nullable:!0,defaultValue:null}),new me({type:"callback"})]),s=C(i,4);if(n=s[0],e=s[1],r=s[2],t=s[3],n)return oe(this._iid,(function(e){e(n,null)}),t);var a=x.get(this._iid),o=a.GroupChannel;return o.cachedChannels[e]?oe(this._iid,(function(t){t(null,o.cachedChannels[e])}),t):o.getChannelWithoutCache(e,r,t)}},{key:"getChannelWithoutCache",value:function(e,t){var n=this,r=null,i=null,s=me.parse(arguments,[new me({type:"string",constraint:function(e){return e.length>0}}),new me({type:"string",optional:!0,nullable:!0,defaultValue:null}),new me({type:"callback"})]),a=C(s,4);return r=a[0],e=a[1],i=a[2],t=a[3],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.getGroupChannel({channelUrl:e,internalCall:i,showMember:!0},(function(e,r){var i=null;e||(i=n.upsert(r)),t(e,i)}))}),t)}},{key:"createDistinctChannelIfNotExist",value:function(e,t){var n=this,r=x.get(this._iid),i=r.GroupChannelParams,s=null,a=me.parse(arguments,[new me({type:i,constraint:function(e){return e._validate()}}),new me({type:"callback"})]),o=C(a,3);return s=o[0],e=o[1],t=o[2],oe(this._iid,(function(t){s?t(s,null):(e.isPublic||(e.accessCode=null),O.get(n._iid).container.apiClient.createGroupChannel(l(l({},e),{},{isDistinct:!0}),(function(e,r){var i=null;if(!e){var s=x.get(n._iid).GroupChannel;i={channel:new s(r),isCreated:r.is_created},s.cachedChannels[i.channel.url]=i.channel}t(e,i)})))}),t)}},{key:"createChannel",value:function(){var e=this,t=me.toArray(arguments),n=void 0;"function"==typeof t[t.length-1]&&(n=t.pop());var r=x.get(this._iid),i=r.GroupChannel,s=r.GroupChannelParams;if(t[0]instanceof s&&1===t.length)return oe(this._iid,(function(n){var r=t[0];(r.isPublic||(r.accessCode=null),r._validate())?O.get(e._iid).container.apiClient.createGroupChannel(r,(function(e,t){var r=null;e||(r=new i(t),i.cachedChannels[r.url]=r),n(e,r)})):n(me.error,null)}),n);if(Array.isArray(t[0])){var a=new s;switch(t.length){case 1:a.addUsers(t[0]);break;case 2:a.addUsers(t[0]),a.isDistinct=t[1];break;case 3:a.addUsers(t[0]),a.isDistinct=t[1],a.customType=t[2];break;case 5:a.addUsers(t[0]),a.isDistinct=t[1],a.name=t[2],"string"==typeof t[3]?a.coverUrl=t[3]:a.coverImage=t[3],a.data=t[4];break;case 6:a.addUsers(t[0]),a.isDistinct=t[1],a.name=t[2],"string"==typeof t[3]?a.coverUrl=t[3]:a.coverImage=t[3],a.data=t[4],a.customType=t[5];break;default:return oe(this._iid,(function(e){return e(me.error,null)}),n)}return n?i.createChannel(a,n):i.createChannel(a)}return oe(this._iid,(function(e){return e(me.error,null)}),n)}},{key:"createChannelWithUserIds",value:function(){var e=me.toArray(arguments),t=void 0;"function"==typeof e[e.length-1]&&(t=e.pop());var n=x.get(this._iid),r=n.GroupChannel,i=n.GroupChannelParams,s=new i;switch(e.length){case 1:s.addUserIds(e[0]);break;case 2:s.addUserIds(e[0]),s.isDistinct=e[1];break;case 3:s.addUserIds(e[0]),s.isDistinct=e[1],s.customType=e[2];break;case 5:s.addUserIds(e[0]),s.isDistinct=e[1],s.name=e[2],"string"==typeof e[3]?s.coverUrl=e[3]:s.coverImage=e[3],s.data=e[4];break;case 6:s.addUserIds(e[0]),s.isDistinct=e[1],s.name=e[2],"string"==typeof e[3]?s.coverUrl=e[3]:s.coverImage=e[3],s.data=e[4],s.customType=e[5];break;default:return oe(this._iid,(function(e){return e(me.error,null)}),t)}return t?r.createChannel(s,t):r.createChannel(s)}},{key:"createMyGroupChannelListQuery",value:function(){return new(0,x.get(this._iid).GroupChannelListQuery)}},{key:"createPublicGroupChannelListQuery",value:function(){return new(0,x.get(this._iid).PublicGroupChannelListQuery)}},{key:"markAsReadAllLastSentAt",get:function(){return nr[this._iid]||0},set:function(e){nr[this._iid]=e}},{key:"getChannelCount",value:function(e,t){return wi.getInstance(this._iid).getGroupChannelCount(e,t)}},{key:"getUnreadItemCount",value:function(e,t){return wi.getInstance(this._iid).getUnreadItemCount(e,t)}},{key:"getTotalUnreadMessageCount",value:function(){var e=me.toArray(arguments),t="function"==typeof e[e.length-1]?e.pop():null,n=wi.getInstance(this._iid);return n.getTotalUnreadMessageCount.apply(n,A(e).concat([t]))}},{key:"getTotalUnreadChannelCount",value:function(e){return wi.getInstance(this._iid).getTotalUnreadChannelCount(e)}}]),n}(Rt),or=function(e){function t(t){var n=e.call(this,t)||this;return n.state="",n.role="",n.isMuted=!1,n.isBlockedByMe=!1,n.isBlockingMe=!1,n.restrictionInfo=null,t&&n._update(t),n}return k(t,e),t.objectify=function(e){var t=x.get(this._iid),n=t.User,r=t.RestrictedUser,i=t.RestrictionInfo,s=e.state,a=e.role,o=void 0===a?"":a,l=e.isMuted,u=void 0!==l&&l,c=e.isBlockedByMe,d=void 0!==c&&c,h=e.isBlockingMe,p=void 0!==h&&h,f=e.restrictionInfo,_=void 0===f?null:f,g=u?r.objectify(e):n.objectify(e);if(g.state=s,g.role=o,g.is_muted=u,g.is_blocked_by_me=d,g.is_blocking_me=p,_){var y=i.objectify(_);g.restriction_type=y.restriction_type,g.muted_description=y.description,g.muted_end_at=y.end_at}return g},t.buildFromSerializedData=function(e){var t=x.get(this._iid).Member,n=ct.deserialize(e);return new t(t.objectify(R({},n)))},t.prototype._update=function(e){var t=x.get(this._iid),n=t.RestrictedUser,r=t.RestrictionInfo;this.state=e.state,this.role=e.role||ar.Role.NONE,e.hasOwnProperty("is_muted")&&(this.isMuted=e.is_muted),e.hasOwnProperty("is_blocked_by_me")&&(this.isBlockedByMe=e.is_blocked_by_me),e.hasOwnProperty("is_blocking_me")&&(this.isBlockingMe=e.is_blocking_me),this.isMuted&&(this.restrictionInfo=new r(e),this.restrictionInfo.restrictionType=n.RestrictionType.MUTED)},t.prototype.parse=function(e){this._update(e)},Object.defineProperty(t,"JOINED",{get:function(){return"joined"},enumerable:!1,configurable:!0}),Object.defineProperty(t,"INVITED",{get:function(){return"invited"},enumerable:!1,configurable:!0}),Object.defineProperty(t,"LEFT",{get:function(){return"left"},enumerable:!1,configurable:!0}),t}(ft),lr=function(e){function t(t){var n=e.call(this,t)||this;return n.role="",n.isBlockedByMe=!1,t&&n._update(t),n}return k(t,e),t.objectify=function(e){var t=x.get(this._iid).User,n=e.role,r=void 0===n?"":n,i=e.isBlockedByMe,s=void 0!==i&&i,a=t.objectify(e);return a.role=r,a.is_blocked_by_me=s,a},t.buildFromSerializedData=function(e){var t=x.get(this._iid).Sender,n=ct.deserialize(e);return new t(t.objectify(R({},n)))},t.prototype.parse=function(e){this._update(e)},t.prototype._update=function(e){this.role=e.role||ar.Role.NONE,e.hasOwnProperty("is_blocked_by_me")&&(this.isBlockedByMe=e.is_blocked_by_me)},t}(ft),ur=function(e){f(n,e);var t=E(n);function n(e){var r;return c(this,n),(r=t.call(this,e)).restrictionInfo=null,e&&r._update(e),r}return h(n,[{key:"_update",value:function(e){var t=x.get(this._iid).RestrictionInfo;this.restrictionInfo=new t(e)}}],[{key:"RestrictionType",get:function(){return{MUTED:"muted",BANNED:"banned"}}},{key:"objectify",value:function(e){var t=x.get(this._iid),n=t.User,r=t.RestrictionInfo,i=e.restrictionInfo,s=void 0===i?{}:i;return l(l({},n.objectify(e)),r.objectify(s))}}]),n}(ft),cr=function(){function e(e){this.emojiHash=null,this.emojiCategories=null,e&&this._update(e)}return e.prototype._update=function(e){var t=x.get(this._iid).EmojiCategory;this.emojiHash=e.emoji_hash||"",this.emojiCategories=e.emoji_categories?e.emoji_categories.map((function(e){return new t(e)})):[]},e}(),dr=function(){function e(e){this.id=null,this.name=null,this.url=null,this.emojis=null,e&&this._update(e)}return e.prototype._update=function(e){var t=x.get(this._iid).Emoji;this.id=e.id||0,this.name=e.name||"",this.url=e.url||"",this.emojis=e.emojis?e.emojis.map((function(e){return new t(e)})):[]},e}(),hr=function(){function e(e){this.key=null,this.url=null,e&&this._update(e)}return e.prototype._update=function(e){this.key=e.key,this.url=e.url},e}(),pr={},fr={},_r=new WeakMap,gr=function(e){f(n,e);var t=E(n);function n(e){var r;return c(this,n),(r=t.call(this,e)).channelType=Rt.CHANNEL_TYPE_OPEN,r.participantCount=0,_r.set(y(r),0),r.operators=[],e&&r._update(e),r}return h(n,[{key:"_update",value:function(e){var t=x.get(this._iid).User;e.hasOwnProperty("participant_count")&&(this.participantCount=parseInt(e.participant_count)),e.hasOwnProperty("operators")&&Array.isArray(e.operators)&&(this.operators=e.operators.map((function(e){return new t(e)})))}},{key:"parse",value:function(e){this._update(e)}},{key:"update",value:function(e){this.__update(e),this._update(e)}},{key:"createParticipantListQuery",value:function(){return new(0,x.get(this._iid).ParticipantListQuery)({channelUrl:this.url})}},{key:"createMutedUserListQuery",value:function(){return new(0,x.get(this._iid).MutedUserListQuery)({channelUrl:this.url,isOpenChannel:!0})}},{key:"createBannedUserListQuery",value:function(){return new(0,x.get(this._iid).BannedUserListQuery)({channelUrl:this.url,isOpenChannel:!0})}},{key:"isOperator",value:function(e){return!!e&&this.isOperatorWithUserId(e.userId)}},{key:"isOperatorWithUserId",value:function(e){return this.operators.map((function(e){return e.userId})).indexOf(e)>-1}},{key:"refresh",value:function(e){return x.get(this._iid).OpenChannel.getChannelWithoutCache(this.url,e)}},{key:"enter",value:function(e){var t=this;return oe(this._iid,(function(e){var n=x.get(t._iid).Command.bEnter({channelUrl:t.url}),r=wi.getInstance(t._iid);r.sendCommand(n,(function(n,i){if(r.getErrorFirstCallback()){var s=[n,i];i=s[0],n=s[1]}i?(i=i?new H(i.message,i.code):null,e(i,null)):(x.get(t._iid).OpenChannel.enteredChannels[t.url]=t,ge.of(t._iid).send({source:de.EVENT_CHANNEL_ENTER,payload:{channel:t}}),t.refresh((function(){return e(null,null)})))}))}),e)}},{key:"exit",value:function(e){var t=this;return oe(this._iid,(function(e){var n=x.get(t._iid),r=n.Command,i=n.FileMessageQueue,s=r.bExit({channelUrl:t.url}),a=wi.getInstance(t._iid);a.sendCommand(s,(function(n,r){if(a.getErrorFirstCallback()){var s=[n,r];r=s[0],n=s[1]}r?(r=r?new H(r.message,r.code):null,e(r,null)):(delete x.get(t._iid).OpenChannel.enteredChannels[t.url],i.delete(t.url),ge.of(t._iid).send({source:de.EVENT_CHANNEL_EXIT,payload:{channel:t}}),e(null,null))}))}),e)}},{key:"updateChannel",value:function(){var e=this,t=me.toArray(arguments),n=null;"function"==typeof t[t.length-1]&&(n=t.pop());var r=x.get(this._iid),i=r.OpenChannel,s=r.OpenChannelParams;if(t[0]instanceof s&&1===t.length)return oe(this._iid,(function(n){var r=t[0];(r.channelUrl=e.url,r._validate())?O.get(e._iid).container.apiClient.updateOpenChannel(r,(function(e,t){var r=null;e||(r=i.upsert(t)),n(e,r)})):n(me.error,null)}),n);if(3===t.length){var a=new s;return a.channelUrl=this.url,a.name=t[0],a.coverUrlOrImage=t[1],a.data=t[2],a.operatorUserIds=this.operators.map((function(e){return e.userId})),n?this.updateChannel(a,n):this.updateChannel(a)}if(4===t.length){var o=new s;return o.channelUrl=this.url,o.name=t[0],o.coverUrlOrImage=t[1],o.data=t[2],Array.isArray(t[3])&&(o.operatorUserIds=t[3]),n?this.updateChannel(o,n):this.updateChannel(o)}if(5===t.length){var l=new s;return l.channelUrl=this.url,l.name=t[0],l.coverUrlOrImage=t[1],l.data=t[2],Array.isArray(t[3])&&(l.operatorUserIds=t[3]),l.customType=t[4],n?this.updateChannel(l,n):this.updateChannel(l)}return oe(this._iid,(function(e){return e(me.error,null)}),n)}},{key:"updateChannelWithOperatorUserIds",value:function(){var e=me.toArray(arguments),t=void 0;switch("function"==typeof e[e.length-1]&&(t=e.pop()),e.length){case 4:case 5:return t?this.updateChannel(params,t):this.updateChannel(params);default:return oe(this._iid,(function(e){return e(me.error,null)}),t)}}},{key:"muteUser",value:function(e,t,n,r){return this.muteUserWithUserId(e?e.userId:null,t,n,r)}},{key:"muteUserWithUserId",value:function(e,t,n,r){var i=this,s=null,a=me.parse(arguments,[new me({type:"string"}),new me({type:"number",optional:!0,defaultValue:-1,constraint:function(e){return e>=-1}}),new me({type:"string",optional:!0,defaultValue:""}),new me({type:"callback"})]),o=C(a,5);return s=o[0],e=o[1],t=o[2],n=o[3],r=o[4],oe(this._iid,(function(r){s?r(s,null):O.get(i._iid).container.apiClient.muteUser({channelUrl:i.url,userId:e,description:n,seconds:t,isGroupChannel:!1},(function(e,t){r(e,null)}))}),r)}},{key:"unmuteUser",value:function(e,t){return this.unmuteUserWithUserId(e?e.userId:null,t)}},{key:"unmuteUserWithUserId",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"string"}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.unmuteUser({channelUrl:n.url,userId:e,isGroupChannel:!1},(function(e,n){t(e,null)}))}),t)}},{key:"banUser",value:function(e,t,n){return this.banUserWithUserId(e?e.userId:null,t,n)}},{key:"banUserWithUserId",value:function(e,t,n){var r=this,i=null,s=me.parse(arguments,[new me({type:"string"}),new me({type:"number",optional:!0,defaultValue:-1,constraint:function(e){return e>=-1}}),new me({type:"callback"})]),a=C(s,4);return i=a[0],e=a[1],t=a[2],n=a[3],oe(this._iid,(function(n){i?n(i,null):O.get(r._iid).container.apiClient.banUser({channelUrl:r.url,userId:e,description:null,seconds:t,isGroupChannel:!1},(function(e,t){n(e,null)}))}),n)}},{key:"unbanUser",value:function(e,t){return this.unbanUserWithUserId(e?e.userId:null,t)}},{key:"unbanUserWithUserId",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"string"}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.unbanUser({channelUrl:n.url,userId:e,isGroupChannel:!1},(function(e,n){t(e,null)}))}),t)}},{key:"setLatestParticipantCount",value:function(e,t){var n=!1;return"number"==typeof e&&"number"==typeof t&&t>=_r.get(this)&&(_r.set(this,t),n=e!==this.participantCount,this.participantCount=e),n}},{key:"delete",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.deleteOpenChannel({channelUrl:t.url},(function(n,r){n||(delete x.get(t._iid).OpenChannel.cachedChannels[t.url],x.get(t._iid).FileMessageQueue.delete(t.url));e(n,r)}))}),e)}}],[{key:"cachedChannels",get:function(){return pr[this._iid]||(pr[this._iid]={}),pr[this._iid]}},{key:"enteredChannels",get:function(){return fr[this._iid]||(fr[this._iid]={}),fr[this._iid]}},{key:"buildFromSerializedData",value:function(e){var t=x.get(this._iid),n=t.User,r=t.OpenChannel,i=ct.deserialize(e);return new r({channel_url:i.url,name:i.name,cover_url:i.coverUrl,data:i.data,custom_type:i.customType,created_at:i.createdAt/1e3,freeze:i.isFrozen,is_ephemeral:i.isEphemeral,participant_count:i.participantCount,operators:i.operators.map((function(e){return n.objectify(e)}))})}},{key:"getChannel",value:function(e,t){var n=null,r=null,i=me.parse(arguments,[new me({type:"string",constraint:function(e){return e.length>0}}),new me({type:"string",optional:!0,nullable:!0,defaultValue:null}),new me({type:"callback"})]),s=C(i,4);if(n=s[0],e=s[1],r=s[2],t=s[3],n)return oe(this._iid,(function(e){e(n,null)}),t);var a=x.get(this._iid),o=a.OpenChannel;return o.cachedChannels[e]?oe(this._iid,(function(t){t(null,o.cachedChannels[e])}),t):o.getChannelWithoutCache(e,r,t)}},{key:"getChannelWithoutCache",value:function(e,t){var n=this,r=null,i=null,s=me.parse(arguments,[new me({type:"string",constraint:function(e){return e.length>0}}),new me({type:"string",optional:!0,nullable:!0,defaultValue:null}),new me({type:"callback"})]),a=C(s,4);return r=a[0],e=a[1],i=a[2],t=a[3],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.getOpenChannel({channelUrl:e,internalCall:i},(function(e,r){var i=null;e||(i=x.get(n._iid).OpenChannel.upsert(r));t(e,i)}))}),t)}},{key:"createChannel",value:function(){var e=this,t=me.toArray(arguments),n=null;"function"==typeof t[t.length-1]&&(n=t.pop());var r=x.get(this._iid),i=r.OpenChannel,s=r.OpenChannelParams;if(t[0]instanceof s&&1===t.length)return oe(this._iid,(function(n){var r=t[0];r._validate()?O.get(e._iid).container.apiClient.createOpenChannel(r,(function(t,r){var i=null;t||(i=x.get(e._iid).OpenChannel.upsert(r));n(t,i)})):n(me.error,null)}),n);var a=new s;switch(t.length){case 0:break;case 1:a.name=t[0];break;case 2:a.name=t[0],a.coverUrlOrImage=t[1];break;case 3:a.name=t[0],a.coverUrlOrImage=t[1],a.data=t[2];break;case 4:a.name=t[0],a.coverUrlOrImage=t[1],a.data=t[2],a.operatorUserIds=t[3];break;case 5:a.name=t[0],a.coverUrlOrImage=t[1],a.data=t[2],a.operatorUserIds=t[3],a.customType=t[4];break;default:return oe(this._iid,(function(e){return e(me.error,null)}),n)}return n?i.createChannel(a,n):i.createChannel(a)}},{key:"createChannelWithOperatorUserIds",value:function(){var e=me.toArray(arguments),t=void 0;switch("function"==typeof e[e.length-1]&&(t=e.pop()),e.length){case 4:case 5:return t?this.createChannel.apply(this,A(e).concat([t])):this.createChannel.apply(this,A(e));default:return oe(this._iid,(function(e){return e(me.error,null)}),t)}}},{key:"upsert",value:function(e){var t=new(0,x.get(this._iid).OpenChannel)(e);return this.cachedChannels.hasOwnProperty(t.url)?this.cachedChannels[t.url].update(e):this.cachedChannels[t.url]=t,this.cachedChannels[t.url]}},{key:"removeCachedChannel",value:function(e){this.cachedChannels[e]&&delete this.cachedChannels[e],x.get(this._iid).FileMessageQueue.delete(e)}},{key:"clearCache",value:function(){pr[this._iid]={},x.get(this._iid).FileMessageQueue.clear()}},{key:"clearEnteredChannels",value:function(){fr[this._iid]={}}},{key:"createOpenChannelListQuery",value:function(){return new(0,x.get(this._iid).OpenChannelListQuery)}}]),n}(Rt),yr="default",mr=function(){function e(e){this.name=yr,this.volume=1,e&&this._update(e)}return e.prototype._update=function(e){e.hasOwnProperty("name")&&(this.name=e.name),e.hasOwnProperty("volume")&&(this.volume=e.volume)},e.objectify=function(e){var t=e.name,n=void 0===t?yr:t,r=e.volume;return{name:n,volume:void 0===r?1:r}},e.prototype.serialize=function(){return ct.serialize(this)},e}(),Er=function(){function e(e,t){void 0===t&&(t=[]),this.key=e,this.value=Array.isArray(t)&&t.every((function(e){return"string"==typeof e}))?t:[]}return e.prototype.encode=function(){return{key:this.key,value:this.value||[]}},e}(),vr=new WeakMap,br=function(){function e(t){c(this,e),this._mentionType=e.MentionType.USERS,this._mentionedUserIds=[],this._cachedMentionedUsers=[],this._cachedMentionedUserIds=[],this._metaArrays=[],vr.set(this,null),this._parentMessageId=null,this._reqId=null,this.data=null,this.customType=null,this.pushNotificationDeliveryOption=null,this.appleCriticalAlertOptions=null,this.isReplyToChannel=!1,this.mentionedMessageTemplate=null,t&&this._update(t)}return h(e,[{key:"mentionType",get:function(){return this._mentionType},set:function(e){var t=x.get(this._iid).BaseMessageParams;Object.keys(t.MentionType).map((function(e){return t.MentionType[e]})).indexOf(e)>-1&&(this._mentionType=e)}},{key:"mentionedUserIds",get:function(){return this._cachedMentionedUserIds},set:function(e){if(Array.isArray(e)){if(0===e.length)return this._cachedMentionedUserIds=[],void(this._mentionedUserIds=[]);for(var t=wi.getInstance(this._iid),n=0;n-1&&this._mentionedUserIds.every((function(e){return"string"==typeof e}))&&("string"==typeof this.mentionedMessageTemplate||null===this.mentionedMessageTemplate)&&Array.isArray(this._metaArrays)&&this._metaArrays.every((function(e){return e instanceof n}))&&("number"==typeof r||null===r)&&("number"==typeof this._parentMessageId||null===this._parentMessageId)&&("string"==typeof this.data||null===this.data)&&("string"==typeof this.customType||null===this.customType)&&(null===this.pushNotificationDeliveryOption||Object.keys(t.PushNotificationDeliveryOption).map((function(e){return t.PushNotificationDeliveryOption[e]})).indexOf(this.pushNotificationDeliveryOption)>-1)&&(null===this.appleCriticalAlertOptions||this.appleCriticalAlertOptions instanceof mr)&&"boolean"==typeof this.isReplyToChannel}}],[{key:"_objectify",value:function(t){var n=t.mentionType,r=void 0===n?e.MentionType.USERS:n,i=t.mentionedUserIds,s=void 0===i?[]:i,a=t.mentionedMessageTemplate,o=void 0===a?null:a,l=t.cachedMentionedUsers,u=void 0===l?[]:l,c=t.cachedMentionedUserIds,d=void 0===c?[]:c,h=t.metaArrays,p=void 0===h?[]:h,f=t.parentMessageId,_=void 0===f?null:f,g=t.pushNotificationDeliveryOption,y=void 0===g?null:g,m=t.appleCriticalAlertOptions,E=void 0===m?null:m,v=t.isReplyToChannel;return{mention_type:r,mentioned_user_ids:s,mentioned_message_template:o,cached_mentioned_users:u,cached_mentioned_user_ids:d,meta_arrays:p,parent_message_id:_,push_notification_delivery_option:y,apple_critical_alert_options:E,is_reply_to_channel:void 0!==v&&v}}},{key:"MentionType",get:function(){return{USERS:"users",CHANNEL:"channel"}}},{key:"PushNotificationDeliveryOption",get:function(){return{DEFAULT:"default",SUPPRESS:"suppress"}}}]),e}(),Cr=function(e){f(n,e);var t=E(n);function n(e){var r;return c(this,n),(r=t.call(this,e)).message=null,r._translationTargetLanguages=[],e&&r._update(e),r}return h(n,[{key:"serialize",value:function(){return b(_(n.prototype),"_serialize",this).call(this,(function(e){e.hasOwnProperty("_translationTargetLanguages")&&(e.translationTargetLanguages=e._translationTargetLanguages,delete e._translationTargetLanguages)}))}},{key:"targetLanguages",get:function(){return this.translationTargetLanguages},set:function(e){this.translationTargetLanguages=e}},{key:"translationTargetLanguages",get:function(){return this._translationTargetLanguages},set:function(e){if(Array.isArray(e)){for(var t=0;t0&&"number"==typeof r?new this(t,n,r):null},e.objectify=function(e){return{key:e.key,user_ids:e.userIds,updated_at:e.updatedAt}},e.prototype._applyEvent=function(e){if(e.key===this.key&&(!this._version[e.userId]||this._version[e.userId]=0&&this.userIds.splice(t,1)}this._version[e.userId]=e.updatedAt}},e}(),Nr=function(e){f(n,e);var t=E(n);function n(e){var r;return c(this,n),(r=t.call(this,e)).messageType=pt.MESSAGE_TYPE_USER,r.message=null,r._sender=null,r.translations={},r.requestState=null,r.requestedMentionUserIds=[],r.errorCode=0,r.messageSurvivalSeconds=-1,r.plugins=[],r._messageParams=null,e&&r._update(e),r}return h(n,[{key:"_update",value:function(e){var t=wi.getInstance(this._iid),n=x.get(this._iid),r=n.Sender,i=n.Plugin;this.message=String(e.message),this._sender=new r(e.user),this.reqId=e.hasOwnProperty("req_id")?String(e.req_id):"",this.translations=e.hasOwnProperty("translations")?e.translations:{},this.requestState=this.messageId>0?t.MessageRequestState.SUCCEEDED:t.MessageRequestState.FAILED,e.hasOwnProperty("sending_status")&&(this.requestState=e.sending_status,this.requestState===t.MessageSendingStatus.CANCELED&&(this.requestState=t.MessageRequestState.FAILED)),this.requestedMentionUserIds=[],e.hasOwnProperty("requested_mention_user_ids")&&(this.requestedMentionUserIds=e.requested_mention_user_ids),this.errorCode=0,e.hasOwnProperty("error_code")&&(this.errorCode=e.error_code),this.messageSurvivalSeconds=-1,e.hasOwnProperty("message_survival_seconds")&&(this.messageSurvivalSeconds=e.message_survival_seconds),this.plugins=[],e.hasOwnProperty("plugins")&&Array.isArray(e.plugins)&&(this.plugins=e.plugins.map((function(e){return new i(e)}))),e.hasOwnProperty("message_params")&&(this._messageParams=new Cr(e.message_params))}},{key:"sender",get:function(){var e=wi.getInstance(this._iid),t=x.get(this._iid).GroupChannel;if(this._sender&&e.Options.useMemberAsMessageSender&&this.isGroupChannel()){var n=t.cachedChannels[this.channelUrl];if(n){var r=n.memberMap[this._sender.userId];r&&(this._sender.nickname!==r.nickname&&(this._sender.nickname=r.nickname),this._sender.plainProfileUrl!==r.plainProfileUrl&&(this._sender.plainProfileUrl=r.plainProfileUrl),se.deepEqual(this._sender.metaData,r.metaData)||(this._sender.metaData=r.metaData))}}return this._sender},set:function(e){this._sender=e}},{key:"isResendable",value:function(){var e=wi.getInstance(this._iid);return this.sendingStatus===e.MessageSendingStatus.FAILED&&se.isResendableError(this.errorCode)}},{key:"serialize",value:function(){var e=this;return b(_(n.prototype),"serialize",this).call(this,(function(t){e._messageParams&&(t.messageParams=e._messageParams.serialize())}))}},{key:"messageParams",get:function(){return this._messageParams}},{key:"_clone",value:function(){return x.get(this._iid).UserMessage.buildFromSerializedData(this.serialize())}},{key:"_isSentByMe",value:function(){var e=wi.getInstance(this._iid);return this.sendingStatus===e.MessageSendingStatus.SUCCEEDED&&0===this.updatedAt&&this._sender&&this._sender.userId===e.currentUser.userId}}],[{key:"objectify",value:function(e){var t=wi.getInstance(this._iid),n=x.get(this._iid),r=n.BaseChannel,i=n.BaseMessageParams,s=n.Sender,a=n.User,o=n.UserMessage,u=n.FileMessage,c=n.AdminMessage,d=n.ThreadInfo,h=n.OGMetaData,p=n.Plugin,f=n.Reaction,_=n.AppleCriticalAlertOptions,g=n.UserMessageParams,y=e.messageId,m=e.messageType,E=void 0===m?pt.MESSAGE_TYPE_BASE:m,v=e.reqId,b=void 0===v?"":v,C=e.user,A=e.channel,N=void 0===A?null:A,S=e.channelUrl,I=void 0===S?"":S,T=e.channelType,U=void 0===T?r.CHANNEL_TYPE_OPEN:T,O=e.message,M=e.data,k=void 0===M?"":M,R=e.customType,L=void 0===R?"":R,w=e.mentionType,P=void 0===w?i.MentionType.USERS:w,D=e.mentionedUsers,H=void 0===D?[]:D,F=e.mentionedUserIds,G=void 0===F?[]:F,j=e.mentionedMessageTemplate,B=void 0===j?null:j,V=e.requestedMentionUserIds,q=void 0===V?[]:V,K=e.reactions,z=void 0===K?[]:K,Y=e.metaArrays,Q=void 0===Y?[]:Y,W=e.rootMessageId,J=void 0===W?0:W,X=e.parentMessageId,Z=void 0===X?0:X,$=e.parentMessageText,ee=void 0===$?"":$,te=e.threadInfo,ne=void 0===te?null:te,re=e.isReplyToChannel,ie=void 0!==re&&re,se=e.parentMessage,ae=void 0===se?null:se,oe=e.translations,le=void 0===oe?{}:oe,ue=e.sendingStatus,ce=e.errorCode,de=void 0===ce?0:ce,he=e.silent,pe=void 0!==he&&he,fe=e.isGlobalBlocked,_e=void 0!==fe&&fe,ge=e.messageSurvivalSeconds,ye=void 0===ge?-1:ge,me=e.ogMetaData,Ee=void 0===me?null:me,ve=e.isOperatorMessage,be=void 0!==ve&&ve,Ce=e.plugins,Ae=void 0===Ce?[]:Ce,Ne=e.appleCriticalAlertOptions,Se=e.createdAt,Ie=e.updatedAt,Te=void 0===Ie?0:Ie,Ue=e.messageParams,Oe=void 0===Ue?null:Ue,Me=e.isAutoResendRegistered,ke=void 0!==Me&&Me,Re={};switch(Re.req_id=b,Re.msg_id=y,E){case pt.MESSAGE_TYPE_USER:Re.type="MESG";break;case pt.MESSAGE_TYPE_FILE:Re.type="FILE";break;case pt.MESSAGE_TYPE_ADMIN:Re.type="ADMM"}if(Re.user=s.objectify(l({},C)),Re.channel_url=N?N.url:I,Re.channel_type=N?N.channelType:U,Re.message=O,Re.data=k,Re.custom_type=L,Re.translations=le,Re.is_global_block=!!_e,Re.ts=Se,Re.updated_at=Te,Re.mention_type=P,Re.mentioned_users=H.map((function(e){return a.objectify(e)})),Re.mentioned_user_ids=G,Re.mentioned_message_template=B,Re.requested_mention_user_ids=q,Re.reactions=z.map((function(e){return f.objectify(e)})),Re.metaarray={},Q.forEach((function(e){var t=e.key;Re.metaarray[t]=e.value})),Re.metaarray_key_order=Q.map((function(e){return e.key})),Re.root_message_id=J,Re.parent_message_id=Z,Re.parent_message_text=ee,ne&&(Re.thread_info=d.objectify(ne)),Re.is_reply_to_channel=ie,ae)switch(ae.messageType){case pt.MESSAGE_TYPE_USER:Re.parent_message_info=o._objectifySerializedData(ae);break;case pt.MESSAGE_TYPE_FILE:Re.parent_message_info=u._objectifySerializedData(ae);break;case pt.MESSAGE_TYPE_ADMIN:Re.parent_message_info=c._objectifySerializedData(ae)}return Re.sending_status=y>0?t.MessageSendingStatus.SUCCEEDED:t.MessageSendingStatus.FAILED,ue&&(Re.sending_status=ue),Re.silent=!!pe,Re.error_code=de,Re.message_survival_seconds=ye,Ee&&(Re.og_tag=h.objectify(Ee)),Re.is_op_msg=!!be,Re.plugins=Ae.map((function(e){return p.objectify(e)})),Ne&&(Re.apple_critical_alert_options=_.objectify(Ne)),Oe&&(Re.message_params=g.objectify(Oe)),Re.is_auto_resend_registered=ke,Re}},{key:"build",value:function(e,t,n,r,i,s,a,o,l,u,c,d,h,p,f,_,g,y,m,E,v,b,C,A,N,S,I,T,U,O){return this.objectify({messageId:t,reqId:e,user:n,channel:r,message:i,data:s,customType:a,mentionType:p,mentionedUsers:f,mentionedUserIds:E,mentionedMessageTemplate:v,requestedMentionUserIds:C,reactions:h,metaArrays:d,rootMessageId:_,parentMessageId:g,parentMessageText:y,threadInfo:m,translations:o,sendingStatus:b,errorCode:A,isGlobalBlocked:l,messageSurvivalSeconds:N,ogMetaData:S,isOperatorMessage:I,plugins:T,appleCriticalAlertOptions:U,createdAt:u,updatedAt:c,messageParams:O})}},{key:"buildFromSerializedData",value:function(e){var t=x.get(this._iid).UserMessage,n=ct.deserialize(e);return new t(this._objectifySerializedData(n))}},{key:"_objectifySerializedData",value:function(e){return x.get(this._iid).UserMessage.objectify(l(l({},e),{},{channel:{url:e.channelUrl,channelType:e.channelType},user:e.sender,messageParams:e.messageParams?new Cr(Cr.objectify(e.messageParams)):null}))}}]),n}(pt),Sr=function(e){f(n,e);var t=E(n);function n(e){var r;return c(this,n),(r=t.call(this,e)).fileName=null,r.mimeType=null,r.fileSize=null,r._isUpdate=!1,r._file=null,r._fileType=null,r._fileUrl=null,r._thumbnailSizes=[],e&&r._update(e),r}return h(n,[{key:"serialize",value:function(){return b(_(n.prototype),"_serialize",this).call(this,(function(e){e.hasOwnProperty("_isUpdate")&&(e.isUpdate=e._isUpdate,delete e._isUpdate),e.hasOwnProperty("_file")&&(e.file=e._file,delete e._file),e.hasOwnProperty("_fileType")&&(e.fileType=e._fileType,delete e._fileType),e.hasOwnProperty("_fileUrl")&&(e.fileUrl=e._fileUrl,delete e._fileUrl),e.hasOwnProperty("_thumbnailSizes")&&(e.thumbnailSizes=e._thumbnailSizes,delete e._thumbnailSizes)}))}},{key:"file",get:function(){return this._file},set:function(e){se.isFile(e)&&(this._fileUrl=null,this._file=e,te.isFile(e)?this._fileType=D.FILE:te.isBlob(e)?this._fileType=D.BLOB:te.isFileLikeObject(e)?this._fileType=D.BLOB_LIKE_OBJECT:"string"==typeof e&&(this._fileType=D.URL))}},{key:"fileType",get:function(){return this._fileType}},{key:"fileUrl",get:function(){return this._fileUrl},set:function(e){"string"==typeof e&&(this._fileUrl=e,this._file=null)}},{key:"thumbnailSizes",get:function(){return this._thumbnailSizes},set:function(e){if(Array.isArray(e)){for(var t=0;t0&&e.maxHeight>0})))}}],[{key:"objectify",value:function(e){var t=e.fileName,n=void 0===t?null:t,r=e.mimeType,i=void 0===r?null:r,s=e.fileSize,a=void 0===s?null:s,o=e.data,u=void 0===o?null:o,c=e.customType,d=void 0===c?null:c,h=e.isUpdate,p=void 0!==h&&h,f=e.file,_=void 0===f?null:f,g=e.fileType,y=void 0===g?null:g,m=e.fileUrl,E=void 0===m?null:m,v=e.thumbnailSizes,b=void 0===v?[]:v;return l(l({},br._objectify(e)),{},{file_name:n,mime_type:i,file_size:a,data:u,custom_type:d,is_update:p,file:_,file_type:y,file_url:E,thumbnail_sizes:b})}}]),n}(br),Ir=function(e){f(n,e);var t=E(n);function n(e){var r;return c(this,n),(r=t.call(this,e)).messageType=pt.MESSAGE_TYPE_FILE,r.plainUrl=null,r.name="File",r.size=0,r.type=null,r.thumbnails=[],r._sender=null,r.requireAuth=null,r.requestState=null,r.requestedMentionUserIds=[],r.errorCode=0,r.messageSurvivalSeconds=-1,r._messageParams=null,e&&r._update(e),r}return h(n,[{key:"_update",value:function(e){var t=wi.getInstance(this._iid),n=O.get(this._iid).container.auth,r=x.get(this._iid).Sender;if(this._sender=new r(e.user),this.requireAuth=!!e.hasOwnProperty("require_auth")&&e.require_auth,e.hasOwnProperty("url")&&(this.plainUrl=e.url.split("?auth=")[0]),this.name=e.hasOwnProperty("name")?e.name:"File",this.size=parseInt(e.size)||0,this.type=e.type,e.hasOwnProperty("custom")&&(this.data=e.custom),e.hasOwnProperty("file")){var i=e.file;i.hasOwnProperty("url")&&(this.plainUrl=i.url),i.hasOwnProperty("name")&&(this.name=i.name),i.hasOwnProperty("size")&&(this.size=i.size),i.hasOwnProperty("type")&&(this.type=i.type),i.hasOwnProperty("custom")&&(this.data=i.custom)}if(Object.defineProperty(this,"url",{value:this.requireAuth?"".concat(this.plainUrl,"?auth=").concat(n.eKey):this.plainUrl,configurable:!0,writable:!1}),this.reqId=e.hasOwnProperty("req_id")?String(e.req_id):"",this.thumbnails=e.hasOwnProperty("thumbnails")?e.thumbnails:[],this.requireAuth)for(var s=0;s0?t.MessageRequestState.SUCCEEDED:t.MessageRequestState.FAILED,e.hasOwnProperty("sending_status")&&(this.requestState=e.sending_status,this.requestState===t.MessageSendingStatus.CANCELED&&(this.requestState=t.MessageRequestState.FAILED)),this.requestedMentionUserIds=[],e.hasOwnProperty("requested_mention_user_ids")&&(this.requestedMentionUserIds=e.requested_mention_user_ids),this.errorCode=0,e.hasOwnProperty("error_code")&&(this.errorCode=e.error_code),this.messageSurvivalSeconds=-1,e.hasOwnProperty("message_survival_seconds")&&(this.messageSurvivalSeconds=e.message_survival_seconds),e.hasOwnProperty("message_params")&&(this._messageParams=new Sr(e.message_params))}},{key:"sender",get:function(){var e=wi.getInstance(this._iid),t=x.get(this._iid).GroupChannel;if(this._sender&&e.Options.useMemberAsMessageSender&&this.isGroupChannel()){var n=t.cachedChannels[this.channelUrl];if(n){var r=n.memberMap[this._sender.userId];r&&(this._sender.nickname!==r.nickname&&(this._sender.nickname=r.nickname),this._sender.plainProfileUrl!==r.plainProfileUrl&&(this._sender.plainProfileUrl=r.plainProfileUrl),se.deepEqual(this._sender.metaData,r.metaData)||(this._sender.metaData=r.metaData))}}return this._sender},set:function(e){this._sender=e}},{key:"isResendable",value:function(){var e=wi.getInstance(this._iid);return this.sendingStatus===e.MessageSendingStatus.FAILED&&se.isResendableError(this.errorCode)}},{key:"serialize",value:function(){var e=this;return b(_(n.prototype),"serialize",this).call(this,(function(t){e._messageParams&&(t.messageParams=e._messageParams.serialize())}))}},{key:"messageParams",get:function(){return this._messageParams}},{key:"_clone",value:function(){var e=x.get(this._iid).FileMessage.buildFromSerializedData(this.serialize());if(this._messageParams&&e._messageParams){var t=this._messageParams.file;t&&te.isBlob(t)&&(e._messageParams.file=t.slice())}return e}},{key:"_isSentByMe",value:function(){var e=wi.getInstance(this._iid);return this.sendingStatus===e.MessageSendingStatus.SUCCEEDED&&0===this.updatedAt&&this._sender&&this._sender.userId===e.currentUser.userId}}],[{key:"objectify",value:function(e){var t=wi.getInstance(this._iid),n=x.get(this._iid),r=n.BaseChannel,i=n.BaseMessageParams,s=n.Sender,a=n.User,o=n.UserMessage,u=n.FileMessage,c=n.AdminMessage,d=n.ThreadInfo,h=n.OGMetaData,p=n.Reaction,f=n.FileMessageParams,_=n.AppleCriticalAlertOptions,g=e.messageId,y=e.messageType,m=void 0===y?pt.MESSAGE_TYPE_BASE:y,E=e.reqId,v=void 0===E?"":E,b=e.user,C=void 0===b?{}:b,A=e.channel,N=e.plainUrl,S=e.name,I=void 0===S?null:S,T=e.type,U=e.size,O=void 0===U?0:U,M=e.data,k=void 0===M?"":M,R=e.customType,L=void 0===R?"":R,w=e.mentionType,P=void 0===w?i.MentionType.USERS:w,D=e.mentionedUsers,H=void 0===D?[]:D,F=e.mentionedUserIds,G=void 0===F?[]:F,j=e.requestedMentionUserIds,B=void 0===j?[]:j,V=e.reactions,q=void 0===V?[]:V,K=e.metaArrays,z=void 0===K?[]:K,Y=e.rootMessageId,Q=void 0===Y?0:Y,W=e.parentMessageId,J=void 0===W?0:W,X=e.parentMessageText,Z=void 0===X?"":X,$=e.threadInfo,ee=void 0===$?null:$,te=e.isReplyToChannel,ne=void 0!==te&&te,re=e.parentMessage,ie=void 0===re?null:re,se=e.thumbnails,ae=void 0===se?[]:se,oe=e.requireAuth,le=void 0!==oe&&oe,ue=e.sendingStatus,ce=e.errorCode,de=void 0===ce?0:ce,he=e.silent,pe=void 0!==he&&he,fe=e.isGlobalBlocked,_e=void 0!==fe&&fe,ge=e.messageSurvivalSeconds,ye=void 0===ge?-1:ge,me=e.ogMetaData,Ee=void 0===me?null:me,ve=e.isOperatorMessage,be=void 0!==ve&&ve,Ce=e.appleCriticalAlertOptions,Ae=e.createdAt,Ne=e.updatedAt,Se=void 0===Ne?0:Ne,Ie=e.messageParams,Te=void 0===Ie?null:Ie,Ue=e.isAutoResendRegistered,Oe=void 0!==Ue&&Ue,Me={};switch(Me.req_id=v,Me.msg_id=g,m){case pt.MESSAGE_TYPE_USER:Me.type="MESG";break;case pt.MESSAGE_TYPE_FILE:Me.type="FILE";break;case pt.MESSAGE_TYPE_ADMIN:Me.type="ADMM"}Me.user=s.objectify(l({},C)),Me.channel_url=A.url,Me.channel_type=A.channelType===r.CHANNEL_TYPE_OPEN?r.CHANNEL_TYPE_OPEN:r.CHANNEL_TYPE_GROUP,Me.url=N,Me.name=I,Me.type=T,Me.size=O,Me.custom=k,Me.custom_type=L,Me.thumbnails=ae,Me.require_auth=le,Me.is_global_block=!!_e,Me.ts=Ae,Me.updated_at=Se,Me.mention_type=P,Me.mentioned_users=H.map((function(e){return a.objectify(e)})),Me.mentioned_user_ids=G,Me.requested_mention_user_ids=B,Me.reactions=q.map((function(e){return p.objectify(e)})),Me.metaarray={};for(var ke=0;ke0?t.MessageSendingStatus.SUCCEEDED:t.MessageSendingStatus.FAILED,ue&&(Me.sending_status=ue),Me.silent=!!pe,Me.error_code=de,Me.message_survival_seconds=ye,Ee&&(Me.og_tag=h.objectify(Ee)),Me.is_op_msg=!!be,Ce&&(Me.apple_critical_alert_options=_.objectify(Ce)),Te&&(Me.message_params=f.objectify(Te)),Me.is_auto_resend_registered=Oe,Me}},{key:"build",value:function(e,t,n,r,i,s,a,o,l,u,c,d,h,p,f,_,g,y,m,E,v,b,C,A,N,S,I,T,U,O,M,k){return this.objectify({messageId:t,reqId:e,user:n,channel:r,plainUrl:i,name:s,type:a,size:o,data:l,customType:u,mentionType:y,mentionedUsers:m,mentionedUserIds:A,requestedMentionUserIds:S,reactions:g,metaArrays:_,rootMessageId:E,parentMessageId:v,parentMessageText:b,threadInfo:C,thumbnails:h,requireAuth:p,sendingStatus:N,errorCode:I,isGlobalBlocked:c,messageSurvivalSeconds:T,ogMetaData:U,isOperatorMessage:O,appleCriticalAlertOptions:M,createdAt:d,updatedAt:f,messageParams:k})}},{key:"buildFromSerializedData",value:function(e){var t=x.get(this._iid).FileMessage,n=ct.deserialize(e);return new t(this._objectifySerializedData(n))}},{key:"_objectifySerializedData",value:function(e){return x.get(this._iid).FileMessage.objectify(l(l({},e),{},{channel:{url:e.channelUrl,channelType:e.channelType},user:e.sender,messageParams:e.messageParams?new Sr(Sr.objectify(e.messageParams)):null}))}}]),n}(pt),Tr=function(e){f(n,e);var t=E(n);function n(e){var r;return c(this,n),(r=t.call(this,e)).messageType=pt.MESSAGE_TYPE_ADMIN,r.message="",r.translations={},e&&r._update(e),r}return h(n,[{key:"_update",value:function(e){this.message=String(e.message),this.translations=e.hasOwnProperty("translations")?e.translations:{}}}],[{key:"objectify",value:function(e){var t=x.get(this._iid),n=t.BaseChannel,r=t.BaseMessageParams,i=t.UserMessage,s=t.FileMessage,a=t.AdminMessage,o=t.User,l=t.ThreadInfo,u=t.OGMetaData,c=t.Reaction,d=e.messageId,h=e.messageType,p=void 0===h?pt.MESSAGE_TYPE_BASE:h,f=e.channel,_=e.message,g=e.data,y=void 0===g?"":g,m=e.customType,E=void 0===m?"":m,v=e.mentionType,b=void 0===v?r.MentionType.USERS:v,C=e.mentionedUsers,A=void 0===C?[]:C,N=e.mentionedMessageTemplate,S=void 0===N?null:N,I=e.reactions,T=void 0===I?[]:I,U=e.metaArrays,O=void 0===U?[]:U,M=e.rootMessageId,k=void 0===M?0:M,R=e.parentMessageId,L=void 0===R?0:R,w=e.parentMessageText,P=void 0===w?"":w,D=e.threadInfo,H=void 0===D?null:D,F=e.isReplyToChannel,G=void 0!==F&&F,j=e.parentMessage,B=void 0===j?null:j,V=e.translations,q=void 0===V?{}:V,K=e.silent,z=void 0!==K&&K,Y=e.ogMetaData,Q=void 0===Y?null:Y,W=e.createdAt,J=e.updatedAt,X=void 0===J?0:J,Z={msg_id:d,channel_url:f.url,channel_type:f.channelType===n.CHANNEL_TYPE_OPEN?n.CHANNEL_TYPE_OPEN:n.CHANNEL_TYPE_GROUP,message:_,data:y,custom_type:E,silent:z,ts:W,updated_at:X};switch(p){case pt.MESSAGE_TYPE_USER:Z.type="MESG";break;case pt.MESSAGE_TYPE_FILE:Z.type="FILE";break;case pt.MESSAGE_TYPE_ADMIN:Z.type="ADMM"}Z.translations=q,Z.mention_type=b,Z.mentioned_users=A.map((function(e){return o.objectify(e)})),Z.mentioned_message_template=S,Z.reactions=T.map((function(e){return c.objectify(e)})),Z.metaarray={};for(var $=0;$0&&Array.isArray(t.userIdsFilter)&&"string"==typeof t.metaDataKeyFilter&&Array.isArray(t.metaDataValuesFilter)&&!!t.metaDataKeyFilter==t.metaDataValuesFilter.length>0&&("string"==typeof t.nicknameStartsWithFilter||null===t.nicknameStartsWithFilter)?t.isLoading?e(new H("Query in progress.",H.QUERY_IN_PROGRESS),null):t.hasNext?(t.isLoading=!0,O.get(t._iid).container.apiClient.loadUserList(l(l({},t),{},{token:t._token}),(function(n,r){var i=null;if(!n){var s=x.get(t._iid).User,a=String(r.next);t._token=a,t.hasNext=!!a,i=r.users.map((function(e){return new s(e)}))}t.isLoading=!1,e(n,i)}))):e(null,[]):e(me.error,null)}),e)}}]),e}(),kr=function(){function e(t){c(this,e),this.isLoading=!1,this.hasNext=!0,this.limit=20,this._isOpenChannel=!1,this._channelUrl=null,this._token="",t.channelUrl&&(this._channelUrl=t.channelUrl),t.isOpenChannel&&(this._isOpenChannel=t.isOpenChannel)}return h(e,[{key:"next",value:function(e){var t=this;return oe(this._iid,(function(e){"number"==typeof t.limit&&t.limit>0?t.isLoading?e(new H("Query in progress.",H.QUERY_IN_PROGRESS),null):t.hasNext?(t.isLoading=!0,O.get(t._iid).container.apiClient.loadBannedUserList(l(l({},t),{},{channelUrl:t._channelUrl,isOpenChannel:t._isOpenChannel,token:t._token}),(function(n,r){var i=null;if(!n){var s=x.get(t._iid).RestrictedUser,a=String(r.next);t._token=a,t.hasNext=!!a,i=r.banned_list.map((function(e){var t=new s(e);return t.restrictionInfo.restrictionType=s.RestrictionType.BANNED,t}))}t.isLoading=!1,e(n,i)}))):e(null,[]):e(me.error,null)}),e)}}]),e}(),Rr=function(){function e(){c(this,e),this.isLoading=!1,this.hasNext=!0,this.limit=20,this.userIdsFilter=[],this._token=""}return h(e,[{key:"next",value:function(e){var t=this;return oe(this._iid,(function(e){"number"==typeof t.limit&&t.limit>0&&Array.isArray(t.userIdsFilter)?t.isLoading?e(new H("Query in progress.",H.QUERY_IN_PROGRESS),null):t.hasNext?(t.isLoading=!0,O.get(t._iid).container.apiClient.loadBlockedUserList(l(l({},t),{},{token:t._token}),(function(n,r){var i=null;if(!n){var s=x.get(t._iid).User,a=String(r.next);t._token=a,t.hasNext=!!a,i=r.users.map((function(e){return new s(e)}))}t.isLoading=!1,e(n,i)}))):e(null,[]):e(me.error,null)}),e)}}]),e}(),Lr=function(){function e(){c(this,e),this.isLoading=!1,this.hasMore=!0,this.limit=20,this._token=""}return h(e,[{key:"next",value:function(e){var t=this;return oe(this._iid,(function(e){"number"==typeof t.limit&&t.limit>0?t.isLoading?e(new H("Query in progress.",H.QUERY_IN_PROGRESS),null):t.hasMore?(t.isLoading=!0,O.get(t._iid).container.apiClient.loadFriendList(l(l({},t),{},{token:t._token}),(function(n,r){var i=null;if(!n){var s=x.get(t._iid).User,a=String(r.next);t._token=a,t.hasMore=!!a,i=r.users.map((function(e){return new s(e)}))}t.isLoading=!1,e(n,i)}))):e(null,[]):e(me.error,null)}),e)}}]),e}(),wr=function(){function e(){c(this,e),this.isLoading=!1,this.hasNext=!0,this.limit=20,this.includeEmpty=!1,this.order=e.ORDER_LATEST_LAST_MESSAGE,this._token="",this._searchFilter={},this._userIdsFilter={userIds:[],includeMode:!0,queryType:e.QueryType.AND},this._userIdsExactFilter=[],this._userIdsIncludeFilter=[],this._userIdsIncludeFilterQueryType=e.QueryType.AND,this.nicknameContainsFilter="",this.nicknameStartsWithFilter="",this.nicknameExactMatchFilter="",this.channelNameContainsFilter="",this.memberStateFilter=ar.MemberStateFilter.ALL,this.customTypesFilter=[],this.channelUrlsFilter=[],this.superChannelFilter=ar.SuperChannelFilter.ALL,this.publicChannelFilter=ar.PublicChannelFilter.ALL,this.customTypeStartsWithFilter=null,this.unreadChannelFilter=ar.UnreadChannelFilter.ALL,this.metadataOrderKeyFilter=null,this.metadataKey=null,this.metadataValues=[],this.metadataValueStartsWith=null,this.hiddenChannelFilter=ar.HiddenChannelFilter.UNHIDDEN,this.includeFrozen=!0,this.includeMetaData=!0}return h(e,[{key:"userIdsExactFilter",get:function(){return this._userIdsExactFilter},set:function(e){Array.isArray(e)&&(this._userIdsExactFilter=e,this._userIdsIncludeFilter=[],this._userIdsFilter.userIds=this._userIdsExactFilter,this._userIdsFilter.includeMode=!1)}},{key:"userIdsIncludeFilter",get:function(){return this._userIdsIncludeFilter},set:function(e){Array.isArray(e)&&(this._userIdsIncludeFilter=e,this._userIdsExactFilter=[],this._userIdsFilter.userIds=this._userIdsIncludeFilter,this._userIdsFilter.includeMode=!0)}},{key:"userIdsIncludeFilterQueryType",get:function(){return this._userIdsIncludeFilterQueryType},set:function(t){Object.keys(e.QueryType).map((function(t){return e.QueryType[t]})).indexOf(t)>-1&&(this._userIdsIncludeFilterQueryType=t.toUpperCase(),this._userIdsFilter.queryType=this._userIdsIncludeFilterQueryType)}},{key:"setSearchFilter",value:function(e,t){Array.isArray(e)&&0!==e.length&&"string"==typeof t&&t&&(this._searchFilter={search_query:t,search_fields:e.join(",").toLocaleLowerCase()})}},{key:"serialize",value:function(){return ct.serialize(this,(function(e){e.isLoading=!1}))}},{key:"next",value:function(e){var t=this;return oe(this._iid,(function(e){var n=x.get(t._iid),r=n.GroupChannel,i=n.GroupChannelListQuery;!("number"==typeof t.limit&&t.limit>0&&"boolean"==typeof t.includeEmpty&&"string"==typeof t.order&&[i.ORDER_CHRONOLOGICAL,i.ORDER_LATEST_LAST_MESSAGE,i.CHANNEL_NAME_ALPHABETICAL,i.METADATA_VALUE_ALPHABETICAL].indexOf(t.order.toLowerCase())>-1&&Array.isArray(t._userIdsExactFilter)&&Array.isArray(t._userIdsIncludeFilter)&&Array.isArray(t.customTypesFilter)&&Array.isArray(t.channelUrlsFilter)&&Object.keys(i.QueryType).map((function(e){return i.QueryType[e]})).indexOf(t._userIdsIncludeFilterQueryType.toUpperCase())>-1&&Object.keys(r.MemberStateFilter).map((function(e){return r.MemberStateFilter[e]})).indexOf(t.memberStateFilter)>-1&&Object.keys(r.SuperChannelFilter).map((function(e){return r.SuperChannelFilter[e]})).indexOf(t.superChannelFilter)>-1&&Object.keys(r.PublicChannelFilter).map((function(e){return r.PublicChannelFilter[e]})).indexOf(t.publicChannelFilter)>-1&&Object.keys(r.UnreadChannelFilter).map((function(e){return r.UnreadChannelFilter[e]})).indexOf(t.unreadChannelFilter)>-1&&Object.keys(r.HiddenChannelFilter).map((function(e){return r.HiddenChannelFilter[e]})).indexOf(t.hiddenChannelFilter)>-1)||"string"!=typeof t.customTypeStartsWithFilter&&null!==t.customTypeStartsWithFilter||"string"!=typeof t.nicknameContainsFilter||"string"!=typeof t.nicknameStartsWithFilter||"string"!=typeof t.nicknameExactMatchFilter||"string"!=typeof t.channelNameContainsFilter||"string"!=typeof t.metadataOrderKeyFilter&&null!==t.metadataOrderKeyFilter||"string"!=typeof t.metadataKey&&null!==t.metadataKey||!Array.isArray(t.metadataValues)||!t.metadataValues.every((function(e){return"string"==typeof e}))||"string"!=typeof t.metadataValueStartsWith&&null!==t.metadataValueStartsWith||"boolean"!=typeof t.includeFrozen||"boolean"!=typeof t.includeMetaData?e(me.error,null):t.isLoading?e(new H("Query in progress.",H.QUERY_IN_PROGRESS),null):t.hasNext?(t.isLoading=!0,O.get(t._iid).container.apiClient.loadGroupChannelList(l(l({},t),{},{token:t._token,userIdsFilter:t._userIdsFilter,searchFilter:t._searchFilter})).then((function(n){var r=x.get(t._iid).GroupChannel,i=String(n.next);t._token=i,t.hasNext=!!i;var s=n.channels;if(!s||!Array.isArray(s))throw new H("Failed at loading group channels.",H.MALFORMED_DATA);var a=s.map((function(e){return"number"==typeof n.ts&&(e.ts=n.ts),r.upsert(e)}));t.isLoading=!1,e(null,a)})).catch((function(n){t.isLoading=!1,e(n,null)}))):e(null,[])}),e)}}],[{key:"ORDER_LATEST_LAST_MESSAGE",get:function(){return"latest_last_message"}},{key:"ORDER_CHRONOLOGICAL",get:function(){return"chronological"}},{key:"CHANNEL_NAME_ALPHABETICAL",get:function(){return"channel_name_alphabetical"}},{key:"METADATA_VALUE_ALPHABETICAL",get:function(){return"metadata_value_alphabetical"}},{key:"QueryType",get:function(){return{AND:"AND",OR:"OR"}}},{key:"SearchField",get:function(){return{MEMBER_NICKNAME:"member_nickname",CHANNEL_NAME:"channel_name"}}},{key:"buildFromSerializedData",value:function(e){var t=x.get(this._iid).GroupChannel,n=ct.deserialize(e),r=t.createMyGroupChannelListQuery();return Object.keys(n).forEach((function(e){r.hasOwnProperty(e)&&(r[e]=n[e])})),r}}]),e}(),Pr=function(){function e(t){c(this,e),this.isLoading=!1,this.hasNext=!0,this.limit=20,this.mutedMemberFilter=e.MutedMemberFilter.ALL,this.memberStateFilter=ar.MemberStateFilter.ALL,this.nicknameStartsWithFilter=null,this.order=e.Order.MEMBER_NICKNAME_ALPHABETICAL,this._token="",this._channelUrl=t}return h(e,[{key:"next",value:function(e){var t=this;return oe(this._iid,(function(e){var n=x.get(t._iid),r=n.GroupChannel,i=n.Member,s=n.MemberListQuery;if("number"==typeof t.limit&&t.limit>0&&Object.keys(s.MutedMemberFilter).map((function(e){return s.MutedMemberFilter[e]})).indexOf(t.mutedMemberFilter)>-1&&Object.keys(r.MemberStateFilter).map((function(e){return r.MemberStateFilter[e]})).indexOf(t.memberStateFilter)>-1&&Object.keys(s.Order).map((function(e){return s.Order[e]})).indexOf(t.order)>-1&&("string"==typeof t.nicknameStartsWithFilter||null===t.nicknameStartsWithFilter))if(t.isLoading)e(new H("Query in progress.",H.QUERY_IN_PROGRESS),null);else if(t.hasNext){t.isLoading=!0;var a=O.get(t._iid);t.memberStateFilter===r.MemberStateFilter.LEFT&&(t.memberStateFilter=r.MemberStateFilter.ALL),a.container.apiClient.loadMemberList(l(l({},t),{},{channelUrl:t._channelUrl,token:t._token}),(function(n,r){var s=null;if(!n){var a=String(r.next);t._token=a,t.hasNext=!!a,s=r.members.map((function(e){return new i(e)}))}t.isLoading=!1,e(n,s)}))}else e(null,[]);else e(me.error,null)}),e)}}],[{key:"MutedMemberFilter",get:function(){return{ALL:"all",MUTED:"muted",UNMUTED:"unmuted"}}},{key:"Order",get:function(){return{MEMBER_NICKNAME_ALPHABETICAL:"member_nickname_alphabetical",OPERATOR_THEN_MEMBER_ALPHABETICAL:"operator_then_member_alphabetical"}}}]),e}(),Dr=function(){function e(t){c(this,e),this.isLoading=!1,this.hasNext=!0,this.limit=20,this._token="",t.channelUrl&&(this._channelUrl=t.channelUrl),t.isOpenChannel&&(this._isOpenChannel=t.isOpenChannel)}return h(e,[{key:"next",value:function(e){var t=this;return oe(this._iid,(function(e){"number"==typeof t.limit&&t.limit>0?t.isLoading?e(new H("Query in progress.",H.QUERY_IN_PROGRESS),null):t.hasNext?(t.isLoading=!0,O.get(t._iid).container.apiClient.loadMutedUserList(l(l({},t),{},{channelUrl:t._channelUrl,isOpenChannel:t._isOpenChannel,token:t._token}),(function(n,r){var i=null;if(!n){var s=x.get(t._iid).RestrictedUser,a=String(r.next);t._token=a,t.hasNext=!!a,i=r.muted_list.map((function(e){var t=new s(e);return t.restrictionInfo.restrictionType=s.RestrictionType.MUTED,t}))}t.isLoading=!1,e(n,i)}))):e(null,[]):e(me.error,null)}),e)}}]),e}(),Hr=function(){function e(){c(this,e),this.limit=20,this.isLoading=!1,this.hasNext=!0,this.nameKeyword=null,this.urlKeyword=null,this.customTypes=[],this.includeFrozen=!0,this.includeMetaData=!0}return h(e,[{key:"next",value:function(e){var t=this;return oe(this._iid,(function(e){!("number"==typeof t.limit&&t.limit>0&&Array.isArray(t.customTypes))||"string"!=typeof t.nameKeyword&&null!==t.nameKeyword||"string"!=typeof t.urlKeyword&&null!==t.urlKeyword||"boolean"!=typeof t.includeFrozen||"boolean"!=typeof t.includeMetaData?e(me.error,null):t.isLoading?e(new H("Query in progress.",H.QUERY_IN_PROGRESS),null):t.hasNext?(t.isLoading=!0,O.get(t._iid).container.apiClient.loadOpenChannelList(l(l({},t),{},{token:t._token}),(function(n,r){var i=null;if(!n){var s=x.get(t._iid).OpenChannel,a=String(r.next);t._token=a,t.hasNext=!!a;var o=r.channels;o&&Array.isArray(o)?i=o.map((function(e){return"number"==typeof r.ts&&(e.ts=r.ts),s.upsert(e)})):n=new H("Failed at loading open channels.",H.MALFORMED_DATA)}t.isLoading=!1,e(n,i)}))):e(null,[])}),e)}}]),e}(),Fr=new WeakMap,Gr=function(){function e(t){c(this,e),this.isLoading=!1,this.hasNext=!0,this.limit=20,this._token="",Fr.set(this,t)}return h(e,[{key:"next",value:function(e){var t=this;return oe(this._iid,(function(e){if("number"==typeof t.limit&&t.limit>0)if(t.isLoading)e(new H("Query in progress.",H.QUERY_IN_PROGRESS),null);else if(t.hasNext){t.isLoading=!0;var n=Fr.get(t);O.get(t._iid).container.apiClient.loadOperatorList(l(l({},t),{},{token:t._token,channelUrl:n.url,isOpenChannel:n.isOpenChannel()}),(function(n,r){var i=null;if(!n){var s=x.get(t._iid).User,a=String(r.next);t._token=a,t.hasNext=!!a,i=r.operators.map((function(e){return new s(e)}))}t.isLoading=!1,e(n,i)}))}else e(null,[]);else e(me.error,null)}),e)}}]),e}(),xr=new WeakMap,jr=function(){function e(t){c(this,e),this.isLoading=!1,this.hasNext=!0,this.limit=20,this._token="",t&&xr.set(this,t.channelUrl)}return h(e,[{key:"next",value:function(e){var t=this;return oe(this._iid,(function(e){"number"==typeof t.limit&&t.limit>0?t.isLoading?e(new H("Query in progress.",H.QUERY_IN_PROGRESS),null):t.hasNext?(t.isLoading=!0,O.get(t._iid).container.apiClient.loadParticipantList(l(l({},t),{},{channelUrl:xr.get(t),token:t._token}),(function(n,r){var i=null;if(!n){var s=x.get(t._iid).User,a=String(r.next);t._token=a,t.hasNext=!!a,i=r.participants.map((function(e){return new s(e)}))}t.isLoading=!1,e(n,i)}))):e(null,[]):e(me.error,null)}),e)}}]),e}(),Br=new WeakMap,Vr=function(){function e(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=n.limit,i=void 0===r?20:r,s=n.reverse,a=void 0!==s&&s,o=n.exactMatch,l=void 0!==o&&o,u=n.channelUrl,d=void 0===u?"":u,h=n.channelCustomType,p=void 0===h?"":h,f=n.messageTimestampFrom,_=void 0===f?null:f,g=n.messageTimestampTo,y=void 0===g?null:g,m=n.order,E=void 0===m?"score":m,v=n.advancedQuery,b=void 0!==v&&v,C=n.targetFields,A=void 0===C?null:C;c(this,e),this.isLoading=!1,this.hasNext=!0,Br.set(this,{keyword:t,limit:i,reverse:a,exactMatch:l,channelUrl:d,channelCustomType:p,messageTimestampFrom:_,messageTimestampTo:y,order:E,advancedQuery:b,targetFields:A,previousToken:"",nextToken:""})}return h(e,[{key:"key",get:function(){return Br.get(this).keyword}},{key:"limit",get:function(){return Br.get(this).limit}},{key:"reverse",get:function(){return Br.get(this).reverse}},{key:"exactMatch",get:function(){return Br.get(this).exactMatch}},{key:"channelUrl",get:function(){return Br.get(this).channelUrl}},{key:"channelCustomType",get:function(){return Br.get(this).channelCustomType}},{key:"messageTimestampFrom",get:function(){return Br.get(this).messageTimestampFrom}},{key:"messageTimestampTo",get:function(){return Br.get(this).messageTimestampTo}},{key:"order",get:function(){return Br.get(this).order}},{key:"next",value:function(e){var t=this,n=x.get(this._iid),r=n.BaseChannel,i=n.GroupChannel,s=n.OpenChannel;return oe(this._iid,(function(e){var n=Br.get(t),a=n.keyword,o=n.limit,l=n.reverse,u=n.exactMatch,c=n.channelUrl,d=n.channelCustomType,h=n.messageTimestampFrom,p=n.messageTimestampTo,f=n.order,_=n.advancedQuery,g=n.targetFields,y=n.nextToken;!("number"==typeof o&&o>0&&o<=1e3&&"boolean"==typeof l&&"boolean"==typeof u)||"string"!=typeof c&&null!==c||"string"!=typeof d&&null!==d||"number"!=typeof h&&null!==h||"number"!=typeof p&&null!==p||!(["score","ts"].indexOf(f)>=0)||"boolean"!=typeof _&&null!==_||!Array.isArray(g)&&null!==g?e(me.error,null):t.isLoading?e(new H("Query in progress.",H.QUERY_IN_PROGRESS),null):t.hasNext?(t.isLoading=!0,O.get(t._iid).container.apiClient.searchMessages({keyword:a,limit:o,reverse:l,exactMatch:u,channelUrl:c,channelCustomType:d,messageTimestampFrom:h,messageTimestampTo:p,order:f,advancedQuery:_,targetFields:g,nextToken:y},(function(n,a){var o=null;n||(o=[],a.results.forEach((function(e){if(e.channel.hasOwnProperty("members")){var t=new i(e.channel);i.cachedChannels[t.url]=t,o.push(r.buildMessage(e,t))}else{var n=new s(e.channel);s.cachedChannels[n.url]=n,o.push(r.buildMessage(e,n))}})),t.hasNext=a.has_next,Br.get(t).nextToken=a.end_cursor),t.isLoading=!1,e(n,o)}))):e(null,[])}),e)}}]),e}(),qr=new WeakMap,Kr=new WeakMap,zr=function(){function e(t){c(this,e),this.isLoading=!1,this.hasMore=!0,this.limit=20,Kr.set(this,Number.MAX_SAFE_INTEGER),qr.set(this,t),this.reverse=!1,this.messageTypeFilter=null,this.customTypeFilter=null,this.customTypesFilter=[],this.senderUserIdsFilter=[],this.includeMetaArray=!1,this.includeReaction=null,this.includeReactions=null,this.includeReplies=null,this.includeParentMessageText=null,this.includeThreadInfo=!1,this.replyType=null,this.includeParentMessageInfo=null,this.showSubchannelMessagesOnly=!1}return h(e,[{key:"load",value:function(e,t,n,r){var i=this,s=x.get(this._iid),a=s.BaseChannel,o=s.BaseMessage,l=null,u=me.parse(arguments,[new me({type:"number",optional:!0,defaultValue:this.limit}),new me({type:"boolean",optional:!0,defaultValue:this.reverse}),new me({type:["string","number"],optional:!0,defaultValue:this.messageTypeFilter,constraint:function(e){return Object.keys(a.MessageTypeFilter).map((function(e){return a.MessageTypeFilter[e]})).indexOf(e)>-1||[0,1,2,3].indexOf(e)>-1}}),new me({type:"callback"})]),c=C(u,5);return l=c[0],e=c[1],t=c[2],n=c[3],r=c[4],oe(this._iid,(function(r){if(("string"!=typeof i.customTypeFilter&&null!==i.customTypeFilter||!Array.isArray(i.customTypesFilter)||!i.customTypesFilter.every((function(e){return"string"==typeof e||null===e}))||!Array.isArray(i.senderUserIdsFilter)||!i.senderUserIdsFilter.every((function(e){return"string"==typeof e}))||"boolean"!=typeof i.includeMetaArray||null!==i.includeReaction&&"boolean"!=typeof i.includeReaction||null!==i.includeReactions&&"boolean"!=typeof i.includeReactions||"boolean"!=typeof i.includeThreadInfo||null!==i.includeReplies&&"boolean"!=typeof i.includeReplies||!(null===i.replyType||"string"==typeof i.replyType&&Object.values(o.ReplyType).includes(i.replyType))||null!==i.includeParentMessageText&&"boolean"!=typeof i.includeParentMessageText||null!==i.includeParentMessageInfo&&"boolean"!=typeof i.includeParentMessageInfo||"boolean"!=typeof i.showSubchannelMessagesOnly)&&(l=me.error),l)r(l,null);else{if(i.limit=e,i.reverse=t,i.messageTypeFilter=n,"number"==typeof i.messageTypeFilter)switch(i.messageTypeFilter){case 0:i.messageTypeFilter=a.MessageTypeFilter.ALL;break;case 1:i.messageTypeFilter=a.MessageTypeFilter.USER;break;case 2:i.messageTypeFilter=a.MessageTypeFilter.FILE;break;case 3:i.messageTypeFilter=a.MessageTypeFilter.ADMIN}if(i.isLoading)r(new H("Query in progress.",H.QUERY_IN_PROGRESS),null);else if(i.hasMore){i.isLoading=!0;var s=qr.get(i);O.get(i._iid).container.apiClient.getMessageList({channel:s,token:Kr.get(i)||(new Date).getTime()+1e4,tokenType:"timestamp",isInclusive:!1,prevResultSize:e,nextResultSize:0,shouldReverse:t,messageType:i.messageTypeFilter,customType:i.customTypeFilter,customTypes:i.customTypesFilter,senderUserIds:i.senderUserIdsFilter,includeMetaArray:i.includeMetaArray,includeReaction:i.includeReaction,includeReactions:i.includeReactions,includeReplies:i.includeReplies,includeParentMessageText:i.includeParentMessageText,includeThreadInfo:i.includeThreadInfo,replyType:i.replyType,includeParentMessageInfo:i.includeParentMessageInfo,showSubchannelMessagesOnly:i.showSubchannelMessagesOnly}).then((function(t){var n=t.messages.map((function(e){return a.buildMessage(e,s)}));(0===n.length||n.length0&&"boolean"==typeof n.includeEmpty&&"string"==typeof n.order&&[e.ORDER_CHRONOLOGICAL,e.CHANNEL_NAME_ALPHABETICAL,e.METADATA_VALUE_ALPHABETICAL,e.ORDER_LATEST_LAST_MESSAGE].indexOf(n.order.toLowerCase())>-1&&Array.isArray(n.customTypesFilter)&&Array.isArray(n.channelUrlsFilter)&&Object.keys(e.MembershipType).map((function(t){return e.MembershipType[t]})).indexOf(n.membershipFilter)>-1&&Object.keys(r.SuperChannelFilter).map((function(e){return r.SuperChannelFilter[e]})).indexOf(n.superChannelFilter)>-1)||"string"!=typeof n.customTypeStartsWithFilter&&null!==n.customTypeStartsWithFilter||"string"!=typeof n.channelNameContainsFilter||"string"!=typeof n.metadataOrderKeyFilter&&null!==n.metadataOrderKeyFilter||"string"!=typeof n.metadataKey&&null!==n.metadataKey||!Array.isArray(n.metadataValues)||!n.metadataValues.every((function(e){return"string"==typeof e}))||"string"!=typeof n.metadataValueStartsWith&&null!==n.metadataValueStartsWith||"boolean"!=typeof n.includeFrozen||"boolean"!=typeof n.includeMetaData?t(me.error,null):n.isLoading?t(new H("Query in progress.",H.QUERY_IN_PROGRESS),null):n.hasNext?(n.isLoading=!0,O.get(n._iid).container.apiClient.loadPublicGroupChannelList(l(l({},n),{},{token:n._token}),(function(e,i){var s=null;if(!e){var a=String(i.next);n._token=a,n.hasNext=!!a;var o=i.channels;o&&Array.isArray(o)?s=o.map((function(e){return"number"==typeof i.ts&&(e.ts=i.ts),r.upsert(e)})):e=new H("Failed at loading group channels.",H.MALFORMED_DATA)}n.isLoading=!1,t(e,s)}))):t(null,[])}),t)}}],[{key:"MembershipType",get:function(){return{ALL:"all",JOINED:"joined"}}},{key:"ORDER_LATEST_LAST_MESSAGE",get:function(){return"latest_last_message"}},{key:"ORDER_CHRONOLOGICAL",get:function(){return"chronological"}},{key:"CHANNEL_NAME_ALPHABETICAL",get:function(){return"channel_name_alphabetical"}},{key:"METADATA_VALUE_ALPHABETICAL",get:function(){return"metadata_value_alphabetical"}}]),e}(),Qr=function(){function e(){c(this,e),this.isDistinct=null,this.isSuper=null,this.isBroadcast=null,this.isPublic=null,this.channelUrl=null,this.isEphemeral=null,this.isDiscoverable=null,this.isStrict=null,this.name=null,this.data=null,this.customType=null,this.channelCover=null,this.coverUrl=null,this.coverImage=null,this.accessCode=null,this.messageSurvivalSeconds=null,this._invitedUserIds=[];var t=null;Object.defineProperty(this,"operators",{set:function(e){Array.isArray(e)&&(e.filter((function(e){return e.hasOwnProperty("userId")})).length===e.length&&(t=e.map((function(e){return e.userId}))))}}),Object.defineProperty(this,"operatorUserIds",{get:function(){return t},set:function(e){Array.isArray(e)&&(e.filter((function(e){return"string"==typeof e})).length===e.length&&(t=e))}})}return h(e,[{key:"_validate",value:function(){return Array.isArray(this._invitedUserIds)&&this._invitedUserIds.every((function(e){return"string"==typeof e}))&&("string"==typeof this.channelUrl||null===this.channelUrl)&&("string"==typeof this.coverUrl||null===this.coverUrl)&&(se.isFile(this.coverImage)||null===this.coverImage)&&("string"==typeof this.name||null===this.name)&&("string"==typeof this.data||null===this.data)&&("string"==typeof this.customType||null===this.customType)&&("boolean"==typeof this.isDistinct||null===this.isDistinct)&&("boolean"==typeof this.isSuper||null===this.isSuper)&&("boolean"==typeof this.isBroadcast||null===this.isBroadcast)&&("boolean"==typeof this.isPublic||null===this.isPublic)&&("boolean"==typeof this.isEphemeral||null===this.isEphemeral)&&("boolean"==typeof this.isDiscoverable||null===this.isDiscoverable)&&("boolean"==typeof this.isStrict||null===this.isStrict)&&(Array.isArray(this.operatorUserIds)&&this.operatorUserIds.every((function(e){return"string"==typeof e}))||null===this.operatorUserIds)&&("string"==typeof this.accessCode||null===this.accessCode)&&("number"==typeof this.messageSurvivalSeconds||null===this.messageSurvivalSeconds)}},{key:"addUsers",value:function(e){if(Array.isArray(e)){var t,n=e.filter((function(e){return e.hasOwnProperty("userId")&&"string"==typeof e.userId})).map((function(e){return e.userId}));(t=this._invitedUserIds).push.apply(t,A(n))}}},{key:"addUser",value:function(e){e.hasOwnProperty("userId")&&"string"==typeof e.userId&&this._invitedUserIds.push(e.userId)}},{key:"addUserIds",value:function(e){if(Array.isArray(e)){var t,n=e.filter((function(e){return"string"==typeof e}));(t=this._invitedUserIds).push.apply(t,A(n))}}},{key:"addUserId",value:function(e){"string"==typeof e&&this._invitedUserIds.push(e)}}]),e}(),Wr=function(){function e(){c(this,e),this.channelUrl=null,this.name=null,this.coverUrlOrImage=null,this.data=null,this.customType=null,this._operatorUserIds=[]}return h(e,[{key:"operatorUserIds",get:function(){return this._operatorUserIds},set:function(e){Array.isArray(e)&&e.every((function(e){return"string"==typeof e}))&&(this._operatorUserIds=e)}},{key:"operators",set:function(e){Array.isArray(e)&&e.every((function(e){return e.hasOwnProperty("userId")}))&&(this._operatorUserIds=e.map((function(e){return e.userId})))}},{key:"_validate",value:function(){return(Array.isArray(this.operatorUserIds)&&this.operatorUserIds.every((function(e){return"string"==typeof e}))||null===this.operatorUserIds)&&("string"==typeof this.coverUrlOrImage||se.isFile(this.coverUrlOrImage)||null===this.coverUrlOrImage)&&("string"==typeof this.name||null===this.name)&&("string"==typeof this.data||null===this.data)&&("string"==typeof this.customType||null===this.customType)&&("string"==typeof this.channelUrl&&/^\w+$/.test(this.channelUrl)||null===this.channelUrl)}}]),e}(),Jr=function(e){f(n,e);var t=E(n);function n(e){var r;return c(this,n),(r=t.call(this)).year=null,r.month=null,r.day=null,r.hour=null,r.min=null,r.timezone=null,r._scheduledDateTimeString=null,e&&r._update(e),r}return h(n,[{key:"scheduledDateTimeString",get:function(){return this._scheduledDateTimeString?this._scheduledDateTimeString:"number"==typeof this.year&&4===this.year.toString().length&&"number"==typeof this.month&&this.month>=1&&this.month<=12&&"number"==typeof this.day&&this.day>=1&&this.day<=31&&"number"==typeof this.hour&&this.hour>=0&&this.hour<=24&&"number"==typeof this.min&&this.min>=0&&this.min<=60&&"string"==typeof this.timezone&&this.timezone.length>0?this.year.toString()+"-"+("0"+this.month.toString()).substr(-2)+"-"+("0"+this.day.toString()).substr(-2)+" "+("0"+this.hour.toString()).substr(-2)+":"+("0"+this.min.toString()).substr(-2):null},set:function(e){e&&"string"==typeof e&&(this._scheduledDateTimeString=e)}},{key:"_update",value:function(e){e.hasOwnProperty("message")&&(this.message=e.message),e.hasOwnProperty("year")&&(this.year=e.year),e.hasOwnProperty("month")&&(this.month=e.month),e.hasOwnProperty("day")&&(this.day=e.day),e.hasOwnProperty("hour")&&(this.hour=e.hour),e.hasOwnProperty("min")&&(this.min=e.min),e.hasOwnProperty("timezone")&&(this.timezone=e.timezone)}},{key:"_getScheduleString",value:function(){return this.scheduledDateTimeString?this.scheduledDateTimeString+" "+this.timezone:"number"==typeof this.year&&4===this.year.toString().length&&"number"==typeof this.month&&this.month>=1&&this.month<=12&&"number"==typeof this.day&&this.day>=1&&this.day<=31&&"number"==typeof this.hour&&this.hour>=0&&this.hour<=24&&"number"==typeof this.min&&this.min>=0&&this.min<=60&&"string"==typeof this.timezone&&this.timezone.length>0?this.year.toString()+"-"+("0"+this.month.toString()).substr(-2)+"-"+("0"+this.day.toString()).substr(-2)+" "+("0"+this.hour.toString()).substr(-2)+":"+("0"+this.min.toString()).substr(-2)+" "+this.timezone:null}},{key:"setSchedule",value:function(e,t,n,r,i,s){"number"==typeof e&&4===e.toString().length&&"number"==typeof t&&t>=1&&t<=12&&"number"==typeof n&&n>=1&&n<=31&&"number"==typeof r&&r>=0&&r<=24&&"number"==typeof i&&i>=0&&i<=60&&"string"==typeof s&&s.length>0&&(this.scheduledDateTimeString=e.toString()+"-"+("0"+t.toString()).substr(-2)+"-"+("0"+n.toString()).substr(-2)+" "+("0"+r.toString()).substr(-2)+":"+("0"+i.toString()).substr(-2),this.timezone=s)}}]),n}(Cr),Xr=h((function e(){c(this,e),this.channelCustomTypesFilter=[],this.superChannelFilter=ar.SuperChannelFilter.ALL})),Zr=function(e){f(n,e);var t=E(n);function n(){return c(this,n),t.call(this)}return h(n)}(Xr),$r=function(e){f(n,e);var t=E(n);function n(){return c(this,n),t.call(this)}return h(n)}(Xr),ei=function(){function e(){c(this,e),this.channelUrl=null,this.channelType=null,this.messageId=0,this.includeMetaArray=!1,this.includeReactions=!1,this.includeParentMessageText=null,this.includeThreadInfo=!1,this.includeParentMessageInfo=null}return h(e,[{key:"_validate",value:function(){var e=x.get(this._iid).BaseChannel;return"string"==typeof this.channelUrl&&"string"==typeof this.channelType&&[e.CHANNEL_TYPE_BASE,e.CHANNEL_TYPE_OPEN,e.CHANNEL_TYPE_GROUP].includes(this.channelType)&&"number"==typeof this.messageId&&"boolean"==typeof this.includeMetaArray&&"boolean"==typeof this.includeReactions&&"boolean"==typeof this.includeThreadInfo&&(null===this.includeParentMessageText||"boolean"==typeof this.includeParentMessageText)&&(null===this.includeParentMessageInfo||"boolean"==typeof this.includeParentMessageInfo)}}]),e}(),ti=function(){function e(){c(this,e);var t=x.get(this._iid).BaseChannel;this.prevResultSize=0,this.nextResultSize=0,this.isInclusive=!1,this.reverse=!1,this.messageType=t.MessageTypeFilter.ALL,this.customType=null,this.customTypes=[],this.senderUserIds=null,this.includeMetaArray=!1,this.includeReaction=null,this.includeReactions=null,this.includeReplies=null,this.includeParentMessageText=null,this.includeThreadInfo=!1,this.replyType=null,this.includeParentMessageInfo=null,this.showSubchannelMessagesOnly=!1}return h(e,[{key:"_validate",value:function(){var e=x.get(this._iid),t=e.BaseChannel,n=e.BaseMessage;return"number"==typeof this.prevResultSize&&"number"==typeof this.nextResultSize&&"boolean"==typeof this.isInclusive&&"boolean"==typeof this.reverse&&"string"==typeof this.messageType&&Object.values(t.MessageTypeFilter).includes(this.messageType)&&("string"==typeof this.customType||null===this.customType)&&Array.isArray(this.customTypes)&&this.customTypes.every((function(e){return"string"==typeof e||null===e}))&&(Array.isArray(this.senderUserIds)&&this.senderUserIds.every((function(e){return"string"==typeof e}))||null===this.senderUserIds)&&"boolean"==typeof this.includeMetaArray&&(null===this.includeReaction||"boolean"==typeof this.includeReaction)&&(null===this.includeReactions||"boolean"==typeof this.includeReactions)&&"boolean"==typeof this.includeThreadInfo&&(null===this.includeReplies||"boolean"==typeof this.includeReplies)&&(null===this.replyType||"string"==typeof this.replyType&&Object.values(n.ReplyType).includes(this.replyType))&&(null===this.includeParentMessageText||"boolean"==typeof this.includeParentMessageText)&&(null===this.includeParentMessageInfo||"boolean"==typeof this.includeParentMessageInfo)&&"boolean"==typeof this.showSubchannelMessagesOnly}},{key:"belongsTo",value:function(e){var t=x.get(this._iid),n=t.BaseChannel,r=t.UserMessageParams,i=t.FileMessageParams,s=t.BaseMessage;if(this.messageType!==n.MessageTypeFilter.ALL){if(e instanceof r&&this.messageType!==n.MessageTypeFilter.USER)return!1;if(e instanceof i&&this.messageType!==n.MessageTypeFilter.FILE)return!1}if(Array.isArray(this.customTypes)&&this.customTypes.length>0&&!this.customTypes.includes(e.customType))return!1;if("string"==typeof this.customType&&this.customType!==e.customType)return!1;if(Array.isArray(this.senderUserIds)&&this.senderUserIds.length>0){var a=wi.getInstance(e._iid);if(!a||!a.currentUser||!this.senderUserIds.includes(a.currentUser.userId))return!1}if("string"==typeof this.replyType&&e.parentMessageId){if(this.replyType===s.ReplyType.NONE)return!1;if(this.replyType===s.ReplyType.ONLY_REPLY_TO_CHANNEL&&!e.isReplyToChannel)return!1}else if(!1===this.includeReplies&&e.parentMessageId)return!1;return!0}}]),e}(),ni=function(){function e(){c(this,e);var t=x.get(this._iid).BaseChannel;this.prevResultSize=0,this.nextResultSize=0,this.isInclusive=!1,this.reverse=!1,this.messageType=t.MessageTypeFilter.ALL,this.customType=null,this.customTypes=[],this.senderUserIds=null,this.includeMetaArray=!1,this.includeReaction=null,this.includeReactions=null,this.includeParentMessageText=null,this.includeParentMessageInfo=null}return h(e,[{key:"_validate",value:function(){var e=x.get(this._iid).BaseChannel;return"number"==typeof this.prevResultSize&&"number"==typeof this.nextResultSize&&"boolean"==typeof this.isInclusive&&"boolean"==typeof this.reverse&&"string"==typeof this.messageType&&Object.values(e.MessageTypeFilter).includes(this.messageType)&&("string"==typeof this.customType||null===this.customType)&&Array.isArray(this.customTypes)&&this.customTypes.every((function(e){return"string"==typeof e||null===e}))&&(Array.isArray(this.senderUserIds)&&this.senderUserIds.every((function(e){return"string"==typeof e}))||null===this.senderUserIds)&&"boolean"==typeof this.includeMetaArray&&(null===this.includeReaction||"boolean"==typeof this.includeReaction)&&(null===this.includeReactions||"boolean"==typeof this.includeReactions)&&(null===this.includeParentMessageText||"boolean"==typeof this.includeParentMessageText)&&(null===this.includeParentMessageInfo||"boolean"==typeof this.includeParentMessageInfo)}}]),e}(),ri=function(){function e(){c(this,e),this.includeMetaArray=!1,this.includeReaction=null,this.includeReactions=null,this.includeReplies=null,this.includeParentMessageText=null,this.includeThreadInfo=!1,this.replyType=null,this.includeParentMessageInfo=null}return h(e,[{key:"_validate",value:function(){return"boolean"==typeof this.includeMetaArray&&(null===this.includeReaction||"boolean"==typeof this.includeReaction)&&(null===this.includeReactions||"boolean"==typeof this.includeReactions)&&"boolean"==typeof this.includeThreadInfo&&(null===this.includeReplies||"boolean"==typeof this.includeReplies)&&(null===this.replyType||"string"==typeof this.replyType&&Object.values(BaseMessage.ReplyType).includes(this.replyType))&&(null===this.includeParentMessageText||"boolean"==typeof this.includeParentMessageText)&&(null===this.includeParentMessageInfo||"boolean"==typeof this.includeParentMessageInfo)}}]),e}(),ii=function(){function e(){c(this,e),this.customTypes=[],this.includeEmpty=!1,this.includeFrozen=!0}return h(e,[{key:"_validate",value:function(){return(Array.isArray(this.customTypes)&&this.customTypes.every((function(e){return"string"==typeof e}))||null===this.customTypes)&&("boolean"==typeof this.includeEmpty||null===this.includeEmpty)&&"boolean"==typeof this.includeFrozen}}]),e}(),si=function(){this.onReconnectStarted=function(){},this.onReconnectSucceeded=function(){},this.onReconnectFailed=function(){}},ai=function(){this.onFriendsDiscovered=function(){},this.onTotalUnreadMessageCountUpdated=function(){}},oi=h((function e(){c(this,e),this.onMessageReceived=function(e,t){},this.onMessageUpdated=function(e,t){},this.onMessageDeleted=function(e,t){},this.onReadReceiptUpdated=function(e){},this.onReactionUpdated=function(e,t){},this.onDeliveryReceiptUpdated=function(e){},this.onTypingStatusUpdated=function(e){},this.onUserJoined=function(e,t){},this.onUserLeft=function(e,t){},this.onOperatorUpdated=function(e,t){},this.onUserEntered=function(e,t){},this.onUserExited=function(e,t){},this.onUserMuted=function(e,t){},this.onUserUnmuted=function(e,t){},this.onUserBanned=function(e,t){},this.onUserUnbanned=function(e,t){},this.onChannelFrozen=function(e){},this.onChannelUnfrozen=function(e){},this.onChannelChanged=function(e){},this.onChannelDeleted=function(e,t){},this.onUserReceivedInvitation=function(e,t,n){},this.onUserDeclinedInvitation=function(e,t,n){},this.onMetaDataCreated=function(e,t){},this.onMetaDataUpdated=function(e,t){},this.onMetaDataDeleted=function(e,t){},this.onMetaCountersCreated=function(e,t){},this.onMetaCountersUpdated=function(e,t){},this.onMetaCountersDeleted=function(e,t){},this.onChannelHidden=function(e){},this.onMentionReceived=function(e,t){},this.onThreadInfoUpdated=function(e,t){},this.onChannelMemberCountChanged=function(e){},this.onChannelParticipantCountChanged=function(e){}})),li=h((function e(t){if(c(this,e),t){var n=x.get(this._iid),r=n.User,i=n.BaseChannel;this.reader=new r(t.user),this.timestamp=parseInt(t.ts),this.channelUrl=t.hasOwnProperty("channel_url")?String(t.channel_url):"",this.channelType=t.hasOwnProperty("channel_type")?String(t.channel_type):i.CHANNEL_TYPE_GROUP}})),ui=function(){function e(e){this.replyCount=0,this.mostRepliedUsers=[],this.lastRepliedAt=0,this.updatedAt=0,e&&this._update(e)}return e.objectify=function(e){var t=x.get(this._iid).User,n=e.replyCount,r=void 0===n?0:n,i=e.mostRepliedUsers,s=void 0===i?[]:i,a=e.lastRepliedAt,o=void 0===a?0:a,l=e.updatedAt,u=void 0===l?0:l,c={};return c.reply_count=r,Array.isArray(s)&&s.every((function(e){return e instanceof t}))&&(c.most_replies=s.map((function(e){return t.objectify(e)}))),c.last_replied_at=o,c.updated_at=u,c},e.build=function(e,t,n,r){return this.objectify({replyCount:e,mostRepliedUsers:t,lastRepliedAt:n,updatedAt:r})},e.prototype._update=function(e){var t=x.get(this._iid).User;e.hasOwnProperty("reply_count")&&(this.replyCount=parseInt(e.reply_count)),e.hasOwnProperty("most_replies")&&Array.isArray(e.most_replies)&&e.most_replies.every((function(e){return"object"==typeof e}))&&(this.mostRepliedUsers=e.most_replies.map((function(e){return new t(e)}))),e.hasOwnProperty("last_replied_at")&&(this.lastRepliedAt=parseInt(e.last_replied_at)),e.hasOwnProperty("updated_at")&&(this.updatedAt=parseInt(e.updated_at))},e}(),ci=function(){function e(e){this.title=null,this.url=null,this.description=null,this.defaultImage=null,e&&this._update(e)}return e.objectify=function(e){var t=x.get(this._iid).OGImage,n=e.title,r=void 0===n?null:n,i=e.url,s=void 0===i?null:i,a=e.description,o=void 0===a?null:a,l=e.defaultImage,u=void 0===l?null:l,c={};return c["og:title"]=r,c["og:url"]=s,c["og:description"]=o,u&&(c["og:image"]=t.objectify(u)),c},e.prototype._update=function(e){var t=x.get(this._iid).OGImage;e.hasOwnProperty("og:title")&&(this.title=e["og:title"]),e.hasOwnProperty("og:url")&&(this.url=e["og:url"]),e.hasOwnProperty("og:description")&&(this.description=e["og:description"]),e.hasOwnProperty("og:image")&&(this.defaultImage=new t(e["og:image"]))},e}(),di=function(){function e(e){this.url=null,this.secureUrl=null,this.type=null,this.width=0,this.height=0,this.alt=null,e&&this._update(e)}return e.objectify=function(e){var t=e.url,n=void 0===t?null:t,r=e.secureUrl,i=void 0===r?null:r,s=e.type,a=void 0===s?null:s,o=e.width,l=void 0===o?0:o,u=e.height,c=void 0===u?0:u,d=e.alt,h=void 0===d?null:d,p={};return p.url=n,p.secure_url=i,p.type=a,p.width=l,p.height=c,p.alt=h,p},e.prototype._update=function(e){e.hasOwnProperty("url")&&(this.url=e.url),e.hasOwnProperty("secure_url")&&(this.secureUrl=e.secure_url),e.hasOwnProperty("type")&&(this.type=e.type),e.hasOwnProperty("width")&&(this.width=parseInt(e.width)),e.hasOwnProperty("height")&&(this.height=parseInt(e.height)),e.hasOwnProperty("alt")&&(this.alt=e.alt)},e}(),hi=function(){function e(e){this.type=null,this.vendor=null,this.detail={},e&&this._update(e)}return e.objectify=function(e){var t=e.type,n=void 0===t?"":t,r=e.vendor,i=void 0===r?"":r,s=e.detail,a=void 0===s?{}:s,o={};return o.type=n,o.vendor=i,o.detail=a,o},e.prototype._update=function(e){this.type=e.hasOwnProperty("type")?e.type:"",this.vendor=e.hasOwnProperty("vendor")?e.vendor:"",e.hasOwnProperty("detail")&&"object"==typeof e.detail&&!Array.isArray(e.detail)&&(this.detail=e.detail)},e}(),pi=function(){function e(t){c(this,e),this.restrictionType=null,this.description=null,this.endAt=-1,t&&this._update(t)}return h(e,[{key:"_update",value:function(e){e.hasOwnProperty("restriction_type")&&(this.restrictionType=e.restriction_type),e.hasOwnProperty("description")?this.description=e.description:e.hasOwnProperty("muted_description")&&(this.description=e.muted_description),e.hasOwnProperty("end_at")?this.endAt=parseInt(e.end_at):e.hasOwnProperty("muted_end_at")&&(this.endAt=parseInt(e.muted_end_at))}}],[{key:"objectify",value:function(e){var t=e.restrictionType,n=void 0===t?null:t,r=e.description,i=void 0===r?null:r,s=e.endAt,a=void 0===s?-1:s,o={};return o.restriction_type=n,o.description=i,o.end_at=a,o}}]),e}(),fi=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];c(this,e),this.isLoading=!1,this.hasNext=!0,this.limit=20,this.userIds=t,this.metaDataKey="",this.metaDataValues=[],this._token=""}return h(e,[{key:"next",value:function(e){var t=this;return oe(this._iid,(function(e){"number"==typeof t.limit&&t.limit>0&&Array.isArray(t.userIds)&&"string"==typeof t.metaDataKey&&Array.isArray(t.metaDataValues)&&!!t.metaDataKey==t.metaDataValues.length>0?t.isLoading?e(new H("Query in progress.",H.QUERY_IN_PROGRESS),null):t.hasNext?(t.isLoading=!0,O.get(t._iid).container.apiClient.loadUserList(l(l({},t),{},{userIdsFilter:t.userIds,metaDataKeyFilter:t.metaDataKey,metaDataValuesFilter:t.metaDataValues,token:t._token}),(function(n,r){var i=null;if(!n){var s=x.get(t._iid).User,a=String(r.next);t._token=a,t.hasNext=!!a,i=r.users.map((function(e){return new s(e)}))}t.isLoading=!1,e(n,i)}))):e(null,[]):e(me.error,null)}),e)}}]),e}(),_i=new WeakMap,gi=function(){function e(t){c(this,e),this.isLoading=!1,_i.set(this,t)}return h(e,[{key:"prev",value:function(e,t,n,r){var i=arguments,s=this;return oe(this._iid,(function(r){var a,o=x.get(s._iid).BaseChannel,l=C(me.parse(i,[new me({type:"number"}),new me({type:"number"}),new me({type:"boolean"}),new me({type:"function"})]),5);if(a=l[0],e=l[1],t=l[2],n=l[3],r=l[4],a)r(a,null);else if(s.isLoading)r(new H("Query in progress.",H.QUERY_IN_PROGRESS),null);else{s.isLoading=!0;var u=_i.get(s);O.get(s._iid).container.apiClient.getMessageList({channelUrl:u.url,channelType:u.channelType,token:e,tokenType:"timestamp",isInclusive:!1,prevResultSize:t,nextResultSize:0,shouldReverse:n,messageType:"",customType:""}).then((function(e){var t=e.messages.map((function(e){return o.buildMessage(e,u)}));s.isLoading=!1,r(null,t)})).catch((function(e){s.isLoading=!1,r(e,null)}))}}),r)}},{key:"next",value:function(e,t,n,r){var i=arguments,s=this;return oe(this._iid,(function(r){var a,o=x.get(s._iid).BaseChannel,l=C(me.parse(i,[new me({type:"number"}),new me({type:"number"}),new me({type:"boolean"}),new me({type:"function"})]),5);if(a=l[0],e=l[1],t=l[2],n=l[3],r=l[4],a)r(a,null);else if(s.isLoading)r(new H("Query in progress.",H.QUERY_IN_PROGRESS),null);else{s.isLoading=!0;var u=_i.get(s);O.get(s._iid).container.apiClient.getMessageList({channelUrl:u.url,channelType:u.channelType,token:e,tokenType:"timestamp",isInclusive:!1,prevResultSize:0,nextResultSize:t,shouldReverse:n,messageType:"",customType:""}).then((function(e){var t=e.messages.map((function(e){return o.buildMessage(e,u)}));s.isLoading=!1,r(null,t)})).catch((function(e){s.isLoading=!1,r(e,null)}))}}),r)}},{key:"load",value:function(e,t,n,r,i){var s=arguments,a=this;return oe(this._iid,(function(i){var o,l=x.get(a._iid).BaseChannel,u=C(me.parse(s,[new me({type:"number"}),new me({type:"number"}),new me({type:"number"}),new me({type:"boolean"}),new me({type:"callback"})]),6);if(o=u[0],e=u[1],t=u[2],n=u[3],r=u[4],i=u[5],o)i(o,null);else if(a.isLoading)i(new H("Query in progress.",H.QUERY_IN_PROGRESS),null);else{a.isLoading=!0;var c=_i.get(a);O.get(a._iid).container.apiClient.getMessageList({channelUrl:c.url,channelType:c.channelType,token:e,tokenType:"timestamp",isInclusive:!1,prevResultSize:t,nextResultSize:n,shouldReverse:r,messageType:"",customType:""}).then((function(e){var t=e.messages.map((function(e){return l.buildMessage(e,c)}));a.isLoading=!1,i(null,t)})).catch((function(e){a.isLoading=!1,i(e,null)}))}}),i)}}]),e}(),yi=0,mi=1,Ei=2,vi=function(){function e(t){var n=this;c(this,e),this.state=yi,this._value=null,this._reason=null;var r=function(e){n.state===yi&&(n.state=Ei,n._reason=e)};if("function"!=typeof t)throw"Promise resolver ".concat(t," is not a function");try{t((function(e){n.state===yi&&(n.state=mi,n._value=e)}),r)}catch(e){r(e)}}return h(e,[{key:"length",get:function(){return 1}},{key:"then",value:function(t,n){var r=this,i=this;switch(this.state){case yi:setTimeout((function(){return r.then(t,n)}),2);break;case mi:t&&"function"==typeof t&&(i=t(this._value));break;case Ei:n&&"function"==typeof n&&(i=n(this._reason))}return i instanceof e?i:this}},{key:"catch",value:function(t){var n=this,r=this;switch(this.state){case yi:setTimeout((function(){return n.catch(t)}),2);break;case mi:break;case Ei:r=t(this._reason)}return r instanceof e?r:this}},{key:"finally",value:function(t){var n=this,r=this;switch(this.state){case yi:setTimeout((function(){return n.finally(t)}),2);break;case mi:case Ei:r=t()}return r instanceof e?r:this}}],[{key:"all",value:function(t){return new e((function(n,r){if(Array.isArray(t)||"string"==typeof t)if(t.length>0){for(var i=[],s=0;s0&&this.numLocksAvailable>0&&!this._isProcessChainAcquireRunning()&&this._hasHighestPriorityResolver())switch(e.key){case this._holdersKey:if(t=JSON.parse(e.oldValue),n=JSON.parse(e.newValue),!t||!n||n.length>=t.length)return[2];this._processChainResolve();break;case this._chainProcessStateKey:if(JSON.parse(e.newValue))return[2];this._processChainResolve();break;default:return[2]}return[2]}))}))})),window.addEventListener("beforeunload",(function(){var e=o._getLocalResolversData(),t=o._localResolversData.map((function(e){return e.key})),n=e.filter((function(e){return t.indexOf(e.key)<0}));n.length>0?window.localStorage.setItem(o._resolversKey,JSON.stringify(n)):window.localStorage.removeItem(o._resolversKey),o._localAcquiredKeys.forEach((function(e){return o.release(e)}))})))}return e.createSemaphoreHoldersKey=function(e){return Ci+e},e.createSemaphoreResolversKey=function(e){return Ai+e},e.createChainProcessStateKey=function(e){return Ni+e},e.removeAllSemaphoreKeys=function(){if("undefined"!=typeof document&&"undefined"!=typeof navigator&&"undefined"!=typeof localStorage){for(var e=[],t=0;t0&&this._localResolversData.map((function(e){return e.key})).indexOf(e[0].key)>=0},e.prototype._isProcessChainAcquireRunning=function(){if($())return Ti[this._chainProcessStateKey];var e=window.localStorage[this._chainProcessStateKey];return void 0!==e&&JSON.parse(e)},e.prototype._setProcessChainAcquireRunning=function(e){$()?Ti[this._chainProcessStateKey]=e:e?window.localStorage.setItem(this._chainProcessStateKey,JSON.stringify(e)):window.localStorage.removeItem(this._chainProcessStateKey)},e.prototype._processChainResolve=function(){return L(this,void 0,void 0,(function(){var e;return w(this,(function(t){switch(t.label){case 0:return this.waitCount>0&&this.numLocksAvailable>0&&!this._isProcessChainAcquireRunning()?(this._setProcessChainAcquireRunning(!0),this._tryResolve()?[4,Ue(this._backOffDelay)]:[3,2]):[3,3];case 1:t.sent(),t.label=2;case 2:this._setProcessChainAcquireRunning(!1),$()?this._processChainResolve():(e=new StorageEvent("storage",{key:this._chainProcessStateKey,oldValue:JSON.stringify(!0),newValue:JSON.stringify(!1)}),dispatchEvent(e)),t.label=3;case 3:return[2]}}))}))},e.prototype.acquire=function(e){return void 0===e&&(e=Ct.BACKGROUND_SYNC_CLOSE),L(this,void 0,void 0,(function(){var t,n=this;return w(this,(function(r){return $()?[2,new Promise((function(t){var r={key:Oe(),resolver:function(e){return t(e)},priority:e};switch(e){case Ct.USER_CALL:case Ct.FILL:case Ct.BACKGROUND_SYNC_OPEN:for(var i=Ii[n._resolversKey],s=-1,a=0;ai[a].priority&&(s=a);if(s>=0){Ii[n._resolversKey].splice(s,0,r);break}case Ct.BACKGROUND_SYNC_CLOSE:Ii[n._resolversKey].push(r)}n._processChainResolve()}))]:(t=this._getLocalResolversData(),[2,new Promise((function(r){var i=Oe(),s={key:i,priority:e},a={key:i,resolver:function(e){return r(e)},priority:e};switch(e){case Ct.USER_CALL:case Ct.FILL:case Ct.BACKGROUND_SYNC_OPEN:for(var o=-1,l=0;lt[l].priority&&(o=l);if(o>=0){t.splice(o,0,s),window.localStorage.setItem(n._resolversKey,JSON.stringify(t)),n._localResolversData.splice(o,0,a);break}case Ct.BACKGROUND_SYNC_CLOSE:t.push(s),window.localStorage.setItem(n._resolversKey,JSON.stringify(t)),n._localResolversData.push(a)}n._processChainResolve()}))])}))}))},e.prototype.release=function(e){if($()){if((t=Si[this._holdersKey].indexOf(e))>=0)return Si[this._holdersKey].splice(t,1),this._processChainResolve(),!0}else{var t,n=JSON.parse(window.localStorage[this._holdersKey]),r=P([],n,!0);if((t=n.indexOf(e))>=0){n.splice(t,1),n.length>0?window.localStorage.setItem(this._holdersKey,JSON.stringify(n)):window.localStorage.removeItem(this._holdersKey),this._localAcquiredKeys.splice(this._localAcquiredKeys.indexOf(e),1);var i=new StorageEvent("storage",{key:this._holdersKey,oldValue:JSON.stringify(r),newValue:JSON.stringify(n)});return dispatchEvent(i),!0}}return!1},e.prototype._tryResolve=function(){if($()){if(Si[this._holdersKey].length0?window.localStorage.setItem(this._resolversKey,JSON.stringify(r)):window.localStorage.removeItem(this._resolversKey),window.localStorage.setItem(this._holdersKey,JSON.stringify(P(P([],t,!0),[e],!1))),this._localAcquiredKeys.push(e);var s=new StorageEvent("storage",{key:this._holdersKey,oldValue:JSON.stringify(P([],t,!0)),newValue:JSON.stringify(P(P([],t,!0),[e],!1))});return dispatchEvent(s),(0,n.resolver)(e),!0}}return!1},e.prototype._getLocalHoldersData=function(){var e=window.localStorage[this._holdersKey];return void 0!==e?JSON.parse(e):[]},e.prototype._getLocalResolversData=function(){var e=window.localStorage[this._resolversKey];return void 0!==e?JSON.parse(e):[]},e}(),Oi=3e5,Mi=null,ki={},Ri=!1,Li=null,wi=function(){function e(){var t=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};c(this,e),bi();var r=!1;if((n.newInstance||!Mi||Mi&&n.appId!==Mi.getApplicationId()&&Mi.getConnectionState()===Mi.ConnectionState.CLOSED)&&(r=!0,Mi=this),r){try{if(!n.hasOwnProperty("appId"))return J.warn("Must be set appId."),Mi=null,null}catch(e){return J.warn("Must be set appId."),Mi=null,null}var i=Xn.create();Object.defineProperty(this,"_iid",{get:function(){return i}}),ki[i]=this,this.customApiHost=null,this.customWsHost=null,this.connecting=!1,this.reconnecting=!1,this.isReconnectingOnError=!1,this.connectionCallbacks=[],this.ConnectionManager=new Ee(this),this.GCMPushToken="",this.APNSPushToken="",this.PUSH_TEMPLATE_DEFAULT="default",this.PUSH_TEMPLATE_ALTERNATIVE="alternative",this.currentUser=null,this.isSessionOpened=!1,this.globalTimer,this.loginTimer,this.reconnectTimer,this.loginHandler=null,this.onLoginTimerCancel,this.onReconnectTimerCancel,this.BaseChannel={MessageTypeFilter:Rt.MessageTypeFilter},this.GroupChannelFilter=Zn,this.MessageFilter=et,this.GroupChannelCollection={GroupChannelOrder:Le},this.MessageCollection={MessageCollectionInitPolicy:at},this.CollectionEventSource=de,this._currentUserId=null;var s={User:ft,Member:or,RestrictedUser:ur,GroupChannel:ar,OpenChannel:gr,UserMessage:Nr,FileMessage:Ir,AdminMessage:Tr,GroupChannelListQuery:wr,MemberListQuery:Pr,GroupChannelParams:Qr,OpenChannelParams:Wr,BaseMessageParams:br,UserMessageParams:Cr,FileMessageParams:Sr,ScheduledUserMessageParams:Jr,GroupChannelTotalUnreadMessageCountParams:Zr,GroupChannelTotalUnreadChannelCountParams:$r,MessageRetrievalParams:ei,MessageListParams:ti,ThreadedMessageListParams:ni,MessageChangeLogsParams:ri,GroupChannelChangeLogsParams:ii,MessageMetaArray:Er,UserEventHandler:ai,SessionHandler:ve,ChannelHandler:oi,ConnectionHandler:si,AppleCriticalAlertOptions:mr},a={SessionManager:be,BaseChannel:Rt,BaseMessage:pt,UserListQuery:fi,ApplicationUserListQuery:Mr,BannedUserListQuery:kr,BlockedUserListQuery:Rr,FriendListQuery:Lr,MutedUserListQuery:Dr,OpenChannelListQuery:Hr,OperatorListQuery:Gr,ParticipantListQuery:jr,MessageListQuery:gi,PreviousMessageListQuery:zr,MessageSearchQuery:Vr,PublicGroupChannelListQuery:Yr,ScheduledUserMessage:Ur,ThreadInfo:ui,ThreadInfoUpdateEvent:Or,OGMetaData:ci,OGImage:di,Plugin:hi,Command:Ne,Sender:lr,ReadStatus:li,Reaction:Ar,ReactionEvent:lt,Emoji:hr,EmojiCategory:dr,EmojiContainer:cr,RestrictionInfo:pi,FileMessageQueue:Gt},o=new x(this._iid,l(l({},s),a));this.BaseMessage={ReplyType:pt.ReplyType,getMessage:o.BaseMessage.getMessage.bind(o.BaseMessage)},Object.keys(o).forEach((function(e){s[e]&&(t[e]=o[e])}));var u={encrypt:function(e){return e},decrypt:function(e){return e}};O.create(i,{appId:n.appId,pinger:new Z(this),apiClient:new ue(this),wsAdapter:new ye(this),commandHandler:new Pt(this),onlineDetector:new Ce(this),ackStateMap:{},subscribedUnreadMessageCount:{all:0,custom_types:{},ts:0},maxUnreadCountOfSuperGroupChannel:T.DEFAULT_MAX_UNREAD_COUNT_OF_SUPER_GROUP_CHANNEL,nestdb:null,currentUserId:null,localCacheEnabled:"boolean"==typeof n.localCacheEnabled&&n.localCacheEnabled,localCacheLock:new X,debugCache:!1,encryption:u,store:new Hn({encryption:u}),preference:null,auth:new F,appInfo:null,pingInterval:15e3,pongTimeout:5e3,connectedAt:0,extensions:{},supportedExtensionKeys:["sb_uikit","sb_syncmanager","device-os-platform"],getUserAgentWithExtensions:function(e){var t=$()?"reactnative":"JS",n=e.sb_syncmanager?"s".concat(e.sb_syncmanager):"",r=e.sb_uikit?"u".concat(e.sb_uikit):"",i=e["device-os-platform"]?"o".concat(e["device-os-platform"]):"";return"".concat(t,"/c").concat(T.SDK_VERSION,"/").concat(n,"/").concat(r,"/").concat(i)},sessionManager:new o.SessionManager(this),stateChangeEnabled:!0,isInBackground:!1,closedByGoingBackground:!1,isErrorFirstInCallback:!1,autoResendQueue:[],isProcessingAutoResend:!1}),this.userEventHandlers={},this.channelHandlers={},this.connectionHandlers={},this.Options={_useMemberAsMessageSender:!0,get UseMemberAsMessageSender(){return this._useMemberAsMessageSender},set UseMemberAsMessageSender(e){"boolean"==typeof e&&(this._useMemberAsMessageSender=e)},get useMemberAsMessageSender(){return this._useMemberAsMessageSender},set useMemberAsMessageSender(e){"boolean"==typeof e&&(this._useMemberAsMessageSender=e)},_typingIndicatorThrottle:1e3,get typingIndicatorThrottle(){return this._typingIndicatorThrottle},set typingIndicatorThrottle(e){"number"==typeof e&&e>=1e3&&e<=9e3&&(this._typingIndicatorThrottle=e)},_websocketResponseTimeout:1e4,get websocketResponseTimeout(){return this._websocketResponseTimeout},set websocketResponseTimeout(e){"number"==typeof e&&e>=5e3&&e<=Oi&&(this._websocketResponseTimeout=e)}};var d=pe.of(i);d.addObserver({onConnect:function(){t.isCacheEnabled&&!t.getIsProcessingAutoResend()&&(0===t.getAutoResendQueue().length?Ut._processAutoResendRegisteredPendingMessages(t).then((function(){Ut._processNextAutoResend(t)})):Ut._processNextAutoResend(t))},onDisconnect:function(){}})}return Mi}return h(e,[{key:"ConnectionState",get:function(){return{CONNECTING:"CONNECTING",OPEN:"OPEN",CLOSED:"CLOSED"}}},{key:"MessageRequestState",get:function(){return{NONE:"none",PENDING:"pending",FAILED:"failed",SUCCEEDED:"succeeded"}}},{key:"MessageSendingStatus",get:function(){return{NONE:"none",PENDING:"pending",FAILED:"failed",CANCELED:"canceled",SUCCEEDED:"succeeded"}}},{key:"pushTokenRegistrationState",get:function(){return{SUCCESS:"success",PENDING:"pending",ERROR:"error"}}},{key:"PushTriggerOption",get:function(){return{ALL:"all",MENTION_ONLY:"mention_only",OFF:"off"}}},{key:"appInfo",get:function(){return O.get(this._iid).container.appInfo}},{key:"isCacheEnabled",get:function(){return O.get(this._iid).container.localCacheEnabled}},{key:"ekey",get:function(){var e=O.get(this._iid).container.auth;return e?e.eKey:""}},{key:"getApplicationId",value:function(){return O.get(this._iid).get("appId")}},{key:"getCurrentUserId",value:function(){return this.currentUser?this.currentUser.userId:null}},{key:"getDebugMode",value:function(){return Ri}},{key:"setDebugMode",value:function(e){Ri=e,J.mode=e?J.Mode.DEBUG:J.Mode.PRODUCTION}},{key:"getErrorFirstCallback",value:function(){return O.get(this._iid).container.isErrorFirstInCallback}},{key:"setErrorFirstCallback",value:function(e){"boolean"==typeof e&&O.get(this._iid).set("isErrorFirstInCallback",e)}},{key:"getAutoResendQueue",value:function(){return O.get(this._iid).container.autoResendQueue}},{key:"getIsProcessingAutoResend",value:function(){return O.get(this._iid).container.isProcessingAutoResend}},{key:"setIsProcessingAutoResend",value:function(e){O.get(this._iid).set("isProcessingAutoResend",e)}},{key:"getCurrentApiHost",value:function(){return this.customApiHost?this.customApiHost:"https://api.sendbird.com"}},{key:"clearCurrentApiHost",value:function(){this.customApiHost=null}},{key:"getCurrentWsHost",value:function(){return this.customWsHost?this.customWsHost:"wss://ws.sendbird.com"}},{key:"clearCurrentWsHost",value:function(){this.customWsHost=null}},{key:"getConnectionState",value:function(){try{var e=O.get(this._iid).container.wsAdapter;return this.connecting||this.reconnecting?this.ConnectionState.CONNECTING:e.client?this.connecting||this.reconnecting?this.ConnectionState.CONNECTING:this.isSessionOpened?e.client.getConnectionState():this.ConnectionState.CLOSED:this.ConnectionState.CLOSED}catch(e){return this.ConnectionState.CLOSED}}},{key:"getPendingGCMToken",value:function(){return this.GCMPushToken}},{key:"getPendingAPNSToken",value:function(){return this.APNSPushToken}},{key:"hasLoggedIn",value:function(){var e=O.get(this._iid);return this.currentUser&&e.get("auth").hasSession()}},{key:"getLastConnectedAt",value:function(){var e=O.get(this._iid);return this.getConnectionState()===this.ConnectionState.OPEN&&this.currentUser?e.get("connectedAt"):0}},{key:"setOnlineListener",value:function(e){O.get(this._iid).container.onlineDetector.setOnlineListener(e)}},{key:"setOfflineListener",value:function(e){O.get(this._iid).container.onlineDetector.setOfflineListener(e)}},{key:"getMemoryStoreForDebugging",value:function(){var e=O.get(this._iid);return e.container.debugCache&&e.container.store instanceof Pn?e.container.store:null}},{key:"useMemoryAsDatabaseForDebugging",value:function(){var e=O.get(this._iid);e.container.debugCache=!0,e.container.store=new Pn}},{key:"useAsyncStorageAsDatabase",value:function(e){var t=O.get(this._iid);t.container.store=new Fn({AsyncStorage:e,encryption:t.container.encryption})}},{key:"useMMKVAsDatabase",value:function(e){var t=O.get(this._iid);t.container.store=new Gn({MMKV:e,encryption:t.container.encryption})}},{key:"initializeDatabase",value:function(e,t){var n=this,r=O.get(this._iid),i=r.container,s=i.appId,a=i.nestdb,o=i.store,l=i.localCacheEnabled;return oe(this._iid,(function(t){if(l)if(a)t(null);else{var i=r.container.nestdb=new Jn({name:"sendbird=".concat(s,"-").concat(e,".db"),version:1,store:o});i.on("upgrade",(function(e,t){if(0===e)i.commitSchema([{collectionName:"GroupChannel",keyName:"url",index:[ze.NAME_ALPHABETICAL,ze.CHRONOLOGICAL,ze.LATEST_LAST_MESSAGE]},{collectionName:"SucceededMessage",keyName:"messageId",index:[Ye.LATEST,Ye.CHILD_MESSAGE_FIRST]},{collectionName:"UnsentMessage",keyName:"reqId",index:[Ye.LATEST_UNSENT,Ye.CHILD_MESSAGE_FIRST]}]).then((function(){return t()})).catch((function(e){throw e}));else t()})),i.on("error",(function(e){e?e.code===xt.STORE_NOT_AVAILABLE||e.code===xt.STORE_NOT_AVAILABLE_IN_PRIVATE_BROWSING?t(null):(J.error("Database initialize failed with an error: ",e),t(e)):t(null)})),i.on("success",(function(){r.container.currentUserId=e,new $e({iid:n._iid,collection:i.collection("GroupChannel")}),new ot({iid:n._iid,collections:{succeeded:i.collection("SucceededMessage"),unsent:i.collection("UnsentMessage")}}),J.debug("Database initialize succeeded."),t(null)})),i.open()}else r.container.currentUserId=e,new $e({iid:n._iid,collection:null}),new ot({iid:n._iid,collections:{succeeded:null,unsent:null}}),t(null)}),t)}},{key:"clearCachedData",value:function(){var e=O.get(this._iid),t=e.container,n=t.localCacheEnabled,r=t.nestdb;return new Promise((function(t,i){n&&r?(r.close(),r.reset().then((function(){J.debug("Database clear succeeded."),e.container.nestdb=null,t()})).catch((function(e){J.error("Database clear failed with an error: ",e),i(e)}))):t()}))}},{key:"connect",value:function(e,t,n,r,i){var s=this,a=O.get(this._iid),o=a.container,l=o.wsAdapter,u=o.onlineDetector,c=o.localCacheEnabled;Ui.removeAllSemaphoreKeys(),u&&u.start();var d=null,h=me.parse(arguments,[new me({type:"string",constraint:function(e){return e.length>0}}),new me({type:"string",nullable:!0,ignoreIf:function(e){return 1===e.length||3===e.length}}),new me({type:"string",nullable:!0,ignoreIf:function(e){return 1===e.length||2===e.length}}),new me({type:"string",nullable:!0,ignoreIf:function(e){return 1===e.length||2===e.length}}),new me({type:"callback"})]),p=C(h,6);return d=p[0],e=p[1],t=p[2],n=p[3],r=p[4],i=p[5],(n||r)&&J.debug("Please note that apiHost and wsHost are for internal use only."),oe(this._iid,(function(i){if(d)i(d,null);else if(s.customApiHost=n,s.customWsHost=r,s.connecting=!0,s.reconnecting=!1,s.isReconnectingOnError=!1,s.reconnectTimer&&(clearTimeout(s.reconnectTimer),s.reconnectTimer=null,s.onReconnectTimerCancel=null),s.getConnectionState()===s.ConnectionState.OPEN&&s.currentUser&&s.currentUser.userId===e)s.connecting=!1,i(null,s.currentUser);else if(c&&(s._currentUserId=e),s.connectionCallbacks.push(i),1===s.connectionCallbacks.length){l.disconnect({clearSession:!0,err:null},null);var o=a.container,u=o.nestdb,h=o.localCacheLock;u?l.connect(e,t).then((function(){if(c)return Ut._processNonAutoResendRegisteredPendingMessages(s)})):h.lock((function(n){s.initializeDatabase(e).then((function(){n(),l.connect(e,t)})).then((function(){if(c)return Ut._processNonAutoResendRegisteredPendingMessages(s)})).catch((function(e){a.container.localCacheEnabled=!1,n(),i(e,null)}))}))}}),i)}},{key:"reconnect",value:function(){var e=this,t=O.get(this._iid).container,n=t.wsAdapter,r=t.auth,i=t.localCacheLock;if(r.sessionKey&&this.currentUser){var s=!0;return n.reconnectCount>0&&(s=!1),i.lock((function(t){n.disconnect({clearSession:!1,err:new H("Connection has been canceled.",H.CONNECTION_CANCELED)},null),n.reconnectCount=0,n.reconnect(e.currentUser.userId,s),t()})),!0}return!1}},{key:"disconnect",value:function(e){var t=this;return oe(this._iid,(function(e){var n=O.get(t._iid).container,r=n.localCacheLock,i=n.wsAdapter,s=n.onlineDetector;s&&s.stop(),r.lock((function(n){i.disconnect({clearSession:!0,err:new H("Connection has been canceled.",H.CONNECTION_CANCELED)},(function(){t.clearCachedData().finally((function(){n(),e(null)}))}))}))}),e)}},{key:"setBackgroundState",value:function(){var e=O.get(this._iid),t=e.container,n=t.wsAdapter,r=t.stateChangeEnabled;!t.isInBackground&&r&&(e.set("isInBackground",!0),this.getConnectionState()!==this.ConnectionState.CLOSED?(e.set("closedByGoingBackground",!0),n.disconnect({clearSession:!1,err:new H("Websocket connection failed as the app goes background.",H.WEBSOCKET_CONNECTION_FAILED)},null),pe.of(this._iid).invokeDisconnect()):e.set("closedByGoingBackground",!1))}},{key:"isInBackground",get:function(){return O.get(this._iid).container.isInBackground}},{key:"setForegroundState",value:function(){var e=O.get(this._iid),t=e.container,n=t.wsAdapter,r=t.stateChangeEnabled,i=t.isInBackground,s=t.closedByGoingBackground;i&&r&&(e.set("isInBackground",!1),s&&this.currentUser&&n.reconnect(this.currentUser.userId,!0))}},{key:"enableStateChange",value:function(){O.get(this._iid).set("enableStateChange",!0)}},{key:"disableStateChange",value:function(){O.get(this._iid).set("enableStateChange",!1)}},{key:"addExtension",value:function(e,t){var n=O.get(this._iid).container,r=n.extensions;n.supportedExtensionKeys.indexOf(e)>-1&&(r[e]=t)}},{key:"createUserListQuery",value:function(e){return new(0,x.get(this._iid).UserListQuery)(e)}},{key:"createApplicationUserListQuery",value:function(){return new(0,x.get(this._iid).ApplicationUserListQuery)}},{key:"createBlockedUserListQuery",value:function(){return new(0,x.get(this._iid).BlockedUserListQuery)}},{key:"createFriendListQuery",value:function(){return new(0,x.get(this._iid).FriendListQuery)}},{key:"createMessageSearchQuery",value:function(e,t){return new(0,x.get(this._iid).MessageSearchQuery)(e,t)}},{key:"sendCommand",value:function(e,t){var n=this;return oe(this._iid,(function(t){n.ConnectionManager.ready((function(r,i){if(r)t(r,null);else{var s=O.get(n._iid).container,a=s.wsAdapter,o=s.ackStateMap;if(null==a||null==a.client||a.client.getConnectionState()!==n.ConnectionState.OPEN||n.getConnectionState()!==n.ConnectionState.OPEN)return void t(new H("Connection is not valid. Please reconnect.",H.WEBSOCKET_CONNECTION_CLOSED),null);if(e.isAckRequired){var l=e.requestId,u={handler:t,timer:setTimeout((function(){t(new H("Command received no ack.",H.ACK_TIMEOUT),null),delete o[l]}),n.Options.websocketResponseTimeout)};o[l]=u,a.client.send(e,(function(e){e&&(clearTimeout(u.timer),t(e,null))}))}else a.client.send(e,t)}}),!1)}),t).catch((function(e){J.debug(e)}))}},{key:"setSessionHandler",value:function(e){O.get(this._iid).container.sessionManager.setHandler(e)}},{key:"addUserEventHandler",value:function(e,t){t instanceof x.get(this._iid).UserEventHandler&&(this.userEventHandlers[e]=t)}},{key:"removeUserEventHandler",value:function(e){delete this.userEventHandlers[e]}},{key:"removeAllUserEventHandler",value:function(){this.userEventHandlers={}}},{key:"addChannelHandler",value:function(e,t){t instanceof x.get(this._iid).ChannelHandler&&(this.channelHandlers[e]=t)}},{key:"removeChannelHandler",value:function(e){delete this.channelHandlers[e]}},{key:"removeAllChannelHandlers",value:function(){this.channelHandlers={}}},{key:"addConnectionHandler",value:function(e,t){t instanceof x.get(this._iid).ConnectionHandler&&(this.connectionHandlers[e]=t)}},{key:"removeConnectionHandler",value:function(e){delete this.connectionHandlers[e]}},{key:"removeAllConnectionHandlers",value:function(){this.connectionHandlers={}}},{key:"updateCurrentUserInfo",value:function(e,t,n){var r=this,i=null,s=me.parse(arguments,[new me({type:"string",nullable:!0}),new me({type:"string",nullable:!0}),new me({type:"callback"})]),a=C(s,4);return i=a[0],e=a[1],t=a[2],n=a[3],oe(this._iid,(function(n){if(i)n(i,null);else{var s=O.get(r._iid);s.container.apiClient.updateCurrentUserInfo({nickname:e,profileUrl:t},(function(i,a){var o=null;i||(r.currentUser&&(e&&(r.currentUser.nickname=e),t&&(r.currentUser.plainProfileUrl=t,Object.defineProperty(r.currentUser,"profileUrl",{value:r.currentUser.requireAuth?"".concat(r.currentUser.plainProfileUrl,"?auth=").concat(s.container.auth.eKey):r.currentUser.plainProfileUrl,configurable:!0,writable:!1}))),o=r.currentUser),n(i,o)}))}}),n)}},{key:"updateCurrentUserInfoWithProfileImage",value:function(e,t,n){var r=this,i=null,s=me.parse(arguments,[new me({type:"string",nullable:!0}),new me({type:"file",nullable:!0}),new me({type:"callback"})]),a=C(s,4);return i=a[0],e=a[1],t=a[2],n=a[3],oe(this._iid,(function(n){if(i)n(i,null);else{var s=O.get(r._iid);s.container.apiClient.updateCurrentUserInfo({nickname:e,profileImage:t},(function(t,i){var a=null;t||(r.currentUser&&(e&&(r.currentUser.nickname=e),i.profile_url&&(r.currentUser.plainProfileUrl=i.profile_url,Object.defineProperty(r.currentUser,"profileUrl",{value:r.currentUser.requireAuth?"".concat(r.currentUser.plainProfileUrl,"?auth=").concat(s.container.auth.eKey):r.currentUser.plainProfileUrl,configurable:!0,writable:!1}))),a=r.currentUser),n(t,a)}))}}),n)}},{key:"updateCurrentUserInfoWithPreferredLanguages",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"array",constraint:function(e){return e.every((function(e){return"string"==typeof e}))}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.updateCurrentUserInfo({preferredLanguages:e},(function(r,i){var s=null;r||(n.currentUser&&e&&(n.currentUser._preferredLanguages=e),s=n.currentUser),t(r,s)}))}),t)}},{key:"registerGCMPushTokenForCurrentUser",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"string",constraint:function(e){return e.length>0}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,n.pushTokenRegistrationState.ERROR):n.currentUser?O.get(n._iid).container.apiClient.registerGCMPushToken({token:e},(function(e,r){var i=n.pushTokenRegistrationState.ERROR;e||(n.GCMPushToken="",i=n.pushTokenRegistrationState.SUCCESS),t(e,i)})):(n.GCMPushToken=e,t(null,n.pushTokenRegistrationState.PENDING))}),t)}},{key:"unregisterGCMPushTokenForCurrentUser",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"string",constraint:function(e){return e.length>0}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):n.currentUser?O.get(n._iid).container.apiClient.unregisterGCMPushToken({token:e},(function(e,n){t(e,null)})):(n.GCMPushToken=e,t(null,n.pushTokenRegistrationState.PENDING))}),t)}},{key:"unregisterGCMPushTokenAllForCurrentUser",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.unregisterAllGCMPushTokens({},(function(t,n){e(t,null)}))}),e)}},{key:"registerAPNSPushTokenForCurrentUser",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"string",constraint:function(e){return e.length>0}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,n.pushTokenRegistrationState.ERROR):n.currentUser?O.get(n._iid).container.apiClient.registerAPNSPushToken({token:e},(function(e,r){var i=n.pushTokenRegistrationState.ERROR;e||(n.APNSPushToken="",i=n.pushTokenRegistrationState.SUCCESS),t(e,i)})):(n.APNSPushToken=e,t(null,n.pushTokenRegistrationState.PENDING))}),t)}},{key:"unregisterAPNSPushTokenForCurrentUser",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"string",constraint:function(e){return e.length>0}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):n.currentUser?O.get(n._iid).container.apiClient.unregisterAPNSPushToken({token:e},(function(e,n){t(e,null)})):(n.APNSPushToken=e,t(null,n.pushTokenRegistrationState.PENDING))}),t)}},{key:"unregisterAPNSPushTokenAllForCurrentUser",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.unregisterAllAPNSPushTokens({},(function(t,n){e(t,null)}))}),e)}},{key:"unregisterPushTokenAllForCurrentUser",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.unregisterAllPushTokens({},(function(t,n){e(t,null)}))}),e)}},{key:"getMyGroupChannelChangeLogsByToken",value:function(e,t,n,r){var i=this,s=null,a=me.parse(arguments,[new me({type:"string",nullable:!0}),new me({type:"array",optional:!0,nullable:!0,defaultValue:null}),new me({type:"boolean",nullable:!0,optional:!0,defaultValue:null}),new me({type:"callback"})]),o=C(a,5);s=o[0],e=o[1],t=o[2],n=o[3],r=o[4];var u=x.get(this._iid),c=u.GroupChannelChangeLogsParams,d=null;if(s){var h=me.parse(arguments,[new me({type:"string",nullable:!0}),new me({type:c,constraint:function(e){return e._validate()}}),new me({type:"callback"})]),p=C(h,4);s=p[0],e=p[1],d=p[2],r=p[3]}else(d=new c).customTypes=t,d.includeEmpty=n,d.includeFrozen=!0;return oe(this._iid,(function(t){s?t(s,null):O.get(i._iid).container.apiClient.getMyGroupChannelChangeLogs(l({ts:null,token:e},d)).then((function(e){var n=x.get(i._iid).GroupChannel,r=e.updated.map((function(e){return new n(e)})),s=e.deleted,a=e.has_more,o=e.next;t(null,{updatedChannels:r,deletedChannelUrls:s,hasMore:a,token:o})})).catch((function(e){t(e,null)}))}),r)}},{key:"getMyGroupChannelChangeLogsByTimestamp",value:function(e,t,n,r){var i=this,s=null,a=me.parse(arguments,[new me({type:"number",constraint:function(e){return e>=0}}),new me({type:"array",optional:!0,nullable:!0,defaultValue:null}),new me({type:"boolean",nullable:!0,optional:!0,defaultValue:null}),new me({type:"callback"})]),o=C(a,5);s=o[0],e=o[1],t=o[2],n=o[3],r=o[4];var u=x.get(this._iid),c=u.GroupChannelChangeLogsParams,d=null;if(s){var h=me.parse(arguments,[new me({type:"number",constraint:function(e){return e>=0}}),new me({type:c,constraint:function(e){return e._validate()}}),new me({type:"callback"})]),p=C(h,4);s=p[0],e=p[1],d=p[2],r=p[3]}else(d=new c).customTypes=t,d.includeEmpty=n,d.includeFrozen=!0;return oe(this._iid,(function(t){s?t(s,null):O.get(i._iid).container.apiClient.getMyGroupChannelChangeLogs(l({ts:e,token:null},d)).then((function(e){var n=x.get(i._iid).GroupChannel,r=e.updated.map((function(e){return new n(e)})),s=e.deleted,a=e.has_more,o=e.next;t(null,{updatedChannels:r,deletedChannelUrls:s,hasMore:a,token:o})})).catch((function(e){t(e,null)}))}),r)}},{key:"getChannelInvitationPreference",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.getChannelInvitationPreference({},(function(t,n){var r=null;t||(r={autoAccept:n.auto_accept}),e(t,r)}))}),e)}},{key:"setChannelInvitationPreference",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"boolean"}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.setChannelInvitationPreference({isAutoAccept:e},(function(e,n){var r=null;e||(r={autoAccept:n.auto_accept}),t(e,r)}))}),t)}},{key:"getDoNotDisturb",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.getDoNotDisturb({},(function(t,n){var r=null;t||(r={doNotDisturbOn:n.do_not_disturb,startHour:n.start_hour,startMin:n.start_min,endHour:n.end_hour,endMin:n.end_min,timezone:n.timezone}),e(t,r)}))}),e)}},{key:"setDoNotDisturb",value:function(e,t,n,r,i,s,a){var o=this,l=null,u=me.parse(arguments,[new me({type:"boolean"}),new me({type:"number",constraint:function(e){return 0<=e&&e<=23}}),new me({type:"number",constraint:function(e){return 0<=e&&e<=59}}),new me({type:"number",constraint:function(e){return 0<=e&&e<=23}}),new me({type:"number",constraint:function(e){return 0<=e&&e<=59}}),new me({type:"string"}),new me({type:"callback"})]),c=C(u,8);return l=c[0],e=c[1],t=c[2],n=c[3],r=c[4],i=c[5],s=c[6],a=c[7],oe(this._iid,(function(a){l?a(l,null):O.get(o._iid).container.apiClient.setDoNotDisturb({doNotDisturbOn:e,startHour:t,startMin:n,endHour:r,endMin:i,timezone:s},(function(e,t){var n=null;e||(n={doNotDisturbOn:t.do_not_disturb,startHour:t.start_hour,startMin:t.start_min,endHour:t.end_hour,endMin:t.end_min,timezone:t.timezone}),a(e,n)}))}),a)}},{key:"getSnoozePeriod",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.getSnoozePeriod({},(function(t,n){var r=null;t||(r={isSnoozeOn:n.snooze_enabled,startTs:n.snooze_start_ts,endTs:n.snooze_end_ts}),e(t,r)}))}),e)}},{key:"setSnoozePeriod",value:function(e,t,n,r){var i=this,s=null,a=me.parse(arguments,[new me({type:"boolean"}),new me({type:"number",constraint:function(e){return e>0}}),new me({type:"number",constraint:function(e){return e>0}}),new me({type:"callback"})]),o=C(a,5);return s=o[0],e=o[1],t=o[2],n=o[3],r=o[4],oe(this._iid,(function(r){s?r(s,null):O.get(i._iid).container.apiClient.setSnoozePeriod({snoozeOn:e,startTs:t,endTs:n},(function(e,t){var n=null;e||(n={isSnoozeOn:t.snooze_enabled,startTs:t.snooze_start_ts,endTs:t.snooze_end_ts}),r(e,n)}))}),r)}},{key:"blockUser",value:function(e,t){var n=null,r=me.parse(arguments,[new me({type:"object",constraint:function(e){return e&&e.hasOwnProperty("userId")}}),new me({type:"callback"})]),i=C(r,3);return n=i[0],e=i[1],t=i[2],n?oe(this._iid,(function(e){e(n,null)}),t):this.blockUserWithUserId(e.userId,t)}},{key:"blockUserWithUserId",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"string",constraint:function(e){return e&&(!n.currentUser||e!==n.currentUser.userId)}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.blockUser({blockedUserId:e},(function(e,n){var r=null;e||(r=new ft(n)),t(e,r)}))}),t)}},{key:"unblockUser",value:function(e,t){var n=null,r=me.parse(arguments,[new me({type:"object",constraint:function(e){return e&&e.hasOwnProperty("userId")}}),new me({type:"callback"})]),i=C(r,3);return n=i[0],e=i[1],t=i[2],n?oe(this._iid,(function(e){e(n,null)}),t):this.unblockUserWithUserId(e.userId,t)}},{key:"unblockUserWithUserId",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"string",constraint:function(e){return e&&(!n.currentUser||e!==n.currentUser.userId)}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.unblockUser({unblockedUserId:e},(function(e,n){t(e,null)}))}),t)}},{key:"getPushTriggerOption",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.getPushTriggerOption({},(function(t,n){e(t,n?n.push_trigger_option:null)}))}),e)}},{key:"setPushTriggerOption",value:function(e,t){var n=this;return oe(this._iid,(function(t){Object.keys(n.PushTriggerOption).map((function(e){return n.PushTriggerOption[e]})).indexOf(e)>-1?O.get(n._iid).container.apiClient.setPushTriggerOption({pushTriggerOption:e},(function(e,n){t(e,n?n.push_trigger_option:null)})):t(me.error,null)}),t)}},{key:"getGroupChannelCount",value:function(e,t){var n=this,r=x.get(this._iid),i=r.GroupChannel,s=null,a=me.parse(arguments,[new me({type:i.MemberStateFilter,optional:!0,defaultValue:i.MemberStateFilter.ALL}),new me({type:"callback"})]),o=C(a,3);return s=o[0],e=o[1],t=o[2],oe(this._iid,(function(t){s?t(s,null):O.get(n._iid).container.apiClient.getGroupChannelCount({memberStateFilter:e},(function(e,n){var r=null;e||(r=parseInt(n.group_channel_count)),t(e,r)}))}),t)}},{key:"getTotalUnreadChannelCount",value:function(e,t){var n=this,r=x.get(this._iid),i=r.GroupChannel,s=r.GroupChannelTotalUnreadChannelCountParams,a=null,o=me.parse(arguments,[new me({type:"object",optional:!0,defaultValue:null,constraint:function(e){return e instanceof s}}),new me({type:"callback"})]),l=C(o,3);return a=l[0],e=l[1],t=l[2],oe(this._iid,(function(t){if(a)t(a,null);else{var r=null,s=i.SuperChannelFilter.ALL;e&&(r=e.channelCustomTypesFilter,s=e.superChannelFilter),O.get(n._iid).container.apiClient.getTotalUnreadChannelCount({customTypesFilter:r,superChannelFilter:s},(function(e,n){var r=null;e||(r=parseInt(n.unread_count)),t(e,r)}))}}),t)}},{key:"getTotalUnreadMessageCount",value:function(e,t){var n=this,r=x.get(this._iid),i=r.GroupChannel,s=r.GroupChannelTotalUnreadMessageCountParams,a=null,o=me.parse(arguments,[new me({type:"object",optional:!0,defaultValue:null,constraint:function(e){return Array.isArray(e)&&e.every((function(e){return"string"==typeof e}))||e instanceof s}}),new me({type:"callback"})]),l=C(o,3);return a=l[0],e=l[1],t=l[2],oe(this._iid,(function(t){if(a)t(a,null);else{var r=i.SuperChannelFilter.ALL;if(e instanceof s){var o=e;e=o.channelCustomTypesFilter,r=o.superChannelFilter}O.get(n._iid).container.apiClient.getTotalUnreadMessageCount({customTypesFilter:e,superChannelFilter:r},(function(e,n){var r=null;e||(r=parseInt(n.unread_count)),t(e,r)}))}}),t)}},{key:"getUnreadItemCount",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"array",constraint:function(e){return e.length>0&&e.every((function(e){return Object.keys(ar.UnreadItemKey).map((function(e){return ar.UnreadItemKey[e]})).indexOf(e)>-1}))}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){if(r)t(r,null);else{var i=e.filter((function(t,n){return e.indexOf(t)===n}));O.get(n._iid).container.apiClient.getUnreadItemCount({keys:i},(function(e,n){t(e,n)}))}}),t)}},{key:"getSubscribedTotalUnreadMessageCount",value:function(){var e=O.get(this._iid).container.subscribedUnreadMessageCount;return e.all>=0?e.all:0}},{key:"getSubscribedCustomTypeTotalUnreadMessageCount",value:function(){var e=O.get(this._iid).container.subscribedUnreadMessageCount;if(Object.keys(e.custom_types).length>0){var t=0;return Object.keys(e.custom_types).forEach((function(n){t+=e.custom_types[n]})),t}return 0}},{key:"getSubscribedCustomTypeUnreadMessageCount",value:function(e){if(e&&"string"==typeof e){var t=O.get(this._iid).container.subscribedUnreadMessageCount;return t.custom_types.hasOwnProperty(e)?t.custom_types[e]:0}return 0}},{key:"getMyPushTokensByToken",value:function(e,t,n){var r=this,i=null,s=me.parse(arguments,[new me({type:"string"}),new me({type:"string",constraint:function(e){return["gcm","apns","apns_voip"].indexOf(e)>-1}}),new me({type:"callback"})]),a=C(s,4);return i=a[0],e=a[1],t=a[2],n=a[3],oe(this._iid,(function(n){i?n(i,null):O.get(r._iid).container.apiClient.getPushTokens({ts:null,token:e,type:t},(function(e,t){if(e)n(e,null);else{var r=t.type;n(null,{deviceTokens:t.device_tokens,type:r?r.toLowerCase():"unknown",hasMore:t.has_more,token:t.token})}}))}),n)}},{key:"getPushTemplate",value:function(e){var t=this;return oe(this._iid,(function(e){O.get(t._iid).container.apiClient.getPushTemplate({},(function(t,n){var r=null;t||(r=n.name.toString()),e(t,r)}))}),e)}},{key:"setPushTemplate",value:function(e,t){var n=this;return oe(this._iid,(function(t){[n.PUSH_TEMPLATE_DEFAULT,n.PUSH_TEMPLATE_ALTERNATIVE].indexOf(e)>-1?O.get(n._iid).container.apiClient.setPushTemplate({templateName:e},(function(e,n){var r=null;e||(r=n.name.toString()),t(e,r)})):t(me.error,null)}),t)}},{key:"markAsReadAll",value:function(e){var t=this;return oe(this._iid,(function(e){var n=x.get(t._iid).GroupChannel,r=(new Date).getTime();r-n.markAsReadAllLastSentAt<1e3?e(new H("MarkAsRead rate limit exceeded.",H.MARK_AS_READ_RATE_LIMIT_EXCEEDED),null):(n.markAsReadAllLastSentAt=r,O.get(t._iid).container.apiClient.markAsReadAll({channelUrls:null},(function(i,s){i||Object.keys(n.cachedChannels).forEach((function(e){t.currentUser&&n.cachedChannels[e].updateReadReceipt(t.currentUser.userId,r),n.cachedChannels[e]._setGroupChannelUnreadCount(0,0)})),e(i,null)})))}),e)}},{key:"markAsReadWithChannelUrls",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"array",constraint:function(e){return e.every((function(e){return"string"==typeof e}))}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){if(r)t(r,null);else{var i=(new Date).getTime();O.get(n._iid).container.apiClient.markAsReadAll({channelUrls:e},(function(r,s){r||e.forEach((function(e){ar.cachedChannels[e]&&(n.currentUser&&ar.cachedChannels[e].updateReadReceipt(n.currentUser.userId,i),ar.cachedChannels[e]._setGroupChannelUnreadCount(0,0))})),t(r,null)}))}}),t)}},{key:"markAsDelivered",value:function(e){"string"==typeof e&&x.get(this._iid).GroupChannel.getChannel(e,T.INTERNAL_CALL).then((function(e){return e.markAsDelivered()})).catch((function(e){return J.debug(e)}))}},{key:"getFriendChangeLogsByToken",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"string",optional:!0,defaultValue:null}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.getFriendChangeLogsByToken({token:e},(function(e,r){var i=null;if(!e){var s=x.get(n._iid).User;i={updatedUsers:r.updated.map((function(e){return new s(e)})),deletedUserIds:r.deleted,hasMore:r.has_more,token:r.next}}t(e,i)}))}),t)}},{key:"uploadFriendDiscoveries",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"array",constraint:function(e){return e.every((function(e){return e.hasOwnProperty("friendDiscoveryKey")}))}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.uploadFriendDiscoveries({discoveries:e},(function(e,n){t(e,n)}))}),t)}},{key:"deleteFriendDiscovery",value:function(e,t){var n=null,r=me.parse(arguments,[new me({type:"string"}),new me({type:"callback"})]),i=C(r,3);return n=i[0],e=i[1],t=i[2],n?oe(this._iid,(function(e){e(n,null)}),t):this.deleteFriendDiscoveries([e],t)}},{key:"deleteFriendDiscoveries",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"array",constraint:function(e){return e.every((function(e){return"string"==typeof e}))}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.deleteFriendDiscoveries({discoveryKeys:e},(function(e,n){t(e,n)}))}),t)}},{key:"addFriends",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"array",constraint:function(e){return e.every((function(e){return"string"==typeof e}))}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.addFriends({userIds:e},(function(e,r){var i=null;if(!e){var s=x.get(n._iid).User;i=r.users.map((function(e){return new s(e)}))}t(e,i)}))}),t)}},{key:"deleteFriend",value:function(e,t){var n=null,r=me.parse(arguments,[new me({type:"string"}),new me({type:"callback"})]),i=C(r,3);return n=i[0],e=i[1],t=i[2],n?oe(this._iid,(function(e){e(n,null)}),t):this.deleteFriends([e],t)}},{key:"deleteFriends",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"array",constraint:function(e){return e.every((function(e){return"string"==typeof e}))}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.deleteFriends({userIds:e},(function(e,n){t(e,n)}))}),t)}},{key:"getAllEmoji",value:function(e){var t=this,n=null,r=me.parse(arguments,[new me({type:"callback"})]),i=C(r,2);return n=i[0],e=i[1],oe(this._iid,(function(e){n?e(n,null):O.get(t._iid).container.apiClient.getAllEmoji((function(n,r){if(n)e(n,null);else{var i=new(0,x.get(t._iid).EmojiContainer)(r);e(null,i)}}))}),e)}},{key:"getEmojiCategory",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"number",constraint:function(e){return e>=0}}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.getEmojiCategory({categoryId:e},(function(e,r){if(e)t(e,null);else{var i=new(0,x.get(n._iid).EmojiCategory)(r);t(null,i)}}))}),t)}},{key:"getEmoji",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"string"}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.getEmoji({emojiKey:e},(function(e,r){if(e)t(e,null);else{var i=new(0,x.get(n._iid).Emoji)(r);t(null,i)}}))}),t)}},{key:"getAllowFriendDiscovery",value:function(e){var t=this,n=null,r=me.parse(arguments,[new me({type:"callback"})]),i=C(r,2);return n=i[0],e=i[1],oe(this._iid,(function(e){n?e(n,null):O.get(t._iid).container.apiClient.getAllowFriendDiscovery((function(t,n){var r=n.allow_friend_discovery;t?e(t,null):e(null,r)}))}),e)}},{key:"setAllowFriendDiscovery",value:function(e,t){var n=this,r=null,i=me.parse(arguments,[new me({type:"boolean"}),new me({type:"callback"})]),s=C(i,3);return r=s[0],e=s[1],t=s[2],oe(this._iid,(function(t){r?t(r,null):O.get(n._iid).container.apiClient.setAllowFriendDiscovery({allowFriendDiscovery:e},(function(n,r){n?t(n,null):t(null,e)}))}),t)}},{key:"clearCachedMessages",value:function(e){var t=this,n=ot.of(this._iid);if(n){var r=O.get(this._iid).container.store;return Promise.all(e.map((function(e){return new Promise((function(i,s){n.clearByChannelUrl(e).then((function(){var n=yt(t._currentUserId,e);return r.remove(n)})).then((function(){var n=vt(t._currentUserId,e);return r.remove(n)})).then((function(){i()})).catch((function(e){s(e)}))}))})))}return Promise.resolve([])}},{key:"_getCurrentUserDataKey",value:function(){return"sendbird:".concat(this._currentUserId,"@currentUserData")}},{key:"_populateVaultFromCurrentUserData",value:function(e){var t=O.get(this._iid),n=t.container.auth,r=x.get(this._iid).User,i=e.currentUser,s=e.maxUnreadCountOfSuperGroupChannel,a=e.profileImageEncryption,o=e.sessionKey,l=e.eKey,u=e.appInfo,c=e.connectedAt,d=e.firstConnectedAt,h=e.concurrentCallLimit,p=e.backOffDelay;i&&(this.currentUser=r.buildFromSerializedData(i)),s&&t.set("maxUnreadCountOfSuperGroupChannel",s),a&&t.set("profileImageEncryption",a),n?(o&&(n.sessionKey=o),l&&(n.ekey=l)):J.debug("Auth should have been created when populating current user data."),u&&t.set("appInfo",new Ie(u)),c&&t.set("connectedAt",c),d&&t.set("firstConnectedAt",d),h&&t.set("concurrentCallLimit",h),p&&t.set("backOffDelay",p)}}],[{key:"version",get:function(){return T.SDK_VERSION}},{key:"LogLevel",get:function(){return J.supportedLogLevels}},{key:"getInstance",value:function(e){return e?ki[e]:Mi}},{key:"getLogLevel",value:function(){return J.logLevel}},{key:"setLogLevel",value:function(e){var t=Object.values(J.supportedLogLevels);if(t.includes(e))J.logLevel=e;else{J.logLevel=J.defaultLogLevel;var n=t.map((function(e){return"'".concat(e,"'")})).join(", ");J.warn("`logLevel` parameter should be one of","".concat(n,","),"not `'".concat(e,"'`."),"Set to default log level","`".concat(J.defaultLogLevel,"`."))}}},{key:"getAppVersion",value:function(){return Li}},{key:"setAppVersion",value:function(e){"string"==typeof e&&$()&&(Li=e)}}]),e}();return wi})); \ No newline at end of file diff --git a/bower.json b/bower.json index ba07579..9593406 100644 --- a/bower.json +++ b/bower.json @@ -1,11 +1,11 @@ { "name": "sendbird", - "version": "3.0.23", + "version": "3.1.33", "authors": [ - "SendBird " + "Sendbird " ], - "homepage": "https://github.com/smilefam/SendBird-SDK-JavaScript", - "description": "SendBird JavaScript SDK", + "homepage": "https://github.com/sendbird/Sendbird-SDK-JavaScript", + "description": "Sendbird JavaScript SDK", "main": "SendBird.min.js", "moduleType": [], "keywords": [ @@ -19,4 +19,4 @@ "ignore": [ "package.json" ] -} +} \ No newline at end of file diff --git a/catalog-info.yaml b/catalog-info.yaml new file mode 100644 index 0000000..faed985 --- /dev/null +++ b/catalog-info.yaml @@ -0,0 +1,12 @@ +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: SendBird-SDK-JavaScript + description: Sendbird Chat SDK for JavaScript for enablement of a rich, engaging, scalable, and real-time chat service + annotations: + github.com/project-slug: sendbird/SendBird-SDK-JavaScript +spec: + type: library + lifecycle: production + owner: dep-client-platform + system: sendbird-chat diff --git a/deprecated.md b/deprecated.md new file mode 100644 index 0000000..f5f88e6 --- /dev/null +++ b/deprecated.md @@ -0,0 +1,288 @@ +# Deprecated classes, methods, properties + + +## v3.1.9 + +### Classes + +| Old class | New Class | +| --------- | --------- | +| ConnectionManager | N/A | + + +## v3.0.159 + +### Methods + +| Old class | Old property | New class | New property | +| --------- | ------------ | --------- | ------------ | +| MessageRetrievalParams | includeParentMessageText: boolean | MessageRetrievalParams | includeParentMessageInfo: boolean | +| PreviousMessageListQuery | includeParentMessageText: boolean | PreviousMessageListQuery | includeParentMessageInfo: boolean | +| PreviousMessageListQuery | includeReplies: boolean | PreviousMessageListQuery | replyType: ReplyType | +| MessageListParams | includeParentMessageText: boolean | MessageListParams | includeParentMessageInfo: boolean | +| MessageListParams | includeReplies: boolean | MessageListParams | replyType: ReplyType | +| ThreadedMessageListParams | includeParentMessageText: boolean | ThreadedMessageListParams | includeParentMessageInfo: boolean | +| MessageChangeLogsParams | includeParentMessageText: boolean | MessageChangeLogsParams | includeParentMessageInfo: boolean | +| MessageChangeLogsParams | includeReplies: boolean | MessageChangeLogsParams | replyType: ReplyType | + + +## v3.0.156 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| GroupChannel | markAsRead(): void | GroupChannel | markAsRead(callback: VoidCallback): Promise<void> | + + +## v3.0.143 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| GroupChannel | markAsDelivered(): void | SendBird | markAsDelivered(channelUrl: String): void | + + +## v3.0.142 + +### Properties + +| Old class | Old property | New class | New property | +| --------- | ------------ | --------- | ------------ | +| UserMessage | sendingStatus: string | BaseMessage | sendingStatus: string | +| FileMessage | sendingStatus: string | BaseMessage | sendingStatus: string | +| AdminMessage | N/A | BaseMessage | sendingStatus: string | +| PreviousMessageListQuery | customTypeFilter: string | PreviousMessageListQuery | customTypesFilter: string[] | +| MessageListParams | customType: string | MessageListParams | customTypes: string[] | +| ThreadedMessageListParams | customType: string | ThreadedMessageListParams | customTypes: string[] | + + +## v3.0.134 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| GroupChannel | getTypingMembers(): Member[] | GroupChannel | getTypingUsers(): Member[] | + + +## v3.0.129 + +### Properties + +| Old class | Old property | New class | New property | +| --------- | ------------ | --------- | ------------ | +| PreviousMessageListQuery | includeReaction: boolean | PreviousMessageListQuery | includeReactions: boolean | +| MessageChangeLogsParams | includeReaction: boolean | MessageChangeLogsParams | includeReactions: boolean | +| MessageListParams | includeReaction: boolean | MessageListParams | includeReactions: boolean | +| ThreadedMessageListParams | includeReaction: boolean | ThreadedMessageListParams | includeReactions: boolean | + + +## v3.0.127 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| GroupChannel | getReadReceipt(message: UserMessage | FileMessage): number | GroupChannel | getUnreadMemberCount(message: UserMessage | FileMessage): number | +| GroupChannel | getDeliveryReceipt(message: UserMessage | FileMessage): number | GroupChannel | getUndeliveredMemberCount(message: UserMessage | FileMessage): number | + + +## v3.0.125 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| SendBird | getMyGroupChannelChangeLogsByToken(token: string, customTypes: string[]): object | SendBird | getMyGroupChannelChangeLogsByToken(token: string, params: GroupChannelChangeLogsParams): object | +| SendBird | getMyGroupChannelChangeLogsByToken(token: string, customTypes: string[], includeEmpty: boolean): object | SendBird | getMyGroupChannelChangeLogsByToken(token: string, params: GroupChannelChangeLogsParams): object | +| SendBird | getMyGroupChannelChangeLogsByTimestamp(timestamp: number, customTypes: string[]): object | SendBird | getMyGroupChannelChangeLogsByTimestamp(timestmap: number, params: GroupChannelChangeLogsParams): object | +| SendBird | getMyGroupChannelChangeLogsByTimestamp(timestamp: number, customTypes: string[], includeEmpty: boolean): object | SendBird | getMyGroupChannelChangeLogsByTimestamp(timestmap: number, params: GroupChannelChangeLogsParams): object | + + +## v3.0.123 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| BaseChannel | getMessageChangeLogsByTimestamp(timestamp: number): object | BaseChannel | getMessageChangeLogsSinceTimestamp(timestamp: number, params: MessageChangeLogsParams): object | +| BaseChannel | getMessageChangeLogsByTimestamp(timestamp: number, includeMetaArray: boolean): object | BaseChannel | getMessageChangeLogsSinceTimestamp(timestamp: number, params: MessageChangeLogsParams): object | +| BaseChannel | getMessageChangeLogsByTimestamp(timestamp: number, includeMetaArray: boolean, includeReactions: boolean): object | BaseChannel | getMessageChangeLogsSinceTimestamp(timestamp: number, params: MessageChangeLogsParams): object | +| BaseChannel | getMessageChangeLogsByToken(): object | BaseChannel | getMessageChangeLogsSinceToken(token: string, params: MessageChangeLogsParams): object | +| BaseChannel | getMessageChangeLogsByToken(token: string): object | BaseChannel | getMessageChangeLogsSinceToken(token: string, params: MessageChangeLogsParams): object | +| BaseChannel | getMessageChangeLogsByToken(token: string, includeMetaArray: boolean): object | BaseChannel | getMessageChangeLogsSinceToken(token: string, params: MessageChangeLogsParams): object | +| BaseChannel | getMessageChangeLogsByToken(token: string, includeMetaArray: boolean, includeReactions: boolean): object | BaseChannel | getMessageChangeLogsSinceToken(token: string, params: MessageChangeLogsParams): object | +| BaseChannel | getPreviousMessagesByTimestamp(timestamp: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByTimestamp(timestamp: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByTimestamp(timestamp: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByTimestamp(timestamp: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByTimestamp(timestamp: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByTimestamp(timestamp: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByTimestamp(timestamp: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByTimestamp(timestamp: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByTimestamp(timestamp: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByTimestamp(timestamp: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByTimestamp(timestamp: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByTimestamp(timestamp: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByTimestamp(timestamp: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByID(messageId: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByID(messageId: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByID(messageId: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByID(messageId: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByID(messageId: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByID(messageId: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByID(messageId: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getNextMessagesByID(messageId: number, isInclusive: boolean, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[]): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | +| BaseChannel | getPreviousAndNextMessagesByID(messageId: number, isInclusive: boolean, prevResultSize: number, nextResultSize: number, shouldReverse: boolean, messageType: string, customType: string, senderUserIds: string[], includeMetaArray: boolean, includeReactions: boolean): BaseMessage[] | BaseChannel | getMessagesByMessageId(messageId: number, params: MessageListParams): BaseMessage[] | + + +## v3.0.122 + +### Properties + +| Old class | Old property | New class | New property | +| --------- | ------------ | --------- | ------------ | +| BaseMessageParams | metaArrayKeys: string[] | BaseMessageParams | metaArrays: MessageMetaArray[] | + + +## v3.0.119 + +### Properties + +| Old class | Old property | New class | New property | +| --------- | ------------ | --------- | ------------ | +| UserMessage | requestState: string | UserMessage | sendingStatus: string | +| FileMessage | requestState: string | FileMessage | sendingStatus: string | + + +### Classes + +| Old class | New class | +| --------- | --------- | +| MessageRequestState | MessageSendingStatus | + + +## v3.0.109 + +### Methods + +| Old class | Old method | New class | New method/property | +| --------- | ---------- | --------- | ------------------- | +| SendBird | getCurrentUserId(): string | SendBird | currentUser: User | + + +## v3.0.105 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| BaseChannel | addMessageMetaArrayValues(message: BaseMessage, metaArrays: object): BaseMessage | BaseChannel | addMessageMetaArrayValues(message: BaseMessage, metaArrays: MessageMetaArray[]): BaseMessage | +| BaseChannel | removeMessageMetaArrayValues(message: BaseMessage, metaArrays: object): BaseMessage | BaseChannel | removeMessageMetaArrayValues(message: BaseMessage, metaArrays: MessageMetaArray[]): BaseMessage | + + +## v3.0.93 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| GroupChannel | getPushPreference(): boolean | GroupChannel | getMyPushTriggerOption(): boolean | +| GroupChannel | setPushPreference(enable: boolean): object | GroupChannel | setMyPushTriggerOption(pushTriggerOption: boolean): boolean | + +### Properties + +| Old class | Old property | New class | New property | +| --------- | ------------ | --------- | ------------ | +| GroupChannel | isPushEnabled: boolean | GroupChannel | myPushTriggerOption: string | + + +## v3.0.86 + +### Classes + +| Old class | New class | +| --------- | --------- | +| UserListQuery | ApplicationUserListQuery | + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| SendBird | createUserListQuery(): UserListQuery | SendBird | createApplicationUserListQuery(): ApplicationUserListQuery | +| SendBird | createUserListQuery(userIds: string[]): UserListQuery | SendBird | createApplicationUserListQuery(): ApplicationUserListQuery | + + +## v3.0.84 + +### Properties + +| Old class | Old property | New class | New property | +| --------- | ------------ | --------- | ------------ | +| UserMessageParams | targetLanguages: string[] | UserMessageParams | translationTargetLanguages: string[] | + + +## v3.0.80 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| GroupChannel | getChannelCount(memberStateFilter: string): number | SendBird | getGroupChannelCount(memberStateFilter: string): number | +| GroupChannel | getUnreadItemCount(keys: string[]): number | SendBird | getUnreadItemCount(keys: string[]): number | +| GroupChannel | getTotalUnreadMessageCount(): number | SendBird | getTotalUnreadMessageCount(): number | +| GroupChannel | getTotalUnreadMessageCount(channelCustomTypes: string[]): number | SendBird | getTotalUnreadMessageCount(channelCustomTypesFilter: string[]): number | +| GroupChannel | getTotalUnreadMessageCount(params: GroupChannelTotalUnreadMessageCountParams): number | SendBird | getTotalUnreadMessageCount(params: GroupChannelTotalUnreadMessageCountParams): number | +| GroupChannel | getTotalUnreadChannelCount(): number | SendBird | getTotalUnreadChannelCount(): number | + + +## v3.0.50 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| GroupChannel | markAsReadAll(): void | SendBird | markAsReadAll(): void | + + +## v3.0.49 + +### Properties + +| Old class | Old property | New class | New property | +| --------- | ------------ | --------- | ------------ | +| GroupChannelListQuery | customTypeFilter: string | GroupChannelListQuery | customTypesFilter: string[] | + + +## v3.0.36 + +### Classes + +| Old class | New class | +| --------- | --------- | +| MessageListQuery | PreviousMessageListQuery | + + +## v3.0.27 + +### Methods + +| Old class | Old method | New class | New method | +| --------- | ---------- | --------- | ---------- | +| N/A | N/A | SendBird | setErrorFirstCallback(errorFirstInCallback: boolean) | diff --git a/package.json b/package.json index eb7f942..f641f89 100644 --- a/package.json +++ b/package.json @@ -1,19 +1,20 @@ { "name": "sendbird", - "version": "3.0.23", - "description": "SendBird JavaScript SDK", + "version": "3.1.33", + "description": "Sendbird JavaScript SDK", "main": "SendBird.min.js", "dependencies": { - "websocket": "1.0.22", - "xhr2": "0.1.3", - "agentkeepalive": "2.2.0" + "agentkeepalive": "4.1.4", + "axios": "^0.27.2", + "form-data": "^4.0.0", + "ws": "^7.5.5" }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", - "url": "https://github.com/smilefam/SendBird-SDK-JavaScript" + "url": "https://github.com/sendbird/Sendbird-SDK-JavaScript" }, "keywords": [ "sendbird", @@ -22,10 +23,10 @@ "chat", "js" ], - "author": "SendBird ", + "author": "Sendbird ", "license": "SEE LICENSE IN LICENSE.md", "bugs": { - "url": "https://github.com/smilefam/SendBird-SDK-JavaScript/issues" + "url": "https://github.com/sendbird/Sendbird-SDK-JavaScript/issues" }, "homepage": "https://sendbird.com", "typings": "SendBird.d.ts"