openapi: 3.1.0
info:
  title: collectr API
  version: "1.3.0"
  description: |
    HTTP API of collectr, the inventory for museums, collections and archives.
    Everything the web app does goes through this API, so scripts and AI agents can
    do the same: search, read, create and edit objects, manage collections and
    attachments, and run data-quality reports.

    Instructions for AI agents: [/api-docs/guide.md](/api-docs/guide.md), summed up in the
    **Agents** section below.

    ## Authentication
    Send HTTP **Basic auth** (`Authorization: Basic base64(username:password)`) with
    every request. Do not log in or keep sessions; ignore `Set-Cookie`. Use a
    dedicated account for each integration and make it a member of the
    organisation(s) it works for, nothing more.

    ## Data model
    - **Owner**: a user or an organisation. Everything belongs to exactly one owner.
      Users relate to an organisation as *owner* (one user), *member* (can edit) or
      *guest* (can read).
    - **Object**: one item. `data` is a flat map of `fieldId -> string`. Fields are
      defined by the object's **template**: `defaultobjtemplate` for objects,
      `defaultmediatemplate` for media (photos, documents, films).
    - **Collection**: a named group of objects of one owner. An object lists its
      collections in `collections`. Objects in a `public` collection, and their
      files, are visible to everyone. Being linked from a public object does not
      make an object public.
    - **Attachment**: a file (image, PDF, video, ...) stored on an object.
    - **References**: links between objects (`references`, a list of object ids).
    - **Field visibility**: an organisation can hide fields per role
      (`templatesettings`). Hidden fields are left out of every response.

    ## Conventions
    - Ids are opaque strings. Links to resources come as `location` (a path).
    - Errors are plain-text status codes: `400` invalid input, `401` missing or
      wrong credentials, `403` not allowed, `404` not found, `409` save conflict.
    - `PUT` on objects and collections **replaces** the whole document.
    - All object values are strings, also numbers and dates.

    ## Agents
    1. Discover first: `GET /owners`, then `GET /templates/{id}` and
       `GET /maintenance/fields?o=` to learn which fields exist.
    2. Always `GET` an object right before you `PUT` it and send the whole object
       back with your changes. Set `modified` (ISO date) and `modifiedby`.
    3. Only use field ids that exist in the template. For `selection` fields use
       one of the listed values.
    4. Keep the language of the data (mostly German). Do not translate.
    5. Prefer empty over guessed.
    6. Never call endpoints tagged *Account*, and never delete without explicit
       instruction from a person.
    7. At most a few requests per second.
  contact:
    name: collectr
    url: https://the.collectr.eu
servers:
  # relative: the host this document was loaded from
  - url: /
    description: This server
  - url: https://the.collectr.eu
    description: collectr

security:
  - basicAuth: []

tags:
  - name: Owners
    description: Who you can act as.
  - name: Organisations
  - name: Templates
    description: Field definitions for objects and media.
  - name: Objects
  - name: Attachments
  - name: Collections
  - name: Maintenance
    description: Read-only data-quality reports. Members only.
  - name: Export
  - name: Public
    description: No authentication. Only data in public collections.
  - name: Users
  - name: Account
    description: Sign-up and password recovery. Meant for people, not for agents.

