This repository has been archived by the owner on Feb 16, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpost.go
365 lines (317 loc) · 9.67 KB
/
post.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
package tent
import (
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"strconv"
"strings"
"github.com/cupcake/sfilter"
"github.com/tent/canonical-json-go"
"github.com/tent/hawk-go"
"github.com/tent/http-link-go"
)
type PostRef struct {
Entity string `json:"entity,omitempty" sfilter:"version"`
OriginalEntity string `json:"original_entity,omitempty"`
Post string `json:"post,omitempty" sfilter:"version"`
Version string `json:"version,omitempty" sfilter:"version"`
Type string `json:"type,omitempty" sfilter:"version"`
}
type PostMention struct {
Entity string `json:"entity,omitempty" sfilter:"version"`
OriginalEntity string `json:"original_entity,omitempty"`
Post string `json:"post,omitempty" sfilter:"version"`
Version string `json:"version,omitempty" sfilter:"version"`
Type string `json:"type,omitempty" sfilter:"version"`
PublicFlag *bool `json:"public,omitempty"` // nil or true is public == true; false is public == false
}
func (mention *PostMention) Public() bool {
return mention.PublicFlag == nil || *mention.PublicFlag
}
type PostAttachment struct {
Name string `json:"name" sfilter:"version"`
Category string `json:"category" sfilter:"version"`
ContentType string `json:"content_type" sfilter:"version"`
Size int64 `json:"size,omitempty" sfilter:"version"`
Digest string `json:"digest,omitempty" sfilter:"version"`
// Include Data to upload a new attachment with the post
Data ReadLenSeeker `json:"-"`
entity string
body io.ReadCloser
client *Client
}
// Read downloads and reads from the attachment body.
// The attachment must have be initialized by downloading the containing post
// from the server in order to use Read.
func (att *PostAttachment) Read(p []byte) (int, error) {
if att.client == nil || att.Digest == "" || att.entity == "" {
return 0, errors.New("tent: improperly initialized attachment")
}
if att.body == nil {
var err error
att.body, _, err = att.client.GetAttachment(att.entity, att.Digest)
if err != nil {
return 0, err
}
}
return att.body.Read(p)
}
func (att *PostAttachment) Close() error {
if att.body == nil {
return nil
}
return att.body.Close()
}
type PostPermissions struct {
PublicFlag *bool `json:"public,omitempty"` // nil or true is public == true; false is public == false
Groups []string `json:"groups,omitempty"`
Entities []string `json:"entities,omitempty"`
}
func (perm *PostPermissions) Public() bool {
return perm == nil || perm.PublicFlag == nil || *perm.PublicFlag
}
type PostApp struct {
Name string `json:"name,omitempty" sfilter:"version"`
URL string `json:"url,omitempty" sfilter:"version"`
ID string `json:"id,omitempty"`
}
type PostVersionParent struct {
Entity string `json:"entity,omitempty" sfilter:"version"`
OriginalEntity string `json:"original_entity,omitempty"`
Post string `json:"post,omitempty" sfilter:"version"`
Version string `json:"version" sfilter:"version"`
}
type PostVersion struct {
ID string `json:"id,omitempty"`
Parents []PostVersionParent `json:"parents,omitempty" sfilter:"version"`
Message string `json:"message,omitempty" sfilter:"version"`
PublishedAt *UnixTime `json:"published_at,omitempty" sfilter:"version"`
ReceivedAt *UnixTime `json:"received_at,omitempty"`
// Used in post version and children lists
Type string `json:"type,omitempty"`
Entity string `json:"entity,omitempty"`
Post string `json:"post,omitempty"`
}
type PostLicense struct {
URL string `json:"url" sfilter:"version"`
}
type Post struct {
ID string `json:"id,omitempty" sfilter:"version"`
Entity string `json:"entity,omitempty" sfilter:"version"`
OriginalEntity string `json:"original_entity,omitempty"`
Type string `json:"type" sfilter:"version"`
Content json.RawMessage `json:"content,omitempty" sfilter:"version"`
Version *PostVersion `json:"version,omitempty" sfilter:"version"`
Refs []PostRef `json:"refs,omitempty" sfilter:"version"`
Mentions []PostMention `json:"mentions,omitempty" sfilter:"version"`
Licenses []PostLicense `json:"licenses,omitempty" sfilter:"version"`
Attachments []*PostAttachment `json:"attachments,omitempty" sfilter:"version"`
Permissions *PostPermissions `json:"permissions,omitempty"`
App *PostApp `json:"app,omitempty" sfilter:"version"`
ReceivedAt *UnixTime `json:"received_at,omitempty"`
PublishedAt *UnixTime `json:"published_at,omitempty" sfilter:"version"`
Links []link.Link `json:"-"`
Notification bool `json:"-"`
}
type PostEnvelope struct {
Post *Post `json:"post"`
Refs []Post `json:"refs"`
}
const RelCredentials = "https://tent.io/rels/credentials"
var ErrMissingCredentialsLink = errors.New("tent: missing credentials link")
type PostRequest struct {
MaxRefs int
}
func (client *Client) GetPost(entity, id, version string, r *PostRequest) (*PostEnvelope, error) {
post := &PostEnvelope{}
header := make(http.Header)
header.Set("Accept", MediaTypePost)
urlFunc := func(server *MetaPostServer) string {
u := server.URLs.PostURL(entity, id, version)
if r != nil && r.MaxRefs > 0 {
u = appendQuery(u, "max_refs="+strconv.Itoa(r.MaxRefs))
}
return u
}
_, err := client.requestJSON("GET", urlFunc, header, nil, post)
if err != nil || post.Post == nil {
if err == nil {
err = newResponseError(ErrBadData, nil)
}
return nil, err
}
post.Post.initAttachments(client)
for _, p := range post.Refs {
p.initAttachments(client)
}
return post, err
}
func GetPost(url string) (*PostEnvelope, error) {
req, err := NewRequest("GET", url, nil, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", MediaTypePost)
res, err := HTTP.Do(req)
if err != nil {
return nil, newRequestError(err, req)
}
defer res.Body.Close()
if res.StatusCode != 200 {
return nil, newResponseError(ErrBadStatusCode, res)
}
post := &PostEnvelope{}
if ok := timeoutRead(res.Body, func() {
err = json.NewDecoder(res.Body).Decode(post)
}); !ok {
return nil, newResponseError(ErrReadTimeout, res)
}
if post.Post == nil {
return nil, newResponseError(ErrBadData, res)
}
c := &Client{}
post.Post.initAttachments(c)
for _, p := range post.Refs {
p.initAttachments(c)
}
return post, err
}
func (post *Post) LinkedCredentials() (*hawk.Credentials, *Post, error) {
var credsPostURL string
for _, l := range post.Links {
if l.Rel == RelCredentials {
credsPostURL = l.URI
break
}
}
if credsPostURL == "" {
return nil, nil, ErrMissingCredentialsLink
}
p, err := GetPost(credsPostURL)
if err != nil {
return nil, nil, err
}
creds, err := ParseCredentials(p.Post)
return creds, p.Post, err
}
func (post *Post) hasNewAttachments() bool {
for _, att := range post.Attachments {
if att.Data != nil {
return true
}
}
return false
}
func (post *Post) CalculateVersion() (string, []byte, error) {
data, _ := sfilter.Map(post, "version")
if post.OriginalEntity != "" {
data["entity"] = post.OriginalEntity
}
if data["mentions"] != nil {
postMentions := data["mentions"].([]map[string]interface{})
mentions := make([]map[string]interface{}, 0, len(postMentions))
for i, mention := range post.Mentions {
if !mention.Public() {
continue
}
if mention.Post == post.ID {
delete(postMentions[i], "post")
}
if mention.OriginalEntity != "" {
postMentions[i]["entity"] = mention.OriginalEntity
}
if data["entity"] == postMentions[i]["entity"] {
delete(postMentions[i], "entity")
}
mentions = append(mentions, postMentions[i])
}
data["mentions"] = mentions
if len(mentions) == 0 {
delete(data, "mentions")
}
}
if data["refs"] != nil {
refs := data["refs"].([]map[string]interface{})
for i, ref := range post.Refs {
if ref.Post == post.ID {
delete(refs[i], "post")
}
if ref.OriginalEntity != "" {
refs[i]["entity"] = ref.OriginalEntity
}
if data["entity"] == refs[i]["entity"] {
delete(refs[i], "entity")
}
}
}
if len(post.Version.Parents) > 0 {
version := data["version"].(map[string]interface{})
parents := version["parents"].([]map[string]interface{})
for i, parent := range post.Version.Parents {
if parent.Post == post.ID {
delete(parents[i], "post")
}
if parent.OriginalEntity != "" {
parents[i]["entity"] = parent.OriginalEntity
}
if data["entity"] == parents[i]["entity"] {
delete(parents[i], "entity")
}
}
}
if len(post.Content) < 3 {
delete(data, "content")
}
canonicalJSON, err := cjson.Marshal(data)
if err != nil {
return "", nil, err
}
h := sha512.New()
h.Write(canonicalJSON)
return "sha512t256-" + hex.EncodeToString(h.Sum(nil)[:32]), canonicalJSON, nil
}
func (post *Post) contentType() string {
params := map[string]string{"type": post.Type}
if post.Notification {
params["rel"] = "https://tent.io/rels/notification"
}
return mime.FormatMediaType(MediaTypePost, params)
}
func (post *Post) initAttachments(client *Client) {
if post == nil {
return
}
for _, att := range post.Attachments {
att.entity = post.Entity
att.client = client
}
}
func SplitType(typ string) (base string, fragment string) {
s := strings.SplitN(typ, "#", 2)
base = s[0]
if len(s) > 1 {
fragment = s[1]
}
return
}
func TypeBase(typ string) string {
base, _ := SplitType(typ)
return base
}
func ParseCredentials(post *Post) (*hawk.Credentials, error) {
creds := &hawk.Credentials{ID: post.ID, Hash: sha256.New}
temp := &Credentials{}
err := json.Unmarshal(post.Content, temp)
creds.Key = temp.HawkKey
for _, mention := range post.Mentions {
if mention.Type == PostTypeApp {
creds.App = mention.Post
}
}
return creds, err
}