Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

feature: add attachments to comments (#734)

Guilherme Oenning851cef85f0e2
diff --git a/app/actions/post.go b/app/actions/post.go
index 8a89538b3..cf45994ec 100644
--- a/app/actions/post.go
+++ b/app/actions/post.go
@@ -146,6 +146,16 @@ func (input *AddNewComment) Validate(user *models.User, services *app.Services)
result.AddFieldFailure("content", "Comment is required.")
}
+ messages, err := validate.MultiImageUpload(nil, input.Model.Attachments, validate.MultiImageUploadOpts{
+ MaxUploads: 2,
+ MaxKilobytes: 5120,
+ ExactRatio: false,
+ })
+ if err != nil {
+ return validate.Error(err)
+ }
+ result.AddFieldFailure("attachments", messages...)
+
return result
}
@@ -235,7 +245,9 @@ func (input *DeletePost) Validate(user *models.User, services *app.Services) *va
// EditComment represents the action to update an existing comment
type EditComment struct {
- Model *models.EditComment
+ Model *models.EditComment
+ Post *models.Post
+ Comment *models.Comment
}
// Initialize the model
@@ -246,11 +258,18 @@ func (input *EditComment) Initialize() interface{} {
// IsAuthorized returns true if current user is authorized to perform this action
func (input *EditComment) IsAuthorized(user *models.User, services *app.Services) bool {
+ post, err := services.Posts.GetByNumber(input.Model.PostNumber)
+ if err != nil {
+ return false
+ }
+
comment, err := services.Posts.GetCommentByID(input.Model.ID)
if err != nil {
return false
}
+ input.Post = post
+ input.Comment = comment
return user.ID == comment.User.ID || user.IsCollaborator()
}
@@ -262,6 +281,21 @@ func (input *EditComment) Validate(user *models.User, services *app.Services) *v
result.AddFieldFailure("content", "Comment is required.")
}
+ attachments, err := services.Posts.GetAttachments(input.Post, input.Comment)
+ if err != nil {
+ return validate.Error(err)
+ }
+
+ messages, err := validate.MultiImageUpload(attachments, input.Model.Attachments, validate.MultiImageUploadOpts{
+ MaxUploads: 2,
+ MaxKilobytes: 5120,
+ ExactRatio: false,
+ })
+ if err != nil {
+ return validate.Error(err)
+ }
+ result.AddFieldFailure("attachments", messages...)
+
return result
}
diff --git a/app/handlers/apiv1/post.go b/app/handlers/apiv1/post.go
index 923a419e9..c9e2f2d90 100644
--- a/app/handlers/apiv1/post.go
+++ b/app/handlers/apiv1/post.go
@@ -206,6 +206,11 @@ func PostComment() web.HandlerFunc {
return c.HandleValidation(result)
}
+ err := webutil.ProcessMultiImageUpload(c, input.Model.Attachments, "attachments")
+ if err != nil {
+ return c.Failure(err)
+ }
+
post, err := c.Services().Posts.GetByNumber(input.Model.Number)
if err != nil {
return c.Failure(err)
@@ -216,6 +221,16 @@ func PostComment() web.HandlerFunc {
return c.Failure(err)
}
+ comment, err := c.Services().Posts.GetCommentByID(id)
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ err = c.Services().Posts.SetAttachments(post, comment, input.Model.Attachments)
+ if err != nil {
+ return c.Failure(err)
+ }
+
c.Enqueue(tasks.NotifyAboutNewComment(post, input.Model))
return c.Ok(web.Map{
@@ -232,7 +247,17 @@ func UpdateComment() web.HandlerFunc {
return c.HandleValidation(result)
}
- err := c.Services().Posts.UpdateComment(input.Model.ID, input.Model.Content)
+ err := webutil.ProcessMultiImageUpload(c, input.Model.Attachments, "attachments")
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ err = c.Services().Posts.UpdateComment(input.Model.ID, input.Model.Content)
+ if err != nil {
+ return c.Failure(err)
+ }
+
+ err = c.Services().Posts.SetAttachments(input.Post, input.Comment, input.Model.Attachments)
if err != nil {
return c.Failure(err)
}
diff --git a/app/models/feedback.go b/app/models/feedback.go
index 7c840c844..67092cc0e 100644
--- a/app/models/feedback.go
+++ b/app/models/feedback.go
@@ -64,15 +64,17 @@ type DeletePost struct {
// NewComment represents a new comment
type NewComment struct {
- Number int `route:"number"`
- Content string `json:"content"`
+ Number int `route:"number"`
+ Content string `json:"content"`
+ Attachments []*ImageUpload `json:"attachments"`
}
// EditComment represents a request to edit existing comment
type EditComment struct {
- PostNumber int `route:"number"`
- ID int `route:"id"`
- Content string `json:"content"`
+ PostNumber int `route:"number"`
+ ID int `route:"id"`
+ Content string `json:"content"`
+ Attachments []*ImageUpload `json:"attachments"`
}
// DeleteComment represents a request to delete an existing comment
@@ -107,12 +109,13 @@ type OriginalPost struct {
//Comment represents an user comment on an post
type Comment struct {
- ID int `json:"id"`
- Content string `json:"content"`
- CreatedAt time.Time `json:"createdAt"`
- User *User `json:"user"`
- EditedAt *time.Time `json:"editedAt,omitempty"`
- EditedBy *User `json:"editedBy,omitempty"`
+ ID int `json:"id"`
+ Content string `json:"content"`
+ CreatedAt time.Time `json:"createdAt"`
+ User *User `json:"user"`
+ Attachments []string `json:"attachments,omitempty"`
+ EditedAt *time.Time `json:"editedAt,omitempty"`
+ EditedBy *User `json:"editedBy,omitempty"`
}
//Tag represents a simple tag
diff --git a/app/storage/postgres/post.go b/app/storage/postgres/post.go
index 4d65ea47c..e64c1cdf5 100644
--- a/app/storage/postgres/post.go
+++ b/app/storage/postgres/post.go
@@ -74,20 +74,22 @@ func (i *dbPost) toModel(ctx storage.Context) *models.Post {
}
type dbComment struct {
- ID int `db:"id"`
- Content string `db:"content"`
- CreatedAt time.Time `db:"created_at"`
- User *dbUser `db:"user"`
- EditedAt dbx.NullTime `db:"edited_at"`
- EditedBy *dbUser `db:"edited_by"`
+ ID int `db:"id"`
+ Content string `db:"content"`
+ CreatedAt time.Time `db:"created_at"`
+ User *dbUser `db:"user"`
+ Attachments []string `db:"attachment_bkeys"`
+ EditedAt dbx.NullTime `db:"edited_at"`
+ EditedBy *dbUser `db:"edited_by"`
}
func (c *dbComment) toModel(ctx storage.Context) *models.Comment {
comment := &models.Comment{
- ID: c.ID,
- Content: c.Content,
- CreatedAt: c.CreatedAt,
- User: c.User.toModel(ctx),
+ ID: c.ID,
+ Content: c.Content,
+ CreatedAt: c.CreatedAt,
+ User: c.User.toModel(ctx),
+ Attachments: c.Attachments,
}
if c.EditedAt.Valid {
comment.EditedBy = c.EditedBy.toModel(ctx)
@@ -369,7 +371,21 @@ func (s *PostStorage) Search(query, view, limit string, tags []string) ([]*model
func (s *PostStorage) GetCommentsByPost(post *models.Post) ([]*models.Comment, error) {
comments := []*dbComment{}
err := s.trx.Select(&comments,
- `SELECT c.id,
+ `WITH agg_attachments AS (
+ SELECT
+ c.id as comment_id,
+ ARRAY_REMOVE(ARRAY_AGG(at.attachment_bkey), NULL) as attachment_bkeys
+ FROM attachments at
+ INNER JOIN comments c
+ ON at.tenant_id = c.tenant_id
+ AND at.post_id = c.post_id
+ AND at.comment_id = c.id
+ WHERE at.post_id = $1
+ AND at.tenant_id = $2
+ AND at.comment_id IS NOT NULL
+ GROUP BY c.id
+ )
+ SELECT c.id,
c.content,
c.created_at,
c.edited_at,
@@ -386,7 +402,8 @@ func (s *PostStorage) GetCommentsByPost(post *models.Post) ([]*models.Comment, e
e.role AS edited_by_role,
e.status AS edited_by_status,
e.avatar_type AS edited_by_avatar_type,
- e.avatar_bkey AS edited_by_avatar_bkey
+ e.avatar_bkey AS edited_by_avatar_bkey,
+ at.attachment_bkeys
FROM comments c
INNER JOIN posts p
ON p.id = c.post_id
@@ -397,6 +414,8 @@ func (s *PostStorage) GetCommentsByPost(post *models.Post) ([]*models.Comment, e
LEFT JOIN users e
ON e.id = c.edited_by_id
AND e.tenant_id = c.tenant_id
+ LEFT JOIN agg_attachments at
+ ON at.comment_id = c.id
WHERE p.id = $1
AND p.tenant_id = $2
AND c.deleted_at IS NULL
diff --git a/public/models/post.ts b/public/models/post.ts
index 3e5082108..7be85d56b 100644
--- a/public/models/post.ts
+++ b/public/models/post.ts
@@ -69,6 +69,7 @@ export interface Comment {
content: string;
createdAt: string;
user: User;
+ attachments?: string[];
editedAt?: string;
editedBy?: User;
}
diff --git a/public/pages/ShowPost/components/CommentInput.tsx b/public/pages/ShowPost/components/CommentInput.tsx
index 15ecd79b2..96185b67b 100644
--- a/public/pages/ShowPost/components/CommentInput.tsx
+++ b/public/pages/ShowPost/components/CommentInput.tsx
@@ -1,7 +1,7 @@
import React from "react";
-import { Post } from "@fider/models";
-import { Avatar, UserName, Button, TextArea, Form } from "@fider/components/common";
+import { Post, ImageUpload } from "@fider/models";
+import { Avatar, UserName, Button, TextArea, Form, MultiImageUploader } from "@fider/components/common";
import { SignInModal } from "@fider/components";
import { cache, actions, Failure, Fider } from "@fider/services";
@@ -14,6 +14,7 @@ interface CommentInputState {
content: string;
error?: Failure;
showSignIn: boolean;
+ attachments: ImageUpload[];
}
const CACHE_TITLE_KEY = "CommentInput-Comment-";
@@ -26,7 +27,8 @@ export class CommentInput extends React.Component<CommentInputProps, CommentInpu
this.state = {
content: (Fider.session.isAuthenticated && cache.session.get(this.getCacheKey())) || "",
- showSignIn: false
+ showSignIn: false,
+ attachments: []
};
}
@@ -39,12 +41,16 @@ export class CommentInput extends React.Component<CommentInputProps, CommentInpu
this.setState({ content });
};
+ private setAttachments = (attachments: ImageUpload[]) => {
+ this.setState({ attachments });
+ };
+
public submit = async () => {
this.setState({
error: undefined
});
- const result = await actions.createComment(this.props.post.number, this.state.content);
+ const result = await actions.createComment(this.props.post.number, this.state.content, this.state.attachments);
if (result.ok) {
cache.session.remove(this.getCacheKey());
location.reload();
@@ -83,6 +89,14 @@ export class CommentInput extends React.Component<CommentInputProps, CommentInpu
onFocus={this.handleOnFocus}
inputRef={this.setInputRef}
/>
+ {this.state.content && (
+ <MultiImageUploader
+ field="attachments"
+ maxUploads={2}
+ previewMaxWidth={100}
+ onChange={this.setAttachments}
+ />
+ )}
{this.state.content && (
<Button color="positive" onClick={this.submit}>
Submit
diff --git a/public/pages/ShowPost/components/ShowComment.tsx b/public/pages/ShowPost/components/ShowComment.tsx
index 8ee202d15..be31b68f3 100644
--- a/public/pages/ShowPost/components/ShowComment.tsx
+++ b/public/pages/ShowPost/components/ShowComment.tsx
@@ -1,5 +1,5 @@
import React from "react";
-import { Comment, Post } from "@fider/models";
+import { Comment, Post, ImageUpload } from "@fider/models";
import {
Avatar,
UserName,
@@ -10,7 +10,9 @@ import {
MultiLineText,
DropDown,
DropDownItem,
- Modal
+ Modal,
+ ImageViewer,
+ MultiImageUploader
} from "@fider/components";
import { formatDate, Failure, actions, Fider } from "@fider/services";
import { FaEllipsisH } from "react-icons/fa";
@@ -24,6 +26,7 @@ interface ShowCommentState {
comment: Comment;
isEditing: boolean;
newContent: string;
+ attachments: ImageUpload[];
error?: Failure;
showDeleteConfirmation: boolean;
}
@@ -35,7 +38,8 @@ export class ShowComment extends React.Component<ShowCommentProps, ShowCommentSt
comment: props.comment,
isEditing: false,
newContent: "",
- showDeleteConfirmation: false
+ showDeleteConfirmation: false,
+ attachments: []
};
}
@@ -55,15 +59,14 @@ export class ShowComment extends React.Component<ShowCommentProps, ShowCommentSt
};
private saveEdit = async () => {
- const response = await actions.updateComment(this.props.post.number, this.state.comment.id, this.state.newContent);
+ const response = await actions.updateComment(
+ this.props.post.number,
+ this.state.comment.id,
+ this.state.newContent,
+ this.state.attachments
+ );
if (response.ok) {
- this.state.comment.content = this.state.newContent;
- this.state.comment.editedAt = new Date().toISOString();
- this.state.comment.editedBy = Fider.session.user;
- this.setState({
- comment: this.state.comment
- });
- this.cancelEdit();
+ location.reload();
} else {
this.setState({ error: response.error });
}
@@ -73,6 +76,10 @@ export class ShowComment extends React.Component<ShowCommentProps, ShowCommentSt
this.setState({ newContent });
};
+ private setAttachments = (attachments: ImageUpload[]) => {
+ this.setState({ attachments });
+ };
+
private renderEllipsis = () => {
return <FaEllipsisH />;
};
@@ -162,6 +169,13 @@ export class ShowComment extends React.Component<ShowCommentProps, ShowCommentSt
placeholder={c.content}
onChange={this.setNewContent}
/>
+ <MultiImageUploader
+ field="attachments"
+ bkeys={c.attachments}
+ maxUploads={2}
+ previewMaxWidth={100}
+ onChange={this.setAttachments}
+ />
<Button size="tiny" onClick={this.saveEdit} color="positive">
Save
</Button>
@@ -170,7 +184,10 @@ export class ShowComment extends React.Component<ShowCommentProps, ShowCommentSt
</Button>
</Form>
) : (
- <MultiLineText text={c.content} style="simple" />
+ <>
+ <MultiLineText text={c.content} style="simple" />
+ {c.attachments && c.attachments.map(x => <ImageViewer key={x} bkey={x} />)}
+ </>
)}
</div>
</div>
diff --git a/public/services/actions/post.ts b/public/services/actions/post.ts
index 3fa986a08..3352e7138 100644
--- a/public/services/actions/post.ts
+++ b/public/services/actions/post.ts
@@ -51,13 +51,24 @@ export const listVotes = async (postNumber: number): Promise<Result<Vote[]>> =>
return http.get<Vote[]>(`/api/v1/posts/${postNumber}/votes`);
};
-export const createComment = async (postNumber: number, content: string): Promise<Result> => {
- return http.post(`/api/v1/posts/${postNumber}/comments`, { content }).then(http.event("comment", "create"));
+export const createComment = async (
+ postNumber: number,
+ content: string,
+ attachments: ImageUpload[]
+): Promise<Result> => {
+ return http
+ .post(`/api/v1/posts/${postNumber}/comments`, { content, attachments })
+ .then(http.event("comment", "create"));
};
-export const updateComment = async (postNumber: number, commentID: number, content: string): Promise<Result> => {
+export const updateComment = async (
+ postNumber: number,
+ commentID: number,
+ content: string,
+ attachments: ImageUpload[]
+): Promise<Result> => {
return http
- .put(`/api/v1/posts/${postNumber}/comments/${commentID}`, { content })
+ .put(`/api/v1/posts/${postNumber}/comments/${commentID}`, { content, attachments })
.then(http.event("comment", "update"));
};