diff --git a/README.md b/README.md index 875a00c..55a07e5 100644 --- a/README.md +++ b/README.md @@ -1370,6 +1370,21 @@ deliver a test payload to it. Data-only (silent) messages go to the app delegate, which a Kivy app does not own in Python: send the data with a notification instead. +**A tap that launches a closed Kivy app.** iOS delivers that tap before a Kivy +app's Python starts, so `on_open` cannot get it by itself. Add the small +optional +[pyios-firebase-notifications-hook](https://github.com/PySimpleObjC/pyios-firebase-notifications-hook) +Swift package: it keeps the tap, and `set_handlers(on_open=...)` delivers it, +with no code change. `notifications.launch_hook_status()` tells whether it is +in the app. Taps while the app is open or in the background need nothing. + +```toml +[tool.kivy.ios.native.swift_packages.PyiosFirebaseNotificationsHook] +url = "https://github.com/PySimpleObjC/pyios-firebase-notifications-hook.git" +requirement = { from = "0.1.0" } +products = ["PyiosFirebaseNotificationsHook"] +``` + --- ## Performance Monitoring @@ -1758,6 +1773,7 @@ by name (`EMAIL_ALREADY_IN_USE`, `WRONG_PASSWORD`, `REQUIRES_RECENT_LOGIN`, | An Analytics event does not show up | It may take up to a day in reports: use DebugView (`-FIRDebugEnabled`) to see events at once | | Crashlytics shows no crash | Crashlytics does not report while the debugger is attached: launch the app from the Home screen, crash, then launch it again to send | | Performance traces or HTTP metrics do nothing | `trace.active` is `False`: data collection is off (`data_collection_enabled`, or `firebase_performance_collection_enabled` in `Info.plist`) | +| Tapping a notification opens a closed Kivy app, but `on_open` is not called | Add the pyios-firebase-notifications-hook package (see Cloud Messaging); `notifications.launch_hook_status()` is `None` without it | | No FCM token | On a device: the push capability and an APNs key in the console are needed. FCM does not work in the Simulator | | Remote Config values never change | `minimum_fetch_interval` (12 h by default) has not passed, or you fetched but did not `activate` | | A query fails with an index error | Open the link in the error message and create the index | diff --git a/docs/getting-started/configuration.md b/docs/getting-started/configuration.md index a4b2bfb..39f74d2 100644 --- a/docs/getting-started/configuration.md +++ b/docs/getting-started/configuration.md @@ -21,7 +21,7 @@ Every app needs the base: `GoogleService-Info.plist` in the bundle, the | [App Check](../app-check/index.md#app-configuration) | `FirebaseAppCheck` | The App Attest entitlement | | [Analytics](../analytics/index.md#app-configuration) | `FirebaseAnalytics` | | | [Crashlytics](../crashlytics/index.md#app-configuration) | `FirebaseCrashlytics` | The dSYM upload (Release builds make them; kivyforge: `upload-symbols` from the archive) | -| [Cloud Messaging](../messaging/index.md#app-configuration) | `FirebaseMessaging` | The `aps-environment` entitlement, `UIBackgroundModes` | +| [Cloud Messaging](../messaging/index.md#app-configuration) | `FirebaseMessaging` | The `aps-environment` entitlement, `UIBackgroundModes`; in Kivy, the launch hook package (optional) | | [Performance Monitoring](../performance/index.md#app-configuration) | `FirebasePerformance` | | ## Everything together @@ -58,6 +58,12 @@ Every app needs the base: `GoogleService-Info.plist` in the bundle, the requirement = { from = "10.1.0" } products = ["GoogleSignIn"] + # --- Messaging, Kivy: the tap that launches a closed app reaches on_open ----- + [tool.kivy.ios.native.swift_packages.PyiosFirebaseNotificationsHook] + url = "https://github.com/PySimpleObjC/pyios-firebase-notifications-hook.git" + requirement = { from = "0.1.0" } + products = ["PyiosFirebaseNotificationsHook"] + [tool.kivy.ios.native.swift_packages.facebook-ios-sdk] url = "https://github.com/facebook/facebook-ios-sdk.git" requirement = { from = "19.0.1" } @@ -103,7 +109,8 @@ Every app needs the base: `GoogleService-Info.plist` in the bundle, the 1. **File > Add Package Dependencies...**: - `https://github.com/firebase/firebase-ios-sdk.git`: pick the products you use; - `https://github.com/google/GoogleSignIn-iOS`: `GoogleSignIn` (Google Sign-In); - - `https://github.com/facebook/facebook-ios-sdk.git`: `FacebookLogin` (Facebook Login). + - `https://github.com/facebook/facebook-ios-sdk.git`: `FacebookLogin` (Facebook Login); + - `https://github.com/PySimpleObjC/pyios-firebase-notifications-hook.git`: `PyiosFirebaseNotificationsHook` (Kivy: notification taps that launch the app). 2. **Build Settings**: add `-ObjC` to *Other Linker Flags*; set *Debug Information Format* to *DWARF with dSYM File*. 3. Add `GoogleService-Info.plist` (and `RemoteConfigDefaults.plist`) to the app target. 4. **Info**: the URL types (the `REVERSED_CLIENT_ID`, `fb`), the Facebook keys, `UIBackgroundModes` with `remote-notification`, and any optional keys. diff --git a/docs/messaging/index.md b/docs/messaging/index.md index 07acc9f..2eba9c4 100644 --- a/docs/messaging/index.md +++ b/docs/messaging/index.md @@ -79,6 +79,12 @@ them all in one `products`; see [App configuration](../getting-started/configura # optional: no token until you ask; register with the installation ID # FirebaseMessagingAutoInitEnabled = false # FirebaseMessagingInstallationIdEnabled = true + + # Kivy: the tap that launches a closed app reaches on_open (optional) + [tool.kivy.ios.native.swift_packages.PyiosFirebaseNotificationsHook] + url = "https://github.com/PySimpleObjC/pyios-firebase-notifications-hook.git" + requirement = { from = "0.1.0" } + products = ["PyiosFirebaseNotificationsHook"] ``` === "Xcode (kivy-ios, Briefcase)" @@ -88,10 +94,16 @@ them all in one `products`; see [App configuration](../getting-started/configura 3. Add `GoogleService-Info.plist` to the app target. 4. **Signing & Capabilities**: *Push Notifications*, and *Background Modes > Remote notifications*. 5. Optional, in **Info**: `FirebaseMessagingAutoInitEnabled` = `NO`, `FirebaseMessagingInstallationIdEnabled` = `YES`. + 6. Kivy (kivy-ios), optional: add the `https://github.com/PySimpleObjC/pyios-firebase-notifications-hook.git` package (product `PyiosFirebaseNotificationsHook`), so a tap that launches the closed app reaches `on_open` ([Notifications](notifications.md#when-the-app-is-closed)). !!! note Upload an APNs authentication key in the console (**Project settings > Cloud Messaging**). +!!! tip "Kivy: taps that launch the app" + Without the `PyiosFirebaseNotificationsHook` package, a Kivy app still + opens when a notification is tapped while it is closed, but `on_open` does + not get that tap. See [When the app is closed](notifications.md#when-the-app-is-closed). + ## The registration token diff --git a/docs/messaging/notifications.md b/docs/messaging/notifications.md index 85761b9..7eb2df5 100644 --- a/docs/messaging/notifications.md +++ b/docs/messaging/notifications.md @@ -12,8 +12,8 @@ from pyios_firebase.messaging.notifications import AuthorizationOptions, Present ## Set the handlers first -Set them **early**, before `App.run()`: a tap that launched the app is -delivered right after start-up, and is lost if no handler is there yet. +Set them **early**, before `App.run()`. In a Kivy app, also add the +[launch hook](#when-the-app-is-closed) to get the tap that opens a closed app. ```python def on_foreground(notification): @@ -44,6 +44,74 @@ and are not shown by default. The handlers run on the main thread. `set_handlers` makes pyios-firebase the notification center's delegate, replacing any other. +## When the app is closed + +What `on_open` gets depends on whether the app was running when the user +tapped: + +| The app was... | The tap opens the app | `on_open` gets the notification | +|---|---|---| +| Open (in front) | (it is open) | Yes | +| In the background | Yes | Yes | +| **Closed** (not running), BeeWare / Toga | Yes | Expected, with `set_handlers` in `startup()`: Python starts before launch there (not tested yet) | +| **Closed** (not running), **Kivy** | Yes | **Only with the launch hook below** | + +**Why Kivy needs a hook.** When a tap launches the app, iOS delivers it +*during* launch. A Kivy app's Python starts only *after* launch (SDL starts the +interpreter), so no handler exists yet: iOS drops the tap +(`response-not-possible` in the system log). The app opens, but cannot know +which notification was tapped. No Python code can run early enough to catch +it. + +### The launch hook + +[pyios-firebase-notifications-hook](https://github.com/PySimpleObjC/pyios-firebase-notifications-hook) +is a tiny optional Swift package (one Objective-C file). It starts before +Python, sets a notification handler before launch ends, and keeps the tap. +`set_handlers(on_open=...)` then passes it to your `on_open`, as soon as the +app's event loop runs. **You write no new code**: add the package, and keep +calling `set_handlers`. + +=== "kivyforge (pyproject.toml)" + + ```toml title="pyproject.toml" + [tool.kivy.ios.native.swift_packages.PyiosFirebaseNotificationsHook] + url = "https://github.com/PySimpleObjC/pyios-firebase-notifications-hook.git" + requirement = { from = "0.1.0" } + products = ["PyiosFirebaseNotificationsHook"] + ``` + +=== "Xcode (kivy-ios)" + + **File > Add Package Dependencies...**, enter + `https://github.com/PySimpleObjC/pyios-firebase-notifications-hook.git`, and + add the `PyiosFirebaseNotificationsHook` product to the app target. + +```python +from pyios_firebase.messaging import notifications + +notifications.set_handlers(on_open=on_open) # before App.run(), as always +print(notifications.launch_hook_status()) # "ok: SDLUIKitSceneDelegate" +``` + +| `launch_hook_status()` | Means | +|---|---| +| `None` | The hook is not in the app: a tap that launches a Kivy app does not reach `on_open` | +| `"ok: SDLUIKitSceneDelegate"` (or another class) | The hook is keeping launch taps | + +Good to know: + +- The `Notification` is the same as for any other tap: title, body, data, FCM + message ID, identifier and date. +- Without `on_open` yet, the tap stays in the hook until a `set_handlers` call + with one. +- For taps the hook kept, pyios-firebase also tells Firebase Messaging the + notification was opened (for its statistics), once Firebase is configured. +- The hook never replaces a notification handler your app set itself. Toga + apps should not need it (see the table). +- Tested end to end in the iOS Simulator: the app is closed, a notification is + pushed, the banner is tapped, and `on_open` gets its data. + ## Ask permission ```python @@ -110,8 +178,9 @@ Data sent with `data={...}` from the server arrives as keys of !!! warning "Data-only messages" Data-only (silent) messages go to the app delegate's `application:didReceiveRemoteNotification:fetchCompletionHandler:`, - which belongs to Kivy's (SDL) or Toga's native code, not to Python. Send - data **with** a notification, or read it when the user opens the app. + which belongs to the app's native code (SDL's in a Kivy app), not to + Python. Send data **with** a notification, or read it when the user opens + the app. Images in notifications need a *Notification Service Extension*, a separate native target (Swift or Objective-C): not something Python can provide. diff --git a/e2e/ios/pyproject.toml b/e2e/ios/pyproject.toml index 2347e62..cf8b1f4 100644 --- a/e2e/ios/pyproject.toml +++ b/e2e/ios/pyproject.toml @@ -59,6 +59,13 @@ url = "https://github.com/facebook/facebook-ios-sdk.git" requirement = { from = "19.0.1" } products = ["FacebookLogin"] +# Keeps the notification tap that launches the app until Python can take it +# (pyios_firebase.messaging.notifications.set_handlers delivers it to on_open) +[tool.kivy.ios.native.swift_packages.PyiosFirebaseNotificationsHook] +url = "https://github.com/PySimpleObjC/pyios-firebase-notifications-hook.git" +requirement = { from = "0.1.0" } +products = ["PyiosFirebaseNotificationsHook"] + [tool.kivy.ios.xcode.build_settings] OTHER_LDFLAGS = "$(inherited) -ObjC" diff --git a/e2e/ios/src/main.py b/e2e/ios/src/main.py index 6ca425f..1f0ae93 100644 --- a/e2e/ios/src/main.py +++ b/e2e/ios/src/main.py @@ -9,6 +9,9 @@ ``E2E_CRASH_AT_END=1``: crash on purpose after the results (Crashlytics). ``E2E_PHASE=after-crash``: only the Crashlytics checks of that crash, written to ``Documents/pyios-e2e-results-after-crash.json``. +``E2E_PHASE=notification-permission``: ask for full notification permission. +No ``E2E_PHASE`` (a launch from a tapped notification): idle; ``on_open`` +records the tap (notification_open.py). No GoogleService-Info.plist: Firebase is configured in code for the offline ``demo-pyios-firebase`` project, which only the emulator serves. @@ -32,7 +35,9 @@ STORAGE_BUCKET = "demo-pyios-firebase.appspot.com" DATABASE_URL = "https://demo-pyios-firebase-default-rtdb.firebaseio.com" DATABASE_EMULATOR_HOST = os.environ.get("FIREBASE_DATABASE_EMULATOR_HOST", "127.0.0.1:9000") -PHASE = os.environ.get("E2E_PHASE", "main") +# no E2E_PHASE: launched by a tapped notification (iOS passes no environment), +# so do nothing but record the tap (notification_open.py) +PHASE = os.environ.get("E2E_PHASE", "idle") CRASH_AT_END = os.environ.get("E2E_CRASH_AT_END") == "1" RESULTS = os.path.join( os.path.expanduser("~/Documents"), @@ -97,6 +102,16 @@ def build(self): return scroll def on_start(self): + if PHASE == "idle": + self.label.text = "pyios-firebase e2e\nlaunched without E2E_PHASE (a notification tap?)" + print("PYIOS-E2E IDLE", flush=True) + return + if PHASE == "notification-permission": + from notification_open import ask_permission + + self.label.text = "pyios-firebase e2e\nasking for notification permission" + ask_permission() + return try: os.remove(RESULTS) except FileNotFoundError: @@ -205,5 +220,10 @@ def finish(self, report, dumps=None): if __name__ == "__main__": + # before App.run(), at every launch, as an app must: a tap that launched the + # app is delivered right after start-up + from notification_open import install + + install() E2EApp().run() sys.exit(0) diff --git a/e2e/ios/src/messaging_tests.py b/e2e/ios/src/messaging_tests.py index e4dabcc..836aa7f 100644 --- a/e2e/ios/src/messaging_tests.py +++ b/e2e/ios/src/messaging_tests.py @@ -126,7 +126,10 @@ def check() -> None: expect(notification.date is not None, "date") t.passed() - notifications.set_handlers(on_foreground=on_foreground) + # keep recording taps (notification_open.py): set_handlers replaces both + from notification_open import install + + install(on_foreground=on_foreground) payload = { "aps": {"alert": {"title": "Sale", "body": "50% off today"}, "badge": 3}, "gcm.message_id": message_id, diff --git a/e2e/ios/src/notification_open.py b/e2e/ios/src/notification_open.py new file mode 100644 index 0000000..0931daa --- /dev/null +++ b/e2e/ios/src/notification_open.py @@ -0,0 +1,67 @@ +"""Notifications tapped while the app is closed: the app records what ``on_open`` +gets, and ``run_ios_e2e.sh`` checks it. + +A notification tapped while the app is not running launches the app with no +environment variables, so ``install()`` runs at every launch, before +``App.run()``, as a real app's ``set_handlers`` call would. + +The ``notification-permission`` phase asks for full permission (alert, badge, +sound), so that banners show on the home screen; the script taps "Allow". +""" + +from __future__ import annotations + +import json +import os +import time +from typing import Any + +from pyios_firebase.messaging import notifications +from pyios_firebase.messaging.notifications import AuthorizationOptions + +DOCUMENTS = os.path.expanduser("~/Documents") +OPENED = os.path.join(DOCUMENTS, "pyios-e2e-notification-open.json") +PERMISSION = os.path.join(DOCUMENTS, "pyios-e2e-notification-permission.json") + +LAUNCHED_AT = time.time() + + +def _write(path: str, value: dict[str, Any]) -> None: + with open(path + ".tmp", "w") as f: + json.dump(value, f) + os.replace(path + ".tmp", path) # the host polls for this file + + +def record_open(notification: notifications.Notification, action: str) -> None: + """``on_open``: write what the tap delivered, for the script to check.""" + _write(OPENED, { + "title": notification.title, + "body": notification.body, + "data": {k: v for k, v in notification.data.items() if k != "aps"}, + "message_id": notification.message_id, + "action": action, + "seconds_after_launch": round(time.time() - LAUNCHED_AT, 2), + }) + print(f"PYIOS-E2E OPENED {notification.title!r} action={action}", flush=True) + + +def install(**handlers: Any) -> None: + """``set_handlers`` with the recorder as ``on_open``. + + Args: + **handlers: other handlers (for example ``on_foreground``). + """ + notifications.set_handlers(on_open=record_open, **handlers) + + +def ask_permission() -> None: + """The ``notification-permission`` phase: ask for full permission.""" + + def answered(granted: bool, error: Any) -> None: + _write(PERMISSION, {"granted": bool(granted), "error": None if error is None else str(error)}) + print(f"PYIOS-E2E PERMISSION granted={granted}", flush=True) + + notifications.request_permission( + AuthorizationOptions.ALERT | AuthorizationOptions.BADGE | AuthorizationOptions.SOUND, + answered, + ) diff --git a/e2e/run_ios_e2e.sh b/e2e/run_ios_e2e.sh index a540811..5cccdb5 100755 --- a/e2e/run_ios_e2e.sh +++ b/e2e/run_ios_e2e.sh @@ -41,6 +41,8 @@ DATABASE_NAMESPACE="demo-pyios-firebase-default-rtdb" APP_CHECK_DEBUG_TOKEN="00000000-e2e0-4000-8000-000000000000" RESULTS_NAME="pyios-e2e-results.json" AFTER_CRASH_RESULTS_NAME="pyios-e2e-results-after-crash.json" +LAUNCH_TAP_RESULTS_NAME="pyios-e2e-results-launch-tap.json" +OPENED_NAME="pyios-e2e-notification-open.json" PUSH_REQUEST_NAME="pyios-e2e-push.json" # the kivyforge commit the build is known to work with KIVYFORGE="git+https://github.com/ElliotGarbus/kivyforge.git@758dc40e6e7f3c430f06f5f25c98023882926e28" @@ -163,6 +165,16 @@ deliver_push() { DEVICE_UDID="$(device_udid)" [[ -n "$DEVICE_UDID" ]] || die "no simulator named \"$DEVICE\" (xcrun simctl list devices available)" +# Boot the simulator here, with no SIMCTL_CHILD_* variables: a device booted +# while they are set keeps them for EVERY app launch (launchd_bootstrap.plist), +# even the one a notification tap makes. Reboot a device that has them. +BOOTSTRAP="$HOME/Library/Developer/CoreSimulator/Devices/$DEVICE_UDID/data/var/run/launchd_bootstrap.plist" +if [[ -f "$BOOTSTRAP" ]] && plutil -p "$BOOTSTRAP" 2>/dev/null | /usr/bin/grep -q '"E2E_'; then + say "restarting the simulator: it was booted with test variables" + xcrun simctl shutdown "$DEVICE_UDID" >/dev/null 2>&1 || true +fi +env -u SIMCTL_CHILD_E2E_PHASE -u SIMCTL_CHILD_E2E_CRASH_AT_END xcrun simctl boot "$DEVICE_UDID" >/dev/null 2>&1 || true +xcrun simctl bootstatus "$DEVICE_UDID" -b >/dev/null 2>&1 || true # results from an earlier run must not be mistaken for this run's for name in "$RESULTS_NAME" "$AFTER_CRASH_RESULTS_NAME" "$PUSH_REQUEST_NAME"; do if old="$(documents_path "$name")"; then rm -f "$old"; fi @@ -171,7 +183,7 @@ done say "building and launching on $DEVICE ($DEVICE_UDID) — the first build takes a few minutes" # simctl hands SIMCTL_CHILD_* variables to the launched app, without the prefix -SIMCTL_CHILD_FIRAAppCheckDebugToken="$APP_CHECK_DEBUG_TOKEN" SIMCTL_CHILD_E2E_CRASH_AT_END=1 \ +SIMCTL_CHILD_E2E_PHASE=main SIMCTL_CHILD_FIRAAppCheckDebugToken="$APP_CHECK_DEBUG_TOKEN" SIMCTL_CHILD_E2E_CRASH_AT_END=1 \ kivyforge run -p ios --simulator --destination "$DEVICE_UDID" >"$LOGS/app.log" 2>&1 & APP_PID=$! @@ -216,14 +228,107 @@ else >"$LOGS/$AFTER_CRASH_RESULTS_NAME" fi -python3 - "$LOGS/$RESULTS_NAME" "$LOGS/$AFTER_CRASH_RESULTS_NAME" <<'PY' +# ---- 6. a notification tap that launches the closed app -------------------------- +# iOS delivers that tap before a Kivy app's Python starts; the +# pyios-firebase-notifications-hook package keeps it for set_handlers. idb +# taps the banner on the home screen, as a user would. +say "tapping a notification while the app is closed (launch tap)" +kill "$APP_PID" 2>/dev/null || true; wait "$APP_PID" 2>/dev/null || true; APP_PID="" +xcrun simctl terminate "$DEVICE_UDID" "$BUNDLE_ID" >/dev/null 2>&1 || true +launch_tap_result() { # launch_tap_result ok|fail|skip "detail" + python3 - "$LOGS/$LAUNCH_TAP_RESULTS_NAME" "$1" "$2" <<'PY' +import json, sys +path, outcome, detail = sys.argv[1:4] +ok = outcome != "fail" +result = {"name": "test_notification_tap_launches_closed_app", "ok": ok, "seconds": 0, + "detail": ("SKIP: " if outcome == "skip" else "") + detail} +if outcome == "skip": + result["skipped"] = True +json.dump({"passed": int(outcome == "ok"), "failed": int(not ok), "skipped": int(outcome == "skip"), + "seconds": 0, "results": [result]}, open(path, "w")) +PY +} +ui_find() { # ui_find "label": the centre of the first element with this exact label + idb ui describe-all --udid "$DEVICE_UDID" 2>/dev/null | python3 -I -c ' +import json, sys +for e in json.load(sys.stdin): + if (e.get("AXLabel") or "") == sys.argv[1]: + f = e["frame"]; print(round(f["x"] + f["width"] / 2), round(f["y"] + f["height"] / 2)); break' "$1" +} +app_running() { pgrep -f "pyios-firebase-e2e.app/pyios-firebase-e2e" >/dev/null; } +# every step below may fail without stopping the script (set -e): a failure +# here is this test's result, and phases 1-5 still report +idb connect "$DEVICE_UDID" >/dev/null 2>&1 || true +if ! command -v idb >/dev/null; then + launch_tap_result skip "idb is not installed (brew install idb-companion; pipx install fb-idb)" +elif ! idb ui describe-all --udid "$DEVICE_UDID" >/dev/null 2>&1; then + launch_tap_result skip "idb cannot reach the simulator (try: idb kill; idb connect $DEVICE_UDID)" +else + # full notification permission, so the banner shows on the home screen: the + # dialog appears once the app is in the background; already granted, none does + SIMCTL_CHILD_E2E_PHASE=notification-permission xcrun simctl launch "$DEVICE_UDID" "$BUNDLE_ID" >/dev/null 2>&1 || true + sleep 12 + xcrun simctl terminate "$DEVICE_UDID" "$BUNDLE_ID" >/dev/null 2>&1 || true + for _ in $(seq 1 8); do + allow="$(ui_find Allow || true)" + if [[ -n "$allow" ]]; then idb ui tap --udid "$DEVICE_UDID" $allow || true; break; fi + sleep 1 + done + sleep 2 + if opened="$(documents_path "$OPENED_NAME")"; then rm -f "$opened"; fi + tap_id="e2e-launch-tap-$(date +%s)" + printf '{"aps": {"alert": {"title": "Your order shipped", "body": "Tap to see it"}}, "gcm.message_id": "%s", "screen": "orders", "order_id": "42"}' \ + "$tap_id" >"$LOGS/launch-tap.json" + xcrun simctl push "$DEVICE_UDID" "$BUNDLE_ID" "$LOGS/launch-tap.json" >>"$LOGS/push.log" 2>&1 || true + sleep 1 + # the banner's centre (iPhone layout: the top of the screen), until it launches the app + for _ in $(seq 1 10); do + idb ui tap --udid "$DEVICE_UDID" 201 92 >/dev/null 2>&1 || true + sleep 0.6 + app_running && break + done + record="" + for _ in $(seq 1 60); do + if opened="$(documents_path "$OPENED_NAME")" && [[ -f "$opened" ]]; then record="$opened"; break; fi + sleep 1 + done + if [[ -z "$record" ]]; then + if app_running; then + launch_tap_result fail "the tap launched the app, but on_open was not called (is the hook in the app?)" + else + launch_tap_result fail "the banner tap did not launch the app" + fi + elif detail="$(python3 - "$record" "$tap_id" <<'PY' +import json, sys +got = json.load(open(sys.argv[1])) +checks = { + "title": got["title"] == "Your order shipped", + "body": got["body"] == "Tap to see it", + "data": got["data"].get("screen") == "orders" and got["data"].get("order_id") == "42", + "message_id": got["message_id"] == sys.argv[2], + "action": got["action"] == "com.apple.UNNotificationDefaultActionIdentifier", +} +bad = [name for name, ok in checks.items() if not ok] +print(("wrong " + ", ".join(bad) + ": ") if bad else "", json.dumps(got), sep="") +sys.exit(1 if bad else 0) +PY +)"; then + launch_tap_result ok "$detail" + else + launch_tap_result fail "$detail" + fi + xcrun simctl terminate "$DEVICE_UDID" "$BUNDLE_ID" >/dev/null 2>&1 || true +fi + +python3 - "$LOGS/$RESULTS_NAME" "$LOGS/$AFTER_CRASH_RESULTS_NAME" "$LOGS/$LAUNCH_TAP_RESULTS_NAME" <<'PY' import json, sys report = json.load(open(sys.argv[1])) -second = json.load(open(sys.argv[2])) -report["results"] += second["results"] -for key in ("passed", "failed", "skipped"): - report[key] = report.get(key, 0) + second.get(key, 0) -report["seconds"] = round(report["seconds"] + second["seconds"], 2) +for extra in sys.argv[2:]: + second = json.load(open(extra)) + report["results"] += second["results"] + for key in ("passed", "failed", "skipped"): + report[key] = report.get(key, 0) + second.get(key, 0) + report["seconds"] = round(report["seconds"] + second["seconds"], 2) for r in report["results"]: if r.get("skipped"): mark = "\033[33mSKIP\033[0m" diff --git a/src/pyios_firebase/messaging/notifications.py b/src/pyios_firebase/messaging/notifications.py index 8072265..d238e2d 100644 --- a/src/pyios_firebase/messaging/notifications.py +++ b/src/pyios_firebase/messaging/notifications.py @@ -33,12 +33,14 @@ def on_open(notification, action): from __future__ import annotations __all__ = ( + "HOOK_CLASS_NAME", "AuthorizationOptions", "AuthorizationStatus", "Notification", "PresentationOptions", "PyNotificationCenterDelegate", "authorization_status", + "launch_hook_status", "register_for_remote_notifications", "request_permission", "set_handlers", @@ -65,6 +67,10 @@ def on_open(notification, action): to_python, ) +HOOK_CLASS_NAME: Final = "PyiosFirebaseNotificationsHook" +"""The class of the optional launch hook package (pyios-firebase-notifications-hook), +which keeps the tap that launches a Kivy app until ``set_handlers`` runs.""" + DEFAULT_ACTION: Final = "com.apple.UNNotificationDefaultActionIdentifier" """The ``action`` of ``on_open`` when the user tapped the notification itself.""" DISMISS_ACTION: Final = "com.apple.UNNotificationDismissActionIdentifier" @@ -264,6 +270,61 @@ class _Handlers: delegate: ClassVar[ObjCObject | None] = None # the center only holds it weakly +def _hook() -> ObjCObject | None: + try: + return objc_class(HOOK_CLASS_NAME) + except NameError: + return None + + +def launch_hook_status() -> str | None: + """Whether the launch hook package is in the app, and working. + + Returns: + ``None`` when the app does not include pyios-firebase-notifications-hook; + otherwise the hook's status, which starts with ``"ok"`` when it is + keeping launch taps (for example ``"ok: SDLUIKitSceneDelegate"``). + """ + hook = _hook() + return None if hook is None else str(hook.status()) + + +def _on_main_thread(function: Callable[[], None]) -> None: + """Run ``function`` on the main thread's next turn (once the app's event + loop runs), not now.""" + queue: ObjCObject = objc_class("NSOperationQueue").mainQueue + if callable(queue): # a class property: Rubicon may give it as a method + queue = queue() + queue.addOperationWithBlock_(one_shot_block(function)) + + +def _report_open(notification: Notification) -> None: + """Tell Firebase Messaging a notification was opened (its "opened" + statistics), for taps the hook kept: Firebase did not see those.""" + try: + app = objc_class("FIRApp").defaultApp() + messaging = objc_class("FIRMessaging") + except NameError: + return + if app is None: # Messaging before configure() would stop the app + return + from rubicon.objc import ns_from_py + + messaging.messaging().appDidReceiveMessage_(ns_from_py(notification.data)) + + +def _deliver_launch_taps() -> None: + """Pass the taps the launch hook kept to ``on_open``.""" + on_open = _Handlers.on_open + hook = _hook() + if on_open is None or hook is None: + return # without on_open, the taps stay in the hook for a later call + for response in hook.takeResponses(): + notification = Notification.from_native(response.notification) + _report_open(notification) + on_open(notification, str(response.actionIdentifier)) + + def set_handlers( on_foreground: ForegroundHandler | None = None, on_open: OpenHandler | None = None, @@ -271,12 +332,17 @@ def set_handlers( default_presentation: int = PresentationOptions.NONE, ) -> None: """Call Python when a notification arrives with the app open, and when the - user taps one. Call it early (before ``App.run()``): a tap that launched - the app is delivered right after start-up. + user taps one. Call it early (before ``App.run()``). This makes pyios-firebase the notification center's delegate (replacing any other). + A tap that **launches** the app (it was not running) is delivered by iOS + before a Kivy app's Python starts. With the optional + pyios-firebase-notifications-hook package in the app, that tap is kept and + passed to ``on_open`` here, once the app's event loop runs. Without the + hook, a Kivy app does not get it. See ``launch_hook_status``. + Args: on_foreground: gets the ``Notification``; returns the ``PresentationOptions`` to show it with (``None`` or 0: do not show). @@ -290,3 +356,5 @@ def set_handlers( if _Handlers.delegate is None: _Handlers.delegate = PyNotificationCenterDelegate.alloc().init() _center().delegate = _Handlers.delegate + if on_open is not None and _hook() is not None: + _on_main_thread(_deliver_launch_taps) diff --git a/tests/test_messaging.py b/tests/test_messaging.py index e140315..c65cd6e 100644 --- a/tests/test_messaging.py +++ b/tests/test_messaging.py @@ -246,3 +246,67 @@ def test_permission_and_status(monkeypatch, blocks): fire(center.block(), settings) assert got == [(True, None), 2] assert not blocks + + +# ---- the tap that launched the app (pyios-firebase-notifications-hook) ----------- + + +@pytest.fixture +def launch_hook(monkeypatch, handlers): + """A launch hook that kept one tap, and a main thread that runs at once.""" + kept = [ + SimpleNamespace( + notification=fake_notification(), actionIdentifier=DEFAULT_ACTION + ) + ] + + def take(): + taken = list(kept) + kept.clear() + return taken + + hook = SimpleNamespace( + status=lambda: "ok: SDLUIKitSceneDelegate", takeResponses=take + ) + monkeypatch.setattr(notifications, "_hook", lambda: hook) + monkeypatch.setattr(notifications, "_on_main_thread", lambda fn: fn()) + return kept + + +def test_launch_tap_is_delivered_to_on_open(launch_hook, handlers): + opened = [] + notifications.set_handlers(on_open=lambda n, action: opened.append((n, action))) + ((notification, action),) = opened + assert action == DEFAULT_ACTION + assert notification.title == "Sale" and notification.data["screen"] == "shop" + assert notification.identifier == "req-1" # the full Notification, not a copy + assert isinstance(handlers.delegate, PyNotificationCenterDelegate) # as before + notifications.set_handlers(on_open=lambda n, action: opened.append((n, action))) + assert len(opened) == 1 # delivered once + + +def test_launch_tap_waits_for_an_on_open(launch_hook, handlers): + notifications.set_handlers(on_foreground=lambda n: None) # no on_open yet + assert len(launch_hook) == 1 # still kept by the hook + opened = [] + notifications.set_handlers(on_open=lambda n, action: opened.append(action)) + assert opened == [DEFAULT_ACTION] and not launch_hook + + +def test_without_the_hook_nothing_changes(monkeypatch, handlers): + monkeypatch.setattr(notifications, "_hook", lambda: None) + scheduled = [] + monkeypatch.setattr(notifications, "_on_main_thread", scheduled.append) + notifications.set_handlers(on_open=lambda n, action: None) + assert not scheduled + assert isinstance(handlers.delegate, PyNotificationCenterDelegate) + assert notifications.launch_hook_status() is None + + +def test_launch_hook_status(launch_hook): + assert notifications.launch_hook_status() == "ok: SDLUIKitSceneDelegate" + + +def test_no_hook_class_in_this_process(): + # the real lookup: the class is not in the test process + assert notifications._hook() is None