Debian Codegraph @

activity.go

raw symbols SCIP
1 package activitypub
2
3 import (
4 "bytes"
5 "encoding/gob"
6 "fmt"
7 "io"
8 "time"
9
10 "github.com/valyala/fastjson"
11 )
12
13 // Activity Types
14 const (
15 AcceptType ActivityVocabularyType = "Accept"
16 AddType ActivityVocabularyType = "Add"
17 AnnounceType ActivityVocabularyType = "Announce"
18 ArriveType ActivityVocabularyType = "Arrive"
19 BlockType ActivityVocabularyType = "Block"
20 CreateType ActivityVocabularyType = "Create"
21 DeleteType ActivityVocabularyType = "Delete"
22 DislikeType ActivityVocabularyType = "Dislike"
23 FlagType ActivityVocabularyType = "Flag"
24 FollowType ActivityVocabularyType = "Follow"
25 IgnoreType ActivityVocabularyType = "Ignore"
26 InviteType ActivityVocabularyType = "Invite"
27 JoinType ActivityVocabularyType = "Join"
28 LeaveType ActivityVocabularyType = "Leave"
29 LikeType ActivityVocabularyType = "Like"
30 ListenType ActivityVocabularyType = "Listen"
31 MoveType ActivityVocabularyType = "Move"
32 OfferType ActivityVocabularyType = "Offer"
33 QuestionType ActivityVocabularyType = "Question"
34 RejectType ActivityVocabularyType = "Reject"
35 ReadType ActivityVocabularyType = "Read"
36 RemoveType ActivityVocabularyType = "Remove"
37 TentativeRejectType ActivityVocabularyType = "TentativeReject"
38 TentativeAcceptType ActivityVocabularyType = "TentativeAccept"
39 TravelType ActivityVocabularyType = "Travel"
40 UndoType ActivityVocabularyType = "Undo"
41 UpdateType ActivityVocabularyType = "Update"
42 ViewType ActivityVocabularyType = "View"
43 )
44
45 // ContentManagementActivityTypes use case primarily deals with activities that involve the creation, modification or
46 // deletion of content.
47 //
48 // https://www.w3.org/TR/activitystreams-vocabulary/#motivations-crud
49 //
50 // This includes, for instance, activities such as "John created a new note", "Sally updated an article", and
51 // "Joe deleted the photo".
52 var ContentManagementActivityTypes = ActivityVocabularyTypes{
53 CreateType,
54 DeleteType,
55 UpdateType,
56 }
57
58 // CollectionManagementActivityTypes use case primarily deals with activities involving the management of content within
59 // collections.
60 //
61 // https://www.w3.org/TR/activitystreams-vocabulary/#motivations-collection
62 //
63 // Examples of collections include things like folders, albums, friend lists, etc.
64 // This includes, for instance, activities such as "Sally added a file to Folder A", "John moved the file from Folder A
65 // to Folder B", etc.
66 var CollectionManagementActivityTypes = ActivityVocabularyTypes{
67 AddType,
68 MoveType,
69 RemoveType,
70 }
71
72 // ReactionsActivityTypes use case primarily deals with reactions to content.
73 //
74 // https://www.w3.org/TR/activitystreams-vocabulary/#motivations-reactions
75 //
76 // This can include activities such as liking or disliking content, ignoring updates, flagging content as being
77 // inappropriate, accepting or rejecting objects, etc.
78 var ReactionsActivityTypes = ActivityVocabularyTypes{
79 AcceptType,
80 BlockType,
81 DislikeType,
82 FlagType,
83 IgnoreType,
84 LikeType,
85 RejectType,
86 TentativeAcceptType,
87 TentativeRejectType,
88 }
89
90 // EventRSVPActivityTypes use case primarily deals with invitations to events and RSVP type responses.
91 //
92 // https://www.w3.org/TR/activitystreams-vocabulary/#motivations-rsvp
93 var EventRSVPActivityTypes = ActivityVocabularyTypes{
94 AcceptType,
95 IgnoreType,
96 InviteType,
97 RejectType,
98 TentativeAcceptType,
99 TentativeRejectType,
100 }
101
102 // GroupManagementActivityTypes use case primarily deals with management of groups.
103 //
104 // https://www.w3.org/TR/activitystreams-vocabulary/#motivations-group
105 //
106 // It can include, for instance, activities such as "John added Sally to Group A", "Sally joined Group A",
107 // "Joe left Group A", etc.
108 var GroupManagementActivityTypes = ActivityVocabularyTypes{
109 AddType,
110 JoinType,
111 LeaveType,
112 RemoveType,
113 }
114
115 // ContentExperienceActivityTypes use case primarily deals with describing activities involving listening to, reading,
116 // or viewing content.
117 //
118 // https://www.w3.org/TR/activitystreams-vocabulary/#motivations-experience
119 //
120 // For instance, "Sally read the article", "Joe listened to the song".
121 var ContentExperienceActivityTypes = ActivityVocabularyTypes{
122 ListenType,
123 ReadType,
124 ViewType,
125 }
126
127 // GeoSocialEventsActivityTypes use case primarily deals with activities involving geo-tagging type activities.
128 //
129 // https://www.w3.org/TR/activitystreams-vocabulary/#motivations-geo
130 //
131 // For instance, it can include activities such as "Joe arrived at work", "Sally left work", and
132 // "John is travel from home to work".
133 var GeoSocialEventsActivityTypes = ActivityVocabularyTypes{
134 ArriveType,
135 LeaveType,
136 TravelType,
137 }
138
139 // NotificationActivityTypes use case primarily deals with calling attention to particular objects or notifications.
140 //
141 // https://www.w3.org/TR/activitystreams-vocabulary/#motivations-notification
142 var NotificationActivityTypes = ActivityVocabularyTypes{
143 AnnounceType,
144 }
145
146 // QuestionActivityTypes use case primarily deals with representing inquiries of any type.
147 //
148 // https://www.w3.org/TR/activitystreams-vocabulary/#motivations-questions
149 //
150 // See 5.4 Representing Questions for more information.
151 // https://www.w3.org/TR/activitystreams-vocabulary/#questions
152 var QuestionActivityTypes = ActivityVocabularyTypes{
153 QuestionType,
154 }
155
156 // RelationshipManagementActivityTypes use case primarily deals with representing activities involving the management of
157 // interpersonal and social relationships
158 //
159 // https://www.w3.org/TR/activitystreams-vocabulary/#motivations-relationships
160 //
161 // (e.g. friend requests, management of social network, etc). See 5.2 Representing Relationships Between Entities
162 // for more information.
163 // https://www.w3.org/TR/activitystreams-vocabulary/#connections
164 var RelationshipManagementActivityTypes = ActivityVocabularyTypes{
165 AcceptType,
166 AddType,
167 BlockType,
168 CreateType,
169 DeleteType,
170 FollowType,
171 IgnoreType,
172 InviteType,
173 RejectType,
174 }
175
176 // NegatingActivityTypes use case primarily deals with the ability to redact previously completed activities.
177 //
178 // https://www.w3.org/TR/activitystreams-vocabulary/#motivations-undo
179 //
180 // See 5.5 Inverse Activities and "Undo" for more information.
181 // https://www.w3.org/TR/activitystreams-vocabulary/#inverse
182 var NegatingActivityTypes = ActivityVocabularyTypes{
183 UndoType,
184 }
185
186 // OffersActivityTypes use case deals with activities involving offering one object to another.
187 //
188 // https://www.w3.org/TR/activitystreams-vocabulary/#motivations-offers
189 //
190 // It can include, for instance, activities such as "Company A is offering a discount on purchase of Product Z to Sally",
191 // "Sally is offering to add a File to Folder A", etc.
192 var OffersActivityTypes = ActivityVocabularyTypes{
193 OfferType,
194 }
195
196 var IntransitiveActivityTypes = ActivityVocabularyTypes{
197 ArriveType,
198 TravelType,
199 QuestionType,
200 }
201
202 var ActivityTypes = ActivityVocabularyTypes{
203 AcceptType,
204 AddType,
205 AnnounceType,
206 BlockType,
207 CreateType,
208 DeleteType,
209 DislikeType,
210 FlagType,
211 FollowType,
212 IgnoreType,
213 InviteType,
214 JoinType,
215 LeaveType,
216 LikeType,
217 ListenType,
218 MoveType,
219 OfferType,
220 RejectType,
221 ReadType,
222 RemoveType,
223 TentativeRejectType,
224 TentativeAcceptType,
225 UndoType,
226 UpdateType,
227 ViewType,
228 }
229
230 // HasRecipients is an interface implemented by activities to return their audience
231 // for further propagation
232 //
233 // Please take care to the fact that the de-duplication functionality requires a pointer receiver
234 // therefore a valid Item interface that wraps around an Object struct, can not be type asserted
235 // to HasRecipients.
236 type HasRecipients interface {
237 // Recipients is a method that should do a recipients de-duplication step and then return
238 // the remaining recipients.
239 Recipients() ItemCollection
240 // Clean is a method that removes BCC/Bto recipients in preparation for public consumption of
241 // the Object.
242 Clean()
243 }
244
245 type Activities interface {
246 Activity
247 }
248
249 // Activity is a subtype of Object that describes some form of action that may happen,
250 // is currently happening, or has already happened.
251 // The Activity type itself serves as an abstract base type for all types of activities.
252 // It is important to note that the Activity type itself does not carry any specific semantics
253 // about the kind of action being taken.
254 type Activity struct {
255 // ID provides the globally unique identifier for anActivity Pub Object or Link.
256 ID ID `jsonld:"id,omitempty"`
257 // Type identifies the Activity Pub Object or Link type. Multiple values may be specified.
258 Type Typer `jsonld:"type,omitempty"`
259 // Name a simple, human-readable, plain-text name for the object.
260 // HTML markup MUST NOT be included. The name MAY be expressed using multiple language-tagged values.
261 Name NaturalLanguageValues `jsonld:"name,omitempty,collapsible"`
262 // Attachment identifies a resource attached or related to an object that potentially requires special handling.
263 // The intent is to provide a model that is at least semantically similar to attachments in email.
264 Attachment Item `jsonld:"attachment,omitempty"`
265 // AttributedTo identifies one or more entities to which this object is attributed. The attributed entities might not be Actors.
266 // For instance, an object might be attributed to the completion of another activity.
267 AttributedTo Item `jsonld:"attributedTo,omitempty"`
268 // Audience identifies one or more entities that represent the total population of entities
269 // for which the object can considered to be relevant.
270 Audience ItemCollection `jsonld:"audience,omitempty"`
271 // Content or textual representation of the Activity Pub Object encoded as a JSON string.
272 // By default, the value of content is HTML.
273 // The mediaType property can be used in the object to indicate a different content type.
274 // (The content MAY be expressed using multiple language-tagged values.)
275 Content NaturalLanguageValues `jsonld:"content,omitempty,collapsible"`
276 // Context identifies the context within which the object exists or an activity was performed.
277 // The notion of "context" used is intentionally vague.
278 // The intended function is to serve as a means of grouping objects and activities that share a
279 // common originating context or purpose. An example could be all activities relating to a common project or event.
280 Context Item `jsonld:"context,omitempty"`
281 // MediaType when used on an Object, identifies the MIME media type of the value of the content property.
282 // If not specified, the content property is assumed to contain text/html content.
283 MediaType MimeType `jsonld:"mediaType,omitempty"`
284 // EndTime the date and time describing the actual or expected ending time of the object.
285 // When used with an Activity object, for instance, the endTime property specifies the moment
286 // the activity concluded or is expected to conclude.
287 EndTime time.Time `jsonld:"endTime,omitempty"`
288 // Generator identifies the entity (e.g. an application) that generated the object.
289 Generator Item `jsonld:"generator,omitempty"`
290 // Icon indicates an entity that describes an icon for this object.
291 // The image should have an aspect ratio of one (horizontal) to one (vertical)
292 // and should be suitable for presentation at a small size.
293 Icon Item `jsonld:"icon,omitempty"`
294 // Image indicates an entity that describes an image for this object.
295 // Unlike the icon property, there are no aspect ratio or display size limitations assumed.
296 Image Item `jsonld:"image,omitempty"`
297 // InReplyTo indicates one or more entities for which this object is considered a response.
298 InReplyTo Item `jsonld:"inReplyTo,omitempty"`
299 // Location indicates one or more physical or logical locations associated with the object.
300 Location Item `jsonld:"location,omitempty"`
301 // Preview identifies an entity that provides a preview of this object.
302 Preview Item `jsonld:"preview,omitempty"`
303 // Published the date and time at which the object was published
304 Published time.Time `jsonld:"published,omitempty"`
305 // Replies identifies a Collection containing objects considered to be responses to this object.
306 Replies Item `jsonld:"replies,omitempty"`
307 // StartTime the date and time describing the actual or expected starting time of the object.
308 // When used with an Activity object, for instance, the startTime property specifies
309 // the moment the activity began or is scheduled to begin.
310 StartTime time.Time `jsonld:"startTime,omitempty"`
311 // Summary a natural language summarization of the object encoded as HTML.
312 // *Multiple language tagged summaries may be provided.)
313 Summary NaturalLanguageValues `jsonld:"summary,omitempty,collapsible"`
314 // Tag one or more "tags" that have been associated with an objects. A tag can be any kind of Activity Pub Object.
315 // The key difference between attachment and tag is that the former implies association by inclusion,
316 // while the latter implies associated by reference.
317 Tag ItemCollection `jsonld:"tag,omitempty"`
318 // Updated the date and time at which the object was updated
319 Updated time.Time `jsonld:"updated,omitempty"`
320 // URL identifies one or more links to representations of the object
321 URL Item `jsonld:"url,omitempty"`
322 // To identifies an entity considered to be part of the public primary audience of an Activity Pub Object
323 To ItemCollection `jsonld:"to,omitempty"`
324 // Bto identifies anActivity Pub Object that is part of the private primary audience of this Activity Pub Object.
325 Bto ItemCollection `jsonld:"bto,omitempty"`
326 // CC identifies anActivity Pub Object that is part of the public secondary audience of this Activity Pub Object.
327 CC ItemCollection `jsonld:"cc,omitempty"`
328 // BCC identifies one or more Objects that are part of the private secondary audience of this Activity Pub Object.
329 BCC ItemCollection `jsonld:"bcc,omitempty"`
330 // Duration when the object describes a time-bound resource, such as an audio or video, a meeting, etc,
331 // the duration property indicates the object's approximate duration.
332 // The value must be expressed as an xsd:duration as defined by [ xmlschema11-2],
333 // section 3.3.6 (e.g. a period of 5 seconds is represented as "PT5S").
334 Duration time.Duration `jsonld:"duration,omitempty"`
335 // This is a list of all Like activities with this object as the object property, added as a side effect.
336 // The likes collection MUST be either an OrderedCollection or a Collection and MAY be filtered on privileges
337 // of an authenticated user or as appropriate when no authentication is given.
338 Likes Item `jsonld:"likes,omitempty"`
339 // This is a list of all Announce activities with this object as the object property, added as a side effect.
340 // The shares collection MUST be either an OrderedCollection or a Collection and MAY be filtered on privileges
341 // of an authenticated user or as appropriate when no authentication is given.
342 Shares Item `jsonld:"shares,omitempty"`
343 // Source property is intended to convey some sort of source from which the content markup was derived,
344 // as a form of provenance, or to support future editing by clients.
345 // In general, clients do the conversion from source to content, not the other way around.
346 Source Source `jsonld:"source,omitempty"`
347 // CanReceiveActivities describes one or more entities that either performed or are expected to perform the activity.
348 // Any single activity can have multiple actors. The actor may be specified using an indirect Link.
349 Actor Item `jsonld:"actor,omitempty"`
350 // Target describes the indirect object, or target, of the activity.
351 // The precise meaning of the target is largely dependent on the type of action being described
352 // but will often be the object of the English preposition "to".
353 // For instance, in the activity "John added a movie to his wishlist",
354 // the target of the activity is John's wishlist. An activity can have more than one target.
355 Target Item `jsonld:"target,omitempty"`
356 // Result describes the result of the activity. For instance, if a particular action results in the creation
357 // of a new resource, the result property can be used to describe that new resource.
358 Result Item `jsonld:"result,omitempty"`
359 // Origin describes an indirect object of the activity from which the activity is directed.
360 // The precise meaning of the origin is the object of the English preposition "from".
361 // For instance, in the activity "John moved an item to List B from List A", the origin of the activity is "List A".
362 Origin Item `jsonld:"origin,omitempty"`
363 // Instrument identifies one or more objects used (or to be used) in the completion of an Activity.
364 Instrument Item `jsonld:"instrument,omitempty"`
365 // Object When used within an Activity, describes the direct object of the activity.
366 // For instance, in the activity "John added a movie to his wishlist",
367 // the object of the activity is the movie added.
368 // When used within a Relationship describes the entity to which the subject is related.
369 Object Item `jsonld:"object,omitempty"`
370 }
371
372 // GetType returns the ActivityVocabulary type of the current Activity
373 func (a Activity) GetType() Typer {
374 return a.Type
375 }
376
377 // IsLink returns false for Activity objects
378 func (a Activity) IsLink() bool {
379 return false
380 }
381
382 // GetID returns the ID corresponding to the Activity object
383 func (a Activity) GetID() ID {
384 return a.ID
385 }
386
387 // GetLink returns the IRI corresponding to the Activity object
388 func (a Activity) GetLink() IRI {
389 return IRI(a.ID)
390 }
391
392 // IsObject returns true for Activity objects
393 func (a Activity) IsObject() bool {
394 return true
395 }
396
397 // IsCollection returns false for Activity objects
398 func (a Activity) IsCollection() bool {
399 return false
400 }
401
402 // Match returns whether the receiver matches the ActivityVocabularyType arguments.
403 func (a Activity) Match(tt ...ActivityVocabularyType) bool {
404 return ActivityVocabularyTypes(tt).Match(a.Type)
405 }
406
407 func removeFromCollection(col ItemCollection, items ...Item) ItemCollection {
408 result := make(ItemCollection, 0)
409 if len(items) == 0 {
410 return col
411 }
412 for _, ob := range col {
413 found := false
414 for _, it := range items {
415 if ob.GetID().Equal(it.GetID()) {
416 found = true
417 break
418 }
419 }
420 if !found {
421 result = append(result, ob)
422 }
423 }
424 return result
425 }
426
427 func removeFromAudience(a *Activity, items ...Item) error {
428 if a.To != nil {
429 a.To = removeFromCollection(a.To, items...)
430 }
431 if a.Bto != nil {
432 a.Bto = removeFromCollection(a.Bto, items...)
433 }
434 if a.CC != nil {
435 a.CC = removeFromCollection(a.CC, items...)
436 }
437 if a.BCC != nil {
438 a.BCC = removeFromCollection(a.BCC, items...)
439 }
440 if a.Audience != nil {
441 a.Audience = removeFromCollection(a.Audience, items...)
442 }
443 return nil
444 }
445
446 // Recipients performs recipient de-duplication on the Activity's To, Bto, CC and BCC properties
447 func (a *Activity) Recipients() ItemCollection {
448 alwaysRemove := make(ItemCollection, 0)
449 if BlockType.Match(a.GetType()) && !IsNil(a.Object) {
450 _ = OnItem(a.Object, func(object Item) error {
451 _ = alwaysRemove.Append(object)
452 return nil
453 })
454 }
455 if len(alwaysRemove) > 0 {
456 _ = removeFromAudience(a, alwaysRemove...)
457 }
458 aud := a.Audience
459 return ItemCollectionDeduplication(&a.To, &a.CC, &a.Bto, &a.BCC, &aud)
460 }
461
462 // CleanRecipients checks if the "it" Item has recipients and cleans them if it does
463 func CleanRecipients(it Item) Item {
464 if IsNil(it) {
465 return nil
466 }
467 if s, ok := it.(HasRecipients); ok {
468 s.Clean()
469 }
470 return it
471 }
472
473 // Clean removes Bto and BCC properties
474 func (a *Activity) Clean() {
475 _ = OnObject(a, func(o *Object) error {
476 o.Clean()
477 return nil
478 })
479 CleanRecipients(a.Object)
480 CleanRecipients(a.Actor)
481 CleanRecipients(a.Target)
482 }
483
484 type (
485 // Accept indicates that the actor accepts the object. The target property can be used in certain circumstances to indicate
486 // the context into which the object has been accepted.
487 Accept = Activity
488
489 // Add indicates that the actor has added the object to the target. If the target property is not explicitly specified,
490 // the target would need to be determined implicitly by context.
491 // The origin can be used to identify the context from which the object originated.
492 Add = Activity
493
494 // Announce indicates that the actor is calling the target's attention the object.
495 // The origin typically has no defined meaning.
496 Announce = Activity
497
498 // Block indicates that the actor is blocking the object. Blocking is a stronger form of Ignore.
499 // The typical use is to support social systems that allow one user to block activities or content of other users.
500 // The target and origin typically have no defined meaning.
501 Block = Ignore
502
503 // Create indicates that the actor has created the object.
504 Create = Activity
505
506 // Delete indicates that the actor has deleted the object.
507 // If specified, the origin indicates the context from which the object was deleted.
508 Delete = Activity
509
510 // Dislike indicates that the actor dislikes the object.
511 Dislike = Activity
512
513 // Flag indicates that the actor is "flagging" the object.
514 // Flagging is defined in the sense common to many social platforms as reporting content as being
515 // inappropriate for any number of reasons.
516 Flag = Activity
517
518 // Follow indicates that the actor is "following" the object. Following is defined in the sense typically used within
519 // Social systems in which the actor is interested in any activity performed by or on the object.
520 // The target and origin typically have no defined meaning.
521 Follow = Activity
522
523 // Ignore indicates that the actor is ignoring the object. The target and origin typically have no defined meaning.
524 Ignore = Activity
525
526 // Invite is a specialization of Offer in which the actor is extending an invitation for the object to the target.
527 Invite = Offer
528
529 // Join indicates that the actor has joined the object. The target and origin typically have no defined meaning.
530 Join = Activity
531
532 // Leave indicates that the actor has left the object. The target and origin typically have no meaning.
533 Leave = Activity
534
535 // Like indicates that the actor likes, recommends or endorses the object.
536 // The target and origin typically have no defined meaning.
537 Like = Activity
538
539 // Listen inherits all properties from Activity.
540 Listen = Activity
541
542 // Move indicates that the actor has moved object from origin to target.
543 // If the origin or target are not specified, either can be determined by context.
544 Move = Activity
545
546 // Offer indicates that the actor is offering the object.
547 // If specified, the target indicates the entity to which the object is being offered.
548 Offer = Activity
549
550 // Reject indicates that the actor is rejecting the object. The target and origin typically have no defined meaning.
551 Reject = Activity
552
553 // Read indicates that the actor has read the object.
554 Read = Activity
555
556 // Remove indicates that the actor is removing the object. If specified,
557 // the origin indicates the context from which the object is being removed.
558 Remove = Activity
559
560 // TentativeReject is a specialization of Reject in which the rejection is considered tentative.
561 TentativeReject = Reject
562
563 // TentativeAccept is a specialization of Accept indicating that the acceptance is tentative.
564 TentativeAccept = Accept
565
566 // Undo indicates that the actor is undoing the object. In most cases, the object will be an Activity describing
567 // some previously performed action (for instance, a person may have previously "liked" an article but,
568 // for whatever reason, might choose to undo that like at some later point in time).
569 // The target and origin typically have no defined meaning.
570 Undo = Activity
571
572 // Update indicates that the actor has updated the object. Note, however, that this vocabulary does not define a mechanism
573 // for describing the actual set of modifications made to object.
574 // The target and origin typically have no defined meaning.
575 Update = Activity
576
577 // View indicates that the actor has viewed the object.
578 View = Activity
579 )
580
581 // AcceptNew initializes an Accept activity
582 func AcceptNew(id ID, ob Item) *Accept {
583 a := ActivityNew(id, AcceptType, ob)
584 o := Accept(*a)
585 return &o
586 }
587
588 // AddNew initializes an Add activity
589 func AddNew(id ID, ob, trgt Item) *Add {
590 a := ActivityNew(id, AddType, ob)
591 o := Add(*a)
592 o.Target = trgt
593 return &o
594 }
595
596 // AnnounceNew initializes an Announce activity
597 func AnnounceNew(id ID, ob Item) *Announce {
598 a := ActivityNew(id, AnnounceType, ob)
599 o := Announce(*a)
600 return &o
601 }
602
603 // BlockNew initializes a Block activity
604 func BlockNew(id ID, ob Item) *Block {
605 a := ActivityNew(id, BlockType, ob)
606 o := Block(*a)
607 return &o
608 }
609
610 // CreateNew initializes a Create activity
611 func CreateNew(id ID, ob Item) *Create {
612 a := ActivityNew(id, CreateType, ob)
613 o := Create(*a)
614 return &o
615 }
616
617 // DeleteNew initializes a Delete activity
618 func DeleteNew(id ID, ob Item) *Delete {
619 a := ActivityNew(id, DeleteType, ob)
620 o := Delete(*a)
621 return &o
622 }
623
624 // DislikeNew initializes a Dislike activity
625 func DislikeNew(id ID, ob Item) *Dislike {
626 a := ActivityNew(id, DislikeType, ob)
627 o := Dislike(*a)
628 return &o
629 }
630
631 // FlagNew initializes a Flag activity
632 func FlagNew(id ID, ob Item) *Flag {
633 a := ActivityNew(id, FlagType, ob)
634 o := Flag(*a)
635 return &o
636 }
637
638 // FollowNew initializes a Follow activity
639 func FollowNew(id ID, ob Item) *Follow {
640 a := ActivityNew(id, FollowType, ob)
641 o := Follow(*a)
642 return &o
643 }
644
645 // IgnoreNew initializes an Ignore activity
646 func IgnoreNew(id ID, ob Item) *Ignore {
647 a := ActivityNew(id, IgnoreType, ob)
648 o := Ignore(*a)
649 return &o
650 }
651
652 // InviteNew initializes an Invite activity
653 func InviteNew(id ID, ob Item) *Invite {
654 a := ActivityNew(id, InviteType, ob)
655 o := Invite(*a)
656 return &o
657 }
658
659 // JoinNew initializes a Join activity
660 func JoinNew(id ID, ob Item) *Join {
661 a := ActivityNew(id, JoinType, ob)
662 o := Join(*a)
663 return &o
664 }
665
666 // LeaveNew initializes a Leave activity
667 func LeaveNew(id ID, ob Item) *Leave {
668 a := ActivityNew(id, LeaveType, ob)
669 o := Leave(*a)
670 return &o
671 }
672
673 // LikeNew initializes a Like activity
674 func LikeNew(id ID, ob Item) *Like {
675 a := ActivityNew(id, LikeType, ob)
676 o := Like(*a)
677 return &o
678 }
679
680 // ListenNew initializes a Listen activity
681 func ListenNew(id ID, ob Item) *Listen {
682 a := ActivityNew(id, ListenType, ob)
683 o := Listen(*a)
684 return &o
685 }
686
687 // MoveNew initializes a Move activity
688 func MoveNew(id ID, ob Item) *Move {
689 a := ActivityNew(id, MoveType, ob)
690 o := Move(*a)
691 return &o
692 }
693
694 // OfferNew initializes an Offer activity
695 func OfferNew(id ID, ob Item) *Offer {
696 a := ActivityNew(id, OfferType, ob)
697 o := Offer(*a)
698 return &o
699 }
700
701 // RejectNew initializes a Reject activity
702 func RejectNew(id ID, ob Item) *Reject {
703 a := ActivityNew(id, RejectType, ob)
704 o := Reject(*a)
705 return &o
706 }
707
708 // ReadNew initializes a Read activity
709 func ReadNew(id ID, ob Item) *Read {
710 a := ActivityNew(id, ReadType, ob)
711 o := Read(*a)
712 return &o
713 }
714
715 // RemoveNew initializes a Remove activity
716 func RemoveNew(id ID, ob, trgt Item) *Remove {
717 a := ActivityNew(id, RemoveType, ob)
718 o := Remove(*a)
719 o.Target = trgt
720 return &o
721 }
722
723 // TentativeRejectNew initializes a TentativeReject activity
724 func TentativeRejectNew(id ID, ob Item) *TentativeReject {
725 a := ActivityNew(id, TentativeRejectType, ob)
726 o := TentativeReject(*a)
727 return &o
728 }
729
730 // TentativeAcceptNew initializes a TentativeAccept activity
731 func TentativeAcceptNew(id ID, ob Item) *TentativeAccept {
732 a := ActivityNew(id, TentativeAcceptType, ob)
733 o := TentativeAccept(*a)
734 return &o
735 }
736
737 // UndoNew initializes an Undo activity
738 func UndoNew(id ID, ob Item) *Undo {
739 a := ActivityNew(id, UndoType, ob)
740 o := Undo(*a)
741 return &o
742 }
743
744 // UpdateNew initializes an Update activity
745 func UpdateNew(id ID, ob Item) *Update {
746 a := ActivityNew(id, UpdateType, ob)
747 u := Update(*a)
748 return &u
749 }
750
751 // ViewNew initializes a View activity
752 func ViewNew(id ID, ob Item) *View {
753 a := ActivityNew(id, ViewType, ob)
754 o := View(*a)
755 return &o
756 }
757
758 // ActivityNew initializes a basic activity
759 func ActivityNew(id ID, typ ActivityVocabularyType, ob Item) *Activity {
760 if !ActivityTypes.Match(typ) {
761 typ = ActivityType
762 }
763 a := Activity{ID: id, Type: typ}
764 a.Name = NaturalLanguageValuesNew()
765 a.Content = NaturalLanguageValuesNew()
766
767 a.Object = ob
768
769 return &a
770 }
771
772 // UnmarshalJSON decodes an incoming JSON document into the receiver object.
773 func (a *Activity) UnmarshalJSON(data []byte) error {
774 p := fastjson.Parser{}
775 val, err := p.ParseBytes(data)
776 if err != nil {
777 return err
778 }
779 return JSONLoadActivity(val, a)
780 }
781
782 func fmtActivityProps(w io.Writer) func(*Activity) error {
783 return func(a *Activity) error {
784 if !IsNil(a.Object) {
785 _, _ = fmt.Fprintf(w, " object: %s", a.Object)
786 }
787 return OnIntransitiveActivity(a, fmtIntransitiveActivityProps(w))
788 }
789 }
790
791 func (a Activity) Format(s fmt.State, verb rune) {
792 switch verb {
793 case 's':
794 if HasTypes(a) && a.ID != "" {
795 _, _ = fmt.Fprintf(s, "%T[%s]( %s )", a, a.GetType(), a.ID)
796 } else if a.ID != "" {
797 _, _ = fmt.Fprintf(s, "%T( %s )", a, a.ID)
798 } else {
799 _, _ = fmt.Fprintf(s, "%T[%p]", a, &a)
800 }
801 case 'v':
802 _, _ = fmt.Fprintf(s, "%T[%s] {", a, a.GetType())
803 _ = fmtActivityProps(s)(&a)
804 _, _ = io.WriteString(s, " }")
805 }
806 }
807
808 // ToActivity
809 func ToActivity(it LinkOrIRI) (*Activity, error) {
810 switch i := it.(type) {
811 case *Activity:
812 return i, nil
813 case Activity:
814 return &i, nil
815 default:
816 return reflectItemToType[Activity](it)
817 }
818 }
819
820 // MarshalJSON encodes the receiver object to a JSON document.
821 func (a Activity) MarshalJSON() ([]byte, error) {
822 b := make([]byte, 0)
823 JSONWrite(&b, '{')
824
825 if !JSONWriteActivityValue(&b, a) {
826 return nil, nil
827 }
828 JSONWrite(&b, '}')
829 return b, nil
830 }
831
832 // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
833 func (a *Activity) UnmarshalBinary(data []byte) error {
834 return a.GobDecode(data)
835 }
836
837 // MarshalBinary implements the encoding.BinaryMarshaler interface.
838 func (a Activity) MarshalBinary() ([]byte, error) {
839 return a.GobEncode()
840 }
841
842 func mapIntransitiveActivityProperties(mm map[string][]byte, a *IntransitiveActivity) (hasData bool, err error) {
843 err = OnObject(a, func(o *Object) error {
844 hasData, err = mapObjectProperties(mm, o)
845 return err
846 })
847 if a.Actor != nil {
848 if mm["actor"], err = gobEncodeItem(a.Actor); err != nil {
849 return hasData, err
850 }
851 hasData = true
852 }
853 if a.Target != nil {
854 if mm["target"], err = gobEncodeItem(a.Target); err != nil {
855 return hasData, err
856 }
857 hasData = true
858 }
859 if a.Result != nil {
860 if mm["result"], err = gobEncodeItem(a.Result); err != nil {
861 return hasData, err
862 }
863 hasData = true
864 }
865 if a.Instrument != nil {
866 if mm["instrument"], err = gobEncodeItem(a.Instrument); err != nil {
867 return hasData, err
868 }
869 hasData = true
870 }
871 return hasData, err
872 }
873
874 func mapActivityProperties(mm map[string][]byte, a *Activity) (hasData bool, err error) {
875 err = OnIntransitiveActivity(a, func(a *IntransitiveActivity) error {
876 hasData, err = mapIntransitiveActivityProperties(mm, a)
877 return err
878 })
879 if a.Object != nil {
880 if mm["object"], err = gobEncodeItem(a.Object); err != nil {
881 return hasData, err
882 }
883 hasData = true
884 }
885 return hasData, err
886 }
887
888 // GobEncode
889 func (a Activity) GobEncode() ([]byte, error) {
890 mm := make(map[string][]byte)
891 hasData, err := mapActivityProperties(mm, &a)
892 if err != nil {
893 return nil, err
894 }
895 if !hasData {
896 return []byte{}, nil
897 }
898 bb := bytes.Buffer{}
899 g := gob.NewEncoder(&bb)
900 if err := g.Encode(mm); err != nil {
901 return nil, err
902 }
903 return bb.Bytes(), nil
904 }
905
906 // GobDecode
907 func (a *Activity) GobDecode(data []byte) error {
908 if len(data) == 0 {
909 return nil
910 }
911 mm, err := gobDecodeObjectAsMap(data)
912 if err != nil {
913 return err
914 }
915 return unmapActivityProperties(mm, a)
916 }
917
918 // Equals verifies if our receiver Activity is equals with the "with" Item
919 func (a *Activity) Equals(with Item) bool {
920 if IsNil(with) {
921 return a == nil
922 }
923 withActivity, err := ToActivity(with)
924 if err != nil {
925 return false
926 }
927 return a.equal(*withActivity)
928 }
929
930 // equal verifies if our receiver Activity is equals with the "with" Activity
931 func (a Activity) equal(with Activity) bool {
932 result := true
933 _ = OnIntransitiveActivity(a, func(oi *IntransitiveActivity) error {
934 result = oi.Equals(with)
935 return nil
936 })
937 if with.Object != nil {
938 if !ItemsEqual(a.Object, with.Object) {
939 result = false
940 }
941 }
942 return result
943 }
944
945 // OnActivity calls function fn on it Item if it can be asserted to type *Activity
946 //
947 // This function should be called if trying to access the Activity specific properties
948 // like "object", for the other properties OnObject, or OnIntransitiveActivity
949 // should be used instead.
950 func OnActivity(it LinkOrIRI, fn func(*Activity) error) error {
951 if it == nil {
952 return nil
953 }
954 if IsItemCollection(it) {
955 return callOnItemCollection(it, OnActivity, fn)
956 }
957 act, err := ToActivity(it)
958 if err != nil {
959 return err
960 }
961 return fn(act)
962 }