aboutsummaryrefslogtreecommitdiff
path: root/sgdfi/_intranet.py
diff options
context:
space:
mode:
Diffstat (limited to 'sgdfi/_intranet.py')
-rwxr-xr-xsgdfi/_intranet.py106
1 files changed, 57 insertions, 49 deletions
diff --git a/sgdfi/_intranet.py b/sgdfi/_intranet.py
index 1b63762..0e54c36 100755
--- a/sgdfi/_intranet.py
+++ b/sgdfi/_intranet.py
@@ -24,59 +24,62 @@ from ._repr import IID as _IID
from ._util import InvalidCredentialsError as _InvalidCredentialsError, \
InvalidUserError as _InvalidUserError, \
InvalidPasswordError as _InvalidPasswordError, \
- UnauthorizedAccountError as _UnauthorizedAccountError
+ UnauthorizedAccountError as _UnauthorizedAccountError, \
+ RedirectError as _RedirectError, BadRequestError as _BadRequestError, \
+ NotFoundError as _NotFoundError, Pagination as _Pagination
__all__ = ["AnonymousIntranetSession", "IntranetSession"]
_monotime = lambda: _getclocktime(_MONOCLOCK)
-class RedirectError(Exception):
- """ The response is a redirection. """
-
- def __init__(self, location):
- super().__init__(f"Was redirected to {repr(location)}.")
- self.__location = location
-
- @property
- def location(self):
- """ The location to which we have been redirected. """
-
- return self.__location
-
-class BadRequestError(RedirectError):
- """ The response is a redirection to the bad request page. """
-
- def __init__(self, location):
- path = '/Specialisation/sgdf/erreurs/Erreur.aspx?' \
- + _urlencode({'aspxerrorpath': location})
- super().__init__(location)
+# ---
+# Définition des objets principaux.
+# ---
- self.__loc = location
+_mgrcls = None
- def __str__(self):
- return f"Erroneous request to {repr(self.__loc)}."
+def _import_manager():
+ """ Import the manager class.
+ Imported in a function because otherwise there would be a recursive
+ import. """
- @property
- def path(self):
- """ The error path. """
+ global _mgrcls
- return self.__loc
+ if _mgrcls is None:
+ from ._manager import Manager
+ _mgrcls = Manager
-# ---
-# Définition des objets principaux.
-# ---
+ return _mgrcls
class AnonymousIntranetSession:
""" Class for interacting with the intranet while not logged in. """
def __init__(self, manager, base = 'https://intranet.sgdf.fr',
debug = False):
- self.__mgr = manager
self.__base = base
self.__session = _Session()
self.__oldsess = None
self.__dbg = bool(debug or manager._debug)
+ self._ref(manager)
+
+ def _ref(self, manager):
+ """ Reference self into a manager. """
+
+ # If the manager doesn't exist, create it here.
+
+ _Manager = _import_manager()
+ if isinstance(manager, _Manager):
+ self.__mgr = manager
+ elif manager is not None:
+ raise ValueError("Expected a Manager.")
+ else:
+ self.__mgr = _Manager()
+
+ # Add self to the sessions manager.
+
+ self.__mgr.sessions.intranet._ref(self)
+
def __repr__(self):
return f"{self.__class__.__name__}()"
@@ -88,6 +91,12 @@ class AnonymousIntranetSession:
if self.__dbg:
_stderr.write(f"{self._log_prefix()} {' '.join(msg)}{_linesep}")
+ @property
+ def user(self):
+ """ Username set (placeholder). """
+
+ return None
+
# ---
# Base utilities.
# ---
@@ -141,15 +150,20 @@ class AnonymousIntranetSession:
try:
p = _urlparse(loc)
- assert p.path.casefold() in ('/erreurs/erreur.aspx',
- '/specialisation/sgdf/erreurs/erreur.aspx')
-
- path = _parse_qs(p.query)['aspxerrorpath'][0]
- raise BadRequestError(path) from None
+ path = p.path.casefold()
+
+ if path in ('/erreurs/erreur.aspx',
+ '/specialisation/sgdf/erreurs/erreur.aspx'):
+ path = _parse_qs(p.query)['aspxerrorpath'][0]
+ raise _BadRequestError() from None
+ elif path in ('/erreurs/404.aspx',
+ '/specialisation/sgdf/erreurs/404.aspx'):
+ path = _parse_qs(p.query)['aspxerrorpath'][0]
+ raise _NotFoundError() from None
except (AssertionError, KeyError, IndexError):
pass
- raise RedirectError(loc)
+ raise _RedirectError(loc)
# Check if we ought to ignore the thing.
@@ -280,13 +294,6 @@ class AnonymousIntranetSession:
else:
pkw['data'] = payload
- if self.__dbg:
- self.__log("Page POST arguments:")
- it = map(lambda x: (x, payload[x]), sorted(payload.keys()))
- for key, value in it:
- self.__log(f"{repr(key)}")
- self.__log(f"= {repr(value)}")
-
tm = _monotime()
r = self.__session.post(self.__base + path, headers = headers,
allow_redirects = False, **pkw)
@@ -483,7 +490,7 @@ class IntranetSession(AnonymousIntranetSession):
method = self.METHOD_FORM,
hint = 'sic',
new_session = True)
- except RedirectError:
+ except _RedirectError:
# We have successfully been redirected!
return
@@ -545,11 +552,12 @@ class IntranetSession(AnonymousIntranetSession):
# Récupération du document et décodage.
resp = self._get_ops_page(ent_type, ent_iid, page)
+ pgn = next(e for e in resp if isinstance(e, _Pagination))
- # Si `curpage < page`, alors c'est un bug connu de l'intranet
+ # Si `pgn.current < page`, alors c'est un bug connu de l'intranet
# où une page est déclarée mais inaccessible, on arrête donc là.
- if self._pgn.current < page:
+ if pgn.current < page:
break
# Ajout des activités à la liste totale.
@@ -558,7 +566,7 @@ class IntranetSession(AnonymousIntranetSession):
# Vérifions si on est arrivés au bout.
- if page == self._pgn.number and not self._pgn.more:
+ if page == pgn.number and not pgn.more:
break
return activities