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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
package main

// The two queries that decide what the UI shows.
//
// Both are ported verbatim from the Haskell version, down to the CTE structure
// and the comments, because they encode judgements that are not reconstructable
// from the code around them (what counts as a "favourite", why a torrent that
// was already downloaded wins over a better-seeded one, and so on).
//
// The placeholder style differs — pgx uses $1 rather than ? — but the SQL is
// otherwise unchanged.

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

	"go.opentelemetry.io/otel/trace"
)

// torrentStatus is the download state of a torrent, in the order the UI cares
// about: we have nothing, we have the .torrent, or Transmission has it.
type torrentStatus int

const (
	noTorrentFileYet torrentStatus = iota
	notInTransmissionYet
	inTransmission
)

// torrentData is one row of the torrent tables.
type torrentData struct {
	GroupID       int
	TorrentID     int
	ReleaseType   releaseType
	SeedingWeight int
	Artists       []artistRef
	GroupName     string
	GroupYear     int
	TorrentFormat string

	Status torrentStatus
	// TorrentHash and PercentDone are only meaningful when Status is
	// inTransmission.
	TorrentHash string
	PercentDone int
}

// recommendation is a torrent together with the favourite artists that led to
// it being suggested.
type recommendation struct {
	Torrent torrentData
	// RecommendedBy lists the favourite artists this suggestion came from.
	RecommendedBy []recommendationReason
}

type recommendationReason struct {
	FavoritedArtistID   int    `json:"favorited_artist_id"`
	FavoritedArtistName string `json:"favorited_artist_name"`
	RecommendedArtistID int    `json:"recommended_artist_id"`
}

// bestTorrentsOrdering selects the sort order of the main table.
type bestTorrentsOrdering int

const (
	bySeedingWeight bestTorrentsOrdering = iota
	byLastReleases
)

// bestTorrentsFilter is the set of knobs the two callers use.
type bestTorrentsFilter struct {
	// OnlyArtistID restricts to one artist (the artist page).
	OnlyArtistID *int
	// OnlyTheseTorrents restricts to a set of torrent ids (search results).
	OnlyTheseTorrents []int
	// DisallowedReleaseTypes are filtered out in SQL.
	DisallowedReleaseTypes []releaseType
	// LimitResults caps the number of rows; nil means no limit.
	LimitResults *int
	Ordering     bestTorrentsOrdering
	// OnlyFavourites restricts to artists we have shown interest in.
	OnlyFavourites bool
}

// getBestTorrents finds the best torrent of each release group.
//
// "Best" is the highest seeding_weight, except that a torrent we already have
// the file for wins regardless — re-downloading a different torrent of a group
// we already own would be wasteful.
func (a *app) getBestTorrents(ctx context.Context, f bestTorrentsFilter) ([]torrentData, error) {
	const query = `
      WITH
      artist_has_been_snatched AS (
        SELECT DISTINCT artist_id
        FROM (
          SELECT
            UNNEST(artist_ids) as artist_id,
            t.torrent_file IS NOT NULL as has_torrent_file
          FROM redacted.torrents t) as _
        WHERE has_torrent_file
      ),
      filtered_torrents AS (
        SELECT DISTINCT ON (torrent_group)
          id
        FROM
          redacted.torrents
        JOIN LATERAL
          -- filter everything that’s not a favourite if requested
          (SELECT (
            artist_ids && ARRAY(
              SELECT DISTINCT unnest(artist_ids)
              FROM redacted.torrents_json
              WHERE transmission_torrent_hash IS NOT NULL
              UNION
              SELECT artist_id
              FROM redacted.artist_favourites
            )
            OR artist_ids && ARRAY(SELECT artist_id FROM artist_has_been_snatched)
          ) as is_favourite) as _
          ON (NOT $1::bool OR is_favourite)
        WHERE
          -- filter by artist id
          ($2::bool OR ($3::int = any (artist_ids)))
          -- filter by torrent ids
          AND
          ($4::bool OR torrent_id = ANY ($5::int[]))
        ORDER BY
          torrent_group,
          -- prefer torrents which we already downloaded
          torrent_file,
          seeding_weight DESC
      ),
      prepare1 AS (
        SELECT
          tg.group_id,
          t.torrent_id,
          t.seeding_weight,
          tg.full_json_result->>'releaseType' AS release_type,
          -- TODO: different endpoints handle this differently (e.g. action=search and action=artist), we should unify this while parsing
          COALESCE(
            t.full_json_result->'artists',
            tg.full_json_result->'artists',
            '[]'::jsonb
          ) as artists,
          t.artist_ids as artist_ids,
          tg.full_json_result->>'groupName' AS group_name,
          tg.full_json_result->>'groupYear' AS group_year,
          t.torrent_file IS NOT NULL AS has_torrent_file,
          t.transmission_torrent_hash,
          t.full_json_result->>'encoding' AS torrent_format
        FROM filtered_torrents f
        JOIN redacted.torrents t ON t.id = f.id
        JOIN redacted.torrent_groups tg ON tg.id = t.torrent_group
        WHERE
          tg.full_json_result->>'releaseType' <> ALL ($6::text[])
      )
      SELECT
        group_id,
        torrent_id,
        seeding_weight,
        release_type,
        artists,
        group_name,
        group_year,
        has_torrent_file,
        transmission_torrent_hash,
        torrent_format
      FROM prepare1
`
	orderBy := "ORDER BY seeding_weight DESC\n"
	if f.Ordering == byLastReleases {
		orderBy = "ORDER BY group_id DESC\n"
	}
	sql := query + orderBy + "LIMIT $7::int\n"

	onlyArtistDisabled := f.OnlyArtistID == nil
	onlyArtistID := 0
	if f.OnlyArtistID != nil {
		onlyArtistID = *f.OnlyArtistID
	}
	onlyTheseDisabled := f.OnlyTheseTorrents == nil
	onlyThese := f.OnlyTheseTorrents
	if onlyThese == nil {
		onlyThese = []int{}
	}

	rows, err := a.pool.Query(ctx, sql,
		f.OnlyFavourites,
		onlyArtistDisabled,
		onlyArtistID,
		onlyTheseDisabled,
		onlyThese,
		disallowedReleaseTypeStrings(f.DisallowedReleaseTypes),
		f.LimitResults,
	)
	if err != nil {
		return nil, fmt.Errorf("querying best torrents: %w", err)
	}
	defer rows.Close()

	var out []torrentData
	for rows.Next() {
		td, err := scanTorrentData(rows)
		if err != nil {
			return nil, err
		}
		out = append(out, td)
	}
	return out, rows.Err()
}

