summaryrefslogtreecommitdiff
path: root/internal/federation/federatingdb/util.go
blob: f1c565aeb619d1d2e508041f1b09717dc712b7b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package federatingdb

import (
	"context"
	"encoding/json"
	"fmt"
	"net/url"

	"codeberg.org/gruf/go-logger/v2/level"
	"github.com/superseriousbusiness/activity/streams"
	"github.com/superseriousbusiness/activity/streams/vocab"
	"github.com/superseriousbusiness/gotosocial/internal/ap"
	"github.com/superseriousbusiness/gotosocial/internal/config"
	"github.com/superseriousbusiness/gotosocial/internal/db"
	"github.com/superseriousbusiness/gotosocial/internal/gtscontext"
	"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
	"github.com/superseriousbusiness/gotosocial/internal/id"
	"github.com/superseriousbusiness/gotosocial/internal/log"
	"github.com/superseriousbusiness/gotosocial/internal/uris"
)

func typeNames(objects []ap.TypeOrIRI) []string {
	names := make([]string, len(objects))
	for i, object := range objects {
		if object.IsIRI() {
			names[i] = "IRI"
		} else if t := object.GetType(); t != nil {
			names[i] = t.GetTypeName()
		} else {
			names[i] = "nil"
		}
	}
	return names
}

// isSender returns whether an object with AttributedTo property comes from the given requesting account.
func isSender(with ap.WithAttributedTo, requester *gtsmodel.Account) bool {
	for _, uri := range ap.GetAttributedTo(with) {
		if uri.String() == requester.URI {
			return true
		}
	}
	return false
}

func sameActor(actor1 vocab.ActivityStreamsActorProperty, actor2 vocab.ActivityStreamsActorProperty) bool {
	if actor1 == nil || actor2 == nil {
		return false
	}

	for a1Iter := actor1.Begin(); a1Iter != actor1.End(); a1Iter = a1Iter.Next() {
		for a2Iter := actor2.Begin(); a2Iter != actor2.End(); a2Iter = a2Iter.Next() {
			if a1Iter.GetIRI() == nil {
				return false
			}

			if a2Iter.GetIRI() == nil {
				return false
			}

			if a1Iter.GetIRI().String() == a2Iter.GetIRI().String() {
				return true
			}
		}
	}

	return false
}

// NewID creates a new IRI id for the provided activity or object. The
// implementation does not need to set the 'id' property and simply
// needs to determine the value.
//
// The go-fed library will handle setting the 'id' property on the
// activity or object provided with the value returned.
func (f *federatingDB) NewID(ctx context.Context, t vocab.Type) (idURL *url.URL, err error) {
	if log.Level() >= level.DEBUG {
		i, err := marshalItem(t)
		if err != nil {
			return nil, err
		}
		l := log.WithContext(ctx).
			WithField("newID", i)
		l.Debug("entering NewID")
	}

	// Most of our types set an ID already
	// by this point, return this if found.
	idProp := t.GetJSONLDId()
	if idProp != nil && idProp.IsIRI() {
		return idProp.GetIRI(), nil
	}

	if t.GetTypeName() == ap.ActivityFollow {
		follow, _ := t.(vocab.ActivityStreamsFollow)

		// If an actor URI has been set, create a new ID
		// based on actor (i.e. followER not the followEE).
		if uri := ap.GetActorIRIs(follow); len(uri) == 1 {
			if actorAccount, err := f.state.DB.GetAccountByURI(ctx, uri[0].String()); err == nil {
				newID, err := id.NewRandomULID()
				if err != nil {
					return nil, err
				}
				return url.Parse(uris.GenerateURIForFollow(actorAccount.Username, newID))
			}
		}
	}

	// Default fallback behaviour:
	// {proto}://{host}/{randomID}
	newID, err := id.NewRandomULID()
	if err != nil {
		return nil, err
	}

	return url.Parse(fmt.Sprintf("%s://%s/%s", config.GetProtocol(), config.GetHost(), newID))
}

// ActorForOutbox fetches the actor's IRI for the given outbox IRI.
//
// The library makes this call only after acquiring a lock first.
func (f *federatingDB) ActorForOutbox(ctx context.Context, outboxIRI *url.URL) (actorIRI *url.URL, err error) {
	acct, err := f.getAccountForIRI(ctx, outboxIRI)
	if err != nil {
		return nil, err
	}
	return url.Parse(acct.URI)
}

