This repository has been archived by the owner on Oct 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backup.js
91 lines (79 loc) · 2.24 KB
/
backup.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import {createWriteStream} from 'node:fs';
import {pipeline} from 'node:stream';
import {promisify} from 'node:util'
import fetch from 'node-fetch';
const baseUrl = process.env.OUTLINE_URL
const apiToken = process.env.OUTLINE_API_KEY
const userAgent = process.env.BACKUP_UA || 'BackupScript/1.0'
const streamPipeline = promisify(pipeline);
async function makeReq(endpoint, body="") {
let options = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${apiToken}`,
'User-Agent': userAgent
},
}
if (body != "") {
options.body = JSON.stringify(body)
}
const res = await fetch(`${baseUrl}/api/${endpoint}`, options)
if (res.ok) {
const bodyRes = await res.json()
const document = bodyRes.data
return document
} else {
console.error(endpoint, body, res, await res.text())
process.exit(1)
}
}
async function startBackup() {
let res = await makeReq('collections.export_all')
console.log(res)
if (res == undefined) {
process.exit(1)
}
return res.fileOperation.id
}
async function trackBackupStatus(id) {
let isComplete = false
while (!isComplete) {
let res = await makeReq('fileOperations.info', {id: id})
isComplete = res.state == 'complete' ? true : false
console.log(`Status: ${res.state}`)
}
return
}
async function getBackup(id) {
const res = await fetch(`${baseUrl}/api/fileOperations.redirect`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${apiToken}`,
'User-Agent': userAgent
},
body: JSON.stringify({id: id})
})
if (!res.ok) throw new Error(`unexpected response ${res.statusText}`);
await streamPipeline(res.body, createWriteStream('./backup.zip'))
}
function checkAllConfigsExist() {
if (baseUrl =="" ||
apiToken == "") {
console.error("Not all config values exist")
process.exit(1)
}
}
async function main() {
checkAllConfigsExist()
// Request export to be done
let fileOperationId = await startBackup()
// Track FileOperation, until completed
await trackBackupStatus(fileOperationId)
// Download Backup
await getBackup(fileOperationId)
}
main()