aboutsummaryrefslogtreecommitdiff
path: root/sgdfi/_intranet.py
blob: 89108688a518d5c0745dc6f285ebe0ed1971fa43 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
#!/usr/bin/env python3
#******************************************************************************
# Copyright (C) 2018 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
# This file is part of the sgdfi project, which is MIT-licensed.
#******************************************************************************
""" Main object to interact with SGDF's intranet. """

from os import linesep as _linesep
from sys import stderr as _stderr
from time import strftime as _strftime, localtime as _localtime, \
	clock_gettime as _getclocktime, CLOCK_MONOTONIC as _MONOCLOCK
from datetime import date as _date, datetime as _datetime
from io import StringIO as _StringIO
from itertools import count as _count
from base64 import b64encode as _b64encode
from urllib.parse import urlencode as _urlencode, urlparse as _urlparse, \
	parse_qs as _parse_qs
from json import dumps as _jsondumps

from requests import Session as _Session
from bs4 import BeautifulSoup as _BeautifulSoup

from ._repr import IID as _IID
from ._util import InvalidCredentialsError as _InvalidCredentialsError, \
	InvalidUserError as _InvalidUserError, \
	InvalidPasswordError as _InvalidPasswordError, \
	UnauthorizedAccountError as _UnauthorizedAccountError

__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)

		self.__loc = location

	def __str__(self):
		return f"Erroneous request to {repr(self.__loc)}."

	@property
	def path(self):
		""" The error path. """

		return self.__loc

