Skip to content

Activity

Bases: Object

Source code in libs/apmodel/src/apmodel/core.py
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
class Activity(Object):
    def __init__(
        self,
        type: str = "Activity",
        id: Optional[str] = None,
        actor: Optional[Union[Object, Link, str, dict]] = None,
        object: Optional[Union[Object, dict]] = None,
        target: Optional[Union[Object, Link]] = None,
        result: Optional[Union[Object, Link]] = None,
        origin: Optional[Union[Object, Link]] = None,
        instrument: Optional[Union[Object, Link]] = None,
        proof: Union[DataIntegrityProof, dict] = {},
        **kwargs,
    ):
        """Represents an Activity object in Activity Streams 2.0.

        The Activity class is used to express an action or event that occurs in a 
        social context. It encapsulates various properties that describe the 
        activity, including the actor, the object acted upon, and other related 
        entities.

        Args:
            type (str, optional): 
                The type of the object. For this class, it is always "Activity". 
                Defaults to "Activity".
            id (Optional[str], optional): 
                A unique identifier for the activity. If not provided, a UUID 
                will be generated. Defaults to None.
            actor (Optional[Union[Object, Link, str, dict]], optional): 
                The entity that is performing the activity. This can be an 
                Object, a Link, a string representing an identifier, or a 
                dictionary containing the entity's data. Defaults to None.
            object (Optional[Union[Object, dict]], optional): 
                The object that is the target of the activity. This can be an 
                Object or a dictionary. Defaults to None.
            target (Optional[Union[Object, Link]], optional): 
                The entity that the activity is directed towards. This can be 
                an Object or a Link. Defaults to None.
            result (Optional[Union[Object, Link]], optional): 
                The result of the activity. This can be an Object or a Link 
                that represents the outcome of the activity. Defaults to None.
            origin (Optional[Union[Object, Link]], optional): 
                The source of the activity, indicating where it originated. 
                This can be an Object or a Link. Defaults to None.
            instrument (Optional[Union[Object, Link]], optional): 
                The tool or means used to perform the activity. This can be 
                an Object or a Link. Defaults to None.
            proof (Union[DataIntegrityProof, dict], optional): 
                A proof of the integrity of the activity data, represented 
                as a DataIntegrityProof object or a dictionary. Defaults to 
                an empty list.
            **kwargs: 
                Additional properties that can be added to the Activity 
                object, allowing for extensibility.

        Note:
            Other values are inherited from apmodel.Object.

        Raises:
            ValueError: 
                If the proof is not a valid DataIntegrityProof object or 
                dictionary.

        """
        from .loader import load

        super().__init__(type="Activity", content=None)
        self.type = type
        self.id = id if id else str(uuid.uuid4())
        self.published = (
            datetime.utcnow().isoformat(timespec='microseconds').replace('+00:00', 'Z')
            if not kwargs.get("published")
            else datetime.datetime.datetime.strptime(
                kwargs.get("published"), "%Y-%m-%dT%H:%M:%S.%fZ"
            )
        )
        self.actor = load(actor) if isinstance(actor, dict) else actor
        self.object = load(object) if isinstance(object, dict) else object
        self.target = target
        self.result = result
        self.origin = origin
        self.instrument = instrument
        self.proof: Optional[DataIntegrityProof] = (load(proof) if isinstance(proof, dict) else proof) if proof != {} else None
        self._extras = {}
        for key, value in kwargs.items():
            self._extras[key] = value

    def accept(self, actor: Object | Link | str):
        obj = self.to_dict(self._extras)
        return _make_accept(obj, actor)

    def reject(self, actor: Object | Link | str):
        obj = self.to_dict(self._extras)
        return _make_reject(obj, actor)

    def to_dict(self, _extras: Optional[dict] = None) -> dict:
        """Outputs the current object as a dictionary.

        Args:
            _extras (Optional[dict], optional): Arguments used internally. It is not recommended that users change them.

        Returns:
            dict: Objects converted to dictionaries
        """
        data = super().to_dict()
        data["@context"] = ["https://www.w3.org/ns/activitystreams", "https://w3id.org/security/data-integrity/v1"]

        if self.type:
            data["type"] = self.type
        if self.actor:
            data["actor"] = (
                self.actor.to_dict()
                if isinstance(self.actor, Object)
                else str(self.actor)
            )
        if self.object:
            data["object"] = (
                self.object.to_dict()
                if isinstance(self.object, Object)
                else str(self.object)
            )
        if self.target:
            data["target"] = (
                self.target.to_dict()
                if isinstance(self.target, Object)
                else str(self.target)
            )
        if self.proof:
            data["proof"] = (
                self.target.to_dict()
                if isinstance(self.proof, DataIntegrityProof)
                else self.proof
            )

        return data

__init__(type='Activity', id=None, actor=None, object=None, target=None, result=None, origin=None, instrument=None, proof={}, **kwargs)

Represents an Activity object in Activity Streams 2.0.

The Activity class is used to express an action or event that occurs in a social context. It encapsulates various properties that describe the activity, including the actor, the object acted upon, and other related entities.

Parameters:

Name Type Description Default
type str

The type of the object. For this class, it is always "Activity". Defaults to "Activity".

'Activity'
id Optional[str]

A unique identifier for the activity. If not provided, a UUID will be generated. Defaults to None.

None
actor Optional[Union[Object, Link, str, dict]]

The entity that is performing the activity. This can be an Object, a Link, a string representing an identifier, or a dictionary containing the entity's data. Defaults to None.

None
object Optional[Union[Object, dict]]

The object that is the target of the activity. This can be an Object or a dictionary. Defaults to None.

None
target Optional[Union[Object, Link]]

The entity that the activity is directed towards. This can be an Object or a Link. Defaults to None.

None
result Optional[Union[Object, Link]]

The result of the activity. This can be an Object or a Link that represents the outcome of the activity. Defaults to None.

None
origin Optional[Union[Object, Link]]

The source of the activity, indicating where it originated. This can be an Object or a Link. Defaults to None.

None
instrument Optional[Union[Object, Link]]

The tool or means used to perform the activity. This can be an Object or a Link. Defaults to None.

None
proof Union[DataIntegrityProof, dict]

A proof of the integrity of the activity data, represented as a DataIntegrityProof object or a dictionary. Defaults to an empty list.

{}
**kwargs

Additional properties that can be added to the Activity object, allowing for extensibility.

{}
Note

Other values are inherited from apmodel.Object.

Raises:

Type Description
ValueError

If the proof is not a valid DataIntegrityProof object or dictionary.

Source code in libs/apmodel/src/apmodel/core.py
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
def __init__(
    self,
    type: str = "Activity",
    id: Optional[str] = None,
    actor: Optional[Union[Object, Link, str, dict]] = None,
    object: Optional[Union[Object, dict]] = None,
    target: Optional[Union[Object, Link]] = None,
    result: Optional[Union[Object, Link]] = None,
    origin: Optional[Union[Object, Link]] = None,
    instrument: Optional[Union[Object, Link]] = None,
    proof: Union[DataIntegrityProof, dict] = {},
    **kwargs,
):
    """Represents an Activity object in Activity Streams 2.0.

    The Activity class is used to express an action or event that occurs in a 
    social context. It encapsulates various properties that describe the 
    activity, including the actor, the object acted upon, and other related 
    entities.

    Args:
        type (str, optional): 
            The type of the object. For this class, it is always "Activity". 
            Defaults to "Activity".
        id (Optional[str], optional): 
            A unique identifier for the activity. If not provided, a UUID 
            will be generated. Defaults to None.
        actor (Optional[Union[Object, Link, str, dict]], optional): 
            The entity that is performing the activity. This can be an 
            Object, a Link, a string representing an identifier, or a 
            dictionary containing the entity's data. Defaults to None.
        object (Optional[Union[Object, dict]], optional): 
            The object that is the target of the activity. This can be an 
            Object or a dictionary. Defaults to None.
        target (Optional[Union[Object, Link]], optional): 
            The entity that the activity is directed towards. This can be 
            an Object or a Link. Defaults to None.
        result (Optional[Union[Object, Link]], optional): 
            The result of the activity. This can be an Object or a Link 
            that represents the outcome of the activity. Defaults to None.
        origin (Optional[Union[Object, Link]], optional): 
            The source of the activity, indicating where it originated. 
            This can be an Object or a Link. Defaults to None.
        instrument (Optional[Union[Object, Link]], optional): 
            The tool or means used to perform the activity. This can be 
            an Object or a Link. Defaults to None.
        proof (Union[DataIntegrityProof, dict], optional): 
            A proof of the integrity of the activity data, represented 
            as a DataIntegrityProof object or a dictionary. Defaults to 
            an empty list.
        **kwargs: 
            Additional properties that can be added to the Activity 
            object, allowing for extensibility.

    Note:
        Other values are inherited from apmodel.Object.

    Raises:
        ValueError: 
            If the proof is not a valid DataIntegrityProof object or 
            dictionary.

    """
    from .loader import load

    super().__init__(type="Activity", content=None)
    self.type = type
    self.id = id if id else str(uuid.uuid4())
    self.published = (
        datetime.utcnow().isoformat(timespec='microseconds').replace('+00:00', 'Z')
        if not kwargs.get("published")
        else datetime.datetime.datetime.strptime(
            kwargs.get("published"), "%Y-%m-%dT%H:%M:%S.%fZ"
        )
    )
    self.actor = load(actor) if isinstance(actor, dict) else actor
    self.object = load(object) if isinstance(object, dict) else object
    self.target = target
    self.result = result
    self.origin = origin
    self.instrument = instrument
    self.proof: Optional[DataIntegrityProof] = (load(proof) if isinstance(proof, dict) else proof) if proof != {} else None
    self._extras = {}
    for key, value in kwargs.items():
        self._extras[key] = value

to_dict(_extras=None)

Outputs the current object as a dictionary.

Parameters:

Name Type Description Default
_extras Optional[dict]

Arguments used internally. It is not recommended that users change them.

None

Returns:

Name Type Description
dict dict

Objects converted to dictionaries

Source code in libs/apmodel/src/apmodel/core.py
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
def to_dict(self, _extras: Optional[dict] = None) -> dict:
    """Outputs the current object as a dictionary.

    Args:
        _extras (Optional[dict], optional): Arguments used internally. It is not recommended that users change them.

    Returns:
        dict: Objects converted to dictionaries
    """
    data = super().to_dict()
    data["@context"] = ["https://www.w3.org/ns/activitystreams", "https://w3id.org/security/data-integrity/v1"]

    if self.type:
        data["type"] = self.type
    if self.actor:
        data["actor"] = (
            self.actor.to_dict()
            if isinstance(self.actor, Object)
            else str(self.actor)
        )
    if self.object:
        data["object"] = (
            self.object.to_dict()
            if isinstance(self.object, Object)
            else str(self.object)
        )
    if self.target:
        data["target"] = (
            self.target.to_dict()
            if isinstance(self.target, Object)
            else str(self.target)
        )
    if self.proof:
        data["proof"] = (
            self.target.to_dict()
            if isinstance(self.proof, DataIntegrityProof)
            else self.proof
        )

    return data

Link

