stream

package module
v8.4.0 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2024 License: BSD-3-Clause Imports: 17 Imported by: 4

README ¶

Official Go SDK for Stream Feeds

Official Go API client for Stream Feeds, a service for building applications with activity feeds.
Explore the docs »

Report Bug · Request Feature


🚨 Breaking change in v7.0 <

From version 7.0.0, all methods' first argument is context.Context. The reason is that we internally changed http.NewRequest() to http.NewRequestWithContext() so that it's easier to handle cancellations, timeouts and deadlines for our users.

About Stream

stream-go2 is a Go client for Stream Feeds API.

You can sign up for a Stream account at our Get Started page.

You can use this library to access chat API endpoints server-side.

For the client-side integrations (web and mobile) have a look at the JavaScript, iOS and Android SDK libraries (docs).

💡 Note: this is a library for the Feeds product. The Chat SDKs can be found here.

build godoc Go Report Card

Contents

Installation

Get the client:

$ go get github.com/GetStream/stream-go2/v8

For v4, use github.com/GetStream/stream-go2/v4 but updating to the last version is highly recommended.

Creating a Client
import stream "github.com/GetStream/stream-go2/v8"

key := "YOUR_API_KEY"
secret := "YOUR_API_SECRET"

client, err := stream.New(key, secret)
if err != nil {
    // ...
}

You can pass additional options when creating a client using the available ClientOption functions:

client, err := stream.NewClient(key, secret,
    stream.WithAPIRegion("us-east"),
    stream.WithAPIVersion("1.0"),
    stream.WithTimeout(5 * time.Second),
    ...,
)

You can also create a client using environment variables:

client, err := stream.NewFromEnv()

Available environment variables:

  • STREAM_API_KEY
  • STREAM_API_SECRET
  • STREAM_API_REGION
  • STREAM_API_VERSION
Rate Limits

API has different rate limits for each distinct endpoint and this information is returned to the client in response headers and SDK parses headers into Rate type.

This info is provided to the user in 2 ways:

  • in responses; resp, _ := feed.GetActivities; resp.Rate.
  • in errors; if request doesn't succeed then error is a type of APIError and headers are accessible via err.(APIError).Rate.
Creating a Feed

Create a flat feed from slug and user ID:

flat, err := client.FlatFeed("user", "123")

Create an aggregated feed from slug and user ID:

aggr, err := client.AggregatedFeed("aggregated", "123")

Create a notification feed from slug and user ID:

notif, err := client.NotificationFeed("notification", "123")

Flat, aggregated, and notification feeds implement the Feed interface methods.

In the snippets below, feed indicates any kind of feed, while flat, aggregated, and notification are used to indicate that only that kind of feed has certain methods or can perform certain operations.

Retrieving activities
Flat feeds
resp, err := flat.GetActivities()
if err != nil {
    // ...
}

fmt.Println("Duration:", resp.Duration)
fmt.Println("Rate:", resp.Rate)
fmt.Println("Next:", resp.Next)
fmt.Println("Activities:")
for _, activity := range resp.Results {
    fmt.Println(activity)
}

You can retrieve flat feeds with custom ranking, using the dedicated method:

resp, err := flat.GetActivitiesWithRanking(ctx, "popularity")
if err != nil {
    // ...
}
Aggregated feeds
resp, err := aggregated.GetActivities(ctx)
if err != nil {
    // ...
}

fmt.Println("Duration:", resp.Duration)
fmt.Println("Rate:", resp.Rate)
fmt.Println("Next:", resp.Next)
fmt.Println("Groups:")
for _, group := range resp.Results {
    fmt.Println("Group:", group.Name, "ID:", group.ID, "Verb:", group.Verb)
    fmt.Println("Activities:", group.ActivityCount, "Actors:", group.ActorCount)
    for _, activity := range group.Activities {
        // ...
    }
}
Notification feeds
resp, err := notification.GetActivities(ctx)
if err != nil {
    // ...
}

fmt.Println("Duration:", resp.Duration)
fmt.Println("Rate:", resp.Rate)
fmt.Println("Next:", resp.Next)
fmt.Println("Unseen:", resp.Unseen, "Unread:", resp.Unread)
fmt.Println("Groups:")
for _, group := range resp.Results {
    fmt.Println("Group:", group.Group, "ID:", group.ID, "Verb:", group.Verb)
    fmt.Println("Seen:", group.IsSeen, "Read:", group.IsRead)
    fmt.Println("Activities:", group.ActivityCount, "Actors:", group.ActorCount)
    for _, activity := range group.Activities {
        // ...
    }
}
Options

You can pass supported options and filters when retrieving activities:

resp, err := flat.GetActivities(
    ctx,
    stream.WithActivitiesIDGTE("f505b3fb-a212-11e7-..."),
    stream.WithActivitiesLimit(5),
    ...,
)
Adding activities

Add a single activity:

resp, err := feed.AddActivity(ctx, stream.Activity{Actor: "bob", ...})
if err != nil {
    // ...
}

fmt.Println("Duration:", resp.Duration)
fmt.Println("Rate:", resp.Rate)
fmt.Println("Activity:", resp.Activity) // resp wraps the stream.Activity type

Add multiple activities:

a1 := stream.Activity{Actor: "bob", ...}
a2 := stream.Activity{Actor: "john", ...}
a3 := stream.Activity{Actor: "alice", ...}

resp, err := feed.AddActivities(ctx, a1, a2, a3)
if err != nil {
    // ...
}

fmt.Println("Duration:", resp.Duration)
fmt.Println("Rate:", resp.Rate)
fmt.Println("Activities:")
for _, activity := range resp.Activities {
    fmt.Println(activity)
}
Updating activities
_, err := feed.UpdateActivities(ctx, a1, a2, ...)
if err != nil {
    // ...
}
Partially updating activities

You can partial update activities identified either by ID:

changesetA := stream.NewUpdateActivityRequestByID("f505b3fb-a212-11e7-...", map[string]any{"key": "new-value"}, []string{"removed", "keys"})
changesetB := stream.NewUpdateActivityRequestByID("f707b3fb-a212-11e7-...", map[string]any{"key": "new-value"}, []string{"removed", "keys"})
resp, err := client.PartialUpdateActivities(ctx, changesetA, changesetB)
if err != nil {
    // ...
}

or by a ForeignID and timestamp pair:

changesetA := stream.NewUpdateActivityRequestByForeignID("dothings:1", stream.Time{...}, map[string]any{"key": "new-value"}, []string{"removed", "keys"})
changesetB := stream.NewUpdateActivityRequestByForeignID("dothings:2", stream.Time{...}, map[string]any{"key": "new-value"}, []string{"removed", "keys"})
resp, err := client.PartialUpdateActivities(ctx, changesetA, changesetB)
if err != nil {
    // ...
}
Removing activities

You can either remove activities by ID or ForeignID:

_, err := feed.RemoveActivityByID(ctx, "f505b3fb-a212-11e7-...")
if err != nil {
    // ...
}

_, err := feed.RemoveActivityByForeignID(ctx, "bob:123")
if err != nil {
    // ...
}
Following another feed
_, err := feed.Follow(ctx, anotherFeed)
if err != nil {
    // ...
}

Beware that it's possible to follow only flat feeds.

Options

You can pass options to the Follow method. For example:

_, err := feed.Follow(ctx,
    anotherFeed,
    stream.WithFollowFeedActivityCopyLimit(15),
    ...,
)
Retrieving followers and followings
Following

Get the feeds that a feed is following:

resp, err := feed.GetFollowing(ctx)
if err != nil {
    // ...
}

fmt.Println("Duration:", resp.Duration)
for _, followed := range resp.Results {
    fmt.Println(followed.FeedID, followed.TargetID)
}

You can pass options to GetFollowing:

resp, err := feed.GetFollowing(
    ctx,
    stream.WithFollowingLimit(5),
    ...,
)
Followers
resp, err := flat.GetFollowers(ctx)
if err != nil {
    // ...
}

fmt.Println("Duration:", resp.Duration)
fmt.Println("Rate:", resp.Rate)
for _, follower := range resp.Results {
    fmt.Println(follower.FeedID, follower.TargetID)
}

Note: this is only possible for FlatFeed types.

You can pass options to GetFollowers:

resp, err := feed.GetFollowing(
    ctx,
    stream.WithFollowersLimit(5),
    ...,
)
Unfollowing a feed
_, err := flat.Unfollow(ctx, anotherFeed)
if err != nil {
    // ...
}

You can pass options to Unfollow:

_, err := flat.Unfollow(ctx,
    anotherFeed,
    stream.WithUnfollowKeepHistory(true),
    ...,
)
Updating an activity's to targets

Remove all old targets and set new ones (replace):

newTargets := []stream.Feed{f1, f2}

_, err := feed.UpdateToTargets(ctx, activity, stream.WithToTargetsNew(newTargets...))
if err != nil {
    // ...
}

Add some targets and remove some others:

add := []stream.Feed{target1, target2}
remove := []stream.Feed{oldTarget1, oldTarget2}

_, err := feed.UpdateToTargets(
    ctx,
    activity,
    stream.WithToTargetsAdd(add),
    stream.WithToTargetsRemove(remove),
)
if err != nil {
    // ...
}

Note: you can't mix stream.WithToTargetsNew with stream.WithToTargetsAdd or stream.WithToTargetsRemove.

Batch adding activities

You can add the same activities to multiple feeds at once with the (*Client).AddToMany method (docs):

_, err := client.AddToMany(ctx,
    activity, feed1, feed2, ...,
)
if err != nil {
    // ...
}
Batch creating follows

You can create multiple follow relationships at once with the (*Client).FollowMany method (docs):

relationships := []stream.FollowRelationship{
    stream.NewFollowRelationship(source, target),
    ...,
}

_, err := client.FollowMany(ctx, relationships)
if err != nil {
    // ...
}
Realtime tokens

You can get a token suitable for client-side real-time feed updates as:

// Read+Write token
token := feed.RealtimeToken(false)

// Read-only token
readonlyToken := feed.RealtimeToken(true)

Analytics

If your app is enabled for analytics collection you can use the Go client to track events. The main documentation for the analytics features is available in our Docs page.

Obtaining an Analytics client

You can obtain a specialized Analytics client (*stream.AnalyticsClient) from a regular client, which you can use to track events:

// Create the client
analytics := client.Analytics()
Tracking engagement

Engagement events can be tracked with the TrackEngagement method of AnalyticsClient. It accepts any number of EngagementEvents.

Events' syntax is not checked by the client, so be sure to follow our documentation about it.

Events are simple maps, but the stream package offers handy helpers to populate such events easily.

