Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ repos:
- python
- pyi
repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.6
rev: v0.14.10
- hooks:
- additional_dependencies:
- cryptography>=45.0.6
Expand All @@ -69,4 +69,4 @@ repos:
name: Pyrefly (type checking)
pass_filenames: false
repo: https://github.com/facebook/pyrefly-pre-commit
rev: 0.46.0
rev: 0.46.1
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 Fediverse for Python

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 1 addition & 1 deletion src/apmodel/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

def to_dict(obj: ActivityPubModel, **options) -> dict:
raw_data = obj.model_dump(
by_alias=True, exclude_none=True, exclude_unset=True, **options
by_alias=True, exclude_none=True, **options
)

master_context = LDContext()
Expand Down
4 changes: 2 additions & 2 deletions src/apmodel/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
commit_id: COMMIT_ID
__commit_id__: COMMIT_ID

__version__ = version = "0.4.5.post1.dev65+g293fe3589.d20251223"
__version_tuple__ = version_tuple = (0, 4, 5, "post1", "dev65", "g293fe3589.d20251223")
__version__ = version = '0.4.5.post1.dev74+gd8d92618f.d20251223'
__version_tuple__ = version_tuple = (0, 4, 5, 'post1', 'dev74', 'gd8d92618f.d20251223')

__commit_id__ = commit_id = None
21 changes: 3 additions & 18 deletions src/apmodel/extra/cid/data_integrity_proof.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from pydantic import Field, field_serializer, field_validator

from ...context import LDContext
from ...types import ActivityPubModel
from ...types import ActivityPubModel, ZDateTime


class DataIntegrityProof(ActivityPubModel):
Expand All @@ -24,7 +24,7 @@ class DataIntegrityProof(ActivityPubModel):
proof_value: str
proof_purpose: str
verification_method: str
created: str | datetime
created: str | ZDateTime

@field_validator("created", mode="before")
@classmethod
Expand All @@ -33,19 +33,4 @@ def convert_created_to_datetime(cls, v: str | datetime) -> datetime:
return datetime.fromisoformat(v.replace("Z", "+00:00"))
if isinstance(v, datetime):
return v
raise ValueError("created must be a string or a datetime object")

@field_serializer("created")
def serialize_created_to_iso_z(self, dt: datetime, _info) -> str:
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)

time_formatted = dt.astimezone(timezone.utc).isoformat(timespec="seconds")

if time_formatted.endswith("+00:00"):
return time_formatted.replace("+00:00", "Z")

if time_formatted.endswith("Z"):
return time_formatted

return time_formatted + "Z"
raise ValueError("created must be a string or a datetime object")
4 changes: 2 additions & 2 deletions src/apmodel/extra/cid/multikey.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def private_key(self):
return self._private_key