Source code in libs/apmodel/src/apmodel/core.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
class Link:
    def __init__(
        self,
        _context: Union[str, list] = "https://www.w3.org/ns/activitystreams",
        type: str = "Link",
        id: Optional[str] = None,
        href: Optional[str] = None,
        rel: Optional[list[str]] = None,
        mediaType: Optional[str] = None,
        name: Optional[str] = None,
        hreflang: Optional[str] = None,
        height: Optional[int] = None,
        width: Optional[int] = None,
        preview: Optional[Union[Object, "Link"]] = None,
        **kwargs,
    ):
        """Represents a Link object in Activity Streams 2.0.

        This class implements the Link type, which is used to represent 
        a hyperlink to a resource. The Link object can contain various 
        attributes that provide metadata about the link.

        Args:
            _context (Union[str, list], optional): 
                The default value for @context. It can be a string 
                or a list of strings. Defaults to "https://www.w3.org/ns/activitystreams".
            type (str, optional): 
                The type of the object. For this class, it is always "Link". 
                Defaults to "Link".
            id (Optional[str], optional): 
                A unique identifier for the link object. 
                This can be a URL or an IRI. Defaults to None.
            href (Optional[str], optional): 
                The URL that the link points to. It must conform to 
                the xsd:anyURI format. If provided, it must be a valid URI. 
                Defaults to None.
            rel (Optional[list[str]], optional): 
                A list of relationship types indicating the nature 
                of the link with respect to the context of the link. 
                Defaults to None.
            mediaType (Optional[str], optional): 
                The media type of the linked resource, such as 
                "image/jpeg". Defaults to None.
            name (Optional[str], optional): 
                A human-readable name for the link. Defaults to None.
            hreflang (Optional[str], optional): 
                The language of the linked resource, represented 
                as a language tag. Defaults to None.
            height (Optional[int], optional): 
                The height of the linked resource in pixels. 
                Must be greater than or equal to 0. Defaults to None.
            width (Optional[int], optional): 
                The width of the linked resource in pixels. 
                Must be greater than or equal to 0. Defaults to None.
            preview (Optional[Union["Object", "Link"]], optional): 
                A resource that provides a preview of the linked 
                content, which could be another Link or an Object. 
                Defaults to None.
            **kwargs: 
                Additional properties that can be added to the Link 
                object, allowing for extensibility.

        Raises:
            ValueError: 
                If `href` is not a valid URI, if `height` is negative, 
                or if `width` is negative.

        """
        if href:
            if not re.fullmatch(r"(%(?![0-9A-F]{2})|#.*#)", href):
                raise ValueError("href must be xsd:anyURI")
        if height:
            if height < 0:
                raise ValueError("height must be greater than or equal to 0")
        if width:
            if width < 0:
                raise ValueError("width must be greater than or equal to 0")
        ctx = kwargs.get("@context")
        self._context = merge_contexts(_context, ctx) if ctx else []
        self.type = type
        self.id = id
        self.href = href
        self.rel = rel
        self.media_type = mediaType
        self.name = name
        self.hreflang = hreflang
        self.height = height
        self.preview = preview
        self._extras = {}
        for key, value in kwargs.items():
            self._extras[key] = value

    def to_dict(self, _extras: Optional[dict] = None, build_context: bool = True):
        """Outputs the current object as a dictionary.

        Args:
            _extras (Optional[dict], optional): Arguments used internally. It is not recommended that users change them.
            build_context (bool): Do we automatically build @context based on the arguments? Defaults to False.

        Returns:
            dict: Objects converted to dictionaries
        """
        if not _extras:
            _extras = self._extras.copy()
        instance_vars = vars(self).copy()

        ctx = self._context.copy()
        context = instance_vars.get("@context")

        if build_context:
            attrs = dir(self)

            ctx2 = []
            ctx2_d = {}
            if _extras.get("publicKey") or "publicKey" in attrs:
                ctx2.append("https://w3id.org/security/v1")

            # Mastodon
            if _extras.get("featured") or "featured" in attrs:
                ctx2_d["featured"] = {
                    "@id": "http://joinmastodon.org/ns#featured",
                    "@type": "@id",
                }
            if _extras.get("featuredTags") or "featuredTags" in attrs:
                ctx2_d["featuredTags"] = {
                    "@id": "http://joinmastodon.org/ns#featuredTags",
                    "@type": "@id",
                }
            if _extras.get("discoverable") or "discoverable" in attrs:
                if not ctx2_d.get("toot"):
                    ctx2_d["toot"] = "http://joinmastodon.org/ns#"
                ctx2_d["discoverable"] = "toot:discoverable"
            if _extras.get("discoverable") or "discoverable" in attrs:
                if not ctx2_d.get("toot"):
                    ctx2_d["toot"] = "http://joinmastodon.org/ns#"
                ctx2_d["discoverable"] = "toot:discoverable"
            if (
                _extras.get("manuallyApprovesFollowers")
                or "manuallyApprovesFollowers" in attrs
            ):
                ctx2_d["manuallyApprovesFollowers"] = "as:manuallyApprovesFollowers"

            # Misskey
            if (
                _extras.get("_misskey_content")
                or _extras.get("_misskey_summary")
                or _extras.get("_misskey_quote")
                or _extras.get("_misskey_reaction")
                or _extras.get("_misskey_votes")
                or _extras.get("_misskey_talk")
                or _extras.get("isCat")
                or _extras.get("_misskey_followedMessage")
                or _extras.get("_misskey_requireSigninToViewContents")
                or _extras.get("_misskey_makeNotesFollowersOnlyBefore")
                or _extras.get("_misskey_makeNotesHiddenBefore")
                or _extras.get("_misskey_license")
            ):
                if not ctx2_d.get("misskey"):
                    ctx2_d["misskey"] = "https://misskey-hub-net/ns#"

            ctx2.append(ctx2_d)
        if context:
            context = merge_contexts(merge_contexts(ctx, context), ctx2)
        else:
            context = ctx
        data: Dict[str, Any] = {
            "@context": context,
        }
        for key, value in instance_vars.items():
            if value is not None:
                if not key.startswith("_") and key != "content":
                    if isinstance(value, datetime.datetime.datetime):
                        data[key] = value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
                    elif isinstance(value, Object):
                        data[key] = value.to_dict(_extras=value._extras)
                    elif isinstance(value, list):
                        data[key] = [
                            item.to_dict(_extras=item._extras)
                            if hasattr(item, "to_dict")
                            else item
                            for item in value
                        ]
                    elif (
                        isinstance(value, dict)
                        or isinstance(value, int)
                        or isinstance(value, bool)
                    ):
                        data[key] = value
                    else:
                        data[key] = str(value)

        _extras = _extras or {}
        for key, value in self._extras.items():
            if value is not None:
                if isinstance(value, datetime.datetime.datetime):
                    data[key] = value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
                elif isinstance(value, Object):
                    data[key] = value.to_dict(_extras=value._extras)
                elif isinstance(value, list):
                    data[key] = [
                        item.to_dict(_extras=item._extras)
                        if hasattr(item, "to_dict")
                        else item
                        for item in value
                    ]
                elif (
                    isinstance(value, dict)
                    or isinstance(value, int)
                    or isinstance(value, bool)
                ):
                    data[key] = value
                else:
                    data[key] = str(value)
        return data

__init__(_context='https://www.w3.org/ns/activitystreams', type='Link', id=None, href=None, rel=None, mediaType=None, name=None, hreflang=None, height=None, width=None, preview=None, **kwargs)

Represents a Link object in Activity Streams 2.0.

This class implements the Link type, which is used to represent a hyperlink to a resource. The Link object can contain various attributes that provide metadata about the link.

Parameters:

Name Type Description Default
_context Union[str, list]

The default value for @context. It can be a string or a list of strings. Defaults to "https://www.w3.org/ns/activitystreams".

'https://www.w3.org/ns/activitystreams'
type str

The type of the object. For this class, it is always "Link". Defaults to "Link".

'Link'
id Optional[str]

A unique identifier for the link object. This can be a URL or an IRI. Defaults to None.

None
href Optional[str]

The URL that the link points to. It must conform to the xsd:anyURI format. If provided, it must be a valid URI. Defaults to None.

None
rel Optional[list[str]]

A list of relationship types indicating the nature of the link with respect to the context of the link. Defaults to None.

None
mediaType Optional[str]

The media type of the linked resource, such as "image/jpeg". Defaults to None.

None
name Optional[str]

A human-readable name for the link. Defaults to None.

None
hreflang Optional[str]

The language of the linked resource, represented as a language tag. Defaults to None.

None
height Optional[int]

The height of the linked resource in pixels. Must be greater than or equal to 0. Defaults to None.

None
width Optional[int]

The width of the linked resource in pixels. Must be greater than or equal to 0. Defaults to None.

None
preview Optional[Union[Object, Link]]

A resource that provides a preview of the linked content, which could be another Link or an Object. Defaults to None.

None
**kwargs

Additional properties that can be added to the Link object, allowing for extensibility.

{}

Raises:

Type Description
ValueError

If href is not a valid URI, if height is negative, or if width is negative.

Source code in libs/apmodel/src/apmodel/core.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
def __init__(
    self,
    _context: Union[str, list] = "https://www.w3.org/ns/activitystreams",
    type: str = "Link",
    id: Optional[str] = None,
    href: Optional[str] = None,
    rel: Optional[list[str]] = None,
    mediaType: Optional[str] = None,
    name: Optional[str] = None,
    hreflang: Optional[str] = None,
    height: Optional[int] = None,
    width: Optional[int] = None,
    preview: Optional[Union[Object, "Link"]] = None,
    **kwargs,
):
    """Represents a Link object in Activity Streams 2.0.

    This class implements the Link type, which is used to represent 
    a hyperlink to a resource. The Link object can contain various 
    attributes that provide metadata about the link.

    Args:
        _context (Union[str, list], optional): 
            The default value for @context. It can be a string 
            or a list of strings. Defaults to "https://www.w3.org/ns/activitystreams".
        type (str, optional): 
            The type of the object. For this class, it is always "Link". 
            Defaults to "Link".
        id (Optional[str], optional): 
            A unique identifier for the link object. 
            This can be a URL or an IRI. Defaults to None.
        href (Optional[str], optional): 
            The URL that the link points to. It must conform to 
            the xsd:anyURI format. If provided, it must be a valid URI. 
            Defaults to None.
        rel (Optional[list[str]], optional): 
            A list of relationship types indicating the nature 
            of the link with respect to the context of the link. 
            Defaults to None.
        mediaType (Optional[str], optional): 
            The media type of the linked resource, such as 
            "image/jpeg". Defaults to None.
        name (Optional[str], optional): 
            A human-readable name for the link. Defaults to None.
        hreflang (Optional[str], optional): 
            The language of the linked resource, represented 
            as a language tag. Defaults to None.
        height (Optional[int], optional): 
            The height of the linked resource in pixels. 
            Must be greater than or equal to 0. Defaults to None.
        width (Optional[int], optional): 
            The width of the linked resource in pixels. 
            Must be greater than or equal to 0. Defaults to None.
        preview (Optional[Union["Object", "Link"]], optional): 
            A resource that provides a preview of the linked 
            content, which could be another Link or an Object. 
            Defaults to None.
        **kwargs: 
            Additional properties that can be added to the Link 
            object, allowing for extensibility.

    Raises:
        ValueError: 
            If `href` is not a valid URI, if `height` is negative, 
            or if `width` is negative.

    """
    if href:
        if not re.fullmatch(r"(%(?![0-9A-F]{2})|#.*#)", href):
            raise ValueError("href must be xsd:anyURI")
    if height:
        if height < 0:
            raise ValueError("height must be greater than or equal to 0")
    if width:
        if width < 0:
            raise ValueError("width must be greater than or equal to 0")
    ctx = kwargs.get("@context")
    self._context = merge_contexts(_context, ctx) if ctx else []
    self.type = type
    self.id = id
    self.href = href
    self.rel = rel
    self.media_type = mediaType
    self.name = name
    self.hreflang = hreflang
    self.height = height
    self.preview = preview
    self._extras = {}
    for key, value in kwargs.items():
        self._extras[key] = value

to_dict(_extras=None, build_context=True)

Outputs the current object as a dictionary.

Parameters:

Name Type Description Default
_extras Optional[dict]

Arguments used internally. It is not recommended that users change them.

None
build_context bool

Do we automatically build @context based on the arguments? Defaults to False.

True

Returns:

Name Type Description
dict

Objects converted to dictionaries

Source code in libs/apmodel/src/apmodel/core.py
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
def to_dict(self, _extras: Optional[dict] = None, build_context: bool = True):
    """Outputs the current object as a dictionary.

    Args:
        _extras (Optional[dict], optional): Arguments used internally. It is not recommended that users change them.
        build_context (bool): Do we automatically build @context based on the arguments? Defaults to False.

    Returns:
        dict: Objects converted to dictionaries
    """
    if not _extras:
        _extras = self._extras.copy()
    instance_vars = vars(self).copy()

    ctx = self._context.copy()
    context = instance_vars.get("@context")

    if build_context:
        attrs = dir(self)

        ctx2 = []
        ctx2_d = {}
        if _extras.get("publicKey") or "publicKey" in attrs:
            ctx2.append("https://w3id.org/security/v1")

        # Mastodon
        if _extras.get("featured") or "featured" in attrs:
            ctx2_d["featured"] = {
                "@id": "http://joinmastodon.org/ns#featured",
                "@type": "@id",
            }
        if _extras.get("featuredTags") or "featuredTags" in attrs:
            ctx2_d["featuredTags"] = {
                "@id": "http://joinmastodon.org/ns#featuredTags",
                "@type": "@id",
            }
        if _extras.get("discoverable") or "discoverable" in attrs:
            if not ctx2_d.get("toot"):
                ctx2_d["toot"] = "http://joinmastodon.org/ns#"
            ctx2_d["discoverable"] = "toot:discoverable"
        if _extras.get("discoverable") or "discoverable" in attrs:
            if not ctx2_d.get("toot"):
                ctx2_d["toot"] = "http://joinmastodon.org/ns#"
            ctx2_d["discoverable"] = "toot:discoverable"
        if (
            _extras.get("manuallyApprovesFollowers")
            or "manuallyApprovesFollowers" in attrs
        ):
            ctx2_d["manuallyApprovesFollowers"] = "as:manuallyApprovesFollowers"

        # Misskey
        if (
            _extras.get("_misskey_content")
            or _extras.get("_misskey_summary")
            or _extras.get("_misskey_quote")
            or _extras.get("_misskey_reaction")
            or _extras.get("_misskey_votes")
            or _extras.get("_misskey_talk")
            or _extras.get("isCat")
            or _extras.get("_misskey_followedMessage")
            or _extras.get("_misskey_requireSigninToViewContents")
            or _extras.get("_misskey_makeNotesFollowersOnlyBefore")
            or _extras.get("_misskey_makeNotesHiddenBefore")
            or _extras.get("_misskey_license")
        ):
            if not ctx2_d.get("misskey"):
                ctx2_d["misskey"] = "https://misskey-hub-net/ns#"

        ctx2.append(ctx2_d)
    if context:
        context = merge_contexts(merge_contexts(ctx, context), ctx2)
    else:
        context = ctx
    data: Dict[str, Any] = {
        "@context": context,
    }
    for key, value in instance_vars.items():
        if value is not None:
            if not key.startswith("_") and key != "content":
                if isinstance(value, datetime.datetime.datetime):
                    data[key] = value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
                elif isinstance(value, Object):
                    data[key] = value.to_dict(_extras=value._extras)
                elif isinstance(value, list):
                    data[key] = [
                        item.to_dict(_extras=item._extras)
                        if hasattr(item, "to_dict")
                        else item
                        for item in value
                    ]
                elif (
                    isinstance(value, dict)
                    or isinstance(value, int)
                    or isinstance(value, bool)
                ):
                    data[key] = value
                else:
                    data[key] = str(value)

    _extras = _extras or {}
    for key, value in self._extras.items():
        if value is not None:
            if isinstance(value, datetime.datetime.datetime):
                data[key] = value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
            elif isinstance(value, Object):
                data[key] = value.to_dict(_extras=value._extras)
            elif isinstance(value, list):
                data[key] = [
                    item.to_dict(_extras=item._extras)
                    if hasattr(item, "to_dict")
                    else item
                    for item in value
                ]
            elif (
                isinstance(value, dict)
                or isinstance(value, int)
                or isinstance(value, bool)
            ):
                data[key] = value
            else:
                data[key] = str(value)
    return data

Object

