# Manage the Apps on a Device

The Device Management Kit ships device actions to list, install and update the applications of a connected device.
Every one of them first brings the device back to the dashboard, and is executed like any other device action: with
`executeDeviceAction()`, which returns a `Flow<DeviceActionResult<T>>`.

| Device Action                               | Result                      | Uses the Manager API | Needs the secure channel |
| ------------------------------------------- | --------------------------- | -------------------- | ------------------------ |
| `ListAppsDeviceAction`                      | `List<InstalledApp>`        | No                   | No                       |
| `ListAppsWithMetadataDeviceAction`          | `List<AppMetadata?>`        | Yes                  | No                       |
| `ListInstalledAppsDeviceAction`             | `ListInstalledAppsResult`   | Yes                  | Yes                      |
| `ListInstalledAppsWithMetadataDeviceAction` | `List<AppMetadata?>`        | Yes                  | Yes                      |
| `InstallAppDeviceAction`                    | `Unit`                      | Yes                  | Yes                      |
| `InstallOrUpdateAppsDeviceAction`           | `InstallOrUpdateAppsResult` | Yes                  | Yes                      |
| `GetDeviceMetadataDeviceAction`             | `GetDeviceMetadataResult`   | Yes                  | Yes                      |

All the device actions of this page live under `com.ledger.devicemanagement.api.deviceaction`. From Swift, they are
exported by `LedgerDeviceManagementKit`.

## List the installed applications

`ListAppsDeviceAction` lists the applications installed on the device as `InstalledApp` (name, size in blocks, code hash
and full hash). The user must allow the listing on the device: while waiting, the action emits
`ListAppsUserInteraction.AllowListApps`. If the user refuses, the result is a failure with
`ListAppsCommandFailureReason.UserConsentRejected`.

**Kotlin:**

```kotlin
import com.ledger.devicemanagement.api.deviceaction.DeviceActionResult
import com.ledger.devicemanagement.api.deviceaction.listapps.ListAppsDeviceAction
import com.ledger.devicemanagement.api.deviceaction.listapps.ListAppsUserInteraction

dmk.executeDeviceAction(deviceUid, ListAppsDeviceAction()).collect { result ->
    when (result) {
        is DeviceActionResult.IntermediateValue -> {
            if (result.userRequirement is ListAppsUserInteraction.AllowListApps) {
                println("Ask the user to allow the listing on the device")
            }
        }
        is DeviceActionResult.Success -> result.value.forEach { app ->
            println("${app.appName}: ${app.appSizeInBlocks} blocks")
        }
        is DeviceActionResult.Failure -> println("Listing failed: ${result.reason}")
    }
}
```

**Swift:**

```swift
import LedgerDeviceManagementKit

for await result in dmk.executeDeviceAction(
    deviceUid: deviceUid,
    deviceAction: ListAppsDeviceAction()
) {
    switch onEnum(of: result) {
    case .intermediateValue(let intermediate):
        if intermediate.userRequirement == ListAppsUserInteraction.AllowListApps() {
            // Ask the user to allow the listing on the device
        }
    case .success(let success):
        let apps = success.value as! [InstalledApp]
        apps.forEach { print("\($0.appName): \($0.appSizeInBlocks) blocks") }
    case .failure(let failure):
        print("Listing failed: \(failure.reason)")
    }
}
```

`ListAppsCommand` is public too, to request the list page by page.

## Add metadata to the list

`ListAppsWithMetadataDeviceAction` lists the installed applications like `ListAppsDeviceAction`, then fetches their
`AppMetadata` (name, version, icon, author, size, type...) from the Manager API. The result has one entry per installed
application, in the same order, or `null` when the Manager API does not know the application.

```kotlin
dmk.executeDeviceAction(deviceUid, ListAppsWithMetadataDeviceAction()).collect { result ->
    when (result) {
        is DeviceActionResult.Success -> result.value.forEach { metadata ->
            println(metadata?.versionDisplayName ?: "unknown application")
        }
        is DeviceActionResult.Failure -> println("Failed: ${result.reason}")
        is DeviceActionResult.IntermediateValue -> Unit // AllowListApps, see above
    }
}
```

```swift
for await result in dmk.executeDeviceAction(
    deviceUid: deviceUid,
    deviceAction: ListAppsWithMetadataDeviceAction()
) {
    if case .success(let success) = onEnum(of: result) {
        let metadata = success.value as! [AppMetadata?]
        metadata.forEach { print($0?.versionDisplayName ?? "unknown application") }
    }
}
```

The failures are the ones of the listing, plus `ListAppsWithMetadataFailureReason.ManagerApiFailed`, which tells the
Manager API request and its cause.

## List through the secure channel

`ListInstalledAppsDeviceAction` lists the installed applications through the secure channel, as `InstalledAppEntry`
(flags, hash, code data hash and name). It resolves the device and firmware versions with the Manager API, then
retrieves the list from the Ledger backend. `ListInstalledAppsWithMetadataDeviceAction` does the same, leaves the
language packages out, and returns the `AppMetadata` of each application, `null` when the Manager API does not know it.

```kotlin
dmk.executeDeviceAction(deviceUid, ListInstalledAppsDeviceAction()).collect { result ->
    when (result) {
        is DeviceActionResult.Success -> result.value.installedApps.forEach { println(it.name) }
        is DeviceActionResult.Failure -> println("Failed: ${result.reason}")
        is DeviceActionResult.IntermediateValue -> Unit
    }
}
```

```swift
for await result in dmk.executeDeviceAction(
    deviceUid: deviceUid,
    deviceAction: ListInstalledAppsDeviceAction()
) {
    if case .success(let success) = onEnum(of: result) {
        let list = success.value as! ListInstalledAppsResult
        list.installedApps.forEach { print($0.name) }
    }
}
```

