forked from mangalorg/luaprovider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
document.go
96 lines (79 loc) · 1.96 KB
/
document.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
package html
import (
md "github.com/JohannesKaufmann/html-to-markdown"
"github.com/PuerkitoBio/goquery"
"github.com/cixtor/readability"
lua "github.com/yuin/gopher-lua"
"strings"
)
const documentTypeName = libName + "_document"
func checkDocument(L *lua.LState, n int) *goquery.Document {
ud := L.CheckUserData(n)
if v, ok := ud.Value.(*goquery.Document); ok {
return v
}
L.ArgError(1, "document expected")
return nil
}
func pushDocument(L *lua.LState, document *goquery.Document) {
ud := L.NewUserData()
ud.Value = document
L.SetMetatable(ud, L.GetTypeMetatable(documentTypeName))
L.Push(ud)
}
func parse(L *lua.LState) int {
value := L.CheckString(1)
reader := strings.NewReader(value)
document, err := goquery.NewDocumentFromReader(reader)
if err != nil {
L.RaiseError(err.Error())
return 0
}
pushDocument(L, document)
return 1
}
func documentFind(L *lua.LState) int {
document := checkDocument(L, 1)
selector := L.CheckString(2)
selection := document.Find(selector)
pushSelection(L, selection)
return 1
}
func documentHtml(L *lua.LState) int {
document := checkDocument(L, 1)
html, err := document.Html()
if err != nil {
L.RaiseError(err.Error())
return 0
}
L.Push(lua.LString(html))
return 1
}
func documentSelection(L *lua.LState) int {
document := checkDocument(L, 1)
selection := document.Selection
pushSelection(L, selection)
return 1
}
func documentMarkdown(L *lua.LState) int {
document := checkDocument(L, 1)
converter := md.NewConverter("", true, nil)
L.Push(lua.LString(converter.Convert(document.Selection)))
return 1
}
func documentSimplified(L *lua.LState) int {
document := checkDocument(L, 1)
html, err := document.Html()
if err != nil {
L.RaiseError(err.Error())
return 0
}
article, err := readability.New().Parse(strings.NewReader(html), "https://example.com")
if err != nil {
L.RaiseError(err.Error())
return 0
}
document = goquery.NewDocumentFromNode(article.Node)
pushDocument(L, document)
return 1
}