Source code in libs/apmodel/src/apmodel/core.py
 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
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
class Object:
    def __init__(
        self,
        _context: Union[str, list] = "https://www.w3.org/ns/activitystreams",
        type: str = "Object",
        id: Optional[str] = None,
        attachment: List[Union["Object", "Link", dict]] = [],
        attributedTo: Optional[Union["Object", "Link", str]] = None,
        audience: Optional[Union["Object", "Link"]] = None,
        content: Optional[str] = None,
        context: Optional[Union["Object", "Link"]] = None,
        name: Optional[str] = None,
        endTime: Optional[str] = None,
        generator: Optional[Union["Object", "Link"]] = None,
        icon: Optional[Union["Image", "Link"]] = None,
        image: Optional["Image"] = None,
        inReplyTo: Optional[Union["Image", "Link"]] = None,
        location: Optional[Union["Image", "Link"]] = None,
        preview: Optional[Union["Object", "Link"]] = None,
        published: Optional[str] = None,
        replies: Optional["Collection"] = None,
        startTime: Optional[str] = None,
        summary: Optional[str] = None,
        tag: Optional[Union["Object", "Link"]] = None,
        updated: Optional[str] = None,
        url: Optional[Union[str, "Link"]] = None,
        to: Optional[Union["Object", "Link"]] = None,
        bto: Optional[Union["Object", "Link"]] = None,
        cc: Optional[Union["Object", "Link"]] = None,
        bcc: Optional[Union["Object", "Link"]] = None,
        mediaType: Optional[str] = None,
        duration: Optional[str] = None,
        sensitive: Optional[bool] = None,
        **kwargs,
    ):
        """Implements the "Object" primary base type of the ActivityStreams vocabulary.

        Args:
            _context (Union[str, list], optional): 
                The default value for @context. Defaults to "https://www.w3.org/ns/activitystreams".
            type (str, optional): 
                The name of the ActivityStreams type. Usually does not need to be changed. Defaults to "Object".
            id (Optional[str], optional): 
                The identifier for the object. Defaults to None.
            attachment (List[Union["Object", "Link", dict]], optional): 
                A list of resources attached to the object. Defaults to an empty list.
            attributedTo (Optional[Union["Object", "Link", str]], optional): 
                The resource indicating the creator of this object. Defaults to None.
            audience (Optional[Union["Object", "Link"]], optional): 
                The resource indicating the intended audience of this object. Defaults to None.
            content (Optional[str], optional): 
                The text representing the content of the object. Defaults to None.
            context (Optional[Union["Object", "Link"]], optional): 
                The resource indicating the context of the object. Defaults to None.
            name (Optional[str], optional): 
                The name of the object. Defaults to None.
            endTime (Optional[str], optional): 
                The end time of the event represented as an ISO8601 formatted string. Defaults to None.
            generator (Optional[Union["Object", "Link"]], optional): 
                The resource indicating the application that generated the object. Defaults to None.
            icon (Optional[Union["Image", "Link"]], optional): 
                The resource for the icon of the object. Defaults to None.
            image (Optional["Image"], optional): 
                The resource for the image of the object. Defaults to None.
            inReplyTo (Optional[Union["Image", "Link"]], optional): 
                The resource indicating the target of this reply. Defaults to None.
            location (Optional[Union["Image", "Link"]], optional): 
                The resource indicating the location of the object. Defaults to None.
            preview (Optional[Union["Object", "Link"]], optional): 
                The resource for the preview of the object. Defaults to None.
            published (Optional[str], optional): 
                The date and time when the object was published, represented as an ISO8601 formatted string. Defaults to None.
            replies (Optional["Collection"], optional): 
                A collection of replies to this object. Defaults to None.
            startTime (Optional[str], optional): 
                The start time of the event represented as an ISO8601 formatted string. Defaults to None.
            summary (Optional[str], optional): 
                A summary of the object. Defaults to None.
            tag (Optional[Union["Object", "Link"]], optional): 
                The resource indicating tags related to the object. Defaults to None.
            updated (Optional[str], optional): 
                The date and time when the object was last updated, represented as an ISO8601 formatted string. Defaults to None.
            url (Optional[Union[str, "Link"]], optional): 
                The URL of the object. Defaults to None.
            to (Optional[Union["Object", "Link"]], optional): 
                The resource indicating the recipient of the object. Defaults to None.
            bto (Optional[Union["Object", "Link"]], optional): 
                The resource indicating BCC recipients. Defaults to None.
            cc (Optional[Union["Object", "Link"]], optional): 
                The resource indicating CC recipients. Defaults to None.
            bcc (Optional[Union["Object", "Link"]], optional): 
                The resource indicating BCC recipients. Defaults to None.
            mediaType (Optional[str], optional): 
                The media type of the object. Defaults to None.
            duration (Optional[str], optional): 
                A string representing the duration of the object. Defaults to None.
            sensitive (Optional[bool], optional): 
                A flag indicating the sensitivity of the content. Defaults to None.

        """
        from .loader import load

        ctx = kwargs.get("@context")
        self._context = merge_contexts(_context, ctx) if ctx else []
        self.type = type
        self.id = id
        self.attachment = [
            load(attach) if isinstance(attach, dict) else attach
            for attach in attachment
        ]
        self.attributedTo = (
            load(attributedTo)
            if isinstance(attributedTo, dict)
            else attributedTo
        )
        self.audience = (
            load(audience) if isinstance(audience, dict) else audience
        )
        self.content = content
        self.context = (
            load(context) if isinstance(context, dict) else context
        )
        self.name = name
        self.endTime = (
            (
                endTime
                if isinstance(endTime, datetime.datetime.datetime)
                else datetime.datetime.datetime.strptime(
                    endTime, "%Y-%m-%dT%H:%M:%S.%fZ"
                )
            )
            if endTime
            else endTime
        )
        self.generator = (
            load(generator) if isinstance(generator, dict) else generator
        )
        self.icon = load(icon) if isinstance(icon, dict) else icon
        self.image = image
        self.inReplyTo = (
            load(inReplyTo) if isinstance(inReplyTo, dict) else inReplyTo
        )
        self.location = (
            load(location) if isinstance(location, dict) else location
        )
        self.preview = (
            load(preview) if isinstance(preview, dict) else preview
        )
        if published:
            self.published = (
                (
                    published
                    if isinstance(published, datetime.datetime.datetime)
                    else datetime.datetime.datetime.strptime(
                        published, "%Y-%m-%dT%H:%M:%S.%fZ"
                    )
                )
                if published
                else published
            )
        else:
            self.published = datetime.utcnow()
        self.replies = (
            load(replies) if isinstance(replies, dict) else replies
        )
        self.startTime = (
            (
                startTime
                if isinstance(startTime, datetime.datetime.datetime)
                else datetime.datetime.datetime.strptime(
                    startTime, "%Y-%m-%dT%H:%M:%S.%fZ"
                )
            )
            if startTime
            else startTime
        )
        self.summary = summary
        self.tag = load(tag) if isinstance(tag, dict) else tag
        self.updated = updated
        self.url = load(url) if isinstance(url, dict) else url
        self.to = load(to) if isinstance(to, dict) else to
        self.bto = load(bto) if isinstance(bto, dict) else bto
        self.cc = load(cc) if isinstance(cc, dict) else cc
        self.bcc = load(bcc) if isinstance(bcc, dict) else bcc
        self.mediaType = mediaType
        self.duration = duration

        # --- Extend Value
        self.sensitive = sensitive
        # ---

        self._extras = {}
        for key, value in kwargs.items():
            self._extras[key] = value

    def to_dict(self, _extras: Optional[dict] = None, build_context: bool = True):
        """Outputs the current object as a dictionary.

        Args:
            _extras (Optional[dict], optional): Arguments used internally. It is not recommended that users change them.
            build_context (bool): Do we automatically build @context based on the arguments? Defaults to True.

        Returns:
            dict: Objects converted to dictionaries
        """
        if not _extras:
            _extras = self._extras.copy()
        instance_vars = vars(self).copy()

        ctx = self._context.copy()
        if build_context:
            attrs = dir(self)

            ctx2 = []
            ctx2_d = {}
            if _extras.get("publicKey") or "publicKey" in attrs:
                ctx2.append("https://w3id.org/security/v1")

            # Mastodon
            if _extras.get("featured") or "featured" in attrs:
                ctx2_d["featured"] = {
                    "@id": "http://joinmastodon.org/ns#featured",
                    "@type": "@id",
                }
            if _extras.get("featuredTags") or "featuredTags" in attrs:
                ctx2_d["featuredTags"] = {
                    "@id": "http://joinmastodon.org/ns#featuredTags",
                    "@type": "@id",
                }
            if _extras.get("discoverable") or "discoverable" in attrs:
                if not ctx2_d.get("toot"):
                    ctx2_d["toot"] = "http://joinmastodon.org/ns#"
                ctx2_d["discoverable"] = "toot:discoverable"
            if _extras.get("discoverable") or "discoverable" in attrs:
                if not ctx2_d.get("toot"):
                    ctx2_d["toot"] = "http://joinmastodon.org/ns#"
                ctx2_d["discoverable"] = "toot:discoverable"
            if (
                _extras.get("manuallyApprovesFollowers")
                or "manuallyApprovesFollowers" in attrs
            ):
                ctx2_d["manuallyApprovesFollowers"] = "as:manuallyApprovesFollowers"

            # Misskey
            if (
                _extras.get("_misskey_content")
                or _extras.get("_misskey_summary")
                or _extras.get("_misskey_quote")
                or _extras.get("_misskey_reaction")
                or _extras.get("_misskey_votes")
                or _extras.get("_misskey_talk")
                or _extras.get("isCat")
                or _extras.get("_misskey_followedMessage")
                or _extras.get("_misskey_requireSigninToViewContents")
                or _extras.get("_misskey_makeNotesFollowersOnlyBefore")
                or _extras.get("_misskey_makeNotesHiddenBefore")
                or _extras.get("_misskey_license")
            ):
                ctx2_d["misskey"] = "https://misskey-hub-net/ns#"

            ctx2.append(ctx2_d)

        context: Optional[list] = instance_vars.get("@context")
        if context:
            context = merge_contexts(merge_contexts(ctx, context), ctx2)
        else:
            context = ctx
        data: Dict[str, Any] = {
            "@context": context,
        }

        if self.content is not None:
            data["content"] = self.content

        for key, value in instance_vars.items():
            if value is not None:
                if not key.startswith("_") and key != "content":
                    if isinstance(value, datetime.datetime.datetime):
                        data[key] = value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
                    elif isinstance(value, Object):
                        data[key] = value.to_dict(_extras=value._extras)
                    elif isinstance(value, list):
                        data[key] = [
                            item.to_dict(_extras=item._extras)
                            if hasattr(item, "to_dict")
                            else item
                            for item in value
                        ]
                    elif (
                        isinstance(value, dict)
                        or isinstance(value, int)
                        or isinstance(value, bool)
                    ):
                        data[key] = value
                    else:
                        data[key] = str(value)

        _extras = _extras or {}
        for key, value in self._extras.items():
            if value is not None:
                if isinstance(value, datetime.datetime.datetime):
                    data[key] = value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
                elif isinstance(value, Object):
                    data[key] = value.to_dict(_extras=value._extras)
                elif isinstance(value, list):
                    data[key] = [
                        item.to_dict(_extras=item._extras)
                        if hasattr(item, "to_dict")
                        else item
                        for item in value
                    ]
                elif (
                    isinstance(value, dict)
                    or isinstance(value, int)
                    or isinstance(value, bool)
                ):
                    data[key] = value
                else:
                    data[key] = str(value)
        return data

__init__(_context='https://www.w3.org/ns/activitystreams', type='Object', id=None, attachment=[], attributedTo=None, audience=None, content=None, context=None, name=None, endTime=None, generator=None, icon=None, image=None, inReplyTo=None, location=None, preview=None, published=None, replies=None, startTime=None, summary=None, tag=None, updated=None, url=None, to=None, bto=None, cc=None, bcc=None, mediaType=None, duration=None, sensitive=None, **kwargs)

Implements the "Object" primary base type of the ActivityStreams vocabulary.

Parameters:

Name Type Description Default
_context Union[str, list]

The default value for @context. Defaults to "https://www.w3.org/ns/activitystreams".

'https://www.w3.org/ns/activitystreams'
type str

The name of the ActivityStreams type. Usually does not need to be changed. Defaults to "Object".

'Object'
id Optional[str]

The identifier for the object. Defaults to None.

None
attachment List[Union[Object, Link, dict]]

A list of resources attached to the object. Defaults to an empty list.

[]
attributedTo Optional[Union[Object, Link, str]]

The resource indicating the creator of this object. Defaults to None.

None
audience Optional[Union[Object, Link]]

The resource indicating the intended audience of this object. Defaults to None.

None
content Optional[str]

The text representing the content of the object. Defaults to None.

None
context Optional[Union[Object, Link]]

The resource indicating the context of the object. Defaults to None.

None
name Optional[str]

The name of the object. Defaults to None.

None
endTime Optional[str]

The end time of the event represented as an ISO8601 formatted string. Defaults to None.

None
generator Optional[Union[Object, Link]]

The resource indicating the application that generated the object. Defaults to None.

None
icon Optional[Union[Image, Link]]

The resource for the icon of the object. Defaults to None.

None
image Optional[Image]

The resource for the image of the object. Defaults to None.

None
inReplyTo Optional[Union[Image, Link]]

The resource indicating the target of this reply. Defaults to None.

None
location Optional[Union[Image, Link]]

The resource indicating the location of the object. Defaults to None.

None
preview Optional[Union[Object, Link]]

The resource for the preview of the object. Defaults to None.

None
published Optional[str]

The date and time when the object was published, represented as an ISO8601 formatted string. Defaults to None.

None
replies Optional[Collection]

A collection of replies to this object. Defaults to None.

None
startTime Optional[str]

The start time of the event represented as an ISO8601 formatted string. Defaults to None.

None
summary Optional[str]

A summary of the object. Defaults to None.

None
tag Optional[Union[Object, Link]]

The resource indicating tags related to the object. Defaults to None.

None
updated Optional[str]

The date and time when the object was last updated, represented as an ISO8601 formatted string. Defaults to None.

None
url Optional[Union[str, Link]]

The URL of the object. Defaults to None.

None
to Optional[Union[Object, Link]]

The resource indicating the recipient of the object. Defaults to None.

None
bto Optional[Union[Object, Link]]

The resource indicating BCC recipients. Defaults to None.

None
cc Optional[Union[Object, Link]]

The resource indicating CC recipients. Defaults to None.

None
bcc Optional[Union[Object, Link]]

The resource indicating BCC recipients. Defaults to None.

None
mediaType Optional[str]

The media type of the object. Defaults to None.

None
duration Optional[str]

A string representing the duration of the object. Defaults to None.

None
sensitive Optional[bool]

A flag indicating the sensitivity of the content. Defaults to None.

