Download all images of an organization

How to download all source images of an organization together with their metadata, for a backup, a migration or an export

Table of Contents

There's no single API call that returns all images of an organization at once. You list the source images page by page and download each original with its hash.

Using rokka-export-org

For a complete export, use rokka-export-org. It downloads every source image with a JSON file containing its metadata next to it, runs several downloads in parallel, can verify every file against its binary hash and can be restarted at any time. A second run only fetches what is missing, changed or new.

git clone https://github.com/rokka-io/rokka-export-org.git
cd rokka-export-org
npm install
cp env.example .env      # put your API key in there
npm run export mycompany # downloads everything into ./export/mycompany

It needs Node.js 22 or newer. See its README for all options.

Writing your own script

If you'd rather write it yourself, or want to integrate it into your own code, these are the things to get right.

Paging through all images

  • Sort by created asc,hash asc. The default sort is by created only, which has a resolution of one second. Images uploaded within the same second (common after a bulk import) have no fixed order between them, and some of them can be skipped at a page boundary. Adding the hash makes the order unique. Sorting ascending also means that images uploaded while your script runs are added at the end instead of shifting the pages.
  • Use the cursor for the next page. If a response contains a cursor, pass it as offset in the next request, otherwise add the number of items you got to the offset. Send the same sort parameter with every request. Don't follow the next link, it only contains limit and offset and your sorting gets lost. See deep paging for details.
  • Stop when items is empty, not when there's no next link anymore.
  • Use a large limit, up to 2000 is possible. The examples below use 1000.

Downloading the images

  • GET /sourceimages/{organization}/{hash}/download returns the original file, byte for byte.
  • Protected images can only be downloaded with an API key that has the sourceimages:download:protected role (read, write and admin include it). Otherwise you get a 403 for them.
  • Don't use the name as it is for the filename. It's the filename the image was uploaded with or what was set later with the API. Many images can have the same name, and a name can contain a /, be empty or be very long. The examples prefix it with the short_hash, which is unique per organization, and replace / and control characters.
  • The metadata is already in the list. Every item in the list contains user_metadata, dynamic_metadata and static_metadata, so you can store them without additional requests.
  • Retry 429 and 5xx responses and don't run too many downloads in parallel. See API rate limiting and throttling.

Examples

The following scripts download all images of an organization into a directory, as <short_hash>_<name>, and write the metadata of each image into a .json file next to it. Files which are already there are skipped, so you can just start a script again after an interruption. The hashes of images which couldn't be downloaded (eg. protected images without the needed role) are written to failed.txt.

They download one image after the other. For many images, the rokka-export-org tool is faster.

Bash

Needs curl and jq.

#!/usr/bin/env bash
# Usage: ROKKA_API_KEY=yourKey ./rokka-download-all.sh mycompany [target-dir]
set -euo pipefail

ORG="$1"
DIR="${2:-$ORG}"
API="https://api.rokka.io"
mkdir -p "$DIR"

offset=0
seen=0
while true; do
  page=$(curl -sS --fail --retry 5 -G \
    -H "Api-Version: 1" -H "Api-Key: $ROKKA_API_KEY" \
    --data-urlencode "limit=1000" \
    --data-urlencode "sort=created asc,hash asc" \
    --data-urlencode "offset=$offset" \
    "$API/sourceimages/$ORG")

  count=$(jq '.items | length' <<<"$page")
  [ "$count" -eq 0 ] && break

  jq -c '.items[]' <<<"$page" | while read -r item; do
    hash=$(jq -r '.hash' <<<"$item")
    # The name can be anything, so only use it after the short hash and without "/"
    name=$(jq -r '(.short_hash + "_" + (.name | gsub("[/[:cntrl:]]"; "_")))[0:100]' <<<"$item")
    file="$DIR/$name"

    jq 'del(.link)' <<<"$item" > "$file.json"
    [ -f "$file" ] && continue
    if curl -sS --fail --retry 5 \
        -H "Api-Version: 1" -H "Api-Key: $ROKKA_API_KEY" \
        -o "$file.part" "$API/sourceimages/$ORG/$hash/download"; then
      mv "$file.part" "$file"
    else
      echo "$hash" >> "$DIR/failed.txt"
    fi
  done

  # The next page starts at the cursor of this one, or at a numeric offset if there is none
  seen=$((seen + count))
  offset=$(jq -r --argjson seen "$seen" '.cursor // $seen' <<<"$page")
