Metadata-Version: 2.3
Name: njord-player-remote
Version: 3.0.0rc1
Summary: Control Njord Player 3 from Python through its local scripting interface
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Typing :: Typed
Requires-Python: >=3.11
Project-URL: Homepage, https://www.sailnjord.com/
Project-URL: Njord Player 3, https://app.sailnjord.com/help/player/v3.html
Description-Content-Type: text/markdown

# njord-player-remote

Control [Njord Player 3](https://app.sailnjord.com/help/player/v3.html) from a
Python script on the same computer. A script can:

- read and move the playhead;
- play and pause;
- choose which boats are shown;
- open a document;
- follow the playhead as it moves.

```python
from njord_player_remote import Player

with Player.connect() as p:
    p.seek_by(-30)          # back 30 seconds
    p.play()
    print(p.get_status())
```

- Pure Python, no dependencies, Python 3.11 or later.
- macOS and Windows, wherever Njord Player 3 runs.
- Synchronous (`Player`) and asyncio (`AsyncPlayer`) interfaces.

## Installation

```sh
pip install njord-player-remote
```

While only release candidates are published, add `--pre`:
`pip install --pre njord-player-remote`. A release candidate needs a Njord
Player 3 build that includes scripting.

The package's version follows Njord Player's: `3.x` talks to Njord Player 3.
The minor version moves with the scripting features the player adds. A patch
release is a fix to the client alone. Release candidates (`3.0.0rc1`)
come before a release.

## How it works

Njord Player 3 always listens for scripts while it runs, and there is
nothing to switch on. It listens on a Unix domain socket on macOS and a named
pipe on Windows. It accepts connections only from the user running it, so a
script must run as the same user, on the same computer. Before
`Player.connect()` sends anything, it checks that the endpoint, and the
process serving it, belong to that user.

Calls that change something (seeking, play and pause, the boat selection,
opening a document) are carried out on the player's main thread, so they
take effect exactly as the same action in the app would. Calls that only
read (`get_status()`, `get_playhead()`) are answered from the state the
player last showed, without waiting for the main thread, so they answer
even while a dialog is open.

If the player is not running, `Player.connect()` raises
`PlayerNotRunningError`:

```python
from njord_player_remote import Player, PlayerNotRunningError

try:
    p = Player.connect()
except PlayerNotRunningError:
    raise SystemExit("Start Njord Player 3 first")

with p:
    print(p.server.version)   # the player's version
```

A `Player` is one connection. Use it as a context manager, or call
`close()`. One `Player` may be shared between threads; their calls are made
one at a time.

## The document and the playhead

All times are UTC:

- `Playhead.t` is epoch seconds;
- `Playhead.time` is the same instant as an aware `datetime`;
- `Playhead.iso` is the same instant as an ISO-8601 string, for display.

```python
from njord_player_remote import Player

with Player.connect() as p:
    s = p.get_status()
    if s.document is None:
        print("no document open")
    else:
        print(s.document.title, s.document.path)   # "race.sail3", its full path
        print(s.extent.start_time, "to", s.extent.end_time)
        print(s.playhead.time, "playing" if s.playing else "paused", s.rate)

        ph = p.get_playhead()        # just the playhead and playing/paused
        print(ph.playhead.iso, ph.playing)
```

`get_status()` always answers:

- `document` is `None` when no document is open: on macOS after the last
  window has been closed, while another document is being opened (the old
  one is closed first), and after an open whose load started and then
  failed. An open refused at once (a missing file, unsaved changes) leaves
  the open document as it was.
- `loading` is `True` while a document is being opened.

`get_playhead()`, `seek()`, `seek_by()`, `play()`, `pause()`,
`list_boats()` and `select_boats()` need an open document. Without one they
raise `NoDocumentError`, or `DocumentLoadingError` while one is being
opened. `open_document()` and the playhead updates work with no document
open.

`document.id` changes whenever a different document is installed: an open,
File ▸ New Document, or a reload after the file changed on disk. A script
can use it to tell that the document changed under it.

The playhead belongs to the document, not to a window: with several windows
open, they all show the same time.

## Seeking

`seek()` moves the playhead to an absolute time, and `seek_by()` moves it by
a number of seconds, forward or back. Both return where the playhead landed.
A target outside the document's time span is clamped to it, and `clamped`
says so. Seeking does not start or stop playback.

```python
from datetime import datetime, timezone

from njord_player_remote import Player

with Player.connect() as p:
    r = p.seek(datetime(2018, 9, 21, 13, 40, tzinfo=timezone.utc))
    print(r.playhead.time, r.clamped)

    p.seek("2018-09-21T13:40:00Z")   # an ISO-8601 UTC string, ending in Z
    p.seek(1537537200)               # epoch seconds: the same instant
    p.seek_by(-10.5)                 # 10.5 s back from wherever it is now
```

A `datetime` must carry a time zone. A naive one raises `TypeError`, since
reading local time as UTC would land hours off without an error. Attach the
zone the race was sailed in first:

```python
from datetime import datetime, timedelta, timezone

from njord_player_remote import Player

cest = timezone(timedelta(hours=2))
with Player.connect() as p:
    p.seek(datetime(2018, 9, 21, 15, 40, tzinfo=cest))   # 13:40 UTC
```

## Playing and pausing

```python
from njord_player_remote import Player

with Player.connect() as p:
    p.play()
    state = p.pause()
    print(state.playhead.time, state.playing)   # where it paused, False
```

Both may be called in any state. For example, `play()` while already
playing is not an error.

## Boats

`list_boats()` returns the document's boats and the current selection, with
the primary boat first. `select_boats()` replaces the selection, and the
first key becomes the primary boat.

```python
from njord_player_remote import Player

with Player.connect() as p:
    boats = p.list_boats()
    for b in boats.boats:
        print(b.key, b.name, b.color, b.length)
    print("selected:", boats.selected)

    p.select_boats(["B2", "B1"])     # B2 becomes the primary boat
```

`b.color` is the colour stored in the document (`None` if it has none), not
necessarily the colour the player draws; `b.length` is in metres; `b.main`
marks the document's main boat, which need not be the selected primary boat.

The first window always shows this selection, and every window shows it
while **Link boat selection across windows** is on. A secondary window with
a selection of its own keeps it.

`select_boats()` raises `InvalidParamsError`, and changes nothing, in three
cases. `e.reason` says which:

- `"empty_selection"`: the list is empty;
- `"duplicate_boats"`: a key is repeated;
- `"unknown_boats"`: the document has no boat for a key. `e.data["unknown"]`
  lists those keys.

## Opening a document

```python
from njord_player_remote import Player, UnsavedChangesError, OpenFailedError

with Player.connect() as p:
    try:
        s = p.open_document("/Users/me/Races/day2.sail3")
    except UnsavedChangesError:
        print("save or discard the open document first")
    except OpenFailedError as e:
        print("could not open it:", e.loader_message)
    else:
        print("opened", s.document.title, "at", s.playhead.time)
```

`open_document()` replaces the open document, as File ▸ Open does:

- It returns once the new document has finished loading, which can take a
  minute for a large one.
- A relative path is taken against the script's working directory.
- The player does not bring a window to the front for a scripted open.
- The document goes onto File ▸ Open Recent as usual.

It can raise:

- `UnsavedChangesError`: the open document has unsaved changes. Nothing was
  changed.
- `OpenFailedError`: the file does not exist, or Njord Player cannot read it.
  In the second case the previous document is already closed.
- `OpenCancelledError`: something else replaced the open first, such as
  File ▸ Open in the app.
- `OpenTimeoutError`: the load took longer than `timeout`, which is 300 s by
  default; `timeout=None` waits without limit. The load is not cancelled and
  may still finish.

The open waits on a connection of its own. Another thread can call
`get_status()` in the meantime, which reports `loading`.

## Following the playhead

`playhead_updates()` reports the playhead as it changes. Each update has a
`reason`:

| `reason`   | sent when                                                       |
| ---------- | --------------------------------------------------------------- |
| `seek`     | the playhead was moved, by a script or in the app               |
| `play`     | playback started                                                |
| `pause`    | playback stopped                                                |
| `document` | the document changed: opened, closed, or saved under a new name |
| `tick`     | every `interval` seconds while playing                          |

```python
from njord_player_remote import Player

with Player.connect() as p:
    with p.playhead_updates(interval=0.5) as updates:
        print(updates.subscription.playhead)    # where it was when subscribing
        for u in updates:
            if u.playhead is None:              # the document was closed
                print(u.reason, "no document")
                continue
            print(u.reason, u.playhead.time, u.playing)
            if u.reason == "pause":
                break
```

`interval` is 1 s by default, and can be set from 0.02 s to 3600 s. Nothing
arrives while playback is paused and nothing changes. The player also moves
the playhead on its own, for example when a hidden window is shown again, so
a `seek` update can carry the time it already had.

Opening another document usually gives two `document` updates: one without
a document (`document` and `playhead` are `None`) when the old one is
closed, then one with the new document once it has loaded. The first can be
missing when the load is quick or the script is behind, since the player
reports the state as it is when it writes an update; wait for the update
whose `document` is the new one, not for a fixed number. Save As also gives a
`document` update, with a new `title` and `path` but the same
`document.id`; compare `id` to tell whether the document itself changed.

The updates come over a second connection of their own, so the `Player`
stays free for calls, from the loop body or from another thread.

Updates wait to be read. A script that does slow work for each one reads
them late, oldest first: the player stops queueing more only once the
connection's buffer is full, and `AsyncPlayer` keeps up to 1024 unread
updates. A script that needs the current position, rather than every
change, should call `get_playhead()` instead of trusting an update it has
read late, or keep its own work per update short.

Leaving the `with` block, or calling `updates.close()`, ends the
subscription. On macOS, `close()` may be called from another thread to stop
a loop that is waiting. On Windows, close from the thread that iterates.

## asyncio

`AsyncPlayer` has the same calls as `Player`, as coroutines. Calls and
playhead updates share one connection, and calls may run concurrently.
`open_document()` waits on a connection of its own, so a long load does not
hold up the other calls. This
script plays five seconds, then pauses:

```python
import asyncio
from njord_player_remote import AsyncPlayer

async def main():
    async with await AsyncPlayer.connect() as p:
        sub = await p.subscribe_playhead(interval=0.5)
        if sub.playhead is None:
            print("no document open")
            return
        await p.play()
        async for u in p.playhead_updates():
            if u.playhead is None:              # the document was closed
                break
            print(u.reason, u.playhead.time)
            if u.playhead.t >= sub.playhead.t + 5:
                await p.pause()
                break

asyncio.run(main())
```

Playhead updates work slightly differently with `AsyncPlayer`:

- `subscribe_playhead()` starts the updates and returns the state they start
  from.
- `playhead_updates()` iterates them.
- `unsubscribe_playhead()` stops them.

Cancelling a call, for example with `asyncio.wait_for`, leaves the
connection usable.

## When the player is busy

A call that needs the player's main thread waits up to about 5 s, for
example while a dialog is open. Then it raises `BusyError`, and the call had
no effect.

A `Player` call can be interrupted while it waits for its answer, with
Ctrl-C or another exception. When that happens:

- The connection is closed, and every later call on that `Player` raises
  `ConnectionClosedError`.
- The interrupted call may still take effect, if the player reaches it
  within those 5 s.
- Connect again, and check the state before repeating the call.

`open_document()` is the exception: interrupting it closes only its own
connection, and the `Player` stays usable. It does not cancel the open. If
the request had reached the player, the open may still happen: a load
already started goes on to the end, however long it takes, and the previous
document is closed. If not, nothing changed. Check `get_status()` before
trying again.

## Errors

Everything this package raises about the player derives from `PlayerError`.
When the player answered with an error, `e.code` is its JSON-RPC code and
`e.data` its detail.

| exception                 | meaning                                                       |
| ------------------------- | ------------------------------------------------------------- |
| `PlayerNotRunningError`   | Njord Player 3 is not running for this user                   |
| `EndpointNotTrustedError` | the endpoint failed verification (e.g. owned by another user) |
| `NotPlayer3Error`         | something other than Njord Player 3 answered                  |
| `ProtocolVersionError`    | the player speaks an incompatible protocol version            |
| `NoDocumentError`         | the call needs a document and none is open                    |
| `DocumentLoadingError`    | the call needs a document and one is being opened             |
| `BusyError`               | the player did not take the call within about 5 s; no effect  |
| `InvalidParamsError`      | the arguments do not fit the method; see `e.reason`           |
| `MethodNotFoundError`     | the running player does not offer this method                 |
| `UnsavedChangesError`     | `open_document`: the open document has unsaved changes        |
| `OpenFailedError`         | `open_document`: the file is missing or cannot be read        |
| `OpenCancelledError`      | `open_document`: another open replaced this one               |
| `OpenTimeoutError`        | `open_document`: the load took longer than `timeout`          |
| `UnavailableError`        | this version of Njord Player may no longer be used            |
| `LimitError`              | too many connections are open to the player (the limit is 8)  |
| `EndpointError`           | the endpoint cannot be used, e.g. a relative override path    |
| `ConnectionClosedError`   | the connection ended, e.g. the player quit                    |

`Player.server` holds what the player reported when the script connected:
its `version`, its protocol version, and the `methods` it serves. A script
can check `methods` before using a method that only newer players offer.

## Connecting to a specific endpoint

`Player.connect()` finds the running player by itself. To connect somewhere
else, for example to a test server, do either of these:

- set the `NJORD_PLAYER3_CONTROL_ENDPOINT` environment variable;
- pass the path or pipe name to `Player.connect(endpoint)`.

Either way, the endpoint is verified as usual. `resolve_endpoint()` returns
the endpoint `connect()` would use.

## Protocol

The player speaks JSON-RPC 2.0, one JSON object per line. The package
includes the protocol's [OpenRPC](https://open-rpc.org/) description as
`njord_player_remote/openrpc.json`, for anyone writing a client in another
language.