@public_key.setter
def set_public_key(
def public_key(
self,
key: ed25519.Ed25519PublicKey
| rsa.RSAPublicKey
Expand All @@ -59,7 +59,7 @@ def set_public_key(
self.public_key_multibase = _encode_public_key_as_multibase(key)

@private_key.setter
def set_private_key(
def private_key(
self, key: ed25519.Ed25519PrivateKey | rsa.RSAPrivateKey
) -> None:
self.secret_key_multibase = _encode_private_key_as_multibase(key)
17 changes: 15 additions & 2 deletions src/apmodel/types.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import Any, Dict, Optional, TypeVar
import datetime
from typing import Annotated, Any, Dict, Optional, TypeVar

from pydantic import (
BaseModel,
Expand All @@ -7,10 +8,20 @@
model_validator,
)
from pydantic.alias_generators import to_camel
from pydantic.functional_serializers import PlainSerializer
from typing_extensions import TypeAlias

from .context import LDContext

T = TypeVar("T", bound="ActivityPubModel")
ZDateTime: TypeAlias = Annotated[
datetime.datetime,
PlainSerializer(
lambda v: (
v if v.tzinfo else v.replace(tzinfo=datetime.timezone.utc)
).astimezone(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ").replace(".000000Z", "Z")
),
]


class ActivityPubModel(BaseModel):
Expand Down Expand Up @@ -71,7 +82,9 @@ def serialize_to_json_ld(self) -> Dict[str, Any]:

if aggregated_context:
if hasattr(item, "context") and item.context:
aggregated_context = aggregated_context + item.context
aggregated_context = (
aggregated_context + item.context
)
child_json.pop("@context", None)
processed_list.append(child_json)
else:
Expand Down
7 changes: 2 additions & 5 deletions src/apmodel/vocab/activity/question.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@
from ...core.activity import IntransitiveActivity
from ...core.link import Link
from ...core.object import Object
from ...types import ZDateTime


class Question(IntransitiveActivity):
type: Optional[str] = Field(default="Question", kw_only=True, frozen=True)
one_of: Optional[str | Object | Link | Dict[str, Any]] = Field(default=None)
any_of: Optional[str | Object | Link | Dict[str, Any]] = Field(default=None)
closed: Optional[
str | Object | Link | Dict[str, Any] | datetime.datetime | bool
str | Object | Link | Dict[str, Any] | ZDateTime | bool
] = Field(default=None)

@field_validator("one_of", mode="before")
Expand Down Expand Up @@ -50,9 +51,5 @@ def validate_closed(

return cast(Optional[str | Object | Link | Dict[str, Any]], load(v, "raw"))

@field_serializer("closed", when_used="always")
def serialize_closed(self, value: Any, _) -> str | bool | Any:
if isinstance(value, datetime.datetime):
return value.isoformat(timespec="seconds").replace("+00:00", "Z")

return value
15 changes: 4 additions & 11 deletions src/apmodel/vocab/tombstone.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@
from typing_extensions import Dict

from ..core.object import Object
from ..types import ZDateTime

DeletedTypes = Optional[datetime.datetime | str]
DeletedTypes = Optional[ZDateTime | str]


class Tombstone(Object):
type: Optional[str] = Field(default="Tombstone", kw_only=True, frozen=True)
former_type: Optional[str | Object | Dict[str, Any]] = Field(default=None)
deleted: Optional[datetime.datetime | str] = Field(default=None)
deleted: Optional[ZDateTime | str] = Field(default=None)

@field_validator("former_type", mode="before")
@classmethod
Expand All @@ -37,12 +38,4 @@ def parse_deleted_datetime(cls, v: Any) -> DeletedTypes:
except ValueError as e:
raise ValueError(
f"Invalid ISO 8601 format for 'deleted' field: {v}. Error: {e}"
)

@field_serializer("deleted", when_used="always")
def serialize_deleted_datetime(self, value: DeletedTypes, _) -> str | Any:
if isinstance(value, datetime.datetime):
iso_string = value.isoformat(timespec="seconds")
return iso_string.replace("+00:00", "Z")

return value
)
8 changes: 4 additions & 4 deletions tests/test_multikey.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def test_multikey_set_public_key_with_ed25519():
multikey = Multikey(id="did:example:123#key-1", controller="did:example:123")

# Set the public key
multikey.set_public_key = public_key
multikey.public_key = public_key

# Check that the multibase representation was set
assert multikey.public_key_multibase is not None
Expand All @@ -99,7 +99,7 @@ def test_multikey_set_public_key_with_rsa():
multikey = Multikey(id="did:example:123#key-1", controller="did:example:123")

# Set the public key
multikey.set_public_key = public_key
multikey.public_key = public_key

# Check that the multibase representation was set
assert multikey.public_key_multibase is not None
Expand All @@ -118,7 +118,7 @@ def test_multikey_set_public_key_with_private_key():
multikey = Multikey(id="did:example:123#key-1", controller="did:example:123")

# Set the public key using the private key (should extract the public key)
multikey.set_public_key = private_key
multikey.public_key = private_key

# Check that the multibase representation was set
assert multikey.public_key_multibase is not None
Expand All @@ -137,7 +137,7 @@ def test_multikey_set_private_key():
multikey = Multikey(id="did:example:123#key-1", controller="did:example:123")

# Set the private key
multikey.set_private_key = private_key
multikey.private_key = private_key

# Check that the multibase representation was set
assert multikey.secret_key_multibase is not None
Expand Down
3 changes: 2 additions & 1 deletion tests/test_tombstone.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import apmodel
import pytest
from datetime import datetime

Expand Down Expand Up @@ -118,7 +119,7 @@ def test_tombstone_serialization():
deleted="2023-01-01T12:00:00Z",
)

serialized = tombstone.model_dump(by_alias=True)
serialized = apmodel.to_dict(tombstone)

assert serialized["id"] == "http://example.com/object/1"
assert serialized["name"] == "Deleted Object"
Expand Down
Loading