// ActorForInbox fetches the actor's IRI for the given outbox IRI.
//
// The library makes this call only after acquiring a lock first.
func (f *federatingDB) ActorForInbox(ctx context.Context, inboxIRI *url.URL) (actorIRI *url.URL, err error) {
	acct, err := f.getAccountForIRI(ctx, inboxIRI)
	if err != nil {
		return nil, err
	}
	return url.Parse(acct.URI)
}

// getAccountForIRI returns the account that corresponds to or owns the given IRI.
func (f *federatingDB) getAccountForIRI(ctx context.Context, iri *url.URL) (*gtsmodel.Account, error) {
	var (
		acct *gtsmodel.Account
		err  error
	)

	switch {
	case uris.IsUserPath(iri):
		if acct, err = f.state.DB.GetAccountByURI(ctx, iri.String()); err != nil {
			if err == db.ErrNoEntries {
				return nil, fmt.Errorf("no actor found that corresponds to uri %s", iri.String())
			}
			return nil, fmt.Errorf("db error searching for actor with uri %s", iri.String())
		}
		return acct, nil
	case uris.IsInboxPath(iri):
		if acct, err = f.state.DB.GetAccountByInboxURI(ctx, iri.String()); err != nil {
			if err == db.ErrNoEntries {
				return nil, fmt.Errorf("no actor found that corresponds to inbox %s", iri.String())
			}
			return nil, fmt.Errorf("db error searching for actor with inbox %s", iri.String())
		}
		return acct, nil
	case uris.IsOutboxPath(iri):
		if acct, err = f.state.DB.GetAccountByOutboxURI(ctx, iri.String()); err != nil {
			if err == db.ErrNoEntries {
				return nil, fmt.Errorf("no actor found that corresponds to outbox %s", iri.String())
			}
			return nil, fmt.Errorf("db error searching for actor with outbox %s", iri.String())
		}
		return acct, nil
	case uris.IsFollowersPath(iri):
		if acct, err = f.state.DB.GetAccountByFollowersURI(ctx, iri.String()); err != nil {
			if err == db.ErrNoEntries {
				return nil, fmt.Errorf("no actor found that corresponds to followers_uri %s", iri.String())
			}
			return nil, fmt.Errorf("db error searching for actor with followers_uri %s", iri.String())
		}
		return acct, nil
	case uris.IsFollowingPath(iri):
		if acct, err = f.state.DB.GetAccountByFollowingURI(ctx, iri.String()); err != nil {
			if err == db.ErrNoEntries {
				return nil, fmt.Errorf("no actor found that corresponds to following_uri %s", iri.String())
			}
			return nil, fmt.Errorf("db error searching for actor with following_uri %s", iri.String())
		}
		return acct, nil
	default:
		return nil, fmt.Errorf("getActorForIRI: iri %s not recognised", iri)
	}
}

// collectFollows takes a slice of iris and converts them into ActivityStreamsCollection of IRIs.
func (f *federatingDB) collectIRIs(ctx context.Context, iris []*url.URL) (vocab.ActivityStreamsCollection, error) {
	collection := streams.NewActivityStreamsCollection()
	items := streams.NewActivityStreamsItemsProperty()
	for _, i := range iris {
		items.AppendIRI(i)
	}
	collection.SetActivityStreamsItems(items)
	return collection, nil
}

// extractFromCtx extracts some useful values from a context passed into the federatingDB:
//
//   - The account that owns the inbox or URI being interacted with.
//   - The account that POSTed a request to the inbox.
//   - Whether this is an internal request (one originating not from
//     the API but from inside the instance).
//
// If the request is internal, the caller can assume that the activity has
// already been processed elsewhere, and should return with no further action.
func extractFromCtx(ctx context.Context) (receivingAccount *gtsmodel.Account, requestingAccount *gtsmodel.Account, internal bool) {
	receivingAccount = gtscontext.ReceivingAccount(ctx)
	requestingAccount = gtscontext.RequestingAccount(ctx)

	// If the receiving account wasn't set on the context, that
	// means this request didn't pass through the API, but
	// came from inside GtS as the result of a local activity.
	internal = receivingAccount == nil

	return
}

func marshalItem(item vocab.Type) (string, error) {
	m, err := ap.Serialize(item)
	if err != nil {
		return "", err
	}

	b, err := json.Marshal(m)
	if err != nil {
		return "", err
	}

	return string(b), nil
}