None
Source code in libs/apmodel/src/apmodel/core.py
 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
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def __init__(
    self,
    _context: Union[str, list] = "https://www.w3.org/ns/activitystreams",
    type: str = "Object",
    id: Optional[str] = None,
    attachment: List[Union["Object", "Link", dict]] = [],
    attributedTo: Optional[Union["Object", "Link", str]] = None,
    audience: Optional[Union["Object", "Link"]] = None,
    content: Optional[str] = None,
    context: Optional[Union["Object", "Link"]] = None,
    name: Optional[str] = None,
    endTime: Optional[str] = None,
    generator: Optional[Union["Object", "Link"]] = None,
    icon: Optional[Union["Image", "Link"]] = None,
    image: Optional["Image"] = None,
    inReplyTo: Optional[Union["Image", "Link"]] = None,
    location: Optional[Union["Image", "Link"]] = None,
    preview: Optional[Union["Object", "Link"]] = None,
    published: Optional[str] = None,
    replies: Optional["Collection"] = None,
    startTime: Optional[str] = None,
    summary: Optional[str] = None,
    tag: Optional[Union["Object", "Link"]] = None,
    updated: Optional[str] = None,
    url: Optional[Union[str, "Link"]] = None,
    to: Optional[Union["Object", "Link"]] = None,
    bto: Optional[Union["Object", "Link"]] = None,
    cc: Optional[Union["Object", "Link"]] = None,
    bcc: Optional[Union["Object", "Link"]] = None,
    mediaType: Optional[str] = None,
    duration: Optional[str] = None,
    sensitive: Optional[bool] = None,
    **kwargs,
):
    """Implements the "Object" primary base type of the ActivityStreams vocabulary.

    Args:
        _context (Union[str, list], optional): 
            The default value for @context. Defaults to "https://www.w3.org/ns/activitystreams".
        type (str, optional): 
            The name of the ActivityStreams type. Usually does not need to be changed. Defaults to "Object".
        id (Optional[str], optional): 
            The identifier for the object. Defaults to None.
        attachment (List[Union["Object", "Link", dict]], optional): 
            A list of resources attached to the object. Defaults to an empty list.
        attributedTo (Optional[Union["Object", "Link", str]], optional): 
            The resource indicating the creator of this object. Defaults to None.
        audience (Optional[Union["Object", "Link"]], optional): 
            The resource indicating the intended audience of this object. Defaults to None.
        content (Optional[str], optional): 
            The text representing the content of the object. Defaults to None.
        context (Optional[Union["Object", "Link"]], optional): 
            The resource indicating the context of the object. Defaults to None.
        name (Optional[str], optional): 
            The name of the object. Defaults to None.
        endTime (Optional[str], optional): 
            The end time of the event represented as an ISO8601 formatted string. Defaults to None.
        generator (Optional[Union["Object", "Link"]], optional): 
            The resource indicating the application that generated the object. Defaults to None.
        icon (Optional[Union["Image", "Link"]], optional): 
            The resource for the icon of the object. Defaults to None.
        image (Optional["Image"], optional): 
            The resource for the image of the object. Defaults to None.
        inReplyTo (Optional[Union["Image", "Link"]], optional): 
            The resource indicating the target of this reply. Defaults to None.
        location (Optional[Union["Image", "Link"]], optional): 
            The resource indicating the location of the object. Defaults to None.
        preview (Optional[Union["Object", "Link"]], optional): 
            The resource for the preview of the object. Defaults to None.
        published (Optional[str], optional): 
            The date and time when the object was published, represented as an ISO8601 formatted string. Defaults to None.
        replies (Optional["Collection"], optional): 
            A collection of replies to this object. Defaults to None.
        startTime (Optional[str], optional): 
            The start time of the event represented as an ISO8601 formatted string. Defaults to None.
        summary (Optional[str], optional): 
            A summary of the object. Defaults to None.
        tag (Optional[Union["Object", "Link"]], optional): 
            The resource indicating tags related to the object. Defaults to None.
        updated (Optional[str], optional): 
            The date and time when the object was last updated, represented as an ISO8601 formatted string. Defaults to None.
        url (Optional[Union[str, "Link"]], optional): 
            The URL of the object. Defaults to None.
        to (Optional[Union["Object", "Link"]], optional): 
            The resource indicating the recipient of the object. Defaults to None.
        bto (Optional[Union["Object", "Link"]], optional): 
            The resource indicating BCC recipients. Defaults to None.
        cc (Optional[Union["Object", "Link"]], optional): 
            The resource indicating CC recipients. Defaults to None.
        bcc (Optional[Union["Object", "Link"]], optional): 
            The resource indicating BCC recipients. Defaults to None.
        mediaType (Optional[str], optional): 
            The media type of the object. Defaults to None.
        duration (Optional[str], optional): 
            A string representing the duration of the object. Defaults to None.
        sensitive (Optional[bool], optional): 
            A flag indicating the sensitivity of the content. Defaults to None.

    """
    from .loader import load

    ctx = kwargs.get("@context")
    self._context = merge_contexts(_context, ctx) if ctx else []
    self.type = type
    self.id = id
    self.attachment = [
        load(attach) if isinstance(attach, dict) else attach
        for attach in attachment
    ]
    self.attributedTo = (
        load(attributedTo)
        if isinstance(attributedTo, dict)
        else attributedTo
    )
    self.audience = (
        load(audience) if isinstance(audience, dict) else audience
    )
    self.content = content
    self.context = (
        load(context) if isinstance(context, dict) else context
    )
    self.name = name
    self.endTime = (
        (
            endTime
            if isinstance(endTime, datetime.datetime.datetime)
            else datetime.datetime.datetime.strptime(
                endTime, "%Y-%m-%dT%H:%M:%S.%fZ"
            )
        )
        if endTime
        else endTime
    )
    self.generator = (
        load(generator) if isinstance(generator, dict) else generator
    )
    self.icon = load(icon) if isinstance(icon, dict) else icon
    self.image = image
    self.inReplyTo = (
        load(inReplyTo) if isinstance(inReplyTo, dict) else inReplyTo
    )
    self.location = (
        load(location) if isinstance(location, dict) else location
    )
    self.preview = (
        load(preview) if isinstance(preview, dict) else preview
    )
    if published:
        self.published = (
            (
                published
                if isinstance(published, datetime.datetime.datetime)
                else datetime.datetime.datetime.strptime(
                    published, "%Y-%m-%dT%H:%M:%S.%fZ"
                )
            )
            if published
            else published
        )
    else:
        self.published = datetime.utcnow()
    self.replies = (
        load(replies) if isinstance(replies, dict) else replies
    )
    self.startTime = (
        (
            startTime
            if isinstance(startTime, datetime.datetime.datetime)
            else datetime.datetime.datetime.strptime(
                startTime, "%Y-%m-%dT%H:%M:%S.%fZ"
            )
        )
        if startTime
        else startTime
    )
    self.summary = summary
    self.tag = load(tag) if isinstance(tag, dict) else tag
    self.updated = updated
    self.url = load(url) if isinstance(url, dict) else url
    self.to = load(to) if isinstance(to, dict) else to
    self.bto = load(bto) if isinstance(bto, dict) else bto
    self.cc = load(cc) if isinstance(cc, dict) else cc
    self.bcc = load(bcc) if isinstance(bcc, dict) else bcc
    self.mediaType = mediaType
    self.duration = duration

    # --- Extend Value
    self.sensitive = sensitive
    # ---

    self._extras = {}
    for key, value in kwargs.items():
        self._extras[key] = value

to_dict(_extras=None, build_context=True)

Outputs the current object as a dictionary.

Parameters:

Name Type Description Default
_extras Optional[dict]

Arguments used internally. It is not recommended that users change them.

None
build_context bool

Do we automatically build @context based on the arguments? Defaults to True.

True

Returns:

Name Type Description
dict

Objects converted to dictionaries

Source code in libs/apmodel/src/apmodel/core.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def to_dict(self, _extras: Optional[dict] = None, build_context: bool = True):
    """Outputs the current object as a dictionary.

    Args:
        _extras (Optional[dict], optional): Arguments used internally. It is not recommended that users change them.
        build_context (bool): Do we automatically build @context based on the arguments? Defaults to True.

    Returns:
        dict: Objects converted to dictionaries
    """
    if not _extras:
        _extras = self._extras.copy()
    instance_vars = vars(self).copy()

    ctx = self._context.copy()
    if build_context:
        attrs = dir(self)

        ctx2 = []
        ctx2_d = {}
        if _extras.get("publicKey") or "publicKey" in attrs:
            ctx2.append("https://w3id.org/security/v1")

        # Mastodon
        if _extras.get("featured") or "featured" in attrs:
            ctx2_d["featured"] = {
                "@id": "http://joinmastodon.org/ns#featured",
                "@type": "@id",
            }
        if _extras.get("featuredTags") or "featuredTags" in attrs:
            ctx2_d["featuredTags"] = {
                "@id": "http://joinmastodon.org/ns#featuredTags",
                "@type": "@id",
            }
        if _extras.get("discoverable") or "discoverable" in attrs:
            if not ctx2_d.get("toot"):
                ctx2_d["toot"] = "http://joinmastodon.org/ns#"
            ctx2_d["discoverable"] = "toot:discoverable"
        if _extras.get("discoverable") or "discoverable" in attrs:
            if not ctx2_d.get("toot"):
                ctx2_d["toot"] = "http://joinmastodon.org/ns#"
            ctx2_d["discoverable"] = "toot:discoverable"
        if (
            _extras.get("manuallyApprovesFollowers")
            or "manuallyApprovesFollowers" in attrs
        ):
            ctx2_d["manuallyApprovesFollowers"] = "as:manuallyApprovesFollowers"

        # Misskey
        if (
            _extras.get("_misskey_content")
            or _extras.get("_misskey_summary")
            or _extras.get("_misskey_quote")
            or _extras.get("_misskey_reaction")
            or _extras.get("_misskey_votes")
            or _extras.get("_misskey_talk")
            or _extras.get("isCat")
            or _extras.get("_misskey_followedMessage")
            or _extras.get("_misskey_requireSigninToViewContents")
            or _extras.get("_misskey_makeNotesFollowersOnlyBefore")
            or _extras.get("_misskey_makeNotesHiddenBefore")
            or _extras.get("_misskey_license")
        ):
            ctx2_d["misskey"] = "https://misskey-hub-net/ns#"

        ctx2.append(ctx2_d)

    context: Optional[list] = instance_vars.get("@context")
    if context:
        context = merge_contexts(merge_contexts(ctx, context), ctx2)
    else:
        context = ctx
    data: Dict[str, Any] = {
        "@context": context,
    }

    if self.content is not None:
        data["content"] = self.content

    for key, value in instance_vars.items():
        if value is not None:
            if not key.startswith("_") and key != "content":
                if isinstance(value, datetime.datetime.datetime):
                    data[key] = value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
                elif isinstance(value, Object):
                    data[key] = value.to_dict(_extras=value._extras)
                elif isinstance(value, list):
                    data[key] = [
                        item.to_dict(_extras=item._extras)
                        if hasattr(item, "to_dict")
                        else item
                        for item in value
                    ]
                elif (
                    isinstance(value, dict)
                    or isinstance(value, int)
                    or isinstance(value, bool)
                ):
                    data[key] = value
                else:
                    data[key] = str(value)

    _extras = _extras or {}
    for key, value in self._extras.items():
        if value is not None:
            if isinstance(value, datetime.datetime.datetime):
                data[key] = value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
            elif isinstance(value, Object):
                data[key] = value.to_dict(_extras=value._extras)
            elif isinstance(value, list):
                data[key] = [
                    item.to_dict(_extras=item._extras)
                    if hasattr(item, "to_dict")
                    else item
                    for item in value
                ]
            elif (
                isinstance(value, dict)
                or isinstance(value, int)
                or isinstance(value, bool)
            ):
                data[key] = value
            else:
                data[key] = str(value)
    return data

StreamsLoader

Source code in libs/apmodel/src/apmodel/loader.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
class StreamsLoader:
    @staticmethod
    @deprecated("StreamsLoader.load is deprecated; use loader.load.")
    def load(
        object: dict[Any, Any], custom_mapper: dict = fedi_mapper
    ) -> Object | Link | Any | dict:  # type: ignore
        """convert json object to model

        Args:
            object (dict[Any, Any]): json object
            custom_mapper (dict, optional): Models available at the time of loading. Defaults to fedi_mapper.

        Returns:
            Object | Link | dict | Any: An object converted from json. If there is no corresponding object, the dictionary type is returned.
        """
        return load(object, custom_mapper)

load(object, custom_mapper=fedi_mapper) staticmethod

convert json object to model

Parameters:

Name Type Description Default
object dict[Any, Any]

json object

required
custom_mapper dict

Models available at the time of loading. Defaults to fedi_mapper.

fedi_mapper

Returns:

Type Description
Object | Link | Any | dict

Object | Link | dict | Any: An object converted from json. If there is no corresponding object, the dictionary type is returned.

Source code in libs/apmodel/src/apmodel/loader.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
@staticmethod
@deprecated("StreamsLoader.load is deprecated; use loader.load.")
def load(
    object: dict[Any, Any], custom_mapper: dict = fedi_mapper
) -> Object | Link | Any | dict:  # type: ignore
    """convert json object to model

    Args:
        object (dict[Any, Any]): json object
        custom_mapper (dict, optional): Models available at the time of loading. Defaults to fedi_mapper.

    Returns:
        Object | Link | dict | Any: An object converted from json. If there is no corresponding object, the dictionary type is returned.
    """
    return load(object, custom_mapper)

load(object, custom_mapper=fedi_mapper)

convert json object to model

Parameters:

Name Type Description Default
object dict[Any, Any]

json object

required
custom_mapper dict

Models available at the time of loading. Defaults to fedi_mapper.

fedi_mapper

Returns:

Type Description
Object | Link | dict | Any

Object | Link | dict | Any: An object converted from json. If there is no corresponding object, the dictionary type is returned.

Source code in libs/apmodel/src/apmodel/loader.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def load(
    object: dict[Any, Any], custom_mapper: dict = fedi_mapper
) -> Object | Link | dict | Any:  # type: ignore
    """convert json object to model

    Args:
        object (dict[Any, Any]): json object
        custom_mapper (dict, optional): Models available at the time of loading. Defaults to fedi_mapper.

    Returns:
        Object | Link | dict | Any: An object converted from json. If there is no corresponding object, the dictionary type is returned.
    """
    type = object.get("type")
    cls = custom_mapper.get(type)
    if cls:
        return cls(**object)
    return object

core

Activity

Bases: Object

Source code in libs/apmodel/src/apmodel/core.py
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
class Activity(Object):
    def __init__(
        self,
        type: str = "Activity",
        id: Optional[str] = None,
        actor: Optional[Union[Object, Link, str, dict]] = None,
        object: Optional[Union[Object, dict]] = None,
        target: Optional[Union[Object, Link]] = None,
        result: Optional[Union[Object, Link]] = None,
        origin: Optional[Union[Object, Link]] = None,
        instrument: Optional[Union[Object, Link]] = None,
        proof: Union[DataIntegrityProof, dict] = {},
        **kwargs,
    ):
        """Represents an Activity object in Activity Streams 2.0.

        The Activity class is used to express an action or event that occurs in a 
        social context. It encapsulates various properties that describe the 
        activity, including the actor, the object acted upon, and other related 
        entities.

        Args:
            type (str, optional): 
                The type of the object. For this class, it is always "Activity". 
                Defaults to "Activity".
            id (Optional[str], optional): 
                A unique identifier for the activity. If not provided, a UUID 
                will be generated. Defaults to None.
            actor (Optional[Union[Object, Link, str, dict]], optional): 
                The entity that is performing the activity. This can be an 
                Object, a Link, a string representing an identifier, or a 
                dictionary containing the entity's data. Defaults to None.
            object (Optional[Union[Object, dict]], optional): 
                The object that is the target of the activity. This can be an 
                Object or a dictionary. Defaults to None.
            target (Optional[Union[Object, Link]], optional): 
                The entity that the activity is directed towards. This can be 
                an Object or a Link. Defaults to None.
            result (Optional[Union[Object, Link]], optional): 
                The result of the activity. This can be an Object or a Link 
                that represents the outcome of the activity. Defaults to None.
            origin (Optional[Union[Object, Link]], optional): 
                The source of the activity, indicating where it originated. 
                This can be an Object or a Link. Defaults to None.
            instrument (Optional[Union[Object, Link]], optional): 
                The tool or means used to perform the activity. This can be 
                an Object or a Link. Defaults to None.
            proof (Union[DataIntegrityProof, dict], optional): 
                A proof of the integrity of the activity data, represented 
                as a DataIntegrityProof object or a dictionary. Defaults to 
                an empty list.
            **kwargs: 
                Additional properties that can be added to the Activity 
                object, allowing for extensibility.

        Note:
            Other values are inherited from apmodel.Object.

        Raises:
            ValueError: 
                If the proof is not a valid DataIntegrityProof object or 
                dictionary.

        """
        from .loader import load

        super().__init__(type="Activity", content=None)
        self.type = type
        self.id = id if id else str(uuid.uuid4())
        self.published = (
            datetime.utcnow().isoformat(timespec='microseconds').replace('+00:00', 'Z')
            if not kwargs.get("published")
            else datetime.datetime.datetime.strptime(
                kwargs.get("published"), "%Y-%m-%dT%H:%M:%S.%fZ"
            )
        )
        self.actor = load(actor) if isinstance(actor, dict) else actor
        self.object = load(object) if isinstance(object, dict) else object
        self.target = target
        self.result = result
        self.origin = origin
        self.instrument = instrument
        self.proof: Optional[DataIntegrityProof] = (load(proof) if isinstance(proof, dict) else proof) if proof != {} else None
        self._extras = {}
        for key, value in kwargs.items():
            self._extras[key] = value

    def accept(self, actor: Object | Link | str):
        obj = self.to_dict(self._extras)
        return _make_accept(obj, actor)

    def reject(self, actor: Object | Link | str):
        obj = self.to_dict(self._extras)
        return _make_reject(obj, actor)

    def to_dict(self, _extras: Optional[dict] = None) -> dict:
        """Outputs the current object as a dictionary.

        Args:
            _extras (Optional[dict], optional): Arguments used internally. It is not recommended that users change them.

        Returns:
            dict: Objects converted to dictionaries
        """
        data = super().to_dict()
        data["@context"] = ["https://www.w3.org/ns/activitystreams", "https://w3id.org/security/data-integrity/v1"]

        if self.type:
            data["type"] = self.type
        if self.actor:
            data["actor"] = (
                self.actor.to_dict()
                if isinstance(self.actor, Object)
                else str(self.actor)
            )
        if self.object:
            data["object"] = (
                self.object.to_dict()
                if isinstance(self.object, Object)
                else str(self.object)
            )
        if self.target:
            data["target"] = (
                self.target.to_dict()
                if isinstance(self.target, Object)
                else str(self.target)
            )
        if self.proof:
            data["proof"] = (
                self.target.to_dict()
                if isinstance(self.proof, DataIntegrityProof)
                else self.proof
            )

        return data

__init__(type='Activity', id=None, actor=None, object=None, target=None, result=None, origin=None, instrument=None, proof={}, **kwargs)

Represents an Activity object in Activity Streams 2.0.

The Activity class is used to express an action or event that occurs in a social context. It encapsulates various properties that describe the activity, including the actor, the object acted upon, and other related entities.

Parameters:

Name Type Description Default
type str

The type of the object. For this class, it is always "Activity". Defaults to "Activity".

'Activity'
id Optional[str]

A unique identifier for the activity. If not provided, a UUID will be generated. Defaults to None.

None
actor Optional[Union[Object, Link, str, dict]]

The entity that is performing the activity. This can be an Object, a Link, a string representing an identifier, or a dictionary containing the entity's data. Defaults to None.

None
object Optional[Union[Object, dict]]

The object that is the target of the activity. This can be an Object or a dictionary. Defaults to None.

None
target Optional[Union[Object, Link]]

The entity that the activity is directed towards. This can be an Object or a Link. Defaults to None.

None
result Optional[Union[Object, Link]]

The result of the activity. This can be an Object or a Link that represents the outcome of the activity. Defaults to None.

None
origin Optional[Union[Object, Link]]

The source of the activity, indicating where it originated. This can be an Object or a Link. Defaults to None.

None
instrument Optional[Union[Object, Link]]

The tool or means used to perform the activity. This can be an Object or a Link. Defaults to None.

None
proof Union[DataIntegrityProof, dict]

A proof of the integrity of the activity data, represented as a DataIntegrityProof object or a dictionary. Defaults to an empty list.

{}
**kwargs

Additional properties that can be added to the Activity object, allowing for extensibility.

{}
Note

Other values are inherited from apmodel.Object.

Raises:

Type Description
ValueError

If the proof is not a valid DataIntegrityProof object or dictionary.

Source code in libs/apmodel/src/apmodel/core.py
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
def __init__(
    self,
    type: str = "Activity",
    id: Optional[str] = None,
    actor: Optional[Union[Object, Link, str, dict]] = None,
    object: Optional[Union[Object, dict]] = None,
    target: Optional[Union[Object, Link]] = None,
    result: Optional[Union[Object, Link]] = None,
    origin: Optional[Union[Object, Link]] = None,
    instrument: Optional[Union[Object, Link]] = None,
    proof: Union[DataIntegrityProof, dict] = {},
    **kwargs,
):
    """Represents an Activity object in Activity Streams 2.0.

    The Activity class is used to express an action or event that occurs in a 
    social context. It encapsulates various properties that describe the 
    activity, including the actor, the object acted upon, and other related 
    entities.

    Args:
        type (str, optional): 
            The type of the object. For this class, it is always "Activity". 
            Defaults to "Activity".
        id (Optional[str], optional): 
            A unique identifier for the activity. If not provided, a UUID 
            will be generated. Defaults to None.
        actor (Optional[Union[Object, Link, str, dict]], optional): 
            The entity that is performing the activity. This can be an 
            Object, a Link, a string representing an identifier, or a 
            dictionary containing the entity's data. Defaults to None.
        object (Optional[Union[Object, dict]], optional): 
            The object that is the target of the activity. This can be an 
            Object or a dictionary. Defaults to None.
        target (Optional[Union[Object, Link]], optional): 
            The entity that the activity is directed towards. This can be 
            an Object or a Link. Defaults to None.
        result (Optional[Union[Object, Link]], optional): 
            The result of the activity. This can be an Object or a Link 
            that represents the outcome of the activity. Defaults to None.
        origin (Optional[Union[Object, Link]], optional): 
            The source of the activity, indicating where it originated. 
            This can be an Object or a Link. Defaults to None.
        instrument (Optional[Union[Object, Link]], optional): 
            The tool or means used to perform the activity. This can be 
            an Object or a Link. Defaults to None.
        proof (Union[DataIntegrityProof, dict], optional): 
            A proof of the integrity of the activity data, represented 
            as a DataIntegrityProof object or a dictionary. Defaults to 
            an empty list.
        **kwargs: 
            Additional properties that can be added to the Activity 
            object, allowing for extensibility.

    Note:
        Other values are inherited from apmodel.Object.

    Raises:
        ValueError: 
            If the proof is not a valid DataIntegrityProof object or 
            dictionary.

    """
    from .loader import load

    super().__init__(type="Activity", content=None)
    self.type = type
    self.id = id if id else str(uuid.uuid4())
    self.published = (
        datetime.utcnow().isoformat(timespec='microseconds').replace('+00:00', 'Z')
        if not kwargs.get("published")
        else datetime.datetime.datetime.strptime(
            kwargs.get("published"), "%Y-%m-%dT%H:%M:%S.%fZ"
        )
    )
    self.actor = load(actor) if isinstance(actor, dict) else actor
    self.object = load(object) if isinstance(object, dict) else object
    self.target = target
    self.result = result
    self.origin = origin
    self.instrument = instrument
    self.proof: Optional[DataIntegrityProof] = (load(proof) if isinstance(proof, dict) else proof) if proof != {} else None
    self._extras = {}
    for key, value in kwargs.items():
        self._extras[key] = value

to_dict(_extras=None)

Outputs the current object as a dictionary.

Parameters:

Name Type Description Default
_extras Optional[dict]

Arguments used internally. It is not recommended that users change them.

None

Returns:

Name Type Description
dict dict

Objects converted to dictionaries

Source code in libs/apmodel/src/apmodel/core.py
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
def to_dict(self, _extras: Optional[dict] = None) -> dict:
    """Outputs the current object as a dictionary.

    Args:
        _extras (Optional[dict], optional): Arguments used internally. It is not recommended that users change them.

    Returns:
        dict: Objects converted to dictionaries
    """
    data = super().to_dict()
    data["@context"] = ["https://www.w3.org/ns/activitystreams", "https://w3id.org/security/data-integrity/v1"]

    if self.type:
        data["type"] = self.type
    if self.actor:
        data["actor"] = (
            self.actor.to_dict()
            if isinstance(self.actor, Object)
            else str(self.actor)
        )
    if self.object:
        data["object"] = (
            self.object.to_dict()
            if isinstance(self.object, Object)
            else str(self.object)
        )
    if self.target:
        data["target"] = (
            self.target.to_dict()
            if isinstance(self.target, Object)
            else str(self.target)
        )
    if self.proof:
        data["proof"] = (
            self.target.to_dict()
            if isinstance(self.proof, DataIntegrityProof)
            else self.proof
        )

    return data
Source code in libs/apmodel/src/apmodel/core.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
class Link:
    def __init__(
        self,
        _context: Union[str, list] = "https://www.w3.org/ns/activitystreams",
        type: str = "Link",
        id: Optional[str] = None,
        href: Optional[str] = None,
        rel: Optional[list[str]] = None,
        mediaType: Optional[str] = None,
        name: Optional[str] = None,
        hreflang: Optional[str] = None,
        height: Optional[int] = None,
        width: Optional[int] = None,
        preview: Optional[Union[Object, "Link"]] = None,
        **kwargs,
    ):
        """Represents a Link object in Activity Streams 2.0.

        This class implements the Link type, which is used to represent 
        a hyperlink to a resource. The Link object can contain various 
        attributes that provide metadata about the link.

        Args:
            _context (Union[str, list], optional): 
                The default value for @context. It can be a string 
                or a list of strings. Defaults to "https://www.w3.org/ns/activitystreams".
            type (str, optional): 
                The type of the object. For this class, it is always "Link". 
                Defaults to "Link".
            id (Optional[str], optional): 
                A unique identifier for the link object. 
                This can be a URL or an IRI. Defaults to None.
            href (Optional[str], optional): 
                The URL that the link points to. It must conform to 
                the xsd:anyURI format. If provided, it must be a valid URI. 
                Defaults to None.
            rel (Optional[list[str]], optional): 
                A list of relationship types indicating the nature 
                of the link with respect to the context of the link. 
                Defaults to None.
            mediaType (Optional[str], optional): 
                The media type of the linked resource, such as 
                "image/jpeg". Defaults to None.
            name (Optional[str], optional): 
                A human-readable name for the link. Defaults to None.
            hreflang (Optional[str], optional): 
                The language of the linked resource, represented 
                as a language tag. Defaults to None.
            height (Optional[int], optional): 
                The height of the linked resource in pixels. 
                Must be greater than or equal to 0. Defaults to None.
            width (Optional[int], optional): 
                The width of the linked resource in pixels. 
                Must be greater than or equal to 0. Defaults to None.
            preview (Optional[Union["Object", "Link"]], optional): 
                A resource that provides a preview of the linked 
                content, which could be another Link or an Object. 
                Defaults to None.
            **kwargs: 
                Additional properties that can be added to the Link 
                object, allowing for extensibility.

        Raises:
            ValueError: 
                If `href` is not a valid URI, if `height` is negative, 
                or if `width` is negative.

        """
        if href:
            if not re.fullmatch(r"(%(?![0-9A-F]{2})|#.*#)", href):
                raise ValueError("href must be xsd:anyURI")
        if height:
            if height < 0:
                raise ValueError("height must be greater than or equal to 0")
        if width:
            if width < 0:
                raise ValueError("width must be greater than or equal to 0")
        ctx = kwargs.get("@context")
        self._context = merge_contexts(_context, ctx) if ctx else []
        self.type = type
        self.id = id
        self.href = href
        self.rel = rel
        self.media_type = mediaType
        self.name = name
        self.hreflang = hreflang
        self.height = height
        self.preview = preview
        self._extras = {}
        for key, value in kwargs.items():
            self._extras[key] = value

    def to_dict(self, _extras: Optional[dict] = None, build_context: bool = True):
        """Outputs the current object as a dictionary.

        Args:
            _extras (Optional[dict], optional): Arguments used internally. It is not recommended that users change them.
            build_context (bool): Do we automatically build @context based on the arguments? Defaults to False.

        Returns:
            dict: Objects converted to dictionaries
        """
        if not _extras:
            _extras = self._extras.copy()
        instance_vars = vars(self).copy()

        ctx = self._context.copy()
        context = instance_vars.get("@context")

        if build_context:
            attrs = dir(self)

            ctx2 = []
            ctx2_d = {}
            if _extras.get("publicKey") or "publicKey" in attrs:
                ctx2.append("https://w3id.org/security/v1")

            # Mastodon
            if _extras.get("featured") or "featured" in attrs:
                ctx2_d["featured"] = {
                    "@id": "http://joinmastodon.org/ns#featured",
                    "@type": "@id",
                }
            if _extras.get("featuredTags") or "featuredTags" in attrs:
                ctx2_d["featuredTags"] = {
                    "@id": "http://joinmastodon.org/ns#featuredTags",
                    "@type": "@id",
                }
            if _extras.get("discoverable") or "discoverable" in attrs:
                if not ctx2_d.get("toot"):
                    ctx2_d["toot"] = "http://joinmastodon.org/ns#"
                ctx2_d["discoverable"] = "toot:discoverable"
            if _extras.get("discoverable") or "discoverable" in attrs:
                if not ctx2_d.get("toot"):
                    ctx2_d["toot"] = "http://joinmastodon.org/ns#"
                ctx2_d["discoverable"] = "toot:discoverable"
            if (
                _extras.get("manuallyApprovesFollowers")
                or "manuallyApprovesFollowers" in attrs
            ):
                ctx2_d["manuallyApprovesFollowers"] = "as:manuallyApprovesFollowers"

            # Misskey
            if (
                _extras.get("_misskey_content")
                or _extras.get("_misskey_summary")
                or _extras.get("_misskey_quote")
                or _extras.get("_misskey_reaction")
                or _extras.get("_misskey_votes")
                or _extras.get("_misskey_talk")
                or _extras.get("isCat")
                or _extras.get("_misskey_followedMessage")
                or _extras.get("_misskey_requireSigninToViewContents")
                or _extras.get("_misskey_makeNotesFollowersOnlyBefore")
                or _extras.get("_misskey_makeNotesHiddenBefore")
                or _extras.get("_misskey_license")
            ):
                if not ctx2_d.get("misskey"):
                    ctx2_d["misskey"] = "https://misskey-hub-net/ns#"

            ctx2.append(ctx2_d)
        if context:
            context = merge_contexts(merge_contexts(ctx, context), ctx2)
        else:
            context = ctx
        data: Dict[str, Any] = {
            "@context": context,
        }
        for key, value in instance_vars.items():
            if value is not None:
                if not key.startswith("_") and key != "content":
                    if isinstance(value, datetime.datetime.datetime):
                        data[key] = value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
                    elif isinstance(value, Object):
                        data[key] = value.to_dict(_extras=value._extras)
                    elif isinstance(value, list):
                        data[key] = [
                            item.to_dict(_extras=item._extras)
                            if hasattr(item, "to_dict")
                            else item
                            for item in value
                        ]
                    elif (
                        isinstance(value, dict)
                        or isinstance(value, int)
                        or isinstance(value, bool)
                    ):
                        data[key] = value
                    else:
                        data[key] = str(value)

        _extras = _extras or {}
        for key, value in self._extras.items():
            if value is not None:
                if isinstance(value, datetime.datetime.datetime):
                    data[key] = value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
                elif isinstance(value, Object):
                    data[key] = value.to_dict(_extras=value._extras)
                elif isinstance(value, list):
                    data[key] = [
                        item.to_dict(_extras=item._extras)
                        if hasattr(item, "to_dict")
                        else item
                        for item in value
                    ]
                elif (
                    isinstance(value, dict)
                    or isinstance(value, int)
                    or isinstance(value, bool)
                ):
                    data[key] = value
                else:
                    data[key] = str(value)
        return data

__init__(_context='https://www.w3.org/ns/activitystreams', type='Link', id=None, href=None, rel=None, mediaType=None, name=None, hreflang=None, height=None, width=None, preview=None, **kwargs)

Represents a Link object in Activity Streams 2.0.

This class implements the Link type, which is used to represent a hyperlink to a resource. The Link object can contain various attributes that provide metadata about the link.

Parameters:

Name Type Description Default
_context Union[str, list]

The default value for @context. It can be a string or a list of strings. Defaults to "https://www.w3.org/ns/activitystreams".

'https://www.w3.org/ns/activitystreams'
type str

The type of the object. For this class, it is always "Link". Defaults to "Link".

'Link'
id Optional[str]

A unique identifier for the link object. This can be a URL or an IRI. Defaults to None.

None
href Optional[str]

The URL that the link points to. It must conform to the xsd:anyURI format. If provided, it must be a valid URI. Defaults to None.

None
rel Optional[list[str]]

A list of relationship types indicating the nature of the link with respect to the context of the link. Defaults to None.

None
mediaType Optional[str]

The media type of the linked resource, such as "image/jpeg". Defaults to None.

None
name Optional[str]

A human-readable name for the link. Defaults to None.

None
hreflang Optional[str]

The language of the linked resource, represented as a language tag. Defaults to None.

None
height Optional[int]

The height of the linked resource in pixels. Must be greater than or equal to 0. Defaults to None.

None
width Optional[int]

The width of the linked resource in pixels. Must be greater than or equal to 0. Defaults to None.

None
preview Optional[Union[Object, Link]]

A resource that provides a preview of the linked content, which could be another Link or an Object. Defaults to None.

None
**kwargs

Additional properties that can be added to the Link object, allowing for extensibility.

{}

Raises:

Type Description
ValueError

If href is not a valid URI, if height is negative, or if width is negative.

Source code in libs/apmodel/src/apmodel/core.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
def __init__(
    self,
    _context: Union[str, list] = "https://www.w3.org/ns/activitystreams",
    type: str = "Link",
    id: Optional[str] = None,
    href: Optional[str] = None,
    rel: Optional[list[str]] = None,
    mediaType: Optional[str] = None,
    name: Optional[str] = None,
    hreflang: Optional[str] = None,
    height: Optional[int] = None,
    width: Optional[int] = None,
    preview: Optional[Union[Object, "Link"]] = None,
    **kwargs,
):
    """Represents a Link object in Activity Streams 2.0.

    This class implements the Link type, which is used to represent 
    a hyperlink to a resource. The Link object can contain various 
    attributes that provide metadata about the link.

    Args:
        _context (Union[str, list], optional): 
            The default value for @context. It can be a string 
            or a list of strings. Defaults to "https://www.w3.org/ns/activitystreams".
        type (str, optional): 
            The type of the object. For this class, it is always "Link". 
            Defaults to "Link".
        id (Optional[str], optional): 
            A unique identifier for the link object. 
            This can be a URL or an IRI. Defaults to None.
        href (Optional[str], optional): 
            The URL that the link points to. It must conform to 
            the xsd:anyURI format. If provided, it must be a valid URI. 
            Defaults to None.
        rel (Optional[list[str]], optional): 
            A list of relationship types indicating the nature 
            of the link with respect to the context of the link. 
            Defaults to None.
        mediaType (Optional[str], optional): 
            The media type of the linked resource, such as 
            "image/jpeg". Defaults to None.
        name (Optional[str], optional): 
            A human-readable name for the link. Defaults to None.
        hreflang (Optional[str], optional): 
            The language of the linked resource, represented 
            as a language tag. Defaults to None.
        height (Optional[int], optional): 
            The height of the linked resource in pixels. 
            Must be greater than or equal to 0. Defaults to None.
        width (Optional[int], optional): 
            The width of the linked resource in pixels. 
            Must be greater than or equal to 0. Defaults to None.
        preview (Optional[Union["Object", "Link"]], optional): 
            A resource that provides a preview of the linked 
            content, which could be another Link or an Object. 
            Defaults to None.
        **kwargs: 
            Additional properties that can be added to the Link 
            object, allowing for extensibility.

    Raises:
        ValueError: 
            If `href` is not a valid URI, if `height` is negative, 
            or if `width` is negative.

    """
    if href:
        if not re.fullmatch(r"(%(?![0-9A-F]{2})|#.*#)", href):
            raise ValueError("href must be xsd:anyURI")
    if height:
        if height < 0:
            raise ValueError("height must be greater than or equal to 0")
    if width:
        if width < 0:
            raise ValueError("width must be greater than or equal to 0")
    ctx = kwargs.get("@context")
    self._context = merge_contexts(_context, ctx) if ctx else []
    self.type = type
    self.id = id
    self.href = href
    self.rel = rel
    self.media_type = mediaType
    self.name = name
    self.hreflang = hreflang
    self.height = height
    self.preview = preview
    self._extras = {}
    for key, value in kwargs.items():
        self._extras[key] = value

to_dict(_extras=None, build_context=True)

Outputs the current object as a dictionary.

Parameters:

Name Type Description Default
_extras Optional[dict]

Arguments used internally. It is not recommended that users change them.

None
build_context bool

Do we automatically build @context based on the arguments? Defaults to False.

True

Returns:

Name Type Description
dict

Objects converted to dictionaries

Source code in libs/apmodel/src/apmodel/core.py
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
def to_dict(self, _extras: Optional[dict] = None, build_context: bool = True):
    """Outputs the current object as a dictionary.

    Args:
        _extras (Optional[dict], optional): Arguments used internally. It is not recommended that users change them.
        build_context (bool): Do we automatically build @context based on the arguments? Defaults to False.

    Returns:
        dict: Objects converted to dictionaries
    """
    if not _extras:
        _extras = self._extras.copy()
    instance_vars = vars(self).copy()

    ctx = self._context.copy()
    context = instance_vars.get("@context")

    if build_context:
        attrs = dir(self)

        ctx2 = []
        ctx2_d = {}
        if _extras.get("publicKey") or "publicKey" in attrs:
            ctx2.append("https://w3id.org/security/v1")

        # Mastodon
        if _extras.get("featured") or "featured" in attrs:
            ctx2_d["featured"] = {
                "@id": "http://joinmastodon.org/ns#featured",
                "@type": "@id",
            }
        if _extras.get("featuredTags") or "featuredTags" in attrs:
            ctx2_d["featuredTags"] = {
                "@id": "http://joinmastodon.org/ns#featuredTags",
                "@type": "@id",
            }
        if _extras.get("discoverable") or "discoverable" in attrs:
            if not ctx2_d.get("toot"):
                ctx2_d["toot"] = "http://joinmastodon.org/ns#"
            ctx2_d["discoverable"] = "toot:discoverable"
        if _extras.get("discoverable") or "discoverable" in attrs:
            if not ctx2_d.get("toot"):
                ctx2_d["toot"] = "http://joinmastodon.org/ns#"
            ctx2_d["discoverable"] = "toot:discoverable"
        if (
            _extras.get("manuallyApprovesFollowers")
            or "manuallyApprovesFollowers" in attrs
        ):
            ctx2_d["manuallyApprovesFollowers"] = "as:manuallyApprovesFollowers"

        # Misskey
        if (
            _extras.get("_misskey_content")
            or _extras.get("_misskey_summary")
            or _extras.get("_misskey_quote")
            or _extras.get("_misskey_reaction")
            or _extras.get("_misskey_votes")
            or _extras.get("_misskey_talk")
            or _extras.get("isCat")
            or _extras.get("_misskey_followedMessage")
            or _extras.get("_misskey_requireSigninToViewContents")
            or _extras.get("_misskey_makeNotesFollowersOnlyBefore")
            or _extras.get("_misskey_makeNotesHiddenBefore")
            or _extras.get("_misskey_license")
        ):
            if not ctx2_d.get("misskey"):
                ctx2_d["misskey"] = "https://misskey-hub-net/ns#"

        ctx2.append(ctx2_d)
    if context:
        context = merge_contexts(merge_contexts(ctx, context), ctx2)
    else:
        context = ctx
    data: Dict[str, Any] = {
        "@context": context,
    }
    for key, value in instance_vars.items():
        if value is not None:
            if not key.startswith("_") and key != "content":
                if isinstance(value, datetime.datetime.datetime):
                    data[key] = value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
                elif isinstance(value, Object):
                    data[key] = value.to_dict(_extras=value._extras)
                elif isinstance(value, list):
                    data[key] = [
                        item.to_dict(_extras=item._extras)
                        if hasattr(item, "to_dict")
                        else item
                        for item in value
                    ]
                elif (
                    isinstance(value, dict)
                    or isinstance(value, int)
                    or isinstance(value, bool)
                ):
                    data[key] = value
                else:
                    data[key] = str(value)

    _extras = _extras or {}
    for key, value in self._extras.items():
        if value is not None:
            if isinstance(value, datetime.datetime.datetime):
                data[key] = value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
            elif isinstance(value, Object):
                data[key] = value.to_dict(_extras=value._extras)
            elif isinstance(value, list):
                data[key] = [
                    item.to_dict(_extras=item._extras)
                    if hasattr(item, "to_dict")
                    else item
                    for item in value
                ]
            elif (
                isinstance(value, dict)
                or isinstance(value, int)
                or isinstance(value, bool)
            ):
                data[key] = value
            else:
                data[key] = str(value)
    return data

Object

