forked from richartkeil/notion-guardian
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
95 lines (79 loc) · 2.46 KB
/
index.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
92
93
94
95
const axios = require(`axios`);
const extract = require(`extract-zip`);
const { createWriteStream } = require(`fs`);
const { rm, mkdir, unlink } = require(`fs/promises`);
const { join } = require(`path`);
const notionAPI = `https://www.notion.so/api/v3`;
const { NOTION_TOKEN, NOTION_SPACE_ID } = process.env;
const client = axios.create({
baseURL: notionAPI,
headers: {
Cookie: `token_v2=${NOTION_TOKEN}`,
},
});
if (!NOTION_TOKEN || !NOTION_SPACE_ID) {
console.error(
`Environment variable NOTION_TOKEN or NOTION_SPACE_ID is missing. Check the README.md for more information.`
);
process.exit(1);
}
const sleep = async (seconds) => {
return new Promise((resolve) => {
setTimeout(resolve, seconds * 1000);
});
};
const round = (number) => Math.round(number * 100) / 100;
const exportFromNotion = async (destination, format) => {
const task = {
eventName: `exportSpace`,
request: {
spaceId: NOTION_SPACE_ID,
exportOptions: {
exportType: format,
timeZone: `Europe/Berlin`,
locale: `en`,
},
},
};
const {
data: { taskId },
} = await client.post(`enqueueTask`, { task });
console.log(`Started Export as task [${taskId}].\n`);
let exportURL;
while (true) {
await sleep(2);
const {
data: { results: tasks },
} = await client.post(`getTasks`, { taskIds: [taskId] });
const task = tasks.find((t) => t.id === taskId);
console.log(`Exported ${task.status.pagesExported} pages.`);
if (task.state === `success`) {
exportURL = task.status.exportURL;
console.log(`\nExport finished.`);
break;
}
}
const response = await client({
method: `GET`,
url: exportURL,
responseType: `stream`,
});
const size = response.headers["content-length"];
console.log(`Downloading ${round(size / 1000 / 1000)}mb...`);
const stream = response.data.pipe(createWriteStream(destination));
await new Promise((resolve, reject) => {
stream.on(`close`, resolve);
stream.on(`error`, reject);
});
};
const run = async () => {
const workspaceDir = join(process.cwd(), `workspace`);
const workspaceZip = join(process.cwd(), `workspace.zip`);
await exportFromNotion(workspaceZip, `markdown`);
await rm(workspaceDir, { recursive: true, force: true });
await mkdir(workspaceDir, { recursive: true });
await extract(workspaceZip, { dir: workspaceDir });
await unlink(workspaceZip);
console.log(`✅ Export downloaded and unzipped.`);
};
run();