> ## Documentation Index
> Fetch the complete documentation index at: https://developers.scoutworks.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Copy the Knowledge Base to Google Drive or SharePoint

> Keep a copy of every Knowledge Base file in Google Drive or SharePoint, refreshed every night with only what changed.

> [!NOTE]
>
> * **For:** group admins and trustees
> * **You get:** a folder in Google Drive or a SharePoint library holding a copy of every Knowledge Base file, in the same folders, refreshed every night
> * **Time:** about twenty minutes the first time
> * **Scopes:** `files:read`

Many groups keep their policies and forms in Scoutworks, but their trustees live in Google Drive or SharePoint. This recipe keeps a copy there, so the documents sit beside the minutes and the accounts, and the group has its own backup. It is a **one-way copy**: change a document in Scoutworks, and the copy follows that night. A change made to the copy is not sent back, and the next change in Scoutworks overwrites it.

Each night it reads only the files that changed since the night before (`updatedSince`), downloads each one through a link that works for 15 minutes, and saves it. It then reads the full list of files, which is quick, and removes copies of files that were deleted in Scoutworks.

The key needs only `files:read`. It reads every Knowledge Base file whatever its section or sharing, as a group admin does, so keep it as carefully as the documents. Documents on a member's care plan and premises audit evidence are never included.

## 1. Try the requests

Paste these into a terminal to see the demo group's folders and files:

```bash theme={null}
curl "https://api-demo.scoutworks.app/api/v1/folders?limit=200" \
  -H "Authorization: Bearer sw_test_473adcc6c7236916021f0f24559db36576a53bab071d0f0c08a025adb510b6ab"

curl "https://api-demo.scoutworks.app/api/v1/files?limit=200" \
  -H "Authorization: Bearer sw_test_473adcc6c7236916021f0f24559db36576a53bab071d0f0c08a025adb510b6ab"
```

A folder has a `name` and a `parentId`, so folders can nest. A file has a `name`, a `folderId` (null when it is in no folder), its `kind`, and `virusScan`. Copy only files whose `kind` is `upload`: a `google_drive` file is already in Google Drive. To download one, ask for its link:

```bash theme={null}
curl "https://api-demo.scoutworks.app/api/v1/files/PASTE_FILE_ID/download" \
  -H "Authorization: Bearer sw_test_473adcc6c7236916021f0f24559db36576a53bab071d0f0c08a025adb510b6ab"
```

It answers a `url` that downloads the file with no key, and works for 15 minutes. Fetch it at once and never store it.

