summaryrefslogtreecommitdiff
path: root/archivist/prefixes.py
blob: 596feb025104ddd050bea8d250cb51e4b77f752b (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
prefixes = {}
registered = False

def register_prefixes():
    global registered
    if registered: return

    if not prefixes:
        _create_prefixes()
    
    for prefix in prefixes.values():
        prefix.get_or_create()

    registered = True

def _create_prefixes():
    from .model import Document
    
    FieldPseudoPrefix('direction', 'In- or outgoing', Document.direction)
    FieldPseudoPrefix('date', 'Date of creation', Document.created)
    FieldPseudoPrefix('mime', 'Mime Type', Document.file_type)
    
    for part in ('day', 'month', 'year'):
        FieldPartPseudoPrefix(part, part.capitalize() + ' of creation', Document.created, part)

def query_pseudo_prefix(prefix, value):
    register_prefixes()

    if prefix in prefixes:
        return prefixes[prefix].as_query(value)
    return None

def is_pseudo_prefix(prefix):
    register_prefixes()
    return prefix in prefixes

class PseudoPrefix:
    def __init__(self, name, description, accessor):
        self.name = name
        self.accessor = accessor
        self.description = description
        prefixes[name] = self

    def get_or_create(self):
        from .model import Prefix
        return Prefix.get_or_create(name = self.name, defaults={
            'description' : self.description, 
            'virtual' : True})

    def check_for(self, document, value):
        return self.accessor(document) == value

    def as_query(self, value):
        raise NotImplementedError

class FieldPseudoPrefix(PseudoPrefix):
    def __init__(self, name, description, field):
        self._field = field
        super().__init__(name, description, lambda doc: getattr(doc, field.name))

    def as_query(self, value):
        return self._field == value

class FieldPartPseudoPrefix(PseudoPrefix):
    def __init__(self, name, description, field, part):
        self._field = field
        self._field_part = getattr(field, part)
        super().__init__(name, description, lambda doc: getattr(getattr(doc, field.name), part))

    def as_query(self, value):
        return self._field_part == value