-
Notifications
You must be signed in to change notification settings - Fork 14
/
PluginIndexBrowser.go
111 lines (100 loc) · 2.47 KB
/
PluginIndexBrowser.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
package wpfinger
import (
"encoding/json"
"github.com/hetiansu5/urlquery"
"log"
"net/http"
)
func Search(browse string) chan PluginInfo {
currentPage := 1
maxPage := 1
pluginChan := make(chan PluginInfo)
go func() {
defer close(pluginChan)
for {
if currentPage > maxPage {
break
}
response, err := searchPage(currentPage)
if err != nil {
break
}
if currentPage == 1 {
maxPage = response.Info.Pages
}
for _, plugin := range response.Plugins {
pluginChan <- plugin
}
currentPage++
}
}()
return pluginChan
}
func searchPage(page int) (*PluginInfoQueryPluginsResponse, error) {
queryStruct := PluginInfoQueryPlugins{
Action: "query_plugins",
Request: PluginInfoQueryPluginsRequest{
Browse: "popular",
Page: page,
Fields: map[string]bool{
"versions": true,
},
},
}
values, err := urlquery.Marshal(queryStruct)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodGet, "http://api.wordpress.org/plugins/info/1.2/?"+string(values), nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "Wordpress/1.0")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
decoder := json.NewDecoder(resp.Body)
var response PluginInfoQueryPluginsResponse
err = decoder.Decode(&response)
if err != nil {
log.Println(err)
return nil, err
}
return &response, nil
}
type PluginInfoQueryPlugins struct {
Action string `query:"action"`
Request PluginInfoQueryPluginsRequest `query:"request"`
}
type PluginInfoQueryPluginsRequest struct {
Browse string `query:"browse,omitempty"`
Search string `query:"search,omitempty"`
Tag string `query:"tag,omitempty"`
Author string `query:"author,omitempty"`
Page int `query:"page"`
Fields map[string]bool `query:"fields"`
}
type PluginInfoQueryPluginsResponse struct {
Info struct {
Page int `json:"page"`
Pages int `json:"pages"`
Results int `json:"results"`
} `json:"info"`
Plugins []PluginInfo `json:"plugins"`
}
type PluginInfo struct {
Name string `json:"name"`
Slug string `json:"slug"`
Version string `json:"version"`
Versions VersionList `json:"versions"`
Downloaded int `json:"downloaded"`
}
type VersionList map[string]string
func (i *VersionList) UnmarshalJSON(data []byte) error {
if string(data) == `[]` {
return nil
}
type tmp VersionList
return json.Unmarshal(data, (*tmp)(i))
}