github.com/dschalla/mattermost-server@v4.8.1-rc1+incompatible/app/auto_posts.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See License.txt for license information. 3 4 package app 5 6 import ( 7 "bytes" 8 "io" 9 "os" 10 11 "github.com/mattermost/mattermost-server/model" 12 "github.com/mattermost/mattermost-server/utils" 13 ) 14 15 type AutoPostCreator struct { 16 client *model.Client 17 channelid string 18 Fuzzy bool 19 TextLength utils.Range 20 HasImage bool 21 ImageFilenames []string 22 Users []string 23 Mentions utils.Range 24 Tags utils.Range 25 } 26 27 // Automatic poster used for testing 28 func NewAutoPostCreator(client *model.Client, channelid string) *AutoPostCreator { 29 return &AutoPostCreator{ 30 client: client, 31 channelid: channelid, 32 Fuzzy: false, 33 TextLength: utils.Range{Begin: 100, End: 200}, 34 HasImage: false, 35 ImageFilenames: TEST_IMAGE_FILENAMES, 36 Users: []string{}, 37 Mentions: utils.Range{Begin: 0, End: 5}, 38 Tags: utils.Range{Begin: 0, End: 7}, 39 } 40 } 41 42 func (cfg *AutoPostCreator) UploadTestFile() ([]string, bool) { 43 filename := cfg.ImageFilenames[utils.RandIntFromRange(utils.Range{Begin: 0, End: len(cfg.ImageFilenames) - 1})] 44 45 path, _ := utils.FindDir("web/static/images") 46 file, err := os.Open(path + "/" + filename) 47 if err != nil { 48 return nil, false 49 } 50 defer file.Close() 51 52 data := &bytes.Buffer{} 53 _, err = io.Copy(data, file) 54 if err != nil { 55 return nil, false 56 } 57 58 resp, appErr := cfg.client.UploadPostAttachment(data.Bytes(), cfg.channelid, filename) 59 if appErr != nil { 60 return nil, false 61 } 62 63 return []string{resp.FileInfos[0].Id}, true 64 } 65 66 func (cfg *AutoPostCreator) CreateRandomPost() (*model.Post, bool) { 67 var fileIds []string 68 if cfg.HasImage { 69 var err1 bool 70 fileIds, err1 = cfg.UploadTestFile() 71 if !err1 { 72 return nil, false 73 } 74 } 75 76 var postText string 77 if cfg.Fuzzy { 78 postText = utils.FuzzPost() 79 } else { 80 postText = utils.RandomText(cfg.TextLength, cfg.Tags, cfg.Mentions, cfg.Users) 81 } 82 83 post := &model.Post{ 84 ChannelId: cfg.channelid, 85 Message: postText, 86 FileIds: fileIds} 87 result, err2 := cfg.client.CreatePost(post) 88 if err2 != nil { 89 return nil, false 90 } 91 return result.Data.(*model.Post), true 92 } 93 94 func (cfg *AutoPostCreator) CreateTestPosts(rangePosts utils.Range) ([]*model.Post, bool) { 95 numPosts := utils.RandIntFromRange(rangePosts) 96 posts := make([]*model.Post, numPosts) 97 98 for i := 0; i < numPosts; i++ { 99 var err bool 100 posts[i], err = cfg.CreateRandomPost() 101 if !err { 102 return posts, false 103 } 104 } 105 106 return posts, true 107 }