astreams

package module
v0.7.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 7, 2024 License: AGPL-3.0 Imports: 9 Imported by: 0

README

astreams

A hand-crafted implementation of the Activity Streams 2.0 specification in Go, especially suitable for projects implementing ActivityPub.

Usage

Documentation

Example Activity Streams 2.0 object:

object := `
{
  "@context": "https://www.w3.org/ns/activitystreams",
  "summary": "Martin's recent activities",
  "type": "Collection",
  "totalItems": 1,
  "items" : [
    {
      "type": "Add",
      "published": "2011-02-10T15:04:55Z",
      "generator": "http://example.org/activities-app",
      "nameMap": {
        "en": "Martin added a new image to his album.",
        "ga": "Martin phost le fisean nua a albam."
      },
      "actor": {
        "type": "Person",
        "id": "http://www.test.example/martin",
        "name": "Martin Smith",
        "url": "http://example.org/martin",
        "image": {
          "type": "Link",
          "href": "http://example.org/martin/image",
          "mediaType": "image/jpeg",
          "width": 250,
          "height": 250
        }
      },
      "object" : {
        "name": "My fluffy cat",
        "type": "Image",
        "id": "http://example.org/album/máiréad.jpg",
        "preview": {
          "type": "Link",
          "href": "http://example.org/album/máiréad.jpg",
          "mediaType": "image/jpeg"
        },
        "url": [
          {
            "type": "Link",
            "href": "http://example.org/album/máiréad.jpg",
            "mediaType": "image/jpeg"
          },
          {
            "type": "Link",
            "href": "http://example.org/album/máiréad.png",
            "mediaType": "image/png"
          }
        ]
      },
      "target": {
        "type": "Collection",
        "id": "http://example.org/album/",
        "nameMap": {
          "en": "Martin's Photo Album",
          "ga": "Grianghraif Mairtin"
        },
        "image": {
          "type": "Link",
          "href": "http://example.org/album/thumbnail.jpg",
          "mediaType": "image/jpeg"
        }
      }
    }
  ]
}
`

Unmarshaling Activity Streams 2.0 JSON objects into Go objects:

// Unmarshal from AS 2.0 JSON
var exobj astreams.Collection
err := json.Unmarshal([]byte(object), &exobj)
if err != nil {
	log.Println(err)
}

↑ An example of unmarshaling into an astreams.Collection object.

Marshaling Go objects into Activity Streams 2.0 JSON objects:

// Marshal to AS 2.0 JSON
jsB, err := json.Marshal(&exobj) // note the use of a pointer here; astreams MarshalJSON methods are defined on pointer receivers
if err != nil {
	log.Println(err)
}

↑ Marshaling the same astreams.Collection back into the original ActivityStreams 2.0 JSON is equally as straightforward.

Contributing

Contributions are welcome. If you've found a bug, or have a feature request, don't hesitate to open an issue.

Documentation

Overview

Package astreams implements JSON serialization/deserialization support for the ActivityStreams 2.0 vocabulary. Simply use json.Marshal/json.Unmarshal on AS 2.0 compliant objects to obtain their JSON/Go representation respectively.

Indirect object references such as a link to an outbox collection within an actor profile need to be fetched explicitly and parsed as a separate object.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConcreteType

func ConcreteType(t ObjectLinker) (reflectType, astreamsType string)

ConcreteType returns both, the type name obtained using reflection, and the Type property of the Object / Link JSON payload. The object's own Type property is going to be more specific, so use that where useful.

func DecodeJSON added in v0.6.0

func DecodeJSON[T ActivityStreamer](jsonPayload io.Reader) (T, error)

DecodeJSON is the generic unmarshaller for any valid ActivityStreams 2.0 object

func EncodeJSON added in v0.6.0

func EncodeJSON[T ActivityStreamer](toEncode T) ([]byte, error)

EncodeJSON is the generic marshaller for any valid ActivityStreams 2.0 object

