github.com/qri-io/qri@v0.10.1-0.20220104210721-c771715036cb/p2p/list_peers.go (about)

     1  package p2p
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/qri-io/qri/config"
     8  	"github.com/qri-io/qri/profile"
     9  )
    10  
    11  // ListPeers lists Peers on the qri network
    12  // userID is the profile identifier of the user making the request
    13  func ListPeers(ctx context.Context, node *QriNode, userID profile.ID, offset, limit int, onlineOnly bool) ([]*config.ProfilePod, error) {
    14  
    15  	r := node.Repo
    16  
    17  	peers := make([]*config.ProfilePod, 0, limit)
    18  	connected := node.ConnectedQriProfiles(ctx)
    19  
    20  	if onlineOnly {
    21  		for _, p := range connected {
    22  			peers = append(peers, p)
    23  		}
    24  		return peers, nil
    25  	}
    26  
    27  	ps, err := r.Profiles().List(ctx)
    28  	if err != nil {
    29  		return nil, fmt.Errorf("error listing peers: %s", err.Error())
    30  	}
    31  
    32  	if len(ps) == 0 || offset >= len(ps) {
    33  		return []*config.ProfilePod{}, nil
    34  	}
    35  
    36  	for _, pro := range ps {
    37  		if offset > 0 {
    38  			offset--
    39  			continue
    40  		}
    41  		if len(peers) >= limit {
    42  			break
    43  		}
    44  		if pro == nil || pro.ID == userID {
    45  			continue
    46  		}
    47  
    48  		if _, ok := connected[pro.ID]; ok {
    49  			pro.Online = true
    50  		}
    51  
    52  		p, err := pro.Encode()
    53  		if err != nil {
    54  			return nil, err
    55  		}
    56  		peers = append(peers, p)
    57  	}
    58  
    59  	return peers, nil
    60  }