Skip to content

Instantly share code, notes, and snippets.

@soharu
Forked from falsetru/submit.py
Last active December 13, 2015 19:59
Show Gist options
  • Save soharu/4966974 to your computer and use it in GitHub Desktop.
Save soharu/4966974 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import urllib, urllib2
import cookielib
import os
from contextlib import closing
import re
import getpass
import webbrowser
import sys
class AlgoSpot(object):
def __init__(self):
cookiefile_path = os.path.join(os.path.expanduser('~'), '.kaka')
self.cj = cj = cookielib.LWPCookieJar(cookiefile_path)
try:
cj.load()
except IOError:
pass
self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
def login(self, username, password):
html = self._request('http://algospot.com/accounts/login/')
csrf_token = self._get_csrf_token(html)
data = urllib.urlencode({
'username': username,
'password': password,
'csrfmiddlewaretoken': csrf_token,
})
html = self._request('http://algospot.com/accounts/login/', data)
ok = self._is_loggedin(html)
if ok:
self.cj.save()
return ok
def is_loggedin(self):
html = self._request('http://algospot.com')
return self._is_loggedin(html)
def ensure_login(self):
if self.is_loggedin():
return
while True:
username = raw_input('Username: ')
password = getpass.getpass()
if self.login(username, password):
break
print 'Login failure.'
def submit(self, problem, lang, content):
url = 'http://algospot.com/judge/problem/submit/{}'.format(problem)
html = self._request(url)
csrf_token = self._get_csrf_token(html)
data = urllib.urlencode({
'csrfmiddlewaretoken': csrf_token,
'language': lang,
'source': content,
})
self._request(url, data)
def open_recent_submission(self):
webbrowser.open('http://algospot.com/judge/submission/recent/')
def _is_loggedin(self, html):
return 'href="/accounts/logout/"' in html
def _get_csrf_token(self, html):
return re.search("name='csrfmiddlewaretoken' value='(\w+)'", html).group(1)
def _request(self, url, data=None):
with closing(self.opener.open(url, data)) as u:
return u.read()
ext_to_lang = {
'.java' : 'java',
'.scala': 'scala',
'.hs' : 'hs',
'.py' : 'py',
'.js' : 'js',
'.rb' : 'rb',
'.c' : 'cpp',
'.cpp' : 'cpp',
'.cxx' : 'cpp',
'.cc' : 'cpp',
}
def guess_language(filename):
base, ext = os.path.splitext(filename)
ext = ext.lower()
return ext_to_lang.get(ext)
assert guess_language('/path/to/boggle.py') == 'py'
def main(problem, filepath):
lang = guess_language(filepath)
if not lang:
print 'Language guess fail.'
return
try:
with open(filepath) as f:
content = f.read()
except IOError:
print "Can't open/read file."
return
site = AlgoSpot()
site.ensure_login()
site.submit(problem.upper(), lang, content)
site.open_recent_submission()
if __name__ == '__main__':
if len(sys.argv) != 3:
print 'Usage: {} <problem> <file>'.format(sys.argv[0])
sys.exit(1)
main(sys.argv[1], sys.argv[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment