@amityco/ts-sdk 7.11.1-8ef0bbb7.0 → 7.11.1-b4621cc1.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 (187) hide show
  1. package/dist/@types/core/events.d.ts +36 -13
  2. package/dist/@types/core/events.d.ts.map +1 -1
  3. package/dist/@types/core/model.d.ts +6 -3
  4. package/dist/@types/core/model.d.ts.map +1 -1
  5. package/dist/@types/core/payload.d.ts +28 -4
  6. package/dist/@types/core/payload.d.ts.map +1 -1
  7. package/dist/@types/core/permissions.d.ts +5 -1
  8. package/dist/@types/core/permissions.d.ts.map +1 -1
  9. package/dist/@types/core/transport.d.ts +3 -0
  10. package/dist/@types/core/transport.d.ts.map +1 -1
  11. package/dist/@types/domains/community.d.ts +11 -1
  12. package/dist/@types/domains/community.d.ts.map +1 -1
  13. package/dist/@types/domains/content.d.ts +1 -4
  14. package/dist/@types/domains/content.d.ts.map +1 -1
  15. package/dist/@types/domains/event.d.ts +103 -0
  16. package/dist/@types/domains/event.d.ts.map +1 -0
  17. package/dist/@types/domains/notification.d.ts +3 -1
  18. package/dist/@types/domains/notification.d.ts.map +1 -1
  19. package/dist/@types/domains/partials.d.ts +2 -2
  20. package/dist/@types/domains/partials.d.ts.map +1 -1
  21. package/dist/@types/domains/post.d.ts +0 -2
  22. package/dist/@types/domains/post.d.ts.map +1 -1
  23. package/dist/@types/index.d.ts +1 -2
  24. package/dist/@types/index.d.ts.map +1 -1
  25. package/dist/core/events.d.ts +3 -3
  26. package/dist/core/events.d.ts.map +1 -1
  27. package/dist/core/model/idResolvers.d.ts.map +1 -1
  28. package/dist/core/model/index.d.ts.map +1 -1
  29. package/dist/eventRepository/api/createEvent.d.ts +16 -0
  30. package/dist/eventRepository/api/createEvent.d.ts.map +1 -0
  31. package/dist/eventRepository/api/deleteEvent.d.ts +15 -0
  32. package/dist/eventRepository/api/deleteEvent.d.ts.map +1 -0
  33. package/dist/eventRepository/api/index.d.ts +4 -0
  34. package/dist/eventRepository/api/index.d.ts.map +1 -0
  35. package/dist/eventRepository/api/updateEvent.d.ts +17 -0
  36. package/dist/eventRepository/api/updateEvent.d.ts.map +1 -0
  37. package/dist/eventRepository/events/enums.d.ts +8 -0
  38. package/dist/eventRepository/events/enums.d.ts.map +1 -0
  39. package/dist/eventRepository/events/index.d.ts +11 -0
  40. package/dist/eventRepository/events/index.d.ts.map +1 -0
  41. package/dist/eventRepository/events/onEventCreated.d.ts +17 -0
  42. package/dist/eventRepository/events/onEventCreated.d.ts.map +1 -0
  43. package/dist/eventRepository/events/onEventDeleted.d.ts +17 -0
  44. package/dist/eventRepository/events/onEventDeleted.d.ts.map +1 -0
  45. package/dist/eventRepository/events/onEventUpdated.d.ts +17 -0
  46. package/dist/eventRepository/events/onEventUpdated.d.ts.map +1 -0
  47. package/dist/eventRepository/events/onLocalEventCreated.d.ts +17 -0
  48. package/dist/eventRepository/events/onLocalEventCreated.d.ts.map +1 -0
  49. package/dist/eventRepository/events/onLocalEventDeleted.d.ts +17 -0
  50. package/dist/eventRepository/events/onLocalEventDeleted.d.ts.map +1 -0
  51. package/dist/eventRepository/events/onLocalEventUpdated.d.ts +17 -0
  52. package/dist/eventRepository/events/onLocalEventUpdated.d.ts.map +1 -0
  53. package/dist/eventRepository/events/onLocalRSVPCreated.d.ts +17 -0
  54. package/dist/eventRepository/events/onLocalRSVPCreated.d.ts.map +1 -0
  55. package/dist/eventRepository/events/onLocalRSVPUpdated.d.ts +17 -0
  56. package/dist/eventRepository/events/onLocalRSVPUpdated.d.ts.map +1 -0
  57. package/dist/eventRepository/events/onRSVPCreated.d.ts +17 -0
  58. package/dist/eventRepository/events/onRSVPCreated.d.ts.map +1 -0
  59. package/dist/eventRepository/events/onRSVPUpdated.d.ts +17 -0
  60. package/dist/eventRepository/events/onRSVPUpdated.d.ts.map +1 -0
  61. package/dist/eventRepository/index.d.ts.map +1 -0
  62. package/dist/eventRepository/internalApi/createRSVP.d.ts +16 -0
  63. package/dist/eventRepository/internalApi/createRSVP.d.ts.map +1 -0
  64. package/dist/eventRepository/internalApi/getEvent.d.ts +32 -0
  65. package/dist/eventRepository/internalApi/getEvent.d.ts.map +1 -0
  66. package/dist/eventRepository/internalApi/getMyRSVP.d.ts +32 -0
  67. package/dist/eventRepository/internalApi/getMyRSVP.d.ts.map +1 -0
  68. package/dist/eventRepository/internalApi/index.d.ts +5 -0
  69. package/dist/eventRepository/internalApi/index.d.ts.map +1 -0
  70. package/dist/eventRepository/internalApi/updateRSVP.d.ts +17 -0
  71. package/dist/eventRepository/internalApi/updateRSVP.d.ts.map +1 -0
  72. package/dist/eventRepository/observers/getEvent.d.ts +21 -0
  73. package/dist/eventRepository/observers/getEvent.d.ts.map +1 -0
  74. package/dist/eventRepository/observers/getEvents/LiveCollectionController.d.ts +13 -0
  75. package/dist/eventRepository/observers/getEvents/LiveCollectionController.d.ts.map +1 -0
  76. package/dist/eventRepository/observers/getEvents/PaginationController.d.ts +5 -0
  77. package/dist/eventRepository/observers/getEvents/PaginationController.d.ts.map +1 -0
  78. package/dist/eventRepository/observers/getEvents/QueryStreamController.d.ts +15 -0
  79. package/dist/eventRepository/observers/getEvents/QueryStreamController.d.ts.map +1 -0
  80. package/dist/eventRepository/observers/getEvents.d.ts +12 -0
  81. package/dist/eventRepository/observers/getEvents.d.ts.map +1 -0
  82. package/dist/eventRepository/observers/getMyEvents/LiveCollectionController.d.ts +13 -0
  83. package/dist/eventRepository/observers/getMyEvents/LiveCollectionController.d.ts.map +1 -0
  84. package/dist/eventRepository/observers/getMyEvents/PaginationController.d.ts +5 -0
  85. package/dist/eventRepository/observers/getMyEvents/PaginationController.d.ts.map +1 -0
  86. package/dist/eventRepository/observers/getMyEvents/QueryStreamController.d.ts +15 -0
  87. package/dist/eventRepository/observers/getMyEvents/QueryStreamController.d.ts.map +1 -0
  88. package/dist/eventRepository/observers/getMyEvents.d.ts +12 -0
  89. package/dist/eventRepository/observers/getMyEvents.d.ts.map +1 -0
  90. package/dist/eventRepository/observers/getRSVPs/LiveCollectionController.d.ts +13 -0
  91. package/dist/eventRepository/observers/getRSVPs/LiveCollectionController.d.ts.map +1 -0
  92. package/dist/eventRepository/observers/getRSVPs/PaginationController.d.ts +5 -0
  93. package/dist/eventRepository/observers/getRSVPs/PaginationController.d.ts.map +1 -0
  94. package/dist/eventRepository/observers/getRSVPs/QueryStreamController.d.ts +15 -0
  95. package/dist/eventRepository/observers/getRSVPs/QueryStreamController.d.ts.map +1 -0
  96. package/dist/eventRepository/observers/getRSVPs.d.ts +12 -0
  97. package/dist/eventRepository/observers/getRSVPs.d.ts.map +1 -0
  98. package/dist/eventRepository/observers/index.d.ts +5 -0
  99. package/dist/eventRepository/observers/index.d.ts.map +1 -0
  100. package/dist/eventRepository/utils/createEventEventSubscriber.d.ts +2 -0
  101. package/dist/eventRepository/utils/createEventEventSubscriber.d.ts.map +1 -0
  102. package/dist/eventRepository/utils/createEventResponseSubscriber.d.ts +2 -0
  103. package/dist/eventRepository/utils/createEventResponseSubscriber.d.ts.map +1 -0
  104. package/dist/eventRepository/utils/index.d.ts +5 -0
  105. package/dist/eventRepository/utils/index.d.ts.map +1 -0
  106. package/dist/eventRepository/utils/prepareEventPayload.d.ts +2 -0
  107. package/dist/eventRepository/utils/prepareEventPayload.d.ts.map +1 -0
  108. package/dist/eventRepository/utils/prepareEventResponsePayload.d.ts +2 -0
  109. package/dist/eventRepository/utils/prepareEventResponsePayload.d.ts.map +1 -0
  110. package/dist/index.cjs.js +3108 -2789
  111. package/dist/index.d.ts +1 -1
  112. package/dist/index.d.ts.map +1 -1
  113. package/dist/index.esm.js +2094 -1775
  114. package/dist/index.umd.js +3 -3
  115. package/dist/messagePreview/utils/getChannelMessagePreviewWithUser.d.ts +1 -1
  116. package/dist/messagePreview/utils/getSubChannelMessagePreviewWithUser.d.ts +1 -1
  117. package/dist/utils/linkedObject/eventLinkObject.d.ts +2 -0
  118. package/dist/utils/linkedObject/eventLinkObject.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/postLinkedObject.d.ts.map +1 -1
  122. package/dist/utils/postTypePredicate.d.ts +0 -1
  123. package/dist/utils/postTypePredicate.d.ts.map +1 -1
  124. package/dist/utils/tests/dummy/comment.d.ts +1 -1
  125. package/package.json +1 -1
  126. package/dist/@types/domains/room.d.ts +0 -71
  127. package/dist/@types/domains/room.d.ts.map +0 -1
  128. package/dist/roomRepository/api/createRoom.d.ts +0 -24
  129. package/dist/roomRepository/api/createRoom.d.ts.map +0 -1
  130. package/dist/roomRepository/api/deleteRoom.d.ts +0 -16
  131. package/dist/roomRepository/api/deleteRoom.d.ts.map +0 -1
  132. package/dist/roomRepository/api/getRecordedUrl.d.ts +0 -19
  133. package/dist/roomRepository/api/getRecordedUrl.d.ts.map +0 -1
  134. package/dist/roomRepository/api/getRoomToken.d.ts +0 -16
  135. package/dist/roomRepository/api/getRoomToken.d.ts.map +0 -1
  136. package/dist/roomRepository/api/index.d.ts +0 -7
  137. package/dist/roomRepository/api/index.d.ts.map +0 -1
  138. package/dist/roomRepository/api/stopRoom.d.ts +0 -16
  139. package/dist/roomRepository/api/stopRoom.d.ts.map +0 -1
  140. package/dist/roomRepository/api/updateRoom.d.ts +0 -24
  141. package/dist/roomRepository/api/updateRoom.d.ts.map +0 -1
  142. package/dist/roomRepository/events/index.d.ts +0 -12
  143. package/dist/roomRepository/events/index.d.ts.map +0 -1
  144. package/dist/roomRepository/events/onRoomCreated.d.ts +0 -17
  145. package/dist/roomRepository/events/onRoomCreated.d.ts.map +0 -1
  146. package/dist/roomRepository/events/onRoomDeleted.d.ts +0 -17
  147. package/dist/roomRepository/events/onRoomDeleted.d.ts.map +0 -1
  148. package/dist/roomRepository/events/onRoomEndBroadcasting.d.ts +0 -17
  149. package/dist/roomRepository/events/onRoomEndBroadcasting.d.ts.map +0 -1
  150. package/dist/roomRepository/events/onRoomParticipantInviting.d.ts +0 -17
  151. package/dist/roomRepository/events/onRoomParticipantInviting.d.ts.map +0 -1
  152. package/dist/roomRepository/events/onRoomParticipantJoined.d.ts +0 -17
  153. package/dist/roomRepository/events/onRoomParticipantJoined.d.ts.map +0 -1
  154. package/dist/roomRepository/events/onRoomParticipantLeft.d.ts +0 -17
  155. package/dist/roomRepository/events/onRoomParticipantLeft.d.ts.map +0 -1
  156. package/dist/roomRepository/events/onRoomRecordedAvailable.d.ts +0 -17
  157. package/dist/roomRepository/events/onRoomRecordedAvailable.d.ts.map +0 -1
  158. package/dist/roomRepository/events/onRoomStartBroadcasting.d.ts +0 -17
  159. package/dist/roomRepository/events/onRoomStartBroadcasting.d.ts.map +0 -1
  160. package/dist/roomRepository/events/onRoomStopped.d.ts +0 -17
  161. package/dist/roomRepository/events/onRoomStopped.d.ts.map +0 -1
  162. package/dist/roomRepository/events/onRoomUpdated.d.ts +0 -17
  163. package/dist/roomRepository/events/onRoomUpdated.d.ts.map +0 -1
  164. package/dist/roomRepository/events/onRoomWaitingReconnect.d.ts +0 -17
  165. package/dist/roomRepository/events/onRoomWaitingReconnect.d.ts.map +0 -1
  166. package/dist/roomRepository/index.d.ts.map +0 -1
  167. package/dist/roomRepository/internalApi/getRoomById.d.ts +0 -5
  168. package/dist/roomRepository/internalApi/getRoomById.d.ts.map +0 -1
  169. package/dist/roomRepository/internalApi/index.d.ts +0 -2
  170. package/dist/roomRepository/internalApi/index.d.ts.map +0 -1
  171. package/dist/roomRepository/observers/enums.d.ts +0 -10
  172. package/dist/roomRepository/observers/enums.d.ts.map +0 -1
  173. package/dist/roomRepository/observers/getRoom.d.ts +0 -2
  174. package/dist/roomRepository/observers/getRoom.d.ts.map +0 -1
  175. package/dist/roomRepository/observers/getRooms/RoomLiveCollectionController.d.ts +0 -14
  176. package/dist/roomRepository/observers/getRooms/RoomLiveCollectionController.d.ts.map +0 -1
  177. package/dist/roomRepository/observers/getRooms/RoomPaginationController.d.ts +0 -5
  178. package/dist/roomRepository/observers/getRooms/RoomPaginationController.d.ts.map +0 -1
  179. package/dist/roomRepository/observers/getRooms/RoomQueryStreamController.d.ts +0 -15
  180. package/dist/roomRepository/observers/getRooms/RoomQueryStreamController.d.ts.map +0 -1
  181. package/dist/roomRepository/observers/getRooms.d.ts +0 -29
  182. package/dist/roomRepository/observers/getRooms.d.ts.map +0 -1
  183. package/dist/roomRepository/observers/index.d.ts +0 -3
  184. package/dist/roomRepository/observers/index.d.ts.map +0 -1
  185. package/dist/roomRepository/observers/utils.d.ts +0 -6
  186. package/dist/roomRepository/observers/utils.d.ts.map +0 -1
  187. /package/dist/{roomRepository → eventRepository}/index.d.ts +0 -0
package/dist/index.esm.js CHANGED
@@ -112,7 +112,6 @@ const PostContentType = Object.freeze({
112
112
  POLL: 'poll',
113
113
  CLIP: 'clip',
114
114
  AUDIO: 'audio',
115
- ROOM: 'room',
116
115
  });
117
116
  const PostStructureType = Object.freeze({
118
117
  TEXT: 'text',
@@ -178,6 +177,29 @@ var FeedSourceEnum;
178
177
  FeedSourceEnum["User"] = "user";
179
178
  })(FeedSourceEnum || (FeedSourceEnum = {}));
180
179
 
180
+ var AmityEventType;
181
+ (function (AmityEventType) {
182
+ AmityEventType["Virtual"] = "virtual";
183
+ AmityEventType["InPerson"] = "in_person";
184
+ })(AmityEventType || (AmityEventType = {}));
185
+ var AmityEventOriginType;
186
+ (function (AmityEventOriginType) {
187
+ AmityEventOriginType["Community"] = "community";
188
+ AmityEventOriginType["User"] = "user";
189
+ })(AmityEventOriginType || (AmityEventOriginType = {}));
190
+ var AmityEventStatus;
191
+ (function (AmityEventStatus) {
192
+ AmityEventStatus["Scheduled"] = "scheduled";
193
+ AmityEventStatus["Live"] = "live";
194
+ AmityEventStatus["Ended"] = "ended";
195
+ AmityEventStatus["Cancelled"] = "cancelled";
196
+ })(AmityEventStatus || (AmityEventStatus = {}));
197
+ var AmityEventResponseStatus;
198
+ (function (AmityEventResponseStatus) {
199
+ AmityEventResponseStatus["Going"] = "going";
200
+ AmityEventResponseStatus["NotGoing"] = "not_going";
201
+ })(AmityEventResponseStatus || (AmityEventResponseStatus = {}));
202
+
181
203
  function getVersion() {
182
204
  try {
183
205
  // the string ''v7.11.0-esm'' should be replaced by actual value by @rollup/plugin-replace
@@ -626,7 +648,9 @@ const idResolvers = {
626
648
  notificationTraySeen: ({ userId }) => userId,
627
649
  invitation: ({ _id }) => _id,
628
650
  joinRequest: ({ joinRequestId }) => joinRequestId,
629
- room: ({ roomId }) => roomId,
651
+ event: ({ eventId }) => eventId,
652
+ eventResponse: ({ eventId }) => eventId,
653
+ discussionCommunity: ({ communityId }) => communityId,
630
654
  };
631
655
  /**
632
656
  * Retrieve the id resolver matching a domain name
@@ -682,7 +706,9 @@ const PAYLOAD2MODEL = {
682
706
  notificationTrayItems: 'notificationTrayItem',
683
707
  invitations: 'invitation',
684
708
  joinRequests: 'joinRequest',
685
- rooms: 'room',
709
+ events: 'event',
710
+ eventResponse: 'eventResponse',
711
+ discussionCommunities: 'discussionCommunity',
686
712
  };
687
713
  /** hidden */
688
714
  const isOutdated = (prevData, nextData) => {
@@ -28302,12 +28328,6 @@ function isAmityAudioPost(post) {
28302
28328
  'fileId' in post.data &&
28303
28329
  post.dataType === 'audio');
28304
28330
  }
28305
- function isAmityRoomPost(post) {
28306
- return !!(post.data &&
28307
- typeof post.data !== 'string' &&
28308
- 'roomId' in post.data &&
28309
- post.dataType === 'room');
28310
- }
28311
28331
 
28312
28332
  const postLinkedObject = (post) => {
28313
28333
  return shallowClone(post, {
@@ -28402,12 +28422,6 @@ const postLinkedObject = (post) => {
28402
28422
  ? (_b = pullFromCache(['file', 'get', (_a = post === null || post === void 0 ? void 0 : post.data) === null || _a === void 0 ? void 0 : _a.fileId])) === null || _b === void 0 ? void 0 : _b.data
28403
28423
  : undefined;
28404
28424
  },
28405
- getRoomInfo() {
28406
- var _a, _b;
28407
- if (!isAmityRoomPost(post))
28408
- return;
28409
- return (_b = pullFromCache(['room', 'get', (_a = post === null || post === void 0 ? void 0 : post.data) === null || _a === void 0 ? void 0 : _a.roomId])) === null || _b === void 0 ? void 0 : _b.data;
28410
- },
28411
28425
  });
28412
28426
  };
28413
28427
 
@@ -29765,6 +29779,239 @@ const communityLinkedObject = (community) => {
29765
29779
  } });
29766
29780
  };
29767
29781
 