// Create the event
event := stream.EngagementEvent{}.
    WithLabel("click").
    WithForeignID("event:1234").
    WithUserData(stream.NewUserData().String("john")).
    WithFeatures(
        stream.NewEventFeature("color", "blue"),
        stream.NewEventFeature("shape", "rectangle"),
    ).
    WithLocation("homepage")

// Track the event(s)
_, err := analytics.TrackEngagement(ctx, event)
if err != nil {
    // ...
}
Tracking impressions

Impression events can be tracked with the TrackImpression method of AnalyticsClient (syntax docs):

// Create the impression events
imp := stream.ImpressionEventData{}.
    WithForeignIDs("product:1", "product:2", "product:3").
    WithUserData(stream.NewUserData().String("john")).
    WithLocation("storepage")

// Track the events
_, err := analytics.TrackImpression(ctx, imp)
if err != nil {
    // ...
}
Email tracking

You can generate URLs to track events and redirect to a specific URL with the RedirectAndTrack method of AnalyticsClient (syntax docs). It accepts any number of engagement and impression events:

// Create the events
engagement := stream.EngagementEvent{}.
    WithLabel("click").
    WithForeignID("event:1234").
    WithUserData(stream.NewUserData().String("john")).
    WithFeatures(
        stream.NewEventFeature("color", "blue"),
        stream.NewEventFeature("shape", "rectangle"),
    ).
    WithLocation("homepage")

impressions := stream.ImpressionEventData{}.
    WithForeignIDs("product:1", "product:2", "product:3").
    WithUserData(stream.NewUserData().String("john")).
    WithLocation("storepage")

// Generate the tracking and redirect URL, which once followed
// will redirect the user to the targetURL.
targetURL := "https://google.com"
url, err := analytics.RedirectAndTrack(targetURL, engagement, impression)
if err != nil {
    // ...
}

// Display the obtained url where needed.

Personalization

Personalization endpoints for enabled apps can be reached using a PersonalizationClient, a specialized client obtained with the Personalization() function of a regular Client.

personalization := client.Personalization()

The PersonalizationClient exposes three functions that you can use to retrieve and manipulate data: Get, Post, and Delete.

For example, to retrieve follow recommendations:

// Get follow recommendations
data := map[string]any{
    "user_id":          123,
    "source_feed_slug": "timeline",
    "target_feed_slug": "user",
}
resp, err = personalization.Get(ctx, "follow_recommendations", data)
if err != nil {
    // ...
}
fmt.Println(resp)

See the complete docs and examples about personalization features on Stream's documentation pages.

Collections

Collections endpoints can be reached using a specialized CollectionsClient which, like PersonalizationClient, can be obtained from a regular Client:

collections := client.Collections()

CollectionsClient exposes three batch functions, Upsert, Select, and DeleteMany as well as CRUD functions: Add, Get, Update, Delete:

// Upsert the "picture" collection
object := stream.CollectionObject{
    ID:   "123",
    Data: map[string]any{
        "name": "Rocky Mountains",
        "location": "North America",
    },
}
_, err = collections.Upsert(ctx, "picture", object)
if err != nil {
    // ...
}

// Get the data from the "picture" collection for ID "123" and "456"
objects, err := collections.Select(ctx, "picture", "123", "456")
if err != nil {
    // ...
}

// Delete the data from the "picture" collection for picture with ID "123"
_, err = collections.Delete(ctx, "picture", "123")
if err != nil {
    // ...
}

// Get a single collection object from the "pictures" collection with ID "123"
_, err = collections.Get(ctx, "pictures", "123")
if err != nil {
    // ...
}

See the complete docs and examples about collections on Stream's documentation pages.

Users

Users endpoints can be reached using a specialized UsersClient which, like CollectionsClient, can be obtained from a regular Client:

users := client.Users()

UsersClient exposes CRUD functions: Add, Get, Update, Delete:

user := stream.User{
    ID: "123",
    Data: map[string]any{
        "name": "Bobby Tables",
    },
}

insertedUser, err := users.Add(ctx, user, false)
if err != nil {
    // ...
}

newUserData :=map[string]any{
    "name": "Bobby Tables",
    "age": 7,
}

updatedUser, err := users.Update(ctx, "123", newUserData)
if err != nil {
    // ...
}

_, err = users.Delete(ctx, "123")
if err != nil {
    // ...
}

See the complete docs and examples about users on Stream's documentation pages.

Reactions

Reactions endpoints can be reached using a specialized Reactions which, like CollectionsClient, can be obtained from a regular Client:

reactions := client.Reactions()

Reactions exposes CRUD functions: Add, Get, Update, Delete, as well as two specialized functions AddChild and Filter:

r := stream.AddReactionRequestObject{
    Kind: "comment",
    UserID: "123",
    ActivityID: "87a9eec0-fd5f-11e8-8080-80013fed2f5b",
    Data: map[string]any{
        "text": "Nice post!!",
    },
    TargetFeeds: []string{"user:bob", "timeline:alice"},
}

comment, err := reactions.Add(ctx, r)
if err != nil {
    // ...
}

like := stream.AddReactionRequestObject{
    Kind: "like",
    UserID: "456",
}

childReaction, err := reactions.AddChild(ctx, comment.ID, like)
if err != nil {
    // ...
}

// If we fetch the "comment" reaction now, it will have the child reaction(s) present.
parent, err := reactions.Get(ctx, comment.ID)
if err != nil {
    // ...
}

for kind, children := range parent.ChildrenReactions {
    // child reactions are grouped by kind
}

// update the target feeds for the `comment` reaction
updatedReaction, err := reactions.Update(ctx, comment.ID, nil, []string{"timeline:jeff"})
if err != nil {
    // ...
}

// get all reactions for the activity "87a9eec0-fd5f-11e8-8080-80013fed2f5b",
// paginated 5 at a time, including the activity data
response, err := reactions.Filter(ctx,
    stream.ByActivityID("87a9eec0-fd5f-11e8-8080-80013fed2f5b"),
    stream.WithLimit(5),
    stream.WithActivityData())
if err != nil {
    // ...
}

// since we requested the activity, it will be present in the response
fmt.Println(response.Activity)

for _, reaction := range response.Results{
    // do something for each reaction
}

//get the next page of reactions
response, err = reactions.GetNextPageFilteredReactions(ctx, response)
if err != nil {
    // ...
}

// get all likes by user "123"
response, err = reactions.Filter(ctx, stream.ByUserID("123").ByKind("like"))
if err != nil {
    // ...
}

See the complete docs and examples about reactions on Stream's documentation pages.

Enrichment

Enrichment is a way of retrieving activities from feeds in which references to Users and Collections will be replaced with the corresponding objects

FlatFeed, AggregatedFeed and NotificationFeed each have a GetEnrichedActivities function to retrieve enriched activities.

u := stream.User{
    ID: "123",
    Data: map[string]any{
        "name": "Bobby Tables",
    },
}

// We add a user
user, err := client.Users().Add(ctx, u, true)
if err != nil {
    // ...
}

c := stream.CollectionObject{
    ID: "123",
    Data: map[string]any{
        "name":     "Rocky Mountains",
        "location": "North America",
    },
}

// We add a collection object
collectionObject, err := client.Collections().Add(ctx, "picture", c)
if err != nil {
    // ...
}

act := stream.Activity{
    Time:      stream.Time{Time: time.Now()},
    Actor:     client.Users().CreateReference(user.ID),
    Verb:      "post",
    Object:    client.Collections().CreateReference("picture", collectionObject.ID),
    ForeignID: "picture:1",
}


// We add the activity to the user's feed
feed, _ := client.FlatFeed("user", "123")
_, err = feed.AddActivity(ctx, act)
if err != nil {
    // ...
}

result, err := feed.GetActivities(ctx)
if err != nil {
    // ...
}
fmt.Println(result.Results[0].Actor) // Will output the user reference
fmt.Println(result.Results[0].Object) // Will output the collection reference

enrichedResult, err := feed.GetEnrichedActivities(ctx)
if err != nil {
    // ...
}
fmt.Println(enrichedResult.Results[0]["actor"].(map[string]any)) // Will output the user object
fmt.Println(enrichedResult.Results[0]["object"].(map[string]any)) // Will output the collection object

See the complete docs and examples about enrichment on Stream's documentation pages.

License

Project is licensed under the BSD 3-Clause.

We are hiring!

We've recently closed a $38 million Series B funding round and we keep actively growing. Our APIs are used by more than a billion end-users, and you'll have a chance to make a huge impact on the product within a team of the strongest engineers all over the world.

Check out our current openings and apply via Stream's website.

Documentation ¶

Index ¶

Constants ¶

View Source
const (
	HeaderRateLimit     = "X-Ratelimit-Limit"
	HeaderRateRemaining = "X-Ratelimit-Remaining"
	HeaderRateReset     = "X-Ratelimit-Reset"
)

Rate limit headers

View Source
const (
	// TimeLayout is the default time parse layout for Stream API JSON time fields
	TimeLayout = "2006-01-02T15:04:05.999999"
	// ReactionTimeLayout is the time parse layout for Stream Reaction API JSON time fields
	ReactionTimeLayout = "2006-01-02T15:04:05.999999Z07:00"
)

Variables ¶

View Source
var (
	// ErrMissingNextPage is returned when trying to read the next page of a response
	// which has an empty "next" field.
	ErrMissingNextPage = errors.New("request missing next page")
	// ErrInvalidNextPage is returned when trying to read the next page of a response
	// which has an invalid "next" field.
	ErrInvalidNextPage = errors.New("invalid format for Next field")
)
View Source
var CreateCollectionReference = (&CollectionsClient{}).CreateReference

CreateCollectionReference is a convenience helper not to require a client.

View Source
var CreateUserReference = (&UsersClient{}).CreateReference

CreateUserReference is a convenience helper not to require a client.

View Source
var Version = "v8.4.0"

Version is the current release version for this client

Functions ¶

This section is empty.

Types ¶

type APIError ¶

type APIError struct {
	Code            int              `json:"code,omitempty"`
	Detail          string           `json:"detail,omitempty"`
	Duration        Duration         `json:"duration,omitempty"`
	Exception       string           `json:"exception,omitempty"`
	ExceptionFields map[string][]any `json:"exception_fields,omitempty"`
	StatusCode      int              `json:"status_code,omitempty"`
	Rate            *Rate            `json:"-"`
}

APIError is an error returned by Stream API when the request cannot be performed or errored server side.

func ToAPIError ¶

func ToAPIError(err error) (APIError, bool)

ToAPIError tries to cast the provided error to APIError type, returning the obtained APIError and whether the operation was successful.

func (APIError) Error ¶

func (e APIError) Error() string

type Activity ¶

