@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
@@ -72,6 +72,11 @@ dependencies {
72
72
  implementation "com.facebook.react:react-android"
73
73
  implementation 'androidx.appcompat:appcompat:1.7.1'
74
74
  implementation 'com.google.android.material:material:1.12.0'
75
+ // Voice-note playback: ExoPlayer's own WebM extractor (vendor MediaPlayer extractors truncate web notes).
76
+ // Host apps can pin the version (same key react-native-video reads), e.g. to keep compileSdk 34:
77
+ // ext { RNVideo_media3Version = "1.4.1" } — media3 1.8.0 needs compileSdk 35.
78
+ def media3Version = rootProject.ext.has("RNVideo_media3Version") ? rootProject.ext.get("RNVideo_media3Version") : "1.8.0"
79
+ implementation "androidx.media3:media3-exoplayer:${media3Version}"
75
80
 
76
81
  // Unit tests for the native editor. Robolectric runs real Android framework code off-device,
77
82
  // which is the only way to assert on spans: the inline-style rules live in a TextWatcher and
@@ -47,6 +47,7 @@ import com.facebook.react.bridge.ReactApplicationContext;
47
47
  import com.facebook.react.bridge.ReactContextBaseJavaModule;
48
48
  import com.facebook.react.bridge.ReactMethod;
49
49
  import com.facebook.react.bridge.ReadableMap;
50
+ import com.facebook.react.bridge.UiThreadUtil;
50
51
  import com.facebook.react.bridge.WritableMap;
51
52
  import com.facebook.react.bridge.WritableArray;
52
53
  import com.facebook.react.bridge.WritableNativeMap;
@@ -306,7 +307,11 @@ public class FileManager extends ReactContextBaseJavaModule {
306
307
  if (fileName == null) {
307
308
  fileName = String.valueOf(System.currentTimeMillis());
308
309
  }
309
- File destFile = new File(dir, fileName);
310
+ String safeName = SafeFileName.of(fileName);
311
+ if (safeName == null) {
312
+ throw new IOException("unsafe file name");
313
+ }
314
+ File destFile = new File(dir, safeName);
310
315
  Uri copyPath = copyFile(context, uri, destFile);
311
316
  map.putString(FIELD_FILE_COPY_URI, copyPath.toString());
312
317
  } catch (Exception e) {
@@ -445,10 +450,19 @@ public class FileManager extends ReactContextBaseJavaModule {
445
450
  }
446
451
 
447
452
  public static void downloadFileInNewThread(Context context, String fileUrl, String fileName, String mimeType) {
448
- File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
453
+ String safeName = SafeFileName.of(fileName);
454
+ if (safeName == null) {
455
+ handleDownloadFailure(context);
456
+ return;
457
+ }
458
+ File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), safeName);
449
459
  Thread downloadThread = new Thread(() -> {
450
460
  try {
451
- if (!file.exists()) {
461
+ if (!file.exists() && SafeFileName.isFileUri(fileUrl)) {
462
+ // A file already on the device: copied only from the offline media cache, no fetch.
463
+ copyLocalFile(context, fileUrl, file);
464
+ handleDownloadSuccess(context, mimeType, file);
465
+ } else if (!file.exists()) {
452
466
  URL url = new URL(fileUrl);
453
467
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
454
468
  connection.connect();
@@ -485,6 +499,37 @@ public class FileManager extends ReactContextBaseJavaModule {
485
499
  downloadThread.start();
486
500
  }
487
501
 
502
+ /**
503
+ * Where the offline Chat SDK keeps media (MediaFileStore): `<dataDir>/no_backup/cometchat/media`
504
+ * (the folder op-sqlite reports as ANDROID_FILES_PATH, one level up, then `no_backup`), or
505
+ * `<files>/cometchat/media` without op-sqlite and before the SDK's one-time move to no_backup.
506
+ * Its database (`no_backup/databases`) and every other private file are outside both.
507
+ */
508
+ private static File[] offlineMediaRoots(Context context) {
509
+ File files = context.getFilesDir();
510
+ return new File[] {
511
+ new File(files.getParentFile(), "no_backup/cometchat/media"),
512
+ new File(files, "cometchat/media"),
513
+ };
514
+ }
515
+
516
+ private static void copyLocalFile(Context context, String fileUri, File dest) throws IOException {
517
+ // A file:// source is the message's data: copy it only when it resolves inside the offline
518
+ // media cache, never any other file the app can read.
519
+ File source = SafeFileName.confinedLocalFile(fileUri, offlineMediaRoots(context));
520
+ if (source == null) {
521
+ throw new IOException("source is not in the offline media cache");
522
+ }
523
+ try (InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(dest)) {
524
+ byte[] buffer = new byte[4096];
525
+ int read;
526
+ while ((read = in.read(buffer)) != -1) {
527
+ out.write(buffer, 0, read);
528
+ }
529
+ out.flush();
530
+ }
531
+ }
532
+
488
533
  private static void handleDownloadSuccess(Context context, String mimeType, final File file) {
489
534
  ((Activity) context).runOnUiThread(() -> {
490
535
  shareFile(mimeType, context, file);
@@ -1805,12 +1850,31 @@ public class FileManager extends ReactContextBaseJavaModule {
1805
1850
  @ReactMethod
1806
1851
  public void checkAndDownload(String url, String name, Callback callback) {
1807
1852
  try {
1853
+ name = SafeFileName.of(name);
1854
+ if (name == null) {
1855
+ callback.invoke("{\"success\": false, \"error\": \"Invalid file name\"}");
1856
+ return;
1857
+ }
1808
1858
  if (fileExists(name)) {
1809
1859
  // Already downloaded — open it and report done
1810
1860
  openFileWithOption(name, ignored -> {});
1811
1861
  callback.invoke("{\"success\": true, \"alreadyExists\": true}");
1812
1862
  return;
1813
1863
  }
1864
+ if (SafeFileName.isFileUri(url)) {
1865
+ // A file already on the device: copied into Downloads only from the offline media cache.
1866
+ File dest = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), name);
1867
+ try {
1868
+ copyLocalFile(getReactApplicationContext(), url, dest);
1869
+ } catch (IOException e) {
1870
+ Log.w(TAG, "checkAndDownload: refused a local file outside the offline media cache");
1871
+ UiThreadUtil.runOnUiThread(() -> Toast.makeText(getReactApplicationContext(), "File download failed.", Toast.LENGTH_SHORT).show());
1872
+ callback.invoke("{\"success\": false, \"error\": \"File is not available\"}");
1873
+ return;
1874
+ }
1875
+ callback.invoke("{\"success\": true, \"alreadyExists\": false}");
1876
+ return;
1877
+ }
1814
1878
  Long downloadId = downloadFile(name, url);
1815
1879
  if (downloadId == null) {
1816
1880
  callback.invoke("{\"success\": false, \"error\": \"Download could not be started\"}");
@@ -1837,6 +1901,11 @@ public class FileManager extends ReactContextBaseJavaModule {
1837
1901
  @ReactMethod
1838
1902
  public void openFileWithOption(String fileName, Callback callback) {
1839
1903
  try {
1904
+ fileName = SafeFileName.of(fileName);
1905
+ if (fileName == null) {
1906
+ callback.invoke("{\"success\": false, \"error\": \"Invalid file name\"}");
1907
+ return;
1908
+ }
1840
1909
  // Get the Downloads directory path
1841
1910
  File downloadsDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
1842
1911
  File file = new File(downloadsDir, fileName);
@@ -1910,12 +1979,18 @@ public class FileManager extends ReactContextBaseJavaModule {
1910
1979
  }
1911
1980
 
1912
1981
  private boolean fileExists(String fileName) {
1982
+ fileName = SafeFileName.of(fileName);
1983
+ if (fileName == null) return false;
1913
1984
  File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
1914
1985
  return f.exists();
1915
1986
  }
1916
1987
 
1917
1988
  private Long downloadFile(String fileName, String url){
1918
1989
  try {
1990
+ fileName = SafeFileName.of(fileName);
1991
+ if (fileName == null) {
1992
+ return null;
1993
+ }
1919
1994
  if (fileExists(fileName)) {
1920
1995
  return null;
1921
1996
  }
@@ -165,6 +165,8 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
165
165
  private var isInitialized = false
166
166
 
167
167
  private var previousText: String = ""
168
+ // Text length at the last onSelectionChanged, for telling typing apart from a caret move.
169
+ private var lastSelectionTextLength = 0
168
170
  private var pendingDelta: Map<String, Any>? = null
169
171
  private var pendingPrefixDeletion: Pair<Int, Int>? = null // (lineStart, prefixLength) for backspace-in-prefix
170
172
  // Saved selected text for URL-paste-over-selection detection in TextWatcher
@@ -548,6 +550,25 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
548
550
  inheritedStyles = null
549
551
  }
550
552
 
553
+ // A colour the user switched off at the caret must stay off for what they type
554
+ // next — including inside an existing coloured run. A span that covers the
555
+ // caret on both sides grows over inserted text on its own, whatever its flags,
556
+ // so the clear was ignored the moment the caret sat mid-word: tap into red
557
+ // text, clear, type, and the new text came out red (ENG-40922, found by
558
+ // InlineColourFuzzTest). Strip the colour from the inserted range explicitly.
559
+ if (addedCount > 0 && s != null && changeStart + addedCount <= s.length) {
560
+ val start = changeStart
561
+ val end = changeStart + addedCount
562
+ isInternalChange = true
563
+ if (explicitlyOffStyles.contains("externalColor")) {
564
+ clearInlineStyleSpans(s, "color", start, end)
565
+ }
566
+ if (explicitlyOffStyles.contains("externalBackgroundColor")) {
567
+ clearInlineStyleSpans(s, "backgroundColor", start, end)
568
+ }
569
+ isInternalChange = false
570
+ }
571
+
551
572
  // Apply pending styles to newly typed text
552
573
  if (addedCount > 0 && removedCount == 0 && s != null) {
553
574
  val spanStart = changeStart
@@ -880,6 +901,14 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
880
901
  s.getSpans(0, 0, StrikethroughSpan::class.java).forEach { s.removeSpan(it) }
881
902
  s.getSpans(0, 0, InlineCodeSpan::class.java).forEach { s.removeSpan(it) }
882
903
  s.getSpans(0, 0, ForegroundColorSpan::class.java).forEach { s.removeSpan(it) }
904
+ // ExternalForegroundColorSpan is not a ForegroundColorSpan, so the line above
905
+ // missed it: delete everything and the next character came back in the old
906
+ // colour, while iOS correctly started plain (ENG-40922, found by
907
+ // InlineColourFuzzTest).
908
+ s.getSpans(0, 0, ExternalForegroundColorSpan::class.java).forEach { s.removeSpan(it) }
909
+ s.getSpans(0, 0, ExternalBackgroundColorSpan::class.java).forEach { s.removeSpan(it) }
910
+ pendingExternalColor = null
911
+ pendingExternalBackgroundColor = null
883
912
  s.getSpans(0, 0, AbsoluteSizeSpan::class.java).forEach { s.removeSpan(it) }
884
913
  s.getSpans(0, 0, CodeBlockBorderSpan::class.java).forEach { s.removeSpan(it) }
885
914
  s.getSpans(0, 0, TypefaceSpan::class.java).forEach { s.removeSpan(it) }
@@ -1387,13 +1416,27 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
1387
1416
  // Skip if not initialized yet (during construction)
1388
1417
  if (!isInitialized) return
1389
1418
 
1419
+ // How many characters landed since the last selection change, measured against the length
1420
+ // recorded here rather than previousText. A keyboard (Gboard, composing mid-word) can run
1421
+ // afterTextChanged — which refreshes previousText — before this callback, so measuring
1422
+ // against previousText read every keystroke as "nothing typed" and disarmed the colour on
1423
+ // the first character (ENG-40922). Tracked unconditionally, as iOS does (ENG-38248).
1424
+ val currentLen = text?.length ?: 0
1425
+ val insertedCount = currentLen - lastSelectionTextLength
1426
+ lastSelectionTextLength = currentLen
1427
+
1390
1428
  // Clear pending/explicitly-off styles when cursor moves WITHOUT text changing
1391
1429
  // (i.e., user tapped somewhere else or used arrow keys)
1392
1430
  if ((pendingStyles.isNotEmpty() || explicitlyOffStyles.isNotEmpty()) && pendingStylesInsertPos >= 0) {
1393
1431
  if (selStart != pendingStylesInsertPos) {
1394
- val currentLen = text?.length ?: 0
1395
- // Allow cursor to advance by 1 (typing) — don't clear in that case
1396
- if (selStart != pendingStylesInsertPos + 1 || currentLen == previousText.length) {
1432
+ // Typing advances the caret by however many characters landed: one for a plain
1433
+ // keystroke, more when the keyboard commits an autocorrection or suggestion (which
1434
+ // "." and space both do). A hardcoded +1 read those as a caret move and disarmed
1435
+ // the colour, so text after a full stop sent plain (ENG-40922). Mirrors iOS.
1436
+ // A backspace at the anchor moves the caret back by exactly what it removed — that is
1437
+ // editing, not a caret jump, so the colour follows it (ENG-40922).
1438
+ val isTypingAdvance = insertedCount != 0 && selStart == pendingStylesInsertPos + insertedCount
1439
+ if (!isTypingAdvance) {
1397
1440
  // Preserve "codeBlock" across cursor movements — it's a persistent
1398
1441
  // block-level style that should survive until explicitly toggled off
1399
1442
  // or exited via triple-Enter. Without this, the clear-and-re-add
@@ -1408,7 +1451,7 @@ class RichTextEditorView(context: Context) : androidx.appcompat.widget.AppCompat
1408
1451
  pendingStylesInsertPos = selStart
1409
1452
  }
1410
1453
  } else {
1411
- // Cursor advanced by 1 due to typing — update insert pos
1454
+ // Text was typed at the anchor — follow it, however many characters landed
1412
1455
  pendingStylesInsertPos = selStart
1413
1456
  }
1414
1457
  }
@@ -0,0 +1,78 @@
1
+ package com.reactnativecometchatuikit;
2
+
3
+ import java.io.File;
4
+ import java.net.URI;
5
+
6
+ /**
7
+ * Checks for the native copy and download code, kept free of Android classes so they can be unit
8
+ * tested on the JVM. A destination name keeps only its base name, as the Android UI Kit's share copy
9
+ * does (MediaViewerSource.copyForShare uses File(displayName).name). A local source must also lie
10
+ * inside the offline media cache ({@link #confinedLocalFile}), which is stricter than the Android
11
+ * UI Kit's MediaViewerSource.localFile (it only checks that the file exists).
12
+ */
13
+ final class SafeFileName {
14
+
15
+ private SafeFileName() {}
16
+
17
+ /**
18
+ * The base name of [name], so a `..` or a path separator can never leave the destination
19
+ * folder, or null when there is no usable name (empty, `.`, `..`, or a NUL character).
20
+ */
21
+ static String of(String name) {
22
+ if (name == null || name.indexOf('\0') >= 0) return null;
23
+ String base = new File(name).getName();
24
+ if (base.isEmpty() || base.equals(".") || base.equals("..")) return null;
25
+ return base;
26
+ }
27
+
28
+ /** The path behind a `file://` [uri], or null for any other scheme or an empty path. */
29
+ static String localPath(String uri) {
30
+ if (uri == null) return null;
31
+ try {
32
+ URI parsed = new URI(uri);
33
+ if (!"file".equalsIgnoreCase(parsed.getScheme())) return null;
34
+ String path = parsed.getPath();
35
+ return path == null || path.isEmpty() ? null : path;
36
+ } catch (Exception e) {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ /** True when [file] is an existing regular file that can be read. */
42
+ static boolean isReadableLocalFile(File file) {
43
+ return file != null && file.isFile() && file.canRead();
44
+ }
45
+
46
+ /** True when [uri] has the `file` scheme, in any letter case. */
47
+ static boolean isFileUri(String uri) {
48
+ return uri != null && uri.length() > 5 && uri.regionMatches(true, 0, "file:", 0, 5);
49
+ }
50
+
51
+ /**
52
+ * The file behind a `file://` [uri] when it may be copied out of the app: after `..` and every
53
+ * symlink are resolved, it is a readable regular file strictly inside one of [roots] (the offline
54
+ * media cache). Anything else is null, so a message cannot name a private file of the app (its
55
+ * database, its storage, `/etc/hosts`) and have it copied into public storage or shared.
56
+ *
57
+ * The Android UI Kit's MediaViewerSource.localFile only checks that the file exists, so it is not
58
+ * the model here. The returned file is the resolved one: the caller reads exactly what was checked.
59
+ */
60
+ static File confinedLocalFile(String uri, File... roots) {
61
+ String path = localPath(uri);
62
+ if (path == null || roots == null) return null;
63
+ try {
64
+ File source = new File(path).getCanonicalFile();
65
+ if (!isReadableLocalFile(source)) return null;
66
+ String resolved = source.getPath();
67
+ for (File root : roots) {
68
+ if (root == null) continue;
69
+ String base = root.getCanonicalPath();
70
+ if (base.isEmpty() || base.equals(File.separator)) continue;
71
+ if (resolved.startsWith(base + File.separator)) return source;
72
+ }
73
+ } catch (Exception e) {
74
+ return null;
75
+ }
76
+ return null;
77
+ }
78
+ }