@app-swiss-knife/react-native-sdk 0.3.2 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +465 -0
- package/LICENSE +21 -0
- package/README.md +229 -42
- package/SwissKnifePurchases.podspec +1 -1
- package/android/build.gradle +24 -2
- package/android/consumer-rules.pro +12 -0
- package/android/src/main/AndroidManifest.xml +15 -1
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
- package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +7 -2
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
- package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
- package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
- package/android/vendor/java/com/appswissknife/SwissKnife.kt +107 -38
- package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
- package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
- package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
- package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
- package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +641 -208
- package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
- package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
- package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
- package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +69 -35
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +756 -98
- package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
- package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
- package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
- package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
- package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
- package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
- package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
- package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
- package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
- package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +266 -64
- package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
- package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +545 -88
- package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
- package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +21 -0
- package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +14 -0
- package/android/vendor-rustore/AndroidManifest.xml +59 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
- package/app.plugin.js +287 -0
- package/ios/SwissKnifePurchases.m +20 -0
- package/ios/SwissKnifePurchases.swift +97 -3
- package/ios/SwissKnifePushBootstrap.m +34 -0
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +531 -100
- package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
- package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
- package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
- package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
- package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
- package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
- package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
- package/lib/commonjs/attribution.js +4 -3
- package/lib/commonjs/attribution.js.map +1 -1
- package/lib/commonjs/identity.js +12 -11
- package/lib/commonjs/identity.js.map +1 -1
- package/lib/commonjs/index.js +16 -5
- package/lib/commonjs/index.js.map +1 -1
- package/lib/commonjs/internal/config.js +105 -8
- package/lib/commonjs/internal/config.js.map +1 -1
- package/lib/commonjs/internal/telemetry-context.js +70 -0
- package/lib/commonjs/internal/telemetry-context.js.map +1 -0
- package/lib/commonjs/modules/analytics.js +18 -25
- package/lib/commonjs/modules/analytics.js.map +1 -1
- package/lib/commonjs/modules/crash-reporting.js +353 -31
- package/lib/commonjs/modules/crash-reporting.js.map +1 -1
- package/lib/commonjs/modules/log.js +1 -1
- package/lib/commonjs/modules/notifications.js +500 -0
- package/lib/commonjs/modules/notifications.js.map +1 -0
- package/lib/commonjs/modules/performance.js +57 -8
- package/lib/commonjs/modules/performance.js.map +1 -1
- package/lib/commonjs/native/module.js +6 -0
- package/lib/commonjs/native/module.js.map +1 -1
- package/lib/commonjs/native/spec.js +12 -5
- package/lib/commonjs/native/spec.js.map +1 -1
- package/lib/commonjs/purchases.js +4 -4
- package/lib/commonjs/types.js +12 -15
- package/lib/commonjs/types.js.map +1 -1
- package/lib/module/attribution.js +4 -3
- package/lib/module/attribution.js.map +1 -1
- package/lib/module/identity.js +12 -11
- package/lib/module/identity.js.map +1 -1
- package/lib/module/index.js +8 -4
- package/lib/module/index.js.map +1 -1
- package/lib/module/internal/config.js +103 -8
- package/lib/module/internal/config.js.map +1 -1
- package/lib/module/internal/telemetry-context.js +63 -0
- package/lib/module/internal/telemetry-context.js.map +1 -0
- package/lib/module/modules/analytics.js +18 -25
- package/lib/module/modules/analytics.js.map +1 -1
- package/lib/module/modules/crash-reporting.js +353 -31
- package/lib/module/modules/crash-reporting.js.map +1 -1
- package/lib/module/modules/log.js +1 -1
- package/lib/module/modules/notifications.js +491 -0
- package/lib/module/modules/notifications.js.map +1 -0
- package/lib/module/modules/performance.js +57 -8
- package/lib/module/modules/performance.js.map +1 -1
- package/lib/module/native/module.js +6 -1
- package/lib/module/native/module.js.map +1 -1
- package/lib/module/native/spec.js +11 -4
- package/lib/module/native/spec.js.map +1 -1
- package/lib/module/purchases.js +4 -4
- package/lib/module/types.js +12 -15
- package/lib/module/types.js.map +1 -1
- package/lib/typescript/commonjs/attribution.d.ts +3 -2
- package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
- package/lib/typescript/commonjs/identity.d.ts.map +1 -1
- package/lib/typescript/commonjs/index.d.ts +3 -1
- package/lib/typescript/commonjs/index.d.ts.map +1 -1
- package/lib/typescript/commonjs/internal/config.d.ts +16 -2
- package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
- package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
- package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
- package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts +50 -12
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
- package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
- package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
- package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
- package/lib/typescript/commonjs/native/module.d.ts +2 -0
- package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
- package/lib/typescript/commonjs/native/spec.d.ts +33 -4
- package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
- package/lib/typescript/commonjs/purchases.d.ts +4 -4
- package/lib/typescript/commonjs/types.d.ts +4 -5
- package/lib/typescript/commonjs/types.d.ts.map +1 -1
- package/lib/typescript/module/attribution.d.ts +3 -2
- package/lib/typescript/module/attribution.d.ts.map +1 -1
- package/lib/typescript/module/identity.d.ts.map +1 -1
- package/lib/typescript/module/index.d.ts +3 -1
- package/lib/typescript/module/index.d.ts.map +1 -1
- package/lib/typescript/module/internal/config.d.ts +16 -2
- package/lib/typescript/module/internal/config.d.ts.map +1 -1
- package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
- package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
- package/lib/typescript/module/modules/analytics.d.ts +8 -11
- package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
- package/lib/typescript/module/modules/crash-reporting.d.ts +50 -12
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
- package/lib/typescript/module/modules/notifications.d.ts +110 -0
- package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
- package/lib/typescript/module/modules/performance.d.ts +13 -0
- package/lib/typescript/module/modules/performance.d.ts.map +1 -1
- package/lib/typescript/module/native/module.d.ts +2 -0
- package/lib/typescript/module/native/module.d.ts.map +1 -1
- package/lib/typescript/module/native/spec.d.ts +33 -4
- package/lib/typescript/module/native/spec.d.ts.map +1 -1
- package/lib/typescript/module/purchases.d.ts +4 -4
- package/lib/typescript/module/types.d.ts +4 -5
- package/lib/typescript/module/types.d.ts.map +1 -1
- package/package.json +13 -4
- package/src/attribution.ts +4 -3
- package/src/identity.ts +12 -11
- package/src/index.ts +18 -4
- package/src/internal/config.ts +113 -8
- package/src/internal/telemetry-context.ts +76 -0
- package/src/modules/analytics.ts +24 -33
- package/src/modules/crash-reporting.ts +476 -67
- package/src/modules/log.ts +1 -1
- package/src/modules/notifications.ts +557 -0
- package/src/modules/performance.ts +94 -14
- package/src/native/module.ts +6 -0
- package/src/native/spec.ts +45 -10
- package/src/purchases.ts +4 -4
- package/src/types.ts +12 -15
- package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
- package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
|
@@ -25,6 +25,30 @@
|
|
|
25
25
|
// - All public methods synchronize on a single object lock. Disk I/O is
|
|
26
26
|
// slow enough that a serial lock is the right tradeoff vs a reader/
|
|
27
27
|
// writer lock; we never need concurrent reads.
|
|
28
|
+
//
|
|
29
|
+
// Cost per append:
|
|
30
|
+
// - `append()` runs on the caller's thread, so it must not grow with the
|
|
31
|
+
// queue. The item count is cached after ONE read of the file and kept
|
|
32
|
+
// current by every mutation; `count()` and the limit check read it, so
|
|
33
|
+
// an append is one write + fsync however many items are queued. Both
|
|
34
|
+
// used to scan the whole file, twice per append. Each use checks the
|
|
35
|
+
// file length the cache was taken at (one stat), so a file another
|
|
36
|
+
// instance wrote is re-read rather than miscounted. Only exceeding a
|
|
37
|
+
// cap still costs a full read + rewrite, and the trim goes down to a
|
|
38
|
+
// low watermark (90% of the item cap), so a queue that stays full pays
|
|
39
|
+
// it once per maxItems / 10 appends instead of on every one.
|
|
40
|
+
//
|
|
41
|
+
// Dead letter:
|
|
42
|
+
// - `dead-letter.jsonl` is capped at `maxDeadLetterBytes`; an append that
|
|
43
|
+
// pushes it over drops the OLDEST lines until it is back under three
|
|
44
|
+
// quarters of the cap, reading only the tail that is kept. It used to
|
|
45
|
+
// grow without bound.
|
|
46
|
+
//
|
|
47
|
+
// Sidecars:
|
|
48
|
+
// - `readSidecar` / `writeSidecar` keep a small state file of the queue's
|
|
49
|
+
// owner in the same directory (IngestClient keeps `set-aside.json`
|
|
50
|
+
// there), replaced atomically. They never touch `items.jsonl`, so the
|
|
51
|
+
// cached count stays valid. Mirror of the iOS store's sidecars.
|
|
28
52
|
|
|
29
53
|
package com.appswissknife.net
|
|
30
54
|
|
|
@@ -35,6 +59,7 @@ import java.io.File
|
|
|
35
59
|
import java.io.FileOutputStream
|
|
36
60
|
import java.io.IOException
|
|
37
61
|
import java.io.InputStreamReader
|
|
62
|
+
import java.io.RandomAccessFile
|
|
38
63
|
|
|
39
64
|
/**
|
|
40
65
|
* One queued item must serialize itself to JSON and expose a stable string
|
|
@@ -53,8 +78,12 @@ internal interface OfflineQueueItem {
|
|
|
53
78
|
internal object OfflineQueueStoreDefaults {
|
|
54
79
|
const val MAX_ITEMS: Int = 10_000
|
|
55
80
|
const val MAX_BYTES: Long = 10L * 1024L * 1024L
|
|
81
|
+
/** Dead letters are diagnostics, not a delivery path: keep a bounded tail. */
|
|
82
|
+
const val MAX_DEAD_LETTER_BYTES: Long = 1L * 1024L * 1024L
|
|
56
83
|
}
|
|
57
84
|
|
|
85
|
+
private const val NEWLINE: Byte = 0x0A
|
|
86
|
+
|
|
58
87
|
/**
|
|
59
88
|
* Generic disk-backed FIFO queue. `T` is any type implementing
|
|
60
89
|
* [OfflineQueueItem]; the caller supplies a `parser` lambda that turns a
|
|
@@ -70,10 +99,17 @@ internal class OfflineQueueStore<T : OfflineQueueItem>(
|
|
|
70
99
|
private val parser: (JSONObject) -> T,
|
|
71
100
|
private val maxItems: Int = OfflineQueueStoreDefaults.MAX_ITEMS,
|
|
72
101
|
private val maxBytes: Long = OfflineQueueStoreDefaults.MAX_BYTES,
|
|
102
|
+
private val maxDeadLetterBytes: Long = OfflineQueueStoreDefaults.MAX_DEAD_LETTER_BYTES,
|
|
73
103
|
) {
|
|
74
104
|
private val tag = "SwissKnife.Queue.$name"
|
|
75
105
|
private val lock = Any()
|
|
76
106
|
|
|
107
|
+
// Guarded by `lock`. `cachedCount` is the number of items in `file` when
|
|
108
|
+
// it was `cachedLength` bytes long; `null` until the first full read.
|
|
109
|
+
private var cachedCount: Int? = null
|
|
110
|
+
private var cachedLength: Long = -1L
|
|
111
|
+
private var fullScans = 0
|
|
112
|
+
|
|
77
113
|
private val file: File
|
|
78
114
|
private val deadLetterFile: File
|
|
79
115
|
|
|
@@ -82,7 +118,10 @@ internal class OfflineQueueStore<T : OfflineQueueItem>(
|
|
|
82
118
|
file = File(directory, "items.jsonl")
|
|
83
119
|
deadLetterFile = File(directory, "dead-letter.jsonl")
|
|
84
120
|
if (!file.exists()) {
|
|
85
|
-
runCatching { file.createNewFile() }
|
|
121
|
+
if (runCatching { file.createNewFile() }.getOrDefault(false)) {
|
|
122
|
+
// A file we just created is empty: nothing to read.
|
|
123
|
+
rememberCountLocked(0)
|
|
124
|
+
}
|
|
86
125
|
}
|
|
87
126
|
}
|
|
88
127
|
|
|
@@ -135,8 +174,8 @@ internal class OfflineQueueStore<T : OfflineQueueItem>(
|
|
|
135
174
|
}
|
|
136
175
|
}
|
|
137
176
|
|
|
138
|
-
/** Current number of items.
|
|
139
|
-
fun count(): Int = synchronized(lock) {
|
|
177
|
+
/** Current number of items. O(1) after the first access: reads the cache. */
|
|
178
|
+
fun count(): Int = synchronized(lock) { countLocked() }
|
|
140
179
|
|
|
141
180
|
/** Bytes on disk for the items file. */
|
|
142
181
|
fun sizeBytes(): Long = synchronized(lock) {
|
|
@@ -180,16 +219,96 @@ internal class OfflineQueueStore<T : OfflineQueueItem>(
|
|
|
180
219
|
}
|
|
181
220
|
}
|
|
182
221
|
|
|
222
|
+
/**
|
|
223
|
+
* A small state file the queue's owner keeps beside the queue ([name] is
|
|
224
|
+
* a plain file name in the queue's directory). Returns null when there is
|
|
225
|
+
* none. Throws when it exists but cannot be read or is larger than
|
|
226
|
+
* [maxBytes], so the owner can tell a damaged file from a missing one.
|
|
227
|
+
*/
|
|
228
|
+
@Throws(IOException::class)
|
|
229
|
+
fun readSidecar(name: String, maxBytes: Long): String? {
|
|
230
|
+
synchronized(lock) {
|
|
231
|
+
val sidecar = sidecarFile(name)
|
|
232
|
+
if (!sidecar.exists()) return null
|
|
233
|
+
val length = sidecar.length()
|
|
234
|
+
if (length > maxBytes) throw IOException("sidecar $name is $length bytes, over $maxBytes")
|
|
235
|
+
return sidecar.readText(Charsets.UTF_8)
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Replace a sidecar atomically (write a temporary file, then rename over
|
|
241
|
+
* it), or delete it when [data] is null. Best-effort like the dead-letter
|
|
242
|
+
* file: a failure is logged and swallowed, because the live queue must
|
|
243
|
+
* keep moving without it. Returns whether the file now holds [data].
|
|
244
|
+
*/
|
|
245
|
+
fun writeSidecar(name: String, data: String?): Boolean {
|
|
246
|
+
synchronized(lock) {
|
|
247
|
+
val sidecar = sidecarFile(name)
|
|
248
|
+
if (data == null) {
|
|
249
|
+
if (!sidecar.exists() || sidecar.delete()) return true
|
|
250
|
+
Log.w(tag, "sidecar $name delete failed")
|
|
251
|
+
return false
|
|
252
|
+
}
|
|
253
|
+
directory.takeIf { !it.exists() }?.mkdirs()
|
|
254
|
+
val tmp = File(directory, "$name.tmp")
|
|
255
|
+
try {
|
|
256
|
+
FileOutputStream(tmp, false).use { out ->
|
|
257
|
+
out.write(data.toByteArray(Charsets.UTF_8))
|
|
258
|
+
out.flush()
|
|
259
|
+
runCatching { out.fd.sync() }
|
|
260
|
+
}
|
|
261
|
+
if (tmp.renameTo(sidecar)) return true
|
|
262
|
+
sidecar.delete()
|
|
263
|
+
if (tmp.renameTo(sidecar)) return true
|
|
264
|
+
Log.w(tag, "sidecar $name rename failed")
|
|
265
|
+
} catch (e: IOException) {
|
|
266
|
+
Log.w(tag, "sidecar $name write failed", e)
|
|
267
|
+
}
|
|
268
|
+
tmp.delete()
|
|
269
|
+
return false
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Test seam — how many times `items.jsonl` has been read in full. */
|
|
274
|
+
internal fun fullScansForTesting(): Int = synchronized(lock) { fullScans }
|
|
275
|
+
|
|
183
276
|
// ----- Internals (must hold lock) -----
|
|
184
277
|
|
|
278
|
+
private fun rememberCountLocked(count: Int) {
|
|
279
|
+
cachedCount = count
|
|
280
|
+
cachedLength = if (file.exists()) file.length() else 0L
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
private fun forgetCountLocked() {
|
|
284
|
+
cachedCount = null
|
|
285
|
+
cachedLength = -1L
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** The cached count while the file is the length it was taken at; else one full read. */
|
|
289
|
+
private fun countLocked(): Int {
|
|
290
|
+
val cached = cachedCount
|
|
291
|
+
val length = if (file.exists()) file.length() else 0L
|
|
292
|
+
if (cached != null && length == cachedLength) return cached
|
|
293
|
+
return readAllLocked().first.size // re-caches
|
|
294
|
+
}
|
|
295
|
+
|
|
185
296
|
private fun appendLocked(item: T) {
|
|
186
297
|
file.parentFile?.takeIf { !it.exists() }?.mkdirs()
|
|
187
298
|
val line = item.toJson().toString() + "\n"
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
299
|
+
// Whether the cache described the file before this write.
|
|
300
|
+
val cached = cachedCount?.takeIf { (if (file.exists()) file.length() else 0L) == cachedLength }
|
|
301
|
+
try {
|
|
302
|
+
FileOutputStream(file, /* append = */ true).use { out ->
|
|
303
|
+
out.write(line.toByteArray(Charsets.UTF_8))
|
|
304
|
+
out.flush()
|
|
305
|
+
runCatching { out.fd.sync() }
|
|
306
|
+
}
|
|
307
|
+
} catch (e: IOException) {
|
|
308
|
+
forgetCountLocked() // unknown what landed; the next use re-reads
|
|
309
|
+
throw e
|
|
192
310
|
}
|
|
311
|
+
if (cached != null) rememberCountLocked(cached + 1) else forgetCountLocked()
|
|
193
312
|
}
|
|
194
313
|
|
|
195
314
|
/**
|
|
@@ -198,9 +317,14 @@ internal class OfflineQueueStore<T : OfflineQueueItem>(
|
|
|
198
317
|
* don't haunt subsequent reads.
|
|
199
318
|
*/
|
|
200
319
|
private fun readAllLocked(): Pair<List<T>, Boolean> {
|
|
201
|
-
if (!file.exists())
|
|
320
|
+
if (!file.exists()) {
|
|
321
|
+
rememberCountLocked(0)
|
|
322
|
+
return Pair(emptyList(), false)
|
|
323
|
+
}
|
|
324
|
+
fullScans++
|
|
202
325
|
val out = ArrayList<T>()
|
|
203
326
|
var sawBad = false
|
|
327
|
+
var readFailed = false
|
|
204
328
|
try {
|
|
205
329
|
BufferedReader(InputStreamReader(file.inputStream(), Charsets.UTF_8)).use { reader ->
|
|
206
330
|
while (true) {
|
|
@@ -216,9 +340,14 @@ internal class OfflineQueueStore<T : OfflineQueueItem>(
|
|
|
216
340
|
}
|
|
217
341
|
} catch (e: IOException) {
|
|
218
342
|
Log.w(tag, "readAll failed; returning ${out.size}", e)
|
|
343
|
+
readFailed = true
|
|
219
344
|
}
|
|
220
|
-
if (
|
|
221
|
-
|
|
345
|
+
if (readFailed) {
|
|
346
|
+
forgetCountLocked()
|
|
347
|
+
} else if (sawBad) {
|
|
348
|
+
runCatching { writeAllLocked(out) } // re-caches on success
|
|
349
|
+
} else {
|
|
350
|
+
rememberCountLocked(out.size)
|
|
222
351
|
}
|
|
223
352
|
return Pair(out, sawBad)
|
|
224
353
|
}
|
|
@@ -226,6 +355,8 @@ internal class OfflineQueueStore<T : OfflineQueueItem>(
|
|
|
226
355
|
private fun writeAllLocked(items: List<T>) {
|
|
227
356
|
file.parentFile?.takeIf { !it.exists() }?.mkdirs()
|
|
228
357
|
val tmp = File(file.parentFile, "${file.name}.tmp")
|
|
358
|
+
// Unknown until the rewrite has landed.
|
|
359
|
+
forgetCountLocked()
|
|
229
360
|
try {
|
|
230
361
|
FileOutputStream(tmp, false).use { out ->
|
|
231
362
|
for (item in items) {
|
|
@@ -239,8 +370,10 @@ internal class OfflineQueueStore<T : OfflineQueueItem>(
|
|
|
239
370
|
file.delete()
|
|
240
371
|
if (!tmp.renameTo(file)) {
|
|
241
372
|
Log.w(tag, "writeAll renameTo failed; queue may be inconsistent")
|
|
373
|
+
return
|
|
242
374
|
}
|
|
243
375
|
}
|
|
376
|
+
rememberCountLocked(items.size)
|
|
244
377
|
} catch (e: IOException) {
|
|
245
378
|
Log.w(tag, "writeAll failed", e)
|
|
246
379
|
tmp.delete()
|
|
@@ -258,24 +391,79 @@ internal class OfflineQueueStore<T : OfflineQueueItem>(
|
|
|
258
391
|
out.flush()
|
|
259
392
|
runCatching { out.fd.sync() }
|
|
260
393
|
}
|
|
394
|
+
try {
|
|
395
|
+
trimDeadLetterLocked()
|
|
396
|
+
} catch (e: IOException) {
|
|
397
|
+
Log.w(tag, "dead-letter trim failed", e)
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Keep `dead-letter.jsonl` under [maxDeadLetterBytes] by dropping its
|
|
403
|
+
* OLDEST lines. Trims to three quarters of the cap so a steady trickle
|
|
404
|
+
* of rejects does not rewrite the file on every append.
|
|
405
|
+
*
|
|
406
|
+
* Reads only the tail that can survive, never the whole file: one written
|
|
407
|
+
* before the cap existed (every 401/403 batch used to land here) may be
|
|
408
|
+
* tens of MB, and loading it as Strings on the flush thread risks an
|
|
409
|
+
* OutOfMemoryError nothing catches.
|
|
410
|
+
*/
|
|
411
|
+
private fun trimDeadLetterLocked() {
|
|
412
|
+
val length = deadLetterFile.length()
|
|
413
|
+
if (maxDeadLetterBytes <= 0L || length <= maxDeadLetterBytes) return
|
|
414
|
+
val budget = maxDeadLetterBytes * 3 / 4
|
|
415
|
+
val tail = readWholeLinesTail(deadLetterFile, length, budget)
|
|
416
|
+
val tmp = File(deadLetterFile.parentFile, "${deadLetterFile.name}.tmp")
|
|
417
|
+
FileOutputStream(tmp, false).use { out ->
|
|
418
|
+
out.write(tail)
|
|
419
|
+
out.flush()
|
|
420
|
+
runCatching { out.fd.sync() }
|
|
421
|
+
}
|
|
422
|
+
if (!tmp.renameTo(deadLetterFile)) {
|
|
423
|
+
deadLetterFile.delete()
|
|
424
|
+
if (!tmp.renameTo(deadLetterFile)) tmp.delete()
|
|
425
|
+
}
|
|
426
|
+
val kept = tail.count { it == NEWLINE }
|
|
427
|
+
Log.i(tag, "dead-letter exceeded $maxDeadLetterBytes bytes; kept the newest $kept line(s)")
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* The longest run of whole lines at the end of [file] that fits in
|
|
432
|
+
* [budget] bytes. Reads `budget + 1` bytes at most: the extra byte, just
|
|
433
|
+
* before the window, says whether the window starts on a line boundary.
|
|
434
|
+
*/
|
|
435
|
+
private fun readWholeLinesTail(file: File, length: Long, budget: Long): ByteArray {
|
|
436
|
+
val from = (length - budget).coerceAtLeast(0L)
|
|
437
|
+
val readFrom = (from - 1).coerceAtLeast(0L)
|
|
438
|
+
val window = ByteArray((length - readFrom).toInt())
|
|
439
|
+
RandomAccessFile(file, "r").use { raf ->
|
|
440
|
+
raf.seek(readFrom)
|
|
441
|
+
raf.readFully(window)
|
|
442
|
+
}
|
|
443
|
+
if (from == 0L) return window
|
|
444
|
+
// `window` starts one byte before `from`; keep from the first line
|
|
445
|
+
// that starts at or after it.
|
|
446
|
+
val newline = window.indexOf(NEWLINE)
|
|
447
|
+
return if (newline < 0) ByteArray(0) else window.copyOfRange(newline + 1, window.size)
|
|
261
448
|
}
|
|
262
449
|
|
|
263
450
|
/**
|
|
264
451
|
* Enforce (maxItems, maxBytes) by dropping oldest first. Common case
|
|
265
|
-
* (under cap) is a file.length()
|
|
452
|
+
* (under cap) is a file.length() stat plus the cached count: no read.
|
|
266
453
|
*/
|
|
267
454
|
private fun enforceLimitsLocked() {
|
|
268
|
-
|
|
269
|
-
if (sizeOk) {
|
|
270
|
-
val approx = approximateCountLocked()
|
|
271
|
-
if (approx <= maxItems) return
|
|
272
|
-
}
|
|
455
|
+
if (file.length() <= maxBytes && countLocked() <= maxItems) return
|
|
273
456
|
val (all, _) = readAllLocked()
|
|
274
457
|
if (all.size <= maxItems && file.length() <= maxBytes) return
|
|
275
458
|
|
|
276
459
|
var keep = all
|
|
277
460
|
if (keep.size > maxItems) {
|
|
278
|
-
|
|
461
|
+
// Down to a low watermark, not to exactly maxItems: trimmed to the
|
|
462
|
+
// cap, a full queue (a refused key keeps it full) would pay this
|
|
463
|
+
// read + rewrite on EVERY append, one dropped item at a time, on
|
|
464
|
+
// the caller's thread. Dropping the oldest tenth buys
|
|
465
|
+
// maxItems / 10 cheap appends.
|
|
466
|
+
val dropped = keep.size - (maxItems - maxItems / 10)
|
|
279
467
|
Log.w(tag, "queue exceeded $maxItems items; dropping oldest $dropped")
|
|
280
468
|
keep = keep.subList(dropped, keep.size).toList()
|
|
281
469
|
}
|
|
@@ -287,25 +475,21 @@ internal class OfflineQueueStore<T : OfflineQueueItem>(
|
|
|
287
475
|
writeAllLocked(keep)
|
|
288
476
|
}
|
|
289
477
|
|
|
290
|
-
private fun approximateCountLocked(): Int {
|
|
291
|
-
if (!file.exists()) return 0
|
|
292
|
-
var count = 0
|
|
293
|
-
try {
|
|
294
|
-
BufferedReader(InputStreamReader(file.inputStream(), Charsets.UTF_8)).use { reader ->
|
|
295
|
-
while (reader.readLine() != null) count++
|
|
296
|
-
}
|
|
297
|
-
} catch (_: IOException) {
|
|
298
|
-
return Int.MAX_VALUE
|
|
299
|
-
}
|
|
300
|
-
return count
|
|
301
|
-
}
|
|
302
|
-
|
|
303
478
|
private fun estimateBytesLocked(items: List<T>): Long {
|
|
304
479
|
var total = 0L
|
|
305
480
|
for (item in items) total += item.toJson().toString().length + 1
|
|
306
481
|
return total
|
|
307
482
|
}
|
|
308
483
|
|
|
484
|
+
/** A sidecar's file: a plain name in the queue's directory, never one of the queue's own files. */
|
|
485
|
+
private fun sidecarFile(name: String): File {
|
|
486
|
+
require(
|
|
487
|
+
name.isNotEmpty() && name != "." && name != ".." && '/' !in name && File.separatorChar !in name &&
|
|
488
|
+
name != file.name && name != deadLetterFile.name && !name.endsWith(".tmp"),
|
|
489
|
+
) { "not a sidecar name: $name" }
|
|
490
|
+
return File(directory, name)
|
|
491
|
+
}
|
|
492
|
+
|
|
309
493
|
private fun ensureDirectory(dir: File) {
|
|
310
494
|
if (dir.exists()) {
|
|
311
495
|
if (!dir.isDirectory) {
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
package com.appswissknife.notifications
|
|
2
|
+
|
|
3
|
+
import android.Manifest
|
|
4
|
+
import android.app.Notification
|
|
5
|
+
import android.app.NotificationChannel
|
|
6
|
+
import android.app.NotificationManager
|
|
7
|
+
import android.app.PendingIntent
|
|
8
|
+
import android.content.Context
|
|
9
|
+
import android.content.Intent
|
|
10
|
+
import android.content.pm.PackageManager
|
|
11
|
+
import android.graphics.Bitmap
|
|
12
|
+
import android.graphics.BitmapFactory
|
|
13
|
+
import android.os.Build
|
|
14
|
+
import android.util.Log
|
|
15
|
+
import androidx.lifecycle.Lifecycle
|
|
16
|
+
import androidx.lifecycle.ProcessLifecycleOwner
|
|
17
|
+
import java.io.ByteArrayOutputStream
|
|
18
|
+
import java.net.HttpURLConnection
|
|
19
|
+
import java.net.URL
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Message the messaging service extracted from FCM, independent of Firebase
|
|
23
|
+
* types so it can be unit-tested.
|
|
24
|
+
*/
|
|
25
|
+
internal data class IncomingPush(
|
|
26
|
+
val data: Map<String, String>,
|
|
27
|
+
/** `notification.title/body/image` when FCM delivered a notification payload to a foreground app. */
|
|
28
|
+
val notificationTitle: String? = null,
|
|
29
|
+
val notificationBody: String? = null,
|
|
30
|
+
val notificationImage: String? = null,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
internal object PushMessageHandler {
|
|
34
|
+
private const val TAG = "SwissKnife.Push"
|
|
35
|
+
|
|
36
|
+
internal var isForeground: () -> Boolean = {
|
|
37
|
+
runCatching {
|
|
38
|
+
ProcessLifecycleOwner.get().lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)
|
|
39
|
+
}.getOrDefault(false)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Test seam: replaces the entitlements invalidate call. */
|
|
43
|
+
internal var invalidateHandler: (Map<String, String>) -> Unit = { data ->
|
|
44
|
+
val repo = com.appswissknife.identity.Identity.entitlementsRepository()
|
|
45
|
+
if (repo != null) {
|
|
46
|
+
val keys = repo.current()?.entitlements?.all?.keys ?: emptySet()
|
|
47
|
+
repo.handleSilentFCM(data, keys)
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
internal var renderer: (Context, NotificationOpen, IncomingPush) -> Unit = { c, o, m ->
|
|
52
|
+
NotificationRenderer.render(c, o, m)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** @return true when the message was a swiss-knife message (handled here). */
|
|
56
|
+
fun handle(context: Context, msg: IncomingPush): Boolean {
|
|
57
|
+
val ctx = context.applicationContext ?: context
|
|
58
|
+
var handled = false
|
|
59
|
+
|
|
60
|
+
if (msg.data["swissknife.invalidate"] == "true") {
|
|
61
|
+
handled = true
|
|
62
|
+
runCatching { invalidateHandler(msg.data) }
|
|
63
|
+
.onFailure { Log.w(TAG, "invalidate routing failed: ${it.message}") }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
val open = PushPayload.fromMap(msg.data) ?: return handled
|
|
67
|
+
handled = true
|
|
68
|
+
|
|
69
|
+
val did = open.deliveryId
|
|
70
|
+
val mid = open.messageId
|
|
71
|
+
if (did != null && mid != null) SwissKnifeNotifications.trackEvent(ctx, did, mid, "received")
|
|
72
|
+
|
|
73
|
+
val title = open.title ?: msg.notificationTitle
|
|
74
|
+
val body = open.body ?: msg.notificationBody
|
|
75
|
+
// System tray already displays notification-payload messages while backgrounded
|
|
76
|
+
// (we never see those); so anything reaching us with text is ours to draw.
|
|
77
|
+
if (title != null || body != null) {
|
|
78
|
+
val hasNotificationPayload = msg.notificationTitle != null || msg.notificationBody != null
|
|
79
|
+
if (isForeground() || !hasNotificationPayload) {
|
|
80
|
+
runCatching { renderer(ctx, open.copy(title = title, body = body, imageUrl = open.imageUrl ?: msg.notificationImage), msg) }
|
|
81
|
+
.onFailure { Log.w(TAG, "render failed: ${it.message}") }
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return handled
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
internal object NotificationRenderer {
|
|
89
|
+
private const val TAG = "SwissKnife.Push"
|
|
90
|
+
private const val IMAGE_TIMEOUT_MS = 5_000
|
|
91
|
+
private const val IMAGE_MAX_BYTES = 5 * 1024 * 1024
|
|
92
|
+
|
|
93
|
+
const val META_CHANNEL_ID = "com.appswissknife.notifications.default_channel_id"
|
|
94
|
+
const val META_CHANNEL_NAME = "com.appswissknife.notifications.default_channel_name"
|
|
95
|
+
private const val DEFAULT_CHANNEL_NAME = "Notifications"
|
|
96
|
+
|
|
97
|
+
private fun meta(context: Context, key: String): String? = runCatching {
|
|
98
|
+
@Suppress("DEPRECATION")
|
|
99
|
+
val info = context.packageManager.getApplicationInfo(context.packageName, PackageManager.GET_META_DATA)
|
|
100
|
+
info.metaData?.get(key)?.toString()?.takeIf { it.isNotBlank() }
|
|
101
|
+
}.getOrNull()
|
|
102
|
+
|
|
103
|
+
/** Manifest meta-data `default_channel_id`, else [SwissKnifeNotifications.DEFAULT_CHANNEL_ID]. */
|
|
104
|
+
fun channelId(context: Context): String =
|
|
105
|
+
meta(context, META_CHANNEL_ID) ?: SwissKnifeNotifications.DEFAULT_CHANNEL_ID
|
|
106
|
+
|
|
107
|
+
/** Manifest meta-data `default_channel_name`, else "Notifications". */
|
|
108
|
+
fun channelName(context: Context): String =
|
|
109
|
+
meta(context, META_CHANNEL_NAME) ?: DEFAULT_CHANNEL_NAME
|
|
110
|
+
|
|
111
|
+
fun ensureDefaultChannel(context: Context) {
|
|
112
|
+
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
|
113
|
+
val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager ?: return
|
|
114
|
+
val id = channelId(context)
|
|
115
|
+
if (nm.getNotificationChannel(id) != null) return
|
|
116
|
+
nm.createNotificationChannel(
|
|
117
|
+
NotificationChannel(id, channelName(context), NotificationManager.IMPORTANCE_DEFAULT)
|
|
118
|
+
)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Launcher intent carrying every message data entry as a string extra. */
|
|
122
|
+
fun buildLaunchIntent(context: Context, data: Map<String, String>): Intent? {
|
|
123
|
+
val intent = context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return null
|
|
124
|
+
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
|
|
125
|
+
for ((k, v) in data) intent.putExtra(k, v)
|
|
126
|
+
return intent
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
fun render(context: Context, open: NotificationOpen, msg: IncomingPush) {
|
|
130
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
|
131
|
+
context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
|
|
132
|
+
) return
|
|
133
|
+
ensureDefaultChannel(context)
|
|
134
|
+
val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager ?: return
|
|
135
|
+
|
|
136
|
+
val launch = buildLaunchIntent(context, msg.data) ?: return
|
|
137
|
+
val notifId = (open.deliveryId ?: open.messageId ?: System.nanoTime().toString()).hashCode()
|
|
138
|
+
val pi = PendingIntent.getActivity(
|
|
139
|
+
context, notifId, launch,
|
|
140
|
+
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
@Suppress("DEPRECATION")
|
|
144
|
+
val b = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
145
|
+
Notification.Builder(context, channelId(context))
|
|
146
|
+
} else {
|
|
147
|
+
Notification.Builder(context)
|
|
148
|
+
}
|
|
149
|
+
val label = context.applicationInfo.loadLabel(context.packageManager).toString()
|
|
150
|
+
b.setSmallIcon(context.applicationInfo.icon)
|
|
151
|
+
.setContentTitle(open.title ?: label)
|
|
152
|
+
.setContentText(open.body)
|
|
153
|
+
.setStyle(Notification.BigTextStyle().bigText(open.body))
|
|
154
|
+
.setContentIntent(pi)
|
|
155
|
+
.setAutoCancel(true)
|
|
156
|
+
|
|
157
|
+
open.imageUrl?.let { url ->
|
|
158
|
+
downloadBitmap(url)?.let { bmp ->
|
|
159
|
+
b.setLargeIcon(bmp)
|
|
160
|
+
b.setStyle(Notification.BigPictureStyle().bigPicture(bmp).setSummaryText(open.body))
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
nm.notify(notifId, b.build())
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** http(s) only, bounded time and size; null on any failure (the text still renders). */
|
|
167
|
+
fun downloadBitmap(url: String): Bitmap? {
|
|
168
|
+
if (!(url.startsWith("https://") || url.startsWith("http://"))) return null
|
|
169
|
+
var conn: HttpURLConnection? = null
|
|
170
|
+
return try {
|
|
171
|
+
conn = (URL(url).openConnection() as HttpURLConnection).apply {
|
|
172
|
+
connectTimeout = IMAGE_TIMEOUT_MS
|
|
173
|
+
readTimeout = IMAGE_TIMEOUT_MS
|
|
174
|
+
}
|
|
175
|
+
if (conn.responseCode !in 200..299) return null
|
|
176
|
+
val out = ByteArrayOutputStream()
|
|
177
|
+
val buf = ByteArray(8192)
|
|
178
|
+
conn.inputStream.use { input ->
|
|
179
|
+
while (true) {
|
|
180
|
+
val n = input.read(buf)
|
|
181
|
+
if (n < 0) break
|
|
182
|
+
out.write(buf, 0, n)
|
|
183
|
+
if (out.size() > IMAGE_MAX_BYTES) return null
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
val bytes = out.toByteArray()
|
|
187
|
+
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
|
188
|
+
} catch (t: Throwable) {
|
|
189
|
+
Log.w(TAG, "image download failed: ${t.message}")
|
|
190
|
+
null
|
|
191
|
+
} finally {
|
|
192
|
+
conn?.disconnect()
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
package com.appswissknife.notifications
|
|
2
|
+
|
|
3
|
+
import android.Manifest
|
|
4
|
+
import android.app.Activity
|
|
5
|
+
import android.content.Intent
|
|
6
|
+
import android.content.pm.PackageManager
|
|
7
|
+
import android.os.Build
|
|
8
|
+
import android.os.Bundle
|
|
9
|
+
import android.os.Handler
|
|
10
|
+
import android.os.Looper
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Transparent trampoline that owns the POST_NOTIFICATIONS request so the host
|
|
14
|
+
* activity does not have to forward `onRequestPermissionsResult`.
|
|
15
|
+
*/
|
|
16
|
+
class PermissionRequestActivity : Activity() {
|
|
17
|
+
|
|
18
|
+
override fun onCreate(savedInstanceState: Bundle?) {
|
|
19
|
+
super.onCreate(savedInstanceState)
|
|
20
|
+
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
|
|
21
|
+
finishWith(true)
|
|
22
|
+
return
|
|
23
|
+
}
|
|
24
|
+
if (savedInstanceState == null) {
|
|
25
|
+
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQUEST_CODE)
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
|
|
30
|
+
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
|
31
|
+
finishWith(grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
private fun finishWith(granted: Boolean) {
|
|
35
|
+
finish()
|
|
36
|
+
@Suppress("DEPRECATION")
|
|
37
|
+
overridePendingTransition(0, 0)
|
|
38
|
+
deliver(granted)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
companion object {
|
|
42
|
+
private const val REQUEST_CODE = 0x5B5B
|
|
43
|
+
|
|
44
|
+
// Every caller that asked while a dialog was in flight gets the result.
|
|
45
|
+
private val pending = ArrayList<(Boolean) -> Unit>()
|
|
46
|
+
|
|
47
|
+
internal fun request(from: Activity, callback: (Boolean) -> Unit) {
|
|
48
|
+
val startDialog = synchronized(pending) { pending.add(callback); pending.size == 1 }
|
|
49
|
+
if (!startDialog) return
|
|
50
|
+
from.startActivity(Intent(from, PermissionRequestActivity::class.java))
|
|
51
|
+
@Suppress("DEPRECATION")
|
|
52
|
+
from.overridePendingTransition(0, 0)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
internal fun deliver(granted: Boolean) {
|
|
56
|
+
val cbs = synchronized(pending) { pending.toList().also { pending.clear() } }
|
|
57
|
+
Handler(Looper.getMainLooper()).post { cbs.forEach { runCatching { it(granted) } } }
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
package com.appswissknife.notifications
|
|
2
|
+
|
|
3
|
+
import android.os.Build
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Push permission state as sent to the server (`permission_status`).
|
|
7
|
+
* Android only ever reports the three values below; `provisional` and
|
|
8
|
+
* `ephemeral` are iOS concepts.
|
|
9
|
+
*/
|
|
10
|
+
enum class PermissionStatus(val wire: String) {
|
|
11
|
+
AUTHORIZED("authorized"),
|
|
12
|
+
DENIED("denied"),
|
|
13
|
+
NOT_DETERMINED("not_determined");
|
|
14
|
+
|
|
15
|
+
companion object {
|
|
16
|
+
/**
|
|
17
|
+
* Pure mapping, kept free of Android calls so it is unit-testable.
|
|
18
|
+
*
|
|
19
|
+
* - API < 33: there is no runtime permission; the only signal is the
|
|
20
|
+
* user's system-level "notifications enabled" switch.
|
|
21
|
+
* - API >= 33: POST_NOTIFICATIONS granted AND notifications not blocked
|
|
22
|
+
* in settings -> authorized. Not granted -> denied only if we have
|
|
23
|
+
* already asked (the dialog was shown and dismissed/denied), else
|
|
24
|
+
* not_determined.
|
|
25
|
+
*/
|
|
26
|
+
@JvmStatic
|
|
27
|
+
fun resolve(
|
|
28
|
+
sdkInt: Int,
|
|
29
|
+
runtimePermissionGranted: Boolean,
|
|
30
|
+
notificationsEnabled: Boolean,
|
|
31
|
+
askedBefore: Boolean,
|
|
32
|
+
): PermissionStatus = when {
|
|
33
|
+
sdkInt < Build.VERSION_CODES.TIRAMISU ->
|
|
34
|
+
if (notificationsEnabled) AUTHORIZED else DENIED
|
|
35
|
+
runtimePermissionGranted ->
|
|
36
|
+
if (notificationsEnabled) AUTHORIZED else DENIED
|
|
37
|
+
askedBefore -> DENIED
|
|
38
|
+
else -> NOT_DETERMINED
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|