asyncapi: 3.0.0
info:
  title: RVRB websocket API
  version: 2.13.0
  description: |
    The live traffic of RVRB: joining a channel, chat, votes, the DJ queue, playback and presence. The HTTP routes are
    described in `openapi.yaml`.

    ## Framing

    Every frame is a text frame holding one JSON-RPC 2.0 message, with two exceptions: a client may send the bare text
    `ping`, which is answered with the bare text `pong` (use it to tell the connection is alive), and a frame holding
    `null` is ignored.

    * A **request** has `method` and `params`. It has an `id` when it wants an answer. A request without an `id` is never
      answered, not even with an error.
    * A **response** has the `id` of its request and either `result` or `error`. `error` is always `{ "message": string }`
      (a few older paths reply with a bare string, see `ErrorResponse`).
    * Either side can send requests. Today the only request the server sends that expects an answer is
      `nextChannelTrack`, and it sends it to a bot only: it takes a person's next track from their active queue itself.
    * A message the server does not recognise is ignored, without a reply.

    ## Connecting

    Connect to `/ws` with the JWT from the Spotify login as the `token` query parameter. A browser cannot set an upgrade
    header, so unlike the HTTP routes there is no `Bearer ` prefix. A token that does not verify closes the socket. Bots
    connect to `/ws-bot` with their `apiKey` instead, and can only join the channel they belong to.

    The server sends `ready` when the connection is usable: send nothing before it. A connection sends `clientId` (any
    string, unique to the browser instance) so that a reconnect resumes the same connection instead of making a second one.
    `ready` says which channel the server has the connection in (`joined`). After a reconnect that does not resume (the server
    was restarted), it is `null` and the client joins its channel again, and steps up to the decks again if it was a DJ. The
    track that was playing carries on and is given to the client when it joins.

    ## Staying connected

    The server sends `keepAwake` about once a minute and expects `stayAwake` back. A connection that misses several in a row
    is closed. A connection idle for three minutes is removed, and a closed one is given ten seconds to come
    back (a reconnect with the same `clientId`) before its user leaves their channel. A mobile client that is hidden
    (`appState`) is kept for an hour.

    A user has one live connection per client. When a second client of the same user connects from another address, the
    first is closed with a `closed` message (`reason: 1`).

    A bot has one connection per `clientId` (its own id when it sends none). A bot that connects with the api key of one that is
    already connected, and the same `clientId`, takes the connection over: the first is closed, whatever its address. With
    another `clientId` from another address the first is closed too; from the same address both stay open, and then both are the
    bot in the channel and both act on its events. For a deploy with no gap, connect the new process and close the old one
    when it is up, instead of keeping both.

    ## Who may send what

    Each client message belongs to a scope (`x-scope` below):

    * `channel`: the connection must be joined to a channel (only `join` is allowed before that, otherwise the answer is
      `Not Allowed`). The caller's role in the channel is checked against the message's required role (all of them need
      none today); a caller without it gets `Unauthorized`.
    * `music`: the user's Spotify token is refreshed first. If the token now belongs to a different Spotify account than the
      user's, the answer is the error `SPOTIFY_ACCOUNT_MISMATCH` and the client should log in again. If Spotify has revoked
      the refresh token (`invalid_grant`), the answer is the error `SPOTIFY_TOKEN_REVOKED` and the client should log in again. If the refresh fails otherwise
      the answer is `Could not refresh spotify token: 403`.
    * `user`: no channel or token needed.

    The Spotify login is the server's (see `GET /api/login/spotify/callback`): a session says who the user is, and the
    refresh is kept on the server, so the client has no new token to keep.

    Connections that have blocked a user, or are blocked by one, do not receive that user's chat and are shown a generic
    user in place of them (see `updateChannelUsers`).
  contact:
    name: RVRB
  license:
    name: ISC

servers:
  local:
    host: localhost:3000
    protocol: ws
    description: A server run from this repository (`PORT` and `HOST` change it). Behind a proxy it is `wss` at the site's host.

defaultContentType: application/json

