Compare commits
2 Commits
main
...
blog-cleanup
| Author | SHA1 | Date | |
|---|---|---|---|
| 7b86dbeaab | |||
| 687fbd7e65 |
@@ -0,0 +1,189 @@
|
|||||||
|
# Blog module
|
||||||
|
|
||||||
|
A simple blog module for darkstorm-backend.
|
||||||
|
|
||||||
|
## Requests
|
||||||
|
|
||||||
|
### Author info
|
||||||
|
|
||||||
|
#### Get author info
|
||||||
|
|
||||||
|
> GET /author/{authorID}
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
id: "authorID",
|
||||||
|
name: "author name",
|
||||||
|
about: "about",
|
||||||
|
picurl: "picture URL"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Update author info
|
||||||
|
|
||||||
|
> POST /author/{authorID}
|
||||||
|
|
||||||
|
Must have a auth token for a user with the `"blog": "admin"` permission.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
name: "author name",
|
||||||
|
about: "about",
|
||||||
|
picurl: "picture url"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Add Author info
|
||||||
|
|
||||||
|
> POST /author
|
||||||
|
|
||||||
|
Must have a auth token for a user with the `"blog": "admin"` permission.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
name: "author name",
|
||||||
|
about: "about",
|
||||||
|
picurl: "picture URL"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Blog
|
||||||
|
|
||||||
|
#### Specific blog
|
||||||
|
|
||||||
|
> GET /blog/{blogID}
|
||||||
|
|
||||||
|
Return:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
id: "blogID",
|
||||||
|
staticPage: false, // static pages don't show up alongside other blog pages.
|
||||||
|
createTime: 0, // creation time in Unix format
|
||||||
|
updateTime: 0, // last update time in Unix format
|
||||||
|
author: "authorID",
|
||||||
|
favicon: "favicon url",
|
||||||
|
title: "blog title",
|
||||||
|
blog: "blog", // blog will have been converted to HTML
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Create blog
|
||||||
|
|
||||||
|
Request:
|
||||||
|
|
||||||
|
> POST /blog
|
||||||
|
|
||||||
|
Must have a auth token for a user with the `"blog": "admin"` permission.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
favicon: "favicon url",
|
||||||
|
title: "blog title",
|
||||||
|
blog: "blog", // blog will have been converted to HTML
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Return:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
id: "blogID"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Update blog
|
||||||
|
|
||||||
|
Request:
|
||||||
|
|
||||||
|
> POST /blog/{blogID}
|
||||||
|
|
||||||
|
Must have a auth token for a user with the `"blog": "admin"` permission.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
favicon: "new icon",
|
||||||
|
title: "new title",
|
||||||
|
blog: "new blog content"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Latest blogs
|
||||||
|
|
||||||
|
> GET /blog?page=0
|
||||||
|
|
||||||
|
Will return up to 5 blogs. `page` query is optional (implies 0 if not set).
|
||||||
|
|
||||||
|
Return:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
num: 1, // Number of returned results, returns up to 5 results
|
||||||
|
blogs: [
|
||||||
|
{
|
||||||
|
id: "blogID",
|
||||||
|
createTime: 0, // creation time in Unix format
|
||||||
|
updateTime: 0, // last update time in Unix format
|
||||||
|
author: "authorID",
|
||||||
|
favicon: "favicon url",
|
||||||
|
title: "blog title",
|
||||||
|
blog: "blog", // blog will have been converted to HTML
|
||||||
|
}
|
||||||
|
...
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Blog List
|
||||||
|
|
||||||
|
> GET /blog/list?page=0
|
||||||
|
|
||||||
|
Will return up to 50 IDs. `page` query is optional (implies 0 if not set).
|
||||||
|
|
||||||
|
Return:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
num: 1, // Number of returned results, returns up to 50 results
|
||||||
|
blogList: [
|
||||||
|
{
|
||||||
|
id: "blogID",
|
||||||
|
createTime: 0, // Unix format
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "blogID",
|
||||||
|
createTime: 0, // Unix format
|
||||||
|
},
|
||||||
|
...
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Portfolio
|
||||||
|
|
||||||
|
#### Get Projects
|
||||||
|
|
||||||
|
> GET: /portfolio?lang=go
|
||||||
|
|
||||||
|
Return:
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
title: "Darkstorm Server",
|
||||||
|
order: 0,
|
||||||
|
repository: "https://github.com/CalebQ42/darkstorm-server",
|
||||||
|
description: "The backend that runs runs my website and APIs",
|
||||||
|
technologies: [ // May be empty
|
||||||
|
"MongoDB",
|
||||||
|
"RESTful API"
|
||||||
|
],
|
||||||
|
language: [
|
||||||
|
{
|
||||||
|
language: "go",
|
||||||
|
dates: "September 2021"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
package blog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
||||||
|
"go.mongodb.org/mongo-driver/bson"
|
||||||
|
"go.mongodb.org/mongo-driver/mongo"
|
||||||
|
)
|
||||||
|
|
||||||
|
const authorInfo = `
|
||||||
|
<table><tr>
|
||||||
|
<td><img src="%v" alt="%v" class='author-pic'></td>
|
||||||
|
<td><h3 class="author-title">%v</h3>%v</td>
|
||||||
|
</tr></table>`
|
||||||
|
|
||||||
|
type Author struct {
|
||||||
|
ID string `json:"id" bson:"_id"`
|
||||||
|
Name string `json:"name" bson:"name"`
|
||||||
|
About string `json:"about" bson:"about"`
|
||||||
|
PicURL string `json:"picurl" bson:"picurl"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a Author) HTML() string {
|
||||||
|
return fmt.Sprintf(authorInfo, a.PicURL, a.Name+"'s profile picture", a.Name, a.About)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) AboutMe(ctx context.Context) (*Author, error) {
|
||||||
|
res := b.authCol.FindOne(ctx, bson.M{"_id": "caleb_gardner"})
|
||||||
|
if res.Err() != nil {
|
||||||
|
log.Println("error getting about me:", res.Err())
|
||||||
|
if res.Err() == mongo.ErrNoDocuments {
|
||||||
|
return nil, backend.ErrNotFound
|
||||||
|
}
|
||||||
|
return nil, res.Err()
|
||||||
|
}
|
||||||
|
var aboutMe Author
|
||||||
|
err := res.Decode(&aboutMe)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("error decoding about me:", res)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &aboutMe, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) reqAuthorInfo(w http.ResponseWriter, r *http.Request) {
|
||||||
|
res := b.authCol.FindOne(r.Context(), r.PathValue("authorID"))
|
||||||
|
if res.Err() == mongo.ErrNoDocuments {
|
||||||
|
backend.ReturnError(w, http.StatusNotFound, "notFound", "Author with ID "+r.PathValue("authorID")+" not found")
|
||||||
|
return
|
||||||
|
} else if res.Err() != nil {
|
||||||
|
log.Println("error getting author info:", res.Err())
|
||||||
|
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var auth Author
|
||||||
|
err := res.Decode(&auth)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("error decoding author info:", err)
|
||||||
|
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
json.NewEncoder(w).Encode(auth)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) addAuthorInfo(w http.ResponseWriter, r *http.Request) {
|
||||||
|
hdr, err := b.back.VerifyHeader(w, r, "blogManagement", false)
|
||||||
|
if hdr == nil {
|
||||||
|
if err != nil {
|
||||||
|
log.Println("request key parsing error:", err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
} else if hdr.Key.AppID != "blog" {
|
||||||
|
backend.ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application is unauthorized")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if hdr.User == nil || hdr.User.Perm["blog"] != "admin" {
|
||||||
|
backend.ReturnError(w, http.StatusUnauthorized, "unauthorized", "Application is unauthorized")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var newAuth Author
|
||||||
|
err = json.NewDecoder(r.Body).Decode(&newAuth)
|
||||||
|
r.Body.Close()
|
||||||
|
if err != nil {
|
||||||
|
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Invalid request")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for i := 1; ; i++ {
|
||||||
|
newID := strings.ReplaceAll(newAuth.Name, " ", "-")
|
||||||
|
if i != 1 {
|
||||||
|
newID += strconv.Itoa(i)
|
||||||
|
}
|
||||||
|
collisionCheck := b.authCol.FindOne(r.Context(), bson.M{"name": newAuth.Name})
|
||||||
|
if collisionCheck.Err() == mongo.ErrNoDocuments {
|
||||||
|
newAuth.ID = newID
|
||||||
|
break
|
||||||
|
} else if collisionCheck.Err() != nil {
|
||||||
|
log.Println("error checking for new author ID collisions:", err)
|
||||||
|
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_, err = b.authCol.InsertOne(r.Context(), newAuth)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("error inserting new author:", err)
|
||||||
|
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) updateAuthorInfo(w http.ResponseWriter, r *http.Request) {
|
||||||
|
hdr, err := b.back.VerifyHeader(w, r, "blogManagement", false)
|
||||||
|
if hdr == nil {
|
||||||
|
if err != nil {
|
||||||
|
log.Println("request key parsing error:", err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
} else if hdr.Key.AppID != "blog" {
|
||||||
|
backend.ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application is unauthorized")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if hdr.User == nil || hdr.User.Perm["blog"] != "admin" {
|
||||||
|
backend.ReturnError(w, http.StatusUnauthorized, "unauthorized", "Application is unauthorized")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var rawUpd map[string]string
|
||||||
|
err = json.NewDecoder(r.Body).Decode(&rawUpd)
|
||||||
|
r.Body.Close()
|
||||||
|
if err != nil {
|
||||||
|
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Invalid request")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
actlUpd := make(map[string]string)
|
||||||
|
if rawUpd["name"] != "" {
|
||||||
|
actlUpd["name"] = rawUpd["name"]
|
||||||
|
}
|
||||||
|
if rawUpd["about"] != "" {
|
||||||
|
actlUpd["about"] = rawUpd["about"]
|
||||||
|
}
|
||||||
|
if rawUpd["picurl"] != "" {
|
||||||
|
actlUpd["picurl"] = rawUpd["picurl"]
|
||||||
|
}
|
||||||
|
res, err := b.authCol.UpdateByID(r.Context(), r.PathValue("authorID"), actlUpd)
|
||||||
|
if err != nil {
|
||||||
|
if err == mongo.ErrNoDocuments {
|
||||||
|
backend.ReturnError(w, http.StatusNotFound, "notFound", "Blog with ID "+r.PathValue("blogID")+" not found")
|
||||||
|
} else {
|
||||||
|
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if res.MatchedCount == 0 {
|
||||||
|
backend.ReturnError(w, http.StatusNotFound, "notFound", "Blog with ID "+r.PathValue("blogID")+" not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
}
|
||||||
@@ -0,0 +1,387 @@
|
|||||||
|
package blog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"go.mongodb.org/mongo-driver/bson"
|
||||||
|
"go.mongodb.org/mongo-driver/mongo"
|
||||||
|
"go.mongodb.org/mongo-driver/mongo/options"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
blogTitle = "<h1 class='blog-title'><a hx-push-url='true' hx-get='/%v' hx-target='#content' href='/%v' style='text-decoration:none'>%v</a></h1>"
|
||||||
|
blogAuthor = "<h4 class='blog-author'><i><b>By %v</b></i></h4>"
|
||||||
|
blogCreate = "<h5 class='blog-time'><i>Written on: %v</i></h5>"
|
||||||
|
blogMain = "<div class='blog'>%v</div>"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Blog struct {
|
||||||
|
ID string `json:"id" bson:"_id"`
|
||||||
|
Author string `json:"author" bson:"author"`
|
||||||
|
Favicon string `json:"favicon" bson:"favicon"`
|
||||||
|
Title string `json:"title" bson:"title"`
|
||||||
|
RawBlog string `json:"blog" bson:"blog"`
|
||||||
|
HTMLBlog string `json:"-" bson:"-"`
|
||||||
|
StaticPage bool `json:"staticPage" bson:"staticPage"`
|
||||||
|
Draft bool `json:"draft" bson:"draft"`
|
||||||
|
CreateTime int64 `json:"createTime" bson:"createTime"`
|
||||||
|
UpdateTime int64 `json:"updateTime" bson:"updateTime"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Blog) HTMX(blogApp *BlogApp, ctx context.Context) string {
|
||||||
|
if b.StaticPage {
|
||||||
|
return b.RawBlog
|
||||||
|
}
|
||||||
|
out := fmt.Sprintf(blogTitle, b.ID, b.ID, b.Title)
|
||||||
|
auth, err := blogApp.GetAuthor(ctx, b)
|
||||||
|
if err == nil {
|
||||||
|
out += fmt.Sprintf(blogAuthor, auth.Name)
|
||||||
|
} else {
|
||||||
|
out += fmt.Sprintf(blogAuthor, "unknown")
|
||||||
|
}
|
||||||
|
cTime := time.Unix(b.CreateTime, 0).Format(time.DateOnly)
|
||||||
|
if b.UpdateTime > b.CreateTime {
|
||||||
|
out += fmt.Sprintf(blogCreate, cTime+"; Last updated on: "+time.Unix(b.UpdateTime, 0).Format(time.DateOnly))
|
||||||
|
} else {
|
||||||
|
out += fmt.Sprintf(blogCreate, cTime)
|
||||||
|
}
|
||||||
|
out += fmt.Sprintf(blogMain, b.HTMLBlog)
|
||||||
|
if err == nil {
|
||||||
|
out += "<h2 class='blog-author-info'>About the author:</h2>" + auth.HTML()
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) ConvertBlog(blog *Blog) {
|
||||||
|
if !blog.StaticPage {
|
||||||
|
blog.HTMLBlog = b.conv.HTMLConvert(blog.RawBlog)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) GetAuthor(ctx context.Context, blog *Blog) (*Author, error) {
|
||||||
|
res := b.authCol.FindOne(ctx, bson.M{"_id": blog.Author})
|
||||||
|
if res.Err() != nil {
|
||||||
|
if res.Err() == mongo.ErrNoDocuments {
|
||||||
|
return nil, backend.ErrNotFound
|
||||||
|
}
|
||||||
|
return nil, res.Err()
|
||||||
|
}
|
||||||
|
var author Author
|
||||||
|
err := res.Decode(&author)
|
||||||
|
return &author, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) Blog(ctx context.Context, ID string) (*Blog, error) {
|
||||||
|
b.cacheMutex.RLock()
|
||||||
|
blog, has := b.blogCache[ID]
|
||||||
|
b.cacheMutex.RUnlock()
|
||||||
|
if has {
|
||||||
|
return &blog, nil
|
||||||
|
}
|
||||||
|
res := b.blogCol.FindOne(ctx, bson.M{"_id": ID, "draft": false})
|
||||||
|
if res.Err() != nil {
|
||||||
|
if res.Err() == mongo.ErrNoDocuments {
|
||||||
|
return nil, backend.ErrNotFound
|
||||||
|
}
|
||||||
|
return nil, res.Err()
|
||||||
|
}
|
||||||
|
err := res.Decode(&blog)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
b.ConvertBlog(&blog)
|
||||||
|
b.cacheMutex.Lock()
|
||||||
|
b.blogCache[ID] = blog
|
||||||
|
b.cacheMutex.Unlock()
|
||||||
|
go b.CleanCache(ID)
|
||||||
|
return &blog, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) AnyBlog(ctx context.Context, ID string) (*Blog, error) {
|
||||||
|
res := b.blogCol.FindOne(ctx, bson.M{"_id": ID})
|
||||||
|
if res.Err() != nil {
|
||||||
|
if res.Err() == mongo.ErrNoDocuments {
|
||||||
|
return nil, backend.ErrNotFound
|
||||||
|
}
|
||||||
|
return nil, res.Err()
|
||||||
|
}
|
||||||
|
var blog Blog
|
||||||
|
err := res.Decode(&blog)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
b.ConvertBlog(&blog)
|
||||||
|
return &blog, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) Contains(ctx context.Context, ID string) bool {
|
||||||
|
res := b.blogCol.FindOne(ctx, bson.M{"_id": ID})
|
||||||
|
return res.Err() == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) CleanCache(ID string) {
|
||||||
|
time.Sleep(5 * time.Minute)
|
||||||
|
b.cacheMutex.Lock()
|
||||||
|
delete(b.blogCache, ID)
|
||||||
|
b.cacheMutex.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) reqBlog(w http.ResponseWriter, r *http.Request) {
|
||||||
|
blogID := r.PathValue("blogID")
|
||||||
|
if blogID == "" {
|
||||||
|
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Must provide a blogID")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
blog, err := b.Blog(r.Context(), blogID)
|
||||||
|
if err != nil {
|
||||||
|
if err == backend.ErrNotFound {
|
||||||
|
backend.ReturnError(w, http.StatusNotFound, "notFound", "Not blog found with the given ID")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Println("error getting blog:", err)
|
||||||
|
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Header.Get("Hx-Request") == "true" {
|
||||||
|
w.Write([]byte(blog.HTMX(b, r.Context())))
|
||||||
|
} else {
|
||||||
|
json.NewEncoder(w).Encode(blog)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) createBlog(w http.ResponseWriter, r *http.Request) {
|
||||||
|
hdr, err := b.back.VerifyHeader(w, r, "blogManagement", false)
|
||||||
|
if hdr == nil {
|
||||||
|
if err != nil {
|
||||||
|
log.Println("request key parsing error:", err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
} else if hdr.Key.AppID != "blog" {
|
||||||
|
backend.ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application is unauthorized")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if hdr.User == nil || hdr.User.Perm["blog"] != "admin" {
|
||||||
|
backend.ReturnError(w, http.StatusUnauthorized, "unauthorized", "Application is unauthorized")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var newBlog Blog
|
||||||
|
err = json.NewDecoder(r.Body).Decode(&newBlog)
|
||||||
|
r.Body.Close()
|
||||||
|
if err != nil {
|
||||||
|
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Bad request")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id, err := uuid.NewV7()
|
||||||
|
if err != nil {
|
||||||
|
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tim := time.Now().Unix()
|
||||||
|
newBlog.ID = id.String()
|
||||||
|
newBlog.CreateTime = tim
|
||||||
|
newBlog.UpdateTime = tim
|
||||||
|
newBlog.Author = hdr.User.Username
|
||||||
|
_, err = b.blogCol.InsertOne(r.Context(), newBlog)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("error when inserting new blog:", err)
|
||||||
|
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) updateBlog(w http.ResponseWriter, r *http.Request) {
|
||||||
|
hdr, err := b.back.VerifyHeader(w, r, "blogManagement", false)
|
||||||
|
if hdr == nil {
|
||||||
|
if err != nil {
|
||||||
|
log.Println("request key parsing error:", err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
} else if hdr.Key.AppID != "blog" {
|
||||||
|
backend.ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application is unauthorized")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if hdr.User == nil || hdr.User.Perm["blog"] != "admin" {
|
||||||
|
backend.ReturnError(w, http.StatusUnauthorized, "unauthorized", "Application is unauthorized")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.PathValue("blogID") == "" {
|
||||||
|
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Bad request")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var reqUpdRaw map[string]string
|
||||||
|
err = json.NewDecoder(r.Body).Decode(&reqUpdRaw)
|
||||||
|
r.Body.Close()
|
||||||
|
if err != nil {
|
||||||
|
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Bad request")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
reqUpd := bson.M{}
|
||||||
|
if fav, ok := reqUpdRaw["favicon"]; ok && fav != "" {
|
||||||
|
reqUpd["favicon"] = fav
|
||||||
|
}
|
||||||
|
if titl, ok := reqUpdRaw["title"]; ok && titl != "" {
|
||||||
|
reqUpd["title"] = titl
|
||||||
|
}
|
||||||
|
if blog, ok := reqUpdRaw["blog"]; ok && blog != "" {
|
||||||
|
reqUpd["blog"] = blog
|
||||||
|
}
|
||||||
|
reqUpd["updateTime"] = time.Now().Unix()
|
||||||
|
res, err := b.blogCol.UpdateByID(r.Context(), r.PathValue("blogID"), reqUpd)
|
||||||
|
if err != nil {
|
||||||
|
if err == mongo.ErrNoDocuments {
|
||||||
|
backend.ReturnError(w, http.StatusNotFound, "notFound", "Blog with ID "+r.PathValue("blogID")+" not found")
|
||||||
|
} else {
|
||||||
|
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if res.MatchedCount == 0 {
|
||||||
|
backend.ReturnError(w, http.StatusNotFound, "notFound", "Blog with ID "+r.PathValue("blogID")+" not found")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) InsertBlog(ctx context.Context, blog Blog) error {
|
||||||
|
_, err := b.blogCol.InsertOne(ctx, blog)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) UpdateBlog(ctx context.Context, ID string, updates bson.M) error {
|
||||||
|
_, err := b.blogCol.UpdateByID(ctx, ID, bson.M{"$set": updates})
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) LatestBlogs(ctx context.Context, page int64) ([]*Blog, error) {
|
||||||
|
res, err := b.blogCol.Find(ctx, bson.M{"staticPage": false, "draft": false}, options.Find().
|
||||||
|
SetSort(bson.M{"createTime": -1}).
|
||||||
|
SetLimit(5).
|
||||||
|
SetSkip(page*5))
|
||||||
|
if err != nil {
|
||||||
|
if err == mongo.ErrNoDocuments {
|
||||||
|
return nil, backend.ErrNotFound
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var out []*Blog
|
||||||
|
err = res.All(ctx, &out)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for i := range out {
|
||||||
|
b.ConvertBlog(out[i])
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) reqLatestBlogs(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var page int
|
||||||
|
var err error
|
||||||
|
pagQuery := r.URL.Query().Get("page")
|
||||||
|
if pagQuery != "" {
|
||||||
|
page, err = strconv.Atoi(pagQuery)
|
||||||
|
if err != nil {
|
||||||
|
page = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
blogs, err := b.LatestBlogs(r.Context(), int64(page))
|
||||||
|
if err != nil && err != backend.ErrNotFound {
|
||||||
|
log.Println("error getting latest blogs:", err)
|
||||||
|
backend.ReturnError(w, http.StatusInternalServerError, "internal", "internal error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var ret struct {
|
||||||
|
Blogs []*Blog `json:"blogs"`
|
||||||
|
Num int `json:"num"`
|
||||||
|
}
|
||||||
|
ret.Num = len(blogs)
|
||||||
|
ret.Blogs = blogs
|
||||||
|
json.NewEncoder(w).Encode(ret)
|
||||||
|
}
|
||||||
|
|
||||||
|
type BlogListResult struct {
|
||||||
|
ID string `json:"id" bson:"_id"`
|
||||||
|
Title string `json:"title" bson:"title"`
|
||||||
|
CreateTime int `json:"createTime" bson:"createTime"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b BlogListResult) HTMX() string {
|
||||||
|
return "<a class='blog-list-item' href='https://darkstorm.tech/" +
|
||||||
|
b.ID +
|
||||||
|
"' hx-push-url='true' hx-target='#content' hx-get='/" +
|
||||||
|
b.ID +
|
||||||
|
"'>" + b.Title + "</a>"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) BlogList(ctx context.Context, page int64) ([]BlogListResult, error) {
|
||||||
|
res, err := b.blogCol.Find(ctx, bson.M{"staticPage": false, "draft": false}, options.Find().
|
||||||
|
SetProjection(bson.M{"_id": 1, "createTime": 1, "title": 1}).
|
||||||
|
SetSort(bson.M{"createTime": -1}).
|
||||||
|
SetLimit(50).
|
||||||
|
SetSkip(page*50))
|
||||||
|
if err != nil {
|
||||||
|
if err == mongo.ErrNoDocuments {
|
||||||
|
return nil, backend.ErrNotFound
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var out []BlogListResult
|
||||||
|
err = res.All(ctx, &out)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) AllBlogsList(ctx context.Context) ([]BlogListResult, error) {
|
||||||
|
res, err := b.blogCol.Find(ctx, bson.M{}, options.Find().
|
||||||
|
SetProjection(bson.M{"_id": 1, "createTime": 1, "title": 1}).
|
||||||
|
SetSort(bson.M{"createTime": -1}))
|
||||||
|
if err != nil {
|
||||||
|
if err == mongo.ErrNoDocuments {
|
||||||
|
return nil, backend.ErrNotFound
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var out []BlogListResult
|
||||||
|
err = res.All(ctx, &out)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) reqBlogList(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var page int
|
||||||
|
var err error
|
||||||
|
pagQuery := r.URL.Query().Get("page")
|
||||||
|
if pagQuery != "" {
|
||||||
|
page, err = strconv.Atoi(pagQuery)
|
||||||
|
if err != nil {
|
||||||
|
page = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
blogList, err := b.BlogList(r.Context(), int64(page))
|
||||||
|
if err != nil && err != backend.ErrNotFound {
|
||||||
|
log.Println("error getting blog list:", err)
|
||||||
|
backend.ReturnError(w, http.StatusInternalServerError, "internal", "internal error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var ret struct {
|
||||||
|
BlogList []BlogListResult `json:"blogList"`
|
||||||
|
Num int `json:"num"`
|
||||||
|
}
|
||||||
|
ret.Num = len(blogList)
|
||||||
|
ret.BlogList = blogList
|
||||||
|
json.NewEncoder(w).Encode(ret)
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package blog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/CalebQ42/bbConvert"
|
||||||
|
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
||||||
|
"go.mongodb.org/mongo-driver/mongo"
|
||||||
|
)
|
||||||
|
|
||||||
|
type BlogApp struct {
|
||||||
|
back *backend.Backend
|
||||||
|
blogCol *mongo.Collection
|
||||||
|
authCol *mongo.Collection
|
||||||
|
portfolioCol *mongo.Collection
|
||||||
|
conv bbConvert.ComboConverter
|
||||||
|
|
||||||
|
cacheMutex *sync.RWMutex
|
||||||
|
blogCache map[string]Blog
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBlogApp(db *mongo.Database) *BlogApp {
|
||||||
|
out := &BlogApp{
|
||||||
|
blogCol: db.Collection("blog"),
|
||||||
|
authCol: db.Collection("author"),
|
||||||
|
portfolioCol: db.Collection("portfolio"),
|
||||||
|
conv: bbConvert.NewComboConverter(),
|
||||||
|
cacheMutex: &sync.RWMutex{},
|
||||||
|
blogCache: make(map[string]Blog),
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) AppID() string {
|
||||||
|
return "blog"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) CountTable() backend.CountTable {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) CrashTable() backend.CrashTable {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) AddBackend(back *backend.Backend) {
|
||||||
|
b.back = back
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) Extension(mux *http.ServeMux) {
|
||||||
|
mux.HandleFunc("GET /blog", b.reqLatestBlogs)
|
||||||
|
mux.HandleFunc("GET /blog/list", b.reqBlogList)
|
||||||
|
mux.HandleFunc("GET /blog/{blogID}", b.reqBlog)
|
||||||
|
mux.HandleFunc("POST /blog", b.createBlog)
|
||||||
|
mux.HandleFunc("POST /blog/{blogID}", b.updateBlog)
|
||||||
|
|
||||||
|
mux.HandleFunc("GET /blog/author/{authorID}", b.reqAuthorInfo)
|
||||||
|
mux.HandleFunc("POST /blog/author", b.addAuthorInfo)
|
||||||
|
mux.HandleFunc("POST /blog/author/{authorID}", b.updateAuthorInfo)
|
||||||
|
|
||||||
|
mux.HandleFunc("GET /blog/portfolio", b.reqPortfolio)
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
package blog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
||||||
|
"go.mongodb.org/mongo-driver/bson"
|
||||||
|
"go.mongodb.org/mongo-driver/mongo/options"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
portfolioTitle = "<h2 class='portfolio-title'>%v</h2>"
|
||||||
|
portfolioLink = "<p class='portfolio-link'><a href='%v'>%v</a>"
|
||||||
|
portfolioLanguage = "<p class='portfolio-language'><b>%v</b>: %v</p>"
|
||||||
|
portfolioTech = "<p class='portfolio-tech'><b>Tech: </b>%v</p>"
|
||||||
|
portfolioDesc = "<p class='portfolio-description'>%v</p>"
|
||||||
|
)
|
||||||
|
|
||||||
|
type PortfolioProject struct {
|
||||||
|
Title string `json:"_id" bson:"_id"`
|
||||||
|
Order int `json:"order" bson:"order"`
|
||||||
|
Repository string `json:"repository" bson:"repository"`
|
||||||
|
Description string `json:"description" bson:"description"`
|
||||||
|
Technologies []string `json:"technologies" bson:"technologies"`
|
||||||
|
Languages []struct {
|
||||||
|
Language string `json:"language" bson:"language"`
|
||||||
|
Dates string `json:"dates" bson:"dates"`
|
||||||
|
} `json:"language" bson:"language"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p PortfolioProject) HTMX() string {
|
||||||
|
out := fmt.Sprintf(portfolioTitle, p.Title)
|
||||||
|
out += fmt.Sprintf(portfolioLink, p.Repository, p.Repository)
|
||||||
|
for _, l := range p.Languages {
|
||||||
|
out += fmt.Sprintf(portfolioLanguage, l.Language, l.Dates)
|
||||||
|
}
|
||||||
|
out += fmt.Sprintf(portfolioTech, strings.Join(p.Technologies, ", "))
|
||||||
|
out += fmt.Sprintf(portfolioDesc, p.Description)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
type Portfolio []PortfolioProject
|
||||||
|
|
||||||
|
const (
|
||||||
|
portfolioSelector = `
|
||||||
|
<p>Tech Filter:
|
||||||
|
<select
|
||||||
|
id='techSelect'
|
||||||
|
name='tech'
|
||||||
|
hx-get='https://api.darkstorm.tech/blog/portfolio'
|
||||||
|
hx-target='#projects'>
|
||||||
|
%v
|
||||||
|
</select>
|
||||||
|
</p>`
|
||||||
|
portfolioSelectorOption = "<option value='%v'%v>%v</option>"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (p Portfolio) FullHTMX(ctx context.Context, blogApp *BlogApp, selectedTech string) string {
|
||||||
|
aboutMe := "<h1 class='about-me-header'>About Me</h1>"
|
||||||
|
if me, err := blogApp.AboutMe(ctx); err != nil {
|
||||||
|
aboutMe += "Error getting info about me :("
|
||||||
|
} else {
|
||||||
|
aboutMe += me.HTML()
|
||||||
|
}
|
||||||
|
aboutMe += "<h1 class='my-projects-header' style='margin-bottom:15px'>My Projects</h1>"
|
||||||
|
tech := make(map[string]struct{})
|
||||||
|
for i := range p {
|
||||||
|
for _, t := range p[i].Technologies {
|
||||||
|
tech[t] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
techKeys := make([]string, 0, len(tech))
|
||||||
|
for k := range tech {
|
||||||
|
techKeys = append(techKeys, k)
|
||||||
|
}
|
||||||
|
slices.Sort(techKeys)
|
||||||
|
var out string
|
||||||
|
if selectedTech == "" {
|
||||||
|
out = fmt.Sprintf(portfolioSelectorOption, "", " selected=true", "All")
|
||||||
|
} else {
|
||||||
|
out = fmt.Sprintf(portfolioSelectorOption, "", "", "All")
|
||||||
|
}
|
||||||
|
for _, k := range techKeys {
|
||||||
|
if selectedTech == strings.ToLower(k) {
|
||||||
|
out += fmt.Sprintf(portfolioSelectorOption, k, " selected=true", k)
|
||||||
|
} else {
|
||||||
|
out += fmt.Sprintf(portfolioSelectorOption, k, "", k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return aboutMe + fmt.Sprintf(portfolioSelector, out) + "<div id='projects'>" + p.HTMX() + "</div>"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p Portfolio) HTMX() string {
|
||||||
|
out := ""
|
||||||
|
for _, proj := range p {
|
||||||
|
out += proj.HTMX()
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) Projects(ctx context.Context, techFilter string) (Portfolio, error) {
|
||||||
|
filter := bson.M{}
|
||||||
|
if techFilter != "" {
|
||||||
|
filter = bson.M{"technologies": techFilter}
|
||||||
|
}
|
||||||
|
res, err := b.portfolioCol.Find(ctx, filter, options.Find().SetSort(bson.M{"order": 1}))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var out []PortfolioProject
|
||||||
|
err = res.All(ctx, &out)
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BlogApp) reqPortfolio(w http.ResponseWriter, r *http.Request) {
|
||||||
|
folio, err := b.Projects(r.Context(), r.URL.Query().Get("tech"))
|
||||||
|
if err != nil {
|
||||||
|
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if r.Header.Get("Hx-Request") == "true" {
|
||||||
|
if r.URL.Query().Has("tech") {
|
||||||
|
w.Write([]byte(folio.HTMX()))
|
||||||
|
} else {
|
||||||
|
w.Write([]byte(folio.FullHTMX(r.Context(), b, r.URL.Query().Get("tech"))))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
json.NewEncoder(w).Encode(folio)
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-188
@@ -1,189 +1,3 @@
|
|||||||
# Blog module
|
# Blogs
|
||||||
|
|
||||||
A simple blog module for darkstorm-backend.
|
An HTMX powered blog system and editor.
|
||||||
|
|
||||||
## Requests
|
|
||||||
|
|
||||||
### Author info
|
|
||||||
|
|
||||||
#### Get author info
|
|
||||||
|
|
||||||
> GET /author/{authorID}
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
id: "authorID",
|
|
||||||
name: "author name",
|
|
||||||
about: "about",
|
|
||||||
picurl: "picture URL"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Update author info
|
|
||||||
|
|
||||||
> POST /author/{authorID}
|
|
||||||
|
|
||||||
Must have a auth token for a user with the `"blog": "admin"` permission.
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
name: "author name",
|
|
||||||
about: "about",
|
|
||||||
picurl: "picture url"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Add Author info
|
|
||||||
|
|
||||||
> POST /author
|
|
||||||
|
|
||||||
Must have a auth token for a user with the `"blog": "admin"` permission.
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
name: "author name",
|
|
||||||
about: "about",
|
|
||||||
picurl: "picture URL"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Blog
|
|
||||||
|
|
||||||
#### Specific blog
|
|
||||||
|
|
||||||
> GET /blog/{blogID}
|
|
||||||
|
|
||||||
Return:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
id: "blogID",
|
|
||||||
staticPage: false, // static pages don't show up alongside other blog pages.
|
|
||||||
createTime: 0, // creation time in Unix format
|
|
||||||
updateTime: 0, // last update time in Unix format
|
|
||||||
author: "authorID",
|
|
||||||
favicon: "favicon url",
|
|
||||||
title: "blog title",
|
|
||||||
blog: "blog", // blog will have been converted to HTML
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Create blog
|
|
||||||
|
|
||||||
Request:
|
|
||||||
|
|
||||||
> POST /blog
|
|
||||||
|
|
||||||
Must have a auth token for a user with the `"blog": "admin"` permission.
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
favicon: "favicon url",
|
|
||||||
title: "blog title",
|
|
||||||
blog: "blog", // blog will have been converted to HTML
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Return:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
id: "blogID"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Update blog
|
|
||||||
|
|
||||||
Request:
|
|
||||||
|
|
||||||
> POST /blog/{blogID}
|
|
||||||
|
|
||||||
Must have a auth token for a user with the `"blog": "admin"` permission.
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
favicon: "new icon",
|
|
||||||
title: "new title",
|
|
||||||
blog: "new blog content"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Latest blogs
|
|
||||||
|
|
||||||
> GET /blog?page=0
|
|
||||||
|
|
||||||
Will return up to 5 blogs. `page` query is optional (implies 0 if not set).
|
|
||||||
|
|
||||||
Return:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
num: 1, // Number of returned results, returns up to 5 results
|
|
||||||
blogs: [
|
|
||||||
{
|
|
||||||
id: "blogID",
|
|
||||||
createTime: 0, // creation time in Unix format
|
|
||||||
updateTime: 0, // last update time in Unix format
|
|
||||||
author: "authorID",
|
|
||||||
favicon: "favicon url",
|
|
||||||
title: "blog title",
|
|
||||||
blog: "blog", // blog will have been converted to HTML
|
|
||||||
}
|
|
||||||
...
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Blog List
|
|
||||||
|
|
||||||
> GET /blog/list?page=0
|
|
||||||
|
|
||||||
Will return up to 50 IDs. `page` query is optional (implies 0 if not set).
|
|
||||||
|
|
||||||
Return:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
num: 1, // Number of returned results, returns up to 50 results
|
|
||||||
blogList: [
|
|
||||||
{
|
|
||||||
id: "blogID",
|
|
||||||
createTime: 0, // Unix format
|
|
||||||
},
|
|
||||||
{
|
|
||||||
id: "blogID",
|
|
||||||
createTime: 0, // Unix format
|
|
||||||
},
|
|
||||||
...
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Portfolio
|
|
||||||
|
|
||||||
#### Get Projects
|
|
||||||
|
|
||||||
> GET: /portfolio?lang=go
|
|
||||||
|
|
||||||
Return:
|
|
||||||
|
|
||||||
```json
|
|
||||||
[
|
|
||||||
{
|
|
||||||
title: "Darkstorm Server",
|
|
||||||
order: 0,
|
|
||||||
repository: "https://github.com/CalebQ42/darkstorm-server",
|
|
||||||
description: "The backend that runs runs my website and APIs",
|
|
||||||
technologies: [ // May be empty
|
|
||||||
"MongoDB",
|
|
||||||
"RESTful API"
|
|
||||||
],
|
|
||||||
language: [
|
|
||||||
{
|
|
||||||
language: "go",
|
|
||||||
dates: "September 2021"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
```
|
|
||||||
|
|||||||
@@ -1,164 +1,8 @@
|
|||||||
package blog
|
package blog
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
|
||||||
"go.mongodb.org/mongo-driver/bson"
|
|
||||||
"go.mongodb.org/mongo-driver/mongo"
|
|
||||||
)
|
|
||||||
|
|
||||||
const authorInfo = `
|
|
||||||
<table><tr>
|
|
||||||
<td><img src="%v" alt="%v" class='author-pic'></td>
|
|
||||||
<td><h3 class="author-title">%v</h3>%v</td>
|
|
||||||
</tr></table>`
|
|
||||||
|
|
||||||
type Author struct {
|
type Author struct {
|
||||||
ID string `json:"id" bson:"_id"`
|
ID string `json:"id" bson:"_id"`
|
||||||
Name string `json:"name" bson:"name"`
|
Name string `json:"name" bson:"name"`
|
||||||
About string `json:"about" bson:"about"`
|
About string `json:"about" bson:"about"`
|
||||||
PicURL string `json:"picurl" bson:"picurl"`
|
PicURL string `json:"picurl" bson:"picurl"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a Author) HTML() string {
|
|
||||||
return fmt.Sprintf(authorInfo, a.PicURL, a.Name+"'s profile picture", a.Name, a.About)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) AboutMe(ctx context.Context) (*Author, error) {
|
|
||||||
res := b.authCol.FindOne(ctx, bson.M{"_id": "caleb_gardner"})
|
|
||||||
if res.Err() != nil {
|
|
||||||
log.Println("error getting about me:", res.Err())
|
|
||||||
if res.Err() == mongo.ErrNoDocuments {
|
|
||||||
return nil, backend.ErrNotFound
|
|
||||||
}
|
|
||||||
return nil, res.Err()
|
|
||||||
}
|
|
||||||
var aboutMe Author
|
|
||||||
err := res.Decode(&aboutMe)
|
|
||||||
if err != nil {
|
|
||||||
log.Println("error decoding about me:", res)
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &aboutMe, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) reqAuthorInfo(w http.ResponseWriter, r *http.Request) {
|
|
||||||
res := b.authCol.FindOne(r.Context(), r.PathValue("authorID"))
|
|
||||||
if res.Err() == mongo.ErrNoDocuments {
|
|
||||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Author with ID "+r.PathValue("authorID")+" not found")
|
|
||||||
return
|
|
||||||
} else if res.Err() != nil {
|
|
||||||
log.Println("error getting author info:", res.Err())
|
|
||||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var auth Author
|
|
||||||
err := res.Decode(&auth)
|
|
||||||
if err != nil {
|
|
||||||
log.Println("error decoding author info:", err)
|
|
||||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
json.NewEncoder(w).Encode(auth)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) addAuthorInfo(w http.ResponseWriter, r *http.Request) {
|
|
||||||
hdr, err := b.back.VerifyHeader(w, r, "blogManagement", false)
|
|
||||||
if hdr == nil {
|
|
||||||
if err != nil {
|
|
||||||
log.Println("request key parsing error:", err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
} else if hdr.Key.AppID != "blog" {
|
|
||||||
backend.ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application is unauthorized")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if hdr.User == nil || hdr.User.Perm["blog"] != "admin" {
|
|
||||||
backend.ReturnError(w, http.StatusUnauthorized, "unauthorized", "Application is unauthorized")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var newAuth Author
|
|
||||||
err = json.NewDecoder(r.Body).Decode(&newAuth)
|
|
||||||
r.Body.Close()
|
|
||||||
if err != nil {
|
|
||||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Invalid request")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
for i := 1; ; i++ {
|
|
||||||
newID := strings.ReplaceAll(newAuth.Name, " ", "-")
|
|
||||||
if i != 1 {
|
|
||||||
newID += strconv.Itoa(i)
|
|
||||||
}
|
|
||||||
collisionCheck := b.authCol.FindOne(r.Context(), bson.M{"name": newAuth.Name})
|
|
||||||
if collisionCheck.Err() == mongo.ErrNoDocuments {
|
|
||||||
newAuth.ID = newID
|
|
||||||
break
|
|
||||||
} else if collisionCheck.Err() != nil {
|
|
||||||
log.Println("error checking for new author ID collisions:", err)
|
|
||||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_, err = b.authCol.InsertOne(r.Context(), newAuth)
|
|
||||||
if err != nil {
|
|
||||||
log.Println("error inserting new author:", err)
|
|
||||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) updateAuthorInfo(w http.ResponseWriter, r *http.Request) {
|
|
||||||
hdr, err := b.back.VerifyHeader(w, r, "blogManagement", false)
|
|
||||||
if hdr == nil {
|
|
||||||
if err != nil {
|
|
||||||
log.Println("request key parsing error:", err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
} else if hdr.Key.AppID != "blog" {
|
|
||||||
backend.ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application is unauthorized")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if hdr.User == nil || hdr.User.Perm["blog"] != "admin" {
|
|
||||||
backend.ReturnError(w, http.StatusUnauthorized, "unauthorized", "Application is unauthorized")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var rawUpd map[string]string
|
|
||||||
err = json.NewDecoder(r.Body).Decode(&rawUpd)
|
|
||||||
r.Body.Close()
|
|
||||||
if err != nil {
|
|
||||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Invalid request")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
actlUpd := make(map[string]string)
|
|
||||||
if rawUpd["name"] != "" {
|
|
||||||
actlUpd["name"] = rawUpd["name"]
|
|
||||||
}
|
|
||||||
if rawUpd["about"] != "" {
|
|
||||||
actlUpd["about"] = rawUpd["about"]
|
|
||||||
}
|
|
||||||
if rawUpd["picurl"] != "" {
|
|
||||||
actlUpd["picurl"] = rawUpd["picurl"]
|
|
||||||
}
|
|
||||||
res, err := b.authCol.UpdateByID(r.Context(), r.PathValue("authorID"), actlUpd)
|
|
||||||
if err != nil {
|
|
||||||
if err == mongo.ErrNoDocuments {
|
|
||||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Blog with ID "+r.PathValue("blogID")+" not found")
|
|
||||||
} else {
|
|
||||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if res.MatchedCount == 0 {
|
|
||||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Blog with ID "+r.PathValue("blogID")+" not found")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
package blog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"go.mongodb.org/mongo-driver/bson"
|
||||||
|
"go.mongodb.org/mongo-driver/mongo/options"
|
||||||
|
)
|
||||||
|
|
||||||
|
type BlogList struct {
|
||||||
|
ID string `json:"id" bson:"_id"`
|
||||||
|
Title string `json:"title" bson:"title"`
|
||||||
|
Draft bool `json:"draft" bson:"draft"`
|
||||||
|
CreateTime int64 `json:"createTime" bson:"createTime"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Backend) FullBlogList(ctx context.Context) ([]BlogList, error) {
|
||||||
|
res, err := b.blogCol.Find(ctx, bson.M{}, options.Find().
|
||||||
|
SetProjection(bson.M{"_id": 1, "createTime": 1, "title": 1, "draft": 1}).
|
||||||
|
SetSort(bson.M{"createTime": -1}))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var list []BlogList
|
||||||
|
err = res.All(ctx, &list)
|
||||||
|
return list, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Backend) BlogList(ctx context.Context) ([]BlogList, error) {
|
||||||
|
res, err := b.blogCol.Find(ctx, bson.M{
|
||||||
|
"draft": false,
|
||||||
|
"staticPage": false,
|
||||||
|
}, options.Find().
|
||||||
|
SetProjection(bson.M{"_id": 1, "createTime": 1, "title": 1, "draft": 1}).
|
||||||
|
SetSort(bson.M{"createTime": -1}))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var list []BlogList
|
||||||
|
err = res.All(ctx, &list)
|
||||||
|
return list, err
|
||||||
|
}
|
||||||
+169
-331
@@ -1,26 +1,15 @@
|
|||||||
package blog
|
package blog
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"go.mongodb.org/mongo-driver/bson"
|
"go.mongodb.org/mongo-driver/bson"
|
||||||
"go.mongodb.org/mongo-driver/mongo"
|
"go.mongodb.org/mongo-driver/mongo"
|
||||||
"go.mongodb.org/mongo-driver/mongo/options"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
blogTitle = "<h1 class='blog-title'><a hx-push-url='true' hx-get='/%v' hx-target='#content' href='/%v' style='text-decoration:none'>%v</a></h1>"
|
|
||||||
blogAuthor = "<h4 class='blog-author'><i><b>By %v</b></i></h4>"
|
|
||||||
blogCreate = "<h5 class='blog-time'><i>Written on: %v</i></h5>"
|
|
||||||
blogMain = "<div class='blog'>%v</div>"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Blog struct {
|
type Blog struct {
|
||||||
@@ -36,352 +25,201 @@ type Blog struct {
|
|||||||
UpdateTime int64 `json:"updateTime" bson:"updateTime"`
|
UpdateTime int64 `json:"updateTime" bson:"updateTime"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Blog) HTMX(blogApp *BlogApp, ctx context.Context) string {
|
func (b *Backend) GetBlog(ctx context.Context, ID string, allowDraft bool) (Blog, error) {
|
||||||
if b.StaticPage {
|
filter := bson.M{"_id": ID}
|
||||||
return b.RawBlog
|
if !allowDraft {
|
||||||
|
filter["draft"] = false
|
||||||
}
|
}
|
||||||
out := fmt.Sprintf(blogTitle, b.ID, b.ID, b.Title)
|
res := b.blogCol.FindOne(ctx, filter)
|
||||||
auth, err := blogApp.GetAuthor(ctx, b)
|
|
||||||
if err == nil {
|
|
||||||
out += fmt.Sprintf(blogAuthor, auth.Name)
|
|
||||||
} else {
|
|
||||||
out += fmt.Sprintf(blogAuthor, "unknown")
|
|
||||||
}
|
|
||||||
cTime := time.Unix(b.CreateTime, 0).Format(time.DateOnly)
|
|
||||||
if b.UpdateTime > b.CreateTime {
|
|
||||||
out += fmt.Sprintf(blogCreate, cTime+"; Last updated on: "+time.Unix(b.UpdateTime, 0).Format(time.DateOnly))
|
|
||||||
} else {
|
|
||||||
out += fmt.Sprintf(blogCreate, cTime)
|
|
||||||
}
|
|
||||||
out += fmt.Sprintf(blogMain, b.HTMLBlog)
|
|
||||||
if err == nil {
|
|
||||||
out += "<h2 class='blog-author-info'>About the author:</h2>" + auth.HTML()
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) ConvertBlog(blog *Blog) {
|
|
||||||
if !blog.StaticPage {
|
|
||||||
blog.HTMLBlog = b.conv.HTMLConvert(blog.RawBlog)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) GetAuthor(ctx context.Context, blog *Blog) (*Author, error) {
|
|
||||||
res := b.authCol.FindOne(ctx, bson.M{"_id": blog.Author})
|
|
||||||
if res.Err() != nil {
|
if res.Err() != nil {
|
||||||
if res.Err() == mongo.ErrNoDocuments {
|
return Blog{}, res.Err()
|
||||||
return nil, backend.ErrNotFound
|
|
||||||
}
|
|
||||||
return nil, res.Err()
|
|
||||||
}
|
}
|
||||||
var author Author
|
var out Blog
|
||||||
err := res.Decode(&author)
|
err := res.Decode(&out)
|
||||||
return &author, err
|
return out, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *BlogApp) Blog(ctx context.Context, ID string) (*Blog, error) {
|
func (b *Backend) postBlogReq(w http.ResponseWriter, r *http.Request) {
|
||||||
b.cacheMutex.RLock()
|
usr := b.verifyEditorCookie(r)
|
||||||
blog, has := b.blogCache[ID]
|
if usr == nil {
|
||||||
b.cacheMutex.RUnlock()
|
redirect(w, r, "/login")
|
||||||
if has {
|
|
||||||
return &blog, nil
|
|
||||||
}
|
|
||||||
res := b.blogCol.FindOne(ctx, bson.M{"_id": ID, "draft": false})
|
|
||||||
if res.Err() != nil {
|
|
||||||
if res.Err() == mongo.ErrNoDocuments {
|
|
||||||
return nil, backend.ErrNotFound
|
|
||||||
}
|
|
||||||
return nil, res.Err()
|
|
||||||
}
|
|
||||||
err := res.Decode(&blog)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
b.ConvertBlog(&blog)
|
|
||||||
b.cacheMutex.Lock()
|
|
||||||
b.blogCache[ID] = blog
|
|
||||||
b.cacheMutex.Unlock()
|
|
||||||
go b.CleanCache(ID)
|
|
||||||
return &blog, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) AnyBlog(ctx context.Context, ID string) (*Blog, error) {
|
|
||||||
res := b.blogCol.FindOne(ctx, bson.M{"_id": ID})
|
|
||||||
if res.Err() != nil {
|
|
||||||
if res.Err() == mongo.ErrNoDocuments {
|
|
||||||
return nil, backend.ErrNotFound
|
|
||||||
}
|
|
||||||
return nil, res.Err()
|
|
||||||
}
|
|
||||||
var blog Blog
|
|
||||||
err := res.Decode(&blog)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
b.ConvertBlog(&blog)
|
|
||||||
return &blog, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) Contains(ctx context.Context, ID string) bool {
|
|
||||||
res := b.blogCol.FindOne(ctx, bson.M{"_id": ID})
|
|
||||||
return res.Err() == nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) CleanCache(ID string) {
|
|
||||||
time.Sleep(5 * time.Minute)
|
|
||||||
b.cacheMutex.Lock()
|
|
||||||
delete(b.blogCache, ID)
|
|
||||||
b.cacheMutex.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) reqBlog(w http.ResponseWriter, r *http.Request) {
|
|
||||||
blogID := r.PathValue("blogID")
|
|
||||||
if blogID == "" {
|
|
||||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Must provide a blogID")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
blog, err := b.Blog(r.Context(), blogID)
|
if usr.Perm["blog"] != "admin" && usr.Perm["blog"] != "writer" {
|
||||||
|
w.Write([]byte("<p>Sorry, but you aren't authorized to do this action.</p>"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err := r.ParseForm()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == backend.ErrNotFound {
|
w.Write([]byte("<p>Error decoding form</p>"))
|
||||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Not blog found with the given ID")
|
return
|
||||||
|
}
|
||||||
|
newBlog := Blog{
|
||||||
|
ID: r.FormValue("id"),
|
||||||
|
Title: r.FormValue("title"),
|
||||||
|
RawBlog: r.FormValue("blog"),
|
||||||
|
StaticPage: r.FormValue("staticPage") == "on",
|
||||||
|
Draft: r.FormValue("draft") == "on",
|
||||||
|
UpdateTime: time.Now().Unix(),
|
||||||
|
}
|
||||||
|
if newBlog.Title == "" || newBlog.RawBlog == "" {
|
||||||
|
w.Write([]byte("<p>Title and blog contents are required</p>"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if newBlog.ID == "" {
|
||||||
|
newBlog.ID = strings.ToLower(strings.ReplaceAll(newBlog.Title, " ", "-"))
|
||||||
|
newBlog.CreateTime = newBlog.UpdateTime
|
||||||
|
newBlog.Author = usr.Username
|
||||||
|
_, err = b.blogCol.InsertOne(r.Context(), newBlog)
|
||||||
|
if mongo.IsDuplicateKeyError(err) {
|
||||||
|
w.Write([]byte("<p>Title already exists</p>"))
|
||||||
|
return
|
||||||
|
} else if err != nil {
|
||||||
|
log.Println("error inserting document")
|
||||||
|
w.Write([]byte("<p>Server error inserting document</p>"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
log.Println("error getting blog:", err)
|
b.blogSuccessFullPageReplace(r.Context(), w, newBlog)
|
||||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server error")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if r.Header.Get("Hx-Request") == "true" {
|
res := b.blogCol.FindOne(r.Context(), bson.M{"_id": newBlog.ID})
|
||||||
w.Write([]byte(blog.HTMX(b, r.Context())))
|
if res.Err() == mongo.ErrNoDocuments {
|
||||||
|
w.Write([]byte("<p>Error finding old document</p>"))
|
||||||
|
return
|
||||||
|
} else if res.Err() != nil {
|
||||||
|
log.Println("error getting old blog for update:", res.Err())
|
||||||
|
w.Write([]byte("<p>Server error!</p>"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var oldBlog Blog
|
||||||
|
err = res.Decode(&oldBlog)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("error decoding old blog for update:", res.Err())
|
||||||
|
w.Write([]byte("<p>Server error!</p>"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
newBlog.CreateTime = oldBlog.CreateTime
|
||||||
|
if oldBlog.Title != newBlog.Title {
|
||||||
|
res = b.blogCol.FindOne(r.Context(), bson.M{"_id": strings.ToLower(strings.ReplaceAll(newBlog.Title, " ", "-"))})
|
||||||
|
if res.Err() == nil {
|
||||||
|
w.Write([]byte("<p>Title already exists</p>"))
|
||||||
|
return
|
||||||
|
} else if res.Err() != mongo.ErrNoDocuments {
|
||||||
|
log.Println("error checking for title existance:", res.Err())
|
||||||
|
w.Write([]byte("<p>Server error!</p>"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
res = b.blogCol.FindOneAndDelete(r.Context(), bson.M{"_id": oldBlog.ID})
|
||||||
|
if res.Err() != nil {
|
||||||
|
log.Println("error deleting old blog:", res.Err())
|
||||||
|
w.Write([]byte("<p>Server error!</p>"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
newBlog.ID = strings.ToLower(strings.ReplaceAll(newBlog.Title, " ", "-"))
|
||||||
|
_, err = b.blogCol.InsertOne(r.Context(), newBlog)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("error inserting document")
|
||||||
|
w.Write([]byte("<p>Server error inserting document</p>"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
b.blogSuccessFullPageReplace(r.Context(), w, newBlog)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, err = b.blogCol.UpdateByID(r.Context(), newBlog.ID, bson.M{
|
||||||
|
"updateTime": newBlog.UpdateTime,
|
||||||
|
"blog": newBlog.RawBlog,
|
||||||
|
"staticPage": newBlog.StaticPage,
|
||||||
|
"draft": newBlog.Draft,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Println("error updating blog:", err)
|
||||||
|
w.Write([]byte("<p>Server error inserting document</p>"))
|
||||||
} else {
|
} else {
|
||||||
json.NewEncoder(w).Encode(blog)
|
w.Write([]byte("<p>Successfully updated</p>"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *BlogApp) createBlog(w http.ResponseWriter, r *http.Request) {
|
func (b *Backend) blogSuccessFullPageReplace(ctx context.Context, w http.ResponseWriter, blog Blog) {
|
||||||
hdr, err := b.back.VerifyHeader(w, r, "blogManagement", false)
|
form, err := b.BlogEditForm(blog)
|
||||||
if hdr == nil {
|
if err != nil {
|
||||||
|
log.Println("error with blogForm template:", err)
|
||||||
|
w.Write([]byte("<p>Success, but error reloading page</p>"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out, err := b.BlogEditPage(ctx, blog.ID, form)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("error with getting blog list:", err)
|
||||||
|
w.Write([]byte("<p>Success, but error reloading page</p>"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Hx-Retarget", "#editPage")
|
||||||
|
w.Write([]byte(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Backend) BlogEditForm(blog Blog) (string, error) {
|
||||||
|
form := new(bytes.Buffer)
|
||||||
|
err := b.tmpl.ExecuteTemplate(form, "blogForm", blogFormStruct{
|
||||||
|
Blog: blog,
|
||||||
|
Result: "<p>Success!!</p>",
|
||||||
|
})
|
||||||
|
return form.String(), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Backend) blogFormReq(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Header.Get("Hx-Request") != "true" {
|
||||||
|
redirect(w, r, "/editor")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
blogID := r.URL.Query().Get("blog")
|
||||||
|
var blog Blog
|
||||||
|
if blogID != "" {
|
||||||
|
var err error
|
||||||
|
blog, err = b.GetBlog(r.Context(), blogID, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("request key parsing error:", err)
|
log.Println("error getting blog:", err)
|
||||||
}
|
w.Write([]byte("<p>Server error!</p>"))
|
||||||
return
|
return
|
||||||
} else if hdr.Key.AppID != "blog" {
|
|
||||||
backend.ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application is unauthorized")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if hdr.User == nil || hdr.User.Perm["blog"] != "admin" {
|
|
||||||
backend.ReturnError(w, http.StatusUnauthorized, "unauthorized", "Application is unauthorized")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var newBlog Blog
|
|
||||||
err = json.NewDecoder(r.Body).Decode(&newBlog)
|
|
||||||
r.Body.Close()
|
|
||||||
if err != nil {
|
|
||||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Bad request")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
id, err := uuid.NewV7()
|
|
||||||
if err != nil {
|
|
||||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
tim := time.Now().Unix()
|
|
||||||
newBlog.ID = id.String()
|
|
||||||
newBlog.CreateTime = tim
|
|
||||||
newBlog.UpdateTime = tim
|
|
||||||
newBlog.Author = hdr.User.Username
|
|
||||||
_, err = b.blogCol.InsertOne(r.Context(), newBlog)
|
|
||||||
if err != nil {
|
|
||||||
log.Println("error when inserting new blog:", err)
|
|
||||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) updateBlog(w http.ResponseWriter, r *http.Request) {
|
|
||||||
hdr, err := b.back.VerifyHeader(w, r, "blogManagement", false)
|
|
||||||
if hdr == nil {
|
|
||||||
if err != nil {
|
|
||||||
log.Println("request key parsing error:", err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
} else if hdr.Key.AppID != "blog" {
|
|
||||||
backend.ReturnError(w, http.StatusUnauthorized, "invalidKey", "Application is unauthorized")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if hdr.User == nil || hdr.User.Perm["blog"] != "admin" {
|
|
||||||
backend.ReturnError(w, http.StatusUnauthorized, "unauthorized", "Application is unauthorized")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if r.PathValue("blogID") == "" {
|
|
||||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Bad request")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
var reqUpdRaw map[string]string
|
|
||||||
err = json.NewDecoder(r.Body).Decode(&reqUpdRaw)
|
|
||||||
r.Body.Close()
|
|
||||||
if err != nil {
|
|
||||||
backend.ReturnError(w, http.StatusBadRequest, "badRequest", "Bad request")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
reqUpd := bson.M{}
|
|
||||||
if fav, ok := reqUpdRaw["favicon"]; ok && fav != "" {
|
|
||||||
reqUpd["favicon"] = fav
|
|
||||||
}
|
|
||||||
if titl, ok := reqUpdRaw["title"]; ok && titl != "" {
|
|
||||||
reqUpd["title"] = titl
|
|
||||||
}
|
|
||||||
if blog, ok := reqUpdRaw["blog"]; ok && blog != "" {
|
|
||||||
reqUpd["blog"] = blog
|
|
||||||
}
|
|
||||||
reqUpd["updateTime"] = time.Now().Unix()
|
|
||||||
res, err := b.blogCol.UpdateByID(r.Context(), r.PathValue("blogID"), reqUpd)
|
|
||||||
if err != nil {
|
|
||||||
if err == mongo.ErrNoDocuments {
|
|
||||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Blog with ID "+r.PathValue("blogID")+" not found")
|
|
||||||
} else {
|
|
||||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if res.MatchedCount == 0 {
|
|
||||||
backend.ReturnError(w, http.StatusNotFound, "notFound", "Blog with ID "+r.PathValue("blogID")+" not found")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) InsertBlog(ctx context.Context, blog Blog) error {
|
|
||||||
_, err := b.blogCol.InsertOne(ctx, blog)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) UpdateBlog(ctx context.Context, ID string, updates bson.M) error {
|
|
||||||
_, err := b.blogCol.UpdateByID(ctx, ID, bson.M{"$set": updates})
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) LatestBlogs(ctx context.Context, page int64) ([]*Blog, error) {
|
|
||||||
res, err := b.blogCol.Find(ctx, bson.M{"staticPage": false, "draft": false}, options.Find().
|
|
||||||
SetSort(bson.M{"createTime": -1}).
|
|
||||||
SetLimit(5).
|
|
||||||
SetSkip(page*5))
|
|
||||||
if err != nil {
|
|
||||||
if err == mongo.ErrNoDocuments {
|
|
||||||
return nil, backend.ErrNotFound
|
|
||||||
}
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var out []*Blog
|
|
||||||
err = res.All(ctx, &out)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
for i := range out {
|
|
||||||
b.ConvertBlog(out[i])
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) reqLatestBlogs(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var page int
|
|
||||||
var err error
|
|
||||||
pagQuery := r.URL.Query().Get("page")
|
|
||||||
if pagQuery != "" {
|
|
||||||
page, err = strconv.Atoi(pagQuery)
|
|
||||||
if err != nil {
|
|
||||||
page = 0
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
blogs, err := b.LatestBlogs(r.Context(), int64(page))
|
form, err := b.BlogEditForm(blog)
|
||||||
if err != nil && err != backend.ErrNotFound {
|
if err != nil {
|
||||||
log.Println("error getting latest blogs:", err)
|
log.Println("error using blogForm template:", err)
|
||||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "internal error")
|
w.Write([]byte("<p>Server error!</p>"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var ret struct {
|
w.Write([]byte(form))
|
||||||
Blogs []*Blog `json:"blogs"`
|
|
||||||
Num int `json:"num"`
|
|
||||||
}
|
|
||||||
ret.Num = len(blogs)
|
|
||||||
ret.Blogs = blogs
|
|
||||||
json.NewEncoder(w).Encode(ret)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type BlogListResult struct {
|
func (b *Backend) BlogEditPage(ctx context.Context, selectedID, editor string) (string, error) {
|
||||||
ID string `json:"id" bson:"_id"`
|
blogs, err := b.FullBlogList(ctx)
|
||||||
Title string `json:"title" bson:"title"`
|
|
||||||
CreateTime int `json:"createTime" bson:"createTime"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b BlogListResult) HTMX() string {
|
|
||||||
return "<a class='blog-list-item' href='https://darkstorm.tech/" +
|
|
||||||
b.ID +
|
|
||||||
"' hx-push-url='true' hx-target='#content' hx-get='/" +
|
|
||||||
b.ID +
|
|
||||||
"'>" + b.Title + "</a>"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) BlogList(ctx context.Context, page int64) ([]BlogListResult, error) {
|
|
||||||
res, err := b.blogCol.Find(ctx, bson.M{"staticPage": false, "draft": false}, options.Find().
|
|
||||||
SetProjection(bson.M{"_id": 1, "createTime": 1, "title": 1}).
|
|
||||||
SetSort(bson.M{"createTime": -1}).
|
|
||||||
SetLimit(50).
|
|
||||||
SetSkip(page*50))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == mongo.ErrNoDocuments {
|
return "", err
|
||||||
return nil, backend.ErrNotFound
|
|
||||||
}
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
var out []BlogListResult
|
out := new(bytes.Buffer)
|
||||||
err = res.All(ctx, &out)
|
err = b.tmpl.ExecuteTemplate(out, "blogPage", blogPageStruct{
|
||||||
if err != nil {
|
Selected: selectedID,
|
||||||
return nil, err
|
Editor: editor,
|
||||||
}
|
Blogs: blogs,
|
||||||
return out, nil
|
})
|
||||||
|
return out.String(), err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *BlogApp) AllBlogsList(ctx context.Context) ([]BlogListResult, error) {
|
func (b *Backend) blogPageReq(w http.ResponseWriter, r *http.Request) {
|
||||||
res, err := b.blogCol.Find(ctx, bson.M{}, options.Find().
|
if r.Header.Get("Hx-Request") != "true" {
|
||||||
SetProjection(bson.M{"_id": 1, "createTime": 1, "title": 1}).
|
redirect(w, r, "/editor")
|
||||||
SetSort(bson.M{"createTime": -1}))
|
|
||||||
if err != nil {
|
|
||||||
if err == mongo.ErrNoDocuments {
|
|
||||||
return nil, backend.ErrNotFound
|
|
||||||
}
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var out []BlogListResult
|
|
||||||
err = res.All(ctx, &out)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) reqBlogList(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var page int
|
|
||||||
var err error
|
|
||||||
pagQuery := r.URL.Query().Get("page")
|
|
||||||
if pagQuery != "" {
|
|
||||||
page, err = strconv.Atoi(pagQuery)
|
|
||||||
if err != nil {
|
|
||||||
page = 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
blogList, err := b.BlogList(r.Context(), int64(page))
|
|
||||||
if err != nil && err != backend.ErrNotFound {
|
|
||||||
log.Println("error getting blog list:", err)
|
|
||||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "internal error")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var ret struct {
|
form, err := b.BlogEditForm(Blog{})
|
||||||
BlogList []BlogListResult `json:"blogList"`
|
if err != nil {
|
||||||
Num int `json:"num"`
|
log.Println("error using blogForm template:", err)
|
||||||
|
w.Write([]byte("<p>Server error!</p>"))
|
||||||
|
return
|
||||||
}
|
}
|
||||||
ret.Num = len(blogList)
|
page, err := b.BlogEditPage(r.Context(), "", form)
|
||||||
ret.BlogList = blogList
|
if err != nil {
|
||||||
json.NewEncoder(w).Encode(ret)
|
log.Println("error using blogPage template:", err)
|
||||||
|
w.Write([]byte("<p>Server error!</p>"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Write([]byte(page))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package blog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (b *Backend) editorReq(w http.ResponseWriter, r *http.Request) {
|
||||||
|
blogForm := new(bytes.Buffer)
|
||||||
|
err := b.tmpl.ExecuteTemplate(blogForm, "blogForm", blogFormStruct{
|
||||||
|
Blog: Blog{},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Println("error using blogForm:", err)
|
||||||
|
b.wrapper(w, r, "error", "<p>Server error</p>")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
blogs, err := b.FullBlogList(r.Context())
|
||||||
|
if err != nil {
|
||||||
|
log.Println("error getting blog list:", err)
|
||||||
|
b.wrapper(w, r, "error", "<p>Server error</p>")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
blogPage := new(bytes.Buffer)
|
||||||
|
err = b.tmpl.ExecuteTemplate(blogPage, "blogPage", blogPageStruct{
|
||||||
|
Selected: "",
|
||||||
|
Editor: blogForm.String(),
|
||||||
|
Blogs: blogs,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Println("error using blogPage:", err)
|
||||||
|
b.wrapper(w, r, "error", "<p>Server error</p>")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out := new(bytes.Buffer)
|
||||||
|
err = b.tmpl.ExecuteTemplate(out, "editor", editorStruct{
|
||||||
|
SelectedPage: "",
|
||||||
|
Page: blogPage.String(),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Println("error using editor:", err)
|
||||||
|
b.wrapper(w, r, "error", "<p>Server error</p>")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
b.wrapper(w, r, "Editor", out.String())
|
||||||
|
}
|
||||||
+60
-42
@@ -1,63 +1,81 @@
|
|||||||
package blog
|
package blog
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"sync"
|
"sync"
|
||||||
|
"text/template"
|
||||||
|
|
||||||
"github.com/CalebQ42/bbConvert"
|
|
||||||
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
||||||
"go.mongodb.org/mongo-driver/mongo"
|
"go.mongodb.org/mongo-driver/mongo"
|
||||||
)
|
)
|
||||||
|
|
||||||
type BlogApp struct {
|
type WrapperFunc func(w http.ResponseWriter, r *http.Request, title, content string)
|
||||||
back *backend.Backend
|
|
||||||
blogCol *mongo.Collection
|
|
||||||
authCol *mongo.Collection
|
|
||||||
portfolioCol *mongo.Collection
|
|
||||||
conv bbConvert.ComboConverter
|
|
||||||
|
|
||||||
cacheMutex *sync.RWMutex
|
type Backend struct {
|
||||||
blogCache map[string]Blog
|
blogCol *mongo.Collection
|
||||||
|
authCol *mongo.Collection
|
||||||
|
projCol *mongo.Collection
|
||||||
|
|
||||||
|
tmpl *template.Template
|
||||||
|
wrapper WrapperFunc
|
||||||
|
|
||||||
|
back *backend.Backend
|
||||||
|
|
||||||
|
cacheMutex sync.RWMutex
|
||||||
|
cache map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewBlogApp(db *mongo.Database) *BlogApp {
|
func New(c *mongo.Client, back *backend.Backend, wrapper WrapperFunc) (*Backend, error) {
|
||||||
out := &BlogApp{
|
var b = &Backend{
|
||||||
blogCol: db.Collection("blog"),
|
blogCol: c.Database("blog").Collection("blog"),
|
||||||
authCol: db.Collection("author"),
|
authCol: c.Database("blog").Collection("blog"),
|
||||||
portfolioCol: db.Collection("portfolio"),
|
projCol: c.Database("blog").Collection("blog"),
|
||||||
conv: bbConvert.NewComboConverter(),
|
wrapper: wrapper,
|
||||||
cacheMutex: &sync.RWMutex{},
|
back: back,
|
||||||
blogCache: make(map[string]Blog),
|
cache: make(map[string]string),
|
||||||
}
|
}
|
||||||
return out
|
return b, b.parseTemplates()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *BlogApp) AppID() string {
|
func (b *Backend) RegisterToMux(mux *http.ServeMux) {
|
||||||
return "blog"
|
mux.HandleFunc("GET /editor", b.editorReq)
|
||||||
|
|
||||||
|
mux.HandleFunc("GET /editor/blog", b.blogPageReq)
|
||||||
|
mux.HandleFunc("GET /editor/blog/edit", b.blogFormReq)
|
||||||
|
mux.HandleFunc("POST /editor/blog/post", b.postBlogReq)
|
||||||
|
|
||||||
|
// mux.HandleFunc("GET /editor/portfolio", b.portfolioPageReq)
|
||||||
|
// mux.HandleFunc("GET /editor/portfolio/edit", b.portfolioFormReq)
|
||||||
|
// mux.HandleFunc("POST /editor/portfolio/post", b.postPortfolioReq)
|
||||||
|
|
||||||
|
// mux.HandleFunc("GET /editor/author", b.authorPageReq)
|
||||||
|
// mux.HandleFunc("GET /editor/author/edit", b.authorFormReq)
|
||||||
|
// mux.HandleFunc("POST /editor/author/post", b.postAuthorReq)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *BlogApp) CountTable() backend.CountTable {
|
func (b *Backend) verifyEditorCookie(r *http.Request) *backend.User {
|
||||||
return nil
|
authCookie, err := r.Cookie("blogAuthToken")
|
||||||
|
if err != nil {
|
||||||
|
if err != http.ErrNoCookie {
|
||||||
|
log.Println("error getting auth cookie:", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
usr, err := b.back.VerifyUser(r.Context(), authCookie.Value)
|
||||||
|
if err != nil {
|
||||||
|
if err != backend.ErrTokenUnauthorized {
|
||||||
|
log.Println("error authorizing JWT token:", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return usr
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *BlogApp) CrashTable() backend.CrashTable {
|
func redirect(w http.ResponseWriter, r *http.Request, path string) {
|
||||||
return nil
|
if r.Header.Get("HX-Request") == "true" {
|
||||||
}
|
w.Header().Set("HX-Location", `{"path": "`+path+`", "target":"#content"}`)
|
||||||
|
return
|
||||||
func (b *BlogApp) AddBackend(back *backend.Backend) {
|
}
|
||||||
b.back = back
|
http.Redirect(w, r, "https://darkstorm.tech"+path, http.StatusFound)
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) Extension(mux *http.ServeMux) {
|
|
||||||
mux.HandleFunc("GET /blog", b.reqLatestBlogs)
|
|
||||||
mux.HandleFunc("GET /blog/list", b.reqBlogList)
|
|
||||||
mux.HandleFunc("GET /blog/{blogID}", b.reqBlog)
|
|
||||||
mux.HandleFunc("POST /blog", b.createBlog)
|
|
||||||
mux.HandleFunc("POST /blog/{blogID}", b.updateBlog)
|
|
||||||
|
|
||||||
mux.HandleFunc("GET /blog/author/{authorID}", b.reqAuthorInfo)
|
|
||||||
mux.HandleFunc("POST /blog/author", b.addAuthorInfo)
|
|
||||||
mux.HandleFunc("POST /blog/author/{authorID}", b.updateAuthorInfo)
|
|
||||||
|
|
||||||
mux.HandleFunc("GET /blog/portfolio", b.reqPortfolio)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,26 +1,5 @@
|
|||||||
package blog
|
package blog
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"slices"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/CalebQ42/darkstorm-server/internal/backend"
|
|
||||||
"go.mongodb.org/mongo-driver/bson"
|
|
||||||
"go.mongodb.org/mongo-driver/mongo/options"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
portfolioTitle = "<h2 class='portfolio-title'>%v</h2>"
|
|
||||||
portfolioLink = "<p class='portfolio-link'><a href='%v'>%v</a>"
|
|
||||||
portfolioLanguage = "<p class='portfolio-language'><b>%v</b>: %v</p>"
|
|
||||||
portfolioTech = "<p class='portfolio-tech'><b>Tech: </b>%v</p>"
|
|
||||||
portfolioDesc = "<p class='portfolio-description'>%v</p>"
|
|
||||||
)
|
|
||||||
|
|
||||||
type PortfolioProject struct {
|
type PortfolioProject struct {
|
||||||
Title string `json:"_id" bson:"_id"`
|
Title string `json:"_id" bson:"_id"`
|
||||||
Order int `json:"order" bson:"order"`
|
Order int `json:"order" bson:"order"`
|
||||||
@@ -32,104 +11,3 @@ type PortfolioProject struct {
|
|||||||
Dates string `json:"dates" bson:"dates"`
|
Dates string `json:"dates" bson:"dates"`
|
||||||
} `json:"language" bson:"language"`
|
} `json:"language" bson:"language"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p PortfolioProject) HTMX() string {
|
|
||||||
out := fmt.Sprintf(portfolioTitle, p.Title)
|
|
||||||
out += fmt.Sprintf(portfolioLink, p.Repository, p.Repository)
|
|
||||||
for _, l := range p.Languages {
|
|
||||||
out += fmt.Sprintf(portfolioLanguage, l.Language, l.Dates)
|
|
||||||
}
|
|
||||||
out += fmt.Sprintf(portfolioTech, strings.Join(p.Technologies, ", "))
|
|
||||||
out += fmt.Sprintf(portfolioDesc, p.Description)
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
type Portfolio []PortfolioProject
|
|
||||||
|
|
||||||
const (
|
|
||||||
portfolioSelector = `
|
|
||||||
<p>Tech Filter:
|
|
||||||
<select
|
|
||||||
id='techSelect'
|
|
||||||
name='tech'
|
|
||||||
hx-get='https://api.darkstorm.tech/blog/portfolio'
|
|
||||||
hx-target='#projects'>
|
|
||||||
%v
|
|
||||||
</select>
|
|
||||||
</p>`
|
|
||||||
portfolioSelectorOption = "<option value='%v'%v>%v</option>"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (p Portfolio) FullHTMX(ctx context.Context, blogApp *BlogApp, selectedTech string) string {
|
|
||||||
aboutMe := "<h1 class='about-me-header'>About Me</h1>"
|
|
||||||
if me, err := blogApp.AboutMe(ctx); err != nil {
|
|
||||||
aboutMe += "Error getting info about me :("
|
|
||||||
} else {
|
|
||||||
aboutMe += me.HTML()
|
|
||||||
}
|
|
||||||
aboutMe += "<h1 class='my-projects-header' style='margin-bottom:15px'>My Projects</h1>"
|
|
||||||
tech := make(map[string]struct{})
|
|
||||||
for i := range p {
|
|
||||||
for _, t := range p[i].Technologies {
|
|
||||||
tech[t] = struct{}{}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
techKeys := make([]string, 0, len(tech))
|
|
||||||
for k := range tech {
|
|
||||||
techKeys = append(techKeys, k)
|
|
||||||
}
|
|
||||||
slices.Sort(techKeys)
|
|
||||||
var out string
|
|
||||||
if selectedTech == "" {
|
|
||||||
out = fmt.Sprintf(portfolioSelectorOption, "", " selected=true", "All")
|
|
||||||
} else {
|
|
||||||
out = fmt.Sprintf(portfolioSelectorOption, "", "", "All")
|
|
||||||
}
|
|
||||||
for _, k := range techKeys {
|
|
||||||
if selectedTech == strings.ToLower(k) {
|
|
||||||
out += fmt.Sprintf(portfolioSelectorOption, k, " selected=true", k)
|
|
||||||
} else {
|
|
||||||
out += fmt.Sprintf(portfolioSelectorOption, k, "", k)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return aboutMe + fmt.Sprintf(portfolioSelector, out) + "<div id='projects'>" + p.HTMX() + "</div>"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p Portfolio) HTMX() string {
|
|
||||||
out := ""
|
|
||||||
for _, proj := range p {
|
|
||||||
out += proj.HTMX()
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) Projects(ctx context.Context, techFilter string) (Portfolio, error) {
|
|
||||||
filter := bson.M{}
|
|
||||||
if techFilter != "" {
|
|
||||||
filter = bson.M{"technologies": techFilter}
|
|
||||||
}
|
|
||||||
res, err := b.portfolioCol.Find(ctx, filter, options.Find().SetSort(bson.M{"order": 1}))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var out []PortfolioProject
|
|
||||||
err = res.All(ctx, &out)
|
|
||||||
return out, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *BlogApp) reqPortfolio(w http.ResponseWriter, r *http.Request) {
|
|
||||||
folio, err := b.Projects(r.Context(), r.URL.Query().Get("tech"))
|
|
||||||
if err != nil {
|
|
||||||
backend.ReturnError(w, http.StatusInternalServerError, "internal", "Server Error")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if r.Header.Get("Hx-Request") == "true" {
|
|
||||||
if r.URL.Query().Has("tech") {
|
|
||||||
w.Write([]byte(folio.HTMX()))
|
|
||||||
} else {
|
|
||||||
w.Write([]byte(folio.FullHTMX(r.Context(), b, r.URL.Query().Get("tech"))))
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
json.NewEncoder(w).Encode(folio)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,187 @@
|
|||||||
|
package blog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"text/template"
|
||||||
|
)
|
||||||
|
|
||||||
|
const editor = `
|
||||||
|
<p id="editSelector" hx-target="#editPage" hx-swap="swap:0.5s settle:0.5s" hx-push-url="true">
|
||||||
|
<a href="/editor/blog" hx-get="/editor/blog" class="editSelectorItems{{if (eq .SelectedPage "blogs") | (eq .SelectedPage "")}} editSelectorSelected{{end}}" {{if eq .SelectedPage "blogs"}}{{end}}>Blogs</a>
|
||||||
|
<a href="/editor/portfolio" hx-get="/editor/portfolio" class="editSelectorItems{{if eq .SelectedPage "portfolio"}} editSelectorSelected{{end}}">Portfolio</a>
|
||||||
|
<a href="/editor/author" hx-get="/editor/author" class="editSelectorItems{{if eq .SelectedPage "author"}} editSelectorSelected{{end}}">Author</a>
|
||||||
|
</p>
|
||||||
|
<div id="editPage">{{ .Page }}</div>`
|
||||||
|
|
||||||
|
type editorStruct struct {
|
||||||
|
SelectedPage string
|
||||||
|
Page string
|
||||||
|
}
|
||||||
|
|
||||||
|
const blogPage = `<p>
|
||||||
|
<label for="blog" style="margin-right:10px">Blog:</label>
|
||||||
|
<select id="blogSelect"
|
||||||
|
name='blog'
|
||||||
|
hx-get='/editor/blog/edit'
|
||||||
|
hx-target='#editor'>
|
||||||
|
<option value=''{{if eq .Selected ""}} selected{{end}}>New Blog</option>
|
||||||
|
{{ range $blog := .Blogs }}
|
||||||
|
<option value='{{.ID}}'{{if eq $.Selected .ID}} selected{{end}}>{{.Title}}{{if .Draft}} (Draft){{end}}</option>
|
||||||
|
{{end}}
|
||||||
|
</select>
|
||||||
|
</p>
|
||||||
|
<div id="editor" hx-on::after-settle="editorResize()">{{.Editor}}</div>`
|
||||||
|
|
||||||
|
type blogPageStruct struct {
|
||||||
|
Selected string
|
||||||
|
Editor string
|
||||||
|
Blogs []BlogList
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Add delete
|
||||||
|
const blogForm = `
|
||||||
|
<form id="editorForm" hx-post="/editor/blog/post" hx-target="#formResult" hx-confirm="Save changes, overwritting previous values??">
|
||||||
|
<input name="id" type="hidden" value="{{.Blog.ID}}"></input>
|
||||||
|
<p>
|
||||||
|
<label for="staticPage" style="margin-right:10px">Static Page:</label><input type="checkbox" name="staticPage"{{if .Blog.StaticPage}} checked {{end}}/>
|
||||||
|
<span class="vertical-seperator"></span>
|
||||||
|
<label for="draft" style="margin-right:10px">Draft:</label><input type="checkbox" name="draft"{{if or .Blog.Draft (not .Blog.ID)}} checked {{end}}/>
|
||||||
|
</p>
|
||||||
|
<label for="title">Title</label>
|
||||||
|
<input id="titleInput" name="title" value="{{.Blog.Title}}" type="text" onkeydown="return event.key != 'Enter';"/>
|
||||||
|
<textarea id="textEditor" name="blog" oninput="editorResize()">{{.Blog.RawBlog}}</textarea>
|
||||||
|
<div id="formResult">{{.Result}}</div>
|
||||||
|
<p style="margin-right:0px;">
|
||||||
|
<button class="formButton" type="submit">{{if eq .Blog.ID ""}}Create{{else}}Update{{end}}</button>
|
||||||
|
<button class="formButton"
|
||||||
|
hx-get="/editor/blog/edit"
|
||||||
|
hx-include="#blogSelect"
|
||||||
|
hx-target="#editor"
|
||||||
|
hx-confirm="Undo all your changes??">
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<p>
|
||||||
|
</form>`
|
||||||
|
|
||||||
|
type blogFormStruct struct {
|
||||||
|
Blog Blog
|
||||||
|
Result string
|
||||||
|
}
|
||||||
|
|
||||||
|
const portfolioPage = `<p>
|
||||||
|
<label for="project" style="margin-right:10px">Project:</label>
|
||||||
|
<select id="projectSelect"
|
||||||
|
name='project'
|
||||||
|
hx-get='/editor/portfolio/edit'
|
||||||
|
hx-target='#editor'>
|
||||||
|
<option value=''{{if eq .Selected ""}} selected{{end}}>New Project</option>
|
||||||
|
{{ range $project := .Projects }}
|
||||||
|
<option value='{{.Title}}'{{if eq $.Selected .Title}} selected{{end}}>{{.Title}}</option>
|
||||||
|
{{end}}
|
||||||
|
</select>
|
||||||
|
</p>
|
||||||
|
<div id="editor" hx-on::after-settle="editorResize()">{{.Editor}}</div>`
|
||||||
|
|
||||||
|
type portfolioPageStruct struct {
|
||||||
|
Selected string
|
||||||
|
Editor string
|
||||||
|
Projects []PortfolioProject
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Add Languages to editor
|
||||||
|
const portfolioForm = `<form id="editorForm" hx-post="/editor/portfolio/post" hx-target="#formResult" hx-confirm="Save changes, overwritting previous values??">
|
||||||
|
<input name="origTitle" type="hidden" value="{{.Project.Title}}"></input>
|
||||||
|
<label for="title">Title</label>
|
||||||
|
<input id="titleInput" name="title" value="{{.Project.Title}}" type="text" onkeydown="return event.key != 'Enter';"/>
|
||||||
|
<label for="technologies">Technologies</label>
|
||||||
|
<input id="techInput" name="technologies" value="{{range $ind, $tech := .Project.Technologies}}{{if not (eq $ind 0)}}, {{end}}$tech{{end}}" type="text" onkeydown="return event.key != 'Enter';"/>
|
||||||
|
<textarea id="textEditor" name="description" oninput="editorResize()">{{.Project.Description}}</textarea>
|
||||||
|
<div id="formResult">{{.Result}}</div>
|
||||||
|
<p style="margin-right:0px;">
|
||||||
|
<button class="formButton" type="submit">{{if eq .Project.Title ""}}Create{{else}}Update{{end}}</button>
|
||||||
|
<button class="formButton"
|
||||||
|
hx-get="/editor/portfolio/edit"
|
||||||
|
hx-include="#projectSelect"
|
||||||
|
hx-target="#editor"
|
||||||
|
hx-confirm="Undo all your changes??">
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<p>
|
||||||
|
</form>`
|
||||||
|
|
||||||
|
type portfolioFormStruct struct {
|
||||||
|
Project PortfolioProject
|
||||||
|
Result string
|
||||||
|
}
|
||||||
|
|
||||||
|
const authorPage = `<p>
|
||||||
|
<label for="author" style="margin-right:10px">Author:</label>
|
||||||
|
<select id="authorSelect"
|
||||||
|
name='author'
|
||||||
|
hx-get='/editor/author/edit'
|
||||||
|
hx-target='#editor'>
|
||||||
|
<option value=''{{if eq .Selected ""}} selected{{end}}>New Author</option>
|
||||||
|
{{ range $author := .Authors }}
|
||||||
|
<option value='{{.ID}}'{{if eq $.Selected .ID}} selected{{end}}>{{.Name}}</option>
|
||||||
|
{{end}}
|
||||||
|
</select>
|
||||||
|
</p>
|
||||||
|
<div id="editor" hx-on::after-settle="editorResize()">{{.Editor}}</div>`
|
||||||
|
|
||||||
|
type authorPageStruct struct {
|
||||||
|
Selected string
|
||||||
|
Editor string
|
||||||
|
Authors []Author
|
||||||
|
}
|
||||||
|
|
||||||
|
const authorForm = `<form id="editorForm" hx-post="/editor/author/post" hx-target="#formResult" hx-confirm="Save changes, overwritting previous values??">
|
||||||
|
<input name="id" type="hidden" value="{{.Author.ID}}"></input>
|
||||||
|
<label for="name">Name</label>
|
||||||
|
<input id="nameInput" name="name" value="{{.Author.Name}}" type="text" onkeydown="return event.key != 'Enter';"/>
|
||||||
|
<textarea id="textEditor" name="about" oninput="editorResize()">{{.Author.About}}</textarea>
|
||||||
|
<div id="formResult">{{.Result}}</div>
|
||||||
|
<p style="margin-right:0px;">
|
||||||
|
<button class="formButton" type="submit">{{if eq .Author.ID ""}}Create{{else}}Update{{end}}</button>
|
||||||
|
<button class="formButton"
|
||||||
|
hx-get="/editor/author/edit"
|
||||||
|
hx-include="#projectSelect"
|
||||||
|
hx-target="#editor"
|
||||||
|
hx-confirm="Undo all your changes??">
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<p>
|
||||||
|
</form>`
|
||||||
|
|
||||||
|
type authorFormStruct struct {
|
||||||
|
Author Author
|
||||||
|
Result string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Backend) parseTemplates() error {
|
||||||
|
var err error
|
||||||
|
b.tmpl, err = template.New("editor").Parse(editor)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
b.tmpl, err = template.New("blogPage").Parse(blogPage)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
b.tmpl, err = template.New("blogForm").Parse(blogForm)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
b.tmpl, err = template.New("portfolioPage").Parse(portfolioPage)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
b.tmpl, err = template.New("portfolioForm").Parse(portfolioForm)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
b.tmpl, err = template.New("authorPage").Parse(authorPage)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
b.tmpl, err = template.New("authorForm").Parse(authorForm)
|
||||||
|
return err
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user