unixfs.go 1.29 KB
Newer Older
1 2 3 4
package coreapi

import (
	"context"
Lars Gierth's avatar
Lars Gierth committed
5
	"io"
6 7 8

	core "github.com/ipfs/go-ipfs/core"
	coreiface "github.com/ipfs/go-ipfs/core/coreapi/interface"
Lars Gierth's avatar
Lars Gierth committed
9
	coreunix "github.com/ipfs/go-ipfs/core/coreunix"
10
	uio "github.com/ipfs/go-ipfs/unixfs/io"
Lars Gierth's avatar
Lars Gierth committed
11 12

	cid "gx/ipfs/QmXfiyr2RWEXpVDdaYnD2HNiBk6UBddsvEP4RPfXb6nGqY/go-cid"
13 14 15 16 17 18 19 20 21 22 23
)

type UnixfsAPI struct {
	node *core.IpfsNode
}

func NewUnixfsAPI(n *core.IpfsNode) coreiface.UnixfsAPI {
	api := &UnixfsAPI{n}
	return api
}

Lars Gierth's avatar
Lars Gierth committed
24 25 26 27 28 29 30 31
func (api *UnixfsAPI) Add(ctx context.Context, r io.Reader) (*cid.Cid, error) {
	k, err := coreunix.AddWithContext(ctx, api.node, r)
	if err != nil {
		return nil, err
	}
	return cid.Decode(k)
}

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
func (api *UnixfsAPI) Cat(ctx context.Context, p string) (coreiface.Reader, error) {
	dagnode, err := resolve(ctx, api.node, p)
	if err != nil {
		return nil, err
	}

	r, err := uio.NewDagReader(ctx, dagnode, api.node.DAG)
	if err == uio.ErrIsDir {
		return nil, coreiface.ErrIsDir
	} else if err != nil {
		return nil, err
	}
	return r, nil
}

func (api *UnixfsAPI) Ls(ctx context.Context, p string) ([]*coreiface.Link, error) {
	dagnode, err := resolve(ctx, api.node, p)
	if err != nil {
		return nil, err
	}

	l := dagnode.Links()
	links := make([]*coreiface.Link, len(l))
	for i, l := range l {
		links[i] = &coreiface.Link{l.Name, l.Size, l.Cid}
	}
	return links, nil
}