-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
getResources.go
107 lines (99 loc) · 2.25 KB
/
getResources.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package pb
import (
"encoding/base64"
"fmt"
"net/url"
"strings"
"github.com/plgd-dev/hub/v2/resource-aggregate/commands"
)
const etagQueryKey = "etag"
func parseQuery(m url.Values, query string) (err error) {
for query != "" {
var key string
key, query, _ = strings.Cut(query, "&")
if strings.Contains(key, ";") {
err = fmt.Errorf("invalid semicolon separator in query")
continue
}
if key == "" {
continue
}
key, value, _ := strings.Cut(key, "=")
if key == "" {
continue
}
m[key] = append(m[key], value)
}
return err
}
// we are permissive in parsing resource id filter
func resourceIdFilterFromString(v string) *ResourceIdFilter {
if len(v) == 0 {
return nil
}
if v[0] == '/' {
v = v[1:]
}
deviceIDHref := strings.SplitN(v, "/", 2)
if len(deviceIDHref) != 2 {
return &ResourceIdFilter{
ResourceId: &commands.ResourceId{
DeviceId: v,
},
}
}
hrefQuery := strings.SplitN(deviceIDHref[1], "?", 2)
if len(hrefQuery) < 2 {
return &ResourceIdFilter{
ResourceId: &commands.ResourceId{
DeviceId: deviceIDHref[0],
Href: "/" + deviceIDHref[1],
},
}
}
values := make(url.Values)
// we cannot use url.ParseQuery because it will unescape values because they are not escaped
err := parseQuery(values, hrefQuery[1])
if err != nil {
return &ResourceIdFilter{
ResourceId: &commands.ResourceId{
DeviceId: deviceIDHref[0],
Href: "/" + hrefQuery[0],
},
}
}
etags := make([][]byte, 0, len(values[etagQueryKey]))
for _, etag := range values[etagQueryKey] {
e, err := base64.StdEncoding.DecodeString(etag)
if err == nil {
etags = append(etags, e)
}
}
if len(etags) == 0 {
etags = nil
}
return &ResourceIdFilter{
ResourceId: &commands.ResourceId{
DeviceId: deviceIDHref[0],
Href: "/" + hrefQuery[0],
},
Etag: etags,
}
}
func ResourceIdFilterFromString(filter []string) []*ResourceIdFilter {
if len(filter) == 0 {
return nil
}
ret := make([]*ResourceIdFilter, 0, len(filter))
for _, s := range filter {
f := resourceIdFilterFromString(s)
if f == nil {
continue
}
ret = append(ret, f)
}
return ret
}
func (r *GetResourcesRequest) ConvertHTTPResourceIDFilter() []*ResourceIdFilter {
return ResourceIdFilterFromString(r.GetHttpResourceIdFilter())
}