reflex-capacitor 0.3.2__tar.gz → 0.3.3__tar.gz

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 (43) hide show
  1. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/.gitignore +2 -1
  2. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/CHANGELOG.md +24 -0
  3. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/PKG-INFO +2 -3
  4. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/README.md +1 -2
  5. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/docs/guide/00-getting-started.md +1 -2
  6. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/docs/guide/02-native-bridge.md +4 -2
  7. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/docs/guide/configuration.md +11 -11
  8. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/docs/guide/debug.md +3 -3
  9. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/docs/guide/faq.md +3 -4
  10. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/docs/guide/install.md +4 -4
  11. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/pyproject.toml +1 -1
  12. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/__init__.py +9 -1
  13. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/bridge/__init__.py +4 -0
  14. reflex_capacitor-0.3.3/src/reflex_capacitor/bridge/android_audio_focus.py +273 -0
  15. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/bridge/api.py +91 -0
  16. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/bridge/api.pyi +26 -0
  17. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/bridge/assets/bridge.js +410 -0
  18. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/bridge/inject.py +3 -1
  19. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/bridge/ios_plist.py +4 -0
  20. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/bridge/plugins.py +80 -8
  21. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/plugin.py +62 -3
  22. reflex_capacitor-0.3.3/src/reflex_capacitor/urls.py +67 -0
  23. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/LICENSE +0 -0
  24. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/docs/README.md +0 -0
  25. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/docs/guide/android-build.md +0 -0
  26. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/docs/guide/ci.md +0 -0
  27. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/docs/guide/cli.md +0 -0
  28. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/docs/guide/dev-reload.md +0 -0
  29. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/docs/guide/publishing.md +0 -0
  30. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/android_signing.py +0 -0
  31. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/bridge/_script.py +0 -0
  32. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/bridge/assets/image-editor.js +0 -0
  33. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/bridge/log.py +0 -0
  34. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/cli.py +0 -0
  35. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/components/__init__.py +0 -0
  36. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/components/image_editor.py +0 -0
  37. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/config.py +0 -0
  38. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/dev_util.py +0 -0
  39. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/network_env.py +0 -0
  40. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/preflight.py +0 -0
  41. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/scaffold/.gitignore +0 -0
  42. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/scaffold/capacitor.config.json +0 -0
  43. {reflex_capacitor-0.3.2 → reflex_capacitor-0.3.3}/src/reflex_capacitor/scaffold/package.json +0 -0
@@ -2,7 +2,8 @@
2
2
  .states
3
3
  .web
4
4
  *.db
5
- assets/external/
5
+ media_cache/
6
+ uploaded_files/
6
7
 
7
8
  # Python-generated files
8
9
  __pycache__/
@@ -2,6 +2,30 @@
2
2
 
3
3
  All notable changes to this project are documented here.
4
4
 
5
+ ## [Unreleased]
6
+
7
+ ## [0.3.3] — 2026-11-09
8
+
9
+ ### Features
10
+
11
+ - ``CapacitorPlugin.plugins`` defaults to ``ALL_PLUGIN_IDS`` (core + extended; push still opt-in via ``PHASE5_PLUGIN_IDS``)
12
+ - ``reflex_capacitor.get_upload_url`` / ``resolve_backend_base`` — absolute ``/_upload`` URLs using Cap ``backend_url`` / ``REFLEX_CAPACITOR_DEV_BACKEND_URL`` (avoids localhost in APK)
13
+ - Built-in voice recording / playback in packaged ``bridge.js`` (``mobile.start_recording`` / ``stop_recording`` / ``play_recording``); enable ``voice-recorder`` for mic permissions
14
+ - ``CapacitorPlugin`` loads bridge scripts during ``reflex run`` (browser) via Vite ``public/`` + document inject
15
+ - Android mic: also declare ``MODIFY_AUDIO_SETTINGS`` (required by WebView ``getUserMedia``; missing it causes ``permission_denied`` even when RECORD_AUDIO is granted)
16
+ - System TTS: ``mobile.speak`` / ``stop_speak`` prefer native ``@capacitor-community/text-to-speech`` (Cap 7 → npm ``^6.1.0``), fall back to ``speechSynthesis``
17
+ - TTS audio focus (Android): ``finalize_bridge`` installs local ``AudioFocusPlugin``; ``mobile.speak`` defaults to ``audio_focus="pause"`` so background music typically pauses (``duck`` / ``none`` also supported)
18
+ - AudioFocus: use ``USAGE_MEDIA`` + ``AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE`` (QQ Music often ignored ``USAGE_ASSISTANT``); speak callback reports ``audioFocus.granted``
19
+
20
+ ### Fixes
21
+
22
+ - Proxy unit test expected wrong Gradle port (``7892`` typo vs ``7890``)
23
+ - Android APK CI: upgrade ``setup-android`` to v4 and install ``platforms;android-35`` + ``build-tools;35.0.0`` (SDK no longer ships obsolete ``tools`` package)
24
+
25
+ ### Chores
26
+
27
+ - Demo default ``CapacitorPlugin.backend_url``: ``http://192.168.10.105:8003`` (was ``192.168.1.56:8003``)
28
+
5
29
  ## [0.3.2] — 2026-08-25
