-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_file.go
51 lines (42 loc) · 1.67 KB
/
get_file.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Package storage provides functions for fetching files from IPFS.
package ipfs
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
files "github.com/ipfs/boxo/files"
"github.com/ipfs/boxo/path"
icore "github.com/ipfs/kubo/core/coreiface"
"github.com/pierreleocadie/SecuraChain/internal/config"
)
// GetFile download a file using its CID (Content Identifier).
// It creates the necessary directory if it doesn't exist and writes the file to a specified path.
func GetFile(ctx context.Context, config *config.Config, ipfsAPI icore.CoreAPI, cidFile path.ImmutablePath) error {
home, err := os.UserHomeDir()
if err != nil {
return err
}
downloadsStoragePath := filepath.Join(home, ".IPFS_Downloads/")
// Ensure the output directory exists or create it.
if err := os.MkdirAll(downloadsStoragePath, os.FileMode(config.FileRights)); err != nil {
return fmt.Errorf("error creating output directory: %v", err)
}
log.Printf("Getting file with CID: %s\n", cidFile.String())
rootNodeFile, err := ipfsAPI.Unixfs().Get(ctx, cidFile)
if err != nil {
return fmt.Errorf("could not get file with CID: %s", err)
}
defer rootNodeFile.Close()
log.Printf("Got the file")
downloadedFilePath := filepath.Join(downloadsStoragePath, filepath.Base(cidFile.String()))
log.Printf("Writing file to %s\n", downloadedFilePath)
err = files.WriteTo(rootNodeFile, downloadedFilePath)
if err != nil {
return fmt.Errorf("could not write out the fetched CID: %v", err) // send error to channel
}
// Print confirmation message indicating the file has been fetched and saved.
log.Printf("Got file back from IPFS (IPFS path: %s) and wrote it to %s\n", cidFile.String(), downloadedFilePath)
return nil
}