Skip to content

Vultron ActivityStreams Vocabulary Base Package

vultron.as_vocab.base

Provides an implementation of the ActivityStreams 2.0 protocol.

activitystreams_activity(cls)

Register an activity for a given activity type.

Parameters:

Name Type Description Default
cls type

The class to register.

required

Returns:

Type Description
type

A decorator that registers the activity class.

Source code in vultron/as_vocab/base/__init__.py
43
44
45
46
47
48
49
50
51
52
53
54
def activitystreams_activity(cls: type) -> type:
    """Register an activity for a given activity type.

    Args:
        cls: The class to register.

    Returns:
        A decorator that registers the activity class.
    """
    key = cls.__name__.lstrip("as_")
    ACTIVITY_TYPES[key] = cls
    return cls

Register a link for a given link type.

Parameters:

Name Type Description Default
cls type

The class to register.

required

Returns:

Type Description
type

A decorator that registers the link class.

Source code in vultron/as_vocab/base/__init__.py
57
58
59
60
61
62
63
64
65
66
67
68
def activitystreams_link(cls: type) -> type:
    """Register a link for a given link type.

    Args:
        cls: The class to register.

    Returns:
        A decorator that registers the link class.
    """
    key = cls.__name__.lstrip("as_")
    LINK_TYPES[key] = cls
    return cls

activitystreams_object(cls)

Register an object for a given object type.

Parameters:

Name Type Description Default
cls type

The class to register.

required

Returns:

Type Description
type

A decorator that registers the object class.

Source code in vultron/as_vocab/base/__init__.py
29
30
31
32
33
34
35
36
37
38
39
40
def activitystreams_object(cls: type) -> type:
    """Register an object for a given object type.

    Args:
        cls: The class to register.

    Returns:
        A decorator that registers the object class.
    """
    key = cls.__name__.lstrip("as_")
    OBJECT_TYPES[key] = cls
    return cls

vultron.as_vocab.base.base

file: base author: adh created_at: 2/17/23 3:59 PM

Objects

Activities

Utilities

vultron.as_vocab.base.dt_utils

This module contains utilities for working with datetime objects.

days_from_now_utc(days=45)

Get a datetime object representing the current time plus the number of days specified.

Parameters:

Name Type Description Default
days int

The number of days to add to the current time

45

Returns:

Type Description
datetime

A datetime object representing the current time plus the number

datetime

of days specified

Source code in vultron/as_vocab/base/dt_utils.py
29
30
31
32
33
34
35
36
37
38
39
def days_from_now_utc(days: int = 45) -> datetime:
    """Get a datetime object representing the current time plus the number of days specified.

    Args:
        days: The number of days to add to the current time

    Returns:
        A datetime object representing the current time plus the number
        of days specified
    """
    return now_utc() + timedelta(days=days)

from_isofmt(datestring)

Decodes a string into a datetime object. If datestring isn't actually a string, but it is a datetime, or None, just return it.

Parameters:

Name Type Description Default
datestring str | datetime | None

an iso-formatted date time string

required

Returns:

Type Description
datetime

a datetime object

Source code in vultron/as_vocab/base/dt_utils.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def from_isofmt(datestring: str | datetime | None) -> datetime:
    """Decodes a string into a datetime object.
    If datestring isn't actually a string, but it is a datetime, or None, just return it.

    Args:
        datestring: an iso-formatted date time string

    Returns:
        a datetime object
    """
    if isinstance(datestring, str):
        return datetime.fromisoformat(datestring)
    if datestring is None or isinstance(datestring, datetime):
        return datestring

    raise IsoDecodingError(
        f"Can't convert {datestring} to datetime (or None.)"
    )

now_utc()

Get the current time in UTC at one second resolution

Returns:

Type Description
datetime

A timezone-aware datetime object representing the current time in UTC

Source code in vultron/as_vocab/base/dt_utils.py
42
43
44
45
46
47
48
def now_utc() -> datetime:
    """Get the current time in UTC at one second resolution

    Returns:
        A timezone-aware datetime object representing the current time in UTC
    """
    return datetime.now(pytz.UTC).replace(microsecond=0)

to_isofmt(dt)

Encodes a datetime object into a string. If dt isn't actually a datetime, but it is a string, or None, just return it.

Parameters:

Name Type Description Default
dt datetime | str | None

a datetime object, or a string, or None

required

Returns:

Type Description
str

an iso-formatted date time string if dt is a datetime, otherwise dt

