# Bell Band — song API for agents

Bell Band is a TV app that shows children which coloured handbell to ring, in time with
an optional MP3 accompaniment. You (an agent) compose a song, render a backing track,
and publish both here. The TV picks the song up the next time it loads and saves it for offline play.

Base URL: this server (e.g. `https://<your-domain>`). Writes need the header
`Authorization: Bearer <key>`. Reads are public (paid songs show as locked without a license).

### Two kinds of key

- **Personal API key** (`bb_...`): part of the $19.99 license (all songs for 3 years). The account
  owner makes one on `/account` (shown once) and gives it to you. Songs you add with it are
  **private** to that account: they appear in its song list with the tag `mine`, under the id
  `u-<8 letters>-<your id>`, and nobody else sees them. There's no limit on how many songs you add.
  Use your own short ids (max 48 characters) in the URLs, e.g. `PUT /api/songs/my-song`. If the
  license is missing or has expired, writes answer **402** ("API access is part of the $19.99
  license"); the key works again once the license is renewed. A revoked key answers 401.
- **Admin key** (`BELL_API_KEY`, the site owner's): writes the public library everyone sees.

### Sharing a private song

`POST /api/songs/<id>/share` (personal key) returns `{url}`, a link like `https://<domain>/s/<token>`.
Anyone who opens it can play that one song, even without a license or an account, and a logged-in
person can press *Add to my songs* to keep it (it shows with the tag `shared`). `DELETE
/api/songs/<id>/share` turns the link off. There is no public list of shared songs. The owner can do
the same on `/account`.

## Endpoints

| Method | Path | What it does |
|---|---|---|
| GET | `/api/songs` | All songs `{version, songs:[...]}`. Without a license (and without the API key) paid songs come with `"locked": true` and no notes |
| GET | `/api/songs/:id` | One song |
| GET | `/api/songs/:id/accompaniment.mp3` | Its backing track. Locked songs answer 402 here and on `/api/songs/:id`; send the API key to read any song |
| GET | `/api/bells` | The bells that exist (keys, sticker labels, colours, MIDI) |
| POST | `/api/validate` | Dry-run: check a song, no key needed. Returns errors, warnings, bells, length |
| PUT | `/api/songs/:id` | Create or replace a song. JSON body (below). May include the MP3 inline |
| POST | `/api/songs` | Create; id from `id` or the title. 409 if it exists (add `?overwrite=1`) |
| PUT | `/api/songs/:id/accompaniment?firstBeatAt=2.5` | Upload the MP3 alone: raw body, `Content-Type: audio/mpeg` |
| DELETE | `/api/songs/:id` | Remove an uploaded song (built-in songs are hidden); with a personal key, one of your private songs |
| POST/DELETE | `/api/songs/:id/share` | Personal key only: make (or return) / turn off the share link of one of your private songs |
| GET/PUT/DELETE | `/api/bands/:id` | One band: `{name, players, bells, assign}`; `id` is the band name as a slug. Bands saved by a logged-in account belong to it (403 for anyone else); older bands open by name alone |

Ids: lowercase letters, digits, dashes, max 60 characters.

## Song JSON

```json
{
  "title": "Snowflake Waltz",
  "composer": "Claude (original)",
  "difficulty": 4,
  "tempo": 120,
  "beatsPerBar": 3,
  "pickup": 0,
  "notes": [
    "E G hiC | B:2 G | A F# G | E:3",
    "C -:2 | loB -:2 | D -:2 | C -:2"
  ],
  "parts": [{ "name": "Tune", "for": "big" }, { "name": "Sparkle", "for": "learning" }],
  "lyrics": "Snow-flakes fall soft-ly, twirl-ing down slow.",
  "tips": "Shown before the song starts: one or two sentences for the grown-up.",
  "tags": ["christmas"],
  "arrangement": { "style": "waltz", "chords": "C | G | D7 | C" },
  "accompaniment": { "firstBeatAt": 1.75, "credit": "Rendered by Claude" },
  "accompaniment_base64": "<MP3 file, base64>"
}
```

### Tags (collections)

`tags` is an array of lowercase strings. The TV's song list has a row of collections built from it,
and search matches tags too, so **tag every song you publish**. A song can be in several collections;
a collection with no songs is hidden.

| Tag | Collection on the TV | Use it for |
|---|---|---|
| `christmas` | Christmas | Any Christmas or nativity song |
| `lds` | LDS / Primary | Songs from the Children's Songbook / Primary (ids `csb-…`; also add `childrens-songbook` and `songbook`) |
| `kids` | Kids' favorites | Children's songs, nursery rhymes, sing-alongs |
| `featured` | Featured | Top picks only: keep it to about 6–8 songs in total, so don't add it unless asked |
| `mine` / `shared` | My songs / Shared with me | Set by the server for a user's private or shared uploads; don't add these yourself |

Every song also appears under **All songs**. Other tags (e.g. `childrens-songbook`) are allowed and searchable.
Example: `"tags": ["christmas", "lds", "childrens-songbook"]`.

Required: `title`, `tempo` (quarter-note beats per minute), `notes`.
`difficulty` 1–5 is optional (computed if missing). `pickup` = beats in an incomplete first bar.
`parts` (optional, one per voice in `notes`) says who each part is written for:
`learning` (children learning to read), `kid`, `big` (about 9–12) or `adult`. The app uses it to
hand bells out: bells of a `learning` part go to the little ones, bells of an `adult` part to grown-ups.

### Notes

One token per note, separated by spaces. Bars are `|` and are checked against `beatsPerBar`.

| Token | Meaning |
|---|---|
| `C D E F G A B` | the 8-note set, stickers C/1 … B/7 |
| `hiC` (or `C8`) `hiD hiE hiF` | high bells (hiC is C/8) |
| `loA loB` | low bells |
| `C# D# F# G# A#` (or `Db Eb Gb Ab Bb`) | black-handle bells |
| `E:2`, `D:0.5`, `G:1.5`, `C:1/3` | duration in beats (default 1) |
| `C+E+G:2` | chord: several bells at once |
| `-` or `-:2` | rest |

`notes` can be a string (one part) or an array of strings (parts, all starting at beat 0).
The first part is the melody; lyrics attach to it. Each bell is one child: never have two
parts strike the same bell at the same time, or strike it while the other part still holds it
(the validator warns). Lowest bell is loA (A4), highest hiF (F6); there is no low G.

### Lyrics

Syllables separated by spaces and hyphens, one per melody note (a chord counts once):
`"Twin-kle, twin-kle, lit-tle star"`. Use `_` for a note with no syllable.
Punctuation `, . ! ?` ends a lyric line on screen.

### Making songs harder (and fun for a group)

- Level 1: one part, 4–6 bells, quarter and half notes.
- Level 2–3: 7–9 bells, eighth notes, a black-handle bell, a second part on downbeats.
- Level 4–5: two parts, syncopation and rests, 10+ bells, fast passages; keep each bell's
  notes playable by one child (no repeated notes faster than about 4 per second at tempo).
- Spread the notes so every bell gets a turn: the app hands bells out to the players it knows about.
- Write a `learning` part for children who can't read yet: one or two bells that are NOT in the
  tune, struck on the first beat of a bar (or on a fun word like "hey!"), at least 2 beats apart.
  High C / Hi D / Hi E and Low A make good sparkle bells; pick the chord tone of each bar.

## Bell sets: write for the 8-note set first

Most families own only the **8-note set**: `C D E F G A B hiC` (C/1 to C/8). The low/high bells
(`loA loB hiD hiE hiF`) and the black-handle bells (`C# D# F# G# A#`) are add-ons
(`BELL_SETS` in `public/notation.js`, also at `GET /api/bells`). Each band tells the app which bells
it owns, and songs that need other bells are greyed out for that band (the app rings the missing
bells if they play anyway). So:

- Prefer songs that use only the 8-note set, sparkle parts included. That means C major or A minor,
  melody between C and high C (no low G, no F-sharp or B-flat).
- `npm test` checks there are enough 8-bell songs at every level (`MIN_EIGHT` in `tools/check_songs.js`).
- A full-set arrangement of a song that also has an 8-bell version is fine: name the 8-bell one
  `"<Title> (8 bells)"` with id `<id>-8`.

## The family this app is set up for

Two grown-ups, two big kids (9 and 12) and two boys learning to read. Most songs are Christmas songs (tag them `christmas`).
A typical arrangement: tune for the big kids (`big`), bass or high answer for the grown-ups (`adult`),
sparkle for the little ones (`learning`).

## Accompaniment (MP3)

The MP3 is played under the bells. The app syncs to it, so tell it where beat 0 is:
`accompaniment.firstBeatAt` = seconds from the start of the MP3 to the first beat of `notes`.
Put a one-bar count-in before beat 0. The app can slow the MP3 down (pitch kept), so render it
at the song's `tempo`. Don't put the bell melody in the MP3 (the children play it); a very soft
guide is fine. Up to 40 MB; 128 kbps mono is plenty.

The repo has a renderer that does all of this from `arrangement`:

```sh
python3 tools/render_accompaniment.py songs/my-song.json      # writes songs/my-song.mp3 and firstBeatAt
BELL_URL=https://<domain> BELL_API_KEY=... node tools/upload.js songs/my-song.json
```

`arrangement.chords`: one chord per token, bars with `|`. Chords without durations split the bar
evenly; `G7:2` lasts 2 beats; `-` is silence (for a pickup). Qualities: `C Cm C7 Cm7 Cmaj7 Cdim Csus4 Csus2 C6`, with `#`/`b`.
`arrangement.style`: `pop`, `march`, `swing`, `waltz`, `lullaby`, `strings`.

## Example: publish with curl

```sh
curl -X POST "$BELL_URL/api/validate" -H 'Content-Type: application/json' -d @song.json

# song + MP3 in one call
jq --arg mp3 "$(base64 -w0 song.mp3)" '. + {accompaniment_base64: $mp3}' song.json \
  | curl -X PUT "$BELL_URL/api/songs/my-song" -H "Authorization: Bearer $BELL_API_KEY" \
         -H 'Content-Type: application/json' --data-binary @-

# or the MP3 on its own, after the song exists
curl -X PUT "$BELL_URL/api/songs/my-song/accompaniment?firstBeatAt=2.0" \
  -H "Authorization: Bearer $BELL_API_KEY" -H 'Content-Type: audio/mpeg' --data-binary @song.mp3
```

The response includes `warnings` (bar lengths, lyric count, bell clashes) and the link `/#song-<id>`,
which opens the song directly on the TV.
