@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
@@ -1,8 +1,16 @@
1
1
  package com.reactnativecometchatuikit;
2
2
 
3
- import android.media.AudioManager;
4
3
  import android.media.MediaPlayer;
5
4
  import android.net.Uri;
5
+ import android.os.Handler;
6
+ import android.os.HandlerThread;
7
+
8
+ import androidx.media3.common.AudioAttributes;
9
+ import androidx.media3.common.C;
10
+ import androidx.media3.common.MediaItem;
11
+ import androidx.media3.common.PlaybackException;
12
+ import androidx.media3.common.Player;
13
+ import androidx.media3.exoplayer.ExoPlayer;
6
14
 
7
15
  import androidx.annotation.NonNull;
8
16
 
@@ -17,7 +25,15 @@ import com.facebook.react.modules.core.DeviceEventManagerModule;
17
25
  import org.json.JSONException;
18
26
  import org.json.JSONObject;
19
27
 
28
+ import java.io.ByteArrayOutputStream;
20
29
  import java.io.IOException;
30
+ import java.io.InputStream;
31
+ import java.net.URL;
32
+ import java.net.URLConnection;
33
+ import java.util.Map;
34
+ import java.util.concurrent.ConcurrentHashMap;
35
+ import java.util.concurrent.ExecutorService;
36
+ import java.util.concurrent.Executors;
21
37
 
22
38
  // NOTE: every MediaPlayer call below is wrapped so a bad player state can never crash the RN app.
23
39
  // The player is a single shared instance (WhatsApp-style, one clip at a time), so with several audio
@@ -26,12 +42,8 @@ import java.io.IOException;
26
42
  // (or NPE when null) for a method invoked in the wrong state — those are RuntimeExceptions that would
27
43
  // otherwise red-screen. We catch broadly and degrade gracefully (no-op / report an error) instead.
