Debian Codegraph @

object.go

raw symbols SCIP
1 package activitypub
2
3 import (
4 "bytes"
5 "encoding/gob"
6 "fmt"
7 "io"
8 "reflect"
9 "strings"
10 "time"
11 "unsafe"
12
13 "github.com/valyala/fastjson"
14 )
15
16 const (
17 IRIType ActivityVocabularyType = "IRI"
18 ObjectType ActivityVocabularyType = "Object"
19 LinkType ActivityVocabularyType = "Link"
20 ActivityType ActivityVocabularyType = "Activity"
21 IntransitiveActivityType ActivityVocabularyType = "IntransitiveActivity"
22 ActorType ActivityVocabularyType = "Actor"
23 CollectionType ActivityVocabularyType = "Collection"
24 OrderedCollectionType ActivityVocabularyType = "OrderedCollection"
25 CollectionPageType ActivityVocabularyType = "CollectionPage"
26 OrderedCollectionPageType ActivityVocabularyType = "OrderedCollectionPage"
27
28 // ActivityPub Object Types
29 ArticleType ActivityVocabularyType = "Article"
30 AudioType ActivityVocabularyType = "Audio"
31 DocumentType ActivityVocabularyType = "Document"
32 EventType ActivityVocabularyType = "Event"
33 ImageType ActivityVocabularyType = "Image"
34 NoteType ActivityVocabularyType = "Note"
35 PageType ActivityVocabularyType = "Page"
36 PlaceType ActivityVocabularyType = "Place"
37 ProfileType ActivityVocabularyType = "Profile"
38 RelationshipType ActivityVocabularyType = "Relationship"
39 TombstoneType ActivityVocabularyType = "Tombstone"
40 VideoType ActivityVocabularyType = "Video"
41
42 // MentionType is a link type for @mentions
43 MentionType ActivityVocabularyType = "Mention"
44 NilType ActivityVocabularyType = ""
45 )
46
47 var GenericTypes = ActivityVocabularyTypes{
48 ActivityType,
49 IntransitiveActivityType,
50 ObjectType,
51 ActorType,
52 }
53
54 var ObjectTypes = ActivityVocabularyTypes{
55 ArticleType,
56 AudioType,
57 DocumentType,
58 EventType,
59 ImageType,
60 NoteType,
61 PageType,
62 PlaceType,
63 ProfileType,
64 RelationshipType,
65 TombstoneType,
66 VideoType,
67 }
68
69 type (
70 // ActivityObject is a subtype of Object that describes some form of action that may happen,
71 // is currently happening, or has already happened
72 ActivityObject interface {
73 // GetID returns the dereferenceable ActivityStreams object id
74 GetID() ID
75 GetType() Typer
76 }
77
78 // LinkOrIRI is an interface that Object and Link structs implement, and at the same time
79 // they are kept disjointed
80 LinkOrIRI interface {
81 // GetLink returns the object id in IRI type
82 GetLink() IRI
83 }
84 // ObjectOrLink describes the requirements of an ActivityStreams object
85 ObjectOrLink interface {
86 ActivityObject
87 LinkOrIRI
88 // IsLink shows if current item represents a Link object or an IRI
89 IsLink() bool
90 // IsObject shows if current item represents an ActivityStreams object
91 IsObject() bool
92 // IsCollection shows if the current item represents an ItemCollection
93 IsCollection() bool
94 }
95 // Mapper interface allows external objects to implement their own mechanism for loading information
96 // from an ActivityStreams vocabulary object
97 Mapper interface {
98 // FromActivityStreams maps an ActivityStreams object to another struct representation
99 FromActivityStreams(Item) error
100 }
101 // Typer interface for ActivityPub items returns one or more ActivityVocabularyTypes
102 // that the Item represent.
103 Typer interface {
104 // AsTypes returns the ActivityVocabularyTypes of the Item
105 AsTypes() ActivityVocabularyTypes
106 }
107
108 // MimeType is the type for representing MIME types in certain ActivityStreams properties
109 MimeType string
110 )
111
112 type Objects interface {
113 Object | Tombstone | Place | Profile | Relationship |
114 Actors |
115 Activities |
116 IntransitiveActivities |
117 Collections |
118 IRI
119 }
120
121 // Object describes an ActivityPub object of any kind.
122 // It serves as the base type for most of the other kinds of objects defined in the Activity
123 // Vocabulary, including other Core types such as Activity, IntransitiveActivity, Collection and OrderedCollection.
124 type Object struct {
125 // ID provides the globally unique identifier for anActivity Pub Object or Link.
126 ID ID `jsonld:"id,omitempty"`
127 // Type identifies the Activity Pub Object or Link type. Multiple values may be specified.
128 Type Typer `jsonld:"type,omitempty"`
129 // Name a simple, human-readable, plain-text name for the object.
130 // HTML markup MUST NOT be included. The name MAY be expressed using multiple language-tagged values.
131 Name NaturalLanguageValues `jsonld:"name,omitempty,collapsible"`
132 // Attachment identifies a resource attached or related to an object that potentially requires special handling.
133 // The intent is to provide a model that is at least semantically similar to attachments in email.
134 Attachment Item `jsonld:"attachment,omitempty"`
135 // AttributedTo identifies one or more entities to which this object is attributed. The attributed entities might not be Actors.
136 // For instance, an object might be attributed to the completion of another activity.
137 AttributedTo Item `jsonld:"attributedTo,omitempty"`
138 // Audience identifies one or more entities that represent the total population of entities
139 // for which the object can considered to be relevant.
140 Audience ItemCollection `jsonld:"audience,omitempty"`
141 // Content or textual representation of the Activity Pub Object encoded as a JSON string.
142 // By default, the value of content is HTML.
143 // The mediaType property can be used in the object to indicate a different content type.
144 // (The content MAY be expressed using multiple language-tagged values.)
145 Content NaturalLanguageValues `jsonld:"content,omitempty,collapsible"`
146 // Context identifies the context within which the object exists or an activity was performed.
147 // The notion of "context" used is intentionally vague.
148 // The intended function is to serve as a means of grouping objects and activities that share a
149 // common originating context or purpose. An example could be all activities relating to a common project or event.
150 Context Item `jsonld:"context,omitempty"`
151 // MediaType when used on an Object, identifies the MIME media type of the value of the content property.
152 // If not specified, the content property is assumed to contain text/html content.
153 MediaType MimeType `jsonld:"mediaType,omitempty"`
154 // EndTime the date and time describing the actual or expected ending time of the object.
155 // When used with an Activity object, for instance, the endTime property specifies the moment
156 // the activity concluded or is expected to conclude.
157 EndTime time.Time `jsonld:"endTime,omitempty"`
158 // Generator identifies the entity (e.g. an application) that generated the object.
159 Generator Item `jsonld:"generator,omitempty"`
160 // Icon indicates an entity that describes an icon for this object.
161 // The image should have an aspect ratio of one (horizontal) to one (vertical)
162 // and should be suitable for presentation at a small size.
163 Icon Item `jsonld:"icon,omitempty"`
164 // Image indicates an entity that describes an image for this object.
165 // Unlike the icon property, there are no aspect ratio or display size limitations assumed.
166 Image Item `jsonld:"image,omitempty"`
167 // InReplyTo indicates one or more entities for which this object is considered a response.
168 InReplyTo Item `jsonld:"inReplyTo,omitempty"`
169 // Location indicates one or more physical or logical locations associated with the object.
170 Location Item `jsonld:"location,omitempty"`
171 // Preview identifies an entity that provides a preview of this object.
172 Preview Item `jsonld:"preview,omitempty"`
173 // Published the date and time at which the object was published
174 Published time.Time `jsonld:"published,omitempty"`
175 // Replies identifies a Collection containing objects considered to be responses to this object.
176 Replies Item `jsonld:"replies,omitempty"`
177 // StartTime the date and time describing the actual or expected starting time of the object.
178 // When used with an Activity object, for instance, the startTime property specifies
179 // the moment the activity began or is scheduled to begin.
180 StartTime time.Time `jsonld:"startTime,omitempty"`
181 // Summary a natural language summarization of the object encoded as HTML.
182 // *Multiple language tagged summaries may be provided.)
183 Summary NaturalLanguageValues `jsonld:"summary,omitempty,collapsible"`
184 // Tag one or more "tags" that have been associated with an objects. A tag can be any kind of Activity Pub Object.
185 // The key difference between attachment and tag is that the former implies association by inclusion,
186 // while the latter implies associated by reference.
187 Tag ItemCollection `jsonld:"tag,omitempty"`
188 // Updated the date and time at which the object was updated
189 Updated time.Time `jsonld:"updated,omitempty"`
190 // URL identifies one or more links to representations of the object
191 URL Item `jsonld:"url,omitempty"`
192 // To identifies an entity considered to be part of the public primary audience of an Activity Pub Object
193 To ItemCollection `jsonld:"to,omitempty"`
194 // Bto identifies anActivity Pub Object that is part of the private primary audience of this Activity Pub Object.
195 Bto ItemCollection `jsonld:"bto,omitempty"`
196 // CC identifies anActivity Pub Object that is part of the public secondary audience of this Activity Pub Object.
197 CC ItemCollection `jsonld:"cc,omitempty"`
198 // BCC identifies one or more Objects that are part of the private secondary audience of this Activity Pub Object.
199 BCC ItemCollection `jsonld:"bcc,omitempty"`
200 // Duration when the object describes a time-bound resource, such as an audio or video, a meeting, etc,
201 // the duration property indicates the object's approximate duration.
202 // The value must be expressed as an xsd:duration as defined by [ xmlschema11-2],
203 // section 3.3.6 (e.g. a period of 5 seconds is represented as "PT5S").
204 Duration time.Duration `jsonld:"duration,omitempty"`
205 // This is a list of all Like activities with this object as the object property, added as a side effect.
206 // The likes collection MUST be either an OrderedCollection or a Collection and MAY be filtered on privileges
207 // of an authenticated user or as appropriate when no authentication is given.
208 Likes Item `jsonld:"likes,omitempty"`
209 // This is a list of all Announce activities with this object as the object property, added as a side effect.
210 // The shares collection MUST be either an OrderedCollection or a Collection and MAY be filtered on privileges
211 // of an authenticated user or as appropriate when no authentication is given.
212 Shares Item `jsonld:"shares,omitempty"`
213 // Source property is intended to convey some sort of source from which the content markup was derived,
214 // as a form of provenance, or to support future editing by clients.
215 // In general, clients do the conversion from source to content, not the other way around.
216 Source Source `jsonld:"source,omitempty"`
217 }
218
219 func types(m Typer) ActivityVocabularyTypes {
220 result := ActivityVocabularyTypes{}
221 if tt, ok := m.(ActivityVocabularyType); ok {
222 result = ActivityVocabularyTypes{tt}
223 }
224 if tt, ok := m.(ActivityVocabularyTypes); ok {
225 result = tt
226 }
227 return result
228 }
229
230 // ObjectNew initializes a new Object
231 func ObjectNew(typ Typer) *Object {
232 if !ObjectTypes.Match(typ) {
233 typ = ObjectType
234 }
235 o := Object{Type: typ}
236 o.Name = NaturalLanguageValuesNew()
237 o.Content = NaturalLanguageValuesNew()
238 return &o
239 }
240
241 // GetID returns the ID corresponding to the current Object
242 func (o Object) GetID() ID {
243 return o.ID
244 }
245
246 // GetLink returns the IRI corresponding to the current Object
247 func (o Object) GetLink() IRI {
248 return IRI(o.ID)
249 }
250
251 // GetType returns the type of the current Object
252 func (o Object) GetType() Typer {
253 return o.Type
254 }
255
256 // IsLink validates if currentActivity Pub Object is a Link
257 func (o Object) IsLink() bool {
258 return false
259 }
260
261 // IsObject validates if currentActivity Pub Object is an Object
262 func (o Object) IsObject() bool {
263 return true
264 }
265
266 // IsCollection returns false for Object objects
267 func (o Object) IsCollection() bool {
268 return false
269 }
270
271 // Match returns whether the receiver matches the ActivityVocabularyType arguments.
272 func (o Object) Match(tt ...ActivityVocabularyType) bool {
273 return ActivityVocabularyTypes(tt).Match(o.Type)
274 }
275
276 // UnmarshalJSON decodes an incoming JSON document into the receiver object.
277 func (o *Object) UnmarshalJSON(data []byte) error {
278 p := fastjson.Parser{}
279 val, err := p.ParseBytes(data)
280 if err != nil {
281 return err
282 }
283 return JSONLoadObject(val, o)
284 }
285
286 // MarshalJSON encodes the receiver object to a JSON document.
287 func (o Object) MarshalJSON() ([]byte, error) {
288 b := make([]byte, 0)
289 JSONWrite(&b, '{')
290
291 if JSONWriteObjectValue(&b, o) {
292 JSONWrite(&b, '}')
293 return b, nil
294 }
295 return nil, nil
296 }
297
298 // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
299 func (o *Object) UnmarshalBinary(data []byte) error {
300 return o.GobDecode(data)
301 }
302
303 // MarshalBinary implements the encoding.BinaryMarshaler interface.
304 func (o Object) MarshalBinary() ([]byte, error) {
305 return o.GobEncode()
306 }
307
308 // GobEncode
309 func (o Object) GobEncode() ([]byte, error) {
310 mm := make(map[string][]byte)
311 hasData, err := mapObjectProperties(mm, &o)
312 if err != nil {
313 return nil, err
314 }
315 if !hasData {
316 return []byte{}, nil
317 }
318 bb := bytes.Buffer{}
319 g := gob.NewEncoder(&bb)
320 if err := g.Encode(mm); err != nil {
321 return nil, err
322 }
323 return bb.Bytes(), nil
324 }
325
326 // GobDecode
327 func (o *Object) GobDecode(data []byte) error {
328 if len(data) == 0 {
329 return nil
330 }
331 mm, err := gobDecodeObjectAsMap(data)
332 if err != nil {
333 return err
334 }
335 return unmapObjectProperties(mm, o)
336 }
337
338 func fmtObjectProps(w io.Writer) func(*Object) error {
339 return func(o *Object) error {
340 if len(o.ID) > 0 {
341 if n, _ := fmt.Fprintf(w, "ID:%s", o.ID); n > 0 {
342 _, _ = io.WriteString(w, ", ")
343 }
344 }
345 if len(o.Name) > 0 {
346 if n, _ := fmt.Fprintf(w, "%s: [%s]", "name", o.Name); n > 0 {
347 _, _ = io.WriteString(w, ", ")
348 }
349 }
350 if len(o.Summary) > 0 {
351 if n, _ := fmt.Fprintf(w, "%s: [%s]", "summary", o.Summary); n > 0 {
352 _, _ = io.WriteString(w, ", ")
353 }
354 }
355 if len(o.Content) > 0 {
356 if n, _ := fmt.Fprintf(w, "%s: [%s]", "content", o.Content); n > 0 {
357 _, _ = io.WriteString(w, ", ")
358 }
359 }
360 if !IsNil(o.Attachment) {
361 if n, _ := fmt.Fprintf(w, "%s: %s", "attachment", o.Attachment); n > 0 {
362 _, _ = io.WriteString(w, ", ")
363 }
364 }
365 if !IsNil(o.AttributedTo) {
366 if n, _ := fmt.Fprintf(w, "%s: %s", "attributedTo", o.AttributedTo); n > 0 {
367 _, _ = io.WriteString(w, ", ")
368 }
369 }
370 if !IsNil(o.Audience) && o.Audience.Count() > 0 {
371 if n, _ := fmt.Fprintf(w, "%s: %s", "audience", o.Audience); n > 0 {
372 _, _ = io.WriteString(w, ", ")
373 }
374 }
375 if !IsNil(o.Context) {
376 if n, _ := fmt.Fprintf(w, "%s: %s", "context", o.Context); n > 0 {
377 _, _ = io.WriteString(w, ", ")
378 }
379 }
380 if !IsNil(o.Generator) {
381 if n, _ := fmt.Fprintf(w, "%s: %s", "generator", o.Generator); n > 0 {
382 _, _ = io.WriteString(w, ", ")
383 }
384 }
385 if !IsNil(o.Icon) {
386 if n, _ := fmt.Fprintf(w, "%s: %s", "icon", o.Icon); n > 0 {
387 _, _ = io.WriteString(w, ", ")
388 }
389 }
390 if !IsNil(o.Image) {
391 if n, _ := fmt.Fprintf(w, "%s: %s", "image", o.Image); n > 0 {
392 _, _ = io.WriteString(w, ", ")
393 }
394 }
395 if !IsNil(o.InReplyTo) {
396 if n, _ := fmt.Fprintf(w, "%s: %s", "inReplyTo", o.InReplyTo); n > 0 {
397 _, _ = io.WriteString(w, ", ")
398 }
399 }
400 if !IsNil(o.Location) {
401 if n, _ := fmt.Fprintf(w, "%s: %s", "location", o.Location); n > 0 {
402 _, _ = io.WriteString(w, ", ")
403 }
404 }
405 if !IsNil(o.Preview) {
406 if n, _ := fmt.Fprintf(w, "%s: %s", "preview", o.Preview); n > 0 {
407 _, _ = io.WriteString(w, ", ")
408 }
409 }
410 if !IsNil(o.Replies) {
411 if n, _ := fmt.Fprintf(w, "%s: %s", "replies", o.Replies); n > 0 {
412 _, _ = io.WriteString(w, ", ")
413 }
414 }
415 if !IsNil(o.Tag) && o.Tag.Count() > 0 {
416 if n, _ := fmt.Fprintf(w, "%s: %s", "tag", o.Tag); n > 0 {
417 _, _ = io.WriteString(w, ", ")
418 }
419 }
420 if !IsNil(o.URL) {
421 if n, _ := fmt.Fprintf(w, "%s: %s", "url", o.URL); n > 0 {
422 _, _ = io.WriteString(w, ", ")
423 }
424 }
425 if !IsNil(o.To) && o.To.Count() > 0 {
426 if n, _ := fmt.Fprintf(w, "%s: %s", "to", o.To); n > 0 {
427 _, _ = io.WriteString(w, ", ")
428 }
429 }
430 if !IsNil(o.Bto) && o.Bto.Count() > 0 {
431 if n, _ := fmt.Fprintf(w, "%s: %s", "bto", o.Bto); n > 0 {
432 _, _ = io.WriteString(w, ", ")
433 }
434 }
435 if !IsNil(o.CC) && o.CC.Count() > 0 {
436 if n, _ := fmt.Fprintf(w, "%s: %s", "cc", o.CC); n > 0 {
437 _, _ = io.WriteString(w, ", ")
438 }
439 }
440 if !IsNil(o.BCC) && o.BCC.Count() > 0 {
441 if n, _ := fmt.Fprintf(w, "%s: %s", "bcc", o.BCC); n > 0 {
442 _, _ = io.WriteString(w, ", ")
443 }
444 }
445 if !o.Published.IsZero() {
446 if n, _ := fmt.Fprintf(w, "%s: %s", "published", o.Published); n > 0 {
447 _, _ = io.WriteString(w, ", ")
448 }
449 }
450 if !o.Updated.IsZero() {
451 if n, _ := fmt.Fprintf(w, "%s: %s", "updated", o.Updated); n > 0 {
452 _, _ = io.WriteString(w, ", ")
453 }
454 }
455 if !o.StartTime.IsZero() {
456 if n, _ := fmt.Fprintf(w, "%s: %s", "startTime", o.StartTime); n > 0 {
457 _, _ = io.WriteString(w, ", ")
458 }
459 }
460 if !o.EndTime.IsZero() {
461 if n, _ := fmt.Fprintf(w, "%s: %s", "endTime", o.EndTime); n > 0 {
462 _, _ = io.WriteString(w, ", ")
463 }
464 }
465 if o.Duration != 0 {
466 if n, _ := fmt.Fprintf(w, "%s: %s", "duration", o.Duration); n > 0 {
467 _, _ = io.WriteString(w, ", ")
468 }
469 }
470 if !IsNil(o.Likes) {
471 if n, _ := fmt.Fprintf(w, "%s: %s", "likes", o.Likes); n > 0 {
472 _, _ = io.WriteString(w, ", ")
473 }
474 }
475 if !IsNil(o.Shares) {
476 if n, _ := fmt.Fprintf(w, "%s: %s", "shares", o.Shares); n > 0 {
477 _, _ = io.WriteString(w, ", ")
478 }
479 }
480 return nil
481 }
482 }
483
484 func (o Object) Format(s fmt.State, verb rune) {
485 switch verb {
486 case 's':
487 if HasTypes(o) && o.ID != "" {
488 _, _ = fmt.Fprintf(s, "%T[%s]( %s )", o, o.GetType(), o.ID)
489 } else if o.ID != "" {
490 _, _ = fmt.Fprintf(s, "%T( %s )", o, o.ID)
491 } else {
492 _, _ = fmt.Fprintf(s, "%T[%p]", o, &o)
493 }
494 case 'v':
495 if HasTypes(o) && o.ID != "" {
496 _, _ = fmt.Fprintf(s, "%T[%s] {", o, o.GetType())
497 _ = fmtObjectProps(s)(&o)
498 _, _ = io.WriteString(s, " }")
499 } else if o.ID != "" {
500 _, _ = fmt.Fprintf(s, "%T { ", o)
501 _ = fmtObjectProps(s)(&o)
502 _, _ = io.WriteString(s, " }")
503 }
504 }
505 }
506
507 // Recipients performs recipient de-duplication on the Object's To, Bto, CC and BCC properties
508 func (o *Object) Recipients() ItemCollection {
509 aud := o.Audience
510 return ItemCollectionDeduplication(&o.To, &o.CC, &o.Bto, &o.BCC, &aud)
511 }
512
513 // Clean removes Bto and BCC properties
514 func (o *Object) Clean() {
515 o.BCC = o.BCC[:0]
516 o.Bto = o.Bto[:0]
517 CleanRecipients(o.Audience)
518 CleanRecipients(o.Attachment)
519 CleanRecipients(o.Icon)
520 CleanRecipients(o.Image)
521 CleanRecipients(o.Context)
522 CleanRecipients(o.Generator)
523 CleanRecipients(o.AttributedTo)
524 CleanRecipients(o.Preview)
525 CleanRecipients(o.Tag)
526 }
527
528 type (
529 // Article represents any kind of multi-paragraph written work.
530 Article = Object
531 // Audio represents an audio document of any kind.
532 Audio = Document
533 // Document represents a document of any kind.
534 Document = Object
535 // Event represents any kind of event.
536 Event = Object
537 // Image An image document of any kind
538 Image = Document
539 // Note represents a short written work typically less than a single paragraph in length.
540 Note = Object
541 // Page represents a Web Page.
542 Page = Document
543 // Video represents a video document of any kind
544 Video = Document
545 )
546
547 // UnmarshalJSON decodes an incoming JSON document into the receiver object.
548 func (m *MimeType) UnmarshalJSON(data []byte) error {
549 *m = MimeType(strings.Trim(string(data), "\""))
550 return nil
551 }
552
553 // MarshalJSON encodes the receiver object to a JSON document.
554 func (m MimeType) MarshalJSON() ([]byte, error) {
555 if len(m) == 0 {
556 return nil, nil
557 }
558 b := make([]byte, 0)
559 JSONWriteStringValue(&b, string(m))
560 return b, nil
561 }
562
563 // GobEncode
564 func (m MimeType) GobEncode() ([]byte, error) {
565 if len(m) == 0 {
566 return []byte{}, nil
567 }
568 b := bytes.Buffer{}
569 gg := gob.NewEncoder(&b)
570 if err := gobEncodeStringLikeType(gg, []byte(m)); err != nil {
571 return nil, err
572 }
573 return b.Bytes(), nil
574 }
575
576 // GobDecode
577 func (m *MimeType) GobDecode(data []byte) error {
578 if len(data) == 0 {
579 // NOTE(marius): this behaviour diverges from vanilla gob package
580 return nil
581 }
582 var bb []byte
583 if err := gob.NewDecoder(bytes.NewReader(data)).Decode(&bb); err != nil {
584 return err
585 }
586 *m = MimeType(bb)
587 return nil
588 }
589
590 // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
591 func (m *MimeType) UnmarshalBinary(data []byte) error {
592 return m.GobDecode(data)
593 }
594
595 // MarshalBinary implements the encoding.BinaryMarshaler interface.
596 func (m MimeType) MarshalBinary() ([]byte, error) {
597 return m.GobEncode()
598 }
599
600 // ToLink returns a Link pointer to the data in the current Item
601 func ToLink(it LinkOrIRI) (*Link, error) {
602 switch i := it.(type) {
603 case *Link:
604 return i, nil
605 case Link:
606 return &i, nil
607 }
608 return nil, fmt.Errorf("unable to convert %T to %T", it, new(Link))
609 }
610
611 // ToObject returns an Object pointer to the data in the current Item
612 // It relies on the fact that all the types in this package have a data layout compatible with Object.
613 func ToObject(it LinkOrIRI) (*Object, error) {
614 switch i := it.(type) {
615 case *Object:
616 return i, nil
617 case Object:
618 return &i, nil
619 case *Place:
620 return (*Object)(unsafe.Pointer(i)), nil
621 case Place:
622 return (*Object)(unsafe.Pointer(&i)), nil
623 case *Profile:
624 return (*Object)(unsafe.Pointer(i)), nil
625 case Profile:
626 return (*Object)(unsafe.Pointer(&i)), nil
627 case *Relationship:
628 return (*Object)(unsafe.Pointer(i)), nil
629 case Relationship:
630 return (*Object)(unsafe.Pointer(&i)), nil
631 case *Tombstone:
632 return (*Object)(unsafe.Pointer(i)), nil
633 case Tombstone:
634 return (*Object)(unsafe.Pointer(&i)), nil
635 case *Actor:
636 return (*Object)(unsafe.Pointer(i)), nil
637 case Actor:
638 return (*Object)(unsafe.Pointer(&i)), nil
639 case *Activity:
640 return (*Object)(unsafe.Pointer(i)), nil
641 case Activity:
642 return (*Object)(unsafe.Pointer(&i)), nil
643 case *IntransitiveActivity:
644 return (*Object)(unsafe.Pointer(i)), nil
645 case IntransitiveActivity:
646 return (*Object)(unsafe.Pointer(&i)), nil
647 case *Question:
648 return (*Object)(unsafe.Pointer(i)), nil
649 case Question:
650 return (*Object)(unsafe.Pointer(&i)), nil
651 case *Collection:
652 return (*Object)(unsafe.Pointer(i)), nil
653 case Collection:
654 return (*Object)(unsafe.Pointer(&i)), nil
655 case *CollectionPage:
656 return (*Object)(unsafe.Pointer(i)), nil
657 case CollectionPage:
658 return (*Object)(unsafe.Pointer(&i)), nil
659 case *OrderedCollection:
660 return (*Object)(unsafe.Pointer(i)), nil
661 case OrderedCollection:
662 return (*Object)(unsafe.Pointer(&i)), nil
663 case *OrderedCollectionPage:
664 return (*Object)(unsafe.Pointer(i)), nil
665 case OrderedCollectionPage:
666 return (*Object)(unsafe.Pointer(&i)), nil
667 default:
668 return reflectItemToType[Object](it)
669 }
670 }
671
672 func reflectItemToType[T Objects | Links](it LinkOrIRI) (*T, error) {
673 if IsNil(it) {
674 return nil, nil
675 }
676 tTyp := reflect.TypeFor[*T]()
677 if !reflect.TypeOf(it).ConvertibleTo(tTyp) {
678 return nil, ErrorInvalidType[T](it)
679 }
680
681 iVal := reflect.ValueOf(it)
682 if !iVal.IsValid() {
683 return nil, ErrorInvalidType[T](it)
684 }
685 if i, ok := iVal.Convert(tTyp).Interface().(*T); ok {
686 return i, nil
687 }
688 return nil, ErrorInvalidType[T](it)
689 }
690
691 // Source is intended to convey some sort of source from which the content markup was derived,
692 // as a form of provenance, or to support future editing by clients.
693 type Source struct {
694 // Content
695 Content NaturalLanguageValues `jsonld:"content"`
696 // MediaType
697 MediaType MimeType `jsonld:"mediaType"`
698 }
699
700 // GetAPSource
701 func GetAPSource(val *fastjson.Value) Source {
702 s := Source{}
703 if val == nil {
704 return s
705 }
706
707 if val.Exists("source", "content") {
708 if contBytes := val.Get("source", "content").String(); len(contBytes) > 0 {
709 s.Content = make(NaturalLanguageValues)
710 _ = s.Content.UnmarshalJSON([]byte(contBytes))
711 }
712 }
713 if val.Exists("source", "mediaType") {
714 if mimeBytes := val.Get("source", "mediaType").GetStringBytes(); len(mimeBytes) > 0 {
715 _ = s.MediaType.UnmarshalJSON(mimeBytes)
716 }
717 }
718
719 return s
720 }
721
722 // UnmarshalJSON decodes an incoming JSON document into the receiver object.
723 func (s *Source) UnmarshalJSON(data []byte) error {
724 p := fastjson.Parser{}
725 val, err := p.ParseBytes(data)
726 if err != nil {
727 return err
728 }
729 *s = GetAPSource(val)
730 return nil
731 }
732
733 // MarshalJSON encodes the receiver object to a JSON document.
734 func (s Source) MarshalJSON() ([]byte, error) {
735 b := make([]byte, 0)
736 empty := true
737 JSONWrite(&b, '{')
738 if len(s.MediaType) > 0 {
739 if v, err := s.MediaType.MarshalJSON(); err == nil && len(v) > 0 {
740 empty = !JSONWriteProp(&b, "mediaType", v)
741 }
742 }
743 if len(s.Content) > 0 {
744 empty = !JSONWriteNaturalLanguageProp(&b, "content", s.Content)
745 }
746 if !empty {
747 JSONWrite(&b, '}')
748 return b, nil
749 }
750 return nil, nil
751 }
752
753 // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
754 func (s *Source) UnmarshalBinary(data []byte) error {
755 return s.GobDecode(data)
756 }
757
758 // MarshalBinary implements the encoding.BinaryMarshaler interface.
759 func (s Source) MarshalBinary() ([]byte, error) {
760 return s.GobEncode()
761 }
762
763 // GobDecode
764 func (s *Source) GobDecode(data []byte) error {
765 if len(data) == 0 {
766 return nil
767 }
768 mm := make(map[string][]byte)
769 g := gob.NewDecoder(bytes.NewReader(data))
770 if err := g.Decode(&mm); err != nil {
771 return err
772 }
773 if raw, ok := mm["mediaType"]; ok {
774 if err := s.MediaType.GobDecode(raw); err != nil {
775 return err
776 }
777 }
778 if raw, ok := mm["content"]; ok {
779 content := make(NaturalLanguageValues)
780 if err := content.GobDecode(raw); err != nil {
781 return err
782 }
783 s.Content = content
784 }
785 return nil
786 }
787
788 // GobEncode
789 func (s Source) GobEncode() ([]byte, error) {
790 var (
791 mm = make(map[string][]byte)
792 err error
793 hasData bool
794 )
795 if len(s.MediaType) > 0 {
796 if mm["mediaType"], err = s.MediaType.GobEncode(); err != nil {
797 return nil, err
798 }
799 hasData = true
800 }
801 if len(s.Content) > 0 {
802 if mm["content"], err = s.Content.GobEncode(); err != nil {
803 return nil, err
804 }
805 hasData = true
806 }
807 if !hasData {
808 return []byte{}, nil
809 }
810 bb := bytes.Buffer{}
811 g := gob.NewEncoder(&bb)
812 if err := g.Encode(mm); err != nil {
813 return nil, err
814 }
815 return bb.Bytes(), nil
816 }
817
818 // Equals verifies if our receiver Object is equals with the "with" Item
819 func (o *Object) Equals(with Item) bool {
820 if IsNil(with) {
821 return o == nil
822 }
823 if IsItemCollection(with) {
824 return false
825 }
826 withObject, err := ToObject(with)
827 if err != nil {
828 return false
829 }
830 if !o.ID.Equal(withObject.ID) {
831 return false
832 }
833 if !TypesEqual(o.Type, withObject.Type) {
834 return false
835 }
836 if with.IsLink() && !with.GetLink().Equal(o.GetLink()) {
837 return false
838 }
839 return o.equal(withObject)
840 }
841
842 // equal verifies if our receiver Object is equals with the "with" Object
843 func (o *Object) equal(with *Object) bool {
844 if with == nil {
845 return o == nil
846 }
847 result := true
848
849 if len(with.Name) > 0 {
850 if !with.Name.Equal(o.Name) {
851 result = false
852 }
853 }
854 if len(with.Summary) > 0 {
855 if !with.Summary.Equal(o.Summary) {
856 result = false
857 }
858 }
859 if len(with.Content) > 0 {
860 if !with.Content.Equal(o.Content) {
861 result = false
862 }
863 }
864 if with.Attachment != nil {
865 if !ItemsEqual(o.Attachment, with.Attachment) {
866 result = false
867 }
868 }
869 if with.AttributedTo != nil {
870 if !ItemsEqual(o.AttributedTo, with.AttributedTo) {
871 result = false
872 }
873 }
874 if with.Audience != nil {
875 if !ItemsEqual(o.Audience, with.Audience) {
876 result = false
877 }
878 }
879 if with.Context != nil {
880 if !ItemsEqual(o.Context, with.Context) {
881 result = false
882 }
883 }
884 if with.Generator != nil {
885 if !ItemsEqual(o.Generator, with.Generator) {
886 result = false
887 }
888 }
889 if with.Icon != nil {
890 if !ItemsEqual(o.Icon, with.Icon) {
891 result = false
892 }
893 }
894 if with.Image != nil {
895 if !ItemsEqual(o.Image, with.Image) {
896 result = false
897 }
898 }
899 if with.InReplyTo != nil {
900 if !ItemsEqual(o.InReplyTo, with.InReplyTo) {
901 result = false
902 }
903 }
904 if with.Location != nil {
905 if !ItemsEqual(o.Location, with.Location) {
906 result = false
907 }
908 }
909 if with.Preview != nil {
910 if !ItemsEqual(o.Preview, with.Preview) {
911 result = false
912 }
913 }
914 if with.Replies != nil {
915 if !ItemsEqual(o.Replies, with.Replies) {
916 result = false
917 }
918 }
919 if with.Tag != nil {
920 if !ItemsEqual(o.Tag, with.Tag) {
921 result = false
922 }
923 }
924 if with.URL != nil {
925 if !ItemsEqual(o.URL, with.URL) {
926 result = false
927 }
928 }
929 if with.To != nil {
930 if !ItemsEqual(o.To, with.To) {
931 result = false
932 }
933 }
934 if with.Bto != nil {
935 if !ItemsEqual(o.Bto, with.Bto) {
936 result = false
937 }
938 }
939 if with.CC != nil {
940 if !ItemsEqual(o.CC, with.CC) {
941 result = false
942 }
943 }
944 if with.BCC != nil {
945 if !ItemsEqual(o.BCC, with.BCC) {
946 result = false
947 }
948 }
949 if !with.Published.IsZero() {
950 if !with.Published.Equal(o.Published) {
951 result = false
952 }
953 }
954 if !with.Updated.IsZero() {
955 if !with.Updated.Equal(o.Updated) {
956 result = false
957 }
958 }
959 if !with.StartTime.IsZero() {
960 if !with.StartTime.Equal(o.StartTime) {
961 result = false
962 }
963 }
964 if !with.EndTime.IsZero() {
965 if !with.EndTime.Equal(o.EndTime) {
966 result = false
967 }
968 }
969 if with.Duration != 0 {
970 if with.Duration != o.Duration {
971 result = false
972 }
973 }
974 if with.Likes != nil {
975 if !ItemsEqual(o.Likes, with.Likes) {
976 result = false
977 }
978 }
979 if with.Shares != nil {
980 if !ItemsEqual(o.Shares, with.Shares) {
981 result = false
982 }
983 }
984 return result
985 }
986
987 // OnObject calls function fn on it Item if it can be asserted to type *Object
988 //
989 // This function should be safe to be called for all types with a structure compatible
990 // to the Object type.
991 func OnObject(it LinkOrIRI, fn func(*Object) error) error {
992 if it == nil {
993 return nil
994 }
995 if IsItemCollection(it) {
996 return callOnItemCollection(it, OnObject, fn)
997 }
998 ob, err := ToObject(it)
999 if err != nil {
1000 return err
1001 }
1002 return fn(ob)
1003 }