Types

type Accept

type Accept = Activity

Extended 'Activity' types

type Activity

type Activity struct {
	Object
	Actor          *ObjectOrLinkOrString `json:"actor,omitempty"`
	ActivityObject *ObjectOrLinkOrString `json:"object,omitempty"` // the 'object' property of Activity
	Target         *ObjectOrLinkOrString `json:"target,omitempty"`
	Result         *ObjectOrLinkOrString `json:"result,omitempty"`
	Origin         *ObjectOrLinkOrString `json:"origin,omitempty"`
	Instrument     *ObjectOrLinkOrString `json:"instrument,omitempty"`
}

type ActivityStreamer added in v0.5.0

ActivityStreamer is a generic type constraint representing all valid Activity Streams 2.0 types

type Actor

type Actor struct {
	Object
	PublicKey                 *PublicKey                   `json:"publicKey,omitempty"`
	Inbox                     *StringWithOrderedCollection `json:"inbox,omitempty"`
	Outbox                    *StringWithOrderedCollection `json:"outbox,omitempty"`
	Followers                 *StringWithOrderedCollection `json:"followers,omitempty"`
	Following                 *StringWithOrderedCollection `json:"following,omitempty"`
	Liked                     *StringWithOrderedCollection `json:"liked,omitempty"`
	Streams                   *ObjectOrLinkOrString        `json:"streams,omitempty"`
	PreferredUsername         string                       `json:"preferredUsername,omitempty"`
	ManuallyApprovesFollowers bool                         `json:"manuallyApprovesFollowers,omitempty"`
	EndpointsOrURI            *EndpointsOrString           `json:"endpoints,omitempty"`
}

type Add

type Add = Activity

type Announce

type Announce = Activity

type Application

type Application = Actor

Extended 'Actor' types

type Arrive

type Arrive = IntransitiveActivity

type Article

type Article = Object

Extended 'Object' types

type Audio

type Audio = Document

type Block

type Block = Ignore

type Collection

type Collection struct {
	Object
	TotalItems int                   `json:"totalItems,omitempty"`
	Current    *ObjectOrLinkOrString `json:"current,omitempty"`
	First      *ObjectOrLinkOrString `json:"first,omitempty"`
	Last       *ObjectOrLinkOrString `json:"last,omitempty"`
	Items      *ObjectOrLinkOrString `json:"items,omitempty"`
}

Collection is provided for spec compliance, prefer OrderedCollection

func (*Collection) MarshalJSON added in v0.7.0

func (col *Collection) MarshalJSON() ([]byte, error)

Implements https://golang.org/pkg/encoding/json/#Marshal

type CollectionPage

type CollectionPage struct {
	Collection
	PartOf *ObjectOrLinkOrString `json:"partOf,omitempty"`
	Next   *ObjectOrLinkOrString `json:"next,omitempty"`
	Prev   *ObjectOrLinkOrString `json:"prev,omitempty"`
}

CollectionPage is provided for spec compliance, prefer OrderedCollectionPage

func (*CollectionPage) MarshalJSON added in v0.7.0

func (colp *CollectionPage) MarshalJSON() ([]byte, error)

Implements https://golang.org/pkg/encoding/json/#Marshal

type Create

type Create = Activity

type Delete

type Delete = Activity

type Dislike

type Dislike = Activity

type Document

type Document = Object

type Endpoint

type Endpoint struct {
	ProxyUrl                   string                       `json:"proxyUrl,omitempty"`
	OauthAuthorizationEndpoint string                       `json:"oauthAuthorizationEndpoint,omitempty"`
	OauthTokenEndpoint         string                       `json:"oauthTokenEndpoint,omitempty"`
	ProvideClientKey           string                       `json:"provideClientKey,omitempty"`
	SignClientKey              string                       `json:"signClientKey,omitempty"`
	SharedInbox                *StringWithOrderedCollection `json:"sharedInbox,omitempty"`
}

