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.

80 lines
1.8 KiB

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