# Plugins

Plugins connect Opal Music to other apps and services. Each one is a small JavaScript package: a `manifest.json` that describes it and a script that reacts to what you play. Plugins can also add panels beside Lyrics and Up Next, drawn by the plugin or by a native program it brings along. Three ship with the app and are off until you turn them on: **Discord activity**, **Last.fm** and **Visualizer**.

## Manage plugins

Open **Settings → Plugins**. Every plugin has a switch, a status line, its settings and its buttons. Settings save when you press Enter or leave the field, and the plugin receives them immediately.

- **Open folder** opens your plugins folder.
- **Reload** rescans the folder and restarts every enabled plugin. Use it after editing a plugin.
- **Import…** copies a plugin folder you pick into your plugins folder. The first time, Opal warns you that plugins run with your access; check **Remember my decision** (on by default) to skip the warning next time.
- **Make a plugin** opens this page.

If a plugin fails to load or throws an error, Opal shows a notification and the error appears in red on its card.

## Built-in plugins

### Discord activity

Shows "Listening to" on your Discord profile with the song, artist, album artwork, a progress bar and a "Listen on Apple Music" button. The Discord desktop app must be running on the same computer.

- **Show while paused** keeps the song on your profile when playback is paused.
- **Show artwork** uses the album artwork as the activity image.
- **Discord application ID**: Discord shows the application's name as the activity title. To use your own name, create an application at [discord.com/developers](https://discord.com/developers/applications) and paste its ID.

### Last.fm

Scrobbles what you play and shows it as now playing on your profile.

1. Turn the plugin on and press **Connect**. Last.fm opens in your browser.
2. Approve Opal Music, come back and press **Connect** again. The status line shows "Connected as" your username.