type EndpointsOrString added in v0.3.0

type EndpointsOrString struct {
	URL       string
	Endpoints Endpoint
}

func (*EndpointsOrString) MarshalJSON added in v0.3.0

func (enp *EndpointsOrString) MarshalJSON() ([]byte, error)

Implements https://golang.org/pkg/encoding/json/#Marshal

func (*EndpointsOrString) String added in v0.3.0

func (enp *EndpointsOrString) String() string

Implements https://golang.org/pkg/fmt/#Stringer

func (*EndpointsOrString) UnmarshalJSON added in v0.3.0

func (enp *EndpointsOrString) UnmarshalJSON(data []byte) error

Implements https://golang.org/pkg/encoding/json/#Unmarshaler

type Event

type Event = Object

type Flag

type Flag = Activity

type Follow

type Follow = Activity

type Group

type Group = Actor

type Hashtag

type Hashtag = Link

type Icon

type Icon struct {
	Object
	Width  int `json:"width"`
	Height int `json:"height"`
}

type Icons

type Icons struct {
	URL   string
	Icons []Icon
}

Icons is a type representing the possible ActivityPub icon values

func (*Icons) MarshalJSON

func (ics *Icons) MarshalJSON() ([]byte, error)

Implements https://golang.org/pkg/encoding/json/#Marshal

func (*Icons) String

func (ics *Icons) String() string

Implements https://golang.org/pkg/fmt/#Stringer

func (*Icons) UnmarshalJSON

func (ics *Icons) UnmarshalJSON(data []byte) error

Implements https://golang.org/pkg/encoding/json/#Unmarshaler

type Ignore

type Ignore = Activity

type Image

type Image struct {
	Document
	Width  int `json:"width,omitempty"`
	Height int `json:"height,omitempty"`
}

type IntransitiveActivity

type IntransitiveActivity struct {
	Object
	Actor      *ObjectOrLinkOrString `json:"actor,omitempty"`
	Target     *ObjectOrLinkOrString `json:"target,omitempty"`
	Result     *ObjectOrLinkOrString `json:"result,omitempty"`
	Origin     *ObjectOrLinkOrString `json:"origin,omitempty"`
	Instrument *ObjectOrLinkOrString `json:"instrument,omitempty"`
}

type Invite

type Invite = Offer

type Join

type Join = Activity

type JsonPayload added in v0.6.0

type JsonPayload struct {
	Type string `json:"type"`
}

func DecodePayloadObjectType added in v0.6.0

func DecodePayloadObjectType(payload io.Reader) (JsonPayload, error)

DecodePayloadObjectType can be used to check the specific type of unknown JSON payload

payloadMeta, err := DecodePayloadObjectType(payload)
if err != nil {
	//
}

switch payloadMeta.Type {
case "Note":
	var note Note
	err = json.Unmarshal([]byte(tc), &note)
	if err != nil {
		//
	}
case "Offer":
	var offer Offer
	err = json.Unmarshal([]byte(tc), &offer)
	if err != nil {
		//
	}
case "Person":
	var person Person
	err = json.Unmarshal([]byte(tc), &person)
	if err != nil {
		//
	}

	if person.Name == "" {
		//
	}
default:
	var obj ObjectOrLinkOrString
	err = json.Unmarshal([]byte(tc), &obj)
	if err != nil {
		//
	}
}

type Leave

type Leave = Activity

type Like

type Like = Activity
type Link struct {
	ASContext  *ObjectOrLinkOrString `json:"@context,omitempty"`
	ASLanguage string                `json:"@language,omitempty"`
	Type       string                `json:"type"`
	Href       string                `json:"href,omitempty"`
	Hreflang   string                `json:"hreflang,omitempty"`
	Rel        []string              `json:"rel,omitempty"`
	MediaType  string                `json:"mediaType,omitempty"`
	Height     int                   `json:"height,omitempty"`
	Width      int                   `json:"width,omitempty"`
	Name       string                `json:"name,omitempty"`
	NameMap    map[string]string     `json:"nameMap,omitempty"`
	Value      string                `json:"value,omitempty"`
	Preview    *ObjectOrLinkOrString `json:"preview,omitempty"`
	Published  *time.Time            `json:"published,omitempty"`
}

