You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.0 KiB

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