github.com/jfrerich/mattermost-server@v5.8.0-rc2+incompatible/model/post.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See License.txt for license information. 3 4 package model 5 6 import ( 7 "encoding/json" 8 "io" 9 "net/http" 10 "sort" 11 "strings" 12 "unicode/utf8" 13 14 "github.com/mattermost/mattermost-server/utils/markdown" 15 ) 16 17 const ( 18 POST_SYSTEM_MESSAGE_PREFIX = "system_" 19 POST_DEFAULT = "" 20 POST_SLACK_ATTACHMENT = "slack_attachment" 21 POST_SYSTEM_GENERIC = "system_generic" 22 POST_JOIN_LEAVE = "system_join_leave" // Deprecated, use POST_JOIN_CHANNEL or POST_LEAVE_CHANNEL instead 23 POST_JOIN_CHANNEL = "system_join_channel" 24 POST_LEAVE_CHANNEL = "system_leave_channel" 25 POST_JOIN_TEAM = "system_join_team" 26 POST_LEAVE_TEAM = "system_leave_team" 27 POST_AUTO_RESPONDER = "system_auto_responder" 28 POST_ADD_REMOVE = "system_add_remove" // Deprecated, use POST_ADD_TO_CHANNEL or POST_REMOVE_FROM_CHANNEL instead 29 POST_ADD_TO_CHANNEL = "system_add_to_channel" 30 POST_REMOVE_FROM_CHANNEL = "system_remove_from_channel" 31 POST_MOVE_CHANNEL = "system_move_channel" 32 POST_ADD_TO_TEAM = "system_add_to_team" 33 POST_REMOVE_FROM_TEAM = "system_remove_from_team" 34 POST_HEADER_CHANGE = "system_header_change" 35 POST_DISPLAYNAME_CHANGE = "system_displayname_change" 36 POST_CONVERT_CHANNEL = "system_convert_channel" 37 POST_PURPOSE_CHANGE = "system_purpose_change" 38 POST_CHANNEL_DELETED = "system_channel_deleted" 39 POST_EPHEMERAL = "system_ephemeral" 40 POST_CHANGE_CHANNEL_PRIVACY = "system_change_chan_privacy" 41 POST_FILEIDS_MAX_RUNES = 150 42 POST_FILENAMES_MAX_RUNES = 4000 43 POST_HASHTAGS_MAX_RUNES = 1000 44 POST_MESSAGE_MAX_RUNES_V1 = 4000 45 POST_MESSAGE_MAX_BYTES_V2 = 65535 // Maximum size of a TEXT column in MySQL 46 POST_MESSAGE_MAX_RUNES_V2 = POST_MESSAGE_MAX_BYTES_V2 / 4 // Assume a worst-case representation 47 POST_PROPS_MAX_RUNES = 8000 48 POST_PROPS_MAX_USER_RUNES = POST_PROPS_MAX_RUNES - 400 // Leave some room for system / pre-save modifications 49 POST_CUSTOM_TYPE_PREFIX = "custom_" 50 PROPS_ADD_CHANNEL_MEMBER = "add_channel_member" 51 POST_PROPS_ADDED_USER_ID = "addedUserId" 52 POST_PROPS_DELETE_BY = "deleteBy" 53 ) 54 55 type Post struct { 56 Id string `json:"id"` 57 CreateAt int64 `json:"create_at"` 58 UpdateAt int64 `json:"update_at"` 59 EditAt int64 `json:"edit_at"` 60 DeleteAt int64 `json:"delete_at"` 61 IsPinned bool `json:"is_pinned"` 62 UserId string `json:"user_id"` 63 ChannelId string `json:"channel_id"` 64 RootId string `json:"root_id"` 65 ParentId string `json:"parent_id"` 66 OriginalId string `json:"original_id"` 67 68 Message string `json:"message"` 69 70 // MessageSource will contain the message as submitted by the user if Message has been modified 71 // by Mattermost for presentation (e.g if an image proxy is being used). It should be used to 72 // populate edit boxes if present. 73 MessageSource string `json:"message_source,omitempty" db:"-"` 74 75 Type string `json:"type"` 76 Props StringInterface `json:"props"` 77 Hashtags string `json:"hashtags"` 78 Filenames StringArray `json:"filenames,omitempty"` // Deprecated, do not use this field any more 79 FileIds StringArray `json:"file_ids,omitempty"` 80 PendingPostId string `json:"pending_post_id" db:"-"` 81 HasReactions bool `json:"has_reactions,omitempty"` 82 83 // Transient data populated before sending a post to the client 84 Metadata *PostMetadata `json:"metadata,omitempty" db:"-"` 85 } 86 87 type PostEphemeral struct { 88 UserID string `json:"user_id"` 89 Post *Post `json:"post"` 90 } 91 92 type PostPatch struct { 93 IsPinned *bool `json:"is_pinned"` 94 Message *string `json:"message"` 95 Props *StringInterface `json:"props"` 96 FileIds *StringArray `json:"file_ids"` 97 HasReactions *bool `json:"has_reactions"` 98 } 99 100 type SearchParameter struct { 101 Terms *string `json:"terms"` 102 IsOrSearch *bool `json:"is_or_search"` 103 TimeZoneOffset *int `json:"time_zone_offset"` 104 Page *int `json:"page"` 105 PerPage *int `json:"per_page"` 106 IncludeDeletedChannels *bool `json:"include_deleted_channels"` 107 } 108 109 func (o *PostPatch) WithRewrittenImageURLs(f func(string) string) *PostPatch { 110 copy := *o 111 if copy.Message != nil { 112 *copy.Message = RewriteImageURLs(*o.Message, f) 113 } 114 return © 115 } 116 117 type PostForExport struct { 118 Post 119 TeamName string 120 ChannelName string 121 Username string 122 ReplyCount int 123 } 124 125 type ReplyForExport struct { 126 Post 127 Username string 128 } 129 130 type PostForIndexing struct { 131 Post 132 TeamId string `json:"team_id"` 133 ParentCreateAt *int64 `json:"parent_create_at"` 134 } 135 136 // Clone shallowly copies the post. 137 func (o *Post) Clone() *Post { 138 copy := *o 139 return © 140 } 141 142 func (o *Post) ToJson() string { 143 copy := o.Clone() 144 copy.StripActionIntegrations() 145 b, _ := json.Marshal(copy) 146 return string(b) 147 } 148 149 func (o *Post) ToUnsanitizedJson() string { 150 b, _ := json.Marshal(o) 151 return string(b) 152 } 153 154 func PostFromJson(data io.Reader) *Post { 155 var o *Post 156 json.NewDecoder(data).Decode(&o) 157 return o 158 } 159 160 func (o *Post) Etag() string { 161 return Etag(o.Id, o.UpdateAt) 162 } 163 164 func (o *Post) IsValid(maxPostSize int) *AppError { 165 166 if len(o.Id) != 26 { 167 return NewAppError("Post.IsValid", "model.post.is_valid.id.app_error", nil, "", http.StatusBadRequest) 168 } 169 170 if o.CreateAt == 0 { 171 return NewAppError("Post.IsValid", "model.post.is_valid.create_at.app_error", nil, "id="+o.Id, http.StatusBadRequest) 172 } 173 174 if o.UpdateAt == 0 { 175 return NewAppError("Post.IsValid", "model.post.is_valid.update_at.app_error", nil, "id="+o.Id, http.StatusBadRequest) 176 } 177 178 if len(o.UserId) != 26 { 179 return NewAppError("Post.IsValid", "model.post.is_valid.user_id.app_error", nil, "", http.StatusBadRequest) 180 } 181 182 if len(o.ChannelId) != 26 { 183 return NewAppError("Post.IsValid", "model.post.is_valid.channel_id.app_error", nil, "", http.StatusBadRequest) 184 } 185 186 if !(len(o.RootId) == 26 || len(o.RootId) == 0) { 187 return NewAppError("Post.IsValid", "model.post.is_valid.root_id.app_error", nil, "", http.StatusBadRequest) 188 } 189 190 if !(len(o.ParentId) == 26 || len(o.ParentId) == 0) { 191 return NewAppError("Post.IsValid", "model.post.is_valid.parent_id.app_error", nil, "", http.StatusBadRequest) 192 } 193 194 if len(o.ParentId) == 26 && len(o.RootId) == 0 { 195 return NewAppError("Post.IsValid", "model.post.is_valid.root_parent.app_error", nil, "", http.StatusBadRequest) 196 } 197 198 if !(len(o.OriginalId) == 26 || len(o.OriginalId) == 0) { 199 return NewAppError("Post.IsValid", "model.post.is_valid.original_id.app_error", nil, "", http.StatusBadRequest) 200 } 201 202 if utf8.RuneCountInString(o.Message) > maxPostSize { 203 return NewAppError("Post.IsValid", "model.post.is_valid.msg.app_error", nil, "id="+o.Id, http.StatusBadRequest) 204 } 205 206 if utf8.RuneCountInString(o.Hashtags) > POST_HASHTAGS_MAX_RUNES { 207 return NewAppError("Post.IsValid", "model.post.is_valid.hashtags.app_error", nil, "id="+o.Id, http.StatusBadRequest) 208 } 209 210 switch o.Type { 211 case 212 POST_DEFAULT, 213 POST_JOIN_LEAVE, 214 POST_AUTO_RESPONDER, 215 POST_ADD_REMOVE, 216 POST_JOIN_CHANNEL, 217 POST_LEAVE_CHANNEL, 218 POST_JOIN_TEAM, 219 POST_LEAVE_TEAM, 220 POST_ADD_TO_CHANNEL, 221 POST_REMOVE_FROM_CHANNEL, 222 POST_MOVE_CHANNEL, 223 POST_ADD_TO_TEAM, 224 POST_REMOVE_FROM_TEAM, 225 POST_SLACK_ATTACHMENT, 226 POST_HEADER_CHANGE, 227 POST_PURPOSE_CHANGE, 228 POST_DISPLAYNAME_CHANGE, 229 POST_CONVERT_CHANNEL, 230 POST_CHANNEL_DELETED, 231 POST_CHANGE_CHANNEL_PRIVACY: 232 default: 233 if !strings.HasPrefix(o.Type, POST_CUSTOM_TYPE_PREFIX) { 234 return NewAppError("Post.IsValid", "model.post.is_valid.type.app_error", nil, "id="+o.Type, http.StatusBadRequest) 235 } 236 } 237 238 if utf8.RuneCountInString(ArrayToJson(o.Filenames)) > POST_FILENAMES_MAX_RUNES { 239 return NewAppError("Post.IsValid", "model.post.is_valid.filenames.app_error", nil, "id="+o.Id, http.StatusBadRequest) 240 } 241 242 if utf8.RuneCountInString(ArrayToJson(o.FileIds)) > POST_FILEIDS_MAX_RUNES { 243 return NewAppError("Post.IsValid", "model.post.is_valid.file_ids.app_error", nil, "id="+o.Id, http.StatusBadRequest) 244 } 245 246 if utf8.RuneCountInString(StringInterfaceToJson(o.Props)) > POST_PROPS_MAX_RUNES { 247 return NewAppError("Post.IsValid", "model.post.is_valid.props.app_error", nil, "id="+o.Id, http.StatusBadRequest) 248 } 249 250 return nil 251 } 252 253 func (o *Post) SanitizeProps() { 254 membersToSanitize := []string{ 255 PROPS_ADD_CHANNEL_MEMBER, 256 } 257 258 for _, member := range membersToSanitize { 259 if _, ok := o.Props[member]; ok { 260 delete(o.Props, member) 261 } 262 } 263 } 264 265 func (o *Post) PreSave() { 266 if o.Id == "" { 267 o.Id = NewId() 268 } 269 270 o.OriginalId = "" 271 272 if o.CreateAt == 0 { 273 o.CreateAt = GetMillis() 274 } 275 276 o.UpdateAt = o.CreateAt 277 o.PreCommit() 278 } 279 280 func (o *Post) PreCommit() { 281 if o.Props == nil { 282 o.Props = make(map[string]interface{}) 283 } 284 285 if o.Filenames == nil { 286 o.Filenames = []string{} 287 } 288 289 if o.FileIds == nil { 290 o.FileIds = []string{} 291 } 292 293 o.GenerateActionIds() 294 295 // There's a rare bug where the client sends up duplicate FileIds so protect against that 296 o.FileIds = RemoveDuplicateStrings(o.FileIds) 297 } 298 299 func (o *Post) MakeNonNil() { 300 if o.Props == nil { 301 o.Props = make(map[string]interface{}) 302 } 303 } 304 305 func (o *Post) AddProp(key string, value interface{}) { 306 307 o.MakeNonNil() 308 309 o.Props[key] = value 310 } 311 312 func (o *Post) IsSystemMessage() bool { 313 return len(o.Type) >= len(POST_SYSTEM_MESSAGE_PREFIX) && o.Type[:len(POST_SYSTEM_MESSAGE_PREFIX)] == POST_SYSTEM_MESSAGE_PREFIX 314 } 315 316 func (p *Post) Patch(patch *PostPatch) { 317 if patch.IsPinned != nil { 318 p.IsPinned = *patch.IsPinned 319 } 320 321 if patch.Message != nil { 322 p.Message = *patch.Message 323 } 324 325 if patch.Props != nil { 326 p.Props = *patch.Props 327 } 328 329 if patch.FileIds != nil { 330 p.FileIds = *patch.FileIds 331 } 332 333 if patch.HasReactions != nil { 334 p.HasReactions = *patch.HasReactions 335 } 336 } 337 338 func (o *PostPatch) ToJson() string { 339 b, err := json.Marshal(o) 340 if err != nil { 341 return "" 342 } 343 344 return string(b) 345 } 346 347 func PostPatchFromJson(data io.Reader) *PostPatch { 348 decoder := json.NewDecoder(data) 349 var post PostPatch 350 err := decoder.Decode(&post) 351 if err != nil { 352 return nil 353 } 354 355 return &post 356 } 357 358 func (o *SearchParameter) SearchParameterToJson() string { 359 b, err := json.Marshal(o) 360 if err != nil { 361 return "" 362 } 363 364 return string(b) 365 } 366 367 func SearchParameterFromJson(data io.Reader) *SearchParameter { 368 decoder := json.NewDecoder(data) 369 var searchParam SearchParameter 370 err := decoder.Decode(&searchParam) 371 if err != nil { 372 return nil 373 } 374 375 return &searchParam 376 } 377 378 func (o *Post) ChannelMentions() []string { 379 return ChannelMentions(o.Message) 380 } 381 382 func (o *Post) Attachments() []*SlackAttachment { 383 if attachments, ok := o.Props["attachments"].([]*SlackAttachment); ok { 384 return attachments 385 } 386 var ret []*SlackAttachment 387 if attachments, ok := o.Props["attachments"].([]interface{}); ok { 388 for _, attachment := range attachments { 389 if enc, err := json.Marshal(attachment); err == nil { 390 var decoded SlackAttachment 391 if json.Unmarshal(enc, &decoded) == nil { 392 ret = append(ret, &decoded) 393 } 394 } 395 } 396 } 397 return ret 398 } 399 400 var markdownDestinationEscaper = strings.NewReplacer( 401 `\`, `\\`, 402 `<`, `\<`, 403 `>`, `\>`, 404 `(`, `\(`, 405 `)`, `\)`, 406 ) 407 408 // WithRewrittenImageURLs returns a new shallow copy of the post where the message has been 409 // rewritten via RewriteImageURLs. 410 func (o *Post) WithRewrittenImageURLs(f func(string) string) *Post { 411 copy := o.Clone() 412 copy.Message = RewriteImageURLs(o.Message, f) 413 if copy.MessageSource == "" && copy.Message != o.Message { 414 copy.MessageSource = o.Message 415 } 416 return copy 417 } 418 419 func (o *PostEphemeral) ToUnsanitizedJson() string { 420 b, _ := json.Marshal(o) 421 return string(b) 422 } 423 424 // RewriteImageURLs takes a message and returns a copy that has all of the image URLs replaced 425 // according to the function f. For each image URL, f will be invoked, and the resulting markdown 426 // will contain the URL returned by that invocation instead. 427 // 428 // Image URLs are destination URLs used in inline images or reference definitions that are used 429 // anywhere in the input markdown as an image. 430 func RewriteImageURLs(message string, f func(string) string) string { 431 if !strings.Contains(message, "![") { 432 return message 433 } 434 435 var ranges []markdown.Range 436 437 markdown.Inspect(message, func(blockOrInline interface{}) bool { 438 switch v := blockOrInline.(type) { 439 case *markdown.ReferenceImage: 440 ranges = append(ranges, v.ReferenceDefinition.RawDestination) 441 case *markdown.InlineImage: 442 ranges = append(ranges, v.RawDestination) 443 default: 444 return true 445 } 446 return true 447 }) 448 449 if ranges == nil { 450 return message 451 } 452 453 sort.Slice(ranges, func(i, j int) bool { 454 return ranges[i].Position < ranges[j].Position 455 }) 456 457 copyRanges := make([]markdown.Range, 0, len(ranges)) 458 urls := make([]string, 0, len(ranges)) 459 resultLength := len(message) 460 461 start := 0 462 for i, r := range ranges { 463 switch { 464 case i == 0: 465 case r.Position != ranges[i-1].Position: 466 start = ranges[i-1].End 467 default: 468 continue 469 } 470 original := message[r.Position:r.End] 471 replacement := markdownDestinationEscaper.Replace(f(markdown.Unescape(original))) 472 resultLength += len(replacement) - len(original) 473 copyRanges = append(copyRanges, markdown.Range{Position: start, End: r.Position}) 474 urls = append(urls, replacement) 475 } 476 477 result := make([]byte, resultLength) 478 479 offset := 0 480 for i, r := range copyRanges { 481 offset += copy(result[offset:], message[r.Position:r.End]) 482 offset += copy(result[offset:], urls[i]) 483 } 484 copy(result[offset:], message[ranges[len(ranges)-1].End:]) 485 486 return string(result) 487 }