# Providers

> Add sources beside Songstress's own, for search, links, lyrics, metadata, artwork, scrobbling, recommendations and audio.

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

A provider is a source your extension adds beside Songstress's own. Declare it under `contributes.providers.<kind>`,
then register it in the server entry, under the same id, with `songstress.providers.<kind>.register(id, provider)`.
It needs the permission `providers`. A `scrobble` provider, which is handed members' plays, needs `listening.read`
too, and hears only the members who granted it.

## The kinds [#the-kinds]

Each kind is a list of up to five sources.

The extension's sources, by what they answer. Each kind is a provider contract the code registers.

| Field | Type | Description |
|---|---|---|
| `search?` | `SearchSource[] \| undefined` | Sources that answer a search. |
| `lookup?` | `LookupSource[] \| undefined` | Sources that open one track, album, artist or playlist by its id. |
| `links?` | `LinkSource[] \| undefined` | Sources that read a pasted link. |
| `lyrics?` | `Source[] \| undefined` | Sources of lyrics. |
| `metadata?` | `MetadataSource[] \| undefined` | Sources of facts about artists, releases and tracks. |
| `artwork?` | `ArtworkSource[] \| undefined` | Sources of artist photos and album covers. |
| `artistInfo?` | `ArtistInfoSource[] \| undefined` | Sources of words about an artist: who they are, and the artists like them. |
| `scrobble?` | `Source[] \| undefined` | Services that plays are reported to. |
| `recommend?` | `RecommendSource[] \| undefined` | Sources of recommendations. |
| `play?` | `Source[] \| undefined` | Sources that can play what their own search found. Switched off until the admin turns each on. |
| `download?` | `DownloadSource[] \| undefined` | Sources songs can be acquired from. Switched off until the admin turns each on. |

