aggregator.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import pickle
  2. import requests
  3. from backends.schoolloop import SchoolloopBackend
  4. from backends.haiku import HaikuBackend
  5. from backends.webassign import WebassignBackend
  6. from backends.dummy import DummyBackend
  7. backends = [DummyBackend, SchoolloopBackend, HaikuBackend, WebassignBackend]
  8. __STATE_CACHE = None
  9. def enable_logging():
  10. from http.client import HTTPConnection
  11. import logging
  12. HTTPConnection.debuglevel = 1
  13. logging.basicConfig()
  14. logging.getLogger().setLevel(logging.DEBUG)
  15. requests_log = logging.getLogger("requests.packages.urllib3")
  16. requests_log.setLevel(logging.DEBUG)
  17. requests_log.propagate = True
  18. def load_state(name):
  19. global __STATE_CACHE
  20. if __STATE_CACHE == None:
  21. try:
  22. with open("state.pkl", "rb") as f:
  23. __STATE_CACHE = pickle.load(f)
  24. except FileNotFoundError:
  25. __STATE_CACHE = {}
  26. try:
  27. return __STATE_CACHE[name]
  28. except KeyError:
  29. __STATE_CACHE[name] = {"authed": False}
  30. return __STATE_CACHE[name]
  31. def save_state():
  32. with open("state.pkl", "wb") as f:
  33. pickle.dump(__STATE_CACHE, f)
  34. def load_backend(name):
  35. sess = requests.Session()
  36. state = load_state(name)
  37. try:
  38. sess.cookies = state["cookies"]
  39. except KeyError:
  40. print("No cookies loaded")
  41. backend = { x.__name__ : x for x in backends } [name] ()
  42. backend.session = sess
  43. return backend
  44. def authenticate(backend, config):
  45. state = load_state(backend.__class__.__name__)
  46. if state["authed"]:
  47. backend.fast_login(config)
  48. return True
  49. if backend.login(config):
  50. backend.authenticated = True
  51. state["authed"] = True
  52. state["cookies"] = backend.session.cookies
  53. save_state()
  54. return True
  55. else:
  56. print("Bad credentials")
  57. return False