github.com/gigforks/mattermost-server@v4.9.1-0.20180619094218-800d97fa55d0+incompatible/model/post_list.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 "sort" 10 ) 11 12 type PostList struct { 13 Order []string `json:"order"` 14 Posts map[string]*Post `json:"posts"` 15 } 16 17 func NewPostList() *PostList { 18 return &PostList{ 19 Order: make([]string, 0), 20 Posts: make(map[string]*Post), 21 } 22 } 23 24 func (o *PostList) WithRewrittenImageURLs(f func(string) string) *PostList { 25 copy := *o 26 copy.Posts = make(map[string]*Post) 27 for id, post := range o.Posts { 28 copy.Posts[id] = post.WithRewrittenImageURLs(f) 29 } 30 return © 31 } 32 33 func (o *PostList) StripActionIntegrations() { 34 posts := o.Posts 35 o.Posts = make(map[string]*Post) 36 for id, post := range posts { 37 pcopy := *post 38 pcopy.StripActionIntegrations() 39 o.Posts[id] = &pcopy 40 } 41 } 42 43 func (o *PostList) ToJson() string { 44 copy := *o 45 copy.StripActionIntegrations() 46 b, err := json.Marshal(©) 47 if err != nil { 48 return "" 49 } else { 50 return string(b) 51 } 52 } 53 54 func (o *PostList) MakeNonNil() { 55 if o.Order == nil { 56 o.Order = make([]string, 0) 57 } 58 59 if o.Posts == nil { 60 o.Posts = make(map[string]*Post) 61 } 62 63 for _, v := range o.Posts { 64 v.MakeNonNil() 65 } 66 } 67 68 func (o *PostList) AddOrder(id string) { 69 70 if o.Order == nil { 71 o.Order = make([]string, 0, 128) 72 } 73 74 o.Order = append(o.Order, id) 75 } 76 77 func (o *PostList) AddPost(post *Post) { 78 79 if o.Posts == nil { 80 o.Posts = make(map[string]*Post) 81 } 82 83 o.Posts[post.Id] = post 84 } 85 86 func (o *PostList) Extend(other *PostList) { 87 for _, postId := range other.Order { 88 if _, ok := o.Posts[postId]; !ok { 89 o.AddPost(other.Posts[postId]) 90 o.AddOrder(postId) 91 } 92 } 93 } 94 95 func (o *PostList) SortByCreateAt() { 96 sort.Slice(o.Order, func(i, j int) bool { 97 return o.Posts[o.Order[i]].CreateAt > o.Posts[o.Order[j]].CreateAt 98 }) 99 } 100 101 func (o *PostList) Etag() string { 102 103 id := "0" 104 var t int64 = 0 105 106 for _, v := range o.Posts { 107 if v.UpdateAt > t { 108 t = v.UpdateAt 109 id = v.Id 110 } else if v.UpdateAt == t && v.Id > id { 111 t = v.UpdateAt 112 id = v.Id 113 } 114 } 115 116 orderId := "" 117 if len(o.Order) > 0 { 118 orderId = o.Order[0] 119 } 120 121 return Etag(orderId, id, t) 122 } 123 124 func (o *PostList) IsChannelId(channelId string) bool { 125 for _, v := range o.Posts { 126 if v.ChannelId != channelId { 127 return false 128 } 129 } 130 131 return true 132 } 133 134 func PostListFromJson(data io.Reader) *PostList { 135 var o *PostList 136 json.NewDecoder(data).Decode(&o) 137 return o 138 }