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.9 kB

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

公共库

Contributors (1)