The failures are reported as `ListInstalledAppsFailureReason`: `DeviceVersionNotFound`, `FirmwareVersionNotFound`,
`ManagerApiFailed(request, cause)`, `SecureChannelFailed(cause)` and `InvalidResult`.

> **Note:** `DeviceVersionNotFound` and `FirmwareVersionNotFound` are raised only when the
> Manager API does not know the version. A request that fails because of the
> network, an unexpected HTTP status or an unreadable response is
> `ManagerApiFailed`. `SecureChannelFailed` carries a `SecureChannelFailureCause`:
> `RefusedByUser`, `ConnectionFailed`, `ServerError` or `UnexpectedStatusWord`.

## Install an application

`InstallAppDeviceAction` installs an application by name. It does nothing when the application is already installed,
checks that its parent application is installed, streams the installation, and verifies it by listing the applications
again. The progress is emitted as `InstallAppProgress` intermediate values.

```kotlin
dmk.executeDeviceAction(deviceUid, InstallAppDeviceAction(appName = "Ethereum")).collect { result ->
    when (result) {
        is DeviceActionResult.IntermediateValue -> {
            val progress = result.value as? InstallAppProgress
            println("Installing: ${progress?.progress}")
        }
        is DeviceActionResult.Success -> println("Installed")
        is DeviceActionResult.Failure -> println("Install failed: ${result.reason}")
    }
}
```

```swift
for await result in dmk.executeDeviceAction(
    deviceUid: deviceUid,
    deviceAction: InstallAppDeviceAction(appName: "Ethereum")
) {
    switch onEnum(of: result) {
    case .intermediateValue(let intermediate):
        if let progress = intermediate.value as AnyObject as? InstallAppProgress {
            print("Installing: \(progress.progress)")
        }
    case .success:
        print("Installed")
    case .failure(let failure):
        print("Install failed: \(failure.reason)")
    }
}
```

Failures are reported as `InstallAppFailureReason`: `AppNotFound`, `DependencyNotInstalled`,
`ManagerApiFailed(request, cause)`, `DeviceVersionNotFound`, `FirmwareVersionNotFound`, `AppAlreadyInstalled`,
`OutOfMemory`, `SecureChannelFailed(cause)`, `InstallNotVerified` and `VerificationFailed(cause)`.

## Install or update several applications

`InstallOrUpdateAppsDeviceAction` makes the device satisfy a list of `ApplicationDependency`, each with optional
`ApplicationConstraint` minimum versions. It plans the installation (dependencies first), checks the device memory, then
installs each application. Its intermediate values are `InstallOrUpdateAppsProgress` (the install plan, the application
being installed and its progress). The result lists the `successfullyInstalled`, `alreadyInstalled` and
`missingApplications` names. With `allowMissingApplication = true`, an application the catalog does not know is
reported as missing instead of failing the action.

```kotlin
val action = InstallOrUpdateAppsDeviceAction(
    applications = listOf(
        ApplicationDependency(
            name = "Ethereum",
            constraints = listOf(
                ApplicationConstraint(minVersion = ApplicationConstraint.MinVersion.Latest),
            ),
        ),
        ApplicationDependency(
            name = "Solana",
            constraints = listOf(
                ApplicationConstraint(minVersion = ApplicationConstraint.MinVersion.Version("1.16.0")),
            ),
        ),
    ),
    allowMissingApplication = false,
)

dmk.executeDeviceAction(deviceUid, action).collect { result ->
    when (result) {
        is DeviceActionResult.IntermediateValue -> println("Progress: ${result.value}")
        is DeviceActionResult.Success -> println("Installed: ${result.value.successfullyInstalled}")
        is DeviceActionResult.Failure -> println("Failed: ${result.reason}") // InstallOrUpdateAppsFailureReason
    }
}
```

```swift
let action = InstallOrUpdateAppsDeviceAction(
    applications: [
        ApplicationDependency(
            name: "Ethereum",
            constraints: [
                ApplicationConstraint(
                    minVersion: ApplicationConstraint.MinVersionLatest(),
                    applicableModels: nil,
                    exemptModels: nil
                )
            ]
        ),
    ],
    allowMissingApplication: false
)

for await result in dmk.executeDeviceAction(deviceUid: deviceUid, deviceAction: action) {
    switch onEnum(of: result) {
    case .intermediateValue(let intermediate):
        print("Progress: \(String(describing: intermediate.value))")
    case .success(let success):
        let installed = success.value as! InstallOrUpdateAppsResult
        print("Installed: \(installed.successfullyInstalled)")
    case .failure(let failure):
        print("Failed: \(failure.reason)")
    }
}
```

## Read the device metadata

`GetDeviceMetadataDeviceAction` reads the firmware, the installed applications and language packages and the custom lock
screen picture of the device, resolves them with the Manager API, and returns them with the available application
updates and the catalog of applications and languages.

```kotlin
dmk.executeDeviceAction(deviceUid, GetDeviceMetadataDeviceAction()).collect { result ->
    if (result is DeviceActionResult.Success) {
        val metadata: GetDeviceMetadataResult = result.value
        println("Firmware: ${metadata.firmwareVersion}")
        println("Updates available for: ${metadata.applicationsUpdates.map { it.versionDisplayName }}")
    }
}
```

```swift
for await result in dmk.executeDeviceAction(
    deviceUid: deviceUid,
    deviceAction: GetDeviceMetadataDeviceAction()
) {
    if case .success(let success) = onEnum(of: result) {
        let metadata = success.value as! GetDeviceMetadataResult
        print("Firmware: \(metadata.firmwareVersion)")
        print("Updates available for: \(metadata.applicationsUpdates.map { $0.versionDisplayName })")
    }
}
```