type Activity struct {
	ID        string         `json:"id,omitempty"`
	Actor     string         `json:"actor,omitempty"`
	Verb      string         `json:"verb,omitempty"`
	Object    string         `json:"object,omitempty"`
	ForeignID string         `json:"foreign_id,omitempty"`
	Target    string         `json:"target,omitempty"`
	Time      Time           `json:"time,omitempty"`
	Origin    string         `json:"origin,omitempty"`
	To        []string       `json:"to,omitempty"`
	Score     float64        `json:"score,omitempty"`
	Extra     map[string]any `json:"-"`
	ScoreVars map[string]any `json:"score_vars,omitempty"`
}

Activity is a Stream activity entity.

func (Activity) MarshalJSON ¶

func (a Activity) MarshalJSON() ([]byte, error)

MarshalJSON encodes the Activity to a valid JSON bytes slice. It's required because of the custom JSON fields and time formats.

func (*Activity) UnmarshalJSON ¶

func (a *Activity) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the provided JSON payload into the Activity. It's required because of the custom JSON fields and time formats.

type ActivityGroup ¶

type ActivityGroup struct {
	Activities []Activity `json:"activities,omitempty"`
	// contains filtered or unexported fields
}

ActivityGroup is a group of Activity obtained from aggregated feeds.

type AddActivitiesResponse ¶

type AddActivitiesResponse struct {
	Activities []Activity `json:"activities,omitempty"`
	// contains filtered or unexported fields
}

AddActivitiesResponse is the API response obtained when adding activities to a feed.

type AddActivityResponse ¶

type AddActivityResponse struct {
	// contains filtered or unexported fields
}

AddActivityResponse is the API response obtained when adding a single activity to a feed.

func (*AddActivityResponse) UnmarshalJSON ¶

func (a *AddActivityResponse) UnmarshalJSON(buf []byte) error

UnmarshalJSON is the custom unmarshaler since activity custom unmarshaler can take extra values.

type AddObjectOption ¶

type AddObjectOption func(*addCollectionRequest)

AddObjectOption is an option usable by the Collections.Add method.

func WithUserID ¶

func WithUserID(userID string) AddObjectOption

WithUserID adds the user id to the Collections.Add request object.

type AddReactionRequestObject ¶

type AddReactionRequestObject struct {
	ID                   string         `json:"id,omitempty"`
	Kind                 string         `json:"kind"`
	ActivityID           string         `json:"activity_id"`
	UserID               string         `json:"user_id"`
	Data                 map[string]any `json:"data,omitempty"`
	TargetFeeds          []string       `json:"target_feeds,omitempty"`
	TargetFeedsExtraData map[string]any `json:"target_feeds_extra_data,omitempty"`
	ParentID             string         `json:"parent,omitempty"`
}

AddReactionRequestObject is an object used only when calling the Add* reaction endpoints

type AddToManyRequest ¶

type AddToManyRequest struct {
	Activity Activity `json:"activity,omitempty"`
	FeedIDs  []string `json:"feeds,omitempty"`
}

AddToManyRequest is the API request body for adding an activity to multiple feeds at once.

type AggregatedFeed ¶

type AggregatedFeed struct {
	// contains filtered or unexported fields
}

AggregatedFeed is a Stream aggregated feed, which contains activities grouped based on the grouping function defined on the dashboard.

func (*AggregatedFeed) AddActivities ¶

func (f *AggregatedFeed) AddActivities(ctx context.Context, activities ...Activity) (*AddActivitiesResponse, error)

AddActivities adds multiple activities to the feed.

func (*AggregatedFeed) AddActivity ¶

func (f *AggregatedFeed) AddActivity(ctx context.Context, activity Activity) (*AddActivityResponse, error)

AddActivity adds a new Activity to the feed.

func (*AggregatedFeed) BatchUpdateToTargets ¶ added in v8.2.0

func (f *AggregatedFeed) BatchUpdateToTargets(ctx context.Context, reqs []UpdateToTargetsRequest) (*UpdateToTargetsResponse, error)

BatchUpdateToTargets updates the "to" targets for up to 100 activities, with the options passed as argument for replacing, adding, or removing to targets. NOTE: Only the first update is executed synchronously (same response as UpdateToTargets()), the remaining N-1 updates will be put in a worker queue and executed asynchronously.

func (*AggregatedFeed) Follow ¶

func (f *AggregatedFeed) Follow(ctx context.Context, feed *FlatFeed, opts ...FollowFeedOption) (*BaseResponse, error)

Follow follows the provided feed (which must be a FlatFeed), applying the provided FollowFeedOptions, if any.

func (*AggregatedFeed) GetActivities ¶

GetActivities requests and retrieves the activities and groups for the aggregated feed.

func (*AggregatedFeed) GetActivitiesWithRanking ¶

func (f *AggregatedFeed) GetActivitiesWithRanking(ctx context.Context, ranking string, opts ...GetActivitiesOption) (*AggregatedFeedResponse, error)

GetActivitiesWithRanking returns the activities and groups for the given AggregatedFeed, using the provided ranking method.

func (*AggregatedFeed) GetEnrichedActivities ¶

func (f *AggregatedFeed) GetEnrichedActivities(ctx context.Context, opts ...GetActivitiesOption) (*EnrichedAggregatedFeedResponse, error)

GetEnrichedActivities requests and retrieves the enriched activities and groups for the aggregated feed.

func (*AggregatedFeed) GetEnrichedActivitiesWithRanking ¶

func (f *AggregatedFeed) GetEnrichedActivitiesWithRanking(ctx context.Context, ranking string, opts ...GetActivitiesOption) (*EnrichedAggregatedFeedResponse, error)

GetEnrichedActivitiesWithRanking returns the enriched activities and groups for the given AggregatedFeed, using the provided ranking method.

func (*AggregatedFeed) GetFollowing ¶

func (f *AggregatedFeed) GetFollowing(ctx context.Context, opts ...FollowingOption) (*FollowingResponse, error)

GetFollowing returns the list of the feeds following the feed, applying the provided FollowingOptions, if any.

func (*AggregatedFeed) GetNextPageActivities ¶

func (f *AggregatedFeed) GetNextPageActivities(ctx context.Context, resp *AggregatedFeedResponse) (*AggregatedFeedResponse, error)

GetNextPageActivities returns the activities for the given AggregatedFeed at the "next" page of a previous *AggregatedFeedResponse response, if any.

func (*AggregatedFeed) GetNextPageEnrichedActivities ¶

func (f *AggregatedFeed) GetNextPageEnrichedActivities(ctx context.Context, resp *EnrichedAggregatedFeedResponse) (*EnrichedAggregatedFeedResponse, error)

GetNextPageEnrichedActivities returns the enriched activities for the given AggregatedFeed at the "next" page of a previous *EnrichedAggregatedFeedResponse response, if any.

func (*AggregatedFeed) ID ¶

func (f *AggregatedFeed) ID() string

ID returns the feed ID, as slug:user_id.

func (*AggregatedFeed) RealtimeToken ¶

func (f *AggregatedFeed) RealtimeToken(readonly bool) string

RealtimeToken returns a token that can be used client-side to listen in real-time to feed changes.

func (*AggregatedFeed) RemoveActivityByForeignID ¶

func (f *AggregatedFeed) RemoveActivityByForeignID(ctx context.Context, foreignID string) (*RemoveActivityResponse, error)

RemoveActivityByForeignID removes an activity from the feed (if present), using the provided foreignID string argument as the foreign_id field of the activity.

func (*AggregatedFeed) RemoveActivityByID ¶

func (f *AggregatedFeed) RemoveActivityByID(ctx context.Context, id string) (*RemoveActivityResponse, error)

RemoveActivityByID removes an activity from the feed (if present), using the provided id string argument as the ID field of the activity.

func (*AggregatedFeed) Slug ¶

func (f *AggregatedFeed) Slug() string

Slug returns the feed's slug.

func (*AggregatedFeed) Unfollow ¶

func (f *AggregatedFeed) Unfollow(ctx context.Context, target Feed, opts ...UnfollowOption) (*BaseResponse, error)

Unfollow unfollows the provided feed, applying the provided UnfollowOptions, if any.

func (*AggregatedFeed) UpdateToTargets ¶

func (f *AggregatedFeed) UpdateToTargets(ctx context.Context, activity Activity, opts ...UpdateToTargetsOption) (*UpdateToTargetsResponse, error)

UpdateToTargets updates the "to" targets for the provided activity, with the options passed as argument for replacing, adding, or removing to targets.

func (*AggregatedFeed) UserID ¶

func (f *AggregatedFeed) UserID() string

UserID returns the feed's user_id.

type AggregatedFeedResponse ¶

type AggregatedFeedResponse struct {
	Results []ActivityGroup `json:"results,omitempty"`
	// contains filtered or unexported fields
}

AggregatedFeedResponse is the API response obtained when retrieving activities from an aggregated feed.

type AnalyticsClient ¶

type AnalyticsClient struct {
	// contains filtered or unexported fields
}

AnalyticsClient is a specialized client used to send and track analytics events for enabled apps.

func (*AnalyticsClient) RedirectAndTrack ¶

func (c *AnalyticsClient) RedirectAndTrack(url string, events ...map[string]any) (string, error)

RedirectAndTrack is used to send and track analytics ImpressionEvents. It tracks the events data (either EngagementEvents or ImpressionEvents) and redirects to the provided URL string.

func (*AnalyticsClient) TrackEngagement ¶

func (c *AnalyticsClient) TrackEngagement(ctx context.Context, events ...EngagementEvent) (*BaseResponse, error)

TrackEngagement is used to send and track analytics EngagementEvents.

func (*AnalyticsClient) TrackImpression ¶

func (c *AnalyticsClient) TrackImpression(ctx context.Context, eventsData ImpressionEventsData) (*BaseResponse, error)

TrackImpression is used to send and track analytics ImpressionEvents.

type BaseResponse ¶

type BaseResponse struct {
	// contains filtered or unexported fields
}

type Client ¶

type Client struct {
	// contains filtered or unexported fields
}

Client is a Stream API client used for retrieving feeds and performing API calls.

func New ¶

func New(key, secret string, opts ...ClientOption) (*Client, error)

New builds a new Client with the provided API key and secret. It can be configured further by passing any number of ClientOption parameters.

func NewFromEnv ¶

func NewFromEnv(extraOptions ...ClientOption) (*Client, error)

NewFromEnv build a new Client using environment variables values, with possible values being STREAM_API_KEY, STREAM_API_SECRET, STREAM_API_REGION, and STREAM_API_VERSION. Additional options can still be provided as parameters.

func (*Client) AddToMany ¶

