@amityco/ts-sdk-react-native 6.23.0 → 6.23.1-d8b4c4c.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/.env +26 -26
  2. package/dist/@types/core/events.d.ts +7 -0
  3. package/dist/@types/core/events.d.ts.map +1 -1
  4. package/dist/@types/core/model.d.ts +4 -2
  5. package/dist/@types/core/model.d.ts.map +1 -1
  6. package/dist/@types/core/payload.d.ts +2 -1
  7. package/dist/@types/core/payload.d.ts.map +1 -1
  8. package/dist/@types/domains/community.d.ts +30 -1
  9. package/dist/@types/domains/community.d.ts.map +1 -1
  10. package/dist/@types/domains/stream.d.ts +19 -3
  11. package/dist/@types/domains/stream.d.ts.map +1 -1
  12. package/dist/client/api/secureLogout.d.ts +1 -1
  13. package/dist/client/utils/ReadReceiptSync/readReceiptSyncEngine.d.ts.map +1 -1
  14. package/dist/commentRepository/api/deleteComment.d.ts.map +1 -1
  15. package/dist/commentRepository/internalApi/createComment.d.ts.map +1 -1
  16. package/dist/communityRepository/api/createCommunity.d.ts.map +1 -1
  17. package/dist/communityRepository/api/getCommunities.d.ts.map +1 -1
  18. package/dist/communityRepository/api/getCommunity.d.ts.map +1 -1
  19. package/dist/communityRepository/api/queryCommunities.d.ts.map +1 -1
  20. package/dist/communityRepository/api/updateCommunity.d.ts.map +1 -1
  21. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.d.ts +14 -0
  22. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.d.ts.map +1 -0
  23. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.d.ts +9 -0
  24. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.d.ts.map +1 -0
  25. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts +15 -0
  26. package/dist/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.d.ts.map +1 -0
  27. package/dist/communityRepository/communityMembership/observers/getMembers/enums.d.ts +10 -0
  28. package/dist/communityRepository/communityMembership/observers/getMembers/enums.d.ts.map +1 -0
  29. package/dist/communityRepository/communityMembership/observers/getMembers.d.ts.map +1 -1
  30. package/dist/communityRepository/communityMembership/observers/index.d.ts +1 -0
  31. package/dist/communityRepository/communityMembership/observers/index.d.ts.map +1 -1
  32. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersLiveCollectionController.d.ts +14 -0
  33. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersLiveCollectionController.d.ts.map +1 -0
  34. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersPaginationController.d.ts +9 -0
  35. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersPaginationController.d.ts.map +1 -0
  36. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.d.ts +15 -0
  37. package/dist/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.d.ts.map +1 -0
  38. package/dist/communityRepository/communityMembership/observers/searchMembers/enums.d.ts +10 -0
  39. package/dist/communityRepository/communityMembership/observers/searchMembers/enums.d.ts.map +1 -0
  40. package/dist/communityRepository/communityMembership/observers/searchMembers.d.ts +20 -0
  41. package/dist/communityRepository/communityMembership/observers/searchMembers.d.ts.map +1 -0
  42. package/dist/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.d.ts +14 -0
  43. package/dist/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.d.ts.map +1 -0
  44. package/dist/communityRepository/observers/getCommunities/CommunitiesPaginationController.d.ts +9 -0
  45. package/dist/communityRepository/observers/getCommunities/CommunitiesPaginationController.d.ts.map +1 -0
  46. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts +15 -0
  47. package/dist/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.d.ts.map +1 -0
  48. package/dist/communityRepository/observers/getCommunities/enums.d.ts +6 -0
  49. package/dist/communityRepository/observers/getCommunities/enums.d.ts.map +1 -0
  50. package/dist/communityRepository/observers/getCommunities.d.ts.map +1 -1
  51. package/dist/communityRepository/observers/index.d.ts +1 -0
  52. package/dist/communityRepository/observers/index.d.ts.map +1 -1
  53. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.d.ts +14 -0
  54. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.d.ts.map +1 -0
  55. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.d.ts +9 -0
  56. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.d.ts.map +1 -0
  57. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts +15 -0
  58. package/dist/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.d.ts.map +1 -0
  59. package/dist/communityRepository/observers/searchCommunities/enums.d.ts +6 -0
  60. package/dist/communityRepository/observers/searchCommunities/enums.d.ts.map +1 -0
  61. package/dist/communityRepository/observers/searchCommunities.d.ts +20 -0
  62. package/dist/communityRepository/observers/searchCommunities.d.ts.map +1 -0
  63. package/dist/communityRepository/utils/payload.d.ts.map +1 -1
  64. package/dist/communityRepository/utils/saveCommunityUsers.d.ts +2 -0
  65. package/dist/communityRepository/utils/saveCommunityUsers.d.ts.map +1 -0
  66. package/dist/core/events.d.ts +3 -3
  67. package/dist/core/events.d.ts.map +1 -1
  68. package/dist/core/liveCollection/LiveCollectionController.d.ts +4 -1
  69. package/dist/core/liveCollection/LiveCollectionController.d.ts.map +1 -1
  70. package/dist/core/model/idResolvers.d.ts.map +1 -1
  71. package/dist/core/model/index.d.ts.map +1 -1
  72. package/dist/index.cjs.js +1604 -977
  73. package/dist/index.esm.js +1372 -745
  74. package/dist/index.umd.js +4 -4
  75. package/dist/marker/events/onChannelUnreadUpdatedLocal.d.ts +12 -0
  76. package/dist/marker/events/onChannelUnreadUpdatedLocal.d.ts.map +1 -0
  77. package/dist/marker/events/onSubChannelUnreadUpdatedLocal.d.ts +12 -0
  78. package/dist/marker/events/onSubChannelUnreadUpdatedLocal.d.ts.map +1 -0
  79. package/dist/marker/events/onUserFeedMarkerUpdated.d.ts.map +1 -1
  80. package/dist/marker/utils/reCalculateChannelUnreadInfo.d.ts +1 -1
  81. package/dist/marker/utils/reCalculateChannelUnreadInfo.d.ts.map +1 -1
  82. package/dist/postRepository/observers/getPost.d.ts.map +1 -1
  83. package/dist/postRepository/observers/getPosts.d.ts.map +1 -1
  84. package/dist/streamRepository/api/createStream.d.ts +4 -4
  85. package/dist/streamRepository/api/createStream.d.ts.map +1 -1
  86. package/dist/streamRepository/api/deleteStream.d.ts +4 -4
  87. package/dist/streamRepository/api/deleteStream.d.ts.map +1 -1
  88. package/dist/streamRepository/api/disposeStream.d.ts +4 -4
  89. package/dist/streamRepository/api/disposeStream.d.ts.map +1 -1
  90. package/dist/streamRepository/api/queryStreams.d.ts +4 -4
  91. package/dist/streamRepository/api/queryStreams.d.ts.map +1 -1
  92. package/dist/streamRepository/api/updateStream.d.ts.map +1 -1
  93. package/dist/streamRepository/events/index.d.ts +2 -0
  94. package/dist/streamRepository/events/index.d.ts.map +1 -1
  95. package/dist/streamRepository/events/onStreamFlagged.d.ts +17 -0
  96. package/dist/streamRepository/events/onStreamFlagged.d.ts.map +1 -0
  97. package/dist/streamRepository/events/onStreamRecorded.d.ts +2 -2
  98. package/dist/streamRepository/events/onStreamRecorded.d.ts.map +1 -1
  99. package/dist/streamRepository/events/onStreamStarted.d.ts +2 -2
  100. package/dist/streamRepository/events/onStreamStarted.d.ts.map +1 -1
  101. package/dist/streamRepository/events/onStreamStopped.d.ts +2 -2
  102. package/dist/streamRepository/events/onStreamStopped.d.ts.map +1 -1
  103. package/dist/streamRepository/events/onStreamTerminated.d.ts +17 -0
  104. package/dist/streamRepository/events/onStreamTerminated.d.ts.map +1 -0
  105. package/dist/streamRepository/internalApi/queryStreams.d.ts +3 -3
  106. package/dist/streamRepository/internalApi/queryStreams.d.ts.map +1 -1
  107. package/dist/streamRepository/observers/getStreamById.d.ts +1 -0
  108. package/dist/streamRepository/observers/getStreamById.d.ts.map +1 -1
  109. package/dist/streamRepository/observers/getStreams/GetStreamsLiveCollectionController.d.ts +14 -0
  110. package/dist/streamRepository/observers/getStreams/GetStreamsLiveCollectionController.d.ts.map +1 -0
  111. package/dist/streamRepository/observers/getStreams/GetStreamsPageController.d.ts +14 -0
  112. package/dist/streamRepository/observers/getStreams/GetStreamsPageController.d.ts.map +1 -0
  113. package/dist/streamRepository/observers/getStreams/GetStreamsQueryStreamController.d.ts +15 -0
  114. package/dist/streamRepository/observers/getStreams/GetStreamsQueryStreamController.d.ts.map +1 -0
  115. package/dist/streamRepository/observers/getStreams/getStreams.d.ts +2 -0
  116. package/dist/streamRepository/observers/getStreams/getStreams.d.ts.map +1 -0
  117. package/dist/streamRepository/observers/getStreams/index.d.ts +2 -0
  118. package/dist/streamRepository/observers/getStreams/index.d.ts.map +1 -0
  119. package/dist/utils/linkedObject/index.d.ts +1 -0
  120. package/dist/utils/linkedObject/index.d.ts.map +1 -1
  121. package/dist/utils/linkedObject/streamLinkedObject.d.ts +2 -0
  122. package/dist/utils/linkedObject/streamLinkedObject.d.ts.map +1 -0
  123. package/dist/utils/liveObject.d.ts +3 -0
  124. package/dist/utils/liveObject.d.ts.map +1 -1
  125. package/package.json +1 -1
  126. package/src/@types/core/events.ts +12 -0
  127. package/src/@types/core/model.ts +4 -2
  128. package/src/@types/core/payload.ts +2 -1
  129. package/src/@types/domains/community.ts +50 -1
  130. package/src/@types/domains/stream.ts +23 -3
  131. package/src/channelRepository/channelMembership/observers/getMembers/ChannelMemberLiveCollectionController.ts +2 -2
  132. package/src/channelRepository/observers/getChannel.ts +2 -2
  133. package/src/channelRepository/observers/getChannels/ChannelLiveCollectionController.ts +7 -7
  134. package/src/client/api/secureLogout.ts +1 -1
  135. package/src/client/utils/ReadReceiptSync/readReceiptSyncEngine.ts +6 -3
  136. package/src/commentRepository/api/createComment.ts +2 -2
  137. package/src/commentRepository/api/deleteComment.ts +2 -4
  138. package/src/commentRepository/events/utils.ts +1 -1
  139. package/src/commentRepository/internalApi/createComment.ts +3 -2
  140. package/src/commentRepository/internalApi/deleteComment.ts +2 -2
  141. package/src/communityRepository/api/createCommunity.ts +5 -2
  142. package/src/communityRepository/api/getCommunities.ts +5 -1
  143. package/src/communityRepository/api/getCommunity.ts +5 -1
  144. package/src/communityRepository/api/queryCommunities.ts +2 -2
  145. package/src/communityRepository/api/updateCommunity.ts +5 -1
  146. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersLiveCollectionController.ts +152 -0
  147. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersPaginationController.ts +26 -0
  148. package/src/communityRepository/communityMembership/observers/getMembers/CommunityMembersQueryStreamController.ts +114 -0
  149. package/src/communityRepository/communityMembership/observers/getMembers/enums.ts +9 -0
  150. package/src/communityRepository/communityMembership/observers/getMembers.ts +15 -128
  151. package/src/communityRepository/communityMembership/observers/index.ts +1 -0
  152. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersLiveCollectionController.ts +130 -0
  153. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersPaginationController.ts +29 -0
  154. package/src/communityRepository/communityMembership/observers/searchMembers/SearchCommunityMembersQueryStreamController.ts +105 -0
  155. package/src/communityRepository/communityMembership/observers/searchMembers/enums.ts +9 -0
  156. package/src/communityRepository/communityMembership/observers/searchMembers.ts +60 -0
  157. package/src/communityRepository/observers/getCommunities/CommunitiesLiveCollectionController.ts +147 -0
  158. package/src/communityRepository/observers/getCommunities/CommunitiesPaginationController.ts +31 -0
  159. package/src/communityRepository/observers/getCommunities/CommunitiesQueryStreamController.ts +86 -0
  160. package/src/communityRepository/observers/getCommunities/enums.ts +5 -0
  161. package/src/communityRepository/observers/getCommunities.ts +7 -150
  162. package/src/communityRepository/observers/index.ts +1 -0
  163. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesLiveCollectionController.ts +129 -0
  164. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesPaginationController.ts +31 -0
  165. package/src/communityRepository/observers/searchCommunities/SearchCommunitiesQueryStreamController.ts +81 -0
  166. package/src/communityRepository/observers/searchCommunities/enums.ts +5 -0
  167. package/src/communityRepository/observers/searchCommunities.ts +56 -0
  168. package/src/communityRepository/utils/payload.ts +35 -1
  169. package/src/communityRepository/utils/saveCommunityUsers.ts +16 -0
  170. package/src/core/liveCollection/LiveCollectionController.ts +6 -3
  171. package/src/core/model/idResolvers.ts +1 -0
  172. package/src/core/model/index.ts +1 -0
  173. package/src/marker/events/onChannelUnreadUpdatedLocal.ts +29 -0
  174. package/src/marker/events/onSubChannelMarkerFetched.ts +1 -1
  175. package/src/marker/events/onSubChannelUnreadUpdatedLocal.ts +29 -0
  176. package/src/marker/events/onUserFeedMarkerUpdated.ts +3 -4
  177. package/src/marker/utils/reCalculateChannelUnreadInfo.ts +7 -3
  178. package/src/messageRepository/observers/getMessages/MessageLiveCollectionController.ts +3 -3
  179. package/src/postRepository/api/editPost.ts +1 -1
  180. package/src/postRepository/api/updatePost.ts +1 -1
  181. package/src/postRepository/observers/getPost.ts +26 -0
  182. package/src/postRepository/observers/getPosts.ts +31 -0
  183. package/src/storyRepository/observers/getGlobalStoryTargets/GlobalStoryLiveCollectionController.ts +2 -2
  184. package/src/storyRepository/observers/getStoriesByTargetIds/StoryLiveCollectionController.ts +1 -1
  185. package/src/streamRepository/api/createStream.ts +8 -5
  186. package/src/streamRepository/api/deleteStream.ts +6 -4
  187. package/src/streamRepository/api/disposeStream.ts +5 -5
  188. package/src/streamRepository/api/queryStreams.ts +4 -4
  189. package/src/streamRepository/api/updateStream.ts +2 -1
  190. package/src/streamRepository/events/index.ts +2 -0
  191. package/src/streamRepository/events/onStreamFlagged.ts +37 -0
  192. package/src/streamRepository/events/onStreamRecorded.ts +4 -2
  193. package/src/streamRepository/events/onStreamStarted.ts +4 -2
  194. package/src/streamRepository/events/onStreamStopped.ts +4 -2
  195. package/src/streamRepository/events/onStreamTerminated.ts +37 -0
  196. package/src/streamRepository/internalApi/queryStreams.ts +3 -3
  197. package/src/streamRepository/observers/getStreamById.ts +18 -5
  198. package/src/streamRepository/observers/getStreams/GetStreamsLiveCollectionController.ts +114 -0
  199. package/src/streamRepository/observers/getStreams/GetStreamsPageController.ts +23 -0
  200. package/src/streamRepository/observers/getStreams/GetStreamsQueryStreamController.ts +83 -0
  201. package/src/streamRepository/observers/getStreams/getStreams.ts +32 -0
  202. package/src/streamRepository/observers/getStreams/index.ts +1 -0
  203. package/src/streamRepository/observers/tests/getStreamById.test.ts +1 -1
  204. package/src/subChannelRepository/observers/getSubChannel.ts +2 -2
  205. package/src/subChannelRepository/observers/getSubChannels/SubChannelLiveCollectionController.ts +4 -4
  206. package/src/utils/linkedObject/index.ts +2 -0
  207. package/src/utils/linkedObject/streamLinkedObject.ts +11 -0
  208. package/src/utils/liveObject.ts +3 -0
  209. package/dist/streamRepository/api/getStreams.d.ts +0 -39
  210. package/dist/streamRepository/api/getStreams.d.ts.map +0 -1
  211. package/dist/streamRepository/observers/getStreams.d.ts +0 -17
  212. package/dist/streamRepository/observers/getStreams.d.ts.map +0 -1
  213. package/src/streamRepository/api/getStreams.ts +0 -81
  214. package/src/streamRepository/observers/getStreams.ts +0 -152
package/dist/index.esm.js CHANGED
@@ -512,6 +512,7 @@ const idResolvers = {
512
512
  reaction: ({ referenceType, referenceId }) => `${referenceType}#${referenceId}`,
513
513
  reactor: ({ reactionId }) => reactionId,
514
514
  stream: ({ streamId }) => streamId,
515
+ streamModeration: ({ streamId }) => streamId,
515
516
  follow: ({ from, to }) => `${from}#${to}`,
516
517
  followInfo: ({ userId }) => userId,
517
518
  followCount: ({ userId }) => userId,
@@ -561,6 +562,7 @@ const PAYLOAD2MODEL = {
561
562
  reactors: 'reactor',
562
563
  reactions: 'reaction',
563
564
  videoStreamings: 'stream',
565
+ videoStreamModerations: 'streamModeration',
564
566
  follows: 'follow',
565
567
  followCounts: 'followCount',
566
568
  feeds: 'feed',
@@ -21340,6 +21342,13 @@ const storyLinkedObject = (story) => {
21340
21342
  } });
21341
21343
  };
21342
21344
 
