react-native-live-widgets 1.2.1 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +89 -49
  3. package/android/src/main/AndroidManifest.xml +12 -0
  4. package/android/src/main/assets/fonts/MaterialIcons-Regular.ttf +0 -0
  5. package/android/src/main/java/com/reactnativeliveactivity/bridge/LiveActivityModule.kt +61 -1
  6. package/android/src/main/java/com/reactnativeliveactivity/liveactivity/LiveActivityNotifier.kt +153 -17
  7. package/android/src/main/java/com/reactnativeliveactivity/liveactivity/LiveActivityReceiver.kt +1 -1
  8. package/android/src/main/java/com/reactnativeliveactivity/renderer/DynamicWidgetCanvasRenderer.kt +86 -13
  9. package/android/src/main/java/com/reactnativeliveactivity/storage/DynamicWidgetImageCache.kt +53 -0
  10. package/android/src/main/java/com/reactnativeliveactivity/storage/DynamicWidgetStateStore.kt +647 -104
  11. package/android/src/main/java/com/reactnativeliveactivity/widgets/DynamicHomeScreenWidgetProvider.kt +3 -1
  12. package/android/src/main/java/com/reactnativeliveactivity/widgets/DynamicQuickSettingsTileService.kt +120 -0
  13. package/app.plugin.js +36 -0
  14. package/assets/MaterialIcons.json +2236 -0
  15. package/cli/codegen.js +789 -0
  16. package/cli/setup.js +323 -63
  17. package/docs/EXPO-GUIDE-EN.md +21 -3
  18. package/docs/EXPO-GUIDE-VI.md +21 -3
  19. package/docs/GUIDE-EN.md +203 -21
  20. package/docs/GUIDE-VI.md +207 -22
  21. package/docs/index.html +1328 -211
  22. package/docs/llms-full.txt +15 -0
  23. package/docs/llms.txt +16 -7
  24. package/ios/Bridge/LiveActivityModule.swift +333 -44
  25. package/ios/Intents/DynamicWidgetActionIntent.swift +57 -2
  26. package/ios/Models/DynamicLayoutModels.swift +114 -4
  27. package/ios/Renderer/DynamicNodeView.swift +15 -6
  28. package/ios/Storage/DynamicWidgetStateStore.swift +649 -38
  29. package/ios/Widgets/DynamicControlWidget.swift +63 -0
  30. package/ios/Widgets/DynamicHomeScreenWidget.swift +99 -26
  31. package/ios/Widgets/DynamicLiveActivityWidget.swift +25 -4
  32. package/lib/builder.d.ts +50 -7
  33. package/lib/builder.d.ts.map +1 -1
  34. package/lib/builder.js +326 -18
  35. package/lib/builder.js.map +1 -1
  36. package/lib/hooks.d.ts +13 -9
  37. package/lib/hooks.d.ts.map +1 -1
  38. package/lib/hooks.js +70 -12
  39. package/lib/hooks.js.map +1 -1
  40. package/lib/index.d.ts +80 -7
  41. package/lib/index.d.ts.map +1 -1
  42. package/lib/index.js +303 -59
  43. package/lib/index.js.map +1 -1
  44. package/lib/ir.d.ts.map +1 -1
  45. package/lib/ir.js +9 -2
  46. package/lib/ir.js.map +1 -1
  47. package/lib/jsx.d.ts +11 -7
  48. package/lib/jsx.d.ts.map +1 -1
  49. package/lib/jsx.js +50 -13
  50. package/lib/jsx.js.map +1 -1
  51. package/lib/material-icons.generated.d.ts +8 -0
  52. package/lib/material-icons.generated.d.ts.map +1 -0
  53. package/lib/material-icons.generated.js +9 -0
  54. package/lib/material-icons.generated.js.map +1 -0
  55. package/lib/preview.d.ts +11 -4
  56. package/lib/preview.d.ts.map +1 -1
  57. package/lib/preview.js +150 -82
  58. package/lib/preview.js.map +1 -1
  59. package/lib/sf-symbols.generated.d.ts +8 -0
  60. package/lib/sf-symbols.generated.d.ts.map +1 -0
  61. package/lib/sf-symbols.generated.js +9 -0
  62. package/lib/sf-symbols.generated.js.map +1 -0
  63. package/lib/types.d.ts +302 -18
  64. package/lib/types.d.ts.map +1 -1
  65. package/package.json +6 -2
  66. package/scripts/build.js +98 -0
  67. package/scripts/generate-material-icons.js +93 -0
  68. package/scripts/generate-sf-symbols.js +95 -0
  69. package/scripts/release.js +115 -0
  70. package/scripts/test-ir-semantic.js +314 -0
  71. package/src/builder.ts +382 -24
  72. package/src/hooks.ts +88 -12
  73. package/src/index.ts +319 -56
  74. package/src/ir.ts +8 -2
  75. package/src/jsx.tsx +69 -21
  76. package/src/material-icons.generated.ts +3844 -0
  77. package/src/preview.tsx +235 -81
  78. package/src/sf-symbols.generated.ts +9533 -0
  79. package/src/types.ts +348 -18
@@ -9,9 +9,13 @@ import org.json.JSONArray
9
9
  import org.json.JSONObject
10
10
  import java.net.HttpURLConnection
11
11
  import java.net.URL
12
+ import java.text.DecimalFormat
13
+ import java.text.DecimalFormatSymbols
12
14
  import java.text.SimpleDateFormat
13
15
  import java.util.Date
14
16
  import java.util.Locale
17
+ import kotlin.math.pow
18
+ import kotlin.math.roundToLong
15
19
  import kotlin.random.Random
16
20
 
