Migrate to stateless app.App (#17542)
* add request context * move initialialization to server * use app interface instead of global app functions * remove app context from webconn * cleanup * remove duplicated services * move context to separate package * remove finalize init method and move content to NewServer function * restart workers and schedulers after adding license for tests * reflect review comments Co-authored-by: Mattermod <mattermod@users.noreply.github.com>
Этот коммит содержится в:
коммит произвёл
GitHub
родитель
c09369f14a
Коммит
5ea06e51d0
180
app/app.go
180
app/app.go
@@ -4,13 +4,13 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/einterfaces"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/services/httpservice"
|
||||
@@ -31,16 +31,6 @@ type App struct {
|
||||
// to be registered in (h *MainHelper) setupStore, but that creates
|
||||
// a cyclic dependency as bleve tests themselves import testlib.
|
||||
searchEngine *searchengine.Broker
|
||||
|
||||
t i18n.TranslateFunc
|
||||
session model.Session
|
||||
requestId string
|
||||
ipAddress string
|
||||
path string
|
||||
userAgent string
|
||||
acceptLanguage string
|
||||
|
||||
context context.Context
|
||||
}
|
||||
|
||||
func New(options ...AppOption) *App {
|
||||
@@ -53,103 +43,6 @@ func New(options ...AppOption) *App {
|
||||
return app
|
||||
}
|
||||
|
||||
func (a *App) InitServer() {
|
||||
a.srv.AppInitializedOnce.Do(func() {
|
||||
a.initEnterprise()
|
||||
|
||||
a.AddConfigListener(func(oldConfig *model.Config, newConfig *model.Config) {
|
||||
if *oldConfig.GuestAccountsSettings.Enable && !*newConfig.GuestAccountsSettings.Enable {
|
||||
if appErr := a.DeactivateGuests(); appErr != nil {
|
||||
mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Disable active guest accounts on first run if guest accounts are disabled
|
||||
if !*a.Config().GuestAccountsSettings.Enable {
|
||||
if appErr := a.DeactivateGuests(); appErr != nil {
|
||||
mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr))
|
||||
}
|
||||
}
|
||||
|
||||
// Scheduler must be started before cluster.
|
||||
a.initJobs()
|
||||
|
||||
if a.srv.joinCluster && a.srv.Cluster != nil {
|
||||
a.registerAppClusterMessageHandlers()
|
||||
}
|
||||
|
||||
a.DoAppMigrations()
|
||||
|
||||
a.InitPostMetadata()
|
||||
|
||||
a.InitPlugins(*a.Config().PluginSettings.Directory, *a.Config().PluginSettings.ClientDirectory)
|
||||
a.AddConfigListener(func(prevCfg, cfg *model.Config) {
|
||||
if *cfg.PluginSettings.Enable {
|
||||
a.InitPlugins(*cfg.PluginSettings.Directory, *a.Config().PluginSettings.ClientDirectory)
|
||||
} else {
|
||||
a.srv.ShutDownPlugins()
|
||||
}
|
||||
})
|
||||
if a.Srv().runEssentialJobs {
|
||||
a.Srv().Go(func() {
|
||||
runLicenseExpirationCheckJob(a)
|
||||
runCheckWarnMetricStatusJob(a)
|
||||
runDNDStatusExpireJob(a)
|
||||
runCheckAdminSupportStatusJob(a)
|
||||
})
|
||||
a.srv.runJobs()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) initJobs() {
|
||||
if jobsLdapSyncInterface != nil {
|
||||
a.srv.Jobs.LdapSync = jobsLdapSyncInterface(a)
|
||||
}
|
||||
if jobsPluginsInterface != nil {
|
||||
a.srv.Jobs.Plugins = jobsPluginsInterface(a)
|
||||
}
|
||||
if jobsExpiryNotifyInterface != nil {
|
||||
a.srv.Jobs.ExpiryNotify = jobsExpiryNotifyInterface(a)
|
||||
}
|
||||
if productNoticesJobInterface != nil {
|
||||
a.srv.Jobs.ProductNotices = productNoticesJobInterface(a)
|
||||
}
|
||||
if jobsImportProcessInterface != nil {
|
||||
a.srv.Jobs.ImportProcess = jobsImportProcessInterface(a)
|
||||
}
|
||||
if jobsImportDeleteInterface != nil {
|
||||
a.srv.Jobs.ImportDelete = jobsImportDeleteInterface(a)
|
||||
}
|
||||
if jobsExportDeleteInterface != nil {
|
||||
a.srv.Jobs.ExportDelete = jobsExportDeleteInterface(a)
|
||||
}
|
||||
|
||||
if jobsExportProcessInterface != nil {
|
||||
a.srv.Jobs.ExportProcess = jobsExportProcessInterface(a)
|
||||
}
|
||||
|
||||
if jobsExportProcessInterface != nil {
|
||||
a.srv.Jobs.ExportProcess = jobsExportProcessInterface(a)
|
||||
}
|
||||
|
||||
if jobsActiveUsersInterface != nil {
|
||||
a.srv.Jobs.ActiveUsers = jobsActiveUsersInterface(a)
|
||||
}
|
||||
|
||||
if jobsCloudInterface != nil {
|
||||
a.srv.Jobs.Cloud = jobsCloudInterface(a.srv)
|
||||
}
|
||||
|
||||
if jobsResendInvitationEmailInterface != nil {
|
||||
a.srv.Jobs.ResendInvitationEmails = jobsResendInvitationEmailInterface(a)
|
||||
}
|
||||
|
||||
a.srv.Jobs.InitWorkers()
|
||||
a.srv.Jobs.InitSchedulers()
|
||||
}
|
||||
|
||||
func (a *App) TelemetryId() string {
|
||||
return a.Srv().TelemetryId()
|
||||
}
|
||||
@@ -343,7 +236,7 @@ func (a *App) getWarnMetricStatusAndDisplayTextsForId(warnMetricId string, T i18
|
||||
}
|
||||
|
||||
//nolint:golint,unused,deadcode
|
||||
func (a *App) notifyAdminsOfWarnMetricStatus(warnMetricId string, isE0Edition bool) *model.AppError {
|
||||
func (a *App) notifyAdminsOfWarnMetricStatus(c *request.Context, warnMetricId string, isE0Edition bool) *model.AppError {
|
||||
perPage := 25
|
||||
userOptions := &model.UserGetOptions{
|
||||
Page: 0,
|
||||
@@ -394,7 +287,7 @@ func (a *App) notifyAdminsOfWarnMetricStatus(warnMetricId string, isE0Edition bo
|
||||
bot.DisplayName = T("app.system.warn_metric.bot_displayname")
|
||||
bot.Description = T("app.system.warn_metric.bot_description")
|
||||
|
||||
channel, appErr := a.GetOrCreateDirectChannel(bot.UserId, sysAdmin.Id)
|
||||
channel, appErr := a.GetOrCreateDirectChannel(c, bot.UserId, sysAdmin.Id)
|
||||
if appErr != nil {
|
||||
return appErr
|
||||
}
|
||||
@@ -462,7 +355,7 @@ func (a *App) notifyAdminsOfWarnMetricStatus(warnMetricId string, isE0Edition bo
|
||||
model.ParseSlackAttachment(botPost, attachments)
|
||||
|
||||
mlog.Debug("Post admin advisory for metric", mlog.String("warnMetricId", warnMetricId), mlog.String("userid", botPost.UserId))
|
||||
if _, err := a.CreatePostAsUser(botPost, a.Session().Id, true); err != nil {
|
||||
if _, err := a.CreatePostAsUser(c, botPost, c.Session().Id, true); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -565,12 +458,12 @@ func (a *App) setWarnMetricsStatusForId(warnMetricId string, status string) *mod
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) RequestLicenseAndAckWarnMetric(warnMetricId string, isBot bool) *model.AppError {
|
||||
func (a *App) RequestLicenseAndAckWarnMetric(c *request.Context, warnMetricId string, isBot bool) *model.AppError {
|
||||
if *a.Config().ExperimentalSettings.RestrictSystemAdmin {
|
||||
return model.NewAppError("RequestLicenseAndAckWarnMetric", "api.restricted_system_admin", nil, "", http.StatusForbidden)
|
||||
}
|
||||
|
||||
currentUser, appErr := a.GetUser(a.Session().UserId)
|
||||
currentUser, appErr := a.GetUser(c.Session().UserId)
|
||||
if appErr != nil {
|
||||
return appErr
|
||||
}
|
||||
@@ -620,27 +513,7 @@ func (a *App) Log() *mlog.Logger {
|
||||
func (a *App) NotificationsLog() *mlog.Logger {
|
||||
return a.srv.NotificationsLog
|
||||
}
|
||||
func (a *App) T(translationID string, args ...interface{}) string {
|
||||
return a.t(translationID, args...)
|
||||
}
|
||||
func (a *App) Session() *model.Session {
|
||||
return &a.session
|
||||
}
|
||||
func (a *App) RequestId() string {
|
||||
return a.requestId
|
||||
}
|
||||
func (a *App) IpAddress() string {
|
||||
return a.ipAddress
|
||||
}
|
||||
func (a *App) Path() string {
|
||||
return a.path
|
||||
}
|
||||
func (a *App) UserAgent() string {
|
||||
return a.userAgent
|
||||
}
|
||||
func (a *App) AcceptLanguage() string {
|
||||
return a.acceptLanguage
|
||||
}
|
||||
|
||||
func (a *App) AccountMigration() einterfaces.AccountMigrationInterface {
|
||||
return a.srv.AccountMigration
|
||||
}
|
||||
@@ -683,41 +556,6 @@ func (a *App) ImageProxy() *imageproxy.ImageProxy {
|
||||
func (a *App) Timezones() *timezones.Timezones {
|
||||
return a.srv.timezones
|
||||
}
|
||||
func (a *App) Context() context.Context {
|
||||
return a.context
|
||||
}
|
||||
|
||||
func (a *App) SetSession(s *model.Session) {
|
||||
a.session = *s
|
||||
}
|
||||
|
||||
func (a *App) SetT(t i18n.TranslateFunc) {
|
||||
a.t = t
|
||||
}
|
||||
func (a *App) SetRequestId(s string) {
|
||||
a.requestId = s
|
||||
}
|
||||
func (a *App) SetIpAddress(s string) {
|
||||
a.ipAddress = s
|
||||
}
|
||||
func (a *App) SetUserAgent(s string) {
|
||||
a.userAgent = s
|
||||
}
|
||||
func (a *App) SetAcceptLanguage(s string) {
|
||||
a.acceptLanguage = s
|
||||
}
|
||||
func (a *App) SetPath(s string) {
|
||||
a.path = s
|
||||
}
|
||||
func (a *App) SetContext(c context.Context) {
|
||||
a.context = c
|
||||
}
|
||||
func (a *App) SetServer(srv *Server) {
|
||||
a.srv = srv
|
||||
}
|
||||
func (a *App) GetT() i18n.TranslateFunc {
|
||||
return a.t
|
||||
}
|
||||
|
||||
func (a *App) DBHealthCheckWrite() error {
|
||||
currentTime := strconv.FormatInt(time.Now().Unix(), 10)
|
||||
@@ -737,6 +575,10 @@ func (a *App) dbHealthCheckKey() string {
|
||||
return fmt.Sprintf("health_check_%s", a.GetClusterId())
|
||||
}
|
||||
|
||||
func (a *App) SetServer(srv *Server) {
|
||||
a.srv = srv
|
||||
}
|
||||
|
||||
func (a *App) UpdateExpiredDNDStatuses() ([]*model.Status, error) {
|
||||
return a.Srv().Store.Status().UpdateExpiredDNDStatuses()
|
||||
}
|
||||
|
||||
221
app/app_iface.go
221
app/app_iface.go
@@ -18,6 +18,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/dyatlov/go-opengraph/opengraph"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/audit"
|
||||
"github.com/mattermost/mattermost-server/v5/einterfaces"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
@@ -36,14 +37,14 @@ import (
|
||||
// AppIface is extracted from App struct and contains all it's exported methods. It's provided to allow partial interface passing and app layers creation.
|
||||
type AppIface interface {
|
||||
// @openTracingParams args
|
||||
ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *model.AppError)
|
||||
ExecuteCommand(c *request.Context, args *model.CommandArgs) (*model.CommandResponse, *model.AppError)
|
||||
// @openTracingParams teamID
|
||||
// previous ListCommands now ListAutocompleteCommands
|
||||
ListAutocompleteCommands(teamID string, T i18n.TranslateFunc) ([]*model.Command, *model.AppError)
|
||||
// @openTracingParams teamID, skipSlackParsing
|
||||
CreateCommandPost(post *model.Post, teamID string, response *model.CommandResponse, skipSlackParsing bool) (*model.Post, *model.AppError)
|
||||
CreateCommandPost(c *request.Context, post *model.Post, teamID string, response *model.CommandResponse, skipSlackParsing bool) (*model.Post, *model.AppError)
|
||||
// AddChannelMember adds a user to a channel. It is a wrapper over AddUserToChannel.
|
||||
AddChannelMember(userID string, channel *model.Channel, opts ChannelMemberOpts) (*model.ChannelMember, *model.AppError)
|
||||
AddChannelMember(c *request.Context, userID string, channel *model.Channel, opts ChannelMemberOpts) (*model.ChannelMember, *model.AppError)
|
||||
// AddCursorIdsForPostList adds NextPostId and PrevPostId as cursor to the PostList.
|
||||
// The conditional blocks ensure that it sets those cursor IDs immediately as afterPost, beforePost or empty,
|
||||
// and only query to database whenever necessary.
|
||||
@@ -78,23 +79,23 @@ type AppIface interface {
|
||||
// ConvertUserToBot converts a user to bot.
|
||||
ConvertUserToBot(user *model.User) (*model.Bot, *model.AppError)
|
||||
// CreateBot creates the given bot and corresponding user.
|
||||
CreateBot(bot *model.Bot) (*model.Bot, *model.AppError)
|
||||
CreateBot(c *request.Context, bot *model.Bot) (*model.Bot, *model.AppError)
|
||||
// CreateChannelScheme creates a new Scheme of scope channel and assigns it to the channel.
|
||||
CreateChannelScheme(channel *model.Channel) (*model.Scheme, *model.AppError)
|
||||
// CreateDefaultChannels creates channels in the given team for each channel returned by (*App).DefaultChannelNames.
|
||||
//
|
||||
CreateDefaultChannels(teamID string) ([]*model.Channel, *model.AppError)
|
||||
CreateDefaultChannels(c *request.Context, teamID string) ([]*model.Channel, *model.AppError)
|
||||
// CreateDefaultMemberships adds users to teams and channels based on their group memberships and how those groups
|
||||
// are configured to sync with teams and channels for group members on or after the given timestamp.
|
||||
// If includeRemovedMembers is true, then members who left or were removed from a team/channel will
|
||||
// be re-added; otherwise, they will not be re-added.
|
||||
CreateDefaultMemberships(since int64, includeRemovedMembers bool) error
|
||||
CreateDefaultMemberships(c *request.Context, since int64, includeRemovedMembers bool) error
|
||||
// CreateGuest creates a guest and sets several fields of the returned User struct to
|
||||
// their zero values.
|
||||
CreateGuest(user *model.User) (*model.User, *model.AppError)
|
||||
CreateGuest(c *request.Context, user *model.User) (*model.User, *model.AppError)
|
||||
// CreateUser creates a user and sets several fields of the returned User struct to
|
||||
// their zero values.
|
||||
CreateUser(user *model.User) (*model.User, *model.AppError)
|
||||
CreateUser(c *request.Context, user *model.User) (*model.User, *model.AppError)
|
||||
// Creates and stores FileInfos for a post created before the FileInfos table existed.
|
||||
MigrateFilenamesToFileInfos(post *model.Post) []*model.FileInfo
|
||||
// DefaultChannelNames returns the list of system-wide default channel names.
|
||||
@@ -112,7 +113,7 @@ type AppIface interface {
|
||||
DeleteChannelScheme(channel *model.Channel) (*model.Channel, *model.AppError)
|
||||
// DeleteGroupConstrainedMemberships deletes team and channel memberships of users who aren't members of the allowed
|
||||
// groups of all group-constrained teams and channels.
|
||||
DeleteGroupConstrainedMemberships() error
|
||||
DeleteGroupConstrainedMemberships(c *request.Context) error
|
||||
// DeletePublicKey will delete plugin public key from the config.
|
||||
DeletePublicKey(name string) *model.AppError
|
||||
// DemoteUserToGuest Convert user's roles and all his mermbership's roles from
|
||||
@@ -196,7 +197,7 @@ type AppIface interface {
|
||||
// lock instead.
|
||||
GetPluginsEnvironment() *plugin.Environment
|
||||
// GetProductNotices is called from the frontend to fetch the product notices that are relevant to the caller
|
||||
GetProductNotices(userID, teamID string, client model.NoticeClientType, clientVersion string, locale string) (model.NoticeMessages, *model.AppError)
|
||||
GetProductNotices(c *request.Context, userID, teamID string, client model.NoticeClientType, clientVersion string, locale string) (model.NoticeMessages, *model.AppError)
|
||||
// GetPublicKey will return the actual public key saved in the `name` file.
|
||||
GetPublicKey(name string) ([]byte, *model.AppError)
|
||||
// GetSanitizedConfig gets the configuration for a system admin without any secrets.
|
||||
@@ -207,7 +208,7 @@ type AppIface interface {
|
||||
// based on the type of session (Mobile, SSO, Web/LDAP).
|
||||
GetSessionLengthInMillis(session *model.Session) int64
|
||||
// GetSuggestions returns suggestions for user input.
|
||||
GetSuggestions(commandArgs *model.CommandArgs, commands []*model.Command, roleID string) []model.AutocompleteSuggestion
|
||||
GetSuggestions(c *request.Context, commandArgs *model.CommandArgs, commands []*model.Command, roleID string) []model.AutocompleteSuggestion
|
||||
// GetTeamGroupUsers returns the users who are associated to the team via GroupTeams and GroupMembers.
|
||||
GetTeamGroupUsers(teamID string) ([]*model.User, *model.AppError)
|
||||
// GetTeamSchemeChannelRoles Checks if a team has an override scheme and returns the scheme channel role names or default channel role names.
|
||||
@@ -249,7 +250,7 @@ type AppIface interface {
|
||||
MentionsToTeamMembers(message, teamID string) model.UserMentionMap
|
||||
// MoveChannel method is prone to data races if someone joins to channel during the move process. However this
|
||||
// function is only exposed to sysadmins and the possibility of this edge case is relatively small.
|
||||
MoveChannel(team *model.Team, channel *model.Channel, user *model.User) *model.AppError
|
||||
MoveChannel(c *request.Context, team *model.Team, channel *model.Channel, user *model.User) *model.AppError
|
||||
// NewWebConn returns a new WebConn instance.
|
||||
NewWebConn(cfg *WebConnConfig) *WebConn
|
||||
// NewWebHub creates a new Hub.
|
||||
@@ -266,15 +267,15 @@ type AppIface interface {
|
||||
// Perform an HTTP POST request to an integration's action endpoint.
|
||||
// Caller must consume and close returned http.Response as necessary.
|
||||
// For internal requests, requests are routed directly to a plugin ServerHTTP hook
|
||||
DoActionRequest(rawURL string, body []byte) (*http.Response, *model.AppError)
|
||||
DoActionRequest(c *request.Context, rawURL string, body []byte) (*http.Response, *model.AppError)
|
||||
// PermanentDeleteBot permanently deletes a bot and its corresponding user.
|
||||
PermanentDeleteBot(botUserId string) *model.AppError
|
||||
// PopulateWebConnConfig checks if the connection id already exists in the hub,
|
||||
// and if so, accordingly populates the other fields of the webconn.
|
||||
PopulateWebConnConfig(cfg *WebConnConfig, seqVal string) (*WebConnConfig, error)
|
||||
PopulateWebConnConfig(s *model.Session, cfg *WebConnConfig, seqVal string) (*WebConnConfig, error)
|
||||
// PromoteGuestToUser Convert user's roles and all his mermbership's roles from
|
||||
// guest roles to regular user roles.
|
||||
PromoteGuestToUser(user *model.User, requestorId string) *model.AppError
|
||||
PromoteGuestToUser(c *request.Context, user *model.User, requestorId string) *model.AppError
|
||||
// RenameChannel is used to rename the channel Name and the DisplayName fields
|
||||
RenameChannel(channel *model.Channel, newChannelName string, newDisplayName string) (*model.Channel, *model.AppError)
|
||||
// RenameTeam is used to rename the team Name and the DisplayName fields
|
||||
@@ -326,7 +327,7 @@ type AppIface interface {
|
||||
SyncPlugins() *model.AppError
|
||||
// SyncRolesAndMembership updates the SchemeAdmin status and membership of all of the members of the given
|
||||
// syncable.
|
||||
SyncRolesAndMembership(syncableID string, syncableType model.GroupSyncableType, includeRemovedMembers bool)
|
||||
SyncRolesAndMembership(c *request.Context, syncableID string, syncableType model.GroupSyncableType, includeRemovedMembers bool)
|
||||
// SyncSyncableRoles updates the SchemeAdmin field value of the given syncable's members based on the configuration of
|
||||
// the member's group memberships and the configuration of those groups to the syncable. This method should only
|
||||
// be invoked on group-synced (aka group-constrained) syncables.
|
||||
@@ -352,7 +353,7 @@ type AppIface interface {
|
||||
// This to be used for places we check the users password when they are already logged in
|
||||
DoubleCheckPassword(user *model.User, password string) *model.AppError
|
||||
// UpdateBotActive marks a bot as active or inactive, along with its corresponding user.
|
||||
UpdateBotActive(botUserId string, active bool) (*model.Bot, *model.AppError)
|
||||
UpdateBotActive(c *request.Context, botUserId string, active bool) (*model.Bot, *model.AppError)
|
||||
// UpdateBotOwner changes a bot's owner to the given value.
|
||||
UpdateBotOwner(botUserId, newOwnerId string) (*model.Bot, *model.AppError)
|
||||
// UpdateChannel updates a given channel by its Id. It also publishes the CHANNEL_UPDATED event.
|
||||
@@ -372,17 +373,17 @@ type AppIface interface {
|
||||
// UpdateWebConnUserActivity sets the LastUserActivityAt of the hub for the given session.
|
||||
UpdateWebConnUserActivity(session model.Session, activityAt int64)
|
||||
// UploadFile uploads a single file in form of a completely constructed byte array for a channel.
|
||||
UploadFile(data []byte, channelID string, filename string) (*model.FileInfo, *model.AppError)
|
||||
UploadFile(c *request.Context, data []byte, channelID string, filename string) (*model.FileInfo, *model.AppError)
|
||||
// UploadFileX uploads a single file as specified in t. It applies the upload
|
||||
// constraints, executes plugins and image processing logic as needed. It
|
||||
// returns a filled-out FileInfo and an optional error. A plugin may reject the
|
||||
// upload, returning a rejection error. In this case FileInfo would have
|
||||
// contained the last "good" FileInfo before the execution of that plugin.
|
||||
UploadFileX(channelID, name string, input io.Reader, opts ...func(*UploadFileTask)) (*model.FileInfo, *model.AppError)
|
||||
UploadFileX(c *request.Context, channelID, name string, input io.Reader, opts ...func(*UploadFileTask)) (*model.FileInfo, *model.AppError)
|
||||
// Uploads some files to the given team and channel as the given user. files and filenames should have
|
||||
// the same length. clientIds should either not be provided or have the same length as files and filenames.
|
||||
// The provided files should be closed by the caller so that they are not leaked.
|
||||
UploadFiles(teamID string, channelID string, userID string, files []io.ReadCloser, filenames []string, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError)
|
||||
UploadFiles(c *request.Context, teamID string, channelID string, userID string, files []io.ReadCloser, filenames []string, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError)
|
||||
// UserIsInAdminRoleGroup returns true at least one of the user's groups are configured to set the members as
|
||||
// admins in the given syncable.
|
||||
UserIsInAdminRoleGroup(userID, syncableID string, syncableType model.GroupSyncableType) (bool, *model.AppError)
|
||||
@@ -390,7 +391,6 @@ type AppIface interface {
|
||||
VerifyPlugin(plugin, signature io.ReadSeeker) *model.AppError
|
||||
//GetUserStatusesByIds used by apiV4
|
||||
GetUserStatusesByIds(userIDs []string) ([]*model.Status, *model.AppError)
|
||||
AcceptLanguage() string
|
||||
AccountMigration() einterfaces.AccountMigrationInterface
|
||||
ActivateMfa(userID, token string) *model.AppError
|
||||
AddChannelsToRetentionPolicy(policyID string, channelIDs []string) *model.AppError
|
||||
@@ -405,22 +405,22 @@ type AppIface interface {
|
||||
AddSessionToCache(session *model.Session)
|
||||
AddStatusCache(status *model.Status)
|
||||
AddStatusCacheSkipClusterSend(status *model.Status)
|
||||
AddTeamMember(teamID, userID string) (*model.TeamMember, *model.AppError)
|
||||
AddTeamMemberByInviteId(inviteId, userID string) (*model.TeamMember, *model.AppError)
|
||||
AddTeamMemberByToken(userID, tokenID string) (*model.TeamMember, *model.AppError)
|
||||
AddTeamMembers(teamID string, userIDs []string, userRequestorId string, graceful bool) ([]*model.TeamMemberWithError, *model.AppError)
|
||||
AddTeamMember(c *request.Context, teamID, userID string) (*model.TeamMember, *model.AppError)
|
||||
AddTeamMemberByInviteId(c *request.Context, inviteId, userID string) (*model.TeamMember, *model.AppError)
|
||||
AddTeamMemberByToken(c *request.Context, userID, tokenID string) (*model.TeamMember, *model.AppError)
|
||||
AddTeamMembers(c *request.Context, teamID string, userIDs []string, userRequestorId string, graceful bool) ([]*model.TeamMemberWithError, *model.AppError)
|
||||
AddTeamsToRetentionPolicy(policyID string, teamIDs []string) *model.AppError
|
||||
AddUserToTeam(teamID string, userID string, userRequestorId string) (*model.Team, *model.TeamMember, *model.AppError)
|
||||
AddUserToTeamByInviteId(inviteId string, userID string) (*model.Team, *model.TeamMember, *model.AppError)
|
||||
AddUserToTeamByTeamId(teamID string, user *model.User) *model.AppError
|
||||
AddUserToTeamByToken(userID string, tokenID string) (*model.Team, *model.TeamMember, *model.AppError)
|
||||
AddUserToTeam(c *request.Context, teamID string, userID string, userRequestorId string) (*model.Team, *model.TeamMember, *model.AppError)
|
||||
AddUserToTeamByInviteId(c *request.Context, inviteId string, userID string) (*model.Team, *model.TeamMember, *model.AppError)
|
||||
AddUserToTeamByTeamId(c *request.Context, teamID string, user *model.User) *model.AppError
|
||||
AddUserToTeamByToken(c *request.Context, userID string, tokenID string) (*model.Team, *model.TeamMember, *model.AppError)
|
||||
AdjustImage(file io.Reader) (*bytes.Buffer, *model.AppError)
|
||||
AllowOAuthAppAccessToUser(userID string, authRequest *model.AuthorizeRequest) (string, *model.AppError)
|
||||
AppendFile(fr io.Reader, path string) (int64, *model.AppError)
|
||||
AsymmetricSigningKey() *ecdsa.PrivateKey
|
||||
AttachDeviceId(sessionID string, deviceID string, expiresAt int64) *model.AppError
|
||||
AttachSessionCookies(w http.ResponseWriter, r *http.Request)
|
||||
AuthenticateUserForLogin(id, loginId, password, mfaToken, cwsToken string, ldapOnly bool) (user *model.User, err *model.AppError)
|
||||
AttachSessionCookies(c *request.Context, w http.ResponseWriter, r *http.Request)
|
||||
AuthenticateUserForLogin(c *request.Context, id, loginId, password, mfaToken, cwsToken string, ldapOnly bool) (user *model.User, err *model.AppError)
|
||||
AuthorizeOAuthUser(w http.ResponseWriter, r *http.Request, service, code, state, redirectUri string) (io.ReadCloser, string, map[string]string, *model.User, *model.AppError)
|
||||
AutocompleteChannels(teamID string, term string) (*model.ChannelList, *model.AppError)
|
||||
AutocompleteChannelsForSearch(teamID string, userID string, term string) (*model.ChannelList, *model.AppError)
|
||||
@@ -431,11 +431,11 @@ type AppIface interface {
|
||||
BuildPushNotificationMessage(contentsConfig string, post *model.Post, user *model.User, channel *model.Channel, channelName string, senderName string, explicitMention bool, channelWideMention bool, replyToThreadType string) (*model.PushNotification, *model.AppError)
|
||||
BuildSamlMetadataObject(idpMetadata []byte) (*model.SamlMetadataResponse, *model.AppError)
|
||||
BulkExport(writer io.Writer, outPath string, opts BulkExportOpts) *model.AppError
|
||||
BulkImport(fileReader io.Reader, dryRun bool, workers int) (*model.AppError, int)
|
||||
BulkImportWithPath(fileReader io.Reader, dryRun bool, workers int, importPath string) (*model.AppError, int)
|
||||
BulkImport(c *request.Context, fileReader io.Reader, dryRun bool, workers int) (*model.AppError, int)
|
||||
BulkImportWithPath(c *request.Context, fileReader io.Reader, dryRun bool, workers int, importPath string) (*model.AppError, int)
|
||||
CancelJob(jobId string) *model.AppError
|
||||
ChannelMembersToRemove(teamID *string) ([]*model.ChannelMember, *model.AppError)
|
||||
CheckAndSendUserLimitWarningEmails() *model.AppError
|
||||
CheckAndSendUserLimitWarningEmails(c *request.Context) *model.AppError
|
||||
CheckCanInviteToSharedChannel(channelId string) error
|
||||
CheckForClientSideCert(r *http.Request) (string, string, string)
|
||||
CheckMandatoryS3Fields(settings *model.FileSettings) *model.AppError
|
||||
@@ -459,14 +459,13 @@ type AppIface interface {
|
||||
Cluster() einterfaces.ClusterInterface
|
||||
CompareAndDeletePluginKey(pluginID string, key string, oldValue []byte) (bool, *model.AppError)
|
||||
CompareAndSetPluginKey(pluginID string, key string, oldValue, newValue []byte) (bool, *model.AppError)
|
||||
CompleteOAuth(service string, body io.ReadCloser, teamID string, props map[string]string, tokenUser *model.User) (*model.User, *model.AppError)
|
||||
CompleteOAuth(c *request.Context, service string, body io.ReadCloser, teamID string, props map[string]string, tokenUser *model.User) (*model.User, *model.AppError)
|
||||
CompleteSwitchWithOAuth(service string, userData io.Reader, email string, tokenUser *model.User) (*model.User, *model.AppError)
|
||||
Compliance() einterfaces.ComplianceInterface
|
||||
Config() *model.Config
|
||||
Context() context.Context
|
||||
CopyFileInfos(userID string, fileIDs []string) ([]string, *model.AppError)
|
||||
CreateChannel(channel *model.Channel, addMember bool) (*model.Channel, *model.AppError)
|
||||
CreateChannelWithUser(channel *model.Channel, userID string) (*model.Channel, *model.AppError)
|
||||
CreateChannel(c *request.Context, channel *model.Channel, addMember bool) (*model.Channel, *model.AppError)
|
||||
CreateChannelWithUser(c *request.Context, channel *model.Channel, userID string) (*model.Channel, *model.AppError)
|
||||
CreateCommand(cmd *model.Command) (*model.Command, *model.AppError)
|
||||
CreateCommandWebhook(commandID string, args *model.CommandArgs) (*model.CommandWebhook, *model.AppError)
|
||||
CreateEmoji(sessionUserId string, emoji *model.Emoji, multiPartImageData *multipart.Form) (*model.Emoji, *model.AppError)
|
||||
@@ -476,37 +475,37 @@ type AppIface interface {
|
||||
CreateJob(job *model.Job) (*model.Job, *model.AppError)
|
||||
CreateOAuthApp(app *model.OAuthApp) (*model.OAuthApp, *model.AppError)
|
||||
CreateOAuthStateToken(extra string) (*model.Token, *model.AppError)
|
||||
CreateOAuthUser(service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError)
|
||||
CreateOAuthUser(c *request.Context, service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError)
|
||||
CreateOutgoingWebhook(hook *model.OutgoingWebhook) (*model.OutgoingWebhook, *model.AppError)
|
||||
CreatePasswordRecoveryToken(userID, email string) (*model.Token, *model.AppError)
|
||||
CreatePost(post *model.Post, channel *model.Channel, triggerWebhooks, setOnline bool) (savedPost *model.Post, err *model.AppError)
|
||||
CreatePostAsUser(post *model.Post, currentSessionId string, setOnline bool) (*model.Post, *model.AppError)
|
||||
CreatePostMissingChannel(post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError)
|
||||
CreatePost(c *request.Context, post *model.Post, channel *model.Channel, triggerWebhooks, setOnline bool) (savedPost *model.Post, err *model.AppError)
|
||||
CreatePostAsUser(c *request.Context, post *model.Post, currentSessionId string, setOnline bool) (*model.Post, *model.AppError)
|
||||
CreatePostMissingChannel(c *request.Context, post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError)
|
||||
CreateRetentionPolicy(policy *model.RetentionPolicyWithTeamAndChannelIDs) (*model.RetentionPolicyWithTeamAndChannelCounts, *model.AppError)
|
||||
CreateRole(role *model.Role) (*model.Role, *model.AppError)
|
||||
CreateScheme(scheme *model.Scheme) (*model.Scheme, *model.AppError)
|
||||
CreateSession(session *model.Session) (*model.Session, *model.AppError)
|
||||
CreateSidebarCategory(userID, teamID string, newCategory *model.SidebarCategoryWithChannels) (*model.SidebarCategoryWithChannels, *model.AppError)
|
||||
CreateTeam(team *model.Team) (*model.Team, *model.AppError)
|
||||
CreateTeamWithUser(team *model.Team, userID string) (*model.Team, *model.AppError)
|
||||
CreateTeam(c *request.Context, team *model.Team) (*model.Team, *model.AppError)
|
||||
CreateTeamWithUser(c *request.Context, team *model.Team, userID string) (*model.Team, *model.AppError)
|
||||
CreateTermsOfService(text, userID string) (*model.TermsOfService, *model.AppError)
|
||||
CreateUploadSession(us *model.UploadSession) (*model.UploadSession, *model.AppError)
|
||||
CreateUserAccessToken(token *model.UserAccessToken) (*model.UserAccessToken, *model.AppError)
|
||||
CreateUserAsAdmin(user *model.User, redirect string) (*model.User, *model.AppError)
|
||||
CreateUserFromSignup(user *model.User, redirect string) (*model.User, *model.AppError)
|
||||
CreateUserWithInviteId(user *model.User, inviteId, redirect string) (*model.User, *model.AppError)
|
||||
CreateUserWithToken(user *model.User, token *model.Token) (*model.User, *model.AppError)
|
||||
CreateWebhookPost(userID string, channel *model.Channel, text, overrideUsername, overrideIconURL, overrideIconEmoji string, props model.StringInterface, postType string, postRootId string) (*model.Post, *model.AppError)
|
||||
CreateUserAsAdmin(c *request.Context, user *model.User, redirect string) (*model.User, *model.AppError)
|
||||
CreateUserFromSignup(c *request.Context, user *model.User, redirect string) (*model.User, *model.AppError)
|
||||
CreateUserWithInviteId(c *request.Context, user *model.User, inviteId, redirect string) (*model.User, *model.AppError)
|
||||
CreateUserWithToken(c *request.Context, user *model.User, token *model.Token) (*model.User, *model.AppError)
|
||||
CreateWebhookPost(c *request.Context, userID string, channel *model.Channel, text, overrideUsername, overrideIconURL, overrideIconEmoji string, props model.StringInterface, postType string, postRootId string) (*model.Post, *model.AppError)
|
||||
DBHealthCheckDelete() error
|
||||
DBHealthCheckWrite() error
|
||||
DataRetention() einterfaces.DataRetentionInterface
|
||||
DeactivateGuests() *model.AppError
|
||||
DeactivateGuests(c *request.Context) *model.AppError
|
||||
DeactivateMfa(userID string) *model.AppError
|
||||
DeauthorizeOAuthAppForUser(userID, appID string) *model.AppError
|
||||
DeleteAllExpiredPluginKeys() *model.AppError
|
||||
DeleteAllKeysForPlugin(pluginID string) *model.AppError
|
||||
DeleteBrandImage() *model.AppError
|
||||
DeleteChannel(channel *model.Channel, userID string) *model.AppError
|
||||
DeleteChannel(c *request.Context, channel *model.Channel, userID string) *model.AppError
|
||||
DeleteCommand(commandID string) *model.AppError
|
||||
DeleteEmoji(emoji *model.Emoji) *model.AppError
|
||||
DeleteEphemeralPost(userID, postID string)
|
||||
@@ -522,7 +521,7 @@ type AppIface interface {
|
||||
DeletePost(postID, deleteByID string) (*model.Post, *model.AppError)
|
||||
DeletePostFiles(post *model.Post)
|
||||
DeletePreferences(userID string, preferences model.Preferences) *model.AppError
|
||||
DeleteReactionForPost(reaction *model.Reaction) *model.AppError
|
||||
DeleteReactionForPost(c *request.Context, reaction *model.Reaction) *model.AppError
|
||||
DeleteRemoteCluster(remoteClusterId string) (bool, *model.AppError)
|
||||
DeleteRetentionPolicy(policyID string) *model.AppError
|
||||
DeleteScheme(schemeId string) (*model.Scheme, *model.AppError)
|
||||
@@ -536,13 +535,13 @@ type AppIface interface {
|
||||
DoCommandRequest(cmd *model.Command, p url.Values) (*model.Command, *model.CommandResponse, *model.AppError)
|
||||
DoEmojisPermissionsMigration()
|
||||
DoGuestRolesCreationMigration()
|
||||
DoLocalRequest(rawURL string, body []byte) (*http.Response, *model.AppError)
|
||||
DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, deviceID string, isMobile, isOAuthUser, isSaml bool) *model.AppError
|
||||
DoPostAction(postID, actionId, userID, selectedOption string) (string, *model.AppError)
|
||||
DoPostActionWithCookie(postID, actionId, userID, selectedOption string, cookie *model.PostActionCookie) (string, *model.AppError)
|
||||
DoLocalRequest(c *request.Context, rawURL string, body []byte) (*http.Response, *model.AppError)
|
||||
DoLogin(c *request.Context, w http.ResponseWriter, r *http.Request, user *model.User, deviceID string, isMobile, isOAuthUser, isSaml bool) *model.AppError
|
||||
DoPostAction(c *request.Context, postID, actionId, userID, selectedOption string) (string, *model.AppError)
|
||||
DoPostActionWithCookie(c *request.Context, postID, actionId, userID, selectedOption string, cookie *model.PostActionCookie) (string, *model.AppError)
|
||||
DoSystemConsoleRolesCreationMigration()
|
||||
DoUploadFile(now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, *model.AppError)
|
||||
DoUploadFileExpectModification(now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, []byte, *model.AppError)
|
||||
DoUploadFile(c *request.Context, now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, *model.AppError)
|
||||
DoUploadFileExpectModification(c *request.Context, now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, []byte, *model.AppError)
|
||||
DownloadFromURL(downloadURL string) ([]byte, error)
|
||||
EnableUserAccessToken(token *model.UserAccessToken) *model.AppError
|
||||
EnvironmentConfig(filter func(reflect.StructField) bool) map[string]interface{}
|
||||
@@ -671,7 +670,7 @@ type AppIface interface {
|
||||
GetOAuthSignupEndpoint(w http.ResponseWriter, r *http.Request, service, teamID string) (string, *model.AppError)
|
||||
GetOAuthStateToken(token string) (*model.Token, *model.AppError)
|
||||
GetOpenGraphMetadata(requestURL string) *opengraph.OpenGraph
|
||||
GetOrCreateDirectChannel(userID, otherUserID string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError)
|
||||
GetOrCreateDirectChannel(c *request.Context, userID, otherUserID string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError)
|
||||
GetOutgoingWebhook(hookID string) (*model.OutgoingWebhook, *model.AppError)
|
||||
GetOutgoingWebhooksForChannelPageByUser(channelID string, userID string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError)
|
||||
GetOutgoingWebhooksForTeamPage(teamID string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError)
|
||||
@@ -679,7 +678,7 @@ type AppIface interface {
|
||||
GetOutgoingWebhooksPage(page, perPage int) ([]*model.OutgoingWebhook, *model.AppError)
|
||||
GetOutgoingWebhooksPageByUser(userID string, page, perPage int) ([]*model.OutgoingWebhook, *model.AppError)
|
||||
GetPasswordRecoveryToken(token string) (*model.Token, *model.AppError)
|
||||
GetPermalinkPost(postID string, userID string) (*model.PostList, *model.AppError)
|
||||
GetPermalinkPost(c *request.Context, postID string, userID string) (*model.PostList, *model.AppError)
|
||||
GetPinnedPosts(channelID string) (*model.PostList, *model.AppError)
|
||||
GetPluginKey(pluginID string, key string) ([]byte, *model.AppError)
|
||||
GetPlugins() (*model.PluginsResponse, *model.AppError)
|
||||
@@ -743,7 +742,6 @@ type AppIface interface {
|
||||
GetStatus(userID string) (*model.Status, *model.AppError)
|
||||
GetStatusFromCache(userID string) *model.Status
|
||||
GetStatusesByIds(userIDs []string) (map[string]interface{}, *model.AppError)
|
||||
GetT() i18n.TranslateFunc
|
||||
GetTeam(teamID string) (*model.Team, *model.AppError)
|
||||
GetTeamByInviteId(inviteId string) (*model.Team, *model.AppError)
|
||||
GetTeamByName(name string) (*model.Team, *model.AppError)
|
||||
@@ -778,7 +776,7 @@ type AppIface interface {
|
||||
GetUserForLogin(id, loginId string) (*model.User, *model.AppError)
|
||||
GetUserTermsOfService(userID string) (*model.UserTermsOfService, *model.AppError)
|
||||
GetUsers(options *model.UserGetOptions) ([]*model.User, *model.AppError)
|
||||
GetUsersByGroupChannelIds(channelIDs []string, asAdmin bool) (map[string][]*model.User, *model.AppError)
|
||||
GetUsersByGroupChannelIds(c *request.Context, channelIDs []string, asAdmin bool) (map[string][]*model.User, *model.AppError)
|
||||
GetUsersByIds(userIDs []string, options *store.UserGetByIdsOpts) ([]*model.User, *model.AppError)
|
||||
GetUsersByUsernames(usernames []string, asAdmin bool, viewRestrictions *model.ViewUsersRestrictions) ([]*model.User, *model.AppError)
|
||||
GetUsersEtag(restrictionsHash string) string
|
||||
@@ -804,11 +802,11 @@ type AppIface interface {
|
||||
GetWarnMetricsStatus() (map[string]*model.WarnMetricStatus, *model.AppError)
|
||||
HTTPService() httpservice.HTTPService
|
||||
Handle404(w http.ResponseWriter, r *http.Request)
|
||||
HandleCommandResponse(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError)
|
||||
HandleCommandResponsePost(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.Post, *model.AppError)
|
||||
HandleCommandWebhook(hookID string, response *model.CommandResponse) *model.AppError
|
||||
HandleCommandResponse(c *request.Context, command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError)
|
||||
HandleCommandResponsePost(c *request.Context, command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.Post, *model.AppError)
|
||||
HandleCommandWebhook(c *request.Context, hookID string, response *model.CommandResponse) *model.AppError
|
||||
HandleImages(previewPathList []string, thumbnailPathList []string, fileData [][]byte)
|
||||
HandleIncomingWebhook(hookID string, req *model.IncomingWebhookRequest) *model.AppError
|
||||
HandleIncomingWebhook(c *request.Context, hookID string, req *model.IncomingWebhookRequest) *model.AppError
|
||||
HandleMessageExportConfig(cfg *model.Config, appCfg *model.Config)
|
||||
HasPermissionTo(askingUserId string, permission *model.Permission) bool
|
||||
HasPermissionToChannel(askingUserId string, channelID string, permission *model.Permission) bool
|
||||
@@ -821,9 +819,7 @@ type AppIface interface {
|
||||
ImageProxyAdder() func(string) string
|
||||
ImageProxyRemover() (f func(string) string)
|
||||
ImportPermissions(jsonl io.Reader) error
|
||||
InitPlugins(pluginDir, webappPluginDir string)
|
||||
InitPostMetadata()
|
||||
InitServer()
|
||||
InitPlugins(c *request.Context, pluginDir, webappPluginDir string)
|
||||
InstallPluginFromData(data model.PluginEventData)
|
||||
InvalidateAllEmailInvites() *model.AppError
|
||||
InvalidateCacheForUser(userID string)
|
||||
@@ -831,19 +827,18 @@ type AppIface interface {
|
||||
InviteGuestsToChannelsGracefully(teamID string, guestsInvite *model.GuestsInvite, senderId string) ([]*model.EmailInviteWithError, *model.AppError)
|
||||
InviteNewUsersToTeam(emailList []string, teamID, senderId string) *model.AppError
|
||||
InviteNewUsersToTeamGracefully(emailList []string, teamID, senderId string) ([]*model.EmailInviteWithError, *model.AppError)
|
||||
IpAddress() string
|
||||
IsFirstUserAccount() bool
|
||||
IsLeader() bool
|
||||
IsPasswordValid(password string) *model.AppError
|
||||
IsPhase2MigrationCompleted() *model.AppError
|
||||
IsUserAway(lastActivityAt int64) bool
|
||||
IsUserSignUpAllowed() *model.AppError
|
||||
JoinChannel(channel *model.Channel, userID string) *model.AppError
|
||||
JoinDefaultChannels(teamID string, user *model.User, shouldBeAdmin bool, userRequestorId string) *model.AppError
|
||||
JoinUserToTeam(team *model.Team, user *model.User, userRequestorId string) (*model.TeamMember, *model.AppError)
|
||||
JoinChannel(c *request.Context, channel *model.Channel, userID string) *model.AppError
|
||||
JoinDefaultChannels(c *request.Context, teamID string, user *model.User, shouldBeAdmin bool, userRequestorId string) *model.AppError
|
||||
JoinUserToTeam(c *request.Context, team *model.Team, user *model.User, userRequestorId string) (*model.TeamMember, *model.AppError)
|
||||
Ldap() einterfaces.LdapInterface
|
||||
LeaveChannel(channelID string, userID string) *model.AppError
|
||||
LeaveTeam(team *model.Team, user *model.User, requestorId string) *model.AppError
|
||||
LeaveChannel(c *request.Context, channelID string, userID string) *model.AppError
|
||||
LeaveTeam(c *request.Context, team *model.Team, user *model.User, requestorId string) *model.AppError
|
||||
LimitedClientConfig() map[string]string
|
||||
ListAllCommands(teamID string, T i18n.TranslateFunc) ([]*model.Command, *model.AppError)
|
||||
ListDirectory(path string) ([]string, *model.AppError)
|
||||
@@ -852,8 +847,8 @@ type AppIface interface {
|
||||
ListPluginKeys(pluginID string, page, perPage int) ([]string, *model.AppError)
|
||||
ListTeamCommands(teamID string) ([]*model.Command, *model.AppError)
|
||||
Log() *mlog.Logger
|
||||
LoginByOAuth(service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError)
|
||||
MakePermissionError(permissions []*model.Permission) *model.AppError
|
||||
LoginByOAuth(c *request.Context, service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError)
|
||||
MakePermissionError(s *model.Session, permissions []*model.Permission) *model.AppError
|
||||
MarkChannelsAsViewed(channelIDs []string, userID string, currentSessionId string) (map[string]int64, *model.AppError)
|
||||
MaxPostSize() int
|
||||
MessageExport() einterfaces.MessageExportInterface
|
||||
@@ -862,34 +857,32 @@ type AppIface interface {
|
||||
MoveCommand(team *model.Team, command *model.Command) *model.AppError
|
||||
MoveFile(oldPath, newPath string) *model.AppError
|
||||
NewClusterDiscoveryService() *ClusterDiscoveryService
|
||||
NewPluginAPI(manifest *model.Manifest) plugin.API
|
||||
NewPluginAPI(c *request.Context, manifest *model.Manifest) plugin.API
|
||||
Notification() einterfaces.NotificationInterface
|
||||
NotificationsLog() *mlog.Logger
|
||||
NotifyAndSetWarnMetricAck(warnMetricId string, sender *model.User, forceAck bool, isBot bool) *model.AppError
|
||||
NotifySharedChannelUserUpdate(user *model.User)
|
||||
OpenInteractiveDialog(request model.OpenDialogRequest) *model.AppError
|
||||
OriginChecker() func(*http.Request) bool
|
||||
PatchChannel(channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError)
|
||||
PatchPost(postID string, patch *model.PostPatch) (*model.Post, *model.AppError)
|
||||
PatchChannel(c *request.Context, channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError)
|
||||
PatchPost(c *request.Context, postID string, patch *model.PostPatch) (*model.Post, *model.AppError)
|
||||
PatchRetentionPolicy(patch *model.RetentionPolicyWithTeamAndChannelIDs) (*model.RetentionPolicyWithTeamAndChannelCounts, *model.AppError)
|
||||
PatchRole(role *model.Role, patch *model.RolePatch) (*model.Role, *model.AppError)
|
||||
PatchScheme(scheme *model.Scheme, patch *model.SchemePatch) (*model.Scheme, *model.AppError)
|
||||
PatchTeam(teamID string, patch *model.TeamPatch) (*model.Team, *model.AppError)
|
||||
PatchUser(userID string, patch *model.UserPatch, asAdmin bool) (*model.User, *model.AppError)
|
||||
Path() string
|
||||
PermanentDeleteAllUsers() *model.AppError
|
||||
PermanentDeleteAllUsers(c *request.Context) *model.AppError
|
||||
PermanentDeleteChannel(channel *model.Channel) *model.AppError
|
||||
PermanentDeleteTeam(team *model.Team) *model.AppError
|
||||
PermanentDeleteTeamId(teamID string) *model.AppError
|
||||
PermanentDeleteUser(user *model.User) *model.AppError
|
||||
PermanentDeleteUser(c *request.Context, user *model.User) *model.AppError
|
||||
PluginCommandsForTeam(teamID string) []*model.Command
|
||||
PluginContext() *plugin.Context
|
||||
PostActionCookieSecret() []byte
|
||||
PostAddToChannelMessage(user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError
|
||||
PostAddToChannelMessage(c *request.Context, user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError
|
||||
PostPatchWithProxyRemovedFromImageURLs(patch *model.PostPatch) *model.PostPatch
|
||||
PostUpdateChannelDisplayNameMessage(userID string, channel *model.Channel, oldChannelDisplayName, newChannelDisplayName string) *model.AppError
|
||||
PostUpdateChannelHeaderMessage(userID string, channel *model.Channel, oldChannelHeader, newChannelHeader string) *model.AppError
|
||||
PostUpdateChannelPurposeMessage(userID string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError
|
||||
PostUpdateChannelDisplayNameMessage(c *request.Context, userID string, channel *model.Channel, oldChannelDisplayName, newChannelDisplayName string) *model.AppError
|
||||
PostUpdateChannelHeaderMessage(c *request.Context, userID string, channel *model.Channel, oldChannelHeader, newChannelHeader string) *model.AppError
|
||||
PostUpdateChannelPurposeMessage(c *request.Context, userID string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError
|
||||
PostWithProxyAddedToImageURLs(post *model.Post) *model.Post
|
||||
PostWithProxyRemovedFromImageURLs(post *model.Post) *model.Post
|
||||
PreparePostForClient(originalPost *model.Post, isNewPost bool, isEditPost bool) *model.Post
|
||||
@@ -922,17 +915,16 @@ type AppIface interface {
|
||||
RemoveSamlPrivateCertificate() *model.AppError
|
||||
RemoveSamlPublicCertificate() *model.AppError
|
||||
RemoveTeamIcon(teamID string) *model.AppError
|
||||
RemoveTeamMemberFromTeam(teamMember *model.TeamMember, requestorId string) *model.AppError
|
||||
RemoveTeamMemberFromTeam(c *request.Context, teamMember *model.TeamMember, requestorId string) *model.AppError
|
||||
RemoveTeamsFromRetentionPolicy(policyID string, teamIDs []string) *model.AppError
|
||||
RemoveUserFromChannel(userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError
|
||||
RemoveUserFromTeam(teamID string, userID string, requestorId string) *model.AppError
|
||||
RemoveUsersFromChannelNotMemberOfTeam(remover *model.User, channel *model.Channel, team *model.Team) *model.AppError
|
||||
RequestId() string
|
||||
RequestLicenseAndAckWarnMetric(warnMetricId string, isBot bool) *model.AppError
|
||||
RemoveUserFromChannel(c *request.Context, userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError
|
||||
RemoveUserFromTeam(c *request.Context, teamID string, userID string, requestorId string) *model.AppError
|
||||
RemoveUsersFromChannelNotMemberOfTeam(c *request.Context, remover *model.User, channel *model.Channel, team *model.Team) *model.AppError
|
||||
RequestLicenseAndAckWarnMetric(c *request.Context, warnMetricId string, isBot bool) *model.AppError
|
||||
ResetPasswordFromToken(userSuppliedTokenString, newPassword string) *model.AppError
|
||||
ResetPermissionsSystem() *model.AppError
|
||||
ResetSamlAuthDataToEmail(includeDeleted bool, dryRun bool, userIDs []string) (numAffected int, appErr *model.AppError)
|
||||
RestoreChannel(channel *model.Channel, userID string) (*model.Channel, *model.AppError)
|
||||
RestoreChannel(c *request.Context, channel *model.Channel, userID string) (*model.Channel, *model.AppError)
|
||||
RestoreTeam(teamID string) *model.AppError
|
||||
RestrictUsersGetByPermissions(userID string, options *model.UserGetOptions) (*model.UserGetOptions, *model.AppError)
|
||||
RestrictUsersSearchByPermissions(userID string, options *model.UserSearchOptions) (*model.UserSearchOptions, *model.AppError)
|
||||
@@ -950,7 +942,7 @@ type AppIface interface {
|
||||
SaveAndBroadcastStatus(status *model.Status)
|
||||
SaveBrandImage(imageData *multipart.FileHeader) *model.AppError
|
||||
SaveComplianceReport(job *model.Compliance) (*model.Compliance, *model.AppError)
|
||||
SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *model.AppError)
|
||||
SaveReactionForPost(c *request.Context, reaction *model.Reaction) (*model.Reaction, *model.AppError)
|
||||
SaveSharedChannel(sc *model.SharedChannel) (*model.SharedChannel, error)
|
||||
SaveSharedChannelRemote(remote *model.SharedChannelRemote) (*model.SharedChannelRemote, error)
|
||||
SaveUserTermsOfService(userID, termsOfServiceId string, accepted bool) *model.AppError
|
||||
@@ -961,10 +953,10 @@ type AppIface interface {
|
||||
SearchChannelsUserNotIn(teamID string, userID string, term string) (*model.ChannelList, *model.AppError)
|
||||
SearchEmoji(name string, prefixOnly bool, limit int) ([]*model.Emoji, *model.AppError)
|
||||
SearchEngine() *searchengine.Broker
|
||||
SearchFilesInTeamForUser(terms string, userId string, teamId string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int) (*model.FileInfoList, *model.AppError)
|
||||
SearchFilesInTeamForUser(c *request.Context, terms string, userId string, teamId string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int) (*model.FileInfoList, *model.AppError)
|
||||
SearchGroupChannels(userID, term string) (*model.ChannelList, *model.AppError)
|
||||
SearchPostsInTeam(teamID string, paramsList []*model.SearchParams) (*model.PostList, *model.AppError)
|
||||
SearchPostsInTeamForUser(terms string, userID string, teamID string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int) (*model.PostSearchResults, *model.AppError)
|
||||
SearchPostsInTeamForUser(c *request.Context, terms string, userID string, teamID string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int) (*model.PostSearchResults, *model.AppError)
|
||||
SearchPrivateTeams(searchOpts *model.TeamSearch) ([]*model.Team, *model.AppError)
|
||||
SearchPublicTeams(searchOpts *model.TeamSearch) ([]*model.Team, *model.AppError)
|
||||
SearchUserAccessTokens(term string) ([]*model.UserAccessToken, *model.AppError)
|
||||
@@ -976,8 +968,8 @@ type AppIface interface {
|
||||
SearchUsersNotInTeam(notInTeamId string, term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError)
|
||||
SearchUsersWithoutTeam(term string, options *model.UserSearchOptions) ([]*model.User, *model.AppError)
|
||||
SendAckToPushProxy(ack *model.PushNotificationAck) error
|
||||
SendAutoResponse(channel *model.Channel, receiver *model.User, post *model.Post) (bool, *model.AppError)
|
||||
SendAutoResponseIfNecessary(channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError)
|
||||
SendAutoResponse(c *request.Context, channel *model.Channel, receiver *model.User, post *model.Post) (bool, *model.AppError)
|
||||
SendAutoResponseIfNecessary(c *request.Context, channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError)
|
||||
SendCloudTrialEndWarningEmail(trialEndDate, siteURL string) *model.AppError
|
||||
SendCloudTrialEndedEmail() *model.AppError
|
||||
SendEmailVerification(user *model.User, newEmail, redirect string) *model.AppError
|
||||
@@ -987,7 +979,6 @@ type AppIface interface {
|
||||
SendPaymentFailedEmail(failedPayment *model.FailedPayment) *model.AppError
|
||||
ServeInterPluginRequest(w http.ResponseWriter, r *http.Request, sourcePluginId, destinationPluginId string)
|
||||
ServePluginRequest(w http.ResponseWriter, r *http.Request)
|
||||
Session() *model.Session
|
||||
SessionCacheLength() int
|
||||
SessionHasPermissionTo(session model.Session, permission *model.Permission) bool
|
||||
SessionHasPermissionToAny(session model.Session, permissions []*model.Permission) bool
|
||||
@@ -999,14 +990,10 @@ type AppIface interface {
|
||||
SessionHasPermissionToTeam(session model.Session, teamID string, permission *model.Permission) bool
|
||||
SessionHasPermissionToUser(session model.Session, userID string) bool
|
||||
SessionHasPermissionToUserOrBot(session model.Session, userID string) bool
|
||||
SetAcceptLanguage(s string)
|
||||
SetActiveChannel(userID string, channelID string) *model.AppError
|
||||
SetAutoResponderStatus(user *model.User, oldNotifyProps model.StringMap)
|
||||
SetContext(c context.Context)
|
||||
SetCustomStatus(userID string, cs *model.CustomStatus) *model.AppError
|
||||
SetDefaultProfileImage(user *model.User) *model.AppError
|
||||
SetIpAddress(s string)
|
||||
SetPath(s string)
|
||||
SetPhase2PermissionsMigrationStatus(isComplete bool) error
|
||||
SetPluginKey(pluginID string, key string, value []byte) *model.AppError
|
||||
SetPluginKeyWithExpiry(pluginID string, key string, value []byte, expireInSeconds int64) *model.AppError
|
||||
@@ -1016,31 +1003,26 @@ type AppIface interface {
|
||||
SetProfileImageFromFile(userID string, file io.Reader) *model.AppError
|
||||
SetProfileImageFromMultiPartFile(userID string, file multipart.File) *model.AppError
|
||||
SetRemoteClusterLastPingAt(remoteClusterId string) *model.AppError
|
||||
SetRequestId(s string)
|
||||
SetSamlIdpCertificateFromMetadata(data []byte) *model.AppError
|
||||
SetSearchEngine(se *searchengine.Broker)
|
||||
SetServer(srv *Server)
|
||||
SetSession(s *model.Session)
|
||||
SetStatusAwayIfNeeded(userID string, manual bool)
|
||||
SetStatusDoNotDisturb(userID string)
|
||||
SetStatusOffline(userID string, manual bool)
|
||||
SetStatusOnline(userID string, manual bool)
|
||||
SetStatusOutOfOffice(userID string)
|
||||
SetT(t i18n.TranslateFunc)
|
||||
SetTeamIcon(teamID string, imageData *multipart.FileHeader) *model.AppError
|
||||
SetTeamIconFromFile(team *model.Team, file io.Reader) *model.AppError
|
||||
SetTeamIconFromMultiPartFile(teamID string, file multipart.File) *model.AppError
|
||||
SetUserAgent(s string)
|
||||
SlackImport(fileData multipart.File, fileSize int64, teamID string) (*model.AppError, *bytes.Buffer)
|
||||
SlackImport(c *request.Context, fileData multipart.File, fileSize int64, teamID string) (*model.AppError, *bytes.Buffer)
|
||||
SoftDeleteTeam(teamID string) *model.AppError
|
||||
Srv() *Server
|
||||
SubmitInteractiveDialog(request model.SubmitDialogRequest) (*model.SubmitDialogResponse, *model.AppError)
|
||||
SubmitInteractiveDialog(c *request.Context, request model.SubmitDialogRequest) (*model.SubmitDialogResponse, *model.AppError)
|
||||
SwitchEmailToLdap(email, password, code, ldapLoginId, ldapPassword string) (string, *model.AppError)
|
||||
SwitchEmailToOAuth(w http.ResponseWriter, r *http.Request, email, password, code, service string) (string, *model.AppError)
|
||||
SwitchLdapToEmail(ldapPassword, code, email, newPassword string) (string, *model.AppError)
|
||||
SwitchOAuthToEmail(email, password, requesterId string) (string, *model.AppError)
|
||||
SyncPluginsActiveState()
|
||||
T(translationID string, args ...interface{}) string
|
||||
TeamMembersToRemove(teamID *string) ([]*model.TeamMember, *model.AppError)
|
||||
TelemetryId() string
|
||||
TestElasticsearch(cfg *model.Config) *model.AppError
|
||||
@@ -1052,15 +1034,15 @@ type AppIface interface {
|
||||
Timezones() *timezones.Timezones
|
||||
ToggleMuteChannel(channelID, userID string) (*model.ChannelMember, *model.AppError)
|
||||
TotalWebsocketConnections() int
|
||||
TriggerWebhook(payload *model.OutgoingWebhookPayload, hook *model.OutgoingWebhook, post *model.Post, channel *model.Channel)
|
||||
TriggerWebhook(c *request.Context, payload *model.OutgoingWebhookPayload, hook *model.OutgoingWebhook, post *model.Post, channel *model.Channel)
|
||||
UnregisterPluginCommand(pluginID, teamID, trigger string)
|
||||
UnregisterPluginCommands(pluginID string)
|
||||
UpdateActive(user *model.User, active bool) (*model.User, *model.AppError)
|
||||
UpdateActive(c *request.Context, user *model.User, active bool) (*model.User, *model.AppError)
|
||||
UpdateChannelLastViewedAt(channelIDs []string, userID string) *model.AppError
|
||||
UpdateChannelMemberNotifyProps(data map[string]string, channelID string, userID string) (*model.ChannelMember, *model.AppError)
|
||||
UpdateChannelMemberRoles(channelID string, userID string, newRoles string) (*model.ChannelMember, *model.AppError)
|
||||
UpdateChannelMemberSchemeRoles(channelID string, userID string, isSchemeGuest bool, isSchemeUser bool, isSchemeAdmin bool) (*model.ChannelMember, *model.AppError)
|
||||
UpdateChannelPrivacy(oldChannel *model.Channel, user *model.User) (*model.Channel, *model.AppError)
|
||||
UpdateChannelPrivacy(c *request.Context, oldChannel *model.Channel, user *model.User) (*model.Channel, *model.AppError)
|
||||
UpdateCommand(oldCmd, updatedCmd *model.Command) (*model.Command, *model.AppError)
|
||||
UpdateConfig(f func(*model.Config))
|
||||
UpdateEphemeralPost(userID string, post *model.Post) *model.Post
|
||||
@@ -1080,7 +1062,7 @@ type AppIface interface {
|
||||
UpdatePasswordAsUser(userID, currentPassword, newPassword string) *model.AppError
|
||||
UpdatePasswordByUserIdSendEmail(userID, newPassword, method string) *model.AppError
|
||||
UpdatePasswordSendEmail(user *model.User, newPassword, method string) *model.AppError
|
||||
UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model.AppError)
|
||||
UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) (*model.Post, *model.AppError)
|
||||
UpdatePreferences(userID string, preferences model.Preferences) *model.AppError
|
||||
UpdateRemoteCluster(rc *model.RemoteCluster) (*model.RemoteCluster, *model.AppError)
|
||||
UpdateRemoteClusterTopics(remoteClusterId string, topics string) (*model.RemoteCluster, *model.AppError)
|
||||
@@ -1100,18 +1082,17 @@ type AppIface interface {
|
||||
UpdateThreadReadForUser(userID, teamID, threadID string, timestamp int64) (*model.ThreadResponse, *model.AppError)
|
||||
UpdateThreadsReadForUser(userID, teamID string) *model.AppError
|
||||
UpdateUser(user *model.User, sendNotifications bool) (*model.User, *model.AppError)
|
||||
UpdateUserActive(userID string, active bool) *model.AppError
|
||||
UpdateUserActive(c *request.Context, userID string, active bool) *model.AppError
|
||||
UpdateUserAsUser(user *model.User, asAdmin bool) (*model.User, *model.AppError)
|
||||
UpdateUserAuth(userID string, userAuth *model.UserAuth) (*model.UserAuth, *model.AppError)
|
||||
UpdateUserNotifyProps(userID string, props map[string]string, sendNotifications bool) (*model.User, *model.AppError)
|
||||
UpdateUserRoles(userID string, newRoles string, sendWebSocketEvent bool) (*model.User, *model.AppError)
|
||||
UpdateUserRolesWithUser(user *model.User, newRoles string, sendWebSocketEvent bool) (*model.User, *model.AppError)
|
||||
UploadData(us *model.UploadSession, rd io.Reader) (*model.FileInfo, *model.AppError)
|
||||
UploadData(c *request.Context, us *model.UploadSession, rd io.Reader) (*model.FileInfo, *model.AppError)
|
||||
UploadEmojiImage(id string, imageData *multipart.FileHeader) *model.AppError
|
||||
UploadMultipartFiles(teamID string, channelID string, userID string, fileHeaders []*multipart.FileHeader, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError)
|
||||
UploadMultipartFiles(c *request.Context, teamID string, channelID string, userID string, fileHeaders []*multipart.FileHeader, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError)
|
||||
UpsertGroupMember(groupID string, userID string) (*model.GroupMember, *model.AppError)
|
||||
UpsertGroupSyncable(groupSyncable *model.GroupSyncable) (*model.GroupSyncable, *model.AppError)
|
||||
UserAgent() string
|
||||
UserCanSeeOtherUser(userID string, otherUserId string) (bool, *model.AppError)
|
||||
VerifyEmailFromToken(userSuppliedTokenString string) *model.AppError
|
||||
VerifyUserEmail(userID, email string) *model.AppError
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mfa"
|
||||
"github.com/mattermost/mattermost-server/v5/utils"
|
||||
@@ -126,13 +127,13 @@ func (a *App) checkUserPassword(user *model.User, password string) *model.AppErr
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) checkLdapUserPasswordAndAllCriteria(ldapId *string, password string, mfaToken string) (*model.User, *model.AppError) {
|
||||
func (a *App) checkLdapUserPasswordAndAllCriteria(c *request.Context, ldapId *string, password string, mfaToken string) (*model.User, *model.AppError) {
|
||||
if a.Ldap() == nil || ldapId == nil {
|
||||
err := model.NewAppError("doLdapAuthentication", "api.user.login_ldap.not_available.app_error", nil, "", http.StatusNotImplemented)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ldapUser, err := a.Ldap().DoLogin(*ldapId, password)
|
||||
ldapUser, err := a.Ldap().DoLogin(c, *ldapId, password)
|
||||
if err != nil {
|
||||
err.StatusCode = http.StatusUnauthorized
|
||||
return nil, err
|
||||
@@ -229,7 +230,7 @@ func checkUserNotBot(user *model.User) *model.AppError {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) authenticateUser(user *model.User, password, mfaToken string) (*model.User, *model.AppError) {
|
||||
func (a *App) authenticateUser(c *request.Context, user *model.User, password, mfaToken string) (*model.User, *model.AppError) {
|
||||
license := a.Srv().License()
|
||||
ldapAvailable := *a.Config().LdapSettings.Enable && a.Ldap() != nil && license != nil && *license.Features.LDAP
|
||||
|
||||
@@ -239,7 +240,7 @@ func (a *App) authenticateUser(user *model.User, password, mfaToken string) (*mo
|
||||
return user, err
|
||||
}
|
||||
|
||||
ldapUser, err := a.checkLdapUserPasswordAndAllCriteria(user.AuthData, password, mfaToken)
|
||||
ldapUser, err := a.checkLdapUserPasswordAndAllCriteria(c, user.AuthData, password, mfaToken)
|
||||
if err != nil {
|
||||
err.StatusCode = http.StatusUnauthorized
|
||||
return user, err
|
||||
|
||||
@@ -12,13 +12,13 @@ import (
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
)
|
||||
|
||||
func (a *App) MakePermissionError(permissions []*model.Permission) *model.AppError {
|
||||
func (a *App) MakePermissionError(s *model.Session, permissions []*model.Permission) *model.AppError {
|
||||
permissionsStr := "permission="
|
||||
for _, permission := range permissions {
|
||||
permissionsStr += permission.Id
|
||||
permissionsStr += ","
|
||||
}
|
||||
return model.NewAppError("Permissions", "api.context.permissions.app_error", nil, "userId="+a.Session().UserId+", "+permissionsStr, http.StatusForbidden)
|
||||
return model.NewAppError("Permissions", "api.context.permissions.app_error", nil, "userId="+s.UserId+", "+permissionsStr, http.StatusForbidden)
|
||||
}
|
||||
|
||||
func (a *App) SessionHasPermissionTo(session model.Session, permission *model.Permission) bool {
|
||||
@@ -263,7 +263,7 @@ func (a *App) SessionHasPermissionToManageBot(session model.Session, botUserId s
|
||||
// the bot doesn't exist at all.
|
||||
return model.MakeBotNotFoundError(botUserId)
|
||||
}
|
||||
return a.MakePermissionError([]*model.Permission{model.PERMISSION_MANAGE_BOTS})
|
||||
return a.MakePermissionError(&session, []*model.Permission{model.PERMISSION_MANAGE_BOTS})
|
||||
}
|
||||
} else {
|
||||
if !a.SessionHasPermissionTo(session, model.PERMISSION_MANAGE_OTHERS_BOTS) {
|
||||
@@ -272,7 +272,7 @@ func (a *App) SessionHasPermissionToManageBot(session model.Session, botUserId s
|
||||
// pretend as if the bot doesn't exist at all.
|
||||
return model.MakeBotNotFoundError(botUserId)
|
||||
}
|
||||
return a.MakePermissionError([]*model.Permission{model.PERMISSION_MANAGE_OTHERS_BOTS})
|
||||
return a.MakePermissionError(&session, []*model.Permission{model.PERMISSION_MANAGE_OTHERS_BOTS})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
@@ -20,7 +21,7 @@ func (a *App) checkIfRespondedToday(createdAt int64, channelId, userId string) (
|
||||
)
|
||||
}
|
||||
|
||||
func (a *App) SendAutoResponseIfNecessary(channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError) {
|
||||
func (a *App) SendAutoResponseIfNecessary(c *request.Context, channel *model.Channel, sender *model.User, post *model.Post) (bool, *model.AppError) {
|
||||
if channel.Type != model.CHANNEL_DIRECT {
|
||||
return false, nil
|
||||
}
|
||||
@@ -48,10 +49,10 @@ func (a *App) SendAutoResponseIfNecessary(channel *model.Channel, sender *model.
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return a.SendAutoResponse(channel, receiver, post)
|
||||
return a.SendAutoResponse(c, channel, receiver, post)
|
||||
}
|
||||
|
||||
func (a *App) SendAutoResponse(channel *model.Channel, receiver *model.User, post *model.Post) (bool, *model.AppError) {
|
||||
func (a *App) SendAutoResponse(c *request.Context, channel *model.Channel, receiver *model.User, post *model.Post) (bool, *model.AppError) {
|
||||
if receiver == nil || receiver.NotifyProps == nil {
|
||||
return false, nil
|
||||
}
|
||||
@@ -76,7 +77,7 @@ func (a *App) SendAutoResponse(channel *model.Channel, receiver *model.User, pos
|
||||
UserId: receiver.Id,
|
||||
}
|
||||
|
||||
if _, err := a.CreatePost(autoResponderPost, channel, false, false); err != nil {
|
||||
if _, err := a.CreatePost(c, autoResponderPost, channel, false, false); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ func TestSetAutoResponderStatus(t *testing.T) {
|
||||
defer th.TearDown()
|
||||
|
||||
user := th.CreateUser()
|
||||
defer th.App.PermanentDeleteUser(user)
|
||||
defer th.App.PermanentDeleteUser(th.Context, user)
|
||||
|
||||
th.App.SetStatusOnline(user.Id, true)
|
||||
|
||||
@@ -56,7 +56,7 @@ func TestDisableAutoResponder(t *testing.T) {
|
||||
defer th.TearDown()
|
||||
|
||||
user := th.CreateUser()
|
||||
defer th.App.PermanentDeleteUser(user)
|
||||
defer th.App.PermanentDeleteUser(th.Context, user)
|
||||
|
||||
th.App.SetStatusOnline(user.Id, true)
|
||||
|
||||
@@ -98,14 +98,14 @@ func TestSendAutoResponseIfNecessary(t *testing.T) {
|
||||
|
||||
channel := th.CreateDmChannel(receiver)
|
||||
|
||||
savedPost, _ := th.App.CreatePost(&model.Post{
|
||||
savedPost, _ := th.App.CreatePost(th.Context, &model.Post{
|
||||
ChannelId: channel.Id,
|
||||
Message: "zz" + model.NewId() + "a",
|
||||
UserId: th.BasicUser.Id},
|
||||
th.BasicChannel,
|
||||
false, true)
|
||||
|
||||
sent, err := th.App.SendAutoResponseIfNecessary(channel, th.BasicUser, savedPost)
|
||||
sent, err := th.App.SendAutoResponseIfNecessary(th.Context, channel, th.BasicUser, savedPost)
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.True(t, sent)
|
||||
@@ -128,14 +128,14 @@ func TestSendAutoResponseIfNecessary(t *testing.T) {
|
||||
|
||||
channel := th.CreateDmChannel(receiver)
|
||||
|
||||
savedPost, _ := th.App.CreatePost(&model.Post{
|
||||
savedPost, _ := th.App.CreatePost(th.Context, &model.Post{
|
||||
ChannelId: channel.Id,
|
||||
Message: "zz" + model.NewId() + "a",
|
||||
UserId: th.BasicUser.Id},
|
||||
th.BasicChannel,
|
||||
false, true)
|
||||
|
||||
sent, err := th.App.SendAutoResponseIfNecessary(channel, th.BasicUser, savedPost)
|
||||
sent, err := th.App.SendAutoResponseIfNecessary(th.Context, channel, th.BasicUser, savedPost)
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.False(t, sent)
|
||||
@@ -145,14 +145,14 @@ func TestSendAutoResponseIfNecessary(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
savedPost, _ := th.App.CreatePost(&model.Post{
|
||||
savedPost, _ := th.App.CreatePost(th.Context, &model.Post{
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "zz" + model.NewId() + "a",
|
||||
UserId: th.BasicUser.Id},
|
||||
th.BasicChannel,
|
||||
false, true)
|
||||
|
||||
sent, err := th.App.SendAutoResponseIfNecessary(th.BasicChannel, th.BasicUser, savedPost)
|
||||
sent, err := th.App.SendAutoResponseIfNecessary(th.Context, th.BasicChannel, th.BasicUser, savedPost)
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.False(t, sent)
|
||||
@@ -175,7 +175,7 @@ func TestSendAutoResponseIfNecessary(t *testing.T) {
|
||||
|
||||
channel := th.CreateDmChannel(receiver)
|
||||
|
||||
bot, err := th.App.CreateBot(&model.Bot{
|
||||
bot, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "botusername",
|
||||
Description: "bot",
|
||||
OwnerId: th.BasicUser.Id,
|
||||
@@ -185,14 +185,14 @@ func TestSendAutoResponseIfNecessary(t *testing.T) {
|
||||
botUser, err := th.App.GetUser(bot.UserId)
|
||||
assert.Nil(t, err)
|
||||
|
||||
savedPost, _ := th.App.CreatePost(&model.Post{
|
||||
savedPost, _ := th.App.CreatePost(th.Context, &model.Post{
|
||||
ChannelId: channel.Id,
|
||||
Message: "zz" + model.NewId() + "a",
|
||||
UserId: botUser.Id},
|
||||
th.BasicChannel,
|
||||
false, true)
|
||||
|
||||
sent, err := th.App.SendAutoResponseIfNecessary(channel, botUser, savedPost)
|
||||
sent, err := th.App.SendAutoResponseIfNecessary(th.Context, channel, botUser, savedPost)
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.False(t, sent)
|
||||
@@ -215,7 +215,7 @@ func TestSendAutoResponseIfNecessary(t *testing.T) {
|
||||
|
||||
channel := th.CreateDmChannel(receiver)
|
||||
|
||||
savedPost, err := th.App.CreatePost(&model.Post{
|
||||
savedPost, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
ChannelId: channel.Id,
|
||||
Message: NewTestId(),
|
||||
UserId: th.BasicUser.Id},
|
||||
@@ -224,12 +224,12 @@ func TestSendAutoResponseIfNecessary(t *testing.T) {
|
||||
|
||||
assert.Nil(t, err)
|
||||
|
||||
sent, err := th.App.SendAutoResponseIfNecessary(channel, th.BasicUser, savedPost)
|
||||
sent, err := th.App.SendAutoResponseIfNecessary(th.Context, channel, th.BasicUser, savedPost)
|
||||
|
||||
require.Nil(t, err)
|
||||
assert.True(t, sent)
|
||||
|
||||
sent, err = th.App.SendAutoResponseIfNecessary(channel, th.BasicUser, savedPost)
|
||||
sent, err = th.App.SendAutoResponseIfNecessary(th.Context, channel, th.BasicUser, savedPost)
|
||||
|
||||
require.Nil(t, err)
|
||||
assert.False(t, sent)
|
||||
@@ -241,7 +241,7 @@ func TestSendAutoResponseSuccess(t *testing.T) {
|
||||
defer th.TearDown()
|
||||
|
||||
user := th.CreateUser()
|
||||
defer th.App.PermanentDeleteUser(user)
|
||||
defer th.App.PermanentDeleteUser(th.Context, user)
|
||||
|
||||
patch := &model.UserPatch{}
|
||||
patch.NotifyProps = make(map[string]string)
|
||||
@@ -251,14 +251,14 @@ func TestSendAutoResponseSuccess(t *testing.T) {
|
||||
userUpdated1, err := th.App.PatchUser(user.Id, patch, true)
|
||||
require.Nil(t, err)
|
||||
|
||||
savedPost, _ := th.App.CreatePost(&model.Post{
|
||||
savedPost, _ := th.App.CreatePost(th.Context, &model.Post{
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "zz" + model.NewId() + "a",
|
||||
UserId: th.BasicUser.Id},
|
||||
th.BasicChannel,
|
||||
false, true)
|
||||
|
||||
sent, err := th.App.SendAutoResponse(th.BasicChannel, userUpdated1, savedPost)
|
||||
sent, err := th.App.SendAutoResponse(th.Context, th.BasicChannel, userUpdated1, savedPost)
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.True(t, sent)
|
||||
@@ -282,7 +282,7 @@ func TestSendAutoResponseSuccessOnThread(t *testing.T) {
|
||||
defer th.TearDown()
|
||||
|
||||
user := th.CreateUser()
|
||||
defer th.App.PermanentDeleteUser(user)
|
||||
defer th.App.PermanentDeleteUser(th.Context, user)
|
||||
|
||||
patch := &model.UserPatch{}
|
||||
patch.NotifyProps = make(map[string]string)
|
||||
@@ -292,14 +292,14 @@ func TestSendAutoResponseSuccessOnThread(t *testing.T) {
|
||||
userUpdated1, err := th.App.PatchUser(user.Id, patch, true)
|
||||
require.Nil(t, err)
|
||||
|
||||
parentPost, _ := th.App.CreatePost(&model.Post{
|
||||
parentPost, _ := th.App.CreatePost(th.Context, &model.Post{
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "zz" + model.NewId() + "a",
|
||||
UserId: th.BasicUser.Id},
|
||||
th.BasicChannel,
|
||||
false, true)
|
||||
|
||||
savedPost, _ := th.App.CreatePost(&model.Post{
|
||||
savedPost, _ := th.App.CreatePost(th.Context, &model.Post{
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "zz" + model.NewId() + "a",
|
||||
UserId: th.BasicUser.Id,
|
||||
@@ -308,7 +308,7 @@ func TestSendAutoResponseSuccessOnThread(t *testing.T) {
|
||||
th.BasicChannel,
|
||||
false, true)
|
||||
|
||||
sent, err := th.App.SendAutoResponse(th.BasicChannel, userUpdated1, savedPost)
|
||||
sent, err := th.App.SendAutoResponse(th.Context, th.BasicChannel, userUpdated1, savedPost)
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.True(t, sent)
|
||||
@@ -332,7 +332,7 @@ func TestSendAutoResponseFailure(t *testing.T) {
|
||||
defer th.TearDown()
|
||||
|
||||
user := th.CreateUser()
|
||||
defer th.App.PermanentDeleteUser(user)
|
||||
defer th.App.PermanentDeleteUser(th.Context, user)
|
||||
|
||||
patch := &model.UserPatch{}
|
||||
patch.NotifyProps = make(map[string]string)
|
||||
@@ -342,14 +342,14 @@ func TestSendAutoResponseFailure(t *testing.T) {
|
||||
userUpdated1, err := th.App.PatchUser(user.Id, patch, true)
|
||||
require.Nil(t, err)
|
||||
|
||||
savedPost, _ := th.App.CreatePost(&model.Post{
|
||||
savedPost, _ := th.App.CreatePost(th.Context, &model.Post{
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "zz" + model.NewId() + "a",
|
||||
UserId: th.BasicUser.Id},
|
||||
th.BasicChannel,
|
||||
false, true)
|
||||
|
||||
sent, err := th.App.SendAutoResponse(th.BasicChannel, userUpdated1, savedPost)
|
||||
sent, err := th.App.SendAutoResponse(th.Context, th.BasicChannel, userUpdated1, savedPost)
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.False(t, sent)
|
||||
|
||||
21
app/bot.go
21
app/bot.go
@@ -11,6 +11,7 @@ import (
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
@@ -18,7 +19,7 @@ import (
|
||||
)
|
||||
|
||||
// CreateBot creates the given bot and corresponding user.
|
||||
func (a *App) CreateBot(bot *model.Bot) (*model.Bot, *model.AppError) {
|
||||
func (a *App) CreateBot(c *request.Context, bot *model.Bot) (*model.Bot, *model.AppError) {
|
||||
user, nErr := a.Srv().Store.User().Save(model.UserFromBot(bot))
|
||||
if nErr != nil {
|
||||
var appErr *model.AppError
|
||||
@@ -67,7 +68,7 @@ func (a *App) CreateBot(bot *model.Bot) (*model.Bot, *model.AppError) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channel, err := a.getOrCreateDirectChannelWithUser(user, botOwner)
|
||||
channel, err := a.getOrCreateDirectChannelWithUser(c, user, botOwner)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -80,7 +81,7 @@ func (a *App) CreateBot(bot *model.Bot) (*model.Bot, *model.AppError) {
|
||||
Message: T("api.bot.teams_channels.add_message_mobile"),
|
||||
}
|
||||
|
||||
if _, err := a.CreatePostAsUser(botAddPost, a.Session().Id, true); err != nil {
|
||||
if _, err := a.CreatePostAsUser(c, botAddPost, c.Session().Id, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -240,7 +241,7 @@ func (a *App) GetBots(options *model.BotGetOptions) (model.BotList, *model.AppEr
|
||||
}
|
||||
|
||||
// UpdateBotActive marks a bot as active or inactive, along with its corresponding user.
|
||||
func (a *App) UpdateBotActive(botUserId string, active bool) (*model.Bot, *model.AppError) {
|
||||
func (a *App) UpdateBotActive(c *request.Context, botUserId string, active bool) (*model.Bot, *model.AppError) {
|
||||
user, nErr := a.Srv().Store.User().Get(context.Background(), botUserId)
|
||||
if nErr != nil {
|
||||
var nfErr *store.ErrNotFound
|
||||
@@ -252,7 +253,7 @@ func (a *App) UpdateBotActive(botUserId string, active bool) (*model.Bot, *model
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := a.UpdateActive(user, active); err != nil {
|
||||
if _, err := a.UpdateActive(c, user, active); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -347,7 +348,7 @@ func (a *App) UpdateBotOwner(botUserId, newOwnerId string) (*model.Bot, *model.A
|
||||
}
|
||||
|
||||
// disableUserBots disables all bots owned by the given user.
|
||||
func (a *App) disableUserBots(userID string) *model.AppError {
|
||||
func (a *App) disableUserBots(c *request.Context, userID string) *model.AppError {
|
||||
perPage := 20
|
||||
for {
|
||||
options := &model.BotGetOptions{
|
||||
@@ -363,7 +364,7 @@ func (a *App) disableUserBots(userID string) *model.AppError {
|
||||
}
|
||||
|
||||
for _, bot := range userBots {
|
||||
_, err := a.UpdateBotActive(bot.UserId, false)
|
||||
_, err := a.UpdateBotActive(c, bot.UserId, false)
|
||||
if err != nil {
|
||||
mlog.Warn("Unable to deactivate bot.", mlog.String("bot_user_id", bot.UserId), mlog.Err(err))
|
||||
}
|
||||
@@ -380,7 +381,7 @@ func (a *App) disableUserBots(userID string) *model.AppError {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) notifySysadminsBotOwnerDeactivated(userID string) *model.AppError {
|
||||
func (a *App) notifySysadminsBotOwnerDeactivated(c *request.Context, userID string) *model.AppError {
|
||||
perPage := 25
|
||||
botOptions := &model.BotGetOptions{
|
||||
OwnerId: userID,
|
||||
@@ -442,7 +443,7 @@ func (a *App) notifySysadminsBotOwnerDeactivated(userID string) *model.AppError
|
||||
|
||||
// for each sysadmin, notify user that owns bots was disabled
|
||||
for _, sysAdmin := range sysAdmins {
|
||||
channel, appErr := a.GetOrCreateDirectChannel(sysAdmin.Id, sysAdmin.Id)
|
||||
channel, appErr := a.GetOrCreateDirectChannel(c, sysAdmin.Id, sysAdmin.Id)
|
||||
if appErr != nil {
|
||||
return appErr
|
||||
}
|
||||
@@ -454,7 +455,7 @@ func (a *App) notifySysadminsBotOwnerDeactivated(userID string) *model.AppError
|
||||
Type: model.POST_SYSTEM_GENERIC,
|
||||
}
|
||||
|
||||
_, appErr = a.CreatePost(post, channel, false, true)
|
||||
_, appErr = a.CreatePost(c, post, channel, false, true)
|
||||
if appErr != nil {
|
||||
return appErr
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ func TestCreateBot(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
_, err := th.App.CreateBot(&model.Bot{
|
||||
_, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "invalid username",
|
||||
Description: "a bot",
|
||||
OwnerId: th.BasicUser.Id,
|
||||
@@ -37,7 +37,7 @@ func TestCreateBot(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
_, err := th.App.CreateBot(&model.Bot{
|
||||
_, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username",
|
||||
Description: strings.Repeat("x", 1025),
|
||||
OwnerId: th.BasicUser.Id,
|
||||
@@ -50,7 +50,7 @@ func TestCreateBot(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
bot, err := th.App.CreateBot(&model.Bot{
|
||||
bot, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username.",
|
||||
Description: "a bot",
|
||||
OwnerId: th.BasicUser.Id,
|
||||
@@ -65,7 +65,7 @@ func TestCreateBot(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
bot, err := th.App.CreateBot(&model.Bot{
|
||||
bot, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username",
|
||||
Description: "a bot",
|
||||
OwnerId: th.BasicUser.Id,
|
||||
@@ -80,7 +80,7 @@ func TestCreateBot(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
|
||||
// Check that a post was created to add bot to team and channels
|
||||
channel, err := th.App.getOrCreateDirectChannelWithUser(user, th.BasicUser)
|
||||
channel, err := th.App.getOrCreateDirectChannelWithUser(th.Context, user, th.BasicUser)
|
||||
require.Nil(t, err)
|
||||
posts, err := th.App.GetPosts(channel.Id, 0, 1)
|
||||
require.Nil(t, err)
|
||||
@@ -94,7 +94,7 @@ func TestCreateBot(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
_, err := th.App.CreateBot(&model.Bot{
|
||||
_, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: th.BasicUser.Username,
|
||||
Description: "a bot",
|
||||
OwnerId: th.BasicUser.Id,
|
||||
@@ -109,7 +109,7 @@ func TestPatchBot(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
bot, err := th.App.CreateBot(&model.Bot{
|
||||
bot, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username",
|
||||
Description: "a bot",
|
||||
OwnerId: th.BasicUser.Id,
|
||||
@@ -132,7 +132,7 @@ func TestPatchBot(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
bot, err := th.App.CreateBot(&model.Bot{
|
||||
bot, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username",
|
||||
Description: "a bot",
|
||||
OwnerId: th.BasicUser.Id,
|
||||
@@ -162,7 +162,7 @@ func TestPatchBot(t *testing.T) {
|
||||
OwnerId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
createdBot, err := th.App.CreateBot(bot)
|
||||
createdBot, err := th.App.CreateBot(th.Context, bot)
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteBot(createdBot.UserId)
|
||||
|
||||
@@ -189,7 +189,7 @@ func TestPatchBot(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
bot, err := th.App.CreateBot(&model.Bot{
|
||||
bot, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username",
|
||||
DisplayName: "bot",
|
||||
Description: "a bot",
|
||||
@@ -212,7 +212,7 @@ func TestGetBot(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
bot1, err := th.App.CreateBot(&model.Bot{
|
||||
bot1, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username",
|
||||
Description: "a bot",
|
||||
OwnerId: th.BasicUser.Id,
|
||||
@@ -220,7 +220,7 @@ func TestGetBot(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteBot(bot1.UserId)
|
||||
|
||||
bot2, err := th.App.CreateBot(&model.Bot{
|
||||
bot2, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username2",
|
||||
Description: "a second bot",
|
||||
OwnerId: th.BasicUser.Id,
|
||||
@@ -228,13 +228,13 @@ func TestGetBot(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteBot(bot2.UserId)
|
||||
|
||||
deletedBot, err := th.App.CreateBot(&model.Bot{
|
||||
deletedBot, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username3",
|
||||
Description: "a deleted bot",
|
||||
OwnerId: th.BasicUser.Id,
|
||||
})
|
||||
require.Nil(t, err)
|
||||
deletedBot, err = th.App.UpdateBotActive(deletedBot.UserId, false)
|
||||
deletedBot, err = th.App.UpdateBotActive(th.Context, deletedBot.UserId, false)
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteBot(deletedBot.UserId)
|
||||
|
||||
@@ -276,7 +276,7 @@ func TestGetBots(t *testing.T) {
|
||||
OwnerId1 := model.NewId()
|
||||
OwnerId2 := model.NewId()
|
||||
|
||||
bot1, err := th.App.CreateBot(&model.Bot{
|
||||
bot1, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username",
|
||||
Description: "a bot",
|
||||
OwnerId: OwnerId1,
|
||||
@@ -284,17 +284,17 @@ func TestGetBots(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteBot(bot1.UserId)
|
||||
|
||||
deletedBot1, err := th.App.CreateBot(&model.Bot{
|
||||
deletedBot1, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username4",
|
||||
Description: "a deleted bot",
|
||||
OwnerId: OwnerId1,
|
||||
})
|
||||
require.Nil(t, err)
|
||||
deletedBot1, err = th.App.UpdateBotActive(deletedBot1.UserId, false)
|
||||
deletedBot1, err = th.App.UpdateBotActive(th.Context, deletedBot1.UserId, false)
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteBot(deletedBot1.UserId)
|
||||
|
||||
bot2, err := th.App.CreateBot(&model.Bot{
|
||||
bot2, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username2",
|
||||
Description: "a second bot",
|
||||
OwnerId: OwnerId1,
|
||||
@@ -302,7 +302,7 @@ func TestGetBots(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteBot(bot2.UserId)
|
||||
|
||||
bot3, err := th.App.CreateBot(&model.Bot{
|
||||
bot3, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username3",
|
||||
Description: "a third bot",
|
||||
OwnerId: OwnerId1,
|
||||
@@ -310,7 +310,7 @@ func TestGetBots(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteBot(bot3.UserId)
|
||||
|
||||
bot4, err := th.App.CreateBot(&model.Bot{
|
||||
bot4, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username5",
|
||||
Description: "a fourth bot",
|
||||
OwnerId: OwnerId2,
|
||||
@@ -318,13 +318,13 @@ func TestGetBots(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteBot(bot4.UserId)
|
||||
|
||||
deletedBot2, err := th.App.CreateBot(&model.Bot{
|
||||
deletedBot2, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username6",
|
||||
Description: "a deleted bot",
|
||||
OwnerId: OwnerId2,
|
||||
})
|
||||
require.Nil(t, err)
|
||||
deletedBot2, err = th.App.UpdateBotActive(deletedBot2.UserId, false)
|
||||
deletedBot2, err = th.App.UpdateBotActive(th.Context, deletedBot2.UserId, false)
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteBot(deletedBot2.UserId)
|
||||
|
||||
@@ -466,7 +466,7 @@ func TestUpdateBotActive(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
_, err := th.App.UpdateBotActive(model.NewId(), false)
|
||||
_, err := th.App.UpdateBotActive(th.Context, model.NewId(), false)
|
||||
require.NotNil(t, err)
|
||||
require.Equal(t, "app.user.missing_account.const", err.Id)
|
||||
})
|
||||
@@ -475,7 +475,7 @@ func TestUpdateBotActive(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
bot, err := th.App.CreateBot(&model.Bot{
|
||||
bot, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username",
|
||||
Description: "a bot",
|
||||
OwnerId: th.BasicUser.Id,
|
||||
@@ -483,21 +483,21 @@ func TestUpdateBotActive(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteBot(bot.UserId)
|
||||
|
||||
disabledBot, err := th.App.UpdateBotActive(bot.UserId, false)
|
||||
disabledBot, err := th.App.UpdateBotActive(th.Context, bot.UserId, false)
|
||||
require.Nil(t, err)
|
||||
require.NotEqual(t, 0, disabledBot.DeleteAt)
|
||||
|
||||
// Disabling should be idempotent
|
||||
disabledBotAgain, err := th.App.UpdateBotActive(bot.UserId, false)
|
||||
disabledBotAgain, err := th.App.UpdateBotActive(th.Context, bot.UserId, false)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, disabledBot.DeleteAt, disabledBotAgain.DeleteAt)
|
||||
|
||||
reenabledBot, err := th.App.UpdateBotActive(bot.UserId, true)
|
||||
reenabledBot, err := th.App.UpdateBotActive(th.Context, bot.UserId, true)
|
||||
require.Nil(t, err)
|
||||
require.EqualValues(t, 0, reenabledBot.DeleteAt)
|
||||
|
||||
// Re-enabling should be idempotent
|
||||
reenabledBotAgain, err := th.App.UpdateBotActive(bot.UserId, true)
|
||||
reenabledBotAgain, err := th.App.UpdateBotActive(th.Context, bot.UserId, true)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, reenabledBot.DeleteAt, reenabledBotAgain.DeleteAt)
|
||||
})
|
||||
@@ -507,7 +507,7 @@ func TestPermanentDeleteBot(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
bot, err := th.App.CreateBot(&model.Bot{
|
||||
bot, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username",
|
||||
Description: "a bot",
|
||||
OwnerId: th.BasicUser.Id,
|
||||
@@ -536,7 +536,7 @@ func TestDisableUserBots(t *testing.T) {
|
||||
}()
|
||||
|
||||
for i := 0; i < 46; i++ {
|
||||
bot, err := th.App.CreateBot(&model.Bot{
|
||||
bot, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: fmt.Sprintf("username%v", i),
|
||||
Description: "a bot",
|
||||
OwnerId: ownerId1,
|
||||
@@ -546,7 +546,7 @@ func TestDisableUserBots(t *testing.T) {
|
||||
}
|
||||
require.Len(t, bots, 46)
|
||||
|
||||
u2bot1, err := th.App.CreateBot(&model.Bot{
|
||||
u2bot1, err := th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "username_nodisable",
|
||||
Description: "a bot",
|
||||
OwnerId: ownerId2,
|
||||
@@ -554,7 +554,7 @@ func TestDisableUserBots(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteBot(u2bot1.UserId)
|
||||
|
||||
err = th.App.disableUserBots(ownerId1)
|
||||
err = th.App.disableUserBots(th.Context, ownerId1)
|
||||
require.Nil(t, err)
|
||||
|
||||
// Check all bots and corrensponding users are disabled for creator 1
|
||||
@@ -574,7 +574,7 @@ func TestDisableUserBots(t *testing.T) {
|
||||
require.Zero(t, user.DeleteAt)
|
||||
|
||||
// Bad id doesn't do anything or break horribly
|
||||
err = th.App.disableUserBots(model.NewId())
|
||||
err = th.App.disableUserBots(th.Context, model.NewId())
|
||||
require.Nil(t, err)
|
||||
}
|
||||
|
||||
@@ -596,7 +596,7 @@ func TestNotifySysadminsBotOwnerDisabled(t *testing.T) {
|
||||
Password: "hello1",
|
||||
Username: "un_sysadmin1",
|
||||
Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
|
||||
_, err := th.App.CreateUser(&sysadmin1)
|
||||
_, err := th.App.CreateUser(th.Context, &sysadmin1)
|
||||
require.Nil(t, err, "failed to create user")
|
||||
th.App.UpdateUserRoles(sysadmin1.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false)
|
||||
|
||||
@@ -606,12 +606,12 @@ func TestNotifySysadminsBotOwnerDisabled(t *testing.T) {
|
||||
Password: "hello1",
|
||||
Username: "un_sysadmin2",
|
||||
Roles: model.SYSTEM_ADMIN_ROLE_ID + " " + model.SYSTEM_USER_ROLE_ID}
|
||||
_, err = th.App.CreateUser(&sysadmin2)
|
||||
_, err = th.App.CreateUser(th.Context, &sysadmin2)
|
||||
require.Nil(t, err, "failed to create user")
|
||||
th.App.UpdateUserRoles(sysadmin2.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false)
|
||||
|
||||
// create user to be disabled
|
||||
user1, err := th.App.CreateUser(&model.User{
|
||||
user1, err := th.App.CreateUser(th.Context, &model.User{
|
||||
Email: "user1@example.com",
|
||||
Username: "user1_disabled",
|
||||
Nickname: "user1",
|
||||
@@ -620,7 +620,7 @@ func TestNotifySysadminsBotOwnerDisabled(t *testing.T) {
|
||||
require.Nil(t, err, "failed to create user")
|
||||
|
||||
// create user that doesn't own any bots
|
||||
user2, err := th.App.CreateUser(&model.User{
|
||||
user2, err := th.App.CreateUser(th.Context, &model.User{
|
||||
Email: "user2@example.com",
|
||||
Username: "user2_disabled",
|
||||
Nickname: "user2",
|
||||
@@ -633,7 +633,7 @@ func TestNotifySysadminsBotOwnerDisabled(t *testing.T) {
|
||||
// create bots owned by user (equal to numBotsToPrint)
|
||||
var bot *model.Bot
|
||||
for i := 0; i < numBotsToPrint; i++ {
|
||||
bot, err = th.App.CreateBot(&model.Bot{
|
||||
bot, err = th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: fmt.Sprintf("bot%v", i),
|
||||
Description: "a bot",
|
||||
OwnerId: user1.Id,
|
||||
@@ -644,13 +644,13 @@ func TestNotifySysadminsBotOwnerDisabled(t *testing.T) {
|
||||
assert.Len(t, userBots, 10)
|
||||
|
||||
// get DM channels for sysadmin1 and sysadmin2
|
||||
channelSys1, appErr := th.App.GetOrCreateDirectChannel(sysadmin1.Id, sysadmin1.Id)
|
||||
channelSys1, appErr := th.App.GetOrCreateDirectChannel(th.Context, sysadmin1.Id, sysadmin1.Id)
|
||||
require.Nil(t, appErr)
|
||||
channelSys2, appErr := th.App.GetOrCreateDirectChannel(sysadmin2.Id, sysadmin2.Id)
|
||||
channelSys2, appErr := th.App.GetOrCreateDirectChannel(th.Context, sysadmin2.Id, sysadmin2.Id)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
// send notification for user without bots
|
||||
err = th.App.notifySysadminsBotOwnerDeactivated(user2.Id)
|
||||
err = th.App.notifySysadminsBotOwnerDeactivated(th.Context, user2.Id)
|
||||
require.Nil(t, err)
|
||||
|
||||
// get posts from sysadmin1 and sysadmin2 DM channels
|
||||
@@ -663,7 +663,7 @@ func TestNotifySysadminsBotOwnerDisabled(t *testing.T) {
|
||||
assert.Empty(t, posts2.Order)
|
||||
|
||||
// send notification for user with bots
|
||||
err = th.App.notifySysadminsBotOwnerDeactivated(user1.Id)
|
||||
err = th.App.notifySysadminsBotOwnerDeactivated(th.Context, user1.Id)
|
||||
require.Nil(t, err)
|
||||
|
||||
// get posts from sysadmin1 and sysadmin2 DM channels
|
||||
@@ -690,7 +690,7 @@ func TestNotifySysadminsBotOwnerDisabled(t *testing.T) {
|
||||
|
||||
// create additional bot to go over the printable limit
|
||||
for i := numBotsToPrint; i < numBotsToPrint+1; i++ {
|
||||
bot, err = th.App.CreateBot(&model.Bot{
|
||||
bot, err = th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: fmt.Sprintf("bot%v", i),
|
||||
Description: "a bot",
|
||||
OwnerId: user1.Id,
|
||||
|
||||
149
app/channel.go
149
app/channel.go
@@ -10,6 +10,7 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/plugin"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
@@ -21,7 +22,7 @@ import (
|
||||
|
||||
// CreateDefaultChannels creates channels in the given team for each channel returned by (*App).DefaultChannelNames.
|
||||
//
|
||||
func (a *App) CreateDefaultChannels(teamID string) ([]*model.Channel, *model.AppError) {
|
||||
func (a *App) CreateDefaultChannels(c *request.Context, teamID string) ([]*model.Channel, *model.AppError) {
|
||||
displayNames := map[string]string{
|
||||
"town-square": i18n.T("api.channel.create_default_channels.town_square"),
|
||||
"off-topic": i18n.T("api.channel.create_default_channels.off_topic"),
|
||||
@@ -31,7 +32,7 @@ func (a *App) CreateDefaultChannels(teamID string) ([]*model.Channel, *model.App
|
||||
for _, name := range defaultChannelNames {
|
||||
displayName := i18n.TDefault(displayNames[name], name)
|
||||
channel := &model.Channel{DisplayName: displayName, Name: name, Type: model.CHANNEL_OPEN, TeamId: teamID}
|
||||
if _, err := a.CreateChannel(channel, false); err != nil {
|
||||
if _, err := a.CreateChannel(c, channel, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channels = append(channels, channel)
|
||||
@@ -65,7 +66,7 @@ func (a *App) DefaultChannelNames() []string {
|
||||
return names
|
||||
}
|
||||
|
||||
func (a *App) JoinDefaultChannels(teamID string, user *model.User, shouldBeAdmin bool, userRequestorId string) *model.AppError {
|
||||
func (a *App) JoinDefaultChannels(c *request.Context, teamID string, user *model.User, shouldBeAdmin bool, userRequestorId string) *model.AppError {
|
||||
var requestor *model.User
|
||||
var nErr error
|
||||
if userRequestorId != "" {
|
||||
@@ -114,7 +115,7 @@ func (a *App) JoinDefaultChannels(teamID string, user *model.User, shouldBeAdmin
|
||||
}
|
||||
|
||||
if *a.Config().ServiceSettings.ExperimentalEnableDefaultChannelLeaveJoinMessages {
|
||||
if aErr := a.postJoinMessageForDefaultChannel(user, requestor, channel); aErr != nil {
|
||||
if aErr := a.postJoinMessageForDefaultChannel(c, user, requestor, channel); aErr != nil {
|
||||
mlog.Warn("Failed to post join/leave message", mlog.Err(aErr))
|
||||
}
|
||||
}
|
||||
@@ -145,24 +146,24 @@ func (a *App) JoinDefaultChannels(teamID string, user *model.User, shouldBeAdmin
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) postJoinMessageForDefaultChannel(user *model.User, requestor *model.User, channel *model.Channel) *model.AppError {
|
||||
func (a *App) postJoinMessageForDefaultChannel(c *request.Context, user *model.User, requestor *model.User, channel *model.Channel) *model.AppError {
|
||||
if channel.Name == model.DEFAULT_CHANNEL {
|
||||
if requestor == nil {
|
||||
if err := a.postJoinTeamMessage(user, channel); err != nil {
|
||||
if err := a.postJoinTeamMessage(c, user, channel); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err := a.postAddToTeamMessage(requestor, user, channel, ""); err != nil {
|
||||
if err := a.postAddToTeamMessage(c, requestor, user, channel, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if requestor == nil {
|
||||
if err := a.postJoinChannelMessage(user, channel); err != nil {
|
||||
if err := a.postJoinChannelMessage(c, user, channel); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if err := a.PostAddToChannelMessage(requestor, user, channel, ""); err != nil {
|
||||
if err := a.PostAddToChannelMessage(c, requestor, user, channel, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -171,7 +172,7 @@ func (a *App) postJoinMessageForDefaultChannel(user *model.User, requestor *mode
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) CreateChannelWithUser(channel *model.Channel, userID string) (*model.Channel, *model.AppError) {
|
||||
func (a *App) CreateChannelWithUser(c *request.Context, channel *model.Channel, userID string) (*model.Channel, *model.AppError) {
|
||||
if channel.IsGroupOrDirect() {
|
||||
return nil, model.NewAppError("CreateChannelWithUser", "api.channel.create_channel.direct_channel.app_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
@@ -192,7 +193,7 @@ func (a *App) CreateChannelWithUser(channel *model.Channel, userID string) (*mod
|
||||
|
||||
channel.CreatorId = userID
|
||||
|
||||
rchannel, err := a.CreateChannel(channel, true)
|
||||
rchannel, err := a.CreateChannel(c, channel, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -202,7 +203,7 @@ func (a *App) CreateChannelWithUser(channel *model.Channel, userID string) (*mod
|
||||
return nil, err
|
||||
}
|
||||
|
||||
a.postJoinChannelMessage(user, channel)
|
||||
a.postJoinChannelMessage(c, user, channel)
|
||||
|
||||
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_CHANNEL_CREATED, "", "", userID, nil)
|
||||
message.Add("channel_id", channel.Id)
|
||||
@@ -235,7 +236,7 @@ func (a *App) RenameChannel(channel *model.Channel, newChannelName string, newDi
|
||||
return newChannel, nil
|
||||
}
|
||||
|
||||
func (a *App) CreateChannel(channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) {
|
||||
func (a *App) CreateChannel(c *request.Context, channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) {
|
||||
channel.DisplayName = strings.TrimSpace(channel.DisplayName)
|
||||
sc, nErr := a.Srv().Store.Channel().Save(channel, *a.Config().TeamSettings.MaxChannelsPerTeam)
|
||||
if nErr != nil {
|
||||
@@ -310,7 +311,7 @@ func (a *App) CreateChannel(channel *model.Channel, addMember bool) (*model.Chan
|
||||
|
||||
if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil {
|
||||
a.Srv().Go(func() {
|
||||
pluginContext := a.PluginContext()
|
||||
pluginContext := pluginContext(c)
|
||||
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
|
||||
hooks.ChannelHasBeenCreated(pluginContext, sc)
|
||||
return true
|
||||
@@ -321,7 +322,7 @@ func (a *App) CreateChannel(channel *model.Channel, addMember bool) (*model.Chan
|
||||
return sc, nil
|
||||
}
|
||||
|
||||
func (a *App) GetOrCreateDirectChannel(userID, otherUserID string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) {
|
||||
func (a *App) GetOrCreateDirectChannel(c *request.Context, userID, otherUserID string, channelOptions ...model.ChannelOption) (*model.Channel, *model.AppError) {
|
||||
channel, nErr := a.getDirectChannel(userID, otherUserID)
|
||||
if nErr != nil {
|
||||
return nil, nErr
|
||||
@@ -339,11 +340,11 @@ func (a *App) GetOrCreateDirectChannel(userID, otherUserID string, channelOption
|
||||
return nil, err
|
||||
}
|
||||
|
||||
a.handleCreationEvent(userID, otherUserID, channel)
|
||||
a.handleCreationEvent(c, userID, otherUserID, channel)
|
||||
return channel, nil
|
||||
}
|
||||
|
||||
func (a *App) getOrCreateDirectChannelWithUser(user, otherUser *model.User) (*model.Channel, *model.AppError) {
|
||||
func (a *App) getOrCreateDirectChannelWithUser(c *request.Context, user, otherUser *model.User) (*model.Channel, *model.AppError) {
|
||||
channel, nErr := a.getDirectChannel(user.Id, otherUser.Id)
|
||||
if nErr != nil {
|
||||
return nil, nErr
|
||||
@@ -361,17 +362,17 @@ func (a *App) getOrCreateDirectChannelWithUser(user, otherUser *model.User) (*mo
|
||||
return nil, err
|
||||
}
|
||||
|
||||
a.handleCreationEvent(user.Id, otherUser.Id, channel)
|
||||
a.handleCreationEvent(c, user.Id, otherUser.Id, channel)
|
||||
return channel, nil
|
||||
}
|
||||
|
||||
func (a *App) handleCreationEvent(userID, otherUserID string, channel *model.Channel) {
|
||||
func (a *App) handleCreationEvent(c *request.Context, userID, otherUserID string, channel *model.Channel) {
|
||||
a.InvalidateCacheForUser(userID)
|
||||
a.InvalidateCacheForUser(otherUserID)
|
||||
|
||||
if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil {
|
||||
a.Srv().Go(func() {
|
||||
pluginContext := a.PluginContext()
|
||||
pluginContext := pluginContext(c)
|
||||
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
|
||||
hooks.ChannelHasBeenCreated(pluginContext, channel)
|
||||
return true
|
||||
@@ -671,13 +672,13 @@ func (a *App) UpdateChannelScheme(channel *model.Channel) (*model.Channel, *mode
|
||||
return a.UpdateChannel(oldChannel)
|
||||
}
|
||||
|
||||
func (a *App) UpdateChannelPrivacy(oldChannel *model.Channel, user *model.User) (*model.Channel, *model.AppError) {
|
||||
func (a *App) UpdateChannelPrivacy(c *request.Context, oldChannel *model.Channel, user *model.User) (*model.Channel, *model.AppError) {
|
||||
channel, err := a.UpdateChannel(oldChannel)
|
||||
if err != nil {
|
||||
return channel, err
|
||||
}
|
||||
|
||||
if err := a.postChannelPrivacyMessage(user, channel); err != nil {
|
||||
if err := a.postChannelPrivacyMessage(c, user, channel); err != nil {
|
||||
if channel.Type == model.CHANNEL_OPEN {
|
||||
channel.Type = model.CHANNEL_PRIVATE
|
||||
} else {
|
||||
@@ -697,7 +698,7 @@ func (a *App) UpdateChannelPrivacy(oldChannel *model.Channel, user *model.User)
|
||||
return channel, nil
|
||||
}
|
||||
|
||||
func (a *App) postChannelPrivacyMessage(user *model.User, channel *model.Channel) *model.AppError {
|
||||
func (a *App) postChannelPrivacyMessage(c *request.Context, user *model.User, channel *model.Channel) *model.AppError {
|
||||
message := (map[string]string{
|
||||
model.CHANNEL_OPEN: i18n.T("api.channel.change_channel_privacy.private_to_public"),
|
||||
model.CHANNEL_PRIVATE: i18n.T("api.channel.change_channel_privacy.public_to_private"),
|
||||
@@ -712,14 +713,14 @@ func (a *App) postChannelPrivacyMessage(user *model.User, channel *model.Channel
|
||||
},
|
||||
}
|
||||
|
||||
if _, err := a.CreatePost(post, channel, false, true); err != nil {
|
||||
if _, err := a.CreatePost(c, post, channel, false, true); err != nil {
|
||||
return model.NewAppError("postChannelPrivacyMessage", "api.channel.post_channel_privacy_message.error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) RestoreChannel(channel *model.Channel, userID string) (*model.Channel, *model.AppError) {
|
||||
func (a *App) RestoreChannel(c *request.Context, channel *model.Channel, userID string) (*model.Channel, *model.AppError) {
|
||||
if channel.DeleteAt == 0 {
|
||||
return nil, model.NewAppError("restoreChannel", "api.channel.restore_channel.restored.app_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
@@ -758,7 +759,7 @@ func (a *App) RestoreChannel(channel *model.Channel, userID string) (*model.Chan
|
||||
},
|
||||
}
|
||||
|
||||
if _, err := a.CreatePost(post, channel, false, true); err != nil {
|
||||
if _, err := a.CreatePost(c, post, channel, false, true); err != nil {
|
||||
mlog.Warn("Failed to post unarchive message", mlog.Err(err))
|
||||
}
|
||||
}
|
||||
@@ -766,7 +767,7 @@ func (a *App) RestoreChannel(channel *model.Channel, userID string) (*model.Chan
|
||||
return channel, nil
|
||||
}
|
||||
|
||||
func (a *App) PatchChannel(channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError) {
|
||||
func (a *App) PatchChannel(c *request.Context, channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError) {
|
||||
oldChannelDisplayName := channel.DisplayName
|
||||
oldChannelHeader := channel.Header
|
||||
oldChannelPurpose := channel.Purpose
|
||||
@@ -778,19 +779,19 @@ func (a *App) PatchChannel(channel *model.Channel, patch *model.ChannelPatch, us
|
||||
}
|
||||
|
||||
if oldChannelDisplayName != channel.DisplayName {
|
||||
if err = a.PostUpdateChannelDisplayNameMessage(userID, channel, oldChannelDisplayName, channel.DisplayName); err != nil {
|
||||
if err = a.PostUpdateChannelDisplayNameMessage(c, userID, channel, oldChannelDisplayName, channel.DisplayName); err != nil {
|
||||
mlog.Warn(err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
if channel.Header != oldChannelHeader {
|
||||
if err = a.PostUpdateChannelHeaderMessage(userID, channel, oldChannelHeader, channel.Header); err != nil {
|
||||
if err = a.PostUpdateChannelHeaderMessage(c, userID, channel, oldChannelHeader, channel.Header); err != nil {
|
||||
mlog.Warn(err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
if channel.Purpose != oldChannelPurpose {
|
||||
if err = a.PostUpdateChannelPurposeMessage(userID, channel, oldChannelPurpose, channel.Purpose); err != nil {
|
||||
if err = a.PostUpdateChannelPurposeMessage(c, userID, channel, oldChannelPurpose, channel.Purpose); err != nil {
|
||||
mlog.Warn(err.Error())
|
||||
}
|
||||
}
|
||||
@@ -1215,7 +1216,7 @@ func (a *App) updateChannelMember(member *model.ChannelMember) (*model.ChannelMe
|
||||
return member, nil
|
||||
}
|
||||
|
||||
func (a *App) DeleteChannel(channel *model.Channel, userID string) *model.AppError {
|
||||
func (a *App) DeleteChannel(c *request.Context, channel *model.Channel, userID string) *model.AppError {
|
||||
ihc := make(chan store.StoreResult, 1)
|
||||
ohc := make(chan store.StoreResult, 1)
|
||||
|
||||
@@ -1282,7 +1283,7 @@ func (a *App) DeleteChannel(channel *model.Channel, userID string) *model.AppErr
|
||||
},
|
||||
}
|
||||
|
||||
if _, err := a.CreatePost(post, channel, false, true); err != nil {
|
||||
if _, err := a.CreatePost(c, post, channel, false, true); err != nil {
|
||||
mlog.Warn("Failed to post archive message", mlog.Err(err))
|
||||
}
|
||||
}
|
||||
@@ -1416,7 +1417,7 @@ type ChannelMemberOpts struct {
|
||||
}
|
||||
|
||||
// AddChannelMember adds a user to a channel. It is a wrapper over AddUserToChannel.
|
||||
func (a *App) AddChannelMember(userID string, channel *model.Channel, opts ChannelMemberOpts) (*model.ChannelMember, *model.AppError) {
|
||||
func (a *App) AddChannelMember(c *request.Context, userID string, channel *model.Channel, opts ChannelMemberOpts) (*model.ChannelMember, *model.AppError) {
|
||||
if member, err := a.Srv().Store.Channel().GetMember(context.Background(), channel.Id, userID); err != nil {
|
||||
var nfErr *store.ErrNotFound
|
||||
if !errors.As(err, &nfErr) {
|
||||
@@ -1447,7 +1448,7 @@ func (a *App) AddChannelMember(userID string, channel *model.Channel, opts Chann
|
||||
|
||||
if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil {
|
||||
a.Srv().Go(func() {
|
||||
pluginContext := a.PluginContext()
|
||||
pluginContext := pluginContext(c)
|
||||
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
|
||||
hooks.UserHasJoinedChannel(pluginContext, cm, userRequestor)
|
||||
return true
|
||||
@@ -1456,10 +1457,10 @@ func (a *App) AddChannelMember(userID string, channel *model.Channel, opts Chann
|
||||
}
|
||||
|
||||
if opts.UserRequestorID == "" || userID == opts.UserRequestorID {
|
||||
a.postJoinChannelMessage(user, channel)
|
||||
a.postJoinChannelMessage(c, user, channel)
|
||||
} else {
|
||||
a.Srv().Go(func() {
|
||||
a.PostAddToChannelMessage(userRequestor, user, channel, opts.PostRootID)
|
||||
a.PostAddToChannelMessage(c, userRequestor, user, channel, opts.PostRootID)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1502,7 +1503,7 @@ func (a *App) AddDirectChannels(teamID string, user *model.User) *model.AppError
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) PostUpdateChannelHeaderMessage(userID string, channel *model.Channel, oldChannelHeader, newChannelHeader string) *model.AppError {
|
||||
func (a *App) PostUpdateChannelHeaderMessage(c *request.Context, userID string, channel *model.Channel, oldChannelHeader, newChannelHeader string) *model.AppError {
|
||||
user, err := a.Srv().Store.User().Get(context.Background(), userID)
|
||||
if err != nil {
|
||||
return model.NewAppError("PostUpdateChannelHeaderMessage", "api.channel.post_update_channel_header_message_and_forget.retrieve_user.error", nil, err.Error(), http.StatusBadRequest)
|
||||
@@ -1529,14 +1530,14 @@ func (a *App) PostUpdateChannelHeaderMessage(userID string, channel *model.Chann
|
||||
},
|
||||
}
|
||||
|
||||
if _, err := a.CreatePost(post, channel, false, true); err != nil {
|
||||
if _, err := a.CreatePost(c, post, channel, false, true); err != nil {
|
||||
return model.NewAppError("", "api.channel.post_update_channel_header_message_and_forget.post.error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) PostUpdateChannelPurposeMessage(userID string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError {
|
||||
func (a *App) PostUpdateChannelPurposeMessage(c *request.Context, userID string, channel *model.Channel, oldChannelPurpose string, newChannelPurpose string) *model.AppError {
|
||||
user, err := a.Srv().Store.User().Get(context.Background(), userID)
|
||||
if err != nil {
|
||||
return model.NewAppError("PostUpdateChannelPurposeMessage", "app.channel.post_update_channel_purpose_message.retrieve_user.error", nil, err.Error(), http.StatusBadRequest)
|
||||
@@ -1562,14 +1563,14 @@ func (a *App) PostUpdateChannelPurposeMessage(userID string, channel *model.Chan
|
||||
"new_purpose": newChannelPurpose,
|
||||
},
|
||||
}
|
||||
if _, err := a.CreatePost(post, channel, false, true); err != nil {
|
||||
if _, err := a.CreatePost(c, post, channel, false, true); err != nil {
|
||||
return model.NewAppError("", "app.channel.post_update_channel_purpose_message.post.error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) PostUpdateChannelDisplayNameMessage(userID string, channel *model.Channel, oldChannelDisplayName, newChannelDisplayName string) *model.AppError {
|
||||
func (a *App) PostUpdateChannelDisplayNameMessage(c *request.Context, userID string, channel *model.Channel, oldChannelDisplayName, newChannelDisplayName string) *model.AppError {
|
||||
user, err := a.Srv().Store.User().Get(context.Background(), userID)
|
||||
if err != nil {
|
||||
return model.NewAppError("PostUpdateChannelDisplayNameMessage", "api.channel.post_update_channel_displayname_message_and_forget.retrieve_user.error", nil, err.Error(), http.StatusBadRequest)
|
||||
@@ -1589,7 +1590,7 @@ func (a *App) PostUpdateChannelDisplayNameMessage(userID string, channel *model.
|
||||
},
|
||||
}
|
||||
|
||||
if _, err := a.CreatePost(post, channel, false, true); err != nil {
|
||||
if _, err := a.CreatePost(c, post, channel, false, true); err != nil {
|
||||
return model.NewAppError("PostUpdateChannelDisplayNameMessage", "api.channel.post_update_channel_displayname_message_and_forget.create_post.error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
@@ -1914,7 +1915,7 @@ func (a *App) GetChannelUnread(channelID, userID string) (*model.ChannelUnread,
|
||||
return channelUnread, nil
|
||||
}
|
||||
|
||||
func (a *App) JoinChannel(channel *model.Channel, userID string) *model.AppError {
|
||||
func (a *App) JoinChannel(c *request.Context, channel *model.Channel, userID string) *model.AppError {
|
||||
userChan := make(chan store.StoreResult, 1)
|
||||
memberChan := make(chan store.StoreResult, 1)
|
||||
go func() {
|
||||
@@ -1958,7 +1959,7 @@ func (a *App) JoinChannel(channel *model.Channel, userID string) *model.AppError
|
||||
|
||||
if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil {
|
||||
a.Srv().Go(func() {
|
||||
pluginContext := a.PluginContext()
|
||||
pluginContext := pluginContext(c)
|
||||
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
|
||||
hooks.UserHasJoinedChannel(pluginContext, cm, nil)
|
||||
return true
|
||||
@@ -1966,14 +1967,14 @@ func (a *App) JoinChannel(channel *model.Channel, userID string) *model.AppError
|
||||
})
|
||||
}
|
||||
|
||||
if err := a.postJoinChannelMessage(user, channel); err != nil {
|
||||
if err := a.postJoinChannelMessage(c, user, channel); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) postJoinChannelMessage(user *model.User, channel *model.Channel) *model.AppError {
|
||||
func (a *App) postJoinChannelMessage(c *request.Context, user *model.User, channel *model.Channel) *model.AppError {
|
||||
message := fmt.Sprintf(i18n.T("api.channel.join_channel.post_and_forget"), user.Username)
|
||||
postType := model.POST_JOIN_CHANNEL
|
||||
|
||||
@@ -1992,14 +1993,14 @@ func (a *App) postJoinChannelMessage(user *model.User, channel *model.Channel) *
|
||||
},
|
||||
}
|
||||
|
||||
if _, err := a.CreatePost(post, channel, false, true); err != nil {
|
||||
if _, err := a.CreatePost(c, post, channel, false, true); err != nil {
|
||||
return model.NewAppError("postJoinChannelMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) postJoinTeamMessage(user *model.User, channel *model.Channel) *model.AppError {
|
||||
func (a *App) postJoinTeamMessage(c *request.Context, user *model.User, channel *model.Channel) *model.AppError {
|
||||
post := &model.Post{
|
||||
ChannelId: channel.Id,
|
||||
Message: fmt.Sprintf(i18n.T("api.team.join_team.post_and_forget"), user.Username),
|
||||
@@ -2010,14 +2011,14 @@ func (a *App) postJoinTeamMessage(user *model.User, channel *model.Channel) *mod
|
||||
},
|
||||
}
|
||||
|
||||
if _, err := a.CreatePost(post, channel, false, true); err != nil {
|
||||
if _, err := a.CreatePost(c, post, channel, false, true); err != nil {
|
||||
return model.NewAppError("postJoinTeamMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) LeaveChannel(channelID string, userID string) *model.AppError {
|
||||
func (a *App) LeaveChannel(c *request.Context, channelID string, userID string) *model.AppError {
|
||||
sc := make(chan store.StoreResult, 1)
|
||||
go func() {
|
||||
channel, err := a.Srv().Store.Channel().Get(channelID, true)
|
||||
@@ -2078,7 +2079,7 @@ func (a *App) LeaveChannel(channelID string, userID string) *model.AppError {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := a.removeUserFromChannel(userID, userID, channel); err != nil {
|
||||
if err := a.removeUserFromChannel(c, userID, userID, channel); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -2087,13 +2088,13 @@ func (a *App) LeaveChannel(channelID string, userID string) *model.AppError {
|
||||
}
|
||||
|
||||
a.Srv().Go(func() {
|
||||
a.postLeaveChannelMessage(user, channel)
|
||||
a.postLeaveChannelMessage(c, user, channel)
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) postLeaveChannelMessage(user *model.User, channel *model.Channel) *model.AppError {
|
||||
func (a *App) postLeaveChannelMessage(c *request.Context, user *model.User, channel *model.Channel) *model.AppError {
|
||||
post := &model.Post{
|
||||
ChannelId: channel.Id,
|
||||
// Message here embeds `@username`, not just `username`, to ensure that mentions
|
||||
@@ -2107,14 +2108,14 @@ func (a *App) postLeaveChannelMessage(user *model.User, channel *model.Channel)
|
||||
},
|
||||
}
|
||||
|
||||
if _, err := a.CreatePost(post, channel, false, true); err != nil {
|
||||
if _, err := a.CreatePost(c, post, channel, false, true); err != nil {
|
||||
return model.NewAppError("postLeaveChannelMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) PostAddToChannelMessage(user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError {
|
||||
func (a *App) PostAddToChannelMessage(c *request.Context, user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError {
|
||||
message := fmt.Sprintf(i18n.T("api.channel.add_member.added"), addedUser.Username, user.Username)
|
||||
postType := model.POST_ADD_TO_CHANNEL
|
||||
|
||||
@@ -2137,14 +2138,14 @@ func (a *App) PostAddToChannelMessage(user *model.User, addedUser *model.User, c
|
||||
},
|
||||
}
|
||||
|
||||
if _, err := a.CreatePost(post, channel, false, true); err != nil {
|
||||
if _, err := a.CreatePost(c, post, channel, false, true); err != nil {
|
||||
return model.NewAppError("postAddToChannelMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) postAddToTeamMessage(user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError {
|
||||
func (a *App) postAddToTeamMessage(c *request.Context, user *model.User, addedUser *model.User, channel *model.Channel, postRootId string) *model.AppError {
|
||||
post := &model.Post{
|
||||
ChannelId: channel.Id,
|
||||
Message: fmt.Sprintf(i18n.T("api.team.add_user_to_team.added"), addedUser.Username, user.Username),
|
||||
@@ -2159,14 +2160,14 @@ func (a *App) postAddToTeamMessage(user *model.User, addedUser *model.User, chan
|
||||
},
|
||||
}
|
||||
|
||||
if _, err := a.CreatePost(post, channel, false, true); err != nil {
|
||||
if _, err := a.CreatePost(c, post, channel, false, true); err != nil {
|
||||
return model.NewAppError("postAddToTeamMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) postRemoveFromChannelMessage(removerUserId string, removedUser *model.User, channel *model.Channel) *model.AppError {
|
||||
func (a *App) postRemoveFromChannelMessage(c *request.Context, removerUserId string, removedUser *model.User, channel *model.Channel) *model.AppError {
|
||||
post := &model.Post{
|
||||
ChannelId: channel.Id,
|
||||
// Message here embeds `@username`, not just `username`, to ensure that mentions
|
||||
@@ -2181,14 +2182,14 @@ func (a *App) postRemoveFromChannelMessage(removerUserId string, removedUser *mo
|
||||
},
|
||||
}
|
||||
|
||||
if _, err := a.CreatePost(post, channel, false, true); err != nil {
|
||||
if _, err := a.CreatePost(c, post, channel, false, true); err != nil {
|
||||
return model.NewAppError("postRemoveFromChannelMessage", "api.channel.post_user_add_remove_message_and_forget.error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) removeUserFromChannel(userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError {
|
||||
func (a *App) removeUserFromChannel(c *request.Context, userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError {
|
||||
user, nErr := a.Srv().Store.User().Get(context.Background(), userIDToRemove)
|
||||
if nErr != nil {
|
||||
var nfErr *store.ErrNotFound
|
||||
@@ -2240,7 +2241,7 @@ func (a *App) removeUserFromChannel(userIDToRemove string, removerUserId string,
|
||||
return model.NewAppError("removeUserFromChannel", "api.team.remove_user_from_team.missing.app_error", nil, err.Error(), http.StatusBadRequest)
|
||||
}
|
||||
|
||||
if err = a.RemoveTeamMemberFromTeam(teamMember, removerUserId); err != nil {
|
||||
if err = a.RemoveTeamMemberFromTeam(c, teamMember, removerUserId); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -2256,7 +2257,7 @@ func (a *App) removeUserFromChannel(userIDToRemove string, removerUserId string,
|
||||
}
|
||||
|
||||
a.Srv().Go(func() {
|
||||
pluginContext := a.PluginContext()
|
||||
pluginContext := pluginContext(c)
|
||||
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
|
||||
hooks.UserHasLeftChannel(pluginContext, cm, actorUser)
|
||||
return true
|
||||
@@ -2278,10 +2279,10 @@ func (a *App) removeUserFromChannel(userIDToRemove string, removerUserId string,
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) RemoveUserFromChannel(userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError {
|
||||
func (a *App) RemoveUserFromChannel(c *request.Context, userIDToRemove string, removerUserId string, channel *model.Channel) *model.AppError {
|
||||
var err *model.AppError
|
||||
|
||||
if err = a.removeUserFromChannel(userIDToRemove, removerUserId, channel); err != nil {
|
||||
if err = a.removeUserFromChannel(c, userIDToRemove, removerUserId, channel); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -2291,12 +2292,12 @@ func (a *App) RemoveUserFromChannel(userIDToRemove string, removerUserId string,
|
||||
}
|
||||
|
||||
if userIDToRemove == removerUserId {
|
||||
if err := a.postLeaveChannelMessage(user, channel); err != nil {
|
||||
if err := a.postLeaveChannelMessage(c, user, channel); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
a.Srv().Go(func() {
|
||||
a.postRemoveFromChannelMessage(removerUserId, user, channel)
|
||||
a.postRemoveFromChannelMessage(c, removerUserId, user, channel)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2689,7 +2690,7 @@ func (a *App) RemoveAllDeactivatedMembersFromChannel(channel *model.Channel) *mo
|
||||
|
||||
// MoveChannel method is prone to data races if someone joins to channel during the move process. However this
|
||||
// function is only exposed to sysadmins and the possibility of this edge case is relatively small.
|
||||
func (a *App) MoveChannel(team *model.Team, channel *model.Channel, user *model.User) *model.AppError {
|
||||
func (a *App) MoveChannel(c *request.Context, team *model.Team, channel *model.Channel, user *model.User) *model.AppError {
|
||||
// Check that all channel members are in the destination team.
|
||||
channelMembers, err := a.GetChannelMembersPage(channel.Id, 0, 10000000)
|
||||
if err != nil {
|
||||
@@ -2777,12 +2778,12 @@ func (a *App) MoveChannel(team *model.Team, channel *model.Channel, user *model.
|
||||
}
|
||||
}
|
||||
|
||||
if err := a.RemoveUsersFromChannelNotMemberOfTeam(user, channel, team); err != nil {
|
||||
if err := a.RemoveUsersFromChannelNotMemberOfTeam(c, user, channel, team); err != nil {
|
||||
mlog.Warn("error while removing non-team member users", mlog.Err(err))
|
||||
}
|
||||
|
||||
if user != nil {
|
||||
if err := a.postChannelMoveMessage(user, channel, previousTeam); err != nil {
|
||||
if err := a.postChannelMoveMessage(c, user, channel, previousTeam); err != nil {
|
||||
mlog.Warn("error while posting move channel message", mlog.Err(err))
|
||||
}
|
||||
}
|
||||
@@ -2790,7 +2791,7 @@ func (a *App) MoveChannel(team *model.Team, channel *model.Channel, user *model.
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) postChannelMoveMessage(user *model.User, channel *model.Channel, previousTeam *model.Team) *model.AppError {
|
||||
func (a *App) postChannelMoveMessage(c *request.Context, user *model.User, channel *model.Channel, previousTeam *model.Team) *model.AppError {
|
||||
|
||||
post := &model.Post{
|
||||
ChannelId: channel.Id,
|
||||
@@ -2802,14 +2803,14 @@ func (a *App) postChannelMoveMessage(user *model.User, channel *model.Channel, p
|
||||
},
|
||||
}
|
||||
|
||||
if _, err := a.CreatePost(post, channel, false, true); err != nil {
|
||||
if _, err := a.CreatePost(c, post, channel, false, true); err != nil {
|
||||
return model.NewAppError("postChannelMoveMessage", "api.team.move_channel.post.error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) RemoveUsersFromChannelNotMemberOfTeam(remover *model.User, channel *model.Channel, team *model.Team) *model.AppError {
|
||||
func (a *App) RemoveUsersFromChannelNotMemberOfTeam(c *request.Context, remover *model.User, channel *model.Channel, team *model.Team) *model.AppError {
|
||||
channelMembers, err := a.GetChannelMembersPage(channel.Id, 0, 10000000)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -2838,7 +2839,7 @@ func (a *App) RemoveUsersFromChannelNotMemberOfTeam(remover *model.User, channel
|
||||
removerId = remover.Id
|
||||
}
|
||||
for userID := range channelMemberMap {
|
||||
if err := a.removeUserFromChannel(userID, removerId, channel); err != nil {
|
||||
if err := a.removeUserFromChannel(c, userID, removerId, channel); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ func TestPermanentDeleteChannel(t *testing.T) {
|
||||
*cfg.ServiceSettings.EnableOutgoingWebhooks = true
|
||||
})
|
||||
|
||||
channel, err := th.App.CreateChannel(&model.Channel{DisplayName: "deletion-test", Name: "deletion-test", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
|
||||
channel, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "deletion-test", Name: "deletion-test", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
|
||||
require.NotNil(t, channel, "Channel shouldn't be nil")
|
||||
require.Nil(t, err)
|
||||
defer func() {
|
||||
@@ -81,18 +81,18 @@ func TestRemoveAllDeactivatedMembersFromChannel(t *testing.T) {
|
||||
th.App.PermanentDeleteTeam(team)
|
||||
}()
|
||||
|
||||
_, _, err = th.App.AddUserToTeam(team.Id, th.BasicUser.Id, "")
|
||||
_, _, err = th.App.AddUserToTeam(th.Context, team.Id, th.BasicUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
|
||||
deacivatedUser := th.CreateUser()
|
||||
_, _, err = th.App.AddUserToTeam(team.Id, deacivatedUser.Id, "")
|
||||
_, _, err = th.App.AddUserToTeam(th.Context, team.Id, deacivatedUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.AddUserToChannel(deacivatedUser, channel, false)
|
||||
require.Nil(t, err)
|
||||
channelMembers, err := th.App.GetChannelMembersPage(channel.Id, 0, 10000000)
|
||||
require.Nil(t, err)
|
||||
require.Len(t, *channelMembers, 2)
|
||||
_, err = th.App.UpdateActive(deacivatedUser, false)
|
||||
_, err = th.App.UpdateActive(th.Context, deacivatedUser, false)
|
||||
require.Nil(t, err)
|
||||
|
||||
err = th.App.RemoveAllDeactivatedMembersFromChannel(channel)
|
||||
@@ -118,13 +118,13 @@ func TestMoveChannel(t *testing.T) {
|
||||
th.App.PermanentDeleteTeam(targetTeam)
|
||||
}()
|
||||
|
||||
_, _, err = th.App.AddUserToTeam(sourceTeam.Id, th.BasicUser.Id, "")
|
||||
_, _, err = th.App.AddUserToTeam(th.Context, sourceTeam.Id, th.BasicUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
|
||||
_, _, err = th.App.AddUserToTeam(sourceTeam.Id, th.BasicUser2.Id, "")
|
||||
_, _, err = th.App.AddUserToTeam(th.Context, sourceTeam.Id, th.BasicUser2.Id, "")
|
||||
require.Nil(t, err)
|
||||
|
||||
_, _, err = th.App.AddUserToTeam(targetTeam.Id, th.BasicUser.Id, "")
|
||||
_, _, err = th.App.AddUserToTeam(th.Context, targetTeam.Id, th.BasicUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
|
||||
_, err = th.App.AddUserToChannel(th.BasicUser, channel1, false)
|
||||
@@ -133,13 +133,13 @@ func TestMoveChannel(t *testing.T) {
|
||||
_, err = th.App.AddUserToChannel(th.BasicUser2, channel1, false)
|
||||
require.Nil(t, err)
|
||||
|
||||
err = th.App.MoveChannel(targetTeam, channel1, th.BasicUser)
|
||||
err = th.App.MoveChannel(th.Context, targetTeam, channel1, th.BasicUser)
|
||||
require.NotNil(t, err, "Should have failed due to mismatched members.")
|
||||
|
||||
_, _, err = th.App.AddUserToTeam(targetTeam.Id, th.BasicUser2.Id, "")
|
||||
_, _, err = th.App.AddUserToTeam(th.Context, targetTeam.Id, th.BasicUser2.Id, "")
|
||||
require.Nil(t, err)
|
||||
|
||||
err = th.App.MoveChannel(targetTeam, channel1, th.BasicUser)
|
||||
err = th.App.MoveChannel(th.Context, targetTeam, channel1, th.BasicUser)
|
||||
require.Nil(t, err)
|
||||
|
||||
// Test moving a channel with a deactivated user who isn't in the destination team.
|
||||
@@ -148,7 +148,7 @@ func TestMoveChannel(t *testing.T) {
|
||||
channel2 := th.CreateChannel(sourceTeam)
|
||||
defer th.App.PermanentDeleteChannel(channel2)
|
||||
|
||||
_, _, err = th.App.AddUserToTeam(sourceTeam.Id, deacivatedUser.Id, "")
|
||||
_, _, err = th.App.AddUserToTeam(th.Context, sourceTeam.Id, deacivatedUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.AddUserToChannel(th.BasicUser, channel2, false)
|
||||
require.Nil(t, err)
|
||||
@@ -156,10 +156,10 @@ func TestMoveChannel(t *testing.T) {
|
||||
_, err = th.App.AddUserToChannel(deacivatedUser, channel2, false)
|
||||
require.Nil(t, err)
|
||||
|
||||
_, err = th.App.UpdateActive(deacivatedUser, false)
|
||||
_, err = th.App.UpdateActive(th.Context, deacivatedUser, false)
|
||||
require.Nil(t, err)
|
||||
|
||||
err = th.App.MoveChannel(targetTeam, channel2, th.BasicUser)
|
||||
err = th.App.MoveChannel(th.Context, targetTeam, channel2, th.BasicUser)
|
||||
require.NotNil(t, err, "Should have failed due to mismatched deacivated member.")
|
||||
|
||||
// Test moving a channel with no members.
|
||||
@@ -171,11 +171,11 @@ func TestMoveChannel(t *testing.T) {
|
||||
CreatorId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
channel3, err = th.App.CreateChannel(channel3, false)
|
||||
channel3, err = th.App.CreateChannel(th.Context, channel3, false)
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteChannel(channel3)
|
||||
|
||||
err = th.App.MoveChannel(targetTeam, channel3, th.BasicUser)
|
||||
err = th.App.MoveChannel(th.Context, targetTeam, channel3, th.BasicUser)
|
||||
assert.Nil(t, err)
|
||||
})
|
||||
|
||||
@@ -201,7 +201,7 @@ func TestMoveChannel(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, []string{channel.Id}, category.Channels)
|
||||
|
||||
err = th.App.MoveChannel(targetTeam, channel, th.BasicUser)
|
||||
err = th.App.MoveChannel(th.Context, targetTeam, channel, th.BasicUser)
|
||||
require.Nil(t, err)
|
||||
|
||||
moved, err := th.App.GetChannel(channel.Id)
|
||||
@@ -234,11 +234,11 @@ func TestRemoveUsersFromChannelNotMemberOfTeam(t *testing.T) {
|
||||
th.App.PermanentDeleteTeam(team2)
|
||||
}()
|
||||
|
||||
_, _, err := th.App.AddUserToTeam(team.Id, th.BasicUser.Id, "")
|
||||
_, _, err := th.App.AddUserToTeam(th.Context, team.Id, th.BasicUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
_, _, err = th.App.AddUserToTeam(team2.Id, th.BasicUser.Id, "")
|
||||
_, _, err = th.App.AddUserToTeam(th.Context, team2.Id, th.BasicUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
_, _, err = th.App.AddUserToTeam(team.Id, th.BasicUser2.Id, "")
|
||||
_, _, err = th.App.AddUserToTeam(th.Context, team.Id, th.BasicUser2.Id, "")
|
||||
require.Nil(t, err)
|
||||
|
||||
_, err = th.App.AddUserToChannel(th.BasicUser, channel1, false)
|
||||
@@ -246,7 +246,7 @@ func TestRemoveUsersFromChannelNotMemberOfTeam(t *testing.T) {
|
||||
_, err = th.App.AddUserToChannel(th.BasicUser2, channel1, false)
|
||||
require.Nil(t, err)
|
||||
|
||||
err = th.App.RemoveUsersFromChannelNotMemberOfTeam(th.SystemAdminUser, channel1, team2)
|
||||
err = th.App.RemoveUsersFromChannelNotMemberOfTeam(th.Context, th.SystemAdminUser, channel1, team2)
|
||||
require.Nil(t, err)
|
||||
|
||||
channelMembers, err := th.App.GetChannelMembersPage(channel1.Id, 0, 10000000)
|
||||
@@ -273,7 +273,7 @@ func TestJoinDefaultChannelsCreatesChannelMemberHistoryRecordTownSquare(t *testi
|
||||
|
||||
// create a new user that joins the default channels
|
||||
user := th.CreateUser()
|
||||
th.App.JoinDefaultChannels(th.BasicTeam.Id, user, false, "")
|
||||
th.App.JoinDefaultChannels(th.Context, th.BasicTeam.Id, user, false, "")
|
||||
|
||||
// there should be a ChannelMemberHistory record for the user
|
||||
histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, townSquareChannelId)
|
||||
@@ -304,7 +304,7 @@ func TestJoinDefaultChannelsCreatesChannelMemberHistoryRecordOffTopic(t *testing
|
||||
|
||||
// create a new user that joins the default channels
|
||||
user := th.CreateUser()
|
||||
th.App.JoinDefaultChannels(th.BasicTeam.Id, user, false, "")
|
||||
th.App.JoinDefaultChannels(th.Context, th.BasicTeam.Id, user, false, "")
|
||||
|
||||
// there should be a ChannelMemberHistory record for the user
|
||||
histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, offTopicChannelId)
|
||||
@@ -331,7 +331,7 @@ func TestJoinDefaultChannelsExperimentalDefaultChannels(t *testing.T) {
|
||||
th.App.Config().TeamSettings.ExperimentalDefaultChannels = defaultChannelList
|
||||
|
||||
user := th.CreateUser()
|
||||
th.App.JoinDefaultChannels(th.BasicTeam.Id, user, false, "")
|
||||
th.App.JoinDefaultChannels(th.Context, th.BasicTeam.Id, user, false, "")
|
||||
|
||||
for _, channelName := range defaultChannelList {
|
||||
channel, err := th.App.GetChannelByName(channelName, th.BasicTeam.Id, false)
|
||||
@@ -377,7 +377,7 @@ func TestCreateChannelDisplayNameTrimsWhitespace(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
channel, err := th.App.CreateChannel(&model.Channel{DisplayName: " Public 1 ", Name: "public1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
|
||||
channel, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: " Public 1 ", Name: "public1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
|
||||
defer th.App.PermanentDeleteChannel(channel)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, channel.DisplayName, "Public 1")
|
||||
@@ -390,7 +390,7 @@ func TestUpdateChannelPrivacy(t *testing.T) {
|
||||
privateChannel := th.createChannel(th.BasicTeam, model.CHANNEL_PRIVATE)
|
||||
privateChannel.Type = model.CHANNEL_OPEN
|
||||
|
||||
publicChannel, err := th.App.UpdateChannelPrivacy(privateChannel, th.BasicUser)
|
||||
publicChannel, err := th.App.UpdateChannelPrivacy(th.Context, privateChannel, th.BasicUser)
|
||||
require.Nil(t, err, "Failed to update channel privacy.")
|
||||
assert.Equal(t, publicChannel.Id, privateChannel.Id)
|
||||
assert.Equal(t, publicChannel.Type, model.CHANNEL_OPEN)
|
||||
@@ -433,7 +433,7 @@ func TestCreateDirectChannelCreatesChannelMemberHistoryRecord(t *testing.T) {
|
||||
user1 := th.CreateUser()
|
||||
user2 := th.CreateUser()
|
||||
|
||||
channel, err := th.App.GetOrCreateDirectChannel(user1.Id, user2.Id)
|
||||
channel, err := th.App.GetOrCreateDirectChannel(th.Context, user1.Id, user2.Id)
|
||||
require.Nil(t, err, "Failed to create direct channel.")
|
||||
|
||||
histories, nErr := th.App.Srv().Store.ChannelMemberHistory().GetUsersInChannelDuring(model.GetMillis()-100, model.GetMillis()+100, channel.Id)
|
||||
@@ -460,7 +460,7 @@ func TestGetDirectChannelCreatesChannelMemberHistoryRecord(t *testing.T) {
|
||||
user2 := th.CreateUser()
|
||||
|
||||
// this function call implicitly creates a direct channel between the two users if one doesn't already exist
|
||||
channel, err := th.App.GetOrCreateDirectChannel(user1.Id, user2.Id)
|
||||
channel, err := th.App.GetOrCreateDirectChannel(th.Context, user1.Id, user2.Id)
|
||||
require.Nil(t, err, "Failed to create direct channel.")
|
||||
|
||||
// there should be a ChannelMemberHistory record for both users
|
||||
@@ -486,7 +486,7 @@ func TestAddUserToChannelCreatesChannelMemberHistoryRecord(t *testing.T) {
|
||||
|
||||
// create a user and add it to a channel
|
||||
user := th.CreateUser()
|
||||
_, err := th.App.AddTeamMember(th.BasicTeam.Id, user.Id)
|
||||
_, err := th.App.AddTeamMember(th.Context, th.BasicTeam.Id, user.Id)
|
||||
require.Nil(t, err, "Failed to add user to team.")
|
||||
|
||||
groupUserIds := make([]string, 0)
|
||||
@@ -523,7 +523,7 @@ func TestLeaveDefaultChannel(t *testing.T) {
|
||||
th.AddUserToChannel(th.BasicUser, townSquare)
|
||||
|
||||
t.Run("User tries to leave the default channel", func(t *testing.T) {
|
||||
err = th.App.LeaveChannel(townSquare.Id, th.BasicUser.Id)
|
||||
err = th.App.LeaveChannel(th.Context, townSquare.Id, th.BasicUser.Id)
|
||||
assert.NotNil(t, err, "It should fail to remove a regular user from the default channel")
|
||||
assert.Equal(t, err.Id, "api.channel.remove.default.app_error")
|
||||
_, err = th.App.GetChannelMember(context.Background(), townSquare.Id, th.BasicUser.Id)
|
||||
@@ -531,7 +531,7 @@ func TestLeaveDefaultChannel(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("Guest leaves the default channel", func(t *testing.T) {
|
||||
err = th.App.LeaveChannel(townSquare.Id, guest.Id)
|
||||
err = th.App.LeaveChannel(th.Context, townSquare.Id, guest.Id)
|
||||
assert.Nil(t, err, "It should allow to remove a guest user from the default channel")
|
||||
_, err = th.App.GetChannelMember(context.Background(), townSquare.Id, guest.Id)
|
||||
assert.NotNil(t, err)
|
||||
@@ -551,14 +551,14 @@ func TestLeaveLastChannel(t *testing.T) {
|
||||
th.AddUserToChannel(guest, th.BasicChannel)
|
||||
|
||||
t.Run("Guest leaves not last channel", func(t *testing.T) {
|
||||
err = th.App.LeaveChannel(townSquare.Id, guest.Id)
|
||||
err = th.App.LeaveChannel(th.Context, townSquare.Id, guest.Id)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.GetTeamMember(th.BasicTeam.Id, guest.Id)
|
||||
assert.Nil(t, err, "It should maintain the team membership")
|
||||
})
|
||||
|
||||
t.Run("Guest leaves last channel", func(t *testing.T) {
|
||||
err = th.App.LeaveChannel(th.BasicChannel.Id, guest.Id)
|
||||
err = th.App.LeaveChannel(th.Context, th.BasicChannel.Id, guest.Id)
|
||||
assert.Nil(t, err, "It should allow to remove a guest user from the default channel")
|
||||
_, err = th.App.GetChannelMember(context.Background(), th.BasicChannel.Id, guest.Id)
|
||||
assert.NotNil(t, err)
|
||||
@@ -573,7 +573,7 @@ func TestAddChannelMemberNoUserRequestor(t *testing.T) {
|
||||
|
||||
// create a user and add it to a channel
|
||||
user := th.CreateUser()
|
||||
_, err := th.App.AddTeamMember(th.BasicTeam.Id, user.Id)
|
||||
_, err := th.App.AddTeamMember(th.Context, th.BasicTeam.Id, user.Id)
|
||||
require.Nil(t, err)
|
||||
|
||||
groupUserIds := make([]string, 0)
|
||||
@@ -582,7 +582,7 @@ func TestAddChannelMemberNoUserRequestor(t *testing.T) {
|
||||
|
||||
channel := th.createChannel(th.BasicTeam, model.CHANNEL_OPEN)
|
||||
|
||||
_, err = th.App.AddChannelMember(user.Id, channel, ChannelMemberOpts{})
|
||||
_, err = th.App.AddChannelMember(th.Context, user.Id, channel, ChannelMemberOpts{})
|
||||
require.Nil(t, err, "Failed to add user to channel.")
|
||||
|
||||
// there should be a ChannelMemberHistory record for the user
|
||||
@@ -679,15 +679,15 @@ func TestFillInChannelProps(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
channelPublic1, err := th.App.CreateChannel(&model.Channel{DisplayName: "Public 1", Name: "public1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
|
||||
channelPublic1, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Public 1", Name: "public1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteChannel(channelPublic1)
|
||||
|
||||
channelPublic2, err := th.App.CreateChannel(&model.Channel{DisplayName: "Public 2", Name: "public2", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
|
||||
channelPublic2, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Public 2", Name: "public2", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteChannel(channelPublic2)
|
||||
|
||||
channelPrivate, err := th.App.CreateChannel(&model.Channel{DisplayName: "Private", Name: "private", Type: model.CHANNEL_PRIVATE, TeamId: th.BasicTeam.Id}, false)
|
||||
channelPrivate, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Private", Name: "private", Type: model.CHANNEL_PRIVATE, TeamId: th.BasicTeam.Id}, false)
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteChannel(channelPrivate)
|
||||
|
||||
@@ -698,11 +698,11 @@ func TestFillInChannelProps(t *testing.T) {
|
||||
Email: "success+" + otherTeamId + "@simulator.amazonses.com",
|
||||
Type: model.TEAM_OPEN,
|
||||
}
|
||||
otherTeam, err = th.App.CreateTeam(otherTeam)
|
||||
otherTeam, err = th.App.CreateTeam(th.Context, otherTeam)
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteTeam(otherTeam)
|
||||
|
||||
channelOtherTeam, err := th.App.CreateChannel(&model.Channel{DisplayName: "Other Team Channel", Name: "other-team", Type: model.CHANNEL_OPEN, TeamId: otherTeam.Id}, false)
|
||||
channelOtherTeam, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "Other Team Channel", Name: "other-team", Type: model.CHANNEL_OPEN, TeamId: otherTeam.Id}, false)
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteChannel(channelOtherTeam)
|
||||
|
||||
@@ -951,7 +951,7 @@ func TestGetChannelMembersTimezones(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
_, err := th.App.AddChannelMember(th.BasicUser2.Id, th.BasicChannel, ChannelMemberOpts{})
|
||||
_, err := th.App.AddChannelMember(th.Context, th.BasicUser2.Id, th.BasicChannel, ChannelMemberOpts{})
|
||||
require.Nil(t, err, "Failed to add user to channel.")
|
||||
|
||||
user := th.BasicUser
|
||||
@@ -964,14 +964,14 @@ func TestGetChannelMembersTimezones(t *testing.T) {
|
||||
th.App.UpdateUser(user2, false)
|
||||
|
||||
user3 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""}
|
||||
ruser, _ := th.App.CreateUser(&user3)
|
||||
ruser, _ := th.App.CreateUser(th.Context, &user3)
|
||||
th.App.AddUserToChannel(ruser, th.BasicChannel, false)
|
||||
|
||||
ruser.Timezone["automaticTimezone"] = "NoWhere/Island"
|
||||
th.App.UpdateUser(ruser, false)
|
||||
|
||||
user4 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""}
|
||||
ruser, _ = th.App.CreateUser(&user4)
|
||||
ruser, _ = th.App.CreateUser(th.Context, &user4)
|
||||
th.App.AddUserToChannel(ruser, th.BasicChannel, false)
|
||||
|
||||
timezones, err := th.App.GetChannelMembersTimezones(th.BasicChannel.Id)
|
||||
@@ -989,7 +989,7 @@ func TestGetChannelsForUser(t *testing.T) {
|
||||
CreatorId: th.BasicUser.Id,
|
||||
TeamId: th.BasicTeam.Id,
|
||||
}
|
||||
th.App.CreateChannel(channel, true)
|
||||
th.App.CreateChannel(th.Context, channel, true)
|
||||
defer th.App.PermanentDeleteChannel(channel)
|
||||
defer th.TearDown()
|
||||
|
||||
@@ -997,7 +997,7 @@ func TestGetChannelsForUser(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
require.Len(t, *channelList, 4)
|
||||
|
||||
th.App.DeleteChannel(channel, th.BasicUser.Id)
|
||||
th.App.DeleteChannel(th.Context, channel, th.BasicUser.Id)
|
||||
|
||||
// Now we get all the non-archived channels for the user
|
||||
channelList, err = th.App.GetChannelsForUser(th.BasicTeam.Id, th.BasicUser.Id, false, 0)
|
||||
@@ -1035,7 +1035,7 @@ func TestGetPublicChannelsForTeam(t *testing.T) {
|
||||
TeamId: team.Id,
|
||||
}
|
||||
var rchannel *model.Channel
|
||||
rchannel, err = th.App.CreateChannel(&channel, false)
|
||||
rchannel, err = th.App.CreateChannel(th.Context, &channel, false)
|
||||
require.Nil(t, err)
|
||||
require.NotNil(t, rchannel)
|
||||
defer th.App.PermanentDeleteChannel(rchannel)
|
||||
@@ -1068,7 +1068,7 @@ func TestGetPrivateChannelsForTeam(t *testing.T) {
|
||||
TeamId: team.Id,
|
||||
}
|
||||
var rchannel *model.Channel
|
||||
rchannel, err := th.App.CreateChannel(&channel, false)
|
||||
rchannel, err := th.App.CreateChannel(th.Context, &channel, false)
|
||||
require.Nil(t, err)
|
||||
require.NotNil(t, rchannel)
|
||||
defer th.App.PermanentDeleteChannel(rchannel)
|
||||
@@ -1093,9 +1093,9 @@ func TestUpdateChannelMemberRolesChangingGuest(t *testing.T) {
|
||||
|
||||
t.Run("from guest to user", func(t *testing.T) {
|
||||
user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""}
|
||||
ruser, _ := th.App.CreateGuest(&user)
|
||||
ruser, _ := th.App.CreateGuest(th.Context, &user)
|
||||
|
||||
_, _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "")
|
||||
_, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "")
|
||||
require.Nil(t, err)
|
||||
|
||||
_, err = th.App.AddUserToChannel(ruser, th.BasicChannel, false)
|
||||
@@ -1107,9 +1107,9 @@ func TestUpdateChannelMemberRolesChangingGuest(t *testing.T) {
|
||||
|
||||
t.Run("from user to guest", func(t *testing.T) {
|
||||
user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""}
|
||||
ruser, _ := th.App.CreateUser(&user)
|
||||
ruser, _ := th.App.CreateUser(th.Context, &user)
|
||||
|
||||
_, _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "")
|
||||
_, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "")
|
||||
require.Nil(t, err)
|
||||
|
||||
_, err = th.App.AddUserToChannel(ruser, th.BasicChannel, false)
|
||||
@@ -1121,9 +1121,9 @@ func TestUpdateChannelMemberRolesChangingGuest(t *testing.T) {
|
||||
|
||||
t.Run("from user to admin", func(t *testing.T) {
|
||||
user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""}
|
||||
ruser, _ := th.App.CreateUser(&user)
|
||||
ruser, _ := th.App.CreateUser(th.Context, &user)
|
||||
|
||||
_, _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "")
|
||||
_, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "")
|
||||
require.Nil(t, err)
|
||||
|
||||
_, err = th.App.AddUserToChannel(ruser, th.BasicChannel, false)
|
||||
@@ -1135,9 +1135,9 @@ func TestUpdateChannelMemberRolesChangingGuest(t *testing.T) {
|
||||
|
||||
t.Run("from guest to guest plus custom", func(t *testing.T) {
|
||||
user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""}
|
||||
ruser, _ := th.App.CreateGuest(&user)
|
||||
ruser, _ := th.App.CreateGuest(th.Context, &user)
|
||||
|
||||
_, _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "")
|
||||
_, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "")
|
||||
require.Nil(t, err)
|
||||
|
||||
_, err = th.App.AddUserToChannel(ruser, th.BasicChannel, false)
|
||||
@@ -1152,9 +1152,9 @@ func TestUpdateChannelMemberRolesChangingGuest(t *testing.T) {
|
||||
|
||||
t.Run("a guest cant have user role", func(t *testing.T) {
|
||||
user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""}
|
||||
ruser, _ := th.App.CreateGuest(&user)
|
||||
ruser, _ := th.App.CreateGuest(th.Context, &user)
|
||||
|
||||
_, _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, "")
|
||||
_, _, err := th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, ruser.Id, "")
|
||||
require.Nil(t, err)
|
||||
|
||||
_, err = th.App.AddUserToChannel(ruser, th.BasicChannel, false)
|
||||
@@ -1186,13 +1186,13 @@ func TestSearchChannelsForUser(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
c1, err := th.App.CreateChannel(&model.Channel{DisplayName: "test-dev-1", Name: "test-dev-1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
|
||||
c1, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "test-dev-1", Name: "test-dev-1", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
|
||||
require.Nil(t, err)
|
||||
|
||||
c2, err := th.App.CreateChannel(&model.Channel{DisplayName: "test-dev-2", Name: "test-dev-2", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
|
||||
c2, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "test-dev-2", Name: "test-dev-2", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
|
||||
require.Nil(t, err)
|
||||
|
||||
c3, err := th.App.CreateChannel(&model.Channel{DisplayName: "dev-3", Name: "dev-3", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
|
||||
c3, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dev-3", Name: "dev-3", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false)
|
||||
require.Nil(t, err)
|
||||
|
||||
defer func() {
|
||||
@@ -1332,7 +1332,7 @@ func TestMarkChannelAsUnreadFromPost(t *testing.T) {
|
||||
_, err := th.App.AddUserToChannel(u2, c2, false)
|
||||
require.Nil(t, err)
|
||||
|
||||
p4, err := th.App.CreatePost(&model.Post{
|
||||
p4, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: u2.Id,
|
||||
ChannelId: c2.Id,
|
||||
Message: "@" + u1.Username,
|
||||
@@ -1340,7 +1340,7 @@ func TestMarkChannelAsUnreadFromPost(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
th.CreatePost(c2)
|
||||
|
||||
th.App.CreatePost(&model.Post{
|
||||
th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: u2.Id,
|
||||
ChannelId: c2.Id,
|
||||
RootId: p4.Id,
|
||||
@@ -1367,7 +1367,7 @@ func TestMarkChannelAsUnreadFromPost(t *testing.T) {
|
||||
th.CreatePost(dc)
|
||||
th.CreatePost(dc)
|
||||
|
||||
_, err := th.App.CreatePost(&model.Post{ChannelId: dc.Id, UserId: th.BasicUser.Id, Message: "testReply", RootId: dm1.Id}, dc, false, false)
|
||||
_, err := th.App.CreatePost(th.Context, &model.Post{ChannelId: dc.Id, UserId: th.BasicUser.Id, Message: "testReply", RootId: dm1.Id}, dc, false, false)
|
||||
assert.Nil(t, err)
|
||||
|
||||
response, err := th.App.MarkChannelAsUnreadFromPost(dm1.Id, u2.Id)
|
||||
@@ -1395,14 +1395,14 @@ func TestAddUserToChannel(t *testing.T) {
|
||||
defer th.TearDown()
|
||||
|
||||
user1 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""}
|
||||
ruser1, _ := th.App.CreateUser(&user1)
|
||||
defer th.App.PermanentDeleteUser(&user1)
|
||||
ruser1, _ := th.App.CreateUser(th.Context, &user1)
|
||||
defer th.App.PermanentDeleteUser(th.Context, &user1)
|
||||
bot := th.CreateBot()
|
||||
botUser, _ := th.App.GetUser(bot.UserId)
|
||||
defer th.App.PermanentDeleteBot(botUser.Id)
|
||||
|
||||
th.App.AddTeamMember(th.BasicTeam.Id, ruser1.Id)
|
||||
th.App.AddTeamMember(th.BasicTeam.Id, bot.UserId)
|
||||
th.App.AddTeamMember(th.Context, th.BasicTeam.Id, ruser1.Id)
|
||||
th.App.AddTeamMember(th.Context, th.BasicTeam.Id, bot.UserId)
|
||||
|
||||
group := th.CreateGroup()
|
||||
|
||||
@@ -1418,7 +1418,7 @@ func TestAddUserToChannel(t *testing.T) {
|
||||
})
|
||||
require.Nil(t, err)
|
||||
|
||||
err = th.App.JoinChannel(th.BasicChannel, ruser1.Id)
|
||||
err = th.App.JoinChannel(th.Context, th.BasicChannel, ruser1.Id)
|
||||
require.Nil(t, err)
|
||||
|
||||
// verify user was added as a non-admin
|
||||
@@ -1427,9 +1427,9 @@ func TestAddUserToChannel(t *testing.T) {
|
||||
require.False(t, cm1.SchemeAdmin)
|
||||
|
||||
user2 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""}
|
||||
ruser2, _ := th.App.CreateUser(&user2)
|
||||
defer th.App.PermanentDeleteUser(&user2)
|
||||
th.App.AddTeamMember(th.BasicTeam.Id, ruser2.Id)
|
||||
ruser2, _ := th.App.CreateUser(th.Context, &user2)
|
||||
defer th.App.PermanentDeleteUser(th.Context, &user2)
|
||||
th.App.AddTeamMember(th.Context, th.BasicTeam.Id, ruser2.Id)
|
||||
|
||||
_, err = th.App.UpsertGroupMember(group.Id, user2.Id)
|
||||
require.Nil(t, err)
|
||||
@@ -1438,7 +1438,7 @@ func TestAddUserToChannel(t *testing.T) {
|
||||
_, err = th.App.UpdateGroupSyncable(gs)
|
||||
require.Nil(t, err)
|
||||
|
||||
err = th.App.JoinChannel(th.BasicChannel, ruser2.Id)
|
||||
err = th.App.JoinChannel(th.Context, th.BasicChannel, ruser2.Id)
|
||||
require.Nil(t, err)
|
||||
|
||||
// Should allow a bot to be added to a public group synced channel
|
||||
@@ -1476,15 +1476,15 @@ func TestRemoveUserFromChannel(t *testing.T) {
|
||||
defer th.TearDown()
|
||||
|
||||
user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""}
|
||||
ruser, _ := th.App.CreateUser(&user)
|
||||
defer th.App.PermanentDeleteUser(ruser)
|
||||
ruser, _ := th.App.CreateUser(th.Context, &user)
|
||||
defer th.App.PermanentDeleteUser(th.Context, ruser)
|
||||
|
||||
bot := th.CreateBot()
|
||||
botUser, _ := th.App.GetUser(bot.UserId)
|
||||
defer th.App.PermanentDeleteBot(botUser.Id)
|
||||
|
||||
th.App.AddTeamMember(th.BasicTeam.Id, ruser.Id)
|
||||
th.App.AddTeamMember(th.BasicTeam.Id, bot.UserId)
|
||||
th.App.AddTeamMember(th.Context, th.BasicTeam.Id, ruser.Id)
|
||||
th.App.AddTeamMember(th.Context, th.BasicTeam.Id, bot.UserId)
|
||||
|
||||
privateChannel := th.CreatePrivateChannel(th.BasicTeam)
|
||||
|
||||
@@ -1509,15 +1509,15 @@ func TestRemoveUserFromChannel(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
|
||||
// Should not allow a group synced user to be removed from channel
|
||||
err = th.App.RemoveUserFromChannel(ruser.Id, th.SystemAdminUser.Id, privateChannel)
|
||||
err = th.App.RemoveUserFromChannel(th.Context, ruser.Id, th.SystemAdminUser.Id, privateChannel)
|
||||
assert.Equal(t, err.Id, "api.channel.remove_members.denied")
|
||||
|
||||
// Should allow a user to remove themselves from group synced channel
|
||||
err = th.App.RemoveUserFromChannel(ruser.Id, ruser.Id, privateChannel)
|
||||
err = th.App.RemoveUserFromChannel(th.Context, ruser.Id, ruser.Id, privateChannel)
|
||||
require.Nil(t, err)
|
||||
|
||||
// Should allow a bot to be removed from a group synced channel
|
||||
err = th.App.RemoveUserFromChannel(botUser.Id, th.SystemAdminUser.Id, privateChannel)
|
||||
err = th.App.RemoveUserFromChannel(th.Context, botUser.Id, th.SystemAdminUser.Id, privateChannel)
|
||||
require.Nil(t, err)
|
||||
}
|
||||
|
||||
@@ -1969,7 +1969,7 @@ func TestMarkChannelsAsViewedPanic(t *testing.T) {
|
||||
mockStore.On("User").Return(&mockUserStore)
|
||||
mockStore.On("Channel").Return(&mockChannelStore)
|
||||
|
||||
_, err := th.App.MarkChannelsAsViewed([]string{"channelID"}, "userID", th.App.Session().Id)
|
||||
_, err := th.App.MarkChannelsAsViewed([]string{"channelID"}, "userID", th.Context.Session().Id)
|
||||
require.Nil(t, err)
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
)
|
||||
@@ -78,13 +79,13 @@ func (a *App) SendAdminUpgradeRequestEmail(username string, subscription *model.
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) CheckAndSendUserLimitWarningEmails() *model.AppError {
|
||||
func (a *App) CheckAndSendUserLimitWarningEmails(c *request.Context) *model.AppError {
|
||||
if a.Srv().License() == nil || (a.Srv().License() != nil && !*a.Srv().License().Features.Cloud) {
|
||||
// Not cloud instance, do nothing
|
||||
return nil
|
||||
}
|
||||
|
||||
subscription, err := a.Cloud().GetSubscription(a.Session().UserId)
|
||||
subscription, err := a.Cloud().GetSubscription(c.Session().UserId)
|
||||
if err != nil {
|
||||
return model.NewAppError(
|
||||
"app.CheckAndSendUserLimitWarningEmails",
|
||||
|
||||
@@ -7,36 +7,20 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/plugin"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
)
|
||||
|
||||
// registerAppClusterMessageHandlers registers the cluster message handlers that are handled by the App layer.
|
||||
//
|
||||
// The cluster event handlers are spread across this function, Server.registerClusterHandlers and
|
||||
// NewLocalCacheLayer. Be careful to not have duplicated handlers here and
|
||||
// there.
|
||||
func (a *App) registerAppClusterMessageHandlers() {
|
||||
a.Cluster().RegisterClusterMessageHandler(model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_USER, a.clusterClearSessionCacheForUserHandler)
|
||||
a.Cluster().RegisterClusterMessageHandler(model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_ALL_USERS, a.clusterClearSessionCacheForAllUsersHandler)
|
||||
a.Cluster().RegisterClusterMessageHandler(model.CLUSTER_EVENT_INSTALL_PLUGIN, a.clusterInstallPluginHandler)
|
||||
a.Cluster().RegisterClusterMessageHandler(model.CLUSTER_EVENT_REMOVE_PLUGIN, a.clusterRemovePluginHandler)
|
||||
a.Cluster().RegisterClusterMessageHandler(model.CLUSTER_EVENT_PLUGIN_EVENT, a.clusterPluginEventHandler)
|
||||
func (s *Server) clusterInstallPluginHandler(msg *model.ClusterMessage) {
|
||||
s.installPluginFromData(model.PluginEventDataFromJson(strings.NewReader(msg.Data)))
|
||||
}
|
||||
|
||||
func (a *App) clusterClearSessionCacheForUserHandler(msg *model.ClusterMessage) {
|
||||
a.ClearSessionCacheForUserSkipClusterSend(msg.Data)
|
||||
func (s *Server) clusterRemovePluginHandler(msg *model.ClusterMessage) {
|
||||
s.removePluginFromData(model.PluginEventDataFromJson(strings.NewReader(msg.Data)))
|
||||
}
|
||||
|
||||
func (a *App) clusterClearSessionCacheForAllUsersHandler(msg *model.ClusterMessage) {
|
||||
a.ClearSessionCacheForAllUsersSkipClusterSend()
|
||||
}
|
||||
|
||||
func (a *App) clusterInstallPluginHandler(msg *model.ClusterMessage) {
|
||||
a.InstallPluginFromData(model.PluginEventDataFromJson(strings.NewReader(msg.Data)))
|
||||
}
|
||||
|
||||
func (a *App) clusterPluginEventHandler(msg *model.ClusterMessage) {
|
||||
env := a.GetPluginsEnvironment()
|
||||
func (s *Server) clusterPluginEventHandler(msg *model.ClusterMessage) {
|
||||
env := s.GetPluginsEnvironment()
|
||||
if env == nil {
|
||||
return
|
||||
}
|
||||
@@ -58,17 +42,16 @@ func (a *App) clusterPluginEventHandler(msg *model.ClusterMessage) {
|
||||
return
|
||||
}
|
||||
|
||||
hooks.OnPluginClusterEvent(a.PluginContext(), model.PluginClusterEvent{
|
||||
hooks.OnPluginClusterEvent(&plugin.Context{}, model.PluginClusterEvent{
|
||||
Id: eventID,
|
||||
Data: []byte(msg.Data),
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) clusterRemovePluginHandler(msg *model.ClusterMessage) {
|
||||
a.RemovePluginFromData(model.PluginEventDataFromJson(strings.NewReader(msg.Data)))
|
||||
}
|
||||
|
||||
// registerClusterHandlers registers the cluster message handlers that are handled by the server.
|
||||
//
|
||||
// The cluster event handlers are spread across this function and NewLocalCacheLayer.
|
||||
// Be careful to not have duplicated handlers here and there.
|
||||
func (s *Server) registerClusterHandlers() {
|
||||
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_PUBLISH, s.clusterPublishHandler)
|
||||
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_UPDATE_STATUS, s.clusterUpdateStatusHandler)
|
||||
@@ -78,6 +61,11 @@ func (s *Server) registerClusterHandlers() {
|
||||
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER, s.clusterInvalidateCacheForUserHandler)
|
||||
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INVALIDATE_CACHE_FOR_USER_TEAMS, s.clusterInvalidateCacheForUserTeamsHandler)
|
||||
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_BUSY_STATE_CHANGED, s.clusterBusyStateChgHandler)
|
||||
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_USER, s.clusterClearSessionCacheForUserHandler)
|
||||
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_CLEAR_SESSION_CACHE_FOR_ALL_USERS, s.clusterClearSessionCacheForAllUsersHandler)
|
||||
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_INSTALL_PLUGIN, s.clusterInstallPluginHandler)
|
||||
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_REMOVE_PLUGIN, s.clusterRemovePluginHandler)
|
||||
s.Cluster.RegisterClusterMessageHandler(model.CLUSTER_EVENT_PLUGIN_EVENT, s.clusterPluginEventHandler)
|
||||
}
|
||||
|
||||
func (s *Server) clusterPublishHandler(msg *model.ClusterMessage) {
|
||||
@@ -136,6 +124,14 @@ func (s *Server) clearSessionCacheForAllUsersSkipClusterSend() {
|
||||
s.sessionCache.Purge()
|
||||
}
|
||||
|
||||
func (s *Server) clusterClearSessionCacheForUserHandler(msg *model.ClusterMessage) {
|
||||
s.clearSessionCacheForUserSkipClusterSend(msg.Data)
|
||||
}
|
||||
|
||||
func (s *Server) clusterClearSessionCacheForAllUsersHandler(msg *model.ClusterMessage) {
|
||||
s.clearSessionCacheForAllUsersSkipClusterSend()
|
||||
}
|
||||
|
||||
func (s *Server) clusterBusyStateChgHandler(msg *model.ClusterMessage) {
|
||||
s.serverBusyStateChanged(model.ServerBusyStateFromJson(strings.NewReader(msg.Data)))
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"sync"
|
||||
"unicode"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
@@ -27,7 +28,7 @@ const (
|
||||
type CommandProvider interface {
|
||||
GetTrigger() string
|
||||
GetCommand(a *App, T i18n.TranslateFunc) *model.Command
|
||||
DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse
|
||||
DoCommand(a *App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse
|
||||
}
|
||||
|
||||
var commandProviders = make(map[string]CommandProvider)
|
||||
@@ -46,7 +47,7 @@ func GetCommandProvider(name string) CommandProvider {
|
||||
}
|
||||
|
||||
// @openTracingParams teamID, skipSlackParsing
|
||||
func (a *App) CreateCommandPost(post *model.Post, teamID string, response *model.CommandResponse, skipSlackParsing bool) (*model.Post, *model.AppError) {
|
||||
func (a *App) CreateCommandPost(c *request.Context, post *model.Post, teamID string, response *model.CommandResponse, skipSlackParsing bool) (*model.Post, *model.AppError) {
|
||||
if skipSlackParsing {
|
||||
post.Message = response.Text
|
||||
} else {
|
||||
@@ -65,7 +66,7 @@ func (a *App) CreateCommandPost(post *model.Post, teamID string, response *model
|
||||
}
|
||||
|
||||
if response.ResponseType == model.COMMAND_RESPONSE_TYPE_IN_CHANNEL {
|
||||
return a.CreatePostMissingChannel(post, true)
|
||||
return a.CreatePostMissingChannel(c, post, true)
|
||||
}
|
||||
|
||||
if (response.ResponseType == "" || response.ResponseType == model.COMMAND_RESPONSE_TYPE_EPHEMERAL) && (response.Text != "" || response.Attachments != nil) {
|
||||
@@ -175,7 +176,7 @@ func (a *App) ListAllCommands(teamID string, T i18n.TranslateFunc) ([]*model.Com
|
||||
}
|
||||
|
||||
// @openTracingParams args
|
||||
func (a *App) ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *model.AppError) {
|
||||
func (a *App) ExecuteCommand(c *request.Context, args *model.CommandArgs) (*model.CommandResponse, *model.AppError) {
|
||||
trigger := ""
|
||||
message := ""
|
||||
index := strings.IndexFunc(args.Command, unicode.IsSpace)
|
||||
@@ -199,12 +200,12 @@ func (a *App) ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *
|
||||
args.TriggerId = triggerId
|
||||
|
||||
// Plugins can override built in and custom commands
|
||||
cmd, response, appErr := a.tryExecutePluginCommand(args)
|
||||
cmd, response, appErr := a.tryExecutePluginCommand(c, args)
|
||||
if appErr != nil {
|
||||
return nil, appErr
|
||||
} else if cmd != nil && response != nil {
|
||||
response.TriggerId = clientTriggerId
|
||||
return a.HandleCommandResponse(cmd, args, response, true)
|
||||
return a.HandleCommandResponse(c, cmd, args, response, true)
|
||||
}
|
||||
|
||||
// Custom commands can override built ins
|
||||
@@ -213,12 +214,12 @@ func (a *App) ExecuteCommand(args *model.CommandArgs) (*model.CommandResponse, *
|
||||
return nil, appErr
|
||||
} else if cmd != nil && response != nil {
|
||||
response.TriggerId = clientTriggerId
|
||||
return a.HandleCommandResponse(cmd, args, response, false)
|
||||
return a.HandleCommandResponse(c, cmd, args, response, false)
|
||||
}
|
||||
|
||||
cmd, response = a.tryExecuteBuiltInCommand(args, trigger, message)
|
||||
cmd, response = a.tryExecuteBuiltInCommand(c, args, trigger, message)
|
||||
if cmd != nil && response != nil {
|
||||
return a.HandleCommandResponse(cmd, args, response, true)
|
||||
return a.HandleCommandResponse(c, cmd, args, response, true)
|
||||
}
|
||||
|
||||
return nil, model.NewAppError("command", "api.command.execute_command.not_found.app_error", map[string]interface{}{"Trigger": trigger}, "", http.StatusNotFound)
|
||||
@@ -338,7 +339,7 @@ func (a *App) MentionsToPublicChannels(message, teamID string) model.ChannelMent
|
||||
|
||||
// tryExecuteBuiltInCommand attempts to run a built in command based on the given arguments. If no such command can be
|
||||
// found, returns nil for all arguments.
|
||||
func (a *App) tryExecuteBuiltInCommand(args *model.CommandArgs, trigger string, message string) (*model.Command, *model.CommandResponse) {
|
||||
func (a *App) tryExecuteBuiltInCommand(c *request.Context, args *model.CommandArgs, trigger string, message string) (*model.Command, *model.CommandResponse) {
|
||||
provider := GetCommandProvider(trigger)
|
||||
if provider == nil {
|
||||
return nil, nil
|
||||
@@ -349,7 +350,7 @@ func (a *App) tryExecuteBuiltInCommand(args *model.CommandArgs, trigger string,
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return cmd, provider.DoCommand(a, args, message)
|
||||
return cmd, provider.DoCommand(a, c, args, message)
|
||||
}
|
||||
|
||||
// tryExecuteCustomCommand attempts to run a custom command based on the given arguments. If no such command can be
|
||||
@@ -527,7 +528,7 @@ func (a *App) DoCommandRequest(cmd *model.Command, p url.Values) (*model.Command
|
||||
return cmd, response, nil
|
||||
}
|
||||
|
||||
func (a *App) HandleCommandResponse(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError) {
|
||||
func (a *App) HandleCommandResponse(c *request.Context, command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.CommandResponse, *model.AppError) {
|
||||
trigger := ""
|
||||
if args.Command != "" {
|
||||
parts := strings.Split(args.Command, " ")
|
||||
@@ -536,7 +537,7 @@ func (a *App) HandleCommandResponse(command *model.Command, args *model.CommandA
|
||||
}
|
||||
|
||||
var lastError *model.AppError
|
||||
_, err := a.HandleCommandResponsePost(command, args, response, builtIn)
|
||||
_, err := a.HandleCommandResponsePost(c, command, args, response, builtIn)
|
||||
|
||||
if err != nil {
|
||||
mlog.Debug("Error occurred in handling command response post", mlog.Err(err))
|
||||
@@ -545,7 +546,7 @@ func (a *App) HandleCommandResponse(command *model.Command, args *model.CommandA
|
||||
|
||||
if response.ExtraResponses != nil {
|
||||
for _, resp := range response.ExtraResponses {
|
||||
_, err := a.HandleCommandResponsePost(command, args, resp, builtIn)
|
||||
_, err := a.HandleCommandResponsePost(c, command, args, resp, builtIn)
|
||||
|
||||
if err != nil {
|
||||
mlog.Debug("Error occurred in handling command response post", mlog.Err(err))
|
||||
@@ -561,7 +562,7 @@ func (a *App) HandleCommandResponse(command *model.Command, args *model.CommandA
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func (a *App) HandleCommandResponsePost(command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.Post, *model.AppError) {
|
||||
func (a *App) HandleCommandResponsePost(c *request.Context, command *model.Command, args *model.CommandArgs, response *model.CommandResponse, builtIn bool) (*model.Post, *model.AppError) {
|
||||
post := &model.Post{}
|
||||
post.ChannelId = args.ChannelId
|
||||
post.RootId = args.RootId
|
||||
@@ -613,7 +614,7 @@ func (a *App) HandleCommandResponsePost(command *model.Command, args *model.Comm
|
||||
response.Attachments = a.ProcessSlackAttachments(response.Attachments)
|
||||
}
|
||||
|
||||
if _, err := a.CreateCommandPost(post, args.TeamId, response, response.SkipSlackParsing); err != nil {
|
||||
if _, err := a.CreateCommandPost(c, post, args.TeamId, response, response.SkipSlackParsing); err != nil {
|
||||
return post, err
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
)
|
||||
@@ -20,7 +21,7 @@ type AutocompleteDynamicArgProvider interface {
|
||||
}
|
||||
|
||||
// GetSuggestions returns suggestions for user input.
|
||||
func (a *App) GetSuggestions(commandArgs *model.CommandArgs, commands []*model.Command, roleID string) []model.AutocompleteSuggestion {
|
||||
func (a *App) GetSuggestions(c *request.Context, commandArgs *model.CommandArgs, commands []*model.Command, roleID string) []model.AutocompleteSuggestion {
|
||||
sort.Slice(commands, func(i, j int) bool {
|
||||
return strings.Compare(strings.ToLower(commands[i].Trigger), strings.ToLower(commands[j].Trigger)) < 0
|
||||
})
|
||||
@@ -34,7 +35,7 @@ func (a *App) GetSuggestions(commandArgs *model.CommandArgs, commands []*model.C
|
||||
}
|
||||
|
||||
userInput := commandArgs.Command
|
||||
suggestions := a.getSuggestions(commandArgs, autocompleteData, "", userInput, roleID)
|
||||
suggestions := a.getSuggestions(c, commandArgs, autocompleteData, "", userInput, roleID)
|
||||
for i, suggestion := range suggestions {
|
||||
for _, command := range commands {
|
||||
if strings.HasPrefix(suggestion.Complete, command.Trigger) {
|
||||
@@ -47,7 +48,7 @@ func (a *App) GetSuggestions(commandArgs *model.CommandArgs, commands []*model.C
|
||||
return suggestions
|
||||
}
|
||||
|
||||
func (a *App) getSuggestions(commandArgs *model.CommandArgs, commands []*model.AutocompleteData, inputParsed, inputToBeParsed, roleID string) []model.AutocompleteSuggestion {
|
||||
func (a *App) getSuggestions(c *request.Context, commandArgs *model.CommandArgs, commands []*model.AutocompleteData, inputParsed, inputToBeParsed, roleID string) []model.AutocompleteSuggestion {
|
||||
suggestions := []model.AutocompleteSuggestion{}
|
||||
index := strings.Index(inputToBeParsed, " ")
|
||||
|
||||
@@ -78,12 +79,12 @@ func (a *App) getSuggestions(commandArgs *model.CommandArgs, commands []*model.A
|
||||
|
||||
if len(command.Arguments) == 0 {
|
||||
// Seek recursively in subcommands
|
||||
subSuggestions := a.getSuggestions(commandArgs, command.SubCommands, parsed, toBeParsed, roleID)
|
||||
subSuggestions := a.getSuggestions(c, commandArgs, command.SubCommands, parsed, toBeParsed, roleID)
|
||||
suggestions = append(suggestions, subSuggestions...)
|
||||
continue
|
||||
}
|
||||
|
||||
found, _, _, suggestion := a.parseArguments(commandArgs, command.Arguments, parsed, toBeParsed)
|
||||
found, _, _, suggestion := a.parseArguments(c, commandArgs, command.Arguments, parsed, toBeParsed)
|
||||
if found {
|
||||
suggestions = append(suggestions, suggestion...)
|
||||
}
|
||||
@@ -92,27 +93,27 @@ func (a *App) getSuggestions(commandArgs *model.CommandArgs, commands []*model.A
|
||||
return suggestions
|
||||
}
|
||||
|
||||
func (a *App) parseArguments(commandArgs *model.CommandArgs, args []*model.AutocompleteArg, parsed, toBeParsed string) (found bool, alreadyParsed string, yetToBeParsed string, suggestions []model.AutocompleteSuggestion) {
|
||||
func (a *App) parseArguments(c *request.Context, commandArgs *model.CommandArgs, args []*model.AutocompleteArg, parsed, toBeParsed string) (found bool, alreadyParsed string, yetToBeParsed string, suggestions []model.AutocompleteSuggestion) {
|
||||
if len(args) == 0 {
|
||||
return false, parsed, toBeParsed, suggestions
|
||||
}
|
||||
|
||||
if args[0].Required {
|
||||
found, changedParsed, changedToBeParsed, suggestion := a.parseArgument(commandArgs, args[0], parsed, toBeParsed)
|
||||
found, changedParsed, changedToBeParsed, suggestion := a.parseArgument(c, commandArgs, args[0], parsed, toBeParsed)
|
||||
if found {
|
||||
suggestions = append(suggestions, suggestion...)
|
||||
return true, changedParsed, changedToBeParsed, suggestions
|
||||
}
|
||||
return a.parseArguments(commandArgs, args[1:], changedParsed, changedToBeParsed)
|
||||
return a.parseArguments(c, commandArgs, args[1:], changedParsed, changedToBeParsed)
|
||||
}
|
||||
|
||||
// Handling optional arguments. Optional argument can be inputted or not,
|
||||
// so we have to pase both cases recursively and output combined suggestions.
|
||||
foundWithOptional, changedParsedWithOptional, changedToBeParsedWithOptional, suggestionsWithOptional := a.parseArgument(commandArgs, args[0], parsed, toBeParsed)
|
||||
foundWithOptional, changedParsedWithOptional, changedToBeParsedWithOptional, suggestionsWithOptional := a.parseArgument(c, commandArgs, args[0], parsed, toBeParsed)
|
||||
if foundWithOptional {
|
||||
suggestions = append(suggestions, suggestionsWithOptional...)
|
||||
} else {
|
||||
foundWithOptionalRest, changedParsedWithOptionalRest, changedToBeParsedWithOptionalRest, suggestionsWithOptionalRest := a.parseArguments(commandArgs, args[1:], changedParsedWithOptional, changedToBeParsedWithOptional)
|
||||
foundWithOptionalRest, changedParsedWithOptionalRest, changedToBeParsedWithOptionalRest, suggestionsWithOptionalRest := a.parseArguments(c, commandArgs, args[1:], changedParsedWithOptional, changedToBeParsedWithOptional)
|
||||
if foundWithOptionalRest {
|
||||
suggestions = append(suggestions, suggestionsWithOptionalRest...)
|
||||
}
|
||||
@@ -121,7 +122,7 @@ func (a *App) parseArguments(commandArgs *model.CommandArgs, args []*model.Autoc
|
||||
changedToBeParsedWithOptional = changedToBeParsedWithOptionalRest
|
||||
}
|
||||
|
||||
foundWithoutOptional, changedParsedWithoutOptional, changedToBeParsedWithoutOptional, suggestionsWithoutOptional := a.parseArguments(commandArgs, args[1:], parsed, toBeParsed)
|
||||
foundWithoutOptional, changedParsedWithoutOptional, changedToBeParsedWithoutOptional, suggestionsWithoutOptional := a.parseArguments(c, commandArgs, args[1:], parsed, toBeParsed)
|
||||
if foundWithoutOptional {
|
||||
suggestions = append(suggestions, suggestionsWithoutOptional...)
|
||||
}
|
||||
@@ -140,7 +141,7 @@ func (a *App) parseArguments(commandArgs *model.CommandArgs, args []*model.Autoc
|
||||
return foundWithoutOptional, changedParsedWithoutOptional, changedToBeParsedWithoutOptional, suggestions
|
||||
}
|
||||
|
||||
func (a *App) parseArgument(commandArgs *model.CommandArgs, arg *model.AutocompleteArg, parsed, toBeParsed string) (found bool, alreadyParsed string, yetToBeParsed string, suggestions []model.AutocompleteSuggestion) {
|
||||
func (a *App) parseArgument(c *request.Context, commandArgs *model.CommandArgs, arg *model.AutocompleteArg, parsed, toBeParsed string) (found bool, alreadyParsed string, yetToBeParsed string, suggestions []model.AutocompleteSuggestion) {
|
||||
if arg.Name != "" { //Parse the --name first
|
||||
found, changedParsed, changedToBeParsed, suggestion := parseNamedArgument(arg, parsed, toBeParsed)
|
||||
if found {
|
||||
@@ -174,7 +175,7 @@ func (a *App) parseArgument(commandArgs *model.CommandArgs, arg *model.Autocompl
|
||||
parsed = changedParsed
|
||||
toBeParsed = changedToBeParsed
|
||||
} else if arg.Type == model.AutocompleteArgTypeDynamicList {
|
||||
found, changedParsed, changedToBeParsed, dynamicListSuggestions := a.getDynamicListArgument(commandArgs, arg, parsed, toBeParsed)
|
||||
found, changedParsed, changedToBeParsed, dynamicListSuggestions := a.getDynamicListArgument(c, commandArgs, arg, parsed, toBeParsed)
|
||||
if found {
|
||||
suggestions = append(suggestions, dynamicListSuggestions...)
|
||||
return true, changedParsed, changedToBeParsed, suggestions
|
||||
@@ -237,7 +238,7 @@ func parseStaticListArgument(arg *model.AutocompleteArg, parsed, toBeParsed stri
|
||||
return parseListItems(a.PossibleArguments, parsed, toBeParsed)
|
||||
}
|
||||
|
||||
func (a *App) getDynamicListArgument(commandArgs *model.CommandArgs, arg *model.AutocompleteArg, parsed, toBeParsed string) (found bool, alreadyParsed string, yetToBeParsed string, suggestions []model.AutocompleteSuggestion) {
|
||||
func (a *App) getDynamicListArgument(c *request.Context, commandArgs *model.CommandArgs, arg *model.AutocompleteArg, parsed, toBeParsed string) (found bool, alreadyParsed string, yetToBeParsed string, suggestions []model.AutocompleteSuggestion) {
|
||||
dynamicArg := arg.Data.(*model.AutocompleteDynamicListArg)
|
||||
|
||||
if strings.HasPrefix(dynamicArg.FetchURL, "builtin:") {
|
||||
@@ -255,7 +256,7 @@ func (a *App) getDynamicListArgument(commandArgs *model.CommandArgs, arg *model.
|
||||
|
||||
// Encode the information normally provided to a plugin slash command handler into the request parameters
|
||||
// Encode PluginContext:
|
||||
pluginContext := a.PluginContext()
|
||||
pluginContext := pluginContext(c)
|
||||
params.Add("request_id", pluginContext.RequestId)
|
||||
params.Add("session_id", pluginContext.SessionId)
|
||||
params.Add("ip_address", pluginContext.IpAddress)
|
||||
@@ -270,7 +271,7 @@ func (a *App) getDynamicListArgument(commandArgs *model.CommandArgs, arg *model.
|
||||
params.Add("user_id", commandArgs.UserId)
|
||||
params.Add("site_url", commandArgs.SiteURL)
|
||||
|
||||
resp, err := a.doPluginRequest("GET", dynamicArg.FetchURL, params, nil)
|
||||
resp, err := a.doPluginRequest(c, "GET", dynamicArg.FetchURL, params, nil)
|
||||
|
||||
if err != nil {
|
||||
a.Log().Error("Can't fetch dynamic list arguments for", mlog.String("url", dynamicArg.FetchURL), mlog.Err(err))
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
)
|
||||
@@ -207,21 +208,21 @@ func TestSuggestions(t *testing.T) {
|
||||
jira := createJiraAutocompleteData()
|
||||
emptyCmdArgs := &model.CommandArgs{}
|
||||
|
||||
suggestions := th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "ji", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "ji", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 1)
|
||||
assert.Equal(t, jira.Trigger, suggestions[0].Complete)
|
||||
assert.Equal(t, jira.Trigger, suggestions[0].Suggestion)
|
||||
assert.Equal(t, "[command]", suggestions[0].Hint)
|
||||
assert.Equal(t, jira.HelpText, suggestions[0].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira crea", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira crea", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 1)
|
||||
assert.Equal(t, "jira create", suggestions[0].Complete)
|
||||
assert.Equal(t, "create", suggestions[0].Suggestion)
|
||||
assert.Equal(t, "[issue text]", suggestions[0].Hint)
|
||||
assert.Equal(t, "Create a new Issue", suggestions[0].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira c", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira c", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 2)
|
||||
assert.Equal(t, "jira create", suggestions[1].Complete)
|
||||
assert.Equal(t, "create", suggestions[1].Suggestion)
|
||||
@@ -232,27 +233,27 @@ func TestSuggestions(t *testing.T) {
|
||||
assert.Equal(t, "[url]", suggestions[0].Hint)
|
||||
assert.Equal(t, "Connect your Mattermost account to your Jira account", suggestions[0].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 1)
|
||||
assert.Equal(t, "jira create ", suggestions[0].Complete)
|
||||
assert.Equal(t, "", suggestions[0].Suggestion)
|
||||
assert.Equal(t, "[text]", suggestions[0].Hint)
|
||||
assert.Equal(t, "This text is optional, will be inserted into the description field", suggestions[0].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create some", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create some", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 1)
|
||||
assert.Equal(t, "jira create some", suggestions[0].Complete)
|
||||
assert.Equal(t, "", suggestions[0].Suggestion)
|
||||
assert.Equal(t, "[text]", suggestions[0].Hint)
|
||||
assert.Equal(t, "This text is optional, will be inserted into the description field", suggestions[0].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create some text ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create some text ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 0)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "invalid command", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "invalid command", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 0)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira settings notifications o", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira settings notifications o", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 2)
|
||||
assert.Equal(t, "jira settings notifications On", suggestions[0].Complete)
|
||||
assert.Equal(t, "On", suggestions[0].Suggestion)
|
||||
@@ -263,48 +264,48 @@ func TestSuggestions(t *testing.T) {
|
||||
assert.Equal(t, "Turn notifications off", suggestions[1].Hint)
|
||||
assert.Equal(t, "", suggestions[1].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 11)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira ", model.SYSTEM_USER_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira ", model.SYSTEM_USER_ROLE_ID)
|
||||
assert.Len(t, suggestions, 9)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create \"some issue text", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira create \"some issue text", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 1)
|
||||
assert.Equal(t, "jira create \"some issue text", suggestions[0].Complete)
|
||||
assert.Equal(t, "", suggestions[0].Suggestion)
|
||||
assert.Equal(t, "[text]", suggestions[0].Hint)
|
||||
assert.Equal(t, "This text is optional, will be inserted into the description field", suggestions[0].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 1)
|
||||
assert.Equal(t, "jira timezone --zone ", suggestions[0].Complete)
|
||||
assert.Equal(t, "--zone", suggestions[0].Suggestion)
|
||||
assert.Equal(t, "", suggestions[0].Hint)
|
||||
assert.Equal(t, "Set timezone", suggestions[0].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 1)
|
||||
assert.Equal(t, "jira timezone --zone ", suggestions[0].Complete)
|
||||
assert.Equal(t, "--zone", suggestions[0].Suggestion)
|
||||
assert.Equal(t, "", suggestions[0].Hint)
|
||||
assert.Equal(t, "Set timezone", suggestions[0].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --zone ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --zone ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 1)
|
||||
assert.Equal(t, "jira timezone --zone ", suggestions[0].Complete)
|
||||
assert.Equal(t, "", suggestions[0].Suggestion)
|
||||
assert.Equal(t, "[UTC+07:00]", suggestions[0].Hint)
|
||||
assert.Equal(t, "Set timezone", suggestions[0].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --zone bla", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone --zone bla", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 1)
|
||||
assert.Equal(t, "jira timezone --zone bla", suggestions[0].Complete)
|
||||
assert.Equal(t, "", suggestions[0].Suggestion)
|
||||
assert.Equal(t, "[UTC+07:00]", suggestions[0].Hint)
|
||||
assert.Equal(t, "Set timezone", suggestions[0].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone bla", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{jira}, "", "jira timezone bla", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 0)
|
||||
|
||||
commandA := &model.Command{
|
||||
@@ -319,7 +320,7 @@ func TestSuggestions(t *testing.T) {
|
||||
Trigger: "charles",
|
||||
AutocompleteData: model.NewAutocompleteData("charles", "", ""),
|
||||
}
|
||||
suggestions = th.App.GetSuggestions(emptyCmdArgs, []*model.Command{commandB, commandC, commandA}, model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.GetSuggestions(th.Context, emptyCmdArgs, []*model.Command{commandB, commandC, commandA}, model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 3)
|
||||
assert.Equal(t, "alice", suggestions[0].Complete)
|
||||
assert.Equal(t, "bob", suggestions[1].Complete)
|
||||
@@ -333,14 +334,14 @@ func TestCommandWithOptionalArgs(t *testing.T) {
|
||||
command := createCommandWithOptionalArgs()
|
||||
emptyCmdArgs := &model.CommandArgs{}
|
||||
|
||||
suggestions := th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "comm", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "comm", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 1)
|
||||
assert.Equal(t, command.Trigger, suggestions[0].Complete)
|
||||
assert.Equal(t, command.Trigger, suggestions[0].Suggestion)
|
||||
assert.Equal(t, "", suggestions[0].Hint)
|
||||
assert.Equal(t, command.HelpText, suggestions[0].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 4)
|
||||
assert.Equal(t, "command subcommand1", suggestions[0].Complete)
|
||||
assert.Equal(t, "subcommand1", suggestions[0].Suggestion)
|
||||
@@ -355,7 +356,7 @@ func TestCommandWithOptionalArgs(t *testing.T) {
|
||||
assert.Equal(t, "", suggestions[2].Hint)
|
||||
assert.Equal(t, "", suggestions[2].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 2)
|
||||
assert.Equal(t, "command subcommand1 item1", suggestions[0].Complete)
|
||||
assert.Equal(t, "item1", suggestions[0].Suggestion)
|
||||
@@ -366,21 +367,21 @@ func TestCommandWithOptionalArgs(t *testing.T) {
|
||||
assert.Equal(t, "", suggestions[1].Hint)
|
||||
assert.Equal(t, "", suggestions[1].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 item1 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 item1 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 1)
|
||||
assert.Equal(t, "command subcommand1 item1 --name2 ", suggestions[0].Complete)
|
||||
assert.Equal(t, "--name2", suggestions[0].Suggestion)
|
||||
assert.Equal(t, "", suggestions[0].Hint)
|
||||
assert.Equal(t, "arg2", suggestions[0].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 item1 --name2 bla", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand1 item1 --name2 bla", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 1)
|
||||
assert.Equal(t, "command subcommand1 item1 --name2 bla", suggestions[0].Complete)
|
||||
assert.Equal(t, "", suggestions[0].Suggestion)
|
||||
assert.Equal(t, "", suggestions[0].Hint)
|
||||
assert.Equal(t, "arg2", suggestions[0].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 2)
|
||||
assert.Equal(t, "command subcommand2 --name1 ", suggestions[0].Complete)
|
||||
assert.Equal(t, "--name1", suggestions[0].Suggestion)
|
||||
@@ -391,7 +392,7 @@ func TestCommandWithOptionalArgs(t *testing.T) {
|
||||
assert.Equal(t, "", suggestions[1].Hint)
|
||||
assert.Equal(t, "arg2", suggestions[1].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 -", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 -", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 2)
|
||||
assert.Equal(t, "command subcommand2 --name1 ", suggestions[0].Complete)
|
||||
assert.Equal(t, "--name1", suggestions[0].Suggestion)
|
||||
@@ -402,7 +403,7 @@ func TestCommandWithOptionalArgs(t *testing.T) {
|
||||
assert.Equal(t, "", suggestions[1].Hint)
|
||||
assert.Equal(t, "arg2", suggestions[1].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 3)
|
||||
assert.Equal(t, "command subcommand2 --name1 item1", suggestions[0].Complete)
|
||||
assert.Equal(t, "item1", suggestions[0].Suggestion)
|
||||
@@ -417,7 +418,7 @@ func TestCommandWithOptionalArgs(t *testing.T) {
|
||||
assert.Equal(t, "", suggestions[2].Hint)
|
||||
assert.Equal(t, "arg3", suggestions[2].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 3)
|
||||
assert.Equal(t, "command subcommand2 --name1 item1", suggestions[0].Complete)
|
||||
assert.Equal(t, "item1", suggestions[0].Suggestion)
|
||||
@@ -432,24 +433,24 @@ func TestCommandWithOptionalArgs(t *testing.T) {
|
||||
assert.Equal(t, "", suggestions[2].Hint)
|
||||
assert.Equal(t, "arg3", suggestions[2].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 1)
|
||||
assert.Equal(t, "command subcommand2 --name1 item1 ", suggestions[0].Complete)
|
||||
assert.Equal(t, "", suggestions[0].Suggestion)
|
||||
assert.Equal(t, "", suggestions[0].Hint)
|
||||
assert.Equal(t, "arg2", suggestions[0].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 bla ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 bla ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 1)
|
||||
assert.Equal(t, "command subcommand2 --name1 item1 bla ", suggestions[0].Complete)
|
||||
assert.Equal(t, "", suggestions[0].Suggestion)
|
||||
assert.Equal(t, "", suggestions[0].Hint)
|
||||
assert.Equal(t, "arg3", suggestions[0].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 bla bla ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand2 --name1 item1 bla bla ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 0)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 3)
|
||||
assert.Equal(t, "command subcommand3 --name1 ", suggestions[0].Complete)
|
||||
assert.Equal(t, "--name1", suggestions[0].Suggestion)
|
||||
@@ -464,7 +465,7 @@ func TestCommandWithOptionalArgs(t *testing.T) {
|
||||
assert.Equal(t, "", suggestions[2].Hint)
|
||||
assert.Equal(t, "arg3", suggestions[2].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 --name", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 --name", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 3)
|
||||
assert.Equal(t, "command subcommand3 --name1 ", suggestions[0].Complete)
|
||||
assert.Equal(t, "--name1", suggestions[0].Suggestion)
|
||||
@@ -479,7 +480,7 @@ func TestCommandWithOptionalArgs(t *testing.T) {
|
||||
assert.Equal(t, "", suggestions[2].Hint)
|
||||
assert.Equal(t, "arg3", suggestions[2].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 --name1 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand3 --name1 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 2)
|
||||
assert.Equal(t, "command subcommand3 --name1 item1", suggestions[0].Complete)
|
||||
assert.Equal(t, "item1", suggestions[0].Suggestion)
|
||||
@@ -490,7 +491,7 @@ func TestCommandWithOptionalArgs(t *testing.T) {
|
||||
assert.Equal(t, "", suggestions[1].Hint)
|
||||
assert.Equal(t, "", suggestions[1].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand4 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand4 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 2)
|
||||
assert.Equal(t, "command subcommand4 item1", suggestions[0].Complete)
|
||||
assert.Equal(t, "item1", suggestions[0].Suggestion)
|
||||
@@ -501,7 +502,7 @@ func TestCommandWithOptionalArgs(t *testing.T) {
|
||||
assert.Equal(t, "message", suggestions[1].Hint)
|
||||
assert.Equal(t, "help4", suggestions[1].Description)
|
||||
|
||||
suggestions = th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand4 item1 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions = th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command}, "", "command subcommand4 item1 ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 1)
|
||||
assert.Equal(t, "command subcommand4 item1 ", suggestions[0].Complete)
|
||||
assert.Equal(t, "", suggestions[0].Suggestion)
|
||||
@@ -624,7 +625,7 @@ func TestDynamicListArgsForBuiltin(t *testing.T) {
|
||||
emptyCmdArgs := &model.CommandArgs{}
|
||||
|
||||
t.Run("GetAutoCompleteListItems", func(t *testing.T) {
|
||||
suggestions := th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command.AutocompleteData}, "", "bogus --dynaArg ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command.AutocompleteData}, "", "bogus --dynaArg ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Len(t, suggestions, 3)
|
||||
assert.Equal(t, "this is hint 1", suggestions[0].Hint)
|
||||
assert.Equal(t, "this is hint 2", suggestions[1].Hint)
|
||||
@@ -632,7 +633,7 @@ func TestDynamicListArgsForBuiltin(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("GetAutoCompleteListItems bad arg", func(t *testing.T) {
|
||||
suggestions := th.App.getSuggestions(emptyCmdArgs, []*model.AutocompleteData{command.AutocompleteData}, "", "bogus --badArg ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
suggestions := th.App.getSuggestions(th.Context, emptyCmdArgs, []*model.AutocompleteData{command.AutocompleteData}, "", "bogus --badArg ", model.SYSTEM_ADMIN_ROLE_ID)
|
||||
assert.Empty(t, suggestions)
|
||||
})
|
||||
}
|
||||
@@ -658,7 +659,7 @@ func (p *testCommandProvider) GetCommand(a *App, T i18n.TranslateFunc) *model.Co
|
||||
}
|
||||
}
|
||||
|
||||
func (p *testCommandProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (p *testCommandProvider) DoCommand(a *App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
return &model.CommandResponse{
|
||||
Text: "I do nothing!",
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL,
|
||||
|
||||
@@ -6,6 +6,8 @@ package app
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/plugin"
|
||||
"github.com/mattermost/mattermost-server/v5/store/sqlstore"
|
||||
)
|
||||
|
||||
@@ -13,3 +15,14 @@ import (
|
||||
func WithMaster(ctx context.Context) context.Context {
|
||||
return sqlstore.WithMaster(ctx)
|
||||
}
|
||||
|
||||
func pluginContext(c *request.Context) *plugin.Context {
|
||||
context := &plugin.Context{
|
||||
RequestId: c.RequestId(),
|
||||
SessionId: c.Session().Id,
|
||||
IpAddress: c.IpAddress(),
|
||||
AcceptLanguage: c.AcceptLanguage(),
|
||||
UserAgent: c.UserAgent(),
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
@@ -23,6 +23,10 @@ const (
|
||||
)
|
||||
|
||||
func (a *App) DownloadFromURL(downloadURL string) ([]byte, error) {
|
||||
return a.Srv().downloadFromURL(downloadURL)
|
||||
}
|
||||
|
||||
func (s *Server) downloadFromURL(downloadURL string) ([]byte, error) {
|
||||
if !model.IsValidHttpUrl(downloadURL) {
|
||||
return nil, errors.Errorf("invalid url %s", downloadURL)
|
||||
}
|
||||
@@ -31,11 +35,11 @@ func (a *App) DownloadFromURL(downloadURL string) ([]byte, error) {
|
||||
if err != nil {
|
||||
return nil, errors.Errorf("failed to parse url %s", downloadURL)
|
||||
}
|
||||
if !*a.Config().PluginSettings.AllowInsecureDownloadUrl && u.Scheme != "https" {
|
||||
if !*s.Config().PluginSettings.AllowInsecureDownloadUrl && u.Scheme != "https" {
|
||||
return nil, errors.Errorf("insecure url not allowed %s", downloadURL)
|
||||
}
|
||||
|
||||
client := a.HTTPService().MakeClient(true)
|
||||
client := s.HTTPService.MakeClient(true)
|
||||
client.Timeout = HTTPRequestTimeout
|
||||
|
||||
var resp *http.Response
|
||||
|
||||
@@ -12,9 +12,9 @@ import (
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
)
|
||||
|
||||
var accountMigrationInterface func(*App) einterfaces.AccountMigrationInterface
|
||||
var accountMigrationInterface func(*Server) einterfaces.AccountMigrationInterface
|
||||
|
||||
func RegisterAccountMigrationInterface(f func(*App) einterfaces.AccountMigrationInterface) {
|
||||
func RegisterAccountMigrationInterface(f func(*Server) einterfaces.AccountMigrationInterface) {
|
||||
accountMigrationInterface = f
|
||||
}
|
||||
|
||||
@@ -66,9 +66,9 @@ func RegisterJobsElasticsearchIndexerInterface(f func(*Server) tjobs.IndexerJobI
|
||||
jobsElasticsearchIndexerInterface = f
|
||||
}
|
||||
|
||||
var jobsLdapSyncInterface func(*App) ejobs.LdapSyncInterface
|
||||
var jobsLdapSyncInterface func(*Server) ejobs.LdapSyncInterface
|
||||
|
||||
func RegisterJobsLdapSyncInterface(f func(*App) ejobs.LdapSyncInterface) {
|
||||
func RegisterJobsLdapSyncInterface(f func(*Server) ejobs.LdapSyncInterface) {
|
||||
jobsLdapSyncInterface = f
|
||||
}
|
||||
|
||||
@@ -78,9 +78,9 @@ func RegisterJobsMigrationsJobInterface(f func(*Server) tjobs.MigrationsJobInter
|
||||
jobsMigrationsInterface = f
|
||||
}
|
||||
|
||||
var jobsPluginsInterface func(*App) tjobs.PluginsJobInterface
|
||||
var jobsPluginsInterface func(*Server) tjobs.PluginsJobInterface
|
||||
|
||||
func RegisterJobsPluginsJobInterface(f func(*App) tjobs.PluginsJobInterface) {
|
||||
func RegisterJobsPluginsJobInterface(f func(*Server) tjobs.PluginsJobInterface) {
|
||||
jobsPluginsInterface = f
|
||||
}
|
||||
|
||||
@@ -90,16 +90,16 @@ func RegisterJobsBleveIndexerInterface(f func(*Server) tjobs.IndexerJobInterface
|
||||
jobsBleveIndexerInterface = f
|
||||
}
|
||||
|
||||
var jobsActiveUsersInterface func(*App) tjobs.ActiveUsersJobInterface
|
||||
var jobsActiveUsersInterface func(*Server) tjobs.ActiveUsersJobInterface
|
||||
|
||||
func RegisterJobsActiveUsersInterface(f func(*App) tjobs.ActiveUsersJobInterface) {
|
||||
func RegisterJobsActiveUsersInterface(f func(*Server) tjobs.ActiveUsersJobInterface) {
|
||||
jobsActiveUsersInterface = f
|
||||
}
|
||||
|
||||
var jobsResendInvitationEmailInterface func(*App) ejobs.ResendInvitationEmailJobInterface
|
||||
var jobsResendInvitationEmailInterface func(*Server) ejobs.ResendInvitationEmailJobInterface
|
||||
|
||||
// RegisterJobsResendInvitationEmailInterface is used to register or initialize the jobsResendInvitationEmailInterface
|
||||
func RegisterJobsResendInvitationEmailInterface(f func(*App) ejobs.ResendInvitationEmailJobInterface) {
|
||||
func RegisterJobsResendInvitationEmailInterface(f func(*Server) ejobs.ResendInvitationEmailJobInterface) {
|
||||
jobsResendInvitationEmailInterface = f
|
||||
}
|
||||
|
||||
@@ -109,45 +109,45 @@ func RegisterJobsCloudInterface(f func(*Server) ejobs.CloudJobInterface) {
|
||||
jobsCloudInterface = f
|
||||
}
|
||||
|
||||
var jobsExpiryNotifyInterface func(*App) tjobs.ExpiryNotifyJobInterface
|
||||
var jobsExpiryNotifyInterface func(*Server) tjobs.ExpiryNotifyJobInterface
|
||||
|
||||
func RegisterJobsExpiryNotifyJobInterface(f func(*App) tjobs.ExpiryNotifyJobInterface) {
|
||||
func RegisterJobsExpiryNotifyJobInterface(f func(*Server) tjobs.ExpiryNotifyJobInterface) {
|
||||
jobsExpiryNotifyInterface = f
|
||||
}
|
||||
|
||||
var jobsImportProcessInterface func(*App) tjobs.ImportProcessInterface
|
||||
var jobsImportProcessInterface func(*Server) tjobs.ImportProcessInterface
|
||||
|
||||
func RegisterJobsImportProcessInterface(f func(*App) tjobs.ImportProcessInterface) {
|
||||
func RegisterJobsImportProcessInterface(f func(*Server) tjobs.ImportProcessInterface) {
|
||||
jobsImportProcessInterface = f
|
||||
}
|
||||
|
||||
var jobsImportDeleteInterface func(*App) tjobs.ImportDeleteInterface
|
||||
var jobsImportDeleteInterface func(*Server) tjobs.ImportDeleteInterface
|
||||
|
||||
func RegisterJobsImportDeleteInterface(f func(*App) tjobs.ImportDeleteInterface) {
|
||||
func RegisterJobsImportDeleteInterface(f func(*Server) tjobs.ImportDeleteInterface) {
|
||||
jobsImportDeleteInterface = f
|
||||
}
|
||||
|
||||
var jobsExportProcessInterface func(*App) tjobs.ExportProcessInterface
|
||||
var jobsExportProcessInterface func(*Server) tjobs.ExportProcessInterface
|
||||
|
||||
func RegisterJobsExportProcessInterface(f func(*App) tjobs.ExportProcessInterface) {
|
||||
func RegisterJobsExportProcessInterface(f func(*Server) tjobs.ExportProcessInterface) {
|
||||
jobsExportProcessInterface = f
|
||||
}
|
||||
|
||||
var jobsExportDeleteInterface func(*App) tjobs.ExportDeleteInterface
|
||||
var jobsExportDeleteInterface func(*Server) tjobs.ExportDeleteInterface
|
||||
|
||||
func RegisterJobsExportDeleteInterface(f func(*App) tjobs.ExportDeleteInterface) {
|
||||
func RegisterJobsExportDeleteInterface(f func(*Server) tjobs.ExportDeleteInterface) {
|
||||
jobsExportDeleteInterface = f
|
||||
}
|
||||
|
||||
var productNoticesJobInterface func(*App) tjobs.ProductNoticesJobInterface
|
||||
var productNoticesJobInterface func(*Server) tjobs.ProductNoticesJobInterface
|
||||
|
||||
func RegisterProductNoticesJobInterface(f func(*App) tjobs.ProductNoticesJobInterface) {
|
||||
func RegisterProductNoticesJobInterface(f func(*Server) tjobs.ProductNoticesJobInterface) {
|
||||
productNoticesJobInterface = f
|
||||
}
|
||||
|
||||
var ldapInterface func(*App) einterfaces.LdapInterface
|
||||
var ldapInterface func(*Server) einterfaces.LdapInterface
|
||||
|
||||
func RegisterLdapInterface(f func(*App) einterfaces.LdapInterface) {
|
||||
func RegisterLdapInterface(f func(*Server) einterfaces.LdapInterface) {
|
||||
ldapInterface = f
|
||||
}
|
||||
|
||||
@@ -169,15 +169,15 @@ func RegisterMetricsInterface(f func(*Server) einterfaces.MetricsInterface) {
|
||||
metricsInterface = f
|
||||
}
|
||||
|
||||
var samlInterfaceNew func(*App) einterfaces.SamlInterface
|
||||
var samlInterfaceNew func(*Server) einterfaces.SamlInterface
|
||||
|
||||
func RegisterNewSamlInterface(f func(*App) einterfaces.SamlInterface) {
|
||||
func RegisterNewSamlInterface(f func(*Server) einterfaces.SamlInterface) {
|
||||
samlInterfaceNew = f
|
||||
}
|
||||
|
||||
var notificationInterface func(*App) einterfaces.NotificationInterface
|
||||
var notificationInterface func(*Server) einterfaces.NotificationInterface
|
||||
|
||||
func RegisterNotificationInterface(f func(*App) einterfaces.NotificationInterface) {
|
||||
func RegisterNotificationInterface(f func(*Server) einterfaces.NotificationInterface) {
|
||||
notificationInterface = f
|
||||
}
|
||||
|
||||
@@ -200,26 +200,23 @@ func (s *Server) initEnterprise() {
|
||||
if elasticsearchInterface != nil {
|
||||
s.SearchEngine.RegisterElasticsearchEngine(elasticsearchInterface(s))
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) initEnterprise() {
|
||||
if accountMigrationInterface != nil {
|
||||
a.srv.AccountMigration = accountMigrationInterface(a)
|
||||
s.AccountMigration = accountMigrationInterface(s)
|
||||
}
|
||||
if ldapInterface != nil {
|
||||
a.srv.Ldap = ldapInterface(a)
|
||||
s.Ldap = ldapInterface(s)
|
||||
}
|
||||
if notificationInterface != nil {
|
||||
a.srv.Notification = notificationInterface(a)
|
||||
s.Notification = notificationInterface(s)
|
||||
}
|
||||
if samlInterfaceNew != nil {
|
||||
mlog.Debug("Loading SAML2 library")
|
||||
a.srv.Saml = samlInterfaceNew(a)
|
||||
if err := a.srv.Saml.ConfigureSP(); err != nil {
|
||||
s.Saml = samlInterfaceNew(s)
|
||||
if err := s.Saml.ConfigureSP(); err != nil {
|
||||
mlog.Error("An error occurred while configuring SAML Service Provider", mlog.Err(err))
|
||||
}
|
||||
a.AddConfigListener(func(_, cfg *model.Config) {
|
||||
if err := a.srv.Saml.ConfigureSP(); err != nil {
|
||||
s.AddConfigListener(func(_, cfg *model.Config) {
|
||||
if err := s.Saml.ConfigureSP(); err != nil {
|
||||
mlog.Error("An error occurred while configuring SAML Service Provider", mlog.Err(err))
|
||||
}
|
||||
})
|
||||
|
||||
@@ -57,7 +57,7 @@ func TestSAMLSettings(t *testing.T) {
|
||||
saml2.Mock.On("ConfigureSP").Return(nil)
|
||||
saml2.Mock.On("GetMetadata").Return("samlTwo", nil)
|
||||
if tc.setNewInterface {
|
||||
RegisterNewSamlInterface(func(a *App) einterfaces.SamlInterface {
|
||||
RegisterNewSamlInterface(func(s *Server) einterfaces.SamlInterface {
|
||||
return saml2
|
||||
})
|
||||
} else {
|
||||
@@ -65,6 +65,7 @@ func TestSAMLSettings(t *testing.T) {
|
||||
}
|
||||
|
||||
th := SetupEnterpriseWithStoreMock(t)
|
||||
|
||||
defer th.TearDown()
|
||||
|
||||
mockStore := th.App.Srv().Store.(*storemocks.Store)
|
||||
@@ -87,8 +88,6 @@ func TestSAMLSettings(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
th.Server.initEnterprise()
|
||||
th.App.initEnterprise()
|
||||
if tc.isNil {
|
||||
assert.Nil(t, th.App.Srv().Saml)
|
||||
} else {
|
||||
|
||||
@@ -39,8 +39,8 @@ func TestReactionsOfPost(t *testing.T) {
|
||||
CreateAt: model.GetMillis(),
|
||||
}
|
||||
|
||||
th.App.SaveReactionForPost(&reactionObject)
|
||||
th.App.SaveReactionForPost(&reactionObjectDeleted)
|
||||
th.App.SaveReactionForPost(th.Context, &reactionObject)
|
||||
th.App.SaveReactionForPost(th.Context, &reactionObjectDeleted)
|
||||
reactionsOfPost, err := th.App.BuildPostReactions(post.Id)
|
||||
require.Nil(t, err)
|
||||
|
||||
@@ -174,7 +174,7 @@ func TestExportAllUsers(t *testing.T) {
|
||||
|
||||
// Adding a user and deactivating it to check whether it gets included in bulk export
|
||||
user := th1.CreateUser()
|
||||
_, err := th1.App.UpdateActive(user, false)
|
||||
_, err := th1.App.UpdateActive(th1.Context, user, false)
|
||||
require.Nil(t, err)
|
||||
|
||||
var b bytes.Buffer
|
||||
@@ -183,7 +183,7 @@ func TestExportAllUsers(t *testing.T) {
|
||||
|
||||
th2 := Setup(t)
|
||||
defer th2.TearDown()
|
||||
err, i := th2.App.BulkImport(&b, false, 5)
|
||||
err, i := th2.App.BulkImport(th2.Context, &b, false, 5)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 0, i)
|
||||
|
||||
@@ -241,7 +241,7 @@ func TestExportDMChannel(t *testing.T) {
|
||||
assert.Equal(t, 0, len(channels))
|
||||
|
||||
// import the exported channel
|
||||
err, i := th2.App.BulkImport(&b, false, 5)
|
||||
err, i := th2.App.BulkImport(th2.Context, &b, false, 5)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, 0, i)
|
||||
|
||||
@@ -263,8 +263,8 @@ func TestExportDMChannel(t *testing.T) {
|
||||
require.NoError(t, nErr)
|
||||
assert.Equal(t, 1, len(channels))
|
||||
|
||||
th1.App.PermanentDeleteUser(th1.BasicUser2)
|
||||
th1.App.PermanentDeleteUser(th1.BasicUser)
|
||||
th1.App.PermanentDeleteUser(th1.Context, th1.BasicUser2)
|
||||
th1.App.PermanentDeleteUser(th1.Context, th1.BasicUser)
|
||||
|
||||
var b bytes.Buffer
|
||||
err := th1.App.BulkExport(&b, "somePath", BulkExportOpts{})
|
||||
@@ -274,7 +274,7 @@ func TestExportDMChannel(t *testing.T) {
|
||||
defer th2.TearDown()
|
||||
|
||||
// import the exported channel
|
||||
err, _ = th2.App.BulkImport(&b, true, 5)
|
||||
err, _ = th2.App.BulkImport(th2.Context, &b, true, 5)
|
||||
require.Nil(t, err)
|
||||
|
||||
channels, nErr = th2.App.Srv().Store.Channel().GetAllDirectChannelsForExportAfter(1000, "00000000")
|
||||
@@ -306,7 +306,7 @@ func TestExportDMChannelToSelf(t *testing.T) {
|
||||
assert.Equal(t, 0, len(channels))
|
||||
|
||||
// import the exported channel
|
||||
err, i := th2.App.BulkImport(&b, false, 5)
|
||||
err, i := th2.App.BulkImport(th2.Context, &b, false, 5)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 0, i)
|
||||
|
||||
@@ -378,7 +378,7 @@ func TestExportGMandDMChannels(t *testing.T) {
|
||||
assert.Equal(t, 0, len(channels))
|
||||
|
||||
// import the exported channel
|
||||
err, i := th2.App.BulkImport(&b, false, 5)
|
||||
err, i := th2.App.BulkImport(th2.Context, &b, false, 5)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 0, i)
|
||||
|
||||
@@ -415,14 +415,14 @@ func TestExportDMandGMPost(t *testing.T) {
|
||||
Message: "aa" + model.NewId() + "a",
|
||||
UserId: th1.BasicUser.Id,
|
||||
}
|
||||
th1.App.CreatePost(p1, dmChannel, false, true)
|
||||
th1.App.CreatePost(th1.Context, p1, dmChannel, false, true)
|
||||
|
||||
p2 := &model.Post{
|
||||
ChannelId: dmChannel.Id,
|
||||
Message: "bb" + model.NewId() + "a",
|
||||
UserId: th1.BasicUser.Id,
|
||||
}
|
||||
th1.App.CreatePost(p2, dmChannel, false, true)
|
||||
th1.App.CreatePost(th1.Context, p2, dmChannel, false, true)
|
||||
|
||||
// GM posts
|
||||
p3 := &model.Post{
|
||||
@@ -430,14 +430,14 @@ func TestExportDMandGMPost(t *testing.T) {
|
||||
Message: "cc" + model.NewId() + "a",
|
||||
UserId: th1.BasicUser.Id,
|
||||
}
|
||||
th1.App.CreatePost(p3, gmChannel, false, true)
|
||||
th1.App.CreatePost(th1.Context, p3, gmChannel, false, true)
|
||||
|
||||
p4 := &model.Post{
|
||||
ChannelId: gmChannel.Id,
|
||||
Message: "dd" + model.NewId() + "a",
|
||||
UserId: th1.BasicUser.Id,
|
||||
}
|
||||
th1.App.CreatePost(p4, gmChannel, false, true)
|
||||
th1.App.CreatePost(th1.Context, p4, gmChannel, false, true)
|
||||
|
||||
posts, err := th1.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000")
|
||||
require.NoError(t, err)
|
||||
@@ -457,7 +457,7 @@ func TestExportDMandGMPost(t *testing.T) {
|
||||
assert.Equal(t, 0, len(posts))
|
||||
|
||||
// import the exported posts
|
||||
appErr, i := th2.App.BulkImport(&b, false, 5)
|
||||
appErr, i := th2.App.BulkImport(th2.Context, &b, false, 5)
|
||||
assert.Nil(t, appErr)
|
||||
assert.Equal(t, 0, i)
|
||||
|
||||
@@ -500,7 +500,7 @@ func TestExportPostWithProps(t *testing.T) {
|
||||
},
|
||||
UserId: th1.BasicUser.Id,
|
||||
}
|
||||
th1.App.CreatePost(p1, dmChannel, false, true)
|
||||
th1.App.CreatePost(th1.Context, p1, dmChannel, false, true)
|
||||
|
||||
p2 := &model.Post{
|
||||
ChannelId: gmChannel.Id,
|
||||
@@ -510,7 +510,7 @@ func TestExportPostWithProps(t *testing.T) {
|
||||
},
|
||||
UserId: th1.BasicUser.Id,
|
||||
}
|
||||
th1.App.CreatePost(p2, gmChannel, false, true)
|
||||
th1.App.CreatePost(th1.Context, p2, gmChannel, false, true)
|
||||
|
||||
posts, err := th1.App.Srv().Store.Post().GetDirectPostParentsForExportAfter(1000, "0000000")
|
||||
require.NoError(t, err)
|
||||
@@ -532,7 +532,7 @@ func TestExportPostWithProps(t *testing.T) {
|
||||
assert.Len(t, posts, 0)
|
||||
|
||||
// import the exported posts
|
||||
appErr, i := th2.App.BulkImport(&b, false, 5)
|
||||
appErr, i := th2.App.BulkImport(th2.Context, &b, false, 5)
|
||||
assert.Nil(t, appErr)
|
||||
assert.Equal(t, 0, i)
|
||||
|
||||
@@ -574,7 +574,7 @@ func TestExportDMPostWithSelf(t *testing.T) {
|
||||
assert.Equal(t, 0, len(posts))
|
||||
|
||||
// import the exported posts
|
||||
err, i := th2.App.BulkImport(&b, false, 5)
|
||||
err, i := th2.App.BulkImport(th2.Context, &b, false, 5)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 0, i)
|
||||
|
||||
@@ -614,7 +614,7 @@ func TestBulkExport(t *testing.T) {
|
||||
jsonFile := extractImportFile(filepath.Join(testsDir, "import_test.zip"))
|
||||
defer jsonFile.Close()
|
||||
|
||||
appErr, _ := th.App.BulkImportWithPath(jsonFile, false, 1, dir)
|
||||
appErr, _ := th.App.BulkImportWithPath(th.Context, jsonFile, false, 1, dir)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
exportFile, err := os.Create(filepath.Join(dir, "export.zip"))
|
||||
@@ -635,6 +635,6 @@ func TestBulkExport(t *testing.T) {
|
||||
jsonFile = extractImportFile(filepath.Join(dir, "export.zip"))
|
||||
defer jsonFile.Close()
|
||||
|
||||
appErr, _ = th.App.BulkImportWithPath(jsonFile, false, 1, filepath.Join(dir, "data"))
|
||||
appErr, _ = th.App.BulkImportWithPath(th.Context, jsonFile, false, 1, filepath.Join(dir, "data"))
|
||||
require.Nil(t, appErr)
|
||||
}
|
||||
|
||||
74
app/file.go
74
app/file.go
@@ -34,6 +34,7 @@ import (
|
||||
_ "golang.org/x/image/bmp"
|
||||
_ "golang.org/x/image/tiff"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/plugin"
|
||||
"github.com/mattermost/mattermost-server/v5/services/docextractor"
|
||||
@@ -131,9 +132,8 @@ func (a *App) ReadFile(path string) ([]byte, *model.AppError) {
|
||||
return a.srv.ReadFile(path)
|
||||
}
|
||||
|
||||
// Caller must close the first return value
|
||||
func (a *App) FileReader(path string) (filestore.ReadCloseSeeker, *model.AppError) {
|
||||
backend, err := a.FileBackend()
|
||||
func (s *Server) fileReader(path string) (filestore.ReadCloseSeeker, *model.AppError) {
|
||||
backend, err := s.FileBackend()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -144,8 +144,17 @@ func (a *App) FileReader(path string) (filestore.ReadCloseSeeker, *model.AppErro
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Caller must close the first return value
|
||||
func (a *App) FileReader(path string) (filestore.ReadCloseSeeker, *model.AppError) {
|
||||
return a.Srv().fileReader(path)
|
||||
}
|
||||
|
||||
func (a *App) FileExists(path string) (bool, *model.AppError) {
|
||||
backend, err := a.FileBackend()
|
||||
return a.Srv().fileExists(path)
|
||||
}
|
||||
|
||||
func (s *Server) fileExists(path string) (bool, *model.AppError) {
|
||||
backend, err := s.FileBackend()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -194,7 +203,20 @@ func (a *App) MoveFile(oldPath, newPath string) *model.AppError {
|
||||
}
|
||||
|
||||
func (a *App) WriteFile(fr io.Reader, path string) (int64, *model.AppError) {
|
||||
return a.srv.WriteFile(fr, path)
|
||||
return a.Srv().writeFile(fr, path)
|
||||
}
|
||||
|
||||
func (s *Server) writeFile(fr io.Reader, path string) (int64, *model.AppError) {
|
||||
backend, err := s.FileBackend()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
result, nErr := backend.WriteFile(fr, path)
|
||||
if nErr != nil {
|
||||
return result, model.NewAppError("WriteFile", "api.file.write_file.app_error", nil, nErr.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (a *App) AppendFile(fr io.Reader, path string) (int64, *model.AppError) {
|
||||
@@ -211,7 +233,11 @@ func (a *App) AppendFile(fr io.Reader, path string) (int64, *model.AppError) {
|
||||
}
|
||||
|
||||
func (a *App) RemoveFile(path string) *model.AppError {
|
||||
backend, err := a.FileBackend()
|
||||
return a.Srv().removeFile(path)
|
||||
}
|
||||
|
||||
func (s *Server) removeFile(path string) *model.AppError {
|
||||
backend, err := s.FileBackend()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -223,7 +249,11 @@ func (a *App) RemoveFile(path string) *model.AppError {
|
||||
}
|
||||
|
||||
func (a *App) ListDirectory(path string) ([]string, *model.AppError) {
|
||||
backend, err := a.FileBackend()
|
||||
return a.Srv().listDirectory(path)
|
||||
}
|
||||
|
||||
func (s *Server) listDirectory(path string) ([]string, *model.AppError) {
|
||||
backend, err := s.FileBackend()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -474,7 +504,7 @@ func GeneratePublicLinkHash(fileID, salt string) string {
|
||||
return base64.RawURLEncoding.EncodeToString(hash.Sum(nil))
|
||||
}
|
||||
|
||||
func (a *App) UploadMultipartFiles(teamID string, channelID string, userID string, fileHeaders []*multipart.FileHeader, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) {
|
||||
func (a *App) UploadMultipartFiles(c *request.Context, teamID string, channelID string, userID string, fileHeaders []*multipart.FileHeader, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) {
|
||||
files := make([]io.ReadCloser, len(fileHeaders))
|
||||
filenames := make([]string, len(fileHeaders))
|
||||
|
||||
@@ -492,13 +522,13 @@ func (a *App) UploadMultipartFiles(teamID string, channelID string, userID strin
|
||||
filenames[i] = fileHeader.Filename
|
||||
}
|
||||
|
||||
return a.UploadFiles(teamID, channelID, userID, files, filenames, clientIds, now)
|
||||
return a.UploadFiles(c, teamID, channelID, userID, files, filenames, clientIds, now)
|
||||
}
|
||||
|
||||
// Uploads some files to the given team and channel as the given user. files and filenames should have
|
||||
// the same length. clientIds should either not be provided or have the same length as files and filenames.
|
||||
// The provided files should be closed by the caller so that they are not leaked.
|
||||
func (a *App) UploadFiles(teamID string, channelID string, userID string, files []io.ReadCloser, filenames []string, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) {
|
||||
func (a *App) UploadFiles(c *request.Context, teamID string, channelID string, userID string, files []io.ReadCloser, filenames []string, clientIds []string, now time.Time) (*model.FileUploadResponse, *model.AppError) {
|
||||
if *a.Config().FileSettings.DriverName == "" {
|
||||
return nil, model.NewAppError("UploadFiles", "api.file.upload_file.storage.app_error", nil, "", http.StatusNotImplemented)
|
||||
}
|
||||
@@ -521,7 +551,7 @@ func (a *App) UploadFiles(teamID string, channelID string, userID string, files
|
||||
io.Copy(buf, file)
|
||||
data := buf.Bytes()
|
||||
|
||||
info, data, err := a.DoUploadFileExpectModification(now, teamID, channelID, userID, filenames[i], data)
|
||||
info, data, err := a.DoUploadFileExpectModification(c, now, teamID, channelID, userID, filenames[i], data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -545,14 +575,14 @@ func (a *App) UploadFiles(teamID string, channelID string, userID string, files
|
||||
}
|
||||
|
||||
// UploadFile uploads a single file in form of a completely constructed byte array for a channel.
|
||||
func (a *App) UploadFile(data []byte, channelID string, filename string) (*model.FileInfo, *model.AppError) {
|
||||
func (a *App) UploadFile(c *request.Context, data []byte, channelID string, filename string) (*model.FileInfo, *model.AppError) {
|
||||
_, err := a.GetChannel(channelID)
|
||||
if err != nil && channelID != "" {
|
||||
return nil, model.NewAppError("UploadFile", "api.file.upload_file.incorrect_channelId.app_error",
|
||||
map[string]interface{}{"channelId": channelID}, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
info, _, appError := a.DoUploadFileExpectModification(time.Now(), "noteam", channelID, "nouser", filename, data)
|
||||
info, _, appError := a.DoUploadFileExpectModification(c, time.Now(), "noteam", channelID, "nouser", filename, data)
|
||||
if appError != nil {
|
||||
return nil, appError
|
||||
}
|
||||
@@ -568,8 +598,8 @@ func (a *App) UploadFile(data []byte, channelID string, filename string) (*model
|
||||
return info, nil
|
||||
}
|
||||
|
||||
func (a *App) DoUploadFile(now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, *model.AppError) {
|
||||
info, _, err := a.DoUploadFileExpectModification(now, rawTeamId, rawChannelId, rawUserId, rawFilename, data)
|
||||
func (a *App) DoUploadFile(c *request.Context, now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, *model.AppError) {
|
||||
info, _, err := a.DoUploadFileExpectModification(c, now, rawTeamId, rawChannelId, rawUserId, rawFilename, data)
|
||||
return info, err
|
||||
}
|
||||
|
||||
@@ -691,7 +721,7 @@ func (t *UploadFileTask) init(a *App) {
|
||||
// returns a filled-out FileInfo and an optional error. A plugin may reject the
|
||||
// upload, returning a rejection error. In this case FileInfo would have
|
||||
// contained the last "good" FileInfo before the execution of that plugin.
|
||||
func (a *App) UploadFileX(channelID, name string, input io.Reader,
|
||||
func (a *App) UploadFileX(c *request.Context, channelID, name string, input io.Reader,
|
||||
opts ...func(*UploadFileTask)) (*model.FileInfo, *model.AppError) {
|
||||
|
||||
t := &UploadFileTask{
|
||||
@@ -741,7 +771,7 @@ func (a *App) UploadFileX(channelID, name string, input io.Reader,
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
aerr = a.runPluginsHook(t.fileinfo, file)
|
||||
aerr = a.runPluginsHook(c, t.fileinfo, file)
|
||||
if aerr != nil {
|
||||
return nil, aerr
|
||||
}
|
||||
@@ -942,7 +972,7 @@ func (t UploadFileTask) newAppError(id string, httpStatus int, extra ...interfac
|
||||
return model.NewAppError("uploadFileTask", id, params, "", httpStatus)
|
||||
}
|
||||
|
||||
func (a *App) DoUploadFileExpectModification(now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, []byte, *model.AppError) {
|
||||
func (a *App) DoUploadFileExpectModification(c *request.Context, now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, []byte, *model.AppError) {
|
||||
filename := filepath.Base(rawFilename)
|
||||
teamID := filepath.Base(rawTeamId)
|
||||
channelID := filepath.Base(rawChannelId)
|
||||
@@ -986,7 +1016,7 @@ func (a *App) DoUploadFileExpectModification(now time.Time, rawTeamId string, ra
|
||||
|
||||
if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil {
|
||||
var rejectionError *model.AppError
|
||||
pluginContext := a.PluginContext()
|
||||
pluginContext := pluginContext(c)
|
||||
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
|
||||
var newBytes bytes.Buffer
|
||||
replacementInfo, rejectionReason := hooks.FileWillBeUploaded(pluginContext, info, bytes.NewReader(data), &newBytes)
|
||||
@@ -1322,7 +1352,7 @@ func populateZipfile(w *zip.Writer, fileDatas []model.FileData) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) SearchFilesInTeamForUser(terms string, userId string, teamId string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int) (*model.FileInfoList, *model.AppError) {
|
||||
func (a *App) SearchFilesInTeamForUser(c *request.Context, terms string, userId string, teamId string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int) (*model.FileInfoList, *model.AppError) {
|
||||
paramsList := model.ParseSearchParams(strings.TrimSpace(terms), timeZoneOffset)
|
||||
includeDeleted := includeDeletedChannels && *a.Config().TeamSettings.ExperimentalViewArchivedChannels
|
||||
|
||||
@@ -1338,8 +1368,8 @@ func (a *App) SearchFilesInTeamForUser(terms string, userId string, teamId strin
|
||||
// Don't allow users to search for "*"
|
||||
if params.Terms != "*" {
|
||||
// Convert channel names to channel IDs
|
||||
params.InChannels = a.convertChannelNamesToChannelIds(params.InChannels, userId, teamId, includeDeletedChannels)
|
||||
params.ExcludedChannels = a.convertChannelNamesToChannelIds(params.ExcludedChannels, userId, teamId, includeDeletedChannels)
|
||||
params.InChannels = a.convertChannelNamesToChannelIds(c, params.InChannels, userId, teamId, includeDeletedChannels)
|
||||
params.ExcludedChannels = a.convertChannelNamesToChannelIds(c, params.ExcludedChannels, userId, teamId, includeDeletedChannels)
|
||||
|
||||
// Convert usernames to user IDs
|
||||
params.FromUsers = a.convertUserNameToUserIds(params.FromUsers)
|
||||
|
||||
@@ -86,7 +86,7 @@ func BenchmarkUploadFile(b *testing.B) {
|
||||
{
|
||||
title: "raw-ish DoUploadFile",
|
||||
f: func(b *testing.B, n int, data []byte, ext string) {
|
||||
info1, err := th.App.DoUploadFile(time.Now(), teamID, channelID,
|
||||
info1, err := th.App.DoUploadFile(th.Context, time.Now(), teamID, channelID,
|
||||
userID, fmt.Sprintf("BenchmarkDoUploadFile-%d%s", n, ext), data)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
@@ -99,7 +99,7 @@ func BenchmarkUploadFile(b *testing.B) {
|
||||
{
|
||||
title: "raw UploadFileX Content-Length",
|
||||
f: func(b *testing.B, n int, data []byte, ext string) {
|
||||
info, aerr := th.App.UploadFileX(channelID,
|
||||
info, aerr := th.App.UploadFileX(th.Context, channelID,
|
||||
fmt.Sprintf("BenchmarkUploadFileTask-%d%s", n, ext),
|
||||
bytes.NewReader(data),
|
||||
UploadFileSetTeamId(teamID),
|
||||
@@ -117,7 +117,7 @@ func BenchmarkUploadFile(b *testing.B) {
|
||||
{
|
||||
title: "raw UploadFileX chunked",
|
||||
f: func(b *testing.B, n int, data []byte, ext string) {
|
||||
info, aerr := th.App.UploadFileX(channelID,
|
||||
info, aerr := th.App.UploadFileX(th.Context, channelID,
|
||||
fmt.Sprintf("BenchmarkUploadFileTask-%d%s", n, ext),
|
||||
bytes.NewReader(data),
|
||||
UploadFileSetTeamId(teamID),
|
||||
@@ -135,7 +135,7 @@ func BenchmarkUploadFile(b *testing.B) {
|
||||
{
|
||||
title: "image UploadFiles",
|
||||
f: func(b *testing.B, n int, data []byte, ext string) {
|
||||
resp, err := th.App.UploadFiles(teamID, channelID, userID,
|
||||
resp, err := th.App.UploadFiles(th.Context, teamID, channelID, userID,
|
||||
[]io.ReadCloser{ioutil.NopCloser(bytes.NewReader(data))},
|
||||
[]string{fmt.Sprintf("BenchmarkDoUploadFiles-%d%s", n, ext)},
|
||||
[]string{},
|
||||
@@ -150,7 +150,7 @@ func BenchmarkUploadFile(b *testing.B) {
|
||||
{
|
||||
title: "image UploadFileX Content-Length",
|
||||
f: func(b *testing.B, n int, data []byte, ext string) {
|
||||
info, aerr := th.App.UploadFileX(channelID,
|
||||
info, aerr := th.App.UploadFileX(th.Context, channelID,
|
||||
fmt.Sprintf("BenchmarkUploadFileTask-%d%s", n, ext),
|
||||
bytes.NewReader(data),
|
||||
UploadFileSetTeamId(teamID),
|
||||
@@ -167,7 +167,7 @@ func BenchmarkUploadFile(b *testing.B) {
|
||||
{
|
||||
title: "image UploadFileX chunked",
|
||||
f: func(b *testing.B, n int, data []byte, ext string) {
|
||||
info, aerr := th.App.UploadFileX(channelID,
|
||||
info, aerr := th.App.UploadFileX(th.Context, channelID,
|
||||
fmt.Sprintf("BenchmarkUploadFileTask-%d%s", n, ext),
|
||||
bytes.NewReader(data),
|
||||
UploadFileSetTeamId(teamID),
|
||||
|
||||
@@ -50,7 +50,7 @@ func TestDoUploadFile(t *testing.T) {
|
||||
filename := "test"
|
||||
data := []byte("abcd")
|
||||
|
||||
info1, err := th.App.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data)
|
||||
info1, err := th.App.DoUploadFile(th.Context, time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data)
|
||||
require.Nil(t, err, "DoUploadFile should succeed with valid data")
|
||||
defer func() {
|
||||
th.App.Srv().Store.FileInfo().PermanentDelete(info1.Id)
|
||||
@@ -60,7 +60,7 @@ func TestDoUploadFile(t *testing.T) {
|
||||
value := fmt.Sprintf("20070204/teams/%v/channels/%v/users/%v/%v/%v", teamID, channelID, userID, info1.Id, filename)
|
||||
assert.Equal(t, value, info1.Path, "stored file at incorrect path")
|
||||
|
||||
info2, err := th.App.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data)
|
||||
info2, err := th.App.DoUploadFile(th.Context, time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data)
|
||||
require.Nil(t, err, "DoUploadFile should succeed with valid data")
|
||||
defer func() {
|
||||
th.App.Srv().Store.FileInfo().PermanentDelete(info2.Id)
|
||||
@@ -70,7 +70,7 @@ func TestDoUploadFile(t *testing.T) {
|
||||
value = fmt.Sprintf("20070204/teams/%v/channels/%v/users/%v/%v/%v", teamID, channelID, userID, info2.Id, filename)
|
||||
assert.Equal(t, value, info2.Path, "stored file at incorrect path")
|
||||
|
||||
info3, err := th.App.DoUploadFile(time.Date(2008, 3, 5, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data)
|
||||
info3, err := th.App.DoUploadFile(th.Context, time.Date(2008, 3, 5, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data)
|
||||
require.Nil(t, err, "DoUploadFile should succeed with valid data")
|
||||
defer func() {
|
||||
th.App.Srv().Store.FileInfo().PermanentDelete(info3.Id)
|
||||
@@ -80,7 +80,7 @@ func TestDoUploadFile(t *testing.T) {
|
||||
value = fmt.Sprintf("20080305/teams/%v/channels/%v/users/%v/%v/%v", teamID, channelID, userID, info3.Id, filename)
|
||||
assert.Equal(t, value, info3.Path, "stored file at incorrect path")
|
||||
|
||||
info4, err := th.App.DoUploadFile(time.Date(2009, 3, 5, 1, 2, 3, 4, time.Local), "../../"+teamID, "../../"+channelID, "../../"+userID, "../../"+filename, data)
|
||||
info4, err := th.App.DoUploadFile(th.Context, time.Date(2009, 3, 5, 1, 2, 3, 4, time.Local), "../../"+teamID, "../../"+channelID, "../../"+userID, "../../"+filename, data)
|
||||
require.Nil(t, err, "DoUploadFile should succeed with valid data")
|
||||
defer func() {
|
||||
th.App.Srv().Store.FileInfo().PermanentDelete(info4.Id)
|
||||
@@ -99,15 +99,15 @@ func TestUploadFile(t *testing.T) {
|
||||
filename := "test"
|
||||
data := []byte("abcd")
|
||||
|
||||
info1, err := th.App.UploadFile(data, "wrong", filename)
|
||||
info1, err := th.App.UploadFile(th.Context, data, "wrong", filename)
|
||||
require.NotNil(t, err, "Wrong Channel ID.")
|
||||
require.Nil(t, info1, "Channel ID does not exist.")
|
||||
|
||||
info1, err = th.App.UploadFile(data, "", filename)
|
||||
info1, err = th.App.UploadFile(th.Context, data, "", filename)
|
||||
require.Nil(t, err, "empty channel IDs should be valid")
|
||||
require.NotNil(t, info1)
|
||||
|
||||
info1, err = th.App.UploadFile(data, channelID, filename)
|
||||
info1, err = th.App.UploadFile(th.Context, data, channelID, filename)
|
||||
require.Nil(t, err, "UploadFile should succeed with valid data")
|
||||
defer func() {
|
||||
th.App.Srv().Store.FileInfo().PermanentDelete(info1.Id)
|
||||
@@ -234,7 +234,7 @@ func TestFindTeamIdForFilename(t *testing.T) {
|
||||
teamID := th.App.findTeamIdForFilename(th.BasicPost, "someid", "somefile.png")
|
||||
assert.Equal(t, th.BasicTeam.Id, teamID)
|
||||
|
||||
_, err := th.App.CreateTeamWithUser(&model.Team{Email: th.BasicUser.Email, Name: "zz" + model.NewId(), DisplayName: "Joram's Test Team", Type: model.TEAM_OPEN}, th.BasicUser.Id)
|
||||
_, err := th.App.CreateTeamWithUser(th.Context, &model.Team{Email: th.BasicUser.Email, Name: "zz" + model.NewId(), DisplayName: "Joram's Test Team", Type: model.TEAM_OPEN}, th.BasicUser.Id)
|
||||
require.Nil(t, err)
|
||||
|
||||
teamID = th.App.findTeamIdForFilename(th.BasicPost, "someid", "somefile.png")
|
||||
@@ -262,13 +262,13 @@ func TestMigrateFilenamesToFileInfos(t *testing.T) {
|
||||
fpath := fmt.Sprintf("/teams/%v/channels/%v/users/%v/%v/test.png", th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, fileID)
|
||||
_, err := th.App.WriteFile(file, fpath)
|
||||
require.Nil(t, err)
|
||||
rpost, err := th.App.CreatePost(&model.Post{UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Filenames: []string{fmt.Sprintf("/%v/%v/%v/test.png", th.BasicChannel.Id, th.BasicUser.Id, fileID)}}, th.BasicChannel, false, true)
|
||||
rpost, err := th.App.CreatePost(th.Context, &model.Post{UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Filenames: []string{fmt.Sprintf("/%v/%v/%v/test.png", th.BasicChannel.Id, th.BasicUser.Id, fileID)}}, th.BasicChannel, false, true)
|
||||
require.Nil(t, err)
|
||||
|
||||
infos = th.App.MigrateFilenamesToFileInfos(rpost)
|
||||
assert.Equal(t, 1, len(infos))
|
||||
|
||||
rpost, err = th.App.CreatePost(&model.Post{UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Filenames: []string{fmt.Sprintf("/%v/%v/%v/../../test.png", th.BasicChannel.Id, th.BasicUser.Id, fileID)}}, th.BasicChannel, false, true)
|
||||
rpost, err = th.App.CreatePost(th.Context, &model.Post{UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Filenames: []string{fmt.Sprintf("/%v/%v/%v/../../test.png", th.BasicChannel.Id, th.BasicUser.Id, fileID)}}, th.BasicChannel, false, true)
|
||||
require.Nil(t, err)
|
||||
|
||||
infos = th.App.MigrateFilenamesToFileInfos(rpost)
|
||||
@@ -303,7 +303,7 @@ func TestCopyFileInfos(t *testing.T) {
|
||||
filename := "test"
|
||||
data := []byte("abcd")
|
||||
|
||||
info1, err := th.App.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data)
|
||||
info1, err := th.App.DoUploadFile(th.Context, time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data)
|
||||
require.Nil(t, err)
|
||||
defer func() {
|
||||
th.App.Srv().Store.FileInfo().PermanentDelete(info1.Id)
|
||||
@@ -399,7 +399,7 @@ func TestSearchFilesInTeamForUser(t *testing.T) {
|
||||
|
||||
page := 0
|
||||
|
||||
results, err := th.App.SearchFilesInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
results, err := th.App.SearchFilesInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
|
||||
require.Nil(t, err)
|
||||
require.NotNil(t, results)
|
||||
@@ -420,7 +420,7 @@ func TestSearchFilesInTeamForUser(t *testing.T) {
|
||||
|
||||
page := 1
|
||||
|
||||
results, err := th.App.SearchFilesInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
results, err := th.App.SearchFilesInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
|
||||
require.Nil(t, err)
|
||||
require.NotNil(t, results)
|
||||
@@ -451,7 +451,7 @@ func TestSearchFilesInTeamForUser(t *testing.T) {
|
||||
th.App.Srv().SearchEngine.ElasticsearchEngine = nil
|
||||
}()
|
||||
|
||||
results, err := th.App.SearchFilesInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
results, err := th.App.SearchFilesInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
|
||||
require.Nil(t, err)
|
||||
require.NotNil(t, results)
|
||||
@@ -480,7 +480,7 @@ func TestSearchFilesInTeamForUser(t *testing.T) {
|
||||
th.App.Srv().SearchEngine.ElasticsearchEngine = nil
|
||||
}()
|
||||
|
||||
results, err := th.App.SearchFilesInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
results, err := th.App.SearchFilesInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
|
||||
require.Nil(t, err)
|
||||
require.NotNil(t, results)
|
||||
@@ -505,7 +505,7 @@ func TestSearchFilesInTeamForUser(t *testing.T) {
|
||||
th.App.Srv().SearchEngine.ElasticsearchEngine = nil
|
||||
}()
|
||||
|
||||
results, err := th.App.SearchFilesInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
results, err := th.App.SearchFilesInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
|
||||
require.Nil(t, err)
|
||||
require.NotNil(t, results)
|
||||
@@ -538,7 +538,7 @@ func TestSearchFilesInTeamForUser(t *testing.T) {
|
||||
th.App.Srv().SearchEngine.ElasticsearchEngine = nil
|
||||
}()
|
||||
|
||||
results, err := th.App.SearchFilesInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
results, err := th.App.SearchFilesInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, []string{}, results.Order)
|
||||
|
||||
@@ -17,8 +17,10 @@ import (
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/config"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/plugin"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
"github.com/mattermost/mattermost-server/v5/store"
|
||||
"github.com/mattermost/mattermost-server/v5/store/localcachelayer"
|
||||
@@ -30,6 +32,7 @@ import (
|
||||
|
||||
type TestHelper struct {
|
||||
App *App
|
||||
Context *request.Context
|
||||
Server *Server
|
||||
BasicTeam *model.Team
|
||||
BasicUser *model.User
|
||||
@@ -86,6 +89,7 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo
|
||||
|
||||
th := &TestHelper{
|
||||
App: New(ServerConnector(s)),
|
||||
Context: &request.Context{},
|
||||
Server: s,
|
||||
LogBuffer: buffer,
|
||||
IncludeCacheLayer: includeCacheLayer,
|
||||
@@ -119,6 +123,8 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo
|
||||
|
||||
if enterprise {
|
||||
th.App.Srv().SetLicense(model.NewTestLicense())
|
||||
th.App.Srv().Jobs.InitWorkers()
|
||||
th.App.Srv().Jobs.InitSchedulers()
|
||||
} else {
|
||||
th.App.Srv().SetLicense(nil)
|
||||
}
|
||||
@@ -127,8 +133,6 @@ func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer boo
|
||||
th.tempWorkspace = tempWorkspace
|
||||
}
|
||||
|
||||
th.App.InitServer()
|
||||
|
||||
return th
|
||||
}
|
||||
|
||||
@@ -238,7 +242,7 @@ func (th *TestHelper) CreateTeam() *model.Team {
|
||||
|
||||
utils.DisableDebugLogForTest()
|
||||
var err *model.AppError
|
||||
if team, err = th.App.CreateTeam(team); err != nil {
|
||||
if team, err = th.App.CreateTeam(th.Context, team); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
utils.EnableDebugLogForTest()
|
||||
@@ -267,11 +271,11 @@ func (th *TestHelper) CreateUserOrGuest(guest bool) *model.User {
|
||||
utils.DisableDebugLogForTest()
|
||||
var err *model.AppError
|
||||
if guest {
|
||||
if user, err = th.App.CreateGuest(user); err != nil {
|
||||
if user, err = th.App.CreateGuest(th.Context, user); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
} else {
|
||||
if user, err = th.App.CreateUser(user); err != nil {
|
||||
if user, err = th.App.CreateUser(th.Context, user); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@@ -289,7 +293,7 @@ func (th *TestHelper) CreateBot() *model.Bot {
|
||||
OwnerId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
bot, err := th.App.CreateBot(bot)
|
||||
bot, err := th.App.CreateBot(th.Context, bot)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@@ -329,7 +333,7 @@ func (th *TestHelper) createChannel(team *model.Team, channelType string, option
|
||||
|
||||
utils.DisableDebugLogForTest()
|
||||
var appErr *model.AppError
|
||||
if channel, appErr = th.App.CreateChannel(channel, true); appErr != nil {
|
||||
if channel, appErr = th.App.CreateChannel(th.Context, channel, true); appErr != nil {
|
||||
panic(appErr)
|
||||
}
|
||||
|
||||
@@ -357,7 +361,7 @@ func (th *TestHelper) CreateDmChannel(user *model.User) *model.Channel {
|
||||
utils.DisableDebugLogForTest()
|
||||
var err *model.AppError
|
||||
var channel *model.Channel
|
||||
if channel, err = th.App.GetOrCreateDirectChannel(th.BasicUser.Id, user.Id); err != nil {
|
||||
if channel, err = th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, user.Id); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
utils.EnableDebugLogForTest()
|
||||
@@ -387,7 +391,7 @@ func (th *TestHelper) CreatePost(channel *model.Channel) *model.Post {
|
||||
|
||||
utils.DisableDebugLogForTest()
|
||||
var err *model.AppError
|
||||
if post, err = th.App.CreatePost(post, channel, false, true); err != nil {
|
||||
if post, err = th.App.CreatePost(th.Context, post, channel, false, true); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
utils.EnableDebugLogForTest()
|
||||
@@ -404,7 +408,7 @@ func (th *TestHelper) CreateMessagePost(channel *model.Channel, message string)
|
||||
|
||||
utils.DisableDebugLogForTest()
|
||||
var err *model.AppError
|
||||
if post, err = th.App.CreatePost(post, channel, false, true); err != nil {
|
||||
if post, err = th.App.CreatePost(th.Context, post, channel, false, true); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
utils.EnableDebugLogForTest()
|
||||
@@ -414,7 +418,7 @@ func (th *TestHelper) CreateMessagePost(channel *model.Channel, message string)
|
||||
func (th *TestHelper) LinkUserToTeam(user *model.User, team *model.Team) {
|
||||
utils.DisableDebugLogForTest()
|
||||
|
||||
_, err := th.App.JoinUserToTeam(team, user, "")
|
||||
_, err := th.App.JoinUserToTeam(th.Context, team, user, "")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@@ -425,7 +429,7 @@ func (th *TestHelper) LinkUserToTeam(user *model.User, team *model.Team) {
|
||||
func (th *TestHelper) RemoveUserFromTeam(user *model.User, team *model.Team) {
|
||||
utils.DisableDebugLogForTest()
|
||||
|
||||
err := th.App.RemoveUserFromTeam(team.Id, user.Id, "")
|
||||
err := th.App.RemoveUserFromTeam(th.Context, team.Id, user.Id, "")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@@ -525,7 +529,7 @@ func (th *TestHelper) CreateEmoji() *model.Emoji {
|
||||
func (th *TestHelper) AddReactionToPost(post *model.Post, user *model.User, emojiName string) *model.Reaction {
|
||||
utils.DisableDebugLogForTest()
|
||||
|
||||
reaction, err := th.App.SaveReactionForPost(&model.Reaction{
|
||||
reaction, err := th.App.SaveReactionForPost(th.Context, &model.Reaction{
|
||||
UserId: user.Id,
|
||||
PostId: post.Id,
|
||||
EmojiName: emojiName,
|
||||
@@ -660,7 +664,7 @@ func (th *TestHelper) SetupPluginAPI() *PluginAPI {
|
||||
Id: "pluginid",
|
||||
}
|
||||
|
||||
return NewPluginAPI(th.App, manifest)
|
||||
return NewPluginAPI(th.App, th.Context, manifest)
|
||||
}
|
||||
|
||||
func (th *TestHelper) RemovePermissionFromRole(permission string, roleName string) {
|
||||
@@ -734,3 +738,7 @@ func NewTestId() string {
|
||||
|
||||
return string(newId)
|
||||
}
|
||||
|
||||
func (th *TestHelper) NewPluginAPI(manifest *model.Manifest) plugin.API {
|
||||
return th.App.NewPluginAPI(th.Context, manifest)
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
)
|
||||
@@ -75,7 +76,7 @@ func rewriteFilePaths(line *LineImportData, basePath string) {
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) bulkImportWorker(dryRun bool, wg *sync.WaitGroup, lines <-chan LineImportWorkerData, errors chan<- LineImportWorkerError) {
|
||||
func (a *App) bulkImportWorker(c *request.Context, dryRun bool, wg *sync.WaitGroup, lines <-chan LineImportWorkerData, errors chan<- LineImportWorkerError) {
|
||||
postLines := []LineImportWorkerData{}
|
||||
directPostLines := []LineImportWorkerData{}
|
||||
for line := range lines {
|
||||
@@ -86,7 +87,7 @@ func (a *App) bulkImportWorker(dryRun bool, wg *sync.WaitGroup, lines <-chan Lin
|
||||
errors <- LineImportWorkerError{model.NewAppError("BulkImport", "app.import.import_line.null_post.error", nil, "", http.StatusBadRequest), line.LineNumber}
|
||||
}
|
||||
if len(postLines) >= importMultiplePostsThreshold {
|
||||
if errLine, err := a.importMultiplePostLines(postLines, dryRun); err != nil {
|
||||
if errLine, err := a.importMultiplePostLines(c, postLines, dryRun); err != nil {
|
||||
errors <- LineImportWorkerError{err, errLine}
|
||||
}
|
||||
postLines = []LineImportWorkerData{}
|
||||
@@ -97,40 +98,40 @@ func (a *App) bulkImportWorker(dryRun bool, wg *sync.WaitGroup, lines <-chan Lin
|
||||
errors <- LineImportWorkerError{model.NewAppError("BulkImport", "app.import.import_line.null_direct_post.error", nil, "", http.StatusBadRequest), line.LineNumber}
|
||||
}
|
||||
if len(directPostLines) >= importMultiplePostsThreshold {
|
||||
if errLine, err := a.importMultipleDirectPostLines(directPostLines, dryRun); err != nil {
|
||||
if errLine, err := a.importMultipleDirectPostLines(c, directPostLines, dryRun); err != nil {
|
||||
errors <- LineImportWorkerError{err, errLine}
|
||||
}
|
||||
directPostLines = []LineImportWorkerData{}
|
||||
}
|
||||
default:
|
||||
if err := a.importLine(line.LineImportData, dryRun); err != nil {
|
||||
if err := a.importLine(c, line.LineImportData, dryRun); err != nil {
|
||||
errors <- LineImportWorkerError{err, line.LineNumber}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(postLines) > 0 {
|
||||
if errLine, err := a.importMultiplePostLines(postLines, dryRun); err != nil {
|
||||
if errLine, err := a.importMultiplePostLines(c, postLines, dryRun); err != nil {
|
||||
errors <- LineImportWorkerError{err, errLine}
|
||||
}
|
||||
}
|
||||
if len(directPostLines) > 0 {
|
||||
if errLine, err := a.importMultipleDirectPostLines(directPostLines, dryRun); err != nil {
|
||||
if errLine, err := a.importMultipleDirectPostLines(c, directPostLines, dryRun); err != nil {
|
||||
errors <- LineImportWorkerError{err, errLine}
|
||||
}
|
||||
}
|
||||
wg.Done()
|
||||
}
|
||||
|
||||
func (a *App) BulkImport(fileReader io.Reader, dryRun bool, workers int) (*model.AppError, int) {
|
||||
return a.bulkImport(fileReader, dryRun, workers, "")
|
||||
func (a *App) BulkImport(c *request.Context, fileReader io.Reader, dryRun bool, workers int) (*model.AppError, int) {
|
||||
return a.bulkImport(c, fileReader, dryRun, workers, "")
|
||||
}
|
||||
|
||||
func (a *App) BulkImportWithPath(fileReader io.Reader, dryRun bool, workers int, importPath string) (*model.AppError, int) {
|
||||
return a.bulkImport(fileReader, dryRun, workers, importPath)
|
||||
func (a *App) BulkImportWithPath(c *request.Context, fileReader io.Reader, dryRun bool, workers int, importPath string) (*model.AppError, int) {
|
||||
return a.bulkImport(c, fileReader, dryRun, workers, importPath)
|
||||
}
|
||||
|
||||
func (a *App) bulkImport(fileReader io.Reader, dryRun bool, workers int, importPath string) (*model.AppError, int) {
|
||||
func (a *App) bulkImport(c *request.Context, fileReader io.Reader, dryRun bool, workers int, importPath string) (*model.AppError, int) {
|
||||
scanner := bufio.NewScanner(fileReader)
|
||||
buf := make([]byte, 0, 64*1024)
|
||||
scanner.Buffer(buf, maxScanTokenSize)
|
||||
@@ -192,7 +193,7 @@ func (a *App) bulkImport(fileReader io.Reader, dryRun bool, workers int, importP
|
||||
linesChan = make(chan LineImportWorkerData, workers)
|
||||
for i := 0; i < workers; i++ {
|
||||
wg.Add(1)
|
||||
go a.bulkImportWorker(dryRun, &wg, linesChan, errorsChan)
|
||||
go a.bulkImportWorker(c, dryRun, &wg, linesChan, errorsChan)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,7 +237,7 @@ func processImportDataFileVersionLine(line LineImportData) (int, *model.AppError
|
||||
return *line.Version, nil
|
||||
}
|
||||
|
||||
func (a *App) importLine(line LineImportData, dryRun bool) *model.AppError {
|
||||
func (a *App) importLine(c *request.Context, line LineImportData, dryRun bool) *model.AppError {
|
||||
switch {
|
||||
case line.Type == "scheme":
|
||||
if line.Scheme == nil {
|
||||
@@ -247,12 +248,12 @@ func (a *App) importLine(line LineImportData, dryRun bool) *model.AppError {
|
||||
if line.Team == nil {
|
||||
return model.NewAppError("BulkImport", "app.import.import_line.null_team.error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
return a.importTeam(line.Team, dryRun)
|
||||
return a.importTeam(c, line.Team, dryRun)
|
||||
case line.Type == "channel":
|
||||
if line.Channel == nil {
|
||||
return model.NewAppError("BulkImport", "app.import.import_line.null_channel.error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
return a.importChannel(line.Channel, dryRun)
|
||||
return a.importChannel(c, line.Channel, dryRun)
|
||||
case line.Type == "user":
|
||||
if line.User == nil {
|
||||
return model.NewAppError("BulkImport", "app.import.import_line.null_user.error", nil, "", http.StatusBadRequest)
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
"github.com/mattermost/mattermost-server/v5/store"
|
||||
@@ -155,7 +156,7 @@ func (a *App) importRole(data *RoleImportData, dryRun bool, isSchemeRole bool) *
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *App) importTeam(data *TeamImportData, dryRun bool) *model.AppError {
|
||||
func (a *App) importTeam(c *request.Context, data *TeamImportData, dryRun bool) *model.AppError {
|
||||
if err := validateTeamImportData(data); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -202,7 +203,7 @@ func (a *App) importTeam(data *TeamImportData, dryRun bool) *model.AppError {
|
||||
}
|
||||
|
||||
if team.Id == "" {
|
||||
if _, err := a.CreateTeam(team); err != nil {
|
||||
if _, err := a.CreateTeam(c, team); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
@@ -214,7 +215,7 @@ func (a *App) importTeam(data *TeamImportData, dryRun bool) *model.AppError {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) importChannel(data *ChannelImportData, dryRun bool) *model.AppError {
|
||||
func (a *App) importChannel(c *request.Context, data *ChannelImportData, dryRun bool) *model.AppError {
|
||||
if err := validateChannelImportData(data); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -267,7 +268,7 @@ func (a *App) importChannel(data *ChannelImportData, dryRun bool) *model.AppErro
|
||||
}
|
||||
|
||||
if channel.Id == "" {
|
||||
if _, err := a.CreateChannel(channel, false); err != nil {
|
||||
if _, err := a.CreateChannel(c, channel, false); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
@@ -1020,7 +1021,7 @@ func (a *App) importReaction(data *ReactionImportData, post *model.Post) *model.
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) importReplies(data []ReplyImportData, post *model.Post, teamID string) *model.AppError {
|
||||
func (a *App) importReplies(c *request.Context, data []ReplyImportData, post *model.Post, teamID string) *model.AppError {
|
||||
var err *model.AppError
|
||||
usernames := []string{}
|
||||
for _, replyData := range data {
|
||||
@@ -1068,7 +1069,7 @@ func (a *App) importReplies(data []ReplyImportData, post *model.Post, teamID str
|
||||
reply.Message = *replyData.Message
|
||||
reply.CreateAt = *replyData.CreateAt
|
||||
|
||||
fileIDs, err := a.uploadAttachments(replyData.Attachments, reply, teamID)
|
||||
fileIDs, err := a.uploadAttachments(c, replyData.Attachments, reply, teamID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -1116,7 +1117,7 @@ func (a *App) importReplies(data []ReplyImportData, post *model.Post, teamID str
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) importAttachment(data *AttachmentImportData, post *model.Post, teamID string) (*model.FileInfo, *model.AppError) {
|
||||
func (a *App) importAttachment(c *request.Context, data *AttachmentImportData, post *model.Post, teamID string) (*model.FileInfo, *model.AppError) {
|
||||
file, err := os.Open(*data.Path)
|
||||
if file == nil || err != nil {
|
||||
return nil, model.NewAppError("BulkImport", "app.import.attachment.bad_file.error", map[string]interface{}{"FilePath": *data.Path}, "", http.StatusBadRequest)
|
||||
@@ -1157,7 +1158,7 @@ func (a *App) importAttachment(data *AttachmentImportData, post *model.Post, tea
|
||||
|
||||
mlog.Info("Uploading file with name", mlog.String("file_name", file.Name()))
|
||||
|
||||
fileInfo, appErr := a.DoUploadFile(timestamp, teamID, post.ChannelId, post.UserId, file.Name(), fileData)
|
||||
fileInfo, appErr := a.DoUploadFile(c, timestamp, teamID, post.ChannelId, post.UserId, file.Name(), fileData)
|
||||
if appErr != nil {
|
||||
mlog.Error("Failed to upload file:", mlog.Err(appErr))
|
||||
return nil, appErr
|
||||
@@ -1251,7 +1252,7 @@ func getPostStrID(post *model.Post) string {
|
||||
|
||||
// importMultiplePostLines will return an error and the line that
|
||||
// caused it whenever possible
|
||||
func (a *App) importMultiplePostLines(lines []LineImportWorkerData, dryRun bool) (int, *model.AppError) {
|
||||
func (a *App) importMultiplePostLines(c *request.Context, lines []LineImportWorkerData, dryRun bool) (int, *model.AppError) {
|
||||
if len(lines) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
@@ -1332,7 +1333,7 @@ func (a *App) importMultiplePostLines(lines []LineImportWorkerData, dryRun bool)
|
||||
post.Props = *line.Post.Props
|
||||
}
|
||||
|
||||
fileIDs, appErr := a.uploadAttachments(line.Post.Attachments, post, team.Id)
|
||||
fileIDs, appErr := a.uploadAttachments(c, line.Post.Attachments, post, team.Id)
|
||||
if appErr != nil {
|
||||
return line.LineNumber, appErr
|
||||
}
|
||||
@@ -1423,7 +1424,7 @@ func (a *App) importMultiplePostLines(lines []LineImportWorkerData, dryRun bool)
|
||||
}
|
||||
|
||||
if postWithData.postData.Replies != nil && len(*postWithData.postData.Replies) > 0 {
|
||||
err := a.importReplies(*postWithData.postData.Replies, postWithData.post, postWithData.team.Id)
|
||||
err := a.importReplies(c, *postWithData.postData.Replies, postWithData.post, postWithData.team.Id)
|
||||
if err != nil {
|
||||
return postWithData.lineNumber, err
|
||||
}
|
||||
@@ -1434,14 +1435,14 @@ func (a *App) importMultiplePostLines(lines []LineImportWorkerData, dryRun bool)
|
||||
}
|
||||
|
||||
// uploadAttachments imports new attachments and returns current attachments of the post as a map
|
||||
func (a *App) uploadAttachments(attachments *[]AttachmentImportData, post *model.Post, teamID string) (map[string]bool, *model.AppError) {
|
||||
func (a *App) uploadAttachments(c *request.Context, attachments *[]AttachmentImportData, post *model.Post, teamID string) (map[string]bool, *model.AppError) {
|
||||
if attachments == nil {
|
||||
return nil, nil
|
||||
}
|
||||
fileIDs := make(map[string]bool)
|
||||
for _, attachment := range *attachments {
|
||||
attachment := attachment
|
||||
fileInfo, err := a.importAttachment(&attachment, post, teamID)
|
||||
fileInfo, err := a.importAttachment(c, &attachment, post, teamID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1538,7 +1539,7 @@ func (a *App) importDirectChannel(data *DirectChannelImportData, dryRun bool) *m
|
||||
|
||||
// importMultipleDirectPostLines will return an error and the line
|
||||
// that caused it whenever possible
|
||||
func (a *App) importMultipleDirectPostLines(lines []LineImportWorkerData, dryRun bool) (int, *model.AppError) {
|
||||
func (a *App) importMultipleDirectPostLines(c *request.Context, lines []LineImportWorkerData, dryRun bool) (int, *model.AppError) {
|
||||
if len(lines) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
@@ -1585,7 +1586,7 @@ func (a *App) importMultipleDirectPostLines(lines []LineImportWorkerData, dryRun
|
||||
var channel *model.Channel
|
||||
var ch *model.Channel
|
||||
if len(userIDs) == 2 {
|
||||
ch, err = a.GetOrCreateDirectChannel(userIDs[0], userIDs[1])
|
||||
ch, err = a.GetOrCreateDirectChannel(c, userIDs[0], userIDs[1])
|
||||
if err != nil && err.Id != store.ChannelExistsError {
|
||||
return line.LineNumber, model.NewAppError("BulkImport", "app.import.import_direct_post.create_direct_channel.error", nil, err.Error(), http.StatusBadRequest)
|
||||
}
|
||||
@@ -1628,7 +1629,7 @@ func (a *App) importMultipleDirectPostLines(lines []LineImportWorkerData, dryRun
|
||||
post.Props = *line.DirectPost.Props
|
||||
}
|
||||
|
||||
fileIDs, err := a.uploadAttachments(line.DirectPost.Attachments, post, "noteam")
|
||||
fileIDs, err := a.uploadAttachments(c, line.DirectPost.Attachments, post, "noteam")
|
||||
if err != nil {
|
||||
return line.LineNumber, err
|
||||
}
|
||||
@@ -1717,7 +1718,7 @@ func (a *App) importMultipleDirectPostLines(lines []LineImportWorkerData, dryRun
|
||||
}
|
||||
|
||||
if postWithData.directPostData.Replies != nil {
|
||||
if err := a.importReplies(*postWithData.directPostData.Replies, postWithData.post, "noteam"); err != nil {
|
||||
if err := a.importReplies(c, *postWithData.directPostData.Replies, postWithData.post, "noteam"); err != nil {
|
||||
return postWithData.lineNumber, err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -518,12 +518,12 @@ func TestImportImportTeam(t *testing.T) {
|
||||
}
|
||||
|
||||
// Try importing an invalid team in dryRun mode.
|
||||
err = th.App.importTeam(&data, true)
|
||||
err = th.App.importTeam(th.Context, &data, true)
|
||||
require.Error(t, err, "Should have received an error importing an invalid team.")
|
||||
|
||||
// Do a valid team in dry-run mode.
|
||||
data.Type = ptrStr("O")
|
||||
appErr := th.App.importTeam(&data, true)
|
||||
appErr := th.App.importTeam(th.Context, &data, true)
|
||||
require.Nil(t, appErr, "Received an error validating valid team.")
|
||||
|
||||
// Check that no more teams are in the DB.
|
||||
@@ -531,7 +531,7 @@ func TestImportImportTeam(t *testing.T) {
|
||||
|
||||
// Do an invalid team in apply mode, check db changes.
|
||||
data.Type = ptrStr("XYZ")
|
||||
err = th.App.importTeam(&data, false)
|
||||
err = th.App.importTeam(th.Context, &data, false)
|
||||
require.Error(t, err, "Import should have failed on invalid team.")
|
||||
|
||||
// Check that no more teams are in the DB.
|
||||
@@ -539,7 +539,7 @@ func TestImportImportTeam(t *testing.T) {
|
||||
|
||||
// Do a valid team in apply mode, check db changes.
|
||||
data.Type = ptrStr("O")
|
||||
appErr = th.App.importTeam(&data, false)
|
||||
appErr = th.App.importTeam(th.Context, &data, false)
|
||||
require.Nil(t, appErr, "Received an error importing valid team: %v", err)
|
||||
|
||||
// Check that one more team is in the DB.
|
||||
@@ -564,7 +564,7 @@ func TestImportImportTeam(t *testing.T) {
|
||||
|
||||
// Check that the original number of teams are again in the DB (because this query doesn't include deleted).
|
||||
data.Type = ptrStr("O")
|
||||
appErr = th.App.importTeam(&data, false)
|
||||
appErr = th.App.importTeam(th.Context, &data, false)
|
||||
require.Nil(t, appErr, "Received an error importing updated valid team.")
|
||||
|
||||
th.CheckTeamCount(t, teamsCount+1)
|
||||
@@ -596,7 +596,7 @@ func TestImportImportChannel(t *testing.T) {
|
||||
|
||||
// Import a Team.
|
||||
teamName := model.NewRandomTeamName()
|
||||
th.App.importTeam(&TeamImportData{
|
||||
th.App.importTeam(th.Context, &TeamImportData{
|
||||
Name: &teamName,
|
||||
DisplayName: ptrStr("Display Name"),
|
||||
Type: ptrStr("O"),
|
||||
@@ -617,7 +617,7 @@ func TestImportImportChannel(t *testing.T) {
|
||||
Purpose: ptrStr("Channel Purpose"),
|
||||
Scheme: &scheme1.Name,
|
||||
}
|
||||
err = th.App.importChannel(&data, true)
|
||||
err = th.App.importChannel(th.Context, &data, true)
|
||||
require.NotNil(t, err, "Expected error due to invalid name.")
|
||||
|
||||
// Check that no more channels are in the DB.
|
||||
@@ -626,7 +626,7 @@ func TestImportImportChannel(t *testing.T) {
|
||||
// Do a valid channel with a nonexistent team in dry-run mode.
|
||||
data.Name = ptrStr("channelname")
|
||||
data.Team = ptrStr(model.NewId())
|
||||
err = th.App.importChannel(&data, true)
|
||||
err = th.App.importChannel(th.Context, &data, true)
|
||||
require.Nil(t, err, "Expected success as cannot validate channel name in dry run mode.")
|
||||
|
||||
// Check that no more channels are in the DB.
|
||||
@@ -634,7 +634,7 @@ func TestImportImportChannel(t *testing.T) {
|
||||
|
||||
// Do a valid channel in dry-run mode.
|
||||
data.Team = &teamName
|
||||
err = th.App.importChannel(&data, true)
|
||||
err = th.App.importChannel(th.Context, &data, true)
|
||||
require.Nil(t, err, "Expected success as valid team.")
|
||||
|
||||
// Check that no more channels are in the DB.
|
||||
@@ -642,7 +642,7 @@ func TestImportImportChannel(t *testing.T) {
|
||||
|
||||
// Do an invalid channel in apply mode.
|
||||
data.Name = nil
|
||||
err = th.App.importChannel(&data, false)
|
||||
err = th.App.importChannel(th.Context, &data, false)
|
||||
require.NotNil(t, err, "Expected error due to invalid name (apply mode).")
|
||||
|
||||
// Check that no more channels are in the DB.
|
||||
@@ -651,7 +651,7 @@ func TestImportImportChannel(t *testing.T) {
|
||||
// Do a valid channel in apply mode with a non-existent team.
|
||||
data.Name = ptrStr("channelname")
|
||||
data.Team = ptrStr(model.NewId())
|
||||
err = th.App.importChannel(&data, false)
|
||||
err = th.App.importChannel(th.Context, &data, false)
|
||||
require.NotNil(t, err, "Expected error due to non-existent team (apply mode).")
|
||||
|
||||
// Check that no more channels are in the DB.
|
||||
@@ -659,7 +659,7 @@ func TestImportImportChannel(t *testing.T) {
|
||||
|
||||
// Do a valid channel in apply mode.
|
||||
data.Team = &teamName
|
||||
err = th.App.importChannel(&data, false)
|
||||
err = th.App.importChannel(th.Context, &data, false)
|
||||
require.Nil(t, err, "Expected success in apply mode")
|
||||
|
||||
// Check that 1 more channel is in the DB.
|
||||
@@ -682,7 +682,7 @@ func TestImportImportChannel(t *testing.T) {
|
||||
data.Header = ptrStr("New Header")
|
||||
data.Purpose = ptrStr("New Purpose")
|
||||
data.Scheme = &scheme2.Name
|
||||
err = th.App.importChannel(&data, false)
|
||||
err = th.App.importChannel(th.Context, &data, false)
|
||||
require.Nil(t, err, "Expected success in apply mode")
|
||||
|
||||
// Check channel count the same.
|
||||
@@ -864,7 +864,7 @@ func TestImportImportUser(t *testing.T) {
|
||||
|
||||
// Test team and channel memberships
|
||||
teamName := model.NewRandomTeamName()
|
||||
th.App.importTeam(&TeamImportData{
|
||||
th.App.importTeam(th.Context, &TeamImportData{
|
||||
Name: &teamName,
|
||||
DisplayName: ptrStr("Display Name"),
|
||||
Type: ptrStr("O"),
|
||||
@@ -873,7 +873,7 @@ func TestImportImportUser(t *testing.T) {
|
||||
require.Nil(t, appErr, "Failed to get team from database.")
|
||||
|
||||
channelName := model.NewId()
|
||||
th.App.importChannel(&ChannelImportData{
|
||||
th.App.importChannel(th.Context, &ChannelImportData{
|
||||
Team: &teamName,
|
||||
Name: &channelName,
|
||||
DisplayName: ptrStr("Display Name"),
|
||||
@@ -1386,7 +1386,7 @@ func TestImportImportUser(t *testing.T) {
|
||||
AllowOpenInvite: ptrBool(true),
|
||||
Scheme: &teamScheme.Name,
|
||||
}
|
||||
appErr = th.App.importTeam(teamData, false)
|
||||
appErr = th.App.importTeam(th.Context, teamData, false)
|
||||
assert.Nil(t, appErr)
|
||||
team, appErr = th.App.GetTeamByName(teamName)
|
||||
require.Nil(t, appErr, "Failed to get team from database.")
|
||||
@@ -1399,7 +1399,7 @@ func TestImportImportUser(t *testing.T) {
|
||||
Header: ptrStr("Channe Header"),
|
||||
Purpose: ptrStr("Channel Purpose"),
|
||||
}
|
||||
appErr = th.App.importChannel(channelData, false)
|
||||
appErr = th.App.importChannel(th.Context, channelData, false)
|
||||
assert.Nil(t, appErr)
|
||||
channel, appErr = th.App.GetChannelByName(*channelData.Name, team.Id, false)
|
||||
require.Nil(t, appErr, "Failed to get channel from database")
|
||||
@@ -1928,7 +1928,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
|
||||
// Create a Team.
|
||||
teamName := model.NewRandomTeamName()
|
||||
th.App.importTeam(&TeamImportData{
|
||||
th.App.importTeam(th.Context, &TeamImportData{
|
||||
Name: &teamName,
|
||||
DisplayName: ptrStr("Display Name"),
|
||||
Type: ptrStr("O"),
|
||||
@@ -1938,7 +1938,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
|
||||
// Create a Channel.
|
||||
channelName := model.NewId()
|
||||
th.App.importChannel(&ChannelImportData{
|
||||
th.App.importChannel(th.Context, &ChannelImportData{
|
||||
Team: &teamName,
|
||||
Name: &channelName,
|
||||
DisplayName: ptrStr("Display Name"),
|
||||
@@ -1971,7 +1971,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
},
|
||||
25,
|
||||
}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, true)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, true)
|
||||
assert.NotNil(t, err)
|
||||
assert.Equal(t, data.LineNumber, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id)
|
||||
@@ -1989,7 +1989,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, true)
|
||||
errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, true)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id)
|
||||
@@ -2006,7 +2006,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
},
|
||||
35,
|
||||
}
|
||||
errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.NotNil(t, err)
|
||||
assert.Equal(t, data.LineNumber, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id)
|
||||
@@ -2024,7 +2024,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
},
|
||||
10,
|
||||
}
|
||||
errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.NotNil(t, err)
|
||||
// Batch will fail when searching for teams, so no specific line
|
||||
// is associated with the error
|
||||
@@ -2044,7 +2044,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
},
|
||||
7,
|
||||
}
|
||||
errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.NotNil(t, err)
|
||||
// Batch will fail when searching for channels, so no specific
|
||||
// line is associated with the error
|
||||
@@ -2064,7 +2064,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
},
|
||||
2,
|
||||
}
|
||||
errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.NotNil(t, err)
|
||||
// Batch will fail when searching for users, so no specific line
|
||||
// is associated with the error
|
||||
@@ -2085,7 +2085,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id)
|
||||
@@ -2113,7 +2113,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id)
|
||||
@@ -2142,7 +2142,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 2, team.Id)
|
||||
@@ -2160,7 +2160,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 3, team.Id)
|
||||
@@ -2179,7 +2179,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 4, team.Id)
|
||||
@@ -2222,7 +2222,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
1,
|
||||
}
|
||||
|
||||
errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.Nil(t, err, "Expected success.")
|
||||
assert.Equal(t, 0, errLine)
|
||||
|
||||
@@ -2261,7 +2261,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.Nil(t, err, "Expected success.")
|
||||
assert.Equal(t, 0, errLine)
|
||||
|
||||
@@ -2302,7 +2302,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.Nil(t, err, "Expected success.")
|
||||
assert.Equal(t, 0, errLine)
|
||||
|
||||
@@ -2348,7 +2348,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.Nil(t, err, "Expected success.")
|
||||
assert.Equal(t, 0, errLine)
|
||||
|
||||
@@ -2372,7 +2372,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.Nil(t, err, "Expected success.")
|
||||
assert.Equal(t, 0, errLine)
|
||||
|
||||
@@ -2396,7 +2396,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.Nil(t, err, "Expected success.")
|
||||
assert.Equal(t, 0, errLine)
|
||||
|
||||
@@ -2404,7 +2404,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
|
||||
// Create another Team.
|
||||
teamName2 := model.NewRandomTeamName()
|
||||
th.App.importTeam(&TeamImportData{
|
||||
th.App.importTeam(th.Context, &TeamImportData{
|
||||
Name: &teamName2,
|
||||
DisplayName: ptrStr("Display Name 2"),
|
||||
Type: ptrStr("O"),
|
||||
@@ -2413,7 +2413,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
require.Nil(t, err, "Failed to get team from database.")
|
||||
|
||||
// Create another Channel for the another team.
|
||||
th.App.importChannel(&ChannelImportData{
|
||||
th.App.importChannel(th.Context, &ChannelImportData{
|
||||
Team: &teamName2,
|
||||
Name: &channelName,
|
||||
DisplayName: ptrStr("Display Name"),
|
||||
@@ -2451,7 +2451,7 @@ func TestImportimportMultiplePostLines(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err = th.App.importMultiplePostLines([]LineImportWorkerData{data, data2}, false)
|
||||
errLine, err = th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data, data2}, false)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 0, errLine)
|
||||
|
||||
@@ -2466,7 +2466,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
|
||||
// Create a Team.
|
||||
teamName := model.NewRandomTeamName()
|
||||
th.App.importTeam(&TeamImportData{
|
||||
th.App.importTeam(th.Context, &TeamImportData{
|
||||
Name: &teamName,
|
||||
DisplayName: ptrStr("Display Name"),
|
||||
Type: ptrStr("O"),
|
||||
@@ -2476,7 +2476,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
|
||||
// Create a Channel.
|
||||
channelName := model.NewId()
|
||||
th.App.importChannel(&ChannelImportData{
|
||||
th.App.importChannel(th.Context, &ChannelImportData{
|
||||
Team: &teamName,
|
||||
Name: &channelName,
|
||||
DisplayName: ptrStr("Display Name"),
|
||||
@@ -2522,7 +2522,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
},
|
||||
12,
|
||||
}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, true)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, true)
|
||||
assert.NotNil(t, err)
|
||||
assert.Equal(t, data.LineNumber, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id)
|
||||
@@ -2541,7 +2541,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, true)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, true)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id)
|
||||
@@ -2559,7 +2559,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
},
|
||||
2,
|
||||
}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.NotNil(t, err)
|
||||
assert.Equal(t, data.LineNumber, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id)
|
||||
@@ -2578,7 +2578,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
},
|
||||
7,
|
||||
}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.NotNil(t, err)
|
||||
assert.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id)
|
||||
@@ -2597,7 +2597,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
},
|
||||
8,
|
||||
}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.NotNil(t, err)
|
||||
assert.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id)
|
||||
@@ -2616,7 +2616,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
},
|
||||
9,
|
||||
}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.NotNil(t, err)
|
||||
assert.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id)
|
||||
@@ -2635,7 +2635,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id)
|
||||
@@ -2664,7 +2664,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id)
|
||||
@@ -2694,7 +2694,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 2, team.Id)
|
||||
@@ -2713,7 +2713,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 3, team.Id)
|
||||
@@ -2732,7 +2732,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 4, team.Id)
|
||||
@@ -2768,7 +2768,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
1,
|
||||
}
|
||||
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err, "Expected success.")
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -2808,7 +2808,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err, "Expected success.")
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -2848,7 +2848,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err, "Expected success.")
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -2895,7 +2895,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err, "Expected success.")
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -2920,7 +2920,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err, "Expected success.")
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -2945,7 +2945,7 @@ func TestImportImportPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err, "Expected success.")
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -3044,7 +3044,7 @@ func TestImportImportDirectChannel(t *testing.T) {
|
||||
AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount)
|
||||
|
||||
// Get the channel to check that the header was updated.
|
||||
channel, appErr := th.App.GetOrCreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id)
|
||||
channel, appErr := th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id)
|
||||
require.Nil(t, appErr)
|
||||
require.Equal(t, channel.Header, *data.Header)
|
||||
|
||||
@@ -3115,7 +3115,7 @@ func TestImportImportDirectChannel(t *testing.T) {
|
||||
appErr = th.App.importDirectChannel(&data, false)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
channel, appErr = th.App.GetOrCreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id)
|
||||
channel, appErr = th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id)
|
||||
require.Nil(t, appErr)
|
||||
checkPreference(t, th.App, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true")
|
||||
checkPreference(t, th.App, th.BasicUser2.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true")
|
||||
@@ -3137,7 +3137,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
|
||||
// Get the channel.
|
||||
var directChannel *model.Channel
|
||||
channel, appErr := th.App.GetOrCreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id)
|
||||
channel, appErr := th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id)
|
||||
require.Nil(t, appErr)
|
||||
require.NotEmpty(t, channel)
|
||||
directChannel = channel
|
||||
@@ -3162,7 +3162,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
7,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, true)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, true)
|
||||
require.NotNil(t, err)
|
||||
require.Equal(t, data.LineNumber, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 0, "")
|
||||
@@ -3183,7 +3183,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, true)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, true)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 0, "")
|
||||
@@ -3204,7 +3204,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
9,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.NotNil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 0, "")
|
||||
@@ -3225,7 +3225,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 1, "")
|
||||
@@ -3256,7 +3256,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 1, "")
|
||||
@@ -3287,7 +3287,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 2, "")
|
||||
@@ -3308,7 +3308,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 3, "")
|
||||
@@ -3329,7 +3329,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 4, "")
|
||||
@@ -3365,7 +3365,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
1,
|
||||
}
|
||||
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -3424,7 +3424,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
4,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, true)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, true)
|
||||
require.NotNil(t, err)
|
||||
require.Equal(t, data.LineNumber, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 0, "")
|
||||
@@ -3446,7 +3446,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, true)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, true)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 0, "")
|
||||
@@ -3469,7 +3469,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
8,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.NotNil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 0, "")
|
||||
@@ -3491,7 +3491,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 1, "")
|
||||
@@ -3523,7 +3523,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 1, "")
|
||||
@@ -3555,7 +3555,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 2, "")
|
||||
@@ -3577,7 +3577,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 3, "")
|
||||
@@ -3599,7 +3599,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
AssertAllPostsCount(t, th.App, initialPostCount, 4, "")
|
||||
@@ -3636,7 +3636,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
1,
|
||||
}
|
||||
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -3675,7 +3675,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err, "Expected success.")
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -3720,7 +3720,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err, "Expected success.")
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -3772,7 +3772,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err, "Expected success.")
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -3802,7 +3802,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err, "Expected success.")
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -3832,7 +3832,7 @@ func TestImportImportDirectPost(t *testing.T) {
|
||||
},
|
||||
1,
|
||||
}
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err, "Expected success.")
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -3891,14 +3891,14 @@ func TestImportAttachment(t *testing.T) {
|
||||
|
||||
userID := model.NewId()
|
||||
data := AttachmentImportData{Path: &testImage}
|
||||
_, err := th.App.importAttachment(&data, &model.Post{UserId: userID, ChannelId: "some-channel"}, "some-team")
|
||||
_, err := th.App.importAttachment(th.Context, &data, &model.Post{UserId: userID, ChannelId: "some-channel"}, "some-team")
|
||||
assert.Nil(t, err, "sample run without errors")
|
||||
|
||||
attachments := GetAttachments(userID, th, t)
|
||||
assert.Len(t, attachments, 1)
|
||||
|
||||
data = AttachmentImportData{Path: &invalidPath}
|
||||
_, err = th.App.importAttachment(&data, &model.Post{UserId: model.NewId(), ChannelId: "some-channel"}, "some-team")
|
||||
_, err = th.App.importAttachment(th.Context, &data, &model.Post{UserId: model.NewId(), ChannelId: "some-channel"}, "some-team")
|
||||
assert.NotNil(t, err, "should have failed when opening the file")
|
||||
assert.Equal(t, err.Id, "app.import.attachment.bad_file.error")
|
||||
}
|
||||
@@ -3909,7 +3909,7 @@ func TestImportPostAndRepliesWithAttachments(t *testing.T) {
|
||||
|
||||
// Create a Team.
|
||||
teamName := model.NewRandomTeamName()
|
||||
th.App.importTeam(&TeamImportData{
|
||||
th.App.importTeam(th.Context, &TeamImportData{
|
||||
Name: &teamName,
|
||||
DisplayName: ptrStr("Display Name"),
|
||||
Type: ptrStr("O"),
|
||||
@@ -3919,7 +3919,7 @@ func TestImportPostAndRepliesWithAttachments(t *testing.T) {
|
||||
|
||||
// Create a Channel.
|
||||
channelName := model.NewId()
|
||||
th.App.importChannel(&ChannelImportData{
|
||||
th.App.importChannel(th.Context, &ChannelImportData{
|
||||
Team: &teamName,
|
||||
Name: &channelName,
|
||||
DisplayName: ptrStr("Display Name"),
|
||||
@@ -3992,7 +3992,7 @@ func TestImportPostAndRepliesWithAttachments(t *testing.T) {
|
||||
}
|
||||
|
||||
t.Run("import with attachment", func(t *testing.T) {
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -4010,7 +4010,7 @@ func TestImportPostAndRepliesWithAttachments(t *testing.T) {
|
||||
|
||||
t.Run("import existing post with new attachment", func(t *testing.T) {
|
||||
data.Post.Attachments = &[]AttachmentImportData{{Path: &testImage}}
|
||||
errLine, err := th.App.importMultiplePostLines([]LineImportWorkerData{data}, false)
|
||||
errLine, err := th.App.importMultiplePostLines(th.Context, []LineImportWorkerData{data}, false)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -4047,7 +4047,7 @@ func TestImportPostAndRepliesWithAttachments(t *testing.T) {
|
||||
7,
|
||||
}
|
||||
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{directImportData}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{directImportData}, false)
|
||||
require.Nil(t, err, "Expected success.")
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -4108,7 +4108,7 @@ func TestImportDirectPostWithAttachments(t *testing.T) {
|
||||
}
|
||||
|
||||
t.Run("Regular import of attachment", func(t *testing.T) {
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{directImportData}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{directImportData}, false)
|
||||
require.Nil(t, err, "Expected success.")
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -4119,7 +4119,7 @@ func TestImportDirectPostWithAttachments(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("Attempt to import again with same file entirely, should NOT add an attachment", func(t *testing.T) {
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{directImportData}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{directImportData}, false)
|
||||
require.Nil(t, err, "Expected success.")
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -4144,7 +4144,7 @@ func TestImportDirectPostWithAttachments(t *testing.T) {
|
||||
2,
|
||||
}
|
||||
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{directImportDataFake}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{directImportDataFake}, false)
|
||||
require.Nil(t, err, "Expected success.")
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
@@ -4169,7 +4169,7 @@ func TestImportDirectPostWithAttachments(t *testing.T) {
|
||||
2,
|
||||
}
|
||||
|
||||
errLine, err := th.App.importMultipleDirectPostLines([]LineImportWorkerData{directImportData2}, false)
|
||||
errLine, err := th.App.importMultipleDirectPostLines(th.Context, []LineImportWorkerData{directImportData2}, false)
|
||||
require.Nil(t, err, "Expected success.")
|
||||
require.Equal(t, 0, errLine)
|
||||
|
||||
|
||||
@@ -85,42 +85,42 @@ func TestImportImportLine(t *testing.T) {
|
||||
Type: "gibberish",
|
||||
}
|
||||
|
||||
err := th.App.importLine(line, false)
|
||||
err := th.App.importLine(th.Context, line, false)
|
||||
require.NotNil(t, err, "Expected an error when importing a line with invalid type.")
|
||||
|
||||
// Try import line with team type but nil team.
|
||||
line.Type = "team"
|
||||
err = th.App.importLine(line, false)
|
||||
err = th.App.importLine(th.Context, line, false)
|
||||
require.NotNil(t, err, "Expected an error when importing a line of type team with a nil team.")
|
||||
|
||||
// Try import line with channel type but nil channel.
|
||||
line.Type = "channel"
|
||||
err = th.App.importLine(line, false)
|
||||
err = th.App.importLine(th.Context, line, false)
|
||||
require.NotNil(t, err, "Expected an error when importing a line with type channel with a nil channel.")
|
||||
|
||||
// Try import line with user type but nil user.
|
||||
line.Type = "user"
|
||||
err = th.App.importLine(line, false)
|
||||
err = th.App.importLine(th.Context, line, false)
|
||||
require.NotNil(t, err, "Expected an error when importing a line with type user with a nil user.")
|
||||
|
||||
// Try import line with post type but nil post.
|
||||
line.Type = "post"
|
||||
err = th.App.importLine(line, false)
|
||||
err = th.App.importLine(th.Context, line, false)
|
||||
require.NotNil(t, err, "Expected an error when importing a line with type post with a nil post.")
|
||||
|
||||
// Try import line with direct_channel type but nil direct_channel.
|
||||
line.Type = "direct_channel"
|
||||
err = th.App.importLine(line, false)
|
||||
err = th.App.importLine(th.Context, line, false)
|
||||
require.NotNil(t, err, "Expected an error when importing a line with type direct_channel with a nil direct_channel.")
|
||||
|
||||
// Try import line with direct_post type but nil direct_post.
|
||||
line.Type = "direct_post"
|
||||
err = th.App.importLine(line, false)
|
||||
err = th.App.importLine(th.Context, line, false)
|
||||
require.NotNil(t, err, "Expected an error when importing a line with type direct_post with a nil direct_post.")
|
||||
|
||||
// Try import line with scheme type but nil scheme.
|
||||
line.Type = "scheme"
|
||||
err = th.App.importLine(line, false)
|
||||
err = th.App.importLine(th.Context, line, false)
|
||||
require.NotNil(t, err, "Expected an error when importing a line with type scheme with a nil scheme.")
|
||||
}
|
||||
|
||||
@@ -185,13 +185,13 @@ func TestImportBulkImport(t *testing.T) {
|
||||
{"type": "direct_post", "direct_post": {"channel_members": ["` + username + `", "` + username2 + `", "` + username3 + `"], "user": "` + username + `", "message": "Hello Group Channel", "create_at": 123456789015}}
|
||||
{"type": "emoji", "emoji": {"name": "` + emojiName + `", "image": "` + testImage + `"}}`
|
||||
|
||||
err, line := th.App.BulkImport(strings.NewReader(data1), false, 2)
|
||||
err, line := th.App.BulkImport(th.Context, strings.NewReader(data1), false, 2)
|
||||
require.Nil(t, err, "BulkImport should have succeeded")
|
||||
require.Equal(t, 0, line, "BulkImport line should be 0")
|
||||
|
||||
// Run bulk import using a string that contains a line with invalid json.
|
||||
data2 := `{"type": "version", "version": 1`
|
||||
err, line = th.App.BulkImport(strings.NewReader(data2), false, 2)
|
||||
err, line = th.App.BulkImport(th.Context, strings.NewReader(data2), false, 2)
|
||||
require.NotNil(t, err, "Should have failed due to invalid JSON on line 1.")
|
||||
require.Equal(t, 1, line, "Should have failed due to invalid JSON on line 1.")
|
||||
|
||||
@@ -200,7 +200,7 @@ func TestImportBulkImport(t *testing.T) {
|
||||
{"type": "channel", "channel": {"type": "O", "display_name": "xr6m6udffngark2uekvr3hoeny", "team": "` + teamName + `", "name": "` + channelName + `"}}
|
||||
{"type": "user", "user": {"username": "kufjgnkxkrhhfgbrip6qxkfsaa", "email": "kufjgnkxkrhhfgbrip6qxkfsaa@example.com"}}
|
||||
{"type": "user", "user": {"username": "bwshaim6qnc2ne7oqkd5b2s2rq", "email": "bwshaim6qnc2ne7oqkd5b2s2rq@example.com", "teams": [{"name": "` + teamName + `", "channels": [{"name": "` + channelName + `"}]}]}}`
|
||||
err, line = th.App.BulkImport(strings.NewReader(data3), false, 2)
|
||||
err, line = th.App.BulkImport(th.Context, strings.NewReader(data3), false, 2)
|
||||
require.NotNil(t, err, "Should have failed due to missing version line on line 1.")
|
||||
require.Equal(t, 1, line, "Should have failed due to missing version line on line 1.")
|
||||
|
||||
@@ -212,7 +212,7 @@ func TestImportBulkImport(t *testing.T) {
|
||||
{"type": "channel", "channel": {"type": "O", "display_name": "xr6m6udffngark2uekvr3hoeny", "team": "` + teamName + `", "name": "` + channelName + `"}}
|
||||
{"type": "user", "user": {"username": "` + username + `", "email": "` + username + `@example.com", "teams": [{"name": "` + teamName + `","theme": "` + teamTheme1 + `", "channels": [{"name": "` + channelName + `"}]}]}}
|
||||
{"type": "post", "post": {"team": "` + teamName + `", "channel": "` + channelName + `", "user": "` + username + `", "message": "Hello World", "create_at": 123456789012}}`
|
||||
err, line = th.App.BulkImport(strings.NewReader(data4+"\r\n"+posts), false, 2)
|
||||
err, line = th.App.BulkImport(th.Context, strings.NewReader(data4+"\r\n"+posts), false, 2)
|
||||
require.Nil(t, err, "BulkImport should have succeeded")
|
||||
require.Equal(t, 0, line, "BulkImport line should be 0")
|
||||
})
|
||||
@@ -220,7 +220,7 @@ func TestImportBulkImport(t *testing.T) {
|
||||
t.Run("First item after version without type", func(t *testing.T) {
|
||||
data := `{"type": "version", "version": 1}
|
||||
{"name": "custom-emoji-troll", "image": "bulkdata/emoji/trollolol.png"}`
|
||||
err, line := th.App.BulkImport(strings.NewReader(data), false, 2)
|
||||
err, line := th.App.BulkImport(th.Context, strings.NewReader(data), false, 2)
|
||||
require.NotNil(t, err, "Should have failed due to invalid type on line 2.")
|
||||
require.Equal(t, 2, line, "Should have failed due to invalid type on line 2.")
|
||||
})
|
||||
@@ -234,7 +234,7 @@ func TestImportBulkImport(t *testing.T) {
|
||||
{"type": "direct_channel", "direct_channel": {"members": ["` + username + `", "` + username + `"]}}
|
||||
{"type": "direct_post", "direct_post": {"channel_members": ["` + username + `", "` + username + `"], "user": "` + username + `", "message": "Hello Direct Channel to myself", "create_at": 123456789014, "props":{"attachments":[{"id":0,"fallback":"[February 4th, 2020 2:46 PM] author: fallback","color":"D0D0D0","pretext":"","author_name":"author","author_link":"","title":"","title_link":"","text":"this post has props","fields":null,"image_url":"","thumb_url":"","footer":"Posted in #general","footer_icon":"","ts":"1580823992.000100"}]}}}}`
|
||||
|
||||
err, line := th.App.BulkImport(strings.NewReader(data6), false, 2)
|
||||
err, line := th.App.BulkImport(th.Context, strings.NewReader(data6), false, 2)
|
||||
require.Nil(t, err, "BulkImport should have succeeded")
|
||||
require.Equal(t, 0, line, "BulkImport line should be 0")
|
||||
})
|
||||
@@ -393,7 +393,7 @@ func BenchmarkBulkImport(b *testing.B) {
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
err, _ := th.App.BulkImportWithPath(jsonFile, false, runtime.NumCPU(), dir)
|
||||
err, _ := th.App.BulkImportWithPath(th.Context, jsonFile, false, runtime.NumCPU(), dir)
|
||||
require.Nil(b, err)
|
||||
}
|
||||
b.StopTimer()
|
||||
|
||||
@@ -32,6 +32,7 @@ import (
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
@@ -39,11 +40,11 @@ import (
|
||||
"github.com/mattermost/mattermost-server/v5/utils"
|
||||
)
|
||||
|
||||
func (a *App) DoPostAction(postID, actionId, userID, selectedOption string) (string, *model.AppError) {
|
||||
return a.DoPostActionWithCookie(postID, actionId, userID, selectedOption, nil)
|
||||
func (a *App) DoPostAction(c *request.Context, postID, actionId, userID, selectedOption string) (string, *model.AppError) {
|
||||
return a.DoPostActionWithCookie(c, postID, actionId, userID, selectedOption, nil)
|
||||
}
|
||||
|
||||
func (a *App) DoPostActionWithCookie(postID, actionId, userID, selectedOption string, cookie *model.PostActionCookie) (string, *model.AppError) {
|
||||
func (a *App) DoPostActionWithCookie(c *request.Context, postID, actionId, userID, selectedOption string, cookie *model.PostActionCookie) (string, *model.AppError) {
|
||||
|
||||
// PostAction may result in the original post being updated. For the
|
||||
// updated post, we need to unconditionally preserve the original
|
||||
@@ -235,13 +236,13 @@ func (a *App) DoPostActionWithCookie(postID, actionId, userID, selectedOption st
|
||||
|
||||
var resp *http.Response
|
||||
if strings.HasPrefix(upstreamURL, "/warn_metrics/") {
|
||||
appErr = a.doLocalWarnMetricsRequest(upstreamURL, upstreamRequest)
|
||||
appErr = a.doLocalWarnMetricsRequest(c, upstreamURL, upstreamRequest)
|
||||
if appErr != nil {
|
||||
return "", appErr
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
resp, appErr = a.DoActionRequest(upstreamURL, upstreamRequest.ToJson())
|
||||
resp, appErr = a.DoActionRequest(c, upstreamURL, upstreamRequest.ToJson())
|
||||
if appErr != nil {
|
||||
return "", appErr
|
||||
}
|
||||
@@ -269,7 +270,7 @@ func (a *App) DoPostActionWithCookie(postID, actionId, userID, selectedOption st
|
||||
response.Update.IsPinned = originalIsPinned
|
||||
response.Update.HasReactions = originalHasReactions
|
||||
|
||||
if _, appErr = a.UpdatePost(response.Update, false); appErr != nil {
|
||||
if _, appErr = a.UpdatePost(c, response.Update, false); appErr != nil {
|
||||
return "", appErr
|
||||
}
|
||||
}
|
||||
@@ -298,7 +299,7 @@ func (a *App) DoPostActionWithCookie(postID, actionId, userID, selectedOption st
|
||||
// Perform an HTTP POST request to an integration's action endpoint.
|
||||
// Caller must consume and close returned http.Response as necessary.
|
||||
// For internal requests, requests are routed directly to a plugin ServerHTTP hook
|
||||
func (a *App) DoActionRequest(rawURL string, body []byte) (*http.Response, *model.AppError) {
|
||||
func (a *App) DoActionRequest(c *request.Context, rawURL string, body []byte) (*http.Response, *model.AppError) {
|
||||
inURL, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return nil, model.NewAppError("DoActionRequest", "api.post.do_action.action_integration.app_error", nil, err.Error(), http.StatusBadRequest)
|
||||
@@ -306,7 +307,7 @@ func (a *App) DoActionRequest(rawURL string, body []byte) (*http.Response, *mode
|
||||
|
||||
rawURLPath := path.Clean(rawURL)
|
||||
if strings.HasPrefix(rawURLPath, "/plugins/") || strings.HasPrefix(rawURLPath, "plugins/") {
|
||||
return a.DoLocalRequest(rawURLPath, body)
|
||||
return a.DoLocalRequest(c, rawURLPath, body)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("POST", rawURL, bytes.NewReader(body))
|
||||
@@ -321,7 +322,7 @@ func (a *App) DoActionRequest(rawURL string, body []byte) (*http.Response, *mode
|
||||
subpath, _ := utils.GetSubpathFromConfig(a.Config())
|
||||
siteURL, _ := url.Parse(*a.Config().ServiceSettings.SiteURL)
|
||||
if (inURL.Hostname() == "localhost" || inURL.Hostname() == "127.0.0.1" || inURL.Hostname() == siteURL.Hostname()) && strings.HasPrefix(inURL.Path, path.Join(subpath, "plugins")) {
|
||||
req.Header.Set(model.HEADER_AUTH, "Bearer "+a.Session().Token)
|
||||
req.Header.Set(model.HEADER_AUTH, "Bearer "+c.Session().Token)
|
||||
httpClient = a.HTTPService().MakeClient(true)
|
||||
} else {
|
||||
httpClient = a.HTTPService().MakeClient(false)
|
||||
@@ -362,7 +363,7 @@ func (w *LocalResponseWriter) WriteHeader(statusCode int) {
|
||||
w.status = statusCode
|
||||
}
|
||||
|
||||
func (a *App) doPluginRequest(method, rawURL string, values url.Values, body []byte) (*http.Response, *model.AppError) {
|
||||
func (a *App) doPluginRequest(c *request.Context, method, rawURL string, values url.Values, body []byte) (*http.Response, *model.AppError) {
|
||||
rawURL = strings.TrimPrefix(rawURL, "/")
|
||||
inURL, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
@@ -405,8 +406,8 @@ func (a *App) doPluginRequest(method, rawURL string, values url.Values, body []b
|
||||
if err != nil {
|
||||
return nil, model.NewAppError("doPluginRequest", "api.post.do_action.action_integration.app_error", nil, "err="+err.Error(), http.StatusBadRequest)
|
||||
}
|
||||
r.Header.Set("Mattermost-User-Id", a.Session().UserId)
|
||||
r.Header.Set(model.HEADER_AUTH, "Bearer "+a.Session().Token)
|
||||
r.Header.Set("Mattermost-User-Id", c.Session().UserId)
|
||||
r.Header.Set(model.HEADER_AUTH, "Bearer "+c.Session().Token)
|
||||
params := make(map[string]string)
|
||||
params["plugin_id"] = pluginID
|
||||
r = mux.SetURLVars(r, params)
|
||||
@@ -428,7 +429,7 @@ func (a *App) doPluginRequest(method, rawURL string, values url.Values, body []b
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (a *App) doLocalWarnMetricsRequest(rawURL string, upstreamRequest *model.PostActionIntegrationRequest) *model.AppError {
|
||||
func (a *App) doLocalWarnMetricsRequest(c *request.Context, rawURL string, upstreamRequest *model.PostActionIntegrationRequest) *model.AppError {
|
||||
_, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return model.NewAppError("doLocalWarnMetricsRequest", "api.post.do_action.action_integration.app_error", nil, err.Error(), http.StatusBadRequest)
|
||||
@@ -445,7 +446,7 @@ func (a *App) doLocalWarnMetricsRequest(rawURL string, upstreamRequest *model.Po
|
||||
return nil
|
||||
}
|
||||
|
||||
user, appErr := a.GetUser(a.Session().UserId)
|
||||
user, appErr := a.GetUser(c.Session().UserId)
|
||||
if appErr != nil {
|
||||
return appErr
|
||||
}
|
||||
@@ -461,7 +462,7 @@ func (a *App) doLocalWarnMetricsRequest(rawURL string, upstreamRequest *model.Po
|
||||
botPost.Message = ":white_check_mark: " + warnMetricDisplayTexts.BotSuccessMessage
|
||||
|
||||
if isE0Edition {
|
||||
if appErr = a.RequestLicenseAndAckWarnMetric(warnMetricId, true); appErr != nil {
|
||||
if appErr = a.RequestLicenseAndAckWarnMetric(c, warnMetricId, true); appErr != nil {
|
||||
botPost.Message = ":warning: " + i18n.T("api.server.warn_metric.bot_response.start_trial_failure.message")
|
||||
}
|
||||
} else {
|
||||
@@ -507,7 +508,7 @@ func (a *App) doLocalWarnMetricsRequest(rawURL string, upstreamRequest *model.Po
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := a.CreatePostAsUser(botPost, a.Session().Id, true); err != nil {
|
||||
if _, err := a.CreatePostAsUser(c, botPost, c.Session().Id, true); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -564,8 +565,8 @@ func (a *App) buildWarnMetricMailtoLink(warnMetricId string, user *model.User) s
|
||||
return mailToLinkContent.ToJson()
|
||||
}
|
||||
|
||||
func (a *App) DoLocalRequest(rawURL string, body []byte) (*http.Response, *model.AppError) {
|
||||
return a.doPluginRequest("POST", rawURL, nil, body)
|
||||
func (a *App) DoLocalRequest(c *request.Context, rawURL string, body []byte) (*http.Response, *model.AppError) {
|
||||
return a.doPluginRequest(c, "POST", rawURL, nil, body)
|
||||
}
|
||||
|
||||
func (a *App) OpenInteractiveDialog(request model.OpenDialogRequest) *model.AppError {
|
||||
@@ -585,7 +586,7 @@ func (a *App) OpenInteractiveDialog(request model.OpenDialogRequest) *model.AppE
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) SubmitInteractiveDialog(request model.SubmitDialogRequest) (*model.SubmitDialogResponse, *model.AppError) {
|
||||
func (a *App) SubmitInteractiveDialog(c *request.Context, request model.SubmitDialogRequest) (*model.SubmitDialogResponse, *model.AppError) {
|
||||
url := request.URL
|
||||
request.URL = ""
|
||||
request.Type = "dialog_submission"
|
||||
@@ -595,7 +596,7 @@ func (a *App) SubmitInteractiveDialog(request model.SubmitDialogRequest) (*model
|
||||
return nil, model.NewAppError("SubmitInteractiveDialog", "app.submit_interactive_dialog.json_error", nil, jsonErr.Error(), http.StatusBadRequest)
|
||||
}
|
||||
|
||||
resp, err := a.DoActionRequest(url, b)
|
||||
resp, err := a.DoActionRequest(c, url, b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -57,14 +57,14 @@ func TestPostActionInvalidURL(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
post, err := th.App.CreatePostAsUser(&interactivePost, "", true)
|
||||
post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true)
|
||||
require.Nil(t, err)
|
||||
attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, attachments[0].Actions)
|
||||
require.NotEmpty(t, attachments[0].Actions[0].Id)
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
_, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.NotNil(t, err)
|
||||
require.True(t, strings.Contains(err.Error(), "missing protocol scheme"))
|
||||
}
|
||||
@@ -157,7 +157,7 @@ func TestPostAction(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
post, err := th.App.CreatePostAsUser(&interactivePost, "", true)
|
||||
post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true)
|
||||
require.Nil(t, err)
|
||||
|
||||
attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment)
|
||||
@@ -194,7 +194,7 @@ func TestPostAction(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
post2, err := th.App.CreatePostAsUser(&menuPost, "", true)
|
||||
post2, err := th.App.CreatePostAsUser(th.Context, &menuPost, "", true)
|
||||
require.Nil(t, err)
|
||||
|
||||
attachments2, ok := post2.GetProp("attachments").([]*model.SlackAttachment)
|
||||
@@ -203,16 +203,16 @@ func TestPostAction(t *testing.T) {
|
||||
require.NotEmpty(t, attachments2[0].Actions)
|
||||
require.NotEmpty(t, attachments2[0].Actions[0].Id)
|
||||
|
||||
clientTriggerId, err := th.App.DoPostAction(post.Id, "notavalidid", th.BasicUser.Id, "")
|
||||
clientTriggerId, err := th.App.DoPostAction(th.Context, post.Id, "notavalidid", th.BasicUser.Id, "")
|
||||
require.NotNil(t, err)
|
||||
assert.Equal(t, http.StatusNotFound, err.StatusCode)
|
||||
assert.True(t, clientTriggerId == "")
|
||||
|
||||
clientTriggerId, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
clientTriggerId, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
assert.True(t, len(clientTriggerId) == 26)
|
||||
|
||||
clientTriggerId, err = th.App.DoPostAction(post2.Id, attachments2[0].Actions[0].Id, th.BasicUser.Id, "selected")
|
||||
clientTriggerId, err = th.App.DoPostAction(th.Context, post2.Id, attachments2[0].Actions[0].Id, th.BasicUser.Id, "selected")
|
||||
require.Nil(t, err)
|
||||
assert.True(t, len(clientTriggerId) == 26)
|
||||
|
||||
@@ -220,7 +220,7 @@ func TestPostAction(t *testing.T) {
|
||||
*cfg.ServiceSettings.AllowedUntrustedInternalConnections = ""
|
||||
})
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
_, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.NotNil(t, err)
|
||||
require.True(t, strings.Contains(err.Error(), "address forbidden"))
|
||||
|
||||
@@ -252,13 +252,13 @@ func TestPostAction(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
postplugin, err := th.App.CreatePostAsUser(&interactivePostPlugin, "", true)
|
||||
postplugin, err := th.App.CreatePostAsUser(th.Context, &interactivePostPlugin, "", true)
|
||||
require.Nil(t, err)
|
||||
|
||||
attachmentsPlugin, ok := postplugin.GetProp("attachments").([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
|
||||
_, err = th.App.DoPostAction(postplugin.Id, attachmentsPlugin[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
_, err = th.App.DoPostAction(th.Context, postplugin.Id, attachmentsPlugin[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
@@ -293,13 +293,13 @@ func TestPostAction(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
postSiteURL, err := th.App.CreatePostAsUser(&interactivePostSiteURL, "", true)
|
||||
postSiteURL, err := th.App.CreatePostAsUser(th.Context, &interactivePostSiteURL, "", true)
|
||||
require.Nil(t, err)
|
||||
|
||||
attachmentsSiteURL, ok := postSiteURL.GetProp("attachments").([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
|
||||
_, err = th.App.DoPostAction(postSiteURL.Id, attachmentsSiteURL[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
_, err = th.App.DoPostAction(th.Context, postSiteURL.Id, attachmentsSiteURL[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.NotNil(t, err)
|
||||
require.False(t, strings.Contains(err.Error(), "address forbidden"))
|
||||
|
||||
@@ -335,13 +335,13 @@ func TestPostAction(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
postSubpath, err := th.App.CreatePostAsUser(&interactivePostSubpath, "", true)
|
||||
postSubpath, err := th.App.CreatePostAsUser(th.Context, &interactivePostSubpath, "", true)
|
||||
require.Nil(t, err)
|
||||
|
||||
attachmentsSubpath, ok := postSubpath.GetProp("attachments").([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
|
||||
_, err = th.App.DoPostAction(postSubpath.Id, attachmentsSubpath[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
_, err = th.App.DoPostAction(th.Context, postSubpath.Id, attachmentsSubpath[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
|
||||
})
|
||||
@@ -410,12 +410,12 @@ func TestPostActionProps(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
post, err := th.App.CreatePostAsUser(&interactivePost, "", true)
|
||||
post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true)
|
||||
require.Nil(t, err)
|
||||
attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
|
||||
clientTriggerId, err := th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
clientTriggerId, err := th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
assert.True(t, len(clientTriggerId) == 26)
|
||||
|
||||
@@ -506,7 +506,7 @@ func TestSubmitInteractiveDialog(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`, `{"id": "myplugin", "backend": {"executable": "backend.exe"}}`, "myplugin", th.App)
|
||||
`, `{"id": "myplugin", "backend": {"executable": "backend.exe"}}`, "myplugin", th.App, th.Context)
|
||||
|
||||
hooks, err2 := th.App.GetPluginsEnvironment().HooksForPlugin("myplugin")
|
||||
require.NoError(t, err2)
|
||||
@@ -514,14 +514,14 @@ func TestSubmitInteractiveDialog(t *testing.T) {
|
||||
|
||||
submit.URL = ts.URL
|
||||
|
||||
resp, err := th.App.SubmitInteractiveDialog(submit)
|
||||
resp, err := th.App.SubmitInteractiveDialog(th.Context, submit)
|
||||
assert.Nil(t, err)
|
||||
require.NotNil(t, resp)
|
||||
assert.Equal(t, "some generic error", resp.Error)
|
||||
assert.Equal(t, "some error", resp.Errors["name1"])
|
||||
|
||||
submit.URL = ""
|
||||
resp, err = th.App.SubmitInteractiveDialog(submit)
|
||||
resp, err = th.App.SubmitInteractiveDialog(th.Context, submit)
|
||||
assert.NotNil(t, err)
|
||||
assert.Nil(t, resp)
|
||||
|
||||
@@ -531,18 +531,18 @@ func TestSubmitInteractiveDialog(t *testing.T) {
|
||||
})
|
||||
|
||||
submit.URL = "/notvalid/myplugin/myaction"
|
||||
resp, err = th.App.SubmitInteractiveDialog(submit)
|
||||
resp, err = th.App.SubmitInteractiveDialog(th.Context, submit)
|
||||
assert.NotNil(t, err)
|
||||
require.Nil(t, resp)
|
||||
|
||||
submit.URL = "/plugins/myplugin/myaction"
|
||||
resp, err = th.App.SubmitInteractiveDialog(submit)
|
||||
resp, err = th.App.SubmitInteractiveDialog(th.Context, submit)
|
||||
assert.Nil(t, err)
|
||||
require.NotNil(t, resp)
|
||||
assert.Equal(t, "some error", resp.Errors["name1"])
|
||||
|
||||
submit.URL = "/plugins/myplugin/myaction?abc=xyz"
|
||||
resp, err = th.App.SubmitInteractiveDialog(submit)
|
||||
resp, err = th.App.SubmitInteractiveDialog(th.Context, submit)
|
||||
assert.Nil(t, err)
|
||||
require.NotNil(t, resp)
|
||||
assert.Equal(t, "some other error", resp.Errors["name1"])
|
||||
@@ -588,14 +588,14 @@ func TestPostActionRelativeURL(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
post, err := th.App.CreatePostAsUser(&interactivePost, "", true)
|
||||
post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true)
|
||||
require.Nil(t, err)
|
||||
attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, attachments[0].Actions)
|
||||
require.NotEmpty(t, attachments[0].Actions[0].Id)
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
_, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.NotNil(t, err)
|
||||
})
|
||||
|
||||
@@ -628,14 +628,14 @@ func TestPostActionRelativeURL(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
post, err := th.App.CreatePostAsUser(&interactivePost, "", true)
|
||||
post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true)
|
||||
require.Nil(t, err)
|
||||
attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, attachments[0].Actions)
|
||||
require.NotEmpty(t, attachments[0].Actions[0].Id)
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
_, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.NotNil(t, err)
|
||||
})
|
||||
|
||||
@@ -668,14 +668,14 @@ func TestPostActionRelativeURL(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
post, err := th.App.CreatePostAsUser(&interactivePost, "", true)
|
||||
post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true)
|
||||
require.Nil(t, err)
|
||||
attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, attachments[0].Actions)
|
||||
require.NotEmpty(t, attachments[0].Actions[0].Id)
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
_, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.NotNil(t, err)
|
||||
|
||||
})
|
||||
@@ -709,14 +709,14 @@ func TestPostActionRelativeURL(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
post, err := th.App.CreatePostAsUser(&interactivePost, "", true)
|
||||
post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true)
|
||||
require.Nil(t, err)
|
||||
attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, attachments[0].Actions)
|
||||
require.NotEmpty(t, attachments[0].Actions[0].Id)
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
_, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.NotNil(t, err)
|
||||
})
|
||||
|
||||
@@ -749,14 +749,14 @@ func TestPostActionRelativeURL(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
post, err := th.App.CreatePostAsUser(&interactivePost, "", true)
|
||||
post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true)
|
||||
require.Nil(t, err)
|
||||
attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, attachments[0].Actions)
|
||||
require.NotEmpty(t, attachments[0].Actions[0].Id)
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
_, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.NotNil(t, err)
|
||||
})
|
||||
}
|
||||
@@ -788,7 +788,7 @@ func TestPostActionRelativePluginURL(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`, `{"id": "myplugin", "backend": {"executable": "backend.exe"}}`, "myplugin", th.App)
|
||||
`, `{"id": "myplugin", "backend": {"executable": "backend.exe"}}`, "myplugin", th.App, th.Context)
|
||||
|
||||
hooks, err2 := th.App.GetPluginsEnvironment().HooksForPlugin("myplugin")
|
||||
require.NoError(t, err2)
|
||||
@@ -823,14 +823,14 @@ func TestPostActionRelativePluginURL(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
post, err := th.App.CreatePostAsUser(&interactivePost, "", true)
|
||||
post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true)
|
||||
require.Nil(t, err)
|
||||
attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, attachments[0].Actions)
|
||||
require.NotEmpty(t, attachments[0].Actions[0].Id)
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
_, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.NotNil(t, err)
|
||||
})
|
||||
|
||||
@@ -863,14 +863,14 @@ func TestPostActionRelativePluginURL(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
post, err := th.App.CreatePostAsUser(&interactivePost, "", true)
|
||||
post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true)
|
||||
require.Nil(t, err)
|
||||
attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, attachments[0].Actions)
|
||||
require.NotEmpty(t, attachments[0].Actions[0].Id)
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
_, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
})
|
||||
|
||||
@@ -903,14 +903,14 @@ func TestPostActionRelativePluginURL(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
post, err := th.App.CreatePostAsUser(&interactivePost, "", true)
|
||||
post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true)
|
||||
require.Nil(t, err)
|
||||
attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, attachments[0].Actions)
|
||||
require.NotEmpty(t, attachments[0].Actions[0].Id)
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
_, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
})
|
||||
|
||||
@@ -943,14 +943,14 @@ func TestPostActionRelativePluginURL(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
post, err := th.App.CreatePostAsUser(&interactivePost, "", true)
|
||||
post, err := th.App.CreatePostAsUser(th.Context, &interactivePost, "", true)
|
||||
require.Nil(t, err)
|
||||
attachments, ok := post.GetProp("attachments").([]*model.SlackAttachment)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, attachments[0].Actions)
|
||||
require.NotEmpty(t, attachments[0].Actions[0].Id)
|
||||
|
||||
_, err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
_, err = th.App.DoPostAction(th.Context, post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id, "")
|
||||
require.Nil(t, err)
|
||||
})
|
||||
}
|
||||
@@ -1007,53 +1007,53 @@ func TestDoPluginRequest(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`, `{"id": "myplugin", "backend": {"executable": "backend.exe"}}`, "myplugin", th.App)
|
||||
`, `{"id": "myplugin", "backend": {"executable": "backend.exe"}}`, "myplugin", th.App, th.Context)
|
||||
|
||||
hooks, err2 := th.App.GetPluginsEnvironment().HooksForPlugin("myplugin")
|
||||
require.NoError(t, err2)
|
||||
require.NotNil(t, hooks)
|
||||
|
||||
resp, err := th.App.doPluginRequest("GET", "/plugins/myplugin", nil, nil)
|
||||
resp, err := th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin", nil, nil)
|
||||
assert.Nil(t, err)
|
||||
require.NotNil(t, resp)
|
||||
body, _ := ioutil.ReadAll(resp.Body)
|
||||
assert.Equal(t, "could not find param abc=xyz", string(body))
|
||||
|
||||
resp, err = th.App.doPluginRequest("GET", "/plugins/myplugin?abc=xyz", nil, nil)
|
||||
resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?abc=xyz", nil, nil)
|
||||
assert.Nil(t, err)
|
||||
require.NotNil(t, resp)
|
||||
body, _ = ioutil.ReadAll(resp.Body)
|
||||
assert.Equal(t, "param multiple should have 3 values", string(body))
|
||||
|
||||
resp, err = th.App.doPluginRequest("GET", "/plugins/myplugin",
|
||||
resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin",
|
||||
url.Values{"abc": []string{"xyz"}, "multiple": []string{"1 first", "2 second", "3 third"}}, nil)
|
||||
assert.Nil(t, err)
|
||||
require.NotNil(t, resp)
|
||||
body, _ = ioutil.ReadAll(resp.Body)
|
||||
assert.Equal(t, "OK", string(body))
|
||||
|
||||
resp, err = th.App.doPluginRequest("GET", "/plugins/myplugin?abc=xyz&multiple=1%20first",
|
||||
resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?abc=xyz&multiple=1%20first",
|
||||
url.Values{"multiple": []string{"2 second", "3 third"}}, nil)
|
||||
assert.Nil(t, err)
|
||||
require.NotNil(t, resp)
|
||||
body, _ = ioutil.ReadAll(resp.Body)
|
||||
assert.Equal(t, "OK", string(body))
|
||||
|
||||
resp, err = th.App.doPluginRequest("GET", "/plugins/myplugin?abc=xyz&multiple=1%20first&multiple=3%20third",
|
||||
resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?abc=xyz&multiple=1%20first&multiple=3%20third",
|
||||
url.Values{"multiple": []string{"2 second"}}, nil)
|
||||
assert.Nil(t, err)
|
||||
require.NotNil(t, resp)
|
||||
body, _ = ioutil.ReadAll(resp.Body)
|
||||
assert.Equal(t, "OK", string(body))
|
||||
|
||||
resp, err = th.App.doPluginRequest("GET", "/plugins/myplugin?multiple=1%20first&multiple=3%20third",
|
||||
resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?multiple=1%20first&multiple=3%20third",
|
||||
url.Values{"multiple": []string{"2 second"}, "abc": []string{"xyz"}}, nil)
|
||||
assert.Nil(t, err)
|
||||
require.NotNil(t, resp)
|
||||
body, _ = ioutil.ReadAll(resp.Body)
|
||||
assert.Equal(t, "OK", string(body))
|
||||
|
||||
resp, err = th.App.doPluginRequest("GET", "/plugins/myplugin?multiple=1%20first&multiple=3%20third",
|
||||
resp, err = th.App.doPluginRequest(th.Context, "GET", "/plugins/myplugin?multiple=1%20first&multiple=3%20third",
|
||||
url.Values{"multiple": []string{"4 fourth"}, "abc": []string{"xyz"}}, nil)
|
||||
assert.Nil(t, err)
|
||||
require.NotNil(t, resp)
|
||||
|
||||
@@ -19,14 +19,6 @@ type {{.Name}} struct {
|
||||
log *mlog.Logger
|
||||
notificationsLog *mlog.Logger
|
||||
|
||||
t i18n.TranslateFunc
|
||||
session model.Session
|
||||
requestId string
|
||||
ipAddress string
|
||||
path string
|
||||
userAgent string
|
||||
acceptLanguage string
|
||||
|
||||
accountMigration einterfaces.AccountMigrationInterface
|
||||
cluster einterfaces.ClusterInterface
|
||||
compliance einterfaces.ComplianceInterface
|
||||
@@ -42,7 +34,6 @@ type {{.Name}} struct {
|
||||
imageProxy *imageproxy.ImageProxy
|
||||
timezones *timezones.Timezones
|
||||
|
||||
context context.Context
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
@@ -84,15 +75,6 @@ func NewOpenTracingAppLayer(childApp app.AppIface, ctx context.Context) *{{.Name
|
||||
newApp.srv = childApp.Srv()
|
||||
newApp.log = childApp.Log()
|
||||
newApp.notificationsLog = childApp.NotificationsLog()
|
||||
newApp.t = childApp.GetT()
|
||||
if childApp.Session() != nil {
|
||||
newApp.session = *childApp.Session()
|
||||
}
|
||||
newApp.requestId = childApp.RequestId()
|
||||
newApp.ipAddress = childApp.IpAddress()
|
||||
newApp.path = childApp.Path()
|
||||
newApp.userAgent = childApp.UserAgent()
|
||||
newApp.acceptLanguage = childApp.AcceptLanguage()
|
||||
newApp.accountMigration = childApp.AccountMigration()
|
||||
newApp.cluster = childApp.Cluster()
|
||||
newApp.compliance = childApp.Compliance()
|
||||
@@ -106,7 +88,6 @@ func NewOpenTracingAppLayer(childApp app.AppIface, ctx context.Context) *{{.Name
|
||||
newApp.httpService = childApp.HTTPService()
|
||||
newApp.imageProxy = childApp.ImageProxy()
|
||||
newApp.timezones = childApp.Timezones()
|
||||
newApp.context = childApp.Context()
|
||||
|
||||
return &newApp
|
||||
}
|
||||
@@ -121,27 +102,6 @@ func (a *{{.Name}}) Log() *mlog.Logger {
|
||||
func (a *{{.Name}}) NotificationsLog() *mlog.Logger {
|
||||
return a.notificationsLog
|
||||
}
|
||||
func (a *{{.Name}}) T(translationID string, args ...interface{}) string {
|
||||
return a.t(translationID, args...)
|
||||
}
|
||||
func (a *{{.Name}}) Session() *model.Session {
|
||||
return &a.session
|
||||
}
|
||||
func (a *{{.Name}}) RequestId() string {
|
||||
return a.requestId
|
||||
}
|
||||
func (a *{{.Name}}) IpAddress() string {
|
||||
return a.ipAddress
|
||||
}
|
||||
func (a *{{.Name}}) Path() string {
|
||||
return a.path
|
||||
}
|
||||
func (a *{{.Name}}) UserAgent() string {
|
||||
return a.userAgent
|
||||
}
|
||||
func (a *{{.Name}}) AcceptLanguage() string {
|
||||
return a.acceptLanguage
|
||||
}
|
||||
func (a *{{.Name}}) AccountMigration() einterfaces.AccountMigrationInterface {
|
||||
return a.accountMigration
|
||||
}
|
||||
@@ -178,36 +138,6 @@ func (a *{{.Name}}) ImageProxy() *imageproxy.ImageProxy {
|
||||
func (a *{{.Name}}) Timezones() *timezones.Timezones {
|
||||
return a.timezones
|
||||
}
|
||||
func (a *{{.Name}}) Context() context.Context {
|
||||
return a.context
|
||||
}
|
||||
func (a *{{.Name}}) SetSession(sess *model.Session) {
|
||||
a.session = *sess
|
||||
}
|
||||
func (a *{{.Name}}) SetT(t i18n.TranslateFunc){
|
||||
a.t = t
|
||||
}
|
||||
func (a *{{.Name}}) SetRequestId(str string){
|
||||
a.requestId = str
|
||||
}
|
||||
func (a *{{.Name}}) SetIpAddress(str string){
|
||||
a.ipAddress = str
|
||||
}
|
||||
func (a *{{.Name}}) SetUserAgent(str string){
|
||||
a.userAgent = str
|
||||
}
|
||||
func (a *{{.Name}}) SetAcceptLanguage(str string) {
|
||||
a.acceptLanguage = str
|
||||
}
|
||||
func (a *{{.Name}}) SetPath(str string){
|
||||
a.path = str
|
||||
}
|
||||
func (a *{{.Name}}) SetContext(c context.Context){
|
||||
a.context = c
|
||||
}
|
||||
func (a *{{.Name}}) SetServer(srv *app.Server) {
|
||||
a.srv = srv
|
||||
}
|
||||
func (a *{{.Name}}) GetT() i18n.TranslateFunc {
|
||||
return a.t
|
||||
}
|
||||
a.srv = srv
|
||||
}
|
||||
22
app/login.go
22
app/login.go
@@ -15,6 +15,7 @@ import (
|
||||
|
||||
"github.com/avct/uasurfer"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/plugin"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
@@ -41,7 +42,7 @@ func (a *App) CheckForClientSideCert(r *http.Request) (string, string, string) {
|
||||
return pem, subject, email
|
||||
}
|
||||
|
||||
func (a *App) AuthenticateUserForLogin(id, loginId, password, mfaToken, cwsToken string, ldapOnly bool) (user *model.User, err *model.AppError) {
|
||||
func (a *App) AuthenticateUserForLogin(c *request.Context, id, loginId, password, mfaToken, cwsToken string, ldapOnly bool) (user *model.User, err *model.AppError) {
|
||||
// Do statistics
|
||||
defer func() {
|
||||
if a.Metrics() != nil {
|
||||
@@ -111,7 +112,7 @@ func (a *App) AuthenticateUserForLogin(id, loginId, password, mfaToken, cwsToken
|
||||
}
|
||||
|
||||
// and then authenticate them
|
||||
if user, err = a.authenticateUser(user, password, mfaToken); err != nil {
|
||||
if user, err = a.authenticateUser(c, user, password, mfaToken); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -154,10 +155,10 @@ func (a *App) GetUserForLogin(id, loginId string) (*model.User, *model.AppError)
|
||||
return nil, model.NewAppError("GetUserForLogin", "store.sql_user.get_for_login.app_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
func (a *App) DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, deviceID string, isMobile, isOAuthUser, isSaml bool) *model.AppError {
|
||||
func (a *App) DoLogin(c *request.Context, w http.ResponseWriter, r *http.Request, user *model.User, deviceID string, isMobile, isOAuthUser, isSaml bool) *model.AppError {
|
||||
if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil {
|
||||
var rejectionReason string
|
||||
pluginContext := a.PluginContext()
|
||||
pluginContext := pluginContext(c)
|
||||
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
|
||||
rejectionReason = hooks.UserWillLogIn(pluginContext, user)
|
||||
return rejectionReason == ""
|
||||
@@ -215,8 +216,7 @@ func (a *App) DoLogin(w http.ResponseWriter, r *http.Request, user *model.User,
|
||||
|
||||
w.Header().Set(model.HEADER_TOKEN, session.Token)
|
||||
|
||||
a.SetSession(session)
|
||||
|
||||
c.SetSession(session)
|
||||
if a.Srv().License() != nil && *a.Srv().License().Features.LDAP && a.Ldap() != nil {
|
||||
userVal := *user
|
||||
sessionVal := *session
|
||||
@@ -227,7 +227,7 @@ func (a *App) DoLogin(w http.ResponseWriter, r *http.Request, user *model.User,
|
||||
|
||||
if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil {
|
||||
a.Srv().Go(func() {
|
||||
pluginContext := a.PluginContext()
|
||||
pluginContext := pluginContext(c)
|
||||
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
|
||||
hooks.UserHasLoggedIn(pluginContext, user)
|
||||
return true
|
||||
@@ -238,7 +238,7 @@ func (a *App) DoLogin(w http.ResponseWriter, r *http.Request, user *model.User,
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) AttachSessionCookies(w http.ResponseWriter, r *http.Request) {
|
||||
func (a *App) AttachSessionCookies(c *request.Context, w http.ResponseWriter, r *http.Request) {
|
||||
secure := false
|
||||
if GetProtocol(r) == "https" {
|
||||
secure = true
|
||||
@@ -251,7 +251,7 @@ func (a *App) AttachSessionCookies(w http.ResponseWriter, r *http.Request) {
|
||||
expiresAt := time.Unix(model.GetMillis()/1000+int64(maxAge), 0)
|
||||
sessionCookie := &http.Cookie{
|
||||
Name: model.SESSION_COOKIE_TOKEN,
|
||||
Value: a.Session().Token,
|
||||
Value: c.Session().Token,
|
||||
Path: subpath,
|
||||
MaxAge: maxAge,
|
||||
Expires: expiresAt,
|
||||
@@ -262,7 +262,7 @@ func (a *App) AttachSessionCookies(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
userCookie := &http.Cookie{
|
||||
Name: model.SESSION_COOKIE_USER,
|
||||
Value: a.Session().UserId,
|
||||
Value: c.Session().UserId,
|
||||
Path: subpath,
|
||||
MaxAge: maxAge,
|
||||
Expires: expiresAt,
|
||||
@@ -272,7 +272,7 @@ func (a *App) AttachSessionCookies(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
csrfCookie := &http.Cookie{
|
||||
Name: model.SESSION_COOKIE_CSRF,
|
||||
Value: a.Session().GetCSRF(),
|
||||
Value: c.Session().GetCSRF(),
|
||||
Path: subpath,
|
||||
MaxAge: maxAge,
|
||||
Expires: expiresAt,
|
||||
|
||||
@@ -51,7 +51,7 @@ func TestCWSLogin(t *testing.T) {
|
||||
token := model.NewToken(TokenTypeCWSAccess, "")
|
||||
defer th.App.DeleteToken(token)
|
||||
os.Setenv("CWS_CLOUD_TOKEN", token.Token)
|
||||
user, err := th.App.AuthenticateUserForLogin("", th.BasicUser.Username, "", "", token.Token, false)
|
||||
user, err := th.App.AuthenticateUserForLogin(th.Context, "", th.BasicUser.Username, "", "", token.Token, false)
|
||||
require.Nil(t, err)
|
||||
require.NotNil(t, user)
|
||||
require.Equal(t, th.BasicUser.Username, user.Username)
|
||||
@@ -65,7 +65,7 @@ func TestCWSLogin(t *testing.T) {
|
||||
os.Setenv("CWS_CLOUD_TOKEN", token.Token)
|
||||
require.NoError(t, th.App.Srv().Store.Token().Save(token))
|
||||
defer th.App.DeleteToken(token)
|
||||
user, err := th.App.AuthenticateUserForLogin("", th.BasicUser.Username, "", "", token.Token, false)
|
||||
user, err := th.App.AuthenticateUserForLogin(th.Context, "", th.BasicUser.Username, "", "", token.Token, false)
|
||||
require.NotNil(t, err)
|
||||
require.Nil(t, user)
|
||||
})
|
||||
|
||||
@@ -20,25 +20,29 @@ const ContentExtractionConfigDefaultTrueMigrationKey = "ContentExtractionConfigD
|
||||
|
||||
// This function migrates the default built in roles from code/config to the database.
|
||||
func (a *App) DoAdvancedPermissionsMigration() {
|
||||
a.Srv().doAdvancedPermissionsMigration()
|
||||
}
|
||||
|
||||
func (s *Server) doAdvancedPermissionsMigration() {
|
||||
// If the migration is already marked as completed, don't do it again.
|
||||
if _, err := a.Srv().Store.System().GetByName(model.ADVANCED_PERMISSIONS_MIGRATION_KEY); err == nil {
|
||||
if _, err := s.Store.System().GetByName(model.ADVANCED_PERMISSIONS_MIGRATION_KEY); err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
mlog.Info("Migrating roles to database.")
|
||||
roles := model.MakeDefaultRoles()
|
||||
roles = utils.SetRolePermissionsFromConfig(roles, a.Config(), a.Srv().License() != nil)
|
||||
roles = utils.SetRolePermissionsFromConfig(roles, s.Config(), s.License() != nil)
|
||||
|
||||
allSucceeded := true
|
||||
|
||||
for _, role := range roles {
|
||||
_, err := a.Srv().Store.Role().Save(role)
|
||||
_, err := s.Store.Role().Save(role)
|
||||
if err == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// If this failed for reasons other than the role already existing, don't mark the migration as done.
|
||||
fetchedRole, err := a.Srv().Store.Role().GetByName(context.Background(), role.Name)
|
||||
fetchedRole, err := s.Store.Role().GetByName(context.Background(), role.Name)
|
||||
if err != nil {
|
||||
mlog.Critical("Failed to migrate role to database.", mlog.Err(err))
|
||||
allSucceeded = false
|
||||
@@ -51,7 +55,7 @@ func (a *App) DoAdvancedPermissionsMigration() {
|
||||
fetchedRole.Description != role.Description ||
|
||||
fetchedRole.SchemeManaged != role.SchemeManaged {
|
||||
role.Id = fetchedRole.Id
|
||||
if _, err = a.Srv().Store.Role().Save(role); err != nil {
|
||||
if _, err = s.Store.Role().Save(role); err != nil {
|
||||
// Role is not the same, but failed to update.
|
||||
mlog.Critical("Failed to migrate role to database.", mlog.Err(err))
|
||||
allSucceeded = false
|
||||
@@ -63,10 +67,10 @@ func (a *App) DoAdvancedPermissionsMigration() {
|
||||
return
|
||||
}
|
||||
|
||||
config := a.Config()
|
||||
config := s.Config()
|
||||
if *config.ServiceSettings.DEPRECATED_DO_NOT_USE_AllowEditPost == model.ALLOW_EDIT_POST_ALWAYS {
|
||||
*config.ServiceSettings.PostEditTimeLimit = -1
|
||||
if err := a.SaveConfig(config, true); err != nil {
|
||||
if err := s.SaveConfig(config, true); err != nil {
|
||||
mlog.Error("Failed to update config in Advanced Permissions Phase 1 Migration.", mlog.Err(err))
|
||||
}
|
||||
}
|
||||
@@ -76,7 +80,7 @@ func (a *App) DoAdvancedPermissionsMigration() {
|
||||
Value: "true",
|
||||
}
|
||||
|
||||
if err := a.Srv().Store.System().Save(&system); err != nil {
|
||||
if err := s.Store.System().Save(&system); err != nil {
|
||||
mlog.Critical("Failed to mark advanced permissions migration as completed.", mlog.Err(err))
|
||||
}
|
||||
}
|
||||
@@ -92,8 +96,12 @@ func (a *App) SetPhase2PermissionsMigrationStatus(isComplete bool) error {
|
||||
}
|
||||
|
||||
func (a *App) DoEmojisPermissionsMigration() {
|
||||
a.Srv().doEmojisPermissionsMigration()
|
||||
}
|
||||
|
||||
func (s *Server) doEmojisPermissionsMigration() {
|
||||
// If the migration is already marked as completed, don't do it again.
|
||||
if _, err := a.Srv().Store.System().GetByName(EmojisPermissionsMigrationKey); err == nil {
|
||||
if _, err := s.Store.System().GetByName(EmojisPermissionsMigrationKey); err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -102,15 +110,15 @@ func (a *App) DoEmojisPermissionsMigration() {
|
||||
var err *model.AppError
|
||||
|
||||
mlog.Info("Migrating emojis config to database.")
|
||||
switch *a.Config().ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation {
|
||||
switch *s.Config().ServiceSettings.DEPRECATED_DO_NOT_USE_RestrictCustomEmojiCreation {
|
||||
case model.RESTRICT_EMOJI_CREATION_ALL:
|
||||
role, err = a.GetRoleByName(context.Background(), model.SYSTEM_USER_ROLE_ID)
|
||||
role, err = s.GetRoleByName(context.Background(), model.SYSTEM_USER_ROLE_ID)
|
||||
if err != nil {
|
||||
mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err))
|
||||
return
|
||||
}
|
||||
case model.RESTRICT_EMOJI_CREATION_ADMIN:
|
||||
role, err = a.GetRoleByName(context.Background(), model.TEAM_ADMIN_ROLE_ID)
|
||||
role, err = s.GetRoleByName(context.Background(), model.TEAM_ADMIN_ROLE_ID)
|
||||
if err != nil {
|
||||
mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err))
|
||||
return
|
||||
@@ -124,13 +132,13 @@ func (a *App) DoEmojisPermissionsMigration() {
|
||||
|
||||
if role != nil {
|
||||
role.Permissions = append(role.Permissions, model.PERMISSION_CREATE_EMOJIS.Id, model.PERMISSION_DELETE_EMOJIS.Id)
|
||||
if _, nErr := a.Srv().Store.Role().Save(role); nErr != nil {
|
||||
if _, nErr := s.Store.Role().Save(role); nErr != nil {
|
||||
mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(nErr))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
systemAdminRole, err = a.GetRoleByName(context.Background(), model.SYSTEM_ADMIN_ROLE_ID)
|
||||
systemAdminRole, err = s.GetRoleByName(context.Background(), model.SYSTEM_ADMIN_ROLE_ID)
|
||||
if err != nil {
|
||||
mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err))
|
||||
return
|
||||
@@ -141,7 +149,7 @@ func (a *App) DoEmojisPermissionsMigration() {
|
||||
model.PERMISSION_DELETE_EMOJIS.Id,
|
||||
model.PERMISSION_DELETE_OTHERS_EMOJIS.Id,
|
||||
)
|
||||
if _, err := a.Srv().Store.Role().Save(systemAdminRole); err != nil {
|
||||
if _, err := s.Store.Role().Save(systemAdminRole); err != nil {
|
||||
mlog.Critical("Failed to migrate emojis creation permissions from mattermost config.", mlog.Err(err))
|
||||
return
|
||||
}
|
||||
@@ -151,40 +159,44 @@ func (a *App) DoEmojisPermissionsMigration() {
|
||||
Value: "true",
|
||||
}
|
||||
|
||||
if err := a.Srv().Store.System().Save(&system); err != nil {
|
||||
if err := s.Store.System().Save(&system); err != nil {
|
||||
mlog.Critical("Failed to mark emojis permissions migration as completed.", mlog.Err(err))
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) DoGuestRolesCreationMigration() {
|
||||
a.Srv().doGuestRolesCreationMigration()
|
||||
}
|
||||
|
||||
func (s *Server) doGuestRolesCreationMigration() {
|
||||
// If the migration is already marked as completed, don't do it again.
|
||||
if _, err := a.Srv().Store.System().GetByName(GuestRolesCreationMigrationKey); err == nil {
|
||||
if _, err := s.Store.System().GetByName(GuestRolesCreationMigrationKey); err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
roles := model.MakeDefaultRoles()
|
||||
|
||||
allSucceeded := true
|
||||
if _, err := a.Srv().Store.Role().GetByName(context.Background(), model.CHANNEL_GUEST_ROLE_ID); err != nil {
|
||||
if _, err := a.Srv().Store.Role().Save(roles[model.CHANNEL_GUEST_ROLE_ID]); err != nil {
|
||||
if _, err := s.Store.Role().GetByName(context.Background(), model.CHANNEL_GUEST_ROLE_ID); err != nil {
|
||||
if _, err := s.Store.Role().Save(roles[model.CHANNEL_GUEST_ROLE_ID]); err != nil {
|
||||
mlog.Critical("Failed to create new guest role to database.", mlog.Err(err))
|
||||
allSucceeded = false
|
||||
}
|
||||
}
|
||||
if _, err := a.Srv().Store.Role().GetByName(context.Background(), model.TEAM_GUEST_ROLE_ID); err != nil {
|
||||
if _, err := a.Srv().Store.Role().Save(roles[model.TEAM_GUEST_ROLE_ID]); err != nil {
|
||||
if _, err := s.Store.Role().GetByName(context.Background(), model.TEAM_GUEST_ROLE_ID); err != nil {
|
||||
if _, err := s.Store.Role().Save(roles[model.TEAM_GUEST_ROLE_ID]); err != nil {
|
||||
mlog.Critical("Failed to create new guest role to database.", mlog.Err(err))
|
||||
allSucceeded = false
|
||||
}
|
||||
}
|
||||
if _, err := a.Srv().Store.Role().GetByName(context.Background(), model.SYSTEM_GUEST_ROLE_ID); err != nil {
|
||||
if _, err := a.Srv().Store.Role().Save(roles[model.SYSTEM_GUEST_ROLE_ID]); err != nil {
|
||||
if _, err := s.Store.Role().GetByName(context.Background(), model.SYSTEM_GUEST_ROLE_ID); err != nil {
|
||||
if _, err := s.Store.Role().Save(roles[model.SYSTEM_GUEST_ROLE_ID]); err != nil {
|
||||
mlog.Critical("Failed to create new guest role to database.", mlog.Err(err))
|
||||
allSucceeded = false
|
||||
}
|
||||
}
|
||||
|
||||
schemes, err := a.Srv().Store.Scheme().GetAllPage("", 0, 1000000)
|
||||
schemes, err := s.Store.Scheme().GetAllPage("", 0, 1000000)
|
||||
if err != nil {
|
||||
mlog.Critical("Failed to get all schemes.", mlog.Err(err))
|
||||
allSucceeded = false
|
||||
@@ -200,7 +212,7 @@ func (a *App) DoGuestRolesCreationMigration() {
|
||||
SchemeManaged: true,
|
||||
}
|
||||
|
||||
if savedRole, err := a.Srv().Store.Role().Save(teamGuestRole); err != nil {
|
||||
if savedRole, err := s.Store.Role().Save(teamGuestRole); err != nil {
|
||||
mlog.Critical("Failed to create new guest role for custom scheme.", mlog.Err(err))
|
||||
allSucceeded = false
|
||||
} else {
|
||||
@@ -216,14 +228,14 @@ func (a *App) DoGuestRolesCreationMigration() {
|
||||
SchemeManaged: true,
|
||||
}
|
||||
|
||||
if savedRole, err := a.Srv().Store.Role().Save(channelGuestRole); err != nil {
|
||||
if savedRole, err := s.Store.Role().Save(channelGuestRole); err != nil {
|
||||
mlog.Critical("Failed to create new guest role for custom scheme.", mlog.Err(err))
|
||||
allSucceeded = false
|
||||
} else {
|
||||
scheme.DefaultChannelGuestRole = savedRole.Name
|
||||
}
|
||||
|
||||
_, err := a.Srv().Store.Scheme().Save(scheme)
|
||||
_, err := s.Store.Scheme().Save(scheme)
|
||||
if err != nil {
|
||||
mlog.Critical("Failed to update custom scheme.", mlog.Err(err))
|
||||
allSucceeded = false
|
||||
@@ -240,34 +252,38 @@ func (a *App) DoGuestRolesCreationMigration() {
|
||||
Value: "true",
|
||||
}
|
||||
|
||||
if err := a.Srv().Store.System().Save(&system); err != nil {
|
||||
if err := s.Store.System().Save(&system); err != nil {
|
||||
mlog.Critical("Failed to mark guest roles creation migration as completed.", mlog.Err(err))
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) DoSystemConsoleRolesCreationMigration() {
|
||||
a.Srv().doSystemConsoleRolesCreationMigration()
|
||||
}
|
||||
|
||||
func (s *Server) doSystemConsoleRolesCreationMigration() {
|
||||
// If the migration is already marked as completed, don't do it again.
|
||||
if _, err := a.Srv().Store.System().GetByName(SystemConsoleRolesCreationMigrationKey); err == nil {
|
||||
if _, err := s.Store.System().GetByName(SystemConsoleRolesCreationMigrationKey); err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
roles := model.MakeDefaultRoles()
|
||||
|
||||
allSucceeded := true
|
||||
if _, err := a.Srv().Store.Role().GetByName(context.Background(), model.SYSTEM_MANAGER_ROLE_ID); err != nil {
|
||||
if _, err := a.Srv().Store.Role().Save(roles[model.SYSTEM_MANAGER_ROLE_ID]); err != nil {
|
||||
if _, err := s.Store.Role().GetByName(context.Background(), model.SYSTEM_MANAGER_ROLE_ID); err != nil {
|
||||
if _, err := s.Store.Role().Save(roles[model.SYSTEM_MANAGER_ROLE_ID]); err != nil {
|
||||
mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SYSTEM_MANAGER_ROLE_ID))
|
||||
allSucceeded = false
|
||||
}
|
||||
}
|
||||
if _, err := a.Srv().Store.Role().GetByName(context.Background(), model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID); err != nil {
|
||||
if _, err := a.Srv().Store.Role().Save(roles[model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID]); err != nil {
|
||||
if _, err := s.Store.Role().GetByName(context.Background(), model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID); err != nil {
|
||||
if _, err := s.Store.Role().Save(roles[model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID]); err != nil {
|
||||
mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SYSTEM_READ_ONLY_ADMIN_ROLE_ID))
|
||||
allSucceeded = false
|
||||
}
|
||||
}
|
||||
if _, err := a.Srv().Store.Role().GetByName(context.Background(), model.SYSTEM_USER_MANAGER_ROLE_ID); err != nil {
|
||||
if _, err := a.Srv().Store.Role().Save(roles[model.SYSTEM_USER_MANAGER_ROLE_ID]); err != nil {
|
||||
if _, err := s.Store.Role().GetByName(context.Background(), model.SYSTEM_USER_MANAGER_ROLE_ID); err != nil {
|
||||
if _, err := s.Store.Role().Save(roles[model.SYSTEM_USER_MANAGER_ROLE_ID]); err != nil {
|
||||
mlog.Critical("Failed to create new role.", mlog.Err(err), mlog.String("role", model.SYSTEM_USER_MANAGER_ROLE_ID))
|
||||
allSucceeded = false
|
||||
}
|
||||
@@ -282,18 +298,18 @@ func (a *App) DoSystemConsoleRolesCreationMigration() {
|
||||
Value: "true",
|
||||
}
|
||||
|
||||
if err := a.Srv().Store.System().Save(&system); err != nil {
|
||||
if err := s.Store.System().Save(&system); err != nil {
|
||||
mlog.Critical("Failed to mark system console roles creation migration as completed.", mlog.Err(err))
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) doContentExtractionConfigDefaultTrueMigration() {
|
||||
func (s *Server) doContentExtractionConfigDefaultTrueMigration() {
|
||||
// If the migration is already marked as completed, don't do it again.
|
||||
if _, err := a.Srv().Store.System().GetByName(ContentExtractionConfigDefaultTrueMigrationKey); err == nil {
|
||||
if _, err := s.Store.System().GetByName(ContentExtractionConfigDefaultTrueMigrationKey); err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
a.UpdateConfig(func(config *model.Config) {
|
||||
s.UpdateConfig(func(config *model.Config) {
|
||||
config.FileSettings.ExtractContent = model.NewBool(true)
|
||||
})
|
||||
|
||||
@@ -302,21 +318,25 @@ func (a *App) doContentExtractionConfigDefaultTrueMigration() {
|
||||
Value: "true",
|
||||
}
|
||||
|
||||
if err := a.Srv().Store.System().Save(&system); err != nil {
|
||||
if err := s.Store.System().Save(&system); err != nil {
|
||||
mlog.Critical("Failed to mark content extraction config migration as completed.", mlog.Err(err))
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) DoAppMigrations() {
|
||||
a.DoAdvancedPermissionsMigration()
|
||||
a.DoEmojisPermissionsMigration()
|
||||
a.DoGuestRolesCreationMigration()
|
||||
a.DoSystemConsoleRolesCreationMigration()
|
||||
a.Srv().doAppMigrations()
|
||||
}
|
||||
|
||||
func (s *Server) doAppMigrations() {
|
||||
s.doAdvancedPermissionsMigration()
|
||||
s.doEmojisPermissionsMigration()
|
||||
s.doGuestRolesCreationMigration()
|
||||
s.doSystemConsoleRolesCreationMigration()
|
||||
// This migration always must be the last, because can be based on previous
|
||||
// migrations. For example, it needs the guest roles migration.
|
||||
err := a.DoPermissionsMigrations()
|
||||
err := s.doPermissionsMigrations()
|
||||
if err != nil {
|
||||
mlog.Critical("(app.App).DoPermissionsMigrations failed", mlog.Err(err))
|
||||
}
|
||||
a.doContentExtractionConfigDefaultTrueMigration()
|
||||
s.doContentExtractionConfigDefaultTrueMigration()
|
||||
}
|
||||
|
||||
@@ -1283,7 +1283,7 @@ func TestAllPushNotifications(t *testing.T) {
|
||||
ExpiresAt: model.GetMillis() + 100000,
|
||||
})
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.AddTeamMember(th.BasicTeam.Id, u.Id)
|
||||
_, err = th.App.AddTeamMember(th.Context, th.BasicTeam.Id, u.Id)
|
||||
require.Nil(t, err)
|
||||
th.AddUserToChannel(u, th.BasicChannel)
|
||||
testData = append(testData, userSession{
|
||||
|
||||
@@ -21,7 +21,7 @@ func TestSendNotifications(t *testing.T) {
|
||||
|
||||
th.App.AddUserToChannel(th.BasicUser2, th.BasicChannel, false)
|
||||
|
||||
post1, appErr := th.App.CreatePostMissingChannel(&model.Post{
|
||||
post1, appErr := th.App.CreatePostMissingChannel(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "@" + th.BasicUser2.Username,
|
||||
@@ -35,10 +35,10 @@ func TestSendNotifications(t *testing.T) {
|
||||
require.NotNil(t, mentions)
|
||||
require.True(t, utils.StringInSlice(th.BasicUser2.Id, mentions), "mentions", mentions)
|
||||
|
||||
dm, appErr := th.App.GetOrCreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id)
|
||||
dm, appErr := th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
post2, appErr := th.App.CreatePostMissingChannel(&model.Post{
|
||||
post2, appErr := th.App.CreatePostMissingChannel(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: dm.Id,
|
||||
Message: "dm message",
|
||||
@@ -49,12 +49,12 @@ func TestSendNotifications(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, mentions)
|
||||
|
||||
_, appErr = th.App.UpdateActive(th.BasicUser2, false)
|
||||
_, appErr = th.App.UpdateActive(th.Context, th.BasicUser2, false)
|
||||
require.Nil(t, appErr)
|
||||
appErr = th.App.Srv().InvalidateAllCaches()
|
||||
require.Nil(t, appErr)
|
||||
|
||||
post3, appErr := th.App.CreatePostMissingChannel(&model.Post{
|
||||
post3, appErr := th.App.CreatePostMissingChannel(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: dm.Id,
|
||||
Message: "dm message",
|
||||
@@ -81,7 +81,7 @@ func TestSendNotifications(t *testing.T) {
|
||||
Props: model.StringInterface{"from_webhook": "true", "override_username": "a bot"},
|
||||
}
|
||||
|
||||
rootPost, appErr = th.App.CreatePostMissingChannel(rootPost, false)
|
||||
rootPost, appErr = th.App.CreatePostMissingChannel(th.Context, rootPost, false)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
childPost := &model.Post{
|
||||
@@ -90,7 +90,7 @@ func TestSendNotifications(t *testing.T) {
|
||||
RootId: rootPost.Id,
|
||||
Message: "a reply",
|
||||
}
|
||||
childPost, appErr = th.App.CreatePostMissingChannel(childPost, false)
|
||||
childPost, appErr = th.App.CreatePostMissingChannel(th.Context, childPost, false)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
postList := model.PostList{
|
||||
@@ -130,7 +130,7 @@ func TestSendNotificationsWithManyUsers(t *testing.T) {
|
||||
users = append(users, user)
|
||||
}
|
||||
|
||||
_, appErr1 := th.App.CreatePostMissingChannel(&model.Post{
|
||||
_, appErr1 := th.App.CreatePostMissingChannel(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "@channel",
|
||||
@@ -150,7 +150,7 @@ func TestSendNotificationsWithManyUsers(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
_, appErr1 = th.App.CreatePostMissingChannel(&model.Post{
|
||||
_, appErr1 = th.App.CreatePostMissingChannel(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "@channel",
|
||||
@@ -213,7 +213,7 @@ func TestFilterOutOfChannelMentions(t *testing.T) {
|
||||
guest := th.CreateGuest()
|
||||
user4 := th.CreateUser()
|
||||
guestAndUser4Channel := th.CreateChannel(th.BasicTeam)
|
||||
defer th.App.PermanentDeleteUser(guest)
|
||||
defer th.App.PermanentDeleteUser(th.Context, guest)
|
||||
th.LinkUserToTeam(user3, th.BasicTeam)
|
||||
th.LinkUserToTeam(user4, th.BasicTeam)
|
||||
th.LinkUserToTeam(guest, th.BasicTeam)
|
||||
@@ -289,7 +289,7 @@ func TestFilterOutOfChannelMentions(t *testing.T) {
|
||||
|
||||
t.Run("should not return inactive users", func(t *testing.T) {
|
||||
inactiveUser := th.CreateUser()
|
||||
inactiveUser, appErr := th.App.UpdateActive(inactiveUser, false)
|
||||
inactiveUser, appErr := th.App.UpdateActive(th.Context, inactiveUser, false)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
post := &model.Post{}
|
||||
|
||||
17
app/oauth.go
17
app/oauth.go
@@ -17,6 +17,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/einterfaces"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
@@ -546,22 +547,22 @@ func (a *App) RevokeAccessToken(token string) *model.AppError {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) CompleteOAuth(service string, body io.ReadCloser, teamID string, props map[string]string, tokenUser *model.User) (*model.User, *model.AppError) {
|
||||
func (a *App) CompleteOAuth(c *request.Context, service string, body io.ReadCloser, teamID string, props map[string]string, tokenUser *model.User) (*model.User, *model.AppError) {
|
||||
defer body.Close()
|
||||
|
||||
action := props["action"]
|
||||
|
||||
switch action {
|
||||
case model.OAUTH_ACTION_SIGNUP:
|
||||
return a.CreateOAuthUser(service, body, teamID, tokenUser)
|
||||
return a.CreateOAuthUser(c, service, body, teamID, tokenUser)
|
||||
case model.OAUTH_ACTION_LOGIN:
|
||||
return a.LoginByOAuth(service, body, teamID, tokenUser)
|
||||
return a.LoginByOAuth(c, service, body, teamID, tokenUser)
|
||||
case model.OAUTH_ACTION_EMAIL_TO_SSO:
|
||||
return a.CompleteSwitchWithOAuth(service, body, props["email"], tokenUser)
|
||||
case model.OAUTH_ACTION_SSO_TO_EMAIL:
|
||||
return a.LoginByOAuth(service, body, teamID, tokenUser)
|
||||
return a.LoginByOAuth(c, service, body, teamID, tokenUser)
|
||||
default:
|
||||
return a.LoginByOAuth(service, body, teamID, tokenUser)
|
||||
return a.LoginByOAuth(c, service, body, teamID, tokenUser)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -582,7 +583,7 @@ func (a *App) getSSOProvider(service string) (einterfaces.OauthProvider, *model.
|
||||
return provider, nil
|
||||
}
|
||||
|
||||
func (a *App) LoginByOAuth(service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError) {
|
||||
func (a *App) LoginByOAuth(c *request.Context, service string, userData io.Reader, teamID string, tokenUser *model.User) (*model.User, *model.AppError) {
|
||||
provider, e := a.getSSOProvider(service)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
@@ -608,7 +609,7 @@ func (a *App) LoginByOAuth(service string, userData io.Reader, teamID string, to
|
||||
user, err := a.GetUserByAuth(model.NewString(*authUser.AuthData), service)
|
||||
if err != nil {
|
||||
if err.Id == MissingAuthAccountError {
|
||||
user, err = a.CreateOAuthUser(service, bytes.NewReader(buf.Bytes()), teamID, tokenUser)
|
||||
user, err = a.CreateOAuthUser(c, service, bytes.NewReader(buf.Bytes()), teamID, tokenUser)
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
@@ -624,7 +625,7 @@ func (a *App) LoginByOAuth(service string, userData io.Reader, teamID string, to
|
||||
return nil, err
|
||||
}
|
||||
if teamID != "" {
|
||||
err = a.AddUserToTeamByTeamId(teamID, user)
|
||||
err = a.AddUserToTeamByTeamId(c, teamID, user)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
@@ -95,6 +95,14 @@ func SetLogger(logger *mlog.Logger) Option {
|
||||
}
|
||||
}
|
||||
|
||||
func SkipPostInitializiation() Option {
|
||||
return func(s *Server) error {
|
||||
s.skipPostInit = true
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
type AppOption func(a *App)
|
||||
type AppOptionCreator func() []AppOption
|
||||
|
||||
|
||||
@@ -157,8 +157,8 @@ func applyPermissionsMap(role *model.Role, roleMap map[string]map[string]bool, m
|
||||
return result
|
||||
}
|
||||
|
||||
func (a *App) doPermissionsMigration(key string, migrationMap permissionsMap, roles []*model.Role) *model.AppError {
|
||||
if _, err := a.Srv().Store.System().GetByName(key); err == nil {
|
||||
func (s *Server) doPermissionsMigration(key string, migrationMap permissionsMap, roles []*model.Role) *model.AppError {
|
||||
if _, err := s.Store.System().GetByName(key); err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -172,7 +172,7 @@ func (a *App) doPermissionsMigration(key string, migrationMap permissionsMap, ro
|
||||
|
||||
for _, role := range roles {
|
||||
role.Permissions = applyPermissionsMap(role, roleMap, migrationMap)
|
||||
if _, err := a.Srv().Store.Role().Save(role); err != nil {
|
||||
if _, err := s.Store.Role().Save(role); err != nil {
|
||||
var invErr *store.ErrInvalidInput
|
||||
switch {
|
||||
case errors.As(err, &invErr):
|
||||
@@ -183,7 +183,7 @@ func (a *App) doPermissionsMigration(key string, migrationMap permissionsMap, ro
|
||||
}
|
||||
}
|
||||
|
||||
if err := a.Srv().Store.System().Save(&model.System{Name: key, Value: "true"}); err != nil {
|
||||
if err := s.Store.System().Save(&model.System{Name: key, Value: "true"}); err != nil {
|
||||
return model.NewAppError("doPermissionsMigration", "app.system.save.app_error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
return nil
|
||||
@@ -904,6 +904,11 @@ func (a *App) getAddAuthenticationSubsectionPermissions() (permissionsMap, error
|
||||
|
||||
// DoPermissionsMigrations execute all the permissions migrations need by the current version.
|
||||
func (a *App) DoPermissionsMigrations() error {
|
||||
return a.Srv().doPermissionsMigrations()
|
||||
}
|
||||
|
||||
func (s *Server) doPermissionsMigrations() error {
|
||||
a := New(ServerConnector(s))
|
||||
PermissionsMigrations := []struct {
|
||||
Key string
|
||||
Migration func() (permissionsMap, error)
|
||||
@@ -936,7 +941,7 @@ func (a *App) DoPermissionsMigrations() error {
|
||||
{Key: model.MIGRATION_KEY_ADD_REPORTING_SUBSECTION_PERMISSIONS, Migration: a.getAddReportingSubsectionPermissions},
|
||||
}
|
||||
|
||||
roles, err := a.srv.Store.Role().GetAll()
|
||||
roles, err := s.Store.Role().GetAll()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -946,7 +951,7 @@ func (a *App) DoPermissionsMigrations() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := a.doPermissionsMigration(migration.Key, migMap, roles); err != nil {
|
||||
if err := s.doPermissionsMigration(migration.Key, migMap, roles); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
215
app/plugin.go
215
app/plugin.go
@@ -20,6 +20,7 @@ import (
|
||||
svg "github.com/h2non/go-is-svg"
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/plugin"
|
||||
"github.com/mattermost/mattermost-server/v5/services/marketplace"
|
||||
@@ -69,21 +70,25 @@ func (a *App) SetPluginsEnvironment(pluginsEnvironment *plugin.Environment) {
|
||||
}
|
||||
|
||||
func (a *App) SyncPluginsActiveState() {
|
||||
a.Srv().syncPluginsActiveState()
|
||||
}
|
||||
|
||||
func (s *Server) syncPluginsActiveState() {
|
||||
// Acquiring lock manually, as plugins might be disabled. See GetPluginsEnvironment.
|
||||
a.Srv().PluginsLock.RLock()
|
||||
pluginsEnvironment := a.Srv().PluginsEnvironment
|
||||
a.Srv().PluginsLock.RUnlock()
|
||||
s.PluginsLock.RLock()
|
||||
pluginsEnvironment := s.PluginsEnvironment
|
||||
s.PluginsLock.RUnlock()
|
||||
|
||||
if pluginsEnvironment == nil {
|
||||
return
|
||||
}
|
||||
|
||||
config := a.Config().PluginSettings
|
||||
config := s.Config().PluginSettings
|
||||
|
||||
if *config.Enable {
|
||||
availablePlugins, err := pluginsEnvironment.Available()
|
||||
if err != nil {
|
||||
a.Log().Error("Unable to get available plugins", mlog.Err(err))
|
||||
s.Log.Error("Unable to get available plugins", mlog.Err(err))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -99,7 +104,7 @@ func (a *App) SyncPluginsActiveState() {
|
||||
|
||||
// Tie Apps proxy disabled status to the feature flag.
|
||||
if pluginID == "com.mattermost.apps" {
|
||||
if !a.Config().FeatureFlags.AppsEnabled {
|
||||
if !s.Config().FeatureFlags.AppsEnabled {
|
||||
pluginEnabled = false
|
||||
}
|
||||
}
|
||||
@@ -124,7 +129,7 @@ func (a *App) SyncPluginsActiveState() {
|
||||
if deactivated && plugin.Manifest.HasClient() {
|
||||
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PLUGIN_DISABLED, "", "", "", nil)
|
||||
message.Add("manifest", plugin.Manifest.ClientManifest())
|
||||
a.Publish(message)
|
||||
s.Publish(message)
|
||||
}
|
||||
}(plugin)
|
||||
}
|
||||
@@ -138,14 +143,14 @@ func (a *App) SyncPluginsActiveState() {
|
||||
pluginID := plugin.Manifest.Id
|
||||
updatedManifest, activated, err := pluginsEnvironment.Activate(pluginID)
|
||||
if err != nil {
|
||||
plugin.WrapLogger(a.Log()).Error("Unable to activate plugin", mlog.Err(err))
|
||||
plugin.WrapLogger(s.Log).Error("Unable to activate plugin", mlog.Err(err))
|
||||
return
|
||||
}
|
||||
|
||||
if activated {
|
||||
// Notify all cluster clients if ready
|
||||
if err := a.notifyPluginEnabled(updatedManifest); err != nil {
|
||||
a.Log().Error("Failed to notify cluster on plugin enable", mlog.Err(err))
|
||||
if err := s.notifyPluginEnabled(updatedManifest); err != nil {
|
||||
s.Log.Error("Failed to notify cluster on plugin enable", mlog.Err(err))
|
||||
}
|
||||
}
|
||||
}(plugin)
|
||||
@@ -155,26 +160,30 @@ func (a *App) SyncPluginsActiveState() {
|
||||
pluginsEnvironment.Shutdown()
|
||||
}
|
||||
|
||||
if err := a.notifyPluginStatusesChanged(); err != nil {
|
||||
if err := s.notifyPluginStatusesChanged(); err != nil {
|
||||
mlog.Warn("failed to notify plugin status changed", mlog.Err(err))
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) NewPluginAPI(manifest *model.Manifest) plugin.API {
|
||||
return NewPluginAPI(a, manifest)
|
||||
func (a *App) NewPluginAPI(c *request.Context, manifest *model.Manifest) plugin.API {
|
||||
return NewPluginAPI(a, c, manifest)
|
||||
}
|
||||
|
||||
func (a *App) InitPlugins(pluginDir, webappPluginDir string) {
|
||||
func (a *App) InitPlugins(c *request.Context, pluginDir, webappPluginDir string) {
|
||||
a.Srv().initPlugins(c, pluginDir, webappPluginDir)
|
||||
}
|
||||
|
||||
func (s *Server) initPlugins(c *request.Context, pluginDir, webappPluginDir string) {
|
||||
// Acquiring lock manually, as plugins might be disabled. See GetPluginsEnvironment.
|
||||
a.Srv().PluginsLock.RLock()
|
||||
pluginsEnvironment := a.Srv().PluginsEnvironment
|
||||
a.Srv().PluginsLock.RUnlock()
|
||||
if pluginsEnvironment != nil || !*a.Config().PluginSettings.Enable {
|
||||
a.SyncPluginsActiveState()
|
||||
s.PluginsLock.RLock()
|
||||
pluginsEnvironment := s.PluginsEnvironment
|
||||
s.PluginsLock.RUnlock()
|
||||
if pluginsEnvironment != nil || !*s.Config().PluginSettings.Enable {
|
||||
s.syncPluginsActiveState()
|
||||
return
|
||||
}
|
||||
|
||||
a.Log().Info("Starting up plugins")
|
||||
s.Log.Info("Starting up plugins")
|
||||
|
||||
if err := os.Mkdir(pluginDir, 0744); err != nil && !os.IsExist(err) {
|
||||
mlog.Error("Failed to start up plugins", mlog.Err(err))
|
||||
@@ -186,57 +195,69 @@ func (a *App) InitPlugins(pluginDir, webappPluginDir string) {
|
||||
return
|
||||
}
|
||||
|
||||
env, err := plugin.NewEnvironment(a.NewPluginAPI, pluginDir, webappPluginDir, a.Log(), a.Metrics())
|
||||
newApiFunc := func(manifest *model.Manifest) plugin.API {
|
||||
return New(ServerConnector(s)).NewPluginAPI(c, manifest)
|
||||
}
|
||||
|
||||
env, err := plugin.NewEnvironment(newApiFunc, pluginDir, webappPluginDir, s.Log, s.Metrics)
|
||||
if err != nil {
|
||||
mlog.Error("Failed to start up plugins", mlog.Err(err))
|
||||
return
|
||||
}
|
||||
a.SetPluginsEnvironment(env)
|
||||
s.PluginsLock.Lock()
|
||||
s.PluginsEnvironment = env
|
||||
s.PluginsLock.Unlock()
|
||||
|
||||
if err := a.SyncPlugins(); err != nil {
|
||||
if err := s.syncPlugins(); err != nil {
|
||||
mlog.Error("Failed to sync plugins from the file store", mlog.Err(err))
|
||||
}
|
||||
|
||||
plugins := a.processPrepackagedPlugins(prepackagedPluginsDir)
|
||||
pluginsEnvironment = a.GetPluginsEnvironment()
|
||||
plugins := s.processPrepackagedPlugins(prepackagedPluginsDir)
|
||||
pluginsEnvironment = s.GetPluginsEnvironment()
|
||||
if pluginsEnvironment == nil {
|
||||
mlog.Info("Plugins environment not found, server is likely shutting down")
|
||||
return
|
||||
}
|
||||
pluginsEnvironment.SetPrepackagedPlugins(plugins)
|
||||
|
||||
a.installFeatureFlagPlugins()
|
||||
s.installFeatureFlagPlugins()
|
||||
|
||||
// Sync plugin active state when config changes. Also notify plugins.
|
||||
a.Srv().PluginsLock.Lock()
|
||||
a.RemoveConfigListener(a.Srv().PluginConfigListenerId)
|
||||
a.Srv().PluginConfigListenerId = a.AddConfigListener(func(old, new *model.Config) {
|
||||
s.PluginsLock.Lock()
|
||||
s.RemoveConfigListener(s.PluginConfigListenerId)
|
||||
s.PluginConfigListenerId = s.AddConfigListener(func(old, new *model.Config) {
|
||||
// If plugin status remains unchanged, only then run this.
|
||||
// Because (*App).InitPlugins is already run as a config change hook.
|
||||
if *old.PluginSettings.Enable == *new.PluginSettings.Enable {
|
||||
a.installFeatureFlagPlugins()
|
||||
a.SyncPluginsActiveState()
|
||||
s.installFeatureFlagPlugins()
|
||||
s.syncPluginsActiveState()
|
||||
}
|
||||
if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil {
|
||||
if pluginsEnvironment := s.GetPluginsEnvironment(); pluginsEnvironment != nil {
|
||||
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
|
||||
if err := hooks.OnConfigurationChange(); err != nil {
|
||||
a.Log().Error("Plugin OnConfigurationChange hook failed", mlog.Err(err))
|
||||
s.Log.Error("Plugin OnConfigurationChange hook failed", mlog.Err(err))
|
||||
}
|
||||
return true
|
||||
}, plugin.OnConfigurationChangeID)
|
||||
}
|
||||
})
|
||||
a.Srv().PluginsLock.Unlock()
|
||||
s.PluginsLock.Unlock()
|
||||
|
||||
a.SyncPluginsActiveState()
|
||||
s.syncPluginsActiveState()
|
||||
}
|
||||
|
||||
// SyncPlugins synchronizes the plugins installed locally
|
||||
// with the plugin bundles available in the file store.
|
||||
func (a *App) SyncPlugins() *model.AppError {
|
||||
return a.Srv().syncPlugins()
|
||||
}
|
||||
|
||||
// SyncPlugins synchronizes the plugins installed locally
|
||||
// with the plugin bundles available in the file store.
|
||||
func (s *Server) syncPlugins() *model.AppError {
|
||||
mlog.Info("Syncing plugins from the file store")
|
||||
|
||||
pluginsEnvironment := a.GetPluginsEnvironment()
|
||||
pluginsEnvironment := s.GetPluginsEnvironment()
|
||||
if pluginsEnvironment == nil {
|
||||
return model.NewAppError("SyncPlugins", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented)
|
||||
}
|
||||
@@ -252,14 +273,14 @@ func (a *App) SyncPlugins() *model.AppError {
|
||||
go func(pluginID string) {
|
||||
defer wg.Done()
|
||||
// Only handle managed plugins with .filestore flag file.
|
||||
_, err := os.Stat(filepath.Join(*a.Config().PluginSettings.Directory, pluginID, managedPluginFileName))
|
||||
_, err := os.Stat(filepath.Join(*s.Config().PluginSettings.Directory, pluginID, managedPluginFileName))
|
||||
if os.IsNotExist(err) {
|
||||
mlog.Warn("Skipping sync for unmanaged plugin", mlog.String("plugin_id", pluginID))
|
||||
} else if err != nil {
|
||||
mlog.Error("Skipping sync for plugin after failure to check if managed", mlog.String("plugin_id", pluginID), mlog.Err(err))
|
||||
} else {
|
||||
mlog.Debug("Removing local installation of managed plugin before sync", mlog.String("plugin_id", pluginID))
|
||||
if err := a.removePluginLocally(pluginID); err != nil {
|
||||
if err := s.removePluginLocally(pluginID); err != nil {
|
||||
mlog.Error("Failed to remove local installation of managed plugin before sync", mlog.String("plugin_id", pluginID), mlog.Err(err))
|
||||
}
|
||||
}
|
||||
@@ -268,7 +289,7 @@ func (a *App) SyncPlugins() *model.AppError {
|
||||
wg.Wait()
|
||||
|
||||
// Install plugins from the file store.
|
||||
pluginSignaturePathMap, appErr := a.getPluginsFromFolder()
|
||||
pluginSignaturePathMap, appErr := s.getPluginsFromFolder()
|
||||
if appErr != nil {
|
||||
return appErr
|
||||
}
|
||||
@@ -277,7 +298,7 @@ func (a *App) SyncPlugins() *model.AppError {
|
||||
wg.Add(1)
|
||||
go func(plugin *pluginSignaturePath) {
|
||||
defer wg.Done()
|
||||
reader, appErr := a.FileReader(plugin.path)
|
||||
reader, appErr := s.fileReader(plugin.path)
|
||||
if appErr != nil {
|
||||
mlog.Error("Failed to open plugin bundle from file store.", mlog.String("bundle", plugin.path), mlog.Err(appErr))
|
||||
return
|
||||
@@ -285,8 +306,8 @@ func (a *App) SyncPlugins() *model.AppError {
|
||||
defer reader.Close()
|
||||
|
||||
var signature filestore.ReadCloseSeeker
|
||||
if *a.Config().PluginSettings.RequirePluginSignature {
|
||||
signature, appErr = a.FileReader(plugin.signaturePath)
|
||||
if *s.Config().PluginSettings.RequirePluginSignature {
|
||||
signature, appErr = s.fileReader(plugin.signaturePath)
|
||||
if appErr != nil {
|
||||
mlog.Error("Failed to open plugin signature from file store.", mlog.Err(appErr))
|
||||
return
|
||||
@@ -295,7 +316,7 @@ func (a *App) SyncPlugins() *model.AppError {
|
||||
}
|
||||
|
||||
mlog.Info("Syncing plugin from file store", mlog.String("bundle", plugin.path))
|
||||
if _, err := a.installPluginLocally(reader, signature, installPluginLocallyAlways); err != nil {
|
||||
if _, err := s.installPluginLocally(reader, signature, installPluginLocallyAlways); err != nil {
|
||||
mlog.Error("Failed to sync plugin from file store", mlog.String("bundle", plugin.path), mlog.Err(err))
|
||||
}
|
||||
}(plugin)
|
||||
@@ -348,7 +369,11 @@ func (a *App) GetActivePluginManifests() ([]*model.Manifest, *model.AppError) {
|
||||
// activation if inactive anywhere in the cluster.
|
||||
// Notifies cluster peers through config change.
|
||||
func (a *App) EnablePlugin(id string) *model.AppError {
|
||||
pluginsEnvironment := a.GetPluginsEnvironment()
|
||||
return a.Srv().enablePlugin(id)
|
||||
}
|
||||
|
||||
func (s *Server) enablePlugin(id string) *model.AppError {
|
||||
pluginsEnvironment := s.GetPluginsEnvironment()
|
||||
if pluginsEnvironment == nil {
|
||||
return model.NewAppError("EnablePlugin", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented)
|
||||
}
|
||||
@@ -372,12 +397,12 @@ func (a *App) EnablePlugin(id string) *model.AppError {
|
||||
return model.NewAppError("EnablePlugin", "app.plugin.not_installed.app_error", nil, "", http.StatusNotFound)
|
||||
}
|
||||
|
||||
a.UpdateConfig(func(cfg *model.Config) {
|
||||
s.UpdateConfig(func(cfg *model.Config) {
|
||||
cfg.PluginSettings.PluginStates[id] = &model.PluginState{Enable: true}
|
||||
})
|
||||
|
||||
// This call will implicitly invoke SyncPluginsActiveState which will activate enabled plugins.
|
||||
if err := a.SaveConfig(a.Config(), true); err != nil {
|
||||
if err := s.SaveConfig(s.Config(), true); err != nil {
|
||||
if err.Id == "ent.cluster.save_config.error" {
|
||||
return model.NewAppError("EnablePlugin", "app.plugin.cluster.save_config.app_error", nil, "", http.StatusInternalServerError)
|
||||
}
|
||||
@@ -390,7 +415,11 @@ func (a *App) EnablePlugin(id string) *model.AppError {
|
||||
// DisablePlugin will set the config for an installed plugin to disabled, triggering deactivation if active.
|
||||
// Notifies cluster peers through config change.
|
||||
func (a *App) DisablePlugin(id string) *model.AppError {
|
||||
pluginsEnvironment := a.GetPluginsEnvironment()
|
||||
return a.Srv().disablePlugin(id)
|
||||
}
|
||||
|
||||
func (s *Server) disablePlugin(id string) *model.AppError {
|
||||
pluginsEnvironment := s.GetPluginsEnvironment()
|
||||
if pluginsEnvironment == nil {
|
||||
return model.NewAppError("DisablePlugin", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented)
|
||||
}
|
||||
@@ -414,13 +443,13 @@ func (a *App) DisablePlugin(id string) *model.AppError {
|
||||
return model.NewAppError("DisablePlugin", "app.plugin.not_installed.app_error", nil, "", http.StatusNotFound)
|
||||
}
|
||||
|
||||
a.UpdateConfig(func(cfg *model.Config) {
|
||||
s.UpdateConfig(func(cfg *model.Config) {
|
||||
cfg.PluginSettings.PluginStates[id] = &model.PluginState{Enable: false}
|
||||
})
|
||||
a.UnregisterPluginCommands(id)
|
||||
s.unregisterPluginCommands(id)
|
||||
|
||||
// This call will implicitly invoke SyncPluginsActiveState which will deactivate disabled plugins.
|
||||
if err := a.SaveConfig(a.Config(), true); err != nil {
|
||||
if err := s.SaveConfig(s.Config(), true); err != nil {
|
||||
return model.NewAppError("DisablePlugin", "app.plugin.config.app_error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
@@ -505,8 +534,8 @@ func (a *App) GetMarketplacePlugins(filter *model.MarketplacePluginFilter) ([]*m
|
||||
}
|
||||
|
||||
// getPrepackagedPlugin returns a pre-packaged plugin.
|
||||
func (a *App) getPrepackagedPlugin(pluginID, version string) (*plugin.PrepackagedPlugin, *model.AppError) {
|
||||
pluginsEnvironment := a.GetPluginsEnvironment()
|
||||
func (s *Server) getPrepackagedPlugin(pluginID, version string) (*plugin.PrepackagedPlugin, *model.AppError) {
|
||||
pluginsEnvironment := s.GetPluginsEnvironment()
|
||||
if pluginsEnvironment == nil {
|
||||
return nil, model.NewAppError("getPrepackagedPlugin", "app.plugin.config.app_error", nil, "plugin environment is nil", http.StatusInternalServerError)
|
||||
}
|
||||
@@ -522,16 +551,16 @@ func (a *App) getPrepackagedPlugin(pluginID, version string) (*plugin.Prepackage
|
||||
}
|
||||
|
||||
// getRemoteMarketplacePlugin returns plugin from marketplace-server.
|
||||
func (a *App) getRemoteMarketplacePlugin(pluginID, version string) (*model.BaseMarketplacePlugin, *model.AppError) {
|
||||
func (s *Server) getRemoteMarketplacePlugin(pluginID, version string) (*model.BaseMarketplacePlugin, *model.AppError) {
|
||||
marketplaceClient, err := marketplace.NewClient(
|
||||
*a.Config().PluginSettings.MarketplaceUrl,
|
||||
a.HTTPService(),
|
||||
*s.Config().PluginSettings.MarketplaceUrl,
|
||||
s.HTTPService,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, model.NewAppError("GetMarketplacePlugin", "app.plugin.marketplace_client.app_error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
filter := a.getBaseMarketplaceFilter()
|
||||
filter := s.getBaseMarketplaceFilter()
|
||||
filter.PluginId = pluginID
|
||||
filter.ReturnAllVersions = true
|
||||
|
||||
@@ -682,11 +711,15 @@ func (a *App) mergeLocalPlugins(remoteMarketplacePlugins map[string]*model.Marke
|
||||
}
|
||||
|
||||
func (a *App) getBaseMarketplaceFilter() *model.MarketplacePluginFilter {
|
||||
return a.Srv().getBaseMarketplaceFilter()
|
||||
}
|
||||
|
||||
func (s *Server) getBaseMarketplaceFilter() *model.MarketplacePluginFilter {
|
||||
filter := &model.MarketplacePluginFilter{
|
||||
ServerVersion: model.CurrentVersion,
|
||||
}
|
||||
|
||||
license := a.Srv().License()
|
||||
license := s.License()
|
||||
if license != nil && *license.Features.EnterprisePlugins {
|
||||
filter.EnterprisePlugins = true
|
||||
}
|
||||
@@ -733,8 +766,8 @@ func pluginMatchesFilter(manifest *model.Manifest, filter string) bool {
|
||||
// it will notify all connected websocket clients (across all peers) to trigger the (re-)installation.
|
||||
// There is a small chance that this never occurs, because the last server to finish installing dies before it can announce.
|
||||
// There is also a chance that multiple servers notify, but the webapp handles this idempotently.
|
||||
func (a *App) notifyPluginEnabled(manifest *model.Manifest) error {
|
||||
pluginsEnvironment := a.GetPluginsEnvironment()
|
||||
func (s *Server) notifyPluginEnabled(manifest *model.Manifest) error {
|
||||
pluginsEnvironment := s.GetPluginsEnvironment()
|
||||
if pluginsEnvironment == nil {
|
||||
return errors.New("pluginsEnvironment is nil")
|
||||
}
|
||||
@@ -744,15 +777,15 @@ func (a *App) notifyPluginEnabled(manifest *model.Manifest) error {
|
||||
|
||||
var statuses model.PluginStatuses
|
||||
|
||||
if a.Cluster() != nil {
|
||||
if s.Cluster != nil {
|
||||
var err *model.AppError
|
||||
statuses, err = a.Cluster().GetPluginStatuses()
|
||||
statuses, err = s.Cluster.GetPluginStatuses()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
localStatus, err := a.GetPluginStatus(manifest.Id)
|
||||
localStatus, err := s.GetPluginStatus(manifest.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -772,26 +805,26 @@ func (a *App) notifyPluginEnabled(manifest *model.Manifest) error {
|
||||
// Notify all cluster peer clients.
|
||||
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PLUGIN_ENABLED, "", "", "", nil)
|
||||
message.Add("manifest", manifest.ClientManifest())
|
||||
a.Publish(message)
|
||||
s.Publish(message)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) getPluginsFromFolder() (map[string]*pluginSignaturePath, *model.AppError) {
|
||||
fileStorePaths, appErr := a.ListDirectory(fileStorePluginFolder)
|
||||
func (s *Server) getPluginsFromFolder() (map[string]*pluginSignaturePath, *model.AppError) {
|
||||
fileStorePaths, appErr := s.listDirectory(fileStorePluginFolder)
|
||||
if appErr != nil {
|
||||
return nil, model.NewAppError("getPluginsFromDir", "app.plugin.sync.list_filestore.app_error", nil, appErr.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return a.getPluginsFromFilePaths(fileStorePaths), nil
|
||||
return s.getPluginsFromFilePaths(fileStorePaths), nil
|
||||
}
|
||||
|
||||
func (a *App) getPluginsFromFilePaths(fileStorePaths []string) map[string]*pluginSignaturePath {
|
||||
func (s *Server) getPluginsFromFilePaths(fileStorePaths []string) map[string]*pluginSignaturePath {
|
||||
pluginSignaturePathMap := make(map[string]*pluginSignaturePath)
|
||||
|
||||
fsPrefix := ""
|
||||
if *a.Config().FileSettings.DriverName == model.IMAGE_DRIVER_S3 {
|
||||
ptr := a.Config().FileSettings.AmazonS3PathPrefix
|
||||
if *s.Config().FileSettings.DriverName == model.IMAGE_DRIVER_S3 {
|
||||
ptr := s.Config().FileSettings.AmazonS3PathPrefix
|
||||
if ptr != nil && *ptr != "" {
|
||||
fsPrefix = *ptr + "/"
|
||||
}
|
||||
@@ -824,7 +857,7 @@ func (a *App) getPluginsFromFilePaths(fileStorePaths []string) map[string]*plugi
|
||||
return pluginSignaturePathMap
|
||||
}
|
||||
|
||||
func (a *App) processPrepackagedPlugins(pluginsDir string) []*plugin.PrepackagedPlugin {
|
||||
func (s *Server) processPrepackagedPlugins(pluginsDir string) []*plugin.PrepackagedPlugin {
|
||||
prepackagedPluginsDir, found := fileutils.FindDir(pluginsDir)
|
||||
if !found {
|
||||
return nil
|
||||
@@ -840,7 +873,7 @@ func (a *App) processPrepackagedPlugins(pluginsDir string) []*plugin.Prepackaged
|
||||
return nil
|
||||
}
|
||||
|
||||
pluginSignaturePathMap := a.getPluginsFromFilePaths(fileStorePaths)
|
||||
pluginSignaturePathMap := s.getPluginsFromFilePaths(fileStorePaths)
|
||||
plugins := make([]*plugin.PrepackagedPlugin, 0, len(pluginSignaturePathMap))
|
||||
prepackagedPlugins := make(chan *plugin.PrepackagedPlugin, len(pluginSignaturePathMap))
|
||||
|
||||
@@ -849,7 +882,7 @@ func (a *App) processPrepackagedPlugins(pluginsDir string) []*plugin.Prepackaged
|
||||
wg.Add(1)
|
||||
go func(psPath *pluginSignaturePath) {
|
||||
defer wg.Done()
|
||||
p, err := a.processPrepackagedPlugin(psPath)
|
||||
p, err := s.processPrepackagedPlugin(psPath)
|
||||
if err != nil {
|
||||
mlog.Error("Failed to install prepackaged plugin", mlog.String("path", psPath.path), mlog.Err(err))
|
||||
return
|
||||
@@ -870,7 +903,7 @@ func (a *App) processPrepackagedPlugins(pluginsDir string) []*plugin.Prepackaged
|
||||
|
||||
// processPrepackagedPlugin will return the prepackaged plugin metadata and will also
|
||||
// install the prepackaged plugin if it had been previously enabled and AutomaticPrepackagedPlugins is true.
|
||||
func (a *App) processPrepackagedPlugin(pluginPath *pluginSignaturePath) (*plugin.PrepackagedPlugin, error) {
|
||||
func (s *Server) processPrepackagedPlugin(pluginPath *pluginSignaturePath) (*plugin.PrepackagedPlugin, error) {
|
||||
mlog.Debug("Processing prepackaged plugin", mlog.String("path", pluginPath.path))
|
||||
|
||||
fileReader, err := os.Open(pluginPath.path)
|
||||
@@ -891,18 +924,18 @@ func (a *App) processPrepackagedPlugin(pluginPath *pluginSignaturePath) (*plugin
|
||||
}
|
||||
|
||||
// Skip installing the plugin at all if automatic prepackaged plugins is disabled
|
||||
if !*a.Config().PluginSettings.AutomaticPrepackagedPlugins {
|
||||
if !*s.Config().PluginSettings.AutomaticPrepackagedPlugins {
|
||||
return plugin, nil
|
||||
}
|
||||
|
||||
// Skip installing if the plugin is has not been previously enabled.
|
||||
pluginState := a.Config().PluginSettings.PluginStates[plugin.Manifest.Id]
|
||||
pluginState := s.Config().PluginSettings.PluginStates[plugin.Manifest.Id]
|
||||
if pluginState == nil || !pluginState.Enable {
|
||||
return plugin, nil
|
||||
}
|
||||
|
||||
mlog.Debug("Installing prepackaged plugin", mlog.String("path", pluginPath.path))
|
||||
if _, err := a.installExtractedPlugin(plugin.Manifest, pluginDir, installPluginLocallyOnlyIfNewOrUpgrade); err != nil {
|
||||
if _, err := s.installExtractedPlugin(plugin.Manifest, pluginDir, installPluginLocallyOnlyIfNewOrUpgrade); err != nil {
|
||||
return nil, errors.Wrapf(err, "Failed to install extracted prepackaged plugin %s", pluginPath.path)
|
||||
}
|
||||
|
||||
@@ -910,24 +943,24 @@ func (a *App) processPrepackagedPlugin(pluginPath *pluginSignaturePath) (*plugin
|
||||
}
|
||||
|
||||
// installFeatureFlagPlugins handles the automatic installation/upgrade of plugins from feature flags
|
||||
func (a *App) installFeatureFlagPlugins() {
|
||||
ffControledPlugins := a.Config().FeatureFlags.Plugins()
|
||||
func (s *Server) installFeatureFlagPlugins() {
|
||||
ffControledPlugins := s.Config().FeatureFlags.Plugins()
|
||||
|
||||
// Respect the automatic prepackaged disable setting
|
||||
if !*a.Config().PluginSettings.AutomaticPrepackagedPlugins {
|
||||
if !*s.Config().PluginSettings.AutomaticPrepackagedPlugins {
|
||||
return
|
||||
}
|
||||
|
||||
for pluginID, version := range ffControledPlugins {
|
||||
// Skip installing if the plugin has been previously disabled.
|
||||
pluginState := a.Config().PluginSettings.PluginStates[pluginID]
|
||||
pluginState := s.Config().PluginSettings.PluginStates[pluginID]
|
||||
if pluginState != nil && !pluginState.Enable {
|
||||
a.Log().Debug("Not auto installing/upgrade because plugin was disabled", mlog.String("plugin_id", pluginID), mlog.String("version", version))
|
||||
s.Log.Debug("Not auto installing/upgrade because plugin was disabled", mlog.String("plugin_id", pluginID), mlog.String("version", version))
|
||||
continue
|
||||
}
|
||||
|
||||
// Check if we already installed this version as InstallMarketplacePlugin can't handle re-installs well.
|
||||
pluginStatus, err := a.Srv().GetPluginStatus(pluginID)
|
||||
pluginStatus, err := s.GetPluginStatus(pluginID)
|
||||
pluginExists := err == nil
|
||||
if pluginExists && pluginStatus.Version == version {
|
||||
continue
|
||||
@@ -935,37 +968,37 @@ func (a *App) installFeatureFlagPlugins() {
|
||||
|
||||
if version != "" && version != "control" {
|
||||
// If we are on-prem skip installation if this is a downgrade
|
||||
license := a.Srv().License()
|
||||
license := s.License()
|
||||
inCloud := license != nil && *license.Features.Cloud
|
||||
if !inCloud && pluginExists {
|
||||
parsedVersion, err := semver.Parse(version)
|
||||
if err != nil {
|
||||
a.Log().Debug("Bad version from feature flag", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version))
|
||||
s.Log.Debug("Bad version from feature flag", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version))
|
||||
return
|
||||
}
|
||||
parsedExistingVersion, err := semver.Parse(pluginStatus.Version)
|
||||
if err != nil {
|
||||
a.Log().Debug("Bad version from plugin manifest", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", pluginStatus.Version))
|
||||
s.Log.Debug("Bad version from plugin manifest", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", pluginStatus.Version))
|
||||
return
|
||||
}
|
||||
|
||||
if parsedVersion.LTE(parsedExistingVersion) {
|
||||
a.Log().Debug("Skip installation because given version was a downgrade and on-prem installations should not downgrade.", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", pluginStatus.Version))
|
||||
s.Log.Debug("Skip installation because given version was a downgrade and on-prem installations should not downgrade.", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", pluginStatus.Version))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
_, err := a.InstallMarketplacePlugin(&model.InstallMarketplacePluginRequest{
|
||||
_, err := s.installMarketplacePlugin(&model.InstallMarketplacePluginRequest{
|
||||
Id: pluginID,
|
||||
Version: version,
|
||||
})
|
||||
if err != nil {
|
||||
a.Log().Debug("Unable to install plugin from FF manifest", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version))
|
||||
s.Log.Debug("Unable to install plugin from FF manifest", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version))
|
||||
} else {
|
||||
if err := a.EnablePlugin(pluginID); err != nil {
|
||||
a.Log().Debug("Unable to enable plugin installed from feature flag.", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version))
|
||||
if err := s.enablePlugin(pluginID); err != nil {
|
||||
s.Log.Debug("Unable to enable plugin installed from feature flag.", mlog.String("plugin_id", pluginID), mlog.Err(err), mlog.String("version", version))
|
||||
} else {
|
||||
a.Log().Debug("Installed and enabled plugin.", mlog.String("plugin_id", pluginID), mlog.String("version", version))
|
||||
s.Log.Debug("Installed and enabled plugin.", mlog.String("plugin_id", pluginID), mlog.String("version", version))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
@@ -23,14 +24,16 @@ import (
|
||||
type PluginAPI struct {
|
||||
id string
|
||||
app *App
|
||||
ctx *request.Context
|
||||
logger *mlog.SugarLogger
|
||||
manifest *model.Manifest
|
||||
}
|
||||
|
||||
func NewPluginAPI(a *App, manifest *model.Manifest) *PluginAPI {
|
||||
func NewPluginAPI(a *App, c *request.Context, manifest *model.Manifest) *PluginAPI {
|
||||
return &PluginAPI{
|
||||
id: manifest.Id,
|
||||
manifest: manifest,
|
||||
ctx: c,
|
||||
app: a,
|
||||
logger: a.Log().With(mlog.String("plugin_id", manifest.Id)).Sugar(),
|
||||
}
|
||||
@@ -79,7 +82,7 @@ func (api *PluginAPI) ExecuteSlashCommand(commandArgs *model.CommandArgs) (*mode
|
||||
}
|
||||
commandArgs.T = i18n.GetUserTranslations(user.Locale)
|
||||
commandArgs.SiteURL = api.app.GetSiteURL()
|
||||
response, appErr := api.app.ExecuteCommand(commandArgs)
|
||||
response, appErr := api.app.ExecuteCommand(api.ctx, commandArgs)
|
||||
if appErr != nil {
|
||||
return response, appErr
|
||||
}
|
||||
@@ -153,7 +156,7 @@ func (api *PluginAPI) GetTelemetryId() string {
|
||||
}
|
||||
|
||||
func (api *PluginAPI) CreateTeam(team *model.Team) (*model.Team, *model.AppError) {
|
||||
return api.app.CreateTeam(team)
|
||||
return api.app.CreateTeam(api.ctx, team)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) DeleteTeam(teamID string) *model.AppError {
|
||||
@@ -190,11 +193,11 @@ func (api *PluginAPI) GetTeamsForUser(userID string) ([]*model.Team, *model.AppE
|
||||
}
|
||||
|
||||
func (api *PluginAPI) CreateTeamMember(teamID, userID string) (*model.TeamMember, *model.AppError) {
|
||||
return api.app.AddTeamMember(teamID, userID)
|
||||
return api.app.AddTeamMember(api.ctx, teamID, userID)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) CreateTeamMembers(teamID string, userIDs []string, requestorId string) ([]*model.TeamMember, *model.AppError) {
|
||||
members, err := api.app.AddTeamMembers(teamID, userIDs, requestorId, false)
|
||||
members, err := api.app.AddTeamMembers(api.ctx, teamID, userIDs, requestorId, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -202,11 +205,11 @@ func (api *PluginAPI) CreateTeamMembers(teamID string, userIDs []string, request
|
||||
}
|
||||
|
||||
func (api *PluginAPI) CreateTeamMembersGracefully(teamID string, userIDs []string, requestorId string) ([]*model.TeamMemberWithError, *model.AppError) {
|
||||
return api.app.AddTeamMembers(teamID, userIDs, requestorId, true)
|
||||
return api.app.AddTeamMembers(api.ctx, teamID, userIDs, requestorId, true)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) DeleteTeamMember(teamID, userID, requestorId string) *model.AppError {
|
||||
return api.app.RemoveUserFromTeam(teamID, userID, requestorId)
|
||||
return api.app.RemoveUserFromTeam(api.ctx, teamID, userID, requestorId)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) GetTeamMembers(teamID string, page, perPage int) ([]*model.TeamMember, *model.AppError) {
|
||||
@@ -230,7 +233,7 @@ func (api *PluginAPI) GetTeamStats(teamID string) (*model.TeamStats, *model.AppE
|
||||
}
|
||||
|
||||
func (api *PluginAPI) CreateUser(user *model.User) (*model.User, *model.AppError) {
|
||||
return api.app.CreateUser(user)
|
||||
return api.app.CreateUser(api.ctx, user)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) DeleteUser(userID string) *model.AppError {
|
||||
@@ -238,7 +241,7 @@ func (api *PluginAPI) DeleteUser(userID string) *model.AppError {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = api.app.UpdateActive(user, false)
|
||||
_, err = api.app.UpdateActive(api.ctx, user, false)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -284,7 +287,7 @@ func (api *PluginAPI) UpdateUser(user *model.User) (*model.User, *model.AppError
|
||||
}
|
||||
|
||||
func (api *PluginAPI) UpdateUserActive(userID string, active bool) *model.AppError {
|
||||
return api.app.UpdateUserActive(userID, active)
|
||||
return api.app.UpdateUserActive(api.ctx, userID, active)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) GetUserStatus(userID string) (*model.Status, *model.AppError) {
|
||||
@@ -363,7 +366,7 @@ func (api *PluginAPI) GetLDAPUserAttributes(userID string, attributes []string)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) CreateChannel(channel *model.Channel) (*model.Channel, *model.AppError) {
|
||||
return api.app.CreateChannel(channel, false)
|
||||
return api.app.CreateChannel(api.ctx, channel, false)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) DeleteChannel(channelID string) *model.AppError {
|
||||
@@ -371,7 +374,7 @@ func (api *PluginAPI) DeleteChannel(channelID string) *model.AppError {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return api.app.DeleteChannel(channel, "")
|
||||
return api.app.DeleteChannel(api.ctx, channel, "")
|
||||
}
|
||||
|
||||
func (api *PluginAPI) GetPublicChannelsForTeam(teamID string, page, perPage int) ([]*model.Channel, *model.AppError) {
|
||||
@@ -415,7 +418,7 @@ func (api *PluginAPI) GetChannelStats(channelID string) (*model.ChannelStats, *m
|
||||
}
|
||||
|
||||
func (api *PluginAPI) GetDirectChannel(userID1, userID2 string) (*model.Channel, *model.AppError) {
|
||||
return api.app.GetOrCreateDirectChannel(userID1, userID2)
|
||||
return api.app.GetOrCreateDirectChannel(api.ctx, userID1, userID2)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) GetGroupChannel(userIDs []string) (*model.Channel, *model.AppError) {
|
||||
@@ -482,7 +485,7 @@ func (api *PluginAPI) SearchPostsInTeamForUser(teamID string, userID string, sea
|
||||
includeDeletedChannels = *searchParams.IncludeDeletedChannels
|
||||
}
|
||||
|
||||
return api.app.SearchPostsInTeamForUser(terms, userID, teamID, isOrSearch, includeDeletedChannels, timeZoneOffset, page, perPage)
|
||||
return api.app.SearchPostsInTeamForUser(api.ctx, terms, userID, teamID, isOrSearch, includeDeletedChannels, timeZoneOffset, page, perPage)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) AddChannelMember(channelID, userID string) (*model.ChannelMember, *model.AppError) {
|
||||
@@ -491,7 +494,7 @@ func (api *PluginAPI) AddChannelMember(channelID, userID string) (*model.Channel
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return api.app.AddChannelMember(userID, channel, ChannelMemberOpts{
|
||||
return api.app.AddChannelMember(api.ctx, userID, channel, ChannelMemberOpts{
|
||||
// For now, don't allow overriding these via the plugin API.
|
||||
UserRequestorID: "",
|
||||
PostRootID: "",
|
||||
@@ -504,7 +507,7 @@ func (api *PluginAPI) AddUserToChannel(channelID, userID, asUserID string) (*mod
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return api.app.AddChannelMember(userID, channel, ChannelMemberOpts{
|
||||
return api.app.AddChannelMember(api.ctx, userID, channel, ChannelMemberOpts{
|
||||
UserRequestorID: asUserID,
|
||||
})
|
||||
}
|
||||
@@ -534,7 +537,7 @@ func (api *PluginAPI) UpdateChannelMemberNotifications(channelID, userID string,
|
||||
}
|
||||
|
||||
func (api *PluginAPI) DeleteChannelMember(channelID, userID string) *model.AppError {
|
||||
return api.app.LeaveChannel(channelID, userID)
|
||||
return api.app.LeaveChannel(api.ctx, channelID, userID)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) GetGroup(groupId string) (*model.Group, *model.AppError) {
|
||||
@@ -560,15 +563,15 @@ func (api *PluginAPI) GetGroupsForUser(userID string) ([]*model.Group, *model.Ap
|
||||
}
|
||||
|
||||
func (api *PluginAPI) CreatePost(post *model.Post) (*model.Post, *model.AppError) {
|
||||
return api.app.CreatePostMissingChannel(post, true)
|
||||
return api.app.CreatePostMissingChannel(api.ctx, post, true)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) AddReaction(reaction *model.Reaction) (*model.Reaction, *model.AppError) {
|
||||
return api.app.SaveReactionForPost(reaction)
|
||||
return api.app.SaveReactionForPost(api.ctx, reaction)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) RemoveReaction(reaction *model.Reaction) *model.AppError {
|
||||
return api.app.DeleteReactionForPost(reaction)
|
||||
return api.app.DeleteReactionForPost(api.ctx, reaction)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) GetReactions(postID string) ([]*model.Reaction, *model.AppError) {
|
||||
@@ -617,7 +620,7 @@ func (api *PluginAPI) GetPostsForChannel(channelID string, page, perPage int) (*
|
||||
}
|
||||
|
||||
func (api *PluginAPI) UpdatePost(post *model.Post) (*model.Post, *model.AppError) {
|
||||
return api.app.UpdatePost(post, false)
|
||||
return api.app.UpdatePost(api.ctx, post, false)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) GetProfileImage(userID string) ([]byte, *model.AppError) {
|
||||
@@ -689,7 +692,7 @@ func (api *PluginAPI) GetFile(fileID string) ([]byte, *model.AppError) {
|
||||
}
|
||||
|
||||
func (api *PluginAPI) UploadFile(data []byte, channelID string, filename string) (*model.FileInfo, *model.AppError) {
|
||||
return api.app.UploadFile(data, channelID, filename)
|
||||
return api.app.UploadFile(api.ctx, data, channelID, filename)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) GetEmojiImage(emojiId string) ([]byte, string, *model.AppError) {
|
||||
@@ -885,7 +888,7 @@ func (api *PluginAPI) CreateBot(bot *model.Bot) (*model.Bot, *model.AppError) {
|
||||
}
|
||||
}
|
||||
|
||||
return api.app.CreateBot(bot)
|
||||
return api.app.CreateBot(api.ctx, bot)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) PatchBot(userID string, botPatch *model.BotPatch) (*model.Bot, *model.AppError) {
|
||||
@@ -903,7 +906,7 @@ func (api *PluginAPI) GetBots(options *model.BotGetOptions) ([]*model.Bot, *mode
|
||||
}
|
||||
|
||||
func (api *PluginAPI) UpdateBotActive(userID string, active bool) (*model.Bot, *model.AppError) {
|
||||
return api.app.UpdateBotActive(userID, active)
|
||||
return api.app.UpdateBotActive(api.ctx, userID, active)
|
||||
}
|
||||
|
||||
func (api *PluginAPI) PermanentDeleteBot(userID string) *model.AppError {
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/einterfaces/mocks"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/plugin"
|
||||
@@ -68,7 +69,7 @@ func setDefaultPluginConfig(th *TestHelper, pluginID string) {
|
||||
})
|
||||
}
|
||||
|
||||
func setupMultiPluginApiTest(t *testing.T, pluginCodes []string, pluginManifests []string, pluginIDs []string, app *App) string {
|
||||
func setupMultiPluginApiTest(t *testing.T, pluginCodes []string, pluginManifests []string, pluginIDs []string, app *App, c *request.Context) string {
|
||||
pluginDir, err := ioutil.TempDir("", "")
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() {
|
||||
@@ -87,7 +88,11 @@ func setupMultiPluginApiTest(t *testing.T, pluginCodes []string, pluginManifests
|
||||
}
|
||||
})
|
||||
|
||||
env, err := plugin.NewEnvironment(app.NewPluginAPI, pluginDir, webappPluginDir, app.Log(), nil)
|
||||
newPluginAPI := func(manifest *model.Manifest) plugin.API {
|
||||
return app.NewPluginAPI(c, manifest)
|
||||
}
|
||||
|
||||
env, err := plugin.NewEnvironment(newPluginAPI, pluginDir, webappPluginDir, app.Log(), nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, len(pluginCodes), len(pluginIDs))
|
||||
@@ -115,8 +120,8 @@ func setupMultiPluginApiTest(t *testing.T, pluginCodes []string, pluginManifests
|
||||
return pluginDir
|
||||
}
|
||||
|
||||
func setupPluginApiTest(t *testing.T, pluginCode string, pluginManifest string, pluginID string, app *App) string {
|
||||
return setupMultiPluginApiTest(t, []string{pluginCode}, []string{pluginManifest}, []string{pluginID}, app)
|
||||
func setupPluginApiTest(t *testing.T, pluginCode string, pluginManifest string, pluginID string, app *App, c *request.Context) string {
|
||||
return setupMultiPluginApiTest(t, []string{pluginCode}, []string{pluginManifest}, []string{pluginID}, app, c)
|
||||
}
|
||||
|
||||
func TestPublicFilesPathConfiguration(t *testing.T) {
|
||||
@@ -141,7 +146,7 @@ func TestPublicFilesPathConfiguration(t *testing.T) {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`,
|
||||
`{"id": "com.mattermost.sample", "server": {"executable": "backend.exe"}, "settings_schema": {"settings": []}}`, pluginID, th.App)
|
||||
`{"id": "com.mattermost.sample", "server": {"executable": "backend.exe"}, "settings_schema": {"settings": []}}`, pluginID, th.App, th.Context)
|
||||
|
||||
publicFilesFolderInTest := filepath.Join(pluginDir, pluginID, "public")
|
||||
publicFilesPath, err := th.App.GetPluginsEnvironment().PublicFilesPath(pluginID)
|
||||
@@ -154,13 +159,13 @@ func TestPluginAPIGetUserPreferences(t *testing.T) {
|
||||
defer th.TearDown()
|
||||
api := th.SetupPluginAPI()
|
||||
|
||||
user1, err := th.App.CreateUser(&model.User{
|
||||
user1, err := th.App.CreateUser(th.Context, &model.User{
|
||||
Email: strings.ToLower(model.NewId()) + "success+test@example.com",
|
||||
Password: "password",
|
||||
Username: "user1" + model.NewId(),
|
||||
})
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteUser(user1)
|
||||
defer th.App.PermanentDeleteUser(th.Context, user1)
|
||||
|
||||
preferences, err := api.GetPreferencesForUser(user1.Id)
|
||||
require.Nil(t, err)
|
||||
@@ -177,13 +182,13 @@ func TestPluginAPIDeleteUserPreferences(t *testing.T) {
|
||||
defer th.TearDown()
|
||||
api := th.SetupPluginAPI()
|
||||
|
||||
user1, err := th.App.CreateUser(&model.User{
|
||||
user1, err := th.App.CreateUser(th.Context, &model.User{
|
||||
Email: strings.ToLower(model.NewId()) + "success+test@example.com",
|
||||
Password: "password",
|
||||
Username: "user1" + model.NewId(),
|
||||
})
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteUser(user1)
|
||||
defer th.App.PermanentDeleteUser(th.Context, user1)
|
||||
|
||||
preferences, err := api.GetPreferencesForUser(user1.Id)
|
||||
require.Nil(t, err)
|
||||
@@ -195,13 +200,13 @@ func TestPluginAPIDeleteUserPreferences(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, 0, len(preferences))
|
||||
|
||||
user2, err := th.App.CreateUser(&model.User{
|
||||
user2, err := th.App.CreateUser(th.Context, &model.User{
|
||||
Email: strings.ToLower(model.NewId()) + "success+test@example.com",
|
||||
Password: "password",
|
||||
Username: "user2" + model.NewId(),
|
||||
})
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteUser(user2)
|
||||
defer th.App.PermanentDeleteUser(th.Context, user2)
|
||||
|
||||
preference := model.Preference{
|
||||
Name: user2.Id,
|
||||
@@ -229,13 +234,13 @@ func TestPluginAPIUpdateUserPreferences(t *testing.T) {
|
||||
defer th.TearDown()
|
||||
api := th.SetupPluginAPI()
|
||||
|
||||
user1, err := th.App.CreateUser(&model.User{
|
||||
user1, err := th.App.CreateUser(th.Context, &model.User{
|
||||
Email: strings.ToLower(model.NewId()) + "success+test@example.com",
|
||||
Password: "password",
|
||||
Username: "user1" + model.NewId(),
|
||||
})
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteUser(user1)
|
||||
defer th.App.PermanentDeleteUser(th.Context, user1)
|
||||
|
||||
preferences, err := api.GetPreferencesForUser(user1.Id)
|
||||
require.Nil(t, err)
|
||||
@@ -278,37 +283,37 @@ func TestPluginAPIGetUsers(t *testing.T) {
|
||||
defer th.TearDown()
|
||||
api := th.SetupPluginAPI()
|
||||
|
||||
user1, err := th.App.CreateUser(&model.User{
|
||||
user1, err := th.App.CreateUser(th.Context, &model.User{
|
||||
Email: strings.ToLower(model.NewId()) + "success+test@example.com",
|
||||
Password: "password",
|
||||
Username: "user1" + model.NewId(),
|
||||
})
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteUser(user1)
|
||||
defer th.App.PermanentDeleteUser(th.Context, user1)
|
||||
|
||||
user2, err := th.App.CreateUser(&model.User{
|
||||
user2, err := th.App.CreateUser(th.Context, &model.User{
|
||||
Email: strings.ToLower(model.NewId()) + "success+test@example.com",
|
||||
Password: "password",
|
||||
Username: "user2" + model.NewId(),
|
||||
})
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteUser(user2)
|
||||
defer th.App.PermanentDeleteUser(th.Context, user2)
|
||||
|
||||
user3, err := th.App.CreateUser(&model.User{
|
||||
user3, err := th.App.CreateUser(th.Context, &model.User{
|
||||
Email: strings.ToLower(model.NewId()) + "success+test@example.com",
|
||||
Password: "password",
|
||||
Username: "user3" + model.NewId(),
|
||||
})
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteUser(user3)
|
||||
defer th.App.PermanentDeleteUser(th.Context, user3)
|
||||
|
||||
user4, err := th.App.CreateUser(&model.User{
|
||||
user4, err := th.App.CreateUser(th.Context, &model.User{
|
||||
Email: strings.ToLower(model.NewId()) + "success+test@example.com",
|
||||
Password: "password",
|
||||
Username: "user4" + model.NewId(),
|
||||
})
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteUser(user4)
|
||||
defer th.App.PermanentDeleteUser(th.Context, user4)
|
||||
|
||||
testCases := []struct {
|
||||
Description string
|
||||
@@ -368,37 +373,37 @@ func TestPluginAPIGetUsersInTeam(t *testing.T) {
|
||||
team1 := th.CreateTeam()
|
||||
team2 := th.CreateTeam()
|
||||
|
||||
user1, err := th.App.CreateUser(&model.User{
|
||||
user1, err := th.App.CreateUser(th.Context, &model.User{
|
||||
Email: strings.ToLower(model.NewId()) + "success+test@example.com",
|
||||
Password: "password",
|
||||
Username: "user1" + model.NewId(),
|
||||
})
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteUser(user1)
|
||||
defer th.App.PermanentDeleteUser(th.Context, user1)
|
||||
|
||||
user2, err := th.App.CreateUser(&model.User{
|
||||
user2, err := th.App.CreateUser(th.Context, &model.User{
|
||||
Email: strings.ToLower(model.NewId()) + "success+test@example.com",
|
||||
Password: "password",
|
||||
Username: "user2" + model.NewId(),
|
||||
})
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteUser(user2)
|
||||
defer th.App.PermanentDeleteUser(th.Context, user2)
|
||||
|
||||
user3, err := th.App.CreateUser(&model.User{
|
||||
user3, err := th.App.CreateUser(th.Context, &model.User{
|
||||
Email: strings.ToLower(model.NewId()) + "success+test@example.com",
|
||||
Password: "password",
|
||||
Username: "user3" + model.NewId(),
|
||||
})
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteUser(user3)
|
||||
defer th.App.PermanentDeleteUser(th.Context, user3)
|
||||
|
||||
user4, err := th.App.CreateUser(&model.User{
|
||||
user4, err := th.App.CreateUser(th.Context, &model.User{
|
||||
Email: strings.ToLower(model.NewId()) + "success+test@example.com",
|
||||
Password: "password",
|
||||
Username: "user4" + model.NewId(),
|
||||
})
|
||||
require.Nil(t, err)
|
||||
defer th.App.PermanentDeleteUser(user4)
|
||||
defer th.App.PermanentDeleteUser(th.Context, user4)
|
||||
|
||||
// Add all users to team 1
|
||||
_, _, err = th.App.joinUserToTeam(team1, user1)
|
||||
@@ -478,7 +483,7 @@ func TestPluginAPIGetFile(t *testing.T) {
|
||||
uploadTime := time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local)
|
||||
filename := "testGetFile"
|
||||
fileData := []byte("Hello World")
|
||||
info, err := th.App.DoUploadFile(uploadTime, th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, filename, fileData)
|
||||
info, err := th.App.DoUploadFile(th.Context, uploadTime, th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, filename, fileData)
|
||||
require.Nil(t, err)
|
||||
defer func() {
|
||||
th.App.Srv().Store.FileInfo().PermanentDelete(info.Id)
|
||||
@@ -500,7 +505,7 @@ func TestPluginAPIGetFileInfos(t *testing.T) {
|
||||
defer th.TearDown()
|
||||
api := th.SetupPluginAPI()
|
||||
|
||||
fileInfo1, err := th.App.DoUploadFile(
|
||||
fileInfo1, err := th.App.DoUploadFile(th.Context,
|
||||
time.Date(2020, 1, 1, 1, 1, 1, 1, time.UTC),
|
||||
th.BasicTeam.Id,
|
||||
th.BasicChannel.Id,
|
||||
@@ -514,7 +519,7 @@ func TestPluginAPIGetFileInfos(t *testing.T) {
|
||||
th.App.RemoveFile(fileInfo1.Path)
|
||||
}()
|
||||
|
||||
fileInfo2, err := th.App.DoUploadFile(
|
||||
fileInfo2, err := th.App.DoUploadFile(th.Context,
|
||||
time.Date(2020, 1, 2, 1, 1, 1, 1, time.UTC),
|
||||
th.BasicTeam.Id,
|
||||
th.BasicChannel.Id,
|
||||
@@ -528,7 +533,7 @@ func TestPluginAPIGetFileInfos(t *testing.T) {
|
||||
th.App.RemoveFile(fileInfo2.Path)
|
||||
}()
|
||||
|
||||
fileInfo3, err := th.App.DoUploadFile(
|
||||
fileInfo3, err := th.App.DoUploadFile(th.Context,
|
||||
time.Date(2020, 1, 3, 1, 1, 1, 1, time.UTC),
|
||||
th.BasicTeam.Id,
|
||||
th.BasicChannel.Id,
|
||||
@@ -598,7 +603,7 @@ func TestPluginAPISavePluginConfig(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
api := NewPluginAPI(th.App, manifest)
|
||||
api := NewPluginAPI(th.App, th.Context, manifest)
|
||||
|
||||
pluginConfigJsonString := `{"mystringsetting": "str", "MyIntSetting": 32, "myboolsetting": true}`
|
||||
|
||||
@@ -641,7 +646,7 @@ func TestPluginAPIGetPluginConfig(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
api := NewPluginAPI(th.App, manifest)
|
||||
api := NewPluginAPI(th.App, th.Context, manifest)
|
||||
|
||||
pluginConfigJsonString := `{"mystringsetting": "str", "myintsetting": 32, "myboolsetting": true}`
|
||||
var pluginConfig map[string]interface{}
|
||||
@@ -761,7 +766,7 @@ func TestPluginAPIGetPlugins(t *testing.T) {
|
||||
defer os.RemoveAll(pluginDir)
|
||||
defer os.RemoveAll(webappPluginDir)
|
||||
|
||||
env, err := plugin.NewEnvironment(th.App.NewPluginAPI, pluginDir, webappPluginDir, th.App.Log(), nil)
|
||||
env, err := plugin.NewEnvironment(th.NewPluginAPI, pluginDir, webappPluginDir, th.App.Log(), nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
pluginIDs := []string{"pluginid1", "pluginid2", "pluginid3"}
|
||||
@@ -834,7 +839,7 @@ func TestInstallPlugin(t *testing.T) {
|
||||
// we need a modified version of setupPluginApiTest() because it wasn't possible to use it directly here
|
||||
// since it removes plugin dirs right after it returns, does not update App configs with the plugin
|
||||
// dirs and this behavior tends to break this test as a result.
|
||||
setupTest := func(t *testing.T, pluginCode string, pluginManifest string, pluginID string, app *App) (func(), string) {
|
||||
setupTest := func(t *testing.T, pluginCode string, pluginManifest string, pluginID string, app *App, c *request.Context) (func(), string) {
|
||||
pluginDir, err := ioutil.TempDir("", "")
|
||||
require.NoError(t, err)
|
||||
webappPluginDir, err := ioutil.TempDir("", "")
|
||||
@@ -845,7 +850,11 @@ func TestInstallPlugin(t *testing.T) {
|
||||
*cfg.PluginSettings.ClientDirectory = webappPluginDir
|
||||
})
|
||||
|
||||
env, err := plugin.NewEnvironment(app.NewPluginAPI, pluginDir, webappPluginDir, app.Log(), nil)
|
||||
newPluginAPI := func(manifest *model.Manifest) plugin.API {
|
||||
return app.NewPluginAPI(c, manifest)
|
||||
}
|
||||
|
||||
env, err := plugin.NewEnvironment(newPluginAPI, pluginDir, webappPluginDir, app.Log(), nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
app.SetPluginsEnvironment(env)
|
||||
@@ -935,7 +944,7 @@ func TestInstallPlugin(t *testing.T) {
|
||||
"type": "text"
|
||||
}
|
||||
]
|
||||
}}`, "testinstallplugin", th.App)
|
||||
}}`, "testinstallplugin", th.App, th.Context)
|
||||
defer tearDown()
|
||||
|
||||
hooks, err := th.App.GetPluginsEnvironment().HooksForPlugin("testinstallplugin")
|
||||
@@ -1046,7 +1055,7 @@ func pluginAPIHookTest(t *testing.T, th *TestHelper, fileName string, id string,
|
||||
}
|
||||
setupPluginApiTest(t, code,
|
||||
fmt.Sprintf(`{"id": "%v", "backend": {"executable": "backend.exe"}, "settings_schema": %v}`, id, schema),
|
||||
id, th.App)
|
||||
id, th.App, th.Context)
|
||||
hooks, err := th.App.GetPluginsEnvironment().HooksForPlugin(id)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, hooks)
|
||||
@@ -1473,6 +1482,7 @@ func TestInterpluginPluginHTTP(t *testing.T) {
|
||||
"testplugininterclient",
|
||||
},
|
||||
th.App,
|
||||
th.Context,
|
||||
)
|
||||
|
||||
hooks, err := th.App.GetPluginsEnvironment().HooksForPlugin("testplugininterclient")
|
||||
@@ -1495,7 +1505,7 @@ func TestApiMetrics(t *testing.T) {
|
||||
defer os.RemoveAll(pluginDir)
|
||||
defer os.RemoveAll(webappPluginDir)
|
||||
|
||||
env, err := plugin.NewEnvironment(th.App.NewPluginAPI, pluginDir, webappPluginDir, th.App.Log(), metricsMock)
|
||||
env, err := plugin.NewEnvironment(th.NewPluginAPI, pluginDir, webappPluginDir, th.App.Log(), metricsMock)
|
||||
require.NoError(t, err)
|
||||
|
||||
th.App.SetPluginsEnvironment(env)
|
||||
@@ -1547,7 +1557,7 @@ func TestApiMetrics(t *testing.T) {
|
||||
Password: "passwd1",
|
||||
AuthService: "",
|
||||
}
|
||||
_, appErr := th.App.CreateUser(user1)
|
||||
_, appErr := th.App.CreateUser(th.Context, user1)
|
||||
require.Nil(t, appErr)
|
||||
time.Sleep(1 * time.Second)
|
||||
user1, appErr = th.App.GetUser(user1.Id)
|
||||
@@ -1617,7 +1627,7 @@ func TestPluginHTTPConnHijack(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, pluginCode)
|
||||
|
||||
tearDown, ids, errors := SetAppEnvironmentWithPlugins(t, []string{string(pluginCode)}, th.App, th.App.NewPluginAPI)
|
||||
tearDown, ids, errors := SetAppEnvironmentWithPlugins(t, []string{string(pluginCode)}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
require.NoError(t, errors[0])
|
||||
require.Len(t, ids, 1)
|
||||
@@ -1652,7 +1662,7 @@ func TestPluginHTTPUpgradeWebSocket(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, pluginCode)
|
||||
|
||||
tearDown, ids, errors := SetAppEnvironmentWithPlugins(t, []string{string(pluginCode)}, th.App, th.App.NewPluginAPI)
|
||||
tearDown, ids, errors := SetAppEnvironmentWithPlugins(t, []string{string(pluginCode)}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
require.NoError(t, errors[0])
|
||||
require.Len(t, ids, 1)
|
||||
@@ -1702,7 +1712,7 @@ func (*MockSlashCommandProvider) GetCommand(a *App, T i18n.TranslateFunc) *model
|
||||
DisplayName: "mock",
|
||||
}
|
||||
}
|
||||
func (mscp *MockSlashCommandProvider) DoCommand(a *App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (mscp *MockSlashCommandProvider) DoCommand(a *App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
mscp.Args = args
|
||||
mscp.Message = message
|
||||
return &model.CommandResponse{
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
@@ -88,16 +89,20 @@ func (a *App) UnregisterPluginCommand(pluginID, teamID, trigger string) {
|
||||
}
|
||||
|
||||
func (a *App) UnregisterPluginCommands(pluginID string) {
|
||||
a.Srv().pluginCommandsLock.Lock()
|
||||
defer a.Srv().pluginCommandsLock.Unlock()
|
||||
a.Srv().unregisterPluginCommands(pluginID)
|
||||
}
|
||||
|
||||
func (s *Server) unregisterPluginCommands(pluginID string) {
|
||||
s.pluginCommandsLock.Lock()
|
||||
defer s.pluginCommandsLock.Unlock()
|
||||
|
||||
var remaining []*PluginCommand
|
||||
for _, pc := range a.Srv().pluginCommands {
|
||||
for _, pc := range s.pluginCommands {
|
||||
if pc.PluginId != pluginID {
|
||||
remaining = append(remaining, pc)
|
||||
}
|
||||
}
|
||||
a.Srv().pluginCommands = remaining
|
||||
s.pluginCommands = remaining
|
||||
}
|
||||
|
||||
func (a *App) PluginCommandsForTeam(teamID string) []*model.Command {
|
||||
@@ -115,7 +120,7 @@ func (a *App) PluginCommandsForTeam(teamID string) []*model.Command {
|
||||
|
||||
// tryExecutePluginCommand attempts to run a command provided by a plugin based on the given arguments. If no such
|
||||
// command can be found, returns nil for all arguments.
|
||||
func (a *App) tryExecutePluginCommand(args *model.CommandArgs) (*model.Command, *model.CommandResponse, *model.AppError) {
|
||||
func (a *App) tryExecutePluginCommand(c *request.Context, args *model.CommandArgs) (*model.Command, *model.CommandResponse, *model.AppError) {
|
||||
parts := strings.Split(args.Command, " ")
|
||||
trigger := parts[0][1:]
|
||||
trigger = strings.ToLower(trigger)
|
||||
@@ -156,7 +161,7 @@ func (a *App) tryExecutePluginCommand(args *model.CommandArgs) (*model.Command,
|
||||
args.AddChannelMention(channelName, channelID)
|
||||
}
|
||||
|
||||
response, appErr := pluginHooks.ExecuteCommand(a.PluginContext(), args)
|
||||
response, appErr := pluginHooks.ExecuteCommand(pluginContext(c), args)
|
||||
|
||||
// Checking if plugin crashed after running the command
|
||||
if err := pluginsEnvironment.PerformHealthCheck(matched.PluginId); err != nil {
|
||||
|
||||
@@ -24,7 +24,7 @@ func TestPluginCommand(t *testing.T) {
|
||||
args.Command = "/plugin"
|
||||
|
||||
t.Run("error before plugin command registered", func(t *testing.T) {
|
||||
_, err := th.App.ExecuteCommand(args)
|
||||
_, err := th.App.ExecuteCommand(th.Context, args)
|
||||
require.NotNil(t, err)
|
||||
})
|
||||
|
||||
@@ -86,12 +86,12 @@ func TestPluginCommand(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`}, th.App, th.App.NewPluginAPI)
|
||||
`}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
require.Len(t, activationErrors, 1)
|
||||
require.Nil(t, nil, activationErrors[0])
|
||||
|
||||
resp, err := th.App.ExecuteCommand(args)
|
||||
resp, err := th.App.ExecuteCommand(th.Context, args)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, resp.ResponseType)
|
||||
require.Equal(t, "text", resp.Text)
|
||||
@@ -180,7 +180,7 @@ func TestPluginCommand(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`}, th.App, th.App.NewPluginAPI)
|
||||
`}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
|
||||
require.Len(t, activationErrors, 1)
|
||||
@@ -191,7 +191,7 @@ func TestPluginCommand(t *testing.T) {
|
||||
go func() {
|
||||
defer close(wait)
|
||||
|
||||
resp, err := th.App.ExecuteCommand(args)
|
||||
resp, err := th.App.ExecuteCommand(th.Context, args)
|
||||
|
||||
// Ignore if we kill below.
|
||||
if !killed {
|
||||
@@ -212,7 +212,7 @@ func TestPluginCommand(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("error after plugin command unregistered", func(t *testing.T) {
|
||||
_, err := th.App.ExecuteCommand(args)
|
||||
_, err := th.App.ExecuteCommand(th.Context, args)
|
||||
require.NotNil(t, err)
|
||||
})
|
||||
|
||||
@@ -274,13 +274,13 @@ func TestPluginCommand(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`}, th.App, th.App.NewPluginAPI)
|
||||
`}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
require.Len(t, activationErrors, 1)
|
||||
require.Nil(t, nil, activationErrors[0])
|
||||
|
||||
args.Command = "/code"
|
||||
resp, err := th.App.ExecuteCommand(args)
|
||||
resp, err := th.App.ExecuteCommand(th.Context, args)
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, resp.ResponseType)
|
||||
require.Equal(t, "text", resp.Text)
|
||||
@@ -320,12 +320,12 @@ func TestPluginCommand(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`}, th.App, th.App.NewPluginAPI)
|
||||
`}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
require.Len(t, activationErrors, 1)
|
||||
require.Nil(t, nil, activationErrors[0])
|
||||
args.Command = "/code"
|
||||
resp, err := th.App.ExecuteCommand(args)
|
||||
resp, err := th.App.ExecuteCommand(th.Context, args)
|
||||
require.Nil(t, resp)
|
||||
require.NotNil(t, err)
|
||||
require.Equal(t, err.Id, "model.plugin_command_error.error.app_error")
|
||||
@@ -365,12 +365,12 @@ func TestPluginCommand(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`}, th.App, th.App.NewPluginAPI)
|
||||
`}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
require.Len(t, activationErrors, 1)
|
||||
require.Nil(t, nil, activationErrors[0])
|
||||
args.Command = "/code"
|
||||
resp, err := th.App.ExecuteCommand(args)
|
||||
resp, err := th.App.ExecuteCommand(th.Context, args)
|
||||
require.Nil(t, resp)
|
||||
require.NotNil(t, err)
|
||||
require.Equal(t, err.Id, "model.plugin_command_crash.error.app_error")
|
||||
|
||||
@@ -2,18 +2,3 @@
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"github.com/mattermost/mattermost-server/v5/plugin"
|
||||
)
|
||||
|
||||
func (a *App) PluginContext() *plugin.Context {
|
||||
context := &plugin.Context{
|
||||
RequestId: a.RequestId(),
|
||||
SessionId: a.Session().Id,
|
||||
IpAddress: a.IpAddress(),
|
||||
AcceptLanguage: a.AcceptLanguage(),
|
||||
UserAgent: a.UserAgent(),
|
||||
}
|
||||
return context
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ func TestPluginDeadlock(t *testing.T) {
|
||||
|
||||
done := make(chan bool)
|
||||
go func() {
|
||||
SetAppEnvironmentWithPlugins(t, plugins, th.App, th.App.NewPluginAPI)
|
||||
SetAppEnvironmentWithPlugins(t, plugins, th.App, th.NewPluginAPI)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
@@ -196,7 +196,7 @@ func TestPluginDeadlock(t *testing.T) {
|
||||
|
||||
done := make(chan bool)
|
||||
go func() {
|
||||
SetAppEnvironmentWithPlugins(t, plugins, th.App, th.App.NewPluginAPI)
|
||||
SetAppEnvironmentWithPlugins(t, plugins, th.App, th.NewPluginAPI)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
@@ -291,7 +291,7 @@ func TestPluginDeadlock(t *testing.T) {
|
||||
}
|
||||
require.False(t, messageWillBePostedCalled, "MessageWillBePosted should not have been called")
|
||||
|
||||
SetAppEnvironmentWithPlugins(t, plugins, th.App, th.App.NewPluginAPI)
|
||||
SetAppEnvironmentWithPlugins(t, plugins, th.App, th.NewPluginAPI)
|
||||
th.TearDown()
|
||||
|
||||
posts, appErr = th.App.GetPosts(th.BasicChannel.Id, 0, 2)
|
||||
|
||||
@@ -7,10 +7,9 @@ import (
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
)
|
||||
|
||||
// notifyClusterPluginEvent publishes `event` to other clusters.
|
||||
func (a *App) notifyClusterPluginEvent(event string, data model.PluginEventData) {
|
||||
if a.Cluster() != nil {
|
||||
a.Cluster().SendClusterMessage(&model.ClusterMessage{
|
||||
func (s *Server) notifyClusterPluginEvent(event string, data model.PluginEventData) {
|
||||
if s.Cluster != nil {
|
||||
s.Cluster.SendClusterMessage(&model.ClusterMessage{
|
||||
Event: event,
|
||||
SendType: model.CLUSTER_SEND_RELIABLE,
|
||||
WaitForAllToSend: true,
|
||||
|
||||
@@ -37,7 +37,7 @@ func TestHealthCheckJob(t *testing.T) {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`,
|
||||
}, th.App, th.App.NewPluginAPI)
|
||||
}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
|
||||
env := th.App.GetPluginsEnvironment()
|
||||
|
||||
@@ -5,6 +5,7 @@ package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
@@ -19,6 +20,7 @@ import (
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/einterfaces/mocks"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/plugin"
|
||||
@@ -87,7 +89,7 @@ func TestHookMessageWillBePosted(t *testing.T) {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`,
|
||||
}, th.App, th.App.NewPluginAPI)
|
||||
}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
|
||||
post := &model.Post{
|
||||
@@ -96,7 +98,7 @@ func TestHookMessageWillBePosted(t *testing.T) {
|
||||
Message: "message_",
|
||||
CreateAt: model.GetMillis() - 10000,
|
||||
}
|
||||
_, err := th.App.CreatePost(post, th.BasicChannel, false, true)
|
||||
_, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true)
|
||||
if assert.NotNil(t, err) {
|
||||
assert.Equal(t, "Post rejected by plugin. rejected", err.Message)
|
||||
}
|
||||
@@ -128,7 +130,7 @@ func TestHookMessageWillBePosted(t *testing.T) {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`,
|
||||
}, th.App, th.App.NewPluginAPI)
|
||||
}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
|
||||
post := &model.Post{
|
||||
@@ -137,7 +139,7 @@ func TestHookMessageWillBePosted(t *testing.T) {
|
||||
Message: "message_",
|
||||
CreateAt: model.GetMillis() - 10000,
|
||||
}
|
||||
_, err := th.App.CreatePost(post, th.BasicChannel, false, true)
|
||||
_, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true)
|
||||
if assert.NotNil(t, err) {
|
||||
assert.Equal(t, "Post rejected by plugin. rejected", err.Message)
|
||||
}
|
||||
@@ -168,7 +170,7 @@ func TestHookMessageWillBePosted(t *testing.T) {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`,
|
||||
}, th.App, th.App.NewPluginAPI)
|
||||
}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
|
||||
post := &model.Post{
|
||||
@@ -177,7 +179,7 @@ func TestHookMessageWillBePosted(t *testing.T) {
|
||||
Message: "message",
|
||||
CreateAt: model.GetMillis() - 10000,
|
||||
}
|
||||
post, err := th.App.CreatePost(post, th.BasicChannel, false, true)
|
||||
post, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true)
|
||||
require.Nil(t, err)
|
||||
|
||||
assert.Equal(t, "message", post.Message)
|
||||
@@ -212,7 +214,7 @@ func TestHookMessageWillBePosted(t *testing.T) {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`,
|
||||
}, th.App, th.App.NewPluginAPI)
|
||||
}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
|
||||
post := &model.Post{
|
||||
@@ -221,7 +223,7 @@ func TestHookMessageWillBePosted(t *testing.T) {
|
||||
Message: "message",
|
||||
CreateAt: model.GetMillis() - 10000,
|
||||
}
|
||||
post, err := th.App.CreatePost(post, th.BasicChannel, false, true)
|
||||
post, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true)
|
||||
require.Nil(t, err)
|
||||
|
||||
assert.Equal(t, "message_fromplugin", post.Message)
|
||||
@@ -278,7 +280,7 @@ func TestHookMessageWillBePosted(t *testing.T) {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`,
|
||||
}, th.App, th.App.NewPluginAPI)
|
||||
}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
|
||||
post := &model.Post{
|
||||
@@ -287,7 +289,7 @@ func TestHookMessageWillBePosted(t *testing.T) {
|
||||
Message: "message",
|
||||
CreateAt: model.GetMillis() - 10000,
|
||||
}
|
||||
post, err := th.App.CreatePost(post, th.BasicChannel, false, true)
|
||||
post, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, "prefix_message_suffix", post.Message)
|
||||
})
|
||||
@@ -331,7 +333,7 @@ func TestHookMessageHasBeenPosted(t *testing.T) {
|
||||
Message: "message",
|
||||
CreateAt: model.GetMillis() - 10000,
|
||||
}
|
||||
_, err := th.App.CreatePost(post, th.BasicChannel, false, true)
|
||||
_, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true)
|
||||
require.Nil(t, err)
|
||||
}
|
||||
|
||||
@@ -361,7 +363,7 @@ func TestHookMessageWillBeUpdated(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`}, th.App, th.App.NewPluginAPI)
|
||||
`}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
|
||||
post := &model.Post{
|
||||
@@ -370,11 +372,11 @@ func TestHookMessageWillBeUpdated(t *testing.T) {
|
||||
Message: "message_",
|
||||
CreateAt: model.GetMillis() - 10000,
|
||||
}
|
||||
post, err := th.App.CreatePost(post, th.BasicChannel, false, true)
|
||||
post, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, "message_", post.Message)
|
||||
post.Message = post.Message + "edited_"
|
||||
post, err = th.App.UpdatePost(post, true)
|
||||
post, err = th.App.UpdatePost(th.Context, post, true)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, "message_edited_fromplugin", post.Message)
|
||||
}
|
||||
@@ -418,11 +420,11 @@ func TestHookMessageHasBeenUpdated(t *testing.T) {
|
||||
Message: "message_",
|
||||
CreateAt: model.GetMillis() - 10000,
|
||||
}
|
||||
post, err := th.App.CreatePost(post, th.BasicChannel, false, true)
|
||||
post, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, "message_", post.Message)
|
||||
post.Message = post.Message + "edited"
|
||||
_, err = th.App.UpdatePost(post, true)
|
||||
_, err = th.App.UpdatePost(th.Context, post, true)
|
||||
require.Nil(t, err)
|
||||
}
|
||||
|
||||
@@ -460,7 +462,7 @@ func TestHookFileWillBeUploaded(t *testing.T) {
|
||||
}, th.App, func(*model.Manifest) plugin.API { return &mockAPI })
|
||||
defer tearDown()
|
||||
|
||||
_, err := th.App.UploadFiles(
|
||||
_, err := th.App.UploadFiles(th.Context,
|
||||
"noteam",
|
||||
th.BasicChannel.Id,
|
||||
th.BasicUser.Id,
|
||||
@@ -513,7 +515,7 @@ func TestHookFileWillBeUploaded(t *testing.T) {
|
||||
}, th.App, func(*model.Manifest) plugin.API { return &mockAPI })
|
||||
defer tearDown()
|
||||
|
||||
_, err := th.App.UploadFiles(
|
||||
_, err := th.App.UploadFiles(th.Context,
|
||||
"noteam",
|
||||
th.BasicChannel.Id,
|
||||
th.BasicUser.Id,
|
||||
@@ -560,7 +562,7 @@ func TestHookFileWillBeUploaded(t *testing.T) {
|
||||
}, th.App, func(*model.Manifest) plugin.API { return &mockAPI })
|
||||
defer tearDown()
|
||||
|
||||
response, err := th.App.UploadFiles(
|
||||
response, err := th.App.UploadFiles(th.Context,
|
||||
"noteam",
|
||||
th.BasicChannel.Id,
|
||||
th.BasicUser.Id,
|
||||
@@ -636,7 +638,7 @@ func TestHookFileWillBeUploaded(t *testing.T) {
|
||||
}, th.App, func(*model.Manifest) plugin.API { return &mockAPI })
|
||||
defer tearDown()
|
||||
|
||||
response, err := th.App.UploadFiles(
|
||||
response, err := th.App.UploadFiles(th.Context,
|
||||
"noteam",
|
||||
th.BasicChannel.Id,
|
||||
th.BasicUser.Id,
|
||||
@@ -690,12 +692,12 @@ func TestUserWillLogIn_Blocked(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`}, th.App, th.App.NewPluginAPI)
|
||||
`}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
|
||||
r := &http.Request{}
|
||||
w := httptest.NewRecorder()
|
||||
err = th.App.DoLogin(w, r, th.BasicUser, "", false, false, false)
|
||||
err = th.App.DoLogin(th.Context, w, r, th.BasicUser, "", false, false, false)
|
||||
|
||||
assert.Contains(t, err.Id, "Login rejected by plugin", "Expected Login rejected by plugin, got %s", err.Id)
|
||||
}
|
||||
@@ -729,15 +731,15 @@ func TestUserWillLogInIn_Passed(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`}, th.App, th.App.NewPluginAPI)
|
||||
`}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
|
||||
r := &http.Request{}
|
||||
w := httptest.NewRecorder()
|
||||
err = th.App.DoLogin(w, r, th.BasicUser, "", false, false, false)
|
||||
err = th.App.DoLogin(th.Context, w, r, th.BasicUser, "", false, false, false)
|
||||
|
||||
assert.Nil(t, err, "Expected nil, got %s", err)
|
||||
assert.Equal(t, th.App.Session().UserId, th.BasicUser.Id)
|
||||
assert.Equal(t, th.Context.Session().UserId, th.BasicUser.Id)
|
||||
}
|
||||
|
||||
func TestUserHasLoggedIn(t *testing.T) {
|
||||
@@ -770,12 +772,12 @@ func TestUserHasLoggedIn(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`}, th.App, th.App.NewPluginAPI)
|
||||
`}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
|
||||
r := &http.Request{}
|
||||
w := httptest.NewRecorder()
|
||||
err = th.App.DoLogin(w, r, th.BasicUser, "", false, false, false)
|
||||
err = th.App.DoLogin(th.Context, w, r, th.BasicUser, "", false, false, false)
|
||||
|
||||
assert.Nil(t, err, "Expected nil, got %s", err)
|
||||
|
||||
@@ -812,7 +814,7 @@ func TestUserHasBeenCreated(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`}, th.App, th.App.NewPluginAPI)
|
||||
`}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
|
||||
user := &model.User{
|
||||
@@ -822,7 +824,7 @@ func TestUserHasBeenCreated(t *testing.T) {
|
||||
Password: "passwd1",
|
||||
AuthService: "",
|
||||
}
|
||||
_, err := th.App.CreateUser(user)
|
||||
_, err := th.App.CreateUser(th.Context, user)
|
||||
require.Nil(t, err)
|
||||
|
||||
time.Sleep(1 * time.Second)
|
||||
@@ -859,7 +861,7 @@ func TestErrorString(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`}, th.App, th.App.NewPluginAPI)
|
||||
`}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
|
||||
require.Len(t, activationErrors, 1)
|
||||
@@ -889,7 +891,7 @@ func TestErrorString(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`}, th.App, th.App.NewPluginAPI)
|
||||
`}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
|
||||
require.Len(t, activationErrors, 1)
|
||||
@@ -909,19 +911,16 @@ func TestHookContext(t *testing.T) {
|
||||
defer th.TearDown()
|
||||
|
||||
// We don't actually have a session, we are faking it so just set something arbitrarily
|
||||
th.App.Session().Id = model.NewId()
|
||||
th.App.requestId = model.NewId()
|
||||
th.App.ipAddress = model.NewId()
|
||||
th.App.acceptLanguage = model.NewId()
|
||||
th.App.userAgent = model.NewId()
|
||||
ctx := request.NewContext(context.Background(), model.NewId(), model.NewId(), model.NewId(), model.NewId(), model.NewId(), model.Session{}, nil)
|
||||
ctx.Session().Id = model.NewId()
|
||||
|
||||
var mockAPI plugintest.API
|
||||
mockAPI.On("LoadPluginConfiguration", mock.Anything).Return(nil)
|
||||
mockAPI.On("LogDebug", th.App.Session().Id).Return(nil)
|
||||
mockAPI.On("LogInfo", th.App.RequestId()).Return(nil)
|
||||
mockAPI.On("LogError", th.App.IpAddress()).Return(nil)
|
||||
mockAPI.On("LogWarn", th.App.AcceptLanguage()).Return(nil)
|
||||
mockAPI.On("DeleteTeam", th.App.UserAgent()).Return(nil)
|
||||
mockAPI.On("LogDebug", ctx.Session().Id).Return(nil)
|
||||
mockAPI.On("LogInfo", ctx.RequestId()).Return(nil)
|
||||
mockAPI.On("LogError", ctx.IpAddress()).Return(nil)
|
||||
mockAPI.On("LogWarn", ctx.AcceptLanguage()).Return(nil)
|
||||
mockAPI.On("DeleteTeam", ctx.UserAgent()).Return(nil)
|
||||
|
||||
tearDown, _, _ := SetAppEnvironmentWithPlugins(t,
|
||||
[]string{
|
||||
@@ -957,7 +956,7 @@ func TestHookContext(t *testing.T) {
|
||||
Message: "not this",
|
||||
CreateAt: model.GetMillis() - 10000,
|
||||
}
|
||||
_, err := th.App.CreatePost(post, th.BasicChannel, false, true)
|
||||
_, err := th.App.CreatePost(ctx, post, th.BasicChannel, false, true)
|
||||
require.Nil(t, err)
|
||||
}
|
||||
|
||||
@@ -996,7 +995,7 @@ func TestActiveHooks(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`}, th.App, th.App.NewPluginAPI)
|
||||
`}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
|
||||
require.Len(t, pluginIDs, 1)
|
||||
@@ -1010,7 +1009,7 @@ func TestActiveHooks(t *testing.T) {
|
||||
Password: "passwd1",
|
||||
AuthService: "",
|
||||
}
|
||||
_, appErr := th.App.CreateUser(user1)
|
||||
_, appErr := th.App.CreateUser(th.Context, user1)
|
||||
require.Nil(t, appErr)
|
||||
time.Sleep(1 * time.Second)
|
||||
user1, appErr = th.App.GetUser(user1.Id)
|
||||
@@ -1046,7 +1045,7 @@ func TestHookMetrics(t *testing.T) {
|
||||
defer os.RemoveAll(pluginDir)
|
||||
defer os.RemoveAll(webappPluginDir)
|
||||
|
||||
env, err := plugin.NewEnvironment(th.App.NewPluginAPI, pluginDir, webappPluginDir, th.App.Log(), metricsMock)
|
||||
env, err := plugin.NewEnvironment(th.NewPluginAPI, pluginDir, webappPluginDir, th.App.Log(), metricsMock)
|
||||
require.NoError(t, err)
|
||||
|
||||
th.App.SetPluginsEnvironment(env)
|
||||
@@ -1116,7 +1115,7 @@ func TestHookMetrics(t *testing.T) {
|
||||
Password: "passwd1",
|
||||
AuthService: "",
|
||||
}
|
||||
_, appErr := th.App.CreateUser(user1)
|
||||
_, appErr := th.App.CreateUser(th.Context, user1)
|
||||
require.Nil(t, appErr)
|
||||
time.Sleep(1 * time.Second)
|
||||
user1, appErr = th.App.GetUser(user1.Id)
|
||||
@@ -1169,7 +1168,7 @@ func TestHookReactionHasBeenAdded(t *testing.T) {
|
||||
EmojiName: "smile",
|
||||
CreateAt: model.GetMillis() - 10000,
|
||||
}
|
||||
_, err := th.App.SaveReactionForPost(reaction)
|
||||
_, err := th.App.SaveReactionForPost(th.Context, reaction)
|
||||
require.Nil(t, err)
|
||||
}
|
||||
|
||||
@@ -1212,7 +1211,7 @@ func TestHookReactionHasBeenRemoved(t *testing.T) {
|
||||
CreateAt: model.GetMillis() - 10000,
|
||||
}
|
||||
|
||||
err := th.App.DeleteReactionForPost(reaction)
|
||||
err := th.App.DeleteReactionForPost(th.Context, reaction)
|
||||
|
||||
require.Nil(t, err)
|
||||
}
|
||||
|
||||
@@ -62,9 +62,13 @@ const managedPluginFileName = ".filestore"
|
||||
const fileStorePluginFolder = "plugins"
|
||||
|
||||
func (a *App) InstallPluginFromData(data model.PluginEventData) {
|
||||
a.Srv().installPluginFromData(data)
|
||||
}
|
||||
|
||||
func (s *Server) installPluginFromData(data model.PluginEventData) {
|
||||
mlog.Debug("Installing plugin as per cluster message", mlog.String("plugin_id", data.Id))
|
||||
|
||||
pluginSignaturePathMap, appErr := a.getPluginsFromFolder()
|
||||
pluginSignaturePathMap, appErr := s.getPluginsFromFolder()
|
||||
if appErr != nil {
|
||||
mlog.Error("Failed to get plugin signatures from filestore. Can't install plugin from data.", mlog.Err(appErr))
|
||||
return
|
||||
@@ -75,7 +79,7 @@ func (a *App) InstallPluginFromData(data model.PluginEventData) {
|
||||
return
|
||||
}
|
||||
|
||||
reader, appErr := a.FileReader(plugin.path)
|
||||
reader, appErr := s.fileReader(plugin.path)
|
||||
if appErr != nil {
|
||||
mlog.Error("Failed to open plugin bundle from file store.", mlog.String("bundle", plugin.path), mlog.Err(appErr))
|
||||
return
|
||||
@@ -83,8 +87,8 @@ func (a *App) InstallPluginFromData(data model.PluginEventData) {
|
||||
defer reader.Close()
|
||||
|
||||
var signature filestore.ReadCloseSeeker
|
||||
if *a.Config().PluginSettings.RequirePluginSignature {
|
||||
signature, appErr = a.FileReader(plugin.signaturePath)
|
||||
if *s.Config().PluginSettings.RequirePluginSignature {
|
||||
signature, appErr = s.fileReader(plugin.signaturePath)
|
||||
if appErr != nil {
|
||||
mlog.Error("Failed to open plugin signature from file store.", mlog.Err(appErr))
|
||||
return
|
||||
@@ -92,36 +96,44 @@ func (a *App) InstallPluginFromData(data model.PluginEventData) {
|
||||
defer signature.Close()
|
||||
}
|
||||
|
||||
manifest, appErr := a.installPluginLocally(reader, signature, installPluginLocallyAlways)
|
||||
manifest, appErr := s.installPluginLocally(reader, signature, installPluginLocallyAlways)
|
||||
if appErr != nil {
|
||||
mlog.Error("Failed to sync plugin from file store", mlog.String("bundle", plugin.path), mlog.Err(appErr))
|
||||
return
|
||||
}
|
||||
|
||||
if err := a.notifyPluginEnabled(manifest); err != nil {
|
||||
if err := s.notifyPluginEnabled(manifest); err != nil {
|
||||
mlog.Error("Failed notify plugin enabled", mlog.Err(err))
|
||||
}
|
||||
|
||||
if err := a.notifyPluginStatusesChanged(); err != nil {
|
||||
if err := s.notifyPluginStatusesChanged(); err != nil {
|
||||
mlog.Error("Failed to notify plugin status changed", mlog.Err(err))
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) RemovePluginFromData(data model.PluginEventData) {
|
||||
a.Srv().removePluginFromData(data)
|
||||
}
|
||||
|
||||
func (s *Server) removePluginFromData(data model.PluginEventData) {
|
||||
mlog.Debug("Removing plugin as per cluster message", mlog.String("plugin_id", data.Id))
|
||||
|
||||
if err := a.removePluginLocally(data.Id); err != nil {
|
||||
if err := s.removePluginLocally(data.Id); err != nil {
|
||||
mlog.Warn("Failed to remove plugin locally", mlog.Err(err), mlog.String("id", data.Id))
|
||||
}
|
||||
|
||||
if err := a.notifyPluginStatusesChanged(); err != nil {
|
||||
if err := s.notifyPluginStatusesChanged(); err != nil {
|
||||
mlog.Warn("failed to notify plugin status changed", mlog.Err(err))
|
||||
}
|
||||
}
|
||||
|
||||
// InstallPluginWithSignature verifies and installs plugin.
|
||||
func (a *App) InstallPluginWithSignature(pluginFile, signature io.ReadSeeker) (*model.Manifest, *model.AppError) {
|
||||
return a.installPlugin(pluginFile, signature, installPluginLocallyAlways)
|
||||
return a.Srv().installPluginWithSignature(pluginFile, signature)
|
||||
}
|
||||
|
||||
func (s *Server) installPluginWithSignature(pluginFile, signature io.ReadSeeker) (*model.Manifest, *model.AppError) {
|
||||
return s.installPlugin(pluginFile, signature, installPluginLocallyAlways)
|
||||
}
|
||||
|
||||
// InstallPlugin unpacks and installs a plugin but does not enable or activate it.
|
||||
@@ -135,36 +147,40 @@ func (a *App) InstallPlugin(pluginFile io.ReadSeeker, replace bool) (*model.Mani
|
||||
}
|
||||
|
||||
func (a *App) installPlugin(pluginFile, signature io.ReadSeeker, installationStrategy pluginInstallationStrategy) (*model.Manifest, *model.AppError) {
|
||||
manifest, appErr := a.installPluginLocally(pluginFile, signature, installationStrategy)
|
||||
return a.Srv().installPlugin(pluginFile, signature, installationStrategy)
|
||||
}
|
||||
|
||||
func (s *Server) installPlugin(pluginFile, signature io.ReadSeeker, installationStrategy pluginInstallationStrategy) (*model.Manifest, *model.AppError) {
|
||||
manifest, appErr := s.installPluginLocally(pluginFile, signature, installationStrategy)
|
||||
if appErr != nil {
|
||||
return nil, appErr
|
||||
}
|
||||
|
||||
if signature != nil {
|
||||
signature.Seek(0, 0)
|
||||
if _, appErr = a.WriteFile(signature, a.getSignatureStorePath(manifest.Id)); appErr != nil {
|
||||
if _, appErr = s.writeFile(signature, getSignatureStorePath(manifest.Id)); appErr != nil {
|
||||
return nil, model.NewAppError("saveSignature", "app.plugin.store_signature.app_error", nil, appErr.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// Store bundle in the file store to allow access from other servers.
|
||||
pluginFile.Seek(0, 0)
|
||||
if _, appErr := a.WriteFile(pluginFile, a.getBundleStorePath(manifest.Id)); appErr != nil {
|
||||
if _, appErr := s.writeFile(pluginFile, getBundleStorePath(manifest.Id)); appErr != nil {
|
||||
return nil, model.NewAppError("uploadPlugin", "app.plugin.store_bundle.app_error", nil, appErr.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
a.notifyClusterPluginEvent(
|
||||
s.notifyClusterPluginEvent(
|
||||
model.CLUSTER_EVENT_INSTALL_PLUGIN,
|
||||
model.PluginEventData{
|
||||
Id: manifest.Id,
|
||||
},
|
||||
)
|
||||
|
||||
if err := a.notifyPluginEnabled(manifest); err != nil {
|
||||
if err := s.notifyPluginEnabled(manifest); err != nil {
|
||||
mlog.Warn("Failed notify plugin enabled", mlog.Err(err))
|
||||
}
|
||||
|
||||
if err := a.notifyPluginStatusesChanged(); err != nil {
|
||||
if err := s.notifyPluginStatusesChanged(); err != nil {
|
||||
mlog.Warn("Failed to notify plugin status changed", mlog.Err(err))
|
||||
}
|
||||
|
||||
@@ -174,9 +190,13 @@ func (a *App) installPlugin(pluginFile, signature io.ReadSeeker, installationStr
|
||||
// InstallMarketplacePlugin installs a plugin listed in the marketplace server. It will get the plugin bundle
|
||||
// from the prepackaged folder, if available, or remotely if EnableRemoteMarketplace is true.
|
||||
func (a *App) InstallMarketplacePlugin(request *model.InstallMarketplacePluginRequest) (*model.Manifest, *model.AppError) {
|
||||
return a.Srv().installMarketplacePlugin(request)
|
||||
}
|
||||
|
||||
func (s *Server) installMarketplacePlugin(request *model.InstallMarketplacePluginRequest) (*model.Manifest, *model.AppError) {
|
||||
var pluginFile, signatureFile io.ReadSeeker
|
||||
|
||||
prepackagedPlugin, appErr := a.getPrepackagedPlugin(request.Id, request.Version)
|
||||
prepackagedPlugin, appErr := s.getPrepackagedPlugin(request.Id, request.Version)
|
||||
if appErr != nil && appErr.Id != "app.plugin.marketplace_plugins.not_found.app_error" {
|
||||
return nil, appErr
|
||||
}
|
||||
@@ -192,14 +212,14 @@ func (a *App) InstallMarketplacePlugin(request *model.InstallMarketplacePluginRe
|
||||
signatureFile = bytes.NewReader(prepackagedPlugin.Signature)
|
||||
}
|
||||
|
||||
if *a.Config().PluginSettings.EnableRemoteMarketplace && pluginFile == nil {
|
||||
if *s.Config().PluginSettings.EnableRemoteMarketplace && pluginFile == nil {
|
||||
var plugin *model.BaseMarketplacePlugin
|
||||
plugin, appErr = a.getRemoteMarketplacePlugin(request.Id, request.Version)
|
||||
plugin, appErr = s.getRemoteMarketplacePlugin(request.Id, request.Version)
|
||||
if appErr != nil {
|
||||
return nil, appErr
|
||||
}
|
||||
|
||||
downloadedPluginBytes, err := a.DownloadFromURL(plugin.DownloadURL)
|
||||
downloadedPluginBytes, err := s.downloadFromURL(plugin.DownloadURL)
|
||||
if err != nil {
|
||||
return nil, model.NewAppError("InstallMarketplacePlugin", "app.plugin.install_marketplace_plugin.app_error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
@@ -218,7 +238,7 @@ func (a *App) InstallMarketplacePlugin(request *model.InstallMarketplacePluginRe
|
||||
return nil, model.NewAppError("InstallMarketplacePlugin", "app.plugin.marketplace_plugins.signature_not_found.app_error", nil, "", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
manifest, appErr := a.InstallPluginWithSignature(pluginFile, signatureFile)
|
||||
manifest, appErr := s.installPluginWithSignature(pluginFile, signatureFile)
|
||||
if appErr != nil {
|
||||
return nil, appErr
|
||||
}
|
||||
@@ -238,14 +258,18 @@ const (
|
||||
)
|
||||
|
||||
func (a *App) installPluginLocally(pluginFile, signature io.ReadSeeker, installationStrategy pluginInstallationStrategy) (*model.Manifest, *model.AppError) {
|
||||
pluginsEnvironment := a.GetPluginsEnvironment()
|
||||
return a.Srv().installPluginLocally(pluginFile, signature, installationStrategy)
|
||||
}
|
||||
|
||||
func (s *Server) installPluginLocally(pluginFile, signature io.ReadSeeker, installationStrategy pluginInstallationStrategy) (*model.Manifest, *model.AppError) {
|
||||
pluginsEnvironment := s.GetPluginsEnvironment()
|
||||
if pluginsEnvironment == nil {
|
||||
return nil, model.NewAppError("installPluginLocally", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented)
|
||||
}
|
||||
|
||||
// verify signature
|
||||
if signature != nil {
|
||||
if err := a.VerifyPlugin(pluginFile, signature); err != nil {
|
||||
if err := s.verifyPlugin(pluginFile, signature); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -261,7 +285,7 @@ func (a *App) installPluginLocally(pluginFile, signature io.ReadSeeker, installa
|
||||
return nil, appErr
|
||||
}
|
||||
|
||||
manifest, appErr = a.installExtractedPlugin(manifest, pluginDir, installationStrategy)
|
||||
manifest, appErr = s.installExtractedPlugin(manifest, pluginDir, installationStrategy)
|
||||
if appErr != nil {
|
||||
return nil, appErr
|
||||
}
|
||||
@@ -296,8 +320,8 @@ func extractPlugin(pluginFile io.ReadSeeker, extractDir string) (*model.Manifest
|
||||
return manifest, extractDir, nil
|
||||
}
|
||||
|
||||
func (a *App) installExtractedPlugin(manifest *model.Manifest, fromPluginDir string, installationStrategy pluginInstallationStrategy) (*model.Manifest, *model.AppError) {
|
||||
pluginsEnvironment := a.GetPluginsEnvironment()
|
||||
func (s *Server) installExtractedPlugin(manifest *model.Manifest, fromPluginDir string, installationStrategy pluginInstallationStrategy) (*model.Manifest, *model.AppError) {
|
||||
pluginsEnvironment := s.GetPluginsEnvironment()
|
||||
if pluginsEnvironment == nil {
|
||||
return nil, model.NewAppError("installExtractedPlugin", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented)
|
||||
}
|
||||
@@ -344,12 +368,12 @@ func (a *App) installExtractedPlugin(manifest *model.Manifest, fromPluginDir str
|
||||
|
||||
// Otherwise remove the existing installation prior to install below.
|
||||
mlog.Debug("Removing existing installation of plugin before local install", mlog.String("plugin_id", existingManifest.Id), mlog.String("version", existingManifest.Version))
|
||||
if err := a.removePluginLocally(existingManifest.Id); err != nil {
|
||||
if err := s.removePluginLocally(existingManifest.Id); err != nil {
|
||||
return nil, model.NewAppError("installExtractedPlugin", "app.plugin.install_id_failed_remove.app_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
pluginPath := filepath.Join(*a.Config().PluginSettings.Directory, manifest.Id)
|
||||
pluginPath := filepath.Join(*s.Config().PluginSettings.Directory, manifest.Id)
|
||||
err = utils.CopyDir(fromPluginDir, pluginPath)
|
||||
if err != nil {
|
||||
return nil, model.NewAppError("installExtractedPlugin", "app.plugin.mvdir.app_error", nil, err.Error(), http.StatusInternalServerError)
|
||||
@@ -371,9 +395,9 @@ func (a *App) installExtractedPlugin(manifest *model.Manifest, fromPluginDir str
|
||||
}
|
||||
|
||||
// Activate the plugin if enabled.
|
||||
pluginState := a.Config().PluginSettings.PluginStates[manifest.Id]
|
||||
pluginState := s.Config().PluginSettings.PluginStates[manifest.Id]
|
||||
if pluginState != nil && pluginState.Enable {
|
||||
if manifest.Id == "com.mattermost.apps" && !a.Config().FeatureFlags.AppsEnabled {
|
||||
if manifest.Id == "com.mattermost.apps" && !s.Config().FeatureFlags.AppsEnabled {
|
||||
return manifest, nil
|
||||
}
|
||||
updatedManifest, _, err := pluginsEnvironment.Activate(manifest.Id)
|
||||
@@ -389,44 +413,44 @@ func (a *App) installExtractedPlugin(manifest *model.Manifest, fromPluginDir str
|
||||
}
|
||||
|
||||
func (a *App) RemovePlugin(id string) *model.AppError {
|
||||
return a.removePlugin(id)
|
||||
return a.Srv().removePlugin(id)
|
||||
}
|
||||
|
||||
func (a *App) removePlugin(id string) *model.AppError {
|
||||
func (s *Server) removePlugin(id string) *model.AppError {
|
||||
// Disable plugin before removal to make sure this
|
||||
// plugin remains disabled on re-install.
|
||||
if err := a.DisablePlugin(id); err != nil {
|
||||
if err := s.disablePlugin(id); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := a.removePluginLocally(id); err != nil {
|
||||
if err := s.removePluginLocally(id); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Remove bundle from the file store.
|
||||
storePluginFileName := a.getBundleStorePath(id)
|
||||
bundleExist, err := a.FileExists(storePluginFileName)
|
||||
storePluginFileName := getBundleStorePath(id)
|
||||
bundleExist, err := s.fileExists(storePluginFileName)
|
||||
if err != nil {
|
||||
return model.NewAppError("removePlugin", "app.plugin.remove_bundle.app_error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
if !bundleExist {
|
||||
return nil
|
||||
}
|
||||
if err = a.RemoveFile(storePluginFileName); err != nil {
|
||||
if err = s.removeFile(storePluginFileName); err != nil {
|
||||
return model.NewAppError("removePlugin", "app.plugin.remove_bundle.app_error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
if err = a.removeSignature(id); err != nil {
|
||||
if err = s.removeSignature(id); err != nil {
|
||||
mlog.Warn("Can't remove signature", mlog.Err(err))
|
||||
}
|
||||
|
||||
a.notifyClusterPluginEvent(
|
||||
s.notifyClusterPluginEvent(
|
||||
model.CLUSTER_EVENT_REMOVE_PLUGIN,
|
||||
model.PluginEventData{
|
||||
Id: id,
|
||||
},
|
||||
)
|
||||
|
||||
if err := a.notifyPluginStatusesChanged(); err != nil {
|
||||
if err := s.notifyPluginStatusesChanged(); err != nil {
|
||||
mlog.Warn("Failed to notify plugin status changed", mlog.Err(err))
|
||||
}
|
||||
|
||||
@@ -434,7 +458,11 @@ func (a *App) removePlugin(id string) *model.AppError {
|
||||
}
|
||||
|
||||
func (a *App) removePluginLocally(id string) *model.AppError {
|
||||
pluginsEnvironment := a.GetPluginsEnvironment()
|
||||
return a.Srv().removePluginLocally(id)
|
||||
}
|
||||
|
||||
func (s *Server) removePluginLocally(id string) *model.AppError {
|
||||
pluginsEnvironment := s.GetPluginsEnvironment()
|
||||
if pluginsEnvironment == nil {
|
||||
return model.NewAppError("removePlugin", "app.plugin.disabled.app_error", nil, "", http.StatusNotImplemented)
|
||||
}
|
||||
@@ -460,7 +488,7 @@ func (a *App) removePluginLocally(id string) *model.AppError {
|
||||
|
||||
pluginsEnvironment.Deactivate(id)
|
||||
pluginsEnvironment.RemovePlugin(id)
|
||||
a.UnregisterPluginCommands(id)
|
||||
s.unregisterPluginCommands(id)
|
||||
|
||||
if err := os.RemoveAll(pluginPath); err != nil {
|
||||
return model.NewAppError("removePlugin", "app.plugin.remove.app_error", nil, err.Error(), http.StatusInternalServerError)
|
||||
@@ -469,9 +497,9 @@ func (a *App) removePluginLocally(id string) *model.AppError {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) removeSignature(pluginID string) *model.AppError {
|
||||
filePath := a.getSignatureStorePath(pluginID)
|
||||
exists, err := a.FileExists(filePath)
|
||||
func (s *Server) removeSignature(pluginID string) *model.AppError {
|
||||
filePath := getSignatureStorePath(pluginID)
|
||||
exists, err := s.fileExists(filePath)
|
||||
if err != nil {
|
||||
return model.NewAppError("removeSignature", "app.plugin.remove_bundle.app_error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
@@ -479,16 +507,16 @@ func (a *App) removeSignature(pluginID string) *model.AppError {
|
||||
mlog.Debug("no plugin signature to remove", mlog.String("plugin_id", pluginID))
|
||||
return nil
|
||||
}
|
||||
if err = a.RemoveFile(filePath); err != nil {
|
||||
if err = s.removeFile(filePath); err != nil {
|
||||
return model.NewAppError("removeSignature", "app.plugin.remove_bundle.app_error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) getBundleStorePath(id string) string {
|
||||
func getBundleStorePath(id string) string {
|
||||
return filepath.Join(fileStorePluginFolder, fmt.Sprintf("%s.tar.gz", id))
|
||||
}
|
||||
|
||||
func (a *App) getSignatureStorePath(id string) string {
|
||||
func getSignatureStorePath(id string) string {
|
||||
return filepath.Join(fileStorePluginFolder, fmt.Sprintf("%s.tar.gz.sig", id))
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ func TestPluginShutdownTest(t *testing.T) {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`,
|
||||
}, th.App, th.App.NewPluginAPI)
|
||||
}, th.App, th.NewPluginAPI)
|
||||
defer tearDown()
|
||||
|
||||
done := make(chan bool)
|
||||
|
||||
@@ -21,12 +21,20 @@ import (
|
||||
|
||||
// GetPluginPublicKeyFiles returns all public keys listed in the config.
|
||||
func (a *App) GetPluginPublicKeyFiles() ([]string, *model.AppError) {
|
||||
return a.Config().PluginSettings.SignaturePublicKeyFiles, nil
|
||||
return a.Srv().getPluginPublicKeyFiles()
|
||||
}
|
||||
|
||||
func (s *Server) getPluginPublicKeyFiles() ([]string, *model.AppError) {
|
||||
return s.Config().PluginSettings.SignaturePublicKeyFiles, nil
|
||||
}
|
||||
|
||||
// GetPublicKey will return the actual public key saved in the `name` file.
|
||||
func (a *App) GetPublicKey(name string) ([]byte, *model.AppError) {
|
||||
data, err := a.Srv().configStore.GetFile(name)
|
||||
return a.Srv().getPublicKey(name)
|
||||
}
|
||||
|
||||
func (s *Server) getPublicKey(name string) ([]byte, *model.AppError) {
|
||||
data, err := s.configStore.GetFile(name)
|
||||
if err != nil {
|
||||
return nil, model.NewAppError("GetPublicKey", "app.plugin.get_public_key.get_file.app_error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
@@ -75,15 +83,19 @@ func (a *App) DeletePublicKey(name string) *model.AppError {
|
||||
|
||||
// VerifyPlugin checks that the given signature corresponds to the given plugin and matches a trusted certificate.
|
||||
func (a *App) VerifyPlugin(plugin, signature io.ReadSeeker) *model.AppError {
|
||||
return a.Srv().verifyPlugin(plugin, signature)
|
||||
}
|
||||
|
||||
func (s *Server) verifyPlugin(plugin, signature io.ReadSeeker) *model.AppError {
|
||||
if err := verifySignature(bytes.NewReader(mattermostPluginPublicKey), plugin, signature); err == nil {
|
||||
return nil
|
||||
}
|
||||
publicKeys, appErr := a.GetPluginPublicKeyFiles()
|
||||
publicKeys, appErr := s.getPluginPublicKeyFiles()
|
||||
if appErr != nil {
|
||||
return appErr
|
||||
}
|
||||
for _, pk := range publicKeys {
|
||||
pkBytes, appErr := a.GetPublicKey(pk)
|
||||
pkBytes, appErr := s.getPublicKey(pk)
|
||||
if appErr != nil {
|
||||
mlog.Warn("Unable to get public key for ", mlog.String("filename", pk))
|
||||
continue
|
||||
|
||||
@@ -71,13 +71,17 @@ func (a *App) GetPluginStatuses() (model.PluginStatuses, *model.AppError) {
|
||||
|
||||
// GetClusterPluginStatuses returns the status for plugins installed anywhere in the cluster.
|
||||
func (a *App) GetClusterPluginStatuses() (model.PluginStatuses, *model.AppError) {
|
||||
pluginStatuses, err := a.GetPluginStatuses()
|
||||
return a.Srv().getClusterPluginStatuses()
|
||||
}
|
||||
|
||||
func (s *Server) getClusterPluginStatuses() (model.PluginStatuses, *model.AppError) {
|
||||
pluginStatuses, err := s.GetPluginStatuses()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if a.Cluster() != nil && *a.Config().ClusterSettings.Enable {
|
||||
clusterPluginStatuses, err := a.Cluster().GetPluginStatuses()
|
||||
if s.Cluster != nil && *s.Config().ClusterSettings.Enable {
|
||||
clusterPluginStatuses, err := s.Cluster.GetPluginStatuses()
|
||||
if err != nil {
|
||||
return nil, model.NewAppError("GetClusterPluginStatuses", "app.plugin.get_cluster_plugin_statuses.app_error", nil, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
@@ -88,8 +92,8 @@ func (a *App) GetClusterPluginStatuses() (model.PluginStatuses, *model.AppError)
|
||||
return pluginStatuses, nil
|
||||
}
|
||||
|
||||
func (a *App) notifyPluginStatusesChanged() error {
|
||||
pluginStatuses, err := a.GetClusterPluginStatuses()
|
||||
func (s *Server) notifyPluginStatusesChanged() error {
|
||||
pluginStatuses, err := s.getClusterPluginStatuses()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -98,7 +102,7 @@ func (a *App) notifyPluginStatusesChanged() error {
|
||||
message := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_PLUGIN_STATUSES_CHANGED, "", "", "", nil)
|
||||
message.Add("plugin_statuses", pluginStatuses)
|
||||
message.GetBroadcast().ContainsSensitiveData = true
|
||||
a.Publish(message)
|
||||
s.Publish(message)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -527,7 +527,7 @@ func TestPluginSync(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
defer fileReader.Close()
|
||||
|
||||
_, appErr := th.App.WriteFile(fileReader, th.App.getBundleStorePath("testplugin"))
|
||||
_, appErr := th.App.WriteFile(fileReader, getBundleStorePath("testplugin"))
|
||||
checkNoError(t, appErr)
|
||||
|
||||
appErr = th.App.SyncPlugins()
|
||||
@@ -545,7 +545,7 @@ func TestPluginSync(t *testing.T) {
|
||||
*cfg.PluginSettings.RequirePluginSignature = false
|
||||
})
|
||||
|
||||
appErr := th.App.RemoveFile(th.App.getBundleStorePath("testplugin"))
|
||||
appErr := th.App.RemoveFile(getBundleStorePath("testplugin"))
|
||||
checkNoError(t, appErr)
|
||||
|
||||
appErr = th.App.SyncPlugins()
|
||||
@@ -565,7 +565,7 @@ func TestPluginSync(t *testing.T) {
|
||||
pluginFileReader, err := os.Open(filepath.Join(path, "testplugin.tar.gz"))
|
||||
require.NoError(t, err)
|
||||
defer pluginFileReader.Close()
|
||||
_, appErr := th.App.WriteFile(pluginFileReader, th.App.getBundleStorePath("testplugin"))
|
||||
_, appErr := th.App.WriteFile(pluginFileReader, getBundleStorePath("testplugin"))
|
||||
checkNoError(t, appErr)
|
||||
|
||||
appErr = th.App.SyncPlugins()
|
||||
@@ -583,7 +583,7 @@ func TestPluginSync(t *testing.T) {
|
||||
signatureFileReader, err := os.Open(filepath.Join(path, "testplugin2.tar.gz.sig"))
|
||||
require.NoError(t, err)
|
||||
defer signatureFileReader.Close()
|
||||
_, appErr := th.App.WriteFile(signatureFileReader, th.App.getSignatureStorePath("testplugin"))
|
||||
_, appErr := th.App.WriteFile(signatureFileReader, getSignatureStorePath("testplugin"))
|
||||
checkNoError(t, appErr)
|
||||
|
||||
appErr = th.App.SyncPlugins()
|
||||
@@ -607,7 +607,7 @@ func TestPluginSync(t *testing.T) {
|
||||
signatureFileReader, err := os.Open(filepath.Join(path, "testplugin.tar.gz.sig"))
|
||||
require.NoError(t, err)
|
||||
defer signatureFileReader.Close()
|
||||
_, appErr = th.App.WriteFile(signatureFileReader, th.App.getSignatureStorePath("testplugin"))
|
||||
_, appErr = th.App.WriteFile(signatureFileReader, getSignatureStorePath("testplugin"))
|
||||
checkNoError(t, appErr)
|
||||
|
||||
appErr = th.App.SyncPlugins()
|
||||
@@ -648,7 +648,7 @@ func TestSyncPluginsActiveState(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
defer fileReader.Close()
|
||||
|
||||
_, appErr := th.App.WriteFile(fileReader, th.App.getBundleStorePath("testplugin"))
|
||||
_, appErr := th.App.WriteFile(fileReader, getBundleStorePath("testplugin"))
|
||||
checkNoError(t, appErr)
|
||||
|
||||
// Sync with file store so the plugin environment has access to this plugin.
|
||||
@@ -691,6 +691,7 @@ func TestPluginPanicLogs(t *testing.T) {
|
||||
t.Run("should panic", func(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
tearDown, _, _ := SetAppEnvironmentWithPlugins(t, []string{
|
||||
`
|
||||
package main
|
||||
@@ -713,7 +714,7 @@ func TestPluginPanicLogs(t *testing.T) {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`,
|
||||
}, th.App, th.App.NewPluginAPI)
|
||||
}, th.App, th.NewPluginAPI)
|
||||
|
||||
post := &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
@@ -721,7 +722,7 @@ func TestPluginPanicLogs(t *testing.T) {
|
||||
Message: "message_",
|
||||
CreateAt: model.GetMillis() - 10000,
|
||||
}
|
||||
_, err := th.App.CreatePost(post, th.BasicChannel, false, true)
|
||||
_, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true)
|
||||
assert.Nil(t, err)
|
||||
// We shutdown plugins first so that the read on the log buffer is race-free.
|
||||
th.App.Srv().ShutDownPlugins()
|
||||
@@ -771,7 +772,7 @@ func TestProcessPrepackagedPlugins(t *testing.T) {
|
||||
*cfg.PluginSettings.EnableRemoteMarketplace = false
|
||||
})
|
||||
|
||||
plugins := th.App.processPrepackagedPlugins(prepackagedPluginsDir)
|
||||
plugins := th.App.Srv().processPrepackagedPlugins(prepackagedPluginsDir)
|
||||
require.Len(t, plugins, 1)
|
||||
require.Equal(t, plugins[0].Manifest.Id, "testplugin")
|
||||
require.Empty(t, plugins[0].Signature, 0)
|
||||
@@ -798,7 +799,7 @@ func TestProcessPrepackagedPlugins(t *testing.T) {
|
||||
|
||||
env := th.App.GetPluginsEnvironment()
|
||||
|
||||
plugins := th.App.processPrepackagedPlugins(prepackagedPluginsDir)
|
||||
plugins := th.App.Srv().processPrepackagedPlugins(prepackagedPluginsDir)
|
||||
require.Len(t, plugins, 1)
|
||||
require.Equal(t, plugins[0].Manifest.Id, "testplugin")
|
||||
require.Empty(t, plugins[0].Signature, 0)
|
||||
@@ -831,7 +832,7 @@ func TestProcessPrepackagedPlugins(t *testing.T) {
|
||||
err = testlib.CopyFile(testPlugin2SignaturePath, filepath.Join(prepackagedPluginsDir, "testplugin2.tar.gz.sig"))
|
||||
require.NoError(t, err)
|
||||
|
||||
plugins := th.App.processPrepackagedPlugins(prepackagedPluginsDir)
|
||||
plugins := th.App.Srv().processPrepackagedPlugins(prepackagedPluginsDir)
|
||||
require.Len(t, plugins, 2)
|
||||
require.Contains(t, []string{"testplugin", "testplugin2"}, plugins[0].Manifest.Id)
|
||||
require.NotEmpty(t, plugins[0].Signature)
|
||||
@@ -880,7 +881,7 @@ func TestProcessPrepackagedPlugins(t *testing.T) {
|
||||
err = testlib.CopyFile(testPlugin2SignaturePath, filepath.Join(prepackagedPluginsDir, "testplugin2.tar.gz.sig"))
|
||||
require.NoError(t, err)
|
||||
|
||||
plugins := th.App.processPrepackagedPlugins(prepackagedPluginsDir)
|
||||
plugins := th.App.Srv().processPrepackagedPlugins(prepackagedPluginsDir)
|
||||
require.Len(t, plugins, 2)
|
||||
require.Contains(t, []string{"testplugin", "testplugin2"}, plugins[0].Manifest.Id)
|
||||
require.NotEmpty(t, plugins[0].Signature)
|
||||
@@ -917,7 +918,7 @@ func TestProcessPrepackagedPlugins(t *testing.T) {
|
||||
err = testlib.CopyFile(testPlugin2SignaturePath, filepath.Join(prepackagedPluginsDir, "testplugin2.tar.gz.sig"))
|
||||
require.NoError(t, err)
|
||||
|
||||
plugins := th.App.processPrepackagedPlugins(prepackagedPluginsDir)
|
||||
plugins := th.App.Srv().processPrepackagedPlugins(prepackagedPluginsDir)
|
||||
require.Len(t, plugins, 2)
|
||||
require.Contains(t, []string{"testplugin", "testplugin2"}, plugins[0].Manifest.Id)
|
||||
require.NotEmpty(t, plugins[0].Signature)
|
||||
|
||||
51
app/post.go
51
app/post.go
@@ -13,6 +13,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/plugin"
|
||||
"github.com/mattermost/mattermost-server/v5/services/cache"
|
||||
@@ -28,7 +29,7 @@ const (
|
||||
PageDefault = 0
|
||||
)
|
||||
|
||||
func (a *App) CreatePostAsUser(post *model.Post, currentSessionId string, setOnline bool) (*model.Post, *model.AppError) {
|
||||
func (a *App) CreatePostAsUser(c *request.Context, post *model.Post, currentSessionId string, setOnline bool) (*model.Post, *model.AppError) {
|
||||
// Check that channel has not been deleted
|
||||
channel, errCh := a.Srv().Store.Channel().Get(post.ChannelId, true)
|
||||
if errCh != nil {
|
||||
@@ -46,7 +47,7 @@ func (a *App) CreatePostAsUser(post *model.Post, currentSessionId string, setOnl
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rp, err := a.CreatePost(post, channel, true, setOnline)
|
||||
rp, err := a.CreatePost(c, post, channel, true, setOnline)
|
||||
if err != nil {
|
||||
if err.Id == "api.post.create_post.root_id.app_error" ||
|
||||
err.Id == "api.post.create_post.channel_root_id.app_error" ||
|
||||
@@ -100,7 +101,7 @@ func (a *App) CreatePostAsUser(post *model.Post, currentSessionId string, setOnl
|
||||
return rp, nil
|
||||
}
|
||||
|
||||
func (a *App) CreatePostMissingChannel(post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) {
|
||||
func (a *App) CreatePostMissingChannel(c *request.Context, post *model.Post, triggerWebhooks bool) (*model.Post, *model.AppError) {
|
||||
channel, err := a.Srv().Store.Channel().Get(post.ChannelId, true)
|
||||
if err != nil {
|
||||
var nfErr *store.ErrNotFound
|
||||
@@ -112,7 +113,7 @@ func (a *App) CreatePostMissingChannel(post *model.Post, triggerWebhooks bool) (
|
||||
}
|
||||
}
|
||||
|
||||
return a.CreatePost(post, channel, triggerWebhooks, true)
|
||||
return a.CreatePost(c, post, channel, triggerWebhooks, true)
|
||||
}
|
||||
|
||||
// deduplicateCreatePost attempts to make posting idempotent within a caching window.
|
||||
@@ -157,7 +158,7 @@ func (a *App) deduplicateCreatePost(post *model.Post) (foundPost *model.Post, er
|
||||
return actualPost, nil
|
||||
}
|
||||
|
||||
func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhooks, setOnline bool) (savedPost *model.Post, err *model.AppError) {
|
||||
func (a *App) CreatePost(c *request.Context, post *model.Post, channel *model.Channel, triggerWebhooks, setOnline bool) (savedPost *model.Post, err *model.AppError) {
|
||||
foundPost, err := a.deduplicateCreatePost(post)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -281,7 +282,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo
|
||||
|
||||
if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil {
|
||||
var rejectionError *model.AppError
|
||||
pluginContext := a.PluginContext()
|
||||
pluginContext := pluginContext(c)
|
||||
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
|
||||
replacementPost, rejectionReason := hooks.MessageWillBePosted(pluginContext, post)
|
||||
if rejectionReason != "" {
|
||||
@@ -326,7 +327,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo
|
||||
rPostCopy := rpost.Clone()
|
||||
if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil {
|
||||
a.Srv().Go(func() {
|
||||
pluginContext := a.PluginContext()
|
||||
pluginContext := pluginContext(c)
|
||||
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
|
||||
hooks.MessageHasBeenPosted(pluginContext, rPostCopy)
|
||||
return true
|
||||
@@ -352,7 +353,7 @@ func (a *App) CreatePost(post *model.Post, channel *model.Channel, triggerWebhoo
|
||||
// to be done when we send the post over the websocket in handlePostEvents
|
||||
rpost = a.PreparePostForClient(rpost, true, false)
|
||||
|
||||
if err := a.handlePostEvents(rpost, user, channel, triggerWebhooks, parentPostList, setOnline); err != nil {
|
||||
if err := a.handlePostEvents(c, rpost, user, channel, triggerWebhooks, parentPostList, setOnline); err != nil {
|
||||
mlog.Warn("Failed to handle post events", mlog.Err(err))
|
||||
}
|
||||
|
||||
@@ -439,7 +440,7 @@ func (a *App) FillInPostProps(post *model.Post, channel *model.Channel) *model.A
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) handlePostEvents(post *model.Post, user *model.User, channel *model.Channel, triggerWebhooks bool, parentPostList *model.PostList, setOnline bool) error {
|
||||
func (a *App) handlePostEvents(c *request.Context, post *model.Post, user *model.User, channel *model.Channel, triggerWebhooks bool, parentPostList *model.PostList, setOnline bool) error {
|
||||
var team *model.Team
|
||||
if channel.TeamId != "" {
|
||||
t, err := a.Srv().Store.Team().Get(channel.TeamId)
|
||||
@@ -461,7 +462,7 @@ func (a *App) handlePostEvents(post *model.Post, user *model.User, channel *mode
|
||||
|
||||
if post.Type != model.POST_AUTO_RESPONDER { // don't respond to an auto-responder
|
||||
a.Srv().Go(func() {
|
||||
_, err := a.SendAutoResponseIfNecessary(channel, user, post)
|
||||
_, err := a.SendAutoResponseIfNecessary(c, channel, user, post)
|
||||
if err != nil {
|
||||
mlog.Error("Failed to send auto response", mlog.String("user_id", user.Id), mlog.String("post_id", post.Id), mlog.Err(err))
|
||||
}
|
||||
@@ -470,7 +471,7 @@ func (a *App) handlePostEvents(post *model.Post, user *model.User, channel *mode
|
||||
|
||||
if triggerWebhooks {
|
||||
a.Srv().Go(func() {
|
||||
if err := a.handleWebhookEvents(post, team, channel, user); err != nil {
|
||||
if err := a.handleWebhookEvents(c, post, team, channel, user); err != nil {
|
||||
mlog.Error(err.Error())
|
||||
}
|
||||
})
|
||||
@@ -535,7 +536,7 @@ func (a *App) DeleteEphemeralPost(userID, postID string) {
|
||||
a.Publish(message)
|
||||
}
|
||||
|
||||
func (a *App) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model.AppError) {
|
||||
func (a *App) UpdatePost(c *request.Context, post *model.Post, safeUpdate bool) (*model.Post, *model.AppError) {
|
||||
post.SanitizeProps()
|
||||
|
||||
postLists, nErr := a.Srv().Store.Post().Get(context.Background(), post.Id, false, false, false, "")
|
||||
@@ -615,7 +616,7 @@ func (a *App) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model
|
||||
|
||||
if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil {
|
||||
var rejectionReason string
|
||||
pluginContext := a.PluginContext()
|
||||
pluginContext := pluginContext(c)
|
||||
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
|
||||
newPost, rejectionReason = hooks.MessageWillBeUpdated(pluginContext, newPost, oldPost)
|
||||
return post != nil
|
||||
@@ -638,7 +639,7 @@ func (a *App) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model
|
||||
|
||||
if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil {
|
||||
a.Srv().Go(func() {
|
||||
pluginContext := a.PluginContext()
|
||||
pluginContext := pluginContext(c)
|
||||
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
|
||||
hooks.MessageHasBeenUpdated(pluginContext, newPost, oldPost)
|
||||
return true
|
||||
@@ -657,7 +658,7 @@ func (a *App) UpdatePost(post *model.Post, safeUpdate bool) (*model.Post, *model
|
||||
return rpost, nil
|
||||
}
|
||||
|
||||
func (a *App) PatchPost(postID string, patch *model.PostPatch) (*model.Post, *model.AppError) {
|
||||
func (a *App) PatchPost(c *request.Context, postID string, patch *model.PostPatch) (*model.Post, *model.AppError) {
|
||||
post, err := a.GetSinglePost(postID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -679,7 +680,7 @@ func (a *App) PatchPost(postID string, patch *model.PostPatch) (*model.Post, *mo
|
||||
|
||||
post.Patch(patch)
|
||||
|
||||
updatedPost, err := a.UpdatePost(post, false)
|
||||
updatedPost, err := a.UpdatePost(c, post, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -790,7 +791,7 @@ func (a *App) GetFlaggedPostsForChannel(userID, channelID string, offset int, li
|
||||
return postList, nil
|
||||
}
|
||||
|
||||
func (a *App) GetPermalinkPost(postID string, userID string) (*model.PostList, *model.AppError) {
|
||||
func (a *App) GetPermalinkPost(c *request.Context, postID string, userID string) (*model.PostList, *model.AppError) {
|
||||
list, nErr := a.Srv().Store.Post().Get(context.Background(), postID, false, false, false, userID)
|
||||
if nErr != nil {
|
||||
var nfErr *store.ErrNotFound
|
||||
@@ -815,7 +816,7 @@ func (a *App) GetPermalinkPost(postID string, userID string) (*model.PostList, *
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err = a.JoinChannel(channel, userID); err != nil {
|
||||
if err = a.JoinChannel(c, channel, userID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -1082,7 +1083,7 @@ func (a *App) DeletePostFiles(post *model.Post) {
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) parseAndFetchChannelIdByNameFromInFilter(channelName, userID, teamID string, includeDeleted bool) (*model.Channel, error) {
|
||||
func (a *App) parseAndFetchChannelIdByNameFromInFilter(c *request.Context, channelName, userID, teamID string, includeDeleted bool) (*model.Channel, error) {
|
||||
if strings.HasPrefix(channelName, "@") && strings.Contains(channelName, ",") {
|
||||
var userIDs []string
|
||||
users, err := a.GetUsersByUsernames(strings.Split(channelName[1:], ","), false, nil)
|
||||
@@ -1105,7 +1106,7 @@ func (a *App) parseAndFetchChannelIdByNameFromInFilter(channelName, userID, team
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
channel, err := a.GetOrCreateDirectChannel(userID, user.Id)
|
||||
channel, err := a.GetOrCreateDirectChannel(c, userID, user.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1156,9 +1157,9 @@ func (a *App) searchPostsInTeam(teamID string, userID string, paramsList []*mode
|
||||
return posts, nil
|
||||
}
|
||||
|
||||
func (a *App) convertChannelNamesToChannelIds(channels []string, userID string, teamID string, includeDeletedChannels bool) []string {
|
||||
func (a *App) convertChannelNamesToChannelIds(c *request.Context, channels []string, userID string, teamID string, includeDeletedChannels bool) []string {
|
||||
for idx, channelName := range channels {
|
||||
channel, err := a.parseAndFetchChannelIdByNameFromInFilter(channelName, userID, teamID, includeDeletedChannels)
|
||||
channel, err := a.parseAndFetchChannelIdByNameFromInFilter(c, channelName, userID, teamID, includeDeletedChannels)
|
||||
if err != nil {
|
||||
mlog.Warn("error getting channel id by name from in filter", mlog.Err(err))
|
||||
continue
|
||||
@@ -1189,7 +1190,7 @@ func (a *App) SearchPostsInTeam(teamID string, paramsList []*model.SearchParams)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) SearchPostsInTeamForUser(terms string, userID string, teamID string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int) (*model.PostSearchResults, *model.AppError) {
|
||||
func (a *App) SearchPostsInTeamForUser(c *request.Context, terms string, userID string, teamID string, isOrSearch bool, includeDeletedChannels bool, timeZoneOffset int, page, perPage int) (*model.PostSearchResults, *model.AppError) {
|
||||
var postSearchResults *model.PostSearchResults
|
||||
paramsList := model.ParseSearchParams(strings.TrimSpace(terms), timeZoneOffset)
|
||||
includeDeleted := includeDeletedChannels && *a.Config().TeamSettings.ExperimentalViewArchivedChannels
|
||||
@@ -1206,8 +1207,8 @@ func (a *App) SearchPostsInTeamForUser(terms string, userID string, teamID strin
|
||||
// Don't allow users to search for "*"
|
||||
if params.Terms != "*" {
|
||||
// Convert channel names to channel IDs
|
||||
params.InChannels = a.convertChannelNamesToChannelIds(params.InChannels, userID, teamID, includeDeletedChannels)
|
||||
params.ExcludedChannels = a.convertChannelNamesToChannelIds(params.ExcludedChannels, userID, teamID, includeDeletedChannels)
|
||||
params.InChannels = a.convertChannelNamesToChannelIds(c, params.InChannels, userID, teamID, includeDeletedChannels)
|
||||
params.ExcludedChannels = a.convertChannelNamesToChannelIds(c, params.ExcludedChannels, userID, teamID, includeDeletedChannels)
|
||||
|
||||
// Convert usernames to user IDs
|
||||
params.FromUsers = a.convertUserNameToUserIds(params.FromUsers)
|
||||
|
||||
@@ -36,9 +36,9 @@ var linkCache = cache.NewLRU(cache.LRUOptions{
|
||||
Size: LinkCacheSize,
|
||||
})
|
||||
|
||||
func (a *App) InitPostMetadata() {
|
||||
func (s *Server) initPostMetadata() {
|
||||
// Dump any cached links if the proxy settings have changed so image URLs can be updated
|
||||
a.AddConfigListener(func(before, after *model.Config) {
|
||||
s.AddConfigListener(func(before, after *model.Config) {
|
||||
if (before.ImageProxySettings.Enable != after.ImageProxySettings.Enable) ||
|
||||
(before.ImageProxySettings.ImageProxyType != after.ImageProxySettings.ImageProxyType) ||
|
||||
(before.ImageProxySettings.RemoteImageProxyURL != after.ImageProxySettings.RemoteImageProxyURL) ||
|
||||
|
||||
@@ -176,11 +176,11 @@ func TestPreparePostForClient(t *testing.T) {
|
||||
th := setup(t)
|
||||
defer th.TearDown()
|
||||
|
||||
fileInfo, err := th.App.DoUploadFile(time.Now(), th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, "test.txt", []byte("test"))
|
||||
fileInfo, err := th.App.DoUploadFile(th.Context, time.Now(), th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, "test.txt", []byte("test"))
|
||||
fileInfo.Content = "test"
|
||||
require.Nil(t, err)
|
||||
|
||||
post, err := th.App.CreatePost(&model.Post{
|
||||
post, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
FileIds: []string{fileInfo.Id},
|
||||
@@ -204,7 +204,7 @@ func TestPreparePostForClient(t *testing.T) {
|
||||
|
||||
emoji := th.CreateEmoji()
|
||||
|
||||
post, err := th.App.CreatePost(&model.Post{
|
||||
post, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: ":" + emoji.Name + ": :taco:",
|
||||
@@ -248,7 +248,7 @@ func TestPreparePostForClient(t *testing.T) {
|
||||
emoji3 := th.CreateEmoji()
|
||||
emoji4 := th.CreateEmoji()
|
||||
|
||||
post, err := th.App.CreatePost(&model.Post{
|
||||
post, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: ":" + emoji3.Name + ": :taco:",
|
||||
@@ -289,7 +289,7 @@ func TestPreparePostForClient(t *testing.T) {
|
||||
*cfg.ServiceSettings.EnablePostIconOverride = override
|
||||
})
|
||||
|
||||
post, err := th.App.CreatePost(&model.Post{
|
||||
post, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "Test",
|
||||
@@ -347,7 +347,7 @@ func TestPreparePostForClient(t *testing.T) {
|
||||
th := setup(t)
|
||||
defer th.TearDown()
|
||||
|
||||
post, err := th.App.CreatePost(&model.Post{
|
||||
post, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: fmt.Sprintf("This is  and ", server.URL, server.URL),
|
||||
@@ -376,7 +376,7 @@ func TestPreparePostForClient(t *testing.T) {
|
||||
th := setup(t)
|
||||
defer th.TearDown()
|
||||
|
||||
post, err := th.App.CreatePost(&model.Post{
|
||||
post, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "some post",
|
||||
@@ -409,7 +409,7 @@ func TestPreparePostForClient(t *testing.T) {
|
||||
th := setup(t)
|
||||
defer th.TearDown()
|
||||
|
||||
post, err := th.App.CreatePost(&model.Post{
|
||||
post, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: `This is our logo: ` + server.URL + `/test-image2.png
|
||||
@@ -445,7 +445,7 @@ func TestPreparePostForClient(t *testing.T) {
|
||||
th := setup(t)
|
||||
defer th.TearDown()
|
||||
|
||||
post, err := th.App.CreatePost(&model.Post{
|
||||
post, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: `This is our web page: ` + server.URL,
|
||||
@@ -482,7 +482,7 @@ func TestPreparePostForClient(t *testing.T) {
|
||||
th := setup(t)
|
||||
defer th.TearDown()
|
||||
|
||||
post, err := th.App.CreatePost(&model.Post{
|
||||
post, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Props: map[string]interface{}{
|
||||
@@ -520,10 +520,10 @@ func TestPreparePostForClient(t *testing.T) {
|
||||
th := setup(t)
|
||||
defer th.TearDown()
|
||||
|
||||
fileInfo, err := th.App.DoUploadFile(time.Now(), th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, "test.txt", []byte("test"))
|
||||
fileInfo, err := th.App.DoUploadFile(th.Context, time.Now(), th.BasicTeam.Id, th.BasicChannel.Id, th.BasicUser.Id, "test.txt", []byte("test"))
|
||||
require.Nil(t, err)
|
||||
|
||||
post, err := th.App.CreatePost(&model.Post{
|
||||
post, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
Message: "test",
|
||||
FileIds: []string{fileInfo.Id},
|
||||
UserId: th.BasicUser.Id,
|
||||
@@ -633,7 +633,7 @@ func testProxyOpenGraphImage(t *testing.T, th *TestHelper, shouldProxy bool) {
|
||||
serverURL = server.URL
|
||||
defer server.Close()
|
||||
|
||||
post, err := th.App.CreatePost(&model.Post{
|
||||
post, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: `This is our web page: ` + server.URL,
|
||||
|
||||
272
app/post_test.go
272
app/post_test.go
@@ -31,7 +31,7 @@ func TestCreatePostDeduplicate(t *testing.T) {
|
||||
|
||||
t.Run("duplicate create post is idempotent", func(t *testing.T) {
|
||||
pendingPostId := model.NewId()
|
||||
post, err := th.App.CreatePostAsUser(&model.Post{
|
||||
post, err := th.App.CreatePostAsUser(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "message",
|
||||
@@ -40,7 +40,7 @@ func TestCreatePostDeduplicate(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
require.Equal(t, "message", post.Message)
|
||||
|
||||
duplicatePost, err := th.App.CreatePostAsUser(&model.Post{
|
||||
duplicatePost, err := th.App.CreatePostAsUser(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "message",
|
||||
@@ -77,10 +77,10 @@ func TestCreatePostDeduplicate(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`, `{"id": "testrejectfirstpost", "backend": {"executable": "backend.exe"}}`, "testrejectfirstpost", th.App)
|
||||
`, `{"id": "testrejectfirstpost", "backend": {"executable": "backend.exe"}}`, "testrejectfirstpost", th.App, th.Context)
|
||||
|
||||
pendingPostId := model.NewId()
|
||||
post, err := th.App.CreatePostAsUser(&model.Post{
|
||||
post, err := th.App.CreatePostAsUser(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "message",
|
||||
@@ -90,7 +90,7 @@ func TestCreatePostDeduplicate(t *testing.T) {
|
||||
require.Equal(t, "Post rejected by plugin. rejected", err.Id)
|
||||
require.Nil(t, post)
|
||||
|
||||
duplicatePost, err := th.App.CreatePostAsUser(&model.Post{
|
||||
duplicatePost, err := th.App.CreatePostAsUser(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "message",
|
||||
@@ -127,7 +127,7 @@ func TestCreatePostDeduplicate(t *testing.T) {
|
||||
func main() {
|
||||
plugin.ClientMain(&MyPlugin{})
|
||||
}
|
||||
`, `{"id": "testdelayfirstpost", "backend": {"executable": "backend.exe"}}`, "testdelayfirstpost", th.App)
|
||||
`, `{"id": "testdelayfirstpost", "backend": {"executable": "backend.exe"}}`, "testdelayfirstpost", th.App, th.Context)
|
||||
|
||||
var post *model.Post
|
||||
pendingPostId := model.NewId()
|
||||
@@ -140,7 +140,7 @@ func TestCreatePostDeduplicate(t *testing.T) {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
var appErr *model.AppError
|
||||
post, appErr = th.App.CreatePostAsUser(&model.Post{
|
||||
post, appErr = th.App.CreatePostAsUser(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "plugin delayed",
|
||||
@@ -154,7 +154,7 @@ func TestCreatePostDeduplicate(t *testing.T) {
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
// Try creating a duplicate post
|
||||
duplicatePost, err := th.App.CreatePostAsUser(&model.Post{
|
||||
duplicatePost, err := th.App.CreatePostAsUser(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "plugin delayed",
|
||||
@@ -170,7 +170,7 @@ func TestCreatePostDeduplicate(t *testing.T) {
|
||||
|
||||
t.Run("duplicate create post after cache expires is not idempotent", func(t *testing.T) {
|
||||
pendingPostId := model.NewId()
|
||||
post, err := th.App.CreatePostAsUser(&model.Post{
|
||||
post, err := th.App.CreatePostAsUser(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "message",
|
||||
@@ -181,7 +181,7 @@ func TestCreatePostDeduplicate(t *testing.T) {
|
||||
|
||||
time.Sleep(PendingPostIDsCacheTTL)
|
||||
|
||||
duplicatePost, err := th.App.CreatePostAsUser(&model.Post{
|
||||
duplicatePost, err := th.App.CreatePostAsUser(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "message",
|
||||
@@ -263,7 +263,7 @@ func TestUpdatePostEditAt(t *testing.T) {
|
||||
post := th.BasicPost.Clone()
|
||||
|
||||
post.IsPinned = true
|
||||
saved, err := th.App.UpdatePost(post, true)
|
||||
saved, err := th.App.UpdatePost(th.Context, post, true)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, saved.EditAt, post.EditAt, "shouldn't have updated post.EditAt when pinning post")
|
||||
post = saved.Clone()
|
||||
@@ -271,7 +271,7 @@ func TestUpdatePostEditAt(t *testing.T) {
|
||||
time.Sleep(time.Millisecond * 100)
|
||||
|
||||
post.Message = model.NewId()
|
||||
saved, err = th.App.UpdatePost(post, true)
|
||||
saved, err = th.App.UpdatePost(th.Context, post, true)
|
||||
require.Nil(t, err)
|
||||
assert.NotEqual(t, saved.EditAt, post.EditAt, "should have updated post.EditAt when updating post message")
|
||||
|
||||
@@ -289,7 +289,7 @@ func TestUpdatePostTimeLimit(t *testing.T) {
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.ServiceSettings.PostEditTimeLimit = -1
|
||||
})
|
||||
_, err := th.App.UpdatePost(post, true)
|
||||
_, err := th.App.UpdatePost(th.Context, post, true)
|
||||
require.Nil(t, err)
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
@@ -297,14 +297,14 @@ func TestUpdatePostTimeLimit(t *testing.T) {
|
||||
})
|
||||
post.Message = model.NewId()
|
||||
|
||||
_, err = th.App.UpdatePost(post, true)
|
||||
_, err = th.App.UpdatePost(th.Context, post, true)
|
||||
require.Nil(t, err, "should allow you to edit the post")
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.ServiceSettings.PostEditTimeLimit = 1
|
||||
})
|
||||
post.Message = model.NewId()
|
||||
_, err = th.App.UpdatePost(post, true)
|
||||
_, err = th.App.UpdatePost(th.Context, post, true)
|
||||
require.NotNil(t, err, "should fail on update old post")
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
@@ -318,9 +318,9 @@ func TestUpdatePostInArchivedChannel(t *testing.T) {
|
||||
|
||||
archivedChannel := th.CreateChannel(th.BasicTeam)
|
||||
post := th.CreatePost(archivedChannel)
|
||||
th.App.DeleteChannel(archivedChannel, "")
|
||||
th.App.DeleteChannel(th.Context, archivedChannel, "")
|
||||
|
||||
_, err := th.App.UpdatePost(post, true)
|
||||
_, err := th.App.UpdatePost(th.Context, post, true)
|
||||
require.NotNil(t, err)
|
||||
require.Equal(t, "api.post.update_post.can_not_update_post_in_deleted.error", err.Id)
|
||||
}
|
||||
@@ -339,7 +339,7 @@ func TestPostReplyToPostWhereRootPosterLeftChannel(t *testing.T) {
|
||||
_, err := th.App.AddUserToChannel(userInChannel, channel, false)
|
||||
require.Nil(t, err)
|
||||
|
||||
err = th.App.RemoveUserFromChannel(userNotInChannel.Id, "", channel)
|
||||
err = th.App.RemoveUserFromChannel(th.Context, userNotInChannel.Id, "", channel)
|
||||
require.Nil(t, err)
|
||||
replyPost := model.Post{
|
||||
Message: "asd",
|
||||
@@ -351,7 +351,7 @@ func TestPostReplyToPostWhereRootPosterLeftChannel(t *testing.T) {
|
||||
CreateAt: 0,
|
||||
}
|
||||
|
||||
_, err = th.App.CreatePostAsUser(&replyPost, "", true)
|
||||
_, err = th.App.CreatePostAsUser(th.Context, &replyPost, "", true)
|
||||
require.Nil(t, err)
|
||||
}
|
||||
|
||||
@@ -373,7 +373,7 @@ func TestPostAttachPostToChildPost(t *testing.T) {
|
||||
CreateAt: 0,
|
||||
}
|
||||
|
||||
res1, err := th.App.CreatePostAsUser(&replyPost1, "", true)
|
||||
res1, err := th.App.CreatePostAsUser(th.Context, &replyPost1, "", true)
|
||||
require.Nil(t, err)
|
||||
|
||||
replyPost2 := model.Post{
|
||||
@@ -386,7 +386,7 @@ func TestPostAttachPostToChildPost(t *testing.T) {
|
||||
CreateAt: 0,
|
||||
}
|
||||
|
||||
_, err = th.App.CreatePostAsUser(&replyPost2, "", true)
|
||||
_, err = th.App.CreatePostAsUser(th.Context, &replyPost2, "", true)
|
||||
assert.Equalf(t, err.StatusCode, http.StatusBadRequest, "Expected BadRequest error, got %v", err)
|
||||
|
||||
replyPost3 := model.Post{
|
||||
@@ -399,7 +399,7 @@ func TestPostAttachPostToChildPost(t *testing.T) {
|
||||
CreateAt: 0,
|
||||
}
|
||||
|
||||
_, err = th.App.CreatePostAsUser(&replyPost3, "", true)
|
||||
_, err = th.App.CreatePostAsUser(th.Context, &replyPost3, "", true)
|
||||
assert.Nil(t, err)
|
||||
}
|
||||
|
||||
@@ -410,7 +410,7 @@ func TestPostChannelMentions(t *testing.T) {
|
||||
channel := th.BasicChannel
|
||||
user := th.BasicUser
|
||||
|
||||
channelToMention, err := th.App.CreateChannel(&model.Channel{
|
||||
channelToMention, err := th.App.CreateChannel(th.Context, &model.Channel{
|
||||
DisplayName: "Mention Test",
|
||||
Name: "mention-test",
|
||||
Type: model.CHANNEL_OPEN,
|
||||
@@ -430,7 +430,7 @@ func TestPostChannelMentions(t *testing.T) {
|
||||
CreateAt: 0,
|
||||
}
|
||||
|
||||
result, err := th.App.CreatePostAsUser(post, "", true)
|
||||
result, err := th.App.CreatePostAsUser(th.Context, post, "", true)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, map[string]interface{}{
|
||||
"mention-test": map[string]interface{}{
|
||||
@@ -440,7 +440,7 @@ func TestPostChannelMentions(t *testing.T) {
|
||||
}, result.GetProp("channel_mentions"))
|
||||
|
||||
post.Message = fmt.Sprintf("goodbye, ~%v!", channelToMention.Name)
|
||||
result, err = th.App.UpdatePost(post, false)
|
||||
result, err = th.App.UpdatePost(th.Context, post, false)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, map[string]interface{}{
|
||||
"mention-test": map[string]interface{}{
|
||||
@@ -630,7 +630,7 @@ func TestDeletePostWithFileAttachments(t *testing.T) {
|
||||
filename := "test"
|
||||
data := []byte("abcd")
|
||||
|
||||
info1, err := th.App.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data)
|
||||
info1, err := th.App.DoUploadFile(th.Context, time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamID, channelID, userID, filename, data)
|
||||
require.Nil(t, err)
|
||||
defer func() {
|
||||
th.App.Srv().Store.FileInfo().PermanentDelete(info1.Id)
|
||||
@@ -646,7 +646,7 @@ func TestDeletePostWithFileAttachments(t *testing.T) {
|
||||
FileIds: []string{info1.Id},
|
||||
}
|
||||
|
||||
post, err = th.App.CreatePost(post, th.BasicChannel, false, true)
|
||||
post, err = th.App.CreatePost(th.Context, post, th.BasicChannel, false, true)
|
||||
assert.Nil(t, err)
|
||||
|
||||
// Delete the post.
|
||||
@@ -667,7 +667,7 @@ func TestDeletePostInArchivedChannel(t *testing.T) {
|
||||
|
||||
archivedChannel := th.CreateChannel(th.BasicTeam)
|
||||
post := th.CreatePost(archivedChannel)
|
||||
th.App.DeleteChannel(archivedChannel, "")
|
||||
th.App.DeleteChannel(th.Context, archivedChannel, "")
|
||||
|
||||
_, err := th.App.DeletePost(post.Id, "")
|
||||
require.NotNil(t, err)
|
||||
@@ -698,7 +698,7 @@ func TestCreatePost(t *testing.T) {
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
rpost, err := th.App.CreatePost(post, th.BasicChannel, false, true)
|
||||
rpost, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, "", rpost.Message)
|
||||
})
|
||||
@@ -714,7 +714,7 @@ func TestCreatePost(t *testing.T) {
|
||||
Message: "This post does not have mentions",
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
rpost, err := th.App.CreatePost(postWithNoMention, th.BasicChannel, false, true)
|
||||
rpost, err := th.App.CreatePost(th.Context, postWithNoMention, th.BasicChannel, false, true)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, rpost.GetProps(), model.StringInterface{})
|
||||
|
||||
@@ -723,7 +723,7 @@ func TestCreatePost(t *testing.T) {
|
||||
Message: "This post has @here mention @all",
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
rpost, err = th.App.CreatePost(postWithMention, th.BasicChannel, false, true)
|
||||
rpost, err = th.App.CreatePost(th.Context, postWithMention, th.BasicChannel, false, true)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, rpost.GetProps(), model.StringInterface{})
|
||||
})
|
||||
@@ -737,7 +737,7 @@ func TestCreatePost(t *testing.T) {
|
||||
Message: "This post does not have mentions",
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
rpost, err := th.App.CreatePost(postWithNoMention, th.BasicChannel, false, true)
|
||||
rpost, err := th.App.CreatePost(th.Context, postWithNoMention, th.BasicChannel, false, true)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, rpost.GetProps(), model.StringInterface{})
|
||||
|
||||
@@ -746,7 +746,7 @@ func TestCreatePost(t *testing.T) {
|
||||
Message: "This post has @here mention @all",
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
rpost, err = th.App.CreatePost(postWithMention, th.BasicChannel, false, true)
|
||||
rpost, err = th.App.CreatePost(th.Context, postWithMention, th.BasicChannel, false, true)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, rpost.GetProp(model.POST_PROPS_MENTION_HIGHLIGHT_DISABLED), true)
|
||||
|
||||
@@ -780,7 +780,7 @@ func TestPatchPost(t *testing.T) {
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
rpost, err := th.App.CreatePost(post, th.BasicChannel, false, true)
|
||||
rpost, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true)
|
||||
require.Nil(t, err)
|
||||
assert.NotEqual(t, "", rpost.Message)
|
||||
|
||||
@@ -788,7 +788,7 @@ func TestPatchPost(t *testing.T) {
|
||||
Message: model.NewString(""),
|
||||
}
|
||||
|
||||
rpost, err = th.App.PatchPost(rpost.Id, patch)
|
||||
rpost, err = th.App.PatchPost(th.Context, rpost.Id, patch)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, "", rpost.Message)
|
||||
})
|
||||
@@ -805,19 +805,19 @@ func TestPatchPost(t *testing.T) {
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
rpost, err := th.App.CreatePost(post, th.BasicChannel, false, true)
|
||||
rpost, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true)
|
||||
require.Nil(t, err)
|
||||
|
||||
t.Run("Does not set prop when user has USE_CHANNEL_MENTIONS", func(t *testing.T) {
|
||||
patchWithNoMention := &model.PostPatch{Message: model.NewString("This patch has no channel mention")}
|
||||
|
||||
rpost, err = th.App.PatchPost(rpost.Id, patchWithNoMention)
|
||||
rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithNoMention)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, rpost.GetProps(), model.StringInterface{})
|
||||
|
||||
patchWithMention := &model.PostPatch{Message: model.NewString("This patch has a mention now @here")}
|
||||
|
||||
rpost, err = th.App.PatchPost(rpost.Id, patchWithMention)
|
||||
rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithMention)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, rpost.GetProps(), model.StringInterface{})
|
||||
})
|
||||
@@ -827,13 +827,13 @@ func TestPatchPost(t *testing.T) {
|
||||
th.RemovePermissionFromRole(model.PERMISSION_USE_CHANNEL_MENTIONS.Id, model.CHANNEL_ADMIN_ROLE_ID)
|
||||
|
||||
patchWithNoMention := &model.PostPatch{Message: model.NewString("This patch still does not have a mention")}
|
||||
rpost, err = th.App.PatchPost(rpost.Id, patchWithNoMention)
|
||||
rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithNoMention)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, rpost.GetProps(), model.StringInterface{})
|
||||
|
||||
patchWithMention := &model.PostPatch{Message: model.NewString("This patch has a mention now @here")}
|
||||
|
||||
rpost, err = th.App.PatchPost(rpost.Id, patchWithMention)
|
||||
rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithMention)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, rpost.GetProp(model.POST_PROPS_MENTION_HIGHLIGHT_DISABLED), true)
|
||||
|
||||
@@ -858,7 +858,7 @@ func TestCreatePostAsUser(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
time.Sleep(1 * time.Millisecond)
|
||||
_, appErr := th.App.CreatePostAsUser(post, "", true)
|
||||
_, appErr := th.App.CreatePostAsUser(th.Context, post, "", true)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
channelMemberAfter, err := th.App.Srv().Store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id)
|
||||
@@ -882,7 +882,7 @@ func TestCreatePostAsUser(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
time.Sleep(1 * time.Millisecond)
|
||||
_, appErr := th.App.CreatePostAsUser(post, "", true)
|
||||
_, appErr := th.App.CreatePostAsUser(th.Context, post, "", true)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
channelMemberAfter, err := th.App.Srv().Store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id)
|
||||
@@ -913,7 +913,7 @@ func TestCreatePostAsUser(t *testing.T) {
|
||||
require.NoError(t, nErr)
|
||||
|
||||
time.Sleep(1 * time.Millisecond)
|
||||
_, appErr = th.App.CreatePostAsUser(post, "", true)
|
||||
_, appErr = th.App.CreatePostAsUser(th.Context, post, "", true)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
channelMemberAfter, nErr := th.App.Srv().Store.Channel().GetMember(context.Background(), th.BasicChannel.Id, th.BasicUser.Id)
|
||||
@@ -935,7 +935,7 @@ func TestCreatePostAsUser(t *testing.T) {
|
||||
UserId: user.Id,
|
||||
}
|
||||
|
||||
_, appErr := th.App.CreatePostAsUser(post, "", true)
|
||||
_, appErr := th.App.CreatePostAsUser(th.Context, post, "", true)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
testlib.AssertLog(t, th.LogBuffer, mlog.LevelWarn, "Failed to get membership")
|
||||
@@ -958,7 +958,7 @@ func TestCreatePostAsUser(t *testing.T) {
|
||||
UserId: bot.UserId,
|
||||
}
|
||||
|
||||
_, appErr = th.App.CreatePostAsUser(post, "", true)
|
||||
_, appErr = th.App.CreatePostAsUser(th.Context, post, "", true)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
testlib.AssertNoLog(t, th.LogBuffer, mlog.LevelWarn, "Failed to get membership")
|
||||
@@ -971,9 +971,9 @@ func TestPatchPostInArchivedChannel(t *testing.T) {
|
||||
|
||||
archivedChannel := th.CreateChannel(th.BasicTeam)
|
||||
post := th.CreatePost(archivedChannel)
|
||||
th.App.DeleteChannel(archivedChannel, "")
|
||||
th.App.DeleteChannel(th.Context, archivedChannel, "")
|
||||
|
||||
_, err := th.App.PatchPost(post.Id, &model.PostPatch{IsPinned: model.NewBool(true)})
|
||||
_, err := th.App.PatchPost(th.Context, post.Id, &model.PostPatch{IsPinned: model.NewBool(true)})
|
||||
require.NotNil(t, err)
|
||||
require.Equal(t, "api.post.patch_post.can_not_update_post_in_deleted.error", err.Id)
|
||||
}
|
||||
@@ -1002,14 +1002,14 @@ func TestUpdatePost(t *testing.T) {
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
rpost, err := th.App.CreatePost(post, th.BasicChannel, false, true)
|
||||
rpost, err := th.App.CreatePost(th.Context, post, th.BasicChannel, false, true)
|
||||
require.Nil(t, err)
|
||||
assert.NotEqual(t, "", rpost.Message)
|
||||
|
||||
post.Id = rpost.Id
|
||||
post.Message = ""
|
||||
|
||||
rpost, err = th.App.UpdatePost(post, false)
|
||||
rpost, err = th.App.UpdatePost(th.Context, post, false)
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, "", rpost.Message)
|
||||
})
|
||||
@@ -1024,7 +1024,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) {
|
||||
|
||||
posts := make([]*model.Post, 7)
|
||||
for i := 0; i < cap(posts); i++ {
|
||||
post, err := th.App.CreatePost(&model.Post{
|
||||
post, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: searchTerm,
|
||||
@@ -1057,7 +1057,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) {
|
||||
|
||||
page := 0
|
||||
|
||||
results, err := th.App.SearchPostsInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
results, err := th.App.SearchPostsInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, []string{
|
||||
@@ -1077,7 +1077,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) {
|
||||
|
||||
page := 1
|
||||
|
||||
results, err := th.App.SearchPostsInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
results, err := th.App.SearchPostsInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, []string{}, results.Order)
|
||||
@@ -1107,7 +1107,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) {
|
||||
th.App.Srv().SearchEngine.ElasticsearchEngine = nil
|
||||
}()
|
||||
|
||||
results, err := th.App.SearchPostsInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
results, err := th.App.SearchPostsInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, resultsPage, results.Order)
|
||||
@@ -1135,7 +1135,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) {
|
||||
th.App.Srv().SearchEngine.ElasticsearchEngine = nil
|
||||
}()
|
||||
|
||||
results, err := th.App.SearchPostsInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
results, err := th.App.SearchPostsInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, resultsPage, results.Order)
|
||||
@@ -1159,7 +1159,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) {
|
||||
th.App.Srv().SearchEngine.ElasticsearchEngine = nil
|
||||
}()
|
||||
|
||||
results, err := th.App.SearchPostsInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
results, err := th.App.SearchPostsInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, []string{
|
||||
@@ -1191,7 +1191,7 @@ func TestSearchPostsInTeamForUser(t *testing.T) {
|
||||
th.App.Srv().SearchEngine.ElasticsearchEngine = nil
|
||||
}()
|
||||
|
||||
results, err := th.App.SearchPostsInTeamForUser(searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
results, err := th.App.SearchPostsInTeamForUser(th.Context, searchTerm, th.BasicUser.Id, th.BasicTeam.Id, false, false, 0, page, perPage)
|
||||
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, []string{}, results.Order)
|
||||
@@ -1210,19 +1210,19 @@ func TestCountMentionsFromPost(t *testing.T) {
|
||||
channel := th.CreateChannel(th.BasicTeam)
|
||||
th.AddUserToChannel(user2, channel)
|
||||
|
||||
post1, err := th.App.CreatePost(&model.Post{
|
||||
post1, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test2",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test3",
|
||||
@@ -1247,19 +1247,19 @@ func TestCountMentionsFromPost(t *testing.T) {
|
||||
|
||||
user2.NotifyProps[model.MENTION_KEYS_NOTIFY_PROP] = "apple"
|
||||
|
||||
post1, err := th.App.CreatePost(&model.Post{
|
||||
post1, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: fmt.Sprintf("@%s", user2.Username),
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test2",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "apple",
|
||||
@@ -1286,19 +1286,19 @@ func TestCountMentionsFromPost(t *testing.T) {
|
||||
|
||||
user2.NotifyProps[model.CHANNEL_MENTIONS_NOTIFY_PROP] = "true"
|
||||
|
||||
post1, err := th.App.CreatePost(&model.Post{
|
||||
post1, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "@channel",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "@all",
|
||||
@@ -1325,19 +1325,19 @@ func TestCountMentionsFromPost(t *testing.T) {
|
||||
|
||||
user2.NotifyProps[model.CHANNEL_MENTIONS_NOTIFY_PROP] = "false"
|
||||
|
||||
post1, err := th.App.CreatePost(&model.Post{
|
||||
post1, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "@channel",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "@all",
|
||||
@@ -1367,19 +1367,19 @@ func TestCountMentionsFromPost(t *testing.T) {
|
||||
}, channel.Id, user2.Id)
|
||||
require.Nil(t, err)
|
||||
|
||||
post1, err := th.App.CreatePost(&model.Post{
|
||||
post1, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "@channel",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "@all",
|
||||
@@ -1404,33 +1404,33 @@ func TestCountMentionsFromPost(t *testing.T) {
|
||||
|
||||
user2.NotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ROOT
|
||||
|
||||
post1, err := th.App.CreatePost(&model.Post{
|
||||
post1, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user2.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
RootId: post1.Id,
|
||||
Message: "test2",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
post3, err := th.App.CreatePost(&model.Post{
|
||||
post3, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test3",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user2.Id,
|
||||
ChannelId: channel.Id,
|
||||
RootId: post3.Id,
|
||||
Message: "test4",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
RootId: post3.Id,
|
||||
@@ -1458,33 +1458,33 @@ func TestCountMentionsFromPost(t *testing.T) {
|
||||
|
||||
user2.NotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ANY
|
||||
|
||||
post1, err := th.App.CreatePost(&model.Post{
|
||||
post1, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user2.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
RootId: post1.Id,
|
||||
Message: "test2",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
post3, err := th.App.CreatePost(&model.Post{
|
||||
post3, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test3",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user2.Id,
|
||||
ChannelId: channel.Id,
|
||||
RootId: post3.Id,
|
||||
Message: "test4",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
RootId: post3.Id,
|
||||
@@ -1510,7 +1510,7 @@ func TestCountMentionsFromPost(t *testing.T) {
|
||||
channel := th.CreateChannel(th.BasicTeam)
|
||||
th.AddUserToChannel(user2, channel)
|
||||
|
||||
post1, err := th.App.CreatePost(&model.Post{
|
||||
post1, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test",
|
||||
@@ -1520,7 +1520,7 @@ func TestCountMentionsFromPost(t *testing.T) {
|
||||
},
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test2",
|
||||
@@ -1530,7 +1530,7 @@ func TestCountMentionsFromPost(t *testing.T) {
|
||||
},
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test3",
|
||||
@@ -1559,14 +1559,14 @@ func TestCountMentionsFromPost(t *testing.T) {
|
||||
channel, err := th.App.createDirectChannel(user1.Id, user2.Id)
|
||||
require.Nil(t, err)
|
||||
|
||||
post1, err := th.App.CreatePost(&model.Post{
|
||||
post1, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test2",
|
||||
@@ -1594,19 +1594,19 @@ func TestCountMentionsFromPost(t *testing.T) {
|
||||
channel := th.CreateChannel(th.BasicTeam)
|
||||
th.AddUserToChannel(user2, channel)
|
||||
|
||||
_, err := th.App.CreatePost(&model.Post{
|
||||
_, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: fmt.Sprintf("@%s", user2.Username),
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
post2, err := th.App.CreatePost(&model.Post{
|
||||
post2, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test2",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: fmt.Sprintf("@%s", user2.Username),
|
||||
@@ -1631,13 +1631,13 @@ func TestCountMentionsFromPost(t *testing.T) {
|
||||
channel := th.CreateChannel(th.BasicTeam)
|
||||
th.AddUserToChannel(user2, channel)
|
||||
|
||||
post1, err := th.App.CreatePost(&model.Post{
|
||||
post1, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: fmt.Sprintf("@%s", user2.Username),
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user2.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: fmt.Sprintf("@%s", user2.Username),
|
||||
@@ -1664,26 +1664,26 @@ func TestCountMentionsFromPost(t *testing.T) {
|
||||
|
||||
user2.NotifyProps[model.COMMENTS_NOTIFY_PROP] = model.COMMENTS_NOTIFY_ANY
|
||||
|
||||
post1, err := th.App.CreatePost(&model.Post{
|
||||
post1, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test1",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user2.Id,
|
||||
ChannelId: channel.Id,
|
||||
RootId: post1.Id,
|
||||
Message: "test2",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
post3, err := th.App.CreatePost(&model.Post{
|
||||
post3, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test3",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
RootId: post1.Id,
|
||||
@@ -1709,19 +1709,19 @@ func TestCountMentionsFromPost(t *testing.T) {
|
||||
channel := th.CreateChannel(th.BasicTeam)
|
||||
th.AddUserToChannel(user2, channel)
|
||||
|
||||
post1, err := th.App.CreatePost(&model.Post{
|
||||
post1, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test1",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user2.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: fmt.Sprintf("@%s", user2.Username),
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user2.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: fmt.Sprintf("@%s", user2.Username),
|
||||
@@ -1751,7 +1751,7 @@ func TestCountMentionsFromPost(t *testing.T) {
|
||||
|
||||
numPosts := 215
|
||||
|
||||
post1, err := th.App.CreatePost(&model.Post{
|
||||
post1, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: fmt.Sprintf("@%s", user2.Username),
|
||||
@@ -1759,7 +1759,7 @@ func TestCountMentionsFromPost(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
|
||||
for i := 0; i < numPosts-1; i++ {
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: fmt.Sprintf("@%s", user2.Username),
|
||||
@@ -1786,7 +1786,7 @@ func TestFillInPostProps(t *testing.T) {
|
||||
|
||||
channel := th.CreateChannel(th.BasicTeam)
|
||||
|
||||
post1, err := th.App.CreatePost(&model.Post{
|
||||
post1, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test123123 @group1 @group2 blah blah blah",
|
||||
@@ -1811,14 +1811,14 @@ func TestFillInPostProps(t *testing.T) {
|
||||
Password: "Password1",
|
||||
EmailVerified: true,
|
||||
}
|
||||
guest, err := th.App.CreateGuest(guest)
|
||||
guest, err := th.App.CreateGuest(th.Context, guest)
|
||||
require.Nil(t, err)
|
||||
th.LinkUserToTeam(guest, th.BasicTeam)
|
||||
|
||||
channel := th.CreateChannel(th.BasicTeam)
|
||||
th.AddUserToChannel(guest, channel)
|
||||
|
||||
post1, err := th.App.CreatePost(&model.Post{
|
||||
post1, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: guest.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test123123 @group1 @group2 blah blah blah",
|
||||
@@ -1844,14 +1844,14 @@ func TestFillInPostProps(t *testing.T) {
|
||||
Password: "Password1",
|
||||
EmailVerified: true,
|
||||
}
|
||||
guest, err := th.App.CreateGuest(guest)
|
||||
guest, err := th.App.CreateGuest(th.Context, guest)
|
||||
require.Nil(t, err)
|
||||
th.LinkUserToTeam(guest, th.BasicTeam)
|
||||
|
||||
channel := th.CreateChannel(th.BasicTeam)
|
||||
th.AddUserToChannel(guest, channel)
|
||||
|
||||
post1, err := th.App.CreatePost(&model.Post{
|
||||
post1, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: guest.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "test123123 @group1 @group2 blah blah blah",
|
||||
@@ -1876,14 +1876,14 @@ func TestThreadMembership(t *testing.T) {
|
||||
channel := th.CreateChannel(th.BasicTeam)
|
||||
th.AddUserToChannel(user2, channel)
|
||||
|
||||
postRoot, err := th.App.CreatePost(&model.Post{
|
||||
postRoot, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "root post",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
RootId: postRoot.Id,
|
||||
@@ -1900,14 +1900,14 @@ func TestThreadMembership(t *testing.T) {
|
||||
require.NoError(t, err2)
|
||||
require.Len(t, memberships, 1)
|
||||
|
||||
post2, err := th.App.CreatePost(&model.Post{
|
||||
post2, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user2.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "second post",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user2.Id,
|
||||
ChannelId: channel.Id,
|
||||
RootId: post2.Id,
|
||||
@@ -1938,25 +1938,25 @@ func TestFollowThreadSkipsParticipants(t *testing.T) {
|
||||
user2 := th.BasicUser2
|
||||
sysadmin := th.SystemAdminUser
|
||||
|
||||
appErr := th.App.JoinChannel(channel, user.Id)
|
||||
appErr := th.App.JoinChannel(th.Context, channel, user.Id)
|
||||
require.Nil(t, appErr)
|
||||
appErr = th.App.JoinChannel(channel, user2.Id)
|
||||
appErr = th.App.JoinChannel(th.Context, channel, user2.Id)
|
||||
require.Nil(t, appErr)
|
||||
_, appErr = th.App.JoinUserToTeam(th.BasicTeam, sysadmin, sysadmin.Id)
|
||||
_, appErr = th.App.JoinUserToTeam(th.Context, th.BasicTeam, sysadmin, sysadmin.Id)
|
||||
require.Nil(t, appErr)
|
||||
appErr = th.App.JoinChannel(channel, sysadmin.Id)
|
||||
appErr = th.App.JoinChannel(th.Context, channel, sysadmin.Id)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
p1, err := th.App.CreatePost(&model.Post{UserId: user.Id, ChannelId: channel.Id, Message: "Hi @" + sysadmin.Username}, channel, false, false)
|
||||
p1, err := th.App.CreatePost(th.Context, &model.Post{UserId: user.Id, ChannelId: channel.Id, Message: "Hi @" + sysadmin.Username}, channel, false, false)
|
||||
require.Nil(t, err)
|
||||
_, err = th.App.CreatePost(&model.Post{RootId: p1.Id, UserId: user.Id, ChannelId: channel.Id, Message: "Hola"}, channel, false, false)
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{RootId: p1.Id, UserId: user.Id, ChannelId: channel.Id, Message: "Hola"}, channel, false, false)
|
||||
require.Nil(t, err)
|
||||
|
||||
thread, err := th.App.GetThreadForUser(user.Id, th.BasicTeam.Id, p1.Id, false)
|
||||
require.Nil(t, err)
|
||||
require.Len(t, thread.Participants, 1) // length should be 1, the original poster, since sysadmin was just mentioned but didn't post
|
||||
|
||||
_, err = th.App.CreatePost(&model.Post{RootId: p1.Id, UserId: sysadmin.Id, ChannelId: channel.Id, Message: "sysadmin reply"}, channel, false, false)
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{RootId: p1.Id, UserId: sysadmin.Id, ChannelId: channel.Id, Message: "sysadmin reply"}, channel, false, false)
|
||||
require.Nil(t, err)
|
||||
|
||||
thread, err = th.App.GetThreadForUser(user.Id, th.BasicTeam.Id, p1.Id, false)
|
||||
@@ -1988,16 +1988,16 @@ func TestAutofollowBasedOnRootPost(t *testing.T) {
|
||||
channel := th.BasicChannel
|
||||
user := th.BasicUser
|
||||
user2 := th.BasicUser2
|
||||
appErr := th.App.JoinChannel(channel, user.Id)
|
||||
appErr := th.App.JoinChannel(th.Context, channel, user.Id)
|
||||
require.Nil(t, appErr)
|
||||
appErr = th.App.JoinChannel(channel, user2.Id)
|
||||
appErr = th.App.JoinChannel(th.Context, channel, user2.Id)
|
||||
require.Nil(t, appErr)
|
||||
p1, err := th.App.CreatePost(&model.Post{UserId: user.Id, ChannelId: channel.Id, Message: "Hi @" + user2.Username}, channel, false, false)
|
||||
p1, err := th.App.CreatePost(th.Context, &model.Post{UserId: user.Id, ChannelId: channel.Id, Message: "Hi @" + user2.Username}, channel, false, false)
|
||||
require.Nil(t, err)
|
||||
m, e := th.App.GetThreadMembershipsForUser(user2.Id, th.BasicTeam.Id)
|
||||
require.NoError(t, e)
|
||||
require.Len(t, m, 0)
|
||||
_, err2 := th.App.CreatePost(&model.Post{RootId: p1.Id, UserId: user.Id, ChannelId: channel.Id, Message: "Hola"}, channel, false, false)
|
||||
_, err2 := th.App.CreatePost(th.Context, &model.Post{RootId: p1.Id, UserId: user.Id, ChannelId: channel.Id, Message: "Hola"}, channel, false, false)
|
||||
require.Nil(t, err2)
|
||||
m, e = th.App.GetThreadMembershipsForUser(user2.Id, th.BasicTeam.Id)
|
||||
require.NoError(t, e)
|
||||
@@ -2018,13 +2018,13 @@ func TestViewChannelShouldNotUpdateThreads(t *testing.T) {
|
||||
channel := th.BasicChannel
|
||||
user := th.BasicUser
|
||||
user2 := th.BasicUser2
|
||||
appErr := th.App.JoinChannel(channel, user.Id)
|
||||
appErr := th.App.JoinChannel(th.Context, channel, user.Id)
|
||||
require.Nil(t, appErr)
|
||||
appErr = th.App.JoinChannel(channel, user2.Id)
|
||||
appErr = th.App.JoinChannel(th.Context, channel, user2.Id)
|
||||
require.Nil(t, appErr)
|
||||
p1, err := th.App.CreatePost(&model.Post{UserId: user.Id, ChannelId: channel.Id, Message: "Hi @" + user2.Username}, channel, false, false)
|
||||
p1, err := th.App.CreatePost(th.Context, &model.Post{UserId: user.Id, ChannelId: channel.Id, Message: "Hi @" + user2.Username}, channel, false, false)
|
||||
require.Nil(t, err)
|
||||
_, err2 := th.App.CreatePost(&model.Post{RootId: p1.Id, UserId: user.Id, ChannelId: channel.Id, Message: "Hola"}, channel, false, false)
|
||||
_, err2 := th.App.CreatePost(th.Context, &model.Post{RootId: p1.Id, UserId: user.Id, ChannelId: channel.Id, Message: "Hola"}, channel, false, false)
|
||||
require.Nil(t, err2)
|
||||
m, e := th.App.GetThreadMembershipsForUser(user2.Id, th.BasicTeam.Id)
|
||||
require.NoError(t, e)
|
||||
@@ -2053,16 +2053,16 @@ func TestCollapsedThreadFetch(t *testing.T) {
|
||||
t.Run("should only return root posts, enriched", func(t *testing.T) {
|
||||
channel := th.CreateChannel(th.BasicTeam)
|
||||
th.AddUserToChannel(user2, channel)
|
||||
defer th.App.DeleteChannel(channel, user1.Id)
|
||||
defer th.App.DeleteChannel(th.Context, channel, user1.Id)
|
||||
|
||||
postRoot, err := th.App.CreatePost(&model.Post{
|
||||
postRoot, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "root post",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err)
|
||||
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
RootId: postRoot.Id,
|
||||
@@ -2098,9 +2098,9 @@ func TestCollapsedThreadFetch(t *testing.T) {
|
||||
|
||||
channel := th.CreateChannel(th.BasicTeam)
|
||||
th.AddUserToChannel(user2, channel)
|
||||
defer th.App.DeleteChannel(channel, user1.Id)
|
||||
defer th.App.DeleteChannel(th.Context, channel, user1.Id)
|
||||
|
||||
postRoot, err := th.App.CreatePost(&model.Post{
|
||||
postRoot, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "root post",
|
||||
@@ -2116,7 +2116,7 @@ func TestCollapsedThreadFetch(t *testing.T) {
|
||||
}()
|
||||
|
||||
require.NotPanics(t, func() {
|
||||
_, err = th.App.CreatePost(&model.Post{
|
||||
_, err = th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user1.Id,
|
||||
ChannelId: channel.Id,
|
||||
RootId: postRoot.Id,
|
||||
@@ -2150,14 +2150,14 @@ func TestReplyToPostWithLag(t *testing.T) {
|
||||
mainHelper.ToggleReplicasOn()
|
||||
defer mainHelper.ToggleReplicasOff()
|
||||
|
||||
root, appErr := th.App.CreatePost(&model.Post{
|
||||
root, appErr := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "root post",
|
||||
}, th.BasicChannel, false, true)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
reply, appErr := th.App.CreatePost(&model.Post{
|
||||
reply, appErr := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: th.BasicUser2.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
RootId: root.Id,
|
||||
@@ -2183,7 +2183,7 @@ func TestSharedChannelSyncForPostActions(t *testing.T) {
|
||||
|
||||
channel := th.CreateChannel(th.BasicTeam, WithShared(true))
|
||||
|
||||
_, err := th.App.CreatePost(&model.Post{
|
||||
_, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "Hello folks",
|
||||
@@ -2207,14 +2207,14 @@ func TestSharedChannelSyncForPostActions(t *testing.T) {
|
||||
|
||||
channel := th.CreateChannel(th.BasicTeam, WithShared(true))
|
||||
|
||||
post, err := th.App.CreatePost(&model.Post{
|
||||
post, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "Hello folks",
|
||||
}, channel, false, true)
|
||||
require.Nil(t, err, "Creating a post should not error")
|
||||
|
||||
_, err = th.App.UpdatePost(post, true)
|
||||
_, err = th.App.UpdatePost(th.Context, post, true)
|
||||
require.Nil(t, err, "Updating a post should not error")
|
||||
|
||||
assert.Len(t, remoteClusterService.notifications, 2)
|
||||
@@ -2235,7 +2235,7 @@ func TestSharedChannelSyncForPostActions(t *testing.T) {
|
||||
|
||||
channel := th.CreateChannel(th.BasicTeam, WithShared(true))
|
||||
|
||||
post, err := th.App.CreatePost(&model.Post{
|
||||
post, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "Hello folks",
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/pkg/errors"
|
||||
date_constraints "github.com/reflog/dateconstraints"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/config"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
@@ -237,9 +238,9 @@ func validateConfigEntry(conf *model.Config, path string, expectedValue interfac
|
||||
}
|
||||
|
||||
// GetProductNotices is called from the frontend to fetch the product notices that are relevant to the caller
|
||||
func (a *App) GetProductNotices(userID, teamID string, client model.NoticeClientType, clientVersion string, locale string) (model.NoticeMessages, *model.AppError) {
|
||||
isSystemAdmin := a.SessionHasPermissionTo(*a.Session(), model.PERMISSION_MANAGE_SYSTEM)
|
||||
isTeamAdmin := a.SessionHasPermissionToTeam(*a.Session(), teamID, model.PERMISSION_MANAGE_TEAM)
|
||||
func (a *App) GetProductNotices(c *request.Context, userID, teamID string, client model.NoticeClientType, clientVersion string, locale string) (model.NoticeMessages, *model.AppError) {
|
||||
isSystemAdmin := a.SessionHasPermissionTo(*c.Session(), model.PERMISSION_MANAGE_SYSTEM)
|
||||
isTeamAdmin := a.SessionHasPermissionToTeam(*c.Session(), teamID, model.PERMISSION_MANAGE_TEAM)
|
||||
|
||||
// check if notices for regular users are disabled
|
||||
if !*a.Srv().Config().AnnouncementSettings.UserNoticesEnabled && !isSystemAdmin {
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/store/storetest/mocks"
|
||||
)
|
||||
@@ -718,7 +719,7 @@ func TestNoticeFetch(t *testing.T) {
|
||||
require.Nil(t, appErr)
|
||||
|
||||
// get them for specified user
|
||||
messages, appErr := th.App.GetProductNotices(th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en")
|
||||
messages, appErr := th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en")
|
||||
require.Nil(t, appErr)
|
||||
require.Len(t, messages, 1)
|
||||
|
||||
@@ -727,7 +728,7 @@ func TestNoticeFetch(t *testing.T) {
|
||||
require.Nil(t, appErr)
|
||||
|
||||
// get them again, see that none are returned
|
||||
messages, appErr = th.App.GetProductNotices(th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en")
|
||||
messages, appErr = th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en")
|
||||
require.Nil(t, appErr)
|
||||
require.Len(t, messages, 0)
|
||||
|
||||
@@ -746,7 +747,7 @@ func TestNoticeFetch(t *testing.T) {
|
||||
require.Nil(t, appErr)
|
||||
|
||||
// get them again, since conditions don't match we should be zero
|
||||
messages, appErr = th.App.GetProductNotices(th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en")
|
||||
messages, appErr = th.App.GetProductNotices(&request.Context{}, th.BasicUser.Id, th.BasicTeam.Id, model.NoticeClientType_All, "1.2.3", "en")
|
||||
require.Nil(t, appErr)
|
||||
require.Len(t, messages, 0)
|
||||
|
||||
|
||||
@@ -7,11 +7,12 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/plugin"
|
||||
)
|
||||
|
||||
func (a *App) SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *model.AppError) {
|
||||
func (a *App) SaveReactionForPost(c *request.Context, reaction *model.Reaction) (*model.Reaction, *model.AppError) {
|
||||
post, err := a.GetSinglePost(reaction.PostId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -54,7 +55,7 @@ func (a *App) SaveReactionForPost(reaction *model.Reaction) (*model.Reaction, *m
|
||||
|
||||
if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil {
|
||||
a.Srv().Go(func() {
|
||||
pluginContext := a.PluginContext()
|
||||
pluginContext := pluginContext(c)
|
||||
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
|
||||
hooks.ReactionHasBeenAdded(pluginContext, reaction)
|
||||
return true
|
||||
@@ -105,7 +106,7 @@ func populateEmptyReactions(postIDs []string, reactions map[string][]*model.Reac
|
||||
return reactions
|
||||
}
|
||||
|
||||
func (a *App) DeleteReactionForPost(reaction *model.Reaction) *model.AppError {
|
||||
func (a *App) DeleteReactionForPost(c *request.Context, reaction *model.Reaction) *model.AppError {
|
||||
post, err := a.GetSinglePost(reaction.PostId)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -140,7 +141,7 @@ func (a *App) DeleteReactionForPost(reaction *model.Reaction) *model.AppError {
|
||||
|
||||
if pluginsEnvironment := a.GetPluginsEnvironment(); pluginsEnvironment != nil {
|
||||
a.Srv().Go(func() {
|
||||
pluginContext := a.PluginContext()
|
||||
pluginContext := pluginContext(c)
|
||||
pluginsEnvironment.RunMultiPluginHook(func(hooks plugin.Hooks) bool {
|
||||
hooks.ReactionHasBeenRemoved(pluginContext, reaction)
|
||||
return true
|
||||
|
||||
@@ -26,7 +26,7 @@ func TestSharedChannelSyncForReactionActions(t *testing.T) {
|
||||
|
||||
channel := th.CreateChannel(th.BasicTeam, WithShared(true))
|
||||
|
||||
post, err := th.App.CreatePost(&model.Post{
|
||||
post, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "Hello folks",
|
||||
@@ -39,7 +39,7 @@ func TestSharedChannelSyncForReactionActions(t *testing.T) {
|
||||
EmojiName: "+1",
|
||||
}
|
||||
|
||||
_, err = th.App.SaveReactionForPost(reaction)
|
||||
_, err = th.App.SaveReactionForPost(th.Context, reaction)
|
||||
require.Nil(t, err, "Adding a reaction should not error")
|
||||
|
||||
th.TearDown() // We need to enforce teardown because reaction instrumentation happens in a goroutine
|
||||
@@ -61,7 +61,7 @@ func TestSharedChannelSyncForReactionActions(t *testing.T) {
|
||||
|
||||
channel := th.CreateChannel(th.BasicTeam, WithShared(true))
|
||||
|
||||
post, err := th.App.CreatePost(&model.Post{
|
||||
post, err := th.App.CreatePost(th.Context, &model.Post{
|
||||
UserId: user.Id,
|
||||
ChannelId: channel.Id,
|
||||
Message: "Hello folks",
|
||||
@@ -74,7 +74,7 @@ func TestSharedChannelSyncForReactionActions(t *testing.T) {
|
||||
EmojiName: "+1",
|
||||
}
|
||||
|
||||
err = th.App.DeleteReactionForPost(reaction)
|
||||
err = th.App.DeleteReactionForPost(th.Context, reaction)
|
||||
require.Nil(t, err, "Adding a reaction should not error")
|
||||
|
||||
th.TearDown() // We need to enforce teardown because reaction instrumentation happens in a goroutine
|
||||
|
||||
@@ -6,6 +6,7 @@ package app
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/services/remotecluster"
|
||||
)
|
||||
@@ -70,6 +71,6 @@ func (mrcs *mockRemoteClusterService) AcceptInvitation(invite *model.RemoteClust
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (mrcs *mockRemoteClusterService) ReceiveIncomingMsg(rc *model.RemoteCluster, msg model.RemoteClusterMsg) remotecluster.Response {
|
||||
func (mrcs *mockRemoteClusterService) ReceiveIncomingMsg(_ *request.Context, rc *model.RemoteCluster, msg model.RemoteClusterMsg) remotecluster.Response {
|
||||
return remotecluster.Response{}
|
||||
}
|
||||
|
||||
99
app/request/context.go
Обычный файл
99
app/request/context.go
Обычный файл
@@ -0,0 +1,99 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package request
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
)
|
||||
|
||||
type Context struct {
|
||||
t i18n.TranslateFunc
|
||||
session model.Session
|
||||
requestId string
|
||||
ipAddress string
|
||||
path string
|
||||
userAgent string
|
||||
acceptLanguage string
|
||||
|
||||
context context.Context
|
||||
}
|
||||
|
||||
func NewContext(ctx context.Context, requestId, ipAddress, path, userAgent, acceptLanguage string, session model.Session, t i18n.TranslateFunc) *Context {
|
||||
return &Context{
|
||||
t: t,
|
||||
session: session,
|
||||
requestId: requestId,
|
||||
ipAddress: ipAddress,
|
||||
path: path,
|
||||
userAgent: userAgent,
|
||||
acceptLanguage: acceptLanguage,
|
||||
context: ctx,
|
||||
}
|
||||
}
|
||||
|
||||
func EmptyContext() *Context {
|
||||
return &Context{
|
||||
t: i18n.T,
|
||||
context: context.Background(),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Context) T(translationID string, args ...interface{}) string {
|
||||
return c.t(translationID, args...)
|
||||
}
|
||||
func (c *Context) Session() *model.Session {
|
||||
return &c.session
|
||||
}
|
||||
func (c *Context) RequestId() string {
|
||||
return c.requestId
|
||||
}
|
||||
func (c *Context) IpAddress() string {
|
||||
return c.ipAddress
|
||||
}
|
||||
func (c *Context) Path() string {
|
||||
return c.path
|
||||
}
|
||||
func (c *Context) UserAgent() string {
|
||||
return c.userAgent
|
||||
}
|
||||
func (c *Context) AcceptLanguage() string {
|
||||
return c.acceptLanguage
|
||||
}
|
||||
|
||||
func (c *Context) Context() context.Context {
|
||||
return c.context
|
||||
}
|
||||
|
||||
func (c *Context) SetSession(s *model.Session) {
|
||||
c.session = *s
|
||||
}
|
||||
|
||||
func (c *Context) SetT(t i18n.TranslateFunc) {
|
||||
c.t = t
|
||||
}
|
||||
func (c *Context) SetRequestId(s string) {
|
||||
c.requestId = s
|
||||
}
|
||||
func (c *Context) SetIpAddress(s string) {
|
||||
c.ipAddress = s
|
||||
}
|
||||
func (c *Context) SetUserAgent(s string) {
|
||||
c.userAgent = s
|
||||
}
|
||||
func (c *Context) SetAcceptLanguage(s string) {
|
||||
c.acceptLanguage = s
|
||||
}
|
||||
func (c *Context) SetPath(s string) {
|
||||
c.path = s
|
||||
}
|
||||
func (c *Context) SetContext(ctx context.Context) {
|
||||
c.context = ctx
|
||||
}
|
||||
|
||||
func (c *Context) GetT() i18n.TranslateFunc {
|
||||
return c.t
|
||||
}
|
||||
160
app/server.go
160
app/server.go
@@ -11,7 +11,6 @@ import (
|
||||
"fmt"
|
||||
"hash/maphash"
|
||||
"html/template"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
@@ -39,6 +38,7 @@ import (
|
||||
"github.com/rs/cors"
|
||||
"golang.org/x/crypto/acme/autocert"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/audit"
|
||||
"github.com/mattermost/mattermost-server/v5/config"
|
||||
"github.com/mattermost/mattermost-server/v5/einterfaces"
|
||||
@@ -77,10 +77,9 @@ var MaxNotificationsPerChannelDefault int64 = 1000000
|
||||
var SentryDSN = "placeholder_sentry_dsn"
|
||||
|
||||
type Server struct {
|
||||
sqlStore *sqlstore.SqlStore
|
||||
Store store.Store
|
||||
WebSocketRouter *WebSocketRouter
|
||||
AppInitializedOnce sync.Once
|
||||
sqlStore *sqlstore.SqlStore
|
||||
Store store.Store
|
||||
WebSocketRouter *WebSocketRouter
|
||||
|
||||
// RootRouter is the starting point for all HTTP requests to the server.
|
||||
RootRouter *mux.Router
|
||||
@@ -176,6 +175,7 @@ type Server struct {
|
||||
joinCluster bool
|
||||
startMetrics bool
|
||||
startSearchEngine bool
|
||||
skipPostInit bool
|
||||
|
||||
SearchEngine *searchengine.Broker
|
||||
|
||||
@@ -642,6 +642,48 @@ func NewServer(options ...Option) (*Server, error) {
|
||||
}()
|
||||
}
|
||||
|
||||
if s.skipPostInit {
|
||||
return s, nil
|
||||
}
|
||||
|
||||
c := request.EmptyContext()
|
||||
s.AddConfigListener(func(oldConfig *model.Config, newConfig *model.Config) {
|
||||
if *oldConfig.GuestAccountsSettings.Enable && !*newConfig.GuestAccountsSettings.Enable {
|
||||
if appErr := fakeApp.DeactivateGuests(c); appErr != nil {
|
||||
mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Disable active guest accounts on first run if guest accounts are disabled
|
||||
if !*s.Config().GuestAccountsSettings.Enable {
|
||||
if appErr := fakeApp.DeactivateGuests(c); appErr != nil {
|
||||
mlog.Error("Unable to deactivate guest accounts", mlog.Err(appErr))
|
||||
}
|
||||
}
|
||||
|
||||
s.doAppMigrations()
|
||||
|
||||
s.initPostMetadata()
|
||||
|
||||
s.initPlugins(c, *s.Config().PluginSettings.Directory, *s.Config().PluginSettings.ClientDirectory)
|
||||
s.AddConfigListener(func(prevCfg, cfg *model.Config) {
|
||||
if *cfg.PluginSettings.Enable {
|
||||
s.initPlugins(c, *cfg.PluginSettings.Directory, *s.Config().PluginSettings.ClientDirectory)
|
||||
} else {
|
||||
s.ShutDownPlugins()
|
||||
}
|
||||
})
|
||||
if s.runEssentialJobs {
|
||||
s.Go(func() {
|
||||
s.runLicenseExpirationCheckJob()
|
||||
runCheckAdminSupportStatusJob(fakeApp, c)
|
||||
runCheckWarnMetricStatusJob(fakeApp, c)
|
||||
runDNDStatusExpireJob(fakeApp)
|
||||
})
|
||||
s.runJobs()
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
@@ -1400,10 +1442,10 @@ func runSessionCleanupJob(s *Server) {
|
||||
}, time.Hour*24)
|
||||
}
|
||||
|
||||
func runLicenseExpirationCheckJob(a *App) {
|
||||
doLicenseExpirationCheck(a)
|
||||
func (s *Server) runLicenseExpirationCheckJob() {
|
||||
s.doLicenseExpirationCheck()
|
||||
model.CreateRecurringTask("License Expiration Check", func() {
|
||||
doLicenseExpirationCheck(a)
|
||||
s.doLicenseExpirationCheck()
|
||||
}, time.Hour*24)
|
||||
}
|
||||
|
||||
@@ -1426,17 +1468,17 @@ func doReportUsageToAWSMeteringService(s *Server) {
|
||||
}
|
||||
|
||||
//nolint:golint,unused,deadcode
|
||||
func runCheckWarnMetricStatusJob(a *App) {
|
||||
doCheckWarnMetricStatus(a)
|
||||
func runCheckWarnMetricStatusJob(a *App, c *request.Context) {
|
||||
doCheckWarnMetricStatus(a, c)
|
||||
model.CreateRecurringTask("Check Warn Metric Status Job", func() {
|
||||
doCheckWarnMetricStatus(a)
|
||||
doCheckWarnMetricStatus(a, c)
|
||||
}, time.Hour*model.WARN_METRIC_JOB_INTERVAL)
|
||||
}
|
||||
|
||||
func runCheckAdminSupportStatusJob(a *App) {
|
||||
doCheckAdminSupportStatus(a)
|
||||
func runCheckAdminSupportStatusJob(a *App, c *request.Context) {
|
||||
doCheckAdminSupportStatus(a, c)
|
||||
model.CreateRecurringTask("Check Admin Support Status Job", func() {
|
||||
doCheckAdminSupportStatus(a)
|
||||
doCheckAdminSupportStatus(a, c)
|
||||
}, time.Hour*model.WARN_METRIC_JOB_INTERVAL)
|
||||
}
|
||||
|
||||
@@ -1461,7 +1503,7 @@ func doSessionCleanup(s *Server) {
|
||||
}
|
||||
|
||||
//nolint:golint,unused,deadcode
|
||||
func doCheckWarnMetricStatus(a *App) {
|
||||
func doCheckWarnMetricStatus(a *App, c *request.Context) {
|
||||
license := a.Srv().License()
|
||||
if license != nil {
|
||||
mlog.Debug("License is present, skip")
|
||||
@@ -1592,7 +1634,7 @@ func doCheckWarnMetricStatus(a *App) {
|
||||
}
|
||||
}
|
||||
|
||||
if nerr := a.notifyAdminsOfWarnMetricStatus(warnMetric.Id, isE0Edition); nerr != nil {
|
||||
if nerr := a.notifyAdminsOfWarnMetricStatus(c, warnMetric.Id, isE0Edition); nerr != nil {
|
||||
mlog.Error("Failed to send notifications to admin users.", mlog.Err(nerr))
|
||||
}
|
||||
|
||||
@@ -1604,11 +1646,11 @@ func doCheckWarnMetricStatus(a *App) {
|
||||
}
|
||||
}
|
||||
|
||||
func doCheckAdminSupportStatus(a *App) {
|
||||
func doCheckAdminSupportStatus(a *App, c *request.Context) {
|
||||
isE0Edition := model.BuildEnterpriseReady == "true"
|
||||
|
||||
if strings.TrimSpace(*a.Config().SupportSettings.SupportEmail) == model.SUPPORT_SETTINGS_DEFAULT_SUPPORT_EMAIL {
|
||||
if err := a.notifyAdminsOfWarnMetricStatus(model.SYSTEM_METRIC_SUPPORT_EMAIL_NOT_CONFIGURED, isE0Edition); err != nil {
|
||||
if err := a.notifyAdminsOfWarnMetricStatus(c, model.SYSTEM_METRIC_SUPPORT_EMAIL_NOT_CONFIGURED, isE0Edition); err != nil {
|
||||
mlog.Error("Failed to send notifications to admin users.", mlog.Err(err))
|
||||
}
|
||||
}
|
||||
@@ -1714,9 +1756,9 @@ func (s *Server) startMetricsServer() {
|
||||
s.Log.Info("Metrics and profiling server is started", mlog.String("address", l.Addr().String()))
|
||||
}
|
||||
|
||||
func doLicenseExpirationCheck(a *App) {
|
||||
a.Srv().LoadLicense()
|
||||
license := a.Srv().License()
|
||||
func (s *Server) doLicenseExpirationCheck() {
|
||||
s.LoadLicense()
|
||||
license := s.License()
|
||||
|
||||
if license == nil {
|
||||
mlog.Debug("License cannot be found.")
|
||||
@@ -1728,7 +1770,7 @@ func doLicenseExpirationCheck(a *App) {
|
||||
return
|
||||
}
|
||||
|
||||
users, err := a.Srv().Store.User().GetSystemAdminProfiles()
|
||||
users, err := s.Store.User().GetSystemAdminProfiles()
|
||||
if err != nil {
|
||||
mlog.Error("Failed to get system admins for license expired message from Mattermost.")
|
||||
return
|
||||
@@ -1743,15 +1785,15 @@ func doLicenseExpirationCheck(a *App) {
|
||||
}
|
||||
|
||||
mlog.Debug("Sending license expired email.", mlog.String("user_email", user.Email))
|
||||
a.Srv().Go(func() {
|
||||
if err := a.Srv().EmailService.SendRemoveExpiredLicenseEmail(user.Email, user.Locale, *a.Config().ServiceSettings.SiteURL); err != nil {
|
||||
s.Go(func() {
|
||||
if err := s.EmailService.SendRemoveExpiredLicenseEmail(user.Email, user.Locale, *s.Config().ServiceSettings.SiteURL); err != nil {
|
||||
mlog.Error("Error while sending the license expired email.", mlog.String("user_email", user.Email), mlog.Err(err))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
//remove the license
|
||||
a.Srv().RemoveLicense()
|
||||
s.RemoveLicense()
|
||||
}
|
||||
|
||||
func (s *Server) StartSearchEngine() (string, string) {
|
||||
@@ -1884,6 +1926,50 @@ func (s *Server) initJobs() {
|
||||
if jobsMigrationsInterface != nil {
|
||||
s.Jobs.Migrations = jobsMigrationsInterface(s)
|
||||
}
|
||||
if jobsLdapSyncInterface != nil {
|
||||
s.Jobs.LdapSync = jobsLdapSyncInterface(s)
|
||||
}
|
||||
if jobsPluginsInterface != nil {
|
||||
s.Jobs.Plugins = jobsPluginsInterface(s)
|
||||
}
|
||||
if jobsExpiryNotifyInterface != nil {
|
||||
s.Jobs.ExpiryNotify = jobsExpiryNotifyInterface(s)
|
||||
}
|
||||
if productNoticesJobInterface != nil {
|
||||
s.Jobs.ProductNotices = productNoticesJobInterface(s)
|
||||
}
|
||||
if jobsImportProcessInterface != nil {
|
||||
s.Jobs.ImportProcess = jobsImportProcessInterface(s)
|
||||
}
|
||||
if jobsImportDeleteInterface != nil {
|
||||
s.Jobs.ImportDelete = jobsImportDeleteInterface(s)
|
||||
}
|
||||
if jobsExportDeleteInterface != nil {
|
||||
s.Jobs.ExportDelete = jobsExportDeleteInterface(s)
|
||||
}
|
||||
|
||||
if jobsExportProcessInterface != nil {
|
||||
s.Jobs.ExportProcess = jobsExportProcessInterface(s)
|
||||
}
|
||||
|
||||
if jobsExportProcessInterface != nil {
|
||||
s.Jobs.ExportProcess = jobsExportProcessInterface(s)
|
||||
}
|
||||
|
||||
if jobsActiveUsersInterface != nil {
|
||||
s.Jobs.ActiveUsers = jobsActiveUsersInterface(s)
|
||||
}
|
||||
|
||||
if jobsCloudInterface != nil {
|
||||
s.Jobs.Cloud = jobsCloudInterface(s)
|
||||
}
|
||||
|
||||
if jobsResendInvitationEmailInterface != nil {
|
||||
s.Jobs.ResendInvitationEmails = jobsResendInvitationEmailInterface(s)
|
||||
}
|
||||
|
||||
s.Jobs.InitWorkers()
|
||||
s.Jobs.InitSchedulers()
|
||||
}
|
||||
|
||||
func (s *Server) TelemetryId() string {
|
||||
@@ -2135,7 +2221,7 @@ func (s *Server) GetProfileImage(user *model.User) ([]byte, bool, *model.AppErro
|
||||
}
|
||||
|
||||
if user.LastPictureUpdate == 0 {
|
||||
if _, err := s.WriteFile(bytes.NewReader(img), path); err != nil {
|
||||
if _, err := s.writeFile(bytes.NewReader(img), path); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
}
|
||||
@@ -2173,18 +2259,18 @@ func (s *Server) ReadFile(path string) ([]byte, *model.AppError) {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Server) WriteFile(fr io.Reader, path string) (int64, *model.AppError) {
|
||||
backend, err := s.FileBackend()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// func (s *Server) WriteFile(fr io.Reader, path string) (int64, *model.AppError) {
|
||||
// backend, err := s.FileBackend()
|
||||
// if err != nil {
|
||||
// return 0, err
|
||||
// }
|
||||
|
||||
result, nErr := backend.WriteFile(fr, path)
|
||||
if nErr != nil {
|
||||
return result, model.NewAppError("WriteFile", "api.file.write_file.app_error", nil, nErr.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
// result, nErr := backend.WriteFile(fr, path)
|
||||
// if nErr != nil {
|
||||
// return result, model.NewAppError("WriteFile", "api.file.write_file.app_error", nil, nErr.Error(), http.StatusInternalServerError)
|
||||
// }
|
||||
// return result, nil
|
||||
// }
|
||||
|
||||
func runDNDStatusExpireJob(a *App) {
|
||||
if a.IsLeader() {
|
||||
|
||||
@@ -709,12 +709,12 @@ func TestAdminAdvisor(t *testing.T) {
|
||||
AuthService: "",
|
||||
Roles: model.SYSTEM_ADMIN_ROLE_ID,
|
||||
}
|
||||
ruser, err := th.App.CreateUser(&user)
|
||||
ruser, err := th.App.CreateUser(th.Context, &user)
|
||||
assert.Nil(t, err, "User should be created")
|
||||
defer th.App.PermanentDeleteUser(&user)
|
||||
defer th.App.PermanentDeleteUser(th.Context, &user)
|
||||
|
||||
t.Run("Should notify admin of un-configured support email", func(t *testing.T) {
|
||||
doCheckAdminSupportStatus(th.App)
|
||||
doCheckAdminSupportStatus(th.App, th.Context)
|
||||
|
||||
bot, err := th.App.GetUserByUsername(model.BOT_WARN_METRIC_BOT_USERNAME)
|
||||
assert.NotNil(t, bot, "Bot should have been created now")
|
||||
@@ -742,7 +742,7 @@ func TestAdminAdvisor(t *testing.T) {
|
||||
err = th.App.PermanentDeleteChannel(channel)
|
||||
assert.Nil(t, err, "No error should be generated")
|
||||
|
||||
doCheckAdminSupportStatus(th.App)
|
||||
doCheckAdminSupportStatus(th.App, th.Context)
|
||||
|
||||
channel, err = th.App.getDirectChannel(bot.Id, ruser.Id)
|
||||
assert.NotNil(t, channel, "DM channel should exist between Admin Advisor and system admin")
|
||||
|
||||
@@ -148,7 +148,7 @@ func TestUpdateSessionOnPromoteDemote(t *testing.T) {
|
||||
require.Nil(t, err)
|
||||
assert.Equal(t, "true", rsession.Props[model.SESSION_PROP_IS_GUEST])
|
||||
|
||||
err = th.App.PromoteGuestToUser(guest, th.BasicUser.Id)
|
||||
err = th.App.PromoteGuestToUser(th.Context, guest, th.BasicUser.Id)
|
||||
require.Nil(t, err)
|
||||
|
||||
rsession, err = th.App.GetSession(session.Token)
|
||||
|
||||
26
app/slack.go
26
app/slack.go
@@ -10,21 +10,31 @@ import (
|
||||
"mime/multipart"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/services/slackimport"
|
||||
"github.com/mattermost/mattermost-server/v5/store"
|
||||
)
|
||||
|
||||
func (a *App) SlackImport(fileData multipart.File, fileSize int64, teamID string) (*model.AppError, *bytes.Buffer) {
|
||||
func (a *App) SlackImport(c *request.Context, fileData multipart.File, fileSize int64, teamID string) (*model.AppError, *bytes.Buffer) {
|
||||
actions := slackimport.Actions{
|
||||
UpdateActive: a.UpdateActive,
|
||||
AddUserToChannel: a.AddUserToChannel,
|
||||
JoinUserToTeam: a.JoinUserToTeam,
|
||||
CreateDirectChannel: a.createDirectChannel,
|
||||
CreateGroupChannel: a.createGroupChannel,
|
||||
CreateChannel: a.CreateChannel,
|
||||
DoUploadFile: a.DoUploadFile,
|
||||
UpdateActive: func(user *model.User, active bool) (*model.User, *model.AppError) {
|
||||
return a.UpdateActive(c, user, active)
|
||||
},
|
||||
AddUserToChannel: a.AddUserToChannel,
|
||||
JoinUserToTeam: func(team *model.Team, user *model.User, userRequestorId string) (*model.TeamMember, *model.AppError) {
|
||||
return a.JoinUserToTeam(c, team, user, userRequestorId)
|
||||
},
|
||||
CreateDirectChannel: a.createDirectChannel,
|
||||
CreateGroupChannel: a.createGroupChannel,
|
||||
CreateChannel: func(channel *model.Channel, addMember bool) (*model.Channel, *model.AppError) {
|
||||
return a.CreateChannel(c, channel, addMember)
|
||||
},
|
||||
DoUploadFile: func(now time.Time, rawTeamId string, rawChannelId string, rawUserId string, rawFilename string, data []byte) (*model.FileInfo, *model.AppError) {
|
||||
return a.DoUploadFile(c, now, rawTeamId, rawChannelId, rawUserId, rawFilename, data)
|
||||
},
|
||||
GenerateThumbnailImage: a.generateThumbnailImage,
|
||||
GeneratePreviewImage: a.generatePreviewImage,
|
||||
InvalidateAllCaches: func() { a.srv.InvalidateAllCaches() },
|
||||
|
||||
@@ -5,6 +5,7 @@ package slashcommands
|
||||
|
||||
import (
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/utils"
|
||||
)
|
||||
@@ -35,7 +36,7 @@ func NewAutoChannelCreator(a *app.App, team *model.Team, userID string) *AutoCha
|
||||
}
|
||||
}
|
||||
|
||||
func (cfg *AutoChannelCreator) createRandomChannel() (*model.Channel, error) {
|
||||
func (cfg *AutoChannelCreator) createRandomChannel(c *request.Context) (*model.Channel, error) {
|
||||
var displayName string
|
||||
if cfg.Fuzzy {
|
||||
displayName = utils.FuzzName()
|
||||
@@ -52,20 +53,20 @@ func (cfg *AutoChannelCreator) createRandomChannel() (*model.Channel, error) {
|
||||
CreatorId: cfg.userID,
|
||||
}
|
||||
|
||||
channel, err := cfg.a.CreateChannel(channel, true)
|
||||
channel, err := cfg.a.CreateChannel(c, channel, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return channel, nil
|
||||
}
|
||||
|
||||
func (cfg *AutoChannelCreator) CreateTestChannels(num utils.Range) ([]*model.Channel, error) {
|
||||
func (cfg *AutoChannelCreator) CreateTestChannels(c *request.Context, 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()
|
||||
channels[i], err = cfg.createRandomChannel(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/utils"
|
||||
)
|
||||
@@ -17,7 +18,7 @@ type TestEnvironment struct {
|
||||
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) {
|
||||
func CreateTestEnvironmentWithTeams(a *app.App, c *request.Context, 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)
|
||||
@@ -32,12 +33,12 @@ func CreateTestEnvironmentWithTeams(a *app.App, client *model.Client4, rangeTeam
|
||||
for i, team := range teams {
|
||||
userCreator := NewAutoUserCreator(a, client, team)
|
||||
userCreator.Fuzzy = fuzzy
|
||||
randomUser, err := userCreator.createRandomUser()
|
||||
randomUser, err := userCreator.createRandomUser(c)
|
||||
if err != nil {
|
||||
return TestEnvironment{}, err
|
||||
}
|
||||
client.LoginById(randomUser.Id, UserPassword)
|
||||
teamEnvironment, err := CreateTestEnvironmentInTeam(a, client, team, rangeChannels, rangeUsers, rangePosts, fuzzy)
|
||||
teamEnvironment, err := CreateTestEnvironmentInTeam(a, c, client, team, rangeChannels, rangeUsers, rangePosts, fuzzy)
|
||||
if err != nil {
|
||||
return TestEnvironment{}, err
|
||||
}
|
||||
@@ -47,7 +48,7 @@ func CreateTestEnvironmentWithTeams(a *app.App, client *model.Client4, rangeTeam
|
||||
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) {
|
||||
func CreateTestEnvironmentInTeam(a *app.App, c *request.Context, 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
|
||||
@@ -57,7 +58,7 @@ func CreateTestEnvironmentInTeam(a *app.App, client *model.Client4, team *model.
|
||||
|
||||
userCreator := NewAutoUserCreator(a, client, team)
|
||||
userCreator.Fuzzy = fuzzy
|
||||
users, err := userCreator.CreateTestUsers(rangeUsers)
|
||||
users, err := userCreator.CreateTestUsers(c, rangeUsers)
|
||||
if err != nil {
|
||||
return TeamEnvironment{}, nil
|
||||
}
|
||||
@@ -68,7 +69,7 @@ func CreateTestEnvironmentInTeam(a *app.App, client *model.Client4, team *model.
|
||||
|
||||
channelCreator := NewAutoChannelCreator(a, team, users[0].Id)
|
||||
channelCreator.Fuzzy = fuzzy
|
||||
channels, err := channelCreator.CreateTestChannels(rangeChannels)
|
||||
channels, err := channelCreator.CreateTestChannels(c, rangeChannels)
|
||||
if err != nil {
|
||||
return TeamEnvironment{}, nil
|
||||
}
|
||||
@@ -102,7 +103,7 @@ func CreateTestEnvironmentInTeam(a *app.App, client *model.Client4, team *model.
|
||||
postCreator.HasImage = i < numImages
|
||||
postCreator.Users = usernames
|
||||
postCreator.Fuzzy = fuzzy
|
||||
_, err := postCreator.CreateRandomPost()
|
||||
_, err := postCreator.CreateRandomPost(c)
|
||||
if err != nil {
|
||||
return TeamEnvironment{}, err
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/utils"
|
||||
"github.com/mattermost/mattermost-server/v5/utils/fileutils"
|
||||
@@ -44,7 +45,7 @@ func NewAutoPostCreator(a *app.App, channelid, userid string) *AutoPostCreator {
|
||||
}
|
||||
}
|
||||
|
||||
func (cfg *AutoPostCreator) UploadTestFile() ([]string, error) {
|
||||
func (cfg *AutoPostCreator) UploadTestFile(c *request.Context) ([]string, error) {
|
||||
filename := cfg.ImageFilenames[utils.RandIntFromRange(utils.Range{Begin: 0, End: len(cfg.ImageFilenames) - 1})]
|
||||
|
||||
path, _ := fileutils.FindDir("tests")
|
||||
@@ -60,7 +61,7 @@ func (cfg *AutoPostCreator) UploadTestFile() ([]string, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fileResp, err2 := cfg.a.UploadFile(data.Bytes(), cfg.channelid, filename)
|
||||
fileResp, err2 := cfg.a.UploadFile(c, data.Bytes(), cfg.channelid, filename)
|
||||
if err2 != nil {
|
||||
return nil, err2
|
||||
}
|
||||
@@ -68,15 +69,15 @@ func (cfg *AutoPostCreator) UploadTestFile() ([]string, error) {
|
||||
return []string{fileResp.Id}, nil
|
||||
}
|
||||
|
||||
func (cfg *AutoPostCreator) CreateRandomPost() (*model.Post, error) {
|
||||
return cfg.CreateRandomPostNested("", "")
|
||||
func (cfg *AutoPostCreator) CreateRandomPost(c *request.Context) (*model.Post, error) {
|
||||
return cfg.CreateRandomPostNested(c, "", "")
|
||||
}
|
||||
|
||||
func (cfg *AutoPostCreator) CreateRandomPostNested(parentId, rootId string) (*model.Post, error) {
|
||||
func (cfg *AutoPostCreator) CreateRandomPostNested(c *request.Context, parentId, rootId string) (*model.Post, error) {
|
||||
var fileIDs []string
|
||||
if cfg.HasImage {
|
||||
var err error
|
||||
fileIDs, err = cfg.UploadTestFile()
|
||||
fileIDs, err = cfg.UploadTestFile(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -97,7 +98,7 @@ func (cfg *AutoPostCreator) CreateRandomPostNested(parentId, rootId string) (*mo
|
||||
Message: postText,
|
||||
FileIds: fileIDs,
|
||||
}
|
||||
rpost, err := cfg.a.CreatePostMissingChannel(post, true)
|
||||
rpost, err := cfg.a.CreatePostMissingChannel(c, post, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/store"
|
||||
"github.com/mattermost/mattermost-server/v5/utils"
|
||||
@@ -77,7 +78,7 @@ func CreateBasicUser(a *app.App, client *model.Client4) *model.AppError {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cfg *AutoUserCreator) createRandomUser() (*model.User, error) {
|
||||
func (cfg *AutoUserCreator) createRandomUser(c *request.Context) (*model.User, error) {
|
||||
var userEmail string
|
||||
var userName string
|
||||
if cfg.Fuzzy {
|
||||
@@ -93,7 +94,7 @@ func (cfg *AutoUserCreator) createRandomUser() (*model.User, error) {
|
||||
Nickname: userName,
|
||||
Password: UserPassword}
|
||||
|
||||
ruser, appErr := cfg.app.CreateUserWithInviteId(user, cfg.team.InviteId, "")
|
||||
ruser, appErr := cfg.app.CreateUserWithInviteId(c, user, cfg.team.InviteId, "")
|
||||
if appErr != nil {
|
||||
return nil, appErr
|
||||
}
|
||||
@@ -112,13 +113,13 @@ func (cfg *AutoUserCreator) createRandomUser() (*model.User, error) {
|
||||
return ruser, nil
|
||||
}
|
||||
|
||||
func (cfg *AutoUserCreator) CreateTestUsers(num utils.Range) ([]*model.User, error) {
|
||||
func (cfg *AutoUserCreator) CreateTestUsers(c *request.Context, 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()
|
||||
users[i], err = cfg.createRandomUser(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ package slashcommands
|
||||
|
||||
import (
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
)
|
||||
@@ -33,7 +34,7 @@ func (*AwayProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command
|
||||
}
|
||||
}
|
||||
|
||||
func (*AwayProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (*AwayProvider) DoCommand(a *app.App, c *request.Context, 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")}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"context"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
)
|
||||
@@ -36,7 +37,7 @@ func (*HeaderProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comma
|
||||
}
|
||||
}
|
||||
|
||||
func (*HeaderProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (*HeaderProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
channel, err := a.GetChannel(args.ChannelId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{
|
||||
@@ -92,7 +93,7 @@ func (*HeaderProvider) DoCommand(a *app.App, args *model.CommandArgs, message st
|
||||
}
|
||||
*patch.Header = message
|
||||
|
||||
_, err = a.PatchChannel(channel, patch, args.UserId)
|
||||
_, err = a.PatchChannel(c, channel, patch, args.UserId)
|
||||
if err != nil {
|
||||
text := args.T("api.command_channel_header.update_channel.app_error")
|
||||
if err.Id == "model.channel.is_valid.header.app_error" {
|
||||
|
||||
@@ -30,7 +30,7 @@ func TestHeaderProviderDoCommand(t *testing.T) {
|
||||
"": "api.command_channel_header.message.app_error",
|
||||
"hello": "",
|
||||
} {
|
||||
actual := hp.DoCommand(th.App, args, msg).Text
|
||||
actual := hp.DoCommand(th.App, th.Context, args, msg).Text
|
||||
assert.Equal(t, expected, actual)
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ func TestHeaderProviderDoCommand(t *testing.T) {
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual := hp.DoCommand(th.App, args, "hello").Text
|
||||
actual := hp.DoCommand(th.App, th.Context, 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)
|
||||
@@ -57,7 +57,7 @@ func TestHeaderProviderDoCommand(t *testing.T) {
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = hp.DoCommand(th.App, args, "hello").Text
|
||||
actual = hp.DoCommand(th.App, th.Context, args, "hello").Text
|
||||
assert.Equal(t, "", actual)
|
||||
|
||||
th.removePermissionFromRole(model.PERMISSION_MANAGE_PRIVATE_CHANNEL_PROPERTIES.Id, model.CHANNEL_USER_ROLE_ID)
|
||||
@@ -69,7 +69,7 @@ func TestHeaderProviderDoCommand(t *testing.T) {
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = hp.DoCommand(th.App, args, "hello").Text
|
||||
actual = hp.DoCommand(th.App, th.Context, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_header.permission.app_error", actual)
|
||||
|
||||
// Try a group channel *with* being a member.
|
||||
@@ -85,7 +85,7 @@ func TestHeaderProviderDoCommand(t *testing.T) {
|
||||
UserId: user1.Id,
|
||||
}
|
||||
|
||||
actual = hp.DoCommand(th.App, args, "hello").Text
|
||||
actual = hp.DoCommand(th.App, th.Context, args, "hello").Text
|
||||
assert.Equal(t, "", actual)
|
||||
|
||||
// Try a group channel *without* being a member.
|
||||
@@ -95,7 +95,7 @@ func TestHeaderProviderDoCommand(t *testing.T) {
|
||||
UserId: user3.Id,
|
||||
}
|
||||
|
||||
actual = hp.DoCommand(th.App, args, "hello").Text
|
||||
actual = hp.DoCommand(th.App, th.Context, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_header.permission.app_error", actual)
|
||||
|
||||
// Try a direct channel *with* being a member.
|
||||
@@ -107,7 +107,7 @@ func TestHeaderProviderDoCommand(t *testing.T) {
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = hp.DoCommand(th.App, args, "hello").Text
|
||||
actual = hp.DoCommand(th.App, th.Context, args, "hello").Text
|
||||
assert.Equal(t, "", actual)
|
||||
|
||||
// Try a direct channel *without* being a member.
|
||||
@@ -117,6 +117,6 @@ func TestHeaderProviderDoCommand(t *testing.T) {
|
||||
UserId: user2.Id,
|
||||
}
|
||||
|
||||
actual = hp.DoCommand(th.App, args, "hello").Text
|
||||
actual = hp.DoCommand(th.App, th.Context, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_header.permission.app_error", actual)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ package slashcommands
|
||||
|
||||
import (
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
)
|
||||
@@ -34,7 +35,7 @@ func (*PurposeProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comm
|
||||
}
|
||||
}
|
||||
|
||||
func (*PurposeProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (*PurposeProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
channel, err := a.GetChannel(args.ChannelId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{
|
||||
@@ -77,7 +78,7 @@ func (*PurposeProvider) DoCommand(a *app.App, args *model.CommandArgs, message s
|
||||
}
|
||||
*patch.Purpose = message
|
||||
|
||||
_, err = a.PatchChannel(channel, patch, args.UserId)
|
||||
_, err = a.PatchChannel(c, channel, patch, args.UserId)
|
||||
if err != nil {
|
||||
text := args.T("api.command_channel_purpose.update_channel.app_error")
|
||||
if err.Id == "model.channel.is_valid.purpose.app_error" {
|
||||
|
||||
@@ -30,7 +30,7 @@ func TestPurposeProviderDoCommand(t *testing.T) {
|
||||
"": "api.command_channel_purpose.message.app_error",
|
||||
"hello": "",
|
||||
} {
|
||||
actual := pp.DoCommand(th.App, args, msg).Text
|
||||
actual := pp.DoCommand(th.App, th.Context, args, msg).Text
|
||||
assert.Equal(t, expected, actual)
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ func TestPurposeProviderDoCommand(t *testing.T) {
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
}
|
||||
|
||||
actual := pp.DoCommand(th.App, args, "hello").Text
|
||||
actual := pp.DoCommand(th.App, th.Context, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_purpose.permission.app_error", actual)
|
||||
|
||||
// Try a private channel *with* permission.
|
||||
@@ -56,7 +56,7 @@ func TestPurposeProviderDoCommand(t *testing.T) {
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = pp.DoCommand(th.App, args, "hello").Text
|
||||
actual = pp.DoCommand(th.App, th.Context, args, "hello").Text
|
||||
assert.Equal(t, "", actual)
|
||||
|
||||
// Try a private channel *without* permission.
|
||||
@@ -67,7 +67,7 @@ func TestPurposeProviderDoCommand(t *testing.T) {
|
||||
ChannelId: privateChannel.Id,
|
||||
}
|
||||
|
||||
actual = pp.DoCommand(th.App, args, "hello").Text
|
||||
actual = pp.DoCommand(th.App, th.Context, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_purpose.permission.app_error", actual)
|
||||
|
||||
// Try a group channel *with* being a member.
|
||||
@@ -81,7 +81,7 @@ func TestPurposeProviderDoCommand(t *testing.T) {
|
||||
ChannelId: groupChannel.Id,
|
||||
}
|
||||
|
||||
actual = pp.DoCommand(th.App, args, "hello").Text
|
||||
actual = pp.DoCommand(th.App, th.Context, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_purpose.direct_group.app_error", actual)
|
||||
|
||||
// Try a direct channel *with* being a member.
|
||||
@@ -92,6 +92,6 @@ func TestPurposeProviderDoCommand(t *testing.T) {
|
||||
ChannelId: directChannel.Id,
|
||||
}
|
||||
|
||||
actual = pp.DoCommand(th.App, args, "hello").Text
|
||||
actual = pp.DoCommand(th.App, th.Context, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_purpose.direct_group.app_error", actual)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ package slashcommands
|
||||
|
||||
import (
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
)
|
||||
@@ -37,7 +38,7 @@ func (*RenameProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comma
|
||||
}
|
||||
}
|
||||
|
||||
func (*RenameProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (*RenameProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
channel, err := a.GetChannel(args.ChannelId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{
|
||||
@@ -91,7 +92,7 @@ func (*RenameProvider) DoCommand(a *app.App, args *model.CommandArgs, message st
|
||||
}
|
||||
*patch.DisplayName = message
|
||||
|
||||
_, err = a.PatchChannel(channel, patch, args.UserId)
|
||||
_, err = a.PatchChannel(c, channel, patch, args.UserId)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_channel_rename.update_channel.app_error"),
|
||||
|
||||
@@ -33,7 +33,7 @@ func TestRenameProviderDoCommand(t *testing.T) {
|
||||
"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
|
||||
actual := rp.DoCommand(th.App, th.Context, args, msg).Text
|
||||
assert.Equal(t, expected, actual)
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ func TestRenameProviderDoCommand(t *testing.T) {
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual := rp.DoCommand(th.App, args, "hello").Text
|
||||
actual := rp.DoCommand(th.App, th.Context, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_rename.permission.app_error", actual)
|
||||
|
||||
// Try a private channel *with* permission.
|
||||
@@ -60,7 +60,7 @@ func TestRenameProviderDoCommand(t *testing.T) {
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = rp.DoCommand(th.App, args, "hello").Text
|
||||
actual = rp.DoCommand(th.App, th.Context, args, "hello").Text
|
||||
assert.Equal(t, "", actual)
|
||||
|
||||
// Try a private channel *without* permission.
|
||||
@@ -72,7 +72,7 @@ func TestRenameProviderDoCommand(t *testing.T) {
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = rp.DoCommand(th.App, args, "hello").Text
|
||||
actual = rp.DoCommand(th.App, th.Context, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_rename.permission.app_error", actual)
|
||||
|
||||
// Try a group channel *with* being a member.
|
||||
@@ -87,7 +87,7 @@ func TestRenameProviderDoCommand(t *testing.T) {
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = rp.DoCommand(th.App, args, "hello").Text
|
||||
actual = rp.DoCommand(th.App, th.Context, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_rename.direct_group.app_error", actual)
|
||||
|
||||
// Try a direct channel *with* being a member.
|
||||
@@ -99,6 +99,6 @@ func TestRenameProviderDoCommand(t *testing.T) {
|
||||
UserId: th.BasicUser.Id,
|
||||
}
|
||||
|
||||
actual = rp.DoCommand(th.App, args, "hello").Text
|
||||
actual = rp.DoCommand(th.App, th.Context, args, "hello").Text
|
||||
assert.Equal(t, "api.command_channel_rename.direct_group.app_error", actual)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
)
|
||||
@@ -36,7 +37,7 @@ func (*CodeProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command
|
||||
}
|
||||
}
|
||||
|
||||
func (*CodeProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (*CodeProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
if message == "" {
|
||||
return &model.CommandResponse{Text: args.T("api.command_code.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ func TestCodeProviderDoCommand(t *testing.T) {
|
||||
"foo\nbar": " foo\n bar",
|
||||
"foo\nbar\n": " foo\n bar\n ",
|
||||
} {
|
||||
actual := cp.DoCommand(nil, args, msg).Text
|
||||
actual := cp.DoCommand(nil, nil, args, msg).Text
|
||||
if actual != expected {
|
||||
t.Errorf("expected `%v`, got `%v`", expected, actual)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
@@ -40,7 +41,7 @@ func (*CustomStatusProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model
|
||||
}
|
||||
}
|
||||
|
||||
func (*CustomStatusProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (*CustomStatusProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
if !*a.Config().TeamSettings.EnableCustomUserStatuses {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ package slashcommands
|
||||
|
||||
import (
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
)
|
||||
@@ -33,7 +34,7 @@ func (*DndProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command
|
||||
}
|
||||
}
|
||||
|
||||
func (*DndProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (*DndProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
a.SetStatusDoNotDisturb(args.UserId)
|
||||
|
||||
return &model.CommandResponse{ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL, Text: args.T("api.command_dnd.success")}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
@@ -41,7 +42,7 @@ func (*EchoProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command
|
||||
}
|
||||
}
|
||||
|
||||
func (*EchoProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (*EchoProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
if message == "" {
|
||||
return &model.CommandResponse{Text: args.T("api.command_echo.message.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
@@ -89,7 +90,7 @@ func (*EchoProvider) DoCommand(a *app.App, args *model.CommandArgs, message stri
|
||||
|
||||
time.Sleep(time.Duration(delay) * time.Second)
|
||||
|
||||
if _, err := a.CreatePostMissingChannel(post, true); err != nil {
|
||||
if _, err := a.CreatePostMissingChannel(c, post, true); err != nil {
|
||||
mlog.Error("Unable to create /echo post.", mlog.Err(err))
|
||||
}
|
||||
})
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strconv"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
)
|
||||
@@ -53,11 +54,11 @@ func (*CollapseProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Com
|
||||
}
|
||||
}
|
||||
|
||||
func (*ExpandProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (*ExpandProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
return setCollapsePreference(a, args, false)
|
||||
}
|
||||
|
||||
func (*CollapseProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (*CollapseProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
return setCollapsePreference(a, args, true)
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
@@ -38,7 +39,7 @@ func (*groupmsgProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Com
|
||||
}
|
||||
}
|
||||
|
||||
func (*groupmsgProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (*groupmsgProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
targetUsers := map[string]*model.User{}
|
||||
targetUsersSlice := []string{args.UserId}
|
||||
invalidUsernames := []string{}
|
||||
@@ -82,7 +83,7 @@ func (*groupmsgProvider) DoCommand(a *app.App, args *model.CommandArgs, message
|
||||
}
|
||||
|
||||
if len(targetUsersSlice) == 2 {
|
||||
return app.GetCommandProvider("msg").DoCommand(a, args, fmt.Sprintf("%s %s", targetUsers[targetUsersSlice[1]].Username, parsedMessage))
|
||||
return app.GetCommandProvider("msg").DoCommand(a, c, args, fmt.Sprintf("%s %s", targetUsers[targetUsersSlice[1]].Username, parsedMessage))
|
||||
}
|
||||
|
||||
if len(targetUsersSlice) < model.CHANNEL_GROUP_MIN_USERS {
|
||||
@@ -126,7 +127,7 @@ func (*groupmsgProvider) DoCommand(a *app.App, args *model.CommandArgs, message
|
||||
post.Message = parsedMessage
|
||||
post.ChannelId = groupChannel.Id
|
||||
post.UserId = args.UserId
|
||||
if _, err := a.CreatePostMissingChannel(post, true); err != nil {
|
||||
if _, err := a.CreatePostMissingChannel(c, post, true); err != nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_groupmsg.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ func TestGroupMsgProvider(t *testing.T) {
|
||||
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{
|
||||
resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: team.Id,
|
||||
@@ -83,7 +83,7 @@ func TestGroupMsgProvider(t *testing.T) {
|
||||
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{
|
||||
resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: team.Id,
|
||||
@@ -95,7 +95,7 @@ func TestGroupMsgProvider(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("Check with permission to create a GM channel.", func(t *testing.T) {
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: team.Id,
|
||||
@@ -108,7 +108,7 @@ func TestGroupMsgProvider(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("Check without permission to post to an existing GM channel.", func(t *testing.T) {
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
SiteURL: "http://test.url",
|
||||
TeamId: team.Id,
|
||||
|
||||
@@ -5,6 +5,7 @@ package slashcommands
|
||||
|
||||
import (
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
)
|
||||
@@ -33,7 +34,7 @@ func (h *HelpProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comma
|
||||
}
|
||||
}
|
||||
|
||||
func (h *HelpProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (h *HelpProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
helpLink := *a.Config().SupportSettings.HelpLink
|
||||
|
||||
if helpLink == "" {
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
@@ -38,7 +39,7 @@ func (*InviteProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comma
|
||||
}
|
||||
}
|
||||
|
||||
func (*InviteProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (*InviteProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
if message == "" {
|
||||
return &model.CommandResponse{
|
||||
Text: args.T("api.command_invite.missing_message.app_error"),
|
||||
@@ -140,7 +141,7 @@ func (*InviteProvider) DoCommand(a *app.App, args *model.CommandArgs, message st
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := a.AddChannelMember(userProfile.Id, channelToJoin, app.ChannelMemberOpts{
|
||||
if _, err := a.AddChannelMember(c, userProfile.Id, channelToJoin, app.ChannelMemberOpts{
|
||||
UserRequestorID: args.UserId,
|
||||
}); err != nil {
|
||||
var text string
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
@@ -41,7 +42,7 @@ func (*InvitePeopleProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model
|
||||
}
|
||||
}
|
||||
|
||||
func (*InvitePeopleProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (*InvitePeopleProvider) DoCommand(a *app.App, c *request.Context, 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}
|
||||
}
|
||||
|
||||
@@ -32,11 +32,11 @@ func TestInvitePeopleProvider(t *testing.T) {
|
||||
UserId: notTeamUser.Id,
|
||||
}
|
||||
|
||||
actual := cmd.DoCommand(th.App, args, model.NewId()+"@simulator.amazonses.com")
|
||||
actual := cmd.DoCommand(th.App, th.Context, 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")
|
||||
actual = cmd.DoCommand(th.App, th.Context, args, model.NewId()+"@simulator.amazonses.com")
|
||||
assert.Equal(t, "api.command.invite_people.sent", actual.Text)
|
||||
}
|
||||
|
||||
@@ -26,34 +26,34 @@ func TestInviteProvider(t *testing.T) {
|
||||
th.linkUserToTeam(basicUser3, th.BasicTeam)
|
||||
basicUser4 := th.createUser()
|
||||
deactivatedUser := th.createUser()
|
||||
th.App.UpdateActive(deactivatedUser, false)
|
||||
th.App.UpdateActive(th.Context, deactivatedUser, false)
|
||||
|
||||
var err *model.AppError
|
||||
_, err = th.App.CreateBot(&model.Bot{
|
||||
_, err = th.App.CreateBot(th.Context, &model.Bot{
|
||||
Username: "bot1",
|
||||
OwnerId: basicUser3.Id,
|
||||
Description: "a test bot",
|
||||
})
|
||||
require.Nil(t, err)
|
||||
|
||||
bot2, err := th.App.CreateBot(&model.Bot{
|
||||
bot2, err := th.App.CreateBot(th.Context, &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)
|
||||
_, _, err = th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, bot2.UserId, basicUser3.Id)
|
||||
require.Nil(t, err)
|
||||
|
||||
bot3, err := th.App.CreateBot(&model.Bot{
|
||||
bot3, err := th.App.CreateBot(th.Context, &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)
|
||||
_, _, err = th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, bot3.UserId, basicUser3.Id)
|
||||
require.Nil(t, err)
|
||||
err = th.App.RemoveUserFromTeam(th.BasicTeam.Id, bot3.UserId, basicUser3.Id)
|
||||
err = th.App.RemoveUserFromTeam(th.Context, th.BasicTeam.Id, bot3.UserId, basicUser3.Id)
|
||||
require.Nil(t, err)
|
||||
|
||||
InviteP := InviteProvider{}
|
||||
@@ -73,7 +73,7 @@ func TestInviteProvider(t *testing.T) {
|
||||
deactivatedUserPublicChannel := "@" + deactivatedUser.Username + " ~" + channel.Name
|
||||
|
||||
groupChannel := th.createChannel(th.BasicTeam, model.CHANNEL_PRIVATE)
|
||||
_, err = th.App.AddChannelMember(th.BasicUser.Id, groupChannel, app.ChannelMemberOpts{})
|
||||
_, err = th.App.AddChannelMember(th.Context, th.BasicUser.Id, groupChannel, app.ChannelMemberOpts{})
|
||||
require.Nil(t, err)
|
||||
groupChannel.GroupConstrained = model.NewBool(true)
|
||||
groupChannel, _ = th.App.UpdateChannel(groupChannel)
|
||||
@@ -169,7 +169,7 @@ func TestInviteProvider(t *testing.T) {
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
actual := InviteP.DoCommand(th.App, args, test.msg).Text
|
||||
actual := InviteP.DoCommand(th.App, th.Context, args, test.msg).Text
|
||||
assert.Equal(t, test.expected, actual)
|
||||
})
|
||||
}
|
||||
@@ -181,8 +181,8 @@ func TestInviteGroup(t *testing.T) {
|
||||
|
||||
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)
|
||||
_, _ = th.App.AddTeamMember(th.Context, th.BasicTeam.Id, th.BasicUser.Id)
|
||||
_, err = th.App.AddTeamMember(th.Context, th.BasicTeam.Id, th.BasicUser2.Id)
|
||||
require.Nil(t, err)
|
||||
th.BasicTeam, _ = th.App.UpdateTeam(th.BasicTeam)
|
||||
|
||||
@@ -225,7 +225,7 @@ func TestInviteGroup(t *testing.T) {
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
actual := InviteP.DoCommand(th.App, args, test.msg).Text
|
||||
actual := InviteP.DoCommand(th.App, th.Context, args, test.msg).Text
|
||||
assert.Equal(t, test.expected, actual)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
)
|
||||
@@ -36,7 +37,7 @@ func (*JoinProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command
|
||||
}
|
||||
}
|
||||
|
||||
func (*JoinProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (*JoinProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
channelName := strings.ToLower(message)
|
||||
|
||||
if strings.HasPrefix(message, "~") {
|
||||
@@ -65,7 +66,7 @@ func (*JoinProvider) DoCommand(a *app.App, args *model.CommandArgs, message stri
|
||||
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 {
|
||||
if appErr := a.JoinChannel(c, channel, args.UserId); appErr != nil {
|
||||
return &model.CommandResponse{Text: args.T("api.command_join.fail.app_error"), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ func TestJoinCommandNoChannel(t *testing.T) {
|
||||
}
|
||||
|
||||
cmd := &JoinProvider{}
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
UserId: th.BasicUser2.Id,
|
||||
SiteURL: "http://test.url",
|
||||
@@ -39,7 +39,7 @@ func TestJoinCommandForExistingChannel(t *testing.T) {
|
||||
t.SkipNow()
|
||||
}
|
||||
|
||||
channel2, _ := th.App.CreateChannel(&model.Channel{
|
||||
channel2, _ := th.App.CreateChannel(th.Context, &model.Channel{
|
||||
DisplayName: "AA",
|
||||
Name: "aa" + model.NewId() + "a",
|
||||
Type: model.CHANNEL_OPEN,
|
||||
@@ -48,7 +48,7 @@ func TestJoinCommandForExistingChannel(t *testing.T) {
|
||||
}, false)
|
||||
|
||||
cmd := &JoinProvider{}
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
UserId: th.BasicUser2.Id,
|
||||
SiteURL: "http://test.url",
|
||||
@@ -67,7 +67,7 @@ func TestJoinCommandWithTilde(t *testing.T) {
|
||||
t.SkipNow()
|
||||
}
|
||||
|
||||
channel2, _ := th.App.CreateChannel(&model.Channel{
|
||||
channel2, _ := th.App.CreateChannel(th.Context, &model.Channel{
|
||||
DisplayName: "AA",
|
||||
Name: "aa" + model.NewId() + "a",
|
||||
Type: model.CHANNEL_OPEN,
|
||||
@@ -76,7 +76,7 @@ func TestJoinCommandWithTilde(t *testing.T) {
|
||||
}, false)
|
||||
|
||||
cmd := &JoinProvider{}
|
||||
resp := cmd.DoCommand(th.App, &model.CommandArgs{
|
||||
resp := cmd.DoCommand(th.App, th.Context, &model.CommandArgs{
|
||||
T: i18n.IdentityTfunc(),
|
||||
UserId: th.BasicUser2.Id,
|
||||
SiteURL: "http://test.url",
|
||||
@@ -91,7 +91,7 @@ func TestJoinCommandPermissions(t *testing.T) {
|
||||
th := setup(t).initBasic()
|
||||
defer th.tearDown()
|
||||
|
||||
channel2, _ := th.App.CreateChannel(&model.Channel{
|
||||
channel2, _ := th.App.CreateChannel(th.Context, &model.Channel{
|
||||
DisplayName: "AA",
|
||||
Name: "aa" + model.NewId() + "a",
|
||||
Type: model.CHANNEL_OPEN,
|
||||
@@ -111,7 +111,7 @@ func TestJoinCommandPermissions(t *testing.T) {
|
||||
TeamId: th.BasicTeam.Id,
|
||||
}
|
||||
|
||||
actual := cmd.DoCommand(th.App, args, "~"+channel2.Name).Text
|
||||
actual := cmd.DoCommand(th.App, th.Context, args, "~"+channel2.Name).Text
|
||||
assert.Equal(t, "api.command_join.fail.app_error", actual)
|
||||
|
||||
// Try a public channel with permission.
|
||||
@@ -122,11 +122,11 @@ func TestJoinCommandPermissions(t *testing.T) {
|
||||
TeamId: th.BasicTeam.Id,
|
||||
}
|
||||
|
||||
actual = cmd.DoCommand(th.App, args, "~"+channel2.Name).Text
|
||||
actual = cmd.DoCommand(th.App, th.Context, args, "~"+channel2.Name).Text
|
||||
assert.Equal(t, "", actual)
|
||||
|
||||
// Try a private channel *without* permission.
|
||||
channel3, _ := th.App.CreateChannel(&model.Channel{
|
||||
channel3, _ := th.App.CreateChannel(th.Context, &model.Channel{
|
||||
DisplayName: "BB",
|
||||
Name: "aa" + model.NewId() + "a",
|
||||
Type: model.CHANNEL_PRIVATE,
|
||||
@@ -141,6 +141,6 @@ func TestJoinCommandPermissions(t *testing.T) {
|
||||
TeamId: th.BasicTeam.Id,
|
||||
}
|
||||
|
||||
actual = cmd.DoCommand(th.App, args, "~"+channel3.Name).Text
|
||||
actual = cmd.DoCommand(th.App, th.Context, args, "~"+channel3.Name).Text
|
||||
assert.Equal(t, "api.command_join.fail.app_error", actual)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ package slashcommands
|
||||
|
||||
import (
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
)
|
||||
@@ -33,7 +34,7 @@ func (*LeaveProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comman
|
||||
}
|
||||
}
|
||||
|
||||
func (*LeaveProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (*LeaveProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
var channel *model.Channel
|
||||
var noChannelErr *model.AppError
|
||||
if channel, noChannelErr = a.GetChannel(args.ChannelId); noChannelErr != nil {
|
||||
@@ -45,7 +46,7 @@ func (*LeaveProvider) DoCommand(a *app.App, args *model.CommandArgs, message str
|
||||
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)
|
||||
err = a.LeaveChannel(c, 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}
|
||||
|
||||
@@ -19,7 +19,7 @@ func TestLeaveProviderDoCommand(t *testing.T) {
|
||||
|
||||
lp := LeaveProvider{}
|
||||
|
||||
publicChannel, _ := th.App.CreateChannel(&model.Channel{
|
||||
publicChannel, _ := th.App.CreateChannel(th.Context, &model.Channel{
|
||||
DisplayName: "AA",
|
||||
Name: "aa" + model.NewId() + "a",
|
||||
Type: model.CHANNEL_OPEN,
|
||||
@@ -27,7 +27,7 @@ func TestLeaveProviderDoCommand(t *testing.T) {
|
||||
CreatorId: th.BasicUser.Id,
|
||||
}, false)
|
||||
|
||||
privateChannel, _ := th.App.CreateChannel(&model.Channel{
|
||||
privateChannel, _ := th.App.CreateChannel(th.Context, &model.Channel{
|
||||
DisplayName: "BB",
|
||||
Name: "aa" + model.NewId() + "a",
|
||||
Type: model.CHANNEL_OPEN,
|
||||
@@ -40,10 +40,10 @@ func TestLeaveProviderDoCommand(t *testing.T) {
|
||||
|
||||
guest := th.createGuest()
|
||||
|
||||
th.App.AddUserToTeam(th.BasicTeam.Id, th.BasicUser.Id, th.BasicUser.Id)
|
||||
th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, th.BasicUser.Id, th.BasicUser.Id)
|
||||
th.App.AddUserToChannel(th.BasicUser, publicChannel, false)
|
||||
th.App.AddUserToChannel(th.BasicUser, privateChannel, false)
|
||||
th.App.AddUserToTeam(th.BasicTeam.Id, guest.Id, guest.Id)
|
||||
th.App.AddUserToTeam(th.Context, th.BasicTeam.Id, guest.Id, guest.Id)
|
||||
th.App.AddUserToChannel(guest, publicChannel, false)
|
||||
th.App.AddUserToChannel(guest, defaultChannel, false)
|
||||
|
||||
@@ -52,7 +52,7 @@ func TestLeaveProviderDoCommand(t *testing.T) {
|
||||
UserId: th.BasicUser.Id,
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
}
|
||||
actual := lp.DoCommand(th.App, args, "")
|
||||
actual := lp.DoCommand(th.App, th.Context, args, "")
|
||||
assert.Equal(t, "api.command_leave.fail.app_error", actual.Text)
|
||||
assert.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, actual.ResponseType)
|
||||
})
|
||||
@@ -63,7 +63,7 @@ func TestLeaveProviderDoCommand(t *testing.T) {
|
||||
ChannelId: publicChannel.Id,
|
||||
T: func(s string, args ...interface{}) string { return s },
|
||||
}
|
||||
actual := lp.DoCommand(th.App, args, "")
|
||||
actual := lp.DoCommand(th.App, th.Context, args, "")
|
||||
assert.Equal(t, "api.command_leave.fail.app_error", actual.Text)
|
||||
assert.Equal(t, model.COMMAND_RESPONSE_TYPE_EPHEMERAL, actual.ResponseType)
|
||||
})
|
||||
@@ -76,7 +76,7 @@ func TestLeaveProviderDoCommand(t *testing.T) {
|
||||
TeamId: th.BasicTeam.Id,
|
||||
SiteURL: "http://localhost:8065",
|
||||
}
|
||||
actual := lp.DoCommand(th.App, args, "")
|
||||
actual := lp.DoCommand(th.App, th.Context, 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)
|
||||
@@ -94,7 +94,7 @@ func TestLeaveProviderDoCommand(t *testing.T) {
|
||||
TeamId: th.BasicTeam.Id,
|
||||
SiteURL: "http://localhost:8065",
|
||||
}
|
||||
actual := lp.DoCommand(th.App, args, "")
|
||||
actual := lp.DoCommand(th.App, th.Context, args, "")
|
||||
assert.Equal(t, "", actual.Text)
|
||||
})
|
||||
|
||||
@@ -106,7 +106,7 @@ func TestLeaveProviderDoCommand(t *testing.T) {
|
||||
TeamId: th.BasicTeam.Id,
|
||||
SiteURL: "http://localhost:8065",
|
||||
}
|
||||
actual := lp.DoCommand(th.App, args, "")
|
||||
actual := lp.DoCommand(th.App, th.Context, args, "")
|
||||
assert.Equal(t, "api.channel.leave.default.app_error", actual.Text)
|
||||
})
|
||||
|
||||
@@ -118,7 +118,7 @@ func TestLeaveProviderDoCommand(t *testing.T) {
|
||||
TeamId: th.BasicTeam.Id,
|
||||
SiteURL: "http://localhost:8065",
|
||||
}
|
||||
actual := lp.DoCommand(th.App, args, "")
|
||||
actual := lp.DoCommand(th.App, th.Context, args, "")
|
||||
assert.Equal(t, "", actual.Text)
|
||||
assert.Equal(t, args.SiteURL+"/"+th.BasicTeam.Name+"/channels/"+publicChannel.Name, actual.GotoLocation)
|
||||
assert.Equal(t, "", actual.ResponseType)
|
||||
@@ -136,7 +136,7 @@ func TestLeaveProviderDoCommand(t *testing.T) {
|
||||
TeamId: th.BasicTeam.Id,
|
||||
SiteURL: "http://localhost:8065",
|
||||
}
|
||||
actual := lp.DoCommand(th.App, args, "")
|
||||
actual := lp.DoCommand(th.App, th.Context, args, "")
|
||||
assert.Equal(t, "", actual.Text)
|
||||
assert.Equal(t, args.SiteURL+"/", actual.GotoLocation)
|
||||
assert.Equal(t, "", actual.ResponseType)
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/mlog"
|
||||
@@ -108,8 +109,8 @@ func (*LoadTestProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Com
|
||||
}
|
||||
}
|
||||
|
||||
func (lt *LoadTestProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
commandResponse, err := lt.doCommand(a, args, message)
|
||||
func (lt *LoadTestProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
commandResponse, err := lt.doCommand(a, c, args, message)
|
||||
if err != nil {
|
||||
mlog.Error("failed command /"+CmdTest, mlog.Err(err))
|
||||
}
|
||||
@@ -117,34 +118,34 @@ func (lt *LoadTestProvider) DoCommand(a *app.App, args *model.CommandArgs, messa
|
||||
return commandResponse
|
||||
}
|
||||
|
||||
func (lt *LoadTestProvider) doCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
func (lt *LoadTestProvider) doCommand(a *app.App, c *request.Context, 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 lt.SetupCommand(a, args, message)
|
||||
return lt.SetupCommand(a, c, args, message)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "users") {
|
||||
return lt.UsersCommand(a, args, message)
|
||||
return lt.UsersCommand(a, c, args, message)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "activate_user") {
|
||||
return lt.ActivateUserCommand(a, args, message)
|
||||
return lt.ActivateUserCommand(a, c, args, message)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "deactivate_user") {
|
||||
return lt.DeActivateUserCommand(a, args, message)
|
||||
return lt.DeActivateUserCommand(a, c, args, message)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "channels") {
|
||||
return lt.ChannelsCommand(a, args, message)
|
||||
return lt.ChannelsCommand(a, c, args, message)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "posts") {
|
||||
return lt.PostsCommand(a, args, message)
|
||||
return lt.PostsCommand(a, c, args, message)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "post") {
|
||||
@@ -152,15 +153,15 @@ func (lt *LoadTestProvider) doCommand(a *app.App, args *model.CommandArgs, messa
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "threaded_post") {
|
||||
return lt.ThreadedPostCommand(a, args, message)
|
||||
return lt.ThreadedPostCommand(a, c, args, message)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "url") {
|
||||
return lt.UrlCommand(a, args, message)
|
||||
return lt.UrlCommand(a, c, args, message)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(message, "json") {
|
||||
return lt.JsonCommand(a, args, message)
|
||||
return lt.JsonCommand(a, c, args, message)
|
||||
}
|
||||
|
||||
return lt.HelpCommand(args, message), nil
|
||||
@@ -170,7 +171,7 @@ func (*LoadTestProvider) HelpCommand(args *model.CommandArgs, message string) *m
|
||||
return &model.CommandResponse{Text: usage, ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}
|
||||
}
|
||||
|
||||
func (*LoadTestProvider) SetupCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
func (*LoadTestProvider) SetupCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
tokens := strings.Fields(strings.TrimPrefix(message, "setup"))
|
||||
doTeams := contains(tokens, "teams")
|
||||
doFuzz := contains(tokens, "fuzz")
|
||||
@@ -220,6 +221,7 @@ func (*LoadTestProvider) SetupCommand(a *app.App, args *model.CommandArgs, messa
|
||||
}
|
||||
environment, err := CreateTestEnvironmentWithTeams(
|
||||
a,
|
||||
c,
|
||||
client,
|
||||
utils.Range{Begin: numTeams, End: numTeams},
|
||||
utils.Range{Begin: numChannels, End: numChannels},
|
||||
@@ -243,6 +245,7 @@ func (*LoadTestProvider) SetupCommand(a *app.App, args *model.CommandArgs, messa
|
||||
|
||||
CreateTestEnvironmentInTeam(
|
||||
a,
|
||||
c,
|
||||
client,
|
||||
team,
|
||||
utils.Range{Begin: numChannels, End: numChannels},
|
||||
@@ -254,25 +257,25 @@ func (*LoadTestProvider) SetupCommand(a *app.App, args *model.CommandArgs, messa
|
||||
return &model.CommandResponse{Text: "Created environment", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
func (*LoadTestProvider) ActivateUserCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
func (*LoadTestProvider) ActivateUserCommand(a *app.App, c *request.Context, 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 {
|
||||
if err := a.UpdateUserActive(c, 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 (*LoadTestProvider) DeActivateUserCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
func (*LoadTestProvider) DeActivateUserCommand(a *app.App, c *request.Context, 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 {
|
||||
if err := a.UpdateUserActive(c, 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 (*LoadTestProvider) UsersCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
func (*LoadTestProvider) UsersCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
cmd := strings.TrimSpace(strings.TrimPrefix(message, "users"))
|
||||
|
||||
doFuzz := false
|
||||
@@ -294,14 +297,14 @@ func (*LoadTestProvider) UsersCommand(a *app.App, args *model.CommandArgs, messa
|
||||
client := model.NewAPIv4Client(args.SiteURL)
|
||||
userCreator := NewAutoUserCreator(a, client, team)
|
||||
userCreator.Fuzzy = doFuzz
|
||||
if _, err := userCreator.CreateTestUsers(usersr); err != nil {
|
||||
if _, err := userCreator.CreateTestUsers(c, usersr); err != nil {
|
||||
return &model.CommandResponse{Text: "Failed to add users: " + err.Error(), ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
|
||||
return &model.CommandResponse{Text: "Added users", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
func (*LoadTestProvider) ChannelsCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
func (*LoadTestProvider) ChannelsCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
cmd := strings.TrimSpace(strings.TrimPrefix(message, "channels"))
|
||||
|
||||
doFuzz := false
|
||||
@@ -322,14 +325,14 @@ func (*LoadTestProvider) ChannelsCommand(a *app.App, args *model.CommandArgs, me
|
||||
|
||||
channelCreator := NewAutoChannelCreator(a, team, args.UserId)
|
||||
channelCreator.Fuzzy = doFuzz
|
||||
if _, err := channelCreator.CreateTestChannels(channelsr); err != nil {
|
||||
if _, err := channelCreator.CreateTestChannels(c, 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 (*LoadTestProvider) ThreadedPostCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
func (*LoadTestProvider) ThreadedPostCommand(a *app.App, c *request.Context, 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 {
|
||||
@@ -344,18 +347,18 @@ func (*LoadTestProvider) ThreadedPostCommand(a *app.App, args *model.CommandArgs
|
||||
testPoster := NewAutoPostCreator(a, args.ChannelId, args.UserId)
|
||||
testPoster.Fuzzy = true
|
||||
testPoster.Users = usernames
|
||||
rpost, err2 := testPoster.CreateRandomPost()
|
||||
rpost, err2 := testPoster.CreateRandomPost(c)
|
||||
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)
|
||||
testPoster.CreateRandomPostNested(c, rpost.Id, rpost.Id)
|
||||
}
|
||||
|
||||
return &model.CommandResponse{Text: "Added threaded post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
func (*LoadTestProvider) PostsCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
func (*LoadTestProvider) PostsCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
cmd := strings.TrimSpace(strings.TrimPrefix(message, "posts"))
|
||||
|
||||
doFuzz := false
|
||||
@@ -396,7 +399,7 @@ func (*LoadTestProvider) PostsCommand(a *app.App, args *model.CommandArgs, messa
|
||||
numPosts := utils.RandIntFromRange(postsr)
|
||||
for i := 0; i < numPosts; i++ {
|
||||
testPoster.HasImage = (i < numImages)
|
||||
_, err := testPoster.CreateRandomPost()
|
||||
_, err := testPoster.CreateRandomPost(c)
|
||||
if err != nil {
|
||||
return &model.CommandResponse{Text: "Failed to add posts", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
@@ -457,7 +460,7 @@ func (*LoadTestProvider) PostCommand(a *app.App, args *model.CommandArgs, messag
|
||||
return &model.CommandResponse{Text: "Added a post to " + channel.DisplayName, ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
func (*LoadTestProvider) UrlCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
func (*LoadTestProvider) UrlCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
url := strings.TrimSpace(strings.TrimPrefix(message, "url"))
|
||||
if url == "" {
|
||||
return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
@@ -503,7 +506,7 @@ func (*LoadTestProvider) UrlCommand(a *app.App, args *model.CommandArgs, message
|
||||
post.ChannelId = args.ChannelId
|
||||
post.UserId = args.UserId
|
||||
|
||||
if _, err := a.CreatePostMissingChannel(post, false); err != nil {
|
||||
if _, err := a.CreatePostMissingChannel(c, post, false); err != nil {
|
||||
return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
}
|
||||
@@ -511,7 +514,7 @@ func (*LoadTestProvider) UrlCommand(a *app.App, args *model.CommandArgs, message
|
||||
return &model.CommandResponse{Text: "Loaded data", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
}
|
||||
|
||||
func (*LoadTestProvider) JsonCommand(a *app.App, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
func (*LoadTestProvider) JsonCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) (*model.CommandResponse, error) {
|
||||
url := strings.TrimSpace(strings.TrimPrefix(message, "json"))
|
||||
if url == "" {
|
||||
return &model.CommandResponse{Text: "Command must contain a url", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, nil
|
||||
@@ -549,7 +552,7 @@ func (*LoadTestProvider) JsonCommand(a *app.App, args *model.CommandArgs, messag
|
||||
post.Message = message
|
||||
}
|
||||
|
||||
if _, err := a.CreatePostMissingChannel(post, false); err != nil {
|
||||
if _, err := a.CreatePostMissingChannel(c, post, false); err != nil {
|
||||
return &model.CommandResponse{Text: "Unable to create post", ResponseType: model.COMMAND_RESPONSE_TYPE_EPHEMERAL}, err
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ package slashcommands
|
||||
|
||||
import (
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
)
|
||||
@@ -34,7 +35,7 @@ func (*LogoutProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Comma
|
||||
}
|
||||
}
|
||||
|
||||
func (*LogoutProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (*LogoutProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
// Actual logout is handled client side.
|
||||
return &model.CommandResponse{GotoLocation: "/login"}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ package slashcommands
|
||||
|
||||
import (
|
||||
"github.com/mattermost/mattermost-server/v5/app"
|
||||
"github.com/mattermost/mattermost-server/v5/app/request"
|
||||
"github.com/mattermost/mattermost-server/v5/model"
|
||||
"github.com/mattermost/mattermost-server/v5/shared/i18n"
|
||||
)
|
||||
@@ -34,7 +35,7 @@ func (*MeProvider) GetCommand(a *app.App, T i18n.TranslateFunc) *model.Command {
|
||||
}
|
||||
}
|
||||
|
||||
func (*MeProvider) DoCommand(a *app.App, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
func (*MeProvider) DoCommand(a *app.App, c *request.Context, args *model.CommandArgs, message string) *model.CommandResponse {
|
||||
return &model.CommandResponse{
|
||||
ResponseType: model.COMMAND_RESPONSE_TYPE_IN_CHANNEL,
|
||||
Type: model.POST_ME,
|
||||
|
||||
Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше
Ссылка в новой задаче
Block a user