aboutsummaryrefslogtreecommitdiff
path: root/sgdfi/_manager.py
blob: 12966142862377139d85756ed440dbbf36b471cb (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
#!/usr/bin/env python3
#******************************************************************************
# Copyright (C) 2018 Thomas 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 representations, and
	manage sessions. """

import os.path as _path

from os import listdir as _listdir, 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 io import RawIOBase as _RawIOBase, TextIOWrapper as _TextIOWrapper
from sys import stdout as _stdout
from string import ascii_letters as _ascii_letters
from shutil import copyfile as _copyfile
from datetime import datetime as _datetime, date as _date

from appdirs import user_cache_dir as _user_cache_dir

from ._repr import Base as _Base, Structure as _Structure, \
	Adherent as _Adherent, Place as _Place, \
	RallyRegistration as _RallyRegistration, Camp as _Camp, \
	Operation as _Operation, FunctionRawData as _FunctionRawData
from ._intranet import AnonymousIntranetSession as _AnonymousIntranetSession, \
	IntranetSession as _IntranetSession
from ._decode import Decoder as _Decoder

__all__ = ["Manager"]

def _names(value):
	names = ()
	try:
		names += (str(value),)
	except:
		pass
	try:
		names += (value.__name__,)
	except:
		pass
	names += (value.__class__.__name__,)

	flt = lambda x: ''.join(c for c in x.casefold() if c in _ascii_letters)
	return tuple(map(flt, names))

def _isany(value):
	""" Check if a value can be considered as any. """

	return bool(value is any or "any" in _names(value))

def _isall(value):
	""" Check if a value can be considered as all. """

	return bool(value is all or "all" in _names(value))

def _isanon(value):
	""" Check if a value can be considered as anonymous. """

	return bool(value is None or any(n for n in _names(value) \
		if n in ("anon", "anonymous", "none")))

# ---
# Utilities.
# ---

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

_type = type

# Get the date for the public interface.

def _dt(value, fromspan = False):
	""" Get a datetime or datetime span from anything (and validate). """

	if   isinstance(value, _datetime):
		return value
	elif isinstance(value, _date):
		return _datetime.fromordinal(value.toordinal())
	else:
		return _datetime.fromtimestamp(value)

# Check if something is a valid symbol, for making valid Python keywords.

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

# ---
# Management classes.
# ---

class _IntranetSessionsManager:
	""" Intranet sessions manager. """

	def __init__(self, mgr, *_, base = 'https://intranet.sgdf.fr'):
		self.__mgr = mgr
		self.__anon = None
		self.__sessions = []
		self.__base = base
		pass

	def __getitem__(self, key):
		if _isanon(key):
			if self.__anon is None:
				# The session will reference itself into this manager.

				_AnonymousIntranetSession(self.__mgr, base = self.__base)

			return self.__anon

		if _isany(key):
			if self.__sessions:
				return self.__sessions[0]
			raise KeyError("no session available")

		try:
			s = next(s for s in self.__sessions if s.user == key)
		except StopIteration:
			# Try and find it using an index.

			try:
				i = int(key)
			except (TypeError, ValueError):
				raise KeyError("invalid key format")

			return self.__sessions[key]

		# Return the found session.

		return s

	def __delitem__(self, key):
		if _isanon(key):
			self.__anon = None
			return

		if _isany(key) or _isall(key):
			self.__sessions = []
			return

		try:
			idx = next(i for i, s in enumerate(self.__sessions) \
				if s.user == key)
		except StopIteration:
			# Try and find it using an index.

			try:
				i = int(key)
			except (TypeError, ValueError):
				raise KeyError("invalid key format")

		self.__sessions[idx]._deref()

	def _ref(self, session):
		""" A session comes to reference itself into this manager, we will
			manage it. """

		if   isinstance(session, _IntranetSession):
			if any(s is session for s in self.__sessions):
				return
			self.__sessions.append(session)
		elif isinstance(session, _AnonymousIntranetSession):
			if   session is self.__anon:
				return
			elif self.__anon is None:
				self.__anon = session
			else:
				raise ValueError("There is already an anonymous session here.")
		else:
			raise ValueError("Expected a session.")

	def _deref(self, session):
		""" A session comes to dereference itself from this manager, we
			will manage it. """

		if   session is self.__anon:
			self.__anon = None
		else:
			try:
				idx = next(i for i, s in enumerate(self.__sessions) \
					if s is session)
				self.__sessions.pop(idx)
			except StopIteration:
				raise ValueError("Unreferenced session.") from None

	def login(self, user, pw):
		""" Add intranet credentials. """

		try:
			idx = next(i for i, s in enumerate(self.__sessions) \
				if s.user == user)
		except StopIteration:
			# No session found, we shall make a new one.

			s = None
		else:
			s = self.__sessions.pop(idx)
			self.__sessions.append(s)

		if s is None:
			# The session will reference itself into this manager.

			_IntranetSession(self.__mgr, user = user, pw = pw,
				base = self.__base)
			return

		if s.pw == pw:
			return

		# Different password than the one we know, we should try to
		# use the new password instead (and NOT change it on the intranet).

		s.pw = pw

class _SessionsManager:
	""" Sessions manager. """

	def __init__(self, mgr, *, intranet = 'https://intranet.sgdf.fr'):
		self.__mgr = mgr
		self.__i = _IntranetSessionsManager(mgr, base = intranet)

	@property
	def intranet(self):
		""" The intranet sessions manager. """

		return self.__i

	def login(self, user, pw):
		""" Add centralized (intranet) credentials. """

		self.intranet.login(user, pw)

class _StructuresManager:
	""" Structure access class. """

	def __init__(self, mgr):
		self.__mgr = mgr

	def __getitem__(self, key):
		raise NotImplementedError

class _AdherentsManager:
	""" Adherent access class. """

	def __init__(self, mgr):
		self.__mgr = mgr

	def __getitem__(self, key):
		raise NotImplementedError

class _RallyRegistrationsManager:
	""" Rally registration access class. """

	def __init__(self, mgr):
		self.__mgr = mgr

	def __getitem__(self, key):
		raise NotImplementedError

class _CampsManager:
	""" Camp access class. """

	def __init__(self, mgr):
		self.__mgr = mgr

	def __getitem__(self, key):
		raise NotImplementedError

class _PlacesManager:
	""" Place access class. """

	def __init__(self, mgr):
		self.__mgr = mgr

	def __getitem__(self, key):
		raise NotImplementedError

class _StructureEventsManager:
	""" Structure event access class. """

	def __init__(self, mgr, st):
		self.__mgr = mgr
		self.__st  = st

	def __getitem__(self, key):
		if   isinstance(key, slice):
			# The mgr.events[<iid>][datetime(y1, m1, d1):datetime(y2, m2, d2)]
			# notations was used. The step is not read.

			start = _dt(key.start) if key.start is not None else None
			stop  = _dt(key.stop)  if key.stop  is not None else None

			if start > stop:
				return []

			raise NotImplementedError
		elif isinstance(key, _date):
			# We ought to get the events corresponding to a date.

			raise NotImplementedError

		raise KeyError("Should only use slice or date key.")

class _EventsManager:
	""" Event access class. """

	def __init__(self, mgr):
		self.__mgr = mgr

	def __getitem__(self, key):
		if _isall(key):
			return _StructureEventsManager(self.__mgr, all)

		raise NotImplementedError

# ---
# The main class.
# ---

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

	def __init__(self, *_, intranet = 'https://intranet.sgdf.fr',
		save = False, folder = None, debug = False):
		super().__init__()

		self.__save     = save
		self.__folder   = folder
		self.__sessions = _SessionsManager(self, intranet = intranet)
		self.__dbg      = bool(debug)

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

		self.__sts = _StructuresManager(self)
		self.__ads = _AdherentsManager(self)
		self.__rrs = _RallyRegistrationsManager(self)
		self.__cps = _CampsManager(self)
		self.__pls = _PlacesManager(self)
		self.__evs = _EventsManager(self)

	@property
	def _debug(self):
		""" Is the manager in debug mode? """

		return self.__dbg

	@property
	def sessions(self):
		""" Managed sessions. """

		return self.__sessions

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

		return self.__sts

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

		return self.__ads

	@property
	def rally_registrations(self):
		""" The rally registrations manager. """

		return self.__rrs

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

		return self.__cps

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

		return self.__pls

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

		return self.__evs

	# ---
	# Dump management.
	# ---

	_guessfile = {
		'html': 'text/html',
		'csv':  'text/csv',
		'xml':  'text/xml',
		'json': 'application/json',
		'xls':  'application/vnd.ms-excel'}

	def load_file(self, path, type = None, **kwargs):
		""" Read from a file without headers. """

		if type is None:
			for ext, mime in _guessfile.items():
				if path.endswith(f".{ext}"):
					type = mime
					break
			else:
				raise ValueError("Could not guess the file type.")

		return self.feed(open(path, "rb"), type = type, **kwargs)

	def load_latest_dump(self):
		""" Load the latest dump (shortcut for simplifying the reverse
			engineering process). """

		l = _listdir(self.__folder)
		l.sort()

		return self.load_dump(l[-1])

	def load_dump(self, time, id = None):
		""" Read from a saved dump (with headers). """

		# Args format:
		# - `mgr.load_dump(<string>)`
		# - `mgr.load_dump(_datetime(2018, 10, 26, 21, 7, 20))`
		# - `mgr.load_dump(_datetime(2018, 10, 26, 21, 7, 20), 5)`
		#
		# Out of these, a filename is deduced.

		if   type(time) == str and id is None:
			fname = time
			if not fname.endswith('.dump'):
				fname += '.dump'
		elif isinstance(time, _datetime) or isinstance(time, _date):
			if isinstance(time, _datetime):
				time = time.timestamp()
			else:
				time = _datetime.fromordinal(time.toordinal()).timestamp()

			if   id is None:
				id = 0
			elif type(id) == str:
				try:
					id = int(id)
				except ValueError:
					raise ValueError("expected an integer as an identifier")
			elif type(id) != int:
				raise ValueError("expected an integer as an identifier")
			if id < 0 or id > 99:
				raise ValueError("expected an integer between 0 and 99.")

			fname = f"{int(time)}{id:02d}.dump"
		else:
			raise ValueError("unknown args format")

		# Load the file.

		kwargs = {}

		fp = open(_path.join(self.__folder, fname), 'rb')
		while True:
			line = fp.readline().decode('UTF-8').splitlines()[0]
			if not line:
				break

			kw, *value = line.split(': ')
			if not _validsym(kw) or kw == 'inp' or not value:
				continue
			value = ': '.join(value)

			kwargs[kw] = value

		st = fp
		if kwargs.get('ctnt') == 'text':
			del kwargs['ctnt']
			st = _TextIOWrapper(fp)

		result = self.feed(st, **kwargs)
		fp.close()
		return result

	def save_dump(self, inp, time = _datetime.now(), **kwargs):
		""" Save a file. """

		if   isinstance(time, _datetime):
			time = time.timestamp()
		elif isinstance(time, _date):
			time = _datetime.fromordinal(time.toordinal()).timestamp()
		else:
			time = int(time)

		# Sanitize the keywords.
		# `ctnt` is used for saying that the file is to be decoded as text
		# instead of bytes.

		try:
			del kwargs["ctnt"]
		except KeyError:
			pass

		# The save process will be slightly different if we have a bytes
		# or a text content.

		mode = 'w'
		if isinstance(inp, _RawIOBase):
			if _type(inp.read(0)) == bytes:
				mode = 'wb'
		elif _type(inp) == bytes:
			mode = 'wb'
		elif _type(inp) == str:
			pass
		else:
			raise ValueError("Could not save this content")

		if not 'b':
			kwargs['ctnt'] = 'text'

		# Open the file.

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

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

		# Write the headers.

		hdr = "\r\n".join(f"{kw}: {value}" for kw, value in kwargs.items())
		hdr += "\r\n\r\n"

		if 'b' in mode:
			hdr = hdr.encode('utf-8')
		f.write(hdr)

		# Then write the content.

		if isinstance(inp, _RawIOBase):
			_copyfile(inp, f)
		else:
			f.write(inp)

		f.close()
		return time, idx

	# ---
	# Session management.
	# ---

	def login(self, user, pw):
		""" Add centralized credentials to the mix. """

		self.sessions.login(user, pw)

	# ---
	# Knowledge management.
	# ---

	def feed(self, inp, type = 'text/html', hint = None, **kwargs):
		""" Decode a document using the `decode` method, and add the
			obtained results to our knowledge. """

		# Save the dump.

		if self.__save:
			# Warning: if it's a stream, we're about to empty it and make
			# it empty for the decoder, which is not what we want.
			# So we make a bytes or str object out of the stream in order
			# to be sure to be able to read it twice (seeking might not work).

			if isinstance(inp, _RawIOBase):
				inp = inp.read()

			# Call the function.

			self.save_dump(inp, type = type, hint = hint)

		# Decode the result using the method inherited from the decoder,
		# and feed the knowledge using what has been returned by it.

		result = self.decode(inp, type = type, hint = hint, **kwargs)

		if isinstance(result, _Base) or _type(result) == list:
			# TODO: go through the result(s), feed our knowledge and
			# complete it with it.

			pass

		return result

	# ---
	# Export dynamically gathered data such as functions as Python files
	# to replace some of those in the `_dbs` submodule.
	# ---

	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.