@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,274 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.app.Activity
4
+ import android.content.Context
5
+ import android.nfc.FormatException
6
+ import android.nfc.NdefMessage
7
+ import android.nfc.NdefRecord
8
+ import android.nfc.NfcAdapter
9
+ import android.nfc.Tag
10
+ import android.nfc.tech.Ndef
11
+ import android.nfc.tech.NdefFormatable
12
+ import android.os.Handler
13
+ import android.os.Looper
14
+ import android.util.Base64
15
+ import com.lynx.jsbridge.LynxMethod
16
+ import com.lynx.jsbridge.LynxModule
17
+ import com.lynx.react.bridge.Callback
18
+ import com.lynx.react.bridge.JavaOnlyArray
19
+ import com.lynx.react.bridge.JavaOnlyMap
20
+ import com.lynx.react.bridge.ReadableMap
21
+ import com.lynx.react.bridge.ReadableType
22
+ import java.io.IOException
23
+
24
+ /**
25
+ * The native module behind the runtime's `LynxNfc`, which calls it as
26
+ * `NativeModules.AngularLynxNfc` (from the background thread, where
27
+ * NativeModules lives). MainActivity registers it with itself as the param,
28
+ * the activity reader mode runs in. iOS's shell has one of the same name and
29
+ * methods (NfcModule.swift), which say what each answers.
30
+ *
31
+ * A session is `NfcAdapter.enableReaderMode`, which hands each tag that comes
32
+ * near the phone to this module rather than to other apps, while the activity
33
+ * is in the foreground: Android pauses it with the activity and starts it
34
+ * again when the app comes back. There's no system sheet, so `alertMessage`
35
+ * and the messages `stop` takes are iOS's alone.
36
+ *
37
+ * The generator leaves this file and the lines in MainActivity that register
38
+ * it out of an app whose angular.json doesn't set `permissions.nfc`, which
39
+ * also declares the NFC permission and the (not required) NFC feature.
40
+ */
41
+ class NfcModule(context: Context, param: Any?) : LynxModule(context, param) {
42
+ private val activity = param as Activity
43
+ private val adapter: NfcAdapter? = NfcAdapter.getDefaultAdapter(context)
44
+ private val main = Handler(Looper.getMainLooper())
45
+
46
+ /** A tag that couldn't be read or written, with the runtime's code. */
47
+ private class TagError(val code: String, message: String) : Exception(message)
48
+
49
+ // Guarded by `this`: Lynx calls the methods on a thread of its own, and
50
+ // reader mode hands over tags on a binder thread.
51
+ private var open = false
52
+ /**
53
+ * Counts the sessions, so a tag read during one that has since ended,
54
+ * and another started, isn't taken for the new one's.
55
+ */
56
+ private var session = 0
57
+ /** Whether a read or write (not a scan) has taken its one tag. */
58
+ private var claimed = false
59
+ private var multiple = false
60
+ private var message: NdefMessage? = null
61
+ private var waiting: Callback? = null
62
+ private val answers = ArrayDeque<JavaOnlyMap>()
63
+
64
+ @LynxMethod
65
+ fun state(callback: Callback) {
66
+ callback.invoke(JavaOnlyMap().apply { putString("state", currentState()) })
67
+ }
68
+
69
+ private fun currentState(): String = when {
70
+ adapter == null -> "unsupported"
71
+ !adapter.isEnabled -> "disabled"
72
+ else -> "ready"
73
+ }
74
+
75
+ @LynxMethod
76
+ fun start(options: ReadableMap, callback: Callback) {
77
+ when (currentState()) {
78
+ "unsupported" -> return callback.invoke(error("unsupported", "This phone has no NFC reader."))
79
+ "disabled" -> return callback.invoke(error("disabled", "NFC is turned off in the phone's settings."))
80
+ }
81
+ val records = if (options.hasKey("write") && options.getType("write") == ReadableType.Array) {
82
+ try {
83
+ NdefMessage(records(options.getArray("write")!!))
84
+ } catch (_: IllegalArgumentException) {
85
+ return callback.invoke(error("failed", "The records to write aren't valid NDEF records."))
86
+ }
87
+ } else {
88
+ null
89
+ }
90
+ synchronized(this) {
91
+ if (open) return callback.invoke(error("busy", "Another NFC read or write is still open."))
92
+ open = true
93
+ session++
94
+ claimed = false
95
+ multiple = options.hasKey("multiple") && options.getType("multiple") == ReadableType.Boolean &&
96
+ options.getBoolean("multiple")
97
+ message = records
98
+ answers.clear()
99
+ }
100
+ // Reader mode starts from the main thread, with the activity in the
101
+ // foreground.
102
+ main.post {
103
+ try {
104
+ adapter!!.enableReaderMode(activity, ::onTag, READER_FLAGS, null)
105
+ callback.invoke(JavaOnlyMap())
106
+ } catch (exception: IllegalStateException) {
107
+ synchronized(this) { open = false }
108
+ callback.invoke(error("failed", "NFC couldn't start: ${exception.message}"))
109
+ }
110
+ }
111
+ }
112
+
113
+ @LynxMethod
114
+ fun next(callback: Callback) {
115
+ synchronized(this) {
116
+ when {
117
+ answers.isNotEmpty() -> callback.invoke(answers.removeFirst())
118
+ !open -> callback.invoke(error("stopped", "The NFC session has ended."))
119
+ waiting != null -> callback.invoke(error("busy", "The module is already waiting for a tag."))
120
+ else -> waiting = callback
121
+ }
122
+ }
123
+ }
124
+
125
+ @LynxMethod
126
+ fun stop(@Suppress("UNUSED_PARAMETER") options: ReadableMap, callback: Callback) {
127
+ val waiter = synchronized(this) {
128
+ val wasOpen = open
129
+ open = false
130
+ val waiter = waiting
131
+ waiting = null
132
+ if (wasOpen) main.post { adapter?.disableReaderMode(activity) }
133
+ waiter
134
+ }
135
+ waiter?.invoke(error("stopped", "The NFC session has ended."))
136
+ callback.invoke(JavaOnlyMap())
137
+ }
138
+
139
+ /** Reader mode's callback, on a binder thread, for each tag it finds. */
140
+ private fun onTag(tag: Tag) {
141
+ // Reader mode keeps handing over tags until `stop`, so a read or a
142
+ // write claims the first before touching it: a second tag that comes
143
+ // near before the runtime stops the session is neither read nor
144
+ // written to.
145
+ val (write, token) = synchronized(this) {
146
+ if (!open || (!multiple && claimed)) return
147
+ if (!multiple) claimed = true
148
+ message to session
149
+ }
150
+ val answer = try {
151
+ JavaOnlyMap().apply { putMap("tag", if (write != null) write(write, tag) else read(tag)) }
152
+ } catch (exception: TagError) {
153
+ error(exception.code, exception.message ?: "")
154
+ } catch (exception: IOException) {
155
+ error("failed", "The tag moved away before it could be read: ${exception.message}")
156
+ } catch (exception: FormatException) {
157
+ error("failed", "The tag's NDEF message is damaged: ${exception.message}")
158
+ }
159
+ val waiter = synchronized(this) {
160
+ // A scan skips a tag it couldn't read; there's no sheet to say so,
161
+ // and the next tap tries again.
162
+ if (!open || token != session || (multiple && answer.hasKey("error"))) return
163
+ val waiter = waiting
164
+ waiting = null
165
+ if (waiter == null) answers.addLast(answer)
166
+ waiter
167
+ }
168
+ waiter?.invoke(answer)
169
+ }
170
+
171
+ private fun read(tag: Tag): JavaOnlyMap {
172
+ Ndef.get(tag)?.let { ndef ->
173
+ ndef.connect()
174
+ try {
175
+ // Null on a tag formatted for NDEF with no message yet.
176
+ val message = ndef.ndefMessage
177
+ return tagMap(message?.records ?: emptyArray(), ndef.isWritable, ndef.maxSize, tag)
178
+ } finally {
179
+ ndef.close()
180
+ }
181
+ }
182
+ // A blank tag that can take NDEF once it's formatted, which a write
183
+ // does.
184
+ if (NdefFormatable.get(tag) != null) return tagMap(emptyArray(), true, 0, tag)
185
+ throw TagError("tagNotNdef", "This tag doesn't hold NDEF records.")
186
+ }
187
+
188
+ private fun write(message: NdefMessage, tag: Tag): JavaOnlyMap {
189
+ Ndef.get(tag)?.let { ndef ->
190
+ ndef.connect()
191
+ try {
192
+ if (!ndef.isWritable) throw TagError("readOnly", "This tag is locked, so it can't be written to.")
193
+ if (message.byteArrayLength > ndef.maxSize) {
194
+ throw TagError(
195
+ "tooLarge",
196
+ "The records take ${message.byteArrayLength} bytes, and this tag holds ${ndef.maxSize}.",
197
+ )
198
+ }
199
+ ndef.writeNdefMessage(message)
200
+ return tagMap(message.records, true, ndef.maxSize, tag)
201
+ } finally {
202
+ ndef.close()
203
+ }
204
+ }
205
+ NdefFormatable.get(tag)?.let { blank ->
206
+ blank.connect()
207
+ try {
208
+ blank.format(message)
209
+ return tagMap(message.records, true, 0, tag)
210
+ } finally {
211
+ blank.close()
212
+ }
213
+ }
214
+ throw TagError("tagNotNdef", "This tag can't hold NDEF records.")
215
+ }
216
+
217
+ private fun tagMap(records: Array<NdefRecord>, writable: Boolean, capacity: Int, tag: Tag) =
218
+ JavaOnlyMap().apply {
219
+ putArray(
220
+ "records",
221
+ JavaOnlyArray().apply {
222
+ for (record in records) {
223
+ pushMap(
224
+ JavaOnlyMap().apply {
225
+ putInt("tnf", record.tnf.toInt())
226
+ putString("type", base64(record.type))
227
+ putString("id", base64(record.id))
228
+ putString("payload", base64(record.payload))
229
+ },
230
+ )
231
+ }
232
+ },
233
+ )
234
+ putBoolean("writable", writable)
235
+ putInt("capacity", capacity)
236
+ putString("id", tag.id.joinToString("") { "%02x".format(it) })
237
+ }
238
+
239
+ /** The runtime's records, which NdefRecord checks: it throws for a bad one. */
240
+ private fun records(list: com.lynx.react.bridge.ReadableArray): Array<NdefRecord> =
241
+ Array(list.size()) { index ->
242
+ val record = list.getMap(index) ?: throw IllegalArgumentException("Not a record")
243
+ if (record.getType("tnf") !in NUMBERS) throw IllegalArgumentException("No tnf")
244
+ NdefRecord(
245
+ record.getDouble("tnf").toInt().toShort(),
246
+ bytes(record, "type"),
247
+ bytes(record, "id"),
248
+ bytes(record, "payload"),
249
+ )
250
+ }
251
+
252
+ private fun bytes(record: ReadableMap, name: String): ByteArray =
253
+ if (record.hasKey(name) && record.getType(name) == ReadableType.String) {
254
+ Base64.decode(record.getString(name), Base64.DEFAULT)
255
+ } else {
256
+ ByteArray(0)
257
+ }
258
+
259
+ private fun base64(bytes: ByteArray): String = Base64.encodeToString(bytes, Base64.NO_WRAP)
260
+
261
+ private fun error(code: String, message: String) = JavaOnlyMap().apply {
262
+ putString("error", code)
263
+ putString("message", message)
264
+ }
265
+
266
+ companion object {
267
+ const val NAME = "AngularLynxNfc"
268
+ private val NUMBERS = setOf(ReadableType.Int, ReadableType.Long, ReadableType.Number)
269
+
270
+ /** Every kind of tag that can hold NDEF. */
271
+ private const val READER_FLAGS = NfcAdapter.FLAG_READER_NFC_A or NfcAdapter.FLAG_READER_NFC_B or
272
+ NfcAdapter.FLAG_READER_NFC_F or NfcAdapter.FLAG_READER_NFC_V
273
+ }
274
+ }
@@ -0,0 +1,35 @@
1
+ package dev.angularlynx.shell
2
+
3
+ /**
4
+ * Asks the person for runtime permissions on a native module's behalf.
5
+ *
6
+ * Android's permission prompt belongs to an activity, and an activity has to
7
+ * register for its result as it's created, before a module that wants it
8
+ * exists. So MainActivity registers once and lends the prompt to whichever
9
+ * module asks, which it hands this as its param. It's generic, so a module
10
+ * that needs a permission later reuses it rather than adding a launcher of
11
+ * its own.
12
+ */
13
+ interface PermissionHost {
14
+ /**
15
+ * Shows Android's prompt for [names] and calls [done] once, on the main
16
+ * thread, with whether each was granted. Must be called on the main
17
+ * thread. Returns false, without asking, while another request is open:
18
+ * the activity shows one prompt at a time.
19
+ *
20
+ * Android answers at once, without a prompt, for a permission the person
21
+ * already granted or refused for good, and for one the manifest doesn't
22
+ * declare (which counts as refused).
23
+ */
24
+ fun requestPermissions(names: Array<String>, done: (Map<String, Boolean>) -> Unit): Boolean
25
+
26
+ /**
27
+ * Whether Android would show its prompt again for [name], which the
28
+ * person refused: true after a refusal they may still change their mind
29
+ * about, false once they've ticked "Don't ask again" (and for a
30
+ * permission never asked for). Only an activity can tell, so a module
31
+ * that reports `denied` and `undetermined` apart asks it here. Any
32
+ * thread.
33
+ */
34
+ fun canAskAgain(name: String): Boolean = false
35
+ }
@@ -0,0 +1,355 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.Manifest
4
+ import android.content.ContentValues
5
+ import android.content.Context
6
+ import android.content.pm.PackageManager
7
+ import android.database.sqlite.SQLiteException
8
+ import android.net.Uri
9
+ import android.os.Build
10
+ import android.os.Environment
11
+ import android.os.Handler
12
+ import android.os.Looper
13
+ import android.provider.MediaStore
14
+ import android.util.Base64
15
+ import androidx.annotation.RequiresApi
16
+ import androidx.core.content.ContextCompat
17
+ import com.lynx.jsbridge.LynxMethod
18
+ import com.lynx.jsbridge.LynxModule
19
+ import com.lynx.react.bridge.Callback
20
+ import com.lynx.react.bridge.JavaOnlyMap
21
+ import com.lynx.react.bridge.ReadableMap
22
+ import java.io.File
23
+ import java.io.IOException
24
+ import java.util.concurrent.Executors
25
+
26
+ /**
27
+ * The native module behind the runtime's `LynxPhotoLibrary`, which calls it
28
+ * as `NativeModules.AngularLynxPhotoLibrary` (from the background thread,
29
+ * where NativeModules lives).
30
+ *
31
+ * Only an app with `permissions.savePhotos` in angular.json has this file
32
+ * and the lines in MainActivity that register it: the generator deletes them
33
+ * from the others (@blotch/angular-lynx-native's android/project.ts).
34
+ *
35
+ * A photo goes into MediaStore's images, in `Pictures/<app name>`, and a
36
+ * video into its videos, in `Movies/<app name>`, where the gallery and
37
+ * Google Photos find them. From Android 10 an app may add its own media
38
+ * there without any permission. Android 7 to 9 need WRITE_EXTERNAL_STORAGE,
39
+ * and READ_EXTERNAL_STORAGE with it (Android 8 and 9 mount shared storage
40
+ * writable only for an app holding both, so with WRITE alone a save is
41
+ * refused once the app restarts), runtime permissions the manifest declares
42
+ * only up to Android 9: the first save there asks for them through
43
+ * MainActivity's prompt (PermissionHost, the module's param), then writes
44
+ * the file into the public folder and adds it to MediaStore, as those
45
+ * versions' MediaStore has no RELATIVE_PATH or IS_PENDING. Each method calls back once with `{ permission }`,
46
+ * `{ id, permission }` or `{ error, message, permission }`, where `error` is
47
+ * one of the runtime's PhotoLibraryErrorCode values.
48
+ */
49
+ class PhotoLibraryModule(context: Context, param: Any?) : LynxModule(context, param) {
50
+ private val appContext = context.applicationContext
51
+ private val resolver = appContext.contentResolver
52
+ private val appName =
53
+ context.applicationInfo.loadLabel(context.packageManager).toString()
54
+
55
+ /**
56
+ * MainActivity's permission prompt, for Android 7 to 9. Null for a module
57
+ * registered without it, as a project ejected before the prompt was lent
58
+ * to this module registers it: that app can't ask, so a save there
59
+ * answers `permission-denied`.
60
+ */
61
+ private val permissions = param as? PermissionHost
62
+
63
+ // The activity's prompt is shown, and answered, on the main thread, so
64
+ // the saves waiting on it are kept there too.
65
+ private val main = Handler(Looper.getMainLooper())
66
+
67
+ /**
68
+ * The saves waiting for the person to answer the storage prompt. The
69
+ * first opens it, and those that come while it's open wait for the same
70
+ * answer, since the activity shows one prompt at a time.
71
+ */
72
+ private val waitingForStorage = mutableListOf<() -> Unit>()
73
+
74
+ // Whether the app has asked for the storage permission before. Android
75
+ // can't tell an app that, and a permission never asked for looks just
76
+ // like one refused for good, so it's kept across launches to tell
77
+ // `undetermined` from `denied`.
78
+ private val preferences = appContext.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE)
79
+
80
+ /** `{ permission }`: whether the app may add to the library. */
81
+ @LynxMethod
82
+ fun permission(callback: Callback) {
83
+ callback.invoke(JavaOnlyMap.from(mapOf("permission" to permissionName())))
84
+ }
85
+
86
+ /**
87
+ * Adds [request]'s file (`{ base64, name, type }`) to the library, and
88
+ * calls back with its `content://` URI.
89
+ */
90
+ @LynxMethod
91
+ fun save(request: ReadableMap, callback: Callback) {
92
+ if (needsStorage() && !storageGranted()) {
93
+ main.post { askForStorage { if (storageGranted()) write(request, callback) else refused(callback) } }
94
+ return
95
+ }
96
+ write(request, callback)
97
+ }
98
+
99
+ /**
100
+ * Asks for the storage permissions, then calls [answered] on the main
101
+ * thread once the person has chosen, or at once when the app can't ask.
102
+ */
103
+ private fun askForStorage(answered: () -> Unit) {
104
+ waitingForStorage += answered
105
+ if (waitingForStorage.size > 1) return
106
+ val host = permissions
107
+ val asked = try {
108
+ host?.requestPermissions(STORAGE) { results ->
109
+ // An empty answer is a prompt closed without a choice (the
110
+ // activity going away mid-request), which refused nothing:
111
+ // counting it as asked would read as denied for good.
112
+ if (results.isNotEmpty()) preferences.edit().putBoolean(ASKED, true).apply()
113
+ answerWaiting()
114
+ } ?: false
115
+ } catch (_: IllegalStateException) {
116
+ // The activity's launcher throws once the activity is going.
117
+ false
118
+ }
119
+ if (!asked) answerWaiting()
120
+ }
121
+
122
+ private fun answerWaiting() {
123
+ val waiting = waitingForStorage.toList()
124
+ waitingForStorage.clear()
125
+ waiting.forEach { it() }
126
+ }
127
+
128
+ private fun refused(callback: Callback) {
129
+ callback.invoke(
130
+ failure(
131
+ "permission-denied",
132
+ if (permissions == null) {
133
+ "This app can't ask for the storage permission Android ${Build.VERSION.RELEASE} needs to save photos."
134
+ } else {
135
+ "The app isn't allowed to add to the photo library."
136
+ },
137
+ ),
138
+ )
139
+ }
140
+
141
+ private fun write(request: ReadableMap, callback: Callback) {
142
+ // Decoding and writing a video takes a moment: off the JavaScript
143
+ // thread, one at a time.
144
+ worker.execute {
145
+ callback.invoke(
146
+ try {
147
+ JavaOnlyMap.from(
148
+ mapOf("id" to insert(request).toString(), "permission" to permissionName()),
149
+ )
150
+ } catch (error: UnsupportedType) {
151
+ failure("unsupported-type", error.message ?: "Only images and videos can be saved.")
152
+ } catch (error: IllegalArgumentException) {
153
+ failure("failed", "The file's bytes couldn't be read.")
154
+ } catch (error: IOException) {
155
+ failure("failed", "The file couldn't be saved to the photo library: ${error.message}")
156
+ } catch (error: SecurityException) {
157
+ failure("permission-denied", "The app isn't allowed to add to the photo library.")
158
+ } catch (error: SQLiteException) {
159
+ // MediaStore's database couldn't take the entry, such as
160
+ // SQLiteFullException on a full phone. The provider
161
+ // rethrows it in the app, unchecked.
162
+ failure("failed", "The file couldn't be saved to the photo library: ${error.message}")
163
+ } catch (error: RuntimeException) {
164
+ // Anything else MediaStore throws: without an answer the
165
+ // runtime's save() would never settle, and an exception
166
+ // left on this thread would end the app.
167
+ failure("failed", "The file couldn't be saved to the photo library: ${error.message}")
168
+ },
169
+ )
170
+ }
171
+ }
172
+
173
+ private fun insert(request: ReadableMap): Uri {
174
+ val media = decode(request)
175
+ // Spelled out rather than needsStorage(), so lint sees the check.
176
+ return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) insertFile(media) else insertPending(media)
177
+ }
178
+
179
+ /** What [request] asks to save: its bytes, name and type, checked. */
180
+ private fun decode(request: ReadableMap): Media {
181
+ val base64 = if (request.hasKey("base64")) request.getString("base64") else null
182
+ val bytes = Base64.decode(base64 ?: throw IllegalArgumentException(), Base64.DEFAULT)
183
+ val type = if (request.hasKey("type")) request.getString("type") ?: "" else ""
184
+ val isVideo = type.startsWith("video/")
185
+ if (!isVideo && !type.startsWith("image/")) {
186
+ throw UnsupportedType("$type isn't an image or a video.")
187
+ }
188
+ val name = (if (request.hasKey("name")) request.getString("name") else null)
189
+ ?.replace('/', '_')
190
+ ?.takeIf { it.isNotBlank() }
191
+ ?: if (isVideo) "Video.mp4" else "Photo.jpg"
192
+ return Media(bytes, name, type, isVideo)
193
+ }
194
+
195
+ /**
196
+ * Android 10 and later: a MediaStore entry in the app's folder, hidden
197
+ * until its bytes are all written.
198
+ */
199
+ @RequiresApi(Build.VERSION_CODES.Q)
200
+ private fun insertPending(media: Media): Uri {
201
+ val (bytes, name, type, isVideo) = media
202
+ val collection =
203
+ if (isVideo) {
204
+ MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
205
+ } else {
206
+ MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
207
+ }
208
+ val folder = if (isVideo) Environment.DIRECTORY_MOVIES else Environment.DIRECTORY_PICTURES
209
+ val values = ContentValues().apply {
210
+ put(MediaStore.MediaColumns.DISPLAY_NAME, name)
211
+ put(MediaStore.MediaColumns.MIME_TYPE, type)
212
+ put(MediaStore.MediaColumns.RELATIVE_PATH, "$folder/${folderName()}")
213
+ // Hidden from the gallery until it's all written, so nobody sees
214
+ // half a photo, and taken out again if writing fails.
215
+ put(MediaStore.MediaColumns.IS_PENDING, 1)
216
+ }
217
+ val uri = try {
218
+ resolver.insert(collection, values)
219
+ } catch (error: IllegalArgumentException) {
220
+ // MediaStore refuses a type its collection doesn't hold, such as
221
+ // an image type it doesn't know.
222
+ throw UnsupportedType("The photo library doesn't take $type files.")
223
+ } ?: throw IOException("MediaStore didn't make an entry for it.")
224
+ try {
225
+ resolver.openOutputStream(uri)?.use { it.write(bytes) }
226
+ ?: throw IOException("The new entry couldn't be opened.")
227
+ resolver.update(
228
+ uri,
229
+ ContentValues().apply { put(MediaStore.MediaColumns.IS_PENDING, 0) },
230
+ null,
231
+ null,
232
+ )
233
+ } catch (error: Exception) {
234
+ // A failed cleanup mustn't hide why the write failed.
235
+ try {
236
+ resolver.delete(uri, null, null)
237
+ } catch (cleanup: RuntimeException) {
238
+ error.addSuppressed(cleanup)
239
+ }
240
+ throw error
241
+ }
242
+ return uri
243
+ }
244
+
245
+ /**
246
+ * Android 7 to 9: the file written into the public Pictures or Movies
247
+ * folder, in the app's own folder, then added to MediaStore by its path,
248
+ * which those versions' MediaStore takes in place of RELATIVE_PATH.
249
+ * Inserting gives the `content://` URI at once, where a media scan would
250
+ * answer later.
251
+ */
252
+ @Suppress("DEPRECATION")
253
+ private fun insertFile(media: Media): Uri {
254
+ val (bytes, name, type, isVideo) = media
255
+ if (Environment.getExternalStorageState() != Environment.MEDIA_MOUNTED) {
256
+ throw IOException("The phone's shared storage isn't available.")
257
+ }
258
+ val folder = File(
259
+ Environment.getExternalStoragePublicDirectory(
260
+ if (isVideo) Environment.DIRECTORY_MOVIES else Environment.DIRECTORY_PICTURES,
261
+ ),
262
+ folderName(),
263
+ )
264
+ if (!folder.isDirectory && !folder.mkdirs()) {
265
+ throw IOException("The folder ${folder.path} couldn't be made.")
266
+ }
267
+ val file = unusedFile(folder, name)
268
+ try {
269
+ file.writeBytes(bytes)
270
+ val values = ContentValues().apply {
271
+ put(MediaStore.MediaColumns.DATA, file.absolutePath)
272
+ put(MediaStore.MediaColumns.DISPLAY_NAME, file.name)
273
+ put(MediaStore.MediaColumns.MIME_TYPE, type)
274
+ put(MediaStore.MediaColumns.SIZE, bytes.size.toLong())
275
+ val now = System.currentTimeMillis()
276
+ put(MediaStore.MediaColumns.DATE_ADDED, now / 1000)
277
+ put(MediaStore.MediaColumns.DATE_MODIFIED, now / 1000)
278
+ if (!isVideo) put(MediaStore.Images.ImageColumns.DATE_TAKEN, now)
279
+ }
280
+ val collection =
281
+ if (isVideo) MediaStore.Video.Media.EXTERNAL_CONTENT_URI else MediaStore.Images.Media.EXTERNAL_CONTENT_URI
282
+ return try {
283
+ resolver.insert(collection, values)
284
+ } catch (error: IllegalArgumentException) {
285
+ throw UnsupportedType("The photo library doesn't take $type files.")
286
+ } ?: throw IOException("MediaStore didn't make an entry for it.")
287
+ } catch (error: Exception) {
288
+ // Nothing half-saved stays behind in the folder.
289
+ file.delete()
290
+ throw error
291
+ }
292
+ }
293
+
294
+ /**
295
+ * [name] in [folder], or `name (2).jpg` and on while that's taken: a file
296
+ * written over would change a photo already in the gallery. Android 10's
297
+ * MediaStore picks a free name itself.
298
+ */
299
+ private fun unusedFile(folder: File, name: String): File {
300
+ val dot = name.lastIndexOf('.').takeIf { it > 0 } ?: name.length
301
+ val stem = name.substring(0, dot)
302
+ val extension = name.substring(dot)
303
+ var file = File(folder, name)
304
+ var count = 2
305
+ while (file.exists()) file = File(folder, "$stem ($count)$extension").also { count++ }
306
+ return file
307
+ }
308
+
309
+ /** The app's name as a folder, without what a path can't hold. */
310
+ private fun folderName(): String =
311
+ appName.replace(Regex("[\\\\/:*?\"<>|]"), "_").trim().ifEmpty { "Pictures" }
312
+
313
+ /** Whether this Android version needs the storage permissions to add media. */
314
+ private fun needsStorage() = Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
315
+
316
+ private fun storageGranted() = STORAGE.all {
317
+ ContextCompat.checkSelfPermission(appContext, it) == PackageManager.PERMISSION_GRANTED
318
+ }
319
+
320
+ /**
321
+ * `granted` from Android 10, or with the storage permission. Without it,
322
+ * `undetermined` while asking would still show Android's prompt (never
323
+ * asked, or refused without "Don't ask again"), and `denied` once only
324
+ * Settings can give it.
325
+ */
326
+ private fun permissionName(): String = when {
327
+ !needsStorage() || storageGranted() -> "granted"
328
+ preferences.getBoolean(ASKED, false) && STORAGE.none { permissions?.canAskAgain(it) == true } -> "denied"
329
+ else -> "undetermined"
330
+ }
331
+
332
+ private fun failure(code: String, message: String) =
333
+ JavaOnlyMap.from(mapOf("error" to code, "message" to message, "permission" to permissionName()))
334
+
335
+ private class UnsupportedType(message: String) : Exception(message)
336
+
337
+ /** A file to save, as [decode] read it from the request. */
338
+ private data class Media(val bytes: ByteArray, val name: String, val type: String, val isVideo: Boolean)
339
+
340
+ companion object {
341
+ const val NAME = "AngularLynxPhotoLibrary"
342
+
343
+ // Capped at Android 9 in the manifest (permissions.ts).
344
+ @Suppress("DEPRECATION")
345
+ private val STORAGE = arrayOf(
346
+ Manifest.permission.READ_EXTERNAL_STORAGE,
347
+ Manifest.permission.WRITE_EXTERNAL_STORAGE,
348
+ )
349
+ private const val PREFERENCES = "dev.angularlynx.shell.PhotoLibrary"
350
+ private const val ASKED = "askedForStorage"
351
+
352
+ // One thread, so saves happen in the order the app made them.
353
+ private val worker = Executors.newSingleThreadExecutor()
354
+ }
355
+ }