A song is scrobbled once it is longer than 30 seconds and you have played half of it or 4 minutes, whichever comes first. Seeking doesn't count as listening. Scrobbles that can't be sent (offline, Last.fm down) are queued and retried. **Disconnect** forgets your session. To use your own [Last.fm API account](https://www.last.fm/api/account/create), enter its API key and shared secret.

### Visualizer

Animated scenes that react to the music. Turn it on and press the waveform button beside Lyrics. The **…** menu picks a scene, and **Pop out** moves the visualizer into its own window, for example for a second screen. Close that window or press **Bring back** to return it to the panel. Add scenes to the `visualizers` folder in Opal's data folder.

## Plugins are code

Opal doesn't review or sign plugins. A plugin's script is sandboxed, but its sidecar (see [Panels](#panels)) is an ordinary program with your access to files and the network. Only install plugins from people you trust.

## Make a plugin

1. Press **Open folder** in Settings → Plugins. It opens your plugins folder:
   - Windows: `%LOCALAPPDATA%\OpalMusic\plugins`
   - macOS: `~/Library/Application Support/OpalMusic/plugins`
   - Linux: `~/.local/share/OpalMusic/plugins`
2. Create a folder inside it, for example `hello`. The folder name is the plugin's ID. It can't be `discord`, `lastfm` or `visualizer`.
3. Put `manifest.json` and `main.js` in that folder.
4. Press **Reload**, then turn the plugin on.

A complete plugin that shows the current song on its card:

```json
{
  "api": 1,
  "name": "Hello",
  "description": "Shows the current song on its card.",
  "author": "Your name",
  "entry": "main.js"
}
```

```js
opal.on("track", (track) => {
  opal.status(track ? `Now playing ${track.title} by ${track.artist}` : "Nothing playing");
});
```

## manifest.json

| Field         | Type   |                                                               |
| ------------- | ------ | ------------------------------------------------------------- |
| `api`         | number | `1`, or `2` for `panels`, `sidecar` and `permissions.audio`.  |
| `name`        | string | Shown in Settings.                                            |
| `description` | string | One sentence.                                                 |
| `author`      | string |                                                               |
| `entry`       | string | The script, relative to the plugin folder. Usually `main.js`. |
| `permissions` | object | Optional. What the plugin may reach. See below.               |
| `settings`    | array  | Optional. Fields shown on the plugin's card.                  |
| `actions`     | array  | Optional. Buttons shown on the plugin's card.                 |
| `panels`      | array  | Optional, API 2. Panels beside Lyrics and Up Next.            |
| `sidecar`     | object | Optional, API 2. A native program per OS. See Panels.         |

Unknown fields are an error, so typos are caught.

### Permissions

By default a plugin can't reach anything outside Opal. Ask only for what you need:

```json
"permissions": {
  "http": ["api.example.com"],
  "discord": true
}
```

- `http`: hostnames `opal.http` may call, over HTTPS only. Redirects aren't followed.
- `discord`: allows `opal.discord`.
- `audio` (API 2): streams what's playing to the sidecar.

### Settings

```json
"settings": [
  { "key": "showPaused", "label": "Show while paused", "description": "Optional help text.", "type": "toggle", "default": false },
  { "key": "username", "label": "Username", "type": "text", "default": "" },
  { "key": "token", "label": "Token", "type": "password", "default": "" }
]
```

`type` is `toggle` (a switch, boolean value), `text` or `password` (a text field, string value; password hides the text). `default` defaults to `false` or `""`. Keys must be unique. Values are in `opal.settings`.

### Actions

```json
"actions": [{ "id": "connect", "label": "Connect" }]
```

Each action is a button. Pressing it sends the `action` event with its `id`.

## Panels

API 2 plugins can add panels to the right side of the window. Each gets a button beside Lyrics and Up Next while the plugin is on.

```json
"panels": [{ "id": "main", "title": "Hello", "icon": "icon.svg", "kind": "view" }]
```

- `id`: unique within the plugin, up to 40 characters. `title` is the tooltip and heading.
- `icon`: optional SVG in the plugin folder, up to 32 KiB. Draw with `currentColor` so it follows the theme. Defaults to a puzzle piece.
- `kind`: `view` or `surface`.

A panel's header can have a **…** menu: `opal.panel.setMenu(panelId, [{ id, label, checked }])`. Picking an item sends `panelAction`. An empty list hides the menu.

### View panels

The script describes the panel as a tree, and calls `opal.panel.render(panelId, tree)` again whenever it changes:

```js
opal.panel.render("main", {
  type: "column",
  children: [
    { type: "text", text: "Now playing", bold: true },
    { type: "row", children: [{ type: "image", url: track.artwork, size: 48 }, { type: "text", text: track.title }] },
    { type: "button", id: "love", label: "Love" },
  ],
});
opal.on("panelAction", ({ panel, id }) => opal.log(panel, id));
```

| Node     | Fields                                                |
| -------- | ----------------------------------------------------- |
| `column` | `children`                                            |
| `row`    | `children`                                            |
| `text`   | `text`, optional `bold` and `muted`                   |
| `image`  | `url` (https), optional `size` in pixels (8–512)      |
| `button` | `id`, `label`. Pressing it sends `panelAction`.       |
| `spacer` | Fills the remaining space in a row or column.         |

Trees are limited to 64 KiB and 32 levels.

### Surface panels and sidecars

A surface panel shows frames drawn by the plugin's sidecar, a native program in the plugin folder:

```json
"sidecar": { "linux": "bin/linux/viz", "macos": "bin/macos/viz", "windows": "bin/windows/viz.exe" },
"permissions": { "audio": true }
```

Paths stay inside the plugin folder. Opal starts the sidecar when the panel opens and stops it when the panel closes. **Pop out** restarts it with `--live`; it then opens its own window and Opal brings it back to the panel when it exits. In the panel it runs as `program --embedded WIDTH HEIGHT`. Its working data folder is in the `OPAL_PLUGIN_DATA` environment variable, and what it writes to stderr goes to `plugin-data/<id>.log` in Opal's data folder.

The sidecar talks to Opal over stdin and stdout. Stdin starts with the 8 bytes `OPALPCM3`, then packets that each begin with a 1-byte tag. Numbers are little-endian.

| Tag | Direction | Body                                                                                                                                           |
| --- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `0` | to it     | Audio, with `permissions.audio`: `u64` stereo-frame clock whose top bit is set while playing, 1024 `f32` samples (512 interleaved stereo frames, 44.1 kHz), then a `u64` that changes with each song. |
| `1` | to it     | Resize: `u32` width, `u32` height, in pixels.                                                                                                  |
| `2` | both      | Message: `u32` length, then that much UTF-8 JSON, up to 1 MiB. `opal.sidecar.send(value)` sends one; the sidecar's arrive as the `sidecar` event. |
| `3` | from it   | Frame: `u32` width, `u32` height, then RGBA pixels, up to 8192 a side. Send at most about 60 a second; Opal shows the newest.                  |

The [visualizer's source](https://github.com/bobosneefdev/apple-music-rs/tree/main/apps/desktop/visualizer) is a complete sidecar.

## Events

Register handlers with `opal.on(event, handler)`. A plugin runs from the moment it's turned on, and right after its script runs it receives the current `track` and `playback`.

| Event      | Data                              | When                                                             |
| ---------- | --------------------------------- | ---------------------------------------------------------------- |
| `track`    | track or `null`                   | The song changes. `null` when nothing is loaded.                 |
| `playback` | `{ playing, position, duration }` | Play, pause, seek or song change. Seconds.                       |
| `tick`     | `{ playing, position, duration }` | About once a second while playing.                               |
| `settings` | the new settings                  | The user changes a setting. `opal.settings` is already updated.  |
| `action`   | `{ id }`                          | The user presses one of the plugin's buttons.                    |
| `stop`     | `null`                            | The plugin is turned off, reloaded or Opal quits. Clean up here. |
| `panelOpen` / `panelClose` | `{ panel }`           | One of the plugin's panels opens or closes.                      |
| `panelAction` | `{ panel, id }`                | A view button or a header menu item is pressed.                  |
| `sidecar`  | the message                       | The sidecar sent a message.                                      |

A track:

```json
{
  "id": "i.abc123",
  "catalogId": "1440818839",
  "title": "Song",
  "artist": "Artist",
  "album": "Album",
  "artwork": "https://…/600x600bb.jpg",
  "duration": 215.4,
  "explicit": false,
  "url": "https://music.apple.com/song/1440818839"
}
```

`artwork`, `catalogId` and `url` can be `null`, for example for songs uploaded to your library.

## The opal object

|                                             |                                                                                           |
| ------------------------------------------- | ----------------------------------------------------------------------------------------- |
| `opal.on(event, handler)`                   | Listen for an event. Several handlers per event are fine.                                 |
| `opal.settings`                             | The current settings, by key.                                                             |
| `opal.status(text)`                         | Set the status line on the plugin's card. `""` clears it.                                 |
| `opal.log(...values)`                       | Write to Opal's log. `console.log` does the same.                                         |
| `opal.http(request)`                        | Make an HTTPS request. See below.                                                         |
| `opal.discord.setActivity(appId, activity)` | Set your Discord activity.                                                                |
| `opal.discord.clearActivity(appId)`         | Clear it.                                                                                 |
| `opal.openUrl(url)`                         | Open an `http` or `https` URL in the browser.                                             |
| `opal.storage.get(key)`                     | Read a value saved by `set`.                                                              |
| `opal.storage.set(key, value)`              | Save any JSON value, kept across restarts. `undefined` deletes the key. 256 KiB in total. |
| `opal.md5(text)`                            | MD5 as hex, for APIs that sign requests with it.                                          |
| `opal.panel.render(panelId, tree)`          | Show a view panel's content. See [Panels](#panels).                                       |
| `opal.panel.setMenu(panelId, items)`        | Set a panel's header menu.                                                                |
| `opal.sidecar.send(value)`                  | Send a JSON message to the running sidecar. Dropped when none is running.                 |

### opal.http

```js
const response = opal.http({
  url: "https://api.example.com/v1/items",
  method: "POST", // default GET
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ hello: "world" }),
});
response.status; // 200
response.headers; // lowercase names
response.body; // text
response.json(); // parsed body
```

Calls are synchronous and time out after 15 seconds. Error statuses are returned, not thrown; network errors and hosts missing from `permissions.http` throw. Responses are limited to 4 MiB.

### opal.discord

`appId` is a Discord application ID. `activity` is a Discord [activity object](https://discord.com/developers/docs/events/gateway-events#activity-object): `type` (2 is Listening), `details`, `state`, `timestamps`, `assets` (`large_image` can be a URL) and up to two `buttons`. It throws if Discord isn't running or rejects the activity.

## Limits

Plugins run in their own sandbox (QuickJS), each on its own thread, so a slow plugin can't freeze Opal or other plugins.

- Plain JavaScript: no DOM, Node.js, `fetch`, timers or modules. Promises work and settle before the next event.
- Each event handler, and the script's first run, has 1 second of CPU time. Waiting on `opal.http` doesn't count.
- 32 MiB of memory per plugin.
- The script can be up to 512 KiB.

An error inside a handler is reported and the plugin keeps running. An error while loading stops it until you press Reload.

## Tips

- Show what's happening with `opal.status`, especially when something needs the user's attention.
- Wrap network calls in `try`/`catch` and turn errors into a status message.
- Clean up in `stop`, for example clear a Discord activity.