28
44
  public class SoundPlayer extends ReactContextBaseJavaModule {
29
- MediaPlayer mediaPlayer = null;
30
- JSONObject obj = new JSONObject();
31
45
  public static final String MODULE_NAME = "SoundPlayer";
32
46
  public static final String EVENT_NAME = "soundPlayStatus";
33
- private static String currentUrl = "";
34
- private static String prevUrl = "";
35
47
  DeviceEventManagerModule.RCTDeviceEventEmitter eventEmitter = null;
36
48
 
37
49
  SoundPlayer(ReactApplicationContext context) {
@@ -45,159 +57,237 @@ public class SoundPlayer extends ReactContextBaseJavaModule {
45
57
  eventEmitter.emit(EVENT_NAME, params);
46
58
  }
47
59
 
48
- @ReactMethod
49
- public void prepareMediaPlayer(String url, Callback resolve) {
50
- if (mediaPlayer == null)
51
- eventEmitter = getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class);
60
+ // Seconds. Browser-recorded WebM (the web UI Kit's voice notes) has no duration header, so
61
+ // MediaPlayer reports 0/-1. Fall back to the timestamps in the file itself: the last cluster's
62
+ // timecode plus its last block's offset. MediaExtractor isn't enough — some vendor extractors
63
+ // (Xiaomi's MMParserExtractor) stop after the first cluster of a MediaRecorder WebM, so a 3 s
64
+ // note came back as 0.24 s → 00:00.
65
+ private static final int PROBE_TIMEOUT_MS = 10_000;
66
+ private static final int PROBE_MAX_BYTES = 10 * 1024 * 1024; // ponytail: voice notes are KBs; bigger files skip the fallback
67
+ // Keyed by the URL without its query: signed media URLs change their signature on every fetch.
68
+ private static final Map<String, Integer> durationCache = new ConcurrentHashMap<>();
69
+ // Probes (network + MediaPlayer.create) run here, never on the shared native-modules thread.
70
+ private static final ExecutorService probes = Executors.newSingleThreadExecutor();
52
71
 
53
- currentUrl = url;
72
+ private int durationSeconds(MediaPlayer mp, String url) {
73
+ int ms = mp.getDuration();
74
+ if (ms > 0) return ms / 1000;
75
+ // Remote URLs only: a bare local path throws MalformedURLException below and returns 0, which
76
+ // is fine because local recordings carry a real duration header.
77
+ String key = url.split("\\?", 2)[0];
78
+ Integer cached = durationCache.get(key);
79
+ if (cached != null) return cached;
54
80
  try {
55
- mediaPlayer = MediaPlayer.create(getReactApplicationContext(), Uri.parse(url));
56
- if (mediaPlayer == null)
57
- return;
58
- mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
59
- obj = new JSONObject();
60
- obj.put("duration", mediaPlayer.getDuration() / 1000);
81
+ URLConnection c = new URL(url).openConnection();
82
+ c.setConnectTimeout(PROBE_TIMEOUT_MS);
83
+ c.setReadTimeout(PROBE_TIMEOUT_MS);
84
+ try (InputStream in = c.getInputStream()) {
85
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
86
+ byte[] buf = new byte[16384];
87
+ for (int n; (n = in.read(buf)) > 0; ) {
88
+ bytes.write(buf, 0, n);
89
+ if (bytes.size() > PROBE_MAX_BYTES) return 0;
90
+ }
91
+ int seconds = (int) Math.round(webmDurationMs(bytes.toByteArray()) / 1000.0);
92
+ if (seconds > 0) durationCache.put(key, seconds);
93
+ return seconds;
94
+ }
61
95
  } catch (Exception e) {
62
- // create() / setAudioStreamType() / getDuration() in a bad state → don't crash.
63
- e.printStackTrace();
64
- return;
96
+ return 0;
65
97
  }
66
- resolve.invoke(obj.toString());
67
98
  }
68
99
 
69
- @ReactMethod
70
- public void play(String url, Callback resolve) {
71
- if (!prevUrl.equals("")){
72
- this.stop();
73
- emitEvent("complete", prevUrl);
100
+ // ponytail: walks clusters only and assumes the default 1 ms TimecodeScale, which is what
101
+ // browser MediaRecorder writes. Parse TimecodeScale (0x2AD7B1) if another encoder needs it.
102
+ static long webmDurationMs(byte[] d) {
103
+ long end = 0;
104
+ for (int i = 0; i + 4 <= d.length; i++) {
105
+ if ((d[i] & 0xFF) != 0x1F || (d[i + 1] & 0xFF) != 0x43 || (d[i + 2] & 0xFF) != 0xB6 || (d[i + 3] & 0xFF) != 0x75) continue;
106
+ int p = i + 4;
107
+ p += vintLength(d, p); // cluster size, often "unknown" for MediaRecorder
108
+ long clusterTc = 0;
109
+ while (p < d.length) {
110
+ int id = d[p] & 0xFF;
111
+ if (id != 0xE7 && id != 0xA3 && id != 0xA0) break; // Timecode, SimpleBlock, BlockGroup
112
+ int sizeLen = vintLength(d, p + 1);
113
+ long size = vintValue(d, p + 1, sizeLen);
114
+ int body = p + 1 + sizeLen;
115
+ if (size < 0 || body + size > d.length) break;
116
+ if (id == 0xE7) {
117
+ clusterTc = 0;
118
+ for (int k = 0; k < size; k++) clusterTc = (clusterTc << 8) | (d[body + k] & 0xFF);
119
+ } else if (id == 0xA3) {
120
+ int tcAt = body + vintLength(d, body); // skip track number
121
+ short rel = (short) (((d[tcAt] & 0xFF) << 8) | (d[tcAt + 1] & 0xFF));
122
+ end = Math.max(end, clusterTc + rel);
123
+ }
124
+ p = (int) (body + size);
125
+ }
126
+ end = Math.max(end, clusterTc);
74
127
  }
128
+ return end;
129
+ }
75
130
 
76
- if (mediaPlayer == null)
77
- eventEmitter = getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class);
131
+ private static int vintLength(byte[] d, int p) {
132
+ int first = d[p] & 0xFF;
133
+ for (int len = 1; len <= 8; len++) if ((first & (0x80 >> (len - 1))) != 0) return len;
134
+ return 8;
135
+ }
78
136
 
79
- currentUrl = url;
80
- try {
81
- mediaPlayer = MediaPlayer.create(getReactApplicationContext(), Uri.parse(url));
82
- if (mediaPlayer == null) {
83
- // create() returns null for an unplayable/unavailable URI — tell JS instead of hanging.
84
- resolve.invoke("Error", "Unable to load audio");
85
- return;
137
+ private static long vintValue(byte[] d, int p, int len) {
138
+ long v = d[p] & (0xFF >> len);
139
+ for (int k = 1; k < len; k++) v = (v << 8) | (d[p + k] & 0xFF);
140
+ return v;
141
+ }
142
+
143
+ @ReactMethod
144
+ public void prepareMediaPlayer(String url, Callback resolve) {
145
+ eventEmitter = getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class);
146
+ probes.execute(() -> {
147
+ // Only reads the duration; playback uses its own ExoPlayer, so the probe is released here.
148
+ MediaPlayer probe = null;
149
+ try {
150
+ probe = MediaPlayer.create(getReactApplicationContext(), Uri.parse(url));
151
+ if (probe == null) return;
152
+ JSONObject o = new JSONObject();
153
+ o.put("duration", durationSeconds(probe, url));
154
+ resolve.invoke(o.toString());
155
+ } catch (Exception e) {
156
+ // create() / getDuration() in a bad state → don't crash.
157
+ e.printStackTrace();
158
+ } finally {
159
+ if (probe != null) probe.release();
86
160
  }
161
+ });
162
+ }
163
+
164
+ // Playback runs on ExoPlayer, not MediaPlayer: MediaPlayer always goes through the device's
165
+ // extractor, and some vendor ones (Xiaomi's MMParserExtractor) stop after the first cluster of
166
+ // a browser WebM, so a web voice note played ~0.4 s and ended. ExoPlayer ships its own Matroska
167
+ // extractor. It must be touched only on its looper thread, so every call below is posted there.
168
+ private static HandlerThread exoThread;
169
+ private static Handler exo;
170
+ private ExoPlayer player = null;
171
+ private String playingUrl = "";
172
+
173
+ private void onExo(Runnable r) {
174
+ if (exoThread == null) {
175
+ exoThread = new HandlerThread("CometChatSoundPlayer");
176
+ exoThread.start();
177
+ exo = new Handler(exoThread.getLooper());
178
+ }
179
+ exo.post(() -> {
180
+ try { r.run(); } catch (Exception e) { e.printStackTrace(); } // never crash the app
181
+ });
182
+ }
87
183
 
88
- mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
184
+ private void releasePlayer() { // exo thread only
185
+ if (player != null) { player.release(); player = null; }
186
+ }
187
+
188
+ @ReactMethod
189
+ public void play(String url, Callback resolve) {
190
+ eventEmitter = getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class);
191
+ onExo(() -> {
192
+ if (player != null && !playingUrl.isEmpty()) emitEvent("complete", playingUrl); // replaced clip
193
+ releasePlayer();
194
+ ExoPlayer p = new ExoPlayer.Builder(getReactApplicationContext()).setLooper(exoThread.getLooper()).build();
195
+ p.setAudioAttributes(new AudioAttributes.Builder()
196
+ .setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MUSIC).build(), false);
197
+ boolean[] answered = {false}; // a Callback may be invoked only once
198
+ p.addListener(new Player.Listener() {
89
199
  @Override
90
- public void onCompletion(MediaPlayer mp) {
91
- emitEvent("complete", url);
92
- if (prevUrl.equals(url)){
93
- prevUrl = "";
200
+ public void onPlaybackStateChanged(int state) {
201
+ if (state == Player.STATE_READY && !answered[0]) {
202
+ answered[0] = true;
203
+ try {
204
+ JSONObject o = new JSONObject();
205
+ o.put("success", true);
206
+ o.put("url", url);
207
+ resolve.invoke(o.toString());
208
+ } catch (JSONException e) {
209
+ resolve.invoke("Error", e.getMessage());
210
+ }
211
+ } else if (state == Player.STATE_ENDED) {
212
+ emitEvent("complete", url);
213
+ if (playingUrl.equals(url)) playingUrl = "";
94
214
  }
95
215
  }
96
- });
97
216
 
98
- mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
99
- mediaPlayer.start();
100
- obj = new JSONObject();
101
- obj.put("success", true);
102
- int duration = mediaPlayer.getDuration();
103
- if (duration > -1) {
104
- duration = duration / 1000;
105
- }
106
- prevUrl = url;
107
- obj.put("duration", duration);
108
- obj.put("url", currentUrl);
109
- resolve.invoke(obj.toString());
110
- } catch (Exception ex) {
111
- // start()/getDuration() on a bad player state (IllegalStateException) or JSON error →
112
- // report it, never crash. resolve is invoked exactly once on every path.
113
- resolve.invoke("Error", ex.getMessage());
114
- }
217
+ @Override
218
+ public void onPlayerError(@NonNull PlaybackException error) {
219
+ // 404, expired signed URL, unsupported file: free the player and reset the bubble.
220
+ if (!answered[0]) {
221
+ answered[0] = true;
222
+ resolve.invoke("Error", error.getMessage());
223
+ }
224
+ emitEvent("complete", url);
225
+ if (player == p) { releasePlayer(); playingUrl = ""; }
226
+ }
227
+ });
228
+ p.setMediaItem(MediaItem.fromUri(url));
229
+ p.prepare();
230
+ p.play();
231
+ player = p;
232
+ playingUrl = url;
233
+ });
115
234
  }
116
235
 
117
236
  @ReactMethod
118
237
  public void resume() {
119
- try {
120
- if (mediaPlayer != null) {
121
- mediaPlayer.start();
122
- }
123
- } catch (Exception e) {
124
- // start() on a released/error/idle player throws IllegalStateException — ignore.
125
- e.printStackTrace();
126
- }
238
+ onExo(() -> { if (player != null) player.play(); });
127
239
  }
128
240
 
129
241
  @ReactMethod
130
242
  public void playAt(int atTime, Callback resolve) {
131
- try {
132
- if (mediaPlayer == null) {
133
- resolve.invoke("Error", "MediaPlayer not prepared.");
134
- return;
135
- }
136
- mediaPlayer.seekTo(atTime * 1000);
137
- } catch (Exception e) {
138
- // seekTo() in an invalid state throws IllegalStateException — report, don't crash.
139
- resolve.invoke("Error", e.getMessage());
140
- return;
141
- }
142
- obj = new JSONObject();
143
- resolve.invoke(obj.toString());
243
+ onExo(() -> {
244
+ if (player == null) { resolve.invoke("Error", "MediaPlayer not prepared."); return; }
245
+ player.seekTo(atTime * 1000L);
246
+ resolve.invoke(new JSONObject().toString());
247
+ });
144
248
  }
145
249
 
146
250
  @ReactMethod
147
251
  public void pause(Callback resolve) {
148
- if (mediaPlayer == null)
149
- return;
150
- try {
151
- mediaPlayer.pause();
152
- obj = new JSONObject();
153
- obj.put("success", true);
154
- resolve.invoke(obj.toString());
155
- } catch (Exception ex) {
156
- // pause() on a non-started player throws IllegalStateException — swallow, don't crash.
157
- resolve.invoke(obj.toString());
158
- }
252
+ onExo(() -> {
253
+ if (player == null) return;
254
+ player.pause();
255
+ try {
256
+ JSONObject o = new JSONObject();
257
+ o.put("success", true);
258
+ resolve.invoke(o.toString());
259
+ } catch (JSONException e) {
260
+ resolve.invoke(new JSONObject().toString());
261
+ }
262
+ });
159
263
  }
160
264
 
161
265
  @ReactMethod
162
266
  public void stop() {
163
- if(mediaPlayer == null)
164
- return;
165
- try {
166
- mediaPlayer.stop();
167
- mediaPlayer.reset();
168
- } catch (Exception e) {
169
- // stop() from Idle/Error state throws IllegalStateException — ignore, never crash.
170
- e.printStackTrace();
171
- }
267
+ onExo(() -> {
268
+ if (!playingUrl.isEmpty()) emitEvent("complete", playingUrl);
269
+ releasePlayer();
270
+ playingUrl = "";
271
+ });
172
272
  }
173
273
 
174
274
  @ReactMethod
175
275
  public void releaseMediaPlayer() {
176
- if(mediaPlayer == null)
177
- return;
178
- try {
179
- mediaPlayer.release();
180
- } catch (Exception e) {
181
- e.printStackTrace();
182
- }
183
- // Null the reference so later calls (getPosition polls, another card's release) see a null
184
- // player and take the safe path instead of touching a released one (IllegalStateException).
185
- mediaPlayer = null;
276
+ // Every audio card calls this on unmount, without saying which clip it is, so it must not
277
+ // stop the shared ExoPlayer: scrolling another card out of view would cut the playing clip
278
+ // and leave its card stuck on "playing". The duration probe releases itself, so there is
279
+ // nothing left to free here. Kept for the JS API.
186
280
  }
187
281
 
188
282
  @ReactMethod
189
283
  public void getPosition(Callback resolve) {
190
- obj = new JSONObject();
191
- try {
192
- // Guard: the shared MediaPlayer may be null (create failed) or released/reset by another
193
- // audio card between polls. getCurrentPosition() on a null/invalid player would throw an
194
- // uncaught NPE/IllegalStateException and red-screen the app — report 0 instead.
195
- int position = (mediaPlayer != null) ? mediaPlayer.getCurrentPosition() / 1000 : 0;
196
- obj.put("position", position);
197
- } catch (Exception e) {
198
- try { obj.put("position", 0); } catch (JSONException ignored) {}
199
- }
200
- resolve.invoke(obj.toString());
284
+ onExo(() -> {
285
+ try {
286
+ JSONObject o = new JSONObject();
287
+ o.put("position", player != null ? player.getCurrentPosition() / 1000 : 0);
288
+ resolve.invoke(o.toString());
289
+ } catch (JSONException ignored) {}
290
+ });
201
291
  }
202
292
 
203
293
  @NonNull
@@ -0,0 +1,19 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ NS_ASSUME_NONNULL_BEGIN
4
+
5
+ /// True when `url` has the `file` scheme, in any letter case.
6
+ FOUNDATION_EXPORT BOOL CCUIKitIsFileURL(NSURL *_Nullable url);
7
+
8
+ /// Where the offline Chat SDK keeps media: `<Documents>/cometchat/media` (its MediaFileStore root,
9
+ /// under react-native-fs's DocumentDirectoryPath).
10
+ FOUNDATION_EXPORT NSArray<NSString *> *CCUIKitOfflineMediaRoots(void);
11
+
12
+ /// The resolved path of the file behind a `file://` `url` when it may be copied out of the app: after
13
+ /// `..` and every symlink are resolved, it is a regular file strictly inside one of `roots` (the offline
14
+ /// media cache). Anything else is nil, so a message cannot name a private file of the app (its database,
15
+ /// its storage, any other file) and have it saved or shared. The caller copies the returned path, i.e.
16
+ /// exactly what was checked.
17
+ FOUNDATION_EXPORT NSString *_Nullable CCUIKitConfinedLocalFilePath(NSURL *_Nullable url, NSArray<NSString *> *roots);
18
+
19
+ NS_ASSUME_NONNULL_END
@@ -0,0 +1,34 @@
1
+ #import "CCLocalFileGuard.h"
2
+ #include <limits.h>
3
+ #include <stdlib.h>
4
+
5
+ BOOL CCUIKitIsFileURL(NSURL *url) {
6
+ return url != nil && url.scheme != nil && [url.scheme caseInsensitiveCompare:@"file"] == NSOrderedSame;
7
+ }
8
+
9
+ NSArray<NSString *> *CCUIKitOfflineMediaRoots(void) {
10
+ NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
11
+ return documents.length > 0 ? @[[documents stringByAppendingPathComponent:@"cometchat/media"]] : @[];
12
+ }
13
+
14
+ // realpath(3): `..` and every symlink resolved, or nil when the path does not exist.
15
+ static NSString *CCUIKitResolvedPath(NSString *path) {
16
+ if (path.length == 0) return nil;
17
+ char resolved[PATH_MAX];
18
+ if (realpath(path.fileSystemRepresentation, resolved) == NULL) return nil;
19
+ return [[NSFileManager defaultManager] stringWithFileSystemRepresentation:resolved length:strlen(resolved)];
20
+ }
21
+
22
+ NSString *CCUIKitConfinedLocalFilePath(NSURL *url, NSArray<NSString *> *roots) {
23
+ if (!CCUIKitIsFileURL(url)) return nil;
24
+ NSString *source = CCUIKitResolvedPath(url.path);
25
+ if (source == nil) return nil;
26
+ BOOL isDir = YES;
27
+ if (![[NSFileManager defaultManager] fileExistsAtPath:source isDirectory:&isDir] || isDir) return nil;
28
+ for (NSString *root in roots) {
29
+ NSString *base = CCUIKitResolvedPath(root);
30
+ if (base.length <= 1) continue; // a missing root, or "/", allows nothing
31
+ if ([source hasPrefix:[base stringByAppendingString:@"/"]]) return source;
32
+ }
33
+ return nil;
34
+ }
package/ios/FileManager.m CHANGED
@@ -1,6 +1,7 @@
1
1
  #import <Foundation/Foundation.h>
2
2
  #import <React/RCTBridgeModule.h>
3
3
  #import "FileManager.h"
4
+ #import "CCLocalFileGuard.h"
4
5
  #import <QuickLook/QuickLook.h>
5
6
  #import <React/RCTUtils.h>
6
7
  #import <React/RCTConvert.h>
@@ -22,6 +23,22 @@ static NSString *const FIELD_NAME = @"name";
22
23
  static NSString *const FIELD_TYPE = @"type";
23
24
  static NSString *const FIELD_SIZE = @"size";
24
25
 
26
+ // The base name of a file name, so a ".." or a path separator can never leave the destination folder,
27
+ // or nil when there is no usable name. Same rule as the Android UI Kit (File(displayName).name).
28
+ static NSString *CCSafeFileName(NSString *name) {
29
+ if (name.length == 0 || [name containsString:@"\0"]) return nil;
30
+ NSString *base = name.lastPathComponent;
31
+ if (base.length == 0 || [base isEqualToString:@"/"] || [base isEqualToString:@"."] || [base isEqualToString:@".."]) return nil;
32
+ return base;
33
+ }
34
+
35
+ // The file behind a file:// URL taken from a message, when it lies inside the offline media cache
36
+ // (CCLocalFileGuard.h), else nil. Stricter than the Android UI Kit's MediaViewerSource.localFile, which
37
+ // only checks that the file exists.
38
+ static NSString *CCOfflineMediaFilePath(NSURL *url) {
39
+ return CCUIKitConfinedLocalFilePath(url, CCUIKitOfflineMediaRoots());
40
+ }
41
+
25
42
 
26
43
  @interface CometChatFileManager () <UIDocumentPickerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, AVAudioRecorderDelegate, AVAudioPlayerDelegate, UIDocumentInteractionControllerDelegate, PHPickerViewControllerDelegate>
27
44
 
@@ -80,11 +97,32 @@ RCT_EXPORT_MODULE(FileManager)
80
97
  - (void)downloadToDocuments:(NSString *)urlToDownload name:(NSString *)name callback:(RCTResponseSenderBlock)callback {
81
98
  NSURL *url = [NSURL URLWithString:urlToDownload];
82
99
  if (url == nil) { callback(@[@"{\"success\": false, \"error\": \"invalid url\"}"]); return; }
100
+ name = CCSafeFileName(name);
101
+ if (name == nil) { callback(@[@"{\"success\": false, \"error\": \"invalid file name\"}"]); return; }
83
102
 
84
103
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
85
104
  NSString *destPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:name];
86
105
  NSURL *destinationFileURL = [NSURL fileURLWithPath:destPath];
87
106
 
107
+ // A file already on the device: copied only from the offline media cache, never fetched.
108
+ if (CCUIKitIsFileURL(url)) {
109
+ NSString *source = CCOfflineMediaFilePath(url);
110
+ if (source == nil) {
111
+ callback(@[@"{\"success\": false, \"error\": \"file is not available\"}"]);
112
+ return;
113
+ }
114
+ NSFileManager *fm = [NSFileManager defaultManager];
115
+ [fm removeItemAtURL:destinationFileURL error:nil];
116
+ NSError *copyErr = nil;
117
+ if (![fm copyItemAtURL:[NSURL fileURLWithPath:source] toURL:destinationFileURL error:&copyErr]) {
118
+ callback(@[@"{\"success\": false, \"error\": \"could not save file\"}"]);
119
+ return;
120
+ }
121
+ self->_url = [NSString stringWithFormat:@"file://%@", destPath];
122
+ callback(@[@"{\"success\": true}"]);
123
+ return;
124
+ }
125
+
88
126
  NSURLSessionDownloadTask *task = [[NSURLSession sharedSession] downloadTaskWithURL:url
89
127
  completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
90
128
  if (error != nil || location == nil) {
@@ -109,7 +147,9 @@ RCT_EXPORT_MODULE(FileManager)
109
147
  // Files / Save to Photos / AirDrop — the sandbox-legal equivalent of Android's visible DownloadManager
110
148
  // save (iOS apps cannot write to a shared public "Downloads" folder). Previously this saved into the
111
149
  // app's PRIVATE Documents dir with no UI, so on iOS the download appeared to do nothing.
112
- RCT_EXPORT_METHOD(checkAndDownload:(NSString *) urlToDownload name:(NSString *) name callback:(RCTResponseSenderBlock) callback) {
150
+ RCT_EXPORT_METHOD(checkAndDownload:(NSString *) urlToDownload name:(NSString *) rawName callback:(RCTResponseSenderBlock) callback) {
151
+ NSString *name = CCSafeFileName(rawName);
152
+ if (name == nil) { callback(@[@"{\"success\": false, \"error\": \"invalid file name\"}"]); return; }
113
153
  [self downloadToDocuments:urlToDownload name:name callback:^(NSArray *response) {
114
154
  NSString *res = response.firstObject ?: @"";
115
155
  if ([res containsString:@"\"success\": true"]) {
@@ -134,13 +174,15 @@ RCT_EXPORT_METHOD(checkAndDownload:(NSString *) urlToDownload name:(NSString *)
134
174
  QLPreviewController* previewCtrl = [[QLPreviewController alloc] init];
135
175
  [previewCtrl setDataSource: self];
136
176
  [[previewCtrl navigationController] setTitle:@""];
137
- [previewCtrl setModalPresentationStyle:UIModalPresentationPopover];
177
+ [previewCtrl setModalPresentationStyle:UIModalPresentationFullScreen];
138
178
  UIViewController *presentedViewController = RCTPresentedViewController();
139
179
  [presentedViewController presentViewController:previewCtrl animated:YES completion:nil];
140
180
  });
141
181
  }
142
182
 
143
- RCT_EXPORT_METHOD(doesFileExist:(NSString *)fileName callback:(RCTResponseSenderBlock)callback) {
183
+ RCT_EXPORT_METHOD(doesFileExist:(NSString *)rawFileName callback:(RCTResponseSenderBlock)callback) {
184
+ NSString *fileName = CCSafeFileName(rawFileName);
185
+ if (fileName == nil) { callback(@[@"{\"exists\": false}"]); return; }
144
186
  // Get the document directory path
145
187
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
146
188
  NSString *documentsDirectory = [paths objectAtIndex:0];
@@ -158,7 +200,9 @@ RCT_EXPORT_METHOD(doesFileExist:(NSString *)fileName callback:(RCTResponseSender
158
200
  }
159
201
 
160
202
 
161
- RCT_EXPORT_METHOD(openFile:(NSString *) url name:(NSString *) fileName myCallback:(RCTResponseSenderBlock)callback) {
203
+ RCT_EXPORT_METHOD(openFile:(NSString *) url name:(NSString *) rawFileName myCallback:(RCTResponseSenderBlock)callback) {
204
+ NSString *fileName = CCSafeFileName(rawFileName);
205
+ if (fileName == nil) { callback(@[@"{\"success\": false}"]); return; }
162
206
  //new way
163
207
  @try {
164
208
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
@@ -194,7 +238,9 @@ RCT_EXPORT_METHOD(openFile:(NSString *) url name:(NSString *) fileName myCallbac
194
238
  }
195
239
  }
196
240
 
197
- RCT_EXPORT_METHOD(openFileWithOption:(NSString *)fileName callback:(RCTResponseSenderBlock)callback) {
241
+ RCT_EXPORT_METHOD(openFileWithOption:(NSString *)rawFileName callback:(RCTResponseSenderBlock)callback) {
242
+ NSString *fileName = CCSafeFileName(rawFileName);
243
+ if (fileName == nil) { callback(@[@"{\"success\": false, \"error\": \"invalid file name\"}"]); return; }
198
244
  @try {
199
245
  // Get the Downloads directory path
200
246
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
@@ -480,7 +526,25 @@ RCT_EXPORT_METHOD(shareMessage: (NSDictionary *) shareObj myCallback:(RCTRespons
480
526
  } else {
481
527
  if (fileUrl) {
482
528
  NSURL *url = [NSURL URLWithString:fileUrl];
483
- if (url) {
529
+ if (url && CCUIKitIsFileURL(url)) {
530
+ // A file already on the device: shared only from the offline media cache, under its own
531
+ // name (the cached file has none), never fetched.
532
+ NSString *shareName = CCSafeFileName(mediaName.length > 0 ? mediaName : url.lastPathComponent);
533
+ NSString *source = CCOfflineMediaFilePath(url);
534
+ if (shareName == nil || source == nil) {
535
+ callback(@[@"{\"success\": false}"]);
536
+ return;
537
+ }
538
+ NSURL *shareUrl = [[NSURL fileURLWithPath:NSTemporaryDirectory()] URLByAppendingPathComponent:shareName];
539
+ NSFileManager *fm = [NSFileManager defaultManager];
540
+ [fm removeItemAtURL:shareUrl error:nil];
541
+ if ([fm copyItemAtURL:[NSURL fileURLWithPath:source] toURL:shareUrl error:nil]) {
542
+ [self shareMedia:shareUrl];
543
+ callback(@[@"{\"success\": true}"]);
544
+ } else {
545
+ callback(@[@"{\"success\": false}"]);
546
+ }
547
+ } else if (url) {
484
548
  [self downloadMediaMessage:url completion:^(NSURL *fileLocation) {
485
549
  if (fileLocation) {
486
550
  [self shareMedia:fileLocation];