6
30
 
7
31
  ### Fixes
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: reflex-capacitor
3
- Version: 0.3.2
3
+ Version: 0.3.3
4
4
  Summary: Package a Reflex app as a Capacitor mobile app (remote backend).
5
5
  Project-URL: Homepage, https://github.com/JiaLiangChen99/reflex_capacitor
6
6
  Project-URL: Documentation, https://github.com/JiaLiangChen99/reflex_capacitor/blob/main/docs/README.md
@@ -45,7 +45,6 @@ See [`docs/guide/cli.md`](docs/guide/cli.md) and [`docs/guide/install.md`](docs/
45
45
  # rxconfig.py
46
46
  import reflex as rx
47
47
  from reflex_capacitor import CapacitorPlugin
48
- from reflex_capacitor.bridge.plugins import ALL_PLUGIN_IDS
49
48
 
50
49
  config = rx.Config(
51
50
  app_name="demo",
@@ -55,7 +54,7 @@ config = rx.Config(
55
54
  backend_url="https://api.example.com",
56
55
  app_id="com.example.myapp",
57
56
  app_name="My App",
58
- plugins=ALL_PLUGIN_IDS, # default in code is CORE only; ALL recommended
57
+ # plugins defaults to ALL_PLUGIN_IDS (camera/TTS/recorder/…; no push)
59
58
  ),
60
59
  ],
61
60
  )
@@ -26,7 +26,6 @@ See [`docs/guide/cli.md`](docs/guide/cli.md) and [`docs/guide/install.md`](docs/
26
26
  # rxconfig.py
27
27
  import reflex as rx
28
28
  from reflex_capacitor import CapacitorPlugin
29
- from reflex_capacitor.bridge.plugins import ALL_PLUGIN_IDS
30
29
 
31
30
  config = rx.Config(
32
31
  app_name="demo",
@@ -36,7 +35,7 @@ config = rx.Config(
36
35
  backend_url="https://api.example.com",
37
36
  app_id="com.example.myapp",
38
37
  app_name="My App",
39
- plugins=ALL_PLUGIN_IDS, # default in code is CORE only; ALL recommended
38
+ # plugins defaults to ALL_PLUGIN_IDS (camera/TTS/recorder/…; no push)
40
39
  ),
41
40
  ],
42
41
  )
