This repository has been archived by the owner on Apr 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
extract_raw_file.go
75 lines (65 loc) · 1.59 KB
/
extract_raw_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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package onion
import (
"bytes"
"context"
"errors"
"fmt"
cid "github.com/ipfs/go-cid"
"github.com/ipfs/go-unixfsnode/file"
"github.com/ipld/go-car/v2/blockstore"
dagpb "github.com/ipld/go-codec-dagpb"
"github.com/ipld/go-ipld-prime"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
"github.com/ipld/go-ipld-prime/storage/bsadapter"
"io"
)
func ExtractRaw(carBytes []byte) (response []byte, err error) {
cr := bytes.NewReader(carBytes)
bs, err := blockstore.NewReadOnly(cr, nil)
if err != nil {
panic(err)
}
roots, err := bs.Roots()
if err != nil {
panic(err)
}
bsa := &bsadapter.Adapter{Wrapped: bs}
ls := cidlink.DefaultLinkSystem()
ls.TrustedStorage = true
ls.SetReadStorage(bsa)
if roots[0].Prefix().Codec == cid.Raw {
blk, err := bs.Get(context.Background(), roots[0])
if err != nil {
panic(err)
}
return blk.RawData(), nil
}
return extractRoot(&ls, roots[0])
}
func extractRoot(ls *ipld.LinkSystem, root cid.Cid) (response []byte, err error) {
if root.Prefix().Codec == cid.Raw {
return nil, errors.New("raw cid not supported")
}
pbn, err := ls.Load(ipld.LinkContext{}, cidlink.Link{Cid: root}, dagpb.Type.PBNode)
if err != nil {
panic(err)
}
pbnode := pbn.(dagpb.PBNode)
node, err := file.NewUnixFSFileWithPreload(context.Background(), pbnode, ls)
if err != nil {
fmt.Print("return 1 bye")
return nil, err
}
nlr, err := node.AsLargeBytes()
if err != nil {
fmt.Print("return 2")
return nil, err
}
resp := bytes.NewBuffer(nil)
_, err = io.Copy(resp, nlr)
if err != nil {
fmt.Print("return 3")
return nil, err
}
return resp.Bytes(), nil
}