-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
117 lines (108 loc) · 2.66 KB
/
main.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
package main
import (
"encoding/json"
"flag"
"fmt"
"net/http"
"net/url"
"os"
"regexp"
"github.com/gin-gonic/gin"
"github.com/mattn/go-lingr"
)
type resp struct {
Items []struct {
Tags []string `json:"tags"`
Owner struct {
Reputation int `json:"reputation"`
UserID int `json:"user_id"`
UserType string `json:"user_type"`
ProfileImage string `json:"profile_image"`
DisplayName string `json:"display_name"`
Link string `json:"link"`
} `json:"owner"`
IsAnswered bool `json:"is_answered"`
ViewCount int `json:"view_count"`
AnswerCount int `json:"answer_count"`
Score int `json:"score"`
LastActivityDate int `json:"last_activity_date"`
CreationDate int `json:"creation_date"`
QuestionID int `json:"question_id"`
Link string `json:"link"`
Title string `json:"title"`
} `json:"items"`
HasMore bool `json:"has_more"`
QuotaMax int `json:"quota_max"`
QuotaRemaining int `json:"quota_remaining"`
}
var re = regexp.MustCompile(`^stackoverflow(?:\w+) (.+)$`)
func defaultAddr() string {
port := os.Getenv("PORT")
if port == "" {
return ":80"
}
return ":" + port
}
var addr = flag.String("addr", defaultAddr(), "server address")
func main() {
flag.Parse()
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.String(200, "")
})
f := func(c *gin.Context) {
site := c.Params.ByName("site")
if site == "" {
site = "stackoverflow"
}
var status lingr.Status
if !c.EnsureBody(&status) {
return
}
urls := ""
for _, event := range status.Events {
message := event.Message
if message == nil {
continue
}
if !re.MatchString(message.Text) {
continue
}
question := re.FindStringSubmatch(message.Text)[1]
params := url.Values{}
params.Add("intitle", question)
params.Add("site", site)
params.Add("sort", "activity")
params.Add("order", "desc")
res, err := http.Get("https://api.stackexchange.com/2.2/search?" + params.Encode())
println("https://api.stackexchange.com/2.2/search?" + params.Encode())
if err != nil {
println(err.Error())
continue
}
defer res.Body.Close()
var resp resp
if err := json.NewDecoder(res.Body).Decode(&resp); err != nil {
println(err.Error())
continue
}
for _, item := range resp.Items {
u := item.Link
if len(u) > 300 {
u = fmt.Sprintf("http://%s.com/q/%d", site, item.QuestionID)
}
s := fmt.Sprintf("%s\n%s\n", item.Title, u)
println(s)
if len(urls+s) > 1000 {
break
}
urls += s
}
}
c.String(200, urls)
return
}
r.POST("/", f)
r.POST("/:site", f)
r.Run(*addr)
}