21345
+ const streamLinkedObject = (stream) => {
21346
+ return Object.assign(Object.assign({}, stream), { get moderation() {
21347
+ var _a;
21348
+ return (_a = pullFromCache(['streamModeration', 'get', stream.streamId])) === null || _a === void 0 ? void 0 : _a.data;
21349
+ } });
21350
+ };
21351
+
21343
21352
  const categoryLinkedObject = (category) => {
21344
21353
  return Object.assign(Object.assign({}, category), { get avatar() {
21345
21354
  var _a;
@@ -21499,7 +21508,7 @@ const markAsReadBySegment = async ({ subChannelId, readToSegment, }) => {
21499
21508
  }
21500
21509
  };
21501
21510
 
21502
- const reCalculateChannelUnreadInfo = async (channelId) => {
21511
+ const reCalculateChannelUnreadInfo = (channelId) => {
21503
21512
  var _a;
21504
21513
  const cacheKeyChannelUnread = ['channelUnreadInfo', 'get', channelId];
21505
21514
  const cacheChannelUnreadInfo = (_a = pullFromCache(cacheKeyChannelUnread)) === null || _a === void 0 ? void 0 : _a.data;
@@ -21516,10 +21525,12 @@ const reCalculateChannelUnreadInfo = async (channelId) => {
21516
21525
  .reduce((acc, cur) => acc + cur, 0);
21517
21526
  isMentioned = subChannelUnreadsInfo.some(({ data }) => data.isMentioned);
21518
21527
  }
21519
- pushToCache(cacheKeyChannelUnread, Object.assign(Object.assign({}, (cacheChannelUnreadInfo !== null && cacheChannelUnreadInfo !== void 0 ? cacheChannelUnreadInfo : {
21528
+ const channelUnreadInfo = Object.assign(Object.assign({}, (cacheChannelUnreadInfo !== null && cacheChannelUnreadInfo !== void 0 ? cacheChannelUnreadInfo : {
21520
21529
  channelId,
21521
21530
  createdAt: new Date().toISOString(),
21522
- })), { updatedAt: new Date().toISOString(), unreadCount: channelUnreads, isMentioned }));
21531
+ })), { updatedAt: new Date().toISOString(), unreadCount: channelUnreads, isMentioned });
21532
+ pushToCache(cacheKeyChannelUnread, channelUnreadInfo);
21533
+ return channelUnreadInfo;
21523
21534
  };
21524
21535
 
21525
21536
  class MessageReadReceiptSyncEngine {
@@ -21664,9 +21675,11 @@ class MessageReadReceiptSyncEngine {
21664
21675
  if (subChannelUnreadInfo && segment > subChannelUnreadInfo.readToSegment) {
21665
21676
  subChannelUnreadInfo.readToSegment = segment;
21666
21677
  subChannelUnreadInfo.unreadCount = Math.max(subChannelUnreadInfo.lastSegment - segment, 0);
21667
- reCalculateChannelUnreadInfo(subChannelUnreadInfo.channelId);
21678
+ const channelUnreadInfo = reCalculateChannelUnreadInfo(subChannelUnreadInfo.channelId);
21679
+ fireEvent('local.channelUnread.updated', channelUnreadInfo);
21680
+ pushToCache(cacheKey, subChannelUnreadInfo);
21681
+ fireEvent('local.subChannelUnread.updated', subChannelUnreadInfo);
21668
21682
  }
21669
- pushToCache(cacheKey, subChannelUnreadInfo);
21670
21683
  // Step 2: Enqueue the read receipt
21671
21684
  this.enqueueReadReceipt(subChannelId, segment);
21672
21685
  }
@@ -21804,6 +21817,7 @@ const LinkedObject = {
21804
21817
  post: postLinkedObject,
21805
21818
  user: userLinkedObject,
21806
21819
  category: categoryLinkedObject,
21820
+ stream: streamLinkedObject,
21807
21821
  story: storyLinkedObject,
21808
21822
  storyTarget: storyTargetLinkedObject,
21809
21823
  message: messageLinkedObject,
@@ -24661,9 +24675,9 @@ const enableUnreadCount = () => {
24661
24675
  const onUserFeedMarkerUpdated = (callback) => {
24662
24676
  const client = getActiveClient();
24663
24677
  const filter = (payload) => {
24664
- // update sub channel unread info and channel unread info in cache
24665
- persistUnreadCountInfo(payload);
24666
- callback(payload.feedMarkers[0]);
24678
+ payload.feedMarkers.forEach(feedMarker => {
24679
+ callback(feedMarker);
24680
+ });
24667
24681
  };
24668
24682
  return createEventSubscriber(client, 'feedMarker/onUserFeedMarkerUpdated', 'marker.userFeed-updated', filter);
24669
24683
  };
@@ -25173,7 +25187,7 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
25173
25187
  */
25174
25188
  /**
25175
25189
  * ```js
25176
- * import { Client } from '@amityco/ts-sdk'
25190
+ * import { Client } from '@amityco/ts-sdk-react-native'
25177
25191
  * const success = await Client.secureLogout()
25178
25192
  * ```
25179
25193
  *
@@ -25259,7 +25273,7 @@ const onChannelMarkerFetched = (callback) => {
25259
25273
  const onSubChannelMarkerFetched = (callback) => {
25260
25274
  const client = getActiveClient();
25261
25275
  const filter = (payload) => {
25262
- callback(payload.userFeedMarkers[0]);
25276
+ payload.userFeedMarkers.forEach(callback);
25263
25277
  };
25264
25278
  return createEventSubscriber(client, 'subChannelMarker/onSubChannelMarkerFetched', 'local.subChannelMarker.fetched', filter);
25265
25279
  };
@@ -25529,6 +25543,9 @@ function isEqual(x, y) {
25529
25543
  }));
25530
25544
  }
25531
25545
 
25546
+ /**
25547
+ * @deprecated This function is deprecated
25548
+ */
25532
25549
  const liveObject = (id, callback, key, fetcher, eventHandlers, options) => {
25533
25550
  const { forceDispatch, callbackDataSelector, callbackFilter } = Object.assign({ forceDispatch: false, callbackDataSelector: (data) => data }, options);
25534
25551
  const { cache } = getActiveClient();
@@ -31514,7 +31531,7 @@ class LiveCollectionController {
31514
31531
  this.notifyChange({ origin: "server" /* Amity.LiveDataOrigin.SERVER */, loading: false, error: e });
31515
31532
  }
31516
31533
  }
31517
- loadPage(initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */) {
31534
+ loadPage({ initial = false, direction = "next" /* Amity.LiveCollectionPageDirection.NEXT */, }) {
31518
31535
  this.setup();
31519
31536
  this.notifyChange({ origin: "local" /* Amity.LiveDataOrigin.LOCAL */, loading: true });
31520
31537
  if (initial) {
@@ -31584,7 +31601,7 @@ class MessageLiveCollectionController extends LiveCollectionController {
31584
31601
  this.query = query;
31585
31602
  this.queryStreamController = new MessageQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareMessagePayload, this.paginationController);
31586
31603
  this.callback = callback.bind(this);
31587
- this.loadPage(true);
31604
+ this.loadPage({ initial: true });
31588
31605
  }
31589
31606
  setup() {
31590
31607
  var _a;
@@ -31632,8 +31649,8 @@ class MessageLiveCollectionController extends LiveCollectionController {
31632
31649
  if (!this.shouldNotify(data) && origin === 'event')
31633
31650
  return;
31634
31651
  this.callback({
31635
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
31636
- onPrevPage: () => this.loadPage(false, "prev" /* Amity.LiveCollectionPageDirection.PREV */),
31652
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
31653
+ onPrevPage: () => this.loadPage({ direction: "prev" /* Amity.LiveCollectionPageDirection.PREV */ }),
31637
31654
  data,
31638
31655
  hasNextPage: !!this.paginationController.getNextToken(),
31639
31656
  hasPrevPage: !!this.paginationController.getPrevToken(),
@@ -31915,6 +31932,24 @@ var index$f = /*#__PURE__*/Object.freeze({
31915
31932
  convertQueryParams: convertQueryParams$1
31916
31933
  });
31917
31934
 
31935
+ /**
31936
+ * Internal used only
31937
+ *
31938
+ * Fired when an {@link Amity.userMessageFeedMarkers} has been resolved by Object Rsesolver
31939
+ *
31940
+ * @param callback The function to call when the event was fired
31941
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
31942
+ *
31943
+ * @category MessageMarker Events
31944
+ */
31945
+ const onSubChannelUnreadUpdatedLocal = (callback) => {
31946
+ const client = getActiveClient();
31947
+ const filter = (payload) => {
31948
+ callback(payload);
31949
+ };
31950
+ return createEventSubscriber(client, 'subChannelMarker/onSubChannelUnreadUpdatedLocal', 'local.subChannelUnread.updated', filter);
31951
+ };
31952
+
31918
31953
  /* begin_public_function
31919
31954
  id: subchannel.get
31920
31955
  */
@@ -32067,7 +32102,7 @@ const getSubChannel = (subChannelId, callback) => {
32067
32102
  };
32068
32103
  return onMessageDeleted(updateMessagePreview);
32069
32104
  }, 'subChannelId', 'subChannel'),
32070
- convertEventPayload(onUserFeedMarkerUpdated, 'feedId', 'subChannel'),
32105
+ convertEventPayload(onSubChannelUnreadUpdatedLocal, 'subChannelId', 'subChannel'),
32071
32106
  ], {
32072
32107
  forceDispatch: true,
32073
32108
  });
@@ -32157,7 +32192,7 @@ class SubChannelLiveCollectionController extends LiveCollectionController {
32157
32192
  this.query = query;
32158
32193
  this.queryStreamController = new SubChannelQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareSubChannelPayload);
32159
32194
  this.callback = callback.bind(this);
32160
- this.loadPage(true);
32195
+ this.loadPage({ initial: true });
32161
32196
  }
32162
32197
  setup() {
32163
32198
  var _a;
@@ -32334,7 +32369,7 @@ class SubChannelLiveCollectionController extends LiveCollectionController {
32334
32369
  action: 'onUpdate',
32335
32370
  },
32336
32371
  {
32337
- fn: convertEventPayload(onUserFeedMarkerUpdated, 'feedId', 'subChannel'),
32372
+ fn: convertEventPayload(onSubChannelUnreadUpdatedLocal, 'subChannelId', 'subChannel'),
32338
32373
  action: 'onUpdate',
32339
32374
  },
32340
32375
  ]);
@@ -32352,7 +32387,7 @@ class SubChannelLiveCollectionController extends LiveCollectionController {
32352
32387
  if (!this.shouldNotify(data) && origin === 'event')
32353
32388
  return;
32354
32389
  this.callback({
32355
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
32390
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
32356
32391
  data,
32357
32392
  hasNextPage: !!this.paginationController.getNextToken(),
32358
32393
  loading,
@@ -32492,6 +32527,24 @@ var index$e = /*#__PURE__*/Object.freeze({
32492
32527
  stopMessageReceiptSync: stopMessageReceiptSync
32493
32528
  });
32494
32529
 
32530
+ /**
32531
+ * Internal used only
32532
+ *
32533
+ * Fired when an {@link Amity.userMessageFeedMarkers} has been resolved by Object Rsesolver
32534
+ *
32535
+ * @param callback The function to call when the event was fired
32536
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
32537
+ *
32538
+ * @category MessageMarker Events
32539
+ */
32540
+ const onChannelUnreadUpdatedLocal = (callback) => {
32541
+ const client = getActiveClient();
32542
+ const filter = (payload) => {
32543
+ callback(payload);
32544
+ };
32545
+ return createEventSubscriber(client, 'channelMarker/onChannelUnreadUpdatedLocal', 'local.channelUnread.updated', filter);
32546
+ };
32547
+
32495
32548
  /* begin_public_function
32496
32549
  id: channel.get
32497
32550
  */
@@ -32667,7 +32720,7 @@ const getChannel = (channelId, callback) => {
32667
32720
  return onSubChannelUpdated(updateMessagePreview);
32668
32721
  }, 'channelId', 'channel'),
32669
32722
  convertEventPayload(onSubChannelCreated, 'channelId', 'channel'),
32670
- convertEventPayload(onUserFeedMarkerUpdated, 'entityId', 'channel'),
32723
+ convertEventPayload(onChannelUnreadUpdatedLocal, 'channelId', 'channel'),
32671
32724
  ], {
32672
32725
  forceDispatch: true,
32673
32726
  });
@@ -32827,7 +32880,7 @@ class ChannelLiveCollectionController extends LiveCollectionController {
32827
32880
  }, paginationController);
32828
32881
  this.paginationController = paginationController;
32829
32882
  this.callback = callback.bind(this);
32830
- this.loadPage(true);
32883
+ this.loadPage({ initial: true });
32831
32884
  }
32832
32885
  setup() {
32833
32886
  var _a;
@@ -32866,7 +32919,7 @@ class ChannelLiveCollectionController extends LiveCollectionController {
32866
32919
  return;
32867
32920
  this.callback({
32868
32921
  onNextPage: this.paginationController instanceof ChannelPaginationController
32869
- ? () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */)
32922
+ ? () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ })
32870
32923
  : undefined,
32871
32924
  data,
32872
32925
  hasNextPage: this.paginationController instanceof ChannelPaginationController
@@ -33146,10 +33199,6 @@ class ChannelLiveCollectionController extends LiveCollectionController {
33146
33199
  }, 'channelId', 'channel'),
33147
33200
  action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
33148
33201
  },
33149
- {
33150
- fn: convertEventPayload(onUserFeedMarkerUpdated, 'entityId', 'channel'),
33151
- action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
33152
- },
33153
33202
  {
33154
33203
  fn: convertEventPayload(onSubChannelCreated, 'channelId', 'channel'),
33155
33204
  action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
@@ -33175,6 +33224,10 @@ class ChannelLiveCollectionController extends LiveCollectionController {
33175
33224
  },
33176
33225
  action: "onResolve" /* Amity.ChannelActionType.OnResolve */,
33177
33226
  },
33227
+ {
33228
+ fn: convertEventPayload(onChannelUnreadUpdatedLocal, 'channelId', 'channel'),
33229
+ action: "onUpdate" /* Amity.ChannelActionType.OnUpdate */,
33230
+ },
33178
33231
  ];
33179
33232
  if (this.paginationController instanceof PaginationController) {
33180
33233
  return [
@@ -33389,7 +33442,7 @@ class ChannelMemberLiveCollectionController extends LiveCollectionController {
33389
33442
  this.query = query;
33390
33443
  this.queryStreamController = new ChannelMemberQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareChannelPayload);
33391
33444
  this.callback = callback.bind(this);
33392
- this.loadPage(true);
33445
+ this.loadPage({ initial: true });
33393
33446
  }
33394
33447
  setup() {
33395
33448
  var _a;
@@ -33431,7 +33484,7 @@ class ChannelMemberLiveCollectionController extends LiveCollectionController {
33431
33484
  if (!this.shouldNotify(data) && origin === 'event')
33432
33485
  return;
33433
33486
  this.callback({
33434
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
33487
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
33435
33488
  data,
33436
33489
  hasNextPage: !!this.paginationController.getNextToken(),
33437
33490
  loading,
@@ -33567,7 +33620,7 @@ const getMembers$1 = (params, callback, config) => {
33567
33620
  *
33568
33621
  * @category Channel Live Collection
33569
33622
  */
33570
- const searchMembers = (params, callback, config) => {
33623
+ const searchMembers$1 = (params, callback, config) => {
33571
33624
  return getMembers$1(params, callback);
33572
33625
  };
33573
33626
  /* end_public_function */
@@ -33578,7 +33631,7 @@ var index$d = /*#__PURE__*/Object.freeze({
33578
33631
  removeMembers: removeMembers$1,
33579
33632
  applyFilter: applyFilter$1,
33580
33633
  getMembers: getMembers$1,
33581
- searchMembers: searchMembers
33634
+ searchMembers: searchMembers$1
33582
33635
  });
33583
33636
 
33584
33637
  /* begin_public_function
@@ -33821,12 +33874,30 @@ var index$b = /*#__PURE__*/Object.freeze({
33821
33874
  prepareChannelPayload: prepareChannelPayload
33822
33875
  });
33823
33876
 
33877
+ const saveCommunityUsers = (communities, communityUsers) => {
33878
+ if (communities.length === 0 || communityUsers.length === 0)
33879
+ return;
33880
+ communities.forEach(({ communityId }) => {
33881
+ const collection = communityUsers.filter(({ communityId: userCommunityId }) => communityId === userCommunityId);
33882
+ pushToCache(['communityUsers', 'collection', communityId], collection);
33883
+ });
33884
+ };
33885
+
33824
33886
  const getMatchPostSetting = (value) => {
33825
33887
  var _a;
33826
33888
  return (_a = Object.keys(CommunityPostSettingMaps).find(key => value.needApprovalOnPostCreation ===
33827
33889
  CommunityPostSettingMaps[key].needApprovalOnPostCreation &&
33828
33890
  value.onlyAdminCanPost === CommunityPostSettingMaps[key].onlyAdminCanPost)) !== null && _a !== void 0 ? _a : DefaultCommunityPostSetting;
33829
33891
  };
33892
+ const convertCommunityUsersToUniqueObject = (communityUsers) => {
33893
+ if (!communityUsers)
33894
+ return communityUsers;
33895
+ const result = {};
33896
+ communityUsers.forEach(user => {
33897
+ result[user.userId] = user;
33898
+ });
33899
+ return result;
33900
+ };
33830
33901
  const prepareCommunityPayload = (rawPayload) => {
33831
33902
  // Unpack community payload by mapping payload field to postSetting value.
33832
33903
  const communities = rawPayload.communities.map((_a) => {
@@ -33836,7 +33907,18 @@ const prepareCommunityPayload = (rawPayload) => {
33836
33907
  onlyAdminCanPost,
33837
33908
  }) }, restCommunityPayload));
33838
33909
  });
33839
- const communityUsers = withUsers(rawPayload.communityUsers);
33910
+ const mergeCommunityUsers = communities.reduce((acc, { communityId }) => {
33911
+ var _a;
33912
+ const users = (_a = pullFromCache([
33913
+ 'communityUsers',
33914
+ 'collection',
33915
+ communityId,
33916
+ ])) === null || _a === void 0 ? void 0 : _a.data;
33917
+ if (!users)
33918
+ return acc;
33919
+ return Object.assign(Object.assign({}, convertCommunityUsersToUniqueObject(users)), acc);
33920
+ }, convertCommunityUsersToUniqueObject(rawPayload.communityUsers));
33921
+ const communityUsers = withUsers(Object.values(mergeCommunityUsers));
33840
33922
  const communityWithMembershipStatus = updateMembershipStatus(communities, communityUsers);
33841
33923
  return Object.assign(Object.assign({}, rawPayload), { communities: communityWithMembershipStatus, communityUsers });
33842
33924
  };
@@ -33870,8 +33952,10 @@ const getCommunities$1 = async (communityIds) => {
33870
33952
  });
33871
33953
  const data = prepareCommunityPayload(payload);
33872
33954
  const cachedAt = client.cache && Date.now();
33873
- if (client.cache)
33955
+ if (client.cache) {
33874
33956
  ingestInCache(data, { cachedAt });
33957
+ saveCommunityUsers(data.communities, data.communityUsers);
33958
+ }
33875
33959
  return {
33876
33960
  data: data.communities,
33877
33961
  cachedAt,
@@ -33933,8 +34017,10 @@ const createCommunity = async (bundle) => {
33933
34017
  fireEvent('community.created', payload);
33934
34018
  const data = prepareCommunityPayload(payload);
33935
34019
  const cachedAt = client.cache && Date.now();
33936
- if (client.cache)
34020
+ if (client.cache) {
33937
34021
  ingestInCache(data, { cachedAt });
34022
+ saveCommunityUsers(data.communities, data.communityUsers);
34023
+ }
33938
34024
  const { communities } = data;
33939
34025
  return {
33940
34026
  data: communities[0],
@@ -33968,8 +34054,10 @@ const updateCommunity = async (communityId, patch) => {
33968
34054
  fireEvent('community.updated', payload);
33969
34055
  const data = prepareCommunityPayload(payload);
33970
34056
  const cachedAt = client.cache && Date.now();
33971
- if (client.cache)
34057
+ if (client.cache) {
33972
34058
  ingestInCache(data, { cachedAt });
34059
+ saveCommunityUsers(data.communities, data.communityUsers);
34060
+ }
33973
34061
  const { communities } = data;
33974
34062
  return {
33975
34063
  data: communities.find(community => community.communityId === communityId),
@@ -33999,8 +34087,10 @@ const getCommunity$1 = async (communityId) => {
33999
34087
  const { data: payload } = await client.http.get(`/api/v3/communities/${communityId}`);
34000
34088
  const data = prepareCommunityPayload(payload);
34001
34089
  const cachedAt = client.cache && Date.now();
34002
- if (client.cache)
34090
+ if (client.cache) {
34003
34091
  ingestInCache(data, { cachedAt });
34092
+ saveCommunityUsers(data.communities, data.communityUsers);
34093
+ }
34004
34094
  const { communities } = data;
34005
34095
  return {
34006
34096
  data: communities.find(community => community.communityId === communityId),
@@ -34539,51 +34629,339 @@ const observeCommunity = (communityId, callback) => {
34539
34629
  };
34540
34630
  };
34541
34631
 
34632
+ /**
34633
+ * TODO: handle cache receive cache option, and cache policy
34634
+ * TODO: check if querybyIds is supported
34635
+ */
34636
+ class CommunitiesPaginationController$1 extends PaginationController {
34637
+ async getRequest(queryParams, token) {
34638
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
34639
+ const options = token ? { token } : { limit };
34640
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
34641
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
34642
+ });
34643
+ return queryResponse;
34644
+ }
34645
+ }
34646
+
34647
+ class CommunitiesQueryStreamController$1 extends QueryStreamController {
34648
+ constructor(query, cacheKey, notifyChange, preparePayload) {
34649
+ super(query, cacheKey);
34650
+ this.notifyChange = notifyChange;
34651
+ this.preparePayload = preparePayload;
34652
+ }
34653
+ async saveToMainDB(response) {
34654
+ const processedPayload = await this.preparePayload(response);
34655
+ const client = getActiveClient();
34656
+ const cachedAt = client.cache && Date.now();
34657
+ if (client.cache) {
34658
+ ingestInCache(processedPayload, { cachedAt });
34659
+ }
34660
+ }
34661
+ appendToQueryStream(response, direction, refresh = false) {
34662
+ var _a, _b;
34663
+ if (refresh) {
34664
+ pushToCache(this.cacheKey, {
34665
+ data: response.communities.map(getResolver('community')),
34666
+ });
34667
+ }
34668
+ else {
34669
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34670
+ const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
34671
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...communities, ...response.communities.map(getResolver('community'))])] }));
34672
+ }
34673
+ }
34674
+ reactor(action) {
34675
+ return (community) => {
34676
+ var _a;
34677
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34678
+ if (!collection)
34679
+ return;
34680
+ pushToCache(this.cacheKey, collection);
34681
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
34682
+ };
34683
+ }
34684
+ subscribeRTE(createSubscriber) {
34685
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
34686
+ }
34687
+ }
34688
+
34689
+ var EnumCommunityActions$1;
34690
+ (function (EnumCommunityActions) {
34691
+ EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
34692
+ EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
34693
+ EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
34694
+ })(EnumCommunityActions$1 || (EnumCommunityActions$1 = {}));
34695
+
34696
+ /* eslint-disable no-use-before-define */
34697
+ class SearchCommunityLiveCollectionController extends LiveCollectionController {
34698
+ constructor(query, callback) {
34699
+ const queryStreamId = hash(query);
34700
+ const cacheKey = ['community', 'collection', queryStreamId];
34701
+ const paginationController = new CommunitiesPaginationController$1(query);
34702
+ super(paginationController, queryStreamId, cacheKey, callback);
34703
+ this.query = query;
34704
+ this.queryStreamController = new CommunitiesQueryStreamController$1(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
34705
+ this.callback = callback.bind(this);
34706
+ this.loadPage({ initial: true });
34707
+ }
34708
+ setup() {
34709
+ var _a;
34710
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34711
+ if (!collection) {
34712
+ pushToCache(this.cacheKey, {
34713
+ data: [],
34714
+ params: {},
34715
+ });
34716
+ }
34717
+ }
34718
+ async persistModel(queryPayload) {
34719
+ await this.queryStreamController.saveToMainDB(queryPayload);
34720
+ }
34721
+ persistQueryStream({ response, direction, refresh, }) {
34722
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
34723
+ }
34724
+ startSubscription() {
34725
+ return this.queryStreamController.subscribeRTE([
34726
+ { fn: onCommunityDeleted, action: EnumCommunityActions$1.OnCommunityDeleted },
34727
+ { fn: onCommunityUpdated, action: EnumCommunityActions$1.OnCommunityUpdated },
34728
+ ]);
34729
+ }
34730
+ notifyChange({ origin, loading, error }) {
34731
+ var _a, _b;
34732
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34733
+ if (!collection)
34734
+ return;
34735
+ const data = this.applyFilter((_b = collection.data
34736
+ .map(id => pullFromCache(['community', 'get', id]))
34737
+ .filter(Boolean)
34738
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
34739
+ if (!this.shouldNotify(data) && origin === 'event')
34740
+ return;
34741
+ this.callback({
34742
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
34743
+ data,
34744
+ hasNextPage: !!this.paginationController.getNextToken(),
34745
+ loading,
34746
+ error,
34747
+ });
34748
+ }
34749
+ applyFilter(data) {
34750
+ const { userId } = getActiveClient();
34751
+ let communities = data;
34752
+ if (this.query.includeDeleted) {
34753
+ communities = filterByPropEquality(communities, 'isDeleted', false);
34754
+ }
34755
+ if (this.query.categoryId) {
34756
+ communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(this.query.categoryId); });
34757
+ }
34758
+ if (this.query.tags) {
34759
+ communities = communities.filter(c => { var _a; return (_a = c.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = this.query.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
34760
+ }
34761
+ if (this.query.membership && userId) {
34762
+ communities = filterByCommunityMembership(communities, this.query.membership, userId);
34763
+ }
34764
+ return communities;
34765
+ }
34766
+ }
34767
+
34768
+ /* begin_public_function
34769
+ id: community.query
34770
+ */
34542
34771
  /**
34543
34772
  * ```js
34544
- * import { queryCommunities } from '@amityco/ts-sdk-react-native'
34545
- * const communities = await queryCommunities()
34773
+ * import { CommunityRepository } from '@amityco/ts-sdk-react-native'
34774
+ *
34775
+ * let communities = []
34776
+ * const unsub = CommunityRepository.searchCommunities({
34777
+ * displayName: Amity.Community['displayName'],
34778
+ * }, response => merge(communities, response.data))
34546
34779
  * ```
34547
34780
  *
34548
- * Queries a paginable list of {@link Amity.Community} objects
34549
- * Search is performed by displayName such as `.startsWith(search)`
34781
+ * Observe all mutations on a list of {@link Amity.Community}s
34550
34782
  *
34551
- * @param query The query parameters
34552
- * @returns A page of {@link Amity.Community} objects
34783
+ * @param params for querying communities
34784
+ * @param callback the function to call when new data are available
34785
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the communities
34553
34786
  *
34554
- * @category Community API
34555
- * @async
34787
+ * @category Community Live Collection
34556
34788
  */
34557
- const queryCommunities = async (query) => {
34558
- const client = getActiveClient();
34559
- client.log('channel/queryCommunities', query);
34560
- // safe decapsulation
34561
- const _a = query !== null && query !== void 0 ? query : {}, { page, limit = 10 } = _a, params = __rest(_a, ["page", "limit"]);
34562
- const _b = params !== null && params !== void 0 ? params : {}, { displayName, membership, includeDeleted } = _b, restParams = __rest(_b, ["displayName", "membership", "includeDeleted"]);
34563
- const options = (() => {
34564
- if (page)
34565
- return { token: page };
34566
- if (limit)
34567
- return { limit };
34568
- return undefined;
34569
- })();
34570
- // API-FIX: parameters should be querystring.
34571
- // API-FIX: backend doesn't answer Amity.Response
34572
- // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<CommunityPayload>>>(
34573
- const { data } = await client.http.get(`/api/v3/communities`, {
34574
- params: Object.assign(Object.assign({}, restParams), { isDeleted: inferIsDeleted(includeDeleted), keyword: displayName, filter: membership, options }),
34575
- });
34576
- const { paging } = data, payload = __rest(data, ["paging"]);
34577
- const unpackedPayload = prepareCommunityPayload(payload);
34578
- const { communities } = unpackedPayload;
34579
- const cachedAt = client.cache && Date.now();
34580
- if (client.cache) {
34581
- ingestInCache(unpackedPayload, { cachedAt });
34582
- const cacheKey = ['community', 'query', Object.assign(Object.assign({}, params), { options })];
34583
- pushToCache(cacheKey, { communities: communities.map(getResolver('community')), paging });
34789
+ const searchCommunities = (params, callback, config) => {
34790
+ const { log, cache } = getActiveClient();
34791
+ if (!cache) {
34792
+ console.log(ENABLE_CACHE_MESSAGE);
34584
34793
  }
34585
- return { data: communities, cachedAt, paging };
34586
- };
34794
+ const timestamp = Date.now();
34795
+ log(`searchCommunities(tmpid: ${timestamp}) > listen`);
34796
+ const searchCommunitiesLiveCollection = new SearchCommunityLiveCollectionController(params, callback);
34797
+ const disposers = searchCommunitiesLiveCollection.startSubscription();
34798
+ const cacheKey = searchCommunitiesLiveCollection.getCacheKey();
34799
+ disposers.push(() => dropFromCache(cacheKey));
34800
+ return () => {
34801
+ log(`searchCommunities(tmpid: ${timestamp}) > dispose`);
34802
+ disposers.forEach(fn => fn());
34803
+ };
34804
+ };
34805
+ /* end_public_function */
34806
+
34807
+ /**
34808
+ * TODO: handle cache receive cache option, and cache policy
34809
+ * TODO: check if querybyIds is supported
34810
+ */
34811
+ class CommunitiesPaginationController extends PaginationController {
34812
+ async getRequest(queryParams, token) {
34813
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
34814
+ const options = token ? { token } : { limit };
34815
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities`, {
34816
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(params.includeDeleted), keyword: params.displayName, filter: params.membership, options }),
34817
+ });
34818
+ return queryResponse;
34819
+ }
34820
+ }
34821
+
34822
+ var EnumCommunityActions;
34823
+ (function (EnumCommunityActions) {
34824
+ EnumCommunityActions["OnCommunityCreated"] = "onCommunityCreated";
34825
+ EnumCommunityActions["OnCommunityDeleted"] = "onCommunityDeleted";
34826
+ EnumCommunityActions["OnCommunityUpdated"] = "onCommunityUpdated";
34827
+ })(EnumCommunityActions || (EnumCommunityActions = {}));
34828
+
34829
+ class CommunitiesQueryStreamController extends QueryStreamController {
34830
+ constructor(query, cacheKey, notifyChange, preparePayload) {
34831
+ super(query, cacheKey);
34832
+ this.notifyChange = notifyChange;
34833
+ this.preparePayload = preparePayload;
34834
+ }
34835
+ async saveToMainDB(response) {
34836
+ const processedPayload = await this.preparePayload(response);
34837
+ const client = getActiveClient();
34838
+ const cachedAt = client.cache && Date.now();
34839
+ if (client.cache) {
34840
+ ingestInCache(processedPayload, { cachedAt });
34841
+ }
34842
+ }
34843
+ appendToQueryStream(response, direction, refresh = false) {
34844
+ var _a, _b;
34845
+ if (refresh) {
34846
+ pushToCache(this.cacheKey, {
34847
+ data: response.communities.map(getResolver('community')),
34848
+ });
34849
+ }
34850
+ else {
34851
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34852
+ const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
34853
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...communities, ...response.communities.map(getResolver('community'))])] }));
34854
+ }
34855
+ }
34856
+ reactor(action) {
34857
+ return (community) => {
34858
+ var _a;
34859
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34860
+ if (!collection)
34861
+ return;
34862
+ if (this.query.displayName && action === EnumCommunityActions.OnCommunityCreated) {
34863
+ return;
34864
+ }
34865
+ /*
34866
+ * Simply update collection and let responder decide what to do with data
34867
+ */
34868
+ collection.data = [...new Set([community.communityId, ...collection.data])];
34869
+ pushToCache(this.cacheKey, collection);
34870
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
34871
+ };
34872
+ }
34873
+ subscribeRTE(createSubscriber) {
34874
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
34875
+ }
34876
+ }
34877
+
34878
+ /* eslint-disable no-use-before-define */
34879
+ class CommunityLiveCollectionController extends LiveCollectionController {
34880
+ constructor(query, callback) {
34881
+ const queryStreamId = hash(query);
34882
+ const cacheKey = ['community', 'collection', queryStreamId];
34883
+ const paginationController = new CommunitiesPaginationController(query);
34884
+ super(paginationController, queryStreamId, cacheKey, callback);
34885
+ this.query = query;
34886
+ this.queryStreamController = new CommunitiesQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
34887
+ this.callback = callback.bind(this);
34888
+ this.loadPage({ initial: true });
34889
+ }
34890
+ setup() {
34891
+ var _a;
34892
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34893
+ if (!collection) {
34894
+ pushToCache(this.cacheKey, {
34895
+ data: [],
34896
+ params: {},
34897
+ });
34898
+ }
34899
+ }
34900
+ async persistModel(queryPayload) {
34901
+ await this.queryStreamController.saveToMainDB(queryPayload);
34902
+ }
34903
+ persistQueryStream({ response, direction, refresh, }) {
34904
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
34905
+ }
34906
+ startSubscription() {
34907
+ return this.queryStreamController.subscribeRTE([
34908
+ { fn: onCommunityCreated, action: EnumCommunityActions.OnCommunityCreated },
34909
+ { fn: onCommunityDeleted, action: EnumCommunityActions.OnCommunityDeleted },
34910
+ { fn: onCommunityUpdated, action: EnumCommunityActions.OnCommunityUpdated },
34911
+ ]);
34912
+ }
34913
+ notifyChange({ origin, loading, error }) {
34914
+ var _a, _b;
34915
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34916
+ if (!collection)
34917
+ return;
34918
+ const data = this.applyFilter((_b = collection.data
34919
+ .map(id => pullFromCache(['community', 'get', id]))
34920
+ .filter(Boolean)
34921
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
34922
+ if (!this.shouldNotify(data) && origin === 'event')
34923
+ return;
34924
+ this.callback({
34925
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
34926
+ data,
34927
+ hasNextPage: !!this.paginationController.getNextToken(),
34928
+ loading,
34929
+ error,
34930
+ });
34931
+ }
34932
+ applyFilter(data) {
34933
+ const { userId } = getActiveClient();
34934
+ let communities = data;
34935
+ if (this.query.includeDeleted) {
34936
+ communities = filterByPropEquality(communities, 'isDeleted', false);
34937
+ }
34938
+ if (this.query.categoryId) {
34939
+ communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(this.query.categoryId); });
34940
+ }
34941
+ if (this.query.tags) {
34942
+ communities = communities.filter(c => { var _a; return (_a = c.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = this.query.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
34943
+ }
34944
+ if (this.query.membership && userId) {
34945
+ communities = filterByCommunityMembership(communities, this.query.membership, userId);
34946
+ }
34947
+ if (!this.query.displayName) {
34948
+ const sortFn = (() => {
34949
+ switch (this.query.sortBy) {
34950
+ case 'firstCreated':
34951
+ return sortByFirstCreated;
34952
+ case 'lastCreated':
34953
+ return sortByLastCreated;
34954
+ case 'displayName':
34955
+ return sortByDisplayName;
34956
+ default:
34957
+ return sortByLastCreated;
34958
+ }
34959
+ })();
34960
+ communities = communities.sort(sortFn);
34961
+ }
34962
+ return communities;
34963
+ }
34964
+ }
34587
34965
 
34588
34966
  /* begin_public_function
34589
34967
  id: community.query
@@ -34607,98 +34985,15 @@ const queryCommunities = async (query) => {
34607
34985
  * @category Community Live Collection
34608
34986
  */
34609
34987
  const getCommunities = (params, callback, config) => {
34610
- const { log, cache, userId } = getActiveClient();
34988
+ const { log, cache } = getActiveClient();
34611
34989
  if (!cache) {
34612
34990
  console.log(ENABLE_CACHE_MESSAGE);
34613
34991
  }
34614
34992
  const timestamp = Date.now();
34615
34993
  log(`getCommunities(tmpid: ${timestamp}) > listen`);
34616
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
34617
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
34618
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
34619
- const disposers = [];
34620
- const cacheKey = ['community', 'collection', queryParams];
34621
- const responder = (data) => {
34622
- var _a, _b;
34623
- let communities = (_a = data.data
34624
- .map(communityId => pullFromCache(['community', 'get', communityId]))
34625
- .filter(Boolean)
34626
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
34627
- communities = filterByStringComparePartially(communities, 'displayName', params.displayName);
34628
- if (!params.includeDeleted) {
34629
- communities = filterByPropEquality(communities, 'isDeleted', false);
34630
- }
34631
- if (params.categoryId) {
34632
- communities = communities.filter(c => { var _a; return (_a = c.categoryIds) === null || _a === void 0 ? void 0 : _a.includes(params.categoryId); });
34633
- }
34634
- if (params.tags) {
34635
- communities = communities.filter(c => { var _a; return (_a = c.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = params.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
34636
- }
34637
- if (params.membership && userId) {
34638
- communities = filterByCommunityMembership(communities, params.membership, userId);
34639
- }
34640
- const sortBy = params.sortBy || 'lastCreated';
34641
- if (sortBy === 'lastCreated' || sortBy === 'firstCreated') {
34642
- communities = communities.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
34643
- }
34644
- /*
34645
- * The server returns communities with empty | null displayName's first before
34646
- * returning sorted list of communities with displayNames
34647
- *
34648
- * This section needs to be updated as displayNames can be null as well
34649
- */
34650
- if (sortBy === 'displayName') {
34651
- communities = communities
34652
- // this needs to be aligned with the backend data type
34653
- .map(c => (c.displayName ? c : Object.assign(Object.assign({}, c), { displayName: '' })))
34654
- // @ts-ignore
34655
- .sort(sortByDisplayName);
34656
- }
34657
- callback({
34658
- onNextPage: onFetch,
34659
- data: communities,
34660
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
34661
- loading: data.loading,
34662
- error: data.error,
34663
- });
34664
- };
34665
- const realtimeRouter = (_) => (community) => {
34666
- var _a;
34667
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34668
- if (!collection)
34669
- return;
34670
- /*
34671
- * Simply update collection and let responder decide what to do with data
34672
- */
34673
- collection.data = [...new Set([community.communityId, ...collection.data])];
34674
- pushToCache(cacheKey, collection);
34675
- responder(collection);
34676
- };
34677
- const onFetch = (initial = false) => {
34678
- var _a, _b;
34679
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
34680
- const communities = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
34681
- if (!initial && communities.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
34682
- return;
34683
- const query = createQuery(queryCommunities, Object.assign(Object.assign({}, queryParams), { limit: initial ? limit : undefined, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
34684
- runQuery(query, ({ data: result, error, loading, paging }) => {
34685
- const data = {
34686
- loading,
34687
- error,
34688
- params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
34689
- data: communities,
34690
- };
34691
- if (result) {
34692
- data.data = initial
34693
- ? result.map(getResolver('community'))
34694
- : [...new Set([...communities, ...result.map(getResolver('community'))])];
34695
- }
34696
- pushToCache(cacheKey, data);
34697
- responder(data);
34698
- }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
34699
- };
34700
- disposers.push(onCommunityCreated(realtimeRouter()), onCommunityDeleted(realtimeRouter()), onCommunityUpdated(realtimeRouter()), onCommunityJoined(realtimeRouter()), onCommunityLeft(realtimeRouter()), onCommunityUserChanged(realtimeRouter()));
34701
- onFetch(true);
34994
+ const communitiesLiveCollection = new CommunityLiveCollectionController(params, callback);
34995
+ const disposers = communitiesLiveCollection.startSubscription();
34996
+ const cacheKey = communitiesLiveCollection.getCacheKey();
34702
34997
  disposers.push(() => dropFromCache(cacheKey));
34703
34998
  return () => {
34704
34999
  log(`getCommunities(tmpid: ${timestamp}) > dispose`);
@@ -35227,87 +35522,187 @@ const removeMembers = async (communityId, userIds) => {
35227
35522
  /* end_public_function */
35228
35523
 
35229
35524
  /**
35230
- * ```js
35231
- * import { queryCommunityMembers } from '@amityco/ts-sdk-react-native'
35232
- * const communityMembers = await queryCommunityMembers({ communityId: 'foo' })
35233
- * ```
35234
- *
35235
- * Queries a paginable list of {@link Amity.CommunityUser} objects
35236
- *
35237
- * @param query The query parameters
35238
- * @returns A page of {@link Amity.CommunityUser} objects
35239
- *
35240
- * @category Community API
35241
- * @async
35242
- * */
35243
- const queryCommunityMembers = async (query) => {
35244
- const client = getActiveClient();
35245
- client.log('community/queryCommunityMembers', query);
35246
- const _a = query !== null && query !== void 0 ? query : {}, { page, limit } = _a, params = __rest(_a, ["page", "limit"]);
35247
- const options = (() => {
35248
- if (page)
35249
- return { token: page };
35250
- if (limit)
35251
- return { limit };
35252
- return undefined;
35253
- })();
35254
- const { data: queryPayload } = await client.http.get(`/api/v3/communities/${params.communityId}/users`, {
35255
- params: Object.assign(Object.assign({}, params), { options }),
35256
- });
35257
- const { paging } = queryPayload, payload = __rest(queryPayload, ["paging"]);
35258
- const preparedPayload = prepareMembershipPayload(payload, 'communityUsers');
35259
- const { communityUsers } = preparedPayload;
35260
- const cachedAt = client.cache && Date.now();
35261
- if (client.cache) {
35262
- ingestInCache(preparedPayload, { cachedAt });
35263
- const cacheKey = ['communityUsers', 'query', Object.assign(Object.assign({}, params), { options })];
35264
- pushToCache(cacheKey, {
35265
- communityUsers: communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
35266
- paging,
35525
+ * TODO: handle cache receive cache option, and cache policy
35526
+ * TODO: check if querybyIds is supported
35527
+ */
35528
+ class CommunityMembersPaginationController extends PaginationController {
35529
+ async getRequest(queryParams, token) {
35530
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
35531
+ const options = token ? { token } : { limit };
35532
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities/${params.communityId}/users`, {
35533
+ params: Object.assign(Object.assign({}, params), { options }),
35267
35534
  });
35535
+ return queryResponse;
35268
35536
  }
35269
- return { data: communityUsers, cachedAt, paging };
35270
- };
35271
- /**
35272
- * ```js
35273
- * import { queryCommunityMembers } from '@amityco/ts-sdk-react-native'
35274
- * const communityMembers = await queryCommunityMembers(query)
35275
- * ```
35276
- *
35277
- * Queries a paginable list of {@link Amity.InternalPost} objects from cache
35278
- *
35279
- * @param query The query parameters
35280
- * @returns posts
35281
- *
35282
- * @category Post API
35283
- */
35284
- queryCommunityMembers.locally = (query) => {
35285
- var _a, _b;
35286
- const client = getActiveClient();
35287
- client.log('community/queryCommunityMembers', query);
35288
- if (!client.cache)
35289
- return;
35290
- const _c = query !== null && query !== void 0 ? query : {}, { page, limit } = _c, params = __rest(_c, ["page", "limit"]);
35291
- const options = (() => {
35292
- if (page)
35293
- return { token: page };
35294
- if (limit)
35295
- return { limit };
35296
- return undefined;
35297
- })();
35298
- const cacheKey = ['communityUsers', 'query', Object.assign(Object.assign({}, params), { options })];
35299
- const { data, cachedAt } = (_a = pullFromCache(cacheKey)) !== null && _a !== void 0 ? _a : {};
35300
- if (!(data === null || data === void 0 ? void 0 : data.communityUsers.length))
35301
- return;
35302
- const communityUsers = data.communityUsers
35303
- .map(key => pullFromCache(['communityUsers', 'get', key]))
35304
- .filter(Boolean)
35305
- .map(({ data }) => data);
35306
- const { paging } = data;
35307
- return communityUsers.length === ((_b = data === null || data === void 0 ? void 0 : data.communityUsers) === null || _b === void 0 ? void 0 : _b.length)
35308
- ? { data: communityUsers, cachedAt, paging }
35309
- : undefined;
35310
- };
35537
+ }
35538
+
35539
+ var EnumCommunityMemberActions$1;
35540
+ (function (EnumCommunityMemberActions) {
35541
+ EnumCommunityMemberActions["OnCommunityJoined"] = "onCommunityJoined";
35542
+ EnumCommunityMemberActions["OnCommunityLeft"] = "onCommunityLeft";
35543
+ EnumCommunityMemberActions["OnCommunityUserBanned"] = "onCommunityUserBanned";
35544
+ EnumCommunityMemberActions["OnCommunityUserChanged"] = "onCommunityUserChanged";
35545
+ EnumCommunityMemberActions["OnCommunityUserRoleAdded"] = "onCommunityUserRoleAdded";
35546
+ EnumCommunityMemberActions["OnCommunityUserRoleRemoved"] = "onCommunityUserRoleRemoved";
35547
+ EnumCommunityMemberActions["OnCommunityUserUnbanned"] = "onCommunityUserUnbanned";
35548
+ })(EnumCommunityMemberActions$1 || (EnumCommunityMemberActions$1 = {}));
35549
+
35550
+ class CommunityMembersQueryStreamController extends QueryStreamController {
35551
+ constructor(query, cacheKey, notifyChange, preparePayload) {
35552
+ super(query, cacheKey);
35553
+ this.notifyChange = notifyChange;
35554
+ this.preparePayload = preparePayload;
35555
+ }
35556
+ async saveToMainDB(response) {
35557
+ const processedPayload = await this.preparePayload(response);
35558
+ const client = getActiveClient();
35559
+ const cachedAt = client.cache && Date.now();
35560
+ if (client.cache) {
35561
+ ingestInCache(processedPayload, { cachedAt });
35562
+ }
35563
+ }
35564
+ appendToQueryStream(response, direction, refresh = false) {
35565
+ var _a, _b;
35566
+ if (refresh) {
35567
+ pushToCache(this.cacheKey, {
35568
+ data: response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
35569
+ });
35570
+ }
35571
+ else {
35572
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35573
+ const communityUsers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
35574
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
35575
+ ...new Set([
35576
+ ...communityUsers,
35577
+ ...response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
35578
+ ]),
35579
+ ] }));
35580
+ }
35581
+ }
35582
+ reactor(action) {
35583
+ return (community, communityMembers) => {
35584
+ var _a;
35585
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35586
+ if (!collection)
35587
+ return;
35588
+ if (action === EnumCommunityMemberActions$1.OnCommunityUserRoleAdded &&
35589
+ this.query.sortBy === 'displayName') {
35590
+ return;
35591
+ }
35592
+ communityMembers.forEach(communityMember => {
35593
+ const communityMemberCacheId = getResolver('communityUsers')({
35594
+ communityId: this.query.communityId,
35595
+ userId: communityMember.userId,
35596
+ });
35597
+ if (communityMember.communityMembership === 'none') {
35598
+ collection.data = collection.data.filter(m => m !== communityMemberCacheId);
35599
+ }
35600
+ else if (!collection.data.includes(communityMemberCacheId)) {
35601
+ collection.data = [communityMemberCacheId, ...collection.data];
35602
+ }
35603
+ });
35604
+ pushToCache(this.cacheKey, collection);
35605
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
35606
+ };
35607
+ }
35608
+ subscribeRTE(createSubscriber) {
35609
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
35610
+ }
35611
+ }
35612
+
35613
+ /* eslint-disable no-use-before-define */
35614
+ class CommunityMembersLiveCollectionController extends LiveCollectionController {
35615
+ constructor(query, callback) {
35616
+ const queryStreamId = hash(query);
35617
+ const cacheKey = ['communityUsers', 'collection', queryStreamId];
35618
+ const paginationController = new CommunityMembersPaginationController(query);
35619
+ super(paginationController, queryStreamId, cacheKey, callback);
35620
+ this.query = query;
35621
+ this.queryStreamController = new CommunityMembersQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
35622
+ this.callback = callback.bind(this);
35623
+ this.loadPage({ initial: true });
35624
+ }
35625
+ setup() {
35626
+ var _a;
35627
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35628
+ if (!collection) {
35629
+ pushToCache(this.cacheKey, {
35630
+ data: [],
35631
+ params: {},
35632
+ });
35633
+ }
35634
+ }
35635
+ async persistModel(queryPayload) {
35636
+ await this.queryStreamController.saveToMainDB(queryPayload);
35637
+ }
35638
+ persistQueryStream({ response, direction, refresh, }) {
35639
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
35640
+ }
35641
+ startSubscription() {
35642
+ return this.queryStreamController.subscribeRTE([
35643
+ { fn: onCommunityJoined, action: EnumCommunityMemberActions$1.OnCommunityJoined },
35644
+ { fn: onCommunityLeft, action: EnumCommunityMemberActions$1.OnCommunityLeft },
35645
+ { fn: onCommunityUserBanned, action: EnumCommunityMemberActions$1.OnCommunityUserBanned },
35646
+ { fn: onCommunityUserChanged, action: EnumCommunityMemberActions$1.OnCommunityUserChanged },
35647
+ { fn: onCommunityUserRoleAdded, action: EnumCommunityMemberActions$1.OnCommunityUserRoleAdded },
35648
+ {
35649
+ fn: onCommunityUserRoleRemoved,
35650
+ action: EnumCommunityMemberActions$1.OnCommunityUserRoleRemoved,
35651
+ },
35652
+ { fn: onCommunityUserUnbanned, action: EnumCommunityMemberActions$1.OnCommunityUserUnbanned },
35653
+ ]);
35654
+ }
35655
+ notifyChange({ origin, loading, error }) {
35656
+ var _a, _b;
35657
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35658
+ if (!collection)
35659
+ return;
35660
+ const data = this.applyFilter((_b = collection.data
35661
+ .map(id => pullFromCache(['communityUsers', 'get', id]))
35662
+ .filter(isNonNullable)
35663
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
35664
+ if (!this.shouldNotify(data) && origin === 'event')
35665
+ return;
35666
+ this.callback({
35667
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
35668
+ data,
35669
+ hasNextPage: !!this.paginationController.getNextToken(),
35670
+ loading,
35671
+ error,
35672
+ });
35673
+ }
35674
+ applyFilter(data) {
35675
+ let communityMembers = filterByPropIntersection(data, 'roles', this.query.roles);
35676
+ if (this.query.memberships) {
35677
+ communityMembers = communityMembers.filter(({ communityMembership }) => {
35678
+ const memberships = this.query.memberships || [];
35679
+ return memberships.includes(communityMembership);
35680
+ });
35681
+ }
35682
+ if (this.query.search) {
35683
+ communityMembers = filterBySearchTerm(communityMembers, this.query.search);
35684
+ }
35685
+ switch (this.query.sortBy) {
35686
+ case 'firstCreated':
35687
+ communityMembers = communityMembers.sort(sortByFirstCreated);
35688
+ break;
35689
+ case 'displayName':
35690
+ communityMembers = communityMembers.sort((a, b) => {
35691
+ var _a, _b, _c, _d;
35692
+ if (((_a = a === null || a === void 0 ? void 0 : a.user) === null || _a === void 0 ? void 0 : _a.displayName) && ((_b = b === null || b === void 0 ? void 0 : b.user) === null || _b === void 0 ? void 0 : _b.displayName)) {
35693
+ return (_c = a === null || a === void 0 ? void 0 : a.user) === null || _c === void 0 ? void 0 : _c.displayName.localeCompare((_d = b === null || b === void 0 ? void 0 : b.user) === null || _d === void 0 ? void 0 : _d.displayName);
35694
+ }
35695
+ return 0;
35696
+ });
35697
+ break;
35698
+ case 'lastCreated':
35699
+ default:
35700
+ communityMembers = communityMembers.sort(sortByLastCreated);
35701
+ break;
35702
+ }
35703
+ return communityMembers;
35704
+ }
35705
+ }
35311
35706
 
35312
35707
  /*
35313
35708
  * Exported for testing
@@ -35356,79 +35751,215 @@ const getMembers = (params, callback, config) => {
35356
35751
  }
35357
35752
  const timestamp = Date.now();
35358
35753
  log(`getMembers(tmpid: ${timestamp}) > listen`);
35359
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
35360
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
35361
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
35362
- const disposers = [];
35363
- const cacheKey = ['communityUsers', 'collection', queryParams];
35364
- const cacheByCommunityIdKey = [
35365
- 'communityUsers',
35366
- 'collection',
35367
- { communityId: params.communityId },
35368
- ];
35369
- const responder = (data, isEventModel = false) => {
35370
- var _a, _b;
35371
- const communityMembers = (_a = data.data
35372
- .map(id => pullFromCache(['communityUsers', 'get', id]))
35373
- .filter(Boolean)
35374
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
35375
- callback({
35376
- onNextPage: onFetch,
35377
- data: isEventModel ? applyFilter(communityMembers, params) : communityMembers,
35378
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
35379
- loading: data.loading,
35380
- error: data.error,
35381
- });
35754
+ const communityMemberLiveCollection = new CommunityMembersLiveCollectionController(params, resp => {
35755
+ console.log('resp', resp);
35756
+ callback(resp);
35757
+ });
35758
+ const disposers = communityMemberLiveCollection.startSubscription();
35759
+ const cacheKey = communityMemberLiveCollection.getCacheKey();
35760
+ disposers.push(() => {
35761
+ dropFromCache(cacheKey);
35762
+ });
35763
+ return () => {
35764
+ log(`getMembers(tmpid: ${timestamp}) > dispose`);
35765
+ disposers.forEach(fn => fn());
35382
35766
  };
35383
- const realtimeRouter = (_) => (_, communityMembers) => {
35384
- var _a;
35385
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35386
- if (!collection) {
35387
- return;
35767
+ };
35768
+ /* end_public_function */
35769
+
35770
+ /**
35771
+ * TODO: handle cache receive cache option, and cache policy
35772
+ * TODO: check if querybyIds is supported
35773
+ */
35774
+ class SearchCommunityMembersPaginationController extends PaginationController {
35775
+ async getRequest(queryParams, token) {
35776
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
35777
+ const options = token ? { token } : { limit };
35778
+ const { data: queryResponse } = await this.http.get(`/api/v3/communities/${params.communityId}/users`, {
35779
+ params: Object.assign(Object.assign({}, params), { options }),
35780
+ });
35781
+ return queryResponse;
35782
+ }
35783
+ }
35784
+
35785
+ class SearchCommunityMembersQueryStreamController extends QueryStreamController {
35786
+ constructor(query, cacheKey, notifyChange, preparePayload) {
35787
+ super(query, cacheKey);
35788
+ this.notifyChange = notifyChange;
35789
+ this.preparePayload = preparePayload;
35790
+ }
35791
+ async saveToMainDB(response) {
35792
+ const processedPayload = await this.preparePayload(response);
35793
+ const client = getActiveClient();
35794
+ const cachedAt = client.cache && Date.now();
35795
+ if (client.cache) {
35796
+ ingestInCache(processedPayload, { cachedAt });
35388
35797
  }
35389
- const communityMemberCacheIds = communityMembers
35390
- .map(communityMember => {
35391
- if (params.communityId !== communityMember.communityId) {
35798
+ }
35799
+ appendToQueryStream(response, direction, refresh = false) {
35800
+ var _a, _b;
35801
+ if (refresh) {
35802
+ pushToCache(this.cacheKey, {
35803
+ data: response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
35804
+ });
35805
+ }
35806
+ else {
35807
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35808
+ const communityUsers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
35809
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
35810
+ ...new Set([
35811
+ ...communityUsers,
35812
+ ...response.communityUsers.map(({ communityId, userId }) => getResolver('communityUsers')({ communityId, userId })),
35813
+ ]),
35814
+ ] }));
35815
+ }
35816
+ }
35817
+ reactor(action) {
35818
+ return (community, communityMembers) => {
35819
+ var _a;
35820
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35821
+ if (!collection)
35392
35822
  return;
35393
- }
35394
- const communityMemberCacheId = getResolver('communityUsers')({
35395
- communityId: params.communityId,
35396
- userId: communityMember.userId,
35823
+ communityMembers.forEach(communityMember => {
35824
+ const communityMemberCacheId = getResolver('communityUsers')({
35825
+ communityId: this.query.communityId,
35826
+ userId: communityMember.userId,
35827
+ });
35828
+ if (communityMember.communityMembership === 'none') {
35829
+ collection.data = collection.data.filter(m => m !== communityMemberCacheId);
35830
+ }
35397
35831
  });
35398
- return communityMemberCacheId;
35399
- })
35400
- .filter(isNonNullable);
35401
- collection.data = [...new Set([...communityMemberCacheIds, ...collection.data])];
35402
- pushToCache(cacheKey, collection);
35403
- pushToCache(cacheByCommunityIdKey, collection);
35404
- responder(collection, true);
35405
- };
35406
- const onFetch = (initial = false) => {
35832
+ pushToCache(this.cacheKey, collection);
35833
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
35834
+ };
35835
+ }
35836
+ subscribeRTE(createSubscriber) {
35837
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
35838
+ }
35839
+ }
35840
+
35841
+ var EnumCommunityMemberActions;
35842
+ (function (EnumCommunityMemberActions) {
35843
+ EnumCommunityMemberActions["OnCommunityJoined"] = "onCommunityJoined";
35844
+ EnumCommunityMemberActions["OnCommunityLeft"] = "onCommunityLeft";
35845
+ EnumCommunityMemberActions["OnCommunityUserBanned"] = "onCommunityUserBanned";
35846
+ EnumCommunityMemberActions["OnCommunityUserChanged"] = "onCommunityUserChanged";
35847
+ EnumCommunityMemberActions["OnCommunityUserRoleAdded"] = "onCommunityUserRoleAdded";
35848
+ EnumCommunityMemberActions["OnCommunityUserRoleRemoved"] = "onCommunityUserRoleRemoved";
35849
+ EnumCommunityMemberActions["OnCommunityUserUnbanned"] = "onCommunityUserUnbanned";
35850
+ })(EnumCommunityMemberActions || (EnumCommunityMemberActions = {}));
35851
+
35852
+ /* eslint-disable no-use-before-define */
35853
+ class SearchCommunityMembersLiveCollectionController extends LiveCollectionController {
35854
+ constructor(query, callback) {
35855
+ const queryStreamId = hash(query);
35856
+ const cacheKey = ['communityUsers', 'collection', queryStreamId];
35857
+ const paginationController = new SearchCommunityMembersPaginationController(query);
35858
+ super(paginationController, queryStreamId, cacheKey, callback);
35859
+ this.query = query;
35860
+ this.queryStreamController = new SearchCommunityMembersQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareCommunityPayload);
35861
+ this.callback = callback.bind(this);
35862
+ this.loadPage({ initial: true });
35863
+ }
35864
+ setup() {
35865
+ var _a;
35866
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35867
+ if (!collection) {
35868
+ pushToCache(this.cacheKey, {
35869
+ data: [],
35870
+ params: {},
35871
+ });
35872
+ }
35873
+ }
35874
+ async persistModel(queryPayload) {
35875
+ await this.queryStreamController.saveToMainDB(queryPayload);
35876
+ }
35877
+ persistQueryStream({ response, direction, refresh, }) {
35878
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
35879
+ }
35880
+ startSubscription() {
35881
+ return this.queryStreamController.subscribeRTE([
35882
+ { fn: onCommunityJoined, action: EnumCommunityMemberActions.OnCommunityJoined },
35883
+ { fn: onCommunityLeft, action: EnumCommunityMemberActions.OnCommunityLeft },
35884
+ { fn: onCommunityUserBanned, action: EnumCommunityMemberActions.OnCommunityUserBanned },
35885
+ { fn: onCommunityUserChanged, action: EnumCommunityMemberActions.OnCommunityUserChanged },
35886
+ {
35887
+ fn: onCommunityUserRoleRemoved,
35888
+ action: EnumCommunityMemberActions.OnCommunityUserRoleRemoved,
35889
+ },
35890
+ { fn: onCommunityUserUnbanned, action: EnumCommunityMemberActions.OnCommunityUserUnbanned },
35891
+ ]);
35892
+ }
35893
+ notifyChange({ origin, loading, error }) {
35407
35894
  var _a, _b;
35408
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35409
- const communityMembers = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
35410
- if (!initial && communityMembers.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
35895
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
35896
+ if (!collection)
35411
35897
  return;
35412
- const query = createQuery(queryCommunityMembers, Object.assign(Object.assign({}, queryParams), { limit: initial ? limit : undefined, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
35413
- runQuery(query, ({ data: result, error, loading, paging }) => {
35414
- const data = {
35415
- loading,
35416
- error,
35417
- params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
35418
- data: communityMembers,
35419
- };
35420
- if (result) {
35421
- data.data = [
35422
- ...new Set([...communityMembers, ...result.map(getResolver('communityUsers'))]),
35423
- ];
35424
- }
35425
- pushToCache(cacheKey, data);
35426
- pushToCache(cacheByCommunityIdKey, data);
35427
- responder(data);
35428
- }, queryOptions(policy));
35429
- };
35430
- disposers.push(onCommunityLeft(realtimeRouter()), onCommunityJoined(realtimeRouter()), onCommunityUserBanned(realtimeRouter()), onCommunityUserUnbanned(realtimeRouter()), onCommunityUserChanged(realtimeRouter()), onCommunityUserRoleAdded(realtimeRouter()), onCommunityUserRoleRemoved(realtimeRouter()));
35431
- onFetch(true);
35898
+ const data = this.applyFilter((_b = collection.data
35899
+ .map(id => pullFromCache(['communityUsers', 'get', id]))
35900
+ .filter(isNonNullable)
35901
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []);
35902
+ if (!this.shouldNotify(data) && origin === 'event')
35903
+ return;
35904
+ this.callback({
35905
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
35906
+ data,
35907
+ hasNextPage: !!this.paginationController.getNextToken(),
35908
+ loading,
35909
+ error,
35910
+ });
35911
+ }
35912
+ applyFilter(data) {
35913
+ let communityMembers = filterByPropIntersection(data, 'roles', this.query.roles);
35914
+ if (this.query.memberships) {
35915
+ communityMembers = communityMembers.filter(({ communityMembership }) => {
35916
+ const memberships = this.query.memberships || [];
35917
+ return memberships.includes(communityMembership);
35918
+ });
35919
+ }
35920
+ if (this.query.search) {
35921
+ communityMembers = filterBySearchTerm(communityMembers, this.query.search);
35922
+ }
35923
+ return communityMembers;
35924
+ }
35925
+ }
35926
+
35927
+ /* begin_public_function
35928
+ id: community.membership.query
35929
+ */
35930
+ /**
35931
+ * ```js
35932
+ * import { searchMembers } from '@amityco/ts-sdk-react-native'
35933
+ *
35934
+ * let communityMembers = []
35935
+ * const unsub = searchMembers({
35936
+ * communityId: Amity.Community['communityId'],
35937
+ * }, response => merge(communityMembers, response.data))
35938
+ * ```
35939
+ *
35940
+ * Observe all mutations on a list of {@link Amity.CommunityUser}s
35941
+ *
35942
+ * @param params for querying community users
35943
+ * @param callback the function to call when new data are available
35944
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the community users
35945
+ *
35946
+ * @category Community Live Collection
35947
+ */
35948
+ const searchMembers = (params, callback, config) => {
35949
+ const { log, cache } = getActiveClient();
35950
+ if (!cache) {
35951
+ console.log(ENABLE_CACHE_MESSAGE);
35952
+ }
35953
+ const timestamp = Date.now();
35954
+ log(`getMembers(tmpid: ${timestamp}) > listen`);
35955
+ const searchCommunityMemberLiveCollection = new SearchCommunityMembersLiveCollectionController(params, resp => {
35956
+ callback(resp);
35957
+ });
35958
+ const disposers = searchCommunityMemberLiveCollection.startSubscription();
35959
+ const cacheKey = searchCommunityMemberLiveCollection.getCacheKey();
35960
+ disposers.push(() => {
35961
+ dropFromCache(cacheKey);
35962
+ });
35432
35963
  return () => {
35433
35964
  log(`getMembers(tmpid: ${timestamp}) > dispose`);
35434
35965
  disposers.forEach(fn => fn());
@@ -35442,6 +35973,7 @@ var index$9 = /*#__PURE__*/Object.freeze({
35442
35973
  removeMembers: removeMembers,
35443
35974
  applyFilter: applyFilter,
35444
35975
  getMembers: getMembers,
35976
+ searchMembers: searchMembers,
35445
35977
  onCommunityUserAdded: onCommunityUserAdded,
35446
35978
  onCommunityUserRemoved: onCommunityUserRemoved,
35447
35979
  onCommunityUserBanned: onCommunityUserBanned,
@@ -35468,6 +36000,7 @@ var index$8 = /*#__PURE__*/Object.freeze({
35468
36000
  onCommunityUpdated: onCommunityUpdated,
35469
36001
  onCommunityDeleted: onCommunityDeleted,
35470
36002
  observeCommunity: observeCommunity,
36003
+ searchCommunities: searchCommunities,
35471
36004
  getCommunities: getCommunities,
35472
36005
  getCommunity: getCommunity,
35473
36006
  getTrendingCommunities: getTrendingCommunities,
@@ -36054,7 +36587,7 @@ const updatePost = async (postId, patch) => {
36054
36587
  const cachedAt = client.cache && Date.now();
36055
36588
  if (client.cache)
36056
36589
  ingestInCache(data, { cachedAt });
36057
- fireEvent('post.updated', data);
36590
+ fireEvent('local.post.updated', data);
36058
36591
  const { posts } = data;
36059
36592
  return {
36060
36593
  data: LinkedObject.post(posts.find(post => post.postId === postId)),
@@ -36091,7 +36624,7 @@ const editPost = async (postId, patch) => {
36091
36624
  const cachedAt = client.cache && Date.now();
36092
36625
  if (client.cache)
36093
36626
  ingestInCache(data, { cachedAt });
36094
- fireEvent('post.updated', data);
36627
+ fireEvent('local.post.updated', data);
36095
36628
  const { posts } = data;
36096
36629
  return {
36097
36630
  data: LinkedObject.post(posts.find(post => post.postId === postId)),
@@ -36464,290 +36997,6 @@ const observePost = (postId, callback, policy = 'cache_then_server') => {
36464
36997
  };
36465
36998
  };
36466
36999
 
36467
- /* begin_public_function
36468
- id: post.get
36469
- */
36470
- /**
36471
- * ```js
36472
- * import { PostRepository } from '@amityco/ts-sdk-react-native';
36473
- *
36474
- * let post;
36475
- *
36476
- * const unsub = PostRepository.getPost(postId, response => {
36477
- * post = response.data;
36478
- * });
36479
- * ```
36480
- *
36481
- * Observe all mutation on a given {@link Amity.Post}
36482
- *
36483
- * @param postId the ID of the message to observe
36484
- * @param callback the function to call when new data are available
36485
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the sub channel
36486
- *
36487
- * @category Post Live Object
36488
- */
36489
- const getPost = (postId, callback) => {
36490
- return liveObject(postId, callback, 'postId', getPost$1, [
36491
- onPostApproved,
36492
- onPostDeclined,
36493
- (callback) => {
36494
- return onPostDeleted((post) => {
36495
- var _a;
36496
- let targetPost = post;
36497
- // check if the deleted post is a child of the target post
36498
- if (post.parentPostId === postId && post.isDeleted) {
36499
- const parentPost = (_a = pullFromCache([
36500
- 'post',
36501
- 'get',
36502
- post.parentPostId,
36503
- ])) === null || _a === void 0 ? void 0 : _a.data;
36504
- if (parentPost) {
36505
- parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
36506
- pushToCache(['post', 'get', parentPost.postId], parentPost);
36507
- // if the deleted post is a child of the target post, then the target post is the parent post
36508
- targetPost = parentPost;
36509
- }
36510
- }
36511
- callback(targetPost);
36512
- });
36513
- },
36514
- onPostFlagged,
36515
- (callback) => {
36516
- return onPostReactionAdded((post) => {
36517
- callback(LinkedObject.post(post));
36518
- });
36519
- },
36520
- (callback) => {
36521
- return onPostReactionRemoved((post) => {
36522
- callback(LinkedObject.post(post));
36523
- });
36524
- },
36525
- onPostUnflagged,
36526
- onPostUpdated,
36527
- ]);
36528
- };
36529
- /* end_public_function */
36530
-
36531
- /**
36532
- * ```js
36533
- * import { queryPosts } from '@amityco/ts-sdk-react-native'
36534
- * const { data: posts, prevPage, nextPage } = await queryPosts({ targetId, targetType })
36535
- * ```
36536
- *
36537
- * Queries a paginable list of {@link Amity.Post} objects
36538
- *
36539
- * @param query The query parameters
36540
- * @returns posts
36541
- *
36542
- * @category Post API
36543
- * @async
36544
- */
36545
- const queryPosts = async (query) => {
36546
- const client = getActiveClient();
36547
- client.log('post/queryPosts', query);
36548
- const { page, limit = 10, includeDeleted } = query, params = __rest(query, ["page", "limit", "includeDeleted"]);
36549
- const { dataTypes, matchingOnlyParentPost } = params;
36550
- const options = (() => {
36551
- if (page)
36552
- return { token: page };
36553
- if (limit)
36554
- return { limit };
36555
- return undefined;
36556
- })();
36557
- // API-FIX: parameters should be querystring. (1)
36558
- // API-FIX: backend should answer Amity.Response (2)
36559
- // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.PostPayload>>>(
36560
- const { data } = await client.http.get(`/api/v4/posts`, {
36561
- params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted),
36562
- /*
36563
- * when creating post like image, file, video BE will create 2 posts
36564
- * 1. parent post to store text with dataType=text
36565
- * 2. child post to store dataTypes post data
36566
- *
36567
- * By default, BE queries only parent post
36568
- */
36569
- matchingOnlyParentPost: matchingOnlyParentPost !== null && matchingOnlyParentPost !== void 0 ? matchingOnlyParentPost : !(dataTypes === null || dataTypes === void 0 ? void 0 : dataTypes.length), options }),
36570
- });
36571
- // API-FIX: backend should answer Amity.Response (2)
36572
- // const { paging, posts } = unwrapPayload(data)
36573
- // unpacking
36574
- const { paging } = data, payload = __rest(data, ["paging"]);
36575
- const paperedPayload = prepareMembershipPayload(payload, 'communityUsers');
36576
- const { posts } = payload;
36577
- const cachedAt = client.cache && Date.now();
36578
- if (client.cache) {
36579
- ingestInCache(paperedPayload, { cachedAt });
36580
- const cacheKey = ['post', 'query', Object.assign(Object.assign({}, params), { options })];
36581
- pushToCache(cacheKey, { posts: posts.map(getResolver('post')), paging });
36582
- }
36583
- return { data: posts.map(LinkedObject.post), cachedAt, paging };
36584
- };
36585
-
36586
- /* begin_public_function
36587
- id: post.query
36588
- */
36589
- /**
36590
- * ```js
36591
- * import { PostRepository } from '@amityco/ts-sdk-react-native'
36592
- *
36593
- * let posts = []
36594
- * const unsub = PostRepository.getPosts({
36595
- * targetType: Amity.PostTargetType,
36596
- * targetId: Amity.Post['targetId'],
36597
- * }, response => merge(posts, response.data))
36598
- * ```
36599
- *
36600
- * Observe all mutations on a list of {@link Amity.Post} for a given target object
36601
- *
36602
- * @param params.targetType the type of the target
36603
- * @param params.targetId the ID of the target
36604
- * @param callback the function to call when new data are available
36605
- * @param config
36606
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
36607
- *
36608
- * @category Posts Live Collection
36609
- */
36610
- const getPosts = (params, callback, config) => {
36611
- const { log, cache } = getActiveClient();
36612
- if (!cache) {
36613
- console.log(ENABLE_CACHE_MESSAGE);
36614
- }
36615
- const timestamp = Date.now();
36616
- log(`getPosts(tmpid: ${timestamp}) > listen`);
36617
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
36618
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
36619
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
36620
- const disposers = [];
36621
- const cacheKey = [
36622
- 'post',
36623
- 'collection',
36624
- { targetId: params.targetId, targetType: params.targetType },
36625
- ];
36626
- const responder = (data) => {
36627
- var _a, _b, _c;
36628
- let posts = (_a = data.data
36629
- .map(postId => pullFromCache(['post', 'get', postId]))
36630
- .filter(Boolean)
36631
- .map(({ data }) => LinkedObject.post(data))) !== null && _a !== void 0 ? _a : [];
36632
- const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
36633
- posts = posts.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
36634
- if (!params.includeDeleted) {
36635
- posts = filterByPropEquality(posts, 'isDeleted', false);
36636
- }
36637
- if (params.tags) {
36638
- posts = posts.filter(p => { var _a; return (_a = p.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = params.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
36639
- }
36640
- if (params.targetType === 'community' && params.feedType) {
36641
- posts = filterByFeedType(posts, params.feedType);
36642
- }
36643
- if ((_b = params.dataTypes) === null || _b === void 0 ? void 0 : _b.length) {
36644
- posts = filterByPostDataTypes(posts, params.dataTypes);
36645
- }
36646
- callback({
36647
- onNextPage: onFetch,
36648
- data: posts,
36649
- hasNextPage: !!((_c = data.params) === null || _c === void 0 ? void 0 : _c.page),
36650
- loading: data.loading,
36651
- error: data.error,
36652
- });
36653
- };
36654
- const realtimeRouter = (action) => (post) => {
36655
- var _a, _b;
36656
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
36657
- if (!collection)
36658
- return;
36659
- if (post.parentPostId && post.isDeleted) {
36660
- const parentPost = (_b = pullFromCache([
36661
- 'post',
36662
- 'get',
36663
- post.parentPostId,
36664
- ])) === null || _b === void 0 ? void 0 : _b.data;
36665
- if (!parentPost || (parentPost === null || parentPost === void 0 ? void 0 : parentPost.targetId) !== params.targetId)
36666
- return;
36667
- parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
36668
- pushToCache(['post', 'get', parentPost.postId], parentPost);
36669
- }
36670
- else {
36671
- if (params.targetId !== post.targetId)
36672
- return;
36673
- if (params.targetType !== post.targetType)
36674
- return;
36675
- }
36676
- /*
36677
- * This is not ideal, but currently this is the only way to update the
36678
- * collection on post declined
36679
- */
36680
- if (action === 'onDeclined') {
36681
- collection.data = collection.data.filter(postId => postId !== post.postId);
36682
- }
36683
- else {
36684
- collection.data = [...new Set([post.postId, ...collection.data])];
36685
- }
36686
- pushToCache(cacheKey, collection);
36687
- responder(collection);
36688
- };
36689
- const onFetch = (initial = false) => {
36690
- var _a, _b, _c;
36691
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
36692
- const posts = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
36693
- if (!initial && posts.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
36694
- return;
36695
- const query = createQuery(queryPosts, Object.assign(Object.assign({}, queryParams), { limit: initial ? limit : undefined, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
36696
- runQuery(query, ({ data: result, error, loading, paging }) => {
36697
- const data = {
36698
- loading,
36699
- error,
36700
- params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
36701
- data: posts,
36702
- };
36703
- if (result) {
36704
- data.data = initial
36705
- ? result.map(getResolver('post'))
36706
- : [...new Set([...posts, ...result.map(getResolver('post'))])];
36707
- }
36708
- pushToCache(cacheKey, data);
36709
- responder(data);
36710
- }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
36711
- };
36712
- disposers.push(onPostCreated(realtimeRouter('onCreate')), onPostApproved(realtimeRouter('onApproved')), onPostDeclined(realtimeRouter('onDeclined')), onPostDeleted(realtimeRouter('onDelete')), onPostUpdated(realtimeRouter('onUpdate')), onPostFlagged(realtimeRouter('onFlagged')), onPostUnflagged(realtimeRouter('onUnflagged')), onPostReactionAdded(realtimeRouter('onReactionAdded')), onPostReactionRemoved(realtimeRouter('onReactionRemoved')));
36713
- onFetch(true);
36714
- disposers.push(() => dropFromCache(cacheKey));
36715
- return () => {
36716
- log(`getPosts(tmpid: ${timestamp}) > dispose`);
36717
- disposers.forEach(fn => fn());
36718
- };
36719
- };
36720
- /* end_public_function */
36721
-
36722
- var index$5 = /*#__PURE__*/Object.freeze({
36723
- __proto__: null,
36724
- getPostByIds: getPostByIds,
36725
- createPost: createPost,
36726
- updatePost: updatePost,
36727
- editPost: editPost,
36728
- deletePost: deletePost,
36729
- softDeletePost: softDeletePost,
36730
- hardDeletePost: hardDeletePost,
36731
- approvePost: approvePost,
36732
- declinePost: declinePost,
36733
- flagPost: flagPost,
36734
- unflagPost: unflagPost,
36735
- isPostFlaggedByMe: isPostFlaggedByMe,
36736
- onPostCreated: onPostCreated,
36737
- onPostUpdated: onPostUpdated,
36738
- onPostDeleted: onPostDeleted,
36739
- onPostApproved: onPostApproved,
36740
- onPostDeclined: onPostDeclined,
36741
- onPostFlagged: onPostFlagged,
36742
- onPostUnflagged: onPostUnflagged,
36743
- onPostReactionAdded: onPostReactionAdded,
36744
- onPostReactionRemoved: onPostReactionRemoved,
36745
- observePosts: observePosts,
36746
- observePost: observePost,
36747
- getPost: getPost,
36748
- getPosts: getPosts
36749
- });
36750
-
36751
37000
  /* begin_public_function
36752
37001
  id: comment.get_by_ids
36753
37002
  */
@@ -36856,7 +37105,7 @@ const createComment = async (bundle) => {
36856
37105
  ingestInCache(data, { cachedAt });
36857
37106
  if (['post', 'content'].includes(bundle.referenceType)) {
36858
37107
  const post = await getPost$1(bundle.referenceId);
36859
- fireEvent('post.updated', {
37108
+ fireEvent('local.post.updated', {
36860
37109
  posts: [post.data],
36861
37110
  categories: [],
36862
37111
  comments: [],
@@ -36894,7 +37143,7 @@ const createComment = async (bundle) => {
36894
37143
  }
36895
37144
  }
36896
37145
  }
36897
- fireEvent('comment.created', data);
37146
+ fireEvent('local.comment.created', data);
36898
37147
  return {
36899
37148
  data: LinkedObject.comment(comments[0]),
36900
37149
  cachedAt,
@@ -37050,8 +37299,7 @@ const deleteComment = async (commentId, permanent = false) => {
37050
37299
  }
37051
37300
  else {
37052
37301
  const post = await getPost$1(comment.data.referenceId);
37053
- // @TODO: Need to separate Local / MQTT later
37054
- fireEvent('post.updated', {
37302
+ fireEvent('local.post.updated', {
37055
37303
  posts: [post.data],
37056
37304
  categories: [],
37057
37305
  comments: [],
@@ -37063,8 +37311,7 @@ const deleteComment = async (commentId, permanent = false) => {
37063
37311
  users: [],
37064
37312
  });
37065
37313
  }
37066
- // @TODO: Need to separate Local / MQTT later
37067
- fireEvent('comment.deleted', {
37314
+ fireEvent('local.comment.deleted', {
37068
37315
  comments: [deleted],
37069
37316
  commentChildren: [],
37070
37317
  files: [],
@@ -37533,7 +37780,7 @@ const getComments = (params, callback, config) => {
37533
37780
  };
37534
37781
  /* end_public_function */
37535
37782
 
37536
- var index$4 = /*#__PURE__*/Object.freeze({
37783
+ var index$5 = /*#__PURE__*/Object.freeze({
37537
37784
  __proto__: null,
37538
37785
  getCommentByIds: getCommentByIds,
37539
37786
  createComment: createComment,
@@ -37557,6 +37804,324 @@ var index$4 = /*#__PURE__*/Object.freeze({
37557
37804
  getComments: getComments
37558
37805
  });
37559
37806
 
37807
+ /* begin_public_function
37808
+ id: post.get
37809
+ */
37810
+ /**
37811
+ * ```js
37812
+ * import { PostRepository } from '@amityco/ts-sdk-react-native';
37813
+ *
37814
+ * let post;
37815
+ *
37816
+ * const unsub = PostRepository.getPost(postId, response => {
37817
+ * post = response.data;
37818
+ * });
37819
+ * ```
37820
+ *
37821
+ * Observe all mutation on a given {@link Amity.Post}
37822
+ *
37823
+ * @param postId the ID of the message to observe
37824
+ * @param callback the function to call when new data are available
37825
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the sub channel
37826
+ *
37827
+ * @category Post Live Object
37828
+ */
37829
+ const getPost = (postId, callback) => {
37830
+ return liveObject(postId, callback, 'postId', getPost$1, [
37831
+ onPostApproved,
37832
+ onPostDeclined,
37833
+ (callback) => {
37834
+ return onPostDeleted((post) => {
37835
+ var _a;
37836
+ let targetPost = post;
37837
+ // check if the deleted post is a child of the target post
37838
+ if (post.parentPostId === postId && post.isDeleted) {
37839
+ const parentPost = (_a = pullFromCache([
37840
+ 'post',
37841
+ 'get',
37842
+ post.parentPostId,
37843
+ ])) === null || _a === void 0 ? void 0 : _a.data;
37844
+ if (parentPost) {
37845
+ parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
37846
+ pushToCache(['post', 'get', parentPost.postId], parentPost);
37847
+ // if the deleted post is a child of the target post, then the target post is the parent post
37848
+ targetPost = parentPost;
37849
+ }
37850
+ }
37851
+ callback(targetPost);
37852
+ });
37853
+ },
37854
+ onPostFlagged,
37855
+ (callback) => {
37856
+ return onPostReactionAdded((post) => {
37857
+ callback(LinkedObject.post(post));
37858
+ });
37859
+ },
37860
+ (callback) => {
37861
+ return onPostReactionRemoved((post) => {
37862
+ callback(LinkedObject.post(post));
37863
+ });
37864
+ },
37865
+ onPostUnflagged,
37866
+ onPostUpdated,
37867
+ convertEventPayload((callback) => {
37868
+ return onCommentCreated(async (comment) => {
37869
+ if (comment.referenceId === postId) {
37870
+ await getPost$1(postId);
37871
+ callback(comment);
37872
+ }
37873
+ });
37874
+ }, 'referenceId', 'post'),
37875
+ convertEventPayload((callback) => {
37876
+ return onCommentDeleted(async (comment) => {
37877
+ if (comment.referenceId === postId) {
37878
+ await getPost$1(postId);
37879
+ callback(comment);
37880
+ }
37881
+ });
37882
+ }, 'referenceId', 'post'),
37883
+ ]);
37884
+ };
37885
+ /* end_public_function */
37886
+
37887
+ /**
37888
+ * ```js
37889
+ * import { queryPosts } from '@amityco/ts-sdk-react-native'
37890
+ * const { data: posts, prevPage, nextPage } = await queryPosts({ targetId, targetType })
37891
+ * ```
37892
+ *
37893
+ * Queries a paginable list of {@link Amity.Post} objects
37894
+ *
37895
+ * @param query The query parameters
37896
+ * @returns posts
37897
+ *
37898
+ * @category Post API
37899
+ * @async
37900
+ */
37901
+ const queryPosts = async (query) => {
37902
+ const client = getActiveClient();
37903
+ client.log('post/queryPosts', query);
37904
+ const { page, limit = 10, includeDeleted } = query, params = __rest(query, ["page", "limit", "includeDeleted"]);
37905
+ const { dataTypes, matchingOnlyParentPost } = params;
37906
+ const options = (() => {
37907
+ if (page)
37908
+ return { token: page };
37909
+ if (limit)
37910
+ return { limit };
37911
+ return undefined;
37912
+ })();
37913
+ // API-FIX: parameters should be querystring. (1)
37914
+ // API-FIX: backend should answer Amity.Response (2)
37915
+ // const { data } = await client.http.get<Amity.Response<Amity.PagedResponse<Amity.PostPayload>>>(
37916
+ const { data } = await client.http.get(`/api/v4/posts`, {
37917
+ params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted),
37918
+ /*
37919
+ * when creating post like image, file, video BE will create 2 posts
37920
+ * 1. parent post to store text with dataType=text
37921
+ * 2. child post to store dataTypes post data
37922
+ *
37923
+ * By default, BE queries only parent post
37924
+ */
37925
+ matchingOnlyParentPost: matchingOnlyParentPost !== null && matchingOnlyParentPost !== void 0 ? matchingOnlyParentPost : !(dataTypes === null || dataTypes === void 0 ? void 0 : dataTypes.length), options }),
37926
+ });
37927
+ // API-FIX: backend should answer Amity.Response (2)
37928
+ // const { paging, posts } = unwrapPayload(data)
37929
+ // unpacking
37930
+ const { paging } = data, payload = __rest(data, ["paging"]);
37931
+ const paperedPayload = prepareMembershipPayload(payload, 'communityUsers');
37932
+ const { posts } = payload;
37933
+ const cachedAt = client.cache && Date.now();
37934
+ if (client.cache) {
37935
+ ingestInCache(paperedPayload, { cachedAt });
37936
+ const cacheKey = ['post', 'query', Object.assign(Object.assign({}, params), { options })];
37937
+ pushToCache(cacheKey, { posts: posts.map(getResolver('post')), paging });
37938
+ }
37939
+ return { data: posts.map(LinkedObject.post), cachedAt, paging };
37940
+ };
37941
+
37942
+ /* begin_public_function
37943
+ id: post.query
37944
+ */
37945
+ /**
37946
+ * ```js
37947
+ * import { PostRepository } from '@amityco/ts-sdk-react-native'
37948
+ *
37949
+ * let posts = []
37950
+ * const unsub = PostRepository.getPosts({
37951
+ * targetType: Amity.PostTargetType,
37952
+ * targetId: Amity.Post['targetId'],
37953
+ * }, response => merge(posts, response.data))
37954
+ * ```
37955
+ *
37956
+ * Observe all mutations on a list of {@link Amity.Post} for a given target object
37957
+ *
37958
+ * @param params.targetType the type of the target
37959
+ * @param params.targetId the ID of the target
37960
+ * @param callback the function to call when new data are available
37961
+ * @param config
37962
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the messages
37963
+ *
37964
+ * @category Posts Live Collection
37965
+ */
37966
+ const getPosts = (params, callback, config) => {
37967
+ const { log, cache } = getActiveClient();
37968
+ if (!cache) {
37969
+ console.log(ENABLE_CACHE_MESSAGE);
37970
+ }
37971
+ const timestamp = Date.now();
37972
+ log(`getPosts(tmpid: ${timestamp}) > listen`);
37973
+ const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
37974
+ const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
37975
+ const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
37976
+ const disposers = [];
37977
+ const cacheKey = [
37978
+ 'post',
37979
+ 'collection',
37980
+ { targetId: params.targetId, targetType: params.targetType },
37981
+ ];
37982
+ const responder = (data) => {
37983
+ var _a, _b, _c;
37984
+ let posts = (_a = data.data
37985
+ .map(postId => pullFromCache(['post', 'get', postId]))
37986
+ .filter(Boolean)
37987
+ .map(({ data }) => LinkedObject.post(data))) !== null && _a !== void 0 ? _a : [];
37988
+ const sortBy = params.sortBy ? params.sortBy : 'lastCreated';
37989
+ posts = posts.sort(sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
37990
+ if (!params.includeDeleted) {
37991
+ posts = filterByPropEquality(posts, 'isDeleted', false);
37992
+ }
37993
+ if (params.tags) {
37994
+ posts = posts.filter(p => { var _a; return (_a = p.tags) === null || _a === void 0 ? void 0 : _a.some(t => { var _a; return (_a = params.tags) === null || _a === void 0 ? void 0 : _a.includes(t); }); });
37995
+ }
37996
+ if (params.targetType === 'community' && params.feedType) {
37997
+ posts = filterByFeedType(posts, params.feedType);
37998
+ }
37999
+ if ((_b = params.dataTypes) === null || _b === void 0 ? void 0 : _b.length) {
38000
+ posts = filterByPostDataTypes(posts, params.dataTypes);
38001
+ }
38002
+ callback({
38003
+ onNextPage: onFetch,
38004
+ data: posts,
38005
+ hasNextPage: !!((_c = data.params) === null || _c === void 0 ? void 0 : _c.page),
38006
+ loading: data.loading,
38007
+ error: data.error,
38008
+ });
38009
+ };
38010
+ const realtimeRouter = (action) => (post) => {
38011
+ var _a, _b;
38012
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38013
+ if (!collection)
38014
+ return;
38015
+ if (post.parentPostId && post.isDeleted) {
38016
+ const parentPost = (_b = pullFromCache([
38017
+ 'post',
38018
+ 'get',
38019
+ post.parentPostId,
38020
+ ])) === null || _b === void 0 ? void 0 : _b.data;
38021
+ if (!parentPost || (parentPost === null || parentPost === void 0 ? void 0 : parentPost.targetId) !== params.targetId)
38022
+ return;
38023
+ parentPost.children = parentPost.children.filter(childId => childId !== post.postId);
38024
+ pushToCache(['post', 'get', parentPost.postId], parentPost);
38025
+ }
38026
+ else {
38027
+ if (params.targetId !== post.targetId)
38028
+ return;
38029
+ if (params.targetType !== post.targetType)
38030
+ return;
38031
+ }
38032
+ /*
38033
+ * This is not ideal, but currently this is the only way to update the
38034
+ * collection on post declined
38035
+ */
38036
+ if (action === 'onDeclined') {
38037
+ collection.data = collection.data.filter(postId => postId !== post.postId);
38038
+ }
38039
+ else {
38040
+ collection.data = [...new Set([post.postId, ...collection.data])];
38041
+ }
38042
+ pushToCache(cacheKey, collection);
38043
+ responder(collection);
38044
+ };
38045
+ const onFetch = (initial = false) => {
38046
+ var _a, _b, _c;
38047
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38048
+ const posts = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
38049
+ if (!initial && posts.length > 0 && !((_c = collection === null || collection === void 0 ? void 0 : collection.params) === null || _c === void 0 ? void 0 : _c.page))
38050
+ return;
38051
+ const query = createQuery(queryPosts, Object.assign(Object.assign({}, queryParams), { limit: initial ? limit : undefined, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
38052
+ runQuery(query, ({ data: result, error, loading, paging }) => {
38053
+ const data = {
38054
+ loading,
38055
+ error,
38056
+ params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
38057
+ data: posts,
38058
+ };
38059
+ if (result) {
38060
+ data.data = initial
38061
+ ? result.map(getResolver('post'))
38062
+ : [...new Set([...posts, ...result.map(getResolver('post'))])];
38063
+ }
38064
+ pushToCache(cacheKey, data);
38065
+ responder(data);
38066
+ }, queryOptions(policy, CACHE_SHORTEN_LIFESPAN));
38067
+ };
38068
+ disposers.push(onPostCreated(realtimeRouter('onCreate')), onPostApproved(realtimeRouter('onApproved')), onPostDeclined(realtimeRouter('onDeclined')), onPostDeleted(realtimeRouter('onDelete')), onPostUpdated(realtimeRouter('onUpdate')), onPostFlagged(realtimeRouter('onFlagged')), onPostUnflagged(realtimeRouter('onUnflagged')), onPostReactionAdded(realtimeRouter('onReactionAdded')), onPostReactionRemoved(realtimeRouter('onReactionRemoved')), convertEventPayload((callback) => {
38069
+ return onCommentCreated(async (comment) => {
38070
+ var _a;
38071
+ const currentCollection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38072
+ if (!currentCollection || currentCollection.data.includes(comment.referenceId))
38073
+ return;
38074
+ await getPost$1(comment.referenceId);
38075
+ callback(comment);
38076
+ });
38077
+ }, 'referenceId', 'post')(realtimeRouter('onUpdate')), convertEventPayload((callback) => {
38078
+ return onCommentDeleted(async (comment) => {
38079
+ var _a;
38080
+ const currentCollection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38081
+ if (!currentCollection || currentCollection.data.includes(comment.referenceId))
38082
+ return;
38083
+ await getPost$1(comment.referenceId);
38084
+ callback(comment);
38085
+ });
38086
+ }, 'referenceId', 'post')(realtimeRouter('onUpdate')));
38087
+ onFetch(true);
38088
+ disposers.push(() => dropFromCache(cacheKey));
38089
+ return () => {
38090
+ log(`getPosts(tmpid: ${timestamp}) > dispose`);
38091
+ disposers.forEach(fn => fn());
38092
+ };
38093
+ };
38094
+ /* end_public_function */
38095
+
38096
+ var index$4 = /*#__PURE__*/Object.freeze({
38097
+ __proto__: null,
38098
+ getPostByIds: getPostByIds,
38099
+ createPost: createPost,
38100
+ updatePost: updatePost,
38101
+ editPost: editPost,
38102
+ deletePost: deletePost,
38103
+ softDeletePost: softDeletePost,
38104
+ hardDeletePost: hardDeletePost,
38105
+ approvePost: approvePost,
38106
+ declinePost: declinePost,
38107
+ flagPost: flagPost,
38108
+ unflagPost: unflagPost,
38109
+ isPostFlaggedByMe: isPostFlaggedByMe,
38110
+ onPostCreated: onPostCreated,
38111
+ onPostUpdated: onPostUpdated,
38112
+ onPostDeleted: onPostDeleted,
38113
+ onPostApproved: onPostApproved,
38114
+ onPostDeclined: onPostDeclined,
38115
+ onPostFlagged: onPostFlagged,
38116
+ onPostUnflagged: onPostUnflagged,
38117
+ onPostReactionAdded: onPostReactionAdded,
38118
+ onPostReactionRemoved: onPostReactionRemoved,
38119
+ observePosts: observePosts,
38120
+ observePost: observePost,
38121
+ getPost: getPost,
38122
+ getPosts: getPosts
38123
+ });
38124
+
37560
38125
  /* begin_public_function
37561
38126
  id: stream.create
37562
38127
  */
@@ -37566,10 +38131,10 @@ var index$4 = /*#__PURE__*/Object.freeze({
37566
38131
  * const created = await createStream({ title: 'my stream', 'thumbnailFileId': fileId })
37567
38132
  * ```
37568
38133
  *
37569
- * Creates an {@link Amity.Stream}
38134
+ * Creates an {@link Amity.InternalStream}
37570
38135
  *
37571
- * @param bundle The data necessary to create a new {@link Amity.Stream}
37572
- * @returns The newly created {@link Amity.Stream}
38136
+ * @param bundle The data necessary to create a new {@link Amity.InternalStream}
38137
+ * @returns The newly created {@link Amity.InternalStream}
37573
38138
  *
37574
38139
  * @category Stream API
37575
38140
  * @async
@@ -37583,7 +38148,7 @@ const createStream = async (bundle) => {
37583
38148
  ingestInCache(data, { cachedAt });
37584
38149
  const { videoStreamings } = data;
37585
38150
  return {
37586
- data: videoStreamings[0],
38151
+ data: LinkedObject.stream(videoStreamings[0]),
37587
38152
  cachedAt,
37588
38153
  };
37589
38154
  };
@@ -37616,7 +38181,7 @@ const updateStream = async (streamId, patch) => {
37616
38181
  ingestInCache(data, { cachedAt });
37617
38182
  const { videoStreamings } = data;
37618
38183
  return {
37619
- data: videoStreamings.find(stream => stream.streamId === streamId),
38184
+ data: LinkedObject.stream(videoStreamings.find(stream => stream.streamId === streamId)),
37620
38185
  cachedAt,
37621
38186
  };
37622
38187
  };
@@ -37690,10 +38255,10 @@ getStream.locally = (streamId) => {
37690
38255
  * const success = await deleteStream(streamId)
37691
38256
  * ```
37692
38257
  *
37693
- * Deletes a {@link Amity.Stream}
38258
+ * Deletes a {@link Amity.InternalStream}
37694
38259
  *
37695
- * @param streamId The {@link Amity.Stream} ID to delete
37696
- * @return A success boolean if the {@link Amity.Stream} was deleted
38260
+ * @param streamId The {@link Amity.InternalStream} ID to delete
38261
+ * @return A success boolean if the {@link Amity.InternalStream} was deleted
37697
38262
  *
37698
38263
  * @category Stream API
37699
38264
  * @async
@@ -37718,11 +38283,11 @@ const deleteStream = async (streamId) => {
37718
38283
  * const stream = await disposeStream(streamId)
37719
38284
  * ```
37720
38285
  *
37721
- * Dispose a {@link Amity.Stream}.
38286
+ * Dispose a {@link Amity.InternalStream}.
37722
38287
  * Streaming status will be updated to "ended" and streaming url will be invalidated
37723
38288
  *
37724
- * @param streamId The {@link Amity.Stream} ID to dispose
37725
- * @returns the associated {@link Amity.Stream} object
38289
+ * @param streamId The {@link Amity.InternalStream} ID to dispose
38290
+ * @returns the associated {@link Amity.InternalStream} object
37726
38291
  *
37727
38292
  * @category Stream API
37728
38293
  * @async
@@ -37753,15 +38318,15 @@ const disposeStream = async (streamId) => {
37753
38318
  * const streams = await getStreams()
37754
38319
  * ```
37755
38320
  *
37756
- * Queries a paginable list of {@link Amity.Stream} objects
38321
+ * Queries a paginable list of {@link Amity.InternalStream} objects
37757
38322
  *
37758
38323
  * @param query The query parameters
37759
- * @returns A page of {@link Amity.Stream} objects
38324
+ * @returns A page of {@link Amity.InternalStream} objects
37760
38325
  *
37761
38326
  * @category Stream API
37762
38327
  * @async
37763
38328
  */
37764
- const queryStreams$1 = async (query) => {
38329
+ const queryStreams = async (query) => {
37765
38330
  const client = getActiveClient();
37766
38331
  client.log('stream/queryStreams', query);
37767
38332
  const _a = query !== null && query !== void 0 ? query : {}, { page } = _a, params = __rest(_a, ["page"]);
@@ -37791,7 +38356,7 @@ const queryStreams$1 = async (query) => {
37791
38356
  * })
37792
38357
  * ```
37793
38358
  *
37794
- * Fired when a {@link Amity.Stream} has started airing
38359
+ * Fired when a {@link Amity.InternalStream} has started airing
37795
38360
  *
37796
38361
  * @param callback The function to call when the event was fired
37797
38362
  * @returns an {@link Amity.Unsubscriber} function to stop listening
@@ -37815,7 +38380,7 @@ const onStreamStarted = (callback) => {
37815
38380
  * })
37816
38381
  * ```
37817
38382
  *
37818
- * Fired when a {@link Amity.Stream} has stopped airing
38383
+ * Fired when a {@link Amity.InternalStream} has stopped airing
37819
38384
  *
37820
38385
  * @param callback The function to call when the event was fired
37821
38386
  * @returns an {@link Amity.Unsubscriber} function to stop listening
@@ -37839,7 +38404,7 @@ const onStreamStopped = (callback) => {
37839
38404
  * })
37840
38405
  * ```
37841
38406
  *
37842
- * Fired when the recordings of a {@link Amity.Stream} are available
38407
+ * Fired when the recordings of a {@link Amity.InternalStream} are available
37843
38408
  *
37844
38409
  * @param callback The function to call when the event was fired
37845
38410
  * @returns an {@link Amity.Unsubscriber} function to stop listening
@@ -37855,6 +38420,54 @@ const onStreamRecorded = (callback) => {
37855
38420
  return createEventSubscriber(client, 'stream/onStreamRecorded', 'v3.video-streaming.didRecord', filter);
37856
38421
  };
37857
38422
 
38423
+ /**
38424
+ * ```js
38425
+ * import { onStreamFlagged } from '@amityco/ts-sdk-react-native'
38426
+ * const dispose = onStreamFlagged(stream => {
38427
+ * // ...
38428
+ * })
38429
+ * ```
38430
+ *
38431
+ * Fired when a {@link Amity.InternalStream} has started airing
38432
+ *
38433
+ * @param callback The function to call when the event was fired
38434
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
38435
+ *
38436
+ * @category Stream Events
38437
+ */
38438
+ const onStreamFlagged = (callback) => {
38439
+ const client = getActiveClient();
38440
+ const filter = (payload) => {
38441
+ ingestInCache(payload);
38442
+ callback(payload.videoStreamings[0]);
38443
+ };
38444
+ return createEventSubscriber(client, 'stream/onStreamFlagged', 'v3.video-streaming.didFlag', filter);
38445
+ };
38446
+
38447
+ /**
38448
+ * ```js
38449
+ * import { onStreamTerminated } from '@amityco/ts-sdk-react-native'
38450
+ * const dispose = onStreamTerminated(stream => {
38451
+ * // ...
38452
+ * })
38453
+ * ```
38454
+ *
38455
+ * Fired when a {@link Amity.InternalStream} has started airing
38456
+ *
38457
+ * @param callback The function to call when the event was fired
38458
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
38459
+ *
38460
+ * @category Stream Events
38461
+ */
38462
+ const onStreamTerminated = (callback) => {
38463
+ const client = getActiveClient();
38464
+ const filter = (payload) => {
38465
+ ingestInCache(payload);
38466
+ callback(payload.videoStreamings[0]);
38467
+ };
38468
+ return createEventSubscriber(client, 'stream/onStreamTerminated', 'v3.video-streaming.didTerminate', filter);
38469
+ };
38470
+
37858
38471
  /* eslint-disable no-use-before-define */
37859
38472
  /* begin_public_function
37860
38473
  id: stream.get
@@ -37869,15 +38482,22 @@ const onStreamRecorded = (callback) => {
37869
38482
  * Fetches a {@link Amity.Stream} object
37870
38483
  *
37871
38484
  * @param streamId the ID of the {@link Amity.Stream} to get
38485
+ * @param callback
37872
38486
  * @returns the associated {@link Amity.Stream} object
37873
38487
  *
37874
38488
  * @category Stream Live Object
37875
38489
  */
37876
38490
  const getStreamById = (streamId, callback) => {
37877
- return liveObject(streamId, callback, 'streamId', getStream, [
38491
+ const reactor = (snapshot) => {
38492
+ const { data } = snapshot;
38493
+ callback(Object.assign(Object.assign({}, snapshot), { data: data ? LinkedObject.stream(snapshot.data) : data }));
38494
+ };
38495
+ return liveObject(streamId, reactor, 'streamId', getStream, [
37878
38496
  onStreamRecorded,
37879
38497
  onStreamStarted,
37880
38498
  onStreamStopped,
38499
+ onStreamFlagged,
38500
+ onStreamTerminated,
37881
38501
  ]);
37882
38502
  };
37883
38503
  /* end_public_function */
@@ -37903,145 +38523,150 @@ getStreamById.locally = (streamId) => {
37903
38523
  if (!cached)
37904
38524
  return;
37905
38525
  return {
37906
- data: cached.data,
38526
+ data: LinkedObject.stream(cached.data),
37907
38527
  cachedAt: cached.cachedAt,
37908
38528
  };
37909
38529
  };
37910
38530
 
37911
- /* begin_public_function
37912
- id: stream.query
37913
- */
37914
- /**
37915
- * ```js
37916
- * import { getStreams } from '@amityco/ts-sdk-react-native'
37917
- * const streams = await getStreams()
37918
- * ```
37919
- *
37920
- * Queries a paginable list of {@link Amity.Stream} objects
37921
- *
37922
- * @param query The query parameters
37923
- * @returns A page of {@link Amity.Stream} objects
37924
- *
37925
- * @category Stream API
37926
- * @async
37927
- */
37928
- const queryStreams = async (query) => {
37929
- const client = getActiveClient();
37930
- client.log('stream/queryStreams', query);
37931
- const _a = query !== null && query !== void 0 ? query : {}, { page, limit } = _a, params = __rest(_a, ["page", "limit"]);
37932
- const options = (() => {
37933
- if (page)
37934
- return { token: page };
37935
- if (limit)
37936
- return { limit };
37937
- return undefined;
37938
- })();
37939
- const { data } = await client.http.get(`/api/v3/video-streaming`, {
37940
- params: Object.assign(Object.assign({}, params), { options }),
37941
- });
37942
- // API-FIX: backend to response Amity.Response: const { paging, videoStreamings } = unwrapPayload(data)
37943
- // API-FIX: seems returned data has a results identifier on top of data, like no other apis, and this is beautiful
37944
- const { paging, results: payload } = data;
37945
- const { videoStreamings } = payload;
37946
- const cachedAt = client.cache && Date.now();
37947
- if (client.cache)
37948
- ingestInCache(payload, { cachedAt });
37949
- return { data: videoStreamings, cachedAt, paging };
37950
- };
37951
- /* end_public_function */
38531
+ class GetStreamsPageController extends PaginationController {
38532
+ async getRequest(queryParams, token) {
38533
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
38534
+ const options = token ? { token } : { limit };
38535
+ const { data: queryResponse } = await this.http.get(`/api/v3/video-streaming`, {
38536
+ params: Object.assign(Object.assign({}, params), { options }),
38537
+ });
38538
+ return Object.assign(Object.assign({}, queryResponse.results), { paging: queryResponse.paging });
38539
+ }
38540
+ }
37952
38541
 
37953
- /* begin_public_function
37954
- id: stream.query
37955
- */
37956
- /**
37957
- * ```js
37958
- * import { StreamRepository } from '@amityco/ts-sdk-react-native'
37959
- * const streams = await StreamRepository.getStreams()
37960
- * ```
37961
- *
37962
- * Observe all mutations on a list of {@link Amity.Stream}s
37963
- *
37964
- * @param params for querying streams
37965
- * @param callback the function to call when new data are available
37966
- * @param config
37967
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the streams
37968
- *
37969
- * @category Stream Live Collection
37970
- */
37971
- const getStreams = (params, callback, config) => {
37972
- const { log, cache } = getActiveClient();
37973
- if (!cache) {
37974
- console.log(ENABLE_CACHE_MESSAGE);
38542
+ class GetStreamsQueryStreamController extends QueryStreamController {
38543
+ constructor(query, cacheKey, notifyChange, paginationController) {
38544
+ super(query, cacheKey);
38545
+ this.notifyChange = notifyChange;
38546
+ this.paginationController = paginationController;
37975
38547
  }
37976
- const timestamp = Date.now();
37977
- log(`getStreams(tmpid: ${timestamp}) > listen`);
37978
- const { limit: queryLimit } = params, queryParams = __rest(params, ["limit"]);
37979
- const limit = queryLimit !== null && queryLimit !== void 0 ? queryLimit : COLLECTION_DEFAULT_PAGINATION_LIMIT;
37980
- const { policy = COLLECTION_DEFAULT_CACHING_POLICY } = config !== null && config !== void 0 ? config : {};
37981
- const disposers = [];
37982
- const cacheKey = ['streams', 'collection', params];
37983
- const applyFilter = (data) => {
37984
- let streams = filterByPropEquality(data, 'isDeleted', params.isDeleted);
37985
- streams = streams.sort(params.sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
37986
- return streams;
37987
- };
37988
- const responder = (data, isEventModel = false) => {
38548
+ // eslint-disable-next-line class-methods-use-this
38549
+ saveToMainDB(response) {
38550
+ const client = getActiveClient();
38551
+ const cachedAt = client.cache && Date.now();
38552
+ if (client.cache) {
38553
+ ingestInCache(response, { cachedAt });
38554
+ }
38555
+ }
38556
+ appendToQueryStream(response, direction, refresh = false) {
37989
38557
  var _a, _b;
37990
- const streams = (_a = data.data
37991
- .map(streamId => {
37992
- return pullFromCache(['stream', 'get', streamId]);
37993
- })
37994
- .filter(Boolean)
37995
- .map(({ data }) => data)) !== null && _a !== void 0 ? _a : [];
37996
- callback({
37997
- onNextPage: onFetch,
37998
- /*
37999
- * Only apply filter to RTE Model
38000
- */
38001
- data: isEventModel ? applyFilter(streams) : streams,
38002
- hasNextPage: !!((_b = data.params) === null || _b === void 0 ? void 0 : _b.page),
38003
- loading: data.loading,
38004
- error: data.error,
38005
- });
38006
- };
38007
- const realtimeRouter = (_) => (stream) => {
38558
+ if (refresh) {
38559
+ pushToCache(this.cacheKey, {
38560
+ data: response.videoStreamings.map(getResolver('stream')),
38561
+ query: this.query,
38562
+ });
38563
+ }
38564
+ else {
38565
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38566
+ const messages = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
38567
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: direction === 'next'
38568
+ ? [...new Set([...messages, ...response.videoStreamings.map(getResolver('stream'))])]
38569
+ : [...new Set([...response.videoStreamings.map(getResolver('stream')), ...messages])] }));
38570
+ }
38571
+ }
38572
+ reactor(action) {
38573
+ return (payload) => {
38574
+ var _a;
38575
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38576
+ if (!collection)
38577
+ return;
38578
+ collection.data = [...new Set([payload.streamId, ...collection.data])];
38579
+ pushToCache(this.cacheKey, collection);
38580
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
38581
+ };
38582
+ }
38583
+ subscribeRTE(createSubscriber) {
38584
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
38585
+ }
38586
+ }
38587
+
38588
+ class GetStreamsLiveCollectionController extends LiveCollectionController {
38589
+ constructor(query, callback) {
38590
+ const queryStreamId = hash(query);
38591
+ const cacheKey = ['streams', 'collection', queryStreamId];
38592
+ const paginationController = new GetStreamsPageController(query);
38593
+ super(paginationController, queryStreamId, cacheKey, callback);
38594
+ this.applyFilter = (data) => {
38595
+ let streams = filterByPropEquality(data, 'isDeleted', this.query.isDeleted);
38596
+ streams = streams.sort(this.query.sortBy === 'lastCreated' ? sortByLastCreated : sortByFirstCreated);
38597
+ return streams;
38598
+ };
38599
+ this.query = query;
38600
+ this.queryStreamController = new GetStreamsQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), paginationController);
38601
+ this.paginationController = paginationController;
38602
+ this.callback = callback.bind(this);
38603
+ this.loadPage({ initial: true });
38604
+ }
38605
+ notifyChange({ origin, loading, error }) {
38008
38606
  var _a;
38009
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38607
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38010
38608
  if (!collection)
38011
38609
  return;
38012
- collection.data = [...new Set([stream.streamId, ...collection.data])];
38013
- pushToCache(cacheKey, collection);
38014
- responder(collection, true);
38015
- };
38016
- const onFetch = (initial = false) => {
38017
- var _a, _b;
38018
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38019
- const streams = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
38020
- if (!initial && streams.length > 0 && !(collection === null || collection === void 0 ? void 0 : collection.params.page))
38610
+ let data = collection.data
38611
+ .map(streamId => pullFromCache(['stream', 'get', streamId]))
38612
+ .filter(Boolean)
38613
+ .map(stream => LinkedObject.stream(stream.data));
38614
+ if (!this.shouldNotify(data) && origin === 'event')
38021
38615
  return;
38022
- const query = createQuery(queryStreams, Object.assign(Object.assign({}, queryParams), { limit: initial ? limit : undefined, page: !initial ? collection === null || collection === void 0 ? void 0 : collection.params.page : undefined }));
38023
- runQuery(query, ({ data: result, error, loading, paging }) => {
38024
- const data = {
38025
- loading,
38026
- error,
38027
- params: { page: paging === null || paging === void 0 ? void 0 : paging.next },
38028
- data: streams,
38029
- };
38030
- if (result) {
38031
- data.data = [...new Set([...streams, ...result.map(getResolver('stream'))])];
38032
- }
38033
- pushToCache(cacheKey, data);
38034
- responder(data);
38035
- }, queryOptions(policy));
38036
- };
38037
- disposers.push(onStreamRecorded(realtimeRouter()), onStreamStarted(realtimeRouter()), onStreamStopped(realtimeRouter()));
38038
- onFetch(true);
38616
+ data = this.applyFilter(data);
38617
+ this.callback({
38618
+ onNextPage: () => this.loadPage({ initial: false, direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
38619
+ data,
38620
+ hasNextPage: !!this.paginationController.getNextToken(),
38621
+ loading,
38622
+ error,
38623
+ });
38624
+ }
38625
+ startSubscription() {
38626
+ return this.queryStreamController.subscribeRTE([
38627
+ { fn: onStreamRecorded, action: 'onStreamRecorded' },
38628
+ { fn: onStreamStarted, action: 'onStreamStarted' },
38629
+ { fn: onStreamStopped, action: 'onStreamStopped' },
38630
+ { fn: onStreamFlagged, action: 'onStreamFlagged' },
38631
+ { fn: onStreamTerminated, action: 'onStreamTerminated' },
38632
+ ]);
38633
+ }
38634
+ setup() {
38635
+ var _a;
38636
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
38637
+ if (!collection) {
38638
+ pushToCache(this.cacheKey, {
38639
+ data: [],
38640
+ params: {},
38641
+ });
38642
+ }
38643
+ }
38644
+ persistModel(response) {
38645
+ this.queryStreamController.saveToMainDB(response);
38646
+ }
38647
+ persistQueryStream({ response, direction, refresh, }) {
38648
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
38649
+ }
38650
+ }
38651
+
38652
+ const getStreams = (params, callback, config) => {
38653
+ const { log, cache, userId } = getActiveClient();
38654
+ if (!cache) {
38655
+ console.log(ENABLE_CACHE_MESSAGE);
38656
+ }
38657
+ const timestamp = Date.now();
38658
+ log(`getStreams(tmpid: ${timestamp}) > listen`);
38659
+ const liveCollection = new GetStreamsLiveCollectionController(params, callback);
38660
+ const disposers = liveCollection.startSubscription();
38661
+ const cacheKey = liveCollection.getCacheKey();
38662
+ disposers.push(() => {
38663
+ dropFromCache(cacheKey);
38664
+ });
38039
38665
  return () => {
38040
38666
  log(`getStreams(tmpid: ${timestamp}) > dispose`);
38041
38667
  disposers.forEach(fn => fn());
38042
38668
  };
38043
- };
38044
- /* end_public_function */
38669
+ };
38045
38670
 
38046
38671
  var index$3 = /*#__PURE__*/Object.freeze({
38047
38672
  __proto__: null,
@@ -38049,11 +38674,13 @@ var index$3 = /*#__PURE__*/Object.freeze({
38049
38674
  updateStream: updateStream,
38050
38675
  deleteStream: deleteStream,
38051
38676
  disposeStream: disposeStream,
38052
- queryStreams: queryStreams$1,
38677
+ queryStreams: queryStreams,
38053
38678
  getStream: getStream,
38054
38679
  onStreamStarted: onStreamStarted,
38055
38680
  onStreamStopped: onStreamStopped,
38056
38681
  onStreamRecorded: onStreamRecorded,
38682
+ onStreamFlagged: onStreamFlagged,
38683
+ onStreamTerminated: onStreamTerminated,
38057
38684
  getStreamById: getStreamById,
38058
38685
  getStreams: getStreams
38059
38686
  });
@@ -38386,7 +39013,7 @@ var index$2 = /*#__PURE__*/Object.freeze({
38386
39013
  getPoll: getPoll
38387
39014
  });
38388
39015
 
38389
- const privateKey = "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDHo80SecH7FuF2\nhFYnb+l26/VN8UMLXAQFLnxciNTEwkGVFMpdezlH8rU2HtUJL4RETogbAOLVY0XM\njs6sPn8G1nALmh9qeDpUtVqFOVtBHxEZ910TLOtQiunjqJKO5nWdqZ71EC3OFluR\niGQkO84BiIFbv37ub7xl3S8XarbtKoLcyVpkDHi+1wx1pgCAn6gtBUgckPL5NR8j\nLseabl3HAXQfhTCKo4tmOFM2Dxwl1IUMmIJrJg/aIU/U0tj/1Eoo7mG0JcNWX19l\nW3EecCbi0ncCJOrkUdwlBrcjaMayaX/ubEwyUeTGiLdyc4L3GRLHjyK8xgVNXRMH\nbZWJ2a5NAgMBAAECggEASxuE+35zTFO/XydKgmvIGcWL9FbgMlXb7Vcf0nBoG945\nbiz0NVc2paraIhJXc608xbYF3qLmtAE1MVBI0ORyRdBHNxY024l/6H6SH60Ed+uI\nM4ysp5ourY6Vj+DLwpdRiI9YDjqYAQDIUmhNxJP7XPhOMoZI6st+xZQBM34ic/bv\nAMSJm9OZphSp3+qXVkFZztr2mxD2EZSJJLYxi8BCdgM2qhazalbcJ6zDKHCZWVWm\n8RRxDGldyMb/237JxETzP40tAlzOZDmBAbUgEnurDJ93RVDIE3rbZUshwgeQd18a\nem096mWgvB1AIKYgsTAR3pw+V19YWAjq/glP6fz8wQKBgQD/oQq+ukKF0PRgBeM5\ngeTjSwsdGppQLmf5ndujvoiz/TpdjDEPu6R8kigQr1rG2t4K/yfdZoI8RdmJD1al\n3Q7N9hofooSy4rj6E3txzWZCHJjHad2cnCp/O26HiReGAl7wTcfTmNdiFHhZQzm5\nJBkvWAiwuvQMNfEbnXxw6/vIDwKBgQDH7fX8gsc77JLvAWgp1MaQN/sbqVb6JeT1\nFQfR8E/WFCSmzQBtNzd5KgYuCeelwr/8DyYytvN2BzCYZXp73gI1jF3YlW5jVn74\nOY6TwQ095digwo6Z0yuxopdIOApKgAkL9PRKgNrqAf3NAyMua6lOGifzjDojC3KU\nfylQmxMn4wKBgHp2B9O/H0dEBw5JQ8W0+JX6yWQz7mEjGiR2/1W+XXb8hQ1zr709\nw1r6Gb+EghRpnZ3fBpYGGbYOMFx8wKHM+N6qW3F0ReX8v2juFGE8aRSa5oYBrWzt\nU16Idjbv8hj84cZ1PJmdyvDtpYn9rpWHOZl4rxEbPvbqkIsOMyNVqdT5AoGAOSge\nmwIIU2le2FVeohbibXiToWTYKMuMmURZ5/r72AgKMmWJKbAPe+Q3wBG01/7FRBpQ\noU8Ma0HC8s6QJbliiEyIx9JwrJWd1vkdecBHONrtA4ibm/5zD2WcOllLF+FitLhi\n3qnX6+6F0IaFGFBPJrTzlv0P4dTz/OAdv52V7GECgYEA2TttOKBAqWllgOaZOkql\nLVMJVmgR7s6tLi1+cEP8ZcapV9aRbRzTAKXm4f8AEhtlG9F9kCOvHYCYGi6JaiWJ\nZkHjeex3T+eE6Di6y5Bm/Ift5jtVhJ4jCVwHOKTMej79NPUFTJfv8hCo29haBDv6\nRXFrv+T21KCcw8k3sJeJWWQ=\n-----END PRIVATE KEY-----";
39016
+ const privateKey = "-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDAARz+hmBgi8pJ\nQb8LeY41gtHhk+ACMwRfhsn7GqpqRQNG2qU0755mzZuVDUqjQMGSo8THJB7O+OJs\nflbZRkFXlFoFOVNw1UpNOgwEQZ6wB9oRwzepTJAfF1sVhm/o/ixvXh1zDFNDy6yZ\npXyiiJHUVxqyjllZhxnwdvjoVtDs6hW6awG09bB9nh/TTejlUKXoAgzqVwu/1QMu\nUVViET495elEe19aUarEy+oL2iKeXCEvqda/pWNBdbieFyJvvZ08HN8dPuT88wq2\njZLEAth1vrwQ2IAa4ktaLcBQdLJgIkrbDvAiVZ8lQAjS/bq5vXQikTGvoPlC5bbn\nvuOM/3eLAgMBAAECggEAVZ+peHAghq2QVj71nX5lxsNCKaCyYwixSJBpfouTt7Rz\nE6PpzMOXFi1W1o+I22jDakuSM2SOQKqI/u0QefB0r0O/KVk5NrZHXk0mkrdYtxOp\nUgaGyf8UvmjB+8VqHrNKyZdk9qtmbnNj01kTTcAtmE4H39zPR7eR/8Rul94vaZbs\nwCnKJS3mLT3JxyGug6lxanveKkjG+CKC1nJQYWaxCJxaFSzbwXQPvDhB+TvrIbee\npd5v4EAyEJohpr+T9oDGGJkb/KARBZCtwLyB976PKJwwBA8MRVL1i5QwawuMiMq5\nUtnOnbGKtCeFzaLbNU0Qi8bqyims84EQxC6DOu1fkQKBgQDdvsoBsEhsOXV7hlIJ\naEd0eSJZVkdqimxH8uGoMM2FeNaOrcB6yBXqTSP0R3OIyf8eaY6yjRvP30ZNXcll\n/gD3O1Mu6YmWQdt1W2WA6pKOsUuPXasf0pdOF7IiFZKlSabz5YHXFqwVuqm8loaj\nsXel3YWqPVdHiankE7tz+3ssnQKBgQDdqi4TNdD1MdEpihx19jr0QjUiXW3939FK\nqp30HESPEGDGQzXdmJgif9HhZb+cJSuWaHEbjgBrYahvgCF+y6LbEpOD+D/dmT+s\nDEAQaR84sah6dokwPjV8fjBSrcVFjCS+doxv0d3p/9OUEeyUhFrY03nxtIEYkLIE\n/Zvn37b4RwKBgQCLENVFe9XfsaVhQ5r9dV2iyTlmh7qgMZG5CbTFs12hQGhm8McO\n+Z7s41YSJCFr/yq1WwP4LJDtrBw99vyQr1zRsG35tNLp3gGRNzGQSQyC2uQFVHw2\np+7mNewsfhUK/gbrXNsyFnDz6635rPlhfbII3sWuP2wWXFqkxE9CbMwR7QKBgQC6\nawDMzxmo2/iYArrkyevSuEuPVxvFwpF1RgAI6C0QVCnPE38dmdN4UB7mfHekje4W\nVEercMURidPp0cxZolCYBQtilUjAyL0vqC3In1/Ogjq6oy3FEMxSop1pKxMY5j+Q\nnoqFD+6deLUrddeNH7J3X4LSr4dSbX4JjG+tlgt+yQKBgQCuwTL4hA6KqeInQ0Ta\n9VQX5Qr8hFlqJz1gpymi/k63tW/Ob8yedbg3WWNWyShwRMFYyY9S81ITFWM95uL6\nvF3x9rmRjwElJw9PMwVu6dmf/CO0Z1wzXSp2VVD12gbrUD/0/d7MUoJ9LgC8X8f/\nn0txLHYGHbx+nf95+JUg6lV3hg==\n-----END PRIVATE KEY-----";
38390
39017
  /*
38391
39018
  * The crypto algorithm used for importing key and signing string
38392
39019
  */
@@ -39531,7 +40158,7 @@ class StoryLiveCollectionController extends LiveCollectionController {
39531
40158
  this.queryStreamController = new StoryQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), paginationController);
39532
40159
  this.paginationController = paginationController;
39533
40160
  this.callback = callback.bind(this);
39534
- this.loadPage(true);
40161
+ this.loadPage({ initial: true });
39535
40162
  }
39536
40163
  setup() {
39537
40164
  var _a;
@@ -39713,7 +40340,7 @@ class GlobalStoryLiveCollectionController extends LiveCollectionController {
39713
40340
  this.queryStreamController = new GlobalStoryQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), paginationController);
39714
40341
  this.paginationController = paginationController;
39715
40342
  this.callback = callback.bind(this);
39716
- this.loadPage(true);
40343
+ this.loadPage({ initial: true });
39717
40344
  }
39718
40345
  setup() {
39719
40346
  var _a;
@@ -39749,7 +40376,7 @@ class GlobalStoryLiveCollectionController extends LiveCollectionController {
39749
40376
  return rest;
39750
40377
  });
39751
40378
  this.callback({
39752
- onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
40379
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
39753
40380
  data,
39754
40381
  hasNextPage: !!this.paginationController.getNextToken(),
39755
40382
  loading,
@@ -39855,4 +40482,4 @@ const createUserToken = async (apiKey, apiRegion, params) => {
39855
40482
  return { accessToken: data.accessToken };
39856
40483
  };
39857
40484
 
39858
- export { API_REGIONS, index$7 as CategoryRepository, index$b as ChannelRepository, index$k as Client, index$4 as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$8 as CommunityRepository, ContentFeedType, DefaultCommunityPostSetting, index$6 as FeedRepository, index$h as FileRepository, FileType, index$1 as LiveStreamPlayer, MessageContentType, index$f as MessageRepository, index$2 as PollRepository, PostContentType, index$5 as PostRepository, index$g as ReactionRepository, index as StoryRepository, index$3 as StreamRepository, index$e as SubChannelRepository, SubscriptionLevels, index$i as UserRepository, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, backupCache, createQuery, createReport, createUserToken, deleteReport, disableCache, dropFromCache, enableCache, filterByChannelMembership, filterByCommunityMembership, filterByFeedType, filterByPostDataTypes, filterByPropEquality, filterByPropInclusion, filterByPropIntersection, filterBySearchTerm, filterByStringComparePartially, getChannelTopic, getCommentTopic, getCommunityStoriesTopic, getCommunityTopic, getMarkedMessageTopic, getMarkerUserFeedTopic, getMessageTopic, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPostTopic, getRole, getSmartFeedChannelTopic, getSmartFeedMessageTopic, getSmartFeedSubChannelTopic, getStoryTopic, getSubChannelTopic, getUserTopic, isAfterBefore, isAfterBeforeRaw, isCachable, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkip, mergeInCache, onChannelMarkerFetched, onFeedMarkerFetched, onFeedMarkerUpdated, onMessageMarked, onMessageMarkerFetched, onSubChannelMarkerFetched, onSubChannelMarkerUpdated, onUserMarkerFetched, onUserMarkerFetchedLegacy, pullFromCache, pushToCache, queryCache, queryOptions, queryRoles, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByFirstUpdated, sortByLastActivity, sortByLastCreated, sortByLastUpdated, sortByLocalSortingDate, sortByName, sortBySegmentNumber, subscribeTopic, toPage, toPageRaw, toToken, upsertInCache, wipeCache };
40485
+ export { API_REGIONS, index$7 as CategoryRepository, index$b as ChannelRepository, index$k as Client, index$5 as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$8 as CommunityRepository, ContentFeedType, DefaultCommunityPostSetting, index$6 as FeedRepository, index$h as FileRepository, FileType, index$1 as LiveStreamPlayer, MessageContentType, index$f as MessageRepository, index$2 as PollRepository, PostContentType, index$4 as PostRepository, index$g as ReactionRepository, index as StoryRepository, index$3 as StreamRepository, index$e as SubChannelRepository, SubscriptionLevels, index$i as UserRepository, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, backupCache, createQuery, createReport, createUserToken, deleteReport, disableCache, dropFromCache, enableCache, filterByChannelMembership, filterByCommunityMembership, filterByFeedType, filterByPostDataTypes, filterByPropEquality, filterByPropInclusion, filterByPropIntersection, filterBySearchTerm, filterByStringComparePartially, getChannelTopic, getCommentTopic, getCommunityStoriesTopic, getCommunityTopic, getMarkedMessageTopic, getMarkerUserFeedTopic, getMessageTopic, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPostTopic, getRole, getSmartFeedChannelTopic, getSmartFeedMessageTopic, getSmartFeedSubChannelTopic, getStoryTopic, getSubChannelTopic, getUserTopic, isAfterBefore, isAfterBeforeRaw, isCachable, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkip, mergeInCache, onChannelMarkerFetched, onFeedMarkerFetched, onFeedMarkerUpdated, onMessageMarked, onMessageMarkerFetched, onSubChannelMarkerFetched, onSubChannelMarkerUpdated, onUserMarkerFetched, onUserMarkerFetchedLegacy, pullFromCache, pushToCache, queryCache, queryOptions, queryRoles, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByFirstUpdated, sortByLastActivity, sortByLastCreated, sortByLastUpdated, sortByLocalSortingDate, sortByName, sortBySegmentNumber, subscribeTopic, toPage, toPageRaw, toToken, upsertInCache, wipeCache };