Compare commits

...

56 Commits

Author SHA1 Message Date
acae07b8f3 Merge branch 'devel' 2025-01-17 18:13:12 +01:00
52b5dbf2c7 Change the way names are given to uploaded pdfs to include the original document name 2025-01-17 18:13:04 +01:00
1b100483de Merge branch 'devel' 2025-01-17 17:52:45 +01:00
7b9438233e Comment out not ready image cleanup function 2025-01-17 17:52:35 +01:00
ff36d65cc3 Add ability to clean up unused images 2025-01-17 05:04:03 +01:00
3d3cda319d Initial version of .docx upload support 2025-01-17 05:02:31 +01:00
0e825a55e5 Fix bug not letting the first user have a session after user creation 2025-01-17 05:01:09 +01:00
e03fd78ea9 Merge branch 'devel' 2025-01-12 14:36:01 +01:00
370ef205a9 Merge branch 'devel' 2024-12-27 21:36:02 +01:00
d328ddb749 Merge branch 'devel' 2024-10-30 03:25:18 +01:00
5dc5590da9 Merge branch 'devel' 2024-10-30 02:24:50 +01:00
364112a0a4 Merge branch 'devel' 2024-10-30 02:14:16 +01:00
a38523e933 Merge branch 'devel' 2024-10-30 02:13:03 +01:00
200672dae2 Merge branch 'devel' 2024-10-28 18:28:31 +01:00
3d3aad88c8 Merge branch 'devel' 2024-10-28 18:27:33 +01:00
e4e43d1a83 Merge branch 'devel' 2024-10-28 18:02:56 +01:00
737a9ec314 Merge branch 'devel' 2024-10-27 15:29:50 +01:00
1ebe0380ee Merge branch 'devel' 2024-10-27 15:28:22 +01:00
d62d71b5d1 Merge branch 'devel' 2024-10-27 15:14:11 +01:00
b36e0ea503 Merge branch 'devel' 2024-10-04 16:06:57 +02:00
bc4d8fa37e Merge branch 'devel' 2024-09-28 13:59:34 +02:00
d2b21e7405 Merge branch 'devel' 2024-09-28 12:36:46 +02:00
e3c192359f Merge branch 'devel' 2024-09-11 18:15:31 +02:00
46532e4c85 Merge branch 'devel' 2024-09-11 18:15:07 +02:00
c722135a56 Merge branch 'devel' 2024-09-11 17:18:42 +02:00
887fa863bc Merge branch 'devel' 2024-09-10 19:43:22 +02:00
74d71cfb6a Merge branch 'devel' 2024-09-09 22:03:43 +02:00
ca7e7cddd3 Merge branch 'devel' 2024-09-08 16:22:59 +02:00
94431a2aa9 Merge branch 'devel' 2024-09-08 16:21:38 +02:00
5b1f20c5bc Merge branch 'devel' 2024-09-08 13:36:22 +02:00
d0c566f8df Merge branch 'devel' 2024-09-01 21:14:05 +02:00
5e586aa49a Merge branch 'devel' 2024-09-01 18:51:33 +02:00
66b2743d3d Merge branch 'devel' 2024-09-01 18:48:26 +02:00
3723b2b5e6 Merge branch 'devel' 2024-09-01 18:18:18 +02:00
ce788bfd50 Merge branch 'devel' 2024-09-01 12:54:12 +02:00
230a6278cc Merge branch 'devel' 2024-09-01 12:49:30 +02:00
42d6e0c198 Merge branch 'devel' 2024-08-31 12:17:41 +02:00
e1af2979af Merge branch 'devel' 2024-08-31 11:27:15 +02:00
f6dedc6f10 Merge branch 'devel' 2024-08-31 01:43:53 +02:00
cdf0a49550 Merge branch 'devel' 2024-08-31 01:38:28 +02:00
c3c0650210 Merge branch 'devel' 2024-08-31 01:00:55 +02:00
d077f700d8 Merge branch 'devel' 2024-08-31 00:36:48 +02:00
ec752b1c66 Merge branch 'devel' 2024-08-30 23:43:12 +02:00
46aef4f12f Merge branch 'devel' 2024-08-25 10:51:35 +02:00
1b29e328cf Merge branch 'devel' 2024-08-25 06:38:55 +02:00
e50cb819f3 Merge branch 'devel' 2024-08-23 21:45:30 +02:00
c32e38ca10 Merge branch 'devel' 2024-08-23 20:57:11 +02:00
d7c8c7a43a Merge branch 'devel' 2024-08-18 17:31:00 +02:00
1cd3edc90c Merge branch 'devel' 2024-08-18 12:06:29 +02:00
0e768c9f61 Merge branch 'devel' 2024-08-08 21:27:07 +02:00
1fcd775cc5 Merge branch 'devel' 2024-08-08 21:14:24 +02:00
203a1ed147 Implemented EasyMDE 2024-08-08 21:13:25 +02:00
ef1914ee5c Implemented article preview 2024-08-08 21:13:25 +02:00
084b101e31 Register f.ArticlePreviewHtmlData in init() 2024-08-08 21:13:25 +02:00
b2db128aa9 Shorten lines by referencing frontend as f and backend as b 2024-08-08 21:13:25 +02:00
081e880fb6 Change structure of code tor frontend and backend one 2024-08-08 21:13:25 +02:00
14 changed files with 330 additions and 43 deletions