// rowScanner is the bit of pgx.Rows we need, so the two scan helpers can share
// code.
type rowScanner interface {
	Scan(dest ...any) error
}

func scanTorrentData(rows rowScanner) (torrentData, error) {
	var (
		td              torrentData
		releaseTypeStr  *string
		artistsJSON     []byte
		groupName       *string
		groupYear       *string
		hasTorrentFile  bool
		transmissionHex *string
		torrentFormat   *string
	)
	if err := rows.Scan(
		&td.GroupID,
		&td.TorrentID,
		&td.SeedingWeight,
		&releaseTypeStr,
		&artistsJSON,
		&groupName,
		&groupYear,
		&hasTorrentFile,
		&transmissionHex,
		&torrentFormat,
	); err != nil {
		return td, err
	}

	if releaseTypeStr != nil {
		td.ReleaseType = releaseTypeFromTextOrIntKey(*releaseTypeStr)
	}
	if len(artistsJSON) > 0 {
		// A malformed artists array must not fail the whole table; the Haskell
		// version also fell back to an empty list here.
		_ = json.Unmarshal(artistsJSON, &td.Artists)
	}
	if groupName != nil {
		td.GroupName = *groupName
	}
	if groupYear != nil {
		fmt.Sscanf(*groupYear, "%d", &td.GroupYear)
	}
	if torrentFormat != nil {
		td.TorrentFormat = prettyTorrentFormat(*torrentFormat)
	}

	switch {
	case !hasTorrentFile:
		td.Status = noTorrentFileYet
	case transmissionHex == nil:
		td.Status = notInTransmissionYet
	default:
		td.Status = inTransmission
		td.TorrentHash = *transmissionHex
	}
	return td, nil
}

// prettyTorrentFormat shortens the encoding names for the table.
func prettyTorrentFormat(s string) string {
	switch s {
	case "Lossless":
		return "flac"
	case "V0 (VBR)":
		return "V0"
	case "V2 (VBR)":
		return "V2"
	default:
		return s
	}
}

