Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions AppleNugs/App/AppModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,16 @@ final class AppModel {
return parsed
}

/// Artist photos for the given catalog ids (Home's crate). Empty on a
/// `-UITEST` run, whose stub catalog's ids are fake — a real lookup would
/// put strangers' photos on the stub artists' names.
func artistAvatars(ids: [String]) async throws -> [String: URL] {
#if DEBUG
if AppModel.isUITestRun { return [:] }
#endif
return try await client.artistAvatars(ids: ids)
}

/// Resolve a display name to the catalog's own entry.
///
/// The player only ever knows an artist's NAME — `QueueTrack` carries no
Expand Down
21 changes: 21 additions & 0 deletions AppleNugs/Core/Catalog.swift
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,27 @@ enum Catalog {
}
}

/// v1 `GET /artists?ids=…` → artist id → avatar photo URL.
///
/// The legacy `catalog.artists` list the app browses carries only a dead
/// header GIF per artist; the v1 catalog carries a real 800×800 photo for
/// every artist (`avatarImage.url`, a redirect to the image CDN). The two
/// share artist ids, so the result keys straight onto `ArtistEntry.id`.
/// Entries without an id or a parseable http(s) URL are skipped, so a
/// missing photo falls back to the monogram rather than a broken image.
static func artistAvatars(from json: JSON) -> [String: URL] {
var avatars: [String: URL] = [:]
for item in json.unwrapped.arr("items", "Items") {
guard let id = item.str("id", "artistID", "artistId"),
let string = item["avatarImage"].str("url"),
let url = URL(string: string),
let scheme = url.scheme?.lowercased(), scheme == "https" || scheme == "http"
else { continue }
avatars[id] = url
}
return avatars
}