29782
+ const prepareEventResponsePayload = (rawPayload) => {
29783
+ return {
29784
+ status: rawPayload.eventResponses[0].status,
29785
+ eventId: rawPayload.eventResponses[0].eventId,
29786
+ event: rawPayload.events,
29787
+ userId: rawPayload.eventResponses[0].userId,
29788
+ user: rawPayload.users.map(convertRawUserToInternalUser),
29789
+ };
29790
+ };
29791
+
29792
+ /* begin_public_function
29793
+ id: event.rsvp.create
29794
+ */
29795
+ /**
29796
+ * ```js
29797
+ * import { event } from '@amityco/ts-sdk'
29798
+ * const response = await event.createRSVP(eventId, status)
29799
+ * ```
29800
+ *
29801
+ * Creates an {@link Amity.InternalEvent}
29802
+ *
29803
+ * @param bundle The data necessary to create a new {@link Amity.InternalEvent}
29804
+ * @returns The newly created {@link Amity.InternalEvent}
29805
+ *
29806
+ * @category Event API
29807
+ * @async
29808
+ */
29809
+ const createRSVP = async (eventId, status) => {
29810
+ const client = getActiveClient();
29811
+ client.log('event/createRSVP', eventId, status);
29812
+ const { data: payload } = await client.http.post(`/api/v1/events/${eventId}/rsvp`, { status });
29813
+ fireEvent('local.rsvp.created', payload);
29814
+ const data = prepareEventResponsePayload(payload);
29815
+ const cachedAt = client.cache && Date.now();
29816
+ if (client.cache)
29817
+ ingestInCache({ eventResponses: [data] }, { cachedAt });
29818
+ return {
29819
+ data,
29820
+ cachedAt,
29821
+ };
29822
+ };
29823
+ /* end_public_function */
29824
+
29825
+ /* begin_public_function
29826
+ id: event.update
29827
+ */
29828
+ /**
29829
+ * ```js
29830
+ * import { event } from '@amityco/ts-sdk'
29831
+ * const response = await event.updateRSVP(eventId, status)
29832
+ * ```
29833
+ *
29834
+ * Updates an {@link Amity.EventResponse}
29835
+ *
29836
+ * @param eventId The ID of the {@link Amity.EventResponse} to edit
29837
+ * @param bundle The data necessary to update an existing {@link Amity.EventResponse}
29838
+ * @returns the updated {@link Amity.EventResponse}
29839
+ *
29840
+ * @category Event API
29841
+ * @async
29842
+ */
29843
+ const updateRSVP = async (eventId, status) => {
29844
+ const client = getActiveClient();
29845
+ client.log('event/updateRSVP', eventId, status);
29846
+ const { data: payload } = await client.http.put(`/api/v1/events/${eventId}/rsvp`, { status });
29847
+ fireEvent('local.rsvp.updated', payload);
29848
+ const data = prepareEventResponsePayload(payload);
29849
+ const cachedAt = client.cache && Date.now();
29850
+ if (client.cache)
29851
+ ingestInCache({ eventResponses: [data] }, { cachedAt });
29852
+ return {
29853
+ data,
29854
+ cachedAt,
29855
+ };
29856
+ };
29857
+ /* end_public_function */
29858
+
29859
+ const prepareEventPayload = (rawPayload) => {
29860
+ return Object.assign(Object.assign({}, rawPayload), { users: rawPayload.users.map(convertRawUserToInternalUser) });
29861
+ };
29862
+
29863
+ const createEventEventSubscriber = (event, callback) => {
29864
+ const client = getActiveClient();
29865
+ const filter = (payload) => {
29866
+ const unpackedPayload = prepareEventPayload(payload);
29867
+ if (!client.cache) {
29868
+ callback(unpackedPayload.events[0]);
29869
+ }
29870
+ else {
29871
+ ingestInCache(unpackedPayload);
29872
+ const event = pullFromCache([
29873
+ 'event',
29874
+ 'get',
29875
+ unpackedPayload.events[0].eventId,
29876
+ ]);
29877
+ callback(event.data);
29878
+ }
29879
+ };
29880
+ return createEventSubscriber(client, event, event, filter);
29881
+ };
29882
+
29883
+ const createEventResponseSubscriber = (event, callback) => {
29884
+ const client = getActiveClient();
29885
+ const filter = (payload) => {
29886
+ const unpackedPayload = prepareEventResponsePayload(payload);
29887
+ if (!client.cache) {
29888
+ callback(unpackedPayload);
29889
+ }
29890
+ else {
29891
+ ingestInCache(unpackedPayload.event[0]);
29892
+ const eventResponse = pullFromCache([
29893
+ 'eventResponse',
29894
+ 'get',
29895
+ payload.eventResponses[0].eventId,
29896
+ ]);
29897
+ callback(eventResponse.data);
29898
+ }
29899
+ };
29900
+ return createEventSubscriber(client, event, event, filter);
29901
+ };
29902
+
29903
+ /* begin_public_function
29904
+ id: event.rsvp.me
29905
+ */
29906
+ /**
29907
+ * ```js
29908
+ * import { event } from '@amityco/ts-sdk'
29909
+ * const myRSVP = await event.getMyRSVP()
29910
+ * ```
29911
+ *
29912
+ * Joins a {@link Amity.EventResponse} object
29913
+ *
29914
+ * @param eventId the {@link Amity.EventResponse} to get RSVP for
29915
+ * @returns A success boolean if the {@link Amity.EventResponse} RSVP was retrieved
29916
+ *
29917
+ * @category Event API
29918
+ * @async
29919
+ */
29920
+ const getMyRSVP = async (eventId) => {
29921
+ const client = getActiveClient();
29922
+ client.log('event/getMyRSVP', eventId);
29923
+ const { data: payload } = await client.http.get(`/api/v1/events/${eventId}/me/rsvp`);
29924
+ const data = prepareEventResponsePayload(payload);
29925
+ const cachedAt = client.cache && Date.now();
29926
+ if (client.cache)
29927
+ ingestInCache({ eventResponses: [data] }, { cachedAt });
29928
+ return {
29929
+ data,
29930
+ cachedAt,
29931
+ };
29932
+ };
29933
+ /* end_public_function */
29934
+ /**
29935
+ * ```js
29936
+ * import { event } from '@amityco/ts-sdk'
29937
+ * const event = event.getMyRSVP.locally(eventId)
29938
+ * ```
29939
+ *
29940
+ * Fetches a {@link Amity.EventResponse} object in cache
29941
+ *
29942
+ * @param eventId the ID of the {@link Amity.EventResponse} to fetch
29943
+ * @returns the associated {@link Amity.EventResponse} object
29944
+ *
29945
+ * @category Event API
29946
+ */
29947
+ getMyRSVP.locally = (eventId) => {
29948
+ const client = getActiveClient();
29949
+ client.log('event/getMyRSVP.locally', eventId);
29950
+ if (!client.cache)
29951
+ return;
29952
+ const cache = pullFromCache(['event', 'getMyRSVP', eventId]);
29953
+ if (!cache)
29954
+ return;
29955
+ return {
29956
+ data: cache.data,
29957
+ cachedAt: cache.cachedAt,
29958
+ };
29959
+ };
29960
+
29961
+ const eventLinkedObject = (event) => {
29962
+ return Object.assign(Object.assign({}, event), { get creator() {
29963
+ const cacheData = pullFromCache(['user', 'get', event.userId]);
29964
+ if (!(cacheData === null || cacheData === void 0 ? void 0 : cacheData.data))
29965
+ return;
29966
+ return userLinkedObject(cacheData.data);
29967
+ },
29968
+ get discussionCommunity() {
29969
+ if (!event.discussionCommunityId)
29970
+ return;
29971
+ const cacheData = pullFromCache([
29972
+ 'discussionCommunity',
29973
+ 'get',
29974
+ event.discussionCommunityId,
29975
+ ]);
29976
+ if (!(cacheData === null || cacheData === void 0 ? void 0 : cacheData.data))
29977
+ return;
29978
+ return communityLinkedObject(cacheData.data);
29979
+ },
29980
+ get targetCommunity() {
29981
+ if (!event.originId)
29982
+ return;
29983
+ const cacheData = pullFromCache(['community', 'get', event.originId]);
29984
+ if (!(cacheData === null || cacheData === void 0 ? void 0 : cacheData.data))
29985
+ return;
29986
+ return communityLinkedObject(cacheData.data);
29987
+ },
29988
+ get coverImage() {
29989
+ if (!event.coverImageFileId)
29990
+ return;
29991
+ const cacheData = pullFromCache(['file', 'get', event.coverImageFileId]);
29992
+ if (!(cacheData === null || cacheData === void 0 ? void 0 : cacheData.data))
29993
+ return;
29994
+ return cacheData.data;
29995
+ },
29996
+ get liveStream() {
29997
+ if (!event.livestreamId)
29998
+ return;
29999
+ const cacheData = pullFromCache(['stream', 'get', event.livestreamId]);
30000
+ if (!(cacheData === null || cacheData === void 0 ? void 0 : cacheData.data))
30001
+ return;
30002
+ return cacheData.data;
30003
+ }, createRSVP: async (status) => {
30004
+ const { data } = await createRSVP(event.eventId, status);
30005
+ return data;
30006
+ }, updateRSVP: async (status) => {
30007
+ const { data } = await updateRSVP(event.eventId, status);
30008
+ return data;
30009
+ }, getMyRSVP: async () => {
30010
+ const { data } = await getMyRSVP(event.eventId);
30011
+ return data;
30012
+ } });
30013
+ };
30014
+
29768
30015
  const LinkedObject = {
29769
30016
  ad: adLinkedObject,
29770
30017
  comment: commentLinkedObject,
@@ -29783,6 +30030,7 @@ const LinkedObject = {
29783
30030
  invitation: invitationLinkedObject,
29784
30031
  joinRequest: joinRequestLinkedObject,
29785
30032
  channelMember: channelMemberLinkedObject,
30033
+ event: eventLinkedObject,
29786
30034
  };
29787
30035
 
29788
30036
  /* begin_public_function
@@ -43768,1163 +44016,440 @@ var index$8 = /*#__PURE__*/Object.freeze({
43768
44016
  });
43769
44017
 
43770
44018
  /* begin_public_function
43771
- id: room.create
44019
+ id: poll.create
43772
44020
  */
43773
44021
  /**
43774
44022
  * ```js
43775
- * import { createRoom } from '@amityco/ts-sdk'
43776
- * const created = await createRoom({ title: 'my room', 'thumbnailFileId': fileId })
44023
+ * import { createPoll } from '@amityco/ts-sdk'
44024
+ * const created = await createPoll({
44025
+ * question: 'question',
44026
+ * answers: [
44027
+ * { dataType: 'text', data: 'answer1', fileId: 'fileId1' },
44028
+ * { dataType: 'text', data: 'answer2', fileId: 'fileId2' },
44029
+ * ],
44030
+ * closedIn: 1649136484
44031
+ * }))
43777
44032
  * ```
43778
44033
  *
43779
- * Creates an {@link Amity.Room}
44034
+ * Creates an {@link Amity.Poll}
43780
44035
  *
43781
- * @param bundle The data necessary to create a new {@link Amity.Room}
43782
- * @returns The newly created {@link Amity.Room}
44036
+ * @param bundle The data necessary to create a new {@link Amity.Poll}
44037
+ * @returns The newly created {@link Amity.Poll}
43783
44038
  *
43784
- * @category Room API
44039
+ * @category Poll API
43785
44040
  * @async
43786
44041
  */
43787
- const createRoom = async (bundle) => {
44042
+ const createPoll = async (bundle) => {
43788
44043
  const client = getActiveClient();
43789
- client.log('room/createRoom', bundle);
43790
- const { data } = await client.http.post('/api/v1/rooms', bundle);
43791
- fireEvent('local.room.created', data);
44044
+ client.log('post/createPoll', bundle);
44045
+ const { data } = await client.http.post('/api/v3/polls', bundle);
43792
44046
  const cachedAt = client.cache && Date.now();
43793
- // TODO: check if should pick `users` filed which contains participants - if no need to ingest in the cache
43794
44047
  if (client.cache)
43795
44048
  ingestInCache(data, { cachedAt });
43796
- const { rooms } = data;
44049
+ const { polls } = data;
43797
44050
  return {
43798
- data: rooms[0],
44051
+ data: polls[0],
43799
44052
  cachedAt,
43800
44053
  };
43801
44054
  };
43802
44055
  /* end_public_function */
43803
44056
 
43804
44057
  /* begin_public_function
43805
- id: room.update
44058
+ id: poll.close
43806
44059
  */
43807
44060
  /**
43808
44061
  * ```js
43809
- * import { updateRoom } from '@amityco/ts-sdk'
43810
- * const updated = await updateRoom('roomId', { title: 'updated title' })
44062
+ * import { closePoll } from '@amityco/ts-sdk'
44063
+ * const updated = await closePoll(pollId)
43811
44064
  * ```
43812
44065
  *
43813
- * Updates an {@link Amity.InternalRoom}
44066
+ * Updates an {@link Amity.Poll}
43814
44067
  *
43815
- * @param roomId The ID of the room to update
43816
- * @param bundle The data to update the room with
43817
- * @returns The updated {@link Amity.InternalRoom}
44068
+ * @param pollId The ID of the {@link Amity.Poll} to close
44069
+ * @returns the updated {@link Amity.Poll} object
43818
44070
  *
43819
- * @category Room API
44071
+ * @category Poll API
43820
44072
  * @async
43821
44073
  */
43822
- const updateRoom = async (roomId, bundle) => {
44074
+ const closePoll = async (pollId) => {
43823
44075
  const client = getActiveClient();
43824
- client.log('room/updateRoom', { roomId, bundle });
43825
- const { data } = await client.http.put(`/api/v1/rooms/${roomId}`, bundle);
43826
- fireEvent('local.room.updated', data);
44076
+ client.log('user/closePoll', pollId);
44077
+ const { data } = await client.http.put(`/api/v3/polls/${encodeURIComponent(pollId)}`, { status: 'closed' });
43827
44078
  const cachedAt = client.cache && Date.now();
43828
44079
  if (client.cache)
43829
44080
  ingestInCache(data, { cachedAt });
43830
- const { rooms } = data;
44081
+ fireEvent('poll.updated', data);
44082
+ const { polls } = data;
43831
44083
  return {
43832
- data: rooms[0],
44084
+ data: polls.find(poll => poll.pollId === pollId),
43833
44085
  cachedAt,
43834
44086
  };
43835
44087
  };
43836
44088
  /* end_public_function */
43837
44089
 
43838
44090
  /* begin_public_function
43839
- id: room.delete
44091
+ id: poll.get
43840
44092
  */
43841
44093
  /**
43842
44094
  * ```js
43843
- * import { deleteRoom } from '@amityco/ts-sdk'
43844
- * const result = await deleteRoom('roomId')
44095
+ * import { getPoll } from '@amityco/ts-sdk'
44096
+ * const poll = await getPoll('foobar')
43845
44097
  * ```
43846
44098
  *
43847
- * Deletes an {@link Amity.Room}
44099
+ * Fetches a {@link Amity.Poll} object
43848
44100
  *
43849
- * @param roomId The ID of the room to delete
43850
- * @returns Promise that resolves when the room is deleted
44101
+ * @param pollId the ID of the {@link Amity.Poll} to fetch
44102
+ * @returns the associated {@link Amity.Poll} object
43851
44103
  *
43852
- * @category Room API
44104
+ * @category Poll API
43853
44105
  * @async
43854
44106
  */
43855
- const deleteRoom = async (roomId) => {
44107
+ const getPoll$1 = async (pollId) => {
43856
44108
  const client = getActiveClient();
43857
- client.log('room/deleteRoom', { roomId });
43858
- await client.http.delete(`/api/v1/rooms/${roomId}`);
43859
- fireEvent('local.room.deleted', { rooms: [{ _id: roomId }] });
44109
+ client.log('poll/getPoll', pollId);
44110
+ const { data } = await client.http.get(`/api/v3/polls/${pollId}`);
44111
+ const cachedAt = client.cache && Date.now();
44112
+ if (client.cache)
44113
+ ingestInCache(data, { cachedAt });
44114
+ const { polls } = data;
44115
+ return {
44116
+ data: polls.find(poll => poll.pollId === pollId),
44117
+ cachedAt,
44118
+ };
43860
44119
  };
43861
44120
  /* end_public_function */
43862
-
43863
- /* begin_public_function
43864
- id: room.stop
43865
- */
43866
44121
  /**
43867
44122
  * ```js
43868
- * import { stopRoom } from '@amityco/ts-sdk'
43869
- * const result = await stopRoom('roomId')
44123
+ * import { getPoll } from '@amityco/ts-sdk'
44124
+ * const poll = getPoll.locally('foobar')
43870
44125
  * ```
43871
44126
  *
43872
- * Stops a room's broadcasting
44127
+ * Fetches a {@link Amity.Poll} object
43873
44128
  *
43874
- * @param roomId The ID of the room to stop
43875
- * @returns The updated room data
44129
+ * @param pollId the ID of the {@link Amity.Poll} to fetch
44130
+ * @returns the associated {@link Amity.Poll} object
43876
44131
  *
43877
- * @category Room API
43878
- * @async
44132
+ * @category Poll API
43879
44133
  */
43880
- const stopRoom = async (roomId) => {
44134
+ getPoll$1.locally = (pollId) => {
43881
44135
  const client = getActiveClient();
43882
- client.log('room/stopRoom', { roomId });
43883
- const { data } = await client.http.post(`/api/v1/rooms/${roomId}/stop`);
43884
- fireEvent('local.room.stopped', data);
43885
- const cachedAt = client.cache && Date.now();
43886
- if (client.cache)
43887
- ingestInCache(data, { cachedAt });
43888
- const { rooms } = data;
44136
+ client.log('poll/getPoll', pollId);
44137
+ if (!client.cache)
44138
+ return;
44139
+ const cached = pullFromCache(['poll', 'get', pollId]);
44140
+ if (!cached)
44141
+ return;
43889
44142
  return {
43890
- data: rooms[0],
43891
- cachedAt,
44143
+ data: cached.data,
44144
+ cachedAt: cached.cachedAt,
43892
44145
  };
43893
44146
  };
43894
- /* end_public_function */
43895
44147
 
43896
44148
  /* begin_public_function
43897
- id: room.getToken
44149
+ id: poll.delete
43898
44150
  */
43899
44151
  /**
43900
44152
  * ```js
43901
- * import { getRoomToken } from '@amityco/ts-sdk'
43902
- * const token = await getRoomToken('roomId')
44153
+ * import { deletePoll } from '@amityco/ts-sdk'
44154
+ * const success = await deletePoll(pollId)
43903
44155
  * ```
43904
44156
  *
43905
- * Gets an access token for a room
44157
+ * Deletes a {@link Amity.Poll}
43906
44158
  *
43907
- * @param roomId The ID of the room to get token for
43908
- * @returns The room access token
44159
+ * @param pollId The {@link Amity.Poll} ID to delete
44160
+ * @return A success boolean if the {@link Amity.Poll} was deleted
43909
44161
  *
43910
- * @category Room API
44162
+ * @category Poll API
43911
44163
  * @async
43912
44164
  */
43913
- const getRoomToken = async (roomId) => {
44165
+ const deletePoll = async (pollId) => {
43914
44166
  const client = getActiveClient();
43915
- client.log('room/getRoomToken', { roomId });
43916
- const { data } = await client.http.get(`/api/v1/rooms/${roomId}/token`);
43917
- return data;
44167
+ client.log('poll/deletePoll', pollId);
44168
+ const poll = await getPoll$1(pollId);
44169
+ // API-FIX: it returns { success: boolean } but seems it should be Amity.Response<{ success: boolean }
44170
+ const { data } = await client.http.delete(`/api/v3/polls/${pollId}`);
44171
+ const { success } = data; // unwrapPayload(data)
44172
+ const deleted = Object.assign(Object.assign({}, poll.data), { isDeleted: true });
44173
+ upsertInCache(['poll', 'get', pollId], deleted);
44174
+ fireEvent('poll.deleted', { polls: [deleted], users: [] });
44175
+ return success;
43918
44176
  };
43919
44177
  /* end_public_function */
43920
44178
 
43921
44179
  /* begin_public_function
43922
- id: room.getRecordedUrl
44180
+ id: poll.vote
43923
44181
  */
43924
44182
  /**
43925
44183
  * ```js
43926
- * import { getRecordedUrl } from '@amityco/ts-sdk'
43927
- * const recordedUrl = await getRecordedUrl('roomId')
44184
+ * import { votePoll } from '@amityco/ts-sdk'
44185
+ * const voted = await votePoll(pollId)
43928
44186
  * ```
43929
44187
  *
43930
- * Gets the recorded URL for a room
44188
+ * Votes for an {@link Amity.Poll}
43931
44189
  *
43932
- * @param roomId The ID of the room to get recorded URL for
43933
- * @returns The recorded URL information
44190
+ * @param pollId The ID of the {@link Amity.Poll} to vote
44191
+ * @param answerIds The IDs of the {@link Amity.Poll} answers to vote {@link Amity.Poll}
44192
+ * @returns the updated {@link Amity.Poll} object
43934
44193
  *
43935
- * @category Room API
44194
+ * @category Poll API
43936
44195
  * @async
43937
44196
  */
43938
- const getRecordedUrl = async (roomId) => {
44197
+ const votePoll = async (pollId, answerIds) => {
43939
44198
  const client = getActiveClient();
43940
- client.log('room/getRecordedUrl', { roomId });
43941
- const { data } = await client.http.get(`/api/v1/rooms/${roomId}/recorded`);
43942
- return data;
44199
+ client.log('user/votePoll', pollId);
44200
+ const { data } = await client.http.post(`/api/v3/polls/${encodeURIComponent(pollId)}/votes`, { pollId, answerIds });
44201
+ const cachedAt = client.cache && Date.now();
44202
+ if (client.cache)
44203
+ ingestInCache(data, { cachedAt });
44204
+ const { polls } = data;
44205
+ fireEvent('poll.updated', data);
44206
+ return {
44207
+ data: polls.find(poll => poll.pollId === pollId),
44208
+ cachedAt,
44209
+ };
43943
44210
  };
43944
44211
  /* end_public_function */
43945
44212
 
44213
+ /* begin_public_function
44214
+ id: poll.unvote
44215
+ */
43946
44216
  /**
43947
44217
  * ```js
43948
- * import { onRoomStartBroadcasting } from '@amityco/ts-sdk'
43949
- * const dispose = onRoomStartBroadcasting(room => {
43950
- * // ...
43951
- * })
44218
+ * import { PollRepository } from '@amityco/ts-sdk'
44219
+ * await PollRepository.unvotePoll(pollId)
43952
44220
  * ```
43953
44221
  *
43954
- * Fired when a {@link Amity.Room} has started broadcasting
44222
+ * Votes for an {@link Amity.Poll}
43955
44223
  *
43956
- * @param callback The function to call when the event was fired
43957
- * @returns an {@link Amity.Unsubscriber} function to stop listening
44224
+ * @param pollId The ID of the {@link Amity.Poll} to vote
44225
+ * @returns void
43958
44226
  *
43959
- * @category Room Events
44227
+ * @category Poll API
44228
+ * @async
43960
44229
  */
43961
- const onRoomStartBroadcasting = (callback) => {
44230
+ const unvotePoll = async (pollId) => {
43962
44231
  const client = getActiveClient();
43963
- const filter = (payload) => {
43964
- ingestInCache(payload);
43965
- callback(payload.rooms[0]);
43966
- };
43967
- return createEventSubscriber(client, 'room/onRoomStartBroadcasting', 'room.startBroadcasting', filter);
44232
+ client.log('user/unvotePoll', pollId);
44233
+ const { data } = await client.http.put(`/api/v3/polls/${encodeURIComponent(pollId)}/votes`, { pollId, answerIds: [] });
44234
+ const cachedAt = client.cache && Date.now();
44235
+ if (client.cache)
44236
+ ingestInCache(data, { cachedAt });
44237
+ fireEvent('poll.updated', data);
43968
44238
  };
44239
+ /* end_public_function */
43969
44240
 
43970
44241
  /**
43971
44242
  * ```js
43972
- * import { onRoomWaitingReconnect } from '@amityco/ts-sdk'
43973
- * const dispose = onRoomWaitingReconnect(room => {
44243
+ * import { onPollUpdated } from '@amityco/ts-sdk'
44244
+ * const dispose = onPollUpdated(poll => {
43974
44245
  * // ...
43975
44246
  * })
43976
44247
  * ```
43977
44248
  *
43978
- * Fired when a {@link Amity.Room} is waiting for reconnection
44249
+ * Fired when an {@link Amity.Poll} has been updated
43979
44250
  *
43980
44251
  * @param callback The function to call when the event was fired
43981
44252
  * @returns an {@link Amity.Unsubscriber} function to stop listening
43982
44253
  *
43983
- * @category Room Events
44254
+ * @category Poll Events
43984
44255
  */
43985
- const onRoomWaitingReconnect = (callback) => {
44256
+ const onPollUpdated = (callback) => {
43986
44257
  const client = getActiveClient();
43987
44258
  const filter = (payload) => {
43988
- ingestInCache(payload);
43989
- callback(payload.rooms[0]);
44259
+ if (client.cache)
44260
+ ingestInCache(payload);
44261
+ callback(payload.polls[0]);
43990
44262
  };
43991
- return createEventSubscriber(client, 'room/onRoomWaitingReconnect', 'room.waitingReconnect', filter);
44263
+ return createEventSubscriber(client, 'poll/onPollUpdated', 'poll.updated', filter);
43992
44264
  };
43993
44265
 
43994
44266
  /**
43995
44267
  * ```js
43996
- * import { onRoomEndBroadcasting } from '@amityco/ts-sdk'
43997
- * const dispose = onRoomEndBroadcasting(room => {
44268
+ * import { onPollDeleted } from '@amityco/ts-sdk'
44269
+ * const dispose = onPollDeleted(poll => {
43998
44270
  * // ...
43999
44271
  * })
44000
44272
  * ```
44001
44273
  *
44002
- * Fired when a {@link Amity.Room} has ended broadcasting
44274
+ * Fired when an {@link Amity.Poll} has been deleted
44003
44275
  *
44004
44276
  * @param callback The function to call when the event was fired
44005
44277
  * @returns an {@link Amity.Unsubscriber} function to stop listening
44006
44278
  *
44007
- * @category Room Events
44279
+ * @category Poll Events
44008
44280
  */
44009
- const onRoomEndBroadcasting = (callback) => {
44281
+ const onPollDeleted = (callback) => {
44010
44282
  const client = getActiveClient();
44011
44283
  const filter = (payload) => {
44012
- ingestInCache(payload);
44013
- callback(payload.rooms[0]);
44284
+ if (client.cache)
44285
+ ingestInCache(payload);
44286
+ callback(payload.polls[0]);
44014
44287
  };
44015
- return createEventSubscriber(client, 'room/onRoomEndBroadcasting', 'room.endBroadcasting', filter);
44288
+ return createEventSubscriber(client, 'poll/onPollDeleted', 'poll.deleted', filter);
44016
44289
  };
44017
44290
 
44291
+ /* begin_public_function
44292
+ id: poll.get
44293
+ */
44018
44294
  /**
44019
44295
  * ```js
44020
- * import { onRoomRecordedAvailable } from '@amityco/ts-sdk'
44021
- * const dispose = onRoomRecordedAvailable(room => {
44022
- * // ...
44023
- * })
44024
- * ```
44025
- *
44026
- * Fired when a {@link Amity.Room} recorded content becomes available
44296
+ * import { PollRepository } from '@amityco/ts-sdk';
44027
44297
  *
44028
- * @param callback The function to call when the event was fired
44029
- * @returns an {@link Amity.Unsubscriber} function to stop listening
44298
+ * let poll;
44030
44299
  *
44031
- * @category Room Events
44032
- */
44033
- const onRoomRecordedAvailable = (callback) => {
44034
- const client = getActiveClient();
44035
- const filter = (payload) => {
44036
- ingestInCache(payload);
44037
- callback(payload.rooms[0]);
44038
- };
44039
- return createEventSubscriber(client, 'room/onRoomRecordedAvailable', 'room.recordedAvailable', filter);
44040
- };
44041
-
44042
- /**
44043
- * ```js
44044
- * import { onRoomParticipantInviting } from '@amityco/ts-sdk'
44045
- * const dispose = onRoomParticipantInviting(room => {
44046
- * // ...
44047
- * })
44300
+ * const unsub = PollRepository.getPoll(commentId, response => {
44301
+ * poll = response.data;
44302
+ * });
44048
44303
  * ```
44049
44304
  *
44050
- * Fired when a participant is being invited to a {@link Amity.Room}
44305
+ * Observe all mutation on a given {@link Amity.Poll}
44051
44306
  *
44052
- * @param callback The function to call when the event was fired
44053
- * @returns an {@link Amity.Unsubscriber} function to stop listening
44307
+ * @param pollId the ID of the poll to observe
44308
+ * @param callback the function to call when new data are available
44309
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the poll
44054
44310
  *
44055
- * @category Room Events
44311
+ * @category Poll Live Object
44056
44312
  */
44057
- const onRoomParticipantInviting = (callback) => {
44058
- const client = getActiveClient();
44059
- const filter = (payload) => {
44060
- ingestInCache(payload);
44061
- callback(payload.rooms[0]);
44062
- };
44063
- return createEventSubscriber(client, 'room/onRoomParticipantInviting', 'room.participantInviting', filter);
44313
+ const getPoll = (pollId, callback) => {
44314
+ return liveObject(pollId, callback, 'pollId', getPoll$1, [onPollUpdated, onPollDeleted]);
44064
44315
  };
44316
+ /* end_public_function */
44065
44317
 
44066
- /**
44067
- * ```js
44068
- * import { onRoomParticipantJoined } from '@amityco/ts-sdk'
44069
- * const dispose = onRoomParticipantJoined(room => {
44070
- * // ...
44071
- * })
44072
- * ```
44073
- *
44074
- * Fired when a participant has joined a {@link Amity.Room}
44075
- *
44076
- * @param callback The function to call when the event was fired
44077
- * @returns an {@link Amity.Unsubscriber} function to stop listening
44078
- *
44079
- * @category Room Events
44318
+ var index$7 = /*#__PURE__*/Object.freeze({
44319
+ __proto__: null,
44320
+ createPoll: createPoll,
44321
+ closePoll: closePoll,
44322
+ deletePoll: deletePoll,
44323
+ votePoll: votePoll,
44324
+ unvotePoll: unvotePoll,
44325
+ onPollUpdated: onPollUpdated,
44326
+ onPollDeleted: onPollDeleted,
44327
+ getPoll: getPoll
44328
+ });
44329
+
44330
+ 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-----";
44331
+ /*
44332
+ * The crypto algorithm used for importing key and signing string
44080
44333
  */
44081
- const onRoomParticipantJoined = (callback) => {
44082
- const client = getActiveClient();
44083
- const filter = (payload) => {
44084
- ingestInCache(payload);
44085
- callback(payload.rooms[0]);
44086
- };
44087
- return createEventSubscriber(client, 'room/onRoomParticipantJoined', 'room.participantJoined', filter);
44334
+ const ALGORITHM = {
44335
+ name: 'RSASSA-PKCS1-v1_5',
44336
+ hash: { name: 'SHA-256' },
44088
44337
  };
44089
-
44090
- /**
44091
- * ```js
44092
- * import { onRoomParticipantLeft } from '@amityco/ts-sdk'
44093
- * const dispose = onRoomParticipantLeft(room => {
44094
- * // ...
44095
- * })
44096
- * ```
44097
- *
44098
- * Fired when a participant has left a {@link Amity.Room}
44338
+ /*
44339
+ * IMPORTANT!
44340
+ * If you are recieving key from other platforms use an online tool to convert
44341
+ * the PKCS1 to PKCS8. For instance the key from Android SDK is of the format
44342
+ * PKCS1.
44099
44343
  *
44100
- * @param callback The function to call when the event was fired
44101
- * @returns an {@link Amity.Unsubscriber} function to stop listening
44344
+ * If recieving from the platform, verify if it's already in the expected
44345
+ * format. Otherwise the crypto.subtle.importKey will throw a DOMException
44346
+ */
44347
+ const PRIVATE_KEY_SIGNATURE = 'pkcs8';
44348
+ /*
44349
+ * Ensure that the private key in the .env follows this format
44350
+ */
44351
+ const PEM_HEADER = '-----BEGIN PRIVATE KEY-----';
44352
+ const PEM_FOOTER = '-----END PRIVATE KEY-----';
44353
+ /*
44354
+ * The crypto.subtle.sign function returns an ArrayBuffer whereas the server
44355
+ * expects a base64 string. This util helps facilitate that process
44356
+ */
44357
+ function base64FromArrayBuffer(buffer) {
44358
+ const uint8Array = new Uint8Array(buffer);
44359
+ let binary = '';
44360
+ uint8Array.forEach(byte => {
44361
+ binary += String.fromCharCode(byte);
44362
+ });
44363
+ return btoa(binary);
44364
+ }
44365
+ /*
44366
+ * Convert a string into an ArrayBuffer
44367
+ * from https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String
44102
44368
  *
44103
- * @category Room Events
44369
+ * Solely used by the importPrivateKey method
44104
44370
  */
44105
- const onRoomParticipantLeft = (callback) => {
44106
- const client = getActiveClient();
44107
- const filter = (payload) => {
44108
- ingestInCache(payload);
44109
- callback(payload.rooms[0]);
44110
- };
44111
- return createEventSubscriber(client, 'room/onRoomParticipantLeft', 'room.participantLeft', filter);
44112
- };
44371
+ function str2ab(str) {
44372
+ const buf = new ArrayBuffer(str.length);
44373
+ const bufView = new Uint8Array(buf);
44374
+ for (let i = 0, strLen = str.length; i < strLen; i += 1) {
44375
+ bufView[i] = str.charCodeAt(i);
44376
+ }
44377
+ return buf;
44378
+ }
44379
+ function importPrivateKey(pem) {
44380
+ // fetch the part of the PEM string between header and footer
44381
+ const pemContents = pem.substring(PEM_HEADER.length, pem.length - PEM_FOOTER.length);
44382
+ /*
44383
+ * base64 decode the string to get the binary data
44384
+ */
44385
+ const binaryDerString = atob(pemContents);
44386
+ // convert from a binary string to an ArrayBuffer
44387
+ const binaryDer = str2ab(binaryDerString);
44388
+ return crypto.subtle.importKey(PRIVATE_KEY_SIGNATURE, binaryDer, ALGORITHM, false, ['sign']);
44389
+ }
44390
+ async function createSignature({ timestamp, streams, }) {
44391
+ const dataStr = streams
44392
+ .map(item => Object.keys(item)
44393
+ .sort()
44394
+ .map(key => `${key}=${item[key]}`)
44395
+ .join('&'))
44396
+ .join(';');
44397
+ /*
44398
+ * nonceStr needs to be unique for each request
44399
+ */
44400
+ const nonceStr = uuid$1.v4();
44401
+ const signStr = `nonceStr=${nonceStr}&timestamp=${timestamp}&data=${dataStr}==`;
44402
+ const encoder = new TextEncoder();
44403
+ const data = encoder.encode(signStr);
44404
+ const key = await importPrivateKey(privateKey);
44405
+ const sign = await crypto.subtle.sign(ALGORITHM, key, data);
44406
+ return { signature: base64FromArrayBuffer(sign), nonceStr };
44407
+ }
44113
44408
 
44114
- /**
44115
- * ```js
44116
- * import { onRoomCreated } from '@amityco/ts-sdk'
44117
- * const dispose = onRoomCreated(room => {
44118
- * // ...
44119
- * })
44120
- * ```
44121
- *
44122
- * Fired when a {@link Amity.Room} has been created locally
44123
- *
44124
- * @param callback The function to call when the event was fired
44125
- * @returns an {@link Amity.Unsubscriber} function to stop listening
44409
+ async function syncUsage({ bufferCurrentUsage, getActiveStreams, updateUsage, dispose, }) {
44410
+ const streams = bufferCurrentUsage();
44411
+ if (!streams.length)
44412
+ return;
44413
+ try {
44414
+ const timestamp = new Date().toISOString();
44415
+ const signatureData = await createSignature({ timestamp, streams });
44416
+ if (!signatureData || !signatureData.signature) {
44417
+ throw new Error('Signature is undefined');
44418
+ }
44419
+ const payload = {
44420
+ signature: signatureData.signature,
44421
+ nonceStr: signatureData.nonceStr,
44422
+ timestamp,
44423
+ streams,
44424
+ };
44425
+ const client = getActiveClient();
44426
+ await client.http.post('/api/v3/user-event/video-streaming', payload);
44427
+ if (!getActiveStreams().length && !bufferCurrentUsage().length) {
44428
+ dispose();
44429
+ }
44430
+ return true;
44431
+ }
44432
+ catch (err) {
44433
+ // push buffer back to usage collector and try again in the next interval
44434
+ streams.forEach(stream => updateUsage(stream));
44435
+ return false;
44436
+ }
44437
+ }
44438
+
44439
+ /*
44440
+ * It was originally planned to be 10 seconds but the signature creation is a
44441
+ * slow process and can take upto 4 to 5 seconds, which might lead to data
44442
+ * inconsitencies and adds complexity to manging sync data.
44126
44443
  *
44127
- * @category Room Events
44444
+ * Hence, I've incerased the USAGE_SYNC_INTERVAL to ensure a more maintainable
44445
+ * code
44128
44446
  */
44129
- const onRoomCreated = (callback) => {
44130
- const client = getActiveClient();
44131
- const filter = (payload) => {
44132
- ingestInCache(payload);
44133
- callback(payload.rooms[0]);
44134
- };
44135
- return createEventSubscriber(client, 'room/onRoomCreated', 'local.room.created', filter);
44136
- };
44137
-
44447
+ const USAGE_SYNC_INTERVAL = 20 * 1000; // 20 seconds;
44138
44448
  /**
44139
- * ```js
44140
- * import { onRoomUpdated } from '@amityco/ts-sdk'
44141
- * const dispose = onRoomUpdated(room => {
44142
- * // ...
44143
- * })
44144
- * ```
44145
- *
44146
- * Fired when a {@link Amity.Room} has been updated locally
44449
+ * @class
44147
44450
  *
44148
- * @param callback The function to call when the event was fired
44149
- * @returns an {@link Amity.Unsubscriber} function to stop listening
44150
- *
44151
- * @category Room Events
44152
- */
44153
- const onRoomUpdated = (callback) => {
44154
- const client = getActiveClient();
44155
- const filter = (payload) => {
44156
- ingestInCache(payload);
44157
- callback(payload.rooms[0]);
44158
- };
44159
- return createEventSubscriber(client, 'room/onRoomUpdated', 'local.room.updated', filter);
44160
- };
44161
-
44162
- /**
44163
- * ```js
44164
- * import { onRoomDeleted } from '@amityco/ts-sdk'
44165
- * const dispose = onRoomDeleted(room => {
44166
- * // ...
44167
- * })
44168
- * ```
44169
- *
44170
- * Fired when a {@link Amity.Room} has been deleted locally
44171
- *
44172
- * @param callback The function to call when the event was fired
44173
- * @returns an {@link Amity.Unsubscriber} function to stop listening
44174
- *
44175
- * @category Room Events
44176
- */
44177
- const onRoomDeleted = (callback) => {
44178
- const client = getActiveClient();
44179
- const filter = (payload) => {
44180
- ingestInCache(payload);
44181
- callback(payload.rooms[0]);
44182
- };
44183
- return createEventSubscriber(client, 'room/onRoomDeleted', 'local.room.deleted', filter);
44184
- };
44185
-
44186
- /**
44187
- * ```js
44188
- * import { onRoomStopped } from '@amityco/ts-sdk'
44189
- * const dispose = onRoomStopped(room => {
44190
- * // ...
44191
- * })
44192
- * ```
44193
- *
44194
- * Fired when a {@link Amity.Room} has been stopped locally
44195
- *
44196
- * @param callback The function to call when the event was fired
44197
- * @returns an {@link Amity.Unsubscriber} function to stop listening
44198
- *
44199
- * @category Room Events
44200
- */
44201
- const onRoomStopped = (callback) => {
44202
- const client = getActiveClient();
44203
- const filter = (payload) => {
44204
- ingestInCache(payload);
44205
- callback(payload.rooms[0]);
44206
- };
44207
- return createEventSubscriber(client, 'room/onRoomStopped', 'local.room.stopped', filter);
44208
- };
44209
-
44210
- const getRoomById = async (roomId) => {
44211
- const client = getActiveClient();
44212
- client.log('room/getRoomById', roomId);
44213
- // Check if room is in tombstone
44214
- isInTombstone('room', roomId);
44215
- let data;
44216
- try {
44217
- const response = await client.http.get(`/api/v1/rooms/${roomId}`);
44218
- data = response.data;
44219
- }
44220
- catch (error) {
44221
- if (checkIfShouldGoesToTombstone(error === null || error === void 0 ? void 0 : error.code)) {
44222
- pushToTombstone('room', roomId);
44223
- }
44224
- throw error;
44225
- }
44226
- const cachedAt = client.cache && Date.now();
44227
- if (client.cache) {
44228
- ingestInCache(data, { cachedAt });
44229
- }
44230
- return {
44231
- data: data.rooms[0],
44232
- cachedAt,
44233
- };
44234
- };
44235
- getRoomById.locally = (roomId) => {
44236
- const client = getActiveClient();
44237
- client.log('room/getRoomById.locally', roomId);
44238
- // Check if room is in tombstone
44239
- isInTombstone('room', roomId);
44240
- const cachedAt = client.cache && Date.now();
44241
- const roomCache = pullFromCache(['room', 'get', roomId]);
44242
- if (!roomCache)
44243
- return;
44244
- return {
44245
- data: roomCache.data,
44246
- cachedAt,
44247
- };
44248
- };
44249
-
44250
- const getRoom = (roomId, callback) => {
44251
- // TODO: add callbackDataSelector if there are linked object fields
44252
- return liveObject(roomId, callback, '_id', getRoomById, [
44253
- onRoomEndBroadcasting,
44254
- onRoomStartBroadcasting,
44255
- onRoomWaitingReconnect,
44256
- onRoomRecordedAvailable,
44257
- ]);
44258
- };
44259
-
44260
- class RoomPaginationController extends PaginationController {
44261
- async getRequest(queryParams, token) {
44262
- const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, includeDeleted } = queryParams, params = __rest(queryParams, ["limit", "includeDeleted"]);
44263
- const baseOptions = {
44264
- type: params.sortBy || queryParams.limit ? 'pagination' : undefined,
44265
- };
44266
- const options = token ? Object.assign(Object.assign({}, baseOptions), { token }) : Object.assign(Object.assign({}, baseOptions), { limit });
44267
- const { data: queryResponse } = await this.http.get(`/api/v1/rooms`, {
44268
- params: Object.assign(Object.assign({}, params), { isDeleted: inferIsDeleted(includeDeleted), options }),
44269
- });
44270
- return queryResponse;
44271
- }
44272
- }
44273
-
44274
- var EnumRoomActions;
44275
- (function (EnumRoomActions) {
44276
- EnumRoomActions["OnRoomCreated"] = "OnRoomCreated";
44277
- EnumRoomActions["OnRoomUpdated"] = "OnRoomUpdated";
44278
- EnumRoomActions["OnRoomDeleted"] = "OnRoomDeleted";
44279
- EnumRoomActions["OnRoomStartBroadcasting"] = "OnRoomStartBroadcasting";
44280
- EnumRoomActions["OnRoomEndBroadcasting"] = "OnRoomEndBroadcasting";
44281
- EnumRoomActions["OnRoomParticipantJoined"] = "OnRoomParticipantJoined";
44282
- EnumRoomActions["OnRoomParticipantLeft"] = "OnRoomParticipantLeft";
44283
- })(EnumRoomActions || (EnumRoomActions = {}));
44284
-
44285
- class RoomQueryStreamController extends QueryStreamController {
44286
- constructor(query, cacheKey, notifyChange, preparePayload) {
44287
- super(query, cacheKey);
44288
- this.notifyChange = notifyChange;
44289
- this.preparePayload = preparePayload;
44290
- }
44291
- async saveToMainDB(response) {
44292
- const processedPayload = await this.preparePayload(response);
44293
- const client = getActiveClient();
44294
- const cachedAt = client.cache && Date.now();
44295
- if (client.cache) {
44296
- ingestInCache(processedPayload, { cachedAt });
44297
- }
44298
- }
44299
- appendToQueryStream(response, direction, refresh = false) {
44300
- var _a, _b;
44301
- if (refresh) {
44302
- pushToCache(this.cacheKey, {
44303
- data: response.rooms.map(getResolver('room')),
44304
- });
44305
- }
44306
- else {
44307
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
44308
- const rooms = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
44309
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...rooms, ...response.rooms.map(getResolver('room'))])] }));
44310
- }
44311
- }
44312
- reactor(action) {
44313
- return (room) => {
44314
- var _a;
44315
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
44316
- if (!collection)
44317
- return;
44318
- if (action === EnumRoomActions.OnRoomDeleted) {
44319
- collection.data = collection.data.filter(roomId => roomId !== room._id);
44320
- }
44321
- if (action === EnumRoomActions.OnRoomCreated) {
44322
- collection.data = [...new Set([room._id, ...collection.data])];
44323
- }
44324
- pushToCache(this.cacheKey, collection);
44325
- this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
44326
- };
44327
- }
44328
- subscribeRTE(createSubscriber) {
44329
- return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
44330
- }
44331
- }
44332
-
44333
- // TODO: confirm related events
44334
- const getRoomSubscription = () => [
44335
- {
44336
- fn: onRoomStartBroadcasting,
44337
- action: EnumRoomActions.OnRoomStartBroadcasting,
44338
- },
44339
- {
44340
- fn: onRoomEndBroadcasting,
44341
- action: EnumRoomActions.OnRoomEndBroadcasting,
44342
- },
44343
- {
44344
- fn: onRoomRecordedAvailable,
44345
- action: EnumRoomActions.OnRoomUpdated,
44346
- },
44347
- ];
44348
-
44349
- class RoomLiveCollectionController extends LiveCollectionController {
44350
- constructor(query, callback) {
44351
- const queryStreamId = hash(query);
44352
- const cacheKey = ['rooms', 'collection', queryStreamId];
44353
- const paginationController = new RoomPaginationController(query);
44354
- super(paginationController, queryStreamId, cacheKey, callback);
44355
- this.query = query;
44356
- this.queryStreamController = new RoomQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), response => response);
44357
- this.callback = callback.bind(this);
44358
- this.loadPage({ initial: true });
44359
- }
44360
- setup() {
44361
- var _a;
44362
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
44363
- if (!collection) {
44364
- pushToCache(this.cacheKey, {
44365
- data: [],
44366
- params: {},
44367
- });
44368
- }
44369
- }
44370
- async persistModel(queryPayload) {
44371
- await this.queryStreamController.saveToMainDB(queryPayload);
44372
- }
44373
- persistQueryStream({ response, direction, refresh, }) {
44374
- this.queryStreamController.appendToQueryStream(response, direction, refresh);
44375
- }
44376
- startSubscription() {
44377
- return this.queryStreamController.subscribeRTE(getRoomSubscription());
44378
- }
44379
- notifyChange({ origin, loading, error }) {
44380
- var _a, _b;
44381
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
44382
- if (!collection)
44383
- return;
44384
- const data = this.applyFilter((_b = collection.data
44385
- .map(id => pullFromCache(['room', 'get', id]))
44386
- .filter(isNonNullable)
44387
- .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(room => room); // Since Room is same as InternalRoom, no transformation needed
44388
- if (!this.shouldNotify(data) && origin === 'event')
44389
- return;
44390
- this.callback({
44391
- onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
44392
- data,
44393
- hasNextPage: !!this.paginationController.getNextToken(),
44394
- loading,
44395
- error,
44396
- });
44397
- }
44398
- applyFilter(data) {
44399
- let rooms = data;
44400
- if (!this.query.includeDeleted) {
44401
- rooms = filterByPropEquality(rooms, 'isDeleted', false);
44402
- }
44403
- if (this.query.statuses && this.query.statuses.length > 0) {
44404
- rooms = rooms.filter(room => { var _a; return (_a = this.query.statuses) === null || _a === void 0 ? void 0 : _a.includes(room.status); });
44405
- }
44406
- if (this.query.type) {
44407
- rooms = filterByPropEquality(rooms, 'type', this.query.type);
44408
- }
44409
- switch (this.query.sortBy) {
44410
- case 'firstCreated':
44411
- rooms = rooms.sort(sortByFirstCreated);
44412
- break;
44413
- case 'lastCreated':
44414
- default:
44415
- rooms = rooms.sort(sortByLastCreated);
44416
- break;
44417
- }
44418
- return rooms;
44419
- }
44420
- }
44421
-
44422
- /* begin_public_function
44423
- id: room.get_rooms
44424
- */
44425
- /**
44426
- * ```js
44427
- * import { RoomRepository } from '@amityco/ts-sdk'
44428
- *
44429
- * let rooms = []
44430
- * const unsub = RoomRepository.getRooms({
44431
- * type: 'direct_streaming',
44432
- * statuses: ['live', 'idle'],
44433
- * sortBy: 'lastCreated',
44434
- * limit: 20,
44435
- * includeDeleted: false
44436
- * }, response => merge(rooms, response.data))
44437
- * ```
44438
- *
44439
- * Observe all mutations on a list of {@link Amity.Room} for a given query
44440
- *
44441
- * @param params.type the type of rooms to filter by ('direct_streaming' | 'co_hosts')
44442
- * @param params.statuses array of room statuses to filter by (['idle', 'live', 'waiting_reconnect', 'ended', 'recorded'])
44443
- * @param params.sortBy sort rooms by creation time ('firstCreated' | 'lastCreated')
44444
- * @param params.limit maximum number of rooms to retrieve per page
44445
- * @param params.includeDeleted whether to include deleted rooms in the results
44446
- * @param callback the function to call when new data are available
44447
- * @param config optional configuration for the live collection
44448
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the rooms
44449
- *
44450
- * @category Rooms Live Collection
44451
- */
44452
- const getRooms = (params, callback, config) => {
44453
- const { log, cache } = getActiveClient();
44454
- if (!cache) {
44455
- console.log(ENABLE_CACHE_MESSAGE);
44456
- }
44457
- const timestamp = Date.now();
44458
- log(`getRooms(tmpid: ${timestamp}) > listen`);
44459
- const roomsLiveCollection = new RoomLiveCollectionController(params, callback);
44460
- const disposers = roomsLiveCollection.startSubscription();
44461
- const cacheKey = roomsLiveCollection.getCacheKey();
44462
- disposers.push(() => dropFromCache(cacheKey));
44463
- return () => {
44464
- log(`getRooms(tmpid: ${timestamp}) > dispose`);
44465
- disposers.forEach(fn => fn());
44466
- };
44467
- };
44468
- /* end_public_function */
44469
-
44470
- var index$7 = /*#__PURE__*/Object.freeze({
44471
- __proto__: null,
44472
- createRoom: createRoom,
44473
- updateRoom: updateRoom,
44474
- deleteRoom: deleteRoom,
44475
- stopRoom: stopRoom,
44476
- getRoomToken: getRoomToken,
44477
- getRecordedUrl: getRecordedUrl,
44478
- onRoomStartBroadcasting: onRoomStartBroadcasting,
44479
- onRoomWaitingReconnect: onRoomWaitingReconnect,
44480
- onRoomEndBroadcasting: onRoomEndBroadcasting,
44481
- onRoomRecordedAvailable: onRoomRecordedAvailable,
44482
- onRoomParticipantInviting: onRoomParticipantInviting,
44483
- onRoomParticipantJoined: onRoomParticipantJoined,
44484
- onRoomParticipantLeft: onRoomParticipantLeft,
44485
- onRoomCreated: onRoomCreated,
44486
- onRoomUpdated: onRoomUpdated,
44487
- onRoomDeleted: onRoomDeleted,
44488
- onRoomStopped: onRoomStopped,
44489
- getRoom: getRoom,
44490
- getRooms: getRooms
44491
- });
44492
-
44493
- /* begin_public_function
44494
- id: poll.create
44495
- */
44496
- /**
44497
- * ```js
44498
- * import { createPoll } from '@amityco/ts-sdk'
44499
- * const created = await createPoll({
44500
- * question: 'question',
44501
- * answers: [
44502
- * { dataType: 'text', data: 'answer1', fileId: 'fileId1' },
44503
- * { dataType: 'text', data: 'answer2', fileId: 'fileId2' },
44504
- * ],
44505
- * closedIn: 1649136484
44506
- * }))
44507
- * ```
44508
- *
44509
- * Creates an {@link Amity.Poll}
44510
- *
44511
- * @param bundle The data necessary to create a new {@link Amity.Poll}
44512
- * @returns The newly created {@link Amity.Poll}
44513
- *
44514
- * @category Poll API
44515
- * @async
44516
- */
44517
- const createPoll = async (bundle) => {
44518
- const client = getActiveClient();
44519
- client.log('post/createPoll', bundle);
44520
- const { data } = await client.http.post('/api/v3/polls', bundle);
44521
- const cachedAt = client.cache && Date.now();
44522
- if (client.cache)
44523
- ingestInCache(data, { cachedAt });
44524
- const { polls } = data;
44525
- return {
44526
- data: polls[0],
44527
- cachedAt,
44528
- };
44529
- };
44530
- /* end_public_function */
44531
-
44532
- /* begin_public_function
44533
- id: poll.close
44534
- */
44535
- /**
44536
- * ```js
44537
- * import { closePoll } from '@amityco/ts-sdk'
44538
- * const updated = await closePoll(pollId)
44539
- * ```
44540
- *
44541
- * Updates an {@link Amity.Poll}
44542
- *
44543
- * @param pollId The ID of the {@link Amity.Poll} to close
44544
- * @returns the updated {@link Amity.Poll} object
44545
- *
44546
- * @category Poll API
44547
- * @async
44548
- */
44549
- const closePoll = async (pollId) => {
44550
- const client = getActiveClient();
44551
- client.log('user/closePoll', pollId);
44552
- const { data } = await client.http.put(`/api/v3/polls/${encodeURIComponent(pollId)}`, { status: 'closed' });
44553
- const cachedAt = client.cache && Date.now();
44554
- if (client.cache)
44555
- ingestInCache(data, { cachedAt });
44556
- fireEvent('poll.updated', data);
44557
- const { polls } = data;
44558
- return {
44559
- data: polls.find(poll => poll.pollId === pollId),
44560
- cachedAt,
44561
- };
44562
- };
44563
- /* end_public_function */
44564
-
44565
- /* begin_public_function
44566
- id: poll.get
44567
- */
44568
- /**
44569
- * ```js
44570
- * import { getPoll } from '@amityco/ts-sdk'
44571
- * const poll = await getPoll('foobar')
44572
- * ```
44573
- *
44574
- * Fetches a {@link Amity.Poll} object
44575
- *
44576
- * @param pollId the ID of the {@link Amity.Poll} to fetch
44577
- * @returns the associated {@link Amity.Poll} object
44578
- *
44579
- * @category Poll API
44580
- * @async
44581
- */
44582
- const getPoll$1 = async (pollId) => {
44583
- const client = getActiveClient();
44584
- client.log('poll/getPoll', pollId);
44585
- const { data } = await client.http.get(`/api/v3/polls/${pollId}`);
44586
- const cachedAt = client.cache && Date.now();
44587
- if (client.cache)
44588
- ingestInCache(data, { cachedAt });
44589
- const { polls } = data;
44590
- return {
44591
- data: polls.find(poll => poll.pollId === pollId),
44592
- cachedAt,
44593
- };
44594
- };
44595
- /* end_public_function */
44596
- /**
44597
- * ```js
44598
- * import { getPoll } from '@amityco/ts-sdk'
44599
- * const poll = getPoll.locally('foobar')
44600
- * ```
44601
- *
44602
- * Fetches a {@link Amity.Poll} object
44603
- *
44604
- * @param pollId the ID of the {@link Amity.Poll} to fetch
44605
- * @returns the associated {@link Amity.Poll} object
44606
- *
44607
- * @category Poll API
44608
- */
44609
- getPoll$1.locally = (pollId) => {
44610
- const client = getActiveClient();
44611
- client.log('poll/getPoll', pollId);
44612
- if (!client.cache)
44613
- return;
44614
- const cached = pullFromCache(['poll', 'get', pollId]);
44615
- if (!cached)
44616
- return;
44617
- return {
44618
- data: cached.data,
44619
- cachedAt: cached.cachedAt,
44620
- };
44621
- };
44622
-
44623
- /* begin_public_function
44624
- id: poll.delete
44625
- */
44626
- /**
44627
- * ```js
44628
- * import { deletePoll } from '@amityco/ts-sdk'
44629
- * const success = await deletePoll(pollId)
44630
- * ```
44631
- *
44632
- * Deletes a {@link Amity.Poll}
44633
- *
44634
- * @param pollId The {@link Amity.Poll} ID to delete
44635
- * @return A success boolean if the {@link Amity.Poll} was deleted
44636
- *
44637
- * @category Poll API
44638
- * @async
44639
- */
44640
- const deletePoll = async (pollId) => {
44641
- const client = getActiveClient();
44642
- client.log('poll/deletePoll', pollId);
44643
- const poll = await getPoll$1(pollId);
44644
- // API-FIX: it returns { success: boolean } but seems it should be Amity.Response<{ success: boolean }
44645
- const { data } = await client.http.delete(`/api/v3/polls/${pollId}`);
44646
- const { success } = data; // unwrapPayload(data)
44647
- const deleted = Object.assign(Object.assign({}, poll.data), { isDeleted: true });
44648
- upsertInCache(['poll', 'get', pollId], deleted);
44649
- fireEvent('poll.deleted', { polls: [deleted], users: [] });
44650
- return success;
44651
- };
44652
- /* end_public_function */
44653
-
44654
- /* begin_public_function
44655
- id: poll.vote
44656
- */
44657
- /**
44658
- * ```js
44659
- * import { votePoll } from '@amityco/ts-sdk'
44660
- * const voted = await votePoll(pollId)
44661
- * ```
44662
- *
44663
- * Votes for an {@link Amity.Poll}
44664
- *
44665
- * @param pollId The ID of the {@link Amity.Poll} to vote
44666
- * @param answerIds The IDs of the {@link Amity.Poll} answers to vote {@link Amity.Poll}
44667
- * @returns the updated {@link Amity.Poll} object
44668
- *
44669
- * @category Poll API
44670
- * @async
44671
- */
44672
- const votePoll = async (pollId, answerIds) => {
44673
- const client = getActiveClient();
44674
- client.log('user/votePoll', pollId);
44675
- const { data } = await client.http.post(`/api/v3/polls/${encodeURIComponent(pollId)}/votes`, { pollId, answerIds });
44676
- const cachedAt = client.cache && Date.now();
44677
- if (client.cache)
44678
- ingestInCache(data, { cachedAt });
44679
- const { polls } = data;
44680
- fireEvent('poll.updated', data);
44681
- return {
44682
- data: polls.find(poll => poll.pollId === pollId),
44683
- cachedAt,
44684
- };
44685
- };
44686
- /* end_public_function */
44687
-
44688
- /* begin_public_function
44689
- id: poll.unvote
44690
- */
44691
- /**
44692
- * ```js
44693
- * import { PollRepository } from '@amityco/ts-sdk'
44694
- * await PollRepository.unvotePoll(pollId)
44695
- * ```
44696
- *
44697
- * Votes for an {@link Amity.Poll}
44698
- *
44699
- * @param pollId The ID of the {@link Amity.Poll} to vote
44700
- * @returns void
44701
- *
44702
- * @category Poll API
44703
- * @async
44704
- */
44705
- const unvotePoll = async (pollId) => {
44706
- const client = getActiveClient();
44707
- client.log('user/unvotePoll', pollId);
44708
- const { data } = await client.http.put(`/api/v3/polls/${encodeURIComponent(pollId)}/votes`, { pollId, answerIds: [] });
44709
- const cachedAt = client.cache && Date.now();
44710
- if (client.cache)
44711
- ingestInCache(data, { cachedAt });
44712
- fireEvent('poll.updated', data);
44713
- };
44714
- /* end_public_function */
44715
-
44716
- /**
44717
- * ```js
44718
- * import { onPollUpdated } from '@amityco/ts-sdk'
44719
- * const dispose = onPollUpdated(poll => {
44720
- * // ...
44721
- * })
44722
- * ```
44723
- *
44724
- * Fired when an {@link Amity.Poll} has been updated
44725
- *
44726
- * @param callback The function to call when the event was fired
44727
- * @returns an {@link Amity.Unsubscriber} function to stop listening
44728
- *
44729
- * @category Poll Events
44730
- */
44731
- const onPollUpdated = (callback) => {
44732
- const client = getActiveClient();
44733
- const filter = (payload) => {
44734
- if (client.cache)
44735
- ingestInCache(payload);
44736
- callback(payload.polls[0]);
44737
- };
44738
- return createEventSubscriber(client, 'poll/onPollUpdated', 'poll.updated', filter);
44739
- };
44740
-
44741
- /**
44742
- * ```js
44743
- * import { onPollDeleted } from '@amityco/ts-sdk'
44744
- * const dispose = onPollDeleted(poll => {
44745
- * // ...
44746
- * })
44747
- * ```
44748
- *
44749
- * Fired when an {@link Amity.Poll} has been deleted
44750
- *
44751
- * @param callback The function to call when the event was fired
44752
- * @returns an {@link Amity.Unsubscriber} function to stop listening
44753
- *
44754
- * @category Poll Events
44755
- */
44756
- const onPollDeleted = (callback) => {
44757
- const client = getActiveClient();
44758
- const filter = (payload) => {
44759
- if (client.cache)
44760
- ingestInCache(payload);
44761
- callback(payload.polls[0]);
44762
- };
44763
- return createEventSubscriber(client, 'poll/onPollDeleted', 'poll.deleted', filter);
44764
- };
44765
-
44766
- /* begin_public_function
44767
- id: poll.get
44768
- */
44769
- /**
44770
- * ```js
44771
- * import { PollRepository } from '@amityco/ts-sdk';
44772
- *
44773
- * let poll;
44774
- *
44775
- * const unsub = PollRepository.getPoll(commentId, response => {
44776
- * poll = response.data;
44777
- * });
44778
- * ```
44779
- *
44780
- * Observe all mutation on a given {@link Amity.Poll}
44781
- *
44782
- * @param pollId the ID of the poll to observe
44783
- * @param callback the function to call when new data are available
44784
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the poll
44785
- *
44786
- * @category Poll Live Object
44787
- */
44788
- const getPoll = (pollId, callback) => {
44789
- return liveObject(pollId, callback, 'pollId', getPoll$1, [onPollUpdated, onPollDeleted]);
44790
- };
44791
- /* end_public_function */
44792
-
44793
- var index$6 = /*#__PURE__*/Object.freeze({
44794
- __proto__: null,
44795
- createPoll: createPoll,
44796
- closePoll: closePoll,
44797
- deletePoll: deletePoll,
44798
- votePoll: votePoll,
44799
- unvotePoll: unvotePoll,
44800
- onPollUpdated: onPollUpdated,
44801
- onPollDeleted: onPollDeleted,
44802
- getPoll: getPoll
44803
- });
44804
-
44805
- 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-----";
44806
- /*
44807
- * The crypto algorithm used for importing key and signing string
44808
- */
44809
- const ALGORITHM = {
44810
- name: 'RSASSA-PKCS1-v1_5',
44811
- hash: { name: 'SHA-256' },
44812
- };
44813
- /*
44814
- * IMPORTANT!
44815
- * If you are recieving key from other platforms use an online tool to convert
44816
- * the PKCS1 to PKCS8. For instance the key from Android SDK is of the format
44817
- * PKCS1.
44818
- *
44819
- * If recieving from the platform, verify if it's already in the expected
44820
- * format. Otherwise the crypto.subtle.importKey will throw a DOMException
44821
- */
44822
- const PRIVATE_KEY_SIGNATURE = 'pkcs8';
44823
- /*
44824
- * Ensure that the private key in the .env follows this format
44825
- */
44826
- const PEM_HEADER = '-----BEGIN PRIVATE KEY-----';
44827
- const PEM_FOOTER = '-----END PRIVATE KEY-----';
44828
- /*
44829
- * The crypto.subtle.sign function returns an ArrayBuffer whereas the server
44830
- * expects a base64 string. This util helps facilitate that process
44831
- */
44832
- function base64FromArrayBuffer(buffer) {
44833
- const uint8Array = new Uint8Array(buffer);
44834
- let binary = '';
44835
- uint8Array.forEach(byte => {
44836
- binary += String.fromCharCode(byte);
44837
- });
44838
- return btoa(binary);
44839
- }
44840
- /*
44841
- * Convert a string into an ArrayBuffer
44842
- * from https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String
44843
- *
44844
- * Solely used by the importPrivateKey method
44845
- */
44846
- function str2ab(str) {
44847
- const buf = new ArrayBuffer(str.length);
44848
- const bufView = new Uint8Array(buf);
44849
- for (let i = 0, strLen = str.length; i < strLen; i += 1) {
44850
- bufView[i] = str.charCodeAt(i);
44851
- }
44852
- return buf;
44853
- }
44854
- function importPrivateKey(pem) {
44855
- // fetch the part of the PEM string between header and footer
44856
- const pemContents = pem.substring(PEM_HEADER.length, pem.length - PEM_FOOTER.length);
44857
- /*
44858
- * base64 decode the string to get the binary data
44859
- */
44860
- const binaryDerString = atob(pemContents);
44861
- // convert from a binary string to an ArrayBuffer
44862
- const binaryDer = str2ab(binaryDerString);
44863
- return crypto.subtle.importKey(PRIVATE_KEY_SIGNATURE, binaryDer, ALGORITHM, false, ['sign']);
44864
- }
44865
- async function createSignature({ timestamp, streams, }) {
44866
- const dataStr = streams
44867
- .map(item => Object.keys(item)
44868
- .sort()
44869
- .map(key => `${key}=${item[key]}`)
44870
- .join('&'))
44871
- .join(';');
44872
- /*
44873
- * nonceStr needs to be unique for each request
44874
- */
44875
- const nonceStr = uuid$1.v4();
44876
- const signStr = `nonceStr=${nonceStr}&timestamp=${timestamp}&data=${dataStr}==`;
44877
- const encoder = new TextEncoder();
44878
- const data = encoder.encode(signStr);
44879
- const key = await importPrivateKey(privateKey);
44880
- const sign = await crypto.subtle.sign(ALGORITHM, key, data);
44881
- return { signature: base64FromArrayBuffer(sign), nonceStr };
44882
- }
44883
-
44884
- async function syncUsage({ bufferCurrentUsage, getActiveStreams, updateUsage, dispose, }) {
44885
- const streams = bufferCurrentUsage();
44886
- if (!streams.length)
44887
- return;
44888
- try {
44889
- const timestamp = new Date().toISOString();
44890
- const signatureData = await createSignature({ timestamp, streams });
44891
- if (!signatureData || !signatureData.signature) {
44892
- throw new Error('Signature is undefined');
44893
- }
44894
- const payload = {
44895
- signature: signatureData.signature,
44896
- nonceStr: signatureData.nonceStr,
44897
- timestamp,
44898
- streams,
44899
- };
44900
- const client = getActiveClient();
44901
- await client.http.post('/api/v3/user-event/video-streaming', payload);
44902
- if (!getActiveStreams().length && !bufferCurrentUsage().length) {
44903
- dispose();
44904
- }
44905
- return true;
44906
- }
44907
- catch (err) {
44908
- // push buffer back to usage collector and try again in the next interval
44909
- streams.forEach(stream => updateUsage(stream));
44910
- return false;
44911
- }
44912
- }
44913
-
44914
- /*
44915
- * It was originally planned to be 10 seconds but the signature creation is a
44916
- * slow process and can take upto 4 to 5 seconds, which might lead to data
44917
- * inconsitencies and adds complexity to manging sync data.
44918
- *
44919
- * Hence, I've incerased the USAGE_SYNC_INTERVAL to ensure a more maintainable
44920
- * code
44921
- */
44922
- const USAGE_SYNC_INTERVAL = 20 * 1000; // 20 seconds;
44923
- /**
44924
- * @class
44925
- *
44926
- * Usage Collector is responsible for collecting data from live stream video
44927
- * events and periodically passing the collected data down to Usage Syncer
44451
+ * Usage Collector is responsible for collecting data from live stream video
44452
+ * events and periodically passing the collected data down to Usage Syncer
44928
44453
  *
44929
44454
  */
44930
44455
  class UsageCollector {
@@ -45173,7 +44698,7 @@ const getPlayer = async (parameters) => {
45173
44698
  return video;
45174
44699
  };
45175
44700
 
45176
- var index$5 = /*#__PURE__*/Object.freeze({
44701
+ var index$6 = /*#__PURE__*/Object.freeze({
45177
44702
  __proto__: null,
45178
44703
  getPlayer: getPlayer
45179
44704
  });
@@ -45965,85 +45490,649 @@ const getTargetsByTargetIds = (params, callback) => {
45965
45490
  onFetch(true);
45966
45491
  disposers.push(() => dropFromCache(cacheKey));
45967
45492
  return () => {
45968
- log(`getTargetsByTargetIds(tmpid: ${timestamp}) > dispose`);
45493
+ log(`getTargetsByTargetIds(tmpid: ${timestamp}) > dispose`);
45494
+ disposers.forEach(fn => fn());
45495
+ };
45496
+ };
45497
+
45498
+ class StoryQueryStreamController extends QueryStreamController {
45499
+ constructor(query, cacheKey, notifyChange, paginationController) {
45500
+ super(query, cacheKey);
45501
+ this.notifyChange = notifyChange;
45502
+ this.paginationController = paginationController;
45503
+ }
45504
+ // eslint-disable-next-line class-methods-use-this
45505
+ saveToMainDB(response) {
45506
+ const client = getActiveClient();
45507
+ const cachedAt = client.cache && Date.now();
45508
+ const convertedData = convertRawStoryToInternal(response);
45509
+ if (client.cache) {
45510
+ ingestInCache(convertedData, { cachedAt });
45511
+ // Update local last story expires
45512
+ updateLocalLastStoryExpires(convertedData.stories);
45513
+ // Map storyId to referenceId
45514
+ mappingStoryIdToReferenceId(convertedData.stories);
45515
+ }
45516
+ }
45517
+ // eslint-disable-next-line class-methods-use-this
45518
+ getStoryReferenceIds(story) {
45519
+ if (story === null || story === void 0 ? void 0 : story.referenceId) {
45520
+ return story.referenceId;
45521
+ }
45522
+ return story.storyId;
45523
+ }
45524
+ appendToQueryStream(response, direction, refresh = false) {
45525
+ var _a, _b;
45526
+ if (refresh) {
45527
+ pushToCache(this.cacheKey, {
45528
+ data: response.stories.map(this.getStoryReferenceIds),
45529
+ });
45530
+ }
45531
+ else {
45532
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
45533
+ const stories = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
45534
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...stories, ...response.stories.map(this.getStoryReferenceIds)])] }));
45535
+ }
45536
+ }
45537
+ reactor(action) {
45538
+ return (payload) => {
45539
+ var _a;
45540
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
45541
+ if (!collection)
45542
+ return;
45543
+ const newReferenceIds = payload.map(({ referenceId }) => referenceId);
45544
+ collection.data = [...new Set([...newReferenceIds, ...collection.data])];
45545
+ pushToCache(this.cacheKey, collection);
45546
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
45547
+ };
45548
+ }
45549
+ subscribeRTE(createSubscriber) {
45550
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
45551
+ }
45552
+ }
45553
+
45554
+ class StoryPaginationNoPageController extends PaginationNoPageController {
45555
+ async getRequest(queryParams) {
45556
+ const { data: queryResponse } = await this.http.get('/api/v4/stories-by-targets', {
45557
+ params: Object.assign({}, queryParams),
45558
+ });
45559
+ return queryResponse;
45560
+ }
45561
+ }
45562
+
45563
+ class StoryLiveCollectionController extends LiveCollectionController {
45564
+ constructor(query, callback) {
45565
+ const queryStreamId = hash(query);
45566
+ const cacheKey = ["story-target-ids" /* STORY_KEY_CACHE.STORY_TARGET_IDS */, 'collection', queryStreamId];
45567
+ const paginationController = new StoryPaginationNoPageController(query);
45568
+ super(paginationController, queryStreamId, cacheKey, callback);
45569
+ this.query = query;
45570
+ this.queryStreamController = new StoryQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), paginationController);
45571
+ this.paginationController = paginationController;
45572
+ this.callback = callback.bind(this);
45573
+ this.loadPage({ initial: true });
45574
+ }
45575
+ setup() {
45576
+ var _a;
45577
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
45578
+ if (!collection) {
45579
+ pushToCache(this.cacheKey, {
45580
+ data: [],
45581
+ params: {},
45582
+ });
45583
+ }
45584
+ }
45585
+ persistModel(response) {
45586
+ this.queryStreamController.saveToMainDB(response);
45587
+ }
45588
+ persistQueryStream({ response, direction, refresh, }) {
45589
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
45590
+ }
45591
+ notifyChange({ origin, loading, error }) {
45592
+ var _a;
45593
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
45594
+ if (!collection)
45595
+ return;
45596
+ let data = collection.data
45597
+ .map(referenceId => pullFromCache(["story" /* STORY_KEY_CACHE.STORY */, 'get', referenceId]))
45598
+ .filter(Boolean)
45599
+ .map(internStory => LinkedObject.story(internStory.data));
45600
+ if (!this.shouldNotify(data) && origin === 'event')
45601
+ return;
45602
+ data = this.applyFilter(data);
45603
+ this.callback({
45604
+ onNextPage: undefined,
45605
+ data,
45606
+ hasNextPage: false,
45607
+ loading,
45608
+ error,
45609
+ });
45610
+ }
45611
+ applyFilter(data) {
45612
+ var _a, _b;
45613
+ const internalStories = data;
45614
+ const orderBy = ((_b = (_a = this.query) === null || _a === void 0 ? void 0 : _a.options) === null || _b === void 0 ? void 0 : _b.orderBy) || 'desc';
45615
+ return orderBy === 'asc'
45616
+ ? internalStories.sort(sortByFirstCreated)
45617
+ : internalStories.sort(sortByLastCreated);
45618
+ }
45619
+ startSubscription() {
45620
+ return this.queryStreamController.subscribeRTE([
45621
+ { fn: onStoryCreated, action: "onCreate" /* Amity.StoryActionType.OnCreate */ },
45622
+ { fn: onStoryUpdated, action: "onUpdate" /* Amity.StoryActionType.OnUpdate */ },
45623
+ { fn: onStoryDeleted, action: "onDelete" /* Amity.StoryActionType.OnDelete */ },
45624
+ { fn: onStoryError, action: "onError" /* Amity.StoryActionType.OnError */ },
45625
+ ]);
45626
+ }
45627
+ }
45628
+
45629
+ const getStoriesByTargetIds = (params, callback, config) => {
45630
+ const { log, cache, userId } = getActiveClient();
45631
+ if (!cache) {
45632
+ console.log(ENABLE_CACHE_MESSAGE);
45633
+ }
45634
+ const timestamp = Date.now();
45635
+ log(`getStoriesByTargetIds(tmpid: ${timestamp}) > listen`);
45636
+ const storyLiveCollection = new StoryLiveCollectionController(params, callback);
45637
+ const disposers = storyLiveCollection.startSubscription();
45638
+ const cacheKey = storyLiveCollection.getCacheKey();
45639
+ disposers.push(() => {
45640
+ dropFromCache(cacheKey);
45641
+ });
45642
+ return () => {
45643
+ log(`getStoriesByTargetIds(tmpid: ${timestamp}) > dispose`);
45644
+ disposers.forEach(fn => fn());
45645
+ };
45646
+ };
45647
+
45648
+ const updateLocalList = (cacheKey, targetIds) => {
45649
+ var _a, _b;
45650
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
45651
+ const storyTargets = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
45652
+ pushToCache(cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...storyTargets, ...targetIds])] }));
45653
+ };
45654
+ class GlobalStoryQueryStreamController extends QueryStreamController {
45655
+ constructor(query, cacheKey, notifyChange, paginationController, preparePayload) {
45656
+ super(query, cacheKey);
45657
+ this.notifyChange = notifyChange;
45658
+ this.paginationController = paginationController;
45659
+ // Fix ESLint, "Expected 'this' to be used by class method"
45660
+ this.preparePayload = preparePayload;
45661
+ }
45662
+ saveToMainDB(response) {
45663
+ const client = getActiveClient();
45664
+ const cachedAt = client.cache && Date.now();
45665
+ // Fix Eslint error for "Expected 'this' to be used by class method"
45666
+ const data = this.preparePayload(response);
45667
+ if (client.cache) {
45668
+ ingestInCache(data, { cachedAt });
45669
+ }
45670
+ }
45671
+ appendToQueryStream(response, direction, refresh = false) {
45672
+ if (refresh) {
45673
+ pushToCache(this.cacheKey, {
45674
+ data: response.storyTargets.map(({ targetId }) => targetId),
45675
+ });
45676
+ }
45677
+ else {
45678
+ updateLocalList(this.cacheKey, response.storyTargets.map(({ targetId }) => targetId));
45679
+ }
45680
+ }
45681
+ reactor(actionType) {
45682
+ return (payload) => {
45683
+ if (actionType === "onCreate" /* Amity.StoryActionType.OnCreate */ &&
45684
+ this.query.seenState !== "seen" /* Amity.StorySeenQuery.SEEN */) {
45685
+ updateLocalList(this.cacheKey, payload.map(({ targetId }) => targetId));
45686
+ }
45687
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
45688
+ };
45689
+ }
45690
+ subscribeRTE(createSubscriber) {
45691
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
45692
+ }
45693
+ }
45694
+
45695
+ const mergeResult = (resultA, resultB) => {
45696
+ return {
45697
+ categories: resultA.categories.concat(resultB.categories),
45698
+ communities: resultA.communities.concat(resultB.communities),
45699
+ communityUsers: resultA.communityUsers.concat(resultB.communityUsers),
45700
+ files: resultA.files.concat(resultB.files),
45701
+ storyTargets: resultA.storyTargets.concat(resultB.storyTargets),
45702
+ users: resultA.users.concat(resultB.users),
45703
+ paging: resultB.paging,
45704
+ };
45705
+ };
45706
+ const addFlagLocalFilter = (payload, filter) => {
45707
+ return Object.assign(Object.assign({}, payload), { storyTargets: payload.storyTargets.map(item => (Object.assign(Object.assign({}, item), { localFilter: filter }))) || [] });
45708
+ };
45709
+ class GlobalStoryPageController extends PaginationController {
45710
+ constructor() {
45711
+ super(...arguments);
45712
+ this.smartFilterState = "unseen" /* Amity.StorySeenQuery.UNSEEN */;
45713
+ }
45714
+ async getRequest(queryParams, token) {
45715
+ var _a;
45716
+ // Apply default values for parameters
45717
+ const { limit = 10, seenState = "unseen" /* Amity.StorySeenQuery.UNSEEN */ } = queryParams;
45718
+ const result = await this.createRequest({
45719
+ seenState: seenState === "smart" /* Amity.StorySeenQuery.SMART */ ? this.smartFilterState : seenState,
45720
+ limit,
45721
+ token,
45722
+ });
45723
+ // Use Early return to reduce condition complexity
45724
+ if ((_a = result.paging) === null || _a === void 0 ? void 0 : _a.next)
45725
+ return result;
45726
+ if (seenState !== "smart" /* Amity.StorySeenQuery.SMART */)
45727
+ return result;
45728
+ if (this.smartFilterState === "seen" /* Amity.StorySeenQuery.SEEN */)
45729
+ return result;
45730
+ this.smartFilterState = "seen" /* Amity.StorySeenQuery.SEEN */;
45731
+ const additionalResult = await this.createRequest({
45732
+ seenState: this.smartFilterState,
45733
+ limit,
45734
+ });
45735
+ return mergeResult(result, additionalResult);
45736
+ }
45737
+ async createRequest(params) {
45738
+ const { data: queryResponse } = await this.http.get('/api/v5/me/global-story-targets', {
45739
+ params,
45740
+ });
45741
+ return addFlagLocalFilter(queryResponse, params.seenState);
45742
+ }
45743
+ }
45744
+
45745
+ class GlobalStoryLiveCollectionController extends LiveCollectionController {
45746
+ constructor(query, callback) {
45747
+ const queryStreamId = hash(query);
45748
+ const cacheKey = ["story-global-feed" /* STORY_KEY_CACHE.STORY_GLOBAL_FEED */, 'collection', queryStreamId];
45749
+ const paginationController = new GlobalStoryPageController(query);
45750
+ super(paginationController, queryStreamId, cacheKey, callback);
45751
+ this.query = query;
45752
+ this.queryStreamController = new GlobalStoryQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), paginationController, (data) => {
45753
+ const _a = prepareCommunityPayload(Object.assign(Object.assign({}, data), { feeds: [] })), rest = __rest(_a, ["feeds"]);
45754
+ return Object.assign(Object.assign({}, data), rest);
45755
+ });
45756
+ this.paginationController = paginationController;
45757
+ this.callback = callback.bind(this);
45758
+ this.loadPage({ initial: true });
45759
+ }
45760
+ setup() {
45761
+ var _a;
45762
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
45763
+ if (!collection) {
45764
+ pushToCache(this.cacheKey, {
45765
+ data: [],
45766
+ params: {},
45767
+ });
45768
+ }
45769
+ }
45770
+ persistModel(response) {
45771
+ this.queryStreamController.saveToMainDB(response);
45772
+ }
45773
+ persistQueryStream({ response, direction, refresh, }) {
45774
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
45775
+ }
45776
+ notifyChange({ origin, loading, error }) {
45777
+ var _a;
45778
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
45779
+ if (!collection)
45780
+ return;
45781
+ const targetIds = collection.data;
45782
+ const cachedTargets = queryCache(["storyTarget" /* STORY_KEY_CACHE.STORY_TARGET */]);
45783
+ if (cachedTargets && (cachedTargets === null || cachedTargets === void 0 ? void 0 : cachedTargets.length) > 0) {
45784
+ cachedTargets === null || cachedTargets === void 0 ? void 0 : cachedTargets.forEach(({ key }) => {
45785
+ if (!collection.data.includes(key[2]))
45786
+ targetIds.push(key[2]);
45787
+ });
45788
+ }
45789
+ let data = targetIds
45790
+ .map(targetId => pullFromCache(["storyTarget" /* STORY_KEY_CACHE.STORY_TARGET */, 'get', targetId]))
45791
+ .filter(Boolean)
45792
+ .map(storyTarget => LinkedObject.storyTarget(storyTarget.data));
45793
+ if (!this.shouldNotify(data) && origin === 'event')
45794
+ return;
45795
+ data = this.applyFilter(data)
45796
+ // exclude story targets with invalid stories
45797
+ .filter(({ localSortingDate }) => !!localSortingDate)
45798
+ // Remove internal fields
45799
+ .map((_a) => {
45800
+ var rest = __rest(_a, ["localFilter", "localLastExpires", "localLastSeen", "localSortingDate"]);
45801
+ return rest;
45802
+ });
45803
+ this.callback({
45804
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
45805
+ data,
45806
+ hasNextPage: !!this.paginationController.getNextToken(),
45807
+ loading,
45808
+ error,
45809
+ });
45810
+ }
45811
+ applyFilter(data) {
45812
+ if (this.query.seenState !== "smart" /* Amity.StorySeenQuery.SMART */) {
45813
+ return data
45814
+ .filter(({ hasUnseen }) => {
45815
+ if (this.query.seenState === "all" /* Amity.StorySeenQuery.ALL */)
45816
+ return true;
45817
+ if (this.query.seenState === "seen" /* Amity.StorySeenQuery.SEEN */ && !hasUnseen)
45818
+ return true;
45819
+ return this.query.seenState === "unseen" /* Amity.StorySeenQuery.UNSEEN */ && hasUnseen;
45820
+ })
45821
+ .sort(sortByLocalSortingDate);
45822
+ }
45823
+ // Smart Filter - Apply local sorting on each list of data
45824
+ const result = data.reduce((acc, storyTarget) => {
45825
+ if (storyTarget.localFilter === "unseen" /* Amity.StorySeenQuery.UNSEEN */) {
45826
+ acc.unseen.push(storyTarget);
45827
+ }
45828
+ else if (storyTarget.localFilter === "seen" /* Amity.StorySeenQuery.SEEN */) {
45829
+ acc.seen.push(storyTarget);
45830
+ }
45831
+ else {
45832
+ acc.unknown.push(storyTarget);
45833
+ }
45834
+ return acc;
45835
+ }, { unseen: [], seen: [], unknown: [] });
45836
+ const sortedUnknown = result.unknown.sort(sortByLocalSortingDate) || [];
45837
+ const sortedUnseen = result.unseen.sort(sortByLocalSortingDate) || [];
45838
+ const sortedSeen = result.seen.sort(sortByLocalSortingDate) || [];
45839
+ // Merge all status and remove internal fields
45840
+ return sortedUnknown.concat(sortedUnseen, sortedSeen);
45841
+ }
45842
+ startSubscription() {
45843
+ return this.queryStreamController.subscribeRTE([
45844
+ { fn: onStoryCreated, action: "onCreate" /* Amity.StoryActionType.OnCreate */ },
45845
+ { fn: onStoryUpdated, action: "onUpdate" /* Amity.StoryActionType.OnUpdate */ },
45846
+ { fn: onStoryDeleted, action: "onDelete" /* Amity.StoryActionType.OnDelete */ },
45847
+ { fn: onStoryCreatedLocal, action: "onCreate" /* Amity.StoryActionType.OnCreate */ },
45848
+ { fn: onStoryUpdatedLocal, action: "onUpdate" /* Amity.StoryActionType.OnUpdate */ },
45849
+ { fn: onStoryDeletedLocal, action: "onDelete" /* Amity.StoryActionType.OnDelete */ },
45850
+ { fn: onStoryError, action: "onError" /* Amity.StoryActionType.OnError */ },
45851
+ ]);
45852
+ }
45853
+ }
45854
+
45855
+ const getGlobalStoryTargets = (params, callback, config) => {
45856
+ const { log, cache, userId } = getActiveClient();
45857
+ if (!cache) {
45858
+ console.log(ENABLE_CACHE_MESSAGE);
45859
+ }
45860
+ const timestamp = Date.now();
45861
+ log(`getGlobalStoryTarget(tmpid: ${timestamp}) > listen`);
45862
+ const storyLiveCollection = new GlobalStoryLiveCollectionController(params, callback);
45863
+ const disposers = storyLiveCollection.startSubscription();
45864
+ const cacheKey = storyLiveCollection.getCacheKey();
45865
+ disposers.push(() => {
45866
+ dropFromCache(cacheKey);
45867
+ });
45868
+ return () => {
45869
+ log(`getGlobalStoryTarget(tmpid: ${timestamp}) > dispose`);
45870
+ disposers.forEach(fn => fn());
45871
+ };
45872
+ };
45873
+
45874
+ var index$5 = /*#__PURE__*/Object.freeze({
45875
+ __proto__: null,
45876
+ createImageStory: createImageStory,
45877
+ createVideoStory: createVideoStory,
45878
+ hardDeleteStory: hardDeleteStory,
45879
+ softDeleteStory: softDeleteStory,
45880
+ getActiveStoriesByTarget: getActiveStoriesByTarget,
45881
+ getStoryByStoryId: getStoryByStoryId,
45882
+ getTargetById: getTargetById,
45883
+ getTargetsByTargetIds: getTargetsByTargetIds,
45884
+ getStoriesByTargetIds: getStoriesByTargetIds,
45885
+ getGlobalStoryTargets: getGlobalStoryTargets
45886
+ });
45887
+
45888
+ const convertToInternalAd = (ad) => {
45889
+ return Object.assign(Object.assign({}, ad), { endAt: ad.endAt ? ad.endAt : null });
45890
+ };
45891
+ const convertToInternalAdvertiser = (advertiser) => {
45892
+ return Object.assign({}, advertiser);
45893
+ };
45894
+ const getNetworkAds = async () => {
45895
+ const client = getActiveClient();
45896
+ const { data } = await client.http.get('/api/v1/ads/me');
45897
+ const internalAds = data.ads.map(convertToInternalAd);
45898
+ const internalAdvertisers = data.advertisers.map(convertToInternalAdvertiser);
45899
+ ingestInCache({
45900
+ ads: internalAds,
45901
+ advertisers: internalAdvertisers,
45902
+ files: data.files,
45903
+ });
45904
+ pushToCache(['ad', 'setting'], data.settings);
45905
+ return {
45906
+ ads: internalAds.map(LinkedObject.ad),
45907
+ settings: data.settings,
45908
+ };
45909
+ };
45910
+
45911
+ var index$4 = /*#__PURE__*/Object.freeze({
45912
+ __proto__: null,
45913
+ getNetworkAds: getNetworkAds
45914
+ });
45915
+
45916
+ /**
45917
+ * Retrieves accessToken info to use in Beta services
45918
+ *
45919
+ * @param apiKey for the Http Client instance
45920
+ * @param apiRegion endpoint to connect to
45921
+ * @param params The token parameters
45922
+ * @param params.userId The userId to use to issue a token
45923
+ * @param params.displayName The user's displayName
45924
+ * @param params.authToken The authentication token - necessary when network option is set to secure
45925
+ * @return An accessToken info object for the given userId
45926
+ *
45927
+ * @category External API
45928
+ * @hidden
45929
+ */
45930
+ const createUserToken = async (apiKey, apiRegion, params) => {
45931
+ const deviceId = await getDeviceId();
45932
+ const deviceInfo = getDeviceInfo();
45933
+ const http = createHttpTransport(computeUrl('http', apiRegion));
45934
+ const { data } = await http.post('/api/v5/sessions', Object.assign(Object.assign({}, params), { deviceId, deviceInfo: Object.assign(Object.assign({}, deviceInfo), { model: 'token management API on TS-SDK' }) }), { headers: { 'X-API-Key': apiKey } });
45935
+ return { accessToken: data.accessToken };
45936
+ };
45937
+
45938
+ /* begin_public_function
45939
+ id: notificationTray.getNotificationTraySeen
45940
+ */
45941
+ /**
45942
+ * ```js
45943
+ * import { notificationTray } from '@amityco/ts-sdk'
45944
+ * const notificationTraySeen = await notificationTray.getNotificationTraySeen()
45945
+ * ```
45946
+ *
45947
+ *
45948
+ * @returns A page of {@link Amity.NotificationTraySeen} objects
45949
+ *
45950
+ * @category NotificationTray API
45951
+ * @async
45952
+ * */
45953
+ const getNotificationTraySeen$1 = async () => {
45954
+ const client = getActiveClient();
45955
+ client.log('notificationTray/getNotificationTraySeen', {});
45956
+ const { data: payload } = await client.http.get(`api/v1/notification-tray/tray/seen`);
45957
+ const cachedAt = client.cache && Date.now();
45958
+ if (client.cache) {
45959
+ const cacheKey = ['notificationTraySeen', 'get', client.userId];
45960
+ pushToCache(cacheKey, {
45961
+ userId: client.userId,
45962
+ lastTraySeenAt: payload.lastTraySeenAt,
45963
+ lastTrayOccuredAt: payload.lastTrayOccurredAt,
45964
+ });
45965
+ }
45966
+ return {
45967
+ data: {
45968
+ userId: client.userId,
45969
+ lastTraySeenAt: payload.lastTraySeenAt,
45970
+ lastTrayOccurredAt: payload.lastTrayOccurredAt,
45971
+ isSeen: payload.lastTraySeenAt > payload.lastTrayOccurredAt,
45972
+ },
45973
+ cachedAt,
45974
+ };
45975
+ };
45976
+ /* end_public_function */
45977
+ /**
45978
+ * ```js
45979
+ * import { notificationTray } from '@amityco/ts-sdk'
45980
+ * const notificationTraySeen = await notificationTray.getNotificationTraySeen.locally()
45981
+ * ```
45982
+ *
45983
+ * Queries a paginable list of {@link Amity.NotificationTraySeen} objects from cache
45984
+ *
45985
+ * @returns A page of {@link Amity.NotificationTraySeen} objects
45986
+ *
45987
+ * @category NotificationTray API
45988
+ * @async
45989
+ * */
45990
+ getNotificationTraySeen$1.locally = () => {
45991
+ var _a;
45992
+ const client = getActiveClient();
45993
+ client.log('notificationTray/getNotificationTraySeen.locally', {});
45994
+ if (!client.cache)
45995
+ return;
45996
+ const queryKey = ['notificationTraySeen', 'get'];
45997
+ const { data, cachedAt } = (_a = pullFromCache(queryKey)) !== null && _a !== void 0 ? _a : {};
45998
+ if (!data)
45999
+ return;
46000
+ return { data, cachedAt };
46001
+ };
46002
+
46003
+ /**
46004
+ * ```js
46005
+ * import { onNotificationTraySeenUpdated } from '@amityco/ts-sdk'
46006
+ * const dispose = onNotificationTraySeenUpdated(data => {
46007
+ * // ...
46008
+ * })
46009
+ * ```
46010
+ *
46011
+ * Fired when an {@link Amity.NotificationTraySeen} has been updated
46012
+ *
46013
+ * @param callback The function to call when the event was fired
46014
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
46015
+ *
46016
+ * @category NotificationTraySeen Events
46017
+ */
46018
+ const onNotificationTraySeenUpdated = (callback) => {
46019
+ const client = getActiveClient();
46020
+ const disposers = [
46021
+ createEventSubscriber(client, 'onNotificationTraySeenUpdated', 'local.notificationTraySeen.updated', payload => callback(payload)),
46022
+ ];
46023
+ return () => {
45969
46024
  disposers.forEach(fn => fn());
45970
46025
  };
45971
46026
  };
