/
note.go
130 lines (105 loc) · 2.24 KB
/
note.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
package internal
import (
"encoding/json"
"fmt"
"io/ioutil"
"strings"
"sync"
"time"
)
type note struct {
Repo string `json:"repo"`
Paths []string `json:"paths"`
Token string `json:"-"`
}
type content struct {
Name string `json:"name"`
Content string `json:"content"`
Message string `json:"message"`
}
type noteImpl struct {
Repo string `json:"repo"`
Paths []string `json:"paths"`
Token string `json:"-"`
}
func repoToContentURL(repo, path string) string {
return "https://api.github.com/repos/" + linkToGithubRepoName(repo) + "/contents/" + path
}
func (n noteImpl) download(path string) (*content, error) {
url := repoToContentURL(n.Repo, path)
resp, err := get(url, n.Token, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var r content
err = json.Unmarshal(body, &r)
if err != nil {
return nil, err
}
if r.Message != "" {
return nil, fmt.Errorf(r.Message)
}
return &r, nil
}
func (n noteImpl) analysisNote(c *content) (*article, error) {
article := &article{
ID: encodeBase64(c.Name),
}
note, err := decodeBase64(c.Content)
if err != nil {
return nil, err
}
var newArticleSlice []string
ts := strings.Split(string(note), "\n")
for k, v := range ts {
if k == 0 {
article.Title = v[2:]
newArticleSlice = append(newArticleSlice, v)
continue
}
if strings.HasPrefix(v, "- time ") {
article.CreatedAt, err = time.Parse(time.RFC3339, strings.TrimLeft(v, " -time")+"T15:04:05Z")
if err != nil {
return nil, err
}
continue
}
newArticleSlice = append(newArticleSlice, v)
}
article.Body = strings.Join(newArticleSlice, "\n")
return article, nil
}
func (n noteImpl) getAllNotes() ([]article, error) {
var s sync.WaitGroup
var errs = make([]error, len(n.Paths))
var articles = make([]article, len(n.Paths))
for k := range n.Paths {
s.Add(1)
go func(i int) {
defer s.Done()
c, err := n.download(n.Paths[i])
if err != nil {
errs[i] = err
return
}
a, err := n.analysisNote(c)
if err != nil {
errs[i] = err
return
}
articles[i] = *a
}(k)
}
s.Wait()
for _, err := range errs {
if err != nil {
return nil, err
}
}
return articles, nil
}