Skip to content

Commit d5f2c9d

Browse files
wxiaoguangsilverwind
andauthoredApr 20, 2023
Fix issue attachment handling (#24202) (#24221)
Backport #24202 Close #24195 Fix the bug: 1. The old code doesn't handle `removedfile` event correctly 2. The old code doesn't provide attachments for type=CommentTypeReview --------- Co-authored-by: silverwind <me@silverwind.io>
1 parent 95c2cb4 commit d5f2c9d

File tree

8 files changed

+132
-130
lines changed

8 files changed

+132
-130
lines changed
 

‎models/issues/comment.go

+71-78
Original file line numberDiff line numberDiff line change
@@ -52,84 +52,61 @@ func (err ErrCommentNotExist) Unwrap() error {
5252
// CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
5353
type CommentType int
5454

55-
// define unknown comment type
56-
const (
57-
CommentTypeUnknown CommentType = -1
58-
)
55+
// CommentTypeUndefined is used to search for comments of any type
56+
const CommentTypeUndefined CommentType = -1
5957

60-
// Enumerate all the comment types
6158
const (
62-
// 0 Plain comment, can be associated with a commit (CommitID > 0) and a line (LineNum > 0)
63-
CommentTypeComment CommentType = iota
64-
CommentTypeReopen // 1
65-
CommentTypeClose // 2
66-
67-
// 3 References.
68-
CommentTypeIssueRef
69-
// 4 Reference from a commit (not part of a pull request)
70-
CommentTypeCommitRef
71-
// 5 Reference from a comment
72-
CommentTypeCommentRef
73-
// 6 Reference from a pull request
74-
CommentTypePullRef
75-
// 7 Labels changed
76-
CommentTypeLabel
77-
// 8 Milestone changed
78-
CommentTypeMilestone
79-
// 9 Assignees changed
80-
CommentTypeAssignees
81-
// 10 Change Title
82-
CommentTypeChangeTitle
83-
// 11 Delete Branch
84-
CommentTypeDeleteBranch
85-
// 12 Start a stopwatch for time tracking
86-
CommentTypeStartTracking
87-
// 13 Stop a stopwatch for time tracking
88-
CommentTypeStopTracking
89-
// 14 Add time manual for time tracking
90-
CommentTypeAddTimeManual
91-
// 15 Cancel a stopwatch for time tracking
92-
CommentTypeCancelTracking
93-
// 16 Added a due date
94-
CommentTypeAddedDeadline
95-
// 17 Modified the due date
96-
CommentTypeModifiedDeadline
97-
// 18 Removed a due date
98-
CommentTypeRemovedDeadline
99-
// 19 Dependency added
100-
CommentTypeAddDependency
101-
// 20 Dependency removed
102-
CommentTypeRemoveDependency
103-
// 21 Comment a line of code
104-
CommentTypeCode
105-
// 22 Reviews a pull request by giving general feedback
106-
CommentTypeReview
107-
// 23 Lock an issue, giving only collaborators access
108-
CommentTypeLock
109-
// 24 Unlocks a previously locked issue
110-
CommentTypeUnlock
111-
// 25 Change pull request's target branch
112-
CommentTypeChangeTargetBranch
113-
// 26 Delete time manual for time tracking
114-
CommentTypeDeleteTimeManual
115-
// 27 add or remove Request from one
116-
CommentTypeReviewRequest
117-
// 28 merge pull request
118-
CommentTypeMergePull
119-
// 29 push to PR head branch
120-
CommentTypePullRequestPush
121-
// 30 Project changed
122-
CommentTypeProject
123-
// 31 Project board changed
124-
CommentTypeProjectBoard
125-
// 32 Dismiss Review
126-
CommentTypeDismissReview
127-
// 33 Change issue ref
128-
CommentTypeChangeIssueRef
129-
// 34 pr was scheduled to auto merge when checks succeed
130-
CommentTypePRScheduledToAutoMerge
131-
// 35 pr was un scheduled to auto merge when checks succeed
132-
CommentTypePRUnScheduledToAutoMerge
59+
CommentTypeComment CommentType = iota // 0 Plain comment, can be associated with a commit (CommitID > 0) and a line (LineNum > 0)
60+
61+
CommentTypeReopen // 1
62+
CommentTypeClose // 2
63+
64+
CommentTypeIssueRef // 3 References.
65+
CommentTypeCommitRef // 4 Reference from a commit (not part of a pull request)
66+
CommentTypeCommentRef // 5 Reference from a comment
67+
CommentTypePullRef // 6 Reference from a pull request
68+
69+
CommentTypeLabel // 7 Labels changed
70+
CommentTypeMilestone // 8 Milestone changed
71+
CommentTypeAssignees // 9 Assignees changed
72+
CommentTypeChangeTitle // 10 Change Title
73+
CommentTypeDeleteBranch // 11 Delete Branch
74+
75+
CommentTypeStartTracking // 12 Start a stopwatch for time tracking
76+
CommentTypeStopTracking // 13 Stop a stopwatch for time tracking
77+
CommentTypeAddTimeManual // 14 Add time manual for time tracking
78+
CommentTypeCancelTracking // 15 Cancel a stopwatch for time tracking
79+
CommentTypeAddedDeadline // 16 Added a due date
80+
CommentTypeModifiedDeadline // 17 Modified the due date
81+
CommentTypeRemovedDeadline // 18 Removed a due date
82+
83+
CommentTypeAddDependency // 19 Dependency added
84+
CommentTypeRemoveDependency // 20 Dependency removed
85+
86+
CommentTypeCode // 21 Comment a line of code
87+
CommentTypeReview // 22 Reviews a pull request by giving general feedback
88+
89+
CommentTypeLock // 23 Lock an issue, giving only collaborators access
90+
CommentTypeUnlock // 24 Unlocks a previously locked issue
91+
92+
CommentTypeChangeTargetBranch // 25 Change pull request's target branch
93+
94+
CommentTypeDeleteTimeManual // 26 Delete time manual for time tracking
95+
96+
CommentTypeReviewRequest // 27 add or remove Request from one
97+
CommentTypeMergePull // 28 merge pull request
98+
CommentTypePullRequestPush // 29 push to PR head branch
99+
100+
CommentTypeProject // 30 Project changed
101+
CommentTypeProjectBoard // 31 Project board changed
102+
103+
CommentTypeDismissReview // 32 Dismiss Review
104+
105+
CommentTypeChangeIssueRef // 33 Change issue ref
106+
107+
CommentTypePRScheduledToAutoMerge // 34 pr was scheduled to auto merge when checks succeed
108+
CommentTypePRUnScheduledToAutoMerge // 35 pr was un scheduled to auto merge when checks succeed
109+
133110
)
134111

135112
var commentStrings = []string{
@@ -181,7 +158,23 @@ func AsCommentType(typeName string) CommentType {
181158
return CommentType(index)
182159
}
183160
}
184-
return CommentTypeUnknown
161+
return CommentTypeUndefined
162+
}
163+
164+
func (t CommentType) HasContentSupport() bool {
165+
switch t {
166+
case CommentTypeComment, CommentTypeCode, CommentTypeReview:
167+
return true
168+
}
169+
return false
170+
}
171+
172+
func (t CommentType) HasAttachmentSupport() bool {
173+
switch t {
174+
case CommentTypeComment, CommentTypeCode, CommentTypeReview:
175+
return true
176+
}
177+
return false
185178
}
186179

187180
// RoleDescriptor defines comment tag type
@@ -1039,7 +1032,7 @@ func (opts *FindCommentsOptions) ToConds() builder.Cond {
10391032
if opts.Before > 0 {
10401033
cond = cond.And(builder.Lte{"comment.updated_unix": opts.Before})
10411034
}
1042-
if opts.Type != CommentTypeUnknown {
1035+
if opts.Type != CommentTypeUndefined {
10431036
cond = cond.And(builder.Eq{"comment.type": opts.Type})
10441037
}
10451038
if opts.Line != 0 {

‎models/issues/comment_test.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,9 @@ func TestFetchCodeComments(t *testing.T) {
6464
}
6565

6666
func TestAsCommentType(t *testing.T) {
67-
assert.Equal(t, issues_model.CommentTypeUnknown, issues_model.AsCommentType(""))
68-
assert.Equal(t, issues_model.CommentTypeUnknown, issues_model.AsCommentType("nonsense"))
67+
assert.Equal(t, issues_model.CommentType(0), issues_model.CommentTypeComment)
68+
assert.Equal(t, issues_model.CommentTypeUndefined, issues_model.AsCommentType(""))
69+
assert.Equal(t, issues_model.CommentTypeUndefined, issues_model.AsCommentType("nonsense"))
6970
assert.Equal(t, issues_model.CommentTypeComment, issues_model.AsCommentType("comment"))
7071
assert.Equal(t, issues_model.CommentTypePRUnScheduledToAutoMerge, issues_model.AsCommentType("pull_cancel_scheduled_merge"))
7172
}

‎models/issues/issue.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ func (issue *Issue) LoadPullRequest(ctx context.Context) (err error) {
267267
}
268268

269269
func (issue *Issue) loadComments(ctx context.Context) (err error) {
270-
return issue.loadCommentsByType(ctx, CommentTypeUnknown)
270+
return issue.loadCommentsByType(ctx, CommentTypeUndefined)
271271
}
272272

273273
// LoadDiscussComments loads discuss comments

‎routers/api/v1/repo/issue_comment.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ func ListIssueCommentsAndTimeline(ctx *context.APIContext) {
173173
IssueID: issue.ID,
174174
Since: since,
175175
Before: before,
176-
Type: issues_model.CommentTypeUnknown,
176+
Type: issues_model.CommentTypeUndefined,
177177
}
178178

179179
comments, err := issues_model.FindComments(ctx, opts)
@@ -549,7 +549,7 @@ func editIssueComment(ctx *context.APIContext, form api.EditIssueCommentOption)
549549
return
550550
}
551551

552-
if comment.Type != issues_model.CommentTypeComment && comment.Type != issues_model.CommentTypeReview && comment.Type != issues_model.CommentTypeCode {
552+
if !comment.Type.HasContentSupport() {
553553
ctx.Status(http.StatusNoContent)
554554
return
555555
}

‎routers/web/repo/issue.go

+16-12
Original file line numberDiff line numberDiff line change
@@ -1563,7 +1563,7 @@ func ViewIssue(ctx *context.Context) {
15631563
return
15641564
}
15651565
}
1566-
} else if comment.Type == issues_model.CommentTypeCode || comment.Type == issues_model.CommentTypeReview || comment.Type == issues_model.CommentTypeDismissReview {
1566+
} else if comment.Type.HasContentSupport() {
15671567
comment.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
15681568
URLPrefix: ctx.Repo.RepoLink,
15691569
Metas: ctx.Repo.Repository.ComposeMetas(),
@@ -2800,7 +2800,7 @@ func UpdateCommentContent(ctx *context.Context) {
28002800
return
28012801
}
28022802

2803-
if comment.Type != issues_model.CommentTypeComment && comment.Type != issues_model.CommentTypeReview && comment.Type != issues_model.CommentTypeCode {
2803+
if !comment.Type.HasContentSupport() {
28042804
ctx.Error(http.StatusNoContent)
28052805
return
28062806
}
@@ -2864,7 +2864,7 @@ func DeleteComment(ctx *context.Context) {
28642864
if !ctx.IsSigned || (ctx.Doer.ID != comment.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(comment.Issue.IsPull)) {
28652865
ctx.Error(http.StatusForbidden)
28662866
return
2867-
} else if comment.Type != issues_model.CommentTypeComment && comment.Type != issues_model.CommentTypeCode {
2867+
} else if !comment.Type.HasContentSupport() {
28682868
ctx.Error(http.StatusNoContent)
28692869
return
28702870
}
@@ -3010,7 +3010,7 @@ func ChangeCommentReaction(ctx *context.Context) {
30103010
return
30113011
}
30123012

3013-
if comment.Type != issues_model.CommentTypeComment && comment.Type != issues_model.CommentTypeCode && comment.Type != issues_model.CommentTypeReview {
3013+
if !comment.Type.HasContentSupport() {
30143014
ctx.Error(http.StatusNoContent)
30153015
return
30163016
}
@@ -3126,15 +3126,19 @@ func GetCommentAttachments(ctx *context.Context) {
31263126
ctx.NotFoundOrServerError("GetCommentByID", issues_model.IsErrCommentNotExist, err)
31273127
return
31283128
}
3129+
3130+
if !comment.Type.HasAttachmentSupport() {
3131+
ctx.ServerError("GetCommentAttachments", fmt.Errorf("comment type %v does not support attachments", comment.Type))
3132+
return
3133+
}
3134+
31293135
attachments := make([]*api.Attachment, 0)
3130-
if comment.Type == issues_model.CommentTypeComment {
3131-
if err := comment.LoadAttachments(ctx); err != nil {
3132-
ctx.ServerError("LoadAttachments", err)
3133-
return
3134-
}
3135-
for i := 0; i < len(comment.Attachments); i++ {
3136-
attachments = append(attachments, convert.ToAttachment(comment.Attachments[i]))
3137-
}
3136+
if err := comment.LoadAttachments(ctx); err != nil {
3137+
ctx.ServerError("LoadAttachments", err)
3138+
return
3139+
}
3140+
for i := 0; i < len(comment.Attachments); i++ {
3141+
attachments = append(attachments, convert.ToAttachment(comment.Attachments[i]))
31383142
}
31393143
ctx.JSON(http.StatusOK, attachments)
31403144
}

‎services/issue/comments.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,7 @@ func CreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_m
9090

9191
// UpdateComment updates information of comment.
9292
func UpdateComment(ctx context.Context, c *issues_model.Comment, doer *user_model.User, oldContent string) error {
93-
needsContentHistory := c.Content != oldContent &&
94-
(c.Type == issues_model.CommentTypeComment || c.Type == issues_model.CommentTypeReview || c.Type == issues_model.CommentTypeCode)
93+
needsContentHistory := c.Content != oldContent && c.Type.HasContentSupport()
9594
if needsContentHistory {
9695
hasContentHistory, err := issues_model.HasIssueContentHistory(ctx, c.IssueID, c.ID)
9796
if err != nil {

‎templates/repo/issue/view_content/attachments.tmpl

+9-9
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
<div class="dropzone-attachments">
22
{{if .Attachments}}
3-
<div class="ui clearing divider"></div>
3+
<div class="ui divider"></div>
44
{{end}}
5-
<div class="ui middle aligned padded grid">
6-
{{$hasThumbnails := false}}
7-
{{- range .Attachments -}}
8-
<div class="twelve wide column" style="padding: 6px;">
5+
{{$hasThumbnails := false}}
6+
{{- range .Attachments -}}
7+
<div class="gt-df">
8+
<div class="gt-f1 gt-p-3">
99
<a target="_blank" rel="noopener noreferrer" href="{{.DownloadURL}}" title='{{$.ctx.locale.Tr "repo.issues.attachment.open_tab" .Name}}'>
1010
{{if FilenameIsImage .Name}}
1111
{{if not (containGeneric $.Content .UUID)}}
@@ -18,14 +18,14 @@
1818
<span><strong>{{.Name}}</strong></span>
1919
</a>
2020
</div>
21-
<div class="four wide column" style="padding: 0px;">
21+
<div class="gt-p-3 gt-df gt-ac">
2222
<span class="ui text grey right">{{.Size | FileSize}}</span>
2323
</div>
24-
{{end -}}
25-
</div>
24+
</div>
25+
{{end -}}
2626

2727
{{if $hasThumbnails}}
28-
<div class="ui clearing divider"></div>
28+
<div class="ui divider"></div>
2929
<div class="ui small thumbnails">
3030
{{- range .Attachments -}}
3131
{{if FilenameIsImage .Name}}

‎web_src/js/features/repo-legacy.js

+29-24
Original file line numberDiff line numberDiff line change
@@ -333,20 +333,19 @@ async function onEditContent(event) {
333333
let dz;
334334
const $dropzone = $editContentZone.find('.dropzone');
335335
if ($dropzone.length === 1) {
336-
$dropzone.data('saved', false);
337-
338-
const fileUuidDict = {};
339-
dz = await createDropzone($dropzone[0], {
340-
url: $dropzone.data('upload-url'),
336+
let disableRemovedfileEvent = false; // when resetting the dropzone (removeAllFiles), disable the "removedfile" event
337+
let fileUuidDict = {}; // to record: if a comment has been saved, then the uploaded files won't be deleted from server when clicking the Remove in the dropzone
338+
const dz = await createDropzone($dropzone[0], {
339+
url: $dropzone.attr('data-upload-url'),
341340
headers: {'X-Csrf-Token': csrfToken},
342-
maxFiles: $dropzone.data('max-file'),
343-
maxFilesize: $dropzone.data('max-size'),
344-
acceptedFiles: (['*/*', ''].includes($dropzone.data('accepts'))) ? null : $dropzone.data('accepts'),
341+
maxFiles: $dropzone.attr('data-max-file'),
342+
maxFilesize: $dropzone.attr('data-max-size'),
343+
acceptedFiles: (['*/*', ''].includes($dropzone.attr('data-accepts'))) ? null : $dropzone.attr('data-accepts'),
345344
addRemoveLinks: true,
346-
dictDefaultMessage: $dropzone.data('default-message'),
347-
dictInvalidFileType: $dropzone.data('invalid-input-type'),
348-
dictFileTooBig: $dropzone.data('file-too-big'),
349-
dictRemoveFile: $dropzone.data('remove-file'),
345+
dictDefaultMessage: $dropzone.attr('data-default-message'),
346+
dictInvalidFileType: $dropzone.attr('data-invalid-input-type'),
347+
dictFileTooBig: $dropzone.attr('data-file-too-big'),
348+
dictRemoveFile: $dropzone.attr('data-remove-file'),
350349
timeout: 0,
351350
thumbnailMethod: 'contain',
352351
thumbnailWidth: 480,
@@ -359,9 +358,10 @@ async function onEditContent(event) {
359358
$dropzone.find('.files').append(input);
360359
});
361360
this.on('removedfile', (file) => {
361+
if (disableRemovedfileEvent) return;
362362
$(`#${file.uuid}`).remove();
363-
if ($dropzone.data('remove-url') && !fileUuidDict[file.uuid].submitted) {
364-
$.post($dropzone.data('remove-url'), {
363+
if ($dropzone.attr('data-remove-url') && !fileUuidDict[file.uuid].submitted) {
364+
$.post($dropzone.attr('data-remove-url'), {
365365
file: file.uuid,
366366
_csrf: csrfToken,
367367
});
@@ -373,20 +373,25 @@ async function onEditContent(event) {
373373
});
374374
});
375375
this.on('reload', () => {
376-
$.getJSON($editContentZone.data('attachment-url'), (data) => {
376+
$.getJSON($editContentZone.attr('data-attachment-url'), (data) => {
377+
// do not trigger the "removedfile" event, otherwise the attachments would be deleted from server
378+
disableRemovedfileEvent = true;
377379
dz.removeAllFiles(true);
378380
$dropzone.find('.files').empty();
379-
$.each(data, function () {
380-
const imgSrc = `${$dropzone.data('link-url')}/${this.uuid}`;
381-
dz.emit('addedfile', this);
382-
dz.emit('thumbnail', this, imgSrc);
383-
dz.emit('complete', this);
384-
dz.files.push(this);
385-
fileUuidDict[this.uuid] = {submitted: true};
381+
fileUuidDict = {};
382+
disableRemovedfileEvent = false;
383+
384+
for (const attachment of data) {
385+
const imgSrc = `${$dropzone.attr('data-link-url')}/${attachment.uuid}`;
386+
dz.emit('addedfile', attachment);
387+
dz.emit('thumbnail', attachment, imgSrc);
388+
dz.emit('complete', attachment);
389+
dz.files.push(attachment);
390+
fileUuidDict[attachment.uuid] = {submitted: true};
386391
$dropzone.find(`img[src='${imgSrc}']`).css('max-width', '100%');
387-
const input = $(`<input id="${this.uuid}" name="files" type="hidden">`).val(this.uuid);
392+
const input = $(`<input id="${attachment.uuid}" name="files" type="hidden">`).val(attachment.uuid);
388393
$dropzone.find('.files').append(input);
389-
});
394+
}
390395
});
391396
});
392397
},

0 commit comments

Comments
 (0)
Please sign in to comment.