gtsocial-umbx

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

account.go (28719B)


      1 // GoToSocial
      2 // Copyright (C) GoToSocial Authors admin@gotosocial.org
      3 // SPDX-License-Identifier: AGPL-3.0-or-later
      4 //
      5 // This program is free software: you can redistribute it and/or modify
      6 // it under the terms of the GNU Affero General Public License as published by
      7 // the Free Software Foundation, either version 3 of the License, or
      8 // (at your option) any later version.
      9 //
     10 // This program is distributed in the hope that it will be useful,
     11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
     12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     13 // GNU Affero General Public License for more details.
     14 //
     15 // You should have received a copy of the GNU Affero General Public License
     16 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
     17 
     18 package dereferencing
     19 
     20 import (
     21 	"context"
     22 	"encoding/json"
     23 	"errors"
     24 	"io"
     25 	"net/url"
     26 	"time"
     27 
     28 	"github.com/superseriousbusiness/activity/streams"
     29 	"github.com/superseriousbusiness/activity/streams/vocab"
     30 	"github.com/superseriousbusiness/gotosocial/internal/ap"
     31 	"github.com/superseriousbusiness/gotosocial/internal/config"
     32 	"github.com/superseriousbusiness/gotosocial/internal/db"
     33 	"github.com/superseriousbusiness/gotosocial/internal/gtscontext"
     34 	"github.com/superseriousbusiness/gotosocial/internal/gtserror"
     35 	"github.com/superseriousbusiness/gotosocial/internal/gtsmodel"
     36 	"github.com/superseriousbusiness/gotosocial/internal/id"
     37 	"github.com/superseriousbusiness/gotosocial/internal/log"
     38 	"github.com/superseriousbusiness/gotosocial/internal/media"
     39 	"github.com/superseriousbusiness/gotosocial/internal/transport"
     40 )
     41 
     42 // accountUpToDate returns whether the given account model is both updateable (i.e.
     43 // non-instance remote account) and whether it needs an update based on `fetched_at`.
     44 func accountUpToDate(account *gtsmodel.Account) bool {
     45 	if account.IsLocal() {
     46 		// Can't update local accounts.
     47 		return true
     48 	}
     49 
     50 	if !account.CreatedAt.IsZero() && account.IsInstance() {
     51 		// Existing instance account. No need for update.
     52 		return true
     53 	}
     54 
     55 	// If this account was updated recently (last interval), we return as-is.
     56 	if next := account.FetchedAt.Add(6 * time.Hour); time.Now().Before(next) {
     57 		return true
     58 	}
     59 
     60 	return false
     61 }
     62 
     63 // GetAccountByURI: implements Dereferencer{}.GetAccountByURI.
     64 func (d *deref) GetAccountByURI(ctx context.Context, requestUser string, uri *url.URL) (*gtsmodel.Account, ap.Accountable, error) {
     65 	// Fetch and dereference account if necessary.
     66 	account, apubAcc, err := d.getAccountByURI(ctx,
     67 		requestUser,
     68 		uri,
     69 	)
     70 	if err != nil {
     71 		return nil, nil, err
     72 	}
     73 
     74 	if apubAcc != nil {
     75 		// This account was updated, enqueue re-dereference featured posts.
     76 		d.state.Workers.Federator.MustEnqueueCtx(ctx, func(ctx context.Context) {
     77 			if err := d.dereferenceAccountFeatured(ctx, requestUser, account); err != nil {
     78 				log.Errorf(ctx, "error fetching account featured collection: %v", err)
     79 			}
     80 		})
     81 	}
     82 
     83 	return account, apubAcc, nil
     84 }
     85 
     86 // getAccountByURI is a package internal form of .GetAccountByURI() that doesn't bother dereferencing featured posts on update.
     87 func (d *deref) getAccountByURI(ctx context.Context, requestUser string, uri *url.URL) (*gtsmodel.Account, ap.Accountable, error) {
     88 	var (
     89 		account *gtsmodel.Account
     90 		uriStr  = uri.String()
     91 		err     error
     92 	)
     93 
     94 	// Search the database for existing account with URI.
     95 	account, err = d.state.DB.GetAccountByURI(
     96 		// request a barebones object, it may be in the
     97 		// db but with related models not yet dereferenced.
     98 		gtscontext.SetBarebones(ctx),
     99 		uriStr,
    100 	)
    101 	if err != nil && !errors.Is(err, db.ErrNoEntries) {
    102 		return nil, nil, gtserror.Newf("error checking database for account %s by uri: %w", uriStr, err)
    103 	}
    104 
    105 	if account == nil {
    106 		// Else, search the database for existing by URL.
    107 		account, err = d.state.DB.GetAccountByURL(
    108 			gtscontext.SetBarebones(ctx),
    109 			uriStr,
    110 		)
    111 		if err != nil && !errors.Is(err, db.ErrNoEntries) {
    112 			return nil, nil, gtserror.Newf("error checking database for account %s by url: %w", uriStr, err)
    113 		}
    114 	}
    115 
    116 	if account == nil {
    117 		// Ensure that this is isn't a search for a local account.
    118 		if uri.Host == config.GetHost() || uri.Host == config.GetAccountDomain() {
    119 			return nil, nil, NewErrNotRetrievable(err) // this will be db.ErrNoEntries
    120 		}
    121 
    122 		// Create and pass-through a new bare-bones model for dereferencing.
    123 		return d.enrichAccount(ctx, requestUser, uri, &gtsmodel.Account{
    124 			ID:     id.NewULID(),
    125 			Domain: uri.Host,
    126 			URI:    uriStr,
    127 		}, nil)
    128 	}
    129 
    130 	// Check whether needs update.
    131 	if accountUpToDate(account) {
    132 		// This is existing up-to-date account, ensure it is populated.
    133 		if err := d.state.DB.PopulateAccount(ctx, account); err != nil {
    134 			log.Errorf(ctx, "error populating existing account: %v", err)
    135 		}
    136 		return account, nil, nil
    137 	}
    138 
    139 	// Try to update existing account model.
    140 	latest, apubAcc, err := d.enrichAccount(ctx,
    141 		requestUser,
    142 		uri,
    143 		account,
    144 		nil,
    145 	)
    146 	if err != nil {
    147 		log.Errorf(ctx, "error enriching remote account: %v", err)
    148 
    149 		// Update fetch-at to slow re-attempts.
    150 		account.FetchedAt = time.Now()
    151 		_ = d.state.DB.UpdateAccount(ctx, account, "fetched_at")
    152 
    153 		// Fallback to existing.
    154 		return account, nil, nil
    155 	}
    156 
    157 	return latest, apubAcc, nil
    158 }
    159 
    160 // GetAccountByUsernameDomain: implements Dereferencer{}.GetAccountByUsernameDomain.
    161 func (d *deref) GetAccountByUsernameDomain(ctx context.Context, requestUser string, username string, domain string) (*gtsmodel.Account, ap.Accountable, error) {
    162 	if domain == config.GetHost() || domain == config.GetAccountDomain() {
    163 		// We do local lookups using an empty domain,
    164 		// else it will fail the db search below.
    165 		domain = ""
    166 	}
    167 
    168 	// Search the database for existing account with USERNAME@DOMAIN.
    169 	account, err := d.state.DB.GetAccountByUsernameDomain(
    170 		// request a barebones object, it may be in the
    171 		// db but with related models not yet dereferenced.
    172 		gtscontext.SetBarebones(ctx),
    173 		username, domain,
    174 	)
    175 	if err != nil && !errors.Is(err, db.ErrNoEntries) {
    176 		return nil, nil, gtserror.Newf("error checking database for account %s@%s: %w", username, domain, err)
    177 	}
    178 
    179 	if account == nil {
    180 		if domain == "" {
    181 			// failed local lookup, will be db.ErrNoEntries.
    182 			return nil, nil, NewErrNotRetrievable(err)
    183 		}
    184 
    185 		// Create and pass-through a new bare-bones model for dereferencing.
    186 		account, apubAcc, err := d.enrichAccount(ctx, requestUser, nil, &gtsmodel.Account{
    187 			ID:       id.NewULID(),
    188 			Username: username,
    189 			Domain:   domain,
    190 		}, nil)
    191 		if err != nil {
    192 			return nil, nil, err
    193 		}
    194 
    195 		// This account was updated, enqueue dereference featured posts.
    196 		d.state.Workers.Federator.MustEnqueueCtx(ctx, func(ctx context.Context) {
    197 			if err := d.dereferenceAccountFeatured(ctx, requestUser, account); err != nil {
    198 				log.Errorf(ctx, "error fetching account featured collection: %v", err)
    199 			}
    200 		})
    201 
    202 		return account, apubAcc, nil
    203 	}
    204 
    205 	// Try to update existing account model.
    206 	latest, apubAcc, err := d.RefreshAccount(ctx,
    207 		requestUser,
    208 		account,
    209 		nil,
    210 		false,
    211 	)
    212 	if err != nil {
    213 		// Fallback to existing.
    214 		return account, nil, nil //nolint
    215 	}
    216 
    217 	if apubAcc == nil {
    218 		// This is existing up-to-date account, ensure it is populated.
    219 		if err := d.state.DB.PopulateAccount(ctx, account); err != nil {
    220 			log.Errorf(ctx, "error populating existing account: %v", err)
    221 		}
    222 	}
    223 
    224 	return latest, apubAcc, nil
    225 }
    226 
    227 // RefreshAccount: implements Dereferencer{}.RefreshAccount.
    228 func (d *deref) RefreshAccount(ctx context.Context, requestUser string, account *gtsmodel.Account, apubAcc ap.Accountable, force bool) (*gtsmodel.Account, ap.Accountable, error) {
    229 	// Check whether needs update (and not forced).
    230 	if accountUpToDate(account) && !force {
    231 		return account, nil, nil
    232 	}
    233 
    234 	// Parse the URI from account.
    235 	uri, err := url.Parse(account.URI)
    236 	if err != nil {
    237 		return nil, nil, gtserror.Newf("invalid account uri %q: %w", account.URI, err)
    238 	}
    239 
    240 	// Try to update + deref existing account model.
    241 	latest, apubAcc, err := d.enrichAccount(ctx,
    242 		requestUser,
    243 		uri,
    244 		account,
    245 		apubAcc,
    246 	)
    247 	if err != nil {
    248 		log.Errorf(ctx, "error enriching remote account: %v", err)
    249 
    250 		// Update fetch-at to slow re-attempts.
    251 		account.FetchedAt = time.Now()
    252 		_ = d.state.DB.UpdateAccount(ctx, account, "fetched_at")
    253 
    254 		return nil, nil, err
    255 	}
    256 
    257 	// This account was updated, enqueue re-dereference featured posts.
    258 	d.state.Workers.Federator.MustEnqueueCtx(ctx, func(ctx context.Context) {
    259 		if err := d.dereferenceAccountFeatured(ctx, requestUser, account); err != nil {
    260 			log.Errorf(ctx, "error fetching account featured collection: %v", err)
    261 		}
    262 	})
    263 
    264 	return latest, apubAcc, nil
    265 }
    266 
    267 // RefreshAccountAsync: implements Dereferencer{}.RefreshAccountAsync.
    268 func (d *deref) RefreshAccountAsync(ctx context.Context, requestUser string, account *gtsmodel.Account, apubAcc ap.Accountable, force bool) {
    269 	// Check whether needs update (and not forced).
    270 	if accountUpToDate(account) && !force {
    271 		return
    272 	}
    273 
    274 	// Parse the URI from account.
    275 	uri, err := url.Parse(account.URI)
    276 	if err != nil {
    277 		log.Errorf(ctx, "invalid account uri %q: %v", account.URI, err)
    278 		return
    279 	}
    280 
    281 	// Enqueue a worker function to enrich this account async.
    282 	d.state.Workers.Federator.MustEnqueueCtx(ctx, func(ctx context.Context) {
    283 		latest, _, err := d.enrichAccount(ctx, requestUser, uri, account, apubAcc)
    284 		if err != nil {
    285 			log.Errorf(ctx, "error enriching remote account: %v", err)
    286 			return
    287 		}
    288 
    289 		// This account was updated, re-dereference account featured posts.
    290 		if err := d.dereferenceAccountFeatured(ctx, requestUser, latest); err != nil {
    291 			log.Errorf(ctx, "error fetching account featured collection: %v", err)
    292 		}
    293 	})
    294 }
    295 
    296 // enrichAccount will enrich the given account, whether a new barebones model, or existing model from the database. It handles necessary dereferencing, webfingering etc.
    297 func (d *deref) enrichAccount(ctx context.Context, requestUser string, uri *url.URL, account *gtsmodel.Account, apubAcc ap.Accountable) (*gtsmodel.Account, ap.Accountable, error) {
    298 	// Pre-fetch a transport for requesting username, used by later deref procedures.
    299 	tsport, err := d.transportController.NewTransportForUsername(ctx, requestUser)
    300 	if err != nil {
    301 		return nil, nil, gtserror.Newf("couldn't create transport: %w", err)
    302 	}
    303 
    304 	if account.Username != "" {
    305 		// A username was provided so we can attempt a webfinger, this ensures up-to-date accountdomain info.
    306 		accDomain, accURI, err := d.fingerRemoteAccount(ctx, tsport, account.Username, account.Domain)
    307 		if err != nil {
    308 			if account.URI == "" {
    309 				// this is a new account (to us) with username@domain but failed webfinger, nothing more we can do.
    310 				return nil, nil, &ErrNotRetrievable{gtserror.Newf("error webfingering account: %w", err)}
    311 			}
    312 
    313 			// Simply log this error and move on, we already have an account URI.
    314 			log.Errorf(ctx, "error webfingering[1] remote account %s@%s: %v", account.Username, account.Domain, err)
    315 		}
    316 
    317 		if err == nil {
    318 			if account.Domain != accDomain {
    319 				// Domain has changed, assume the activitypub
    320 				// account data provided may not be the latest.
    321 				apubAcc = nil
    322 
    323 				// After webfinger, we now have correct account domain from which we can do a final DB check.
    324 				alreadyAccount, err := d.state.DB.GetAccountByUsernameDomain(ctx, account.Username, accDomain)
    325 				if err != nil && !errors.Is(err, db.ErrNoEntries) {
    326 					return nil, nil, gtserror.Newf("db err looking for account again after webfinger: %w", err)
    327 				}
    328 
    329 				if alreadyAccount != nil {
    330 					// Enrich existing account.
    331 					account = alreadyAccount
    332 				}
    333 			}
    334 
    335 			// Update account with latest info.
    336 			account.URI = accURI.String()
    337 			account.Domain = accDomain
    338 			uri = accURI
    339 		}
    340 	}
    341 
    342 	if uri == nil {
    343 		// No URI provided / found, must parse from account.
    344 		uri, err = url.Parse(account.URI)
    345 		if err != nil {
    346 			return nil, nil, gtserror.Newf("invalid uri %q: %w", account.URI, err)
    347 		}
    348 	}
    349 
    350 	// Check whether this account URI is a blocked domain / subdomain.
    351 	if blocked, err := d.state.DB.IsDomainBlocked(ctx, uri.Host); err != nil {
    352 		return nil, nil, gtserror.Newf("error checking blocked domain: %w", err)
    353 	} else if blocked {
    354 		return nil, nil, gtserror.Newf("%s is blocked", uri.Host)
    355 	}
    356 
    357 	// Mark deref+update handshake start.
    358 	d.startHandshake(requestUser, uri)
    359 	defer d.stopHandshake(requestUser, uri)
    360 
    361 	// By default we assume that apubAcc has been passed,
    362 	// indicating that the given account is already latest.
    363 	latestAcc := account
    364 
    365 	if apubAcc == nil {
    366 		// Dereference latest version of the account.
    367 		b, err := tsport.Dereference(ctx, uri)
    368 		if err != nil {
    369 			return nil, nil, &ErrNotRetrievable{gtserror.Newf("error deferencing %s: %w", uri, err)}
    370 		}
    371 
    372 		// Attempt to resolve ActivityPub account from data.
    373 		apubAcc, err = ap.ResolveAccountable(ctx, b)
    374 		if err != nil {
    375 			return nil, nil, gtserror.Newf("error resolving accountable from data for account %s: %w", uri, err)
    376 		}
    377 
    378 		// Convert the dereferenced AP account object to our GTS model.
    379 		latestAcc, err = d.typeConverter.ASRepresentationToAccount(ctx,
    380 			apubAcc,
    381 			account.Domain,
    382 		)
    383 		if err != nil {
    384 			return nil, nil, gtserror.Newf("error converting accountable to gts model for account %s: %w", uri, err)
    385 		}
    386 	}
    387 
    388 	if account.Username == "" {
    389 		// No username was provided, so no webfinger was attempted earlier.
    390 		//
    391 		// Now we have a username we can attempt again, to ensure up-to-date
    392 		// accountDomain info. For this final attempt we should use the domain
    393 		// of the ID of the dereffed account, rather than the URI we were given.
    394 		//
    395 		// This avoids cases where we were given a URI like
    396 		// https://example.org/@someone@somewhere.else and we've been redirected
    397 		// from example.org to somewhere.else: we want to take somewhere.else
    398 		// as the accountDomain then, not the example.org we were redirected from.
    399 
    400 		// Assume the host from the returned ActivityPub representation.
    401 		idProp := apubAcc.GetJSONLDId()
    402 		if idProp == nil || !idProp.IsIRI() {
    403 			return nil, nil, gtserror.New("no id property found on person, or id was not an iri")
    404 		}
    405 
    406 		// Get IRI host value.
    407 		accHost := idProp.GetIRI().Host
    408 
    409 		latestAcc.Domain, _, err = d.fingerRemoteAccount(ctx,
    410 			tsport,
    411 			latestAcc.Username,
    412 			accHost,
    413 		)
    414 		if err != nil {
    415 			// We still couldn't webfinger the account, so we're not certain
    416 			// what the accountDomain actually is. Still, we can make a solid
    417 			// guess that it's the Host of the ActivityPub URI of the account.
    418 			// If we're wrong, we can just try again in a couple days.
    419 			log.Errorf(ctx, "error webfingering[2] remote account %s@%s: %v", latestAcc.Username, accHost, err)
    420 			latestAcc.Domain = accHost
    421 		}
    422 	}
    423 
    424 	// Ensure ID is set and update fetch time.
    425 	latestAcc.ID = account.ID
    426 	latestAcc.FetchedAt = time.Now()
    427 
    428 	// Reuse the existing account media attachments by default.
    429 	latestAcc.AvatarMediaAttachmentID = account.AvatarMediaAttachmentID
    430 	latestAcc.HeaderMediaAttachmentID = account.HeaderMediaAttachmentID
    431 
    432 	if (latestAcc.AvatarMediaAttachmentID == "") ||
    433 		(latestAcc.AvatarRemoteURL != account.AvatarRemoteURL) {
    434 		// Reset the avatar media ID (handles removed).
    435 		latestAcc.AvatarMediaAttachmentID = ""
    436 
    437 		if latestAcc.AvatarRemoteURL != "" {
    438 			// Avatar has changed to a new one, fetch up-to-date copy and use new ID.
    439 			latestAcc.AvatarMediaAttachmentID, err = d.fetchRemoteAccountAvatar(ctx,
    440 				tsport,
    441 				latestAcc.AvatarRemoteURL,
    442 				latestAcc.ID,
    443 			)
    444 			if err != nil {
    445 				log.Errorf(ctx, "error fetching remote avatar for account %s: %v", uri, err)
    446 
    447 				// Keep old avatar for now, we'll try again in $interval.
    448 				latestAcc.AvatarMediaAttachmentID = account.AvatarMediaAttachmentID
    449 				latestAcc.AvatarRemoteURL = account.AvatarRemoteURL
    450 			}
    451 		}
    452 	}
    453 
    454 	if (latestAcc.HeaderMediaAttachmentID == "") ||
    455 		(latestAcc.HeaderRemoteURL != account.HeaderRemoteURL) {
    456 		// Reset the header media ID (handles removed).
    457 		latestAcc.HeaderMediaAttachmentID = ""
    458 
    459 		if latestAcc.HeaderRemoteURL != "" {
    460 			// Header has changed to a new one, fetch up-to-date copy and use new ID.
    461 			latestAcc.HeaderMediaAttachmentID, err = d.fetchRemoteAccountHeader(ctx,
    462 				tsport,
    463 				latestAcc.HeaderRemoteURL,
    464 				latestAcc.ID,
    465 			)
    466 			if err != nil {
    467 				log.Errorf(ctx, "error fetching remote header for account %s: %v", uri, err)
    468 
    469 				// Keep old header for now, we'll try again in $interval.
    470 				latestAcc.HeaderMediaAttachmentID = account.HeaderMediaAttachmentID
    471 				latestAcc.HeaderRemoteURL = account.HeaderRemoteURL
    472 			}
    473 		}
    474 	}
    475 
    476 	// Fetch the latest remote account emoji IDs used in account display name/bio.
    477 	if _, err = d.fetchRemoteAccountEmojis(ctx, latestAcc, requestUser); err != nil {
    478 		log.Errorf(ctx, "error fetching remote emojis for account %s: %v", uri, err)
    479 	}
    480 
    481 	if account.CreatedAt.IsZero() {
    482 		// CreatedAt will be zero if no local copy was
    483 		// found in one of the GetAccountBy___() functions.
    484 		//
    485 		// Set time of creation from the last-fetched date.
    486 		latestAcc.CreatedAt = latestAcc.FetchedAt
    487 		latestAcc.UpdatedAt = latestAcc.FetchedAt
    488 
    489 		// This is new, put it in the database.
    490 		err := d.state.DB.PutAccount(ctx, latestAcc)
    491 
    492 		if errors.Is(err, db.ErrAlreadyExists) {
    493 			// TODO: replace this quick fix with per-URI deref locks.
    494 			latestAcc, err = d.state.DB.GetAccountByURI(ctx, latestAcc.URI)
    495 			return latestAcc, nil, err
    496 		}
    497 
    498 		if err != nil {
    499 			return nil, nil, gtserror.Newf("error putting in database: %w", err)
    500 		}
    501 	} else {
    502 		// Set time of update from the last-fetched date.
    503 		latestAcc.UpdatedAt = latestAcc.FetchedAt
    504 
    505 		// Use existing account values.
    506 		latestAcc.CreatedAt = account.CreatedAt
    507 		latestAcc.Language = account.Language
    508 
    509 		// This is an existing account, update the model in the database.
    510 		if err := d.state.DB.UpdateAccount(ctx, latestAcc); err != nil {
    511 			return nil, nil, gtserror.Newf("error updating database: %w", err)
    512 		}
    513 	}
    514 
    515 	return latestAcc, apubAcc, nil
    516 }
    517 
    518 func (d *deref) fetchRemoteAccountAvatar(ctx context.Context, tsport transport.Transport, avatarURL string, accountID string) (string, error) {
    519 	// Parse and validate provided media URL.
    520 	avatarURI, err := url.Parse(avatarURL)
    521 	if err != nil {
    522 		return "", err
    523 	}
    524 
    525 	// Acquire lock for derefs map.
    526 	unlock := d.derefAvatarsMu.Lock()
    527 	defer unlock()
    528 
    529 	// Look for an existing dereference in progress.
    530 	processing, ok := d.derefAvatars[avatarURL]
    531 
    532 	if !ok {
    533 		var err error
    534 
    535 		// Set the media data function to dereference avatar from URI.
    536 		data := func(ctx context.Context) (io.ReadCloser, int64, error) {
    537 			return tsport.DereferenceMedia(ctx, avatarURI)
    538 		}
    539 
    540 		// Create new media processing request from the media manager instance.
    541 		processing, err = d.mediaManager.PreProcessMedia(ctx, data, accountID, &media.AdditionalMediaInfo{
    542 			Avatar:    func() *bool { v := true; return &v }(),
    543 			RemoteURL: &avatarURL,
    544 		})
    545 		if err != nil {
    546 			return "", err
    547 		}
    548 
    549 		// Store media in map to mark as processing.
    550 		d.derefAvatars[avatarURL] = processing
    551 
    552 		defer func() {
    553 			// On exit safely remove media from map.
    554 			unlock := d.derefAvatarsMu.Lock()
    555 			delete(d.derefAvatars, avatarURL)
    556 			unlock()
    557 		}()
    558 	}
    559 
    560 	// Unlock map.
    561 	unlock()
    562 
    563 	// Start media attachment loading (blocking call).
    564 	if _, err := processing.LoadAttachment(ctx); err != nil {
    565 		return "", err
    566 	}
    567 
    568 	return processing.AttachmentID(), nil
    569 }
    570 
    571 func (d *deref) fetchRemoteAccountHeader(ctx context.Context, tsport transport.Transport, headerURL string, accountID string) (string, error) {
    572 	// Parse and validate provided media URL.
    573 	headerURI, err := url.Parse(headerURL)
    574 	if err != nil {
    575 		return "", err
    576 	}
    577 
    578 	// Acquire lock for derefs map.
    579 	unlock := d.derefHeadersMu.Lock()
    580 	defer unlock()
    581 
    582 	// Look for an existing dereference in progress.
    583 	processing, ok := d.derefHeaders[headerURL]
    584 
    585 	if !ok {
    586 		var err error
    587 
    588 		// Set the media data function to dereference header from URI.
    589 		data := func(ctx context.Context) (io.ReadCloser, int64, error) {
    590 			return tsport.DereferenceMedia(ctx, headerURI)
    591 		}
    592 
    593 		// Create new media processing request from the media manager instance.
    594 		processing, err = d.mediaManager.PreProcessMedia(ctx, data, accountID, &media.AdditionalMediaInfo{
    595 			Header:    func() *bool { v := true; return &v }(),
    596 			RemoteURL: &headerURL,
    597 		})
    598 		if err != nil {
    599 			return "", err
    600 		}
    601 
    602 		// Store media in map to mark as processing.
    603 		d.derefHeaders[headerURL] = processing
    604 
    605 		defer func() {
    606 			// On exit safely remove media from map.
    607 			unlock := d.derefHeadersMu.Lock()
    608 			delete(d.derefHeaders, headerURL)
    609 			unlock()
    610 		}()
    611 	}
    612 
    613 	// Unlock map.
    614 	unlock()
    615 
    616 	// Start media attachment loading (blocking call).
    617 	if _, err := processing.LoadAttachment(ctx); err != nil {
    618 		return "", err
    619 	}
    620 
    621 	return processing.AttachmentID(), nil
    622 }
    623 
    624 func (d *deref) fetchRemoteAccountEmojis(ctx context.Context, targetAccount *gtsmodel.Account, requestingUsername string) (bool, error) {
    625 	maybeEmojis := targetAccount.Emojis
    626 	maybeEmojiIDs := targetAccount.EmojiIDs
    627 
    628 	// It's possible that the account had emoji IDs set on it, but not Emojis
    629 	// themselves, depending on how it was fetched before being passed to us.
    630 	//
    631 	// If we only have IDs, fetch the emojis from the db. We know they're in
    632 	// there or else they wouldn't have IDs.
    633 	if len(maybeEmojiIDs) > len(maybeEmojis) {
    634 		maybeEmojis = make([]*gtsmodel.Emoji, 0, len(maybeEmojiIDs))
    635 		for _, emojiID := range maybeEmojiIDs {
    636 			maybeEmoji, err := d.state.DB.GetEmojiByID(ctx, emojiID)
    637 			if err != nil {
    638 				return false, err
    639 			}
    640 			maybeEmojis = append(maybeEmojis, maybeEmoji)
    641 		}
    642 	}
    643 
    644 	// For all the maybe emojis we have, we either fetch them from the database
    645 	// (if we haven't already), or dereference them from the remote instance.
    646 	gotEmojis, err := d.populateEmojis(ctx, maybeEmojis, requestingUsername)
    647 	if err != nil {
    648 		return false, err
    649 	}
    650 
    651 	// Extract the ID of each fetched or dereferenced emoji, so we can attach
    652 	// this to the account if necessary.
    653 	gotEmojiIDs := make([]string, 0, len(gotEmojis))
    654 	for _, e := range gotEmojis {
    655 		gotEmojiIDs = append(gotEmojiIDs, e.ID)
    656 	}
    657 
    658 	var (
    659 		changed  = false // have the emojis for this account changed?
    660 		maybeLen = len(maybeEmojis)
    661 		gotLen   = len(gotEmojis)
    662 	)
    663 
    664 	// if the length of everything is zero, this is simple:
    665 	// nothing has changed and there's nothing to do
    666 	if maybeLen == 0 && gotLen == 0 {
    667 		return changed, nil
    668 	}
    669 
    670 	// if the *amount* of emojis on the account has changed, then the got emojis
    671 	// are definitely different from the previous ones (if there were any) --
    672 	// the account has either more or fewer emojis set on it now, so take the
    673 	// discovered emojis as the new correct ones.
    674 	if maybeLen != gotLen {
    675 		changed = true
    676 		targetAccount.Emojis = gotEmojis
    677 		targetAccount.EmojiIDs = gotEmojiIDs
    678 		return changed, nil
    679 	}
    680 
    681 	// if the lengths are the same but not all of the slices are
    682 	// zero, something *might* have changed, so we have to check
    683 
    684 	// 1. did we have emojis before that we don't have now?
    685 	for _, maybeEmoji := range maybeEmojis {
    686 		var stillPresent bool
    687 
    688 		for _, gotEmoji := range gotEmojis {
    689 			if maybeEmoji.URI == gotEmoji.URI {
    690 				// the emoji we maybe had is still present now,
    691 				// so we can stop checking gotEmojis
    692 				stillPresent = true
    693 				break
    694 			}
    695 		}
    696 
    697 		if !stillPresent {
    698 			// at least one maybeEmoji is no longer present in
    699 			// the got emojis, so we can stop checking now
    700 			changed = true
    701 			targetAccount.Emojis = gotEmojis
    702 			targetAccount.EmojiIDs = gotEmojiIDs
    703 			return changed, nil
    704 		}
    705 	}
    706 
    707 	// 2. do we have emojis now that we didn't have before?
    708 	for _, gotEmoji := range gotEmojis {
    709 		var wasPresent bool
    710 
    711 		for _, maybeEmoji := range maybeEmojis {
    712 			// check emoji IDs here as well, because unreferenced
    713 			// maybe emojis we didn't already have would not have
    714 			// had IDs set on them yet
    715 			if gotEmoji.URI == maybeEmoji.URI && gotEmoji.ID == maybeEmoji.ID {
    716 				// this got emoji was present already in the maybeEmoji,
    717 				// so we can stop checking through maybeEmojis
    718 				wasPresent = true
    719 				break
    720 			}
    721 		}
    722 
    723 		if !wasPresent {
    724 			// at least one gotEmojis was not present in
    725 			// the maybeEmojis, so we can stop checking now
    726 			changed = true
    727 			targetAccount.Emojis = gotEmojis
    728 			targetAccount.EmojiIDs = gotEmojiIDs
    729 			return changed, nil
    730 		}
    731 	}
    732 
    733 	return changed, nil
    734 }
    735 
    736 // dereferenceAccountFeatured dereferences an account's featuredCollectionURI (if not empty). For each discovered status, this status will
    737 // be dereferenced (if necessary) and marked as pinned (if necessary). Then, old pins will be removed if they're not included in new pins.
    738 func (d *deref) dereferenceAccountFeatured(ctx context.Context, requestUser string, account *gtsmodel.Account) error {
    739 	uri, err := url.Parse(account.FeaturedCollectionURI)
    740 	if err != nil {
    741 		return err
    742 	}
    743 
    744 	// Pre-fetch a transport for requesting username, used by later deref procedures.
    745 	tsport, err := d.transportController.NewTransportForUsername(ctx, requestUser)
    746 	if err != nil {
    747 		return gtserror.Newf("couldn't create transport: %w", err)
    748 	}
    749 
    750 	b, err := tsport.Dereference(ctx, uri)
    751 	if err != nil {
    752 		return err
    753 	}
    754 
    755 	m := make(map[string]interface{})
    756 	if err := json.Unmarshal(b, &m); err != nil {
    757 		return gtserror.Newf("error unmarshalling bytes into json: %w", err)
    758 	}
    759 
    760 	t, err := streams.ToType(ctx, m)
    761 	if err != nil {
    762 		return gtserror.Newf("error resolving json into ap vocab type: %w", err)
    763 	}
    764 
    765 	if t.GetTypeName() != ap.ObjectOrderedCollection {
    766 		return gtserror.Newf("%s was not an OrderedCollection", uri)
    767 	}
    768 
    769 	collection, ok := t.(vocab.ActivityStreamsOrderedCollection)
    770 	if !ok {
    771 		return gtserror.New("couldn't coerce OrderedCollection")
    772 	}
    773 
    774 	items := collection.GetActivityStreamsOrderedItems()
    775 	if items == nil {
    776 		return gtserror.New("nil orderedItems")
    777 	}
    778 
    779 	// Get previous pinned statuses (we'll need these later).
    780 	wasPinned, err := d.state.DB.GetAccountPinnedStatuses(ctx, account.ID)
    781 	if err != nil && !errors.Is(err, db.ErrNoEntries) {
    782 		return gtserror.Newf("error getting account pinned statuses: %w", err)
    783 	}
    784 
    785 	statusURIs := make([]*url.URL, 0, items.Len())
    786 	for iter := items.Begin(); iter != items.End(); iter = iter.Next() {
    787 		var statusURI *url.URL
    788 
    789 		switch {
    790 		case iter.IsActivityStreamsNote():
    791 			// We got a whole Note. Extract the URI.
    792 			if note := iter.GetActivityStreamsNote(); note != nil {
    793 				if id := note.GetJSONLDId(); id != nil {
    794 					statusURI = id.GetIRI()
    795 				}
    796 			}
    797 		case iter.IsActivityStreamsArticle():
    798 			// We got a whole Article. Extract the URI.
    799 			if article := iter.GetActivityStreamsArticle(); article != nil {
    800 				if id := article.GetJSONLDId(); id != nil {
    801 					statusURI = id.GetIRI()
    802 				}
    803 			}
    804 		default:
    805 			// Try to get just the URI.
    806 			statusURI = iter.GetIRI()
    807 		}
    808 
    809 		if statusURI == nil {
    810 			continue
    811 		}
    812 
    813 		if statusURI.Host != uri.Host {
    814 			// If this status doesn't share a host with its featured
    815 			// collection URI, we shouldn't trust it. Just move on.
    816 			continue
    817 		}
    818 
    819 		// Already append this status URI to our slice.
    820 		// We do this here so that even if we can't get
    821 		// the status in the next part for some reason,
    822 		// we still know it was *meant* to be pinned.
    823 		statusURIs = append(statusURIs, statusURI)
    824 
    825 		status, _, err := d.getStatusByURI(ctx, requestUser, statusURI)
    826 		if err != nil {
    827 			// We couldn't get the status, bummer. Just log + move on, we can try later.
    828 			log.Errorf(ctx, "error getting status from featured collection %s: %v", statusURI, err)
    829 			continue
    830 		}
    831 
    832 		// If the status was already pinned, we don't need to do anything.
    833 		if !status.PinnedAt.IsZero() {
    834 			continue
    835 		}
    836 
    837 		if status.AccountID != account.ID {
    838 			// Someone's pinned a status that doesn't
    839 			// belong to them, this doesn't work for us.
    840 			continue
    841 		}
    842 
    843 		if status.BoostOfID != "" {
    844 			// Someone's pinned a boost. This also
    845 			// doesn't work for us.
    846 			continue
    847 		}
    848 
    849 		// All conditions are met for this status to
    850 		// be pinned, so we can finally update it.
    851 		status.PinnedAt = time.Now()
    852 		if err := d.state.DB.UpdateStatus(ctx, status, "pinned_at"); err != nil {
    853 			log.Errorf(ctx, "error updating status in featured collection %s: %v", status.URI, err)
    854 			continue
    855 		}
    856 	}
    857 
    858 	// Now that we know which statuses are pinned, we should
    859 	// *unpin* previous pinned statuses that aren't included.
    860 outerLoop:
    861 	for _, status := range wasPinned {
    862 		for _, statusURI := range statusURIs {
    863 			if status.URI == statusURI.String() {
    864 				// This status is included in most recent
    865 				// pinned uris. No need to keep checking.
    866 				continue outerLoop
    867 			}
    868 		}
    869 
    870 		// Status was pinned before, but is not included
    871 		// in most recent pinned uris, so unpin it now.
    872 		status.PinnedAt = time.Time{}
    873 		if err := d.state.DB.UpdateStatus(ctx, status, "pinned_at"); err != nil {
    874 			log.Errorf(ctx, "error unpinning status %s: %v", status.URI, err)
    875 			continue
    876 		}
    877 	}
    878 
    879 	return nil
    880 }