Implement top shares page

This commit is contained in:
Pijus Kamandulis
2025-06-23 14:37:06 +03:00
parent 260d2ec24b
commit d801debaf6
10 changed files with 279 additions and 9 deletions

View File

@@ -14,6 +14,9 @@ import (
const (
CollectionName = "shares"
TopSharesCollectionName = "TopShares"
TopSharesAmount = 20
)
func InitDatabase(path string) (*clover.DB, error) {
@@ -42,10 +45,30 @@ func InitDatabase(path string) (*clover.DB, error) {
}
}
// Init TopShares collection
hasTopSharesCollection, err := db.HasCollection(TopSharesCollectionName)
if err != nil {
return nil, fmt.Errorf("failed to check TopShares collection: %v", err)
}
if !hasTopSharesCollection {
if err := db.CreateCollection(TopSharesCollectionName); err != nil {
return nil, fmt.Errorf("failed to create TopShares collection: %v", err)
}
if err := db.CreateIndex(TopSharesCollectionName, "CreateDate"); err != nil {
return nil, fmt.Errorf("failed to create index for TopShares: %v", err)
}
if err := db.CreateIndex(TopSharesCollectionName, "SDiff"); err != nil {
return nil, fmt.Errorf("failed to create index for TopShares SDiff: %v", err)
}
}
return db, nil
}
func GetHighestShareInRange(db *clover.DB, collection string, since time.Time) (*document.Document, error) {
func GetHighestSharesInRange(db *clover.DB, collection string, since time.Time, count int) ([]models.ShareLog, error) {
// Convert `since` to the format in `createdate`
lower := since.Unix()
upper := time.Now().Unix()
@@ -58,12 +81,22 @@ func GetHighestShareInRange(db *clover.DB, collection string, since time.Time) (
results, err := db.FindAll(c.NewQuery(collection).
Where(criteria).
Sort(c.SortOption{Field: "SDiff", Direction: -1}).
Limit(1))
Limit(count))
if err != nil || len(results) == 0 {
return nil, err
}
return results[0], nil
var shares []models.ShareLog
for _, doc := range results {
var s models.ShareLog
if err := doc.Unmarshal(&s); err != nil {
return nil, err
}
shares = append(shares, s)
}
return shares, nil
}
func PrintAllHashes(db *clover.DB) {
@@ -99,3 +132,36 @@ func ListShares(db *clover.DB, offset int, count int) []models.ShareLog {
return shareLogs
}
func ListTopShares(db *clover.DB) []models.ShareLog {
results, err := db.FindAll(
c.NewQuery(TopSharesCollectionName).
Sort(c.SortOption{Field: "SDiff", Direction: -1}),
)
if err != nil {
log.Printf("failed to list top shares: %v", err)
return nil
}
topShares := make([]models.ShareLog, len(results))
for idx, doc := range results {
var shareLog models.ShareLog
doc.Unmarshal(&shareLog)
topShares[idx] = shareLog
}
return topShares
}
func ReplaceTopShares(db *clover.DB, shares []models.ShareLog) {
db.Delete(c.NewQuery(TopSharesCollectionName))
for _, share := range shares {
doc := document.NewDocumentOf(&share)
if _, err := db.InsertOne(TopSharesCollectionName, doc); err != nil {
return
}
}
log.Printf("Replaced TopShares with %d shares", len(shares))
}