Source code in vultron/as_vocab/base/dt_utils.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def to_isofmt(dt: datetime | str | None) -> str:
    """Encodes a datetime object into a string.
    If dt isn't actually a datetime, but it is a string, or None, just return it.

    Args:
        dt: a datetime object, or a string, or None

    Returns:
        an iso-formatted date time string if dt is a datetime, otherwise dt
    """
    if isinstance(dt, datetime):
        return datetime.isoformat(dt)
    if dt is None or isinstance(dt, str):
        return dt
    raise IsoEncodingError(f"Can't convert {dt} to string (or None.)")

vultron.as_vocab.base.utils

Provides utilities for the ActivityStreams Vocabulary.

exclude_if_empty(value)

Exclude a field if it is empty

Parameters:

Name Type Description Default
value any

The value to check

required

Returns:

Type Description
bool

True if the value is empty, False otherwise

Source code in vultron/as_vocab/base/utils.py
49
50
51
52
53
54
55
56
57
58
def exclude_if_empty(value: any) -> bool:
    """Exclude a field if it is empty

    Args:
        value: The value to check

    Returns:
        True if the value is empty, False otherwise
    """
    return len(value) == 0

exclude_if_none(value)

Exclude a field if it is None

Parameters:

Name Type Description Default
value any

The value to check

required

Returns:

Type Description
bool

True if the value is None, False otherwise

Source code in vultron/as_vocab/base/utils.py
37
38
39
40
41
42
43
44
45
46
def exclude_if_none(value: any) -> bool:
    """Exclude a field if it is None

    Args:
        value: The value to check

    Returns:
        True if the value is None, False otherwise
    """
    return value is None

generate_new_id()

Generate a new ID for an object

Returns:

Type Description
str

the new ID

Source code in vultron/as_vocab/base/utils.py
61
62
63
64
65
66
67
68
69
70
71
72
73
def generate_new_id() -> str:
    """Generate a new ID for an object

    Returns:
        the new ID
    """
    # The .example TLD is reserved for use in documentation and examples.
    # https://en.wikipedia.org/wiki/.example
    prefix = "https://for.example"
    random = str(uuid.uuid4())
    _id = f"{prefix}/{random}"

    return _id

name_of(obj)

Get the name of an object if it has one, otherwise return the object itself

Parameters:

Name Type Description Default
obj any

The object to get the name of

required

Returns:

Type Description
str

Either the name of the object or the object itself

Source code in vultron/as_vocab/base/utils.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def name_of(obj: any) -> str:
    """Get the name of an object if it has one, otherwise return the object itself

    Args:
        obj: The object to get the name of

    Returns:
        Either the name of the object or the object itself
    """

    try:
        return obj.name
    except AttributeError:
        return obj

print_activity_examples()

Print out empty examples of the classes in the given module

Source code in vultron/as_vocab/base/utils.py
94
95
96
97
98
99
def print_activity_examples():
    """Print out empty examples of the classes in the given module"""
    from vultron.as_vocab.base import VOCABULARY

    activity_types = VOCABULARY["activities"]
    _print_examples(activity_types)

Print out empty examples of the classes in the given module

Source code in vultron/as_vocab/base/utils.py
102
103
104
105
106
107
def print_link_examples():
    """Print out empty examples of the classes in the given module"""
    from vultron.as_vocab.base import VOCABULARY

    link_types = VOCABULARY["links"]
    _print_examples(link_types)

print_object_examples()

Print out empty examples of the classes in the given module

Source code in vultron/as_vocab/base/utils.py
86
87
88
89
90
91
def print_object_examples() -> None:
    """Print out empty examples of the classes in the given module"""
    from vultron.as_vocab.base import VOCABULARY

    object_types = VOCABULARY["objects"]
    _print_examples(object_types)

vultron.as_vocab.base.objects.utils

Provides Utility functions for the as_vocab.base.objects module

object_from_dict(data)

Create an object from the given json data. Figures out the type and creates the appropriate object.

Parameters:

Name Type Description Default
data dict

the json data

required

Returns:

Type Description
as_Base

an object that is a subclass of as_Base

Raises:

Type Description
MissingTypeError

if the type is missing

UnrecognizedTypeError

if the type is not recognized

UnrecognizedTypeError

if the type of any sub-object is not recognized

