]> BookStack Code Mirror - api-scripts/commitdiff
Added export-all-books example
authorDan Brown <redacted>
Sat, 2 Jan 2021 18:24:31 +0000 (18:24 +0000)
committerDan Brown <redacted>
Sat, 2 Jan 2021 18:24:31 +0000 (18:24 +0000)
README.md
php-export-all-books/export-books.php [new file with mode: 0644]
php-export-all-books/readme.md [new file with mode: 0644]

index 016d34acd95dc574493dead094e69d342cf0417d..3cb6b1a0880f36e27a0757d552d4da791bd3ef50 100644 (file)
--- a/README.md
+++ b/README.md
@@ -1,2 +1,9 @@
-# api-scripts
-Examples of BookStack API scripts
+# BookStack API Scripts
+
+This repository contains different examples of BookStack API scripts that you might find useful to use or modify.
+
+
+Each folder within this repo is a different script. Each script has it's own readme. Click into a folder to see the readme for detail about the script.
+
+
+These scripts are not part an officially supported part of the BookStack project itself and therefore may be outdated or more likely to have bugs.
\ No newline at end of file
diff --git a/php-export-all-books/export-books.php b/php-export-all-books/export-books.php
new file mode 100644 (file)
index 0000000..a0f9ff9
--- /dev/null
@@ -0,0 +1,92 @@
+#!/usr/bin/env php
+<?php
+
+// API Credentials
+// You can either provide them as environment variables
+// or hard-code them in the empty strings below.
+$apiUrl = getenv('BS_URL') ?: ''; // http://bookstack.local/
+$clientId = getenv('BS_TOKEN_ID') ?: '';
+$clientSecret = getenv('BS_TOKEN_SECRET') ?: '';
+
+// Export Format & Location
+// Can be provided as a arguments when calling the script
+// or be hard-coded as strings below.
+$exportFormat = $argv[1] ?? 'pdf';
+$exportLocation = $argv[2] ?? './';
+
+// Script logic
+////////////////
+
+$books = getAllBooks();
+$outDir = realpath($exportLocation);
+
+$extensionByFormat = [
+    'pdf' => 'pdf',
+    'html' => 'html',
+    'plaintext' => 'txt',
+];
+
+foreach ($books as $book) {
+    $id = $book['id'];
+    $extension = $extensionByFormat[$exportFormat] ?? $exportFormat;
+    $content = apiGet("api/books/{$id}/export/{$exportFormat}");
+    $outPath = $outDir  . "/{$book['slug']}.{$extension}";
+    file_put_contents($outPath, $content);
+}
+
+/**
+ * Get all books from the system API.
+ */
+function getAllBooks() {
+    $count = 100;
+    $offset = 0;
+    $total = 0;
+    $allBooks = [];
+
+    do {
+        $endpoint = 'api/books?' . http_build_query(['count' => $count, 'offset' => $offset]);
+        $resp = apiGetJson($endpoint);
+
+        // Only set total on first request, due to API bug:
+        // https://github.com/BookStackApp/BookStack/issues/2043
+        if ($offset == 0) {
+            $total = $resp['total'] ?? 0;
+        }
+
+        $newBooks = $resp['data'] ?? [];
+        array_push($allBooks, ...$newBooks);
+        $offset += $count;
+    } while ($offset < $total);
+
+    return $allBooks;
+}
+
+/**
+ * Make a simple GET HTTP request to the API.
+ */
+function apiGet(string $endpoint): string {
+    global $apiUrl, $clientId, $clientSecret;
+    $url = rtrim($apiUrl, '/') . '/' . ltrim($endpoint, '/');
+    $opts = ['http' => ['header' => "Authorization: Token {$clientId}:{$clientSecret}"]];
+    $context = stream_context_create($opts);
+    return file_get_contents($url, false, $context);
+}
+
+/**
+ * Make a simple GET HTTP request to the API &
+ * decode the JSON response to an array.
+ */
+function apiGetJson(string $endpoint): array {
+    $data = apiGet($endpoint);
+    return json_decode($data, true);
+}
+
+/**
+ * DEBUG: Dump out the given variables and exit.
+ */
+function dd(...$args) {
+    foreach ($args as $arg) {
+        var_dump($arg);
+    }
+    exit(1);
+}
\ No newline at end of file
diff --git a/php-export-all-books/readme.md b/php-export-all-books/readme.md
new file mode 100644 (file)
index 0000000..b076a39
--- /dev/null
@@ -0,0 +1,37 @@
+# Export All Books
+
+This script will export all books in your preferred format (PDF, HTML or TXT).
+
+## Requirements
+
+You will need php (~7.1+) installed on the machine you want to run this script on.
+You will also need BookStack API credentials (TOKEN_ID & TOKEN_SECRET) at the ready.
+
+## Running
+
+```bash
+# Downloading the script
+curl https://raw.githubusercontent.com/BookStackApp/api-scripts/main/php-export-all-books/export-books.php > export-books.php
+
+# Setup
+# ALTERNATIVELY: Open the script and edit the variables at the top.
+export BS_URL=https://bookstack.example.com # Set to be your BookStack base URL
+export BS_TOKEN_ID=abc123 # Set to be your API token_id
+export BS_TOKEN_SECRET=123abc # Set to be your API token_secret
+
+# Running the script
+php export-books.php <format> <output_dir>
+```
+
+## Examples
+
+```bash
+# Export as plaintext to an existing "out" directory
+php export-books.php plaintext ./out
+
+# Export as pdf to the current directory
+php export-books.php pdf ./
+
+# Export as HTML to an existing "html" directory
+php export-books.php html ./html
+```
\ No newline at end of file