Link represents the base ActivityStreams Link and all of its properties Other Link types extend it

func (l Link) GetLink() *Link

func (Link) GetObject

func (l Link) GetObject() *Object
func (l Link) IsLink() bool

func (Link) IsObject

func (l Link) IsObject() bool

Implements 'ObjectLinker' interface for 'Link'

type Listen

type Listen = Activity

type Location

type Location struct {
	Object
	Longitude float32 `json:"longitude,omitempty"`
	Latitude  float32 `json:"latitude,omitempty"`
	Altitude  int     `json:"altitude,omitempty"`
	Units     string  `json:"units,omitempty"`
}

func (*Location) String

func (loc *Location) String() string

Implements https://golang.org/pkg/fmt/#Stringer

type Mention

type Mention = Link

Extended 'Link' types

type Move

type Move = Activity

type Note

type Note = Object

type Object

type Object struct {
	ASContext    *ObjectOrLinkOrString `json:"@context,omitempty"`
	ASLanguage   string                `json:"@language,omitempty"`
	Schema       string                `json:"schema,omitempty"`
	ID           string                `json:"id,omitempty"`
	Type         string                `json:"type,omitempty"`
	AtType       string                `json:"@type,omitempty"`
	Summary      string                `json:"summary,omitempty"`
	SummaryMap   map[string]string     `json:"summaryMap,omitempty"`
	AtID         string                `json:"@id,omitempty"`
	Name         string                `json:"name,omitempty"`
	NameMap      map[string]string     `json:"nameMap,omitempty"`
	AlsoKnownAs  *ObjectOrLinkOrString `json:"alsoKnownAs,omitempty"`
	MovedTo      *ObjectOrLinkOrString `json:"movedTo,omitempty"`
	Attachment   *ObjectOrLinkOrString `json:"attachment,omitempty"`
	AttributedTo *ObjectOrLinkOrString `json:"attributedTo,omitempty"`
	Audience     *ObjectOrLinkOrString `json:"audience,omitempty"`
	Content      string                `json:"content,omitempty"` // needs to be parsed safely ie by https://golang.org/pkg/html/template
	ContentMap   map[string]string     `json:"contentMap,omitempty"`
	Source       *ObjectOrLinkOrString `json:"source,omitempty"`
	Context      *ObjectOrLinkOrString `json:"context,omitempty"`
	StartTime    *time.Time            `json:"startTime,omitempty"`
	EndTime      *time.Time            `json:"endTime,omitempty"`
	Generator    *ObjectOrLinkOrString `json:"generator,omitempty"`
	Featured     *ObjectOrLinkOrString `json:"featured,omitempty"`
	Likes        *ObjectOrLinkOrString `json:"likes,omitempty"`
	Shares       *ObjectOrLinkOrString `json:"shares,omitempty"`
	Icon         *ObjectOrLinkOrString `json:"icon,omitempty"`
	Image        *ObjectOrLinkOrString `json:"image,omitempty"`
	InReplyTo    *ObjectOrLinkOrString `json:"inReplyTo,omitempty"`
	Location     *ObjectOrLinkOrString `json:"location,omitempty"`
	Preview      *ObjectOrLinkOrString `json:"preview,omitempty"`
	Published    *time.Time            `json:"published,omitempty"`
	Replies      *OrderedCollection    `json:"replies,omitempty"`
	Tag          *ObjectOrLinkOrString `json:"tag,omitempty"`
	Updated      *time.Time            `json:"updated,omitempty"`
	URL          *ObjectOrLinkOrString `json:"url,omitempty"`
	To           *ObjectOrLinkOrString `json:"to,omitempty"`
	Bto          *ObjectOrLinkOrString `json:"bto,omitempty"`
	Cc           *ObjectOrLinkOrString `json:"cc,omitempty"`
	Bcc          *ObjectOrLinkOrString `json:"bcc,omitempty"`
	MediaType    string                `json:"mediaType,omitempty"`
	Duration     string                `json:"duration,omitempty"` // xsd:duration
}

