-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsubmission.go
259 lines (235 loc) · 7.09 KB
/
submission.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package main
import (
"context"
"errors"
"fmt"
"math"
"strings"
"github.com/andersfylling/disgord"
"github.com/meooow25/cfspy/bot"
"github.com/meooow25/cfspy/fetch"
)
var languageNameToExt = map[string]string{
// Available in the filter options on the status page of contests, as of 2022-10-12.
"GNU C11": "c",
"Clang++20 Diagnostics": "cpp",
"Clang++17 Diagnostics": "cpp",
"GNU C++14": "cpp",
"GNU C++17": "cpp",
"GNU C++20 (64)": "cpp",
"MS C++ 2017": "cpp",
"GNU C++17 (64)": "cpp",
"C# 8": "cs",
"C# 10": "cs",
"Mono C#": "cs",
"D": "d",
"Go": "go",
"Haskell": "hs",
"Java 11": "java",
"Java 17": "java",
"Java 8": "java",
"Kotlin 1.4": "kt",
"Kotlin 1.5": "kt",
"Kotlin 1.6": "kt",
"Ocaml": "ml",
"Delphi": "pas",
"FPC": "pas",
"PascalABC.NET": "pas",
"Perl": "pl",
"PHP": "php",
"Python 2": "py",
"Python 3": "py",
"PyPy 2": "py",
"PyPy 3": "py",
"PyPy 3-64": "py",
"Ruby 3": "rb",
"Rust 2021": "rs",
"Scala": "sc",
"JavaScript": "js",
"Node.js": "js",
// Some old ones. I have no way of getting an exhaustive list of these removed names.
"GNU C": "c",
"GNU C++": "cpp",
"GNU C++0x": "cpp",
"Java 6": "java",
"Java 7": "java",
"GNU C++11": "cpp",
"MS C++": "cpp",
"Kotlin": "kt",
"Ruby": "rb",
".NET Core C#": "cs",
"Rust": "rs",
}
// The number of lines beyond which the snippet is sent as a file instead of message text.
// This is because Discord's new file previews are nice and collapsible, taking up less space
// compared to a wall of text in the message body.
// The value below is chosen because it seems reasonable to me.
const maxSnippetMsgLines = 30
var (
errSelectionEmpty = errors.New("Selected lines are empty")
errMissingAuthor = errors.New("Missing author details in submission info")
)
const (
ghostColor = 0x999999 // Same color as text on CF
teamColor = 0x666666 // Darker than ghosts
)
// Installs the submission watcher feature. The bot watches for Codeforces submission links and
// responds with an embed containing info about the submission. If the submission has line numbers,
// responds with the lines.
func installSubmissionFeature(bot *bot.Bot) {
bot.Client.Logger().Info("Setting up CF submission feature")
bot.OnMessageCreate(maybeHandleSubmissionURL)
}
func maybeHandleSubmissionURL(ctx *bot.Context, evt *disgord.MessageCreate) {
go func() {
submissionURLMatches := fetch.ParseSubmissionURLs(evt.Message.Content)
if len(submissionURLMatches) == 0 {
return
}
first := submissionURLMatches[0]
handleSubmissionURL(ctx, first)
}()
}
// Fetches the submission page and responds on the Discord channel.
func handleSubmissionURL(ctx *bot.Context, match *fetch.SubmissionURLMatch) {
ctx.Logger.Info("Processing submission URL: ", match.URL)
submissionInfo, err := fetch.Submission(context.Background(), match.URL)
if err != nil {
err = fmt.Errorf("Error fetching submission from %v: %w", match.URL, err)
ctx.Logger.Error(err)
respondWithError(ctx, err)
return
}
content, embed, file, err :=
makeSubmissionResponse(submissionInfo, match.LineBegin, match.LineEnd)
if err != nil {
ctx.Logger.Error(err)
respondWithError(ctx, err)
return
}
page := bot.NewPage(content, embed)
if file != nil {
err = respondWithOnePagePreview(ctx, page, *file)
} else {
err = respondWithOnePagePreview(ctx, page)
}
if err != nil {
ctx.Logger.Error(fmt.Errorf("Error sending problem info: %w", err))
}
}
func makeSubmissionResponse(
info *fetch.SubmissionInfo,
lineBegin int,
lineEnd int,
) (string, *disgord.Embed, *disgord.CreateMessageFileParams, error) {
// No line numbers, show summary
if lineBegin == 0 {
embed, err := makeSubmissionEmbed(info)
return "", embed, nil, err
}
snippet, numLines, err := makeCodeSnippet(info.Content, lineBegin, lineEnd)
if err != nil {
return "", nil, nil, err
}
content := makeContent(snippet, info.Language)
// Content ok in a message, send
if numLines <= maxSnippetMsgLines && !bot.ContentTooLong(content) {
return content, nil, nil, nil
}
// Content too large or ugly in a message, send as file
// The file size is never expected to be too large as Codeforces source limit is 64KB
// and Discord limit is 8MB
file := &disgord.CreateMessageFileParams{
Reader: strings.NewReader(snippet),
FileName: makeFilename(info.ID, info.Language),
}
return "", nil, file, nil
}
func makeSubmissionEmbed(s *fetch.SubmissionInfo) (*disgord.Embed, error) {
prefix := ""
if s.Verdict == "Accepted" || strings.HasPrefix(s.Verdict, "Perfect result") {
prefix = "✅ "
}
var author string
var color int
switch {
case s.Author != nil:
author = s.Author.Handle
color = s.Author.Color
case s.AuthorGhost != "":
author = s.AuthorGhost + " 👻"
color = ghostColor
case s.AuthorTeam != nil:
var handles []string
for _, author := range s.AuthorTeam.Authors {
handles = append(handles, author.Handle)
}
author = s.AuthorTeam.Name + ": " + strings.Join(handles, ", ")
color = teamColor
default:
// not expected
return nil, errMissingAuthor
}
language := s.Language
if language == "Unknown" { // Happens for ghosts
language = "Unknown language"
}
embed := &disgord.Embed{
Title: "Submission for " + s.Problem + " by " + author,
URL: s.URL,
Color: color,
Description: prefix + s.Verdict + " • " + s.ParticipantType + " • " + language,
Timestamp: disgord.Time{Time: s.SentTime},
}
return embed, nil
}
func makeCodeSnippet(code string, begin, end int) (snippet string, numLines int, err error) {
code = strings.ReplaceAll(code, "\r\n", "\n")
lines := strings.Split(code, "\n")
begin, end = clamp(begin, 1, len(lines)), clamp(end, 1, len(lines))
lines = lines[begin-1 : end]
// This might not look nice if there are mixed spaces and tabs.
// But if you write such code, you deserve it.
minSpaceCount := math.MaxInt32
for _, line := range lines {
for i, c := range line {
if c != ' ' && c != '\t' {
if i < minSpaceCount {
minSpaceCount = i
}
break
}
}
}
allEmpty := true
for i := range lines {
if len(lines[i]) > minSpaceCount {
lines[i] = lines[i][minSpaceCount:]
allEmpty = false
} else {
lines[i] = ""
}
}
if allEmpty {
return "", 0, errSelectionEmpty
}
return strings.Join(lines, "\n"), len(lines), nil
}
func makeContent(snippet, language string) string {
return "```" + languageNameToExt[language] + "\n" + snippet + "```"
}
func makeFilename(id, language string) string {
var ext string
if ext = languageNameToExt[language]; ext == "" {
ext = "txt"
}
return "snippet_" + id + "." + ext
}
func clamp(x, low, high int) int {
if x < low {
x = low
} else if x > high {
x = high
}
return x
}