-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathapp.go
108 lines (85 loc) · 2.27 KB
/
app.go
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
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/kjk/notionapi"
)
const version = "1.0.0"
type App struct {
client *notionapi.Client
pageID string
exportType string
exportDir string
}
func main() {
authToken := os.Getenv("NOTION_TOKEN")
pageID := os.Getenv("NOTION_PAGEID")
if authToken == "" || pageID == "" {
log.Fatalln("You have to set the env vars NOTION_TOKEN and NOTION_PAGEID.")
}
app := &App{
client: ¬ionapi.Client{
AuthToken: authToken,
},
pageID: pageID,
exportType: os.Getenv("NOTION_EXPORTTYPE"),
}
var err error
app.exportDir = os.Getenv("NOTION_EXPORTDIR")
if app.exportDir == "" {
app.exportDir, err = os.Getwd()
if err != nil {
log.Fatal(err)
}
}
log.Printf("notionbackup (v%s) | Starting the export process ...\n", version)
startTime := time.Now()
exportURL, err := app.exportPageURL(true)
if err != nil {
log.Fatal(err)
}
log.Printf("Notion export successful. Starting to download the exported .zip file now ...\n")
bytesWritten := app.saveToFile(exportURL)
log.Printf("Notion export (page id: %s) took %s, %d bytes written.\n", app.pageID, time.Since(startTime).String(), bytesWritten)
}
func (app *App) exportPageURL(recursive bool) (string, error) {
if app.exportType == "" {
app.exportType = "markdown"
}
// support full url, like https://www.notion.so/username/PageName-abcdefghia1f4505762g63874a1e97yz
if strings.HasPrefix(app.pageID, "https://") {
app.pageID = notionapi.ExtractNoDashIDFromNotionURL(app.pageID)
}
return app.client.RequestPageExportURL(app.pageID, app.exportType, recursive)
}
func (app *App) saveToFile(exportURL string) int64 {
fileName := fmt.Sprintf("%s_%s.zip", time.Now().Format("20060102150405"), app.pageID)
if err := os.MkdirAll(app.exportDir, 0755); err != nil {
log.Fatal(err)
}
sep := string(os.PathSeparator)
if strings.HasSuffix(app.exportDir, sep) {
sep = ""
}
path := strings.Join([]string{app.exportDir, fileName}, sep)
file, err := os.Create(path)
if err != nil {
log.Fatalln(err)
}
defer file.Close()
resp, err := http.Get(exportURL)
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
bytesWritten, err := io.Copy(file, resp.Body)
if err != nil {
log.Fatalln(err)
}
return bytesWritten
}