catalyst-core 0.0.3-canary.9 → 0.1.0-beta.2

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 (182) hide show
  1. package/README.md +4 -5
  2. package/bin/catalyst.js +28 -15
  3. package/changelog.md +139 -30
  4. package/dist/native/androidProject/app/build.gradle.kts +125 -15
  5. package/dist/native/androidProject/app/proguard-rules.pro +85 -14
  6. package/dist/native/androidProject/app/src/debug/res/xml/network_security_config.xml +8 -0
  7. package/dist/native/androidProject/app/src/main/AndroidManifest.xml +10 -3
  8. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/BridgeMessageValidator.kt +552 -0
  9. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/CatalystConstants.kt +109 -0
  10. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/CustomWebview.kt +605 -124
  11. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/MainActivity.kt +405 -47
  12. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/MetricsMonitor.kt +341 -0
  13. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/NativeBridge.kt +954 -71
  14. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/SplashActivity.kt +111 -0
  15. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/URLWhitelistManager.kt +231 -0
  16. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/Utils.kt +49 -55
  17. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/WebCacheManager.kt +81 -8
  18. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/design/DesignTokens.kt +307 -0
  19. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/security/EmulatorDetector.kt +203 -0
  20. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/security/FridaDetector.kt +187 -0
  21. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/security/SecurityAlertHandler.kt +170 -0
  22. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/security/SecurityAlertUI.kt +366 -0
  23. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/security/SecurityBottomSheet.kt +138 -0
  24. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/security/SecurityCheckManager.kt +511 -0
  25. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/security/SecurityCheckScheduler.kt +68 -0
  26. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/BridgeUtils.kt +47 -11
  27. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/DeviceInfoUtils.kt +38 -13
  28. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/DownloadUtils.kt +36 -14
  29. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/FileUtils.kt +3 -2
  30. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/FrameworkServerUtils.kt +57 -8
  31. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/IntentUtils.kt +31 -6
  32. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/KeyboardUtil.kt +82 -0
  33. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/NetworkUtils.kt +105 -0
  34. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/NotificationConstants.kt +28 -0
  35. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/NotificationUtils.kt +639 -0
  36. package/dist/native/androidProject/app/src/main/java/io/yourname/androidproject/utils/SafeAreaUtils.kt +62 -0
  37. package/dist/native/androidProject/app/src/main/res/drawable/splashscreen_fallback.png +0 -0
  38. package/dist/native/androidProject/app/src/main/res/layout/activity_main.xml +1 -0
  39. package/dist/native/androidProject/app/src/main/res/layout/activity_splash.xml +20 -0
  40. package/dist/native/androidProject/app/src/main/res/values/themes.xml +23 -0
  41. package/dist/native/androidProject/app/src/main/res/values-night/themes.xml +11 -0
  42. package/dist/native/androidProject/app/src/main/res/xml/network_security_config.xml +12 -0
  43. package/dist/native/androidProject/app/src/noFcm/java/io/yourname/androidproject/utils/NotificationManager.kt +166 -0
  44. package/dist/native/androidProject/app/src/noFcm/java/io/yourname/androidproject/utils/PushNotificationUtils.kt +94 -0
  45. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/BridgeMessageValidatorTest.kt +267 -0
  46. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/BridgeUtilsTest.kt +286 -0
  47. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/CameraUtilsTest.kt +296 -0
  48. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/ConfigMappingTest.kt +594 -0
  49. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/CustomWebviewTest.kt +466 -0
  50. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/DeviceInfoUtilsTest.kt +187 -0
  51. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/FileUtilsTest.kt +304 -0
  52. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/NativeBridgeTest.kt +424 -0
  53. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/NotificationUtilsTest.kt +469 -0
  54. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/SecurityBridgeTest.kt +199 -0
  55. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/URLWhitelistManagerTest.kt +462 -0
  56. package/dist/native/androidProject/app/src/test/java/io/yourname/androidproject/WebCacheManagerTest.kt +391 -0
  57. package/dist/native/androidProject/app/src/withFcm/java/io/yourname/androidproject/utils/NotificationManager.kt +224 -0
  58. package/dist/native/androidProject/app/src/withFcm/java/io/yourname/androidproject/utils/PushNotificationUtils.kt +399 -0
  59. package/dist/native/androidProject/build.gradle.kts +6 -0
  60. package/dist/native/androidProject/gradle/libs.versions.toml +8 -2
  61. package/dist/native/androidSetup.js +4 -3
  62. package/dist/native/assets/catalyst.png +0 -0
  63. package/dist/native/bridge/WebBridge.js +16 -3
  64. package/dist/native/bridge/constants/NativeInterfaces.js +28 -10
  65. package/dist/native/bridge/errors.js +1 -1
  66. package/dist/native/bridge/hooks.js +76 -16
  67. package/dist/native/bridge/safeArea.js +5 -0
  68. package/dist/native/bridge/standardizedHooks.js +23 -5
  69. package/dist/native/bridge/useBaseHook.js +7 -9
  70. package/dist/native/bridge/utils/CameraUtils.js +58 -0
  71. package/dist/native/bridge/utils/FileObjectConverter.js +40 -0
  72. package/dist/native/bridge/utils/NativeBridge.js +57 -8
  73. package/dist/native/buildAppAndroid.js +115 -43
  74. package/dist/native/buildAppIos.js +291 -26
  75. package/dist/native/iosnativeWebView/Configurations/Debug.xcconfig +21 -0
  76. package/dist/native/iosnativeWebView/Configurations/Release.xcconfig +24 -0
  77. package/dist/native/iosnativeWebView/Configurations/Shared.xcconfig +50 -0
  78. package/dist/native/iosnativeWebView/Package.resolved +32 -0
  79. package/dist/native/iosnativeWebView/Package.swift +37 -0
  80. package/dist/native/iosnativeWebView/Sources/CatalystNotifications/LocalNotificationHandler.swift +293 -0
  81. package/dist/native/iosnativeWebView/Sources/CatalystNotifications/NotificationManager.swift +299 -0
  82. package/dist/native/iosnativeWebView/Sources/CatalystNotifications/PushNotificationHandler.swift +199 -0
  83. package/dist/native/iosnativeWebView/Sources/Core/Constants/CatalystConstants.swift +125 -0
  84. package/dist/native/iosnativeWebView/Sources/Core/Constants/ConfigConstants.swift +70 -0
  85. package/dist/native/iosnativeWebView/Sources/Core/Notifications/NotificationModels.swift +156 -0
  86. package/dist/native/iosnativeWebView/Sources/Core/Protocols/NotificationHandlerProtocol.swift +35 -0
  87. package/dist/native/iosnativeWebView/Sources/Core/Utils/BootTimingUtility.swift +26 -0
  88. package/dist/native/iosnativeWebView/{iosnativeWebView → Sources/Core/Utils}/CacheManager.swift +69 -36
  89. package/dist/native/iosnativeWebView/Sources/Core/Utils/CameraTransportUtils.swift +363 -0
  90. package/dist/native/iosnativeWebView/Sources/Core/Utils/DeviceInfoUtils.swift +67 -0
  91. package/dist/native/iosnativeWebView/Sources/Core/Utils/FilePickerHandler.swift +1053 -0
  92. package/dist/native/iosnativeWebView/Sources/Core/Utils/FrameworkServerUtils.swift +901 -0
  93. package/dist/native/iosnativeWebView/{iosnativeWebView → Sources/Core/Utils}/ImageHandler.swift +206 -20
  94. package/dist/native/iosnativeWebView/Sources/Core/Utils/NetworkMonitor.swift +112 -0
  95. package/dist/native/iosnativeWebView/Sources/Core/Utils/NotificationHandlerProvider.swift +20 -0
  96. package/dist/native/iosnativeWebView/Sources/Core/Utils/NullNotificationHandler.swift +85 -0
  97. package/dist/native/iosnativeWebView/{iosnativeWebView → Sources/Core/Utils}/ResourceURLProtocol.swift +60 -25
  98. package/dist/native/iosnativeWebView/Sources/Core/Utils/SafeAreaUtils.swift +132 -0
  99. package/dist/native/iosnativeWebView/Sources/Core/Utils/ScreenSecureManager.swift +131 -0
  100. package/dist/native/iosnativeWebView/Sources/Core/Utils/URLWhitelistManager.swift +224 -0
  101. package/dist/native/iosnativeWebView/Sources/Core/Utils/WebKitConfig.swift +43 -0
  102. package/dist/native/iosnativeWebView/Sources/Core/WebView/BridgeCommandHandler.swift +991 -0
  103. package/dist/native/iosnativeWebView/Sources/Core/WebView/BridgeDelegateHandler.swift +166 -0
  104. package/dist/native/iosnativeWebView/Sources/Core/WebView/BridgeFileHandler.swift +340 -0
  105. package/dist/native/iosnativeWebView/Sources/Core/WebView/BridgeJavaScriptInterface.swift +149 -0
  106. package/dist/native/iosnativeWebView/Sources/Core/WebView/BridgeMessageValidator.swift +611 -0
  107. package/dist/native/iosnativeWebView/Sources/Core/WebView/NativeBridge.swift +334 -0
  108. package/dist/native/iosnativeWebView/Sources/Core/WebView/SplashView.swift +95 -0
  109. package/dist/native/iosnativeWebView/Sources/Core/WebView/SplashViewModel.swift +86 -0
  110. package/dist/native/iosnativeWebView/Sources/Core/WebView/WebView.swift +181 -0
  111. package/dist/native/iosnativeWebView/Sources/Core/WebView/WebViewModel.swift +182 -0
  112. package/dist/native/iosnativeWebView/Sources/Core/WebView/WebViewNavigationDelegate.swift +395 -0
  113. package/dist/native/iosnativeWebView/iosnativeWebView/AppDelegate.swift +84 -0
  114. package/dist/native/iosnativeWebView/iosnativeWebView/Assets.xcassets/AccentColor.colorset/Contents.json +8 -8
  115. package/dist/native/iosnativeWebView/iosnativeWebView/Assets.xcassets/AppIcon.appiconset/Contents.json +10 -10
  116. package/dist/native/iosnativeWebView/iosnativeWebView/Assets.xcassets/Contents.json +4 -4
  117. package/dist/native/iosnativeWebView/iosnativeWebView/ContentView.swift +65 -10
  118. package/dist/native/iosnativeWebView/iosnativeWebView/Info-Release.plist +21 -0
  119. package/dist/native/iosnativeWebView/iosnativeWebView/Info.plist +13 -0
  120. package/dist/native/iosnativeWebView/iosnativeWebView/Preview Content/Preview Assets.xcassets/Contents.json +4 -4
  121. package/dist/native/iosnativeWebView/iosnativeWebView/iosnativeWebView.entitlements +12 -0
  122. package/dist/native/iosnativeWebView/iosnativeWebView/iosnativeWebViewApp.swift +80 -0
  123. package/dist/native/iosnativeWebView/iosnativeWebView/localhost.p12 +0 -0
  124. package/dist/native/iosnativeWebView/iosnativeWebView.xcodeproj/project.pbxproj +118 -100
  125. package/dist/native/iosnativeWebView/iosnativeWebView.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +69 -0
  126. package/dist/native/iosnativeWebView/iosnativeWebView.xcodeproj/xcshareddata/xcschemes/iosnativeWebView.xcscheme +9 -4
  127. package/dist/native/iosnativeWebView/iosnativeWebView.xctestplan +47 -0
  128. package/dist/native/iosnativeWebView/iosnativeWebViewTests/BootTimingUtilityTests.swift +236 -0
  129. package/dist/native/iosnativeWebView/iosnativeWebViewTests/BridgeCommandHandlerSecurityTests.swift +212 -0
  130. package/dist/native/iosnativeWebView/iosnativeWebViewTests/BridgeMessageValidatorTests.swift +418 -0
  131. package/dist/native/iosnativeWebView/iosnativeWebViewTests/CacheManagerTests.swift +390 -0
  132. package/dist/native/iosnativeWebView/iosnativeWebViewTests/ConfigMappingTests.swift +299 -0
  133. package/dist/native/iosnativeWebView/iosnativeWebViewTests/FilePickerHandlerTests.swift +383 -0
  134. package/dist/native/iosnativeWebView/iosnativeWebViewTests/FrameworkServerUtilsTests.swift +391 -0
  135. package/dist/native/iosnativeWebView/iosnativeWebViewTests/NativeBridgeTests.swift +581 -0
  136. package/dist/native/iosnativeWebView/iosnativeWebViewTests/NotificationHandlerTests.swift +430 -0
  137. package/dist/native/iosnativeWebView/iosnativeWebViewTests/ScreenSecureManagerTests.swift +121 -0
  138. package/dist/native/iosnativeWebView/iosnativeWebViewTests/URLWhitelistManagerTests.swift +367 -0
  139. package/dist/native/iosnativeWebView/iosnativeWebViewTests/WebViewTests.swift +440 -0
  140. package/dist/native/renameAndroidProject.js +80 -70
  141. package/dist/native/setupEmulatorIos.js +22 -5
  142. package/dist/native/setupServer.js +11 -10
  143. package/dist/native/terminalProgress.js +10 -10
  144. package/dist/native/utils.js +4 -5
  145. package/dist/otel.js +4 -0
  146. package/dist/scripts/build.js +2 -2
  147. package/dist/scripts/devBuild.js +2 -2
  148. package/dist/scripts/loadEnvironmentVariables.js +3 -1
  149. package/dist/scripts/scriptUtils.js +2 -2
  150. package/dist/sentry.js +4 -1
  151. package/dist/server/renderer/document/Body.js +4 -4
  152. package/dist/server/renderer/handler.js +7 -5
  153. package/dist/webpack/development.client.babel.js +1 -1
  154. package/mcp_v2/conversion-tasks.json +326 -0
  155. package/mcp_v2/knowledge-base.json +1068 -0
  156. package/mcp_v2/lib/helpers.js +165 -0
  157. package/mcp_v2/mcp.js +563 -0
  158. package/mcp_v2/package.json +13 -0
  159. package/mcp_v2/schema.sql +88 -0
  160. package/mcp_v2/setup.js +278 -0
  161. package/mcp_v2/tools/build.js +686 -0
  162. package/mcp_v2/tools/config.js +453 -0
  163. package/mcp_v2/tools/conversion.js +799 -0
  164. package/mcp_v2/tools/debug.js +113 -0
  165. package/mcp_v2/tools/knowledge.js +219 -0
  166. package/mcp_v2/tools/sync.js +23 -0
  167. package/mcp_v2/tools/tasks.js +945 -0
  168. package/package.json +11 -15
  169. package/dist/native/androidProject/.idea/.name +0 -1
  170. package/dist/native/androidProject/.idea/AndroidProjectSystem.xml +0 -6
  171. package/dist/native/androidProject/.idea/compiler.xml +0 -6
  172. package/dist/native/androidProject/.idea/deploymentTargetSelector.xml +0 -10
  173. package/dist/native/androidProject/.idea/gradle.xml +0 -18
  174. package/dist/native/androidProject/.idea/migrations.xml +0 -10
  175. package/dist/native/androidProject/.idea/misc.xml +0 -10
  176. package/dist/native/androidProject/.idea/runConfigurations.xml +0 -17
  177. package/dist/native/androidProject/.idea/vcs.xml +0 -6
  178. package/dist/native/iosnativeWebView/iosnativeWebView/NativeBridge.swift +0 -217
  179. package/dist/native/iosnativeWebView/iosnativeWebView/WebView.swift +0 -96
  180. package/dist/native/iosnativeWebView/iosnativeWebView/WebViewModel.swift +0 -47
  181. package/dist/native/iosnativeWebView/iosnativeWebView/WebViewNavigationDelegate.swift +0 -140
  182. package/license +0 -10
