GoBlog/comments.go

221 lines
6.6 KiB
Go
Raw Normal View History

2021-01-23 16:24:47 +00:00
package main
import (
"database/sql"
"errors"
2022-12-06 19:02:03 +00:00
"fmt"
2021-01-23 16:24:47 +00:00
"net/http"
2021-02-14 13:15:01 +00:00
"net/url"
2021-09-01 14:38:08 +00:00
"path"
2021-01-23 16:24:47 +00:00
"strconv"
2021-02-14 13:15:01 +00:00
"strings"
2021-01-23 16:24:47 +00:00
2021-03-03 17:19:55 +00:00
"github.com/go-chi/chi/v5"
2023-02-03 22:33:48 +00:00
"go.goblog.app/app/pkgs/builderpool"
2021-01-23 16:24:47 +00:00
)
2021-09-01 14:38:08 +00:00
const commentPath = "/comment"
2021-01-23 16:24:47 +00:00
type comment struct {
ID int
Target string
Name string
Website string
Comment string
Original string
2021-01-23 16:24:47 +00:00
}
func (a *goBlog) serveComment(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
2022-12-06 18:43:06 +00:00
a.serveError(w, r, "id missing or wrong format", http.StatusBadRequest)
return
}
2022-12-06 18:43:06 +00:00
comments, err := a.db.getComments(&commentsRequestConfig{id: id})
if err != nil {
2022-12-06 18:43:06 +00:00
a.serveError(w, r, "failed to query comments from database", http.StatusInternalServerError)
return
}
2022-12-06 18:43:06 +00:00
if len(comments) < 1 {
a.serve404(w, r)
return
2021-01-23 16:24:47 +00:00
}
2022-12-06 18:43:06 +00:00
comment := comments[0]
_, bc := a.getBlog(r)
canonical := a.getFullAddress(bc.getRelativePath(path.Join(commentPath, strconv.Itoa(id))))
a.render(w, r, a.renderComment, &renderData{
2022-12-06 18:43:06 +00:00
Canonical: defaultIfEmpty(comment.Original, canonical),
Data: comment,
})
2021-01-23 16:24:47 +00:00
}
func (a *goBlog) createCommentFromRequest(w http.ResponseWriter, r *http.Request) {
target := r.FormValue("target")
comment := r.FormValue("comment")
name := r.FormValue("name")
website := r.FormValue("website")
_, bc := a.getBlog(r)
// Create comment
result, errStatus, err := a.createComment(bc, target, comment, name, website, "")
if err != nil {
a.serveError(w, r, err.Error(), errStatus)
return
}
// Redirect to comment
http.Redirect(w, r, result, http.StatusFound)
}
func (a *goBlog) createComment(bc *configBlog, target, comment, name, website, original string) (string, int, error) {
updateId := -1
// Check target
target, status, err := a.checkCommentTarget(target)
if err != nil {
return "", status, err
}
// Check and clean comment
comment = cleanHTMLText(comment)
if comment == "" {
return "", http.StatusBadRequest, errors.New("comment is empty")
}
name = defaultIfEmpty(cleanHTMLText(name), "Anonymous")
website = cleanHTMLText(website)
original = cleanHTMLText(original)
if original != "" {
// Check if comment already exists
exists, id, err := a.db.commentIdByOriginal(original)
if err != nil {
return "", http.StatusInternalServerError, errors.New("failed to check the database")
}
if exists {
updateId = id
}
}
// Insert
if updateId == -1 {
result, err := a.db.Exec(
"insert into comments (target, comment, name, website, original) values (@target, @comment, @name, @website, @original)",
sql.Named("target", target), sql.Named("comment", comment), sql.Named("name", name), sql.Named("website", website), sql.Named("original", original),
)
if err != nil {
return "", http.StatusInternalServerError, errors.New("failed to save comment to database")
}
if commentID, err := result.LastInsertId(); err != nil {
return "", http.StatusInternalServerError, errors.New("failed to save comment to database")
} else {
2022-12-06 19:02:03 +00:00
commentAddress := bc.getRelativePath(fmt.Sprintf("%s/%d", commentPath, commentID))
// Send webmention
_ = a.createWebmention(a.getFullAddress(commentAddress), a.getFullAddress(target))
// Return comment path
return commentAddress, 0, nil
}
} else {
2022-12-06 18:43:06 +00:00
if err := a.db.updateComment(updateId, comment, name, website); err != nil {
return "", http.StatusInternalServerError, errors.New("failed to update comment in database")
}
2022-12-06 19:02:03 +00:00
commentAddress := bc.getRelativePath(fmt.Sprintf("%s/%d", commentPath, updateId))
// Send webmention
_ = a.createWebmention(a.getFullAddress(commentAddress), a.getFullAddress(target))
// Return comment path
return commentAddress, 0, nil
2021-01-23 16:24:47 +00:00
}
}
func (a *goBlog) checkCommentTarget(target string) (string, int, error) {
2021-01-23 16:24:47 +00:00
if target == "" {
return "", http.StatusBadRequest, errors.New("no target specified")
} else if !strings.HasPrefix(target, a.cfg.Server.PublicAddress) {
return "", http.StatusBadRequest, errors.New("bad target")
2021-01-23 16:24:47 +00:00
}
2021-02-14 13:15:01 +00:00
targetURL, err := url.Parse(target)
if err != nil {
return "", http.StatusBadRequest, errors.New("failed to parse URL")
2021-01-23 16:24:47 +00:00
}
return targetURL.Path, 0, nil
2021-01-23 16:24:47 +00:00
}
2021-02-17 15:07:42 +00:00
type commentsRequestConfig struct {
2022-12-06 18:43:06 +00:00
id, offset, limit int
2021-02-17 15:07:42 +00:00
}
2022-03-16 07:28:03 +00:00
func buildCommentsQuery(config *commentsRequestConfig) (query string, args []any) {
2023-02-03 22:33:48 +00:00
queryBuilder := builderpool.Get()
defer builderpool.Put(queryBuilder)
2022-12-06 18:43:06 +00:00
queryBuilder.WriteString("select id, target, name, website, comment, original from comments")
if config.id != 0 {
queryBuilder.WriteString(" where id = @id")
args = append(args, sql.Named("id", config.id))
}
queryBuilder.WriteString(" order by id desc")
2021-02-17 15:07:42 +00:00
if config.limit != 0 || config.offset != 0 {
queryBuilder.WriteString(" limit @limit offset @offset")
2021-02-17 15:07:42 +00:00
args = append(args, sql.Named("limit", config.limit), sql.Named("offset", config.offset))
2021-01-23 16:24:47 +00:00
}
return queryBuilder.String(), args
2021-01-23 16:24:47 +00:00
}
func (db *database) getComments(config *commentsRequestConfig) ([]*comment, error) {
2022-12-06 18:43:06 +00:00
var comments []*comment
2021-02-17 15:07:42 +00:00
query, args := buildCommentsQuery(config)
rows, err := db.Query(query, args...)
2021-01-23 16:24:47 +00:00
if err != nil {
return nil, err
}
for rows.Next() {
c := &comment{}
err = rows.Scan(&c.ID, &c.Target, &c.Name, &c.Website, &c.Comment, &c.Original)
2021-01-23 16:24:47 +00:00
if err != nil {
return nil, err
}
comments = append(comments, c)
}
return comments, nil
}
func (db *database) countComments(config *commentsRequestConfig) (count int, err error) {
2021-02-17 15:07:42 +00:00
query, params := buildCommentsQuery(config)
query = "select count(*) from (" + query + ")"
row, err := db.QueryRow(query, params...)
2021-01-23 16:24:47 +00:00
if err != nil {
return
}
2021-02-17 15:07:42 +00:00
err = row.Scan(&count)
return
2021-01-23 16:24:47 +00:00
}
2022-12-06 18:43:06 +00:00
func (db *database) updateComment(id int, comment, name, website string) error {
_, err := db.Exec(
"update comments set comment = @comment, name = @name, website = @website where id = @id",
sql.Named("comment", comment), sql.Named("name", name), sql.Named("website", website), sql.Named("id", id),
)
return err
}
func (db *database) deleteComment(id int) error {
_, err := db.Exec("delete from comments where id = @id", sql.Named("id", id))
2021-01-23 16:24:47 +00:00
return err
}
func (db *database) commentIdByOriginal(original string) (bool, int, error) {
var id int
row, err := db.QueryRow("select id from comments where original = @original", sql.Named("original", original))
if err != nil {
return false, 0, err
}
if err := row.Scan(&id); err != nil && errors.Is(err, sql.ErrNoRows) {
return false, 0, nil
} else if err != nil {
return false, 0, err
}
return true, id, nil
}
2022-12-14 15:03:54 +00:00
func (blog *configBlog) commentsEnabled() bool {
return blog.Comments != nil && blog.Comments.Enabled
}
const commentsPostParam = "comments"
func (a *goBlog) commentsEnabledForPost(post *post) bool {
2022-12-14 15:03:54 +00:00
return post != nil && a.getBlogFromPost(post).commentsEnabled() && post.firstParameter(commentsPostParam) != "false"
}