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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
package logic

import (
	"encoding/json"
	"fmt"
	"github.com/microcosm-cc/bluemonday"
	"net/url"
	"regexp"
	"rss_parrot/dal"
	"rss_parrot/dto"
	"rss_parrot/shared"
	"rss_parrot/texts"
	"time"
)

type IInbox interface {
	HandleFollow(receivingUser string, senderInfo *dto.UserInfo, bodyBytes []byte) (string, error)
	HandleUndo(receivingUser string, senderInfo *dto.UserInfo, bodyBytes []byte) (string, error)
	HandleCreateNote(actBase dto.ActivityInBase, senderInfo *dto.UserInfo, bodyBytes []byte) (string, error)
}

const (
	firstPurgeDelayMin     = 1
	purgeActivitiesLoopMin = 60
	activitiesKeptHr       = 48
)

type inbox struct {
	cfg             *shared.Config
	logger          shared.ILogger
	idb             shared.IdBuilder
	repo            dal.IRepo
	txt             texts.ITexts
	metrics         IMetrics
	udir            IUserDirectory
	keyStore        IKeyStore
	sender          IActivitySender
	messenger       IMessenger
	fdfol           IFeedFollower
	reUserUrlParser *regexp.Regexp
	reHttps         *regexp.Regexp
}

func NewInbox(
	cfg *shared.Config,
	logger shared.ILogger,
	repo dal.IRepo,
	txt texts.ITexts,
	metrics IMetrics,
	udir IUserDirectory,
	keyStore IKeyStore,
	sender IActivitySender,
	messenger IMessenger,
	fdfol IFeedFollower,
) IInbox {

	reUserUrlParser := regexp.MustCompile("https://" + cfg.Host + "/u/([^/]+)/?")
	reHttps := regexp.MustCompile("https?://[^ ]+")
	res := inbox{cfg, logger, shared.IdBuilder{Host: cfg.Host}, repo, txt, metrics, udir,
		keyStore, sender, messenger, fdfol,
		reUserUrlParser, reHttps}

	go res.purgeOldAvititiesLoop()

	// If we don't update at startup, metric will be 0 until first time someone follows a feed
	res.updateFollowerMetric()

	return &res
}

func (ib *inbox) purgeOldAvititiesLoop() {
	time.Sleep(time.Minute * firstPurgeDelayMin)
	for {
		before := time.Now().Add(-activitiesKeptHr * time.Hour)
		ib.logger.Infof("Purging handled activities from before %s", before.Format(time.RFC3339))
		err := ib.repo.DeleteHandledActivities(before)
		if err != nil {
			ib.logger.Errorf("Failed to purge old handled activities: %v", err)
		}
		time.Sleep(time.Minute * purgeActivitiesLoopMin)
	}
}

// Mastodon servers send Follow and Undo activities to user inbox
// GTO sends them to instance inbox, and specifies recipient in 'to' field
// This function retrieves user from 'to' field; verifies that it's the same as inbox user, if present
func (ib *inbox) getSingleRecipient(
	receivingUser string,
	actTo *[]string) (user, reqProblem string) {
	user = receivingUser
	reqProblem = ""
	if len(*actTo) > 1 {
		reqProblem = fmt.Sprintf("Expected at most 1 recipient, got %d", len(*actTo))
		return
	}
	if len(*actTo) == 0 {
		return
	}
	to := (*actTo)[0]
	groups := ib.reUserUrlParser.FindStringSubmatch(to)
	if groups == nil {
		reqProblem = fmt.Sprintf("Cannot parse recipient as a URL: %s", to)
		return
	}
	toUser := groups[1]
	if receivingUser != "" && toUser != receivingUser {
		reqProblem = fmt.Sprintf("Recipient is %s but request was sent to Inbox of %s", toUser, receivingUser)
		return
	}
	if receivingUser == "" {
		user = toUser
	}
	return
}