func (c *Client) AddToMany(ctx context.Context, activity Activity, feeds ...Feed) error

AddToMany adds an activity to multiple feeds at once.

func (*Client) AggregatedFeed ¶

func (c *Client) AggregatedFeed(slug, userID string) (*AggregatedFeed, error)

AggregatedFeed returns a new Aggregated Feed with the provided slug and userID.

func (*Client) Analytics ¶

func (c *Client) Analytics() *AnalyticsClient

Analytics returns a new AnalyticsClient sharing the base configuration of the original Client.

func (*Client) Collections ¶

func (c *Client) Collections() *CollectionsClient

Collections returns a new CollectionsClient.

func (*Client) CreateUserToken ¶

func (c *Client) CreateUserToken(userID string) (string, error)

func (*Client) CreateUserTokenWithClaims ¶

func (c *Client) CreateUserTokenWithClaims(userID string, claims map[string]any) (string, error)

func (*Client) FlatFeed ¶

func (c *Client) FlatFeed(slug, userID string) (*FlatFeed, error)

FlatFeed returns a new Flat Feed with the provided slug and userID.

func (*Client) FollowMany ¶

func (c *Client) FollowMany(ctx context.Context, relationships []FollowRelationship, opts ...FollowManyOption) error

FollowMany creates multiple follows at once.

func (*Client) GenericFeed ¶

func (c *Client) GenericFeed(targetID string) (Feed, error)

GenericFeed returns a standard Feed implementation using the provided target id.

func (*Client) GetActivitiesByForeignID ¶

func (c *Client) GetActivitiesByForeignID(ctx context.Context, values ...ForeignIDTimePair) (*GetActivitiesResponse, error)

GetActivitiesByForeignID returns activities for the current app having the given foreign IDs and timestamps.

func (*Client) GetActivitiesByID ¶

func (c *Client) GetActivitiesByID(ctx context.Context, ids ...string) (*GetActivitiesResponse, error)

GetActivitiesByID returns activities for the current app having the given IDs.

func (*Client) GetEnrichedActivitiesByForeignID ¶

func (c *Client) GetEnrichedActivitiesByForeignID(ctx context.Context, values []ForeignIDTimePair, opts ...GetActivitiesOption) (*GetEnrichedActivitiesResponse, error)

GetEnrichedActivitiesByForeignID returns enriched activities for the current app having the given foreign IDs and timestamps.

func (*Client) GetEnrichedActivitiesByID ¶

func (c *Client) GetEnrichedActivitiesByID(ctx context.Context, ids []string, opts ...GetActivitiesOption) (*GetEnrichedActivitiesResponse, error)

GetEnrichedActivitiesByID returns enriched activities for the current app having the given IDs.

func (*Client) NotificationFeed ¶

func (c *Client) NotificationFeed(slug, userID string) (*NotificationFeed, error)

NotificationFeed returns a new Notification Feed with the provided slug and userID.

func (*Client) PartialUpdateActivities ¶

func (c *Client) PartialUpdateActivities(ctx context.Context, changesets ...UpdateActivityRequest) (*UpdateActivitiesResponse, error)

PartialUpdateActivities performs a partial update on multiple activities with the given set and unset operations specified by each changeset. This returns the affected activities.

func (*Client) Personalization ¶

func (c *Client) Personalization() *PersonalizationClient

Personalization returns a new PersonalizationClient.

func (*Client) Reactions ¶

func (c *Client) Reactions() *ReactionsClient

Reactions returns a new ReactionsClient.

func (*Client) UnfollowMany ¶

func (c *Client) UnfollowMany(ctx context.Context, relationships []UnfollowRelationship) error

UnfollowMany removes multiple follow relationships at once.

func (*Client) UpdateActivities ¶

func (c *Client) UpdateActivities(ctx context.Context, activities ...Activity) (*BaseResponse, error)

UpdateActivities updates existing activities.

func (*Client) UpdateActivityByForeignID ¶

func (c *Client) UpdateActivityByForeignID(ctx context.Context, foreignID string, timestamp Time, set map[string]any, unset []string) (*UpdateActivityResponse, error)

UpdateActivityByForeignID performs a partial activity update with the given set and unset operations, returning the affected activity, on the activity with the given foreign ID and timestamp.

func (*Client) UpdateActivityByID ¶

func (c *Client) UpdateActivityByID(ctx context.Context, id string, set map[string]any, unset []string) (*UpdateActivityResponse, error)

UpdateActivityByID performs a partial activity update with the given set and unset operations, returning the affected activity, on the activity with the given ID.

func (*Client) Users ¶

func (c *Client) Users() *UsersClient

Users returns a new UsersClient.

func (*Client) WithTimeout ¶

func (c *Client) WithTimeout(timeout time.Duration) *Client

WithTimeout clones the client with the given timeout. If a custom requester was given while initializing, it will be overridden.

type ClientOption ¶

type ClientOption func(*Client)

ClientOption is a function used for adding specific configuration options to a Stream client.

func WithAPIRegion ¶

func WithAPIRegion(region string) ClientOption

WithAPIRegion sets the region for a given Client.

func WithAPIVersion ¶

func WithAPIVersion(version string) ClientOption

WithAPIVersion sets the version for a given Client.

func WithHTTPRequester ¶

func WithHTTPRequester(requester Requester) ClientOption

WithHTTPRequester sets the HTTP requester for a given client, used mostly for testing.

func WithTimeout ¶

func WithTimeout(dur time.Duration) ClientOption

WithTimeout sets the HTTP request timeout

type CollectionObject ¶

type CollectionObject struct {
	ID   string         `json:"id,omitempty"`
	Data map[string]any `json:"data"`
}

CollectionObject is a collection's object.

func (CollectionObject) MarshalJSON ¶

func (o CollectionObject) MarshalJSON() ([]byte, error)

MarshalJSON marshals the CollectionObject to a flat JSON object.

type CollectionObjectResponse ¶

type CollectionObjectResponse struct {
	CollectionObject `json:",inline"`
	// contains filtered or unexported fields
}

type CollectionsClient ¶

type CollectionsClient struct {
	// contains filtered or unexported fields
}

CollectionsClient is a specialized client used to interact with the Collection endpoints.

func (*CollectionsClient) Add ¶

Add adds a single object to a collection.

func (*CollectionsClient) CreateReference ¶

func (c *CollectionsClient) CreateReference(collection, id string) string

CreateReference returns a new reference string in the form SO:<collection>:<id>.

func (*CollectionsClient) Delete ¶

func (c *CollectionsClient) Delete(ctx context.Context, collection, id string) (*BaseResponse, error)

Delete removes from a collection the object having the given ID.

func (*CollectionsClient) DeleteMany ¶

func (c *CollectionsClient) DeleteMany(ctx context.Context, collection string, ids ...string) (*BaseResponse, error)

DeleteMany removes from a collection the objects having the given IDs.

func (*CollectionsClient) Get ¶

func (c *CollectionsClient) Get(ctx context.Context, collection, id string) (*CollectionObjectResponse, error)

Get retrieves a collection object having the given ID.

func (*CollectionsClient) Select ¶

func (c *CollectionsClient) Select(ctx context.Context, collection string, ids ...string) (*GetCollectionResponse, error)

Select returns a list of CollectionObjects for the given collection name having the given IDs.

func (*CollectionsClient) Update ¶

func (c *CollectionsClient) Update(ctx context.Context, collection, id string, data map[string]any) (*CollectionObjectResponse, error)

Update updates the given collection object's data.

func (*CollectionsClient) Upsert ¶

func (c *CollectionsClient) Upsert(ctx context.Context, collection string, objects ...CollectionObject) (*BaseResponse, error)

Upsert creates new or updates existing objects for the given collection's name.

type Data ¶

type Data struct {
	ID    string         `json:"id"`
	Extra map[string]any `json:"-"`
}

Data is a representation of an enriched activities enriched object, such as the the user or the object

func (Data) MarshalJSON ¶

func (a Data) MarshalJSON() ([]byte, error)

MarshalJSON encodes data into json.

type Duration ¶

type Duration struct {
	time.Duration
}

Duration wraps time.Duration, used because of JSON marshaling and unmarshaling.

func (Duration) MarshalJSON ¶

func (d Duration) MarshalJSON() ([]byte, error)

MarshalJSON marshals the Duration to a string like "30s".

func (*Duration) UnmarshalJSON ¶

func (d *Duration) UnmarshalJSON(b []byte) error

UnmarshalJSON for Duration is required because of the incoming duration string.

type EngagementEvent ¶

type EngagementEvent map[string]any

EngagementEvent represents an analytics engagement event. It must be populated with the available methods, or custom data can be arbitrarily added to it manually as key(string),value(any) pairs.

func (EngagementEvent) WithBoost ¶

func (e EngagementEvent) WithBoost(boost int) EngagementEvent

WithBoost sets the event's boost field to the given int.

func (EngagementEvent) WithContent ¶

func (e EngagementEvent) WithContent(foreignID string, content map[string]any) EngagementEvent

WithContent sets the event's content field to the given content map, and also sets the foreign_id field of such object to the given foreign ID string. If just the foreign ID is required to be sent, use the WithForeignID method.

func (EngagementEvent) WithFeatures ¶

func (e EngagementEvent) WithFeatures(features ...EventFeature) EngagementEvent

WithFeatures sets the event's features field to the given list of EventFeatures.

func (EngagementEvent) WithFeedID ¶

func (e EngagementEvent) WithFeedID(feedID string) EngagementEvent

WithFeedID sets the event's feed_id field to the given string.

func (EngagementEvent) WithForeignID ¶

func (e EngagementEvent) WithForeignID(foreignID string) EngagementEvent

WithForeignID sets the event's content field to the given foreign ID. If the content payload must be an object, use the WithContent method.

func (EngagementEvent) WithLabel ¶

func (e EngagementEvent) WithLabel(label string) EngagementEvent

WithLabel sets the event's label field to the given string.

func (EngagementEvent) WithLocation ¶

func (e EngagementEvent) WithLocation(location string) EngagementEvent

WithLocation sets the event's location field to the given string.

func (EngagementEvent) WithPosition ¶

func (e EngagementEvent) WithPosition(position int) EngagementEvent

WithPosition sets the event's position field to the given int.

func (EngagementEvent) WithTrackedAt ¶

func (e EngagementEvent) WithTrackedAt(trackedAt time.Time) EngagementEvent

WithTrackedAt sets the event's tracked_at field to the given time.Time.

func (EngagementEvent) WithUserData ¶

func (e EngagementEvent) WithUserData(userData *UserData) EngagementEvent

WithUserData sets the event's user_data field to the given UserData's value.

type EnrichedActivity ¶

