github.com/cryptomisa/mattermost-server@v5.11.1+incompatible/cmd/mattermost/commands/team.go (about)

     1  // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
     2  // See License.txt for license information.
     3  
     4  package commands
     5  
     6  import (
     7  	"errors"
     8  	"fmt"
     9  	"sort"
    10  
    11  	"github.com/mattermost/mattermost-server/app"
    12  	"github.com/mattermost/mattermost-server/model"
    13  	"github.com/spf13/cobra"
    14  )
    15  
    16  var TeamCmd = &cobra.Command{
    17  	Use:   "team",
    18  	Short: "Management of teams",
    19  }
    20  
    21  var TeamCreateCmd = &cobra.Command{
    22  	Use:   "create",
    23  	Short: "Create a team",
    24  	Long:  `Create a team.`,
    25  	Example: `  team create --name mynewteam --display_name "My New Team"
    26    team create --name private --display_name "My New Private Team" --private`,
    27  	RunE: createTeamCmdF,
    28  }
    29  
    30  var RemoveUsersCmd = &cobra.Command{
    31  	Use:     "remove [team] [users]",
    32  	Short:   "Remove users from team",
    33  	Long:    "Remove some users from team",
    34  	Example: "  team remove myteam user@example.com username",
    35  	Args:    cobra.MinimumNArgs(2),
    36  	RunE:    removeUsersCmdF,
    37  }
    38  
    39  var AddUsersCmd = &cobra.Command{
    40  	Use:     "add [team] [users]",
    41  	Short:   "Add users to team",
    42  	Long:    "Add some users to team",
    43  	Example: "  team add myteam user@example.com username",
    44  	Args:    cobra.MinimumNArgs(2),
    45  	RunE:    addUsersCmdF,
    46  }
    47  
    48  var DeleteTeamsCmd = &cobra.Command{
    49  	Use:   "delete [teams]",
    50  	Short: "Delete teams",
    51  	Long: `Permanently delete some teams.
    52  Permanently deletes a team along with all related information including posts from the database.`,
    53  	Example: "  team delete myteam",
    54  	Args:    cobra.MinimumNArgs(1),
    55  	RunE:    deleteTeamsCmdF,
    56  }
    57  
    58  var ListTeamsCmd = &cobra.Command{
    59  	Use:     "list",
    60  	Short:   "List all teams.",
    61  	Long:    `List all teams on the server.`,
    62  	Example: "  team list",
    63  	RunE:    listTeamsCmdF,
    64  }
    65  
    66  var SearchTeamCmd = &cobra.Command{
    67  	Use:     "search [teams]",
    68  	Short:   "Search for teams",
    69  	Long:    "Search for teams based on name",
    70  	Example: "  team search team1",
    71  	Args:    cobra.MinimumNArgs(1),
    72  	RunE:    searchTeamCmdF,
    73  }
    74  
    75  var ArchiveTeamCmd = &cobra.Command{
    76  	Use:     "archive [teams]",
    77  	Short:   "Archive teams",
    78  	Long:    "Archive teams based on name",
    79  	Example: "  team archive team1",
    80  	Args:    cobra.MinimumNArgs(1),
    81  	RunE:    archiveTeamCmdF,
    82  }
    83  
    84  var RestoreTeamsCmd = &cobra.Command{
    85  	Use:     "restore [teams]",
    86  	Short:   "Restore some teams",
    87  	Long:    `Restore a previously deleted team`,
    88  	Example: "  team restore myteam",
    89  	Args:    cobra.MinimumNArgs(1),
    90  	RunE:    restoreTeamsCmdF,
    91  }
    92  
    93  var TeamRenameCmd = &cobra.Command{
    94  	Use:   "rename",
    95  	Short: "Rename a team",
    96  	Long:  `Rename a team.`,
    97  	Example: `  team rename myteam newteamname --display_name "My New Team Name"
    98  	team rename myteam - --display_name "My New Team Name"`,
    99  	Args: cobra.MinimumNArgs(2),
   100  	RunE: renameTeamCmdF,
   101  }
   102  
   103  func init() {
   104  	TeamCreateCmd.Flags().String("name", "", "Team Name")
   105  	TeamCreateCmd.Flags().String("display_name", "", "Team Display Name")
   106  	TeamCreateCmd.Flags().Bool("private", false, "Create a private team.")
   107  	TeamCreateCmd.Flags().String("email", "", "Administrator Email (anyone with this email is automatically a team admin)")
   108  
   109  	DeleteTeamsCmd.Flags().Bool("confirm", false, "Confirm you really want to delete the team and a DB backup has been performed.")
   110  
   111  	TeamRenameCmd.Flags().String("display_name", "", "Team Display Name")
   112  
   113  	TeamCmd.AddCommand(
   114  		TeamCreateCmd,
   115  		RemoveUsersCmd,
   116  		AddUsersCmd,
   117  		DeleteTeamsCmd,
   118  		ListTeamsCmd,
   119  		SearchTeamCmd,
   120  		ArchiveTeamCmd,
   121  		RestoreTeamsCmd,
   122  		TeamRenameCmd,
   123  	)
   124  	RootCmd.AddCommand(TeamCmd)
   125  }
   126  
   127  func createTeamCmdF(command *cobra.Command, args []string) error {
   128  	a, err := InitDBCommandContextCobra(command)
   129  	if err != nil {
   130  		return err
   131  	}
   132  	defer a.Shutdown()
   133  
   134  	name, errn := command.Flags().GetString("name")
   135  	if errn != nil || name == "" {
   136  		return errors.New("Name is required")
   137  	}
   138  	displayname, errdn := command.Flags().GetString("display_name")
   139  	if errdn != nil || displayname == "" {
   140  		return errors.New("Display Name is required")
   141  	}
   142  	email, _ := command.Flags().GetString("email")
   143  	useprivate, _ := command.Flags().GetBool("private")
   144  
   145  	teamType := model.TEAM_OPEN
   146  	if useprivate {
   147  		teamType = model.TEAM_INVITE
   148  	}
   149  
   150  	team := &model.Team{
   151  		Name:        name,
   152  		DisplayName: displayname,
   153  		Email:       email,
   154  		Type:        teamType,
   155  	}
   156  
   157  	if _, err := a.CreateTeam(team); err != nil {
   158  		return errors.New("Team creation failed: " + err.Error())
   159  	}
   160  
   161  	return nil
   162  }
   163  
   164  func removeUsersCmdF(command *cobra.Command, args []string) error {
   165  	a, err := InitDBCommandContextCobra(command)
   166  	if err != nil {
   167  		return err
   168  	}
   169  	defer a.Shutdown()
   170  
   171  	team := getTeamFromTeamArg(a, args[0])
   172  	if team == nil {
   173  		return errors.New("Unable to find team '" + args[0] + "'")
   174  	}
   175  
   176  	users := getUsersFromUserArgs(a, args[1:])
   177  	for i, user := range users {
   178  		removeUserFromTeam(a, team, user, args[i+1])
   179  	}
   180  
   181  	return nil
   182  }
   183  
   184  func removeUserFromTeam(a *app.App, team *model.Team, user *model.User, userArg string) {
   185  	if user == nil {
   186  		CommandPrintErrorln("Can't find user '" + userArg + "'")
   187  		return
   188  	}
   189  	if err := a.LeaveTeam(team, user, ""); err != nil {
   190  		CommandPrintErrorln("Unable to remove '" + userArg + "' from " + team.Name + ". Error: " + err.Error())
   191  	}
   192  }
   193  
   194  func addUsersCmdF(command *cobra.Command, args []string) error {
   195  	a, err := InitDBCommandContextCobra(command)
   196  	if err != nil {
   197  		return err
   198  	}
   199  	defer a.Shutdown()
   200  
   201  	team := getTeamFromTeamArg(a, args[0])
   202  	if team == nil {
   203  		return errors.New("Unable to find team '" + args[0] + "'")
   204  	}
   205  
   206  	users := getUsersFromUserArgs(a, args[1:])
   207  	for i, user := range users {
   208  		addUserToTeam(a, team, user, args[i+1])
   209  	}
   210  
   211  	return nil
   212  }
   213  
   214  func addUserToTeam(a *app.App, team *model.Team, user *model.User, userArg string) {
   215  	if user == nil {
   216  		CommandPrintErrorln("Can't find user '" + userArg + "'")
   217  		return
   218  	}
   219  	if err := a.JoinUserToTeam(team, user, ""); err != nil {
   220  		CommandPrintErrorln("Unable to add '" + userArg + "' to " + team.Name)
   221  	}
   222  }
   223  
   224  func deleteTeamsCmdF(command *cobra.Command, args []string) error {
   225  	a, err := InitDBCommandContextCobra(command)
   226  	if err != nil {
   227  		return err
   228  	}
   229  	defer a.Shutdown()
   230  
   231  	confirmFlag, _ := command.Flags().GetBool("confirm")
   232  	if !confirmFlag {
   233  		var confirm string
   234  		CommandPrettyPrintln("Have you performed a database backup? (YES/NO): ")
   235  		fmt.Scanln(&confirm)
   236  
   237  		if confirm != "YES" {
   238  			return errors.New("ABORTED: You did not answer YES exactly, in all capitals.")
   239  		}
   240  		CommandPrettyPrintln("Are you sure you want to delete the teams specified?  All data will be permanently deleted? (YES/NO): ")
   241  		fmt.Scanln(&confirm)
   242  		if confirm != "YES" {
   243  			return errors.New("ABORTED: You did not answer YES exactly, in all capitals.")
   244  		}
   245  	}
   246  
   247  	teams := getTeamsFromTeamArgs(a, args)
   248  	for i, team := range teams {
   249  		if team == nil {
   250  			CommandPrintErrorln("Unable to find team '" + args[i] + "'")
   251  			continue
   252  		}
   253  		if err := deleteTeam(a, team); err != nil {
   254  			CommandPrintErrorln("Unable to delete team '" + team.Name + "' error: " + err.Error())
   255  		} else {
   256  			CommandPrettyPrintln("Deleted team '" + team.Name + "'")
   257  		}
   258  	}
   259  
   260  	return nil
   261  }
   262  
   263  func deleteTeam(a *app.App, team *model.Team) *model.AppError {
   264  	return a.PermanentDeleteTeam(team)
   265  }
   266  
   267  func listTeamsCmdF(command *cobra.Command, args []string) error {
   268  	a, err := InitDBCommandContextCobra(command)
   269  	if err != nil {
   270  		return err
   271  	}
   272  	defer a.Shutdown()
   273  
   274  	teams, err2 := a.GetAllTeams()
   275  	if err2 != nil {
   276  		return err2
   277  	}
   278  
   279  	for _, team := range teams {
   280  		if team.DeleteAt > 0 {
   281  			CommandPrettyPrintln(team.Name + " (archived)")
   282  		} else {
   283  			CommandPrettyPrintln(team.Name)
   284  		}
   285  	}
   286  
   287  	return nil
   288  }
   289  
   290  func searchTeamCmdF(command *cobra.Command, args []string) error {
   291  	a, err := InitDBCommandContextCobra(command)
   292  	if err != nil {
   293  		return err
   294  	}
   295  	defer a.Shutdown()
   296  
   297  	var teams []*model.Team
   298  
   299  	for _, searchTerm := range args {
   300  		foundTeams, err := a.SearchAllTeams(searchTerm)
   301  		if err != nil {
   302  			return err
   303  		}
   304  		teams = append(teams, foundTeams...)
   305  	}
   306  
   307  	sortedTeams := removeDuplicatesAndSortTeams(teams)
   308  
   309  	for _, team := range sortedTeams {
   310  		if team.DeleteAt > 0 {
   311  			CommandPrettyPrintln(team.Name + ": " + team.DisplayName + " (" + team.Id + ")" + " (archived)")
   312  		} else {
   313  			CommandPrettyPrintln(team.Name + ": " + team.DisplayName + " (" + team.Id + ")")
   314  		}
   315  	}
   316  
   317  	return nil
   318  }
   319  
   320  // Restores archived teams by name
   321  func restoreTeamsCmdF(command *cobra.Command, args []string) error {
   322  	a, err := InitDBCommandContextCobra(command)
   323  	if err != nil {
   324  		return err
   325  	}
   326  	defer a.Shutdown()
   327  
   328  	teams := getTeamsFromTeamArgs(a, args)
   329  	for i, team := range teams {
   330  		if team == nil {
   331  			CommandPrintErrorln("Unable to find team '" + args[i] + "'")
   332  			continue
   333  		}
   334  		err := a.RestoreTeam(team.Id)
   335  		if err != nil {
   336  			CommandPrintErrorln("Unable to restore team '" + team.Name + "' error: " + err.Error())
   337  		}
   338  	}
   339  	return nil
   340  }
   341  
   342  // Removes duplicates and sorts teams by name
   343  func removeDuplicatesAndSortTeams(teams []*model.Team) []*model.Team {
   344  	keys := make(map[string]bool)
   345  	result := []*model.Team{}
   346  	for _, team := range teams {
   347  		if _, value := keys[team.Name]; !value {
   348  			keys[team.Name] = true
   349  			result = append(result, team)
   350  		}
   351  	}
   352  	sort.Slice(result, func(i, j int) bool {
   353  		return result[i].Name < result[j].Name
   354  	})
   355  	return result
   356  }
   357  
   358  func archiveTeamCmdF(command *cobra.Command, args []string) error {
   359  	a, err := InitDBCommandContextCobra(command)
   360  	if err != nil {
   361  		return err
   362  	}
   363  	defer a.Shutdown()
   364  
   365  	foundTeams := getTeamsFromTeamArgs(a, args)
   366  	for i, team := range foundTeams {
   367  		if team == nil {
   368  			CommandPrintErrorln("Unable to find team '" + args[i] + "'")
   369  			continue
   370  		}
   371  		if err := a.SoftDeleteTeam(team.Id); err != nil {
   372  			CommandPrintErrorln("Unable to archive team '"+team.Name+"' error: ", err)
   373  		}
   374  	}
   375  
   376  	return nil
   377  }
   378  
   379  func renameTeamCmdF(command *cobra.Command, args []string) error {
   380  
   381  	a, err := InitDBCommandContextCobra(command)
   382  	if err != nil {
   383  		return err
   384  	}
   385  	defer a.Shutdown()
   386  
   387  	team := getTeamFromTeamArg(a, args[0])
   388  	if team == nil {
   389  		return errors.New("Unable to find team '" + args[0] + "'")
   390  	}
   391  
   392  	var newDisplayName, newTeamName string
   393  
   394  	newTeamName = args[1]
   395  
   396  	// let user use old team Name when only Display Name change is wanted
   397  	if newTeamName == team.Name {
   398  		newTeamName = "-"
   399  	}
   400  
   401  	newDisplayName, errdn := command.Flags().GetString("display_name")
   402  	if errdn != nil {
   403  		return errdn
   404  	}
   405  
   406  	_, errrt := a.RenameTeam(team, newTeamName, newDisplayName)
   407  	if errrt != nil {
   408  		CommandPrintErrorln("Unable to rename team to '"+newTeamName+"' error: ", errrt)
   409  	}
   410  
   411  	return nil
   412  }