* Updated patch/update post API to allow file modification (#29447)

* WIP

* WIP

* Atatched new files ton post

* WIP: deleting removed files

* Deleted removed files and invalidated file metadata cache

* removed file ignore logif from update post API

* Added TestFindExclusives

* Added tests for DeleteForPostByIds

* Added app layer tests

* Added tests

* Added API level tests

* test enhancements

* Fixed a test

* Edit history include file metadata (#29505)

* Send file metadata in edit history metadata

* Added app tests

* Added store tests

* Added tests for populateEditHistoryFileMetadata{

* Added cache to avoid repetitigve DB calls for edits with only message changes

* Added API tests

* i18m fix

* removed commented code

* Improved test helper

* Show attachments in edit history RHS (#29519)

* Send file metadata in edit history metadata

* Added app tests

* Added store tests

* Added tests for populateEditHistoryFileMetadata{

* Added cache to avoid repetitigve DB calls for edits with only message changes

* Added API tests

* i18m fix

* WIUP: displa files in edit

* removed commented code

* Displayed file in edit history

* Handled file icon

* Fixed closing history component on clicking on file

* Simplified selector

* Simplified selector

* Improved test helper

* Disabled action menu on edit history file

* Added tests

* Improved selector

* Updated snapshot

* review Fixes

* restructured componnets

* Updated test

* Updated test

* Restore post api (#29643)

* Restore post version API WIP

* Undelete files WIP

* Added store tests

* Created post restore API

* Updated updatepost safeUpdate signature

* review fixex and improvements

* Fixed an app test

* Added API laer tests

* Added API tests and OpenAPI specs

* Fixed a typo

* Allow editing files when editing posts (#29709)

* WIP - basic view files when editing post

* Cleanup

* bg color

* Added text editor tests for files

* WIP

* WIP

* removed debug log

* Allowed admin to add and remove files on someone else's post

* Handled drafts and scheduled posts

* linter fixes

* Updated snapshot

* server test fix

* CI

* Added doc

* Restore post api integration (#29719)

* WIP - basic view files when editing post

* Cleanup

* bg color

* Added text editor tests for files

* WIP

* WIP

* removed debug log

* Allowed admin to add and remove files on someone else's post

* Handled drafts and scheduled posts

* linter fixes

* Updated snapshot

* server test fix

* Used new API to restore post

* handled edut limit and undo

* lint fix

* added comments

* Fixed edit post item tests

* Fixed buttons

* Aded snapshots

* fix test

* Updated snapshot

* Minor fixes

* fixed snapshot

* Edit file dnd area (#29763)

* dnd wip

* DND continued

* Supported multiple unbind dragster funcs

* lint fixes

* Got center channel file drop working when editing a post

* file dnd working with center channel and rhs

* file dnd working with center channel and rhs

* removed unneeded stopPropogation calls

* cleanup

* DND overlay fix

* Lint fix

* Advanced text editor test updates for file upload overlay

* fixed use upload hook tests

* Updated some more snapshots

* minor cleanup

* Updated i18n

* removed need of array for dragster unbind events

* lint fixes

* edit history cursor

* Fixed bugu causing faliure to delete empty posts (#29778)

* Files in restore confirmation (#29781)

* Added files to restore post confirmation dialog

* Fixed post restore toast colors

* Fixed restore bug

* Fixed restore confirmation toast tests

* a11y improvement and modal width fix

* Edit attachment misc fixes (#29808)

* Removed single image actions in restore post confirmation dialog

* Fixed file drop overlay size and position

* Made edit indiator accessible

* Lint fix

* Added bunch of more tests

* ANother test migrated from enzyme to react testing library

* More test enhancements

* More test enhancements

* More test enhancements

* lint fixes

* Fixed  a test

* Added missing snapshots

* Test fixes
Этот коммит содержится в:
Harshil Sharma
2025-01-13 18:16:56 +05:30
коммит произвёл GitHub
родитель ecdce71fc4
Коммит 6e5a67caec
91 изменённых файлов: 4945 добавлений и 1284 удалений

Просмотреть файл

@@ -975,7 +975,7 @@ type AppIface interface {
OutgoingOAuthConnections() einterfaces.OutgoingOAuthConnectionInterface
PatchChannel(c request.CTX, channel *model.Channel, patch *model.ChannelPatch, userID string) (*model.Channel, *model.AppError)
PatchChannelMembersNotifyProps(c request.CTX, members []*model.ChannelMemberIdentifier, notifyProps map[string]string) ([]*model.ChannelMember, *model.AppError)
PatchPost(c request.CTX, postID string, patch *model.PostPatch) (*model.Post, *model.AppError)
PatchPost(c request.CTX, postID string, patch *model.PostPatch, patchPostOptions *model.UpdatePostOptions) (*model.Post, *model.AppError)
PatchRemoteCluster(rcId string, patch *model.RemoteClusterPatch) (*model.RemoteCluster, *model.AppError)
PatchRetentionPolicy(patch *model.RetentionPolicyWithTeamAndChannelIDs) (*model.RetentionPolicyWithTeamAndChannelCounts, *model.AppError)
PatchRole(role *model.Role, patch *model.RolePatch) (*model.Role, *model.AppError)
@@ -1043,6 +1043,7 @@ type AppIface interface {
ResetSamlAuthDataToEmail(includeDeleted bool, dryRun bool, userIDs []string) (numAffected int, appErr *model.AppError)
RestoreChannel(c request.CTX, channel *model.Channel, userID string) (*model.Channel, *model.AppError)
RestoreGroup(groupID string) (*model.Group, *model.AppError)
RestorePostVersion(c request.CTX, userID, postID, restoreVersionID string) (*model.Post, *model.AppError)
RestoreTeam(teamID string) *model.AppError
RestrictUsersGetByPermissions(c request.CTX, userID string, options *model.UserGetOptions) (*model.UserGetOptions, *model.AppError)
RestrictUsersSearchByPermissions(c request.CTX, userID string, options *model.UserSearchOptions) (*model.UserSearchOptions, *model.AppError)
@@ -1200,7 +1201,7 @@ type AppIface interface {
UpdatePasswordAsUser(c request.CTX, userID, currentPassword, newPassword string) *model.AppError
UpdatePasswordByUserIdSendEmail(c request.CTX, userID, newPassword, method string) *model.AppError
UpdatePasswordSendEmail(c request.CTX, user *model.User, newPassword, method string) *model.AppError
UpdatePost(c request.CTX, receivedUpdatedPost *model.Post, safeUpdate bool) (*model.Post, *model.AppError)
UpdatePost(c request.CTX, receivedUpdatedPost *model.Post, updatePostOptions *model.UpdatePostOptions) (*model.Post, *model.AppError)
UpdatePreferences(c request.CTX, userID string, preferences model.Preferences) *model.AppError
UpdateRemoteCluster(rc *model.RemoteCluster) (*model.RemoteCluster, *model.AppError)
UpdateRemoteClusterTopics(remoteClusterId string, topics string) (*model.RemoteCluster, *model.AppError)

Просмотреть файл

@@ -2647,7 +2647,7 @@ func TestMarkUnreadCRTOffUpdatesThreads(t *testing.T) {
require.Nil(t, appErr)
editedPost := r1.Clone()
editedPost.Message += " edited"
_, appErr = th.App.UpdatePost(th.Context, editedPost, false)
_, appErr = th.App.UpdatePost(th.Context, editedPost, &model.UpdatePostOptions{SafeUpdate: false})
require.Nil(t, appErr)
th.LinkUserToTeam(user3, th.BasicTeam)

Просмотреть файл

@@ -116,7 +116,7 @@ func (a *App) getFileInfosForDraft(rctx request.CTX, draft *model.Draft) ([]*mod
return nil, nil
}
allFileInfos, err := a.Srv().Store().FileInfo().GetByIds(draft.FileIds)
allFileInfos, err := a.Srv().Store().FileInfo().GetByIds(draft.FileIds, false, true)
if err != nil {
return nil, model.NewAppError("GetFileInfosForDraft", "app.draft.get_for_draft.app_error", nil, "", http.StatusInternalServerError).Wrap(err)
}

Просмотреть файл

@@ -50,6 +50,10 @@ type TestHelper struct {
tempWorkspace string
}
type PostOptions func(*model.Post)
type PostPatchOptions func(patch *model.PostPatch)
func setupTestHelper(dbStore store.Store, enterprise bool, includeCacheLayer bool,
updateConfig func(*model.Config), options []Option, tb testing.TB) *TestHelper {
tempWorkspace, err := os.MkdirTemp("", "apptest")
@@ -445,7 +449,7 @@ func (th *TestHelper) CreateGroupChannel(c request.CTX, user1 *model.User, user2
return channel
}
func (th *TestHelper) CreatePost(channel *model.Channel) *model.Post {
func (th *TestHelper) CreatePost(channel *model.Channel, postOptions ...PostOptions) *model.Post {
id := model.NewId()
post := &model.Post{
@@ -455,6 +459,10 @@ func (th *TestHelper) CreatePost(channel *model.Channel) *model.Post {
CreateAt: model.GetMillis() - 10000,
}
for _, option := range postOptions {
option(post)
}
var err *model.AppError
if post, err = th.App.CreatePost(th.Context, post, channel, model.CreatePostFlags{SetOnline: true}); err != nil {
panic(err)
@@ -772,6 +780,41 @@ func (th *TestHelper) AddPermissionToRole(permission string, roleName string) {
}
}
func (th *TestHelper) CreateFileInfo(userId, postId, channelId string) *model.FileInfo {
fileInfo := &model.FileInfo{
Id: model.NewId(),
CreatorId: userId,
PostId: postId,
ChannelId: channelId,
CreateAt: model.GetMillis(),
Name: model.NewRandomString(10),
Path: model.NewRandomString(50),
}
createdFileInfo, err := th.App.Srv().Store().FileInfo().Save(th.Context, fileInfo)
if err != nil {
panic(err)
}
return createdFileInfo
}
func (th *TestHelper) PostPatch(post *model.Post, message string, options ...PostPatchOptions) *model.Post {
postPatch := &model.PostPatch{
Message: model.NewPointer(message),
}
for _, optionFunc := range options {
optionFunc(postPatch)
}
updatedPost, appErr := th.App.PatchPost(th.Context, post.Id, postPatch, nil)
if appErr != nil {
panic(appErr)
}
return updatedPost
}
// This function is copy of storetest/NewTestId
// NewTestId is used for testing as a replacement for model.NewId(). It is a [A-Z0-9] string 26
// characters long. It replaces every odd character with a digit.

Просмотреть файл

@@ -271,7 +271,7 @@ func (a *App) DoPostActionWithCookie(c request.CTX, postID, actionId, userID, se
response.Update.IsPinned = originalIsPinned
response.Update.HasReactions = originalHasReactions
if _, appErr = a.UpdatePost(c, response.Update, false); appErr != nil {
if _, appErr = a.UpdatePost(c, response.Update, &model.UpdatePostOptions{SafeUpdate: false}); appErr != nil {
return "", appErr
}
}

Просмотреть файл

@@ -13433,7 +13433,7 @@ func (a *OpenTracingAppLayer) PatchChannelModerationsForChannel(c request.CTX, c
return resultVar0, resultVar1
}
func (a *OpenTracingAppLayer) PatchPost(c request.CTX, postID string, patch *model.PostPatch) (*model.Post, *model.AppError) {
func (a *OpenTracingAppLayer) PatchPost(c request.CTX, postID string, patch *model.PostPatch, patchPostOptions *model.UpdatePostOptions) (*model.Post, *model.AppError) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.PatchPost")
@@ -13445,7 +13445,7 @@ func (a *OpenTracingAppLayer) PatchPost(c request.CTX, postID string, patch *mod
}()
defer span.Finish()
resultVar0, resultVar1 := a.app.PatchPost(c, postID, patch)
resultVar0, resultVar1 := a.app.PatchPost(c, postID, patch, patchPostOptions)
if resultVar1 != nil {
span.LogFields(spanlog.Error(resultVar1))
@@ -15033,6 +15033,28 @@ func (a *OpenTracingAppLayer) RestoreGroup(groupID string) (*model.Group, *model
return resultVar0, resultVar1
}
func (a *OpenTracingAppLayer) RestorePostVersion(c request.CTX, userID string, postID string, restoreVersionID string) (*model.Post, *model.AppError) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RestorePostVersion")
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.RestorePostVersion(c, userID, postID, restoreVersionID)
if resultVar1 != nil {
span.LogFields(spanlog.Error(resultVar1))
ext.Error.Set(span, true)
}
return resultVar0, resultVar1
}
func (a *OpenTracingAppLayer) RestoreTeam(teamID string) *model.AppError {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.RestoreTeam")
@@ -18660,7 +18682,7 @@ func (a *OpenTracingAppLayer) UpdatePasswordSendEmail(c request.CTX, user *model
return resultVar0
}
func (a *OpenTracingAppLayer) UpdatePost(c request.CTX, receivedUpdatedPost *model.Post, safeUpdate bool) (*model.Post, *model.AppError) {
func (a *OpenTracingAppLayer) UpdatePost(c request.CTX, receivedUpdatedPost *model.Post, updatePostOptions *model.UpdatePostOptions) (*model.Post, *model.AppError) {
origCtx := a.ctx
span, newCtx := tracing.StartSpanWithParentByContext(a.ctx, "app.UpdatePost")
@@ -18672,7 +18694,7 @@ func (a *OpenTracingAppLayer) UpdatePost(c request.CTX, receivedUpdatedPost *mod
}()
defer span.Finish()
resultVar0, resultVar1 := a.app.UpdatePost(c, receivedUpdatedPost, safeUpdate)
resultVar0, resultVar1 := a.app.UpdatePost(c, receivedUpdatedPost, updatePostOptions)
if resultVar1 != nil {
span.LogFields(spanlog.Error(resultVar1))

Просмотреть файл

@@ -744,7 +744,7 @@ func (api *PluginAPI) GetPostsForChannel(channelID string, page, perPage int) (*
}
func (api *PluginAPI) UpdatePost(post *model.Post) (*model.Post, *model.AppError) {
post, appErr := api.app.UpdatePost(api.ctx, post, false)
post, appErr := api.app.UpdatePost(api.ctx, post, &model.UpdatePostOptions{SafeUpdate: false})
if post != nil {
post = post.ForPlugin()
}

Просмотреть файл

@@ -379,7 +379,7 @@ func TestHookMessageWillBeUpdated(t *testing.T) {
require.Nil(t, err)
assert.Equal(t, "message_", post.Message)
post.Message = post.Message + "edited_"
post, err = th.App.UpdatePost(th.Context, post, true)
post, err = th.App.UpdatePost(th.Context, post, &model.UpdatePostOptions{SafeUpdate: true})
require.Nil(t, err)
assert.Equal(t, "message_edited_fromplugin", post.Message)
}
@@ -427,7 +427,7 @@ func TestHookMessageHasBeenUpdated(t *testing.T) {
require.Nil(t, err)
assert.Equal(t, "message_", post.Message)
post.Message = post.Message + "edited"
_, err = th.App.UpdatePost(th.Context, post, true)
_, err = th.App.UpdatePost(th.Context, post, &model.UpdatePostOptions{SafeUpdate: true})
require.Nil(t, err)
}

Просмотреть файл

@@ -458,16 +458,7 @@ func (a *App) addPostPreviewProp(rctx request.CTX, post *model.Post) (*model.Pos
}
func (a *App) attachFilesToPost(rctx request.CTX, post *model.Post) *model.AppError {
var attachedIds []string
for _, fileID := range post.FileIds {
err := a.Srv().Store().FileInfo().AttachToPost(rctx, fileID, post.Id, post.ChannelId, post.UserId)
if err != nil {
rctx.Logger().Warn("Failed to attach file to post", mlog.String("file_id", fileID), mlog.String("post_id", post.Id), mlog.Err(err))
continue
}
attachedIds = append(attachedIds, fileID)
}
attachedIds := a.attachFileIDsToPost(rctx, post.Id, post.ChannelId, post.UserId, post.FileIds)
if len(post.FileIds) != len(attachedIds) {
// We couldn't attach all files to the post, so ensure that post.FileIds reflects what was actually attached
@@ -481,6 +472,20 @@ func (a *App) attachFilesToPost(rctx request.CTX, post *model.Post) *model.AppEr
return nil
}
func (a *App) attachFileIDsToPost(rctx request.CTX, postID, channelID, userID string, fileIDs []string) []string {
var attachedIds []string
for _, fileID := range fileIDs {
err := a.Srv().Store().FileInfo().AttachToPost(rctx, fileID, postID, channelID, userID)
if err != nil {
rctx.Logger().Warn("Failed to attach file to post", mlog.String("file_id", fileID), mlog.String("post_id", postID), mlog.Err(err))
continue
}
attachedIds = append(attachedIds, fileID)
}
return attachedIds
}
// FillInPostProps should be invoked before saving posts to fill in properties such as
// channel_mentions.
//
@@ -674,7 +679,11 @@ func (a *App) DeleteEphemeralPost(rctx request.CTX, userID, postID string) {
a.Publish(message)
}
func (a *App) UpdatePost(c request.CTX, receivedUpdatedPost *model.Post, safeUpdate bool) (*model.Post, *model.AppError) {
func (a *App) UpdatePost(c request.CTX, receivedUpdatedPost *model.Post, updatePostOptions *model.UpdatePostOptions) (*model.Post, *model.AppError) {
if updatePostOptions == nil {
updatePostOptions = model.DefaultUpdatePostOptions()
}
receivedUpdatedPost.SanitizeProps()
postLists, nErr := a.Srv().Store().Post().Get(context.Background(), receivedUpdatedPost.Id, model.GetPostsOptions{}, "", a.Config().GetSanitizeOptions())
@@ -725,11 +734,17 @@ func (a *App) UpdatePost(c request.CTX, receivedUpdatedPost *model.Post, safeUpd
newPost.Hashtags, _ = model.ParseHashtags(receivedUpdatedPost.Message)
}
if !safeUpdate {
if !updatePostOptions.SafeUpdate {
newPost.IsPinned = receivedUpdatedPost.IsPinned
newPost.HasReactions = receivedUpdatedPost.HasReactions
newPost.FileIds = receivedUpdatedPost.FileIds
newPost.SetProps(receivedUpdatedPost.GetProps())
var fileIds []string
fileIds, appErr = a.processPostFileChanges(c, receivedUpdatedPost, oldPost, updatePostOptions)
if appErr != nil {
return nil, appErr
}
newPost.FileIds = fileIds
}
// Avoid deep-equal checks if EditAt was already modified through message change
@@ -928,7 +943,11 @@ func (a *App) setupBroadcastHookForPermalink(rctx request.CTX, post *model.Post,
return nil
}
func (a *App) PatchPost(c request.CTX, postID string, patch *model.PostPatch) (*model.Post, *model.AppError) {
func (a *App) PatchPost(c request.CTX, postID string, patch *model.PostPatch, patchPostOptions *model.UpdatePostOptions) (*model.Post, *model.AppError) {
if patchPostOptions == nil {
patchPostOptions = model.DefaultUpdatePostOptions()
}
post, err := a.GetSinglePost(c, postID, false)
if err != nil {
return nil, err
@@ -950,7 +969,8 @@ func (a *App) PatchPost(c request.CTX, postID string, patch *model.PostPatch) (*
post.Patch(patch)
updatedPost, err := a.UpdatePost(c, post, false)
patchPostOptions.SafeUpdate = false
updatedPost, err := a.UpdatePost(c, post, patchPostOptions)
if err != nil {
return nil, err
}
@@ -2144,9 +2164,30 @@ func (a *App) GetEditHistoryForPost(postID string) ([]*model.Post, *model.AppErr
}
}
if appErr := a.populateEditHistoryFileMetadata(posts); appErr != nil {
return nil, appErr
}
return posts, nil
}
func (a *App) populateEditHistoryFileMetadata(editHistoryPosts []*model.Post) *model.AppError {
for _, post := range editHistoryPosts {
fileInfos, err := a.Srv().Store().FileInfo().GetByIds(post.FileIds, true, true)
if err != nil {
return model.NewAppError("app.populateEditHistoryFileMetadata", "app.file_info.get_by_ids.app_error", map[string]any{"post_id": post.Id}, "", http.StatusInternalServerError).Wrap(err)
}
if post.Metadata == nil {
post.Metadata = &model.PostMetadata{}
}
post.Metadata.Files = fileInfos
}
return nil
}
func (a *App) SetPostReminder(rctx request.CTX, postID, userID string, targetTime int64) *model.AppError {
// Store the reminder in the DB
reminder := &model.PostReminder{

70
server/channels/app/post_file_change.go Обычный файл
Просмотреть файл

@@ -0,0 +1,70 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package app
import (
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/request"
"github.com/mattermost/mattermost/server/public/utils"
)
func (a *App) processPostFileChanges(rctx request.CTX, newPost, oldPost *model.Post, updatePostOptions *model.UpdatePostOptions) (model.StringArray, *model.AppError) {
newFileIDs := model.RemoveDuplicateStrings(newPost.FileIds)
oldFileIDs := model.RemoveDuplicateStrings(oldPost.FileIds)
addedFileIDs, removedFileIDs, unchangedFileIDs := utils.FindExclusives(newFileIDs, oldFileIDs)
if len(addedFileIDs) > 0 {
if updatePostOptions != nil && updatePostOptions.IsRestorePost {
err := a.Srv().Store().FileInfo().RestoreForPostByIds(rctx, newPost.Id, addedFileIDs)
if err != nil {
return nil, model.NewAppError("app.processPostFileChanges", "app.file_info.undelete_for_post_ids.app_error", map[string]any{"post_id": newPost.Id}, "", 0).Wrap(err)
}
} else {
a.attachNewFilesToPost(rctx, newPost, addedFileIDs, unchangedFileIDs)
}
}
if len(removedFileIDs) > 0 {
if appErr := a.detachFilesFromPost(rctx, newPost.Id, removedFileIDs); appErr != nil {
return nil, appErr
}
}
filesChanged := len(addedFileIDs) > 0 || len(removedFileIDs) > 0
if filesChanged {
// if files were modified, invalidate the file metadata cache for the post
// so that the updated file metadata can be returned.
a.Srv().Store().FileInfo().InvalidateFileInfosForPostCache(newPost.Id, false)
}
return newPost.FileIds, nil
}
func (a *App) attachNewFilesToPost(rctx request.CTX, post *model.Post, addedFileIDs, unchangedFileIDs []string) {
// for newly added files, we need to attach them to the post
// intentionally using UserID from session instead of post.UserID
// to support admin attaching files in someone else's post.
// Admins can edit other's posts, including message, removing existing files,
// and attaching new files.
// When an admin uploads new files, they are associated with their user ID. So, when attaching
// these file to a post, we need to search for their FileInfo entry
// by the admin's user ID and not the post author's user ID.
userId := rctx.Session().UserId
attachedFileIDs := a.attachFileIDsToPost(rctx, post.Id, post.ChannelId, userId, addedFileIDs)
if len(attachedFileIDs) != len(addedFileIDs) {
// if not all files could be attached, the final list of files
// is those that could be attached + the existing, unchanged files
post.FileIds = append(attachedFileIDs, unchangedFileIDs...)
}
}
func (a *App) detachFilesFromPost(rctx request.CTX, postId string, removedFileIDs []string) *model.AppError {
if err := a.Srv().Store().FileInfo().DeleteForPostByIds(rctx, postId, removedFileIDs); err != nil {
return model.NewAppError("app.detachFilesFromPost", "app.file_info.delete_for_post_ids.app_error", map[string]any{"post_id": postId}, "", 0).Wrap(err)
}
return nil
}

274
server/channels/app/post_file_change_test.go Обычный файл
Просмотреть файл

@@ -0,0 +1,274 @@
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package app
import (
"testing"
"github.com/mattermost/mattermost/server/public/model"
"github.com/stretchr/testify/require"
)
func TestProcessPostFileChanges(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
t.Run("no files", func(t *testing.T) {
oldPost := &model.Post{FileIds: []string{}}
newPost := &model.Post{FileIds: []string{}}
fileIds, appErr := th.App.processPostFileChanges(th.Context, newPost, oldPost, nil)
require.Nil(t, appErr)
require.Equal(t, 0, len(fileIds))
})
t.Run("have files but nothing changed", func(t *testing.T) {
oldPost := &model.Post{FileIds: []string{"file_id_1", "file_id_2"}}
newPost := &model.Post{FileIds: []string{"file_id_1", "file_id_2"}}
fileIds, appErr := th.App.processPostFileChanges(th.Context, newPost, oldPost, nil)
require.Nil(t, appErr)
require.Equal(t, 2, len(fileIds))
})
t.Run("one file deleted", func(t *testing.T) {
postId := model.NewId()
fileInfo1 := th.CreateFileInfo(th.BasicUser.Id, postId, th.BasicChannel.Id)
fileInfo2 := th.CreateFileInfo(th.BasicUser.Id, postId, th.BasicChannel.Id)
oldPost := &model.Post{
Id: postId,
UserId: th.BasicUser.Id,
ChannelId: th.BasicChannel.Id,
Message: "Message",
CreateAt: model.GetMillis() - 10000,
FileIds: []string{fileInfo1.Id, fileInfo2.Id},
}
newPost := &model.Post{
Id: postId,
UserId: th.BasicUser.Id,
ChannelId: th.BasicChannel.Id,
Message: "Message",
CreateAt: model.GetMillis() - 10000,
FileIds: []string{fileInfo1.Id},
}
fileIds, appErr := th.App.processPostFileChanges(th.Context, newPost, oldPost, nil)
require.Nil(t, appErr)
require.Equal(t, 1, len(fileIds))
require.Equal(t, fileInfo1.Id, fileIds[0])
// verify file2 was soft deleted
updatedFileInfos, err := th.App.Srv().Store().FileInfo().GetForPost(postId, true, true, false)
require.NoError(t, err)
require.Equal(t, 2, len(updatedFileInfos))
for _, fileInfo := range updatedFileInfos {
if fileInfo.Id == fileInfo1.Id {
require.Equal(t, int64(0), fileInfo.DeleteAt)
} else if fileInfo.Id == fileInfo2.Id {
require.Greater(t, fileInfo.DeleteAt, int64(0))
} else {
require.Fail(t, "unexpected file info")
}
}
})
t.Run("one file added", func(t *testing.T) {
postId := model.NewId()
fileInfo1 := th.CreateFileInfo(th.BasicUser.Id, postId, th.BasicChannel.Id)
fileInfo2 := th.CreateFileInfo(th.BasicUser.Id, "", th.BasicChannel.Id)
oldPost := &model.Post{
Id: postId,
UserId: th.BasicUser.Id,
ChannelId: th.BasicChannel.Id,
Message: "Message",
CreateAt: model.GetMillis() - 10000,
FileIds: []string{fileInfo1.Id},
}
newPost := &model.Post{
Id: postId,
UserId: th.BasicUser.Id,
ChannelId: th.BasicChannel.Id,
Message: "Message",
CreateAt: model.GetMillis() - 10000,
FileIds: []string{fileInfo1.Id, fileInfo2.Id},
}
th.Context.Session().UserId = th.BasicUser.Id
fileIds, appErr := th.App.processPostFileChanges(th.Context, newPost, oldPost, nil)
require.Nil(t, appErr)
require.Equal(t, 2, len(fileIds))
require.Contains(t, fileIds, fileInfo1.Id)
require.Contains(t, fileIds, fileInfo2.Id)
// verify file2 is attached to the post
updatedFileInfo2, err := th.App.Srv().Store().FileInfo().Get(fileInfo2.Id)
require.NoError(t, err)
require.Equal(t, postId, updatedFileInfo2.PostId)
})
t.Run("all files removed", func(t *testing.T) {
postId := model.NewId()
fileInfo1 := th.CreateFileInfo(th.BasicUser.Id, postId, th.BasicChannel.Id)
fileInfo2 := th.CreateFileInfo(th.BasicUser.Id, postId, th.BasicChannel.Id)
oldPost := &model.Post{
Id: postId,
UserId: th.BasicUser.Id,
ChannelId: th.BasicChannel.Id,
Message: "Message",
CreateAt: model.GetMillis() - 10000,
FileIds: []string{fileInfo1.Id, fileInfo2.Id},
}
newPost := &model.Post{
Id: postId,
UserId: th.BasicUser.Id,
ChannelId: th.BasicChannel.Id,
Message: "Message",
CreateAt: model.GetMillis() - 10000,
FileIds: []string{},
}
fileIds, appErr := th.App.processPostFileChanges(th.Context, newPost, oldPost, nil)
require.Nil(t, appErr)
require.Equal(t, 0, len(fileIds))
// verify file2 was soft deleted
updatedFileInfos, err := th.App.Srv().Store().FileInfo().GetForPost(postId, true, true, false)
require.NoError(t, err)
require.Equal(t, 2, len(updatedFileInfos))
for _, fileInfo := range updatedFileInfos {
if fileInfo.Id == fileInfo1.Id || fileInfo.Id == fileInfo2.Id {
require.Greater(t, fileInfo.DeleteAt, int64(0))
} else {
require.Fail(t, "unexpected file info")
}
}
})
t.Run("files added when no files existed", func(t *testing.T) {
fileInfo1 := th.CreateFileInfo(th.BasicUser.Id, "", th.BasicChannel.Id)
fileInfo2 := th.CreateFileInfo(th.BasicUser.Id, "", th.BasicChannel.Id)
postId := model.NewId()
oldPost := &model.Post{
Id: postId,
UserId: th.BasicUser.Id,
ChannelId: th.BasicChannel.Id,
Message: "Message",
CreateAt: model.GetMillis() - 10000,
FileIds: []string{},
}
newPost := &model.Post{
Id: postId,
UserId: th.BasicUser.Id,
ChannelId: th.BasicChannel.Id,
Message: "Message",
CreateAt: model.GetMillis() - 10000,
FileIds: []string{fileInfo1.Id, fileInfo2.Id},
}
fileIds, appErr := th.App.processPostFileChanges(th.Context, newPost, oldPost, nil)
require.Nil(t, appErr)
require.Equal(t, 2, len(fileIds))
require.Contains(t, fileIds, fileInfo1.Id)
require.Contains(t, fileIds, fileInfo2.Id)
updatedFileInfo1, err := th.App.Srv().Store().FileInfo().Get(fileInfo2.Id)
require.NoError(t, err)
require.Equal(t, postId, updatedFileInfo1.PostId)
updatedFileInfo2, err := th.App.Srv().Store().FileInfo().Get(fileInfo2.Id)
require.NoError(t, err)
require.Equal(t, postId, updatedFileInfo2.PostId)
})
t.Run("other post's attached file added", func(t *testing.T) {
postId := model.NewId()
fileInfo1 := th.CreateFileInfo(th.BasicUser.Id, postId, th.BasicChannel.Id)
fileInfo2 := th.CreateFileInfo(th.BasicUser.Id, model.NewId(), th.BasicChannel.Id)
oldPost := &model.Post{
Id: postId,
UserId: th.BasicUser.Id,
ChannelId: th.BasicChannel.Id,
Message: "Message",
CreateAt: model.GetMillis() - 10000,
FileIds: []string{fileInfo1.Id},
}
newPost := &model.Post{
Id: postId,
UserId: th.BasicUser.Id,
ChannelId: th.BasicChannel.Id,
Message: "Message",
CreateAt: model.GetMillis() - 10000,
FileIds: []string{fileInfo1.Id, fileInfo2.Id},
}
fileIds, appErr := th.App.processPostFileChanges(th.Context, newPost, oldPost, nil)
require.Nil(t, appErr)
require.Equal(t, 1, len(fileIds))
require.Equal(t, fileInfo1.Id, fileIds[0])
// verify file2 is attached to the post
updatedFileInfo2, err := th.App.Srv().Store().FileInfo().Get(fileInfo2.Id)
require.NoError(t, err)
require.NotEqual(t, postId, updatedFileInfo2.PostId)
})
t.Run("when admin adds a file to other user's post", func(t *testing.T) {
postId := model.NewId()
// admin uploads the files
fileInfo1 := th.CreateFileInfo(th.SystemAdminUser.Id, "", th.BasicChannel.Id)
fileInfo2 := th.CreateFileInfo(th.SystemAdminUser.Id, "", th.BasicChannel.Id)
// basic user's post
oldPost := &model.Post{
Id: postId,
UserId: th.BasicUser.Id,
ChannelId: th.BasicChannel.Id,
Message: "Message",
CreateAt: model.GetMillis() - 10000,
}
newPost := &model.Post{
Id: postId,
UserId: th.BasicUser.Id,
ChannelId: th.BasicChannel.Id,
Message: "Message",
CreateAt: model.GetMillis() - 10000,
FileIds: []string{fileInfo1.Id, fileInfo2.Id}, // admin attaching two files
}
// admin's session
th.Context.Session().UserId = th.SystemAdminUser.Id
fileIds, appErr := th.App.processPostFileChanges(th.Context, newPost, oldPost, nil)
require.Nil(t, appErr)
require.Equal(t, 2, len(fileIds))
require.Contains(t, fileIds, fileInfo1.Id)
require.Contains(t, fileIds, fileInfo2.Id)
// verify files are attached to the post and still belong tyo the admin
updatedFileInfo1, err := th.App.Srv().Store().FileInfo().Get(fileInfo1.Id)
require.NoError(t, err)
require.Equal(t, postId, updatedFileInfo1.PostId)
require.Equal(t, th.SystemAdminUser.Id, updatedFileInfo1.CreatorId)
updatedFileInfo2, err := th.App.Srv().Store().FileInfo().Get(fileInfo2.Id)
require.NoError(t, err)
require.Equal(t, postId, updatedFileInfo2.PostId)
require.Equal(t, th.SystemAdminUser.Id, updatedFileInfo2.CreatorId)
})
}

58
server/channels/app/post_restore.go Обычный файл
Просмотреть файл

@@ -0,0 +1,58 @@
// 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/v8/channels/store"
"github.com/pkg/errors"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/request"
)
func (a *App) RestorePostVersion(c request.CTX, userID, postID, restoreVersionID string) (*model.Post, *model.AppError) {
toRestorePostVersion, err := a.Srv().Store().Post().GetSingle(c, restoreVersionID, true)
if err != nil {
var statusCode int
var notFoundErr *store.ErrNotFound
switch {
case errors.As(err, &notFoundErr):
statusCode = http.StatusNotFound
default:
statusCode = http.StatusInternalServerError
}
return nil, model.NewAppError("RestorePostVersion", "app.post.restore_post_version.get_single.app_error", nil, err.Error(), statusCode)
}
// restoreVersionID needs to be an old version of postID
// this is only a safeguard and this should never happen in practice.
if toRestorePostVersion.OriginalId != postID {
return nil, model.NewAppError("RestorePostVersion", "app.post.restore_post_version.not_an_history_item.app_error", nil, "", http.StatusBadRequest)
}
// the user needs to be the author of the post
// this is only a safeguard and this should never happen in practice.
if toRestorePostVersion.UserId != userID {
return nil, model.NewAppError("RestorePostVersion", "app.post.restore_post_version.not_allowed.app_error", nil, "", http.StatusForbidden)
}
// the old version of post needs to be a deleted post
if toRestorePostVersion.DeleteAt == 0 {
return nil, model.NewAppError("RestorePostVersion", "app.post.restore_post_version.not_valid_post_history_item.app_error", nil, "", http.StatusBadRequest)
}
postPatch := &model.PostPatch{
Message: &toRestorePostVersion.Message,
FileIds: &toRestorePostVersion.FileIds,
}
patchPostOptions := &model.UpdatePostOptions{
IsRestorePost: true,
}
return a.PatchPost(c, postID, postPatch, patchPostOptions)
}

180
server/channels/app/post_restore_test.go Обычный файл
Просмотреть файл

@@ -0,0 +1,180 @@
// 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 TestRestorePostVersion(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
t.Run("is able to restore a post version", func(t *testing.T) {
post := th.CreatePost(th.BasicChannel, func(p *model.Post) {
p.Message = "original message"
})
th.PostPatch(post, "new message 2")
th.PostPatch(post, "new message 3")
// verify post's state
fetchedPost, err := th.App.Srv().Store().Post().GetSingle(th.Context, post.Id, true)
require.NoError(t, err)
require.Equal(t, "new message 3", fetchedPost.Message)
editHistory, appErr := th.App.GetEditHistoryForPost(post.Id)
require.Nil(t, appErr)
require.Equal(t, 2, len(editHistory))
require.Equal(t, "new message 2", editHistory[0].Message)
// now we'll restore a post version
restoredPost, appErr := th.App.RestorePostVersion(th.Context, th.BasicUser.Id, post.Id, editHistory[0].Id)
require.Nil(t, appErr)
require.Equal(t, "new message 2", restoredPost.Message)
// verify from database
fetchedPost, err = th.App.Srv().Store().Post().GetSingle(th.Context, post.Id, true)
require.NoError(t, err)
require.Equal(t, "new message 2", fetchedPost.Message)
// verify that we now have 3 items in post's edit history
editHistory, appErr = th.App.GetEditHistoryForPost(post.Id)
require.Nil(t, appErr)
require.Equal(t, 3, len(editHistory))
require.Equal(t, "new message 3", editHistory[0].Message)
require.Equal(t, "new message 2", editHistory[1].Message)
require.Equal(t, "original message", editHistory[2].Message)
})
t.Run("is able to restore a post version including its files", func(t *testing.T) {
fileBytes := []byte("file contents")
fileInfo, appErr := th.App.UploadFile(th.Context, fileBytes, th.BasicChannel.Id, "file.txt")
require.Nil(t, appErr)
post := th.CreatePost(th.BasicChannel, func(p *model.Post) {
p.FileIds = []string{fileInfo.Id}
p.Message = "original message"
})
// this update removes all files
th.PostPatch(post, "new message 2", func(p *model.PostPatch) {
p.FileIds = &model.StringArray{}
})
// this update only changes the message
th.PostPatch(post, "new message 3")
// verify post's state
fetchedPost, err := th.App.Srv().Store().Post().GetSingle(th.Context, post.Id, true)
require.NoError(t, err)
require.Equal(t, "new message 3", fetchedPost.Message)
require.Empty(t, fetchedPost.FileIds)
editHistory, appErr := th.App.GetEditHistoryForPost(post.Id)
require.Nil(t, appErr)
require.Equal(t, 2, len(editHistory))
require.Equal(t, "new message 2", editHistory[0].Message)
require.Equal(t, 0, len(editHistory[0].FileIds))
require.Equal(t, "original message", editHistory[1].Message)
require.Equal(t, 1, len(editHistory[1].FileIds))
// now we'll restore a post version
restoredPost, appErr := th.App.RestorePostVersion(th.Context, th.BasicUser.Id, post.Id, editHistory[1].Id)
require.Nil(t, appErr)
require.Equal(t, "original message", restoredPost.Message)
require.Equal(t, 1, len(restoredPost.FileIds))
// verify from database
fetchedPost, err = th.App.Srv().Store().Post().GetSingle(th.Context, post.Id, true)
require.NoError(t, err)
require.Equal(t, "original message", fetchedPost.Message)
require.Equal(t, 1, len(fetchedPost.FileIds))
// verify edit history\
editHistory, appErr = th.App.GetEditHistoryForPost(post.Id)
require.Nil(t, appErr)
require.Equal(t, 3, len(editHistory))
require.Equal(t, "new message 3", editHistory[0].Message)
require.Equal(t, 0, len(editHistory[0].FileIds))
require.Equal(t, "new message 2", editHistory[1].Message)
require.Equal(t, 0, len(editHistory[1].FileIds))
require.Equal(t, "original message", editHistory[2].Message)
require.Equal(t, 1, len(editHistory[2].FileIds))
})
t.Run("should return an error if trying to restore a post that is not in any edit history", func(t *testing.T) {
post := th.CreatePost(th.BasicChannel, func(p *model.Post) {
p.Message = "original message"
})
th.PostPatch(post, "new message 2")
th.PostPatch(post, "new message 3")
// verify post's state
fetchedPost, err := th.App.Srv().Store().Post().GetSingle(th.Context, post.Id, true)
require.NoError(t, err)
require.Equal(t, "new message 3", fetchedPost.Message)
// now we'll restore a post version
otherPost := th.CreatePost(th.BasicChannel)
restoredPost, appErr := th.App.RestorePostVersion(th.Context, th.BasicUser.Id, post.Id, otherPost.Id)
require.NotNil(t, appErr)
require.Equal(t, http.StatusBadRequest, appErr.StatusCode)
require.Equal(t, "app.post.restore_post_version.not_an_history_item.app_error", appErr.Id)
require.Nil(t, restoredPost)
// verify from database that the post wasn't modified
fetchedPost, err = th.App.Srv().Store().Post().GetSingle(th.Context, post.Id, true)
require.NoError(t, err)
require.Equal(t, "new message 3", fetchedPost.Message)
})
t.Run("should return an error if the post does not exist", func(t *testing.T) {
restoredPost, appErr := th.App.RestorePostVersion(th.Context, th.BasicUser.Id, model.NewId(), model.NewId())
require.NotNil(t, appErr)
require.Equal(t, http.StatusNotFound, appErr.StatusCode)
require.Equal(t, "app.post.restore_post_version.get_single.app_error", appErr.Id)
require.Nil(t, restoredPost)
})
t.Run("should return an error if the restore post does not exist", func(t *testing.T) {
post := th.CreatePost(th.BasicChannel)
// now we'll restore a post version
invalidRestorePostIUd := model.NewId()
restoredPost, appErr := th.App.RestorePostVersion(th.Context, th.BasicUser.Id, post.Id, invalidRestorePostIUd)
require.NotNil(t, appErr)
require.Equal(t, http.StatusNotFound, appErr.StatusCode)
require.Equal(t, "app.post.restore_post_version.get_single.app_error", appErr.Id)
require.Nil(t, restoredPost)
})
t.Run("should return an error if trying to restore a post that is in some other posts edit history", func(t *testing.T) {
post := th.CreatePost(th.BasicChannel)
th.PostPatch(post, "new message 2")
otherPost := th.CreatePost(th.BasicChannel, func(post *model.Post) {
post.Message = "other post original message"
})
th.PostPatch(otherPost, "other post new message 2")
otherPostEditHistory, appErr := th.App.GetEditHistoryForPost(otherPost.Id)
require.Nil(t, appErr)
require.Equal(t, 1, len(otherPostEditHistory))
require.Equal(t, "other post original message", otherPostEditHistory[0].Message)
// we'll specify post's ID and other post's version ID, his should fail
restoredPost, appErr := th.App.RestorePostVersion(th.Context, th.BasicUser.Id, post.Id, otherPostEditHistory[0].Id)
require.NotNil(t, appErr)
require.Equal(t, "app.post.restore_post_version.not_an_history_item.app_error", appErr.Id)
require.Equal(t, http.StatusBadRequest, appErr.StatusCode)
require.Nil(t, restoredPost)
})
}

Просмотреть файл

@@ -269,7 +269,7 @@ func TestUpdatePostEditAt(t *testing.T) {
post := th.BasicPost.Clone()
post.IsPinned = true
saved, err := th.App.UpdatePost(th.Context, post, true)
saved, err := th.App.UpdatePost(th.Context, post, &model.UpdatePostOptions{SafeUpdate: true})
require.Nil(t, err)
assert.Equal(t, saved.EditAt, post.EditAt, "shouldn't have updated post.EditAt when pinning post")
post = saved.Clone()
@@ -277,7 +277,7 @@ func TestUpdatePostEditAt(t *testing.T) {
time.Sleep(time.Millisecond * 100)
post.Message = model.NewId()
saved, err = th.App.UpdatePost(th.Context, post, true)
saved, err = th.App.UpdatePost(th.Context, post, &model.UpdatePostOptions{SafeUpdate: true})
require.Nil(t, err)
assert.NotEqual(t, saved.EditAt, post.EditAt, "should have updated post.EditAt when updating post message")
@@ -295,7 +295,7 @@ func TestUpdatePostTimeLimit(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.PostEditTimeLimit = -1
})
_, err := th.App.UpdatePost(th.Context, post, true)
_, err := th.App.UpdatePost(th.Context, post, &model.UpdatePostOptions{SafeUpdate: true})
require.Nil(t, err)
th.App.UpdateConfig(func(cfg *model.Config) {
@@ -303,14 +303,14 @@ func TestUpdatePostTimeLimit(t *testing.T) {
})
post.Message = model.NewId()
_, err = th.App.UpdatePost(th.Context, post, true)
_, err = th.App.UpdatePost(th.Context, post, &model.UpdatePostOptions{SafeUpdate: 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(th.Context, post, true)
_, err = th.App.UpdatePost(th.Context, post, &model.UpdatePostOptions{SafeUpdate: true})
require.Nil(t, err, "should allow you to edit an old post because the time check is applied above in the call hierarchy")
th.App.UpdateConfig(func(cfg *model.Config) {
@@ -326,7 +326,7 @@ func TestUpdatePostInArchivedChannel(t *testing.T) {
post := th.CreatePost(archivedChannel)
th.App.DeleteChannel(th.Context, archivedChannel, "")
_, err := th.App.UpdatePost(th.Context, post, true)
_, err := th.App.UpdatePost(th.Context, post, &model.UpdatePostOptions{SafeUpdate: true})
require.NotNil(t, err)
require.Equal(t, "api.post.update_post.can_not_update_post_in_deleted.error", err.Id)
}
@@ -472,7 +472,7 @@ func TestUpdatePostPluginHooks(t *testing.T) {
require.Nil(t, err)
post.Message = "new message"
updatedPost, err := th.App.UpdatePost(th.Context, post, false)
updatedPost, err := th.App.UpdatePost(th.Context, post, nil)
require.Nil(t, updatedPost)
require.NotNil(t, err)
require.Equal(t, "Post rejected by plugin. rejected", err.Id)
@@ -539,7 +539,7 @@ func TestUpdatePostPluginHooks(t *testing.T) {
require.Nil(t, err)
post.Message = "new message"
updatedPost, err := th.App.UpdatePost(th.Context, post, false)
updatedPost, err := th.App.UpdatePost(th.Context, post, nil)
require.Nil(t, err)
require.NotNil(t, updatedPost)
require.Equal(t, "2 new message 1", updatedPost.Message)
@@ -591,7 +591,7 @@ func TestPostChannelMentions(t *testing.T) {
}, post.GetProp("channel_mentions"))
post.Message = fmt.Sprintf("goodbye, ~%v!", channelToMention2.Name)
result, err := th.App.UpdatePost(th.Context, post, false)
result, err := th.App.UpdatePost(th.Context, post, nil)
require.Nil(t, err)
assert.Equal(t, map[string]any{
"mention-test2": map[string]any{
@@ -601,7 +601,7 @@ func TestPostChannelMentions(t *testing.T) {
}, result.GetProp("channel_mentions"))
result.Message = "no more mentions!"
result, err = th.App.UpdatePost(th.Context, result, false)
result, err = th.App.UpdatePost(th.Context, result, nil)
require.Nil(t, err)
assert.Nil(t, result.GetProp("channel_mentions"))
}
@@ -1123,7 +1123,7 @@ func TestCreatePost(t *testing.T) {
go func() {
defer wg.Done()
post := previewPost.Clone()
th.App.UpdatePost(th.Context, post, false)
th.App.UpdatePost(th.Context, post, nil)
}()
}
@@ -1194,7 +1194,7 @@ func TestPatchPost(t *testing.T) {
Message: model.NewPointer("![image](" + imageURL + ")"),
}
rpost, err = th.App.PatchPost(th.Context, rpost.Id, patch)
rpost, err = th.App.PatchPost(th.Context, rpost.Id, patch, nil)
require.Nil(t, err)
assert.Equal(t, "![image]("+proxiedImageURL+")", rpost.Message)
})
@@ -1217,13 +1217,13 @@ func TestPatchPost(t *testing.T) {
t.Run("Does not set prop when user has USE_CHANNEL_MENTIONS", func(t *testing.T) {
patchWithNoMention := &model.PostPatch{Message: model.NewPointer("This patch has no channel mention")}
rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithNoMention)
rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithNoMention, nil)
require.Nil(t, err)
assert.Equal(t, rpost.GetProps(), model.StringInterface{})
patchWithMention := &model.PostPatch{Message: model.NewPointer("This patch has a mention now @here")}
rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithMention)
rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithMention, nil)
require.Nil(t, err)
assert.Equal(t, rpost.GetProps(), model.StringInterface{})
})
@@ -1233,13 +1233,13 @@ func TestPatchPost(t *testing.T) {
th.RemovePermissionFromRole(model.PermissionUseChannelMentions.Id, model.ChannelAdminRoleId)
patchWithNoMention := &model.PostPatch{Message: model.NewPointer("This patch still does not have a mention")}
rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithNoMention)
rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithNoMention, nil)
require.Nil(t, err)
assert.Equal(t, rpost.GetProps(), model.StringInterface{})
patchWithMention := &model.PostPatch{Message: model.NewPointer("This patch has a mention now @here")}
rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithMention)
rpost, err = th.App.PatchPost(th.Context, rpost.Id, patchWithMention, nil)
require.Nil(t, err)
assert.Equal(t, rpost.GetProp(model.PostPropsMentionHighlightDisabled), true)
@@ -1433,7 +1433,7 @@ func TestPatchPostInArchivedChannel(t *testing.T) {
post := th.CreatePost(archivedChannel)
th.App.DeleteChannel(th.Context, archivedChannel, "")
_, err := th.App.PatchPost(th.Context, post.Id, &model.PostPatch{IsPinned: model.NewPointer(true)})
_, err := th.App.PatchPost(th.Context, post.Id, &model.PostPatch{IsPinned: model.NewPointer(true)}, nil)
require.NotNil(t, err)
require.Equal(t, "api.post.patch_post.can_not_update_post_in_deleted.error", err.Id)
}
@@ -1539,7 +1539,7 @@ func TestUpdatePost(t *testing.T) {
post.Id = rpost.Id
post.Message = "![image](" + imageURL + ")"
rpost, err = th.App.UpdatePost(th.Context, post, false)
rpost, err = th.App.UpdatePost(th.Context, post, nil)
require.Nil(t, err)
assert.Equal(t, "![image]("+proxiedImageURL+")", rpost.Message)
})
@@ -1578,7 +1578,7 @@ func TestUpdatePost(t *testing.T) {
assert.Equal(t, model.StringInterface{}, testPost.GetProps())
testPost.Message = permalink
testPost, err = th.App.UpdatePost(th.Context, testPost, false)
testPost, err = th.App.UpdatePost(th.Context, testPost, nil)
require.Nil(t, err)
assert.Equal(t, model.StringInterface{model.PostPropsPreviewedPost: referencedPost.Id}, testPost.GetProps())
})
@@ -1639,7 +1639,7 @@ func TestUpdatePost(t *testing.T) {
permalink := fmt.Sprintf("%s/%s/pl/%s", *th.App.Config().ServiceSettings.SiteURL, th.BasicTeam.Name, referencedPost.Id)
previewPost.Message = permalink
previewPost, err = th.App.UpdatePost(th.Context, previewPost, false)
previewPost, err = th.App.UpdatePost(th.Context, previewPost, nil)
require.Nil(t, err)
require.Len(t, previewPost.Metadata.Embeds, testCase.Length)
@@ -3126,7 +3126,7 @@ func TestSharedChannelSyncForPostActions(t *testing.T) {
}, channel, model.CreatePostFlags{SetOnline: true})
require.Nil(t, err, "Creating a post should not error")
_, err = th.App.UpdatePost(th.Context, post, true)
_, err = th.App.UpdatePost(th.Context, post, &model.UpdatePostOptions{SafeUpdate: true})
require.Nil(t, err, "Updating a post should not error")
require.Len(t, sharedChannelService.channelNotifications, 2)
@@ -3410,7 +3410,6 @@ func TestComputeLastAccessiblePostTime(t *testing.T) {
}
func TestGetEditHistoryForPost(t *testing.T) {
t.Skip("This needs fixing, OriginalId seems to be empty for all posts")
th := Setup(t).InitBasic()
defer th.TearDown()
@@ -3427,7 +3426,7 @@ func TestGetEditHistoryForPost(t *testing.T) {
patch := &model.PostPatch{
Message: model.NewPointer("new message edited"),
}
_, err1 := th.App.PatchPost(th.Context, rpost.Id, patch)
_, err1 := th.App.PatchPost(th.Context, rpost.Id, patch, nil)
require.Nil(t, err1)
// update the post message again
@@ -3435,14 +3434,13 @@ func TestGetEditHistoryForPost(t *testing.T) {
Message: model.NewPointer("new message edited again"),
}
_, err2 := th.App.PatchPost(th.Context, rpost.Id, patch)
_, err2 := th.App.PatchPost(th.Context, rpost.Id, patch, nil)
require.Nil(t, err2)
// get the edit history
edits, err := th.App.GetEditHistoryForPost(post.Id)
require.Nil(t, err)
t.Run("should return the edit history", func(t *testing.T) {
edits, err := th.App.GetEditHistoryForPost(post.Id)
require.Nil(t, err)
require.Len(t, edits, 2)
require.Equal(t, "new message edited", edits[0].Message)
require.Equal(t, "new message", edits[1].Message)
@@ -3453,6 +3451,103 @@ func TestGetEditHistoryForPost(t *testing.T) {
require.NotNil(t, err)
require.Empty(t, edits)
})
t.Run("edit history should contain file metadata", func(t *testing.T) {
fileBytes := []byte("file contents")
fileInfo, err := th.App.UploadFile(th.Context, fileBytes, th.BasicChannel.Id, "file.txt")
require.Nil(t, err)
post := &model.Post{
ChannelId: th.BasicChannel.Id,
Message: "new message",
UserId: th.BasicUser.Id,
FileIds: model.StringArray{fileInfo.Id},
}
_, err = th.App.CreatePost(th.Context, post, th.BasicChannel, model.CreatePostFlags{SetOnline: true})
require.Nil(t, err)
patch := &model.PostPatch{
Message: model.NewPointer("new message edited"),
}
_, appErr := th.App.PatchPost(th.Context, post.Id, patch, nil)
require.Nil(t, appErr)
patch = &model.PostPatch{
Message: model.NewPointer("new message edited 2"),
}
_, appErr = th.App.PatchPost(th.Context, post.Id, patch, nil)
require.Nil(t, appErr)
patch = &model.PostPatch{
Message: model.NewPointer("new message edited 3"),
}
_, appErr = th.App.PatchPost(th.Context, post.Id, patch, nil)
require.Nil(t, appErr)
edits, err := th.App.GetEditHistoryForPost(post.Id)
require.Nil(t, err)
require.Len(t, edits, 3)
for _, edit := range edits {
require.Len(t, edit.FileIds, 1)
require.Equal(t, fileInfo.Id, edit.FileIds[0])
require.Len(t, edit.Metadata.Files, 1)
require.Equal(t, fileInfo.Id, edit.Metadata.Files[0].Id)
}
})
t.Run("edit history should contain file metadata even if the file info is deleted", func(t *testing.T) {
fileBytes := []byte("file contents")
fileInfo, appErr := th.App.UploadFile(th.Context, fileBytes, th.BasicChannel.Id, "file.txt")
require.Nil(t, appErr)
post := &model.Post{
ChannelId: th.BasicChannel.Id,
Message: "new message",
UserId: th.BasicUser.Id,
FileIds: model.StringArray{fileInfo.Id},
}
_, appErr = th.App.CreatePost(th.Context, post, th.BasicChannel, model.CreatePostFlags{SetOnline: true})
require.Nil(t, appErr)
patch := &model.PostPatch{
Message: model.NewPointer("new message edited"),
}
_, appErr = th.App.PatchPost(th.Context, post.Id, patch, nil)
require.Nil(t, appErr)
patch = &model.PostPatch{
Message: model.NewPointer("new message edited 2"),
}
_, appErr = th.App.PatchPost(th.Context, post.Id, patch, nil)
require.Nil(t, appErr)
patch = &model.PostPatch{
Message: model.NewPointer("new message edited 3"),
}
_, appErr = th.App.PatchPost(th.Context, post.Id, patch, nil)
require.Nil(t, appErr)
// now delete the file info, and it should still be include in edit history metadata
_, err := th.App.Srv().Store().FileInfo().DeleteForPost(th.Context, post.Id)
require.NoError(t, err)
edits, appErr := th.App.GetEditHistoryForPost(post.Id)
require.Nil(t, appErr)
require.Len(t, edits, 3)
for _, edit := range edits {
require.Len(t, edit.FileIds, 1)
require.Equal(t, fileInfo.Id, edit.FileIds[0])
require.Len(t, edit.Metadata.Files, 1)
require.Equal(t, fileInfo.Id, edit.Metadata.Files[0].Id)
require.Greater(t, edit.Metadata.Files[0].DeleteAt, int64(0))
}
})
}
func TestCopyWranglerPostlist(t *testing.T) {
@@ -3731,3 +3826,121 @@ func TestSendTestMessage(t *testing.T) {
assert.NotEmpty(t, post.GetProp(model.PostPropsForceNotification))
})
}
func TestPopulateEditHistoryFileMetadata(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
t.Run("should populate file metadata for all posts", func(t *testing.T) {
fileInfo1, err := th.App.Srv().Store().FileInfo().Save(th.Context,
&model.FileInfo{
CreatorId: th.BasicUser.Id,
Path: "path.txt",
})
require.NoError(t, err)
fileInfo2, err := th.App.Srv().Store().FileInfo().Save(th.Context,
&model.FileInfo{
CreatorId: th.BasicUser.Id,
Path: "path.txt",
})
require.NoError(t, err)
post1 := th.CreatePost(th.BasicChannel, func(post *model.Post) {
post.FileIds = model.StringArray{fileInfo1.Id}
})
post2 := th.CreatePost(th.BasicChannel, func(post *model.Post) {
post.FileIds = model.StringArray{fileInfo2.Id}
})
appErr := th.App.populateEditHistoryFileMetadata([]*model.Post{post1, post2})
require.Nil(t, appErr)
require.Len(t, post1.Metadata.Files, 1)
require.Equal(t, fileInfo1.Id, post1.Metadata.Files[0].Id)
require.Len(t, post2.Metadata.Files, 1)
require.Equal(t, fileInfo2.Id, post2.Metadata.Files[0].Id)
})
t.Run("should populate file metadata even for deleted posts", func(t *testing.T) {
fileInfo1, err := th.App.Srv().Store().FileInfo().Save(th.Context,
&model.FileInfo{
CreatorId: th.BasicUser.Id,
Path: "path.txt",
})
require.NoError(t, err)
fileInfo2, err := th.App.Srv().Store().FileInfo().Save(th.Context,
&model.FileInfo{
CreatorId: th.BasicUser.Id,
Path: "path.txt",
})
require.NoError(t, err)
post1 := th.CreatePost(th.BasicChannel, func(post *model.Post) {
post.FileIds = model.StringArray{fileInfo1.Id}
})
post2 := th.CreatePost(th.BasicChannel, func(post *model.Post) {
post.FileIds = model.StringArray{fileInfo2.Id}
})
_, appErr := th.App.DeletePost(th.Context, post1.Id, th.BasicUser.Id)
require.Nil(t, appErr)
_, appErr = th.App.DeletePost(th.Context, post2.Id, th.BasicUser.Id)
require.Nil(t, appErr)
appErr = th.App.populateEditHistoryFileMetadata([]*model.Post{post1, post2})
require.Nil(t, appErr)
require.Len(t, post1.Metadata.Files, 1)
require.Equal(t, fileInfo1.Id, post1.Metadata.Files[0].Id)
require.Len(t, post2.Metadata.Files, 1)
require.Equal(t, fileInfo2.Id, post2.Metadata.Files[0].Id)
})
t.Run("should populate file metadata even for deleted fileInfos", func(t *testing.T) {
fileInfo1, err := th.App.Srv().Store().FileInfo().Save(th.Context,
&model.FileInfo{
CreatorId: th.BasicUser.Id,
Path: "path.txt",
})
require.NoError(t, err)
fileInfo2, err := th.App.Srv().Store().FileInfo().Save(th.Context,
&model.FileInfo{
CreatorId: th.BasicUser.Id,
Path: "path.txt",
})
require.NoError(t, err)
post1 := th.CreatePost(th.BasicChannel, func(post *model.Post) {
post.FileIds = model.StringArray{fileInfo1.Id}
})
post2 := th.CreatePost(th.BasicChannel, func(post *model.Post) {
post.FileIds = model.StringArray{fileInfo2.Id}
})
_, err = th.App.Srv().Store().FileInfo().DeleteForPost(th.Context, post1.Id)
require.NoError(t, err)
_, err = th.App.Srv().Store().FileInfo().DeleteForPost(th.Context, post2.Id)
require.NoError(t, err)
appErr := th.App.populateEditHistoryFileMetadata([]*model.Post{post1, post2})
require.Nil(t, appErr)
require.Len(t, post1.Metadata.Files, 1)
require.Equal(t, fileInfo1.Id, post1.Metadata.Files[0].Id)
require.Greater(t, post1.Metadata.Files[0].DeleteAt, int64(0))
require.Len(t, post2.Metadata.Files, 1)
require.Equal(t, fileInfo2.Id, post2.Metadata.Files[0].Id)
require.Greater(t, post2.Metadata.Files[0].DeleteAt, int64(0))
})
}