paths:
  # ---------------------------------------------------------------- Owners
  /owners:
    get:
      tags: [Owners]
      operationId: listOwners
      summary: List the owners you can act for
      description: Your own user plus every organisation you are owner, member or guest of. Use the ids as the `o` parameter elsewhere.
      responses:
        "200":
          description: Owners
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/Link" }
              example:
                - { id: 46de5198e86b4b1cf9f8b1912090ac90, location: /organisations/46de5198e86b4b1cf9f8b1912090ac90 }
        "401": { $ref: "#/components/responses/Unauthorized" }

  /owners/{ownerId}:
    get:
      tags: [Owners]
      operationId: resolveOwner
      summary: Find out whether an owner is a user or an organisation
      description: Redirects (303) to `/users/{id}` or `/organisations/{id}`.
      security: []
      parameters:
        - $ref: "#/components/parameters/ownerId"
      responses:
        "303":
          description: See Location
          headers:
            Location: { schema: { type: string } }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Link" }
        "404": { $ref: "#/components/responses/NotFound" }

  /owners/{ownerId}/picture:
    parameters:
      - $ref: "#/components/parameters/ownerId"
    get:
      tags: [Owners]
      operationId: getOwnerPicture
      summary: Profile picture or logo (PNG, 240x240)
      security: []
      responses:
        "200":
          description: Image
          content:
            image/png: { schema: { type: string, format: binary } }
            image/jpeg: { schema: { type: string, format: binary } }
        "404": { $ref: "#/components/responses/NotFound" }
    post:
      tags: [Owners]
      operationId: uploadOwnerPicture
      summary: Replace the profile picture or logo
      description: Allowed for the user themself, or for an organisation's owner.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [picture]
              properties:
                picture: { type: string, format: binary }
      responses:
        "200":
          description: Stored
          content:
            application/json:
              schema:
                type: object
                properties:
                  picture: { type: string, description: URL of the new picture }
        "403": { $ref: "#/components/responses/Forbidden" }

  # ---------------------------------------------------------------- Organisations
  /organisations:
    get:
      tags: [Organisations]
      operationId: listOrganisations
      summary: Organisations you are member or guest of
      parameters:
        - name: q
          in: query
          description: Name prefix.
          schema: { type: string }
      responses:
        "200":
          description: Organisations
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/Link" }
    post:
      tags: [Organisations]
      operationId: createOrganisation
      summary: Create an organisation
      description: "`owner` must be your own user id. You become its owner and first member."
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, owner]
              properties:
                name: { type: string }
                owner: { type: string }
      responses:
        "201":
          description: Created
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
        "403": { $ref: "#/components/responses/Forbidden" }

  /organisations/{organisationId}:
    parameters:
      - name: organisationId
        in: path
        required: true
        schema: { type: string }
    get:
      tags: [Organisations]
      operationId: getOrganisation
      summary: Get an organisation
      description: Includes members, guests, field visibility settings and your permissions on it.
      responses:
        "200":
          description: Organisation
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Organisation" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
    put:
      tags: [Organisations]
      operationId: updateOrganisation
      summary: Update an organisation
      description: |
        Owner only. Only the properties you send are changed (merge, not replace).
        This is also how members and guests are managed: send the complete new
        `members` or `guests` list.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/Organisation" }
      responses:
        "200": { description: Saved }
        "403": { $ref: "#/components/responses/Forbidden" }
    delete:
      tags: [Organisations]
      operationId: deleteOrganisation
      summary: Delete an organisation with all its objects and collections
      description: Owner only. **Irreversible.** Agents must never call this.
      responses:
        "200":
          description: Deleted
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Deleted" }
        "403": { $ref: "#/components/responses/Forbidden" }

  # ---------------------------------------------------------------- Templates
  /templates/{templateId}:
    get:
      tags: [Templates]
      operationId: getTemplate
      summary: Field definitions of a template (XML)
      description: |
        Fields are grouped in sections (`type="section"`). Field types: `text`
        (one line), `multitext` (several lines) and `selection` (one of the listed
        `<values>`). Labels in `de` and mostly `en`. Organisations can use fields that
        are not in the template; `GET /maintenance/fields` lists what is really used.
      security: []
      parameters:
        - $ref: "#/components/parameters/templateId"
      responses:
        "200":
          description: Template
          content:
            application/xml:
              schema: { type: string }
              example: |
                <template>
                 <field id="general" type="section">
                  <label lang="de">Allgemein</label>
                  <fields>
                    <field id="title" type="text">
                      <label lang="de">Titel</label>
                      <label lang="en">Title</label>
                    </field>
                  </fields>
                 </field>
                </template>

  /objects/templates:
    get:
      tags: [Templates]
      operationId: listTemplatesUsedByOwner
      summary: Templates an owner's objects use
      security: []
      parameters:
        - $ref: "#/components/parameters/ownerQueryRequired"
      responses:
        "200":
          description: Template ids
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/Id" }

  # ---------------------------------------------------------------- Objects
  /objects/search:
    get:
      tags: [Objects]
      operationId: searchObjects
      summary: Search and page through an owner's objects
      parameters:
        - $ref: "#/components/parameters/ownerQuery"
        - name: q
          in: query
          required: true
          description: |
            JSON filter `{"fieldId": ["value", ...], "all": ["value"]}`. Matching is
            case-insensitive and finds values that start or end with the term. Several
            values in one field must all match. `all` searches every visible field.
            Values starting with `<` or `>` are numeric ranges (`">1900"`). `{}`
            returns everything. Invalid JSON returns 500.
          schema: { type: string }
          examples:
            all: { value: "{}" }
            field: { value: '{"category":["zubehör"]}' }
            fulltext: { value: '{"all":["hupe"]}' }
            range: { value: '{"height":[">100"]}' }
        - $ref: "#/components/parameters/templateFilter"
        - name: c
          in: query
          description: Only objects in this collection.
          schema: { type: string }
        - name: limit
          in: query
          schema: { type: integer, default: 48 }
        - name: offset
          in: query
          description: The `bookmark` from the previous page (opaque string, not a number).
          schema: { type: string }
        - name: sort
          in: query
          description: Field to sort by; prefix `-` for descending.
          schema: { type: string, default: -created }
        - name: fields
          in: query
          description: JSON array of field ids. Rows then contain only these fields, not the whole document. Much smaller responses.
          schema: { type: string, example: '["title","inventorynumber"]' }
        - name: countmatchingfields
          in: query
          description: If set, returns a map of field id to number of matches for the term in `q` (a plain string here, not JSON) instead of objects.
          schema: { type: boolean }
      responses:
        "200":
          description: One page of results
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SearchResult" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { description: Owner not found }

  /objects/fieldvalues:
    get:
      tags: [Objects]
      operationId: listFieldValues
      summary: Values already used in a field (autocomplete)
      description: Use it to stay consistent with existing spelling.
      parameters:
        - $ref: "#/components/parameters/ownerQuery"
        - $ref: "#/components/parameters/fieldQuery"
        - name: q
          in: query
          description: Prefix, case-insensitive. Without it, values are sorted alphabetically; with it, most used first.
          schema: { type: string }
        - name: limit
          in: query
          schema: { type: integer, default: 100, maximum: 200 }
      responses:
        "200":
          description: Values with counts
          content:
            application/json:
              schema:
                type: object
                properties:
                  values:
                    type: array
                    items: { $ref: "#/components/schemas/ValueCount" }
                  more: { type: integer, description: Matches that did not fit }
                  truncated: { type: boolean, description: "If true, `more` is a lower bound" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /objects:
    post:
      tags: [Objects]
      operationId: createObject
      summary: Create an object
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ObjectWrite" }
      responses:
        "201":
          description: Created
          headers:
            Location: { schema: { type: string } }
          content:
            application/json:
              schema:
                type: object
                properties:
                  location: { type: string, example: /objects/034d51ac8231d62e500da831a200eee6 }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /objects/bulk:
    post:
      tags: [Objects]
      operationId: createObjects
      summary: Create many objects at once
      description: Creates only, never updates. Each entry is a `data` map. `created_by`, `created_on`, `modified_by` and `modified_on` inside an entry are moved to the object's metadata.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [ownerid, objects]
              properties:
                ownerid: { type: string }
                template: { $ref: "#/components/schemas/TemplateId" }
                objects:
                  type: array
                  items: { $ref: "#/components/schemas/ObjectData" }
      responses:
        "201":
          description: One result per object, in order. Check each for `error`.
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  properties:
                    id: { type: string }
                    rev: { type: string }
                    error: { type: string }
        "403": { $ref: "#/components/responses/Forbidden" }

  /objects/{objectId}:
    parameters:
      - $ref: "#/components/parameters/objectId"
    get:
      tags: [Objects]
      operationId: getObject
      summary: Get an object
      description: With `?pdf=1` returns a printable PDF data sheet instead.
      parameters:
        - name: pdf
          in: query
          schema: { type: boolean }
      responses:
        "200":
          description: The object
          headers:
            ETag: { schema: { type: string } }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Object" }
            application/pdf:
              schema: { type: string, format: binary }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
    put:
      tags: [Objects]
      operationId: replaceObject
      summary: Replace an object
      description: |
        **Full replacement.** Send the complete object from `GET` with your changes.
        Fields missing from `data` are deleted. `owner` and `template` are required.
        `id`, `type` and `attachments` are kept from the stored object. The server
        does not stamp edits: set `modified` and `modifiedby` yourself.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/ObjectWrite" }
      responses:
        "200": { description: Saved (empty body) }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
        "409": { description: "Save conflict: read the object again and retry" }
    delete:
      tags: [Objects]
      operationId: deleteObject
      summary: Delete an object
      description: Irreversible. Agents must only delete when a person asked for it.
      responses:
        "200":
          description: Deleted
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Deleted" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
    options:
      tags: [Objects]
      operationId: getObjectRights
      summary: What you may do with an object
      description: The `Allow` header lists the methods, e.g. `OPTIONS, GET, PUT, DELETE`.
      responses:
        "200":
          description: Rights
          headers:
            Allow: { schema: { type: string } }

  /objects/{objectId}/references:
    get:
      tags: [Objects]
      operationId: getObjectReferences
      summary: Objects linked to and from this object
      description: Only linked objects you may read, with hidden fields removed. Links to deleted objects are left out.
      parameters:
        - $ref: "#/components/parameters/objectId"
      responses:
        "403": { $ref: "#/components/responses/Forbidden" }
        "200":
          description: Linked objects
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/Object" }

  /objects/{objectId}/previewpicture:
    get:
      tags: [Objects]
      operationId: getObjectPreviewPicture
      summary: Which attachment represents the object
      description: The highlighted image, else the first image, else one from a linked object.
      parameters:
        - $ref: "#/components/parameters/objectId"
      responses:
        "200":
          description: Preview
          content:
            application/json:
              schema:
                type: object
                properties:
                  att: { $ref: "#/components/schemas/Attachment" }
                  docId: { type: string, description: Object the attachment belongs to }

  # ---------------------------------------------------------------- Attachments
  /objects/{objectId}/attachments:
    parameters:
      - $ref: "#/components/parameters/objectId"
    get:
      tags: [Attachments]
      operationId: listAttachments
      summary: List an object's attachments
      description: |
        The attachments come in the order they were uploaded, unless they were
        reordered with `PUT /objects/{objectId}/attachments`.

        Readers of the owner see all of them. Anyone else only sees the attachments of objects in a public collection.
      responses:
        "403": { $ref: "#/components/responses/Forbidden" }
        "200":
          description: Attachments
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/Attachment" }
    post:
      tags: [Attachments]
      operationId: uploadAttachment
      summary: Upload a file to an object
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [uploadFile]
              properties:
                uploadFile: { type: string, format: binary }
      responses:
        "201":
          description: Created
          headers:
            Location: { schema: { type: string } }
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Attachment" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
    put:
      tags: [Attachments]
      operationId: orderAttachments
      summary: Change the order of an object's attachments
      description: |
        Send the ids of all the object's attachments in the new order, each once.
        Listing the attachments then returns them in this order.

        The object's preview picture is the image in its `highlighted` field.
        Without one, it is the first image in this order.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [order]
              properties:
                order:
                  type: array
                  items: { type: string }
                  description: Attachment ids (`id`), every attachment of the object exactly once
            example:
              order:
                - 5f1c2a9e-7d43-4b8a-9e21-3c6f0d8a41b2.jpeg
                - 9a07e3d1-2b5c-4f6e-8a19-d4c7b0e5f2c4.png
                - 0d3e8b6a-c1f9-47d2-b5a3-6e9f2c0d4871.pdf
      responses:
        "200":
          description: Saved
          content:
            application/json:
              schema:
                type: object
                properties:
                  order: { type: array, items: { type: string } }
        "400": { description: "`order` is missing or not an array" }
        "401": { description: Not allowed to change this object }
        "404": { $ref: "#/components/responses/NotFound" }
        "409": { description: "`order` does not list every attachment of the object exactly once, e.g. after an upload or delete in between: list the attachments again and retry" }

  /objects/{objectId}/attachments/{attachmentId}:
    parameters:
      - $ref: "#/components/parameters/objectId"
      - $ref: "#/components/parameters/attachmentId"
    get:
      tags: [Attachments]
      operationId: getAttachment
      summary: Download an attachment, or get a resized preview
      description: |
        By default images are returned resized, videos and PDFs as a preview image.
        Use `download=1` for the original file. Send the request with
        `Content-Type: application/json` to get the metadata instead.

        Readers of the owner get every file. Anyone else only gets files of objects
        in a public collection, delivered like the public route: watermarked if the
        owner requires it. A watermarked preview that cannot be rendered fails with
        500; the original is never sent in its place.
      parameters:
        - $ref: "#/components/parameters/attDownload"
        - $ref: "#/components/parameters/attFile"
        - $ref: "#/components/parameters/attWidth"
        - $ref: "#/components/parameters/attHeight"
        - $ref: "#/components/parameters/attRotation"
        - $ref: "#/components/parameters/attWatermark"
      responses:
        "200":
          description: File, preview image, or metadata
          content:
            "*/*": { schema: { type: string, format: binary } }
            application/json: { schema: { $ref: "#/components/schemas/Attachment" } }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
        "500": { description: "The preview could not be rendered" }
    put:
      tags: [Attachments]
      operationId: updateAttachment
      summary: Change rotation and metadata of an attachment
      description: Both values are replaced; send both.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                rotation: { type: integer, enum: [0, 90, 180, 270] }
                metadata: { type: object, description: "Free-form, e.g. caption or photographer" }
      responses:
        "200": { description: Saved }
        "401": { description: Not allowed to change this object }
        "404": { $ref: "#/components/responses/NotFound" }
    delete:
      tags: [Attachments]
      operationId: deleteAttachment
      summary: Delete an attachment
      description: Irreversible. Agents must only delete when a person asked for it.
      responses:
        "200":
          description: Deleted
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Deleted" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }

  # ---------------------------------------------------------------- Collections
  /collections:
    get:
      tags: [Collections]
      operationId: listCollections
      summary: An owner's collections
      parameters:
        - $ref: "#/components/parameters/ownerQuery"
        - name: q
          in: query
          description: Name prefix.
          schema: { type: string }
      responses:
        "200":
          description: Collections
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  properties:
                    id: { type: string }
                    location: { type: string }
                    name: { type: string }
                    public: { type: boolean }
        "403": { $ref: "#/components/responses/Forbidden" }
    post:
      tags: [Collections]
      operationId: createCollection
      summary: Create a collection
      description: To put objects into it, add its id to each object's `collections`.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/Collection" }
      responses:
        "201":
          description: Created
          headers:
            Location: { schema: { type: string } }
          content:
            application/json:
              schema:
                type: object
                properties:
                  location: { type: string }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /collections/{collectionId}:
    parameters:
      - $ref: "#/components/parameters/collectionId"
    get:
      tags: [Collections]
      operationId: getCollection
      summary: Get a collection
      responses:
        "200":
          description: Collection
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Collection" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
    put:
      tags: [Collections]
      operationId: replaceCollection
      summary: Replace a collection
      description: Full replacement; `owner` and `name` are required.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/Collection" }
      responses:
        "200": { description: Saved }
        "403": { $ref: "#/components/responses/Forbidden" }
        "404": { $ref: "#/components/responses/NotFound" }
    delete:
      tags: [Collections]
      operationId: deleteCollection
      summary: Delete a collection
      description: The objects stay; only the grouping is removed.
      responses:
        "200":
          description: Deleted
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Deleted" }
        "403": { $ref: "#/components/responses/Forbidden" }

  # ---------------------------------------------------------------- Maintenance
  /maintenance/stats:
    get:
      tags: [Maintenance]
      operationId: getMaintenanceStats
      summary: Object counts per template and illustration state
      parameters:
        - $ref: "#/components/parameters/ownerQuery"
      responses:
        "200":
          description: Stats
          content:
            application/json:
              schema:
                type: object
                properties:
                  templates:
                    type: object
                    additionalProperties:
                      type: object
                      properties:
                        objects: { type: integer }
                        image: { type: integer, description: With at least one image }
                        noimage: { type: integer, description: "With attachments, none an image" }
                        none: { type: integer, description: Without attachments }
        "403": { $ref: "#/components/responses/Forbidden" }

  /maintenance/fields:
    get:
      tags: [Maintenance]
      operationId: getMaintenanceFields
      summary: Every field in use, with how many objects fill it
      parameters:
        - $ref: "#/components/parameters/ownerQuery"
        - $ref: "#/components/parameters/maintTemplate"
      responses:
        "200":
          description: Fields
          content:
            application/json:
              schema:
                type: object
                properties:
                  template: { type: string }
                  fields:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string }
                        objects: { type: integer }
        "403": { $ref: "#/components/responses/Forbidden" }

  /maintenance/values:
    get:
      tags: [Maintenance]
      operationId: getMaintenanceValues
      summary: Distinct values of a field, with counts
      description: Shows spelling variants and inconsistent values.
      parameters:
        - $ref: "#/components/parameters/ownerQuery"
        - $ref: "#/components/parameters/maintTemplate"
        - $ref: "#/components/parameters/fieldQuery"
        - name: q
          in: query
          description: Prefix.
          schema: { type: string }
        - name: sort
          in: query
          schema: { type: string, enum: [value, count], default: value }
        - $ref: "#/components/parameters/pageOffset"
        - name: limit
          in: query
          schema: { type: integer, default: 100, maximum: 500 }
      responses:
        "200":
          description: Values
          content:
            application/json:
              schema:
                type: object
                properties:
                  template: { type: string }
                  field: { type: string }
                  total: { type: integer, description: Number of distinct values }
                  objects: { type: integer, description: Objects with a value }
                  offset: { type: integer }
                  values:
                    type: array
                    items: { $ref: "#/components/schemas/ValueCount" }
        "403": { $ref: "#/components/responses/Forbidden" }

  /maintenance/objects:
    get:
      tags: [Maintenance]
      operationId: getMaintenanceObjects
      summary: Objects with a given value in a field
      parameters:
        - $ref: "#/components/parameters/ownerQuery"
        - $ref: "#/components/parameters/maintTemplate"
        - $ref: "#/components/parameters/fieldQuery"
        - name: value
          in: query
          required: true
          schema: { type: string }
        - $ref: "#/components/parameters/pageOffset"
        - name: limit
          in: query
          schema: { type: integer, default: 50, maximum: 200 }
      responses:
        "200":
          description: Objects (id and title)
          content:
            application/json:
              schema:
                type: object
                properties:
                  template: { type: string }
                  field: { type: string }
                  value: { type: string }
                  offset: { type: integer }
                  more: { type: boolean }
                  objects:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string }
                        title: { type: string }
        "403": { $ref: "#/components/responses/Forbidden" }

  /maintenance/mediaobjects:
    get:
      tags: [Maintenance]
      operationId: getMaintenanceMediaObjects
      summary: Objects by illustration state
      parameters:
        - $ref: "#/components/parameters/ownerQuery"
        - $ref: "#/components/parameters/maintTemplate"
        - name: state
          in: query
          description: Comma-separated `image`, `noimage`, `none`.
          schema: { type: string, example: none }
        - $ref: "#/components/parameters/pageOffset"
        - name: limit
          in: query
          schema: { type: integer, default: 100, maximum: 500 }
      responses:
        "200":
          description: Objects
          content:
            application/json:
              schema:
                type: object
                properties:
                  template: { type: string }
                  state: { type: string }
                  offset: { type: integer }
                  more: { type: boolean }
                  objects:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string }
                        title: { type: string }
                        attachments: { type: integer }
                        images: { type: integer }
        "403": { $ref: "#/components/responses/Forbidden" }

  # ---------------------------------------------------------------- Export
  /export/objects:
    get:
      tags: [Export]
      operationId: exportObjects
      summary: Export all of an owner's objects as CSV in a ZIP
      description: |
        The ZIP holds `collectr-object-export.csv` plus every attachment under
        `files/{objectId}/`. With `exportoptions={"dataOnly":true}` only the CSV.
        Large owners take minutes; prefer paging `/objects/search` for agents.
      parameters:
        - $ref: "#/components/parameters/ownerQuery"
        - name: export
          in: query
          schema: { type: string, enum: [csv], default: csv }
        - name: exportoptions
          in: query
          schema: { type: string, example: '{"dataOnly":true}' }
      responses:
        "200":
          description: ZIP archive
          content:
            application/zip: { schema: { type: string, format: binary } }
        "403": { $ref: "#/components/responses/Forbidden" }

  # ---------------------------------------------------------------- Public
  /objects/public-search:
    get:
      tags: [Public]
      operationId: searchPublicObjects
      summary: Search the objects of a public collection
      description: Same parameters and response as `/objects/search`; `o` and `c` are required. Also available as `/public-objects/public-search`.
      security: []
      parameters:
        - $ref: "#/components/parameters/ownerQueryRequired"
        - name: c
          in: query
          required: true
          schema: { type: string }
        - name: q
          in: query
          required: true
          schema: { type: string, default: "{}" }
        - name: limit
          in: query
          schema: { type: integer, default: 48 }
        - name: offset
          in: query
          schema: { type: string }
      responses:
        "200":
          description: Results
          content:
            application/json:
              schema: { $ref: "#/components/schemas/SearchResult" }
        "404": { description: Owner not found }

  /public-objects/{objectId}:
    get:
      tags: [Public]
      operationId: getPublicObject
      summary: An object in a public collection
      description: With `Accept application/json` the object, otherwise a redirect to its public page.
      security: []
      parameters:
        - $ref: "#/components/parameters/objectId"
      responses:
        "200":
          description: Object (public fields only)
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Object" }
        "302": { description: Redirect to the public page or the file }
        "403": { description: Not in a public collection }

  /public-objects/{objectId}/attachments:
    get:
      tags: [Public]
      operationId: listPublicAttachments
      summary: Attachments of a public object
      description: Only for objects in a public collection.
      security: []
      parameters:
        - $ref: "#/components/parameters/objectId"
      responses:
        "200":
          description: Attachments
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/Attachment" }
        "403": { description: Not in a public collection }

  /public-objects/{objectId}/attachments/{attachmentId}:
    get:
      tags: [Public]
      operationId: getPublicAttachment
      summary: A file of a public object
      description: |
        Only for objects in a public collection. Same options as the authenticated
        download. Watermarked with the owner's profile picture if the owner
        requires a watermark; an owner without a profile picture gets
        unwatermarked images.
      security: []
      parameters:
        - $ref: "#/components/parameters/objectId"
        - $ref: "#/components/parameters/attachmentId"
        - $ref: "#/components/parameters/attDownload"
        - $ref: "#/components/parameters/attFile"
        - $ref: "#/components/parameters/attWidth"
        - $ref: "#/components/parameters/attHeight"
      responses:
        "200":
          description: File
          content:
            "*/*": { schema: { type: string, format: binary } }

  /public/collections/{collectionId}:
    get:
      tags: [Public]
      operationId: getPublicCollection
      summary: A public collection
      security: []
      parameters:
        - $ref: "#/components/parameters/collectionId"
      responses:
        "200":
          description: Collection
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Collection" }
        "401": { description: Not public }

  /public-organisations/{organisationId}:
    get:
      tags: [Public]
      operationId: getPublicOrganisation
      summary: Public profile of an organisation
      security: []
      parameters:
        - name: organisationId
          in: path
          required: true
          schema: { type: string }
      responses:
        "200":
          description: Name, picture and field visibility
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Organisation" }

  /public-owners/{ownerId}:
    get:
      tags: [Public]
      operationId: resolvePublicOwner
      summary: Like /owners/{ownerId}, linking to the public organisation profile
      security: []
      parameters:
        - $ref: "#/components/parameters/ownerId"
      responses:
        "303": { description: See Location }

  /objects/fields:
    get:
      tags: [Public]
      operationId: listPublicFields
      summary: Fields an owner uses that the public may see
      description: For Basic-auth clients this only returns publicly visible fields. Use `/maintenance/fields` instead.
      security: []
      parameters:
        - $ref: "#/components/parameters/ownerQueryRequired"
        - $ref: "#/components/parameters/templateFilter"
      responses:
        "200":
          description: Field ids
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/Id" }
        "404": { description: Owner not found }

  # ---------------------------------------------------------------- Users
  /users:
    get:
      tags: [Users]
      operationId: listUsers
      summary: Find users, or list an organisation's members or guests
      description: With `o`, the members (or guests) of that organisation; without, up to 10 users whose username starts with `q`.
      parameters:
        - name: o
          in: query
          description: Organisation id.
          schema: { type: string }
        - name: type
          in: query
          schema: { type: string, enum: [member, guest], default: member }
        - name: q
          in: query
          description: Username prefix (when `o` is not given).
          schema: { type: string }
      responses:
        "200":
          description: Users
          content:
            application/json:
              schema:
                type: array
                items: { $ref: "#/components/schemas/Link" }
        "403": { $ref: "#/components/responses/Forbidden" }
    post:
      tags: [Account]
      operationId: signUp
      summary: Sign up
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [username, password, email]
              properties:
                username: { type: string }
                password: { type: string }
                email: { type: string }
                name: { type: string }
      responses:
        "201":
          description: Created; the body is the new user's path
          content:
            text/plain: { schema: { type: string, example: /users/46de5198e86b4b1cf9f8b1912090ac90 } }
        "400": { $ref: "#/components/responses/BadRequest" }
        "422": { description: Username or email taken }

  /users/{userId}:
    parameters:
      - name: userId
        in: path
        required: true
        schema: { type: string }
    get:
      tags: [Users]
      operationId: getUser
      summary: A user's profile
      description: Works without credentials. `email` is only included for yourself and for people who share an organisation with you.
      security: [{}, basicAuth: []]
      responses:
        "200":
          description: User
          content:
            application/json:
              schema: { $ref: "#/components/schemas/User" }
        "404": { $ref: "#/components/responses/NotFound" }
    put:
      tags: [Account]
      operationId: updateUser
      summary: Change your own profile
      description: Username, email, name, picture and language. A `password` in the body is ignored; use `POST /users/{userId}/password`.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/User" }
      responses:
        "200":
          description: Saved; the body is the user's path
          content:
            text/plain: { schema: { type: string, example: /users/46de5198e86b4b1cf9f8b1912090ac90 } }
        "400": { $ref: "#/components/responses/BadRequest" }
        "403": { $ref: "#/components/responses/Forbidden" }
        "422": { description: Username or email taken }
    delete:
      tags: [Account]
      operationId: deleteUser
      summary: Delete your own account
      responses:
        "200": { description: Deleted }
        "403": { $ref: "#/components/responses/Forbidden" }

  /users/{userId}/password:
    post:
      tags: [Account]
      operationId: changePassword
      summary: Change your own password
      description: |
        Needs the current password. Signs the account out everywhere else: every
        other session ends, and the session making the change gets a new one.
      parameters:
        - name: userId
          in: path
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [currentPassword, newPassword]
              properties:
                currentPassword: { type: string }
                newPassword: { type: string }
      responses:
        "200": { description: Changed }
        "400": { description: Missing current or new password }
        "403": { description: "Wrong current password, or not your account" }

  /users/resetpass:
    post:
      tags: [Account]
      operationId: requestPasswordReset
      summary: Email a password reset link
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [username]
              properties:
                username: { type: string, description: Username or email }
                host: { type: string }
                returnroute: { type: string }
      responses:
        "200": { description: Sent if the account exists }

  /users/restorepass:
    post:
      tags: [Account]
      operationId: resetPassword
      summary: Set a new password with the token from the email
      description: Ends every existing session of the account.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [recoverytoken, password]
              properties:
                recoverytoken: { type: string }
                password: { type: string }
      responses:
        "200": { description: Password changed }
        "404": { description: Token unknown or expired }

