@blotch/angular-lynx-native 22.3.1 → 22.3.3

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 (123) hide show
  1. package/README.md +47 -15
  2. package/dist/android/project.d.ts +114 -1
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +440 -5
  5. package/dist/eject.d.ts +15 -1
  6. package/dist/eject.d.ts.map +1 -1
  7. package/dist/eject.js +14 -2
  8. package/dist/features.d.ts +70 -0
  9. package/dist/features.d.ts.map +1 -0
  10. package/dist/features.js +115 -0
  11. package/dist/files.d.ts +24 -0
  12. package/dist/files.d.ts.map +1 -0
  13. package/dist/files.js +41 -0
  14. package/dist/generate.d.ts +34 -3
  15. package/dist/generate.d.ts.map +1 -1
  16. package/dist/generate.js +78 -19
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +16 -2
  20. package/dist/ios/build.d.ts.map +1 -1
  21. package/dist/ios/build.js +8 -2
  22. package/dist/ios/frameworks.d.ts +6 -5
  23. package/dist/ios/frameworks.d.ts.map +1 -1
  24. package/dist/ios/frameworks.js +46 -15
  25. package/dist/ios/project.d.ts +192 -11
  26. package/dist/ios/project.d.ts.map +1 -1
  27. package/dist/ios/project.js +823 -33
  28. package/dist/options.d.ts +208 -1
  29. package/dist/options.d.ts.map +1 -1
  30. package/dist/options.js +154 -0
  31. package/dist/permissions.d.ts +18 -1
  32. package/dist/permissions.d.ts.map +1 -1
  33. package/dist/permissions.js +79 -4
  34. package/dist/plugins.d.ts +245 -0
  35. package/dist/plugins.d.ts.map +1 -0
  36. package/dist/plugins.js +1244 -0
  37. package/package.json +1 -1
  38. package/templates/android/README.md +46 -5
  39. package/templates/android/angular-lynx.properties +2 -0
  40. package/templates/android/app/build.gradle.kts +78 -11
  41. package/templates/android/app/src/main/AndroidManifest.xml +19 -3
  42. package/templates/android/app/src/main/java/dev/angularlynx/shell/AngularLynxPlugins.kt +13 -0
  43. package/templates/android/app/src/main/java/dev/angularlynx/shell/AudioRecorderModule.kt +520 -0
  44. package/templates/android/app/src/main/java/dev/angularlynx/shell/BarcodeScannerModule.kt +144 -0
  45. package/templates/android/app/src/main/java/dev/angularlynx/shell/BiometricsModule.kt +433 -0
  46. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapPresenter.kt +98 -0
  47. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapRendererContext.kt +175 -0
  48. package/templates/android/app/src/main/java/dev/angularlynx/shell/BluetoothModule.kt +1288 -0
  49. package/templates/android/app/src/main/java/dev/angularlynx/shell/CalendarModule.kt +127 -0
  50. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DContext.kt +1557 -0
  51. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DOps.kt +63 -0
  52. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasFilter.kt +357 -0
  53. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasUI.kt +4 -3
  54. package/templates/android/app/src/main/java/dev/angularlynx/shell/EdgeToEdgeOverlay.kt +24 -0
  55. package/templates/android/app/src/main/java/dev/angularlynx/shell/EngineThreadHint.kt +156 -0
  56. package/templates/android/app/src/main/java/dev/angularlynx/shell/FilePickerModule.kt +263 -0
  57. package/templates/android/app/src/main/java/dev/angularlynx/shell/GeolocationModule.kt +557 -0
  58. package/templates/android/app/src/main/java/dev/angularlynx/shell/HapticsModule.kt +82 -0
  59. package/templates/android/app/src/main/java/dev/angularlynx/shell/HostElementUI.kt +331 -0
  60. package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePickerModule.kt +143 -0
  61. package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePipeline.kt +83 -0
  62. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +523 -9
  63. package/templates/android/app/src/main/java/dev/angularlynx/shell/ModuleBytes.kt +58 -0
  64. package/templates/android/app/src/main/java/dev/angularlynx/shell/MotionModule.kt +332 -0
  65. package/templates/android/app/src/main/java/dev/angularlynx/shell/NetworkStatus.kt +121 -0
  66. package/templates/android/app/src/main/java/dev/angularlynx/shell/NfcModule.kt +274 -0
  67. package/templates/android/app/src/main/java/dev/angularlynx/shell/PermissionRequests.kt +35 -0
  68. package/templates/android/app/src/main/java/dev/angularlynx/shell/PhotoLibraryModule.kt +355 -0
  69. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShareTargetModule.kt +234 -0
  70. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +7 -8
  71. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +58 -4
  72. package/templates/android/app/src/main/java/dev/angularlynx/shell/StoreReviewModule.kt +66 -0
  73. package/templates/android/app/src/main/java/dev/angularlynx/shell/SystemFontFamilies.kt +68 -0
  74. package/templates/android/app/src/main/java/dev/angularlynx/shell/TrackingModule.kt +74 -0
  75. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoFrameTarget.kt +429 -0
  76. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoUI.kt +676 -0
  77. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +128 -13
  78. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +493 -65
  79. package/templates/android/app/src/main/java/dev/angularlynx/shell/WifiModule.kt +429 -0
  80. package/templates/android/app/src/main/res/values/biometrics.xml +9 -0
  81. package/templates/android/app/src/main/res/values/share_target.xml +11 -0
  82. package/templates/android/app/src/main/res/xml/backup_rules.xml +5 -3
  83. package/templates/android/app/src/main/res/xml/data_extraction_rules.xml +6 -3
  84. package/templates/android/app/src/main/res/xml/share_paths.xml +7 -2
  85. package/templates/android/build.gradle.kts +1 -1
  86. package/templates/android/gradle/wrapper/gradle-wrapper.properties +2 -2
  87. package/templates/ios/App/AngularLynxBitmapRendererContext.m +188 -0
  88. package/templates/ios/App/AngularLynxCanvas2DContext.m +2467 -0
  89. package/templates/ios/App/AngularLynxCanvas2DOps.h +61 -0
  90. package/templates/ios/App/AngularLynxPlugins.swift +22 -0
  91. package/templates/ios/App/AngularLynxVideo.h +37 -0
  92. package/templates/ios/App/AngularLynxVideo.m +435 -0
  93. package/templates/ios/App/AngularLynxWebGL.h +69 -7
  94. package/templates/ios/App/AngularLynxWebGL.m +538 -29
  95. package/templates/ios/App/AngularLynxWebGLContext.m +148 -46
  96. package/templates/ios/App/AnimationFrameRate.swift +66 -0
  97. package/templates/ios/App/AppDelegate.swift +37 -3
  98. package/templates/ios/App/AppleSignInButton.swift +106 -0
  99. package/templates/ios/App/AppleSignInModule.swift +222 -0
  100. package/templates/ios/App/AudioRecorderModule.swift +433 -0
  101. package/templates/ios/App/BarcodeScannerModule.swift +284 -0
  102. package/templates/ios/App/BiometricsModule.swift +256 -0
  103. package/templates/ios/App/BluetoothModule.swift +1086 -0
  104. package/templates/ios/App/CalendarModule.swift +158 -0
  105. package/templates/ios/App/FilePickerModule.swift +240 -0
  106. package/templates/ios/App/GeolocationModule.swift +455 -0
  107. package/templates/ios/App/HapticsModule.swift +90 -0
  108. package/templates/ios/App/HostElementUI.swift +270 -0
  109. package/templates/ios/App/ImagePickerModule.swift +160 -1
  110. package/templates/ios/App/Info.plist +2 -0
  111. package/templates/ios/App/LynxViewController.swift +274 -9
  112. package/templates/ios/App/MotionModule.swift +430 -0
  113. package/templates/ios/App/NetworkStatus.swift +41 -0
  114. package/templates/ios/App/NfcModule.swift +346 -0
  115. package/templates/ios/App/PhotoLibraryModule.swift +169 -0
  116. package/templates/ios/App/ShareTargetModule.swift +150 -0
  117. package/templates/ios/App/ShellModule.swift +17 -0
  118. package/templates/ios/App/StoreReviewModule.swift +61 -0
  119. package/templates/ios/App/TrackingModule.swift +121 -0
  120. package/templates/ios/App/WifiModule.swift +237 -0
  121. package/templates/ios/App/XElementRegistry.swift +13 -3
  122. package/templates/ios/ShareExtension/Info.plist +42 -0
  123. package/templates/ios/ShareExtension/ShareViewController.swift +387 -0
