github.com/code-to-go/safepool.lib@v0.0.0-20221205180519-ee25e63c226e/pool/list.go (about)

     1  package pool
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"path"
     7  	"strconv"
     8  	"strings"
     9  	"time"
    10  
    11  	"github.com/code-to-go/safepool.lib/core"
    12  	"github.com/code-to-go/safepool.lib/security"
    13  )
    14  
    15  func (p *Pool) list(afterId uint64, afterTime time.Time) ([]Head, error) {
    16  	hs, err := sqlGetHeads(p.Name, afterId, afterTime)
    17  	if core.IsErr(err, "cannot read Pool heads: %v") {
    18  		return nil, err
    19  	}
    20  
    21  	heads := map[uint64]Head{}
    22  	for _, h := range hs {
    23  		heads[h.Id] = h
    24  	}
    25  
    26  	fs, err := p.e.ReadDir(p.Name, 0)
    27  	if core.IsErr(err, "cannot read content in pool %s/%s", p.e, p.Name) {
    28  		return hs, err
    29  	}
    30  	for _, f := range fs {
    31  		name := f.Name()
    32  		if !strings.HasSuffix(name, ".head") {
    33  			continue
    34  		}
    35  
    36  		id, _ := strconv.ParseInt(name, 10, 64)
    37  		if _, found := heads[uint64(id)]; found {
    38  			continue
    39  		}
    40  
    41  		h, err := p.readHead(path.Join(p.Name, name))
    42  		if core.IsErr(err, "cannot read file %s from %s: %v", name, p.e) {
    43  			continue
    44  		}
    45  		_ = sqlAddHead(p.Name, h)
    46  		hs = append(hs, h)
    47  	}
    48  	return hs, nil
    49  }
    50  
    51  func (p *Pool) readHead(name string) (Head, error) {
    52  	var b bytes.Buffer
    53  	_, err := p.readFile(name, nil, &b)
    54  	if core.IsErr(err, "cannot read header of %s in %s: %v", name, p.e) {
    55  		return Head{}, err
    56  	}
    57  
    58  	var h Head
    59  	err = json.Unmarshal(b.Bytes(), &h)
    60  	if core.IsErr(err, "corrupted header for file %s", name) {
    61  		return Head{}, err
    62  	}
    63  
    64  	if !security.Verify(h.Author.Id(), h.Hash, h.Signature) {
    65  		return Head{}, ErrNoExchange
    66  	}
    67  
    68  	return h, err
    69  }