@@ -9,13 +9,131 @@ import android.webkit.JavascriptInterface
9
9
  import android.webkit.WebView
10
10
  import androidx.activity.result.ActivityResultLauncher
11
11
  import androidx.activity.result.contract.ActivityResultContracts
12
+ import androidx.core.app.NotificationCompat
13
+ import androidx.credentials.CredentialManager
14
+ import androidx.credentials.GetCredentialRequest
15
+ import androidx.credentials.exceptions.GetCredentialCancellationException
16
+ import androidx.credentials.exceptions.GetCredentialException
17
+ import com.google.android.libraries.identity.googleid.GetSignInWithGoogleOption
18
+ import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential
12
19
  import io.yourname.androidproject.MainActivity
13
20
  import io.yourname.androidproject.utils.*
14
21
  import kotlinx.coroutines.*
22
+ import org.json.JSONArray
23
+ import org.json.JSONObject
24
+ import java.util.Properties
25
+ import java.util.concurrent.atomic.AtomicBoolean
15
26
 
16
- class NativeBridge(private val mainActivity: MainActivity, private val webView: WebView) : CoroutineScope {
27
+ private data class FilePickerOptions(
28
+ val mimeType: String = "*/*",
29
+ val multiple: Boolean = false,
30
+ val minFiles: Int? = null,
31
+ val maxFiles: Int? = null,
32
+ val minFileSize: Long? = null,
33
+ val maxFileSize: Long? = null
34
+ ) {
35
+ companion object {
36
+ fun fromRaw(optionsRaw: String?): FilePickerOptions {
37
+ if (optionsRaw.isNullOrBlank()) {
38
+ return FilePickerOptions()
39
+ }
40
+
41
+ val trimmed = optionsRaw.trim()
42
+
43
+ // Backward compatibility: plain MIME type strings
44
+ if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) {
45
+ return FilePickerOptions(mimeType = trimmed.ifBlank { "*/*" })
46
+ }
47
+
48
+ return try {
49
+ val json = JSONObject(trimmed)
50
+
51
+ val mimeType = json.optString("mimeType").ifBlank { "*/*" }
52
+ val explicitMultiple = json.optBoolean("multiple", false)
53
+ val minFiles = json.optIntNullable("minFiles")
54
+ val maxFiles = json.optIntNullable("maxFiles")
55
+ val minFileSize = json.optLongNullable("minFileSize")
56
+ val maxFileSize = json.optLongNullable("maxFileSize")
57
+
58
+ // Auto-enable multiple select when constraints demand more than one file
59
+ val shouldAllowMultiple = explicitMultiple ||
60
+ (minFiles != null && minFiles > 1) ||
61
+ (maxFiles != null && maxFiles > 1)
62
+
63
+ FilePickerOptions(
64
+ mimeType = mimeType,
65
+ multiple = shouldAllowMultiple,
66
+ minFiles = minFiles,
67
+ maxFiles = maxFiles,
68
+ minFileSize = minFileSize,
69
+ maxFileSize = maxFileSize
70
+ )
71
+ } catch (e: Exception) {
72
+ Log.e("FilePickerOptions", "Failed to parse options JSON", e)
73
+ FilePickerOptions(mimeType = trimmed.ifBlank { "*/*" })
74
+ }
75
+ }
76
+ }
77
+
78
+ fun toJson(): JSONObject {
79
+ val json = JSONObject()
80
+ json.put("mimeType", mimeType)
81
+ json.put("multiple", multiple)
82
+ minFiles?.let { json.put("minFiles", it) }
83
+ maxFiles?.let { json.put("maxFiles", it) }
84
+ minFileSize?.let { json.put("minFileSize", it) }
85
+ maxFileSize?.let { json.put("maxFileSize", it) }
86
+ return json
87
+ }
88
+ }
89
+
90
+ private fun JSONObject.optIntNullable(key: String): Int? =
91
+ if (has(key) && !isNull(key)) getInt(key) else null
92
+
93
+ private fun JSONObject.optLongNullable(key: String): Long? =
94
+ if (has(key) && !isNull(key)) getLong(key) else null
95
+
96
+ private data class GoogleSignInOptions(
97
+ val clientId: String,
98
+ val nonce: String? = null,
99
+ val autoSelect: Boolean = false,
100
+ val filterByAuthorizedAccounts: Boolean = false
101
+ ) {
102
+ companion object {
103
+ fun fromRaw(raw: String?): GoogleSignInOptions {
104
+ if (raw.isNullOrBlank()) {
105
+ // Allow fallback to config-supplied clientId
106
+ return GoogleSignInOptions(clientId = "")
107
+ }
108
+
109
+ return try {
110
+ val json = JSONObject(raw)
111
+ val resolvedClientId = json.optString("clientId")
112
+ .ifBlank { json.optString("webClientId") }
113
+
114
+ GoogleSignInOptions(
115
+ clientId = resolvedClientId,
116
+ nonce = json.optString("nonce").takeIf { it.isNotBlank() },
117
+ autoSelect = json.optBoolean("autoSelect", false),
118
+ filterByAuthorizedAccounts = json.optBoolean("filterByAuthorizedAccounts", false)
119
+ )
120
+ } catch (e: Exception) {
121
+ BridgeUtils.logDebug("NativeBridge", "Failed to parse options JSON: ${e.message}")
122
+ GoogleSignInOptions(clientId = raw.trim())
123
+ }
124
+ }
125
+ }
126
+ }
127
+
128
+ class NativeBridge(
129
+ private val mainActivity: MainActivity,
130
+ private val webView: WebView,
131
+ private val properties: Properties
132
+ ) : CoroutineScope {
17
133
  private var currentPhotoUri: Uri? = null
18
134
  private var shouldLaunchCameraAfterPermission = false
135
+ private var allowedUrls: List<String> = emptyList()
136
+ private var accessControlEnabled: Boolean = false
19
137
 
20
138
  // Coroutine scope for async operations
21
139
  private val supervisorJob = SupervisorJob()
@@ -24,19 +142,89 @@ class NativeBridge(private val mainActivity: MainActivity, private val webView:
24
142
  private lateinit var cameraLauncher: ActivityResultLauncher<Uri>
25
143
  private lateinit var permissionLauncher: ActivityResultLauncher<String>
26
144
  private lateinit var filePickerLauncher: ActivityResultLauncher<Intent>
145
+ private var currentFilePickerOptions: FilePickerOptions = FilePickerOptions()
146
+ private val isGoogleSignInInProgress = AtomicBoolean(false)
147
+ private val credentialManager: CredentialManager by lazy { CredentialManager.create(mainActivity) }
148
+ private val isGoogleSignInEnabled: Boolean by lazy {
149
+ properties.getProperty("googleSignIn.enabled", "false").toBoolean()
150
+ }
151
+
152
+ private var networkMonitor: NetworkMonitor? = null
153
+
154
+ // Unified notification manager
155
+ private val notificationManager = AppNotificationManager(mainActivity, mainActivity.properties)
27
156
 
28
157
  companion object {
29
158
  private const val TAG = "NativeBridge"
159
+ private const val GOOGLE_SIGN_IN_SAFE_EXECUTE_ACTION = "start Google Sign-In"
160
+
161
+ /**
162
+ * Parse and validate bridge message
163
+ * @param messageJson JSON string containing bridge message
164
+ * @return BridgeValidationResult with validation status
165
+ */
166
+ fun parseAndValidateMessage(messageJson: String): BridgeValidationResult {
167
+ return try {
168
+ val jsonObject = org.json.JSONObject(messageJson)
169
+ BridgeMessageValidator.validate(jsonObject)
170
+ } catch (e: org.json.JSONException) {
171
+ BridgeUtils.logError(TAG, "Failed to parse message JSON", e)
172
+ BridgeValidationResult(
173
+ isValid = false,
174
+ command = null,
175
+ params = null,
176
+ body = null,
177
+ error = BridgeValidationError(
178
+ message = "Invalid JSON format: ${e.message}",
179
+ code = "INVALID_JSON",
180
+ eventName = "BRIDGE_ERROR"
181
+ )
182
+ )
183
+ } catch (e: Exception) {
184
+ BridgeUtils.logError(TAG, "Unexpected error during validation", e)
185
+ BridgeValidationResult(
186
+ isValid = false,
187
+ command = null,
188
+ params = null,
189
+ body = null,
190
+ error = BridgeValidationError(
191
+ message = "Validation error: ${e.message}",
192
+ code = "VALIDATION_ERROR",
193
+ eventName = "BRIDGE_ERROR"
194
+ )
195
+ )
196
+ }
197
+ }
30
198
  }
31
199
 
32
200
  init {
33
201
  try {
202
+ // Load allowed URLs from properties for whitelisting
203
+ allowedUrls = properties.getProperty("accessControl.allowedUrls", "")
204
+ .split(",")
205
+ .map { it.trim() }
206
+ .filter { it.isNotEmpty() }
207
+
208
+ accessControlEnabled = properties
209
+ .getProperty("accessControl.enabled", "true")
210
+ .equals("true", ignoreCase = true)
211
+
212
+ if (accessControlEnabled && allowedUrls.isNotEmpty()) {
213
+ BridgeUtils.logDebug(TAG, "Whitelisting enabled with ${allowedUrls.size} allowed URLs")
214
+ } else if (!accessControlEnabled) {
215
+ BridgeUtils.logDebug(TAG, "Access control disabled; whitelist checks will be skipped")
216
+ }
217
+
34
218
  initializeCameraLauncher()
35
219
  initializePermissionLauncher()
36
220
  initializeFilePickerLauncher()
37
-
221
+
38
222
  // Initialize FrameworkServer for large file handling
39
223
  initializeFrameworkServer()
224
+
225
+ // Initialize NotificationManager and set WebView reference
226
+ notificationManager.initialize()
227
+ notificationManager.setWebViewReference(webView)
40
228
  } catch (e: Exception) {
41
229
  BridgeUtils.logError(TAG, "Error initializing NativeBridge", e)
42
230
  }
@@ -95,6 +283,55 @@ class NativeBridge(private val mainActivity: MainActivity, private val webView:
95
283
  }
96
284
  }
97
285
 
286
+ @JavascriptInterface
287
+ fun googleSignIn(optionsRaw: String?) {
288
+ BridgeUtils.safeExecute(
289
+ webView,
290
+ BridgeUtils.WebEvents.ON_GOOGLE_SIGN_IN_ERROR,
291
+ GOOGLE_SIGN_IN_SAFE_EXECUTE_ACTION
292
+ ) {
293
+ if (!isGoogleSignInEnabled) {
294
+ BridgeUtils.notifyWebError(
295
+ webView,
296
+ BridgeUtils.WebEvents.ON_GOOGLE_SIGN_IN_ERROR,
297
+ "Google Sign-In is disabled in config"
298
+ )
299
+ return@safeExecute
300
+ }
301
+
302
+ val options = GoogleSignInOptions.fromRaw(optionsRaw)
303
+
304
+ val resolvedClientId = when {
305
+ options.clientId.isNotBlank() -> options.clientId
306
+ !properties.getProperty("googleSignIn.clientId", "").isNullOrBlank() ->
307
+ properties.getProperty("googleSignIn.clientId", "")
308
+ else -> ""
309
+ }
310
+
311
+ if (resolvedClientId.isBlank()) {
312
+ BridgeUtils.notifyWebError(
313
+ webView,
314
+ BridgeUtils.WebEvents.ON_GOOGLE_SIGN_IN_ERROR,
315
+ "clientId is required for Google Sign-In"
316
+ )
317
+ return@safeExecute
318
+ }
319
+
320
+ if (!isGoogleSignInInProgress.compareAndSet(false, true)) {
321
+ BridgeUtils.notifyWebError(
322
+ webView,
323
+ BridgeUtils.WebEvents.ON_GOOGLE_SIGN_IN_ERROR,
324
+ "A Google Sign-In request is already in progress"
325
+ )
326
+ return@safeExecute
327
+ }
328
+
329
+ BridgeUtils.logDebug(TAG, "Google Sign-In using clientId prefix: ${resolvedClientId.take(12)}...")
330
+
331
+ launchGoogleSignIn(options.copy(clientId = resolvedClientId))
332
+ }
333
+ }
334
+
98
335
  @JavascriptInterface
99
336
  fun openFileWithIntent(params: String?) {
100
337
  BridgeUtils.safeExecute(webView, BridgeUtils.WebEvents.ON_INTENT_ERROR, "open file with intent") {
@@ -114,20 +351,50 @@ class NativeBridge(private val mainActivity: MainActivity, private val webView:
114
351
  }
115
352
 
116
353
  @JavascriptInterface
117
- fun pickFile(mimeType: String?) {
354
+ fun pickFile(optionsJson: String?) {
118
355
  BridgeUtils.safeExecute(webView, BridgeUtils.WebEvents.ON_FILE_PICK_ERROR, "pick file") {
119
356
  mainActivity.runOnUiThread {
357
+ currentFilePickerOptions = FilePickerOptions.fromRaw(optionsJson)
358
+
120
359
  BridgeUtils.logDebug(TAG, "pickFile called from JavaScript")
121
- BridgeUtils.logDebug(TAG, "MIME Type filter: ${mimeType ?: "*/*"}")
360
+ BridgeUtils.logDebug(TAG, "Options: $currentFilePickerOptions")
122
361
 
123
- // Send initial state
362
+ // Send initial state to web layer
124
363
  FileUtils.sendFilePickStateUpdate(webView, "opening")
125
364
 
126
- val effectiveMimeType = mimeType?.takeIf { it.isNotBlank() } ?: "*/*"
127
- BridgeUtils.logDebug(TAG, "Effective MIME Type: $effectiveMimeType")
365
+ // Launch file picker with resolved configuration
366
+ launchFilePicker(currentFilePickerOptions)
367
+ }
368
+ }
369
+ }
128
370
 
129
- // Launch file picker
130
- launchFilePicker(effectiveMimeType)
371
+ @JavascriptInterface
372
+ fun getNetworkStatus(param: String? = null) {
373
+ BridgeUtils.safeExecute(webView, BridgeUtils.WebEvents.NETWORK_STATUS_CHANGED, "get network status") {
374
+ // Lazily start monitor on first request
375
+ if (networkMonitor == null) {
376
+ networkMonitor = NetworkMonitor(mainActivity) { status ->
377
+ mainActivity.runOnUiThread {
378
+ try {
379
+ val payload = JSONObject().apply {
380
+ put("online", status.isOnline)
381
+ status.transport?.let { put("type", it) }
382
+ }
383
+ BridgeUtils.notifyWebJson(webView, BridgeUtils.WebEvents.NETWORK_STATUS_CHANGED, payload)
384
+ } catch (e: Exception) {
385
+ BridgeUtils.logError(TAG, "Failed to send network status to web: ${e.message}")
386
+ }
387
+ }
388
+ }.also { it.start() }
389
+ } else {
390
+ val status = NetworkUtils.getCurrentStatus(mainActivity)
391
+ val payload = JSONObject().apply {
392
+ put("online", status.isOnline)
393
+ status.transport?.let { put("type", it) }
394
+ }
395
+ mainActivity.runOnUiThread {
396
+ BridgeUtils.notifyWebJson(webView, BridgeUtils.WebEvents.NETWORK_STATUS_CHANGED, payload)
397
+ }
131
398
  }
132
399
  }
133
400
  }
@@ -136,12 +403,231 @@ class NativeBridge(private val mainActivity: MainActivity, private val webView:
136
403
  fun getDeviceInfo(options: String?) {
137
404
  BridgeUtils.safeExecute(webView, BridgeUtils.WebEvents.ON_DEVICE_INFO_ERROR, "get device info") {
138
405
  mainActivity.runOnUiThread {
139
- val deviceInfo = DeviceInfoUtils.getDeviceInfo(mainActivity)
406
+ val deviceInfo = DeviceInfoUtils.getDeviceInfo(mainActivity, properties)
140
407
  BridgeUtils.logDebug(TAG, "Device info retrieved: $deviceInfo")
141
408
  BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.ON_DEVICE_INFO_SUCCESS, deviceInfo.toString())
142
409
  }
143
410
  }
144
411
  }
412
+
413
+ @JavascriptInterface
414
+ fun scheduleLocalNotification(config: String?) {
415
+ BridgeUtils.safeExecute(webView, BridgeUtils.WebEvents.LOCAL_NOTIFICATION_SCHEDULED, "schedule local notification") {
416
+ mainActivity.runOnUiThread {
417
+ try {
418
+ // Parse config with full NotificationConfig support
419
+ val notificationConfig = if (config.isNullOrBlank()) {
420
+ NotificationConfig(title = NotificationConstants.DEFAULT_NOTIFICATION_TITLE, body = NotificationConstants.DEFAULT_NOTIFICATION_BODY)
421
+ } else {
422
+ val json = org.json.JSONObject(config)
423
+
424
+ // Parse actions array with title and actionId
425
+ val actions = if (json.has("actions")) {
426
+ val actionsArray = json.getJSONArray("actions")
427
+ val actionsList = mutableListOf<NotificationAction>()
428
+ for (i in 0 until actionsArray.length()) {
429
+ val actionObj = actionsArray.getJSONObject(i)
430
+ actionsList.add(
431
+ NotificationAction(
432
+ title = actionObj.getString("title"),
433
+ actionId = actionObj.getString("action")
434
+ )
435
+ )
436
+ }
437
+ actionsList
438
+ } else null
439
+
440
+ // Parse data map if present - support Any type
441
+ val data = if (json.has("data")) {
442
+ val dataObj = json.getJSONObject("data")
443
+ val dataMap = mutableMapOf<String, Any>()
444
+ dataObj.keys().forEach { key ->
445
+ dataMap[key] = dataObj.get(key)
446
+ }
447
+ dataMap
448
+ } else null
449
+
450
+ // Parse style enum if present
451
+ val style = if (json.has("style")) {
452
+ try {
453
+ NotificationStyle.valueOf(json.getString("style"))
454
+ } catch (e: IllegalArgumentException) {
455
+ NotificationStyle.BASIC
456
+ }
457
+ } else NotificationStyle.BASIC
458
+
459
+ NotificationConfig(
460
+ title = json.optString("title", NotificationConstants.DEFAULT_NOTIFICATION_TITLE),
461
+ body = json.optString("body", NotificationConstants.DEFAULT_NOTIFICATION_BODY),
462
+ channel = json.optString("channel", NotificationConstants.DEFAULT_CHANNEL_ID),
463
+ badge = if (json.has("badge")) json.getInt("badge") else null,
464
+ actions = actions,
465
+ largeImage = json.optString("largeImage", null),
466
+ style = style,
467
+ priority = json.optInt("priority", NotificationCompat.PRIORITY_DEFAULT),
468
+ vibrate = json.optBoolean("vibrate", true),
469
+ autoCancel = json.optBoolean("autoCancel", true),
470
+ ongoing = json.optBoolean("ongoing", false),
471
+ data = data
472
+ )
473
+ }
474
+
475
+ val notificationId = notificationManager.scheduleLocal(notificationConfig)
476
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.LOCAL_NOTIFICATION_SCHEDULED,
477
+ """{"notificationId": "$notificationId", "scheduled": true, "success": true}""")
478
+
479
+ // Emit received event
480
+ val payload = org.json.JSONObject().apply {
481
+ put("title", notificationConfig.title)
482
+ put("body", notificationConfig.body)
483
+ notificationConfig.data?.let { dataMap ->
484
+ put("data", org.json.JSONObject(dataMap))
485
+ }
486
+ put("foreground", false)
487
+ put("notificationId", notificationId)
488
+ }
489
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.NOTIFICATION_RECEIVED, payload.toString())
490
+ } catch (e: Exception) {
491
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.LOCAL_NOTIFICATION_SCHEDULED,
492
+ """{"notificationId": "", "scheduled": false, "success": false, "error": "Failed to schedule notification: ${e.message}"}""")
493
+ }
494
+ }
495
+ }
496
+ }
497
+
498
+ @JavascriptInterface
499
+ fun cancelLocalNotification(notificationId: String?) {
500
+ BridgeUtils.safeExecute(webView, BridgeUtils.WebEvents.LOCAL_NOTIFICATION_CANCELLED, "cancel local notification") {
501
+ mainActivity.runOnUiThread {
502
+ try {
503
+ val success = notificationManager.cancelLocal(notificationId)
504
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.LOCAL_NOTIFICATION_CANCELLED,
505
+ """{"notificationId": "${notificationId ?: ""}", "success": $success}""")
506
+ } catch (e: Exception) {
507
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.LOCAL_NOTIFICATION_CANCELLED,
508
+ """{"notificationId": "${notificationId ?: ""}", "success": false, "error": "Failed to cancel notification: ${e.message}"}""")
509
+ }
510
+ }
511
+ }
512
+ }
513
+
514
+ @JavascriptInterface
515
+ fun requestNotificationPermission(config: String?) {
516
+ BridgeUtils.safeExecute(webView, BridgeUtils.WebEvents.NOTIFICATION_PERMISSION_STATUS, "request notification permission") {
517
+ mainActivity.runOnUiThread {
518
+ notificationManager.requestPermission(mainActivity) { granted ->
519
+ val status = if (granted) "GRANTED" else "DENIED"
520
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.NOTIFICATION_PERMISSION_STATUS, status)
521
+ }
522
+ }
523
+ }
524
+ }
525
+
526
+ @JavascriptInterface
527
+ fun checkNotificationPermissionStatus(config: String?) {
528
+ BridgeUtils.safeExecute(webView, BridgeUtils.WebEvents.NOTIFICATION_PERMISSION_STATUS, "check notification permission status") {
529
+ val status = notificationManager.checkPermissionStatus()
530
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.NOTIFICATION_PERMISSION_STATUS, status)
531
+ }
532
+ }
533
+
534
+ @JavascriptInterface
535
+ fun registerForPushNotifications(config: String?) {
536
+ BridgeUtils.safeExecute(webView, BridgeUtils.WebEvents.PUSH_NOTIFICATION_TOKEN, "register for push notifications") {
537
+ mainActivity.runOnUiThread {
538
+ launch {
539
+ try {
540
+ val token = notificationManager.initializePush()
541
+ if (token.isBlank()) {
542
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.PUSH_NOTIFICATION_TOKEN,
543
+ """{"success": false, "error": "Push registration returned empty token"}""")
544
+ } else {
545
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.PUSH_NOTIFICATION_TOKEN,
546
+ """{"token": "$token", "success": true}""")
547
+ }
548
+ } catch (e: Exception) {
549
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.PUSH_NOTIFICATION_TOKEN,
550
+ """{"success": false, "error": "Push registration failed: ${e.message}"}""")
551
+ }
552
+ }
553
+ }
554
+ }
555
+ }
556
+
557
+
558
+ @JavascriptInterface
559
+ fun subscribeToTopic(config: String?) {
560
+ BridgeUtils.safeExecute(webView, BridgeUtils.WebEvents.TOPIC_SUBSCRIPTION_RESULT, "subscribe to topic") {
561
+ mainActivity.runOnUiThread {
562
+ launch {
563
+ try {
564
+ val json = org.json.JSONObject(config ?: "{}")
565
+ val topic = json.optString("topic", "")
566
+
567
+ if (topic.isBlank()) {
568
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.TOPIC_SUBSCRIPTION_RESULT,
569
+ """{"topic": "$topic", "success": false, "error": "Topic name cannot be empty", "action": "subscribe"}""")
570
+ return@launch
571
+ }
572
+
573
+ val success = notificationManager.subscribeToTopic(topic)
574
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.TOPIC_SUBSCRIPTION_RESULT,
575
+ """{"topic": "$topic", "success": $success, "action": "subscribe"}""")
576
+
577
+ } catch (e: Exception) {
578
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.TOPIC_SUBSCRIPTION_RESULT,
579
+ """{"topic": "", "success": false, "error": "Topic subscription failed: ${e.message}", "action": "subscribe"}""")
580
+ }
581
+ }
582
+ }
583
+ }
584
+ }
585
+
586
+ @JavascriptInterface
587
+ fun unsubscribeFromTopic(config: String?) {
588
+ BridgeUtils.safeExecute(webView, BridgeUtils.WebEvents.TOPIC_SUBSCRIPTION_RESULT, "unsubscribe from topic") {
589
+ mainActivity.runOnUiThread {
590
+ launch {
591
+ try {
592
+ val json = org.json.JSONObject(config ?: "{}")
593
+ val topic = json.optString("topic", "")
594
+
595
+ if (topic.isBlank()) {
596
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.TOPIC_SUBSCRIPTION_RESULT,
597
+ """{"topic": "$topic", "success": false, "error": "Topic name cannot be empty", "action": "unsubscribe"}""")
598
+ return@launch
599
+ }
600
+
601
+ val success = notificationManager.unsubscribeFromTopic(topic)
602
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.TOPIC_SUBSCRIPTION_RESULT,
603
+ """{"topic": "$topic", "success": $success, "action": "unsubscribe"}""")
604
+
605
+ } catch (e: Exception) {
606
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.TOPIC_SUBSCRIPTION_RESULT,
607
+ """{"topic": "", "success": false, "error": "Topic unsubscription failed: ${e.message}", "action": "unsubscribe"}""")
608
+ }
609
+ }
610
+ }
611
+ }
612
+ }
613
+
614
+ @JavascriptInterface
615
+ fun getSubscribedTopics(config: String?) {
616
+ BridgeUtils.safeExecute(webView, BridgeUtils.WebEvents.SUBSCRIBED_TOPICS_RESULT, "get subscribed topics") {
617
+ mainActivity.runOnUiThread {
618
+ try {
619
+ val topics = notificationManager.getSubscribedTopics()
620
+ val topicsArray = org.json.JSONArray(topics.toList())
621
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.SUBSCRIBED_TOPICS_RESULT,
622
+ """{"topics": $topicsArray, "success": true}""")
623
+
624
+ } catch (e: Exception) {
625
+ BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.SUBSCRIBED_TOPICS_RESULT,
626
+ """{"topics": [], "success": false, "error": "Failed to get subscribed topics: ${e.message}"}""")
627
+ }
628
+ }
629
+ }
630
+ }
145
631
 
