# Laravel Rust

Use the ActivitySmith Laravel Rust SDK to send Push Notifications and Live Activities from Laravel notifications, jobs, and handlers.

Send Push Notifications and Live Activities to your iPhone from [Laravel Rust](https://laravel.com/rust). Use them as channels in your Laravel notifications, next to mail and Slack, or call the whole ActivitySmith API from handlers and jobs.

ActivitySmith sends to the devices paired to your own ActivitySmith account, so use it to tell you and your team what happens in your application. It doesn't reach your application's users.

![Push Notification example for a new subscription event](https://cdn.activitysmith.com/features/new-subscription-push-notification.png)

## Installation

1. Add the crate to your application:

   ```bash
   cargo add activitysmith-laravel
   ```

2. [Create an API key](https://activitysmith.com/app/keys) and add it to `.env`:

   ```ini
   ACTIVITYSMITH_API_KEY=your-api-key
   ```

3. Register the service provider in `src/app.rs`:

   ```rust
   use activitysmith_laravel::ActivitySmithServiceProvider;
   use laravel::Application;
   use laravel::foundation::ApplicationBuilder;

   pub fn configure() -> ApplicationBuilder {
       Application::configure()
           // Your migrations, routes, and middleware...
           .with_providers(|providers| {
               providers.add(ActivitySmithServiceProvider);
           })
   }
   ```

## Push Notifications

1. Add a method marked `#[via(PushNotificationChannel)]` to a notification, and return a `PushNotification`.
2. Say who receives it. `Recipients::everyone()` sends to every device in your ActivitySmith account. `Recipients::channels` sends to some of its [Channels](/docs/sdks/rust#channels). Return `None` to send nothing.
3. Send or queue the notification.

```rust
use activitysmith_laravel::{PushNotification, PushNotificationChannel, Recipients};
use laravel::notification::{self, Receives};

pub struct SubscriptionStarted {
    pub plan: String,
    pub amount: u32,
}

#[laravel::notification]
impl SubscriptionStarted {
    #[via(PushNotificationChannel)]
    fn push_notification(&self, _team: &Team) -> PushNotification {
        PushNotification::new("New subscription 💸")
            .message(format!("{} plan, ${}/month", self.plan, self.amount))
            .sound("coin")
            .metadata("amount", self.amount)
    }
}

pub struct Team {
    pub activitysmith_channel: Option<String>,
}

impl Receives<PushNotificationChannel> for Team {
    fn route(&self) -> Option<Recipients> {
        Some(match &self.activitysmith_channel {
            Some(channel) => Recipients::channels([channel]),
            None => Recipients::everyone(),
        })
    }
}

pub async fn notify(team: &Team) -> laravel::Result<()> {
    let notification = SubscriptionStarted {
        plan: "Pro".to_owned(),
        amount: 29,
    };
    notification::to(team).queue(notification).await?;

    Ok(())
}
```

The queue tries again after a rate limit or an outage. It doesn't when ActivitySmith refuses the request, for example because no device is paired. After a timeout, a second try can send the same Push Notification twice.

## Live Activities

![Progress Live Activity showing percentage completion](https://cdn.activitysmith.com/features/progress-live-activity.png)

Live Activities stay on the Lock Screen and change as the work moves on. Inject the client to update one from a handler or a job. The first call with a stream key starts it, and later calls update it:

```rust
use activitysmith_laravel::{ActivitySmith, ContentState};
use laravel::container::Inject;

pub async fn import(activitysmith: Inject<ActivitySmith>) -> laravel::Result<()> {
    for percentage in [0, 50, 100] {
        // Import some customers here...

        activitysmith
            .live_activities
            .stream(
                "customer-import",
                ContentState::progress("Customer Import", percentage),
            )
            .await?;
    }
    activitysmith
        .live_activities
        .end_stream("customer-import")
        .await?;

    Ok(())
}
```

Outside handlers, get the client with `activitysmith_laravel::client().await?`.

A notification can also update a Live Activity, through `LiveActivityChannel`:

```rust
use activitysmith_laravel::{
    ContentState, LiveActivityChannel, LiveActivityMessage, Recipients,
};
use laravel::notification::Receives;

pub struct BackupStepFinished {
    pub step: u32,
}

#[laravel::notification]
impl BackupStepFinished {
    #[via(LiveActivityChannel)]
    fn live_activity(&self, _team: &Team) -> LiveActivityMessage {
        LiveActivityMessage::stream(
            "nightly-backup",
            ContentState::segmented_progress("Nightly Backup", self.step, 3),
        )
    }
}

pub struct Team;

impl Receives<LiveActivityChannel> for Team {
    fn route(&self) -> Option<Recipients> {
        Some(Recipients::everyone())
    }
}
```

Queue workers can run jobs out of order. When updates follow each other quickly, use `send` instead of `queue`.

## Lock Screen Widgets

![Lock screen widgets](https://cdn.activitysmith.com/features/lock-screen-widgets.png)

Send a value to a metric key and see it in a widget on your Lock Screen. The first value creates the metric:

```rust
use activitysmith_laravel::ActivitySmith;
use laravel::container::Inject;

pub async fn report(activitysmith: Inject<ActivitySmith>) -> laravel::Result<()> {
    activitysmith.metrics.update("mrr", 12450).await?;

    Ok(())
}
```

## App Icon Badge

![ActivitySmith app icon with an App Icon Badge](https://cdn.activitysmith.com/features/badge-count.png)

Show a number on your ActivitySmith app icon. Pass `0` to clear it:

```rust
use activitysmith_laravel::ActivitySmith;
use laravel::container::Inject;

pub async fn badge(activitysmith: Inject<ActivitySmith>) -> laravel::Result<()> {
    activitysmith.badge_count(8333).await?;

    Ok(())
}
```

## More of the API

The injected client is the [ActivitySmith Rust SDK](/docs/sdks/rust). Its docs show every option, such as icons, buttons, sounds, and the other Live Activity types. Import its types from `activitysmith_laravel::activitysmith`.

## Testing

Use `notification::fake()` to check what your code sends:

```rust
use activitysmith_laravel::PushNotificationChannel;
use laravel::notification;
use laravel::testing::prelude::*;

#[laravel::test]
async fn a_new_subscription_notifies_the_team(_app: Application) -> laravel::Result<()> {
    let team = Team { activitysmith_channel: None };
    let notifications = notification::fake();

    notify(&team).await?;

    notifications.assert_sent_to_where::<SubscriptionStarted>(&team, |sent| {
        sent.message::<PushNotificationChannel>()
            .is_some_and(|message| message.title == "New subscription 💸")
    });

    Ok(())
}
```

Requests go through Laravel's HTTP client, so `client::fake()` intercepts them too.

## Configuration

| Variable | Description | Default |
| --- | --- | --- |
| `ACTIVITYSMITH_API_KEY` | Your API key. Without it, the application starts and sending fails. | None |
| `ACTIVITYSMITH_TIMEOUT` | How long one request may take, in seconds. | `30` |

## Additional Resources

### [Crates.io Package](https://crates.io/crates/activitysmith-laravel)

Install the ActivitySmith Laravel Rust SDK from crates.io

### [Source Code](https://github.com/ActivitySmithHQ/activitysmith-rust/tree/main/activitysmith-laravel)

View the Laravel Rust SDK source on GitHub