What your code answers for each kind is under [What your code answers](#what-your-code-answers).

## Every source [#every-source]

Every source has an `id`, and may have a `name` as people read it (left out, your extension's name). The same id
under several kinds is one source, with one name and one group (`PROVIDER_MISMATCH`). Lyrics, scrobble and play
sources take only these:

A source that answers beside Songstress's own.

| Field | Type | Description |
|---|---|---|
| `id` | `string` | The source's name inside the extension. Code registers the provider under it; the same id under several kinds is one source. |
| `name?` | `string \| undefined` | The source's name as people read it. Left out, it is the extension's name. |

Search sources say what a search finds:

A source that answers a search.

| Field | Type | Description |
|---|---|---|
| `id` | `string` | The source's name inside the extension. Code registers the provider under it; the same id under several kinds is one source. |
| `name?` | `string \| undefined` | The source's name as people read it. Left out, it is the extension's name. |
| `group?` | `ProviderGroup \| undefined` | The catalogue of Songstress's own whose results this source's are merged with. Left out, the source is a group of its own. |
| `types` | `CatalogType[]` | What a search can find. |

Lookup sources, what they open by id:

A source that opens one track, album, artist or playlist by its id.

| Field | Type | Description |
|---|---|---|
| `id` | `string` | The source's name inside the extension. Code registers the provider under it; the same id under several kinds is one source. |
| `name?` | `string \| undefined` | The source's name as people read it. Left out, it is the extension's name. |
| `group?` | `ProviderGroup \| undefined` | The catalogue of Songstress's own whose ids this source speaks. Left out, the source is a group of its own. |
| `types` | `CatalogType[]` | What it can open by id. |

Link sources, the links they read:

A source that reads a pasted link.

| Field | Type | Description |
|---|---|---|
| `id` | `string` | The source's name inside the extension. Code registers the provider under it; the same id under several kinds is one source. |
| `name?` | `string \| undefined` | The source's name as people read it. Left out, it is the extension's name. |
| `group?` | `ProviderGroup \| undefined` | The catalogue of Songstress's own whose links this source reads. Left out, the source is a group of its own. |
| `patterns` | `string[]` | The links it reads. The longest pattern that fits a link wins. |

A link pattern is a host with an optional path that a link must begin with (`soundcloud.com`,
`example.com/album/`), or an app link's scheme (`spotify:`). A host also takes links to the hosts under it, and the
longest pattern that fits a link wins. `http:` and `https:` alone are refused (`LINK_PATTERN_TOO_BROAD`).

Metadata, artwork, artist info and recommendation sources say what they support:

A source of facts about artists, releases and tracks.

| Field | Type | Description |
|---|---|---|
| `id` | `string` | The source's name inside the extension. Code registers the provider under it; the same id under several kinds is one source. |
| `name?` | `string \| undefined` | The source's name as people read it. Left out, it is the extension's name. |
| `group?` | `ProviderGroup \| undefined` | The catalogue of Songstress's own whose artist ids this source speaks. Left out, the source is a group of its own. |
| `supports` | `("discography" \| "enrich")[]` | What it answers: an artist's discography (their releases, their most played songs, a release's tracks), or the missing facts of one track. |

A source of artist photos and album covers.

| Field | Type | Description |
|---|---|---|
| `id` | `string` | The source's name inside the extension. Code registers the provider under it; the same id under several kinds is one source. |
| `name?` | `string \| undefined` | The source's name as people read it. Left out, it is the extension's name. |
| `supports` | `("album-cover" \| "artist-photo")[]` | The pictures it can find. |

A source of words about an artist.

| Field | Type | Description |
|---|---|---|
| `id` | `string` | The source's name inside the extension. Code registers the provider under it; the same id under several kinds is one source. |
| `name?` | `string \| undefined` | The source's name as people read it. Left out, it is the extension's name. |
| `supports` | `("biography" \| "similar")[]` | What it can say about an artist: who they are, in words, or the artists like them. |

A source of recommendations.

| Field | Type | Description |
|---|---|---|
| `id` | `string` | The source's name inside the extension. Code registers the provider under it; the same id under several kinds is one source. |
| `name?` | `string \| undefined` | The source's name as people read it. Left out, it is the extension's name. |
| `modes` | `("artist" \| "context" \| "track")[]` | What it recommends from: one song, one artist, or a list of songs. |

Download sources list their qualities, best first:

A source the library can fetch audio from, at the qualities it offers.

| Field | Type | Description |
|---|---|---|
| `id` | `string` | The source's name inside the extension. Code registers the provider under it; the same id under several kinds is one source. |
| `name?` | `string \| undefined` | The source's name as people read it. Left out, it is the extension's name. |
| `qualities` | `Quality[]` | The qualities it offers, best first. The admin picks one. |

One quality a download source offers.

| Field | Type | Description |
|---|---|---|
| `id` | `string` | The quality's name, as code receives it. |
| `title` | `string` | The quality as people read it (AAC 256 kbps). |
| `lossless?` | `boolean \| undefined` | The audio is lossless. |

## What your code answers [#what-your-code-answers]

Each kind's provider, as the SDK declares it. Every method is also handed the context it is asked in:

What every provider call is told.

| Field | Type | Description |
|---|---|---|
| `userId?` | `string \| undefined` | The member the answer is for. Absent when the server asks for itself, as a background job does. |

### Search [#search]

Answers a search.

| Field | Type | Description |
|---|---|---|
| `search` | `(query: SearchQuery, context: ProviderContext) => Awaitable<SearchResults>` | Searches the source for the query's text, in the kinds it asks for. |

### Lookup [#lookup]

Opens one thing by the source's own id. Implement a method for each kind
the manifest lists under `types`. Null when the source has no such thing.

| Field | Type | Description |
|---|---|---|
| `track?` | `((id: string, context: ProviderContext) => Awaitable<CatalogTrack \| null>) \| undefined` | The track with this id. |
| `album?` | `((id: string, context: ProviderContext) => Awaitable<CatalogAlbumDetail \| null>) \| undefined` | The album with this id, with its tracks. |
| `artist?` | `((id: string, context: ProviderContext) => Awaitable<CatalogArtistDetail \| null>) \| undefined` | The artist with this id, with their albums and top tracks. |
| `playlist?` | `((id: string, context: ProviderContext) => Awaitable<CatalogPlaylistDetail \| null>) \| undefined` | The playlist with this id, with its tracks. |

### Link [#link]

Reads a link one of the manifest's `patterns` claimed: a pasted address,
or a playlist a member follows. Null when it leads nowhere.

| Field | Type | Description |
|---|---|---|
| `resolve` | `(url: string, context: ProviderContext) => Awaitable<LinkResult \| null>` | What the link is: a track, an album, an artist or a playlist of the source's. |

### Lyrics [#lyrics]

Finds a song's lyrics. Asked by the server's nightly library pass, never
while a song plays, within 10 seconds, once an admin adds the source to the
lyrics order. The pass asks the whole order about every track without
synced lyrics, those with plain ones too, since Songstress's own sources
may match exactly enough to replace them; this answer is used for a track
with no lyrics at all, and never replaces lyrics a track has. The track is
asked again only after a rest (SPEC.md, section 11).

| Field | Type | Description |
|---|---|---|
| `find` | `(song: TrackQuery, context: ProviderContext) => Awaitable<LyricsResult>` | The song's lyrics as the source has them: synced or plain lines, instrumental, or none. |

### Metadata [#metadata]

Facts about artists, releases and tracks. Implement the three discography
methods when the manifest's `supports` lists "discography" (artists are
named by the source's own id, or by the id of the group the provider
joined), and `enrich` when it lists "enrich".