@@ -0,0 +1,520 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.Manifest
4
+ import android.app.Activity
5
+ import android.app.Application
6
+ import android.content.Context
7
+ import android.content.pm.PackageManager
8
+ import android.media.MediaRecorder
9
+ import android.net.Uri
10
+ import android.os.Build
11
+ import android.os.Bundle
12
+ import android.os.Handler
13
+ import android.os.HandlerThread
14
+ import android.os.Looper
15
+ import android.os.SystemClock
16
+ import android.util.Base64
17
+ import androidx.core.content.ContextCompat
18
+ import com.lynx.jsbridge.LynxContextModule
19
+ import com.lynx.jsbridge.LynxMethod
20
+ import com.lynx.react.bridge.Callback
21
+ import com.lynx.react.bridge.JavaOnlyArray
22
+ import com.lynx.react.bridge.JavaOnlyMap
23
+ import com.lynx.react.bridge.ReadableMap
24
+ import com.lynx.tasm.behavior.LynxContext
25
+ import java.io.File
26
+ import java.io.IOException
27
+ import kotlin.math.log10
28
+
29
+ /**
30
+ * The native module behind the runtime's `LynxAudioRecorder`, which calls it
31
+ * as `NativeModules.AngularLynxAudioRecorder` (from the background thread,
32
+ * where NativeModules lives). The iOS shell has one of the same name.
33
+ *
34
+ * It records AAC into an MPEG-4 file (`.m4a`) in the app's cache folder with
35
+ * `MediaRecorder`, one recording at a time:
36
+ *
37
+ * - `permission` answers `{ permission }`: `granted`, `denied` (the person
38
+ * refused when this module asked) or `undetermined`, without asking.
39
+ * Android can't tell an app whether a permission it doesn't hold was ever
40
+ * asked for, so until this module has asked, it's `undetermined`.
41
+ * - `requestPermission` asks for `RECORD_AUDIO` through MainActivity's
42
+ * prompt (the [PermissionHost] MainActivity registers the module with),
43
+ * and answers `{ permission }` once the person has chosen.
44
+ * - `start` takes `{ recording, maxDuration? }`, asks first if it needs to,
45
+ * and answers `{}` once it records, or `{ error, message }`: `denied`,
46
+ * `busy` while another recording is open or the microphone is taken, or
47
+ * `failed`.
48
+ * - `pause` and `resume` answer `{}`.
49
+ * - `stop` ends the recording and answers `{ clip }`: `{ uri, name,
50
+ * durationMs, mimeType, size }`. Once it ended by itself, it answers with
51
+ * that clip.
52
+ * - `cancel` ends it and deletes the file.
53
+ * - `read` takes `{ uri }` and answers `{ base64 }`, the bytes of a clip this
54
+ * module recorded.
55
+ *
56
+ * What the app didn't ask for at that moment arrives as the
57
+ * `angularLynxAudioRecorder` global event, carrying the `recording` id
58
+ * `start` was given: `level` about ten times a second while it records
59
+ * (`{ level, durationMs }`), `paused` when the app went to the background
60
+ * (Android gives an app in the background only silence from the microphone,
61
+ * so it records in the foreground only), and `ended` once it reached
62
+ * `maxDuration` (`{ clip }`) or failed (`{ error, message }`).
63
+ *
64
+ * The generator keeps this file, and the lines in MainActivity that register
65
+ * it, only in an app whose angular.json sets `permissions.microphone`, which
66
+ * also declares `RECORD_AUDIO`. So it's looked up by name.
67
+ */
68
+ class AudioRecorderModule : LynxContextModule {
69
+ // Lynx creates a module through whichever of its constructors it finds.
70
+ constructor(context: LynxContext) : super(context)
71
+ constructor(context: LynxContext, param: Any?) : super(context, param)
72
+
73
+ private val appContext: Context = mContext.applicationContext
74
+
75
+ // Every field below is read and written on this one thread. The methods
76
+ // (which Lynx calls from its JavaScript thread), the meter's ticks, the
77
+ // recorder's errors and the activity's lifecycle all post to it, so
78
+ // nothing needs a lock.
79
+ private val thread = HandlerThread(TAG).apply { start() }
80
+ private val handler = Handler(thread.looper)
81
+
82
+ // The activity's permission prompt runs on the UI thread.
83
+ private val main = Handler(Looper.getMainLooper())
84
+
85
+ @Volatile
86
+ private var destroyed = false
87
+
88
+ // Whether the person refused when this module asked.
89
+ private var refused = false
90
+
91
+ // How the person's answer came out for those waiting on it.
92
+ private enum class Answer { GRANTED, DENIED, BUSY, CLOSED }
93
+
94
+ // Who's waiting for the prompt this module has open, so a second start
95
+ // joins it instead of opening another.
96
+ private val askers = mutableListOf<(Answer) -> Unit>()
97
+
98
+ private class Recording(
99
+ val id: Int,
100
+ val recorder: MediaRecorder,
101
+ val file: File,
102
+ val maxDuration: Long?,
103
+ ) {
104
+ // How long it recorded before its latest start or resume.
105
+ var recorded = 0L
106
+
107
+ // When it last started or resumed, or null while it's paused.
108
+ var since: Long? = SystemClock.elapsedRealtime()
109
+
110
+ val elapsed: Long
111
+ get() = recorded + (since?.let { SystemClock.elapsedRealtime() - it } ?: 0L)
112
+ }
113
+
114
+ private var recording: Recording? = null
115
+
116
+ // The clip of the recording that ended by itself, for the stop after it.
117
+ private var ended: JavaOnlyMap? = null
118
+
119
+ private val tick = object : Runnable {
120
+ override fun run() {
121
+ meter()
122
+ if (recording != null) handler.postDelayed(this, LEVEL_INTERVAL)
123
+ }
124
+ }
125
+
126
+ // The app going to the background, where Android gives it only silence.
127
+ // onActivityStopped rather than paused: Android's own permission prompt
128
+ // pauses the activity.
129
+ private val lifecycle = object : Application.ActivityLifecycleCallbacks {
130
+ override fun onActivityStopped(stopped: Activity) {
131
+ handler.post { systemPaused() }
132
+ }
133
+
134
+ override fun onActivityCreated(created: Activity, state: Bundle?) = Unit
135
+
136
+ override fun onActivityStarted(started: Activity) = Unit
137
+
138
+ override fun onActivityResumed(resumed: Activity) = Unit
139
+
140
+ override fun onActivityPaused(paused: Activity) = Unit
141
+
142
+ override fun onActivitySaveInstanceState(saved: Activity, state: Bundle) = Unit
143
+
144
+ override fun onActivityDestroyed(destroyed: Activity) = Unit
145
+ }
146
+
147
+ init {
148
+ (appContext as? Application)?.registerActivityLifecycleCallbacks(lifecycle)
149
+ }
150
+
151
+ override fun destroy() {
152
+ destroyed = true
153
+ (appContext as? Application)?.unregisterActivityLifecycleCallbacks(lifecycle)
154
+ handler.post {
155
+ // Nobody can stop it into a clip now, so its file goes too.
156
+ recording?.let {
157
+ release(it)
158
+ it.file.delete()
159
+ }
160
+ recording = null
161
+ answerAll(Answer.CLOSED)
162
+ thread.quitSafely()
163
+ }
164
+ super.destroy()
165
+ }
166
+
167
+ @LynxMethod
168
+ fun permission(callback: Callback) {
169
+ handler.post {
170
+ callback.invoke(JavaOnlyMap().apply { putString("permission", permissionState()) })
171
+ }
172
+ }
173
+
174
+ @LynxMethod
175
+ fun requestPermission(callback: Callback) {
176
+ handler.post {
177
+ whenAnswered { answer ->
178
+ when (answer) {
179
+ Answer.CLOSED -> callback.invoke(failure(FAILED, PAGE_CLOSED))
180
+ Answer.BUSY -> callback.invoke(failure(BUSY, PROMPT_OPEN))
181
+ else -> callback.invoke(JavaOnlyMap().apply { putString("permission", permissionState()) })
182
+ }
183
+ }
184
+ }
185
+ }
186
+
187
+ @LynxMethod
188
+ fun start(options: ReadableMap?, callback: Callback) {
189
+ handler.post {
190
+ whenAnswered { answer ->
191
+ when (answer) {
192
+ Answer.CLOSED -> callback.invoke(failure(FAILED, PAGE_CLOSED))
193
+ Answer.BUSY -> callback.invoke(failure(BUSY, PROMPT_OPEN))
194
+ Answer.DENIED -> callback.invoke(failure(DENIED, "The person didn't allow the microphone."))
195
+ Answer.GRANTED -> callback.invoke(begin(options))
196
+ }
197
+ }
198
+ }
199
+ }
200
+
201
+ @LynxMethod
202
+ fun pause(callback: Callback) {
203
+ handler.post {
204
+ pauseRecording()
205
+ callback.invoke(JavaOnlyMap())
206
+ }
207
+ }
208
+
209
+ @LynxMethod
210
+ fun resume(callback: Callback) {
211
+ handler.post {
212
+ val current = recording
213
+ if (current == null || current.since != null) {
214
+ callback.invoke(JavaOnlyMap())
215
+ return@post
216
+ }
217
+ try {
218
+ current.recorder.resume()
219
+ } catch (error: IllegalStateException) {
220
+ callback.invoke(failure(FAILED, error.message ?: "The recording couldn't carry on."))
221
+ return@post
222
+ }
223
+ current.since = SystemClock.elapsedRealtime()
224
+ callback.invoke(JavaOnlyMap())
225
+ }
226
+ }
227
+
228
+ @LynxMethod
229
+ fun stop(callback: Callback) {
230
+ handler.post {
231
+ val finished = finish()
232
+ val error = finished?.error
233
+ val clip = if (finished != null) finished.clip else ended
234
+ when {
235
+ error != null -> callback.invoke(failure(FAILED, error))
236
+ clip != null -> callback.invoke(JavaOnlyMap().apply { putMap("clip", clip) })
237
+ else -> callback.invoke(failure(FAILED, "Nothing is recording."))
238
+ }
239
+ }
240
+ }
241
+
242
+ @LynxMethod
243
+ fun cancel(callback: Callback) {
244
+ handler.post {
245
+ recording?.let {
246
+ recording = null
247
+ release(it)
248
+ it.file.delete()
249
+ }
250
+ ended = null
251
+ callback.invoke(JavaOnlyMap())
252
+ }
253
+ }
254
+
255
+ @LynxMethod
256
+ fun read(options: ReadableMap?, callback: Callback) {
257
+ handler.post {
258
+ // Only this module's own recordings: the runtime gives back the uri it
259
+ // was handed, and the module reads no other file.
260
+ // Resolving the path can throw too, and the call must answer.
261
+ val bytes = try {
262
+ options?.getString("uri", null)
263
+ ?.let { Uri.parse(it) }
264
+ ?.takeIf { it.scheme == "file" }
265
+ ?.path
266
+ ?.let { File(it).canonicalFile }
267
+ ?.takeIf { it.parentFile == folder().canonicalFile && it.isFile }
268
+ ?.readBytes()
269
+ } catch (_: IOException) {
270
+ null
271
+ }
272
+ if (bytes == null) {
273
+ callback.invoke(failure(FAILED, "The recording couldn't be read."))
274
+ } else {
275
+ callback.invoke(JavaOnlyMap().apply { putString("base64", Base64.encodeToString(bytes, Base64.NO_WRAP)) })
276
+ }
277
+ }
278
+ }
279
+
280
+ // ─── Helpers ────────────────────────────────────────────────────────────
281
+
282
+ private fun granted(): Boolean =
283
+ ContextCompat.checkSelfPermission(appContext, Manifest.permission.RECORD_AUDIO) ==
284
+ PackageManager.PERMISSION_GRANTED
285
+
286
+ private fun permissionState(): String = when {
287
+ granted() -> "granted"
288
+ refused -> "denied"
289
+ else -> "undetermined"
290
+ }
291
+
292
+ /**
293
+ * Calls [done] with whether the app may record, asking the person first
294
+ * when it doesn't know: [Answer.BUSY] while another module's prompt is
295
+ * open, which says nothing about the microphone, and [Answer.CLOSED] once
296
+ * the page has closed.
297
+ */
298
+ private fun whenAnswered(done: (Answer) -> Unit) {
299
+ if (granted()) return done(Answer.GRANTED)
300
+ askers += done
301
+ if (askers.size > 1) return
302
+ val host = mParam as? PermissionHost
303
+ main.post {
304
+ if (destroyed) return@post
305
+ val asked = try {
306
+ host?.requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO)) {
307
+ handler.post { answered() }
308
+ } ?: false
309
+ } catch (_: IllegalStateException) {
310
+ // The activity's launcher throws once the activity is going.
311
+ handler.post { answerAll(Answer.CLOSED) }
312
+ return@post
313
+ }
314
+ if (asked) return@post
315
+ // No host can't ask, which is as good as refused. Another
316
+ // module's prompt being open (the Wi-Fi module's location prompt)
317
+ // is only for now: the person refused nothing.
318
+ handler.post { if (host == null) answered() else answerAll(Answer.BUSY) }
319
+ }
320
+ }
321
+
322
+ private fun answered() {
323
+ val allowed = granted()
324
+ refused = !allowed
325
+ answerAll(if (allowed) Answer.GRANTED else Answer.DENIED)
326
+ }
327
+
328
+ private fun answerAll(answer: Answer) {
329
+ val waiting = askers.toList()
330
+ askers.clear()
331
+ waiting.forEach { it(answer) }
332
+ }
333
+
334
+ private fun folder(): File = File(appContext.cacheDir, "recordings")
335
+
336
+ private fun begin(options: ReadableMap?): JavaOnlyMap {
337
+ if (recording != null) return failure(BUSY, "Another recording is still open: stop it first.")
338
+ val id = options?.getDouble("recording", 0.0)?.toInt() ?: 0
339
+ val maxDuration = options
340
+ ?.takeIf { it.hasKey("maxDuration") }
341
+ ?.getDouble("maxDuration", 0.0)
342
+ ?.toLong()
343
+ ?.takeIf { it > 0 }
344
+ val directory = folder().apply { mkdirs() }
345
+ val file = File(directory, "recording-${System.currentTimeMillis()}.m4a")
346
+ val recorder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
347
+ MediaRecorder(appContext)
348
+ } else {
349
+ @Suppress("DEPRECATION")
350
+ MediaRecorder()
351
+ }
352
+ try {
353
+ recorder.setAudioSource(MediaRecorder.AudioSource.MIC)
354
+ recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
355
+ recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
356
+ recorder.setAudioSamplingRate(44_100)
357
+ recorder.setAudioChannels(1)
358
+ // Enough for a voice, at a fraction of music's bit rate.
359
+ recorder.setAudioEncodingBitRate(64_000)
360
+ recorder.setOutputFile(file.absolutePath)
361
+ recorder.prepare()
362
+ recorder.start()
363
+ } catch (error: Exception) {
364
+ recorder.release()
365
+ file.delete()
366
+ // start() throws IllegalStateException when another app holds
367
+ // the microphone, such as a call.
368
+ return if (error is IllegalStateException) {
369
+ failure(BUSY, "The microphone is in use: another app may be recording, or a call is on.")
370
+ } else {
371
+ failure(FAILED, error.message ?: "The recording couldn't start.")
372
+ }
373
+ }
374
+ val current = Recording(id, recorder, file, maxDuration)
375
+ recorder.setOnErrorListener { _, what, _ ->
376
+ handler.post {
377
+ if (recording !== current) return@post
378
+ recording = null
379
+ release(current)
380
+ // It ended without a clip the app can have, so its file goes.
381
+ current.file.delete()
382
+ emit("ended", current.id) {
383
+ putString("error", FAILED)
384
+ putString("message", "The recorder failed (error $what).")
385
+ }
386
+ }
387
+ }
388
+ recording = current
389
+ ended = null
390
+ // getMaxAmplitude() is the loudest sample since it was last read, so
391
+ // the first tick reads from here.
392
+ recorder.maxAmplitude.let { }
393
+ handler.postDelayed(tick, LEVEL_INTERVAL)
394
+ return JavaOnlyMap()
395
+ }
396
+
397
+ private fun pauseRecording() {
398
+ val current = recording ?: return
399
+ if (current.since == null) return
400
+ try {
401
+ current.recorder.pause()
402
+ } catch (_: IllegalStateException) {
403
+ return
404
+ }
405
+ current.recorded = current.elapsed
406
+ current.since = null
407
+ }
408
+
409
+ private fun systemPaused() {
410
+ val current = recording ?: return
411
+ if (current.since == null) return
412
+ pauseRecording()
413
+ emit("paused", current.id) {}
414
+ }
415
+
416
+ /** A stopped recording: its clip, or why its file couldn't be finished. */
417
+ private class Finished(val clip: JavaOnlyMap?, val error: String?)
418
+
419
+ /** Stops the recording and describes its file. Null when nothing records. */
420
+ private fun finish(): Finished? {
421
+ val current = recording ?: return null
422
+ val durationMs = current.elapsed
423
+ recording = null
424
+ val stopped = try {
425
+ current.recorder.stop()
426
+ true
427
+ } catch (_: RuntimeException) {
428
+ // stop() throws when the encoder had nothing yet, such as a stop
429
+ // right after start(): the file isn't a playable MPEG-4.
430
+ false
431
+ }
432
+ release(current)
433
+ if (!stopped) {
434
+ current.file.delete()
435
+ return Finished(null, "The recording was too short to keep: nothing had been recorded yet.")
436
+ }
437
+ return Finished(
438
+ JavaOnlyMap().apply {
439
+ putString("uri", Uri.fromFile(current.file).toString())
440
+ putString("name", current.file.name)
441
+ putDouble("durationMs", durationMs.toDouble())
442
+ putString("mimeType", "audio/mp4")
443
+ putDouble("size", current.file.length().toDouble())
444
+ },
445
+ null,
446
+ )
447
+ }
448
+
449
+ private fun release(current: Recording) {
450
+ handler.removeCallbacks(tick)
451
+ current.recorder.release()
452
+ }
453
+
454
+ private fun meter() {
455
+ val current = recording ?: return
456
+ if (current.since == null) return
457
+ val elapsed = current.elapsed
458
+ val maxDuration = current.maxDuration
459
+ if (maxDuration != null && elapsed >= maxDuration) {
460
+ val finished = finish() ?: return
461
+ ended = finished.clip
462
+ emit("ended", current.id) {
463
+ val clip = finished.clip
464
+ if (clip != null) {
465
+ putMap("clip", clip)
466
+ } else {
467
+ putString("error", FAILED)
468
+ putString("message", finished.error ?: "The recording couldn't be finished.")
469
+ }
470
+ }
471
+ return
472
+ }
473
+ val amplitude = try {
474
+ current.recorder.maxAmplitude
475
+ } catch (_: IllegalStateException) {
476
+ 0
477
+ }
478
+ // The loudest sample since the last tick, in dBFS, from -60 to 0 as
479
+ // 0..1, as the iOS shell and the web preview scale it.
480
+ val level = if (amplitude <= 0) {
481
+ 0.0
482
+ } else {
483
+ val db = 20 * log10(amplitude / 32767.0)
484
+ ((db - LEVEL_FLOOR_DB) / -LEVEL_FLOOR_DB).coerceIn(0.0, 1.0)
485
+ }
486
+ emit("level", current.id) {
487
+ putDouble("level", level)
488
+ putDouble("durationMs", elapsed.toDouble())
489
+ }
490
+ }
491
+
492
+ private fun emit(type: String, recording: Int, fill: JavaOnlyMap.() -> Unit) {
493
+ if (destroyed) return
494
+ val payload = JavaOnlyMap().apply {
495
+ putString("type", type)
496
+ putInt("recording", recording)
497
+ fill()
498
+ }
499
+ mLynxContext.sendGlobalEvent(EVENT, JavaOnlyArray().apply { pushMap(payload) })
500
+ }
501
+
502
+ private fun failure(code: String, message: String) = JavaOnlyMap().apply {
503
+ putString("error", code)
504
+ putString("message", message)
505
+ }
506
+
507
+ companion object {
508
+ /** The name the runtime calls it by, and MainActivity registers it with. */
509
+ const val NAME = "AngularLynxAudioRecorder"
510
+ private const val EVENT = "angularLynxAudioRecorder"
511
+ private const val TAG = "AngularLynxAudioRecorder"
512
+ private const val LEVEL_INTERVAL = 100L
513
+ private const val LEVEL_FLOOR_DB = -60.0
514
+ private const val DENIED = "denied"
515
+ private const val BUSY = "busy"
516
+ private const val FAILED = "failed"
517
+ private const val PAGE_CLOSED = "The page closed before the person answered."
518
+ private const val PROMPT_OPEN = "Another permission prompt is open: try again once it's answered."
519
+ }
520
+ }
@@ -0,0 +1,144 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.app.Activity
4
+ import android.content.Context
5
+ import android.os.Handler
6
+ import android.os.Looper
7
+ import com.google.android.gms.common.ConnectionResult
8
+ import com.google.android.gms.common.GoogleApiAvailability
9
+ import com.google.mlkit.common.MlKitException
10
+ import com.google.mlkit.vision.barcode.common.Barcode
11
+ import com.google.mlkit.vision.codescanner.GmsBarcodeScannerOptions
12
+ import com.google.mlkit.vision.codescanner.GmsBarcodeScanning
13
+ import com.lynx.jsbridge.LynxMethod
14
+ import com.lynx.jsbridge.LynxModule
15
+ import com.lynx.react.bridge.Callback
16
+ import com.lynx.react.bridge.JavaOnlyMap
17
+ import com.lynx.react.bridge.ReadableMap
18
+
19
+ /**
20
+ * The native module behind the runtime's `LynxBarcodeScanner`, which calls it
21
+ * as `NativeModules.AngularLynxBarcodeScanner` (from the background thread,
22
+ * where NativeModules lives). MainActivity registers it with itself as the
23
+ * param: the scanner opens over it.
24
+ *
25
+ * It opens Google's code scanner, which runs in Google Play services rather
26
+ * than the app: Play services shows the camera and hands back only the code
27
+ * read, so the app needs no CAMERA permission and draws no camera screen.
28
+ * A phone without Play services has no scanner, and a scan reports
29
+ * `unavailable`; Play services downloads the scanner the first time an app
30
+ * asks for it, and a scan before that's done reports `unavailable` too.
31
+ *
32
+ * Only an app whose angular.json sets `permissions.camera` has this file and
33
+ * the Play services library behind it (app/build.gradle.kts's
34
+ * `angular-lynx:barcode-scanner` lines), as only it has the iOS module. So
35
+ * MainActivity looks it up by name, and nothing else may name the class.
36
+ */
37
+ class BarcodeScannerModule(context: Context, param: Any?) : LynxModule(context, param) {
38
+ private val activity = param as Activity
39
+ private val main = Handler(Looper.getMainLooper())
40
+
41
+ /** Whether a scan is open: Play services runs one at a time. */
42
+ private var scanning = false
43
+
44
+ /**
45
+ * Opens the scanner and calls back once with `{ format, value }`, or
46
+ * `{ error, message }`, where `error` is `canceled`, `unavailable`,
47
+ * `denied` or `failed`, as the iOS module does.
48
+ */
49
+ @LynxMethod
50
+ fun scan(request: ReadableMap, callback: Callback) {
51
+ val names = request.getArray("formats")?.let { formats ->
52
+ (0 until formats.size()).map { formats.getString(it) }
53
+ } ?: emptyList()
54
+ // Lynx calls modules off the main thread, and the scanner starts an
55
+ // activity.
56
+ main.post { start(names, callback) }
57
+ }
58
+
59
+ private fun start(names: List<String>, callback: Callback) {
60
+ if (scanning) {
61
+ callback.invoke(error("failed", "A scan is already open."))
62
+ return
63
+ }
64
+ if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(activity) !=
65
+ ConnectionResult.SUCCESS
66
+ ) {
67
+ callback.invoke(error("unavailable", "The barcode scanner needs Google Play services."))
68
+ return
69
+ }
70
+ val formats = names.mapNotNull { FORMATS[it] }.distinct()
71
+ val options = GmsBarcodeScannerOptions.Builder()
72
+ .apply {
73
+ if (formats.isNotEmpty()) {
74
+ setBarcodeFormats(formats.first(), *formats.drop(1).toIntArray())
75
+ }
76
+ }
77
+ // Zooms in on a code that's far away, as the system camera does.
78
+ .enableAutoZoom()
79
+ .build()
80
+ scanning = true
81
+ val done = { result: JavaOnlyMap ->
82
+ scanning = false
83
+ callback.invoke(result)
84
+ }
85
+ GmsBarcodeScanning.getClient(activity, options)
86
+ .startScan()
87
+ .addOnSuccessListener { barcode ->
88
+ val format = NAMES[barcode.format]
89
+ val value = barcode.rawValue ?: barcode.displayValue
90
+ if (format == null || value == null) {
91
+ done(error("failed", "The scanner read a code it couldn't hand over."))
92
+ } else {
93
+ done(JavaOnlyMap.from(mapOf("format" to format, "value" to value)))
94
+ }
95
+ }
96
+ .addOnCanceledListener { done(error("canceled", "The scan was canceled.")) }
97
+ .addOnFailureListener { failure ->
98
+ val code = (failure as? MlKitException)?.errorCode
99
+ done(
100
+ when (code) {
101
+ MlKitException.CODE_SCANNER_CANCELLED ->
102
+ error("canceled", "The scan was canceled.")
103
+ // Play services shows the camera, so it's Play
104
+ // services, not the app, that the person refused it
105
+ // to.
106
+ MlKitException.CODE_SCANNER_CAMERA_PERMISSION_NOT_GRANTED ->
107
+ error("denied", "Google Play services isn't allowed to use the camera.")
108
+ MlKitException.UNAVAILABLE, MlKitException.CODE_SCANNER_UNAVAILABLE ->
109
+ error(
110
+ "unavailable",
111
+ "Google Play services has no barcode scanner yet. It downloads one the first time an app asks: try again shortly.",
112
+ )
113
+ else -> error("failed", failure.message ?: "The scanner could not read a code.")
114
+ },
115
+ )
116
+ }
117
+ }
118
+
119
+ private fun error(code: String, message: String) =
120
+ JavaOnlyMap.from(mapOf("error" to code, "message" to message))
121
+
122
+ companion object {
123
+ const val NAME = "AngularLynxBarcodeScanner"
124
+
125
+ /** The runtime's BarcodeFormat names as ML Kit's formats. */
126
+ private val FORMATS = mapOf(
127
+ "qr" to Barcode.FORMAT_QR_CODE,
128
+ "aztec" to Barcode.FORMAT_AZTEC,
129
+ "dataMatrix" to Barcode.FORMAT_DATA_MATRIX,
130
+ "pdf417" to Barcode.FORMAT_PDF417,
131
+ "ean13" to Barcode.FORMAT_EAN_13,
132
+ "ean8" to Barcode.FORMAT_EAN_8,
133
+ "upcA" to Barcode.FORMAT_UPC_A,
134
+ "upcE" to Barcode.FORMAT_UPC_E,
135
+ "code39" to Barcode.FORMAT_CODE_39,
136
+ "code93" to Barcode.FORMAT_CODE_93,
137
+ "code128" to Barcode.FORMAT_CODE_128,
138
+ "itf" to Barcode.FORMAT_ITF,
139
+ "codabar" to Barcode.FORMAT_CODABAR,
140
+ )
141
+
142
+ private val NAMES = FORMATS.entries.associate { (name, format) -> format to name }
143
+ }
144
+ }