aboutsummaryrefslogtreecommitdiff
path: root/sgdfi/_util.py
blob: e78bc35fa82b607b899062d2da2034001b9c1b96 (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
#!/usr/bin/env python3
#******************************************************************************
# Copyright (C) 2018 Thomas Touhey <thomas@touhey.fr>
# This file is part of the sgdfi project, which is MIT-licensed.
#******************************************************************************
""" Base objects for the intranet objects representations, never used
	by the end user of the module. """

from inspect import getargspec as _getargspec
from copy import deepcopy as _deepcopy
from urllib.parse import quote as _quote, unquote as _unquote
from enum import Enum
from datetime import datetime as _datetime, date as _date
from base64 import b64decode as _b64decode, b64encode as _b64encode

import regex as _re
from pytz import timezone as _timezone

__all__ = ["IID", "Enum",
	"Property",	"IIDProperty", "DateProperty", "BoolProperty", "EnumProperty",
	"ArrayProperty", "TextProperty", "ObjectProperty", "ValueProperty", "Base",
	"InvalidCredentialsError", "InvalidUserError", "InvalidPasswordError",
	"UnauthorizedAccountError"]

# ---
# Attribute helpers.
# ---

class IID:
	""" Identifier for any resource on the intranet. """

	# Three formats are managed:
	# - a 16-byte sequence.
	# - the equivalent in base64 as a byte sequence.
	# - the equivalent as text.

	def __init__(self, value):
		if isinstance(value, IID):
			self.__val = bytes(value)
			return

		validbyteident = lambda x: len(x) == 16

		if   isinstance(value, str):
			value = str(value)
			try:
				value = _unquote(value)
			except:
				pass

			try:
				b = _b64decode(value)
				assert validbyteident(b)
				self.__val = b
				return
			except:
				pass
		elif isinstance(value, bytes):
			value = bytes(value)

			try:
				b = value.decode('ASCII')
				try:
					b = _unquote(b)
				except:
					pass

				b = _b64decode(b)
				assert validbyteident(b)
				self.__val = b
				return
			except:
				try:
					assert validbyteident(value)
					self.__val = value
					return
				except:
					pass

		raise ValueError(f"unsuitable iid: {repr(value)}")

	def __str__(self):
		return _b64encode(self.__val).decode('ASCII')

	def __repr__(self):
		return str(self)

	def __bytes__(self):
		return self.__val

	def urlsafe(self):
		""" Get a URL-safe version of the identifier. """

		return _quote(_b64encode(self.__val))

class _Array:
	""" An array of certain objects, for the base class. """

	def __init__(self, types = ()):
		self.__list  = []
		self.__types = types

	def __repr__(self):
		return repr(self.__list)

	def __iter__(self):
		return iter(self.__list)

	def __len__(self):
		return len(self.__list)

	def __getitem__(self, x):
		return self.__list[x]

	def add(self, elt):
		""" Add an element into the array. """

		if self.__types and not any(isinstance(elt, t) for t in self.__types):
			raise TypeError(f"element to add is of unknown type {type(elt)}")
		if any(elt is e or elt == e for e in self.__list):
			raise ValueError("element already inserted")
		self.__list.append(elt)

	def empty(self):
		""" Empty the array. """

		self.__list = []

# ---
# Attributes.
# ---

class Property:
	""" A base property. """

	def __init__(self, doc = None, *args, **kwargs):
		self._doc = doc
		kwargs['doc'] = doc

		try:
			spec = _getargspec(self.init)
			if not 'doc' in spec.args and spec.varargs is None and \
				spec.keywords is None:
				del kwargs['doc']
		except:
			pass

		self.init(*args, **kwargs)

	def init(self, *args, **kwargs):
		""" Normal initialize method. """

		self.doc = "The default property."

	def doc(self, element, name):
		""" The documentation string method. """

		if self.__doc is not None:
			return self.__doc
		return self.defaultdoc(element, name)

	def defaultdoc(self, element, name):
		""" A default documentation string method. """

		return f"A default property for a {element.lower()}."

	def defaultdoc(self, element, name):
		""" """

	def get(self):
		""" Get the current property value. """

		return None

	def set(self, value):
		""" Set the current property value. """

		pass

	def delete(self):
		""" Delete the current property value. """

		pass

class IIDProperty(Property):
	""" An intranet identifier property. """

	def init(self):
		self.__iid = None

	def defaultdoc(self, element, name):
		return f"The intranet identifier for a {element.lower()}."

	def get(self):
		return self.__iid

	def set(self, value):
		if value is None:
			self.__iid = None
		else:
			self.__iid = IID(value)

	def delete(self):
		self.__iid = value

_datere = _re.compile('(?P<dom>[0-9]+)\/(?P<mon>[0-9]+)\/(?P<yr>[0-9]+)')

class DateProperty(Property):
	""" A date property. """

	def init(self):
		self.__date = None

	def defaultdoc(self, element, name):
		return f"The {name.replace('_', ' ')} timestamp for the {element}."

	def get(self):
		return self.__date

	def set(self, value):
		if value is None:
			self.__date = value
			return

		if   isinstance(value, _datetime):
			pass # use the value as is.
		elif isinstance(value, _date):
			value = _datetime.fromordinal(value.toordinal())
		elif type(value) == str:
			m = _datere.match(value)
			if   m is None:
				raise TypeError("uncorrectly formatted date string: " \
					f"{repr(value)}")
			else: # if m.group('yr'):
				year = int(m.group('yr'))
				mon  = int(m.group('mon'))
				dom  = int(m.group('dom'))
				value = _datetime(year, mon, dom)
		else:
			raise TypeError("Could not determinate a valid datetime.")

		if value.tzinfo is None:
			value = value.replace(tzinfo = _timezone('Europe/Paris'))
		self.__date = value

	def delete(self):
		self.__date = value

class BoolProperty(Property):
	""" A boolean property. """

	def init(self, default = False):
		self.__default = bool(default)
		self.__value = self.__default

	def defaultdoc(self, element, name):
		return f"If the {element} has {name.replace('_', ' ')}."

	def get(self):
		return self.__value

	def set(self, value):
		if value is None:
			self.__value = self.__default
		else:
			self.__value = bool(value)

	def delete(self):
		self.__value = self.__default

class EnumProperty(Property):
	""" An enumeration property. """

	def init(self, enum = Enum, default = None):
		if default is not None:
			try:
				default = enum(default)
			except ValueError:
				msg = "Default should be None or a valid enum value."
				raise ValueError(msg) from None

		self.__enum = enum
		self.__default = default
		self.__value = default

	def defaultdoc(self, element, name):
		return f"The {name.replace('_', ' ')} constant for " \
			f"the {element.lower()}."

	def get(self):
		return self.__value

	def set(self, value):
		if value is None:
			self.__value = self.__default
		else:
			self.__value = self.__enum(value)

	def delete(self):
		self.__value = self.__default

class ArrayProperty(Property):
	""" An array made of different objets.
		`types` are the accepted types (an empty array representing that
		all types are accepted). """

	def init(self, types = ()):
		self.__array = _Array(types)

	def defaultdoc(self, element, name):
		return f"The {name.replace('_', ' ')} array for the {element.lower()}."

	def get(self):
		return self.__array

	def set(self, value):
		if value is None:
			self.__array.empty()
			return

		raise ValueError("non settable")

	def delete(self):
		self.__array.empty()

class ObjectProperty(Property):
	""" An object property among specified types. """

	def init(self, types = (), default = None):
		self.__default = default
		self.__types = types
		self.__value = self.__default

	def get(self):
		return self.__value

	def set(self, value):
		if value is None:
			self.__value = self.__default
			return

		if not any(isinstance(value, cls) for cls in self.__types):
			raise ValueError("Shall be an instance of one of: " \
				f"{repr(self.__types)}")

		self.__value = value

	def delete(self):
		self.__value = self.__default

class ValueProperty(Property):
	""" A value property.
		Basically uses a class to store its value. """

	def init(self, cls, default = None):
		self.__cls = cls
		self.__data = default

	def get(self):
		return self.__data

	def set(self, value):
		if value is None:
			self.__data = _deepcopy(default)
			return

		self.__data = self.__cls(value)

	def delete(self):
		self.__data = _deepcopy(default)

class TextProperty(Property):
	""" A text property.
		`lines` represents the maximum number of allowed lines.
		`maxchars` represents the maximum number of characters.
		`not_empty`: if True, empty strings are considered as None. """

	def init(self, lines = 0, maxchars = 0, not_empty = False):
		self.__value = None
		self.__lines = lines
		self.__maxchars = maxchars
		self.__nempty = bool(not_empty)

	def get(self):
		return self.__value

	def set(self, value):
		if value is None or (self.__nempty and value == ''):
			self.__value = None
			return

		value = str(value)

		# Manage the lines.

		value = value.splitlines()
		lines = self.__lines
		if lines < 0:
			lines = len(value)

		tab  = ['\n'.join(value[:lines])] if lines != 0 else []
		tab += value[lines:]
		value = ' '.join(tab)
		del tab

		# Manage the maximum number of characters.

		maxchars = self.__maxchars
		if maxchars > 0 and len(value) > maxchars:
			msg = f"{name}: max text length exceeded (> {maxchars})"
			raise ValueError(msg)

		self.__value = value

	def delete(self):
		self.__value = None

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

class Base:
	""" The base class for all complex objects. """

	def __init__(self):
		for name in self.__findprops():
			super().__setattr__(name,
				_deepcopy(super().__getattribute__(name)))

	def __repr__(self):
		def getproperty(self, name):
			return super().__getattribute__(name)

		attrs = lambda: (f"{name} = {repr(val)}" for name, val \
			in map(lambda x: (x, getproperty(self, x).get()), \
			self.__findprops()) if val is not None)

		return f"{self.__class__.__name__}({', '.join(attrs())})"

	def __findprops(self):
		""" Find the properties' names. """

		def getproperty(self, name):
			return super().__getattribute__(name)

		return [i for i in dir(self) if not i.startswith('_') \
			and isinstance(getproperty(self, i), Property)]

	def __getattribute__(self, name):
		try:
			attr = super().__getattribute__(name)
		except AttributeError as e:
			raise e from None

		if name.startswith('_') or not isinstance(attr, Property):
			return attr

		if isinstance(attr, Property):
			return attr.get()
		return attr

	def __setattr__(self, name, value):
		if name.startswith('_'):
			super().__setattr__(name, value)
			return

		attr = super().__getattribute__(name)

		if not isinstance(attr, Property):
			super().__setattr__(name, value)
		attr.set(value)

	def __delattr__(self, name):
		if name.startswith('_'):
			super().__delattr__(name, value)
			return

		attr = super().__getattribute__(name)

		if not isinstance(attr, property):
			super().__delattr__(name, value)
		attr.delete()

# ---
# Exceptions.
# ---

class InvalidCredentialsError(Exception):
	""" Exception for when the credentials are invalid. """

	def __init__(self, msg = None, user = None, pw = None):
		if msg is None:
			msg = f"Invalid credentials ({repr(user)}: {repr(pw)})."

		super().__init__(msg)

		self.__user = user
		self.__pw   = pw

	@property
	def user(self):
		""" Username for which the credentials are invalid. """

		return self.__user

	@property
	def pw(self):
		""" Password which is involved in the error. """

		return self.__pw

class InvalidUserError(InvalidCredentialsError):
	""" Exception for when the user identifier is invalid. """

	def __init__(self, user):
		super().__init__(f"Invalid identifier ({repr(user)}).", user = user)

class InvalidPasswordError(InvalidCredentialsError):
	""" Exception for when the password is invalid. """

	def __init__(self, user, pw):
		super().__init__(f"Invalid password for {repr(user)} ({repr(pw)}).",
			user = user, pw = pw)

class UnauthorizedAccountError(InvalidCredentialsError):
	""" Exception for when the user is not allowed to log in. """

	def __init__(self, user):
		super().__init__(f"User with identifier {repr(user)} is not allowed " \
			"to log in.", user = user)

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(Exception):
	""" The response is a redirection to the bad request page. """

	def __init__(self):
		super().__init__("Bad request.")

class NotFoundError(Exception):
	""" The response is a redirection to the not found page. """

	def __init__(self):
		super().__init__("Page not found.")

class ForbiddenError(Exception):
	""" The response is a redirection to the forbidden page. """

	def __init__(self):
		super().__init__("Access to this page was denied.")

# ---
# Other utilities.
# ---

class Pagination:
	def __init__(self, current, number, more):
		self.current = current
		self.number = number
		self.more = more

	def __repr__(self):
		p = (f"current = {repr(self.current)}",
			f"number = {repr(self.number)}", f"more = {repr(self.more)}")
		return f"{self.__class__.__name__}({', '.join(p)})"

# End of file.