type EnrichedActivity struct {
	ID              string                         `json:"id,omitempty"`
	Actor           Data                           `json:"actor,omitempty"`
	Verb            string                         `json:"verb,omitempty"`
	Object          Data                           `json:"object,omitempty"`
	ForeignID       string                         `json:"foreign_id,omitempty"`
	Target          Data                           `json:"target,omitempty"`
	Time            Time                           `json:"time,omitempty"`
	Origin          Data                           `json:"origin,omitempty"`
	To              []string                       `json:"to,omitempty"`
	Score           float64                        `json:"score,omitempty"`
	ReactionCounts  map[string]int                 `json:"reaction_counts,omitempty"`
	OwnReactions    map[string][]*EnrichedReaction `json:"own_reactions,omitempty"`
	LatestReactions map[string][]*EnrichedReaction `json:"latest_reactions,omitempty"`
	Extra           map[string]any                 `json:"-"`
}

EnrichedActivity is an enriched Stream activity entity.

func (EnrichedActivity) MarshalJSON ¶

func (a EnrichedActivity) MarshalJSON() ([]byte, error)

MarshalJSON encodes the EnrichedActivity to a valid JSON bytes slice. It's required because of the custom JSON fields and time formats.

func (*EnrichedActivity) UnmarshalJSON ¶

func (a *EnrichedActivity) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the provided JSON payload into the EnrichedActivity. It's required because of the custom JSON fields and time formats.

type EnrichedActivityGroup ¶

type EnrichedActivityGroup struct {
	Activities []EnrichedActivity `json:"activities,omitempty"`
	Score      float64            `json:"score,omitempty"`
	// contains filtered or unexported fields
}

EnrichedActivityGroup is a group of enriched Activities obtained from aggregated feeds.

type EnrichedAggregatedFeedResponse ¶

type EnrichedAggregatedFeedResponse struct {
	Results []EnrichedActivityGroup `json:"results,omitempty"`
	// contains filtered or unexported fields
}

EnrichedAggregatedFeedResponse is the API response obtained when retrieving enriched activities from an aggregated feed.

type EnrichedFlatFeedResponse ¶

type EnrichedFlatFeedResponse struct {
	Results []EnrichedActivity `json:"results,omitempty"`
	// contains filtered or unexported fields
}

EnrichedFlatFeedResponse is the API response obtained when retrieving enriched activities from a flat feed.

type EnrichedNotificationFeedResponse ¶

type EnrichedNotificationFeedResponse struct {
	Results []EnrichedNotificationFeedResult `json:"results"`
	// contains filtered or unexported fields
}

EnrichedNotificationFeedResponse is the API response obtained when retrieving enriched activities from a notification feed.

type EnrichedNotificationFeedResult ¶

type EnrichedNotificationFeedResult struct {
	Activities []EnrichedActivity `json:"activities"`
	// contains filtered or unexported fields
}

EnrichedNotificationFeedResult is a notification-feed specific response, containing the list of enriched activities in the group, plus the extra fields about the group read+seen status.

type EnrichedReaction ¶

type EnrichedReaction struct {
	ID                string                         `json:"id,omitempty"`
	Kind              string                         `json:"kind"`
	ActivityID        string                         `json:"activity_id"`
	UserID            string                         `json:"user_id"`
	Data              map[string]any                 `json:"data,omitempty"`
	TargetFeeds       []string                       `json:"target_feeds,omitempty"`
	ParentID          string                         `json:"parent,omitempty"`
	ChildrenReactions map[string][]*EnrichedReaction `json:"latest_children,omitempty"`
	OwnChildren       map[string][]*EnrichedReaction `json:"own_children,omitempty"`
	ChildrenCounters  map[string]int                 `json:"children_counts,omitempty"`
	User              Data                           `json:"user,omitempty"`
	CreatedAt         Time                           `json:"created_at,omitempty"`
	UpdatedAt         Time                           `json:"updated_at,omitempty"`
}

EnrichedReaction is an enriched Stream reaction entity.

type EventFeature ¶

type EventFeature struct {
	Group string `json:"group"`
	Value string `json:"value"`
}

EventFeature is a single analytics event feature, a pair of group and value strings.

func NewEventFeature ¶

func NewEventFeature(group, value string) EventFeature

NewEventFeature returns a new EventFeature from the given group and value params.

type Feed ¶

Feed is a generic Stream feed, exporting the generic functions common to any Stream feed.

type FilterReactionResponse ¶

type FilterReactionResponse struct {
	Results  []Reaction     `json:"results"`
	Activity map[string]any `json:"activity"`
	// contains filtered or unexported fields
}

FilterReactionResponse is the response received from the ReactionsClient.Filter call.

type FilterReactionsAttribute ¶

type FilterReactionsAttribute func() string

FilterReactionsAttribute specifies the filtering method of Reactions.Filter()

func ByActivityID ¶

func ByActivityID(activityID string) FilterReactionsAttribute

ByActivityID will filter reactions based on the specified activity id.

func ByReactionID ¶

func ByReactionID(reactionID string) FilterReactionsAttribute

ByReactionID will filter reactions based on the specified parent reaction id.

func ByUserID ¶

func ByUserID(userID string) FilterReactionsAttribute

ByUserID will filter reactions based on the specified user id.

func (FilterReactionsAttribute) ByKind ¶

ByKind filters reactions by kind, after the initial desired filtering method was applied.

type FilterReactionsOption ¶

type FilterReactionsOption struct {
	// contains filtered or unexported fields
}

FilterReactionsOption is an option used by Reactions.Filter() to support pagination.

func WithActivityData ¶

func WithActivityData() FilterReactionsOption

WithActivityData will enable returning the activity data when filtering reactions by activity_id.

func WithChildrenUserID ¶

func WithChildrenUserID(userID string) FilterReactionsOption

WithChildrenUserID will enable further filtering own children by the given user id. It's different than FilterReactionsAttribute user id.

func WithIDGT ¶

func WithIDGT(id string) FilterReactionsOption

WithIDGT adds the id_gt parameter to API calls, used when retrieving paginated reactions.

func WithIDGTE ¶

func WithIDGTE(id string) FilterReactionsOption

WithIDGTE adds the id_gte parameter to API calls, used when retrieving paginated reactions, returning activities with ID greater or equal than the provided id.

func WithIDLT ¶

func WithIDLT(id string) FilterReactionsOption

WithIDLT adds the id_lt parameter to API calls, used when retrieving paginated reactions.

func WithIDLTE ¶

func WithIDLTE(id string) FilterReactionsOption

WithIDLTE adds the id_lte parameter to API calls, used when retrieving paginated reactions.

func WithLimit ¶

func WithLimit(limit int) FilterReactionsOption

WithLimit adds the limit parameter to the Reactions.Filter() call.

func WithOwnChildren ¶

func WithOwnChildren() FilterReactionsOption

WithOwnChildren will enable returning the children reactions when filtering reactions by parent ID.

func WithOwnUserID ¶

func WithOwnUserID(userID string) FilterReactionsOption

WithOwnUserID will enable further filtering by the given user id. It's similar to FilterReactionsAttribute user id.

func WithRanking ¶ added in v8.4.0

func WithRanking(ranking string) FilterReactionsOption

WithRanking adds the ranking parameter to API calls, used when retrieving ranked reactions.

type FlatFeed ¶

type FlatFeed struct {
	// contains filtered or unexported fields
}

FlatFeed is a Stream flat feed.

func (*FlatFeed) AddActivities ¶

func (f *FlatFeed) AddActivities(ctx context.Context, activities ...Activity) (*AddActivitiesResponse, error)

AddActivities adds multiple activities to the feed.

func (*FlatFeed) AddActivity ¶

func (f *FlatFeed) AddActivity(ctx context.Context, activity Activity) (*AddActivityResponse, error)

AddActivity adds a new Activity to the feed.

func (*FlatFeed) BatchUpdateToTargets ¶ added in v8.2.0

func (f *FlatFeed) BatchUpdateToTargets(ctx context.Context, reqs []UpdateToTargetsRequest) (*UpdateToTargetsResponse, error)

BatchUpdateToTargets updates the "to" targets for up to 100 activities, with the options passed as argument for replacing, adding, or removing to targets. NOTE: Only the first update is executed synchronously (same response as UpdateToTargets()), the remaining N-1 updates will be put in a worker queue and executed asynchronously.

func (*FlatFeed) Follow ¶

func (f *FlatFeed) Follow(ctx context.Context, feed *FlatFeed, opts ...FollowFeedOption) (*BaseResponse, error)

Follow follows the provided feed (which must be a FlatFeed), applying the provided FollowFeedOptions, if any.

func (*FlatFeed) FollowStats ¶

func (f *FlatFeed) FollowStats(ctx context.Context, opts ...FollowStatOption) (*FollowStatResponse, error)

FollowStats returns the follower/following counts of the feed. If options are given, counts are filtered for the given slugs. Counts will be capped at 10K, if higher counts are needed and contact to support.

func (*FlatFeed) GetActivities ¶

func (f *FlatFeed) GetActivities(ctx context.Context, opts ...GetActivitiesOption) (*FlatFeedResponse, error)

GetActivities returns the activities for the given FlatFeed, filtering results with the provided GetActivitiesOption parameters.

func (*FlatFeed) GetActivitiesWithRanking ¶

func (f *FlatFeed) GetActivitiesWithRanking(ctx context.Context, ranking string, opts ...GetActivitiesOption) (*FlatFeedResponse, error)

GetActivitiesWithRanking returns the activities (filtered) for the given FlatFeed, using the provided ranking method.

func (*FlatFeed) GetEnrichedActivities ¶

func (f *FlatFeed) GetEnrichedActivities(ctx context.Context, opts ...GetActivitiesOption) (*EnrichedFlatFeedResponse, error)

GetEnrichedActivities returns the enriched activities for the given FlatFeed, filtering results with the provided GetActivitiesOption parameters.

func (*FlatFeed) GetEnrichedActivitiesWithRanking ¶

func (f *FlatFeed) GetEnrichedActivitiesWithRanking(ctx context.Context, ranking string, opts ...GetActivitiesOption) (*EnrichedFlatFeedResponse, error)

GetEnrichedActivitiesWithRanking returns the enriched activities (filtered) for the given FlatFeed, using the provided ranking method.

func (*FlatFeed) GetFollowers ¶

func (f *FlatFeed) GetFollowers(ctx context.Context, opts ...FollowersOption) (*FollowersResponse, error)

GetFollowers returns the feeds following the given FlatFeed.

func (*FlatFeed) GetFollowing ¶

func (f *FlatFeed) GetFollowing(ctx context.Context, opts ...FollowingOption) (*FollowingResponse, error)

