github.com/haalcala/mattermost-server-change-repo@v0.0.0-20210713015153-16753fbeee5f/app/slashcommands/auto_posts.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See LICENSE.txt for license information. 3 4 package slashcommands 5 6 import ( 7 "bytes" 8 "io" 9 "os" 10 "path/filepath" 11 12 "github.com/mattermost/mattermost-server/v5/app" 13 "github.com/mattermost/mattermost-server/v5/model" 14 "github.com/mattermost/mattermost-server/v5/utils" 15 "github.com/mattermost/mattermost-server/v5/utils/fileutils" 16 ) 17 18 type AutoPostCreator struct { 19 a *app.App 20 channelid string 21 userid string 22 Fuzzy bool 23 TextLength utils.Range 24 HasImage bool 25 ImageFilenames []string 26 Users []string 27 Mentions utils.Range 28 Tags utils.Range 29 } 30 31 // Automatic poster used for testing 32 func NewAutoPostCreator(a *app.App, channelid, userid string) *AutoPostCreator { 33 return &AutoPostCreator{ 34 a: a, 35 channelid: channelid, 36 userid: userid, 37 Fuzzy: false, 38 TextLength: utils.Range{Begin: 100, End: 200}, 39 HasImage: false, 40 ImageFilenames: TestImageFileNames, 41 Users: []string{}, 42 Mentions: utils.Range{Begin: 0, End: 5}, 43 Tags: utils.Range{Begin: 0, End: 7}, 44 } 45 } 46 47 func (cfg *AutoPostCreator) UploadTestFile() ([]string, error) { 48 filename := cfg.ImageFilenames[utils.RandIntFromRange(utils.Range{Begin: 0, End: len(cfg.ImageFilenames) - 1})] 49 50 path, _ := fileutils.FindDir("tests") 51 file, err := os.Open(filepath.Join(path, filename)) 52 if err != nil { 53 return nil, err 54 } 55 defer file.Close() 56 57 data := &bytes.Buffer{} 58 _, err = io.Copy(data, file) 59 if err != nil { 60 return nil, err 61 } 62 63 fileResp, err2 := cfg.a.UploadFile(data.Bytes(), cfg.channelid, filename) 64 if err2 != nil { 65 return nil, err2 66 } 67 68 return []string{fileResp.Id}, nil 69 } 70 71 func (cfg *AutoPostCreator) CreateRandomPost() (*model.Post, error) { 72 return cfg.CreateRandomPostNested("", "") 73 } 74 75 func (cfg *AutoPostCreator) CreateRandomPostNested(parentId, rootId string) (*model.Post, error) { 76 var fileIds []string 77 if cfg.HasImage { 78 var err error 79 fileIds, err = cfg.UploadTestFile() 80 if err != nil { 81 return nil, err 82 } 83 } 84 85 var postText string 86 if cfg.Fuzzy { 87 postText = utils.FuzzPost() 88 } else { 89 postText = utils.RandomText(cfg.TextLength, cfg.Tags, cfg.Mentions, cfg.Users) 90 } 91 92 post := &model.Post{ 93 ChannelId: cfg.channelid, 94 UserId: cfg.userid, 95 ParentId: parentId, 96 RootId: rootId, 97 Message: postText, 98 FileIds: fileIds, 99 } 100 rpost, err := cfg.a.CreatePostMissingChannel(post, true) 101 if err != nil { 102 return nil, err 103 } 104 return rpost, nil 105 }