# Data and the app

> A member's library changed in their name, more of it read on either side, the player asked, the app's events, files and uploads, songs asked for, and a request's digests.

Page: https://songstress.app/docs/develop/data/

From extension API 0.1.14 an extension reaches more of Songstress: it changes a member's library in their name, reads
pages of the library and a member's listening from either side, asks the player, hears what the app does, keeps
files, and asks for songs. Ask for `"songstress": "^0.1.14"` in `engines`. Each call about a member needs that
member's own yes (see [Permissions](/docs/develop/permissions/)): an admin's grant never stands in for it.

## A member's library, in their name [#a-members-library-in-their-name]

With `library.write` (the admin allows it, each member says yes), server code marks favourites, rates, and makes and
changes the member's own playlists, as they would in the app. A smart playlist and another member's are out of
reach. A change is told to every other extension's hooks, never back to yours.

```ts
import { songstress } from 'songstress/server'

songstress.commands.register('road-trip', async (_input, context) => {
  const member = { userId: context.userId }
  const made = await songstress.library.createPlaylist('Road trip', ['s1', 's2'], member)
  await songstress.library.setFavorite([{ type: 'song', id: 's1' }], true, member)
  return { action: { type: 'toast', message: `${made.playlist.name}: ${made.songs} songs` } }
})
```

What changed is told in the member's Activity, one line for your extension's changes of one kind in a minute,
whatever playlists they touch ("Added 40 songs to 3 playlists"). At most 200 songs or marks a call and 60 changes a
minute for one member.

## Reading more, on either side [#reading-more-on-either-side]

`library.listSongs`, `listAlbums`, `listArtists`, `listGenres` and `listPlaylists` answer pages (`items`, `total`,
`nextOffset`); "added lately" is `sort: 'recentlyAdded'`. `library.getLyrics` is what the library holds of a song's
lyrics. `listening.history` and `listening.top` read a member's past (their yes to `listening.history`);
`listening.now` what they play at this moment (`listening.read`). Client code reads them too, as the member signed
in, so an extension that runs only in the app needs no server entry to read.

Every read is counted: a member's own (their history, top lists, what they play now, their playlists, a page in their
order) 60 a minute, and pages of the catalogue and lyrics 120 a minute for each member (or server code naming none);
past either, `limit-exceeded`. A blocked member's own is read by nobody, whatever they said yes to: their history,
top lists and what they play now are refused (`permission-denied`), and their private playlists are read for no one.

A playlist is read when it is public, or, with `{ userId }` and that member's yes to `listening.playlists`, when it
is their own or one of the server's shared smart playlists. A smart playlist's rules may read a member's marks and
plays (their favourites, ratings and play counts): a shared one is read with that member's only when they also said
yes to `listening.read` and `listening.history`, and otherwise with no one's.

```ts
import { songstress } from 'songstress/client'

songstress.hooks.onTrackChange(async (song) => {
  const lyrics = song ? await songstress.library.getLyrics(song.id) : null
  const top = await songstress.listening.top('artist', { period: 'month', limit: 3 })
  console.log(lyrics?.synced, top.map((artist) => artist.name))
})
```

## The player, asked [#the-player-asked]

With `player.control` the client code asks this device's player, as a tap on the app's own controls would, and the
person keeps the last word on what plays:

- **What is playing, at any time.** `play`, `pause`, `next`, `previous` and `seek` act on what plays on this device,
  and so do `setVolume`, `setShuffle`, `setRepeat` and `queue.add` (which only appends, or puts songs next): a sleep
  timer pauses, a remote skips. That is what the permission has always meant.
- **What replaces or reorders it waits for a person's press.** `playSongs`, `queue.remove`, `move` and `clear`, and
  `ui.navigate`, go right after the person pressed something of your extension's in this app (a button, a menu, a
  control of its tree, its canvas, a command they ran, the answer to its question) in the last five seconds, and one
  press covers one `playSongs` or `ui.navigate` and ten other asks, then it is spent. A hook, a timer, a message or a
  job is never a press.