Source code in libs/apmodel/src/apmodel/core.py
 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
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
class Object:
    def __init__(
        self,
        _context: Union[str, list] = "https://www.w3.org/ns/activitystreams",
        type: str = "Object",
        id: Optional[str] = None,
        attachment: List[Union["Object", "Link", dict]] = [],
        attributedTo: Optional[Union["Object", "Link", str]] = None,
        audience: Optional[Union["Object", "Link"]] = None,
        content: Optional[str] = None,
        context: Optional[Union["Object", "Link"]] = None,
        name: Optional[str] = None,
        endTime: Optional[str] = None,
        generator: Optional[Union["Object", "Link"]] = None,
        icon: Optional[Union["Image", "Link"]] = None,
        image: Optional["Image"] = None,
        inReplyTo: Optional[Union["Image", "Link"]] = None,
        location: Optional[Union["Image", "Link"]] = None,
        preview: Optional[Union["Object", "Link"]] = None,
        published: Optional[str] = None,
        replies: Optional["Collection"] = None,
        startTime: Optional[str] = None,
        summary: Optional[str] = None,
        tag: Optional[Union["Object", "Link"]] = None,
        updated: Optional[str] = None,
        url: Optional[Union[str, "Link"]] = None,
        to: Optional[Union["Object", "Link"]] = None,
        bto: Optional[Union["Object", "Link"]] = None,
        cc: Optional[Union["Object", "Link"]] = None,
        bcc: Optional[Union["Object", "Link"]] = None,
        mediaType: Optional[str] = None,
        duration: Optional[str] = None,
        sensitive: Optional[bool] = None,
        **kwargs,
    ):
        """Implements the "Object" primary base type of the ActivityStreams vocabulary.

        Args:
            _context (Union[str, list], optional): 
                The default value for @context. Defaults to "https://www.w3.org/ns/activitystreams".
            type (str, optional): 
                The name of the ActivityStreams type. Usually does not need to be changed. Defaults to "Object".
            id (Optional[str], optional): 
                The identifier for the object. Defaults to None.
            attachment (List[Union["Object", "Link", dict]], optional): 
                A list of resources attached to the object. Defaults to an empty list.
            attributedTo (Optional[Union["Object", "Link", str]], optional): 
                The resource indicating the creator of this object. Defaults to None.
            audience (Optional[Union["Object", "Link"]], optional): 
                The resource indicating the intended audience of this object. Defaults to None.
            content (Optional[str], optional): 
                The text representing the content of the object. Defaults to None.
            context (Optional[Union["Object", "Link"]], optional): 
                The resource indicating the context of the object. Defaults to None.
            name (Optional[str], optional): 
                The name of the object. Defaults to None.
            endTime (Optional[str], optional): 
                The end time of the event represented as an ISO8601 formatted string. Defaults to None.
            generator (Optional[Union["Object", "Link"]], optional): 
                The resource indicating the application that generated the object. Defaults to None.
            icon (Optional[Union["Image", "Link"]], optional): 
                The resource for the icon of the object. Defaults to None.
            image (Optional["Image"], optional): 
                The resource for the image of the object. Defaults to None.
            inReplyTo (Optional[Union["Image", "Link"]], optional): 
                The resource indicating the target of this reply. Defaults to None.
            location (Optional[Union["Image", "Link"]], optional): 
                The resource indicating the location of the object. Defaults to None.
            preview (Optional[Union["Object", "Link"]], optional): 
                The resource for the preview of the object. Defaults to None.
            published (Optional[str], optional): 
                The date and time when the object was published, represented as an ISO8601 formatted string. Defaults to None.
            replies (Optional["Collection"], optional): 
                A collection of replies to this object. Defaults to None.
            startTime (Optional[str], optional): 
                The start time of the event represented as an ISO8601 formatted string. Defaults to None.
            summary (Optional[str], optional): 
                A summary of the object. Defaults to None.
            tag (Optional[Union["Object", "Link"]], optional): 
                The resource indicating tags related to the object. Defaults to None.
            updated (Optional[str], optional): 
                The date and time when the object was last updated, represented as an ISO8601 formatted string. Defaults to None.
            url (Optional[Union[str, "Link"]], optional): 
                The URL of the object. Defaults to None.
            to (Optional[Union["Object", "Link"]], optional): 
                The resource indicating the recipient of the object. Defaults to None.
            bto (Optional[Union["Object", "Link"]], optional): 
                The resource indicating BCC recipients. Defaults to None.
            cc (Optional[Union["Object", "Link"]], optional): 
                The resource indicating CC recipients. Defaults to None.
            bcc (Optional[Union["Object", "Link"]], optional): 
                The resource indicating BCC recipients. Defaults to None.
            mediaType (Optional[str], optional): 
                The media type of the object. Defaults to None.
            duration (Optional[str], optional): 
                A string representing the duration of the object. Defaults to None.
            sensitive (Optional[bool], optional): 
                A flag indicating the sensitivity of the content. Defaults to None.

        """
        from .loader import load

        ctx = kwargs.get("@context")
        self._context = merge_contexts(_context, ctx) if ctx else []
        self.type = type
        self.id = id
        self.attachment = [
            load(attach) if isinstance(attach, dict) else attach
            for attach in attachment
        ]
        self.attributedTo = (
            load(attributedTo)
            if isinstance(attributedTo, dict)
            else attributedTo
        )
        self.audience = (
            load(audience) if isinstance(audience, dict) else audience
        )
        self.content = content
        self.context = (
            load(context) if isinstance(context, dict) else context
        )
        self.name = name
        self.endTime = (
            (
                endTime
                if isinstance(endTime, datetime.datetime.datetime)
                else datetime.datetime.datetime.strptime(
                    endTime, "%Y-%m-%dT%H:%M:%S.%fZ"
                )
            )
            if endTime
            else endTime
        )
        self.generator = (
            load(generator) if isinstance(generator, dict) else generator
        )
        self.icon = load(icon) if isinstance(icon, dict) else icon
        self.image = image
        self.inReplyTo = (
            load(inReplyTo) if isinstance(inReplyTo, dict) else inReplyTo
        )
        self.location = (
            load(location) if isinstance(location, dict) else location
        )
        self.preview = (
            load(preview) if isinstance(preview, dict) else preview
        )
        if published:
            self.published = (
                (
                    published
                    if isinstance(published, datetime.datetime.datetime)
                    else datetime.datetime.datetime.strptime(
                        published, "%Y-%m-%dT%H:%M:%S.%fZ"
                    )
                )
                if published
                else published
            )
        else:
            self.published = datetime.utcnow()
        self.replies = (
            load(replies) if isinstance(replies, dict) else replies
        )
        self.startTime = (
            (
                startTime
                if isinstance(startTime, datetime.datetime.datetime)
                else datetime.datetime.datetime.strptime(
                    startTime, "%Y-%m-%dT%H:%M:%S.%fZ"
                )
            )
            if startTime
            else startTime
        )
        self.summary = summary
        self.tag = load(tag) if isinstance(tag, dict) else tag
        self.updated = updated
        self.url = load(url) if isinstance(url, dict) else url
        self.to = load(to) if isinstance(to, dict) else to
        self.bto = load(bto) if isinstance(bto, dict) else bto
        self.cc = load(cc) if isinstance(cc, dict) else cc
        self.bcc = load(bcc) if isinstance(bcc, dict) else bcc
        self.mediaType = mediaType
        self.duration = duration

        # --- Extend Value
        self.sensitive = sensitive
        # ---

        self._extras = {}
        for key, value in kwargs.items():
            self._extras[key] = value

    def to_dict(self, _extras: Optional[dict] = None, build_context: bool = True):
        """Outputs the current object as a dictionary.

        Args:
            _extras (Optional[dict], optional): Arguments used internally. It is not recommended that users change them.
            build_context (bool): Do we automatically build @context based on the arguments? Defaults to True.

        Returns:
            dict: Objects converted to dictionaries
        """
        if not _extras:
            _extras = self._extras.copy()
        instance_vars = vars(self).copy()

        ctx = self._context.copy()
        if build_context:
            attrs = dir(self)

            ctx2 = []
            ctx2_d = {}
            if _extras.get("publicKey") or "publicKey" in attrs:
                ctx2.append("https://w3id.org/security/v1")

            # Mastodon
            if _extras.get("featured") or "featured" in attrs:
                ctx2_d["featured"] = {
                    "@id": "http://joinmastodon.org/ns#featured",
                    "@type": "@id",
                }
            if _extras.get("featuredTags") or "featuredTags" in attrs:
                ctx2_d["featuredTags"] = {
                    "@id": "http://joinmastodon.org/ns#featuredTags",
                    "@type": "@id",
                }
            if _extras.get("discoverable") or "discoverable" in attrs:
                if not ctx2_d.get("toot"):
                    ctx2_d["toot"] = "http://joinmastodon.org/ns#"
                ctx2_d["discoverable"] = "toot:discoverable"
            if _extras.get("discoverable") or "discoverable" in attrs:
                if not ctx2_d.get("toot"):
                    ctx2_d["toot"] = "http://joinmastodon.org/ns#"
                ctx2_d["discoverable"] = "toot:discoverable"
            if (
                _extras.get("manuallyApprovesFollowers")
                or "manuallyApprovesFollowers" in attrs
            ):
                ctx2_d["manuallyApprovesFollowers"] = "as:manuallyApprovesFollowers"

            # Misskey
            if (
                _extras.get("_misskey_content")
                or _extras.get("_misskey_summary")
                or _extras.get("_misskey_quote")
                or _extras.get("_misskey_reaction")
                or _extras.get("_misskey_votes")
                or _extras.get("_misskey_talk")
                or _extras.get("isCat")
                or _extras.get("_misskey_followedMessage")
                or _extras.get("_misskey_requireSigninToViewContents")
                or _extras.get("_misskey_makeNotesFollowersOnlyBefore")
                or _extras.get("_misskey_makeNotesHiddenBefore")
                or _extras.get("_misskey_license")
            ):
                ctx2_d["misskey"] = "https://misskey-hub-net/ns#"

            ctx2.append(ctx2_d)

        context: Optional[list] = instance_vars.get("@context")
        if context:
            context = merge_contexts(merge_contexts(ctx, context), ctx2)
        else:
            context = ctx
        data: Dict[str, Any] = {
            "@context": context,
        }

        if self.content is not None:
            data["content"] = self.content

        for key, value in instance_vars.items():
            if value is not None:
                if not key.startswith("_") and key != "content":
                    if isinstance(value, datetime.datetime.datetime):
                        data[key] = value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
                    elif isinstance(value, Object):
                        data[key] = value.to_dict(_extras=value._extras)
                    elif isinstance(value, list):
                        data[key] = [
                            item.to_dict(_extras=item._extras)
                            if hasattr(item, "to_dict")
                            else item
                            for item in value
                        ]
                    elif (
                        isinstance(value, dict)
                        or isinstance(value, int)
                        or isinstance(value, bool)
                    ):
                        data[key] = value
                    else:
                        data[key] = str(value)

        _extras = _extras or {}
        for key, value in self._extras.items():
            if value is not None:
                if isinstance(value, datetime.datetime.datetime):
                    data[key] = value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
                elif isinstance(value, Object):
                    data[key] = value.to_dict(_extras=value._extras)
                elif isinstance(value, list):
                    data[key] = [
                        item.to_dict(_extras=item._extras)
                        if hasattr(item, "to_dict")
                        else item
                        for item in value
                    ]
                elif (
                    isinstance(value, dict)
                    or isinstance(value, int)
                    or isinstance(value, bool)
                ):
                    data[key] = value
                else:
                    data[key] = str(value)
        return data

__init__(_context='https://www.w3.org/ns/activitystreams', type='Object', id=None, attachment=[], attributedTo=None, audience=None, content=None, context=None, name=None, endTime=None, generator=None, icon=None, image=None, inReplyTo=None, location=None, preview=None, published=None, replies=None, startTime=None, summary=None, tag=None, updated=None, url=None, to=None, bto=None, cc=None, bcc=None, mediaType=None, duration=None, sensitive=None, **kwargs)

Implements the "Object" primary base type of the ActivityStreams vocabulary.

Parameters:

Name Type Description Default
_context Union[str, list]

The default value for @context. Defaults to "https://www.w3.org/ns/activitystreams".

'https://www.w3.org/ns/activitystreams'
type str

The name of the ActivityStreams type. Usually does not need to be changed. Defaults to "Object".

'Object'
id Optional[str]

The identifier for the object. Defaults to None.

None
attachment List[Union[Object, Link, dict]]

A list of resources attached to the object. Defaults to an empty list.

[]
attributedTo Optional[Union[Object, Link, str]]

The resource indicating the creator of this object. Defaults to None.

None
audience Optional[Union[Object, Link]]

The resource indicating the intended audience of this object. Defaults to None.

None
content Optional[str]

The text representing the content of the object. Defaults to None.

None
context Optional[Union[Object, Link]]

The resource indicating the context of the object. Defaults to None.

None
name Optional[str]

The name of the object. Defaults to None.

None
endTime Optional[str]

The end time of the event represented as an ISO8601 formatted string. Defaults to None.

None
generator Optional[Union[Object, Link]]

The resource indicating the application that generated the object. Defaults to None.

None
icon Optional[Union[Image, Link]]

The resource for the icon of the object. Defaults to None.

None
image Optional[Image]

The resource for the image of the object. Defaults to None.

None
inReplyTo Optional[Union[Image, Link]]

The resource indicating the target of this reply. Defaults to None.

None
location Optional[Union[Image, Link]]

The resource indicating the location of the object. Defaults to None.

None
preview Optional[Union[Object, Link]]

The resource for the preview of the object. Defaults to None.

None
published Optional[str]

The date and time when the object was published, represented as an ISO8601 formatted string. Defaults to None.

None
replies Optional[Collection]

A collection of replies to this object. Defaults to None.

None
startTime Optional[str]

The start time of the event represented as an ISO8601 formatted string. Defaults to None.

None
summary Optional[str]

A summary of the object. Defaults to None.

None
tag Optional[Union[Object, Link]]

The resource indicating tags related to the object. Defaults to None.

None
updated Optional[str]

The date and time when the object was last updated, represented as an ISO8601 formatted string. Defaults to None.

None
url Optional[Union[str, Link]]

The URL of the object. Defaults to None.

None
to Optional[Union[Object, Link]]

The resource indicating the recipient of the object. Defaults to None.

None
bto Optional[Union[Object, Link]]

The resource indicating BCC recipients. Defaults to None.

None
cc Optional[Union[Object, Link]]

The resource indicating CC recipients. Defaults to None.

None
bcc Optional[Union[Object, Link]]

The resource indicating BCC recipients. Defaults to None.

None
mediaType Optional[str]

The media type of the object. Defaults to None.

None
duration Optional[str]

A string representing the duration of the object. Defaults to None.

None
sensitive Optional[bool]

A flag indicating the sensitivity of the content. Defaults to None.