// getBestRecommendations returns one highest-weighted release per recommended
// artist.
//
// A "recommended artist" is one that the API considers similar to an artist we
// like, and that we do not already like ourselves.
func (a *app) getBestRecommendations(ctx context.Context, disallowed []releaseType, limit *int) ([]recommendation, error) {
	const query = `
      WITH
        favorited_artists AS (
          SELECT DISTINCT unnest(artist_ids) as artist_id
          FROM redacted.torrents_json
          WHERE transmission_torrent_hash IS NOT NULL
          UNION
          SELECT artist_id
          FROM redacted.artist_favourites
        ),
        valid_recommendations AS (
          SELECT
            sa.artist_id as favorited_artist_id,
            sa.similar_artist_id as recommended_artist_id,
            a.artist_name as favorited_artist_name,
            sa.rn
          FROM (
            SELECT
              artist_id,
              similar_artist_id,
              ROW_NUMBER() OVER (PARTITION BY artist_id ORDER BY score DESC) as rn
            FROM redacted.similar_artists
            WHERE
              artist_id IN (SELECT artist_id FROM favorited_artists)
              AND similar_artist_id NOT IN (SELECT artist_id FROM favorited_artists)
          ) sa
          JOIN redacted.artists a ON a.artist_id = sa.artist_id
        ),
        top_recommendations AS (
          SELECT DISTINCT ON (rec_id)
            tg.group_id,
            t.torrent_id,
            t.seeding_weight,
            tg.full_json_result->>'releaseType' AS release_type,
            COALESCE(
              t.full_json_result->'artists',
              tg.full_json_result->'artists',
              '[]'::jsonb
            ) as artists,
            t.artist_ids as artist_ids,
            tg.full_json_result->>'groupName' AS group_name,
            tg.full_json_result->>'groupYear' AS group_year,
            t.torrent_file IS NOT NULL AS has_torrent_file,
            t.transmission_torrent_hash,
            t.full_json_result->>'encoding' AS torrent_format
          FROM (SELECT recommended_artist_id FROM valid_recommendations) vr
          CROSS JOIN LATERAL unnest(ARRAY[vr.recommended_artist_id]) AS rec_id
          JOIN redacted.torrents_json t ON t.artist_ids @> ARRAY[rec_id]
          JOIN redacted.torrent_groups tg ON tg.id = t.torrent_group
          WHERE
            tg.full_json_result->>'releaseType' <> ALL ($1::text[])
          ORDER BY
            rec_id,
            t.seeding_weight DESC
        ),
        final_unsorted AS (
          SELECT
            tr.group_id,
            tr.torrent_id,
            tr.seeding_weight,
            tr.release_type,
            tr.artists,
            tr.group_name,
            tr.group_year,
            tr.has_torrent_file,
            tr.transmission_torrent_hash,
            tr.torrent_format,
            (
              SELECT json_agg(
                json_build_object(
                  'favorited_artist_id', vr2.favorited_artist_id,
                  'favorited_artist_name', vr2.favorited_artist_name,
                  'recommended_artist_id', vr2.recommended_artist_id
                )
              )
              FROM valid_recommendations vr2
              WHERE ARRAY[vr2.recommended_artist_id] <@ tr.artist_ids
            ) as recommendation_mappings
          FROM top_recommendations tr
          ORDER BY
            (SELECT MIN(vr2.rn) FROM valid_recommendations vr2 WHERE ARRAY[vr2.recommended_artist_id] <@ tr.artist_ids)
        )
      SELECT * FROM final_unsorted
      ORDER BY seeding_weight DESC
      LIMIT $2::int
`
	rows, err := a.pool.Query(ctx, query, disallowedReleaseTypeStrings(disallowed), limit)
	if err != nil {
		return nil, fmt.Errorf("querying recommendations: %w", err)
	}
	defer rows.Close()

	var out []recommendation
	for rows.Next() {
		var (
			rec             recommendation
			releaseTypeStr  *string
			artistsJSON     []byte
			groupName       *string
			groupYear       *string
			hasTorrentFile  bool
			transmissionHex *string
			torrentFormat   *string
			reasonsJSON     []byte
		)
		if err := rows.Scan(
			&rec.Torrent.GroupID,
			&rec.Torrent.TorrentID,
			&rec.Torrent.SeedingWeight,
			&releaseTypeStr,
			&artistsJSON,
			&groupName,
			&groupYear,
			&hasTorrentFile,
			&transmissionHex,
			&torrentFormat,
			&reasonsJSON,
		); err != nil {
			return nil, err
		}
		if releaseTypeStr != nil {
			rec.Torrent.ReleaseType = releaseTypeFromTextOrIntKey(*releaseTypeStr)
		}
		if len(artistsJSON) > 0 {
			_ = json.Unmarshal(artistsJSON, &rec.Torrent.Artists)
		}
		if groupName != nil {
			rec.Torrent.GroupName = *groupName
		}
		if groupYear != nil {
			fmt.Sscanf(*groupYear, "%d", &rec.Torrent.GroupYear)
		}
		if torrentFormat != nil {
			rec.Torrent.TorrentFormat = prettyTorrentFormat(*torrentFormat)
		}
		switch {
		case !hasTorrentFile:
			rec.Torrent.Status = noTorrentFileYet
		case transmissionHex == nil:
			rec.Torrent.Status = notInTransmissionYet
		default:
			rec.Torrent.Status = inTransmission
			rec.Torrent.TorrentHash = *transmissionHex
		}
		if len(reasonsJSON) > 0 {
			_ = json.Unmarshal(reasonsJSON, &rec.RecommendedBy)
		}
		out = append(out, rec)
	}
	return out, rows.Err()
}

