mirror of https://github.com/jlelse/GoBlog
Some improvements
This commit is contained in:
parent
d6518c3a5d
commit
d953b331c4
27
blogroll.go
27
blogroll.go
|
@ -2,13 +2,14 @@ package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"fmt"
|
"context"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/carlmjohnson/requests"
|
||||||
"github.com/kaorimatz/go-opml"
|
"github.com/kaorimatz/go-opml"
|
||||||
"github.com/thoas/go-funk"
|
"github.com/thoas/go-funk"
|
||||||
"go.goblog.app/app/pkgs/contenttype"
|
"go.goblog.app/app/pkgs/contenttype"
|
||||||
|
@ -64,22 +65,16 @@ func (a *goBlog) getBlogrollOutlines(blog string) ([]*opml.Outline, error) {
|
||||||
if cache := a.db.loadOutlineCache(blog); cache != nil {
|
if cache := a.db.loadOutlineCache(blog); cache != nil {
|
||||||
return cache, nil
|
return cache, nil
|
||||||
}
|
}
|
||||||
req, err := http.NewRequest(http.MethodGet, config.Opml, nil)
|
rb := requests.URL(config.Opml).Client(a.httpClient).UserAgent(appUserAgent)
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if config.AuthHeader != "" && config.AuthValue != "" {
|
if config.AuthHeader != "" && config.AuthValue != "" {
|
||||||
req.Header.Set(config.AuthHeader, config.AuthValue)
|
rb.Header(config.AuthHeader, config.AuthValue)
|
||||||
}
|
}
|
||||||
res, err := a.httpClient.Do(req)
|
var o *opml.OPML
|
||||||
if err != nil {
|
err := rb.Handle(func(r *http.Response) (err error) {
|
||||||
return nil, err
|
defer r.Body.Close()
|
||||||
}
|
o, err = opml.Parse(r.Body)
|
||||||
defer res.Body.Close()
|
return
|
||||||
if code := res.StatusCode; code < 200 || 300 <= code {
|
}).Fetch(context.Background())
|
||||||
return nil, fmt.Errorf("opml request not successful, status code: %d", code)
|
|
||||||
}
|
|
||||||
o, err := opml.Parse(res.Body)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
@ -117,7 +112,7 @@ func (db *database) loadOutlineCache(blog string) []*opml.Outline {
|
||||||
if err != nil || data == nil {
|
if err != nil || data == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
o, err := opml.NewParser(bytes.NewReader(data)).Parse()
|
o, err := opml.Parse(bytes.NewReader(data))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,9 +1,11 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/carlmjohnson/requests"
|
||||||
"github.com/mmcdole/gofeed"
|
"github.com/mmcdole/gofeed"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
|
@ -17,6 +19,7 @@ func Test_feeds(t *testing.T) {
|
||||||
_ = app.initDatabase(false)
|
_ = app.initDatabase(false)
|
||||||
app.initComponents(false)
|
app.initComponents(false)
|
||||||
app.d, _ = app.buildRouter()
|
app.d, _ = app.buildRouter()
|
||||||
|
handlerClient := newHandlerClient(app.d)
|
||||||
|
|
||||||
err := app.createPost(&post{
|
err := app.createPost(&post{
|
||||||
Path: "/testpost",
|
Path: "/testpost",
|
||||||
|
@ -26,21 +29,18 @@ func Test_feeds(t *testing.T) {
|
||||||
Parameters: map[string][]string{"title": {"Test Post"}},
|
Parameters: map[string][]string{"title": {"Test Post"}},
|
||||||
Content: "Test Content",
|
Content: "Test Content",
|
||||||
})
|
})
|
||||||
|
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
for _, typ := range []feedType{rssFeed, atomFeed, jsonFeed} {
|
for _, typ := range []feedType{rssFeed, atomFeed, jsonFeed} {
|
||||||
req, _ := http.NewRequest(http.MethodGet, "http://localhost:8080/posts."+string(typ), nil)
|
var feed *gofeed.Feed
|
||||||
res, err := doHandlerRequest(req, app.d)
|
err := requests.URL("http://localhost:8080/posts." + string(typ)).Client(handlerClient).
|
||||||
|
Handle(func(r *http.Response) (err error) {
|
||||||
require.NoError(t, err)
|
fp := gofeed.NewParser()
|
||||||
|
defer r.Body.Close()
|
||||||
require.Equal(t, http.StatusOK, res.StatusCode)
|
feed, err = fp.Parse(r.Body)
|
||||||
|
return
|
||||||
fp := gofeed.NewParser()
|
}).
|
||||||
feed, err := fp.Parse(res.Body)
|
Fetch(context.Background())
|
||||||
_ = res.Body.Close()
|
|
||||||
|
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
require.NotNil(t, feed)
|
require.NotNil(t, feed)
|
||||||
|
|
||||||
|
|
36
geo.go
36
geo.go
|
@ -1,14 +1,14 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
"embed"
|
"embed"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
gogeouri "git.jlel.se/jlelse/go-geouri"
|
gogeouri "git.jlel.se/jlelse/go-geouri"
|
||||||
|
"github.com/carlmjohnson/requests"
|
||||||
geojson "github.com/paulmach/go.geojson"
|
geojson "github.com/paulmach/go.geojson"
|
||||||
"github.com/thoas/go-funk"
|
"github.com/thoas/go-funk"
|
||||||
)
|
)
|
||||||
|
@ -39,33 +39,19 @@ func (a *goBlog) photonReverse(lat, lon float64, lang string) ([]byte, error) {
|
||||||
if cache != nil {
|
if cache != nil {
|
||||||
return cache, nil
|
return cache, nil
|
||||||
}
|
}
|
||||||
uv := url.Values{}
|
var buf bytes.Buffer
|
||||||
uv.Set("lat", fmt.Sprintf("%v", lat))
|
rb := requests.URL("https://photon.komoot.io/reverse").Client(a.httpClient).UserAgent(appUserAgent).ToBytesBuffer(&buf)
|
||||||
uv.Set("lon", fmt.Sprintf("%v", lon))
|
rb.Param("lat", fmt.Sprintf("%v", lat)).Param("lon", fmt.Sprintf("%v", lon))
|
||||||
if lang == "de" || lang == "fr" || lang == "it" {
|
if lang == "de" || lang == "fr" || lang == "it" {
|
||||||
uv.Set("lang", lang)
|
rb.Param("lang", lang)
|
||||||
} else {
|
} else {
|
||||||
uv.Set("lang", "en")
|
rb.Param("lang", "en")
|
||||||
}
|
}
|
||||||
req, err := http.NewRequest(http.MethodGet, "https://photon.komoot.io/reverse?"+uv.Encode(), nil)
|
if err := rb.Fetch(context.Background()); err != nil {
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
req.Header.Set(userAgent, appUserAgent)
|
_ = a.db.cachePersistently(cacheKey, buf.Bytes())
|
||||||
resp, err := a.httpClient.Do(req)
|
return buf.Bytes(), nil
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
return nil, fmt.Errorf("response status code: %v", resp.StatusCode)
|
|
||||||
}
|
|
||||||
ba, err := io.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
_ = a.db.cachePersistently(cacheKey, ba)
|
|
||||||
return ba, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func geoOSMLink(g *gogeouri.Geo) string {
|
func geoOSMLink(g *gogeouri.Geo) string {
|
||||||
|
|
|
@ -15,25 +15,21 @@ type fakeHttpClient struct {
|
||||||
|
|
||||||
func newFakeHttpClient() *fakeHttpClient {
|
func newFakeHttpClient() *fakeHttpClient {
|
||||||
fc := &fakeHttpClient{}
|
fc := &fakeHttpClient{}
|
||||||
fc.Client = &http.Client{
|
fc.Client = newHandlerClient(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
||||||
Transport: &handlerRoundTripper{
|
fc.req = r
|
||||||
handler: http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
|
if fc.handler != nil {
|
||||||
fc.req = r
|
rec := httptest.NewRecorder()
|
||||||
if fc.handler != nil {
|
fc.handler.ServeHTTP(rec, r)
|
||||||
rec := httptest.NewRecorder()
|
fc.res = rec.Result()
|
||||||
fc.handler.ServeHTTP(rec, r)
|
// Copy the headers from the response recorder
|
||||||
fc.res = rec.Result()
|
for k, v := range rec.Header() {
|
||||||
// Copy the headers from the response recorder
|
rw.Header()[k] = v
|
||||||
for k, v := range rec.Header() {
|
}
|
||||||
rw.Header()[k] = v
|
// Copy result status code and body
|
||||||
}
|
rw.WriteHeader(fc.res.StatusCode)
|
||||||
// Copy result status code and body
|
_, _ = io.Copy(rw, rec.Body)
|
||||||
rw.WriteHeader(fc.res.StatusCode)
|
}
|
||||||
_, _ = io.Copy(rw, rec.Body)
|
}))
|
||||||
}
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
return fc
|
return fc
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -51,24 +51,14 @@ func Test_indieAuthServer(t *testing.T) {
|
||||||
_ = app.initDatabase(false)
|
_ = app.initDatabase(false)
|
||||||
app.initComponents(false)
|
app.initComponents(false)
|
||||||
|
|
||||||
app.ias.Client = &http.Client{
|
app.ias.Client = newHandlerClient(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
Transport: &handlerRoundTripper{
|
w.WriteHeader(http.StatusOK)
|
||||||
handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
}))
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
iac := indieauth.NewClient(
|
iac := indieauth.NewClient(
|
||||||
"https://example.com/",
|
"https://example.com/",
|
||||||
"https://example.com/redirect",
|
"https://example.com/redirect",
|
||||||
&http.Client{
|
newHandlerClient(app.d),
|
||||||
Transport: &handlerRoundTripper{
|
|
||||||
handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
app.d.ServeHTTP(w, r)
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
require.NotNil(t, iac)
|
require.NotNil(t, iac)
|
||||||
|
|
||||||
|
|
|
@ -90,13 +90,14 @@ type tinify struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (tf *tinify) compress(url string, upload mediaStorageSaveFunc, hc *http.Client) (string, error) {
|
func (tf *tinify) compress(url string, upload mediaStorageSaveFunc, hc *http.Client) (string, error) {
|
||||||
|
tinifyErr := errors.New("failed to compress image using tinify")
|
||||||
// Check url
|
// Check url
|
||||||
fileExtension, allowed := urlHasExt(url, "jpg", "jpeg", "png")
|
fileExtension, allowed := urlHasExt(url, "jpg", "jpeg", "png")
|
||||||
if !allowed {
|
if !allowed {
|
||||||
return "", nil
|
return "", nil
|
||||||
}
|
}
|
||||||
// Compress
|
// Compress
|
||||||
compressedLocation := ""
|
headers := http.Header{}
|
||||||
err := requests.
|
err := requests.
|
||||||
URL("https://api.tinify.com/shrink").
|
URL("https://api.tinify.com/shrink").
|
||||||
Client(hc).
|
Client(hc).
|
||||||
|
@ -107,17 +108,16 @@ func (tf *tinify) compress(url string, upload mediaStorageSaveFunc, hc *http.Cli
|
||||||
"url": url,
|
"url": url,
|
||||||
},
|
},
|
||||||
}).
|
}).
|
||||||
Handle(func(r *http.Response) error {
|
ToHeaders(headers).
|
||||||
compressedLocation = r.Header.Get("Location")
|
|
||||||
if compressedLocation == "" {
|
|
||||||
return errors.New("location header missing")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}).
|
|
||||||
Fetch(context.Background())
|
Fetch(context.Background())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("Tinify error:", err.Error())
|
log.Println("Tinify error:", err.Error())
|
||||||
return "", errors.New("failed to compress image using tinify")
|
return "", tinifyErr
|
||||||
|
}
|
||||||
|
compressedLocation := headers.Get("Location")
|
||||||
|
if compressedLocation == "" {
|
||||||
|
log.Println("Tinify error: location header missing")
|
||||||
|
return "", tinifyErr
|
||||||
}
|
}
|
||||||
// Resize and download image
|
// Resize and download image
|
||||||
var imgBuffer bytes.Buffer
|
var imgBuffer bytes.Buffer
|
||||||
|
@ -137,7 +137,7 @@ func (tf *tinify) compress(url string, upload mediaStorageSaveFunc, hc *http.Cli
|
||||||
Fetch(context.Background())
|
Fetch(context.Background())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("Tinify error:", err.Error())
|
log.Println("Tinify error:", err.Error())
|
||||||
return "", errors.New("failed to compress image using tinify")
|
return "", tinifyErr
|
||||||
}
|
}
|
||||||
// Upload compressed file
|
// Upload compressed file
|
||||||
return uploadCompressedFile(fileExtension, &imgBuffer, upload)
|
return uploadCompressedFile(fileExtension, &imgBuffer, upload)
|
||||||
|
|
|
@ -26,7 +26,9 @@ func (a *goBlog) checkDeletedPosts() {
|
||||||
for _, post := range postsToDelete {
|
for _, post := range postsToDelete {
|
||||||
// Check if post is deleted for more than 7 days
|
// Check if post is deleted for more than 7 days
|
||||||
if deleted, err := dateparse.ParseLocal(post.firstParameter("deleted")); err == nil && deleted.Add(time.Hour*24*7).Before(time.Now()) {
|
if deleted, err := dateparse.ParseLocal(post.firstParameter("deleted")); err == nil && deleted.Add(time.Hour*24*7).Before(time.Now()) {
|
||||||
a.deletePost(post.Path)
|
if err := a.deletePost(post.Path); err != nil {
|
||||||
|
log.Println("Error deleting post:", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,12 +16,13 @@ func Test_checkDeletedPosts(t *testing.T) {
|
||||||
app.initComponents(false)
|
app.initComponents(false)
|
||||||
|
|
||||||
// Create a post
|
// Create a post
|
||||||
app.createPost(&post{
|
err := app.createPost(&post{
|
||||||
Content: "Test",
|
Content: "Test",
|
||||||
Status: statusPublished,
|
Status: statusPublished,
|
||||||
Path: "/testpost",
|
Path: "/testpost",
|
||||||
Section: "posts",
|
Section: "posts",
|
||||||
})
|
})
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
// Check if post count is 1
|
// Check if post count is 1
|
||||||
count, err := app.db.countPosts(&postsRequestConfig{})
|
count, err := app.db.countPosts(&postsRequestConfig{})
|
||||||
|
@ -49,7 +50,8 @@ func Test_checkDeletedPosts(t *testing.T) {
|
||||||
require.Equal(t, 1, count)
|
require.Equal(t, 1, count)
|
||||||
|
|
||||||
// Set deleted time to more than 7 days ago
|
// Set deleted time to more than 7 days ago
|
||||||
app.db.replacePostParam("/testpost", "deleted", []string{time.Now().Add(-time.Hour * 24 * 8).Format(time.RFC3339)})
|
err = app.db.replacePostParam("/testpost", "deleted", []string{time.Now().Add(-time.Hour * 24 * 8).Format(time.RFC3339)})
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
// Run deleter
|
// Run deleter
|
||||||
app.checkDeletedPosts()
|
app.checkDeletedPosts()
|
||||||
|
|
|
@ -34,11 +34,7 @@ func Test_serveDate(t *testing.T) {
|
||||||
|
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
client := &http.Client{
|
client := newHandlerClient(app.d)
|
||||||
Transport: &handlerRoundTripper{
|
|
||||||
handler: app.d,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
var resString string
|
var resString string
|
||||||
|
|
||||||
|
@ -128,11 +124,7 @@ func Test_servePost(t *testing.T) {
|
||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
client := &http.Client{
|
client := newHandlerClient(app.d)
|
||||||
Transport: &handlerRoundTripper{
|
|
||||||
handler: app.d,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
var resString string
|
var resString string
|
||||||
|
|
||||||
|
|
|
@ -36,11 +36,7 @@ func Test_sitemap(t *testing.T) {
|
||||||
})
|
})
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
client := &http.Client{
|
client := newHandlerClient(app.d)
|
||||||
Transport: &handlerRoundTripper{
|
|
||||||
handler: app.d,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
var resString string
|
var resString string
|
||||||
|
|
||||||
|
|
9
utils.go
9
utils.go
|
@ -302,14 +302,15 @@ func (rt *handlerRoundTripper) RoundTrip(req *http.Request) (*http.Response, err
|
||||||
return nil, errors.New("no handler")
|
return nil, errors.New("no handler")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func newHandlerClient(handler http.Handler) *http.Client {
|
||||||
|
return &http.Client{Transport: &handlerRoundTripper{handler: handler}}
|
||||||
|
}
|
||||||
|
|
||||||
func doHandlerRequest(req *http.Request, handler http.Handler) (*http.Response, error) {
|
func doHandlerRequest(req *http.Request, handler http.Handler) (*http.Response, error) {
|
||||||
client := &http.Client{
|
|
||||||
Transport: &handlerRoundTripper{handler: handler},
|
|
||||||
}
|
|
||||||
if req.URL.Path == "" {
|
if req.URL.Path == "" {
|
||||||
req.URL.Path = "/"
|
req.URL.Path = "/"
|
||||||
}
|
}
|
||||||
return client.Do(req)
|
return newHandlerClient(handler).Do(req)
|
||||||
}
|
}
|
||||||
|
|
||||||
func saveToFile(reader io.Reader, fileName string) error {
|
func saveToFile(reader io.Reader, fileName string) error {
|
||||||
|
|
Loading…
Reference in New Issue