aboutsummaryrefslogtreecommitdiff
path: root/sgdfi/_decode.py
blob: b6b359f86a2842a4ed5e12be178e560ffa6d238e (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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
#!/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 decode files and dumps from SGDF's intranet. """

from itertools import count as _count
from datetime import datetime as _datetime
from re import finditer as _rfindter, sub as _rreplace, split as _rsplit
from io import IOBase as _IOBase, StringIO as _StringIO, BytesIO as _BytesIO, \
	TextIOWrapper as _TextIOWrapper
from base64 import b64decode as _b64decode
from urllib.parse import urlparse as _urlparse, parse_qs as _parse_qs, \
	unquote as _unquote
from html import unescape as _htmlunescape
from json import load as _jsonload, loads as _jsonloads
from csv import reader as _csvreader

from bs4 import BeautifulSoup as _BeautifulSoup
from pandas import read_excel as _read_excel

from ._repr import Structure as _Structure, Adherent as _Adherent, \
	Place as _Place, RallyRegistration as _RallyRegistration, Camp as _Camp, \
	Operation as _Operation, FunctionRawData as _FunctionRawData
from ._util import NotFoundError as _NotFoundError, \
	ForbiddenError as _ForbiddenError, Pagination as _Pagination

__all__ = ["Decoder"]

# ---
# Utilities.
# ---

# As `type` is a local variable in some functions, we define an alias to
# the real function named `_type`.

_type = type

# Ajax field for when decoding an Ajax response.

class _AjaxField:
	""" Microsoft Ajax response part. """

	def __init__(self, code, name, value, text):
		self.__code = str(code)
		self.__name = str(name)
		self.__value = str(value)
		self.__text = str(text)

	def __repr__(self):
		return f'Field(id = {repr(self.code)}, name = {repr(self.name)}, ' \
			f'attrib = {repr(self.value)})'

	@property
	def code(self):
		""" The code (first field). """

		return self.__code

	@property
	def name(self):
		""" The name (second field). """

		return self.__name

	@property
	def value(self):
		""" The value (third field). """

		return self.__value

	@property
	def text(self):
		""" The text (fourth field). """

		return self.__text

# ---
# Main class.
# ---

def _validsym(s):
	""" Check if is a valid symbol part. """

	allowed_fst = 'abcdefghijklmnopqrstuvwxyz'
	allowed_end = allowed_fst + '0123456789'
	allowed_all = allowed_end + '_'

	if s is None:
		return True

	if s != s.casefold():
		return False
	if not len(s) or len(s) > 30:
		return False
	if any(x not in allowed_all for x in s):
		return False
	if s[0] not in allowed_fst or s[-1] not in allowed_end:
		return False
	return True

class Decoder:
	""" Return objects from SGDF's intranet. """

	def __init__(self):
		# Find out the AJAX code parts.

		self._ajaxcodes = {}
		for ctx in ('intranet',):
			frg = (x[13:-9] for x in dir(self) \
				if x.startswith(f"_decode_html_{ctx}_") \
				and x.endswith("_fragment"))

			self._ajaxcodes[ctx] = {getattr(self,
				f"_decode_ajax_{frag}_codes"): frag for frag in frg \
				if hasattr(self, f"_decode_ajax_{frag}_codes")}

	def decode(self, inp, type = 'text/html', hint = None, **kwargs):
		""" Decode a document and return what's in it.

			`content`: the content as a stream, bytes or text object.
			`type`: the MIME type.
			`hint`: the hint, including the context (e.g.
				`intranet_place`).

			Special hints:
			- `ignore`: ignore the content.
			- `raw`: return the raw content.
			- `sic`: return the type decoded content. """

		if hint == 'ignore':
			return None

		# Sanitize the keyword arguments.

		for kw in ('tree', 'content', 'text', 'entries', 'data'):
			try:
				del kwargs[kw]
			except KeyError:
				pass

		# Check that the document type is valid.

		if not type in ('text/html', 'text/csv', 'text/xml',
			'application/x-microsoft-ajax', 'application/json',
			'application/vnd.ms-excel'):
			raise ValueError(f"Unknown document type: {repr(type)}")

		# Check that the hint is valid.

		if hint is not None and not _validsym(hint):
			raise ValueError("invalid hint format")

		# FIXME: in case of a stream, we want to seek back to where we are.

		if hint == 'raw':
			if isinstance(inp, _IOBase):
				inp = inp.read()
			return inp

		# FIXME: check if the document is actually an error?
		# FIXME: get request data somehow, such as iid?

		if   type == 'text/html':
			# An HTML page or fragment, use BeautifulSoup.

			if not hint:
				raise ValueError(f"Missing HTML hint")
			elif hint != 'sic':
				try:
					func = getattr(self, f"_decode_html_{hint}")
				except AttributeError:
					msg = f"Unknown HTML hint: {repr(hint)}"
					raise ValueError(msg) from None

			tree = _BeautifulSoup(inp, 'lxml')

			# Check for an error div with a known error.

			enode = tree.find(id = 'ctl00__upMainContent')
			if enode is not None:
				# Check if it is a 404 or a 403.

				node = enode.find(attrs = {'class': 'interdit'})

				if node is not None:
					nftext = "Cette page est introuvable."
					fptext = "Vous n'avez pas les droits nécessaires pour " \
						"accéder à cette page."

					if   node.text == nftext:
						raise _NotFoundError()
					elif node.text == fptext:
						raise _ForbiddenError()

			# Treat the answer.

			if hint == 'sic':
				return tree

			result = func(tree)
		elif type == 'application/x-microsoft-ajax':
			# The input might be a stream.

			if isinstance(inp, _IOBase):
				if _type(inp.read(0)) == bytes:
					inp = _TextIOWrapper(inp)

				content = inp.read()
			elif _type(inp) == bytes:
				content = inp.decode('UTF-8')
			elif _type(inp) == str:
				content = str(inp)
			else:
				raise ValueError("Invalid input type")

			# Answers to Microsoft Ajax calls are a set of elements separated
			# by pipes ('|'), and must be read four by four as described
			# in the intranet's Ajax documentation.

			resp = []
			raw = iter(content.split('|')[:-1])
			for code in raw:
				code = int(code)
				name = next(raw)
				attrib = next(raw)
				text = next(raw)

				resp.append(_AjaxField(code, name, attrib, text))

			if hint == 'sic':
				return resp

			# The answer's payload usually is in the second entry.
			# The code may allow to determinate what it corresponds to,
			# but a lot of codes can be used depending on the actions
			# leading to the fragment gathering and the context (e.g.
			# the state of the search form), so we'll try to match one
			# of the known codes and trust the context for the other cases.

			field = resp[1]

			# If we need a hint, let's find out the hint.

			if hint is None:
				try:
					part = self._ajaxcodes[hint][field.code]
				except KeyError:
					raise ValueError("ajax hint could not be determined")
			else:
				part = hint

			try:
				assert hint != None
				func = getattr(self, f"_decode_html_{hint}_fragment")
			except (AssertionError, AttributeError):
				try:
					hint = self._ajaxcodes[hint][field.code]
					func = getattr(self, f"_decode_html_{hint}_fragment")
				except (KeyError, AttributeError):
					msg = "Ajax hint could not be determined"
					raise ValueError(msg) from None

			return func(field.text)
		elif type == 'text/csv':
			# The input might be of different type, we want a text stream.

			if isinstance(inp, _IOBase):
				if _type(inp.read(0)) == bytes:
					inp = _TextIOWrapper(inp)
			elif _type(inp) == bytes:
				inp = _TextIOWrapper(_BytesIO(inp))
			elif _type(inp) == str:
				inp = _StringIO(inp)
			else:
				raise ValueError("Invalid input type")

			# Try to find out for the hint.

			if hint != 'sic':
				try:
					assert hint != None
					func = getattr(self, f"_decode_csv_{hint}")
				except (AssertionError, AttributeError):
					raise ValueError(f"Invalid CSV hint: {hint}") from None

			# Decode the file through the CSV reader, and send it to the
			# function.

			reader = _csvreader(content, delimiter = ';')
			resp = [row for row in reader]

			if hint == 'sic':
				return resp

			return func(resp)
		elif type == 'application/vnd.ms-excel': # XLS document.
			# The input might be of different type, we want a text stream.

			if isinstance(inp, _IOBase) and _type(inp.read(0)) == bytes:
				pass # ok!
			elif _type(inp) == bytes:
				inp = _BytesIO(inp)
			else:
				raise ValueError("Invalid input type (expected bytes)")

			# Get the hint.

			if hint != 'sic':
				try:
					assert hint != None
					func = getattr(self, f"_decode_xls_{hint}")
				except (AssertionError, AttributeError):
					raise ValueError(f"Invalid XLS hint: {hint}") from None

			# Read the entries through pandas and call the function.

			def entries(content):
				""" Récupération des entrées depuis une dataframe, et
					extraction en tant qu'itérateur. """

				df = _read_excel(stream)

				for i in _it.count():
					try:
						yield {i.replace(".", ""): j \
							for i, j in dict(df.ix[i]).items()}
					except KeyError:
						break

			resp = [e for e in entries(content)]
			if hint == 'sic':
				return resp

			return func(resp)
		elif type == 'text/xml':
			# We ought to read the XML document through BeautifulSoup.
			# If the first element is a '<string>', then we suppose the
			# content is JSON.

			content = _BeautifulSoup(inp, 'lxml')
			if next(content.body.children).name == 'string':
				content = _jsonloads(next(content.body.children).text)

			if hint == 'sic':
				return hint

			# And here we manage this manually.
			# TODO: there is a more elegant solution.

			if   hint == 'intranet_functions':
				return self.__decode_json_intranet_functions(content)
			else:
				raise ValueError("Unknown XML hint: {repr(hint)}")
		elif type == 'application/json':
			# The input might be of different type, we want a text stream.

			if isinstance(inp, _IOBase):
				if _type(inp.read(0)) == bytes:
					inp = _TextIOWrapper(inp)
			elif _type(inp) == bytes:
				inp = _TextIOWrapper(_BytesIO(inp))
			elif _type(inp) == str:
				inp = _StringIO(inp)
			else:
				raise ValueError("Invalid input type")

			# Try to find out for the hint.

			if hint != 'sic':
				try:
					assert hint != None
					func = getattr(self, f"_decode_json_{hint}")
				except (AssertionError, AttributeError):
					raise ValueError(f"Invalid JSON hint: {hint}") from None

			# Then load using the standard json module.
			# If it is a {'d': '…'} payload, it is a WebService answer and
			# we should redecode the content pointed by the 'd' key, which
			# is a string representing a JSON content.
			# Then send the to the function.

			data = _jsonload(inp)

			try:
				data = _jsonloads(data['d'])
			except:
				pass

			if hint == 'sic':
				return data

			return func(data)
		else:
			raise ValueError(f"unknown type: {repr(type)}")

		return result

	# ---
	# HTML pages decoding.
	# ---

	def __get_html_pagination(self, tree):
		""" Get the pagination from an HTML page. """

		# Récupération de la pagination.
		# `numpages` : numéro maximal de page dans la pagination.
		# `more`: y a-t-il plus de pages (la dernière page est-elle
		#         en « ... » ?).
		# `curpage` : page actuelle selon la pagination.

		p = tree.find('tr', {'class': ['pagination']})
		if p != None:
			p = p.find('tr')
			td = p.find_all('td')[-1]
			button = next(td.children)

			if button.name == 'span':
				num = button.text.strip()
				more = False
			else:
				num = button['href']
				num = num[num.find("'Page$") + 6:]
				num = num[:num.find("'")]
				more = button.text == '...'

			numpages = int(num)

			for td in p.find_all('td'):
				child = next(td.children)
				if child.name == 'span':
					curpage = int(child.text)
					break
		else:
			curpage = 1
			numpages = 1
			more = False

		pgn = _Pagination(curpage, numpages, more)
		print(pgn)
		return pgn

	def _decode_html_intranet_operations(self, tree):
		""" Decode the HTML operations from a BeautifulSoup decoded
			content. """

		stprefix = '/Specialisation/Sgdf/structures/ResumeStructure.aspx'
		adprefix = '/Specialisation/Sgdf/adherents/ResumeAdherent.aspx'
		irprefix = '/Specialisation/Sgdf/Rassemblements/' \
			'InscriptionRassemblementV2.aspx'
		cpprefix = '/Specialisation/Sgdf/camps/ConsulterModifierCamp.aspx'
		laprefix = '/Specialisation/Sgdf/Commun/ResumeLieuActivite.aspx'

		parent = tree.find(id = 'ctl00_Popup__evenements__gvEvenements')
		if not parent:
			return []

		elts = []

		# Récupération de la pagination.

		elts.append(self.__get_html_pagination(parent))

		# Récupération de la liste d'évènements.

		if not parent.find('tr', attrs = {'class': ['vide']}):
			for elt in parent.find_all('tr', recursive = False):
				try:
					assert 'entete' in elt['class']
					continue
				except:
					pass
				try:
					assert 'pagination' in elt['class']
					continue
				except:
					pass

				td = elt.find_all('td')
				ch = iter(td)

				edate = next(ch).text.strip()
				ename = next(ch).text.strip()
				etype = next(ch).text.strip()
				eobjs = next(ch)
				edesc = next(ch).text.strip()

				# Time decoding.

				d, t = edate.split()
				day, mon, year = map(int, d.split('/'))
				hour, min, sec = map(int, t.split(':'))
				dt = _datetime(year, mon, day, hour, min, sec)

				# Operation creation.

				op = _Operation()
				op.author.name = ename
				if not op.author.name:
					# XXX: Bogus event of type `Individu /`… for now we're
					# ignoring it.

					continue

				op.time = dt
				op.type = etype
				op.fields = edesc

				# Objects decoding.

				for link in eobjs.find_all('a'):
					name = link.text
					url = _urlparse(link['href'])
					if   url.path == stprefix:
						st = _Structure()
						st.iid = _parse_qs(url.query)['id'][0]
						st.name = name
						op.related.add(st)
					elif url.path == adprefix:
						ad = _Adherent()
						ad.iid = _parse_qs(url.query)['id'][0]
						ad.name = name
						op.related.add(ad)
					elif url.path == irprefix:
						ir = _RallyRegistration()
						ir.iid = _parse_qs(url.query)['id'][0]
						ir.name = name
						op.related.add(ir)
					elif url.path == cpprefix:
						cp = _Camp()
						cp.iid = _parse_qs(url.query)['IdCamp'][0]
						cp.name = name
						op.related.add(cp)
					elif url.path == laprefix:
						la = _Place()
						la.iid = _parse_qs(url.query)['id'][0]
						la.name = name
						op.related.add(la)

				elts.append(op)

		return elts

	def _decode_html_intranet_place(self, tree):
		""" Decode the HTML place from a BeautifulSoup decoded
			content. """

		parent = tree.find(id = 'ctl00__upMainContent')
		rp = 'ctl00_MainContent__resume__'

		place = _Place()

		# Informations générales: Libellé.

		lib = parent.find(id = f'{rp}lbLibelle')
		place.name = lib.text

		# Informations générales: Description.

		desc = parent.find(id = f'{rp}lbDescription')
		place.description = desc.text

		# Informations générales: Fiche. TODO
		# XXX: absence de champ… faut voir ce que ça donne quand c'est rempli ?

		# Coordonnées: Adresse (lignes).
		# Avec plusieurs lignes du type `lbLigne1`, `lbLigne2`, `lbLigne3`.
		# Certaines lignes peuvent ne pas être présentes, e.g. `lbLigne2`
		# peut manquer.

		def lines():
			for i in range(1, 4):
				try:
					aid = f'{rp}resumeAdresse__lbLigne{i}'
					al = parent.find(id = aid)
					assert al != None
				except:
					continue
				yield al.text.strip()

		place.address = '\n'.join(lines())

		# Coordonnées: Adresse (code postal).

		cp = parent.find(id = f'{rp}resumeAdresse__lbCodePostal')
		place.postal_code = cp.text

		# Coordonnées: Adresse (nom de la commune).

		vil = parent.find(id = f'{rp}resumeAdresse__lbVille')
		place.town = vil.text

		# Coordonnées: Adresse (pays).

		pays = parent.find(id = f'{rp}resumeAdresse__lbPays')
		place.country = pays.text

		# Coordonnées: département administratif.
		# Au format `XX - Nom du département` (où XX représente le numéro).

		dept = parent.find(id = f'{rp}lbDepartementAdministratif')
		place.department = dept.text

		# Coordonnées: étranger.
		# "Oui" ou "Non" selon si le lieu se trouve en France ou non… ?

		etr = parent.find(id = f'{rp}lbEtranger')
		place.out_of_france = (True, False)[etr.text == 'Non']

		# Coordonnées: continent.
		# Nom du continent, e.g. « Europe ».

		cont = parent.find(id = f'{rp}lbContinent')
		place.continent = cont.text

		# Coordonnées: numéro de téléphone.
		# Numéro de téléphone fixe associé au lieu.

		phone = parent.find(id = f'{rp}lbTelephone')
		place.phone = phone.text

		# Coordonnées: numéro de fax.
		# Numéro de fax associé au lieu.

		fax = parent.find(id = f'{rp}lbFax')
		place.fax = fax.text

		# Coordonnées: adresse de courriel.
		# Adresse de courriel associée au lieu.

		email = parent.find(id = f'{rp}lbCourriel')
		place.email = email.text

		# Informations complémentaires: numéro J&S.
		# XXX: ?? (vide sur les lieux explorés).

		numjs = parent.find(id = f'{rp}lbNumeroJS')
		place.js = numjs.text

		# Informations complémentaires: hébergement "dur".
		# "Oui" s'il y a un hébergement en "dur" sur le lieu, "Non" sinon.

		hebd = parent.find(id = f'{rp}lbHebergementDur')
		place.hardwall = (True, False)[hebd.text == 'Non']

		# Informations complémentaires: numéro de local.
		# XXX: ?? (vide sur les lieux explorés).

		numloc = parent.find(id = f'{rp}lbNumeroLocal')
		place.localnumber = numloc.text

		# Informations complémentaires: propriétaire.
		# Nom du propriétaire, e.g. « Bertrand DUPONT » (format libre).

		prop = parent.find(id = f'{rp}lbProprietaire')
		place.owner = prop.text

		# Informations complémentaires: adresse du propriétaire.
		# XXX: ?? (vide sur les lieux explorés).

		addrp = parent.find(id = f'{rp}lbAdresseProprietaire')
		place.owner_address = addrp.text

		# Accès: numéro de carte IGN.
		# XXX: ?? (vide sur les lieux explorés).

		ign = parent.find(id = f'{rp}lbNumeroCarteIGN')
		place.ign_num = ign.text

		# Accès: accès voiture.
		# "Oui" si le lieu est accessible en voiture, "Non" sinon.

		voit = parent.find(id = f'{rp}lbAccesVoiture')
		place.car_access = (True, False)[voit.text == 'Non']

		# Accès: distance de la gare la plus proche.
		# Au format libre (e.g. « 5km »).

		gard = parent.find(id = f'{rp}lbDistanceGare')
		place.closest_train_station_distance = gard.text

		# Accès: nom de la gare la plus proche.
		# Au format libre (e.g. « Saint julien du Sault »).

		garn = parent.find(id = f'{rp}lbNomGare')
		place.closest_train_station = garn.text

		# Accès: distance de l'arrêt de bus le plus proche.
		# Au format libre.

		busd = parent.find(id = f'{rp}lbDistanceArretBus')
		place.closest_bus_stop_distance = busd.text

		# Accès: nom de l'arrêt de bus le plus proche.
		# Au format libre.

		busn = parent.find(id = f'{rp}lbNomArretBus')
		place.closest_bus_stop = busn.text

		return place

	def _decode_html_intranet_structure_search(self, tree):
		""" Decode the HTML search results for structures from a
			BeautifulSoup decoded content. """

		parent = tree.find(id = 'ctl00_Popup__recherche__gvResultats')
		elts = []

		# Récupération de la pagination.

		pgn = self.__get_html_pagination(parent)
		elts.append(pgn)

		# Récupération des structures.

		search_attrs = {'class': ['ligne1', 'ligne2']}
		for tr in parent.find_all('tr', attrs = search_attrs):
			tds = tr.find_all('td')
			name = tds[1].find('span').text
			sta = tds[2].find('span').text
			dep = tds[3].find('span').text
			typ = tds[4].find('span').text
			telsp = tds[5].find('span')
			tel = telsp.text if telsp is not None else ""

			code, *name = name.split('-')
			code = code.rstrip()
			name = '-'.join(name).lstrip()

			st = _Structure()
			st.name = name
			st.code = code
			st.status = sta
			st.department = dep
			st.type = typ
			st.phone = tel

			elts.append(st)

		return elts

	def _decode_html_intranet_structure_summary(self, tree):
		""" Decode the HTML summary page for a structure from a
			BeautifulSoup decoded content. """

		parent = tree.find(id = 'ctl00_ctl00_MainContent_TabsContent_' \
			'TabContainerResumeStructure__tabResume')
		rp = 'ctl00_ctl00_MainContent_TabsContent_' \
			'TabContainerResumeStructure__tabResume__resume__'

		st = _Structure()

		# Type de structure, parmi :
		# - « Unité 8-11 ans » : unité louveteaux-jeanettes.

		typ = parent.find(id = f"{rp}lblType")
		st.type = typ.text

		# Code de la structure.

		code = parent.find(id = f"{rp}lblCodeStructure")
		st.code = code.text

		# Nom de la structure.

		nom = parent.find(id = f"{rp}lblNom")
		st.name = nom.text

		# Description de la structure.

		desc = parent.find(id = f"{rp}lblDescription")
		st.description = desc.text

		# Statut de la structure. TODO
		# Par exemple, « Ouverte ».

		status = parent.find(id =  f"{rp}lblStatut")
		st.status = status.text

		# Hémisphère de la structure. TODO

		hemis = parent.find(id = f"{rp}lblHemisphere")
		st.hemisphere = hemis.text

		# Adresse de la structure. TODO

		def lines():
			for i in range(1, 4):
				try:
					aid = f'{rp}resumeAdresse__lbLigne{i}'
					al = parent.find(id = aid)
					assert al != None
				except:
					continue
				yield al.text.strip()

		st.address = '\n'.join(lines())

		# Code postal.

		cp = parent.find(id = f"{rp}resumeAdresse__lbCodePostal")
		st.postal_code = cp.text.strip()

		# Nom de la commune.

		vil = parent.find(id = f"{rp}resumeAdresse__lbVille")
		st.town = vil.text.strip()

		# Pays de la commune.

		pays = parent.find(id = f"{rp}resumeAdresse__lbPays")
		st.country = pays.text.strip()

		# Département administratif.

		dept = parent.find(id = f"{rp}lblDepartement")
		st.department = dept.text.strip()

		# Numéro de téléphone.

		phone = parent.find(id = f"{rp}lblTelephone")
		st.phone = phone.text.strip()

		# Numéro de fax.

		fax = parent.find(id = f"{rp}lblFax")
		st.fax = fax.text.strip()

		# Adresse de courriel.

		email = parent.find(id = f"{rp}lblCourrier")
		st.email = email.text.strip()

		# Site web.

		website = parent.find(id = f"{rp}hlSiteWeb")
		try:
			st.website = website['href']
		except KeyError:
			pass

		# Date de début d'activité pour la saison courante.

		deb = parent.find(id = f"{rp}lblDateDebutActivite")
		st.start = deb.text

		# Informations de localisation.

		loc = parent.find(id = f"{rp}lblInfosLocalisation")
		st.location_info = loc.text

		# Coordonnées GPS. TODO

		lat = parent.find(id = f"{rp}lblCoordonneesGPSLatitude")
		st.gps_latitude = lat.text
		lon = parent.find(id = f"{rp}lblCoordonneesGPSLongitude")
		st.gps_longitude = lon.text

		return st

	def _decode_html_intranet_structure_hierarchy(self, tree):
		""" Decode the HTML hierarchy page for a structure from a
			BeautifulSoup decoded content. """

		parent = tree.find(id = 'ctl00_ctl00_MainContent_TabsContent_' \
			'TabContainerResumeStructure__tabHierarche')

		# Récupération de la structure parente. TODO
		# `pid`: identifiant de la structure parente.
		# `pcode`: code de la structure parente.
		# `pname`: nom de la structure parente.

		code = parent.find(id = 'ctl00_ctl00_MainContent_TabsContent_' \
			'TabContainerResumeStructure__tabHierarche__gvParents_ctl02_' \
			'_hlStructure')
		pid  = _parse_qs(_urlparse(code['href']).query)['id'][0]
		pid  = _b64decode(pid)
		pcode = code.text

		p = parent.find(id = 'ctl00_ctl00_MainContent_TabsContent_' \
			'TabContainerResumeStructure__tabHierarche__gvParents')
		pname = p.find_all('td')[1].text

		#self.structures.add(st)
		return None

	# ---
	# HTML (Ajax) fragments decoding.
	# ---

	_decode_ajax_intranet_personlist_codes = (9192, 9431, 9449, 15819, 17464,
		17721, 20723, 22607, 22864)
	_decode_ajax_intranet_person_summary_codes = (21686,)
	_decode_ajax_intranet_person_family_codes = (7190,)
	_decode_ajax_intranet_calendar_month_codes = (23896, 24180, 24954, 26883,
		26931, 27407, 27933, 28026, 29232, 31576, 33283, 33288, 33438, 38663,
		39664, 40051, 47167)

	def _decode_html_intranet_personlist_fragment(self, tree):
		""" Decode the HTML operations from a BeautifulSoup decoded
			content. """

		people = []

		parent = tree.find(id = 'ctl00_MainContent__recherche__gvResultats')
		for line in parent.children:
			try:
				_, name, adh, fct, st, finfct, cp, vil, \
					finadh, *_ = line.children
			except:
				continue

			p = Person()

			# Nom et ID interne.

			try:
				url = next(name.children)['href']
				q = _parse_qs(_urlparse(url).query)
				iid = q['id'][0]
			except:
				continue

			nom = next(name.children).text
			props = nom.split()

			p.iid = iid
			p.common_name = props[0]
			p.first_name = props[-1]

			# Code d'adhérent, fonction, structure associée,
			# période d'adhésion. TODO
			#
			# La date de fin de fonction est au format JJ/MM/AAAA.
			# La date de fin d'adhésion est au format JJ/MM/AAAA.
			# Le code adhérent est un nombre uniquement, e.g. « 110 ».
			#
			# Si la personne est une invitée, les champs de fin d'adhésion
			# ainsi que le code adhérent sont vides (mais pas le champ de
			# fin de fonction, qui fait référence à la date de fin du
			# statut d'invité).
			#
			# Il peut y avoir un code adhérent mais pas de date de fin
			# d'adhésion + fonction, ou simplement pas de date de fin de
			# fonction.

			try:
				code = next(adh.children).text
				fin_adhesion = next(finadh.children).text
			except:
				code = None

			fonction = fct.text
			try:
				finfonction = next(finfct.children).text
			except:
				finfonction = None
			structure = next(st.children).text

			# Commune de résidence.

			code_postal = next(cp.children).text
			ville = next(vil.children).text

			p.address.municipality.name = ville
			p.address.municipality.postal_code = code_postal

			# Ajout au tableau.

			people.append(p)

		return people

	def _decode_html_intranet_calendar_month_fragment(self, tree):
		""" Decode the HTML page for a calendar month from a
			BeautifulSoup decoded content. """

		parent = tree.find(id = 'ctl00_MainContent__calendrier')
		events = []

		for jour in parent.find_all(attrs = {'class': ['jourDuMois']}):
			for div in jour.find_all('div'):
				try:
					e_id = div.find_all('a', recursive = False)[1]
				except:
					continue
				e_id = _parse_qs(_urlparse(e_id['href']).query)['id'][0]

				e = Event()

				span = div.find('span')['onmouseover']
				span = span[span.find("'") + 1:]
				spanidx = next(_rfinditer(r"($|[^\\])(\\{2})*\'", span)).end()
				span = span[:spanidx - 1]
				span = _rreplace(r"($|[^\\])\\*'", r"\1'", span)
				span = _htmlunescape(span)

				span = span.replace('<br />', '\n')
				span = span.replace('<hr />', '')
				span = span.replace('<u>', '')
				span = span.replace('</u>', '')
				span = _rsplit(r'</?b>', span)

				# Identifiant de l'intranet.

				e.iid = e_id

				# Libellé de l'évènement.

				e.name = span[1].strip()

				# Description de l'évènement.
				# Au format multi-lignes.

				desc = span[14].strip()
				if desc != "Indéterminée":
					e.desc = desc

				# Type de l'évènement. TODO
				# Parmi :
				# - "Sortie Journée"
				# - "Réunion Demi-Journée"
				# - "Week-End"
				# - "Réunion de travail"
				# - "Camp Année"
				# - "Camp Eté"
				# - "Extrajob"

				typ  = span[4].strip()

				# Date de début de l'évènement.
				# Sous le format "JJ/MM/AAAA HH:MM".

				def dateheure(x):
					jma, hm = x.split()
					j, M, a = map(int, jma.split('/'))
					h, m = map(int, hm.split(':'))

					return DateHeure(a, M, j, h, m)

				du   = span[6].strip()
				e.start = dateheure(du)

				# Date de fin de l'évènement.
				# Sous le format "JJ/MM/AAAA HH:MM".

				au   = span[8].strip()
				e.end = dateheure(au)

				# Lieu de l'évènement.
				# En une ligne. "Indéterminé" s'il n'y en a pas.

				lieu = span[10].strip()
				if lieu != "Indéterminé":
					e.place.name = lieu

				# Structure principale ayant proposé l'évènement. TODO
				# Au format "CODE - NOM".

				prop = span[12].strip()

				# Dernier utilisateur ayant mis à jour l'évènement. TODO
				# Nom seulement.

				maj  = span[16].strip()

				# Fonctions concernées. TODO
				# Valeurs possibles :
				# - "Toutes".

				fct  = span[18].strip()

				# Date de rappel de l'évènement. TODO
				# Valeurs possibles :
				# - "Aucune"
				# - ?

				dr   = span[20].strip()

				# Visibilité de l'évènement. TODO
				# Valeurs possibles :
				# - "Structure seule"
				# - "Structures dépendantes"

				vis  = span[22].strip()

				# Date de dernier envoi des invitations. TODO
				# Valeurs possibles :
				# - "Aucun"
				# - ?

				inv  = span[24].strip()

				# Ajout de l'évènement à la liste.

				events.append(e)

		return events

	# ---
	# XLS documents decoding.
	# ---

	def _decode_xls_intranet_operations(self, data):
		""" Decode the XLS documents for operations ("Journal_activites.xls")
			from a pandas decoded content. """

		print(content)
		raise NotImplementedError

	# ---
	# JSON documents decoding.
	# ---

	def _decode_json_intranet_functions(self, data):
		""" Decode the JSON functions autocompletion data. """

		def _sfix(code):
			if code[-1:] == "L" or code[:1] == "3":
				return "_L"
			if code[-1:] == "N" or code[:1] == "6":
				return "_N"
			if code[-1:] == "T" or code[:1] == "9":
				return "_T"
			return ""

		def _cname(cname):
			""" Make a canonical name out of a name. """

			cfilt = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_'

			cname = cname.casefold().upper()
			cname = cname.replace(' - ', ' ')
			cname = cname.replace(' !', '')
			cname = cname.replace('  ', ' ')
			cname = cname.replace("D'", '')
			cname = cname.replace(' ', '_')
			cname = cname.replace('É', 'E')
			cname = cname.replace('À', 'A')
			cname = ''.join(filter(lambda c: c in cfilt, cname))

			return cname

		# First phase: load from the JSON and store as an array under the
		# constant name.

		funcs = {}

		for idx, value in enumerate(data):
			iid = int(value['id'])
			name = value['name']

			code, rest = name.split('(')
			code = code.strip()
			rest = rest.split(')')[0]

			rest = rest.split('/')
			nm = rest[0].strip()
			if len(rest) == 1:
				nf = None
			else:
				nf = '/'.join(rest[1:])
				nf = nf.strip()
				if nf == nm:
					nf = None

			cnames = [_cname(nm)]
			if nf is not None and _cname(nf) != _cname(nm):
				cnames.append(_cname(nf))

			func = _FunctionRawData(iid, code, nm, nf, cnames, idx + 1)

			for cname in cnames:
				if not cname in funcs:
					funcs[cname] = []
				funcs[cname].append(func)

		# Second phase: disambiguation.

		while True:
			try:
				cname = next(cn for cn in funcs.keys() if len(funcs[cn]) > 1)
			except StopIteration:
				break

			disf = funcs[cname]
			del funcs[cname]

			# We ought to find a solution to make other canonical names.

			codes = [func.code for func in disf]
			sfix = [_sfix(code) for code in codes]
			if len(sfix) > len(set(sfix)):
				raise ValueError(f"Could not deduplicate using scale: {codes}")

			for func, suffix in zip(disf, sfix):
				# Delete all the current function references.

				for cname in func.cnames:
					try:
						f = funcs[cname]
					except KeyError:
						continue

					f.remove(func)
					if not f:
						del funcs[cname]

				# Replace all of the cnames.

				func = func.add_cname_suffix(suffix)

				# Add all of the references again.

				for cname in func.cnames:
					if not cname in funcs:
						funcs[cname] = []
					funcs[cname].append(func)

		# Third phase: flatten the functions and we're done!

		funcs = list(set(func[0] for func in funcs.values()))
		funcs.sort(key = lambda x: x.srcorder)

		return funcs

# End of file.