aboutsummaryrefslogtreecommitdiff
path: root/sgdfi/_manager.py
blob: 8442817f63c61d2fa93743c89bc68d743647f406 (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
#!/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.
#******************************************************************************
""" Definition of the main object to decode and manage objects of the
	SGDF's intranet, without the network part which is managed by the
	`Session` object, which inherits from this class to manage its
	received data. """

import os.path as _path

from os import makedirs as _makedirs, open as _open, fdopen as _fdopen, \
	O_WRONLY as _O_WRONLY, O_CREAT as _O_CREAT, O_EXCL as _O_EXCL
from sys import stdout as _stdout
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
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 xml.etree.ElementTree import ElementTree as _XMLTree, \
	fromstring as _XMLFromString
from json import loads as _jsonloads
from csv import reader as _csvreader

from bs4 import BeautifulSoup as _BeautifulSoup
from pandas import read_excel as _read_excel
from appdirs import user_cache_dir as _user_cache_dir

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 ._db import Database as _Database

__all__ = ["Manager"]

# Internal classes for the `_Manager` class.

class _Pagination:
	def __init__(self):
		self.current = 0
		self.number = 0
		self.more = False

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

class _OperationManager:
	""" The operations manager. """

	def __init__(self, main):
		self.__main = main

	def add(self, op):
		if not isinstance(op, _Operation):
			raise ValueError("Expected an 'Operation'.")

		self.__main.add_op(op)

class _PlaceManager:
	""" The place manager. """

	def __init__(self, main):
		self.__main = main

	def add(self, pl):
		if not isinstance(pl, _Place):
			raise ValueError("Expected a 'Place'.")

		self.__main.add_place(pl)

class _StructureManager:
	""" The structure manager. """

	def __init__(self, main):
		self.__main = main

	def add(self, st):
		if not isinstance(st, _Structure):
			raise ValueError("Expected a 'Structure'.")

		self.__main.add_structure(st)

class _AdherentManager:
	""" The adherent manager. """

	def __init__(self, main):
		self.__main = main

	def add(self, ad):
		if not isinstance(ad, _Adherent):
			raise ValueError("Expected an 'Adherent'.")

		self.__main.add_adherent(ad)

# The main class.

_type = type

class Manager:
	""" Manage objects from SGDF's intranet. """

	def __init__(self, save = False, folder = None):
		self._pgn = _Pagination()
		self.__save = save
		self.__folder = folder

		# Work out the folder, and make sure it exists.

		cache_dir = _user_cache_dir(appname = "sgdfi")
		if folder is None:
			self.__folder = cache_dir
		try:
			_makedirs(self.__folder)
		except FileExistsError:
			pass

		# Make the data manager.

		data = _Database(cache_dir = cache_dir)
		self.__ops = _OperationManager(data)
		self.__pls = _PlaceManager(data)
		self.__sts = _StructureManager(data)
		self.__ads = _AdherentManager(data)

	@property
	def operations(self):
		""" The operations manager. """

		return self.__ops

	@property
	def places(self):
		""" The places manager. """

		return self.__pls

	@property
	def structures(self):
		""" The structures manager. """

		return self.__sts

	@property
	def adherents(self):
		""" The adherents manager. """

		return self.__ads

	# ---
	# Save file management.
	# ---

	def load_dump(self, name):
		""" Read from a saved dump. """

		path = _path.join(self.__folder, name)

		name, *ext = name.split('.')
		ext = '.'.join(ext)
		name, *hint = name.split('-')
		hint = '-'.join(hint)
		if not hint:
			hint = None

		if   ext == 'html':
			type = 'html'
		elif ext == 'txt':
			type = 'ajax'
		elif ext == 'csv':
			type = 'csv'
		elif ext == 'xls':
			type = 'xls'
		elif ext == 'xml':
			type = 'xml'
		elif ext == 'json':
			type = 'json'
		else:
			type = None

		return self.read(path, type, hint)

	def save_dump(self, content, hint = None, type = 'html'):
		""" Save a file. """

		exts = {'html': 'html', 'csv': 'csv', 'xls': 'xls', 'xml': 'xml',
			'json': 'json'}
		ext = exts.get(type, 'txt')

		fdmode = 'w'
		if _type(hint) == str:
			hint = f"-{hint}"
		else:
			hint = ""

		srt = f"{_datetime.now().strftime('%Y%m%d%H%M%S')}"
		end = f"{hint}.{ext}"

		for idx in range(100):
			try:
				fd = _open(_path.join(self.__folder, f"{srt}{idx:02d}{end}"),
					_O_WRONLY | _O_CREAT | _O_EXCL)
			except FileExistsError:
				continue

			f = _fdopen(fd, fdmode)
			break
		else:
			raise ValueError("Could not find a suitable index…")

		f.write(content)

	# ---
	# Decoding/feeding part.
	# ---

	def read(self, path, type, hint = None):
		""" Read from any file. """

		return self.feed(open(path).read(), type, hint)

	_AjaxFieldHintCodes = {
		'personlist': (9192, 9431, 9449, 15819, 17464, 17721, 20723,
			22607, 22864),
		'person_summary': (21686,),
		'person_family': (7190,)
	}
	_AjaxFieldCodeHints = {code: hint \
		for hint, codes in _AjaxFieldHintCodes.items() for code in codes}

	def feed(self, content, type, hint = None):
		""" Feed the manager with a document.

			`content`: the raw content as UTF-8 encoded text.
			`type`: the type amongst "html", "ajax", "csv", "xls".
			`hint`: the hint. """

		if hint == 'ignore':
			return None

		if self.__save:
			self.save_dump(content, hint, type)
		if hint == 'raw':
			return content

		# FIXME: vérifier s'il y a eu une erreur.

		if   type == 'html':
			if   hint == 'operations':
				func = self.__feed_html_operations
			elif hint == 'place':
				func = self.__feed_html_place
			elif hint == 'personlist_fragment':
				func = self.__feed_html_personlist_fragment
			elif hint == 'person_summary_fragment':
				func = self.__feed_html_person_summary_fragment
			elif hint == 'person_family_fragment':
				func = self.__feed_html_person_family_fragment
			elif hint == 'structure_summary':
				func = self.__feed_html_structure_summary
			elif hint == 'structure_hierarchy':
				func = self.__feed_html_structure_hierarchy
			elif hint == 'calendar_month_fragment':
				func = self.__feed_html_calendar_month_fragment
			else:
				raise ValueError(f"unknown html hint: {repr(hint)}")

			content = _BeautifulSoup(content, 'lxml')
			return func(content)
		elif type == 'ajax':
			# Les réponses aux appels AJAX sont un ensemble d'éléments séparés
			# par des pipes ('|'), à prendre par groupe de quatre tels que
			# décrits par le document `intranet.rst`.

			resp = []
			raw = iter(text.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))

			# La charge utile de la réponse est dans la seconde entrée
			# généralement. Le code permet de déterminer de quoi il en
			# retourne, mais beaucoup de codes peuvent être émis selon les
			# actions précédentes et le contexte (e.g. état du formulaire
			# de recherche), donc on fait confiance au contexte tout en
			# proposant un contexte par défaut selon le code.

			field = resp[1]

			# On vérifie l'indice donné par l'utilisateur, s'il y en a un.

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

			if   hint == 'personlist':
				func = self.__feed_html_personlist_fragment
			elif hint == 'person_summary':
				func = self.__feed_html_person_summary_fragment
			elif hint == 'person_family':
				func = self.__feed_html_person_family_fragment
			elif hint == 'calendar_month':
				func = self.__feed_html_calendar_month_fragment
			else:
				raise ValueError(f"unknown ajax hint: {repr(hint)}")

			return func(field.text)
		elif type == 'csv':
			if   hint == 'attend':
				func = self.__feed_csv_attend
			else:
				raise ValueError(f"unknown csv hint: {repr(hint)}")

			if not isinstance(content, _IOBase):
				stream = _StringIO(content)
			reader = _csvreader(content, delimiter = ';')
			resp = [row for row in reader]

			return func(resp)
		elif type == 'xls':
			if   hint == 'people':
				func = self.__feed_xls_people
			else:
				raise ValueError(f"unknown xls hint: {repr(hint)}")

			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)]
			return func(resp)
		elif type == 'xml':
			tree = _XMLTree(_XMLFromString(content))

			if   hint == 'functions':
				data = _jsonloads(tree.getroot().text)
				return self.__feed_json_functions(data)
			else:
				raise ValueError("unknown xml hint: {repr(hint)}")
		elif type == 'json':
			data = _jsonloads(content)

			if   hint == 'functions':
				return self.__feed_json_functions(data)
			else:
				raise ValueError("unknown json hint: {repr(hint)}")
		else:
			raise ValueError(f"unknown type: {repr(type)}")

	# ---
	# HTML pages and fragments decoding.
	# ---

	def __feed_json_functions(self, content):
		""" Decode the JSON functions autocompletion data and return
			them without feeding the database. """

		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(content):
			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

	def __feed_html_operations(self, content):
		""" Decode the HTML operations from a BeautifulSoup decoded
			content and feed it into the manager's operations. """

		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 = content.find(id = 'ctl00_Popup__evenements__gvEvenements')
		if not parent:
			return [_Pagination(0, False, 1)]

		elts = []

		# 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 = parent.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

		self._pgn.current = curpage
		self._pgn.number = numpages
		self._pgn.more = more

		# 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.time = dt
				op.type = etype
				op.author = ename
				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)

				self.operations.add(op)
				elts.append(op)

		return elts

	def __feed_html_place(self, content):
		""" Decode the HTML place from a BeautifulSoup decoded
			content and feed it into the manager's places. """

		parent = content.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

		self.places.add(place)
		return place

	def __feed_html_structure_summary(self, content):
		""" Decode the HTML summary page for a structure from a
			BeautifulSoup decoded content and feed it into the
			manager's structures. """

		parent = content.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

		self.structures.add(st)
		return st

	def __feed_html_structure_hierarchy(self, content):
		""" Decode the HTML hierarchy page for a structure from a
			BeautifulSoup decoded content and feed it into the
			manager's structures. """

		parent = content.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

	def __feed_html_personlist_fragment(self, content):
		""" Decode the HTML operations from a BeautifulSoup decoded
			content and feed it into the manager's operations. """

		people = []

		parent = content.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)

		# TODO: feed.
		return people

	# ---
	# Export functions as a Python file to replace the one
	# in `_dbs/_funcdata.py`.
	# ---

	def export_functions(self, functions, to = _stdout):
		""" Export a functions array as a `_dbs/_funcdata.py` file. """

		docstring = "Generated functions reference for `_funcs.py`."

		# Initial header.

		print("#!/usr/bin/env python3", file = to)
		print("#" + "*" * 78, file = to)
		print("# Copyright (C) 2018 Thomas Touhey <thomas@touhey.fr>",
			file = to)
		print("# This file is part of the sgdfi project, which " \
			"is MIT-licensed.", file = to)
		print("#" + "*" * 78, file = to)
		print(f"{repr(docstring)}", file = to)
		print("", file = to)
		print("from enum import Enum as _Enum", file = to)
		print("", file = to)
		print("__all__ = [\"Function\", \"FunctionData\"]", file = to)
		print("", file = to)
		print("# This file was generated, do not edit it manually!", file = to)
		print("", file = to)

		# Enumeration definition.

		print("class Function(_Enum):", file = to)
		print("\t\"Unknown function.\"", file = to)
		print("\tUNKNOWN = 0", file = to)
		print("", file = to)

		for i, func in enumerate(functions, start = 1):
			print(f"\t{repr(func.name)}", file = to)
			for cname in func.cnames:
				print(f"\t{cname} = {i}")
			print("", file = to)

		# Function data definition.

		print("FunctionData = {", file = to)

		for func in functions:
			lnk = "," if func.nf is not None else "),"

			print(f"\tFunction.{func.cnames[0]}: " \
				f"({repr(func.code)}, {repr(func.iid)},", file = to)
			print(f"\t\t{repr(func.nm)}{lnk}", file = to)

			if func.nf is not None:
				print(f"\t\t{repr(func.nf)}),", file = to)

		print("}", file = to)
		print("", file = to)
		print("# End of file.", file = to)

# End of file.