@cometchat/chat-uikit-react-native 5.5.3 → 5.6.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 (100) hide show
  1. package/android/build.gradle +5 -0
  2. package/android/src/main/java/com/reactnativecometchatuikit/FileManager.java +78 -3
  3. package/android/src/main/java/com/reactnativecometchatuikit/RichTextEditorView.kt +47 -4
  4. package/android/src/main/java/com/reactnativecometchatuikit/SafeFileName.java +78 -0
  5. package/android/src/main/java/com/reactnativecometchatuikit/SoundPlayer.java +209 -119
  6. package/ios/CCLocalFileGuard.h +19 -0
  7. package/ios/CCLocalFileGuard.m +34 -0
  8. package/ios/FileManager.m +70 -6
  9. package/ios/RichTextEditorView.swift +96 -1
  10. package/ios/SoundPlayer.m +152 -6
  11. package/ios/VideoManager.m +1 -1
  12. package/package.json +18 -3
  13. package/react-native-cometchat-ui-kit.podspec +1 -1
  14. package/src/CometChatCompactMessageComposer/CometChatCompactMessageComposer.tsx +167 -79
  15. package/src/CometChatConversations/CometChatConversations.tsx +240 -117
  16. package/src/CometChatGroupMembers/CometChatGroupMembers.tsx +4 -0
  17. package/src/CometChatGroups/CometChatGroups.tsx +61 -52
  18. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +173 -85
  19. package/src/CometChatMessageHeader/CometChatMessageHeader.tsx +7 -3
  20. package/src/CometChatMessageHeader/listners.ts +76 -56
  21. package/src/CometChatMessageList/CometChatMessageList.tsx +1423 -205
  22. package/src/CometChatNotificationFeed/CometChatNotificationFeed.tsx +71 -7
  23. package/src/CometChatPinnedMessages/CometChatPinnedMessages.tsx +74 -2
  24. package/src/CometChatSavedMessages/CometChatSavedMessages.tsx +69 -4
  25. package/src/CometChatSearch/CometChatSearch.tsx +353 -101
  26. package/src/CometChatThreadHeader/CometChatThreadHeader.tsx +23 -1
  27. package/src/CometChatUsers/CometChatUsers.tsx +2 -0
  28. package/src/calls/CometChatCallButtons/CometChatCallButtons.tsx +19 -0
  29. package/src/extensions/LinkPreview/LinkPreviewBubble.tsx +48 -47
  30. package/src/extensions/Stickers/StickersExtensionDecorator.tsx +2 -0
  31. package/src/index.ts +6 -0
  32. package/src/shared/CometChatUiKit/CometChatUIKit.ts +85 -2
  33. package/src/shared/CometChatUiKit/UIKitSettings.ts +20 -0
  34. package/src/shared/events/CometChatUIEventHandler/Listener.ts +10 -0
  35. package/src/shared/events/index.ts +4 -0
  36. package/src/shared/events/offline.ts +28 -0
  37. package/src/shared/formatters/CometChatMentionsFormatter/CometChatMentionsFormatter.tsx +5 -3
  38. package/src/shared/framework/MessageDataSource.tsx +34 -14
  39. package/src/shared/index.ts +2 -0
  40. package/src/shared/offline/OfflineHub.ts +651 -0
  41. package/src/shared/offline/OfflineMediaBubble.tsx +49 -0
  42. package/src/shared/offline/OfflineViews.tsx +218 -0
  43. package/src/shared/offline/conversationPins.ts +137 -0
  44. package/src/shared/offline/conversations.ts +325 -0
  45. package/src/shared/offline/frameProbe.ts +24 -0
  46. package/src/shared/offline/gate.ts +94 -0
  47. package/src/shared/offline/groupActions.ts +81 -0
  48. package/src/shared/offline/identity.ts +162 -0
  49. package/src/shared/offline/index.ts +76 -0
  50. package/src/shared/offline/media.ts +247 -0
  51. package/src/shared/offline/notices.ts +90 -0
  52. package/src/shared/offline/reconcile.ts +296 -0
  53. package/src/shared/offline/searchOutcome.ts +62 -0
  54. package/src/shared/offline/send.ts +430 -0
  55. package/src/shared/offline/stateContract.ts +85 -0
  56. package/src/shared/offline/threadReplies.ts +125 -0
  57. package/src/shared/offline/twoPhase.ts +372 -0
  58. package/src/shared/offline/unsentActions.ts +168 -0
  59. package/src/shared/offline/useOfflineMediaUri.ts +87 -0
  60. package/src/shared/offline/useOfflineReconnect.ts +25 -0
  61. package/src/shared/offline/useOfflineSessionEnded.ts +22 -0
  62. package/src/shared/offline/useOfflineUploadTray.ts +76 -0
  63. package/src/shared/offline/usePresenceHidden.ts +33 -0
  64. package/src/shared/resources/CometChatLocalizeNew/resources/de/translation.json +24 -1
  65. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +24 -1
  66. package/src/shared/resources/CometChatLocalizeNew/resources/es/translation.json +24 -1
  67. package/src/shared/resources/CometChatLocalizeNew/resources/fr/translation.json +24 -1
  68. package/src/shared/resources/CometChatLocalizeNew/resources/hi/translation.json +24 -1
  69. package/src/shared/resources/CometChatLocalizeNew/resources/hu/translation.json +24 -1
  70. package/src/shared/resources/CometChatLocalizeNew/resources/it/translation.json +24 -1
  71. package/src/shared/resources/CometChatLocalizeNew/resources/ja/translation.json +24 -1
  72. package/src/shared/resources/CometChatLocalizeNew/resources/ko/translation.json +24 -1
  73. package/src/shared/resources/CometChatLocalizeNew/resources/lt/translation.json +24 -1
  74. package/src/shared/resources/CometChatLocalizeNew/resources/ms/translation.json +24 -1
  75. package/src/shared/resources/CometChatLocalizeNew/resources/nl/translation.json +24 -1
  76. package/src/shared/resources/CometChatLocalizeNew/resources/pt/translation.json +24 -1
  77. package/src/shared/resources/CometChatLocalizeNew/resources/ru/translation.json +24 -1
  78. package/src/shared/resources/CometChatLocalizeNew/resources/sv/translation.json +24 -1
  79. package/src/shared/resources/CometChatLocalizeNew/resources/tr/translation.json +24 -1
  80. package/src/shared/resources/CometChatLocalizeNew/resources/zh/translation.json +24 -1
  81. package/src/shared/resources/CometChatLocalizeNew/resources/zh-tw/translation.json +24 -1
  82. package/src/shared/services/UploadQueueService.ts +106 -1
  83. package/src/shared/utils/MessageReceiptUtils.ts +8 -0
  84. package/src/shared/utils/SavedMessagesHelper.ts +18 -1
  85. package/src/shared/utils/catchUpCursor.ts +36 -0
  86. package/src/shared/utils/failedMessageRetry.ts +73 -0
  87. package/src/shared/utils/messageIdentity.ts +38 -0
  88. package/src/shared/views/CometChatAttachmentViewer/CometChatAttachmentViewer.tsx +34 -5
  89. package/src/shared/views/CometChatAudiosBubble/CometChatAudiosBubble.tsx +10 -2
  90. package/src/shared/views/CometChatFileBubble/CometChatFileBubble.tsx +13 -27
  91. package/src/shared/views/CometChatFilesBubble/CometChatFilesBubble.tsx +60 -11
  92. package/src/shared/views/CometChatImagesBubble/CometChatImagesBubble.tsx +27 -2
  93. package/src/shared/views/CometChatList/CometChatList.tsx +468 -7
  94. package/src/shared/views/CometChatMediaViewer/CometChatMediaViewer.tsx +27 -5
  95. package/src/shared/views/CometChatMessageInput/CometChatMessageInput.tsx +1 -0
  96. package/src/shared/views/CometChatReactionList/CometChatReactionList.tsx +56 -10
  97. package/src/shared/views/CometChatStatusIndicator/CometChatStatusIndicator.tsx +4 -0
  98. package/src/shared/views/CometChatVideosBubble/CometChatVideosBubble.tsx +36 -2
  99. package/src/shared/views/CometChatVoiceNoteBubble/CometChatVoiceNoteBubble.tsx +24 -12
  100. package/src/theme/type.ts +17 -0
