aboutsummaryrefslogtreecommitdiffstats
path: root/bsie/matcher/default_matcher.py
blob: 94bbe2cfdfb9c30118e4750a8c404ee4fc8c1543 (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

# standard imports
import os
import typing
import urllib

# bsie imports
from bsie.utils import bsfs

# inner-module imports
from . import nodes
from .matcher import Matcher

# exports
__all__: typing.Sequence[str] = (
    'DefaultMatcher',
    )


## code ##

class DefaultMatcher(Matcher):
    """Compose URIs as <host/user/node_type#fragment>

    What information is used as fragment depends on the node type.
    Typically, the default is to use the "ucid" hint.
    The fallback in all cases is to generate a random uuid.

    Never changes previously assigned uris. Sets uris in-place.

    """

    def __init__(
            self,
            host: bsfs.URI,
            user: str,
            ):
        self._prefix = bsfs.Namespace(os.path.join(host, user))

    def match_node(self, node: nodes.Node) -> nodes.Node:
        if node.uri is not None:
            return node
        if isinstance(node, nodes.Entity):
            return self.match_entity(node)
        if isinstance(node, nodes.Preview):
            return self.match_preview(node)
        if isinstance(node, nodes.Tag):
            return self.match_tag(node)
        if isinstance(node, nodes.Face):
            return self.match_face(node)
        raise ValueError(f'no matching policy available for bsfs.typename{node}')

    def match_entity(self, node: nodes.Entity) -> nodes.Entity:
        """Set a bsn:Entity node's uri fragment to its ucid."""
        node.uri = getattr(self._prefix.file(), node.ucid)
        return node

    def match_preview(self, node: nodes.Preview) -> nodes.Preview:
        """Set a bsn:Preview node's uri fragment to its ucid and size suffix."""
        fragment = node.ucid + '_s' + str(node.size)
        node.uri = getattr(self._prefix.preview(), fragment)
        return node

    def match_tag(self, node: nodes.Tag) -> nodes.Tag:
        """Set a bsn:Tag node's uri to its label."""
        # FIXME: match to existing tags in bsfs storage?!
        fragment = urllib.parse.quote(node.label)
        node.uri = getattr(self._prefix.tag(), fragment)
        return node

    def match_face(self, node: nodes.Face) -> nodes.Face:
        """Set a bsn:Face node's uri to its ucid."""
        node.uri = getattr(self._prefix.face(), node.ucid)
        return node

## EOF ##