45972
46027
 
45973
- class StoryQueryStreamController extends QueryStreamController {
45974
- constructor(query, cacheKey, notifyChange, paginationController) {
46028
+ /* begin_public_function
46029
+ id: notificationTray.getNotificationTraySeen
46030
+ */
46031
+ /**
46032
+ * ```js
46033
+ * import { notificationTray } from '@amityco/ts-sdk';
46034
+ *
46035
+ * let notificationTraySeen;
46036
+ *
46037
+ * const unsubscribe = getNotificationTraySeen(response => {
46038
+ * notificationTraySeen = response.data;
46039
+ * });
46040
+ * ```
46041
+ *
46042
+ * Observe all mutation on a given {@link Amity.NotificationTraySeen}
46043
+ *
46044
+ * @param callback the function to call when new data are available
46045
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the message
46046
+ *
46047
+ * @category NotificationTraySeen Live Object
46048
+ */
46049
+ const getNotificationTraySeen = (callback) => {
46050
+ const { userId } = getActiveUser();
46051
+ return liveObject(userId, callback, 'userId', getNotificationTraySeen$1, [onNotificationTraySeenUpdated], {
46052
+ callbackDataSelector: (data) => {
46053
+ let isSeen = true;
46054
+ if (data === null || data === void 0 ? void 0 : data.lastTrayOccurredAt) {
46055
+ if (!data.lastTraySeenAt) {
46056
+ isSeen = false;
46057
+ }
46058
+ else {
46059
+ isSeen =
46060
+ convertDateStringToTimestamp(data.lastTraySeenAt) >
46061
+ convertDateStringToTimestamp(data.lastTrayOccurredAt);
46062
+ }
46063
+ }
46064
+ return {
46065
+ lastTrayOccurredAt: data === null || data === void 0 ? void 0 : data.lastTrayOccurredAt,
46066
+ lastTraySeenAt: data === null || data === void 0 ? void 0 : data.lastTraySeenAt,
46067
+ isSeen,
46068
+ };
46069
+ },
46070
+ });
46071
+ };
46072
+ /* end_public_function */
46073
+
46074
+ /**
46075
+ * TODO: handle cache receive cache option, and cache policy
46076
+ * TODO: check if querybyIds is supported
46077
+ */
46078
+ class NotificationTrayItemsPaginationController extends PaginationController {
46079
+ async getRequest(queryParams, token) {
46080
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
46081
+ const options = token ? { token } : { limit };
46082
+ const { data: queryResponse } = await this.http.get(`/api/v1/notification-tray`, {
46083
+ params: Object.assign(Object.assign({}, params), { options }),
46084
+ });
46085
+ return queryResponse;
46086
+ }
46087
+ }
46088
+
46089
+ class NotificationTrayItemsQuerystreamController extends QueryStreamController {
46090
+ constructor(query, cacheKey, notifyChange, preparePayload) {
45975
46091
  super(query, cacheKey);
45976
46092
  this.notifyChange = notifyChange;
45977
- this.paginationController = paginationController;
46093
+ this.preparePayload = preparePayload;
45978
46094
  }
45979
- // eslint-disable-next-line class-methods-use-this
45980
- saveToMainDB(response) {
46095
+ async saveToMainDB(response) {
46096
+ const processedPayload = await this.preparePayload(response);
45981
46097
  const client = getActiveClient();
45982
46098
  const cachedAt = client.cache && Date.now();
45983
- const convertedData = convertRawStoryToInternal(response);
45984
46099
  if (client.cache) {
45985
- ingestInCache(convertedData, { cachedAt });
45986
- // Update local last story expires
45987
- updateLocalLastStoryExpires(convertedData.stories);
45988
- // Map storyId to referenceId
45989
- mappingStoryIdToReferenceId(convertedData.stories);
45990
- }
45991
- }
45992
- // eslint-disable-next-line class-methods-use-this
45993
- getStoryReferenceIds(story) {
45994
- if (story === null || story === void 0 ? void 0 : story.referenceId) {
45995
- return story.referenceId;
46100
+ ingestInCache(processedPayload, { cachedAt });
45996
46101
  }
45997
- return story.storyId;
45998
46102
  }
45999
46103
  appendToQueryStream(response, direction, refresh = false) {
46000
46104
  var _a, _b;
46001
46105
  if (refresh) {
46002
46106
  pushToCache(this.cacheKey, {
46003
- data: response.stories.map(this.getStoryReferenceIds),
46107
+ data: response.notificationTrayItems.map(getResolver('notificationTrayItem')),
46004
46108
  });
46005
46109
  }
46006
46110
  else {
46007
46111
  const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
46008
- const stories = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
46009
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...stories, ...response.stories.map(this.getStoryReferenceIds)])] }));
46112
+ const notifications = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
46113
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
46114
+ ...new Set([
46115
+ ...notifications,
46116
+ ...response.notificationTrayItems.map(getResolver('notificationTrayItem')),
46117
+ ]),
46118
+ ] }));
46010
46119
  }