@@ -613,5 +613,28 @@
613
613
  "PIN_SAVE_MODERATION_PENDING": "Bu mesaj hâlâ kontrol ediliyor. Birazdan tekrar deneyin.",
614
614
  "PIN_SAVE_FEATURE_OFF": "Bu özellik bu uygulama için kullanılamıyor.",
615
615
  "PIN_SAVE_GENERIC_ERROR": "Bir şeyler yanlış gitti. Lütfen tekrar deneyin.",
616
- "MESSAGE_NO_LONGER_AVAILABLE": "Bu mesaj artık kullanılamıyor."
616
+ "MESSAGE_NO_LONGER_AVAILABLE": "Bu mesaj artık kullanılamıyor.",
617
+ "OFFLINE_MESSAGE_NOT_SENT_YET": "Henüz gönderilmedi",
618
+ "OFFLINE_MESSAGE_NOT_SENT_TAP_TO_RETRY": "Gönderilmedi. Yeniden denemek için dokunun",
619
+ "OFFLINE_UNSENT_MESSAGE_REMOVED": "Gönderilmemiş 1 mesaj kaldırıldı",
620
+ "OFFLINE_MESSAGES_NOT_SENT_ONE": "{count} mesaj gönderilmedi",
621
+ "OFFLINE_MESSAGES_NOT_SENT_OTHER": "{count} mesaj gönderilmedi",
622
+ "OFFLINE_UNSENT_MESSAGES_LOST_ONE": "Gönderilmemiş {count} mesaj kurtarılamadı",
623
+ "OFFLINE_UNSENT_MESSAGES_LOST_OTHER": "Gönderilmemiş {count} mesaj kurtarılamadı",
624
+ "OFFLINE_UNSENT_MESSAGES_MAYBE_LOST": "Bazı mesajlar gönderilmemiş olabilir",
625
+ "OFFLINE_QUEUE_FULL": "Gönderilmeyi bekleyen çok fazla mesaj var",
626
+ "OFFLINE_FILE_TOO_LARGE": "Dosya çevrimdışı göndermek için çok büyük",
627
+ "OFFLINE_CONNECT_TO_LOAD_MORE": "Daha fazlasını yüklemek için bağlanın",
628
+ "OFFLINE_CONNECT_TO_SEARCH": "Aramak için bağlanın",
629
+ "OFFLINE_CONNECT_TO_SEARCH_MESSAGES": "Aramak için bağlanın",
630
+ "OFFLINE_CONNECT_TO_SEARCH_SUBTITLE": "Arama için internet bağlantısı gerekir.",
631
+ "OFFLINE_CONNECT_TO_LOAD_USERS": "Kullanıcıları yüklemek için bağlanın",
632
+ "OFFLINE_CONNECT_TO_LOAD_GROUPS": "Grupları yüklemek için bağlanın",
633
+ "OFFLINE_CONNECT_TO_LOAD_CHATS": "Sohbetleri yüklemek için bağlanın",
634
+ "OFFLINE_CONNECT_TO_LOAD_MEMBERS": "Üyeleri yüklemek için bağlanın",
635
+ "OFFLINE_CONNECT_TO_LOAD_MESSAGES": "Mesajları yüklemek için bağlanın",
636
+ "OFFLINE_CONNECT_TO_LOAD_REACTIONS": "Tepkileri yüklemek için bağlanın",
637
+ "OFFLINE_CONNECT_TO_LOAD_NOTIFICATIONS": "Bildirimleri yüklemek için bağlanın",
638
+ "OFFLINE_MEDIA_AVAILABLE_WHEN_ONLINE": "Çevrimiçiyken kullanılabilir",
639
+ "OFFLINE_SEND_IN_FLIGHT": "Gönderiliyor… birazdan tekrar deneyin"
617
640
  }
