Browse Source

WIP on log: 8300c18 Merge branch 'dev' into 'master'

log^2
Laurent Kislaire 9 months ago
parent
commit
af6983dde9
2 changed files with 28 additions and 1 deletions
  1. +24
    -1
      pyfbx/client.py
  2. +4
    -0
      pyfbx/mdns.py

+ 24
- 1
pyfbx/client.py View File

@@ -3,9 +3,11 @@
Fbx Client
"""
import os
import logging
import re
import hmac
import hashlib
import logging
import time
import requests
from . import api
@@ -36,10 +38,10 @@ class FbxTransport():
self._session = session or requests.session()
self._session.verify = os.path.join(os.path.dirname(__file__), 'fb.pem')
self.set_url(url)
self.log = logging.getLogger("pyfbx.trans")

def set_url(self, url):
if url is None:
# Detect using MDNS or fallback
self._url = mdns.FbxMDNS().search() or self.get_local_base()
else:
if re.search("https?://", url) is None:
@@ -55,16 +57,20 @@ class FbxTransport():
def api_exec(self, http_method, endpoint, post_data=None, **kwargs):
req_response = self._session.request(
http_method, self._url + "/" + endpoint.format(**kwargs), json=post_data)
self.log.debug(">> Sent %s %s/%s Post: %s", http_method, self._url,
endpoint.format(**kwargs), post_data)
req_response.raise_for_status()
response = req_response.json()
if response['success']:
if 'result' in response:
self.log.debug(f"<< Got {response['result']}")
return response['result']
else:
raise FbxErrorResponse(response['error_code'], response['msg'])

def get_local_base(self, url=api._DISC_HTTP_URL):
response = self._session.get(f"{url}/api_version").json()
self.log.debug(f"<< Detected api {response['api_version']}")
return "%s%sv%s" % (url, response['api_base_url'], response['api_version'][0])


@@ -75,6 +81,7 @@ class Fbx():

def __init__(self, url=None, session=None):
self._trn = FbxTransport(url, session=session)
self.log = logging.getLogger("pyfbx.fbx")

# Create on the fly attributes to classes
_globals = globals()
@@ -92,10 +99,12 @@ class Fbx():
res = self._trn.api_exec("POST", "login/authorize/", data)
trackid, self.token = res["track_id"], res["app_token"]
s = "pending"
self.log.warning("Press Ok on the freebox to register application")
while s == "pending":
s = self._trn.api_exec("GET", f"login/authorize/{trackid}")["status"]
if s == "pending":
time.sleep(1)
self.log.debug(f"Registration returned: {s}")
return s == "granted" and self.token

def mksession(self, app_id=None, token=None):
@@ -115,6 +124,7 @@ class Fbx():
session_token = resp["session_token"]
self.app_id = app_id
self._trn.set_session_header(session_token)
self.log.debug(f"Got session token, permissions are {resp['permissions']}")
return resp["permissions"]


@@ -127,7 +137,20 @@ class FbxErrorResponse(Exception):
return f'{self.msg} [{self.error_code}]'


def logger():
log = logging.getLogger("pyfbx")
log.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#stream_handler = logging.StreamHandler() only for main() and set by the user
#stream_handler.setFormatter(formatter) not in a library!
#log.addHandler(stream_handler)
return log


log = logger()

# All FB subsystems are classes deriving from FbxClass
for _classname in api.SYSTEMS:
log.debug(f"Adding class {_classname} to locals")
locals()[_classname] = type(_classname, (FbxClass, ), {})
__all__.append(_classname)

+ 4
- 0
pyfbx/mdns.py View File

@@ -3,6 +3,7 @@ Search Freebox through MDNS
"""

import time
import logging
from zeroconf import ServiceBrowser, Zeroconf
from . import api

@@ -29,12 +30,15 @@ class FbxMDNS():

def __init__(self, timeout=1):
self.timeout = timeout
self.log = logging.getLogger("pyfbx.mdns")

def search(self, svc_name=api._DISC_MDNS_NAME, timeout=1):
self.log.debug("Searching with MDNS")
zeroconf = Zeroconf()
self._listener = FbxMDNS.MyListener()
browser = ServiceBrowser(zeroconf, svc_name, self._listener)
time.sleep(timeout)
self.log.debug("Closing MDNS")
browser.cancel() # slow
zeroconf.close() # slow
if self.svc_info:

Loading…
Cancel
Save