@@ -28,7 +28,6 @@ reflex-capacitor check --android
28
28
  ```python
29
29
  import reflex as rx
30
30
  from reflex_capacitor import CapacitorPlugin
31
- from reflex_capacitor.bridge.plugins import ALL_PLUGIN_IDS
32
31
 
33
32
  config = rx.Config(
34
33
  app_name="demo",
@@ -38,7 +37,7 @@ config = rx.Config(
38
37
  backend_url="http://192.168.1.56:8001", # 生产用 https://
39
38
  app_id="dev.reflex.myapp",
40
39
  app_name="My App",
41
- plugins=ALL_PLUGIN_IDS, # 推送等见 configuration.md
40
+ # 默认 ALL_PLUGIN_IDS;推送见 configuration.md
42
41
  ),
43
42
  ],
44
43
  )
@@ -112,6 +112,8 @@ window.__REFLEX_CAPACITOR__ = {
112
112
  | 生物识别 | community / `@capawesome/...` | `biometric_verify(callback)` | 未做 |
113
113
  | 条码扫描 | community | `scan_barcode(callback)` | 未做 |
114
114
  | 应用内浏览器 | `@capacitor/browser` | `browser_open(url)` | P1(EXTENDED) |
115
+ | 录音 / 回放 | 内置 `bridge.js`(MediaRecorder) | `start_recording` / `stop_recording` / `play_recording` | P1(EXTENDED,builtin) |
116
+ | 系统播报 TTS | `@capacitor-community/text-to-speech`(原生)+ Web 回退 | `speak` / `stop_speak` | 启用 `text-to-speech`;播报时 Android 默认申请 audio focus(`audio_focus="pause"` 暂停多数音乐 App,`"duck"` 仅压低音量,`"none"` 混播);需 `sync` 后重装 APK 以注入 `AudioFocusPlugin` |
115
117
 
116
118
  > **「组件」**:Capacitor 官方几乎都是 **命令式 Plugin API**,不是 React Native 那种 `<Camera />` 组件。Google Maps 等少数带 Web Component;MVP **不包地图组件**,需要时再单独立项。
117
119
 
@@ -206,8 +208,8 @@ def invoke(command: str, args: Mapping | None = None, *, callback=None) -> Event
206
208
  | 层级 | 常量 | 典型内容 |
207
209
  |------|------|----------|
208
210
  | 核心 | `CORE_PLUGIN_IDS` | app、splash、status-bar、notify、toast、haptics、clipboard、share、device、network |
209
- | 扩展 | `EXTENDED_PLUGIN_IDS` | camera、geolocation、filesystem、preferences、keyboard、browser |
210
- | 推荐默认 | `ALL_PLUGIN_IDS` | CORE + EXTENDED(**不含**推送) |
211
+ | 扩展 | `EXTENDED_PLUGIN_IDS` | camera、geolocation、filesystem、preferences、keyboard、browser、voice-recorder |
212
+ | 推荐默认 | `ALL_PLUGIN_IDS` | CORE + EXTENDED(**不含**推送;即 `CapacitorPlugin` 默认值) |
211
213
  | 可选 | `PHASE5_PLUGIN_IDS` | `push-notifications`(需自备 FCM/APNs) |
212
214
 
213
215
  ---
@@ -15,42 +15,42 @@
15
15
  | `app_name` | Reflex `app_name` | 桌面显示名 |
16
16
  | `capacitor_dir` | `"capacitor"` | Cap 工程目录 |
17
17
  | `web_dir` | `"www"` | 静态资源目录名(相对 `capacitor_dir`) |
18
- | `plugins` | **`CORE_PLUGIN_IDS`** | 短 id 元组;多数 App 建议显式传 `ALL_PLUGIN_IDS` |
18
+ | `plugins` | **`ALL_PLUGIN_IDS`** | 短 id 元组(CORE + EXTENDED);推送仍需另加 `PHASE5_PLUGIN_IDS` |
19
19
  | `icon` | `None` | 可选 PNG,sync 时拷到 Android mipmap |
20
20
 
21
21
  ```python
22
22
  from reflex_capacitor import CapacitorPlugin
23
- from reflex_capacitor.bridge.plugins import ALL_PLUGIN_IDS
24
23
 
25
24
  CapacitorPlugin(
26
25
  backend_url="https://api.example.com",
27
26
  app_id="com.example.myapp",
28
27
  app_name="My App",
29
- plugins=ALL_PLUGIN_IDS, # 推荐;默认仅 CORE
28
+ # plugins 默认已是 ALL_PLUGIN_IDS;要缩小体积再传 CORE_PLUGIN_IDS
30
29
  )
31
30
  ```
32
31
 
33
32
  ---
34
33
 
35
- ## 插件分层(推荐默认)
34
+ ## 插件分层
36
35
 
37
36
  | 常量 | 内容 | 何时用 |
38
37
  |------|------|--------|
39
- | `CORE_PLUGIN_IDS` | 通知、剪贴板、分享、状态栏、设备、网络… | 最小壳 |
40
- | `EXTENDED_PLUGIN_IDS` | 相机、定位、文件系统、键盘、browser… | 需要传感器/文件 |
41
- | `ALL_PLUGIN_IDS` | CORE + EXTENDED | **PyPI / 通用默认推荐** |
38
+ | `ALL_PLUGIN_IDS` | CORE + EXTENDED | **默认**(相机/定位/TTS/录音等,不含推送) |
39
+ | `CORE_PLUGIN_IDS` | 通知、剪贴板、分享、状态栏、设备、网络… | 想瘦身时显式传入 |
40
+ | `EXTENDED_PLUGIN_IDS` | 相机、定位、文件系统、键盘、browser、录音、TTS… | 一般不必单独用 |
42
41
  | `PHASE5_PLUGIN_IDS` | 当前含 `push-notifications` | **显式**需要远程推送时再加 |
43
42
 
44
43
  ```python
45
- from reflex_capacitor.bridge.plugins import ALL_PLUGIN_IDS, PHASE5_PLUGIN_IDS
44
+ from reflex_capacitor.bridge.plugins import ALL_PLUGIN_IDS, CORE_PLUGIN_IDS, PHASE5_PLUGIN_IDS
46
45
 
47
- # 推荐默认(不含 FCM)
48
- plugins=ALL_PLUGIN_IDS
46
+ # 默认即可,不必写 plugins=
47
+
48
+ # 瘦身
49
+ plugins=CORE_PLUGIN_IDS
49
50
 