@@ -613,5 +613,28 @@
613
613
  "PIN_SAVE_MODERATION_PENDING": "此消息仍在审核中。请稍后再试。",
614
614
  "PIN_SAVE_FEATURE_OFF": "此应用无法使用该功能。",
615
615
  "PIN_SAVE_GENERIC_ERROR": "出了点问题。请再试一次。",
616
- "MESSAGE_NO_LONGER_AVAILABLE": "此消息已不可用。"
616
+ "MESSAGE_NO_LONGER_AVAILABLE": "此消息已不可用。",
617
+ "OFFLINE_MESSAGE_NOT_SENT_YET": "尚未发送",
618
+ "OFFLINE_MESSAGE_NOT_SENT_TAP_TO_RETRY": "未发送。点按重试",
619
+ "OFFLINE_UNSENT_MESSAGE_REMOVED": "已移除 1 条未发送的消息",
620
+ "OFFLINE_MESSAGES_NOT_SENT_ONE": "{count} 条消息未发送",
621
+ "OFFLINE_MESSAGES_NOT_SENT_OTHER": "{count} 条消息未发送",
622
+ "OFFLINE_UNSENT_MESSAGES_LOST_ONE": "无法恢复 {count} 条未发送的消息",
623
+ "OFFLINE_UNSENT_MESSAGES_LOST_OTHER": "无法恢复 {count} 条未发送的消息",
624
+ "OFFLINE_UNSENT_MESSAGES_MAYBE_LOST": "部分消息可能未发送",
625
+ "OFFLINE_QUEUE_FULL": "等待发送的消息过多",
626
+ "OFFLINE_FILE_TOO_LARGE": "文件过大,无法离线发送",
627
+ "OFFLINE_CONNECT_TO_LOAD_MORE": "连接网络以加载更多",
628
+ "OFFLINE_CONNECT_TO_SEARCH": "连接网络以搜索",
629
+ "OFFLINE_CONNECT_TO_SEARCH_MESSAGES": "连接网络后搜索",
630
+ "OFFLINE_CONNECT_TO_SEARCH_SUBTITLE": "搜索需要网络连接。",
631
+ "OFFLINE_CONNECT_TO_LOAD_USERS": "连接网络以加载用户",
632
+ "OFFLINE_CONNECT_TO_LOAD_GROUPS": "连接网络以加载群组",
633
+ "OFFLINE_CONNECT_TO_LOAD_CHATS": "连接网络以加载聊天",
634
+ "OFFLINE_CONNECT_TO_LOAD_MEMBERS": "连接网络以加载成员",
635
+ "OFFLINE_CONNECT_TO_LOAD_MESSAGES": "连接网络以加载消息",
636
+ "OFFLINE_CONNECT_TO_LOAD_REACTIONS": "连接网络以加载回应",
637
+ "OFFLINE_CONNECT_TO_LOAD_NOTIFICATIONS": "连接网络以加载通知",
638
+ "OFFLINE_MEDIA_AVAILABLE_WHEN_ONLINE": "联网后可用",
639
+ "OFFLINE_SEND_IN_FLIGHT": "正在发送…请稍后再试"
617
640
  }
@@ -613,5 +613,28 @@
613
613
  "PIN_SAVE_MODERATION_PENDING": "此訊息仍在審核中。請稍後再試。",
614
614
  "PIN_SAVE_FEATURE_OFF": "此應用程式無法使用該功能。",
615
615
  "PIN_SAVE_GENERIC_ERROR": "出了什麼問題請再試一次。",
616
- "MESSAGE_NO_LONGER_AVAILABLE": "此訊息已無法使用。"
616
+ "MESSAGE_NO_LONGER_AVAILABLE": "此訊息已無法使用。",
617
+ "OFFLINE_MESSAGE_NOT_SENT_YET": "尚未傳送",
618
+ "OFFLINE_MESSAGE_NOT_SENT_TAP_TO_RETRY": "未傳送。點一下重試",
619
+ "OFFLINE_UNSENT_MESSAGE_REMOVED": "已移除 1 則未傳送的訊息",
620
+ "OFFLINE_MESSAGES_NOT_SENT_ONE": "{count} 則訊息未傳送",
621
+ "OFFLINE_MESSAGES_NOT_SENT_OTHER": "{count} 則訊息未傳送",
622
+ "OFFLINE_UNSENT_MESSAGES_LOST_ONE": "無法復原 {count} 則未傳送的訊息",
623
+ "OFFLINE_UNSENT_MESSAGES_LOST_OTHER": "無法復原 {count} 則未傳送的訊息",
624
+ "OFFLINE_UNSENT_MESSAGES_MAYBE_LOST": "部分訊息可能未傳送",
625
+ "OFFLINE_QUEUE_FULL": "等待傳送的訊息過多",
626
+ "OFFLINE_FILE_TOO_LARGE": "檔案過大,無法離線傳送",
627
+ "OFFLINE_CONNECT_TO_LOAD_MORE": "連線以載入更多",
628
+ "OFFLINE_CONNECT_TO_SEARCH": "連線以搜尋",
629
+ "OFFLINE_CONNECT_TO_SEARCH_MESSAGES": "連線後即可搜尋",
630
+ "OFFLINE_CONNECT_TO_SEARCH_SUBTITLE": "搜尋需要網路連線。",
631
+ "OFFLINE_CONNECT_TO_LOAD_USERS": "連線以載入使用者",
632
+ "OFFLINE_CONNECT_TO_LOAD_GROUPS": "連線以載入群組",
633
+ "OFFLINE_CONNECT_TO_LOAD_CHATS": "連線以載入聊天",
634
+ "OFFLINE_CONNECT_TO_LOAD_MEMBERS": "連線以載入成員",
635
+ "OFFLINE_CONNECT_TO_LOAD_MESSAGES": "連線以載入訊息",
636
+ "OFFLINE_CONNECT_TO_LOAD_REACTIONS": "連線以載入回應",
637
+ "OFFLINE_CONNECT_TO_LOAD_NOTIFICATIONS": "連線以載入通知",
638
+ "OFFLINE_MEDIA_AVAILABLE_WHEN_ONLINE": "連線後即可使用",
639
+ "OFFLINE_SEND_IN_FLIGHT": "正在傳送…請稍後再試"
617
640
  }
