Moving slash-commands out of app package (#14979)
* Moving slash-commands out of app package * Fixing golint checks * Fixing golangci-lint * Fixing golangci-lint errors
Этот коммит содержится в:
коммит произвёл
GitHub
родитель
788c130774
Коммит
1f09d86f42
75
app/slashcommands/auto_channels.go
Обычный файл
75
app/slashcommands/auto_channels.go
Обычный файл
@@ -0,0 +1,75 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/utils"
|
||||
)
|
||||
|
||||
type AutoChannelCreator struct {
|
||||
a *app.App
|
||||
userId string
|
||||
team *model.Team
|
||||
Fuzzy bool
|
||||
DisplayNameLen utils.Range
|
||||
DisplayNameCharset string
|
||||
NameLen utils.Range
|
||||
NameCharset string
|
||||
ChannelType string
|
||||
}
|
||||
|
||||
func NewAutoChannelCreator(a *app.App, team *model.Team, userId string) *AutoChannelCreator {
|
||||
return &AutoChannelCreator{
|
||||
a: a,
|
||||
team: team,
|
||||
userId: userId,
|
||||
Fuzzy: false,
|
||||
DisplayNameLen: CHANNEL_DISPLAY_NAME_LEN,
|
||||
DisplayNameCharset: utils.ALPHANUMERIC,
|
||||
NameLen: CHANNEL_NAME_LEN,
|
||||
NameCharset: utils.LOWERCASE,
|
||||
ChannelType: CHANNEL_TYPE,
|
||||
}
|
||||
}
|
||||
|
||||
func (cfg *AutoChannelCreator) createRandomChannel() (*model.Channel, error) {
|
||||
var displayName string
|
||||
if cfg.Fuzzy {
|
||||
displayName = utils.FuzzName()
|
||||
} else {
|
||||
displayName = utils.RandomName(cfg.NameLen, cfg.NameCharset)
|
||||
}
|
||||
name := utils.RandomName(cfg.NameLen, cfg.NameCharset)
|
||||
|
||||
channel := &model.Channel{
|
||||
TeamId: cfg.team.Id,
|
||||
DisplayName: displayName,
|
||||
Name: name,
|
||||
Type: cfg.ChannelType,
|
||||
CreatorId: cfg.userId,
|
||||
}
|
||||
|
||||
channel, err := cfg.a.CreateChannel(channel, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return channel, nil
|
||||
}
|
||||
|
||||
func (cfg *AutoChannelCreator) CreateTestChannels(num utils.Range) ([]*model.Channel, error) {
|
||||
numChannels := utils.RandIntFromRange(num)
|
||||
channels := make([]*model.Channel, numChannels)
|
||||
|
||||
for i := 0; i < numChannels; i++ {
|
||||
var err error
|
||||
channels[i], err = cfg.createRandomChannel()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return channels, nil
|
||||
}
|
||||
32
app/slashcommands/auto_constants.go
Обычный файл
32
app/slashcommands/auto_constants.go
Обычный файл
@@ -0,0 +1,32 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
USER_PASSWORD = "passwd"
|
||||
CHANNEL_TYPE = model.CHANNEL_OPEN
|
||||
BTEST_TEAM_DISPLAY_NAME = "TestTeam"
|
||||
BTEST_TEAM_NAME = "z-z-testdomaina"
|
||||
BTEST_TEAM_EMAIL = "test@nowhere.com"
|
||||
BTEST_TEAM_TYPE = model.TEAM_OPEN
|
||||
BTEST_USER_NAME = "Mr. Testing Tester"
|
||||
BTEST_USER_EMAIL = "success+ttester@simulator.amazonses.com"
|
||||
BTEST_USER_PASSWORD = "passwd"
|
||||
)
|
||||
|
||||
var (
|
||||
TEAM_NAME_LEN = utils.Range{Begin: 10, End: 20}
|
||||
TEAM_DOMAIN_NAME_LEN = utils.Range{Begin: 10, End: 20}
|
||||
TEAM_EMAIL_LEN = utils.Range{Begin: 15, End: 30}
|
||||
USER_NAME_LEN = utils.Range{Begin: 5, End: 20}
|
||||
USER_EMAIL_LEN = utils.Range{Begin: 15, End: 30}
|
||||
CHANNEL_DISPLAY_NAME_LEN = utils.Range{Begin: 10, End: 20}
|
||||
CHANNEL_NAME_LEN = utils.Range{Begin: 5, End: 20}
|
||||
TEST_IMAGE_FILENAMES = []string{"test.png", "testjpg.jpg", "testgif.gif"}
|
||||
)
|
||||
113
app/slashcommands/auto_environment.go
Обычный файл
113
app/slashcommands/auto_environment.go
Обычный файл
@@ -0,0 +1,113 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/utils"
|
||||
)
|
||||
|
||||
type TestEnvironment struct {
|
||||
Teams []*model.Team
|
||||
Environments []TeamEnvironment
|
||||
}
|
||||
|
||||
func CreateTestEnvironmentWithTeams(a *app.App, client *model.Client4, rangeTeams utils.Range, rangeChannels utils.Range, rangeUsers utils.Range, rangePosts utils.Range, fuzzy bool) (TestEnvironment, error) {
|
||||
rand.Seed(time.Now().UTC().UnixNano())
|
||||
|
||||
teamCreator := NewAutoTeamCreator(client)
|
||||
teamCreator.Fuzzy = fuzzy
|
||||
teams, err := teamCreator.CreateTestTeams(rangeTeams)
|
||||
if err != nil {
|
||||
return TestEnvironment{}, err
|
||||
}
|
||||
|
||||
environment := TestEnvironment{teams, make([]TeamEnvironment, len(teams))}
|
||||
|
||||
for i, team := range teams {
|
||||
userCreator := NewAutoUserCreator(a, client, team)
|
||||
userCreator.Fuzzy = fuzzy
|
||||
randomUser, err := userCreator.createRandomUser()
|
||||
if err != nil {
|
||||
return TestEnvironment{}, err
|
||||
}
|
||||
client.LoginById(randomUser.Id, USER_PASSWORD)
|
||||
teamEnvironment, err := CreateTestEnvironmentInTeam(a, client, team, rangeChannels, rangeUsers, rangePosts, fuzzy)
|
||||
if err != nil {
|
||||
return TestEnvironment{}, err
|
||||
}
|
||||
environment.Environments[i] = teamEnvironment
|
||||
}
|
||||
|
||||
return environment, nil
|
||||
}
|
||||
|
||||
func CreateTestEnvironmentInTeam(a *app.App, client *model.Client4, team *model.Team, rangeChannels utils.Range, rangeUsers utils.Range, rangePosts utils.Range, fuzzy bool) (TeamEnvironment, error) {
|
||||
rand.Seed(time.Now().UTC().UnixNano())
|
||||
|
||||
// We need to create at least one user
|
||||
if rangeUsers.Begin <= 0 {
|
||||
rangeUsers.Begin = 1
|
||||
}
|
||||
|
||||
userCreator := NewAutoUserCreator(a, client, team)
|
||||
userCreator.Fuzzy = fuzzy
|
||||
users, err := userCreator.CreateTestUsers(rangeUsers)
|
||||
if err != nil {
|
||||
return TeamEnvironment{}, nil
|
||||
}
|
||||
usernames := make([]string, len(users))
|
||||
for i, user := range users {
|
||||
usernames[i] = user.Username
|
||||
}
|
||||
|
||||
channelCreator := NewAutoChannelCreator(a, team, users[0].Id)
|
||||
channelCreator.Fuzzy = fuzzy
|
||||
channels, err := channelCreator.CreateTestChannels(rangeChannels)
|
||||
if err != nil {
|
||||
return TeamEnvironment{}, nil
|
||||
}
|
||||
|
||||
// Have every user join every channel
|
||||
for _, user := range users {
|
||||
for _, channel := range channels {
|
||||
_, resp := client.LoginById(user.Id, USER_PASSWORD)
|
||||
if resp.Error != nil {
|
||||
return TeamEnvironment{}, resp.Error
|
||||
}
|
||||
|
||||
_, resp = client.AddChannelMember(channel.Id, user.Id)
|
||||
if resp.Error != nil {
|
||||
return TeamEnvironment{}, resp.Error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
numPosts := utils.RandIntFromRange(rangePosts)
|
||||
numImages := utils.RandIntFromRange(rangePosts) / 4
|
||||
for j := 0; j < numPosts; j++ {
|
||||
user := users[utils.RandIntFromRange(utils.Range{Begin: 0, End: len(users) - 1})]
|
||||
_, resp := client.LoginById(user.Id, USER_PASSWORD)
|
||||
if resp.Error != nil {
|
||||
return TeamEnvironment{}, resp.Error
|
||||
}
|
||||
|
||||
for i, channel := range channels {
|
||||
postCreator := NewAutoPostCreator(a, channel.Id, user.Id)
|
||||
postCreator.HasImage = i < numImages
|
||||
postCreator.Users = usernames
|
||||
postCreator.Fuzzy = fuzzy
|
||||
_, err := postCreator.CreateRandomPost()
|
||||
if err != nil {
|
||||
return TeamEnvironment{}, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return TeamEnvironment{users, channels}, nil
|
||||
}
|
||||
105
app/slashcommands/auto_posts.go
Обычный файл
105
app/slashcommands/auto_posts.go
Обычный файл
@@ -0,0 +1,105 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/utils"
|
||||
"github.com/mattermost/mattermost-server/v5/utils/fileutils"
|
||||
)
|
||||
|
||||
type AutoPostCreator struct {
|
||||
a *app.App
|
||||
channelid string
|
||||
userid string
|
||||
Fuzzy bool
|
||||
TextLength utils.Range
|
||||
HasImage bool
|
||||
ImageFilenames []string
|
||||
Users []string
|
||||
Mentions utils.Range
|
||||
Tags utils.Range
|
||||
}
|
||||
|
||||
// Automatic poster used for testing
|
||||
func NewAutoPostCreator(a *app.App, channelid, userid string) *AutoPostCreator {
|
||||
return &AutoPostCreator{
|
||||
a: a,
|
||||
channelid: channelid,
|
||||
userid: userid,
|
||||
Fuzzy: false,
|
||||
TextLength: utils.Range{Begin: 100, End: 200},
|
||||
HasImage: false,
|
||||
ImageFilenames: TEST_IMAGE_FILENAMES,
|
||||
Users: []string{},
|
||||
Mentions: utils.Range{Begin: 0, End: 5},
|
||||
Tags: utils.Range{Begin: 0, End: 7},
|
||||
}
|
||||
}
|
||||
|
||||
func (cfg *AutoPostCreator) UploadTestFile() ([]string, error) {
|
||||
filename := cfg.ImageFilenames[utils.RandIntFromRange(utils.Range{Begin: 0, End: len(cfg.ImageFilenames) - 1})]
|
||||
|
||||
path, _ := fileutils.FindDir("tests")
|
||||
file, err := os.Open(filepath.Join(path, filename))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
data := &bytes.Buffer{}
|
||||
_, err = io.Copy(data, file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fileResp, err2 := cfg.a.UploadFile(data.Bytes(), cfg.channelid, filename)
|
||||
if err2 != nil {
|
||||
return nil, err2
|
||||
}
|
||||
|
||||
return []string{fileResp.Id}, nil
|
||||
}
|
||||
|
||||
func (cfg *AutoPostCreator) CreateRandomPost() (*model.Post, error) {
|
||||
return cfg.CreateRandomPostNested("", "")
|
||||
}
|
||||
|
||||
func (cfg *AutoPostCreator) CreateRandomPostNested(parentId, rootId string) (*model.Post, error) {
|
||||
var fileIds []string
|
||||
if cfg.HasImage {
|
||||
var err error
|
||||
fileIds, err = cfg.UploadTestFile()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
var postText string
|
||||
if cfg.Fuzzy {
|
||||
postText = utils.FuzzPost()
|
||||
} else {
|
||||
postText = utils.RandomText(cfg.TextLength, cfg.Tags, cfg.Mentions, cfg.Users)
|
||||
}
|
||||
|
||||
post := &model.Post{
|
||||
ChannelId: cfg.channelid,
|
||||
UserId: cfg.userid,
|
||||
ParentId: parentId,
|
||||
RootId: rootId,
|
||||
Message: postText,
|
||||
FileIds: fileIds,
|
||||
}
|
||||
rpost, err := cfg.a.CreatePostMissingChannel(post, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return rpost, nil
|
||||
}
|
||||
80
app/slashcommands/auto_teams.go
Обычный файл
80
app/slashcommands/auto_teams.go
Обычный файл
@@ -0,0 +1,80 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/utils"
|
||||
)
|
||||
|
||||
type TeamEnvironment struct {
|
||||
Users []*model.User
|
||||
Channels []*model.Channel
|
||||
}
|
||||
|
||||
type AutoTeamCreator struct {
|
||||
client *model.Client4
|
||||
Fuzzy bool
|
||||
NameLength utils.Range
|
||||
NameCharset string
|
||||
DomainLength utils.Range
|
||||
DomainCharset string
|
||||
EmailLength utils.Range
|
||||
EmailCharset string
|
||||
}
|
||||
|
||||
func NewAutoTeamCreator(client *model.Client4) *AutoTeamCreator {
|
||||
return &AutoTeamCreator{
|
||||
client: client,
|
||||
Fuzzy: false,
|
||||
NameLength: TEAM_NAME_LEN,
|
||||
NameCharset: utils.LOWERCASE,
|
||||
DomainLength: TEAM_DOMAIN_NAME_LEN,
|
||||
DomainCharset: utils.LOWERCASE,
|
||||
EmailLength: TEAM_EMAIL_LEN,
|
||||
EmailCharset: utils.LOWERCASE,
|
||||
}
|
||||
}
|
||||
|
||||
func (cfg *AutoTeamCreator) createRandomTeam() (*model.Team, error) {
|
||||
var teamEmail string
|
||||
var teamDisplayName string
|
||||
var teamName string
|
||||
if cfg.Fuzzy {
|
||||
teamEmail = "success+" + model.NewId() + "simulator.amazonses.com"
|
||||
teamDisplayName = utils.FuzzName()
|
||||
teamName = model.NewRandomTeamName()
|
||||
} else {
|
||||
teamEmail = "success+" + model.NewId() + "simulator.amazonses.com"
|
||||
teamDisplayName = utils.RandomName(cfg.NameLength, cfg.NameCharset)
|
||||
teamName = utils.RandomName(cfg.NameLength, cfg.NameCharset) + model.NewId()
|
||||
}
|
||||
team := &model.Team{
|
||||
DisplayName: teamDisplayName,
|
||||
Name: teamName,
|
||||
Email: teamEmail,
|
||||
Type: model.TEAM_OPEN,
|
||||
}
|
||||
|
||||
createdTeam, resp := cfg.client.CreateTeam(team)
|
||||
if resp.Error != nil {
|
||||
return nil, resp.Error
|
||||
}
|
||||
return createdTeam, nil
|
||||
}
|
||||
|
||||
func (cfg *AutoTeamCreator) CreateTestTeams(num utils.Range) ([]*model.Team, error) {
|
||||
numTeams := utils.RandIntFromRange(num)
|
||||
teams := make([]*model.Team, numTeams)
|
||||
|
||||
for i := 0; i < numTeams; i++ {
|
||||
var err error
|
||||
teams[i], err = cfg.createRandomTeam()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return teams, nil
|
||||
}
|
||||
112
app/slashcommands/auto_users.go
Обычный файл
112
app/slashcommands/auto_users.go
Обычный файл
@@ -0,0 +1,112 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/utils"
|
||||
)
|
||||
|
||||
type AutoUserCreator struct {
|
||||
app *app.App
|
||||
client *model.Client4
|
||||
team *model.Team
|
||||
EmailLength utils.Range
|
||||
EmailCharset string
|
||||
NameLength utils.Range
|
||||
NameCharset string
|
||||
Fuzzy bool
|
||||
}
|
||||
|
||||
func NewAutoUserCreator(a *app.App, client *model.Client4, team *model.Team) *AutoUserCreator {
|
||||
return &AutoUserCreator{
|
||||
app: a,
|
||||
client: client,
|
||||
team: team,
|
||||
EmailLength: USER_EMAIL_LEN,
|
||||
EmailCharset: utils.LOWERCASE,
|
||||
NameLength: USER_NAME_LEN,
|
||||
NameCharset: utils.LOWERCASE,
|
||||
Fuzzy: false,
|
||||
}
|
||||
}
|
||||
|
||||
// Basic test team and user so you always know one
|
||||
func CreateBasicUser(a *app.App, client *model.Client4) *model.AppError {
|
||||
found, _ := client.TeamExists(BTEST_TEAM_NAME, "")
|
||||
if found {
|
||||
return nil
|
||||
}
|
||||
|
||||
newteam := &model.Team{DisplayName: BTEST_TEAM_DISPLAY_NAME, Name: BTEST_TEAM_NAME, Email: BTEST_TEAM_EMAIL, Type: BTEST_TEAM_TYPE}
|
||||
basicteam, resp := client.CreateTeam(newteam)
|
||||
if resp.Error != nil {
|
||||
return resp.Error
|
||||
}
|
||||
newuser := &model.User{Email: BTEST_USER_EMAIL, Nickname: BTEST_USER_NAME, Password: BTEST_USER_PASSWORD}
|
||||
ruser, resp := client.CreateUser(newuser)
|
||||
if resp.Error != nil {
|
||||
return resp.Error
|
||||
}
|
||||
_, err := a.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = a.Srv().Store.Team().SaveMember(&model.TeamMember{TeamId: basicteam.Id, UserId: ruser.Id}, *a.Config().TeamSettings.MaxUsersPerTeam); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cfg *AutoUserCreator) createRandomUser() (*model.User, error) {
|
||||
var userEmail string
|
||||
var userName string
|
||||
if cfg.Fuzzy {
|
||||
userEmail = "success+" + model.NewId() + "@simulator.amazonses.com"
|
||||
userName = utils.FuzzName()
|
||||
} else {
|
||||
userEmail = "success+" + model.NewId() + "@simulator.amazonses.com"
|
||||
userName = utils.RandomName(cfg.NameLength, cfg.NameCharset)
|
||||
}
|
||||
|
||||
user := &model.User{
|
||||
Email: userEmail,
|
||||
Nickname: userName,
|
||||
Password: USER_PASSWORD}
|
||||
|
||||
ruser, resp := cfg.client.CreateUserWithInviteId(user, cfg.team.InviteId)
|
||||
if resp.Error != nil {
|
||||
return nil, resp.Error
|
||||
}
|
||||
|
||||
status := &model.Status{UserId: ruser.Id, Status: model.STATUS_ONLINE, Manual: false, LastActivityAt: model.GetMillis(), ActiveChannel: ""}
|
||||
if err := cfg.app.Srv().Store.Status().SaveOrUpdate(status); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// We need to cheat to verify the user's email
|
||||
_, err := cfg.app.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return ruser, nil
|
||||
}
|
||||
|
||||
func (cfg *AutoUserCreator) CreateTestUsers(num utils.Range) ([]*model.User, error) {
|
||||
numUsers := utils.RandIntFromRange(num)
|
||||
users := make([]*model.User, numUsers)
|
||||
|
||||
for i := 0; i < numUsers; i++ {
|
||||
var err error
|
||||
users[i], err = cfg.createRandomUser()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return users, nil
|
||||
}
|
||||
40
app/slashcommands/command_away.go
Обычный файл
40
app/slashcommands/command_away.go
Обычный файл
@@ -0,0 +1,40 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type AwayProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_AWAY = "away"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&AwayProvider{})
|
||||
}
|
||||
|
||||
func (me *AwayProvider) GetTrigger() string {
|
||||
return CMD_AWAY
|
||||
}
|
||||
|
||||
func (me *AwayProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_AWAY,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_away.desc"),
|
||||
DisplayName: T("api.command_away.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *AwayProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
a.SetStatusAwayIfNeeded(args.UserId, true)
|
||||
|
||||
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_away.success")}
|
||||
}
|
||||
103
app/slashcommands/command_channel_header.go
Обычный файл
103
app/slashcommands/command_channel_header.go
Обычный файл
@@ -0,0 +1,103 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type HeaderProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_HEADER = "header"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&HeaderProvider{})
|
||||
}
|
||||
|
||||
func (me *HeaderProvider) GetTrigger() string {
|
||||
return CMD_HEADER
|
||||
}
|
||||
|
||||
func (me *HeaderProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_HEADER,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_channel_header.desc"),
|
||||
AutoCompleteHint: T("api.command_channel_header.hint"),
|
||||
DisplayName: T("api.command_channel_header.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *HeaderProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
channel, err := a.GetChannel(args.ChannelId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_header.channel.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
switch channel.Type {
|
||||
case model.CHANNEL_OPEN:
|
||||
if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_header.permission.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
case model.CHANNEL_PRIVATE:
|
||||
if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_header.permission.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
case model.CHANNEL_GROUP, model.CHANNEL_DIRECT:
|
||||
// Modifying the header is not linked to any specific permission for group/dm channels, so just check for membership.
|
||||
var channelMember *model.ChannelMember
|
||||
channelMember, err = a.GetChannelMember(args.ChannelId, args.UserId)
|
||||
if err != nil || channelMember == nil {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_header.permission.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_header.permission.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
if len(message) == 0 {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_header.message.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
patch := &model.ChannelPatch{
|
||||
Header: new(string),
|
||||
}
|
||||
*patch.Header = message
|
||||
|
||||
_, err = a.PatchChannel(channel, patch, args.UserId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_header.update_channel.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
return &model.CommandResponse{}
|
||||
}
|
||||
122
app/slashcommands/command_channel_header_test.go
Обычный файл
122
app/slashcommands/command_channel_header_test.go
Обычный файл
@@ -0,0 +1,122 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
func TestHeaderProviderDoCommand(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
hp := HeaderProvider{}
|
||||
|
||||
th.addPermissionToRole(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID)
|
||||
|
||||
// Try a public channel *with* permission.
|
||||
args := &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
for msg, expected := range map[string]string{
|
||||
"": "api.command_channel_header.message.app_error",
|
||||
"hello": "",
|
||||
} {
|
||||
actual := hp.DoCommand(th.App, args, msg).Text
|
||||
assert.Equal(t, expected, actual)
|
||||
}
|
||||
|
||||
th.removePermissionFromRole(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID)
|
||||
|
||||
// Try a public channel *without* permission.
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual := hp.DoCommand(th.App, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_header.permission.app_error", actual)
|
||||
|
||||
th.addPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID)
|
||||
|
||||
// Try a private channel *with* permission.
|
||||
privateChannel := th.createPrivateChannel(th.BasicTeam)
|
||||
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: privateChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = hp.DoCommand(th.App, args, "hello").Text
|
||||
assert.Equal(t, "", actual)
|
||||
|
||||
th.removePermissionFromRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID)
|
||||
|
||||
// Try a private channel *without* permission.
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: privateChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = hp.DoCommand(th.App, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_header.permission.app_error", actual)
|
||||
|
||||
// Try a group channel *with* being a member.
|
||||
user1 := th.createUser()
|
||||
user2 := th.createUser()
|
||||
user3 := th.createUser()
|
||||
|
||||
groupChannel := th.createGroupChannel(user1, user2)
|
||||
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: groupChannel.Id,
|
||||
UserId: user1.Id,
|
||||
}
|
||||
|
||||
actual = hp.DoCommand(th.App, args, "hello").Text
|
||||
assert.Equal(t, "", actual)
|
||||
|
||||
// Try a group channel *without* being a member.
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: groupChannel.Id,
|
||||
UserId: user3.Id,
|
||||
}
|
||||
|
||||
actual = hp.DoCommand(th.App, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_header.permission.app_error", actual)
|
||||
|
||||
// Try a direct channel *with* being a member.
|
||||
directChannel := th.createDmChannel(user1)
|
||||
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: directChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = hp.DoCommand(th.App, args, "hello").Text
|
||||
assert.Equal(t, "", actual)
|
||||
|
||||
// Try a direct channel *without* being a member.
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: directChannel.Id,
|
||||
UserId: user2.Id,
|
||||
}
|
||||
|
||||
actual = hp.DoCommand(th.App, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_header.permission.app_error", actual)
|
||||
}
|
||||
90
app/slashcommands/command_channel_purpose.go
Обычный файл
90
app/slashcommands/command_channel_purpose.go
Обычный файл
@@ -0,0 +1,90 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type PurposeProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_PURPOSE = "purpose"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&PurposeProvider{})
|
||||
}
|
||||
|
||||
func (me *PurposeProvider) GetTrigger() string {
|
||||
return CMD_PURPOSE
|
||||
}
|
||||
|
||||
func (me *PurposeProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_PURPOSE,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_channel_purpose.desc"),
|
||||
AutoCompleteHint: T("api.command_channel_purpose.hint"),
|
||||
DisplayName: T("api.command_channel_purpose.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *PurposeProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
channel, err := a.GetChannel(args.ChannelId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_purpose.channel.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
switch channel.Type {
|
||||
case model.CHANNEL_OPEN:
|
||||
if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_purpose.permission.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
case model.CHANNEL_PRIVATE:
|
||||
if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_purpose.permission.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
default:
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_purpose.direct_group.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
if len(message) == 0 {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_purpose.message.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
patch := &model.ChannelPatch{
|
||||
Purpose: new(string),
|
||||
}
|
||||
*patch.Purpose = message
|
||||
|
||||
_, err = a.PatchChannel(channel, patch, args.UserId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_purpose.update_channel.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
return &model.CommandResponse{}
|
||||
}
|
||||
97
app/slashcommands/command_channel_purpose_test.go
Обычный файл
97
app/slashcommands/command_channel_purpose_test.go
Обычный файл
@@ -0,0 +1,97 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
func TestPurposeProviderDoCommand(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
pp := PurposeProvider{}
|
||||
|
||||
// Try a public channel *with* permission.
|
||||
th.addPermissionToRole(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID)
|
||||
|
||||
args := &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
for msg, expected := range map[string]string{
|
||||
"": "api.command_channel_purpose.message.app_error",
|
||||
"hello": "",
|
||||
} {
|
||||
actual := pp.DoCommand(th.App, args, msg).Text
|
||||
assert.Equal(t, expected, actual)
|
||||
}
|
||||
|
||||
// Try a public channel *without* permission.
|
||||
th.removePermissionFromRole(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID)
|
||||
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
}
|
||||
|
||||
actual := pp.DoCommand(th.App, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_purpose.permission.app_error", actual)
|
||||
|
||||
// Try a private channel *with* permission.
|
||||
privateChannel := th.createPrivateChannel(th.BasicTeam)
|
||||
|
||||
th.addPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID)
|
||||
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: privateChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = pp.DoCommand(th.App, args, "hello").Text
|
||||
assert.Equal(t, "", actual)
|
||||
|
||||
// Try a private channel *without* permission.
|
||||
th.removePermissionFromRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID)
|
||||
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: privateChannel.Id,
|
||||
}
|
||||
|
||||
actual = pp.DoCommand(th.App, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_purpose.permission.app_error", actual)
|
||||
|
||||
// Try a group channel *with* being a member.
|
||||
user1 := th.createUser()
|
||||
user2 := th.createUser()
|
||||
|
||||
groupChannel := th.createGroupChannel(user1, user2)
|
||||
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: groupChannel.Id,
|
||||
}
|
||||
|
||||
actual = pp.DoCommand(th.App, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_purpose.direct_group.app_error", actual)
|
||||
|
||||
// Try a direct channel *with* being a member.
|
||||
directChannel := th.createDmChannel(user1)
|
||||
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: directChannel.Id,
|
||||
}
|
||||
|
||||
actual = pp.DoCommand(th.App, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_purpose.direct_group.app_error", actual)
|
||||
}
|
||||
104
app/slashcommands/command_channel_rename.go
Обычный файл
104
app/slashcommands/command_channel_rename.go
Обычный файл
@@ -0,0 +1,104 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type RenameProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_RENAME = "rename"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&RenameProvider{})
|
||||
}
|
||||
|
||||
func (me *RenameProvider) GetTrigger() string {
|
||||
return CMD_RENAME
|
||||
}
|
||||
|
||||
func (me *RenameProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
renameAutocompleteData := model.NewAutocompleteData(CMD_RENAME, T("api.command_channel_rename.hint"), T("api.command_channel_rename.desc"))
|
||||
renameAutocompleteData.AddTextArgument(T("api.command_channel_rename.hint"), "[text]", "")
|
||||
return &model.Command{
|
||||
Trigger: CMD_RENAME,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_channel_rename.desc"),
|
||||
AutoCompleteHint: T("api.command_channel_rename.hint"),
|
||||
DisplayName: T("api.command_channel_rename.name"),
|
||||
AutocompleteData: renameAutocompleteData,
|
||||
}
|
||||
}
|
||||
|
||||
func (me *RenameProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
channel, err := a.GetChannel(args.ChannelId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_rename.channel.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
switch channel.Type {
|
||||
case model.CHANNEL_OPEN:
|
||||
if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES) {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_rename.permission.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
case model.CHANNEL_PRIVATE:
|
||||
if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES) {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_rename.permission.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
default:
|
||||
return &model.CommandResponse{Text: args.T("api.command_channel_rename.direct_group.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
if len(message) == 0 {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_rename.message.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
} else if len(message) > model.CHANNEL_NAME_MAX_LENGTH {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_rename.too_long.app_error", map[string]interface{}{
|
||||
"Length": model.CHANNEL_NAME_MAX_LENGTH,
|
||||
}),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
} else if len(message) < model.CHANNEL_NAME_MIN_LENGTH {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_rename.too_short.app_error", map[string]interface{}{
|
||||
"Length": model.CHANNEL_NAME_MIN_LENGTH,
|
||||
}),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
patch := &model.ChannelPatch{
|
||||
DisplayName: new(string),
|
||||
}
|
||||
*patch.DisplayName = message
|
||||
|
||||
_, err = a.PatchChannel(channel, patch, args.UserId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_rename.update_channel.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
return &model.CommandResponse{}
|
||||
}
|
||||
104
app/slashcommands/command_channel_rename_test.go
Обычный файл
104
app/slashcommands/command_channel_rename_test.go
Обычный файл
@@ -0,0 +1,104 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
func TestRenameProviderDoCommand(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
th.addPermissionToRole(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID)
|
||||
|
||||
rp := RenameProvider{}
|
||||
args := &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
// Table Test for basic cases. Blank text in response indicates success
|
||||
for msg, expected := range map[string]string{
|
||||
"": "api.command_channel_rename.message.app_error",
|
||||
"o": "api.command_channel_rename.too_short.app_error",
|
||||
"joram": "",
|
||||
"More than 22 chars but less than 64": "",
|
||||
strings.Repeat("12345", 13): "api.command_channel_rename.too_long.app_error",
|
||||
} {
|
||||
actual := rp.DoCommand(th.App, args, msg).Text
|
||||
assert.Equal(t, expected, actual)
|
||||
}
|
||||
|
||||
// Try a public channel *without* permission.
|
||||
th.removePermissionFromRole(model.PERMISSION_MANAGE_PUBLIC_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID)
|
||||
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual := rp.DoCommand(th.App, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_rename.permission.app_error", actual)
|
||||
|
||||
// Try a private channel *with* permission.
|
||||
privateChannel := th.createPrivateChannel(th.BasicTeam)
|
||||
|
||||
th.addPermissionToRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID)
|
||||
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: privateChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = rp.DoCommand(th.App, args, "hello").Text
|
||||
assert.Equal(t, "", actual)
|
||||
|
||||
// Try a private channel *without* permission.
|
||||
th.removePermissionFromRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID)
|
||||
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: privateChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = rp.DoCommand(th.App, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_rename.permission.app_error", actual)
|
||||
|
||||
// Try a group channel *with* being a member.
|
||||
user1 := th.createUser()
|
||||
user2 := th.createUser()
|
||||
|
||||
groupChannel := th.createGroupChannel(user1, user2)
|
||||
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: groupChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = rp.DoCommand(th.App, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_rename.direct_group.app_error", actual)
|
||||
|
||||
// Try a direct channel *with* being a member.
|
||||
directChannel := th.createDmChannel(user1)
|
||||
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: directChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = rp.DoCommand(th.App, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_rename.direct_group.app_error", actual)
|
||||
}
|
||||
45
app/slashcommands/command_code.go
Обычный файл
45
app/slashcommands/command_code.go
Обычный файл
@@ -0,0 +1,45 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type CodeProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_CODE = "code"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&CodeProvider{})
|
||||
}
|
||||
|
||||
func (me *CodeProvider) GetTrigger() string {
|
||||
return CMD_CODE
|
||||
}
|
||||
|
||||
func (me *CodeProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_CODE,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_code.desc"),
|
||||
AutoCompleteHint: T("api.command_code.hint"),
|
||||
DisplayName: T("api.command_code.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *CodeProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
if len(message) == 0 {
|
||||
return &model.CommandResponse{Text: args.T("api.command_code.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
rmsg := " " + strings.Join(strings.Split(message, "\n"), "\n ")
|
||||
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, Text: rmsg, SkipSlackParsing: true}
|
||||
}
|
||||
29
app/slashcommands/command_code_test.go
Обычный файл
29
app/slashcommands/command_code_test.go
Обычный файл
@@ -0,0 +1,29 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
func TestCodeProviderDoCommand(t *testing.T) {
|
||||
cp := CodeProvider{}
|
||||
args := &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
}
|
||||
|
||||
for msg, expected := range map[string]string{
|
||||
"": "api.command_code.message.app_error",
|
||||
"foo": " foo",
|
||||
"foo\nbar": " foo\n bar",
|
||||
"foo\nbar\n": " foo\n bar\n ",
|
||||
} {
|
||||
actual := cp.DoCommand(nil, args, msg).Text
|
||||
if actual != expected {
|
||||
t.Errorf("expected `%v`, got `%v`", expected, actual)
|
||||
}
|
||||
}
|
||||
}
|
||||
50
app/slashcommands/command_dnd.go
Обычный файл
50
app/slashcommands/command_dnd.go
Обычный файл
@@ -0,0 +1,50 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type DndProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_DND = "dnd"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&DndProvider{})
|
||||
}
|
||||
|
||||
func (me *DndProvider) GetTrigger() string {
|
||||
return CMD_DND
|
||||
}
|
||||
|
||||
func (me *DndProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_DND,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_dnd.desc"),
|
||||
DisplayName: T("api.command_dnd.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *DndProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
status, err := a.GetStatus(args.UserId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_dnd.error")}
|
||||
} else {
|
||||
if status.Status == "dnd" {
|
||||
a.SetStatusOnline(args.UserId, true)
|
||||
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_dnd.disabled")}
|
||||
}
|
||||
}
|
||||
|
||||
a.SetStatusDoNotDisturb(args.UserId)
|
||||
|
||||
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_dnd.success")}
|
||||
}
|
||||
98
app/slashcommands/command_echo.go
Обычный файл
98
app/slashcommands/command_echo.go
Обычный файл
@@ -0,0 +1,98 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/mlog"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
var echoSem chan bool
|
||||
|
||||
type EchoProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_ECHO = "echo"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&EchoProvider{})
|
||||
}
|
||||
|
||||
func (me *EchoProvider) GetTrigger() string {
|
||||
return CMD_ECHO
|
||||
}
|
||||
|
||||
func (me *EchoProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_ECHO,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_echo.desc"),
|
||||
AutoCompleteHint: T("api.command_echo.hint"),
|
||||
DisplayName: T("api.command_echo.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *EchoProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
if len(message) == 0 {
|
||||
return &model.CommandResponse{Text: args.T("api.command_echo.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
maxThreads := 100
|
||||
|
||||
delay := 0
|
||||
if endMsg := strings.LastIndex(message, "\""); string(message[0]) == "\"" && endMsg > 1 {
|
||||
if checkDelay, err := strconv.Atoi(strings.Trim(message[endMsg:], " \"")); err == nil {
|
||||
delay = checkDelay
|
||||
}
|
||||
message = message[1:endMsg]
|
||||
} else if strings.Contains(message, " ") {
|
||||
delayIdx := strings.LastIndex(message, " ")
|
||||
delayStr := strings.Trim(message[delayIdx:], " ")
|
||||
|
||||
if checkDelay, err := strconv.Atoi(delayStr); err == nil {
|
||||
delay = checkDelay
|
||||
message = message[:delayIdx]
|
||||
}
|
||||
}
|
||||
|
||||
if delay > 10000 {
|
||||
return &model.CommandResponse{Text: args.T("api.command_echo.delay.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
if echoSem == nil {
|
||||
// We want one additional thread allowed so we never reach channel lockup
|
||||
echoSem = make(chan bool, maxThreads+1)
|
||||
}
|
||||
|
||||
if len(echoSem) >= maxThreads {
|
||||
return &model.CommandResponse{Text: args.T("api.command_echo.high_volume.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
echoSem <- true
|
||||
a.Srv().Go(func() {
|
||||
defer func() { <-echoSem }()
|
||||
post := &model.Post{}
|
||||
post.ChannelId = args.ChannelId
|
||||
post.RootId = args.RootId
|
||||
post.ParentId = args.ParentId
|
||||
post.Message = message
|
||||
post.UserId = args.UserId
|
||||
|
||||
time.Sleep(time.Duration(delay) * time.Second)
|
||||
|
||||
if _, err := a.CreatePostMissingChannel(post, true); err != nil {
|
||||
mlog.Error("Unable to create /echo post.", mlog.Err(err))
|
||||
}
|
||||
})
|
||||
|
||||
return &model.CommandResponse{}
|
||||
}
|
||||
88
app/slashcommands/command_expand_collapse.go
Обычный файл
88
app/slashcommands/command_expand_collapse.go
Обычный файл
@@ -0,0 +1,88 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type ExpandProvider struct {
|
||||
}
|
||||
|
||||
type CollapseProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_EXPAND = "expand"
|
||||
CMD_COLLAPSE = "collapse"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&ExpandProvider{})
|
||||
app.RegisterCommandProvider(&CollapseProvider{})
|
||||
}
|
||||
|
||||
func (me *ExpandProvider) GetTrigger() string {
|
||||
return CMD_EXPAND
|
||||
}
|
||||
|
||||
func (me *CollapseProvider) GetTrigger() string {
|
||||
return CMD_COLLAPSE
|
||||
}
|
||||
|
||||
func (me *ExpandProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_EXPAND,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_expand.desc"),
|
||||
DisplayName: T("api.command_expand.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *CollapseProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_COLLAPSE,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_collapse.desc"),
|
||||
DisplayName: T("api.command_collapse.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *ExpandProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
return setCollapsePreference(a, args, false)
|
||||
}
|
||||
|
||||
func (me *CollapseProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
return setCollapsePreference(a, args, true)
|
||||
}
|
||||
|
||||
func setCollapsePreference(a *app.App, args *model.CommandArgs, isCollapse bool) *model.CommandResponse {
|
||||
pref := model.Preference{
|
||||
UserId: args.UserId,
|
||||
Category: model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS,
|
||||
Name: model.PREFERENCE_NAME_COLLAPSE_SETTING,
|
||||
Value: strconv.FormatBool(isCollapse),
|
||||
}
|
||||
|
||||
if err := a.Srv().Store.Preference().Save(&model.Preferences{pref}); err != nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_expand_collapse.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
socketMessage := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PREFERENCE_CHANGED, "", "", args.UserId, nil)
|
||||
socketMessage.Add("preference", pref.ToJson())
|
||||
a.Publish(socketMessage)
|
||||
|
||||
var rmsg string
|
||||
|
||||
if isCollapse {
|
||||
rmsg = args.T("api.command_collapse.success")
|
||||
} else {
|
||||
rmsg = args.T("api.command_expand.success")
|
||||
}
|
||||
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: rmsg}
|
||||
}
|
||||
159
app/slashcommands/command_groupmsg.go
Обычный файл
159
app/slashcommands/command_groupmsg.go
Обычный файл
@@ -0,0 +1,159 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/mlog"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type groupmsgProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_GROUPMSG = "groupmsg"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&groupmsgProvider{})
|
||||
}
|
||||
|
||||
func (me *groupmsgProvider) GetTrigger() string {
|
||||
return CMD_GROUPMSG
|
||||
}
|
||||
|
||||
func (me *groupmsgProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_GROUPMSG,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_groupmsg.desc"),
|
||||
AutoCompleteHint: T("api.command_groupmsg.hint"),
|
||||
DisplayName: T("api.command_groupmsg.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *groupmsgProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
targetUsers := map[string]*model.User{}
|
||||
targetUsersSlice := []string{args.UserId}
|
||||
invalidUsernames := []string{}
|
||||
|
||||
users, parsedMessage := groupMsgUsernames(message)
|
||||
|
||||
for _, username := range users {
|
||||
username = strings.TrimSpace(username)
|
||||
username = strings.TrimPrefix(username, "@")
|
||||
targetUser, err := a.Srv().Store.User().GetByUsername(username)
|
||||
if err != nil {
|
||||
invalidUsernames = append(invalidUsernames, username)
|
||||
continue
|
||||
}
|
||||
|
||||
canSee, err := a.UserCanSeeOtherUser(args.UserId, targetUser.Id)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_groupmsg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
if !canSee {
|
||||
invalidUsernames = append(invalidUsernames, username)
|
||||
continue
|
||||
}
|
||||
|
||||
_, exists := targetUsers[targetUser.Id]
|
||||
if !exists && targetUser.Id != args.UserId {
|
||||
targetUsers[targetUser.Id] = targetUser
|
||||
targetUsersSlice = append(targetUsersSlice, targetUser.Id)
|
||||
}
|
||||
}
|
||||
|
||||
if len(invalidUsernames) > 0 {
|
||||
invalidUsersString := map[string]interface{}{
|
||||
"Users": "@" + strings.Join(invalidUsernames, ", @"),
|
||||
}
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_groupmsg.invalid_user.app_error", len(invalidUsernames), invalidUsersString),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
if len(targetUsersSlice) == 2 {
|
||||
return app.GetCommandProvider("msg").DoCommand(a, args, fmt.Sprintf("%s %s", targetUsers[targetUsersSlice[1]].Username, parsedMessage))
|
||||
}
|
||||
|
||||
if len(targetUsersSlice) < model.CHANNEL_GROUP_MIN_USERS {
|
||||
minUsers := map[string]interface{}{
|
||||
"MinUsers": model.CHANNEL_GROUP_MIN_USERS - 1,
|
||||
}
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_groupmsg.min_users.app_error", minUsers),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
if len(targetUsersSlice) > model.CHANNEL_GROUP_MAX_USERS {
|
||||
maxUsers := map[string]interface{}{
|
||||
"MaxUsers": model.CHANNEL_GROUP_MAX_USERS - 1,
|
||||
}
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_groupmsg.max_users.app_error", maxUsers),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
var groupChannel *model.Channel
|
||||
var channelErr *model.AppError
|
||||
|
||||
if a.HasPermissionTo(args.UserId, model.PERMISSION_CREATE_GROUP_CHANNEL) {
|
||||
groupChannel, channelErr = a.CreateGroupChannel(targetUsersSlice, args.UserId)
|
||||
if channelErr != nil {
|
||||
mlog.Error(channelErr.Error())
|
||||
return &model.CommandResponse{Text: args.T("api.command_groupmsg.group_fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
} else {
|
||||
groupChannel, channelErr = a.GetGroupChannel(targetUsersSlice)
|
||||
if channelErr != nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_groupmsg.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
}
|
||||
|
||||
if len(parsedMessage) > 0 {
|
||||
post := &model.Post{}
|
||||
post.Message = parsedMessage
|
||||
post.ChannelId = groupChannel.Id
|
||||
post.UserId = args.UserId
|
||||
if _, err := a.CreatePostMissingChannel(post, true); err != nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_groupmsg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
}
|
||||
|
||||
team, err := a.GetTeam(args.TeamId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_groupmsg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
return &model.CommandResponse{GotoLocation: args.SiteURL + "/" + team.Name + "/channels/" + groupChannel.Name, Text: "", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
func groupMsgUsernames(message string) ([]string, string) {
|
||||
result := []string{}
|
||||
resultMessage := ""
|
||||
for idx, part := range strings.Split(message, ",") {
|
||||
clean := strings.TrimPrefix(strings.TrimSpace(part), "@")
|
||||
split := strings.Fields(clean)
|
||||
if len(split) > 0 {
|
||||
result = append(result, split[0])
|
||||
}
|
||||
if len(split) > 1 {
|
||||
splitted := strings.SplitN(message, ",", idx+1)
|
||||
resultMessage = strings.TrimPrefix(strings.TrimSpace(splitted[len(splitted)-1]), "@")
|
||||
resultMessage = strings.TrimSpace(strings.TrimPrefix(resultMessage, split[0]))
|
||||
break
|
||||
}
|
||||
}
|
||||
return result, resultMessage
|
||||
}
|
||||
122
app/slashcommands/command_groupmsg_test.go
Обычный файл
122
app/slashcommands/command_groupmsg_test.go
Обычный файл
@@ -0,0 +1,122 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
func TestGroupMsgUsernames(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
|
||||
users, parsedMessage := groupMsgUsernames("")
|
||||
assert.Len(users, 0)
|
||||
assert.Empty(parsedMessage)
|
||||
|
||||
users, parsedMessage = groupMsgUsernames("test")
|
||||
assert.Len(users, 1)
|
||||
assert.Empty(parsedMessage)
|
||||
|
||||
users, parsedMessage = groupMsgUsernames("test1, test2, test3 , test4")
|
||||
assert.Len(users, 4)
|
||||
assert.Empty(parsedMessage)
|
||||
|
||||
users, parsedMessage = groupMsgUsernames("test1, test2 message with spaces")
|
||||
assert.Len(users, 2)
|
||||
assert.Equal(parsedMessage, "message with spaces", "error parsing message")
|
||||
|
||||
users, parsedMessage = groupMsgUsernames("test1, test2 message with, comma")
|
||||
assert.Len(users, 2)
|
||||
assert.Equal(parsedMessage, "message with, comma", "error parsing messages with comma")
|
||||
|
||||
users, parsedMessage = groupMsgUsernames("test1,,,test2")
|
||||
assert.Len(users, 2)
|
||||
assert.Empty(parsedMessage)
|
||||
|
||||
users, parsedMessage = groupMsgUsernames(" test1, test2 other message ")
|
||||
assert.Len(users, 2)
|
||||
assert.Equal(parsedMessage, "other message", "error parsing strange usage of spaces")
|
||||
|
||||
users, _ = groupMsgUsernames(" test1, test2,,123,@321,+123")
|
||||
assert.Len(users, 5)
|
||||
assert.Equal(users[0], "test1")
|
||||
assert.Equal(users[1], "test2")
|
||||
assert.Equal(users[2], "123")
|
||||
assert.Equal(users[3], "321")
|
||||
assert.Equal(users[4], "+123")
|
||||
assert.Equal(parsedMessage, "other message", "error parsing different types of users")
|
||||
}
|
||||
|
||||
func TestGroupMsgProvider(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
user3 := th.createUser()
|
||||
targetUsers := "@" + th.BasicUser2.Username + ",@" + user3.Username + " "
|
||||
|
||||
team := th.createTeam()
|
||||
th.linkUserToTeam(th.BasicUser, team)
|
||||
cmd := &groupmsgProvider{}
|
||||
|
||||
th.removePermissionFromRole(model.PERMISSION_CREATE_GROUP_CHANNEL.Id, model.SYSTEM_USER_ROLE_ID)
|
||||
|
||||
t.Run("Check without permission to create a GM channel.", func(t *testing.T) {
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: team.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}, targetUsers+"hello")
|
||||
|
||||
assert.Equal(t, "api.command_groupmsg.permission.app_error", resp.Text)
|
||||
assert.Equal(t, "", resp.GotoLocation)
|
||||
})
|
||||
|
||||
th.addPermissionToRole(model.PERMISSION_CREATE_GROUP_CHANNEL.Id, model.SYSTEM_USER_ROLE_ID)
|
||||
|
||||
t.Run("Check without permissions to view a user in the list.", func(t *testing.T) {
|
||||
th.removePermissionFromRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID)
|
||||
defer th.addPermissionToRole(model.PERMISSION_VIEW_MEMBERS.Id, model.SYSTEM_USER_ROLE_ID)
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: team.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}, targetUsers+"hello")
|
||||
|
||||
assert.Equal(t, "api.command_groupmsg.invalid_user.app_error", resp.Text)
|
||||
assert.Equal(t, "", resp.GotoLocation)
|
||||
})
|
||||
|
||||
t.Run("Check with permission to create a GM channel.", func(t *testing.T) {
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: team.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}, targetUsers+"hello")
|
||||
|
||||
channelName := model.GetGroupNameFromUserIds([]string{th.BasicUser.Id, th.BasicUser2.Id, user3.Id})
|
||||
assert.Equal(t, "", resp.Text)
|
||||
assert.Equal(t, "http://test.url/"+team.Name+"/channels/"+channelName, resp.GotoLocation)
|
||||
})
|
||||
|
||||
t.Run("Check without permission to post to an existing GM channel.", func(t *testing.T) {
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: team.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}, targetUsers+"hello")
|
||||
|
||||
channelName := model.GetGroupNameFromUserIds([]string{th.BasicUser.Id, th.BasicUser2.Id, user3.Id})
|
||||
assert.Equal(t, "", resp.Text)
|
||||
assert.Equal(t, "http://test.url/"+team.Name+"/channels/"+channelName, resp.GotoLocation)
|
||||
})
|
||||
}
|
||||
44
app/slashcommands/command_help.go
Обычный файл
44
app/slashcommands/command_help.go
Обычный файл
@@ -0,0 +1,44 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type HelpProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_HELP = "help"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&HelpProvider{})
|
||||
}
|
||||
|
||||
func (h *HelpProvider) GetTrigger() string {
|
||||
return CMD_HELP
|
||||
}
|
||||
|
||||
func (h *HelpProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_HELP,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_help.desc"),
|
||||
DisplayName: T("api.command_help.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *HelpProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
helpLink := *a.Config().SupportSettings.HelpLink
|
||||
|
||||
if helpLink == "" {
|
||||
helpLink = model.SUPPORT_SETTINGS_DEFAULT_HELP_LINK
|
||||
}
|
||||
|
||||
return &model.CommandResponse{GotoLocation: helpLink}
|
||||
}
|
||||
172
app/slashcommands/command_invite.go
Обычный файл
172
app/slashcommands/command_invite.go
Обычный файл
@@ -0,0 +1,172 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/mlog"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type InviteProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_INVITE = "invite"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&InviteProvider{})
|
||||
}
|
||||
|
||||
func (me *InviteProvider) GetTrigger() string {
|
||||
return CMD_INVITE
|
||||
}
|
||||
|
||||
func (me *InviteProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_INVITE,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_invite.desc"),
|
||||
AutoCompleteHint: T("api.command_invite.hint"),
|
||||
DisplayName: T("api.command_invite.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *InviteProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
if message == "" {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_invite.missing_message.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
splitMessage := strings.SplitN(message, " ", 2)
|
||||
targetUsername := splitMessage[0]
|
||||
targetUsername = strings.TrimPrefix(targetUsername, "@")
|
||||
|
||||
userProfile, err := a.Srv().Store.User().GetByUsername(targetUsername)
|
||||
if err != nil {
|
||||
mlog.Error(err.Error())
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_invite.missing_user.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
if userProfile.DeleteAt != 0 {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_invite.missing_user.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
var channelToJoin *model.Channel
|
||||
// User set a channel to add the invited user
|
||||
if len(splitMessage) > 1 && splitMessage[1] != "" {
|
||||
targetChannelName := strings.TrimPrefix(strings.TrimSpace(splitMessage[1]), "~")
|
||||
|
||||
if channelToJoin, err = a.GetChannelByName(targetChannelName, args.TeamId, false); err != nil {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_invite.channel.error", map[string]interface{}{
|
||||
"Channel": targetChannelName,
|
||||
}),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
channelToJoin, err = a.GetChannel(args.ChannelId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_invite.channel.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Permissions Check
|
||||
switch channelToJoin.Type {
|
||||
case model.CHANNEL_OPEN:
|
||||
if !a.HasPermissionToChannel(args.UserId, channelToJoin.Id, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_invite.permission.app_error", map[string]interface{}{
|
||||
"User": userProfile.Username,
|
||||
"Channel": channelToJoin.Name,
|
||||
}),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
case model.CHANNEL_PRIVATE:
|
||||
if !a.HasPermissionToChannel(args.UserId, channelToJoin.Id, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) {
|
||||
if _, err = a.GetChannelMember(channelToJoin.Id, args.UserId); err == nil {
|
||||
// User doing the inviting is a member of the channel.
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_invite.permission.app_error", map[string]interface{}{
|
||||
"User": userProfile.Username,
|
||||
"Channel": channelToJoin.Name,
|
||||
}),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
} else {
|
||||
// User doing the inviting is *not* a member of the channel.
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_invite.private_channel.app_error", map[string]interface{}{
|
||||
"Channel": channelToJoin.Name,
|
||||
}),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_invite.directchannel.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
// Check if user is already in the channel
|
||||
_, err = a.GetChannelMember(channelToJoin.Id, userProfile.Id)
|
||||
if err == nil {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_invite.user_already_in_channel.app_error", map[string]interface{}{
|
||||
"User": userProfile.Username,
|
||||
}),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := a.AddChannelMember(userProfile.Id, channelToJoin, args.UserId, ""); err != nil {
|
||||
var text string
|
||||
if err.Id == "api.channel.add_members.user_denied" {
|
||||
text = args.T("api.command_invite.group_constrained_user_denied")
|
||||
} else if err.Id == "store.sql_team.get_member.missing.app_error" ||
|
||||
err.Id == "api.channel.add_user.to.channel.failed.deleted.app_error" {
|
||||
text = args.T("api.command_invite.user_not_in_team.app_error", map[string]interface{}{
|
||||
"Username": userProfile.Username,
|
||||
})
|
||||
} else {
|
||||
text = args.T("api.command_invite.fail.app_error")
|
||||
}
|
||||
return &model.CommandResponse{
|
||||
Text: text,
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
if args.ChannelId != channelToJoin.Id {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_invite.success", map[string]interface{}{
|
||||
"User": userProfile.Username,
|
||||
"Channel": channelToJoin.Name,
|
||||
}),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
return &model.CommandResponse{}
|
||||
}
|
||||
84
app/slashcommands/command_invite_people.go
Обычный файл
84
app/slashcommands/command_invite_people.go
Обычный файл
@@ -0,0 +1,84 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/mlog"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type InvitePeopleProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_INVITE_PEOPLE = "invite_people"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&InvitePeopleProvider{})
|
||||
}
|
||||
|
||||
func (me *InvitePeopleProvider) GetTrigger() string {
|
||||
return CMD_INVITE_PEOPLE
|
||||
}
|
||||
|
||||
func (me *InvitePeopleProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
autoComplete := true
|
||||
if !*a.Config().EmailSettings.SendEmailNotifications || !*a.Config().TeamSettings.EnableUserCreation || !*a.Config().ServiceSettings.EnableEmailInvitations {
|
||||
autoComplete = false
|
||||
}
|
||||
return &model.Command{
|
||||
Trigger: CMD_INVITE_PEOPLE,
|
||||
AutoComplete: autoComplete,
|
||||
AutoCompleteDesc: T("api.command.invite_people.desc"),
|
||||
AutoCompleteHint: T("api.command.invite_people.hint"),
|
||||
DisplayName: T("api.command.invite_people.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *InvitePeopleProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
if !a.HasPermissionToTeam(args.UserId, args.TeamId, model.PERMISSION_INVITE_USER) {
|
||||
return &model.CommandResponse{Text: args.T("api.command_invite_people.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
if !a.HasPermissionToTeam(args.UserId, args.TeamId, model.PERMISSION_ADD_USER_TO_TEAM) {
|
||||
return &model.CommandResponse{Text: args.T("api.command_invite_people.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
if !*a.Config().EmailSettings.SendEmailNotifications {
|
||||
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.email_off")}
|
||||
}
|
||||
|
||||
if !*a.Config().TeamSettings.EnableUserCreation {
|
||||
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.invite_off")}
|
||||
}
|
||||
|
||||
if !*a.Config().ServiceSettings.EnableEmailInvitations {
|
||||
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.email_invitations_off")}
|
||||
}
|
||||
|
||||
emailList := strings.Fields(message)
|
||||
|
||||
for i := len(emailList) - 1; i >= 0; i-- {
|
||||
emailList[i] = strings.Trim(emailList[i], ",")
|
||||
if !strings.Contains(emailList[i], "@") {
|
||||
emailList = append(emailList[:i], emailList[i+1:]...)
|
||||
}
|
||||
}
|
||||
|
||||
if len(emailList) == 0 {
|
||||
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.no_email")}
|
||||
}
|
||||
|
||||
if err := a.InviteNewUsersToTeam(emailList, args.TeamId, args.UserId); err != nil {
|
||||
mlog.Error(err.Error())
|
||||
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.fail")}
|
||||
}
|
||||
|
||||
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command.invite_people.sent")}
|
||||
}
|
||||
42
app/slashcommands/command_invite_people_test.go
Обычный файл
42
app/slashcommands/command_invite_people_test.go
Обычный файл
@@ -0,0 +1,42 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
func TestInvitePeopleProvider(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.EmailSettings.SendEmailNotifications = true
|
||||
*cfg.ServiceSettings.EnableEmailInvitations = true
|
||||
})
|
||||
|
||||
cmd := InvitePeopleProvider{}
|
||||
|
||||
notTeamUser := th.createUser()
|
||||
|
||||
// Test without required permissions
|
||||
args := &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
TeamId: th.BasicTeam.Id,
|
||||
UserId: notTeamUser.Id,
|
||||
}
|
||||
|
||||
actual := cmd.DoCommand(th.App, args, model.NewId()+"@simulator.amazonses.com")
|
||||
assert.Equal(t, "api.command_invite_people.permission.app_error", actual.Text)
|
||||
|
||||
// Test with required permissions.
|
||||
args.UserId = th.BasicUser.Id
|
||||
actual = cmd.DoCommand(th.App, args, model.NewId()+"@simulator.amazonses.com")
|
||||
assert.Equal(t, "api.command.invite_people.sent", actual.Text)
|
||||
}
|
||||
231
app/slashcommands/command_invite_test.go
Обычный файл
231
app/slashcommands/command_invite_test.go
Обычный файл
@@ -0,0 +1,231 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
func TestInviteProvider(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
channel := th.createChannel(th.BasicTeam, model.CHANNEL_OPEN)
|
||||
privateChannel := th.createChannel(th.BasicTeam, model.CHANNEL_PRIVATE)
|
||||
dmChannel := th.createDmChannel(th.BasicUser2)
|
||||
privateChannel2 := th.createChannelWithAnotherUser(th.BasicTeam, model.CHANNEL_PRIVATE, th.BasicUser2.Id)
|
||||
|
||||
basicUser3 := th.createUser()
|
||||
th.linkUserToTeam(basicUser3, th.BasicTeam)
|
||||
basicUser4 := th.createUser()
|
||||
deactivatedUser := th.createUser()
|
||||
th.App.UpdateActive(deactivatedUser, false)
|
||||
|
||||
var err *model.AppError
|
||||
_, err = th.App.CreateBot(&model.Bot{
|
||||
Username: "bot1",
|
||||
OwnerId: basicUser3.Id,
|
||||
Description: "a test bot",
|
||||
})
|
||||
require.Nil(t, err)
|
||||
|
||||
bot2, err := th.App.CreateBot(&model.Bot{
|
||||
Username: "bot2",
|
||||
OwnerId: basicUser3.Id,
|
||||
Description: "a test bot",
|
||||
})
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.AddUserToTeam(th.BasicTeam.Id, bot2.UserId, basicUser3.Id)
|
||||
require.Nil(t, err)
|
||||
|
||||
bot3, err := th.App.CreateBot(&model.Bot{
|
||||
Username: "bot3",
|
||||
OwnerId: basicUser3.Id,
|
||||
Description: "a test bot",
|
||||
})
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.AddUserToTeam(th.BasicTeam.Id, bot3.UserId, basicUser3.Id)
|
||||
require.Nil(t, err)
|
||||
err = th.App.RemoveUserFromTeam(th.BasicTeam.Id, bot3.UserId, basicUser3.Id)
|
||||
require.Nil(t, err)
|
||||
|
||||
InviteP := InviteProvider{}
|
||||
args := &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
TeamId: th.BasicTeam.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
userAndWrongChannel := "@" + th.BasicUser2.Username + " wrongchannel1"
|
||||
userAndChannel := "@" + th.BasicUser2.Username + " ~" + channel.Name + " "
|
||||
userAndDisplayChannel := "@" + th.BasicUser2.Username + " ~" + channel.DisplayName + " "
|
||||
userAndPrivateChannel := "@" + th.BasicUser2.Username + " ~" + privateChannel.Name
|
||||
userAndDMChannel := "@" + basicUser3.Username + " ~" + dmChannel.Name
|
||||
userAndInvalidPrivate := "@" + basicUser3.Username + " ~" + privateChannel2.Name
|
||||
deactivatedUserPublicChannel := "@" + deactivatedUser.Username + " ~" + channel.Name
|
||||
|
||||
groupChannel := th.createChannel(th.BasicTeam, model.CHANNEL_PRIVATE)
|
||||
_, err = th.App.AddChannelMember(th.BasicUser.Id, groupChannel, "", "")
|
||||
require.Nil(t, err)
|
||||
groupChannel.GroupConstrained = model.NewBool(true)
|
||||
groupChannel, _ = th.App.UpdateChannel(groupChannel)
|
||||
|
||||
groupChannelNonUser := "@" + th.BasicUser2.Username + " ~" + groupChannel.Name
|
||||
|
||||
tests := []struct {
|
||||
desc string
|
||||
expected string
|
||||
msg string
|
||||
}{
|
||||
{
|
||||
desc: "Missing user and channel in the command",
|
||||
expected: "api.command_invite.missing_message.app_error",
|
||||
msg: "",
|
||||
},
|
||||
{
|
||||
desc: "User added in the current channel",
|
||||
expected: "",
|
||||
msg: th.BasicUser2.Username,
|
||||
},
|
||||
{
|
||||
desc: "Add user to another channel not the current",
|
||||
expected: "api.command_invite.success",
|
||||
msg: userAndChannel,
|
||||
},
|
||||
{
|
||||
desc: "try to add a user to a direct channel",
|
||||
expected: "api.command_invite.directchannel.app_error",
|
||||
msg: userAndDMChannel,
|
||||
},
|
||||
{
|
||||
desc: "Try to add a user to a invalid channel",
|
||||
expected: "api.command_invite.channel.error",
|
||||
msg: userAndWrongChannel,
|
||||
},
|
||||
{
|
||||
desc: "Try to add a user to an private channel",
|
||||
expected: "api.command_invite.success",
|
||||
msg: userAndPrivateChannel,
|
||||
},
|
||||
{
|
||||
desc: "Using display channel name which is different form Channel name",
|
||||
expected: "api.command_invite.channel.error",
|
||||
msg: userAndDisplayChannel,
|
||||
},
|
||||
{
|
||||
desc: "Invalid user to current channel",
|
||||
expected: "api.command_invite.missing_user.app_error",
|
||||
msg: "@invalidUser123",
|
||||
},
|
||||
{
|
||||
desc: "Invalid user to current channel without @",
|
||||
expected: "api.command_invite.missing_user.app_error",
|
||||
msg: "invalidUser321",
|
||||
},
|
||||
{
|
||||
desc: "try to add a user which is not part of the team",
|
||||
expected: "api.command_invite.user_not_in_team.app_error",
|
||||
msg: basicUser4.Username,
|
||||
},
|
||||
{
|
||||
desc: "try to add a user not part of the group to a group channel",
|
||||
expected: "api.command_invite.group_constrained_user_denied",
|
||||
msg: groupChannelNonUser,
|
||||
},
|
||||
{
|
||||
desc: "try to add a user to a private channel with no permission",
|
||||
expected: "api.command_invite.private_channel.app_error",
|
||||
msg: userAndInvalidPrivate,
|
||||
},
|
||||
{
|
||||
desc: "try to add a deleted user to a public channel",
|
||||
expected: "api.command_invite.missing_user.app_error",
|
||||
msg: deactivatedUserPublicChannel,
|
||||
},
|
||||
{
|
||||
desc: "try to add bot to a public channel",
|
||||
expected: "api.command_invite.user_not_in_team.app_error",
|
||||
msg: "@bot1",
|
||||
},
|
||||
{
|
||||
desc: "add bot to a public channel",
|
||||
expected: "",
|
||||
msg: "@bot2",
|
||||
},
|
||||
{
|
||||
desc: "try to add bot removed from a team to a public channel",
|
||||
expected: "api.command_invite.user_not_in_team.app_error",
|
||||
msg: "@bot3",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
actual := InviteP.DoCommand(th.App, args, test.msg).Text
|
||||
assert.Equal(t, test.expected, actual)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInviteGroup(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
th.BasicTeam.GroupConstrained = model.NewBool(true)
|
||||
var err *model.AppError
|
||||
_, _ = th.App.AddTeamMember(th.BasicTeam.Id, th.BasicUser.Id)
|
||||
_, err = th.App.AddTeamMember(th.BasicTeam.Id, th.BasicUser2.Id)
|
||||
require.Nil(t, err)
|
||||
th.BasicTeam, _ = th.App.UpdateTeam(th.BasicTeam)
|
||||
|
||||
privateChannel := th.createChannel(th.BasicTeam, model.CHANNEL_PRIVATE)
|
||||
|
||||
groupChannelUser1 := "@" + th.BasicUser.Username + " ~" + privateChannel.Name
|
||||
groupChannelUser2 := "@" + th.BasicUser2.Username + " ~" + privateChannel.Name
|
||||
basicUser3 := th.createUser()
|
||||
groupChannelUser3 := "@" + basicUser3.Username + " ~" + privateChannel.Name
|
||||
|
||||
InviteP := InviteProvider{}
|
||||
args := &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
TeamId: th.BasicTeam.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
desc string
|
||||
expected string
|
||||
msg string
|
||||
}{
|
||||
{
|
||||
desc: "try to add an existing user part of the group to a group channel",
|
||||
expected: "api.command_invite.user_already_in_channel.app_error",
|
||||
msg: groupChannelUser1,
|
||||
},
|
||||
{
|
||||
desc: "try to add a user part of the group to a group channel",
|
||||
expected: "api.command_invite.success",
|
||||
msg: groupChannelUser2,
|
||||
},
|
||||
{
|
||||
desc: "try to add a user NOT part of the group to a group channel",
|
||||
expected: "api.command_invite.user_not_in_team.app_error",
|
||||
msg: groupChannelUser3,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
actual := InviteP.DoCommand(th.App, args, test.msg).Text
|
||||
assert.Equal(t, test.expected, actual)
|
||||
})
|
||||
}
|
||||
}
|
||||
78
app/slashcommands/command_join.go
Обычный файл
78
app/slashcommands/command_join.go
Обычный файл
@@ -0,0 +1,78 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type JoinProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_JOIN = "join"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&JoinProvider{})
|
||||
}
|
||||
|
||||
func (me *JoinProvider) GetTrigger() string {
|
||||
return CMD_JOIN
|
||||
}
|
||||
|
||||
func (me *JoinProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_JOIN,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_join.desc"),
|
||||
AutoCompleteHint: T("api.command_join.hint"),
|
||||
DisplayName: T("api.command_join.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *JoinProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
channelName := message
|
||||
|
||||
if strings.HasPrefix(message, "~") {
|
||||
channelName = message[1:]
|
||||
}
|
||||
|
||||
channel, err := a.Srv().Store.Channel().GetByName(args.TeamId, channelName, true)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_join.list.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
if channel.Name != channelName {
|
||||
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_join.missing.app_error")}
|
||||
}
|
||||
|
||||
switch channel.Type {
|
||||
case model.CHANNEL_OPEN:
|
||||
if !a.HasPermissionToChannel(args.UserId, channel.Id, model.PERMISSION_JOIN_PUBLIC_CHANNELS) {
|
||||
return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
case model.CHANNEL_PRIVATE:
|
||||
if !a.HasPermissionToChannel(args.UserId, channel.Id, model.PERMISSION_READ_CHANNEL) {
|
||||
return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
default:
|
||||
return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
if appErr := a.JoinChannel(channel, args.UserId); appErr != nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
team, appErr := a.GetTeam(channel.TeamId)
|
||||
if appErr != nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
return &model.CommandResponse{GotoLocation: args.SiteURL + "/" + team.Name + "/channels/" + channel.Name}
|
||||
}
|
||||
146
app/slashcommands/command_join_test.go
Обычный файл
146
app/slashcommands/command_join_test.go
Обычный файл
@@ -0,0 +1,146 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
func TestJoinCommandNoChannel(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
if testing.Short() {
|
||||
t.SkipNow()
|
||||
}
|
||||
|
||||
cmd := &JoinProvider{}
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
UserId: th.BasicUser2.Id,
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: th.BasicTeam.Id,
|
||||
}, "asdsad")
|
||||
|
||||
assert.Equal(t, "api.command_join.list.app_error", resp.Text)
|
||||
}
|
||||
|
||||
func TestJoinCommandForExistingChannel(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
if testing.Short() {
|
||||
t.SkipNow()
|
||||
}
|
||||
|
||||
channel2, _ := th.App.CreateChannel(&model.Channel{
|
||||
DisplayName: "AA",
|
||||
Name: "aa" + model.NewId() + "a",
|
||||
Type: model.CHANNEL_OPEN,
|
||||
TeamId: th.BasicTeam.Id,
|
||||
CreatorId: th.BasicUser.Id,
|
||||
}, false)
|
||||
|
||||
cmd := &JoinProvider{}
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
UserId: th.BasicUser2.Id,
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: th.BasicTeam.Id,
|
||||
}, channel2.Name)
|
||||
|
||||
assert.Equal(t, "", resp.Text)
|
||||
assert.Equal(t, "http://test.url/"+th.BasicTeam.Name+"/channels/"+channel2.Name, resp.GotoLocation)
|
||||
}
|
||||
|
||||
func TestJoinCommandWithTilde(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
if testing.Short() {
|
||||
t.SkipNow()
|
||||
}
|
||||
|
||||
channel2, _ := th.App.CreateChannel(&model.Channel{
|
||||
DisplayName: "AA",
|
||||
Name: "aa" + model.NewId() + "a",
|
||||
Type: model.CHANNEL_OPEN,
|
||||
TeamId: th.BasicTeam.Id,
|
||||
CreatorId: th.BasicUser.Id,
|
||||
}, false)
|
||||
|
||||
cmd := &JoinProvider{}
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
UserId: th.BasicUser2.Id,
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: th.BasicTeam.Id,
|
||||
}, "~"+channel2.Name)
|
||||
|
||||
assert.Equal(t, "", resp.Text)
|
||||
assert.Equal(t, "http://test.url/"+th.BasicTeam.Name+"/channels/"+channel2.Name, resp.GotoLocation)
|
||||
}
|
||||
|
||||
func TestJoinCommandPermissions(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
channel2, _ := th.App.CreateChannel(&model.Channel{
|
||||
DisplayName: "AA",
|
||||
Name: "aa" + model.NewId() + "a",
|
||||
Type: model.CHANNEL_OPEN,
|
||||
TeamId: th.BasicTeam.Id,
|
||||
CreatorId: th.BasicUser.Id,
|
||||
}, false)
|
||||
|
||||
cmd := &JoinProvider{}
|
||||
|
||||
user3 := th.createUser()
|
||||
|
||||
// Try a public channel *without* permission.
|
||||
args := &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
UserId: user3.Id,
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: th.BasicTeam.Id,
|
||||
}
|
||||
|
||||
actual := cmd.DoCommand(th.App, args, "~"+channel2.Name).Text
|
||||
assert.Equal(t, "api.command_join.fail.app_error", actual)
|
||||
|
||||
// Try a public channel with permission.
|
||||
args = &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
UserId: th.BasicUser2.Id,
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: th.BasicTeam.Id,
|
||||
}
|
||||
|
||||
actual = cmd.DoCommand(th.App, args, "~"+channel2.Name).Text
|
||||
assert.Equal(t, "", actual)
|
||||
|
||||
// Try a private channel *without* permission.
|
||||
channel3, _ := th.App.CreateChannel(&model.Channel{
|
||||
DisplayName: "BB",
|
||||
Name: "aa" + model.NewId() + "a",
|
||||
Type: model.CHANNEL_PRIVATE,
|
||||
TeamId: th.BasicTeam.Id,
|
||||
CreatorId: th.BasicUser.Id,
|
||||
}, false)
|
||||
|
||||
args = &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
UserId: th.BasicUser2.Id,
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: th.BasicTeam.Id,
|
||||
}
|
||||
|
||||
actual = cmd.DoCommand(th.App, args, "~"+channel3.Name).Text
|
||||
assert.Equal(t, "api.command_join.fail.app_error", actual)
|
||||
}
|
||||
79
app/slashcommands/command_leave.go
Обычный файл
79
app/slashcommands/command_leave.go
Обычный файл
@@ -0,0 +1,79 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type LeaveProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_LEAVE = "leave"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&LeaveProvider{})
|
||||
}
|
||||
|
||||
func (me *LeaveProvider) GetTrigger() string {
|
||||
return CMD_LEAVE
|
||||
}
|
||||
|
||||
func (me *LeaveProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_LEAVE,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_leave.desc"),
|
||||
DisplayName: T("api.command_leave.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *LeaveProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
var channel *model.Channel
|
||||
var noChannelErr *model.AppError
|
||||
if channel, noChannelErr = a.GetChannel(args.ChannelId); noChannelErr != nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
team, err := a.GetTeam(args.TeamId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
err = a.LeaveChannel(args.ChannelId, args.UserId)
|
||||
if err != nil {
|
||||
if channel.Name == model.DEFAULT_CHANNEL {
|
||||
return &model.CommandResponse{Text: args.T("api.channel.leave.default.app_error", map[string]interface{}{"Channel": model.DEFAULT_CHANNEL}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
member, err := a.GetTeamMember(team.Id, args.UserId)
|
||||
if err != nil || member.DeleteAt != 0 {
|
||||
return &model.CommandResponse{GotoLocation: args.SiteURL + "/"}
|
||||
}
|
||||
|
||||
user, err := a.GetUser(args.UserId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
if user.IsGuest() {
|
||||
members, err := a.GetChannelMembersForUser(team.Id, args.UserId)
|
||||
if err != nil || len(*members) == 0 {
|
||||
return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
channel, err := a.GetChannel((*members)[0].ChannelId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_leave.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
return &model.CommandResponse{GotoLocation: args.SiteURL + "/" + team.Name + "/channels/" + channel.Name}
|
||||
}
|
||||
|
||||
return &model.CommandResponse{GotoLocation: args.SiteURL + "/" + team.Name + "/channels/" + model.DEFAULT_CHANNEL}
|
||||
}
|
||||
147
app/slashcommands/command_leave_test.go
Обычный файл
147
app/slashcommands/command_leave_test.go
Обычный файл
@@ -0,0 +1,147 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
func TestLeaveProviderDoCommand(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
lp := LeaveProvider{}
|
||||
|
||||
publicChannel, _ := th.App.CreateChannel(&model.Channel{
|
||||
DisplayName: "AA",
|
||||
Name: "aa" + model.NewId() + "a",
|
||||
Type: model.CHANNEL_OPEN,
|
||||
TeamId: th.BasicTeam.Id,
|
||||
CreatorId: th.BasicUser.Id,
|
||||
}, false)
|
||||
|
||||
privateChannel, _ := th.App.CreateChannel(&model.Channel{
|
||||
DisplayName: "BB",
|
||||
Name: "aa" + model.NewId() + "a",
|
||||
Type: model.CHANNEL_OPEN,
|
||||
TeamId: th.BasicTeam.Id,
|
||||
CreatorId: th.BasicUser.Id,
|
||||
}, false)
|
||||
|
||||
defaultChannel, err := th.App.GetChannelByName(model.DEFAULT_CHANNEL, th.BasicTeam.Id, false)
|
||||
require.Nil(t, err)
|
||||
|
||||
guest := th.createGuest()
|
||||
|
||||
th.App.AddUserToTeam(th.BasicTeam.Id, th.BasicUser.Id, th.BasicUser.Id)
|
||||
th.App.AddUserToChannel(th.BasicUser, publicChannel)
|
||||
th.App.AddUserToChannel(th.BasicUser, privateChannel)
|
||||
th.App.AddUserToTeam(th.BasicTeam.Id, guest.Id, guest.Id)
|
||||
th.App.AddUserToChannel(guest, publicChannel)
|
||||
th.App.AddUserToChannel(guest, defaultChannel)
|
||||
|
||||
t.Run("Should error when no Channel ID in args", func(t *testing.T) {
|
||||
args := &model.CommandArgs{
|
||||
UserId: th.BasicUser.Id,
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
}
|
||||
actual := lp.DoCommand(th.App, args, "")
|
||||
assert.Equal(t, "api.command_leave.fail.app_error", actual.Text)
|
||||
assert.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, actual.ResponseType)
|
||||
})
|
||||
|
||||
t.Run("Should error when no Team ID in args", func(t *testing.T) {
|
||||
args := &model.CommandArgs{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: publicChannel.Id,
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
}
|
||||
actual := lp.DoCommand(th.App, args, "")
|
||||
assert.Equal(t, "api.command_leave.fail.app_error", actual.Text)
|
||||
assert.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, actual.ResponseType)
|
||||
})
|
||||
|
||||
t.Run("Leave a public channel", func(t *testing.T) {
|
||||
args := &model.CommandArgs{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: publicChannel.Id,
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
TeamId: th.BasicTeam.Id,
|
||||
SiteURL: "http://localhost:8065",
|
||||
}
|
||||
actual := lp.DoCommand(th.App, args, "")
|
||||
assert.Equal(t, "", actual.Text)
|
||||
assert.Equal(t, args.SiteURL+"/"+th.BasicTeam.Name+"/channels/"+model.DEFAULT_CHANNEL, actual.GotoLocation)
|
||||
assert.Equal(t, "", actual.ResponseType)
|
||||
|
||||
_, err = th.App.GetChannelMember(publicChannel.Id, th.BasicUser.Id)
|
||||
assert.NotNil(t, err)
|
||||
assert.NotNil(t, err.Id, "store.sql_channel.get_member.missing.app_error")
|
||||
})
|
||||
|
||||
t.Run("Leave a private channel", func(t *testing.T) {
|
||||
args := &model.CommandArgs{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: privateChannel.Id,
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
TeamId: th.BasicTeam.Id,
|
||||
SiteURL: "http://localhost:8065",
|
||||
}
|
||||
actual := lp.DoCommand(th.App, args, "")
|
||||
assert.Equal(t, "", actual.Text)
|
||||
})
|
||||
|
||||
t.Run("Should not leave a default channel", func(t *testing.T) {
|
||||
args := &model.CommandArgs{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: defaultChannel.Id,
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
TeamId: th.BasicTeam.Id,
|
||||
SiteURL: "http://localhost:8065",
|
||||
}
|
||||
actual := lp.DoCommand(th.App, args, "")
|
||||
assert.Equal(t, "api.channel.leave.default.app_error", actual.Text)
|
||||
})
|
||||
|
||||
t.Run("Should allow to leave a default channel if user is guest", func(t *testing.T) {
|
||||
args := &model.CommandArgs{
|
||||
UserId: guest.Id,
|
||||
ChannelId: defaultChannel.Id,
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
TeamId: th.BasicTeam.Id,
|
||||
SiteURL: "http://localhost:8065",
|
||||
}
|
||||
actual := lp.DoCommand(th.App, args, "")
|
||||
assert.Equal(t, "", actual.Text)
|
||||
assert.Equal(t, args.SiteURL+"/"+th.BasicTeam.Name+"/channels/"+publicChannel.Name, actual.GotoLocation)
|
||||
assert.Equal(t, "", actual.ResponseType)
|
||||
|
||||
_, err = th.App.GetChannelMember(defaultChannel.Id, guest.Id)
|
||||
assert.NotNil(t, err)
|
||||
assert.NotNil(t, err.Id, "store.sql_channel.get_member.missing.app_error")
|
||||
})
|
||||
|
||||
t.Run("Should redirect to the team if is the last channel", func(t *testing.T) {
|
||||
args := &model.CommandArgs{
|
||||
UserId: guest.Id,
|
||||
ChannelId: publicChannel.Id,
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
TeamId: th.BasicTeam.Id,
|
||||
SiteURL: "http://localhost:8065",
|
||||
}
|
||||
actual := lp.DoCommand(th.App, args, "")
|
||||
assert.Equal(t, "", actual.Text)
|
||||
assert.Equal(t, args.SiteURL+"/", actual.GotoLocation)
|
||||
assert.Equal(t, "", actual.ResponseType)
|
||||
|
||||
_, err = th.App.GetChannelMember(publicChannel.Id, guest.Id)
|
||||
assert.NotNil(t, err)
|
||||
assert.NotNil(t, err.Id, "store.sql_channel.get_member.missing.app_error")
|
||||
})
|
||||
}
|
||||
585
app/slashcommands/command_loadtest.go
Обычный файл
585
app/slashcommands/command_loadtest.go
Обычный файл
@@ -0,0 +1,585 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"path"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/mlog"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/utils"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
var usage = `Mattermost testing commands to help configure the system
|
||||
|
||||
COMMANDS:
|
||||
|
||||
Setup - Creates a testing environment in current team.
|
||||
/test setup [teams] [fuzz] <Num Channels> <Num Users> <NumPosts>
|
||||
|
||||
Example:
|
||||
/test setup teams fuzz 10 20 50
|
||||
|
||||
Users - Add a specified number of random users with fuzz text to current team.
|
||||
/test users [fuzz] <Min Users> <Max Users>
|
||||
|
||||
Example:
|
||||
/test users fuzz 5 10
|
||||
|
||||
Channels - Add a specified number of random channels with fuzz text to current team.
|
||||
/test channels [fuzz] <Min Channels> <Max Channels>
|
||||
|
||||
Example:
|
||||
/test channels fuzz 5 10
|
||||
|
||||
ThreadedPost - create a large threaded post
|
||||
/test threaded_post
|
||||
|
||||
Posts - Add some random posts with fuzz text to current channel.
|
||||
/test posts [fuzz] <Min Posts> <Max Posts> <Max Images>
|
||||
|
||||
Example:
|
||||
/test posts fuzz 5 10 3
|
||||
|
||||
Post - Add post to a channel as another user.
|
||||
/test post u=@username p=passwd c=~channelname t=teamname "message"
|
||||
|
||||
Example:
|
||||
/test post u=@user-1 p=user-1 c=~town-square t=ad-1 "message"
|
||||
|
||||
Url - Add a post containing the text from a given url to current channel.
|
||||
/test url
|
||||
|
||||
Example:
|
||||
/test http://www.example.com/sample_file.md
|
||||
|
||||
Json - Add a post using the JSON file as payload to the current channel.
|
||||
/test json url
|
||||
|
||||
Example
|
||||
/test json http://www.example.com/sample_body.json
|
||||
|
||||
`
|
||||
|
||||
const (
|
||||
CMD_TEST = "test"
|
||||
)
|
||||
|
||||
var (
|
||||
userRE = regexp.MustCompile(`u=@([^\s]+)`)
|
||||
passwdRE = regexp.MustCompile(`p=([^\s]+)`)
|
||||
teamRE = regexp.MustCompile(`t=([^\s]+)`)
|
||||
channelRE = regexp.MustCompile(`c=~([^\s]+)`)
|
||||
messageRE = regexp.MustCompile(`"(.*)"`)
|
||||
)
|
||||
|
||||
type LoadTestProvider struct {
|
||||
}
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&LoadTestProvider{})
|
||||
}
|
||||
|
||||
func (me *LoadTestProvider) GetTrigger() string {
|
||||
return CMD_TEST
|
||||
}
|
||||
|
||||
func (me *LoadTestProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
if !*a.Config().ServiceSettings.EnableTesting {
|
||||
return nil
|
||||
}
|
||||
return &model.Command{
|
||||
Trigger: CMD_TEST,
|
||||
AutoComplete: false,
|
||||
AutoCompleteDesc: "Debug Load Testing",
|
||||
AutoCompleteHint: "help",
|
||||
DisplayName: "test",
|
||||
}
|
||||
}
|
||||
|
||||
func (me *LoadTestProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
commandResponse, err := me.doCommand(a, args, message)
|
||||
if err != nil {
|
||||
mlog.Error("failed command /"+CMD_TEST, mlog.Err(err))
|
||||
}
|
||||
|
||||
return commandResponse
|
||||
}
|
||||
|
||||
func (me *LoadTestProvider) doCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
//This command is only available when EnableTesting is true
|
||||
if !*a.Config().ServiceSettings.EnableTesting {
|
||||
return &model.CommandResponse{}, nil
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "setup") {
|
||||
return me.SetupCommand(a, args, message)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "users") {
|
||||
return me.UsersCommand(a, args, message)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "activate_user") {
|
||||
return me.ActivateUserCommand(a, args, message)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "deactivate_user") {
|
||||
return me.DeActivateUserCommand(a, args, message)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "channels") {
|
||||
return me.ChannelsCommand(a, args, message)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "posts") {
|
||||
return me.PostsCommand(a, args, message)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "post") {
|
||||
return me.PostCommand(a, args, message)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "threaded_post") {
|
||||
return me.ThreadedPostCommand(a, args, message)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "url") {
|
||||
return me.UrlCommand(a, args, message)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "json") {
|
||||
return me.JsonCommand(a, args, message)
|
||||
}
|
||||
|
||||
return me.HelpCommand(args, message), nil
|
||||
}
|
||||
|
||||
func (me *LoadTestProvider) HelpCommand(args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
return &model.CommandResponse{Text: usage, ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
func (me *LoadTestProvider) SetupCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
tokens := strings.Fields(strings.TrimPrefix(message, "setup"))
|
||||
doTeams := contains(tokens, "teams")
|
||||
doFuzz := contains(tokens, "fuzz")
|
||||
|
||||
numArgs := 0
|
||||
if doTeams {
|
||||
numArgs++
|
||||
}
|
||||
if doFuzz {
|
||||
numArgs++
|
||||
}
|
||||
|
||||
var numTeams int
|
||||
var numChannels int
|
||||
var numUsers int
|
||||
var numPosts int
|
||||
|
||||
// Defaults
|
||||
numTeams = 10
|
||||
numChannels = 10
|
||||
numUsers = 10
|
||||
numPosts = 10
|
||||
|
||||
if doTeams {
|
||||
if (len(tokens) - numArgs) >= 4 {
|
||||
numTeams, _ = strconv.Atoi(tokens[numArgs+0])
|
||||
numChannels, _ = strconv.Atoi(tokens[numArgs+1])
|
||||
numUsers, _ = strconv.Atoi(tokens[numArgs+2])
|
||||
numPosts, _ = strconv.Atoi(tokens[numArgs+3])
|
||||
}
|
||||
} else {
|
||||
if (len(tokens) - numArgs) >= 3 {
|
||||
numChannels, _ = strconv.Atoi(tokens[numArgs+0])
|
||||
numUsers, _ = strconv.Atoi(tokens[numArgs+1])
|
||||
numPosts, _ = strconv.Atoi(tokens[numArgs+2])
|
||||
}
|
||||
}
|
||||
client := model.NewAPIv4Client(args.SiteURL)
|
||||
|
||||
if doTeams {
|
||||
if err := CreateBasicUser(a, client); err != nil {
|
||||
return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
_, resp := client.Login(BTEST_USER_EMAIL, BTEST_USER_PASSWORD)
|
||||
if resp.Error != nil {
|
||||
return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, resp.Error
|
||||
}
|
||||
environment, err := CreateTestEnvironmentWithTeams(
|
||||
a,
|
||||
client,
|
||||
utils.Range{Begin: numTeams, End: numTeams},
|
||||
utils.Range{Begin: numChannels, End: numChannels},
|
||||
utils.Range{Begin: numUsers, End: numUsers},
|
||||
utils.Range{Begin: numPosts, End: numPosts},
|
||||
doFuzz)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
|
||||
mlog.Info("Testing environment created")
|
||||
for i := 0; i < len(environment.Teams); i++ {
|
||||
mlog.Info("Team Created: " + environment.Teams[i].Name)
|
||||
mlog.Info("\t User to login: " + environment.Environments[i].Users[0].Email + ", " + USER_PASSWORD)
|
||||
}
|
||||
} else {
|
||||
team, err := a.Srv().Store.Team().Get(args.TeamId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
|
||||
CreateTestEnvironmentInTeam(
|
||||
a,
|
||||
client,
|
||||
team,
|
||||
utils.Range{Begin: numChannels, End: numChannels},
|
||||
utils.Range{Begin: numUsers, End: numUsers},
|
||||
utils.Range{Begin: numPosts, End: numPosts},
|
||||
doFuzz)
|
||||
}
|
||||
|
||||
return &model.CommandResponse{Text: "Created environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
func (me *LoadTestProvider) ActivateUserCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
user_id := strings.TrimSpace(strings.TrimPrefix(message, "activate_user"))
|
||||
if err := a.UpdateUserActive(user_id, true); err != nil {
|
||||
return &model.CommandResponse{Text: "Failed to activate user", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
|
||||
return &model.CommandResponse{Text: "Activated user", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
func (me *LoadTestProvider) DeActivateUserCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
user_id := strings.TrimSpace(strings.TrimPrefix(message, "deactivate_user"))
|
||||
if err := a.UpdateUserActive(user_id, false); err != nil {
|
||||
return &model.CommandResponse{Text: "Failed to deactivate user", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
|
||||
return &model.CommandResponse{Text: "DeActivated user", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
func (me *LoadTestProvider) UsersCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
cmd := strings.TrimSpace(strings.TrimPrefix(message, "users"))
|
||||
|
||||
doFuzz := false
|
||||
if strings.Index(cmd, "fuzz") == 0 {
|
||||
doFuzz = true
|
||||
cmd = strings.TrimSpace(strings.TrimPrefix(cmd, "fuzz"))
|
||||
}
|
||||
|
||||
usersr, ok := parseRange(cmd, "")
|
||||
if !ok {
|
||||
usersr = utils.Range{Begin: 2, End: 5}
|
||||
}
|
||||
|
||||
team, err := a.Srv().Store.Team().Get(args.TeamId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: "Failed to add users", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
|
||||
client := model.NewAPIv4Client(args.SiteURL)
|
||||
userCreator := NewAutoUserCreator(a, client, team)
|
||||
userCreator.Fuzzy = doFuzz
|
||||
userCreator.CreateTestUsers(usersr)
|
||||
|
||||
return &model.CommandResponse{Text: "Added users", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
func (me *LoadTestProvider) ChannelsCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
cmd := strings.TrimSpace(strings.TrimPrefix(message, "channels"))
|
||||
|
||||
doFuzz := false
|
||||
if strings.Index(cmd, "fuzz") == 0 {
|
||||
doFuzz = true
|
||||
cmd = strings.TrimSpace(strings.TrimPrefix(cmd, "fuzz"))
|
||||
}
|
||||
|
||||
channelsr, ok := parseRange(cmd, "")
|
||||
if !ok {
|
||||
channelsr = utils.Range{Begin: 2, End: 5}
|
||||
}
|
||||
|
||||
team, err := a.Srv().Store.Team().Get(args.TeamId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: "Failed to add channels", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
|
||||
channelCreator := NewAutoChannelCreator(a, team, args.UserId)
|
||||
channelCreator.Fuzzy = doFuzz
|
||||
if _, err := channelCreator.CreateTestChannels(channelsr); err != nil {
|
||||
return &model.CommandResponse{Text: "Failed to create test channels: " + err.Error(), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
|
||||
return &model.CommandResponse{Text: "Added channels", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
func (me *LoadTestProvider) ThreadedPostCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
var usernames []string
|
||||
options := &model.UserGetOptions{InTeamId: args.TeamId, Page: 0, PerPage: 1000}
|
||||
if profileUsers, err := a.Srv().Store.User().GetProfiles(options); err == nil {
|
||||
usernames = make([]string, len(profileUsers))
|
||||
i := 0
|
||||
for _, userprof := range profileUsers {
|
||||
usernames[i] = userprof.Username
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
testPoster := NewAutoPostCreator(a, args.ChannelId, args.UserId)
|
||||
testPoster.Fuzzy = true
|
||||
testPoster.Users = usernames
|
||||
rpost, err2 := testPoster.CreateRandomPost()
|
||||
if err2 != nil {
|
||||
return &model.CommandResponse{Text: "Failed to create a post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err2
|
||||
}
|
||||
for i := 0; i < 1000; i++ {
|
||||
testPoster.CreateRandomPostNested(rpost.Id, rpost.Id)
|
||||
}
|
||||
|
||||
return &model.CommandResponse{Text: "Added threaded post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
func (me *LoadTestProvider) PostsCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
cmd := strings.TrimSpace(strings.TrimPrefix(message, "posts"))
|
||||
|
||||
doFuzz := false
|
||||
if strings.Index(cmd, "fuzz") == 0 {
|
||||
doFuzz = true
|
||||
cmd = strings.TrimSpace(strings.TrimPrefix(cmd, "fuzz"))
|
||||
}
|
||||
|
||||
postsr, ok := parseRange(cmd, "")
|
||||
if !ok {
|
||||
postsr = utils.Range{Begin: 20, End: 30}
|
||||
}
|
||||
|
||||
tokens := strings.Fields(cmd)
|
||||
rimages := utils.Range{Begin: 0, End: 0}
|
||||
if len(tokens) >= 3 {
|
||||
if numImages, err := strconv.Atoi(tokens[2]); err == nil {
|
||||
rimages = utils.Range{Begin: numImages, End: numImages}
|
||||
}
|
||||
}
|
||||
|
||||
var usernames []string
|
||||
options := &model.UserGetOptions{InTeamId: args.TeamId, Page: 0, PerPage: 1000}
|
||||
if profileUsers, err := a.Srv().Store.User().GetProfiles(options); err == nil {
|
||||
usernames = make([]string, len(profileUsers))
|
||||
i := 0
|
||||
for _, userprof := range profileUsers {
|
||||
usernames[i] = userprof.Username
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
testPoster := NewAutoPostCreator(a, args.ChannelId, args.UserId)
|
||||
testPoster.Fuzzy = doFuzz
|
||||
testPoster.Users = usernames
|
||||
|
||||
numImages := utils.RandIntFromRange(rimages)
|
||||
numPosts := utils.RandIntFromRange(postsr)
|
||||
for i := 0; i < numPosts; i++ {
|
||||
testPoster.HasImage = (i < numImages)
|
||||
_, err := testPoster.CreateRandomPost()
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: "Failed to add posts", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return &model.CommandResponse{Text: "Added posts", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
func getMatch(re *regexp.Regexp, text string) string {
|
||||
if match := re.FindStringSubmatch(text); match != nil {
|
||||
return match[1]
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func (me *LoadTestProvider) PostCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
textMessage := getMatch(messageRE, message)
|
||||
if textMessage == "" {
|
||||
return &model.CommandResponse{Text: "No message to post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
teamName := getMatch(teamRE, message)
|
||||
team, err := a.GetTeamByName(teamName)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: "Failed to get a team", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
|
||||
channelName := getMatch(channelRE, message)
|
||||
channel, err := a.GetChannelByName(channelName, team.Id, true)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: "Failed to get a channel", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
|
||||
passwd := getMatch(passwdRE, message)
|
||||
username := getMatch(userRE, message)
|
||||
user, err := a.GetUserByUsername(username)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: "Failed to get a user", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
|
||||
client := model.NewAPIv4Client(args.SiteURL)
|
||||
_, resp := client.LoginById(user.Id, passwd)
|
||||
if resp.Error != nil {
|
||||
return &model.CommandResponse{Text: "Failed to login a user", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, resp.Error
|
||||
}
|
||||
|
||||
post := &model.Post{
|
||||
ChannelId: channel.Id,
|
||||
Message: textMessage,
|
||||
}
|
||||
_, resp = client.CreatePost(post)
|
||||
if resp.Error != nil {
|
||||
return &model.CommandResponse{Text: "Failed to create a post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, resp.Error
|
||||
}
|
||||
|
||||
return &model.CommandResponse{Text: "Added a post to " + channel.DisplayName, ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
func (me *LoadTestProvider) UrlCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
url := strings.TrimSpace(strings.TrimPrefix(message, "url"))
|
||||
if len(url) == 0 {
|
||||
return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
// provide a shortcut to easily access tests stored in doc/developer/tests
|
||||
if !strings.HasPrefix(url, "http") {
|
||||
url = "https://raw.githubusercontent.com/mattermost/mattermost-server/master/tests/" + url
|
||||
|
||||
if path.Ext(url) == "" {
|
||||
url += ".md"
|
||||
}
|
||||
}
|
||||
|
||||
r, err := http.Get(url)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: "Unable to get file", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
defer func() {
|
||||
io.Copy(ioutil.Discard, r.Body)
|
||||
r.Body.Close()
|
||||
}()
|
||||
|
||||
if r.StatusCode > 400 {
|
||||
return &model.CommandResponse{Text: "Unable to get file", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, errors.Errorf("unexpected status code %d", r.StatusCode)
|
||||
}
|
||||
|
||||
bytes := make([]byte, 4000)
|
||||
|
||||
// break contents into 4000 byte posts
|
||||
for {
|
||||
length, err := r.Body.Read(bytes)
|
||||
if err != nil && err != io.EOF {
|
||||
return &model.CommandResponse{Text: "Encountered error reading file", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
|
||||
if length == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
post := &model.Post{}
|
||||
post.Message = string(bytes[:length])
|
||||
post.ChannelId = args.ChannelId
|
||||
post.UserId = args.UserId
|
||||
|
||||
if _, err := a.CreatePostMissingChannel(post, false); err != nil {
|
||||
return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
}
|
||||
|
||||
return &model.CommandResponse{Text: "Loaded data", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
func (me *LoadTestProvider) JsonCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
url := strings.TrimSpace(strings.TrimPrefix(message, "json"))
|
||||
if len(url) == 0 {
|
||||
return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
// provide a shortcut to easily access tests stored in doc/developer/tests
|
||||
if !strings.HasPrefix(url, "http") {
|
||||
url = "https://raw.githubusercontent.com/mattermost/mattermost-server/master/tests/" + url
|
||||
|
||||
if path.Ext(url) == "" {
|
||||
url += ".json"
|
||||
}
|
||||
}
|
||||
|
||||
r, err := http.Get(url)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: "Unable to get file", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
|
||||
if r.StatusCode > 400 {
|
||||
return &model.CommandResponse{Text: "Unable to get file", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, errors.Errorf("unexpected status code %d", r.StatusCode)
|
||||
}
|
||||
defer func() {
|
||||
io.Copy(ioutil.Discard, r.Body)
|
||||
r.Body.Close()
|
||||
}()
|
||||
|
||||
post := model.PostFromJson(r.Body)
|
||||
post.ChannelId = args.ChannelId
|
||||
post.UserId = args.UserId
|
||||
if post.Message == "" {
|
||||
post.Message = message
|
||||
}
|
||||
|
||||
if _, err := a.CreatePostMissingChannel(post, false); err != nil {
|
||||
return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
|
||||
return &model.CommandResponse{Text: "Loaded data", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
func parseRange(command string, cmd string) (utils.Range, bool) {
|
||||
tokens := strings.Fields(strings.TrimPrefix(command, cmd))
|
||||
var begin int
|
||||
var end int
|
||||
var err1 error
|
||||
var err2 error
|
||||
switch {
|
||||
case len(tokens) == 1:
|
||||
begin, err1 = strconv.Atoi(tokens[0])
|
||||
end = begin
|
||||
if err1 != nil {
|
||||
return utils.Range{Begin: 0, End: 0}, false
|
||||
}
|
||||
case len(tokens) >= 2:
|
||||
begin, err1 = strconv.Atoi(tokens[0])
|
||||
end, err2 = strconv.Atoi(tokens[1])
|
||||
if err1 != nil || err2 != nil {
|
||||
return utils.Range{Begin: 0, End: 0}, false
|
||||
}
|
||||
default:
|
||||
return utils.Range{Begin: 0, End: 0}, false
|
||||
}
|
||||
return utils.Range{Begin: begin, End: end}, true
|
||||
}
|
||||
|
||||
func contains(items []string, token string) bool {
|
||||
for _, elem := range items {
|
||||
if elem == token {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
40
app/slashcommands/command_logout.go
Обычный файл
40
app/slashcommands/command_logout.go
Обычный файл
@@ -0,0 +1,40 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type LogoutProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_LOGOUT = "logout"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&LogoutProvider{})
|
||||
}
|
||||
|
||||
func (me *LogoutProvider) GetTrigger() string {
|
||||
return CMD_LOGOUT
|
||||
}
|
||||
|
||||
func (me *LogoutProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_LOGOUT,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_logout.desc"),
|
||||
AutoCompleteHint: "",
|
||||
DisplayName: T("api.command_logout.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *LogoutProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
// Actual logout is handled client side.
|
||||
return &model.CommandResponse{GotoLocation: "/login"}
|
||||
}
|
||||
46
app/slashcommands/command_me.go
Обычный файл
46
app/slashcommands/command_me.go
Обычный файл
@@ -0,0 +1,46 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type MeProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_ME = "me"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&MeProvider{})
|
||||
}
|
||||
|
||||
func (me *MeProvider) GetTrigger() string {
|
||||
return CMD_ME
|
||||
}
|
||||
|
||||
func (me *MeProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_ME,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_me.desc"),
|
||||
AutoCompleteHint: T("api.command_me.hint"),
|
||||
DisplayName: T("api.command_me.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *MeProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
return &model.CommandResponse{
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL,
|
||||
Type: model.POST_ME,
|
||||
Text: "*" + message + "*",
|
||||
Props: model.StringInterface{
|
||||
"message": message,
|
||||
},
|
||||
}
|
||||
}
|
||||
30
app/slashcommands/command_me_test.go
Обычный файл
30
app/slashcommands/command_me_test.go
Обычный файл
@@ -0,0 +1,30 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
func TestMeProviderDoCommand(t *testing.T) {
|
||||
th := setup(t)
|
||||
defer th.tearDown()
|
||||
|
||||
mp := MeProvider{}
|
||||
|
||||
msg := "hello"
|
||||
|
||||
resp := mp.DoCommand(th.App, &model.CommandArgs{}, msg)
|
||||
|
||||
assert.Equal(t, model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, resp.ResponseType)
|
||||
assert.Equal(t, model.POST_ME, resp.Type)
|
||||
assert.Equal(t, "*"+msg+"*", resp.Text)
|
||||
assert.Equal(t, model.StringInterface{
|
||||
"message": msg,
|
||||
}, resp.Props)
|
||||
}
|
||||
115
app/slashcommands/command_msg.go
Обычный файл
115
app/slashcommands/command_msg.go
Обычный файл
@@ -0,0 +1,115 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/mlog"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/store"
|
||||
)
|
||||
|
||||
type msgProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_MSG = "msg"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&msgProvider{})
|
||||
}
|
||||
|
||||
func (me *msgProvider) GetTrigger() string {
|
||||
return CMD_MSG
|
||||
}
|
||||
|
||||
func (me *msgProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_MSG,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_msg.desc"),
|
||||
AutoCompleteHint: T("api.command_msg.hint"),
|
||||
DisplayName: T("api.command_msg.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *msgProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
splitMessage := strings.SplitN(message, " ", 2)
|
||||
|
||||
parsedMessage := ""
|
||||
targetUsername := ""
|
||||
|
||||
if len(splitMessage) > 1 {
|
||||
parsedMessage = strings.SplitN(message, " ", 2)[1]
|
||||
}
|
||||
targetUsername = strings.SplitN(message, " ", 2)[0]
|
||||
targetUsername = strings.TrimPrefix(targetUsername, "@")
|
||||
|
||||
userProfile, err := a.Srv().Store.User().GetByUsername(targetUsername)
|
||||
if err != nil {
|
||||
mlog.Error(err.Error())
|
||||
return &model.CommandResponse{Text: args.T("api.command_msg.missing.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
if userProfile.Id == args.UserId {
|
||||
return &model.CommandResponse{Text: args.T("api.command_msg.missing.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
canSee, err := a.UserCanSeeOtherUser(args.UserId, userProfile.Id)
|
||||
if err != nil {
|
||||
mlog.Error(err.Error())
|
||||
return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
if !canSee {
|
||||
return &model.CommandResponse{Text: args.T("api.command_msg.missing.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
// Find the channel based on this user
|
||||
channelName := model.GetDMNameFromIds(args.UserId, userProfile.Id)
|
||||
|
||||
targetChannelId := ""
|
||||
if channel, channelErr := a.Srv().Store.Channel().GetByName(args.TeamId, channelName, true); channelErr != nil {
|
||||
var nfErr *store.ErrNotFound
|
||||
if errors.As(channelErr, &nfErr) {
|
||||
if !a.HasPermissionTo(args.UserId, model.PERMISSION_CREATE_DIRECT_CHANNEL) {
|
||||
return &model.CommandResponse{Text: args.T("api.command_msg.permission.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
var directChannel *model.Channel
|
||||
if directChannel, err = a.GetOrCreateDirectChannel(args.UserId, userProfile.Id); err != nil {
|
||||
mlog.Error(err.Error())
|
||||
return &model.CommandResponse{Text: args.T("api.command_msg.dm_fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
} else {
|
||||
targetChannelId = directChannel.Id
|
||||
}
|
||||
} else {
|
||||
mlog.Error(channelErr.Error())
|
||||
return &model.CommandResponse{Text: args.T("api.command_msg.dm_fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
} else {
|
||||
targetChannelId = channel.Id
|
||||
}
|
||||
|
||||
if len(parsedMessage) > 0 {
|
||||
post := &model.Post{}
|
||||
post.Message = parsedMessage
|
||||
post.ChannelId = targetChannelId
|
||||
post.UserId = args.UserId
|
||||
if _, err = a.CreatePostMissingChannel(post, true); err != nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
}
|
||||
|
||||
team, err := a.GetTeam(args.TeamId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_msg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
return &model.CommandResponse{GotoLocation: args.SiteURL + "/" + team.Name + "/channels/" + channelName, Text: "", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
94
app/slashcommands/command_msg_test.go
Обычный файл
94
app/slashcommands/command_msg_test.go
Обычный файл
@@ -0,0 +1,94 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
func TestMsgProvider(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
team := th.createTeam()
|
||||
th.linkUserToTeam(th.BasicUser, team)
|
||||
cmd := &msgProvider{}
|
||||
|
||||
th.removePermissionFromRole(model.PERMISSION_CREATE_DIRECT_CHANNEL.Id, model.SYSTEM_USER_ROLE_ID)
|
||||
|
||||
// Check without permission to create a DM channel.
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: team.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}, "@"+th.BasicUser2.Username+" hello")
|
||||
|
||||
channelName := model.GetDMNameFromIds(th.BasicUser.Id, th.BasicUser2.Id)
|
||||
assert.Equal(t, "api.command_msg.permission.app_error", resp.Text)
|
||||
assert.Equal(t, "", resp.GotoLocation)
|
||||
|
||||
th.addPermissionToRole(model.PERMISSION_CREATE_DIRECT_CHANNEL.Id, model.SYSTEM_USER_ROLE_ID)
|
||||
|
||||
// Check with permission to create a DM channel.
|
||||
resp = cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: team.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}, "@"+th.BasicUser2.Username+" hello")
|
||||
|
||||
assert.Equal(t, "", resp.Text)
|
||||
assert.Equal(t, "http://test.url/"+team.Name+"/channels/"+channelName, resp.GotoLocation)
|
||||
|
||||
// Check without permission to post to an existing DM channel.
|
||||
resp = cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: team.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}, "@"+th.BasicUser2.Username+" hello")
|
||||
|
||||
assert.Equal(t, "", resp.Text)
|
||||
assert.Equal(t, "http://test.url/"+team.Name+"/channels/"+channelName, resp.GotoLocation)
|
||||
|
||||
// Check that a guest user cannot message a user who is not in a channel/team with him
|
||||
guest := th.createGuest()
|
||||
user := th.createUser()
|
||||
|
||||
th.linkUserToTeam(user, team)
|
||||
th.linkUserToTeam(guest, th.BasicTeam)
|
||||
th.addUserToChannel(guest, th.BasicChannel)
|
||||
|
||||
resp = cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: th.BasicTeam.Id,
|
||||
UserId: guest.Id,
|
||||
}, "@"+user.Username+" hello")
|
||||
|
||||
assert.Equal(t, "api.command_msg.missing.app_error", resp.Text)
|
||||
assert.Equal(t, "", resp.GotoLocation)
|
||||
|
||||
// Check that a guest user can message a user who is in a channel/team with him
|
||||
th.linkUserToTeam(user, th.BasicTeam)
|
||||
th.addUserToChannel(user, th.BasicChannel)
|
||||
|
||||
resp = cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: th.BasicTeam.Id,
|
||||
UserId: guest.Id,
|
||||
}, "@"+user.Username+" hello")
|
||||
|
||||
channelName = model.GetDMNameFromIds(guest.Id, user.Id)
|
||||
|
||||
assert.Equal(t, "", resp.Text)
|
||||
assert.Equal(t, "http://test.url/"+th.BasicTeam.Name+"/channels/"+channelName, resp.GotoLocation)
|
||||
}
|
||||
96
app/slashcommands/command_mute.go
Обычный файл
96
app/slashcommands/command_mute.go
Обычный файл
@@ -0,0 +1,96 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type MuteProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_MUTE = "mute"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&MuteProvider{})
|
||||
}
|
||||
|
||||
func (me *MuteProvider) GetTrigger() string {
|
||||
return CMD_MUTE
|
||||
}
|
||||
|
||||
func (me *MuteProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_MUTE,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_mute.desc"),
|
||||
AutoCompleteHint: T("api.command_mute.hint"),
|
||||
DisplayName: T("api.command_mute.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *MuteProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
var channel *model.Channel
|
||||
var noChannelErr *model.AppError
|
||||
|
||||
if channel, noChannelErr = a.GetChannel(args.ChannelId); noChannelErr != nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_mute.no_channel.error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
channelName := ""
|
||||
splitMessage := strings.Split(message, " ")
|
||||
// Overwrite channel with channel-handle if set
|
||||
if strings.HasPrefix(message, "~") {
|
||||
channelName = splitMessage[0][1:]
|
||||
} else {
|
||||
channelName = splitMessage[0]
|
||||
}
|
||||
|
||||
if len(channelName) > 0 && len(message) > 0 {
|
||||
channel, _ = a.Srv().Store.Channel().GetByName(channel.TeamId, channelName, true)
|
||||
|
||||
if channel == nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_mute.error", map[string]interface{}{"Channel": channelName}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
}
|
||||
|
||||
channelMember := a.ToggleMuteChannel(channel.Id, args.UserId)
|
||||
if channelMember == nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_mute.not_member.error", map[string]interface{}{"Channel": channelName}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
// Invalidate cache to allow cache lookups while sending notifications
|
||||
a.Srv().Store.Channel().InvalidateCacheForChannelMembersNotifyProps(channel.Id)
|
||||
|
||||
// Direct and Group messages won't have a nice channel title, omit it
|
||||
if channel.Type == model.CHANNEL_DIRECT || channel.Type == model.CHANNEL_GROUP {
|
||||
if channelMember.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] == model.CHANNEL_NOTIFY_MENTION {
|
||||
publishChannelMemberEvt(a, channelMember, args.UserId)
|
||||
return &model.CommandResponse{Text: args.T("api.command_mute.success_mute_direct_msg"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
} else {
|
||||
publishChannelMemberEvt(a, channelMember, args.UserId)
|
||||
return &model.CommandResponse{Text: args.T("api.command_mute.success_unmute_direct_msg"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
}
|
||||
|
||||
if channelMember.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] == model.CHANNEL_NOTIFY_MENTION {
|
||||
publishChannelMemberEvt(a, channelMember, args.UserId)
|
||||
return &model.CommandResponse{Text: args.T("api.command_mute.success_mute", map[string]interface{}{"Channel": channel.DisplayName}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
} else {
|
||||
publishChannelMemberEvt(a, channelMember, args.UserId)
|
||||
return &model.CommandResponse{Text: args.T("api.command_mute.success_unmute", map[string]interface{}{"Channel": channel.DisplayName}), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
}
|
||||
|
||||
func publishChannelMemberEvt(a *app.App, channelMember *model.ChannelMember, userId string) {
|
||||
evt := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_MEMBER_UPDATED, "", "", userId, nil)
|
||||
evt.Add("channelMember", channelMember.ToJson())
|
||||
a.Publish(evt)
|
||||
}
|
||||
203
app/slashcommands/command_mute_test.go
Обычный файл
203
app/slashcommands/command_mute_test.go
Обычный файл
@@ -0,0 +1,203 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestMuteCommandNoChannel(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
if testing.Short() {
|
||||
t.SkipNow()
|
||||
}
|
||||
|
||||
channel1 := th.BasicChannel
|
||||
channel1M, channel1MError := th.App.GetChannelMember(channel1.Id, th.BasicUser.Id)
|
||||
|
||||
assert.Nil(t, channel1MError, "User is not a member of channel 1")
|
||||
assert.NotEqual(
|
||||
t,
|
||||
channel1M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP],
|
||||
model.CHANNEL_NOTIFY_MENTION,
|
||||
"Channel shouldn't be muted on initial setup",
|
||||
)
|
||||
|
||||
cmd := &MuteProvider{}
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
UserId: th.BasicUser.Id,
|
||||
}, "")
|
||||
assert.Equal(t, "api.command_mute.no_channel.error", resp.Text)
|
||||
}
|
||||
|
||||
func TestMuteCommandNoArgs(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
channel1 := th.BasicChannel
|
||||
channel1M, _ := th.App.GetChannelMember(channel1.Id, th.BasicUser.Id)
|
||||
|
||||
assert.Equal(t, model.CHANNEL_NOTIFY_ALL, channel1M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP])
|
||||
|
||||
cmd := &MuteProvider{}
|
||||
|
||||
// First mute the channel
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
ChannelId: channel1.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}, "")
|
||||
assert.Equal(t, "api.command_mute.success_mute", resp.Text)
|
||||
|
||||
// Now unmute the channel
|
||||
time.Sleep(time.Millisecond)
|
||||
resp = cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
ChannelId: channel1.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}, "")
|
||||
|
||||
assert.Equal(t, "api.command_mute.success_unmute", resp.Text)
|
||||
}
|
||||
|
||||
func TestMuteCommandSpecificChannel(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
if testing.Short() {
|
||||
t.SkipNow()
|
||||
}
|
||||
|
||||
channel1 := th.BasicChannel
|
||||
channel2, _ := th.App.CreateChannel(&model.Channel{
|
||||
DisplayName: "AA",
|
||||
Name: "aa" + model.NewId() + "a",
|
||||
Type: model.CHANNEL_OPEN,
|
||||
TeamId: th.BasicTeam.Id,
|
||||
CreatorId: th.BasicUser.Id,
|
||||
}, true)
|
||||
|
||||
channel2M, _ := th.App.GetChannelMember(channel2.Id, th.BasicUser.Id)
|
||||
|
||||
assert.Equal(t, model.CHANNEL_NOTIFY_ALL, channel2M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP])
|
||||
|
||||
cmd := &MuteProvider{}
|
||||
|
||||
// First mute the channel
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
ChannelId: channel1.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}, channel2.Name)
|
||||
assert.Equal(t, "api.command_mute.success_mute", resp.Text)
|
||||
channel2M, _ = th.App.GetChannelMember(channel2.Id, th.BasicUser.Id)
|
||||
assert.Equal(t, model.CHANNEL_NOTIFY_MENTION, channel2M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP])
|
||||
|
||||
// Now unmute the channel
|
||||
resp = cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
ChannelId: channel1.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}, "~"+channel2.Name)
|
||||
|
||||
assert.Equal(t, "api.command_mute.success_unmute", resp.Text)
|
||||
channel2M, _ = th.App.GetChannelMember(channel2.Id, th.BasicUser.Id)
|
||||
assert.Equal(t, model.CHANNEL_NOTIFY_ALL, channel2M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP])
|
||||
}
|
||||
|
||||
func TestMuteCommandNotMember(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
if testing.Short() {
|
||||
t.SkipNow()
|
||||
}
|
||||
|
||||
channel1 := th.BasicChannel
|
||||
channel2, _ := th.App.CreateChannel(&model.Channel{
|
||||
DisplayName: "AA",
|
||||
Name: "aa" + model.NewId() + "a",
|
||||
Type: model.CHANNEL_OPEN,
|
||||
TeamId: th.BasicTeam.Id,
|
||||
CreatorId: th.BasicUser.Id,
|
||||
}, false)
|
||||
|
||||
cmd := &MuteProvider{}
|
||||
|
||||
// First mute the channel
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
ChannelId: channel1.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}, channel2.Name)
|
||||
assert.Equal(t, "api.command_mute.not_member.error", resp.Text)
|
||||
}
|
||||
|
||||
func TestMuteCommandNotChannel(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
if testing.Short() {
|
||||
t.SkipNow()
|
||||
}
|
||||
|
||||
channel1 := th.BasicChannel
|
||||
|
||||
cmd := &MuteProvider{}
|
||||
|
||||
// First mute the channel
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
ChannelId: channel1.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}, "~noexists")
|
||||
assert.Equal(t, "api.command_mute.error", resp.Text)
|
||||
}
|
||||
|
||||
func TestMuteCommandDMChannel(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
if testing.Short() {
|
||||
t.SkipNow()
|
||||
}
|
||||
|
||||
channel2, _ := th.App.GetOrCreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id)
|
||||
channel2M, _ := th.App.GetChannelMember(channel2.Id, th.BasicUser.Id)
|
||||
|
||||
assert.Equal(t, model.CHANNEL_NOTIFY_ALL, channel2M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP])
|
||||
|
||||
cmd := &MuteProvider{}
|
||||
|
||||
// First mute the channel
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
ChannelId: channel2.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}, "")
|
||||
assert.Equal(t, "api.command_mute.success_mute_direct_msg", resp.Text)
|
||||
time.Sleep(time.Millisecond)
|
||||
channel2M, _ = th.App.GetChannelMember(channel2.Id, th.BasicUser.Id)
|
||||
assert.Equal(t, model.CHANNEL_NOTIFY_MENTION, channel2M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP])
|
||||
|
||||
// Now unmute the channel
|
||||
resp = cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
ChannelId: channel2.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}, "")
|
||||
|
||||
assert.Equal(t, "api.command_mute.success_unmute_direct_msg", resp.Text)
|
||||
time.Sleep(time.Millisecond)
|
||||
channel2M, _ = th.App.GetChannelMember(channel2.Id, th.BasicUser.Id)
|
||||
assert.Equal(t, model.CHANNEL_NOTIFY_ALL, channel2M.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP])
|
||||
}
|
||||
40
app/slashcommands/command_offline.go
Обычный файл
40
app/slashcommands/command_offline.go
Обычный файл
@@ -0,0 +1,40 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type OfflineProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_OFFLINE = "offline"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&OfflineProvider{})
|
||||
}
|
||||
|
||||
func (me *OfflineProvider) GetTrigger() string {
|
||||
return CMD_OFFLINE
|
||||
}
|
||||
|
||||
func (me *OfflineProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_OFFLINE,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_offline.desc"),
|
||||
DisplayName: T("api.command_offline.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *OfflineProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
a.SetStatusOffline(args.UserId, true)
|
||||
|
||||
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_offline.success")}
|
||||
}
|
||||
40
app/slashcommands/command_online.go
Обычный файл
40
app/slashcommands/command_online.go
Обычный файл
@@ -0,0 +1,40 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type OnlineProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_ONLINE = "online"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&OnlineProvider{})
|
||||
}
|
||||
|
||||
func (me *OnlineProvider) GetTrigger() string {
|
||||
return CMD_ONLINE
|
||||
}
|
||||
|
||||
func (me *OnlineProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_ONLINE,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_online.desc"),
|
||||
DisplayName: T("api.command_online.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *OnlineProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
a.SetStatusOnline(args.UserId, true)
|
||||
|
||||
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_online.success")}
|
||||
}
|
||||
33
app/slashcommands/command_open.go
Обычный файл
33
app/slashcommands/command_open.go
Обычный файл
@@ -0,0 +1,33 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type OpenProvider struct {
|
||||
JoinProvider
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_OPEN = "open"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&OpenProvider{})
|
||||
}
|
||||
|
||||
func (open *OpenProvider) GetTrigger() string {
|
||||
return CMD_OPEN
|
||||
}
|
||||
|
||||
func (open *OpenProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
cmd := open.JoinProvider.GetCommand(a, T)
|
||||
cmd.Trigger = CMD_OPEN
|
||||
cmd.DisplayName = T("api.command_open.name")
|
||||
return cmd
|
||||
}
|
||||
153
app/slashcommands/command_remove.go
Обычный файл
153
app/slashcommands/command_remove.go
Обычный файл
@@ -0,0 +1,153 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/mlog"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type RemoveProvider struct {
|
||||
}
|
||||
|
||||
type KickProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_REMOVE = "remove"
|
||||
CMD_KICK = "kick"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&RemoveProvider{})
|
||||
app.RegisterCommandProvider(&KickProvider{})
|
||||
}
|
||||
|
||||
func (me *RemoveProvider) GetTrigger() string {
|
||||
return CMD_REMOVE
|
||||
}
|
||||
|
||||
func (me *KickProvider) GetTrigger() string {
|
||||
return CMD_KICK
|
||||
}
|
||||
|
||||
func (me *RemoveProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_REMOVE,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_remove.desc"),
|
||||
AutoCompleteHint: T("api.command_remove.hint"),
|
||||
DisplayName: T("api.command_remove.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *KickProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_KICK,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_remove.desc"),
|
||||
AutoCompleteHint: T("api.command_remove.hint"),
|
||||
DisplayName: T("api.command_kick.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *RemoveProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
return doCommand(a, args, message)
|
||||
}
|
||||
|
||||
func (me *KickProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
return doCommand(a, args, message)
|
||||
}
|
||||
|
||||
func doCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
channel, err := a.GetChannel(args.ChannelId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_remove.channel.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
switch channel.Type {
|
||||
case model.CHANNEL_OPEN:
|
||||
if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PUBLIC_CHANNEL_MEMBERS) {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_remove.permission.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
case model.CHANNEL_PRIVATE:
|
||||
if !a.HasPermissionToChannel(args.UserId, args.ChannelId, model.PERMISSION_MANAGE_PRIVATE_CHANNEL_MEMBERS) {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_remove.permission.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
default:
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_remove.direct_group.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
if len(message) == 0 {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_remove.message.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
targetUsername := ""
|
||||
|
||||
targetUsername = strings.SplitN(message, " ", 2)[0]
|
||||
targetUsername = strings.TrimPrefix(targetUsername, "@")
|
||||
|
||||
userProfile, err := a.Srv().Store.User().GetByUsername(targetUsername)
|
||||
if err != nil {
|
||||
mlog.Error(err.Error())
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_remove.missing.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
if userProfile.DeleteAt != 0 {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_remove.missing.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
_, err = a.GetChannelMember(args.ChannelId, userProfile.Id)
|
||||
if err != nil {
|
||||
nameFormat := *a.Config().TeamSettings.TeammateNameDisplay
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_remove.user_not_in_channel", map[string]interface{}{
|
||||
"Username": userProfile.GetDisplayName(nameFormat),
|
||||
}),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
if err = a.RemoveUserFromChannel(userProfile.Id, args.UserId, channel); err != nil {
|
||||
var text string
|
||||
if err.Id == "api.channel.remove_members.denied" {
|
||||
text = args.T("api.command_remove.group_constrained_user_denied")
|
||||
} else {
|
||||
text = args.T(err.Id, map[string]interface{}{
|
||||
"Channel": model.DEFAULT_CHANNEL,
|
||||
})
|
||||
}
|
||||
return &model.CommandResponse{
|
||||
Text: text,
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
|
||||
return &model.CommandResponse{}
|
||||
}
|
||||
124
app/slashcommands/command_remove_test.go
Обычный файл
124
app/slashcommands/command_remove_test.go
Обычный файл
@@ -0,0 +1,124 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
func TestRemoveProviderDoCommand(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
rp := RemoveProvider{}
|
||||
|
||||
publicChannel, _ := th.App.CreateChannel(&model.Channel{
|
||||
DisplayName: "AA",
|
||||
Name: "aa" + model.NewId() + "a",
|
||||
Type: model.CHANNEL_OPEN,
|
||||
TeamId: th.BasicTeam.Id,
|
||||
CreatorId: th.BasicUser.Id,
|
||||
}, false)
|
||||
|
||||
privateChannel, _ := th.App.CreateChannel(&model.Channel{
|
||||
DisplayName: "BB",
|
||||
Name: "aa" + model.NewId() + "a",
|
||||
Type: model.CHANNEL_OPEN,
|
||||
TeamId: th.BasicTeam.Id,
|
||||
CreatorId: th.BasicUser.Id,
|
||||
}, false)
|
||||
|
||||
targetUser := th.createUser()
|
||||
th.App.AddUserToTeam(th.BasicTeam.Id, targetUser.Id, targetUser.Id)
|
||||
th.App.AddUserToChannel(targetUser, publicChannel)
|
||||
th.App.AddUserToChannel(targetUser, privateChannel)
|
||||
|
||||
// Try a public channel *without* permission.
|
||||
args := &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: publicChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual := rp.DoCommand(th.App, args, targetUser.Username).Text
|
||||
assert.Equal(t, "api.command_remove.permission.app_error", actual)
|
||||
|
||||
// Try a public channel *with* permission.
|
||||
th.App.AddUserToChannel(th.BasicUser, publicChannel)
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: publicChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = rp.DoCommand(th.App, args, targetUser.Username).Text
|
||||
assert.Equal(t, "", actual)
|
||||
|
||||
// Try a private channel *without* permission.
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: privateChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = rp.DoCommand(th.App, args, targetUser.Username).Text
|
||||
assert.Equal(t, "api.command_remove.permission.app_error", actual)
|
||||
|
||||
// Try a private channel *with* permission.
|
||||
th.App.AddUserToChannel(th.BasicUser, privateChannel)
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: privateChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = rp.DoCommand(th.App, args, targetUser.Username).Text
|
||||
assert.Equal(t, "", actual)
|
||||
|
||||
// Try a group channel
|
||||
user1 := th.createUser()
|
||||
user2 := th.createUser()
|
||||
|
||||
groupChannel := th.createGroupChannel(user1, user2)
|
||||
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: groupChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = rp.DoCommand(th.App, args, user1.Username).Text
|
||||
assert.Equal(t, "api.command_remove.direct_group.app_error", actual)
|
||||
|
||||
// Try a direct channel *with* being a member.
|
||||
directChannel := th.createDmChannel(user1)
|
||||
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: directChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = rp.DoCommand(th.App, args, user1.Username).Text
|
||||
assert.Equal(t, "api.command_remove.direct_group.app_error", actual)
|
||||
|
||||
// Try a public channel with a deactivated user.
|
||||
deactivatedUser := th.createUser()
|
||||
th.App.AddUserToTeam(th.BasicTeam.Id, deactivatedUser.Id, deactivatedUser.Id)
|
||||
th.App.AddUserToChannel(deactivatedUser, publicChannel)
|
||||
th.App.UpdateActive(deactivatedUser, false)
|
||||
|
||||
args = &model.CommandArgs{
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
ChannelId: publicChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = rp.DoCommand(th.App, args, deactivatedUser.Username).Text
|
||||
assert.Equal(t, "api.command_remove.missing.app_error", actual)
|
||||
}
|
||||
43
app/slashcommands/command_search.go
Обычный файл
43
app/slashcommands/command_search.go
Обычный файл
@@ -0,0 +1,43 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type SearchProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_SEARCH = "search"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&SearchProvider{})
|
||||
}
|
||||
|
||||
func (search *SearchProvider) GetTrigger() string {
|
||||
return CMD_SEARCH
|
||||
}
|
||||
|
||||
func (search *SearchProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_SEARCH,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_search.desc"),
|
||||
AutoCompleteHint: T("api.command_search.hint"),
|
||||
DisplayName: T("api.command_search.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (search *SearchProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
// This command is handled client-side and shouldn't hit the server.
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_search.unsupported.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
43
app/slashcommands/command_settings.go
Обычный файл
43
app/slashcommands/command_settings.go
Обычный файл
@@ -0,0 +1,43 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type SettingsProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_SETTINGS = "settings"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&SettingsProvider{})
|
||||
}
|
||||
|
||||
func (settings *SettingsProvider) GetTrigger() string {
|
||||
return CMD_SETTINGS
|
||||
}
|
||||
|
||||
func (settings *SettingsProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_SETTINGS,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_settings.desc"),
|
||||
AutoCompleteHint: "",
|
||||
DisplayName: T("api.command_settings.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (settings *SettingsProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
// This command is handled client-side and shouldn't hit the server.
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_settings.unsupported.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
43
app/slashcommands/command_shortcuts.go
Обычный файл
43
app/slashcommands/command_shortcuts.go
Обычный файл
@@ -0,0 +1,43 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type ShortcutsProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_SHORTCUTS = "shortcuts"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&ShortcutsProvider{})
|
||||
}
|
||||
|
||||
func (me *ShortcutsProvider) GetTrigger() string {
|
||||
return CMD_SHORTCUTS
|
||||
}
|
||||
|
||||
func (me *ShortcutsProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_SHORTCUTS,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_shortcuts.desc"),
|
||||
AutoCompleteHint: "",
|
||||
DisplayName: T("api.command_shortcuts.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *ShortcutsProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
// This command is handled client-side and shouldn't hit the server.
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_shortcuts.unsupported.app_error"),
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
}
|
||||
}
|
||||
44
app/slashcommands/command_shrug.go
Обычный файл
44
app/slashcommands/command_shrug.go
Обычный файл
@@ -0,0 +1,44 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
goi18n "github.com/mattermost/go-i18n/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
type ShrugProvider struct {
|
||||
}
|
||||
|
||||
const (
|
||||
CMD_SHRUG = "shrug"
|
||||
)
|
||||
|
||||
func init() {
|
||||
app.RegisterCommandProvider(&ShrugProvider{})
|
||||
}
|
||||
|
||||
func (me *ShrugProvider) GetTrigger() string {
|
||||
return CMD_SHRUG
|
||||
}
|
||||
|
||||
func (me *ShrugProvider) GetCommand(a *app.App, T goi18n.TranslateFunc) *model.Command {
|
||||
return &model.Command{
|
||||
Trigger: CMD_SHRUG,
|
||||
AutoComplete: true,
|
||||
AutoCompleteDesc: T("api.command_shrug.desc"),
|
||||
AutoCompleteHint: T("api.command_shrug.hint"),
|
||||
DisplayName: T("api.command_shrug.name"),
|
||||
}
|
||||
}
|
||||
|
||||
func (me *ShrugProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
rmsg := `¯\\\_(ツ)\_/¯`
|
||||
if len(message) > 0 {
|
||||
rmsg = message + " " + rmsg
|
||||
}
|
||||
|
||||
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL, Text: rmsg}
|
||||
}
|
||||
617
app/slashcommands/command_test.go
Обычный файл
617
app/slashcommands/command_test.go
Обычный файл
@@ -0,0 +1,617 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/services/httpservice"
|
||||
)
|
||||
|
||||
type InfiniteReader struct {
|
||||
Prefix string
|
||||
}
|
||||
|
||||
func (r InfiniteReader) Read(p []byte) (n int, err error) {
|
||||
for i := range p {
|
||||
p[i] = 'a'
|
||||
}
|
||||
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func TestMoveCommand(t *testing.T) {
|
||||
th := setup(t)
|
||||
defer th.tearDown()
|
||||
|
||||
sourceTeam := th.createTeam()
|
||||
targetTeam := th.createTeam()
|
||||
|
||||
command := &model.Command{}
|
||||
command.CreatorId = model.NewId()
|
||||
command.Method = model.COMMAND_METHOD_POST
|
||||
command.TeamId = sourceTeam.Id
|
||||
command.URL = "http://nowhere.com/"
|
||||
command.Trigger = "trigger1"
|
||||
|
||||
command, err := th.App.CreateCommand(command)
|
||||
assert.Nil(t, err)
|
||||
|
||||
defer func() {
|
||||
th.App.PermanentDeleteTeam(sourceTeam)
|
||||
th.App.PermanentDeleteTeam(targetTeam)
|
||||
}()
|
||||
|
||||
// Move a command and check the team is updated.
|
||||
assert.Nil(t, th.App.MoveCommand(targetTeam, command))
|
||||
retrievedCommand, err := th.App.GetCommand(command.Id)
|
||||
assert.Nil(t, err)
|
||||
assert.EqualValues(t, targetTeam.Id, retrievedCommand.TeamId)
|
||||
|
||||
// Move it to the team it's already in. Nothing should change.
|
||||
assert.Nil(t, th.App.MoveCommand(targetTeam, command))
|
||||
retrievedCommand, err = th.App.GetCommand(command.Id)
|
||||
assert.Nil(t, err)
|
||||
assert.EqualValues(t, targetTeam.Id, retrievedCommand.TeamId)
|
||||
}
|
||||
|
||||
func TestCreateCommandPost(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
post := &model.Post{
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
Type: model.POST_SYSTEM_GENERIC,
|
||||
}
|
||||
|
||||
resp := &model.CommandResponse{
|
||||
Text: "some message",
|
||||
}
|
||||
|
||||
skipSlackParsing := false
|
||||
_, err := th.App.CreateCommandPost(post, th.BasicTeam.Id, resp, skipSlackParsing)
|
||||
require.NotNil(t, err)
|
||||
require.Equal(t, err.Id, "api.context.invalid_param.app_error")
|
||||
}
|
||||
|
||||
func TestExecuteCommand(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
t.Run("valid tests with different whitespace characters", func(t *testing.T) {
|
||||
TestCases := map[string]string{
|
||||
"/code happy path": " happy path",
|
||||
"/code\nnewline path": " newline path",
|
||||
"/code\n/nDouble newline path": " /nDouble newline path",
|
||||
"/code double space": " double space",
|
||||
"/code\ttab": " tab",
|
||||
}
|
||||
|
||||
for TestCase, result := range TestCases {
|
||||
args := &model.CommandArgs{
|
||||
Command: TestCase,
|
||||
TeamId: th.BasicTeam.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
}
|
||||
resp, err := th.App.ExecuteCommand(args)
|
||||
require.Nil(t, err)
|
||||
require.NotNil(t, resp)
|
||||
|
||||
assert.Equal(t, resp.Text, result)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing slash character", func(t *testing.T) {
|
||||
argsMissingSlashCharacter := &model.CommandArgs{
|
||||
Command: "missing leading slash character",
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
}
|
||||
_, err := th.App.ExecuteCommand(argsMissingSlashCharacter)
|
||||
require.Equal(t, "api.command.execute_command.format.app_error", err.Id)
|
||||
})
|
||||
|
||||
t.Run("empty", func(t *testing.T) {
|
||||
argsMissingSlashCharacter := &model.CommandArgs{
|
||||
Command: "",
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
}
|
||||
_, err := th.App.ExecuteCommand(argsMissingSlashCharacter)
|
||||
require.Equal(t, "api.command.execute_command.format.app_error", err.Id)
|
||||
})
|
||||
}
|
||||
|
||||
func TestHandleCommandResponsePost(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
command := &model.Command{}
|
||||
args := &model.CommandArgs{
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
TeamId: th.BasicTeam.Id,
|
||||
UserId: th.BasicUser.Id,
|
||||
RootId: "",
|
||||
ParentId: "",
|
||||
}
|
||||
|
||||
resp := &model.CommandResponse{
|
||||
Type: model.POST_DEFAULT,
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL,
|
||||
Props: model.StringInterface{"some_key": "some value"},
|
||||
Text: "some message",
|
||||
}
|
||||
|
||||
builtIn := true
|
||||
|
||||
post, err := th.App.HandleCommandResponsePost(command, args, resp, builtIn)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, args.ChannelId, post.ChannelId)
|
||||
assert.Equal(t, args.RootId, post.RootId)
|
||||
assert.Equal(t, args.ParentId, post.ParentId)
|
||||
assert.Equal(t, args.UserId, post.UserId)
|
||||
assert.Equal(t, resp.Type, post.Type)
|
||||
assert.Equal(t, resp.Props, post.GetProps())
|
||||
assert.Equal(t, resp.Text, post.Message)
|
||||
assert.Nil(t, post.GetProp("override_icon_url"))
|
||||
assert.Nil(t, post.GetProp("override_username"))
|
||||
assert.Nil(t, post.GetProp("from_webhook"))
|
||||
|
||||
// Command is not built in, so it is a bot command.
|
||||
builtIn = false
|
||||
post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn)
|
||||
assert.Equal(t, "true", post.GetProp("from_webhook"))
|
||||
|
||||
builtIn = true
|
||||
|
||||
// Channel id is specified by response, it should override the command args value.
|
||||
channel := th.CreateChannel(th.BasicTeam)
|
||||
resp.ChannelId = channel.Id
|
||||
th.addUserToChannel(th.BasicUser, channel)
|
||||
|
||||
post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, resp.ChannelId, post.ChannelId)
|
||||
assert.NotEqual(t, args.ChannelId, post.ChannelId)
|
||||
|
||||
// Override username config is turned off. No override should occur.
|
||||
*th.App.Config().ServiceSettings.EnablePostUsernameOverride = false
|
||||
resp.ChannelId = ""
|
||||
command.Username = "Command username"
|
||||
resp.Username = "Response username"
|
||||
|
||||
post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn)
|
||||
assert.Nil(t, err)
|
||||
assert.Nil(t, post.GetProp("override_username"))
|
||||
|
||||
*th.App.Config().ServiceSettings.EnablePostUsernameOverride = true
|
||||
|
||||
// Override username config is turned on. Override username through command property.
|
||||
post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, command.Username, post.GetProp("override_username"))
|
||||
assert.Equal(t, "true", post.GetProp("from_webhook"))
|
||||
|
||||
command.Username = ""
|
||||
|
||||
// Override username through response property.
|
||||
post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, resp.Username, post.GetProp("override_username"))
|
||||
assert.Equal(t, "true", post.GetProp("from_webhook"))
|
||||
|
||||
*th.App.Config().ServiceSettings.EnablePostUsernameOverride = false
|
||||
|
||||
// Override icon url config is turned off. No override should occur.
|
||||
*th.App.Config().ServiceSettings.EnablePostIconOverride = false
|
||||
command.IconURL = "Command icon url"
|
||||
resp.IconURL = "Response icon url"
|
||||
|
||||
post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn)
|
||||
assert.Nil(t, err)
|
||||
assert.Nil(t, post.GetProp("override_icon_url"))
|
||||
|
||||
*th.App.Config().ServiceSettings.EnablePostIconOverride = true
|
||||
|
||||
// Override icon url config is turned on. Override icon url through command property.
|
||||
post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, command.IconURL, post.GetProp("override_icon_url"))
|
||||
assert.Equal(t, "true", post.GetProp("from_webhook"))
|
||||
|
||||
command.IconURL = ""
|
||||
|
||||
// Override icon url through response property.
|
||||
post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, resp.IconURL, post.GetProp("override_icon_url"))
|
||||
assert.Equal(t, "true", post.GetProp("from_webhook"))
|
||||
|
||||
// Test Slack text conversion.
|
||||
resp.Text = "<!channel>"
|
||||
|
||||
post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, "@channel", post.Message)
|
||||
assert.Equal(t, "true", post.GetProp("from_webhook"))
|
||||
|
||||
// Test Slack attachments text conversion.
|
||||
resp.Attachments = []*model.SlackAttachment{
|
||||
{
|
||||
Text: "<!here>",
|
||||
},
|
||||
}
|
||||
|
||||
post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, "@channel", post.Message)
|
||||
if assert.Len(t, post.Attachments(), 1) {
|
||||
assert.Equal(t, "@here", post.Attachments()[0].Text)
|
||||
}
|
||||
assert.Equal(t, "true", post.GetProp("from_webhook"))
|
||||
|
||||
channel = th.createPrivateChannel(th.BasicTeam)
|
||||
resp.ChannelId = channel.Id
|
||||
args.UserId = th.BasicUser2.Id
|
||||
post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn)
|
||||
|
||||
require.NotNil(t, err)
|
||||
require.Equal(t, err.Id, "api.command.command_post.forbidden.app_error")
|
||||
|
||||
// Test that /code text is not converted with the Slack text conversion.
|
||||
command.Trigger = "code"
|
||||
resp.ChannelId = ""
|
||||
resp.Text = "<test.com|test website>"
|
||||
resp.Attachments = []*model.SlackAttachment{
|
||||
{
|
||||
Text: "<!here>",
|
||||
},
|
||||
}
|
||||
|
||||
// set and unset SkipSlackParsing here seems the nicest way as no separate response objects are created for every testcase.
|
||||
resp.SkipSlackParsing = true
|
||||
post, err = th.App.HandleCommandResponsePost(command, args, resp, builtIn)
|
||||
resp.SkipSlackParsing = false
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, resp.Text, post.Message, "/code text should not be converted to Slack links")
|
||||
assert.Equal(t, "<!here>", resp.Attachments[0].Text)
|
||||
}
|
||||
|
||||
func TestHandleCommandResponse(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
command := &model.Command{}
|
||||
|
||||
args := &model.CommandArgs{
|
||||
Command: "/invite username",
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
}
|
||||
|
||||
resp := &model.CommandResponse{
|
||||
Text: "message 1",
|
||||
Type: model.POST_SYSTEM_GENERIC,
|
||||
}
|
||||
|
||||
builtIn := true
|
||||
|
||||
_, err := th.App.HandleCommandResponse(command, args, resp, builtIn)
|
||||
require.NotNil(t, err)
|
||||
require.Equal(t, err.Id, "api.command.execute_command.create_post_failed.app_error")
|
||||
|
||||
resp = &model.CommandResponse{
|
||||
Text: "message 1",
|
||||
}
|
||||
|
||||
_, err = th.App.HandleCommandResponse(command, args, resp, builtIn)
|
||||
assert.Nil(t, err)
|
||||
|
||||
resp = &model.CommandResponse{
|
||||
Text: "message 1",
|
||||
ExtraResponses: []*model.CommandResponse{
|
||||
{
|
||||
Text: "message 2",
|
||||
},
|
||||
{
|
||||
Type: model.POST_SYSTEM_GENERIC,
|
||||
Text: "message 3",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_, err = th.App.HandleCommandResponse(command, args, resp, builtIn)
|
||||
require.NotNil(t, err)
|
||||
require.Equal(t, err.Id, "api.command.execute_command.create_post_failed.app_error")
|
||||
|
||||
resp = &model.CommandResponse{
|
||||
ExtraResponses: []*model.CommandResponse{
|
||||
{},
|
||||
{},
|
||||
},
|
||||
}
|
||||
|
||||
_, err = th.App.HandleCommandResponse(command, args, resp, builtIn)
|
||||
assert.Nil(t, err)
|
||||
}
|
||||
|
||||
func TestDoCommandRequest(t *testing.T) {
|
||||
th := setup(t)
|
||||
defer th.tearDown()
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
cfg.ServiceSettings.AllowedUntrustedInternalConnections = model.NewString("127.0.0.1")
|
||||
cfg.ServiceSettings.EnableCommands = model.NewBool(true)
|
||||
})
|
||||
|
||||
t.Run("with a valid text response", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
io.Copy(w, strings.NewReader("Hello, World!"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
_, resp, err := th.App.DoCommandRequest(&model.Command{URL: server.URL}, url.Values{})
|
||||
require.Nil(t, err)
|
||||
|
||||
assert.NotNil(t, resp)
|
||||
assert.Equal(t, "Hello, World!", resp.Text)
|
||||
})
|
||||
|
||||
t.Run("with a valid json response", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
|
||||
io.Copy(w, strings.NewReader(`{"text": "Hello, World!"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
_, resp, err := th.App.DoCommandRequest(&model.Command{URL: server.URL}, url.Values{})
|
||||
require.Nil(t, err)
|
||||
|
||||
assert.NotNil(t, resp)
|
||||
assert.Equal(t, "Hello, World!", resp.Text)
|
||||
})
|
||||
|
||||
t.Run("with a large text response", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
io.Copy(w, InfiniteReader{})
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
// Since we limit the length of the response, no error will be returned and resp.Text will be a finite string
|
||||
|
||||
_, resp, err := th.App.DoCommandRequest(&model.Command{URL: server.URL}, url.Values{})
|
||||
require.Nil(t, err)
|
||||
require.NotNil(t, resp)
|
||||
})
|
||||
|
||||
t.Run("with a large, valid json response", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
|
||||
io.Copy(w, io.MultiReader(strings.NewReader(`{"text": "`), InfiniteReader{}, strings.NewReader(`"}`)))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
_, _, err := th.App.DoCommandRequest(&model.Command{URL: server.URL}, url.Values{})
|
||||
require.NotNil(t, err)
|
||||
require.Equal(t, "api.command.execute_command.failed.app_error", err.Id)
|
||||
})
|
||||
|
||||
t.Run("with a large, invalid json response", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
|
||||
io.Copy(w, InfiniteReader{})
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
_, _, err := th.App.DoCommandRequest(&model.Command{URL: server.URL}, url.Values{})
|
||||
require.NotNil(t, err)
|
||||
require.Equal(t, "api.command.execute_command.failed.app_error", err.Id)
|
||||
})
|
||||
|
||||
t.Run("with a slow response", func(t *testing.T) {
|
||||
done := make(chan bool)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
<-done
|
||||
io.Copy(w, strings.NewReader(`{"text": "Hello, World!"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
th.App.HTTPService().(*httpservice.HTTPServiceImpl).RequestTimeout = 100 * time.Millisecond
|
||||
defer func() {
|
||||
th.App.HTTPService().(*httpservice.HTTPServiceImpl).RequestTimeout = httpservice.RequestTimeout
|
||||
}()
|
||||
|
||||
_, _, err := th.App.DoCommandRequest(&model.Command{URL: server.URL}, url.Values{})
|
||||
require.NotNil(t, err)
|
||||
require.Equal(t, "api.command.execute_command.failed.app_error", err.Id)
|
||||
close(done)
|
||||
})
|
||||
}
|
||||
|
||||
func TestMentionsToTeamMembers(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
otherTeam := th.createTeam()
|
||||
otherUser := th.createUser()
|
||||
th.linkUserToTeam(otherUser, otherTeam)
|
||||
|
||||
fixture := []struct {
|
||||
message string
|
||||
inTeam string
|
||||
expectedMap model.UserMentionMap
|
||||
}{
|
||||
{
|
||||
"",
|
||||
th.BasicTeam.Id,
|
||||
model.UserMentionMap{},
|
||||
},
|
||||
{
|
||||
"/trigger",
|
||||
th.BasicTeam.Id,
|
||||
model.UserMentionMap{},
|
||||
},
|
||||
{
|
||||
"/trigger 0 mentions",
|
||||
th.BasicTeam.Id,
|
||||
model.UserMentionMap{},
|
||||
},
|
||||
{
|
||||
fmt.Sprintf("/trigger 1 valid user @%s", th.BasicUser.Username),
|
||||
th.BasicTeam.Id,
|
||||
model.UserMentionMap{th.BasicUser.Username: th.BasicUser.Id},
|
||||
},
|
||||
{
|
||||
fmt.Sprintf("/trigger 2 valid users @%s @%s",
|
||||
th.BasicUser.Username, th.BasicUser2.Username,
|
||||
),
|
||||
th.BasicTeam.Id,
|
||||
model.UserMentionMap{
|
||||
th.BasicUser.Username: th.BasicUser.Id,
|
||||
th.BasicUser2.Username: th.BasicUser2.Id,
|
||||
},
|
||||
},
|
||||
{
|
||||
fmt.Sprintf("/trigger 1 user from another team @%s", otherUser.Username),
|
||||
th.BasicTeam.Id,
|
||||
model.UserMentionMap{},
|
||||
},
|
||||
{
|
||||
fmt.Sprintf("/trigger 2 valid users + 1 from another team @%s @%s @%s",
|
||||
th.BasicUser.Username, th.BasicUser2.Username, otherUser.Username,
|
||||
),
|
||||
th.BasicTeam.Id,
|
||||
model.UserMentionMap{
|
||||
th.BasicUser.Username: th.BasicUser.Id,
|
||||
th.BasicUser2.Username: th.BasicUser2.Id,
|
||||
},
|
||||
},
|
||||
{
|
||||
fmt.Sprintf("/trigger a valid channel ~%s", th.BasicChannel.Name),
|
||||
th.BasicTeam.Id,
|
||||
model.UserMentionMap{},
|
||||
},
|
||||
{
|
||||
fmt.Sprintf("/trigger channel and mentions ~%s @%s",
|
||||
th.BasicChannel.Name, th.BasicUser.Username),
|
||||
th.BasicTeam.Id,
|
||||
model.UserMentionMap{th.BasicUser.Username: th.BasicUser.Id},
|
||||
},
|
||||
{
|
||||
fmt.Sprintf("/trigger repeated users @%s @%s @%s",
|
||||
th.BasicUser.Username, th.BasicUser2.Username, th.BasicUser.Username),
|
||||
th.BasicTeam.Id,
|
||||
model.UserMentionMap{
|
||||
th.BasicUser.Username: th.BasicUser.Id,
|
||||
th.BasicUser2.Username: th.BasicUser2.Id,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, data := range fixture {
|
||||
actualMap := th.App.MentionsToTeamMembers(data.message, data.inTeam)
|
||||
require.Equal(t, actualMap, data.expectedMap)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMentionsToPublicChannels(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
otherPublicChannel := th.CreateChannel(th.BasicTeam)
|
||||
privateChannel := th.createPrivateChannel(th.BasicTeam)
|
||||
|
||||
fixture := []struct {
|
||||
message string
|
||||
inTeam string
|
||||
expectedMap model.ChannelMentionMap
|
||||
}{
|
||||
{
|
||||
"",
|
||||
th.BasicTeam.Id,
|
||||
model.ChannelMentionMap{},
|
||||
},
|
||||
{
|
||||
"/trigger",
|
||||
th.BasicTeam.Id,
|
||||
model.ChannelMentionMap{},
|
||||
},
|
||||
{
|
||||
"/trigger 0 mentions",
|
||||
th.BasicTeam.Id,
|
||||
model.ChannelMentionMap{},
|
||||
},
|
||||
{
|
||||
fmt.Sprintf("/trigger 1 public channel ~%s", th.BasicChannel.Name),
|
||||
th.BasicTeam.Id,
|
||||
model.ChannelMentionMap{th.BasicChannel.Name: th.BasicChannel.Id},
|
||||
},
|
||||
{
|
||||
fmt.Sprintf("/trigger 2 public channels ~%s ~%s",
|
||||
th.BasicChannel.Name, otherPublicChannel.Name,
|
||||
),
|
||||
th.BasicTeam.Id,
|
||||
model.ChannelMentionMap{
|
||||
th.BasicChannel.Name: th.BasicChannel.Id,
|
||||
otherPublicChannel.Name: otherPublicChannel.Id,
|
||||
},
|
||||
},
|
||||
{
|
||||
fmt.Sprintf("/trigger 1 private channel ~%s", privateChannel.Name),
|
||||
th.BasicTeam.Id,
|
||||
model.ChannelMentionMap{},
|
||||
},
|
||||
{
|
||||
fmt.Sprintf("/trigger 2 public channel + 1 private ~%s ~%s ~%s",
|
||||
th.BasicChannel.Name, otherPublicChannel.Name, privateChannel.Name,
|
||||
),
|
||||
th.BasicTeam.Id,
|
||||
model.ChannelMentionMap{
|
||||
th.BasicChannel.Name: th.BasicChannel.Id,
|
||||
otherPublicChannel.Name: otherPublicChannel.Id,
|
||||
},
|
||||
},
|
||||
{
|
||||
fmt.Sprintf("/trigger a valid user @%s", th.BasicUser.Username),
|
||||
th.BasicTeam.Id,
|
||||
model.ChannelMentionMap{},
|
||||
},
|
||||
{
|
||||
fmt.Sprintf("/trigger channel and mentions ~%s @%s",
|
||||
th.BasicChannel.Name, th.BasicUser.Username),
|
||||
th.BasicTeam.Id,
|
||||
model.ChannelMentionMap{th.BasicChannel.Name: th.BasicChannel.Id},
|
||||
},
|
||||
{
|
||||
fmt.Sprintf("/trigger repeated channels ~%s ~%s ~%s",
|
||||
th.BasicChannel.Name, otherPublicChannel.Name, th.BasicChannel.Name),
|
||||
th.BasicTeam.Id,
|
||||
model.ChannelMentionMap{
|
||||
th.BasicChannel.Name: th.BasicChannel.Id,
|
||||
otherPublicChannel.Name: otherPublicChannel.Id,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, data := range fixture {
|
||||
actualMap := th.App.MentionsToPublicChannels(data.message, data.inTeam)
|
||||
require.Equal(t, actualMap, data.expectedMap)
|
||||
}
|
||||
}
|
||||
455
app/slashcommands/helper_test.go
Обычный файл
455
app/slashcommands/helper_test.go
Обычный файл
@@ -0,0 +1,455 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"testing"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/config"
|
||||
"github.com/mattermost/mattermost-server/v5/mlog"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/store"
|
||||
"github.com/mattermost/mattermost-server/v5/store/localcachelayer"
|
||||
"github.com/mattermost/mattermost-server/v5/utils"
|
||||
)
|
||||
|
||||
type TestHelper struct {
|
||||
App *app.App
|
||||
Server *app.Server
|
||||
BasicTeam *model.Team
|
||||
BasicUser *model.User
|
||||
BasicUser2 *model.User
|
||||
BasicChannel *model.Channel
|
||||
BasicPost *model.Post
|
||||
|
||||
SystemAdminUser *model.User
|
||||
LogBuffer *bytes.Buffer
|
||||
IncludeCacheLayer bool
|
||||
|
||||
tempWorkspace string
|
||||
}
|
||||
|
||||
func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer bool, tb testing.TB, configSet func(*model.Config)) *TestHelper {
|
||||
tempWorkspace, err := ioutil.TempDir("", "apptest")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
memoryStore, err := config.NewMemoryStoreWithOptions(&config.MemoryStoreOptions{IgnoreEnvironmentOverrides: true})
|
||||
if err != nil {
|
||||
panic("failed to initialize memory store: " + err.Error())
|
||||
}
|
||||
|
||||
config := memoryStore.Get()
|
||||
if configSet != nil {
|
||||
configSet(config)
|
||||
}
|
||||
*config.PluginSettings.Directory = filepath.Join(tempWorkspace, "plugins")
|
||||
*config.PluginSettings.ClientDirectory = filepath.Join(tempWorkspace, "webapp")
|
||||
*config.LogSettings.EnableSentry = false // disable error reporting during tests
|
||||
memoryStore.Set(config)
|
||||
|
||||
buffer := &bytes.Buffer{}
|
||||
|
||||
var options []app.Option
|
||||
options = append(options, app.ConfigStore(memoryStore))
|
||||
options = append(options, app.StoreOverride(dbStore))
|
||||
options = append(options, app.SetLogger(mlog.NewTestingLogger(tb, buffer)))
|
||||
|
||||
s, err := app.NewServer(options...)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
if includeCacheLayer {
|
||||
// Adds the cache layer to the test store
|
||||
s.Store = localcachelayer.NewLocalCacheLayer(s.Store, s.Metrics, s.Cluster, s.CacheProvider)
|
||||
}
|
||||
|
||||
th := &TestHelper{
|
||||
App: app.New(app.ServerConnector(s)),
|
||||
Server: s,
|
||||
LogBuffer: buffer,
|
||||
IncludeCacheLayer: includeCacheLayer,
|
||||
}
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.MaxUsersPerTeam = 50 })
|
||||
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.RateLimitSettings.Enable = false })
|
||||
prevListenAddress := *th.App.Config().ServiceSettings.ListenAddress
|
||||
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = ":0" })
|
||||
serverErr := th.Server.Start()
|
||||
if serverErr != nil {
|
||||
panic(serverErr)
|
||||
}
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress })
|
||||
|
||||
th.App.Srv().SearchEngine = mainHelper.SearchEngine
|
||||
|
||||
th.App.Srv().Store.MarkSystemRanUnitTests()
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true })
|
||||
|
||||
// Disable strict password requirements for test
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.PasswordSettings.MinimumLength = 5
|
||||
*cfg.PasswordSettings.Lowercase = false
|
||||
*cfg.PasswordSettings.Uppercase = false
|
||||
*cfg.PasswordSettings.Symbol = false
|
||||
*cfg.PasswordSettings.Number = false
|
||||
})
|
||||
|
||||
if enterprise {
|
||||
th.App.Srv().SetLicense(model.NewTestLicense())
|
||||
} else {
|
||||
th.App.Srv().SetLicense(nil)
|
||||
}
|
||||
|
||||
if th.tempWorkspace == "" {
|
||||
th.tempWorkspace = tempWorkspace
|
||||
}
|
||||
|
||||
th.App.InitServer()
|
||||
|
||||
return th
|
||||
}
|
||||
|
||||
func setup(tb testing.TB) *TestHelper {
|
||||
if testing.Short() {
|
||||
tb.SkipNow()
|
||||
}
|
||||
dbStore := mainHelper.GetStore()
|
||||
dbStore.DropAllTables()
|
||||
dbStore.MarkSystemRanUnitTests()
|
||||
|
||||
return setupTestHelper(dbStore, false, true, tb, nil)
|
||||
}
|
||||
|
||||
var initBasicOnce sync.Once
|
||||
var userCache struct {
|
||||
SystemAdminUser *model.User
|
||||
BasicUser *model.User
|
||||
BasicUser2 *model.User
|
||||
}
|
||||
|
||||
func (me *TestHelper) initBasic() *TestHelper {
|
||||
// create users once and cache them because password hashing is slow
|
||||
initBasicOnce.Do(func() {
|
||||
me.SystemAdminUser = me.createUser()
|
||||
me.App.UpdateUserRoles(me.SystemAdminUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false)
|
||||
me.SystemAdminUser, _ = me.App.GetUser(me.SystemAdminUser.Id)
|
||||
userCache.SystemAdminUser = me.SystemAdminUser.DeepCopy()
|
||||
|
||||
me.BasicUser = me.createUser()
|
||||
me.BasicUser, _ = me.App.GetUser(me.BasicUser.Id)
|
||||
userCache.BasicUser = me.BasicUser.DeepCopy()
|
||||
|
||||
me.BasicUser2 = me.createUser()
|
||||
me.BasicUser2, _ = me.App.GetUser(me.BasicUser2.Id)
|
||||
userCache.BasicUser2 = me.BasicUser2.DeepCopy()
|
||||
})
|
||||
// restore cached users
|
||||
me.SystemAdminUser = userCache.SystemAdminUser.DeepCopy()
|
||||
me.BasicUser = userCache.BasicUser.DeepCopy()
|
||||
me.BasicUser2 = userCache.BasicUser2.DeepCopy()
|
||||
mainHelper.GetSQLSupplier().GetMaster().Insert(me.SystemAdminUser, me.BasicUser, me.BasicUser2)
|
||||
|
||||
me.BasicTeam = me.createTeam()
|
||||
|
||||
me.linkUserToTeam(me.BasicUser, me.BasicTeam)
|
||||
me.linkUserToTeam(me.BasicUser2, me.BasicTeam)
|
||||
me.BasicChannel = me.CreateChannel(me.BasicTeam)
|
||||
me.BasicPost = me.createPost(me.BasicChannel)
|
||||
return me
|
||||
}
|
||||
|
||||
func (me *TestHelper) createTeam() *model.Team {
|
||||
id := model.NewId()
|
||||
team := &model.Team{
|
||||
DisplayName: "dn_" + id,
|
||||
Name: "name" + id,
|
||||
Email: "success+" + id + "@simulator.amazonses.com",
|
||||
Type: model.TEAM_OPEN,
|
||||
}
|
||||
|
||||
utils.DisableDebugLogForTest()
|
||||
var err *model.AppError
|
||||
if team, err = me.App.CreateTeam(team); err != nil {
|
||||
mlog.Error(err.Error())
|
||||
|
||||
time.Sleep(time.Second)
|
||||
panic(err)
|
||||
}
|
||||
utils.EnableDebugLogForTest()
|
||||
return team
|
||||
}
|
||||
|
||||
func (me *TestHelper) createUser() *model.User {
|
||||
return me.createUserOrGuest(false)
|
||||
}
|
||||
|
||||
func (me *TestHelper) createGuest() *model.User {
|
||||
return me.createUserOrGuest(true)
|
||||
}
|
||||
|
||||
func (me *TestHelper) createUserOrGuest(guest bool) *model.User {
|
||||
id := model.NewId()
|
||||
|
||||
user := &model.User{
|
||||
Email: "success+" + id + "@simulator.amazonses.com",
|
||||
Username: "un_" + id,
|
||||
Nickname: "nn_" + id,
|
||||
Password: "Password1",
|
||||
EmailVerified: true,
|
||||
}
|
||||
|
||||
utils.DisableDebugLogForTest()
|
||||
var err *model.AppError
|
||||
if guest {
|
||||
if user, err = me.App.CreateGuest(user); err != nil {
|
||||
mlog.Error(err.Error())
|
||||
|
||||
time.Sleep(time.Second)
|
||||
panic(err)
|
||||
}
|
||||
} else {
|
||||
if user, err = me.App.CreateUser(user); err != nil {
|
||||
mlog.Error(err.Error())
|
||||
|
||||
time.Sleep(time.Second)
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
utils.EnableDebugLogForTest()
|
||||
return user
|
||||
}
|
||||
|
||||
func (me *TestHelper) CreateChannel(team *model.Team) *model.Channel {
|
||||
return me.createChannel(team, model.CHANNEL_OPEN)
|
||||
}
|
||||
|
||||
func (me *TestHelper) createPrivateChannel(team *model.Team) *model.Channel {
|
||||
return me.createChannel(team, model.CHANNEL_PRIVATE)
|
||||
}
|
||||
|
||||
func (me *TestHelper) createChannel(team *model.Team, channelType string) *model.Channel {
|
||||
id := model.NewId()
|
||||
|
||||
channel := &model.Channel{
|
||||
DisplayName: "dn_" + id,
|
||||
Name: "name_" + id,
|
||||
Type: channelType,
|
||||
TeamId: team.Id,
|
||||
CreatorId: me.BasicUser.Id,
|
||||
}
|
||||
|
||||
utils.DisableDebugLogForTest()
|
||||
var err *model.AppError
|
||||
if channel, err = me.App.CreateChannel(channel, true); err != nil {
|
||||
mlog.Error(err.Error())
|
||||
|
||||
time.Sleep(time.Second)
|
||||
panic(err)
|
||||
}
|
||||
utils.EnableDebugLogForTest()
|
||||
return channel
|
||||
}
|
||||
|
||||
func (me *TestHelper) createChannelWithAnotherUser(team *model.Team, channelType, userId string) *model.Channel {
|
||||
id := model.NewId()
|
||||
|
||||
channel := &model.Channel{
|
||||
DisplayName: "dn_" + id,
|
||||
Name: "name_" + id,
|
||||
Type: channelType,
|
||||
TeamId: team.Id,
|
||||
CreatorId: userId,
|
||||
}
|
||||
|
||||
utils.DisableDebugLogForTest()
|
||||
var err *model.AppError
|
||||
if channel, err = me.App.CreateChannel(channel, true); err != nil {
|
||||
mlog.Error(err.Error())
|
||||
|
||||
time.Sleep(time.Second)
|
||||
panic(err)
|
||||
}
|
||||
utils.EnableDebugLogForTest()
|
||||
return channel
|
||||
}
|
||||
|
||||
func (me *TestHelper) createDmChannel(user *model.User) *model.Channel {
|
||||
utils.DisableDebugLogForTest()
|
||||
var err *model.AppError
|
||||
var channel *model.Channel
|
||||
if channel, err = me.App.GetOrCreateDirectChannel(me.BasicUser.Id, user.Id); err != nil {
|
||||
mlog.Error(err.Error())
|
||||
|
||||
time.Sleep(time.Second)
|
||||
panic(err)
|
||||
}
|
||||
utils.EnableDebugLogForTest()
|
||||
return channel
|
||||
}
|
||||
|
||||
func (me *TestHelper) createGroupChannel(user1 *model.User, user2 *model.User) *model.Channel {
|
||||
utils.DisableDebugLogForTest()
|
||||
var err *model.AppError
|
||||
var channel *model.Channel
|
||||
if channel, err = me.App.CreateGroupChannel([]string{me.BasicUser.Id, user1.Id, user2.Id}, me.BasicUser.Id); err != nil {
|
||||
mlog.Error(err.Error())
|
||||
|
||||
time.Sleep(time.Second)
|
||||
panic(err)
|
||||
}
|
||||
utils.EnableDebugLogForTest()
|
||||
return channel
|
||||
}
|
||||
|
||||
func (me *TestHelper) createPost(channel *model.Channel) *model.Post {
|
||||
id := model.NewId()
|
||||
|
||||
post := &model.Post{
|
||||
UserId: me.BasicUser.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "message_" + id,
|
||||
CreateAt: model.GetMillis() - 10000,
|
||||
}
|
||||
|
||||
utils.DisableDebugLogForTest()
|
||||
var err *model.AppError
|
||||
if post, err = me.App.CreatePost(post, channel, false, true); err != nil {
|
||||
mlog.Error(err.Error())
|
||||
|
||||
time.Sleep(time.Second)
|
||||
panic(err)
|
||||
}
|
||||
utils.EnableDebugLogForTest()
|
||||
return post
|
||||
}
|
||||
|
||||
func (me *TestHelper) linkUserToTeam(user *model.User, team *model.Team) {
|
||||
utils.DisableDebugLogForTest()
|
||||
|
||||
err := me.App.JoinUserToTeam(team, user, "")
|
||||
if err != nil {
|
||||
mlog.Error(err.Error())
|
||||
|
||||
time.Sleep(time.Second)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
utils.EnableDebugLogForTest()
|
||||
}
|
||||
|
||||
func (me *TestHelper) addUserToChannel(user *model.User, channel *model.Channel) *model.ChannelMember {
|
||||
utils.DisableDebugLogForTest()
|
||||
|
||||
member, err := me.App.AddUserToChannel(user, channel)
|
||||
if err != nil {
|
||||
mlog.Error(err.Error())
|
||||
|
||||
time.Sleep(time.Second)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
utils.EnableDebugLogForTest()
|
||||
|
||||
return member
|
||||
}
|
||||
|
||||
func (me *TestHelper) shutdownApp() {
|
||||
done := make(chan bool)
|
||||
go func() {
|
||||
me.Server.Shutdown()
|
||||
close(done)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(30 * time.Second):
|
||||
// panic instead of fatal to terminate all tests in this package, otherwise the
|
||||
// still running App could spuriously fail subsequent tests.
|
||||
panic("failed to shutdown App within 30 seconds")
|
||||
}
|
||||
}
|
||||
|
||||
func (me *TestHelper) tearDown() {
|
||||
if me.IncludeCacheLayer {
|
||||
// Clean all the caches
|
||||
me.App.Srv().InvalidateAllCaches()
|
||||
}
|
||||
me.shutdownApp()
|
||||
if me.tempWorkspace != "" {
|
||||
os.RemoveAll(me.tempWorkspace)
|
||||
}
|
||||
}
|
||||
|
||||
func (me *TestHelper) removePermissionFromRole(permission string, roleName string) {
|
||||
utils.DisableDebugLogForTest()
|
||||
|
||||
role, err1 := me.App.GetRoleByName(roleName)
|
||||
if err1 != nil {
|
||||
utils.EnableDebugLogForTest()
|
||||
panic(err1)
|
||||
}
|
||||
|
||||
var newPermissions []string
|
||||
for _, p := range role.Permissions {
|
||||
if p != permission {
|
||||
newPermissions = append(newPermissions, p)
|
||||
}
|
||||
}
|
||||
|
||||
if strings.Join(role.Permissions, " ") == strings.Join(newPermissions, " ") {
|
||||
utils.EnableDebugLogForTest()
|
||||
return
|
||||
}
|
||||
|
||||
role.Permissions = newPermissions
|
||||
|
||||
_, err2 := me.App.UpdateRole(role)
|
||||
if err2 != nil {
|
||||
utils.EnableDebugLogForTest()
|
||||
panic(err2)
|
||||
}
|
||||
|
||||
utils.EnableDebugLogForTest()
|
||||
}
|
||||
|
||||
func (me *TestHelper) addPermissionToRole(permission string, roleName string) {
|
||||
utils.DisableDebugLogForTest()
|
||||
|
||||
role, err1 := me.App.GetRoleByName(roleName)
|
||||
if err1 != nil {
|
||||
utils.EnableDebugLogForTest()
|
||||
panic(err1)
|
||||
}
|
||||
|
||||
for _, existingPermission := range role.Permissions {
|
||||
if existingPermission == permission {
|
||||
utils.EnableDebugLogForTest()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
role.Permissions = append(role.Permissions, permission)
|
||||
|
||||
_, err2 := me.App.UpdateRole(role)
|
||||
if err2 != nil {
|
||||
utils.EnableDebugLogForTest()
|
||||
panic(err2)
|
||||
}
|
||||
|
||||
utils.EnableDebugLogForTest()
|
||||
}
|
||||
24
app/slashcommands/main_test.go
Обычный файл
24
app/slashcommands/main_test.go
Обычный файл
@@ -0,0 +1,24 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package slashcommands
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/testlib"
|
||||
)
|
||||
|
||||
var mainHelper *testlib.MainHelper
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
var options = testlib.HelperOptions{
|
||||
EnableStore: true,
|
||||
EnableResources: true,
|
||||
}
|
||||
|
||||
mainHelper = testlib.NewMainHelperWithOptions(&options)
|
||||
defer mainHelper.Close()
|
||||
|
||||
mainHelper.Main(m)
|
||||
}
|
||||
Ссылка в новой задаче
Block a user