arnaucube
arnaucube/pad2ipfsPublic Self-hosted repository
pad2ipfs/pad2ipfs.go
pad2ipfs.goRaw
 1package pad2ipfs
 2
 3import (
 4	"errors"
 5	"fmt"
 6	"io/ioutil"
 7	"net/http"
 8	"os"
 9	"strings"
10
11	sh "github.com/ipfs/go-ipfs-api"
12)
13
14//AddedPads is the directory where are stored the pads that are added to IPFS
15const AddedPads = "addedPads"
16
17//GettedPads is the directory where are stored the pads that are getted from IPFS
18const GettedPads = "gettedPads"
19
20//Add gets the content from the etherpad specified in the link, and downloads it in the format of the specified extension, and then, puts it into IPFS
21func Add(link string, extension string) (string, error) {
22	if extension != "md" && extension != "txt" && extension != "html" && extension != "pdf" && extension != "odt" {
23		return "", errors.New("No valid extension")
24	}
25	format := extension
26	if extension == "md" {
27		format = "markdown"
28		extension = "md"
29	}
30
31	//create the pads directory
32	_ = os.Mkdir(AddedPads, os.ModePerm)
33
34	//get the pad name
35	linkSplitted := strings.Split(link, "/")
36	padName := linkSplitted[len(linkSplitted)-1]
37	completeLink := link + "/export/" + format
38
39	//get the content from the url
40	r, err := http.Get(completeLink)
41	if err != nil {
42		fmt.Println(err)
43		return "", err
44	}
45	defer r.Body.Close()
46	content, err := ioutil.ReadAll(r.Body)
47	if err != nil {
48		fmt.Printf("%s", err)
49		return "", err
50	}
51
52	//save the content into a file
53	err = ioutil.WriteFile(AddedPads+"/"+padName+"."+extension, content, 0644)
54	if err != nil {
55		fmt.Println(err)
56		return "", err
57	}
58
59	//connect to ipfs shell
60	s := sh.NewShell("localhost:5001")
61	//save the file into IPFS
62	ipfsHash, err := s.AddDir(AddedPads + "/" + padName + "." + extension)
63	if err != nil {
64		fmt.Println(err)
65		return "", err
66	}
67	return ipfsHash, nil
68}
69
70//Get gets the content from IPFS for a given hash, and saves it into a file
71func Get(hash string, filename string) error {
72	//create the pads directory
73	_ = os.Mkdir(GettedPads, os.ModePerm)
74
75	//connect to ipfs shell
76	s := sh.NewShell("localhost:5001")
77	err := s.Get(hash, GettedPads+"/"+filename)
78	if err != nil {
79		fmt.Println(err)
80		return err
81	}
82	return nil
83}