Object represents the base ActivityStreams Object and all of its properties Most of the other types extend Object

func (o Object) GetLink() *Link

func (Object) GetObject

func (o Object) GetObject() *Object
func (o Object) IsLink() bool

func (Object) IsObject

func (o Object) IsObject() bool

Implements 'ObjectLinker' interface for 'Object'

type ObjectLinker added in v0.6.0

type ObjectLinker interface {
	IsObject() bool
	IsLink() bool
	GetObject() *Object
	GetLink() *Link
}

ObjectLinker can be either a (sub)type of 'Object' or a (sub)type of 'Link'

type ObjectOrLink []ObjectLinker

ObjectOrLink is a wrapper type that represents any valid ActivityStreams 2.0 object or link Single objects are still presented as slices, but with a single element

func (*ObjectOrLink) MarshalJSON

func (ol *ObjectOrLink) MarshalJSON() ([]byte, error)

Implements https://golang.org/pkg/encoding/json/#Marshal

func (*ObjectOrLink) UnmarshalJSON

func (ol *ObjectOrLink) UnmarshalJSON(data []byte) error

Implements https://golang.org/pkg/encoding/json/#Unmarshaler

type ObjectOrLinkOrString

type ObjectOrLinkOrString struct {
	URL    []string
	Target ObjectOrLink
}

ObjectOrLinkOrString is a type that can either represent simple string URL(s) or an Object/Link slice

func (*ObjectOrLinkOrString) MarshalJSON

func (ols *ObjectOrLinkOrString) MarshalJSON() ([]byte, error)

Implements https://golang.org/pkg/encoding/json/#Marshal

func (*ObjectOrLinkOrString) String

func (ols *ObjectOrLinkOrString) String() string

Implements https://golang.org/pkg/fmt/#Stringer

func (*ObjectOrLinkOrString) UnmarshalJSON

func (ols *ObjectOrLinkOrString) UnmarshalJSON(data []byte) error

Implements https://golang.org/pkg/encoding/json/#Unmarshaler

type Offer

type Offer = Activity

type OrderedCollection

type OrderedCollection struct {
	Object
	TotalItems   int                   `json:"totalItems"`
	Current      *ObjectOrLinkOrString `json:"current,omitempty"`
	First        *ObjectOrLinkOrString `json:"first,omitempty"`
	Last         *ObjectOrLinkOrString `json:"last,omitempty"`
	OrderedItems *ObjectOrLinkOrString `json:"orderedItems"`
}

OrderedCollection implements https://golang.org/pkg/sort/#Interface

func (*OrderedCollection) Len

func (oc *OrderedCollection) Len() int

func (*OrderedCollection) Less

func (oc *OrderedCollection) Less(i, j int) bool

func (*OrderedCollection) MarshalJSON added in v0.7.0

func (oc *OrderedCollection) MarshalJSON() ([]byte, error)

Implements https://golang.org/pkg/encoding/json/#Marshal

func (*OrderedCollection) SortByUpdated

func (oc *OrderedCollection) SortByUpdated()

SortByUpdated sorts OrderedCollection objects by Updated rather than Published date

func (*OrderedCollection) String

func (oc *OrderedCollection) String() string

Implements https://golang.org/pkg/fmt/#Stringer

func (*OrderedCollection) Swap

func (oc *OrderedCollection) Swap(i, j int)

type OrderedCollectionPage