# ---
# Définition des objets principaux.
# ---

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)

	def __repr__(self):
		return f"{self.__class__.__name__}()"

	def _log_prefix(self):
		return f"[{_strftime('%Y-%m-%d %H:%M:%S', _localtime())} " \
			f"I:anon]"

	def __log(self, *msg):
		if self.__dbg:
			_stderr.write(f"{self._log_prefix()} {' '.join(msg)}{_linesep}")

	# ---
	# Base utilities.
	# ---

	METHOD_BASIC = 1
	METHOD_JSONPOST  = 2
	METHOD_FORM  = 3
	METHOD_AJAX  = 4

	def _restore_session(self):
		""" Restore the previous session. """

		if self.__oldsession is not None:
			self.__session = self.__oldsession
			self.__oldsession = None

	def get_page(self, path, args = {}, method = METHOD_BASIC, hint = None,
		new_session = False):
		""" Gather a page:
			- as a normal page using GET (`METHOD_BASIC`).
			- as a POST page (`METHOD_POST`).
			- as a form using POST and predefined fields (`METHOD_FORM`).
			- as a page fragment using POST with AJAX (`METHOD_AJAX`).

			The hint is for decoding the content, according to the
			context. The `session` argument is `None` if we shall use the
			object's requests Session object, or the requests Session object
			to use. """

		if new_session:
			self.__oldsession = self.__session
			self.__session = _Session()

		if not method in (self.METHOD_BASIC, self.METHOD_JSONPOST,
			self.METHOD_FORM, self.METHOD_AJAX):
			raise ValueError("invalid method")

		mname = ("basic", "jsonpost", "form", "ajax")[method - 1]
		self.__log(f"Get a page using {mname} method")

		def ret(r):
			""" Treat the response to know what to return """

			status_code = r.status_code

			# Check if it is a redirection.

			if status_code in (301, 302):
				loc = r.headers['Location']
				self.__log(f"({r.status_code}) {loc}")

				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
				except (AssertionError, KeyError, IndexError):
					pass

				raise RedirectError(loc)

			# Check if we ought to ignore the thing.

			if hint == 'ignore':
				self.__log(f"Ignore normal response.")
				return None

			# Décodage en fonction du code de retour.

			ct = r.headers['Content-Type'].split(';')[0].strip()

			htext = f" with hint {repr(hint)}" if hint != None else ""
			if   ct == 'text/plain':
				self.__log(f"Decoding AJAX response{htext}.")

				return self.__mgr.feed(r.text, 'application/x-microsoft-ajax',
					hint)
			elif ct == 'text/csv':
				self.__log(f"Decoding CSV content{htext}.")

				return self.__mgr.feed(r.text, 'text/csv', hint)
			elif ct == 'text/html':
				self.__log(f"Decoding HTML content{htext}.")

				return self.__mgr.feed(r.text, 'text/html', hint)
			elif ct == 'text/xml':
				self.__log(f"Decoding XML content{htext}.")

				return self.__mgr.feed(r.text, 'text/xml', hint)
			elif ct == 'application/json':
				self.__log(f"Decoding JSON content{htext}.")

				return self.__mgr.feed(r.text, 'application/json', hint)

			self.__log(f"Unmanaged Content-Type {repr(ct)}")
			self.__log(f"Falling back on HTML decoding.")

			return self.__mgr.feed(r.text, 'text/html', hint)

		# Définition des headers.

		headers = {
			'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:58.0) ' \
				'Gecko/20100101 Firefox/58.0',
			'Cache-Control': 'no-cache',
			'Upgrade-Insecure-Requests': '1',
			'Referer': self.__base + path,
			'DNT': '1'
		}

		# ---
		# Récupération de la version GET de la page pour les champs
		# prédéfinis.
		# ---

		df = {}

		if method != self.METHOD_JSONPOST:
			# Récupération à proprement parler.

			tm = _monotime()
			r = self.__session.get(self.__base + path, headers = headers)
			self.__log("Page GET request delay: " \
				f"{round(_monotime() - tm, 4)}s")

			# Si la méthode est un GET basique, on peut s'arrêter là.

			if method == self.METHOD_BASIC:
				return ret(r)

			# Décodage du contenu récupéré et récupération des valeurs par
			# défaut de l'ensemble des champs, dont `__EVENTVALIDATION`
			# qui sert de cookie CSRF.

			it = _BeautifulSoup(r.text, 'lxml').find_all('input',
				recursive = True)
			for elt in it:
				try:
					name = elt['name']
				except:
					continue
				try:
					value = elt['value']
				except:
					value = ''

				df[name] = value

		# ---
		# Préparation des paramètres POST (payload).
		# ---

		# Tout d'abord, ajoutons les données par défaut, à savoir ce
		# qu'il y a dans la page.

		payload = {}
		payload.update(df)

		# Ensuite, ajoutons les arguments de l'utilisateur.

		def recursive_args(elements, prefix = ''):
			for key in elements:
				value = elements[key]
				if isinstance(value, dict):
					recursive_args(value, prefix + key + '$')
					continue

				payload[prefix + key] = value

		recursive_args(args)

		# ---
		# Préparation des cookies et exécution de la requête.
		# ---

		# Ajustement des headers pour de l'AJAX.

		if method == self.METHOD_AJAX:
			headers.update({
				'X-MicrosoftAjax': 'Delta=true',
				'X-Requested-With': 'XMLHttpRequest'})

		# Exécution de la requête.

		pkw = {}
		if method == self.METHOD_JSONPOST:
			pkw['json'] = payload
		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)
		self.__log(f"Page POST request delay: {round(_monotime() - tm, 4)}s")

		return ret(r)

	# ---
	# Session-related.
	# ---

	def request_password(self, code):
		""" Request a password for an account. """

		if type(code) != str:
			raise ValueError("Code must be a string.")

		# Make the request.

		path = '/securite/OubliMotDePasse.aspx'
		result = self.get_page(path, args = {
			'ctl00': {
				'MainContent': {
					'_tbIdentifiant': code}}},
			method = self.METHOD_FORM,
			hint = 'sic')

		# Check if there is an error.

		espan = result.find(id = 'ctl00__erreur__lblErreur')
		if espan is not None:
			error = espan.text.strip()
			if   error.startswith("Le compte associé à l'identifiant '") \
			 and error.endswith("' ne donne pas le droit d'utiliser cette " \
				 "application"):
				raise _UnauthorizedAccountError(code)

			raise _InvalidUserError(user = code)

		# We have succeeded!

	def request_code(self, common_name, first_name, birth_date):
		""" Request an email for an account without knowing the adherent
			code. """

		if type(common_name) != str:
			raise ValueError("Common name must be a string.")
		if type(first_name) != str:
			raise ValueError("First name must be a string.")
		if isinstance(birth_date, _date) \
		or isinstance(birth_date, _datetime):
			d = _date(birth_date.year, birth_date.month, birth_date.day)
		else:
			raise ValueError("Birth date must be a date.")

		# Make the request.
		# This is just pro level reverse engineering.
		# Please do not read this if you do not want to lose your sanity.
		# Please read this if you don't care.
		# Please modify it if you ought to break it.

		path = '/securite/OubliMotDePasse.aspx?num=1'
		dfr = d.strftime("%d/%m/%Y")
		dus = d.strftime("%Y-%m-%d")
		cus = _datetime.now().strftime("%Y-%m-01")
		eo_obj_states = _b64encode(b'\x01!\x01BA' \
			b'ctl00_MainContent__eocDateNaissance__picker:' + \
			cus.encode('ASCII') + b'|' + dus.encode('ASCII')).decode('ASCII')

		result = self.get_page(path, args = {
			'__eo_obj_states': eo_obj_states,
			'__eo_sc': '/wEdAAcSMJ8leNaA/vPZOzulfZuPEvHhCaPIDCCxX3XQg2l5e+BQ' \
				'RR32SiwZGot7RnRIo09TjFeQwbB4Eo7GP2ptXnbAnMyq24KvMxlGsP7uRmE' \
				'TdaVE1CbS15+9uPB4lF6xMlznDHPtMay3TLJDvEyyRG6LaDe0jqt5G6yCDS' \
				'sQZSEP8hLNmoo=',
			'_eo_js_modules': '',
			'_eo_obj_inst': '',

			'_eo_ctl00_MainContent__eocDateNaissance__picker_picker': dfr,
			'_eo_ctl00_MainContent__eocDateNaissance__picker_h': dus,
			'ctl00': {
				'MainContent': {
					'_tbNom': common_name,
					'_tbPrenom': first_name}}},
			method = self.METHOD_FORM,
			hint = 'sic')

		# Print the result.

		node = result.find(id = 'ctl00__upMainContent')
		print(node)

		espan = result.find(id = 'ctl00__erreur__lblErreur')
		if espan is not None:
			# There has been an error!

			etx = espan.text.strip()

			noinfo = "Nous ne pouvons pas vous donner votre numéro " \
				"d’adhérent pour la raison suivante : Pas de résultat avec " \
				"les informations fournies"

			if etx == noinfo:
				raise ValueError("no result")

