Debian Codegraph @

collection.go

raw symbols SCIP
1 package activitypub
2
3 import (
4 "bytes"
5 "encoding/gob"
6 "fmt"
7 "time"
8 "unsafe"
9
10 "github.com/valyala/fastjson"
11 )
12
13 const CollectionOfIRIs ActivityVocabularyType = "IRICollection"
14 const CollectionOfItems ActivityVocabularyType = "ItemCollection"
15
16 var CollectionTypes = ActivityVocabularyTypes{
17 CollectionOfItems,
18 CollectionType,
19 OrderedCollectionType,
20 CollectionPageType,
21 OrderedCollectionPageType,
22 }
23
24 // Collections
25 //
26 // https://www.w3.org/TR/activitypub/#collections
27 //
28 // [ActivityStreams] defines the collection concept; ActivityPub defines several collections with special behavior.
29 //
30 // Note that ActivityPub makes use of ActivityStreams paging to traverse large sets of objects.
31 //
32 // Note that some of these collections are specified to be of type OrderedCollection specifically,
33 // while others are permitted to be either a Collection or an OrderedCollection.
34 // An OrderedCollection MUST be presented consistently in reverse chronological order.
35 //
36 // NOTE
37 // What property is used to determine the reverse chronological order is intentionally left as an implementation detail.
38 // For example, many SQL-style databases use an incrementing integer as an identifier, which can be reasonably used for
39 // handling insertion order in most cases. In other databases, an insertion time timestamp may be preferred.
40 // What is used isn't important, but the ordering of elements must remain intact, with newer items first.
41 // A property which changes regularly, such a "last updated" timestamp, should not be used.
42 type Collections interface {
43 Collection | CollectionPage | OrderedCollection | OrderedCollectionPage | ItemCollection | IRIs
44 }
45
46 type CollectionInterface interface {
47 ObjectOrLink
48 Collection() ItemCollection
49 Append(ob ...Item) error
50 Remove(ob ...Item)
51 Count() uint
52 Contains(Item) bool
53 }
54
55 // Collection is a subtype of Activity Pub Object that represents ordered or unordered sets of Activity Pub Object or Link instances.
56 type Collection struct {
57 // ID provides the globally unique identifier for anActivity Pub Object or Link.
58 ID ID `jsonld:"id,omitempty"`
59 // Type identifies the Activity Pub Object or Link type. Multiple values may be specified.
60 Type Typer `jsonld:"type,omitempty"`
61 // Name a simple, human-readable, plain-text name for the object.
62 // HTML markup MUST NOT be included. The name MAY be expressed using multiple language-tagged values.
63 Name NaturalLanguageValues `jsonld:"name,omitempty,collapsible"`
64 // Attachment identifies a resource attached or related to an object that potentially requires special handling.
65 // The intent is to provide a model that is at least semantically similar to attachments in email.
66 Attachment Item `jsonld:"attachment,omitempty"`
67 // AttributedTo identifies one or more entities to which this object is attributed. The attributed entities might not be Actors.
68 // For instance, an object might be attributed to the completion of another activity.
69 AttributedTo Item `jsonld:"attributedTo,omitempty"`
70 // Audience identifies one or more entities that represent the total population of entities
71 // for which the object can considered to be relevant.
72 Audience ItemCollection `jsonld:"audience,omitempty"`
73 // Content or textual representation of the Activity Pub Object encoded as a JSON string.
74 // By default, the value of content is HTML.
75 // The mediaType property can be used in the object to indicate a different content type.
76 // (The content MAY be expressed using multiple language-tagged values.)
77 Content NaturalLanguageValues `jsonld:"content,omitempty,collapsible"`
78 // Context identifies the context within which the object exists or an activity was performed.
79 // The notion of "context" used is intentionally vague.
80 // The intended function is to serve as a means of grouping objects and activities that share a
81 // common originating context or purpose. An example could be all activities relating to a common project or event.
82 Context Item `jsonld:"context,omitempty"`
83 // MediaType when used on an Object, identifies the MIME media type of the value of the content property.
84 // If not specified, the content property is assumed to contain text/html content.
85 MediaType MimeType `jsonld:"mediaType,omitempty"`
86 // EndTime the date and time describing the actual or expected ending time of the object.
87 // When used with an Activity object, for instance, the endTime property specifies the moment
88 // the activity concluded or is expected to conclude.
89 EndTime time.Time `jsonld:"endTime,omitempty"`
90 // Generator identifies the entity (e.g. an application) that generated the object.
91 Generator Item `jsonld:"generator,omitempty"`
92 // Icon indicates an entity that describes an icon for this object.
93 // The image should have an aspect ratio of one (horizontal) to one (vertical)
94 // and should be suitable for presentation at a small size.
95 Icon Item `jsonld:"icon,omitempty"`
96 // Image indicates an entity that describes an image for this object.
97 // Unlike the icon property, there are no aspect ratio or display size limitations assumed.
98 Image Item `jsonld:"image,omitempty"`
99 // InReplyTo indicates one or more entities for which this object is considered a response.
100 InReplyTo Item `jsonld:"inReplyTo,omitempty"`
101 // Location indicates one or more physical or logical locations associated with the object.
102 Location Item `jsonld:"location,omitempty"`
103 // Preview identifies an entity that provides a preview of this object.
104 Preview Item `jsonld:"preview,omitempty"`
105 // Published the date and time at which the object was published
106 Published time.Time `jsonld:"published,omitempty"`
107 // Replies identifies a Collection containing objects considered to be responses to this object.
108 Replies Item `jsonld:"replies,omitempty"`
109 // StartTime the date and time describing the actual or expected starting time of the object.
110 // When used with an Activity object, for instance, the startTime property specifies
111 // the moment the activity began or is scheduled to begin.
112 StartTime time.Time `jsonld:"startTime,omitempty"`
113 // Summary a natural language summarization of the object encoded as HTML.
114 // *Multiple language tagged summaries may be provided.)
115 Summary NaturalLanguageValues `jsonld:"summary,omitempty,collapsible"`
116 // Tag one or more "tags" that have been associated with an objects. A tag can be any kind of Activity Pub Object.
117 // The key difference between attachment and tag is that the former implies association by inclusion,
118 // while the latter implies associated by reference.
119 Tag ItemCollection `jsonld:"tag,omitempty"`
120 // Updated the date and time at which the object was updated
121 Updated time.Time `jsonld:"updated,omitempty"`
122 // URL identifies one or more links to representations of the object
123 URL Item `jsonld:"url,omitempty"`
124 // To identifies an entity considered to be part of the public primary audience of an Activity Pub Object
125 To ItemCollection `jsonld:"to,omitempty"`
126 // Bto identifies anActivity Pub Object that is part of the private primary audience of this Activity Pub Object.
127 Bto ItemCollection `jsonld:"bto,omitempty"`
128 // CC identifies anActivity Pub Object that is part of the public secondary audience of this Activity Pub Object.
129 CC ItemCollection `jsonld:"cc,omitempty"`
130 // BCC identifies one or more Objects that are part of the private secondary audience of this Activity Pub Object.
131 BCC ItemCollection `jsonld:"bcc,omitempty"`
132 // Duration when the object describes a time-bound resource, such as an audio or video, a meeting, etc,
133 // the duration property indicates the object's approximate duration.
134 // The value must be expressed as an xsd:duration as defined by [ xmlschema11-2],
135 // section 3.3.6 (e.g. a period of 5 seconds is represented as "PT5S").
136 Duration time.Duration `jsonld:"duration,omitempty"`
137 // This is a list of all Like activities with this object as the object property, added as a side effect.
138 // The likes collection MUST be either an OrderedCollection or a Collection and MAY be filtered on privileges
139 // of an authenticated user or as appropriate when no authentication is given.
140 Likes Item `jsonld:"likes,omitempty"`
141 // This is a list of all Announce activities with this object as the object property, added as a side effect.
142 // The shares collection MUST be either an OrderedCollection or a Collection and MAY be filtered on privileges
143 // of an authenticated user or as appropriate when no authentication is given.
144 Shares Item `jsonld:"shares,omitempty"`
145 // Source property is intended to convey some sort of source from which the content markup was derived,
146 // as a form of provenance, or to support future editing by clients.
147 // In general, clients do the conversion from source to content, not the other way around.
148 Source Source `jsonld:"source,omitempty"`
149 // In a paged Collection, indicates the page that contains the most recently updated member items.
150 Current ObjectOrLink `jsonld:"current,omitempty"`
151 // In a paged Collection, indicates the furthest preceding page of items in the collection.
152 First ObjectOrLink `jsonld:"first,omitempty"`
153 // In a paged Collection, indicates the furthest proceeding page of the collection.
154 Last ObjectOrLink `jsonld:"last,omitempty"`
155 // A non-negative integer specifying the total number of objects contained by the logical view of the collection.
156 // This number might not reflect the actual number of items serialized within the Collection object instance.
157 TotalItems uint `jsonld:"totalItems"`
158 // Identifies the items contained in a collection. The items might be ordered or unordered.
159 Items ItemCollection `jsonld:"items,omitempty"`
160 }
161
162 type (
163 // FollowersCollection is a collection of followers
164 FollowersCollection = Collection
165
166 // FollowingCollection is a list of everybody that the actor has followed, added as a side effect.
167 // The following collection MUST be either an OrderedCollection or a Collection and MAY
168 // be filtered on privileges of an authenticated user or as appropriate when no authentication is given.
169 FollowingCollection = Collection
170 )
171
172 // CollectionNew initializes a new Collection
173 func CollectionNew(id ID) *Collection {
174 c := Collection{ID: id, Type: CollectionType}
175 c.Name = NaturalLanguageValuesNew()
176 c.Content = NaturalLanguageValuesNew()
177 c.Summary = NaturalLanguageValuesNew()
178 return &c
179 }
180
181 // OrderedCollectionNew initializes a new OrderedCollection
182 func OrderedCollectionNew(id ID) *OrderedCollection {
183 o := OrderedCollection{ID: id, Type: OrderedCollectionType}
184 o.Name = NaturalLanguageValuesNew()
185 o.Content = NaturalLanguageValuesNew()
186
187 return &o
188 }
189
190 // GetID returns the ID corresponding to the Collection object
191 func (c Collection) GetID() ID {
192 return c.ID
193 }
194
195 // GetType returns the Collection's type
196 func (c Collection) GetType() Typer {
197 return c.Type
198 }
199
200 // IsLink returns false for a Collection object
201 func (c Collection) IsLink() bool {
202 return false
203 }
204
205 // IsObject returns true for a Collection object
206 func (c Collection) IsObject() bool {
207 return true
208 }
209
210 // IsCollection returns true for Collection objects
211 func (c Collection) IsCollection() bool {
212 return true
213 }
214
215 // GetLink returns the IRI corresponding to the Collection object
216 func (c Collection) GetLink() IRI {
217 return IRI(c.ID)
218 }
219
220 // Match returns whether the receiver matches the ActivityVocabularyType arguments.
221 func (c Collection) Match(tt ...ActivityVocabularyType) bool {
222 return ActivityVocabularyTypes(tt).Match(c.Type)
223 }
224
225 // Collection returns the Collection's items
226 func (c Collection) Collection() ItemCollection {
227 return c.Items
228 }
229
230 // Append adds items to a Collection
231 func (c *Collection) Append(it ...Item) error {
232 for _, ob := range it {
233 if !c.Items.Contains(ob) {
234 c.Items = append(c.Items, ob)
235 c.TotalItems += 1
236 }
237 }
238 return nil
239 }
240
241 // Remove removes items from a Collection
242 func (c *Collection) Remove(it ...Item) {
243 for _, ob := range it {
244 if c.Items.Contains(ob) {
245 c.Items.Remove(ob)
246 c.TotalItems -= 1
247 }
248 }
249 }
250
251 // Count returns the maximum between the length of Items in collection and its TotalItems property
252 func (c *Collection) Count() uint {
253 if c == nil {
254 return 0
255 }
256 return uint(len(c.Items))
257 }
258
259 // Contains verifies if Collection array contains the received one
260 func (c Collection) Contains(r Item) bool {
261 if len(c.Items) == 0 {
262 return false
263 }
264 for _, it := range c.Items {
265 if ItemsEqual(it, r) {
266 return true
267 }
268 }
269 return false
270 }
271
272 // UnmarshalJSON decodes an incoming JSON document into the receiver object.
273 func (c *Collection) UnmarshalJSON(data []byte) error {
274 par := fastjson.Parser{}
275 val, err := par.ParseBytes(data)
276 if err != nil {
277 return err
278 }
279 return JSONLoadCollection(val, c)
280 }
281
282 // MarshalJSON encodes the receiver object to a JSON document.
283 func (c Collection) MarshalJSON() ([]byte, error) {
284 b := make([]byte, 0)
285 notEmpty := false
286 JSONWrite(&b, '{')
287
288 OnObject(c, func(o *Object) error {
289 notEmpty = JSONWriteObjectValue(&b, *o)
290 return nil
291 })
292 if c.Current != nil {
293 notEmpty = JSONWriteItemProp(&b, "current", c.Current) || notEmpty
294 }
295 if c.First != nil {
296 notEmpty = JSONWriteItemProp(&b, "first", c.First) || notEmpty
297 }
298 if c.Last != nil {
299 notEmpty = JSONWriteItemProp(&b, "last", c.Last) || notEmpty
300 }
301 notEmpty = JSONWriteIntProp(&b, "totalItems", int64(c.TotalItems)) || notEmpty
302 if c.Items != nil {
303 notEmpty = JSONWriteItemCollectionProp(&b, "items", c.Items, false) || notEmpty
304 }
305 if notEmpty {
306 JSONWrite(&b, '}')
307 return b, nil
308 }
309 return nil, nil
310 }
311
312 // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
313 func (c *Collection) UnmarshalBinary(data []byte) error {
314 return c.GobDecode(data)
315 }
316
317 // MarshalBinary implements the encoding.BinaryMarshaler interface.
318 func (c Collection) MarshalBinary() ([]byte, error) {
319 return c.GobEncode()
320 }
321
322 func (c Collection) GobEncode() ([]byte, error) {
323 mm := make(map[string][]byte)
324 hasData, err := mapCollectionProperties(mm, c)
325 if err != nil {
326 return nil, err
327 }
328 if !hasData {
329 return []byte{}, nil
330 }
331 bb := bytes.Buffer{}
332 g := gob.NewEncoder(&bb)
333 if err := g.Encode(mm); err != nil {
334 return nil, err
335 }
336 return bb.Bytes(), nil
337 }
338
339 func (c *Collection) GobDecode(data []byte) error {
340 if len(data) == 0 {
341 return nil
342 }
343 mm, err := gobDecodeObjectAsMap(data)
344 if err != nil {
345 return err
346 }
347 return unmapCollectionProperties(mm, c)
348 }
349
350 func (c Collection) Format(s fmt.State, verb rune) {
351 switch verb {
352 case 's', 'v':
353 _, _ = fmt.Fprintf(s, "%T[%s] { totalItems: %d }", c, c.Type, c.TotalItems)
354 }
355 }
356
357 // ToCollection
358 func ToCollection(it LinkOrIRI) (*Collection, error) {
359 switch i := it.(type) {
360 case *Collection:
361 return i, nil
362 case Collection:
363 return &i, nil
364 case *CollectionPage:
365 return (*Collection)(unsafe.Pointer(i)), nil
366 case CollectionPage:
367 return (*Collection)(unsafe.Pointer(&i)), nil
368 // NOTE(marius): let's try again to convert OrderedCollection -> Collection, as they have the same
369 // shape in memory.
370 case *OrderedCollection:
371 return (*Collection)(unsafe.Pointer(i)), nil
372 case OrderedCollection:
373 return (*Collection)(unsafe.Pointer(&i)), nil
374 case *OrderedCollectionPage:
375 return (*Collection)(unsafe.Pointer(i)), nil
376 case OrderedCollectionPage:
377 return (*Collection)(unsafe.Pointer(&i)), nil
378 default:
379 return reflectItemToType[Collection](it)
380 }
381 }
382
383 // ItemsMatch
384 func (c Collection) ItemsMatch(col ...Item) bool {
385 for _, it := range col {
386 if match := c.Items.Contains(it); !match {
387 return false
388 }
389 }
390 return true
391 }
392
393 // Equals verifies if our receiver Collection is equals with the "with" Item
394 func (c *Collection) Equals(with Item) bool {
395 if IsNil(with) {
396 return c == nil
397 }
398 if !with.IsCollection() {
399 return false
400 }
401 withCollection, err := ToCollection(with)
402 if err != nil {
403 return false
404 }
405 return c.equal(*withCollection)
406 }
407
408 // equal verifies if our receiver Collection is equals with the "with" Collection
409 func (c Collection) equal(with Collection) bool {
410 result := true
411 _ = OnObject(with, func(wo *Object) error {
412 if !wo.Equals(c) {
413 result = false
414 return nil
415 }
416 return nil
417 })
418 if with.TotalItems > 0 {
419 if with.TotalItems != c.TotalItems {
420 result = false
421 }
422 }
423 if with.Current != nil {
424 if !ItemsEqual(c.Current, with.Current) {
425 result = false
426 }
427 }
428 if with.First != nil {
429 if !ItemsEqual(c.First, with.First) {
430 result = false
431 }
432 }
433 if with.Last != nil {
434 if !ItemsEqual(c.Last, with.Last) {
435 result = false
436 }
437 }
438 if with.Items != nil {
439 if !ItemsEqual(c.Items, with.Items) {
440 result = false
441 }
442 }
443 return result
444 }
445
446 func (c *Collection) Recipients() ItemCollection {
447 aud := c.Audience
448 return ItemCollectionDeduplication(&c.To, &c.CC, &c.Bto, &c.BCC, &aud)
449 }
450
451 func (c *Collection) Clean() {
452 _ = OnObject(c, func(o *Object) error {
453 o.Clean()
454 return nil
455 })
456 }
457
458 // OnCollection calls function fn on it Item if it can be asserted to type *Collection
459 //
460 // This function should be called if trying to access the Collection specific
461 // properties like "totalItems", "items", etc. For the other properties
462 // OnObject should be used instead.
463 func OnCollection(it Item, fn WithCollectionFn) error {
464 if it == nil {
465 return nil
466 }
467 col, err := ToCollection(it)
468 if err != nil {
469 return err
470 }
471 return fn(col)
472 }