@amityco/ts-sdk 6.17.3-beac0a2.0 → 6.17.3-e382dbe.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 (65) hide show
  1. package/dist/@types/core/payload.d.ts +2 -0
  2. package/dist/@types/core/payload.d.ts.map +1 -1
  3. package/dist/@types/domains/client.d.ts +2 -0
  4. package/dist/@types/domains/client.d.ts.map +1 -1
  5. package/dist/@types/domains/story.d.ts +18 -1
  6. package/dist/@types/domains/story.d.ts.map +1 -1
  7. package/dist/channelRepository/observers/getChannels/ChannelLiveCollectionController.d.ts.map +1 -1
  8. package/dist/channelRepository/observers/getChannels/ChannelQueryStreamController.d.ts.map +1 -1
  9. package/dist/client/api/createClient.d.ts.map +1 -1
  10. package/dist/client/api/validateTexts.d.ts +8 -0
  11. package/dist/client/api/validateTexts.d.ts.map +1 -0
  12. package/dist/client/api/validateUrls.d.ts +8 -0
  13. package/dist/client/api/validateUrls.d.ts.map +1 -0
  14. package/dist/core/query/sorting.d.ts +6 -0
  15. package/dist/core/query/sorting.d.ts.map +1 -1
  16. package/dist/index.cjs.js +385 -39
  17. package/dist/index.esm.js +385 -40
  18. package/dist/index.umd.js +4 -4
  19. package/dist/storyRepository/api/createImageStory.d.ts.map +1 -1
  20. package/dist/storyRepository/api/createVideoStory.d.ts.map +1 -1
  21. package/dist/storyRepository/constants.d.ts +2 -0
  22. package/dist/storyRepository/constants.d.ts.map +1 -1
  23. package/dist/storyRepository/observers/getGlobalStoryTargets/GlobalStoryLiveCollectionController.d.ts +14 -0
  24. package/dist/storyRepository/observers/getGlobalStoryTargets/GlobalStoryLiveCollectionController.d.ts.map +1 -0
  25. package/dist/storyRepository/observers/getGlobalStoryTargets/GlobalStoryPageController.d.ts +13 -0
  26. package/dist/storyRepository/observers/getGlobalStoryTargets/GlobalStoryPageController.d.ts.map +1 -0
  27. package/dist/storyRepository/observers/getGlobalStoryTargets/GlobalStoryQueryStreamController.d.ts +16 -0
  28. package/dist/storyRepository/observers/getGlobalStoryTargets/GlobalStoryQueryStreamController.d.ts.map +1 -0
  29. package/dist/storyRepository/observers/getGlobalStoryTargets/getGlobalStoryTargets.d.ts +2 -0
  30. package/dist/storyRepository/observers/getGlobalStoryTargets/getGlobalStoryTargets.d.ts.map +1 -0
  31. package/dist/storyRepository/observers/getGlobalStoryTargets/index.d.ts +2 -0
  32. package/dist/storyRepository/observers/getGlobalStoryTargets/index.d.ts.map +1 -0
  33. package/dist/storyRepository/observers/getStoriesByTargetIds/StoryPaginationNoPageController.d.ts.map +1 -1
  34. package/dist/storyRepository/observers/index.d.ts +1 -0
  35. package/dist/storyRepository/observers/index.d.ts.map +1 -1
  36. package/dist/storyRepository/utils/StoryComputedValue.d.ts +23 -0
  37. package/dist/storyRepository/utils/StoryComputedValue.d.ts.map +1 -0
  38. package/dist/utils/linkedObject/storyLinkedObject.d.ts.map +1 -1
  39. package/dist/utils/linkedObject/storyTargetLinkedObject.d.ts.map +1 -1
  40. package/package.json +1 -1
  41. package/src/@types/core/payload.ts +4 -0
  42. package/src/@types/domains/client.ts +2 -0
  43. package/src/@types/domains/story.ts +22 -2
  44. package/src/channelRepository/observers/getChannels/ChannelLiveCollectionController.ts +24 -1
  45. package/src/channelRepository/observers/getChannels/ChannelQueryStreamController.ts +4 -1
  46. package/src/client/api/createClient.ts +4 -0
  47. package/src/client/api/validateTexts.ts +23 -0
  48. package/src/client/api/validateUrls.ts +23 -0
  49. package/src/core/query/sorting.ts +8 -0
  50. package/src/storyRepository/api/createImageStory.ts +7 -0
  51. package/src/storyRepository/api/createVideoStory.ts +7 -0
  52. package/src/storyRepository/constants.ts +2 -0
  53. package/src/storyRepository/observers/getGlobalStoryTargets/GlobalStoryLiveCollectionController.ts +153 -0
  54. package/src/storyRepository/observers/getGlobalStoryTargets/GlobalStoryPageController.ts +73 -0
  55. package/src/storyRepository/observers/getGlobalStoryTargets/GlobalStoryQueryStreamController.ts +94 -0
  56. package/src/storyRepository/observers/getGlobalStoryTargets/getGlobalStoryTargets.ts +32 -0
  57. package/src/storyRepository/observers/getGlobalStoryTargets/index.ts +1 -0
  58. package/src/storyRepository/observers/getStoriesByTargetIds/StoryPaginationNoPageController.ts +0 -2
  59. package/src/storyRepository/observers/index.ts +1 -0
  60. package/src/storyRepository/utils/StoryComputedValue.ts +144 -0
  61. package/src/utils/linkedObject/storyLinkedObject.ts +2 -1
  62. package/src/utils/linkedObject/storyTargetLinkedObject.ts +27 -4
  63. package/dist/storyRepository/utils/calculateHasUnseenFlag.d.ts +0 -6
  64. package/dist/storyRepository/utils/calculateHasUnseenFlag.d.ts.map +0 -1
  65. package/src/storyRepository/utils/calculateHasUnseenFlag.ts +0 -47
