// POST /api/teams
504557
func (hs *HTTPServer) CreateTeam(c *m.ReqContext, cmd m.CreateTeamCommand) Response {
	cmd.OrgId = c.OrgId

	if c.OrgRole == m.ROLE_VIEWER {
		return Error(403, "Not allowed to create team.", nil)
	}

	if err := hs.Bus.Dispatch(&cmd); err != nil {
		if err == m.ErrTeamNameTaken {
			return Error(409, "Team name taken", err)
		}
		return Error(500, "Failed to create Team", err)
	}

	if c.OrgRole == m.ROLE_EDITOR && hs.Cfg.EditorsCanAdmin {
		addMemberCmd := m.AddTeamMemberCommand{
			UserId:     c.SignedInUser.UserId,
			OrgId:      cmd.OrgId,
			TeamId:     cmd.Result.Id,
			Permission: m.PERMISSION_ADMIN,
		}

		if err := hs.Bus.Dispatch(&addMemberCmd); err != nil {
			c.Logger.Error("Could not add creator to team.", "error", err)
		}
	}

	return JSON(200, &util.DynMap{
		"teamId":  cmd.Result.Id,
		"message": "Team created",
	})
}
205812
func (c *CmdTeamDelete) listSubteamsRecursive(cli *keybase1.TeamsClient) (res []keybase1.TeamName, err error) {
	subs, err := cli.TeamListSubteamsRecursive(context.TODO(), keybase1.TeamListSubteamsRecursiveArg{
		ParentTeamName: c.Team.String(),
		ForceRepoll:    true,
	})
	if err != nil {
		return res, err
	}
	// Sort the response alphabetically
	sort.Slice(subs, func(i, j int) bool {
		return subs[i].Name.String() < subs[j].Name.String()
	})
	for _, sub := range subs {
		res = append(res, sub.Name)
	}
	return res, err
}
577801
func (s *TeamsService) ListTeamMembers(ctx context.Context, team int64, opt *TeamListTeamMembersOptions) ([]*User, *Response, error) {
	u := fmt.Sprintf("teams/%v/members", team)
	u, err := addOptions(u, opt)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	req.Header.Set("Accept", mediaTypeNestedTeamsPreview)

	var members []*User
	resp, err := s.client.Do(ctx, req, &members)
	if err != nil {
		return nil, resp, err
	}

	return members, resp, nil
}
1137200
func (p *provider) getUserTeams(token string) (sets.String, error) {
	userTeams := sets.NewString()
	err := p.page(p.githubUserTeamURL, token,
		func() interface{} {
			return &[]githubTeam{}
		},
		func(obj interface{}) error {
			for _, team := range *(obj.(*[]githubTeam)) {
				if len(team.Slug) > 0 && len(team.Organization.Login) > 0 {
					userTeams.Insert(strings.ToLower(team.Organization.Login + "/" + team.Slug))
				}
			}
			return nil
		},
	)
	return userTeams, err
}
1143431
func GetTeamsByUser(query *m.GetTeamsByUserQuery) error {
	query.Result = make([]*m.TeamDTO, 0)

	var sql bytes.Buffer

	sql.WriteString(getTeamSelectSqlBase())
	sql.WriteString(` INNER JOIN team_member on team.id = team_member.team_id`)
	sql.WriteString(` WHERE team.org_id = ? and team_member.user_id = ?`)

	err := x.SQL(sql.String(), query.OrgId, query.UserId).Find(&query.Result)
	return err
}
1008166
func (p *PostService) CreateSharing(teamName string, postNumber int) (*SharedPost, error) {
	postNumberStr := strconv.Itoa(postNumber)
	postURL := PostURL + "/" + teamName + "/posts" + "/" + postNumberStr + "/sharing"
	var sharedRes SharedPost
	var postReq PostReq
	var data []byte
	var err error
	if data, err = json.Marshal(postReq); err != nil {
		return nil, err
	}

	res, err := p.client.post(postURL, "application/json", bytes.NewReader(data), &sharedRes)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()

	return &sharedRes, nil
}
1042243
func (t *TeamsService) Create(uri *Hyperlink, input TeamParams,
	uriParams M) (team Team, result *Result) {
	url, err := ExpandWithDefault(uri, &OrganizationTeamsURL, uriParams)
	if err != nil {
		return Team{}, &Result{Err: err}
	}
	result = t.client.post(url, input, &team)
	return
}
458926
func (t *TeamsClient) Create(ctx context.Context, orgID *identity.ID, name string,
	teamType primitive.TeamType) (*envelope.Team, error) {
	if orgID == nil {
		return nil, errors.New("invalid org")
	}

	teamBody := primitive.Team{
		Name:     name,
		OrgID:    orgID,
		TeamType: teamType,
	}

	ID, err := identity.NewMutable(&teamBody)
	if err != nil {
		return nil, err
	}

	team := envelope.Team{
		ID:      &ID,
		Version: 1,
		Body:    &teamBody,
	}

	result := &envelope.Team{}
	err = t.client.RoundTrip(ctx, "POST", "/teams", nil, &team, result)
	return result, err
}
506981
func (t *TeamsService) All(uri *Hyperlink, uriParams M) (
	teams []Team, result *Result) {
	url, err := ExpandWithDefault(uri, &OrganizationTeamsURL, uriParams)
	if err != nil {
		return []Team(nil), &Result{Err: err}
	}
	result = t.client.get(url, &teams)
	return
}
777535
func GetUserTeams(orgID, userID int64) ([]*Team, error) {
	return getUserTeams(x, orgID, userID)
}
37011
func (p *PostService) GetPosts(teamName string, query url.Values) (*PostsResponse, error) {
	var postsRes PostsResponse
	queries := createQuery(query)

	postsURL := PostURL + "/" + teamName + "/posts"
	res, err := p.client.get(postsURL, queries, &postsRes)
	if err != nil {
		return nil, err
	}

	defer res.Body.Close()

	return &postsRes, nil

}
871194
func (m *MMClient) GetTeamName(teamId string) string { //nolint:golint
	m.RLock()
	defer m.RUnlock()
	for _, t := range m.OtherTeams {
		if t.Id == teamId {
			return t.Team.Name
		}
	}
	return ""
}
92316
func (hs *HTTPServer) UpdateTeamMember(c *m.ReqContext, cmd m.UpdateTeamMemberCommand) Response {
	teamId := c.ParamsInt64(":teamId")
	orgId := c.OrgId

	if err := teamguardian.CanAdmin(hs.Bus, orgId, teamId, c.SignedInUser); err != nil {
		return Error(403, "Not allowed to update team member", err)
	}

	if c.OrgRole != m.ROLE_ADMIN {
		cmd.ProtectLastAdmin = true
	}

	cmd.TeamId = teamId
	cmd.UserId = c.ParamsInt64(":userId")
	cmd.OrgId = orgId

	if err := hs.Bus.Dispatch(&cmd); err != nil {
		if err == m.ErrTeamMemberNotFound {
			return Error(404, "Team member not found.", nil)
		}
		return Error(500, "Failed to update team member.", err)
	}
	return Success("Team member updated")
}
1022857
func (l *localLoadedTeams) getTeamForMember(ctx context.Context, member keybase1.MemberInfo,
	needAdmin bool) (team *Team, uv keybase1.UserVersion, err error) {
	teamID := member.TeamID
	team = l.teams[teamID]
	if team == nil {
		// Team was not there in local cache - this is the first time
		// localLoadedTeams is asked for this team. Try with no
		// forceRepoll first.
		team, err = Load(ctx, l.G(), keybase1.LoadTeamArg{
			ID:               teamID,
			NeedAdmin:        needAdmin,
			Public:           teamID.IsPublic(),
			ForceRepoll:      false,
			RefreshUIDMapper: true,
		})
		if err != nil {
			return nil, uv, err
		}
		l.teams[teamID] = team
	}

	memberUV, err := verifyMemberRoleInTeam(ctx, member.UserID, member.Role, team)
	if err != nil {
		team, err = Load(ctx, l.G(), keybase1.LoadTeamArg{
			ID:          teamID,
			NeedAdmin:   needAdmin,
			Public:      teamID.IsPublic(),
			ForceRepoll: true,
		})
		if err != nil {
			return nil, uv, err
		}
		l.teams[teamID] = team

		memberUV, err = verifyMemberRoleInTeam(ctx, member.UserID, member.Role, team)
		if err != nil {
			return nil, uv, fmt.Errorf("server was wrong about role in team : %v", err)
		}
	}

	return team, memberUV, nil
}
994024
func (s *Service) TeamList(ctx context.Context, lr *ListRange) (TeamListResult, error) {
	var team TeamListResult
	return team, s.Get(ctx, &team, fmt.Sprintf("/teams"), nil, lr)
}
237036
func NewGetTeamEventsResult(Events []*TeamEvent, Cursor string, HasMore bool) *GetTeamEventsResult {
	s := new(GetTeamEventsResult)
	s.Events = Events
	s.Cursor = Cursor
	s.HasMore = HasMore
	return s
}
94392
func (cs *TeamService) Create(team Team) (*TeamResponse, error) {
	if err := team.Valid(); err != nil {
		return nil, err
	}

	req, err := cs.client.NewRequest("POST", "/teams", team.PostParams())
	if err != nil {
		return nil, err
	}

	t := &TeamResponse{}
	_, err = cs.client.Do(req, t)
	if err != nil {
		return nil, err
	}
	return t, err
}