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
14const addedPads = "addedPads"
15const gettedPads = "gettedPads"
16
17//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
18func Add(link string, extension string) (string, error) {
19	if extension != "md" && extension != "txt" && extension != "html" && extension != "pdf" && extension != "odt" {
20		return "", errors.New("No valid extension")
21	}
22	format := extension
23	if extension == "md" {
24		format = "markdown"
25		extension = "md"
26	}
27
28	//create the pads directory
29	_ = os.Mkdir(addedPads, os.ModePerm)
30
31	//get the pad name
32	linkSplitted := strings.Split(link, "/")
33	padName := linkSplitted[len(linkSplitted)-1]
34	completeLink := link + "/export/" + format
35
36	//get the content from the url
37	r, err := http.Get(completeLink)
38	if err != nil {
39		fmt.Println(err)
40		return "", err
41	}
42	defer r.Body.Close()
43	content, err := ioutil.ReadAll(r.Body)
44	if err != nil {
45		fmt.Printf("%s", err)
46		return "", err
47	}
48
49	//save the content into a file
50	err = ioutil.WriteFile(addedPads+"/"+padName+"."+extension, content, 0644)
51	if err != nil {
52		fmt.Println(err)
53		return "", err
54	}
55
56	//connect to ipfs shell
57	s := sh.NewShell("localhost:5001")
58	//save the file into IPFS
59	ipfsHash, err := s.AddDir(addedPads + "/" + padName + "." + extension)
60	if err != nil {
61		fmt.Println(err)
62		return "", err
63	}
64	return ipfsHash, nil
65}
66
67//Get gets the content from IPFS for a given hash, and saves it into a file
68func Get(hash string, filename string) error {
69	//create the pads directory
70	_ = os.Mkdir(gettedPads, os.ModePerm)
71
72	//connect to ipfs shell
73	s := sh.NewShell("localhost:5001")
74	err := s.Get(hash, gettedPads+"/"+filename)
75	if err != nil {
76		fmt.Println(err)
77		return err
78	}
79	return nil
80}