package/dist/index.esm.js CHANGED
@@ -1218,6 +1218,10 @@ const sortBySegmentNumber = ({ segmentNumber: a }, { segmentNumber: b }) => a -
1218
1218
  * Sorting a collection by its oldest items
1219
1219
  */
1220
1220
  const sortByFirstCreated = ({ createdAt: a }, { createdAt: b }) => new Date(a).valueOf() - new Date(b).valueOf();
1221
+ /**
1222
+ * Sorting a story-collection by its localSortingDate
1223
+ */
1224
+ const sortByLocalSortingDate = ({ localSortingDate: a }, { localSortingDate: b }) => new Date(b).getTime() - new Date(a).getTime();
1221
1225
  /**
1222
1226
  * Sorting a collection by its newest items
1223
1227
  */
@@ -21111,55 +21115,125 @@ const userLinkedObject = (user) => {
21111
21115
  } });
21112
21116
  };
21113
21117
 
21114
- const calculateHasUnseenFlag = (params) => {
21115
- const cacheStoryExpireTime = pullFromCache([
21116
- "story-expire" /* STORY_KEY_CACHE.EXPIRE */,
21117
- params.targetId,
21118
- ]);
21119
- const cacheStoreSeenTime = pullFromCache([
21120
- "story-last-seen" /* STORY_KEY_CACHE.LAST_SEEN */,
21121
- params.targetId,
21122
- ]);
21123
- const now = new Date().getTime();
21124
- const lastStoryExpiresAt = params.lastStoryExpiresAt
21125
- ? new Date(params.lastStoryExpiresAt).getTime()
21126
- : 0;
21127
- const lastStorySeenExpiresAt = params.lastStorySeenExpiresAt
21128
- ? new Date(params.lastStorySeenExpiresAt).getTime()
21129
- : 0;
21130
- const localLastStoryExpires = (cacheStoryExpireTime === null || cacheStoryExpireTime === void 0 ? void 0 : cacheStoryExpireTime.data)
21131
- ? new Date(cacheStoryExpireTime === null || cacheStoryExpireTime === void 0 ? void 0 : cacheStoryExpireTime.data).getTime()
21132
- : 0;
21133
- const localLastStorySeenExpiresAt = (cacheStoreSeenTime === null || cacheStoreSeenTime === void 0 ? void 0 : cacheStoreSeenTime.data)
21134
- ? new Date(cacheStoreSeenTime === null || cacheStoreSeenTime === void 0 ? void 0 : cacheStoreSeenTime.data).getTime()
21135
- : 0;
21136
- const highestSeen = Math.max(lastStorySeenExpiresAt, localLastStorySeenExpiresAt);
21137
- const currentSyncingState = pullFromCache([
21138
- "story-sync-state" /* STORY_KEY_CACHE.SYNC_STATE */,
21139
- params.targetId,
21140
- ]);
21141
- if (currentSyncingState === null || currentSyncingState === void 0 ? void 0 : currentSyncingState.data) {
21142
- if (["syncing" /* Amity.SyncState.Syncing */, "error" /* Amity.SyncState.Error */].includes(currentSyncingState.data)) {
21143
- return localLastStoryExpires > now && localLastStoryExpires > highestSeen;
21118
+ class StoryComputedValue {
21119
+ constructor(targetId, lastStoryExpiresAt, lastStorySeenExpiresAt) {
21120
+ this._syncingStoriesCount = 0;
21121
+ this._syncedStoriesCount = 0;
21122
+ this._errorStoriesCount = 0;
21123
+ this._targetId = targetId;
21124
+ this._lastStoryExpiresAt = lastStoryExpiresAt;
21125
+ this._lastStorySeenExpiresAt = lastStorySeenExpiresAt;
21126
+ this.cacheStoryExpireTime = pullFromCache([
21127
+ "story-expire" /* STORY_KEY_CACHE.EXPIRE */,
21128
+ this._targetId,
21129
+ ]);
21130
+ this.cacheStoreSeenTime = pullFromCache([
21131
+ "story-last-seen" /* STORY_KEY_CACHE.LAST_SEEN */,
21132
+ this._targetId,
21133
+ ]);
21134
+ this.getTotalStoryByStatus();
21135
+ }
21136
+ get lastStoryExpiresAt() {
21137
+ return this._lastStoryExpiresAt ? new Date(this._lastStoryExpiresAt).getTime() : 0;
21138
+ }
21139
+ get lastStorySeenExpiresAt() {
21140
+ return this._lastStorySeenExpiresAt ? new Date(this._lastStorySeenExpiresAt).getTime() : 0;
21141
+ }
21142
+ get localLastStoryExpires() {
21143
+ var _a, _b;
21144
+ return ((_a = this.cacheStoryExpireTime) === null || _a === void 0 ? void 0 : _a.data)
21145
+ ? new Date((_b = this.cacheStoryExpireTime) === null || _b === void 0 ? void 0 : _b.data).getTime()
21146
+ : 0;
21147
+ }
21148
+ get localLastStorySeenExpiresAt() {
21149
+ var _a, _b;
21150
+ return ((_a = this.cacheStoreSeenTime) === null || _a === void 0 ? void 0 : _a.data) ? new Date((_b = this.cacheStoreSeenTime) === null || _b === void 0 ? void 0 : _b.data).getTime() : 0;
21151
+ }
21152
+ get isContainUnSyncedStory() {
21153
+ const currentSyncingState = pullFromCache([
21154
+ "story-sync-state" /* STORY_KEY_CACHE.SYNC_STATE */,
21155
+ this._targetId,
21156
+ ]);
21157
+ if (!(currentSyncingState === null || currentSyncingState === void 0 ? void 0 : currentSyncingState.data))
21158
+ return false;
21159
+ return ["syncing" /* Amity.SyncState.Syncing */, "error" /* Amity.SyncState.Error */].includes(currentSyncingState.data);
21160
+ }
21161
+ getLocalLastSortingDate() {
21162
+ if (this.isContainUnSyncedStory) {
21163
+ return this.localLastStoryExpires;
21144
21164
  }
21165
+ return this.lastStoryExpiresAt;
21166
+ }
21167
+ getHasUnseenFlag() {
21168
+ const now = new Date().getTime();
21169
+ const highestSeen = Math.max(this.lastStorySeenExpiresAt, this.localLastStorySeenExpiresAt);
21170
+ pullFromCache([
21171
+ "story-sync-state" /* STORY_KEY_CACHE.SYNC_STATE */,
21172
+ this._targetId,
21173
+ ]);
21174
+ if (this.isContainUnSyncedStory) {
21175
+ return this.localLastStoryExpires > now && this.localLastStoryExpires > highestSeen;
21176
+ }
21177
+ return this.lastStoryExpiresAt > now && this.lastStoryExpiresAt > highestSeen;
21178
+ }
21179
+ getTotalStoryByStatus() {
21180
+ const stories = queryCache(["story" /* STORY_KEY_CACHE.STORY */, 'get']);
21181
+ if (!stories) {
21182
+ this._errorStoriesCount = 0;
21183
+ this._syncedStoriesCount = 0;
21184
+ this._syncingStoriesCount = 0;
21185
+ return;
21186
+ }
21187
+ const groupByType = stories.reduce((acc, story) => {
21188
+ const { data: { targetId, syncState }, } = story;
21189
+ if (targetId === this._targetId) {
21190
+ acc[syncState] += 1;
21191
+ }
21192
+ return acc;
21193
+ }, {
21194
+ syncing: 0,
21195
+ error: 0,
21196
+ synced: 0,
21197
+ });
21198
+ this._errorStoriesCount = groupByType.error;
21199
+ this._syncedStoriesCount = groupByType.synced;
21200
+ this._syncingStoriesCount = groupByType.syncing;
21145
21201
  }
21146
- return lastStoryExpiresAt > now && lastStoryExpiresAt > highestSeen;
21147
- };
21202
+ get syncedStoriesCount() {
21203
+ return this._syncedStoriesCount;
21204
+ }
21205
+ get syncingStoriesCount() {
21206
+ return this._syncingStoriesCount;
21207
+ }
21208
+ get failedStoriesCount() {
21209
+ return this._errorStoriesCount;
21210
+ }
21211
+ }
21148
21212
 
21149
21213
  const storyTargetLinkedObject = (storyTarget) => {
21150
- const { targetType, targetId, lastStoryExpiresAt, lastStorySeenExpiresAt, targetUpdatedAt } = storyTarget;
21214
+ const { targetType, targetId, lastStoryExpiresAt, lastStorySeenExpiresAt, targetUpdatedAt, localFilter, } = storyTarget;
21215
+ const computedValue = new StoryComputedValue(targetId, lastStoryExpiresAt, lastStorySeenExpiresAt);
21151
21216
  return {
21152
21217
  targetType,
21153
21218
  targetId,
21219
+ lastStoryExpiresAt,
21154
21220
  updatedAt: targetUpdatedAt,
21155
- hasUnseen: calculateHasUnseenFlag({ targetId, lastStoryExpiresAt, lastStorySeenExpiresAt }),
21221
+ // Additional data
21222
+ hasUnseen: computedValue.getHasUnseenFlag(),
21223
+ syncedStoriesCount: computedValue.syncedStoriesCount,
21224
+ syncingStoriesCount: computedValue.syncingStoriesCount,
21225
+ failedStoriesCount: computedValue.failedStoriesCount,
21226
+ localFilter,
21227
+ localLastExpires: computedValue.localLastStoryExpires,
21228
+ localLastSeen: computedValue.localLastStorySeenExpiresAt,
21229
+ localSortingDate: computedValue.getLocalLastSortingDate(),
21156
21230
  };
21157
21231
  };
21158
21232
 
21159
21233
  const storyLinkedObject = (story) => {
21160
21234
  const analyticsEngineInstance = AnalyticsEngine$1.getInstance();
21161
21235
  const storyTargetCache = pullFromCache([
21162
- 'storyTarget',
21236
+ "storyTarget" /* STORY_KEY_CACHE.STORY_TARGET */,
21163
21237
  'get',
21164
21238
  story.targetId,
21165
21239
  ]);
@@ -23207,6 +23281,40 @@ const hasPermission$1 = (permission) => {
23207
23281
  };
23208
23282
  };
23209
23283
 
23284
+ /**
23285
+ * Validate a list of urls
23286
+ * @param urls array of strings to validate (max 10 items)
23287
+ *
23288
+ * @category Client API
23289
+ */
23290
+ const validateUrls = async (urls) => {
23291
+ const client = getActiveClient();
23292
+ client.log('channel/markerSync');
23293
+ if (urls.length === 0)
23294
+ return false;
23295
+ const { data: payload } = await client.http.post('/api/v3/allowlists/verify', {
23296
+ data: urls,
23297
+ });
23298
+ return payload.success;
23299
+ };
23300
+
23301
+ /**
23302
+ * Validate a list of texts
23303
+ * @param texts array of strings to validate (max 10 items)
23304
+ *
23305
+ * @category Client API
23306
+ */
23307
+ const validateTexts = async (texts) => {
23308
+ const client = getActiveClient();
23309
+ client.log('channel/markerSync');
23310
+ if (texts.length === 0)
23311
+ return false;
23312
+ const { data: payload } = await client.http.post('/api/v3/blocklists/verify', {
23313
+ data: texts,
23314
+ });
23315
+ return payload.success;
23316
+ };
23317
+
23210
23318
  /**
23211
23319
  * ```js
23212
23320
  * import { getFeedSettings } from '@amityco/ts-sdk'
@@ -24744,6 +24852,8 @@ const createClient = (apiKey, apiRegion = API_REGIONS.SG, { debugSession = DEFAU
24744
24852
  accessTokenExpiryWatcher,
24745
24853
  sessionHandler,
24746
24854
  hasPermission: hasPermission$1,
24855
+ validateUrls,
24856
+ validateTexts,
24747
24857
  getFeedSettings,
24748
24858
  getSocialSettings,
24749
24859
  getMessagePreviewSetting,
@@ -32259,7 +32369,8 @@ class ChannelQueryStreamController extends QueryStreamController {
32259
32369
  const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
32260
32370
  if (!collection)
32261
32371
  return;
32262
- if (this.paginationController instanceof ChannelPaginationController) {
32372
+ if (this.paginationController instanceof ChannelPaginationController &&
32373
+ action === 'onCreate') {
32263
32374
  collection.data = [...new Set([payload.channelId, ...collection.data])];
32264
32375
  pushToCache(this.cacheKey, collection);
32265
32376
  }
@@ -32447,7 +32558,22 @@ class ChannelLiveCollectionController extends LiveCollectionController {
32447
32558
  { fn: onChannelUpdated, action: 'onUpdate' },
32448
32559
  { fn: onChannelMuted, action: 'onMute' },
32449
32560
  { fn: onChannelJoined, action: 'onJoin' },
32450
- { fn: onChannelLeft, action: 'onLeft' },
32561
+ {
32562
+ fn: (reactor) => {
32563
+ const callback = (channel, member) => {
32564
+ var _a, _b;
32565
+ const { userId } = getActiveClient();
32566
+ // if query for channel member and user is not a member, remove channelId from curren collection
32567
+ if (this.query.membership === 'member' && userId === member.userId) {
32568
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
32569
+ pushToCache(this.cacheKey, Object.assign(Object.assign({}, collection), { data: (_b = collection === null || collection === void 0 ? void 0 : collection.data.filter(c => c !== channel.channelId)) !== null && _b !== void 0 ? _b : [] }));
32570
+ }
32571
+ return reactor(channel);
32572
+ };
32573
+ return onChannelLeft(callback);
32574
+ },
32575
+ action: 'onLeft',
32576
+ },
32451
32577
  { fn: onChannelMemberAdded, action: 'onMemberAdded' },
32452
32578
  { fn: onChannelMemberRemoved, action: 'onMemberRemoved' },
32453
32579
  {
@@ -38265,7 +38391,10 @@ const createImageStory = async (targetType, targetId, formData, metadata = {}, i
38265
38391
  targetId,
38266
38392
  metadata,
38267
38393
  };
38394
+ const date = new Date();
38268
38395
  pushToCache(["story-sync-state" /* STORY_KEY_CACHE.SYNC_STATE */, targetId], "syncing" /* Amity.SyncState.Syncing */);