/// catalog.containersAll → containers (newest-first per the API).
static func containers(from json: JSON) -> [ContainerSummary] {
json.unwrapped.arr("containers", "Containers").compactMap { c in
Expand Down
12 changes: 12 additions & 0 deletions AppleNugs/Core/NugsClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,18 @@ actor NugsClient {
return try await getJSON(url, bearer: session.accessToken)
}

/// Artist photos for a handful of artists, in ONE request: the v1
/// catalog's `/artists?ids=` filter (verified 2026-11-16 — the unfiltered
/// list is 718 artists across 8 pages). Keyed by `ArtistEntry.id`.
func artistAvatars(ids: [String]) async throws -> [String: URL] {
guard !ids.isEmpty else { return [:] }
let json = try await catalogV1Get("/artists", query: [
"ids": ids.joined(separator: ","),
"limit": String(ids.count),
])
return Catalog.artistAvatars(from: json)
}

// --- video catalog ------------------------------------------------------

/// Recently-added VOD (the only artist-independent global video listing).
Expand Down
86 changes: 76 additions & 10 deletions AppleNugs/Views/HomeView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ struct HomeView: View {
@State private var artistCount = 0
@State private var appeared = false
@State private var sampleError: String?
/// The crate artists' photos, by artist id. Empty until the lookup lands
/// (and for good if it fails) — tiles show the monogram meanwhile.
@State private var avatars: [String: URL] = [:]
/// Starts true: the fetch is already coming, and a one-frame "nothing in
/// the crate" is a worse lie than a spinner nobody sees.
@State private var loadingSample = true
Expand Down Expand Up @@ -237,20 +240,32 @@ struct HomeView: View {
private var crateColumn: GridItem.Size { .adaptive(minimum: 92, maximum: 132) }
private var crateSpacing: CGFloat { 10 }

/// Monogram over the name, centered. The name always reserves two lines,
/// so every tile in a row stands the same height whatever the name's length.
/// The artist's photo in a circle (Apple Music's shape for an artist, so it
/// reads apart from the square show covers in Favorites above), the name
/// centered below.
///
/// Names are never cut off for ~98% of the catalog: up to three lines,
/// shrinking to 85% before truncating (median name 14 characters, 1 in 10
/// past 27, the longest 62). Two lines are always reserved, and the tile
/// stretches to its row, so a row of short and long names lines up.
private func crateCell(_ artist: ArtistEntry) -> some View {
VStack(spacing: 8) {
MonogramTile(text: artist.name, size: 44)
Text(artist.name)
.font(theme.type.body(13))
.foregroundStyle(theme.palette.textPrimary)
.multilineTextAlignment(.center)
.lineLimit(2, reservesSpace: true)
ArtistPortrait(url: avatars[artist.id], name: artist.name)
ZStack(alignment: .top) {
// Holds two lines' height at the current Dynamic Type size.
Text(" ").lineLimit(2, reservesSpace: true).hidden()
Text(artist.name)
.foregroundStyle(theme.palette.textPrimary)
.multilineTextAlignment(.center)
.lineLimit(3)
.minimumScaleFactor(0.85)
}
.font(theme.type.body(13))
}
.padding(.horizontal, 8)
.padding(.vertical, 12)
.frame(maxWidth: .infinity)
.padding(.top, 10)
.padding(.bottom, 10)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
}
#else
private var crateColumn: GridItem.Size { .adaptive(minimum: 200, maximum: 280) }
Expand Down Expand Up @@ -344,6 +359,13 @@ struct HomeView: View {
} catch {
sampleError = error.localizedDescription
}
#if os(iOS)
// Photos are a nicety on top of a crate that already works: a failure
// leaves the monograms, and reports nothing.
if !sample.isEmpty {
avatars = (try? await app.artistAvatars(ids: sample.map(\.id))) ?? [:]
}
#endif
}
}

Expand Down Expand Up @@ -444,3 +466,47 @@ private extension View {
modifier(Reveal(appeared: appeared, index: index))
}
}

#if os(iOS)
// MARK: - Artist portrait

/// An artist's photo clipped to a circle, filling the width it's given. The
/// monogram stands in while the photo loads, when there is none, and when it
/// fails — so a crate with no network still reads as artists, not holes.
private struct ArtistPortrait: View {
@Environment(\.theme) private var theme

let url: URL?
let name: String

var body: some View {
GeometryReader { geo in
let side = min(geo.size.width, geo.size.height)
Group {
if let url {
AsyncImage(url: url) { phase in
if case .success(let image) = phase {
image.resizable().aspectRatio(contentMode: .fill)
} else {
monogram(side)
}
}
} else {
monogram(side)
}
}
.frame(width: side, height: side)
.clipShape(Circle())
.overlay { Circle().strokeBorder(theme.palette.hairline, lineWidth: 1) }
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.aspectRatio(1, contentMode: .fit)
.accessibilityHidden(true)
}

private func monogram(_ side: CGFloat) -> some View {
MonogramTile(text: name, size: side)
}
}
#endif

50 changes: 50 additions & 0 deletions AppleNugsTests/CatalogArtistAvatarsTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import XCTest

final class CatalogArtistAvatarsTests: XCTestCase {

private func parse(_ items: String) -> [String: URL] {
let data = #"{"offset":0,"limit":9,"total":2,"items":["#.appending(items).appending("]}").data(using: .utf8)!
return Catalog.artistAvatars(from: JSON.parse(data))
}

/// The real v1 shape (trimmed): id → the avatar's redirecting URL.
func testMapsIdToAvatarURL() {
let avatars = parse(#"""
{"id":"1205","name":"Goose","abbreviation":"goo",
"avatarImage":{"id":null,"url":"https://catalog.nugs.net/api/v1/artists/1205/images/avatar/8a5a8811"},
"coverImage":{"id":null,"url":"https://catalog.nugs.net/api/v1/artists/1205/images/cover/a54e"}},
{"id":"101","name":"Lotus",
"avatarImage":{"id":null,"url":"https://catalog.nugs.net/api/v1/artists/101/images/avatar/0e8a"}}
"""#)
XCTAssertEqual(avatars.count, 2)
XCTAssertEqual(avatars["1205"]?.absoluteString,
"https://catalog.nugs.net/api/v1/artists/1205/images/avatar/8a5a8811")
XCTAssertEqual(avatars["101"]?.lastPathComponent, "0e8a")
}

/// The avatar, never the wide cover image.
func testIgnoresCoverImage() {
let avatars = parse(#"""
{"id":"7","name":"Cover Only","coverImage":{"url":"https://x/cover.jpg"}}
"""#)
XCTAssertTrue(avatars.isEmpty)
}

/// Missing ids, missing or empty urls and non-http urls fall back to the
/// monogram (no entry) instead of a broken image.
func testSkipsUnusableEntries() {
let avatars = parse(#"""
{"name":"No Id","avatarImage":{"url":"https://x/a.jpg"}},
{"id":"2","name":"Null Url","avatarImage":{"id":null,"url":null}},
{"id":"3","name":"Empty Url","avatarImage":{"url":""}},
{"id":"4","name":"Relative","avatarImage":{"url":"/images/a.jpg"}},
{"id":"5","name":"Good","avatarImage":{"url":"https://x/5.jpg"}}
"""#)
XCTAssertEqual(Array(avatars.keys), ["5"])
}

func testEmptyOrMalformedResponse() {
XCTAssertTrue(Catalog.artistAvatars(from: JSON.parse(Data("{}".utf8))).isEmpty)
XCTAssertTrue(Catalog.artistAvatars(from: JSON.parse(Data("not json".utf8))).isEmpty)
}
}
Loading