Debian Codegraph @

actor.go

raw symbols SCIP
1 package activitypub
2
3 import (
4 "bytes"
5 "encoding/gob"
6 "encoding/json"
7 "fmt"
8 "time"
9
10 "github.com/valyala/fastjson"
11 )
12
13 // CanReceiveActivities Types
14 const (
15 ApplicationType ActivityVocabularyType = "Application"
16 GroupType ActivityVocabularyType = "Group"
17 OrganizationType ActivityVocabularyType = "Organization"
18 PersonType ActivityVocabularyType = "Person"
19 ServiceType ActivityVocabularyType = "Service"
20 )
21
22 // ActorTypes represent the valid Actor types.
23 var ActorTypes = ActivityVocabularyTypes{
24 ApplicationType,
25 GroupType,
26 OrganizationType,
27 PersonType,
28 ServiceType,
29 }
30
31 // CanReceiveActivities is generally one of the ActivityStreams Actor Types, but they don't have to be.
32 // For example, a Profile object might be used as an actor, or a type from an ActivityStreams extension.
33 // Actors are retrieved like any other Object in ActivityPub.
34 // Like other ActivityStreams objects, actors have an id, which is a URI.
35 type CanReceiveActivities Item
36
37 type Actors interface {
38 Actor
39 }
40
41 // Actor is generally one of the ActivityStreams actor Types, but they don't have to be.
42 // For example, a Profile object might be used as an actor, or a type from an ActivityStreams extension.
43 // Actors are retrieved like any other Object in ActivityPub.
44 // Like other ActivityStreams objects, actors have an id, which is a URI.
45 type Actor struct {
46 // ID provides the globally unique identifier for anActivity Pub Object or Link.
47 ID ID `jsonld:"id,omitempty"`
48 // Type identifies the Activity Pub Object or Link type. Multiple values may be specified.
49 Type Typer `jsonld:"type,omitempty"`
50 // Name a simple, human-readable, plain-text name for the object.
51 // HTML markup MUST NOT be included. The name MAY be expressed using multiple language-tagged values.
52 Name NaturalLanguageValues `jsonld:"name,omitempty,collapsible"`
53 // Attachment identifies a resource attached or related to an object that potentially requires special handling.
54 // The intent is to provide a model that is at least semantically similar to attachments in email.
55 Attachment Item `jsonld:"attachment,omitempty"`
56 // AttributedTo identifies one or more entities to which this object is attributed. The attributed entities might not be Actors.
57 // For instance, an object might be attributed to the completion of another activity.
58 AttributedTo Item `jsonld:"attributedTo,omitempty"`
59 // Audience identifies one or more entities that represent the total population of entities
60 // for which the object can considered to be relevant.
61 Audience ItemCollection `jsonld:"audience,omitempty"`
62 // Content or textual representation of the Activity Pub Object encoded as a JSON string.
63 // By default, the value of content is HTML.
64 // The mediaType property can be used in the object to indicate a different content type.
65 // (The content MAY be expressed using multiple language-tagged values.)
66 Content NaturalLanguageValues `jsonld:"content,omitempty,collapsible"`
67 // Context identifies the context within which the object exists or an activity was performed.
68 // The notion of "context" used is intentionally vague.
69 // The intended function is to serve as a means of grouping objects and activities that share a
70 // common originating context or purpose. An example could be all activities relating to a common project or event.
71 Context Item `jsonld:"context,omitempty"`
72 // MediaType when used on an Object, identifies the MIME media type of the value of the content property.
73 // If not specified, the content property is assumed to contain text/html content.
74 MediaType MimeType `jsonld:"mediaType,omitempty"`
75 // EndTime the date and time describing the actual or expected ending time of the object.
76 // When used with an Activity object, for instance, the endTime property specifies the moment
77 // the activity concluded or is expected to conclude.
78 EndTime time.Time `jsonld:"endTime,omitempty"`
79 // Generator identifies the entity (e.g. an application) that generated the object.
80 Generator Item `jsonld:"generator,omitempty"`
81 // Icon indicates an entity that describes an icon for this object.
82 // The image should have an aspect ratio of one (horizontal) to one (vertical)
83 // and should be suitable for presentation at a small size.
84 Icon Item `jsonld:"icon,omitempty"`
85 // Image indicates an entity that describes an image for this object.
86 // Unlike the icon property, there are no aspect ratio or display size limitations assumed.
87 Image Item `jsonld:"image,omitempty"`
88 // InReplyTo indicates one or more entities for which this object is considered a response.
89 InReplyTo Item `jsonld:"inReplyTo,omitempty"`
90 // Location indicates one or more physical or logical locations associated with the object.
91 Location Item `jsonld:"location,omitempty"`
92 // Preview identifies an entity that provides a preview of this object.
93 Preview Item `jsonld:"preview,omitempty"`
94 // Published the date and time at which the object was published
95 Published time.Time `jsonld:"published,omitempty"`
96 // Replies identifies a Collection containing objects considered to be responses to this object.
97 Replies Item `jsonld:"replies,omitempty"`
98 // StartTime the date and time describing the actual or expected starting time of the object.
99 // When used with an Activity object, for instance, the startTime property specifies
100 // the moment the activity began or is scheduled to begin.
101 StartTime time.Time `jsonld:"startTime,omitempty"`
102 // Summary a natural language summarization of the object encoded as HTML.
103 // *Multiple language tagged summaries may be provided.)
104 Summary NaturalLanguageValues `jsonld:"summary,omitempty,collapsible"`
105 // Tag one or more "tags" that have been associated with an objects. A tag can be any kind of Activity Pub Object.
106 // The key difference between attachment and tag is that the former implies association by inclusion,
107 // while the latter implies associated by reference.
108 Tag ItemCollection `jsonld:"tag,omitempty"`
109 // Updated the date and time at which the object was updated
110 Updated time.Time `jsonld:"updated,omitempty"`
111 // URL identifies one or more links to representations of the object
112 URL Item `jsonld:"url,omitempty"`
113 // To identifies an entity considered to be part of the public primary audience of an Activity Pub Object
114 To ItemCollection `jsonld:"to,omitempty"`
115 // Bto identifies anActivity Pub Object that is part of the private primary audience of this Activity Pub Object.
116 Bto ItemCollection `jsonld:"bto,omitempty"`
117 // CC identifies anActivity Pub Object that is part of the public secondary audience of this Activity Pub Object.
118 CC ItemCollection `jsonld:"cc,omitempty"`
119 // BCC identifies one or more Objects that are part of the private secondary audience of this Activity Pub Object.
120 BCC ItemCollection `jsonld:"bcc,omitempty"`
121 // Duration when the object describes a time-bound resource, such as an audio or video, a meeting, etc,
122 // the duration property indicates the object's approximate duration.
123 // The value must be expressed as an xsd:duration as defined by [ xmlschema11-2],
124 // section 3.3.6 (e.g. a period of 5 seconds is represented as "PT5S").
125 Duration time.Duration `jsonld:"duration,omitempty"`
126 // This is a list of all Like activities with this object as the object property, added as a side effect.
127 // The likes collection MUST be either an OrderedCollection or a Collection and MAY be filtered on privileges
128 // of an authenticated user or as appropriate when no authentication is given.
129 Likes Item `jsonld:"likes,omitempty"`
130 // This is a list of all Announce activities with this object as the object property, added as a side effect.
131 // The shares collection MUST be either an OrderedCollection or a Collection and MAY be filtered on privileges
132 // of an authenticated user or as appropriate when no authentication is given.
133 Shares Item `jsonld:"shares,omitempty"`
134 // Source property is intended to convey some sort of source from which the content markup was derived,
135 // as a form of provenance, or to support future editing by clients.
136 // In general, clients do the conversion from source to content, not the other way around.
137 Source Source `jsonld:"source,omitempty"`
138 // A reference to an [ActivityStreams] OrderedCollection comprised of all the messages received by the actor;
139 // see 5.2 Inbox.
140 Inbox Item `jsonld:"inbox,omitempty"`
141 // An [ActivityStreams] OrderedCollection comprised of all the messages produced by the actor;
142 // see 5.1 outbox.
143 Outbox Item `jsonld:"outbox,omitempty"`
144 // A link to an [ActivityStreams] collection of the actors that this actor is following;
145 // see 5.4 Following Collection
146 Following Item `jsonld:"following,omitempty"`
147 // A link to an [ActivityStreams] collection of the actors that follow this actor;
148 // see 5.3 Followers Collection.
149 Followers Item `jsonld:"followers,omitempty"`
150 // A link to an [ActivityStreams] collection of objects this actor has liked;
151 // see 5.5 Liked Collection.
152 Liked Item `jsonld:"liked,omitempty"`
153 // A short username which may be used to refer to the actor, with no uniqueness guarantees.
154 PreferredUsername NaturalLanguageValues `jsonld:"preferredUsername,omitempty,collapsible"`
155 // A json object which maps additional (typically server/domain-wide) endpoints which may be useful either
156 // for this actor or someone referencing this actor.
157 // This mapping may be nested inside the actor document as the value or may be a link
158 // to a JSON-LD document with these properties.
159 Endpoints *Endpoints `jsonld:"endpoints,omitempty"`
160 // A list of supplementary Collections which may be of interest.
161 Streams ItemCollection `jsonld:"streams,omitempty"`
162 PublicKey PublicKey `jsonld:"publicKey,omitempty"`
163 }
164
165 // GetID returns the ID corresponding to the current Actor
166 func (a Actor) GetID() ID {
167 return a.ID
168 }
169
170 // GetLink returns the IRI corresponding to the current Actor
171 func (a Actor) GetLink() IRI {
172 return IRI(a.ID)
173 }
174
175 // GetType returns the type of the current Actor
176 func (a Actor) GetType() Typer {
177 return a.Type
178 }
179
180 // IsLink validates if currentActivity Pub Actor is a Link
181 func (a Actor) IsLink() bool {
182 return false
183 }
184
185 // IsObject validates if currentActivity Pub Actor is an Object
186 func (a Actor) IsObject() bool {
187 return true
188 }
189
190 // IsCollection returns false for Actor Objects
191 func (a Actor) IsCollection() bool {
192 return false
193 }
194
195 // Match returns whether the receiver matches the ActivityVocabularyType arguments.
196 func (a Actor) Match(tt ...ActivityVocabularyType) bool {
197 return ActivityVocabularyTypes(tt).Match(a.Type)
198 }
199
200 // PublicKey holds the ActivityPub compatible public key data
201 // The document reference can be found at:
202 // https://w3c-ccg.github.io/security-vocab/#publicKey
203 type PublicKey struct {
204 ID ID `jsonld:"id,omitempty"`
205 Owner IRI `jsonld:"owner,omitempty"`
206 PublicKeyPem string `jsonld:"publicKeyPem,omitempty"`
207 }
208
209 func (p *PublicKey) UnmarshalJSON(data []byte) error {
210 par := fastjson.Parser{}
211 val, err := par.ParseBytes(data)
212 if err != nil {
213 return err
214 }
215
216 return JSONLoadPublicKey(val, p)
217 }
218
219 func (p PublicKey) MarshalJSON() ([]byte, error) {
220 b := make([]byte, 0)
221 notEmpty := true
222 JSONWrite(&b, '{')
223 if v, err := p.ID.MarshalJSON(); err == nil && len(v) > 0 {
224 notEmpty = !JSONWriteProp(&b, "id", v)
225 }
226 if len(p.Owner) > 0 {
227 notEmpty = JSONWriteIRIProp(&b, "owner", p.Owner) || notEmpty
228 }
229 if len(p.PublicKeyPem) > 0 {
230 if pem, err := json.Marshal(p.PublicKeyPem); err == nil {
231 notEmpty = JSONWriteProp(&b, "publicKeyPem", pem) || notEmpty
232 }
233 }
234
235 if notEmpty {
236 JSONWrite(&b, '}')
237 return b, nil
238 }
239 return nil, nil
240 }
241
242 // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
243 func (a *Actor) UnmarshalBinary(data []byte) error {
244 return a.GobDecode(data)
245 }
246
247 // MarshalBinary implements the encoding.BinaryMarshaler interface.
248 func (a Actor) MarshalBinary() ([]byte, error) {
249 return a.GobEncode()
250 }
251
252 func (a Actor) GobEncode() ([]byte, error) {
253 mm := make(map[string][]byte)
254 hasData, err := mapActorProperties(mm, &a)
255 if err != nil {
256 return nil, err
257 }
258 if !hasData {
259 return []byte{}, nil
260 }
261 bb := bytes.Buffer{}
262 g := gob.NewEncoder(&bb)
263 if err := g.Encode(mm); err != nil {
264 return nil, err
265 }
266 return bb.Bytes(), nil
267 }
268
269 func (a *Actor) GobDecode(data []byte) error {
270 if len(data) == 0 {
271 return nil
272 }
273 mm, err := gobDecodeObjectAsMap(data)
274 if err != nil {
275 return err
276 }
277 return unmapActorProperties(mm, a)
278 }
279
280 type (
281 // Application describes a software application.
282 Application = Actor
283
284 // Group represents a formal or informal collective of Actors.
285 Group = Actor
286
287 // Organization represents an organization.
288 Organization = Actor
289
290 // Person represents an individual person.
291 Person = Actor
292
293 // Service represents a service of any kind.
294 Service = Actor
295 )
296
297 // ActorNew initializes an CanReceiveActivities type actor
298 func ActorNew(id ID, typ ActivityVocabularyType) *Actor {
299 if !ActorTypes.Match(typ) {
300 typ = ActorType
301 }
302
303 a := Actor{ID: id, Type: typ}
304 a.Name = NaturalLanguageValuesNew()
305 a.Content = NaturalLanguageValuesNew()
306 a.Summary = NaturalLanguageValuesNew()
307 a.PreferredUsername = NaturalLanguageValuesNew()
308
309 return &a
310 }
311
312 // ApplicationNew initializes an Application type actor
313 func ApplicationNew(id ID) *Application {
314 a := ActorNew(id, ApplicationType)
315 o := Application(*a)
316 return &o
317 }
318
319 // GroupNew initializes a Group type actor
320 func GroupNew(id ID) *Group {
321 a := ActorNew(id, GroupType)
322 o := Group(*a)
323 return &o
324 }
325
326 // OrganizationNew initializes an Organization type actor
327 func OrganizationNew(id ID) *Organization {
328 a := ActorNew(id, OrganizationType)
329 o := Organization(*a)
330 return &o
331 }
332
333 // PersonNew initializes a Person type actor
334 func PersonNew(id ID) *Person {
335 a := ActorNew(id, PersonType)
336 o := Person(*a)
337 return &o
338 }
339
340 // ServiceNew initializes a Service type actor
341 func ServiceNew(id ID) *Service {
342 a := ActorNew(id, ServiceType)
343 o := Service(*a)
344 return &o
345 }
346
347 func (a *Actor) Recipients() ItemCollection {
348 aud := a.Audience
349 return ItemCollectionDeduplication(&a.To, &a.CC, &a.Bto, &a.BCC, &aud)
350 }
351
352 func (a *Actor) Clean() {
353 _ = OnObject(a, func(o *Object) error {
354 o.Clean()
355 return nil
356 })
357 }
358
359 func (a *Actor) UnmarshalJSON(data []byte) error {
360 p := fastjson.Parser{}
361 val, err := p.ParseBytes(data)
362 if err != nil {
363 return err
364 }
365 return JSONLoadActor(val, a)
366 }
367
368 func (a Actor) MarshalJSON() ([]byte, error) {
369 b := make([]byte, 0)
370 notEmpty := false
371 JSONWrite(&b, '{')
372
373 _ = OnObject(a, func(o *Object) error {
374 notEmpty = JSONWriteObjectValue(&b, *o)
375 return nil
376 })
377 if a.Inbox != nil {
378 notEmpty = JSONWriteItemProp(&b, "inbox", a.Inbox) || notEmpty
379 }
380 if a.Outbox != nil {
381 notEmpty = JSONWriteItemProp(&b, "outbox", a.Outbox) || notEmpty
382 }
383 if a.Following != nil {
384 notEmpty = JSONWriteItemProp(&b, "following", a.Following) || notEmpty
385 }
386 if a.Followers != nil {
387 notEmpty = JSONWriteItemProp(&b, "followers", a.Followers) || notEmpty
388 }
389 if a.Liked != nil {
390 notEmpty = JSONWriteItemProp(&b, "liked", a.Liked) || notEmpty
391 }
392 if a.PreferredUsername != nil {
393 notEmpty = JSONWriteNaturalLanguageProp(&b, "preferredUsername", a.PreferredUsername) || notEmpty
394 }
395 if a.Endpoints != nil {
396 if v, err := a.Endpoints.MarshalJSON(); err == nil && len(v) > 0 {
397 notEmpty = JSONWriteProp(&b, "endpoints", v) || notEmpty
398 }
399 }
400 if len(a.Streams) > 0 {
401 notEmpty = JSONWriteItemCollectionProp(&b, "streams", a.Streams, false)
402 }
403 if len(a.PublicKey.PublicKeyPem)+len(a.PublicKey.ID) > 0 {
404 if v, err := a.PublicKey.MarshalJSON(); err == nil && len(v) > 0 {
405 notEmpty = JSONWriteProp(&b, "publicKey", v) || notEmpty
406 }
407 }
408
409 if notEmpty {
410 JSONWrite(&b, '}')
411 return b, nil
412 }
413 return nil, nil
414 }
415
416 func (a Actor) Format(s fmt.State, verb rune) {
417 switch verb {
418 case 's':
419 if HasTypes(a) && a.ID != "" {
420 _, _ = fmt.Fprintf(s, "%T[%s]( %s )", a, a.GetType(), a.ID)
421 } else if a.ID != "" {
422 _, _ = fmt.Fprintf(s, "%T( %s )", a, a.ID)
423 } else {
424 _, _ = fmt.Fprintf(s, "%T[%p]", a, &a)
425 }
426 case 'v':
427 _, _ = fmt.Fprintf(s, "%T[%s] { }", a, a.Type)
428 }
429 }
430
431 // Endpoints a json object which maps additional (typically server/domain-wide)
432 // endpoints which may be useful either for this actor or someone referencing this actor.
433 // This mapping may be nested inside the actor document as the value or may be a link to
434 // a JSON-LD document with these properties.
435 type Endpoints struct {
436 // UploadMedia Upload endpoint URI for this user for binary data.
437 UploadMedia Item `jsonld:"uploadMedia,omitempty"`
438 // OauthAuthorizationEndpoint Endpoint URI so this actor's clients may access remote ActivityStreams objects which require authentication
439 // to access. To use this endpoint, the client posts an x-www-form-urlencoded id parameter with the value being
440 // the id of the requested ActivityStreams object.
441 OauthAuthorizationEndpoint Item `jsonld:"oauthAuthorizationEndpoint,omitempty"`
442 // OauthTokenEndpoint If OAuth 2.0 bearer tokens [RFC6749] [RFC6750] are being used for authenticating client to server interactions,
443 // this endpoint specifies a URI at which a browser-authenticated user may obtain a new authorization grant.
444 OauthTokenEndpoint Item `jsonld:"oauthTokenEndpoint,omitempty"`
445 // ProvideClientKey If OAuth 2.0 bearer tokens [RFC6749] [RFC6750] are being used for authenticating client to server interactions,
446 // this endpoint specifies a URI at which a client may acquire an access token.
447 ProvideClientKey Item `jsonld:"provideClientKey,omitempty"`
448 // SignClientKey If Linked Data Signatures and HTTP Signatures are being used for authentication and authorization,
449 // this endpoint specifies a URI at which browser-authenticated users may authorize a client's public
450 // key for client to server interactions.
451 SignClientKey Item `jsonld:"signClientKey,omitempty"`
452 // SharedInbox An optional endpoint used for wide delivery of publicly addressed activities and activities sent to followers.
453 // SharedInbox endpoints SHOULD also be publicly readable OrderedCollection objects containing objects addressed to the
454 // Public special collection. Reading from the sharedInbox endpoint MUST NOT present objects which are not addressed to the Public endpoint.
455 SharedInbox Item `jsonld:"sharedInbox,omitempty"`
456 // ProxyURL
457 // Endpoint URI so this actor's clients may access remote ActivityStreams objects which require authentication to
458 // access. To use this endpoint, the client posts an x-www-form-urlencoded id parameter with the value being the id
459 // of the requested ActivityStreams object.
460 ProxyURL IRI `jsonld:"proxyUrl,omitempty"`
461 }
462
463 // UnmarshalJSON decodes an incoming JSON document into the receiver object.
464 func (e *Endpoints) UnmarshalJSON(data []byte) error {
465 p := fastjson.Parser{}
466 val, err := p.ParseBytes(data)
467 if err != nil {
468 return err
469 }
470 e.OauthAuthorizationEndpoint = JSONGetItem(val, "oauthAuthorizationEndpoint")
471 e.OauthTokenEndpoint = JSONGetItem(val, "oauthTokenEndpoint")
472 e.UploadMedia = JSONGetItem(val, "uploadMedia")
473 e.ProvideClientKey = JSONGetItem(val, "provideClientKey")
474 e.SignClientKey = JSONGetItem(val, "signClientKey")
475 e.SharedInbox = JSONGetItem(val, "sharedInbox")
476 return nil
477 }
478
479 // MarshalJSON encodes the receiver object to a JSON document.
480 func (e Endpoints) MarshalJSON() ([]byte, error) {
481 b := make([]byte, 0)
482 notEmpty := false
483
484 JSONWrite(&b, '{')
485 if e.OauthAuthorizationEndpoint != nil {
486 notEmpty = JSONWriteItemProp(&b, "oauthAuthorizationEndpoint", e.OauthAuthorizationEndpoint)
487 }
488 if e.OauthTokenEndpoint != nil {
489 notEmpty = JSONWriteItemProp(&b, "oauthTokenEndpoint", e.OauthTokenEndpoint) || notEmpty
490 }
491 if e.ProvideClientKey != nil {
492 notEmpty = JSONWriteItemProp(&b, "provideClientKey", e.ProvideClientKey) || notEmpty
493 }
494 if e.SignClientKey != nil {
495 notEmpty = JSONWriteItemProp(&b, "signClientKey", e.SignClientKey) || notEmpty
496 }
497 if e.SharedInbox != nil {
498 notEmpty = JSONWriteItemProp(&b, "sharedInbox", e.SharedInbox) || notEmpty
499 }
500 if e.UploadMedia != nil {
501 notEmpty = JSONWriteItemProp(&b, "uploadMedia", e.UploadMedia) || notEmpty
502 }
503 if notEmpty {
504 JSONWrite(&b, '}')
505 return b, nil
506 }
507 return nil, nil
508 }
509
510 // ToActor
511 func ToActor(it LinkOrIRI) (*Actor, error) {
512 switch i := it.(type) {
513 case *Actor:
514 return i, nil
515 case Actor:
516 return &i, nil
517 default:
518 return reflectItemToType[Actor](it)
519 }
520 }
521
522 // Equals verifies if our receiver Object is equals with the "with" Item
523 func (a *Actor) Equals(with Item) bool {
524 if IsNil(with) {
525 return a == nil
526 }
527 withActor, err := ToActor(with)
528 if err != nil {
529 return false
530 }
531 return a.equal(*withActor)
532 }
533
534 // equal verifies if our receiver Object is equals with the "with" Object
535 func (a Actor) equal(with Actor) bool {
536 result := true
537
538 _ = OnObject(a, func(oa *Object) error {
539 result = oa.Equals(with)
540 return nil
541 })
542 if with.Inbox != nil {
543 if !ItemsEqual(a.Inbox, with.Inbox) {
544 result = false
545 }
546 }
547 if with.Outbox != nil {
548 if !ItemsEqual(a.Outbox, with.Outbox) {
549 result = false
550 }
551 }
552 if with.Liked != nil {
553 if !ItemsEqual(a.Liked, with.Liked) {
554 result = false
555 }
556 }
557 if with.PreferredUsername != nil {
558 if !a.PreferredUsername.Equal(with.PreferredUsername) {
559 result = false
560 }
561 }
562 return result
563 }
564
565 func (e Endpoints) GobEncode() ([]byte, error) {
566 return nil, nil
567 }
568
569 func (e *Endpoints) GobDecode(data []byte) error {
570 return nil
571 }
572
573 func (p PublicKey) GobEncode() ([]byte, error) {
574 var (
575 mm = make(map[string][]byte)
576 err error
577 hasData bool
578 )
579 if len(p.ID) > 0 {
580 if mm["id"], err = p.ID.GobEncode(); err != nil {
581 return nil, err
582 }
583 hasData = true
584 }
585 if len(p.PublicKeyPem) > 0 {
586 mm["publicKeyPem"] = []byte(p.PublicKeyPem)
587 hasData = true
588 }
589 if len(p.Owner) > 0 {
590 if mm["owner"], err = gobEncodeItem(p.Owner); err != nil {
591 return nil, err
592 }
593 hasData = true
594 }
595 if !hasData {
596 return []byte{}, nil
597 }
598 bb := bytes.Buffer{}
599 g := gob.NewEncoder(&bb)
600 if err := g.Encode(mm); err != nil {
601 return nil, err
602 }
603 return bb.Bytes(), nil
604 }
605
606 func (p *PublicKey) GobDecode(data []byte) error {
607 if len(data) == 0 {
608 return nil
609 }
610 mm, err := gobDecodeObjectAsMap(data)
611 if err != nil {
612 return err
613 }
614 if raw, ok := mm["id"]; ok {
615 if err = p.ID.GobDecode(raw); err != nil {
616 return err
617 }
618 }
619 if raw, ok := mm["owner"]; ok {
620 if err = p.Owner.GobDecode(raw); err != nil {
621 return err
622 }
623 }
624 if raw, ok := mm["publicKeyPem"]; ok {
625 p.PublicKeyPem = string(raw)
626 }
627 return nil
628 }
629
630 // WithActorFn represents a function type that can be used as a parameter for OnActor helper function
631 type WithActorFn func(*Actor) error
632
633 // OnActor calls function fn on it Item if it can be asserted to type *Actor
634 //
635 // This function should be called if trying to access the Actor specific
636 // properties like "preferredName", "publicKey", etc. For the other properties
637 // OnObject should be used instead.
638 func OnActor(it LinkOrIRI, fn func(*Actor) error) error {
639 if it == nil {
640 return nil
641 }
642 if IsItemCollection(it) {
643 return callOnItemCollection(it, OnActor, fn)
644 }
645 act, err := ToActor(it)
646 if err != nil {
647 return err
648 }
649 return fn(act)
650 }