type OrderedCollectionPage struct {
	OrderedCollection
	PartOf     *ObjectOrLinkOrString `json:"partOf,omitempty"`
	Next       *ObjectOrLinkOrString `json:"next,omitempty"`
	Prev       *ObjectOrLinkOrString `json:"prev,omitempty"`
	StartIndex uint                  `json:"startIndex,omitempty"`
}

OrderedCollectionPage implements https://golang.org/pkg/sort/#Interface

func (*OrderedCollectionPage) MarshalJSON added in v0.7.0

func (ocolp *OrderedCollectionPage) MarshalJSON() ([]byte, error)

Implements https://golang.org/pkg/encoding/json/#Marshal

type Organization

type Organization = Actor

type Page

type Page = Document

type Person

type Person = Actor

type Place

type Place struct {
	Location
	Accuracy float32 `json:"accuracy,omitempty"`
	Radius   float32 `json:"radius,omitempty"`
}

type Profile

type Profile struct {
	Object
	Describes ObjectOrLinkOrString `json:"describes,omitempty"`
}

type PropertyValue

type PropertyValue = Link

type PublicKey

type PublicKey struct {
	Object
	ID           string `json:"id"`
	Owner        string `json:"owner"`
	PublicKeyPem string `json:"publicKeyPem"`
}

type Question

type Question struct {
	IntransitiveActivity
	// only OneOf or AnyOf can be set, not both
	OneOf  *ObjectOrLinkOrString `json:"oneOf,omitempty"`
	AnyOf  *ObjectOrLinkOrString `json:"anyOf,omitempty"`
	Closed *time.Time            `json:"closed,omitempty"`
}

type Read

type Read = Activity

type Reject

type Reject = Activity

type Relationship

type Relationship struct {
	Object
	Subject            *ObjectOrLinkOrString `json:"subject,omitempty"`
	Relationship       string                `json:"relationship,omitempty"`
	RelationshipObject *ObjectOrLinkOrString `json:"object"`
}

type Remove

type Remove = Activity

type Service

type Service = Actor

type StringWithCollection

type StringWithCollection struct {
	URL        string
	Collection Collection
}

StringWithCollection can store a string URL pointing to a Collection, which can itself be stored in the struct

func (*StringWithCollection) MarshalJSON

func (sc *StringWithCollection) MarshalJSON() ([]byte, error)

Implements https://golang.org/pkg/encoding/json/#Marshal

func (*StringWithCollection) String

func (sc *StringWithCollection) String() string

Implements https://golang.org/pkg/fmt/#Stringer

func (*StringWithCollection) UnmarshalJSON

func (sc *StringWithCollection) UnmarshalJSON(data []byte) error

Implements https://golang.org/pkg/encoding/json/#Unmarshaler

type StringWithOrderedCollection

type StringWithOrderedCollection struct {
	URL           string
	OrdCollection OrderedCollection
}

StringWithOrderedCollection can store a string URL pointing to an OrderedCollection, which can itself be stored in the struct

func (*StringWithOrderedCollection) MarshalJSON

func (soc *StringWithOrderedCollection) MarshalJSON() ([]byte, error)

Implements https://golang.org/pkg/encoding/json/#Marshal

func (*StringWithOrderedCollection) String

func (soc *StringWithOrderedCollection) String() string

Implements https://golang.org/pkg/fmt/#Stringer

func (*StringWithOrderedCollection) UnmarshalJSON

func (soc *StringWithOrderedCollection) UnmarshalJSON(data []byte) error

Implements https://golang.org/pkg/encoding/json/#Unmarshaler

type TentativeAccept

type TentativeAccept = Accept

type TentativeReject

type TentativeReject = Reject

type Tombstone

type Tombstone struct {
	Object
	FormerType string     `json:"formerType,omitempty"`
	Deleted    *time.Time `json:"deleted,omitempty"`
}

type Travel

type Travel = IntransitiveActivity

type Undo

type Undo = Activity

type Update

type Update = Activity

type Video

type Video = Document

type View

type View = Activity

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL