-
Notifications
You must be signed in to change notification settings - Fork 12
/
attrs.go
88 lines (70 loc) · 2.13 KB
/
attrs.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
package main
import (
"strings"
"github.com/PuerkitoBio/goquery"
"go.riyazali.net/sqlite"
)
/** html_attribute_get(document, selector, name)
* html_attr_get(document, selector, name)
* Get the value of the "name" attribute from the element found in document, using selector
**/
type HtmlAttributeGetFunc struct{}
func (*HtmlAttributeGetFunc) Deterministic() bool { return true }
func (*HtmlAttributeGetFunc) Args() int { return 3 }
func (*HtmlAttributeGetFunc) Apply(c *sqlite.Context, values ...sqlite.Value) {
html := values[0].Text()
selector := values[1].Text()
attribute := values[2].Text()
doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
if err != nil {
c.ResultError(err)
return
}
attr, exists := doc.FindMatcher(goquery.Single(selector)).Attr(attribute)
if !exists {
c.ResultNull()
} else {
c.ResultText(attr)
}
}
/** html_attribute_has(document, selector, name)
* html_attr_has(document, selector, name)
* Returns 1 or 0, if the "name" attribute from the element
* found in document, using selector, exists
**/
//
type HtmlAttributeHasFunc struct{}
func (*HtmlAttributeHasFunc) Deterministic() bool { return true }
func (*HtmlAttributeHasFunc) Args() int { return 3 }
func (*HtmlAttributeHasFunc) Apply(c *sqlite.Context, values ...sqlite.Value) {
html := values[0].Text()
selector := values[1].Text()
attribute := values[2].Text()
doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
if err != nil {
c.ResultError(err)
return
}
_, exists := doc.FindMatcher(goquery.Single(selector)).Attr(attribute)
if !exists {
c.ResultInt(0)
} else {
c.ResultInt(1)
}
}
func RegisterAttrs(api *sqlite.ExtensionApi) error {
var err error
if err = api.CreateFunction("html_attribute_get", &HtmlAttributeGetFunc{}); err != nil {
return err
}
if err = api.CreateFunction("html_attr_get", &HtmlAttributeGetFunc{}); err != nil {
return err
}
if err = api.CreateFunction("html_attribute_has", &HtmlAttributeHasFunc{}); err != nil {
return err
}
if err = api.CreateFunction("html_attr_has", &HtmlAttributeHasFunc{}); err != nil {
return err
}
return nil
}