/
playground.go
235 lines (190 loc) · 6.12 KB
/
playground.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
// Package playground provides a handler.MatchFn and a Client struct with a
// Handler method that can be used as handler.ActionFn.
package playground
import (
"bytes"
"context"
"fmt"
"html"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/gobridge/gopherbot/handler"
"github.com/gobridge/gopherbot/mparser"
"github.com/gobridge/gopherbot/workqueue"
"github.com/rs/zerolog"
)
// Client is the Go Playground client.
type Client struct {
httpc *http.Client
logger zerolog.Logger
blacklist map[string]struct{}
}
// New takes an HTTP client and returns a Playground Client. If httpc is nil
// this program will probably panic at some point.
func New(httpc *http.Client, logger zerolog.Logger, channelBlacklist []string) *Client {
m := make(map[string]struct{}, len(channelBlacklist))
for _, cid := range channelBlacklist {
m[cid] = struct{}{}
}
return &Client{
httpc: httpc,
logger: logger,
blacklist: m,
}
}
// Handler is a handler.ActionFn.
func (c *Client) Handler(ctx workqueue.Context, m handler.Messenger, r handler.Responder) error {
for _, file := range m.Files() {
if file.Filetype == "go" || file.Filetype == "text" {
return c.pgForFiles(ctx, m, r)
}
}
return c.pgForMessage(ctx, m, r)
}
func (c *Client) pgForMessage(ctx workqueue.Context, m handler.Messenger, r handler.Responder) error {
link, err := c.upload(ctx, messageToPlayground(m.Text()))
if err != nil {
return fmt.Errorf("failed to upload to playground: %w", err)
}
mention := mparser.Mention{
Type: mparser.TypeUser,
ID: m.UserID(),
}
msg := fmt.Sprintf("The above code from %s in the playground: <%s>", mention.String(), link)
err = r.Respond(ctx, msg)
if err != nil {
return fmt.Errorf("failed to send message with Playground link: %w", err)
}
err = r.RespondEphemeral(ctx, `I've noticed you've written a large block of text (more than 9 lines). `+
`To faciliate collaboration and make the conversation easier to follow, `+
`please consider using <https://go.dev/play/> to share code. If you wish to not `+
`link against the playground, please start the message with "nolink". Thank you!`,
)
if err != nil {
ctx.Logger().Error().
Err(err).
Msg("failed to respond with ephemeral Go Playground etiquette")
}
return nil
}
func (c *Client) pgForFiles(ctx workqueue.Context, m handler.Messenger, r handler.Responder) error {
sc := ctx.Slack()
files := m.Files()
// XXX(theckman): following comment and code has been copied verbatim from gopherv1
//
// Empirically, attempting to call GetFileInfoContext too quickly after a
// file is uploaded can cause a "file_not_found" error.
time.Sleep(1 * time.Second)
for _, f := range files {
i, _, _, err := sc.GetFileInfoContext(ctx, f.ID, 0, 0)
if err != nil {
return fmt.Errorf("failed to get file info for %s: %w", f.ID, err)
}
if i.Lines < 6 || i.PrettyType == "Plain Text" {
return nil
}
buf := &bytes.Buffer{}
err = sc.GetFile(i.URLPrivateDownload, buf)
if err != nil {
return fmt.Errorf("failed to get file %s: %w", f.ID, err)
}
link, err := c.upload(ctx, buf)
if err != nil {
return fmt.Errorf("failed to upload to playground: %w", err)
}
mention := mparser.Mention{
Type: mparser.TypeUser,
ID: m.UserID(),
}
msg := fmt.Sprintf("The above code from %s in the playground: <%s>", mention.String(), link)
err = r.Respond(ctx, msg)
if err != nil {
return fmt.Errorf("failed to send message with Playground link: %w", err)
}
}
err := r.RespondEphemeral(ctx, `I've noticed you uploaded a Go file. To facilitate collaboration and make `+
`it easier for others to share back the snippet, please consider using: `+
`<https://go.dev/play/>. If you wish to not link against the playground, please use `+
`"nolink" in the message. Thank you!`,
)
if err != nil {
ctx.Logger().Error().
Err(err).
Msg("failed to respond with ephemeral Go Playground etiquette")
}
return nil
}
func (c *Client) upload(ctx context.Context, body io.Reader) (link string, err error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://go.dev/_/share", body)
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
req.Header.Add("User-Agent", "Gophers Slack Bot V2")
resp, err := c.httpc.Do(req)
if err != nil {
return "", err
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != 200 {
return "", fmt.Errorf("unexpected HTTP response status: %s", resp.Status)
}
id, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("failed to read response body: %w", err)
}
return "https://go.dev/play/p/" + string(id), nil
}
// MessageMatchFn satisfies handler.MessageMatchFn
func (c *Client) MessageMatchFn(shadowMode bool, m handler.Messenger) bool {
// channel is blacklisted
if _, ok := c.blacklist[m.ChannelID()]; ok {
c.logger.Debug().
Str("reason", "channel not permitted").
Msg("playground match skipped")
return false
}
rt := m.RawText()
if strings.Contains(rt, "nolink") || (len(m.Files()) == 0 && strings.Count(rt, "\n") < 10) {
return false
}
if shadowMode {
c.logger.Debug().
Str("reason", "shadow mode").
Msg("playground match skipped")
return false
}
return true
}
// messageToPlayground converts the text of a post into code for the playground. It is not perfect but works most of the time.
// Text outside of ``` quotes is converted into a comment and included in the code, everything inside of those quotes is
// considered code and pasted as-is.
func messageToPlayground(text string) *bytes.Buffer {
var buf bytes.Buffer
// unescape the post to prevent the insertion of HTML escapes into the playground
text = html.UnescapeString(text)
parts := strings.Split(text, "```")
for i, part := range parts {
part = strings.Trim(part, "\n")
if i&1 == 0 {
// it's a comment
if strings.TrimSpace(part) == "" {
continue
}
buf.WriteString("\n// ")
buf.WriteString(strings.Replace(part, "\n", "\n// ", -1))
buf.WriteString("\n\n")
} else {
// it's code
if part == "" {
continue
}
buf.WriteString(part)
buf.WriteByte('\n')
}
}
return &buf
}