Source code in vultron/as_vocab/base/objects/utils.py
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
def object_from_dict(data: dict) -> as_Base:
    """Create an object from the given json data.
    Figures out the type and creates the appropriate object.

    Args:
        data: the json data

    Returns:
        an object that is a subclass of as_Base

    Raises:
        MissingTypeError: if the type is missing
        UnrecognizedTypeError: if the type is not recognized
        UnrecognizedTypeError: if the type of any sub-object is not
            recognized
    """
    obj = simple_object_from_dict(data)

    # todo should this be recursive instead?
    for attrib in ["actor", "as_object", "target", "origin"]:
        if hasattr(obj, attrib):
            data = getattr(obj, attrib)
            parsed = parse_sub_object(data)
            setattr(obj, attrib, parsed)

    return obj

simple_object_from_dict(data)

Get the object from the given json data

Parameters:

Name Type Description Default
data dict

the json data

required

Returns:

Type Description
as_Base

the object

Raises:

Type Description
MissingTypeError

if the type is missing

UnrecognizedTypeError

if the type is not recognized

Source code in vultron/as_vocab/base/objects/utils.py
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
def simple_object_from_dict(data: dict) -> as_Base:
    """
    Get the object from the given json data

    Args:
        data: the json data

    Returns:
        the object

    Raises:
        MissingTypeError: if the type is missing
        UnrecognizedTypeError: if the type is not recognized
    """
    try:
        obj_type = data["type"]
    except KeyError:
        logger.warning("Object type is missing in message")
        raise MissingTypeError("Missing type")

    # find the class that matches the type
    obj_cls = None

    for kind, classes in VOCABULARY.items():
        # ensure classes is not empty
        assert classes, f"Empty {kind} in vocabulary"

        logger.debug(f"Looking for {obj_type} in {kind}: {classes}")
        if obj_type in classes:
            obj_cls = classes[obj_type]
            # found it, we're done
            break

    if obj_cls is None:
        logger.warning(f"Unknown type: {obj_type}")
        raise UnrecognizedTypeError(f"Unrecognized object type")

    obj = obj_cls.from_dict(data, infer_missing=True)

    return obj

Errors

vultron.as_vocab.base.errors

file: errors author: adh created_at: 2/17/23 1:49 PM

ActivityVocabularyError

Bases: VultronError

Base class for all ActivityPub as_vocab errors.

Source code in vultron/as_vocab/base/errors.py
27
28
class ActivityVocabularyError(VultronError):
    """Base class for all ActivityPub as_vocab errors."""

DeserializationError

Bases: ActivityVocabularyError

Raised when a JSON object cannot be deserialized.

Source code in vultron/as_vocab/base/errors.py
52
53
class DeserializationError(ActivityVocabularyError):
    """Raised when a JSON object cannot be deserialized."""

IsoDecodingError

Bases: DeserializationError

Raised when an ISO decoding is not recognized.

Source code in vultron/as_vocab/base/errors.py
64
65
class IsoDecodingError(DeserializationError):
    """Raised when an ISO decoding is not recognized."""

IsoEncodingError

Bases: SerializationError

Raised when an ISO encoding is not recognized.

Source code in vultron/as_vocab/base/errors.py
41
42
class IsoEncodingError(SerializationError):
    """Raised when an ISO encoding is not recognized."""

MissingTypeError

Bases: DeserializationError

Raised when a type is missing from a JSON object.

Source code in vultron/as_vocab/base/errors.py
56
57
class MissingTypeError(DeserializationError):
    """Raised when a type is missing from a JSON object."""

SerializationError

Bases: ActivityVocabularyError

Raised when a JSON object cannot be serialized.

Source code in vultron/as_vocab/base/errors.py
37
38
class SerializationError(ActivityVocabularyError):
    """Raised when a JSON object cannot be serialized."""

UnrecognizedTypeError

Bases: DeserializationError

Raised when an unknown type is encountered.

Source code in vultron/as_vocab/base/errors.py
60
61
class UnrecognizedTypeError(DeserializationError):
    """Raised when an unknown type is encountered."""

vultron.as_vocab.base.objects.errors

file: errors author: adh created_at: 2/17/23 1:50 PM

ActivityVocabularyObjectError

Bases: ActivityVocabularyError

Base class for all ActivityPub object errors.

Source code in vultron/as_vocab/base/objects/errors.py
23
24
class ActivityVocabularyObjectError(ActivityVocabularyError):
    """Base class for all ActivityPub object errors."""

vultron.as_vocab.base.objects.activities.errors

file: errors author: adh created_at: 2/17/23 1:52 PM

ActivityVocabularyActivityError

Bases: ActivityVocabularyObjectError

Base class for all ActivityPub activity errors.

Source code in vultron/as_vocab/base/objects/activities/errors.py
25
26
class ActivityVocabularyActivityError(ActivityVocabularyObjectError):
    """Base class for all ActivityPub activity errors."""