17
21
  data class InteractiveWidgetState(
@@ -21,7 +25,13 @@ data class InteractiveWidgetState(
21
25
  var lastActionId: String? = null,
22
26
  var lastSyncTime: String? = null,
23
27
  var remoteVariables: MutableMap<String, String> = mutableMapOf(),
24
- var updatedAt: Long = System.currentTimeMillis()
28
+ var updatedAt: Long = System.currentTimeMillis(),
29
+ var etags: MutableMap<String, String> = mutableMapOf(),
30
+ var lastModified: MutableMap<String, String> = mutableMapOf(),
31
+ var syncStatus: String? = null,
32
+ var lastSyncError: String? = null,
33
+ var lastHttpStatus: Int? = null,
34
+ var accessToken: String? = null
25
35
  )
26
36
 
27
37
  object DynamicWidgetStateStore {
@@ -39,6 +49,26 @@ object DynamicWidgetStateStore {
39
49
  getPrefs(context).edit().putString(key, value).apply()
40
50
  }
41
51
 
52
+ private fun readStringMap(obj: JSONObject, key: String): MutableMap<String, String> {
53
+ val map = mutableMapOf<String, String>()
54
+ obj.optJSONObject(key)?.let { sub ->
55
+ val keys = sub.keys()
56
+ while (keys.hasNext()) {
57
+ val k = keys.next()
58
+ map[k] = sub.optString(k, "")
59
+ }
60
+ }
61
+ return map
62
+ }
63
+
64
+ private fun writeStringMap(obj: JSONObject, key: String, map: Map<String, String>) {
65
+ val sub = JSONObject()
66
+ for ((k, v) in map) {
67
+ sub.put(k, v)
68
+ }
69
+ obj.put(key, sub)
70
+ }
71
+
42
72
  fun loadState(context: Context): InteractiveWidgetState {
43
73
  val raw = readSharedString(context, STATE_KEY) ?: return InteractiveWidgetState()
44
74
  return try {
@@ -57,22 +87,24 @@ object DynamicWidgetStateStore {
57
87
  toggled[k] = tObj.optBoolean(k, false)
58
88
  }
59
89
  }
60
- val vars = mutableMapOf<String, String>()
61
- obj.optJSONObject("remoteVariables")?.let { vObj ->
62
- val keys = vObj.keys()
63
- while (keys.hasNext()) {
64
- val k = keys.next()
65
- vars[k] = vObj.optString(k, "")
66
- }
67
- }
90
+ val httpStatus = if (obj.has("lastHttpStatus") && !obj.isNull("lastHttpStatus")) {
91
+ obj.optInt("lastHttpStatus")
92
+ } else null
93
+
68
94
  InteractiveWidgetState(
69
95
  activePage = obj.optString("activePage", "").ifEmpty { null },
70
96
  pageOrder = orderList,
71
97
  toggledItems = toggled,
72
98
  lastActionId = obj.optString("lastActionId", "").ifEmpty { null },
73
99
  lastSyncTime = obj.optString("lastSyncTime", "").ifEmpty { null },
74
- remoteVariables = vars,
75
- updatedAt = obj.optLong("updatedAt", System.currentTimeMillis())
100
+ remoteVariables = readStringMap(obj, "remoteVariables"),
101
+ updatedAt = obj.optLong("updatedAt", System.currentTimeMillis()),
102
+ etags = readStringMap(obj, "etags"),
103
+ lastModified = readStringMap(obj, "lastModified"),
104
+ syncStatus = obj.optString("syncStatus", "").ifEmpty { null },
105
+ lastSyncError = obj.optString("lastSyncError", "").ifEmpty { null },
106
+ lastHttpStatus = httpStatus,
107
+ accessToken = obj.optString("accessToken", "").ifEmpty { null }
76
108
  )
77
109
  } catch (_: Exception) {
78
110
  InteractiveWidgetState()
@@ -93,13 +125,14 @@ object DynamicWidgetStateStore {
93
125
 
94
126
  state.lastActionId?.let { obj.put("lastActionId", it) }
95
127
  state.lastSyncTime?.let { obj.put("lastSyncTime", it) }
96
-
97
- val vObj = JSONObject()
98
- for ((k, v) in state.remoteVariables) {
99
- vObj.put(k, v)
100
- }
101
- obj.put("remoteVariables", vObj)
128
+ writeStringMap(obj, "remoteVariables", state.remoteVariables)
102
129
  obj.put("updatedAt", state.updatedAt)
130
+ writeStringMap(obj, "etags", state.etags)
131
+ writeStringMap(obj, "lastModified", state.lastModified)
132
+ state.syncStatus?.let { obj.put("syncStatus", it) }
133
+ state.lastSyncError?.let { obj.put("lastSyncError", it) }
134
+ state.lastHttpStatus?.let { obj.put("lastHttpStatus", it) }
135
+ state.accessToken?.let { obj.put("accessToken", it) }
103
136
 
104
137
  writeSharedString(context, STATE_KEY, obj.toString())
105
138
  } catch (_: Exception) {
@@ -213,122 +246,640 @@ object DynamicWidgetStateStore {
213
246
  return defaultChecked
214
247
  }
215
248
 
249
+ // ─── JSON FLATTENER, SCHEMA VALIDATOR & PIPE EVALUATOR ───────────────────
250
+
251
+ fun flattenJson(value: Any?, prefix: String = "", out: MutableMap<String, String>) {
252
+ if (value == null || value === JSONObject.NULL) return
253
+ when (value) {
254
+ is JSONObject -> {
255
+ val keys = value.keys()
256
+ while (keys.hasNext()) {
257
+ val k = keys.next()
258
+ val nextKey = if (prefix.isEmpty()) k else "$prefix.$k"
259
+ flattenJson(value.opt(k), nextKey, out)
260
+ }
261
+ }
262
+ is JSONArray -> {
263
+ for (i in 0 until value.length()) {
264
+ val nextKey = if (prefix.isEmpty()) "$i" else "$prefix.$i"
265
+ flattenJson(value.opt(i), nextKey, out)
266
+ }
267
+ }
268
+ else -> {
269
+ if (prefix.isNotEmpty()) {
270
+ out[prefix] = value.toString()
271
+ }
272
+ }
273
+ }
274
+ }
275
+
276
+ private fun validateAndApplySchema(
277
+ flatVars: MutableMap<String, String>,
278
+ schemaObj: JSONObject?
279
+ ): Pair<Boolean, String?> {
280
+ if (schemaObj == null) return Pair(true, null)
281
+
282
+ schemaObj.optJSONObject("defaults")?.let { defs ->
283
+ val keys = defs.keys()
284
+ while (keys.hasNext()) {
285
+ val k = keys.next()
286
+ val existing = flatVars[k]
287
+ if (existing.isNullOrEmpty() && !defs.isNull(k)) {
288
+ flatVars[k] = defs.opt(k)?.toString() ?: ""
289
+ }
290
+ }
291
+ }
292
+
293
+ schemaObj.optJSONArray("requiredKeys")?.let { reqArr ->
294
+ for (i in 0 until reqArr.length()) {
295
+ val reqKey = reqArr.optString(i, "")
296
+ if (reqKey.isNotEmpty() && flatVars[reqKey].isNullOrEmpty()) {
297
+ return Pair(false, "Missing required key '$reqKey'")
298
+ }
299
+ }
300
+ }
301
+
302
+ schemaObj.optJSONObject("types")?.let { typesObj ->
303
+ val keys = typesObj.keys()
304
+ while (keys.hasNext()) {
305
+ val k = keys.next()
306
+ val valStr = flatVars[k] ?: continue
307
+ when (typesObj.optString(k)) {
308
+ "number" -> {
309
+ if (valStr.trim().toDoubleOrNull() == null) {
310
+ return Pair(false, "Key '$k' expected number")
311
+ }
312
+ }
313
+ "boolean" -> {
314
+ val lower = valStr.trim().lowercase(Locale.ROOT)
315
+ if (lower != "true" && lower != "false" && lower != "1" && lower != "0") {
316
+ return Pair(false, "Key '$k' expected boolean")
317
+ }
318
+ }
319
+ }
320
+ }
321
+ }
322
+
323
+ return Pair(true, null)
324
+ }
325
+
326
+ private fun formatNumber(value: Double): String {
327
+ return if (value.isFinite() && Math.rint(value) == value && kotlin.math.abs(value) <= Long.MAX_VALUE) {
328
+ value.toLong().toString()
329
+ } else {
330
+ value.toString()
331
+ }
332
+ }
333
+
334
+ private fun sanitizeVariableValue(raw: String?): String? {
335
+ if (raw == null) return null
336
+ val trimmed = raw.trim()
337
+ if (trimmed.startsWith("{{") && trimmed.endsWith("}}")) {
338
+ val inner = trimmed.substring(2, trimmed.length - 2)
339
+ if (!inner.contains('{') && !inner.contains('}') && !inner.contains('|')) {
340
+ return inner.trim()
341
+ }
342
+ }
343
+ return raw
344
+ }
345
+
346
+ fun evaluateTemplatePipe(rawValue: String?, pipes: List<String>): String {
347
+ var current = sanitizeVariableValue(rawValue) ?: ""
348
+
349
+ for (rawPipe in pipes) {
350
+ val colonIdx = rawPipe.indexOf(':')
351
+ val op = if (colonIdx >= 0) rawPipe.substring(0, colonIdx).trim() else rawPipe.trim()
352
+ val arg = if (colonIdx >= 0) rawPipe.substring(colonIdx + 1) else ""
353
+
354
+ when (op) {
355
+ "default" -> {
356
+ if (current.isEmpty()) current = arg
357
+ }
358
+ "divide" -> {
359
+ val num = current.toDoubleOrNull()
360
+ val div = arg.toDoubleOrNull()
361
+ if (num != null && div != null && div != 0.0) {
362
+ current = formatNumber(num / div)
363
+ }
364
+ }
365
+ "multiply" -> {
366
+ val num = current.toDoubleOrNull()
367
+ val mul = arg.toDoubleOrNull()
368
+ if (num != null && mul != null) {
369
+ current = formatNumber(num * mul)
370
+ }
371
+ }
372
+ "add" -> {
373
+ val num = current.toDoubleOrNull()
374
+ val off = arg.toDoubleOrNull()
375
+ if (num != null && off != null) {
376
+ current = formatNumber(num + off)
377
+ }
378
+ }
379
+ "round" -> {
380
+ val num = current.toDoubleOrNull()
381
+ if (num != null) {
382
+ val decimals = (arg.toIntOrNull() ?: 0).coerceAtLeast(0)
383
+ current = if (decimals == 0) {
384
+ num.roundToLong().toString()
385
+ } else {
386
+ String.format(Locale.US, "%.${decimals}f", num)
387
+ }
388
+ }
389
+ }
390
+ "upper" -> current = current.uppercase(Locale.getDefault())
391
+ "lower" -> current = current.lowercase(Locale.getDefault())
392
+ "currency" -> {
393
+ val num = current.toDoubleOrNull()
394
+ if (num != null) {
395
+ val sym = arg.ifEmpty { "₫" }
396
+ val fmt = DecimalFormat("#,###", DecimalFormatSymbols(Locale.US))
397
+ current = "${fmt.format(num.roundToLong())}$sym"
398
+ }
399
+ }
400
+ "percent" -> {
401
+ val num = current.toDoubleOrNull()
402
+ if (num != null) {
403
+ val decimals = (arg.toIntOrNull() ?: 0).coerceAtLeast(0)
404
+ val numStr = if (decimals == 0) {
405
+ num.roundToLong().toString()
406
+ } else {
407
+ String.format(Locale.US, "%.${decimals}f", num)
408
+ }
409
+ current = "$numStr%"
410
+ }
411
+ }
412
+ "if" -> {
413
+ val splitIdx = arg.indexOf(':')
414
+ val thenVal = if (splitIdx >= 0) arg.substring(0, splitIdx) else arg
415
+ val elseVal = if (splitIdx >= 0) arg.substring(splitIdx + 1) else ""
416
+ val lower = current.trim().lowercase(Locale.ROOT)
417
+ val isTruthy = lower.isNotEmpty() && lower != "false" && lower != "0" && lower != "null"
418
+ current = if (isTruthy) thenVal else elseVal
419
+ }
420
+ }
421
+ }
422
+ return current
423
+ }
424
+
425
+ fun resolveTemplateString(
426
+ raw: String,
427
+ vars: Map<String, String>,
428
+ escapeForJson: Boolean = false
429
+ ): String {
430
+ if (!raw.contains("{{")) return raw
431
+ return Regex("\\{\\{([^}]+)\\}\\}").replace(raw) { match ->
432
+ val expr = match.groupValues[1]
433
+ val parts = expr.split("|")
434
+ val pathKey = parts[0].trim()
435
+ val pipes = parts.drop(1)
436
+ val hasKey = vars.containsKey(pathKey)
437
+ val hasFallback = pipes.any { p ->
438
+ val t = p.trim()
439
+ t.startsWith("default:") || t.startsWith("if:")
440
+ }
441
+ if (!hasKey && !hasFallback) {
442
+ match.value
443
+ } else {
444
+ var evaluated = evaluateTemplatePipe(vars[pathKey], pipes)
445
+ if (escapeForJson) {
446
+ evaluated = evaluated
447
+ .replace("\\", "\\\\")
448
+ .replace("\"", "\\\"")
449
+ .replace("\n", "\\n")
450
+ .replace("\r", "\\r")
451
+ .replace("\t", "\\t")
452
+ }
453
+ evaluated
454
+ }
455
+ }
456
+ }
457
+
216
458
  fun resolveLayoutJsonWithVariables(context: Context, widgetKey: String): String? {
217
- var raw = readSharedString(context, "widget_layout_$widgetKey") ?: return null
218
459
  val state = loadState(context)
219
460
  val syncTime = state.lastSyncTime
220
461
  ?: SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date())
221
- raw = raw.replace("{{_lastSyncTime}}", syncTime)
222
462
 
463
+ val vars = mutableMapOf<String, String>()
464
+ val boundJson = readSharedString(context, "widget_bound_data_$widgetKey")
465
+ ?: if (widgetKey != "main") readSharedString(context, "widget_bound_data_main") else null
466
+ if (!boundJson.isNullOrEmpty()) {
467
+ runCatching {
468
+ flattenJson(JSONObject(boundJson), "", vars)
469
+ }
470
+ }
471
+ vars.putAll(state.remoteVariables)
472
+ vars["_lastSyncTime"] = syncTime
473
+ vars["_syncStatus"] = state.syncStatus ?: vars["_syncStatus"] ?: "ok"
474
+ vars["_syncError"] = state.lastSyncError ?: vars["_syncError"] ?: ""
475
+ state.lastHttpStatus?.let { vars["_httpStatus"] = it.toString() }
476
+
477
+ readSharedString(context, "widget_selected_config_$widgetKey")?.let { sel ->
478
+ vars["_selectedConfigId"] = sel
479
+ vars["selectedConfigId"] = sel
480
+ }
481
+
482
+ if (!vars.containsKey("id")) vars["id"] = "2026"
483
+ if (!vars.containsKey("title")) vars["title"] = "Hoàn thành kế hoạch quý 4"
484
+
485
+ var raw: String? = null
486
+ if (state.syncStatus == "error") {
487
+ readSharedString(context, "widget_remote_config_$widgetKey")?.let { cfgJson ->
488
+ runCatching {
489
+ val cfg = JSONObject(cfgJson)
490
+ val errNode = cfg.optJSONObject("errorFallback")
491
+ if (errNode != null) {
492
+ raw = JSONObject().apply {
493
+ put("version", "2.0")
494
+ put("root", errNode)
495
+ }.toString()
496
+ }
497
+ }
498
+ }
499
+ }
500
+
501
+ if (raw == null) {
502
+ raw = readSharedString(context, "widget_layout_$widgetKey") ?: return null
503
+ }
504
+
505
+ var working = raw!!
223
506
  val counterVal = readSharedString(context, "widget_counter_value")
224
507
  if (counterVal != null) {
225
- raw = Regex("\"text\":\"-?\\d+\",(\"props\":\\{)?\"fontSize\":(26|32)").replace(raw) { m ->
226
- "\"text\":\"$counterVal\",${m.groupValues[1]}\"fontSize\":${m.groupValues[2]}"
508
+ working = Regex("(\"text\"\\s*:\\s*)\"-?\\d+\"(\\s*,\\s*(?:\"style\"\\s*:\\s*\\{\\s*)?\"fontSize\"\\s*:\\s*(?:26|32)\\b)").replace(working) { m ->
509
+ "${m.groupValues[1]}\"$counterVal\"${m.groupValues[2]}"
227
510
  }
228
- raw = raw.replace(Regex("\"text\":\"-?\\d+ lượt\""), "\"text\":\"$counterVal lượt\"")
229
- raw = raw.replace(Regex("Count: -?\\d+"), "Count: $counterVal")
230
- raw = raw.replace(Regex("Số đếm hiện tại: -?\\d+"), "Số đếm hiện tại: $counterVal")
231
- raw = raw.replace("{{counter}}", counterVal)
511
+ working = working.replace(Regex("-?\\d+(\\s+lượt)"), "$counterVal$1")
512
+ working = working.replace(Regex("Count:\\s*-?\\d+"), "Count: $counterVal")
513
+ working = working.replace(Regex("Số đếm hiện tại:\\s*-?\\d+"), "Số đếm hiện tại: $counterVal")
514
+ working = working.replace("{{counter}}", counterVal)
232
515
  }
233
516
 
234
- state.remoteVariables["demo_ts_label"]?.takeIf { it.isNotEmpty() }?.let { label ->
517
+ vars["demo_ts_label"]?.takeIf { it.isNotEmpty() }?.let { label ->
235
518
  val escaped = label.replace("\"", "\\\"")
236
- raw = raw.replace("\"title\":\"Chạy hàm TS\"", "\"title\":\"$escaped\"")
519
+ working = working.replace("\"title\":\"Chạy hàm TS\"", "\"title\":\"$escaped\"")
237
520
  }
238
521
 
239
- state.remoteVariables["jsx_status"]?.takeIf { it.isNotEmpty() }?.let { status ->
522
+ vars["jsx_status"]?.takeIf { it.isNotEmpty() }?.let { status ->
240
523
  val escaped = status.replace("\"", "\\\"")
241
- raw = raw.replace("\"text\":\"Đã chấm công (07:54)\"", "\"text\":\"$escaped\"")
242
- raw = raw.replace("\"text\":\"Vào ca sáng (07:54)\"", "\"text\":\"$escaped\"")
524
+ working = working.replace("\"text\":\"Đã chấm công (07:54)\"", "\"text\":\"$escaped\"")
525
+ working = working.replace("\"text\":\"Vào ca sáng (07:54)\"", "\"text\":\"$escaped\"")
243
526
  }
244
527
 
245
- // Fallback mặc định cho các template variables thông dụng nếu chưa fetch từ API
246
- if (!state.remoteVariables.containsKey("id")) {
247
- state.remoteVariables["id"] = "2026"
528
+ return resolveTemplateString(working, vars, escapeForJson = true)
529
+ }
530
+
531
+ // ─── BACKGROUND DATA ENGINE 2.0 (REST, TTL, ETag, Retry, Multi-Source, Auth) ─
532
+
533
+ private sealed class SourceFetchResult {
534
+ data class Updated(
535
+ val text: String,
536
+ val etag: String?,
537
+ val lastModified: String?,
538
+ val statusCode: Int
539
+ ) : SourceFetchResult()
540
+ data class NotModified(val statusCode: Int) : SourceFetchResult()
541
+ data class Failed(val error: String, val statusCode: Int?) : SourceFetchResult()
542
+ }
543
+
544
+ private fun extractBodyString(obj: JSONObject?): String? {
545
+ if (obj == null || !obj.has("body") || obj.isNull("body")) return null
546
+ val b = obj.opt("body") ?: return null
547
+ return when (b) {
548
+ is String -> b
549
+ else -> b.toString()
248
550
  }
249
- if (!state.remoteVariables.containsKey("title")) {
250
- state.remoteVariables["title"] = "Hoàn thành kế hoạch quý 4"
551
+ }
552
+
553
+ private fun performAuthRefresh(authObj: JSONObject, timeoutMs: Int): String? {
554
+ val authUrl = authObj.optString("url", "").ifEmpty { return null }
555
+ var conn: HttpURLConnection? = null
556
+ return try {
557
+ conn = (URL(authUrl).openConnection() as HttpURLConnection).apply {
558
+ requestMethod = authObj.optString("method", "POST")
559
+ connectTimeout = timeoutMs
560
+ readTimeout = timeoutMs
561
+ authObj.optJSONObject("headers")?.let { hdrs ->
562
+ val keys = hdrs.keys()
563
+ while (keys.hasNext()) {
564
+ val k = keys.next()
565
+ setRequestProperty(k, hdrs.optString(k))
566
+ }
567
+ }
568
+ val bodyStr = extractBodyString(authObj)
569
+ if (bodyStr != null) {
570
+ if (getRequestProperty("Content-Type") == null) {
571
+ setRequestProperty("Content-Type", "application/json")
572
+ }
573
+ doOutput = true
574
+ outputStream.use { it.write(bodyStr.toByteArray(Charsets.UTF_8)) }
575
+ }
576
+ }
577
+ val status = conn.responseCode
578
+ if (status !in 200..299) return null
579
+ val text = conn.inputStream.bufferedReader().use { it.readText() }
580
+ val jsonObj = JSONObject(text)
581
+ val flat = mutableMapOf<String, String>()
582
+ flattenJson(jsonObj, "", flat)
583
+ val tokenPath = authObj.optString("tokenPath", "accessToken")
584
+ flat[tokenPath] ?: flat["token"] ?: flat["access_token"]
585
+ } catch (_: Exception) {
586
+ null
587
+ } finally {
588
+ conn?.disconnect()
251
589
  }
590
+ }
591
+
592
+ private fun fetchWithRetryAndAuth(
593
+ cacheKey: String,
594
+ urlString: String,
595
+ method: String,
596
+ headers: JSONObject?,
597
+ bodyStr: String?,
598
+ timeoutMs: Int,
599
+ enableETag: Boolean,
600
+ maxRetries: Int,
601
+ retryDelayMs: Int,
602
+ authObj: JSONObject?,
603
+ state: InteractiveWidgetState
604
+ ): SourceFetchResult {
605
+ val randomId = Random.nextInt(1, 100)
606
+ val resolvedUrl = urlString.replace("{{_randomId}}", randomId.toString())
607
+ var didRefreshAuth = false
608
+ var lastError = "Network error"
609
+ var lastStatus: Int? = null
610
+
611
+ var attempt = 0
612
+ val totalAttempts = maxRetries.coerceAtLeast(0)
613
+ while (attempt <= totalAttempts) {
614
+ if (attempt > 0) {
615
+ val backoffMs = (retryDelayMs.coerceAtLeast(100) * 2.0.pow((attempt - 1).toDouble()))
616
+ .toLong().coerceAtMost(10_000L)
617
+ runCatching { Thread.sleep(backoffMs) }
618
+ }
252
619
 
253
- for ((k, v) in state.remoteVariables) {
254
- val escaped = v.replace("\"", "\\\"")
255
- raw = raw.replace("{{$k}}", escaped)
620
+ var conn: HttpURLConnection? = null
621
+ try {
622
+ conn = (URL(resolvedUrl).openConnection() as HttpURLConnection).apply {
623
+ requestMethod = method
624
+ connectTimeout = timeoutMs
625
+ readTimeout = timeoutMs
626
+ headers?.let { hdrs ->
627
+ val keys = hdrs.keys()
628
+ while (keys.hasNext()) {
629
+ val k = keys.next()
630
+ setRequestProperty(k, hdrs.optString(k))
631
+ }
632
+ }
633
+
634
+ state.accessToken?.takeIf { it.isNotEmpty() }?.let { tok ->
635
+ val hName = authObj?.optString("headerName", "Authorization")?.ifEmpty { null } ?: "Authorization"
636
+ val hPrefix = authObj?.optString("headerPrefix", "Bearer ") ?: "Bearer "
637
+ setRequestProperty(hName, "$hPrefix$tok")
638
+ }
639
+
640
+ if (enableETag) {
641
+ state.etags[cacheKey]?.takeIf { it.isNotEmpty() }?.let {
642
+ setRequestProperty("If-None-Match", it)
643
+ }
644
+ state.lastModified[cacheKey]?.takeIf { it.isNotEmpty() }?.let {
645
+ setRequestProperty("If-Modified-Since", it)
646
+ }
647
+ }
648
+
649
+ if (bodyStr != null && (method == "POST" || method == "PUT")) {
650
+ if (getRequestProperty("Content-Type") == null) {
651
+ setRequestProperty("Content-Type", "application/json")
652
+ }
653
+ doOutput = true
654
+ outputStream.use { it.write(bodyStr.toByteArray(Charsets.UTF_8)) }
655
+ }
656
+ }
657
+
658
+ val status = conn.responseCode
659
+ lastStatus = status
660
+
661
+ if (status == HttpURLConnection.HTTP_NOT_MODIFIED) {
662
+ return SourceFetchResult.NotModified(304)
663
+ }
664
+
665
+ if (status == HttpURLConnection.HTTP_UNAUTHORIZED && authObj != null && !didRefreshAuth) {
666
+ didRefreshAuth = true
667
+ conn.disconnect()
668
+ val newToken = performAuthRefresh(authObj, timeoutMs)
669
+ if (newToken != null) {
670
+ state.accessToken = newToken
671
+ // Gọi lại ngay với token mới mà không tăng attempt backoff
672
+ continue
673
+ }
674
+ return SourceFetchResult.Failed("HTTP 401 Unauthorized", 401)
675
+ }
676
+
677
+ if (status in 200..299) {
678
+ val responseText = conn.inputStream.bufferedReader().use { it.readText() }
679
+ val etag = conn.getHeaderField("ETag")
680
+ val lastMod = conn.getHeaderField("Last-Modified")
681
+ return SourceFetchResult.Updated(responseText, etag, lastMod, status)
682
+ }
683
+
684
+ lastError = "HTTP $status"
685
+ if (status < 500 && status != 429) {
686
+ return SourceFetchResult.Failed(lastError, status)
687
+ }
688
+ } catch (e: Exception) {
689
+ lastError = e.message ?: "Network error"
690
+ } finally {
691
+ conn?.disconnect()
692
+ }
693
+ attempt++
256
694
  }
257
- return raw
695
+
696
+ return SourceFetchResult.Failed(lastError, lastStatus)
258
697
  }
259
698
 
260
699
  /**
261
700
  * Đồng bộ API chạy ngầm trực tiếp từ BroadcastReceiver / AppWidgetProvider
262
701
  * kể cả khi ứng dụng React Native đã bị Kill hoàn toàn!
263
702
  */
264
- fun performRemoteSync(context: Context, widgetKey: String = "main") {
703
+ fun performRemoteSync(context: Context, widgetKey: String = "main", forceRefresh: Boolean = false) {
265
704
  val configJson = readSharedString(context, "widget_remote_config_$widgetKey")
266
- val rawUrl = if (!configJson.isNullOrEmpty()) {
267
- try {
268
- JSONObject(configJson).optString("url", "")
269
- } catch (_: Exception) { "" }
270
- } else {
271
- // Demo API endpoint tự động nạp id và title khi bấm nút Làm mới dữ liệu ngầm
272
- "https://jsonplaceholder.typicode.com/todos/{{_randomId}}"
273
- }.ifEmpty { "https://jsonplaceholder.typicode.com/todos/{{_randomId}}" }
705
+ val cfg = if (!configJson.isNullOrEmpty()) runCatching { JSONObject(configJson) }.getOrNull() else null
706
+ val state = loadState(context)
274
707
 
275
- try {
276
- val randomId = Random.nextInt(1, 100)
277
- val resolvedUrl = rawUrl.replace("{{_randomId}}", randomId.toString())
278
- val conn = (URL(resolvedUrl).openConnection() as HttpURLConnection).apply {
279
- requestMethod = "GET"
280
- connectTimeout = 8000
281
- readTimeout = 8000
282
- if (!configJson.isNullOrEmpty()) {
283
- try {
284
- val cfg = JSONObject(configJson)
285
- requestMethod = cfg.optString("method", "GET")
286
- cfg.optJSONObject("headers")?.let { headers ->
287
- val keys = headers.keys()
288
- while (keys.hasNext()) {
289
- val k = keys.next()
290
- setRequestProperty(k, headers.optString(k))
291
- }
292
- }
293
- } catch (_: Exception) {}
294
- }
708
+ val ttlSeconds = cfg?.optInt("cacheTtlSeconds", 0) ?: 0
709
+ if (!forceRefresh && ttlSeconds > 0 && state.lastSyncTime != null && state.syncStatus != "error") {
710
+ val ageMs = System.currentTimeMillis() - state.updatedAt
711
+ if (ageMs < ttlSeconds * 1000L) {
712
+ return
295
713
  }
714
+ }
296
715
 
297
- val responseText = conn.inputStream.bufferedReader().use { it.readText() }
298
- conn.disconnect()
299
-
300
- val state = loadState(context)
301
- state.lastSyncTime = SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date())
302
- state.updatedAt = System.currentTimeMillis()
303
-
304
- val jsonObj = JSONObject(responseText)
305
- if (jsonObj.has("small") || jsonObj.has("medium") || jsonObj.has("large") || jsonObj.has("pages")) {
306
- writeSharedString(context, "widget_layout_$widgetKey", responseText)
307
- DynamicWidgetImageCache.prefetchUrlsSync(context, responseText)
716
+ val timeoutMs = (cfg?.optInt("timeoutMs", 8000) ?: 8000).coerceAtLeast(1000)
717
+ val enableETag = cfg?.optBoolean("enableETag", false) ?: false
718
+ val maxRetries = cfg?.optInt("maxRetries", 0) ?: 0
719
+ val retryDelayMs = cfg?.optInt("retryDelayMs", 500) ?: 500
720
+ val defaultMethod = cfg?.optString("method", "GET")?.ifEmpty { null } ?: "GET"
721
+ val defaultHeaders = cfg?.optJSONObject("headers")
722
+ val authObj = cfg?.optJSONObject("authRefresh")
723
+ val primaryUrl = cfg?.optString("url", "")?.ifEmpty { null }
724
+ ?: if (cfg?.optJSONObject("sources") == null) "https://jsonplaceholder.typicode.com/todos/{{_randomId}}" else null
725
+
726
+ val mergedVars = state.remoteVariables.toMutableMap()
727
+ var anyError: String? = null
728
+ var finalStatus: Int? = null
729
+ var fetchedAnyData = false
730
+ var allNotModified = true
731
+
732
+ if (primaryUrl != null) {
733
+ when (val res = fetchWithRetryAndAuth(
734
+ cacheKey = "$widgetKey:main",
735
+ urlString = primaryUrl,
736
+ method = defaultMethod,
737
+ headers = defaultHeaders,
738
+ bodyStr = extractBodyString(cfg),
739
+ timeoutMs = timeoutMs,
740
+ enableETag = enableETag,
741
+ maxRetries = maxRetries,
742
+ retryDelayMs = retryDelayMs,
743
+ authObj = authObj,
744
+ state = state
745
+ )) {
746
+ is SourceFetchResult.Updated -> {
747
+ fetchedAnyData = true
748
+ allNotModified = false
749
+ finalStatus = res.statusCode
750
+ res.etag?.let { state.etags["$widgetKey:main"] = it }
751
+ res.lastModified?.let { state.lastModified["$widgetKey:main"] = it }
752
+ runCatching {
753
+ val jsonObj = JSONObject(res.text)
754
+ if (jsonObj.has("small") || jsonObj.has("medium") || jsonObj.has("large") || jsonObj.has("pages")) {
755
+ writeSharedString(context, "widget_layout_$widgetKey", res.text)
756
+ DynamicWidgetImageCache.prefetchUrlsSync(context, res.text)
757
+ }
758
+ flattenJson(jsonObj, "", mergedVars)
759
+ }
760
+ }
761
+ is SourceFetchResult.NotModified -> {
762
+ finalStatus = res.statusCode
763
+ }
764
+ is SourceFetchResult.Failed -> {
765
+ allNotModified = false
766
+ anyError = res.error
767
+ finalStatus = res.statusCode
768
+ }
308
769
  }
770
+ }
309
771
 
310
- val keys = jsonObj.keys()
311
- while (keys.hasNext()) {
312
- val k = keys.next()
313
- val v = jsonObj.opt(k)
314
- if (v is String || v is Number || v is Boolean) {
315
- state.remoteVariables[k] = v.toString()
772
+ val sourcesObj = cfg?.optJSONObject("sources")
773
+ if (sourcesObj != null) {
774
+ val srcKeys = sourcesObj.keys()
775
+ while (srcKeys.hasNext()) {
776
+ val srcKey = srcKeys.next()
777
+ val srcCfg = sourcesObj.optJSONObject(srcKey) ?: continue
778
+ val srcUrl = srcCfg.optString("url", "")
779
+ if (srcUrl.isEmpty()) continue
780
+ val res = fetchWithRetryAndAuth(
781
+ cacheKey = "$widgetKey:$srcKey",
782
+ urlString = srcUrl,
783
+ method = srcCfg.optString("method", "").ifEmpty { null } ?: defaultMethod,
784
+ headers = srcCfg.optJSONObject("headers") ?: defaultHeaders,
785
+ bodyStr = extractBodyString(srcCfg),
786
+ timeoutMs = srcCfg.optInt("timeoutMs", timeoutMs).coerceAtLeast(1000),
787
+ enableETag = if (srcCfg.has("enableETag")) srcCfg.optBoolean("enableETag", enableETag) else enableETag,
788
+ maxRetries = maxRetries,
789
+ retryDelayMs = retryDelayMs,
790
+ authObj = authObj,
791
+ state = state
792
+ )
793
+ when (res) {
794
+ is SourceFetchResult.Updated -> {
795
+ fetchedAnyData = true
796
+ allNotModified = false
797
+ if (finalStatus == null) finalStatus = res.statusCode
798
+ res.etag?.let { state.etags["$widgetKey:$srcKey"] = it }
799
+ res.lastModified?.let { state.lastModified["$widgetKey:$srcKey"] = it }
800
+ runCatching {
801
+ val jsonObj = JSONObject(res.text)
802
+ flattenJson(jsonObj, srcKey, mergedVars)
803
+ }
804
+ }
805
+ is SourceFetchResult.NotModified -> {
806
+ if (finalStatus == null) finalStatus = res.statusCode
807
+ }
808
+ is SourceFetchResult.Failed -> {
809
+ allNotModified = false
810
+ if (anyError == null) anyError = "$srcKey: ${res.error}"
811
+ if (finalStatus == null) finalStatus = res.statusCode
812
+ }
316
813
  }
317
814
  }
318
- saveState(context, state)
815
+ }
319
816
 
320
- val intervalMins = try {
321
- val cfg = if (!configJson.isNullOrEmpty()) JSONObject(configJson) else null
322
- if (cfg?.has("refreshIntervalMinutes") == true) {
323
- cfg.optInt("refreshIntervalMinutes", 15)
324
- } else {
325
- cfg?.optInt("intervalMinutes", 15) ?: 15
817
+ state.lastSyncTime = SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date())
818
+ state.updatedAt = System.currentTimeMillis()
819
+ state.lastHttpStatus = finalStatus
820
+
821
+ if (anyError != null && !fetchedAnyData && !allNotModified) {
822
+ state.syncStatus = "error"
823
+ state.lastSyncError = anyError
824
+ state.remoteVariables["_syncStatus"] = "error"
825
+ state.remoteVariables["_syncError"] = anyError!!
826
+ finalStatus?.let { state.remoteVariables["_httpStatus"] = it.toString() }
827
+ saveState(context, state)
828
+ } else {
829
+ val (schemaOk, schemaErr) = validateAndApplySchema(mergedVars, cfg?.optJSONObject("schema"))
830
+ if (!schemaOk) {
831
+ val errMsg = schemaErr ?: "Schema validation failed"
832
+ state.syncStatus = "error"
833
+ state.lastSyncError = errMsg
834
+ state.remoteVariables["_syncStatus"] = "error"
835
+ state.remoteVariables["_syncError"] = errMsg
836
+ finalStatus?.let { state.remoteVariables["_httpStatus"] = it.toString() }
837
+ saveState(context, state)
838
+ } else {
839
+ cfg?.optJSONObject("mapping")?.let { mapObj ->
840
+ val keys = mapObj.keys()
841
+ while (keys.hasNext()) {
842
+ val targetKey = keys.next()
843
+ val expr = mapObj.optString(targetKey, "")
844
+ if (expr.isNotEmpty()) {
845
+ if (expr.contains("{{")) {
846
+ mergedVars[targetKey] = resolveTemplateString(expr, mergedVars)
847
+ } else {
848
+ val parts = expr.split("|")
849
+ val pathKey = parts[0].trim()
850
+ val pipes = parts.drop(1)
851
+ mergedVars[targetKey] = when {
852
+ mergedVars.containsKey(pathKey) -> {
853
+ val existing = mergedVars[pathKey]
854
+ if (pipes.isEmpty()) sanitizeVariableValue(existing) ?: (existing ?: "")
855
+ else evaluateTemplatePipe(existing, pipes)
856
+ }
857
+ pipes.isNotEmpty() -> evaluateTemplatePipe(null, pipes)
858
+ else -> expr
859
+ }
860
+ }
861
+ }
862
+ }
326
863
  }
327
- } catch (_: Exception) { 15 }.coerceAtLeast(1)
328
- scheduleBackgroundWidgetSync(context, widgetKey, intervalMins)
329
- } catch (_: Exception) {
330
- stampSyncTimeOnly(context)
864
+
865
+ state.syncStatus = if (anyError != null) "partial" else "ok"
866
+ state.lastSyncError = anyError
867
+ mergedVars["_syncStatus"] = state.syncStatus!!
868
+ mergedVars["_syncError"] = anyError ?: ""
869
+ finalStatus?.let { mergedVars["_httpStatus"] = it.toString() }
870
+ state.remoteVariables = mergedVars
871
+ saveState(context, state)
872
+ }
331
873
  }
874
+
875
+ val intervalMins = try {
876
+ if (cfg?.has("refreshIntervalMinutes") == true) {
877
+ cfg.optInt("refreshIntervalMinutes", 15)
878
+ } else {
879
+ cfg?.optInt("intervalMinutes", 15) ?: 15
880
+ }
881
+ } catch (_: Exception) { 15 }.coerceAtLeast(1)
882
+ scheduleBackgroundWidgetSync(context, widgetKey, intervalMins)
332
883
  }
333
884
 
334
885
  fun scheduleBackgroundWidgetSync(context: Context, widgetKey: String, intervalMinutes: Int) {
@@ -353,12 +904,4 @@ object DynamicWidgetStateStore {
353
904
  } catch (_: Exception) {
354
905
  }
355
906
  }
356
-
357
- private fun stampSyncTimeOnly(context: Context) {
358
- val state = loadState(context)
359
- state.lastSyncTime = SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date())
360
- state.updatedAt = System.currentTimeMillis()
361
- saveState(context, state)
362
- }
363
907
  }
364
-