func (ib *inbox) HandleFollow(
	receivingUser string,
	senderInfo *dto.UserInfo,
	bodyBytes []byte) (reqProblem string, err error) {

	err = nil
	reqProblem = ""
	ib.logger.Infof("Handling Follow activity to %s", receivingUser)

	// Unmarshal as Follow activity
	var actFollow dto.ActivityIn[string]
	if jsonErr := json.Unmarshal(bodyBytes, &actFollow); jsonErr != nil {
		ib.logger.Info("Invalid JSON in Follow activity body")
		reqProblem = fmt.Sprintf("Invalid JSON: %d", jsonErr)
		return
	}

	receivingUser, reqProblem = ib.getSingleRecipient(receivingUser, &actFollow.To)
	if reqProblem != "" {
		return
	}

	var account *dal.Account
	account, err = ib.repo.GetAccount(receivingUser)
	if err != nil {
		return "", err
	}
	if account == nil {
		reqProblem = fmt.Sprintf("User does not exist: %s", receivingUser)
		return
	}

	// This activity already handled?
	var alreadyHandled bool
	alreadyHandled, err = ib.repo.MarkActivityHandled(actFollow.Id, time.Now())
	if err != nil {
		return
	}
	if alreadyHandled {
		ib.logger.Infof("Activity has already been handled: %s", actFollow.Id)
		return
	}

	// Is object the ID if this account?
	myUserUrl := ib.idb.UserUrl(receivingUser)
	if myUserUrl != actFollow.Object {
		msg := fmt.Sprintf("Follow activity sent to inbox of %s, but object is %s", receivingUser, actFollow.Object)
		ib.logger.Warn(msg)
		reqProblem = msg
		return
	}

	// Store new follower
	var actorHostName string
	var urlError error
	actorHostName, urlError = shared.GetHostName(actFollow.Actor)
	if urlError != nil {
		ib.logger.Warn(urlError.Error())
		reqProblem = urlError.Error()
		return
	}

	flwr := dal.FollowerInfo{
		RequestId:     actFollow.Id,
		ApproveStatus: 0,
		UserUrl:       actFollow.Actor,
		Handle:        senderInfo.PreferredUserName,
		Host:          actorHostName,
		UserInbox:     senderInfo.Inbox,
		SharedInbox:   senderInfo.Endpoints.SharedInbox,
	}
	err = ib.repo.AddFollower(receivingUser, &flwr)
	if err != nil {
		return "", err
	}
	ib.updateFollowerMetric()

	autoAccept := true
	if account.Handle == ib.cfg.Birb.User && ib.cfg.Birb.ManuallyApprovesFollows {
		autoAccept = false
	}
	if autoAccept {
		go func() {
			time.Sleep(1000)
			err := ib.udir.AcceptFollower(flwr.RequestId, flwr.UserUrl, flwr.UserInbox, receivingUser)
			if err != nil {
				ib.logger.Errorf("Error accepting follower: %v", err)
			}
		}()
	}

	return
}

func (ib *inbox) updateFollowerMetric() {
	if count, err := ib.repo.GetFeedFollowerCount(); err != nil {
		ib.logger.Errorf("Error getting feed follower count: %v", err)
		return
	} else {
		ib.metrics.TotalFollowers(count)
	}
}

func (ib *inbox) HandleUndo(
	receivingUser string,
	senderInfo *dto.UserInfo,
	bodyBytes []byte) (reqProblem string, err error) {

	reqProblem = ""
	err = nil
	ib.logger.Infof("Handling Undo activity to %s", receivingUser)

	// Unmarshal as Undo activity
	var actUndo dto.ActivityIn[dto.ActivityInBase]
	if jsonErr := json.Unmarshal(bodyBytes, &actUndo); jsonErr != nil {
		ib.logger.Info("Invalid JSON in Undo activity body")
		reqProblem = fmt.Sprintf("Invalid JSON: %d", jsonErr)
		return
	}

	receivingUser, reqProblem = ib.getSingleRecipient(receivingUser, &actUndo.To)
	if reqProblem != "" {
		return
	}

	// This activity already handled?
	var alreadyHandled bool
	alreadyHandled, err = ib.repo.MarkActivityHandled(actUndo.Id, time.Now())
	if err != nil {
		return
	}
	if alreadyHandled {
		ib.logger.Infof("Activity has already been handled: %s", actUndo.Id)
		return
	}

	// Undoing what?
	if actUndo.Object.Type == "Follow" {
		reqProblem, err = ib.handleUnfollow(receivingUser, bodyBytes)
	}

	return
}