// ---------------------------------------------------------------------------
// Status refresh
// ---------------------------------------------------------------------------

// releaseTypesHiddenFromTables are dropped from the main tables after querying.
//
// This filter is applied in Go rather than SQL because that is what the Haskell
// version did, and moving it into the query would change which torrent is
// picked per group.
var releaseTypesHiddenFromTables = []releaseType{
	releaseTypeCompilation,
	releaseTypeDJMix,
	releaseTypeMixtape,
	releaseTypeRemix,
}

// getBestTorrentsData runs the query, refreshes Transmission status, and re-runs
// the query if our stored state turned out to be stale.
func (a *app) getBestTorrentsData(ctx context.Context, f bestTorrentsFilter) ([]torrentData, error) {
	return inSpan1(ctx, "get torrents table data", func(ctx context.Context, span trace.Span) ([]torrentData, error) {
		if f.OnlyArtistID != nil {
			attr(span, "artist-filter.redacted-id", *f.OnlyArtistID)
		}
		if f.OnlyTheseTorrents != nil {
			attr(span, "torrent-filter.ids", fmt.Sprint(f.OnlyTheseTorrents))
		}

		best, err := a.getBestTorrents(ctx, f)
		if err != nil {
			return nil, err
		}

		stale, status, err := a.refreshStatuses(ctx, best)
		if err != nil {
			return nil, err
		}
		if stale {
			// Rather than serving a table mentioning torrents that no longer
			// exist, fetch the whole thing again. Wasteful, but deletions are
			// rare; revisit if that stops being true.
			event(span, "The transmission torrent list was out of date, refetching torrent list.")
			best, err = a.getBestTorrents(ctx, f)
			if err != nil {
				return nil, err
			}
		}

		out := make([]torrentData, 0, len(best))
		for _, td := range best {
			if isHiddenReleaseType(td.ReleaseType) {
				continue
			}
			applyStatus(&td, status)
			out = append(out, td)
		}
		return out, nil
	})
}

// getRecommendedTorrentsData is getBestTorrentsData for the recommendations.
func (a *app) getRecommendedTorrentsData(ctx context.Context, disallowed []releaseType, limit *int) ([]recommendation, error) {
	return inSpan1(ctx, "get recommended torrents data", func(ctx context.Context, span trace.Span) ([]recommendation, error) {
		recs, err := a.getBestRecommendations(ctx, disallowed, limit)
		if err != nil {
			return nil, err
		}
		attr(span, "recommendations.count", len(recs))
		if len(recs) == 0 {
			return nil, nil
		}

		torrents := make([]torrentData, len(recs))
		for i, r := range recs {
			torrents[i] = r.Torrent
		}
		stale, status, err := a.refreshStatuses(ctx, torrents)
		if err != nil {
			return nil, err
		}
		if stale {
			event(span, "The transmission torrent list was out of date, refetching torrent list.")
			recs, err = a.getBestRecommendations(ctx, disallowed, limit)
			if err != nil {
				return nil, err
			}
		}
		for i := range recs {
			applyStatus(&recs[i].Torrent, status)
		}
		return recs, nil
	})
}

// refreshStatuses asks Transmission about the torrents we believe it has.
func (a *app) refreshStatuses(ctx context.Context, torrents []torrentData) (bool, map[string]torrentStatusInfo, error) {
	var hashes []string
	for _, td := range torrents {
		if td.Status == inTransmission && td.TorrentHash != "" {
			hashes = append(hashes, td.TorrentHash)
		}
	}
	if len(hashes) == 0 {
		return false, map[string]torrentStatusInfo{}, nil
	}
	return a.getAndUpdateTransmissionTorrentsStatus(ctx, hashes)
}

// applyStatus folds the fresh Transmission status into a row.
//
// A torrent we thought was in Transmission but which is not there anymore
// becomes notInTransmissionYet.
func applyStatus(td *torrentData, status map[string]torrentStatusInfo) {
	if td.Status != inTransmission {
		return
	}
	info, ok := status[td.TorrentHash]
	if !ok {
		td.Status = notInTransmissionYet
		td.TorrentHash = ""
		return
	}
	td.PercentDone = info.PercentDone
}

func isHiddenReleaseType(rt releaseType) bool {
	for _, hidden := range releaseTypesHiddenFromTables {
		if hidden.IntKey == rt.IntKey && hidden.StringKey == rt.StringKey {
			return true
		}
	}
	return false
}