class IntranetSession(AnonymousIntranetSession):
	""" Class for interacting with the intranet while logged in. """

	def __init__(self, manager, user = None, pw = None, *args, **kwargs):
		super().__init__(manager, *args, **kwargs)

		self.__user    = user
		self.__pw      = pw

		# Login process.

		self.login()
		# XXX: get information about self.

	def __repr__(self):
		return f"{self.__class__.__name__}(user = {repr(self.__user)})"

	# ---
	# Properties.
	# ---

	@property
	def user(self):
		""" Username set. """

		return self.__user

	@property
	def pw(self):
		""" Password set. """

		return self.__pw

	@pw.setter
	def pw(self, value):
		# Use another password instead.

		if type(value) != str:
			raise ValueError("expected a string")

		self.login(pw = value, new_session = True)
		self.__pw = value

	@property
	def password(self):
		""" Alias for `pw`. """

		return self.pw

	@password.setter
	def password(self, value):
		self.pw = value

	def _log_prefix(self):
		return f"[{_strftime('%Y-%m-%d %H:%M:%S', _localtime())} " \
			f"I:{self.__user}]"

	# ---
	# Data generation.
	# ---

	def get_functions(self):
		""" Get the functions. """

		path = '/Specialisation/Sgdf' \
			'/WebServices/AutoComplete.asmx/GetFonctions'
		args = {'id_token': 'undefined', 'q': ''}

		return self.get_page(path, method = self.METHOD_JSONPOST, args = args,
			hint = 'intranet_functions')

	# ---
	# Session-related.
	# ---

	def login(self, pw = None, session = None):
		""" Gather session data (cookies) within the internal session. """

		if pw is None:
			pw = self.__pw

		e = None

		try:
			result = self.get_page('/Default.aspx', {
				'ctl00': {
					'MainContent': {
						'login': self.__user,
						'password': pw}}},
				method = self.METHOD_FORM,
				hint = 'sic',
				new_session = True)
		except RedirectError:
			# We have successfully been redirected!

			return

		# The credentials were invalid.

		self._restore_session()

		espan = result.find(id = 'ctl00__erreur__lblErreur')
		if espan is None:
			raise _InvalidCredentialsError(user = self.__user, pw = pw)

		error = espan.text.strip()
		if   error == "Identifiant invalide":
			raise _InvalidUserError(self.__user)
		elif error == "Mot de passe invalide":
			raise _InvalidPasswordError(self.__user, pw)
		elif error.startswith("Le compte associé à l'identifiant '") \
		 and error.endswith("' ne donne pas le droit d'utiliser cette " \
		     "application"):
			raise _UnauthorizedAccountError(self.__user)
		else:
			raise _InvalidCredentialsError(user = self.__user, pw = pw)

	# ---
	# Obtain objects.
	# ---

	def _get_ops_page(self, ent_type, ent_iid, page):
		""" Get an operation page. """

		path = '/Specialisation/Sgdf/popups/JournalEvenements.aspx' \
			f'?typeEntite={ent_type}&idEntite={ent_iid.urlsafe()}'

		return self.get_page(path, {
			'__EVENTARGUMENT': f"Page${page}",
			'__EVENTTARGET': 'ctl00$Popup$_evenements$_gvEvenements'},
			method = self.METHOD_FORM,
			hint = 'operations')

	def get_ops(self, ent_type, ent_id):
		""" Get the operations corresponding to something. """

		try:
			ent_type = int(ent_type)
			assert 1 <= ent_type <= 25
			ent_type = str(ent_type)
		except:
			raise ValueError("Entry type should be an integer between.")
		ent_iid = _IID(ent_id)

		# ---
		# Récupération des évènements.
		# ---

		activities = []

		for page in _count(1):
			# Récupération du document et décodage.

			resp = self._get_ops_page(ent_type, ent_iid, page)

			# Si `curpage < 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:
				break

			# Ajout des activités à la liste totale.

			activities.extend(resp)

			# Vérifions si on est arrivés au bout.

			if page == self._pgn.number and not self._pgn.more:
				break

		return activities

	def get_place(self, pl_id):
		""" Get a place's data. """

		iid = _IID(pl_id)
		path = '/Specialisation/Sgdf/Commun/ResumeLieuActivite.aspx' \
			f'?id={iid.urlsafe()}'

		# Récupération et décodage de la page.
		# XXX: hack pour l'iid. Le récupérer directement sur la page ?

		elts = self.get_page(path, hint = 'place')
		pl.iid = iid
		return pl

	def get_structure(self, st_id):
		""" Get a structure's data. """

		iid = _IID(st_id)
		path = '/Specialisation/Sgdf/structures/ResumeStructure.aspx' \
			f'?id={iid.urlsafe()}'
		stname = 'ctl00_ctl00_MainContent_TabsContent_' \
			'TabContainerResumeStructure_ClientState'
		state = {
			'ActiveTabIndex': 1,
			'TabState': [True] * 10}
		args = {
			stname: _jsondumps(state),
			'ctl00': {
				'ctl00': {
					'_ddDelegations': '0',
					'_hidReferenceStatistiqueUtilisation': '-1',
					'_tbRechAdherent': '',
					'_tbRechStructure': ''}}}

		# Récupération de l'onglet "Résumé".

		state['ActiveTabIndex'] = 1
		args[stname] = _jsondumps(state)
		st = self.get_page(path, args, method = self.METHOD_FORM,
			hint = "structure_summary")

		# Récupération de l'onglet "Hiérarchie".

		state['ActiveTabIndex'] = 0
		args[stname] = _jsondumps(state)
		st_updates = self.get_page(path, args, method = self.METHOD_FORM,
			hint = "structure_hierarchy")

		# FIXME: feed with iid
		st.iid = iid

		return st

	def get_events(self, year = 2018, month = 6):
		""" Get events in the calendar. """

		# Check the arguments.

		if not isinstance(year, int):
			raise ValueError("expected an integer for the year")
		if not isinstance(month, int):
			raise ValueError("expected an integer for the month")
		year = int(year)
		month = int(month)
		if year < 2004:
			raise ValueError("expected a year >= 2004")
		if not month in range(1, 13):
			raise ValueError("month should be in 1-12")

		# Get the page corresponding to the selected month.
		#
		# FIXME: Remove the following :
		# - `ctl00$MainContent$_navigateur$_ddStructure`: 1061745 (XXX: valeur
		#   principale sélectionnée, probablement ID interne)
		# - `ctl00$MainContent$_navigateur$_hidCodeStructure`: 119101231 (code
		#   public de la structure), toujours le code de structure lié à
		#   la délégation courante et non celui de la structure.

		path = '/Specialisation/Sgdf/animation/ConsulterCalendrier.aspx'
		return self.get_page(path, {
			'__EVENTTARGET': 'ctl00$MainContent$_ddlMois',
			'ctl00': {
				'ScriptManager1': 'ctl00$_upMainContent|' \
					'ctl00$MainContent$_ddlMois',
				'MainContent': {
					'_ddlAnnees': str(year),
					'_ddlMois': str(month),
					'_navigateur': {
						'_ddStructure': '1061745',
						'_hidCodeStructure': '119101231'}}}},
			method = self.METHOD_AJAX,
			hint = 'calendar_month')

# End of file.