View File

@ -7,6 +7,8 @@ import (
"log"
"os"
"time"
"github.com/google/uuid"
)
type Article struct {
@ -14,6 +16,7 @@ type Article struct {
Title string
BannerLink string
Summary string
UUID uuid.UUID
ID int64
CreatorID int64
IssueID int64
@ -31,8 +34,8 @@ func (db *DB) AddArticle(a *Article) (int64, error) {
selectQuery := "SELECT id FROM issues WHERE published = false"
insertQuery := `
INSERT INTO articles
(title, banner_link, summary, published, rejected, creator_id, issue_id, edited_id, clicks, is_in_issue, auto_generated)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
(title, banner_link, summary, published, rejected, creator_id, issue_id, edited_id, clicks, is_in_issue, auto_generated, uuid)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`
for i := 0; i < TxMaxRetries; i++ {
@ -49,7 +52,7 @@ func (db *DB) AddArticle(a *Article) (int64, error) {
return 0, fmt.Errorf("error getting issue ID when adding article to DB: %v", err)
}
result, err := tx.Exec(insertQuery, a.Title, a.BannerLink, a.Summary, a.Published, a.Rejected, a.CreatorID, id, a.EditedID, 0, a.IsInIssue, a.AutoGenerated)
result, err := tx.Exec(insertQuery, a.Title, a.BannerLink, a.Summary, a.Published, a.Rejected, a.CreatorID, id, a.EditedID, 0, a.IsInIssue, a.AutoGenerated, a.UUID.String())
if err != nil {
if rollbackErr := tx.Rollback(); rollbackErr != nil {
log.Fatalf("transaction error: %v, rollback error: %v", err, rollbackErr)
@ -83,7 +86,7 @@ func (db *DB) AddArticle(a *Article) (int64, error) {
func (db *DB) GetArticle(id int64) (*Article, error) {
query := `
SELECT title, created, banner_link, summary, published, creator_id, issue_id, edited_id, clicks, is_in_issue, auto_generated
SELECT title, created, banner_link, summary, published, creator_id, issue_id, edited_id, clicks, is_in_issue, auto_generated, uuid
FROM articles
WHERE id = ?
`
@ -91,9 +94,10 @@ func (db *DB) GetArticle(id int64) (*Article, error) {
article := new(Article)
var created []byte
var uuidString string
var err error
if err := row.Scan(&article.Title, &created, &article.BannerLink, &article.Summary, &article.Published, &article.CreatorID, &article.IssueID, &article.EditedID, &article.Clicks, &article.IsInIssue, &article.AutoGenerated); err != nil {
if err := row.Scan(&article.Title, &created, &article.BannerLink, &article.Summary, &article.Published, &article.CreatorID, &article.IssueID, &article.EditedID, &article.Clicks, &article.IsInIssue, &article.AutoGenerated, &uuidString); err != nil {
return nil, fmt.Errorf("error scanning article row: %v", err)
}
@ -103,12 +107,17 @@ func (db *DB) GetArticle(id int64) (*Article, error) {
return nil, fmt.Errorf("error parsing created: %v", err)
}
article.UUID, err = uuid.Parse(uuidString)
if err != nil {
return nil, fmt.Errorf("error parsing uuid: %v", err)
}
return article, nil
}
func (db *DB) GetCertainArticles(attribute string, value bool) ([]*Article, error) {
query := fmt.Sprintf(`
SELECT id, title, created, banner_link, summary, creator_id, issue_id, clicks, published, rejected, is_in_issue, auto_generated
SELECT id, title, created, banner_link, summary, creator_id, issue_id, clicks, published, rejected, is_in_issue, auto_generated, uuid
FROM articles
WHERE %s = ?
`, attribute)
@ -121,8 +130,9 @@ func (db *DB) GetCertainArticles(attribute string, value bool) ([]*Article, erro
for rows.Next() {
article := new(Article)
var created []byte
var uuidString string
if err = rows.Scan(&article.ID, &article.Title, &created, &article.BannerLink, &article.Summary, &article.CreatorID, &article.IssueID, &article.Clicks, &article.Published, &article.Rejected, &article.IsInIssue, &article.AutoGenerated); err != nil {
if err = rows.Scan(&article.ID, &article.Title, &created, &article.BannerLink, &article.Summary, &article.CreatorID, &article.IssueID, &article.Clicks, &article.Published, &article.Rejected, &article.IsInIssue, &article.AutoGenerated, &uuidString); err != nil {
return nil, fmt.Errorf("error scanning article row: %v", err)
}
@ -131,6 +141,11 @@ func (db *DB) GetCertainArticles(attribute string, value bool) ([]*Article, erro
return nil, fmt.Errorf("error parsing created: %v", err)
}
article.UUID, err = uuid.Parse(uuidString)
if err != nil {
return nil, fmt.Errorf("error parsing uuid: %v", err)
}
articleList = append(articleList, article)
}
@ -142,7 +157,7 @@ func (db *DB) GetCurrentIssueArticles() ([]*Article, error) {
txOptions := &sql.TxOptions{Isolation: sql.LevelSerializable}
issueQuery := "SELECT id FROM issues WHERE published = false"
articlesQuery := `
SELECT id, title, created, banner_link, summary, clicks, auto_generated
SELECT id, title, created, banner_link, summary, clicks, auto_generated, uuid
FROM articles
WHERE issue_id = ? AND published = true AND is_in_issue = true
`
@ -174,8 +189,9 @@ func (db *DB) GetCurrentIssueArticles() ([]*Article, error) {
for rows.Next() {
article := new(Article)
var created []byte
var uuidString string
if err = rows.Scan(&article.ID, &article.Title, &created, &article.BannerLink, &article.Summary, &article.Clicks, &article.AutoGenerated); err != nil {
if err = rows.Scan(&article.ID, &article.Title, &created, &article.BannerLink, &article.Summary, &article.Clicks, &article.AutoGenerated, &uuidString); err != nil {
if rollbackErr := tx.Rollback(); rollbackErr != nil {
log.Fatalf("transaction error: %v, rollback error: %v", err, rollbackErr)
}
@ -190,6 +206,14 @@ func (db *DB) GetCurrentIssueArticles() ([]*Article, error) {
return nil, fmt.Errorf("error parsing created: %v", err)
}
article.UUID, err = uuid.Parse(uuidString)
if err != nil {
if rollbackErr := tx.Rollback(); rollbackErr != nil {
log.Fatalf("transaction error: %v, rollback error: %v", err, rollbackErr)
}
return nil, fmt.Errorf("error parsing uuid: %v", err)
}
articleList = append(articleList, article)
}
@ -284,11 +308,11 @@ func (db *DB) DeleteArticle(id int64) error {
return nil
}
func WriteArticleToFile(c *Config, articleID int64, content []byte) error {
articleAbsName := fmt.Sprint(c.ArticleDir, "/", articleID, ".md")
func WriteArticleToFile(c *Config, articleUUID uuid.UUID, content []byte) error {
articleAbsName := fmt.Sprint(c.ArticleDir, "/", articleUUID, ".md")
if err := os.WriteFile(articleAbsName, content, 0644); err != nil {
return fmt.Errorf("error writing article %v to file: %v", articleID, err)
return fmt.Errorf("error writing article %v to file: %v", articleUUID, err)
}
return nil

View File

@ -33,7 +33,7 @@ func GenerateAtomFeed(c *Config, db *DB) (*string, error) {
entry := atom.NewEntry(articleTitle)
entry.ID = atom.NewID(fmt.Sprint("urn:entry:", article.ID))
entry.Published = atom.NewDate(article.Created)
entry.Content = atom.NewContent(atom.OutOfLine, "text/hmtl", fmt.Sprint(c.Domain, "/article/serve/", article.ID))
entry.Content = atom.NewContent(atom.OutOfLine, "text/html", fmt.Sprint(c.Domain, "/article/serve/", article.UUID))
if article.AutoGenerated {
entry.Summary = atom.NewText("text", "automatically generated")

59
cmd/backend/docx.go Normal file
View File

@ -0,0 +1,59 @@
package backend
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"github.com/google/uuid"
)
func ConvertToMarkdown(c *Config, filename string) ([]byte, error) {
var stderr bytes.Buffer
articleID := uuid.New()
articleFileName := fmt.Sprint("/tmp/", articleID, ".md")
tmpDir, err := os.MkdirTemp("/tmp", "cpolis_images")
if err != nil {
return nil, fmt.Errorf("error creating temporary directory: %v", err)
}
defer os.RemoveAll(tmpDir)
cmd := exec.Command("pandoc", "-s", "-f", "docx", "-t", "commonmark_x", "-o", articleFileName, "--extract-media", tmpDir, filename) // TODO: Is writing to a file necessary?
cmd.Stderr = &stderr
if err = cmd.Run(); err != nil {
return nil, fmt.Errorf("error converting docx to markdown: %v: %v", err, stderr.String())
}
defer os.Remove(articleFileName)
articleContent, err := os.ReadFile(articleFileName)
if err != nil {
return nil, fmt.Errorf("error reading markdown file: %v", err)
}
imageNames, err := filepath.Glob(filepath.Join(tmpDir, "/media/*"))
if err != nil {
return nil, fmt.Errorf("error getting docx images from temporary directory: %v", err)
}
for _, name := range imageNames {
image, err := os.Open(name)
if err != nil {
return nil, fmt.Errorf("error opening image file %v: %v", name, err)
}
defer image.Close()
newImageName, err := SaveImage(image, c.MaxImgHeight, c.MaxImgWidth, c.PicsDir)
if err != nil {
return nil, fmt.Errorf("error saving image %v: %v", name, err)
}
articleContent = regexp.MustCompile(name).ReplaceAll(articleContent, []byte(c.PicsDir+"/"+newImageName))
}
return articleContent, nil
}

View File

@ -1,10 +1,16 @@
package backend
import (
"bufio"
"fmt"
"image"
"io"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/chai2010/webp"
"github.com/disintegration/imaging"
@ -30,7 +36,7 @@ func SaveImage(src io.Reader, maxHeight, maxWidth int, path string) (string, err
}
filename := fmt.Sprint(uuid.New(), ".webp")
file, err := os.Create(path + filename)
file, err := os.Create(filepath.Join(path, filename))
if err != nil {
return "", fmt.Errorf("error creating new image file: %v", err)
}
@ -42,3 +48,59 @@ func SaveImage(src io.Reader, maxHeight, maxWidth int, path string) (string, err
return filename, nil
}
func CleanUpImages(c *Config) {
for {
if err := filepath.Walk(c.PicsDir, func(path string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
imageName := info.Name()
absImageName := path
if err = filepath.Walk(c.ArticleDir, func(path string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
mdFile, err := os.Open(path)
if err != nil {
return err
}
defer mdFile.Close()
scanner := bufio.NewScanner(mdFile)
imageWasFound := false
for scanner.Scan() {
if strings.Contains(scanner.Text(), imageName) {
imageWasFound = true
}
}
if !imageWasFound {
if err = os.Remove(absImageName); err != nil {
return err
}
}
return scanner.Err()
}
return nil
}); err != nil {
return err
}
}
return nil
}); err != nil {
log.Println(err)
}
time.Sleep(time.Hour)
}
}

View File

@ -10,6 +10,7 @@ import (
"strings"
"time"
"github.com/google/uuid"
b "streifling.com/jason/cpolis/cmd/backend"
)
@ -109,6 +110,7 @@ func SubmitArticle(c *b.Config, db *b.DB, s map[string]*Session) http.HandlerFun
IsInIssue: r.PostFormValue("issue") == "on",
AutoGenerated: false,
EditedID: 0,
UUID: uuid.New(),
}
if len(article.Title) == 0 {
@ -164,7 +166,7 @@ func SubmitArticle(c *b.Config, db *b.DB, s map[string]*Session) http.HandlerFun
http.Error(w, "Bitte den Artikel eingeben.", http.StatusBadRequest)
return
}
if err := b.WriteArticleToFile(c, article.ID, content); err != nil {
if err := b.WriteArticleToFile(c, article.UUID, content); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@ -221,14 +223,26 @@ func ResubmitArticle(c *b.Config, db *b.DB, s map[string]*Session) http.HandlerF
return
}
article := &b.Article{
Title: r.PostFormValue("article-title"),
BannerLink: r.PostFormValue("article-banner-url"),
Summary: r.PostFormValue("article-summary"),
CreatorID: session.User.ID,
IsInIssue: r.PostFormValue("issue") == "on",
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
article, err := db.GetArticle(id)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
article.Title = r.PostFormValue("article-title")
article.BannerLink = r.PostFormValue("article-banner-url")
article.Summary = r.PostFormValue("article-summary")
article.CreatorID = session.User.ID
article.IsInIssue = r.PostFormValue("issue") == "on"
if len(article.Title) == 0 {
http.Error(w, "Bitte den Titel eingeben.", http.StatusBadRequest)
return
@ -270,20 +284,13 @@ func ResubmitArticle(c *b.Config, db *b.DB, s map[string]*Session) http.HandlerF
return
}
article.ID, err = strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
content := r.PostFormValue("article-content")
if len(content) == 0 {
http.Error(w, "Bitte den Artikel eingeben.", http.StatusBadRequest)
return
}
contentLink := fmt.Sprint(c.ArticleDir, "/", article.ID, ".md")
if err = os.WriteFile(contentLink, []byte(content), 0644); err != nil {
if err = b.WriteArticleToFile(c, article.UUID, []byte(content)); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@ -448,7 +455,7 @@ func ReviewRejectedArticle(c *b.Config, db *b.DB, s map[string]*Session) http.Ha
data.Image = data.Article.BannerLink
articleAbsName := fmt.Sprint(c.ArticleDir, "/", data.Article.ID, ".md")
articleAbsName := fmt.Sprint(c.ArticleDir, "/", data.Article.UUID, ".md")
content, err := os.ReadFile(articleAbsName)
if err != nil {
log.Println(err)
@ -579,7 +586,7 @@ func PublishArticle(c *b.Config, db *b.DB, s map[string]*Session) http.HandlerFu
return
}
if err = os.Remove(fmt.Sprint(c.ArticleDir, "/", oldArticle.ID, ".md")); err != nil {
if err = os.Remove(fmt.Sprint(c.ArticleDir, "/", oldArticle.UUID, ".md")); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@ -757,7 +764,7 @@ func ReviewArticle(c *b.Config, db *b.DB, s map[string]*Session, action, title,
return
}
articleAbsName := fmt.Sprint(c.ArticleDir, "/", article.ID, ".md")
articleAbsName := fmt.Sprint(c.ArticleDir, "/", article.UUID, ".md")
content, err := os.ReadFile(articleAbsName)
if err != nil {
log.Println(err)
@ -819,13 +826,20 @@ func DeleteArticle(c *b.Config, db *b.DB, s map[string]*Session) http.HandlerFun
return
}
article, err := db.GetArticle(id)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err = db.DeleteArticle(id); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err = os.Remove(fmt.Sprint(c.ArticleDir, "/", id, ".md")); err != nil {
if err = os.Remove(fmt.Sprint(c.ArticleDir, "/", article.UUID, ".md")); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
@ -896,8 +910,8 @@ func AllowEditArticle(c *b.Config, db *b.DB, s map[string]*Session) http.Handler
return
}
src := fmt.Sprint(c.ArticleDir, "/", oldArticle.ID, ".md")
dst := fmt.Sprint(c.ArticleDir, "/", newArticle.ID, ".md")
src := fmt.Sprint(c.ArticleDir, "/", oldArticle.UUID, ".md")
dst := fmt.Sprint(c.ArticleDir, "/", newArticle.UUID, ".md")
if err = b.CopyFile(src, dst); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
@ -973,7 +987,7 @@ func EditArticle(c *b.Config, db *b.DB, s map[string]*Session) http.HandlerFunc
data.Image = data.Article.BannerLink
content, err := os.ReadFile(fmt.Sprint(c.ArticleDir, "/", data.Article.ID, ".md"))
content, err := os.ReadFile(fmt.Sprint(c.ArticleDir, "/", data.Article.UUID, ".md"))
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)

107
cmd/frontend/docx.go Normal file
View File

@ -0,0 +1,107 @@
package frontend
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"time"
"github.com/gabriel-vasile/mimetype"
"github.com/google/uuid"
b "streifling.com/jason/cpolis/cmd/backend"
)
func UploadDocx(c *b.Config, db *b.DB, s map[string]*Session) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
session, err := ManageSession(w, r, c, s)
if err != nil {
http.Error(w, "Die Session ist abgelaufen. Bitte erneut anmelden.", http.StatusUnauthorized)
return
}
file, fileHeader, err := r.FormFile("docx-upload")
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer file.Close()
var buf bytes.Buffer
if _, err = io.Copy(&buf, file); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
mime := mimetype.Detect(buf.Bytes())
if !mime.Is("application/vnd.openxmlformats-officedocument.wordprocessingml.document") {
http.Error(w, "Die Datei ist kein DOCX Worddokument.", http.StatusBadRequest)
return
}
docxFilename := fmt.Sprint(uuid.New(), ".docx")
absDocxFilepath, err := filepath.Abs("/tmp/" + docxFilename)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err = os.WriteFile(absDocxFilepath, buf.Bytes(), 0644); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer os.Remove(absDocxFilepath)
mdString, err := b.ConvertToMarkdown(c, absDocxFilepath)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
uuidName := uuid.New()
mdFilename := fmt.Sprint(uuidName, ".md")
absMdFilepath, err := filepath.Abs(c.ArticleDir + "/" + mdFilename)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err = os.WriteFile(absMdFilepath, mdString, 0644); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
article := &b.Article{
Created: time.Now(),
UUID: uuidName,
CreatorID: session.User.ID,
Rejected: true,
}
article.Title = fmt.Sprint(fileHeader.Filename, "-", article.UUID)
id, err := db.AddArticle(article)
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err = db.WriteArticleAuthors(id, []int64{session.User.ID}); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
}

View File

@ -8,6 +8,7 @@ import (
"os"
"time"
"github.com/google/uuid"
b "streifling.com/jason/cpolis/cmd/backend"
)
@ -26,6 +27,7 @@ func PublishLatestIssue(c *b.Config, db *b.DB, s map[string]*Session) http.Handl
Rejected: false,
Created: time.Now(),
AutoGenerated: true,
UUID: uuid.New(),
}
if len(article.Title) == 0 {
@ -55,7 +57,7 @@ func PublishLatestIssue(c *b.Config, db *b.DB, s map[string]*Session) http.Handl
return
}
articleAbsName := fmt.Sprint(c.ArticleDir, "/", article.ID, ".md")
articleAbsName := fmt.Sprint(c.ArticleDir, "/", article.UUID, ".md")
if err = os.WriteFile(articleAbsName, content, 0644); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)

View File

@ -5,6 +5,7 @@ import (
"log"
"net/http"
"path/filepath"
"strings"
"github.com/google/uuid"
b "streifling.com/jason/cpolis/cmd/backend"
@ -17,7 +18,7 @@ func UploadPDF(c *b.Config, s map[string]*Session) http.HandlerFunc {
return
}
file, _, err := r.FormFile("pdf-upload")
file, header, err := r.FormFile("pdf-upload")
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
@ -43,7 +44,9 @@ func UploadPDF(c *b.Config, s map[string]*Session) http.HandlerFunc {
return
}
filename := fmt.Sprint(uuid.New(), ".pdf")
oldFilename := header.Filename
oldFilename = strings.Join(strings.Split(oldFilename, ".")[:len(oldFilename)-1], ".")
filename := fmt.Sprint(oldFilename, ".", uuid.New(), ".pdf")
absFilepath, err := filepath.Abs(c.PDFDir + "/" + filename)
if err != nil {
log.Println(err)

View File

@ -252,7 +252,7 @@ func UpdateSelf(c *b.Config, db *b.DB, s map[string]*Session) http.HandlerFunc {
}
}
func AddFirstUser(c *b.Config, db *b.DB, s map[string]*Session) http.HandlerFunc {
func AddFirstUser(c *b.Config, db *b.DB, s map[string]*Session, sessionExpiryChan chan string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var err error
user := &b.User{
@ -305,8 +305,12 @@ func AddFirstUser(c *b.Config, db *b.DB, s map[string]*Session) http.HandlerFunc
return
}
session := newSession(w, c, sessionExpiryChan, user)
s[session.cookie.Value] = session
http.SetCookie(w, session.cookie)
data := new(struct{ Role int })
data.Role = 0
data.Role = user.Role
tmpl, err := template.ParseFiles(c.WebDir + "/templates/hub.html")
if err = template.Must(tmpl, err).ExecuteTemplate(w, "page-content", data); err != nil {

View File

@ -32,6 +32,8 @@ func main() {
sessions, sessionExpiryChan := f.StartSessions()
defer close(sessionExpiryChan)
// go b.CleanUpImages(config)
mux := http.NewServeMux()
mux.Handle("/web/static/", http.StripPrefix("/web/static/",
http.FileServer(http.Dir(config.WebDir+"/static/"))))
@ -72,13 +74,14 @@ func main() {
mux.HandleFunc("POST /article/submit", f.SubmitArticle(config, db, sessions))
mux.HandleFunc("POST /article/upload-banner", f.UploadImage(config, sessions, "article-banner", "editor.html", "article-banner-template"))
mux.HandleFunc("POST /article/upload-image", f.UploadEasyMDEImage(config, sessions))
mux.HandleFunc("POST /docx/upload", f.UploadDocx(config, db, sessions))
mux.HandleFunc("POST /issue/publish", f.PublishLatestIssue(config, db, sessions))
mux.HandleFunc("POST /issue/upload-banner", f.UploadImage(config, sessions, "issue-banner", "current-issue.html", "issue-banner-template"))
mux.HandleFunc("POST /login", f.Login(config, db, sessions, sessionExpiryChan))
mux.HandleFunc("POST /pdf/upload", f.UploadPDF(config, sessions))
mux.HandleFunc("POST /tag/add", f.AddTag(config, db, sessions))
mux.HandleFunc("POST /user/add", f.AddUser(config, db, sessions))
mux.HandleFunc("POST /user/add-first", f.AddFirstUser(config, db, sessions))
mux.HandleFunc("POST /user/add-first", f.AddFirstUser(config, db, sessions, sessionExpiryChan))
mux.HandleFunc("POST /user/update/{id}", f.UpdateUser(config, db, sessions))
mux.HandleFunc("POST /user/update/self", f.UpdateSelf(config, db, sessions))
mux.HandleFunc("POST /user/upload-profile-pic", f.UploadImage(config, sessions, "upload-profile-pic", "edit-user.html", "profile-pic-template"))

View File

@ -38,6 +38,7 @@ CREATE TABLE articles (
clicks INT NOT NULL,
is_in_issue BOOL NOT NULL,
auto_generated BOOL NOT NULL,
uuid VARCHAR(36) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (creator_id) REFERENCES users (id),
FOREIGN KEY (issue_id) REFERENCES issues (id)

1
go.mod
View File

@ -8,6 +8,7 @@ require (
github.com/BurntSushi/toml v1.4.0
github.com/chai2010/webp v1.1.1
github.com/disintegration/imaging v1.6.2
github.com/gabriel-vasile/mimetype v1.4.8
github.com/go-sql-driver/mysql v1.8.1
github.com/google/uuid v1.6.0
github.com/microcosm-cc/bluemonday v1.0.27

2
go.sum
View File

@ -62,6 +62,8 @@ github.com/envoyproxy/protoc-gen-validate v1.1.0 h1:tntQDh69XqOCOZsDz0lVJQez/2L6
github.com/envoyproxy/protoc-gen-validate v1.1.0/go.mod h1:sXRDRVmzEbkM7CVcM06s9shE/m23dg3wzjl0UWqJ2q4=
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=

View File

@ -7,6 +7,11 @@
<h2>Artikel</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-2">
<button class="btn" hx-get="/article/write" hx-target="#page-content">Artikel schreiben</button>
<form class="flex" hx-encoding="multipart/form-data">
<label class="btn text-center" for="docx-upload">Word-Dokument hochladen</label>
<input accept=".docx" class="hidden" id="docx-upload" name="docx-upload" type="file"
hx-post="/docx/upload" />
</form>
<button class="btn" hx-get="/article/all-rejected" hx-target="#page-content">Artikel bearbeiten</button>
{{if lt .Role 3}}<button class="btn" hx-get="/article/all-unpublished-unrejected-and-published-rejected"
hx-target="#page-content">Artikel veröffentlichen</button>{{end}}