50
51
  # 需要远程推送时
51
52
  plugins=ALL_PLUGIN_IDS + PHASE5_PLUGIN_IDS
52
53
  ```
53
-
54
54
  推送需自备 Firebase / APNs;本包**不含**服务端实现 → [push-notifications.md](push-notifications.md)。
55
55
 
56
56
  ---
@@ -66,10 +66,10 @@ Android 真机 USB 调试时,Chrome 打开 `chrome://inspect` 可查看 WebVie
66
66
 
67
67
  | 现象 | 排查 |
68
68
  |------|------|
69
- | 诊断 `bridge_not_loaded` | 未执行 `reflex-capacitor sync`,或 `index.html` 未注入 bridge |
70
- | `pluginsMissing` 非空 | `npm install` / `finalize_bridge` 未跑,vendor JS 缺失 |
69
+ | 诊断 `bridge_not_loaded` | 刷新页面;确认 `rxconfig` 含 `CapacitorPlugin`;重启 `reflex run`。Cap 壳还需 `sync` |
70
+ | `pluginsMissing` 非空 | `npm install` / `finalize_bridge` 未跑,vendor JS 缺失(浏览器下多数 Cap 插件本就会缺失,属正常) |
71
71
  | 客户端有日志、服务端无 | 正常:void 调用(notify/toast)只在 WebView 执行;带 callback 的才会回后端 |
72
- | `isNative: false` | 在浏览器打开,非 Capacitor 壳 |
72
+ | `isNative: false` | 在浏览器打开,非 Capacitor 壳 — **可测录音/回放**(MediaRecorder);相机/推送等仍需真机 |
73
73
  | WebSocket / 连不上后端 | 后端 `0.0.0.0`、同 Wi‑Fi、HTTP 需 cleartext;见 [android-build.md](android-build.md) |
74
74
  | Gradle / 缺 SDK | `reflex-capacitor check --android` |
75
75
 
@@ -12,10 +12,9 @@
12
12
 
13
13
  ---
14
14
 
15
- ### 为什么默认插件不是「全家桶」?
15
+ ### 默认会装哪些原生插件?
16
16
 
17
- 代码默认是 `CORE_PLUGIN_IDS`(体积与权限更小)。文档推荐多数 App 显式写 `ALL_PLUGIN_IDS`。
18
- **推送不在默认里**,需 `PHASE5_PLUGIN_IDS`。见 [configuration.md](configuration.md)。
17
+ 默认是 `ALL_PLUGIN_IDS`(相机、定位、TTS、录音等)。**推送不在默认里**,需 `PHASE5_PLUGIN_IDS`。想瘦身再显式传 `CORE_PLUGIN_IDS`。见 [configuration.md](configuration.md)。
19
18
 
20
19
  ---
21
20
 
@@ -73,7 +72,7 @@ reflex-capacitor sync --proxy http://127.0.0.1:7890
73
72
  ### PyPI 上的包和本仓库 demo 有什么差别?
74
73
 
75
74
  库本身不含你的 `capacitor/android` 工程(`init` 生成)。
76
- 本仓库 `demo/` + `PHASE5` 仅为演示;对外示例应默认 `ALL_PLUGIN_IDS`、不含推送。见 [install.md](install.md)。
75
+ 本仓库 `demo/` + `PHASE5` 仅为演示;对外默认已是 `ALL_PLUGIN_IDS`、不含推送。见 [install.md](install.md)。
77
76
 
78
77
  ---
79
78
 
@@ -70,7 +70,7 @@ reflex-capacitor sync
70
70
  ```
71
71
 
72
72
  配置示例 → [configuration.md](configuration.md)。
73
- 默认 `plugins=` 为 `CORE_PLUGIN_IDS`;多数 App 建议显式传 `ALL_PLUGIN_IDS`(仍**不含**推送)。
73
+ 默认 `plugins=` 为 `ALL_PLUGIN_IDS`(仍**不含**推送;推送用 `PHASE5_PLUGIN_IDS`)。
74
74
 
75
75
  ---
76
76
 
@@ -112,16 +112,16 @@ reflex-capacitor sync
112
112
 
113
113
  #### 每次发版
114
114
 
115
- 1. 改 `pyproject.toml` 里 `version`(当前 `0.3.2`)
115
+ 1. 改 `pyproject.toml` 里 `version`(当前 `0.3.3`)
116
116
  2. 更新 `CHANGELOG.md`,提交并 push
117
117
  3. GitHub → **Releases** → **Draft a new release**
118
- - Tag:`v0.3.2`(**必须**与 `pyproject.toml` 的 version 一致,带 `v` 前缀)
118
+ - Tag:`v0.3.3`(**必须**与 `pyproject.toml` 的 version 一致,带 `v` 前缀)
119
119
  - Title / 说明:粘贴 CHANGELOG 摘要
120
120
  - 点 **Publish release**
121
121
  4. Actions 里看 **Publish to PyPI** workflow;成功后:
122
122
 
123
123
  ```bash