channels:
  ws:
    address: /ws
    title: Users
    description: The connection of a logged in user.
    bindings:
      ws:
        bindingVersion: 0.1.0
        query:
          type: object
          required:
            - token
          properties:
            token:
              type: string
              description: The JWT from the Spotify login, without a `Bearer ` prefix.
            clientId:
              type: string
              description: Names this client (one per browser instance), so a reconnect resumes the connection. Defaults to the user's id, which makes two clients of one user the same connection.
    messages: &clientAndServerMessages
      ready:
        $ref: '#/components/messages/ready'
      keepAwake:
        $ref: '#/components/messages/keepAwake'
      stayAwake:
        $ref: '#/components/messages/stayAwake'
      appState:
        $ref: '#/components/messages/appState'
      closed:
        $ref: '#/components/messages/closed'
      join:
        $ref: '#/components/messages/join'
      leave:
        $ref: '#/components/messages/leave'
      joinDjs:
        $ref: '#/components/messages/joinDjs'
      leaveDjs:
        $ref: '#/components/messages/leaveDjs'
      selectQueue:
        $ref: '#/components/messages/selectQueue'
      pushMessage:
        $ref: '#/components/messages/pushMessage'
      userStatus:
        $ref: '#/components/messages/userStatus'
      vote:
        $ref: '#/components/messages/vote'
      playTrack:
        $ref: '#/components/messages/playTrack'
      pauseTrack:
        $ref: '#/components/messages/pauseTrack'
      syncTrack:
        $ref: '#/components/messages/syncTrack'
      registerPlayer:
        $ref: '#/components/messages/registerPlayer'
      deregisterPlayer:
        $ref: '#/components/messages/deregisterPlayer'
      nextChannelTrack:
        $ref: '#/components/messages/nextChannelTrack'
      nextChannelTrackAnswer:
        $ref: '#/components/messages/nextChannelTrackAnswer'
      response:
        $ref: '#/components/messages/response'
      errorResponse:
        $ref: '#/components/messages/errorResponse'
      activePlayer:
        $ref: '#/components/messages/activePlayer'
      leaveChannel:
        $ref: '#/components/messages/leaveChannel'
      playChannelTrack:
        $ref: '#/components/messages/playChannelTrack'
      pauseChannelTrack:
        $ref: '#/components/messages/pauseChannelTrack'
      updateChannelMeter:
        $ref: '#/components/messages/updateChannelMeter'
      updateChannelDjs:
        $ref: '#/components/messages/updateChannelDjs'
      updateChannelUsers:
        $ref: '#/components/messages/updateChannelUsers'
      updateChannelUserStatus:
        $ref: '#/components/messages/updateChannelUserStatus'
      updateChannelHistory:
        $ref: '#/components/messages/updateChannelHistory'
      updateChannel:
        $ref: '#/components/messages/updateChannel'
      updateUser:
        $ref: '#/components/messages/updateUser'
      pushChannelMessage:
        $ref: '#/components/messages/pushChannelMessage'
      clearChannelMessages:
        $ref: '#/components/messages/clearChannelMessages'
      pushNotification:
        $ref: '#/components/messages/pushNotification'
      refreshDjStack:
        $ref: '#/components/messages/refreshDjStack'
  wsBot:
    address: /ws-bot
    title: Bots
    description: The connection of a bot. It carries the same messages as `/ws`. The server's `ready` includes the bot's `userName`, `displayName` and `channelId`, and a bot can only `join` its own channel.
    bindings:
      ws:
        bindingVersion: 0.1.0
        query:
          type: object
          required:
            - apiKey
          properties:
            apiKey:
              type: string
              description: The bot's API key. An unknown key closes the socket.
    messages: *clientAndServerMessages