> [tab] Google Drive
>
> ## 2. Add the script
>
> Go to [script.google.com](https://script.google.com) and choose **New project**. Name it "Scoutworks Knowledge Base copy". Delete what is there, paste the script below and choose **Save**.
>
> ```javascript Code.gs theme={null}
> // Scoutworks → copy the Knowledge Base to Google Drive, nightly.
> // https://developers.scoutworks.app/recipes/mirror-knowledge-base
>
> const BASE = 'https://api-demo.scoutworks.app/api/v1';
> const ROOT_NAME = 'Scoutworks Knowledge Base';
>
> function copyKnowledgeBase() {
>   const props = PropertiesService.getScriptProperties();
>   const since = props.getProperty('NEXT_UPDATED_SINCE');
>   // A minute before this run began: a file changed while it runs is read again next time.
>   const startedAt = new Date(Date.now() - 60 * 1000).toISOString();
>   const root = rootFolder();
>
>   // Folders: one Drive folder for each Scoutworks folder, nested the same way.
>   const folders = readAll('/folders');
>   const byId = {};
>   folders.forEach(function (f) { byId[f.id] = f; });
>   const driveFolders = {};
>   function driveFolderFor(id) {
>     if (!id) return root;
>     if (driveFolders[id]) return driveFolders[id];
>     const f = byId[id];
>     const parent = driveFolderFor(f.parentId);
>     driveFolders[id] = childFolder(parent, f.name, f.id);
>     return driveFolders[id];
>   }
>
>   // Files that changed since last night (every file, the first time).
>   const changed = since
>     ? readPages('/files?updatedSince=' + encodeURIComponent(since))
>     : readPages('/files');
>   // Files skipped on an earlier night are tried again, changed or not.
>   const seen = {};
>   changed.items.forEach(function (f) { seen[f.id] = true; });
>   props.getKeys().forEach(function (key) {
>     if (key.indexOf('retry:') !== 0 || seen[key.slice(6)]) return;
>     const res = fetchOrNull(BASE + '/files/' + key.slice(6));
>     if (res) changed.items.push(res.data);
>     else props.deleteProperty(key); // Deleted in Scoutworks since.
>   });
>
>   changed.items.forEach(function (file) {
>     // A file still waiting for its scan is copied once the scan is done, which changes its updatedAt.
>     if (file.kind !== 'upload' || file.virusScan === 'infected' || file.virusScan === 'pending') return;
>     // Already copied as it is now: a run stopped part-way carries on from here.
>     if (props.getProperty('ver:' + file.id) === file.updatedAt) return;
>     const link = downloadLink(file.id);
>     if (!link) {
>       // Not downloadable just now: kept on a list and tried again next night.
>       props.setProperty('retry:' + file.id, file.name);
>       return;
>     }
>     props.deleteProperty('retry:' + file.id);
>     const blob = UrlFetchApp.fetch(link.url).getBlob().setName(file.name);
>     const target = driveFolderFor(file.folderId);
>     removeCopy(file.id);
>     props.setProperty('file:' + file.id, target.createFile(blob).getId());
>     props.setProperty('ver:' + file.id, file.updatedAt);
>     Utilities.sleep(600); // Stay well under 120 requests a minute.
>   });
>
>   // Copies of files deleted in Scoutworks go to the bin.
>   const live = {};
>   readAll('/files').forEach(function (f) { live[f.id] = true; });
>   props.getKeys().forEach(function (key) {
>     if (key.indexOf('file:') === 0 && !live[key.slice(5)]) removeCopy(key.slice(5));
>   });
>
>   // Only once everything is saved: next time, read what changed after this.
>   props.setProperty('NEXT_UPDATED_SINCE', changed.nextUpdatedSince || startedAt);
> }
>
> // One record, or null when it no longer exists.
> function fetchOrNull(url) {
>   const apiKey = PropertiesService.getScriptProperties().getProperty('SCOUTWORKS_API_KEY');
>   const res = UrlFetchApp.fetch(url, {
>     headers: { Authorization: 'Bearer ' + apiKey },
>     muteHttpExceptions: true,
>   });
>   if (res.getResponseCode() === 404) return null;
>   return fetchScoutworks(url);
> }
>
> // A file's 15-minute link, or null when it cannot be downloaded now
> // (a Drive doc, a flagged file, or one waiting for its scan).
> function downloadLink(id) {
>   const apiKey = PropertiesService.getScriptProperties().getProperty('SCOUTWORKS_API_KEY');
>   const res = UrlFetchApp.fetch(BASE + '/files/' + id + '/download', {
>     headers: { Authorization: 'Bearer ' + apiKey },
>     muteHttpExceptions: true,
>   });
>   if (res.getResponseCode() === 409 || res.getResponseCode() === 503) return null;
>   if (res.getResponseCode() === 429) {
>     Utilities.sleep(Number(res.getHeaders()['Retry-After'] || 60) * 1000);
>     return downloadLink(id);
>   }
>   const body = JSON.parse(res.getContentText());
>   if (res.getResponseCode() !== 200) throw new Error(body.error.code + ': ' + body.error.message);
>   return body.data;
> }
>
> function rootFolder() {
>   const found = DriveApp.getFoldersByName(ROOT_NAME);
>   return found.hasNext() ? found.next() : DriveApp.createFolder(ROOT_NAME);
> }
>
> // The Drive folder for a Scoutworks folder. The script remembers which
> // Drive folder each Scoutworks id became, so a renamed folder is renamed
> // here too rather than copied twice.
> function childFolder(parent, name, id) {
>   const props = PropertiesService.getScriptProperties();
>   const known = props.getProperty('folder:' + id);
>   let folder = null;
>   if (known) {
>     try { folder = DriveApp.getFolderById(known); } catch (e) { folder = null; }
>   }
>   if (!folder || folder.isTrashed()) {
>     folder = parent.createFolder(name);
>     props.setProperty('folder:' + id, folder.getId());
>   }
>   if (folder.getName() !== name) folder.setName(name);
>   // A folder moved in Scoutworks moves here too.
>   const parents = folder.getParents();
>   if (!parents.hasNext() || parents.next().getId() !== parent.getId()) folder.moveTo(parent);
>   return folder;
> }
>
> // Bin the copy of a Scoutworks file, if the script made one.
> function removeCopy(id) {
>   const props = PropertiesService.getScriptProperties();
>   const known = props.getProperty('file:' + id);
>   if (!known) return;
>   try { DriveApp.getFileById(known).setTrashed(true); } catch (e) { /* already gone */ }
>   props.deleteProperty('file:' + id);
>   props.deleteProperty('ver:' + id);
> }
>
> // Every item in a list, following nextCursor to the last page.
> function readAll(path) {
>   return readPages(path).items;
> }
>
> function readPages(path) {
>   const items = [];
>   let cursor = null;
>   let nextUpdatedSince = null;
>   do {
>     let url = BASE + path + (path.indexOf('?') === -1 ? '?' : '&') + 'limit=200';
>     if (cursor) url += '&cursor=' + encodeURIComponent(cursor);
>     const body = fetchScoutworks(url);
>     items.push.apply(items, body.data);
>     cursor = body.nextCursor;
>     nextUpdatedSince = body.nextUpdatedSince || nextUpdatedSince;
>   } while (cursor);
>   return { items: items, nextUpdatedSince: nextUpdatedSince };
> }
>
> // Calls the API. Waits and tries again if the rate limit is reached.
> function fetchScoutworks(url) {
>   const apiKey = PropertiesService.getScriptProperties().getProperty('SCOUTWORKS_API_KEY');
>   if (!apiKey) throw new Error('Add SCOUTWORKS_API_KEY in Project Settings → Script Properties.');
>   for (let attempt = 0; attempt < 3; attempt++) {
>     const res = UrlFetchApp.fetch(url, {
>       headers: { Authorization: 'Bearer ' + apiKey },
>       muteHttpExceptions: true,
>     });
>     const body = JSON.parse(res.getContentText());
>     if (res.getResponseCode() === 200) return body;
>     if (res.getResponseCode() === 429 || res.getResponseCode() === 503) {
>       Utilities.sleep(Number(body.retryAfter || res.getHeaders()['Retry-After'] || 60) * 1000);
>       continue;
>     }
>     throw new Error(body.error.code + ': ' + body.error.message);
>   }
>   throw new Error('Scoutworks is still busy. The copy will try again tomorrow night.');
> }
> ```
>
> ## 3. Add your key
>
> Choose **Project Settings** (the cog), then **Script Properties → Add script property**. Property: `SCOUTWORKS_API_KEY`. Value: the [sandbox key](https://developers.scoutworks.app/guides/sandbox.md) to try it, or your own key with `files:read`.
>
> ## 4. Run it once
>
> Choose `copyKnowledgeBase` and **Run**. Google asks you to allow the script to use your Drive and reach an outside service. When it finishes, open **Scoutworks Knowledge Base** in your Drive: it holds the demo group's folders and files.
>
> The first run copies every file. A group with hundreds of documents may reach Apps Script's six-minute limit; just run it again. The script remembers each file it has copied, so the next run skips those and carries on with the rest.
>
> ## 5. Run it every night
>
> Choose **Triggers** (the clock), then **Add Trigger**: function `copyKnowledgeBase`, event source **Time-driven**, **Day timer**, **2am to 3am**.

> [tab] SharePoint (Power Automate)
>
> ## 2. Build the flow
>
> In [Power Automate](https://make.powerautomate.com), choose **Create → Scheduled cloud flow**. Name it "Scoutworks Knowledge Base copy", and run it every **1 day** at 2am. The **HTTP** action needs a premium licence; a charity's Microsoft 365 nonprofit plan usually includes one.
>
> Make a document library in SharePoint called **Scoutworks Knowledge Base** first. Then add these actions:
>
> **1. HTTP: the folders**
>
> Method **GET**. URI `https://api.scoutworks.app/api/v1/folders?limit=200`. Header `Authorization`: `Bearer ` followed by your key.
>
> **2. HTTP: what changed since yesterday**
>
> Method **GET**. URI: type `https://api.scoutworks.app/api/v1/files?limit=200&updatedSince=` and then add this **Expression**: `encodeUriComponent(addHours(utcNow(), -25))`. Header `Authorization` as before. The extra hour means a file changed while last night's run was going is copied again, never missed.
>
> **3. Apply to each file**
>
> Over `body('HTTP_2')?['data']`. Inside it, add a **Condition**: `items('Apply_to_each')?['kind']` is equal to `upload`. In the **Yes** branch:
>
> * **HTTP: the link.** Method **GET**. URI: type `https://api.scoutworks.app/api/v1/files/PASTE_FILE_ID/download`, then replace `PASTE_FILE_ID` with the **Expression** `items('Apply_to_each')?['id']`. Header `Authorization` as before.
> * **HTTP: the file.** Method **GET**. URI: the **Expression** `body('HTTP_3')?['data']?['url']`. No headers: the link needs no key.
> * **Filter array: its folder.** From `body('HTTP')?['data']`, keep items where `item()?['id']` is equal to `items('Apply_to_each')?['folderId']`.
> * **Create file** (SharePoint). Site: yours. Folder path: `/Scoutworks Knowledge Base/` followed by the **Expression** `if(empty(body('Filter_array')), 'Unfiled', first(body('Filter_array'))?['name'])`. File name: the **Expression** `items('Apply_to_each')?['name']`. File content: `body('HTTP_4')`. A file of the same name already in that folder is replaced, so a changed document overwrites its old copy.
>
> A folder inside another is copied under its own name, beside its parent, so the library stays one level deep. If a nightly run fails, the next one picks up what it missed only if it changed in the last 25 hours: once a month, run the flow with `-25` changed to `-800` to copy everything again.
>
> Files deleted in Scoutworks stay in the library. Tidy them by hand now and then, or compare with a full `https://api.scoutworks.app/api/v1/files?limit=200` list.

## Switch to your group

Change `api-demo.scoutworks.app` to `api.scoutworks.app`, and replace the sandbox key with your own key with `files:read`. Create it in **Settings → Integrations → API keys**, and name it "Drive copy" or "SharePoint copy", so you know which tool to revoke if you stop using it.

## Who can see the copy

The copy keeps the files, not their sharing. A document shared only with Beavers leaders in Scoutworks is in the copy for whoever can open the Drive folder or the library. Share the copy only with people who could read every document in Scoutworks: usually the group admins and trustees.

## If something goes wrong

* **`409 not_downloadable`**: the file is a linked Google Drive doc, or the virus scan found something in it. The script skips both.
* **`503 scan_unavailable`**: a file is still waiting for its virus scan. The script waits and tries again; if it still waits, the file is copied the next night.
* **`429 rate_limited`**: the key made more than 120 requests in a minute. The script waits and carries on.
* **`403 insufficient_scope`**: the key has no `files:read`.

See [Errors](https://developers.scoutworks.app/guides/errors.md) for every code.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.