GetFollowing returns the list of the feeds following the feed, applying the provided FollowingOptions, if any.

func (*FlatFeed) GetNextPageActivities ¶

func (f *FlatFeed) GetNextPageActivities(ctx context.Context, resp *FlatFeedResponse) (*FlatFeedResponse, error)

GetNextPageActivities returns the activities for the given FlatFeed at the "next" page of a previous *FlatFeedResponse response, if any.

func (*FlatFeed) GetNextPageEnrichedActivities ¶

func (f *FlatFeed) GetNextPageEnrichedActivities(ctx context.Context, resp *EnrichedFlatFeedResponse) (*EnrichedFlatFeedResponse, error)

GetNextPageEnrichedActivities returns the enriched activities for the given FlatFeed at the "next" page of a previous *EnrichedFlatFeedResponse response, if any.

func (*FlatFeed) ID ¶

func (f *FlatFeed) ID() string

ID returns the feed ID, as slug:user_id.

func (*FlatFeed) RealtimeToken ¶

func (f *FlatFeed) RealtimeToken(readonly bool) string

RealtimeToken returns a token that can be used client-side to listen in real-time to feed changes.

func (*FlatFeed) RemoveActivityByForeignID ¶

func (f *FlatFeed) RemoveActivityByForeignID(ctx context.Context, foreignID string) (*RemoveActivityResponse, error)

RemoveActivityByForeignID removes an activity from the feed (if present), using the provided foreignID string argument as the foreign_id field of the activity.

func (*FlatFeed) RemoveActivityByID ¶

func (f *FlatFeed) RemoveActivityByID(ctx context.Context, id string) (*RemoveActivityResponse, error)

RemoveActivityByID removes an activity from the feed (if present), using the provided id string argument as the ID field of the activity.

func (*FlatFeed) Slug ¶

func (f *FlatFeed) Slug() string

Slug returns the feed's slug.

func (*FlatFeed) Unfollow ¶

func (f *FlatFeed) Unfollow(ctx context.Context, target Feed, opts ...UnfollowOption) (*BaseResponse, error)

Unfollow unfollows the provided feed, applying the provided UnfollowOptions, if any.

func (*FlatFeed) UpdateToTargets ¶

func (f *FlatFeed) UpdateToTargets(ctx context.Context, activity Activity, opts ...UpdateToTargetsOption) (*UpdateToTargetsResponse, error)

UpdateToTargets updates the "to" targets for the provided activity, with the options passed as argument for replacing, adding, or removing to targets.

func (*FlatFeed) UserID ¶

func (f *FlatFeed) UserID() string

UserID returns the feed's user_id.

type FlatFeedResponse ¶

type FlatFeedResponse struct {
	Results []Activity `json:"results,omitempty"`
	// contains filtered or unexported fields
}

FlatFeedResponse is the API response obtained when retrieving activities from a flat feed.

type FollowFeedOption ¶

type FollowFeedOption func(*followFeedOptions)

FollowFeedOption is a function used to customize FollowFeed API calls.

func WithFollowFeedActivityCopyLimit ¶

func WithFollowFeedActivityCopyLimit(activityCopyLimit int) FollowFeedOption

WithFollowFeedActivityCopyLimit sets the activity copy threshold for Follow Feed API calls.

type FollowManyOption ¶

type FollowManyOption struct {
	// contains filtered or unexported fields
}

FollowManyOption is an option to customize behavior of Follow Many calls.

func WithFollowManyActivityCopyLimit ¶

func WithFollowManyActivityCopyLimit(activityCopyLimit int) FollowManyOption

WithFollowManyActivityCopyLimit sets how many activities should be copied from the target feed.

type FollowRelationship ¶

type FollowRelationship struct {
	Source            string `json:"source,omitempty"`
	Target            string `json:"target,omitempty"`
	ActivityCopyLimit *int   `json:"activity_copy_limit,omitempty"`
}

FollowRelationship represents a follow relationship between a source ("follower") and a target ("following"), used for FollowMany requests.

func NewFollowRelationship ¶

func NewFollowRelationship(source, target Feed, opts ...FollowRelationshipOption) FollowRelationship

NewFollowRelationship is a helper for creating a FollowRelationship from the source ("follower") and target ("following") feeds.

type FollowRelationshipOption ¶

type FollowRelationshipOption func(r *FollowRelationship)

FollowRelationshipOption customizes a FollowRelationship.

func WithFollowRelationshipActivityCopyLimit ¶

func WithFollowRelationshipActivityCopyLimit(activityCopyLimit int) FollowRelationshipOption

WithFollowRelationshipActivityCopyLimit sets the ActivityCopyLimit field for a given FollowRelationship.

type FollowStatOption ¶

type FollowStatOption struct {
	// contains filtered or unexported fields
}

FollowStatOption is an option used to customize FollowStats API calls.

func WithFollowerSlugs ¶

func WithFollowerSlugs(slugs ...string) FollowStatOption

WithFollowerSlugs sets the follower feed slugs for filtering in counting.

func WithFollowingSlugs ¶

func WithFollowingSlugs(slugs ...string) FollowStatOption

WithFollowerSlugs sets the following feed slugs for filtering in counting.

type FollowStatResponse ¶

type FollowStatResponse struct {
	// contains filtered or unexported fields
}

FollowStatResponse is the result of follow stats endpoint.

type Follower ¶

type Follower struct {
	FeedID   string `json:"feed_id,omitempty"`
	TargetID string `json:"target_id,omitempty"`
}

Follower is the representation of a feed following another feed.

type FollowersOption ¶

type FollowersOption struct {
	// contains filtered or unexported fields
}

FollowersOption is an option usable by followers feed methods.

func WithFollowersLimit ¶

func WithFollowersLimit(limit int) FollowersOption

WithFollowersLimit limits the number of followers in the response to the provided limit.

func WithFollowersOffset ¶

func WithFollowersOffset(offset int) FollowersOption

WithFollowersOffset returns followers starting from the given offset.

type FollowersResponse ¶

type FollowersResponse struct {
	// contains filtered or unexported fields
}

FollowersResponse is the API response obtained when retrieving followers from a feed.

type FollowingOption ¶

type FollowingOption struct {
	// contains filtered or unexported fields
}

FollowingOption is an option usable by following feed methods.

func WithFollowingFilter ¶

func WithFollowingFilter(ids ...string) FollowingOption

WithFollowingFilter adds the filter parameter to API calls, used when retrieving following feeds, allowing the check whether certain feeds are being followed.

func WithFollowingLimit ¶

func WithFollowingLimit(limit int) FollowingOption

WithFollowingLimit limits the number of followings in the response to the provided limit.

func WithFollowingOffset ¶

func WithFollowingOffset(offset int) FollowingOption

WithFollowingOffset returns followings starting from the given offset.

type FollowingResponse ¶

type FollowingResponse struct {
	// contains filtered or unexported fields
}

FollowingResponse is the API response obtained when retrieving following feeds from a feed.

type ForeignIDTimePair ¶

type ForeignIDTimePair struct {
	ForeignID string
	Timestamp Time
}

ForeignIDTimePair couples an activity's foreignID and timestamp.

func NewForeignIDTimePair ¶

func NewForeignIDTimePair(foreignID string, timestamp Time) ForeignIDTimePair

NewForeignIDTimePair creates a new ForeignIDTimePair with the given foreign ID and timestamp.

type GetActivitiesOption ¶

type GetActivitiesOption struct {
	// contains filtered or unexported fields
}

GetActivitiesOption is an option usable by GetActivities methods for flat and aggregated feeds.

func WithActivitiesIDGT ¶

func WithActivitiesIDGT(id string) GetActivitiesOption

WithActivitiesIDGT adds the id_gt parameter to API calls, used when retrieving paginated activities from feeds, returning activities with ID greater than the provided id.

func WithActivitiesIDGTE ¶

func WithActivitiesIDGTE(id string) GetActivitiesOption

WithActivitiesIDGTE adds the id_gte parameter to API calls, used when retrieving paginated activities from feeds, returning activities with ID greater or equal than the provided id.

func WithActivitiesIDLT ¶

func WithActivitiesIDLT(id string) GetActivitiesOption

WithActivitiesIDLT adds the id_lt parameter to API calls, used when retrieving paginated activities from feeds, returning activities with ID lesser than the provided id.

func WithActivitiesIDLTE ¶

func WithActivitiesIDLTE(id string) GetActivitiesOption

WithActivitiesIDLTE adds the id_lte parameter to API calls, used when retrieving paginated activities from feeds, returning activities with ID lesser or equal than the provided id.

func WithActivitiesLimit ¶

func WithActivitiesLimit(limit int) GetActivitiesOption

WithActivitiesLimit adds the limit parameter to API calls which support it, limiting the number of results in the response to the provided limit threshold. Supported operations: retrieve activities, retrieve followers, retrieve following.

func WithActivitiesOffset ¶

func WithActivitiesOffset(offset int) GetActivitiesOption

WithActivitiesOffset adds the offset parameter to API calls which support it, getting results starting from the provided offset index. Supported operations: retrieve activities, retrieve followers, retrieve following.

func WithActivitiesRanking ¶ added in v8.4.0

func WithActivitiesRanking(ranking string) GetActivitiesOption

func WithCustomParam ¶

func WithCustomParam(name, value string) GetActivitiesOption

WithCustomParam adds a custom parameter to the read request.

func WithEnrichFirstReactions ¶

func WithEnrichFirstReactions() GetActivitiesOption

WithEnrichRecentReactions enriches the activities with the first reactions to them.

func WithEnrichOwnChildren ¶

func WithEnrichOwnChildren() GetActivitiesOption

WithEnrichOwnChildren enriches the activities with the children reactions.

func WithEnrichOwnChildrenKindsFilter ¶

func WithEnrichOwnChildrenKindsFilter(kinds ...string) GetActivitiesOption

WithEnrichOwnChildrenKindsFilter filters the reactions by the specified kinds for own children

func WithEnrichOwnReactions ¶

func WithEnrichOwnReactions() GetActivitiesOption

WithEnrichOwnReactions enriches the activities with the reactions to them.

func WithEnrichReactionCounts ¶

func WithEnrichReactionCounts() GetActivitiesOption

WithEnrichReactionCounts enriches the activities with the reaction counts.

func WithEnrichReactionKindsFilter ¶

func WithEnrichReactionKindsFilter(kinds ...string) GetActivitiesOption

WithEnrichReactionKindsFilter filters the reactions by the specified kinds

func WithEnrichReactionsLimit ¶

func WithEnrichReactionsLimit(limit int) GetActivitiesOption

WithEnrichReactionsLimit specifies how many reactions to include in the enrichment.

