Feature scheduled messages (#28932)
* Create scheduled post api (#27920) * Added migration files for Postgres * Added migrations for MySQL * Added store method * Added API and store tests * Renamed migration after syncing with master * Added app layer tests * API is ready * API is ready * API is ready * Renamed migration after syncing with master * Updated migration list * Fixed retry layer tests * Allowed posts with empty messages * Review fixes * Reverted an incorrect change * Renamed migration and fixed ID assignment * CI * Send post button changes (#28019) * added Split button * WIP * Added core menu options * WIP * WIP * WIP * Handled displaying error in creating scheduled post * lint fixes * webapp i18n fix * Review fixes * Fixed a webapp test * A few more fixes * Removed a duplicate comment * Scheduled post job (#28088) * Added the job function * Added query for fetching scheduled posts for pricessing * WIP * WIP * WIP * WIP * WIP * WIP * Reafactoring of scheduled post job * Lint fixes * Updated i18n files * FInishing touches * Added tests for GetScheduledPosts * Added tests for PermanentlyDeleteScheduledPosts * Updated all layer * Some changes as discussed with team * Added tests for UpdatedScheduledPost * Code review refactoring * Added job test * MM-60120 - Custom time selection (#28120) * Added a common date time picker modal and used it for post reminder * Added a common date time picker modal and used it for post reminderggp * Added modal for custom schedule time and fixed TZ issue * WIP * Removed event from useSubmit hook * Removed event from useSubmit hook * Added timezone handling * fixed type error * Updated i18n strings * Minor cleanup * updated snapshots * review fixes * Handled event * Supported for having a DM thread open in RHS while in a regular channel * Review fixes * MM-60136 - Scheduled messages tab (#28133) * WIP * WIP * Created Tabs and Tab wrapper with added styling * Added API to get scheduled posts * WIP * Displated scheduled post count * i18n fix * Added tests * Handled asetting active tab absed on URL: * Reverted unintended change * Added API to client ad OpenAPI specs * Renamed file * Adding fileinfo to schedule posts * Partial review fixes * Made get scheduled post API return posts by teamID * review fixes * Moved scheduled post redux code to MM-redux package * Usedd selector factory * WIP: * WIP: * Lint fix * Fixed an incorrect openapi spec file * Removed redundent permission check * Clreaed scheduled post data on logout * Removed unused i18n string: * lint fix * Render scheduled posts (#28208) * WIP * WIP * Created Tabs and Tab wrapper with added styling * Added API to get scheduled posts * WIP * Displated scheduled post count * i18n fix * Added tests * Handled asetting active tab absed on URL: * Reverted unintended change * Added API to client ad OpenAPI specs * Renamed file * Created common component for draft list item * WIP * WIP * Adding fileinfo to schedule posts * Basic rendering * Added count badge to tabs * WIP * Made the Drafts LHS iteam appear if no drafts exist but scheduled posts do * Fixed icon size * Partial review fixes * Made get scheduled post API return posts by teamID * Handled initial vs team switch load * Displayed scheduled date in panel header * Added error message and error indiocator * WIP * review fixes * WIP Adding error reason tag * Added error codes * Moved scheduled post redux code to MM-redux package * Usedd selector factory * WIP: * WIP: * Lint fix * Fixed an incorrect openapi spec file * Removed redundent permission check * Clreaed scheduled post data on logout * Removed unused i18n string: * lint fix * Opened rescheduling modal * Updated graphic for empty state of schduled post list * Added delete scheduled post option and modal * Badge and timezone fix * WIP: * Added send now confirmation modal * lint * Webapp i18n fix * Fixed webapp test * Fixed a bug where DM/GM scheduled posts weren't immideatly showing up in UI * Minor fixes * WIP * Review fixes * Review fixes * Optimisations * Fixed reducer name * Moment optimizatin * Updated route check * MM-60144 - added API to update a scheduled post (#28248) * WIP * Added api and ap layer for update scheduled post ̛̦̄ * Added API to OpenAI specs, Go client and TS client * removed permissio check * Added tests * Fixed tests * Added PreUpdate method on scheduled post model * MM-60131 - Reschedule post integration (#28281) * Handled rescheduling post in webapp * Added error handling * MM-60146 - Delete scheduled post api (#28265) * WIP * Added api and ap layer for update scheduled post ̛̦̄ * Added API to OpenAI specs, Go client and TS client * removed permissio check * Added tests * Fixed tests * Added PreUpdate method on scheduled post model * Added delete scheduled post API * Added API to Go client and OpenAPI specs * Added API to TS client * Added tests * CI * Rmeoved two incorrect code comments * MM-60653 - Integrated delete scheduled post API (#28296) * Integrated delete scheduled apost API * Lint fix * Review fixes * Excluded draft checks from scheduled posts (#28370) * Excluded draft checks from scheduled posts * Added a removed todo * MM-60125 - Scheduled post channel indicator (#28320) * Integrated delete scheduled apost API * Lint fix * Added state for storing scheduled posts by channel ID * Refactored redux store to store scheudled posts by ID, thens tore IDs everywhere * Refactored redux store to store scheudled posts by ID, thens tore IDs everywhere * WIP * Added scheduled post indiocator * Handled single and multiple scheudled posts * Review fixes * Fixed styling and handled center channel, RHS and threads view * Lint fix * i18n fix * Fixed a cycling dependency * Lint fix * Added some more comments * Updated styling * Review fixes * Added common component for remote user time and scheduled post indicator * Updated scheduled post count * Minor change * Moved CSS code around * Fixed a bug where files in scheduled post didn't show up until refresh (#28359) --------- Co-authored-by: Daniel Espino García <larkox@gmail.com> * Scheduled post config (#28485) * Added config * Added config on server and webapp side * Added config check in server and webapp * Added license check * Added license check * Added placeholder help text * Added license check to job * Fixed job test * Review fixes * Updated English text * Review fixes * MM-60118 - Added index on ScheduledPosts table (#28579) * Added index * Updated indexes * Scheduled posts misc fixes (#28625) * Added detailed logging for scheduled post job * Limited scheduled posts processing to 24 hours * Marked old scheduled posts as unable to send * Added t5ests * converted some logs to trace level * Fixed a bug causing error message to show up on deleting a scheduled post in a deleted thread (#28630) * Fixed scheduled posts link in RHS (#28659) * Fixed scheduled posts link in RHS * Review fixes * Fix permission name in scheduled posts by team (#28580) * Fix permission name * fix wording --------- Co-authored-by: Mattermost Build <build@mattermost.com> * FIxed width of generic modal header to fix browser channel modal (#28639) * Only consider error-free scheduled posts for indicator in channel and RHS (#28683) * Show only errro free scheudled posts in post box indicator * Fixed a bug to handle no scheduled posts * Fixed draft and scheudled post UI in mobile view (#28680) * MM-60873 and MM-60872 - Fixed a bug with updating scheduled posts (#28656) * Fixed a bug with updating scheduled posts * Better selectors * MOved shceuled post message length validation to app layer * MM-60732 - Scheduled posts channel link now takes you to the first scheduled post in channel/thread in list (#28768) * Ordered scheudle dposts by schgeudled at nad create at * Ordered in client * Added scroll to target * Removed classname prop * Fixed tests * Added doc * Import fix * MM-60961 - Fixed a bug where API used incoming create at date for scheduled post (#28703) * Fixed a bug where API used incoming create at date for scheduled post * Stopped sending created at value for scheduled post * MM-60785 - Fixed a bug where scheduled posts of channel we are no longer member of didn't show up (#28637) * Fixed a bug where scheduled posts of channel we are no longer member of didn't show up * Added a comment * CI * Used data loader to optimise laoding missing channels * Minor refactoring * MM-60963 - Added common checks for post and scheduled posts (#28713) * Added commen checks for post and scheuled posts * Sanitised scheduled posts * Fixed tests * Splitted post checks into app and context functions * Added checks on scheduiled posts job as well: * i18n fix * Fixed a test * Renamed a func * removed duplicate check * Scheduled posts UI fixes (#28828) * Fixed send button and time picker borders * Fixed center alignment of time picker * Removed on for today and tomorrow * Lint fix * Date time modal hover state fix * Badge fix * Fixed a mnerge issue * Scheduled Post send now and add schedule on draft (#28851) * Added send now option on scheduled posts * Minor refactoring * WIP * WIP * WIP * Lint fix * i18n fix * Snapshot update * Review fixes * Scheduled post inline editing (#28893) * Added send now option on scheduled posts * Minor refactoring * WIP * WIP * WIP * Lint fix * i18n fix * Snapshot update * Displayed editing component in scheduled post * Added handling for updating scheduled post * Handle events * Fixed escape key issue in scheudled post editing * Fixes * Displayed error message for editing error * Don't show mention warning * Handled dev mode (#28918) * MInor fixes * client fix * Fixes * CI * Removed dev mode behaviour temperorily (#29008) --------- Co-authored-by: Daniel Espino García <larkox@gmail.com> Co-authored-by: Eva Sarafianou <eva.sarafianou@gmail.com> Co-authored-by: Mattermost Build <build@mattermost.com>
Этот коммит содержится в:
коммит произвёл
GitHub
родитель
aaf9234c8e
Коммит
e281b3f37e
@@ -584,6 +584,7 @@ type AppIface interface {
|
||||
DeleteReactionForPost(c request.CTX, reaction *model.Reaction) *model.AppError
|
||||
DeleteRemoteCluster(remoteClusterId string) (bool, *model.AppError)
|
||||
DeleteRetentionPolicy(policyID string) *model.AppError
|
||||
DeleteScheduledPost(rctx request.CTX, userId, scheduledPostId, connectionId string) (*model.ScheduledPost, *model.AppError)
|
||||
DeleteScheme(schemeId string) (*model.Scheme, *model.AppError)
|
||||
DeleteSharedChannelRemote(id string) (bool, error)
|
||||
DeleteSidebarCategory(c request.CTX, userID, teamID, categoryId string) *model.AppError
|
||||
@@ -870,6 +871,7 @@ type AppIface interface {
|
||||
GetUserByUsername(username string) (*model.User, *model.AppError)
|
||||
GetUserCountForReport(filter *model.UserReportOptions) (*int64, *model.AppError)
|
||||
GetUserForLogin(c request.CTX, id, loginId string) (*model.User, *model.AppError)
|
||||
GetUserTeamScheduledPosts(rctx request.CTX, userId, teamId string) ([]*model.ScheduledPost, *model.AppError)
|
||||
GetUserTermsOfService(userID string) (*model.UserTermsOfService, *model.AppError)
|
||||
GetUsers(userIDs []string) ([]*model.User, *model.AppError)
|
||||
GetUsersByGroupChannelIds(c request.CTX, channelIDs []string, asAdmin bool) (map[string][]*model.User, *model.AppError)
|
||||
@@ -1002,6 +1004,7 @@ type AppIface interface {
|
||||
PreparePostForClient(c request.CTX, originalPost *model.Post, isNewPost, isEditPost, includePriority bool) *model.Post
|
||||
PreparePostForClientWithEmbedsAndImages(c request.CTX, originalPost *model.Post, isNewPost, isEditPost, includePriority bool) *model.Post
|
||||
PreparePostListForClient(c request.CTX, originalList *model.PostList) *model.PostList
|
||||
ProcessScheduledPosts(rctx request.CTX)
|
||||
ProcessSlackText(text string) string
|
||||
Publish(message *model.WebSocketEvent)
|
||||
PublishUserTyping(userID, channelID, parentId string) *model.AppError
|
||||
@@ -1067,6 +1070,7 @@ type AppIface interface {
|
||||
SaveComplianceReport(rctx request.CTX, job *model.Compliance) (*model.Compliance, *model.AppError)
|
||||
SaveReactionForPost(c request.CTX, reaction *model.Reaction) (*model.Reaction, *model.AppError)
|
||||
SaveReportChunk(format string, prefix string, count int, reportData []model.ReportableObject) *model.AppError
|
||||
SaveScheduledPost(rctx request.CTX, scheduledPost *model.ScheduledPost) (*model.ScheduledPost, *model.AppError)
|
||||
SaveSharedChannelRemote(remote *model.SharedChannelRemote) (*model.SharedChannelRemote, error)
|
||||
SaveUserTermsOfService(userID, termsOfServiceId string, accepted bool) *model.AppError
|
||||
SchemesIterator(scope string, batchSize int) func() []*model.Scheme
|
||||
@@ -1203,6 +1207,7 @@ type AppIface interface {
|
||||
UpdateRemoteCluster(rc *model.RemoteCluster) (*model.RemoteCluster, *model.AppError)
|
||||
UpdateRemoteClusterTopics(remoteClusterId string, topics string) (*model.RemoteCluster, *model.AppError)
|
||||
UpdateRole(role *model.Role) (*model.Role, *model.AppError)
|
||||
UpdateScheduledPost(rctx request.CTX, userId string, scheduledPost *model.ScheduledPost) (*model.ScheduledPost, *model.AppError)
|
||||
UpdateScheme(scheme *model.Scheme) (*model.Scheme, *model.AppError)
|
||||
UpdateSharedChannel(sc *model.SharedChannel) (*model.SharedChannel, error)
|
||||
UpdateSharedChannelRemoteCursor(id string, cursor model.GetPostsSinceForSyncCursor) error
|
||||
|
||||
@@ -77,7 +77,9 @@ type Channels struct {
|
||||
postReminderMut sync.Mutex
|
||||
postReminderTask *model.ScheduledTask
|
||||
|
||||
loginAttemptsMut sync.Mutex
|
||||
scheduledPostMut sync.Mutex
|
||||
scheduledPostTask *model.ScheduledTask
|
||||
loginAttemptsMut sync.Mutex
|
||||
}
|
||||
|
||||
func NewChannels(s *Server) (*Channels, error) {
|
||||
|
||||
@@ -3727,6 +3727,28 @@ func (a *OpenTracingAppLayer) DeleteRetentionPolicy(policyID string) *model.AppE
|
||||
return resultVar0
|
||||
}
|
||||
|
||||
func (a *OpenTracingAppLayer) DeleteScheduledPost(rctx request.CTX, userId string, scheduledPostId string, connectionId string) (*model.ScheduledPost, *model.AppError) {
|
||||
origCtx := a.ctx
|
||||
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteScheduledPost")
|
||||
|
||||
a.ctx = newCtx
|
||||
a.app.Srv().Store().SetContext(newCtx)
|
||||
defer func() {
|
||||
a.app.Srv().Store().SetContext(origCtx)
|
||||
a.ctx = origCtx
|
||||
}()
|
||||
|
||||
defer span.Finish()
|
||||
resultVar0, resultVar1 := a.app.DeleteScheduledPost(rctx, userId, scheduledPostId, connectionId)
|
||||
|
||||
if resultVar1 != nil {
|
||||
span.LogFields(spanlog.Error(resultVar1))
|
||||
ext.Error.Set(span, true)
|
||||
}
|
||||
|
||||
return resultVar0, resultVar1
|
||||
}
|
||||
|
||||
func (a *OpenTracingAppLayer) DeleteScheme(schemeId string) (*model.Scheme, *model.AppError) {
|
||||
origCtx := a.ctx
|
||||
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.DeleteScheme")
|
||||
@@ -10990,6 +11012,28 @@ func (a *OpenTracingAppLayer) GetUserStatusesByIds(userIDs []string) ([]*model.S
|
||||
return resultVar0, resultVar1
|
||||
}
|
||||
|
||||
func (a *OpenTracingAppLayer) GetUserTeamScheduledPosts(rctx request.CTX, userId string, teamId string) ([]*model.ScheduledPost, *model.AppError) {
|
||||
origCtx := a.ctx
|
||||
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUserTeamScheduledPosts")
|
||||
|
||||
a.ctx = newCtx
|
||||
a.app.Srv().Store().SetContext(newCtx)
|
||||
defer func() {
|
||||
a.app.Srv().Store().SetContext(origCtx)
|
||||
a.ctx = origCtx
|
||||
}()
|
||||
|
||||
defer span.Finish()
|
||||
resultVar0, resultVar1 := a.app.GetUserTeamScheduledPosts(rctx, userId, teamId)
|
||||
|
||||
if resultVar1 != nil {
|
||||
span.LogFields(spanlog.Error(resultVar1))
|
||||
ext.Error.Set(span, true)
|
||||
}
|
||||
|
||||
return resultVar0, resultVar1
|
||||
}
|
||||
|
||||
func (a *OpenTracingAppLayer) GetUserTermsOfService(userID string) (*model.UserTermsOfService, *model.AppError) {
|
||||
origCtx := a.ctx
|
||||
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.GetUserTermsOfService")
|
||||
@@ -13964,6 +14008,21 @@ func (a *OpenTracingAppLayer) PreparePostListForClient(c request.CTX, originalLi
|
||||
return resultVar0
|
||||
}
|
||||
|
||||
func (a *OpenTracingAppLayer) ProcessScheduledPosts(rctx request.CTX) {
|
||||
origCtx := a.ctx
|
||||
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ProcessScheduledPosts")
|
||||
|
||||
a.ctx = newCtx
|
||||
a.app.Srv().Store().SetContext(newCtx)
|
||||
defer func() {
|
||||
a.app.Srv().Store().SetContext(origCtx)
|
||||
a.ctx = origCtx
|
||||
}()
|
||||
|
||||
defer span.Finish()
|
||||
a.app.ProcessScheduledPosts(rctx)
|
||||
}
|
||||
|
||||
func (a *OpenTracingAppLayer) ProcessSlackAttachments(attachments []*model.SlackAttachment) []*model.SlackAttachment {
|
||||
origCtx := a.ctx
|
||||
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.ProcessSlackAttachments")
|
||||
@@ -15511,6 +15570,28 @@ func (a *OpenTracingAppLayer) SaveReportChunk(format string, prefix string, coun
|
||||
return resultVar0
|
||||
}
|
||||
|
||||
func (a *OpenTracingAppLayer) SaveScheduledPost(rctx request.CTX, scheduledPost *model.ScheduledPost) (*model.ScheduledPost, *model.AppError) {
|
||||
origCtx := a.ctx
|
||||
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveScheduledPost")
|
||||
|
||||
a.ctx = newCtx
|
||||
a.app.Srv().Store().SetContext(newCtx)
|
||||
defer func() {
|
||||
a.app.Srv().Store().SetContext(origCtx)
|
||||
a.ctx = origCtx
|
||||
}()
|
||||
|
||||
defer span.Finish()
|
||||
resultVar0, resultVar1 := a.app.SaveScheduledPost(rctx, scheduledPost)
|
||||
|
||||
if resultVar1 != nil {
|
||||
span.LogFields(spanlog.Error(resultVar1))
|
||||
ext.Error.Set(span, true)
|
||||
}
|
||||
|
||||
return resultVar0, resultVar1
|
||||
}
|
||||
|
||||
func (a *OpenTracingAppLayer) SaveSharedChannelRemote(remote *model.SharedChannelRemote) (*model.SharedChannelRemote, error) {
|
||||
origCtx := a.ctx
|
||||
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.SaveSharedChannelRemote")
|
||||
@@ -18690,6 +18771,28 @@ func (a *OpenTracingAppLayer) UpdateRole(role *model.Role) (*model.Role, *model.
|
||||
return resultVar0, resultVar1
|
||||
}
|
||||
|
||||
func (a *OpenTracingAppLayer) UpdateScheduledPost(rctx request.CTX, userId string, scheduledPost *model.ScheduledPost) (*model.ScheduledPost, *model.AppError) {
|
||||
origCtx := a.ctx
|
||||
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateScheduledPost")
|
||||
|
||||
a.ctx = newCtx
|
||||
a.app.Srv().Store().SetContext(newCtx)
|
||||
defer func() {
|
||||
a.app.Srv().Store().SetContext(origCtx)
|
||||
a.ctx = origCtx
|
||||
}()
|
||||
|
||||
defer span.Finish()
|
||||
resultVar0, resultVar1 := a.app.UpdateScheduledPost(rctx, userId, scheduledPost)
|
||||
|
||||
if resultVar1 != nil {
|
||||
span.LogFields(spanlog.Error(resultVar1))
|
||||
ext.Error.Set(span, true)
|
||||
}
|
||||
|
||||
return resultVar0, resultVar1
|
||||
}
|
||||
|
||||
func (a *OpenTracingAppLayer) UpdateScheme(scheme *model.Scheme) (*model.Scheme, *model.AppError) {
|
||||
origCtx := a.ctx
|
||||
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdateScheme")
|
||||
|
||||
118
server/channels/app/post_permission_utils.go
Обычный файл
118
server/channels/app/post_permission_utils.go
Обычный файл
@@ -0,0 +1,118 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
"github.com/mattermost/mattermost/server/public/shared/request"
|
||||
)
|
||||
|
||||
func PostPriorityCheckWithApp(where string, a AppIface, userId string, priority *model.PostPriority, rootId string) *model.AppError {
|
||||
user, appErr := a.GetUser(userId)
|
||||
if appErr != nil {
|
||||
return appErr
|
||||
}
|
||||
|
||||
isPostPriorityEnabled := a.IsPostPriorityEnabled()
|
||||
IsPersistentNotificationsEnabled := a.IsPersistentNotificationsEnabled()
|
||||
allowPersistentNotificationsForGuests := *a.Config().ServiceSettings.AllowPersistentNotificationsForGuests
|
||||
license := a.License()
|
||||
|
||||
appErr = postPriorityCheck(user, priority, rootId, isPostPriorityEnabled, IsPersistentNotificationsEnabled, allowPersistentNotificationsForGuests, license)
|
||||
if appErr != nil {
|
||||
appErr.Where = where
|
||||
return appErr
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func postPriorityCheck(
|
||||
user *model.User,
|
||||
priority *model.PostPriority,
|
||||
rootId string,
|
||||
isPostPriorityEnabled,
|
||||
isPersistentNotificationsEnabled,
|
||||
allowPersistentNotificationsForGuests bool,
|
||||
license *model.License,
|
||||
) *model.AppError {
|
||||
if priority == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
priorityForbiddenErr := model.NewAppError("", "api.post.post_priority.priority_post_not_allowed_for_user.request_error", nil, "userId="+user.Id, http.StatusForbidden)
|
||||
|
||||
if !isPostPriorityEnabled {
|
||||
return priorityForbiddenErr
|
||||
}
|
||||
|
||||
if rootId != "" {
|
||||
return model.NewAppError("", "api.post.post_priority.priority_post_only_allowed_for_root_post.request_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
if ack := priority.RequestedAck; ack != nil && *ack {
|
||||
licenseErr := model.MinimumProfessionalProvidedLicense(license)
|
||||
if licenseErr != nil {
|
||||
return licenseErr
|
||||
}
|
||||
}
|
||||
|
||||
if notification := priority.PersistentNotifications; notification != nil && *notification {
|
||||
licenseErr := model.MinimumProfessionalProvidedLicense(license)
|
||||
if licenseErr != nil {
|
||||
return licenseErr
|
||||
}
|
||||
if !isPersistentNotificationsEnabled {
|
||||
return priorityForbiddenErr
|
||||
}
|
||||
|
||||
if *priority.Priority != model.PostPriorityUrgent {
|
||||
return model.NewAppError("", "api.post.post_priority.urgent_persistent_notification_post.request_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
if !allowPersistentNotificationsForGuests {
|
||||
if user.IsGuest() {
|
||||
return priorityForbiddenErr
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func PostHardenedModeCheckWithApp(a AppIface, isIntegration bool, props model.StringInterface) *model.AppError {
|
||||
hardenedModeEnabled := *a.Config().ServiceSettings.ExperimentalEnableHardenedMode
|
||||
return postHardenedModeCheck(hardenedModeEnabled, isIntegration, props)
|
||||
}
|
||||
|
||||
func postHardenedModeCheck(hardenedModeEnabled, isIntegration bool, props model.StringInterface) *model.AppError {
|
||||
if hardenedModeEnabled {
|
||||
if reservedProps := model.ContainsIntegrationsReservedProps(props); len(reservedProps) > 0 && !isIntegration {
|
||||
return model.NewAppError("", "api.context.invalid_body_param.app_error", map[string]any{"Name": "props"}, fmt.Sprintf("Cannot use props reserved for integrations. props: %v", reservedProps), http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func userCreatePostPermissionCheckWithApp(c request.CTX, a AppIface, userId, channelId string) *model.AppError {
|
||||
hasPermission := false
|
||||
if a.HasPermissionToChannel(c, userId, channelId, model.PermissionCreatePost) {
|
||||
hasPermission = true
|
||||
} else if channel, err := a.GetChannel(c, channelId); err == nil {
|
||||
// Temporary permission check method until advanced permissions, please do not copy
|
||||
if channel.Type == model.ChannelTypeOpen && a.HasPermissionToTeam(c, userId, channel.TeamId, model.PermissionCreatePostPublic) {
|
||||
hasPermission = true
|
||||
}
|
||||
}
|
||||
|
||||
if !hasPermission {
|
||||
return model.MakePermissionErrorForUser(userId, []*model.Permission{model.PermissionCreatePost})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
112
server/channels/app/scheduled_post.go
Обычный файл
112
server/channels/app/scheduled_post.go
Обычный файл
@@ -0,0 +1,112 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
"github.com/mattermost/mattermost/server/public/shared/request"
|
||||
)
|
||||
|
||||
func (a *App) SaveScheduledPost(rctx request.CTX, scheduledPost *model.ScheduledPost) (*model.ScheduledPost, *model.AppError) {
|
||||
maxMessageLength := a.Srv().Store().ScheduledPost().GetMaxMessageSize()
|
||||
scheduledPost.PreSave()
|
||||
if validationErr := scheduledPost.IsValid(maxMessageLength); validationErr != nil {
|
||||
return nil, validationErr
|
||||
}
|
||||
|
||||
// validate the channel is not archived
|
||||
channel, appErr := a.GetChannel(rctx, scheduledPost.ChannelId)
|
||||
if appErr != nil {
|
||||
return nil, appErr
|
||||
}
|
||||
|
||||
if channel.DeleteAt > 0 {
|
||||
return nil, model.NewAppError("App.scheduledPostPreSaveChecks", "app.save_scheduled_post.channel_deleted.app_error", map[string]any{"user_id": scheduledPost.UserId, "channel_id": scheduledPost.ChannelId}, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
savedScheduledPost, err := a.Srv().Store().ScheduledPost().CreateScheduledPost(scheduledPost)
|
||||
if err != nil {
|
||||
return nil, model.NewAppError("App.ScheduledPost", "app.save_scheduled_post.save.app_error", map[string]any{"user_id": scheduledPost.UserId, "channel_id": scheduledPost.ChannelId}, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
// TODO: add WebSocket event broadcast here
|
||||
|
||||
return savedScheduledPost, nil
|
||||
}
|
||||
|
||||
func (a *App) GetUserTeamScheduledPosts(rctx request.CTX, userId, teamId string) ([]*model.ScheduledPost, *model.AppError) {
|
||||
scheduledPosts, err := a.Srv().Store().ScheduledPost().GetScheduledPostsForUser(userId, teamId)
|
||||
if err != nil {
|
||||
return nil, model.NewAppError("App.GetUserTeamScheduledPosts", "app.get_user_team_scheduled_posts.error", map[string]any{"user_id": userId, "team_id": teamId}, "", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
if scheduledPosts == nil {
|
||||
scheduledPosts = []*model.ScheduledPost{}
|
||||
}
|
||||
|
||||
for _, scheduledPost := range scheduledPosts {
|
||||
a.prepareDraftWithFileInfos(rctx, userId, &scheduledPost.Draft)
|
||||
}
|
||||
|
||||
return scheduledPosts, nil
|
||||
}
|
||||
|
||||
func (a *App) UpdateScheduledPost(rctx request.CTX, userId string, scheduledPost *model.ScheduledPost) (*model.ScheduledPost, *model.AppError) {
|
||||
maxMessageLength := a.Srv().Store().ScheduledPost().GetMaxMessageSize()
|
||||
scheduledPost.PreUpdate()
|
||||
if validationErr := scheduledPost.IsValid(maxMessageLength); validationErr != nil {
|
||||
return nil, validationErr
|
||||
}
|
||||
|
||||
// validate the scheduled post belongs to the said user
|
||||
existingScheduledPost, err := a.Srv().Store().ScheduledPost().Get(scheduledPost.Id)
|
||||
if err != nil {
|
||||
return nil, model.NewAppError("app.UpdateScheduledPost", "app.update_scheduled_post.get_scheduled_post.error", map[string]any{"user_id": userId, "scheduled_post_id": scheduledPost.Id}, "", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
if existingScheduledPost == nil {
|
||||
return nil, model.NewAppError("app.UpdateScheduledPost", "app.update_scheduled_post.existing_scheduled_post.not_exist", map[string]any{"user_id": userId, "scheduled_post_id": scheduledPost.Id}, "", http.StatusNotFound)
|
||||
}
|
||||
|
||||
if existingScheduledPost.UserId != userId {
|
||||
return nil, model.NewAppError("app.UpdateScheduledPost", "app.update_scheduled_post.update_permission.error", map[string]any{"user_id": userId, "scheduled_post_id": scheduledPost.Id}, "", http.StatusForbidden)
|
||||
}
|
||||
|
||||
// This step is not required for update but is useful as we want to return the
|
||||
// updated scheduled post. It's better to do this before calling update than after.
|
||||
scheduledPost.RestoreNonUpdatableFields(existingScheduledPost)
|
||||
|
||||
if err := a.Srv().Store().ScheduledPost().UpdatedScheduledPost(scheduledPost); err != nil {
|
||||
return nil, model.NewAppError("app.UpdateScheduledPost", "app.update_scheduled_post.update.error", map[string]any{"user_id": userId, "scheduled_post_id": scheduledPost.Id}, "", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
// TODO: add WebSocket event broadcast here. This will be done in a later PR
|
||||
|
||||
return scheduledPost, nil
|
||||
}
|
||||
|
||||
func (a *App) DeleteScheduledPost(rctx request.CTX, userId, scheduledPostId, connectionId string) (*model.ScheduledPost, *model.AppError) {
|
||||
scheduledPost, err := a.Srv().Store().ScheduledPost().Get(scheduledPostId)
|
||||
if err != nil {
|
||||
return nil, model.NewAppError("app.DeleteScheduledPost", "app.delete_scheduled_post.get_scheduled_post.error", map[string]any{"user_id": userId, "scheduled_post_id": scheduledPostId}, "", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
if scheduledPost == nil {
|
||||
return nil, model.NewAppError("app.DeleteScheduledPost", "app.delete_scheduled_post.existing_scheduled_post.not_exist", map[string]any{"user_id": userId, "scheduled_post_id": scheduledPostId}, "", http.StatusNotFound)
|
||||
}
|
||||
|
||||
if scheduledPost.UserId != userId {
|
||||
return nil, model.NewAppError("app.DeleteScheduledPost", "app.delete_scheduled_post.delete_permission.error", map[string]any{"user_id": userId, "scheduled_post_id": scheduledPostId}, "", http.StatusForbidden)
|
||||
}
|
||||
|
||||
if err := a.Srv().Store().ScheduledPost().PermanentlyDeleteScheduledPosts([]string{scheduledPostId}); err != nil {
|
||||
return nil, model.NewAppError("app.DeleteScheduledPost", "app.delete_scheduled_post.delete_error", map[string]any{"user_id": userId, "scheduled_post_id": scheduledPostId}, "", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
// TODO: add WebSocket event broadcast here. This will be done in a later PR
|
||||
|
||||
return scheduledPost, nil
|
||||
}
|
||||
357
server/channels/app/scheduled_post_job.go
Обычный файл
357
server/channels/app/scheduled_post_job.go
Обычный файл
@@ -0,0 +1,357 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
"github.com/mattermost/mattermost/server/public/shared/mlog"
|
||||
"github.com/mattermost/mattermost/server/public/shared/request"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
getPendingScheduledPostsPageSize = 100
|
||||
scheduledPostBatchWaitTime = 1 * time.Second
|
||||
)
|
||||
|
||||
func (a *App) ProcessScheduledPosts(rctx request.CTX) {
|
||||
rctx = rctx.WithLogger(rctx.Logger().With(mlog.String("component", "scheduled_post_job")))
|
||||
rctx.Logger().Debug("ProcessScheduledPosts called...")
|
||||
|
||||
if !*a.Config().ServiceSettings.ScheduledPosts {
|
||||
rctx.Logger().Debug("ProcessScheduledPosts exiting as the feature is turned off via ServiceSettings.ScheduledPosts setting...")
|
||||
return
|
||||
}
|
||||
|
||||
if a.License() == nil {
|
||||
rctx.Logger().Debug("ProcessScheduledPosts exiting as no license is available")
|
||||
return
|
||||
}
|
||||
|
||||
beforeTime := model.GetMillis()
|
||||
afterTime := beforeTime - (24 * 60 * 60 * 1000) // subtracting 24 hours from beforeTime
|
||||
lastScheduledPostId := ""
|
||||
|
||||
for {
|
||||
// we wait some time before processing each batch to avoid hammering the database with too many requests.
|
||||
time.Sleep(scheduledPostBatchWaitTime)
|
||||
rctx.Logger().Debug("ProcessScheduledPosts: fetching page of pending scheduled posts...")
|
||||
|
||||
scheduledPostsBatch, err := a.Srv().Store().ScheduledPost().GetPendingScheduledPosts(beforeTime, afterTime, lastScheduledPostId, getPendingScheduledPostsPageSize)
|
||||
if err != nil {
|
||||
rctx.Logger().Error(
|
||||
"App.ProcessScheduledPosts: failed to fetch pending scheduled posts page from database",
|
||||
mlog.Int("before_time", beforeTime),
|
||||
mlog.String("last_scheduled_post_id", lastScheduledPostId),
|
||||
mlog.Int("items_per_page", getPendingScheduledPostsPageSize),
|
||||
mlog.Err(err),
|
||||
)
|
||||
|
||||
// Break the loop if we can't fetch the page.
|
||||
// Missed posts will be processed in job's next round.
|
||||
// Since we don't know any item's details, we can't fetch the next page as well.
|
||||
// We could retry here but that's the same as trying in job's next round.
|
||||
break
|
||||
}
|
||||
|
||||
rctx.Logger().Debug("ProcessScheduledPosts: entries found in page of pending scheduled posts", mlog.Int("entries", len(scheduledPostsBatch)))
|
||||
if len(scheduledPostsBatch) == 0 {
|
||||
rctx.Logger().Debug("ProcessScheduledPosts: skipping as there are no pending scheduled")
|
||||
// break loop if there are no more scheduled posts
|
||||
break
|
||||
}
|
||||
|
||||
// Saving the last item to use as marker for next page
|
||||
lastScheduledPostId = scheduledPostsBatch[len(scheduledPostsBatch)-1].Id
|
||||
beforeTime = scheduledPostsBatch[len(scheduledPostsBatch)-1].ScheduledAt
|
||||
|
||||
if err := a.processScheduledPostBatch(rctx, scheduledPostsBatch); err != nil {
|
||||
rctx.Logger().Error(
|
||||
"App.ProcessScheduledPosts: failed to process scheduled posts batch",
|
||||
mlog.Int("before_time", beforeTime),
|
||||
mlog.String("last_scheduled_post_id", lastScheduledPostId),
|
||||
mlog.Int("items_per_page", getPendingScheduledPostsPageSize),
|
||||
mlog.Err(err),
|
||||
)
|
||||
|
||||
// failure to process one batch doesn't mean other batches will fail as well.
|
||||
// Continue processing next batch. The posts that failed in this batch will be picked
|
||||
// up when the job next runs.
|
||||
continue
|
||||
}
|
||||
|
||||
rctx.Logger().Debug("ProcessScheduledPosts: finished processing a page of pending scheduled posts.")
|
||||
|
||||
if len(scheduledPostsBatch) < getPendingScheduledPostsPageSize {
|
||||
// if we got less than page size worth of scheduled posts, it indicates
|
||||
// that we have no more pending scheduled posts. So, we can break instead of making
|
||||
// an additional database call as we know there are going to be no records in there.
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// once all scheduled posts are processed, we need to update and close the old ones
|
||||
// as we don't process pending scheduled posts more than 24 hours old.
|
||||
if err := a.Srv().Store().ScheduledPost().UpdateOldScheduledPosts(beforeTime); err != nil {
|
||||
rctx.Logger().Error(
|
||||
"App.ProcessScheduledPosts: failed to update old scheduled posts",
|
||||
mlog.Int("before_time", beforeTime),
|
||||
mlog.Err(err),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// processScheduledPostBatch processes one batch
|
||||
func (a *App) processScheduledPostBatch(rctx request.CTX, scheduledPosts []*model.ScheduledPost) error {
|
||||
rctx.Logger().Debug("processScheduledPostBatch called...")
|
||||
var failedScheduledPosts []*model.ScheduledPost
|
||||
var successfulScheduledPostIDs []string
|
||||
|
||||
for i := range scheduledPosts {
|
||||
rctx.Logger().Trace("processScheduledPostBatch processing scheduled post", mlog.String("scheduled_post_id", scheduledPosts[i].Id))
|
||||
scheduledPost, err := a.postScheduledPost(rctx, scheduledPosts[i])
|
||||
if err != nil {
|
||||
rctx.Logger().Debug("processScheduledPostBatch scheduled post processing failed", mlog.String("scheduled_post_id", scheduledPosts[i].Id), mlog.Err(err))
|
||||
failedScheduledPosts = append(failedScheduledPosts, scheduledPost)
|
||||
continue
|
||||
}
|
||||
|
||||
rctx.Logger().Trace("processScheduledPostBatch scheduled post processing successful", mlog.String("scheduled_post_id", scheduledPosts[i].Id))
|
||||
successfulScheduledPostIDs = append(successfulScheduledPostIDs, scheduledPost.Id)
|
||||
}
|
||||
|
||||
rctx.Logger().Trace("processScheduledPostBatch handling successful scheduled posts...", mlog.Int("count", len(successfulScheduledPostIDs)))
|
||||
if err := a.handleSuccessfulScheduledPosts(rctx, successfulScheduledPostIDs); err != nil {
|
||||
return errors.Wrap(err, "App.processScheduledPostBatch: failed to handle successfully posted scheduled posts")
|
||||
}
|
||||
|
||||
rctx.Logger().Trace("processScheduledPostBatch handling failed scheduled posts...", mlog.Int("count", len(failedScheduledPosts)))
|
||||
a.handleFailedScheduledPosts(rctx, failedScheduledPosts)
|
||||
rctx.Logger().Debug("processScheduledPostBatch finished...")
|
||||
return nil
|
||||
}
|
||||
|
||||
// postScheduledPost processes an individual scheduled post
|
||||
func (a *App) postScheduledPost(rctx request.CTX, scheduledPost *model.ScheduledPost) (*model.ScheduledPost, error) {
|
||||
rctx.Logger().Debug("postScheduledPost called...", mlog.String("scheduled_post_id", scheduledPost.Id))
|
||||
|
||||
// we'll process scheduled posts one by one.
|
||||
// If an error occurs, we'll log it and move onto the next scheduled post
|
||||
|
||||
rctx.Logger().Trace("postScheduledPost fetching channel for scheduled post", mlog.String("scheduled_post_id", scheduledPost.Id), mlog.String("channel_id", scheduledPost.ChannelId))
|
||||
channel, appErr := a.GetChannel(rctx, scheduledPost.ChannelId)
|
||||
if appErr != nil {
|
||||
if appErr.StatusCode == http.StatusNotFound {
|
||||
rctx.Logger().Debug("postScheduledPost channel for scheduled post not found, setting error code", mlog.String("scheduled_post_id", scheduledPost.Id), mlog.String("channel_id", scheduledPost.ChannelId), mlog.String("error_code", model.ScheduledPostErrorCodeChannelNotFound))
|
||||
|
||||
scheduledPost.ErrorCode = model.ScheduledPostErrorCodeChannelNotFound
|
||||
return scheduledPost, nil
|
||||
}
|
||||
|
||||
rctx.Logger().Error(
|
||||
"App.processScheduledPostBatch: failed to get channel for scheduled post",
|
||||
mlog.String("scheduled_post_id", scheduledPost.Id),
|
||||
mlog.String("channel_id", scheduledPost.ChannelId),
|
||||
mlog.String("error_code", model.ScheduledPostErrorUnknownError),
|
||||
mlog.Err(appErr),
|
||||
)
|
||||
|
||||
scheduledPost.ErrorCode = model.ScheduledPostErrorUnknownError
|
||||
return scheduledPost, appErr
|
||||
}
|
||||
|
||||
rctx.Logger().Trace("postScheduledPost checking if scheduled post can be posted", mlog.String("scheduled_post_id", scheduledPost.Id))
|
||||
errorCode, err := a.canPostScheduledPost(rctx, scheduledPost, channel)
|
||||
scheduledPost.ErrorCode = errorCode
|
||||
if err != nil {
|
||||
rctx.Logger().Error(
|
||||
"App.processScheduledPostBatch: failed to check if scheduled post can be posted",
|
||||
mlog.String("scheduled_post_id", scheduledPost.Id),
|
||||
mlog.String("user_id", scheduledPost.UserId),
|
||||
mlog.String("channel_id", scheduledPost.ChannelId),
|
||||
mlog.Err(err),
|
||||
)
|
||||
|
||||
return scheduledPost, err
|
||||
}
|
||||
|
||||
if scheduledPost.ErrorCode != "" {
|
||||
rctx.Logger().Warn(
|
||||
"App.processScheduledPostBatch: skipping posting a scheduled post as `can post` check failed",
|
||||
mlog.String("scheduled_post_id", scheduledPost.Id),
|
||||
mlog.String("user_id", scheduledPost.UserId),
|
||||
mlog.String("channel_id", scheduledPost.ChannelId),
|
||||
mlog.String("error_code", scheduledPost.ErrorCode),
|
||||
)
|
||||
|
||||
return scheduledPost, fmt.Errorf("App.processScheduledPostBatch: skipping posting a scheduled post as `can post` check failed, error_code: %s", scheduledPost.ErrorCode)
|
||||
}
|
||||
|
||||
rctx.Logger().Trace("postScheduledPost converting scheduled post to post", mlog.String("scheduled_post_id", scheduledPost.Id))
|
||||
post, err := scheduledPost.ToPost()
|
||||
if err != nil {
|
||||
rctx.Logger().Error(
|
||||
"App.processScheduledPostBatch: failed to convert scheduled post to a post",
|
||||
mlog.String("scheduled_post_id", scheduledPost.Id),
|
||||
mlog.String("error_code", model.ScheduledPostErrorUnknownError),
|
||||
mlog.Err(err),
|
||||
)
|
||||
|
||||
scheduledPost.ErrorCode = model.ScheduledPostErrorUnknownError
|
||||
return scheduledPost, err
|
||||
}
|
||||
|
||||
rctx.Logger().Trace("postScheduledPost posting the scheduled post", mlog.String("scheduled_post_id", scheduledPost.Id))
|
||||
createPostFlags := model.CreatePostFlags{
|
||||
TriggerWebhooks: true,
|
||||
SetOnline: false,
|
||||
}
|
||||
_, appErr = a.CreatePost(rctx, post, channel, createPostFlags)
|
||||
if appErr != nil {
|
||||
rctx.Logger().Error(
|
||||
"App.processScheduledPostBatch: failed to post scheduled post",
|
||||
mlog.String("scheduled_post_id", scheduledPost.Id),
|
||||
mlog.String("channel_id", scheduledPost.ChannelId),
|
||||
mlog.String("error_code", model.ScheduledPostErrorUnknownError),
|
||||
mlog.Err(appErr),
|
||||
)
|
||||
|
||||
scheduledPost.ErrorCode = model.ScheduledPostErrorUnknownError
|
||||
return scheduledPost, appErr
|
||||
}
|
||||
|
||||
return scheduledPost, nil
|
||||
}
|
||||
|
||||
// canPostScheduledPost checks whether the scheduled post be created based on permissions and other checks.
|
||||
func (a *App) canPostScheduledPost(rctx request.CTX, scheduledPost *model.ScheduledPost, channel *model.Channel) (string, error) {
|
||||
rctx.Logger().Trace("canPostScheduledPost called...", mlog.String("scheduled_post_id", scheduledPost.Id))
|
||||
|
||||
user, appErr := a.GetUser(scheduledPost.UserId)
|
||||
if appErr != nil {
|
||||
if appErr.Id == MissingAccountError {
|
||||
rctx.Logger().Debug("canPostScheduledPost user not found for scheduled post", mlog.String("scheduled_post_id", scheduledPost.Id), mlog.String("user_id", scheduledPost.UserId), mlog.String("error_code", model.ScheduledPostErrorCodeUserDoesNotExist))
|
||||
return model.ScheduledPostErrorCodeUserDoesNotExist, nil
|
||||
}
|
||||
|
||||
rctx.Logger().Error(
|
||||
"App.canPostScheduledPost: failed to get user from database",
|
||||
mlog.String("user_id", scheduledPost.UserId),
|
||||
mlog.String("error_code", model.ScheduledPostErrorUnknownError),
|
||||
mlog.Err(appErr),
|
||||
)
|
||||
return model.ScheduledPostErrorUnknownError, errors.Wrapf(appErr, "App.canPostScheduledPost: failed to get user from database, userId: %s", scheduledPost.UserId)
|
||||
}
|
||||
|
||||
if user.DeleteAt != 0 {
|
||||
rctx.Logger().Debug("canPostScheduledPost user for scheduled posts is deleted", mlog.String("scheduled_post_id", scheduledPost.Id), mlog.String("user_id", scheduledPost.UserId), mlog.String("error_code", model.ScheduledPostErrorCodeUserDeleted))
|
||||
return model.ScheduledPostErrorCodeUserDeleted, nil
|
||||
}
|
||||
|
||||
if channel.DeleteAt != 0 {
|
||||
rctx.Logger().Debug("canPostScheduledPost channel for scheduled post is archived", mlog.String("scheduled_post_id", scheduledPost.Id), mlog.String("channel_id", channel.Id), mlog.String("error_code", model.ScheduledPostErrorCodeChannelArchived))
|
||||
return model.ScheduledPostErrorCodeChannelArchived, nil
|
||||
}
|
||||
|
||||
if scheduledPost.RootId != "" {
|
||||
rootPosts, _, appErr := a.GetPostsByIds([]string{scheduledPost.RootId})
|
||||
if appErr != nil {
|
||||
if appErr.StatusCode == http.StatusNotFound {
|
||||
rctx.Logger().Debug("canPostScheduledPost thread root post for scheduled post is missing", mlog.String("scheduled_post_id", scheduledPost.Id), mlog.String("root_post_id", scheduledPost.RootId), mlog.String("error_code", model.ScheduledPostErrorThreadDeleted))
|
||||
return model.ScheduledPostErrorThreadDeleted, nil
|
||||
}
|
||||
|
||||
rctx.Logger().Error(
|
||||
"App.canPostScheduledPost: failed to get root post",
|
||||
mlog.String("scheduled_post_id", scheduledPost.Id),
|
||||
mlog.String("root_post_id", scheduledPost.RootId),
|
||||
mlog.String("error_code", model.ScheduledPostErrorUnknownError),
|
||||
mlog.Err(appErr),
|
||||
)
|
||||
|
||||
return model.ScheduledPostErrorUnknownError, errors.Wrapf(appErr, "App.canPostScheduledPost: failed to get root post, scheduled_post_id: %s, root_post_id: %s", scheduledPost.Id, scheduledPost.RootId)
|
||||
}
|
||||
|
||||
// you do get deleted posts from `GetPostsByIds`, so need to validate that as well
|
||||
if len(rootPosts) == 1 && rootPosts[0].Id == scheduledPost.RootId && rootPosts[0].DeleteAt != 0 {
|
||||
rctx.Logger().Debug("canPostScheduledPost thread root post is deleted", mlog.String("scheduled_post_id", scheduledPost.Id), mlog.String("root_post_id", scheduledPost.RootId), mlog.String("error_code", model.ScheduledPostErrorThreadDeleted))
|
||||
return model.ScheduledPostErrorThreadDeleted, nil
|
||||
}
|
||||
}
|
||||
|
||||
if appErr := userCreatePostPermissionCheckWithApp(rctx, a, scheduledPost.UserId, scheduledPost.ChannelId); appErr != nil {
|
||||
rctx.Logger().Debug(
|
||||
"canPostScheduledPost user does not have permission to create post in channel",
|
||||
mlog.String("scheduled_post_id", scheduledPost.Id),
|
||||
mlog.String("user_id", scheduledPost.UserId),
|
||||
mlog.String("channel_id", scheduledPost.ChannelId),
|
||||
mlog.String("error_code", model.ScheduledPostErrorCodeNoChannelPermission),
|
||||
mlog.Err(appErr),
|
||||
)
|
||||
return model.ScheduledPostErrorCodeNoChannelPermission, nil
|
||||
}
|
||||
|
||||
if appErr := PostHardenedModeCheckWithApp(a, false, scheduledPost.GetProps()); appErr != nil {
|
||||
rctx.Logger().Debug(
|
||||
"canPostScheduledPost hardened mode enabled: post contains props prohibited in hardened mode",
|
||||
mlog.String("scheduled_post_id", scheduledPost.Id),
|
||||
mlog.String("user_id", scheduledPost.UserId),
|
||||
mlog.String("channel_id", scheduledPost.ChannelId),
|
||||
mlog.String("error_code", model.ScheduledPostErrorInvalidPost),
|
||||
mlog.Err(appErr),
|
||||
)
|
||||
return model.ScheduledPostErrorInvalidPost, nil
|
||||
}
|
||||
|
||||
if appErr := PostPriorityCheckWithApp("ScheduledPostJob.postChecks", a, scheduledPost.UserId, scheduledPost.GetPriority(), scheduledPost.RootId); appErr != nil {
|
||||
rctx.Logger().Debug(
|
||||
"canPostScheduledPost post priority check failed",
|
||||
mlog.String("scheduled_post_id", scheduledPost.Id),
|
||||
mlog.String("user_id", scheduledPost.UserId),
|
||||
mlog.String("channel_id", scheduledPost.ChannelId),
|
||||
mlog.String("error_code", model.ScheduledPostErrorInvalidPost),
|
||||
mlog.Err(appErr),
|
||||
)
|
||||
return model.ScheduledPostErrorInvalidPost, nil
|
||||
}
|
||||
|
||||
rctx.Logger().Debug("canPostScheduledPost scheduled post can be posted", mlog.String("scheduled_post_id", scheduledPost.Id))
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (a *App) handleSuccessfulScheduledPosts(rctx request.CTX, successfulScheduledPostIDs []string) error {
|
||||
if len(successfulScheduledPostIDs) > 0 {
|
||||
// Successfully posted scheduled posts can be safely permanently deleted as no data is lost.
|
||||
// The data is moved into the posts table.
|
||||
err := a.Srv().Store().ScheduledPost().PermanentlyDeleteScheduledPosts(successfulScheduledPostIDs)
|
||||
if err != nil {
|
||||
rctx.Logger().Error(
|
||||
"App.handleSuccessfulScheduledPosts: failed to delete successfully posted scheduled posts",
|
||||
mlog.Int("successfully_posted_count", len(successfulScheduledPostIDs)),
|
||||
mlog.Err(err),
|
||||
)
|
||||
return errors.Wrap(err, "App.handleSuccessfulScheduledPosts: failed to delete successfully posted scheduled posts")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) handleFailedScheduledPosts(rctx request.CTX, failedScheduledPosts []*model.ScheduledPost) {
|
||||
for _, failedScheduledPost := range failedScheduledPosts {
|
||||
err := a.Srv().Store().ScheduledPost().UpdatedScheduledPost(failedScheduledPost)
|
||||
if err != nil {
|
||||
// we intentionally don't stop on error as its possible to continue updating other scheduled posts
|
||||
rctx.Logger().Error(
|
||||
"App.processScheduledPostBatch: failed to updated failed scheduled posts",
|
||||
mlog.String("scheduled_post_id", failedScheduledPost.Id),
|
||||
mlog.Err(err),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
211
server/channels/app/scheduled_post_job_test.go
Обычный файл
211
server/channels/app/scheduled_post_job_test.go
Обычный файл
@@ -0,0 +1,211 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestProcessScheduledPosts(t *testing.T) {
|
||||
t.Run("base case - happy path", func(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
th.App.Srv().SetLicense(getLicWithSkuShortName(model.LicenseShortSkuProfessional))
|
||||
|
||||
scheduledAt := model.GetMillis() + 1000
|
||||
scheduledPost1 := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: scheduledAt,
|
||||
}
|
||||
_, err := th.Server.Store().ScheduledPost().CreateScheduledPost(scheduledPost1)
|
||||
assert.NoError(t, err)
|
||||
|
||||
scheduledPost2 := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "this is second scheduled post",
|
||||
},
|
||||
ScheduledAt: scheduledAt,
|
||||
}
|
||||
_, err = th.Server.Store().ScheduledPost().CreateScheduledPost(scheduledPost2)
|
||||
assert.NoError(t, err)
|
||||
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
th.App.ProcessScheduledPosts(th.Context)
|
||||
|
||||
scheduledPosts, err := th.App.Srv().Store().ScheduledPost().GetScheduledPostsForUser(th.BasicUser.Id, th.BasicChannel.TeamId)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, scheduledPosts, 0)
|
||||
})
|
||||
|
||||
t.Run("sets error code for archived channel", func(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
th.App.Srv().SetLicense(getLicWithSkuShortName(model.LicenseShortSkuProfessional))
|
||||
|
||||
appErr := th.App.DeleteChannel(th.Context, th.BasicChannel, th.BasicUser.Id)
|
||||
assert.Nil(t, appErr)
|
||||
|
||||
scheduledAt := model.GetMillis() - (5 * 60 * 60 * 1000)
|
||||
scheduledPost1 := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: scheduledAt,
|
||||
}
|
||||
_, err := th.Server.Store().ScheduledPost().CreateScheduledPost(scheduledPost1)
|
||||
assert.NoError(t, err)
|
||||
|
||||
scheduledPost2 := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "this is second scheduled post",
|
||||
},
|
||||
ScheduledAt: scheduledAt,
|
||||
}
|
||||
_, err = th.Server.Store().ScheduledPost().CreateScheduledPost(scheduledPost2)
|
||||
assert.NoError(t, err)
|
||||
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
th.App.ProcessScheduledPosts(th.Context)
|
||||
|
||||
// since the channel ID we set in the above created scheduled posts is of a
|
||||
// non-existing channel, the job should have set the appropriate error code for them in the database
|
||||
scheduledPosts, err := th.App.Srv().Store().ScheduledPost().GetScheduledPostsForUser(th.BasicUser.Id, th.BasicChannel.TeamId)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, scheduledPosts, 2)
|
||||
|
||||
assert.Equal(t, model.ScheduledPostErrorCodeChannelArchived, scheduledPosts[0].ErrorCode)
|
||||
assert.Greater(t, scheduledPosts[0].ProcessedAt, int64(0))
|
||||
|
||||
assert.Equal(t, model.ScheduledPostErrorCodeChannelArchived, scheduledPosts[1].ErrorCode)
|
||||
assert.Greater(t, scheduledPosts[1].ProcessedAt, int64(0))
|
||||
})
|
||||
|
||||
t.Run("sets error code for archived user", func(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
th.App.Srv().SetLicense(getLicWithSkuShortName(model.LicenseShortSkuProfessional))
|
||||
|
||||
scheduledAt := model.GetMillis() + 1000
|
||||
scheduledPost1 := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: scheduledAt,
|
||||
}
|
||||
_, err := th.Server.Store().ScheduledPost().CreateScheduledPost(scheduledPost1)
|
||||
assert.NoError(t, err)
|
||||
|
||||
scheduledPost2 := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "this is second scheduled post",
|
||||
},
|
||||
ScheduledAt: scheduledAt,
|
||||
}
|
||||
_, err = th.Server.Store().ScheduledPost().CreateScheduledPost(scheduledPost2)
|
||||
assert.NoError(t, err)
|
||||
|
||||
_, appErr := th.App.UpdateActive(th.Context, th.BasicUser, false)
|
||||
assert.Nil(t, appErr)
|
||||
|
||||
defer func() {
|
||||
_, _ = th.App.UpdateActive(th.Context, th.BasicUser, true)
|
||||
}()
|
||||
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
th.App.ProcessScheduledPosts(th.Context)
|
||||
|
||||
scheduledPosts, err := th.App.Srv().Store().ScheduledPost().GetScheduledPostsForUser(th.BasicUser.Id, th.BasicChannel.TeamId)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, scheduledPosts, 2)
|
||||
|
||||
assert.Equal(t, model.ScheduledPostErrorCodeUserDeleted, scheduledPosts[0].ErrorCode)
|
||||
assert.Greater(t, scheduledPosts[0].ProcessedAt, int64(0))
|
||||
|
||||
assert.Equal(t, model.ScheduledPostErrorCodeUserDeleted, scheduledPosts[1].ErrorCode)
|
||||
assert.Greater(t, scheduledPosts[1].ProcessedAt, int64(0))
|
||||
})
|
||||
|
||||
t.Run("sets error code when user is not a channel member", func(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
th.App.Srv().SetLicense(getLicWithSkuShortName(model.LicenseShortSkuProfessional))
|
||||
|
||||
scheduledAt := model.GetMillis() + 1000
|
||||
scheduledPost1 := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: scheduledAt,
|
||||
}
|
||||
_, err := th.Server.Store().ScheduledPost().CreateScheduledPost(scheduledPost1)
|
||||
assert.NoError(t, err)
|
||||
|
||||
scheduledPost2 := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "this is second scheduled post",
|
||||
},
|
||||
ScheduledAt: scheduledAt,
|
||||
}
|
||||
_, err = th.Server.Store().ScheduledPost().CreateScheduledPost(scheduledPost2)
|
||||
assert.NoError(t, err)
|
||||
|
||||
appErr := th.App.LeaveChannel(th.Context, th.BasicChannel.Id, th.BasicUser.Id)
|
||||
assert.Nil(t, appErr)
|
||||
|
||||
defer func() {
|
||||
_ = th.App.JoinChannel(th.Context, th.BasicChannel, th.BasicUser.Id)
|
||||
}()
|
||||
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
th.App.ProcessScheduledPosts(th.Context)
|
||||
|
||||
scheduledPosts, err := th.App.Srv().Store().ScheduledPost().GetScheduledPostsForUser(th.BasicUser.Id, th.BasicChannel.TeamId)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, scheduledPosts, 2)
|
||||
|
||||
assert.Equal(t, model.ScheduledPostErrorCodeNoChannelPermission, scheduledPosts[0].ErrorCode)
|
||||
assert.Greater(t, scheduledPosts[0].ProcessedAt, int64(0))
|
||||
|
||||
assert.Equal(t, model.ScheduledPostErrorCodeNoChannelPermission, scheduledPosts[1].ErrorCode)
|
||||
assert.Greater(t, scheduledPosts[1].ProcessedAt, int64(0))
|
||||
})
|
||||
}
|
||||
663
server/channels/app/scheduled_post_test.go
Обычный файл
663
server/channels/app/scheduled_post_test.go
Обычный файл
@@ -0,0 +1,663 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/mattermost/mattermost/server/public/model"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSaveScheduledPost(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
t.Run("base case", func(t *testing.T) {
|
||||
userId := model.NewId()
|
||||
|
||||
channel, err := th.GetSqlStore().Channel().Save(th.Context, &model.Channel{
|
||||
Name: model.NewId(),
|
||||
DisplayName: "Channel",
|
||||
Type: model.ChannelTypeOpen,
|
||||
}, 1000)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = th.GetSqlStore().Channel().SaveMember(th.Context, &model.ChannelMember{
|
||||
ChannelId: channel.Id,
|
||||
UserId: userId,
|
||||
NotifyProps: model.GetDefaultChannelNotifyProps(),
|
||||
SchemeGuest: false,
|
||||
SchemeUser: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
defer func() {
|
||||
_ = th.GetSqlStore().Channel().Delete(channel.Id, model.GetMillis())
|
||||
_ = th.GetSqlStore().Channel().RemoveMember(th.Context, channel.Id, userId)
|
||||
}()
|
||||
|
||||
scheduledPost := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: userId,
|
||||
ChannelId: channel.Id,
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, createdScheduledPost)
|
||||
})
|
||||
|
||||
t.Run("cannot save invalid scheduled post", func(t *testing.T) {
|
||||
scheduledPost := &model.ScheduledPost{
|
||||
// a completely empty scheduled post
|
||||
}
|
||||
createdScheduledPost, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost)
|
||||
require.NotNil(t, appErr)
|
||||
require.Nil(t, createdScheduledPost)
|
||||
})
|
||||
|
||||
t.Run("cannot save post scheduled in the past", func(t *testing.T) {
|
||||
userId := model.NewId()
|
||||
|
||||
scheduledPost := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: userId,
|
||||
ChannelId: "channel_id",
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() - 100000, // 100 seconds in the past
|
||||
}
|
||||
createdScheduledPost, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost)
|
||||
require.NotNil(t, appErr)
|
||||
require.Nil(t, createdScheduledPost)
|
||||
})
|
||||
|
||||
t.Run("cannot scheduled post in a channel you don't belong to", func(t *testing.T) {
|
||||
userId := model.NewId()
|
||||
|
||||
// we didn't create any channel member entry, so the user doesn't
|
||||
// belong to the channel
|
||||
scheduledPost := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: userId,
|
||||
ChannelId: "channel_id",
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost)
|
||||
require.NotNil(t, appErr)
|
||||
require.Nil(t, createdScheduledPost)
|
||||
})
|
||||
|
||||
t.Run("cannot schedule post in an archived channel", func(t *testing.T) {
|
||||
userId := model.NewId()
|
||||
|
||||
channel, err := th.GetSqlStore().Channel().Save(th.Context, &model.Channel{
|
||||
Name: model.NewId(),
|
||||
DisplayName: "Channel",
|
||||
Type: model.ChannelTypeOpen,
|
||||
}, 1000)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = th.GetSqlStore().Channel().SaveMember(th.Context, &model.ChannelMember{
|
||||
ChannelId: channel.Id,
|
||||
UserId: userId,
|
||||
NotifyProps: model.GetDefaultChannelNotifyProps(),
|
||||
SchemeGuest: false,
|
||||
SchemeUser: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
err = th.GetSqlStore().Channel().Delete(channel.Id, model.GetMillis())
|
||||
require.NoError(t, err)
|
||||
|
||||
defer func() {
|
||||
_ = th.GetSqlStore().Channel().Delete(channel.Id, model.GetMillis())
|
||||
_ = th.GetSqlStore().Channel().RemoveMember(th.Context, channel.Id, userId)
|
||||
}()
|
||||
|
||||
scheduledPost := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: userId,
|
||||
ChannelId: channel.Id,
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost)
|
||||
require.NotNil(t, appErr)
|
||||
require.Nil(t, createdScheduledPost)
|
||||
})
|
||||
|
||||
t.Run("can scheduled multiple posts in the same channel", func(t *testing.T) {
|
||||
userId := model.NewId()
|
||||
|
||||
channel, err := th.GetSqlStore().Channel().Save(th.Context, &model.Channel{
|
||||
Name: model.NewId(),
|
||||
DisplayName: "Channel",
|
||||
Type: model.ChannelTypeOpen,
|
||||
}, 1000)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = th.GetSqlStore().Channel().SaveMember(th.Context, &model.ChannelMember{
|
||||
ChannelId: channel.Id,
|
||||
UserId: userId,
|
||||
NotifyProps: model.GetDefaultChannelNotifyProps(),
|
||||
SchemeGuest: false,
|
||||
SchemeUser: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
defer func() {
|
||||
_ = th.GetSqlStore().Channel().Delete(channel.Id, model.GetMillis())
|
||||
_ = th.GetSqlStore().Channel().RemoveMember(th.Context, channel.Id, userId)
|
||||
}()
|
||||
|
||||
scheduledPost := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: userId,
|
||||
ChannelId: channel.Id,
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, createdScheduledPost)
|
||||
|
||||
scheduledPost.Message = "this is a second scheduled post"
|
||||
scheduledPost.Id = model.NewId()
|
||||
createdScheduledPost, appErr = th.App.SaveScheduledPost(th.Context, scheduledPost)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, createdScheduledPost)
|
||||
})
|
||||
|
||||
t.Run("cannot save an empty post", func(t *testing.T) {
|
||||
userId := model.NewId()
|
||||
|
||||
channel, err := th.GetSqlStore().Channel().Save(th.Context, &model.Channel{
|
||||
Name: model.NewId(),
|
||||
DisplayName: "Channel",
|
||||
Type: model.ChannelTypeOpen,
|
||||
}, 1000)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = th.GetSqlStore().Channel().SaveMember(th.Context, &model.ChannelMember{
|
||||
ChannelId: channel.Id,
|
||||
UserId: userId,
|
||||
NotifyProps: model.GetDefaultChannelNotifyProps(),
|
||||
SchemeGuest: false,
|
||||
SchemeUser: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
defer func() {
|
||||
_ = th.GetSqlStore().Channel().Delete(channel.Id, model.GetMillis())
|
||||
_ = th.GetSqlStore().Channel().RemoveMember(th.Context, channel.Id, userId)
|
||||
}()
|
||||
|
||||
scheduledPost := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: userId,
|
||||
ChannelId: channel.Id,
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost)
|
||||
require.NotNil(t, appErr)
|
||||
require.Nil(t, createdScheduledPost)
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetUserTeamScheduledPosts(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
t.Run("should get created scheduled posts", func(t *testing.T) {
|
||||
scheduledPost1 := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost1, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost1)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, createdScheduledPost1)
|
||||
|
||||
scheduledPost2 := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "this is a second scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost2, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost2)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, createdScheduledPost2)
|
||||
|
||||
defer func() {
|
||||
_ = th.Server.Store().ScheduledPost().PermanentlyDeleteScheduledPosts([]string{scheduledPost1.Id, createdScheduledPost2.Id})
|
||||
}()
|
||||
|
||||
retrievedScheduledPosts, appErr := th.App.GetUserTeamScheduledPosts(th.Context, th.BasicUser.Id, th.BasicChannel.TeamId)
|
||||
require.Nil(t, appErr)
|
||||
require.Equal(t, 2, len(retrievedScheduledPosts))
|
||||
|
||||
// more recently created scheduled post appears first in the list
|
||||
require.Equal(t, createdScheduledPost1.Id, retrievedScheduledPosts[0].Id)
|
||||
require.Equal(t, createdScheduledPost2.Id, retrievedScheduledPosts[1].Id)
|
||||
})
|
||||
|
||||
t.Run("should handle no scheduled posts", func(t *testing.T) {
|
||||
retrievedScheduledPosts, appErr := th.App.GetUserTeamScheduledPosts(th.Context, th.BasicUser.Id, th.BasicChannel.TeamId)
|
||||
require.Nil(t, appErr)
|
||||
require.Equal(t, 0, len(retrievedScheduledPosts))
|
||||
})
|
||||
|
||||
t.Run("should restrict to specified teams and DM/GMs", func(t *testing.T) {
|
||||
scheduledPost1 := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost1, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost1)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, createdScheduledPost1)
|
||||
|
||||
scheduledPost2 := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "this is a second scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost2, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost2)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, createdScheduledPost2)
|
||||
|
||||
defer func() {
|
||||
_ = th.Server.Store().ScheduledPost().PermanentlyDeleteScheduledPosts([]string{scheduledPost1.Id, createdScheduledPost2.Id})
|
||||
}()
|
||||
|
||||
// create a dummy team
|
||||
secondTeam := th.CreateTeam()
|
||||
_, appErr = th.App.JoinUserToTeam(th.Context, secondTeam, th.BasicUser, th.BasicUser.Id)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
retrievedScheduledPosts, appErr := th.App.GetUserTeamScheduledPosts(th.Context, th.BasicUser.Id, secondTeam.Id)
|
||||
require.Nil(t, appErr)
|
||||
require.Equal(t, 0, len(retrievedScheduledPosts))
|
||||
})
|
||||
|
||||
t.Run("should not return scheduled posts from DMs and GMs when teamId is specified", func(t *testing.T) {
|
||||
// start a DM between BasicUser1 and BasicUser2
|
||||
dm, appErr := th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
// create a GM. Since a GM needs at least 3 users, we'll create a third user first
|
||||
thirdUser := th.CreateUser()
|
||||
_, appErr = th.App.JoinUserToTeam(th.Context, th.BasicTeam, thirdUser, thirdUser.Id)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
gm, appErr := th.App.CreateGroupChannel(th.Context, []string{th.BasicUser.Id, th.BasicUser2.Id, thirdUser.Id}, th.BasicUser.Id)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
scheduledPost1 := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: dm.Id,
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost1, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost1)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, createdScheduledPost1)
|
||||
|
||||
scheduledPost2 := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: gm.Id,
|
||||
Message: "this is a second scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost2, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost2)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, createdScheduledPost2)
|
||||
|
||||
defer func() {
|
||||
_ = th.Server.Store().ScheduledPost().PermanentlyDeleteScheduledPosts([]string{scheduledPost1.Id, createdScheduledPost2.Id})
|
||||
}()
|
||||
|
||||
retrievedScheduledPosts, appErr := th.App.GetUserTeamScheduledPosts(th.Context, th.BasicUser.Id, th.BasicChannel.TeamId)
|
||||
require.Nil(t, appErr)
|
||||
require.Equal(t, 0, len(retrievedScheduledPosts))
|
||||
})
|
||||
|
||||
t.Run("should return scheduled posts from DMs and GMs when teamId is empty", func(t *testing.T) {
|
||||
// start a DM between BasicUser1 and BasicUser2
|
||||
dm, appErr := th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, th.BasicUser2.Id)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
// create a GM. Since a GM needs at least 3 users, we'll create a third user first
|
||||
thirdUser := th.CreateUser()
|
||||
_, appErr = th.App.JoinUserToTeam(th.Context, th.BasicTeam, thirdUser, thirdUser.Id)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
gm, appErr := th.App.CreateGroupChannel(th.Context, []string{th.BasicUser.Id, th.BasicUser2.Id, thirdUser.Id}, th.BasicUser.Id)
|
||||
require.Nil(t, appErr)
|
||||
|
||||
scheduledPost1 := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: dm.Id,
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost1, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost1)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, createdScheduledPost1)
|
||||
|
||||
scheduledPost2 := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis() + 100,
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: gm.Id,
|
||||
Message: "this is a second scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost2, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost2)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, createdScheduledPost2)
|
||||
|
||||
defer func() {
|
||||
_ = th.Server.Store().ScheduledPost().PermanentlyDeleteScheduledPosts([]string{scheduledPost1.Id, createdScheduledPost2.Id})
|
||||
}()
|
||||
|
||||
retrievedScheduledPosts, appErr := th.App.GetUserTeamScheduledPosts(th.Context, th.BasicUser.Id, "")
|
||||
require.Nil(t, appErr)
|
||||
require.Equal(t, 2, len(retrievedScheduledPosts))
|
||||
|
||||
// more recently created scheduled post appears first in the list
|
||||
require.Equal(t, createdScheduledPost1.Id, retrievedScheduledPosts[0].Id)
|
||||
require.Equal(t, createdScheduledPost2.Id, retrievedScheduledPosts[1].Id)
|
||||
})
|
||||
}
|
||||
|
||||
func TestUpdateScheduledPost(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
t.Run("base case", func(t *testing.T) {
|
||||
// first we'll create a scheduled post
|
||||
userId := model.NewId()
|
||||
|
||||
channel, err := th.GetSqlStore().Channel().Save(th.Context, &model.Channel{
|
||||
Name: model.NewId(),
|
||||
DisplayName: "Channel",
|
||||
Type: model.ChannelTypeOpen,
|
||||
}, 1000)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = th.GetSqlStore().Channel().SaveMember(th.Context, &model.ChannelMember{
|
||||
ChannelId: channel.Id,
|
||||
UserId: userId,
|
||||
NotifyProps: model.GetDefaultChannelNotifyProps(),
|
||||
SchemeGuest: false,
|
||||
SchemeUser: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
defer func() {
|
||||
_ = th.GetSqlStore().Channel().Delete(channel.Id, model.GetMillis())
|
||||
_ = th.GetSqlStore().Channel().RemoveMember(th.Context, channel.Id, userId)
|
||||
}()
|
||||
|
||||
scheduledPost := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: userId,
|
||||
ChannelId: channel.Id,
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, createdScheduledPost)
|
||||
|
||||
// now we'll try updating it
|
||||
newScheduledAtTime := model.GetMillis() + 9999999
|
||||
createdScheduledPost.ScheduledAt = newScheduledAtTime
|
||||
createdScheduledPost.Message = "Updated Message!!!"
|
||||
|
||||
updatedScheduledPost, appErr := th.App.UpdateScheduledPost(th.Context, userId, createdScheduledPost)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, updatedScheduledPost)
|
||||
|
||||
require.Equal(t, newScheduledAtTime, updatedScheduledPost.ScheduledAt)
|
||||
require.Equal(t, "Updated Message!!!", updatedScheduledPost.Message)
|
||||
})
|
||||
|
||||
t.Run("should ot be allowed to updated a scheduled post not belonging to the user", func(t *testing.T) {
|
||||
// first we'll create a scheduled post
|
||||
userId := model.NewId()
|
||||
|
||||
channel, err := th.GetSqlStore().Channel().Save(th.Context, &model.Channel{
|
||||
Name: model.NewId(),
|
||||
DisplayName: "Channel",
|
||||
Type: model.ChannelTypeOpen,
|
||||
}, 1000)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = th.GetSqlStore().Channel().SaveMember(th.Context, &model.ChannelMember{
|
||||
ChannelId: channel.Id,
|
||||
UserId: userId,
|
||||
NotifyProps: model.GetDefaultChannelNotifyProps(),
|
||||
SchemeGuest: false,
|
||||
SchemeUser: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
defer func() {
|
||||
_ = th.GetSqlStore().Channel().Delete(channel.Id, model.GetMillis())
|
||||
_ = th.GetSqlStore().Channel().RemoveMember(th.Context, channel.Id, userId)
|
||||
}()
|
||||
|
||||
scheduledPost := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: userId,
|
||||
ChannelId: channel.Id,
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, createdScheduledPost)
|
||||
|
||||
// now we'll try updating it
|
||||
newScheduledAtTime := model.GetMillis() + 9999999
|
||||
createdScheduledPost.ScheduledAt = newScheduledAtTime
|
||||
createdScheduledPost.Message = "Updated Message!!!"
|
||||
|
||||
updatedScheduledPost, appErr := th.App.UpdateScheduledPost(th.Context, th.BasicUser2.Id, createdScheduledPost)
|
||||
require.NotNil(t, appErr)
|
||||
require.Equal(t, http.StatusForbidden, appErr.StatusCode)
|
||||
require.Nil(t, updatedScheduledPost)
|
||||
})
|
||||
|
||||
t.Run("should only allow updating limited fields", func(t *testing.T) {
|
||||
// first we'll create a scheduled post
|
||||
userId := model.NewId()
|
||||
|
||||
channel, err := th.GetSqlStore().Channel().Save(th.Context, &model.Channel{
|
||||
Name: model.NewId(),
|
||||
DisplayName: "Channel",
|
||||
Type: model.ChannelTypeOpen,
|
||||
}, 1000)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = th.GetSqlStore().Channel().SaveMember(th.Context, &model.ChannelMember{
|
||||
ChannelId: channel.Id,
|
||||
UserId: userId,
|
||||
NotifyProps: model.GetDefaultChannelNotifyProps(),
|
||||
SchemeGuest: false,
|
||||
SchemeUser: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
defer func() {
|
||||
_ = th.GetSqlStore().Channel().Delete(channel.Id, model.GetMillis())
|
||||
_ = th.GetSqlStore().Channel().RemoveMember(th.Context, channel.Id, userId)
|
||||
}()
|
||||
|
||||
scheduledPost := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: userId,
|
||||
ChannelId: channel.Id,
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, createdScheduledPost)
|
||||
|
||||
// now we'll try updating it
|
||||
newUpdatedAt := model.GetMillis() + 1000000
|
||||
createdScheduledPost.UpdateAt = newUpdatedAt // this should be overridden by the actual update time
|
||||
createdScheduledPost.Message = "Updated Message" // this will update
|
||||
newChannelId := model.NewId()
|
||||
createdScheduledPost.ChannelId = newChannelId // this won't update
|
||||
newCreateAt := model.GetMillis() + 5000000
|
||||
createdScheduledPost.CreateAt = newCreateAt // this won't update
|
||||
createdScheduledPost.FileIds = []string{model.NewId(), model.NewId()}
|
||||
createdScheduledPost.ErrorCode = model.ScheduledPostErrorUnknownError
|
||||
|
||||
updatedScheduledPost, appErr := th.App.UpdateScheduledPost(th.Context, userId, createdScheduledPost)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, createdScheduledPost)
|
||||
|
||||
require.NotEqual(t, newUpdatedAt, updatedScheduledPost.UpdateAt)
|
||||
require.Equal(t, "Updated Message", updatedScheduledPost.Message)
|
||||
require.NotEqual(t, newChannelId, updatedScheduledPost.ChannelId)
|
||||
require.NotEqual(t, newCreateAt, updatedScheduledPost.CreateAt)
|
||||
require.Equal(t, 2, len(updatedScheduledPost.FileIds))
|
||||
require.Equal(t, model.ScheduledPostErrorUnknownError, createdScheduledPost.ErrorCode)
|
||||
})
|
||||
}
|
||||
|
||||
func TestDeleteScheduledPost(t *testing.T) {
|
||||
th := Setup(t).InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
t.Run("base case", func(t *testing.T) {
|
||||
// first we'll create a scheduled post
|
||||
scheduledPost := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, createdScheduledPost)
|
||||
|
||||
fetchedScheduledPost, err := th.Server.Store().ScheduledPost().Get(scheduledPost.Id)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, fetchedScheduledPost)
|
||||
require.Equal(t, createdScheduledPost.Id, fetchedScheduledPost.Id)
|
||||
require.Equal(t, createdScheduledPost.Message, fetchedScheduledPost.Message)
|
||||
|
||||
// now we'll delete it
|
||||
var deletedScheduledPost *model.ScheduledPost
|
||||
deletedScheduledPost, appErr = th.App.DeleteScheduledPost(th.Context, th.BasicUser.Id, scheduledPost.Id, "connection_id")
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, deletedScheduledPost)
|
||||
|
||||
require.Equal(t, scheduledPost.Id, deletedScheduledPost.Id)
|
||||
require.Equal(t, scheduledPost.Message, deletedScheduledPost.Message)
|
||||
|
||||
// try to fetch it again
|
||||
reFetchedScheduledPost, err := th.Server.Store().ScheduledPost().Get(scheduledPost.Id)
|
||||
require.Error(t, err) // This will produce error as the row doesn't exist
|
||||
require.Nil(t, reFetchedScheduledPost)
|
||||
})
|
||||
|
||||
t.Run("should not allow deleting someone else's scheduled post", func(t *testing.T) {
|
||||
// first we'll create a scheduled post
|
||||
scheduledPost := &model.ScheduledPost{
|
||||
Draft: model.Draft{
|
||||
CreateAt: model.GetMillis(),
|
||||
UserId: th.BasicUser.Id,
|
||||
ChannelId: th.BasicChannel.Id,
|
||||
Message: "this is a scheduled post",
|
||||
},
|
||||
ScheduledAt: model.GetMillis() + 100000, // 100 seconds in the future
|
||||
}
|
||||
createdScheduledPost, appErr := th.App.SaveScheduledPost(th.Context, scheduledPost)
|
||||
require.Nil(t, appErr)
|
||||
require.NotNil(t, createdScheduledPost)
|
||||
|
||||
fetchedScheduledPost, err := th.Server.Store().ScheduledPost().Get(scheduledPost.Id)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, fetchedScheduledPost)
|
||||
require.Equal(t, createdScheduledPost.Id, fetchedScheduledPost.Id)
|
||||
require.Equal(t, createdScheduledPost.Message, fetchedScheduledPost.Message)
|
||||
|
||||
// now we'll delete it
|
||||
var deletedScheduledPost *model.ScheduledPost
|
||||
deletedScheduledPost, appErr = th.App.DeleteScheduledPost(th.Context, th.BasicUser2.Id, scheduledPost.Id, "connection_id")
|
||||
require.NotNil(t, appErr)
|
||||
require.Nil(t, deletedScheduledPost)
|
||||
|
||||
// try to fetch it again
|
||||
reFetchedScheduledPost, err := th.Server.Store().ScheduledPost().Get(scheduledPost.Id)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, reFetchedScheduledPost)
|
||||
require.Equal(t, createdScheduledPost.Id, reFetchedScheduledPost.Id)
|
||||
require.Equal(t, createdScheduledPost.Message, reFetchedScheduledPost.Message)
|
||||
})
|
||||
|
||||
t.Run("should producer error when deleting non existing scheduled post", func(t *testing.T) {
|
||||
var deletedScheduledPost *model.ScheduledPost
|
||||
deletedScheduledPost, appErr := th.App.DeleteScheduledPost(th.Context, th.BasicUser.Id, model.NewId(), "connection_id")
|
||||
require.NotNil(t, appErr)
|
||||
require.Nil(t, deletedScheduledPost)
|
||||
})
|
||||
}
|
||||
@@ -81,6 +81,10 @@ import (
|
||||
"github.com/mattermost/mattermost/server/v8/platform/shared/templates"
|
||||
)
|
||||
|
||||
const (
|
||||
scheduledPostJobInterval = 5 * time.Minute
|
||||
)
|
||||
|
||||
var SentryDSN = "https://9d7c9cccf549479799f880bcf4f26323@o94110.ingest.sentry.io/5212327"
|
||||
|
||||
// This is a placeholder to allow the existing release pipelines to run without failing to insert
|
||||
@@ -506,6 +510,7 @@ func (s *Server) runJobs() {
|
||||
appInstance := New(ServerConnector(s.Channels()))
|
||||
runDNDStatusExpireJob(appInstance)
|
||||
runPostReminderJob(appInstance)
|
||||
runScheduledPostJob(appInstance)
|
||||
})
|
||||
s.Go(func() {
|
||||
runSecurityJob(s)
|
||||
@@ -1819,6 +1824,30 @@ func runPostReminderJob(a *App) {
|
||||
})
|
||||
}
|
||||
|
||||
func runScheduledPostJob(a *App) {
|
||||
if a.IsLeader() {
|
||||
doRunScheduledPostJob(a)
|
||||
}
|
||||
|
||||
a.ch.srv.AddClusterLeaderChangedListener(func() {
|
||||
mlog.Info("Cluster leader changed. Determining if scheduled posts task should be running", mlog.Bool("isLeader", a.IsLeader()))
|
||||
if a.IsLeader() {
|
||||
doRunScheduledPostJob(a)
|
||||
} else {
|
||||
mlog.Info("This is no longer leader node. Cancelling the scheduled post task", mlog.Bool("isLeader", a.IsLeader()))
|
||||
cancelTask(&a.ch.scheduledPostMut, &a.ch.scheduledPostTask)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func doRunScheduledPostJob(a *App) {
|
||||
rctx := request.EmptyContext(a.Log())
|
||||
withMut(&a.ch.scheduledPostMut, func() {
|
||||
fn := func() { a.ProcessScheduledPosts(rctx) }
|
||||
a.ch.scheduledPostTask = model.CreateRecurringTaskFromNextIntervalTime("Process Scheduled Posts", fn, scheduledPostJobInterval)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) GetAppliedSchemaMigrations() ([]model.AppliedMigration, *model.AppError) {
|
||||
table, err := a.Srv().Store().GetAppliedMigrations()
|
||||
if err != nil {
|
||||
|
||||
Ссылка в новой задаче
Block a user