func (ib *inbox) handleUnfollow(receivingUser string, bodyBytes []byte) (reqProblem string, err error) {

	ib.logger.Infof("Handling Undo Follow activity to '%s'", receivingUser)

	reqProblem = ""
	err = nil
	var userExists bool
	userExists, err = ib.repo.DoesAccountExist(receivingUser)
	if err != nil {
		return
	}
	if !userExists {
		reqProblem = fmt.Sprintf("User does not exist: %s", receivingUser)
		return
	}

	// Now parse the embeded object
	var actUndoFollow dto.ActivityIn[dto.ActivityIn[string]]
	if jsonErr := json.Unmarshal(bodyBytes, &actUndoFollow); jsonErr != nil {
		ib.logger.Info("Invalid JSON in Undo Follow activity body")
		reqProblem = fmt.Sprintf("Invalid JSON: %d", jsonErr)
		return
	}

	// Who is being unfollowed, according to the object?
	groups := ib.reUserUrlParser.FindStringSubmatch(actUndoFollow.Object.Object)
	if groups == nil {
		reqProblem = fmt.Sprintf("Cannot parse Undo Follow object as a URL: %s", actUndoFollow.Object.Object)
		return
	}
	objectUser := groups[1]
	if objectUser != receivingUser {
		reqProblem = fmt.Sprintf("Undo Follow sent to '%s' but user in object URL us %s", receivingUser, objectUser)
		return
	}

	err = ib.repo.RemoveFollower(receivingUser, actUndoFollow.Actor)
	if err != nil {
		ib.logger.Errorf("Error removing follower '%s' of '%s': %v", actUndoFollow.Actor, receivingUser, err)
		return
	}

	ib.updateFollowerMetric()

	return
}

func (ib *inbox) HandleCreateNote(
	actBase dto.ActivityInBase,
	senderInfo *dto.UserInfo,
	bodyBytes []byte) (reqProblem string, err error) {

	ib.logger.Infof("Handling Create Note activity")

	reqProblem = ""
	err = nil

	// Parse activity with Note object
	var act dto.ActivityIn[dto.Note]
	if jsonErr := json.Unmarshal(bodyBytes, &act); jsonErr != nil {
		ib.logger.Info("Invalid JSON in Create Note activity body")
		reqProblem = fmt.Sprintf("Invalid JSON: %v", jsonErr)
		return
	}

	// Is this a reply?
	if act.Object.InReplyTo != nil && *act.Object.InReplyTo != "" {
		ib.logger.Info("Note is a reply to something; ignoring it.")
		return
	}

	// This activity already handled?
	var alreadyHandled bool
	alreadyHandled, err = ib.repo.MarkActivityHandled(actBase.Id, time.Now())
	if err != nil {
		return
	}
	if alreadyHandled {
		ib.logger.Infof("Activity has already been handled: %s", actBase.Id)
		return
	}

	// Is it addressed to both me, and "public"?
	birbUsrUrl := ib.idb.UserUrl(ib.cfg.Birb.User)
	toBirb := false
	toPublicOrFollowers := false
	checkAddressee := func(str string) {
		if str == shared.ActivityPublic || str == senderInfo.Followers {
			toPublicOrFollowers = true
		} else if str == birbUsrUrl {
			toBirb = true
		}
	}
	for _, str := range actBase.To {
		checkAddressee(str)
	}
	for _, str := range actBase.Cc {
		checkAddressee(str)
	}

	// If not addressed to me: simply ignore
	if !toBirb {
		ib.logger.Info("Note not addressed to the birb; ignoring it.")
		return
	}

	// So, we will reply *something* with a mention.
	// Let's get the sender's moniker! -> @twilliability@genart.social
	var senderHostName string
	senderHostName, err = shared.GetHostName(senderInfo.Id)
	if err != nil {
		reqProblem = fmt.Sprintf("Failed to extract host from sender ID %s: %d", senderInfo.Id, err)
		ib.logger.Info(reqProblem)
		return
	}
	moniker := shared.MakeFullMoniker(senderHostName, senderInfo.PreferredUserName)

	// What goes into to and cc
	to, cc := ib.getRecipients(act.Actor, senderInfo.Followers, !toPublicOrFollowers)

	// Allowlist: when restriction is on, requests are closed by default and
	// only allowlisted requesters may add new feeds.
	if !isRequesterAllowed(ib.cfg.RestrictRequests, ib.cfg.AllowedRequestersFile, moniker) {
		ib.logger.Infof("Requester %s is not on the allowlist; refusing feed request", moniker)
		msg := ib.txt.WithVals("reply_not_allowed.html", map[string]string{
			"moniker": moniker,
			"userUrl": senderInfo.Id,
		})
		ib.messenger.SendMessageAsync(ib.cfg.Birb.User, senderInfo.Inbox, msg,
			[]*MsgMention{{moniker, act.Actor}}, to, cc, act.Object.Id)
		return
	}

	// Look for exactly 1 valid URL in message
	blogUrl := ib.getUrl(act.Object.Content)
	if blogUrl == "" {
		ib.logger.Info("No single URL found in message")
		msg := ib.txt.WithVals("reply_no_single_url.html", map[string]string{
			"moniker": moniker,
			"userUrl": senderInfo.Id,
		})
		ib.messenger.SendMessageAsync(ib.cfg.Birb.User, senderInfo.Inbox, msg,
			[]*MsgMention{{moniker, act.Actor}}, to, cc, act.Object.Id)
		return
	}

	go ib.handleSiteRequest(senderInfo, act, to, cc, moniker, blogUrl)

	return
}