operations:
  # --- what a client sends ------------------------------------------------------------------------------------------
  receiveStayAwake:
    action: receive
    channel: { $ref: '#/channels/ws' }
    summary: Answer a keepAwake
    messages:
      - $ref: '#/channels/ws/messages/stayAwake'
  receiveAppState:
    action: receive
    channel: { $ref: '#/channels/ws' }
    summary: Say whether the app is in view (and whether it is a mobile client)
    messages:
      - $ref: '#/channels/ws/messages/appState'
  receiveJoin:
    action: receive
    channel: { $ref: '#/channels/ws' }
    summary: Join a channel
    description: |
      Leaves the channel the connection is in, if another. On success the server answers, then sends the joiner the
      `playChannelTrack` of the track playing (if any) and the `updateChannelDjs`, and tells the room with
      `updateChannelUsers` (`type: join`). Joining the channel the connection is already in answers with success and
      sends the same state again.
    messages:
      - $ref: '#/channels/ws/messages/join'
    reply:
      channel: { $ref: '#/channels/ws' }
      messages:
        - $ref: '#/channels/ws/messages/response'
        - $ref: '#/channels/ws/messages/errorResponse'
  receiveLeave:
    action: receive
    channel: { $ref: '#/channels/ws' }
    summary: Leave the channel
    description: >-
      Done by the server too when a connection is lost for good, a user logs out or their account is deleted. Tells the room with `updateChannelUsers` (`type: leave`).
    messages:
      - $ref: '#/channels/ws/messages/leave'
    reply:
      channel: { $ref: '#/channels/ws' }
      messages:
        - $ref: '#/channels/ws/messages/response'
        - $ref: '#/channels/ws/messages/errorResponse'
  receiveJoinDjs:
    action: receive
    channel: { $ref: '#/channels/ws' }
    summary: Step up to the decks
    description: Tells the room with `updateChannelDjs`. Fails with `Max DJS Already` when the channel limits its DJs and they are all taken. The first DJ in line has their next track taken from their active queue by the server, and is told with `refreshDjStack`. A bot has no queue, so it is asked for the next track with `nextChannelTrack`.
    messages:
      - $ref: '#/channels/ws/messages/joinDjs'
    reply:
      channel: { $ref: '#/channels/ws' }
      messages:
        - $ref: '#/channels/ws/messages/response'
        - $ref: '#/channels/ws/messages/errorResponse'
  receiveSelectQueue:
    action: receive
    channel: { $ref: '#/channels/ws' }
    summary: Pick which of your queues plays in the channel you are in
    messages:
      - $ref: '#/channels/ws/messages/selectQueue'
    reply:
      channel: { $ref: '#/channels/ws' }
      messages:
        - $ref: '#/channels/ws/messages/response'
        - $ref: '#/channels/ws/messages/errorResponse'
  receiveLeaveDjs:
    action: receive
    channel: { $ref: '#/channels/ws' }
    summary: Step down from the decks, or choose to step down after the current play
    messages:
      - $ref: '#/channels/ws/messages/leaveDjs'
    reply:
      channel: { $ref: '#/channels/ws' }
      messages:
        - $ref: '#/channels/ws/messages/response'
        - $ref: '#/channels/ws/messages/errorResponse'
  receivePushMessage:
    action: receive
    channel: { $ref: '#/channels/ws' }
    summary: Send a chat message
    description: |
      Answered with the sent message's `pushChannelMessage` to the room (not a response). Counts as activity (clears AFK).
      Text is sanitised, links are enriched and `@` mentions are resolved. Chat commands (`/...`) are handled by the
      channel's bot. Only the server and bots may send the other types and formats.
    messages:
      - $ref: '#/channels/ws/messages/pushMessage'
    reply:
      channel: { $ref: '#/channels/ws' }
      messages:
        - $ref: '#/channels/ws/messages/errorResponse'
  receiveUserStatus:
    action: receive
    channel: { $ref: '#/channels/ws' }
    summary: Report typing or activity
    description: Gathered and sent to the room a second or three later as one `updateChannelUserStatus`.
    messages:
      - $ref: '#/channels/ws/messages/userStatus'
    reply:
      channel: { $ref: '#/channels/ws' }
      messages:
        - $ref: '#/channels/ws/messages/response'
  receiveVote:
    action: receive
    channel: { $ref: '#/channels/ws' }
    summary: Vote on the track playing
    description: Updates the room's meter with `updateChannelMeter`. A `dope` or `nope` for the DJ's own track is refused with `Cannot vote for yourself`; the DJ can still `star` it, which is not counted in the track's score. A vote with nothing playing, or one that is both `dope` and `nope`, is ignored without a reply.
    messages:
      - $ref: '#/channels/ws/messages/vote'
    reply:
      channel: { $ref: '#/channels/ws' }
      messages:
        - $ref: '#/channels/ws/messages/response'
        - $ref: '#/channels/ws/messages/errorResponse'
  receivePlayTrack:
    action: receive
    channel: { $ref: '#/channels/ws' }
    summary: Play a track on the user's Spotify
    description: |
      Starts the track on a device of the user's own Spotify account (the one in `device_id`, or the one their settings
      pick). When it switches the device, the user's connections are told with `activePlayer`. For the channel's track,
      pass the `uri` from `playChannelTrack`; the position is then worked out by the server. A `preview` plays any track
      from its start and needs no channel.
    messages:
      - $ref: '#/channels/ws/messages/playTrack'
    reply:
      channel: { $ref: '#/channels/ws' }
      messages:
        - $ref: '#/channels/ws/messages/response'
        - $ref: '#/channels/ws/messages/errorResponse'
  receivePauseTrack:
    action: receive
    channel: { $ref: '#/channels/ws' }
    summary: Pause the user's Spotify
    messages:
      - $ref: '#/channels/ws/messages/pauseTrack'
    reply:
      channel: { $ref: '#/channels/ws' }
      messages:
        - $ref: '#/channels/ws/messages/response'
        - $ref: '#/channels/ws/messages/errorResponse'
  receiveSyncTrack:
    action: receive
    channel: { $ref: '#/channels/ws' }
    summary: Play the channel's track from where it has got to, or pause when nothing is playing
    messages:
      - $ref: '#/channels/ws/messages/syncTrack'
    reply:
      channel: { $ref: '#/channels/ws' }
      messages:
        - $ref: '#/channels/ws/messages/response'
        - $ref: '#/channels/ws/messages/errorResponse'
  receiveRegisterPlayer:
    action: receive
    channel: { $ref: '#/channels/ws' }
    summary: Tell the server which Spotify device is this client's own web player
    description: The server removes it from the user's Spotify devices when the connection goes, so a closed tab does not leave a dead player behind.
    messages:
      - $ref: '#/channels/ws/messages/registerPlayer'
    reply:
      channel: { $ref: '#/channels/ws' }
      messages:
        - $ref: '#/channels/ws/messages/response'
        - $ref: '#/channels/ws/messages/errorResponse'
  receiveDeregisterPlayer:
    action: receive
    channel: { $ref: '#/channels/ws' }
    summary: Say the web player is gone
    messages:
      - $ref: '#/channels/ws/messages/deregisterPlayer'
    reply:
      channel: { $ref: '#/channels/ws' }
      messages:
        - $ref: '#/channels/ws/messages/response'
  receiveNextChannelTrackAnswer:
    action: receive
    channel: { $ref: '#/channels/ws' }
    summary: Answer a nextChannelTrack with the track to play (bot only)
    description: Only a bot is asked, and only a bot's answer is heard. The server waits 2.5 seconds for it. A DJ that does not answer, or answers with an error, is taken off the decks.
    messages:
      - $ref: '#/channels/ws/messages/nextChannelTrackAnswer'
      - $ref: '#/channels/ws/messages/errorResponse'

  # --- what the server sends ----------------------------------------------------------------------------------------
  sendReady:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: The connection is usable
    messages:
      - $ref: '#/channels/ws/messages/ready'
  sendKeepAwake:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: A heart beat (about every minute)
    messages:
      - $ref: '#/channels/ws/messages/keepAwake'
  sendClosed:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: The server is about to close the connection
    messages:
      - $ref: '#/channels/ws/messages/closed'
  sendNextChannelTrack:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: Ask the bot whose turn it is for the track to play (bot only)
    messages:
      - $ref: '#/channels/ws/messages/nextChannelTrack'
    reply:
      channel: { $ref: '#/channels/ws' }
      messages:
        - $ref: '#/channels/ws/messages/nextChannelTrackAnswer'
  sendPlayChannelTrack:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: A track started (or the one playing, to someone who just joined)
    messages:
      - $ref: '#/channels/ws/messages/playChannelTrack'
  sendPauseChannelTrack:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: Nothing is playing any more
    messages:
      - $ref: '#/channels/ws/messages/pauseChannelTrack'
  sendUpdateChannelMeter:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: The votes on the track playing changed
    messages:
      - $ref: '#/channels/ws/messages/updateChannelMeter'
  sendUpdateChannelDjs:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: The DJs in the queue changed
    messages:
      - $ref: '#/channels/ws/messages/updateChannelDjs'
  sendUpdateChannelUsers:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: Someone joined or left the channel
    messages:
      - $ref: '#/channels/ws/messages/updateChannelUsers'
  sendUpdateChannelUserStatus:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: Users typed or were seen
    messages:
      - $ref: '#/channels/ws/messages/updateChannelUserStatus'
  sendUpdateChannelHistory:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: A track finished and was added to the channel's history
    messages:
      - $ref: '#/channels/ws/messages/updateChannelHistory'
  sendUpdateChannel:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: The channel's settings or roles changed
    messages:
      - $ref: '#/channels/ws/messages/updateChannel'
  sendUpdateUser:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: The user's own settings changed (sent to all of their connections)
    messages:
      - $ref: '#/channels/ws/messages/updateUser'
  sendPushChannelMessage:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: A chat message
    messages:
      - $ref: '#/channels/ws/messages/pushChannelMessage'
  sendClearChannelMessages:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: Chat messages were deleted
    messages:
      - $ref: '#/channels/ws/messages/clearChannelMessages'
  sendLeaveChannel:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: Leave the channel (kicked, banned, the channel was deleted, or the user logged out)
    messages:
      - $ref: '#/channels/ws/messages/leaveChannel'
  sendActivePlayer:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: The user's Spotify device in use changed
    messages:
      - $ref: '#/channels/ws/messages/activePlayer'
  sendPushNotification:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: A notification for the user (sent to all of their connections)
    messages:
      - $ref: '#/channels/ws/messages/pushNotification'
  sendRefreshDjStack:
    action: send
    channel: { $ref: '#/channels/ws' }
    summary: >-
      The DJ's queue changed on the server (a track was taken off it): load it again
    messages:
      - $ref: '#/channels/ws/messages/refreshDjStack'