124
- pip install reflex-capacitor==0.3.2
124
+ pip install reflex-capacitor==0.3.3
125
125
  ```
126
126
 
127
127
  Workflow 会:跑 L1 集成测试 → `python -m build` → 校验 wheel 含 `bridge.js` / scaffold → 校验 tag 与 version → `pypi-publish`。
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "reflex-capacitor"
3
- version = "0.3.2"
3
+ version = "0.3.3"
4
4
  description = "Package a Reflex app as a Capacitor mobile app (remote backend)."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -4,5 +4,13 @@ from .bridge import api as mobile
4
4
  from .bridge import api # noqa: F401 — re-export module for `from reflex_capacitor.bridge import api`
5
5
  from . import components
6
6
  from .plugin import CapacitorPlugin as CapacitorPlugin
7
+ from .urls import get_upload_url, resolve_backend_base
7
8
 
8
- __all__ = ["CapacitorPlugin", "mobile", "api", "components"]
9
+ __all__ = [
10
+ "CapacitorPlugin",
11
+ "mobile",
12
+ "api",
13
+ "components",
14
+ "get_upload_url",
15
+ "resolve_backend_base",
16
+ ]
@@ -7,18 +7,21 @@ from .inject import install_bridge
7
7
  from .log import log_bridge
8
8
  from .plugins import (
9
9
  ALL_PLUGIN_IDS,
10
+ BUILTIN_BRIDGE_PLUGIN_IDS,
10
11
  CAPACITOR_PLUGIN_PACKAGES,
11
12
  CORE_PLUGIN_IDS,
12
13
  EXTENDED_PLUGIN_IDS,
13
14
  apply_package_json_deps,
14
15
  copy_plugin_vendor_scripts,
15
16
  ensure_android_notification_permission,
17
+ has_npm_package,
16
18
  resolve_plugin_ids,
17
19
  vendor_script_filename,
18
20
  )
19
21
 
20
22
  __all__ = [
21
23
  "ALL_PLUGIN_IDS",
24
+ "BUILTIN_BRIDGE_PLUGIN_IDS",
22
25
  "CAPACITOR_PLUGIN_PACKAGES",
23
26
  "CORE_PLUGIN_IDS",
24
27
  "EXTENDED_PLUGIN_IDS",
@@ -29,6 +32,7 @@ __all__ = [
29
32
  "apply_package_json_deps",
30
33
  "copy_plugin_vendor_scripts",
31
34
  "ensure_android_notification_permission",
35
+ "has_npm_package",
32
36
  "resolve_plugin_ids",
33
37
  "vendor_script_filename",
34
38
  ]
@@ -0,0 +1,273 @@
1
+ """Install a local Capacitor AudioFocus plugin into the Android app module.
2
+
3
+ Used so TTS can pause/duck background music (Android audio focus). The community
4
+ TextToSpeech plugin does not request focus on its own.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from pathlib import Path
11
+
12
+ __all__ = [
13
+ "find_main_activity",
14
+ "install_audio_focus_plugin",
15
+ ]
16
+
17
+ _PLUGIN_CLASS = "AudioFocusPlugin"
18
+ _PLUGIN_NAME = "AudioFocus"
19
+
20
+
21
+ def find_main_activity(android_root: Path) -> Path | None:
22
+ """Return ``MainActivity.java`` / ``.kt`` under the Android app module."""
23
+ app_src = android_root / "app" / "src" / "main"
24
+ if not app_src.is_dir():
25
+ return None
26
+ for path in app_src.rglob("MainActivity.java"):
27
+ return path
28
+ for path in app_src.rglob("MainActivity.kt"):
29
+ return path
30
+ return None
31
+
32
+
33
+ def _package_name(main_activity: Path) -> str | None:
34
+ text = main_activity.read_text(encoding="utf-8")
35
+ match = re.search(r"^\s*package\s+([\w.]+)\s*;?", text, flags=re.MULTILINE)
36
+ return match.group(1) if match else None
37
+
38
+
39
+ def _plugin_java_source(package: str) -> str:
40
+ return f"""package {package};
41
+
42
+ import android.content.Context;
43
+ import android.media.AudioAttributes;
44
+ import android.media.AudioFocusRequest;
45
+ import android.media.AudioManager;
46
+ import android.os.Build;
47
+ import android.os.Handler;
48
+ import android.os.Looper;
49
+
50
+ import com.getcapacitor.JSObject;
51
+ import com.getcapacitor.Plugin;
52
+ import com.getcapacitor.PluginCall;
53
+ import com.getcapacitor.PluginMethod;
54
+ import com.getcapacitor.annotation.CapacitorPlugin;
55
+
56
+ /**
57
+ * Requests transient audio focus so TTS can pause/duck other apps (music, etc.).
58
+ * Generated by reflex-capacitor — do not edit by hand.
59
+ *
60
+ * Uses USAGE_MEDIA (not ASSISTANT): QQ Music / NetEase often ignore assistant focus.
61
+ */
62
+ @CapacitorPlugin(name = "{_PLUGIN_NAME}")
63
+ public class {_PLUGIN_CLASS} extends Plugin {{
64
+ private AudioManager audioManager;
65
+ private AudioFocusRequest focusRequest;
66
+ private final Handler mainHandler = new Handler(Looper.getMainLooper());
67
+ private final AudioManager.OnAudioFocusChangeListener focusChangeListener =
68
+ focusChange -> {{
69
+ /* no-op: TTS owns the focus for the utterance duration */
70
+ }};
71
+
72
+ @Override
73
+ public void load() {{
74
+ audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
75
+ }}
76
+
77
+ @PluginMethod
78
+ public void request(PluginCall call) {{
79
+ if (audioManager == null) {{
80
+ call.reject("audio_manager_missing");
81
+ return;
82
+ }}
83
+ // Run on main thread — some OEMs ignore focus requests from bridge threads.
84
+ mainHandler.post(() -> {{
85
+ try {{
86
+ resolveRequest(call);
87
+ }} catch (Exception e) {{
88
+ call.reject("audio_focus_failed", e);
89
+ }}
90
+ }});
91
+ }}
92
+
93
+ private void resolveRequest(PluginCall call) {{
94
+ // Abandon any previous request so we do not stack listeners.
95
+ abandonFocusQuietly();
96
+
97
+ String mode = call.getString("mode", "pause");
98
+ int durationHint;
99
+ if ("duck".equalsIgnoreCase(mode)) {{
100
+ durationHint = AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK;
101
+ }} else if ("exclusive".equalsIgnoreCase(mode) || "pause".equalsIgnoreCase(mode)) {{
102
+ // EXCLUSIVE asks others to pause (not merely duck). Better for QQ Music.
103
+ durationHint = AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE;
104
+ }} else {{
105
+ durationHint = AudioManager.AUDIOFOCUS_GAIN_TRANSIENT;
106
+ }}
107
+
108
+ int result;
109
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {{
110
+ AudioAttributes attrs =
111
+ new AudioAttributes.Builder()
112
+ .setUsage(AudioAttributes.USAGE_MEDIA)
113
+ .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
114
+ .build();
115
+ AudioFocusRequest.Builder builder =
116
+ new AudioFocusRequest.Builder(durationHint)
117
+ .setAudioAttributes(attrs)
118
+ .setAcceptsDelayedFocusGain(false)
119
+ .setOnAudioFocusChangeListener(focusChangeListener, mainHandler);
120
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {{
121
+ builder.setForceDucking(false);
122
+ }}
123
+ focusRequest = builder.build();
124
+ result = audioManager.requestAudioFocus(focusRequest);
125
+ }} else {{
126
+ result =
127
+ audioManager.requestAudioFocus(
128
+ focusChangeListener, AudioManager.STREAM_MUSIC, durationHint);
129
+ }}
130
+
131
+ JSObject ret = new JSObject();
132
+ ret.put("granted", result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED);
133
+ ret.put("result", result);
134
+ ret.put("mode", mode);
135
+ call.resolve(ret);
136
+ }}
137
+
138
+ @PluginMethod
139
+ public void abandon(PluginCall call) {{
140
+ mainHandler.post(() -> {{
141
+ abandonFocusQuietly();
142
+ JSObject ret = new JSObject();
143
+ ret.put("ok", true);
144
+ call.resolve(ret);
145
+ }});
146
+ }}
147
+
148
+ private void abandonFocusQuietly() {{
149
+ if (audioManager == null) {{
150
+ return;
151
+ }}
152
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && focusRequest != null) {{
153
+ audioManager.abandonAudioFocusRequest(focusRequest);
154
+ focusRequest = null;
155
+ }} else {{
156
+ audioManager.abandonAudioFocus(focusChangeListener);
157
+ }}
158
+ }}
159
+ }}
160
+ """
161
+
162
+
163
+ def _ensure_main_activity_registers(main_activity: Path) -> bool:
164
+ """Ensure MainActivity registers AudioFocusPlugin before super.onCreate. Returns True if changed."""
165
+ text = main_activity.read_text(encoding="utf-8")
166
+ if _PLUGIN_CLASS in text and "registerPlugin" in text:
167
+ return False
168
+
169
+ if main_activity.suffix == ".kt":
170
+ patched = text
171
+ if "import android.os.Bundle" not in patched:
172
+ patched = patched.replace(
173
+ "import com.getcapacitor.BridgeActivity",
174
+ "import android.os.Bundle\nimport com.getcapacitor.BridgeActivity",
175
+ 1,
176
+ )
177
+ if "override fun onCreate" in patched:
178
+ if f"registerPlugin({_PLUGIN_CLASS}::class.java)" not in patched:
179
+ patched = re.sub(
180
+ r"(override fun onCreate\s*\([^)]*\)\s*\{)",
181
+ rf"\1\n registerPlugin({_PLUGIN_CLASS}::class.java)",
182
+ patched,
183
+ count=1,
184
+ )
185
+ else:
186
+ # Empty BridgeActivity subclass — add onCreate
187
+ with_body = re.sub(
188
+ r"(class\s+MainActivity\s*:\s*BridgeActivity\s*\(\s*\)\s*\{)",
189
+ rf"\1\n override fun onCreate(savedInstanceState: Bundle?) {{\n"
190
+ rf" registerPlugin({_PLUGIN_CLASS}::class.java)\n"
191
+ rf" super.onCreate(savedInstanceState)\n }}\n",
192
+ patched,
193
+ count=1,
194
+ )
195
+ if with_body != patched:
196
+ patched = with_body
197
+ else:
198
+ # No body braces: `class MainActivity : BridgeActivity()`
199
+ patched = re.sub(
200
+ r"(class\s+MainActivity\s*:\s*BridgeActivity\s*\(\s*\))",
201
+ rf"\1 {{\n override fun onCreate(savedInstanceState: Bundle?) {{\n"
202
+ rf" registerPlugin({_PLUGIN_CLASS}::class.java)\n"
203
+ rf" super.onCreate(savedInstanceState)\n }}\n}}",
204
+ patched,
205
+ count=1,
206
+ )
207
+ if f"registerPlugin({_PLUGIN_CLASS}::class.java)" not in patched:
208
+ return False
209
+ if patched != text:
210
+ main_activity.write_text(patched, encoding="utf-8")
211
+ return True
212
+ return False
213
+
214
+ # Java MainActivity
215
+ patched = text
216
+ if "import android.os.Bundle;" not in patched:
217
+ patched = patched.replace(
218
+ "import com.getcapacitor.BridgeActivity;",
219
+ "import android.os.Bundle;\nimport com.getcapacitor.BridgeActivity;",
220
+ 1,
221
+ )
222
+
223
+ if "void onCreate" in patched:
224
+ if f"registerPlugin({_PLUGIN_CLASS}.class)" not in patched:
225
+ patched = re.sub(
226
+ r"(protected\s+void\s+onCreate\s*\([^)]*\)\s*\{|public\s+void\s+onCreate\s*\([^)]*\)\s*\{)",
227
+ rf"\1\n registerPlugin({_PLUGIN_CLASS}.class);",
228
+ patched,
229
+ count=1,
230
+ )
231
+ else:
232
+ # Empty BridgeActivity subclass — add onCreate
233
+ patched = re.sub(
234
+ r"(public\s+class\s+MainActivity\s+extends\s+BridgeActivity\s*\{)",
235
+ rf"\1\n @Override\n public void onCreate(Bundle savedInstanceState) {{\n"
236
+ rf" registerPlugin({_PLUGIN_CLASS}.class);\n"
237
+ rf" super.onCreate(savedInstanceState);\n }}\n",
238
+ patched,
239
+ count=1,
240
+ )
241
+
242
+ if patched == text:
243
+ return False
244
+ main_activity.write_text(patched, encoding="utf-8")
245
+ return True
246
+
247
+
248
+ def install_audio_focus_plugin(android_root: Path | str) -> list[str]:
249
+ """Write ``AudioFocusPlugin`` and register it from MainActivity.
250
+
251
+ Returns:
252
+ Human-readable list of actions taken (empty if Android tree missing).
253
+ """
254
+ root = Path(android_root)
255
+ main_activity = find_main_activity(root)
256
+ if main_activity is None:
257
+ return []
258
+
259
+ package = _package_name(main_activity)
260
+ if not package:
261
+ return []
262
+
263
+ actions: list[str] = []
264
+ plugin_path = main_activity.parent / f"{_PLUGIN_CLASS}.java"
265
+ source = _plugin_java_source(package)
266
+ if not plugin_path.is_file() or plugin_path.read_text(encoding="utf-8") != source:
267
+ plugin_path.write_text(source, encoding="utf-8")
268
+ actions.append(f"wrote {plugin_path.name}")
269
+
270
+ if _ensure_main_activity_registers(main_activity):
271
+ actions.append(f"registered plugin in {main_activity.name}")
272
+
273
+ return actions
@@ -234,6 +234,97 @@ def fs_read(path: str, callback: Any, *, directory: str = "DATA") -> rx.event.Ev
234
234
  return call_bridge("fsRead", {"path": path, "directory": directory}, callback=callback)
235
235
 
236
236
 
237
+ def start_recording(
238
+ *,
239
+ directory: str | None = None,
240
+ sub_directory: str | None = None,
241
+ callback: Any = None,
242
+ ) -> rx.event.EventSpec:
243
+ """Start microphone recording (built into packaged ``bridge.js``).
244
+
245
+ Enable ``voice-recorder`` in ``CapacitorPlugin.plugins`` so finalize_bridge
246
+ writes Android ``RECORD_AUDIO`` / iOS microphone usage strings.
247
+
248
+ ``directory`` / ``sub_directory`` are reserved for future sandbox writes and
249
+ currently ignored (audio is returned as a ``dataUrl`` on stop).
250
+ """
251
+ args: dict[str, Any] = {}
252
+ if directory is not None:
253
+ args["directory"] = directory
254
+ if sub_directory is not None:
255
+ args["subDirectory"] = sub_directory
256
+ return call_bridge("startRecording", args, callback=callback)
257
+
258
+
259
+ def stop_recording(callback: Any) -> rx.event.EventSpec:
260
+ """Stop recording; callback receives ``{ok, dataUrl, mimeType, msDuration, path, ...}``."""
261
+ return call_bridge("stopRecording", callback=callback)
262
+
263
+
264
+ def play_recording(
265
+ *,
266
+ data_url: str | None = None,
267
+ path: str | None = None,
268
+ callback: Any = None,
269
+ ) -> rx.event.EventSpec:
270
+ """Play the last recording, or an explicit ``data_url`` / filesystem ``path``."""
271
+ args: dict[str, Any] = {}
272
+ if data_url is not None:
273
+ args["dataUrl"] = data_url
274
+ if path is not None:
275
+ args["path"] = path
276
+ return call_bridge("playRecording", args, callback=callback)
277
+
278
+
279
+ def stop_playback(*, callback: Any = None) -> rx.event.EventSpec:
280
+ """Stop in-WebView playback started by :func:`play_recording`."""
281
+ return call_bridge("stopPlayback", callback=callback)
282
+
283
+
284
+ def recording_status(callback: Any) -> rx.event.EventSpec:
285
+ """Return current recorder status (``RECORDING`` / ``PAUSED`` / ``NONE``)."""
286
+ return call_bridge("recordingStatus", callback=callback)
287
+
288
+
289
+ def speak(
290
+ text: str,
291
+ *,
292
+ lang: str = "zh-CN",
293
+ rate: float = 1.0,
294
+ pitch: float = 1.0,
295
+ volume: float = 1.0,
296
+ audio_focus: Literal["pause", "duck", "none"] = "pause",
297
+ callback: Any = None,
298
+ ) -> rx.event.EventSpec:
299
+ """Speak ``text`` with on-device system TTS.
300
+
301
+ Prefers the Capacitor ``TextToSpeech`` native plugin when ``text-to-speech``
302
+ is enabled (recommended on Android WebView). Falls back to Web
303
+ ``speechSynthesis`` in browsers that support it.
304
+
305
+ ``audio_focus`` (Android): ``pause`` requests transient focus so many music
306
+ apps pause; ``duck`` only lowers their volume; ``none`` mixes with others.
307
+ iOS uses TTS ``category=playback``.
308
+ """
309
+ return call_bridge(
310
+ "speak",
311
+ {
312
+ "text": text,
313
+ "lang": lang,
314
+ "rate": rate,
315
+ "pitch": pitch,
316
+ "volume": volume,
317
+ "audioFocus": audio_focus,
318
+ },
319
+ callback=callback,
320
+ )
321
+
322
+
323
+ def stop_speak(*, callback: Any = None) -> rx.event.EventSpec:
324
+ """Stop any in-progress :func:`speak` utterance."""
325
+ return call_bridge("stopSpeak", callback=callback)
326
+
327
+
237
328
  def invoke(
238
329
  plugin: str,
239
330
  method: str,