aboutsummaryrefslogtreecommitdiffstats
path: root/pkg/index/index.go
blob: f3dc00da3c66a89aac8bc368638ddd728f0d1fa3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package index

import (
	"maps"
	"slices"
	"sort"
	"sync"

	"github.com/LMBishop/scrapbook/pkg/site"
)

type SiteIndex struct {
	mu          sync.RWMutex
	sites       map[string]*site.Site
	sitesByHost map[string]*site.Site
}

func NewSiteIndex() *SiteIndex {
	var siteIndex SiteIndex
	siteIndex.sites = make(map[string]*site.Site)
	siteIndex.sitesByHost = make(map[string]*site.Site)
	return &siteIndex
}

func (s *SiteIndex) GetSiteByHost(host string) *site.Site {
	s.mu.RLock()
	defer s.mu.RUnlock()

	return s.sitesByHost[host]
}

func (s *SiteIndex) GetSite(site string) *site.Site {
	s.mu.RLock()
	defer s.mu.RUnlock()

	return s.sites[site]
}

func (s *SiteIndex) GetSites() []*site.Site {
	s.mu.RLock()
	defer s.mu.RUnlock()

	sites := slices.Collect(maps.Values(s.sites))
	sort.Slice(sites, func(i, j int) bool {
		return sites[i].Name < sites[j].Name
	})
	return sites
}

func (s *SiteIndex) AddSite(site *site.Site) {
	s.mu.Lock()
	defer s.mu.Unlock()

	s.sites[site.Name] = site
	s.updateSiteIndexes()
}

func (s *SiteIndex) UpdateSiteIndexes() {
	s.mu.Lock()
	defer s.mu.Unlock()

	s.updateSiteIndexes()
}

func (s *SiteIndex) updateSiteIndexes() {
	clear(s.sitesByHost)
	for _, site := range s.sites {
		if site.SiteConfig.Host != "" {
			s.sitesByHost[site.SiteConfig.Host] = site
		}
	}
}