| Field | Type | Description |
|---|---|---|
| `releases?` | `((artistId: string, context: ProviderContext) => Awaitable<CatalogAlbum[]>) \| undefined` | What the artist released, without tracks. |
| `topTracks?` | `((artistId: string, context: ProviderContext) => Awaitable<CatalogTrack[]>) \| undefined` | The artist's tracks the source ranks, most played first; empty when it ranks none. |
| `releaseTracks?` | `((releaseId: string, context: ProviderContext) => Awaitable<CatalogTrack[]>) \| undefined` | One release's tracks, in order. |
| `enrich?` | `((track: TrackQuery, context: ProviderContext) => Awaitable<TrackFacts \| null>) \| undefined` | The facts the track lacks; null when the source does not know the track. |

### Artwork [#artwork]

Pictures. Implement the method for each kind the manifest lists under
`supports`.

| Field | Type | Description |
|---|---|---|
| `artistPhoto?` | `((artist: ArtistQuery, context: ProviderContext) => Awaitable<ArtistPhoto \| null>) \| undefined` | The artist's photo; null unless the source can stand behind who it is. A namesake's photo is worse than none. |
| `albumCover?` | `((album: { artist: string; title: string; }, context: ProviderContext) => Awaitable<string \| null>) \| undefined` | The address of the album's cover; null when the source lists none. |

### ArtistInfo [#artistinfo]

Words about an artist. Implement the method for each thing the manifest
lists under `supports`. Both are asked by the server for itself, never
for one member.

| Field | Type | Description |
|---|---|---|
| `biography?` | `((artist: ArtistQuery, context: ProviderContext) => Awaitable<ArtistBiography \| null>) \| undefined` | Supports "biography": who the artist is; null unless the source can stand behind who it is. A namesake's story is worse than none. |
| `similarArtists?` | `((artist: ArtistQuery, limit: number, context: ProviderContext) => Awaitable<CatalogArtist[]>) \| undefined` | Supports "similar": the artists like this one, most alike first, at most `limit` (never over 50). Each is named by the source's own id; Songstress finds them in the library by name and by `ids`. Empty when the source knows none. |

### Scrobble [#scrobble]

A service plays are reported to, for each member who connected it. A
play that fails with `rate-limited` or `unavailable` is tried again later;
`sign-in-required` asks the member to connect again. It is handed members'
plays, so it needs the permission `listening.read` beside `providers`, and
hears only the members who granted it.

| Field | Type | Description |
|---|---|---|
| `scrobble` | `(play: ScrobblePlay, context: ProviderContext) => Awaitable<void>` | A play counted. |
| `nowPlaying?` | `((play: ScrobblePlay, context: ProviderContext) => Awaitable<void>) \| undefined` | A song started. Sent live only, and not for every play. |

### Recommend [#recommend]

Recommendations, best first. Implement the method for each mode the
manifest lists under `modes`. Empty when the source has nothing for the
seed.

| Field | Type | Description |
|---|---|---|
| `similarTracks?` | `((seed: RecommendSeed, limit: number, context: ProviderContext) => Awaitable<RecommendedTrack[]>) \| undefined` | Mode "track": songs like this one. |
| `artistRadio?` | `((artist: RecommendSeed, limit: number, context: ProviderContext) => Awaitable<RecommendedTrack[]>) \| undefined` | Mode "artist": a radio of this artist. |
| `contextMix?` | `((seeds: RecommendSeed[], limit: number, context: ProviderContext) => Awaitable<RecommendedTrack[]>) \| undefined` | Mode "context": one mix from several songs. |

### Play [#play]

Plays what the search provider of the same id found. Off until the admin
turns it on. One progressive file only: never a playlist of segments.

| Field | Type | Description |
|---|---|---|
| `resolve` | `(track: CatalogTrack, context: ProviderContext) => Awaitable<StreamLocation \| null>` | Null when the source has no stream for the track right now. |

### Download [#download]

A source songs can be acquired from. Off until the admin adds it and
turns it on.

