github.com/masterhung0112/hk_server/v5@v5.0.0-20220302090640-ec71aef15e1c/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/masterhung0112/hk_server/v5/app" 13 "github.com/masterhung0112/hk_server/v5/app/request" 14 "github.com/masterhung0112/hk_server/v5/model" 15 "github.com/masterhung0112/hk_server/v5/utils" 16 "github.com/masterhung0112/hk_server/v5/utils/fileutils" 17 ) 18 19 type AutoPostCreator struct { 20 a *app.App 21 channelid string 22 userid string 23 Fuzzy bool 24 TextLength utils.Range 25 HasImage bool 26 ImageFilenames []string 27 Users []string 28 Mentions utils.Range 29 Tags utils.Range 30 } 31 32 // Automatic poster used for testing 33 func NewAutoPostCreator(a *app.App, channelid, userid string) *AutoPostCreator { 34 return &AutoPostCreator{ 35 a: a, 36 channelid: channelid, 37 userid: userid, 38 Fuzzy: false, 39 TextLength: utils.Range{Begin: 100, End: 200}, 40 HasImage: false, 41 ImageFilenames: TestImageFileNames, 42 Users: []string{}, 43 Mentions: utils.Range{Begin: 0, End: 5}, 44 Tags: utils.Range{Begin: 0, End: 7}, 45 } 46 } 47 48 func (cfg *AutoPostCreator) UploadTestFile(c *request.Context) ([]string, error) { 49 filename := cfg.ImageFilenames[utils.RandIntFromRange(utils.Range{Begin: 0, End: len(cfg.ImageFilenames) - 1})] 50 51 path, _ := fileutils.FindDir("tests") 52 file, err := os.Open(filepath.Join(path, filename)) 53 if err != nil { 54 return nil, err 55 } 56 defer file.Close() 57 58 data := &bytes.Buffer{} 59 _, err = io.Copy(data, file) 60 if err != nil { 61 return nil, err 62 } 63 64 fileResp, err2 := cfg.a.UploadFile(c, data.Bytes(), cfg.channelid, filename) 65 if err2 != nil { 66 return nil, err2 67 } 68 69 return []string{fileResp.Id}, nil 70 } 71 72 func (cfg *AutoPostCreator) CreateRandomPost(c *request.Context) (*model.Post, error) { 73 return cfg.CreateRandomPostNested(c, "", "") 74 } 75 76 func (cfg *AutoPostCreator) CreateRandomPostNested(c *request.Context, parentId, rootId string) (*model.Post, error) { 77 var fileIDs []string 78 if cfg.HasImage { 79 var err error 80 fileIDs, err = cfg.UploadTestFile(c) 81 if err != nil { 82 return nil, err 83 } 84 } 85 86 var postText string 87 if cfg.Fuzzy { 88 postText = utils.FuzzPost() 89 } else { 90 postText = utils.RandomText(cfg.TextLength, cfg.Tags, cfg.Mentions, cfg.Users) 91 } 92 93 post := &model.Post{ 94 ChannelId: cfg.channelid, 95 UserId: cfg.userid, 96 ParentId: parentId, 97 RootId: rootId, 98 Message: postText, 99 FileIds: fileIDs, 100 } 101 rpost, err := cfg.a.CreatePostMissingChannel(c, post, true) 102 if err != nil { 103 return nil, err 104 } 105 return rpost, nil 106 }