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

ipfs.go 1.7 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package ipfs
  2. import (
  3. "fmt"
  4. "io"
  5. shell "github.com/ipfs/go-ipfs-api"
  6. myio "gitlink.org.cn/cloudream/common/utils/io"
  7. )
  8. type IPFS struct {
  9. shell *shell.Shell
  10. }
  11. func NewIPFS(cfg *Config) (*IPFS, error) {
  12. ipfsAddr := fmt.Sprintf("localhost:%d", cfg.Port)
  13. sh := shell.NewShell(ipfsAddr)
  14. // 检测连通性
  15. if !sh.IsUp() {
  16. return nil, fmt.Errorf("cannot connect to %s", ipfsAddr)
  17. }
  18. return &IPFS{
  19. shell: sh,
  20. }, nil
  21. }
  22. func (fs *IPFS) IsUp() bool {
  23. return fs.shell.IsUp()
  24. }
  25. func (fs *IPFS) CreateFile() (myio.PromiseWriteCloser[string], error) {
  26. pr, pw := io.Pipe()
  27. ipfsWriter := ipfsWriter{
  28. writer: pw,
  29. finished: make(chan any, 1),
  30. }
  31. go func() {
  32. hash, err := fs.shell.Add(pr)
  33. ipfsWriter.finishErr = err
  34. ipfsWriter.fileHash = hash
  35. close(ipfsWriter.finished)
  36. pr.CloseWithError(err)
  37. }()
  38. return &ipfsWriter, nil
  39. }
  40. func (fs *IPFS) OpenRead(hash string) (io.ReadCloser, error) {
  41. return fs.shell.Cat(hash)
  42. }
  43. func (fs *IPFS) Pin(hash string) error {
  44. return fs.shell.Pin(hash)
  45. }
  46. func (fs *IPFS) Unpin(hash string) error {
  47. return fs.shell.Unpin(hash)
  48. }
  49. type ipfsWriter struct {
  50. writer *io.PipeWriter
  51. finished chan any
  52. finishErr error
  53. fileHash string
  54. }
  55. func (p *ipfsWriter) Write(data []byte) (n int, err error) {
  56. return p.writer.Write(data)
  57. }
  58. // 设置一个error中断写入
  59. func (w *ipfsWriter) Abort(err error) {
  60. w.writer.CloseWithError(err)
  61. }
  62. // Finish 结束写入,并获得返回值(文件哈希值)
  63. func (w *ipfsWriter) Finish() (string, error) {
  64. w.writer.CloseWithError(io.EOF)
  65. <-w.finished
  66. return w.fileHash, w.finishErr
  67. }
  68. func IPFSRemoteDeamonDetector() { //探测本地IPFS Deamon与目的地IPFS Deamon的连接状态
  69. }

公共库

Contributors (1)