-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpin.go
196 lines (193 loc) · 5.13 KB
/
pin.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
package notebrew
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"net/http"
"path"
"slices"
"strings"
"sync/atomic"
"github.com/bokwoon95/notebrew/sq"
"github.com/bokwoon95/notebrew/stacktrace"
"golang.org/x/sync/errgroup"
)
func (nbrew *Notebrew) pin(w http.ResponseWriter, r *http.Request, user User, sitePrefix string) {
type Response struct {
Error string `json:"error"`
Parent string `json:"parent"`
NumPinned int `json:"numPinned"`
}
databaseFS, ok := &DatabaseFS{}, false
switch v := nbrew.FS.(type) {
case interface{ As(any) bool }:
ok = v.As(&databaseFS)
}
if !ok {
nbrew.NotFound(w, r)
return
}
if r.Method != "POST" {
nbrew.MethodNotAllowed(w, r)
return
}
r.Body = http.MaxBytesReader(w, r.Body, 1<<20 /* 1 MB */)
err := r.ParseForm()
if err != nil {
nbrew.BadRequest(w, r, err)
return
}
referer := r.Referer()
if referer == "" {
http.Redirect(w, r, "/"+path.Join("files", sitePrefix)+"/", http.StatusFound)
return
}
writeResponse := func(w http.ResponseWriter, r *http.Request, response Response) {
if r.Form.Has("api") {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
encoder := json.NewEncoder(w)
encoder.SetIndent("", " ")
encoder.SetEscapeHTML(false)
err := encoder.Encode(&response)
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
}
return
}
if response.Error != "" {
http.Redirect(w, r, "/"+path.Join("files", sitePrefix)+"/", http.StatusFound)
return
}
err := nbrew.SetFlashSession(w, r, map[string]any{
"postRedirectGet": map[string]any{
"from": "pin",
"numPinned": response.NumPinned,
},
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
http.Redirect(w, r, referer, http.StatusFound)
}
response := Response{
Parent: path.Clean(strings.Trim(r.Form.Get("parent"), "/")),
}
head, _, _ := strings.Cut(response.Parent, "/")
if head != "notes" && head != "pages" && head != "posts" && head != "output" && head != "imports" && head != "exports" {
response.Error = "InvalidParent"
writeResponse(w, r, response)
return
}
parentID, err := sq.FetchOne(r.Context(), databaseFS.DB, sq.Query{
Dialect: databaseFS.Dialect,
Format: "SELECT {*} FROM files WHERE file_path = {parent} AND is_dir",
Values: []any{
sq.StringParam("parent", path.Join(sitePrefix, response.Parent)),
},
}, func(row *sq.Row) ID {
return row.UUID("file_id")
})
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
response.Error = "InvalidParent"
writeResponse(w, r, response)
return
}
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
names := r.Form["name"]
if len(names) == 0 {
http.Redirect(w, r, referer, http.StatusFound)
return
}
slices.Sort(names)
names = slices.Compact(names)
numPinned := atomic.Int64{}
tx, err := databaseFS.DB.BeginTx(r.Context(), nil)
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
defer tx.Rollback()
var preparedExec *sq.PreparedExec
defer func() {
if preparedExec == nil {
return
}
preparedExec.Close()
}()
switch databaseFS.Dialect {
case "sqlite", "postgres":
preparedExec, err = sq.PrepareExec(r.Context(), tx, sq.Query{
Dialect: databaseFS.Dialect,
Format: "INSERT INTO pinned_file (parent_id, file_id)" +
" SELECT {parentID}, file_id FROM files WHERE file_path = {filePath}" +
" ON CONFLICT DO NOTHING",
Values: []any{
sq.UUIDParam("parentID", parentID),
sq.Param("filePath", nil),
},
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
case "mysql":
preparedExec, err = sq.PrepareExec(r.Context(), tx, sq.Query{
Dialect: databaseFS.Dialect,
Format: "INSERT INTO pinned_file (parent_id, file_id, creation_time)" +
" SELECT {parentID}, file_id FROM files WHERE file_path = {filePath}" +
" ON DUPLICATE KEY UPDATE parent_id = parent_id",
Values: []any{
sq.UUIDParam("parentID", parentID),
sq.Param("filePath", nil),
},
})
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
default:
panic(fmt.Sprintf("unsupported dialect %q", databaseFS.Dialect))
}
group, groupctx := errgroup.WithContext(r.Context())
for _, name := range names {
name := name
if strings.Contains(name, "/") {
continue
}
group.Go(func() (err error) {
defer stacktrace.RecoverPanic(&err)
result, err := preparedExec.Exec(groupctx, sq.StringParam("filePath", path.Join(sitePrefix, response.Parent, name)))
if err != nil {
return stacktrace.New(err)
}
if result.RowsAffected > 0 {
numPinned.Add(1)
}
return nil
})
}
err = group.Wait()
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
err = tx.Commit()
if err != nil {
nbrew.GetLogger(r.Context()).Error(err.Error())
nbrew.InternalServerError(w, r, err)
return
}
response.NumPinned = int(numPinned.Load())
writeResponse(w, r, response)
}