Drop lots of legacy code. Support Python 3.7-3.11.
[librarian.git] / src / librarian / meta / types / wluri.py
1 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 import re
5 from .base import MetaValue
6
7
8 class WLURI(MetaValue):
9     """Represents a WL URI. Extracts slug from it."""
10     template = 'http://wolnelektury.pl/katalog/lektura/%s/'
11     _re_wl_uri = re.compile(
12         r'http://(www\.)?wolnelektury.pl/katalog/lektur[ay]/'
13         '(?P<slug>[-a-z0-9]+)/?$'
14     )
15
16     def __init__(self, slug, uri=None):
17         """Contructs an URI from slug.
18
19         >>> print(WLURI('a-slug').uri)
20         http://wolnelektury.pl/katalog/lektura/a-slug/
21
22         """
23         if uri is None:
24             uri = self.template % slug
25         self.uri = uri
26         return super().__init__(slug)
27
28     @classmethod
29     def from_text(cls, uri):
30         slug = uri.rstrip('/').rsplit('/', 1)[-1]
31         return cls(slug, uri)
32
33     def validate(self):
34         match = self._re_wl_uri.match(self.uri)
35         if not match:
36             raise ValidationError('Invalid URI (%s). Should match: %s' % (
37                         self.uri, self._re_wl_uri.pattern))
38
39     def __str__(self):
40         return self.uri
41
42     def __eq__(self, other):
43         return self.value == other.value
44
45     @property
46     def slug(self):
47         return self.value