Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -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.

Expand All @@ -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

Expand Down Expand Up @@ -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.
Expand All @@ -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`.

Expand Down
2 changes: 2 additions & 0 deletions ci/check-stubs.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, Any>): Map<String, Any>"
expect "$kotlin/bridge/BridgeRouter.kt" "fun success(data: Map<String, Any> = emptyMap()): Map<String, Any>"
expect "$kotlin/bridge/BridgeRouter.kt" "fun error(code: String, message: String, data: Map<String, Any> = emptyMap()): Map<String, Any>"
Expand Down
8 changes: 7 additions & 1 deletion ci/ios/Sources/BashoCheck/Stubs/NativePHPStubs.swift
Original file line number Diff line number Diff line change
@@ -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)
Expand Down Expand Up @@ -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) {}
}
17 changes: 16 additions & 1 deletion nativephp.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand All @@ -28,6 +42,7 @@
"NSLocationWhenInUseUsageDescription": "Votre position est enregistrée avec chaque lieu pour le retrouver."
}
},
"init_function": "BSHNotificationCenter.install",
"dependencies": {
"swift_packages": [],
"pods": []
Expand Down
19 changes: 19 additions & 0 deletions resources/android/BashoFunctions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,23 @@ object BashoFunctions {
}
}
}

class ScheduleNotification(private val activity: FragmentActivity) : BridgeFunction {
override fun execute(parameters: Map<String, Any>): Map<String, Any> {
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<String, Any>): Map<String, Any> {
return BridgeResponse.success()
}
}
}
105 changes: 105 additions & 0 deletions resources/ios/BSHNotificationCenter.swift
Original file line number Diff line number Diff line change
@@ -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])
}
}
32 changes: 32 additions & 0 deletions resources/ios/BashoFunctions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
22 changes: 22 additions & 0 deletions src/Basho.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> $ids
*/
public function cancelNotifications(array $ids): void
{
if ($ids === []) {
return;
}

Bridge::call('Basho.CancelNotifications', ['ids' => array_values($ids)]);
}
}
25 changes: 25 additions & 0 deletions src/Events/NotificationFailed.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

declare(strict_types=1);

namespace AlpineRonin\NativeBasho\Events;

use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Native\Mobile\Events\Contracts\DispatchableFromNative;

class NotificationFailed implements DispatchableFromNative
{
use Dispatchable, SerializesModels;

/**
* @param string $id
* @param string $code
* @param string $message
*/
public function __construct(
public string $id,
public string $code = 'unknown',
public string $message = '',
) {}
}
23 changes: 23 additions & 0 deletions src/Events/NotificationTapped.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace AlpineRonin\NativeBasho\Events;

use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Native\Mobile\Events\Contracts\DispatchableFromNative;

class NotificationTapped implements DispatchableFromNative
{
use Dispatchable, SerializesModels;

/**
* @param string $id
* @param string $url
*/
public function __construct(
public string $id,
public string $url = '',
) {}
}
3 changes: 3 additions & 0 deletions src/Facades/Basho.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@

namespace AlpineRonin\NativeBasho\Facades;

use AlpineRonin\NativeBasho\PendingNotification;
use AlpineRonin\NativeBasho\PendingPosition;
use Illuminate\Support\Facades\Facade;

/**
* @method static PendingPosition currentPosition()
* @method static PendingNotification notification(string $id)
* @method static void cancelNotifications(list<string> $ids)
*
* @see \AlpineRonin\NativeBasho\Basho
*/
Expand Down
Loading
Loading