forked from JaCoB1123/bookstack-import
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimport.go
390 lines (329 loc) · 9 KB
/
import.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package main
import (
"bytes"
"fmt"
"io/fs"
"io/ioutil"
"log"
"path/filepath"
"strconv"
"strings"
cache "github.com/Code-Hex/go-generics-cache"
)
type bookstackImport struct {
Client *bookStackClient
Books *cache.Cache[string, *book]
Chapters *cache.Cache[string, *chapter]
Pages *cache.Cache[string, *page]
}
func NewImport(client *bookStackClient) *bookstackImport {
imp := &bookstackImport{
Client: client,
}
books, err := client.GetBooks()
if err != nil {
log.Fatal("Could not get list of books:", err)
return nil
}
imp.Books = cache.New[string, *book]()
for _, book := range books.Data {
book2 := book
imp.Books.Set(book.String(), &book2)
}
chapters, err := client.GetChapters()
if err != nil {
log.Fatal("Could not get list of chapters:", err)
return nil
}
imp.Chapters = cache.New[string, *chapter]()
for _, chapter := range chapters.Data {
chapter2 := chapter
imp.Chapters.Set(chapter.String(), &chapter2)
}
pages, err := client.GetPages()
if err != nil {
log.Fatal("Could not get list of pages:", err)
return nil
}
imp.Pages = cache.New[string, *page]()
for _, page := range pages.Data {
page2 := page
imp.Pages.Set(page.String(), &page2)
}
return imp
}
func (imp *bookstackImport) GetBook(name string) *book {
book := &book{
Name: name,
}
existingBook, ok := imp.Books.Get(book.String())
if ok {
return existingBook
}
log.Println("Creating new book", name)
newBook, err := imp.Client.CreateBook(name)
if err != nil {
log.Fatal(err)
return nil
}
imp.Books.Set(newBook.String(), newBook)
log.Println("New book:", newBook)
return newBook
}
func (imp *bookstackImport) GetChapter(name string, bookID int) *chapter {
chapter := &chapter{
BookID: bookID,
Name: name,
}
existingChapter, ok := imp.Chapters.Get(chapter.String())
if ok {
return existingChapter
}
log.Println("Creating new chapter", name)
newChapter, err := imp.Client.CreateChapter(bookID, name)
if err != nil {
log.Fatal(err)
return nil
}
imp.Chapters.Set(newChapter.String(), newChapter)
log.Println("New chapter:", newChapter)
return newChapter
}
func (imp *bookstackImport) GetPageID(name string, chapterID int) (int, error) {
page := &page{
ChapterID: chapterID,
Name: name,
}
existingPage, ok := imp.Pages.Get(page.String())
if !ok {
log.Println("Creating new page", name)
newPage, err := imp.Client.CreatePage(chapterID, name, []byte("empty"))
if err != nil {
return -1, fmt.Errorf("create page: %w", err)
}
imp.Pages.Set(newPage.String(), newPage)
return newPage.ID, nil
}
return existingPage.ID, nil
}
func (imp *bookstackImport) GetPage(name string, chapterID int, content []byte) *page {
page := &page{
ChapterID: chapterID,
Name: name,
}
existingPage, ok := imp.Pages.Get(page.String())
if !ok {
log.Println("Creating new page", name)
newPage, err := imp.Client.CreatePage(chapterID, name, content)
if err != nil {
return nil
}
imp.Pages.Set(newPage.String(), newPage)
return newPage
}
log.Println("Updating existing page", existingPage.ID, name)
page, err := imp.Client.UpdatePageContent(existingPage.ID, content)
if err != nil {
log.Printf("could not update page %d: %s\n", existingPage.ID, err)
return nil
}
imp.Pages.Set(page.String(), page)
return page
}
func (imp *bookstackImport) ImportFolder(importPath string) error {
return filepath.WalkDir(importPath, func(fullPath string, info fs.DirEntry, err error) error {
if err != nil {
return err
}
if info.IsDir() {
if info.Name() == "media" || info.Name() == "docx" {
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(fullPath, ".md") {
return nil
}
path := fullPath[len(importPath)+1:]
segments := strings.FieldsFunc(path, IsDirSeparator)
book := imp.GetBook(segments[0])
chapter := imp.GetChapter(segments[1], book.ID)
pageName := strings.Join(segments[2:], "/")
content, err := ioutil.ReadFile(fullPath)
if err != nil {
return fmt.Errorf("read file: %w", err)
}
// Header entfernen
headerSeparator := FindNextMultiChar(content, 0, '-', '-', '-')
content = content[headerSeparator+5:]
// Pfeile sind in OneNote mit WingDings formatiert, durch ASCII-Pfeile ersetzen
content = []byte(bytes.ReplaceAll(content, []byte("à"), []byte("->")))
pageID, err := imp.GetPageID(pageName, chapter.ID)
if err != nil {
return fmt.Errorf("get page ID: %w", err)
}
content, err = imp.ReplaceAllImages(pageID, content, fullPath)
if err != nil {
return fmt.Errorf("replace images: %w", err)
}
content, err = imp.ReplaceAllEmbeds(pageID, content, fullPath)
if err != nil {
return fmt.Errorf("replace embeds: %w", err)
}
content, err = imp.ReplaceAllInternalLinks(pageID, content, fullPath)
if err != nil {
return fmt.Errorf("replace internal links: %w", err)
}
imp.GetPage(pageName, chapter.ID, content)
return nil
})
}
func (imp *bookstackImport) ReplaceAllInternalLinks(pageID int, content []byte, path string) ([]byte, error) {
// TODO Implement
for i := 0; i < len(content); i++ {
if content[i] != '[' {
continue
}
_, bracketEnd := FindNext(content, i, '[', ']')
if bracketEnd == -1 {
continue
}
parenthesisStart, parenthesisEnd := FindNext(content, bracketEnd+1, '(', ')')
if parenthesisEnd == -1 {
continue
}
//name := content[bracketStart+1 : bracketEnd]
src := SafeUnquote("\"" + string(content[parenthesisStart+1:parenthesisEnd]) + "\"")
if strings.HasPrefix(string(src), "onenote:") {
log.Println("Found onenote link", src)
}
}
return content, nil
}
func SafeUnquote(text string) string {
unquoted, err := strconv.Unquote(text)
if err != nil {
log.Printf("unquote failed for: '%s': %s", text, err)
return text
}
return unquoted
}
func (imp *bookstackImport) ReplaceAllImages(pageID int, content []byte, path string) ([]byte, error) {
for i := 0; i < len(content); i++ {
if content[i] != '!' {
continue
}
bracketStart, bracketEnd := FindNext(content, i+1, '[', ']')
if bracketEnd == -1 {
continue
}
parenthesisStart, parenthesisEnd := FindNext(content, bracketEnd+1, '(', ')')
if parenthesisEnd == -1 {
continue
}
name := content[bracketStart+1 : bracketEnd]
src := SafeUnquote("\"" + string(content[parenthesisStart+1:parenthesisEnd]) + "\"")
path := filepath.Join(filepath.Dir(path), src)
image, err := imp.Client.UploadImage(pageID, string(name), path)
if err != nil {
return nil, fmt.Errorf("uploadimage: %w", err)
}
src = image.Path
contentTail := content[parenthesisEnd+1:]
newImage := []byte(fmt.Sprintf("", filepath.Base(src), src))
content = append(content[:i], newImage...)
i = len(newImage) + i - 1
content = append(content, contentTail...)
}
return content, nil
}
func (imp *bookstackImport) ReplaceAllEmbeds(pageID int, content []byte, path string) ([]byte, error) {
for i := 0; i < len(content); i++ {
if content[i] != '\\' || content[i+1] != '<' {
continue
}
if content[i+2] != '\\' || content[i+3] != '<' {
continue
}
firstClosing := FindNextMultiChar(content, i+3, '\\', '>', '\\', '>')
if firstClosing == -1 {
continue
}
bracketStart, bracketEnd := FindNext(content, i+4, '[', ']')
if bracketEnd == -1 {
continue
}
parenthesisStart, parenthesisEnd := FindNext(content, bracketEnd+1, '(', ')')
if parenthesisEnd == -1 {
continue
}
name := content[bracketStart+1 : bracketEnd]
src := SafeUnquote("\"" + string(content[parenthesisStart+1:parenthesisEnd]) + "\"")
path := filepath.Join(filepath.Dir(path), string(src))
attachment, err := imp.Client.UploadAttachment(pageID, string(name), path)
if err != nil {
return nil, fmt.Errorf("upload attachment: %w", err)
}
src = fmt.Sprintf("/attachments/%d", attachment.ID)
contentTail := content[parenthesisEnd+5:]
newImage := []byte(fmt.Sprintf("[%s](%s)", filepath.Base(src), src))
content = append(content[:i], newImage...)
i = len(newImage) + i - 1
content = append(content, contentTail...)
}
return content, nil
}
func FindNextAnywhere(content []byte, start int, nested byte, char byte) (int, int) {
for ; start < len(content)-1; start++ {
if content[start] != nested {
continue
}
end := start + 1
nestedCount := 0
for ; end < len(content); end++ {
switch content[end] {
case nested:
nestedCount++
case char:
nestedCount--
if nestedCount < 0 {
return start, end
}
}
}
}
return -1, -1
}
func FindNext(content []byte, start int, nested byte, char byte) (int, int) {
if content[start] != nested {
return -1, -1
}
end := start + 1
nestedCount := 0
for ; end < len(content); end++ {
switch content[end] {
case nested:
nestedCount++
case char:
nestedCount--
if nestedCount < 0 {
return start, end
}
}
}
return -1, -1
}
func FindNextMultiChar(content []byte, start int, chars ...byte) int {
end := start + 1
for ; end < len(content); end++ {
switch content[end] {
case chars[0]:
for i := 1; i < len(chars); i++ {
if content[end+i] == chars[i] {
return end + i
}
}
}
}
return -1
}