diff --git a/index_migration_test.go b/index_migration_test.go index ac92b868..2e01c01a 100644 --- a/index_migration_test.go +++ b/index_migration_test.go @@ -91,8 +91,12 @@ func TestGetIndexesRebuildsOlderDocuments(t *testing.T) { seedDocumentIndex(t, version) authors := index.CreateAuthorsIndex(homeDir + authorsIndexPath) retrieved := time.Now().UTC().Truncate(time.Second) - if err := authors.Index("existing-author", index.Author{ - Slug: "existing-author", Name: "Existing Author", DataSourceID: "Q1", RetrievedOn: retrieved, + if err := authors.Index("existing-author", struct { + index.Author + DataSourceReferences string + }{ + Author: index.Author{Slug: "existing-author", Name: "Existing Author", RetrievedOn: retrieved}, + DataSourceReferences: `{"wikidata":"Q1"}`, }); err != nil { t.Fatal(err) } @@ -150,7 +154,7 @@ func TestGetIndexesRebuildsOlderDocuments(t *testing.T) { t.Fatalf("library must be searchable after rebuilding: %+v, %v", book, err) } author, err := idx.Author("existing-author", "") - if err != nil || author.DataSourceID != "Q1" || !author.RetrievedOn.Equal(retrieved) { + if err != nil || author.DataSourceReferences["wikidata"] != "Q1" || !author.RetrievedOn.Equal(retrieved) { t.Fatalf("rebuilding must preserve author metadata: %+v, %v", author, err) } if err := idx.Close(); err != nil { @@ -269,14 +273,19 @@ func TestGetIndexesMigratesAuthorsWithoutReindexingDocuments(t *testing.T) { t.Fatal(err) } legacyMapping := index.CreateAuthorsMapping().(*mapping.IndexMappingImpl) - delete(legacyMapping.DefaultMapping.Properties, "DataSourceLinks") + delete(legacyMapping.DefaultMapping.Properties, "DataSourceReferences") + legacyMapping.DefaultMapping.AddFieldMappingsAt("DataSourceID", bleve.NewKeywordFieldMapping()) authors, err := bleve.New(homeDir+authorsIndexPath, legacyMapping) if err != nil { t.Fatal(err) } retrieved := time.Now().UTC().Truncate(time.Second) - if err := authors.Index("alice-borchardt", index.Author{ - Slug: "alice-borchardt", Name: "Alice Borchardt", DataSourceID: "Q1", RetrievedOn: retrieved, + if err := authors.Index("alice-borchardt", struct { + index.Author + DataSourceID string + }{ + Author: index.Author{Slug: "alice-borchardt", Name: "Alice Borchardt", RetrievedOn: retrieved}, + DataSourceID: "Q1", }); err != nil { t.Fatal(err) } @@ -305,7 +314,7 @@ func TestGetIndexesMigratesAuthorsWithoutReindexingDocuments(t *testing.T) { t.Fatalf("author migration changed document enrichment state: %+v, %v", data, err) } author, err := idx.Author("alice-borchardt", "") - if err != nil || author.DataSourceID != "Q1" || !author.RetrievedOn.Equal(retrieved) { + if err != nil || author.DataSourceReferences["wikidata"] != "Q1" || !author.RetrievedOn.Equal(retrieved) { t.Fatalf("expected existing author metadata preserved: %+v, %v", author, err) } if pending, err := idx.AuthorsWithoutInfo(); err != nil || len(pending) != 0 { diff --git a/internal/biography/service.go b/internal/biography/service.go index 79707bf2..bdc5f6f4 100644 --- a/internal/biography/service.go +++ b/internal/biography/service.go @@ -34,7 +34,7 @@ var spaceBeforePunctuation = regexp.MustCompile(` +([,.;:!?)\]])`) // Source supplies cleaned biography HTML (b, strong, i and em, with newline-separated // paragraphs) and identifies the profile it belongs to. type Source interface { - LinkKey() string + ReferenceKey() string ProfileServiceName() string ProfileInputName() string ProfileValue(author index.Author) string @@ -108,7 +108,7 @@ func (s *Service) RefreshMetadataBio(ctx context.Context, author index.Author, l } func (s *Service) authorLink(author index.Author) (string, bool) { - value := author.DataSourceLinks[s.source.LinkKey()] + value := author.DataSourceReferences[s.source.ReferenceKey()] id, err := s.source.NormalizeAuthorID(value) return value, err == nil && id != "" && id == value } @@ -177,8 +177,8 @@ func (s *Service) RefreshBio(ctx context.Context, author index.Author, language type storeFunc func(slug string, bio index.AuthorBio) error func (s *Service) bioStore(author index.Author, merge bool) storeFunc { - linkKey := s.source.LinkKey() - previousLink := author.DataSourceLinks[linkKey] + linkKey := s.source.ReferenceKey() + previousLink := author.DataSourceReferences[linkKey] return func(slug string, bio index.AuthorBio) error { if bio.Source != previousLink { return s.index.StoreCanonicalAuthorBio(slug, linkKey, previousLink, bio) @@ -191,9 +191,9 @@ func (s *Service) bioStore(author index.Author, merge bool) storeFunc { // An empty ID removes the profile and biography. func (s *Service) UpdateBio(ctx context.Context, author index.Author, id, language string) (string, string, error) { s = s.forLanguage(language) - linkKey := s.source.LinkKey() + linkKey := s.source.ReferenceKey() if id == "" { - if err := s.index.StoreCanonicalAuthorBio(author.Slug, linkKey, author.DataSourceLinks[linkKey], index.AuthorBio{}); err != nil { + if err := s.index.StoreCanonicalAuthorBio(author.Slug, linkKey, author.DataSourceReferences[linkKey], index.AuthorBio{}); err != nil { return "", "", fmt.Errorf("clearing %s author link: %w", s.ProfileServiceName(), err) } return "", "", nil @@ -206,11 +206,11 @@ func (s *Service) UpdateBio(ctx context.Context, author index.Author, id, langua return "", "", fmt.Errorf("invalid %s author ID %q", s.ProfileServiceName(), id) } save := s.bioStore(author, false) - author.DataSourceLinks = maps.Clone(author.DataSourceLinks) - if author.DataSourceLinks == nil { - author.DataSourceLinks = make(map[string]string) + author.DataSourceReferences = maps.Clone(author.DataSourceReferences) + if author.DataSourceReferences == nil { + author.DataSourceReferences = make(map[string]string) } - author.DataSourceLinks[linkKey] = id + author.DataSourceReferences[linkKey] = id author.Bio = index.AuthorBio{} ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), requestTimeout) defer cancel() diff --git a/internal/biography/service_test.go b/internal/biography/service_test.go index 312ac967..eb3fe9cf 100644 --- a/internal/biography/service_test.go +++ b/internal/biography/service_test.go @@ -28,11 +28,11 @@ type fakeSource struct { refreshes []bool } -func (*fakeSource) LinkKey() string { return "catalog" } +func (*fakeSource) ReferenceKey() string { return "catalog" } func (*fakeSource) ProfileServiceName() string { return "Example catalog" } func (*fakeSource) ProfileInputName() string { return "catalogID" } func (*fakeSource) ProfileValue(author index.Author) string { - return author.DataSourceLinks["catalog"] + return author.DataSourceReferences["catalog"] } func (*fakeSource) NormalizeAuthorID(value string) (string, error) { if value == "invalid" { @@ -114,7 +114,7 @@ func (f *fakeBioIndex) StoreAuthorBioForLink(_ string, linkKey, previousSource s func catalogAuthor(bio index.AuthorBio) index.Author { return index.Author{ Slug: "alice", Name: "Alice Example", - DataSourceLinks: map[string]string{"catalog": "alice"}, Bio: bio, + DataSourceReferences: map[string]string{"catalog": "alice"}, Bio: bio, } } @@ -423,7 +423,7 @@ func TestUpdateBio(t *testing.T) { source := &fakeSource{desc: englishBio, canonical: "primary"} idx := &fakeBioIndex{} provider := biography.NewService(source, &fakeTranslator{}, idx) - author := index.Author{Slug: "alice", DataSourceLinks: map[string]string{"catalog": previous}} + author := index.Author{Slug: "alice", DataSourceReferences: map[string]string{"catalog": previous}} text, _, err := provider.UpdateBio(context.Background(), author, "variant", "es") if err != nil || text != "[es] "+englishBio || idx.linkKey != "catalog" || idx.previousSource != previous || len(idx.replaced) != 1 || idx.replaced[0].Source != "primary" { @@ -432,7 +432,7 @@ func TestUpdateBio(t *testing.T) { if !slices.Equal(source.calls, []string{"variant"}) || !slices.Equal(source.refreshes, []bool{true}) { t.Fatalf("profile edits must bypass source caches, got %q, refresh=%v", source.calls, source.refreshes) } - if author.DataSourceLinks["catalog"] != previous { + if author.DataSourceReferences["catalog"] != previous { t.Fatal("updating must not mutate the caller's author") } }) diff --git a/internal/datasource/biblioreads/adapter_test.go b/internal/datasource/biblioreads/adapter_test.go index 075814a4..e6879a49 100644 --- a/internal/datasource/biblioreads/adapter_test.go +++ b/internal/datasource/biblioreads/adapter_test.go @@ -167,11 +167,11 @@ func TestEnrichStoresMatchingResult(t *testing.T) { t.Error("expected document to be marked as BiblioReads-enriched") } author, err := idx.Author("alice-borchardt", "") - if err != nil || author.DataSourceLinks["goodreads"] != wantAuthorURL { + if err != nil || author.DataSourceReferences["goodreads"] != wantAuthorURL { t.Fatalf("expected matching author URL stored, got %+v, %v", author, err) } other, err := idx.Author("second-author", "") - if err != nil || other.DataSourceLinks["goodreads"] != "" { + if err != nil || other.DataSourceReferences["goodreads"] != "" { t.Fatalf("unmatched coauthor must not receive the URL, got %+v, %v", other, err) } if want := []string{"La Reina Dragon Alice Borchardt", "La Reina Dragon"}; !slices.Equal(source.Queries(), want) { @@ -240,7 +240,7 @@ func TestEnrichStoresSecondAuthorURLAndPreservesItOnEdits(t *testing.T) { if err != nil { t.Fatal(err) } - stale.DataSourceLinks = map[string]string{"other": "https://example.org/second-author"} + stale.DataSourceReferences = map[string]string{"other": "https://example.org/second-author"} if err := idx.IndexAuthor(stale); err != nil { t.Fatal(err) } @@ -248,34 +248,34 @@ func TestEnrichStoresSecondAuthorURLAndPreservesItOnEdits(t *testing.T) { t.Fatal(err) } author, err := idx.Author("second-author", "") - if err != nil || author.DataSourceLinks["goodreads"] != "2" || - author.DataSourceLinks["other"] != "https://example.org/second-author" { + if err != nil || author.DataSourceReferences["goodreads"] != "2" || + author.DataSourceReferences["other"] != "https://example.org/second-author" { t.Fatalf("expected second author URL stored, got %+v, %v", author, err) } first, err := idx.Author("alice-borchardt", "") - if err != nil || first.DataSourceLinks["goodreads"] != "" { + if err != nil || first.DataSourceReferences["goodreads"] != "" { t.Fatalf("first author must not receive coauthor URL, got %+v, %v", first, err) } - stale.DataSourceID = "Q2" + stale.DataSourceReferences["wikidata"] = "Q2" stale.RetrievedOn = time.Now().UTC() - stale.DataSourceLinks["goodreads"] = "999.Stale" + stale.DataSourceReferences["goodreads"] = "999.Stale" if err := idx.IndexAuthor(stale); err != nil { t.Fatal(err) } - if stale.DataSourceLinks["goodreads"] != "999.Stale" { + if stale.DataSourceReferences["goodreads"] != "999.Stale" { t.Fatal("indexing an author mutated the caller's links") } author, err = idx.Author("second-author", "") - if err != nil || author.DataSourceLinks["goodreads"] != "2" || - author.DataSourceLinks["other"] != "https://example.org/second-author" || - author.DataSourceID != "Q2" || author.DocumentCount != 1 { + if err != nil || author.DataSourceReferences["goodreads"] != "2" || + author.DataSourceReferences["other"] != "https://example.org/second-author" || + author.DataSourceReferences["wikidata"] != "Q2" || author.DocumentCount != 1 { t.Fatalf("stale author edit lost URL or metadata: %+v, %v", author, err) } if _, err := idx.NewFile("second.pdf", []byte("")); err != nil { t.Fatal(err) } author, err = idx.Author("second-author", "") - if err != nil || author.DataSourceLinks["goodreads"] != "2" || author.DocumentCount != 2 { + if err != nil || author.DataSourceReferences["goodreads"] != "2" || author.DocumentCount != 2 { t.Fatalf("incrementing document count lost author URL: %+v, %v", author, err) } } @@ -292,7 +292,7 @@ func TestEnrichRejectsInvalidAuthorURL(t *testing.T) { t.Fatal(err) } author, err := idx.Author("alice-borchardt", "") - if err != nil || author.DataSourceLinks["goodreads"] != "" { + if err != nil || author.DataSourceReferences["goodreads"] != "" { t.Fatalf("invalid author paths must not be stored as author IDs: %+v, %v", author, err) } doc, err := idx.DocumentByID(testID) @@ -700,11 +700,11 @@ func TestBookMatchesKennedyMiddleName(t *testing.T) { t.Fatalf("expected persisted book match and rating, got %+v, %v", stored, err) } author, err := idx.Author("paul-kennedy", "") - if err != nil || author.DataSourceLinks["goodreads"] != "8390124.Paul_M_Kennedy" || author.Name != "Paul Kennedy" { + if err != nil || author.DataSourceReferences["goodreads"] != "8390124.Paul_M_Kennedy" || author.Name != "Paul Kennedy" { t.Fatalf("expected author URL with original name preserved, got %+v, %v", author, err) } other, err := idx.Author("another-writer", "") - if err != nil || other.DataSourceLinks["goodreads"] != "" { + if err != nil || other.DataSourceReferences["goodreads"] != "" { t.Fatalf("unmatched coauthor must not receive the URL, got %+v, %v", other, err) } if want := []string{title + " Paul Kennedy", title}; !slices.Equal(source.Queries(), want) { @@ -1228,7 +1228,7 @@ func TestMatchesTolkienOmnibusSearchResults(t *testing.T) { t.Fatalf("expected persisted omnibus match, got %+v", stored) } author, err := idx.Author("j-r-r-tolkien", "") - if err != nil || author.DataSourceLinks["goodreads"] != "656983.J_R_R_Tolkien" { + if err != nil || author.DataSourceReferences["goodreads"] != "656983.J_R_R_Tolkien" { t.Fatalf("expected author URL on author record, got %+v, %v", author, err) } if want := []string{title + " J. R. R. Tolkien", title}; !slices.Equal(source.Queries(), want) { diff --git a/internal/datasource/biblioreads/bio.go b/internal/datasource/biblioreads/bio.go index 7c68344f..0d533852 100644 --- a/internal/datasource/biblioreads/bio.go +++ b/internal/datasource/biblioreads/bio.go @@ -36,7 +36,7 @@ func NewBioSource(client AuthorClient) *BioSource { return &BioSource{client: client} } -func (*BioSource) LinkKey() string { return Source } +func (*BioSource) ReferenceKey() string { return Source } func (*BioSource) ProfileServiceName() string { return "Goodreads" @@ -47,7 +47,7 @@ func (*BioSource) ProfileInputName() string { } func (*BioSource) ProfileValue(author index.Author) string { - if id := author.DataSourceLinks[Source]; id != "" { + if id := author.DataSourceReferences[Source]; id != "" { return goodreadsBaseURL + goodreadsAuthorPrefix + id } return "" diff --git a/internal/datasource/biblioreads/reviews.go b/internal/datasource/biblioreads/reviews.go index b682ce9a..0319e2dd 100644 --- a/internal/datasource/biblioreads/reviews.go +++ b/internal/datasource/biblioreads/reviews.go @@ -43,7 +43,7 @@ func (b *ReviewProvider) Name() string { // AuthorLink returns the indexed author link without making a network request. func (b *ReviewProvider) AuthorLink(author index.Author, _ string) datasourcemodel.DataSourceLink { - id := author.DataSourceLinks[Source] + id := author.DataSourceReferences[Source] if !authorIDPattern.MatchString(id) { return goodreadsDataSourceLink("", goodreadsAuthorPrefix) } diff --git a/internal/datasource/biblioreads/reviews_test.go b/internal/datasource/biblioreads/reviews_test.go index fe19c404..6341e45b 100644 --- a/internal/datasource/biblioreads/reviews_test.go +++ b/internal/datasource/biblioreads/reviews_test.go @@ -21,7 +21,7 @@ func withBiblioReadsData(t *testing.T, document index.Document, data biblioreads func TestBiblioReadsDataSourceLinks(t *testing.T) { provider := biblioreads.NewReviewProvider(nil, nil) author := provider.AuthorLink(index.Author{ - DataSourceLinks: map[string]string{"goodreads": "123.Jane_Doe"}, + DataSourceReferences: map[string]string{"goodreads": "123.Jane_Doe"}, }, "en") if author.URL != "https://www.goodreads.com/author/show/123.Jane_Doe" || author.Source != "Goodreads" || author.Icon != "/images/goodreads.svg" || !author.IconInvertible { @@ -42,7 +42,7 @@ func TestBiblioReadsDataSourceLinks(t *testing.T) { {"goodreads": "123.Jane_Doe/"}, {"goodreads": "123?x=y"}, } { - if link := provider.AuthorLink(index.Author{DataSourceLinks: links}, "en"); link.URL != "" { + if link := provider.AuthorLink(index.Author{DataSourceReferences: links}, "en"); link.URL != "" { t.Errorf("unexpected Goodreads link for %v: %+v", links, link) } } diff --git a/internal/datasource/model/author.go b/internal/datasource/model/author.go index e02faffd..d3f31544 100644 --- a/internal/datasource/model/author.go +++ b/internal/datasource/model/author.go @@ -24,11 +24,10 @@ type Author interface { DateOfBirth() precisiondate.PrecisionDate DateOfDeath() precisiondate.PrecisionDate Image() string - // Links returns the current links owned by this datasource, including language-specific keys. + // Links returns source-owned profile IDs and URLs, including language-specific keys. Links() map[string]string // OwnsLink identifies entries replaced by a metadata refresh, even if absent from Links. OwnsLink(key string) bool - SourceID() string RetrievedOn() time.Time Pseudonyms() []string } diff --git a/internal/datasource/wikidata/author.go b/internal/datasource/wikidata/author.go index 19e1c511..cc9cffd1 100644 --- a/internal/datasource/wikidata/author.go +++ b/internal/datasource/wikidata/author.go @@ -83,7 +83,10 @@ func (a Author) DateOfDeath() precisiondate.PrecisionDate { } func (a Author) Links() map[string]string { - links := make(map[string]string, len(a.wikipediaLink)+1) + links := make(map[string]string, len(a.wikipediaLink)+2) + if a.wikidataEntityId != "" { + links["wikidata"] = a.wikidataEntityId + } if a.website != "" { links["website"] = a.website } @@ -96,7 +99,7 @@ func (a Author) Links() map[string]string { } func (a Author) OwnsLink(key string) bool { - return key == "website" || strings.HasPrefix(key, "wikipedia:") + return key == "wikidata" || key == "website" || strings.HasPrefix(key, "wikipedia:") } func (a Author) Image() string { @@ -111,10 +114,6 @@ func (a Author) Gender() float64 { return a.gender } -func (a Author) SourceID() string { - return a.wikidataEntityId -} - func (a Author) RetrievedOn() time.Time { return a.retrievedOn } diff --git a/internal/datasource/wikidata/bio.go b/internal/datasource/wikidata/bio.go index 67f6e60b..793b2db5 100644 --- a/internal/datasource/wikidata/bio.go +++ b/internal/datasource/wikidata/bio.go @@ -31,15 +31,15 @@ func (*BioSource) ForLanguage(language string) biography.Source { return &BioSource{language: language} } -func (s *BioSource) Language() string { return s.language } -func (s *BioSource) LinkKey() string { return "wikipedia:" + s.language } +func (s *BioSource) Language() string { return s.language } +func (s *BioSource) ReferenceKey() string { return "wikipedia:" + s.language } func (*BioSource) ProfileServiceName() string { return "Wikipedia" } func (*BioSource) ProfileInputName() string { return "wikipediaURL" } func (*BioSource) MetadataServiceName() string { return "Wikidata" } func (s *BioSource) ProfileValue(author index.Author) string { - return author.DataSourceLinks[s.LinkKey()] + return author.DataSourceReferences[s.ReferenceKey()] } // NormalizeAuthorID accepts article URLs, retaining their language and encoded title. diff --git a/internal/datasource/wikidata/bio_test.go b/internal/datasource/wikidata/bio_test.go index afad23f5..471c364a 100644 --- a/internal/datasource/wikidata/bio_test.go +++ b/internal/datasource/wikidata/bio_test.go @@ -43,7 +43,7 @@ func TestBioUsesKnownLinkInCurrentLanguage(t *testing.T) { idx := authorIndex(t) author := index.Author{ Slug: "example", Name: "Example", - DataSourceLinks: map[string]string{ + DataSourceReferences: map[string]string{ "wikipedia:en": "https://en.wikipedia.org/wiki/Example", "wikipedia:es": "https://es.wikipedia.org/wiki/Autor_%C3%B1", }, @@ -78,7 +78,7 @@ func TestBioUsesKnownLinkInCurrentLanguage(t *testing.T) { }}, nil }) provider := biography.NewService(NewBioSource(), nil, idx) - if value := provider.ProfileValueForLanguage(author, "es"); value != author.DataSourceLinks["wikipedia:es"] { + if value := provider.ProfileValueForLanguage(author, "es"); value != author.DataSourceReferences["wikipedia:es"] { t.Fatalf("profile input must show the current language's link: %q", value) } if _, _, pending := provider.StoredBio(author, "fr"); pending { @@ -96,7 +96,7 @@ func TestBioUsesKnownLinkInCurrentLanguage(t *testing.T) { if err != nil { t.Fatal(err) } - if stored.Bio.Source != author.DataSourceLinks["wikipedia:es"] || + if stored.Bio.Source != author.DataSourceReferences["wikipedia:es"] || stored.Bio.Language != "es" || stored.Bio.Text["es"] != want { t.Fatalf("must persist safe emphasis and paragraph breaks with the known language: %+v", stored.Bio) } diff --git a/internal/datasource/wikidata/service.go b/internal/datasource/wikidata/service.go index 81592e72..ec3b910f 100644 --- a/internal/datasource/wikidata/service.go +++ b/internal/datasource/wikidata/service.go @@ -44,6 +44,8 @@ type WikidataSource struct { wikidata wikidata } +func (WikidataSource) ReferenceKey() string { return "wikidata" } + func (WikidataSource) OwnsLink(key string) bool { return (Author{}).OwnsLink(key) } @@ -53,10 +55,11 @@ func (WikidataSource) ProfileServiceName() string { } func (WikidataSource) ProfileValue(author index.Author) string { - if author.DataSourceID == "" { + id := author.DataSourceReferences["wikidata"] + if id == "" { return "" } - return "https://www.wikidata.org/wiki/" + author.DataSourceID + return "https://www.wikidata.org/wiki/" + id } // NormalizeAuthorID accepts a Wikidata author ID or profile URL. @@ -90,7 +93,7 @@ func (WikidataSource) NormalizeAuthorID(value string) (string, error) { } func (WikidataSource) AuthorLink(author index.Author, language string) model.DataSourceLink { - url := author.DataSourceLinks["wikipedia:"+language] + url := author.DataSourceReferences["wikipedia:"+language] if url == "" { return model.DataSourceLink{} } diff --git a/internal/datasource/wikidata/service_test.go b/internal/datasource/wikidata/service_test.go index 8af7eaed..7fa6ecbd 100644 --- a/internal/datasource/wikidata/service_test.go +++ b/internal/datasource/wikidata/service_test.go @@ -50,7 +50,8 @@ func TestNormalizeAuthorID(t *testing.T) { func TestAuthorLinks(t *testing.T) { author := Author{ - website: "https://author.example", + wikidataEntityId: "Q1234", + website: "https://author.example", wikipediaLink: map[string]string{ "en": "https://en.wikipedia.org/wiki/Example", "es": "https://es.wikipedia.org/wiki/Ejemplo", @@ -58,6 +59,7 @@ func TestAuthorLinks(t *testing.T) { }, } want := map[string]string{ + "wikidata": "Q1234", "website": "https://author.example", "wikipedia:en": "https://en.wikipedia.org/wiki/Example", "wikipedia:es": "https://es.wikipedia.org/wiki/Ejemplo", @@ -66,12 +68,13 @@ func TestAuthorLinks(t *testing.T) { t.Fatalf("unexpected author links: %+v", got) } links := author.Links() + links["wikidata"] = "Q1" links["website"] = "https://changed.example" links["wikipedia:en"] = "https://changed.example/en" if got := author.Links(); !reflect.DeepEqual(got, want) { t.Fatalf("caller mutated author links: %+v", got) } - for _, key := range []string{"website", "wikipedia:en", "wikipedia:de"} { + for _, key := range []string{"wikidata", "website", "wikipedia:en", "wikipedia:de"} { if !author.OwnsLink(key) { t.Errorf("Wikidata should own %q, including missing language links", key) } @@ -89,7 +92,7 @@ func TestAuthorLinks(t *testing.T) { func TestWikipediaDataSourceLink(t *testing.T) { source := NewWikidataSource(Gowikidata{}) link := source.AuthorLink(index.Author{ - DataSourceLinks: map[string]string{ + DataSourceReferences: map[string]string{ "wikipedia:en": "https://en.wikipedia.org/wiki/Example", "wikipedia:es": "https://es.wikipedia.org/wiki/Ejemplo", }, @@ -186,7 +189,7 @@ func TestRetrieveAuthorsBatch(t *testing.T) { if len(authors) != 1 { t.Fatalf("expected 1 author from batch retrieve, got %d", len(authors)) } - if authors["miguel"].SourceID() != "Q1234" { - t.Fatalf("expected Q1234, got %q", authors["miguel"].SourceID()) + if authors["miguel"].Links()["wikidata"] != "Q1234" { + t.Fatalf("expected Q1234, got %q", authors["miguel"].Links()["wikidata"]) } } diff --git a/internal/index/author.go b/internal/index/author.go index b69d46c0..8d829057 100644 --- a/internal/index/author.go +++ b/internal/index/author.go @@ -11,21 +11,20 @@ import ( ) type Author struct { - Slug string - Name string - BirthName string - DataSourceID string - RetrievedOn time.Time - InstanceOf float64 - Description map[string]string - DateOfBirth precisiondate.PrecisionDate - DateOfDeath precisiondate.PrecisionDate - // DataSourceLinks contains references owned by external data sources. - DataSourceLinks map[string]string - DataSourceImage string - Gender float64 - Pseudonyms []string - DocumentCount uint64 + Slug string + Name string + BirthName string + RetrievedOn time.Time + InstanceOf float64 + Description map[string]string + DateOfBirth precisiondate.PrecisionDate + DateOfDeath precisiondate.PrecisionDate + // DataSourceReferences contains source-owned profile IDs and URLs. + DataSourceReferences map[string]string + DataSourceImage string + Gender float64 + Pseudonyms []string + DocumentCount uint64 // Bio is managed by StoreAuthorBio; IndexAuthor keeps the stored value. Bio AuthorBio // ownsRefreshedLink marks links replaced by a metadata refresh or explicit reset. @@ -44,7 +43,7 @@ type AuthorBio struct { } func (a Author) ClearMetadata(ownsLink func(string) bool) Author { - links := maps.Clone(a.DataSourceLinks) + links := maps.Clone(a.DataSourceReferences) for source := range links { if ownsLink(source) { delete(links, source) @@ -52,7 +51,7 @@ func (a Author) ClearMetadata(ownsLink func(string) bool) Author { } return Author{ Slug: a.Slug, Name: a.Name, DocumentCount: a.DocumentCount, - RetrievedOn: time.Now().UTC(), DataSourceLinks: links, Bio: a.Bio, + RetrievedOn: time.Now().UTC(), DataSourceReferences: links, Bio: a.Bio, ownsRefreshedLink: ownsLink, } } diff --git a/internal/index/author_bio_test.go b/internal/index/author_bio_test.go index 5bf4b0c3..060a7517 100644 --- a/internal/index/author_bio_test.go +++ b/internal/index/author_bio_test.go @@ -125,7 +125,7 @@ func TestStoreCanonicalAuthorBio(t *testing.T) { idx := newAuthorsTestIndex(t) const variant = "18647721.Plat_n" const linkKey = "external-profile" - author := index.Author{Slug: "platon", Name: "Platón", DataSourceLinks: map[string]string{ + author := index.Author{Slug: "platon", Name: "Platón", DataSourceReferences: map[string]string{ linkKey: variant, "website": "https://example.com", }} if err := idx.IndexAuthor(author); err != nil { @@ -139,7 +139,7 @@ func TestStoreCanonicalAuthorBio(t *testing.T) { if err != nil { t.Fatal(err) } - if stored.DataSourceLinks[linkKey] != bio.Source || stored.Bio.Source != bio.Source || !maps.Equal(stored.Bio.Text, bio.Text) || stored.DataSourceLinks["website"] != "https://example.com" || stored.Name != author.Name { + if stored.DataSourceReferences[linkKey] != bio.Source || stored.Bio.Source != bio.Source || !maps.Equal(stored.Bio.Text, bio.Text) || stored.DataSourceReferences["website"] != "https://example.com" || stored.Name != author.Name { t.Fatalf("canonical resolution must update only the profile link and bio: %+v", stored) } if err := idx.StoreCanonicalAuthorBio(author.Slug, linkKey, variant, index.AuthorBio{Source: "999"}); err == nil { @@ -152,7 +152,7 @@ func TestStoreCanonicalAuthorBio(t *testing.T) { t.Fatal("a stale biography must not restore a cleared source") } stored, err = idx.Author(author.Slug, "en") - if err != nil || stored.DataSourceLinks[linkKey] != "" || stored.DataSourceLinks["website"] != "https://example.com" || stored.Bio.Source != "" { + if err != nil || stored.DataSourceReferences[linkKey] != "" || stored.DataSourceReferences["website"] != "https://example.com" || stored.Bio.Source != "" { t.Fatalf("clearing the profile link must preserve other author data: %+v, %v", stored, err) } } diff --git a/internal/index/authors_enrich_test.go b/internal/index/authors_enrich_test.go index 51244e02..16696890 100644 --- a/internal/index/authors_enrich_test.go +++ b/internal/index/authors_enrich_test.go @@ -18,6 +18,7 @@ type mockAuthorDataSource struct { byName map[string]datasourcemodel.Author bySlug map[string]datasourcemodel.Author entityIDs map[string][]string + candidates map[string][]string calls int searchCalls int retrieveCalls int @@ -25,6 +26,8 @@ type mockAuthorDataSource struct { errName string } +func (*mockAuthorDataSource) ReferenceKey() string { return "example" } + func (m *mockAuthorDataSource) SearchAuthor(name string, _ []string) (datasourcemodel.Author, error) { m.calls++ m.searchCalls++ @@ -54,7 +57,7 @@ func (m *mockAuthorDataSource) SearchEntityIDs(name string) ([]string, error) { } } if author, ok := m.byName[name]; ok && author != nil { - return []string{author.SourceID()}, nil + return []string{author.Links()["example"]}, nil } return nil, nil } @@ -68,6 +71,7 @@ func (m *mockAuthorDataSource) RetrieveAuthor(_ []string, _ []string) (datasourc func (m *mockAuthorDataSource) RetrieveAuthors(candidates map[string][]string, _ []string, _ time.Duration, onResult func(string, datasourcemodel.Author) error) error { m.calls++ m.retrieveCalls++ + m.candidates = maps.Clone(candidates) for slug := range candidates { author := m.bySlug[slug] if err := onResult(slug, author); err != nil { @@ -90,11 +94,19 @@ func (a stubAuthor) Gender() float64 { return 0 } func (a stubAuthor) DateOfBirth() precisiondate.PrecisionDate { return precisiondate.PrecisionDate{} } func (a stubAuthor) DateOfDeath() precisiondate.PrecisionDate { return precisiondate.PrecisionDate{} } func (a stubAuthor) Image() string { return "" } -func (a stubAuthor) Links() map[string]string { return maps.Clone(a.links) } +func (a stubAuthor) Links() map[string]string { + links := maps.Clone(a.links) + if a.sourceID != "" { + if links == nil { + links = make(map[string]string) + } + links["example"] = a.sourceID + } + return links +} func (a stubAuthor) OwnsLink(key string) bool { - return a.linkPrefix != "" && strings.HasPrefix(key, a.linkPrefix) + return key == "example" || (a.linkPrefix != "" && strings.HasPrefix(key, a.linkPrefix)) } -func (a stubAuthor) SourceID() string { return a.sourceID } func (a stubAuthor) RetrievedOn() time.Time { return time.Now().UTC() } func (a stubAuthor) Pseudonyms() []string { return nil } @@ -107,7 +119,7 @@ func TestAuthorMetadataRefreshUpdatesLinks(t *testing.T) { idx := index.NewBleve(nil, authors, nil, "", nil, index.Config{}) author := index.Author{ Slug: "writer", Name: "Writer", - DataSourceLinks: map[string]string{ + DataSourceReferences: map[string]string{ "example:website": "https://old.example", "example:en": "https://en.example/Old", "example:es": "https://es.example/Old", @@ -129,7 +141,7 @@ func TestAuthorMetadataRefreshUpdatesLinks(t *testing.T) { if err != nil { t.Fatal(err) } - current.DataSourceLinks["another-provider"] = "https://another.example/writer" + current.DataSourceReferences["another-provider"] = "https://another.example/writer" if err := idx.IndexAuthor(current); err != nil { t.Fatal(err) } @@ -140,18 +152,18 @@ func TestAuthorMetadataRefreshUpdatesLinks(t *testing.T) { if err != nil { t.Fatal(err) } - if got.DataSourceLinks["example:website"] != source.links["example:website"] || - got.DataSourceLinks["example:en"] != source.links["example:en"] || - got.DataSourceLinks["example:es"] != "" { - t.Fatalf("metadata links were not refreshed: %+v", got.DataSourceLinks) + if got.DataSourceReferences["example:website"] != source.links["example:website"] || + got.DataSourceReferences["example:en"] != source.links["example:en"] || + got.DataSourceReferences["example:es"] != "" { + t.Fatalf("metadata links were not refreshed: %+v", got.DataSourceReferences) } - if got.DataSourceLinks["goodreads"] != "1.Writer" || - got.DataSourceLinks["catalog"] != "https://catalog.example/writer" || - got.DataSourceLinks["another-provider"] != "https://another.example/writer" { - t.Fatalf("metadata refresh lost independent provider links: %+v", got.DataSourceLinks) + if got.DataSourceReferences["goodreads"] != "1.Writer" || + got.DataSourceReferences["catalog"] != "https://catalog.example/writer" || + got.DataSourceReferences["another-provider"] != "https://another.example/writer" { + t.Fatalf("metadata refresh lost independent provider links: %+v", got.DataSourceReferences) } if source.links != nil { - author.DataSourceLinks["example:website"] = "https://caller.example" + author.DataSourceReferences["example:website"] = "https://caller.example" if source.links["example:website"] != "https://new.example" { t.Fatal("combining metadata retained a mutable datasource map") } @@ -167,8 +179,9 @@ func TestAuthorMetadataResetPreservesConcurrentProviderLinks(t *testing.T) { defer authors.Close() idx := index.NewBleve(nil, authors, nil, "", nil, index.Config{}) author := index.Author{ - Slug: "writer", Name: "Writer", DataSourceID: "Q1", DocumentCount: 3, - DataSourceLinks: map[string]string{ + Slug: "writer", Name: "Writer", DocumentCount: 3, + DataSourceReferences: map[string]string{ + "example": "Q1", "example:website": "https://old.example", "example:en": "https://en.example/Old", "catalog": "https://catalog.example/writer", }, @@ -177,14 +190,14 @@ func TestAuthorMetadataResetPreservesConcurrentProviderLinks(t *testing.T) { t.Fatal(err) } reset := author.ClearMetadata((stubAuthor{linkPrefix: "example:"}).OwnsLink) - if author.DataSourceLinks["example:website"] == "" { + if author.DataSourceReferences["example:website"] == "" { t.Fatal("reset must not mutate the caller's links") } current, err := idx.Author("writer", "en") if err != nil { t.Fatal(err) } - current.DataSourceLinks["goodreads"] = "1.Writer" + current.DataSourceReferences["goodreads"] = "1.Writer" if err := idx.IndexAuthor(current); err != nil { t.Fatal(err) } @@ -195,12 +208,12 @@ func TestAuthorMetadataResetPreservesConcurrentProviderLinks(t *testing.T) { if err != nil { t.Fatal(err) } - if stored.DataSourceLinks["example:website"] != "" || stored.DataSourceLinks["example:en"] != "" || - stored.DataSourceID != "" || stored.RetrievedOn.IsZero() { + if stored.DataSourceReferences["example:website"] != "" || stored.DataSourceReferences["example:en"] != "" || + stored.DataSourceReferences["example"] != "" || stored.RetrievedOn.IsZero() { t.Fatalf("reset must remove metadata association and owned links: %+v", stored) } - if stored.DataSourceLinks["catalog"] != "https://catalog.example/writer" || - stored.DataSourceLinks["goodreads"] != "1.Writer" || stored.DocumentCount != 3 { + if stored.DataSourceReferences["catalog"] != "https://catalog.example/writer" || + stored.DataSourceReferences["goodreads"] != "1.Writer" || stored.DocumentCount != 3 { t.Fatalf("reset must retain independent and concurrent author data: %+v", stored) } stale := index.Author{Slug: "writer", Name: "Writer"} @@ -211,8 +224,8 @@ func TestAuthorMetadataResetPreservesConcurrentProviderLinks(t *testing.T) { if err != nil { t.Fatal(err) } - if len(stored.DataSourceLinks) != 2 { - t.Fatalf("ordinary stale writes must preserve independent links: %+v", stored.DataSourceLinks) + if len(stored.DataSourceReferences) != 2 { + t.Fatalf("ordinary stale writes must preserve independent links: %+v", stored.DataSourceReferences) } } @@ -268,10 +281,16 @@ func TestEnrichAuthorsFromDataSource(t *testing.T) { if err := idx.IndexAuthor(index.Author{Slug: "done", Name: "Done Author", RetrievedOn: time.Now().UTC()}); err != nil { t.Fatal(err) } + if err := idx.IndexAuthor(index.Author{ + Slug: "known", Name: "Known Author", DataSourceReferences: map[string]string{"example": "Q2", "other": "unrelated"}, + }); err != nil { + t.Fatal(err) + } dataSource := &mockAuthorDataSource{ bySlug: map[string]datasourcemodel.Author{ "found": stubAuthor{sourceID: "Q1"}, + "known": stubAuthor{sourceID: "Q2"}, }, entityIDs: map[string][]string{ "Found Author": {"Q1"}, @@ -290,6 +309,9 @@ func TestEnrichAuthorsFromDataSource(t *testing.T) { if dataSource.retrieveCalls != 1 { t.Fatalf("expected 1 batched Wikidata entity fetch, got %d", dataSource.retrieveCalls) } + if ids := dataSource.candidates["known"]; len(ids) != 1 || ids[0] != "Q2" { + t.Fatalf("expected the known source reference reused without a name search, got %v", ids) + } if elapsed < 50*time.Millisecond { t.Fatalf("expected throttling between lookups, took %s", elapsed) } @@ -298,8 +320,12 @@ func TestEnrichAuthorsFromDataSource(t *testing.T) { if err != nil { t.Fatal(err) } - if found.DataSourceID != "Q1" { - t.Fatalf("expected enriched author Q1, got %q", found.DataSourceID) + if found.DataSourceReferences["example"] != "Q1" { + t.Fatalf("expected enriched author Q1, got %q", found.DataSourceReferences["example"]) + } + known, err := idx.Author("known", "en") + if err != nil || known.DataSourceReferences["example"] != "Q2" || known.DataSourceReferences["other"] != "unrelated" { + t.Fatalf("enrichment lost existing source references: %+v, %v", known, err) } missing, err := idx.Author("missing", "en") @@ -309,8 +335,8 @@ func TestEnrichAuthorsFromDataSource(t *testing.T) { if missing.RetrievedOn.IsZero() { t.Fatal("expected missing author to be marked as processed") } - if missing.DataSourceID != "" { - t.Fatalf("expected missing author to have no data source id, got %q", missing.DataSourceID) + if missing.DataSourceReferences["example"] != "" { + t.Fatalf("expected missing author to have no data source id, got %q", missing.DataSourceReferences["example"]) } remaining, err := idx.AuthorsWithoutInfo() diff --git a/internal/index/bleve.go b/internal/index/bleve.go index 6e0d43b5..f917f80f 100644 --- a/internal/index/bleve.go +++ b/internal/index/bleve.go @@ -35,7 +35,7 @@ const DocumentVersion = "v14" // AuthorVersion identifies the mapping used for indexing authors. Any changes in the mapping requires an increase // of version, to signal that a new index needs to be created. -const AuthorVersion = "3" +const AuthorVersion = "4" // Metadata fields var ( @@ -578,9 +578,8 @@ func CreateAuthorsMapping() mapping.IndexMapping { indexMapping.DefaultMapping.AddFieldMappingsAt("Name", simpleTextFieldMapping) indexMapping.DefaultMapping.AddFieldMappingsAt("BirthName", simpleTextFieldMapping) indexMapping.DefaultMapping.AddFieldMappingsAt("RetrievedOn", dateTimeFieldMapping) - indexMapping.DefaultMapping.AddFieldMappingsAt("DataSourceID", keywordFieldMappingNotIndexable) indexMapping.DefaultMapping.AddFieldMappingsAt("DataSourceImage", keywordFieldMappingNotIndexable) - indexMapping.DefaultMapping.AddFieldMappingsAt("DataSourceLinks", storedOnlyFieldMapping) + indexMapping.DefaultMapping.AddFieldMappingsAt("DataSourceReferences", storedOnlyFieldMapping) indexMapping.DefaultMapping.AddFieldMappingsAt("DateOfBirth.Date", numericFieldMapping) indexMapping.DefaultMapping.AddFieldMappingsAt("DateOfBirth.Precision", numericFieldMapping) indexMapping.DefaultMapping.AddFieldMappingsAt("DateOfDeath.Date", numericFieldMapping) diff --git a/internal/index/bleve_author_migrate.go b/internal/index/bleve_author_migrate.go index 4fdc6900..6a6ddf00 100644 --- a/internal/index/bleve_author_migrate.go +++ b/internal/index/bleve_author_migrate.go @@ -9,9 +9,10 @@ import ( "strings" "github.com/blevesearch/bleve/v2" + "github.com/blevesearch/bleve/v2/mapping" ) -// OpenAuthorsIndex upgrades version 2 without discarding stored author metadata. +// OpenAuthorsIndex upgrades older author mappings without discarding stored metadata. // The previous index is kept only until the migrated index opens successfully. func OpenAuthorsIndex(path string, batchSize int) (bleve.Index, error) { authors, err := bleve.Open(path) @@ -34,7 +35,15 @@ func OpenAuthorsIndex(path string, batchSize int) (bleve.Index, error) { if err != nil { return nil, errors.Join(err, authors.Close()) } - if string(version) == "2" { + legacyMapping := false + if string(version) == AuthorVersion { + m, ok := authors.Mapping().(*mapping.IndexMappingImpl) + if !ok || m.DefaultMapping == nil { + return nil, errors.Join(fmt.Errorf("unsupported authors index mapping"), authors.Close()) + } + _, legacyMapping = m.DefaultMapping.Properties["DataSourceLinks"] + } + if string(version) == "2" || string(version) == "3" || legacyMapping { upgraded, err := migrateAuthorsIndex(authors, path, batchSize) if err != nil { return nil, errors.Join(err, authors.Close()) @@ -54,6 +63,7 @@ func migrateAuthorsIndex(authors bleve.Index, path string, batchSize int) (bleve if batchSize <= 0 { return nil, fmt.Errorf("authors migration batch size must be positive") } + // Retain the historical path for recovery of interrupted version 2 upgrades. backup := path + ".v2-backup" if _, err := os.Stat(backup); err == nil { return nil, fmt.Errorf("authors migration backup already exists: %s", backup) @@ -106,7 +116,18 @@ func copyAuthors(source, destination bleve.Index, batchSize int) error { } batch := destination.NewBatch() for _, hit := range result.Hits { + if _, exists := hit.Fields["DataSourceReferences"]; !exists { + if legacyLinks, ok := hit.Fields["DataSourceLinks"]; ok { + hit.Fields["DataSourceReferences"] = legacyLinks + } + } author := hydrateAuthor(hit) + if legacyID, ok := hit.Fields["DataSourceID"].(string); ok && legacyID != "" && author.DataSourceReferences["wikidata"] == "" { + if author.DataSourceReferences == nil { + author.DataSourceReferences = make(map[string]string) + } + author.DataSourceReferences["wikidata"] = legacyID + } for field, value := range hit.Fields { source := "" switch { @@ -116,11 +137,11 @@ func copyAuthors(source, destination bleve.Index, batchSize int) error { source = "wikipedia:" + strings.TrimPrefix(field, "WikipediaLink.") } if link, ok := value.(string); source != "" && ok && link != "" { - if author.DataSourceLinks == nil { - author.DataSourceLinks = make(map[string]string) + if author.DataSourceReferences == nil { + author.DataSourceReferences = make(map[string]string) } - if author.DataSourceLinks[source] == "" { - author.DataSourceLinks[source] = link + if author.DataSourceReferences[source] == "" { + author.DataSourceReferences[source] = link } } } diff --git a/internal/index/bleve_author_migrate_test.go b/internal/index/bleve_author_migrate_test.go index 7e964cbf..769d0987 100644 --- a/internal/index/bleve_author_migrate_test.go +++ b/internal/index/bleve_author_migrate_test.go @@ -1,6 +1,7 @@ package index import ( + "encoding/json" "os" "path/filepath" "reflect" @@ -17,7 +18,8 @@ import ( func legacyAuthorsIndex(t *testing.T, path string) bleve.Index { t.Helper() m := CreateAuthorsMapping().(*mapping.IndexMappingImpl) - delete(m.DefaultMapping.Properties, "DataSourceLinks") + delete(m.DefaultMapping.Properties, "DataSourceReferences") + m.DefaultMapping.AddFieldMappingsAt("DataSourceID", bleve.NewKeywordFieldMapping()) idx, err := bleve.New(path, m) if err != nil { t.Fatal(err) @@ -34,8 +36,9 @@ func TestOpenAuthorsIndexMigratesStoredMetadata(t *testing.T) { retrieved := time.Date(2026, 10, 28, 12, 0, 0, 0, time.UTC) want := Author{ Slug: "alice-borchardt", Name: "Alice Borchardt", BirthName: "Alice O'Brien", - DataSourceID: "Q1", RetrievedOn: retrieved, - DataSourceLinks: map[string]string{ + RetrievedOn: retrieved, + DataSourceReferences: map[string]string{ + "wikidata": "Q1", "wikipedia:en": "https://en.wikipedia.org/wiki/Alice_Borchardt", "wikipedia:es": "https://es.wikipedia.org/wiki/Alice_Borchardt", "website": "https://example.org", @@ -47,12 +50,15 @@ func TestOpenAuthorsIndexMigratesStoredMetadata(t *testing.T) { Pseudonyms: []string{"Alice", "A. Borchardt"}, DocumentCount: 7, } for _, author := range []Author{want, {Slug: "other", Name: "Other", RetrievedOn: retrieved}, {Slug: "third", Name: "Third", RetrievedOn: retrieved}} { + stored := author + stored.DataSourceReferences = nil if err := legacy.Index(author.Slug, struct { Author + DataSourceID string Website string WikipediaLink map[string]string - }{author, author.DataSourceLinks["website"], map[string]string{ - "en": author.DataSourceLinks["wikipedia:en"], "es": author.DataSourceLinks["wikipedia:es"], + }{stored, author.DataSourceReferences["wikidata"], author.DataSourceReferences["website"], map[string]string{ + "en": author.DataSourceReferences["wikipedia:en"], "es": author.DataSourceReferences["wikipedia:es"], }}); err != nil { t.Fatal(err) } @@ -90,7 +96,7 @@ func TestOpenAuthorsIndexMigratesStoredMetadata(t *testing.T) { t.Fatalf("expected original index removed after successful migration, got %v", err) } - got.DataSourceLinks["goodreads"] = "1.Writer" + got.DataSourceReferences["goodreads"] = "1.Writer" if err := idx.IndexAuthor(got); err != nil { t.Fatal(err) } @@ -108,7 +114,7 @@ func TestOpenAuthorsIndexMigratesStoredMetadata(t *testing.T) { if err != nil || len(result.Hits) != 1 { t.Fatalf("reading reopened author: %v", err) } - want.DataSourceLinks["goodreads"] = "1.Writer" + want.DataSourceReferences["goodreads"] = "1.Writer" if got := hydrateAuthor(result.Hits[0]); !reflect.DeepEqual(got, want) { t.Fatalf("migrated mapping or URL did not survive reopening: %#v", got) } @@ -117,7 +123,7 @@ func TestOpenAuthorsIndexMigratesStoredMetadata(t *testing.T) { func TestOpenAuthorsIndexRecoversInterruptedSwap(t *testing.T) { path := filepath.Join(t.TempDir(), "authors_index") legacy := legacyAuthorsIndex(t, path+".v2-backup") - if err := legacy.Index("saved", Author{Slug: "saved", Name: "Saved Author", DataSourceID: "Q1"}); err != nil { + if err := legacy.Index("saved", map[string]string{"Slug": "saved", "Name": "Saved Author", "DataSourceID": "Q1"}); err != nil { t.Fatal(err) } if err := legacy.Close(); err != nil { @@ -133,6 +139,155 @@ func TestOpenAuthorsIndexRecoversInterruptedSwap(t *testing.T) { } } +func TestOpenAuthorsIndexMigratesVersion3SourceID(t *testing.T) { + for _, referenceID := range []string{"", "Q2"} { + t.Run("reference="+referenceID, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "authors_index") + m := oldReferenceAuthorsMapping() + m.DefaultMapping.AddFieldMappingsAt("DataSourceID", bleve.NewKeywordFieldMapping()) + legacy, err := bleve.New(path, m) + if err != nil { + t.Fatal(err) + } + want := Author{ + Slug: "writer", Name: "Writer", RetrievedOn: time.Now().UTC().Truncate(time.Second), + Description: map[string]string{"en": "Writer", "es": "Escritora"}, DocumentCount: 7, + Pseudonyms: []string{"Writer Alias"}, + DataSourceReferences: map[string]string{ + "goodreads": "1.Writer", "wikipedia:es": "https://es.wikipedia.org/wiki/Writer", + }, + Bio: AuthorBio{Source: "https://es.wikipedia.org/wiki/Writer", Language: "es", + Text: map[string]string{"es": "Biografia", "en": "Biography"}}, + } + if referenceID != "" { + want.DataSourceReferences["wikidata"] = referenceID + } + links, err := json.Marshal(want.DataSourceReferences) + if err != nil { + t.Fatal(err) + } + stored := want + stored.DataSourceReferences = nil + if err := legacy.Index(want.Slug, struct { + Author + DataSourceID string + DataSourceLinks string + }{stored, "Q1", string(links)}); err != nil { + t.Fatal(err) + } + if err := legacy.SetInternal(internalVersion, []byte("3")); err != nil { + t.Fatal(err) + } + if err := legacy.Close(); err != nil { + t.Fatal(err) + } + upgraded, err := OpenAuthorsIndex(path, 1) + if err != nil { + t.Fatal(err) + } + if err := upgraded.Close(); err != nil { + t.Fatal(err) + } + reopened, err := OpenAuthorsIndex(path, 1) + if err != nil { + t.Fatal(err) + } + defer reopened.Close() + req := bleve.NewSearchRequest(bleve.NewDocIDQuery([]string{want.Slug})) + req.Fields = []string{"*"} + result, err := reopened.Search(req) + if err != nil || len(result.Hits) != 1 { + t.Fatalf("reading migrated author: %v", err) + } + if _, found := result.Hits[0].Fields["DataSourceID"]; found { + t.Fatal("migration retained the standalone source ID") + } + if _, found := result.Hits[0].Fields["DataSourceLinks"]; found { + t.Fatal("migration retained the old reference field") + } + if _, found := result.Hits[0].Fields["DataSourceReferences"]; !found { + t.Fatal("migration did not store the renamed reference field") + } + if referenceID == "" { + want.DataSourceReferences["wikidata"] = "Q1" + } + if got := hydrateAuthor(result.Hits[0]); !reflect.DeepEqual(got, want) { + t.Fatalf("migration changed author metadata or references:\ngot: %#v\nwant: %#v", got, want) + } + }) + } +} + +func oldReferenceAuthorsMapping() *mapping.IndexMappingImpl { + m := CreateAuthorsMapping().(*mapping.IndexMappingImpl) + m.DefaultMapping.Properties["DataSourceLinks"] = m.DefaultMapping.Properties["DataSourceReferences"] + delete(m.DefaultMapping.Properties, "DataSourceReferences") + return m +} + +func TestOpenAuthorsIndexMigratesDevelopmentVersion4(t *testing.T) { + path := filepath.Join(t.TempDir(), "authors_index") + authors, err := bleve.New(path, oldReferenceAuthorsMapping()) + if err != nil { + t.Fatal(err) + } + if err := authors.SetInternal(internalVersion, []byte(AuthorVersion)); err != nil { + t.Fatal(err) + } + if err := authors.Index("writer", struct { + Author + DataSourceLinks string + }{ + Author: Author{Slug: "writer", Name: "Writer", DocumentCount: 3, + Bio: AuthorBio{Source: "1.Writer", Language: "en", Text: map[string]string{"en": "Biography"}}}, + DataSourceLinks: `{"wikidata":"Q1","website":"https://example.org"}`, + }); err != nil { + t.Fatal(err) + } + if err := authors.Close(); err != nil { + t.Fatal(err) + } + authors, err = OpenAuthorsIndex(path, 1) + if err != nil { + t.Fatal(err) + } + idx := NewBleve(nil, authors, nil, "", nil, Config{}) + author, err := idx.Author("writer", "") + if err != nil || author.DataSourceReferences["wikidata"] != "Q1" || author.DataSourceReferences["website"] != "https://example.org" || + author.DocumentCount != 3 || author.Bio.Text["en"] != "Biography" { + t.Fatalf("existing references lost: %+v, %v", author, err) + } + author.DataSourceReferences["goodreads"] = "1.Writer" + if err := idx.IndexAuthor(author); err != nil { + t.Fatal(err) + } + if err := authors.Close(); err != nil { + t.Fatal(err) + } + authors, err = OpenAuthorsIndex(path, 0) + if err != nil { + t.Fatal(err) + } + defer authors.Close() + req := bleve.NewSearchRequest(bleve.NewDocIDQuery([]string{"writer"})) + req.Fields = []string{"*"} + result, err := authors.Search(req) + if err != nil || len(result.Hits) != 1 { + t.Fatalf("reading saved author: %v", err) + } + fields := result.Hits[0].Fields + if _, ok := fields["DataSourceReferences"].(string); !ok { + t.Fatal("references must use the renamed stored field") + } + if _, ok := fields["DataSourceLinks"]; ok { + t.Fatal("migration retained the old reference field") + } + got := hydrateAuthor(result.Hits[0]) + if !reflect.DeepEqual(got.DataSourceReferences, author.DataSourceReferences) { + t.Fatalf("references did not survive reopening: %+v", got.DataSourceReferences) + } +} + func TestOpenAuthorsIndexRemovesPreviouslyRetainedBackup(t *testing.T) { path := filepath.Join(t.TempDir(), "authors_index") backup := legacyAuthorsIndex(t, path+".v2-backup") @@ -140,7 +295,7 @@ func TestOpenAuthorsIndexRemovesPreviouslyRetainedBackup(t *testing.T) { t.Fatal(err) } current := CreateAuthorsIndex(path) - if err := current.Index("saved", Author{Slug: "saved", Name: "Saved Author", DataSourceID: "Q1"}); err != nil { + if err := indexAuthor(current, "saved", Author{Slug: "saved", Name: "Saved Author", DataSourceReferences: map[string]string{"wikidata": "Q1"}}); err != nil { t.Fatal(err) } if err := current.Close(); err != nil { @@ -162,7 +317,7 @@ func TestOpenAuthorsIndexRemovesPreviouslyRetainedBackup(t *testing.T) { func TestOpenAuthorsIndexMigrationFailurePreservesOriginal(t *testing.T) { path := filepath.Join(t.TempDir(), "authors_index") legacy := legacyAuthorsIndex(t, path) - if err := legacy.Index("saved", Author{Slug: "saved", Name: "Saved Author", DataSourceID: "Q1"}); err != nil { + if err := legacy.Index("saved", map[string]string{"Slug": "saved", "Name": "Saved Author", "DataSourceID": "Q1"}); err != nil { t.Fatal(err) } @@ -188,7 +343,8 @@ func TestOpenAuthorsIndexMigrationFailurePreservesOriginal(t *testing.T) { func TestOpenAuthorsIndexMigratesLegacyAuthorLinks(t *testing.T) { path := filepath.Join(t.TempDir(), "authors_index") m := CreateAuthorsMapping().(*mapping.IndexMappingImpl) - delete(m.DefaultMapping.Properties, "DataSourceLinks") + delete(m.DefaultMapping.Properties, "DataSourceReferences") + m.DefaultMapping.AddFieldMappingsAt("DataSourceID", bleve.NewKeywordFieldMapping()) legacyURL := bleve.NewKeywordFieldMapping() legacyURL.Index = false legacyURL.IncludeInAll = false @@ -222,13 +378,13 @@ func TestOpenAuthorsIndexMigratesLegacyAuthorLinks(t *testing.T) { } idx := NewBleve(nil, upgraded, nil, "", nil, Config{}) author, err := idx.Author("alice", "") - if err != nil || author.DataSourceID != "Q1" || author.DocumentCount != 7 || - author.DataSourceLinks["website"] != "https://example.org" || - author.DataSourceLinks["wikipedia:en"] != "https://en.wikipedia.org/wiki/Alice" || - author.DataSourceLinks["wikipedia:es"] != "https://es.wikipedia.org/wiki/Alice" { + if err != nil || author.DataSourceReferences["wikidata"] != "Q1" || author.DocumentCount != 7 || + author.DataSourceReferences["website"] != "https://example.org" || + author.DataSourceReferences["wikipedia:en"] != "https://en.wikipedia.org/wiki/Alice" || + author.DataSourceReferences["wikipedia:es"] != "https://es.wikipedia.org/wiki/Alice" { t.Fatalf("migration lost legacy links or metadata: %+v, %v", author, err) } - author.DataSourceLinks["other"] = "https://example.org/alice" + author.DataSourceReferences["other"] = "https://example.org/alice" if err := idx.IndexAuthor(author); err != nil { t.Fatal(err) } diff --git a/internal/index/bleve_author_read.go b/internal/index/bleve_author_read.go index 7eb82733..ac788756 100644 --- a/internal/index/bleve_author_read.go +++ b/internal/index/bleve_author_read.go @@ -108,13 +108,6 @@ func hydrateAuthorFromFields(fields map[string]any, docID string) Author { } } - dataSourceID := "" - if val, ok := fields["DataSourceID"]; ok && val != nil { - if str, ok := val.(string); ok { - dataSourceID = str - } - } - dataSourceImage := "" if val, ok := fields["DataSourceImage"]; ok && val != nil { if str, ok := val.(string); ok { @@ -147,7 +140,6 @@ func hydrateAuthorFromFields(fields map[string]any, docID string) Author { Name: name, BirthName: birthName, Slug: slug, - DataSourceID: dataSourceID, RetrievedOn: retrievedOn, InstanceOf: instanceOf, Description: make(map[string]string), @@ -158,9 +150,9 @@ func hydrateAuthorFromFields(fields map[string]any, docID string) Author { Pseudonyms: slicer(fields["Pseudonyms"]), DocumentCount: documentCount, } - if links, ok := fields["DataSourceLinks"].(string); ok { - if err := json.Unmarshal([]byte(links), &author.DataSourceLinks); err != nil { - log.Printf("Error reading data source links for author %s: %s", docID, err) + if references, ok := fields["DataSourceReferences"].(string); ok { + if err := json.Unmarshal([]byte(references), &author.DataSourceReferences); err != nil { + log.Printf("Error reading data source references for author %s: %s", docID, err) } } author.Bio.Source, _ = fields["Bio.Source"].(string) diff --git a/internal/index/bleve_author_write.go b/internal/index/bleve_author_write.go index 8e6f0c75..b7733045 100644 --- a/internal/index/bleve_author_write.go +++ b/internal/index/bleve_author_write.go @@ -11,16 +11,16 @@ import ( datasourcemodel "github.com/svera/coreander/v5/internal/datasource/model" ) -// indexAuthor stores links as one stored-only field so new sources need no mapping changes. +// indexAuthor stores references as one stored-only field so new sources need no mapping changes. func indexAuthor(destination interface{ Index(string, any) error }, id string, author Author) error { - links, err := json.Marshal(author.DataSourceLinks) + links, err := json.Marshal(author.DataSourceReferences) if err != nil { return err } - author.DataSourceLinks = nil + author.DataSourceReferences = nil return destination.Index(id, struct { Author - DataSourceLinks string + DataSourceReferences string }{author, string(links)}) } @@ -173,18 +173,18 @@ func (b *BleveIndexer) IndexAuthor(author Author) error { return err } // Link enrichment runs independently of metadata enrichment and UI edits. - links := maps.Clone(author.DataSourceLinks) - if len(current.DataSourceLinks) > 0 { + links := maps.Clone(author.DataSourceReferences) + if len(current.DataSourceReferences) > 0 { if links == nil { links = make(map[string]string) } - for source, link := range current.DataSourceLinks { + for source, link := range current.DataSourceReferences { if author.ownsRefreshedLink == nil || !author.ownsRefreshedLink(source) { links[source] = link } } } - author.DataSourceLinks = links + author.DataSourceReferences = links if current.Slug != "" { author.Bio = current.Bio } @@ -215,16 +215,16 @@ func (b *BleveIndexer) StoreCanonicalAuthorBio(slug, linkKey, previousLink strin if err != nil || author.Slug == "" { return err } - if author.DataSourceLinks[linkKey] != previousLink { + if author.DataSourceReferences[linkKey] != previousLink { return fmt.Errorf("data source link changed while resolving primary profile for %s", slug) } - if author.DataSourceLinks == nil { - author.DataSourceLinks = make(map[string]string) + if author.DataSourceReferences == nil { + author.DataSourceReferences = make(map[string]string) } if bio.Source == "" { - delete(author.DataSourceLinks, linkKey) + delete(author.DataSourceReferences, linkKey) } else { - author.DataSourceLinks[linkKey] = bio.Source + author.DataSourceReferences[linkKey] = bio.Source } author.Bio = bio return indexAuthor(b.authorsIdx, slug, author) @@ -246,7 +246,7 @@ func (b *BleveIndexer) storeAuthorBioChecked(slug, linkKey string, bio AuthorBio if err != nil || author.Slug == "" { return err } - if expectedLink != nil && author.DataSourceLinks[linkKey] != *expectedLink { + if expectedLink != nil && author.DataSourceReferences[linkKey] != *expectedLink { return fmt.Errorf("data source link changed while retrieving biography for %s", slug) } if merge && author.Bio.Source == bio.Source && author.Bio.Language == bio.Language { @@ -290,6 +290,7 @@ const ( // AuthorDataSource retrieves author metadata from an external source. type AuthorDataSource interface { + ReferenceKey() string SearchAuthor(name string, languages []string) (datasourcemodel.Author, error) SearchEntityIDs(name string) ([]string, error) RetrieveAuthor(ids []string, languages []string) (datasourcemodel.Author, error) @@ -298,17 +299,16 @@ type AuthorDataSource interface { // CombineWithDataSource merges external author metadata into an indexed author. func CombineWithDataSource(author *Author, authorDataSource datasourcemodel.Author, supportedLanguages []string) { - author.DataSourceID = authorDataSource.SourceID() author.BirthName = authorDataSource.BirthName() author.RetrievedOn = authorDataSource.RetrievedOn() - author.DataSourceLinks = maps.Clone(author.DataSourceLinks) + author.DataSourceReferences = maps.Clone(author.DataSourceReferences) author.ownsRefreshedLink = authorDataSource.OwnsLink - if author.DataSourceLinks == nil { - author.DataSourceLinks = make(map[string]string) + if author.DataSourceReferences == nil { + author.DataSourceReferences = make(map[string]string) } - for source := range author.DataSourceLinks { + for source := range author.DataSourceReferences { if authorDataSource.OwnsLink(source) { - delete(author.DataSourceLinks, source) + delete(author.DataSourceReferences, source) } } author.InstanceOf = authorDataSource.InstanceOf() @@ -317,7 +317,7 @@ func CombineWithDataSource(author *Author, authorDataSource datasourcemodel.Auth author.DateOfDeath = authorDataSource.DateOfDeath() for key, link := range authorDataSource.Links() { if link != "" { - author.DataSourceLinks[key] = link + author.DataSourceReferences[key] = link } } author.DataSourceImage = authorDataSource.Image() @@ -364,8 +364,8 @@ func (b *BleveIndexer) EnrichAuthorsFromDataSource(dataSource AuthorDataSource, searchIndex := 0 for _, author := range authors { authorsBySlug[author.Slug] = author - if author.DataSourceID != "" { - candidates[author.Slug] = []string{author.DataSourceID} + if id := author.DataSourceReferences[dataSource.ReferenceKey()]; id != "" { + candidates[author.Slug] = []string{id} b.recordAuthorEnrichmentProgress() continue } diff --git a/internal/index/bleve_document_data_sources.go b/internal/index/bleve_document_data_sources.go index 4912b048..0a3d4982 100644 --- a/internal/index/bleve_document_data_sources.go +++ b/internal/index/bleve_document_data_sources.go @@ -77,13 +77,13 @@ func (b *BleveIndexer) storeAuthorLinkLocked(link AuthorLink) error { author.DocumentCount += result.Total } } - if author.DataSourceLinks[link.Source] != "" { + if author.DataSourceReferences[link.Source] != "" { return nil } - if author.DataSourceLinks == nil { - author.DataSourceLinks = make(map[string]string) + if author.DataSourceReferences == nil { + author.DataSourceReferences = make(map[string]string) } - author.DataSourceLinks[link.Source] = link.Value + author.DataSourceReferences[link.Source] = link.Value return indexAuthor(b.authorsIdx, link.Slug, author) } diff --git a/internal/index/data_source_fields_test.go b/internal/index/data_source_fields_test.go index 07dd7083..f0fc0479 100644 --- a/internal/index/data_source_fields_test.go +++ b/internal/index/data_source_fields_test.go @@ -198,7 +198,7 @@ func TestDataSourceFieldsAreStoredButNotSearchable(t *testing.T) { queries := map[string]bleve.SearchRequest{ "provider data field term": *bleve.NewSearchRequest(fieldTermQuery("DataSources", bookURL)), "provider URL field term": *bleve.NewSearchRequest(fieldTermQuery("DataSources.dummy.url", bookURL)), - "author URL field term": *bleve.NewSearchRequest(fieldTermQuery("DataSourceLinks.dummy", authorURL)), + "author URL field term": *bleve.NewSearchRequest(fieldTermQuery("DataSourceReferences.dummy", authorURL)), "resource ID field term": *bleve.NewSearchRequest(fieldTermQuery("DataSources.dummy.referenceId", referenceID)), "legacy ID numeric field": *bleve.NewSearchRequest(providerRecordIDQuery(recordID)), "_all match": *bleve.NewSearchRequest(bleve.NewMatchQuery("zyxwvbook")), @@ -275,7 +275,7 @@ func providerRecordIDQuery(id int) *query.NumericRangeQuery { return q } -func TestAuthorDataSourceLinksAreStoredButNotSearchable(t *testing.T) { +func TestAuthorDataSourceReferencesAreStoredButNotSearchable(t *testing.T) { authors, err := bleve.NewMemOnly(index.CreateAuthorsMapping()) if err != nil { t.Fatal(err) @@ -287,23 +287,23 @@ func TestAuthorDataSourceLinksAreStoredButNotSearchable(t *testing.T) { "dummy": authorURL, "other": "https://example.org/Zyxwv_Author", } - if err := idx.IndexAuthor(index.Author{Slug: "alice", Name: "Example Writer", DataSourceLinks: links}); err != nil { + if err := idx.IndexAuthor(index.Author{Slug: "alice", Name: "Example Writer", DataSourceReferences: links}); err != nil { t.Fatal(err) } author, err := idx.Author("alice", "") if err != nil { t.Fatal(err) } - if !maps.Equal(author.DataSourceLinks, links) { - t.Fatalf("expected stored author links, got %+v", author.DataSourceLinks) + if !maps.Equal(author.DataSourceReferences, links) { + t.Fatalf("expected stored author links, got %+v", author.DataSourceReferences) } for _, q := range []query.Query{ - fieldTermQuery("DataSourceLinks", authorURL), - fieldTermQuery("DataSourceLinks.dummy", authorURL), - fieldTermQuery("DataSourceLinks.other", links["other"]), + fieldTermQuery("DataSourceReferences", authorURL), + fieldTermQuery("DataSourceReferences.dummy", authorURL), + fieldTermQuery("DataSourceReferences.other", links["other"]), bleve.NewTermQuery(authorURL), bleve.NewMatchQuery("Zyxwv_Author"), - bleve.NewQueryStringQuery(`DataSourceLinks:"` + authorURL + `"`), + bleve.NewQueryStringQuery(`DataSourceReferences:"` + authorURL + `"`), } { result, err := authors.Search(bleve.NewSearchRequest(q)) if err != nil { diff --git a/internal/index/document_data_sources_test.go b/internal/index/document_data_sources_test.go index 3c79047d..2ef73111 100644 --- a/internal/index/document_data_sources_test.go +++ b/internal/index/document_data_sources_test.go @@ -296,8 +296,8 @@ func TestUpdateDocumentStoresAuthorLinksFirstWins(t *testing.T) { } if existing { if err := idx.IndexAuthor(Author{ - Name: "Existing Writer", Slug: "writer", DocumentCount: 42, DataSourceID: "external-id", - DataSourceLinks: map[string]string{"other": "other-reference"}, + Name: "Existing Writer", Slug: "writer", DocumentCount: 42, + DataSourceReferences: map[string]string{"wikidata": "external-id", "other": "other-reference"}, }); err != nil { t.Fatal(err) } @@ -312,12 +312,12 @@ func TestUpdateDocumentStoresAuthorLinksFirstWins(t *testing.T) { } } author, err := idx.Author("writer", "") - if err != nil || author.DataSourceLinks["dummy"] != "first-reference" { + if err != nil || author.DataSourceReferences["dummy"] != "first-reference" { t.Fatalf("first author link lost: %+v, %v", author, err) } if existing { if author.Name != "Existing Writer" || author.DocumentCount != 42 || - author.DataSourceID != "external-id" || author.DataSourceLinks["other"] != "other-reference" { + author.DataSourceReferences["wikidata"] != "external-id" || author.DataSourceReferences["other"] != "other-reference" { t.Fatalf("existing author metadata changed: %+v", author) } } else if author.Name != "Writer" || author.DocumentCount != 3 { diff --git a/internal/index/rebuild_authors_test.go b/internal/index/rebuild_authors_test.go index 76a8c08b..901464b8 100644 --- a/internal/index/rebuild_authors_test.go +++ b/internal/index/rebuild_authors_test.go @@ -63,7 +63,7 @@ func TestRebuildAuthorsFromDocuments(t *testing.T) { if author.DocumentCount != 1 { t.Fatalf("expected DocumentCount=1 for George Orwell, got %d", author.DocumentCount) } - author.DataSourceLinks = map[string]string{ + author.DataSourceReferences = map[string]string{ "goodreads": "3706.George_Orwell", "other": "https://example.org/authors/orwell", } @@ -74,8 +74,8 @@ func TestRebuildAuthorsFromDocuments(t *testing.T) { t.Fatal(err) } author, err = idx.Author("george-orwell", "en") - if err != nil || author.DataSourceLinks["goodreads"] != "3706.George_Orwell" || - author.DataSourceLinks["other"] != "https://example.org/authors/orwell" { + if err != nil || author.DataSourceReferences["goodreads"] != "3706.George_Orwell" || + author.DataSourceReferences["other"] != "https://example.org/authors/orwell" { t.Fatalf("expected existing author URL preserved during rebuild, got %+v, %v", author, err) } diff --git a/internal/webserver/author_bio_test.go b/internal/webserver/author_bio_test.go index 19d6e376..65272ed5 100644 --- a/internal/webserver/author_bio_test.go +++ b/internal/webserver/author_bio_test.go @@ -94,7 +94,7 @@ func seedBioTestAuthor(t *testing.T, idx *index.BleveIndexer, links map[string]s if err != nil { t.Fatal(err) } - author.DataSourceLinks = links + author.DataSourceReferences = links author.RetrievedOn = time.Now() if err := idx.IndexAuthor(author); err != nil { t.Fatal(err) @@ -177,12 +177,12 @@ func TestAuthorDetailCardLayoutAndSanitization(t *testing.T) { if err != nil { t.Fatal(err) } - author.DataSourceID = "Q1234" author.Description = map[string]string{"en": "American novelist"} author.RetrievedOn = time.Now() author.DateOfBirth = precisiondate.NewPrecisionDate("+1920-01-02T00:00:00Z", precisiondate.PrecisionDay) author.DateOfDeath = precisiondate.NewPrecisionDate("+1992-04-06T00:00:00Z", precisiondate.PrecisionDay) - author.DataSourceLinks = map[string]string{ + author.DataSourceReferences = map[string]string{ + "wikidata": "Q1234", "goodreads": "1.John_Doe", "website": "https://example.com", } @@ -190,7 +190,7 @@ func TestAuthorDetailCardLayoutAndSanitization(t *testing.T) { t.Fatal(err) } if err := idx.StoreAuthorBio(author.Slug, index.AuthorBio{ - Source: author.DataSourceLinks["goodreads"], Language: "en", + Source: author.DataSourceReferences["goodreads"], Language: "en", Text: map[string]string{"en": `John Doe wrote many books.`}, }); err != nil { t.Fatal(err) @@ -329,12 +329,12 @@ func (s *localizedBioSource) ForLanguage(language string) biography.Source { return &localizedBioSource{language: language, result: s.result} } func (s *localizedBioSource) Language() string { return s.language } -func (s *localizedBioSource) LinkKey() string { return "catalog:" + s.language } +func (s *localizedBioSource) ReferenceKey() string { return "catalog:" + s.language } func (*localizedBioSource) ProfileServiceName() string { return "Example biographies" } func (*localizedBioSource) MetadataServiceName() string { return "Example catalog" } func (*localizedBioSource) ProfileInputName() string { return "catalogBioID" } func (s *localizedBioSource) ProfileValue(author index.Author) string { - return author.DataSourceLinks[s.LinkKey()] + return author.DataSourceReferences[s.ReferenceKey()] } func (*localizedBioSource) NormalizeAuthorID(value string) (string, error) { return strings.TrimSpace(value), nil @@ -356,19 +356,22 @@ func (*bioMetadataSource) NormalizeAuthorID(value string) (string, error) { func (s *bioMetadataSource) RetrieveAuthor(ids []string, _ []string) (datasourcemodel.Author, error) { return bioMetadata{sourceID: ids[0], link: s.link}, nil } -func (*bioMetadataSource) OwnsLink(key string) bool { return strings.HasPrefix(key, "catalog:") } +func (*bioMetadataSource) OwnsLink(key string) bool { + return key == "example" || strings.HasPrefix(key, "catalog:") +} type bioMetadata struct { alternativeAuthorMetadata sourceID, link string } -func (m bioMetadata) SourceID() string { return m.sourceID } func (m bioMetadata) Links() map[string]string { + links := map[string]string{"example": m.sourceID} if m.link == "" { - return nil + return links } - return map[string]string{"catalog:es": m.link} + links["catalog:es"] = m.link + return links } func (bioMetadata) OwnsLink(key string) bool { return (&bioMetadataSource{}).OwnsLink(key) @@ -394,8 +397,8 @@ func TestLocalizedAuthorBioUsesCurrentLanguageOnAuthorPage(t *testing.T) { if page.Find(`[hx-get="/authors/john-doe/bio"]`).Length() != 1 || len(result.calls) != 0 { t.Fatal("a known profile must enable lazy biography retrieval without requesting the source") } - if err := idx.StoreAuthorBioForLink(author.Slug, "catalog:es", author.DataSourceLinks["catalog:es"], index.AuthorBio{ - Source: author.DataSourceLinks["catalog:es"], Language: "es", Text: map[string]string{"es": "Stored Spanish biography."}, + if err := idx.StoreAuthorBioForLink(author.Slug, "catalog:es", author.DataSourceReferences["catalog:es"], index.AuthorBio{ + Source: author.DataSourceReferences["catalog:es"], Language: "es", Text: map[string]string{"es": "Stored Spanish biography."}, }, true); err != nil { t.Fatal(err) } @@ -424,8 +427,8 @@ func TestMetadataProfileUpdateRefreshesBiography(t *testing.T) { if err != nil { t.Fatal(err) } - author.DataSourceID = "old-author" - author.DataSourceLinks = map[string]string{ + author.DataSourceReferences = map[string]string{ + "example": "old-author", "catalog:es": "old-profile", "independent": "other-profile", } @@ -433,7 +436,7 @@ func TestMetadataProfileUpdateRefreshesBiography(t *testing.T) { t.Fatal(err) } if err := idx.StoreAuthorBio(author.Slug, index.AuthorBio{ - Source: author.DataSourceLinks["catalog:es"], Language: "es", Text: map[string]string{"es": "Stale biography."}, + Source: author.DataSourceReferences["catalog:es"], Language: "es", Text: map[string]string{"es": "Stale biography."}, }); err != nil { t.Fatal(err) } @@ -455,8 +458,8 @@ func TestMetadataProfileUpdateRefreshesBiography(t *testing.T) { if err != nil { t.Fatal(err) } - if stored.DataSourceID != "new-author" || stored.Bio.Source != source.link || stored.Bio.Text["es"] != result.text || - stored.DataSourceLinks["independent"] != "other-profile" { + if stored.DataSourceReferences["example"] != "new-author" || stored.Bio.Source != source.link || stored.Bio.Text["es"] != result.text || + stored.DataSourceReferences["independent"] != "other-profile" { t.Fatalf("metadata update must refresh and persist its biography while preserving independent links: %+v", stored) } if style == "" && strings.TrimSpace(page.Find("#author-bio-text").Text()) != result.text { @@ -500,9 +503,9 @@ func TestMetadataProfileUpdateRefreshesBiography(t *testing.T) { if err != nil { t.Fatal(err) } - if response.StatusCode != http.StatusOK || stored.DataSourceID != sourceID || + if response.StatusCode != http.StatusOK || stored.DataSourceReferences["example"] != sourceID || stored.Bio.Source != "" || len(stored.Bio.Text) != 0 || - stored.DataSourceLinks["catalog:es"] != "" || len(result.calls) != beforeCalls { + stored.DataSourceReferences["catalog:es"] != "" || len(result.calls) != beforeCalls { t.Fatalf("missing or cleared metadata links must clear the biography without requests: %+v", stored) } } @@ -523,7 +526,7 @@ func testAuthorBioRefreshResults(t *testing.T) { client := &bioAuthorClient{} app, idx := newAuthorBioTestApp(t, client, &bioTranslator{}) author := seedBioTestAuthor(t, idx, map[string]string{"goodreads": "1.John_Doe"}) - cached := index.AuthorBio{Source: author.DataSourceLinks["goodreads"], Language: "en"} + cached := index.AuthorBio{Source: author.DataSourceReferences["goodreads"], Language: "en"} if state == "populated" { cached.Text = map[string]string{"en": "Old biography", "es": "Old translation", "fr": "Stale translation"} } @@ -688,7 +691,7 @@ func testAuthorBioProfileEditing(t *testing.T) { if err != nil { t.Fatal(err) } - if response.StatusCode != http.StatusOK || stored.DataSourceLinks["goodreads"] != "879.Plato" || stored.Bio.Source != "879.Plato" || + if response.StatusCode != http.StatusOK || stored.DataSourceReferences["goodreads"] != "879.Plato" || stored.Bio.Source != "879.Plato" || page.Find("#author-john-doe").Length() != 1 || page.Find(`a[href="https://www.goodreads.com/author/show/879.Plato"]`).Length() != 1 || page.Find(`input[name="goodreadsID"]`).AttrOr("value", "") != "https://www.goodreads.com/author/show/879.Plato" { t.Fatalf("updating the Goodreads ID must refresh the whole card and persist the new source, got %+v", stored.Bio) @@ -718,7 +721,7 @@ func testAuthorBioProfileEditing(t *testing.T) { if err != nil { t.Fatal(err) } - if response.StatusCode != http.StatusOK || stored.DataSourceLinks["goodreads"] != "" || stored.Bio.Source != "" || + if response.StatusCode != http.StatusOK || stored.DataSourceReferences["goodreads"] != "" || stored.Bio.Source != "" || len(stored.Bio.Text) != 0 || client.calls != 2 || page.Find(`a[href*="goodreads.com/author/"]`).Length() != 0 || page.Find(`input[name="goodreadsID"]`).AttrOr("value", "") != "" { t.Fatalf("blank Goodreads ID must clear link and biography without lookup: status=%d author=%+v calls=%d", response.StatusCode, stored, client.calls) diff --git a/internal/webserver/author_summary_test.go b/internal/webserver/author_summary_test.go index a4a828a3..4973b291 100644 --- a/internal/webserver/author_summary_test.go +++ b/internal/webserver/author_summary_test.go @@ -31,8 +31,10 @@ type alternativeAuthorSource struct { } func (*alternativeAuthorSource) ProfileServiceName() string { return "Example catalog" } +func (*alternativeAuthorSource) ReferenceKey() string { return "example" } +func (*alternativeAuthorSource) OwnsLink(key string) bool { return key == "example" } func (*alternativeAuthorSource) ProfileValue(author index.Author) string { - return "https://example.org/authors/" + author.DataSourceID + return "https://example.org/authors/" + author.DataSourceReferences["example"] } func (*alternativeAuthorSource) AuthorLink(index.Author, string) datasourcemodel.DataSourceLink { return datasourcemodel.DataSourceLink{} @@ -62,10 +64,11 @@ func (alternativeAuthorMetadata) DateOfBirth() precisiondate.PrecisionDate { func (alternativeAuthorMetadata) DateOfDeath() precisiondate.PrecisionDate { return precisiondate.PrecisionDate{} } -func (alternativeAuthorMetadata) Image() string { return "" } -func (alternativeAuthorMetadata) Links() map[string]string { return nil } -func (alternativeAuthorMetadata) OwnsLink(string) bool { return false } -func (alternativeAuthorMetadata) SourceID() string { return "alice" } +func (alternativeAuthorMetadata) Image() string { return "" } +func (alternativeAuthorMetadata) Links() map[string]string { + return map[string]string{"example": "alice"} +} +func (alternativeAuthorMetadata) OwnsLink(key string) bool { return key == "example" } func (alternativeAuthorMetadata) RetrievedOn() time.Time { return time.Unix(1, 0).UTC() } func (alternativeAuthorMetadata) Pseudonyms() []string { return nil } @@ -83,8 +86,7 @@ func TestUpdateUsesDataSourceProfileParser(t *testing.T) { if err != nil { t.Fatal(err) } - author.DataSourceID = "old-profile" - author.DataSourceLinks = map[string]string{"independent": "https://other.example/author"} + author.DataSourceReferences = map[string]string{"example": "old-profile", "independent": "https://other.example/author"} if err := idx.IndexAuthor(author); err != nil { t.Fatal(err) } @@ -145,18 +147,41 @@ func TestUpdateUsesDataSourceProfileParser(t *testing.T) { if value := page.Find(`input[name="sourceID"]`).AttrOr("value", ""); value != "https://example.org/authors/alice" { t.Fatalf("expected the provider profile URL in the form, got %q", value) } + if description := strings.TrimSpace(page.Find("p.capitalize.lead").Text()); description != "Updated author metadata" { + t.Fatalf("expected metadata rendered from the provider's reference, got %q", description) + } + if imageURL := page.Find(`img[src^="/authors/"]`).AttrOr("src", ""); imageURL != "/authors/john-doe_alice.webp" { + t.Fatalf("expected image URL to use the provider's reference, got %q", imageURL) + } stored, err := idx.Author("john-doe", "en") if err != nil { t.Fatal(err) } - if stored.DataSourceID != "alice" || stored.BirthName != "Alice Example" || + if stored.DataSourceReferences["example"] != "alice" || stored.BirthName != "Alice Example" || stored.Description["en"] != "Updated author metadata" || - stored.DataSourceLinks["independent"] != before.DataSourceLinks["independent"] || + stored.DataSourceReferences["independent"] != before.DataSourceReferences["independent"] || !reflect.DeepEqual(source.retrievedIDs, []string{"alice"}) { t.Fatalf("expected normalized ID retrieval and persisted metadata while preserving independent links: %+v", stored) } }) } + for _, path := range []string{ + "/authors/john-doe", "/authors/john-doe/summary", "/authors/john-doe/summary?style=clear", + "/documents/john-doe-test-epub", + } { + t.Run(path, func(t *testing.T) { + for _, cookie := range []*http.Cookie{admin, {Name: "anonymous"}} { + page := getPageWithCookie(t, app, cookie, path) + card := page.Find("#author-john-doe") + if got := strings.TrimSpace(card.Find("p.capitalize.lead").Text()); got != "Updated author metadata" { + t.Fatalf("%s: expected metadata for the configured source, got %q", path, got) + } + if got := card.Find(`img[src^="/authors/"]`).AttrOr("src", ""); got != "/authors/john-doe_alice.webp" { + t.Fatalf("%s: expected image URL with the configured source reference, got %q", path, got) + } + } + }) + } } func TestClearAuthorRemovesImage(t *testing.T) { @@ -202,7 +227,7 @@ func TestClearAuthorRemovesImage(t *testing.T) { if err != nil { t.Fatal(err) } - author.DataSourceLinks = map[string]string{ + author.DataSourceReferences = map[string]string{ "website": "https://old.example", "wikipedia:en": "https://en.wikipedia.org/wiki/Old", "wikipedia:es": "https://es.wikipedia.org/wiki/Old", "goodreads": "1.Writer", "catalog": "https://catalog.example/writer", @@ -275,13 +300,13 @@ func TestClearAuthorRemovesImage(t *testing.T) { if err != nil { t.Fatal(err) } - if stored.DataSourceID != "" || stored.DataSourceImage != "" || - stored.DataSourceLinks["website"] != "" || stored.DataSourceLinks["wikipedia:en"] != "" || - stored.DataSourceLinks["wikipedia:es"] != "" { + if stored.DataSourceReferences["wikidata"] != "" || stored.DataSourceImage != "" || + stored.DataSourceReferences["website"] != "" || stored.DataSourceReferences["wikipedia:en"] != "" || + stored.DataSourceReferences["wikipedia:es"] != "" { t.Fatalf("metadata reset restored stale metadata: %+v", stored) } - if stored.DataSourceLinks["goodreads"] != "1.Writer" || - stored.DataSourceLinks["catalog"] != "https://catalog.example/writer" || + if stored.DataSourceReferences["goodreads"] != "1.Writer" || + stored.DataSourceReferences["catalog"] != "https://catalog.example/writer" || stored.DocumentCount != documentCount { t.Fatalf("metadata reset lost independent author data: %+v", stored) } @@ -292,7 +317,7 @@ func TestClearAuthorRemovesImage(t *testing.T) { type summaryDataSourceLinks struct{} func (summaryDataSourceLinks) AuthorLink(author index.Author, _ string) datasourcemodel.DataSourceLink { - if author.DataSourceID == "" { + if author.DataSourceReferences["wikidata"] == "" { return datasourcemodel.DataSourceLink{} } return datasourcemodel.DataSourceLink{ @@ -320,12 +345,12 @@ func TestAuthorSummaryDataSourceLinks(t *testing.T) { } { author := index.Author{ Slug: tc.name, Name: "Alice Borchardt", - DataSourceID: tc.dataSourceID, RetrievedOn: time.Now().UTC(), - DataSourceLinks: map[string]string{"website": "https://author.example/" + tc.name}, + RetrievedOn: time.Now().UTC(), + DataSourceReferences: map[string]string{"wikidata": tc.dataSourceID, "website": "https://author.example/" + tc.name}, } if tc.wikipedia { for _, lang := range locales { - author.DataSourceLinks["wikipedia:"+lang] = strings.Replace(wikipediaURL, "en.wikipedia.org", lang+".wikipedia.org", 1) + author.DataSourceReferences["wikipedia:"+lang] = strings.Replace(wikipediaURL, "en.wikipedia.org", lang+".wikipedia.org", 1) } } if err := idx.IndexAuthor(author); err != nil { @@ -406,12 +431,13 @@ func (editableAlternativeLinks) AuthorLink(author index.Author, _ string) dataso } func (editableAlternativeLinks) ProfileServiceName() string { return "Example catalog" } +func (editableAlternativeLinks) ReferenceKey() string { return "example" } func (editableAlternativeLinks) ProfileValue(index.Author) string { return "catalog-profile" } func TestDocumentAuthorProfileUsesMetadataSource(t *testing.T) { app, idx := newDataSourceProvidersTestApp(t, nil, nil, editableAlternativeLinks{}) if err := idx.IndexAuthor(index.Author{ - Slug: "jane-doe", Name: "Jane Doe", DataSourceID: "Q1234", RetrievedOn: time.Now().UTC(), + Slug: "jane-doe", Name: "Jane Doe", DataSourceReferences: map[string]string{"wikidata": "Q1234"}, RetrievedOn: time.Now().UTC(), }); err != nil { t.Fatal(err) } diff --git a/internal/webserver/controller/author/bio.go b/internal/webserver/controller/author/bio.go index 65342856..d1960489 100644 --- a/internal/webserver/controller/author/bio.go +++ b/internal/webserver/controller/author/bio.go @@ -93,10 +93,11 @@ func (a *Controller) renderAuthorSummary(c fiber.Ctx, author index.Author, lang, session, _ := c.Locals("Session").(model.Session) vars := fiber.Map{ "Author": author, "Lang": lang, "Session": session, - "DataSourceLinks": a.authorDataSourceLinks(author, lang), - "ImageVersion": a.getImageVersion(author.Slug), - "ProfileInputs": a.profileInputs(author, lang, "", invalidProfile, c.FormValue(invalidProfile)), - "InvalidProfile": invalidProfile != "", + "AuthorDataSourceReference": AuthorDataSourceReference(author, a.dataSource), + "DataSourceLinks": a.authorDataSourceLinks(author, lang), + "ImageVersion": a.getImageVersion(author.Slug), + "ProfileInputs": a.profileInputs(author, lang, "", invalidProfile, c.FormValue(invalidProfile)), + "InvalidProfile": invalidProfile != "", } a.addBioVars(vars, "partials/author-summary", author, lang) if err := c.Render("partials/author-summary", vars); err != nil { diff --git a/internal/webserver/controller/author/controller.go b/internal/webserver/controller/author/controller.go index 4aebf4fb..57cac331 100644 --- a/internal/webserver/controller/author/controller.go +++ b/internal/webserver/controller/author/controller.go @@ -23,6 +23,11 @@ type ProfileInputProvider interface { ProfileValue(author index.Author) string } +type AuthorDataSourceProfileProvider interface { + ProfileInputProvider + ReferenceKey() string +} + type ProfileInput struct { Name string ServiceName string @@ -44,6 +49,14 @@ func NewProfileInput(provider ProfileInputProvider, author index.Author, name, m } } +func AuthorDataSourceReference(author index.Author, provider AuthorDataSourceProfileProvider) string { + key := "wikidata" + if provider != nil { + key = provider.ReferenceKey() + } + return author.DataSourceReferences[key] +} + func NewMetadataProfileInput(provider ProfileInputProvider, author index.Author, style string) ProfileInput { action := "/authors/" + author.Slug if style == "clear" { diff --git a/internal/webserver/controller/author/datasource.go b/internal/webserver/controller/author/datasource.go index af3ee8cb..dbd93029 100644 --- a/internal/webserver/controller/author/datasource.go +++ b/internal/webserver/controller/author/datasource.go @@ -3,7 +3,7 @@ package author import "github.com/svera/coreander/v5/internal/datasource/model" type DataSource interface { - ProfileInputProvider + AuthorDataSourceProfileProvider OwnsLink(key string) bool NormalizeAuthorID(value string) (string, error) SearchAuthor(name string, languages []string) (model.Author, error) diff --git a/internal/webserver/controller/author/documents.go b/internal/webserver/controller/author/documents.go index 5167675f..591d58cc 100644 --- a/internal/webserver/controller/author/documents.go +++ b/internal/webserver/controller/author/documents.go @@ -66,25 +66,26 @@ func (a *Controller) Documents(c fiber.Ctx) error { bioParagraphs, bioTranslatedFrom, bioPending := a.storedBio(author, lang) templateVars := fiber.Map{ - "Author": author, - "BioParagraphs": bioParagraphs, - "BioPending": bioPending, - "BioTranslatedFrom": bioTranslatedFrom, - "BioRefreshAvailable": a.bioRefreshAvailable(author), - "DataSourceLinks": a.authorDataSourceLinks(author, lang), - "ProfileInputs": a.profileInputs(author, lang, "", "", ""), - "ImageVersion": a.getImageVersion(author.Slug), - "DocumentSearchFields": searchFields, - "DocumentsOnly": true, - "Results": searchResults, - "Paginator": view.Pagination(model.MaxPagesNavigator, searchResults, c.Queries()), - "Title": author.Name, - "EmailFrom": a.sender.From(), - "WordsPerMinute": a.config.WordsPerMinute, - "URL": view.URL(c), - "SortURL": view.BaseURLWithout(c, "sort-by", "page"), - "SortBy": c.Query("sort-by"), - "AdditionalSortOptions": authorDocumentSortOptions(a.config.ReviewSourceConfigured), + "Author": author, + "AuthorDataSourceReference": AuthorDataSourceReference(author, a.dataSource), + "BioParagraphs": bioParagraphs, + "BioPending": bioPending, + "BioTranslatedFrom": bioTranslatedFrom, + "BioRefreshAvailable": a.bioRefreshAvailable(author), + "DataSourceLinks": a.authorDataSourceLinks(author, lang), + "ProfileInputs": a.profileInputs(author, lang, "", "", ""), + "ImageVersion": a.getImageVersion(author.Slug), + "DocumentSearchFields": searchFields, + "DocumentsOnly": true, + "Results": searchResults, + "Paginator": view.Pagination(model.MaxPagesNavigator, searchResults, c.Queries()), + "Title": author.Name, + "EmailFrom": a.sender.From(), + "WordsPerMinute": a.config.WordsPerMinute, + "URL": view.URL(c), + "SortURL": view.BaseURLWithout(c, "sort-by", "page"), + "SortBy": c.Query("sort-by"), + "AdditionalSortOptions": authorDocumentSortOptions(a.config.ReviewSourceConfigured), } if c.Get("hx-request") == "true" { diff --git a/internal/webserver/controller/author/summary.go b/internal/webserver/controller/author/summary.go index c8168322..1f6db798 100644 --- a/internal/webserver/controller/author/summary.go +++ b/internal/webserver/controller/author/summary.go @@ -47,10 +47,11 @@ func (a *Controller) Summary(c fiber.Ctx) error { if !author.RetrievedOn.IsZero() { templateVars := fiber.Map{ - "Author": author, - "DataSourceLinks": a.authorDataSourceLinks(author, lang), - "ImageVersion": imageVersion, - "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), + "Author": author, + "AuthorDataSourceReference": AuthorDataSourceReference(author, a.dataSource), + "DataSourceLinks": a.authorDataSourceLinks(author, lang), + "ImageVersion": imageVersion, + "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), } a.addBioVars(templateVars, template, author, lang) @@ -76,10 +77,11 @@ func (a *Controller) Summary(c fiber.Ctx) error { } templateVars := fiber.Map{ - "Author": author, - "DataSourceLinks": a.authorDataSourceLinks(author, lang), - "ImageVersion": imageVersion, - "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), + "Author": author, + "AuthorDataSourceReference": AuthorDataSourceReference(author, a.dataSource), + "DataSourceLinks": a.authorDataSourceLinks(author, lang), + "ImageVersion": imageVersion, + "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), } a.addBioVars(templateVars, template, author, lang) diff --git a/internal/webserver/controller/author/update.go b/internal/webserver/controller/author/update.go index fa0d2511..d5aa9934 100644 --- a/internal/webserver/controller/author/update.go +++ b/internal/webserver/controller/author/update.go @@ -83,12 +83,13 @@ func (a *Controller) Update(c fiber.Ctx) error { } templateVars := fiber.Map{ - "Author": author, - "DataSourceLinks": a.authorDataSourceLinks(author, lang), - "ImageVersion": a.getImageVersion(author.Slug), - "Lang": lang, - "Session": session, - "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), + "Author": author, + "AuthorDataSourceReference": AuthorDataSourceReference(author, a.dataSource), + "DataSourceLinks": a.authorDataSourceLinks(author, lang), + "ImageVersion": a.getImageVersion(author.Slug), + "Lang": lang, + "Session": session, + "ProfileInputs": a.profileInputs(author, lang, c.Query("style"), "", ""), } a.addBioVars(templateVars, template, author, lang) diff --git a/internal/webserver/controller/document/controller.go b/internal/webserver/controller/document/controller.go index 813883e7..bd54e6dc 100644 --- a/internal/webserver/controller/document/controller.go +++ b/internal/webserver/controller/document/controller.go @@ -103,12 +103,12 @@ type Controller struct { appFs afero.Fs translator i18n.Translator reviewProvider ReviewProvider - authorDataSource authorcontroller.ProfileInputProvider + authorDataSource authorcontroller.AuthorDataSourceProfileProvider linkProviders []authorcontroller.DataSourceLinkProvider } // NewController creates a document controller. A nil reviewProvider disables scores and reviews. -func NewController(hlRepository highlightsRepository, usersRepository usersRepository, readingRepository readingRepository, annotationsRepository annotationsRepository, sender Sender, idx IdxReaderWriter, appFs afero.Fs, cfg Config, translator i18n.Translator, reviewProvider ReviewProvider, authorDataSource authorcontroller.ProfileInputProvider, linkProviders ...authorcontroller.DataSourceLinkProvider) *Controller { +func NewController(hlRepository highlightsRepository, usersRepository usersRepository, readingRepository readingRepository, annotationsRepository annotationsRepository, sender Sender, idx IdxReaderWriter, appFs afero.Fs, cfg Config, translator i18n.Translator, reviewProvider ReviewProvider, authorDataSource authorcontroller.AuthorDataSourceProfileProvider, linkProviders ...authorcontroller.DataSourceLinkProvider) *Controller { return &Controller{ hlRepository: hlRepository, usersRepository: usersRepository, diff --git a/internal/webserver/controller/document/detail.go b/internal/webserver/controller/document/detail.go index 0ac443c4..103ba694 100644 --- a/internal/webserver/controller/document/detail.go +++ b/internal/webserver/controller/document/detail.go @@ -17,10 +17,11 @@ import ( // render eagerly (i.e. without the async /summary htmx round-trip), so it can // only fall back to that round-trip when the author hasn't been enriched yet. type authorSummary struct { - Author index.Author - ImageVersion string - DataSourceLinks []datasourcemodel.DataSourceLink - ProfileInputs []authorcontroller.ProfileInput + Author index.Author + AuthorDataSourceReference string + ImageVersion string + DataSourceLinks []datasourcemodel.DataSourceLink + ProfileInputs []authorcontroller.ProfileInput } func (d *Controller) Detail(c fiber.Ctx) error { @@ -152,7 +153,8 @@ func (d *Controller) authorSummaryFor(authorSlug, lang string) authorSummary { } return authorSummary{ Author: author, ImageVersion: fsutil.AuthorImageVersion(d.appFs, d.config.CacheDir, author.Slug), - DataSourceLinks: links, ProfileInputs: profileInputs, + AuthorDataSourceReference: authorcontroller.AuthorDataSourceReference(author, d.authorDataSource), + DataSourceLinks: links, ProfileInputs: profileInputs, } } diff --git a/internal/webserver/document_biblioreads_test.go b/internal/webserver/document_biblioreads_test.go index f541fee9..ebfdddc9 100644 --- a/internal/webserver/document_biblioreads_test.go +++ b/internal/webserver/document_biblioreads_test.go @@ -550,7 +550,7 @@ func TestDocumentDetailBiblioReadsSearchesUnlinkedDocuments(t *testing.T) { t.Errorf("expected the found link to be stored, got %+v", stored) } author, err := idx.Author("jane-doe", "") - if err != nil || author.DataSourceLinks["goodreads"] != "1.Jane_Doe" || author.DocumentCount != 1 { + if err != nil || author.DataSourceReferences["goodreads"] != "1.Jane_Doe" || author.DocumentCount != 1 { t.Fatalf("expected missing author entry created with URL and document count, got %+v, %v", author, err) } if mustBiblioReadsData(t, stored).ResourceID != "" || mustBiblioReadsData(t, stored).LegacyBookID != 0 { diff --git a/internal/webserver/embedded/views/author/list.html b/internal/webserver/embedded/views/author/list.html index d87f704a..60b36f51 100644 --- a/internal/webserver/embedded/views/author/list.html +++ b/internal/webserver/embedded/views/author/list.html @@ -1,6 +1,6 @@ {{if ne .Author.Name ""}} {{if not .Author.RetrievedOn.IsZero}} - {{template "partials/author-summary" dict "Lang" .Lang "Author" .Author "Session" .Session "ImageVersion" .ImageVersion "DataSourceLinks" .DataSourceLinks "BioParagraphs" .BioParagraphs "BioPending" .BioPending "BioTranslatedFrom" .BioTranslatedFrom "BioRefreshAvailable" .BioRefreshAvailable "ProfileInputs" .ProfileInputs}} + {{template "partials/author-summary" dict "Lang" .Lang "Author" .Author "Session" .Session "AuthorDataSourceReference" .AuthorDataSourceReference "ImageVersion" .ImageVersion "DataSourceLinks" .DataSourceLinks "BioParagraphs" .BioParagraphs "BioPending" .BioPending "BioTranslatedFrom" .BioTranslatedFrom "BioRefreshAvailable" .BioRefreshAvailable "ProfileInputs" .ProfileInputs}} {{else}}
diff --git a/internal/webserver/embedded/views/document/detail.html b/internal/webserver/embedded/views/document/detail.html index 1c543081..3eebbfaf 100644 --- a/internal/webserver/embedded/views/document/detail.html +++ b/internal/webserver/embedded/views/document/detail.html @@ -60,7 +60,7 @@

{{.Document.Title}}


{{range .AuthorSummaries}} {{if not .Author.RetrievedOn.IsZero}} - {{template "partials/author-summary-doc-detail" dict "Lang" $.Lang "Author" .Author "Session" $.Session "ImageVersion" .ImageVersion "DataSourceLinks" .DataSourceLinks "ProfileInputs" .ProfileInputs}} + {{template "partials/author-summary-doc-detail" dict "Lang" $.Lang "Author" .Author "Session" $.Session "AuthorDataSourceReference" .AuthorDataSourceReference "ImageVersion" .ImageVersion "DataSourceLinks" .DataSourceLinks "ProfileInputs" .ProfileInputs}} {{else}} {{template "partials/author-summary-doc-detail-placeholder" dict "AuthorSlug" .Author.Slug "Lang" $.Lang}} {{end}} @@ -71,7 +71,7 @@

{{.Document.Title}}

{{range $i, $entry := .IllustratorSummaries}} {{if eq $i 0}}
{{end}} {{if not $entry.Author.RetrievedOn.IsZero}} - {{template "partials/author-summary-doc-detail" dict "Lang" $.Lang "Author" $entry.Author "Session" $.Session "ImageVersion" $entry.ImageVersion "DataSourceLinks" $entry.DataSourceLinks "ProfileInputs" $entry.ProfileInputs}} + {{template "partials/author-summary-doc-detail" dict "Lang" $.Lang "Author" $entry.Author "Session" $.Session "AuthorDataSourceReference" $entry.AuthorDataSourceReference "ImageVersion" $entry.ImageVersion "DataSourceLinks" $entry.DataSourceLinks "ProfileInputs" $entry.ProfileInputs}} {{else}} {{template "partials/author-summary-doc-detail-placeholder" dict "AuthorSlug" $entry.Author.Slug "Lang" $.Lang}} {{end}} diff --git a/internal/webserver/embedded/views/partials/author-summary-doc-detail.html b/internal/webserver/embedded/views/partials/author-summary-doc-detail.html index a0f35509..ea4776c7 100644 --- a/internal/webserver/embedded/views/partials/author-summary-doc-detail.html +++ b/internal/webserver/embedded/views/partials/author-summary-doc-detail.html @@ -1,3 +1,4 @@ +{{$authorDataSourceReference := .AuthorDataSourceReference}}
@@ -7,7 +8,7 @@

{{.Author.Name}}

{{.Author.BirthName}}

{{end}}
- {{if eq .Author.DataSourceID ""}} + {{if eq $authorDataSourceReference ""}}

{{t .Lang "Sorry, we don't have information about this author at the moment"}}

{{else if index .Author.Description .Lang}}

{{index .Author.Description .Lang}}

@@ -18,7 +19,7 @@

{{.Author.Name}}

{{end}} - {{if ne .Author.DataSourceID ""}} + {{if ne $authorDataSourceReference ""}}
{{if ne .Author.DateOfBirth.Date 0}}
{{t .Lang "Date of birth"}}
@@ -71,9 +72,9 @@

{{.Author.Name}}

{{end}}
{{end}} - {{if or (index .Author.DataSourceLinks "website") .DataSourceLinks}} + {{if or (index .Author.DataSourceReferences "website") .DataSourceLinks}}
- {{.Author.Name}} + {{.Author.Name}}
diff --git a/internal/webserver/embedded/views/partials/author-summary.html b/internal/webserver/embedded/views/partials/author-summary.html index a40f234a..e5fc60b2 100644 --- a/internal/webserver/embedded/views/partials/author-summary.html +++ b/internal/webserver/embedded/views/partials/author-summary.html @@ -1,3 +1,4 @@ +{{$authorDataSourceReference := .AuthorDataSourceReference}}
@@ -7,14 +8,14 @@

{{.Author.Name}}

{{.Author.BirthName}}

{{end}}
- {{if eq .Author.DataSourceID ""}} + {{if eq $authorDataSourceReference ""}} {{if not (or .BioParagraphs .BioPending)}}

{{t .Lang "Sorry, we don't have information about this author at the moment"}}

{{end}} {{else if index .Author.Description .Lang}}

{{index .Author.Description .Lang}}

{{end}} - {{if ne .Author.DataSourceID ""}} + {{if ne $authorDataSourceReference ""}}
{{if ne .Author.DateOfBirth.Date 0}}
{{t .Lang "Date of birth"}}
@@ -86,12 +87,12 @@

{{.Author.Name}}

- {{.Author.Name}} + {{.Author.Name}}
- {{if or (index .Author.DataSourceLinks "website") .DataSourceLinks}} + {{if or (index .Author.DataSourceReferences "website") .DataSourceLinks}}
    - {{with index .Author.DataSourceLinks "website"}} + {{with index .Author.DataSourceReferences "website"}}
  • {{t $.Lang "Website"}} diff --git a/internal/webserver/embedded/views/partials/authors-list-item.html b/internal/webserver/embedded/views/partials/authors-list-item.html index 487f19ca..19547a36 100644 --- a/internal/webserver/embedded/views/partials/authors-list-item.html +++ b/internal/webserver/embedded/views/partials/authors-list-item.html @@ -2,7 +2,7 @@