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
|
// 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 dereferencing
import (
"context"
"errors"
"io"
"net/url"
"code.superseriousbusiness.org/gotosocial/internal/config"
"code.superseriousbusiness.org/gotosocial/internal/db"
"code.superseriousbusiness.org/gotosocial/internal/gtserror"
"code.superseriousbusiness.org/gotosocial/internal/gtsmodel"
"code.superseriousbusiness.org/gotosocial/internal/log"
"code.superseriousbusiness.org/gotosocial/internal/media"
"code.superseriousbusiness.org/gotosocial/internal/util"
)
// GetEmoji fetches the emoji with given shortcode,
// domain and remote URL to dereference it by. This
// handles the case of existing emojis by passing them
// to RefreshEmoji(), which in the case of a local
// emoji will be a no-op. If the emoji does not yet
// exist it will be newly inserted into the database
// followed by dereferencing the actual media file.
//
// Please note that even if an error is returned,
// an emoji model may still be returned if the error
// was only encountered during actual dereferencing.
// In this case, it will act as a placeholder.
func (d *Dereferencer) GetEmoji(
ctx context.Context,
shortcode string,
domain string,
remoteURL string,
info media.AdditionalEmojiInfo,
refresh bool,
async bool,
) (
*gtsmodel.Emoji,
error,
) {
// Look for an existing emoji with shortcode domain.
emoji, err := d.state.DB.GetEmojiByShortcodeDomain(ctx,
shortcode,
domain,
)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
return nil, gtserror.Newf("error fetching emoji from db: %w", err)
}
if emoji != nil {
// This was an existing emoji, pass to refresh func.
return d.RefreshEmoji(ctx, emoji, info, refresh, async)
}
if domain == "" {
// failed local lookup, will be db.ErrNoEntries.
return nil, gtserror.SetUnretrievable(err)
}
// Pass along for safe processing.
return d.processEmojiSafely(ctx,
shortcode,
domain,
func() (*media.ProcessingEmoji, error) {
// Ensure we have a valid remote URL.
url, err := url.Parse(remoteURL)
if err != nil {
err := gtserror.Newf("invalid image remote url %s for emoji %s@%s: %w", remoteURL, shortcode, domain, err)
return nil, err
}
// Acquire new instance account transport for emoji dereferencing.
tsport, err := d.transportController.NewTransportForUsername(ctx, "")
if err != nil {
err := gtserror.Newf("error getting instance transport: %w", err)
return nil, err
}
// Get maximum supported remote emoji size.
maxsz := int64(config.GetMediaEmojiRemoteMaxSize()) // #nosec G115 -- Already validated.
// Prepare data function to dereference remote emoji media.
data := func(context.Context) (io.ReadCloser, error) {
return tsport.DereferenceMedia(ctx, url, maxsz)
}
// Create new emoji with prepared info.
return d.mediaManager.CreateEmoji(ctx,
shortcode,
domain,
data,
info,
)
},
false, // refresh
async,
)
}
// RefreshEmoji ensures that the given emoji is
// up-to-date, both in terms of being cached in
// in local instance storage, and compared to extra
// information provided in media.AdditionEmojiInfo{}.
// (note that is a no-op to pass in a local emoji).
//
// Please note that even if an error is returned,
// an emoji model may still be returned if the error
// was only encountered during actual dereferencing.
// In this case, it will act as a placeholder.
func (d *Dereferencer) RefreshEmoji(
ctx context.Context,
emoji *gtsmodel.Emoji,
info media.AdditionalEmojiInfo,
force bool,
async bool,
) (
*gtsmodel.Emoji,
error,
) {
// Check uri up-to-date.
if info.URI != nil &&
*info.URI != emoji.URI {
emoji.URI = *info.URI
force = true
}
// Check image remote URL up-to-date.
if info.ImageRemoteURL != nil &&
*info.ImageRemoteURL != emoji.ImageRemoteURL {
emoji.ImageRemoteURL = *info.ImageRemoteURL
force = true
}
// Check image static remote URL up-to-date.
if info.ImageStaticRemoteURL != nil &&
*info.ImageStaticRemoteURL != emoji.ImageStaticRemoteURL {
emoji.ImageStaticRemoteURL = *info.ImageStaticRemoteURL
force = true
}
// Check if needs
// force refresh.
if !force {
// We still want to make sure
// the emoji is cached. Simply
// check whether emoji is cached.
return d.RecacheEmoji(ctx, emoji, async)
}
// Can't refresh local.
if emoji.IsLocal() {
return emoji, nil
}
// Ensure we have a valid image remote URL.
url, err := url.Parse(emoji.ImageRemoteURL)
if err != nil {
err := gtserror.Newf("invalid image remote url %s for emoji %s@%s: %w", emoji.ImageRemoteURL, emoji.Shortcode, emoji.Domain, err)
return nil, err
}
// Pass along for safe processing.
return d.processEmojiSafely(ctx,
emoji.Shortcode,
emoji.Domain,
func() (*media.ProcessingEmoji, error) {
// Acquire new instance account transport for emoji dereferencing.
tsport, err := d.transportController.NewTransportForUsername(ctx, "")
if err != nil {
err := gtserror.Newf("error getting instance transport: %w", err)
return nil, err
}
// Get maximum supported remote emoji size.
maxsz := int64(config.GetMediaEmojiRemoteMaxSize()) // #nosec G115 -- Already validated.
// Prepare data function to dereference remote emoji media.
data := func(context.Context) (io.ReadCloser, error) {
return tsport.DereferenceMedia(ctx, url, maxsz)
}
// Update emoji with prepared info.
return d.mediaManager.UpdateEmoji(ctx,
emoji,
data,
info,
)
},
true, // refresh
async,
)
}
// RecacheEmoji handles the simplest case which is that
// of an existing emoji that only needs to be recached.
// It handles the case of both local emojis, and those
// already cached as no-ops.
//
// Please note that even if an error is returned,
// an emoji model may still be returned if the error
// was only encountered during actual dereferencing.
// In this case, it will act as a placeholder.
func (d *Dereferencer) RecacheEmoji(
ctx context.Context,
emoji *gtsmodel.Emoji,
async bool,
) (
*gtsmodel.Emoji,
error,
) {
// Can't recache local.
if emoji.IsLocal() {
return emoji, nil
}
if *emoji.Cached {
// Already cached.
return emoji, nil
}
// Ensure we have a valid image remote URL.
url, err := url.Parse(emoji.ImageRemoteURL)
if err != nil {
err := gtserror.Newf("invalid image remote url %s for emoji %s@%s: %w", emoji.ImageRemoteURL, emoji.Shortcode, emoji.Domain, err)
return nil, err
}
// Pass along for safe processing.
return d.processEmojiSafely(ctx,
emoji.Shortcode,
emoji.Domain,
func() (*media.ProcessingEmoji, error) {
// Acquire new instance account transport for emoji dereferencing.
tsport, err := d.transportController.NewTransportForUsername(ctx, "")
if err != nil {
err := gtserror.Newf("error getting instance transport: %w", err)
return nil, err
}
// Get maximum supported remote emoji size.
maxsz := int64(config.GetMediaEmojiRemoteMaxSize()) // #nosec G115 -- Already validated.
// Prepare data function to dereference remote emoji media.
data := func(context.Context) (io.ReadCloser, error) {
return tsport.DereferenceMedia(ctx, url, maxsz)
}
// Recache emoji with prepared info.
return d.mediaManager.CacheEmoji(ctx,
emoji,
data,
)
},
false, // refresh
async,
)
}
// processingEmojiSafely provides concurrency-safe processing of
// an emoji with given shortcode+domain. if a copy of the emoji is
// not already being processed, the given 'process' callback will
// be used to generate new *media.ProcessingEmoji{} instance. async
// determines whether to load it immediately, or in the background.
func (d *Dereferencer) processEmojiSafely(
ctx context.Context,
shortcode string,
domain string,
process func() (*media.ProcessingEmoji, error),
refresh bool,
async bool,
) (
emoji *gtsmodel.Emoji,
err error,
) {
// Generate shortcode@domain for locks + logging.
shortcodeDomain := shortcode + "@" + domain
// Acquire map lock.
d.derefEmojisMu.Lock()
// Ensure unlock only done once.
unlock := d.derefEmojisMu.Unlock
unlock = util.DoOnce(unlock)
defer unlock()
// Look for an existing dereference in progress.
processing, ok := d.derefEmojis[shortcodeDomain]
if !ok {
if !refresh {
// Before starting processing, ensure the information
// we have about emoji (i.e. getting here) is up-to-date.
emoji, err := d.state.DB.GetEmojiByShortcodeDomain(ctx,
shortcode,
domain,
)
if err != nil && !errors.Is(err, db.ErrNoEntries) {
return nil, gtserror.Newf("error fetching emoji from db: %w", err)
}
// If just been cached, use this!
if emoji != nil && *emoji.Cached {
return emoji, nil
}
}
// Start new processing emoji.
processing, err = process()
if err != nil {
return nil, err
}
// Add processing emoji media to hash map.
d.derefEmojis[shortcodeDomain] = processing
}
// Unlock map.
unlock()
if async {
emoji = processing.LoadAsync(func() {
// Remove on finish.
d.derefEmojisMu.Lock()
delete(d.derefEmojis, shortcodeDomain)
d.derefEmojisMu.Unlock()
})
} else {
defer func() {
// Remove on finish.
d.derefEmojisMu.Lock()
delete(d.derefEmojis, shortcodeDomain)
d.derefEmojisMu.Unlock()
}()
// Perform emoji load operation.
emoji, err = processing.Load(ctx)
if err != nil {
err = gtserror.Newf("error loading emoji %s: %w", shortcodeDomain, err)
// TODO: in time we should return checkable flags by gtserror.Is___()
// which can determine if loading error should allow remaining placeholder.
}
}
return
}
func (d *Dereferencer) fetchEmojis(
ctx context.Context,
existing []*gtsmodel.Emoji,
emojis []*gtsmodel.Emoji, // newly dereferenced
) (
[]*gtsmodel.Emoji,
bool, // any changes?
error,
) {
// Track any changes.
changed := false
for i, placeholder := range emojis {
// Look for an existing emoji with shortcode + domain.
existing, ok := getEmojiByShortcodeDomain(existing,
placeholder.Shortcode,
placeholder.Domain,
)
if ok && existing.ID != "" {
// Check for any emoji changes that
// indicate we should force a refresh.
force := emojiChanged(existing, placeholder)
// Ensure that the existing emoji model is up-to-date and cached.
existing, err := d.RefreshEmoji(ctx, existing, media.AdditionalEmojiInfo{
// Set latest values from placeholder.
URI: &placeholder.URI,
ImageRemoteURL: &placeholder.ImageRemoteURL,
ImageStaticRemoteURL: &placeholder.ImageStaticRemoteURL,
}, force, true)
if err != nil {
log.Errorf(ctx, "error refreshing emoji: %v", err)
// specifically do NOT continue here,
// we already have a model, we don't
// want to drop it from the slice, just
// log that an update for it failed.
}
// Set existing emoji.
emojis[i] = existing
continue
}
// Emojis changed!
changed = true
// Fetch this newly added emoji,
// this function handles the case
// of existing cached emojis and
// new ones requiring dereference.
emoji, err := d.GetEmoji(ctx,
placeholder.Shortcode,
placeholder.Domain,
placeholder.ImageRemoteURL,
media.AdditionalEmojiInfo{
URI: &placeholder.URI,
ImageRemoteURL: &placeholder.ImageRemoteURL,
ImageStaticRemoteURL: &placeholder.ImageStaticRemoteURL,
},
false,
true,
)
if err != nil {
if emoji == nil {
log.Errorf(ctx, "error loading emoji %s: %v", placeholder.ImageRemoteURL, err)
continue
}
// non-fatal error occurred during loading, still use it.
log.Warnf(ctx, "partially loaded emoji: %v", err)
}
// Set updated emoji.
emojis[i] = emoji
}
for i := 0; i < len(emojis); {
if emojis[i].ID == "" {
// Remove failed emoji populations.
copy(emojis[i:], emojis[i+1:])
emojis = emojis[:len(emojis)-1]
continue
}
i++
}
return emojis, changed, nil
}
|