publish.go 1.74 KB
Newer Older
1 2 3 4 5 6 7
package commands

import (
	"errors"
	"fmt"

	cmds "github.com/jbenet/go-ipfs/commands"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
8 9
	core "github.com/jbenet/go-ipfs/core"
	crypto "github.com/jbenet/go-ipfs/crypto"
10 11 12 13 14
	nsys "github.com/jbenet/go-ipfs/namesys"
	u "github.com/jbenet/go-ipfs/util"
)

type PublishOutput struct {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
15 16
	Name  string
	Value string
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
}

var publishCmd = &cmds.Command{
	Help: "TODO",
	Run: func(res cmds.Response, req cmds.Request) {
		n := req.Context().Node
		args := req.Arguments()

		if n.Identity == nil {
			res.SetError(errors.New("Identity not loaded!"), cmds.ErrNormal)
			return
		}

		// name := ""
		ref := ""

		switch len(args) {
		case 2:
			// name = args[0]
36
			ref = args[1].(string)
37 38 39 40
			res.SetError(errors.New("keychains not yet implemented"), cmds.ErrNormal)
			return
		case 1:
			// name = n.Identity.ID.String()
41
			ref = args[0].(string)
42 43 44 45 46

		default:
			res.SetError(fmt.Errorf("Publish expects 1 or 2 args; got %d.", len(args)), cmds.ErrClient)
		}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
47 48 49
		// TODO n.Keychain.Get(name).PrivKey
		k := n.Identity.PrivKey()
		publishOutput, err := publish(n, k, ref)
50 51 52 53 54

		if err != nil {
			res.SetError(err, cmds.ErrNormal)
			return
		}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
55
		res.SetOutput(publishOutput)
56
	},
57 58 59 60 61 62
	Marshallers: map[cmds.EncodingType]cmds.Marshaller{
		cmds.Text: func(res cmds.Response) ([]byte, error) {
			v := res.Output().(*PublishOutput)
			s := fmt.Sprintf("Published name %s to %s\n", v.Name, v.Value)
			return []byte(s), nil
		},
63 64 65
	},
	Type: &PublishOutput{},
}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83

func publish(n *core.IpfsNode, k crypto.PrivKey, ref string) (*PublishOutput, error) {
	pub := nsys.NewRoutingPublisher(n.Routing)
	err := pub.Publish(k, ref)
	if err != nil {
		return nil, err
	}

	hash, err := k.GetPublic().Hash()
	if err != nil {
		return nil, err
	}

	return &PublishOutput{
		Name:  u.Key(hash).String(),
		Value: ref,
	}, nil
}