-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontent.go
322 lines (268 loc) · 7.81 KB
/
content.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
package main
import (
"context"
"crypto/sha256"
"database/sql"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/jxskiss/base62"
"golang.org/x/time/rate"
)
type content struct {
id string
title string
text string
}
func processExternalContentURLs(ctx context.Context, db *sql.DB, limiter *rate.Limiter, args []string) error {
if err := checkPDF(); err != nil {
return err
}
urls, err := unfetchedURLs(ctx, db)
if err != nil {
return fmt.Errorf("unfetched urls: %w", err)
}
log.Println("need", len(urls), "external content urls")
start := time.Now()
for i, u := range urls {
if err := limiter.Wait(ctx); err != nil {
return fmt.Errorf("process %v: %w", u, err)
}
if err := processURL(ctx, db, u); err != nil {
return fmt.Errorf("process %v: %w", u, err)
}
if (i+1)%10 == 0 {
log.Println("completed", i+1, "/", len(urls), "external content urls")
}
if time.Since(start) > 30*time.Minute {
log.Println("completed", i+1, "/", len(urls), "external content urls and ran out of time")
return nil
}
}
log.Println("completed", len(urls), "external content urls")
return nil
}
func unfetchedURLs(ctx context.Context, db *sql.DB) ([]string, error) {
rows, err := db.Query("select url from external_content_urls where fetched is null limit 500")
if err != nil {
return nil, fmt.Errorf("select: %w", err)
}
defer rows.Close()
var urls []string
for rows.Next() {
var u string
if err := rows.Scan(&u); err != nil {
return nil, fmt.Errorf("scan: %w", err)
}
urls = append(urls, u)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("select: %w", err)
}
return urls, nil
}
func processURL(ctx context.Context, db *sql.DB, u string) error {
now := time.Now()
saveErr := func(ferr error) error {
_, err := db.Exec("update external_content_urls set fetched=?, error=? where url=?", newTimeValue(&now), ferr.Error(), u)
if err != nil {
return fmt.Errorf("update external_content_urls: %w", err)
}
return nil
}
uc, ferr := fetchURLContent(ctx, u)
if ferr != nil {
if err := saveErr(ferr); err != nil {
return fmt.Errorf("save error: %w", err)
}
return nil
}
defer uc.f.Close()
defer os.Remove(uc.f.Name())
c := content{id: uc.contentID}
exists, err := contentExists(ctx, db, c.id)
if err != nil {
return fmt.Errorf("checking content ID %v existence: %w", c.id, err)
}
if !exists {
switch uc.contentType {
case "application/pdf":
p, perr := processPDF(ctx, uc.f)
if err != nil {
if err := saveErr(perr); err != nil {
return fmt.Errorf("save error: %w", err)
}
return nil
}
c.title = p.title
c.text = p.text
}
}
tx, err := db.Begin()
if err != nil {
return fmt.Errorf("begin tx: %w", err)
}
defer tx.Rollback()
if !exists {
if err := saveContent(ctx, tx, c); err != nil {
return fmt.Errorf("saving content ID %v: %w", c.id, err)
}
}
var etag sql.NullString
if uc.etag != "" {
etag.Valid = true
etag.String = uc.etag
}
if _, err := tx.Exec("update external_content_urls set fetched=?, content_type=?, size=?, last_modified=?, etag=?, error=?, external_content_id=? where url=?", newTimeValue(&now), uc.contentType, uc.size, newTimeValue(&uc.lastModified), etag, nil, c.id, u); err != nil {
return fmt.Errorf("update external_content_urls: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit: %w", err)
}
return nil
}
func contentExists(ctx context.Context, db *sql.DB, id string) (bool, error) {
var exists bool
if err := db.QueryRow("select 1 from external_content where id=?", id).Scan(&exists); err != nil && !errors.Is(err, sql.ErrNoRows) {
return false, fmt.Errorf("select: %w", err)
}
return exists, nil
}
func saveContent(ctx context.Context, tx *sql.Tx, c content) error {
if _, err := tx.Exec("insert into external_content (id, title, text) values (?, ?, ?) on conflict do nothing", c.id, c.title, c.text); err != nil {
return fmt.Errorf("insert content: %w", err)
}
const sq = `insert into external_content_search (rowid, title, text) values ((select rowid from external_content where id=?), ?, ?)`
if _, err := tx.Exec(sq, c.id, c.title, c.text); err != nil {
return fmt.Errorf("insert content search: %w", err)
}
return nil
}
type urlContent struct {
f *os.File
contentType string
contentID string
size int64
lastModified time.Time
etag string
}
func fetchURLContent(ctx context.Context, u string) (_ urlContent, rerr error) {
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", u, nil)
if err != nil {
return urlContent{}, fmt.Errorf("new request: %w", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return urlContent{}, fmt.Errorf("fetch: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return urlContent{}, fmt.Errorf("fetch: bad status %v", resp.StatusCode)
}
f, err := os.CreateTemp("", "fetchURLContent")
if err != nil {
return urlContent{}, fmt.Errorf("fetch: %w", err)
}
defer func() {
if rerr == nil {
return
}
f.Close()
}()
contentSum := sha256.New224()
size, err := io.Copy(io.MultiWriter(f, contentSum), resp.Body)
if err != nil {
return urlContent{}, fmt.Errorf("fetch: %w", err)
}
contentID := base62.EncodeToString(contentSum.Sum(nil))
if _, err := f.Seek(0, 0); err != nil {
return urlContent{}, fmt.Errorf("fetch: %w", err)
}
var lastModified time.Time
if lm := resp.Header.Get("Last-Modified"); lm != "" {
t, err := time.Parse(time.RFC1123, lm)
if err == nil {
lastModified = t
}
}
return urlContent{f, resp.Header.Get("Content-Type"), contentID, size, lastModified, resp.Header.Get("ETag")}, nil
}
type pdf struct {
title string
text string
}
func checkPDF() error {
for _, cmd := range []string{"pdfinfo", "pdftotext", "pdftoppm", "tesseract"} {
_, err := exec.LookPath(cmd)
if err != nil {
return fmt.Errorf("missing %v, need to install poppler-utils and tesseract-ocr on ubuntu or poppler and tesseract via homebrew: %w", cmd, err)
}
}
return nil
}
func processPDF(ctx context.Context, f *os.File) (pdf, error) {
ctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
tc := exec.CommandContext(ctx, "pdfinfo", f.Name())
out, err := tc.Output()
if err != nil {
return pdf{}, fmt.Errorf("pdfinfo: %w", err)
}
var title string
for l := range strings.SplitSeq(string(out), "\n") {
if strings.HasPrefix(l, "Title:") {
title = l
break
}
}
title = strings.TrimSpace(strings.TrimPrefix(title, "Title:"))
title = strings.TrimSpace(strings.TrimSuffix(title, "| Halifax.ca"))
tc = exec.CommandContext(ctx, "pdftotext", f.Name(), "-")
out, err = tc.Output()
if err != nil {
return pdf{}, fmt.Errorf("pdftotext: %w", err)
}
if text := strings.TrimSpace(string(out)); text != "" {
return pdf{title, text}, nil
}
td, err := os.MkdirTemp("", "processPDF")
if err != nil {
return pdf{}, fmt.Errorf("mkdir temp: %w", err)
}
defer os.RemoveAll(td)
tc = exec.CommandContext(ctx, "pdftoppm", "-png", f.Name(), filepath.Join(td, "page"))
if err := tc.Run(); err != nil {
return pdf{}, fmt.Errorf("pdftoppm: %w", err)
}
pageFns, err := filepath.Glob(filepath.Join(td, "page*.png"))
if err != nil {
return pdf{}, fmt.Errorf("glob: %w", err)
}
for _, pageFn := range pageFns {
if err := exec.CommandContext(ctx, "tesseract", pageFn, pageFn).Run(); err != nil {
return pdf{}, fmt.Errorf("tesseract: %w", err)
}
}
textFns, err := filepath.Glob(filepath.Join(td, "page*.txt"))
if err != nil {
return pdf{}, fmt.Errorf("glob: %w", err)
}
var text string
for _, textFn := range textFns {
b, err := os.ReadFile(textFn)
if err != nil {
return pdf{}, fmt.Errorf("read text: %w", err)
}
text += string(b) + "\n"
}
return pdf{title, strings.TrimSpace(text)}, nil
}