func WithEnrichRecentReactions ¶

func WithEnrichRecentReactions() GetActivitiesOption

WithEnrichRecentReactions enriches the activities with the recent reactions to them.

func WithEnrichRecentReactionsLimit ¶

func WithEnrichRecentReactionsLimit(limit int) GetActivitiesOption

WithEnrichRecentReactionsLimit specifies how many recent reactions to include in the enrichment.

func WithEnrichUserReactions ¶ added in v8.1.0

func WithEnrichUserReactions(userID string) GetActivitiesOption

func WithExternalRankingVars ¶ added in v8.4.0

func WithExternalRankingVars(externalVarJSON string) GetActivitiesOption

externalVarJSON should be valid json

func WithNotificationsMarkRead ¶

func WithNotificationsMarkRead(all bool, activityIDs ...string) GetActivitiesOption

WithNotificationsMarkRead marks as read the given activity ids in a notification feed. If the all parameter is true, every activity in the feed is marked as read.

func WithNotificationsMarkSeen ¶

func WithNotificationsMarkSeen(all bool, activityIDs ...string) GetActivitiesOption

WithNotificationsMarkSeen marks as seen the given activity ids in a notification feed. If the all parameter is true, every activity in the feed is marked as seen.

func WithRankingScoreVars ¶ added in v8.3.0

func WithRankingScoreVars() GetActivitiesOption

type GetActivitiesResponse ¶

type GetActivitiesResponse struct {
	Results []Activity `json:"results"`
	// contains filtered or unexported fields
}

GetActivitiesResponse contains a slice of Activity returned by GetActivitiesByID and GetActivitiesByForeignID requests.

type GetCollectionResponse ¶

type GetCollectionResponse struct {
	Objects []GetCollectionResponseObject
	// contains filtered or unexported fields
}

GetCollectionResponse represents a single response coming from a Collection Select request after a CollectionsClient.Select call.

type GetCollectionResponseObject ¶

type GetCollectionResponseObject struct {
	ForeignID string         `json:"foreign_id"`
	Data      map[string]any `json:"data"`
}

GetCollectionResponseObject represents a single response coming from a Collection Get request after a CollectionsClient.Get call.

type GetEnrichedActivitiesResponse ¶

type GetEnrichedActivitiesResponse struct {
	Results []EnrichedActivity `json:"results"`
	// contains filtered or unexported fields
}

GetEnrichedActivitiesResponse contains a slice of enriched Activity returned by GetEnrichedActivitiesByID and GetEnrichedActivitiesByForeignID requests.

type ImpressionEventsData ¶

type ImpressionEventsData map[string]any

ImpressionEventsData represents the payload of an arbitrary number of impression events. It must be populated with the available methods, or custom data can be arbitrarily added to it manually as key(string),value(any) pairs.

func (ImpressionEventsData) AddForeignIDs ¶

func (d ImpressionEventsData) AddForeignIDs(foreignIDs ...string) ImpressionEventsData

AddForeignIDs adds the given foreign ID strings to the content_list field, creating it if it doesn't exist.

func (ImpressionEventsData) WithFeatures ¶

func (d ImpressionEventsData) WithFeatures(features ...EventFeature) ImpressionEventsData

WithFeatures sets the features field to the given list of EventFeatures.

func (ImpressionEventsData) WithFeedID ¶

func (d ImpressionEventsData) WithFeedID(feedID string) ImpressionEventsData

WithFeedID sets the feed_id field to the given string.

func (ImpressionEventsData) WithForeignIDs ¶

func (d ImpressionEventsData) WithForeignIDs(foreignIDs ...string) ImpressionEventsData

WithForeignIDs sets the content_list field to the given list of strings.

func (ImpressionEventsData) WithLocation ¶

func (d ImpressionEventsData) WithLocation(location string) ImpressionEventsData

WithLocation sets the location field to the given string.

func (ImpressionEventsData) WithPosition ¶

func (d ImpressionEventsData) WithPosition(position int) ImpressionEventsData

WithPosition sets the position field to the given int.

func (ImpressionEventsData) WithTrackedAt ¶

func (d ImpressionEventsData) WithTrackedAt(trackedAt time.Time) ImpressionEventsData

WithTrackedAt sets the tracked_at field to the given time.Time.

func (ImpressionEventsData) WithUserData ¶

func (d ImpressionEventsData) WithUserData(userData *UserData) ImpressionEventsData

WithUserData sets the user_data field to the given UserData value.

type NotificationFeed ¶

type NotificationFeed struct {
	// contains filtered or unexported fields
}

NotificationFeed is a Stream notification feed.

func (*NotificationFeed) AddActivities ¶

func (f *NotificationFeed) AddActivities(ctx context.Context, activities ...Activity) (*AddActivitiesResponse, error)

AddActivities adds multiple activities to the feed.

func (*NotificationFeed) AddActivity ¶

func (f *NotificationFeed) AddActivity(ctx context.Context, activity Activity) (*AddActivityResponse, error)

AddActivity adds a new Activity to the feed.

func (*NotificationFeed) BatchUpdateToTargets ¶ added in v8.2.0

func (f *NotificationFeed) BatchUpdateToTargets(ctx context.Context, reqs []UpdateToTargetsRequest) (*UpdateToTargetsResponse, error)

BatchUpdateToTargets updates the "to" targets for up to 100 activities, with the options passed as argument for replacing, adding, or removing to targets. NOTE: Only the first update is executed synchronously (same response as UpdateToTargets()), the remaining N-1 updates will be put in a worker queue and executed asynchronously.

func (*NotificationFeed) Follow ¶

func (f *NotificationFeed) Follow(ctx context.Context, feed *FlatFeed, opts ...FollowFeedOption) (*BaseResponse, error)

Follow follows the provided feed (which must be a FlatFeed), applying the provided FollowFeedOptions, if any.

func (*NotificationFeed) GetActivities ¶

GetActivities returns the activities for the given NotificationFeed, filtering results with the provided GetActivitiesOption parameters.

func (*NotificationFeed) GetEnrichedActivities ¶

GetEnrichedActivities returns the enriched activities for the given NotificationFeed, filtering results with the provided GetActivitiesOption parameters.

func (*NotificationFeed) GetFollowing ¶

func (f *NotificationFeed) GetFollowing(ctx context.Context, opts ...FollowingOption) (*FollowingResponse, error)

GetFollowing returns the list of the feeds following the feed, applying the provided FollowingOptions, if any.

func (*NotificationFeed) GetNextPageActivities ¶

GetNextPageActivities returns the activities for the given NotificationFeed at the "next" page of a previous *NotificationFeedResponse response, if any.

func (*NotificationFeed) GetNextPageEnrichedActivities ¶

GetNextPageEnrichedActivities returns the enriched activities for the given NotificationFeed at the "next" page of a previous *EnrichedNotificationFeedResponse response, if any.

func (*NotificationFeed) ID ¶

func (f *NotificationFeed) ID() string

ID returns the feed ID, as slug:user_id.

func (*NotificationFeed) RealtimeToken ¶

func (f *NotificationFeed) RealtimeToken(readonly bool) string

RealtimeToken returns a token that can be used client-side to listen in real-time to feed changes.

func (*NotificationFeed) RemoveActivityByForeignID ¶

func (f *NotificationFeed) RemoveActivityByForeignID(ctx context.Context, foreignID string) (*RemoveActivityResponse, error)

RemoveActivityByForeignID removes an activity from the feed (if present), using the provided foreignID string argument as the foreign_id field of the activity.

func (*NotificationFeed) RemoveActivityByID ¶

func (f *NotificationFeed) RemoveActivityByID(ctx context.Context, id string) (*RemoveActivityResponse, error)

RemoveActivityByID removes an activity from the feed (if present), using the provided id string argument as the ID field of the activity.

func (*NotificationFeed) Slug ¶

func (f *NotificationFeed) Slug() string

Slug returns the feed's slug.

func (*NotificationFeed) Unfollow ¶

func (f *NotificationFeed) Unfollow(ctx context.Context, target Feed, opts ...UnfollowOption) (*BaseResponse, error)

Unfollow unfollows the provided feed, applying the provided UnfollowOptions, if any.

func (*NotificationFeed) UpdateToTargets ¶

func (f *NotificationFeed) UpdateToTargets(ctx context.Context, activity Activity, opts ...UpdateToTargetsOption) (*UpdateToTargetsResponse, error)

UpdateToTargets updates the "to" targets for the provided activity, with the options passed as argument for replacing, adding, or removing to targets.

func (*NotificationFeed) UserID ¶

func (f *NotificationFeed) UserID() string

UserID returns the feed's user_id.

type NotificationFeedResponse ¶

type NotificationFeedResponse struct {
	Results []NotificationFeedResult `json:"results"`
	// contains filtered or unexported fields
}

NotificationFeedResponse is the API response obtained when retrieving activities from a notification feed.

type NotificationFeedResult ¶

type NotificationFeedResult struct {
	Activities []Activity `json:"activities"`
	// contains filtered or unexported fields
}

NotificationFeedResult is a notification-feed specific response, containing the list of activities in the group, plus the extra fields about the group read+seen status.

type PersonalizationClient ¶

type PersonalizationClient struct {
	// contains filtered or unexported fields
}

PersonalizationClient is a specialized client for personalization features.

func (*PersonalizationClient) Delete ¶

func (c *PersonalizationClient) Delete(ctx context.Context, resource string, params map[string]any) (*PersonalizationResponse, error)

Delete removes data from the given resource, adding the given params to the request.

func (*PersonalizationClient) Get ¶

func (c *PersonalizationClient) Get(ctx context.Context, resource string, params map[string]any) (*PersonalizationResponse, error)

Get obtains a PersonalizationResponse for the given resource and params.

func (*PersonalizationClient) Post ¶

func (c *PersonalizationClient) Post(ctx context.Context, resource string, params, data map[string]any) (*PersonalizationResponse, error)

Post sends data to the given resource, adding the given params to the request.

type PersonalizationResponse ¶

type PersonalizationResponse struct {
	AppID    int              `json:"app_id"`
	Duration Duration         `json:"duration"`
	Rate     Rate             `json:"ratelimit"`
	Limit    int              `json:"limit"`
	Offset   int              `json:"offset"`
	Version  string           `json:"version"`
	Next     string           `json:"next"`
	Results  []map[string]any `json:"results"`
	// contains filtered or unexported fields
}

PersonalizationResponse is a generic response from the personalization endpoints obtained after a PersonalizationClient.Get call. Common JSON fields are directly available as struct fields, while non-standard JSON fields can be retrieved using the Extra() method.

func (*PersonalizationResponse) Extra ¶

