forked from go-ap/activitypub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiri.go
439 lines (395 loc) · 9.64 KB
/
iri.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
package activitypub
import (
"bytes"
"encoding/gob"
"fmt"
"io"
"net/url"
"path/filepath"
"strings"
"github.com/valyala/fastjson"
)
const (
// ActivityBaseURI the URI for the ActivityStreams namespace
ActivityBaseURI = IRI("https://www.w3.org/ns/activitystreams")
// SecurityContextURI the URI for the security namespace (for an Actor's PublicKey)
SecurityContextURI = IRI("https://w3id.org/security/v1")
// PublicNS is the reference to the Public entity in the ActivityStreams namespace.
//
// Public Addressing
//
// https://www.w3.org/TR/activitypub/#public-addressing
//
// In addition to [ActivityStreams] collections and objects, Activities may additionally be addressed to the
// special "public" collection, with the identifier https://www.w3.org/ns/activitystreams#Public. For example:
//
// {
// "@context": "https://www.w3.org/ns/activitystreams",
// "id": "https://www.w3.org/ns/activitystreams#Public",
// "type": "Collection"
// }
// Activities addressed to this special URI shall be accessible to all users, without authentication.
// Implementations MUST NOT deliver to the "public" special collection; it is not capable of receiving
// actual activities. However, actors MAY have a sharedInbox endpoint which is available for efficient
// shared delivery of public posts (as well as posts to followers-only); see 7.1.3 Shared Inbox Delivery.
//
// NOTE
// Compacting an ActivityStreams object using the ActivityStreams JSON-LD context might result in
// https://www.w3.org/ns/activitystreams#Public being represented as simply Public or as:Public which are valid
// representations of the Public collection. Implementations which treat ActivityStreams objects as simply JSON
// rather than converting an incoming activity over to a local context using JSON-LD tooling should be aware
// of this and should be prepared to accept all three representations.
PublicNS = ActivityBaseURI + "#Public"
)
// JsonLDContext is a slice of IRIs that form the default context for the objects in the
// GoActivitypub vocabulary.
// It does not represent just the default ActivityStreams public namespace, but it also
// has the W3 Permanent Identifier Community Group's Security namespace, which appears
// in the Actor type objects, which contain public key related data.
var JsonLDContext = []IRI{
ActivityBaseURI,
SecurityContextURI,
}
type (
// IRI is a Internationalized Resource Identifiers (IRIs) RFC3987
IRI string
IRIs []IRI
)
func (i IRI) Format(s fmt.State, verb rune) {
switch verb {
case 's', 'v':
_, _ = io.WriteString(s, i.String())
}
}
// String returns the String value of the IRI object
func (i IRI) String() string {
return string(i)
}
// GetLink
func (i IRI) GetLink() IRI {
return i
}
// URL
func (i IRI) URL() (*url.URL, error) {
return url.ParseRequestURI(string(i))
}
// UnmarshalJSON decodes an incoming JSON document into the receiver object.
func (i *IRI) UnmarshalJSON(s []byte) error {
*i = IRI(strings.Trim(string(s), "\""))
return nil
}
// MarshalJSON encodes the receiver object to a JSON document.
func (i IRI) MarshalJSON() ([]byte, error) {
if i == "" {
return nil, nil
}
b := make([]byte, 0)
JSONWrite(&b, '"')
JSONWriteS(&b, i.String())
JSONWrite(&b, '"')
return b, nil
}
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
func (i *IRI) UnmarshalBinary(data []byte) error {
return i.GobDecode(data)
}
// MarshalBinary implements the encoding.BinaryMarshaler interface.
func (i IRI) MarshalBinary() ([]byte, error) {
return i.GobEncode()
}
// GobEncode
func (i IRI) GobEncode() ([]byte, error) {
return []byte(i), nil
}
// GobEncode
func (i IRIs) GobEncode() ([]byte, error) {
if len(i) == 0 {
return []byte{}, nil
}
b := bytes.Buffer{}
gg := gob.NewEncoder(&b)
bb := make([][]byte, 0)
for _, iri := range i {
bb = append(bb, []byte(iri))
}
if err := gg.Encode(bb); err != nil {
return nil, err
}
return b.Bytes(), nil
}
// GobDecode
func (i *IRI) GobDecode(data []byte) error {
*i = IRI(data)
return nil
}
func (i *IRIs) GobDecode(data []byte) error {
if len(data) == 0 {
// NOTE(marius): this behaviour diverges from vanilla gob package
return nil
}
err := gob.NewDecoder(bytes.NewReader(data)).Decode(i)
if err == nil {
return nil
}
bb := make([][]byte, 0)
err = gob.NewDecoder(bytes.NewReader(data)).Decode(&bb)
if err != nil {
return err
}
for _, b := range bb {
*i = append(*i, IRI(b))
}
return nil
}
// AddPath concatenates el elements as a path to i
func (i IRI) AddPath(el ...string) IRI {
iri := strings.TrimRight(i.String(), "/")
return IRI(iri + filepath.Clean(filepath.Join("/", filepath.Join(el...))))
}
// GetID
func (i IRI) GetID() ID {
return i
}
// GetType
func (i IRI) GetType() ActivityVocabularyType {
return IRIType
}
// IsLink
func (i IRI) IsLink() bool {
return true
}
// IsObject
func (i IRI) IsObject() bool {
return false
}
// IsCollection returns false for IRI objects
func (i IRI) IsCollection() bool {
return false
}
// FlattenToIRI checks if Item can be flatten to an IRI and returns it if so
func FlattenToIRI(it Item) Item {
if !IsNil(it) && it.IsObject() && len(it.GetLink()) > 0 {
return it.GetLink()
}
return it
}
func (i IRIs) MarshalJSON() ([]byte, error) {
if len(i) == 0 {
return []byte{'[', ']'}, nil
}
b := make([]byte, 0)
writeCommaIfNotEmpty := func(notEmpty bool) {
if notEmpty {
JSONWriteS(&b, ",")
}
}
JSONWrite(&b, '[')
for k, iri := range i {
writeCommaIfNotEmpty(k > 0)
JSONWrite(&b, '"')
JSONWriteS(&b, iri.String())
JSONWrite(&b, '"')
}
JSONWrite(&b, ']')
return b, nil
}
func (i *IRIs) UnmarshalJSON(data []byte) error {
if i == nil {
return nil
}
p := fastjson.Parser{}
val, err := p.ParseBytes(data)
if err != nil {
return err
}
switch val.Type() {
case fastjson.TypeString:
if iri, ok := asIRI(val); ok && len(iri) > 0 {
*i = append(*i, iri)
}
case fastjson.TypeArray:
for _, v := range val.GetArray() {
if iri, ok := asIRI(v); ok && len(iri) > 0 {
*i = append(*i, iri)
}
}
}
return nil
}
// GetID returns the ID corresponding to ItemCollection
func (i IRIs) GetID() ID {
return EmptyID
}
// GetLink returns the empty IRI
func (i IRIs) GetLink() IRI {
return EmptyIRI
}
// GetType returns the ItemCollection's type
func (i IRIs) GetType() ActivityVocabularyType {
return CollectionOfIRIs
}
// IsLink returns false for an ItemCollection object
func (i IRIs) IsLink() bool {
return false
}
// IsObject returns true for a ItemCollection object
func (i IRIs) IsObject() bool {
return false
}
// IsCollection returns true for IRI slices
func (i IRIs) IsCollection() bool {
return true
}
// Append facilitates adding elements to IRI slices
// and ensures IRIs implements the Collection interface
func (i *IRIs) Append(it ...Item) error {
for _, ob := range it {
if (*i).Contains(ob.GetLink()) {
continue
}
*i = append(*i, ob.GetLink())
}
return nil
}
func (i *IRIs) Collection() ItemCollection {
res := make(ItemCollection, len(*i))
for k, iri := range *i {
res[k] = iri
}
return res
}
func (i *IRIs) Count() uint {
return uint(len(*i))
}
// Contains verifies if IRIs array contains the received one
func (i IRIs) Contains(r Item) bool {
if len(i) == 0 {
return false
}
for _, iri := range i {
if r.GetLink().Equals(iri, false) {
return true
}
}
return false
}
func validURL(u *url.URL) bool {
return len(u.Scheme) > 0 && len(u.Host) > 0
}
func stripFragment(u string) string {
p := strings.Index(u, "#")
if p <= 0 {
p = len(u)
}
return u[:p]
}
func stripScheme(u string) string {
p := strings.Index(u, "://")
if p < 0 {
p = 0
}
return u[p:]
}
func irisEqual(i1, i2 IRI, checkScheme bool) bool {
u, e := i1.URL()
uw, ew := i2.URL()
if e != nil || ew != nil || !validURL(u) || !validURL(uw) {
return strings.EqualFold(i1.String(), i2.String())
}
if checkScheme {
if !strings.EqualFold(u.Scheme, uw.Scheme) {
return false
}
}
if !strings.EqualFold(u.Host, uw.Host) {
return false
}
if !(u.Path == "/" && uw.Path == "" || u.Path == "" && uw.Path == "/") &&
!strings.EqualFold(filepath.Clean(u.Path), filepath.Clean(uw.Path)) {
return false
}
uq := u.Query()
uwq := uw.Query()
if len(uq) != len(uwq) {
return false
}
for k, uqv := range uq {
uwqv, ok := uwq[k]
if !ok {
return false
}
if len(uqv) != len(uwqv) {
return false
}
for _, uqvv := range uqv {
eq := false
for _, uwqvv := range uwqv {
if uwqvv == uqvv {
eq = true
continue
}
}
if !eq {
return false
}
}
}
return true
}
// Equals verifies if our receiver IRI is equals with the "with" IRI
func (i IRI) Equals(with IRI, checkScheme bool) bool {
is := stripFragment(string(i))
ws := stripFragment(string(with))
if !checkScheme {
is = stripScheme(is)
ws = stripScheme(ws)
}
if strings.EqualFold(is, ws) {
return true
}
return irisEqual(i, with, checkScheme)
}
func hostSplit(h string) (string, string) {
pieces := strings.Split(h, ":")
if len(pieces) == 0 {
return "", ""
}
if len(pieces) == 1 {
return pieces[0], ""
}
return pieces[0], pieces[1]
}
func (i IRI) Contains(what IRI, checkScheme bool) bool {
u, e := i.URL()
uw, ew := what.URL()
if e != nil || ew != nil {
return strings.Contains(i.String(), what.String())
}
if checkScheme {
if u.Scheme != uw.Scheme {
return false
}
}
uHost, _ := hostSplit(u.Host)
uwHost, _ := hostSplit(uw.Host)
if uHost != uwHost {
return false
}
p := u.Path
if p != "" {
p = filepath.Clean(p)
}
pw := uw.Path
if pw != "" {
pw = filepath.Clean(pw)
}
return strings.Contains(p, pw)
}
func (i IRI) ItemsMatch(col ...Item) bool {
for _, it := range col {
if match := it.GetLink().Contains(i, false); !match {
return false
}
}
return true
}