| Field | Type | Description |
|---|---|---|
| `check` | `(track: TrackQuery, context: ProviderContext) => Awaitable<DownloadAvailability>` | Says whether the source has a track, and its id there. |
| `locate` | `(request: { id: string; quality: string; }, context: ProviderContext) => Awaitable<{ location: DownloadLocation; tags?: TrackFacts; } \| null>` | Where the audio is, at one of the manifest's `qualities`; null when it turned out not to be there. `tags` may carry what the source knows that the request did not (an ISRC above all). |

A search is asked with a query, and answers results of each type asked for:

What a search asks a source.

| Field | Type | Description |
|---|---|---|
| `text` | `string` | What the person typed. |
| `types` | `CatalogType[]` | The kinds asked for, from those the manifest lists under `types`. |
| `limit` | `number` | How many of each kind, at most. |
| `offset` | `number` | How many of each kind to skip: the next page. |

What a source found, for each kind asked. Leave out a kind it found nothing of.

| Field | Type | Description |
|---|---|---|
| `tracks?` | `CatalogTrack[] \| undefined` | The tracks found, best first. |
| `albums?` | `CatalogAlbum[] \| undefined` | The albums found, best first. |
| `artists?` | `CatalogArtist[] \| undefined` | The artists found, best first. |
| `playlists?` | `CatalogPlaylist[] \| undefined` | The playlists found, best first. |

A scrobble is handed the play:

One play to report.

| Field | Type | Description |
|---|---|---|
| `song` | `Song` | The song that was played, from the library. |
| `userId` | `string` | The member who listened: `context.userId` is theirs too. |
| `playedAt` | `string` | When the play started, as an ISO 8601 time. |

## A search source [#a-search-source]

```json title="songstress.json"
"permissions": {
  "providers": { "reason": "Search Tunelog's catalogue beside your library." },
  "network": { "reason": "Ask Tunelog what it has.", "hosts": ["api.tunelog.example"] }
},
"contributes": {
  "providers": { "search": [{ "id": "tunelog", "name": "Tunelog", "types": ["track"] }] }
}
```

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

interface Found {
  id: string
  title: string
  artist: string
  seconds: number
}

songstress.providers.search.register('tunelog', {
  async search(query) {
    const url = `https://api.tunelog.example/v1/search?q=${encodeURIComponent(query.text)}&limit=${query.limit}`
    const answer = await songstress.net.fetch(url)
    if (answer.status === 429) throw new ProviderFailure('rate-limited', { retryAfterS: 60 })
    if (answer.status !== 200) throw new ProviderFailure('unavailable')
    const found = JSON.parse(answer.body) as Found[]
    return {
      tracks: found.map((track) => ({ id: track.id, title: track.title, artists: [track.artist], durationS: track.seconds })),
    }
  },
})
```

## The rules [#the-rules]

- **`group`** names the catalogue of Songstress's own that the source reads too: `musicbrainz`, `spotify`, `deezer`,
  `tidal`, `itunes` or `ytmusic`. Its results are then merged with that catalogue's, and it speaks that catalogue's
  ids. Left out, the source is a group of its own.
- **`lookup` and `metadata`.** A `lookup` source's artists and albums give their discographies too. Declare
  `metadata` with `discography` for a source that answers discographies without pages of its own, and with `enrich`
  for one that fills a track's missing facts.
- **`artistInfo`** is what an artist's page says about them. A biography is plain text, its paragraphs apart by a line
  break; the first 4000 characters are kept. It may carry its page (`url`) and its language (`language`, a BCP 47
  tag). Similar artists come most alike first, 50 at most. Both are asked by the server for itself and kept: `null`
  is the answer of a source that can't tell the artist from a namesake. It came with API 0.1.6.
- **Beside, never instead.** A source joins switched off or last, the admin's order decides, and one that fails never
  fails the rest. Lyrics from a provider never replace the lyrics a song's own file carries. Results carry your
  extension's mark.
- **`play` and `download`** are switched off on a server until its admin turns each on. A `play` provider plays what
  the `search` provider of the same id found (`PROVIDER_PLAY_NEEDS_SEARCH`). Both answer where the audio is, as
  addresses; Songstress fetches it, under your `network` permission on every hop, and joins segments itself. Nothing
  is decrypted. From API 0.1.8 an extension with either may be listed like any other.

## Failure [#failure]

"Nothing found" is an empty list or `null`. A failure Songstress knows what to do about is thrown as a
`ProviderFailure` with one of four codes:

- `rate-limited`: the service asks to wait. Give `retryAfterS`, the seconds to wait.
- `sign-in-required`: the account is missing or signed out.
- `not-configured`: something it needs isn't set up yet.
- `unavailable`: the service can't answer now.

Anything else thrown counts as the provider being broken for now.
