This repository has been archived by the owner on Nov 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
source.go
384 lines (337 loc) · 9.09 KB
/
source.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
package core
import (
"database/sql"
"encoding/json"
"fmt"
"github.com/datatogether/sql_datastore"
"github.com/datatogether/sqlutil"
"github.com/ipfs/go-datastore"
"github.com/pborman/uuid"
"net/url"
"strings"
"time"
)
// Source is a concreate handle for archiving. Crawlers use
// source's url as a base of a link tree. Sources are connected
// to a parent Primer to provide context & organization.
type Source struct {
// version 4 uuid
Id string `json:"id"`
// Created timestamp rounded to seconds in UTC
Created time.Time `json:"created"`
// Updated timestamp rounded to seconds in UTC
Updated time.Time `json:"updated"`
// human-readable title for this source
Title string `json:"title"`
// description of the source, ideally one paragraph
Description string `json:"description"`
// absolute url to serve as the root of the
Url string `json:"url"`
// primer this source is connected to
Primer *Primer `json:"primer"`
// weather or not this url should be crawled be a web crawler
Crawl bool `json:"crawl"`
// amount of time before a link within this tree is considered in need
// of re-checking for changes. currently not in use, but planned.
StaleDuration time.Duration `json:"staleDuration"`
// yeah this'll probably get depricated. Part of a half-baked alerts feature idea.
LastAlertSent *time.Time `json:"lastAlertSent"`
// Metadata associated with this source that should be added to all
// child urls, currently not in use, but planned
Meta map[string]interface{} `json:"meta"`
// Stats about this source
Stats *SourceStats `json:"stats"`
}
type SourceStats struct {
UrlCount int `json:"urlCount"`
ArchivedUrlCount int `json:"archivedUrlCount"`
ContentUrlCount int `json:"contentUrlCount"`
ContentMetadataCount int `json:"contentMetadataCount"`
}
func (s Source) DatastoreType() string {
return "Source"
}
func (s Source) GetId() string {
return s.Id
}
func (s Source) Key() datastore.Key {
return datastore.NewKey(fmt.Sprintf("%s:%s", s.DatastoreType(), s.GetId()))
}
func (s *Source) CalcStats(db *sql.DB) error {
urlCount, err := s.urlCount(db)
if err != nil {
return err
}
contentUrlCount, err := s.contentUrlCount(db)
if err != nil {
return err
}
metadataCount, err := s.contentWithMetadataCount(db)
if err != nil {
return err
}
s.Stats = &SourceStats{
UrlCount: urlCount,
ContentUrlCount: contentUrlCount,
ContentMetadataCount: metadataCount,
}
// TODO - stop saving here & instead hook this up to some sort of cron task
store := sql_datastore.NewDatastore(db)
if err := store.Register(&Source{}); err != nil {
return err
}
return s.Save(store)
}
func (s *Source) urlCount(db sqlutil.Queryable) (count int, err error) {
err = db.QueryRow(qSourceUrlCount, "%"+s.Url+"%").Scan(&count)
return
}
func (s *Source) contentUrlCount(db sqlutil.Queryable) (count int, err error) {
err = db.QueryRow(qSourceContentUrlCount, "%"+s.Url+"%").Scan(&count)
return
}
func (s *Source) contentWithMetadataCount(db sqlutil.Queryable) (count int, err error) {
err = db.QueryRow(qSourceContentWithMetadataCount, "%"+s.Url+"%").Scan(&count)
return
}
// MatchesUrl checks to see if the url pattern of Source is contained
// within the passed-in url string
// TODO - make this more sophisticated, checking against the beginning of the
// url to avoid things like accidental matches, or urls in query params matching
// within rawurl
func (s *Source) MatchesUrl(rawurl string) bool {
return strings.Contains(rawurl, s.Url)
}
// AsUrl retrieves the url that corresponds for the crawlUrl. If one doesn't exist & the url is saved,
// a new url is created
func (c *Source) AsUrl(db *sql.DB) (*Url, error) {
// TODO - this assumes http protocol, make moar robust
addr, err := url.Parse(fmt.Sprintf("http://%s", c.Url))
if err != nil {
return nil, err
}
store := sql_datastore.NewDatastore(db)
if err := store.Register(&Url{}); err != nil {
return nil, err
}
u := &Url{Url: addr.String()}
if err := u.Read(store); err != nil {
if err == ErrNotFound {
if err := u.Save(store); err != nil {
return u, err
}
} else {
return nil, err
}
}
return u, nil
}
// TODO - this currently doesn't check the status of metadata, gonna need to do that
// UndescribedContent returns a list of content-urls from this subprimer that need work.
func (s *Source) UndescribedContent(db sqlutil.Queryable, limit, offset int) ([]*Url, error) {
rows, err := db.Query(qSourceUndescribedContentUrls, "%"+s.Url+"%", limit, offset)
if err != nil {
return nil, err
}
defer rows.Close()
urls := make([]*Url, limit)
i := 0
for rows.Next() {
u := &Url{}
if err := u.UnmarshalSQL(rows); err != nil {
return nil, err
}
urls[i] = u
i++
}
return urls[:i], nil
}
// TODO - this currently doesn't check the status of metadata, gonna need to do that
// DescribedContent returns a list of content-urls from this subprimer that need work.
func (s *Source) DescribedContent(db sqlutil.Queryable, limit, offset int) ([]*Url, error) {
rows, err := db.Query(qSourceDescribedContentUrls, "%"+s.Url+"%", limit, offset)
if err != nil {
return nil, err
}
defer rows.Close()
urls := make([]*Url, limit)
i := 0
for rows.Next() {
u := &Url{}
if err := u.UnmarshalSQL(rows); err != nil {
return nil, err
}
urls[i] = u
i++
}
return urls[:i], nil
}
// func (s *Source) Stats() {
// }
func (s *Source) Read(store datastore.Datastore) error {
if s.Id != "" {
ci, err := store.Get(s.Key())
if err != nil {
return err
}
got, ok := ci.(*Source)
if !ok {
return ErrInvalidResponse
}
*s = *got
return nil
} else if s.Url != "" {
// TODO - figure out a way to query stores by url...
if sqlstore, ok := store.(*sql_datastore.Datastore); ok {
row := sqlstore.DB.QueryRow(qSourceByUrl, s.Url)
return s.UnmarshalSQL(row)
}
}
return ErrNotFound
}
func (s *Source) Save(store datastore.Datastore) (err error) {
var exists bool
if s.Id != "" {
exists, err = store.Has(s.Key())
if err != nil {
return err
}
}
if !exists {
s.Id = uuid.New()
s.Created = time.Now().Round(time.Second)
s.Updated = s.Created
} else {
s.Updated = time.Now().Round(time.Second)
}
return store.Put(s.Key(), s)
}
func (s *Source) Delete(store datastore.Datastore) error {
return store.Delete(s.Key())
}
func (s *Source) NewSQLModel(key datastore.Key) sql_datastore.Model {
return &Source{
Id: key.Name(),
Url: s.Url,
}
}
func (s *Source) SQLQuery(cmd sql_datastore.Cmd) string {
switch cmd {
case sql_datastore.CmdCreateTable:
return qSourceCreateTable
case sql_datastore.CmdExistsOne:
if s.Id != "" {
return qSourceExists
} else {
return qSourceExistsByUrl
}
case sql_datastore.CmdSelectOne:
if s.Id != "" {
return qSourceById
} else {
return qSourceByUrl
}
case sql_datastore.CmdInsertOne:
return qSourceInsert
case sql_datastore.CmdUpdateOne:
return qSourceUpdate
case sql_datastore.CmdDeleteOne:
return qSourceDelete
case sql_datastore.CmdList:
return qSourcesList
default:
return ""
}
}
func (s *Source) SQLParams(cmd sql_datastore.Cmd) []interface{} {
switch cmd {
case sql_datastore.CmdList:
return []interface{}{}
case sql_datastore.CmdSelectOne, sql_datastore.CmdExistsOne:
if s.Id != "" {
return []interface{}{s.Id}
} else {
return []interface{}{s.Url}
}
case sql_datastore.CmdDeleteOne:
return []interface{}{s.Id}
default:
date := s.LastAlertSent
if date != nil {
utc := date.In(time.UTC)
date = &utc
}
metaBytes, err := json.Marshal(s.Meta)
if err != nil {
panic(err)
}
statBytes, err := json.Marshal(s.Stats)
if err != nil {
panic(err)
}
if s.Primer == nil {
s.Primer = &Primer{}
}
return []interface{}{
s.Id,
s.Created.In(time.UTC),
s.Updated.In(time.UTC),
s.Title,
s.Description,
s.Url,
s.Primer.Id,
s.Crawl,
s.StaleDuration / 1000000,
date,
metaBytes,
statBytes,
}
}
}
func (c *Source) UnmarshalSQL(row sqlutil.Scannable) error {
var (
id, url, pId, title, description string
created, updated time.Time
lastAlert *time.Time
stale int64
crawl bool
metaBytes, statsBytes []byte
)
if err := row.Scan(&id, &created, &updated, &title, &description, &url, &pId, &crawl, &stale, &lastAlert, &metaBytes, &statsBytes); err != nil {
if err == sql.ErrNoRows {
return ErrNotFound
}
return err
}
if lastAlert != nil {
utc := lastAlert.In(time.UTC)
lastAlert = &utc
}
var meta map[string]interface{}
if metaBytes != nil {
if err := json.Unmarshal(metaBytes, &meta); err != nil {
return err
}
}
stats := &SourceStats{}
if statsBytes != nil {
if err := json.Unmarshal(statsBytes, stats); err != nil {
return err
}
}
*c = Source{
Id: id,
Created: created.In(time.UTC),
Updated: updated.In(time.UTC),
Title: title,
Description: description,
Url: url,
Primer: &Primer{Id: pId},
Crawl: crawl,
StaleDuration: time.Duration(stale * 1000000),
LastAlertSent: lastAlert,
Meta: meta,
Stats: stats,
}
return nil
}