Export BookStack Wiki as Markdown (Use with NotebookLM via Google Drive)

In the previous installment on how to export BookStack to use it as a source with NotebookLM, I use existing solutions.

BookStack API is inefficient for large exports

However the BookStack API export is slow, specially if you have hundreds of pages as each needs to be individually iterated in an export loop. Slow, inefficient and definitely not something you want to do to your server regularly.

This solution cuts the time needed for export from 8 minutes to 30 seconds!

Skipping BookStack export API, using the power of SQL!

This mammoth query will extract all info you need for exporting to Markdown:

SELECT
    -- Parent Hierarchy
    COALESCE(sh.name, '[No Shelf]') AS bookshelf_name,
    COALESCE(bk.name, '[No Book]') AS book_name,
    CASE
        WHEN pg.chapter_id = 0 THEN ''
        ELSE COALESCE(ch.name, '')
    END AS chapter_name,
    bk.slug AS book_slug,

    -- Container Descriptions (New Joins)
    bk_data.description AS book_description,
    ch_data.description AS chapter_description,

    -- Page Data
    pg.name AS page_name,
    pg.slug AS page_slug,
    pg_content.html AS page_html

FROM entities pg

-- 1. Joins for Hierarchy
LEFT JOIN entities ch ON pg.chapter_id = ch.id AND ch.type = 'chapter'
LEFT JOIN entities bk ON (pg.book_id = bk.id OR ch.book_id = bk.id) AND bk.type = 'book'

-- 2. Link Book to Shelf
LEFT JOIN bookshelves_books bb ON bk.id = bb.book_id
LEFT JOIN entities sh ON bb.bookshelf_id = sh.id AND sh.type = 'bookshelf'

-- 3. Get Descriptions (Joining entity_container_data)
LEFT JOIN entity_container_data bk_data ON bk.id = bk_data.entity_id
    AND bk_data.entity_type = 'book'
LEFT JOIN entity_container_data ch_data ON ch.id = ch_data.entity_id
    AND ch_data.entity_type = 'chapter'

-- 4. Get Page Content
LEFT JOIN entity_page_data pg_content ON pg.id = pg_content.page_id

WHERE pg.type = 'page'
ORDER BY
    COALESCE(sh.id, 999999),
    COALESCE(bk.id, 999999),
    COALESCE(ch.id, 0),
    pg.id;

Exporting from BookStack directly to Google Drive in Markdown

This function first connect to your BookStack database using the SQL query above and then uses that data to create very simple Markdown using each book and chapter as headings and adding content from your wiki.

Moreover, it splits your export into multiple files as Google Drive has undocumented limit on Markdown size. Google Drive silently tries to convert your Markdown content to Google Docs format on upload. This fails when Markdown is just a couple of MBs in size. It was failing for me, when Markdown text file was just 1.8 megabytes. I suspect they have issues with images etc. and provide just generic 503 error. Unfortunately this is not properly documented anywhere and took me some time to debug.

Prerequisites

  1. BookStack database access
  2. Google client – I recommend google-api-php-client
  3. Service key or client id / client secret from Google console
  4. Code to initialize Google client + Drive access (scopes / permissions)
  5. Once all exports finish, add sources (converted to Google Docs) to your NotebookLM
  6. Run this once a day to get fresh data from your wiki

PHP export function

The whole PHP function to export from your BookStack database to Google Drive is this:

function exportWiki()
    {
        // initialize Google Client with API token (service key) to access Google Drive
        $initializeClient();
        // WIKI_FOLDER_ID is Drive folder to export Markdown content to
        $query = "'" . WIKI_FOLDER_ID . "' in parents and trashed = false";
        $results = $this->drive_service->files->listFiles([
            'q' => $query,
            'spaces' => 'drive',
            'fields' => 'files(id, name)',
            'supportsAllDrives' => true,
            'includeItemsFromAllDrives' => true,
        ]);
        if (!empty($results->getFiles())) {
            $patch = new \Google\Service\Drive\DriveFile();
            $patch->setTrashed(true);
            foreach ($results->getFiles() as $file) {
                $this->drive_service->files->update($file->id, $patch, [
                    'supportsAllDrives' => true,
                ]);
            }
        }
        // use query from above (change connection to whatever you are using, this is Laravel)
        $wiki = DB::connection('wiki')->select(DB::raw(QUERY));
        $book = '';
        $chapter = '';
        $markdown = '# Your Wiki name goes here - main heading';
        $counter = 0;
        foreach ($wiki as $key => $page) {
            // fix your base Wiki URL
            $markdown .= "\n\n" . '## ' . $page->bookshelf_name . ' > ' . $page->book_name . ' > ' . $page->chapter_name . ' > ' . $page->page_name . "\n" . '<https://example.com/wiki/' . $page->book_slug . '/page/' . $page->page_slug . ">\n\n";
            if ($book != $page->book_name and $page->book_description) {
                $markdown .= "\n\n" . $page->book_description . "\n\n";
                $book = $page->book_name;
            }
            if ($chapter != $page->chapter_name and $page->chapter_description) {
                $markdown .= "\n\n" . $page->chapter_description . "\n\n";
                $chapter = $page->chapter_name;
            }
            $markdown .= $converter->convert($page->page_html);
            if ($key != 0 and fmod($key, 50) == 0 or $key == count($wiki) - 1) {
                $file = new Google_Service_Drive_DriveFile();
                $file->setName('_brain' . $counter);
                // whatever you like as description
                $file->setDescription('Your wiki export');
                $file->setMimeType('application/vnd.google-apps.document');
                $file->setParents([WIKI_FOLDER_ID]);
                // change locale, if needed
                $file->setProperties(['locale' => 'en_US']);
                $result = $this->drive_service->files->create($file, [
                    'data' => $markdown,
                    'mimeType' => 'text/markdown',
                    'uploadType' => 'multipart',
                    'supportsAllDrives' => true,
                    'fields' => 'id',
                ]);
                $counter++;
                $markdown = '';
                $book = '';
                $chapter = '';
            }
        }
    }


Have a comment? Join discussion on Mastodon as a reply to: @dusoft@fosstodon.org