Start refinement of CREST utilities:

* Add preference page which gives option of implicit grant or user client details
* Improve CREST service
* Changes in pycrest which make things a little easier
This commit is contained in:
blitzmann
2015-10-21 23:10:06 -04:00
parent 69a4e42ab0
commit e0f99ee133
10 changed files with 176 additions and 95 deletions

View File

@@ -1,9 +1,23 @@
import eos.db
from eos.types import Crest as CrestUser
import config
import pycrest
import copy
import service
from service.server import *
import uuid
from wx.lib.pubsub import setupkwargs
from wx.lib.pubsub import pub
# TODO:
# With implicit grant, make sure we know when it expires and delete/inactive char
class Crest():
# @todo: move this to settings
clientCallback = 'http://localhost:6461'
clientTest = True
_instance = None
@classmethod
def getInstance(cls):
@@ -13,22 +27,47 @@ class Crest():
return cls._instance
def __init__(self):
pass
self.settings = service.settings.CRESTSettings.getInstance()
self.httpd = StoppableHTTPServer(('', 6461), AuthHandler)
self.scopes = ['characterFittingsRead', 'characterFittingsWrite']
self.state = None
# Base EVE connection that is copied to all characters
self.eve = pycrest.EVE(
client_id=self.settings.get('clientID'),
api_key=self.settings.get('clientSecret') if self.settings.get('mode') == 1 else None,
redirect_uri=self.clientCallback,
testing=self.clientTest)
self.implicitCharacter = None
pub.subscribe(self.handleLogin, 'sso_login')
def getCrestCharacters(self):
return eos.db.getCrestCharacters()
chars = eos.db.getCrestCharacters()
for char in chars:
if not hasattr(char, "eve"):
char.eve = copy.copy(self.eve)
# Give EVE instance refresh info. This allows us to set it
# without actually making the request to authorize at this time.
char.eve.temptoken_authorize(refresh_token=char.refresh_token)
return chars
def getCrestCharacter(self, charID):
return eos.db.getCrestCharacter(charID)
'''
Get character, and modify to include the eve connection
'''
char = eos.db.getCrestCharacter(charID)
if not hasattr(char, "eve"):
char.eve = copy.copy(self.eve)
char.eve.temptoken_authorize(refresh_token=char.refresh_token)
return char
def getFittings(self, charID):
char = self.getCrestCharacter(charID)
char.auth()
return char.eve.get('https://api-sisi.testeveonline.com/characters/%d/fittings/'%char.ID)
def postFitting(self, charID, json):
char = self.getCrestCharacter(charID)
char.auth()
res = char.eve._session.post('https://api-sisi.testeveonline.com/characters/%d/fittings/'%char.ID, data=json)
return res
@@ -38,3 +77,37 @@ class Crest():
char = CrestUser(info['CharacterName'], info['CharacterID'], connection.refresh_token)
eos.db.save(char)
def startServer(self):
thread.start_new_thread(self.httpd.serve, ())
self.state = str(uuid.uuid4())
return self.eve.auth_uri(scopes=self.scopes, state=self.state)
def handleLogin(self, message):
if not message:
return
if message['state'][0] != self.state:
return
print "handling login by making characters and stuff"
print message
if 'access_token' in message: # implicit
eve = copy.copy(self.eve)
eve.temptoken_authorize(
access_token=message['access_token'][0],
expires_in=int(message['expires_in'][0])
)
eve()
info = eve.whoami()
self.implicitCharacter = CrestUser(info['CharacterID'], info['CharacterName'])
self.implicitCharacter.eve = eve
wx.CallAfter(pub.sendMessage, 'login_success', type=0)
elif 'code' in message:
print "handle authentication code"
#wx.CallAfter(pub.sendMessage, 'login_success', type=1)

30
service/html.py Normal file
View File

@@ -0,0 +1,30 @@
# HTML is stored here as frankly I'm not sure how loading a file would work with
# our current zipfile packaging (and I'm too lazy to find out)
HTML = '''
<!DOCTYPE html>
<html>
<body>
Done. Please close this window.
(will put more interesting messages here later)
<script type="text/javascript">
function extractFromHash(name, hash) {
var match = hash.match(new RegExp(name + "=([^&]+)"));
return !!match && match[1];
}
var hash = window.location.hash;
var token = extractFromHash("access_token", hash);
if (token){
var redirect = window.location.origin.concat('/?', window.location.hash.substr(1));
window.location = redirect;
}
else {
console.log("do nothing");
}
</script>
</body>
</html>
'''

View File

@@ -7,18 +7,20 @@ import wx
from wx.lib.pubsub import setupkwargs
from wx.lib.pubsub import pub
from html import HTML
# https://github.com/fuzzysteve/CREST-Market-Downloader/
class AuthHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
print "GET"
if self.path == "/favicon.ico":
return
parsed_path = urlparse.urlparse(self.path)
parts=urlparse.parse_qs(parsed_path.query)
parts = urlparse.parse_qs(parsed_path.query)
self.send_response(200)
self.end_headers()
self.wfile.write('Login successful. you can close this window now')
wx.CallAfter(pub.sendMessage, 'sso_login', message=str(parts['code'][0]))
self.wfile.write(HTML)
wx.CallAfter(pub.sendMessage, 'sso_login', message=parts)
def log_message(self, format, *args):
return
@@ -51,7 +53,7 @@ class StoppableHTTPServer(BaseHTTPServer.HTTPServer):
# this can happen if stopping server in middle of request?
pass
if __name__=="__main__":
if __name__ == "__main__":
httpd = StoppableHTTPServer(('', 6461), AuthHandler)
thread.start_new_thread(httpd.serve, ())
raw_input("Press <RETURN> to stop server\n")

View File

@@ -263,4 +263,30 @@ class UpdateSettings():
def set(self, type, value):
self.serviceUpdateSettings[type] = value
class CRESTSettings():
_instance = None
@classmethod
def getInstance(cls):
if cls._instance is None:
cls._instance = CRESTSettings()
return cls._instance
def __init__(self):
# mode
# 0 - Implicit authentication
# 1 - User-supplied client details
serviceCRESTDefaultSettings = {"mode": 0, "clientID": "", "clientSecret": ""}
self.serviceCRESTSettings = SettingsProvider.getInstance().getSettings("pyfaServiceCRESTSettings", serviceCRESTDefaultSettings)
def get(self, type):
return self.serviceCRESTSettings[type]
def set(self, type, value):
self.serviceCRESTSettings[type] = value
# @todo: migrate fit settings (from fit service) here?