- **Only what a person did is a press.** The command a person ran is one, and so is their answer in the app's own
  dialog: a yes, a pick, an input, an upload. A command your code runs itself (`commands.execute`) is none, and a
  later command of a chain (one a command's answer runs with `invoke`) rides what is left of the first one's press.
- **`playSongs` with no press only on an empty queue.** `playSongs` also goes with no press when the queue holds no
  song, never over a paused song nor a queue played to its end: to start music after one ended, `queue.add(ids)` then
  `player.next()`, the queue kept before them. A pause is not a stop, and the person's place is theirs.
- **Never for other people, never on another device.** In a Jam, or while this app follows another device, every ask
  of the player and the queue needs that press, and so does a start (`play`, `next`, `previous`, `seek`, `playSongs`)
  while another of the member's devices plays; while this app follows another device, `playSongs` and the queue's
  edits are not this device's at all (`not-available`).
- **Counted.** The player's changes are five a second at most (the volume twenty); `queue.add` with no press takes
  500 songs a minute (right after a press, an add spends one of its ten asks), and never takes the queue past 2,000
  songs still to come; `player.getState` and `queue.get` are
  64 at once, then ten a second together. More answer `limit-exceeded` ([Limits](/docs/develop/api/#limits)).
  `queue.clear` takes what comes after the song playing, which plays on.

What does not follow the rule answers `not-available`, and nothing changes.

```ts title="src/fade.ts"
import { songstress } from 'songstress/client'

// A sleep timer: the volume falls, then the song pauses. Neither needs a press.
songstress.commands.register('fade-out', async () => {
  const { volume } = await songstress.player.getState()
  for (let step = 1; step <= 20; step++) {
    await songstress.player.setVolume(volume * (1 - step / 20))
    await new Promise((done) => setTimeout(done, 150))
  }
  await songstress.player.pause()
})

// The "Play the mix" button of the extension's page: a press, so playSongs may replace the queue.
songstress.commands.register('play-mix', async () => {
  await songstress.player.playSongs(['s1', 's2', 's3'])
})

// After the last song of the queue ended by itself: add, then move on. The member's queue stays as it was.
songstress.hooks.onPlaybackState(async (state) => {
  if (state !== 'ended') return
  const queue = await songstress.queue.get()
  if (queue.index < queue.songs.length - 1) return
  await songstress.queue.add(['s1', 's2'])
  await songstress.player.next()
})
```

## The app's events [#the-apps-events]

Client hooks beside the player's: `onPlaybackState` (waiting, ended, failed), `onShuffleChange`, `onRepeatChange`,
`onLyricsLine`, `onNavigate` (the page shown, by kind and id, never what a person typed), `onAppearanceChange`,
`onVisibilityChange`, `onConnectionChange` and `onFavorite`. They observe: none blocks anything, and the app holds
each to a rate, telling a burst as its newest value. See [Hooks](/docs/develop/hooks/#client-hooks).

## Files and uploads [#files-and-uploads]

`storage.files` keeps files beside your store, under `storage`, in the same parts: each member's, and your
extension's own. Server code names the part in every call: `{ userId }` for a member's, `{ everyone: true }` for
your extension's own, whose images every member may be shown; a call that names neither is refused. Client code
names none: its part is the member's. A part holds 16 MiB, 100 files and 64 megapixels of images (four of 4096 by
4096). Code writes and deletes 60 files a minute in one part at most, and reads and lists 120 a minute for each
member, server code's reads counted too; an upload keeps every file it was given or, when one is refused, none. A file is what its name says, or it is refused: `.png`,
`.jpg`, `.webp` images (never SVG), `.json`, and text (`.txt`, `.csv`, `.m3u`, `.lrc`...). An image among them is an
image source, `{ file: 'pets/prince.webp' }`, shown to its member alone. The `upload` action has the app ask the
person for a file, keep it in their part and run your command with it: your code never holds the bytes.

```ts
import { songstress } from 'songstress/server'

songstress.commands.register('add-pet', async () => ({
  action: { type: 'upload', accept: ['image', 'json'], folder: 'pets', many: true, command: 'pet-added' },
}))

songstress.commands.register('pet-added', async (_input, context) => {
  return { action: { type: 'toast', message: `${context.files?.length ?? 0} files kept` } }
})
```

## Songs asked for [#songs-asked-for]

With `library.acquire` (the admin allows it, each member says yes), server code asks for songs in a member's name,
as their own Acquire does: each counts toward their daily limit and shows in Activity as theirs, and `onAcquired`
tells when it came in. Your extension's asks also have a limit of their own, whatever the member's daily limit is
and for an admin too: two asks a minute and a hundred songs a day in one member's name. A title, an artist and an
album are one line of at most 300 characters, and an ISRC and a MusicBrainz id must have their shapes. Songstress's
own sources find it.

```ts title="src/finder.ts"
import { songstress } from 'songstress/server'

// "Find it for me" in a song's menu of the extension's own page: asked in the member's name, on their daily limit.
songstress.commands.register('find-it', async (_input, context) => {
  await songstress.library.acquire([{ title: 'So What', artist: 'Miles Davis', album: 'Kind of Blue' }], { userId: context.userId })
  return { action: { type: 'toast', message: 'Asked for. It shows in your Activity.' } }
})
```

## Listening privately [#listening-privately]

A member who turns on private listening keeps what they play to themselves, and no yes they gave reaches into it:

- **On the server**, such a play is in their own Stats and nowhere an extension reads. `listening.history` leaves it
  out, `listening.top` counts only the plays outside it, a list in their play count's or last play's order counts
  none of it, `listening.now` answers `null` while it is on, no `onPlay`, `onScrobble` or `scrobble` provider is
  told of it, and `onAcquired` names no member while the member who asked listens privately.
- **In what your extension draws**, no status item, overlay or now-playing panel is told the song playing: each still
  draws, with no `song` in its context, whichever side renders it.
- **In the app**, client code is told nothing of what plays, and neither is an in-app view: no player hook fires,
  nor `onLyricsLine`, and `player.getState` and `queue.get` answer `not-available` ("listening privately"). Until
  the app has read whether the member listens privately, they count as listening privately, so nothing is told that
  they hid. When private listening ends, the hooks begin again from what plays then. The asks of the player still
  work: a sleep timer must pause.
- Marks and ratings are not plays: `onFavorite` and `onRating` are told as ever.

## A request's digests [#a-requests-digests]

Server code works out the digests a service asks a request to carry, with no permission: `net.sha256(data)` and
`net.hmacSha256(key, data)`, as lowercase hex, for a webhook's signature. A key is text, or bytes as `{ hex }` or
`{ base64 }`, for a secret given in base64 or a chain of HMACs.

```ts
import { songstress } from 'songstress/server'

const body = JSON.stringify({ event: 'favorite' })
const signature = await songstress.net.hmacSha256((await songstress.secrets.get('secret')) ?? 'unset', body)
await songstress.net.fetch('https://hooks.example.com/in', { method: 'POST', body, headers: { 'x-signature-256': `sha256=${signature}` } })
```

## Testing it [#testing-it]

The mock host of `songstress/testing` answers all of it: give it a `library` (songs, playlists by owner, plays, each
member's yes) and, for client code, a `player`; read back `host.library`, `host.player`, `host.files()`, and carry
out an upload with `host.upload(command, files)`. See [Testing](/docs/develop/testing/).