None
Source code in libs/apmodel/src/apmodel/core.py
 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
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def __init__(
    self,
    _context: Union[str, list] = "https://www.w3.org/ns/activitystreams",
    type: str = "Object",
    id: Optional[str] = None,
    attachment: List[Union["Object", "Link", dict]] = [],
    attributedTo: Optional[Union["Object", "Link", str]] = None,
    audience: Optional[Union["Object", "Link"]] = None,
    content: Optional[str] = None,
    context: Optional[Union["Object", "Link"]] = None,
    name: Optional[str] = None,
    endTime: Optional[str] = None,
    generator: Optional[Union["Object", "Link"]] = None,
    icon: Optional[Union["Image", "Link"]] = None,
    image: Optional["Image"] = None,
    inReplyTo: Optional[Union["Image", "Link"]] = None,
    location: Optional[Union["Image", "Link"]] = None,
    preview: Optional[Union["Object", "Link"]] = None,
    published: Optional[str] = None,
    replies: Optional["Collection"] = None,
    startTime: Optional[str] = None,
    summary: Optional[str] = None,
    tag: Optional[Union["Object", "Link"]] = None,
    updated: Optional[str] = None,
    url: Optional[Union[str, "Link"]] = None,
    to: Optional[Union["Object", "Link"]] = None,
    bto: Optional[Union["Object", "Link"]] = None,
    cc: Optional[Union["Object", "Link"]] = None,
    bcc: Optional[Union["Object", "Link"]] = None,
    mediaType: Optional[str] = None,
    duration: Optional[str] = None,
    sensitive: Optional[bool] = None,
    **kwargs,
):
    """Implements the "Object" primary base type of the ActivityStreams vocabulary.

    Args:
        _context (Union[str, list], optional): 
            The default value for @context. Defaults to "https://www.w3.org/ns/activitystreams".
        type (str, optional): 
            The name of the ActivityStreams type. Usually does not need to be changed. Defaults to "Object".
        id (Optional[str], optional): 
            The identifier for the object. Defaults to None.
        attachment (List[Union["Object", "Link", dict]], optional): 
            A list of resources attached to the object. Defaults to an empty list.
        attributedTo (Optional[Union["Object", "Link", str]], optional): 
            The resource indicating the creator of this object. Defaults to None.
        audience (Optional[Union["Object", "Link"]], optional): 
            The resource indicating the intended audience of this object. Defaults to None.
        content (Optional[str], optional): 
            The text representing the content of the object. Defaults to None.
        context (Optional[Union["Object", "Link"]], optional): 
            The resource indicating the context of the object. Defaults to None.
        name (Optional[str], optional): 
            The name of the object. Defaults to None.
        endTime (Optional[str], optional): 
            The end time of the event represented as an ISO8601 formatted string. Defaults to None.
        generator (Optional[Union["Object", "Link"]], optional): 
            The resource indicating the application that generated the object. Defaults to None.
        icon (Optional[Union["Image", "Link"]], optional): 
            The resource for the icon of the object. Defaults to None.
        image (Optional["Image"], optional): 
            The resource for the image of the object. Defaults to None.
        inReplyTo (Optional[Union["Image", "Link"]], optional): 
            The resource indicating the target of this reply. Defaults to None.
        location (Optional[Union["Image", "Link"]], optional): 
            The resource indicating the location of the object. Defaults to None.
        preview (Optional[Union["Object", "Link"]], optional): 
            The resource for the preview of the object. Defaults to None.
        published (Optional[str], optional): 
            The date and time when the object was published, represented as an ISO8601 formatted string. Defaults to None.
        replies (Optional["Collection"], optional): 
            A collection of replies to this object. Defaults to None.
        startTime (Optional[str], optional): 
            The start time of the event represented as an ISO8601 formatted string. Defaults to None.
        summary (Optional[str], optional): 
            A summary of the object. Defaults to None.
        tag (Optional[Union["Object", "Link"]], optional): 
            The resource indicating tags related to the object. Defaults to None.
        updated (Optional[str], optional): 
            The date and time when the object was last updated, represented as an ISO8601 formatted string. Defaults to None.
        url (Optional[Union[str, "Link"]], optional): 
            The URL of the object. Defaults to None.
        to (Optional[Union["Object", "Link"]], optional): 
            The resource indicating the recipient of the object. Defaults to None.
        bto (Optional[Union["Object", "Link"]], optional): 
            The resource indicating BCC recipients. Defaults to None.
        cc (Optional[Union["Object", "Link"]], optional): 
            The resource indicating CC recipients. Defaults to None.
        bcc (Optional[Union["Object", "Link"]], optional): 
            The resource indicating BCC recipients. Defaults to None.
        mediaType (Optional[str], optional): 
            The media type of the object. Defaults to None.
        duration (Optional[str], optional): 
            A string representing the duration of the object. Defaults to None.
        sensitive (Optional[bool], optional): 
            A flag indicating the sensitivity of the content. Defaults to None.

    """
    from .loader import load

    ctx = kwargs.get("@context")
    self._context = merge_contexts(_context, ctx) if ctx else []
    self.type = type
    self.id = id
    self.attachment = [
        load(attach) if isinstance(attach, dict) else attach
        for attach in attachment
    ]
    self.attributedTo = (
        load(attributedTo)
        if isinstance(attributedTo, dict)
        else attributedTo
    )
    self.audience = (
        load(audience) if isinstance(audience, dict) else audience
    )
    self.content = content
    self.context = (
        load(context) if isinstance(context, dict) else context
    )
    self.name = name
    self.endTime = (
        (
            endTime
            if isinstance(endTime, datetime.datetime.datetime)
            else datetime.datetime.datetime.strptime(
                endTime, "%Y-%m-%dT%H:%M:%S.%fZ"
            )
        )
        if endTime
        else endTime
    )
    self.generator = (
        load(generator) if isinstance(generator, dict) else generator
    )
    self.icon = load(icon) if isinstance(icon, dict) else icon
    self.image = image
    self.inReplyTo = (
        load(inReplyTo) if isinstance(inReplyTo, dict) else inReplyTo
    )
    self.location = (
        load(location) if isinstance(location, dict) else location
    )
    self.preview = (
        load(preview) if isinstance(preview, dict) else preview
    )
    if published:
        self.published = (
            (
                published
                if isinstance(published, datetime.datetime.datetime)
                else datetime.datetime.datetime.strptime(
                    published, "%Y-%m-%dT%H:%M:%S.%fZ"
                )
            )
            if published
            else published
        )
    else:
        self.published = datetime.utcnow()
    self.replies = (
        load(replies) if isinstance(replies, dict) else replies
    )
    self.startTime = (
        (
            startTime
            if isinstance(startTime, datetime.datetime.datetime)
            else datetime.datetime.datetime.strptime(
                startTime, "%Y-%m-%dT%H:%M:%S.%fZ"
            )
        )
        if startTime
        else startTime
    )
    self.summary = summary
    self.tag = load(tag) if isinstance(tag, dict) else tag
    self.updated = updated
    self.url = load(url) if isinstance(url, dict) else url
    self.to = load(to) if isinstance(to, dict) else to
    self.bto = load(bto) if isinstance(bto, dict) else bto
    self.cc = load(cc) if isinstance(cc, dict) else cc
    self.bcc = load(bcc) if isinstance(bcc, dict) else bcc
    self.mediaType = mediaType
    self.duration = duration

    # --- Extend Value
    self.sensitive = sensitive
    # ---

    self._extras = {}
    for key, value in kwargs.items():
        self._extras[key] = value

to_dict(_extras=None, build_context=True)

Outputs the current object as a dictionary.

Parameters:

Name Type Description Default
_extras Optional[dict]

Arguments used internally. It is not recommended that users change them.

None
build_context bool

Do we automatically build @context based on the arguments? Defaults to True.

True

Returns:

Name Type Description
dict

Objects converted to dictionaries

Source code in libs/apmodel/src/apmodel/core.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def to_dict(self, _extras: Optional[dict] = None, build_context: bool = True):
    """Outputs the current object as a dictionary.

    Args:
        _extras (Optional[dict], optional): Arguments used internally. It is not recommended that users change them.
        build_context (bool): Do we automatically build @context based on the arguments? Defaults to True.

    Returns:
        dict: Objects converted to dictionaries
    """
    if not _extras:
        _extras = self._extras.copy()
    instance_vars = vars(self).copy()

    ctx = self._context.copy()
    if build_context:
        attrs = dir(self)

        ctx2 = []
        ctx2_d = {}
        if _extras.get("publicKey") or "publicKey" in attrs:
            ctx2.append("https://w3id.org/security/v1")

        # Mastodon
        if _extras.get("featured") or "featured" in attrs:
            ctx2_d["featured"] = {
                "@id": "http://joinmastodon.org/ns#featured",
                "@type": "@id",
            }
        if _extras.get("featuredTags") or "featuredTags" in attrs:
            ctx2_d["featuredTags"] = {
                "@id": "http://joinmastodon.org/ns#featuredTags",
                "@type": "@id",
            }
        if _extras.get("discoverable") or "discoverable" in attrs:
            if not ctx2_d.get("toot"):
                ctx2_d["toot"] = "http://joinmastodon.org/ns#"
            ctx2_d["discoverable"] = "toot:discoverable"
        if _extras.get("discoverable") or "discoverable" in attrs:
            if not ctx2_d.get("toot"):
                ctx2_d["toot"] = "http://joinmastodon.org/ns#"
            ctx2_d["discoverable"] = "toot:discoverable"
        if (
            _extras.get("manuallyApprovesFollowers")
            or "manuallyApprovesFollowers" in attrs
        ):
            ctx2_d["manuallyApprovesFollowers"] = "as:manuallyApprovesFollowers"

        # Misskey
        if (
            _extras.get("_misskey_content")
            or _extras.get("_misskey_summary")
            or _extras.get("_misskey_quote")
            or _extras.get("_misskey_reaction")
            or _extras.get("_misskey_votes")
            or _extras.get("_misskey_talk")
            or _extras.get("isCat")
            or _extras.get("_misskey_followedMessage")
            or _extras.get("_misskey_requireSigninToViewContents")
            or _extras.get("_misskey_makeNotesFollowersOnlyBefore")
            or _extras.get("_misskey_makeNotesHiddenBefore")
            or _extras.get("_misskey_license")
        ):
            ctx2_d["misskey"] = "https://misskey-hub-net/ns#"

        ctx2.append(ctx2_d)

    context: Optional[list] = instance_vars.get("@context")
    if context:
        context = merge_contexts(merge_contexts(ctx, context), ctx2)
    else:
        context = ctx
    data: Dict[str, Any] = {
        "@context": context,
    }

    if self.content is not None:
        data["content"] = self.content

    for key, value in instance_vars.items():
        if value is not None:
            if not key.startswith("_") and key != "content":
                if isinstance(value, datetime.datetime.datetime):
                    data[key] = value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
                elif isinstance(value, Object):
                    data[key] = value.to_dict(_extras=value._extras)
                elif isinstance(value, list):
                    data[key] = [
                        item.to_dict(_extras=item._extras)
                        if hasattr(item, "to_dict")
                        else item
                        for item in value
                    ]
                elif (
                    isinstance(value, dict)
                    or isinstance(value, int)
                    or isinstance(value, bool)
                ):
                    data[key] = value
                else:
                    data[key] = str(value)

    _extras = _extras or {}
    for key, value in self._extras.items():
        if value is not None:
            if isinstance(value, datetime.datetime.datetime):
                data[key] = value.isoformat(timespec='microseconds').replace('+00:00', 'Z')
            elif isinstance(value, Object):
                data[key] = value.to_dict(_extras=value._extras)
            elif isinstance(value, list):
                data[key] = [
                    item.to_dict(_extras=item._extras)
                    if hasattr(item, "to_dict")
                    else item
                    for item in value
                ]
            elif (
                isinstance(value, dict)
                or isinstance(value, int)
                or isinstance(value, bool)
            ):
                data[key] = value
            else:
                data[key] = str(value)
    return data

loader

StreamsLoader

Source code in libs/apmodel/src/apmodel/loader.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
class StreamsLoader:
    @staticmethod
    @deprecated("StreamsLoader.load is deprecated; use loader.load.")
    def load(
        object: dict[Any, Any], custom_mapper: dict = fedi_mapper
    ) -> Object | Link | Any | dict:  # type: ignore
        """convert json object to model

        Args:
            object (dict[Any, Any]): json object
            custom_mapper (dict, optional): Models available at the time of loading. Defaults to fedi_mapper.

        Returns:
            Object | Link | dict | Any: An object converted from json. If there is no corresponding object, the dictionary type is returned.
        """
        return load(object, custom_mapper)

load(object, custom_mapper=fedi_mapper) staticmethod

convert json object to model

Parameters:

Name Type Description Default
object dict[Any, Any]

json object

required
custom_mapper dict

Models available at the time of loading. Defaults to fedi_mapper.

fedi_mapper

Returns:

Type Description
Object | Link | Any | dict

Object | Link | dict | Any: An object converted from json. If there is no corresponding object, the dictionary type is returned.

Source code in libs/apmodel/src/apmodel/loader.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
@staticmethod
@deprecated("StreamsLoader.load is deprecated; use loader.load.")
def load(
    object: dict[Any, Any], custom_mapper: dict = fedi_mapper
) -> Object | Link | Any | dict:  # type: ignore
    """convert json object to model

    Args:
        object (dict[Any, Any]): json object
        custom_mapper (dict, optional): Models available at the time of loading. Defaults to fedi_mapper.

    Returns:
        Object | Link | dict | Any: An object converted from json. If there is no corresponding object, the dictionary type is returned.
    """
    return load(object, custom_mapper)

load(object, custom_mapper=fedi_mapper)

convert json object to model

Parameters:

Name Type Description Default
object dict[Any, Any]

json object

required
custom_mapper dict

Models available at the time of loading. Defaults to fedi_mapper.

fedi_mapper

Returns:

Type Description
Object | Link | dict | Any

Object | Link | dict | Any: An object converted from json. If there is no corresponding object, the dictionary type is returned.

Source code in libs/apmodel/src/apmodel/loader.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def load(
    object: dict[Any, Any], custom_mapper: dict = fedi_mapper
) -> Object | Link | dict | Any:  # type: ignore
    """convert json object to model

    Args:
        object (dict[Any, Any]): json object
        custom_mapper (dict, optional): Models available at the time of loading. Defaults to fedi_mapper.

    Returns:
        Object | Link | dict | Any: An object converted from json. If there is no corresponding object, the dictionary type is returned.
    """
    type = object.get("type")
    cls = custom_mapper.get(type)
    if cls:
        return cls(**object)
    return object