func (r *PersonalizationResponse) Extra() map[string]any

Extra returns the non-common response fields as a map[string]any.

func (*PersonalizationResponse) UnmarshalJSON ¶

func (r *PersonalizationResponse) UnmarshalJSON(data []byte) error

UnmarshalJSON for PersonalizationResponse is required because of the incoming duration string, and for storing non-standard fields without losing their values, so they can be retrieved later on with the Extra() function.

type Rate ¶

type Rate struct {
	// Reset is the time for limit to reset
	Reset Time

	// Limit is the existing limit for the resource
	Limit int

	// Remaining is the remaining possible calls
	Remaining int
}

Rate is the information to be filled if a rate limited response

func NewRate ¶

func NewRate(headers http.Header) *Rate

type Reaction ¶

type Reaction struct {
	AddReactionRequestObject
	User              User                   `json:"user,omitempty"`
	ChildrenReactions map[string][]*Reaction `json:"latest_children,omitempty"`
	OwnChildren       map[string][]*Reaction `json:"own_children,omitempty"`
	ChildrenCounters  map[string]any         `json:"children_counts,omitempty"`
	CreatedAt         time.Time              `json:"created_at"`
	UpdatedAt         time.Time              `json:"updated_at"`
	DeletedAt         *time.Time             `json:"deleted_at,omitempty"`
	Score             float64                `json:"score,omitempty"`
}

Reaction is a reaction retrieved from the API.

type ReactionResponse ¶

type ReactionResponse struct {
	Reaction `json:",inline"`
	// contains filtered or unexported fields
}

type ReactionsClient ¶

type ReactionsClient struct {
	// contains filtered or unexported fields
}

ReactionsClient is a specialized client used to interact with the Reactions endpoints.

func (*ReactionsClient) Add ¶

Add adds a reaction.

func (*ReactionsClient) AddChild ¶

AddChild adds a child reaction to the provided parent.

func (*ReactionsClient) Delete ¶

Delete deletes a reaction having the given id. The reaction is permanently deleted and cannot be restored. Returned reaction is empty.

func (*ReactionsClient) Filter ¶

Filter lists reactions based on the provided criteria and with the specified pagination.

func (*ReactionsClient) Get ¶

Get retrieves a reaction having the given id.

func (*ReactionsClient) GetNextPageFilteredReactions ¶

func (c *ReactionsClient) GetNextPageFilteredReactions(ctx context.Context, resp *FilterReactionResponse) (*FilterReactionResponse, error)

GetNextPageFilteredReactions returns the reactions at the "next" page of a previous *FilterReactionResponse response, if any.

func (*ReactionsClient) Restore ¶ added in v8.3.0

func (c *ReactionsClient) Restore(ctx context.Context, id string) error

Restore restores a soft deleted reaction having the given id.

func (*ReactionsClient) SoftDelete ¶ added in v8.3.0

func (c *ReactionsClient) SoftDelete(ctx context.Context, id string) error

SoftDelete soft-deletes a reaction having the given id. It is possible to restore this reaction using ReactionsClient.Restore.

func (*ReactionsClient) Update ¶

func (c *ReactionsClient) Update(ctx context.Context, id string, data map[string]any, targetFeeds []string) (*ReactionResponse, error)

Update updates the reaction's data and/or target feeds.

type RemoveActivityResponse ¶

type RemoveActivityResponse struct {
	Removed string `json:"removed"`
	// contains filtered or unexported fields
}

RemoveActivityResponse is the API response obtained when removing an activity from a feed.

type Requester ¶

type Requester interface {
	Do(*http.Request) (*http.Response, error)
}

Requester performs HTTP requests.

type Time ¶

type Time struct {
	time.Time
}

Time wraps time.Time, used because of custom API time format in JSON marshaling and unmarshaling.

func (Time) MarshalJSON ¶

func (t Time) MarshalJSON() ([]byte, error)

MarshalJSON marshals Time (NOTE! in UTC) into a string formatted with the TimeLayout format.

func (*Time) UnmarshalJSON ¶

func (t *Time) UnmarshalJSON(b []byte) error

UnmarshalJSON for Time is required because of the incoming time string format.

type UnfollowOption ¶

type UnfollowOption struct {
	// contains filtered or unexported fields
}

UnfollowOption is an option usable with the Unfollow feed method.

func WithUnfollowKeepHistory ¶

func WithUnfollowKeepHistory(keepHistory bool) UnfollowOption

WithUnfollowKeepHistory adds the keep_history parameter to API calls, used to keep history when unfollowing feeds, rather than purging it (default behavior). If the keepHistory parameter is false, nothing happens.

type UnfollowRelationship ¶

type UnfollowRelationship struct {
	Source      string `json:"source"`
	Target      string `json:"target"`
	KeepHistory bool   `json:"keep_history"`
}

UnfollowRelationship represents a single follow relationship to remove, used for UnfollowMany requests.

func NewUnfollowRelationship ¶

func NewUnfollowRelationship(source, target Feed, opts ...UnfollowRelationshipOption) UnfollowRelationship

NewUnfollowRelationship is a helper for creating an UnfollowRelationship from the source ("follower") and target ("following") feeds.

type UnfollowRelationshipOption ¶

type UnfollowRelationshipOption func(r *UnfollowRelationship)

UnfollowRelationshipOption customizes an UnfollowRelationship.

func WithUnfollowRelationshipKeepHistory ¶

func WithUnfollowRelationshipKeepHistory() UnfollowRelationshipOption

WithUnfollowRelationshipKeepHistory sets the KeepHistory field for a given UnfollowRelationship.

type UpdateActivitiesResponse ¶

type UpdateActivitiesResponse struct {
	Activities []*Activity `json:"activities"`
	// contains filtered or unexported fields
}

type UpdateActivityRequest ¶

type UpdateActivityRequest struct {
	ID        *string        `json:"id,omitempty"`
	ForeignID *string        `json:"foreign_id,omitempty"`
	Time      *Time          `json:"time,omitempty"`
	Set       map[string]any `json:"set,omitempty"`
	Unset     []string       `json:"unset,omitempty"`
}

UpdateActivityRequest is the API request body for partially updating an activity.

func NewUpdateActivityRequestByForeignID ¶

func NewUpdateActivityRequestByForeignID(foreignID string, timestamp Time, set map[string]any, unset []string) UpdateActivityRequest

NewUpdateActivityRequestByForeignID creates a new UpdateActivityRequest to be used by PartialUpdateActivities

func NewUpdateActivityRequestByID ¶

func NewUpdateActivityRequestByID(id string, set map[string]any, unset []string) UpdateActivityRequest

NewUpdateActivityRequestByID creates a new UpdateActivityRequest to be used by PartialUpdateActivities

type UpdateActivityResponse ¶

type UpdateActivityResponse struct {
	// contains filtered or unexported fields
}

UpdateActivityResponse is the response returned by the UpdateActivityByID and UpdateActivityByForeignID methods.

func (*UpdateActivityResponse) UnmarshalJSON ¶

func (a *UpdateActivityResponse) UnmarshalJSON(buf []byte) error

UnmarshalJSON is the custom unmarshaler since activity custom unmarshaler can take extra values.

type UpdateToTargetsOption ¶

type UpdateToTargetsOption func(*updateToTargetsRequest)

UpdateToTargetsOption determines what operations perform during an UpdateToTargets API call.

func WithToTargetsAdd ¶

func WithToTargetsAdd(targets ...string) UpdateToTargetsOption

WithToTargetsAdd sets the add to targets, adding them to the activity's existing ones.

func WithToTargetsNew ¶

func WithToTargetsNew(targets ...string) UpdateToTargetsOption

WithToTargetsNew sets the new to targets, replacing all the existing ones. It cannot be used in combination with any other UpdateToTargetsOption.

func WithToTargetsRemove ¶

func WithToTargetsRemove(targets ...string) UpdateToTargetsOption

WithToTargetsRemove sets the remove to targets, removing them from activity's the existing ones.

type UpdateToTargetsRequest ¶ added in v8.2.0

type UpdateToTargetsRequest struct {
	ForeignID string
	Time      Time
	Opts      []UpdateToTargetsOption
}

UpdateToTargetsRequest is a helper type for batch updating TO targets.

type UpdateToTargetsResponse ¶

type UpdateToTargetsResponse struct {
	Activity map[string]any `json:"activity"`
	Added    []string       `json:"added"`
	Removed  []string       `json:"removed"`
	// contains filtered or unexported fields
}

UpdateToTargetsResponse is the response for updating to targets of an activity.

type User ¶

type User struct {
	ID   string         `json:"id"`
	Data map[string]any `json:"data,omitempty"`
}

User represents a user

type UserData ¶

type UserData struct {
	// contains filtered or unexported fields
}

UserData represents an analytics event user data field, which can either be a single string/integer representing the user's ID, or a dictionary made of an ID (string or integer) and a string alias. For example NewUserData().Int(123).Alias("john") will result in a dictionary like {"user_data":{"id": 123, "alias": "john"}}, while NewUserData().String("bob") will result in {"user_data": "bob"}.

func NewUserData ¶

func NewUserData() *UserData

NewUserData initializes an empty UserData type, which must be populated using the String, Int, and/or Alias methods.

func (*UserData) Alias ¶

func (d *UserData) Alias(alias string) *UserData

Alias sets the alias as the given string.

func (*UserData) Int ¶

func (d *UserData) Int(id int) *UserData

Int sets the ID as the given integer.

func (*UserData) String ¶

func (d *UserData) String(id string) *UserData

String sets the ID as the given string.

type UserResponse ¶

type UserResponse struct {
	User `json:",inline"`
	// contains filtered or unexported fields
}

type UsersClient ¶

type UsersClient struct {
	// contains filtered or unexported fields
}

UsersClient is a specialized client used to interact with the Users endpoints.

func (*UsersClient) Add ¶

func (c *UsersClient) Add(ctx context.Context, user User, getOrCreate bool) (*UserResponse, error)

Add adds a new user with the specified id and optional extra data.

func (*UsersClient) CreateReference ¶

func (c *UsersClient) CreateReference(id string) string

CreateReference returns a new reference string in the form SU:<id>.

func (*UsersClient) Delete ¶

func (c *UsersClient) Delete(ctx context.Context, id string) (*BaseResponse, error)

Delete deletes a user having the given id.

func (*UsersClient) Get ¶

func (c *UsersClient) Get(ctx context.Context, id string) (*UserResponse, error)

Get retrieves a user having the given id.

func (*UsersClient) Update ¶

func (c *UsersClient) Update(ctx context.Context, id string, data map[string]any) (*UserResponse, error)

Update updates the user's data.

Jump to

Keyboard shortcuts

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