diff --git a/README.md b/README.md index e8b725e..bebac0f 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,11 @@ # alpine-ronin/nativephp-basho -Location for [NativePHP Mobile](https://nativephp.com) v4, driven from Laravel. Basho (場所) means "place". +Location and local notifications for [NativePHP Mobile](https://nativephp.com) v4, driven from Laravel. Basho (場所) means "place". - **One-shot position**: ask for the "when in use" permission if needed, then get one fix (latitude, longitude, accuracy) as an event. +- **Local notifications**: schedule a notification at a given time, cancel it, and open a route of the app when it is tapped, even from a cold start. -Geofencing and local notifications are planned. +Geofencing is planned. > Status: v0.1, experimental. @@ -13,6 +14,7 @@ Geofencing and local notifications are planned. | Feature | iOS | Android | |---|---|---| | `Basho.CurrentPosition` | yes (CoreLocation) | yes (`LocationManager`); the first call without permission shows the system dialog and fails with `permission_requested` | +| `Basho.ScheduleNotification`, `Basho.CancelNotifications` | yes (`UNUserNotificationCenter`) | not yet: scheduling fails with `unsupported` | ## Installation @@ -56,6 +58,23 @@ public function onFailed(string $code, string $message): void {} Callbacks can also be attached to the request: `->positionReceived(fn (PositionReceived $fix) => ...)`, `->positionFailed(...)`, `->permissionDenied(...)`. +### Local notifications + +```php +Basho::notification('note-3') + ->title('Kitchen') + ->body('Buy milk') + ->at(now()->addMinutes(2)) + ->url('/places/3') + ->schedule(); + +Basho::cancelNotifications(['note-3']); +``` + +The first `schedule()` asks for the notification permission. Scheduling again with the same id replaces the notification; cancelling also removes it from the notification centre once delivered. Tapping a notification opens its `url` as a deep link (`Route::native` screens included), also when the tap launches the app. Notifications are shown while the app is in the foreground too. + +On iOS the plugin becomes the `UNUserNotificationCenter` delegate at launch (`ios.init_function`). Another plugin that sets this delegate, such as a push notification plugin, would replace it. + ## Events Every event carries `id`, the request id. @@ -65,6 +84,8 @@ Every event carries `id`, the request id. | `PositionReceived` | `id`, `latitude`, `longitude`, `accuracy` (metres) | | `PositionFailed` | `id`, `code` (`unavailable`, `permission_requested`), `message` | | `PermissionDenied` | `id` | +| `NotificationTapped` | `id`, `url`; dropped when the tap cold-starts the app before PHP is up (the `url` still opens) | +| `NotificationFailed` | `id`, `code` (`permission_denied`, `unavailable`, `unsupported`), `message` | Native errors returned synchronously by the bridge are thrown as `BashoBridgeException`. diff --git a/ci/check-stubs.sh b/ci/check-stubs.sh index 74eb564..cb26a4c 100755 --- a/ci/check-stubs.sh +++ b/ci/check-stubs.sh @@ -24,6 +24,8 @@ expect "$swift/BridgeRouter.swift" "func execute(parameters: [String: Any]) thro expect "$swift/BridgeRouter.swift" "static func success(data: [String: Any] = [:]) -> [String: Any]" expect "$swift/BridgeRouter.swift" "static func error(code: String, message: String, data: [String: Any] = [:]) -> [String: Any]" expect "$swift/NativePHP.swift" "var send: ((_ event: String, _ payload: [String: Any?]) -> Void)?" +expect "$core/resources/xcode/NativePHP/DeepLinkRouter.swift" "func handle(url: URL)" +expect "$core/resources/stubs/ios/PluginBridgeFunctionRegistration.swift.stub" "{{ INIT_FUNCTIONS }}" expect "$kotlin/bridge/BridgeRouter.kt" "fun execute(parameters: Map): Map" expect "$kotlin/bridge/BridgeRouter.kt" "fun success(data: Map = emptyMap()): Map" expect "$kotlin/bridge/BridgeRouter.kt" "fun error(code: String, message: String, data: Map = emptyMap()): Map" diff --git a/ci/ios/Sources/BashoCheck/Stubs/NativePHPStubs.swift b/ci/ios/Sources/BashoCheck/Stubs/NativePHPStubs.swift index 84c2cf8..5e585a0 100644 --- a/ci/ios/Sources/BashoCheck/Stubs/NativePHPStubs.swift +++ b/ci/ios/Sources/BashoCheck/Stubs/NativePHPStubs.swift @@ -1,7 +1,7 @@ import Foundation // Compile-time stand-ins for the NativePHP Mobile v4 host app symbols used by the plugin. -// Signatures mirror nativephp/mobile resources/xcode/NativePHP/Bridge (BridgeRouter.swift, NativePHP.swift). +// Signatures mirror nativephp/mobile resources/xcode/NativePHP (Bridge/BridgeRouter.swift, Bridge/NativePHP.swift, DeepLinkRouter.swift). enum BridgeError: Error { case functionNotFound(String) @@ -31,3 +31,9 @@ final class LaravelBridge { var send: ((_ event: String, _ payload: [String: Any?]) -> Void)? = { _, _ in } } + +final class DeepLinkRouter { + static let shared = DeepLinkRouter() + + func handle(url: URL) {} +} diff --git a/nativephp.json b/nativephp.json index e4ccbc5..9a665de 100644 --- a/nativephp.json +++ b/nativephp.json @@ -6,12 +6,26 @@ "ios": "BashoFunctions.CurrentPosition", "android": "com.alpineronin.nativebasho.BashoFunctions.CurrentPosition", "description": "Ask for location permission if needed, then deliver one position fix as an event" + }, + { + "name": "Basho.ScheduleNotification", + "ios": "BashoFunctions.ScheduleNotification", + "android": "com.alpineronin.nativebasho.BashoFunctions.ScheduleNotification", + "description": "Ask for notification permission if needed, then schedule a local notification at a unix timestamp; tapping it opens its url" + }, + { + "name": "Basho.CancelNotifications", + "ios": "BashoFunctions.CancelNotifications", + "android": "com.alpineronin.nativebasho.BashoFunctions.CancelNotifications", + "description": "Remove scheduled and delivered local notifications by id" } ], "events": [ "AlpineRonin\\NativeBasho\\Events\\PositionReceived", "AlpineRonin\\NativeBasho\\Events\\PositionFailed", - "AlpineRonin\\NativeBasho\\Events\\PermissionDenied" + "AlpineRonin\\NativeBasho\\Events\\PermissionDenied", + "AlpineRonin\\NativeBasho\\Events\\NotificationTapped", + "AlpineRonin\\NativeBasho\\Events\\NotificationFailed" ], "android": { "permissions": [ @@ -28,6 +42,7 @@ "NSLocationWhenInUseUsageDescription": "Votre position est enregistrée avec chaque lieu pour le retrouver." } }, + "init_function": "BSHNotificationCenter.install", "dependencies": { "swift_packages": [], "pods": [] diff --git a/resources/android/BashoFunctions.kt b/resources/android/BashoFunctions.kt index 6947f69..5cf2fc4 100644 --- a/resources/android/BashoFunctions.kt +++ b/resources/android/BashoFunctions.kt @@ -96,4 +96,23 @@ object BashoFunctions { } } } + + class ScheduleNotification(private val activity: FragmentActivity) : BridgeFunction { + override fun execute(parameters: Map): Map { + val id = parameters["id"] as? String ?: UUID.randomUUID().toString() + + dispatch(activity, "NotificationFailed", JSONObject() + .put("id", id) + .put("code", "unsupported") + .put("message", "Local notifications are not implemented on Android yet.")) + + return BridgeResponse.success(mapOf("id" to id)) + } + } + + class CancelNotifications(private val activity: FragmentActivity) : BridgeFunction { + override fun execute(parameters: Map): Map { + return BridgeResponse.success() + } + } } diff --git a/resources/ios/BSHNotificationCenter.swift b/resources/ios/BSHNotificationCenter.swift new file mode 100644 index 0000000..8975275 --- /dev/null +++ b/resources/ios/BSHNotificationCenter.swift @@ -0,0 +1,105 @@ +import Foundation +import UserNotifications + +/// Schedules local notifications and routes their taps. Installed as the +/// notification center delegate at launch (`ios.init_function`), so a tap +/// that cold-starts the app is delivered here too. +final class BSHNotificationCenter: NSObject, UNUserNotificationCenterDelegate { + static let shared = BSHNotificationCenter() + + private static let urlKey = "basho_url" + + static func install() { + UNUserNotificationCenter.current().delegate = shared + } + + func schedule(id: String, title: String, body: String, at: Date, url: String?) { + let center = UNUserNotificationCenter.current() + + center.getNotificationSettings { settings in + switch settings.authorizationStatus { + case .notDetermined: + center.requestAuthorization(options: [.alert, .sound]) { granted, error in + if granted { + self.add(id: id, title: title, body: body, at: at, url: url) + } else { + self.fail(id, "permission_denied", error?.localizedDescription ?? "Notifications are not allowed.") + } + } + + case .denied: + self.fail(id, "permission_denied", "Notifications are not allowed.") + + default: + self.add(id: id, title: title, body: body, at: at, url: url) + } + } + } + + func cancel(_ ids: [String]) { + let center = UNUserNotificationCenter.current() + center.removePendingNotificationRequests(withIdentifiers: ids) + center.removeDeliveredNotifications(withIdentifiers: ids) + } + + func userNotificationCenter( + _ center: UNUserNotificationCenter, + willPresent notification: UNNotification, + withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void + ) { + completionHandler([.banner, .list, .sound]) + } + + func userNotificationCenter( + _ center: UNUserNotificationCenter, + didReceive response: UNNotificationResponse, + withCompletionHandler completionHandler: @escaping () -> Void + ) { + let id = response.notification.request.identifier + let url = response.notification.request.content.userInfo[Self.urlKey] as? String ?? "" + + DispatchQueue.main.async { + BSHEventBus.send("NotificationTapped", ["id": id, "url": url]) + + if let link = Self.deepLink(url) { + DeepLinkRouter.shared.handle(url: link) + } + + completionHandler() + } + } + + /// DeepLinkRouter reads a custom scheme's host as the first path segment, + /// so "/places/3" becomes "basho://places/3" and routes to /places/3. + private static func deepLink(_ route: String) -> URL? { + guard route.hasPrefix("/"), route.count > 1 else { + return nil + } + + return URL(string: "basho:/" + route) + } + + private func add(id: String, title: String, body: String, at: Date, url: String?) { + let content = UNMutableNotificationContent() + content.title = title + content.body = body + content.sound = .default + + if let url { + content.userInfo = [Self.urlKey: url] + } + + let trigger = UNTimeIntervalNotificationTrigger(timeInterval: max(1, at.timeIntervalSinceNow), repeats: false) + let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger) + + UNUserNotificationCenter.current().add(request) { error in + if let error { + self.fail(id, "unavailable", error.localizedDescription) + } + } + } + + private func fail(_ id: String, _ code: String, _ message: String) { + BSHEventBus.send("NotificationFailed", ["id": id, "code": code, "message": message]) + } +} diff --git a/resources/ios/BashoFunctions.swift b/resources/ios/BashoFunctions.swift index da0bd1d..5d54d06 100644 --- a/resources/ios/BashoFunctions.swift +++ b/resources/ios/BashoFunctions.swift @@ -18,6 +18,38 @@ enum BashoFunctions { return BridgeResponse.success(data: ["id": id]) } } + + // MARK: - Basho.ScheduleNotification + + class ScheduleNotification: BridgeFunction { + func execute(parameters: [String: Any]) throws -> [String: Any] { + guard let id = parameters["id"] as? String, let at = (parameters["at"] as? NSNumber)?.doubleValue else { + return BridgeResponse.error(code: "invalid_parameters", message: "id and at are required") + } + + BSHNotificationCenter.shared.schedule( + id: id, + title: parameters["title"] as? String ?? "", + body: parameters["body"] as? String ?? "", + at: Date(timeIntervalSince1970: at), + url: parameters["url"] as? String + ) + + return BridgeResponse.success(data: ["id": id]) + } + } + + // MARK: - Basho.CancelNotifications + + class CancelNotifications: BridgeFunction { + func execute(parameters: [String: Any]) throws -> [String: Any] { + let ids = parameters["ids"] as? [String] ?? [] + + BSHNotificationCenter.shared.cancel(ids) + + return BridgeResponse.success(data: ["ids": ids]) + } + } } enum BSHEventBus { diff --git a/src/Basho.php b/src/Basho.php index 3449036..cc2814f 100644 --- a/src/Basho.php +++ b/src/Basho.php @@ -4,10 +4,32 @@ namespace AlpineRonin\NativeBasho; +use AlpineRonin\NativeBasho\Support\Bridge; + class Basho { public function currentPosition(): PendingPosition { return new PendingPosition; } + + /** + * @param string $id + */ + public function notification(string $id): PendingNotification + { + return new PendingNotification($id); + } + + /** + * @param list $ids + */ + public function cancelNotifications(array $ids): void + { + if ($ids === []) { + return; + } + + Bridge::call('Basho.CancelNotifications', ['ids' => array_values($ids)]); + } } diff --git a/src/Events/NotificationFailed.php b/src/Events/NotificationFailed.php new file mode 100644 index 0000000..abd924b --- /dev/null +++ b/src/Events/NotificationFailed.php @@ -0,0 +1,25 @@ + $ids) * * @see \AlpineRonin\NativeBasho\Basho */ diff --git a/src/PendingNotification.php b/src/PendingNotification.php new file mode 100644 index 0000000..2690df0 --- /dev/null +++ b/src/PendingNotification.php @@ -0,0 +1,99 @@ +title = $title; + + return $this; + } + + /** + * @param string $body + */ + public function body(string $body): self + { + $this->body = $body; + + return $this; + } + + /** + * @param DateTimeInterface $at + */ + public function at(DateTimeInterface $at): self + { + $this->at = $at; + + return $this; + } + + /** + * @param string $url + */ + public function url(string $url): self + { + $this->url = $url; + + return $this; + } + + public function getId(): string + { + return $this->id; + } + + /** + * @return array{id: string, title: string, body: string, at: int, url?: string} + * + * @throws \LogicException + */ + public function toPayload(): array + { + if ($this->at === null) { + throw new \LogicException("Notification [{$this->id}] has no time: call at() before schedule()."); + } + + $payload = [ + 'id' => $this->id, + 'title' => $this->title, + 'body' => $this->body, + 'at' => $this->at->getTimestamp(), + ]; + + if ($this->url !== null) { + $payload['url'] = $this->url; + } + + return $payload; + } + + public function schedule(): void + { + Bridge::call('Basho.ScheduleNotification', $this->toPayload()); + } +} diff --git a/tests/BridgeContractTest.php b/tests/BridgeContractTest.php index df38cca..642016b 100644 --- a/tests/BridgeContractTest.php +++ b/tests/BridgeContractTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +use AlpineRonin\NativeBasho\Events\NotificationFailed; +use AlpineRonin\NativeBasho\Events\NotificationTapped; use AlpineRonin\NativeBasho\Events\PermissionDenied; use AlpineRonin\NativeBasho\Events\PositionFailed; use AlpineRonin\NativeBasho\Events\PositionReceived; @@ -65,3 +67,49 @@ Basho::currentPosition()->get(); })->throws(BashoBridgeException::class, 'unavailable'); + +it('schedules a notification at a unix timestamp', function () { + Basho::notification('note-3') + ->title('Kitchen') + ->body('Buy milk') + ->at(new DateTimeImmutable('2026-11-18T14:30:00+01:00')) + ->url('/places/3') + ->schedule(); + + $this->bridge->assertCalled('Basho.ScheduleNotification', fn (array $p) => $p === [ + 'id' => 'note-3', + 'title' => 'Kitchen', + 'body' => 'Buy milk', + 'at' => 1795008600, + 'url' => '/places/3', + ]); +}); + +it('leaves the url out when none is given', function () { + Basho::notification('n1')->at(new DateTimeImmutable('@1795008600'))->schedule(); + + $this->bridge->assertCalled('Basho.ScheduleNotification', fn (array $p) => ! array_key_exists('url', $p) && $p['at'] === 1795008600); +}); + +it('refuses to schedule a notification without a time', function () { + Basho::notification('n1')->title('Kitchen')->schedule(); +})->throws(LogicException::class, 'n1'); + +it('cancels notifications in one call', function () { + Basho::cancelNotifications(['note-1', 'note-2']); + + $this->bridge->assertCalled('Basho.CancelNotifications', fn (array $p) => $p === ['ids' => ['note-1', 'note-2']]); +}); + +it('does not call the bridge to cancel nothing', function () { + Basho::cancelNotifications([]); + + $this->bridge->assertNotCalled('Basho.CancelNotifications'); +}); + +it('builds notification events from native payloads', function () { + $tap = new NotificationTapped(...['id' => 'note-3', 'url' => '/places/3']); + + expect($tap->url)->toBe('/places/3') + ->and(new NotificationFailed('note-3', 'permission_denied'))->code->toBe('permission_denied'); +}); diff --git a/tests/ManifestTest.php b/tests/ManifestTest.php index d970d34..20b3353 100644 --- a/tests/ManifestTest.php +++ b/tests/ManifestTest.php @@ -49,3 +49,10 @@ expect(array_keys($this->manifest['ios']['info_plist_localizations']['fr'])) ->toBe(array_keys($this->manifest['ios']['info_plist'])); }); + +it('installs the notification delegate at launch', function () { + [$class, $method] = explode('.', $this->manifest['ios']['init_function']); + + expect($this->swift)->toContain("final class {$class}") + ->and($this->swift)->toContain("static func {$method}()"); +});