import http.server import urllib.parse import socket import threading from logbook import Logger import socketserver pyfalog = Logger(__name__) # noinspection PyPep8 HTML = ''' pyfa Local Server

pyfa

{0}
''' # https://github.com/fuzzysteve/CREST-Market-Downloader/ class AuthHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): if self.path == "/favicon.ico": return parsed_path = urllib.parse.urlparse(self.path) parts = urllib.parse.parse_qs(parsed_path.query) msg = "" step2 = 'step' in parts try: if step2: self.server.callback(parts) pyfalog.info("Successfully logged into EVE.") msg = "If you see this message then it means you should be logged into EVE SSO. You may close this window and return to the application." else: # For implicit mode, we have to serve up the page which will take the hash and redirect using a querystring pyfalog.info("Processing response from EVE Online.") msg = "Processing response from EVE Online" except Exception as ex: pyfalog.error("Error logging into EVE") pyfalog.error(ex) msg = "

Error

\n

{}

".format(ex.message) finally: self.send_response(200) self.end_headers() self.wfile.write(str.encode(HTML.format(msg))) if step2: # Only stop once if we've received something in the querystring self.server.stop() def log_message(self, format, *args): return # http://code.activestate.com/recipes/425210-simple-stoppable-server-using-socket-timeout/ class StoppableHTTPServer(socketserver.TCPServer): def server_bind(self): # Can't use HTTPServer due to reliance on socket.getfqdn() which seems to be bugged. # See https://github.com/pyfa-org/Pyfa/issues/1560#issuecomment-390095101 socketserver.TCPServer.server_bind(self) host, port = self.server_address[:2] self.server_name = host self.server_port = port # self.settings = CRESTSettings.getInstance() # Allow listening for x seconds sec = 120 pyfalog.debug("Running server for {0} seconds", sec) self.socket.settimeout(1) self.max_tries = sec / self.socket.gettimeout() self.tries = 0 self.run = True def get_request(self): while self.run: try: sock, addr = self.socket.accept() sock.settimeout(None) return sock, addr except socket.timeout: pyfalog.warning("Server timed out waiting for connection") pass def stop(self): pyfalog.warning("Setting pyfa server to stop.") self.run = False def handle_timeout(self): pyfalog.debug("Number of tries: {0}", self.tries) self.tries += 1 if self.tries == self.max_tries: pyfalog.debug("Server timed out waiting for connection") self.stop() def serve(self, callback=None): self.callback = callback while self.run: try: self.handle_request() except TypeError: pyfalog.debug("Caught exception in serve") pass self.server_close() if __name__ == "__main__": httpd = StoppableHTTPServer(('', 6461), AuthHandler) t = threading.Thread(target=httpd.serve) input("Press to stop server\n") httpd.stop()