done

PHP

With the PHP client library (composer require rokka/client).

<?php
// Usage: ROKKA_API_KEY=yourKey php rokka-download-all.php mycompany [target-dir]
require __DIR__.'/vendor/autoload.php';

$org = $argv[1];
$dir = $argv[2] ?? $org;
$client = \Rokka\Client\Factory::getImageClient($org, getenv('ROKKA_API_KEY'));
if (!is_dir($dir)) {
    mkdir($dir, 0777, true);
}

$offset = 0;
$seen = 0;
while (true) {
    $collection = $client->searchSourceImages([], ['created' => 'asc', 'hash' => 'asc'], 1000, $offset);
    $images = $collection->getSourceImages();
    if (0 === count($images)) {
        break;
    }

    foreach ($images as $image) {
        // The name can be anything, so only use it after the short hash and without "/"
        $name = mb_substr($image->shortHash.'_'.preg_replace('/[\/\x00-\x1f]/', '_', $image->name), 0, 100);
        $file = $dir.'/'.$name;

        file_put_contents($file.'.json', json_encode([
            'hash' => $image->hash,
            'name' => $image->name,
            'created' => $image->created->format(DATE_ATOM),
            'user_metadata' => $image->userMetadata,
            'dynamic_metadata' => $image->dynamicMetadata,
            'static_metadata' => $image->staticMetadata,
        ], JSON_PRETTY_PRINT));
        if (file_exists($file)) {
            continue;
        }
        try {
            file_put_contents($file.'.part', $client->getSourceImageContents($image->hash));
            rename($file.'.part', $file);
        } catch (\Exception $e) {
            file_put_contents($dir.'/failed.txt', $image->hash."\n", FILE_APPEND);
        }
    }

    // The next page starts at the cursor of this one, or at a numeric offset if there is none
    $seen += count($images);
    $offset = $collection->getCursor() ?? $seen;
}

JavaScript

With the JavaScript client library (npm install rokka) in Node.js. Use downloadAsBuffer() for this, download() returns the image as text and corrupts binary files.

// Usage: ROKKA_API_KEY=yourKey node rokka-download-all.mjs mycompany [target-dir]
import { Rokka } from 'rokka'
import { existsSync } from 'node:fs'
import { mkdir, rename, writeFile, appendFile } from 'node:fs/promises'
import path from 'node:path'

const org = process.argv[2]
const dir = process.argv[3] ?? org
const rokka = new Rokka({ apiKey: process.env.ROKKA_API_KEY })
await mkdir(dir, { recursive: true })

let offset = 0
let seen = 0
while (true) {
  const { body } = await rokka.sourceimages.list(org, {
    limit: 1000,
    sort: 'created asc,hash asc',
    offset,
  })
  if (body.items.length === 0) break

  for (const image of body.items) {
    // The name can be anything, so only use it after the short hash and without "/"
    const name = `${image.short_hash}_${image.name.replace(/[/\x00-\x1f]/g, '_')}`.slice(0, 100)
    const file = path.join(dir, name)

    const { link, ...metadata } = image
    await writeFile(`${file}.json`, JSON.stringify(metadata, null, 2))
    if (existsSync(file)) continue
    try {
      const { body: data } = await rokka.sourceimages.downloadAsBuffer(org, image.hash)
      await writeFile(`${file}.part`, data)
      await rename(`${file}.part`, file)
    } catch (e) {
      await appendFile(path.join(dir, 'failed.txt'), `${image.hash}\n`)
    }
  }

  // The next page starts at the cursor of this one, or at a numeric offset if there is none
  seen += body.items.length
  offset = body.cursor ?? seen
}

Downloading only some images

All of this also works for a subset of your images. Add search parameters to the list request, eg. --data-urlencode "user:str:category=shoes" in the Bash example, or ['user:str:category' => 'shoes'] as the first argument of searchSourceImages() in PHP. Send them with every request, like the sort parameter.