46011
46120
  }
46012
- reactor(action) {
46013
- return (payload) => {
46014
- var _a;
46015
- const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
46016
- if (!collection)
46017
- return;
46018
- const newReferenceIds = payload.map(({ referenceId }) => referenceId);
46019
- collection.data = [...new Set([...newReferenceIds, ...collection.data])];
46020
- pushToCache(this.cacheKey, collection);
46021
- this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
46022
- };
46023
- }
46024
- subscribeRTE(createSubscriber) {
46025
- return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
46026
- }
46027
46121
  }
46028
46122
 
46029
- class StoryPaginationNoPageController extends PaginationNoPageController {
46030
- async getRequest(queryParams) {
46031
- const { data: queryResponse } = await this.http.get('/api/v4/stories-by-targets', {
46032
- params: Object.assign({}, queryParams),
46033
- });
46034
- return queryResponse;
46035
- }
46036
- }
46123
+ const prepareNotificationTrayItemsPayload = (rawPayload) => {
46124
+ const users = rawPayload.users.map(convertRawUserToInternalUser);
46125
+ return Object.assign(Object.assign({}, rawPayload), { users });
46126
+ };
46037
46127
 
46038
- class StoryLiveCollectionController extends LiveCollectionController {
46128
+ class NotificationTrayItemsLiveCollectionController extends LiveCollectionController {
46039
46129
  constructor(query, callback) {
46040
46130
  const queryStreamId = hash(query);
46041
- const cacheKey = ["story-target-ids" /* STORY_KEY_CACHE.STORY_TARGET_IDS */, 'collection', queryStreamId];
46042
- const paginationController = new StoryPaginationNoPageController(query);
46131
+ const cacheKey = ['notificationTrayItem', 'collection', queryStreamId];
46132
+ const paginationController = new NotificationTrayItemsPaginationController(query);
46043
46133
  super(paginationController, queryStreamId, cacheKey, callback);
46044
46134
  this.query = query;
46045
- this.queryStreamController = new StoryQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), paginationController);
46046
- this.paginationController = paginationController;
46135
+ this.queryStreamController = new NotificationTrayItemsQuerystreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareNotificationTrayItemsPayload);
46047
46136
  this.callback = callback.bind(this);