func (ib *inbox) getRecipients(actor, followers string, isDM bool) (to, cc []string) {
	if isDM {
		to = []string{actor}
		cc = []string{}
	} else {
		to = []string{shared.ActivityPublic}
		cc = []string{actor, followers}
	}
	return
}

func (ib *inbox) handleSiteRequest(senderInfo *dto.UserInfo, act dto.ActivityIn[dto.Note],
	to, cc []string, moniker, blogUrl string) {

	acct, status, err := ib.fdfol.GetAccountForFeed(blogUrl)

	if status < 0 {
		ib.logger.Infof("Could not create/retrieve account for site: %s: %v", blogUrl, err)
		template := "reply_site_not_found.html"
		if status == FsMastodon {
			template = "reply_feed_mastodon.html"
		} else if status == FsBanned {
			template = "reply_feed_banned.html"
		} else if status == FsOptOut {
			template = "reply_feed_optout.html"
		}
		msg := ib.txt.WithVals(template, map[string]string{
			"moniker": moniker,
			"userUrl": senderInfo.Id,
		})
		ib.messenger.SendMessageAsync(ib.cfg.Birb.User, senderInfo.Inbox, msg,
			[]*MsgMention{{moniker, act.Actor}}, to, cc, act.Object.Id)
		return
	}

	ib.logger.Infof("Account for site created/retrieved: %s -> %s", blogUrl, acct.Handle)
	accountMoniker := shared.MakeFullMoniker(ib.cfg.Host, acct.Handle)
	accountUrl := ib.idb.UserUrl(acct.Handle)
	msg := ib.txt.WithVals("reply_got_feed.html", map[string]string{
		"userHandle":     senderInfo.PreferredUserName,
		"userUrl":        senderInfo.Id,
		"accountName":    acct.FeedName,
		"accountMoniker": "@" + acct.Handle,
		"host":           ib.cfg.Host,
		"accountUrl":     accountUrl,
	})
	ib.messenger.SendMessageAsync(ib.cfg.Birb.User, senderInfo.Inbox, msg,
		[]*MsgMention{{moniker, act.Actor}, {accountMoniker, accountUrl}},
		to, cc, act.Object.Id)
}

func (ib *inbox) getUrl(content string) string {

	pol := bluemonday.StrictPolicy()
	plain := pol.Sanitize(content)
	matches := ib.reHttps.FindAllString(plain, -1)

	// Looking for exactly one valid Url
	res := ""
	for _, str := range matches {
		_, err := url.Parse(str)
		if err != nil {
			continue
		}
		if res != "" {
			return ""
		}
		res = str
	}
	return res
}