summaryrefslogtreecommitdiff
path: root/internal/federation/federatingdb/create.go
blob: b07f4f04f011f208c819936ab98373de05f721a9 (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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/*
   GoToSocial
   Copyright (C) 2021-2022 GoToSocial Authors admin@gotosocial.org

   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"
	"errors"
	"fmt"
	"strings"

	"github.com/sirupsen/logrus"
	"github.com/superseriousbusiness/activity/streams/vocab"
	"github.com/superseriousbusiness/gotosocial/internal/ap"
	"github.com/superseriousbusiness/gotosocial/internal/db"
	"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
	"github.com/superseriousbusiness/gotosocial/internal/id"
	"github.com/superseriousbusiness/gotosocial/internal/messages"
)

// Create adds a new entry to the database which must be able to be
// keyed by its id.
//
// Note that Activity values received from federated peers may also be
// created in the database this way if the Federating Protocol is
// enabled. The client may freely decide to store only the id instead of
// the entire value.
//
// The library makes this call only after acquiring a lock first.
//
// Under certain conditions and network activities, Create may be called
// multiple times for the same ActivityStreams object.
func (f *federatingDB) Create(ctx context.Context, asType vocab.Type) error {
	l := logrus.WithFields(
		logrus.Fields{
			"func": "Create",
		},
	)

	if logrus.GetLevel() >= logrus.DebugLevel {
		i, err := marshalItem(asType)
		if err != nil {
			return err
		}
		l = l.WithField("create", i)
		l.Debug("entering Create")
	}

	receivingAccount, requestingAccount, fromFederatorChan := extractFromCtx(ctx)
	if receivingAccount == nil || fromFederatorChan == nil {
		// If the receiving account or federator channel 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 another activity on this instance. That being so,
		// we can safely just ignore this activity, since we know we've already processed it elsewhere.
		return nil
	}

	switch asType.GetTypeName() {
	case ap.ActivityBlock:
		// BLOCK SOMETHING
		return f.activityBlock(ctx, asType, receivingAccount, requestingAccount, fromFederatorChan)
	case ap.ActivityCreate:
		// CREATE SOMETHING
		return f.activityCreate(ctx, asType, receivingAccount, requestingAccount, fromFederatorChan)
	case ap.ActivityFollow:
		// FOLLOW SOMETHING
		return f.activityFollow(ctx, asType, receivingAccount, requestingAccount, fromFederatorChan)
	case ap.ActivityLike:
		// LIKE SOMETHING
		return f.activityLike(ctx, asType, receivingAccount, requestingAccount, fromFederatorChan)
	}
	return nil
}

/*
	BLOCK HANDLERS
*/

func (f *federatingDB) activityBlock(ctx context.Context, asType vocab.Type, receiving *gtsmodel.Account, requestingAccount *gtsmodel.Account, fromFederatorChan chan messages.FromFederator) error {
	blockable, ok := asType.(vocab.ActivityStreamsBlock)
	if !ok {
		return errors.New("activityBlock: could not convert type to block")
	}

	block, err := f.typeConverter.ASBlockToBlock(ctx, blockable)
	if err != nil {
		return fmt.Errorf("activityBlock: could not convert Block to gts model block")
	}

	newID, err := id.NewULID()
	if err != nil {
		return err
	}
	block.ID = newID

	if err := f.db.Put(ctx, block); err != nil {
		return fmt.Errorf("activityBlock: database error inserting block: %s", err)
	}

	fromFederatorChan <- messages.FromFederator{
		APObjectType:     ap.ActivityBlock,
		APActivityType:   ap.ActivityCreate,
		GTSModel:         block,
		ReceivingAccount: receiving,
	}
	return nil
}

/*
	CREATE HANDLERS
*/

func (f *federatingDB) activityCreate(ctx context.Context, asType vocab.Type, receivingAccount *gtsmodel.Account, requestingAccount *gtsmodel.Account, fromFederatorChan chan messages.FromFederator) error {
	create, ok := asType.(vocab.ActivityStreamsCreate)
	if !ok {
		return errors.New("activityCreate: could not convert type to create")
	}

	// create should have an object
	object := create.GetActivityStreamsObject()
	if object == nil {
		return errors.New("Create had no Object")
	}

	errs := []string{}
	// iterate through the object(s) to see what we're meant to be creating
	for objectIter := object.Begin(); objectIter != object.End(); objectIter = objectIter.Next() {
		asObjectType := objectIter.GetType()
		if asObjectType == nil {
			// currently we can't do anything with just a Create of something that's not an Object with a type
			// TODO: process a Create with an Object that's just a URI or something
			errs = append(errs, "object of Create was not a Type")
			continue
		}

		// we have a type -- what is it?
		asObjectTypeName := asObjectType.GetTypeName()
		switch asObjectTypeName {
		case ap.ObjectNote:
			// CREATE A NOTE
			if err := f.createNote(ctx, objectIter.GetActivityStreamsNote(), receivingAccount, requestingAccount, fromFederatorChan); err != nil {
				errs = append(errs, err.Error())
			}
		default:
			errs = append(errs, fmt.Sprintf("received an object on a Create that we couldn't handle: %s", asObjectType.GetTypeName()))
		}
	}

	if len(errs) != 0 {
		return fmt.Errorf("activityCreate: one or more errors while processing activity: %s", strings.Join(errs, "; "))
	}

	return nil
}

// createNote handles a Create activity with a Note type.
func (f *federatingDB) createNote(ctx context.Context, note vocab.ActivityStreamsNote, receivingAccount *gtsmodel.Account, requestingAccount *gtsmodel.Account, fromFederatorChan chan messages.FromFederator) error {
	l := logrus.WithFields(logrus.Fields{
		"func":              "createNote",
		"receivingAccount":  receivingAccount.URI,
		"requestingAccount": requestingAccount.URI,
	})

	// Check if we have a forward.
	// In other words, was the note posted to our inbox by at least one actor who actually created the note, or are they just forwarding it?
	forward := true

	// note should have an attributedTo
	noteAttributedTo := note.GetActivityStreamsAttributedTo()
	if noteAttributedTo == nil {
		return errors.New("createNote: note had no attributedTo")
	}

	// compare the attributedTo(s) with the actor who posted this to our inbox
	for attributedToIter := noteAttributedTo.Begin(); attributedToIter != noteAttributedTo.End(); attributedToIter = attributedToIter.Next() {
		if !attributedToIter.IsIRI() {
			continue
		}
		iri := attributedToIter.GetIRI()
		if requestingAccount.URI == iri.String() {
			// at least one creator of the note, and the actor who posted the note to our inbox, are the same, so it's not a forward
			forward = false
		}
	}

	// If we do have a forward, we should ignore the content for now and just dereference based on the URL/ID of the note instead, to get the note straight from the horse's mouth
	if forward {
		l.Trace("note is a forward")
		id := note.GetJSONLDId()
		if !id.IsIRI() {
			// if the note id isn't an IRI, there's nothing we can do here
			return nil
		}
		// pass the note iri into the processor and have it do the dereferencing instead of doing it here
		fromFederatorChan <- messages.FromFederator{
			APObjectType:     ap.ObjectNote,
			APActivityType:   ap.ActivityCreate,
			APIri:            id.GetIRI(),
			GTSModel:         nil,
			ReceivingAccount: receivingAccount,
		}
		return nil
	}

	// if we reach this point, we know it's not a forwarded status, so proceed with processing it as normal

	status, err := f.typeConverter.ASStatusToStatus(ctx, note)
	if err != nil {
		return fmt.Errorf("createNote: error converting note to status: %s", err)
	}

	// id the status based on the time it was created
	statusID, err := id.NewULIDFromTime(status.CreatedAt)
	if err != nil {
		return err
	}
	status.ID = statusID

	if err := f.db.PutStatus(ctx, status); err != nil {
		if err == db.ErrAlreadyExists {
			// the status already exists in the database, which means we've already handled everything else,
			// so we can just return nil here and be done with it.
			return nil
		}
		// an actual error has happened
		return fmt.Errorf("createNote: database error inserting status: %s", err)
	}

	fromFederatorChan <- messages.FromFederator{
		APObjectType:     ap.ObjectNote,
		APActivityType:   ap.ActivityCreate,
		GTSModel:         status,
		ReceivingAccount: receivingAccount,
	}

	return nil
}

/*
	FOLLOW HANDLERS
*/

func (f *federatingDB) activityFollow(ctx context.Context, asType vocab.Type, receivingAccount *gtsmodel.Account, requestingAccount *gtsmodel.Account, fromFederatorChan chan messages.FromFederator) error {
	follow, ok := asType.(vocab.ActivityStreamsFollow)
	if !ok {
		return errors.New("activityFollow: could not convert type to follow")
	}

	followRequest, err := f.typeConverter.ASFollowToFollowRequest(ctx, follow)
	if err != nil {
		return fmt.Errorf("activityFollow: could not convert Follow to follow request: %s", err)
	}

	newID, err := id.NewULID()
	if err != nil {
		return err
	}
	followRequest.ID = newID

	if err := f.db.Put(ctx, followRequest); err != nil {
		return fmt.Errorf("activityFollow: database error inserting follow request: %s", err)
	}

	fromFederatorChan <- messages.FromFederator{
		APObjectType:     ap.ActivityFollow,
		APActivityType:   ap.ActivityCreate,
		GTSModel:         followRequest,
		ReceivingAccount: receivingAccount,
	}

	return nil
}

/*
	LIKE HANDLERS
*/

func (f *federatingDB) activityLike(ctx context.Context, asType vocab.Type, receivingAccount *gtsmodel.Account, requestingAccount *gtsmodel.Account, fromFederatorChan chan messages.FromFederator) error {
	like, ok := asType.(vocab.ActivityStreamsLike)
	if !ok {
		return errors.New("activityLike: could not convert type to like")
	}

	fave, err := f.typeConverter.ASLikeToFave(ctx, like)
	if err != nil {
		return fmt.Errorf("activityLike: could not convert Like to fave: %s", err)
	}

	newID, err := id.NewULID()
	if err != nil {
		return err
	}
	fave.ID = newID

	if err := f.db.Put(ctx, fave); err != nil {
		return fmt.Errorf("activityLike: database error inserting fave: %s", err)
	}

	fromFederatorChan <- messages.FromFederator{
		APObjectType:     ap.ActivityLike,
		APActivityType:   ap.ActivityCreate,
		GTSModel:         fave,
		ReceivingAccount: receivingAccount,
	}

	return nil
}