46048
46137
  this.loadPage({ initial: true });
46049
46138
  }
@@ -46057,108 +46146,232 @@ class StoryLiveCollectionController extends LiveCollectionController {
46057
46146
  });
46058
46147
  }
46059
46148
  }
46060
- persistModel(response) {
46061
- this.queryStreamController.saveToMainDB(response);
46149
+ async persistModel(queryPayload) {
46150
+ await this.queryStreamController.saveToMainDB(queryPayload);
46062
46151
  }
46063
46152
  persistQueryStream({ response, direction, refresh, }) {
46064
46153
  this.queryStreamController.appendToQueryStream(response, direction, refresh);
46065
46154
  }
46155
+ // eslint-disable-next-line class-methods-use-this
46156
+ startSubscription() {
46157
+ return [];
46158
+ }
46066
46159
  notifyChange({ origin, loading, error }) {
46067
- var _a;
46160
+ var _a, _b;
46068
46161
  const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
46069
46162
  if (!collection)
46070
46163
  return;
46071
- let data = collection.data
46072
- .map(referenceId => pullFromCache(["story" /* STORY_KEY_CACHE.STORY */, 'get', referenceId]))
46073
- .filter(Boolean)
46074
- .map(internStory => LinkedObject.story(internStory.data));
46164
+ const data = ((_b = collection.data
46165
+ .map(id => pullFromCache(['notificationTrayItem', 'get', id]))
46166
+ .filter(isNonNullable)
46167
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.notificationTray);
46075
46168
  if (!this.shouldNotify(data) && origin === 'event')
46076
46169
  return;
46077
- data = this.applyFilter(data);
46078
46170
  this.callback({
46079
- onNextPage: undefined,
46171
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
46080
46172
  data,
46081
- hasNextPage: false,
46173
+ hasNextPage: !!this.paginationController.getNextToken(),
46082
46174
  loading,
46083
46175
  error,
46084
46176
  });
46085
46177
  }
46086
- applyFilter(data) {
46087
- var _a, _b;
46088
- const internalStories = data;
46089
- const orderBy = ((_b = (_a = this.query) === null || _a === void 0 ? void 0 : _a.options) === null || _b === void 0 ? void 0 : _b.orderBy) || 'desc';
46090
- return orderBy === 'asc'
46091
- ? internalStories.sort(sortByFirstCreated)
46092
- : internalStories.sort(sortByLastCreated);
46093
- }
46094
- startSubscription() {
46095
- return this.queryStreamController.subscribeRTE([
46096
- { fn: onStoryCreated, action: "onCreate" /* Amity.StoryActionType.OnCreate */ },
46097
- { fn: onStoryUpdated, action: "onUpdate" /* Amity.StoryActionType.OnUpdate */ },
46098
- { fn: onStoryDeleted, action: "onDelete" /* Amity.StoryActionType.OnDelete */ },
46099
- { fn: onStoryError, action: "onError" /* Amity.StoryActionType.OnError */ },
46100
- ]);
46101
- }
46102
46178
  }
46103
46179
 
46104
- const getStoriesByTargetIds = (params, callback, config) => {
46105
- const { log, cache, userId } = getActiveClient();
46180
+ /**
46181
+ * Get notification tray items for a notification tray page
46182
+ *
46183
+ * @param params the limit query parameters
46184
+ * @param callback the callback to be called when the notification tray items are updated
46185
+ * @returns items in the notification tray
46186
+ *
46187
+ * @category Notification tray items Live Collection
46188
+ *
46189
+ */
46190
+ const getNotificationTrayItems = (params, callback, config) => {
46191
+ const { log, cache } = getActiveClient();
46106
46192
  if (!cache) {
46107
46193
  console.log(ENABLE_CACHE_MESSAGE);
46108
46194
  }
46109
46195
  const timestamp = Date.now();
46110
- log(`getStoriesByTargetIds(tmpid: ${timestamp}) > listen`);
46111
- const storyLiveCollection = new StoryLiveCollectionController(params, callback);
46112
- const disposers = storyLiveCollection.startSubscription();
46113
- const cacheKey = storyLiveCollection.getCacheKey();
46114
- disposers.push(() => {
46115
- dropFromCache(cacheKey);
46116
- });
46196
+ log(`getNotificationTrayItems(tmpid: ${timestamp}) > listen`);
46197
+ const notiTrayItemsLiveCollection = new NotificationTrayItemsLiveCollectionController(params, callback);
46198
+ const disposers = notiTrayItemsLiveCollection.startSubscription();
46199
+ const cacheKey = notiTrayItemsLiveCollection.getCacheKey();
46200
+ disposers.push(() => dropFromCache(cacheKey));
46117
46201
  return () => {
46118
- log(`getStoriesByTargetIds(tmpid: ${timestamp}) > dispose`);
46202
+ log(`getNotificationTrayItems(tmpid: ${timestamp}) > dispose`);
46119
46203
  disposers.forEach(fn => fn());
46120
46204
  };
46121
46205
  };
46122
46206
 
46123
- const updateLocalList = (cacheKey, targetIds) => {
46124
- var _a, _b;
46125
- const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
46126
- const storyTargets = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
46127
- pushToCache(cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...storyTargets, ...targetIds])] }));
46207
+ /* begin_public_function
46208
+ id: notificationTrayItem.markSeen
46209
+ */
46210
+ /**
46211
+ * ```js
46212
+ * import { notificationTray } from '@amityco/ts-sdk'
46213
+ * const updated = await notificationTray.markItemsSeen()
46214
+ * ```
46215
+ *
46216
+ * Updates an {@link Amity.NotificationItemSeen}
46217
+ *
46218
+ * @param trayItems[] that include id and lastTraySeenAt, The ID of the {@link Amity.NotificationItemSeen} to edit
46219
+ * @returns the updated {@link Amity.NotificationItemSeen} object
46220
+ *
46221
+ * @category NotificationItemSeen API
46222
+ * @async
46223
+ */
46224
+ const markItemsSeen = async (trayItems) => {
46225
+ const client = getActiveClient();
46226
+ client.log('notificationTray/markItemsSeen', {});
46227
+ const { data: payload } = await client.http.post(`api/v1/notification-tray/items/seen`, {
46228
+ trayItems: trayItems.map(item => ({
46229
+ id: item.id,
46230
+ lastSeenAt: item.lastSeenAt,
46231
+ })),
46232
+ });
46233
+ const updatedData = payload.trayItems
46234
+ .map(patchItem => {
46235
+ var _a;
46236
+ const cacheData = (_a = pullFromCache([
46237
+ 'notificationTrayItem',
46238
+ 'get',
46239
+ patchItem.id,
46240
+ ])) === null || _a === void 0 ? void 0 : _a.data;
46241
+ if (!cacheData)
46242
+ return;
46243
+ const data = Object.assign(Object.assign({}, cacheData), { lastSeenAt: patchItem.lastSeenAt });
46244
+ if (client.cache) {
46245
+ const cachedAt = Date.now();
46246
+ pushToCache(['notificationTrayItem', 'get'], data, { cachedAt });
46247
+ }
46248
+ return data;
46249
+ })
46250
+ .filter(Boolean);
46251
+ fireEvent('local.notificationTrayItem.updated', { notificationTrayItems: updatedData });
46128
46252
  };
46129
- class GlobalStoryQueryStreamController extends QueryStreamController {
46130
- constructor(query, cacheKey, notifyChange, paginationController, preparePayload) {
46253
+ /* end_public_function */
46254
+
46255
+ /* begin_public_function
46256
+ id: notificationTray.markSeen
46257
+ */
46258
+ /**
46259
+ * ```js
46260
+ * import { notificationTray } from '@amityco/ts-sdk'
46261
+ * const updated = await notificationTray.markTraySeen({
46262
+ * lastSeenAt: Amity.timestamp,
46263
+ * })
46264
+ * ```
46265
+ *
46266
+ * Updates an {@link Amity.NotificationTraySeen}
46267
+ *
46268
+ * @param userId The ID of the {@link Amity.NotificationTraySeen} to edit
46269
+ * @param lastSeenAt The patch data to apply
46270
+ * @returns the updated {@link Amity.NotificationTraySeen} object
46271
+ *
46272
+ * @category Post API
46273
+ * @async
46274
+ */
46275
+ const markTraySeen = async (lastSeenAt) => {
46276
+ var _a;
46277
+ const client = getActiveClient();
46278
+ client.log('notificationTray/markTraySeen', {});
46279
+ const { data: payload } = await client.http.post(`api/v1/notification-tray/tray/seen`, {
46280
+ lastSeenAt,
46281
+ });
46282
+ const cacheData = (_a = pullFromCache([
46283
+ 'notificationTraySeen',
46284
+ 'get',
46285
+ ])) === null || _a === void 0 ? void 0 : _a.data;
46286
+ const data = {
46287
+ userId: client.userId,
46288
+ lastTraySeenAt: payload.lastSeenAt,
46289
+ };
46290
+ const updateCacheData = Object.assign(Object.assign({}, cacheData), data);
46291
+ const cachedAt = client.cache && Date.now();
46292
+ if (client.cache)
46293
+ pushToCache(['notificationTraySeen', 'get', client.userId], updateCacheData, { cachedAt });
46294
+ fireEvent('local.notificationTraySeen.updated', data);
46295
+ return {
46296
+ data: payload,
46297
+ cachedAt,
46298
+ };
46299
+ };
46300
+ /* end_public_function */
46301
+
46302
+ var index$3 = /*#__PURE__*/Object.freeze({
46303
+ __proto__: null,
46304
+ getNotificationTraySeen: getNotificationTraySeen,
46305
+ getNotificationTrayItems: getNotificationTrayItems,
46306
+ markItemsSeen: markItemsSeen,
46307
+ markTraySeen: markTraySeen,
46308
+ onNotificationTraySeenUpdated: onNotificationTraySeenUpdated
46309
+ });
46310
+
46311
+ class MyInvitationsPaginationController extends PaginationController {
46312
+ async getRequest(queryParams, token) {
46313
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
46314
+ const options = token ? { token } : { limit };
46315
+ const { data } = await this.http.get('/api/v1/invitations/me', { params: Object.assign(Object.assign({}, params), { options }) });
46316
+ await getCommunities$1(data.invitations.map(invitation => invitation.communityId));
46317
+ return data;
46318
+ }
46319
+ }
46320
+
46321
+ class MyInvitationsQueryStreamController extends QueryStreamController {
46322
+ constructor(query, cacheKey, notifyChange, preparePayload) {
46131
46323
  super(query, cacheKey);
46132
46324
  this.notifyChange = notifyChange;
46133
- this.paginationController = paginationController;
46134
- // Fix ESLint, "Expected 'this' to be used by class method"
46135
46325
  this.preparePayload = preparePayload;
46136
46326
  }
46137
- saveToMainDB(response) {
46327
+ async saveToMainDB(response) {
46328
+ const processedPayload = await this.preparePayload(response);
46138
46329
  const client = getActiveClient();
46139
46330
  const cachedAt = client.cache && Date.now();
46140
- // Fix Eslint error for "Expected 'this' to be used by class method"
46141
- const data = this.preparePayload(response);
46142
46331
  if (client.cache) {
46143
- ingestInCache(data, { cachedAt });
46332
+ ingestInCache(processedPayload, { cachedAt });
46144
46333
  }
46145
46334
  }
46146
46335
  appendToQueryStream(response, direction, refresh = false) {
46336
+ var _a, _b;
46147
46337
  if (refresh) {
46148
46338
  pushToCache(this.cacheKey, {
46149
- data: response.storyTargets.map(({ targetId }) => targetId),
46339
+ data: response.invitations.map(getResolver('invitation')),
46150
46340
  });
46151
46341
  }
46152
46342
  else {
46153
- updateLocalList(this.cacheKey, response.storyTargets.map(({ targetId }) => targetId));
46343
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
46344
+ const invitations = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
46345
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
46346
+ ...new Set([...invitations, ...response.invitations.map(getResolver('invitation'))]),
46347
+ ] }));
46154
46348
  }
46155
46349
  }
