-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmain.user.js
More file actions
393 lines (384 loc) · 13.4 KB
/
main.user.js
File metadata and controls
393 lines (384 loc) · 13.4 KB
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
// ==UserScript==
// @name cf-fast-submit
// @name:ja cf-fast-submit
// @namespace https://github.com/LumaKernel/cf-fast-submit
// @version 2.11
// @description append the form to submit to codeforces contest problem page.
// @description:ja codeforcesのコンテストの問題ページに提出フォームを置くツール.
// @author Luma
// @match http://codeforces.com/contest/*/problem/*
// @match http://codeforces.com/gym/*/problem/*
// @match http://codeforces.com/problemset/problem/*
// @match http://codeforces.com/group/*/contest/*/problem/*
// @match http://*.contest.codeforces.com/group/*/contest/*/problem/*
// @match https://codeforces.com/contest/*/problem/*
// @match https://codeforces.com/gym/*/problem/*
// @match https://codeforces.com/problemset/problem/*
// @match https://codeforces.com/group/*/contest/*/problem/*
// @match https://*.contest.codeforces.com/group/*/contest/*/problem/*
// @grant none
// ==/UserScript==
/* global $ ace Codeforces */
;(function () {
'use strict'
const openNewWindow = false
const SCRIPT_NAME = 'cf fast submit'
const origin = location.origin
const pathname = location.pathname
const modelist = ace.require('ace/ext/modelist')
const logged = !!$('a').filter((_, el) => $(el).text() === 'Logout' || $(el).text() === 'Выйти').length
let $form
let $programType
let $toggleEditor
let $tabSize
let $selectProblem
let editor
// ~/0 というURLは A 問題として扱われる
const startId = '0'
const defaultProblemIds = ['A', 'A1']
const pattern = /(contest|gym)\/(.*)\/problem\/([^/]*)\/?$/
const problemsetPattern = /problemset\/problem\/([^/]*)\/([^/]*)\/?$/
const groupPattern = /group\/([^/]+)\/contest\/([^/]*)\/problem\/([^/]*)\/?$/
let type // 'contest' | 'gym' | 'problemset' | 'group'
let submitURL
let problemId
let contestId
let participantId
// got from submit page
/* eslint-disable-next-line object-property-newline */
const extensionMap = {3: "program.dpr", 4: "program.pas", 6: "program.php", 7: "program.py", 9: "program.cs", 12: "program.hs", 13: "program.pl", 19: "program.ml",
20: "[^{}]*object\\s+(\\w+).*|$1.scala", 28: "program.d", 31: "a.py", 32: "program.go", 34: "program.js", 36: "[^{}]*public\\s+(final)?\\s*class\\s+(\\w+).*|$2.java",
40: "a.py", 41: "a.py", 43: "program.c", 48: "program.kt", 49: "program.rs", 50: "program.cpp", 51: "program.pas", 52: "program.cpp", 54: "program.cpp", 55: "program.js", 59: "program.cpp",
60: "[^{}]*public\\s+(final)?\\s*class\\s+(\\w+).*|$2.java", 61: "program.cpp", 65: "program.cs", 67: "program.rb",
70: "a.py", 73: "program.cpp", 74:"[^{}]*public\\s+(final)?\\s*class\\s+(\\w+).*|$2.java", 75:"program.rs", 77:"program.kt", 79:"program.cs",
80:"program.c", 83: "program.kt",87:"[^{}]*public\\s+(final)?\\s*class\\s+(\\w+).*|$2.java", 88: "program.kt", 89: "program.cpp",
90: "program.cpp", 91:"program.cpp",}
const regenerateInterval = 30 // minutes
const retryInterval = 1000 // msec
const retryTimes = 20
let doRegenerateOnSubmit = false
if (!checkRequirements()) return
if (!initInfo()) return
tryToInit(true)
function checkRequirements () {
if (!logged) {
console.error(`[${SCRIPT_NAME}] not logged in.`)
return false
}
if (!$) {
console.error(`[${SCRIPT_NAME}] not found jQuery.`)
return false
}
if (!ace) {
console.error(`[${SCRIPT_NAME}] not found ace.`)
return false
}
return true
}
function initInfo () {
if (pathname.match(/^\/problemset\//)) {
type = 'problemset'
submitURL = origin + '/problemset/submit'
const match = pathname.match(problemsetPattern)
contestId = match[1]
problemId = match[2]
} else if (pathname.match(/^\/group\//)) {
type = 'group'
const match = pathname.match(groupPattern)
const groupId = match[1]
contestId = match[2]
problemId = match[3]
submitURL = `${origin}/group/${groupId}/contest/${contestId}/submit`
} else {
pathname.match(pattern)
const match = pathname.match(pattern)
if (!match) return false
type = match[1]
submitURL = origin + '/' + type + '/' + match[2] + '/submit'
problemId = match[3]
}
return true
}
async function tryToInit (first) {
for (let i = 0; i < retryTimes; i++) {
try {
if (await initAppendForm(first, false)) return
} catch (e) {
removeForm()
console.error(`[${SCRIPT_NAME}] unexpected error has been occured.`)
throw e
}
removeForm()
await delay(retryInterval)
}
console.error(`[${SCRIPT_NAME}] tried some times but failed.`)
}
function delay (ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms)
})
}
async function initAppendForm (first = true, doNotRegenerateOnSubmit = false) {
let code = ''
let srcFile
const ajaxData = {}
const raw = await $.ajax(submitURL, {
method: 'get',
...ajaxData
})
const $newForm = $(raw).find('form.submit-form')
if (!$newForm.length) return false
if (!first) {
code = getCode() || ''
srcFile = $form.find('[name=sourceFile]')
removeForm()
}
$form = $newForm
$('.problem-statement').append($form)
editor = ace.edit('editor')
$form.attr('action', submitURL + $form.attr('action'))
$programType = $form.find('select[name=programTypeId]')
$toggleEditor = $form.find('#toggleEditorCheckbox')
$tabSize = $form.find('#tabSizeInput')
$selectProblem = $form.find('[name=submittedProblemIndex]')
// codeforces default settings
editor.setTheme('ace/theme/chrome')
editor.setShowPrintMargin(false)
editor.setOptions({
enableBasicAutocompletion: true
})
if (type === 'contest' || type === 'gym' || type === 'group') {
const existsProblemID = id => $selectProblem.find('option').filter((_, el) => $(el).val() === id).length
let exists = existsProblemID(problemId)
if (!exists && problemId === startId) {
for (const id of defaultProblemIds) {
if (existsProblemID(id)) {
problemId = id
exists = true
break
}
}
}
if (!exists) return false
$selectProblem.val(problemId)
// ダミーを作る
// そのままdisabledにするとformに含まれなくなるので
const $cloneSelectProblem = $($selectProblem.prop('outerHTML'))
$cloneSelectProblem.prop('disabled', true)
$cloneSelectProblem.removeAttr('name')
$cloneSelectProblem.val(problemId)
$cloneSelectProblem.attr('id', 'submitted_problem_index_fake_display')
$selectProblem.after($cloneSelectProblem)
$selectProblem.prop('hidden', true)
}
if (type === 'problemset') {
if (problemId === startId) {
$form.find('[name=submittedProblemCode]').val(contestId + 'A')
}
}
if (type === 'contest' || type === 'problemset') {
contestId = (raw.match(/contestId\s*=\s*(\d+)/) || {1: 0})[1]
participantId = (raw.match(/participantId\s*:\s*(\d+)/) || {1: 0})[1]
}
if (raw.match('updateProblemLockInfo')) updateProblemLockInfo()
if (raw.match('updateSubmitButtonState')) updateSubmitButtonState()
applyEditorVisibility()
setAceMode()
updateFilesAndLimits()
$toggleEditor.on('change', () => {
applyEditorVisibility()
const editorEnabled = !$toggleEditor.is(':checked')
$.post(
'/data/customtest',
{
communityCode: '',
action: 'setEditorEnabled',
editorEnabled: editorEnabled
},
function (response) {}
)
return false
})
$tabSize.on('change', () => {
const tabSize = $tabSize.val()
editor.setOptions({ tabSize })
$.post(
'/data/customtest',
{ communityCode: '', action: 'setTabSize', tabSize: tabSize },
function (response) {}
)
})
$programType.on('change', () => {
setAceMode()
})
editor.getSession().on('change', function () {
$('#sourceCodeTextarea').val(editor.getValue())
})
$('#sourceCodeTextarea').on('change', function () {
editor.setValue($(this).val(), 1)
})
$form.on('submit', preSubmit)
if (!first) {
if (code) setCode(code)
if (srcFile) $form.find('[name=sourceFile]').replaceWith(srcFile)
}
doRegenerateOnSubmit = false
if (!doNotRegenerateOnSubmit) {
delay(1000 * 60 * regenerateInterval).then(() => { doRegenerateOnSubmit = true })
}
return true
}
function setAceMode () {
var filePath = extensionMap[$programType.val()]
const mode = modelist.getModeForPath(filePath).mode
if (editor) editor.session.setMode(mode)
}
function applyEditorVisibility () {
if ($('#toggleEditorCheckbox').is(':checked')) {
$('#editor').hide()
$('#sourceCodeTextarea').show()
$('.tabSizeDiv').hide()
} else {
$('#editor').show()
editor.setValue(editor.getValue())
$('#sourceCodeTextarea').hide()
$('.tabSizeDiv').show()
}
}
function updateFilesAndLimits () {
var problemFiles = $('#submittedProblemFiles')
var problemLimits = $('#submittedProblemLimits')
var problemIndex = $('select[name=submittedProblemIndex]').val()
var option = $('select[name=submittedProblemIndex] option:selected')
var timeLimit = option.attr('data-time-limit')
var memoryLimit = option.attr('data-memory-limit')
var inputFile = option.attr('data-input-file')
var outputFile = option.attr('data-output-file')
if (problemIndex === '') {
problemFiles.text('')
problemLimits.text('')
} else {
var filesStyle = 'float: left; font-weight: bold'
if (inputFile === '') {
if (outputFile === '') {
filesStyle = 'float: left;'
problemFiles.text('standard input/output')
} else {
problemFiles.text('standard input / ' + outputFile)
}
} else {
if (outputFile === '') {
problemFiles.text(inputFile + ' / standard output')
} else {
problemFiles.text(inputFile + ' / ' + outputFile)
}
}
problemFiles.attr('style', filesStyle)
problemLimits.text(timeLimit + ' s, ' + memoryLimit + ' MB')
}
}
function removeForm () {
$('.submit-form').remove()
}
function succeedSubmit() {
if(openNewWindow) {
window.open(location.href)
}
}
function preSubmit () {
if (doRegenerateOnSubmit) {
initAppendForm(false, true).then(() => {
$form.trigger('submit')
})
return false
}
const button = $form.find('input.submit')
const img = $form.find('img.ajax-loading-gif')
if ($(this).hasAttr('data-submitting')) {
succeedSubmit()
return true
}
if (button.prop('disabled')) {
return false
}
var result = callback.call(this)
let alwaysDisable = false
if (result || alwaysDisable) {
img.show()
button.prop('disabled', true)
setTimeout(function () {
img.hide()
button.prop('disabled', false)
}, alwaysDisable ? 1000 : 10000)
}
if(result) succeedSubmit()
return result
}
function callback () {
var form = $(this)
var $ftaa = form.find("input[name='ftaa']")
var $bfaa = form.find("input[name='bfaa']")
if (window._ftaa && window._bfaa) {
$ftaa.val(window._ftaa)
$bfaa.val(window._bfaa)
}
if (form.attr('enctype') === 'multipart/form-data') {
var sourceFiles = form.find('.table-form input[name=sourceFile]')
if (
sourceFiles.length === 1 &&
sourceFiles[0].files &&
sourceFiles[0].files.length === 0
) {
form.removeAttr('enctype')
}
}
return true
}
function getCode () {
const $el = $('#sourceCodeTextarea')
return $el.val()
}
function setCode (code) {
const $el = $('#sourceCodeTextarea')
$el.val(code)
$el.trigger('change')
}
/* eslint-disable */
// from contest submit page (/contest/****/submit) {{{
function updateProblemLockInfo () {
var problemIndex = $('select[name=submittedProblemIndex]').val()
updateFilesAndLimits()
if (problemIndex != '') {
$.post('/data/problemLock',
{action: 'checkProblemLock', contestId, participantId, problemIndex: problemIndex},
function (response) {
if (response['problemLocked'] == 'true') {
Codeforces.setAjaxFormErrors('form table',
{error__submittedProblemIndex: 'Problem was locked for submission, it is impossible to resubmit it'})
$('.submit-form :submit').attr('disabled', 'disabled')
$('#submittedProblemFiles').text('')
$('#submittedProblemLimits').text('')
} else {
Codeforces.clearAjaxFormErrors('form table')
$('.submit-form :submit').removeAttr('disabled')
}
},
'json'
)
} else {
Codeforces.clearAjaxFormErrors('form table')
$('.submit-form :submit').attr('disabled', 'disabled')
}
}
function updateSubmitButtonState () {
var problemIndex = $('select[name=submittedProblemIndex]').val()
updateFilesAndLimits()
if (problemIndex == '') {
$('.submit-form :submit').attr('disabled', 'disabled')
} else {
$('.submit-form :submit').removeAttr('disabled')
}
}
// }}}
/* eslint-enable */
})()