components:
  messages:
    # --- connection ---------------------------------------------------------------------------------------------------
    ready:
      name: ready
      title: ready
      summary: The server is ready for messages
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            properties:
              method: { const: ready }
              params:
                type: object
                properties:
                  joined:
                    type:
                      - string
                      - 'null'
                    description: >-
                      The channel the server has this connection in. A connection that was resumed (a reconnect with the same
                      `clientId`) still has it; a new one, as after the server was restarted, has `null`. A client that was
                      in a channel and gets `null` has to `join` again (and `joinDjs`, if it was a DJ).
                  userName: { type: string, description: Only for a bot. }
                  displayName: { type: string, description: Only for a bot. }
                  channelId: { type: string, description: Only for a bot. }
    keepAwake:
      name: keepAwake
      title: keepAwake
      summary: A heart beat
      description: Answer with `stayAwake`. The server uses the time it takes to measure `latency`.
      payload:
        type: object
        description: Has no `jsonrpc` member, unlike the other messages.
        required: [method, params]
        properties:
          method: { const: keepAwake }
          params:
            type: object
            properties:
              date:
                type: integer
                description: The server's time, in milliseconds since the epoch.
              latency:
                type: integer
                description: The round trip of the last heart beat, in milliseconds.
    stayAwake:
      name: stayAwake
      title: stayAwake
      x-scope: connection
      summary: The answer to keepAwake
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            properties:
              method: { const: stayAwake }
    appState:
      name: appState
      title: appState
      x-scope: connection
      summary: Whether the app is in view
      description: A hidden mobile client is not sent heart beats and is kept for an hour after its socket closes, so it can wake and resume.
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            required: [params]
            properties:
              method: { const: appState }
              params:
                type: object
                required: [hidden]
                properties:
                  hidden: { type: boolean }
                  mobile:
                    type: boolean
                    description: Overrides the server's guess from the user agent.
                  control:
                    type: string
                    enum: [server, browser]
                    description: |
                      Who controls the player of a service whose music the server can play (Spotify). `browser` says the page plays on
                      its own web player: the server then treats the connection as one of a service the browser plays (a `playChannelTrack`
                      to play, `pauseChannelTrack` to stop, no `playTrack` of its own). `server` (the default, until the page says) is
                      every other device. The page says it with every `appState`, which it sends each time it connects.
    closed:
      name: closed
      title: closed
      summary: The server is closing this connection
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            required: [params]
            properties:
              method: { const: closed }
              params:
                type: object
                properties:
                  reason:
                    type: integer
                    enum: [-1, 1]
                    description: '`1` means another client of the same user connected and this one was replaced; reconnecting would replace that one in turn. `-1` is any other reason.'

    # --- channel ------------------------------------------------------------------------------------------------------
    join:
      name: join
      title: join
      x-scope: channel
      x-role: 0
      summary: Join a channel
      payload:
        allOf:
          - $ref: '#/components/schemas/Request'
          - type: object
            required: [params]
            properties:
              method: { const: join }
              params:
                type: object
                required: [channelId]
                properties:
                  channelId:
                    type: string
                    description: The channel's `_id`.
                  password:
                    type: string
                    description: For a private channel with a password, unless the user created the channel.
      examples:
        - payload:
            jsonrpc: '2.0'
            method: join
            params: { channelId: 62bf6a0d2f6774dd199cdd99 }
            id: 4
    leave:
      name: leave
      title: leave
      x-scope: channel
      x-role: 0
      summary: Leave the channel
      payload:
        allOf:
          - $ref: '#/components/schemas/Request'
          - type: object
            properties:
              method: { const: leave }
    joinDjs:
      name: joinDjs
      title: joinDjs
      x-scope: channel
      x-role: 0
      summary: Step up to the decks of the channel the connection is in
      description: >-
        The channel is the one joined: it is not sent, so a client cannot name another.
      payload:
        allOf:
          - $ref: '#/components/schemas/Request'
          - type: object
            properties:
              method: { const: joinDjs }
    leaveDjs:
      name: leaveDjs
      title: leaveDjs
      x-scope: channel
      x-role: 0
      summary: Step down, or choose to step down after the track that is playing
      payload:
        allOf:
          - $ref: '#/components/schemas/Request'
          - type: object
            properties:
              method: { const: leaveDjs }
              params:
                type: object
                properties:
                  stepDownAfterPlay:
                    type: boolean
                    description: When sent, the DJ does not step down now; the choice is kept for the connection (and returned in the reply to `join` and `joinDjs`).
    selectQueue:
      name: selectQueue
      title: selectQueue
      x-scope: channel
      x-role: 0
      summary: Pick which of your queues plays in this channel, until you leave it
      description: |
        A DJ plays from the queue made for the channel they are in (`channelId` on the stack, see `/api/music/stack`) and, where
        there is none, from their general queue. This picks another of their queues in its place, for as long as they are in the
        channel; joining a channel starts again from its own. `stackId: null` goes back to the channel's own. The reply is
        `{ queue }`: the queue in use, as `join` returns it.
      payload:
        allOf:
          - $ref: '#/components/schemas/Request'
          - type: object
            properties:
              method: { const: selectQueue }
              params:
                type: object
                properties:
                  stackId:
                    type: [string, 'null']
                    description: One of the user's own stacks, or null for the channel's own queue.
    pushMessage:
      name: pushMessage
      title: pushMessage
      x-scope: channel
      x-role: 0
      summary: Send a chat message
      payload:
        allOf:
          - $ref: '#/components/schemas/Request'
          - type: object
            required: [params]
            properties:
              method: { const: pushMessage }
              params:
                type: object
                required: [payload]
                properties:
                  payload:
                    type: string
                    description: The message. It cannot be empty and is limited in length (for people; not for the server and bots).
                  type:
                    type: string
                    enum: [chat, whisper, alert, play, expandable, hay, botResponse]
                    description: What kind of message it is. A command typed in the message (`/...`) sets it itself.
                  format:
                    type: string
                    enum: [text, base64image, table]
                    default: text
                  expandable:
                    type: boolean
                  summary:
                    type: string
                    description: The part of an expandable message shown while it is closed.
                  targetUserId:
                    type: string
                    description: Whom a whisper is for.
                  replyTo:
                    type: string
                    description: The message being answered.
      examples:
        - payload:
            jsonrpc: '2.0'
            method: pushMessage
            params: { payload: Hello from the other side., type: chat, expandable: false }
            id: 5
    userStatus:
      name: userStatus
      title: userStatus
      x-scope: user
      x-role: 0
      summary: Report typing or that the user is active
      description: >-
        The client does not need to send `afk` for the messages that count as activity (chat, votes, joining the decks and so on): the server does.
      payload:
        allOf:
          - $ref: '#/components/schemas/Request'
          - type: object
            required: [params]
            properties:
              method: { const: userStatus }
              params:
                type: object
                properties:
                  typing:
                    type: boolean
                  afk:
                    description: Any value; its presence says the user is active.
    vote:
      name: vote
      title: vote
      x-scope: user
      x-role: 0
      summary: Vote on the track playing
      description: Each key present sets that vote. Only one of `dope` and `nope` can be true.
      payload:
        allOf:
          - $ref: '#/components/schemas/Request'
          - type: object
            required: [params]
            properties:
              method: { const: vote }
              params:
                type: object
                properties:
                  dope: { type: boolean }
                  nope: { type: boolean }
                  star:
                    type: boolean
                    description: Stars the track.

    # --- playback -----------------------------------------------------------------------------------------------------
    playTrack:
      name: playTrack
      title: playTrack
      x-scope: music
      x-role: 0
      summary: Play a track on one of the user's Spotify devices
      payload:
        allOf:
          - $ref: '#/components/schemas/Request'
          - type: object
            required: [params]
            properties:
              method: { const: playTrack }
              params:
                type: object
                required: [uri]
                properties:
                  uri:
                    type: string
                    examples: ['spotify:track:63126c61aebd8']
                  device_id:
                    type: string
                    description: The device to play on. Otherwise the user's settings pick one (active, preferred, any, or their web player).
                  preview:
                    type: boolean
                    description: Play the track from its start, outside any channel.
                  albumUri:
                    type: string
                    description: The album the track is on, for a preview. The track is then played from inside its album, which some Android Spotify apps need; without it the album is looked up only if the device does not play the track.
                    examples: ['spotify:album:4aawyAB9vmqN3uQ7FjRGTy']
                  syncTime:
                    type: integer
                    description: Kept for old clients; the server measures the latency.
    pauseTrack:
      name: pauseTrack
      title: pauseTrack
      x-scope: music
      x-role: 0
      summary: Pause the device that was last played on
      payload:
        allOf:
          - $ref: '#/components/schemas/Request'
          - type: object
            properties:
              method: { const: pauseTrack }
    syncTrack:
      name: syncTrack
      title: syncTrack
      x-scope: user
      x-role: 0
      summary: Play the channel's track from its current position
      description: Pauses instead when the channel has nothing playing.
      payload:
        allOf:
          - $ref: '#/components/schemas/Request'
          - type: object
            properties:
              method: { const: syncTrack }
    registerPlayer:
      name: registerPlayer
      title: registerPlayer
      x-scope: music
      x-role: 0
      summary: Register this client's web player
      payload:
        allOf:
          - $ref: '#/components/schemas/Request'
          - type: object
            required: [params]
            properties:
              method: { const: registerPlayer }
              params:
                type: object
                required: [device_id]
                properties:
                  device_id: { type: string }
    deregisterPlayer:
      name: deregisterPlayer
      title: deregisterPlayer
      x-scope: music
      x-role: 0
      summary: The web player is gone
      description: Without a reply (and no work) when `device_id` is `null`.
      payload:
        allOf:
          - $ref: '#/components/schemas/Request'
          - type: object
            required: [params]
            properties:
              method: { const: deregisterPlayer }
              params:
                type: object
                required: [device_id]
                properties:
                  device_id: { type: [string, 'null'] }
    nextChannelTrack:
      name: nextChannelTrack
      title: nextChannelTrack
      summary: The bot whose turn it is is asked for the next track (bot only)
      description: >-
        Answer with the same `id` (see `nextChannelTrackAnswer`) within 2.5 seconds. The `id` is not in sequence for one connection: it comes from a counter the whole server shares.
      payload:
        allOf:
          - $ref: '#/components/schemas/Request'
          - type: object
            required: [id, params]
            properties:
              method: { const: nextChannelTrack }
              params:
                type: object
                properties:
                  userId:
                    type: string
                    description: The DJ asked. A client can check it is itself.
                  channelId:
                    type: string
    nextChannelTrackAnswer:
      name: nextChannelTrackAnswer
      title: nextChannelTrackAnswer
      summary: The track to play next
      description: |
        The Spotify track object (as the Spotify Web API returns it). `duration_ms`, `album.name`, `album.images`, `artists`,
        `uri`, `id` and `name` are used. A response without a `track`, or one that arrives when the DJ is no longer first, is
        ignored; an error response takes the DJ off the decks.
      payload:
        type: object
        required: [jsonrpc, id, result]
        properties:
          jsonrpc: { const: '2.0' }
          id:
            type: integer
            description: The `id` of the `nextChannelTrack`.
          result:
            type: object
            required: [track]
            properties:
              track:
                $ref: '#/components/schemas/Track'
    refreshDjStack:
      name: refreshDjStack
      title: refreshDjStack
      summary: The DJ's queue changed on the server
      description: Sent to the DJ whose track was just taken from the top of their queue, or moved to the end of it when they keep played tracks. Not sent to a bot.
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            properties:
              method: { const: refreshDjStack }
    playChannelTrack:
      name: playChannelTrack
      title: playChannelTrack
      summary: A track is playing in the channel
      description: |
        Sent when a track starts, and to a user who joins while one plays. The client plays `playback.uri` with `playTrack`
        unless `playTrack` is `false`: for a mobile client with Spotify, the server has already sent its own play to
        Spotify and the message is only for the room's state.

        `track` is the DJ's track, of the DJ's service (`track.provider`). `playback` is that same recording at the service the
        listener is signed in with, found by its ISRC, which is not always the DJ's: it is `{ provider, id, uri }` to play,
        `{ provider, unavailable: true }` when their service has not got the track (keep the room's state and play nothing),
        or `{ provider, pending: true }` when it is still being looked for, which is followed by another `playChannelTrack`
        once it is found. A client that has no `playback` plays `track.uri`, as before.
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            required: [params]
            properties:
              method: { const: playChannelTrack }
              params:
                type: object
                properties:
                  playTrack: { type: boolean }
                  track:
                    $ref: '#/components/schemas/Track'
                  voting:
                    $ref: '#/components/schemas/Voting'
                  endsAt:
                    type: integer
                    description: When the track ends, in milliseconds since the epoch.
                  startAt:
                    type: integer
                    description: How far into the track to start, in milliseconds. Take the time the message took into account with `syncTime`.
                  syncTime:
                    type: integer
                    description: The server's time when the message was made.
                  playback:
                    type: object
                    description: The track as the listener's own music service has it. See above.
                    required: [provider]
                    properties:
                      provider: { type: string, enum: [spotify, apple, tidal] }
                      id: { type: string, description: The track's id at the service. }
                      uri: { type: string, description: What to play at the service. }
                      unavailable: { type: boolean }
                      pending: { type: boolean }
    pauseChannelTrack:
      name: pauseChannelTrack
      title: pauseChannelTrack
      summary: >-
        Stop playing: the last DJ stepped down, or no one has a track
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            properties:
              method: { const: pauseChannelTrack }
    updateChannelMeter:
      name: updateChannelMeter
      title: updateChannelMeter
      summary: The votes on the playing track
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            required: [params]
            properties:
              method: { const: updateChannelMeter }
              params:
                type: object
                properties:
                  voting:
                    $ref: '#/components/schemas/Voting'
    activePlayer:
      name: activePlayer
      title: activePlayer
      summary: The user's Spotify device now playing
      description: Sent to all the user's connections after playback was switched to a device, by `playTrack` or by the `PUT /api/music/devices/active` route.
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            required: [params]
            properties:
              method: { const: activePlayer }
              params:
                type: object
                properties:
                  device_id: { type: string }

    # --- the room -----------------------------------------------------------------------------------------------------
    updateChannelDjs:
      name: updateChannelDjs
      title: updateChannelDjs
      summary: The DJs, in the order they play
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            required: [params]
            properties:
              method: { const: updateChannelDjs }
              params:
                type: object
                properties:
                  type: { const: updateDjs }
                  djs:
                    type: array
                    description: The user ids of the DJs. The first is the one playing.
                    items: { type: string }
                  syncTime: { type: integer }
    updateChannelUsers:
      name: updateChannelUsers
      title: updateChannelUsers
      summary: Who is in the channel
      description: A user a receiver has blocked (or who blocked the receiver) is replaced by an `Unknown User` with `_id` `#` and the default images.
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            required: [params]
            properties:
              method: { const: updateChannelUsers }
              params:
                type: object
                properties:
                  type:
                    type: string
                    description: Why it was sent, such as `join` or `leave`.
                  syncTime: { type: integer }
                  users:
                    type: array
                    items:
                      $ref: '#/components/schemas/ChannelUser'
                  usersInRegion:
                    type: object
                    description: The number of listeners by country code.
                    additionalProperties: { type: integer }
    updateChannelUserStatus:
      name: updateChannelUserStatus
      title: updateChannelUserStatus
      summary: Who was seen or typing lately
      description: |
        The key of each entry is a user id (blocked users' entries are left out for the receiver). It is sent a second or
        three after the first status of a batch.
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            required: [params]
            properties:
              method: { const: updateChannelUserStatus }
              params:
                type: object
                additionalProperties:
                  type: object
                  properties:
                    lastSeen:
                      type: integer
                      description: When the user last did something, in milliseconds since the epoch.
                    lastTyping:
                      type: integer
    updateChannelHistory:
      name: updateChannelHistory
      title: updateChannelHistory
      summary: A track that finished
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            required: [params]
            properties:
              method: { const: updateChannelHistory }
              params:
                type: object
                properties:
                  track:
                    $ref: '#/components/schemas/Track'
                  voteSummary:
                    type: object
                    description: The votes the track ended with.
                    additionalProperties: true
                  timestamp:
                    type: integer
                    description: When the track started.
                  skipped:
                    type: boolean
                  playedBy:
                    type: object
                    description: The user (or the channel's bot) who played it.
                    properties:
                      userName: { type: string }
                      displayName: { type: string }
                    additionalProperties: true
                  syncTime: { type: integer }
    updateChannel:
      name: updateChannel
      title: updateChannel
      summary: The channel changed
      description: Sent when it was edited, a role was changed or someone was banned or unbanned. After an edit it includes the channel's `bot`.
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            required: [params]
            properties:
              method: { const: updateChannel }
              params:
                type: object
                properties:
                  syncTime: { type: integer }
                  channel:
                    type: object
                    description: The channel, without its password hash (and without its Last.fm and Discord settings unless the receiver is its admin).
                    additionalProperties: true
                  bot:
                    type: object
                    additionalProperties: true
    pushChannelMessage:
      name: pushChannelMessage
      title: pushChannelMessage
      summary: A chat message
      description: |
        A message from a user the receiver has blocked is not sent to them. `userId` is `server` or `bot` when the message
        is from RVRB or the channel's bot. System messages (announcements, a moderator deleting messages) arrive with
        `type: alert` and without a user.
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            required: [params]
            properties:
              method: { const: pushChannelMessage }
              params:
                type: object
                properties:
                  deleted: { type: boolean }
                  userId: { type: string }
                  userName: { type: string }
                  type:
                    type: string
                    enum: [chat, whisper, alert, play, expandable, hay, botResponse]
                  payload:
                    description: >-
                      The sanitised message, as HTML. A table is sent as `{ type: repeatingTable | standard, ... }`.
                  expandable: { type: boolean }
                  summary: { type: string }
                  syncTime:
                    type: integer
                    description: When it was sent. Together with the channel it names the message (it is how `clearChannelMessages` finds one).
                  fromUserId: { type: string }
                  fromChannelId: { type: string }
                  fromChannelName: { type: string }
                  replyTo: { type: string }
    clearChannelMessages:
      name: clearChannelMessages
      title: clearChannelMessages
      summary: Delete chat messages
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            required: [params]
            properties:
              method: { const: clearChannelMessages }
              params:
                type: object
                properties:
                  channelId: { type: string }
                  syncTime:
                    type: array
                    description: The `syncTime` of each message to remove. Without it, the whole chat is cleared.
                    items: { type: integer }
    leaveChannel:
      name: leaveChannel
      title: leaveChannel
      summary: Go back to the lobby
      description: The user is no longer in the channel on the server (they were removed, banned, or logged out, or the channel was deleted).
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            required: [params]
            properties:
              method: { const: leaveChannel }
              params:
                type: object
                properties:
                  channelId: { type: string }
    updateUser:
      name: updateUser
      title: updateUser
      summary: The user's own account changed
      description: Sent to all the connections of the user after `PATCH /api/users/{userId}` or muting and unmuting a user.
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            required: [params]
            properties:
              method: { const: updateUser }
              params:
                type: object
                properties:
                  syncTime: { type: integer }
                  user:
                    type: object
                    description: The user's saved account, with their settings.
                    additionalProperties: true
    pushNotification:
      name: pushNotification
      title: pushNotification
      summary: A new or updated notification
      payload:
        allOf:
          - $ref: '#/components/schemas/Notification'
          - type: object
            required: [params]
            properties:
              method: { const: pushNotification }
              params:
                type: object
                properties:
                  notification:
                    $ref: '#/components/schemas/UserNotification'

    # --- answers ------------------------------------------------------------------------------------------------------
    response:
      name: response
      title: response
      summary: A success
      description: Sent for a request that had an `id`.
      payload:
        type: object
        required: [jsonrpc, id, result]
        properties:
          jsonrpc: { const: '2.0' }
          id:
            type: integer
          result:
            type: object
            description: |
              `{ "message": "success" }` unless the request says otherwise: `join` and `joinDjs` return
              `{ stepDownAfterPlay }`, and `join` and `selectQueue` the queue the user plays from there: `queue`.
            properties:
              message: { type: string }
              stepDownAfterPlay: { type: boolean }
              queue:
                description: The queue the user plays from in the channel, or null where they have none.
                oneOf:
                  - type: 'null'
                  - type: object
                    properties:
                      stackId: { type: string }
                      name: { type: string }
                      source:
                        type: string
                        enum: [channel, override, general]
            additionalProperties: true
    errorResponse:
      name: errorResponse
      title: errorResponse
      summary: A failure
      description: |
        The messages a client may need to tell apart:

        * `Not Allowed`: sent a channel message without having joined one.
        * `Not allowed to join that channel`: a bot tried a channel that is not its own.
        * `Unauthorized`: the caller's role in the channel is too low.
        * `UC:Unknown Channel`, `BN:You're banned from <title>`, `PR:Password required to join <title>`, `PW:Wrong Password`,
          `UANF:User Account Not Found`, `Channel Not Joinable.`: why a `join` was refused. The text before the first `:` is a
          code.
        * `This session belongs to a different Spotify account. Log in again.`: a `music` message came from a user whose
          Spotify token is another account's (`SPOTIFY_ACCOUNT_MISMATCH`). End the session and log in again.
        * `Spotify no longer accepts this session. Log in again.`: a `music` message came from a user whose Spotify refresh token Spotify has revoked or expired (`SPOTIFY_TOKEN_REVOKED`). The message was not carried out. End the session and log in again.
        * `Could not refresh spotify token: 403`: the Spotify token could not be refreshed (the error is then a bare string, as is `Not Allowed`).
      payload:
        $ref: '#/components/schemas/ErrorResponse'

  schemas:
    Request:
      type: object
      required: [jsonrpc, method]
      properties:
        jsonrpc: { const: '2.0' }
        method: { type: string }
        params: { type: object }
        id:
          type: integer
          description: Asks for an answer carrying the same id.
    Notification:
      type: object
      required: [jsonrpc, method]
      properties:
        jsonrpc:
          const: '2.0'
          description: Every message the server sends has it, except `keepAwake`, which is a bare `{ method, params }`.
        method: { type: string }
        params: { type: object }
    ErrorResponse:
      type: object
      required: [jsonrpc, id, error]
      properties:
        jsonrpc: { const: '2.0' }
        id:
          type: integer
        error:
          oneOf:
            - type: object
              required: [message]
              properties:
                message: { type: string }
            - type: string
              description: >-
                Only `Not Allowed`, `Not allowed to join that channel` and `Could not refresh spotify token: 403`.
    Voting:
      type: object
      description: The votes of the track. Each voter's entry is keyed by their user id; the counts are totals.
      properties:
        dope: { type: integer }
        nope: { type: integer }
        star: { type: integer }
      additionalProperties: true
    Track:
      type: object
      description: >-
        A track, with the fields of a Spotify track object as the Spotify Web API returns it, whichever service it is from, and the
        service, the recording and where else the track is known.
      properties:
        id: { type: string, description: The track's id at its `provider`. }
        uri: { type: string, description: What plays the track at its `provider`. }
        provider:
          type: string
          enum: [spotify, apple, tidal]
          description: The service `id` and `uri` are of, which is the DJ's. A track with none is a Spotify one.
        isrc: { type: string, description: The recording, which is how the track is found at another service. }
        refs:
          type: object
          description: The ids of the track at the services it has been found at, by service.
          additionalProperties: { type: string }
        name: { type: string }
        duration_ms: { type: integer }
        artists:
          type: array
          items:
            type: object
            properties:
              name: { type: string }
            additionalProperties: true
        album:
          type: object
          properties:
            name: { type: string }
            images:
              type: array
              items:
                type: object
                properties:
                  url: { type: string }
                additionalProperties: true
          additionalProperties: true
      additionalProperties: true
    ChannelUser:
      type: object
      description: A user in the channel, as the room sees them. The email, links, Spotify uri, API key, and the account's settings are removed; the country and profile settings are only there when the user shows them.
      properties:
        _id: { type: string }
        userName: { type: string }
        displayName: { type: string }
        image: { type: string }
        djImage: { type: string }
        thumbsUpImage: { type: string }
        thumbsDownImage: { type: string }
        role:
          type: integer
        mobile: { type: boolean }
      additionalProperties: true
    UserNotification:
      type: object
      properties:
        _id: { type: string }
        title: { type: string }
        icon: { type: string }
        message: { type: string }
        originalString: { type: string }
        relatedUser: { type: string }
        relatedChannel: { type: string }
        type: { type: string }
        visualIndicator: { type: boolean }
        occurrences: { type: integer }
        createdDate: { type: string, format: date-time }
      additionalProperties: true