@@ -1,6 +1,7 @@
1
1
  import { CometChat } from '@cometchat/chat-sdk-react-native';
2
2
  import { SelectedAttachment } from '../modals/SelectedAttachment';
3
3
  import { linkUploadedVideo } from '../utils/videoThumbnail';
4
+ import { isOfflineOn, offlineSdk } from '../offline/gate';
4
5
 
5
6
  type CometChatException = InstanceType<typeof CometChat.CometChatException>;
6
7
 
@@ -24,6 +25,17 @@ export interface UploadBatchResult {
24
25
  rejected: { fileId: string; error: CometChatException }[];
25
26
  }
26
27
 
28
+ /** The destination of one batch: (receiver, type, thread parent) — the durable batch's identity. */
29
+ export interface UploadTarget {
30
+ receiver?: string;
31
+ receiverType?: string;
32
+ parentMessageId?: string | number;
33
+ }
34
+
35
+ function hasParent(parentMessageId: unknown): parentMessageId is string | number {
36
+ return parentMessageId !== undefined && parentMessageId !== null && parentMessageId !== '' && parentMessageId !== 0;
37
+ }
38
+
27
39
  export type UploadQueueCallbacks = {
28
40
  onProgress: (fileId: string, percent: number) => void;
29
41
  onFileComplete: (fileId: string, attachment: CometChat.Attachment) => void;
@@ -55,6 +67,11 @@ export class UploadQueueService {
55
67
  private completed = new Map<string, CometChat.Attachment>();
56
68
  // Local uri of each enqueued VIDEO, so its upload can be linked to a local thumbnail.
57
69
  private localVideoUris = new Map<string, string>();
70
+ // Offline ON only: files restored from the SDK's durable batch (BEH-UPLOAD-14). Their picker
71
+ // handles are gone, so a retry streams the SDK's own copy (`retryAttachment`).
72
+ private restoredIds = new Set<string>();
73
+ // Bumped on every detach / destroy so a restore that lands late is dropped.
74
+ private restoreToken = 0;
58
75
 
59
76
  // Kept for signature compatibility; the request API no longer exposes a presign buffer knob.
60
77
  constructor(callbacks: UploadQueueCallbacks, _opts?: { presignBufferMs?: number }) {
@@ -96,12 +113,17 @@ export class UploadQueueService {
96
113
  * composer's conversation refs at enqueue time; only the first enqueue creates the request (the batch
97
114
  * is fixed to one destination), later picks add to the same batch.
98
115
  */
99
- enqueue(attachment: SelectedAttachment, target?: { receiver?: string; receiverType?: string }): void {
116
+ enqueue(attachment: SelectedAttachment, target?: UploadTarget): void {
100
117
  const { fileId, file } = attachment;
101
118
  if (file.type?.startsWith('video/')) this.localVideoUris.set(fileId, file.uri);
102
119
  if (!this.request) {
103
120
  this.request = CometChat.createUploadFileRequest(target?.receiver ?? '', target?.receiverType ?? '');
104
121
  this.request.setConcurrency(UPLOAD_CONCURRENCY);
122
+ // Offline ON: the thread parent is part of the durable batch's identity, so a thread
123
+ // composer never adopts the main chat's batch (UIT-UP-02). Offline OFF: today's request.
124
+ if (hasParent(target?.parentMessageId) && isOfflineOn()) {
125
+ (this.request as any).setParentMessageId?.(target!.parentMessageId);
126
+ }
105
127
  }
106
128
  // Pass the tile id as the SDK fileId, and the per-call listener (deduped into the batch's listener
107
129
  // set) so this one listener drives every file's events + the whole-batch onComplete.
@@ -122,6 +144,11 @@ export class UploadQueueService {
122
144
  retry(tileId: string, file: SelectedAttachment): void {
123
145
  // DD §12/§13 — retry = re-upload the SAME fileId through the request (re-presigns if needed).
124
146
  this.completed.delete(tileId);
147
+ // A restored tile has no live file: the SDK streams its own copy (offline ON only).
148
+ if (this.restoredIds.has(tileId) && typeof (this.request as any)?.retryAttachment === 'function') {
149
+ (this.request as any).retryAttachment(tileId, this.listener);
150
+ return;
151
+ }
125
152
  this.request?.uploadAttachment(
126
153
  tileId,
127
154
  { uri: file.file.uri, name: file.file.name, type: file.file.type, size: file.file.size },
@@ -130,10 +157,88 @@ export class UploadQueueService {
130
157
  }
131
158
 
132
159
  cancelAll(): void {
160
+ this.restoreToken++;
133
161
  this.request?.clearAll();
134
162
  this.request = null;
135
163
  this.completed.clear();
136
164
  this.localVideoUris.clear();
165
+ this.restoredIds.clear();
166
+ }
167
+
168
+ /**
169
+ * Let go of the batch WITHOUT clearing it: the SDK keeps it (offline ON) so the tray can be
170
+ * restored when the user comes back to this chat. Nothing is aborted or deleted.
171
+ */
172
+ detach(): void {
173
+ this.restoreToken++;
174
+ this.request = null;
175
+ this.completed.clear();
176
+ this.localVideoUris.clear();
177
+ this.restoredIds.clear();
178
+ }
179
+
180
+ /**
181
+ * The composer leaves its (receiver, type, parent) triple — chat switch or unmount. The gate is
182
+ * read now: offline ON detaches (the batch survives for restore, BEH-UPLOAD-14); offline OFF
183
+ * destroys the batch exactly as today (`cancelAll`, UIT-OFF-08).
184
+ */
185
+ leave(): void {
186
+ if (isOfflineOn()) this.detach();
187
+ else this.cancelAll();
188
+ }
189
+
190
+ /**
191
+ * BEH-UPLOAD-14 restore, offline ON only: read back the durable batch of `target`
192
+ * (`getExistingUploadFileRequest`) and return the tray's tiles, keyed by the SDK fileId:
193
+ * `UPLOADED` → done, `REJECTED` → rejected, anything else → failed with retry. Nothing uploads
194
+ * as a result. Resolves `null` (and changes nothing) with offline off, on an SDK without the
195
+ * call, when there is no batch, when the tray already has a request (the user picked), or when
196
+ * the composer moved on before the answer.
197
+ */
198
+ async restore(target: UploadTarget): Promise<SelectedAttachment[] | null> {
199
+ if (this.request || !target?.receiver || !target?.receiverType || !isOfflineOn()) return null;
200
+ const sdk = offlineSdk();
201
+ if (typeof sdk?.getExistingUploadFileRequest !== 'function') return null;
202
+ const token = ++this.restoreToken;
203
+ let restored: any;
204
+ try {
205
+ restored = await sdk.getExistingUploadFileRequest(
206
+ target.receiver,
207
+ target.receiverType,
208
+ hasParent(target.parentMessageId) ? target.parentMessageId : undefined,
209
+ );
210
+ } catch {
211
+ return null;
212
+ }
213
+ if (!restored || token !== this.restoreToken || this.request) return null;
214
+ const read = typeof restored.getItems === 'function' ? restored.getItems : restored.getFiles;
215
+ const items: any[] = typeof read === 'function' ? read.call(restored) : [];
216
+ if (!Array.isArray(items) || items.length === 0) return null;
217
+ this.request = restored;
218
+ return items
219
+ .filter((item) => item && typeof item.fileId === 'string' && item.fileId)
220
+ .map((item) => {
221
+ const fileId: string = item.fileId;
222
+ this.restoredIds.add(fileId);
223
+ const state = String(item.state ?? '');
224
+ const attachment = item.attachment;
225
+ const file = {
226
+ uri: item.localCopyPath ?? item.localUri ?? attachment?.getUrl?.() ?? '',
227
+ name: item.name ?? attachment?.getName?.() ?? '',
228
+ type: item.mimeType ?? attachment?.getMimeType?.() ?? '',
229
+ size: Number(item.size ?? attachment?.getSize?.() ?? 0) || 0,
230
+ };
231
+ if (state === 'UPLOADED' && attachment) {
232
+ this.completed.set(fileId, attachment);
233
+ return { fileId, file, uploadState: 'COMPLETED', uploadProgress: 100, uploadedAttachment: attachment } as SelectedAttachment;
234
+ }
235
+ if (state === 'REJECTED') {
236
+ const code = item.error?.code ?? item.error?.getCode?.();
237
+ return { fileId, file, uploadState: 'REJECTED', uploadProgress: 0, errorKey: 'ATTACHMENT_UPLOAD_UNAVAILABLE', errorCode: code, rawError: item.error } as SelectedAttachment;
238
+ }
239
+ // FAILED, or a file still in flight when the app died: retryable, never resumed by itself.
240
+ return { fileId, file, uploadState: 'FAILED', uploadProgress: 0, errorKey: 'UPLOAD_FAILED', rawError: item.error } as SelectedAttachment;
241
+ });
137
242
  }
138
243
 
139
244
  get completedAttachments(): CometChat.Attachment[] {
@@ -1,6 +1,8 @@
1
1
  import { MessageReceipt } from "../constants/UIKitConstants";
2
2
  import { CometChat } from "@cometchat/chat-sdk-react-native";
3
3
  import { getModerationStatus } from "./MessageUtils";
4
+ import { isOfflineUnsent, isOutboxFailed } from "../offline/identity";
5
+ import { OfflineHub } from "../offline/OfflineHub";
4
6
 
5
7
  /**
6
8
  * Utility helper for deriving a message receipt status from a BaseMessage instance.
@@ -9,6 +11,12 @@ export const MessageReceiptUtils = {
9
11
  getReceiptStatus(message: CometChat.BaseMessage | undefined): MessageReceipt {
10
12
  if (!message) return MessageReceipt.WAIT;
11
13
 
14
+ // Offline: an own unsent message shows the clock or the failed mark, never a receipt
15
+ // (BEH-SEND-32). Only the offline SDK produces such messages.
16
+ const directFailure = OfflineHub.getInstance().directFailureOf(message) !== undefined;
17
+ if (directFailure || isOutboxFailed(message)) return MessageReceipt.ERROR;
18
+ if (isOfflineUnsent(message)) return MessageReceipt.WAIT;
19
+
12
20
  // Moderation status (if available)
13
21
  const moderationStatus = getModerationStatus(message);
14
22
  if (moderationStatus === "disapproved") return MessageReceipt.ERROR;
@@ -216,7 +216,24 @@ export const sourceLabelFor = (
216
216
  };
217
217
 
218
218
  /**
219
- * A fresh request for the logged-in user's saved messages, newest save first.
219
+ * The Saved list's order: newest message first, by when it was *sent*, as the React UI Kit
220
+ * does (`sentAtDesc` in its saved-messages reducer). Pages arrive in the request's own order
221
+ * (oldest first within a page) and a later page can hold a message newer than anything
222
+ * already shown, so the order is re-established on every merge. Ties break on id so equal
223
+ * timestamps don't shuffle between renders. Guarded: a row from an event is not guaranteed
224
+ * to be a fully hydrated SDK instance, and an ordering helper must never throw.
225
+ */
226
+ export const sentAtDesc = (a: CometChat.BaseMessage, b: CometChat.BaseMessage): number => {
227
+ const at = typeof a?.getSentAt === "function" ? Number(a.getSentAt()) || 0 : 0;
228
+ const bt = typeof b?.getSentAt === "function" ? Number(b.getSentAt()) || 0 : 0;
229
+ if (bt !== at) return bt - at;
230
+ const aid = typeof a?.getId === "function" ? Number(a.getId()) || 0 : 0;
231
+ const bid = typeof b?.getId === "function" ? Number(b.getId()) || 0 : 0;
232
+ return bid - aid;
233
+ };
234
+
235
+ /**
236
+ * A fresh request for the logged-in user's saved messages, newest message first by send time.
220
237
  *
221
238
  * The ordinary messages request, filtered to saved rows. Deliberately carries NO
222
239
  * uid/guid: `saved=1` is account-wide, and scoping it to a conversation would turn
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Reconnect catch-up paging for the message list (plan D3).
3
+ *
4
+ * `getNewMessages` fetched forward from `lastID` and recursed only when a page held exactly 30
5
+ * messages, without ever moving the cursor: a full page re-fetched the same page forever, and a
6
+ * request with a different limit never paged at all. The next page now starts after the newest
7
+ * server id of the page just fetched, and paging stops on a page shorter than the request's own
8
+ * limit (or one that did not move the cursor).
9
+ */
10
+
11
+ function numericId(message: any): number {
12
+ const raw = typeof message?.getId === "function" ? message.getId() : message?.id;
13
+ const id = typeof raw === "string" ? parseInt(raw, 10) : Number(raw);
14
+ return Number.isFinite(id) && id > 0 ? id : 0;
15
+ }
16
+
17
+ /** Newest server id in `messages` (0 when none has one). */
18
+ export function newestServerIdIn(messages: readonly any[] | null | undefined): number {
19
+ let newest = 0;
20
+ for (const message of messages ?? []) newest = Math.max(newest, numericId(message));
21
+ return newest;
22
+ }
23
+
24
+ /**
25
+ * The cursor for the next catch-up page, or `null` when catch-up is complete.
26
+ * @param page the page just fetched (any order)
27
+ * @param cursor the message id that page was fetched after
28
+ * @param limit the request's own page size
29
+ */
30
+ export function nextCatchUpCursor(page: readonly any[] | null | undefined, cursor: number, limit: number): number | null {
31
+ const size = page?.length ?? 0;
32
+ const pageLimit = Number(limit) > 0 ? Number(limit) : 30;
33
+ if (size < pageLimit) return null;
34
+ const newest = newestServerIdIn(page);
35
+ return newest > (Number(cursor) || 0) ? newest : null;
36
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Retry of a failed own message on the offline-OFF path (plan D1).
3
+ *
4
+ * The bubble's "Retry" used to call a media-only resend that returned early for text and custom
5
+ * messages, so tapping Retry on a failed text did nothing. It also showed on moderation-
6
+ * disapproved rows (which have a server id and must not be re-sent) and re-sent them if media.
7
+ *
8
+ * Rules: Retry is offered only for a row the server never accepted (no server id) that was not
9
+ * rejected by moderation. It clears the kit's error marks and re-sends through the same public
10
+ * `CometChatUIKit.send*` path a first send uses, which re-emits ccMessageSent
11
+ * inprogress -> success/error; the list reconciles by muid in place.
12
+ */
13
+
14
+ export interface FailedMessageSenders {
15
+ sendText(message: any): Promise<unknown>;
16
+ sendMedia(message: any): Promise<unknown>;
17
+ sendCustom(message: any): Promise<unknown>;
18
+ }
19
+
20
+ function serverId(message: any): unknown {
21
+ return typeof message?.getId === "function" ? message.getId() : message?.id;
22
+ }
23
+
24
+ /** Whether the failed row may offer Retry (no server id, not rejected by moderation). */
25
+ export function isRetryableFailedRow(message: any, moderationStatus?: string): boolean {
26
+ if (!message) return false;
27
+ if (moderationStatus === "disapproved") return false;
28
+ const id = serverId(message);
29
+ return id === undefined || id === null || id === "" || id === 0 || id === "0";
30
+ }
31
+
32
+ /** Remove the error marks the send paths stamp (data.metaData.error, metadata.error, .error). */
33
+ export function clearSendErrorMarks(message: any): void {
34
+ const data: any = message?.getData?.() || {};
35
+ if (data?.metaData?.error) {
36
+ delete data.metaData.error;
37
+ message?.setData?.(data);
38
+ }
39
+ const metadata: any = message?.getMetadata?.();
40
+ if (metadata?.error) {
41
+ delete metadata.error;
42
+ message?.setMetadata?.(metadata);
43
+ }
44
+ if (message && "error" in message) message.error = undefined;
45
+ }
46
+
47
+ /** Which send a message goes through: "media", "custom" or "text"; `null` for anything else. */
48
+ export function resendKindOf(message: any): "text" | "media" | "custom" | null {
49
+ const category = message?.getCategory?.();
50
+ const type = message?.getType?.();
51
+ if (category === "custom") return "custom";
52
+ if (category === "message") {
53
+ if (type === "text") return "text";
54
+ if (type === "image" || type === "video" || type === "audio" || type === "file") return "media";
55
+ }
56
+ return null;
57
+ }
58
+
59
+ /** Re-send a failed row. Returns false when the row may not be retried. Never throws. */
60
+ export function resendFailedMessage(message: any, senders: FailedMessageSenders, moderationStatus?: string): boolean {
61
+ try {
62
+ if (!isRetryableFailedRow(message, moderationStatus)) return false;
63
+ const kind = resendKindOf(message);
64
+ if (!kind) return false;
65
+ clearSendErrorMarks(message);
66
+ const send = kind === "media" ? senders.sendMedia : kind === "custom" ? senders.sendCustom : senders.sendText;
67
+ // On failure the send path re-applies the error mark and emits ccMessageSent(error).
68
+ send(message).catch(() => {});
69
+ return true;
70
+ } catch {
71
+ return false;
72
+ }
73
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Null-safe identity checks for the message list's replace-in-place paths (plan D2).
3
+ *
4
+ * The list used to match `msg.getId() == edited.getId()` and `msg["muid"] == edited["muid"]`
5
+ * directly, so a message with no id (an unsent row) matched the first other row with no id
6
+ * (`undefined == undefined`), and a message with no muid matched any row without one. Two
7
+ * missing identities are never the same message.
8
+ */
9
+
10
+ function present(value: unknown): value is string | number {
11
+ return value !== undefined && value !== null && value !== "" && value !== 0 && value !== "0";
12
+ }
13
+
14
+ function idOf(message: any): unknown {
15
+ if (!message) return undefined;
16
+ return typeof message.getId === "function" ? message.getId() : message.id;
17
+ }
18
+
19
+ function muidOf(message: any): unknown {
20
+ if (!message) return undefined;
21
+ return message["muid"] ?? (typeof message.getMuid === "function" ? message.getMuid() : undefined);
22
+ }
23
+
24
+ /** Same server id, and both actually have one. Loose compare: ids arrive as numbers or strings. */
25
+ export function sameMessageById(a: any, b: any): boolean {
26
+ const left = idOf(a);
27
+ const right = idOf(b);
28
+ // eslint-disable-next-line eqeqeq
29
+ return present(left) && present(right) && left == right;
30
+ }
31
+
32
+ /** Same muid, and both actually have one. */
33
+ export function sameMessageByMuid(a: any, b: any): boolean {
34
+ const left = muidOf(a);
35
+ const right = muidOf(b);
36
+ // eslint-disable-next-line eqeqeq
37
+ return present(left) && present(right) && left == right;
38
+ }
@@ -13,6 +13,10 @@ import {
13
13
  } from 'react-native';
14
14
  import { CometChat } from '@cometchat/chat-sdk-react-native';
15
15
  import { Icon } from '../../icons/Icon';
16
+ import { useMediaOutOfReach, useOfflineMediaUri } from '../../offline/useOfflineMediaUri';
17
+ import { mediaActionSource, notifyMediaUnavailable } from '../../offline/media';
18
+ import { MediaOutOfReachLabel } from '../../offline/OfflineViews';
19
+ import { useCometChatTranslation } from '../../resources/CometChatLocalizeNew';
16
20
 
17
21
  export interface CometChatAttachmentViewerProps {
18
22
  attachments: CometChat.Attachment[];
@@ -23,7 +27,7 @@ export interface CometChatAttachmentViewerProps {
23
27
  visible?: boolean;
24
28
  }
25
29
 
26
- type DownloadState = 'IDLE' | 'DOWNLOADING' | 'DONE' | 'FAILED';
30
+ type DownloadState = 'IDLE' | 'DOWNLOADING' | 'DONE' | 'FAILED' | 'OUT_OF_REACH';
27
31
 
28
32
  const { FileManager } = NativeModules;
29
33
 
@@ -54,6 +58,11 @@ export const CometChatAttachmentViewer = ({
54
58
  const [downloadState, setDownloadState] = useState<DownloadState>('IDLE');
55
59
 
56
60
  const current = attachments[currentIndex];
61
+ const { t } = useCometChatTranslation();
62
+ // Offline ON: the saved file for display, download and Share; the URL as today otherwise.
63
+ const currentUri = useOfflineMediaUri(current);
64
+ const outOfReachRaw = useMediaOutOfReach(current);
65
+ const outOfReach = !!current && outOfReachRaw;
57
66
  const senderName = message.getSender?.()?.getName?.() ?? '';
58
67
  const sentAtStr = message.getSentAt ? formatSentAt(message.getSentAt()) : '';
59
68
 
@@ -77,8 +86,15 @@ export const CometChatAttachmentViewer = ({
77
86
 
78
87
  const handleDownload = () => {
79
88
  if (downloadState === 'DOWNLOADING' || downloadState === 'DONE') return;
89
+ const source = mediaActionSource(current);
90
+ if (source.kind === 'unavailable') {
91
+ // Say so, as Share does: without the notice the Download button looks like it does nothing.
92
+ setDownloadState('OUT_OF_REACH');
93
+ notifyMediaUnavailable();
94
+ return;
95
+ }
80
96
  setDownloadState('DOWNLOADING');
81
- const url = current.getUrl();
97
+ const url = source.uri;
82
98
  const name = current.getName();
83
99
  FileManager?.checkAndDownload(url, name, (result: string) => {
84
100
  try {
@@ -96,7 +112,13 @@ export const CometChatAttachmentViewer = ({
96
112
 
97
113
  const handleShare = async () => {
98
114
  try {
99
- await Share.share({ url: current.getUrl(), message: current.getName() });
115
+ const source = mediaActionSource(current);
116
+ if (source.kind === 'unavailable') {
117
+ setDownloadState('OUT_OF_REACH');
118
+ notifyMediaUnavailable();
119
+ return;
120
+ }
121
+ await Share.share({ url: source.uri, message: current.getName() });
100
122
  } catch {
101
123
  // share cancelled
102
124
  }
@@ -167,15 +189,22 @@ export const CometChatAttachmentViewer = ({
167
189
 
168
190
  {/* Media area */}
169
191
  <View style={styles.mediaArea} {...panResponder.panHandlers}>
170
- {!imageLoaded && (
192
+ {/* Out of reach, the image never loads, so the spinner would run under the label for
193
+ ever. Same rule as CometChatMediaViewer (line 231). */}
194
+ {!imageLoaded && !outOfReach && (
171
195
  <ActivityIndicator
172
196
  color="#fff"
173
197
  size="large"
174
198
  style={StyleSheet.absoluteFill}
175
199
  />
176
200
  )}
201
+ {outOfReach ? (
202
+ <View style={[StyleSheet.absoluteFill, { justifyContent: 'center', alignItems: 'center' }]}>
203
+ <MediaOutOfReachLabel t={t} textStyle={{ color: 'rgba(255,255,255,0.8)', fontSize: 14 }} />
204
+ </View>
205
+ ) : null}
177
206
  <Image
178
- source={{ uri: current.getUrl() }}
207
+ source={{ uri: currentUri }}
179
208
  style={styles.image}
180
209
  resizeMode="contain"
181
210
  onLoad={() => setImageLoaded(true)}
@@ -1,4 +1,7 @@
1
1
  import React, { useEffect, useMemo, useRef, useState } from 'react';
2
+ import { useOfflineMediaUri } from '../../offline/useOfflineMediaUri';
3
+ import { isMediaOutOfReach, requestMediaDownload } from '../../offline/media';
4
+ import { MediaOutOfReachNote } from '../../offline/OfflineMediaBubble';
2
5
  import {
3
6
  GestureResponderEvent,
4
7
  ImageStyle,
@@ -80,7 +83,8 @@ const AudioFilePlayer = ({
80
83
  timeTextStyle,
81
84
  downloadIconStyle,
82
85
  }: AudioFilePlayerProps) => {
83
- const url = attachment.getUrl();
86
+ // Offline ON: play the SDK's cached copy (with an extension AVFoundation accepts); else the URL.
87
+ const url = useOfflineMediaUri(attachment, { playable: true });
84
88
  // Dimension tokens (theme spacing): CIRCLE 56 = s14, THUMB 12 = s3, TRACK_H = s2 (8) — a proper
85
89
  // seek-bar thickness (s1/4 read as a thin hairline). No raw pixel literals — everything derives
86
90
  // from the theme scale.
@@ -201,6 +205,9 @@ const AudioFilePlayer = ({
201
205
  };
202
206
 
203
207
  const togglePlay = () => {
208
+ // Offline ON: no copy and no connection, so nothing to play; online, the SDK caches one too.
209
+ if (isMediaOutOfReach(attachment)) return;
210
+ requestMediaDownload(attachment);
204
211
  if (status === 'playing') {
205
212
  // User pause — the native player is still ours, so a plain resume works later.
206
213
  wasInterruptedRef.current = false;
@@ -275,7 +282,7 @@ const AudioFilePlayer = ({
275
282
  // Reuse the same native download path as the file/media bubbles.
276
283
  const download = () => {
277
284
  if (!url) return;
278
- FileManager?.checkAndDownload?.(url, attachment.getName(), () => {});
285
+ FileManager?.checkAndDownload?.(attachment.getUrl() ?? url, attachment.getName(), () => {});
279
286
  };
280
287
 
281
288
  // All colors are theme tokens (no hardcoded literals). Sent = purple bubble, received = neutral.
@@ -333,6 +340,7 @@ const AudioFilePlayer = ({
333
340
  >
334
341
  {attachment.getName()}
335
342
  </Text>
343
+ <MediaOutOfReachNote attachment={attachment} color={timeColor} />
336
344
 
337
345
  {/* Seek track (draggable) with the download button on its right — design §8.1a */}
338
346
  <View style={{ flexDirection: 'row', alignItems: 'center', gap: S.s2, marginTop: S.s0_5 }}>
@@ -6,8 +6,6 @@ import {
6
6
  ImageStyle,
7
7
  NativeEventEmitter,
8
8
  NativeModules,
9
- NativeSyntheticEvent,
10
- NativeTouchEvent,
11
9
  Platform,
12
10
  Text,
13
11
  TextStyle,
@@ -127,6 +125,15 @@ export const CometChatFileBubble = ({
127
125
  }
128
126
  } else {
129
127
  if (downloadAndOpenFile) {
128
+ if (Platform.OS == "ios") {
129
+ // native openFile downloads without the share sheet that checkAndDownload shows
130
+ setProcessing(true);
131
+ FileManager.openFile(fileUrl, fileName, (result: string) => {
132
+ setProcessing(false);
133
+ if (JSON.parse(result).success == true) setFileExists(true);
134
+ });
135
+ return;
136
+ }
130
137
  openFileAfterDownloading.current = true;
131
138
  downloadFile();
132
139
  }
@@ -135,7 +142,7 @@ export const CometChatFileBubble = ({
135
142
  };
136
143
 
137
144
  /**
138
- * Initiates the file download if it is not already processed or exists.
145
+ * Starts an Android DownloadManager download if not already processing or downloaded.
139
146
  */
140
147
  const downloadFile = () => {
141
148
  if (processing || fileExists) return; // Do not process if file already exists
@@ -144,19 +151,9 @@ export const CometChatFileBubble = ({
144
151
 
145
152
  setProcessing(true);
146
153
  FileManager.checkAndDownload(fileUrl, getFileName(), (result: string) => {
147
- if (Platform.OS == "ios") {
148
- let parsedResult = JSON.parse(result);
149
- if (parsedResult.success == true) {
150
- setProcessing(false);
151
- setFileExists(true);
152
- }
153
- if (openFileAfterDownloading.current) {
154
- openFile();
155
- openFileAfterDownloading.current = false;
156
- }
157
- } else if (Platform.OS == "android") {
158
- downloadIdRef.current = JSON.parse(result).downloadId;
159
- }
154
+ // Android only (iOS downloads through openFile in checkFileExists); the
155
+ // downloadComplete listener opens the file once this downloadId finishes.
156
+ downloadIdRef.current = JSON.parse(result).downloadId;
160
157
  });
161
158
  };
162
159
 
@@ -224,17 +221,6 @@ export const CometChatFileBubble = ({
224
221
  : {};
225
222
  }, []);
226
223
 
227
- /**
228
- * Handler to download the file when the download icon is pressed.
229
- *
230
- * @param {NativeSyntheticEvent<NativeTouchEvent>} e - The touch event.
231
- */
232
- const shouldDownload = (e: NativeSyntheticEvent<NativeTouchEvent>) => {
233
- e.stopPropagation();
234
- setProcessing(true);
235
- downloadFile();
236
- };
237
-
238
224
  return (
239
225
  <View {...viewProps} style={{ flexDirection: "row", gap: 8 }}>
240
226
  <View {...viewPropsForAndroid} style={{ height: 32, width: 32 }}>