38396
+ // Update local story expires time
38397
+ pushToCache(["story-expire" /* STORY_KEY_CACHE.EXPIRE */, targetId], new Date(date.setFullYear(date.getFullYear() + 1)));
38269
38398
  // Fire optimistic event
38270
38399
  createOptimisticEvent({ payload, formData }, optimisticData => {
38271
38400
  fireEvent('local.story.created', optimisticData);
@@ -38326,7 +38455,10 @@ const createVideoStory = async (targetType, targetId, formData, metadata = {}, i
38326
38455
  targetId,
38327
38456
  metadata,
38328
38457
  };
38458
+ const date = new Date();
38329
38459
  pushToCache(["story-sync-state" /* STORY_KEY_CACHE.SYNC_STATE */, targetId], "syncing" /* Amity.SyncState.Syncing */);
38460
+ // Update local story expires time
38461
+ pushToCache(["story-expire" /* STORY_KEY_CACHE.EXPIRE */, targetId], new Date(date.setFullYear(date.getFullYear() + 1)));
38330
38462
  // Fire optimistic event
38331
38463
  createOptimisticEvent({ payload, formData, isVideo: true }, optimisticData => {
38332
38464
  fireEvent('local.story.created', optimisticData);
@@ -38914,7 +39046,6 @@ class StoryQueryStreamController extends QueryStreamController {
38914
39046
  }
38915
39047
  }
38916
39048
 
38917
- /* eslint-disable no-use-before-define */
38918
39049
  class StoryPaginationNoPageController extends PaginationNoPageController {
38919
39050
  async getRequest(queryParams) {
38920
39051
  const { data: queryResponse } = await this.http.get('/api/v4/stories-by-targets', {
@@ -39009,6 +39140,219 @@ const getStoriesByTargetIds = (params, callback, config) => {
39009
39140
  };
39010
39141
  };
39011
39142
 
39143
+ const updateLocalList = (cacheKey, targetIds) => {
39144
+ var _a, _b;
39145
+ const collection = (_a = pullFromCache(cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39146
+ const storyTargets = (_b = collection === null || collection === void 0 ? void 0 : collection.data) !== null && _b !== void 0 ? _b : [];
39147
+ pushToCache(cacheKey, Object.assign(Object.assign({}, collection), { data: [...new Set([...storyTargets, ...targetIds])] }));
39148
+ };
39149
+ class GlobalStoryQueryStreamController extends QueryStreamController {
39150
+ constructor(query, cacheKey, notifyChange, paginationController) {
39151
+ super(query, cacheKey);
39152
+ this.notifyChange = notifyChange;
39153
+ this.paginationController = paginationController;
39154
+ // Fix ESLint, "Expected 'this' to be used by class method"
39155
+ this.preparePayload = payload => payload;
39156
+ }
39157
+ saveToMainDB(response) {
39158
+ const client = getActiveClient();
39159
+ const cachedAt = client.cache && Date.now();
39160
+ // Fix Eslint error for "Expected 'this' to be used by class method"
39161
+ const data = this.preparePayload(response);
39162
+ if (client.cache) {
39163
+ ingestInCache(data, { cachedAt });
39164
+ }
39165
+ }
39166
+ appendToQueryStream(response, direction, refresh = false) {
39167
+ if (refresh) {
39168
+ pushToCache(this.cacheKey, {
39169
+ data: response.storyTargets.map(({ targetId }) => targetId),
39170
+ });
39171
+ }
39172
+ else {
39173
+ updateLocalList(this.cacheKey, response.storyTargets.map(({ targetId }) => targetId));
39174
+ }
39175
+ }
39176
+ reactor(actionType) {
39177
+ return (payload) => {
39178
+ if (actionType === "onCreate" /* Amity.StoryActionType.OnCreate */ &&
39179
+ this.query.seenState !== "seen" /* Amity.StorySeenQuery.SEEN */) {
39180
+ updateLocalList(this.cacheKey, payload.map(({ targetId }) => targetId));
39181
+ }
39182
+ this.notifyChange({ origin: "event" /* Amity.LiveDataOrigin.EVENT */, loading: false });
39183
+ };
39184
+ }
39185
+ subscribeRTE(createSubscriber) {
39186
+ return createSubscriber.map(subscriber => subscriber.fn(this.reactor(subscriber.action)));
39187
+ }
39188
+ }
39189
+
39190
+ const mergeResult = (resultA, resultB) => {
39191
+ return {
39192
+ categories: resultA.categories.concat(resultB.categories),
39193
+ communities: resultA.communities.concat(resultB.communities),
39194
+ communityUsers: resultA.communityUsers.concat(resultB.communityUsers),
39195
+ files: resultA.files.concat(resultB.files),
39196
+ storyTargets: resultA.storyTargets.concat(resultB.storyTargets),
39197
+ users: resultA.users.concat(resultB.users),
39198
+ paging: resultB.paging,
39199
+ };
39200
+ };
39201
+ const addFlagLocalFilter = (payload, filter) => {
39202
+ return Object.assign(Object.assign({}, payload), { storyTargets: payload.storyTargets.map(item => (Object.assign(Object.assign({}, item), { localFilter: filter }))) || [] });
39203
+ };
39204
+ class GlobalStoryPageController extends PaginationController {
39205
+ constructor() {
39206
+ super(...arguments);
39207
+ this.smartFilterState = "unseen" /* Amity.StorySeenQuery.UNSEEN */;
39208
+ }
39209
+ async getRequest(queryParams, token) {
39210
+ var _a;
39211
+ // Apply default values for parameters
39212
+ const { limit = 10, seenState = "unseen" /* Amity.StorySeenQuery.UNSEEN */ } = queryParams;
39213
+ const result = await this.createRequest({
39214
+ seenState: seenState === "smart" /* Amity.StorySeenQuery.SMART */ ? this.smartFilterState : seenState,
39215
+ limit,
39216
+ token,
39217
+ });
39218
+ // Use Early return to reduce condition complexity
39219
+ if ((_a = result.paging) === null || _a === void 0 ? void 0 : _a.next)
39220
+ return result;
39221
+ if (seenState !== "smart" /* Amity.StorySeenQuery.SMART */)
39222
+ return result;
39223
+ if (this.smartFilterState === "seen" /* Amity.StorySeenQuery.SEEN */)
39224
+ return result;
39225
+ this.smartFilterState = "seen" /* Amity.StorySeenQuery.SEEN */;
39226
+ const additionalResult = await this.createRequest({
39227
+ seenState: this.smartFilterState,
39228
+ limit,
39229
+ });
39230
+ return mergeResult(result, additionalResult);
39231
+ }
39232
+ async createRequest(params) {
39233
+ const { data: queryResponse } = await this.http.get('/api/v5/me/global-story-targets', {
39234
+ params,
39235
+ });
39236
+ return addFlagLocalFilter(queryResponse, params.seenState);
39237
+ }
39238
+ }
39239
+
39240
+ class GlobalStoryLiveCollectionController extends LiveCollectionController {
39241
+ constructor(query, callback) {
39242
+ const queryStreamId = hash(query);
39243
+ const cacheKey = ["story-global-feed" /* STORY_KEY_CACHE.STORY_GLOBAL_FEED */, 'collection', queryStreamId];
39244
+ const paginationController = new GlobalStoryPageController(query);
39245
+ super(paginationController, queryStreamId, cacheKey, callback);
39246
+ this.query = query;
39247
+ this.queryStreamController = new GlobalStoryQueryStreamController(this.query, this.cacheKey, this.notifyChange.bind(this), paginationController);
39248
+ this.paginationController = paginationController;
39249
+ this.callback = callback.bind(this);
39250
+ this.loadPage(true);
39251
+ }
39252
+ setup() {
39253
+ var _a;
39254
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39255
+ if (!collection) {
39256
+ pushToCache(this.cacheKey, {
39257
+ data: [],
39258
+ params: {},
39259
+ });
39260
+ }
39261
+ }
39262
+ persistModel(response) {
39263
+ this.queryStreamController.saveToMainDB(response);
39264
+ }
39265
+ persistQueryStream({ response, direction, refresh, }) {
39266
+ this.queryStreamController.appendToQueryStream(response, direction, refresh);
39267
+ }
39268
+ notifyChange({ origin, loading, error }) {
39269
+ var _a;
39270
+ const collection = (_a = pullFromCache(this.cacheKey)) === null || _a === void 0 ? void 0 : _a.data;
39271
+ if (!collection)
39272
+ return;
39273
+ let data = collection.data
39274
+ .map(targetId => pullFromCache(["storyTarget" /* STORY_KEY_CACHE.STORY_TARGET */, 'get', targetId]))
39275
+ .filter(Boolean)
39276
+ .map(storyTarget => LinkedObject.storyTarget(storyTarget.data));
39277
+ if (!this.shouldNotify(data) && origin === 'event')
39278
+ return;
39279
+ data = this.applyFilter(data);
39280
+ this.callback({
39281
+ onNextPage: () => this.loadPage(false, "next" /* Amity.LiveCollectionPageDirection.NEXT */),
39282
+ data,
39283
+ hasNextPage: !!this.paginationController.getNextToken(),
39284
+ loading,
39285
+ error,
39286
+ });
39287
+ }
39288
+ applyFilter(data) {
39289
+ if (this.query.seenState !== "smart" /* Amity.StorySeenQuery.SMART */) {
39290
+ return data
39291
+ .filter(({ hasUnseen }) => {
39292
+ if (this.query.seenState === "all" /* Amity.StorySeenQuery.ALL */)
39293
+ return true;
39294
+ if (this.query.seenState === "seen" /* Amity.StorySeenQuery.SEEN */ && !hasUnseen)
39295
+ return true;
39296
+ return this.query.seenState === "unseen" /* Amity.StorySeenQuery.UNSEEN */ && hasUnseen;
39297
+ })
39298
+ .sort(sortByLocalSortingDate);
39299
+ }
39300
+ // Smart Filter - Apply local sorting on each list of data
39301
+ const result = data.reduce((acc, storyTarget) => {
39302
+ if (storyTarget.localFilter === "unseen" /* Amity.StorySeenQuery.UNSEEN */) {
39303
+ acc.unseen.push(storyTarget);
39304
+ }
39305
+ else if (storyTarget.localFilter === "seen" /* Amity.StorySeenQuery.SEEN */) {
39306
+ acc.seen.push(storyTarget);
39307
+ }
39308
+ else {
39309
+ acc.unknown.push(storyTarget);
39310
+ }
39311
+ return acc;
39312
+ }, { unseen: [], seen: [], unknown: [] });
39313
+ const sortedUnknown = result.unknown.sort(sortByLocalSortingDate) || [];
39314
+ const sortedUnseen = result.unseen.sort(sortByLocalSortingDate) || [];
39315
+ const sortedSeen = result.seen.sort(sortByLocalSortingDate) || [];
39316
+ // Merge all status and remove internal fields
39317
+ return sortedUnknown
39318
+ .concat(sortedUnseen, sortedSeen)
39319
+ .map((_a) => {
39320
+ var rest = __rest(_a, ["localFilter", "localLastExpires", "localLastSeen", "localSortingDate"]);
39321
+ return rest;
39322
+ });
39323
+ }
39324
+ startSubscription() {
39325
+ return this.queryStreamController.subscribeRTE([
39326
+ { fn: onStoryCreated, action: "onCreate" /* Amity.StoryActionType.OnCreate */ },
39327
+ { fn: onStoryUpdated, action: "onUpdate" /* Amity.StoryActionType.OnUpdate */ },
39328
+ { fn: onStoryDeleted, action: "onDelete" /* Amity.StoryActionType.OnDelete */ },
39329
+ { fn: onStoryCreatedLocal, action: "onCreate" /* Amity.StoryActionType.OnCreate */ },
39330
+ { fn: onStoryUpdatedLocal, action: "onUpdate" /* Amity.StoryActionType.OnUpdate */ },
39331
+ { fn: onStoryDeletedLocal, action: "onDelete" /* Amity.StoryActionType.OnDelete */ },
39332
+ { fn: onStoryError, action: "onError" /* Amity.StoryActionType.OnError */ },
39333
+ ]);
39334
+ }
39335
+ }
39336
+
39337
+ const getGlobalStoryTargets = (params, callback, config) => {
39338
+ const { log, cache, userId } = getActiveClient();
39339
+ if (!cache) {
39340
+ console.log(ENABLE_CACHE_MESSAGE);
39341
+ }
39342
+ const timestamp = Date.now();
39343
+ log(`getGlobalStoryTarget(tmpid: ${timestamp}) > listen`);
39344
+ const storyLiveCollection = new GlobalStoryLiveCollectionController(params, callback);
39345
+ const disposers = storyLiveCollection.startSubscription();
39346
+ const cacheKey = storyLiveCollection.getCacheKey();
39347
+ disposers.push(() => {
39348
+ dropFromCache(cacheKey);
39349
+ });
39350
+ return () => {
39351
+ log(`getGlobalStoryTarget(tmpid: ${timestamp}) > dispose`);
39352
+ disposers.forEach(fn => fn());
39353
+ };
39354
+ };
39355
+
39012
39356
  var index = /*#__PURE__*/Object.freeze({
39013
39357
  __proto__: null,
39014
39358
  createImageStory: createImageStory,
@@ -39019,7 +39363,8 @@ var index = /*#__PURE__*/Object.freeze({
39019
39363
  getStoryByStoryId: getStoryByStoryId,
39020
39364
  getTargetById: getTargetById,
39021
39365
  getTargetsByTargetIds: getTargetsByTargetIds,
39022
- getStoriesByTargetIds: getStoriesByTargetIds
39366
+ getStoriesByTargetIds: getStoriesByTargetIds,
39367
+ getGlobalStoryTargets: getGlobalStoryTargets
39023
39368
  });
39024
39369
 
39025
39370
  /**
@@ -39044,4 +39389,4 @@ const createUserToken = async (apiKey, apiRegion, params) => {
39044
39389
  return { accessToken: data.accessToken };
39045
39390
  };
39046
39391
 
39047
- export { API_REGIONS, index$7 as CategoryRepository, index$b as ChannelRepository, index$k as Client, index$4 as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$8 as CommunityRepository, ContentFeedType, DefaultCommunityPostSetting, index$6 as FeedRepository, index$h as FileRepository, FileType, index$1 as LiveStreamPlayer, MessageContentType, index$f as MessageRepository, index$2 as PollRepository, PostContentType, index$5 as PostRepository, index$g as ReactionRepository, index as StoryRepository, index$3 as StreamRepository, index$e as SubChannelRepository, SubscriptionLevels, index$i as UserRepository, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, backupCache, createQuery, createReport, createUserToken, deleteReport, disableCache, dropFromCache, enableCache, filterByChannelMembership, filterByCommunityMembership, filterByFeedType, filterByPostDataTypes, filterByPropEquality, filterByPropInclusion, filterByPropIntersection, filterBySearchTerm, filterByStringComparePartially, getChannelTopic, getCommentTopic, getCommunityStoriesTopic, getCommunityTopic, getMarkedMessageTopic, getMarkerUserFeedTopic, getMessageTopic, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPostTopic, getRole, getSmartFeedChannelTopic, getSmartFeedMessageTopic, getSmartFeedSubChannelTopic, getStoryTopic, getSubChannelTopic, getUserTopic, isAfterBefore, isAfterBeforeRaw, isCachable, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkip, mergeInCache, onChannelMarkerFetched, onFeedMarkerFetched, onFeedMarkerUpdated, onMessageMarked, onMessageMarkerFetched, onSubChannelMarkerFetched, onSubChannelMarkerUpdated, onUserMarkerFetched, onUserMarkerFetchedLegacy, pullFromCache, pushToCache, queryCache, queryOptions, queryRoles, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByFirstUpdated, sortByLastActivity, sortByLastCreated, sortByLastUpdated, sortByName, sortBySegmentNumber, subscribeTopic, toPage, toPageRaw, toToken, upsertInCache, wipeCache };
39392
+ export { API_REGIONS, index$7 as CategoryRepository, index$b as ChannelRepository, index$k as Client, index$4 as CommentRepository, CommunityPostSettingMaps, CommunityPostSettings, index$8 as CommunityRepository, ContentFeedType, DefaultCommunityPostSetting, index$6 as FeedRepository, index$h as FileRepository, FileType, index$1 as LiveStreamPlayer, MessageContentType, index$f as MessageRepository, index$2 as PollRepository, PostContentType, index$5 as PostRepository, index$g as ReactionRepository, index as StoryRepository, index$3 as StreamRepository, index$e as SubChannelRepository, SubscriptionLevels, index$i as UserRepository, VERSION, VideoResolution, VideoSize, VideoTranscodingStatus, backupCache, createQuery, createReport, createUserToken, deleteReport, disableCache, dropFromCache, enableCache, filterByChannelMembership, filterByCommunityMembership, filterByFeedType, filterByPostDataTypes, filterByPropEquality, filterByPropInclusion, filterByPropIntersection, filterBySearchTerm, filterByStringComparePartially, getChannelTopic, getCommentTopic, getCommunityStoriesTopic, getCommunityTopic, getMarkedMessageTopic, getMarkerUserFeedTopic, getMessageTopic, getMyFollowersTopic, getMyFollowingsTopic, getNetworkTopic, getPostTopic, getRole, getSmartFeedChannelTopic, getSmartFeedMessageTopic, getSmartFeedSubChannelTopic, getStoryTopic, getSubChannelTopic, getUserTopic, isAfterBefore, isAfterBeforeRaw, isCachable, isFetcher, isFresh, isLocal, isMutator, isOffline, isPaged, isReportedByMe, isSkip, mergeInCache, onChannelMarkerFetched, onFeedMarkerFetched, onFeedMarkerUpdated, onMessageMarked, onMessageMarkerFetched, onSubChannelMarkerFetched, onSubChannelMarkerUpdated, onUserMarkerFetched, onUserMarkerFetchedLegacy, pullFromCache, pushToCache, queryCache, queryOptions, queryRoles, restoreCache, runQuery, sortByChannelSegment, sortByDisplayName, sortByFirstCreated, sortByFirstUpdated, sortByLastActivity, sortByLastCreated, sortByLastUpdated, sortByLocalSortingDate, sortByName, sortBySegmentNumber, subscribeTopic, toPage, toPageRaw, toToken, upsertInCache, wipeCache };