github.com/0chain/gosdk@v1.17.11/zboxcore/fileref/refpath.go (about) 1 package fileref 2 3 import ( 4 "github.com/0chain/errors" 5 "github.com/mitchellh/mapstructure" 6 ) 7 8 type ReferencePath struct { 9 Meta map[string]interface{} `json:"meta_data"` 10 List []*ReferencePath `json:"list,omitempty"` 11 } 12 13 func (rp *ReferencePath) GetRefFromObjectTree(allocationID string) (RefEntity, error) { 14 reftype := rp.Meta["type"].(string) 15 if reftype == FILE { 16 rootRef := &FileRef{} 17 rootRef.Type = FILE 18 rootRef.AllocationID = allocationID 19 var md mapstructure.Metadata 20 config := &mapstructure.DecoderConfig{ 21 Metadata: &md, 22 Result: rootRef, 23 TagName: "mapstructure", 24 } 25 decoder, err := mapstructure.NewDecoder(config) 26 if err != nil { 27 return nil, err 28 } 29 err = decoder.Decode(rp.Meta) 30 if err != nil { 31 return nil, err 32 } 33 return rootRef, nil 34 } 35 return rp.GetDirTree(allocationID) 36 } 37 38 // GetDirTree covert and build root Ref with children 39 func (rp *ReferencePath) GetDirTree(allocationID string) (*Ref, error) { 40 reftype := rp.Meta["type"].(string) 41 if reftype == DIRECTORY { 42 rootRef := &Ref{Type: DIRECTORY} 43 rootRef.AllocationID = allocationID 44 var md mapstructure.Metadata 45 config := &mapstructure.DecoderConfig{ 46 Metadata: &md, 47 Result: rootRef, 48 TagName: "mapstructure", 49 } 50 decoder, err := mapstructure.NewDecoder(config) 51 if err != nil { 52 return nil, err 53 } 54 err = decoder.Decode(rp.Meta) 55 if err != nil { 56 return nil, err 57 } 58 err = rp.populateChildren(rootRef) 59 if err != nil { 60 return nil, err 61 } 62 return rootRef, nil 63 } 64 return nil, errors.New("invalid_ref_path", "Invalid reference path. root was not a directory type") 65 } 66 67 func (rp *ReferencePath) populateChildren(ref *Ref) error { 68 for _, rpc := range rp.List { 69 reftype := rpc.Meta["type"].(string) 70 var childEntity RefEntity 71 if reftype == DIRECTORY { 72 dref := &Ref{Type: DIRECTORY} 73 dref.AllocationID = ref.AllocationID 74 childEntity = dref 75 } else { 76 fref := &FileRef{} 77 fref.Type = FILE 78 fref.AllocationID = ref.AllocationID 79 childEntity = fref 80 } 81 var md mapstructure.Metadata 82 config := &mapstructure.DecoderConfig{ 83 Metadata: &md, 84 Result: childEntity, 85 TagName: "mapstructure", 86 } 87 decoder, err := mapstructure.NewDecoder(config) 88 if err != nil { 89 return err 90 } 91 err = decoder.Decode(rpc.Meta) 92 if err != nil { 93 return err 94 } 95 ref.AddChild(childEntity) //append(ref.Children, childEntity) 96 if childEntity.GetType() == DIRECTORY && rpc.List != nil && len(rpc.List) > 0 { 97 err = rpc.populateChildren(childEntity.(*Ref)) 98 } 99 if err != nil { 100 return err 101 } 102 } 103 return nil 104 }