146
632
  private fun initializeCameraLauncher() {
147
633
  cameraLauncher = mainActivity.registerForActivityResult(ActivityResultContracts.TakePicture()) { success ->
@@ -167,16 +653,43 @@ class NativeBridge(private val mainActivity: MainActivity, private val webView:
167
653
  ) { result ->
168
654
  when (result.resultCode) {
169
655
  Activity.RESULT_OK -> {
170
- result.data?.data?.let { uri ->
171
- BridgeUtils.logDebug(TAG, "File selected: $uri")
172
- FileUtils.sendFilePickStateUpdate(webView, "processing")
173
-
174
- BridgeUtils.safeExecute(webView, BridgeUtils.WebEvents.ON_FILE_PICK_ERROR, "process selected file") {
175
- // Use new tri-transport processing
176
- processSelectedFileWithTriTransport(uri)
656
+ val data = result.data
657
+ val options = currentFilePickerOptions
658
+ val selectedUris = mutableListOf<Uri>()
659
+
660
+ val clipData = data?.clipData
661
+ if (clipData != null) {
662
+ for (index in 0 until clipData.itemCount) {
663
+ clipData.getItemAt(index)?.uri?.let { selectedUris.add(it) }
177
664
  }
178
- } ?: run {
179
- BridgeUtils.notifyWebError(webView, BridgeUtils.WebEvents.ON_FILE_PICK_ERROR, "No file selected")
665
+ } else {
666
+ data?.data?.let { selectedUris.add(it) }
667
+ }
668
+
669
+ if (selectedUris.isEmpty()) {
670
+ notifyFilePickError("No file selected")
671
+ return@registerForActivityResult
672
+ }
673
+
674
+ BridgeUtils.logDebug(
675
+ TAG,
676
+ "Files selected (${selectedUris.size}): ${selectedUris.joinToString { it.toString() }}"
677
+ )
678
+
679
+ if (!validateFileSelectionCount(selectedUris.size, options)) {
680
+ return@registerForActivityResult
681
+ }
682
+
683
+ val urisToProcess = sanitizeSelectionForSingleSelect(selectedUris, options)
684
+
685
+ FileUtils.sendFilePickStateUpdate(webView, "processing")
686
+
687
+ BridgeUtils.safeExecute(
688
+ webView,
689
+ BridgeUtils.WebEvents.ON_FILE_PICK_ERROR,
690
+ "process selected files"
691
+ ) {
692
+ processSelectedFiles(urisToProcess, options)
180
693
  }
181
694
  }
182
695
  Activity.RESULT_CANCELED -> {
@@ -208,66 +721,292 @@ class NativeBridge(private val mainActivity: MainActivity, private val webView:
208
721
  }
209
722
  }
210
723
  }
724
+
725
+ private fun launchGoogleSignIn(options: GoogleSignInOptions) {
726
+ launch {
727
+ try {
728
+ val googleOptionBuilder = GetSignInWithGoogleOption.Builder(options.clientId)
729
+ options.nonce?.let { googleOptionBuilder.setNonce(it) }
730
+ val googleOption = googleOptionBuilder.build()
731
+
732
+ val request = GetCredentialRequest.Builder()
733
+ .addCredentialOption(googleOption)
734
+ .build()
735
+
736
+ BridgeUtils.logDebug(
737
+ TAG,
738
+ "Starting Google Sign-In via CredentialManager (hasNonce=${options.nonce != null})"
739
+ )
740
+
741
+ val response = credentialManager.getCredential(mainActivity, request)
742
+ handleCredentialResponse(response)
743
+ } catch (e: GetCredentialCancellationException) {
744
+ isGoogleSignInInProgress.set(false)
745
+ BridgeUtils.logDebug(
746
+ TAG,
747
+ "Google Sign-In cancelled: ${e.message} :: ${e.javaClass.simpleName}"
748
+ )
749
+ BridgeUtils.notifyWeb(
750
+ webView,
751
+ BridgeUtils.WebEvents.ON_GOOGLE_SIGN_IN_CANCELLED,
752
+ "User cancelled Google sign-in"
753
+ )
754
+ } catch (e: GetCredentialException) {
755
+ isGoogleSignInInProgress.set(false)
756
+ val message = e.errorMessage?.toString() ?: e.message ?: "Credential request failed"
757
+ BridgeUtils.logError(
758
+ TAG,
759
+ "Google Sign-In credential error: $message :: ${e.javaClass.simpleName}",
760
+ e
761
+ )
762
+ BridgeUtils.notifyWebError(
763
+ webView,
764
+ BridgeUtils.WebEvents.ON_GOOGLE_SIGN_IN_ERROR,
765
+ message
766
+ )
767
+ } catch (e: Exception) {
768
+ isGoogleSignInInProgress.set(false)
769
+ BridgeUtils.logError(
770
+ TAG,
771
+ "Google Sign-In unexpected error: ${e.message} :: ${e.javaClass.simpleName}",
772
+ e
773
+ )
774
+ BridgeUtils.notifyWebError(
775
+ webView,
776
+ BridgeUtils.WebEvents.ON_GOOGLE_SIGN_IN_ERROR,
777
+ "Error preparing Google sign-in: ${e.message}"
778
+ )
779
+ }
780
+ }
781
+ }
782
+
783
+ private fun handleCredentialResponse(response: androidx.credentials.GetCredentialResponse) {
784
+ try {
785
+ val credential = response.credential
786
+ if (credential.type != GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL) {
787
+ BridgeUtils.logError(TAG, "Unexpected credential type: ${credential.type}")
788
+ isGoogleSignInInProgress.set(false)
789
+ BridgeUtils.notifyWebError(
790
+ webView,
791
+ BridgeUtils.WebEvents.ON_GOOGLE_SIGN_IN_ERROR,
792
+ "Unsupported credential type returned"
793
+ )
794
+ return
795
+ }
796
+
797
+ val googleCredential = GoogleIdTokenCredential.createFrom(credential.data)
798
+ val idToken = googleCredential.idToken
799
+
800
+ if (idToken.isNullOrBlank()) {
801
+ isGoogleSignInInProgress.set(false)
802
+ BridgeUtils.notifyWebError(
803
+ webView,
804
+ BridgeUtils.WebEvents.ON_GOOGLE_SIGN_IN_ERROR,
805
+ "No ID token returned from Google sign-in"
806
+ )
807
+ return
808
+ }
809
+
810
+ val payload = JSONObject().apply {
811
+ put("idToken", idToken)
812
+ googleCredential.id?.let { put("email", it) }
813
+ googleCredential.displayName?.let { put("name", it) }
814
+ googleCredential.profilePictureUri?.toString()?.let { put("photoUrl", it) }
815
+ put("provider", "google")
816
+ }
817
+
818
+ isGoogleSignInInProgress.set(false)
819
+ BridgeUtils.notifyWebJson(
820
+ webView,
821
+ BridgeUtils.WebEvents.ON_GOOGLE_SIGN_IN_SUCCESS,
822
+ payload
823
+ )
824
+ } catch (e: Exception) {
825
+ isGoogleSignInInProgress.set(false)
826
+ BridgeUtils.notifyWebError(
827
+ webView,
828
+ BridgeUtils.WebEvents.ON_GOOGLE_SIGN_IN_ERROR,
829
+ "Error handling Google credential: ${e.message}"
830
+ )
831
+ }
832
+ }
211
833
 
212
- /**
213
- * Process selected file using tri-transport architecture based on file size
214
- */
215
- private fun processSelectedFileWithTriTransport(uri: Uri) {
834
+ private fun processSelectedFiles(uris: List<Uri>, options: FilePickerOptions) {
216
835
  launch {
217
836
  try {
218
- // Convert URI to File
219
- val file = FileUtils.uriToFile(mainActivity, uri)
220
- if (file == null) {
221
- BridgeUtils.notifyWebError(webView, BridgeUtils.WebEvents.ON_FILE_PICK_ERROR, "Unable to access selected file")
837
+ val filesArray = JSONArray()
838
+ var totalSize = 0L
839
+ var firstFile: JSONObject? = null
840
+
841
+ uris.forEachIndexed { index, uri ->
842
+ val processed = processFile(index, uri, options) ?: return@launch
843
+ filesArray.put(processed)
844
+ totalSize += processed.optLong("size")
845
+ if (firstFile == null) {
846
+ firstFile = processed
847
+ }
848
+ }
849
+
850
+ if (filesArray.length() == 0) {
851
+ notifyFilePickError("No files processed")
222
852
  return@launch
223
853
  }
224
-
225
- BridgeUtils.logDebug(TAG, "Processing file with tri-transport: ${file.name} (${FileSizeRouterUtils.formatFileSize(file.length())})")
226
-
227
- // Determine transport method based on file size
228
- val routingDecision = FileSizeRouterUtils.determineTransport(file)
229
- BridgeUtils.logInfo(TAG, "Transport decision: ${routingDecision.transportType} - ${routingDecision.reason}")
230
-
231
- // Update WebView with transport information
232
- FileUtils.sendFilePickStateUpdate(webView, "routing")
233
-
234
- // Process file using determined transport
235
- val processingResult = FileSizeRouterUtils.processFile(mainActivity, webView, routingDecision)
236
-
237
- if (processingResult.success && processingResult.fileSrc != null) {
238
- // Notify WebView with successful result
239
- val resultData = mapOf(
240
- "fileName" to processingResult.fileName,
241
- "fileSrc" to processingResult.fileSrc,
242
- "filePath" to processingResult.filePath,
243
- "size" to processingResult.fileSize,
244
- "mimeType" to processingResult.mimeType,
245
- "transport" to processingResult.transportUsed.name
246
- )
247
-
248
- BridgeUtils.logInfo(TAG, "File processed successfully via ${processingResult.transportUsed}: ${processingResult.fileName}")
249
- BridgeUtils.notifyWeb(webView, BridgeUtils.WebEvents.ON_FILE_PICKED,
250
- org.json.JSONObject(resultData).toString())
251
-
252
- } else {
253
- // Processing failed
254
- val errorMsg = processingResult.error ?: "Unknown error processing file"
255
- BridgeUtils.logError(TAG, "File processing failed: $errorMsg")
256
- BridgeUtils.notifyWebError(webView, BridgeUtils.WebEvents.ON_FILE_PICK_ERROR, errorMsg)
854
+
855
+ val payload = JSONObject().apply {
856
+ put("multiple", filesArray.length() > 1)
857
+ put("count", filesArray.length())
858
+ put("totalSize", totalSize)
859
+ put("files", filesArray)
860
+ put("options", options.toJson())
861
+ firstFile?.let { first ->
862
+ put("fileName", first.optString("fileName", null))
863
+ put("fileSrc", first.optString("fileSrc", null))
864
+ put("filePath", first.optString("filePath", null))
865
+ put("size", first.optLong("size"))
866
+ put("mimeType", first.optString("mimeType", null))
867
+ put("transport", first.optString("transport", null))
868
+ }
257
869
  }
258
-
870
+
871
+ BridgeUtils.notifyWeb(
872
+ webView,
873
+ BridgeUtils.WebEvents.ON_FILE_PICKED,
874
+ payload.toString()
875
+ )
259
876
  } catch (e: Exception) {
260
- BridgeUtils.logError(TAG, "Error in tri-transport file processing", e)
261
- BridgeUtils.notifyWebError(webView, BridgeUtils.WebEvents.ON_FILE_PICK_ERROR,
262
- "File processing error: ${e.message}")
877
+ BridgeUtils.logError(TAG, "Error processing selected files", e)
878
+ notifyFilePickError("File processing error: ${e.message}")
879
+ }
880
+ }
881
+ }
882
+
883
+ private fun processFile(index: Int, uri: Uri, options: FilePickerOptions): JSONObject? {
884
+ val declaredSize = FileUtils.getFileSize(mainActivity, uri)
885
+ if (!passesSizeBounds(index, declaredSize, options)) {
886
+ return null
887
+ }
888
+
889
+ val file = FileUtils.uriToFile(mainActivity, uri) ?: run {
890
+ val message = "Unable to access selected file at index ${index + 1}"
891
+ BridgeUtils.logError(TAG, message)
892
+ notifyFilePickError(message)
893
+ return null
894
+ }
895
+
896
+ val actualSize = if (file.length() > 0) file.length() else declaredSize
897
+ if (!passesSizeBounds(index, actualSize, options)) {
898
+ return null
899
+ }
900
+
901
+ BridgeUtils.logDebug(
902
+ TAG,
903
+ "Processing file with tri-transport: ${file.name} (${FileSizeRouterUtils.formatFileSize(actualSize)})"
904
+ )
905
+
906
+ val routingDecision = FileSizeRouterUtils.determineTransport(file)
907
+ FileUtils.sendFilePickStateUpdate(webView, "routing")
908
+
909
+ val processingResult = FileSizeRouterUtils.processFile(mainActivity, webView, routingDecision)
910
+ if (!processingResult.success || processingResult.fileSrc == null) {
911
+ val errorMsg = processingResult.error ?: "Unknown error processing file"
912
+ BridgeUtils.logError(TAG, "File processing failed: $errorMsg")
913
+ notifyFilePickError(errorMsg)
914
+ return null
915
+ }
916
+
917
+ return JSONObject().apply {
918
+ put("index", index)
919
+ put("uri", uri.toString())
920
+ put("fileName", processingResult.fileName)
921
+ put("fileSrc", processingResult.fileSrc)
922
+ put("filePath", processingResult.filePath)
923
+ put("size", processingResult.fileSize)
924
+ put("mimeType", processingResult.mimeType)
925
+ put("transport", processingResult.transportUsed.name)
926
+ }
927
+ }
928
+
929
+ private fun passesSizeBounds(index: Int, size: Long, options: FilePickerOptions): Boolean {
930
+ if (size <= 0) return true
931
+
932
+ options.minFileSize?.let { minSize ->
933
+ if (size < minSize) {
934
+ val formattedSize = FileSizeRouterUtils.formatFileSize(size)
935
+ val minFormatted = FileSizeRouterUtils.formatFileSize(minSize)
936
+ val message = "File ${index + 1} is too small ($formattedSize). Minimum size is $minFormatted."
937
+ BridgeUtils.logWarning(TAG, message)
938
+ notifyFilePickError(message)
939
+ return false
263
940
  }
264
941
  }
942
+
943
+ options.maxFileSize?.let { maxSize ->
944
+ if (size > maxSize) {
945
+ val formattedSize = FileSizeRouterUtils.formatFileSize(size)
946
+ val maxFormatted = FileSizeRouterUtils.formatFileSize(maxSize)
947
+ val message = "File ${index + 1} exceeds maximum size ($formattedSize > $maxFormatted)."
948
+ BridgeUtils.logWarning(TAG, message)
949
+ notifyFilePickError(message)
950
+ return false
951
+ }
952
+ }
953
+
954
+ return true
955
+ }
956
+
957
+ private fun validateFileSelectionCount(count: Int, options: FilePickerOptions): Boolean {
958
+ options.minFiles?.let { min ->
959
+ if (count < min) {
960
+ val errorMessage = "Select at least $min file(s). You selected $count."
961
+ BridgeUtils.logWarning(TAG, errorMessage)
962
+ notifyFilePickError(errorMessage)
963
+ return false
964
+ }
965
+ }
966
+
967
+ options.maxFiles?.let { max ->
968
+ if (count > max) {
969
+ val errorMessage = "You can select up to $max file(s). You selected $count."
970
+ BridgeUtils.logWarning(TAG, errorMessage)
971
+ notifyFilePickError(errorMessage)
972
+ return false
973
+ }
974
+ }
975
+
976
+ return true
977
+ }
978
+
979
+ private fun sanitizeSelectionForSingleSelect(
980
+ uris: List<Uri>,
981
+ options: FilePickerOptions
982
+ ): List<Uri> {
983
+ if (options.multiple || uris.size <= 1) {
984
+ return uris
985
+ }
986
+
987
+ BridgeUtils.logWarning(
988
+ TAG,
989
+ "Multiple files selected but picker configured for single selection. Only the first file will be processed."
990
+ )
991
+ return listOf(uris.first())
992
+ }
993
+
994
+ private fun notifyFilePickError(message: String) {
995
+ BridgeUtils.notifyWebError(
996
+ webView,
997
+ BridgeUtils.WebEvents.ON_FILE_PICK_ERROR,
998
+ message
999
+ )
265
1000
  }
266
1001
 
267
- private fun launchFilePicker(mimeType: String) {
1002
+ private fun launchFilePicker(options: FilePickerOptions) {
268
1003
  BridgeUtils.safeExecute(webView, BridgeUtils.WebEvents.ON_FILE_PICK_ERROR, "launch file picker") {
269
- val intent = IntentUtils.createFilePickerIntent(mimeType, false)
270
- BridgeUtils.logDebug(TAG, "Launching file picker with MIME type: $mimeType")
1004
+ val allowMultiple = options.multiple
1005
+ val intent = IntentUtils.createFilePickerIntent(options.mimeType, allowMultiple)
1006
+ BridgeUtils.logDebug(
1007
+ TAG,
1008
+ "Launching file picker with MIME type: ${options.mimeType}, allowMultiple: $allowMultiple"
1009
+ )
271
1010
  filePickerLauncher.launch(intent)
272
1011
  }
273
1012
  }
@@ -280,19 +1019,161 @@ class NativeBridge(private val mainActivity: MainActivity, private val webView:
280
1019
 
281
1020
  // Removed getFileSize - now handled by FileUtils.getFileSize
282
1021
 
1022
+ /**
1023
+ * Handle permission request results
1024
+ */
1025
+ fun handlePermissionResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
1026
+ BridgeUtils.safeExecute(webView, BridgeUtils.WebEvents.NOTIFICATION_PERMISSION_STATUS, "handle permission result") {
1027
+ // Delegate to notification manager which handles notification permissions
1028
+ notificationManager.getNotificationUtils().handlePermissionResult(requestCode, permissions, grantResults)
1029
+ }
1030
+ }
1031
+
1032
+ @JavascriptInterface
1033
+ fun setScreenSecure(params: String?) {
1034
+ mainActivity.runOnUiThread {
1035
+ try {
1036
+ val enable = try {
1037
+ org.json.JSONObject(params ?: "{}").optBoolean("enable", true)
1038
+ } catch (e: Exception) {
1039
+ true
1040
+ }
1041
+ mainActivity.setScreenSecure(enable)
1042
+ BridgeUtils.notifyWeb(
1043
+ webView,
1044
+ BridgeUtils.WebEvents.ON_SCREEN_SECURE_SET,
1045
+ """{"secure": $enable, "success": true}"""
1046
+ )
1047
+ } catch (e: Exception) {
1048
+ // Use notifyWebJson to prevent JSON injection from e.message
1049
+ BridgeUtils.notifyWebJson(
1050
+ webView,
1051
+ BridgeUtils.WebEvents.ON_SCREEN_SECURE_ERROR,
1052
+ org.json.JSONObject().apply {
1053
+ put("success", false)
1054
+ put("error", e.message ?: "setScreenSecure failed")
1055
+ }
1056
+ )
1057
+ }
1058
+ }
1059
+ }
1060
+
1061
+ @JavascriptInterface
1062
+ fun getScreenSecure(params: String?) {
1063
+ mainActivity.runOnUiThread {
1064
+ try {
1065
+ val isSecure = mainActivity.isScreenSecure()
1066
+ BridgeUtils.notifyWebJson(
1067
+ webView,
1068
+ BridgeUtils.WebEvents.ON_SCREEN_SECURE_STATUS,
1069
+ org.json.JSONObject().apply {
1070
+ put("secure", isSecure)
1071
+ put("success", true)
1072
+ }
1073
+ )
1074
+ } catch (e: Exception) {
1075
+ BridgeUtils.notifyWebJson(
1076
+ webView,
1077
+ BridgeUtils.WebEvents.ON_SCREEN_SECURE_ERROR,
1078
+ org.json.JSONObject().apply {
1079
+ put("success", false)
1080
+ put("error", e.message ?: "getScreenSecure failed")
1081
+ }
1082
+ )
1083
+ }
1084
+ }
1085
+ }
1086
+
1087
+ @JavascriptInterface
1088
+ fun clearWebData(params: String?) {
1089
+ mainActivity.runOnUiThread {
1090
+ try {
1091
+ webView.clearCache(true)
1092
+ webView.clearHistory()
1093
+ android.webkit.WebStorage.getInstance().deleteAllData()
1094
+ mainActivity.clearWebCache()
1095
+ // CookieManager.removeAllCookies is async — fire success only from its callback
1096
+ android.webkit.CookieManager.getInstance().removeAllCookies { cookiesRemoved ->
1097
+ android.webkit.CookieManager.getInstance().flush()
1098
+ mainActivity.runOnUiThread {
1099
+ try {
1100
+ // Use notifyWebJson to prevent JSON injection; cookiesRemoved is a
1101
+ // Boolean so string interpolation is safe, but keep consistent pattern
1102
+ BridgeUtils.notifyWebJson(
1103
+ webView,
1104
+ BridgeUtils.WebEvents.ON_WEB_DATA_CLEARED,
1105
+ org.json.JSONObject().apply {
1106
+ put("success", true)
1107
+ put("cookiesRemoved", cookiesRemoved)
1108
+ }
1109
+ )
1110
+ } catch (e: Exception) {
1111
+ BridgeUtils.notifyWebJson(
1112
+ webView,
1113
+ BridgeUtils.WebEvents.ON_WEB_DATA_CLEAR_ERROR,
1114
+ org.json.JSONObject().apply {
1115
+ put("success", false)
1116
+ put("error", e.message ?: "clearWebData cookie flush failed")
1117
+ }
1118
+ )
1119
+ }
1120
+ }
1121
+ }
1122
+ } catch (e: Exception) {
1123
+ // Use notifyWebJson to prevent JSON injection from e.message
1124
+ BridgeUtils.notifyWebJson(
1125
+ webView,
1126
+ BridgeUtils.WebEvents.ON_WEB_DATA_CLEAR_ERROR,
1127
+ org.json.JSONObject().apply {
1128
+ put("success", false)
1129
+ put("error", e.message ?: "clearWebData failed")
1130
+ }
1131
+ )
1132
+ }
1133
+ }
1134
+ }
1135
+
1136
+ @JavascriptInterface
1137
+ fun getSafeArea(data: String? = null) {
1138
+ BridgeUtils.safeExecute(webView, BridgeUtils.WebEvents.ON_SAFE_AREA_INSETS_UPDATED, "get safe area") {
1139
+ mainActivity.runOnUiThread {
1140
+ val insets = mainActivity.getCurrentSafeAreaInsets()
1141
+ val insetsJson = org.json.JSONObject().apply {
1142
+ put("top", insets.top)
1143
+ put("right", insets.right)
1144
+ put("bottom", insets.bottom)
1145
+ put("left", insets.left)
1146
+ }
1147
+
1148
+ BridgeUtils.notifyWebJson(
1149
+ webView,
1150
+ BridgeUtils.WebEvents.ON_SAFE_AREA_INSETS_UPDATED,
1151
+ insetsJson
1152
+ )
1153
+ }
1154
+ }
1155
+ }
1156
+
283
1157
  /**
284
1158
  * Cleanup method to be called when the bridge is being destroyed
285
1159
  */
286
1160
  fun cleanup() {
287
1161
  BridgeUtils.logDebug(TAG, "Cleaning up NativeBridge resources")
288
-
1162
+
289
1163
  try {
1164
+ // Cleanup NotificationManager
1165
+ notificationManager.cleanup()
1166
+
1167
+ // Stop network monitoring
1168
+ networkMonitor?.stop()
1169
+ networkMonitor = null
1170
+
290
1171
  // Stop FrameworkServer
291
1172
  FrameworkServerUtils.stopServer()
292
-
1173
+
293
1174
  // Cancel any pending coroutines
294
1175
  supervisorJob.cancel()
295
-
1176
+
296
1177
  BridgeUtils.logInfo(TAG, "NativeBridge cleanup completed")
297
1178
  } catch (e: Exception) {
298
1179
  BridgeUtils.logError(TAG, "Error during NativeBridge cleanup", e)
@@ -333,6 +1214,8 @@ class NativeBridge(private val mainActivity: MainActivity, private val webView:
333
1214
  webView,
334
1215
  fileUrl,
335
1216
  mimeType,
1217
+ allowedUrls,
1218
+ accessControlEnabled,
336
1219
  onSuccess = { downloadedFile, detectedMimeType ->
337
1220
  IntentUtils.openFileWithSystemIntent(mainActivity, webView, downloadedFile, detectedMimeType)
338
1221
  }
@@ -353,4 +1236,4 @@ class NativeBridge(private val mainActivity: MainActivity, private val webView:
353
1236
  fun destroy() {
354
1237
  supervisorJob.cancel()
355
1238
  }
356
- }
1239
+ }