components:
  securitySchemes:
    basicAuth:
      type: http
      scheme: basic
      description: Username and password of a collectr account, on every request.

  parameters:
    ownerId:
      name: ownerId
      in: path
      required: true
      schema: { type: string }
    ownerQuery:
      name: o
      in: query
      description: Owner (user or organisation) id. Defaults to your own user.
      schema: { type: string }
    ownerQueryRequired:
      name: o
      in: query
      required: true
      description: Owner (user or organisation) id.
      schema: { type: string }
    objectId:
      name: objectId
      in: path
      required: true
      schema: { type: string }
    attachmentId:
      name: attachmentId
      in: path
      required: true
      schema: { type: string, example: 7c0e8f1a-2b3c-4d5e-8f90-a1b2c3d4e5f6.jpg }
    collectionId:
      name: collectionId
      in: path
      required: true
      schema: { type: string }
    templateId:
      name: templateId
      in: path
      required: true
      schema: { $ref: "#/components/schemas/TemplateId" }
    templateFilter:
      name: t
      in: query
      description: Only this template.
      schema: { $ref: "#/components/schemas/TemplateId" }
    maintTemplate:
      name: t
      in: query
      schema:
        type: string
        enum: [defaultobjtemplate, defaultmediatemplate]
        default: defaultobjtemplate
    fieldQuery:
      name: f
      in: query
      required: true
      description: Field id.
      schema: { type: string }
    pageOffset:
      name: offset
      in: query
      schema: { type: integer, default: 0 }
    attDownload:
      name: download
      in: query
      description: Original file as a download.
      schema: { type: boolean }
    attFile:
      name: file
      in: query
      description: Original file for inline display (PDF viewer, video player).
      schema: { type: boolean }
    attWidth:
      name: w
      in: query
      description: Width in pixels for image previews. Larger values are capped at 4096; anything that is not a positive number is ignored.
      schema: { type: integer, minimum: 1, maximum: 4096 }
    attHeight:
      name: h
      in: query
      description: Height in pixels for image previews. Larger values are capped at 4096; anything that is not a positive number is ignored.
      schema: { type: integer, minimum: 1, maximum: 4096 }
    attRotation:
      name: rotation
      in: query
      description: Quarter turns only; other values are ignored.
      schema: { type: integer, enum: [0, 90, 180, 270] }
    attWatermark:
      name: watermark
      in: query
      description: Stamp the owner's profile picture onto the image.
      schema: { type: boolean }

  responses:
    BadRequest:
      description: Missing or invalid input; the body names the problem.
    Unauthorized:
      description: Missing or wrong credentials.
    Forbidden:
      description: Your account may not do this for this owner.
    NotFound:
      description: Not found.

  schemas:
    Id:
      type: object
      properties:
        id: { type: string }

    Link:
      type: object
      properties:
        id: { type: string }
        location: { type: string, description: Path of the resource }

    Deleted:
      type: object
      properties:
        deleted: { type: boolean, const: true }

    TemplateId:
      type: string
      enum: [defaultobjtemplate, defaultmediatemplate]
      default: defaultobjtemplate

    ObjectData:
      type: object
      description: Field id to value. Values are always strings.
      additionalProperties: { type: string }
      example:
        title: Autohupe Messing antik
        inventorynumber: "300100"
        category: Zubehör
        condition: mittel
        acquisitiondate: "2.2020"

    ObjectWrite:
      type: object
      required: [owner, template, data]
      properties:
        owner: { type: string }
        template: { $ref: "#/components/schemas/TemplateId" }
        data: { $ref: "#/components/schemas/ObjectData" }
        collections:
          type: array
          items: { type: string }
          description: Ids of the collections the object is in.
        references:
          type: array
          items: { type: string }
          description: Ids of linked objects.
        highlighted:
          type: string
          description: Id of the attachment (or linked object) that represents the object.
        modified: { type: string, format: date-time }
        modifiedby: { type: string }

    Object:
      allOf:
        - $ref: "#/components/schemas/ObjectWrite"
        - type: object
          properties:
            id: { type: string }
            creator: { type: string }
            created: { type: string, format: date-time }
            attachments:
              type: array
              items: { $ref: "#/components/schemas/Attachment" }

    SearchResult:
      type: object
      properties:
        total_rows: { type: integer }
        bookmark: { type: string, description: "Pass as `offset` for the next page" }
        rows:
          type: array
          items:
            type: object
            properties:
              id: { type: string }
              doc: { $ref: "#/components/schemas/Object" }

    Attachment:
      type: object
      properties:
        id: { type: string, description: Stored file name }
        filename: { type: string, description: Original file name }
        type: { type: string, description: MIME type }
        length: { type: integer, description: Size in bytes }
        rotation: { type: integer }
        metadata: { type: object }
        location: { type: string }

    Collection:
      type: object
      required: [owner, name]
      properties:
        id: { type: string }
        owner: { type: string }
        name: { type: string }
        public: { type: boolean, description: Objects in it are visible to everyone }
        permissions: { type: object, readOnly: true }

    Organisation:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        owner: { type: string, description: User id of the owner }
        members: { type: array, items: { type: string } }
        guests: { type: array, items: { type: string } }
        picture: { type: string }
        requiresWatermark: { type: boolean }
        templatesettings:
          type: object
          description: Per field, which roles may see it.
          additionalProperties:
            type: object
            properties:
              visibility:
                type: object
                properties:
                  public: { type: boolean }
                  guest: { type: boolean }
                  member: { type: boolean }
        isOwner: { type: boolean, readOnly: true }
        permissions: { type: object, readOnly: true }

    User:
      type: object
      properties:
        id: { type: string }
        username: { type: string }
        email: { type: string }
        name: { type: string }
        picture: { type: string }
        language: { type: string }

    ValueCount:
      type: object
      properties:
        value: { type: string }
        count: { type: integer }