46156
- reactor(actionType) {
46157
- return (payload) => {
46158
- if (actionType === "onCreate" /* Amity.StoryActionType.OnCreate */ &&
46159
- this.query.seenState !== "seen" /* Amity.StorySeenQuery.SEEN */) {
46160
- updateLocalList(this.cacheKey, payload.map(({ targetId }) => targetId));
46350
+ reactor(action) {
46351
+ return (invitations) => {
46352
+ var _a;
46353
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
46354
+ if (!collection)
46355
+ return;
46356
+ if (action === InvitationActionsEnum.OnLocalInvitationUpdated) {
46357
+ const isExist = collection.data.find(id => id === invitations[0].invitationId);
46358
+ if (!isExist)
46359
+ return;
46360
+ }
46361
+ if (action === InvitationActionsEnum.OnLocalInvitationCreated) {
46362
+ const client = getActiveClient();
46363
+ const myInvitations = invitations.filter(invitation => invitation.invitedUserId === client.userId);
46364
+ collection.data = [
46365
+ ...new Set([
46366
+ ...myInvitations.map(invitation => invitation.invitationId),
46367
+ ...collection.data,
46368
+ ]),
46369
+ ];
46370
+ }
46371
+ if (action === InvitationActionsEnum.OnLocalInvitationDeleted) {
46372
+ collection.data = collection.data.filter(id => id !== invitations[0].invitationId);
46161
46373
  }
46374
+ pushToCache(this.cacheKey, collection);
46162
46375
  this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
46163
46376
  };
46164
46377
  }
@@ -46167,68 +46380,14 @@ class GlobalStoryQueryStreamController extends QueryStreamController {
46167
46380
  }
46168
46381
  }
46169
46382
 
46170
- const mergeResult = (resultA, resultB) => {
46171
- return {
46172
- categories: resultA.categories.concat(resultB.categories),
46173
- communities: resultA.communities.concat(resultB.communities),
46174
- communityUsers: resultA.communityUsers.concat(resultB.communityUsers),
46175
- files: resultA.files.concat(resultB.files),
46176
- storyTargets: resultA.storyTargets.concat(resultB.storyTargets),
46177
- users: resultA.users.concat(resultB.users),
46178
- paging: resultB.paging,
46179
- };
46180
- };
46181
- const addFlagLocalFilter = (payload, filter) => {
46182
- return Object.assign(Object.assign({}, payload), { storyTargets: payload.storyTargets.map(item => (Object.assign(Object.assign({}, item), { localFilter: filter }))) || [] });
46183
- };
46184
- class GlobalStoryPageController extends PaginationController {
46185
- constructor() {
46186
- super(...arguments);
46187
- this.smartFilterState = "unseen" /* Amity.StorySeenQuery.UNSEEN */;
46188
- }
46189
- async getRequest(queryParams, token) {
46190
- var _a;
46191
- // Apply default values for parameters
46192
- const { limit = 10, seenState = "unseen" /* Amity.StorySeenQuery.UNSEEN */ } = queryParams;
46193
- const result = await this.createRequest({
46194
- seenState: seenState === "smart" /* Amity.StorySeenQuery.SMART */ ? this.smartFilterState : seenState,
46195
- limit,
46196
- token,
46197
- });
46198
- // Use Early return to reduce condition complexity
46199
- if ((_a = result.paging) === null || _a === void 0 ? void 0 : _a.next)
46200
- return result;
46201
- if (seenState !== "smart" /* Amity.StorySeenQuery.SMART */)
46202
- return result;
46203
- if (this.smartFilterState === "seen" /* Amity.StorySeenQuery.SEEN */)
46204
- return result;
46205
- this.smartFilterState = "seen" /* Amity.StorySeenQuery.SEEN */;
46206
- const additionalResult = await this.createRequest({
46207
- seenState: this.smartFilterState,
46208
- limit,
46209
- });
46210
- return mergeResult(result, additionalResult);
46211
- }
46212
- async createRequest(params) {
46213
- const { data: queryResponse } = await this.http.get('/api/v5/me/global-story-targets', {
46214
- params,
46215
- });
46216
- return addFlagLocalFilter(queryResponse, params.seenState);
46217
- }
46218
- }
46219
-
46220
- class GlobalStoryLiveCollectionController extends LiveCollectionController {
46383
+ class MyInvitationsLiveCollectionController extends LiveCollectionController {
46221
46384
  constructor(query, callback) {
46222
46385
  const queryStreamId = hash(query);
46223
- const cacheKey = ["story-global-feed" /* STORY_KEY_CACHE.STORY_GLOBAL_FEED */, 'collection', queryStreamId];
46224
- const paginationController = new GlobalStoryPageController(query);
46386
+ const cacheKey = ['invitation', 'collection', queryStreamId];
46387
+ const paginationController = new MyInvitationsPaginationController(query);
46225
46388
  super(paginationController, queryStreamId, cacheKey, callback);
46226
46389
  this.query = query;
46227
- this.queryStreamController = new GlobalStoryQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), paginationController, (data) => {
46228
- const _a = prepareCommunityPayload(Object.assign(Object.assign({}, data), { feeds: [] })), rest = __rest(_a, ["feeds"]);
46229
- return Object.assign(Object.assign({}, data), rest);
46230
- });
46231
- this.paginationController = paginationController;
46390
+ this.queryStreamController = new MyInvitationsQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareMyInvitationsPayload);
46232
46391
  this.callback = callback.bind(this);
46233
46392
  this.loadPage({ initial: true });
46234
46393
  }
@@ -46238,388 +46397,694 @@ class GlobalStoryLiveCollectionController extends LiveCollectionController {
46238
46397
  if (!collection) {
46239
46398
  pushToCache(this.cacheKey, {
46240
46399
  data: [],
46241
- params: {},
46400
+ params: this.query,
46242
46401
  });
46243
46402
  }
46244
46403
  }
46245
- persistModel(response) {
46246
- this.queryStreamController.saveToMainDB(response);
46404
+ async persistModel(queryPayload) {
46405
+ await this.queryStreamController.saveToMainDB(queryPayload);
46247
46406
  }
46248
46407
  persistQueryStream({ response, direction, refresh, }) {
46249
46408
  this.queryStreamController.appendToQueryStream(response, direction, refresh);
46250
46409
  }
46410
+ startSubscription() {
46411
+ return this.queryStreamController.subscribeRTE([
46412
+ {
46413
+ fn: onLocalInvitationCreated,
46414
+ action: InvitationActionsEnum.OnLocalInvitationCreated,
46415
+ },
46416
+ {
46417
+ fn: onLocalInvitationUpdated,
46418
+ action: InvitationActionsEnum.OnLocalInvitationUpdated,
46419
+ },
46420
+ {
46421
+ fn: onLocalInvitationDeleted,
46422
+ action: InvitationActionsEnum.OnLocalInvitationDeleted,
46423
+ },
46424
+ ]);
46425
+ }
46251
46426
  notifyChange({ origin, loading, error }) {
46252
- var _a;
46427
+ var _a, _b;
46253
46428
  const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
46254
46429
  if (!collection)
46255
46430
  return;
46256
- const targetIds = collection.data;
46257
- const cachedTargets = queryCache(["storyTarget" /* STORY_KEY_CACHE.STORY_TARGET */]);
46258
- if (cachedTargets && (cachedTargets === null || cachedTargets === void 0 ? void 0 : cachedTargets.length) > 0) {
46259
- cachedTargets === null || cachedTargets === void 0 ? void 0 : cachedTargets.forEach(({ key }) => {
46260
- if (!collection.data.includes(key[2]))
46261
- targetIds.push(key[2]);
46262
- });
46263
- }
46264
- let data = targetIds
46265
- .map(targetId => pullFromCache(["storyTarget" /* STORY_KEY_CACHE.STORY_TARGET */, 'get', targetId]))
46266
- .filter(Boolean)
46267
- .map(storyTarget => LinkedObject.storyTarget(storyTarget.data));
46431
+ const data = this.applyFilter((_b = collection.data
46432
+ .map(id => pullFromCache(['invitation', 'get', id]))
46433
+ .filter(isNonNullable)
46434
+ .map(({ data }) => invitationLinkedObject(data))) !== null && _b !== void 0 ? _b : []);
46268
46435
  if (!this.shouldNotify(data) && origin === 'event')
46269
46436
  return;
46270
- data = this.applyFilter(data)
46271
- // exclude story targets with invalid stories
46272
- .filter(({ localSortingDate }) => !!localSortingDate)
46273
- // Remove internal fields
46274
- .map((_a) => {
46275
- var rest = __rest(_a, ["localFilter", "localLastExpires", "localLastSeen", "localSortingDate"]);
46276
- return rest;
46277
- });
46278
46437
  this.callback({
46279
46438
  onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
46280
46439
  data,
46281
46440
  hasNextPage: !!this.paginationController.getNextToken(),
46282
46441
  loading,
46283
46442
  error,
46284
- });
46285
- }
46286
- applyFilter(data) {
46287
- if (this.query.seenState !== "smart" /* Amity.StorySeenQuery.SMART */) {
46288
- return data
46289
- .filter(({ hasUnseen }) => {
46290
- if (this.query.seenState === "all" /* Amity.StorySeenQuery.ALL */)
46291
- return true;
46292
- if (this.query.seenState === "seen" /* Amity.StorySeenQuery.SEEN */ && !hasUnseen)
46293
- return true;
46294
- return this.query.seenState === "unseen" /* Amity.StorySeenQuery.UNSEEN */ && hasUnseen;
46295
- })
46296
- .sort(sortByLocalSortingDate);
46443
+ });
46444
+ }
46445
+ applyFilter(data) {
46446
+ let invitations = data;
46447
+ if (this.query.targetId) {
46448
+ invitations = invitations.filter(invitation => invitation.targetId === this.query.targetId);
46297
46449
  }
46298
- // Smart Filter - Apply local sorting on each list of data
46299
- const result = data.reduce((acc, storyTarget) => {
46300
- if (storyTarget.localFilter === "unseen" /* Amity.StorySeenQuery.UNSEEN */) {
46301
- acc.unseen.push(storyTarget);
46302
- }
46303
- else if (storyTarget.localFilter === "seen" /* Amity.StorySeenQuery.SEEN */) {
46304
- acc.seen.push(storyTarget);
46305
- }
46306
- else {
46307
- acc.unknown.push(storyTarget);
46450
+ if (this.query.statuses) {
46451
+ invitations = invitations.filter(invitation => { var _a; return (_a = this.query.statuses) === null || _a === void 0 ? void 0 : _a.includes(invitation.status); });
46452
+ }
46453
+ if (this.query.targetType) {
46454
+ invitations = invitations.filter(invitation => invitation.targetType === this.query.targetType);
46455
+ }
46456
+ if (this.query.type) {
46457
+ invitations = invitations.filter(invitation => invitation.type === this.query.type);
46458
+ }
46459
+ const sortFn = (() => {
46460
+ switch (this.query.sortBy) {
46461
+ case 'firstCreated':
46462
+ return sortByFirstCreated;
46463
+ case 'lastCreated':
46464
+ return sortByLastCreated;
46465
+ default:
46466
+ return sortByLastCreated;
46308
46467
  }
46309
- return acc;
46310
- }, { unseen: [], seen: [], unknown: [] });
46311
- const sortedUnknown = result.unknown.sort(sortByLocalSortingDate) || [];
46312
- const sortedUnseen = result.unseen.sort(sortByLocalSortingDate) || [];
46313
- const sortedSeen = result.seen.sort(sortByLocalSortingDate) || [];
46314
- // Merge all status and remove internal fields
46315
- return sortedUnknown.concat(sortedUnseen, sortedSeen);
46316
- }
46317
- startSubscription() {
46318
- return this.queryStreamController.subscribeRTE([
46319
- { fn: onStoryCreated, action: "onCreate" /* Amity.StoryActionType.OnCreate */ },
46320
- { fn: onStoryUpdated, action: "onUpdate" /* Amity.StoryActionType.OnUpdate */ },
46321
- { fn: onStoryDeleted, action: "onDelete" /* Amity.StoryActionType.OnDelete */ },
46322
- { fn: onStoryCreatedLocal, action: "onCreate" /* Amity.StoryActionType.OnCreate */ },
46323
- { fn: onStoryUpdatedLocal, action: "onUpdate" /* Amity.StoryActionType.OnUpdate */ },
46324
- { fn: onStoryDeletedLocal, action: "onDelete" /* Amity.StoryActionType.OnDelete */ },
46325
- { fn: onStoryError, action: "onError" /* Amity.StoryActionType.OnError */ },
46326
- ]);
46468
+ })();
46469
+ invitations = invitations.sort(sortFn);
46470
+ return invitations;
46327
46471
  }
46328
46472
  }
46329
46473
 
46330
- const getGlobalStoryTargets = (params, callback, config) => {
46331
- const { log, cache, userId } = getActiveClient();
46474
+ /**
46475
+ * Get my community invitations
46476
+ *
46477
+ * @param params the query parameters
46478
+ * @param callback the callback to be called when the invitations are fetched
46479
+ * @returns invitations
46480
+ *
46481
+ * @category My Community Invitations Live Collection
46482
+ *
46483
+ */
46484
+ const getMyCommunityInvitations = (params, callback, config) => {
46485
+ const { log, cache } = getActiveClient();
46332
46486
  if (!cache) {
46333
46487
  console.log(ENABLE_CACHE_MESSAGE);
46334
46488
  }
46335
46489
  const timestamp = Date.now();
46336
- log(`getGlobalStoryTarget(tmpid: ${timestamp}) > listen`);
46337
- const storyLiveCollection = new GlobalStoryLiveCollectionController(params, callback);
46338
- const disposers = storyLiveCollection.startSubscription();
46339
- const cacheKey = storyLiveCollection.getCacheKey();
46490
+ log(`getMyCommunityInvitations: (tmpid: ${timestamp}) > listen`);
46491
+ const invitationsLiveCollection = new MyInvitationsLiveCollectionController(Object.assign(Object.assign({}, params), { targetType: 'community', statuses: ["pending" /* InvitationStatusEnum.Pending */] }), callback);
46492
+ const disposers = invitationsLiveCollection.startSubscription();
46493
+ const cacheKey = invitationsLiveCollection.getCacheKey();
46340
46494
  disposers.push(() => {
46341
46495
  dropFromCache(cacheKey);
46342
46496
  });
46343
46497
  return () => {
46344
- log(`getGlobalStoryTarget(tmpid: ${timestamp}) > dispose`);
46498
+ log(`getInvitations (tmpid: ${timestamp}) > dispose`);
46345
46499
  disposers.forEach(fn => fn());
46346
46500
  };
46347
46501
  };
46348
46502
 
46349
- var index$4 = /*#__PURE__*/Object.freeze({
46503
+ var index$2 = /*#__PURE__*/Object.freeze({
46350
46504
  __proto__: null,
46351
- createImageStory: createImageStory,
46352
- createVideoStory: createVideoStory,
46353
- hardDeleteStory: hardDeleteStory,
46354
- softDeleteStory: softDeleteStory,
46355
- getActiveStoriesByTarget: getActiveStoriesByTarget,
46356
- getStoryByStoryId: getStoryByStoryId,
46357
- getTargetById: getTargetById,
46358
- getTargetsByTargetIds: getTargetsByTargetIds,
46359
- getStoriesByTargetIds: getStoriesByTargetIds,
46360
- getGlobalStoryTargets: getGlobalStoryTargets
46505
+ onLocalInvitationCreated: onLocalInvitationCreated,
46506
+ onLocalInvitationUpdated: onLocalInvitationUpdated,
46507
+ onLocalInvitationDeleted: onLocalInvitationDeleted,
46508
+ getMyCommunityInvitations: getMyCommunityInvitations
46361
46509
  });
46362
46510
 
46363
- const convertToInternalAd = (ad) => {
46364
- return Object.assign(Object.assign({}, ad), { endAt: ad.endAt ? ad.endAt : null });
46511
+ // TODO: confirm id
46512
+ /* begin_public_function
46513
+ id: live_reaction.create
46514
+ */
46515
+ /**
46516
+ * ```js
46517
+ * import { LiveReactionRepository } from '@amityco/ts-sdk'
46518
+ * await LiveReactionRepository.createReaction({
46519
+ * referenceType: 'post',
46520
+ * referenceId: 'postId',
46521
+ * streamId: 'streamId',
46522
+ * reactionName: 'like',
46523
+ * })
46524
+ * ```
46525
+ *
46526
+ *
46527
+ * @param referenceId that is target post's ID linked with a livestream
46528
+ * @param referenceType should be 'post'
46529
+ * @param reactionName that is the reaction name
46530
+ * @param streamId stream id
46531
+ * @returns a success boolean if the reaction was added
46532
+ *
46533
+ * @category Live Reaction API
46534
+ * @async
46535
+ */
46536
+ const createReaction = async ({ referenceId, referenceType, reactionName, streamId, }) => {
46537
+ const client = getActiveClient();
46538
+ client.log('live_reaction/createReaction', {
46539
+ referenceId,
46540
+ referenceType,
46541
+ reactionName,
46542
+ });
46543
+ const reactionSynceEngine = ReactionSyncEngine.getInstance();
46544
+ const reaction = {
46545
+ reactionName,
46546
+ referencePublicId: referenceId,
46547
+ referenceType,
46548
+ streamId,
46549
+ occurredAt: new Date().toISOString(),
46550
+ };
46551
+ reactionSynceEngine.createLiveReaction(reaction);
46552
+ fireEvent('local.liveReaction.created', [Object.assign(Object.assign({}, reaction), { userId: client.userId, referenceId })]);
46553
+ return true;
46365
46554
  };
46366
- const convertToInternalAdvertiser = (advertiser) => {
46367
- return Object.assign({}, advertiser);
46555
+ /* end_public_function */
46556
+
46557
+ /**
46558
+ * ```js
46559
+ * import { onLiveReactionCreated } from '@amityco/ts-sdk'
46560
+ * const dispose = onLiveReactionCreated(reactions => {
46561
+ * // ...
46562
+ * })
46563
+ * ```
46564
+ *
46565
+ * Fired when a batch of {@link Amity.LiveReaction} has been created
46566
+ *
46567
+ * @param callback The function to call when the event was fired
46568
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
46569
+ *
46570
+ * @category Live Reaction Events
46571
+ */
46572
+ const onLiveReactionCreated = (callback) => {
46573
+ const client = getActiveClient();
46574
+ const filter = (rawPayload) => {
46575
+ if (rawPayload.reactions.length > 0) {
46576
+ // TODO: check with BE if user id is internal or pulbic id
46577
+ const filteredPayload = rawPayload.reactions.filter(({ userId }) => userId !== client.userId);
46578
+ callback(filteredPayload);
46579
+ }
46580
+ };
46581
+ return createEventSubscriber(client, 'live_reaction/onLiveReactionCreated', 'liveReaction.created', filter);
46368
46582
  };
46369
- const getNetworkAds = async () => {
46583
+
46584
+ /**
46585
+ * ```js
46586
+ * import { onLiveReactionCreatedLocal } from '@amityco/ts-sdk'
46587
+ * const dispose = onLiveReactionCreatedLocal(reactions => {
46588
+ * // ...
46589
+ * })
46590
+ * ```
46591
+ *
46592
+ * Fired when a batch of {@link Amity.LiveReaction} has been created
46593
+ *
46594
+ * @param callback The function to call when the event was fired
46595
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
46596
+ *
46597
+ * @category Live Reaction Events
46598
+ */
46599
+ const onLiveReactionCreatedLocal = (callback) => {
46370
46600
  const client = getActiveClient();
46371
- const { data } = await client.http.get('/api/v1/ads/me');
46372
- const internalAds = data.ads.map(convertToInternalAd);
46373
- const internalAdvertisers = data.advertisers.map(convertToInternalAdvertiser);
46374
- ingestInCache({
46375
- ads: internalAds,
46376
- advertisers: internalAdvertisers,
46377
- files: data.files,
46378
- });
46379
- pushToCache(['ad', 'setting'], data.settings);
46380
- return {
46381
- ads: internalAds.map(LinkedObject.ad),
46382
- settings: data.settings,
46601
+ return createEventSubscriber(client, 'live_reaction/onLiveReactionCreated', 'local.liveReaction.created', callback);
46602
+ };
46603
+
46604
+ /**
46605
+ *
46606
+ * ```js
46607
+ * import { getReactions } from '@amityco/ts-sdk';
46608
+ *
46609
+ * const unsubscribe = getReactions(response => {
46610
+ * reactions = response.data
46611
+ * });
46612
+ * ```
46613
+ *
46614
+ * Observe live reactions {@link_Amity.LiveReaction} that have been created in a post linked with a stream
46615
+ *
46616
+ * @param callback the function to call when new data are available
46617
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the events
46618
+ *
46619
+ * @category Live Reaction Observable
46620
+ */
46621
+ // TODO: confirm return type for this observable property
46622
+ const getReactions = (postId, callback) => {
46623
+ const { _id: userId } = getActiveUser();
46624
+ if (!userId)
46625
+ throw new ASCError('The _id has not been defined in ActiveUser', 800000 /* Amity.ClientError.UNKNOWN_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
46626
+ const { log } = getActiveClient();
46627
+ const timestamp = Date.now();
46628
+ log(`getReactions(tmpid: ${timestamp}) > listen`);
46629
+ const disposers = [];
46630
+ const dispatcher = (data) => {
46631
+ callback(data);
46632
+ };
46633
+ const realtimeRouter = (data) => {
46634
+ const relevantReactions = data.filter(({ referenceId }) => referenceId === postId);
46635
+ dispatcher(relevantReactions);
46636
+ };
46637
+ disposers.push(onLiveReactionCreated(realtimeRouter));
46638
+ disposers.push(onLiveReactionCreatedLocal(realtimeRouter));
46639
+ return () => {
46640
+ disposers.forEach(fn => fn());
46383
46641
  };
46384
46642
  };
46385
46643
 
46386
- var index$3 = /*#__PURE__*/Object.freeze({
46644
+ var index$1 = /*#__PURE__*/Object.freeze({
46387
46645
  __proto__: null,
46388
- getNetworkAds: getNetworkAds
46646
+ createReaction: createReaction,
46647
+ onLiveReactionCreated: onLiveReactionCreated,
46648
+ getReactions: getReactions
46389
46649
  });
46390
46650
 
46651
+ /* begin_public_function
46652
+ id: event.create
46653
+ */
46391
46654
  /**
46392
- * Retrieves accessToken info to use in Beta services
46655
+ * ```js
46656
+ * import { EventRepository } from '@amityco/ts-sdk'
46657
+ * const response = await EventRepository.createEvent(bundle)
46658
+ * ```
46393
46659
  *
46394
- * @param apiKey for the Http Client instance
46395
- * @param apiRegion endpoint to connect to
46396
- * @param params The token parameters
46397
- * @param params.userId The userId to use to issue a token
46398
- * @param params.displayName The user's displayName
46399
- * @param params.authToken The authentication token - necessary when network option is set to secure
46400
- * @return An accessToken info object for the given userId
46660
+ * Creates an {@link Amity.Event}
46401
46661
  *
46402
- * @category External API
46403
- * @hidden
46662
+ * @param bundle The data necessary to create a new {@link Amity.Event}
46663
+ * @returns The newly created {@link Amity.Event}
46664
+ *
46665
+ * @category Event API
46666
+ * @async
46404
46667
  */
46405
- const createUserToken = async (apiKey, apiRegion, params) => {
46406
- const deviceId = await getDeviceId();
46407
- const deviceInfo = getDeviceInfo();
46408
- const http = createHttpTransport(computeUrl('http', apiRegion));
46409
- const { data } = await http.post('/api/v5/sessions', Object.assign(Object.assign({}, params), { deviceId, deviceInfo: Object.assign(Object.assign({}, deviceInfo), { model: 'token management API on TS-SDK' }) }), { headers: { 'X-API-Key': apiKey } });
46410
- return { accessToken: data.accessToken };
46668
+ const createEvent = async (bundle) => {
46669
+ const client = getActiveClient();
46670
+ client.log('event/createEvent', bundle);
46671
+ const { data: payload } = await client.http.post('/api/v1/events', bundle);
46672
+ fireEvent('local.event.created', payload);
46673
+ const preparedPayload = prepareEventPayload(payload);
46674
+ const cachedAt = client.cache && Date.now();
46675
+ if (client.cache)
46676
+ ingestInCache(preparedPayload, { cachedAt });
46677
+ return {
46678
+ data: eventLinkedObject(preparedPayload.events[0]),
46679
+ cachedAt,
46680
+ };
46411
46681
  };
46682
+ /* end_public_function */
46412
46683
 
46413
46684
  /* begin_public_function
46414
- id: notificationTray.getNotificationTraySeen
46685
+ id: event.update
46415
46686
  */
46416
46687
  /**
46417
46688
  * ```js
46418
- * import { notificationTray } from '@amityco/ts-sdk'
46419
- * const notificationTraySeen = await notificationTray.getNotificationTraySeen()
46689
+ * import { EventRepository } from '@amityco/ts-sdk'
46690
+ * const response = await EventRepository.updateEvent(eventId, bundle)
46420
46691
  * ```
46421
46692
  *
46693
+ * Updates an {@link Amity.Event}
46422
46694
  *
46423
- * @returns A page of {@link Amity.NotificationTraySeen} objects
46695
+ * @param eventId The ID of the {@link Amity.Event} to edit
46696
+ * @param bundle The data necessary to update an existing {@link Amity.Event}
46697
+ * @returns the updated {@link Amity.Event}
46424
46698
  *
46425
- * @category NotificationTray API
46699
+ * @category Event API
46426
46700
  * @async
46427
- * */
46428
- const getNotificationTraySeen$1 = async () => {
46701
+ */
46702
+ const updateEvent = async (eventId, bundle) => {
46429
46703
  const client = getActiveClient();
46430
- client.log('notificationTray/getNotificationTraySeen', {});
46431
- const { data: payload } = await client.http.get(`api/v1/notification-tray/tray/seen`);
46704
+ client.log('event/updateEvent', eventId, bundle);
46705
+ const { data: payload } = await client.http.put(`/api/v1/events/${eventId}`, bundle);
46706
+ fireEvent('local.event.updated', payload);
46707
+ const preparedPayload = prepareEventPayload(payload);
46432
46708
  const cachedAt = client.cache && Date.now();
46433
- if (client.cache) {
46434
- const cacheKey = ['notificationTraySeen', 'get', client.userId];
46435
- pushToCache(cacheKey, {
46436
- userId: client.userId,
46437
- lastTraySeenAt: payload.lastTraySeenAt,
46438
- lastTrayOccuredAt: payload.lastTrayOccurredAt,
46439
- });
46440
- }
46709
+ if (client.cache)
46710
+ ingestInCache(preparedPayload, { cachedAt });
46441
46711
  return {
46442
- data: {
46443
- userId: client.userId,
46444
- lastTraySeenAt: payload.lastTraySeenAt,
46445
- lastTrayOccurredAt: payload.lastTrayOccurredAt,
46446
- isSeen: payload.lastTraySeenAt > payload.lastTrayOccurredAt,
46447
- },
46712
+ data: eventLinkedObject(preparedPayload.events.find(event => event.eventId === eventId)),
46448
46713
  cachedAt,
46449
46714
  };
46450
46715
  };
46451
46716
  /* end_public_function */
46717
+
46718
+ /* begin_public_function
46719
+ id: event.get
46720
+ */
46452
46721
  /**
46453
46722
  * ```js
46454
- * import { notificationTray } from '@amityco/ts-sdk'
46455
- * const notificationTraySeen = await notificationTray.getNotificationTraySeen.locally()
46723
+ * import { EventRepository } from '@amityco/ts-sdk'
46724
+ * const event = await EventRepository.getEvent(eventId)
46456
46725
  * ```
46457
46726
  *
46458
- * Queries a paginable list of {@link Amity.NotificationTraySeen} objects from cache
46727
+ * Fetches a {@link Amity.Event} object
46459
46728
  *
46460
- * @returns A page of {@link Amity.NotificationTraySeen} objects
46729
+ * @param eventId the ID of the {@link Amity.Event} to fetch
46730
+ * @returns the associated {@link Amity.Event} object
46461
46731
  *
46462
- * @category NotificationTray API
46732
+ * @category Event API
46463
46733
  * @async
46464
- * */
46465
- getNotificationTraySeen$1.locally = () => {
46466
- var _a;
46734
+ */
46735
+ const getEvent$1 = async (eventId) => {
46467
46736
  const client = getActiveClient();
46468
- client.log('notificationTray/getNotificationTraySeen.locally', {});
46737
+ client.log('event/getEvent', eventId);
46738
+ const { data: payload } = await client.http.get(`/api/v1/events/${eventId}`);
46739
+ const data = prepareEventPayload(payload);
46740
+ const cachedAt = client.cache && Date.now();
46741
+ if (client.cache)
46742
+ ingestInCache(data, { cachedAt });
46743
+ return {
46744
+ data: data.events.find(event => event.eventId === eventId),
46745
+ cachedAt,
46746
+ };
46747
+ };
46748
+ /* end_public_function */
46749
+ /**
46750
+ * ```js
46751
+ * import { EventRepository } from '@amityco/ts-sdk'
46752
+ * const event = EventRepository.getEvent.locally(eventId)
46753
+ * ```
46754
+ *
46755
+ * Fetches a {@link Amity.Event} object in cache
46756
+ *
46757
+ * @param eventId the ID of the {@link Amity.Event} to fetch
46758
+ * @returns the associated {@link Amity.Event} object
46759
+ *
46760
+ * @category Event API
46761
+ */
46762
+ getEvent$1.locally = (eventId) => {
46763
+ const client = getActiveClient();
46764
+ client.log('event/getEvent.locally', eventId);
46469
46765
  if (!client.cache)
46470
46766
  return;
46471
- const queryKey = ['notificationTraySeen', 'get'];
46472
- const { data, cachedAt } = (_a = pullFromCache(queryKey)) !== null && _a !== void 0 ? _a : {};
46473
- if (!data)
46767
+ const cache = pullFromCache(['event', 'get', eventId]);
46768
+ if (!cache)
46474
46769
  return;
46475
- return { data, cachedAt };
46770
+ return {
46771
+ data: cache.data,
46772
+ cachedAt: cache.cachedAt,
46773
+ };
46476
46774
  };
46477
46775
 
46776
+ /* begin_public_function
46777
+ id: event.delete
46778
+ */
46478
46779
  /**
46479
46780
  * ```js
46480
- * import { onNotificationTraySeenUpdated } from '@amityco/ts-sdk'
46481
- * const dispose = onNotificationTraySeenUpdated(data => {
46781
+ * import { EventRepository } from '@amityco/ts-sdk'
46782
+ * const { success } = await EventRepository.deleteEvent(eventId)
46783
+ * ```
46784
+ *
46785
+ * Deletes a {@link Amity.Event}
46786
+ *
46787
+ * @param eventId The {@link Amity.Event} ID to delete
46788
+ *
46789
+ * @category Event API
46790
+ * @async
46791
+ */
46792
+ const deleteEvent = async (eventId) => {
46793
+ const client = getActiveClient();
46794
+ client.log('event/deleteEvent', eventId);
46795
+ const event = await getEvent$1(eventId);
46796
+ await client.http.delete(`/api/v1/events/${eventId}`);
46797
+ const deletedEvent = Object.assign(Object.assign({}, event.data), { isDeleted: true });
46798
+ upsertInCache(['event', 'get', eventId], deletedEvent);
46799
+ fireEvent('local.event.deleted', {
46800
+ users: [],
46801
+ files: [],
46802
+ communities: [],
46803
+ videoStreamings: [],
46804
+ events: [deletedEvent],
46805
+ discussionCommunities: [],
46806
+ });
46807
+ };
46808
+ /* end_public_function */
46809
+
46810
+ /**
46811
+ * ```js
46812
+ * import { EventRepository } from '@amityco/ts-sdk'
46813
+ * const dispose = EventRepository.onEventCreated(event => {
46482
46814
  * // ...
46483
46815
  * })
46484
46816
  * ```
46485
46817
  *
46486
- * Fired when an {@link Amity.NotificationTraySeen} has been updated
46818
+ * Fired when a {@link Amity.Event} has been created
46487
46819
  *
46488
46820
  * @param callback The function to call when the event was fired
46489
46821
  * @returns an {@link Amity.Unsubscriber} function to stop listening
46490
46822
  *
46491
- * @category NotificationTraySeen Events
46823
+ * @category Event Events
46492
46824
  */
46493
- const onNotificationTraySeenUpdated = (callback) => {
46494
- const client = getActiveClient();
46495
- const disposers = [
46496
- createEventSubscriber(client, 'onNotificationTraySeenUpdated', 'local.notificationTraySeen.updated', payload => callback(payload)),
46497
- ];
46498
- return () => {
46499
- disposers.forEach(fn => fn());
46500
- };
46501
- };
46825
+ const onEventCreated = (callback) => createEventEventSubscriber('event.created', callback);
46826
+
46827
+ /**
46828
+ * ```js
46829
+ * import { EventRepository } from '@amityco/ts-sdk'
46830
+ * const dispose = EventRepository.onEventUpdated(event => {
46831
+ * // ...
46832
+ * })
46833
+ * ```
46834
+ *
46835
+ * Fired when a {@link Amity.Event} has been updated
46836
+ *
46837
+ * @param callback The function to call when the event was fired
46838
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
46839
+ *
46840
+ * @category Event Events
46841
+ */
46842
+ const onEventUpdated = (callback) => createEventEventSubscriber('event.updated', callback);
46843
+
46844
+ /**
46845
+ * ```js
46846
+ * import { EventRepository } from '@amityco/ts-sdk'
46847
+ * const dispose = EventRepository.onEventDeleted(event => {
46848
+ * // ...
46849
+ * })
46850
+ * ```
46851
+ *
46852
+ * Fired when a {@link Amity.Event} has been deleted
46853
+ *
46854
+ * @param callback The function to call when the event was fired
46855
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
46856
+ *
46857
+ * @category Event Events
46858
+ */
46859
+ const onEventDeleted = (callback) => createEventEventSubscriber('event.deleted', callback);
46860
+
46861
+ /**
46862
+ * ```js
46863
+ * import { EventRepository } from '@amityco/ts-sdk'
46864
+ * const dispose = EventRepository.onLocalEventCreated(event => {
46865
+ * // ...
46866
+ * })
46867
+ * ```
46868
+ *
46869
+ * Fired when a {@link Amity.Event} has been created
46870
+ *
46871
+ * @param callback The function to call when the event was fired
46872
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
46873
+ *
46874
+ * @category Event Events
46875
+ */
46876
+ const onLocalEventCreated = (callback) => createEventEventSubscriber('local.event.created', callback);
46877
+
46878
+ /**
46879
+ * ```js
46880
+ * import { EventRepository } from '@amityco/ts-sdk'
46881
+ * const dispose = EventRepository.onLocalEventUpdated(event => {
46882
+ * // ...
46883
+ * })
46884
+ * ```
46885
+ *
46886
+ * Fired when a {@link Amity.Event} has been updated
46887
+ *
46888
+ * @param callback The function to call when the event was fired
46889
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
46890
+ *
46891
+ * @category Event Events
46892
+ */
46893
+ const onLocalEventUpdated = (callback) => createEventEventSubscriber('local.event.updated', callback);
46894
+
46895
+ /**
46896
+ * ```js
46897
+ * import { EventRepository } from '@amityco/ts-sdk'
46898
+ * const dispose = EventRepository.onLocalEventDeleted(event => {
46899
+ * // ...
46900
+ * })
46901
+ * ```
46902
+ *
46903
+ * Fired when a {@link Amity.Event} has been deleted
46904
+ *
46905
+ * @param callback The function to call when the event was fired
46906
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
46907
+ *
46908
+ * @category Event Events
46909
+ */
46910
+ const onLocalEventDeleted = (callback) => createEventEventSubscriber('local.event.deleted', callback);
46911
+
46912
+ /**
46913
+ * ```js
46914
+ * import { EventRepository } from '@amityco/ts-sdk'
46915
+ * const dispose = EventRepository.onRSVPCreated(event => {
46916
+ * // ...
46917
+ * })
46918
+ * ```
46919
+ *
46920
+ * Fired when a {@link Amity.Event} has been created
46921
+ *
46922
+ * @param callback The function to call when the event was fired
46923
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
46924
+ *
46925
+ * @category Event Events
46926
+ */
46927
+ const onRSVPCreated = (callback) => createEventResponseSubscriber('event.rsvp.created', callback);
46928
+
46929
+ /**
46930
+ * ```js
46931
+ * import { EventRepository } from '@amityco/ts-sdk'
46932
+ * const dispose = EventRepository.onRSVPUpdated(event => {
46933
+ * // ...
46934
+ * })
46935
+ * ```
46936
+ *
46937
+ * Fired when a {@link Amity.InternalEventResponse} has been updated
46938
+ *
46939
+ * @param callback The function to call when the event was fired
46940
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
46941
+ *
46942
+ * @category Event Events
46943
+ */
46944
+ const onRSVPUpdated = (callback) => createEventResponseSubscriber('event.rsvp.updated', callback);
46945
+
46946
+ /**
46947
+ * ```js
46948
+ * import { EventRepository } from '@amityco/ts-sdk'
46949
+ * const dispose = EventRepository.onLocalRSVPCreated(event => {
46950
+ * // ...
46951
+ * })
46952
+ * ```
46953
+ *
46954
+ * Fired when a {@link Amity.Event} has been created
46955
+ *
46956
+ * @param callback The function to call when the event was fired
46957
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
46958
+ *
46959
+ * @category Event Events
46960
+ */
46961
+ const onLocalRSVPCreated = (callback) => createEventResponseSubscriber('local.rsvp.created', callback);
46962
+
46963
+ /**
46964
+ * ```js
46965
+ * import { EventRepository } from '@amityco/ts-sdk'
46966
+ * const dispose = EventRepository.onLocalEventUpdated(event => {
46967
+ * // ...
46968
+ * })
46969
+ * ```
46970
+ *
46971
+ * Fired when a {@link Amity.Event} has been updated
46972
+ *
46973
+ * @param callback The function to call when the event was fired
46974
+ * @returns an {@link Amity.Unsubscriber} function to stop listening
46975
+ *
46976
+ * @category Event Events
46977
+ */
46978
+ const onLocalRSVPUpdated = (callback) => createEventResponseSubscriber('local.rsvp.updated', callback);
46502
46979
 
46503
46980
  /* begin_public_function
46504
- id: notificationTray.getNotificationTraySeen
46981
+ id: event.get
46505
46982
  */
46506
46983
  /**
46507
46984
  * ```js
46508
- * import { notificationTray } from '@amityco/ts-sdk';
46985
+ * import { EventRepository } from '@amityco/ts-sdk';
46509
46986
  *
46510
- * let notificationTraySeen;
46987
+ * let event;
46511
46988
  *
46512
- * const unsubscribe = getNotificationTraySeen(response => {
46513
- * notificationTraySeen = response.data;
46989
+ * const unsubscribe = EventRepository.getEvent(eventId, response => {
46990
+ * event = response.data;
46514
46991
  * });
46515
46992
  * ```
46516
46993
  *
46517
- * Observe all mutation on a given {@link Amity.NotificationTraySeen}
46994
+ * Observe all mutation on a given {@link Amity.Event}
46518
46995
  *
46519
- * @param callback the function to call when new data are available
46520
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the message
46996
+ * @param eventId the ID of the event to observe
46997
+ * @param callback the function to call when new snapshot of event are available
46998
+ * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the event
46521
46999
  *
46522
- * @category NotificationTraySeen Live Object
47000
+ * @category Event Live Object
46523
47001
  */
46524
- const getNotificationTraySeen = (callback) => {
46525
- const { userId } = getActiveUser();
46526
- return liveObject(userId, callback, 'userId', getNotificationTraySeen$1, [onNotificationTraySeenUpdated], {
46527
- callbackDataSelector: (data) => {
46528
- let isSeen = true;
46529
- if (data === null || data === void 0 ? void 0 : data.lastTrayOccurredAt) {
46530
- if (!data.lastTraySeenAt) {
46531
- isSeen = false;
46532
- }
46533
- else {
46534
- isSeen =
46535
- convertDateStringToTimestamp(data.lastTraySeenAt) >
46536
- convertDateStringToTimestamp(data.lastTrayOccurredAt);
46537
- }
46538
- }
46539
- return {
46540
- lastTrayOccurredAt: data === null || data === void 0 ? void 0 : data.lastTrayOccurredAt,
46541
- lastTraySeenAt: data === null || data === void 0 ? void 0 : data.lastTraySeenAt,
46542
- isSeen,
46543
- };
46544
- },
47002
+ const getEvent = (eventId, callback) => {
47003
+ return liveObject(eventId, callback, 'eventId', getEvent$1, [onEventUpdated, onEventDeleted, onLocalEventUpdated, onLocalEventDeleted], {
47004
+ callbackDataSelector: (data) => (data ? eventLinkedObject(data) : data),
46545
47005
  });
46546
47006
  };
46547
47007
  /* end_public_function */
46548
-
46549
- /**
46550
- * TODO: handle cache receive cache option, and cache policy
46551
- * TODO: check if querybyIds is supported
46552
- */
46553
- class NotificationTrayItemsPaginationController extends PaginationController {
47008
+
47009
+ var EventActionsEnum;
47010
+ (function (EventActionsEnum) {
47011
+ EventActionsEnum["OnEventCreated"] = "onEventCreated";
47012
+ EventActionsEnum["OnEventUpdated"] = "onEventUpdated";
47013
+ EventActionsEnum["OnEventDeleted"] = "onEventDeleted";
47014
+ EventActionsEnum["OnRSVPCreated"] = "onRSVPCreated";
47015
+ EventActionsEnum["OnRSVPUpdated"] = "onRSVPUpdated";
47016
+ })(EventActionsEnum || (EventActionsEnum = {}));
47017
+
47018
+ class EventPaginationController extends PaginationController {
46554
47019
  async getRequest(queryParams, token) {
46555
47020
  const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
46556
47021
  const options = token ? { token } : { limit };
46557
- const { data: queryResponse } = await this.http.get(`/api/v1/notification-tray`, {
46558
- params: Object.assign(Object.assign({}, params), { options }),
46559
- });
46560
- return queryResponse;
47022
+ const { data: response } = await this.http.get(`/api/v1/events`, { params: Object.assign(Object.assign({}, params), { options }) });
47023
+ return response;
46561
47024
  }
46562
47025
  }
46563
47026
 
46564
- class NotificationTrayItemsQuerystreamController extends QueryStreamController {
47027
+ class EventQueryStreamController extends QueryStreamController {
46565
47028
  constructor(query, cacheKey, notifyChange, preparePayload) {
46566
47029
  super(query, cacheKey);
46567
47030
  this.notifyChange = notifyChange;
46568
47031
  this.preparePayload = preparePayload;
46569
47032
  }
46570
47033
  async saveToMainDB(response) {
46571
- const processedPayload = await this.preparePayload(response);
47034
+ const processedPayload = this.preparePayload(response);
46572
47035
  const client = getActiveClient();
46573
47036
  const cachedAt = client.cache && Date.now();
46574
- if (client.cache) {
47037
+ if (client.cache)
46575
47038
  ingestInCache(processedPayload, { cachedAt });
46576
- }
46577
47039
  }
46578
47040
  appendToQueryStream(response, direction, refresh = false) {
46579
47041
  var _a, _b;
46580
47042
  if (refresh) {
46581
- pushToCache(this.cacheKey, {
46582
- data: response.notificationTrayItems.map(getResolver('notificationTrayItem')),
46583
- });
47043
+ pushToCache(this.cacheKey, { data: response.events.map(getResolver('event')) });
46584
47044
  }
46585
47045
  else {
46586
47046
  const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
46587
- const notifications = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
46588
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
46589
- ...new Set([
46590
- ...notifications,
46591
- ...response.notificationTrayItems.map(getResolver('notificationTrayItem')),
46592
- ]),
46593
- ] }));
47047
+ const events = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
47048
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...events, ...response.events.map(getResolver('event'))])] }));
46594
47049
  }
46595
47050
  }
47051
+ reactor(action) {
47052
+ return (event) => {
47053
+ var _a;
47054
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
47055
+ if (!collection)
47056
+ return;
47057
+ if (action === EventActionsEnum.OnEventCreated) {
47058
+ collection.data = [...new Set([event.eventId, ...collection.data])];
47059
+ }
47060
+ if (action === EventActionsEnum.OnEventDeleted) {
47061
+ collection.data = collection.data.filter(eventId => eventId !== event.eventId);
47062
+ }
47063
+ pushToCache(this.cacheKey, collection);
47064
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
47065
+ };
47066
+ }
47067
+ subscribeRTE(createSubscriber) {
47068
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
47069
+ }
46596
47070
  }
46597
47071
 
46598
- const prepareNotificationTrayItemsPayload = (rawPayload) => {
46599
- const users = rawPayload.users.map(convertRawUserToInternalUser);
46600
- return Object.assign(Object.assign({}, rawPayload), { users });
46601
- };
46602
-
46603
- class NotificationTrayItemsLiveCollectionController extends LiveCollectionController {
47072
+ class EventLiveCollectionController extends LiveCollectionController {
46604
47073
  constructor(query, callback) {
46605
47074
  const queryStreamId = hash(query);
46606
- const cacheKey = ['notificationTrayItem', 'collection', queryStreamId];
46607
- const paginationController = new NotificationTrayItemsPaginationController(query);
47075
+ const cacheKey = ['event', 'collection', queryStreamId];
47076
+ const paginationController = new EventPaginationController(query);
46608
47077
  super(paginationController, queryStreamId, cacheKey, callback);
46609
47078
  this.query = query;
46610
- this.queryStreamController = new NotificationTrayItemsQuerystreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareNotificationTrayItemsPayload);
47079
+ this.queryStreamController = new EventQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareEventPayload);
46611
47080
  this.callback = callback.bind(this);
46612
47081
  this.loadPage({ initial: true });
46613
47082
  }
46614
47083
  setup() {
46615
47084
  var _a;
46616
47085
  const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
46617
- if (!collection) {
46618
- pushToCache(this.cacheKey, {
46619
- data: [],
46620
- params: {},
46621
- });
46622
- }
47086
+ if (!collection)
47087
+ pushToCache(this.cacheKey, { data: [], params: {} });
46623
47088
  }
46624
47089
  async persistModel(queryPayload) {
46625
47090
  await this.queryStreamController.saveToMainDB(queryPayload);
@@ -46627,9 +47092,15 @@ class NotificationTrayItemsLiveCollectionController extends LiveCollectionContro
46627
47092
  persistQueryStream({ response, direction, refresh, }) {
46628
47093
  this.queryStreamController.appendToQueryStream(response, direction, refresh);
46629
47094
  }
46630
- // eslint-disable-next-line class-methods-use-this
46631
47095
  startSubscription() {
46632
- return [];
47096
+ return this.queryStreamController.subscribeRTE([
47097
+ { fn: onEventCreated, action: EventActionsEnum.OnEventCreated },
47098
+ { fn: onEventUpdated, action: EventActionsEnum.OnEventUpdated },
47099
+ { fn: onEventDeleted, action: EventActionsEnum.OnEventDeleted },
47100
+ { fn: onLocalEventCreated, action: EventActionsEnum.OnEventCreated },
47101
+ { fn: onLocalEventUpdated, action: EventActionsEnum.OnEventUpdated },
47102
+ { fn: onLocalEventDeleted, action: EventActionsEnum.OnEventDeleted },
47103
+ ]);
46633
47104
  }
46634
47105
  notifyChange({ origin, loading, error }) {
46635
47106
  var _a, _b;
@@ -46637,214 +47108,94 @@ class NotificationTrayItemsLiveCollectionController extends LiveCollectionContro
46637
47108
  if (!collection)
46638
47109
  return;
46639
47110
  const data = ((_b = collection.data
46640
- .map(id => pullFromCache(['notificationTrayItem', 'get', id]))
47111
+ .map(eventId => pullFromCache(['event', 'get', eventId]))
46641
47112
  .filter(isNonNullable)
46642
- .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.notificationTray);
46643
- if (!this.shouldNotify(data) && origin === 'event')
47113
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.event);
47114
+ if (!this.shouldNotify(data) && origin === "event" /* Amity.LiveDataOrigin.EVENT */)
46644
47115
  return;
46645
47116
  this.callback({
46646
- onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
46647
47117
  data,
46648
- hasNextPage: !!this.paginationController.getNextToken(),
46649
- loading,
46650
47118
  error,
47119
+ loading,
47120
+ hasNextPage: !!this.paginationController.getNextToken(),
47121
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
46651
47122
  });
46652
47123
  }
46653
47124
  }
46654
47125
 
46655
47126
  /**
46656
- * Get notification tray items for a notification tray page
47127
+ * Get events
46657
47128
  *
46658
- * @param params the limit query parameters
46659
- * @param callback the callback to be called when the notification tray items are updated
46660
- * @returns items in the notification tray
47129
+ * @param params the query parameters
47130
+ * @param callback the callback to be called when the events are updated
47131
+ * @returns events
46661
47132
  *
46662
- * @category Notification tray items Live Collection
47133
+ * @category Event Live Collection
46663
47134
  *
46664
47135
  */
46665
- const getNotificationTrayItems = (params, callback, config) => {
47136
+ const getEvents = (params, callback, config) => {
46666
47137
  const { log, cache } = getActiveClient();
46667
- if (!cache) {
47138
+ if (!cache)
46668
47139
  console.log(ENABLE_CACHE_MESSAGE);
46669
- }
46670
47140
  const timestamp = Date.now();
46671
- log(`getNotificationTrayItems(tmpid: ${timestamp}) > listen`);
46672
- const notiTrayItemsLiveCollection = new NotificationTrayItemsLiveCollectionController(params, callback);
46673
- const disposers = notiTrayItemsLiveCollection.startSubscription();
46674
- const cacheKey = notiTrayItemsLiveCollection.getCacheKey();
47141
+ log(`getEvents: (tmpid: ${timestamp}) > listen`);
47142
+ const eventLiveCollection = new EventLiveCollectionController(params, callback);
47143
+ const disposers = eventLiveCollection.startSubscription();
47144
+ const cacheKey = eventLiveCollection.getCacheKey();
46675
47145
  disposers.push(() => dropFromCache(cacheKey));
46676
47146
  return () => {
46677
- log(`getNotificationTrayItems(tmpid: ${timestamp}) > dispose`);
47147
+ log(`getEvents (tmpid: ${timestamp}) > dispose`);
46678
47148
  disposers.forEach(fn => fn());
46679
47149
  };
46680
47150
  };
46681
47151
 
46682
- /* begin_public_function
46683
- id: notificationTrayItem.markSeen
46684
- */
46685
- /**
46686
- * ```js
46687
- * import { notificationTray } from '@amityco/ts-sdk'
46688
- * const updated = await notificationTray.markItemsSeen()
46689
- * ```
46690
- *
46691
- * Updates an {@link Amity.NotificationItemSeen}
46692
- *
46693
- * @param trayItems[] that include id and lastTraySeenAt, The ID of the {@link Amity.NotificationItemSeen} to edit
46694
- * @returns the updated {@link Amity.NotificationItemSeen} object
46695
- *
46696
- * @category NotificationItemSeen API
46697
- * @async
46698
- */
46699
- const markItemsSeen = async (trayItems) => {
46700
- const client = getActiveClient();
46701
- client.log('notificationTray/markItemsSeen', {});
46702
- const { data: payload } = await client.http.post(`api/v1/notification-tray/items/seen`, {
46703
- trayItems: trayItems.map(item => ({
46704
- id: item.id,
46705
- lastSeenAt: item.lastSeenAt,
46706
- })),
46707
- });
46708
- const updatedData = payload.trayItems
46709
- .map(patchItem => {
46710
- var _a;
46711
- const cacheData = (_a = pullFromCache([
46712
- 'notificationTrayItem',
46713
- 'get',
46714
- patchItem.id,
46715
- ])) === null || _a === void 0 ? void 0 : _a.data;
46716
- if (!cacheData)
46717
- return;
46718
- const data = Object.assign(Object.assign({}, cacheData), { lastSeenAt: patchItem.lastSeenAt });
46719
- if (client.cache) {
46720
- const cachedAt = Date.now();
46721
- pushToCache(['notificationTrayItem', 'get'], data, { cachedAt });
46722
- }
46723
- return data;
46724
- })
46725
- .filter(Boolean);
46726
- fireEvent('local.notificationTrayItem.updated', { notificationTrayItems: updatedData });
46727
- };
46728
- /* end_public_function */
46729
-
46730
- /* begin_public_function
46731
- id: notificationTray.markSeen
46732
- */
46733
- /**
46734
- * ```js
46735
- * import { notificationTray } from '@amityco/ts-sdk'
46736
- * const updated = await notificationTray.markTraySeen({
46737
- * lastSeenAt: Amity.timestamp,
46738
- * })
46739
- * ```
46740
- *
46741
- * Updates an {@link Amity.NotificationTraySeen}
46742
- *
46743
- * @param userId The ID of the {@link Amity.NotificationTraySeen} to edit
46744
- * @param lastSeenAt The patch data to apply
46745
- * @returns the updated {@link Amity.NotificationTraySeen} object
46746
- *
46747
- * @category Post API
46748
- * @async
46749
- */
46750
- const markTraySeen = async (lastSeenAt) => {
46751
- var _a;
46752
- const client = getActiveClient();
46753
- client.log('notificationTray/markTraySeen', {});
46754
- const { data: payload } = await client.http.post(`api/v1/notification-tray/tray/seen`, {
46755
- lastSeenAt,
46756
- });
46757
- const cacheData = (_a = pullFromCache([
46758
- 'notificationTraySeen',
46759
- 'get',
46760
- ])) === null || _a === void 0 ? void 0 : _a.data;
46761
- const data = {
46762
- userId: client.userId,
46763
- lastTraySeenAt: payload.lastSeenAt,
46764
- };
46765
- const updateCacheData = Object.assign(Object.assign({}, cacheData), data);
46766
- const cachedAt = client.cache && Date.now();
46767
- if (client.cache)
46768
- pushToCache(['notificationTraySeen', 'get', client.userId], updateCacheData, { cachedAt });
46769
- fireEvent('local.notificationTraySeen.updated', data);
46770
- return {
46771
- data: payload,
46772
- cachedAt,
46773
- };
46774
- };
46775
- /* end_public_function */
46776
-
46777
- var index$2 = /*#__PURE__*/Object.freeze({
46778
- __proto__: null,
46779
- getNotificationTraySeen: getNotificationTraySeen,
46780
- getNotificationTrayItems: getNotificationTrayItems,
46781
- markItemsSeen: markItemsSeen,
46782
- markTraySeen: markTraySeen,
46783
- onNotificationTraySeenUpdated: onNotificationTraySeenUpdated
46784
- });
46785
-
46786
- class MyInvitationsPaginationController extends PaginationController {
47152
+ class MyEventPaginationController extends PaginationController {
46787
47153
  async getRequest(queryParams, token) {
46788
47154
  const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT } = queryParams, params = __rest(queryParams, ["limit"]);
46789
47155
  const options = token ? { token } : { limit };
46790
- const { data } = await this.http.get('/api/v1/invitations/me', { params: Object.assign(Object.assign({}, params), { options }) });
46791
- await getCommunities$1(data.invitations.map(invitation => invitation.communityId));
46792
- return data;
47156
+ const { data: response } = await this.http.get(`/api/v1/events/me/rsvps`, { params: Object.assign(Object.assign({}, params), { options }) });
47157
+ return response;
46793
47158
  }
46794
47159
  }
46795
47160
 
46796
- class MyInvitationsQueryStreamController extends QueryStreamController {
47161
+ class MyEventQueryStreamController extends QueryStreamController {
46797
47162
  constructor(query, cacheKey, notifyChange, preparePayload) {
46798
47163
  super(query, cacheKey);
46799
47164
  this.notifyChange = notifyChange;
46800
47165
  this.preparePayload = preparePayload;
46801
47166
  }
46802
47167
  async saveToMainDB(response) {
46803
- const processedPayload = await this.preparePayload(response);
47168
+ const processedPayload = this.preparePayload(response);
46804
47169
  const client = getActiveClient();
46805
47170
  const cachedAt = client.cache && Date.now();
46806
- if (client.cache) {
47171
+ if (client.cache)
46807
47172
  ingestInCache(processedPayload, { cachedAt });
46808
- }
46809
47173
  }
46810
47174
  appendToQueryStream(response, direction, refresh = false) {
46811
47175
  var _a, _b;
46812
47176
  if (refresh) {
46813
- pushToCache(this.cacheKey, {
46814
- data: response.invitations.map(getResolver('invitation')),
46815
- });
47177
+ pushToCache(this.cacheKey, { data: response.events.map(getResolver('event')) });
46816
47178
  }
46817
47179
  else {
46818
47180
  const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
46819
- const invitations = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
46820
- pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [
46821
- ...new Set([...invitations, ...response.invitations.map(getResolver('invitation'))]),
46822
- ] }));
47181
+ const events = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
47182
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...events, ...response.events.map(getResolver('event'))])] }));
46823
47183
  }
46824
47184
  }
46825
47185
  reactor(action) {
46826
- return (invitations) => {
47186
+ return (event) => {
46827
47187
  var _a;
46828
47188
  const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
46829
47189
  if (!collection)
46830
47190
  return;
46831
- if (action === InvitationActionsEnum.OnLocalInvitationUpdated) {
46832
- const isExist = collection.data.find(id => id === invitations[0].invitationId);
46833
- if (!isExist)
46834
- return;
46835
- }
46836
- if (action === InvitationActionsEnum.OnLocalInvitationCreated) {
47191
+ if (action === EventActionsEnum.OnEventCreated) {
46837
47192
  const client = getActiveClient();
46838
- const myInvitations = invitations.filter(invitation => invitation.invitedUserId === client.userId);
46839
- collection.data = [
46840
- ...new Set([
46841
- ...myInvitations.map(invitation => invitation.invitationId),
46842
- ...collection.data,
46843
- ]),
46844
- ];
47193
+ if (client.userId !== event.userId)
47194
+ return;
47195
+ collection.data = [...new Set([event.eventId, ...collection.data])];
46845
47196
  }
46846
- if (action === InvitationActionsEnum.OnLocalInvitationDeleted) {
46847
- collection.data = collection.data.filter(id => id !== invitations[0].invitationId);
47197
+ if (action === EventActionsEnum.OnEventDeleted) {
47198
+ collection.data = collection.data.filter(eventId => eventId !== event.eventId);
46848
47199
  }
46849
47200
  pushToCache(this.cacheKey, collection);
46850
47201
  this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
@@ -46855,26 +47206,22 @@ class MyInvitationsQueryStreamController extends QueryStreamController {
46855
47206
  }
46856
47207
  }
46857
47208
 
46858
- class MyInvitationsLiveCollectionController extends LiveCollectionController {
47209
+ class MyEventLiveCollectionController extends LiveCollectionController {
46859
47210
  constructor(query, callback) {
46860
47211
  const queryStreamId = hash(query);
46861
- const cacheKey = ['invitation', 'collection', queryStreamId];
46862
- const paginationController = new MyInvitationsPaginationController(query);
47212
+ const cacheKey = ['event', 'collection', queryStreamId];
47213
+ const paginationController = new MyEventPaginationController(query);
46863
47214
  super(paginationController, queryStreamId, cacheKey, callback);
46864
47215
  this.query = query;
46865
- this.queryStreamController = new MyInvitationsQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareMyInvitationsPayload);
47216
+ this.queryStreamController = new MyEventQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareEventPayload);
46866
47217
  this.callback = callback.bind(this);
46867
47218
  this.loadPage({ initial: true });
46868
47219
  }
46869
47220
  setup() {
46870
47221
  var _a;
46871
47222
  const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
46872
- if (!collection) {
46873
- pushToCache(this.cacheKey, {
46874
- data: [],
46875
- params: this.query,
46876
- });
46877
- }
47223
+ if (!collection)
47224
+ pushToCache(this.cacheKey, { data: [], params: {} });
46878
47225
  }
46879
47226
  async persistModel(queryPayload) {
46880
47227
  await this.queryStreamController.saveToMainDB(queryPayload);
@@ -46884,18 +47231,12 @@ class MyInvitationsLiveCollectionController extends LiveCollectionController {
46884
47231
  }
46885
47232
  startSubscription() {
46886
47233
  return this.queryStreamController.subscribeRTE([
46887
- {
46888
- fn: onLocalInvitationCreated,
46889
- action: InvitationActionsEnum.OnLocalInvitationCreated,
46890
- },
46891
- {
46892
- fn: onLocalInvitationUpdated,
46893
- action: InvitationActionsEnum.OnLocalInvitationUpdated,
46894
- },
46895
- {
46896
- fn: onLocalInvitationDeleted,
46897
- action: InvitationActionsEnum.OnLocalInvitationDeleted,
46898
- },
47234
+ { fn: onEventCreated, action: EventActionsEnum.OnEventCreated },
47235
+ { fn: onEventUpdated, action: EventActionsEnum.OnEventUpdated },
47236
+ { fn: onEventDeleted, action: EventActionsEnum.OnEventDeleted },
47237
+ { fn: onLocalEventCreated, action: EventActionsEnum.OnEventCreated },
47238
+ { fn: onLocalEventUpdated, action: EventActionsEnum.OnEventUpdated },
47239
+ { fn: onLocalEventDeleted, action: EventActionsEnum.OnEventDeleted },
46899
47240
  ]);
46900
47241
  }
46901
47242
  notifyChange({ origin, loading, error }) {
@@ -46903,224 +47244,202 @@ class MyInvitationsLiveCollectionController extends LiveCollectionController {
46903
47244
  const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
46904
47245
  if (!collection)
46905
47246
  return;
46906
- const data = this.applyFilter((_b = collection.data
46907
- .map(id => pullFromCache(['invitation', 'get', id]))
47247
+ const data = ((_b = collection.data
47248
+ .map(eventId => pullFromCache(['event', 'get', eventId]))
46908
47249
  .filter(isNonNullable)
46909
- .map(({ data }) => invitationLinkedObject(data))) !== null && _b !== void 0 ? _b : []);
46910
- if (!this.shouldNotify(data) && origin === 'event')
47250
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.event);
47251
+ if (!this.shouldNotify(data) && origin === "event" /* Amity.LiveDataOrigin.EVENT */)
46911
47252
  return;
46912
47253
  this.callback({
46913
- onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
46914
47254
  data,
46915
- hasNextPage: !!this.paginationController.getNextToken(),
46916
- loading,
46917
47255
  error,
47256
+ loading,
47257
+ hasNextPage: !!this.paginationController.getNextToken(),
47258
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
46918
47259
  });
46919
47260
  }
46920
- applyFilter(data) {
46921
- let invitations = data;
46922
- if (this.query.targetId) {
46923
- invitations = invitations.filter(invitation => invitation.targetId === this.query.targetId);
46924
- }
46925
- if (this.query.statuses) {
46926
- invitations = invitations.filter(invitation => { var _a; return (_a = this.query.statuses) === null || _a === void 0 ? void 0 : _a.includes(invitation.status); });
46927
- }
46928
- if (this.query.targetType) {
46929
- invitations = invitations.filter(invitation => invitation.targetType === this.query.targetType);
46930
- }
46931
- if (this.query.type) {
46932
- invitations = invitations.filter(invitation => invitation.type === this.query.type);
46933
- }
46934
- const sortFn = (() => {
46935
- switch (this.query.sortBy) {
46936
- case 'firstCreated':
46937
- return sortByFirstCreated;
46938
- case 'lastCreated':
46939
- return sortByLastCreated;
46940
- default:
46941
- return sortByLastCreated;
46942
- }
46943
- })();
46944
- invitations = invitations.sort(sortFn);
46945
- return invitations;
46946
- }
46947
47261
  }
46948
47262
 
46949
47263
  /**
46950
- * Get my community invitations
47264
+ * Get my events
46951
47265
  *
46952
47266
  * @param params the query parameters
46953
- * @param callback the callback to be called when the invitations are fetched
46954
- * @returns invitations
47267
+ * @param callback the callback to be called when the events are updated
47268
+ * @returns events
46955
47269
  *
46956
- * @category My Community Invitations Live Collection
47270
+ * @category Event Live Collection
46957
47271
  *
46958
47272
  */
46959
- const getMyCommunityInvitations = (params, callback, config) => {
47273
+ const getMyEvents = (params, callback, config) => {
46960
47274
  const { log, cache } = getActiveClient();
46961
- if (!cache) {
47275
+ if (!cache)
46962
47276
  console.log(ENABLE_CACHE_MESSAGE);
46963
- }
46964
47277
  const timestamp = Date.now();
46965
- log(`getMyCommunityInvitations: (tmpid: ${timestamp}) > listen`);
46966
- const invitationsLiveCollection = new MyInvitationsLiveCollectionController(Object.assign(Object.assign({}, params), { targetType: 'community', statuses: ["pending" /* InvitationStatusEnum.Pending */] }), callback);
46967
- const disposers = invitationsLiveCollection.startSubscription();
46968
- const cacheKey = invitationsLiveCollection.getCacheKey();
46969
- disposers.push(() => {
46970
- dropFromCache(cacheKey);
46971
- });
47278
+ log(`getMyEvents: (tmpid: ${timestamp}) > listen`);
47279
+ const myEventLiveCollection = new MyEventLiveCollectionController(params, callback);
47280
+ const disposers = myEventLiveCollection.startSubscription();
47281
+ const cacheKey = myEventLiveCollection.getCacheKey();
47282
+ disposers.push(() => dropFromCache(cacheKey));
46972
47283
  return () => {
46973
- log(`getInvitations (tmpid: ${timestamp}) > dispose`);
47284
+ log(`getMyEvents (tmpid: ${timestamp}) > dispose`);
46974
47285
  disposers.forEach(fn => fn());
46975
47286
  };
46976
47287
  };
46977
47288
 
46978
- var index$1 = /*#__PURE__*/Object.freeze({
46979
- __proto__: null,
46980
- onLocalInvitationCreated: onLocalInvitationCreated,
46981
- onLocalInvitationUpdated: onLocalInvitationUpdated,
46982
- onLocalInvitationDeleted: onLocalInvitationDeleted,
46983
- getMyCommunityInvitations: getMyCommunityInvitations
46984
- });
46985
-
46986
- // TODO: confirm id
46987
- /* begin_public_function
46988
- id: live_reaction.create
46989
- */
46990
- /**
46991
- * ```js
46992
- * import { LiveReactionRepository } from '@amityco/ts-sdk'
46993
- * await LiveReactionRepository.createReaction({
46994
- * referenceType: 'post',
46995
- * referenceId: 'postId',
46996
- * streamId: 'streamId',
46997
- * reactionName: 'like',
46998
- * })
46999
- * ```
47000
- *
47001
- *
47002
- * @param referenceId that is target post's ID linked with a livestream
47003
- * @param referenceType should be 'post'
47004
- * @param reactionName that is the reaction name
47005
- * @param streamId stream id
47006
- * @returns a success boolean if the reaction was added
47007
- *
47008
- * @category Live Reaction API
47009
- * @async
47010
- */
47011
- const createReaction = async ({ referenceId, referenceType, reactionName, streamId, }) => {
47012
- const client = getActiveClient();
47013
- client.log('live_reaction/createReaction', {
47014
- referenceId,
47015
- referenceType,
47016
- reactionName,
47017
- });
47018
- const reactionSynceEngine = ReactionSyncEngine.getInstance();
47019
- const reaction = {
47020
- reactionName,
47021
- referencePublicId: referenceId,
47022
- referenceType,
47023
- streamId,
47024
- occurredAt: new Date().toISOString(),
47025
- };
47026
- reactionSynceEngine.createLiveReaction(reaction);
47027
- fireEvent('local.liveReaction.created', [Object.assign(Object.assign({}, reaction), { userId: client.userId, referenceId })]);
47028
- return true;
47029
- };
47030
- /* end_public_function */
47289
+ class RSVPPaginationController extends PaginationController {
47290
+ async getRequest(queryParams, token) {
47291
+ const { limit = COLLECTION_DEFAULT_PAGINATION_LIMIT, eventId } = queryParams, params = __rest(queryParams, ["limit", "eventId"]);
47292
+ const options = token ? { token } : { limit };
47293
+ const { data: response } = await this.http.get(`/api/v1/events/${eventId}/rsvps`, { params: Object.assign(Object.assign({}, params), { options }) });
47294
+ return response;
47295
+ }
47296
+ }
47031
47297
 
47032
- /**
47033
- * ```js
47034
- * import { onLiveReactionCreated } from '@amityco/ts-sdk'
47035
- * const dispose = onLiveReactionCreated(reactions => {
47036
- * // ...
47037
- * })
47038
- * ```
47039
- *
47040
- * Fired when a batch of {@link Amity.LiveReaction} has been created
47041
- *
47042
- * @param callback The function to call when the event was fired
47043
- * @returns an {@link Amity.Unsubscriber} function to stop listening
47044
- *
47045
- * @category Live Reaction Events
47046
- */
47047
- const onLiveReactionCreated = (callback) => {
47048
- const client = getActiveClient();
47049
- const filter = (rawPayload) => {
47050
- if (rawPayload.reactions.length > 0) {
47051
- // TODO: check with BE if user id is internal or pulbic id
47052
- const filteredPayload = rawPayload.reactions.filter(({ userId }) => userId !== client.userId);
47053
- callback(filteredPayload);
47298
+ class RSVPQueryStreamController extends QueryStreamController {
47299
+ constructor(query, cacheKey, notifyChange, preparePayload) {
47300
+ super(query, cacheKey);
47301
+ this.notifyChange = notifyChange;
47302
+ this.preparePayload = preparePayload;
47303
+ }
47304
+ async saveToMainDB(response) {
47305
+ const processedPayload = this.preparePayload(response);
47306
+ const client = getActiveClient();
47307
+ const cachedAt = client.cache && Date.now();
47308
+ if (client.cache)
47309
+ ingestInCache(processedPayload, { cachedAt });
47310
+ }
47311
+ appendToQueryStream(response, direction, refresh = false) {
47312
+ var _a, _b;
47313
+ if (refresh) {
47314
+ pushToCache(this.cacheKey, { data: response.events.map(getResolver('event')) });
47054
47315
  }
47055
- };
47056
- return createEventSubscriber(client, 'live_reaction/onLiveReactionCreated', 'liveReaction.created', filter);
47057
- };
47316
+ else {
47317
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
47318
+ const events = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
47319
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...events, ...response.events.map(getResolver('event'))])] }));
47320
+ }
47321
+ }
47322
+ reactor(action) {
47323
+ return (event) => {
47324
+ var _a;
47325
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
47326
+ if (!collection)
47327
+ return;
47328
+ if (action === EventActionsEnum.OnEventCreated) {
47329
+ const client = getActiveClient();
47330
+ if (client.userId !== event.userId)
47331
+ return;
47332
+ collection.data = [...new Set([event.eventId, ...collection.data])];
47333
+ }
47334
+ if (action === EventActionsEnum.OnEventDeleted) {
47335
+ collection.data = collection.data.filter(eventId => eventId !== event.eventId);
47336
+ }
47337
+ pushToCache(this.cacheKey, collection);
47338
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
47339
+ };
47340
+ }
47341
+ subscribeRTE(createSubscriber) {
47342
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
47343
+ }
47344
+ }
47058
47345
 
47059
- /**
47060
- * ```js
47061
- * import { onLiveReactionCreatedLocal } from '@amityco/ts-sdk'
47062
- * const dispose = onLiveReactionCreatedLocal(reactions => {
47063
- * // ...
47064
- * })
47065
- * ```
47066
- *
47067
- * Fired when a batch of {@link Amity.LiveReaction} has been created
47068
- *
47069
- * @param callback The function to call when the event was fired
47070
- * @returns an {@link Amity.Unsubscriber} function to stop listening
47071
- *
47072
- * @category Live Reaction Events
47073
- */
47074
- const onLiveReactionCreatedLocal = (callback) => {
47075
- const client = getActiveClient();
47076
- return createEventSubscriber(client, 'live_reaction/onLiveReactionCreated', 'local.liveReaction.created', callback);
47077
- };
47346
+ class RSVPLiveCollectionController extends LiveCollectionController {
47347
+ constructor(query, callback) {
47348
+ const queryStreamId = hash(query);
47349
+ const cacheKey = ['event', 'collection', queryStreamId];
47350
+ const paginationController = new RSVPPaginationController(query);
47351
+ super(paginationController, queryStreamId, cacheKey, callback);
47352
+ this.query = query;
47353
+ this.queryStreamController = new RSVPQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), prepareEventPayload);
47354
+ this.callback = callback.bind(this);
47355
+ this.loadPage({ initial: true });
47356
+ }
47357
+ setup() {
47358
+ var _a;
47359
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
47360
+ if (!collection)
47361
+ pushToCache(this.cacheKey, { data: [], params: {} });
47362
+ }
47363
+ async persistModel(queryPayload) {
47364
+ await this.queryStreamController.saveToMainDB(queryPayload);
47365
+ }
47366
+ persistQueryStream({ response, direction, refresh, }) {
47367
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
47368
+ }
47369
+ startSubscription() {
47370
+ return this.queryStreamController.subscribeRTE([
47371
+ { fn: onRSVPCreated, action: EventActionsEnum.OnRSVPCreated },
47372
+ { fn: onRSVPUpdated, action: EventActionsEnum.OnRSVPUpdated },
47373
+ { fn: onLocalRSVPCreated, action: EventActionsEnum.OnRSVPCreated },
47374
+ { fn: onLocalRSVPUpdated, action: EventActionsEnum.OnRSVPUpdated },
47375
+ ]);
47376
+ }
47377
+ notifyChange({ origin, loading, error }) {
47378
+ var _a, _b;
47379
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
47380
+ if (!collection)
47381
+ return;
47382
+ const data = ((_b = collection.data
47383
+ .map(eventId => pullFromCache(['event', 'get', eventId]))
47384
+ .filter(isNonNullable)
47385
+ .map(({ data }) => data)) !== null && _b !== void 0 ? _b : []).map(LinkedObject.event);
47386
+ if (!this.shouldNotify(data) && origin === "event" /* Amity.LiveDataOrigin.EVENT */)
47387
+ return;
47388
+ this.callback({
47389
+ data,
47390
+ error,
47391
+ loading,
47392
+ hasNextPage: !!this.paginationController.getNextToken(),
47393
+ onNextPage: () => this.loadPage({ direction: "next" /* Amity.LiveCollectionPageDirection.NEXT */ }),
47394
+ });
47395
+ }
47396
+ }
47078
47397
 
47079
47398
  /**
47399
+ * Get events
47080
47400
  *
47081
- * ```js
47082
- * import { getReactions } from '@amityco/ts-sdk';
47083
- *
47084
- * const unsubscribe = getReactions(response => {
47085
- * reactions = response.data
47086
- * });
47087
- * ```
47088
- *
47089
- * Observe live reactions {@link_Amity.LiveReaction} that have been created in a post linked with a stream
47401
+ * @param params the query parameters
47402
+ * @param callback the callback to be called when the events are updated
47403
+ * @returns events
47090
47404
  *
47091
- * @param callback the function to call when new data are available
47092
- * @returns An {@link Amity.Unsubscriber} function to run when willing to stop observing the events
47405
+ * @category RSVP Live Collection
47093
47406
  *
47094
- * @category Live Reaction Observable
47095
47407
  */
47096
- // TODO: confirm return type for this observable property
47097
- const getReactions = (postId, callback) => {
47098
- const { _id: userId } = getActiveUser();
47099
- if (!userId)
47100
- throw new ASCError('The _id has not been defined in ActiveUser', 800000 /* Amity.ClientError.UNKNOWN_ERROR */, "error" /* Amity.ErrorLevel.ERROR */);
47101
- const { log } = getActiveClient();
47408
+ const getRSVPs = (params, callback, config) => {
47409
+ const { log, cache } = getActiveClient();
47410
+ if (!cache)
47411
+ console.log(ENABLE_CACHE_MESSAGE);
47102
47412
  const timestamp = Date.now();
47103
- log(`getReactions(tmpid: ${timestamp}) > listen`);
47104
- const disposers = [];
47105
- const dispatcher = (data) => {
47106
- callback(data);
47107
- };
47108
- const realtimeRouter = (data) => {
47109
- const relevantReactions = data.filter(({ referenceId }) => referenceId === postId);
47110
- dispatcher(relevantReactions);
47111
- };
47112
- disposers.push(onLiveReactionCreated(realtimeRouter));
47113
- disposers.push(onLiveReactionCreatedLocal(realtimeRouter));
47413
+ log(`getRSVPs: (tmpid: ${timestamp}) > listen`);
47414
+ const eventLiveCollection = new RSVPLiveCollectionController(params, callback);
47415
+ const disposers = eventLiveCollection.startSubscription();
47416
+ const cacheKey = eventLiveCollection.getCacheKey();
47417
+ disposers.push(() => dropFromCache(cacheKey));
47114
47418
  return () => {
47419
+ log(`getRSVPs (tmpid: ${timestamp}) > dispose`);
47115
47420
  disposers.forEach(fn => fn());
47116
47421
  };
47117
47422
  };
47118
47423
 
47119
47424
  var index = /*#__PURE__*/Object.freeze({
47120
47425
  __proto__: null,
47121
- createReaction: createReaction,
47122
- onLiveReactionCreated: onLiveReactionCreated,
47123
- getReactions: getReactions
47426
+ createEvent: createEvent,
47427
+ updateEvent: updateEvent,
47428
+ deleteEvent: deleteEvent,
47429
+ onEventCreated: onEventCreated,
47430
+ onEventUpdated: onEventUpdated,
47431
+ onEventDeleted: onEventDeleted,
47432
+ onLocalEventCreated: onLocalEventCreated,
47433
+ onLocalEventUpdated: onLocalEventUpdated,
47434
+ onLocalEventDeleted: onLocalEventDeleted,
47435
+ onRSVPCreated: onRSVPCreated,
47436
+ onRSVPUpdated: onRSVPUpdated,
47437
+ onLocalRSVPCreated: onLocalRSVPCreated,
47438
+ onLocalRSVPUpdated: onLocalRSVPUpdated,
47439
+ getEvent: getEvent,
47440
+ getEvents: getEvents,
47441
+ getMyEvents: getMyEvents,
47442
+ getRSVPs: getRSVPs
47124
47443
  });
47125
47444
 
47126
- export { API_REGIONS, index$3 as AdRepository, index$c as CategoryRepository, index$g as ChannelRepository, index$p as Client, index$b as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$d as CommunityRepository, ContentFeedType, ContentFlagReasonEnum, DefaultCommunityPostSetting, FeedDataTypeEnum, index$a as FeedRepository, FeedSortByEnum, FeedSourceEnum, FileAccessTypeEnum, index$m as FileRepository, FileType, GET_WATCHER_URLS, index$1 as InvitationRepository, InvitationSortByEnum, InvitationStatusEnum, InvitationTypeEnum, JoinRequestStatusEnum, JoinResultStatusEnum, index as LiveReactionRepository, index$5 as LiveStreamPlayer, MembershipAcceptanceTypeEnum, MessageContentType, index$k as MessageRepository, index$6 as PollRepository, PostContentType, index$9 as PostRepository, PostStructureType, index$l as ReactionRepository, index$7 as RoomRepository, index$4 as StoryRepository, index$8 as StreamRepository, index$j as SubChannelRepository, SubscriptionLevels, index$n as UserRepository, UserTypeEnum, 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, getLiveReactionTopic, getLiveStreamTopic, 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, index$2 as notificationTray, 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 };
47445
+ export { API_REGIONS, index$4 as AdRepository, AmityEventOriginType, AmityEventResponseStatus, AmityEventStatus, AmityEventType, index$c as CategoryRepository, index$g as ChannelRepository, index$p as Client, index$b as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$d as CommunityRepository, ContentFeedType, ContentFlagReasonEnum, DefaultCommunityPostSetting, index as EventRepository, FeedDataTypeEnum, index$a as FeedRepository, FeedSortByEnum, FeedSourceEnum, FileAccessTypeEnum, index$m as FileRepository, FileType, GET_WATCHER_URLS, index$2 as InvitationRepository, InvitationSortByEnum, InvitationStatusEnum, InvitationTypeEnum, JoinRequestStatusEnum, JoinResultStatusEnum, index$1 as LiveReactionRepository, index$6 as LiveStreamPlayer, MembershipAcceptanceTypeEnum, MessageContentType, index$k as MessageRepository, index$7 as PollRepository, PostContentType, index$9 as PostRepository, PostStructureType, index$l as ReactionRepository, index$5 as StoryRepository, index$8 as StreamRepository, index$j as SubChannelRepository, SubscriptionLevels, index$n as UserRepository, UserTypeEnum, 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, getLiveReactionTopic, getLiveStreamTopic, 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, index$3 as notificationTray, 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 };